void ProcessEvent( EFlowEvent event, SActivationInfo *pActInfo )
  {
    IGameFramework* pGF = gEnv->pGame->GetIGameFramework();
  
    if (event == eFE_Activate && IsPortActive(pActInfo,0))
    {
			IActor* pActor = GetInputActor( pActInfo );
			if (!pActor)
				return;

			IInventory *pInventory = pActor->GetInventory();
      if (!pInventory)
        return;

      const string& item = GetPortString(pActInfo, 1);

			IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(item);
      if (0 == pInventory->GetItemByClass(pClass))
      {
        ActivateOutput(pActInfo, 0, false);
      }
      else
      {
        pGF->GetIItemSystem()->SetActorItem(pActor, item, true);
        ActivateOutput(pActInfo, 0, true);
      }
    }
  }
Beispiel #2
0
	void CreateView()
	{
		if (gEnv->pGame == NULL)
			return;

		IGameFramework* pGF = gEnv->pGame->GetIGameFramework();

		if (pGF == NULL)
			return;

		m_pViewSystem = pGF->GetIViewSystem();

		if (m_pViewSystem == NULL)
			return;
		//if the game has a clientactor, cache the view
		if (pGF->GetClientActor())
		{
			m_pLocalPlayerView = m_pViewSystem->GetViewByEntityId(pGF->GetClientActor()->GetEntityId());
		}



		if (m_pLocalPlayerView && (m_pViewSystem->GetActiveView() != m_pLocalPlayerView))
			m_pViewSystem->SetActiveView(m_pLocalPlayerView);

		if (m_pView == NULL)
			m_pView = m_pViewSystem->CreateView();
	}
Beispiel #3
0
//------------------------------------------------------------------------
void CWeaponSystem::RefGun(IConsoleCmdArgs *args)
{
	IGameFramework *pGF = gEnv->pGame->GetIGameFramework();
	IItemSystem *pItemSystem = pGF->GetIItemSystem();

	IActor *pActor = pGF->GetClientActor();

	if(!pActor || !pActor->IsPlayer())
		return;

	IInventory *pInventory = pActor->GetInventory();

	if(!pInventory)
		return;

	// give & select the refgun
	EntityId itemId = pInventory->GetItemByClass(CItem::sRefWeaponClass);

	if(0 == itemId)
	{
		// if actor doesn't have it, only give it in editor
		if(!gEnv->IsEditor())
			return;

		itemId = pItemSystem->GiveItem(pActor, CItem::sRefWeaponClass->GetName(), false, true, true);
	}

	pItemSystem->SetActorItem(pActor, itemId, true);

}
Beispiel #4
0
//--------------------------------------------------------------
void CWeaponSystem::OnGameTokenEvent( EGameTokenEvent event,IGameToken *pGameToken )
{
	assert(pGameToken);

	if(EGAMETOKEN_EVENT_CHANGE == event)
	{
		bool handled = false;
		if(!strcmp("weapon.effects.ice",pGameToken->GetName()))
		{
			pGameToken->GetValueAs(m_frozenEnvironment);
			handled = true;
		}
		else if(!strcmp("weapon.effects.wet",pGameToken->GetName()))
		{
			pGameToken->GetValueAs(m_wetEnvironment);
			handled = true;
		}

		if (handled)
		{
			IGameFramework* pGF = gEnv->pGame->GetIGameFramework();
			IActorSystem* pAS = pGF->GetIActorSystem();

			int count = pAS->GetActorCount();
			if (count)
			{
				IActorIteratorPtr it = pAS->CreateActorIterator();
				while (CActor* pActor = (CActor*)it->Next())
				{
					CPlayer *pPlayer = (pActor->GetActorClass() == CPlayer::GetActorClassType()) ? static_cast<CPlayer*>(pActor) : 0;
					if (pPlayer && pPlayer->GetNanoSuit())
					{
						// go through all players and turn their ice effects on/off
						IEntityRenderProxy* pRenderProxy = (IEntityRenderProxy*)pPlayer->GetEntity()->GetProxy(ENTITY_PROXY_RENDER);
						if (pRenderProxy)
						{
							uint8 mask = pRenderProxy->GetMaterialLayersMask();
							uint32 blend = pRenderProxy->GetMaterialLayersBlend();
							mask = IsFrozenEnvironment() ? mask|MTL_LAYER_DYNAMICFROZEN : mask&~MTL_LAYER_DYNAMICFROZEN;
							mask = IsWetEnvironment() ? mask|MTL_LAYER_WET : mask&~MTL_LAYER_WET;
							pRenderProxy->SetMaterialLayersMask(mask);
							pRenderProxy->SetMaterialLayersBlend(blend);
							if (CItem* pItem = static_cast<CItem*>(pPlayer->GetCurrentItem(true)))
							{
								pItem->FrostSync(true);
								pItem->WetSync(true);
							}
							if (COffHand* pOffHand = static_cast<COffHand*>(pPlayer->GetItemByClass(CItem::sOffHandClass)))
							{
								pOffHand->FrostSync(pOffHand->GetOffHandState() != eOHS_INIT_STATE);
								pOffHand->WetSync(pOffHand->GetOffHandState() != eOHS_INIT_STATE);
							}
						}
					}
				}
			}
		}
	}
}
Beispiel #5
0
CSPAnalyst::~CSPAnalyst()
{
    IGameFramework *pGF = g_pGame->GetIGameFramework();

    if(m_bEnabled)
        pGF->GetIGameplayRecorder()->UnregisterListener(this);

    pGF->GetILevelSystem()->RemoveListener(this);
    pGF->UnregisterListener(this);
}
Beispiel #6
0
//------------------------------------------------------------------------
IEntity * CEditorGame::GetPlayer()
{
	IGameFramework * pGameFramework = m_pGame->GetIGameFramework();	

	if(!m_pGame)
		return 0;

	IActor * pActor = pGameFramework->GetClientActor();
	return pActor? pActor->GetEntity() : NULL;
}
Beispiel #7
0
//------------------------------------------------------------------------
bool CEditorGame::ConfigureNetContext( bool on )
{
	bool ok = false;

	IGameFramework * pGameFramework = m_pGame->GetIGameFramework();

	if (on == m_bEnabled)
	{
		ok = true;
	}
	else if (on)
	{
		SGameContextParams ctx;

		SGameStartParams gameParams;
		gameParams.flags = eGSF_Server
			| eGSF_NoSpawnPlayer
			| eGSF_Client
			| eGSF_NoLevelLoading
			| eGSF_BlockingClientConnect
			| eGSF_NoGameRules
			| eGSF_NoQueries;

		if (!m_bUsingMultiplayerGameRules)
		{
			gameParams.flags |= eGSF_LocalOnly;
		}
		
		if (m_bUsingMultiplayerGameRules)
		{
			gameParams.flags |= eGSF_ImmersiveMultiplayer;
		}

		gameParams.connectionString = "";
		gameParams.hostname = "localhost";
		gameParams.port = EDITOR_SERVER_PORT;
		gameParams.pContextParams = &ctx;
		gameParams.maxPlayers = 1;

		if (pGameFramework->StartGameContext( &gameParams ))
			ok = true;
	}
	else
	{
		pGameFramework->EndGameContext();
		gEnv->pNetwork->SyncWithGame(eNGS_Shutdown);
		ok = true;
	}

	m_bEnabled = on && ok;
	return ok;
}
	void ProcessEvent( EFlowEvent event, SActivationInfo *pActInfo )
	{
		if (event == eFE_Activate)
		{
			IGameFramework* pGF = gEnv->pGame->GetIGameFramework();

			IActor * pActor = pGF->GetClientActor();
			if (!pActor)
				return;
			const bool bHolster = IsPortActive(pActInfo, 0);
			pActor->HolsterItem(bHolster);
			ActivateOutput(pActInfo, 0, true);
		}
	}
Beispiel #9
0
bool CHeavyWeapon::AllowInteraction(EntityId interactionEntity, EInteractionType interactionType)
{
    IGameFramework* pGameFramework = g_pGame->GetIGameFramework();
    IVehicleSystem* pVehicleSystem = pGameFramework->GetIVehicleSystem();
    IVehicle* pInteractiveVehicle = pVehicleSystem->GetVehicle(interactionEntity);

    if (pInteractiveVehicle != 0)
        {
            return false;
        }
    else
        {
            return BaseClass::AllowInteraction(interactionEntity, interactionType);
        }
}
void CMountedGunController::InitMannequinParams()
{
    CRY_ASSERT(g_pGame);
    IGameFramework* pGameFramework = g_pGame->GetIGameFramework();
    CRY_ASSERT(pGameFramework);
    CMannequinUserParamsManager& mannequinUserParams = pGameFramework->GetMannequinInterface().GetMannequinUserParamsManager();

    CRY_ASSERT(m_pControlledPlayer);
    IAnimatedCharacter* pAnimatedCharacter = m_pControlledPlayer->GetAnimatedCharacter();
    CRY_ASSERT(pAnimatedCharacter);
    IActionController* pActionController = pAnimatedCharacter->GetActionController();
    m_pMannequinParams = mannequinUserParams.FindOrCreateParams<SMannequinMountedGunParams>(pActionController);

    MountedGunCRCs.Init();
}
CGameRulesCommonDamageHandling::SCollisionEntityInfo::SCollisionEntityInfo( const IEntity* _pEntity )
: pEntity(_pEntity)
, entityId(0)
, pEntityActor(NULL)
, pEntityVehicle(NULL)
{
	if (pEntity)
	{
		entityId = pEntity->GetId();

		IGameFramework* pGameFrameWork = g_pGame->GetIGameFramework();

		pEntityActor = pGameFrameWork->GetIActorSystem()->GetActor(entityId);
		pEntityVehicle = (pEntityActor == NULL) ? pGameFrameWork->GetIVehicleSystem()->GetVehicle(entityId) : NULL;
	}
}
Beispiel #12
0
bool CEditorGame::Init(ISystem *pSystem,IGameToEditorInterface *pGameToEditorInterface)
{
	assert(pSystem);

	SSystemInitParams startupParams;
	startupParams.bEditor = true;
	startupParams.pSystem = pSystem;
	startupParams.bExecuteCommandLine=false;		// in editor we do it later - after other things are initialized

	m_pGameStartup = CreateGameStartup();

	m_pGame = m_pGameStartup->Init(startupParams);

	if (!m_pGame)
	{
		return false;
	}

	IGameFramework* pGameFramework = m_pGame->GetIGameFramework();
	if ( pGameFramework != NULL )
	{
		pGameFramework->InitEditor( pGameToEditorInterface );
	}

	InitUIEnums(pGameToEditorInterface);

	gEnv->bServer = true;
	gEnv->bMultiplayer = false;

#if !defined(XENON) && !defined(PS3) && !defined(GRINGO)
	gEnv->SetIsClient(true);
#endif

	m_bUsingMultiplayerGameRules = false;

	s_pEditorGameMode = REGISTER_INT( "net_gamemode", 0, 0, "Should editor connect a new client?");
	s_pEditorGameMode->SetOnChangeCallback(&OnChangeEditorMode);

	SetGameMode(false);

	REGISTER_COMMAND( "net_reseteditorclient", ResetClient, 0, "Resets player and gamerules!" );

	ConfigureNetContext(true);
		
	return true;
}
//------------------------------------------------------------------------
bool CEditorGame::SetGameMode(bool bGameMode)
{
	m_bGameMode = bGameMode;
	bool on = bGameMode;

	if (s_pEditorGameMode->GetIVal() == 0)
	{
		on = m_bPlayer;
	}

	bool ok = ConfigureNetContext( on );

	if (ok)
	{
		if(gEnv->IsEditor())
		{
			m_pGame->EditorResetGame(bGameMode);
		}

		IGameFramework *pGameFramework = m_pGame->GetIGameFramework();
		pGameFramework->OnEditorSetGameMode(bGameMode);
		CActor *pActor = static_cast<CActor *>(m_pGame->GetIGameFramework()->GetClientActor());

		if (pActor)
		{
			if (bGameMode)
			{
				// Revive actor in its current location (it will be moved to the editor viewpoint location later)
				const Vec3 pos = pActor->GetEntity()->GetWorldPos();
				const Quat rot = pActor->GetEntity()->GetWorldRotation();
				const int teamId = g_pGame->GetGameRules()->GetTeam(pActor->GetEntityId());
				pActor->NetReviveAt(pos, rot, teamId);
			}
			else
			{
				pActor->Reset(true);
			}
		}
	}
	else
	{
		GameWarning("Failed configuring net context");
	}

	return ok;
}
Beispiel #14
0
//------------------------------------------------------------------------------
void CWeapon::ToggleFlashLight()
{
	static IEntityClass* pFlashLightClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass("Flashlight");

	IGameFramework* pGameFramework = g_pGame->GetIGameFramework();
	IItemSystem* pItemSystem = pGameFramework->GetIItemSystem();

	for (size_t i = 0; i < m_accessories.size(); ++i)
	{
		if (m_accessories[i].pClass == pFlashLightClass)
		{
			IItem* pItem = pItemSystem->GetItem(m_accessories[i].accessoryId);
			CFlashLight* pFlashLight = static_cast<CFlashLight*>(pItem);
			pFlashLight->ToggleFlashLight();
			break;
		}
	}
}
Beispiel #15
0
//--------------------------------------------------------------------------------------------------
// Name: IsEntity3rdPerson
// Desc: Returns 3rd person state
//--------------------------------------------------------------------------------------------------
bool CGameEffect::IsEntity3rdPerson(EntityId entityId)
{
	bool bIs3rdPerson = true;

	IGame* pGame = gEnv->pGame;
	if(pGame)
	{
		IGameFramework* pGameFramework = pGame->GetIGameFramework();
		if(pGameFramework)
		{
			EntityId clientEntityId = pGameFramework->GetClientActorId();
			if(clientEntityId == entityId)
			{
				bIs3rdPerson = pGameFramework->GetClientActor()->IsThirdPerson();
			}
		}
	}

	return bIs3rdPerson;
}//-------------------------------------------------------------------------------------------------
void CEditorGame::SetGameRules()
{
	IGameFramework *pGameFramework = g_pGame->GetIGameFramework();
	IConsole *pConsole = gEnv->pConsole;
	const char *szGameRules = NULL;
	const char *szLevelName = pConsole->GetCVar("sv_map")->GetString();
	ILevelInfo *pLevelInfo = pGameFramework->GetILevelSystem()->GetLevelInfo(szLevelName);

	if (pLevelInfo)
	{
		szGameRules = pLevelInfo->GetDefaultGameRules();
	}

	if (!szGameRules)
	{
		szGameRules = s_pEditorGame->m_bUsingMultiplayerGameRules ? "DeathMatch" : "SinglePlayer";
	}

	pGameFramework->GetIGameRulesSystem()->CreateGameRules(szGameRules);
	pConsole->GetCVar("sv_gamerules")->Set(szGameRules);
}
//--------------------------------------------------------------------------------------------------
// Name: Update
// Desc: Updates effects system and any effects registered in it's update list
//--------------------------------------------------------------------------------------------------
void GameSDKCGameEffectsSystem::Update(float frameTime)
{
	FX_ASSERT_MESSAGE(m_isInitialised,"Game Effects System trying to update without being initialised");

	// Get pause state
	bool isPaused = false;
	IGame* pGame = gEnv->pGame;
	if(pGame)
	{
		IGameFramework* pGameFramework = pGame->GetIGameFramework();
		if(pGameFramework)
		{
			isPaused = pGameFramework->IsGamePaused();
		}
	}

	// Update effects
	if(m_effectsToUpdate)
	{
        GameSDKIGameEffect* effect = m_effectsToUpdate;
		while(effect)
		{
			m_nextEffectToUpdate = effect->Next();
			if((!isPaused) || (effect->IsFlagSet(GAME_EFFECT_UPDATE_WHEN_PAUSED)))
			{
				SOFTCODE_RETRY(effect,effect->Update(frameTime));
			}
			effect = m_nextEffectToUpdate;
		}
	}

	m_nextEffectToUpdate = NULL;

#if DEBUG_GAME_FX_SYSTEM
	DrawDebugDisplay();
#endif
}//-------------------------------------------------------------------------------------------------
Beispiel #18
0
	//----------------------------------------------------------------------
	IView* GetView( SActivationInfo* pActInfo )
	{
		SInputParams inputParams;
		ReadCurrentInputParams( pActInfo, inputParams );
		IGameFramework* pGF         = gEnv->pGame->GetIGameFramework();
		IView*          pView       = 0;
		IView*          pActiveView = pGF->GetIViewSystem()->GetActiveView();
		eViewType       viewType    = inputParams.view;
		if (viewType == VT_FirstPerson) // use player's view
		{
			IActor* pActor = pGF->GetClientActor();
			if (pActor == 0)
				return NULL;

			eRestriction restriction = inputParams.restriction;
			if (restriction != ER_None)
			{
				IVehicle* pVehicle = pActor->GetLinkedVehicle();
				if (restriction == ER_InVehicle && pVehicle == 0)
					return NULL;
				if (restriction == ER_NoVehicle && pVehicle != 0 /* && pVehicle->GetSeatForPassenger(entityId) != 0 */)
					return NULL;
			}

			EntityId entityId = pActor->GetEntityId();
			pView = pGF->GetIViewSystem()->GetViewByEntityId(entityId);
		}
		else                            // active view
		{
			pView = pActiveView;
		}
		if (pView != pActiveView)
			return NULL;

		return pView;
	}
Beispiel #19
0
//--------------------------------------------------------------------------------------
// Initialize everything and go into a render loop
//--------------------------------------------------------------------------------------
INT WINAPI wWinMain( HINSTANCE, HINSTANCE, LPWSTR, int )
{
	// Enable run-time memory check for debug builds.
#if (defined(DEBUG) || defined(_DEBUG)) && defined( OS_WIN32 )
	_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif

#ifdef _STATIC_LIB
	IGameFramework* game = gkLoadStaticModule_gkGameFramework();
#else
	// load gkSystem dll
	HINSTANCE hHandle = 0;
	gkOpenModule(hHandle, _T("gkGameFramework"));//, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
	GET_SYSTEM pFuncStart = (GET_SYSTEM)DLL_GETSYM(hHandle, "gkModuleInitialize");
	IGameFramework* game = pFuncStart();
#endif

	int width = 1280;
	int height = 720;

	// init
	ISystemInitInfo sii;
	sii.fWidth = width;
	sii.fHeight = height;

	if (!(game->Init(sii)))
	{
		return 0;
	}


	game->PostInit( NULL, sii );

	game->InitGame( NULL );

	// run
	game->Run();

	// destroy
	game->DestroyGame(false);
	game->Destroy();

	// free
#ifdef _STATIC_LIB
	gkFreeStaticModule_gkGameFramework();
#else
	gkFreeModule( hHandle );
#endif
	return 0;
}
Beispiel #20
0
CSPAnalyst::CSPAnalyst() : m_bEnabled(false), m_bChainLoad(false)
{
    IGameFramework *pGF = g_pGame->GetIGameFramework();
    pGF->GetILevelSystem()->AddListener(this);
    pGF->RegisterListener(this, "CSPAnalyst", eFLPriority_Game);
}
//------------------------------------------------------------------------
SCreateChannelResult CGameServerNub::CreateChannel(INetChannel *pChannel, const char *pRequest)
{
	CRY_ASSERT(m_maxPlayers);

	CGameServerChannel *pNewChannel;

	if (!pRequest)
	{
		CRY_ASSERT(false);
		SCreateChannelResult res(eDC_GameError);
		return res;
	}

	SParsedConnectionInfo info = m_pGameContext->ParseConnectionInfo(pRequest);
	if (!info.allowConnect)
	{
		GameWarning( "Not allowed to connect to server: %s", info.errmsg.c_str() );
		SCreateChannelResult res(info.cause);
		cry_strcpy(res.errorMsg, info.errmsg.c_str());
		return res;
	}

	if (int(m_channels.size()) >= m_maxPlayers)
	{
		SCreateChannelResult res(eDC_ServerFull);
		cry_strcpy(res.errorMsg, string().Format("Disallowing more than %d players",m_maxPlayers).c_str());
		return res;
	}

	if (info.isMigrating && CCryAction::GetCryAction()->IsGameSessionMigrating())
	{
		pChannel->SetMigratingChannel(true);
	}

	pNewChannel = GetOnHoldChannelFor(pChannel);
	if (!pNewChannel)
	{
		pNewChannel = new CGameServerChannel(pChannel, m_pGameContext, this);

		if (pChannel->GetSession() != CrySessionInvalidHandle)
		{
			// There is a valid CrySessionHandle created by the lobby so use this as the channel id
			// as it contains information that can identify the connection in the lobby.
			pNewChannel->SetChannelId(pChannel->GetSession());
		}
		else
		{
			// No valid CrySessionHandle so create an id here.
			pNewChannel->SetChannelId(++m_genId);
		}
		
		if (m_channels.find(pNewChannel->GetChannelId()) != m_channels.end())
		{
			CryFatalError("CGameServerNub::CreateChannel: Trying to create channel with duplicate id %d", pNewChannel->GetChannelId());
		}

		m_channels.insert(TServerChannelMap::value_type(pNewChannel->GetChannelId(), pNewChannel));
	}
	else
	{
		pNewChannel->SetNetChannel(pChannel);
#if !NEW_BANDWIDTH_MANAGEMENT
		pNewChannel->SetupNetChannel(pChannel);
#endif // NEW_BANDWIDTH_MANAGEMENT
	}

	ICVar* pPass = gEnv->pConsole->GetCVar("sv_password");
	if (pPass && gEnv->bMultiplayer)
	{
		pChannel->SetPassword(pPass->GetString());
	}
	pChannel->SetNickname(info.playerName.c_str());

	// Host migration
	if (info.isMigrating && CCryAction::GetCryAction()->IsGameSessionMigrating())
	{
		// Enable the game rules to find the migrating player details by channel id
		IGameFramework *pGameFramework = gEnv->pGame->GetIGameFramework();
		IGameRules *pGameRules = pGameFramework->GetIGameRulesSystem()->GetCurrentGameRules();
		
		if(pGameRules)
		{
			EntityId playerID = pGameRules->SetChannelForMigratingPlayer(info.playerName.c_str(), pNewChannel->GetChannelId());

			if (playerID)
			{
				CryLog("CGameServerNub::CreateChannel() assigning actor %d '%s' to channel %d", playerID, info.playerName.c_str(), pNewChannel->GetChannelId());
				pNewChannel->SetPlayerId(playerID);
			}
			else
			{
				CryLog("CGameServerNub::CreateChannel() failed to assign actor '%s' to channel %d", info.playerName.c_str(), pNewChannel->GetChannelId());
			}
		}
		else
		{
			CryLog("[host migration] terminating because game rules is NULL, game session migrating %d session 0x%08x", CCryAction::GetCryAction()->IsGameSessionMigrating(), pChannel->GetSession());
			gEnv->pNetwork->TerminateHostMigration(pChannel->GetSession());
		}
	}

	m_netchannels.insert(TNetServerChannelMap::value_type(pChannel, pNewChannel->GetChannelId()));

	return SCreateChannelResult(pNewChannel);
}
//------------------------------------------------------------------------
void CGameRulesMPDamageHandling::SvOnCollision(const IEntity *pVictimEntity, const CGameRules::SCollisionHitInfo& collisionHitInfo)
{
	FUNCTION_PROFILER(gEnv->pSystem, PROFILE_GAME);
	CRY_ASSERT(gEnv->bMultiplayer);

#if !defined(_RELEASE)
	if (g_pGameCVars->g_DisableCollisionDamage)
		return;
#endif

	IGameFramework* gameFramwork = g_pGame->GetIGameFramework();

	EntityId victimID = pVictimEntity->GetId();
	EntityId offenderID = collisionHitInfo.targetId;

	const IEntity* pOffenderEntity = gEnv->pEntitySystem->GetEntity(offenderID);

	float currentTime = gEnv->pTimer->GetCurrTime();

	CActor* victimActor = static_cast<CActor*>(gameFramwork->GetIActorSystem()->GetActor(victimID));
	IVehicle* offenderVehicle = gameFramwork->GetIVehicleSystem()->GetVehicle(offenderID);
	IVehicle* victimVehicle = gameFramwork->GetIVehicleSystem()->GetVehicle(victimID);
	IActor* offenderActor = gameFramwork->GetIActorSystem()->GetActor(offenderID);

	if(pOffenderEntity && !offenderVehicle && !offenderActor)
	{
		if( IEntity* pParent = pOffenderEntity->GetParent() )
		{
			 offenderVehicle = gameFramwork->GetIVehicleSystem()->GetVehicle(pParent->GetId());
		}
	}

	// Vehicles being flipped do no damage, for now
	if (offenderVehicle != NULL && offenderVehicle->GetStatus().beingFlipped)
		return;

	// Players can't damage vehicles
	if (victimVehicle && offenderActor)
		return;

	// Filter frequent collisions
	if (pOffenderEntity)
	{
		FRAME_PROFILER("Filter out recent collisions", gEnv->pSystem, PROFILE_GAME);

		EntityCollisionRecords::const_iterator collisionRecordIter = m_entityCollisionRecords.find(victimID);
		if (collisionRecordIter != m_entityCollisionRecords.end())
		{
			const EntityCollisionRecord& record = collisionRecordIter->second;
			if (record.entityID == offenderID &&
			    record.time + EntityCollisionIgnoreTimeBetweenCollisions > currentTime)
			{
				return;
			}
		}
	}

	float offenderMass = collisionHitInfo.target_mass;

	enum
	{
		CollisionWithEntity,
		CollisionWithStaticWorld
	}
	collisionType = (pOffenderEntity || offenderMass > 0.0f) ? CollisionWithEntity : CollisionWithStaticWorld;

	const Vec3& victimVelocity = collisionHitInfo.velocity;
	const Vec3& offenderVelocity = collisionHitInfo.target_velocity;

	float relativeSpeedSq = 0.0f;
	float minSpeedToCareAboutCollisionSq = 0.0f;
	float contactMass = 0.0f;

	bool offenderIsBig = offenderMass > 1000.f;

	switch (collisionType)
	{
	case CollisionWithEntity:
		{
			Vec3 relativeVelocity = victimVelocity - offenderVelocity;
			relativeSpeedSq = relativeVelocity.GetLengthSquared();

			minSpeedToCareAboutCollisionSq = sqr(10.0f);

			if (victimActor && offenderIsBig)
			{
				minSpeedToCareAboutCollisionSq = sqr(1.0f);
			}

			if (victimActor && offenderVehicle)
			{
				//Players won't be hurt by vehicles with a negative kill player speed
				if(offenderVehicle->GetDamageParams().aiKillPlayerSpeed < 0.f)
				{
					return;
				}

				minSpeedToCareAboutCollisionSq = sqr(2.0f);
			}

			const float offenderSpeedSq = offenderVelocity.GetLengthSquared();
			if (offenderSpeedSq == 0.0f) // -- if collision target it not moving
			{
				minSpeedToCareAboutCollisionSq *= sqr(2.0f);
			}

			//////////////////////////////////////////////////////////////////////////

			contactMass = offenderMass;
			break;
		}

	case CollisionWithStaticWorld:
		{
			// Actors don't take damage from running into walls!
			if (victimActor)
			{
				return;
			}

			relativeSpeedSq = victimVelocity.GetLengthSquared();
			minSpeedToCareAboutCollisionSq = sqr(7.5f);
			contactMass = collisionHitInfo.mass;

			break;
		}
	}

	const bool contactMassIsTooLowToCare = contactMass < 0.01f;
	if (contactMassIsTooLowToCare)
		return;

			
	//////////////////////////////////////////////////////////////////////////
	// Calculate the collision damage
	if (relativeSpeedSq >= minSpeedToCareAboutCollisionSq)
	{
		bool useDefaultCalculation = true;
		float fEnergy = 0.f;
		float damage = 0.f;
		EntityId kickerId = 0;

		// Calculate damage
		if (offenderVehicle && victimActor)
		{
			useDefaultCalculation = false;
			damage = ProcessActorVehicleCollision(victimActor, victimID, offenderVehicle, offenderID, damage, collisionHitInfo, kickerId);
		}
		else if (offenderIsBig && victimActor) // i.e. a kickable car
		{
			// Try to find the kicker
			CTimeValue time = gEnv->pTimer->GetAsyncTime();
			IActorSystem* pActorSystem = gEnv->pGame->GetIGameFramework()->GetIActorSystem();
			IActorIteratorPtr pActorIterator = pActorSystem->CreateActorIterator();
			IActor* pActor = pActorIterator->Next();
			float lowestTime = 5.f;
			while (pActor != NULL)
			{
				CPlayer* pPlayer = static_cast<CPlayer*>(pActor);
				EntityId kicked = pPlayer->GetLargeObjectInteraction().GetLastObjectId();
				if (kicked==offenderID)
				{
					float timeSinceKick = (time - pPlayer->GetLargeObjectInteraction().GetLastObjectTime()).GetSeconds();
					if (timeSinceKick < lowestTime)
					{
						// We found the kicker and the kicked
						kickerId = pActor->GetEntityId();
						lowestTime = timeSinceKick;
					}
				}
				pActor = pActorIterator->Next();
			}
			damage = ProcessActorKickedVehicle(victimActor, victimID, kickerId, offenderID, damage, collisionHitInfo);
			useDefaultCalculation = false;
		}

		if (useDefaultCalculation)
		{
			fEnergy = GetCollisionEnergy(pVictimEntity, collisionHitInfo);
			if (victimVehicle || offenderIsBig)
			{
				damage = 0.0005f * fEnergy;
			}
			else
			{
				damage = 0.0025f * fEnergy;
			}

			// Apply damage multipliers
			damage *= GetCollisionDamageMult(pVictimEntity, pOffenderEntity, collisionHitInfo);

			if (victimActor)
			{
				const bool victimIsPlayer = victimActor->IsPlayer();

				if (victimIsPlayer)
				{
					damage = AdjustPlayerCollisionDamage(pVictimEntity, pOffenderEntity, collisionHitInfo, damage);
				}
			}
		}

		if (damage >= DAMAGE_THRESHOLD_COLLISIONS)
		{
			HitInfo hit;
			hit.damage = damage;
			hit.pos = collisionHitInfo.pos;
			if (collisionHitInfo.target_velocity.GetLengthSquared() > 1e-6)
				hit.dir = collisionHitInfo.target_velocity.GetNormalized();
			hit.radius = 0.0f;
			hit.partId = collisionHitInfo.partId;
			hit.targetId = victimID;
			hit.weaponId = offenderID;
			hit.shooterId = kickerId != 0 ? kickerId : offenderID;
			hit.material = 0;
			hit.type = CGameRules::EHitType::Collision;
			hit.explosion = false;

			CGameRules *pGameRules = g_pGame->GetGameRules();
			if (pGameRules->GetTeamCount() > 1)
			{
				int shooterTeamId = pGameRules->GetTeam(hit.shooterId);
				int targetTeamId = pGameRules->GetTeam(hit.targetId);

				if (shooterTeamId && (shooterTeamId == targetTeamId))
				{
					damage = GetFriendlyFireDamage(damage, hit, victimActor);
				}
			}

			if (damage >= DAMAGE_THRESHOLD_COLLISIONS)
			{
				IScriptTable* pVictimScript = pVictimEntity ? pVictimEntity->GetScriptTable() : NULL;
				IScriptTable* pOffenderScript = pOffenderEntity ? pOffenderEntity->GetScriptTable() : NULL;

				if (!pOffenderEntity && pVictimEntity)
				{
					pOffenderEntity = pVictimEntity;
					offenderID = victimID;
				}

				m_entityCollisionRecords[victimID] = EntityCollisionRecord(offenderID, currentTime);

				if(victimVehicle)
				{
					victimVehicle->OnHit(hit);
				}	
				else if (pVictimScript)
				{
					FRAME_PROFILER("Call to OnHit", gEnv->pSystem, PROFILE_GAME);

					if (!IsDead(victimActor, pVictimScript))
					{
						if (IActor* offenderDriver = offenderVehicle ? offenderVehicle->GetDriver() : NULL)
							hit.shooterId = offenderDriver->GetEntityId();

						DelegateServerHit(pVictimScript, hit, victimActor);
					}
				}
			}
		}
	}
}
Beispiel #23
0
	virtual void ProcessEvent( EFlowEvent event,SActivationInfo* pActInfo )
	{
		if (event != eFE_Activate)
			return;

		if (!InputEntityIsLocalPlayer( pActInfo ))
			return;

		const bool bTriggered     = IsPortActive(pActInfo, EIP_Trigger);
		const bool bFreqTriggered = IsPortActive(pActInfo, EIP_Frequency);
		if (bTriggered == false && bFreqTriggered == false)
			return;

		IGameFramework* pGF         = gEnv->pGame->GetIGameFramework();
		IView*          pView       = 0;
		IView*          pActiveView = pGF->GetIViewSystem()->GetActiveView();
		int             viewType    = GetPortInt(pActInfo, EIP_ViewType);
		if (viewType == VT_FirstPerson)                                // use player's view
		{
			IActor* pActor = pGF->GetClientActor();
			if (pActor == 0)
				return;

			const int restriction = GetPortInt(pActInfo, EIP_Restriction);
			if (restriction != ER_None)
			{
				IVehicle* pVehicle = pActor->GetLinkedVehicle();
				if (restriction == ER_InVehicle && pVehicle == 0)
					return;
				if (restriction == ER_NoVehicle && pVehicle != 0 /* && pVehicle->GetSeatForPassenger(entityId) != 0 */)
					return;
			}

			EntityId entityId = pActor->GetEntityId();
			pView = pGF->GetIViewSystem()->GetViewByEntityId(entityId);
		}
		else                                                           // active view
		{
			pView = pActiveView;
		}
		if (pView == 0 || pView != pActiveView)
			return;

		const bool  bGroundOnly = GetPortBool(pActInfo, EIP_GroundOnly);
		Ang3        angles      = Ang3(DEG2RAD(GetPortVec3(pActInfo, EIP_Angle)));
		Vec3        shift       = GetPortVec3(pActInfo, EIP_Shift);
		const float duration    = GetPortFloat(pActInfo, EIP_Duration);
		float       freq        = GetPortFloat(pActInfo, EIP_Frequency);
		if (iszero(freq) == false)
			freq = 1.0f / freq;
		const float       randomness  = GetPortFloat(pActInfo, EIP_Randomness);
		static const bool bFlip       = true;                          // GetPortBool(pActInfo, EIP_Flip);
		const bool        bUpdateOnly = !bTriggered && bFreqTriggered; // it's an update if and only if Frequency has been changed

		const float distance = GetPortFloat(pActInfo, EIP_Distance);
		const float rangeMin = GetPortFloat(pActInfo, EIP_RangeMin);
		const float rangeMax = GetPortFloat(pActInfo, EIP_RangeMax);
		float       amount   = min(1.f, max(0.f, (rangeMax - distance) / (rangeMax - rangeMin)));

		angles *= amount;
		shift  *= amount;

		pView->SetViewShake(angles, shift, duration, freq, randomness, FLOWGRAPH_SHAKE_ID, bFlip, bUpdateOnly, bGroundOnly);
	}
Beispiel #24
0
//
//-----------------------------------------------------------------------------------------------------------
// (MATT) Moved here from Scriptbind_AI when that was moved to the AI system {2008/02/15:15:23:16}
int CScriptBind_Action::RegisterWithAI(IFunctionHandler *pH)
{
	if (gEnv->bMultiplayer && !gEnv->bServer)
		return pH->EndFunction();

	int type;
	ScriptHandle hdl;

	if (!pH->GetParams(hdl, type))
		return pH->EndFunction();

	EntityId entityID = (EntityId)hdl.n;
	IEntity *pEntity = gEnv->pEntitySystem->GetEntity(entityID);

	if(!pEntity)
	{
		GameWarning("RegisterWithAI: Tried to set register with AI nonExisting entity with id [%d]. ", entityID);
		return pH->EndFunction();
	}

	// Apparently we can't assume that there is just one IGameObject to an entity, because we choose between (at least) Actor and Vehicle objects.
	// (MATT) Do we really need to check on the actor system here? {2008/02/15:18:38:34}
	IGameFramework *pGameFramework = gEnv->pGame->GetIGameFramework();
	IVehicleSystem*	pVSystem = pGameFramework->GetIVehicleSystem();
	IActorSystem*	pASystem = pGameFramework->GetIActorSystem();
	if(!pASystem)
	{
		GameWarning("RegisterWithAI: no ActorSystem for %s.", pEntity->GetName());
		return pH->EndFunction();
	}

	AIObjectParams params(type, 0, entityID);
	bool autoDisable(true);

	// For most types, we need to parse the tables
	// For others we leave them blank
	switch (type)
	{
	case AIOBJECT_ACTOR:
	case AIOBJECT_2D_FLY:
	case AIOBJECT_BOAT:
	case AIOBJECT_CAR:
	case AIOBJECT_HELICOPTER:
	
	case AIOBJECT_INFECTED:
	case AIOBJECT_ALIENTICK:
	
	case AIOBJECT_HELICOPTERCRYSIS2:
		if(gEnv->pAISystem && ! gEnv->pAISystem->ParseTables(3, true, pH, params, autoDisable))
			return pH->EndFunction();
	default:;
	}

	// Most types check these, so just get them in advance
	IActor*	pActor = pASystem->GetActor( pEntity->GetId() );

	IVehicle*	pVehicle = NULL;
	if( pVSystem )
		pVehicle = pVSystem->GetVehicle( pEntity->GetId() );

	// Set this if we've found something to create a proxy from
	IGameObject* pGameObject = NULL;

	switch(type)
	{
	case AIOBJECT_ACTOR:
	case AIOBJECT_2D_FLY:
	
	case AIOBJECT_INFECTED:
	case AIOBJECT_ALIENTICK:
	
		{
			// (MATT) The pActor/pVehicle test below - is it basically trying to distiguish between the two cases above? If so, separate them! {2008/02/15:19:38:08}
			if(!pActor)
			{
				GameWarning("RegisterWithAI: no Actor for %s.", pEntity->GetName());
				return pH->EndFunction(); 
			}
			pGameObject = pActor->GetGameObject();
		}
		break;
	case AIOBJECT_BOAT:
	case AIOBJECT_CAR:
		{
			if(!pVehicle)
			{
				GameWarning("RegisterWithAI: no Vehicle for %s (Id %i).", pEntity->GetName(), pEntity->GetId());
				return pH->EndFunction(); 
			}
			pGameObject = pVehicle->GetGameObject();
		}
		break;

	case AIOBJECT_HELICOPTER:
	case AIOBJECT_HELICOPTERCRYSIS2:
		{
			if(!pVehicle)
			{
				GameWarning("RegisterWithAI: no Vehicle for %s (Id %i).", pEntity->GetName(), pEntity->GetId());
				return pH->EndFunction(); 
			}
			pGameObject = pVehicle->GetGameObject();
			params.m_moveAbility.b3DMove = true;
		}
		break;
	case AIOBJECT_PLAYER:
		{
			if(IsDemoPlayback())
				return pH->EndFunction();

			SmartScriptTable pTable;

			if (pH->GetParamCount() > 2)
				pH->GetParam(3,pTable);
			else
				return pH->EndFunction();

			pGameObject = pActor->GetGameObject();

			pTable->GetValue("groupid",params.m_sParamStruct.m_nGroup);       

			const char* faction = 0;
			if (pTable->GetValue("esFaction", faction) && gEnv->pAISystem)
			{
				params.m_sParamStruct.factionID = gEnv->pAISystem->GetFactionMap().GetFactionID(faction);
				if (faction && *faction && (params.m_sParamStruct.factionID == IFactionMap::InvalidFactionID))
				{
					GameWarning("Unknown faction '%s' being set...", faction);
				}
			}
			else
			{
				// Márcio: backwards compatibility
				int species = -1;
				if (!pTable->GetValue("eiSpecies", species))
					pTable->GetValue("species", species);

				if (species > -1)
					params.m_sParamStruct.factionID = species;
			}

			pTable->GetValue("commrange",params.m_sParamStruct.m_fCommRange); //Luciano - added to use GROUPONLY signals

			SmartScriptTable pPerceptionTable;
			if(pTable->GetValue("Perception",pPerceptionTable))
			{
				pPerceptionTable->GetValue( "sightrange", params.m_sParamStruct.m_PerceptionParams.sightRange);
			}
		}
		break;
	case AIOBJECT_SNDSUPRESSOR:
		{
			// (MATT) This doesn't need a proxy? {2008/02/15:19:45:58}
			SmartScriptTable pTable;
			// Properties table
			if (pH->GetParamCount() > 2)
				pH->GetParam(3,pTable);
			else
				return pH->EndFunction();
			if (!pTable->GetValue("radius",params.m_moveAbility.pathRadius))
				params.m_moveAbility.pathRadius = 10.f;
			break;
		}
	case AIOBJECT_WAYPOINT:
		break;
		/*
		// this block is commented out since params.m_sParamStruct is currently ignored in pEntity->RegisterInAISystem()
		// instead of setting the group id here, it will be set from the script right after registering
		default:
		// try to get groupid settings for anchors
		params.m_sParamStruct.m_nGroup = -1;
		params.m_sParamStruct.m_nSpecies = -1;
		{
		SmartScriptTable pTable;
		if ( pH->GetParamCount() > 2 )
		pH->GetParam( 3, pTable );
		if ( *pTable )
		pTable->GetValue( "groupid", params.m_sParamStruct.m_nGroup );
		}
		break;
		*/
	}

	// Remove any existing AI object
	pEntity->RegisterInAISystem(AIObjectParams(0));
 
	// Register in AI to get a new AI object, deregistering the old one in the process
	pEntity->RegisterInAISystem(params);

	// (MATT) ? {2008/02/15:19:46:29}
	// AI object was not created (possibly AI System is disabled)
	if (IAIObject* aiObject = pEntity->GetAI())
	{
		if(type==AIOBJECT_SNDSUPRESSOR)
			aiObject->SetRadius(params.m_moveAbility.pathRadius);
		else if(type>=AIANCHOR_FIRST)	// if anchor - set radius
		{
			SmartScriptTable pTable;
			// Properties table
			if (pH->GetParamCount() > 2)
				pH->GetParam(3,pTable);
			else
				return pH->EndFunction();
			float radius(0.f);
			pTable->GetValue("radius",radius);
			int groupId = -1;
			pTable->GetValue("groupid", groupId);
			aiObject->SetGroupId(groupId);
			aiObject->SetRadius(radius);
		}

		if (IAIActorProxy* proxy = aiObject->GetProxy())
			proxy->UpdateMeAlways(!autoDisable);
	}

	return pH->EndFunction();
}
//--------------------------------------------------------------------------------------------------
// Name: CFrontEndModelCache
// Desc: Constructor
//--------------------------------------------------------------------------------------------------
CFrontEndModelCache::CFrontEndModelCache()
{
#if FEMC_USE_LEVEL_HEAP
	SwitchToLevelHeap();
#endif // #if FEMC_USE_LEVEL_HEAP

	FE_LOG("Front End model cache creation");
	INDENT_LOG_DURING_SCOPE();

	IGameFramework* pGameFramework = g_pGame->GetIGameFramework();
	if(pGameFramework)
	{
		pGameFramework->StartNetworkStallTicker(true);
	}

	m_bIsMultiplayerCache = gEnv->bMultiplayer;

#if FEMC_FILE_ACCESS_LOG
	gEnv->pConsole->GetCVar("sys_FileAccessLog")->Set(1);
#endif // #if FEMC_FILE_ACCESS_LOG

#ifdef FEMC_LOG_CACHE_TIME
	const float startTime = gEnv->pTimer->GetAsyncCurTime();
#endif // #ifdef FEMC_LOG_CACHE_TIME

#if FEMC_CACHE_FILE_ACCESSES
	if (g_pGameCVars->g_FEMenuCacheSaveList)
	{
		gEnv->pCryPak->RegisterFileAccessSink(this);
		m_recordedFiles.clear();
	}
	int oldSaveLevelResourceList = 0;
	ICVar* pPakSaveLevelResourceListCvar = gEnv->pConsole->GetCVar("sys_PakSaveLevelResourceList");
	if(pPakSaveLevelResourceListCvar)
	{
		oldSaveLevelResourceList = pPakSaveLevelResourceListCvar->GetIVal();
		pPakSaveLevelResourceListCvar->Set(0);
	}
	m_pReasonForReportingFileOpen = "CFrontEndModelCache constructor";
#endif // #if FEMC_CACHE_FILE_ACCESSES

	CRY_ASSERT(s_pSingletonInstance == NULL);
	s_pSingletonInstance = this;

	// Load model list from xml, and cache each entry
	XmlNodeRef pRootNode = gEnv->pSystem->LoadXmlFromFile(FEMC_CACHE_LIST_FILENAME);
	if(pRootNode)
	{
		CGameXmlParamReader xmlParamReader(pRootNode);
		const char* pPakName = NULL;

		// Pak
		const char* const pGameFolder = gEnv->pCryPak->GetGameFolder();
		const XmlNodeRef pPakData = xmlParamReader.FindFilteredChild("PakData");
		if(pPakData && pPakData->getChildCount())
		{
			const XmlNodeRef pPak = pPakData->getChild(0);
			if(pPak)
			{
				pPakName = pPak->getAttr("name");
				bool bSucceeded = gEnv->pCryPak->OpenPack(pGameFolder,pPakName,ICryPak::FLAGS_FILENAMES_AS_CRC32);
				bSucceeded |= gEnv->pCryPak->LoadPakToMemory(pPakName,ICryPak::eInMemoryPakLocale_GPU);
				FE_LOG ("%s to open pack file '%s' bound to %s", bSucceeded ? "Managed" : "Failed", pPakName, pGameFolder);
			}

			// There is a pak, so reserve space for some materials in cache
			const uint materialCacheReserve = 64;
			m_materialCache.reserve(materialCacheReserve);
		}

		// Cache character models
		const XmlNodeRef pCharacterModelList = xmlParamReader.FindFilteredChild("CharacterModels");
		if(pCharacterModelList)
		{
			const int characterModelCount = pCharacterModelList->getChildCount();
			if(characterModelCount)
			{
				CreateSupportForFrontEnd3dModels();
			}

			for(int i=0; i<characterModelCount; i++)
			{
				const XmlNodeRef pCharacterModel = pCharacterModelList->getChild(i);
				if(pCharacterModel)
				{
					const char* pCharacterModelName = pCharacterModel->getAttr("name");
					CacheCharacterModel(pCharacterModelName);
				}
			}
		}

		// Cache item models
		const XmlNodeRef pItemModelsList = xmlParamReader.FindFilteredChild("ItemModels");
		if(pItemModelsList)
		{
			const int itemModelCount = pItemModelsList->getChildCount();
			if(itemModelCount)
			{
				CreateSupportForFrontEnd3dModels();
			}

			for(int i=0; i<itemModelCount; i++)
			{
				const XmlNodeRef pItemModel = pItemModelsList->getChild(i);
				if(pItemModel)
				{
					const char* pItemModelName = pItemModel->getAttr("name");
					if (strcmp(pItemModel->getTag(), "GeometryModels") == 0)
					{
						m_myGeometryCache.CacheGeometry(pItemModelName, false, IStatObj::ELoadingFlagsIgnoreLoDs);
					}
					else if (strcmp(pItemModel->getTag(), "ItemModel") == 0)
					{
						CacheItemModel(pItemModelName);
					}
				}
			}
		}

		// Unload pak
		if(pPakName)
		{
			gEnv->pCryPak->LoadPakToMemory( pPakName,ICryPak::eInMemoryPakLocale_Unload );
			bool bSucceeded = gEnv->pCryPak->ClosePack( pPakName,0 );
			FE_LOG ("%s to close pack file '%s'", bSucceeded ? "Managed" : "Failed", pPakName);
		}
	}

#if FEMC_FILE_ACCESS_LOG
	gEnv->pConsole->GetCVar("sys_FileAccessLog")->Set(0);
#endif // #if FEMC_FILE_ACCESS_LOG
#ifdef FEMC_LOG_CACHE_TIME
	const float endTime = gEnv->pTimer->GetAsyncCurTime();
	const float deltaTime = endTime - startTime;
	FE_LOG("FrontEndModelCache loading took %3.1f seconds", deltaTime);
#endif // #FEMC_LOG_CACHE_TIME FE_MODEL_CACHE_LOG_CACHE_TIME
#if FEMC_CACHE_FILE_ACCESSES
	m_pReasonForReportingFileOpen = NULL;

	if (g_pGameCVars->g_FEMenuCacheSaveList)
	{
		// To stop any other threads from messing
		gEnv->pCryPak->UnregisterFileAccessSink(this);

		std::set<string> fileset;
		// eliminate duplicate values
		std::vector<string>::iterator endLocation = std::unique( m_recordedFiles.begin(),m_recordedFiles.end() );
		m_recordedFiles.erase( endLocation,m_recordedFiles.end() );

		fileset.insert( m_recordedFiles.begin(),m_recordedFiles.end() );

		string sResourceSetFilename = PathUtil::AddSlash("Levels/Multiplayer") + "mpmenu_list.txt";
		{
			FILE* pFile = fxopen(sResourceSetFilename,"wb",true);
			if(pFile)
			{
				for(std::set<string>::iterator it = fileset.begin(); it != fileset.end(); ++it)
				{
					const char *pStr = it->c_str();
					fprintf( pFile,"%s\n",pStr );
					// Automatically add cgf->cgfm, cga->cgam, dds->dds.0
					const char* const pExt = PathUtil::GetExt(pStr);
					if (strcmp(pExt, "cgf") == 0)
					{
						fprintf( pFile,"%sm\n",pStr );
					}
					else if (strcmp(pExt, "cga") == 0)
					{
						fprintf( pFile,"%sm\n",pStr );
					}
					else if (strcmp(pExt, "dds") == 0)
					{
						fprintf( pFile,"%s.0\n",pStr );
					}
				}
				fclose(pFile);
			}
		}
	}
	if(pPakSaveLevelResourceListCvar)
	{
		pPakSaveLevelResourceListCvar->Set(oldSaveLevelResourceList);
	}
#endif // #if FEMC_CACHE_FILE_ACCESSES

	if(pGameFramework)
	{
		pGameFramework->StopNetworkStallTicker();
	}

	FE_LOG("Done caching items for front end");

#if FEMC_USE_LEVEL_HEAP
	SwitchToGlobalHeap();
#endif // #if FEMC_USE_LEVEL_HEAP
}//-------------------------------------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////////
// IsMountedWeaponUsableWithTarget
// A piece of game-code moved from CryAction when scriptbind_AI moved to the AI system
//////////////////////////////////////////////////////////////////////////
int CScriptBind_Game::IsMountedWeaponUsableWithTarget(IFunctionHandler *pH)
{
	int paramCount = pH->GetParamCount();
	if(paramCount<2)
	{
		GameWarning("%s: too few parameters.", __FUNCTION__);
		return pH->EndFunction();
	}

	GET_ENTITY(1);

	if(!pEntity)
	{
		GameWarning("%s: wrong entity id in parameter 1.", __FUNCTION__);
		return pH->EndFunction();
	}

	IAIObject* pAI = pEntity->GetAI();
	if (!pAI)
	{
		GameWarning("%s: Entity '%s' does not have AI.",__FUNCTION__,  pEntity->GetName());
		return pH->EndFunction();
	}

	EntityId itemEntityId;
	ScriptHandle hdl2;

	if(!pH->GetParam(2,hdl2))
	{
		GameWarning("%s: wrong parameter 2 format.", __FUNCTION__);
		return pH->EndFunction();
	}

	itemEntityId = (EntityId)hdl2.n;

	if (!itemEntityId)
	{
		GameWarning("%s: wrong entity id in parameter 2.", __FUNCTION__);
		return pH->EndFunction();
	}
	
	IGameFramework *pGameFramework = gEnv->pGame->GetIGameFramework();
	IItem* pItem = pGameFramework->GetIItemSystem()->GetItem(itemEntityId);
	if (!pItem)
	{
		//gEnv->pAISystem->Warning("<CScriptBind> ", "entity in parameter 2 is not an item/weapon");
		GameWarning("%s: entity in parameter 2 is not an item/weapon.", __FUNCTION__);
		return pH->EndFunction();
	}

	float minDist = 7;
	bool bSkipTargetCheck = false;
	Vec3 targetPos(ZERO);

	if(paramCount > 2)
	{
		for(int i=3;i <= paramCount ; i++)
		{
			if(pH->GetParamType(i) == svtBool)
				pH->GetParam(i,bSkipTargetCheck);
			else if(pH->GetParamType(i) == svtNumber)
				pH->GetParam(i,minDist);
			else if(pH->GetParamType(i) == svtObject)
				pH->GetParam(i,targetPos);
		}
	}

	IAIActor* pAIActor = CastToIAIActorSafe(pAI);
	if (!pAIActor)
	{
		GameWarning("%s: entity '%s' in parameter 1 is not an AI actor.", __FUNCTION__, pEntity->GetName());
		return pH->EndFunction();
	}


	IEntity* pItemEntity = pItem->GetEntity();
	if(!pItemEntity)
		return pH->EndFunction();


	if(!pItem->GetOwnerId())
	{
		// weapon is not used, check if it is on a vehicle
		IEntity* pParentEntity = pItemEntity->GetParent();
		if(pParentEntity)
		{
			IAIObject* pParentAI = pParentEntity->GetAI();
			if(pParentAI && pParentAI->GetAIType()==AIOBJECT_VEHICLE)
			{
				// (MATT) Feature was cut and code was tricky, hence ignore weapons in vehicles  {2008/02/15:11:08:51}
				return pH->EndFunction();
			}
		}
	}
	else if( pItem->GetOwnerId()!= pEntity->GetId()) // item is used by someone else?
		return pH->EndFunction(false);

	// check target
	if(bSkipTargetCheck)
		return pH->EndFunction(true);

	IAIObject* pTarget = pAIActor->GetAttentionTarget();
	if(targetPos.IsZero())
	{
		if(!pTarget)
			return pH->EndFunction();
		targetPos = pTarget->GetPos();
	}

	Vec3 targetDir(targetPos - pItemEntity->GetWorldPos());
	Vec3 targetDirXY(targetDir.x, targetDir.y, 0);

	float length2D = targetDirXY.GetLength();
	if(length2D < minDist || length2D<=0)
		return pH->EndFunction();

	targetDirXY /= length2D;//normalize

	IWeapon* pWeapon = pItem->GetIWeapon(); 
	bool vehicleGun = pWeapon && pWeapon->GetHostId();

	if (!vehicleGun)
	{
		Vec3 mountedAngleLimits(pItem->GetMountedAngleLimits());

		float yawRange = DEG2RAD(mountedAngleLimits.z);
		if(yawRange > 0 && yawRange < gf_PI)
		{
			float deltaYaw = pItem->GetMountedDir().Dot(targetDirXY);
			if(deltaYaw < cosf(yawRange))
				return pH->EndFunction(false);
		}

		float minPitch = DEG2RAD(mountedAngleLimits.x);
		float maxPitch = DEG2RAD(mountedAngleLimits.y);

		//maxPitch = (maxPitch - minPitch)/2;
		//minPitch = -maxPitch;

		float pitch = atanf(targetDir.z / length2D);

		if ( pitch < minPitch || pitch > maxPitch )
			return pH->EndFunction(false);
	}

	if(pTarget)
	{
		IEntity* pTargetEntity = pTarget->GetEntity();
		if(pTargetEntity)
		{
			// check target distance and where he's going
			IPhysicalEntity *phys = pTargetEntity->GetPhysics();
			if(phys)
			{
				pe_status_dynamics	dyn;
				phys->GetStatus(&dyn);
				Vec3 velocity ( dyn.v);
				velocity.z = 0;

				float speed = velocity.GetLength2D();
				if(speed>0)
				{
					//velocity /= speed;
					if(length2D< minDist * 0.75f && velocity.Dot(targetDirXY)<=0)
						return pH->EndFunction(false);
				}
			}
		}
	}
	return pH->EndFunction(true);

}
// TODO parameterise and refactor this now its mainly duplicated between the two runs
void CAutoTester::UpdateTestNumClients()
{
	if(gEnv->bServer)
	{
		IGameFramework *pFramework = gEnv->pGame->GetIGameFramework();
		int numChannels = 1; //local channel

		if(pFramework)
		{
			INetNub *pNub = pFramework->GetServerNetNub();

			if(pNub)
			{
				numChannels = pNub->GetNumChannels();
			}
		}

		if (numChannels > m_stateData.testNumClients.m_maxNumClientsConnected)
		{
			m_stateData.testNumClients.m_maxNumClientsConnected=numChannels;
		}

		float timeSeconds=gEnv->pTimer->GetFrameStartTime().GetSeconds();
		CryWatch("time=%f; numClients=%d; maxNumClients=%d; numClientsExpected=%d", timeSeconds, numChannels, m_stateData.testNumClients.m_maxNumClientsConnected, m_stateData.testNumClients.m_numClientsExpected);

		if (timeSeconds > m_stateData.testNumClients.m_debugTimer)
		{
			m_stateData.testNumClients.m_debugTimer = timeSeconds+2.0f;
			CryLogAlways("CAutoTester::UpdateTestNumClients() updating time=%f; numClients=%d; maxNumClients=%d; numClientsExpected=%d", timeSeconds, numChannels, m_stateData.testNumClients.m_maxNumClientsConnected, m_stateData.testNumClients.m_numClientsExpected);
		}

		if (timeSeconds > m_stateData.testNumClients.m_timeOut)
		{
			CryLogAlways("CAutoTester::UpdateTestNumClients() testing num clients and time has expired. numClients=%d; maxNumClients=%d; numClientsExpected=%d", numChannels, m_stateData.testNumClients.m_maxNumClientsConnected, m_stateData.testNumClients.m_numClientsExpected);

			bool passed=false;

			string mapName = g_pGame->GetIGameFramework()->GetILevelSystem()->GetCurrentLevel()->GetLevelInfo()->GetName();
			string gameRulesName;
			gameRulesName = g_pGame->GetGameRules()->GetEntity()->GetClass()->GetName();

			XmlNodeRef testCase = GetISystem()->CreateXmlNode();
			string nameStr;
			nameStr.Format("Level: %s; gameRules: %s; numClients=%d; timeTested=%.1f seconds", mapName.c_str(), gameRulesName.c_str(), numChannels, m_stateData.testNumClients.m_timeOut);
			testCase->setTag("testcase");
			testCase->setAttr("name", nameStr.c_str());
			testCase->setAttr("time", 0);

			testCase->setAttr("numClients", numChannels);
			testCase->setAttr("maxNumClientsConnected",m_stateData.testNumClients.m_maxNumClientsConnected);
			testCase->setAttr("numClientsExpected", m_stateData.testNumClients.m_numClientsExpected);

			if (numChannels == m_stateData.testNumClients.m_maxNumClientsConnected)
			{
				CryLogAlways("CAutoTester::UpdateTestNumClients() testing num clients and time has expired. We have the same number of clients are our maxNumClients %d", numChannels);

				if (numChannels == m_stateData.testNumClients.m_numClientsExpected)	// may want to remove this check as keeping the number that joined should be sufficient
				{
					CryLogAlways("CAutoTester::UpdateTestNumClients() testing num clients and time has expired. We have the same number of clients as we expected to have %d", numChannels);
					testCase->setAttr("status", "run");
					passed=true;
				}
				else
				{
					CryLogAlways("CAutoTester::UpdateTestNumClients() testing num clients and time has expired. We DON'T have the same number of clients %d as we expected to have %d", numChannels, m_stateData.testNumClients.m_numClientsExpected);
					//testCase->setAttr("status", "failed");
					XmlNodeRef failedCase = GetISystem()->CreateXmlNode();
					failedCase->setTag("failure");
					failedCase->setAttr("type", "NotEnoughClients");
					failedCase->setAttr("message", string().Format("testing num clients and time has expired. We DON'T have the same number of clients %d as we expected to have %d", numChannels, m_stateData.testNumClients.m_numClientsExpected));
					testCase->addChild(failedCase);
				}
			}
			else
			{
				//testCase->setAttr("status", "failed");
				XmlNodeRef failedCase = GetISystem()->CreateXmlNode();
				failedCase->setTag("failure");
				failedCase->setAttr("type", "NotEnoughClients");
				failedCase->setAttr("message", string().Format("testing num clients and time has expired. We DON'T have the same number of clients %d as we peaked at %d", numChannels, m_stateData.testNumClients.m_maxNumClientsConnected));
				testCase->addChild(failedCase);
			}






			AddTestCaseResult("Test Clients In Levels", testCase, passed);

			Stop();
		}
	}
}
void CAutoTester::UpdateTestNumClientsLevelRotate()
{
	if(gEnv->bServer)
	{
		IGameFramework *pFramework = gEnv->pGame->GetIGameFramework();
		int numChannels = 1; //local channel

		if(pFramework)
		{
			INetNub *pNub = pFramework->GetServerNetNub();

			if(pNub)
			{
				numChannels = pNub->GetNumChannels();
			}
		}

		if (numChannels > m_stateData.testNumClientsRotate.m_maxNumClientsConnected)
		{
			m_stateData.testNumClientsRotate.m_maxNumClientsConnected=numChannels;
		}

		float timeSeconds=gEnv->pTimer->GetFrameStartTime().GetSeconds();
		CryWatch("time=%f; nextTimeOut=%f; numClients=%d; maxNumClients=%d; numClientsExpected=%d", timeSeconds, m_stateData.testNumClientsRotate.m_nextTimeOut, numChannels, m_stateData.testNumClientsRotate.m_maxNumClientsConnected, m_stateData.testNumClientsRotate.m_numClientsExpected);

		if (timeSeconds > m_stateData.testNumClientsRotate.m_debugTimer)
		{
			m_stateData.testNumClientsRotate.m_debugTimer = timeSeconds+2.0f;
			CryLogAlways("CAutoTester::UpdateTestNumClientsLevelRotate() updating time=%f; nextTimeOut=%f; numClients=%d; maxNumClients=%d; numClientsExpected=%d", timeSeconds, m_stateData.testNumClientsRotate.m_nextTimeOut, numChannels, m_stateData.testNumClientsRotate.m_maxNumClientsConnected, m_stateData.testNumClientsRotate.m_numClientsExpected);
		}

		if (timeSeconds > m_stateData.testNumClientsRotate.m_nextTimeOut)
		{
			CryLogAlways("CAutoTester::UpdateTestNumClientsLevelRotate() testing num clients and time has expired. numClients=%d; maxNumClients=%d; numClientsExpected=%d", numChannels, m_stateData.testNumClientsRotate.m_maxNumClientsConnected, m_stateData.testNumClientsRotate.m_numClientsExpected);

			bool passed=false;

			ILevelRotation *pLevelRotation = g_pGame->GetIGameFramework()->GetILevelSystem()->GetLevelRotation();

			string mapName = g_pGame->GetIGameFramework()->GetILevelSystem()->GetCurrentLevel()->GetLevelInfo()->GetName();
			string gameRulesName;
			gameRulesName = g_pGame->GetGameRules()->GetEntity()->GetClass()->GetName();

			XmlNodeRef testCase = GetISystem()->CreateXmlNode();
			string nameStr;
			if (m_stateData.testNumClientsRotate.m_levelIndex == 0)
			{
				nameStr.Format("%02d/%d) Level: %s; gameRules: %s; numClients=%d; timeTested=%.1f seconds", m_stateData.testNumClientsRotate.m_levelIndex+1, pLevelRotation->GetLength(), mapName.c_str(), gameRulesName.c_str(), numChannels, m_stateData.testNumClientsRotate.m_firstLevelTimeOut);
			}
			else
			{
				nameStr.Format("%02d/%d) Level: %s; gameRules: %s; numClients=%d; timeTested=%.1f seconds", m_stateData.testNumClientsRotate.m_levelIndex+1, pLevelRotation->GetLength(), mapName.c_str(), gameRulesName.c_str(), numChannels, m_stateData.testNumClientsRotate.m_levelTimeOut);
			}

			CryLogAlways("CAutoTester::UpdateTestNumClientsLevelRotate() outputting a test result with these details [%s]", nameStr.c_str());

			testCase->setTag("testcase");
			testCase->setAttr("name", nameStr.c_str());
			testCase->setAttr("time", 0);

			testCase->setAttr("numClients", numChannels);
			testCase->setAttr("maxNumClientsConnected",m_stateData.testNumClientsRotate.m_maxNumClientsConnected);
			testCase->setAttr("numClientsExpected", m_stateData.testNumClientsRotate.m_numClientsExpected);

			if (numChannels == m_stateData.testNumClientsRotate.m_maxNumClientsConnected)
			{
				CryLogAlways("CAutoTester::UpdateTestNumClientsLevelRotate() testing num clients and time has expired. We have the same number of clients are our maxNumClients %d", numChannels);

				if (numChannels == m_stateData.testNumClientsRotate.m_numClientsExpected)	// may want to remove this check as keeping the number that joined should be sufficient
				{
					CryLogAlways("CAutoTester::UpdateTestNumClientsLevelRotate() testing num clients and time has expired. We have the same number of clients as we expected to have %d", numChannels);
					testCase->setAttr("status", "run");
					passed=true;
				}
				else
				{
					CryLogAlways("CAutoTester::UpdateTestNumClientsLevelRotate() testing num clients and time has expired. We DON'T have the same number of clients %d as we expected to have %d", numChannels, m_stateData.testNumClientsRotate.m_numClientsExpected);
					//testCase->setAttr("status", "failed");
					XmlNodeRef failedCase = GetISystem()->CreateXmlNode();
					failedCase->setTag("failure");
					failedCase->setAttr("type", "NotEnoughClients");
					failedCase->setAttr("message", string().Format("testing num clients and time has expired. We DON'T have the same number of clients %d as we expected to have %d", numChannels, m_stateData.testNumClientsRotate.m_numClientsExpected));
					testCase->addChild(failedCase);
				}
			}
			else
			{
				//testCase->setAttr("status", "failed");
				XmlNodeRef failedCase = GetISystem()->CreateXmlNode();
				failedCase->setTag("failure");
				failedCase->setAttr("type", "NotEnoughClients");
				failedCase->setAttr("message", string().Format("testing num clients and time has expired. We DON'T have the same number of clients %d as we peaked at %d", numChannels, m_stateData.testNumClientsRotate.m_maxNumClientsConnected));
				testCase->addChild(failedCase);
			}

			AddTestCaseResult("Test Clients In Level Rotation", testCase, passed);
			Stop();


		
			if (pLevelRotation->GetNext() != 0)
			{
				CryLogAlways("CAutoTester::UpdateTestNumClientsLevelRotate() has found we're not at the end of the level rotation moving on to the next level - levelIndex=%d; rotation->GetNext()=%d\n", m_stateData.testNumClientsRotate.m_levelIndex+1, pLevelRotation->GetNext());
				Restart();
				gEnv->pConsole->ExecuteString("g_nextlevel");	// has to be a better way of doing this
				m_stateData.testNumClientsRotate.m_nextTimeOut = timeSeconds + m_stateData.testNumClientsRotate.m_levelTimeOut;
				m_stateData.testNumClientsRotate.m_levelIndex++;
			}
			else
			{
				CryLogAlways("CAutoTester::UpdateTestNumClientsLevelRotate() has found we ARE at the end of the level rotation. Not doing anymore tests\n");
			}
		}
	}
}
Beispiel #29
0
bool CRichPresence::SetRichPresence(ERichPresenceState state)
{
	// don't set rich presence if we don't have a controller yet
	if(!g_pGame->HasExclusiveControllerIndex())
	{
		CryLog("[Rich Presence] not setting rich presence, no player set");
		return true;
	}

	CrySessionID sessionID = CrySessionInvalidID;

	if((m_currentState == state) && GameNetworkUtils::CompareCrySessionId(sessionID, m_currentSessionID))
	{
		if(state != eRPS_InGame || !gEnv->bMultiplayer)
		{
			CryLog("[Rich Presence] not setting rich presence state %d multiplayer %d", state, gEnv->bMultiplayer);
			return true;
		}
	}

	// we are already setting rich presence, so wait until that task has finished
	if (m_taskID != CryLobbyInvalidTaskID)
	{
		CryLog("  already setting rich presence, setting desired state to %d", state);
		m_desiredState = state;
		return false;
	}

	ICryLobby *pLobby = gEnv->pNetwork->GetLobby();
	ICryLobbyService *pLobbyService = pLobby ? pLobby->GetLobbyService(eCLS_Online) : NULL;
	ICryLobbyUI *pLobbyUI = pLobbyService ? pLobbyService->GetLobbyUI() : NULL;
	ECryLobbyError error = eCLE_Success;

	m_pendingSessionID = sessionID;

	if(pLobbyUI)
	{
		uint32 userIndex = g_pGame->GetExclusiveControllerDeviceIndex();
		
		CryLog("[Rich Presence] SetRichPresence %d userIndex %d", state, userIndex);

		switch(state)
		{
			case eRPS_Idle:
			{
				SCryLobbyUserData data;

				data.m_id = RICHPRESENCE_ID;
				data.m_type = eCLUDT_Int32;
				data.m_int32 = RICHPRESENCE_IDLE;
				
				error = pLobbyUI->SetRichPresence(userIndex, &data, 1, &m_taskID, CRichPresence::SetRichPresenceCallback, this);
				break;
			}

			case eRPS_FrontEnd:
			{
				SCryLobbyUserData data;

				data.m_id = RICHPRESENCE_ID;
				data.m_type = eCLUDT_Int32;
				data.m_int32 = RICHPRESENCE_FRONTEND;

				error = pLobbyUI->SetRichPresence(userIndex, &data, 1, &m_taskID, CRichPresence::SetRichPresenceCallback, this);
				break;
			}

			case eRPS_Lobby:
			{
				SCryLobbyUserData data;

				data.m_id = RICHPRESENCE_ID;
				data.m_type = eCLUDT_Int32;
				data.m_int32 = RICHPRESENCE_LOBBY;

				error = pLobbyUI->SetRichPresence(userIndex, &data, 1, &m_taskID, CRichPresence::SetRichPresenceCallback, this);
				break;
			}

			case eRPS_InGame:
			{
				if(gEnv->bMultiplayer)
				{
					CGameRules *pGameRules = g_pGame->GetGameRules();
					IGameFramework *pGameFramework = g_pGame->GetIGameFramework();
					const char *levelName = pGameFramework ? pGameFramework->GetLevelName() : NULL;
					const char *gameRulesName = pGameRules ? pGameRules->GetEntity()->GetClass()->GetName() : NULL;
					int32 gameMode = 0;
					int32 map = 0;

					if(levelName)
					{
						levelName = PathUtil::GetFileName(levelName);
						TRichPresenceMap::const_iterator iter = m_richPresence.find(levelName);
						map = (iter == m_richPresence.end()) ? 0 : iter->second;
					}

					if(gameRulesName)
					{
						TRichPresenceMap::const_iterator iter = m_richPresence.find(gameRulesName);
						gameMode = (iter == m_richPresence.end()) ? 0 : iter->second;
					}

					SCryLobbyUserData data[eRPT_Max];
					
					data[eRPT_String].m_id = RICHPRESENCE_ID;
					data[eRPT_String].m_type = eCLUDT_Int32;
					data[eRPT_String].m_int32 = RICHPRESENCE_GAMEPLAY;
					
					data[eRPT_Param1].m_id = RICHPRESENCE_GAMEMODES;
					data[eRPT_Param1].m_type = eCLUDT_Int32;
					data[eRPT_Param1].m_int32 = gameMode;
					
					data[eRPT_Param2].m_id = RICHPRESENCE_MAPS;
					data[eRPT_Param2].m_type = eCLUDT_Int32;
					data[eRPT_Param2].m_int32 = map;

					error = pLobbyUI->SetRichPresence(userIndex, data, 3, &m_taskID, CRichPresence::SetRichPresenceCallback, this);
				}
				else
				{
					SCryLobbyUserData data;

					data.m_id = RICHPRESENCE_ID;
					data.m_type = eCLUDT_Int32;
					data.m_int32 = RICHPRESENCE_SINGLEPLAYER;
					
					error = pLobbyUI->SetRichPresence(userIndex, &data, 1, &m_taskID, CRichPresence::SetRichPresenceCallback, this);
				}
				break;
			}

			default:
				CryLog("[RichPresence] SetRichPresence - unknown rich presence %d", state);
				break;
		}

		if(error != eCLE_Success)
		{
			// failed to set rich presence, possibly because of too many lobby tasks, store it and try again later
			m_desiredState = state;
			m_pendingSessionID = CrySessionInvalidID;
			
			CryLog("[Rich Presence] SetRichPresence - Rich presence %s with error code %d", error == eCLE_Success ? "succeeded" : "failed", error);
		}
		else
		{
			m_pendingState = state;
			m_desiredState = eRPS_None;

			CryLog("[Rich Presence] SetRichPresence - Rich presence has been successfully started");
		}
	}
#if !defined(_RELEASE)
	else
	{
		error = eCLE_InternalError;
		CryLog("[Rich Presence] SetRichPresence called but we have no lobby, tried to set state to %d", state);
	}
#endif

	return (error == eCLE_Success);
}
void CMelee::Impulse(const Vec3 &pt, const Vec3 &dir, const Vec3 &normal, IPhysicalEntity *pCollider, EntityId collidedEntityId, int partId, int ipart, int surfaceIdx, int hitTypeID, int iPrim)
{
	if (pCollider && m_pMeleeParams->meleeparams.impulse>0.001f)
	{
		CActor* pOwnerActor = m_pWeapon->GetOwnerActor();
		const SPlayerMelee& meleeCVars = g_pGameCVars->pl_melee;
		const SMeleeParams& meleeParams = m_pMeleeParams->meleeparams;
		float impulse = meleeParams.impulse;
		bool aiShooter = pOwnerActor ? !pOwnerActor->IsPlayer() : true;
		bool delayImpulse = false;

		float impulseScale = 1.0f;
		
		//[kirill] add impulse to phys proxy - to make sure it's applied to cylinder as well (not only skeleton) - so that entity gets pushed
		// if no pEntity - do it old way
		IEntity * pEntity = gEnv->pEntitySystem->GetEntity(collidedEntityId);
		IGameFramework* pGameFramework = g_pGame->GetIGameFramework();
		CActor* pTargetActor = static_cast<CActor*>(pGameFramework->GetIActorSystem()->GetActor(collidedEntityId));
		if (pEntity && pTargetActor)
		{
			//If it's an entity, use the specific impulses if needed, and apply to physics proxy
			if ( meleeCVars.impulses_enable != SPlayerMelee::ei_Disabled )
			{
				impulse = meleeParams.impulse_actor;

				bool aiTarget = !pTargetActor->IsPlayer();

				if (aiShooter && !aiTarget)
				{
					float impulse_ai_to_player = GetImpulseAiToPlayer();
					if (impulse_ai_to_player != -1.f)
					{
						impulse = impulse_ai_to_player;
					}
				}

				//Delay a bit on death actors, when switching from alive to death, impulses don't apply
				//I schedule an impulse here, to get rid off the ugly .lua code which was calculating impulses on its own
				if (pTargetActor->IsDead())
				{
					if (meleeCVars.impulses_enable != SPlayerMelee::ei_OnlyToAlive)
					{
						delayImpulse = true;
						const float actorCustomScale = 1.0f;

						impulseScale *= actorCustomScale;
					}
					else
					{
						impulse = 0.0f;
					}
				}
				else if (meleeCVars.impulses_enable == SPlayerMelee::ei_OnlyToDead)
				{
					// Always allow impulses for melee from AI to local player
					// [*DavidR | 27/Oct/2010] Not sure about this
					if (!(aiShooter && !aiTarget))
						impulse = 0.0f;
				}
			}
			else if (pGameFramework->GetIVehicleSystem()->GetVehicle(collidedEntityId))
			{
				impulse = m_pMeleeParams->meleeparams.impulse_vehicle;
				impulseScale = 1.0f;
			}
		}

		const float fScaledImpulse = impulse * impulseScale;
		if (fScaledImpulse > 0.0f)
		{
			if (!delayImpulse)
			{
				m_collisionHelper.Impulse(pCollider, pt, dir * fScaledImpulse, partId, ipart, hitTypeID);
			}
			else
			{
				//Force up impulse, to make the enemy fly a bit
				Vec3 newDir = (dir.z < 0.0f) ? Vec3(dir.x, dir.y, 0.1f) : dir;
				newDir.Normalize();
				newDir.x *= fScaledImpulse;
				newDir.y *= fScaledImpulse;
				newDir.z *= impulse;

				if( pTargetActor )
				{
					pe_action_impulse imp;
					imp.iApplyTime = 0;
					imp.impulse = newDir;
					//imp.ipart = ipart;
					imp.partid = partId;
					imp.point = pt;
					pTargetActor->GetImpulseHander()->SetOnRagdollPhysicalizedImpulse( imp );
				}
				else
				{
					m_pWeapon->GetScheduler()->TimerAction(100, CSchedulerAction<DelayedImpulse>::Create(DelayedImpulse(*this, collidedEntityId, pt, newDir, partId, ipart, hitTypeID)), true);
				}
			}
		}

		// scar bullet
		// m = 0.0125
		// v = 800
		// energy: 4000
		// in this case the mass of the active collider is a player part
		// so we must solve for v given the same energy as a scar bullet
		float speed = cry_sqrtf(4000.0f/(80.0f*0.5f)); // 80.0f is the mass of the player

		if( IRenderNode *pBrush = (IRenderNode*)pCollider->GetForeignData(PHYS_FOREIGN_ID_STATIC) )
		{
			speed = 0.003f;
		}

		m_collisionHelper.GenerateArtificialCollision(m_pWeapon->GetOwner(), pCollider, pt, normal, dir * speed, partId, ipart, surfaceIdx, iPrim);
	}
}