Ang3 CCinematicInput::UpdateAdditiveCameraInputWithController( const SUpdateContext& updateCtx, const Ang3& rawControllerInput ) { if (updateCtx.m_recenter) { Ang3 finalControllerAnglesLimited = rawControllerInput; //Yaw angle (Z axis) finalControllerAnglesLimited.z = -clamp_tpl((float)__fsel(finalControllerAnglesLimited.z, finalControllerAnglesLimited.z * updateCtx.m_lookRightLimit, finalControllerAnglesLimited.z * updateCtx.m_lookLeftLimit), -updateCtx.m_lookLeftLimit, updateCtx.m_lookRightLimit); //Pitch angle (X axis) finalControllerAnglesLimited.x *= (g_pGameCVars->cl_invertController == 0) ? 1.0f : -1.0f; finalControllerAnglesLimited.x = clamp_tpl((float)__fsel(finalControllerAnglesLimited.x, finalControllerAnglesLimited.x * updateCtx.m_lookUpLimit, finalControllerAnglesLimited.x * updateCtx.m_lookDownLimit), -updateCtx.m_lookDownLimit, updateCtx.m_lookUpLimit); //No roll allowed finalControllerAnglesLimited.y = 0.0f; Interpolate(m_controllerAccumulatedAngles, finalControllerAnglesLimited, 2.5f, updateCtx.m_frameTime); } else { Ang3 finalControllerAnglesLimited = m_controllerAccumulatedAngles; finalControllerAnglesLimited.x += ( (rawControllerInput.x * updateCtx.m_frameTime * 1.5f) * ((g_pGameCVars->cl_invertController == 0) ? 1.0f : -1.0f) ); finalControllerAnglesLimited.z -= (rawControllerInput.z * updateCtx.m_frameTime * 1.5f); finalControllerAnglesLimited.x = clamp_tpl(finalControllerAnglesLimited.x, -updateCtx.m_lookDownLimit, updateCtx.m_lookUpLimit); finalControllerAnglesLimited.z = clamp_tpl(finalControllerAnglesLimited.z, -updateCtx.m_lookLeftLimit, updateCtx.m_lookRightLimit); finalControllerAnglesLimited.y = 0.0f; m_controllerAccumulatedAngles = finalControllerAnglesLimited; } return m_controllerAccumulatedAngles; }
//------------------------------------------------------------------------ int CVehicleUsableActionFlip::OnEvent(int eventType, SVehicleEventParams &eventParams) { if (IPhysicalEntity* pPhysics = m_pVehicle->GetEntity()->GetPhysics()) { if (eventType == eVAE_IsUsable) { return 1; } else if (eventType == eVAE_OnUsed) { if (m_pVehicle->IsFlipped()) { IEntity* pEntity = gEnv->pEntitySystem->GetEntity(eventParams.entityId); if (pEntity) { static const float speed = 3.f; // Decide which axis to turn around pe_status_pos physPos; pe_status_dynamics physDyn; pPhysics->GetStatus(&physPos); pPhysics->GetStatus(&physDyn); const Vec3 xAxis = physPos.q.GetColumn0(); const Vec3 yAxis = physPos.q.GetColumn1(); if (fabsf(yAxis.z) > 0.6f) { // Standing on its nose or tail // Rotate about the x m_localAngVel.Set(speed * (float)__fsel(yAxis.z, -1.f, +1.f), 0.f, 0.f); } else { // Rotate about the y (away from the user) const Vec3 centre = physPos.pos + (physPos.BBox[0] + physPos.BBox[1]) * 0.5f; const Vec3 entityPos = pEntity->GetWorldPos(); m_localAngVel.Set(0.f, speed * (float)__fsel((entityPos - centre).dot(xAxis), +1.f, -1.f), 0.f); } // Start the update m_pVehicle->SetObjectUpdate(this, IVehicle::eVOU_AlwaysUpdate); // Inform the vehicle that flipping has started SVehicleEventParams params; params.bParam = true; m_pVehicle->BroadcastVehicleEvent(eVE_BeingFlipped, params); m_pVehicle->NeedsUpdate(IVehicle::eVUF_AwakePhysics); } } return 0; } } return 0; }
//------------------------------------------------------------------------ void CVehicleMountedWeapon::CorrectRipperEntityPosition(float timeStep) { IVehicle *pVehicle = gEnv->pGame->GetIGameFramework()->GetIVehicleSystem()->GetVehicle(m_vehicleId); if(pVehicle) { const IEntity* pVehicleEnt = pVehicle->GetEntity(); Vec3 posDiff(ZERO); IActor* pOwner = GetOwnerActor(); if (pOwner && pOwner->IsPlayer()) { CPlayer* pPlayer = static_cast<CPlayer*>(pOwner); const Matrix34& wMat = pVehicleEnt->GetWorldTM(); Vec3 vehiclePos = wMat.GetTranslation(); Vec3 currWSpaceRipUserOffset = wMat.TransformPoint(m_localRipUserOffset); posDiff = currWSpaceRipUserOffset - m_previousWSpaceOffsetPosition; // Don't want to overwrite anyone else changes with an absolute 'set' pOwner->GetEntity()->SetPos(pOwner->GetEntity()->GetWorldPos() + posDiff); m_previousWSpaceOffsetPosition = currWSpaceRipUserOffset; //Update view limit direction based on change in vehicle rotation if(pPlayer->IsClient()) { SViewLimitParams &viewLimits = pPlayer->GetActorParams().viewLimits; if(viewLimits.GetViewLimitRangeH()) //Don't do this unless we are currently horizontally constrained { Quat vehicleRotation(wMat); Quat rotationChange = vehicleRotation * m_previousVehicleRotation.GetInverted(); Vec3 viewLimitDir = rotationChange * viewLimits.GetViewLimitDir(); viewLimitDir.z = 0.f; viewLimitDir.Normalize(); viewLimits.SetViewLimit(viewLimitDir, 0.01f, 0.01f, 0.f, 0.f, SViewLimitParams::eVLS_Item); m_previousVehicleRotation = vehicleRotation; } //Reset the pitch/roll view angles over time Quat viewDirFinal = pPlayer->GetViewQuatFinal(); Ang3 viewAngles(viewDirFinal); float xAdjustment = (float)__fsel(viewAngles.x, max(-viewAngles.x, -0.5f * timeStep), min(-viewAngles.x, 0.5f * timeStep)); float yAdjustment = (float)__fsel(viewAngles.y, max(-viewAngles.y, -0.5f * timeStep), min(-viewAngles.y, 0.5f * timeStep)); if(xAdjustment || yAdjustment) { pPlayer->AddViewAngles(Ang3(xAdjustment, yAdjustment, 0.f)); } } } } }
void CWeapon::NetUpdateFireMode(SEntityUpdateContext& ctx) { // CGunTurret and CVehicleWeapon overide NetAllowUpdate to perform their own checks. if(NetAllowUpdate(true)) { m_netNextShot -= ctx.fFrameTime; if(IsReloading()) return; // reloading, bail if((!m_isFiringStarted) && (m_isFiring || m_shootCounter > 0)) { m_isFiringStarted = true; m_netNextShot = 0.f; NetStartFire(); EnableUpdate(true, eIUS_FireMode); } if(m_fm) { if(m_shootCounter > 0 && m_netNextShot <= 0.0f) { // Aside from the prediction handle, needed for the server, NetShoot/Ex parameters // are no longer used, these will need removing when the client->server RMI's are tided up m_fm->NetShoot(Vec3(0.f, 0.f, 0.f), 0); m_shootCounter--; //if fireRate == 0.0f, set m_netNextShot to 0.0f, otherwise increment by 60.f / fireRate. // fres used to avoid microcoded instructions, fsel to avoid branching - Rich S const float fRawFireRate = m_fm->GetFireRate(); const float fFireRateSelect = -fabsf(fRawFireRate); const float fFireRateForDiv = (float)__fsel(fFireRateSelect, 1.0f, fRawFireRate); const float fNextShot = (float)__fsel(fFireRateSelect, 0.0f, m_netNextShot + (60.f * __fres(fFireRateForDiv))); m_netNextShot = fNextShot; } } if(m_isFiringStarted && !m_isFiring && m_shootCounter <= 0) { m_isFiringStarted = false; NetStopFire(); EnableUpdate(false, eIUS_FireMode); } // this needs to happen here, or NetStopFire interrupts the animation if(m_doMelee && m_melee) { m_melee->NetAttack(); m_doMelee= false; } } }
void CPlayerRotation::ProcessNormal( float frameTime ) { #ifdef ENABLE_NAN_CHECK //create a matrix perpendicular to the ground Vec3 up(0,0,1); //..or perpendicular to the linked object Z SLinkStats *pLinkStats = &m_player.m_linkStats; if (pLinkStats->linkID && pLinkStats->flags & SLinkStats::LINKED_FREELOOK) { IEntity *pLinked = pLinkStats->GetLinked(); if (pLinked) up = pLinked->GetRotation().GetColumn2(); } const Vec3 right(m_baseQuat.GetColumn0()); const Vec3 forward((up % right).GetNormalized()); PR_CHECKQNAN_VEC(up); PR_CHECKQNAN_VEC(right); #endif //ENABLE_NAN_CHECK const Ang3 vNewDeltaAngles = m_deltaAngles * m_player.m_stats.flashBangStunMult; #ifdef PLAYER_MOVEMENT_DEBUG_ENABLED m_player.DebugGraph_AddValue("AimDeltaH", vNewDeltaAngles.z); m_player.DebugGraph_AddValue("AimDeltaV", vNewDeltaAngles.x); #endif Ang3 newViewAngles; newViewAngles.Set(m_viewAngles.x + vNewDeltaAngles.x, m_viewAngles.y, m_viewAngles.z + vNewDeltaAngles.z); newViewAngles += m_externalAngles; //These values need to be used because the player rotation is a quat and quaternions wrap on 720 degrees newViewAngles.z = (float)__fsel( newViewAngles.z - (2.0f * gf_PI2), newViewAngles.z - (4.0f * gf_PI2), newViewAngles.z); newViewAngles.z = (float)__fsel(-(newViewAngles.z + (2.0f * gf_PI2)), newViewAngles.z + (4.0f * gf_PI2), newViewAngles.z); m_viewAngles = newViewAngles; if (m_player.CanTurnBody()) { m_baseQuat = Quat::CreateRotationZ(newViewAngles.z); } newViewAngles.y += m_viewRoll; m_viewQuat.SetRotationXYZ(newViewAngles); m_deltaAngles = vNewDeltaAngles; if(!m_player.GetLinkedVehicle()) { CHANGED_NETWORK_STATE_REF(m_player, CPlayer::ASPECT_INPUT_CLIENT); } }
void CCinematicInput::UpdateAdditiveCameraInput(IScriptSystem *pScriptSystem, float frameTime) { float lookUpLimit = 0.0f, lookDownLimit = 0.0f; float lookLeftLimit = 0.0f, lookRightLimit = 0.0f; pScriptSystem->GetGlobalValue("Cinematic_CameraLookUp", lookUpLimit); pScriptSystem->GetGlobalValue("Cinematic_CameraLookDown", lookDownLimit); pScriptSystem->GetGlobalValue("Cinematic_CameraLookLeft", lookLeftLimit); pScriptSystem->GetGlobalValue("Cinematic_CameraLookRight", lookRightLimit); lookUpLimit = DEG2RAD(lookUpLimit); lookDownLimit = DEG2RAD(lookDownLimit); lookLeftLimit = DEG2RAD(lookLeftLimit); lookRightLimit = DEG2RAD(lookRightLimit); CActor *pClientActor = static_cast<CActor *>(g_pGame->GetIGameFramework()->GetClientActor()); if(pClientActor) { CRY_ASSERT(pClientActor->GetActorClass() == CPlayer::GetActorClassType()); CPlayer *pClientPlayer = static_cast<CPlayer *>(pClientActor); IPlayerInput *pIPlayerInput = pClientPlayer->GetPlayerInput(); if(pIPlayerInput && pIPlayerInput->GetType() == IPlayerInput::PLAYER_INPUT) { CPlayerInput *pPlayerInput = static_cast<CPlayerInput *>(pIPlayerInput); Ang3 rawMouseInput = pPlayerInput->GetRawMouseInput() * 0.25f; rawMouseInput.z = - rawMouseInput.z; rawMouseInput.x *= (g_pGameCVars->cl_invertMouse == 0) ? 1.0f : -1.0f; Ang3 rawControllerInput = pPlayerInput->GetRawControllerInput() + rawMouseInput; //Yaw angle (Z axis) rawControllerInput.z = -clamp((float)__fsel(rawControllerInput.z, rawControllerInput.z * lookRightLimit, rawControllerInput.z * lookLeftLimit), -lookLeftLimit, lookRightLimit); //Pitch angle (X axis) rawControllerInput.x *= (g_pGameCVars->cl_invertController == 0) ? 1.0f : -1.0f; rawControllerInput.x = clamp((float)__fsel(rawControllerInput.x, rawControllerInput.x * lookUpLimit, rawControllerInput.x * lookDownLimit), -lookDownLimit, lookUpLimit); //No roll allowed rawControllerInput.y = 0.0f; Interpolate(m_currentRawInputAngles, rawControllerInput, 2.5f, frameTime); IView *pActiveView = g_pGame->GetIGameFramework()->GetIViewSystem()->GetActiveView(); if(pActiveView) { pActiveView->SetFrameAdditiveCameraAngles(m_currentRawInputAngles); } } } }
//------------------------------------------------------------------------------------ // Adjust the aim dir before we pass it to the torsoAim pose modifier, this allows us // to have the weapon deviate from the camera in certain circumstances // Should only be called once per frame as it time-steps internal vars //------------------------------------------------------------------------------------ void CLocalPlayerComponent::AdjustTorsoAimDir(float fFrameTime, Vec3 &aimDir) { const f32 HALF_PI = gf_PI * 0.5f; float newElevLimit = HALF_PI; const f32 MIN_FLATTEN_LEVEL = -0.3f; const f32 MAX_FLATTEN_LEVEL = -0.1f; const f32 TARGET_FLATTEN_ELEV = -0.2f; const f32 LIMIT_CHANGE_RATE = HALF_PI; if (g_pGameCVars->pl_swimAlignArmsToSurface && m_rPlayer.IsSwimming() && (m_rPlayer.m_playerStateSwim_WaterTestProxy.GetRelativeWaterLevel() > MIN_FLATTEN_LEVEL)) { newElevLimit = (m_rPlayer.m_playerStateSwim_WaterTestProxy.GetRelativeWaterLevel() - MIN_FLATTEN_LEVEL) / (MAX_FLATTEN_LEVEL - MIN_FLATTEN_LEVEL); newElevLimit = LERP(gf_PI * 0.5f, TARGET_FLATTEN_ELEV, clamp_tpl(newElevLimit, 0.0f, 1.0f)); } float limitDelta = LIMIT_CHANGE_RATE * fFrameTime; float limitDiff = newElevLimit - m_stapElevLimit; float smoothedLimit = (float) __fsel(fabs_tpl(limitDiff) - limitDelta, m_stapElevLimit + (fsgnf(limitDiff) * limitDelta), newElevLimit); m_stapElevLimit = smoothedLimit; if (smoothedLimit < HALF_PI) { //--- Need to limit, convert to yaw & elev, limit & then convert back float yaw, elev; float xy = aimDir.GetLengthSquared2D(); if (xy > 0.001f) { yaw = atan2_tpl(aimDir.y,aimDir.x); elev = asin_tpl(clamp_tpl(aimDir.z, -1.f, +1.f)); } else { yaw = 0.f; elev = (float)__fsel(aimDir.z, +1.f, -1.f) * (gf_PI*0.5f); } elev = min(elev, smoothedLimit); float sinYaw, cosYaw; float sinElev, cosElev; sincos_tpl(yaw, &sinYaw, &cosYaw); sincos_tpl(elev, &sinElev, &cosElev); aimDir.x = cosYaw * cosElev; aimDir.y = sinYaw * cosElev; aimDir.z = sinElev; } }
void CScopeReticule::Update(CWeapon* pWeapon) { if (!m_scopeReticuleMaterial || (m_blinkFrequency==0.f)) return; const float frequency = (float)__fsel(-m_blinkFrequency, 12.0f, m_blinkFrequency); const float maxOpacity = 0.99f; float opacity = maxOpacity; if (!pWeapon->CanFire() && !pWeapon->IsDeselecting()) opacity = (float)__fsel(cry_fmod(gEnv->pTimer->GetCurrTime(), 1.0f/frequency)*frequency-0.5f, maxOpacity, 0.0f); m_disabledTimeOut = max(m_disabledTimeOut - gEnv->pTimer->GetFrameTime(), 0.0f); opacity = (float)__fsel(-m_disabledTimeOut, opacity, 0.0f); m_scopeReticuleMaterial->SetGetMaterialParamFloat("opacity", opacity, false); }
void CMFXForceFeedbackEffect::Execute(SMFXRunTimeEffectParams& params) { FUNCTION_PROFILER(gEnv->pSystem, PROFILE_ACTION); if (params.playflags & MFX_PLAY_FORCEFEEDBACK) { float distanceToPlayerSqr = FLT_MAX; IActor *pClientActor = gEnv->pGame->GetIGameFramework()->GetClientActor(); if (pClientActor) { distanceToPlayerSqr = (pClientActor->GetEntity()->GetWorldPos() - params.pos).GetLengthSquared(); } const float testDistanceSqr = clamp_tpl(distanceToPlayerSqr, m_forceFeedbackParams.intensityFallOffMinDistanceSqr, m_forceFeedbackParams.intensityFallOffMaxDistanceSqr); const float minMaxDiffSqr = m_forceFeedbackParams.intensityFallOffMaxDistanceSqr - m_forceFeedbackParams.intensityFallOffMinDistanceSqr; float effectIntensity = (float)__fsel(-minMaxDiffSqr, 0.0f, 1.0f - (testDistanceSqr - m_forceFeedbackParams.intensityFallOffMinDistanceSqr) / (minMaxDiffSqr + FLT_EPSILON)); effectIntensity *= effectIntensity; if (effectIntensity > 0.01f) { IForceFeedbackSystem* pForceFeedback = CCryAction::GetCryAction()->GetIForceFeedbackSystem(); assert(pForceFeedback); ForceFeedbackFxId fxId = pForceFeedback->GetEffectIdByName(m_forceFeedbackParams.forceFeedbackEventName.c_str()); pForceFeedback->PlayForceFeedbackEffect(fxId, SForceFeedbackRuntimeParams(effectIntensity, 0.0f)); } } }
void CGameRulesRSSpawning::UpdateFriendlyPlayerPositionsAndMultipliers( SUsefulSpawnData& spawnData, TPositionList& FriendlyPlayerPositions, TMultiplierList& FriendlyPlayerMultipliers ) { int idx = 0; EntityId friendlyPlayerId = 0; const float fCurrentTime = gEnv->pTimer->GetFrameStartTime().GetMilliSeconds(); const float fDurationWithNoProximityPenalty = 5.0f * 1000.0f; while( friendlyPlayerId = m_pGameRules->GetTeamActivePlayer(spawnData.playerTeamId, idx++)) { const IEntity * pFriendlyPlayer = gEnv->pEntitySystem->GetEntity(friendlyPlayerId); float fPlayerScoreMultiplier = 1.0f; TPlayerDataMap::iterator it = m_playerValues.find(friendlyPlayerId); if (it != m_playerValues.end()) { SPlayerData& friendlyPlayerData = it->second; float fTimeSinceRevived = fCurrentTime - friendlyPlayerData.lastRevivedTime; //If the player has spawned within fDurationWithNoProximityPenalty seconds, there is no // score penalty for spawners near them, to encourage groups spawning together fPlayerScoreMultiplier = (float)__fsel(fTimeSinceRevived - fDurationWithNoProximityPenalty, 1.0f, 0.0f); } FriendlyPlayerMultipliers.push_back(fPlayerScoreMultiplier); FriendlyPlayerPositions.push_back(pFriendlyPlayer->GetPos()); } }
void CPlayerStateSwim_WaterTestProxy::RayTestBottomLevel( const CPlayer& player, const Vec3& referencePosition, float maxRelevantDepth ) { FUNCTION_PROFILER(gEnv->pSystem, PROFILE_GAME); const float terrainWorldZ = gEnv->p3DEngine->GetTerrainElevation(referencePosition.x, referencePosition.y); int rayFlags = geom_colltype_player<<rwi_colltype_bit | rwi_stop_at_pierceable; int entityFlags = ent_terrain|ent_static|ent_sleeping_rigid|ent_rigid; const float padding = 0.2f; // NOTE: Terrain is above m_referencePos, so m_referencePos is probably inside a voxel or something. const float fPosWorldDiff = referencePosition.z - terrainWorldZ; float rayLength = (float)__fsel(fPosWorldDiff, min(maxRelevantDepth, fPosWorldDiff), maxRelevantDepth) + (padding * 2.0f); //We should not have entered this function if still waiting for the last result CRY_ASSERT(m_bottomLevelRayID == 0); m_bottomLevelRayID = g_pGame->GetRayCaster().Queue( player.IsClient() ? RayCastRequest::HighPriority : RayCastRequest::MediumPriority, RayCastRequest(referencePosition + Vec3(0,0,padding), Vec3(0,0,-rayLength), entityFlags, rayFlags, 0, 0), functor(*this, &CPlayerStateSwim_WaterTestProxy::OnRayCastBottomLevelDataReceived)); }
void CVehicleSeatActionOrientateBoneToView::PrePhysUpdate( const float deltaTime ) { Vec3 lookPos = GetCurrentLookPosition(); Vec3 aimPos = GetDesiredAimPosition(); const Ang3 desiredViewAngles = GetDesiredViewAngles(lookPos, aimPos); //Rotating between -Pi and Pi and need to catch the cross over from one to the other to make sure smoothing is in correct direction float yawDif = m_BoneOrientationAngles.z - desiredViewAngles.z; if(fabs(yawDif) > gf_PI) { m_BoneOrientationAngles.z += (float)__fsel(m_BoneOrientationAngles.z, -2.f * gf_PI, 2.f * gf_PI); } SmoothCD<Ang3>(m_BoneOrientationAngles, m_BoneSmoothingRate, deltaTime, desiredViewAngles, m_Sluggishness); IAnimationPoseModifierPtr modPtr = m_poseModifier; m_pVehicle->GetEntity()->GetCharacter(0)->GetISkeletonAnim()->PushPoseModifier(2, modPtr, "VehicleSeat"); Quat vehicleRotation = m_pVehicle->GetEntity()->GetWorldRotation(); Quat headOrientation; headOrientation.SetRotationXYZ(m_BoneOrientationAngles); Quat finalheadOrientation = vehicleRotation.GetInverted()*headOrientation*m_BoneBaseOrientation; m_poseModifier->PushOrientation(m_MoveBoneId, IAnimationOperatorQueue::eOp_Override, finalheadOrientation); }
float CRecoil::GetMaxRecoil() const { float scale = 1.0f; if (IsHoldingBreath()) scale = (float)__fsel(-m_recoilParams.recoil_holdBreathActive_m, 1.0f, m_recoilParams.recoil_holdBreathActive_m); return m_recoilParams.max_recoil * scale; }
void CC4Projectile::UpdateLight(float fFrameTime, bool forceColorChange) { const Matrix34& mat = GetEntity()->GetWorldTM(); m_pLightSource->SetMatrix(mat); SC4ExplosiveParams* pExplosiveParams = m_pAmmoParams->pC4ExplosiveParams; if(pExplosiveParams->pulseBeatsPerSecond > 0.f) { float fNewPulseTimer = m_pulseTimer + (fFrameTime * pExplosiveParams->pulseBeatsPerSecond); float timerScaledToWavelength = fNewPulseTimer * gf_PI; timerScaledToWavelength = (float)__fsel(timerScaledToWavelength - gf_PI2, timerScaledToWavelength - gf_PI2, timerScaledToWavelength); float finalMult = sinf(timerScaledToWavelength) * 0.5f + 0.5f; finalMult *= 1.0f - pExplosiveParams->pulseMinColorMultiplier; finalMult += pExplosiveParams->pulseMinColorMultiplier; m_pulseTimer = fNewPulseTimer; CDLight& light = m_pLightSource->GetLightProperties(); light.SetLightColor(ColorF(m_armed && m_OnSameTeam ? pExplosiveParams->armedLightColour * finalMult : pExplosiveParams->disarmedLightColour * finalMult)); } else if(forceColorChange) { CDLight& light = m_pLightSource->GetLightProperties(); light.SetLightColor(ColorF(m_armed && m_OnSameTeam ? pExplosiveParams->armedLightColour : pExplosiveParams->disarmedLightColour)); } }
void CRecoil::RecoilShoot(bool firstShot, float maxRecoil) { float attack = firstShot ? m_recoilParams.first_attack : m_recoilParams.attack; attack = (float)__fsel(attack, attack, m_recoilParams.attack); m_attack = attack; m_recoil_time = m_recoilParams.recoil_time; if (m_recoil_time == 0.0f) m_recoil = clamp(m_recoil + m_attack, 0.0f, maxRecoil); Vec2 direction = Vec2(ZERO); const int recoilHintsCount = m_pRecoilHints ? m_pRecoilHints->hints.size() : 0; if (recoilHintsCount > 0) { direction = m_pRecoilHints->hints[m_recoil_dir_idx]; m_recoil_dir_idx = (m_recoil_dir_idx+1) % recoilHintsCount; } const Vec3 randomDirectionAdd = Vec3( Random(m_recoilParams.randomness), BiRandom(m_recoilParams.randomness), Random(m_recoilParams.tilt)); m_recoil_dir = direction.GetNormalized() + randomDirectionAdd; CRecoilDebugDraw::AddRecoilPoint(m_recoil_dir, m_recoil); }
//--------------------------------------------------------------- void CPlayerRotation::ProcessNormalRoll( float frameTime ) { //apply lean/roll float rollAngleGoal(0); const Vec3 velocity = m_player.GetActorPhysics().velocity; const float speed2( velocity.len2()); if ((speed2 > 0.01f) && m_player.m_stats.inAir) { const float maxSpeed = m_player.GetStanceMaxSpeed(STANCE_STAND); const float maxSpeedInverse = (float)__fsel(-maxSpeed, 1.0f, __fres(maxSpeed + FLT_EPSILON)); const Vec3 velVec = velocity * maxSpeedInverse; const float dotSide(m_viewQuat.GetColumn0() * velVec); rollAngleGoal -= DEG2RAD(dotSide * 1.5f);; } const float tempLean = m_leanAmount; const float leanAmountMultiplier = 3.0f; const float leanAmount = clamp_tpl(tempLean * leanAmountMultiplier, -1.0f, 1.0f); rollAngleGoal += DEG2RAD(leanAmount * m_player.m_params.leanAngle); Interpolate(m_viewRoll,rollAngleGoal,9.9f,frameTime); m_deltaAngles += m_angularImpulseDelta; }
//------------------------------------------------------------------------ bool CItem::PlayFragment(IAction* pAction, float speedOverride, float timeOverride, float animWeight, float ffeedbackWeight, bool concentratedFire) { _smart_ptr<IAction> pActionPtr(pAction); CRY_ASSERT(pAction); if(!pAction) { return false; } CWeapon *pWeapon = static_cast<CWeapon*>(GetIWeapon()); if (pWeapon && pWeapon->IsProxyWeapon()) { return false; } bool success = false; float speed = (float)__fsel(-speedOverride, 1.0f, speedOverride); FragmentID fragID = pAction->GetFragmentID(); pAction->SetSubContext(m_subContext); IActionController *pActionController = GetActionController(); if ((fragID != FRAGMENT_ID_INVALID) && pActionController) { float fragmentDuration, transitionDuration; if (pActionController->QueryDuration(*pAction, fragmentDuration, transitionDuration)) { float duration = fragmentDuration+transitionDuration; if ((duration > 0.0f) && (timeOverride > 0.0f)) { speed = (duration / timeOverride); CRY_ASSERT((speed > 0.0f) && (speed < 99999.0f)); } if(duration > 0.f) { m_animationTime[eIGS_Owner] = (uint32) MAX((duration*1000.0f/speed) - 20, 0.0f); } pAction->SetSpeedBias(speed); pAction->SetAnimWeight(animWeight); if(concentratedFire) { pAction->SetParam(CItem::sActionParamCRCs.concentratedFire, 1.f); } if(ffeedbackWeight != 1.f) { pAction->SetParam(CItem::sActionParamCRCs.ffeedbackScale, ffeedbackWeight); } pActionController->Queue(pAction); success = true; } } return success; }
void CPlayerStateSwim_WaterTestProxy::UpdateSubmergedFraction(const float referenceHeight, const float playerHeight, const float waterLevel) { const float referenceHeightFinal = max(referenceHeight, 1.3f); const float submergedTotal = playerHeight - waterLevel; const float submergedFraction = (float)__fsel(submergedTotal, 0.0f, clamp_tpl(-submergedTotal * __fres(referenceHeightFinal), 0.0f, 1.0f)); SetSubmergedFraction(submergedFraction); }
float EntityEffects::CHeatController::UpdateCoolDown(const float frameTime) { const float cooldownRate = 0.075f; m_baseHeat = clamp(m_baseHeat - (frameTime * cooldownRate), 0.0f, m_baseHeat); m_coolDownHeat = (float)__fsel(-(m_baseHeat - m_coolDownHeat), -1.0f, m_coolDownHeat); return m_baseHeat; }
void EntityEffects::CHeatController::AddHeatPulse( const float intensity, const float time ) { const float currentPulseHeat = (float)__fsel(-m_heatPulse.baseTime, 0.0f, clamp((1.0f - (m_heatPulse.runningTime * (float)__fres(m_heatPulse.baseTime + FLT_EPSILON))) * m_heatPulse.heat, 0.0f, 1.0f)); m_heatPulse.heat = clamp(currentPulseHeat + intensity, 0.0f, 1.0f - m_baseHeat); m_heatPulse.baseTime = clamp((m_heatPulse.baseTime - m_heatPulse.runningTime) + time, 0.0f, 4.5f); //Fixed to maximum of 4.5secs to cool down m_heatPulse.runningTime = 0.0f; }
float CMountedGunController::CalculateAnimationTime(float aimRad) { const float ANIM_ANGLE_RANGE = gf_PI*0.25; float time = cry_fmod(aimRad / ANIM_ANGLE_RANGE, 1.0f); time = (float)__fsel(time, time, 1.0f + time); return time; }
void CPlayerStateJump::FinalizeVelocity( CPlayer& player, const Vec3& newVelocity ) { const float fNewSpeed = newVelocity.len(); const float fVelocityMultiplier = (float)__fsel(fNewSpeed - 22.0f, __fres(fNewSpeed+FLT_EPSILON) * 22.0f, 1.0f); // TODO: Maybe we should tell physics about this new velocity ? Or maybe SPlayerStats::velocity ? (stephenn). player.GetMoveRequest().velocity = newVelocity * fVelocityMultiplier; }
void CStickyProjectile::CalculateLocationForStick( const IEntity& projectile, const Vec3& collPos, const Vec3& collNormal, QuatT& outLocation ) const { if(m_flags&eSF_OrientateToCollNormal) { const float bigz = cry_fabsf(collNormal.z)-cry_fabsf(collNormal.y); const Vec3 temp(0.f,(float)__fsel(bigz,1.f,0.f),(float)__fsel(bigz,0.f,1.f)); outLocation.q = Quat(Matrix33::CreateOrientation( temp.Cross(collNormal), -collNormal, 0)); AABB aabb; projectile.GetLocalBounds(aabb); outLocation.t = collPos + (outLocation.q.GetColumn2() * ((aabb.max.y-aabb.min.y)*0.5f)); } else { outLocation.q = projectile.GetRotation(); outLocation.t = collPos + (outLocation.q.GetColumn1() * 0.1f); } }
void CNetPlayerInput::UpdateErrorSnap(const Vec3 &entPos, const Vec3 &desiredPos, f32 netPosDist, const Vec3 &desPosOffset, const CTimeValue &curTime) { if (g_pGameCVars->pl_velocityInterpAlwaysSnap) { //--- Snap to target m_pPlayer->GetEntity()->SetPos(desiredPos); m_passedNetPos = true; m_passedPredictionPos = true; } else if (curTime > m_nextBCTime && !(m_pPlayer->m_stats.inFreefall.Value() > 0)) { //--- Breadcrumbs dropped for simulated annealing, whilst the player is blocked we reduce the maximum //--- allowed offset until the character is snapped to the last net position Vec3 prevOffset = entPos - m_breadCrumb; bool blocked = false; if (!m_passedNetPos) { float moveDist = prevOffset.Dot(desPosOffset) / netPosDist; float moveSpeed = moveDist / k_timePerBC; blocked = ((moveSpeed / m_netLerpSpeed) <= k_BCMovingRatio); } if (blocked) { m_blockedTime += k_timePerBC; } else { m_blockedTime = 0.0f; } m_breadCrumb = entPos; m_nextBCTime = curTime+k_timePerBC; Vec3 v0(desiredPos.x, desiredPos.y, 0.0f); Vec3 v1(m_predictedPosition.x, m_predictedPosition.y, 0.0f); Vec3 pt(entPos.x, entPos.y, 0.0f); Lineseg validPath(v0, v1); float t; float distSqrXY = Distance::Point_LinesegSq(pt, validPath, t); float heightDiff = m_predictedPosition.z - entPos.z; float blockedFactor = (1.0f - (m_blockedTime / k_maxBlockTime)); float maxDistXY = !m_passedNetPos ? blockedFactor * k_maxInterpolateDist : k_reachedTargetAllowedDeviation; float timeOnGround = m_pPlayer->GetActorStats()->onGround; float allowedHeightDiff = (float)__fsel(timeOnGround - k_onGroundTime, k_allowedHeightDiff, k_allowedHeightDiffInAir); if ((distSqrXY > (maxDistXY * maxDistXY)) || (cry_fabsf(heightDiff) > allowedHeightDiff)) { //--- Snap to target m_pPlayer->GetEntity()->SetPos(desiredPos); m_passedNetPos = true; const bool isfallen = m_pPlayer->m_stats.inFreefall.Value()==1; } } }
float CGameRulesRSSpawning::GetScoreFromProximityToFriendlies( SUsefulSpawnData& spawnData, TPositionList& FriendlyPlayerPositions, TMultiplierList& FriendlyScoreMultipliers, const Vec3& potentialSpawnPosition ) { SpawnLogAlways("[SPAWN] > GetScoreFromProximityToFriendlies()"); float fScoreFromFriendlies = 0.0f; if(spawnData.numActiveFriendlyPlayers > 0) { const float fIdealMax = 30.0f; const float fIdealMin = 15.0f; const float fCloseFriendlyScoreMultiplier = 500.0f; const float fFarFriendlyScoreMultiplier = 2.0f; float fClosestFriendlySq = FLT_MAX; int index = 0; for(int i = FriendlyPlayerPositions.size() - 1; i >= 0; i--) { Vec3 diff = (FriendlyPlayerPositions[i] - potentialSpawnPosition); //This will bias against using spawn positions near in X/Y but on a different level in Z float fZBiasDistanceFromFriendlySq = (diff.x * diff.x) + (diff.y * diff.y) + fabsf(diff.z * diff.z * diff.z); if(fZBiasDistanceFromFriendlySq < fClosestFriendlySq) { fClosestFriendlySq = fZBiasDistanceFromFriendlySq; index = i; } } float fClosestFriendly = sqrt_fast_tpl(fClosestFriendlySq); if(fClosestFriendly < fIdealMin) { const float fAbortDist = 0.7f; //If the sapwn is within this distance of a friendly, we're going to be intersecting - abort const float fDiff = (fIdealMin - fClosestFriendly); const float fDistanceScore = (float)__fsel(fDiff - fAbortDist, fDiff, sqr(fDiff) * 10.0f); fScoreFromFriendlies = fDiff * fCloseFriendlyScoreMultiplier * FriendlyScoreMultipliers[index]; } else { const float fIdealSub = (fIdealMin + fIdealMax) * 0.5f; const float fIdealRadius = fabsf(fIdealMax - fIdealSub); fScoreFromFriendlies = max(fabsf(fClosestFriendly - fIdealSub) - fIdealRadius, 0.0f) * fFarFriendlyScoreMultiplier; } SpawnLogAlways("[SPAWN] >> Total Score from Friendlies: %.6f, closest was at %.2f, spawn time modifier %s", fScoreFromFriendlies, fClosestFriendly, FriendlyScoreMultipliers[index] < 1.0f ? "APPLIED" : "NOT APPLIED"); } return fScoreFromFriendlies; }
EStatus Update(float timePassed) { if (IsTransitioningOut()) { const float ROTATION_LERP_SPEED = 10.0f; //--- Blend body rotation to match current view Ang3 targetViewDir = m_player.GetAngles(); Quat targetRotation = Quat::CreateRotationZ(targetViewDir.z); Quat newRotation = Quat::CreateNlerp(m_player.GetEntity()->GetRotation(), targetRotation, timePassed*ROTATION_LERP_SPEED); m_player.GetEntity()->SetRotation(newRotation); } else { static uint32 leanParamCRC = gEnv->pSystem->GetCrc32Gen()->GetCRC32Lowercase("SlideFactor"); const Matrix34 &worldTM = m_player.GetEntity()->GetWorldTM(); const Vec3 baseRgt = worldTM.GetColumn0(); const Vec3 baseFwd = worldTM.GetColumn1(); const Vec3 lookFwd = m_player.GetViewQuatFinal().GetColumn1(); const float leanAngle = cry_acosf(baseFwd.Dot(lookFwd)); float targetLeanFactor = clamp(leanAngle / MAX_LEAN_ANGLE, 0.0f, 1.0f); if (baseRgt.Dot(lookFwd) < 0.0f) { targetLeanFactor *= -1.0f; } CWeapon *pWeapon = m_player.GetWeapon(m_player.GetCurrentItemId()); if (pWeapon) { IFireMode *pFiremode = pWeapon->GetFireMode(pWeapon->GetCurrentFireMode()); if (pFiremode && (pFiremode->GetNextShotTime() > 0.0f)) { targetLeanFactor = 0.0f; } } const float delta = targetLeanFactor - m_leanFactor; const float step = LEAN_RATE * timePassed; const float newLeanFactor = (float)__fsel(delta, min(m_leanFactor + step, targetLeanFactor), max(m_leanFactor - step, targetLeanFactor)); SWeightData weightData; weightData.weights[0] = newLeanFactor; SetParam(leanParamCRC, weightData); m_leanFactor = newLeanFactor; if (GetRootScope().IsDifferent(m_fragmentID, m_fragTags)) { SetFragment(m_fragmentID, m_fragTags); } } return TPlayerAction::Update(timePassed); }
//----------------------------------------------------------------------- bool CSpectacularKill::ObstacleCheck(const Vec3& vKillerPos, const Vec3& vTargetPos, const SSpectacularKillAnimation& anim) const { // [*DavidR | 13/Sep/2010] ToDo: Find a way to make this asynchronously const float OBSTACLE_CHECK_RADIUS = 0.6f; const float OBSTACLE_CHECK_GROUND_OFFSET = 0.2f; const Vec3& vCapsuleKillerEnd = vKillerPos + anim.vKillerObstacleCheckOffset; primitives::capsule capsPrim; const Vec3& vKillerToTargetDist = vTargetPos - vCapsuleKillerEnd; capsPrim.axis = vKillerToTargetDist.GetNormalized(); capsPrim.r = OBSTACLE_CHECK_RADIUS; // hh is actually half the total height (it's measured from the center) capsPrim.hh = static_cast<float>(__fsel(anim.fObstacleCheckLength, (anim.fObstacleCheckLength * 0.5f) - capsPrim.r, (min(g_pGameCVars->g_spectacularKill.maxDistanceError, vKillerToTargetDist.GetLength()) * 0.5f) - capsPrim.r)); capsPrim.center = vCapsuleKillerEnd + (capsPrim.axis * (capsPrim.hh + capsPrim.r)); capsPrim.center.z += capsPrim.r + OBSTACLE_CHECK_GROUND_OFFSET; geom_contact* pContact = NULL; int collisionEntityTypes = ent_static | ent_terrain | ent_sleeping_rigid | ent_ignore_noncolliding; float d = gEnv->pPhysicalWorld->PrimitiveWorldIntersection(capsPrim.type, &capsPrim, Vec3Constants<float>::fVec3_Zero, collisionEntityTypes, &pContact, 0, geom_colltype0); bool bObstacleFound = (d != 0.0f) && pContact; #ifndef _RELEASE if (bObstacleFound && (g_pGameCVars->g_spectacularKill.debug > 1)) { const float fTime = 6.0f; // visually show why it failed IPersistantDebug* pPersistantDebug = BeginPersistantDebug(); // Draw a capsule using a cylinder and two spheres const ColorF debugColor = Col_Coral * ColorF(1.0f, 1.0f, 1.0f, 0.6f); pPersistantDebug->AddCylinder(capsPrim.center, capsPrim.axis, capsPrim.r, capsPrim.hh * 2.0f, debugColor, fTime); pPersistantDebug->AddSphere(capsPrim.center - (capsPrim.axis * capsPrim.hh), capsPrim.r, debugColor, fTime); pPersistantDebug->AddSphere(capsPrim.center + (capsPrim.axis * capsPrim.hh), capsPrim.r, debugColor, fTime); for (int i = 0; i < (int)d; ++i) { // Draw the collision point geom_contact collisionData(pContact[i]); pPersistantDebug->AddCone(collisionData.pt, -collisionData.n, 0.1f, 0.8f, Col_Red, fTime + 2.0f); } } #endif return bObstacleFound; }
void CalcLowpassCoeffs( float Fc, float Q, vector4_out coeffsA, vector4_out coeffsB ) { Q = ( float )__fsel( Q, Q, .0001f ); Fc = ( float )__fsel( Fc, Fc, FLT_EPSILON * 2.0f ); float w0 = ( float )M_PI * Fc; float sin0 = sin( w0 ); float cos0 = cos( w0 ); float alpha = sin0 / ( 2.0f * Q ); float a0 = alpha + 1.0f; coeffsA.v[0] = ( -2.0f * cos0 ) / a0; coeffsA.v[1] = ( 1.0f - alpha ) / a0; coeffsA.v[2] = 0.0f; coeffsA.v[3] = 0.0f; coeffsB.v[0] = ( ( 1.0f - cos0 ) / 2.0f ) / a0; coeffsB.v[1] = ( 1.0f - cos0 ) / a0; coeffsB.v[2] = ( ( 1.0f - cos0 ) / 2.0f ) / a0; coeffsB.v[3] = 0.0f; }
bool CPlayerStateJump::UpdateCommon( CPlayer& player, const bool isHeavyWeapon, const Vec3 &move, float frameTime, Vec3* pDesiredVel ) { GetDesiredVelocity(move, player, pDesiredVel); const SActorPhysics& actorPhysics = player.GetActorPhysics(); // generate stats. if (actorPhysics.velocity*actorPhysics.gravity>0.0f) { const float fHeightofEntity = player.GetEntity()->GetWorldTM().GetTranslation().z; m_startFallingHeight= (float)__fsel(-player.m_stats.fallSpeed, fHeightofEntity, max(m_startFallingHeight, fHeightofEntity)); player.m_stats.fallSpeed = -actorPhysics.velocity.z; } if (!gEnv->bMultiplayer && player.IsInPickAndThrowMode() && (player.m_stats.fallSpeed > 10.f)) player.ExitPickAndThrow(); // inAir is set to 0.0f if we're swimming later - before refactoring this test happened *after* that, hence this test is here. m_jumpLock = (float)__fsel(-fabsf(player.m_stats.inAir), max(0.0f, m_jumpLock - frameTime), m_jumpLock); return true; }
void CVehicleMovementHelicopter::CalculatePitch(const Ang3& worldAngles, const Vec3& desiredMoveDir, float currentSpeed2d, float desiredSpeed, float deltaTime) { static const float kSpeedToPitchFactor = 100.0f; float desiredPitch = -static_cast<float>(__fsel(currentSpeed2d - desiredSpeed * 0.50f, currentSpeed2d, currentSpeed2d * kSpeedToPitchFactor)) / m_maxSpeed * gf_PI * 0.25f; desiredPitch += m_steeringDamage.x; Limit(desiredPitch, -m_maxPitchAngle - m_steeringDamage.x, m_maxPitchAngle + m_steeringDamage.x); //additional pitch due to path slope is max 90 degrees float upDown = GetAdditionalSlopePitch(desiredMoveDir); float upDownAbs = fabsf(upDown); m_actionPitch = worldAngles.x + (desiredPitch - worldAngles.x + upDown) * deltaTime; Limit(m_actionPitch, -m_maxPitchAngle - upDownAbs * 0.1f , m_maxPitchAngle + upDownAbs); }