CHitDeathReactionsPtr	CCustomReactionFunctions::GetActorHitDeathReactions(CActor& actor) const
{
	CRY_ASSERT(actor.GetActorClass() == CPlayer::GetActorClassType());
	CPlayer& player = static_cast<CPlayer&>(actor);
	return player.GetHitDeathReactions();
}
Example #2
0
//------------------------------------------------------------------------
void CGameRules::ProcessServerHit(const HitInfo &hitInfo)
{
	bool ok=true;
	// check if shooter is alive
	CActor *pShooter = GetActorByEntityId(hitInfo.shooterId);
	CActor *pTarget = GetActorByEntityId(hitInfo.targetId);

	if (hitInfo.shooterId)
	{
		if (pShooter && pShooter->GetHealth()<=0)
			ok=false;
	}

	if (hitInfo.targetId)
	{
		if (pTarget && pTarget->GetSpectatorMode())
			ok=false;
	}

	if (ok)
	{
		float fTargetHealthBeforeHit = 0.0f;
		if(pTarget)
		{
			fTargetHealthBeforeHit = pTarget->GetHealth();
		}

		CreateScriptHitInfo(m_scriptHitInfo, hitInfo);
		CallScript(m_serverStateScript, "OnHit", m_scriptHitInfo);

		if(pTarget && !pTarget->IsDead())
		{
			const float fCausedDamage = fTargetHealthBeforeHit - pTarget->GetHealth();
			ProcessLocalHit(hitInfo, fCausedDamage);
		}

		// call hit listeners if any
		if (m_hitListeners.empty() == false)
		{
			for (size_t i = 0; i < m_hitListeners.size(); )
			{
				size_t count = m_hitListeners.size();
				m_hitListeners[i]->OnHit(hitInfo);
				if (count == m_hitListeners.size())
					i++;
				else
					continue;
			}
		}

		if (pShooter && hitInfo.shooterId!=hitInfo.targetId && hitInfo.weaponId!=hitInfo.shooterId && hitInfo.weaponId!=hitInfo.targetId && hitInfo.damage>=0)
		{
			EntityId params[2];
			params[0] = hitInfo.weaponId;
			params[1] = hitInfo.targetId;
			m_pGameplayRecorder->Event(pShooter->GetEntity(), GameplayEvent(eGE_WeaponHit, 0, 0, (void *)params));
		}

		if (pShooter)
			m_pGameplayRecorder->Event(pShooter->GetEntity(), GameplayEvent(eGE_Hit, 0, 0, (void *)hitInfo.weaponId));

		if (pShooter)
			m_pGameplayRecorder->Event(pShooter->GetEntity(), GameplayEvent(eGE_Damage, 0, hitInfo.damage, (void *)hitInfo.weaponId));
	}
}
Example #3
0
//------------------------------------------------------------------------
void CGameRules::ServerSimpleHit(const SimpleHitInfo &simpleHitInfo)
{
	if (my->CallHook(
		"OnEntityDamage", 
		oohh::GetEntityFromId(simpleHitInfo.targetId), 
		oohh::GetEntityFromId(simpleHitInfo.weaponId), 
		oohh::GetEntityFromId(simpleHitInfo.shooterId), 
		simpleHitInfo.value, 
		Vec3(0,0,0), 
		Vec3(0,0,0)
	))
	{
		if (true)
			return;
	}

	switch (simpleHitInfo.type)
	{
	case 0: // tag
		{
			if (!simpleHitInfo.targetId)
				return;

			// tagged entities are temporary in MP, not in SP.
			bool temp = gEnv->bMultiplayer;

			AddTaggedEntity(simpleHitInfo.shooterId, simpleHitInfo.targetId, temp);
		}
		break;
	case 1: // tac
		{
			if (!simpleHitInfo.targetId)
				return;

			CActor *pActor = (CActor *)gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(simpleHitInfo.targetId);

			if (pActor && pActor->CanSleep())
				pActor->Fall(Vec3(0.0f,0.0f,0.0f),simpleHitInfo.value);
		}
		break;
	case 0xe: // freeze
		{
			if (!simpleHitInfo.targetId)
				return;
			
			// call OnFreeze
			bool allow=true;
			if (m_serverStateScript.GetPtr() && m_serverStateScript->GetValueType("OnFreeze")==svtFunction)
			{
				HSCRIPTFUNCTION func=0;
				m_serverStateScript->GetValue("OnFreeze", func);
				Script::CallReturn(m_serverStateScript->GetScriptSystem(), func, m_script, ScriptHandle(simpleHitInfo.targetId), ScriptHandle(simpleHitInfo.shooterId), ScriptHandle(simpleHitInfo.weaponId), simpleHitInfo.value, allow);
				gEnv->pScriptSystem->ReleaseFunc(func);
			}

			if (!allow)
				return;

			if (IEntity *pEntity=gEnv->pEntitySystem->GetEntity(simpleHitInfo.targetId))
			{
				IScriptTable *pScriptTable=pEntity->GetScriptTable();

				// call OnFrost
				if (pScriptTable && pScriptTable->GetValueType("OnFrost")==svtFunction)
				{
					HSCRIPTFUNCTION func=0;
					pScriptTable->GetValue("OnFrost", func);
					Script::Call(pScriptTable->GetScriptSystem(), func, pScriptTable, ScriptHandle(simpleHitInfo.shooterId), ScriptHandle(simpleHitInfo.weaponId), simpleHitInfo.value);
					gEnv->pScriptSystem->ReleaseFunc(func);
				}

				FreezeEntity(simpleHitInfo.targetId, true, true, simpleHitInfo.value>0.999f);
			}
		}
		break;
	default:
		assert(!"Unknown Simple Hit type!");
	}
}
//-------------------------------------------
void CGameRules::ProcessClientExplosionScreenFX(const ExplosionInfo &explosionInfo)
{
	IActor *pClientActor = g_pGame->GetIGameFramework()->GetClientActor();

	if (pClientActor)
	{
		//Distance
		float dist = (pClientActor->GetEntity()->GetWorldPos() - explosionInfo.pos).len();
		//Is the explosion in Player's FOV (let's suppose the FOV a bit higher, like 80)
		CActor *pActor = (CActor *)pClientActor;
		SMovementState state;

		if (IMovementController *pMV = pActor->GetMovementController())
		{
			pMV->GetMovementState(state);
		}

		Vec3 eyeToExplosion = explosionInfo.pos - state.eyePosition;
		eyeToExplosion.Normalize();
		bool inFOV = (state.eyeDirection.Dot(eyeToExplosion) > 0.68f);
		//All explosions have radial blur (default 30m radius, to make Sean happy =))
		float maxBlurDistance = (explosionInfo.maxblurdistance > 0.0f) ? explosionInfo.maxblurdistance : 30.0f;

		if (maxBlurDistance > 0.0f && g_pGameCVars->g_radialBlur > 0.0f && m_explosionScreenFX && explosionInfo.radius > 0.5f)
		{
			if (inFOV && dist < maxBlurDistance)
			{
				ray_hit hit;
				int col = gEnv->pPhysicalWorld->RayWorldIntersection(explosionInfo.pos , -eyeToExplosion * dist, ent_static | ent_terrain, rwi_stop_at_pierceable | rwi_colltype_any, &hit, 1);

				//If there was no obstacle between flashbang grenade and player
				if(!col)
				{
					float distAmp = 1.0f - (dist / maxBlurDistance);

					if (gEnv->pInput)
					{
						gEnv->pInput->ForceFeedbackEvent( SFFOutputEvent(eDI_XI, eFF_Rumble_Basic, 0.5f, distAmp * 3.0f, 0.0f));
					}
				}
			}
		}

		//Flashbang effect
		if(dist < explosionInfo.radius && inFOV &&
				(!strcmp(explosionInfo.effect_class, "flashbang") || !strcmp(explosionInfo.effect_class, "FlashbangAI")))
		{
			ray_hit hit;
			int col = gEnv->pPhysicalWorld->RayWorldIntersection(explosionInfo.pos , -eyeToExplosion * dist, ent_static | ent_terrain, rwi_stop_at_pierceable | rwi_colltype_any, &hit, 1);

			//If there was no obstacle between flashbang grenade and player
			if(!col)
			{
				float power = explosionInfo.flashbangScale;
				power *= max(0.0f, 1 - (dist / explosionInfo.radius));
				float lookingAt = (eyeToExplosion.Dot(state.eyeDirection.normalize()) + 1) * 0.5f;
				power *= lookingAt;
				gEnv->p3DEngine->SetPostEffectParam("Flashbang_Time", 1.0f + (power * 4));
				gEnv->p3DEngine->SetPostEffectParam("FlashBang_BlindAmount", explosionInfo.blindAmount);
				gEnv->p3DEngine->SetPostEffectParam("Flashbang_DifractionAmount", (power * 2));
				gEnv->p3DEngine->SetPostEffectParam("Flashbang_Active", 1);
			}
		}
		else if(inFOV && (dist < explosionInfo.radius))
		{
			if (explosionInfo.damage > 10.0f || explosionInfo.pressure > 100.0f)
			{
				//Add some angular impulse to the client actor depending on distance, direction...
				float dt = (1.0f - dist / explosionInfo.radius);
				dt = dt * dt;
				float angleZ = gf_PI * 0.15f * dt;
				float angleX = gf_PI * 0.15f * dt;
				pActor->AddAngularImpulse(Ang3(Random(-angleX * 0.5f, angleX), 0.0f, Random(-angleZ, angleZ)), 0.0f, dt * 2.0f);
			}
		}
	}
}
Example #5
0
void CLevel::ProcessGameEvents		()
{
	// Game events
	{
		NET_Packet			P;
		u32 svT				= timeServer()-NET_Latency;

		/*
		if (!game_events->queue.empty())	
			Msg("- d[%d],ts[%d] -- E[svT=%d],[evT=%d]",Device.dwTimeGlobal,timeServer(),svT,game_events->queue.begin()->timestamp);
		*/
#ifdef   SPAWN_ANTIFREEZE
		while (spawn_events->available(svT))
		{
			u16 ID, dest, type;
			spawn_events->get(ID, dest, type, P);
			game_events->insert(P);
		}
		u32 avail_time = 5;
		u32 elps = Device.frame_elapsed();
		if (elps < 30) avail_time = 33 - elps;
		u32 work_limit = elps + avail_time;

#endif
		while	(game_events->available(svT))
		{
			u16 ID,dest,type;
			game_events->get	(ID,dest,type,P);

#ifdef   SPAWN_ANTIFREEZE
			// не отправлять события не заспавненным объектам
			if (g_bootComplete && M_EVENT == ID && PostponedSpawn(dest))
			{
				spawn_events->insert(P);
				continue;
			}
			if (g_bootComplete && M_SPAWN == ID && Device.frame_elapsed() > work_limit) // alpet: позволит плавнее выводить объекты в онлайн, без заметных фризов
			{
				u16 parent_id;
				GetSpawnInfo(P, parent_id);
				//-------------------------------------------------				
				if (parent_id < 0xffff) // откладывать спавн только объектов в контейнеры
				{
					//if (!spawn_events->available(svT))
						//Msg("* ProcessGameEvents, spawn event postponed. Events rest = %d", game_events->queue.size());

					spawn_events->insert(P);
					continue;
				}
			}
#endif
			switch (ID)
			{
			case M_SPAWN:
				{
					u16 dummy16;
					P.r_begin(dummy16);
					cl_Process_Spawn(P);
				}break;
			case M_EVENT:
				{
					cl_Process_Event(dest, type, P);
				}break;
			case M_MOVE_PLAYERS:
				{
					u8 Count = P.r_u8();
					for (u8 i=0; i<Count; i++)
					{
						u16 ID = P.r_u16();					
						Fvector NewPos, NewDir;
						P.r_vec3(NewPos);
						P.r_vec3(NewDir);

						CActor*	OActor	= smart_cast<CActor*>(Objects.net_Find		(ID));
						if (0 == OActor)		break;
						OActor->MoveActor(NewPos, NewDir);
					};

					NET_Packet PRespond;
					PRespond.w_begin(M_MOVE_PLAYERS_RESPOND);
					Send(PRespond, net_flags(TRUE, TRUE));
				}break;
			case M_STATISTIC_UPDATE:
				{
					if (GameID() != eGameIDSingle)
						Game().m_WeaponUsageStatistic->OnUpdateRequest(&P);
				}break;
			case M_FILE_TRANSFER:
				{
					if (m_file_transfer)			//in case of net_Stop
						m_file_transfer->on_message(&P);
				}break;
			case M_GAMEMESSAGE:
				{
					Game().OnGameMessage(P);
				}break;
			default:
				{
					VERIFY(0);
				}break;
			}			
		}
	}
	if (OnServer() && GameID()!= eGameIDSingle)
		Game().m_WeaponUsageStatistic->Send_Check_Respond();
}
Example #6
0
void CTacBullet::HandleEvent(const SGameObjectEvent &event)
{
	if (m_destroying)
		return;

	CProjectile::HandleEvent(event);

	if (event.event == eGFE_OnCollision)
	{
		EventPhysCollision *pCollision = reinterpret_cast<EventPhysCollision *>(event.ptr);
		if (!pCollision)
			return;

		IEntity *pTarget = pCollision->iForeignData[1]==PHYS_FOREIGN_ID_ENTITY ? (IEntity*)pCollision->pForeignData[1]:0;
		if (pTarget)
		{
			CGameRules *pGameRules = g_pGame->GetGameRules();

			EntityId targetId = pTarget->GetId();
			CActor *pActor = (CActor *)gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(targetId);
			
			if(pActor && pActor->CanSleep())
			{
				if(pActor->GetLinkedVehicle() && !gEnv->bMultiplayer)
				{
					SleepTargetInVehicle(m_ownerId,pActor);
				}
				else if(IEntity* pOwnerEntity = gEnv->pEntitySystem->GetEntity(m_ownerId))
				{
					if (pTarget->GetAI() && !pTarget->GetAI()->IsFriendly(pOwnerEntity->GetAI(), false))
					{
						float sleepTime = 30.0f;
						if(m_pAmmoParams)
							sleepTime = m_pAmmoParams->sleepTime;
						SimpleHitInfo info(m_ownerId, targetId, m_weaponId, 1, sleepTime); // 0=tag,1=tac
						info.remote=IsRemote();

						pGameRules->ClientSimpleHit(info);
					}
				}
			}
			else
			{
				Vec3 dir(0, 0, 0);
				if (pCollision->vloc[0].GetLengthSquared() > 1e-6f)
					dir = pCollision->vloc[0].GetNormalized();

				HitInfo hitInfo(m_ownerId, pTarget->GetId(), m_weaponId,
					(float)m_damage, 0.0f, pGameRules->GetHitMaterialIdFromSurfaceId(pCollision->idmat[1]), pCollision->partid[1],
					m_hitTypeId, pCollision->pt, dir, pCollision->n);

				hitInfo.remote = IsRemote();
				hitInfo.projectileId = GetEntityId();
				hitInfo.bulletType = m_pAmmoParams->bulletType;

				pGameRules->ClientHit(hitInfo);
			}

		}
		else if (pCollision->pEntity[0]->GetType() == PE_PARTICLE)
		{
			float bouncy, friction;
			uint32	pierceabilityMat;
			gEnv->pPhysicalWorld->GetSurfaceParameters(pCollision->idmat[1], bouncy, friction, pierceabilityMat);
			pierceabilityMat&=sf_pierceable_mask;

			pe_params_particle params;
			if(pCollision->pEntity[0]->GetParams(&params)==0)
				SetDefaultParticleParams(&params);

			if (pierceabilityMat>params.iPierceability && pCollision->idCollider!=-1) 
				return;
		}

		Destroy();
	}
}
Example #7
0
void CGameStateRecorder::OnRecordedGameplayEvent(IEntity *pEntity, const GameplayEvent &event, int currentFrame, bool bRecording)
{
	EntityId id;
	m_currentFrame = currentFrame;

	int demo_forceGameState = 0;
	if(!bRecording)
	{
		ICVar *pVar = gEnv->pConsole->GetCVar( "demo_force_game_state" );
		if(pVar)
			demo_forceGameState = pVar->GetIVal();
	}
	
	if(!pEntity || !(id = pEntity->GetId()))
		return;

	if(m_IgnoredEvents.size())
		if(event.event == m_IgnoredEvents[0])
		{
			m_IgnoredEvents.erase(m_IgnoredEvents.begin());
			return;
		}

		TGameStates::iterator itActor = m_GameStates.find(id);
	if(itActor == m_GameStates.end())
	{
		m_GameStates.insert(std::make_pair(id,SActorGameState()));
		itActor = m_GameStates.find(id);
	}
	if(itActor == m_GameStates.end())
	{
		GameWarning("TimeDemo:GameState: actor %s not found in records",pEntity->GetName());
		return;
	}

	SActorGameState& gstate = itActor->second;

	switch(event.event)
	{
		case eGE_HealthChanged: 
			{
				gstate.health = event.value;

				if(!m_bRecording)
				{
					CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
					if(pActor)
					{
						if(m_bLogWarning)
						{
							if(CHECK_MISMATCH(pActor->GetHealth(), gstate.health,10))
							{
								if(!gstate.bHealthDifferent)
								{
									GameWarning("TimeDemo:GameState: Frame %d - Actor %s - HEALTH mismatch (%d, %d)",m_currentFrame,pEntity->GetName(), static_cast<int>(pActor->GetHealth()), static_cast<int>(gstate.health));
									gstate.bHealthDifferent = true;
								}
							}
							else
								gstate.bHealthDifferent = false;
						}

						if( demo_forceGameState)
							pActor->SetHealth(gstate.health);
					}
				}
			}
			break;

		case eGE_WeaponFireModeChanged:
			{
				TItemName sel = (event.description);
				if(sel)
				{
					TItemContainer& Items = gstate.Items;
					TItemContainer::iterator iti = Items.find(sel);
					uint8 recFireModeIdx = uint8(event.value);
					if(iti != Items.end())
						iti->second.fireMode = recFireModeIdx;

					CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
					if(pActor && pActor->GetInventory())
					{
						IItem* pItem = pActor->GetInventory()->GetItemByName(sel);
						CWeapon* pWeapon;
						if(pItem && (pWeapon = (CWeapon*)(pItem->GetIWeapon())))
						{

						int fireModeIdx = pWeapon->GetCurrentFireMode();
						if(m_bLogWarning)
							{
									CheckDifference(recFireModeIdx,fireModeIdx,"TimeDemo:GameState: Frame %d - Actor %s - FIRE MODE mismatch for weapon %s (rec:%d, cur:%d)",pEntity,pItem->GetEntity() ? pItem->GetEntity()->GetName() : "(null)");
							}

							if(demo_forceGameState==2 && fireModeIdx!= recFireModeIdx)
								pWeapon->SetCurrentFireMode(recFireModeIdx);
						}
					}
				}
			}
			break;

		case eGE_WeaponReload:
			{
				const char* ammoType = event.description;
				TAmmoContainer& ammoMags = gstate.AmmoMags;
				TAmmoContainer::iterator it = ammoMags.find(ammoType);
				if(it!=ammoMags.end())
				{
					it->second -= (uint16)event.value;
				
					CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
					if(pActor)
					{
						CInventory* pInventory = (CInventory*)(pActor->GetInventory());
						if(pInventory)
						{
							{
								IEntityClass* pAmmoClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(ammoType);
								if(pAmmoClass)
								{
									if(m_bLogWarning)
										CheckDifference(it->second,pInventory->GetAmmoCount(pAmmoClass),"TimeDemo:GameState: Frame %d - Actor %s - WEAPON RELOAD, ammo count mismatch for ammo class %s (rec:%d, cur:%d)",pEntity,ammoType);
		
									if(demo_forceGameState == 2)
										pInventory->SetAmmoCount(pAmmoClass,it->second);
								}
							}
						}
					}
				}
			}
			break;

		case eGE_ItemSelected:
			{
				TItemName itemName = event.description;
				gstate.itemSelected = itemName;
				if(itemName)
				{
					if( !bRecording && (event.value > 0 || demo_forceGameState==2)) // EVENT.VALUE > 0 means initialization
					{
						CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
						if(pActor && pActor->GetInventory())
						{
							IItem* pItem = pActor->GetInventory()->GetItemByName(itemName);
							if(pItem)
								pActor->SelectItem(pItem->GetEntityId(),false);
						}
					}
				}

				if(m_bLogWarning)
				{	
					CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
					if(pActor)
					{
						IItem* pItem = pActor->GetCurrentItem();
						const char* curItemName= pItem && pItem->GetEntity() ? pItem->GetEntity()->GetName(): NULL;
						CheckDifferenceString(itemName,curItemName,"TimeDemo:GameState: Frame %d - Actor %s - SELECTED ITEM mismatch (rec:%s, cur:%s)",pEntity);
					}
				}
				break;
			}
			break;

		case eGE_ItemExchanged:
			{
				// prevent unwanted record/play mismatch error with current item during item exchanging
				// two unneeded game events are sent (selecting fists)
				m_IgnoredEvents.push_back(eGE_ItemSelected);
				m_IgnoredEvents.push_back(eGE_ItemSelected);
			}
			break;

		case eGE_ItemPickedUp:
			{
				TItemName sel = (TItemName)event.description;
//				gstate.itemSelected = sel;
				TItemContainer& Items = gstate.Items;
				TItemContainer::iterator it = Items.find(sel);
				if(it == Items.end())
				{
					Items.insert(std::make_pair(sel,SItemProperties()));
					it = Items.find(sel);
				}

				if(it != Items.end())
				{
					it->second.count++;

					CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
					if(pActor && !m_bRecording)
					{
						CInventory* pInventory = (CInventory*)(pActor->GetInventory());
						if(pInventory)
						{
							// just check if the item is the inventory
							if(m_bLogWarning && !pInventory->GetItemByName(sel))
								GameWarning("TimeDemo:GameState: Frame %d - Actor %s - Recorded PICKED UP ITEM class '%s' not found in current inventory",m_currentFrame,pEntity->GetName(),sel);

							if(demo_forceGameState == 2)
							{
								IEntity* pItemEntity = gEnv->pEntitySystem->FindEntityByName(sel);
								if(pItemEntity)
									pInventory->AddItem(pItemEntity->GetId());
								else
									GameWarning("TimeDemo:GameState: Frame %d - Actor %s - PICKED UP ITEM entity %s not found in level",m_currentFrame,pEntity->GetName(),sel);
							}
						}
					}
				}
				else if(m_bLogWarning)
				{
					if(!sel)
						sel = "(null)";
					GameWarning("TimeDemo:GameState: Frame %d - Actor %s - PICKED UP ITEM %s not found in recorded inventory",m_currentFrame,pEntity->GetName(),sel);
				}

			}
			break;

		case eGE_AmmoPickedUp:
			{
				uint16 ammoCount = (uint16)(event.value);
				TItemName sel = (TItemName)event.description;
				TAmmoContainer& Ammo = gstate.AmmoMags;

				TAmmoContainer::iterator it = Ammo.find(sel);
				if(it == Ammo.end())
					Ammo.insert(std::make_pair(sel,ammoCount));
				else
					it->second = ammoCount;

				if( !m_bRecording)
				{
					CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
					if(pActor)
					{
						CInventory* pInventory = (CInventory*)(pActor->GetInventory());
						if(pInventory)
						{
							IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(sel);
							if(m_bLogWarning)
								CheckDifference(ammoCount,pInventory->GetAmmoCount(pClass),"TimeDemo:GameState: Frame %d - Actor %s - AMMO PICKEDUP: count mismatch for ammo class %s (rec:%d, cur:%d)", pEntity,sel);

							if(demo_forceGameState == 2)
								pInventory->SetAmmoCount(pClass,ammoCount);
						}
					}
				}
			}
			break;

		case eGE_AccessoryPickedUp:
			{
				TItemName sel = (TItemName)event.description;
				//				gstate.itemSelected = sel;
				TAccessoryContainer& Accessories = gstate.Accessories;
				TAccessoryContainer::iterator it = Accessories.find(sel);
				if(it == Accessories.end())
				{
					Accessories.insert(std::make_pair(sel,1));
				}
				else
					it->second++;

				CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
				if(pActor)
				{
					CInventory* pInventory = (CInventory*)(pActor->GetInventory());
					if(pInventory)
					{
						IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(sel);
						
						if(m_bLogWarning && !pInventory->HasAccessory(pClass))
							GameWarning("TimeDemo:GameState: Frame %d - Actor %s - ACCESSORY PICKEDUP %s not found in current inventory", m_currentFrame, pEntity->GetName(),sel ? sel:"(null)");

						if(demo_forceGameState == 2 && pClass)					
							pInventory->AddAccessory(pClass);// doesn't actually add it if it's there already

					}
				}
			}
			break;

		case eGE_ItemDropped:
			{
				TItemName sel = (TItemName)event.description;
				//gstate.itemSelected = sel;
				TItemContainer& Items = gstate.Items;
				TItemContainer::iterator it = Items.find(sel);
				if(it != Items.end())
				{
					it->second.count--;
					if(it->second.count<=0)
						Items.erase(it);

					if(demo_forceGameState == 2)
					{
						CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
						if(pActor)
						{
							CInventory* pInventory = (CInventory*)(pActor->GetInventory());
							if(pInventory)
							{
								IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(sel);
								if(pClass)
								{
									EntityId itemId = pInventory->GetItemByClass(pClass);
									if(itemId)
										pInventory->RemoveItem(itemId);
								}
							}
						}
					}
				}
				else
					GameWarning("TimeDemo:GameState: Frame %d - Actor %s - ITEM DROPPED, wrong item selected (%s)",m_currentFrame,pEntity->GetName(),sel);
			}
			break;

		case eGE_AmmoCount: 
			{
				TItemContainer& Items = gstate.Items;
				TItemName itemClassDesc = event.description;
				TItemContainer::iterator it = Items.find(itemClassDesc);
				if(it != Items.end())
				{
					SItemProperties& item = it->second;
					const char* ammoClassDesc = (const char*)(event.extra);
					if(ammoClassDesc)
					{
						string szAmmoClassDesc(ammoClassDesc);
						bool bAmmoMag = IsAmmoGrenade(ammoClassDesc);
						TAmmoContainer& itemAmmo = bAmmoMag ? gstate.AmmoMags : item.Ammo;

						if(itemAmmo.find(szAmmoClassDesc)==itemAmmo.end())
							itemAmmo.insert(std::make_pair(szAmmoClassDesc,int(event.value)));
						else
							itemAmmo[szAmmoClassDesc] = (uint16)event.value;

						if(!bRecording && (m_bLogWarning || demo_forceGameState==2))
						{
							CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
							if(pActor)
							{
								CInventory* pInventory = (CInventory*)(pActor->GetInventory());
								if(pInventory)
								{
									IItem* pItem = pInventory->GetItemByName(itemClassDesc);

									if(pItem)
									{
										CWeapon* pWeapon = (CWeapon*)(pItem->GetIWeapon());
										if(pWeapon)
										{
											IEntityClass* pAmmoClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(ammoClassDesc);
											if(pAmmoClass)
											{
												if(m_bLogWarning)
												{
													int curAmmoCount = (bAmmoMag ? pInventory->GetAmmoCount(pAmmoClass) : 
														pWeapon->GetAmmoCount(pAmmoClass));
													CheckDifference( int(event.value),curAmmoCount,"TimeDemo:GameState: Frame %d - Actor %s - AMMO COUNT mismatch for ammo class %s (rec:%d, cur:%d)",pEntity,ammoClassDesc);
												}

												if(demo_forceGameState==2)
													pWeapon->SetAmmoCount(pAmmoClass,int(event.value));

											}
										}
									}
								}
							}
						}
					}
					else
						GameWarning("TimeDemo:GameState: Frame %d - Actor %s - AMMO COUNT null ammoClass descriptor",m_currentFrame,pEntity->GetName());
				}
				else
					GameWarning("TimeDemo:GameState: Frame %d - Actor %s - AMMO COUNT wrong item selected (%s)",m_currentFrame,pEntity->GetName(),itemClassDesc);
			}
			break;

		case eGE_AttachedAccessory: 
			{
				// always force attachment of accessory to the current weapon
				// kind of a workaround, the HUD weapon modifier menu is spawned during timedemo playback 
				// but it doesn't use recorded input events
				if(!bRecording)
				{
					CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
					if(pActor)
					{
						CInventory* pInventory = (CInventory*)(pActor->GetInventory());
						if(pInventory)
						{
							const char* sel = event.description;
							IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(sel);
							if(!sel)
								sel = "(null)";
							if(!pInventory->HasAccessory(pClass))
							{
								if(m_bLogWarning)
									GameWarning("TimeDemo:GameState: Frame %d - Actor %s - ATTACHED ACCESSORY %s not found in current inventory", m_currentFrame,pEntity->GetName(),sel);
							}
							else
							{
								CItem* pCurrentItem = (CItem*)(pActor->GetCurrentItem());
								if(pCurrentItem)
									pCurrentItem->SwitchAccessory(sel);
							}
						}
					}
				}
			}
			break;

		case eGE_EntityGrabbed:
			{
				if(demo_forceGameState==2)
				{
					TItemName itemName = event.description;
					if(itemName)
					{
						IEntity * pGrabbedEntity = gEnv->pEntitySystem->FindEntityByName(itemName);
						if(pGrabbedEntity)
						{
							CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
							if(pActor)
							{
								IItem* pItem = GetItemOfName(pActor,itemName);
								if(!pItem)
								{
									// it's a pickable entity, won't end up in the inventory
									//(otherwise it would be managed by eGE_ItemPickedUp)
									COffHand* pOffHand = static_cast<COffHand*>(pActor->GetWeaponByClass(CItem::sOffHandClass));
									if(pOffHand && !pOffHand->GetPreHeldEntityId())
										pOffHand->ForcePickUp(pGrabbedEntity->GetId());
								}
							}
						}
					}	
				}
			}
			break;

		default:
			break;
	}
}
Example #8
0
bool CInventory::Action(u16 cmd, u32 flags) 
{
	CActor *pActor = smart_cast<CActor*>(m_pOwner);
	
	if (pActor)
	{
		switch(cmd)
		{
			case kWPN_FIRE:
			{
				pActor->SetShotRndSeed();
			}break;
			case kWPN_ZOOM : 
			{
				pActor->SetZoomRndSeed();
			}break;
		};
	};

	if (g_pGameLevel && OnClient() && pActor) 
	{
		switch(cmd)
		{
		case kUSE:		break;
		
		case kDROP:		
			{
				if ((flags & CMD_STOP) && !IsGameTypeSingle())
				{
					PIItem tmp_item = ActiveItem();
					if (tmp_item)
					{
						tmp_item->DenyTrade();
					}
				}
				SendActionEvent	(cmd, flags);
				return			true;
			}break;

		case kWPN_NEXT:
		case kWPN_RELOAD:
		case kWPN_FIRE:
		case kWPN_FUNC:
		case kWPN_FIREMODE_NEXT:
		case kWPN_FIREMODE_PREV:
		case kWPN_ZOOM	 : 
		case kTORCH:
		case kNIGHT_VISION:
			{
				SendActionEvent(cmd, flags);
			}break;
		}
	}


	if (	ActiveItem() && 
			ActiveItem()->Action(cmd, flags)) 
											return true;
	bool b_send_event = false;
	switch(cmd) 
	{
	case kWPN_1:
	case kWPN_2:
	case kWPN_3:
	case kWPN_4:
	case kWPN_5:
	case kWPN_6:
		{
			b_send_event = true;
			if (cmd == kWPN_6 && !IsGameTypeSingle()) return false;
			
			u16 slot = u16(cmd - kWPN_1 + 1);
			if ( flags & CMD_START )
			{
				ActiveWeapon( slot );
			}
		}break;
	case kARTEFACT:
		{
		    b_send_event = true;
			if(flags&CMD_START)
			{
                if(GetActiveSlot() == ARTEFACT_SLOT &&
					ActiveItem() /*&& IsGameTypeSingle()*/)
				{
					Activate(NO_ACTIVE_SLOT);
				}else {
					Activate(ARTEFACT_SLOT);
				}
			}
		}break;
	}

	if(b_send_event && g_pGameLevel && OnClient() && pActor)
			SendActionEvent(cmd, flags);

	return false;
}
//--------------------------------------
void CThrow::DoDrop()
{
	m_pWeapon->HideItem(true);

	if (m_throwableId)
	{
		IEntity *pEntity = gEnv->pEntitySystem->GetEntity(m_throwableId);

		if (pEntity)
		{
			IPhysicalEntity *pPE = pEntity->GetPhysics();

			if (pPE && (pPE->GetType() == PE_RIGID || pPE->GetType() == PE_PARTICLE))
			{
				Vec3 hit = GetProbableHit(WEAPON_HIT_RANGE);
				Vec3 pos = GetFiringPos(hit);
				CActor *pActor = m_pWeapon->GetOwnerActor();
				IMovementController *pMC = pActor ? pActor->GetMovementController() : 0;

				if (pMC)
				{
					SMovementState info;
					pMC->GetMovementState(info);
					float speed = 2.5f;
					CPlayer *pPlayer = static_cast<CPlayer *>(m_pWeapon->GetOwnerActor());

					if(info.aimDirection.z < -0.1f)
					{
						if(pPlayer)
						{
							if(SPlayerStats *pStats = static_cast<SPlayerStats *>(pPlayer->GetActorStats()))
							{
								if(pStats->grabbedHeavyEntity)
								{
									speed = 4.0f;
								}
							}
						}
					}

					if(CheckForIntersections(pPE, info.eyeDirection))
					{
						Matrix34 newTM = pEntity->GetWorldTM();
						newTM.SetTranslation(newTM.GetTranslation() - (info.eyeDirection * 0.4f));
						pEntity->SetWorldTM(newTM, ENTITY_XFORM_POS);
						pe_action_set_velocity asv;
						asv.v = (-info.eyeDirection * speed);
						pPE->Action(&asv);
					}
					else
					{
						pe_action_set_velocity asv;
						asv.v = (info.eyeDirection * speed);
						pPE->Action(&asv);
					}

					SEntityEvent entityEvent;
					entityEvent.event = ENTITY_EVENT_PICKUP;
					entityEvent.nParam[0] = 0;

					if (pPlayer)
					{
						entityEvent.nParam[1] = pPlayer->GetEntityId();
					}

					entityEvent.fParam[0] = speed;
					pEntity->SendEvent( entityEvent );
				}
			}
		}

		if (m_throwableAction)
		{
			m_throwableAction->execute(m_pWeapon);
		}
	}
}
Example #10
0
// returns true if firing is allowed
bool CPlant::GetPlantingParameters(Vec3& pos, Vec3& dir, Vec3& vel) const
{
	CActor *pActor = m_pWeapon->GetOwnerActor();
	IMovementController *pMC = pActor?pActor->GetMovementController():0;
	SMovementState info;
	if (pMC)
		pMC->GetMovementState(info);

	if (m_pWeapon->GetStats().fp)
		pos = m_pWeapon->GetSlotHelperPos( eIGS_FirstPerson, m_plantparams.helper.c_str(), true);
	else if (pMC)
		pos = info.eyePosition+info.eyeDirection*0.25f;
	else
		pos = pActor->GetEntity()->GetWorldPos();

	if (pMC)
		dir = info.eyeDirection;
	else
		dir = pActor->GetEntity()->GetWorldRotation().GetColumn1();

	if (IPhysicalEntity *pPE=pActor->GetEntity()->GetPhysics())
	{
		pe_status_dynamics sv;
		if (pPE->GetStatus(&sv))
		{
			if (sv.v.len2()>0.01f)
			{
				float dot=sv.v.GetNormalized().Dot(dir);
				if (dot<0.0f)
					dot=0.0f;
				vel=sv.v*dot;
			}
		}
	}

	// if the ammo should be placed (claymore/mine) rather than thrown forward (c4), check if we can do so...
	if(m_plantparams.place_on_ground)
	{
		ray_hit hit;
		static const int objTypes = ent_static | ent_terrain;
		static const unsigned int flags = rwi_stop_at_pierceable|rwi_colltype_any;
		static IPhysicalEntity* pSkipEnts[10];
		int nskip = CSingle::GetSkipEntities(m_pWeapon, pSkipEnts, 10);
		int res = gEnv->pPhysicalWorld->RayWorldIntersection(pos, 2.0f * dir, objTypes, flags, &hit, 1, pSkipEnts, nskip);
		if(!res)
			return false;
		else
		{
			// check surface normal - must be close to up
			if(hit.n.z < 0.8f)
				return false;

 			// special case to stop stacking of claymores/mines (they are static so are hit by the ray)
 			if(hit.pCollider && hit.pCollider->GetiForeignData() == PHYS_FOREIGN_ID_ENTITY)
			{
				IEntity * pEntity = (IEntity*)hit.pCollider->GetForeignData(PHYS_FOREIGN_ID_ENTITY);
				if(pEntity)
				{
					if(!m_pClaymoreClass)
						m_pClaymoreClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass("claymoreexplosive");
					if(!m_pAVMineClass)
						m_pAVMineClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass("avexplosive");

					if(pEntity->GetClass() == m_pClaymoreClass || pEntity->GetClass() == m_pAVMineClass)
						return false;
				}
 			}

			// second check to see if there is another object in the way
			float hitDist = hit.dist;
			int res = gEnv->pPhysicalWorld->RayWorldIntersection(pos, 2.0f * dir, ent_all, flags, &hit, 1, pSkipEnts, nskip);
			if(res && hit.dist < hitDist-0.1f)
			{
				return false;
			}

			pos = hit.pt;
		}
	}

	return true;
}
Example #11
0
bool CInventory::DropItem(CGameObject *pObj, bool just_before_destroy, bool dont_create_shell) 
{
	CInventoryItem *pIItem				= smart_cast<CInventoryItem*>(pObj);
	VERIFY								(pIItem);
	VERIFY								(pIItem->m_pInventory);
	VERIFY								(pIItem->m_pInventory==this);
	VERIFY								(pIItem->m_ItemCurrPlace.type!=eItemPlaceUndefined);
	
	pIItem->object().processing_activate(); 
	
	switch(pIItem->CurrPlace())
	{
	case eItemPlaceBelt:{
			VERIFY(InBelt(pIItem));
			TIItemContainer::iterator temp_iter = std::find(m_belt.begin(), m_belt.end(), pIItem);
			if (temp_iter != m_belt.end())
			{
				m_belt.erase(temp_iter);
			} else
			{
				Msg("! ERROR: CInventory::Drop item not found in belt...");
			}
			pIItem->object().processing_deactivate();
		}break;
	case eItemPlaceRuck:{
			VERIFY(InRuck(pIItem));
			TIItemContainer::iterator temp_iter = std::find(m_ruck.begin(), m_ruck.end(), pIItem);
			if (temp_iter != m_ruck.end())
			{
				m_ruck.erase(temp_iter);
			} else
			{
				Msg("! ERROR: CInventory::Drop item not found in ruck...");
			}
		}break;
	case eItemPlaceSlot:{
			VERIFY			(InSlot(pIItem));
			if(m_iActiveSlot == pIItem->CurrSlot())
			{
				CActor* pActor	= smart_cast<CActor*>(m_pOwner);
				if (!pActor || pActor->g_Alive())
				{
					if (just_before_destroy)
					{
#ifdef DEBUG
						Msg("---DropItem activating slot [-1], forced, Frame[%d]", Device.dwFrame);
#endif // #ifdef DEBUG
						Activate		(NO_ACTIVE_SLOT, true);
					} else 
					{
#ifdef DEBUG
						Msg("---DropItem activating slot [-1], Frame[%d]", Device.dwFrame);
#endif // #ifdef DEBUG
						Activate		(NO_ACTIVE_SLOT);
					}
				}
			}
			m_slots[pIItem->CurrSlot()].m_pIItem = NULL;							
			pIItem->object().processing_deactivate();
		}break;
	default:
		NODEFAULT;
	};
	TIItemContainer::iterator it = std::find(m_all.begin(), m_all.end(), pIItem);
	if(it!=m_all.end())
		m_all.erase(std::find(m_all.begin(), m_all.end(), pIItem));
	else
		Msg("! CInventory::Drop item not found in inventory!!!");

	pIItem->m_pInventory = NULL;


	m_pOwner->OnItemDrop	(smart_cast<CInventoryItem*>(pObj), just_before_destroy);

	CalcTotalWeight					();
	InvalidateState					();
	m_drop_last_frame				= true;

	if( CurrentGameUI() )
	{
		CObject* pActor_owner = smart_cast<CObject*>(m_pOwner);

		if (Level().CurrentViewEntity() == pActor_owner)
			CurrentGameUI()->OnInventoryAction(pIItem, GE_OWNERSHIP_REJECT);
	};
	pObj->H_SetParent(0, dont_create_shell);
	return							true;
}
void CGameRulesMPActorAction::OnActorAction(IActor *pActor, const ActionId& actionId, int activationMode, float value)
{
	CActor *pActorImpl = static_cast<CActor *>(pActor);
	if (pActorImpl)
	{
		EntityId  pid = pActor->GetEntityId();  // player id

		CGameRules *pGameRules = g_pGame->GetGameRules();
		IGameRulesSpectatorModule *specmod = pGameRules->GetSpectatorModule();

		if (!specmod || (pActorImpl->GetSpectatorMode() <= 0))
		{
			// Not in spectator mode

			if (pActorImpl->IsDead())
			{
				// if dead 

				CRecordingSystem *crs = g_pGame->GetRecordingSystem();

				if (crs != NULL && crs->IsPlayingBack())
				{
					// Recording system playing back 
					if (actionId == g_pGame->Actions().spectate_gen_skipdeathcam && g_pGameCVars->kc_canSkip )
						crs->StopPlayback();
				}
				else if ((actionId == g_pGame->Actions().spectate_gen_spawn || actionId == g_pGame->Actions().hud_mouseclick) && activationMode == eAAM_OnPress && pActorImpl->GetSpectatorState() != CActor::eASS_SpectatorMode)
				{
					// Revive requested.
					//	This may happen immediately or not at all.

					if (IGameRulesSpawningModule* pSpawningModule=pGameRules->GetSpawningModule())
					{
						IGameRulesStateModule*  stateModule = pGameRules->GetStateModule();
						if (!stateModule || (stateModule->GetGameState() != IGameRulesStateModule::EGRS_PostGame))
						{
							CryLog("CGameRulesMPActorAction::OnActorAction() Requesting revive");
							pSpawningModule->ClRequestRevive(pActor->GetEntityId());
						}
					}
				}
				else if ((specmod != NULL && specmod->CanChangeSpectatorMode(pid)) && (((actionId == g_pGame->Actions().spectate_gen_nextmode) || (actionId == g_pGame->Actions().spectate_gen_prevmode)) && (activationMode == eAAM_OnPress)))  
				{
					// get into spectate mode
					if (!crs || !crs->IsPlayingOrQueued())
					{
						specmod->ChangeSpectatorModeBestAvailable(pActor, false);
					}
				}
			}
		}
		else
		{
			// is spectating

			int  curspecmode = pActorImpl->GetSpectatorMode();
			int  curspecstate = pActorImpl->GetSpectatorState();

			const CRecordingSystem* pRecordingSystem = g_pGame->GetRecordingSystem();
			// actions general across almost all spectator modes
			if( (curspecmode == CActor::eASM_Killer && !g_pGameCVars->g_killercam_canSkip) || (pRecordingSystem && pRecordingSystem->IsPlayingBack()) )
			{
				// Can't change mode or respawn-request, when in KillerCam mode or watching Killcam.
			}
			else if ((actionId == g_pGame->Actions().spectate_gen_spawn) && (activationMode == eAAM_OnPress) && pActorImpl->GetSpectatorState() != CActor::eASS_SpectatorMode)
			{
				IGameRulesSpawningModule *pSpawningModule = pGameRules->GetSpawningModule();
				if (pSpawningModule)
				{
					IGameRulesStateModule*  stateModule = pGameRules->GetStateModule();
					if (!stateModule || (stateModule->GetGameState() != IGameRulesStateModule::EGRS_PostGame))
					{
						CryLog("CGameRulesMPActorAction::OnActorAction() Spectating, received spectate_gen_spawn action, requesting revive");
						pSpawningModule->ClRequestRevive(pActor->GetEntityId());
					}			
				}			
			}
			else if (((actionId == g_pGame->Actions().spectate_gen_nextmode) || (actionId == g_pGame->Actions().spectate_gen_prevmode)) && (activationMode == eAAM_OnPress))
			{
				CryLog("[tlh] > changemode button pressed");
				if (specmod->CanChangeSpectatorMode(pid))
				{
					CryLog("[tlh] > can change");
					int  mode;
					EntityId  othEntId;
					mode = specmod->GetNextMode(pid, ((actionId == g_pGame->Actions().spectate_gen_nextmode) ? 1 : -1), &othEntId);
					if (mode != curspecmode)
					{
						CryLog("[tlh] > changing to mode %d with othEnt %d",mode,othEntId);
						specmod->ChangeSpectatorMode(pActor, mode, othEntId, false);
					}
				}
			}
			else
			{
				// actions specific to individual spectator modes

				if (specmod->CanChangeSpectatorMode(pid))  // "CanChangeSpectatorMode?" is essentially "CanInteractWithSpectatorMode?" - ie. we don't want to be able to do any of this on the Join Game screen
				{
					if (curspecmode == CActor::eASM_Fixed)
					{
						int  changeCam = 0;

						if (((actionId == g_pGame->Actions().spectate_cctv_nextcam) || (actionId == g_pGame->Actions().spectate_cctv_prevcam)) && (activationMode == eAAM_OnPress))
						{
							changeCam = (actionId == g_pGame->Actions().spectate_cctv_nextcam ? 1 : -1);
						}
						else if (actionId == g_pGame->Actions().spectate_cctv_changecam_xi)
						{
							if (value >= 1.f)
							{
								changeCam = 1;
							}
							else if (value <= -1.f)
							{
								changeCam = -1;
							}
						}

						if (changeCam != 0)
						{
							EntityId  locationId;

							if (changeCam > 0)
							{
								locationId = specmod->GetNextSpectatorLocation(pActorImpl);
							}
							else
							{
								locationId = specmod->GetPrevSpectatorLocation(pActorImpl);
							}

							pActorImpl->SetSpectatorFixedLocation(locationId);
						}
					}
					else if (curspecmode == CActor::eASM_Free)
					{
						;  // none
					}
					else if (curspecmode == CActor::eASM_Follow)
					{
						int  change = 0;

						const CGameActions& actions = g_pGame->Actions();

						if (((actionId == actions.spectate_3rdperson_nextteammate) || (actionId == actions.spectate_3rdperson_prevteammate)) && (activationMode == eAAM_OnPress))
						{
							change = ((actionId == actions.spectate_3rdperson_nextteammate) ? 1 : -1);
						}
						else if (actionId == actions.spectate_3rdperson_changeteammate_xi)
						{
							if (value >= 1.f)
							{
								change = 1;
							}
							else if (value <= -1.f)
							{
								change = -1;
							}
						}
						else if(actionId == actions.xi_rotateyaw && pActorImpl->CanSpectatorOrbitYaw())
						{
							pActorImpl->SetSpectatorOrbitYawSpeed(fabs(value) > 0.2f ? value : 0.f, false);
						}
						else if(actionId == actions.rotateyaw && pActorImpl->CanSpectatorOrbitYaw())
						{
							pActorImpl->SetSpectatorOrbitYawSpeed(value * g_pGameCVars->g_spectate_follow_orbitMouseSpeedMultiplier, true);
						}
						else if(actionId == actions.xi_rotatepitch && pActorImpl->CanSpectatorOrbitPitch())
						{
							float val = fabs(value) > 0.2f ? value : 0.f;
							if(val && g_pGameCVars->cl_invertController)
							{
								val = -value;
							}
							pActorImpl->SetSpectatorOrbitPitchSpeed(val, false);
						}
						else if(actionId == actions.rotatepitch && pActorImpl->CanSpectatorOrbitPitch())
						{
							float val = fabs(value) > 0.2f ? value : 0.f;
							if(val && g_pGameCVars->cl_invertMouse)
							{
								val = -val;
							}
							pActorImpl->SetSpectatorOrbitPitchSpeed(val * g_pGameCVars->g_spectate_follow_orbitMouseSpeedMultiplier, true);
						}
						else if(actionId == actions.spectate_gen_nextcamera)
						{
							pActorImpl->ChangeCurrentFollowCameraSettings(true);
						}

						if (change != 0)
						{
							if (EntityId newTargetId=specmod->GetNextSpectatorTarget(pid, change))
							{
								pActorImpl->SetSpectatorTarget(newTargetId);
							}
						}
					}
					else if (curspecmode == CActor::eASM_Killer)
					{
						;  // none
					}
				}
			}
		}

		pGameRules->ActorActionInformOnAction(actionId, activationMode, value);
	}
}
Example #13
0
void CLevel::IR_OnKeyboardPress	(int key)
{
	if(Device.dwPrecacheFrame)
		return;

#ifdef INGAME_EDITOR
	if (Device.editor() && (pInput->iGetAsyncKeyState(DIK_LALT) || pInput->iGetAsyncKeyState(DIK_RALT)))
		return;
#endif // #ifdef INGAME_EDITOR

	bool b_ui_exist = (!!CurrentGameUI());

	EGameActions _curr = get_binded_action(key);

	if(_curr==kPAUSE)
	{
		#ifdef INGAME_EDITOR
			if (Device.editor())	return;
		#endif // INGAME_EDITOR

		if (!g_block_pause && (IsGameTypeSingle() || IsDemoPlay()))
		{
#ifdef DEBUG
			if(psActorFlags.test(AF_NO_CLIP))
				Device.Pause(!Device.Paused(), TRUE, TRUE, "li_pause_key_no_clip");
			else
#endif //DEBUG
				Device.Pause(!Device.Paused(), TRUE, TRUE, "li_pause_key");
		}
		return;
	}

	if(	g_bDisableAllInput )	return;

	switch ( _curr ) 
	{
	case kSCREENSHOT:
		Render->Screenshot();
		return;
		break;

	case kCONSOLE:
		Console->Show				();
		return;
		break;

	case kQUIT: 
		{
			if(b_ui_exist && CurrentGameUI()->TopInputReceiver() )
			{
					if(CurrentGameUI()->IR_UIOnKeyboardPress(key))	return;//special case for mp and main_menu
					CurrentGameUI()->TopInputReceiver()->HideDialog();
			}else
			{
				Console->Execute("main_menu");
			}return;
		}break;
	};

	if ( !bReady || !b_ui_exist )			return;

	if ( b_ui_exist && CurrentGameUI()->IR_UIOnKeyboardPress(key)) return;

	if ( Device.Paused() && !IsDemoPlay() 
#ifdef DEBUG
		&& !psActorFlags.test(AF_NO_CLIP) 
#endif //DEBUG
		)	return;

	if ( game && game->OnKeyboardPress(get_binded_action(key)) )	return;

	if(_curr == kQUICK_SAVE && IsGameTypeSingle())
	{
		Console->Execute			("save");
		return;
	}
	if(_curr == kQUICK_LOAD && IsGameTypeSingle())
	{
#ifdef DEBUG
		FS.get_path					("$game_config$")->m_Flags.set(FS_Path::flNeedRescan, TRUE);
		FS.get_path					("$game_scripts$")->m_Flags.set(FS_Path::flNeedRescan, TRUE);
		FS.rescan_pathes			();
#endif // DEBUG
		string_path					saved_game,command;
		strconcat					(sizeof(saved_game),saved_game,Core.UserName," - ","quicksave");
		if (!CSavedGameWrapper::valid_saved_game(saved_game))
			return;

		strconcat					(sizeof(command),command,"load ",saved_game);
		Console->Execute			(command);
		return;
	}

#ifndef MASTER_GOLD
	switch (key) {
	case DIK_F7: {
		if (GameID() != eGameIDSingle) return;
		FS.get_path					("$game_config$")->m_Flags.set(FS_Path::flNeedRescan, TRUE);
		FS.get_path					("$game_scripts$")->m_Flags.set(FS_Path::flNeedRescan, TRUE);
		FS.rescan_pathes			();
		NET_Packet					net_packet;
		net_packet.w_begin			(M_RELOAD_GAME);
		Send						(net_packet,net_flags(TRUE));
		return;
	}
	case DIK_DIVIDE: {
		if (!Server)
			break;

		SetGameTimeFactor			(g_fTimeFactor);

#ifdef DEBUG
		if(!m_bEnvPaused)
			SetEnvironmentGameTimeFactor(GetEnvironmentGameTime(), g_fTimeFactor);
#else //DEBUG
		SetEnvironmentGameTimeFactor(GetEnvironmentGameTime(), g_fTimeFactor);
#endif //DEBUG
		
		break;	
	}
	case DIK_MULTIPLY: {
		if (!Server)
			break;

		SetGameTimeFactor			(1000.f);
#ifdef DEBUG
		if(!m_bEnvPaused)
			SetEnvironmentGameTimeFactor(GetEnvironmentGameTime(), 1000.f);
#else //DEBUG
		SetEnvironmentGameTimeFactor(GetEnvironmentGameTime(), 1000.f);
#endif //DEBUG
		
		break;
	}
#ifdef DEBUG
	case DIK_SUBTRACT:{
		if (!Server)
			break;
		if(m_bEnvPaused)
			SetEnvironmentGameTimeFactor(GetEnvironmentGameTime(), g_fTimeFactor);
		else
			SetEnvironmentGameTimeFactor(GetEnvironmentGameTime(), 0.00001f);

		m_bEnvPaused = !m_bEnvPaused;
		break;
	}
#endif //DEBUG
	case DIK_NUMPAD5: 
		{
			if (GameID()!=eGameIDSingle) 
			{
				Msg("For this game type Demo Record is disabled.");
///				return;
			};
			if(!pInput->iGetAsyncKeyState(DIK_LSHIFT))
			{
				Console->Hide	();
				Console->Execute("demo_record 1");
			}
		}
		break;

#ifdef DEBUG

	// Lain: added TEMP!!!
	case DIK_UP:
	{
		g_separate_factor /= 0.9f;
		break;
	}
	case DIK_DOWN:
	{
		g_separate_factor *= 0.9f;
		if ( g_separate_factor < 0.1f )
		{
			g_separate_factor = 0.1f;
		}
		break;
	}
	case DIK_LEFT:
	{
		g_separate_radius *= 0.9f;
		if ( g_separate_radius < 0 )
		{
			g_separate_radius = 0;
		}
		break;
	}
	case DIK_RIGHT:
	{
		g_separate_radius /= 0.9f;
		break;
	}

	case DIK_RETURN: {
		bDebug	= !bDebug;
		return;
	}
	case DIK_BACK:
		if (GameID() == eGameIDSingle)
			DRender->NextSceneMode();
			//HW.Caps.SceneMode			= (HW.Caps.SceneMode+1)%3;
		return;

	case DIK_F4: {
		if (pInput->iGetAsyncKeyState(DIK_LALT))
			break;

		if (pInput->iGetAsyncKeyState(DIK_RALT))
			break;

		bool bOk = false;
		u32 i=0, j, n=Objects.o_count();
		if (pCurrentEntity)
			for ( ; i<n; ++i)
				if (Objects.o_get_by_iterator(i) == pCurrentEntity)
					break;
		if (i < n) {
			j = i;
			bOk = false;
			for (++i; i <n; ++i) {
				CEntityAlive* tpEntityAlive = smart_cast<CEntityAlive*>(Objects.o_get_by_iterator(i));
				if (tpEntityAlive) {
					bOk = true;
					break;
				}
			}
			if (!bOk)
				for (i = 0; i <j; ++i) {
					CEntityAlive* tpEntityAlive = smart_cast<CEntityAlive*>(Objects.o_get_by_iterator(i));
					if (tpEntityAlive) {
						bOk = true;
						break;
					}
				}
			if (bOk) {
				CObject *tpObject = CurrentEntity();
				CObject *__I = Objects.o_get_by_iterator(i);
				CObject **I = &__I;
				
				SetEntity(*I);
				if (tpObject != *I)
				{
					CActor* pActor = smart_cast<CActor*> (tpObject);
					if (pActor)
						pActor->inventory().Items_SetCurrentEntityHud(false);
				}
				if (tpObject)
				{
					Engine.Sheduler.Unregister	(tpObject);
					Engine.Sheduler.Register	(tpObject, TRUE);
				};
				Engine.Sheduler.Unregister	(*I);
				Engine.Sheduler.Register	(*I, TRUE);

				CActor* pActor = smart_cast<CActor*> (*I);
				if (pActor)
				{
					pActor->inventory().Items_SetCurrentEntityHud(true);

					CHudItem* pHudItem = smart_cast<CHudItem*>(pActor->inventory().ActiveItem());
					if (pHudItem) 
					{
						pHudItem->OnStateSwitch(pHudItem->GetState());
					}
				}
			}
		}
		return;
	}
	// Lain: added
	case DIK_F5: 
	{
		if ( CBaseMonster* pBM = smart_cast<CBaseMonster*>(CurrentEntity()))
		{
			DBG().log_debug_info();			
		}
		break;
	}

	case MOUSE_1: {
		if (GameID() != eGameIDSingle)
			break;

		if (pInput->iGetAsyncKeyState(DIK_LALT)) {
			if (smart_cast<CActor*>(CurrentEntity()))
				try_change_current_entity	();
			else
				restore_actor				();
			return;
		}
		break;
	}
	/**/
#endif
#ifdef DEBUG
	case DIK_F9:{
//		if (!ai().get_alife())
//			break;
//		const_cast<CALifeSimulatorHeader&>(ai().alife().header()).set_state(ALife::eZoneStateSurge);
		break;
	}
		return;
//	case DIK_F10:{
//		ai().level_graph().set_dest_point();
//		ai().level_graph().build_detail_path();
//		if (!Objects.FindObjectByName("m_stalker_e0000") || !Objects.FindObjectByName("localhost/dima"))
//			return;
//		if (!m_bSynchronization) {
//			m_bSynchronization	= true;
//			ai().level_graph().set_start_point();
//			m_bSynchronization	= false;
//		}
//		luabind::functor<void>	functor;
//		ai().script_engine().functor("alife_test.set_switch_online",functor);
//		functor(0,false);
//	}
//		return;
//	case DIK_F11:
//		ai().level_graph().build_detail_path();
//		if (!Objects.FindObjectByName("m_stalker_e0000") || !Objects.FindObjectByName("localhost/dima"))
//			return;
//		if (!m_bSynchronization) {
//			m_bSynchronization	= true;
//			ai().level_graph().set_dest_point();
//			ai().level_graph().select_cover_point();
//			m_bSynchronization	= false;
//		}
//		return;
#endif // DEBUG
	}
#endif // MASTER_GOLD

	if (bindConsoleCmds.execute(key))
		return;

	if (CURRENT_ENTITY())		
	{
		IInputReceiver*		IR	= smart_cast<IInputReceiver*>	(smart_cast<CGameObject*>(CURRENT_ENTITY()));
		if (IR)				IR->IR_OnKeyboardPress(get_binded_action(key));
	}


	#ifdef _DEBUG
		CObject *obj = Level().Objects.FindObjectByName("monster");
		if (obj) {
			CBaseMonster *monster = smart_cast<CBaseMonster *>(obj);
			if (monster) 
				monster->debug_on_key(key);
		}
	#endif
}
void CCustomReactionFunctions::FallAndPlay_Reaction(CActor& actor, const SReactionParams& reactionParams, const HitInfo& hitInfo)
{
	actor.Fall();
	DeathImpulse_Reaction(actor, reactionParams, hitInfo);
}
Example #15
0
void CLTagSingle::NetShootEx(const Vec3 &pos, const Vec3 &dir, const Vec3 &vel, const Vec3 &hit, float extra, int predictionHandle)
{
	IEntityClass* ammo = m_fireParams->fireparams.ammo_type_class;
	int weaponAmmoCount = m_pWeapon->GetAmmoCount(ammo);
	int ammoCount = weaponAmmoCount;

	CActor* pOwnerActor = m_pWeapon->GetOwnerActor();
	bool playerIsShooter = pOwnerActor ? pOwnerActor->IsPlayer() : false;

	if (IsProceduralRecoilEnabled() && pOwnerActor)
	{
		pOwnerActor->ProceduralRecoil(m_fireParams->proceduralRecoilParams.duration, m_fireParams->proceduralRecoilParams.strength, m_fireParams->proceduralRecoilParams.kickIn, m_fireParams->proceduralRecoilParams.arms);
	}

	m_pWeapon->PlayAction(GetFragmentIds().fire, 0, false, CItem::eIPAF_Default);
	
	CProjectile *pAmmo = m_pWeapon->SpawnAmmo(m_fireParams->fireparams.spawn_ammo_class, true);
	CLTAGGrenade* pGrenade = static_cast<CLTAGGrenade*>(pAmmo);

	if (pGrenade)
	{
		CRY_ASSERT_MESSAGE(m_fireParams->fireparams.hitTypeId, string().Format("Invalid hit type '%s' in fire params for '%s'", m_fireParams->fireparams.hit_type.c_str(), m_pWeapon->GetEntity()->GetName()));
		CRY_ASSERT_MESSAGE(m_fireParams->fireparams.hitTypeId == g_pGame->GetGameRules()->GetHitTypeId(m_fireParams->fireparams.hit_type.c_str()), "Sanity Check Failed: Stored hit type id does not match the type string, possibly CacheResources wasn't called on this weapon type");

		pGrenade->SetParams(CProjectile::SProjectileDesc(
			m_pWeapon->GetOwnerId(), m_pWeapon->GetHostId(), m_pWeapon->GetEntityId(), 
			m_fireParams->fireparams.damage, 0.f, 0.f, 0.f, m_fireParams->fireparams.hitTypeId,
			m_fireParams->fireparams.bullet_pierceability_modifier, m_pWeapon->IsZoomed()));
		// this must be done after owner is set
		pGrenade->InitWithAI();
		pGrenade->SetDestination(m_pWeapon->GetDestination());
		pGrenade->SetGrenadeType(m_grenadeType);
		pGrenade->Launch(pos, dir, vel, m_speed_scale);

		m_projectileId = pGrenade->GetEntity()->GetId();
	}

	if (m_pWeapon->IsServer())
	{
		const char *ammoName = ammo != NULL ? ammo->GetName() : NULL;
		g_pGame->GetIGameFramework()->GetIGameplayRecorder()->Event(m_pWeapon->GetOwner(), GameplayEvent(eGE_WeaponShot, ammoName, 1, (void *)(EXPAND_PTR)m_pWeapon->GetEntityId()));
	
#ifdef SERVER_CHECKS
		if (pOwnerActor && m_pWeapon->IsServerSpawn(ammo))
		{
			int inventoryAmmoCount = m_pWeapon->GetInventoryAmmoCount(ammo);

			int totalAmmoCount=weaponAmmoCount+inventoryAmmoCount; // this needed seeing as how this seems to use weaponAmmo or inventoryAmmo but NOT both?
			if (totalAmmoCount <= 0)
			{
				g_pGame->GetAntiCheatManager()->FlagActivity(eCT_ServerSpawnedAmmoUsed, pOwnerActor->GetChannelId());
			}
		}
#endif
	}

	m_muzzleEffect.Shoot(this, hit, m_barrelId);
	RecoilImpulse(pos, dir);

	m_fired = true;
	m_next_shot = 0.0f;

	ammoCount--;

	if(ammoCount<0)
		ammoCount = 0;

	if (m_pWeapon->IsServer())
	{
		int clipSize = GetClipSize();
		if (clipSize != -1)
		{
			if (clipSize != 0)
				m_pWeapon->SetAmmoCount(ammo, ammoCount);
			else
				m_pWeapon->SetInventoryAmmoCount(ammo, ammoCount);
		}
	}

	OnShoot(m_pWeapon->GetOwnerId(), pAmmo?pAmmo->GetEntity()->GetId():0, ammo, pos, dir, vel);

	if(playerIsShooter)
	{
		const SThermalVisionParams& thermalParams = m_fireParams->thermalVisionParams;
		m_pWeapon->AddShootHeatPulse(pOwnerActor, thermalParams.weapon_shootHeatPulse, thermalParams.weapon_shootHeatPulseTime,
			thermalParams.owner_shootHeatPulse, thermalParams.owner_shootHeatPulseTime);
	}

	if (OutOfAmmo())
		m_pWeapon->OnOutOfAmmo(ammo);

	if (pAmmo && predictionHandle && pOwnerActor)
	{
		pAmmo->GetGameObject()->RegisterAsValidated(pOwnerActor->GetGameObject(), predictionHandle);
		pAmmo->GetGameObject()->BindToNetwork();
	}
	else if (pAmmo && pAmmo->IsPredicted() && gEnv->IsClient() && gEnv->bServer && pOwnerActor && pOwnerActor->IsClient())
	{
		pAmmo->GetGameObject()->BindToNetwork();
	}

	m_pWeapon->RequireUpdate(eIUS_FireMode);
}
Example #16
0
int CScriptBind_Weapon::AttachAccessoryPlaceHolder(IFunctionHandler *pH, SmartScriptTable accessory, bool attach)
{
	CWeapon *pWeapon = GetWeapon(pH);
	if (!pWeapon)
		return pH->EndFunction();

	const char *accessoryName;
	accessory->GetValue("class", accessoryName);
	ScriptHandle id;
	accessory->GetValue("id", id);
	
	EntityId entId = (EntityId)id.n;
	//CryLogAlways("id = %d", entId);
	IEntity *attachment = gEnv->pEntitySystem->GetEntity(entId);
	

	if (accessoryName)
	{
		//CryLogAlways("got name: %s", accessoryName);
		if (pWeapon->GetAccessoryPlaceHolder(accessoryName))
		{
			//CryLogAlways("found accessory place holder");
			pWeapon->AttachAccessoryPlaceHolder(accessoryName, attach);
		}
		else
		{
			//CryLogAlways("accessory place holder not found");
			CActor *pActor = pWeapon->GetOwnerActor();
			IEntity *wep = pWeapon->GetEntity();
			//IGameObject *pGameObject = pWeapon->GetOwnerActor()->GetGameObject();
			IInventory *pInventory = pActor->GetInventory();
			if (pInventory)
			{
				//CryLogAlways("found inventory");
				if (attachment)
				{
					if (pInventory->FindItem(entId) != -1)
					{
						//CryLogAlways("found attachment in inventory already...");
					}
					else
					{
						//CryLogAlways("attachment not found in inventory, adding...");
					}
					//CryLogAlways("found attachment");
					
					
					//attachment->DetachThis(0);
					//attachment->SetParentId(0);
					//CItem *t = (CItem *)attachment;
					//t->SetParentId(0);
					//pWeapon->GetEntity()->AttachChild(attachment, false)
					pInventory->AddItem(attachment->GetId());
					//for (int i = 0; i < wep->GetChildCount(); i++)
					//{
					//	IEntity *cur = wep->GetChild(i);
					//	CryLogAlways("none of these should be %s", attachment->GetName());
					//	CryLogAlways(" %s", cur->GetName());
					//}
					pWeapon->AttachAccessoryPlaceHolder(accessoryName, attach);
					pInventory->RemoveItem(attachment->GetId());
					
				}
				else
				{
					//CryLogAlways("!attachment");
				}
			}
		}
		
	}
	return pH->EndFunction();
}
//------------------------------------------------------------------------
void CRapid::Update(float frameTime, uint32 frameId)
{
	FUNCTION_PROFILER( GetISystem(), PROFILE_GAME );

	PlayStopRapidFireIfNeeded();

	BaseClass::Update(frameTime, frameId);

	if (m_speed <= 0.0f && m_acceleration < 0.0001f)
	{
		FinishDeceleration();
		return;
	}

	CActor* pOwnerActor = m_pWeapon->GetOwnerActor();
	const bool isOwnerClient = pOwnerActor ? pOwnerActor->IsClient() : false;
	const bool isOwnerPlayer = pOwnerActor ? pOwnerActor->IsPlayer() : false;

	m_pWeapon->RequireUpdate(eIUS_FireMode);

	m_speed = m_speed + m_acceleration*frameTime;

	if (m_speed > m_fireParams->rapidparams.max_speed)
	{
		m_speed = m_fireParams->rapidparams.max_speed;
		m_rapidFlags &= ~eRapidFlag_accelerating;
	}

	if ((m_speed >= m_fireParams->rapidparams.min_speed) && !(m_rapidFlags & eRapidFlag_decelerating))
	{
		float dt = 1.0f;
		if (cry_fabsf(m_speed)>0.001f && cry_fabsf(m_fireParams->rapidparams.max_speed)>0.001f)
		{
			dt = m_speed * (float)__fres(m_fireParams->rapidparams.max_speed);
		}
		CRY_ASSERT(m_fireParams->fireparams.rate > 0);
		
		m_next_shot_dt = 60.0f* (float)__fres((m_fireParams->fireparams.rate*dt));

		if (CanFire(false))
		{
			if (!OutOfAmmo())
			{
				const bool firing = (m_rapidFlags & eRapidFlag_netShooting) || Shoot(true, m_fireParams->fireparams.autoReload);
				Firing(firing);
			}
			else
			{
				StopFire();
			}
		}
	}
	else if (m_firing)
	{
		StopFire();
		if (OutOfAmmo() && isOwnerPlayer)
		{
			m_pWeapon->Reload();
		}
	}

	if ((m_speed < m_fireParams->rapidparams.min_speed) && (m_acceleration < 0.0f) && !(m_rapidFlags & eRapidFlag_decelerating))
		Accelerate(m_fireParams->rapidparams.deceleration);

	UpdateRotation(frameTime);
	UpdateFiring(pOwnerActor, isOwnerClient, isOwnerPlayer, frameTime);
}
Example #18
0
bool CShotgun::Shoot(bool resetAnimation, bool autoreload/* =true */, bool noSound /* =false */)
{
	IEntityClass *ammo = m_pShared->fireparams.ammo_type_class;
	int ammoCount = m_pWeapon->GetAmmoCount(ammo);

	if(m_pShared->fireparams.clip_size==0)
		ammoCount = m_pWeapon->GetInventoryAmmoCount(ammo);

	CActor *pActor = m_pWeapon->GetOwnerActor();
	bool playerIsShooter = pActor?pActor->IsPlayer():false;

	if(!CanFire(true))
	{
		if((ammoCount <= 0) && (!m_reloading))
		{
			m_pWeapon->PlayAction(m_pShared->actions.empty_clip);
			//Auto reload
			m_pWeapon->Reload();
		}

		return false;
	}
	else if(m_pWeapon->IsWeaponLowered())
	{
		m_pWeapon->PlayAction(m_pShared->actions.null_fire);
		return false;
	}

	if(m_reloading)
	{
		if(m_pWeapon->IsBusy())
			m_pWeapon->SetBusy(false);

		if(CanFire(true) && !m_break_reload)
		{
			m_break_reload = true;
			m_pWeapon->RequestCancelReload();
		}

		return false;
	}

	// Aim assistance
	m_pWeapon->AssistAiming();

	const char *action = m_pShared->actions.fire_cock.c_str();

	if(ammoCount == 1 || (m_pShared->fireparams.no_cock && m_pWeapon->IsZoomed()))
		action = m_pShared->actions.fire.c_str();

	m_pWeapon->PlayAction(action, 0, false, CItem::eIPAF_Default|CItem::eIPAF_RestartAnimation|CItem::eIPAF_CleanBlending);

	Vec3 hit = GetProbableHit(WEAPON_HIT_RANGE);
	Vec3 pos = GetFiringPos(hit);
	Vec3 fdir = ApplySpread(GetFiringDir(hit, pos), GetSpread());
	Vec3 vel = GetFiringVelocity(fdir);
	Vec3 dir;

	CheckNearMisses(hit, pos, fdir, WEAPON_HIT_RANGE, m_pShared->shotgunparams.spread);

	bool serverSpawn = m_pWeapon->IsServerSpawn(ammo);

	// SHOT HERE
	for(int i = 0; i < m_pShared->shotgunparams.pellets; i++)
	{
		CProjectile *pAmmo = m_pWeapon->SpawnAmmo(ammo, false);

		if(pAmmo)
		{
			dir = ApplySpread(fdir, m_pShared->shotgunparams.spread);
			int hitTypeId = g_pGame->GetGameRules()->GetHitTypeId(m_pShared->fireparams.hit_type.c_str());

			pAmmo->SetParams(m_pWeapon->GetOwnerId(), m_pWeapon->GetHostId(), m_pWeapon->GetEntityId(), m_pShared->shotgunparams.pelletdamage, hitTypeId, playerIsShooter?m_pShared->fireparams.damage_drop_per_meter:0.0f, m_pShared->fireparams.damage_drop_min_distance);
			pAmmo->SetDestination(m_pWeapon->GetDestination());
			pAmmo->Launch(pos, dir, vel);

			if((!m_pShared->tracerparams.geometry.empty() || !m_pShared->tracerparams.effect.empty()) && (ammoCount==GetClipSize() || (ammoCount%m_pShared->tracerparams.frequency==0)))
			{
				EmitTracer(pos,hit,false);
			}

			m_projectileId = pAmmo->GetEntity()->GetId();
		}
	}

	m_pWeapon->OnShoot(m_pWeapon->GetOwnerId(), 0, ammo, pos, dir, vel);

	if(m_pWeapon->IsServer())
	{
		const char *ammoName = ammo != NULL ? ammo->GetName() : NULL;
		g_pGame->GetIGameFramework()->GetIGameplayRecorder()->Event(m_pWeapon->GetOwner(), GameplayEvent(eGE_WeaponShot, ammoName, m_pShared->shotgunparams.pellets, (void *)m_pWeapon->GetEntityId()));
	}

	MuzzleFlashEffect(true);
	RejectEffect();

	m_fired = true;
	m_next_shot += m_next_shot_dt;
	m_zoomtimeout = m_next_shot + 0.5f;
	ammoCount--;

	if(playerIsShooter)
	{
		if(pActor->InZeroG())
		{
			IEntityPhysicalProxy *pPhysicsProxy = (IEntityPhysicalProxy *)pActor->GetEntity()->GetProxy(ENTITY_PROXY_PHYSICS);
			SMovementState ms;
			pActor->GetMovementController()->GetMovementState(ms);
			CPlayer *plr = (CPlayer *)pActor;

			if(m_recoilparams.back_impulse > 0.0f)
			{
				Vec3 impulseDir = ms.aimDirection * -1.0f;
				Vec3 impulsePos = ms.pos;
				float impulse = m_recoilparams.back_impulse;
				pPhysicsProxy->AddImpulse(-1, impulsePos, impulseDir * impulse * 100.0f, true, 1.0f);
			}

			if(m_recoilparams.angular_impulse > 0.0f)
			{
				float impulse = m_recoilparams.angular_impulse;
				pActor->AddAngularImpulse(Ang3(0,impulse,0), 1.0f);
			}
		}

		if(pActor->IsClient())
			if(gEnv->pInput)
				gEnv->pInput->ForceFeedbackEvent(SFFOutputEvent(eDI_XI, eFF_Rumble_Basic, 0.15f, 0.0f, fabsf(m_recoilparams.back_impulse)*3.0f));
	}

	if(m_pShared->fireparams.clip_size != -1)
	{
		if(m_pShared->fireparams.clip_size!=0)
			m_pWeapon->SetAmmoCount(ammo, ammoCount);
		else
			m_pWeapon->SetInventoryAmmoCount(ammo, ammoCount);
	}

	if((ammoCount<1) && !m_pShared->fireparams.slider_layer.empty())
	{
		const char *slider_back_layer = m_pShared->fireparams.slider_layer.c_str();
		m_pWeapon->PlayLayer(slider_back_layer, CItem::eIPAF_Default|CItem::eIPAF_NoBlend);
	}

	if(OutOfAmmo())
	{
		m_pWeapon->OnOutOfAmmo(ammo);

		if(autoreload)
		{
			m_pWeapon->GetScheduler()->TimerAction(m_pWeapon->GetCurrentAnimationTime(eIGS_FirstPerson), CSchedulerAction<ScheduleReload>::Create(m_pWeapon), false);
		}
	}

	m_pWeapon->RequestShoot(ammo, pos, dir, vel, hit, 1.0f, 0, false);

	return true;
}
Example #19
0
float CGameStateRecorder::RenderInfo(float y, bool bRecording)
{
	float retY = 0;

	IRenderer *pRenderer = gEnv->pRenderer;

	if (bRecording)
	{
		float fColor[4] = {1,0,0,1};
		pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false," Recording game state");
		retY +=15;
	}
	else 
	{
		const float xp = 300;
		const float xr = 400;
		const float xri = 600;

		float fColor[4] = {0,1,0,1};
		float fColorWarning[4] = {1,1,0,1};

		const char* actorName = m_demo_actorInfo->GetString();
		CActor *pActor = GetActorOfName(actorName);
		if(pActor)
		{
			pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false," Game state - Actor: %s --------------------------------------------------",pActor->GetEntity()? pActor->GetEntity()->GetName(): "(no entity)");
			retY +=15;

			if(m_itSingleActorGameState != m_GameStates.end() && pActor->GetEntity() && m_itSingleActorGameState->first == pActor->GetEntity()->GetId())
			{
				ICVar *pVar = gEnv->pConsole->GetCVar( "demo_force_game_state" );
				if(pVar)
				{
					int demo_forceGameState = pVar->GetIVal();
					if(demo_forceGameState)
					{
						pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false,demo_forceGameState==1 ? 
							" Override mode = (health, suit energy)" : " Override mode = (all)");
						retY +=15;
					}
				}

				pRenderer->Draw2dLabel( xp,y+retY, 1.3f, fColor,false,"Current");
				pRenderer->Draw2dLabel( xr,y+retY, 1.3f, fColor,false,"Recorded");
				retY +=15;

				SActorGameState& gstate = m_itSingleActorGameState->second;
				float recordedHealth = (float)gstate.health;
				float health = (float)pActor->GetHealth();
				bool bError = CHECK_MISMATCH(health, recordedHealth,10);

				pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false," Health:");
				pRenderer->Draw2dLabel( xp,y+retY, 1.3f, bError? fColorWarning : fColor, false,"%d",(int)health);
				pRenderer->Draw2dLabel( xr,y+retY, 1.3f, bError? fColorWarning : fColor, false,"%d",(int)recordedHealth);
				retY +=15;
				
				// items
				pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false," Inventory ---------------------------------------------------------------------------------------");
				retY +=15;
				pRenderer->Draw2dLabel( xp,y+retY, 1.3f, fColor,false,"Current");
				pRenderer->Draw2dLabel( xri,y+retY, 1.3f, fColor,false,"Recorded");
				retY +=15;

				CInventory *pInventory = (CInventory*)(pActor->GetInventory());
				if(pInventory)
				{
					int nInvItems = pInventory->GetCount();
						
					TItemContainer& Items = gstate.Items;
					int nRecItems = Items.size();
					int maxItems = max(nRecItems,nInvItems);

					int i=0;
					EntityId curSelectedId = pActor->GetCurrentItemId();
					TItemName curSelClass = GetItemName(curSelectedId);
					bool bSelectedError = !equal_strings(gstate.itemSelected,curSelClass);

					for(; i< nInvItems; i++)
					{
						IItem *pItem = g_pGame->GetIGameFramework()->GetIItemSystem()->GetItem(pInventory->GetItem(i));
						if(pItem)	
						{
							TItemName szItemName = GetItemName(pItem->GetEntityId());

							TItemContainer::iterator it = Items.find(szItemName);
							bError = it==Items.end();
							pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false," %2d)",i+1);

							EntityId curId = pItem->GetEntityId();
							TItemName curClass = GetItemName(curId);
							if(equal_strings(curClass,curSelClass) )
								pRenderer->Draw2dLabel( xp-16,y+retY, 1.3f,bSelectedError ? fColorWarning:fColor, false, "[]");

							if(equal_strings(szItemName, gstate.itemSelected))
								pRenderer->Draw2dLabel( xri-16,y+retY, 1.3f,bSelectedError ? fColorWarning:fColor, false, "[]");

							char itemName[32];
							const char* originalItemName = pItem->GetEntity() ? pItem->GetEntity()->GetName():"(null)";
							int length = strlen(originalItemName);
							length = min(length,31);
							strncpy(itemName,originalItemName,length);
							itemName[length]=0;
							pRenderer->Draw2dLabel( 1,y+retY, 1.3f, bError? fColorWarning : fColor, false,"     %s",itemName);

							if(bError)
								pRenderer->Draw2dLabel( xp,y+retY, 1.3f, fColorWarning, false, "Missing");
							else
							{
								SItemProperties& recItem = it->second;
								CWeapon *pWeapon = (CWeapon*)(pItem->GetIWeapon());

								IEntityClass* pItemClass = pItem->GetEntity()->GetClass();
								if(pItemClass && !strcmpi(pItemClass->GetName(),"binoculars"))
									pWeapon = NULL; // no fire mode or ammo recorded for binocular (which is a weapon)

								if(pWeapon)
								{
									int idx = 0;
									// ammo
									float xa = 0;
									for(SWeaponAmmo weaponAmmo = pWeapon->GetFirstAmmo(); weaponAmmo.pAmmoClass ; weaponAmmo = pWeapon->GetNextAmmo())
									{
										int ammoCount = weaponAmmo.count;
										const char* ammoClass;
										if(weaponAmmo.pAmmoClass && (ammoClass = weaponAmmo.pAmmoClass->GetName()))
										{
											TAmmoContainer::iterator it = recItem.Ammo.find(ammoClass);
											if(it!=recItem.Ammo.end())
											{
												int recAmmoCount = recItem.Ammo[ammoClass];
												bool bError2 = ammoCount!=recAmmoCount;
												pRenderer->Draw2dLabel( xp+xa,y+retY, 1.3f, bError2? fColorWarning : fColor, false,"Am%d:%d",idx,ammoCount);
												pRenderer->Draw2dLabel( xri+xa,y+retY, 1.3f, bError2? fColorWarning : fColor, false,"Am%d:%d",idx,recAmmoCount);
												xa += 50;
												++idx;
												if(idx%5 ==0)
												{
													xa=0;
													retY+=15;
												}
											}
										}
									}

									// current fire mode
									int curFireModeIdx = pWeapon->GetCurrentFireMode();
									int recFireModeIdx = recItem.fireMode;
									bool bError3 = curFireModeIdx!= recFireModeIdx;
									pRenderer->Draw2dLabel( xp+xa,y+retY, 1.3f, bError3? fColorWarning : fColor, false,"FMode:%d",curFireModeIdx);
									pRenderer->Draw2dLabel( xri+xa,y+retY, 1.3f, bError3? fColorWarning : fColor, false,"FMode:%d",recFireModeIdx);
								}
								else
								{
									pRenderer->Draw2dLabel( xp,y+retY, 1.3f, fColor, false, "Ok");
								}
							}

						}
						retY +=15;
					}

					/// Accessories

					int nInvAccessories = pInventory->GetAccessoryCount();

					TAccessoryContainer& Accessories = gstate.Accessories;
					int nRecAccessories = Accessories.size();
					if(nRecAccessories)
					{
						pRenderer->Draw2dLabel( 1,y+retY, 1.3f, bError? fColorWarning : fColor, false," Accessories");
						retY +=15;
					}

					for(int j=0 ; j< nInvAccessories; j++,i++)
					{
						const char* accessory = pInventory->GetAccessory(j);
						if(accessory && strlen(accessory))	
						{

							IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(accessory);
							if(pClass)
							{
								TItemName szItemName = pClass->GetName();
								TAccessoryContainer::iterator it = Accessories.find(szItemName);
								bError = it==Accessories.end();
								pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false," %2d)",i+1);

								char itemName[32];
								int length = strlen(accessory);
								length = min(length,31);
								strncpy(itemName,accessory,length);
								itemName[length]=0;
								pRenderer->Draw2dLabel( 1,y+retY, 1.3f, bError? fColorWarning : fColor, false,"     %s",itemName);

								if(bError)
									pRenderer->Draw2dLabel( xp,y+retY, 1.3f, fColorWarning, false, "Missing");
								else
									pRenderer->Draw2dLabel( xp,y+retY, 1.3f, fColor, false, "Ok");

								retY +=15;
							}
						}

					}
					/// Ammo Mags
					TAmmoContainer& Ammo = gstate.AmmoMags;
					int nRecAmmo = Ammo.size();
					int nInvAmmo = pInventory->GetAmmoPackCount();
					if(nInvAmmo)
					{
						pRenderer->Draw2dLabel( 1,y+retY, 1.3f, bError? fColorWarning : fColor, false," Ammo Packs");
						retY +=15;
					}

					pInventory->AmmoIteratorFirst();
					for(int j=0 ; !pInventory->AmmoIteratorEnd(); j++, pInventory->AmmoIteratorNext())
					{
						TAmmoContainer& Mags = gstate.AmmoMags;
						const IEntityClass* pAmmoClass = pInventory->AmmoIteratorGetClass();
						if(pAmmoClass)
						{
							int invAmmoCount = pInventory->AmmoIteratorGetCount();
							const char* ammoClassName = pAmmoClass->GetName();
							bool bNotFound = Mags.find(ammoClassName) == Mags.end();
							int recAmmoCount = bNotFound ? 0 :Mags[ammoClassName];
							bool bError =  bNotFound || invAmmoCount!= recAmmoCount;

							pRenderer->Draw2dLabel( 1,y+retY, 1.3f, bError? fColorWarning : fColor, false,"  %s:",ammoClassName);
							pRenderer->Draw2dLabel( xp,y+retY, 1.3f, bError? fColorWarning : fColor, false,"%d",invAmmoCount);
							if(bNotFound)
								pRenderer->Draw2dLabel( xr,y+retY, 1.3f, fColorWarning, false,"NotRecd");
							else
								pRenderer->Draw2dLabel( xr,y+retY, 1.3f, bError? fColorWarning : fColor, false,"%d",recAmmoCount);
							retY +=15;

						}
					}
				}
			}
			else // m_itSingleActorGameState != m_GameStates.end()
			{
				pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false, "<<Not Recorded>>");
				retY +=15;
			}
		}
		else // pActor
		{
			pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false, "<<Actor %s not in the map>>",actorName ? actorName:"(no name)");
			retY +=15;		
		}

	}
	return retY;
}
Example #20
0
//------------------------------------------------------------------------
void CShotgun::NetShootEx(const Vec3 &pos, const Vec3 &dir, const Vec3 &vel, const Vec3 &hit, float extra, int ph)
{
	assert(0 == ph);

	IEntityClass *ammo = m_pShared->fireparams.ammo_type_class;
	const char *action = m_pShared->actions.fire_cock.c_str();

	CActor *pActor = m_pWeapon->GetOwnerActor();
	bool playerIsShooter = pActor?pActor->IsPlayer():false;

	int ammoCount = m_pWeapon->GetAmmoCount(ammo);

	if(m_pShared->fireparams.clip_size==0)
		ammoCount = m_pWeapon->GetInventoryAmmoCount(ammo);

	if(ammoCount == 1)
		action = m_pShared->actions.fire.c_str();

	m_pWeapon->ResetAnimation();
	m_pWeapon->PlayAction(action, 0, false, CItem::eIPAF_Default|CItem::eIPAF_NoBlend);

	Vec3 pdir;

	// SHOT HERE
	for(int i = 0; i < m_pShared->shotgunparams.pellets; i++)
	{
		CProjectile *pAmmo = m_pWeapon->SpawnAmmo(ammo, true);

		if(pAmmo)
		{
			pdir = ApplySpread(dir, m_pShared->shotgunparams.spread);
			int hitTypeId = g_pGame->GetGameRules()->GetHitTypeId(m_pShared->fireparams.hit_type.c_str());

			pAmmo->SetParams(m_pWeapon->GetOwnerId(), m_pWeapon->GetHostId(), m_pWeapon->GetEntityId(), m_pShared->shotgunparams.pelletdamage, hitTypeId, playerIsShooter?m_pShared->fireparams.damage_drop_per_meter:0.0f, m_pShared->fireparams.damage_drop_min_distance);
			pAmmo->SetDestination(m_pWeapon->GetDestination());
			pAmmo->SetRemote(true);
			pAmmo->Launch(pos, pdir, vel);

			bool emit = false;

			if(m_pWeapon->GetStats().fp)
				emit = (!m_pShared->tracerparams.geometryFP.empty() || !m_pShared->tracerparams.effectFP.empty()) && (ammoCount==GetClipSize() || (ammoCount%m_pShared->tracerparams.frequency==0));
			else
				emit = (!m_pShared->tracerparams.geometry.empty() || !m_pShared->tracerparams.effect.empty()) && (ammoCount==GetClipSize() || (ammoCount%m_pShared->tracerparams.frequency==0));

			if(emit)
				EmitTracer(pos,hit,false);

			m_projectileId = pAmmo->GetEntity()->GetId();
		}
	}

	m_pWeapon->OnShoot(m_pWeapon->GetOwnerId(), 0, ammo, pos, dir, vel);

	if(m_pWeapon->IsServer())
	{
		const char *ammoName = ammo != NULL ? ammo->GetName() : NULL;
		g_pGame->GetIGameFramework()->GetIGameplayRecorder()->Event(m_pWeapon->GetOwner(), GameplayEvent(eGE_WeaponShot, ammoName, m_pShared->shotgunparams.pellets, (void *)m_pWeapon->GetEntityId()));
	}

	MuzzleFlashEffect(true);
	RejectEffect();

	m_fired = true;
	m_next_shot = 0.0f;

	ammoCount--;

	if(m_pWeapon->IsServer())
	{
		if(m_pShared->fireparams.clip_size != -1)
		{
			if(m_pShared->fireparams.clip_size!=0)
				m_pWeapon->SetAmmoCount(ammo, ammoCount);
			else
				m_pWeapon->SetInventoryAmmoCount(ammo, ammoCount);
		}
	}

	if((ammoCount<1) && !m_pShared->fireparams.slider_layer.empty())
	{
		const char *slider_back_layer = m_pShared->fireparams.slider_layer.c_str();
		m_pWeapon->PlayLayer(slider_back_layer, CItem::eIPAF_Default|CItem::eIPAF_NoBlend);
	}

	m_pWeapon->RequireUpdate(eIUS_FireMode);
}
Example #21
0
void CGameStateRecorder::OnGameplayEvent(IEntity *pEntity, const GameplayEvent &event)
{
	EntityId id;
	if(!pEntity || !(id = pEntity->GetId()))
	{
		GameWarning("TimeDemo:GameState::OnGamePlayEvent: Entity not found");
		return;
	}
	CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
	if(!pActor)
	{
		GameWarning("TimeDemo:GameState::OnGamePlayEvent: Entity %s has no actor", pEntity->GetName());
		return;
	}

	GameplayEvent  event2 = event;
	event2.extra = 0;// event2 is the forwarded event, extra either will be not used by the listener or re-set as a string
	uint8 eType = event.event;

	bool bPlayer = (pActor->IsPlayer() && m_mode);
	if(bPlayer || m_mode==GPM_AllActors)
	{
		//items
		switch(eType)
		{
			case eGE_ItemPickedUp:
				{
					CheckInventory(pActor,0);//,*m_pRecordGameEventFtor);
				}
				break;

			case eGE_ItemDropped:
				{
					TItemName itemName = GetItemName(EntityId(event.extra));
					if(!itemName ) //if(itemIdx < 0)
						break;
					event2.description = itemName;
					SendGamePlayEvent(pEntity,event2);
					IEntity* pItemEntity = gEnv->pEntitySystem->FindEntityByName(itemName);
					if(!pItemEntity)
						break;
					IItem* pItem = g_pGame->GetIGameFramework()->GetIItemSystem()->GetItem(pItemEntity->GetId());
					if(!pItem)
						break;

					IEntityClass* pItemClass = pItem->GetEntity()->GetClass();
					if(pItemClass && !strcmpi(pItemClass->GetName(),"SOCOM"))
					{
						IItem* pCurrentItem = pActor->GetCurrentItem();
						if(pCurrentItem)
						{
							IEntityClass* pCurrentItemClass = pCurrentItem->GetEntity()->GetClass();
							if(pCurrentItemClass && !strcmpi(pCurrentItemClass->GetName(),"SOCOM"))
							{
								GameplayEvent event3;
								event3.event = eGE_ItemSelected;
								TItemName itemName = GetItemName(pCurrentItem->GetEntity()->GetId());
								if(!itemName)
									break;
								event3.value = 0;
								event3.description = (const char*)itemName;
								SendGamePlayEvent(pEntity,event3);
							}
						}
					}
				}
				break;

			case eGE_WeaponFireModeChanged:
				{
					TItemName itemIdx = GetItemName(EntityId(event.extra));
					if(!itemIdx)//if(itemIdx < 0)
						break;
					event2.description = (const char*)itemIdx;
					SendGamePlayEvent(pEntity,event2);
				}
				break;

			case eGE_ItemSelected:
				{
					EntityId itemId = EntityId(event.extra);
					TItemName itemIdx = GetItemName(itemId);
					if(itemId && !itemIdx)
						break;
					event2.value = 0;
					event2.description = (const char*)itemIdx;
					SendGamePlayEvent(pEntity,event2);
				}
				break;

			case eGE_AttachedAccessory:
				{
					if(!IsGrenade(event.description)) // NOT OffHandGrenade
						SendGamePlayEvent(pEntity,event2);
				}
				break;

			case eGE_AmmoCount:
				{
					const char* itemIdx = event.description;
					if(!itemIdx)
						break;

					TGameStates::iterator itGS;
					/*if(pActor->IsPlayer())
						itGS = m_itSingleActorGameState;
					else */if(pActor->GetEntity())
						itGS = m_GameStates.find(pActor->GetEntity()->GetId());
					else
						break;

					if(itGS == m_GameStates.end())
						break;

					SActorGameState& gstate = itGS->second;

					IEntity* pItemEntity = gEnv->pEntitySystem->FindEntityByName(itemIdx);
					if(!pItemEntity)
						break;
					IItem* pItem = g_pGame->GetIGameFramework()->GetIItemSystem()->GetItem(pItemEntity->GetId());
					if(!pItem)
						break;

					CWeapon* pWeapon = (CWeapon*)(pItem->GetIWeapon());
					if(pWeapon && pWeapon->GetEntity())
					{
						TItemContainer::iterator it = gstate.Items.find(itemIdx);
						if(it==gstate.Items.end())
							break;
						SItemProperties& recItem = it->second;
						
						SWeaponAmmo weaponAmmo = pWeapon->GetFirstAmmo();
						bool bGrenade = false;
						if(!weaponAmmo.pAmmoClass)
						{
							// special case for grenades
							if(IsAmmoGrenade((const char*)(event.extra)))
							{
								weaponAmmo.pAmmoClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass((const char*)event.extra);
								weaponAmmo.count = (int)event.value;
								bGrenade = true;
							}
						}
						
						for(; weaponAmmo.pAmmoClass ; weaponAmmo = pWeapon->GetNextAmmo())
						{
							int ammoCount = weaponAmmo.count;
							const char* ammoClass;
							if(weaponAmmo.pAmmoClass && (ammoClass = weaponAmmo.pAmmoClass->GetName()))
							{
								TAmmoContainer& recAmmo = bGrenade? gstate.AmmoMags : recItem.Ammo;
								if(recAmmo.find(ammoClass) == recAmmo.end())
									recAmmo.insert(std::make_pair(ammoClass,0));
								if(ammoCount != recAmmo[ammoClass])
								{
									event2.event = eGE_AmmoCount;
									event2.value = (float)ammoCount;
									if(event2.value < 0)
										event2.value = 0;
									event2.extra = (void*)ammoClass;
									event2.description = (const char*)itemIdx;
									SendGamePlayEvent(pEntity,event2);
								}
							}
						}
					}

				}
				break;

			case eGE_EntityGrabbed:
				{
					EntityId entityId = EntityId(event.extra);
					IEntity * pGrabbedEntity = gEnv->pEntitySystem->GetEntity(entityId);
					if(pGrabbedEntity)
					{
						event2.description = pGrabbedEntity->GetName();
						SendGamePlayEvent(pEntity,event2);
					}
				}
				break;

			case eGE_WeaponReload:
			case eGE_ZoomedIn:
			case eGE_ZoomedOut:			
			case eGE_HealthChanged:
			case eGE_ItemExchanged:
				SendGamePlayEvent(pEntity,event2);
				break;

			default:
				break;
		}

	}
}
Example #22
0
//------------------------------------------------------------------------
void CWeapon::OnShoot(EntityId shooterId, EntityId ammoId, IEntityClass* pAmmoType, const Vec3 &pos, const Vec3 &dir, const Vec3&vel)
{
	BROADCAST_WEAPON_EVENT(OnShoot, (this, shooterId, ammoId, pAmmoType, pos, dir, vel));

	//FIXME:quick temporary solution
	CActor *pActor = static_cast<CActor*> (g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(shooterId));
	if (pActor)
		pActor->HandleEvent(SGameObjectEvent(eCGE_OnShoot,eGOEF_ToExtensions));

	IActor *pClientActor=m_pGameFramework->GetClientActor();

	if (pActor && pActor->GetActorClass() == CPlayer::GetActorClassType() && IsServer())
	{
		if (pActor == pClientActor)
		{
			if (IAIObject *pAIObject=pActor->GetEntity()->GetAI())
				gEnv->pAISystem->SendSignal(SIGNALFILTER_LEADER, 1, "OnEnableFire",	pAIObject, 0);
		}

		CPlayer *pPlayer=static_cast<CPlayer *>(pActor);
		CNanoSuit *pSuit=pPlayer->GetNanoSuit();

		if(m_fm && strcmp(m_fm->GetType(), "Repair"))
		{
			if(pSuit)
			{
				if (pSuit->GetMode() == NANOMODE_STRENGTH && !IsMounted())
					pSuit->SetSuitEnergy(pSuit->GetSuitEnergy()-g_pGameCVars->g_suitRecoilEnergyCost);
				else if(pSuit->GetMode() == NANOMODE_CLOAK)
					pSuit->SetSuitEnergy(0.0f);
			}
		}

		if (gEnv->bServer && pSuit && pSuit->IsInvulnerable())
			pSuit->SetInvulnerability(false);
	}
	
	if (pClientActor && m_fm && strcmp(m_fm->GetType(), "Thrown"))	
	{
		// inform the HUDRadar about the sound event
		Vec3 vPlayerPos=pClientActor->GetEntity()->GetWorldPos();
		float fDist2=(vPlayerPos-pos).len2();
		if (fDist2<250.0f*250.0f)
		{			
			//if (pClientActor->GetEntityId() != shooterId) 
				//	pHUD->ShowSoundOnRadar(pos);
				
			if(gEnv->bMultiplayer)
			{
				CGameRules *pGameRules = g_pGame->GetGameRules();
				if(pGameRules->GetTeamCount() < 2 || (pGameRules->GetTeam(shooterId) != pGameRules->GetTeam(pClientActor->GetEntityId())))
				{
					//Small workaround for patch2...
					IFireMode* pFM = GetFireMode(GetCurrentFireMode());
					bool grenade = pFM?(pFM->GetAmmoType()==CItem::sScarGrenadeClass):false;
					//~...

					if (!IsSilencerAttached() || grenade)
					{
						SAFE_HUD_FUNC(GetRadar()->AddEntityTemporarily(shooterId, 5.0f));
					}
					else if(fDist2<5.0f*5.0f)
					{
						//Silencer attached
						SAFE_HUD_FUNC(GetRadar()->AddEntityTemporarily(shooterId, 5.0f));
					}
				}
			}

			if ((!IsSilencerAttached()) && fDist2<sqr(SAFE_HUD_FUNC_RET(GetBattleRange())))
				SAFE_HUD_FUNC(TickBattleStatus(1.0f));
		}
	}
}
Example #23
0
bool CSpammer::ShootRocket(EntityId target)
{
	IEntityClass* pAmmoClass = m_fireParams->fireparams.ammo_type_class;
	int ammoCount = m_pWeapon->GetAmmoCount(pAmmoClass);

	CActor *pOwnerActor = m_pWeapon->GetOwnerActor();

	const bool playerIsShooter = pOwnerActor ? pOwnerActor->IsPlayer() : false;
	const bool clientIsShooter = pOwnerActor ? pOwnerActor->IsClient() : false;

	bool bHit = false;
	ray_hit rayhit;	 
	rayhit.pCollider = 0;

	Vec3 hit = GetProbableHit(WEAPON_HIT_RANGE, &bHit, &rayhit);
	Vec3 pos = GetFiringPos(hit);
	Vec3 dir = GetFiringDir(hit, pos);
	Vec3 vel = GetFiringVelocity(dir);

	int flags = CItem::eIPAF_Default;
	if (IsProceduralRecoilEnabled() && pOwnerActor)
	{
		pOwnerActor->ProceduralRecoil(m_fireParams->proceduralRecoilParams.duration, m_fireParams->proceduralRecoilParams.strength, m_fireParams->proceduralRecoilParams.kickIn, m_fireParams->proceduralRecoilParams.arms);
	}

	float speedOverride = -1.f;
	GetWeapon()->PlayAction(GetFragmentIds().fire, 0, false, flags, speedOverride);

	CheckNearMisses(hit, pos, dir, (hit-pos).len(), 1.0f);

	CProjectile* pAmmo = m_pWeapon->SpawnAmmo(m_fireParams->fireparams.spawn_ammo_class, false);
	const EntityId weaponOwnerId = m_pWeapon->GetOwnerId();
	EntityId ammoId = 0;

	if (pAmmo)
	{
		ammoId = pAmmo->GetEntityId();

		CRY_ASSERT_MESSAGE(m_fireParams->fireparams.hitTypeId, string().Format("Invalid hit type '%s' in fire params for '%s'", m_fireParams->fireparams.hit_type.c_str(), m_pWeapon->GetEntity()->GetName()));
		CRY_ASSERT_MESSAGE(m_fireParams->fireparams.hitTypeId == g_pGame->GetGameRules()->GetHitTypeId(m_fireParams->fireparams.hit_type.c_str()), "Sanity Check Failed: Stored hit type id does not match the type string, possibly CacheResources wasn't called on this weapon type");

		pAmmo->SetParams(CProjectile::SProjectileDesc(
			weaponOwnerId, m_pWeapon->GetHostId(), m_pWeapon->GetEntityId(), 
			m_fireParams->fireparams.damage, m_fireParams->fireparams.damage_drop_min_distance, m_fireParams->fireparams.damage_drop_per_meter, m_fireParams->fireparams.damage_drop_min_damage,
			m_fireParams->fireparams.hitTypeId, m_fireParams->fireparams.bullet_pierceability_modifier, m_pWeapon->IsZoomed()));
		// this must be done after owner is set
		pAmmo->InitWithAI();
		pAmmo->SetDestination(target);
		pAmmo->Launch(pos, dir, vel, m_speed_scale);

		m_projectileId = ammoId;

		if (clientIsShooter && pAmmo->IsPredicted() && gEnv->IsClient() && gEnv->bServer)
		{
			pAmmo->GetGameObject()->BindToNetwork();
		}
	}

	if (m_pWeapon->IsServer())
	{
		const char *ammoName = pAmmoClass != NULL ? pAmmoClass->GetName() : NULL;
		g_pGame->GetIGameFramework()->GetIGameplayRecorder()->Event(m_pWeapon->GetOwner(), GameplayEvent(eGE_WeaponShot, ammoName, 1, (void *)(EXPAND_PTR)m_pWeapon->GetEntityId()));
	}

	OnShoot(weaponOwnerId, ammoId, pAmmoClass, pos, dir, vel);

	if(playerIsShooter)
	{
		const SThermalVisionParams& thermalParams = m_fireParams->thermalVisionParams;
		m_pWeapon->AddShootHeatPulse(pOwnerActor, thermalParams.weapon_shootHeatPulse, thermalParams.weapon_shootHeatPulseTime,
			thermalParams.owner_shootHeatPulse, thermalParams.owner_shootHeatPulseTime);
	}

	m_muzzleEffect.Shoot(this, hit, m_barrelId);
	RecoilImpulse(pos, dir);

	m_fired = true;
	m_next_shot += m_next_shot_dt;

	if (++m_barrelId == m_fireParams->fireparams.barrel_count)
		m_barrelId = 0;

	ammoCount--;

	int clipSize = GetClipSize();
	if (clipSize != -1)
	{
		if (clipSize!=0)
			m_pWeapon->SetAmmoCount(pAmmoClass, ammoCount);
		else
			m_pWeapon->SetInventoryAmmoCount(pAmmoClass, ammoCount);
	}

	m_pWeapon->RequestShoot(pAmmoClass, pos, dir, vel, hit, m_speed_scale, pAmmo? pAmmo->GetGameObject()->GetPredictionHandle() : 0, false);

	return true;
}
Example #24
0
void CHandGrenades::UpdateStowedWeapons()
{
	CActor *pOwnerActor = GetOwnerActor();
	if (!pOwnerActor)
		return;

	ICharacterInstance *pOwnerCharacter = pOwnerActor->GetEntity()->GetCharacter(0);
	if (!pOwnerCharacter)
		return;

	IStatObj *pTPObj = GetEntity()->GetStatObj(eIGS_ThirdPerson);
	if (!pTPObj)
		return;


	int ammoCount = m_fm ? pOwnerActor->GetInventory()->GetAmmoCount(m_fm->GetAmmoType()) : 0;
	if (IsSelected() && (ammoCount > 0))
	{
		ammoCount--;
	}
	if (!pOwnerActor->IsThirdPerson())
	{
		ammoCount = 0;
	}

	int numGrenDiff = ammoCount - m_numStowedCopies;
	if(numGrenDiff != 0)
	{
		if (m_stowSlot < 0)
		{
			m_stowSlot = PickStowSlot(pOwnerCharacter->GetIAttachmentManager(), m_sharedparams->params.bone_attachment_01.c_str(), m_sharedparams->params.bone_attachment_02.c_str());
		}

		if (m_stowSlot >= 0)
		{
			bool attach = numGrenDiff > 0;
			int tot = abs(numGrenDiff);

			IAttachmentManager *pAttachmentManager = pOwnerCharacter->GetIAttachmentManager();
			IAttachment *pAttachment = NULL;

			for (int i=0; i<tot; i++)
			{
				//--- Generate the secondary slot from the first by adding one to the attachment name, is all we need at present...
				const char *attach1 = (m_stowSlot == 0) ? m_sharedparams->params.bone_attachment_01.c_str() : m_sharedparams->params.bone_attachment_02.c_str();
				int lenAttachName = strlen(attach1);
				stack_string attach2(attach1, lenAttachName-1);
				attach2 += (attach1[lenAttachName-1]+1);

				if (attach)
				{
					pAttachment = pAttachmentManager->GetInterfaceByName(attach1);
					if(pAttachment && pAttachment->GetIAttachmentObject())
					{
						pAttachment = pAttachmentManager->GetInterfaceByName(attach2);
					}

					if (pAttachment && !pAttachment->GetIAttachmentObject())
					{
						CCGFAttachment *pCGFAttachment = new CCGFAttachment();
						pCGFAttachment->pObj = pTPObj;
						pAttachment->AddBinding(pCGFAttachment);
						pAttachment->HideAttachment(0);
						pAttachment->HideInShadow(0);

						m_numStowedCopies++;
					}
				}
				else
				{
					pAttachment = pAttachmentManager->GetInterfaceByName(attach2);
					if(!pAttachment || !pAttachment->GetIAttachmentObject())
					{
						pAttachment = pAttachmentManager->GetInterfaceByName(attach1);
					}

					if (pAttachment && pAttachment->GetIAttachmentObject())
					{
						pAttachment->ClearBinding();
						m_numStowedCopies--;					
					}
				}
			}
		}
	}
}
// method for adding a new actor to the scene
CActor *CActorManager::newActor(const std::string &type, const std::string &name)
{
	LastActorId = CEntityId::Unknown;

	if (getActor(name)!=NULL)
	{
		nlinfo("Actor already exists: %s",name.c_str());
		return NULL;
	}

	CSheetId				sheetId(type);
	const CSheets::CSheet	*sheet=CSheets::lookup(sheetId);
	if (!sheet)
	{
		nlwarning("ERROR: Can't find static type data for '%s'(%d) for entity %s", type.c_str(), sheetId.asInt(), name.c_str());
		return NULL;
	}

	// create a new actor record and COPY it into the actor vector

//	EGSPD::CPeople::TPeople p_type = EGSPD::CPeople::fromString( type );
	bool success = false;
	CActor *aNewActor;
	if ( sheet->isNpc /*EGSPD::CPeople::isPlayableRace( p_type )*/ )
		aNewActor = new CActor(type,name,CEntityId(RYZOMID::npc,_nextActorID++),success);
	else
		aNewActor = new CActor(type,name,CEntityId(RYZOMID::creature,_nextActorID++),success);

	if ( ! success )
	{
		if (aNewActor)
			delete aNewActor;
		return NULL;
	}

	LastActorId = aNewActor->_id;

	int x,y;
	CPositionGenerator::next(x,y);
	aNewActor->setPos(x, y, 0);
	aNewActor->setAngle(0);
	_actors.push_back(aNewActor);

	// get hold of a pointer of the copy of the actor in the actor vector
	CActor *theActor=getActor(name);

	// add the actor to the GPMS, the IOS, etc
	if (theActor!=0)
		theActor->addToOtherServices();
/*
	CMessage	msgMode("SET_MODE");
	TDataSetRow		index = CMirrors::DataSet->getDataSetRow(theActor->_id);
	msgMode.serial(index);
	MBEHAV::TMode	mode(MBEHAV::NORMAL, x, y);
	msgMode.serial(mode);
	sendMessageViaMirror("EGS", msgMode);
*/
	CMirrors::initSheet( aNewActor->getSid(), sheetId ); // initialize out the sheet
	// Let the position & angle & tick be sent ("UPDATE_ENTITIES_POSITIONS") in update
	//aNewActor->initMode();

	MBEHAV::TMode	mode(MBEHAV::NORMAL, x, y);
	theActor->_mode = mode.RawModeAndParam;

	aNewActor->display();
	theActor->setGroup(_defaultActorGroup);

	GlobalActorCount++;
	return theActor;
}
Example #26
0
bool CHandGrenades::CanOwnerThrowGrenade() const
{
	CActor* pOwnerActor = GetOwnerActor();

	return pOwnerActor ? pOwnerActor->CanFire() : true;
}
Example #27
0
//-------------------------------------------
void CGameRules::ProcessClientExplosionScreenFX(const ExplosionInfo &explosionInfo)
{
	IActor *pClientActor = g_pGame->GetIGameFramework()->GetClientActor();
	if (pClientActor)
	{
		//Distance
		float dist = (pClientActor->GetEntity()->GetWorldPos() - explosionInfo.pos).len();

		//Is the explosion in Player's FOV (let's suppose the FOV a bit higher, like 80)
		CActor *pActor = (CActor *)pClientActor;
		SMovementState state;
		if (IMovementController *pMV = pActor->GetMovementController())
		{
			pMV->GetMovementState(state);
		}

		Vec3 eyeToExplosion = explosionInfo.pos - state.eyePosition;
		eyeToExplosion.Normalize();
		bool inFOV = (state.eyeDirection.Dot(eyeToExplosion) > 0.68f);
		
		// if in a vehicle eyeDirection is wrong
		if(pActor && pActor->GetLinkedVehicle())
		{
			Vec3 eyeDir = static_cast<CPlayer*>(pActor)->GetVehicleViewDir();
			inFOV = (eyeDir.Dot(eyeToExplosion) > 0.68f);
		}

		//All explosions have radial blur (default 30m radius, to make Sean happy =))
		float maxBlurDistance = (explosionInfo.maxblurdistance>0.0f)?explosionInfo.maxblurdistance:30.0f;
		if (maxBlurDistance>0.0f && g_pGameCVars->g_radialBlur>0.0f && m_explosionScreenFX && explosionInfo.radius>0.5f)
		{		
			if (inFOV && dist < maxBlurDistance)
			{
				ray_hit hit;
				int col = gEnv->pPhysicalWorld->RayWorldIntersection(explosionInfo.pos , -eyeToExplosion*dist, ent_static | ent_terrain, rwi_stop_at_pierceable|rwi_colltype_any, &hit, 1);

				//If there was no obstacle between flashbang grenade and player
				if(!col)
				{
					if (CScreenEffects* pSE = pActor->GetScreenEffects())
					{
						float blurRadius = (-1.0f/maxBlurDistance)*dist + 1.0f;

						gEnv->p3DEngine->SetPostEffectParam("FilterRadialBlurring_Radius", blurRadius);
						gEnv->p3DEngine->SetPostEffectParam("FilterRadialBlurring_Amount", 1.0f);

						IBlendedEffect *pBlur	= CBlendedEffect<CPostProcessEffect>::Create(CPostProcessEffect(pClientActor->GetEntityId(),"FilterRadialBlurring_Amount", 0.0f));
						IBlendType   *pLinear = CBlendType<CLinearBlend>::Create(CLinearBlend(1.0f));
						pSE->StartBlend(pBlur, pLinear, 1.0f, CScreenEffects::eSFX_GID_RBlur);
						pSE->SetUpdateCoords("FilterRadialBlurring_ScreenPosX","FilterRadialBlurring_ScreenPosY", explosionInfo.pos);
					}

					float distAmp = 1.0f - (dist / maxBlurDistance);
					if (gEnv->pInput) 
						gEnv->pInput->ForceFeedbackEvent( SFFOutputEvent(eDI_XI, eFF_Rumble_Basic, 0.5f, distAmp*3.0f, 0.0f));
				}
			}
		}

		//Flashbang effect 
		if(dist<explosionInfo.radius && inFOV &&
			(!strcmp(explosionInfo.effect_class,"flashbang") || !strcmp(explosionInfo.effect_class,"FlashbangAI")))
		{
			ray_hit hit;
			int col = gEnv->pPhysicalWorld->RayWorldIntersection(explosionInfo.pos , -eyeToExplosion*dist, ent_static | ent_terrain, rwi_stop_at_pierceable|rwi_colltype_any, &hit, 1);

			//If there was no obstacle between flashbang grenade and player
			if(!col)
			{
				float power = explosionInfo.flashbangScale;
				power *= max(0.0f, 1 - (dist/explosionInfo.radius));
				float lookingAt = (eyeToExplosion.Dot(state.eyeDirection.normalize()) + 1)*0.5f;
				power *= lookingAt;

				SAFE_GAMEAUDIO_SOUNDMOODS_FUNC(AddSoundMood(SOUNDMOOD_EXPLOSION,MIN(power*40.0f,100.0f)));

				gEnv->p3DEngine->SetPostEffectParam("Flashbang_Time", 1.0f + (power * 4));
				gEnv->p3DEngine->SetPostEffectParam("FlashBang_BlindAmount",explosionInfo.blindAmount);
				gEnv->p3DEngine->SetPostEffectParam("Flashbang_DifractionAmount", (power * 2));
				gEnv->p3DEngine->SetPostEffectParam("Flashbang_Active", 1);
			}
		}
		else if(inFOV && (dist < explosionInfo.radius))
		{
			if (explosionInfo.damage>10.0f || explosionInfo.pressure>100.0f)
			{
				//Add some angular impulse to the client actor depending on distance, direction...
				float dt = (1.0f - dist/explosionInfo.radius);
				dt = dt * dt;
				float angleZ = gf_PI*0.15f*dt;
				float angleX = gf_PI*0.15f*dt;

				pActor->AddAngularImpulse(Ang3(Random(-angleX*0.5f,angleX),0.0f,Random(-angleZ,angleZ)),0.0f,dt*2.0f);
			}
		}


		float fDist2=(pClientActor->GetEntity()->GetWorldPos()-explosionInfo.pos).len2();
		if (fDist2<250.0f*250.0f)
		{		
			if (fDist2<sqr(SAFE_GAMEAUDIO_BATTLESTATUS_FUNC_RET(GetBattleRange())))
				SAFE_GAMEAUDIO_BATTLESTATUS_FUNC(TickBattleStatus(1.0f));
		}
	}

}
Example #28
0
//------------------------------------------------------------------------
tSoundID CItem::PlayAction(const ItemString &actionName, int layer, bool loop, uint32 flags, float speedOverride)
{
	if(!m_enableAnimations || !IsOwnerInGame())
		return (tSoundID)-1;

	TActionMap::iterator it = m_sharedparams->actions.find(CONST_TEMPITEM_STRING(actionName));

	if(it == m_sharedparams->actions.end())
	{
//		GameWarning("Action '%s' not found on item '%s'!", actionName, GetEntity()->GetName());

		for(int i=0; i<eIGS_Last; i++)
		{
			m_animationTime[i]=0;
			m_animationSpeed[i]=1.0f;
			m_animationEnd[i]=0;
		}

		return 0;
	}

	bool fp = m_stats.fp;

	if(m_parentId)
	{
		CItem *pParent=static_cast<CItem *>(m_pItemSystem->GetItem(m_parentId));

		if(pParent)
			fp=pParent->GetStats().fp;
	}

	if(flags&eIPAF_ForceFirstPerson)
		fp = true;

	if(flags&eIPAF_ForceThirdPerson)
		fp = false;

	int sid=fp?eIGS_FirstPerson:eIGS_ThirdPerson;
	SAction &action = it->second;

	tSoundID result = INVALID_SOUNDID;

	if((flags&eIPAF_Sound) && !action.sound[sid].name.empty() && IsSoundEnabled() && g_pGameCVars->i_soundeffects)
	{
		int nSoundFlags = FLAG_SOUND_DEFAULT_3D;
		nSoundFlags |= flags&eIPAF_SoundStartPaused?FLAG_SOUND_START_PAUSED:0;
		IEntitySoundProxy *pSoundProxy = GetSoundProxy(true);

		//GetSound proxy from dualwield master if neccesary
		if(IsDualWieldSlave())
		{
			CItem *pMaster = static_cast<CItem *>(GetDualWieldMaster());

			if(pMaster)
			{
				pSoundProxy = pMaster->GetSoundProxy(true);
			}
		}

		EntityId pSkipEnts[3];
		int nSkipEnts = 0;

		// TODO for Marcio :)
		// check code changes

		// Skip the Item
		pSkipEnts[nSkipEnts] = GetEntity()->GetId();
		++nSkipEnts;

		// Skip the Owner
		if(GetOwner())
		{
			pSkipEnts[nSkipEnts] = GetOwner()->GetId();
			++nSkipEnts;
		}

		if(pSoundProxy)
		{

			TempResourceName name;
			FixResourceName(action.sound[sid].name, name, flags);
			//nSoundFlags = nSoundFlags | (fp?FLAG_SOUND_DEFAULT_3D|FLAG_SOUND_RELATIVE:FLAG_SOUND_DEFAULT_3D);
			Vec3 vOffset(0,0,0);

			if(fp)
				vOffset.x = 0.3f; // offset for first person weapon to the front

			if(!g_pGameCVars->i_staticfiresounds)
			{
				result = pSoundProxy->PlaySoundEx(name, vOffset, FORWARD_DIRECTION, nSoundFlags, 1.0f, 0, 0, eSoundSemantic_Weapon, pSkipEnts, nSkipEnts);
				ISound *pSound = pSoundProxy->GetSound(result);

				if(pSound && action.sound[sid].sphere>0.0f)
					pSound->SetSphereSpec(action.sound[sid].sphere);
			}
			else
			{
				SInstanceAudio *pInstanceAudio=0;

				if(action.sound[sid].isstatic)
				{
					TInstanceActionMap::iterator iit = m_instanceActions.find(CONST_TEMPITEM_STRING(actionName));

					if(iit == m_instanceActions.end())
					{
						std::pair<TInstanceActionMap::iterator, bool> insertion=m_instanceActions.insert(TInstanceActionMap::value_type(actionName, SInstanceAction()));
						pInstanceAudio=&insertion.first->second.sound[sid];
					}
					else
						pInstanceAudio=&iit->second.sound[sid];
				}

				if(pInstanceAudio && (pInstanceAudio->id != INVALID_SOUNDID) && (name != pInstanceAudio->static_name))
					ReleaseStaticSound(pInstanceAudio);

				if(!pInstanceAudio || pInstanceAudio->id == INVALID_SOUNDID)
				{
					result = pSoundProxy->PlaySoundEx(name, vOffset, FORWARD_DIRECTION, nSoundFlags, 1.0f, 0, 0, eSoundSemantic_Weapon, pSkipEnts, nSkipEnts);
					ISound *pSound = pSoundProxy->GetSound(result);

					if(pSound && action.sound[sid].sphere>0.0f)
						pSound->SetSphereSpec(action.sound[sid].sphere);
				}

				if(action.sound[sid].isstatic)
				{
					if(pInstanceAudio->id == INVALID_SOUNDID)
					{
						if(pSoundProxy->SetStaticSound(result, true))
						{
							pInstanceAudio->id = result;
							pInstanceAudio->static_name = name;
							pInstanceAudio->synch = action.sound[sid].issynched;
						}
					}
					else
					{
						ISound *pSound = pSoundProxy->GetSound(pInstanceAudio->id);

						if(pSound)
							pSound->Play(1.0, true, true, pSoundProxy);
					}
				}
			}

			if(gEnv->pAISystem && action.sound[sid].airadius > 0.0f)
			{
				EntityId ownerId = GetOwner() ? GetOwner()->GetId() : 0;

				// associate sound event with vehicle if the shooter is in a vehicle (tank cannon shot, etc)
				if(CActor *pOwnerActor = GetOwnerActor())
				{
					IVehicle *pOwnerVehicle = pOwnerActor->GetLinkedVehicle();

					if(pOwnerVehicle && pOwnerVehicle->GetEntityId())
						ownerId = pOwnerVehicle->GetEntityId();
				}

				SAIStimulus stim(AISTIM_SOUND, AISOUND_WEAPON, ownerId?ownerId:GetEntityId() , 0,
								 GetEntity()->GetWorldPos(), ZERO, action.sound[sid].airadius);

				gEnv->pAISystem->RegisterStimulus(stim);
			}
		}
	}


	if(flags&eIPAF_Animation)
	{
		TempResourceName name;
		// generate random number only once per call to allow animations to
		// match across geometry slots (like first person and third person)
		float randomNumber = Random();

		for(int i=0; i<eIGS_Last; i++)
		{
			if(!(flags&(1<<i)))
				continue;

			int nanimations=action.animation[i].size();

			if(nanimations <= 0)
				continue;

			int anim = int(randomNumber * float(nanimations));

			if(action.animation[i][anim].name.empty())
				continue;

			FixResourceName(action.animation[i][anim].name, name, flags);

			if((i == eIGS_Owner) || (i == eIGS_OwnerLooped))
			{
				if(!action.animation[i][anim].name.empty())
				{
					bool looping=(eIGS_OwnerLooped==i);

					CActor *pOwner = GetOwnerActor();

					if(pOwner)
					{
						if(IsDualWield() && !m_sharedparams->params.dual_wield_pose.empty())
							pOwner->PlayAction(name, m_sharedparams->params.dual_wield_pose.c_str(), looping);
						else
							pOwner->PlayAction(name, m_sharedparams->params.pose.c_str(), looping);
					}
				}

				continue;
			}
			else if(i == eIGS_OffHand)
			{
				if(!action.animation[eIGS_OffHand][anim].name.empty())
				{
					CActor *pOwner = GetOwnerActor();

					if(pOwner)
					{
						CItem *pOffHand = pOwner->GetItemByClass(CItem::sOffHandClass);

						if(pOffHand && pOffHand!=this)
						{
							uint32 ohflags=eIPAF_Default;

							if(action.animation[eIGS_OffHand][anim].blend==0.0f)
								ohflags|=eIPAF_NoBlend;

							pOffHand->PlayAction(action.animation[eIGS_OffHand][anim].name, 0, false, ohflags);
						}
					}
				}

				continue;
			}

			SAnimation &animation=action.animation[i][anim];

			if(!animation.name.empty())
			{
				float blend = animation.blend;

				if(flags&eIPAF_NoBlend)
					blend = 0.0f;

				if(speedOverride > 0.0f)
					PlayAnimationEx(name, i, layer, loop, blend, speedOverride, flags);
				else
					PlayAnimationEx(name, i, layer, loop, blend, animation.speed, flags);
			}

			if((m_stats.fp || m_stats.viewmode&eIVM_FirstPerson) && i==eIGS_FirstPerson && !animation.camera_helper.empty())
			{
				m_camerastats.animating=true;
				m_camerastats.helper=animation.camera_helper;
				m_camerastats.position=animation.camera_pos;
				m_camerastats.rotation=animation.camera_rot;
				m_camerastats.follow=animation.camera_follow;
				m_camerastats.reorient=animation.camera_reorient;
			}
			else if(m_camerastats.animating)
				m_camerastats=SCameraAnimationStats();
		}
	}

	if(flags&eIPAF_Effect && !action.effect[sid].name.empty())
	{
		// change this to attach, if needed
		SpawnEffect(sid, action.effect[sid].name.c_str(), action.effect[sid].helper.c_str());
	}

	if(action.children)
	{
		for(TAccessoryMap::iterator ait=m_accessories.begin(); ait!=m_accessories.end(); ait++)
		{
			EntityId aId=(EntityId)ait->second;
			CItem *pAccessory=static_cast<CItem *>(m_pItemSystem->GetItem(aId));

			if(pAccessory)
				pAccessory->PlayAction(actionName, layer, loop, flags, speedOverride);
		}
	}

	return result;
}
Example #29
0
void ui_actor_state_wnd::UpdateActorInfo( CInventoryOwner* owner )
{
	CActor* actor = smart_cast<CActor*>( owner );
	if ( !actor )
	{
		return;
	}

	float value = 0.0f;
	
	value = actor->conditions().GetHealth();
	value = floor(value * 55) / 55; // number of sticks in progress bar
// show bleeding icon
	m_state[stt_health]->set_progress(value);
	value = actor->conditions().BleedingSpeed();					
	m_state[stt_bleeding]->show_static(false, 1);
	m_state[stt_bleeding]->show_static(false, 2);
	m_state[stt_bleeding]->show_static(false, 3);
	if(!fis_zero(value, EPS))
	{
		if(value<0.35f)
			m_state[stt_bleeding]->show_static(true, 1);
		else if(value<0.7f)
			m_state[stt_bleeding]->show_static(true, 2);
		else 
			m_state[stt_bleeding]->show_static(true, 3);
	}
// show radiation icon
	value = actor->conditions().GetRadiation();
	m_state[stt_radiation]->show_static(false, 1);
	m_state[stt_radiation]->show_static(false, 2);
	m_state[stt_radiation]->show_static(false, 3);
	if(!fis_zero(value, EPS))
	{
		if(value<0.35f)
			m_state[stt_radiation]->show_static(true, 1);
		else if(value<0.7f)
			m_state[stt_radiation]->show_static(true, 2);
		else 
			m_state[stt_radiation]->show_static(true, 3);
	}

	CCustomOutfit* outfit = actor->GetOutfit();
	PIItem itm = actor->inventory().ItemFromSlot(HELMET_SLOT);
	CHelmet* helmet = smart_cast<CHelmet*>(itm);

	m_state[stt_fire]->set_progress(0.0f);
	m_state[stt_radia]->set_progress(0.0f);
	m_state[stt_acid]->set_progress(0.0f);
	m_state[stt_psi]->set_progress(0.0f);
	m_state[stt_wound]->set_progress(0.0f);
	m_state[stt_fire_wound]->set_progress(0.0f);
	m_state[stt_shock]->set_progress(0.0f);
	m_state[stt_power]->set_progress(0.0f);

	float burn_value = 0.0f;
	float radi_value = 0.0f;
	float cmbn_value = 0.0f;
	float tele_value = 0.0f;
	float woun_value = 0.0f;
	float shoc_value = 0.0f;
	float fwou_value = 0.0f;

	CEntityCondition::BOOSTER_MAP cur_booster_influences = actor->conditions().GetCurBoosterInfluences();
	CEntityCondition::BOOSTER_MAP::const_iterator it;
	it = cur_booster_influences.find(eBoostRadiationProtection);
	if(it!=cur_booster_influences.end())
		radi_value += it->second.fBoostValue;

	it = cur_booster_influences.find(eBoostChemicalBurnProtection);
	if(it!=cur_booster_influences.end())
		cmbn_value += it->second.fBoostValue;

	it = cur_booster_influences.find(eBoostTelepaticProtection);
	if(it!=cur_booster_influences.end())
		tele_value += it->second.fBoostValue;

	if(outfit)
	{
		burn_value += outfit->GetDefHitTypeProtection(ALife::eHitTypeBurn);
		radi_value += outfit->GetDefHitTypeProtection(ALife::eHitTypeRadiation);
		cmbn_value += outfit->GetDefHitTypeProtection(ALife::eHitTypeChemicalBurn);
		tele_value += outfit->GetDefHitTypeProtection(ALife::eHitTypeTelepatic);
		woun_value += outfit->GetDefHitTypeProtection(ALife::eHitTypeWound);
		shoc_value += outfit->GetDefHitTypeProtection(ALife::eHitTypeShock);

		IKinematics* ikv = smart_cast<IKinematics*>(actor->Visual());
		VERIFY(ikv);
		u16 spine_bone = ikv->LL_BoneID("bip01_spine");
		fwou_value += outfit->GetBoneArmor(spine_bone)*outfit->GetCondition();					
		if(!outfit->bIsHelmetAvaliable)
		{
			u16 spine_bone = ikv->LL_BoneID("bip01_head");
			fwou_value += outfit->GetBoneArmor(spine_bone)*outfit->GetCondition();
		}
	}
	if(helmet)
	{
		burn_value += helmet->GetDefHitTypeProtection(ALife::eHitTypeBurn);
		radi_value += helmet->GetDefHitTypeProtection(ALife::eHitTypeRadiation);
		cmbn_value += helmet->GetDefHitTypeProtection(ALife::eHitTypeChemicalBurn);
		tele_value += helmet->GetDefHitTypeProtection(ALife::eHitTypeTelepatic);
		woun_value += helmet->GetDefHitTypeProtection(ALife::eHitTypeWound);
		shoc_value += helmet->GetDefHitTypeProtection(ALife::eHitTypeShock);

		IKinematics* ikv = smart_cast<IKinematics*>(actor->Visual());
		VERIFY(ikv);
		u16 spine_bone = ikv->LL_BoneID("bip01_head");
		fwou_value += helmet->GetBoneArmor(spine_bone)*helmet->GetCondition();
	}
	
//fire burn protection progress bar
	{
		burn_value += actor->GetProtection_ArtefactsOnBelt(ALife::eHitTypeBurn);
		float max_power = actor->conditions().GetZoneMaxPower(ALife::eHitTypeBurn);
		burn_value = floor(burn_value / max_power * 31) / 31; // number of sticks in progress bar
		m_state[stt_fire]->set_progress(burn_value);//0..1
	}
//radiation protection progress bar
	{
		radi_value += actor->GetProtection_ArtefactsOnBelt(ALife::eHitTypeRadiation);
		float max_power = actor->conditions().GetZoneMaxPower(ALife::eHitTypeRadiation);
		radi_value = floor(radi_value / max_power * 31) / 31; // number of sticks in progress bar
		m_state[stt_radia]->set_progress(radi_value);//0..1
	}
//chemical burn protection progress bar
	{
		cmbn_value += actor->GetProtection_ArtefactsOnBelt(ALife::eHitTypeChemicalBurn);
		float max_power = actor->conditions().GetZoneMaxPower(ALife::eHitTypeChemicalBurn);
		cmbn_value = floor(cmbn_value / max_power * 31) / 31; // number of sticks in progress bar
		m_state[stt_acid]->set_progress(cmbn_value);//0..1
	}
//telepatic protection progress bar
	{
		tele_value += actor->GetProtection_ArtefactsOnBelt(ALife::eHitTypeTelepatic);
		float max_power = actor->conditions().GetZoneMaxPower(ALife::eHitTypeTelepatic);
		tele_value = floor(tele_value / max_power * 31) / 31; // number of sticks in progress bar  
		m_state[stt_psi]->set_progress(tele_value);//0..1
	}
//wound protection progress bar
	{
		float max_power = actor->conditions().GetMaxWoundProtection();
		woun_value = floor(woun_value / max_power * 31) / 31; // number of sticks in progress bar
		m_state[stt_wound]->set_progress(woun_value);//0..1
	}
//shock protection progress bar
	{
		shoc_value += actor->GetProtection_ArtefactsOnBelt(ALife::eHitTypeShock);
		float max_power = actor->conditions().GetZoneMaxPower(ALife::eHitTypeShock);
		shoc_value = floor(shoc_value / max_power * 31) / 31; // number of sticks in progress bar  
		m_state[stt_shock]->set_progress(shoc_value);//0..1
	}
//fire wound protection progress bar
	{
		float max_power = actor->conditions().GetMaxFireWoundProtection();
		fwou_value = floor(fwou_value / max_power * 31) / 31; // number of sticks in progress bar
		m_state[stt_fire_wound]->set_progress(fwou_value);
	}
//power restore speed progress bar
	{
		value = actor->GetRestoreSpeed(ALife::ePowerRestoreSpeed) / actor->conditions().GetMaxPowerRestoreSpeed();;
		value = floor(value * 31) / 31; // number of sticks in progress bar  
		m_state[stt_power]->set_progress(value);//0..1
	}
// -----------------------------------------------------------------------------------

	UpdateHitZone();
}
Example #30
0
//------------------------------------------------------------------------
void CIronSight::Update(float frameTime, uint32 frameId)
{
	bool keepUpdating=false;
	CActor *pActor = m_pWeapon->GetOwnerActor();
	bool isClient = (pActor && pActor->IsClient());

	float doft = 1.0f;

	if(!m_zoomed)
		doft = 0.0f;

	if(m_zoomTime > 0.0f)	// zoomTime is set to 0.0 when zooming ends
	{
		keepUpdating=true;
		float t = CLAMP(1.0f-m_zoomTimer/m_zoomTime, 0.0f, 1.0f);
		float fovScale;

		if(m_smooth)
		{
			if(m_startFoV > m_endFoV)
				doft = t;
			else
				doft = 1.0f-t;

			fovScale = m_startFoV+t*(m_endFoV-m_startFoV);
		}
		else
		{
			fovScale = m_startFoV;

			if(t>=1.0f)
				fovScale = m_endFoV;
		}

		OnZoomStep(m_startFoV>m_endFoV, t);

		SetActorFoVScale(fovScale, true, true, true);

		if(isClient && m_pShared->zoomParams.scope_mode && !UseAlternativeIronSight())
		{
			AdjustScopePosition(t*1.25f,m_startFoV>m_endFoV);
			AdjustNearFov(t*1.25f,m_startFoV>m_endFoV);
		}

		// marcok: please don't touch
		if(isClient && g_pGameCVars->goc_enable)
		{
			g_pGameCVars->goc_targety = LERP((-2.5f), (-1.5f), doft*doft);
		}

		if(t>=1.0f)
		{
			if(m_zoomingIn)
			{
				m_zoomed = true;
				m_pWeapon->RequestZoom(fovScale);
			}
			else
			{
				m_zoomed = false;
				m_pWeapon->RequestZoom(1.0f);
			}

			m_zoomTime = 0.0f;
		}
	}

	if(isClient && g_pGameCVars->g_dof_ironsight != 0 && g_pGameCVars->goc_enable==0)
		UpdateDepthOfField(pActor, frameTime, doft);

	bool wasZooming = m_zoomTimer>0.0f;

	if(wasZooming || m_zoomed)
	{
		m_zoomTimer -= frameTime;

		if(m_zoomTimer<0.0f)
		{
			m_zoomTimer=0.0f;

			if(wasZooming)
			{
				if(m_zoomingIn)
				{
					OnZoomedIn();
				}
				else
				{
					OnZoomedOut();
				}
			}
		}

		if(m_focus < 1.0f)
		{
			m_focus += frameTime*1.5f;
		}
		else if(m_focus > 1.0f)
		{
			m_focus = 1.0f;
		}

		if(isClient)
		{
			//float t=m_zoomTimer/m_zoomTime;
			if(m_zoomTime > 0.0f)
			{
				//t=1.0f-max(t, 0.0f);
				gEnv->p3DEngine->SetPostEffectParam("Dof_BlurAmount", 1.0f);
			}

			// try to convert user-defined settings to IronSight system (used for Core)
			float userActive;
			gEnv->p3DEngine->GetPostEffectParam("Dof_User_Active", userActive);

			if(userActive > 0.0f)
			{
				float focusRange;
				float focusDistance;
				gEnv->p3DEngine->GetPostEffectParam("Dof_User_FocusRange", focusRange);
				gEnv->p3DEngine->GetPostEffectParam("Dof_User_FocusDistance", focusDistance);
				gEnv->p3DEngine->SetPostEffectParam("Dof_FocusMin", focusDistance);
				gEnv->p3DEngine->SetPostEffectParam("Dof_FocusMax", focusDistance);
				gEnv->p3DEngine->SetPostEffectParam("Dof_FocusLimit", focusDistance+focusRange*0.5f);
			}
			else
			{
				gEnv->p3DEngine->SetPostEffectParam("Dof_FocusMin", g_pGameCVars->g_dofset_minScale * m_minDoF);
				gEnv->p3DEngine->SetPostEffectParam("Dof_FocusMax", g_pGameCVars->g_dofset_maxScale * m_averageDoF);
				gEnv->p3DEngine->SetPostEffectParam("Dof_FocusLimit", g_pGameCVars->g_dofset_limitScale * m_averageDoF);
			}
		}

		keepUpdating=true;
	}

	if(keepUpdating)
		m_pWeapon->RequireUpdate(eIUS_Zooming);
}