void OnUpdate( SActivationInfo* pActInfo ) { const Vec3 positionOffsetLocal = GetPortVec3( pActInfo, PORT_IN_POSITION_OFFSET_LOCAL ); const float maxDistance = max( 0.f, GetPortFloat( pActInfo, PORT_IN_MAX_LENGTH ) ); const CCamera& camera = GetISystem()->GetViewCamera(); const Vec3 cameraDirection = camera.GetViewdir(); const Vec3 cameraPositionWorld = camera.GetPosition(); const Matrix33 cameraOrientation = Matrix33::CreateRotationVDir( cameraDirection ); const Vec3 positionOffsetWorld = cameraOrientation * positionOffsetLocal; const Vec3 rayOriginWorld = cameraPositionWorld + positionOffsetWorld; const Vec3 raySegment = cameraDirection * maxDistance; IPhysicalWorld* pWorld = gEnv->pPhysicalWorld; const int objectTypes = ent_all; const unsigned int raycastFlags = rwi_stop_at_pierceable | rwi_colltype_any; ray_hit hit; const int hitCount = pWorld->RayWorldIntersection( rayOriginWorld, raySegment, objectTypes, raycastFlags, &hit, 1 ); float hitDistance = maxDistance; if ( 0 < hitCount ) { hitDistance = hit.dist; } const float timeDelta = 0.1f; const float smoothTime = max( 0.f, GetPortFloat( pActInfo, PORT_IN_SMOOTH_TIME ) ); SmoothCD( m_smoothedHitDistance, m_hitDistanceChangeRate, timeDelta, hitDistance, smoothTime ); ActivateOutput( pActInfo, PORT_OUT_FOCUS_DISTANCE, m_smoothedHitDistance ); const float focusRangeFactor = max( 0.f, GetPortFloat( pActInfo, PORT_IN_FOCUS_RANGE_FACTOR ) ); const float focusRange = focusRangeFactor * m_smoothedHitDistance; ActivateOutput( pActInfo, PORT_OUT_FOCUS_RANGE, focusRange ); const bool drawDebugInfo = GetPortBool( pActInfo, PORT_IN_DEBUG_ENABLED ); if ( ! drawDebugInfo ) { return; } IRenderer* pRenderer = gEnv->pRenderer; IRenderAuxGeom* pRenderAuxGeom = pRenderer->GetIRenderAuxGeom(); ColorB rayColor = ( 0 < hitCount ) ? ColorB( 255, 255, 0 ) : ColorB( 255, 0, 0 ); pRenderAuxGeom->DrawSphere( hit.pt, 0.1f, rayColor ); pRenderAuxGeom->DrawLine( rayOriginWorld, rayColor, hit.pt, rayColor ); }
void CIntersectionAssistanceUnit::DebugUpdate() const { if(g_pGameCVars->pl_pickAndThrow.intersectionAssistDebugEnabled) { IEntity* pEntity = gEnv->pEntitySystem->GetEntity(m_subjectEntityId); if(pEntity) { IPhysicalEntity *pPhysical = pEntity->GetPhysics(); if(pPhysical) { const float fFontSize = 1.2f; float drawColor[4] = {1.0f, 1.0f, 1.0f, 1.0f}; string sMsg(string().Format(" Entity ID: [%d]", m_subjectEntityId)); sMsg += string().Format("\n Entity Name: [%s]", pEntity->GetName()); sMsg += string().Format("\n EmbedTimer: [%.3f]", m_embedTimer); sMsg += string().Format("\n EmbedState: [%s]",(m_embedState == eES_None) ? "NONE" : (m_embedState == eES_Evaluating) ? "EVALUATING" : (m_embedState == eES_ReEvaluating) ? "REEVALUATING" : (m_embedState == eES_NotEmbedded) ? "NOT EMBEDDED" : (m_embedState == eES_Embedded) ? "EMBEDDED" : "UNKNOWN"); Vec3 vCurrTrans = m_entityStartingWPos - pEntity->GetWorldPos(); sMsg += string().Format("\n Translation: < %.3f, %.3f, %.3f >", vCurrTrans.x, vCurrTrans.y, vCurrTrans.z ); sMsg += string().Format("\n Trans magnitude: < %.3f >", vCurrTrans.GetLength() ); sMsg += string().Format("\n Trans per sec: < %.3f >", vCurrTrans.GetLength() / g_pGameCVars->pl_pickAndThrow.intersectionAssistTimePeriod ); sMsg += string().Format("\n Collision count: %u", m_collisionCount ); // RENDER Vec3 vDrawPos = pEntity->GetWorldPos() + Vec3(0.0f,0.0f,0.6f); gEnv->pRenderer->DrawLabelEx(vDrawPos, fFontSize, drawColor, true, true, sMsg.c_str()); // Box pe_params_bbox bbox; if(pPhysical->GetParams(&bbox)) { ColorB colDefault = ColorB( 127,127,127 ); ColorB embedded = ColorB(255, 0, 0); ColorB notEmbedded = ColorB(0, 255, 0); gEnv->pRenderer->GetIRenderAuxGeom()->DrawAABB( AABB(bbox.BBox[0],bbox.BBox[1]), Matrix34(IDENTITY), false, (m_embedState == eES_Embedded) ? embedded : (m_embedState == eES_NotEmbedded) ? notEmbedded : colDefault, eBBD_Faceted); } } } } }
void CToolboxApplication::SetupDefaultStyle() { m_toolboxStyle = SToolboxStyle(); m_toolboxStyle.backgroundColor = ColorF(239 / 255.f, 239 / 255.f, 242 / 255.f); m_toolboxStyle.viewportClearColor = ColorF(0.f); m_toolboxStyle.toolWindowBorderColor = ColorB(214, 214, 214); m_toolboxStyle.delimiterColor = ColorB(150, 150, 147); m_toolboxStyle.delimiterSize = 5; m_toolboxStyle.topBarHeight = 35; m_toolboxStyle.infoBarHeight = 25; m_toolboxStyle.moverColor = ColorB(150, 150, 147); m_toolboxStyle.moverSize = 9; m_toolboxStyle.activeTabColor = ColorB(90, 142, 194); m_toolboxStyle.tabHeight = 20; m_toolboxStyle.tabWidthOffset = 25; m_toolboxStyle.tabPaddingX = 4; m_toolboxStyle.tabPaddingY = 2; m_toolboxStyle.tabFontSize = 16.f; m_toolboxStyle.tabFontColor = ColorB(51, 51, 51); m_toolboxStyle.activeTabFontColor = ColorB(255, 255, 255); m_toolboxStyle.pFont = gEnv->pCryFont->GetFont("roboto"); m_toolboxStyle.defaultFontColor = ColorB(51, 51, 51); }
void gkAuxRenderer::AuxRenderText(const TCHAR* text, int posx, int posy, const IFtFont* font, const ColorB& color, uint32 alignment, uint32 style ) { if (style) { gEnv->pFont->DrawString( text, font, Vec2(posx + 1, posy + 1), ColorB(0,0,0,127), alignment ); } // gEnv->pFont->DrawString( text, font, Vec2(posx, posy), color, alignment ); //gEnv->pFont->DrawString( it->text, it->font, Vec2(it->posx, it->posy), it->color, it->alignment ); }
//------------------------------------------------------------------------ //chr safe to remove? bool CGunTurret::IsTargetCloaked(IActor *pActor) const { // cloak check if(m_turretparams.find_cloaked) return false; bool cloaked = false; // if destinationId assigned, target can always be found if(m_destinationId && pActor->GetEntityId() == m_destinationId) return false; if(cloaked && m_turretparams.light_fov != 0.f) { // if cloaked, target can only be found with searchlight // check if target inside light cone const Matrix34 &weaponTM = GetEntity()->GetSlotWorldTM(eIGS_ThirdPerson); Vec3 wpos(weaponTM.GetTranslation()); Vec3 wdir(weaponTM.GetColumn1()); Vec3 tpos(GetTargetPos(pActor->GetEntity())); float epsilon = 0.8f; Quat rot = Quat::CreateRotationAA(epsilon*0.5f*DEG2RAD(m_turretparams.light_fov), weaponTM.GetColumn2()); Vec3 a = wpos + m_turretparams.mg_range*(wdir*rot); Vec3 b = wpos + m_turretparams.mg_range*(wdir*rot.GetInverted()); bool inside = Overlap::PointInTriangle(tpos, wpos, a, b, weaponTM.GetColumn2()); if(inside) { rot = Quat::CreateRotationAA(0.5f*DEG2RAD(m_turretparams.light_fov), weaponTM.GetColumn0()); a = wpos + m_turretparams.mg_range*(wdir*rot); b = wpos + m_turretparams.mg_range*(wdir*rot.GetInverted()); inside = Overlap::PointInTriangle(tpos, wpos, a, b, weaponTM.GetColumn0()); } cloaked = !inside; if(g_pGameCVars->i_debug_turrets == eGTD_Search) { IRenderAuxGeom *pGeom = gEnv->pRenderer->GetIRenderAuxGeom(); pGeom->SetRenderFlags(e_Def3DPublicRenderflags); float color[] = {1,1,1,1}; Vec3 points[] = {wpos, a, b}; pGeom->DrawPolyline(points, 3, true, ColorB(0,255,0,255)); if(inside) gEnv->pRenderer->Draw2dLabel(200,200,1.4f,color,false,"target inside cone"); } } return cloaked; }
void CHeavyMountedWeapon::Update( SEntityUpdateContext& ctx, int slot ) { BaseClass::Update(ctx, slot); if (m_rotatingSoundID!=INVALID_SOUNDID) { if (m_RotationSoundTimeOut>0) { m_RotationSoundTimeOut -= ctx.fFrameTime; RequireUpdate( eIUS_General ); } else { StopSound(m_rotatingSoundID); m_rotatingSoundID = INVALID_SOUNDID; } } // Helper for editor placing if (gEnv->IsEditing()) { // If host id is not 0, it means it is mounted to a vehicle, so don't render the helper in that case if (!GetHostId()) { IRenderAuxGeom* pRenderAux = gEnv->pRenderer->GetIRenderAuxGeom(); const Matrix34& weaponTM = GetEntity()->GetWorldTM(); const Vec3 point1 = weaponTM.GetTranslation(); const Vec3 point2 = point1 - (m_sharedparams->pMountParams->ground_distance * weaponTM.GetColumn2()); const Vec3 point3 = point2 - (m_sharedparams->pMountParams->body_distance * weaponTM.GetColumn1()); pRenderAux->DrawLine(point1, ColorB(0, 192, 0), point2, ColorB(0, 192, 0), 3.0f); pRenderAux->DrawLine(point2, ColorB(0, 192, 0), point3, ColorB(0, 192, 0), 3.0f); pRenderAux->DrawSphere(point3, 0.15f, ColorB(192, 0, 0)); RequireUpdate(eIUS_General); } } }
void GUIGadget::drawBgRect( const dim::rect2di &DrawRect, const dim::rect2di &MouseRect, bool isSwaped, bool isAlwaysUsing, s32 UsageType) { const f32 Factor = ( isEnabled_ && Usable_ && ( mouseOver(MouseRect) || ( isAlwaysUsing && usage() ) ) ? 0.8f : 0.6f ); video::color ColorA(Color_), ColorB(Color_ * Factor); if ( ( UsageType == -1 && usage() ) || usage(UsageType) ) std::swap(ColorA, ColorB); if (isSwaped) std::swap(ColorA, ColorB); GlbRenderSys->draw2DRectangle(DrawRect, ColorA, ColorA, ColorB, ColorB); }
Vec3 CPlayerRotation::GetCloseCombatSnapTargetDirection( const Vec3& aimPos, const Vec3& aimDirection, const SAutoaimTarget& aaTarget ) const { Lineseg targetLine; targetLine.start = aaTarget.secondaryAimPosition; targetLine.end = aaTarget.primaryAimPosition; Lineseg aimLine; aimLine.start = aimPos; aimLine.end = aimPos + (aimDirection * g_pGameCVars->aim_assistMaxDistance); float t0 = -1.0f, t1 = -1.0f; Distance::Lineseg_LinesegSq<float>(targetLine, aimLine, &t0, &t1); if (t0 >= 0.0f) { const Vec3 snapTarget = ((targetLine.start) + ((targetLine.end - targetLine.start) * t0)); #if DBG_AUTO_AIM SAuxGeomRenderFlags oldFlags = gEnv->pRenderer->GetIRenderAuxGeom()->GetRenderFlags(); SAuxGeomRenderFlags newFlags = e_Def3DPublicRenderflags; newFlags.SetAlphaBlendMode(e_AlphaBlended); newFlags.SetDepthTestFlag(e_DepthTestOff); newFlags.SetCullMode(e_CullModeNone); gEnv->pRenderer->GetIRenderAuxGeom()->SetRenderFlags(newFlags); gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(targetLine.start, ColorB(196, 196, 0), targetLine.end, ColorB(196, 196, 0), 4.0f); gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(snapTarget, 0.125f, ColorB(0, 196, 0)); gEnv->pRenderer->GetIRenderAuxGeom()->SetRenderFlags(oldFlags); #endif return (snapTarget - aimPos).GetNormalizedSafe(Vec3Constants<float>::fVec3_OneY); } return ZERO; }
//------------------------------------------------------------------------ void CVehicleMovementTank::Update(const float deltaTime) { CVehicleMovementStdWheeled::Update(deltaTime); #if ENABLE_VEHICLE_DEBUG if (IsProfilingMovement()) { if (m_steeringImpulseMin > 0.f && m_wheelContactsLeft != 0 && m_wheelContactsRight != 0) { const Matrix34& worldTM = m_pVehicle->GetEntity()->GetWorldTM(); Vec3 localVel = worldTM.GetInvertedFast().TransformVector(m_statusDyn.v); Vec3 localW = worldTM.GetInvertedFast().TransformVector(m_statusDyn.w); float speed = m_statusDyn.v.len(); float speedRatio = min(1.f, speed/m_maxSpeed); const float maxW = 0.3f*gf_PI; float steer = abs(m_currSteer)>0.001f ? m_currSteer : 0.f; float desired = steer * maxW; float curr = -localW.z; float err = desired - curr; // err>0 means correction to right Limit(err, -maxW, maxW); if (abs(err) > 0.01f) { float amount = m_steeringImpulseMin + speedRatio*(m_steeringImpulseMax-m_steeringImpulseMin); float corr = -err * amount * m_statusDyn.mass * deltaTime; pe_action_impulse imp; imp.iApplyTime = 1; imp.angImpulse = worldTM.GetColumn2() * corr; float color[] = {1,1,1,1}; gEnv->pRenderer->Draw2dLabel(300,300,1.5f,color,false,"err: %.2f ", err); gEnv->pRenderer->Draw2dLabel(300,320,1.5f,color,false,"corr: %.3f", corr/m_statusDyn.mass); IRenderAuxGeom* pGeom = gEnv->pRenderer->GetIRenderAuxGeom(); float len = 4.f * imp.angImpulse.len() / deltaTime / m_statusDyn.mass; Vec3 dir = (float)-sgn(corr) * worldTM.GetColumn0(); //imp.angImpulse.GetNormalized(); pGeom->DrawCone(worldTM.GetTranslation()+Vec3(0,0,5)-(dir*len), dir, 0.5f, len, ColorB(128,0,0,255)); } } } DebugDrawMovement(deltaTime); #endif }
void CFirstPersonCameraComponent::Update() { auto pPlayer = CPlayerComponent::GetLocalPlayer(); auto pPlayerInput = pPlayer->GetPlayerInput(); // Default on failure is to return a cleanly constructed default matrix. Matrix34 newCameraMatrix = Matrix34::Create(Vec3(1.0f), IDENTITY, ZERO); if (pPlayerInput) { // Resolve the entity. if (auto pEntity = gEnv->pEntitySystem->GetEntity(m_targetEntityID)) { // It's possible there is no actor to query for eye position, in that case, return a safe default // value for an average height person. Vec3 localEyePosition { AverageEyePosition }; // If we are attached to an entity that is an actor we can use their eye position. auto pActor = CActorComponent::GetActor(m_targetEntityID); if (pActor) localEyePosition = pActor->GetLocalEyePos(); // Apply the player input rotation for this frame, and limit the pitch / yaw movement according to the set max and min values. if (pPlayer->GetinteractionState().IsCameraMovementAllowed()) { m_viewPitch -= pPlayerInput->GetMousePitchDelta() - pPlayerInput->GetXiPitchDelta(); m_viewPitch = clamp_tpl(m_viewPitch, DEG2RAD(g_cvars.m_firstPersonCameraPitchMin), DEG2RAD(g_cvars.m_firstPersonCameraPitchMax)); } // Pose is based on entity position and the eye position. // We will use the rotation of the entity as a base, and apply pitch based on our own reckoning. const Vec3 position = pEntity->GetPos() + localEyePosition; const Quat rotation = pEntity->GetRotation() * Quat(Ang3(m_viewPitch, 0.0f, 0.0f)); newCameraMatrix = Matrix34::Create(Vec3(1.0f), rotation, position + rotation * m_pCameraManager->GetViewOffset()); #if defined(_DEBUG) if (g_cvars.m_firstPersonCameraDebug) { gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(position, 0.04f, ColorB(0, 0, 255, 255)); } #endif } } // Store the new matrix for later. m_cameraMatrix = newCameraMatrix; }
void Draw() { IRenderAuxGeom* pRender = gEnv->pRenderer->GetIRenderAuxGeom(); SAuxGeomRenderFlags flags = pRender->GetRenderFlags(); SAuxGeomRenderFlags oldFlags = pRender->GetRenderFlags(); flags.SetDepthWriteFlag(e_DepthWriteOff); flags.SetDepthTestFlag(e_DepthTestOff); pRender->SetRenderFlags(flags); m_timer += gEnv->pTimer->GetFrameTime(); if (m_timer>30.f) m_timer = 0.f; float time = gEnv->pTimer->GetCurrTime(); float dt = (1.f/50.f); Vec3 offset = Vec3(0.f, 0.f, 0.025f + 0.003f*sinf(8.f*m_timer)); Vec3 offset2 = Vec3(0.f, 0.f, 0.035f + 0.003f*sinf(5.f*m_timer)); ColorB desiredColour = ColorB(255,0,0,255); // Red ColorB desiredVelColour = ColorB(255,(int)(128.f+127.f*sinf(8.f*m_timer)),0,255); // Yellow/Red ColorB actualPosColour = ColorB(0,255,0,255); // Green ColorB actualVelColour = ColorB(0,0,(int)(128.f+127.f*sinf(5.f*m_timer)),255); // blue/black ColorB snapPosColour = ColorB(255,255,255,255); // White ColorB lerpErrorColour = ColorB(255,0,0,255); // Red // Draw the desired positions for (unsigned int i=0; i<m_desired.size(); i++) { Desired &d = m_desired[i]; pRender->DrawSphere(d.pos + offset, 0.025f, desiredColour); pRender->DrawLine(d.pos + offset, desiredVelColour, d.pos + offset + d.vel*dt, desiredVelColour); } if(g_pGameCVars->pl_debugInterpolation == 1) // Show entity position + velocity { for (unsigned int i=0; i<m_actual.size(); i++) { Actual &a = m_actual[i]; pRender->DrawSphere(a.pos + offset2, 0.025f, a.snapped ? snapPosColour : actualPosColour); pRender->DrawLine(a.pos + offset2, actualVelColour, a.pos + offset2 + a.vel*dt, actualVelColour); } } if(g_pGameCVars->pl_debugInterpolation == 2) // Show entity position + lerpError { for (unsigned int i=0; i<m_actual.size(); i++) { Actual &a = m_actual[i]; pRender->DrawSphere(a.pos + offset2, 0.025f, a.snapped ? snapPosColour : actualPosColour); pRender->DrawLine(a.pos + offset2, lerpErrorColour, a.pos + offset2 + a.lerpError, lerpErrorColour); } } pRender->SetRenderFlags(oldFlags); }
int CScriptBind_Game::DebugDrawCone( IFunctionHandler *pH, float x, float y, float z, float radius, float height, int r, int g, int b, int a ) { IRenderAuxGeom* pRenderAuxGeom = gEnv->pRenderer->GetIRenderAuxGeom(); if (pRenderAuxGeom) { SAuxGeomRenderFlags oldFlags = pRenderAuxGeom->GetRenderFlags(); SAuxGeomRenderFlags newFlags = oldFlags; newFlags.SetCullMode(e_CullModeNone); newFlags.SetAlphaBlendMode(e_AlphaBlended); pRenderAuxGeom->SetRenderFlags(newFlags); pRenderAuxGeom->DrawCone(Vec3(x,y,z), Vec3(0.f, 0.f, 1.f), radius, height, ColorB(r,g,b,a)); pRenderAuxGeom->SetRenderFlags(oldFlags); } return pH->EndFunction(); }
int CScriptBind_Game::DebugDrawAABB( IFunctionHandler *pH, float x, float y, float z, float x2, float y2, float z2, int r, int g, int b, int a ) { IRenderAuxGeom* pRenderAuxGeom = gEnv->pRenderer->GetIRenderAuxGeom(); if (pRenderAuxGeom) { SAuxGeomRenderFlags oldFlags = pRenderAuxGeom->GetRenderFlags(); SAuxGeomRenderFlags newFlags = oldFlags; newFlags.SetCullMode(e_CullModeNone); newFlags.SetAlphaBlendMode(e_AlphaBlended); pRenderAuxGeom->SetRenderFlags(newFlags); AABB bbox(Vec3(x, y, z), Vec3(x2, y2, z2)); pRenderAuxGeom->DrawAABB(bbox, true, ColorB(r, g, b, a), eBBD_Faceted); pRenderAuxGeom->SetRenderFlags(oldFlags); } return pH->EndFunction(); }
//------------------------------------------------------------------------ void CGameRulesHoldObjectiveBase::DebugDrawCylinder(SHoldEntityDetails *pDetails) { // Draw debug cylinder if(g_pGameCVars->g_holdObjectiveDebug == eHOB_Debug_Draw_Sphere) { IEntity *pHoldEntity = gEnv->pEntitySystem->GetEntity(pDetails->m_id); if (pHoldEntity) { IRenderAuxGeom* pAuxRenderer = gEnv->pRenderer->GetIRenderAuxGeom(); SAuxGeomRenderFlags renderFlags = pAuxRenderer->GetRenderFlags(); renderFlags.SetAlphaBlendMode(e_AlphaBlended); pAuxRenderer->SetRenderFlags(renderFlags); pAuxRenderer->DrawCylinder( pHoldEntity->GetPos()+Vec3(0.f,0.f,pDetails->m_controlOffsetZ+(pDetails->m_controlHeight*0.5f)), Vec3(0.0f,0.0f,1.0f), pDetails->m_controlRadius, pDetails->m_controlHeight, ColorB(255,255,0,128)); } } }
void SearchSpot::DebugDraw(float searchTimeOut) { ColorB spotColor; switch (m_status) { case NotSearchedYet: spotColor = ColorB(0, 0, 255); break; case BeingSearchedRightAboutNow: spotColor = ColorB(255, 255, 0); break; case Searched: spotColor = ColorB(0, 255, 0); break; case Unreachable: spotColor = ColorB(255, 0, 0); break; case SearchedTimingOut: if(searchTimeOut) { uint8 green = (uint8)(255 * clamp_tpl( (m_searchTimeoutLeft / (searchTimeOut / 2.0f)), 0.0f, 1.0f)); uint8 blue = (uint8)(255 * clamp_tpl(((searchTimeOut - m_searchTimeoutLeft) / (searchTimeOut / 2.0f)), 0.0f, 1.0f)); spotColor = ColorB(0, green, blue); } break; } IRenderAuxGeom* pDebugRenderer = gEnv->pRenderer->GetIRenderAuxGeom(); pDebugRenderer->DrawSphere(m_pos, 0.3f, spotColor); if (m_assigneeID) { Agent agent(m_assigneeID); if (agent) pDebugRenderer->DrawLine(agent.GetPos(), ColorB(255, 255, 0), m_pos, ColorB(255, 255, 0), 2.0f); } }
//----------------------------------------------------------------------- void gkObjectManager::Update() { if (ms_pCurrentPick) { if (!m_isDarging) { // update hover states UpdateGizmoHover(ms_objselmode); } else { // update move/rot/scale draging UpdateGizmoDraging(ms_objselmode); } // draw gizmo and Frame // gizmo length float gizmo_len = ms_pCurrentPick->getAABB().GetRadius() > 5.0 ? 5.0 : ms_pCurrentPick->getAABB().GetRadius(); gEnv->pRenderer->getAuxRenderer()->AuxRender3DGird( ms_pCurrentPick->getWorldPosition(), 21, 0.1f, ColorF(0.f,0.f,0.f,0.1f), false ); gEnv->pRenderer->getAuxRenderer()->AuxRenderGizmo( ms_pCurrentPick->GetWorldMatrix(), gizmo_len, ms_selectedAxis, true, ms_objselmode ); gEnv->pRenderer->getAuxRenderer()->AuxRenderMeshFrame( ms_pCurrentPick->getRenderLayer(), ColorF(0,1,0,1) ); //gEnv->pRenderer->getAuxRenderer()->AuxRenderAABB( ms_pCurrentPick->getAABB(), ColorF(1,1,1,0.5) ); Vec2 ptx, pty, ptz, getPt; if( GetIEditor()->getMainViewport()->getScreenPosFromScene(ms_pCurrentPick->getWorldPosition(), getPt) ) { // gizmo text Vec3 posx = ms_pCurrentPick->getWorldPosition() + ms_pCurrentPick->getWorldOrientation().GetColumn0() * (gizmo_len + 2.0f); Vec3 posy = ms_pCurrentPick->getWorldPosition() + ms_pCurrentPick->getWorldOrientation().GetColumn1() * (gizmo_len + 2.0f); Vec3 posz = ms_pCurrentPick->getWorldPosition() + ms_pCurrentPick->getWorldOrientation().GetColumn2() * (gizmo_len + 2.0f); GetIEditor()->getMainViewport()->getScreenPosFromScene(posx, ptx); GetIEditor()->getMainViewport()->getScreenPosFromScene(posy, pty); GetIEditor()->getMainViewport()->getScreenPosFromScene(posz, pty); gEnv->pRenderer->getAuxRenderer()->AuxRenderText( _T("x"), ptx.x, ptx.y, GetIEditor()->getDefaultFont(), ColorF(1,1,1,1), 9u, true); gEnv->pRenderer->getAuxRenderer()->AuxRenderText( _T("y"), pty.x, pty.y, GetIEditor()->getDefaultFont(), ColorF(1,1,1,1), 9u, true); gEnv->pRenderer->getAuxRenderer()->AuxRenderText( _T("z"), ptz.x, ptz.y, GetIEditor()->getDefaultFont(), ColorF(1,1,1,1), 9u, true); gEnv->pRenderer->getAuxRenderer()->AuxRenderText( ms_pCurrentPick->getName().c_str(), getPt.x, getPt.y, GetIEditor()->getDefaultFont(), ColorF(1,1,1,1), eFA_HCenter | eFA_HCenter , true); } } // 绘制特殊gameobjectçš„å›¾æ ‡ [12/31/2014 gameKnife] { const IGameObjectQueue& list = gEnv->pGameObjSystem->GetGameObjects(); for (IGameObjectQueue::const_iterator it = list.begin(); it != list.end(); ++it) { switch( (*it)->getGameObjectSuperClass() ) { case eGOClass_LIGHT: { //m_icon_lightstatic gkTexturePtr light_icon; m_icon_light = gEnv->pSystem->getTextureMngPtr()->load( _T("/engine/assets/textures/editor/icon_light.tga") ); if (!m_icon_light.isNull()) { Vec3 pos = (*it)->getRenderLayer()->getWorldPosition(); Vec2 curcor_pos = GetIEditor()->getMainViewport()->getCursorOnClientScreen(); Vec2 ptx; if( GetIEditor()->getMainViewport()->getScreenPosFromScene(pos, ptx) ) { ColorB color_icon = ColorB(255,255,255,180); if ((curcor_pos - ptx).GetLength() < 16 ) { color_icon = ColorB(0,169,255,180); } if( ms_pCurrentPick == *it ) { color_icon = ColorB(0,169,255,255); } ptx.x -= 16; ptx.y -= 16; gEnv->pRenderer->getAuxRenderer()->AuxRenderScreenBox( ptx, Vec2(32, 32), color_icon, m_icon_light.getPointer() ); } } } break; default: break; } } } }
EMovementTransitionState STransition::Update( const CMovementTransitions& transitions, const STransitionSelectionParams& transParams, const STransitionMatch& match, const Vec3& playerPos, const Vec3& oldMoveDirection, const Vec3& newMoveDirection, float*const pJukeTurnRateFraction, Vec3*const pBodyTarget, const char**const pBodyTargetType, CPlayer*const pPlayer, CMovementTransitionsController*const pController ) const { EMovementTransitionState newState; if (transParams.m_transitionDistance > maxDistance) { // Prepare transition by orienting the body towards the desiredTravelAngle if (match.angleDifference <= prepareTravelAngleTolerance) { // Preparation: turn towards closest juke direction (as we didn't LMG-ize those) float prepare = prepareDistance - maxDistance; *pJukeTurnRateFraction = (prepare > FLT_EPSILON) ? 1.0f - (transParams.m_transitionDistance - maxDistance)/prepare : 0.0f; // starts at 0, builds up to 1 *pBodyTarget = playerPos + (Quat::CreateRotationZ(-desiredTravelAngle) * newMoveDirection); // move bodytarget to be at -desiredTravelAngle from movedirection *pBodyTargetType = "transAdjust"; newState = eMTS_Preparing; } else { newState = eMTS_WaitingForRange; } } else { if (match.angleDifference <= travelAngleTolerance) { if (CheckSpaceToPerformTransition(transitions, transParams, oldMoveDirection, playerPos, pPlayer)) { bool bSignaled = pController->RequestTransition(animGraphSignal.c_str(), this, transParams.m_future); newState = bSignaled ? eMTS_Requesting_Succeeded : eMTS_Requesting_DelayedBecauseControllerRequestFailed; } else { newState = eMTS_Requesting_DelayedBecauseWalkabilityFail; } } else { newState = eMTS_Requesting_DelayedBecauseAngleOutOfRange; } } #ifndef _RELEASE { const ColorB debugColors[eMTS_COUNT] = { ColorB(0, 0, 0), // none - black ColorB(0, 0, 255), // considering - blue ColorB(0, 175, 175), // preparing - green-blue ColorB(0, 255, 0), // requesting succeeded - full green ColorB(128, 0, 0), // request fail - dark red ColorB(255, 0, 0), // travel angle fail - red ColorB(255, 100, 100) // walkability fail - pink }; if (g_pGame->GetCVars()->g_movementTransitions_debug) { if (transitionType == eTT_DirectionChange) { Vec3 up(0.0f, 0.0f, 0.1f); IAIDebugRenderer* pDc = gEnv->pAISystem->GetAIDebugRenderer(); pDc->PushState(); ColorB debugColor = debugColors[newState]; float distanceAfterJuke = 2.0f; Vec3 jukePoint = playerPos + oldMoveDirection * transParams.m_transitionDistance; Vec3 startPoint = jukePoint - oldMoveDirection * (this->maxDistance + this->minDistance)/2.0f; Vec3 desiredEndPoint = jukePoint + Quat::CreateRotationZ(this->desiredJukeAngle) * oldMoveDirection * distanceAfterJuke; Vec3 realEndPoint = jukePoint + Quat::CreateRotationZ(transParams.m_jukeAngle) * oldMoveDirection * distanceAfterJuke; Vec3 desiredBodyDirection = Quat::CreateRotationZ(-this->desiredTravelAngle) * oldMoveDirection; Vec3 currentBodyDirection = Quat::CreateRotationZ(-transParams.m_travelAngle) * oldMoveDirection; pDc->DrawSphere(jukePoint + 8.00f*up, 0.1f, debugColor); pDc->DrawArrow(startPoint + 8.00f*up, (jukePoint - startPoint), 0.1f, debugColor); pDc->DrawArrow(jukePoint + 8.00f*up, (desiredEndPoint - jukePoint), 0.1f, debugColor); pDc->DrawArrow(jukePoint + 8.05f*up, (realEndPoint - jukePoint), 0.1f, debugColor); pDc->DrawRangeArc(jukePoint+ 8.00f*up, (desiredEndPoint - jukePoint).GetNormalized(), 2.0f*jukeAngleTolerance, distanceAfterJuke, 0.1f, debugColor, debugColor, false); float debugTravelAngleDistance = 0.8f*(this->maxDistance+this->minDistance)/2; pDc->DrawArrow(playerPos + 8.05f*up, desiredBodyDirection*debugTravelAngleDistance , 0.1f, debugColor); pDc->DrawRangeArc(startPoint + 8.00f*up, desiredBodyDirection, 2.0f*travelAngleTolerance, debugTravelAngleDistance, 0.1f, debugColor, debugColor, false); pDc->PopState(); } // eTT_DirectionChange } // if debugging on } #endif // RELEASE return newState; }
virtual bool OnUpdate() { if(!m_tgt) { return true; } if( gEnv->pInGUI->gkGUIButton( _T("prophet"), Vec2(gEnv->pRenderer->GetScreenWidth() - 105, 200), 100, 50, ColorB(255,255,255,255), ColorB(0,0,0,128) ) ) { const TCHAR* chrfile = _T("objects/characters/prophet/prophet.chr"); const TCHAR* mtlfile = _T("objects/characters/prophet/prophet.mtl"); create_chr(chrfile, mtlfile); } if( gEnv->pInGUI->gkGUIButton( _T("faraa"), Vec2(gEnv->pRenderer->GetScreenWidth() - 105, 251), 100, 50, ColorB(255,255,255,255), ColorB(0,0,0,128) ) ) { const TCHAR* chrfile = _T("objects/characters/faraa/faraa.chr"); const TCHAR* mtlfile = _T("objects/characters/faraa/faraa.mtl"); create_chr(chrfile, mtlfile); } if( gEnv->pInGUI->gkGUIButton( _T("idle"), Vec2(10, 100), 100, 50, ColorB(255,255,255,255), ColorB(0,0,0,128) ) ) { IGameObjectAnimLayer* anilayer = reinterpret_cast<IGameObjectAnimLayer*>( m_tgt->getGameObjectLayer(eGL_AnimLayer) ); anilayer->stopAllAnimation(0); anilayer->playAnimation(_T("idle"), 0); anilayer->setAnimationSpeed(_T("idle"), 1.0); } if( gEnv->pInGUI->gkGUIButton( _T("walk"), Vec2(10, 151), 100, 50, ColorB(255,255,255,255), ColorB(0,0,0,128) ) ) { IGameObjectAnimLayer* anilayer = reinterpret_cast<IGameObjectAnimLayer*>( m_tgt->getGameObjectLayer(eGL_AnimLayer) ); anilayer->stopAllAnimation(0); anilayer->playAnimation(_T("walk"), 0); anilayer->setAnimationSpeed(_T("walk"), 1.0); } if( gEnv->pInGUI->gkGUIButton( _T("run"), Vec2(10, 202), 100, 50, ColorB(255,255,255,255), ColorB(0,0,0,128) ) ) { IGameObjectAnimLayer* anilayer = reinterpret_cast<IGameObjectAnimLayer*>( m_tgt->getGameObjectLayer(eGL_AnimLayer) ); anilayer->stopAllAnimation(0); anilayer->playAnimation(_T("run"), 0); anilayer->setAnimationSpeed(_T("run"), 1.0); } if( gEnv->pInGUI->gkGUIButton( _T("crouch_opt"), Vec2(10, 253), 100, 50, ColorB(255,255,255,255), ColorB(0,0,0,128) ) ) { IGameObjectAnimLayer* anilayer = reinterpret_cast<IGameObjectAnimLayer*>( m_tgt->getGameObjectLayer(eGL_AnimLayer) ); anilayer->stopAllAnimation(0); anilayer->playAnimation(_T("crouch_opt"), 0); anilayer->setAnimationSpeed(_T("crouch_opt"), 1.0); } if( gEnv->pInGUI->gkGUIButton( _T("swing"), Vec2(10, 304), 100, 50, ColorB(255,255,255,255), ColorB(0,0,0,128) ) ) { IGameObjectAnimLayer* anilayer = reinterpret_cast<IGameObjectAnimLayer*>( m_tgt->getGameObjectLayer(eGL_AnimLayer) ); anilayer->stopAllAnimation(0); anilayer->playAnimation(_T("swing"), 0); anilayer->setAnimationSpeed(_T("swing"), 1.0); } return true; }
void CFlock::Update( CCamera *pCamera ) { FUNCTION_PROFILER( GetISystem(),PROFILE_ENTITY ); if (!IsFlockActive()) return; if (!m_e_flocks) { if (m_bEntityCreated) DeleteEntities( true ); return; } if(GetISystem()->IsSerializingFile() == 1) //quickloading return; if (!m_bEntityCreated) { if (!CreateEntities()) return; } float dt = gEnv->pTimer->GetFrameTime(); // Make sure delta time is limited. if (dt > 1.0f) dt = 0.01f; if (dt > 0.1f) dt = 0.1f; m_bc.fSmoothFactor = 1.f - gEnv->pTimer->GetProfileFrameBlending(); /* for (Boids::iterator it = m_boids.begin(); it != m_boids.end(); ++it) { CBoidObject *boid = *it; boid->Think(); } */ //m_bc.playerPos = m_flockMgr->GetPlayerPos(); m_bc.playerPos = GetISystem()->GetViewCamera().GetMatrix().GetTranslation(); // Player position is position of camera. m_bc.flockPos = m_origin; m_bc.waterLevel = m_bc.engine->GetWaterLevel( &m_origin ); m_bounds.min = Vec3(FLT_MAX,FLT_MAX,FLT_MAX); m_bounds.max = Vec3(-FLT_MAX,-FLT_MAX,-FLT_MAX); int numBoids = m_boids.size(); if (m_percentEnabled < 100) { numBoids = (m_percentEnabled*numBoids)/100; } if (!m_pEntity->GetRotation().IsIdentity()) { // Entity matrix must not have rotation. //Quat q; //q.SetIdentity(); //m_pEntity->SetRotation(q); } ////////////////////////////////////////////////////////////////////////// // Update flock random center. ////////////////////////////////////////////////////////////////////////// m_fCenterFloatingTime += gEnv->pTimer->GetFrameTime(); float tc = m_fCenterFloatingTime*0.2f; m_bc.randomFlockCenter = m_bc.flockPos + //m_bc.fSpawnRadius*Vec3(sinf(0.9f*m_fCenterFloatingTime),cosf(1.1f*sin(0.9f*m_fCenterFloatingTime)),0.3f*sinf(1.2f*m_fCenterFloatingTime) ); m_bc.fSpawnRadius*Vec3(sinf(tc*0.913f)*cosf(tc*1.12f),sinf(tc*0.931f)*cosf(tc*0.971f),0.4f*sinf(tc*1.045f)*cosf(tc*0.962f) ); //gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere( m_bc.randomFlockCenter,0.1f,ColorB(255,0,0,255) ); ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// IEntityRenderProxy *pRenderProxy = (IEntityRenderProxy*)m_pEntity->GetProxy(ENTITY_PROXY_RENDER); if (pRenderProxy) { if (pRenderProxy->GetRenderNode()->GetViewDistRatio() != m_nViewDistRatio) UpdateBoidsViewDistRatio(); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Update scare factors. if (m_bc.scareThreatLevel > 0) { m_bc.scareThreatLevel *= 0.95f; m_bc.scareRatio *= 0.95f; if (m_bc.scareRatio < 0.01f) { m_bc.scareRatio = 0; m_bc.scareThreatLevel = 0; } if (m_e_flocks == 2) { int c = (int)(255*m_bc.scareRatio); gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere( m_bc.scarePoint,m_bc.scareRadius,ColorB(c,0,0,c),false ); } } ////////////////////////////////////////////////////////////////////////// UpdateBoidCollisions(); Vec3 entityPos = m_pEntity->GetWorldPos(); Matrix34 boidTM; int num = 0; for (Boids::iterator it = m_boids.begin(); it != m_boids.end(); ++it,num++) { if (num > numBoids) break; CBoidObject* boid = *it; m_bc.terrainZ = m_bc.engine->GetTerrainElevation(boid->m_pos.x,boid->m_pos.y); boid->Update(dt,m_bc); if (!boid->m_physicsControlled && !boid->m_dead) { IEntity *pBoidEntity = gEnv->pEntitySystem->GetEntity(boid->m_entity); if (pBoidEntity) { Quat q(IDENTITY); boid->CalcOrientation(q); const Vec3 scaleVector(boid->m_scale,boid->m_scale,boid->m_scale); pBoidEntity->SetPosRotScale( boid->m_pos, q, scaleVector, ENTITY_XFORM_NO_SEND_TO_ENTITY_SYSTEM ); } } } m_updateFrameID = gEnv->pRenderer->GetFrameID(false); //gEnv->pLog->Log( "Birds Update" ); }
void CLocalPlayerComponent::UpdateFPIKTorso(float fFrameTime, IItem * pCurrentItem, const Vec3& cameraPosition) { //Get const ref instead of doing a full copy SMovementState info; m_rPlayer.m_pMovementController->GetMovementState(info); const QuatT &cameraTran = m_rPlayer.GetCameraTran(); if (m_rPlayer.m_torsoAimIK.GetBlendFactor() > 0.9f) { m_lastSTAPCameraDelta = m_rPlayer.m_torsoAimIK.GetLastEffectorTransform().GetInverted() * cameraTran; } else { m_lastSTAPCameraDelta.SetIdentity(); } ICharacterInstance* pCharacter = m_rPlayer.GetEntity()->GetCharacter(0); ICharacterInstance* pCharacterShadow = m_rPlayer.GetShadowCharacter(); QuatT torsoOffset; GetFPTotalTorsoOffset(torsoOffset, pCurrentItem); if (pCharacter != 0) { Vec3 aimDir; if (m_rPlayer.m_params.mountedWeaponCameraTarget.IsZero() && (m_rPlayer.GetLinkedVehicle() == NULL)) { aimDir = !m_rPlayer.m_pPlayerRotation->GetBaseQuat() * info.aimDirection; } else { aimDir = !m_rPlayer.GetEntity()->GetWorldRotation() * info.aimDirection; } AdjustTorsoAimDir(fFrameTime, aimDir); const bool needsPositionAdjust = !m_rPlayer.IsSliding(); CIKTorsoAim_Helper::SIKTorsoParams IKParams(pCharacter, pCharacterShadow, aimDir, torsoOffset, cameraPosition, m_rPlayer.GetBoneID(BONE_CAMERA), m_rPlayer.GetBoneID(BONE_SPINE2), m_rPlayer.GetBoneID(BONE_SPINE), ShouldUpdateTranslationPinning(), needsPositionAdjust); m_rPlayer.m_torsoAimIK.Update(IKParams); } #ifndef _RELEASE if (g_pGameCVars->pl_debug_view != 0) { CryWatch("CPlayer:UpdateFPIKTorso: RawCamera Pos(%f, %f, %f) Rot(%f, %f, %f, %f)", cameraTran.t.x, cameraTran.t.x, cameraTran.t.x, cameraTran.q.v.x, cameraTran.q.v.y, cameraTran.q.v.z, cameraTran.q.w ); CryWatch("CPlayer:UpdateFPIKTorso: MountedTarget (%f, %f, %f)", m_rPlayer.m_params.mountedWeaponCameraTarget.x, m_rPlayer.m_params.mountedWeaponCameraTarget.y, m_rPlayer.m_params.mountedWeaponCameraTarget.z ); CryWatch("CPlayer:UpdateFPIKTorso: CamPos(%f, %f, %f) Dir(%f, %f, %f)", cameraPosition.x, cameraPosition.y, cameraPosition.z, info.aimDirection.x, info.aimDirection.y, info.aimDirection.z); CryWatch("CPlayer:UpdateFPIKTorso: Anim Pos(%f, %f, %f) Rot(%f, %f, %f, %f)", m_lastSTAPCameraDelta.t.x, m_lastSTAPCameraDelta.t.y, m_lastSTAPCameraDelta.t.z, m_lastSTAPCameraDelta.q.v.x, m_lastSTAPCameraDelta.q.v.y, m_lastSTAPCameraDelta.q.v.z, m_lastSTAPCameraDelta.q.w); if (g_pGameCVars->pl_debug_view >= 2) { CryLog("CPlayer:UpdateFPIKTorso: CamPos(%f, %f, %f) Dir(%f, %f, %f)", cameraPosition.x, cameraPosition.y, cameraPosition.z, info.aimDirection.x, info.aimDirection.y, info.aimDirection.z); CryLog("CPlayer:UpdateFPIKTorso: EyeOffset(%f, %f, %f)", m_rPlayer.m_eyeOffset.x, m_rPlayer.m_eyeOffset.y, m_rPlayer.m_eyeOffset.z); } const QuatT cameraWorld = QuatT(m_rPlayer.GetEntity()->GetWorldTM()) * cameraTran; gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(cameraWorld.t, 0.1f, ColorB(0, 0, 255)); gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(cameraWorld.t, ColorB(255, 0, 0), cameraWorld.t + cameraWorld.q.GetColumn1(), ColorB(255, 0, 0), 3.0f); } if(g_pGameCVars->p_collclassdebug == 1) { const QuatT cameraQuatT = QuatT(m_rPlayer.GetEntity()->GetWorldTM()) * cameraTran; ray_hit hit; if(gEnv->pPhysicalWorld->RayWorldIntersection(cameraQuatT.t+(cameraQuatT.q.GetColumn1()*1.5f), cameraQuatT.q.GetColumn1()*200.f, ent_all, rwi_colltype_any(geom_collides)|rwi_force_pierceable_noncoll|rwi_stop_at_pierceable, &hit, 1 )) { if(hit.pCollider) { gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(hit.pt, 0.1f, ColorB(0, 0, 255)); g_pGame->GetGamePhysicsSettings()->Debug(*hit.pCollider, true); } } } #endif }
void SearchGroup::Update() { IVisionMap& visionMap = *gEnv->pAISystem->GetVisionMap(); // Update vision { std::vector<SearchActor>::iterator actorIt = m_actors.begin(); std::vector<SearchActor>::iterator actorEnd = m_actors.end(); for ( ; actorIt != actorEnd; ++actorIt) { SearchActor& actor = (*actorIt); Agent agent(actor.entityID); if(!agent.IsValid()) continue; ObserverParams observerParams; observerParams.eyePosition = agent.GetPos(); observerParams.eyeDirection = agent.GetViewDir(); visionMap.ObserverChanged(actor.visionID, observerParams, eChangedPosition | eChangedOrientation); } } // Debug draw target pos if (g_pGameCVars->ai_DebugSearch) { IRenderAuxGeom* pDebugRenderer = gEnv->pRenderer->GetIRenderAuxGeom(); pDebugRenderer->DrawSphere(m_targetPos, 0.6f, ColorB(255, 255, 255, 128)); } const float frameTime = gEnv->pTimer->GetFrameTime(); std::vector<SearchSpot>::iterator spotIt = m_searchSpots.begin(); std::vector<SearchSpot>::iterator spotEnd = m_searchSpots.end(); for ( ; spotIt != spotEnd; ++spotIt) { SearchSpot& searchSpot = (*spotIt); if (g_pGameCVars->ai_DebugSearch) searchSpot.DebugDraw(m_searchSpotTimeout); if(searchSpot.IsTimingOut()) searchSpot.UpdateSearchedTimeout(frameTime); if (searchSpot.HasBeenSearched()) continue; // Naive Implementation! // Go through all the actors and see // if they see any of the search spots. // Later on, use a callback for this! SearchActorIter actorIt = m_actors.begin(); std::vector<SearchActor>::iterator actorEnd = m_actors.end(); for ( ; actorIt != actorEnd; ++actorIt) { SearchActor& actor = *actorIt; if (visionMap.IsVisible(actor.visionID, searchSpot)) { searchSpot.MarkAsSearchedBy(actor, m_searchSpotTimeout); break; } } } }
void CPlayerStateJump::StartJump( CPlayer& player, const bool isHeavyWeapon, const float fVerticalSpeedModifier ) { const SActorPhysics& actorPhysics = player.GetActorPhysics(); const SPlayerStats& stats = *player.GetActorStats(); const float onGroundTime = 0.2f; float g = actorPhysics.gravity.len(); const float jumpHeightScale = 1.0f; const float jumpHeight = player.GetActorParams().jumpHeight * jumpHeightScale; float playerZ = player.GetEntity()->GetWorldPos().z; float expectedJumpEndHeight = playerZ + jumpHeight; pe_player_dimensions dimensions; IPhysicalEntity *pPhysics = player.GetEntity()->GetPhysics(); if (pPhysics && pPhysics->GetParams(&dimensions)) { float physicsBottom = dimensions.heightCollider - dimensions.sizeCollider.z; if (dimensions.bUseCapsule) { physicsBottom -= dimensions.sizeCollider.x; } expectedJumpEndHeight += physicsBottom; } float jumpSpeed = 0.0f; if (g > 0.0f) { jumpSpeed = sqrt_tpl(2.0f*jumpHeight*(1.0f/g)) * g; if( isHeavyWeapon ) { jumpSpeed *= g_pGameCVars->pl_movement.nonCombat_heavy_weapon_speed_scale; } } //this is used to easily find steep ground float slopeDelta = (Vec3Constants<float>::fVec3_OneZ - actorPhysics.groundNormal).len(); SetJumpState(player, JState_Jump); Vec3 jumpVec(ZERO); bool bNormalJump = true; player.PlaySound(CPlayer::ESound_Jump); OnSpecialMove(player, IPlayerEventListener::eSM_Jump); CCCPOINT_IF( player.IsClient(), PlayerMovement_LocalPlayerNormalJump); CCCPOINT_IF(!player.IsClient(), PlayerMovement_NonLocalPlayerNormalJump); { // This was causing the vertical jumping speed to be much slower. float verticalMult = max(1.0f - m_jumpLock, 0.3f); const Quat baseQuat = player.GetBaseQuat(); jumpVec += baseQuat.GetColumn2() * jumpSpeed * verticalMult; jumpVec.z += fVerticalSpeedModifier; #ifdef STATE_DEBUG if (g_pGameCVars->pl_debugInterpolation > 1) { CryWatch("Jumping: vec from player BaseQuat only = (%f, %f, %f)", jumpVec.x, jumpVec.y, jumpVec.z); } #endif if (g_pGameCVars->pl_adjustJumpAngleWithFloorNormal && actorPhysics.groundNormal.len2() > 0.0f) { float vertical = clamp_tpl((actorPhysics.groundNormal.z - 0.25f) / 0.5f, 0.0f, 1.0f); Vec3 modifiedJumpDirection = LERP(actorPhysics.groundNormal, Vec3(0,0,1), vertical); jumpVec = modifiedJumpDirection * jumpVec.len(); } #ifdef STATE_DEBUG if (g_pGameCVars->pl_debugInterpolation > 1) { CryWatch("Jumping (%f, %f, %f)", jumpVec.x, jumpVec.y, jumpVec.z); } #endif } NETINPUT_TRACE(player.GetEntityId(), jumpVec); FinalizeVelocity( player, jumpVec ); if (!player.IsRemote()) { player.HasJumped(player.GetMoveRequest().velocity); } IPhysicalEntity* pPhysEnt = player.GetEntity()->GetPhysics(); if (pPhysEnt != NULL) { SAnimatedCharacterParams params = player.m_pAnimatedCharacter->GetParams(); pe_player_dynamics pd; pd.kAirControl = player.GetAirControl()* g_pGameCVars->pl_jump_control.air_control_scale; pd.kAirResistance = player.GetAirResistance() * g_pGameCVars->pl_jump_control.air_resistance_scale; params.inertia = player.GetInertia() * g_pGameCVars->pl_jump_control.air_inertia_scale; if(player.IsRemote() && (g_pGameCVars->pl_velocityInterpAirControlScale > 0)) { pd.kAirControl = g_pGameCVars->pl_velocityInterpAirControlScale; } pPhysEnt->SetParams(&pd); // Let Animated character handle the inertia player.SetAnimatedCharacterParams(params); } #if 0 if (debugJumping) { Vec3 entityPos = m_player.GetEntity()->GetWorldPos(); gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(entityPos, ColorB(255,255,255,255), entityPos, ColorB(255,255,0,255), 2.0f); gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(entityPos+Vec3(0,0,2), ColorB(255,255,255,255), entityPos+Vec3(0,0,2) + desiredVel, ColorB(0,255,0,255), 2.0f); gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(entityPos, ColorB(255,255,255,255), entityPos + jumpVec, ColorB(0,255,255,255), 2.0f); gEnv->pRenderer->DrawLabel(entityPos - entityRight * 1.0f + Vec3(0,0,3.0f), 1.5f, "Velo[%2.3f = %2.3f, %2.3f, %2.3f]", m_request.velocity.len(), m_request.velocity.x, m_request.velocity.y, m_request.velocity.z); } #endif m_expectedJumpEndHeight = expectedJumpEndHeight; m_bSprintJump = player.IsSprinting(); }
void CNetPlayerInput::UpdateInterpolation() { Vec3 desiredPosition = m_curInput.position; Vec3 entPos = m_pPlayer->GetEntity()->GetPos(); Vec3 displacement = desiredPosition - entPos; displacement.z = 0.0f; float dist = displacement.len(); CTimeValue curTime=gEnv->pTimer->GetFrameStartTime(); Vec3 desiredVelocity = m_curInput.deltaMovement * g_pGameCVars->pl_netSerialiseMaxSpeed; m_netDesiredSpeed = desiredVelocity.GetLength2D(); if (m_newInterpolation) { InitialiseInterpolation(dist, displacement, desiredVelocity, curTime); } float dt = curTime.GetDifferenceInSeconds(m_netLastUpdate) + k_lerpTargetTime; dt = min(dt, k_maxPredictTime); m_predictedPosition = desiredPosition + (desiredVelocity * dt); Vec3 predOffset = m_predictedPosition - entPos; float predDist = predOffset.GetLength2D(); float lerpSpeed = (predDist/k_lerpTargetTime); lerpSpeed=clamp(lerpSpeed, k_minInterpolateSpeed, k_maxInterpolateSpeed); m_netLerpSpeed = lerpSpeed; UpdateErrorSnap(entPos, desiredPosition, dist, displacement, curTime); if (!m_passedNetPos && (m_initialDir.Dot(displacement) < 0.0f)) { m_passedNetPos = true; } Vec3 maxPrediction = desiredPosition + (desiredVelocity * k_maxPredictTime); if (m_passedNetPos && !m_passedPredictionPos && (m_initialDir.Dot(maxPrediction - entPos) < 0.0f)) { m_passedPredictionPos = true; } #if !defined(_RELEASE) if (g_pGameCVars->pl_debugInterpolation) { CryWatch("Cur: (%f, %f, %f) Des: (%f, %f, %f) Pred: (%f, %f, %f) ", entPos.x, entPos.y, entPos.z, desiredPosition.x, desiredPosition.y, desiredPosition.z, m_predictedPosition.x, m_predictedPosition.y, m_predictedPosition.z); CryWatch("BlockTime: (%f) PredictTime (%f) LastNetTime (%f) CurTime (%f)", m_blockedTime, dt, m_netLastUpdate.GetSeconds(), curTime.GetSeconds()); CryWatch("Lerp Speed: (%f) Passed pred pos (%d) Passed net pos (%d)", m_netLerpSpeed, m_passedPredictionPos, m_passedNetPos); CryWatch("InputSpeed: (%f, %f, %f) ", desiredVelocity.x, desiredVelocity.y, desiredVelocity.z); IRenderAuxGeom* pRender = gEnv->pRenderer->GetIRenderAuxGeom(); SAuxGeomRenderFlags flags = pRender->GetRenderFlags(); SAuxGeomRenderFlags oldFlags = pRender->GetRenderFlags(); flags.SetDepthWriteFlag(e_DepthWriteOff); flags.SetDepthTestFlag(e_DepthTestOff); pRender->SetRenderFlags(flags); pRender->DrawSphere(desiredPosition + Vec3(0.0f, 0.0f, 0.035f), 0.07f, ColorB(255,0,0,255)); pRender->DrawSphere(m_predictedPosition + Vec3(0.0f, 0.0f, 0.025f), 0.05f, ColorB(255,255,255,255)); pRender->SetRenderFlags(oldFlags); ColorF ballCol = m_passedPredictionPos ? ColorF(1.0f,1.0f,0.0f,0.75f) : (m_passedNetPos ? ColorF(1.0f,1.0f,1.0f,0.75f) : ColorF(0.0f,1.0f,0.0f,0.75f)); g_pGame->GetIGameFramework()->GetIPersistantDebug()->Begin("INTERPOLATION TRAIL", false); g_pGame->GetIGameFramework()->GetIPersistantDebug()->AddSphere(desiredPosition + Vec3(0.0f, 0.0f, 0.1f), 0.04f, ColorF(1.0f,0.0f,0.0f,0.75f), 30.f); g_pGame->GetIGameFramework()->GetIPersistantDebug()->AddSphere(m_predictedPosition + Vec3(0.0f, 0.0f, 0.1f), 0.03f, ColorF(0.0f,0.0f,1.0f,0.8f), 30.f); ballCol.a = 1.0f; g_pGame->GetIGameFramework()->GetIPersistantDebug()->AddSphere(entPos + Vec3(0.0f, 0.0f, 0.1f), 0.02f, ballCol, 30.f); g_pGame->GetIGameFramework()->GetIPersistantDebug()->AddLine(entPos + Vec3(0.0f, 0.0f, 0.1f), m_predictedPosition + Vec3(0.0f, 0.0f, 0.1f), ballCol, 30.f); } #endif //!_RELEASE }
//------------------------------------------------------------------ void CLam::UpdateFPLaser(float frameTime, CItem* parent) { Vec3 lamPos, dir; if (m_laserActivated) AdjustLaserFPDirection(parent,dir,lamPos); else { // Lam Light lamPos = parent->GetSlotHelperPos(eIGS_FirstPerson,m_laserHelperFP.c_str(),true); Quat lamRot = Quat(parent->GetSlotHelperRotation(eIGS_FirstPerson,m_laserHelperFP.c_str(),true)); dir = lamRot.GetColumn1(); } // float len = m_lamparams.laser_range[eIGS_FirstPerson]; dir.Normalize(); const float nearClipPlaneLimit = 10.0f; Vec3 hitPos(0,0,0); float laserLength = 0.0f; float dotScale = 1.0f; { IPhysicalEntity* pSkipEntity = NULL; if(parent->GetOwner()) pSkipEntity = parent->GetOwner()->GetPhysics(); const int objects = ent_all; const int flags = (geom_colltype_ray << rwi_colltype_bit) | rwi_colltype_any | (10 & rwi_pierceability_mask) | (geom_colltype14 << rwi_colltype_bit); ray_hit hit; if (gEnv->pPhysicalWorld->RayWorldIntersection(lamPos, dir*m_lamparams.laser_range[eIGS_FirstPerson], objects, flags, &hit, 1, &pSkipEntity, pSkipEntity?1:0)) { //Clamp distance below near clip plane limits, if not dot will be overdrawn during rasterization if(hit.dist>nearClipPlaneLimit) { laserLength = nearClipPlaneLimit; m_lastLaserHitPt = lamPos + (nearClipPlaneLimit*dir); } else { laserLength = hit.dist; m_lastLaserHitPt = hit.pt; } m_lastLaserHitSolid = true; if(parent->GetOwnerActor() && parent->GetOwnerActor()->GetActorParams()) dotScale *= max(0.3f,parent->GetOwnerActor()->GetActorParams()->viewFoVScale); } else { m_lastLaserHitSolid = false; m_lastLaserHitPt = lamPos - (dir*3.0f); laserLength = 3.0f; } hitPos = m_lastLaserHitPt; if(g_pGameCVars->i_debug_projectiles!=0) gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(hitPos, 0.2f, ColorB(255,0,0)); } if (m_laserActivated && m_dotEffectSlot >= 0) { Matrix34 worldMatrix = GetEntity()->GetWorldTM(); if(laserLength<=0.7f) hitPos = lamPos+(0.7f*dir); CWeapon* pWep = static_cast<CWeapon*>(parent->GetIWeapon()); if(pWep && pWep->IsWeaponLowered()) { hitPos = lamPos+(2.0f*dir); laserLength = 2.0f; } if(laserLength<=2.0f) dotScale *= min(1.0f,(0.35f + ((laserLength-0.7f)*0.5f))); IEntity* pDotEntity = m_pEntitySystem->GetEntity(m_pLaserEntityId); if(pDotEntity) { Matrix34 finalMatrix = Matrix34::CreateTranslationMat(hitPos-(0.2f*dir)); pDotEntity->SetWorldTM(finalMatrix); Matrix34 localScale = Matrix34::CreateIdentity(); localScale.SetScale(Vec3(dotScale,dotScale,dotScale)); pDotEntity->SetSlotLocalTM(m_dotEffectSlot,localScale); } } if (m_laserActivated || m_lightActivated) { float laserAIRange = m_laserActivated ? laserLength : 0.0f; float lightAIRange = m_lightActivated ? min(laserLength, m_lamparams.light_range[eIGS_FirstPerson] * 1.5f) : 0.0f; UpdateAILightAndLaser(lamPos, dir, lightAIRange, m_lamparams.light_fov[eIGS_FirstPerson], laserAIRange); } }
bool CIntersectionAssistanceUnit::TestForIntersectionAtLocation(const eTestMethod testMethod, const Matrix34& wMat, EntityId testEntityId, EntityId ignoreEnt, QuatT& outAdjustedResult, const bool bCentreOnFocalEnt /* = false */, bool bRenderOnFail /* = true */, const int index /* = -1*/) { // Build an OOBB that surrounds this entity, test for intersection between that and world IEntity* pEntity = gEnv->pEntitySystem->GetEntity(testEntityId); if(pEntity) { IPhysicalEntity* pPhysical = pEntity->GetPhysics(); if(pPhysical) { OBB entOBB; AABB entAABB; pEntity->GetLocalBounds(entAABB); entOBB.SetOBBfromAABB(Quat(IDENTITY), entAABB); // Do Primitive world intersection primitives::box physBox; physBox.bOriented = 1; // LSpace physBox.center = entOBB.c; physBox.Basis = entOBB.m33; physBox.size.x = entOBB.h.x; physBox.size.y = entOBB.h.y; physBox.size.z = entOBB.h.z; // WSpace physBox.center = wMat.TransformPoint(physBox.center); physBox.Basis *= Matrix33(wMat).GetInverted(); // Optional tweak - We can get away with a little bit of scaling down (if edges are slightly embedded the physics pushes them out easily) physBox.size = physBox.size.scale(kPhysBoxScaleFactor); // adjust Vec3 vAdjustments(0.0f,0.0f,0.0f); if(bCentreOnFocalEnt && m_focalEntityId) { Vec3 vDesiredPos = CalculateTargetAdjustPoint(pEntity, wMat, physBox.center); vAdjustments = (vDesiredPos - physBox.center); physBox.center += vAdjustments; } IEntity* pIgnoreEnt = gEnv->pEntitySystem->GetEntity(ignoreEnt); IPhysicalEntity* pIgnorePhys = pIgnoreEnt ? pIgnoreEnt->GetPhysics() : NULL; // Test if(testMethod == eTM_Immediate #ifndef _RELEASE || g_pGameCVars->pl_pickAndThrow.intersectionAssistDebugEnabled >= 1 #endif // #ifndef _RELEASE ) { geom_contact *contacts; intersection_params params; float numHits = gEnv->pPhysicalWorld->PrimitiveWorldIntersection(primitives::box::type, &physBox, Vec3(ZERO), ent_static|ent_terrain, &contacts, 0, 3, ¶ms, 0, 0, &pIgnorePhys, pIgnorePhys ? 1 : 0); // Debug #ifndef _RELEASE if(g_pGameCVars->pl_pickAndThrow.intersectionAssistDebugEnabled) { const bool bIntersect = numHits <= 0.0f ? false : true; if(bRenderOnFail || !bIntersect) { const ColorB colorPositive = ColorB(16, 96, 16); const ColorB colorNegative = ColorB(128, 0, 0); const ColorB colorSelected = ColorB(0,255,0); if(numHits > 0.0f) { gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(contacts->pt, 0.1f, colorPositive); } OBB finalOBB; finalOBB.SetOBB(Matrix33(IDENTITY), physBox.size, Vec3(0.0f,0.0f,0.0f)); Matrix34 drawMat = wMat; drawMat.AddTranslation(physBox.center - wMat.GetTranslation()); if(index != -1 && index == m_currentBestIndex) { gEnv->pRenderer->GetIRenderAuxGeom()->DrawOBB(finalOBB, drawMat, false, colorSelected, eBBD_Faceted); } else { gEnv->pRenderer->GetIRenderAuxGeom()->DrawOBB(finalOBB, drawMat, false, bIntersect ? colorNegative : colorPositive, eBBD_Faceted); } } } #endif //#ifndef RELEASE // If we performed an adjust, make sure we pass out the QuatT representing the FINAL ENTITY POSITION that passed/failed (not the phys box etc) outAdjustedResult.t = wMat.GetTranslation() + vAdjustments; outAdjustedResult.q = Quat(wMat); #ifndef _RELEASE // allow optional debug drawing of last known good positions by retaining non adjusted position if(g_pGameCVars->pl_pickAndThrow.intersectionAssistDebugEnabled == 1) { outAdjustedResult.t = wMat.GetTranslation(); } #endif // #ifndef _RELEASE return (numHits > 0.0f); } else { // QUEUE primitive intersection check outAdjustedResult.t = wMat.GetTranslation() + vAdjustments; outAdjustedResult.q = Quat(wMat); CRY_ASSERT(index >= 0); m_intersectionTester.DoCheck(index,physBox,outAdjustedResult,pIgnorePhys); return false; } } } return false; }
//----------------------------------------------------------------------------- void CHomingMissile::UpdateControlledMissile(float frameTime) { bool isServer = gEnv->bServer; bool isClient = gEnv->bClient; CActor *pClientActor=0; if (gEnv->bClient) pClientActor=static_cast<CActor *>(g_pGame->GetIGameFramework()->GetClientActor()); bool isOwner = ((!m_ownerId && isServer) || (isClient && pClientActor && (pClientActor->GetEntityId() == m_ownerId) && pClientActor->IsPlayer())); IRenderer* pRenderer = gEnv->pRenderer; IRenderAuxGeom* pGeom = pRenderer->GetIRenderAuxGeom(); float color[4] = {1,1,1,1}; const static float step = 15.f; float y = 20.f; bool bDebug = g_pGameCVars->i_debug_projectiles > 0; if (isOwner || isServer) { //If there's a target, follow the target if(isServer) { if (m_targetId) { if (m_lockedTimer>0.0f) m_lockedTimer=m_lockedTimer-frameTime; else { // If we are here, there's a target IEntity* pTarget = gEnv->pEntitySystem->GetEntity(m_targetId); if (pTarget) { AABB box; pTarget->GetWorldBounds(box); Vec3 finalDes = box.GetCenter(); SetDestination(finalDes); //SetDestination( box.GetCenter() ); if (bDebug) pRenderer->Draw2dLabel(5.0f, y+=step, 1.5f, color, false, "Target Entity: %s", pTarget->GetName()); } m_lockedTimer+=0.05f; } } else if(m_autoControlled) return; } if (m_controlled && !m_autoControlled && isOwner && !m_targetId) { //Check if the weapon is still selected CWeapon *pWeapon = GetWeapon(); if(!pWeapon || !pWeapon->IsSelected()) return; if (m_controlledTimer>0.0f) m_controlledTimer=m_controlledTimer-frameTime; else if (pClientActor && pClientActor->IsPlayer()) //Follow the crosshair { if (IMovementController *pMC=pClientActor->GetMovementController()) { Vec3 eyePos(ZERO); Vec3 eyeDir(ZERO); IVehicle* pVehicle = pClientActor->GetLinkedVehicle(); if(!pVehicle) { SMovementState state; pMC->GetMovementState(state); eyePos = state.eyePosition; eyeDir = state.eyeDirection; } else { SViewParams viewParams; pVehicle->UpdateView(viewParams, pClientActor->GetEntityId()); eyePos = viewParams.position; eyeDir = viewParams.rotation * Vec3(0,1,0); //eyeDir = (viewParams.targetPos - viewParams.position).GetNormalizedSafe(); } int pierceability=7; if (IPhysicalEntity *pPE=GetEntity()->GetPhysics()) { if (pPE->GetType()==PE_PARTICLE) { pe_params_particle pp; if (pPE->GetParams(&pp)) pierceability=pp.iPierceability; } } static const int objTypes = ent_all; static const int flags = (geom_colltype_ray << rwi_colltype_bit) | rwi_colltype_any | (pierceability & rwi_pierceability_mask) | (geom_colltype14 << rwi_colltype_bit); IPhysicalWorld* pWorld = gEnv->pPhysicalWorld; static IPhysicalEntity* pSkipEnts[10]; int numSkip = CSingle::GetSkipEntities(pWeapon, pSkipEnts, 10); ray_hit hit; int hits = 0; float range=m_maxTargetDistance; hits = pWorld->RayWorldIntersection(eyePos + 1.5f*eyeDir, eyeDir*range, objTypes, flags, &hit, 1, pSkipEnts, numSkip); while (hits) { if (gEnv->p3DEngine->RefineRayHit(&hit, eyeDir*range)) break; eyePos = hit.pt+eyeDir*0.003f; range -= hit.dist+0.003f; hits = pWorld->RayWorldIntersection(eyePos, eyeDir*range, objTypes, flags, &hit, 1, pSkipEnts, numSkip); } DestinationParams params; if(hits) params.pt=hit.pt; else params.pt=(eyePos+m_maxTargetDistance*eyeDir); //Some point in the sky... GetGameObject()->InvokeRMI(SvRequestDestination(), params, eRMI_ToServer); if (bDebug) { pRenderer->Draw2dLabel(5.0f, y+=step, 1.5f, color, false, "PlayerView eye direction: %.3f %.3f %.3f", eyeDir.x, eyeDir.y, eyeDir.z); pRenderer->Draw2dLabel(5.0f, y+=step, 1.5f, color, false, "PlayerView Target: %.3f %.3f %.3f", hit.pt.x, hit.pt.y, hit.pt.z); pRenderer->GetIRenderAuxGeom()->DrawCone(m_destination, Vec3(0,0,-1), 2.5f, 7.f, ColorB(255,0,0,255)); } } m_controlledTimer+=0.0f; } } } //This code is shared by both modes above (auto and controlled) if(!m_destination.IsZero()) { pe_status_dynamics status; if (!GetEntity()->GetPhysics()->GetStatus(&status)) { CryLogAlways("couldn't get physics status!"); return; } pe_status_pos pos; if (!GetEntity()->GetPhysics()->GetStatus(&pos)) { CryLogAlways("couldn't get physics pos!"); return; } float currentSpeed = status.v.len(); if (currentSpeed>0.001f) { Vec3 currentVel = status.v; Vec3 currentPos = pos.pos; Vec3 goalDir(ZERO); assert(!_isnan(currentSpeed)); assert(!_isnan(currentVel.x) && !_isnan(currentVel.y) && !_isnan(currentVel.z)); //Just a security check if((currentPos-m_destination).len2()<(m_detonationRadius*m_detonationRadius)) { Explode(true, true, m_destination, -currentVel.normalized(), currentVel, m_targetId); return; } goalDir = m_destination - currentPos; goalDir.Normalize(); //Turn more slowly... currentVel.Normalize(); if(bDebug) { pRenderer->Draw2dLabel(50,55,2.0f,color,false, " Destination: %.3f, %.3f, %.3f",m_destination.x,m_destination.y,m_destination.z); pRenderer->Draw2dLabel(50,80,2.0f,color,false, " Current Dir: %.3f, %.3f, %.3f",currentVel.x,currentVel.y,currentVel.z); pRenderer->Draw2dLabel(50,105,2.0f,color,false," Goal Dir: %.3f, %.3f, %.3f",goalDir.x,goalDir.y,goalDir.z); } float cosine = currentVel.Dot(goalDir); cosine = CLAMP(cosine,-1.0f,1.0f); float totalAngle = RAD2DEG(cry_acosf(cosine)); assert(totalAngle>=0); if (cosine<0.99) { float maxAngle = m_turnSpeed*frameTime; if (maxAngle>totalAngle) maxAngle=totalAngle; float t=(maxAngle/totalAngle)*m_lazyness; assert(t>=0.0 && t<=1.0); goalDir = Vec3::CreateSlerp(currentVel, goalDir, t); goalDir.Normalize(); } if(bDebug) pRenderer->Draw2dLabel(50,180,2.0f,color,false,"Corrected Dir: %.3f, %.3f, %.3f",goalDir.x,goalDir.y,goalDir.z); pe_action_set_velocity action; action.v = goalDir * currentSpeed; GetEntity()->GetPhysics()->Action(&action); } } }
//------------------------------------------------------------------------ void CVehiclePartTread::Update(const float frameTime) { FUNCTION_PROFILER( GetISystem(), PROFILE_ACTION ); if (!m_pCharInstance) return; if (m_bForceSetU) { m_bForceSetU = false; m_currentU = m_wantedU + 1.0f; UpdateU(); } ISkeletonPose* pSkeletonPose = m_pCharInstance->GetISkeletonPose(); pSkeletonPose->SetForceSkeletonUpdate(0); if (VehicleCVars().v_staticTreadDeform == 0 && m_pVehicle->GetStatus().speed < 0.001f) { return; } if (frameTime > 0.f && (m_damageRatio >= 1.f || !m_pVehicle->GetGameObject()->IsProbablyVisible() || m_pVehicle->IsProbablyDistant())) { return; } // we need a tread update in next frame pSkeletonPose->SetForceSkeletonUpdate(1); m_pVehicle->NeedsUpdate(); // animate the UV texture according to the wheels speed if (m_uvSpeedMultiplier != 0.0f && frameTime > 0.0f) { IPhysicalEntity* pPhysics = GetEntity()->GetPhysics(); pe_status_wheel wheelStatus; wheelStatus.iWheel = m_lastWheelIndex; if (pPhysics && pPhysics->GetStatus(&wheelStatus) != 0) { m_wantedU += m_uvSpeedMultiplier * (wheelStatus.w * wheelStatus.r * frameTime); m_wantedU -= std::floor(m_wantedU); UpdateU(); } } // deform the tread to follow the wheels QuatT absRoot = pSkeletonPose->GetAbsJointByID(0); for (TWheelInfoVector::const_iterator ite=m_wheels.begin(), end=m_wheels.end(); ite != end; ++ite) { const SWheelInfo& wheelInfo = *ite; const Matrix34& slotTM = GetEntity()->GetSlotLocalTM(wheelInfo.slot, true); VALIDATE_MAT(slotTM); if (m_operatorQueue) { m_operatorQueue->PushPosition(wheelInfo.jointId, IAnimationOperatorQueue::eOp_Override, slotTM.GetTranslation()); } #if ENABLE_VEHICLE_DEBUG if (VehicleCVars().v_debugdraw == 4) { Vec3 local = GetEntity()->GetWorldTM().GetInverted() * slotTM.GetTranslation(); gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(GetEntity()->GetWorldTM() * (local+Vec3((float)sgn(local.x)*0.5f,0.f,0.f)),0.1f,ColorB(0,0,255,255)); } #endif } ISkeletonAnim* pSkeletonAnim = m_pCharInstance->GetISkeletonAnim(); pSkeletonAnim->PushPoseModifier(VEH_ANIM_POSE_MODIFIER_LAYER, m_operatorQueue, "VehiclePartAnimatedJoint"); }
//---------------------------------------------------------------------------- void CHomingMissile::UpdateCruiseMissile(float frameTime) { IRenderer* pRenderer = gEnv->pRenderer; IRenderAuxGeom* pGeom = pRenderer->GetIRenderAuxGeom(); float color[4] = {1,1,1,1}; const static float step = 15.f; float y = 20.f; bool bDebug = g_pGameCVars->i_debug_projectiles > 0; if (m_targetId) { IEntity* pTarget = gEnv->pEntitySystem->GetEntity(m_targetId); if (pTarget) { AABB box; pTarget->GetWorldBounds(box); SetDestination( box.GetCenter() ); //if (bDebug) //pRenderer->Draw2dLabel(5.0f, y+=step, 1.5f, color, false, "Target Entity: %s", pTarget->GetName()); } } else { // update destination pos from weapon static IItemSystem* pItemSystem = g_pGame->GetIGameFramework()->GetIItemSystem(); IItem* pItem = pItemSystem->GetItem(m_weaponId); if (pItem && pItem->GetIWeapon()) { const Vec3& dest = pItem->GetIWeapon()->GetDestination(); SetDestination( dest ); //if (bDebug) //pRenderer->Draw2dLabel(5.0f, y+=step, 1.5f, color, false, "Weapon Destination: (%.1f %.1f %.1f)", dest.x, dest.y, dest.z); } } pe_status_dynamics status; if (!GetEntity()->GetPhysics()->GetStatus(&status)) return; float currentSpeed = status.v.len(); Vec3 currentPos = GetEntity()->GetWorldPos(); Vec3 goalDir(ZERO); if (!m_destination.IsZero()) { if((currentPos-m_destination).len2()<(m_detonationRadius*m_detonationRadius)) { Explode(true, true, m_destination, -status.v.normalized(), status.v, m_targetId); return; } if (bDebug) pGeom->DrawCone(m_destination, Vec3(0,0,-1), 2.5f, 7.f, ColorB(255,0,0,255)); float heightDiff = (m_cruiseAltitude-m_alignAltitude) - currentPos.z; if (!m_isCruising && heightDiff * sgn(status.v.z) > 0.f) { // if heading towards align altitude (but not yet reached) accelerate to max speed if (bDebug) pRenderer->Draw2dLabel(5.0f, y+=step, 1.5f, color, false, "[HomingMissile] accelerating (%.1f / %.1f)", currentSpeed, m_maxSpeed); } else if (!m_isCruising && heightDiff * sgnnz(status.v.z) < 0.f && (status.v.z<0 || status.v.z>0.25f)) { // align to cruise if (currentSpeed != 0) { goalDir = status.v; goalDir.z = 0; goalDir.normalize(); } if (bDebug) pRenderer->Draw2dLabel(5.0f, y+=step, 1.5f, color, false, "[HomingMissile] aligning"); } else { if (bDebug) pRenderer->Draw2dLabel(5.0f, y+=step, 1.5f, color, false, "[HomingMissile] cruising..."); // cruise m_isCruising = true; if (!m_destination.IsZero()) { float groundDistSq = m_destination.GetSquaredDistance2D(currentPos); float distSq = m_destination.GetSquaredDistance(currentPos); float descendDistSq = sqr(m_descendDistance); if (m_isDescending || groundDistSq <= descendDistSq) { if (bDebug) pRenderer->Draw2dLabel(5.0f, y+=step, 1.5f, color, false, "[HomingMissile] descending!"); if (distSq != 0) goalDir = (m_destination - currentPos).normalized(); else goalDir.zero(); m_isDescending = true; } else { Vec3 airPos = m_destination; airPos.z = currentPos.z; goalDir = airPos - currentPos; if (goalDir.len2() != 0) goalDir.Normalize(); } } } } float desiredSpeed = currentSpeed; if (currentSpeed < m_maxSpeed-0.1f) { desiredSpeed = min(m_maxSpeed, desiredSpeed + m_accel*frameTime); } Vec3 currentDir = status.v.GetNormalizedSafe(FORWARD_DIRECTION); Vec3 dir = currentDir; if (!goalDir.IsZero()) { float cosine = max(min(currentDir.Dot(goalDir), 0.999f), -0.999f); float goalAngle = RAD2DEG(acos_tpl(cosine)); float maxAngle = m_turnSpeed * frameTime; if (bDebug) { pGeom->DrawCone( currentPos, goalDir, 0.4f, 12.f, ColorB(255,0,0,255) ); pRenderer->Draw2dLabel(5.0f, y+=step, 1.5f, color, false, "[HomingMissile] goalAngle: %.2f", goalAngle); } if (goalAngle > maxAngle+0.05f) dir = (Vec3::CreateSlerp(currentDir, goalDir, maxAngle/goalAngle)).normalize(); else //if (goalAngle < 0.005f) dir = goalDir; } pe_action_set_velocity action; action.v = dir * desiredSpeed; GetEntity()->GetPhysics()->Action(&action); if (bDebug) { pGeom->DrawCone( currentPos, dir, 0.4f, 12.f, ColorB(128,128,0,255) ); pRenderer->Draw2dLabel(5.0f, y+=step, 1.5f, color, false, "[HomingMissile] currentSpeed: %.1f (max: %.1f)", currentSpeed, m_maxSpeed); } }
void CIntersectionAssistanceUnit::UpdateEmbeddingPrevention() { #ifndef _RELEASE // allow optional debug drawing of last known good positions by retaining non adjusted position if(g_pGameCVars->pl_pickAndThrow.intersectionAssistDebugEnabled == 2) { QuatT qSafe; GetSafeLocationForSubjectEntity(qSafe); const ColorB colorPositive = ColorB(128, 255, 128); gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(qSafe.t, 0.1f, colorPositive); Vec3 dirVec = qSafe.q.GetColumn2().GetNormalized(); Vec3 endPos = Vec3(qSafe.t); endPos += dirVec; gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(qSafe.t, colorPositive, endPos, colorPositive); } #endif // #ifndef _RELEASE // Lets queue as many intersection tests as allowed. IEntity* pFocalEnt = gEnv->pEntitySystem->GetEntity(m_focalEntityId); if(pFocalEnt) { if(!s_embedPreventRotations.empty()) { const Matrix34& focalMat = pFocalEnt->GetWorldTM(); const QuatT qFocalQuatT(focalMat); int count = 0; const uint8 numTestRotations = s_embedPreventRotations.size(); while(true) { CRY_ASSERT(m_currentTestIndex < m_lastKnownGoodPositions.size()); // request a primitive world intersection on the physics thread + process the results on callback eTestMethod testMethod = eTM_Deferred; #ifndef _RELEASE if(g_pGameCVars->pl_pickAndThrow.intersectionAssistDebugEnabled) { testMethod = eTM_Immediate; } #endif // #ifndef _RELEASE TestForIntersection(testMethod, qFocalQuatT,s_embedPreventRotations[m_currentTestIndex], true, m_currentTestIndex); ++m_currentTestIndex; // WRAP if(m_currentTestIndex >= numTestRotations) { m_currentTestIndex = 0; } ++count; if(count >= kMaxNumOOBBIntersectionTestsPerFrame || count >= numTestRotations) { return; } } } } }
void CFireModePlugin_AutoAim::AdjustFiringDirection( const Vec3& attackerPos, Vec3& firingDirToAdjust, const bool bCurrentlyZoomed, const EntityId ownerId ) const { CPlayer* pAttackingPlayer = static_cast<CPlayer*>(g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(ownerId)); if (pAttackingPlayer && pAttackingPlayer->IsPlayer()) { const ConeParams& aimConeSettings = GetAimConeSettings(bCurrentlyZoomed); // Don't do any projectile adjusting if the player already has a target for themselves, and is on target (e.g. manually scoping to get a headshot) if( m_targetSelectionParams.m_bDisableAutoAimIfPlayerAlreadyHasTarget && pAttackingPlayer->GetCurrentTargetEntityId() || !aimConeSettings.m_enabled) { #if ALLOW_PROJECTILEHELPER_DEBUGGING m_lastShotAutoAimedStatus.append("FALSE - [Reason]: Player already on target"); #endif //#if #endif //#if ALLOW_PROJECTILEHELPER_DEBUGGING return; } float incomingDirLength = firingDirToAdjust.GetLength(); CRY_ASSERT(incomingDirLength>0.f); Vec3 firingDirToAdjustNorm(firingDirToAdjust*__fres(incomingDirLength)); #if ALLOW_PROJECTILEHELPER_DEBUGGING // DEBUG RENDER if (g_pGameCVars->pl_debug_projectileAimHelper) { // Draw Target acquisition cone float length = aimConeSettings.m_maxDistance; float radius = length * tan(aimConeSettings.m_outerConeRads * 0.5f); SAuxGeomRenderFlags originalFlags = gEnv->pRenderer->GetIRenderAuxGeom()->GetRenderFlags(); SAuxGeomRenderFlags newFlags = originalFlags; newFlags.SetCullMode(e_CullModeNone); newFlags.SetFillMode(e_FillModeWireframe); newFlags.SetAlphaBlendMode(e_AlphaBlended); gEnv->pRenderer->GetIRenderAuxGeom()->SetRenderFlags(newFlags); gEnv->pRenderer->GetIRenderAuxGeom()->DrawCone(attackerPos + (firingDirToAdjustNorm*aimConeSettings.m_maxDistance),-firingDirToAdjustNorm, radius , length , ColorB(132,190,255,120), true ); // Draw projectile adjust cone radius = length * tan(aimConeSettings.m_innerConeRads * 0.5f); gEnv->pRenderer->GetIRenderAuxGeom()->DrawCone(attackerPos + (firingDirToAdjustNorm*aimConeSettings.m_maxDistance),-firingDirToAdjustNorm, radius , length ,ColorB(0,0,127,120), true ); // Restore render flags gEnv->pRenderer->GetIRenderAuxGeom()->SetRenderFlags(originalFlags); } #endif //#if ALLOW_PROJECTILEHELPER_DEBUGGING IEntity* pTargetPlayer = CalculateBestProjectileAutoAimTarget(attackerPos, firingDirToAdjustNorm, bCurrentlyZoomed, ownerId); if(pTargetPlayer) { const SAutoaimTarget* pAutoAimInfo = g_pGame->GetAutoAimManager().GetTargetInfo(pTargetPlayer->GetId()); if(pAutoAimInfo) { Vec3 desiredFiringDir = ( pAutoAimInfo->primaryAimPosition - attackerPos ).GetNormalized(); // Make sure final firing dir still constrained to valid cone float vecDot = firingDirToAdjustNorm.Dot(desiredFiringDir); float maxConeAngle = cos(0.5f * aimConeSettings.m_innerConeRads); if(vecDot >= maxConeAngle) { // within cone firingDirToAdjustNorm = desiredFiringDir; #if ALLOW_PROJECTILEHELPER_DEBUGGING m_lastShotAutoAimedStatus.append("TRUE + desired dir fully WITHIN allowed adjust cone"); #endif //#if ALLOW_PROJECTILEHELPER_DEBUGGING } else { // constrain (generally working with small angles, nLerp should be fine + cheap) const float invConeDot = 1.0f - maxConeAngle; const float invVecDot = 1.0f - vecDot; float zeroToOne = invConeDot / invVecDot; Vec3 finalVec = (zeroToOne * desiredFiringDir) + ((1.0f - zeroToOne) * firingDirToAdjustNorm); finalVec.Normalize(); firingDirToAdjustNorm = finalVec; #if ALLOW_PROJECTILEHELPER_DEBUGGING m_lastShotAutoAimedStatus.Format("TRUE + desired dir CONSTRAINED to allowed cone [desired]: %.3f deg [constrained To]: %.3f deg", RAD2DEG(acos(vecDot)), 0.5f * RAD2DEG(aimConeSettings.m_innerConeRads)); #endif //#if ALLOW_PROJECTILEHELPER_DEBUGGING } } } #if ALLOW_PROJECTILEHELPER_DEBUGGING else { m_lastShotAutoAimedStatus.Format("FALSE - CalculateBestProjectileAutoAimTarget NULL [Last reason]: %s", m_lastTargetRejectionReason.c_str()); } // Draw adjusted vec if (g_pGameCVars->pl_debug_projectileAimHelper) { float length = aimConeSettings.m_maxDistance; gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(attackerPos,ColorB(255,0,255,0),attackerPos + firingDirToAdjustNorm * length,ColorB(255,0,255,0)); } #endif //#if ALLOW_PROJECTILEHELPER_DEBUGGING firingDirToAdjust = firingDirToAdjustNorm*incomingDirLength; } }