diff --git a/Runtime/CGameOptions.cpp b/Runtime/CGameOptions.cpp index 1f662ef9d..5b8e4ff3a 100644 --- a/Runtime/CGameOptions.cpp +++ b/Runtime/CGameOptions.cpp @@ -117,7 +117,7 @@ CPersistentOptions::CPersistentOptions(CBitStreamReader& stream) { xd0_29_allItemsCollected = stream.ReadEncoded(1) != 0; xbc_autoMapperKeyState = stream.ReadEncoded(2); - auto& memWorlds = g_MemoryCardSys->GetMemoryWorlds(); + const auto& memWorlds = g_MemoryCardSys->GetMemoryWorlds(); size_t cinematicCount = 0; for (const auto& world : memWorlds) { TLockedToken saveWorld = @@ -162,7 +162,7 @@ void CPersistentOptions::PutTo(CBitStreamWriter& w) const { w.WriteEncoded(xd0_29_allItemsCollected, 1); w.WriteEncoded(xbc_autoMapperKeyState, 2); - auto& memWorlds = g_MemoryCardSys->GetMemoryWorlds(); + const auto& memWorlds = g_MemoryCardSys->GetMemoryWorlds(); for (const auto& world : memWorlds) { const TLockedToken saveWorld = g_SimplePool->GetObj(SObjectTag{FOURCC('SAVW'), world.second.GetSaveWorldAssetId()}); diff --git a/Runtime/CObjectList.hpp b/Runtime/CObjectList.hpp index 6222877b3..68efd1d1d 100644 --- a/Runtime/CObjectList.hpp +++ b/Runtime/CObjectList.hpp @@ -69,8 +69,8 @@ public: [[nodiscard]] iterator end() { return iterator(*this, -1); } [[nodiscard]] const_iterator begin() const { return const_iterator(*this, x2008_firstId); } [[nodiscard]] const_iterator end() const { return const_iterator(*this, -1); } - [[nodiscard]] const_iterator cbegin() const { return const_iterator(*this, x2008_firstId); } - [[nodiscard]] const_iterator cend() const { return const_iterator(*this, -1); } + [[nodiscard]] const_iterator cbegin() const { return begin(); } + [[nodiscard]] const_iterator cend() const { return end(); } explicit CObjectList(EGameObjectList listEnum); virtual ~CObjectList() = default; diff --git a/Runtime/CRelayTracker.cpp b/Runtime/CRelayTracker.cpp index 20f358742..9428af090 100644 --- a/Runtime/CRelayTracker.cpp +++ b/Runtime/CRelayTracker.cpp @@ -42,7 +42,7 @@ void CRelayTracker::RemoveRelay(TEditorId id) { return; } - x0_relayStates.erase(std::remove(x0_relayStates.begin(), x0_relayStates.end(), id), x0_relayStates.end()); + std::erase(x0_relayStates, id); } void CRelayTracker::SendMsgs(TAreaId areaId, CStateManager& stateMgr) { diff --git a/Runtime/CResLoader.cpp b/Runtime/CResLoader.cpp index 24318ad84..43cade117 100644 --- a/Runtime/CResLoader.cpp +++ b/Runtime/CResLoader.cpp @@ -132,10 +132,10 @@ void CResLoader::GetTagListForFile(const char* pakName, std::vector& bool CResLoader::_GetTagListForFile(std::vector& out, const std::string& path, const std::unique_ptr& file) const { if (CStringExtras::CompareCaseInsensitive(file->GetPath(), path)) { - auto& depList = file->GetDepList(); + const auto& depList = file->GetDepList(); out.reserve(depList.size()); for (const auto& dep : depList) { - auto resInfo = file->GetResInfo(dep); + const auto* const resInfo = file->GetResInfo(dep); out.emplace_back(resInfo->GetType(), dep); } return true; diff --git a/Runtime/CStateManager.cpp b/Runtime/CStateManager.cpp index f654c7905..2698a3d19 100644 --- a/Runtime/CStateManager.cpp +++ b/Runtime/CStateManager.cpp @@ -220,8 +220,9 @@ CStateManager::~CStateManager() { for (auto it = x808_objLists[0]->begin(); it != x808_objLists[0]->end();) { CEntity* ent = *it; ++it; - if (ent == x84c_player.get()) + if (ent == x84c_player.get()) { continue; + } ent->AcceptScriptMsg(EScriptObjectMessage::Deleted, kInvalidUniqueId, *this); RemoveObject(ent->GetUniqueId()); std::default_delete()(ent); @@ -237,52 +238,57 @@ CStateManager::~CStateManager() { void CStateManager::UpdateThermalVisor() { xf28_thermColdScale2 = 0.f; xf24_thermColdScale1 = 0.f; - CPlayerState::EPlayerVisor visor = x8b8_playerState->GetActiveVisor(*this); - if (visor == CPlayerState::EPlayerVisor::Thermal && x8cc_nextAreaId != kInvalidAreaId) { - CGameArea* area = x850_world->GetArea(x8cc_nextAreaId); - const zeus::CTransform& playerXf = x84c_player->GetTransform(); - zeus::CVector3f playerXYPos(playerXf.origin.x(), playerXf.origin.y(), 0.f); - CGameArea* lastArea = nullptr; - float closestDist = FLT_MAX; - for (const CGameArea::Dock& dock : area->GetDocks()) { - zeus::CVector3f dockCenter = (dock.GetPlaneVertices()[0] + dock.GetPlaneVertices()[1] + - dock.GetPlaneVertices()[2] + dock.GetPlaneVertices()[3]) * - 0.25f; - dockCenter.z() = 0.f; - float dist = (playerXYPos - dockCenter).magSquared(); - if (dist < closestDist) { - TAreaId connAreaId = dock.GetConnectedAreaId(0); - if (connAreaId != kInvalidAreaId) { - CGameArea* connArea = x850_world->GetArea(x8cc_nextAreaId); - if (connArea->IsPostConstructed()) { - CGameArea::EOcclusionState occState = connArea->GetPostConstructed()->x10dc_occlusionState; - if (occState == CGameArea::EOcclusionState::Visible) { - closestDist = dist; - lastArea = connArea; - } + + const auto visor = x8b8_playerState->GetActiveVisor(*this); + if (visor != CPlayerState::EPlayerVisor::Thermal || x8cc_nextAreaId == kInvalidAreaId) { + return; + } + + CGameArea* area = x850_world->GetArea(x8cc_nextAreaId); + const zeus::CTransform& playerXf = x84c_player->GetTransform(); + const zeus::CVector3f playerXYPos(playerXf.origin.x(), playerXf.origin.y(), 0.f); + CGameArea* lastArea = nullptr; + float closestDist = FLT_MAX; + for (const CGameArea::Dock& dock : area->GetDocks()) { + zeus::CVector3f dockCenter = (dock.GetPlaneVertices()[0] + dock.GetPlaneVertices()[1] + dock.GetPlaneVertices()[2] + + dock.GetPlaneVertices()[3]) * + 0.25f; + dockCenter.z() = 0.f; + const float dist = (playerXYPos - dockCenter).magSquared(); + if (dist < closestDist) { + const TAreaId connAreaId = dock.GetConnectedAreaId(0); + if (connAreaId != kInvalidAreaId) { + CGameArea* connArea = x850_world->GetArea(x8cc_nextAreaId); + if (connArea->IsPostConstructed()) { + const auto occState = connArea->GetPostConstructed()->x10dc_occlusionState; + if (occState == CGameArea::EOcclusionState::Visible) { + closestDist = dist; + lastArea = connArea; } } } } - - if (lastArea != nullptr) { - if (closestDist != 0.f) - closestDist /= std::sqrt(closestDist); - closestDist -= 2.f; - if (closestDist < 8.f) { - if (closestDist > 0.f) - closestDist = (closestDist / 8.f) * 0.5f + 0.5f; - else - closestDist = 0.5f; - - xf24_thermColdScale1 = (1.f - closestDist) * lastArea->GetPostConstructed()->x111c_thermalCurrent + - closestDist * area->GetPostConstructed()->x111c_thermalCurrent; - return; - } - } - - xf24_thermColdScale1 = area->GetPostConstructed()->x111c_thermalCurrent; } + + if (lastArea != nullptr) { + if (closestDist != 0.f) { + closestDist /= std::sqrt(closestDist); + } + closestDist -= 2.f; + if (closestDist < 8.f) { + if (closestDist > 0.f) { + closestDist = (closestDist / 8.f) * 0.5f + 0.5f; + } else { + closestDist = 0.5f; + } + + xf24_thermColdScale1 = (1.f - closestDist) * lastArea->GetPostConstructed()->x111c_thermalCurrent + + closestDist * area->GetPostConstructed()->x111c_thermalCurrent; + return; + } + } + + xf24_thermColdScale1 = area->GetPostConstructed()->x111c_thermalCurrent; } void CStateManager::RendererDrawCallback(void* drawable, void* ctx, int type) { @@ -312,8 +318,9 @@ void CStateManager::RendererDrawCallback(void* drawable, void* ctx, int type) { } bool CStateManager::RenderLast(TUniqueId uid) { - if (x86c_stateManagerContainer->xf39c_renderLast.size() == 20) + if (x86c_stateManagerContainer->xf39c_renderLast.size() == 20) { return false; + } x86c_stateManagerContainer->xf39c_renderLast.push_back(uid); return true; } @@ -329,14 +336,16 @@ void CStateManager::AddDrawableActor(CActor& actor, const zeus::CVector3f& vec, } bool CStateManager::SpecialSkipCinematic() { - if (xf38_skipCineSpecialFunc == kInvalidUniqueId) + if (xf38_skipCineSpecialFunc == kInvalidUniqueId) { return false; + } - CScriptSpecialFunction* ent = static_cast(ObjectById(xf38_skipCineSpecialFunc)); - if (!ent || !ent->ShouldSkipCinematic(*this)) + auto* ent = static_cast(ObjectById(xf38_skipCineSpecialFunc)); + if (ent == nullptr || !ent->ShouldSkipCinematic(*this)) { return false; + } - bool hadRandom = x900_activeRandom != nullptr; + const bool hadRandom = x900_activeRandom != nullptr; SetActiveRandomToDefault(); x870_cameraManager->SkipCinematic(*this); ent->SkipCinematic(*this); @@ -348,9 +357,10 @@ bool CStateManager::SpecialSkipCinematic() { TAreaId CStateManager::GetVisAreaId() const { const CGameCamera* cam = static_cast(x870_cameraManager->GetCurrentCamera(*this)); const CBallCamera* ballCam = x870_cameraManager->GetBallCamera(); - TAreaId curArea = x850_world->x68_curAreaId; - if (cam != ballCam) + const TAreaId curArea = x850_world->x68_curAreaId; + if (cam != ballCam) { return curArea; + } const zeus::CVector3f& camTranslation = ballCam->GetTranslation(); zeus::CAABox camAABB(camTranslation, camTranslation); @@ -359,10 +369,13 @@ TAreaId CStateManager::GetVisAreaId() const { BuildNearList(nearList, camAABB, CMaterialFilter(EMaterialTypes::AIBlock, CMaterialList(), CMaterialFilter::EFilterType::Include), nullptr); - for (TUniqueId id : nearList) - if (TCastToConstPtr dock = GetObjectById(id)) - if (dock->GetAreaId() == curArea && dock->HasPointCrossedDock(*this, camTranslation)) + for (const TUniqueId id : nearList) { + if (const TCastToConstPtr dock = GetObjectById(id)) { + if (dock->GetAreaId() == curArea && dock->HasPointCrossedDock(*this, camTranslation)) { return dock->GetCurrentConnectedAreaId(*this); + } + } + } return curArea; } @@ -376,11 +389,14 @@ void CStateManager::RemoveWeaponId(TUniqueId uid, EWeaponType type) { x878_weapo void CStateManager::AddWeaponId(TUniqueId uid, EWeaponType type) { x878_weaponManager->IncrCount(uid, type); } void CStateManager::UpdateEscapeSequenceTimer(float dt) { - if (xf0c_escapeTimer <= 0.f) + if (xf0c_escapeTimer <= 0.f) { return; + } + xf0c_escapeTimer = std::max(FLT_EPSILON, xf0c_escapeTimer - dt); - if (xf0c_escapeTimer <= FLT_EPSILON) + if (xf0c_escapeTimer <= FLT_EPSILON) { x8b8_playerState->SetPlayerAlive(false); + } if (!g_EscapeShakeCountdownInit) { g_EscapeShakeCountdown = 0.f; @@ -388,14 +404,16 @@ void CStateManager::UpdateEscapeSequenceTimer(float dt) { } g_EscapeShakeCountdown -= dt; - if (g_EscapeShakeCountdown < 0.f) { - float factor = 1.f - xf0c_escapeTimer / xf10_escapeTotalTime; - float factor2 = factor * factor; - CCameraShakeData shakeData(1.f, factor2 * 0.2f * x900_activeRandom->Range(0.5f, 1.f)); - x870_cameraManager->AddCameraShaker(shakeData, true); - x88c_rumbleManager->Rumble(*this, ERumbleFxId::EscapeSequenceShake, 0.75f, ERumblePriority::One); - g_EscapeShakeCountdown = -12.f * factor2 + 15.f; + if (g_EscapeShakeCountdown >= 0.f) { + return; } + + const float factor = 1.f - xf0c_escapeTimer / xf10_escapeTotalTime; + const float factor2 = factor * factor; + const CCameraShakeData shakeData(1.f, factor2 * 0.2f * x900_activeRandom->Range(0.5f, 1.f)); + x870_cameraManager->AddCameraShaker(shakeData, true); + x88c_rumbleManager->Rumble(*this, ERumbleFxId::EscapeSequenceShake, 0.75f, ERumblePriority::One); + g_EscapeShakeCountdown = -12.f * factor2 + 15.f; } void CStateManager::ResetEscapeSequenceTimer(float time) { @@ -414,23 +432,28 @@ std::string CStateManager::HashInstanceName(CInputStream& in) { } void CStateManager::SetActorAreaId(CActor& actor, TAreaId aid) { - TAreaId actorAid = actor.GetAreaIdAlways(); - if (actorAid == aid) + const TAreaId actorAid = actor.GetAreaIdAlways(); + if (actorAid == aid) { return; + } if (actorAid != kInvalidAreaId) { CGameArea* area = x850_world->GetArea(actorAid); - if (area->IsPostConstructed()) + if (area->IsPostConstructed()) { area->GetAreaObjects()->RemoveObject(actor.GetUniqueId()); + } } actor.x4_areaId = aid; - if (aid == kInvalidAreaId) + if (aid == kInvalidAreaId) { return; + } + CGameArea* area = x850_world->GetArea(aid); - if (!area->IsPostConstructed() || area->GetAreaObjects()->GetValidObjectById(actor.GetUniqueId())) + if (!area->IsPostConstructed() || area->GetAreaObjects()->GetValidObjectById(actor.GetUniqueId())) { return; + } area->GetAreaObjects()->AddObject(actor); } @@ -438,33 +461,39 @@ void CStateManager::SetActorAreaId(CActor& actor, TAreaId aid) { void CStateManager::TouchSky() const { x850_world->TouchSky(); } void CStateManager::TouchPlayerActor() { - if (xf6c_playerActorHead == kInvalidUniqueId) + if (xf6c_playerActorHead == kInvalidUniqueId) { return; - if (CEntity* ent = ObjectById(xf6c_playerActorHead)) - static_cast(ent)->TouchModels(*this); -} + } -void CStateManager::DrawSpaceWarp(const zeus::CVector3f& v, float strength) const { - CPlayerState::EPlayerVisor visor = x8b8_playerState->GetActiveVisor(*this); - if (visor == CPlayerState::EPlayerVisor::Scan || visor == CPlayerState::EPlayerVisor::Combat) { - zeus::CVector3f screenV = - TCastToConstPtr(x870_cameraManager->GetCurrentCamera(*this))->ConvertToScreenSpace(v); - g_Renderer->DrawSpaceWarp(screenV, strength); + if (CEntity* ent = ObjectById(xf6c_playerActorHead)) { + static_cast(ent)->TouchModels(*this); } } +void CStateManager::DrawSpaceWarp(const zeus::CVector3f& v, float strength) const { + const CPlayerState::EPlayerVisor visor = x8b8_playerState->GetActiveVisor(*this); + + if (visor != CPlayerState::EPlayerVisor::Scan && visor != CPlayerState::EPlayerVisor::Combat) { + return; + } + + const zeus::CVector3f screenV = + TCastToConstPtr(x870_cameraManager->GetCurrentCamera(*this))->ConvertToScreenSpace(v); + g_Renderer->DrawSpaceWarp(screenV, strength); +} + void CStateManager::DrawReflection(const zeus::CVector3f& reflectPoint) { - zeus::CAABox aabb = x84c_player->GetBoundingBox(); - zeus::CVector3f playerPos = aabb.center(); + const zeus::CAABox aabb = x84c_player->GetBoundingBox(); + const zeus::CVector3f playerPos = aabb.center(); zeus::CVector3f surfToPlayer = playerPos - reflectPoint; surfToPlayer.z() = 0.f; - zeus::CVector3f viewPos = playerPos - surfToPlayer.normalized() * 3.5f; - zeus::CTransform look = zeus::lookAt(viewPos, playerPos, {0.f, 0.f, -1.f}); + const zeus::CVector3f viewPos = playerPos - surfToPlayer.normalized() * 3.5f; + const zeus::CTransform look = zeus::lookAt(viewPos, playerPos, {0.f, 0.f, -1.f}); - zeus::CTransform backupView = CGraphics::g_ViewMatrix; + const zeus::CTransform backupView = CGraphics::g_ViewMatrix; CGraphics::SetViewPointMatrix(look); - CGraphics::CProjectionState backupProj = CGraphics::GetProjectionState(); - CGameCamera* cam = x870_cameraManager->GetCurrentCamera(*this); + const CGraphics::CProjectionState backupProj = CGraphics::GetProjectionState(); + const CGameCamera* cam = x870_cameraManager->GetCurrentCamera(*this); g_Renderer->SetPerspective(cam->GetFov(), g_Viewport.x8_width, g_Viewport.xc_height, cam->GetNearClipDistance(), cam->GetFarClipDistance()); @@ -490,16 +519,18 @@ void CStateManager::BuildDynamicLightListForWorld() { return; } - if (GetLightObjectList().size() == 0) + if (GetLightObjectList().size()) { return; + } x8e0_dynamicLights.clear(); - for (CEntity* ent : GetLightObjectList()) { - CGameLight& light = static_cast(*ent); + for (const CEntity* ent : GetLightObjectList()) { + const auto& light = static_cast(*ent); if (light.GetActive()) { - CLight l = light.GetLight(); - if (l.GetIntensity() > FLT_EPSILON && l.GetRadius() > FLT_EPSILON) + const CLight l = light.GetLight(); + if (l.GetIntensity() > FLT_EPSILON && l.GetRadius() > FLT_EPSILON) { x8e0_dynamicLights.push_back(l); + } } } } @@ -507,7 +538,7 @@ void CStateManager::BuildDynamicLightListForWorld() { void CStateManager::DrawDebugStuff() const { #ifndef NDEBUG for (CEntity* ent : GetActorObjectList()) { - if (TCastToPtr ai = ent) { + if (const TCastToPtr ai = ent) { if (CPathFindSearch* path = ai->GetSearchPath()) { path->DebugDraw(); } @@ -525,43 +556,47 @@ void CStateManager::RenderCamerasAndAreaLights() { void CStateManager::DrawE3DeathEffect() { const CPlayer& player = *x84c_player; - if (player.x9f4_deathTime > 0.f) { - if (player.x2f8_morphBallState != CPlayer::EPlayerMorphBallState::Unmorphed) { - float blurAmt = zeus::clamp(0.f, (player.x9f4_deathTime - 1.f) / (6.f - 1.f), 1.f); - if (blurAmt > 0.f) { - CCameraBlurPass blur; - blur.SetBlur(EBlurType::HiBlur, 7.f * blurAmt, 0.f); - blur.Draw(); - } - } - - const float whiteAmt = zeus::clamp(0.f, 1.f - player.x9f4_deathTime / (0.05f * 6.f), 1.f); - zeus::CColor color = zeus::skWhite; - color.a() = whiteAmt; - m_deathWhiteout.draw(color); + if (player.x9f4_deathTime <= 0.f) { + return; } + + if (player.x2f8_morphBallState != CPlayer::EPlayerMorphBallState::Unmorphed) { + const float blurAmt = zeus::clamp(0.f, (player.x9f4_deathTime - 1.f) / (6.f - 1.f), 1.f); + if (blurAmt > 0.f) { + CCameraBlurPass blur; + blur.SetBlur(EBlurType::HiBlur, 7.f * blurAmt, 0.f); + blur.Draw(); + } + } + + const float whiteAmt = zeus::clamp(0.f, 1.f - player.x9f4_deathTime / (0.05f * 6.f), 1.f); + zeus::CColor color = zeus::skWhite; + color.a() = whiteAmt; + m_deathWhiteout.draw(color); } void CStateManager::DrawAdditionalFilters() { - if (xf0c_escapeTimer < 1.f && xf0c_escapeTimer > 0.f && !x870_cameraManager->IsInCinematicCamera()) { - zeus::CColor color = zeus::skWhite; - color.a() = 1.f - xf0c_escapeTimer; - m_escapeWhiteout.draw(color); + if (xf0c_escapeTimer >= 1.f || xf0c_escapeTimer <= 0.f || x870_cameraManager->IsInCinematicCamera()) { + return; } + + zeus::CColor color = zeus::skWhite; + color.a() = 1.f - xf0c_escapeTimer; + m_escapeWhiteout.draw(color); } zeus::CFrustum CStateManager::SetupDrawFrustum(const SViewport& vp) const { zeus::CFrustum ret; const CGameCamera* cam = x870_cameraManager->GetCurrentCamera(*this); - zeus::CTransform camXf = x870_cameraManager->GetCurrentCameraTransform(*this); - int vpWidth = xf2c_viewportScale.x() * vp.x8_width; - int vpHeight = xf2c_viewportScale.y() * vp.xc_height; - int vpLeft = (vp.x8_width - vpWidth) / 2 + vp.x0_left; - int vpTop = (vp.xc_height - vpHeight) / 2 + vp.x4_top; + const zeus::CTransform camXf = x870_cameraManager->GetCurrentCameraTransform(*this); + const int vpWidth = static_cast(xf2c_viewportScale.x() * vp.x8_width); + const int vpHeight = static_cast(xf2c_viewportScale.y() * vp.xc_height); + const int vpLeft = static_cast((vp.x8_width - vpWidth) / 2 + vp.x0_left); + const int vpTop = static_cast((vp.xc_height - vpHeight) / 2 + vp.x4_top); g_Renderer->SetViewport(vpLeft, vpTop, vpWidth, vpHeight); - float fov = std::atan(std::tan(zeus::degToRad(cam->GetFov()) * 0.5f) * xf2c_viewportScale.y()) * 2.f; - float width = xf2c_viewportScale.x() * vp.x8_width; - float height = xf2c_viewportScale.y() * vp.xc_height; + const float fov = std::atan(std::tan(zeus::degToRad(cam->GetFov()) * 0.5f) * xf2c_viewportScale.y()) * 2.f; + const float width = xf2c_viewportScale.x() * vp.x8_width; + const float height = xf2c_viewportScale.y() * vp.xc_height; zeus::CProjection proj; proj.setPersp(zeus::SProjPersp{fov, width / height, cam->GetNearClipDistance(), cam->GetFarClipDistance()}); ret.updatePlanes(camXf, proj); @@ -570,18 +605,18 @@ zeus::CFrustum CStateManager::SetupDrawFrustum(const SViewport& vp) const { zeus::CFrustum CStateManager::SetupViewForDraw(const SViewport& vp) const { const CGameCamera* cam = x870_cameraManager->GetCurrentCamera(*this); - zeus::CTransform camXf = x870_cameraManager->GetCurrentCameraTransform(*this); + const zeus::CTransform camXf = x870_cameraManager->GetCurrentCameraTransform(*this); g_Renderer->SetWorldViewpoint(camXf); CBooModel::SetNewPlayerPositionAndTime(x84c_player->GetTranslation()); - int vpWidth = xf2c_viewportScale.x() * vp.x8_width; - int vpHeight = xf2c_viewportScale.y() * vp.xc_height; - int vpLeft = (vp.x8_width - vpWidth) / 2 + vp.x0_left; - int vpTop = (vp.xc_height - vpHeight) / 2 + vp.x4_top; + const int vpWidth = static_cast(xf2c_viewportScale.x() * vp.x8_width); + const int vpHeight = static_cast(xf2c_viewportScale.y() * vp.xc_height); + const int vpLeft = static_cast((vp.x8_width - vpWidth) / 2 + vp.x0_left); + const int vpTop = static_cast((vp.xc_height - vpHeight) / 2 + vp.x4_top); g_Renderer->SetViewport(vpLeft, vpTop, vpWidth, vpHeight); CGraphics::SetDepthRange(DEPTH_WORLD, DEPTH_FAR); - float fov = std::atan(std::tan(zeus::degToRad(cam->GetFov()) * 0.5f) * xf2c_viewportScale.y()) * 2.f; - float width = xf2c_viewportScale.x() * vp.x8_width; - float height = xf2c_viewportScale.y() * vp.xc_height; + const float fov = std::atan(std::tan(zeus::degToRad(cam->GetFov()) * 0.5f) * xf2c_viewportScale.y()) * 2.f; + const float width = xf2c_viewportScale.x() * vp.x8_width; + const float height = xf2c_viewportScale.y() * vp.xc_height; g_Renderer->SetPerspective(zeus::radToDeg(fov), width, height, cam->GetNearClipDistance(), cam->GetFarClipDistance()); zeus::CFrustum frustum; zeus::CProjection proj; @@ -596,8 +631,8 @@ zeus::CFrustum CStateManager::SetupViewForDraw(const SViewport& vp) const { } zeus::CFrustum CStateManager::SetupViewForCubeFaceDraw(const zeus::CVector3f& pos, int face) const { - zeus::CTransform mainCamXf = x870_cameraManager->GetCurrentCameraTransform(*this); - zeus::CTransform camXf = zeus::CTransform(mainCamXf.basis * CGraphics::skCubeBasisMats[face], pos); + const zeus::CTransform mainCamXf = x870_cameraManager->GetCurrentCameraTransform(*this); + const zeus::CTransform camXf = zeus::CTransform(mainCamXf.basis * CGraphics::skCubeBasisMats[face], pos); g_Renderer->SetWorldViewpoint(camXf); CBooModel::SetNewPlayerPositionAndTime(x84c_player->GetTranslation()); constexpr float width = CUBEMAP_RES; @@ -683,8 +718,8 @@ void CStateManager::DrawWorld() { int mask; int targetMask; - CPlayerState::EPlayerVisor visor = x8b8_playerState->GetActiveVisor(*this); - bool thermal = visor == CPlayerState::EPlayerVisor::Thermal; + const auto visor = x8b8_playerState->GetActiveVisor(*this); + const bool thermal = visor == CPlayerState::EPlayerVisor::Thermal; if (thermal) { xf34_thermalFlag = EThermalDrawFlag::Cold; mask = 0x34; @@ -707,17 +742,19 @@ void CStateManager::DrawWorld() { g_Renderer->DrawUnsortedGeometry(area.x4_selfIdx, mask, targetMask); } - if (!SetupFogForDraw()) + if (!SetupFogForDraw()) { g_Renderer->SetWorldFog(ERglFogMode::None, 0.f, 1.f, zeus::skBlack); + } x850_world->DrawSky(zeus::CTransform::Translate(CGraphics::g_ViewPoint)); - if (areaCount) + if (areaCount != 0) { SetupFogForArea(*areaArr[areaCount - 1]); + } for (const TUniqueId id : x86c_stateManagerContainer->xf370_) { if (auto* ent = static_cast(ObjectById(id))) { - if (!thermal || ent->xe6_27_thermalVisorFlags & 0x1) { + if (!thermal || (ent->xe6_27_thermalVisorFlags & 1) != 0) { ent->Render(*this); } } @@ -729,20 +766,24 @@ void CStateManager::DrawWorld() { for (int i = 0; i < areaCount; ++i) { const CGameArea& area = *areaArr[i]; CPVSVisSet& pvs = pvsArr[i]; - bool isVisArea = area.x4_selfIdx == visAreaId; + const bool isVisArea = area.x4_selfIdx == visAreaId; SetupFogForArea(area); g_Renderer->SetWorldLightFadeLevel(area.GetPostConstructed()->x1128_worldLightingLevel); for (CEntity* ent : *area.GetAreaObjects()) { - if (TCastToPtr actor = ent) { - if (!actor->IsDrawEnabled()) + if (const TCastToPtr actor = ent) { + if (!actor->IsDrawEnabled()) { continue; - TUniqueId actorId = actor->GetUniqueId(); - if (!thermal && area.LookupPVSUniqueID(actorId) == actorId) - if (pvs.GetVisible(area.LookupPVSID(actorId)) == EPVSVisSetState::EndOfTree) + } + const TUniqueId actorId = actor->GetUniqueId(); + if (!thermal && area.LookupPVSUniqueID(actorId) == actorId) { + if (pvs.GetVisible(area.LookupPVSID(actorId)) == EPVSVisSetState::EndOfTree) { continue; + } + } if (x84c_player.get() == actor.GetPtr()) { - if (thermal) + if (thermal) { continue; + } switch (x84c_player->GetMorphballTransitionState()) { case CPlayer::EPlayerMorphBallState::Unmorphed: case CPlayer::EPlayerMorphBallState::Morphed: @@ -753,10 +794,12 @@ void CStateManager::DrawWorld() { continue; } } - if (!thermal || actor->xe6_27_thermalVisorFlags & 0x1) + if (!thermal || (actor->xe6_27_thermalVisorFlags & 1) != 0) { actor->AddToRenderer(frustum, *this); - if (thermal && actor->xe6_27_thermalVisorFlags & 0x2) + } + if (thermal && (actor->xe6_27_thermalVisorFlags & 2) != 0) { thermalActorArr[thermalActorCount++] = actor.GetPtr(); + } } } @@ -769,8 +812,9 @@ void CStateManager::DrawWorld() { x84c_player->GetMorphBall()->DrawBallShadow(*this); - if (xf7c_projectedShadow) + if (xf7c_projectedShadow != nullptr) { xf7c_projectedShadow->Render(*this); + } g_Renderer->EnablePVS(pvs, area.x4_selfIdx); g_Renderer->DrawSortedGeometry(area.x4_selfIdx, mask, targetMask); @@ -778,8 +822,9 @@ void CStateManager::DrawWorld() { x880_envFxManager->Render(*this); - if (morphingPlayerVisible) + if (morphingPlayerVisible) { x84c_player->Render(*this); + } g_Renderer->PostRenderFogs(); @@ -788,7 +833,7 @@ void CStateManager::DrawWorld() { CGraphics::SetDepthRange(DEPTH_SCREEN_ACTORS, DEPTH_GUN); for (const TUniqueId id : x86c_stateManagerContainer->xf39c_renderLast) { if (auto* actor = static_cast(ObjectById(id))) { - if (actor->xe6_27_thermalVisorFlags & 0x1) { + if ((actor->xe6_27_thermalVisorFlags & 1) != 0) { actor->Render(*this); } } @@ -800,7 +845,7 @@ void CStateManager::DrawWorld() { for (const TUniqueId id : x86c_stateManagerContainer->xf370_) { if (auto* actor = static_cast(ObjectById(id))) { - if (actor->xe6_27_thermalVisorFlags & 0x2) { + if ((actor->xe6_27_thermalVisorFlags & 2) != 0) { actor->Render(*this); } } @@ -823,17 +868,20 @@ void CStateManager::DrawWorld() { for (int j = 0; j < thermalActorCount; ++j) { CActor* actor = thermalActorArr[j]; - if (actor->GetAreaIdAlways() != area.x4_selfIdx) - if (actor->GetAreaIdAlways() != kInvalidAreaId || area.x4_selfIdx != visAreaId) + if (actor->GetAreaIdAlways() != area.x4_selfIdx) { + if (actor->GetAreaIdAlways() != kInvalidAreaId || area.x4_selfIdx != visAreaId) { continue; + } + } actor->AddToRenderer(frustum, *this); } if (areaCount - 1 == i) { x884_actorModelParticles->AddStragglersToRenderer(*this); CDecalManager::AddToRenderer(frustum, *this); - if (x84c_player) + if (x84c_player) { x84c_player->AddToRenderer(frustum, *this); + } } ++x8dc_objectDrawToken; @@ -850,12 +898,14 @@ void CStateManager::DrawWorld() { g_Renderer->SetWorldFog(ERglFogMode::None, 0.f, 1.f, zeus::skBlack); #if 0 - if (false) + if (false) { CacheReflection(); + } #endif - if (x84c_player) + if (x84c_player) { x84c_player->RenderGun(*this, x870_cameraManager->GetGlobalCameraTranslation(*this)); + } if (x86c_stateManagerContainer->xf39c_renderLast.size()) { CGraphics::SetDepthRange(DEPTH_SCREEN_ACTORS, DEPTH_GUN); @@ -887,8 +937,8 @@ void CStateManager::DrawActorCubeFaces(CActor& actor, int& cubeInst) const { (!TCastToPtr(actor) && (!actor.GetActive() || !actor.IsDrawEnabled() || actor.xe4_30_outOfFrustum))) return; - TAreaId visAreaId = actor.GetAreaIdAlways(); - SViewport backupVp = g_Viewport; + const TAreaId visAreaId = actor.GetAreaIdAlways(); + const SViewport backupVp = g_Viewport; int areaCount = 0; std::array areaArr; @@ -896,7 +946,7 @@ void CStateManager::DrawActorCubeFaces(CActor& actor, int& cubeInst) const { if (areaCount == 10) { break; } - CGameArea::EOcclusionState occState = CGameArea::EOcclusionState::Occluded; + auto occState = CGameArea::EOcclusionState::Occluded; if (area.IsPostConstructed()) { occState = area.GetOcclusionState(); } @@ -945,8 +995,9 @@ void CStateManager::DrawActorCubeFaces(CActor& actor, int& cubeInst) const { g_Renderer->DrawUnsortedGeometry(area.x4_selfIdx, 0x2, 0x0); } - if (!SetupFogForDraw()) + if (!SetupFogForDraw()) { g_Renderer->SetWorldFog(ERglFogMode::None, 0.f, 1.f, zeus::skBlack); + } x850_world->DrawSky(zeus::CTransform::Translate(CGraphics::g_ViewPoint)); @@ -975,7 +1026,7 @@ void CStateManager::DrawWorldCubeFaces() const { if (areaCount == areaArr.size()) { break; } - CGameArea::EOcclusionState occState = CGameArea::EOcclusionState::Occluded; + auto occState = CGameArea::EOcclusionState::Occluded; if (area.IsPostConstructed()) { occState = area.GetOcclusionState(); } @@ -988,52 +1039,65 @@ void CStateManager::DrawWorldCubeFaces() const { const CGameArea& area = *areaArr[ai]; int cubeInst = 0; for (CEntity* ent : *area.GetAreaObjects()) { - if (TCastToPtr actor = ent) + if (const TCastToPtr actor = ent) { DrawActorCubeFaces(*actor, cubeInst); + } } } } void CStateManager::SetupFogForArea3XRange(TAreaId area) const { - if (area == kInvalidAreaId) + if (area == kInvalidAreaId) { area = x8cc_nextAreaId; + } + const CGameArea* areaObj = x850_world->GetAreaAlways(area); - if (areaObj->IsPostConstructed()) + if (areaObj->IsPostConstructed()) { SetupFogForArea3XRange(*areaObj); -} - -void CStateManager::SetupFogForArea(TAreaId area) const { - if (area == kInvalidAreaId) - area = x8cc_nextAreaId; - const CGameArea* areaObj = x850_world->GetAreaAlways(area); - if (areaObj->IsPostConstructed()) - SetupFogForArea(*areaObj); -} - -void CStateManager::SetupFogForAreaNonCurrent(TAreaId area) const { - if (area == kInvalidAreaId) - area = x8cc_nextAreaId; - const CGameArea* areaObj = x850_world->GetAreaAlways(area); - if (areaObj->IsPostConstructed()) - SetupFogForAreaNonCurrent(*areaObj); -} - -void CStateManager::SetupFogForArea3XRange(const CGameArea& area) const { - if (x8b8_playerState->GetActiveVisor(*this) == CPlayerState::EPlayerVisor::XRay) { - float fogDist = area.GetXRayFogDistance(); - float farz = (g_tweakGui->GetXRayFogNearZ() * (1.f - fogDist) + g_tweakGui->GetXRayFogFarZ() * fogDist) * 3.f; - g_Renderer->SetWorldFog(ERglFogMode(g_tweakGui->GetXRayFogMode()), g_tweakGui->GetXRayFogNearZ(), farz, - g_tweakGui->GetXRayFogColor()); } } -void CStateManager::SetupFogForArea(const CGameArea& area) const { - if (SetupFogForDraw()) +void CStateManager::SetupFogForArea(TAreaId area) const { + if (area == kInvalidAreaId) { + area = x8cc_nextAreaId; + } + + const CGameArea* areaObj = x850_world->GetAreaAlways(area); + if (areaObj->IsPostConstructed()) { + SetupFogForArea(*areaObj); + } +} + +void CStateManager::SetupFogForAreaNonCurrent(TAreaId area) const { + if (area == kInvalidAreaId) { + area = x8cc_nextAreaId; + } + + const CGameArea* areaObj = x850_world->GetAreaAlways(area); + if (areaObj->IsPostConstructed()) { + SetupFogForAreaNonCurrent(*areaObj); + } +} + +void CStateManager::SetupFogForArea3XRange(const CGameArea& area) const { + if (x8b8_playerState->GetActiveVisor(*this) != CPlayerState::EPlayerVisor::XRay) { return; + } + + const float fogDist = area.GetXRayFogDistance(); + const float farz = (g_tweakGui->GetXRayFogNearZ() * (1.f - fogDist) + g_tweakGui->GetXRayFogFarZ() * fogDist) * 3.f; + g_Renderer->SetWorldFog(ERglFogMode(g_tweakGui->GetXRayFogMode()), g_tweakGui->GetXRayFogNearZ(), farz, + g_tweakGui->GetXRayFogColor()); +} + +void CStateManager::SetupFogForArea(const CGameArea& area) const { + if (SetupFogForDraw()) { + return; + } if (x8b8_playerState->GetActiveVisor(*this) == CPlayerState::EPlayerVisor::XRay) { - float fogDist = area.GetXRayFogDistance(); - float farz = g_tweakGui->GetXRayFogNearZ() * (1.f - fogDist) + g_tweakGui->GetXRayFogFarZ() * fogDist; + const float fogDist = area.GetXRayFogDistance(); + const float farz = g_tweakGui->GetXRayFogNearZ() * (1.f - fogDist) + g_tweakGui->GetXRayFogFarZ() * fogDist; g_Renderer->SetWorldFog(ERglFogMode(g_tweakGui->GetXRayFogMode()), g_tweakGui->GetXRayFogNearZ(), farz, g_tweakGui->GetXRayFogColor()); } else { @@ -1042,15 +1106,18 @@ void CStateManager::SetupFogForArea(const CGameArea& area) const { } void CStateManager::SetupFogForAreaNonCurrent(const CGameArea& area) const { - if (SetupFogForDraw()) + if (SetupFogForDraw()) { return; - - if (x8b8_playerState->GetActiveVisor(*this) == CPlayerState::EPlayerVisor::XRay) { - float fogDist = area.GetXRayFogDistance(); - float farz = g_tweakGui->GetXRayFogNearZ() * (1.f - fogDist) + g_tweakGui->GetXRayFogFarZ() * fogDist; - g_Renderer->SetWorldFog(ERglFogMode(g_tweakGui->GetXRayFogMode()), g_tweakGui->GetXRayFogNearZ(), farz, - g_tweakGui->GetXRayFogColor()); } + + if (x8b8_playerState->GetActiveVisor(*this) != CPlayerState::EPlayerVisor::XRay) { + return; + } + + const float fogDist = area.GetXRayFogDistance(); + const float farz = g_tweakGui->GetXRayFogNearZ() * (1.f - fogDist) + g_tweakGui->GetXRayFogFarZ() * fogDist; + g_Renderer->SetWorldFog(ERglFogMode(g_tweakGui->GetXRayFogMode()), g_tweakGui->GetXRayFogNearZ(), farz, + g_tweakGui->GetXRayFogColor()); } bool CStateManager::SetupFogForDraw() const { @@ -1064,41 +1131,45 @@ bool CStateManager::SetupFogForDraw() const { case CPlayerState::EPlayerVisor::Combat: case CPlayerState::EPlayerVisor::Scan: auto& fog = x870_cameraManager->Fog(); - if (fog.IsFogDisabled()) + if (fog.IsFogDisabled()) { return false; + } fog.SetCurrent(); return true; } } void CStateManager::PreRender() { - if (xf94_24_readyToRender) { - SCOPED_GRAPHICS_DEBUG_GROUP("CStateManager::PreRender", zeus::skBlue); - zeus::CFrustum frustum = SetupDrawFrustum(g_Viewport); - x86c_stateManagerContainer->xf370_.clear(); - x86c_stateManagerContainer->xf39c_renderLast.clear(); - xf7c_projectedShadow = nullptr; - x850_world->PreRender(); - BuildDynamicLightListForWorld(); - for (const CGameArea& area : *x850_world) { - CGameArea::EOcclusionState occState = CGameArea::EOcclusionState::Occluded; - if (area.IsPostConstructed()) - occState = area.GetOcclusionState(); - if (occState == CGameArea::EOcclusionState::Visible) { - for (CEntity* ent : *area.GetPostConstructed()->x10c0_areaObjs) { - if (TCastToPtr act = ent) { - if (act->IsDrawEnabled()) { - act->CalculateRenderBounds(); - act->PreRender(*this, frustum); - } + if (!xf94_24_readyToRender) { + return; + } + + SCOPED_GRAPHICS_DEBUG_GROUP("CStateManager::PreRender", zeus::skBlue); + const zeus::CFrustum frustum = SetupDrawFrustum(g_Viewport); + x86c_stateManagerContainer->xf370_.clear(); + x86c_stateManagerContainer->xf39c_renderLast.clear(); + xf7c_projectedShadow = nullptr; + x850_world->PreRender(); + BuildDynamicLightListForWorld(); + for (const CGameArea& area : *x850_world) { + auto occState = CGameArea::EOcclusionState::Occluded; + if (area.IsPostConstructed()) { + occState = area.GetOcclusionState(); + } + if (occState == CGameArea::EOcclusionState::Visible) { + for (CEntity* ent : *area.GetPostConstructed()->x10c0_areaObjs) { + if (const TCastToPtr act = ent) { + if (act->IsDrawEnabled()) { + act->CalculateRenderBounds(); + act->PreRender(*this, frustum); } } } } - - CacheReflection(); - g_Renderer->PrepareDynamicLights(x8e0_dynamicLights); } + + CacheReflection(); + g_Renderer->PrepareDynamicLights(x8e0_dynamicLights); } void CStateManager::GetCharacterRenderMaskAndTarget(bool thawed, int& mask, int& target) const { @@ -1139,24 +1210,27 @@ void CStateManager::GetCharacterRenderMaskAndTarget(bool thawed, int& mask, int& } bool CStateManager::GetVisSetForArea(TAreaId a, TAreaId b, CPVSVisSet& setOut) const { - if (b == kInvalidAreaId) + if (b == kInvalidAreaId) { return false; + } - zeus::CVector3f viewPoint = CGraphics::g_ViewMatrix.origin; + const zeus::CVector3f viewPoint = CGraphics::g_ViewMatrix.origin; zeus::CVector3f closestDockPoint = viewPoint; bool hasClosestDock = false; if (a != b) { - CGameArea& area = *x850_world->GetGameAreas()[b]; + const CGameArea& area = *x850_world->GetGameAreas()[b]; if (area.IsPostConstructed()) { for (const CGameArea::Dock& dock : area.GetDocks()) { for (int i = 0; i < dock.GetDockRefs().size(); ++i) { - TAreaId connArea = dock.GetConnectedAreaId(i); + const TAreaId connArea = dock.GetConnectedAreaId(i); if (connArea == a) { const auto& verts = dock.GetPlaneVertices(); - zeus::CVector3f dockCenter = (verts[0] + verts[1] + verts[2] + verts[3]) * 0.25f; - if (hasClosestDock) - if ((dockCenter - viewPoint).magSquared() >= (closestDockPoint - viewPoint).magSquared()) + const zeus::CVector3f dockCenter = (verts[0] + verts[1] + verts[2] + verts[3]) * 0.25f; + if (hasClosestDock) { + if ((dockCenter - viewPoint).magSquared() >= (closestDockPoint - viewPoint).magSquared()) { continue; + } + } closestDockPoint = dockCenter; hasClosestDock = true; } @@ -1170,7 +1244,7 @@ bool CStateManager::GetVisSetForArea(TAreaId a, TAreaId b, CPVSVisSet& setOut) c if (hasClosestDock) { if (CPVSAreaSet* pvs = x850_world->GetGameAreas()[a]->GetPostConstructed()->xa0_pvs.get()) { const CPVSVisOctree& octree = pvs->GetVisOctree(); - zeus::CVector3f closestDockLocal = x850_world->GetGameAreas()[a]->GetInverseTransform() * closestDockPoint; + const zeus::CVector3f closestDockLocal = x850_world->GetGameAreas()[a]->GetInverseTransform() * closestDockPoint; CPVSVisSet set; set.SetTestPoint(octree, closestDockLocal); @@ -1199,12 +1273,16 @@ void CStateManager::RecursiveDrawTree(TUniqueId node) { } void CStateManager::SendScriptMsg(CEntity* dest, TUniqueId src, EScriptObjectMessage msg) { - if (dest && !dest->x30_26_scriptingBlocked) { - if (sm_logScripting && sm_logScripting->toBoolean()) - LogModule.report(logvisor::Info, FMT_STRING("Sending '{}' to '{}' id= {}"), ScriptObjectMessageToStr(msg), - dest->GetName(), dest->GetUniqueId()); - dest->AcceptScriptMsg(msg, src, *this); + if (dest == nullptr || dest->x30_26_scriptingBlocked) { + return; } + + if (sm_logScripting != nullptr && sm_logScripting->toBoolean()) { + LogModule.report(logvisor::Info, FMT_STRING("Sending '{}' to '{}' id= {}"), ScriptObjectMessageToStr(msg), + dest->GetName(), dest->GetUniqueId()); + } + + dest->AcceptScriptMsg(msg, src, *this); } void CStateManager::SendScriptMsg(TUniqueId dest, TUniqueId src, EScriptObjectMessage msg) { @@ -1214,30 +1292,38 @@ void CStateManager::SendScriptMsg(TUniqueId dest, TUniqueId src, EScriptObjectMe void CStateManager::SendScriptMsgAlways(TUniqueId dest, TUniqueId src, EScriptObjectMessage msg) { CEntity* dst = ObjectById(dest); - if (dst) { - if (sm_logScripting && sm_logScripting->toBoolean()) - LogModule.report(logvisor::Info, FMT_STRING("Sending '{}' to '{}' id= {}"), ScriptObjectMessageToStr(msg), - dst->GetName(), dst->GetUniqueId()); - dst->AcceptScriptMsg(msg, src, *this); + if (dst == nullptr) { + return; } + + if (sm_logScripting != nullptr && sm_logScripting->toBoolean()) { + LogModule.report(logvisor::Info, FMT_STRING("Sending '{}' to '{}' id= {}"), ScriptObjectMessageToStr(msg), + dst->GetName(), dst->GetUniqueId()); + } + + dst->AcceptScriptMsg(msg, src, *this); } void CStateManager::SendScriptMsg(TUniqueId src, TEditorId dest, EScriptObjectMessage msg, EScriptObjectState state) { // CEntity* ent = GetObjectById(src); - auto search = GetIdListForScript(dest); - if (search.first != x890_scriptIdMap.cend()) { - for (auto it = search.first; it != search.second; ++it) { - TUniqueId id = it->second; - CEntity* dobj = GetAllObjectList().GetObjectById(id); - SendScriptMsg(dobj, src, msg); - } + const auto search = GetIdListForScript(dest); + if (search.first == x890_scriptIdMap.cend()) { + return; + } + + for (auto it = search.first; it != search.second; ++it) { + const TUniqueId id = it->second; + CEntity* dobj = GetAllObjectList().GetObjectById(id); + SendScriptMsg(dobj, src, msg); } } void CStateManager::FreeScriptObjects(TAreaId aid) { - for (const auto& p : x890_scriptIdMap) - if (p.first.AreaNum() == aid) + for (const auto& p : x890_scriptIdMap) { + if (p.first.AreaNum() == aid) { FreeScriptObject(p.second); + } + } for (auto it = x8a4_loadedScriptObjects.begin(); it != x8a4_loadedScriptObjects.end();) { if (it->first.AreaNum() == aid) { @@ -1247,52 +1333,59 @@ void CStateManager::FreeScriptObjects(TAreaId aid) { ++it; } - CGameArea* area = x850_world->GetGameAreas()[aid].get(); + const CGameArea* area = x850_world->GetGameAreas()[aid].get(); if (area->IsPostConstructed()) { const CGameArea::CPostConstructed* pc = area->GetPostConstructed(); - for (CEntity* ent : *pc->x10c0_areaObjs) - if (ent && !ent->IsInUse()) + for (CEntity* ent : *pc->x10c0_areaObjs) { + if (ent != nullptr && !ent->IsInUse()) { FreeScriptObject(ent->GetUniqueId()); + } + } } } void CStateManager::FreeScriptObject(TUniqueId id) { CEntity* ent = ObjectById(id); - if (!ent || ent->IsInGraveyard()) + if (ent == nullptr || ent->IsInGraveyard()) { return; + } ent->SetIsInGraveyard(true); x854_objectGraveyard.push_back(id); ent->AcceptScriptMsg(EScriptObjectMessage::Deleted, kInvalidUniqueId, *this); ent->SetIsScriptingBlocked(true); - if (TCastToPtr act = ent) { + if (const TCastToPtr act = ent) { x874_sortedListManager->Remove(act.GetPtr()); act->SetUseInSortedLists(false); } - if (sm_logScripting && sm_logScripting->toBoolean()) + if (sm_logScripting && sm_logScripting->toBoolean()) { LogModule.report(logvisor::Info, FMT_STRING("Removed '{}'"), ent->GetName()); + } } std::pair CStateManager::GetBuildForScript(TEditorId id) const { - auto search = x8a4_loadedScriptObjects.find(id); - if (search == x8a4_loadedScriptObjects.cend()) + const auto search = x8a4_loadedScriptObjects.find(id); + if (search == x8a4_loadedScriptObjects.cend()) { return {nullptr, kInvalidEditorId}; + } return {&search->second, search->first}; } TEditorId CStateManager::GetEditorIdForUniqueId(TUniqueId id) const { const CEntity* ent = GetObjectById(id); - if (ent) + if (ent != nullptr) { return ent->GetEditorId(); + } return kInvalidEditorId; } TUniqueId CStateManager::GetIdForScript(TEditorId id) const { - auto search = x890_scriptIdMap.find(id); - if (search == x890_scriptIdMap.cend()) + const auto search = x890_scriptIdMap.find(id); + if (search == x890_scriptIdMap.cend()) { return kInvalidUniqueId; + } return search->second; } @@ -1308,18 +1401,24 @@ CStateManager::GetIdListForScript(TEditorId id) const { void CStateManager::LoadScriptObjects(TAreaId aid, CInputStream& in, std::vector& idsOut) { in.readUByte(); - int objCount = in.readUint32Big(); + + const u32 objCount = in.readUint32Big(); idsOut.reserve(idsOut.size() + objCount); - for (int i = 0; i < objCount; ++i) { - EScriptObjectType objType = EScriptObjectType(in.readUByte()); - u32 objSize = in.readUint32Big(); - u32 pos = in.position(); - auto id = LoadScriptObject(aid, objType, objSize, in); - if (id.first == kInvalidEditorId) + + for (u32 i = 0; i < objCount; ++i) { + const auto objType = static_cast(in.readUByte()); + const u32 objSize = in.readUint32Big(); + const u32 pos = static_cast(in.position()); + const auto id = LoadScriptObject(aid, objType, objSize, in); + if (id.first == kInvalidEditorId) { continue; - auto build = GetBuildForScript(id.first); - if (build.first) + } + + const auto build = GetBuildForScript(id.first); + if (build.first) { continue; + } + x8a4_loadedScriptObjects[id.first] = SScriptObjectStream{objType, pos, objSize}; idsOut.push_back(id.first); } @@ -1350,28 +1449,33 @@ std::pair CStateManager::LoadScriptObject(TAreaId aid, ESc } CEntity* ent = nullptr; - if (loader) { + if (loader != nullptr) { const CEntityInfo info(aid, std::move(conns), id); ent = loader(*this, in, propCount, info); } else { error = true; } - if (ent) + if (ent != nullptr) { AddObject(ent); - else + } else { error = true; + } - u32 readAmt = in.position() - startPos; - if (readAmt > length) - LogModule.report(logvisor::Fatal, FMT_STRING("Script object overread while reading {}"), ScriptObjectTypeToStr(type)); - u32 leftover = length - readAmt; - for (u32 i = 0; i < leftover; ++i) + const u32 readAmt = in.position() - startPos; + if (readAmt > length) { + LogModule.report(logvisor::Fatal, FMT_STRING("Script object overread while reading {}"), + ScriptObjectTypeToStr(type)); + } + + const u32 leftover = length - readAmt; + for (u32 i = 0; i < leftover; ++i) { in.readByte(); + } if (error || ent == nullptr) { in.seek(startPos, athena::SeekOrigin::Begin); - std::string name = HashInstanceName(in); + const std::string name = HashInstanceName(in); in.seek(startPos + length, athena::SeekOrigin::Begin); LogModule.report(logvisor::Error, FMT_STRING("Script load error while loading {}, name: {}"), ScriptObjectTypeToStr(type), name); @@ -1383,39 +1487,50 @@ std::pair CStateManager::LoadScriptObject(TAreaId aid, ESc } std::pair CStateManager::GenerateObject(TEditorId eid) { - std::pair build = GetBuildForScript(eid); + const std::pair build = GetBuildForScript(eid); + if (build.first) { - CGameArea* area = x850_world->GetArea(build.second.AreaNum()); + const CGameArea* area = x850_world->GetArea(build.second.AreaNum()); if (area->IsPostConstructed()) { - std::pair buf = area->GetLayerScriptBuffer(build.second.LayerNum()); + const std::pair buf = area->GetLayerScriptBuffer(build.second.LayerNum()); CMemoryInStream stream(buf.first + build.first->x4_position, build.first->x8_length); return LoadScriptObject(build.second.AreaNum(), build.first->x0_type, build.first->x8_length, stream); } } + return {kInvalidEditorId, kInvalidUniqueId}; } void CStateManager::InitScriptObjects(const std::vector& ids) { - for (TEditorId id : ids) { - if (id == kInvalidEditorId) + for (const TEditorId id : ids) { + if (id == kInvalidEditorId) { continue; - TUniqueId uid = GetIdForScript(id); + } + + const TUniqueId uid = GetIdForScript(id); SendScriptMsg(uid, kInvalidUniqueId, EScriptObjectMessage::InitializedInArea); } + MurderScriptInstanceNames(); } void CStateManager::InformListeners(const zeus::CVector3f& pos, EListenNoiseType type) { for (CEntity* ent : GetListeningAiObjectList()) { - if (TCastToPtr ai = ent) { - if (!ai->GetActive()) + if (const TCastToPtr ai = ent) { + if (!ai->GetActive()) { continue; + } + CGameArea* area = x850_world->GetArea(ai->GetAreaIdAlways()); CGameArea::EOcclusionState occState = CGameArea::EOcclusionState::Occluded; - if (area->IsPostConstructed()) + + if (area->IsPostConstructed()) { occState = area->GetPostConstructed()->x10dc_occlusionState; - if (occState != CGameArea::EOcclusionState::Occluded) + } + + if (occState != CGameArea::EOcclusionState::Occluded) { ai->Listen(pos, type); + } } } } @@ -1426,22 +1541,23 @@ void CStateManager::ApplyKnockBack(CActor& actor, const CDamageInfo& info, const return; } - CHealthInfo* hInfo = actor.HealthInfo(*this); + const CHealthInfo* hInfo = actor.HealthInfo(*this); if (hInfo == nullptr) { return; } - float dampedPower = (1.f - dampen) * info.GetKnockBackPower(); - if (TCastToPtr player = actor) { + const float dampedPower = (1.f - dampen) * info.GetKnockBackPower(); + if (const TCastToPtr player = actor) { KnockBackPlayer(*player, pos, dampedPower, hInfo->GetKnockbackResistance()); return; } - TCastToPtr ai = actor; + const TCastToPtr ai = actor; if (!ai && hInfo->GetHP() <= 0.f) { if (dampedPower > hInfo->GetKnockbackResistance()) { - if (TCastToPtr physActor = actor) { - zeus::CVector3f kbVec = pos * (dampedPower - hInfo->GetKnockbackResistance()) * physActor->GetMass() * 1.5f; + if (const TCastToPtr physActor = actor) { + const zeus::CVector3f kbVec = + pos * (dampedPower - hInfo->GetKnockbackResistance()) * physActor->GetMass() * 1.5f; if (physActor->GetMaterialList().HasMaterial(EMaterialTypes::Immovable) || !physActor->GetMaterialList().HasMaterial(EMaterialTypes::Solid)) { return; @@ -1466,7 +1582,7 @@ void CStateManager::KnockBackPlayer(CPlayer& player, const zeus::CVector3f& pos, float usePower; if (player.GetMorphballTransitionState() != CPlayer::EPlayerMorphBallState::Morphed) { usePower = power * 1000.f; - CPlayer::ESurfaceRestraints surface = + const auto surface = player.x2b0_outOfWaterTicks == 2 ? player.x2ac_surfaceRestraint : CPlayer::ESurfaceRestraints::Water; if (surface != CPlayer::ESurfaceRestraints::Normal && player.GetOrbitState() == CPlayer::EPlayerOrbitState::NoOrbit) { usePower /= 7.f; @@ -1475,41 +1591,41 @@ void CStateManager::KnockBackPlayer(CPlayer& player, const zeus::CVector3f& pos, usePower = power * 500.f; } - float minVel = player.GetMorphballTransitionState() == CPlayer::EPlayerMorphBallState::Morphed ? 35.f : 70.f; - float playerVel = player.x138_velocity.magnitude(); - float maxVel = std::max(playerVel, minVel); - zeus::CVector3f negVel = -player.x138_velocity; + const float minVel = player.GetMorphballTransitionState() == CPlayer::EPlayerMorphBallState::Morphed ? 35.f : 70.f; + const float playerVel = player.x138_velocity.magnitude(); + const float maxVel = std::max(playerVel, minVel); + const zeus::CVector3f negVel = -player.x138_velocity; usePower *= (1.f - 0.5f * zeus::CVector3f::getAngleDiff(pos, negVel) / M_PIF); player.ApplyImpulseWR(pos * usePower, zeus::CAxisAngle()); player.UseCollisionImpulses(); player.x2d4_accelerationChangeTimer = 0.25f; - float newVel = player.x138_velocity.magnitude(); + const float newVel = player.x138_velocity.magnitude(); if (newVel > maxVel) { - zeus::CVector3f vel = (1.f / newVel) * player.x138_velocity * maxVel; + const zeus::CVector3f vel = (1.f / newVel) * player.x138_velocity * maxVel; player.SetVelocityWR(vel); } } void CStateManager::ApplyDamageToWorld(TUniqueId damager, const CActor& actor, const zeus::CVector3f& pos, const CDamageInfo& info, const CMaterialFilter& filter) { - zeus::CAABox aabb(pos - info.GetRadius(), pos + info.GetRadius()); + const zeus::CAABox aabb(pos - info.GetRadius(), pos + info.GetRadius()); bool bomb = false; - TCastToConstPtr weapon = actor; + const TCastToConstPtr weapon = actor; if (weapon) { bomb = True(weapon->GetAttribField() & (EProjectileAttrib::Bombs | EProjectileAttrib::PowerBombs)); } rstl::reserved_vector nearList; BuildNearList(nearList, aabb, filter, &actor); - for (TUniqueId id : nearList) { + for (const TUniqueId id : nearList) { CEntity* ent = ObjectById(id); if (ent == nullptr) { continue; } - TCastToPtr player = ent; + const TCastToPtr player = ent; if (bomb && player) { if (player->GetFrozenState()) { g_GameState->SystemOptions().IncrementFrozenBallCount(); @@ -1527,11 +1643,11 @@ void CStateManager::ApplyDamageToWorld(TUniqueId damager, const CActor& actor, c } } - if (TCastToPtr swarm = ent) { + if (const TCastToPtr swarm = ent) { swarm->ApplyRadiusDamage(pos, info, *this); } - if (TCastToPtr swarm = ent) { + if (const TCastToPtr swarm = ent) { swarm->ApplyRadiusDamage(pos, info, *this); } } @@ -1539,18 +1655,20 @@ void CStateManager::ApplyDamageToWorld(TUniqueId damager, const CActor& actor, c void CStateManager::ProcessRadiusDamage(const CActor& damager, CActor& damagee, TUniqueId senderId, const CDamageInfo& info, const CMaterialFilter& filter) { - zeus::CAABox aabb(damager.GetTranslation() - info.GetRadius(), damager.GetTranslation() + info.GetRadius()); + const zeus::CAABox aabb(damager.GetTranslation() - info.GetRadius(), damager.GetTranslation() + info.GetRadius()); rstl::reserved_vector nearList; BuildNearList(nearList, aabb, filter, nullptr); - for (TUniqueId id : nearList) { + for (const TUniqueId id : nearList) { CEntity* ent = ObjectById(id); - if (!ent || ent->GetUniqueId() == damager.GetUniqueId() || ent->GetUniqueId() == senderId || - ent->GetUniqueId() == damagee.GetUniqueId()) + if (ent == nullptr || ent->GetUniqueId() == damager.GetUniqueId() || ent->GetUniqueId() == senderId || + ent->GetUniqueId() == damagee.GetUniqueId()) { continue; + } TestBombHittingWater(damager, damager.GetTranslation(), static_cast(*ent)); - if (TestRayDamage(damager.GetTranslation(), static_cast(*ent), nearList)) + if (TestRayDamage(damager.GetTranslation(), static_cast(*ent), nearList)) { ApplyRadiusDamage(damager, damager.GetTranslation(), static_cast(*ent), info); + } } } @@ -1572,7 +1690,7 @@ void CStateManager::ApplyRadiusDamage(const CActor& a1, const zeus::CVector3f& p } bool alive = false; - if (CHealthInfo* hInfo = a2.HealthInfo(*this)) { + if (const CHealthInfo* hInfo = a2.HealthInfo(*this)) { if (hInfo->GetHP() > 0.f) { alive = true; } @@ -1581,7 +1699,7 @@ void CStateManager::ApplyRadiusDamage(const CActor& a1, const zeus::CVector3f& p const CDamageVulnerability* vuln = rad > 0.f ? a2.GetDamageVulnerability(pos, delta, info) : a2.GetDamageVulnerability(); if (vuln->WeaponHurts(info.GetWeaponMode(), true)) { - float dam = info.GetRadiusDamage(*vuln); + const float dam = info.GetRadiusDamage(*vuln); if (dam > 0.f) { ApplyLocalDamage(pos, delta, a2, dam, info.GetWeaponMode()); } @@ -1601,38 +1719,44 @@ void CStateManager::ApplyRadiusDamage(const CActor& a1, const zeus::CVector3f& p bool CStateManager::TestRayDamage(const zeus::CVector3f& pos, const CActor& damagee, const rstl::reserved_vector& nearList) const { const CHealthInfo* hInfo = const_cast(damagee).HealthInfo(const_cast(*this)); - if (!hInfo) + if (hInfo == nullptr) { return false; + } static constexpr CMaterialList incList(EMaterialTypes::Solid); static constexpr CMaterialList exList(EMaterialTypes::ProjectilePassthrough, EMaterialTypes::Player, EMaterialTypes::Occluder, EMaterialTypes::Character); static constexpr CMaterialFilter filter(incList, exList, CMaterialFilter::EFilterType::IncludeExclude); - std::optional bounds = damagee.GetTouchBounds(); - if (!bounds) + const std::optional bounds = damagee.GetTouchBounds(); + if (!bounds) { return false; + } - zeus::CVector3f center = bounds->center(); + const zeus::CVector3f center = bounds->center(); zeus::CVector3f dir = center - pos; - if (!dir.canBeNormalized()) + if (!dir.canBeNormalized()) { return true; - float origMag = dir.magnitude(); + } + const float origMag = dir.magnitude(); dir = dir * (1.f / origMag); - if (RayCollideWorld(pos, center, nearList, filter, &damagee)) + if (RayCollideWorld(pos, center, nearList, filter, &damagee)) { return true; + } - zeus::CMRay ray(pos, dir, origMag); - if (!MultiRayCollideWorld(ray, filter)) + const zeus::CMRay ray(pos, dir, origMag); + if (!MultiRayCollideWorld(ray, filter)) { return false; + } float depth; zeus::CVector3f norm; - u32 count = CollisionUtil::RayAABoxIntersection(ray, *bounds, norm, depth); - if (count == 0 || count == 1) + const u32 count = CollisionUtil::RayAABoxIntersection(ray, *bounds, norm, depth); + if (count == 0 || count == 1) { return true; + } return CGameCollision::RayDynamicIntersectionBool(*this, pos, dir, filter, nearList, &damagee, depth * origMag); } @@ -1640,7 +1764,7 @@ bool CStateManager::TestRayDamage(const zeus::CVector3f& pos, const CActor& dama bool CStateManager::RayCollideWorld(const zeus::CVector3f& start, const zeus::CVector3f& end, const CMaterialFilter& filter, const CActor* damagee) const { zeus::CVector3f delta = end - start; - float mag = delta.magnitude(); + const float mag = delta.magnitude(); delta = delta / mag; rstl::reserved_vector nearList; BuildNearList(nearList, start, delta, mag, filter, damagee); @@ -1657,14 +1781,16 @@ bool CStateManager::RayCollideWorldInternal(const zeus::CVector3f& start, const const CMaterialFilter& filter, const rstl::reserved_vector& nearList, const CActor* damagee) const { - zeus::CVector3f delta = end - start; - if (!delta.canBeNormalized()) + const zeus::CVector3f delta = end - start; + if (!delta.canBeNormalized()) { return true; + } - float mag = delta.magnitude(); - zeus::CVector3f dir = delta * (1.f / mag); - if (!CGameCollision::RayStaticIntersectionBool(*this, start, dir, mag, filter)) + const float mag = delta.magnitude(); + const zeus::CVector3f dir = delta * (1.f / mag); + if (!CGameCollision::RayStaticIntersectionBool(*this, start, dir, mag, filter)) { return false; + } return CGameCollision::RayDynamicIntersectionBool(*this, start, dir, filter, nearList, damagee, mag); } @@ -1674,53 +1800,65 @@ bool CStateManager::MultiRayCollideWorld(const zeus::CMRay& ray, const CMaterial ray.dir.y() * ray.dir.y() - ray.dir.x() * -ray.dir.z()}; crossed.normalize(); - zeus::CVector3f crossed2 = ray.dir.cross(crossed) * 0.35355338f; - zeus::CVector3f negCrossed2 = -crossed2; - zeus::CVector3f rms = crossed * 0.35355338f; - zeus::CVector3f negRms = -rms; + const zeus::CVector3f crossed2 = ray.dir.cross(crossed) * 0.35355338f; + const zeus::CVector3f negCrossed2 = -crossed2; + const zeus::CVector3f rms = crossed * 0.35355338f; + const zeus::CVector3f negRms = -rms; for (int i = 0; i < 4; ++i) { - zeus::CVector3f& useCrossed = (i & 2) ? negCrossed2 : crossed2; - zeus::CVector3f& useRms = (i & 1) ? rms : negRms; - if (CGameCollision::RayStaticIntersectionBool(*this, ray.start + useCrossed + useRms, ray.dir, ray.length, filter)) + const zeus::CVector3f& useCrossed = (i & 2) != 0 ? negCrossed2 : crossed2; + const zeus::CVector3f& useRms = (i & 1) != 0 ? rms : negRms; + if (CGameCollision::RayStaticIntersectionBool(*this, ray.start + useCrossed + useRms, ray.dir, ray.length, + filter)) { return true; + } } return false; } void CStateManager::TestBombHittingWater(const CActor& damager, const zeus::CVector3f& pos, CActor& damagee) { - if (TCastToConstPtr wpn = damager) { - if (True(wpn->GetAttribField() & (EProjectileAttrib::Bombs | EProjectileAttrib::PowerBombs))) { - bool powerBomb = (wpn->GetAttribField() & EProjectileAttrib::PowerBombs) == EProjectileAttrib::PowerBombs; - if (TCastToPtr water = damagee) { - zeus::CAABox bounds = water->GetTriggerBoundsWR(); - zeus::CVector3f hitPos(pos.x(), pos.y(), bounds.max.z()); - float bombRad = powerBomb ? 4.f : 2.f; - float delta = bounds.max.z() - pos.dot(zeus::skUp); - if (delta <= bombRad && delta > 0.f) { - // Below surface - float rippleFactor = 1.f - delta / bombRad; - if (x87c_fluidPlaneManager->GetLastRippleDeltaTime(damager.GetUniqueId()) >= 0.15f) { - float bombMag = powerBomb ? 1.f : 0.75f; - float mag = 0.6f * bombMag + 0.4f * bombMag * std::sin(2.f * M_PIF * rippleFactor * 0.25f); - water->GetFluidPlane().AddRipple(mag, damager.GetUniqueId(), hitPos, *water, *this); - } - if (!powerBomb) - x87c_fluidPlaneManager->CreateSplash(damager.GetUniqueId(), *this, *water, hitPos, rippleFactor, true); - } else { - // Above surface - float bombMag = powerBomb ? 2.f : 1.f; - if (delta <= -bombMag || delta >= 0.f) - return; - CRayCastResult res = RayStaticIntersection(pos, zeus::skDown, -delta, CMaterialFilter::skPassEverything); - if (res.IsInvalid() && x87c_fluidPlaneManager->GetLastRippleDeltaTime(damager.GetUniqueId()) >= 0.15f) { - // Not blocked by static geometry - float mag = 0.6f * bombMag + 0.4f * bombMag * std::sin(2.f * M_PIF * -delta / bombMag * 0.25f); - water->GetFluidPlane().AddRipple(mag, damager.GetUniqueId(), hitPos, *water, *this); - } - } - } + const TCastToConstPtr wpn = damager; + if (!wpn) { + return; + } + + if (False(wpn->GetAttribField() & (EProjectileAttrib::Bombs | EProjectileAttrib::PowerBombs))) { + return; + } + + const bool powerBomb = (wpn->GetAttribField() & EProjectileAttrib::PowerBombs) == EProjectileAttrib::PowerBombs; + const TCastToPtr water = damagee; + if (!water) { + return; + } + + const zeus::CAABox bounds = water->GetTriggerBoundsWR(); + const zeus::CVector3f hitPos(pos.x(), pos.y(), bounds.max.z()); + const float bombRad = powerBomb ? 4.f : 2.f; + const float delta = bounds.max.z() - pos.dot(zeus::skUp); + if (delta <= bombRad && delta > 0.f) { + // Below surface + const float rippleFactor = 1.f - delta / bombRad; + if (x87c_fluidPlaneManager->GetLastRippleDeltaTime(damager.GetUniqueId()) >= 0.15f) { + const float bombMag = powerBomb ? 1.f : 0.75f; + const float mag = 0.6f * bombMag + 0.4f * bombMag * std::sin(2.f * M_PIF * rippleFactor * 0.25f); + water->GetFluidPlane().AddRipple(mag, damager.GetUniqueId(), hitPos, *water, *this); + } + if (!powerBomb) { + x87c_fluidPlaneManager->CreateSplash(damager.GetUniqueId(), *this, *water, hitPos, rippleFactor, true); + } + } else { + // Above surface + const float bombMag = powerBomb ? 2.f : 1.f; + if (delta <= -bombMag || delta >= 0.f) { + return; + } + const CRayCastResult res = RayStaticIntersection(pos, zeus::skDown, -delta, CMaterialFilter::skPassEverything); + if (res.IsInvalid() && x87c_fluidPlaneManager->GetLastRippleDeltaTime(damager.GetUniqueId()) >= 0.15f) { + // Not blocked by static geometry + const float mag = 0.6f * bombMag + 0.4f * bombMag * std::sin(2.f * M_PIF * -delta / bombMag * 0.25f); + water->GetFluidPlane().AddRipple(mag, damager.GetUniqueId(), hitPos, *water, *this); } } } @@ -1728,57 +1866,69 @@ void CStateManager::TestBombHittingWater(const CActor& damager, const zeus::CVec bool CStateManager::ApplyLocalDamage(const zeus::CVector3f& pos, const zeus::CVector3f& dir, CActor& damagee, float dam, const CWeaponMode& weapMode) { CHealthInfo* hInfo = damagee.HealthInfo(*this); - if (!hInfo || dam < 0.f) + if (hInfo == nullptr || dam < 0.f) { return false; + } - if (hInfo->GetHP() <= 0.f) + if (hInfo->GetHP() <= 0.f) { return true; + } float mulDam = dam; TCastToPtr player = damagee; CAi* ai = TCastToPtr(damagee).GetPtr(); - if (!ai) + if (ai == nullptr) { ai = TCastToPtr(damagee).GetPtr(); + } if (player) { if (GetPlayerState()->CanTakeDamage()) { if (x870_cameraManager->IsInCinematicCamera() || (weapMode.GetType() == EWeaponType::Phazon && - x8b8_playerState->HasPowerUp(CPlayerState::EItemType::PhazonSuit))) + x8b8_playerState->HasPowerUp(CPlayerState::EItemType::PhazonSuit))) { return false; + } - if (g_GameState->GetHardMode()) + if (g_GameState->GetHardMode()) { mulDam *= g_GameState->GetHardModeDamageMultiplier(); + } float damReduction = 0.f; - if (x8b8_playerState->HasPowerUp(CPlayerState::EItemType::VariaSuit)) + if (x8b8_playerState->HasPowerUp(CPlayerState::EItemType::VariaSuit)) { damReduction = g_tweakPlayer->GetVariaDamageReduction(); - if (x8b8_playerState->HasPowerUp(CPlayerState::EItemType::GravitySuit)) + } + if (x8b8_playerState->HasPowerUp(CPlayerState::EItemType::GravitySuit)) { damReduction = std::max(g_tweakPlayer->GetGravityDamageReduction(), damReduction); - if (x8b8_playerState->HasPowerUp(CPlayerState::EItemType::PhazonSuit)) + } + if (x8b8_playerState->HasPowerUp(CPlayerState::EItemType::PhazonSuit)) { damReduction = std::max(g_tweakPlayer->GetPhazonDamageReduction(), damReduction); + } mulDam = -(damReduction * mulDam - mulDam); - } else + } else { mulDam = 0.f; + } } - float newHp = hInfo->GetHP() - mulDam; - bool significant = std::fabs(newHp - hInfo->GetHP()) >= 0.00001; + const float newHp = hInfo->GetHP() - mulDam; + const bool significant = std::fabs(newHp - hInfo->GetHP()) >= 0.00001; hInfo->SetHP(newHp); if (player && GetPlayerState()->CanTakeDamage()) { player->TakeDamage(significant, pos, mulDam, weapMode.GetType(), *this); - if (newHp <= 0.f) + if (newHp <= 0.f) { x8b8_playerState->SetPlayerAlive(false); + } } - if (ai) { - if (significant) + if (ai != nullptr) { + if (significant) { ai->TakeDamage(dir, mulDam); - if (newHp <= 0.f) + } + if (newHp <= 0.f) { ai->Death(*this, dir, EScriptObjectState::DeathRattle); + } } return significant; @@ -1789,29 +1939,31 @@ bool CStateManager::ApplyDamage(TUniqueId damagerId, TUniqueId damageeId, TUniqu const zeus::CVector3f& knockbackVec) { CEntity* ent0 = ObjectById(damagerId); CEntity* ent1 = ObjectById(damageeId); - TCastToPtr damager = ent0; - TCastToPtr damagee = ent1; - bool isPlayer = TCastToPtr(ent1); + const TCastToPtr damager = ent0; + const TCastToPtr damagee = ent1; + const bool isPlayer = TCastToPtr(ent1); if (damagee) { if (CHealthInfo* hInfo = damagee->HealthInfo(*this)) { zeus::CVector3f position; zeus::CVector3f direction = zeus::skRight; - bool alive = hInfo->GetHP() > 0.f; + const bool alive = hInfo->GetHP() > 0.f; if (damager) { position = damager->GetTranslation(); direction = damager->GetTransform().basis[1]; } const CDamageVulnerability* dVuln; - if (damager || isPlayer) + if (damager || isPlayer) { dVuln = damagee->GetDamageVulnerability(position, direction, info); - else + } else { dVuln = damagee->GetDamageVulnerability(); + } if (info.GetWeaponMode().GetType() == EWeaponType::None || dVuln->WeaponHurts(info.GetWeaponMode(), false)) { - if (info.GetDamage() > 0.f) + if (info.GetDamage() > 0.f) { ApplyLocalDamage(position, direction, *damagee, info.GetDamage(), info.GetWeaponMode()); + } damagee->SendScriptMsgs(EScriptObjectState::Damage, *this, EScriptObjectMessage::None); SendScriptMsg(damagee.GetPtr(), damagerId, EScriptObjectMessage::Damage); } else { @@ -1820,18 +1972,21 @@ bool CStateManager::ApplyDamage(TUniqueId damagerId, TUniqueId damageeId, TUniqu } if (alive && damager && info.GetKnockBackPower() > 0.f) { - zeus::CVector3f delta = + const zeus::CVector3f delta = knockbackVec.isZero() ? (damagee->GetTranslation() - damager->GetTranslation()) : knockbackVec; ApplyKnockBack(*damagee, info, *dVuln, delta.normalized(), 0.f); } } - if (damager && info.GetRadius() > 0.f) + if (damager && info.GetRadius() > 0.f) { ProcessRadiusDamage(*damager, *damagee, radiusSender, info, filter); + } - if (TCastToPtr swarm = ent1) - if (damager) + if (const TCastToPtr swarm = ent1) { + if (damager) { swarm->ApplyRadiusDamage(damager->GetTranslation(), info, *this); + } + } } return false; @@ -1840,11 +1995,13 @@ bool CStateManager::ApplyDamage(TUniqueId damagerId, TUniqueId damageeId, TUniqu void CStateManager::UpdateAreaSounds() { rstl::reserved_vector areas; for (CGameArea& area : *x850_world) { - CGameArea::EOcclusionState occState = CGameArea::EOcclusionState::Occluded; - if (area.IsPostConstructed()) + auto occState = CGameArea::EOcclusionState::Occluded; + if (area.IsPostConstructed()) { occState = area.GetOcclusionState(); - if (occState == CGameArea::EOcclusionState::Visible) + } + if (occState == CGameArea::EOcclusionState::Visible) { areas.push_back(area.GetAreaId()); + } } CSfxManager::SetActiveAreas(areas); } @@ -1852,25 +2009,30 @@ void CStateManager::UpdateAreaSounds() { void CStateManager::FrameEnd() { g_SimplePool->Flush(); } void CStateManager::ProcessPlayerInput() { - if (x84c_player) + if (x84c_player) { x84c_player->ProcessInput(xb54_finalInput, *this); + } } void CStateManager::SetGameState(EGameState state) { - if (x904_gameState == state) + if (x904_gameState == state) { return; + } - if (x904_gameState == EGameState::SoftPaused) + if (x904_gameState == EGameState::SoftPaused) { x850_world->SetLoadPauseState(false); + } switch (state) { case EGameState::Running: - if (x88c_rumbleManager->IsDisabled()) + if (x88c_rumbleManager->IsDisabled()) { x88c_rumbleManager->SetDisabled(false); + } break; case EGameState::SoftPaused: - if (!x88c_rumbleManager->IsDisabled()) + if (!x88c_rumbleManager->IsDisabled()) { x88c_rumbleManager->SetDisabled(true); + } x850_world->SetLoadPauseState(true); break; default: @@ -1884,10 +2046,11 @@ static const CFinalInput s_DisabledFinalInput = {}; void CStateManager::ProcessInput(const CFinalInput& input) { if (input.ControllerIdx() == 0) { - CGameCamera* cam = x870_cameraManager->GetCurrentCamera(*this); + const CGameCamera* cam = x870_cameraManager->GetCurrentCamera(*this); bool disableInput = cam->x170_25_disablesInput; - if (x84c_player->x9c6_29_disableInput) + if (x84c_player->x9c6_29_disableInput) { disableInput = true; + } if (disableInput) { xb54_finalInput = s_DisabledFinalInput; xb54_finalInput.x0_dt = input.DeltaTime(); @@ -1900,8 +2063,9 @@ void CStateManager::ProcessInput(const CFinalInput& input) { void CStateManager::UpdateGraphicsTiming(float dt) { xf14_curTimeMod900 += dt; - if (xf14_curTimeMod900 > 900.f) + if (xf14_curTimeMod900 > 900.f) { xf14_curTimeMod900 -= 900.f; + } } void CStateManager::Update(float dt) { @@ -1918,7 +2082,7 @@ void CStateManager::Update(float dt) { UpdateThermalVisor(); UpdateGameState(); - bool dying = x84c_player->x9f4_deathTime > 0.f; + const bool dying = x84c_player->x9f4_deathTime > 0.f; if (x904_gameState == EGameState::Running) { if (!TCastToPtr(x870_cameraManager->GetCurrentCamera(*this))) { @@ -1938,31 +2102,37 @@ void CStateManager::Update(float dt) { } if (x904_gameState == EGameState::Running) { - if (!dying) + if (!dying) { CDecalManager::Update(dt, *this); + } UpdateSortedLists(); if (!dying) { MovePlatforms(dt); MoveActors(dt); } ProcessPlayerInput(); - if (x904_gameState != EGameState::SoftPaused) + if (x904_gameState != EGameState::SoftPaused) { CGameCollision::Move(*this, *x84c_player, dt, nullptr); + } UpdateSortedLists(); - if (!dying) + if (!dying) { CrossTouchActors(); + } } else { ProcessPlayerInput(); } - if (!dying && x904_gameState == EGameState::Running) + if (!dying && x904_gameState == EGameState::Running) { x884_actorModelParticles->Update(dt, *this); + } - if (x904_gameState == EGameState::Running || x904_gameState == EGameState::SoftPaused) + if (x904_gameState == EGameState::Running || x904_gameState == EGameState::SoftPaused) { Think(dt); + } - if (x904_gameState != EGameState::SoftPaused) + if (x904_gameState != EGameState::SoftPaused) { x870_cameraManager->Update(dt, *this); + } while (xf76_lastRelay != kInvalidUniqueId) { if (CEntity* ent = ObjectById(xf76_lastRelay)) { @@ -1973,8 +2143,9 @@ void CStateManager::Update(float dt) { } } - if (x904_gameState != EGameState::Paused) + if (x904_gameState != EGameState::Paused) { PostUpdatePlayer(dt); + } if (xf84_ == xf80_hudMessageFrameCount) { ShowPausedHUDMemo(xf88_, xf8c_); @@ -1982,14 +2153,16 @@ void CStateManager::Update(float dt) { xf88_.Reset(); } - if (!dying && x904_gameState == EGameState::Running && !x870_cameraManager->IsInCinematicCamera()) + if (!dying && x904_gameState == EGameState::Running && !x870_cameraManager->IsInCinematicCamera()) { UpdateEscapeSequenceTimer(dt); + } x850_world->Update(dt); x88c_rumbleManager->Update(dt); - if (!dying) + if (!dying) { x880_envFxManager->Update(dt, *this); + } UpdateAreaSounds(); @@ -1997,8 +2170,9 @@ void CStateManager::Update(float dt) { if (xf94_27_inMapScreen) { if (const CHintOptions::SHintState* hint = g_GameState->HintOptions().GetCurrentDisplayedHint()) { - if (hint->CanContinue()) + if (hint->CanContinue()) { g_GameState->HintOptions().DismissDisplayedHint(); + } } xf94_27_inMapScreen = false; } @@ -2051,46 +2225,57 @@ void CStateManager::PreThinkObjects(float dt) { if (x84c_player->x9f4_deathTime > 0.f) { x84c_player->DoPreThink(dt, *this); } else if (x904_gameState == EGameState::SoftPaused) { - for (CEntity* ent : GetAllObjectList()) - if (TCastToPtr effect = ent) + for (CEntity* ent : GetAllObjectList()) { + if (const TCastToPtr effect = ent) { effect->PreThink(dt, *this); + } + } } else { - for (CEntity* ent : GetAllObjectList()) - if (ent && !GetCameraObjectList().GetObjectById(ent->GetUniqueId())) + for (CEntity* ent : GetAllObjectList()) { + if (ent != nullptr && !GetCameraObjectList().GetObjectById(ent->GetUniqueId())) { ent->PreThink(dt, *this); + } + } } } void CStateManager::MovePlatforms(float dt) { for (CEntity* ent : GetPlatformAndDoorObjectList()) { - if (!ent || !GetPlatformAndDoorObjectList().IsPlatform(*ent)) + if (ent == nullptr || !GetPlatformAndDoorObjectList().IsPlatform(*ent)) { continue; - CScriptPlatform& plat = static_cast(*ent); - if (!plat.GetActive() || plat.GetMass() == 0.f) + } + + auto& plat = static_cast(*ent); + if (!plat.GetActive() || plat.GetMass() == 0.f) { continue; + } + CGameCollision::Move(*this, plat, dt, nullptr); } } void CStateManager::MoveActors(float dt) { for (CEntity* ent : GetPhysicsActorObjectList()) { - if (!ent || !ent->GetActive()) - continue; - CPhysicsActor& physActor = static_cast(*ent); - if (physActor.GetMass() == 0.f) + if (ent == nullptr || !ent->GetActive()) { continue; + } - if (TCastToPtr ai = physActor) { + auto& physActor = static_cast(*ent); + if (physActor.GetMass() == 0.f) { + continue; + } + + if (const TCastToPtr ai = physActor) { bool doThink = !xf94_29_cinematicPause; if (doThink && ai->GetAreaIdAlways() != kInvalidAreaId) { const CGameArea* area = x850_world->GetAreaAlways(ai->GetAreaIdAlways()); - float occTime; - if (area->IsPostConstructed()) + float occTime = 0.0f; + if (area->IsPostConstructed()) { occTime = area->GetPostConstructed()->x10e4_occludedTime; - else - occTime = 0.f; - if (occTime > 5.f) + } + if (occTime > 5.f) { doThink = false; + } } if (!doThink) { SendScriptMsgAlways(ai->GetUniqueId(), kInvalidUniqueId, EScriptObjectMessage::SuspendedMove); @@ -2098,9 +2283,11 @@ void CStateManager::MoveActors(float dt) { } } - if (x84c_player.get() != ent) - if (!GetPlatformAndDoorObjectList().IsPlatform(*ent)) + if (x84c_player.get() != ent) { + if (!GetPlatformAndDoorObjectList().IsPlatform(*ent)) { CGameCollision::Move(*this, physActor, dt, nullptr); + } + } } } @@ -2108,7 +2295,7 @@ void CStateManager::CrossTouchActors() { std::array visits{}; for (CEntity* ent : GetActorObjectList()) { - if (!ent) { + if (ent == nullptr) { continue; } @@ -2117,7 +2304,7 @@ void CStateManager::CrossTouchActors() { continue; } - std::optional touchAABB = actor.GetTouchBounds(); + const std::optional touchAABB = actor.GetTouchBounds(); if (!touchAABB) { continue; } @@ -2130,13 +2317,13 @@ void CStateManager::CrossTouchActors() { rstl::reserved_vector nearList; BuildNearList(nearList, *touchAABB, filter, &actor); - for (TUniqueId id : nearList) { + for (const TUniqueId id : nearList) { auto* ent2 = static_cast(ObjectById(id)); if (!ent2) { continue; } - std::optional touchAABB2 = ent2->GetTouchBounds(); + const std::optional touchAABB2 = ent2->GetTouchBounds(); if (!ent2->GetActive() || !touchAABB2) { continue; } @@ -2162,28 +2349,32 @@ void CStateManager::Think(float dt) { } if (x904_gameState == EGameState::SoftPaused) { - for (CEntity* ent : GetAllObjectList()) - if (TCastToPtr effect = ent) + for (CEntity* ent : GetAllObjectList()) { + if (const TCastToPtr effect = ent) { effect->Think(dt, *this); + } + } } else { for (CEntity* ent : GetAllObjectList()) { - if (TCastToPtr ai = ent) { + if (const TCastToPtr ai = ent) { bool doThink = !xf94_29_cinematicPause; if (doThink && ai->GetAreaIdAlways() != kInvalidAreaId) { const CGameArea* area = x850_world->GetAreaAlways(ai->GetAreaIdAlways()); - float occTime; - if (area->IsPostConstructed()) + float occTime = 0.0f; + if (area->IsPostConstructed()) { occTime = area->GetPostConstructed()->x10e4_occludedTime; - else - occTime = 0.f; - if (occTime > 5.f) + } + if (occTime > 5.f) { doThink = false; + } } - if (!doThink) + if (!doThink) { continue; + } } - if (!GetCameraObjectList().GetObjectById(ent->GetUniqueId())) + if (!GetCameraObjectList().GetObjectById(ent->GetUniqueId())) { ent->Think(dt, *this); + } } } } @@ -2197,7 +2388,7 @@ void CStateManager::ShowPausedHUDMemo(CAssetId strg, float time) { } void CStateManager::ClearGraveyard() { - for (TUniqueId id : x854_objectGraveyard) { + for (const TUniqueId id : x854_objectGraveyard) { CEntity* ent = GetAllObjectList().GetValidObjectById(id); RemoveObject(id); std::default_delete()(ent); @@ -2208,7 +2399,7 @@ void CStateManager::ClearGraveyard() { void CStateManager::FrameBegin(s32 frameCount) { x8d4_inputFrameIdx = frameCount; } void CStateManager::InitializeState(CAssetId mlvlId, TAreaId aid, CAssetId mreaId) { - bool hadRandom = x900_activeRandom != nullptr; + const bool hadRandom = x900_activeRandom != nullptr; SetActiveRandomToDefault(); if (xb3c_initPhase == EInitPhase::LoadWorld) { @@ -2218,12 +2409,14 @@ void CStateManager::InitializeState(CAssetId mlvlId, TAreaId aid, CAssetId mreaI } if (xb3c_initPhase == EInitPhase::LoadFirstArea) { - if (!x8f0_shadowTex.IsLoaded()) + if (!x8f0_shadowTex.IsLoaded()) { return; + } x8f0_shadowTex.GetObj(); - if (!x850_world->CheckWorldComplete(this, aid, mreaId)) + if (!x850_world->CheckWorldComplete(this, aid, mreaId)) { return; + } x8cc_nextAreaId = x850_world->x68_curAreaId; CGameArea* area = x850_world->x18_areas[x8cc_nextAreaId].get(); if (x850_world->ScheduleAreaToLoad(area, *this)) { @@ -2238,35 +2431,39 @@ void CStateManager::InitializeState(CAssetId mlvlId, TAreaId aid, CAssetId mreaI x850_world->TravelToArea(x8cc_nextAreaId, *this, true); UpdateRoomAcoustics(x8cc_nextAreaId); - for (CEntity* ent : GetAllObjectList()) + for (CEntity* ent : GetAllObjectList()) { SendScriptMsg(ent, kInvalidUniqueId, EScriptObjectMessage::WorldInitialized); + } for (CEntity* ent : GetAllObjectList()) { CScriptSpawnPoint* sp = TCastToPtr(ent); - if (sp && sp->x30_24_active && sp->FirstSpawn()) { + if (sp != nullptr && sp->x30_24_active && sp->FirstSpawn()) { const zeus::CTransform& xf = sp->GetTransform(); - zeus::CVector3f lookVec = xf.frontVector(); + const zeus::CVector3f lookVec = xf.frontVector(); if (lookVec.canBeNormalized()) { - auto lookXf = zeus::lookAt(xf.origin, xf.origin + lookVec); + const auto lookXf = zeus::lookAt(xf.origin, xf.origin + lookVec); x84c_player->Teleport(lookXf, *this, true); } - if (!g_GameState->x228_25_initPowerupsAtFirstSpawn) + if (!g_GameState->x228_25_initPowerupsAtFirstSpawn) { break; + } g_GameState->x228_25_initPowerupsAtFirstSpawn = false; for (int i = 0; i < int(CPlayerState::EItemType::Max); ++i) { - CPlayerState::EItemType iType = CPlayerState::EItemType(i); + const auto iType = CPlayerState::EItemType(i); u32 spawnPu = sp->GetPowerup(iType); u32 statePu = x8b8_playerState->GetItemAmount(iType); - if (statePu < spawnPu) + if (statePu < spawnPu) { x8b8_playerState->AddPowerUp(iType, spawnPu - statePu); + } spawnPu = sp->GetPowerup(iType); statePu = x8b8_playerState->GetItemAmount(iType); - if (statePu < spawnPu) + if (statePu < spawnPu) { x8b8_playerState->IncrPickup(iType, spawnPu - statePu); + } } } } @@ -2274,10 +2471,11 @@ void CStateManager::InitializeState(CAssetId mlvlId, TAreaId aid, CAssetId mreaI x84c_player->AsyncLoadSuit(*this); x870_cameraManager->ResetCameras(*this); - if (!hadRandom) + if (!hadRandom) { ClearActiveRandom(); - else + } else { SetActiveRandomToDefault(); + } x880_envFxManager->AsyncLoadResources(*this); } @@ -2300,21 +2498,23 @@ void CStateManager::CreateStandardGameObjects() { } CObjectList* CStateManager::ObjectListById(EGameObjectList type) { - if (type == EGameObjectList::Invalid) + if (type == EGameObjectList::Invalid) { return nullptr; + } return x808_objLists[int(type)].get(); } const CObjectList* CStateManager::GetObjectListById(EGameObjectList type) const { - if (type == EGameObjectList::Invalid) + if (type == EGameObjectList::Invalid) { return nullptr; + } return x808_objLists[int(type)].get(); } void CStateManager::RemoveObject(TUniqueId uid) { if (CEntity* ent = GetAllObjectList().GetValidObjectById(uid)) { if (ent->GetEditorId() != kInvalidEditorId) { - auto search = x890_scriptIdMap.equal_range(ent->GetEditorId()); + const auto search = x890_scriptIdMap.equal_range(ent->GetEditorId()); for (auto it = search.first; it != search.second;) { if (it->second == uid) { it = x890_scriptIdMap.erase(it); @@ -2325,21 +2525,24 @@ void CStateManager::RemoveObject(TUniqueId uid) { } if (ent->GetAreaIdAlways() != kInvalidAreaId) { CGameArea* area = x850_world->GetArea(ent->GetAreaIdAlways()); - if (area->IsPostConstructed()) + if (area->IsPostConstructed()) { area->GetAreaObjects()->RemoveObject(uid); + } } - if (TCastToPtr act = ent) + if (const TCastToPtr act = ent) { x874_sortedListManager->Remove(act.GetPtr()); + } } - for (auto& list : x808_objLists) + for (auto& list : x808_objLists) { list->RemoveObject(uid); + } } void CStateManager::UpdateRoomAcoustics(TAreaId aid) { u32 updateCount = 0; std::array updates; for (CEntity* ent : GetAllObjectList()) { - if (TCastToPtr acoustics = ent) { + if (const TCastToPtr acoustics = ent) { if (acoustics->GetAreaIdAlways() != aid || !acoustics->GetActive()) { continue; } @@ -2366,10 +2569,12 @@ void CStateManager::SetCurrentAreaId(TAreaId aid) { x8cc_nextAreaId = aid; } - if (aid == kInvalidAreaId) + if (aid == kInvalidAreaId) { return; - if (x8c0_mapWorldInfo->IsAreaVisited(aid)) + } + if (x8c0_mapWorldInfo->IsAreaVisited(aid)) { return; + } x8c0_mapWorldInfo->SetAreaVisited(aid, true); x850_world->IGetMapWorld()->RecalculateWorldSphere(*x8c0_mapWorldInfo, *x850_world); } @@ -2380,9 +2585,11 @@ void CStateManager::AreaUnloaded(TAreaId) { void CStateManager::PrepareAreaUnload(TAreaId aid) { for (CEntity* ent : GetAllObjectList()) { - if (TCastToPtr door = ent) - if (door->IsConnectedToArea(*this, aid)) + if (const TCastToPtr door = ent) { + if (door->IsConnectedToArea(*this, aid)) { door->ForceClosed(*this); + } + } } FreeScriptObjects(aid); } @@ -2409,11 +2616,12 @@ void CStateManager::BuildNearList(rstl::reserved_vector& listOu } void CStateManager::UpdateActorInSortedLists(CActor& act) { - if (!act.GetUseInSortedLists() || !act.xe4_27_notInSortedLists) + if (!act.GetUseInSortedLists() || !act.xe4_27_notInSortedLists) { return; + } - std::optional aabb = CalculateObjectBounds(act); - bool actorInLists = x874_sortedListManager->ActorInLists(&act); + const std::optional aabb = CalculateObjectBounds(act); + const bool actorInLists = x874_sortedListManager->ActorInLists(&act); if (actorInLists || aabb) { act.xe4_27_notInSortedLists = false; if (actorInLists) { @@ -2429,10 +2637,13 @@ void CStateManager::UpdateActorInSortedLists(CActor& act) { } void CStateManager::UpdateSortedLists() { - if (!x850_world) + if (!x850_world) { return; - for (CEntity* actor : GetActorObjectList()) + } + + for (CEntity* actor : GetActorObjectList()) { UpdateActorInSortedLists(static_cast(*actor)); + } } std::optional CStateManager::CalculateObjectBounds(const CActor& actor) { @@ -2442,50 +2653,61 @@ std::optional CStateManager::CalculateObjectBounds(const CActor& a aabb.accumulateBounds(bounds->min); aabb.accumulateBounds(bounds->max); if (TCastToConstPtr physAct = actor) { - zeus::CAABox physAabb = physAct->GetBoundingBox(); + const zeus::CAABox physAabb = physAct->GetBoundingBox(); aabb.accumulateBounds(physAabb.min); aabb.accumulateBounds(physAabb.max); } - return {aabb}; + return aabb; } else { - if (TCastToConstPtr physAct = actor) - return {physAct->GetBoundingBox()}; + if (const TCastToConstPtr physAct = actor) { + return physAct->GetBoundingBox(); + } } - return {}; + return std::nullopt; } void CStateManager::AddObject(CEntity& ent) { - if (ent.GetEditorId() != kInvalidEditorId) + if (ent.GetEditorId() != kInvalidEditorId) { x890_scriptIdMap.insert(std::make_pair(ent.GetEditorId(), ent.GetUniqueId())); - for (auto& list : x808_objLists) + } + for (auto& list : x808_objLists) { list->AddObject(ent); - - if (ent.GetAreaIdAlways() == kInvalidAreaId && x84c_player && ent.GetUniqueId() != x84c_player->GetUniqueId()) - ent.x4_areaId = x84c_player->GetAreaIdAlways(); - if (ent.GetAreaIdAlways() != kInvalidAreaId) { - CGameArea* area = x850_world->GetArea(ent.GetAreaIdAlways()); - if (area->IsPostConstructed()) - area->GetAreaObjects()->AddObject(ent); } - if (TCastToPtr act = ent) + if (ent.GetAreaIdAlways() == kInvalidAreaId && x84c_player && ent.GetUniqueId() != x84c_player->GetUniqueId()) { + ent.x4_areaId = x84c_player->GetAreaIdAlways(); + } + if (ent.GetAreaIdAlways() != kInvalidAreaId) { + CGameArea* area = x850_world->GetArea(ent.GetAreaIdAlways()); + if (area->IsPostConstructed()) { + area->GetAreaObjects()->AddObject(ent); + } + } + + if (const TCastToPtr act = ent) { UpdateActorInSortedLists(*act.GetPtr()); + } ent.AcceptScriptMsg(EScriptObjectMessage::Registered, kInvalidUniqueId, *this); if (ent.GetAreaIdAlways() != kInvalidAreaId && x850_world) { CGameArea* area = x850_world->GetArea(ent.GetAreaIdAlways()); - if (area->IsValidated()) + if (area->IsValidated()) { SendScriptMsg(&ent, kInvalidUniqueId, EScriptObjectMessage::InitializedInArea); + } } - if (sm_logScripting && sm_logScripting->toBoolean()) + if (sm_logScripting != nullptr && sm_logScripting->toBoolean()) { LogModule.report(logvisor::Info, FMT_STRING("Added '{}'"), ent.GetName()); + } } void CStateManager::AddObject(CEntity* ent) { - if (ent) - AddObject(*ent); + if (!ent) { + return; + } + + AddObject(*ent); } CRayCastResult CStateManager::RayStaticIntersection(const zeus::CVector3f& pos, const zeus::CVector3f& dir, @@ -2502,19 +2724,23 @@ CRayCastResult CStateManager::RayWorldIntersection(TUniqueId& idOut, const zeus: zeus::CVector3f CStateManager::Random2f(float scaleMin, float scaleMax) { zeus::CVector3f ret(x900_activeRandom->Float() - 0.5f, x900_activeRandom->Float() - 0.5f, 0.f); - if (std::fabs(ret.x()) < 0.001f) + if (std::fabs(ret.x()) < 0.001f) { ret.x() = 0.001f; + } ret.normalize(); return ret * ((scaleMax - scaleMin) * x900_activeRandom->Float() + scaleMin); } void CStateManager::UpdateObjectInLists(CEntity& ent) { for (auto& list : x808_objLists) { - if (list->GetValidObjectById(ent.GetUniqueId())) - if (!list->IsQualified(ent)) + if (list->GetValidObjectById(ent.GetUniqueId())) { + if (!list->IsQualified(ent)) { list->RemoveObject(ent.GetUniqueId()); - if (!list->GetValidObjectById(ent.GetUniqueId())) + } + } + if (!list->GetValidObjectById(ent.GetUniqueId())) { list->AddObject(ent); + } } } @@ -2524,13 +2750,15 @@ TUniqueId CStateManager::AllocateUniqueId() { do { ourIndex = x0_nextFreeIndex; x0_nextFreeIndex = (x0_nextFreeIndex + 1) & 0x3ff; - if (x0_nextFreeIndex == lastIndex) + if (x0_nextFreeIndex == lastIndex) { LogModule.report(logvisor::Fatal, FMT_STRING("Object List Full!")); + } } while (GetAllObjectList().GetObjectByIndex(ourIndex) != nullptr); x8_idArr[ourIndex] = (x8_idArr[ourIndex] + 1) & 0x3f; - if (TUniqueId(ourIndex, x8_idArr[ourIndex]) == kInvalidUniqueId) + if (TUniqueId(ourIndex, x8_idArr[ourIndex]) == kInvalidUniqueId) { x8_idArr[ourIndex] = 0; + } return TUniqueId(ourIndex, x8_idArr[ourIndex]); } @@ -2551,8 +2779,9 @@ void CStateManager::DeferStateTransition(EStateManagerTransition t) { bool CStateManager::CanShowMapScreen() const { const CHintOptions::SHintState* curDispHint = g_GameState->HintOptions().GetCurrentDisplayedHint(); - if (!curDispHint || curDispHint->CanContinue()) + if (curDispHint == nullptr || curDispHint->CanContinue()) { return true; + } return false; } @@ -2561,11 +2790,12 @@ std::pair CStateManager::CalculateScanCompletionRate() const { u32 denom = 0; int idx = 0; for (const std::pair& scan : x8b8_playerState->GetScanTimes()) { - CSaveWorld::EScanCategory category = g_MemoryCardSys->GetScanStates()[idx++].second; + const auto category = g_MemoryCardSys->GetScanStates()[idx++].second; if (category != CSaveWorld::EScanCategory::None && category != CSaveWorld::EScanCategory::Research) { ++denom; - if (scan.second == 1.f) + if (scan.second == 1.f) { ++num; + } } } return {num, denom}; @@ -2578,8 +2808,9 @@ void CStateManager::SetBossParams(TUniqueId bossId, float maxEnergy, u32 stringI } float CStateManager::IntegrateVisorFog(float f) const { - if (x8b8_playerState->GetActiveVisor(*this) == CPlayerState::EPlayerVisor::Scan) + if (x8b8_playerState->GetActiveVisor(*this) == CPlayerState::EPlayerVisor::Scan) { return (1.f - x8b8_playerState->GetVisorTransitionFactor()) * f; + } return f; } diff --git a/Runtime/Character/CAnimSourceReader.cpp b/Runtime/Character/CAnimSourceReader.cpp index 88c72f7eb..c4effdb7c 100644 --- a/Runtime/Character/CAnimSourceReader.cpp +++ b/Runtime/Character/CAnimSourceReader.cpp @@ -106,24 +106,27 @@ void CAnimSourceReaderBase::UpdatePOIStates() { const std::vector& soundNodes = x4_sourceInfo->GetSoundPOIStream(); while (x14_passedBoolCount < boolNodes.size() && boolNodes[x14_passedBoolCount].GetTime() <= xc_curTime) { - auto& node = boolNodes[x14_passedBoolCount]; - if (node.GetIndex() >= 0) + const auto& node = boolNodes[x14_passedBoolCount]; + if (node.GetIndex() >= 0) { x24_boolStates[node.GetIndex()].second = node.GetValue(); + } ++x14_passedBoolCount; } while (x18_passedIntCount < int32Nodes.size() && int32Nodes[x18_passedIntCount].GetTime() <= xc_curTime) { - auto& node = int32Nodes[x18_passedIntCount]; - if (node.GetIndex() >= 0) + const auto& node = int32Nodes[x18_passedIntCount]; + if (node.GetIndex() >= 0) { x34_int32States[node.GetIndex()].second = node.GetValue(); + } ++x18_passedIntCount; } while (x1c_passedParticleCount < particleNodes.size() && particleNodes[x1c_passedParticleCount].GetTime() <= xc_curTime) { - auto& node = particleNodes[x1c_passedParticleCount]; - if (node.GetIndex() >= 0) + const auto& node = particleNodes[x1c_passedParticleCount]; + if (node.GetIndex() >= 0) { x44_particleStates[node.GetIndex()].second = node.GetParticleData().GetParentedMode(); + } ++x1c_passedParticleCount; } diff --git a/Runtime/Character/CAnimTreeTweenBase.cpp b/Runtime/Character/CAnimTreeTweenBase.cpp index ef1fb01c4..8452c06d2 100644 --- a/Runtime/Character/CAnimTreeTweenBase.cpp +++ b/Runtime/Character/CAnimTreeTweenBase.cpp @@ -25,10 +25,11 @@ void CAnimTreeTweenBase::VGetSegStatementSet(const CSegIdList& list, CSegStateme if (w >= 1.f) { x18_b->VGetSegStatementSet(list, setOut); } else if (sStack > 3) { - auto& n = w > 0.5f ? x18_b : x14_a; + const auto& n = w > 0.5f ? x18_b : x14_a; auto ptr = n->GetBestUnblendedChild(); - if (!ptr) + if (!ptr) { ptr = n; + } ptr->VGetSegStatementSet(list, setOut); } else { CSegStatementSet setA, setB; @@ -61,7 +62,7 @@ void CAnimTreeTweenBase::VGetSegStatementSet(const CSegIdList& list, CSegStateme if (w >= 1.f) { x18_b->VGetSegStatementSet(list, setOut, time); } else if (sStack > 3) { - auto& n = w > 0.5f ? x18_b : x14_a; + const auto& n = w > 0.5f ? x18_b : x14_a; n->GetBestUnblendedChild()->VGetSegStatementSet(list, setOut, time); } else { CSegStatementSet setA, setB; diff --git a/Runtime/Character/CMetaAnimRandom.cpp b/Runtime/Character/CMetaAnimRandom.cpp index 8c88127e5..48c978667 100644 --- a/Runtime/Character/CMetaAnimRandom.cpp +++ b/Runtime/Character/CMetaAnimRandom.cpp @@ -27,12 +27,13 @@ void CMetaAnimRandom::GetUniquePrimitives(std::set& primsOut) const std::shared_ptr CMetaAnimRandom::VGetAnimationTree(const CAnimSysContext& animSys, const CMetaAnimTreeBuildOrders& orders) const { - u32 r = animSys.x8_random->Range(1, 100); + const u32 r = animSys.x8_random->Range(1, 100); const std::pair, u32>* useRd = nullptr; - for (auto& rd : x4_randomData) { + for (const auto& rd : x4_randomData) { useRd = &rd; - if (r <= rd.second) + if (r <= rd.second) { break; + } } return useRd->first->GetAnimationTree(animSys, orders); diff --git a/Runtime/Character/CParticleDatabase.cpp b/Runtime/Character/CParticleDatabase.cpp index 6ac19bfa9..ee206a320 100644 --- a/Runtime/Character/CParticleDatabase.cpp +++ b/Runtime/Character/CParticleDatabase.cpp @@ -205,36 +205,39 @@ void CParticleDatabase::Update(float dt, const CPoseAsTransforms& pose, const CC } void CParticleDatabase::RenderParticleGenMap(const std::map>& map) { - for (auto& e : map) { + for (const auto& e : map) { e.second->Render(); } } void CParticleDatabase::RenderParticleGenMapMasked(const std::map>& map, int mask, int target) { - for (auto& e : map) { - if ((e.second->GetFlags() & mask) == target) + for (const auto& e : map) { + if ((e.second->GetFlags() & mask) == target) { e.second->Render(); + } } } void CParticleDatabase::AddToRendererClippedParticleGenMap( const std::map>& map, const zeus::CFrustum& frustum) { - for (auto& e : map) { - auto bounds = e.second->GetBounds(); - if (bounds && frustum.aabbFrustumTest(*bounds)) + for (const auto& e : map) { + const auto bounds = e.second->GetBounds(); + if (bounds && frustum.aabbFrustumTest(*bounds)) { e.second->AddToRenderer(); + } } } void CParticleDatabase::AddToRendererClippedParticleGenMapMasked( const std::map>& map, const zeus::CFrustum& frustum, int mask, int target) { - for (auto& e : map) { + for (const auto& e : map) { if ((e.second->GetFlags() & mask) == target) { - auto bounds = e.second->GetBounds(); - if (bounds && frustum.aabbFrustumTest(*bounds)) + const auto bounds = e.second->GetBounds(); + if (bounds && frustum.aabbFrustumTest(*bounds)) { e.second->AddToRenderer(); + } } } } diff --git a/Runtime/Graphics/CModelBoo.cpp b/Runtime/Graphics/CModelBoo.cpp index 122e6ecde..5e1f4defe 100644 --- a/Runtime/Graphics/CModelBoo.cpp +++ b/Runtime/Graphics/CModelBoo.cpp @@ -340,12 +340,13 @@ CBooModel::ModelInstance* CBooModel::PushNewModelInstance(int sharedLayoutBuf) { }; if (!g_DummyTextures) { for (const auto& ch : mat.chunks) { - if (auto pass = ch.get_if()) { + if (const auto* const pass = ch.get_if()) { auto search = x1c_textures.find(pass->texId.toUint32()); boo::ObjToken btex; - if (search != x1c_textures.cend() && (btex = search->second.GetObj()->GetBooTexture())) + if (search != x1c_textures.cend() && (btex = search->second.GetObj()->GetBooTexture())) { texs[MaterialSet::Material::TexMapIdx(pass->type)] = btex; - } else if (auto pass = ch.get_if()) { + } + } else if (const auto* const pass = ch.get_if()) { boo::ObjToken btex = g_Renderer->GetColorTexture(zeus::CColor(pass->color)); texs[MaterialSet::Material::TexMapIdx(pass->type)] = btex; } @@ -424,7 +425,7 @@ void CBooModel::MakeTexturesFromMats(const MaterialSet& matSet, IObjectStore& store) { for (const auto& mat : matSet.materials) { for (const auto& chunk : mat.chunks) { - if (auto pass = chunk.get_if()) { + if (const auto* const pass = chunk.get_if()) { toksOut.emplace(std::make_pair(pass->texId.toUint32(), store.GetObj({SBIG('TXTR'), pass->texId.toUint32()}))); } } @@ -485,8 +486,8 @@ bool CBooModel::TryLockTextures() { } if (allLoad) { - for (auto& pipeline : *m_pipelines) { - for (auto& subpipeline : *pipeline.second) { + for (const auto& pipeline : *m_pipelines) { + for (const auto& subpipeline : *pipeline.second) { if (!subpipeline->isReady()) { allLoad = false; break; @@ -682,7 +683,7 @@ void CBooModel::WarmupDrawSurface(const CBooSurface& surf) const { return; const ModelInstance& inst = m_instances[m_uniUpdateCount - 1]; - for (auto& binding : inst.m_shaderDataBindings[surf.selfIdx]) { + for (const auto& binding : inst.m_shaderDataBindings[surf.selfIdx]) { CGraphics::SetShaderDataBinding(binding); CGraphics::DrawArrayIndexed(surf.m_data.idxStart, std::min(u32(3), surf.m_data.idxCount)); } @@ -865,7 +866,7 @@ void CBooModel::UVAnimationBuffer::Update(u8*& bufOut, const MaterialSet* matSet } u8* bufOrig = bufOut; for (const auto& chunk : mat.chunks) { - if (auto pass = chunk.get_if()) { + if (const auto* const pass = chunk.get_if()) { ProcessAnimation(bufOut, *pass); } } @@ -1289,14 +1290,14 @@ bool CModel::IsLoaded(int shaderIdx) const { size_t CModel::GetPoolVertexOffset(size_t idx) const { return m_hmdlMeta.vertStride * idx; } zeus::CVector3f CModel::GetPoolVertex(size_t idx) const { - auto* floats = reinterpret_cast(m_dynamicVertexData.get() + GetPoolVertexOffset(idx)); + const auto* floats = reinterpret_cast(m_dynamicVertexData.get() + GetPoolVertexOffset(idx)); return {floats}; } size_t CModel::GetPoolNormalOffset(size_t idx) const { return m_hmdlMeta.vertStride * idx + 12; } zeus::CVector3f CModel::GetPoolNormal(size_t idx) const { - auto* floats = reinterpret_cast(m_dynamicVertexData.get() + GetPoolNormalOffset(idx)); + const auto* floats = reinterpret_cast(m_dynamicVertexData.get() + GetPoolNormalOffset(idx)); return {floats}; } diff --git a/Runtime/Graphics/CRainSplashGenerator.cpp b/Runtime/Graphics/CRainSplashGenerator.cpp index 50338e6d5..22340971e 100644 --- a/Runtime/Graphics/CRainSplashGenerator.cpp +++ b/Runtime/Graphics/CRainSplashGenerator.cpp @@ -151,13 +151,13 @@ void CRainSplashGenerator::Update(float dt, CStateManager& mgr) { u32 CRainSplashGenerator::GetNextBestPt(u32 pt, const std::vector>& vn, CRandom16& rand, float minZ) { - auto& refVert = vn[pt]; + const auto& refVert = vn[pt]; float maxDist = 0.f; u32 nextPt = pt; for (int i = 0; i < 3; ++i) { - auto idx = u32(rand.Range(0, int(vn.size() - 1))); - auto& vert = vn[idx]; - float distSq = (refVert.first - vert.first).magSquared(); + const auto idx = u32(rand.Range(0, int(vn.size() - 1))); + const auto& vert = vn[idx]; + const float distSq = (refVert.first - vert.first).magSquared(); if (distSq > maxDist && vert.second.dot(zeus::skUp) >= 0.f && (vert.first.z() <= 0.f || vert.first.z() > minZ)) { nextPt = idx; diff --git a/Runtime/Graphics/CTextureBoo.cpp b/Runtime/Graphics/CTextureBoo.cpp index d271c0cad..5c298eb4c 100644 --- a/Runtime/Graphics/CTextureBoo.cpp +++ b/Runtime/Graphics/CTextureBoo.cpp @@ -1,5 +1,7 @@ #include "Runtime/Graphics/CTexture.hpp" +#include + #include "Runtime/CSimplePool.hpp" #include "Runtime/CToken.hpp" #include "Runtime/Graphics/CGraphics.hpp" @@ -7,28 +9,43 @@ #include "Runtime/GameGlobalObjects.hpp" namespace urde { -static logvisor::Module Log("urde::CTextureBoo"); +namespace { +logvisor::Module Log("urde::CTextureBoo"); + +struct RGBA8 { + u8 r; + u8 g; + u8 b; + u8 a; +}; + +struct DXT1Block { + u16 color1; + u16 color2; + std::array lines; +}; /* GX uses this upsampling technique to extract full 8-bit range */ -constexpr uint8_t Convert3To8(uint8_t v) { +constexpr u8 Convert3To8(u8 v) { /* Swizzle bits: 00000123 -> 12312312 */ - return (v << 5) | (v << 2) | (v >> 1); + return static_cast((u32{v} << 5) | (u32{v} << 2) | (u32{v} >> 1)); } -constexpr uint8_t Convert4To8(uint8_t v) { +constexpr u8 Convert4To8(u8 v) { /* Swizzle bits: 00001234 -> 12341234 */ - return (v << 4) | v; + return static_cast((u32{v} << 4) | u32{v}); } -constexpr uint8_t Convert5To8(uint8_t v) { +constexpr u8 Convert5To8(u8 v) { /* Swizzle bits: 00012345 -> 12345123 */ - return (v << 3) | (v >> 2); + return static_cast((u32{v} << 3) | (u32{v} >> 2)); } -constexpr uint8_t Convert6To8(uint8_t v) { +constexpr u8 Convert6To8(u8 v) { /* Swizzle bits: 00123456 -> 12345612 */ - return (v << 2) | (v >> 4); + return static_cast((u32{v} << 2) | (u32{v} >> 4)); } +} // Anonymous namespace size_t CTexture::ComputeMippedTexelCount() const { size_t w = x4_w; @@ -58,32 +75,25 @@ size_t CTexture::ComputeMippedBlockCountDXT1() const { return ret; } -struct RGBA8 { - u8 r; - u8 g; - u8 b; - u8 a; -}; - void CTexture::BuildI4FromGCN(CInputStream& in) { - size_t texelCount = ComputeMippedTexelCount(); + const size_t texelCount = ComputeMippedTexelCount(); std::unique_ptr buf(new RGBA8[texelCount]); int w = x4_w; int h = x6_h; RGBA8* targetMip = buf.get(); for (u32 mip = 0; mip < x8_mips; ++mip) { - int bwidth = (w + 7) / 8; - int bheight = (h + 7) / 8; + const int bwidth = (w + 7) / 8; + const int bheight = (h + 7) / 8; for (int by = 0; by < bheight; ++by) { - int baseY = by * 8; + const int baseY = by * 8; for (int bx = 0; bx < bwidth; ++bx) { - int baseX = bx * 8; + const int baseX = bx * 8; for (int y = 0; y < 8; ++y) { RGBA8* target = targetMip + (baseY + y) * w + baseX; - u8 source[4]; - in.readBytesToBuf(source, 4); - for (int x = 0; x < 8; ++x) { + std::array source; + in.readBytesToBuf(source.data(), source.size()); + for (size_t x = 0; x < 8; ++x) { target[x].r = Convert4To8(source[x / 2] >> ((x & 1) ? 0 : 4) & 0xf); target[x].g = target[x].r; target[x].b = target[x].r; @@ -93,10 +103,12 @@ void CTexture::BuildI4FromGCN(CInputStream& in) { } } targetMip += w * h; - if (w > 1) + if (w > 1) { w /= 2; - if (h > 1) + } + if (h > 1) { h /= 2; + } } CGraphics::CommitResources([&](boo::IGraphicsDataFactory::Context& ctx) { @@ -108,24 +120,24 @@ void CTexture::BuildI4FromGCN(CInputStream& in) { } void CTexture::BuildI8FromGCN(CInputStream& in) { - size_t texelCount = ComputeMippedTexelCount(); + const size_t texelCount = ComputeMippedTexelCount(); std::unique_ptr buf(new RGBA8[texelCount]); int w = x4_w; int h = x6_h; RGBA8* targetMip = buf.get(); for (u32 mip = 0; mip < x8_mips; ++mip) { - int bwidth = (w + 7) / 8; - int bheight = (h + 3) / 4; + const int bwidth = (w + 7) / 8; + const int bheight = (h + 3) / 4; for (int by = 0; by < bheight; ++by) { - int baseY = by * 4; + const int baseY = by * 4; for (int bx = 0; bx < bwidth; ++bx) { - int baseX = bx * 8; + const int baseX = bx * 8; for (int y = 0; y < 4; ++y) { RGBA8* target = targetMip + (baseY + y) * w + baseX; - u8 source[8]; - in.readBytesToBuf(source, 8); - for (int x = 0; x < 8; ++x) { + std::array source; + in.readBytesToBuf(source.data(), source.size()); + for (size_t x = 0; x < source.size(); ++x) { target[x].r = source[x]; target[x].g = source[x]; target[x].b = source[x]; @@ -135,10 +147,12 @@ void CTexture::BuildI8FromGCN(CInputStream& in) { } } targetMip += w * h; - if (w > 1) + if (w > 1) { w /= 2; - if (h > 1) + } + if (h > 1) { h /= 2; + } } CGraphics::CommitResources([&](boo::IGraphicsDataFactory::Context& ctx) { @@ -150,25 +164,25 @@ void CTexture::BuildI8FromGCN(CInputStream& in) { } void CTexture::BuildIA4FromGCN(CInputStream& in) { - size_t texelCount = ComputeMippedTexelCount(); + const size_t texelCount = ComputeMippedTexelCount(); std::unique_ptr buf(new RGBA8[texelCount]); int w = x4_w; int h = x6_h; RGBA8* targetMip = buf.get(); for (u32 mip = 0; mip < x8_mips; ++mip) { - int bwidth = (w + 7) / 8; - int bheight = (h + 3) / 4; + const int bwidth = (w + 7) / 8; + const int bheight = (h + 3) / 4; for (int by = 0; by < bheight; ++by) { - int baseY = by * 4; + const int baseY = by * 4; for (int bx = 0; bx < bwidth; ++bx) { - int baseX = bx * 8; + const int baseX = bx * 8; for (int y = 0; y < 4; ++y) { RGBA8* target = targetMip + (baseY + y) * w + baseX; - u8 source[8]; - in.readBytesToBuf(source, 8); - for (int x = 0; x < 8; ++x) { - u8 intensity = Convert4To8(source[x] >> 4 & 0xf); + std::array source; + in.readBytesToBuf(source.data(), source.size()); + for (size_t x = 0; x < source.size(); ++x) { + const u8 intensity = Convert4To8(source[x] >> 4 & 0xf); target[x].r = intensity; target[x].g = intensity; target[x].b = intensity; @@ -178,10 +192,12 @@ void CTexture::BuildIA4FromGCN(CInputStream& in) { } } targetMip += w * h; - if (w > 1) + if (w > 1) { w /= 2; - if (h > 1) + } + if (h > 1) { h /= 2; + } } CGraphics::CommitResources([&](boo::IGraphicsDataFactory::Context& ctx) { @@ -193,25 +209,25 @@ void CTexture::BuildIA4FromGCN(CInputStream& in) { } void CTexture::BuildIA8FromGCN(CInputStream& in) { - size_t texelCount = ComputeMippedTexelCount(); + const size_t texelCount = ComputeMippedTexelCount(); std::unique_ptr buf(new RGBA8[texelCount]); int w = x4_w; int h = x6_h; RGBA8* targetMip = buf.get(); for (u32 mip = 0; mip < x8_mips; ++mip) { - int bwidth = (w + 3) / 4; - int bheight = (h + 3) / 4; + const int bwidth = (w + 3) / 4; + const int bheight = (h + 3) / 4; for (int by = 0; by < bheight; ++by) { - int baseY = by * 4; + const int baseY = by * 4; for (int bx = 0; bx < bwidth; ++bx) { - int baseX = bx * 4; + const int baseX = bx * 4; for (int y = 0; y < 4; ++y) { RGBA8* target = targetMip + (baseY + y) * w + baseX; - u16 source[4]; - in.readBytesToBuf(source, 8); - for (int x = 0; x < 4; ++x) { - u8 intensity = source[x] >> 8; + std::array source; + in.readBytesToBuf(source.data(), sizeof(source)); + for (size_t x = 0; x < source.size(); ++x) { + const u8 intensity = source[x] >> 8; target[x].r = intensity; target[x].g = intensity; target[x].b = intensity; @@ -221,10 +237,12 @@ void CTexture::BuildIA8FromGCN(CInputStream& in) { } } targetMip += w * h; - if (w > 1) + if (w > 1) { w /= 2; - if (h > 1) + } + if (h > 1) { h /= 2; + } } CGraphics::CommitResources([&](boo::IGraphicsDataFactory::Context& ctx) { @@ -277,7 +295,7 @@ static std::vector DecodePalette(int numEntries, CInputStream& in) { } void CTexture::BuildC4FromGCN(CInputStream& in) { - size_t texelCount = ComputeMippedTexelCount(); + const size_t texelCount = ComputeMippedTexelCount(); std::unique_ptr buf(new RGBA8[texelCount]); std::vector palette = DecodePalette(16, in); @@ -285,26 +303,29 @@ void CTexture::BuildC4FromGCN(CInputStream& in) { int h = x6_h; RGBA8* targetMip = buf.get(); for (u32 mip = 0; mip < x8_mips; ++mip) { - int bwidth = (w + 7) / 8; - int bheight = (h + 7) / 8; + const int bwidth = (w + 7) / 8; + const int bheight = (h + 7) / 8; for (int by = 0; by < bheight; ++by) { - int baseY = by * 8; + const int baseY = by * 8; for (int bx = 0; bx < bwidth; ++bx) { - int baseX = bx * 8; + const int baseX = bx * 8; for (int y = 0; y < 8; ++y) { RGBA8* target = targetMip + (baseY + y) * w + baseX; - u8 source[4]; - in.readBytesToBuf(source, 4); - for (int x = 0; x < 8; ++x) + std::array source; + in.readBytesToBuf(source.data(), source.size()); + for (size_t x = 0; x < 8; ++x) { target[x] = palette[source[x / 2] >> ((x & 1) ? 0 : 4) & 0xf]; + } } } } targetMip += w * h; - if (w > 1) + if (w > 1) { w /= 2; - if (h > 1) + } + if (h > 1) { h /= 2; + } } CGraphics::CommitResources([&](boo::IGraphicsDataFactory::Context& ctx) { @@ -316,7 +337,7 @@ void CTexture::BuildC4FromGCN(CInputStream& in) { } void CTexture::BuildC8FromGCN(CInputStream& in) { - size_t texelCount = ComputeMippedTexelCount(); + const size_t texelCount = ComputeMippedTexelCount(); std::unique_ptr buf(new RGBA8[texelCount]); std::vector palette = DecodePalette(256, in); @@ -324,26 +345,29 @@ void CTexture::BuildC8FromGCN(CInputStream& in) { int h = x6_h; RGBA8* targetMip = buf.get(); for (u32 mip = 0; mip < x8_mips; ++mip) { - int bwidth = (w + 7) / 8; - int bheight = (h + 3) / 4; + const int bwidth = (w + 7) / 8; + const int bheight = (h + 3) / 4; for (int by = 0; by < bheight; ++by) { - int baseY = by * 4; + const int baseY = by * 4; for (int bx = 0; bx < bwidth; ++bx) { - int baseX = bx * 8; + const int baseX = bx * 8; for (int y = 0; y < 4; ++y) { RGBA8* target = targetMip + (baseY + y) * w + baseX; - u8 source[8]; - in.readBytesToBuf(source, 8); - for (int x = 0; x < 8; ++x) + std::array source; + in.readBytesToBuf(source.data(), source.size()); + for (size_t x = 0; x < source.size(); ++x) { target[x] = palette[source[x]]; + } } } } targetMip += w * h; - if (w > 1) + if (w > 1) { w /= 2; - if (h > 1) + } + if (h > 1) { h /= 2; + } } CGraphics::CommitResources([&](boo::IGraphicsDataFactory::Context& ctx) { @@ -357,23 +381,23 @@ void CTexture::BuildC8FromGCN(CInputStream& in) { void CTexture::BuildC14X2FromGCN(CInputStream& in) {} void CTexture::BuildRGB565FromGCN(CInputStream& in) { - size_t texelCount = ComputeMippedTexelCount(); + const size_t texelCount = ComputeMippedTexelCount(); std::unique_ptr buf(new RGBA8[texelCount]); int w = x4_w; int h = x6_h; RGBA8* targetMip = buf.get(); for (u32 mip = 0; mip < x8_mips; ++mip) { - int bwidth = (w + 3) / 4; - int bheight = (h + 3) / 4; + const int bwidth = (w + 3) / 4; + const int bheight = (h + 3) / 4; for (int by = 0; by < bheight; ++by) { - int baseY = by * 4; + const int baseY = by * 4; for (int bx = 0; bx < bwidth; ++bx) { - int baseX = bx * 4; + const int baseX = bx * 4; for (int y = 0; y < 4; ++y) { RGBA8* target = targetMip + (baseY + y) * w + baseX; - for (int x = 0; x < 4; ++x) { - u16 texel = in.readUint16Big(); + for (size_t x = 0; x < 4; ++x) { + const u16 texel = in.readUint16Big(); target[x].r = Convert5To8(texel >> 11 & 0x1f); target[x].g = Convert6To8(texel >> 5 & 0x3f); target[x].b = Convert5To8(texel & 0x1f); @@ -383,10 +407,12 @@ void CTexture::BuildRGB565FromGCN(CInputStream& in) { } } targetMip += w * h; - if (w > 1) + if (w > 1) { w /= 2; - if (h > 1) + } + if (h > 1) { h /= 2; + } } CGraphics::CommitResources([&](boo::IGraphicsDataFactory::Context& ctx) { @@ -405,17 +431,17 @@ void CTexture::BuildRGB5A3FromGCN(CInputStream& in) { int h = x6_h; RGBA8* targetMip = buf.get(); for (u32 mip = 0; mip < x8_mips; ++mip) { - int bwidth = (w + 3) / 4; - int bheight = (h + 3) / 4; + const int bwidth = (w + 3) / 4; + const int bheight = (h + 3) / 4; for (int by = 0; by < bheight; ++by) { - int baseY = by * 4; + const int baseY = by * 4; for (int bx = 0; bx < bwidth; ++bx) { - int baseX = bx * 4; + const int baseX = bx * 4; for (int y = 0; y < 4; ++y) { RGBA8* target = targetMip + (baseY + y) * w + baseX; - for (int x = 0; x < 4; ++x) { - u16 texel = in.readUint16Big(); - if (texel & 0x8000) { + for (size_t x = 0; x < 4; ++x) { + const u16 texel = in.readUint16Big(); + if ((texel & 0x8000) != 0) { target[x].r = Convert5To8(texel >> 10 & 0x1f); target[x].g = Convert5To8(texel >> 5 & 0x1f); target[x].b = Convert5To8(texel & 0x1f); @@ -431,10 +457,12 @@ void CTexture::BuildRGB5A3FromGCN(CInputStream& in) { } } targetMip += w * h; - if (w > 1) + if (w > 1) { w /= 2; - if (h > 1) + } + if (h > 1) { h /= 2; + } } CGraphics::CommitResources([&](boo::IGraphicsDataFactory::Context& ctx) { @@ -446,26 +474,26 @@ void CTexture::BuildRGB5A3FromGCN(CInputStream& in) { } void CTexture::BuildRGBA8FromGCN(CInputStream& in) { - size_t texelCount = ComputeMippedTexelCount(); + const size_t texelCount = ComputeMippedTexelCount(); std::unique_ptr buf(new RGBA8[texelCount]); int w = x4_w; int h = x6_h; RGBA8* targetMip = buf.get(); for (u32 mip = 0; mip < x8_mips; ++mip) { - int bwidth = (w + 3) / 4; - int bheight = (h + 3) / 4; + const int bwidth = (w + 3) / 4; + const int bheight = (h + 3) / 4; for (int by = 0; by < bheight; ++by) { - int baseY = by * 4; + const int baseY = by * 4; for (int bx = 0; bx < bwidth; ++bx) { - int baseX = bx * 4; + const int baseX = bx * 4; for (int c = 0; c < 2; ++c) { for (int y = 0; y < 4; ++y) { RGBA8* target = targetMip + (baseY + y) * w + baseX; - u8 source[8]; - in.readBytesToBuf(source, 8); - for (int x = 0; x < 4; ++x) { - if (c) { + std::array source; + in.readBytesToBuf(source.data(), source.size()); + for (size_t x = 0; x < 4; ++x) { + if (c != 0) { target[x].g = source[x * 2]; target[x].b = source[x * 2 + 1]; } else { @@ -478,10 +506,12 @@ void CTexture::BuildRGBA8FromGCN(CInputStream& in) { } } targetMip += w * h; - if (w > 1) + if (w > 1) { w /= 2; - if (h > 1) + } + if (h > 1) { h /= 2; + } } CGraphics::CommitResources([&](boo::IGraphicsDataFactory::Context& ctx) { @@ -492,36 +522,30 @@ void CTexture::BuildRGBA8FromGCN(CInputStream& in) { } BooTrace); } -struct DXT1Block { - uint16_t color1; - uint16_t color2; - uint8_t lines[4]; -}; - void CTexture::BuildDXT1FromGCN(CInputStream& in) { - size_t blockCount = ComputeMippedBlockCountDXT1(); + const size_t blockCount = ComputeMippedBlockCountDXT1(); std::unique_ptr buf(new DXT1Block[blockCount]); int w = x4_w / 4; int h = x6_h / 4; DXT1Block* targetMip = buf.get(); for (u32 mip = 0; mip < x8_mips; ++mip) { - int bwidth = (w + 1) / 2; - int bheight = (h + 1) / 2; + const int bwidth = (w + 1) / 2; + const int bheight = (h + 1) / 2; for (int by = 0; by < bheight; ++by) { - int baseY = by * 2; + const int baseY = by * 2; for (int bx = 0; bx < bwidth; ++bx) { - int baseX = bx * 2; + const int baseX = bx * 2; for (int y = 0; y < 2; ++y) { DXT1Block* target = targetMip + (baseY + y) * w + baseX; - DXT1Block source[2]; - in.readBytesToBuf(source, 16); - for (int x = 0; x < 2; ++x) { + std::array source; + in.readBytesToBuf(source.data(), sizeof(source)); + for (size_t x = 0; x < source.size(); ++x) { target[x].color1 = hecl::SBig(source[x].color1); target[x].color2 = hecl::SBig(source[x].color2); - for (u32 i = 0; i < 4; ++i) { - u8 ind[4]; - u8 packed = source[x].lines[i]; + for (size_t i = 0; i < 4; ++i) { + std::array ind; + const u8 packed = source[x].lines[i]; ind[3] = packed & 0x3; ind[2] = (packed >> 2) & 0x3; ind[1] = (packed >> 4) & 0x3; @@ -534,10 +558,12 @@ void CTexture::BuildDXT1FromGCN(CInputStream& in) { } targetMip += w * h; - if (w > 1) + if (w > 1) { w /= 2; - if (h > 1) + } + if (h > 1) { h /= 2; + } } CGraphics::CommitResources([&](boo::IGraphicsDataFactory::Context& ctx) { @@ -602,10 +628,9 @@ void CTexture::BuildC8Font(const void* data, EFontType ftype) { break; } - uint32_t nentries = hecl::SBig(*reinterpret_cast(data)); + const uint32_t nentries = hecl::SBig(*reinterpret_cast(data)); const u8* texels = reinterpret_cast(data) + 4 + nentries * 4; - std::unique_ptr buf(new RGBA8[texelCount * layerCount]); - memset(buf.get(), 0, texelCount * layerCount * 4); + auto buf = std::make_unique(texelCount * layerCount); size_t w = x4_w; size_t h = x6_h; diff --git a/Runtime/Graphics/Shaders/CColoredQuadFilter.cpp b/Runtime/Graphics/Shaders/CColoredQuadFilter.cpp index b7a19e217..062f89cd7 100644 --- a/Runtime/Graphics/Shaders/CColoredQuadFilter.cpp +++ b/Runtime/Graphics/Shaders/CColoredQuadFilter.cpp @@ -88,8 +88,6 @@ void CWideScreenFilter::draw(const zeus::CColor& color, float t) { } } -void CWideScreenFilter::DrawFilter(EFilterShape shape, const zeus::CColor& color, float t) {} - float CWideScreenFilter::SetViewportToMatch(float t) { if (g_Viewport.aspect < 1.7777f) { float targetHeight = g_Viewport.x8_width / 1.7777f; diff --git a/Runtime/Graphics/Shaders/CColoredQuadFilter.hpp b/Runtime/Graphics/Shaders/CColoredQuadFilter.hpp index 631a4ee68..fe42325d4 100644 --- a/Runtime/Graphics/Shaders/CColoredQuadFilter.hpp +++ b/Runtime/Graphics/Shaders/CColoredQuadFilter.hpp @@ -42,7 +42,7 @@ public: explicit CWideScreenFilter(EFilterType type) : m_top(type), m_bottom(type) {} explicit CWideScreenFilter(EFilterType type, const TLockedToken&) : CWideScreenFilter(type) {} void draw(const zeus::CColor& color, float t); - void DrawFilter(EFilterShape shape, const zeus::CColor& color, float t); + void DrawFilter(EFilterShape shape, const zeus::CColor& color, float t) { draw(color, t); } static float SetViewportToMatch(float t); static void SetViewportToFull(); diff --git a/Runtime/Graphics/Shaders/CFluidPlaneShader.cpp b/Runtime/Graphics/Shaders/CFluidPlaneShader.cpp index 9ca4e35f4..f845e2f8e 100644 --- a/Runtime/Graphics/Shaders/CFluidPlaneShader.cpp +++ b/Runtime/Graphics/Shaders/CFluidPlaneShader.cpp @@ -204,10 +204,10 @@ CFluidPlaneShader::CFluidPlaneShader(EFluidType type, const TLockedToken& patternTex1, const TLockedToken& patternTex2, const TLockedToken& colorTex, u32 maxVertCount) : m_patternTex1(patternTex1), m_patternTex2(patternTex2), m_colorTex(colorTex) { - SFluidPlaneDoorShaderInfo shaderInfo(m_patternTex1.operator bool(), m_patternTex2.operator bool(), - m_colorTex.operator bool()); + SFluidPlaneDoorShaderInfo shaderInfo(m_patternTex1.HasReference(), m_patternTex2.HasReference(), + m_colorTex.HasReference()); m_pipelines = _cache.GetOrBuildShader(shaderInfo); PrepareBinding(maxVertCount); } diff --git a/Runtime/Graphics/Shaders/CParticleSwooshShaders.cpp b/Runtime/Graphics/Shaders/CParticleSwooshShaders.cpp index 8d83479e6..2deef8f1b 100644 --- a/Runtime/Graphics/Shaders/CParticleSwooshShaders.cpp +++ b/Runtime/Graphics/Shaders/CParticleSwooshShaders.cpp @@ -19,8 +19,6 @@ std::array, 2> CParticleSwooshShaders::m_noT std::array, 2> CParticleSwooshShaders::m_noTexAdditiveZWrite; std::array, 2> CParticleSwooshShaders::m_noTexAdditiveNoZWrite; -static boo::ObjToken s_Pipeline; - void CParticleSwooshShaders::Initialize() { m_texZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderTexZWrite{}), hecl::conv->convert(Shader_CParticleSwooshShaderTexZWriteAWrite{})}; diff --git a/Runtime/GuiSys/CCompoundTargetReticle.cpp b/Runtime/GuiSys/CCompoundTargetReticle.cpp index 8415c92e9..9fcbd19e7 100644 --- a/Runtime/GuiSys/CCompoundTargetReticle.cpp +++ b/Runtime/GuiSys/CCompoundTargetReticle.cpp @@ -349,7 +349,7 @@ void CCompoundTargetReticle::UpdateCurrLockOnGroup(float dt, const CStateManager const TUniqueId targetId = mgr.GetPlayer().GetOrbitTargetId(); if (targetId != xf0_targetId) { if (targetId != kInvalidUniqueId) { - if (const TCastToConstPtr point = mgr.GetObjectById(targetId)) { + if (TCastToConstPtr(mgr.GetObjectById(targetId))) { CSfxManager::SfxStart(SFXui_lockon_grapple, 1.f, 0.f, false, 0x7f, false, kInvalidAreaId); } else { CSfxManager::SfxStart(SFXui_lockon_poi, 1.f, 0.f, false, 0x7f, false, kInvalidAreaId); diff --git a/Runtime/GuiSys/CGuiFrame.cpp b/Runtime/GuiSys/CGuiFrame.cpp index 151a7cfa1..221870588 100644 --- a/Runtime/GuiSys/CGuiFrame.cpp +++ b/Runtime/GuiSys/CGuiFrame.cpp @@ -187,11 +187,14 @@ void CGuiFrame::LoadWidgetsInGame(CInputStream& in, CSimplePool* sp) { } void CGuiFrame::ProcessUserInput(const CFinalInput& input) const { - if (input.ControllerIdx() != 0) + if (input.ControllerIdx() != 0) { return; - for (auto& widget : x2c_widgets) { - if (widget->GetIsActive()) + } + + for (const auto& widget : x2c_widgets) { + if (widget->GetIsActive()) { widget->ProcessUserInput(input); + } } } diff --git a/Runtime/GuiSys/CGuiPane.cpp b/Runtime/GuiSys/CGuiPane.cpp index 5cd7658a5..86abb0467 100644 --- a/Runtime/GuiSys/CGuiPane.cpp +++ b/Runtime/GuiSys/CGuiPane.cpp @@ -4,7 +4,7 @@ namespace urde { CGuiPane::CGuiPane(const CGuiWidgetParms& parms, const zeus::CVector2f& dim, const zeus::CVector3f& scaleCenter) : CGuiWidget(parms), xb8_dim(dim), xc8_scaleCenter(scaleCenter) { - InitializeBuffers(); + CGuiPane::InitializeBuffers(); } void CGuiPane::ScaleDimensions(const zeus::CVector3f& scale) { diff --git a/Runtime/GuiSys/CGuiSliderGroup.cpp b/Runtime/GuiSys/CGuiSliderGroup.cpp index bdb3e49d7..bc9438412 100644 --- a/Runtime/GuiSys/CGuiSliderGroup.cpp +++ b/Runtime/GuiSys/CGuiSliderGroup.cpp @@ -33,12 +33,15 @@ void CGuiSliderGroup::StartIncreasing() { } bool CGuiSliderGroup::TestCursorHit(const zeus::CMatrix4f& vp, const zeus::CVector2f& point) const { - if (xcc_sliderRangeWidgets[0]->GetWidgetTypeID() != FOURCC('MODL')) + if (xcc_sliderRangeWidgets[0]->GetWidgetTypeID() != FOURCC('MODL')) { return false; + } + CGuiModel* bar = static_cast(xcc_sliderRangeWidgets[0]); - auto& modelTok = bar->GetModel(); - if (!modelTok || !modelTok.IsLoaded()) + const auto& modelTok = bar->GetModel(); + if (!modelTok || !modelTok.IsLoaded()) { return false; + } const zeus::CVector3f& s0 = xcc_sliderRangeWidgets[0]->GetIdlePosition(); const zeus::CVector3f& s1 = xcc_sliderRangeWidgets[1]->GetIdlePosition(); diff --git a/Runtime/GuiSys/CGuiTextSupport.cpp b/Runtime/GuiSys/CGuiTextSupport.cpp index 9a62ed6c0..7a93a8e9b 100644 --- a/Runtime/GuiSys/CGuiTextSupport.cpp +++ b/Runtime/GuiSys/CGuiTextSupport.cpp @@ -68,7 +68,7 @@ float CGuiTextSupport::GetCurrentAnimationOverAge() const { if (const CTextRenderBuffer* buf = GetCurrentPageRenderBuffer()) { if (x50_typeEnable) { if (x40_primStartTimes.size()) { - auto& lastTime = x40_primStartTimes.back(); + const auto& lastTime = x40_primStartTimes.back(); ret = std::max(ret, (buf->GetPrimitiveCount() - lastTime.second) / x58_chRate + lastTime.first); } else { ret = std::max(ret, buf->GetPrimitiveCount() / x58_chRate); diff --git a/Runtime/GuiSys/CHudVisorBeamMenu.cpp b/Runtime/GuiSys/CHudVisorBeamMenu.cpp index 8d6623665..2cc4a9388 100644 --- a/Runtime/GuiSys/CHudVisorBeamMenu.cpp +++ b/Runtime/GuiSys/CHudVisorBeamMenu.cpp @@ -13,23 +13,23 @@ namespace urde { constexpr std::array BaseMenuNames{ - "BaseWidget_VisorMenu", - "BaseWidget_BeamMenu", + "BaseWidget_VisorMenu"sv, + "BaseWidget_BeamMenu"sv, }; constexpr std::array TextNames{ - "TextPane_VisorMenu", - "TextPane_BeamMenu", + "TextPane_VisorMenu"sv, + "TextPane_BeamMenu"sv, }; constexpr std::array BaseTitleNames{ - "basewidget_visormenutitle", - "basewidget_beammenutitle", + "basewidget_visormenutitle"sv, + "basewidget_beammenutitle"sv, }; constexpr std::array ModelNames{ - "model_visor", - "model_beam", + "model_visor"sv, + "model_beam"sv, }; constexpr std::array, 2> MenuItemOrders{{ diff --git a/Runtime/GuiSys/CTextParser.cpp b/Runtime/GuiSys/CTextParser.cpp index 952e8b35d..154e7d5f3 100644 --- a/Runtime/GuiSys/CTextParser.cpp +++ b/Runtime/GuiSys/CTextParser.cpp @@ -5,7 +5,7 @@ namespace urde { -static float u16stof(char16_t* str) { +static float u16stof(const char16_t* str) { char cstr[16]; int i; for (i = 0; i < 15 && str[i] != u'\0'; ++i) diff --git a/Runtime/MP1/CMFGame.cpp b/Runtime/MP1/CMFGame.cpp index 7c413d8f0..e6d974961 100644 --- a/Runtime/MP1/CMFGame.cpp +++ b/Runtime/MP1/CMFGame.cpp @@ -289,7 +289,7 @@ void CMFGameLoader::MakeLoadDependencyList() { static constexpr std::array loadDepPAKs{"TestAnim", "SamusGun", "SamGunFx"}; std::vector tags; - for (const auto pak : loadDepPAKs) { + for (const auto* const pak : loadDepPAKs) { g_ResFactory->GetTagListForFile(pak, tags); } diff --git a/Runtime/MP1/CSlideShow.cpp b/Runtime/MP1/CSlideShow.cpp index 57dd34af3..1ad833348 100644 --- a/Runtime/MP1/CSlideShow.cpp +++ b/Runtime/MP1/CSlideShow.cpp @@ -1,10 +1,16 @@ #include "Runtime/MP1/CSlideShow.hpp" -#include "Editor/ProjectManager.hpp" +#include +#include "Editor/ProjectManager.hpp" #include "Runtime/GameGlobalObjects.hpp" namespace urde { +namespace { +bool AreAllDepsLoaded(const std::vector>& deps) { + return std::all_of(deps.cbegin(), deps.cend(), [](const auto& dep) { return dep.IsLoaded(); }); +} +} // Anonymous namespace CSlideShow::CSlideShow() : CIOWin("SlideShow"), x130_(g_tweakSlideShow->GetX54()) { const SObjectTag* font = g_ResFactory->GetResourceIdByName(g_tweakSlideShow->GetFont()); @@ -58,14 +64,6 @@ bool CSlideShow::LoadTXTRDep(std::string_view name) { return false; } -bool CSlideShow::AreAllDepsLoaded(const std::vector>& deps) { - for (const TLockedToken& token : deps) { - if (!token.IsLoaded()) - return false; - } - return true; -} - CIOWin::EMessageReturn CSlideShow::OnMessage(const CArchitectureMessage& msg, CArchitectureQueue& queue) { switch (msg.GetType()) { case EArchMsgType::TimerTick: { diff --git a/Runtime/MP1/CSlideShow.hpp b/Runtime/MP1/CSlideShow.hpp index 4d2689f72..0c6d9ecab 100644 --- a/Runtime/MP1/CSlideShow.hpp +++ b/Runtime/MP1/CSlideShow.hpp @@ -98,7 +98,6 @@ private: bool x135_24_ : 1 = true; bool LoadTXTRDep(std::string_view name); - static bool AreAllDepsLoaded(const std::vector>& deps); public: CSlideShow(); diff --git a/Runtime/MP1/CTweaks.cpp b/Runtime/MP1/CTweaks.cpp index 790b632c1..fb9d86943 100644 --- a/Runtime/MP1/CTweaks.cpp +++ b/Runtime/MP1/CTweaks.cpp @@ -21,9 +21,7 @@ #include -namespace urde { - -namespace MP1 { +namespace urde::MP1 { static logvisor::Module Log("MP1::CTweaks"); @@ -136,5 +134,4 @@ void CTweaks::RegisterResourceTweaks(hecl::CVarManager* cvarMgr) { g_tweakPlayerRes->initCVars(cvarMgr); } -} // namespace MP1 -} // namespace urde +} // namespace urde::MP1 diff --git a/Runtime/MP1/World/CBurrower.cpp b/Runtime/MP1/World/CBurrower.cpp index ca2956771..91f87ed92 100644 --- a/Runtime/MP1/World/CBurrower.cpp +++ b/Runtime/MP1/World/CBurrower.cpp @@ -228,7 +228,7 @@ void CBurrower::Active(CStateManager& mgr, EStateMsg msg, float dt) { x6ac_24_doFacePlayer = true; x32c_animState = EAnimState::Ready; } else if (msg == EStateMsg::Update) { - TryCommand(mgr, pas::EAnimationState::Generate, &CPatterned::TryGenerate, 0); + TryCommand(mgr, pas::EAnimationState::Generate, &CPatterned::TryGenerateNoXf, 0); } else if (msg == EStateMsg::Deactivate) { x6ac_24_doFacePlayer = false; x6ac_25_inAir = true; @@ -267,7 +267,7 @@ void CBurrower::Retreat(CStateManager& mgr, EStateMsg msg, float dt) { if (msg == EStateMsg::Activate) { x32c_animState = EAnimState::Ready; } else if (msg == EStateMsg::Update) { - TryCommand(mgr, pas::EAnimationState::Generate, &CPatterned::TryGenerate, 1); + TryCommand(mgr, pas::EAnimationState::Generate, &CPatterned::TryGenerateNoXf, 1); } else if (msg == EStateMsg::Deactivate) { x32c_animState = EAnimState::NotReady; if (x678_trailParticle) { diff --git a/Runtime/MP1/World/CChozoGhost.cpp b/Runtime/MP1/World/CChozoGhost.cpp index b59524219..2519b3ce4 100644 --- a/Runtime/MP1/World/CChozoGhost.cpp +++ b/Runtime/MP1/World/CChozoGhost.cpp @@ -405,7 +405,7 @@ void CChozoGhost::Deactivate(CStateManager& mgr, EStateMsg msg, float) { x32c_animState = EAnimState::Ready; x665_24_ = true; } else if (msg == EStateMsg::Update) { - TryCommand(mgr, pas::EAnimationState::Generate, &CPatterned::TryGenerate, 1); + TryCommand(mgr, pas::EAnimationState::Generate, &CPatterned::TryGenerateNoXf, 1); if (x32c_animState == EAnimState::Repeat) GetBodyController()->SetLocomotionType(pas::ELocomotionType::Relaxed); } else if (msg == EStateMsg::Deactivate) { diff --git a/Runtime/MP1/World/CElitePirate.cpp b/Runtime/MP1/World/CElitePirate.cpp index 2757e0d4e..8d3602796 100644 --- a/Runtime/MP1/World/CElitePirate.cpp +++ b/Runtime/MP1/World/CElitePirate.cpp @@ -1,5 +1,6 @@ #include "Runtime/MP1/World/CElitePirate.hpp" +#include "Runtime/Camera/CFirstPersonCamera.hpp" #include "Runtime/Collision/CCollisionActor.hpp" #include "Runtime/Collision/CCollisionActorManager.hpp" #include "Runtime/CSimplePool.hpp" @@ -248,10 +249,10 @@ void CElitePirate::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CSta void CElitePirate::PreRender(CStateManager& mgr, const zeus::CFrustum& frustum) { CPatterned::PreRender(mgr, frustum); - auto modelData = GetModelData(); + auto* modelData = GetModelData(); x6f8_boneTracking.PreRender(mgr, *modelData->GetAnimationData(), GetTransform(), modelData->GetScale(), *x450_bodyController); - auto numMaterialSets = modelData->GetNumMaterialSets(); + const auto numMaterialSets = modelData->GetNumMaterialSets(); xb4_drawFlags.x1_matSetIdx = numMaterialSets - 1 < x7cc_activeMaterialSet ? numMaterialSets - 1 : x7cc_activeMaterialSet; } @@ -292,27 +293,22 @@ zeus::CVector3f CElitePirate::GetAimPosition(const CStateManager& mgr, float) co } void CElitePirate::DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node, EUserEventType type, float dt) { - bool handled = false; switch (type) { case EUserEventType::Projectile: if (x772_launcherId != kInvalidUniqueId) { CEntity* launcher = mgr.ObjectById(x772_launcherId); mgr.SendScriptMsg(launcher, GetUniqueId(), EScriptObjectMessage::Action); } - handled = true; - break; + return; case EUserEventType::DamageOn: - handled = true; x988_24_damageOn = true; - break; + return; case EUserEventType::DamageOff: - handled = true; x988_24_damageOn = false; - break; + return; case EUserEventType::ScreenShake: - HasWeakPointHead(); - handled = true; - break; + ShakeCamera(mgr); + return; case EUserEventType::BeginAction: { const zeus::CVector3f origin = GetTranslation(); const zeus::CVector3f front = GetTransform().frontVector(); @@ -325,8 +321,7 @@ void CElitePirate::DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node mgr.AddObject(new CShockWave(mgr.AllocateUniqueId(), "Shock Wave", {GetAreaIdAlways(), CEntity::NullConnectionList}, xf, GetUniqueId(), GetShockWaveData(), IsElitePirate() ? 2.f : 1.3f, IsElitePirate() ? 0.4f : 0.5f)); - handled = true; - break; + return; } case EUserEventType::BecomeShootThrough: if (HasWeakPointHead()) { @@ -338,14 +333,11 @@ void CElitePirate::DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node } } } - handled = true; - break; + return; default: break; } - if (!handled) { - CPatterned::DoUserAnimEvent(mgr, node, type, dt); - } + CPatterned::DoUserAnimEvent(mgr, node, type, dt); } const CCollisionPrimitive* CElitePirate::GetCollisionPrimitive() const { return &x738_collisionAabb; } @@ -757,7 +749,7 @@ void CElitePirate::SetupHealthInfo(CStateManager& mgr) { x7b4_hp = health->GetHP(); if (HasWeakPointHead()) { if (TCastToPtr actor = mgr.ObjectById(x770_collisionHeadId)) { - auto actHealth = actor->HealthInfo(mgr); + auto* actHealth = actor->HealthInfo(mgr); actHealth->SetHP(health->GetHP()); actHealth->SetKnockbackResistance(health->GetKnockbackResistance()); actor->SetDamageVulnerability(x56c_vulnerability); @@ -940,13 +932,15 @@ void CElitePirate::CreateEnergyAbsorb(CStateManager& mgr, const zeus::CTransform void CElitePirate::SetupLauncherHealthInfo(CStateManager& mgr, TUniqueId uid) { const CHealthInfo* const health = HealthInfo(mgr); - if (uid != kInvalidUniqueId) { - if (TCastToPtr actor = mgr.ObjectById(uid)) { - auto actHealth = actor->HealthInfo(mgr); - actHealth->SetHP(x5d8_data.GetLauncherHP()); - actHealth->SetKnockbackResistance(health->GetKnockbackResistance()); - actor->SetDamageVulnerability(x56c_vulnerability); - } + if (uid == kInvalidUniqueId) { + return; + } + + if (const TCastToPtr actor = mgr.ObjectById(uid)) { + auto* actHealth = actor->HealthInfo(mgr); + actHealth->SetHP(x5d8_data.GetLauncherHP()); + actHealth->SetKnockbackResistance(health->GetKnockbackResistance()); + actor->SetDamageVulnerability(x56c_vulnerability); } } @@ -954,7 +948,7 @@ void CElitePirate::SetLauncherActive(CStateManager& mgr, bool val, TUniqueId uid if (uid == kInvalidUniqueId) { return; } - if (auto entity = mgr.ObjectById(uid)) { + if (auto* entity = mgr.ObjectById(uid)) { mgr.SendScriptMsg(entity, GetUniqueId(), val ? EScriptObjectMessage::Start : EScriptObjectMessage::Stop); } } @@ -1178,6 +1172,25 @@ bool CElitePirate::IsClosestEnergyAttractor(const CStateManager& mgr, return true; } +void CElitePirate::ShakeCamera(CStateManager& mgr) { + CPlayer& player = mgr.GetPlayer(); + const float distance = (GetTranslation() - player.GetTranslation()).magnitude(); + const float scale = x988_29_shockWaveAnim ? 1.f : 0.25f; + const float magnitude = (scale * GetModelData()->GetScale().magnitude()) - (0.005f * distance); + if (magnitude <= 0.f || player.GetSurfaceRestraint() == CPlayer::ESurfaceRestraints::Air || + player.IsInWaterMovement()) { + return; + } + if (player.GetMorphballTransitionState() == CPlayer::EPlayerMorphBallState::Morphed) { + const float intensity = x988_29_shockWaveAnim ? 20.f : 10.f; + player.ApplyImpulseWR(player.GetMass() * intensity * zeus::skUp, zeus::CAxisAngle{}); + player.SetMoveState(CPlayer::EPlayerMovementState::ApplyJump, mgr); + } else if (mgr.GetCameraManager()->GetCurrentCameraId() == + mgr.GetCameraManager()->GetFirstPersonCamera()->GetUniqueId()) { + mgr.GetCameraManager()->AddCameraShaker(CCameraShakeData{0.5f, magnitude}, true); + } +} + zeus::CVector3f CElitePirate::SPositionHistory::GetValue(const zeus::CVector3f& pos, const zeus::CVector3f& face) { while (!x4_values.empty()) { const zeus::CVector3f v = x4_values.back() - pos; diff --git a/Runtime/MP1/World/CElitePirate.hpp b/Runtime/MP1/World/CElitePirate.hpp index f582c145e..c3d3b506a 100644 --- a/Runtime/MP1/World/CElitePirate.hpp +++ b/Runtime/MP1/World/CElitePirate.hpp @@ -244,5 +244,6 @@ private: const zeus::CVector3f& vec) const; bool IsClosestEnergyAttractor(const CStateManager& mgr, const rstl::reserved_vector& charNearList, const zeus::CVector3f& projectilePos) const; + void ShakeCamera(CStateManager& mgr); }; } // namespace urde::MP1 diff --git a/Runtime/MP1/World/CMagdolite.cpp b/Runtime/MP1/World/CMagdolite.cpp index 60e0c0c89..465b39403 100644 --- a/Runtime/MP1/World/CMagdolite.cpp +++ b/Runtime/MP1/World/CMagdolite.cpp @@ -350,7 +350,7 @@ void CMagdolite::Generate(CStateManager& mgr, EStateMsg msg, float arg) { x32c_animState = EAnimState::Ready; x754_24_retreat = false; } else if (msg == EStateMsg::Update) { - TryCommand(mgr, pas::EAnimationState::Generate, &CPatterned::TryGenerateNoXf, 0); + TryCommand(mgr, pas::EAnimationState::Generate, &CPatterned::TryGenerate, 0); if (x32c_animState == EAnimState::Repeat) { GetBodyController()->SetLocomotionType(pas::ELocomotionType::Relaxed); } @@ -552,7 +552,7 @@ void CMagdolite::Retreat(CStateManager& mgr, EStateMsg msg, float arg) { GetBodyController()->GetCommandMgr().DeliverCmd(CBodyStateCmd(EBodyStateCmd::NextState)); x754_28_alert = true; } else if (msg == EStateMsg::Update) { - TryCommand(mgr, pas::EAnimationState::Generate, &CPatterned::TryGenerate, 1); + TryCommand(mgr, pas::EAnimationState::Generate, &CPatterned::TryGenerateNoXf, 1); if (x32c_animState == EAnimState::Repeat) { GetBodyController()->SetLocomotionType(pas::ELocomotionType::Internal7); } diff --git a/Runtime/MP1/World/CMetaree.cpp b/Runtime/MP1/World/CMetaree.cpp index 55697d0b6..2434111cd 100644 --- a/Runtime/MP1/World/CMetaree.cpp +++ b/Runtime/MP1/World/CMetaree.cpp @@ -15,7 +15,7 @@ CMetaree::CMetaree(TUniqueId uid, std::string_view name, EFlavorType flavor, con : CPatterned(ECharacter::Metaree, uid, name, flavor, info, xf, std::move(mData), pInfo, EMovementType::Flyer, EColliderType::Zero, bodyType, aParms, EKnockBackVariant::Small) , x568_delay(f3) -, x56c_(f4) +, x56c_haltDelay(f4) , x570_dropHeight(f1) , x574_offset(v1) , x580_attackSpeed(f2) @@ -29,10 +29,11 @@ void CMetaree::Accept(IVisitor& visitor) { visitor.Visit(this); } void CMetaree::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) { CPatterned::AcceptScriptMsg(msg, uid, mgr); - if (msg == EScriptObjectMessage::Start) + if (msg == EScriptObjectMessage::Start) { x5ca_25_started = true; - else if (msg == EScriptObjectMessage::Registered) + } else if (msg == EScriptObjectMessage::Registered) { x450_bodyController->Activate(mgr); + } } void CMetaree::Think(float dt, CStateManager& mgr) { @@ -46,8 +47,9 @@ void CMetaree::Think(float dt, CStateManager& mgr) { } void CMetaree::Explode(CStateManager& mgr, EStateMsg msg, float) { - if (msg != EStateMsg::Activate) + if (msg != EStateMsg::Activate) { return; + } mgr.ApplyDamage(GetUniqueId(), mgr.GetPlayer().GetUniqueId(), GetUniqueId(), x5ac_damageInfo, CMaterialFilter::MakeIncludeExclude({EMaterialTypes::Solid}, {}), {}); @@ -55,12 +57,14 @@ void CMetaree::Explode(CStateManager& mgr, EStateMsg msg, float) { } void CMetaree::Touch(CActor& act, CStateManager& mgr) { - if (!x400_25_alive) + if (!x400_25_alive) { return; + } if (TCastToPtr projectile = act) { - if (projectile->GetOwnerId() != mgr.GetPlayer().GetUniqueId()) + if (projectile->GetOwnerId() != mgr.GetPlayer().GetUniqueId()) { return; + } x400_24_hitByPlayerProjectile = true; x590_projectileDelta = projectile->GetTranslation() - projectile->GetPreviousPos(); @@ -68,8 +72,9 @@ void CMetaree::Touch(CActor& act, CStateManager& mgr) { } void CMetaree::CollidedWith(TUniqueId id, const CCollisionInfoList& colList, CStateManager& mgr) { - if (!x400_25_alive || colList.GetCount() <= 0) + if (!x400_25_alive || colList.GetCount() <= 0) { return; + } mgr.ApplyDamageToWorld(GetUniqueId(), *this, GetTranslation(), x5ac_damageInfo, CMaterialFilter::MakeInclude({EMaterialTypes::Player})); @@ -79,15 +84,15 @@ void CMetaree::CollidedWith(TUniqueId id, const CCollisionInfoList& colList, CSt void CMetaree::Flee(CStateManager& mgr, EStateMsg msg, float) { if (msg == EStateMsg::Activate) { - ApplyImpulseWR(5.f * (GetMass() * (x590_projectileDelta * zeus::CVector3f{1.f, 1.f, 0.f})), - zeus::CAxisAngle()); + ApplyImpulseWR(5.f * (GetMass() * (x590_projectileDelta * zeus::CVector3f{1.f, 1.f, 0.f})), zeus::CAxisAngle()); SetMomentumWR({0.f, 0.f, -GetGravityConstant() * GetMass()}); SetTranslation(GetTranslation()); x5a8_ = 0; } else if (msg == EStateMsg::Update) { - if (x5a8_ != 0) + if (x5a8_ != 0) { return; + } if (x450_bodyController->GetBodyStateInfo().GetCurrentStateId() == pas::EAnimationState::LieOnGround) { x5a8_ = 1; @@ -99,8 +104,9 @@ void CMetaree::Flee(CStateManager& mgr, EStateMsg msg, float) { } void CMetaree::Dead(CStateManager& mgr, EStateMsg msg, float) { - if (msg != EStateMsg::Activate) + if (msg != EStateMsg::Activate) { return; + } mgr.ApplyDamageToWorld(GetUniqueId(), *this, GetTranslation(), x5ac_damageInfo, CMaterialFilter::MakeIncludeExclude({EMaterialTypes::Player}, {})); @@ -116,9 +122,9 @@ void CMetaree::Attack(CStateManager&, EStateMsg msg, float) { x450_bodyController->SetLocomotionType(pas::ELocomotionType::Combat); x59c_velocity = x580_attackSpeed * dir; } else if (msg == EStateMsg::Update) { - if (x450_bodyController->GetPercentageFrozen() == 0.f) + if (x450_bodyController->GetPercentageFrozen() == 0.f) { SetVelocityWR(x59c_velocity); - else { + } else { Stop(); SetVelocityWR({}); } @@ -126,15 +132,17 @@ void CMetaree::Attack(CStateManager&, EStateMsg msg, float) { } void CMetaree::Halt(CStateManager& mgr, EStateMsg msg, float) { - if (msg != EStateMsg::Activate) + if (msg != EStateMsg::Activate) { return; + } Stop(); - SetVelocityWR({}); - SetMomentumWR({}); + SetVelocityWR(zeus::skZero3f); + SetMomentumWR(zeus::skZero3f); x450_bodyController->SetLocomotionType(pas::ELocomotionType::Lurk); x584_lookPos = x574_offset + mgr.GetPlayer().GetTranslation(); SetTransform(zeus::lookAt(GetTranslation(), x584_lookPos)); + x330_stateMachineState.SetDelay(x56c_haltDelay); } void CMetaree::Active(CStateManager& mgr, EStateMsg msg, float) { @@ -153,8 +161,7 @@ void CMetaree::Active(CStateManager& mgr, EStateMsg msg, float) { void CMetaree::InActive(CStateManager&, EStateMsg msg, float) { if (msg == EStateMsg::Activate) { - const auto locomotionType = x5ca_26_deactivated ? pas::ELocomotionType::Crouch - : pas::ELocomotionType::Relaxed; + const auto locomotionType = x5ca_26_deactivated ? pas::ELocomotionType::Crouch : pas::ELocomotionType::Relaxed; x450_bodyController->SetLocomotionType(locomotionType); } else if (msg == EStateMsg::Deactivate) { x5ca_26_deactivated = true; @@ -162,8 +169,9 @@ void CMetaree::InActive(CStateManager&, EStateMsg msg, float) { } bool CMetaree::InRange(CStateManager& mgr, float arg) { - if (x5ca_25_started) + if (x5ca_25_started) { return true; + } return CPatterned::InRange(mgr, arg); } diff --git a/Runtime/MP1/World/CMetaree.hpp b/Runtime/MP1/World/CMetaree.hpp index 6cec68b29..9f3d8a54e 100644 --- a/Runtime/MP1/World/CMetaree.hpp +++ b/Runtime/MP1/World/CMetaree.hpp @@ -10,7 +10,7 @@ namespace urde::MP1 { class CMetaree : public CPatterned { float x568_delay; - float x56c_; + float x56c_haltDelay; float x570_dropHeight; zeus::CVector3f x574_offset; float x580_attackSpeed; @@ -20,16 +20,9 @@ class CMetaree : public CPatterned { u32 x5a8_ = 0; CDamageInfo x5ac_damageInfo; u16 x5c8_attackSfx = SFXsfx0225; - - struct { - struct { - bool x5ca_24_ : 1; - bool x5ca_25_started : 1; - bool x5ca_26_deactivated : 1; - }; - u16 _dummy; - }; - + bool x5ca_24_ : 1; + bool x5ca_25_started : 1; + bool x5ca_26_deactivated : 1; u32 x5cc_; public: diff --git a/Runtime/MP1/World/CPhazonHealingNodule.cpp b/Runtime/MP1/World/CPhazonHealingNodule.cpp index 45a1533ed..cbd7c6692 100644 --- a/Runtime/MP1/World/CPhazonHealingNodule.cpp +++ b/Runtime/MP1/World/CPhazonHealingNodule.cpp @@ -162,9 +162,9 @@ void CPhazonHealingNodule::UpdateParticleElectric(CStateManager& mgr) { if (!x57c_particleElectric) { return; } - if (auto entity = static_cast(mgr.GetObjectById(x56e_connId))) { - auto electricityLctrXf = GetLctrTransform("Electricity_LCTR"sv); - auto actorLctrXf = entity->GetLctrTransform(x58c_actorLctr); + if (const auto* entity = static_cast(mgr.GetObjectById(x56e_connId))) { + const auto electricityLctrXf = GetLctrTransform("Electricity_LCTR"sv); + const auto actorLctrXf = entity->GetLctrTransform(x58c_actorLctr); x57c_particleElectric->SetOverrideIPos(electricityLctrXf.origin); x57c_particleElectric->SetOverrideFPos(actorLctrXf.origin); } diff --git a/Runtime/MP1/World/CRidley.cpp b/Runtime/MP1/World/CRidley.cpp index e882b9f10..9df3433c2 100644 --- a/Runtime/MP1/World/CRidley.cpp +++ b/Runtime/MP1/World/CRidley.cpp @@ -18,9 +18,7 @@ #include "Runtime/World/CScriptWaypoint.hpp" #include "TCastTo.hpp" // Generated file, do not modify include path -namespace urde { -namespace MP1 { - +namespace urde::MP1 { namespace { struct SSomeRidleyStruct { u32 x0_; @@ -116,11 +114,14 @@ constexpr std::array, 5> skSomeRidleyStruct{{ }}, }}; -constexpr std::array skSomeStruct{{{4, 6, 50.f, 50.f, 0.f, 33.f, 0.f, 1, 0, 0, 0, 0}, - {4, 6, 20.f, 20.f, 60.f, 50.f, 0.f, 2, 0, 0, 0, 0}, - {4, 6, 40.f, 40.f, 20.f, 50.f, 50.f, 2, 1, 0, 0, 0}, - {3, 5, 10.f, 15.f, 75.f, 100.f, 25.f, 2, 0, 0, 0, 0}, - {3, 5, 30.f, 30.f, 40.f, 50.f, 50.f, 2, 1, 0, 0, 0}}}; +constexpr std::array skSomeStruct{{ + {4, 6, 50.f, 50.f, 0.f, 33.f, 0.f, 1, 0, 0, 0, 0}, + {4, 6, 20.f, 20.f, 60.f, 50.f, 0.f, 2, 0, 0, 0, 0}, + {4, 6, 40.f, 40.f, 20.f, 50.f, 50.f, 2, 1, 0, 0, 0}, + {3, 5, 10.f, 15.f, 75.f, 100.f, 25.f, 2, 0, 0, 0, 0}, + {3, 5, 30.f, 30.f, 40.f, 50.f, 50.f, 2, 1, 0, 0, 0}, +}}; + constexpr std::array skWingBones{ "L_wingBone1_1"sv, "L_wingBone1_2"sv, "L_wingBone2_1"sv, "L_wingBone2_2"sv, "L_wingBone3_1"sv, "L_wingBone3_2"sv, "L_wingFlesh1_1"sv, "L_wingFlesh1_2"sv, "L_wingFlesh2_1"sv, "L_wingFlesh2_2"sv, @@ -131,30 +132,11 @@ constexpr std::array skWingBones{ }; constexpr std::array skWingEffects{ - "WingSmokeSmall1"sv, - "WingSmokeSmall2"sv, - "WingSmokeSmall3"sv, - "WingSmokeSmall4"sv, - "WingSmokeSmall5"sv, - "WingSmokeSmall6"sv, - "WingSmokeSmall7"sv, - "WingSmokeSmall8"sv - "WingFire1"sv, - "WingFire2"sv, - "WingFire3"sv, - "WingFire4"sv, - "WingFire5"sv, - "WingFire6"sv, - "WingFire7"sv, - "WingFire8"sv, - "WingSparks1"sv, - "WingSparks2"sv, - "WingSparks3"sv, - "WingSparks4"sv, - "WingSparks5"sv, - "WingSparks6"sv, - "WingSparks7"sv, - "WingSparks8"sv, + "WingSmokeSmall1"sv, "WingSmokeSmall2"sv, "WingSmokeSmall3"sv, "WingSmokeSmall4"sv, "WingSmokeSmall5"sv, + "WingSmokeSmall6"sv, "WingSmokeSmall7"sv, "WingSmokeSmall8"sv, "WingFire1"sv, "WingFire2"sv, + "WingFire3"sv, "WingFire4"sv, "WingFire5"sv, "WingFire6"sv, "WingFire7"sv, + "WingFire8"sv, "WingSparks1"sv, "WingSparks2"sv, "WingSparks3"sv, "WingSparks4"sv, + "WingSparks5"sv, "WingSparks6"sv, "WingSparks7"sv, "WingSparks8"sv, }; constexpr std::array skTail{{ @@ -167,7 +149,7 @@ constexpr std::array skTail{{ constexpr std::array skSphereJoints{{ {"Skeleton_Root", 0.6f}, {"Spine_2", 0.6f}, - {"breastPlate_LCTR", 0.6f}, + {"breastPlate_LCTR", 0.3f}, {"Head_1", 0.6f}, {"L_wrist", 0.5f}, {"R_wrist", 0.5f}, @@ -186,29 +168,31 @@ struct SSomeRidleyStruct3 { float x14_; }; -constexpr std::array skFloats{{{0.0, 20.0, 40.0, 0.0, 0.0, 40.0}, - {0.0, 0.0, 70.0, 0.0, 0.0, 30.0}, - {0.0, 60.0, 0.0, 0.0, 0.0, 40.0}, - {0.0, 40.0, 30.0, 0.0, 0.0, 30.0}, - {0.0, 0.0, 50.0, 0.0, 0.0, 50.0}, - {0.0, 40.0, 60.0, 0.0, 0.0, 0.0}}}; +constexpr std::array skFloats{{ + {0.0, 20.0, 40.0, 0.0, 0.0, 40.0}, + {0.0, 0.0, 70.0, 0.0, 0.0, 30.0}, + {0.0, 60.0, 0.0, 0.0, 0.0, 40.0}, + {0.0, 40.0, 30.0, 0.0, 0.0, 30.0}, + {0.0, 0.0, 50.0, 0.0, 0.0, 50.0}, + {0.0, 40.0, 60.0, 0.0, 0.0, 0.0}, +}}; -const CDamageVulnerability skDirectNormal{EVulnerability::DirectNormal, EVulnerability::DirectNormal, - EVulnerability::DirectNormal, EVulnerability::DirectNormal, - EVulnerability::DirectNormal, EVulnerability::DirectNormal, - EVulnerability::DirectNormal, EVulnerability::DirectNormal, - EVulnerability::DirectNormal, EVulnerability::DirectNormal, - EVulnerability::DirectNormal, EVulnerability::DirectNormal, - EVulnerability::DirectNormal, EVulnerability::DirectNormal, - EVulnerability::DirectNormal, EDeflectType::None}; -const CDamageVulnerability skIceWeakness{EVulnerability::DirectNormal, EVulnerability::DirectWeak, - EVulnerability::DirectNormal, EVulnerability::DirectNormal, - EVulnerability::DirectNormal, EVulnerability::DirectNormal, - EVulnerability::DirectNormal, EVulnerability::DirectNormal, - EVulnerability::DirectNormal, EVulnerability::DirectNormal, - EVulnerability::DirectNormal, EVulnerability::DirectNormal, - EVulnerability::DirectNormal, EVulnerability::DirectNormal, - EVulnerability::DirectNormal, EDeflectType::None}; +constexpr CDamageVulnerability skDirectNormal{EVulnerability::DirectNormal, EVulnerability::DirectNormal, + EVulnerability::DirectNormal, EVulnerability::DirectNormal, + EVulnerability::DirectNormal, EVulnerability::DirectNormal, + EVulnerability::DirectNormal, EVulnerability::DirectNormal, + EVulnerability::DirectNormal, EVulnerability::DirectNormal, + EVulnerability::DirectNormal, EVulnerability::DirectNormal, + EVulnerability::DirectNormal, EVulnerability::DirectNormal, + EVulnerability::DirectNormal, EDeflectType::None}; +constexpr CDamageVulnerability skIceWeakness{EVulnerability::DirectNormal, EVulnerability::DirectWeak, + EVulnerability::DirectNormal, EVulnerability::DirectNormal, + EVulnerability::DirectNormal, EVulnerability::DirectNormal, + EVulnerability::DirectNormal, EVulnerability::DirectNormal, + EVulnerability::DirectNormal, EVulnerability::DirectNormal, + EVulnerability::DirectNormal, EVulnerability::DirectNormal, + EVulnerability::DirectNormal, EVulnerability::DirectNormal, + EVulnerability::DirectNormal, EDeflectType::None}; } // namespace CRidleyData::CRidleyData(CInputStream& in, u32 propCount) : x0_(in) @@ -289,12 +273,13 @@ CRidley::CRidley(TUniqueId uid, std::string_view name, const CEntityInfo& info, xc14_.Token().Lock(); xc3c_.Token().Lock(); - if (xce0_) + if (xce0_) { xce0_->SetParticleEmission(false); + } const auto& animData = GetModelData()->GetAnimationData(); - for (size_t i = 0; i < skWingBones.size(); ++i) { - xce4_wingBoneIds.push_back(animData->GetLocatorSegId(skWingBones[i])); + for (const auto& wingBone : skWingBones) { + xce4_wingBoneIds.push_back(animData->GetLocatorSegId(wingBone)); } xae4_ = GetModelData()->GetScale().x() * @@ -344,7 +329,6 @@ void CRidley::SetupCollisionActorManager(urde::CStateManager& mgr) { include.Remove(EMaterialTypes::Platform); SetMaterialFilter(CMaterialFilter::MakeIncludeExclude(include, exclude)); AddMaterial(EMaterialTypes::ProjectilePassthrough); - // mgr.SendScriptMsg(this, GetUniqueId(), EScriptObjectMessage::Reset); } void CRidley::SetupCollisionActors(CStateManager& mgr) { @@ -387,7 +371,7 @@ void CRidley::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateMan case EScriptObjectMessage::Reset: { xa34_26_ = true; if (!GetActive()) { - AcceptScriptMsg(EScriptObjectMessage::Activate, uid, mgr); + CPatterned::AcceptScriptMsg(EScriptObjectMessage::Activate, uid, mgr); } break; } @@ -416,8 +400,9 @@ void CRidley::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateMan } case EScriptObjectMessage::InitializedInArea: { TUniqueId wpId = GetWaypointForState(mgr, EScriptObjectState::Patrol, EScriptObjectMessage::Follow); - if (wpId == kInvalidUniqueId) + if (wpId == kInvalidUniqueId) { break; + } if (TCastToConstPtr wp = mgr.GetObjectById(wpId)) { xa84_ = wp->GetTransform(); @@ -441,14 +426,27 @@ void CRidley::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateMan colAct->HealthInfo(mgr)->SetHP(1000.f); bool dontKnockback = false; if (xc64_aiStage == 2) { - if (xa33_28_) { - dontKnockback = true; - } else { + if (!xa33_28_) { bool r26 = false; xb10_ -= lowHealth; xb24_ = 0.33f; x430_damageColor = zeus::CColor(0.5f, 0.f, 0.f); - if (xb10_ <= 0.f) { + if (xb10_ > 0.f) { + if (xb10_ >= xcbc_&& xa33_26_ && !xa31_31_ && lowHealth > x568_data.x3f4_) { + dontKnockback = true; + x450_bodyController->GetCommandMgr().DeliverCmd( + CBCKnockBackCmd(GetTransform().basis[1], pas::ESeverity::Zero)); + } else { + xa32_27_ = true; + dontKnockback = true; + xcb0_ += 1; + xcb0_ = xcb0_ < 5 ? xcb0_ : 4; + r26 = true; + xcbc_ = .2f * float(5 - (xcb0_ + 1)) * xcb8_; + xcb4_ = 0; + xcc8_ = 2.f * 0.33f; + } + } else { xc64_aiStage = 3; xa31_25_ = false; sub80257650(mgr); @@ -461,78 +459,68 @@ void CRidley::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateMan xcc8_ = 2.f * 0.33f; xb10_ = 0.f; - } else { - if (xb10_ < xcbc_) { - xa32_27_ = true; - dontKnockback = true; - xcb0_ += 1; - xcb0_ = xcb0_ < 5 ? xcb0_ : 4; - r26 = true; - xcbc_ = .2f * (5 - (xcb0_ + 1)) * xcb8_; - xcb4_ = 0; - xcc8_ = 2.f * 0.33f; - } else if (xa33_26_ && !xa31_31_ && lowHealth > x568_data.x3f4_) { - dontKnockback = true; - x450_bodyController->GetCommandMgr().DeliverCmd( - CBCKnockBackCmd(GetTransform().basis[1], pas::ESeverity::Zero)); - } } sub80256914(2.f * 0.33f, r26); + } else { + dontKnockback = true; } } else if (xc64_aiStage == 3) { if (xa32_29_) { zeus::CTransform xf = GetLctrTransform(xb90_headSegId); - if (xf.basis[1].dot(mgr.GetPlayer().GetTranslation() - xf.origin) < 0.5f) { - dontKnockback = true; + if ((mgr.GetPlayer().GetTranslation() - xf.origin).dot(xf.frontVector()) < 0.5f) { + HealthInfo(mgr)->SetHP(xb1c_ + xb10_ + xb18_); + break; + } + } + + TakeDamage(zeus::skForward, 1.f); + xb20_ = 0.33f; + if (xa32_29_) { + if (TCastToConstPtr proj = mgr.GetObjectById(colAct->GetLastTouchedObject())) { + CWeaponMode wMode = proj->GetDamageInfo().GetWeaponMode(); + if (wMode.IsCharged() || wMode.IsComboed() || wMode.GetType() == EWeaponType::Missile) { + xb14_ = 0.f; + } + xb14_ -= lowHealth; + xb24_ = 0.33f; + x430_damageColor = zeus::CColor(0.5f, 0.f, 0.f); + if (xb10_ <= 0.f) { + xa32_29_ = false; + dontKnockback = true; + xa32_28_shotAt = true; + xb14_ = x568_data.x38_; + } + } + } else if (xa31_27_) { + x430_damageColor = zeus::CColor(0.5f, 0.f, 0.f); + if (xb18_ > 0.f) { + xb18_ -= lowHealth; + if (xb18_ <= 0.f) { + xa31_26_ = true; + dontKnockback = true; + xb18_ = 0.f; + xcbc_ = 0.6667f * x568_data.x40_; + } else if (xb18_ < xcbc_) { + x450_bodyController->GetCommandMgr().DeliverCmd( + CBCKnockBackCmd(GetTransform().basis[1], pas::ESeverity::Six)); + xcbc_ -= (0.333f * x568_data.x3c_); + } } else { - TakeDamage(zeus::skForward, 1.f); - xb20_ = 0.33f; - if (xa32_29_) { - if (TCastToConstPtr proj = mgr.GetObjectById(colAct->GetLastTouchedObject())) { - CWeaponMode wMode = proj->GetDamageInfo().GetWeaponMode(); - if (!wMode.IsCharged() && !wMode.IsComboed() && wMode.GetType() == EWeaponType::Missile) - xb14_ = 0.f; - xb14_ -= lowHealth; - xb24_ = 0.33f; - x430_damageColor = zeus::CColor(0.5f, 0.f, 0.f); - if (xb10_ <= 0.f) { - xa32_29_ = false; - dontKnockback = true; - xa32_28_shotAt = true; - xb14_ = x568_data.x38_; - } - } - } else if (xa31_27_) { - x430_damageColor = zeus::CColor(0.5f, 0.f, 0.f); - if (xb18_ > 0.f) { - xb18_ -= lowHealth; - if (xb18_ <= 0.f) { - xa31_26_ = true; - dontKnockback = true; - xb18_ = 0.f; - xcbc_ = 0.6667 * x568_data.x40_; - } else if (xb18_ < xcbc_) { - x450_bodyController->GetCommandMgr().DeliverCmd( - CBCKnockBackCmd(GetTransform().basis[1], pas::ESeverity::Six)); - xcbc_ -= (0.333f * x568_data.x3c_); - } - } - } else { - xb1c_ -= lowHealth; - if (xb1c_ <= 0.f) { - x401_30_pendingDeath = true; - mgr.GetPlayer().SetIsOverrideRadarRadius(false); - xb1c_ = 0.f; - } else if (xb1c_ < xcbc_) { - dontKnockback = true; - x450_bodyController->GetCommandMgr().DeliverCmd( - CBCKnockBackCmd(GetTransform().basis[1], pas::ESeverity::Six)); - xcbc_ -= (0.333f * x568_data.x40_); - } + xb1c_ -= lowHealth; + if (xb1c_ <= 0.f) { + x401_30_pendingDeath = true; + mgr.GetPlayer().SetIsOverrideRadarRadius(false); + xb1c_ = 0.f; + } else if (xb1c_ < xcbc_) { + dontKnockback = true; + x450_bodyController->GetCommandMgr().DeliverCmd( + CBCKnockBackCmd(GetTransform().basis[1], pas::ESeverity::Six)); + xcbc_ -= (0.333f * x568_data.x40_); } } } } + HealthInfo(mgr)->SetHP(xb1c_ + xb10_ + xb18_); if (!dontKnockback) { @@ -546,29 +534,27 @@ void CRidley::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateMan } case EScriptObjectMessage::InvulnDamage: { /* This code never executes, should have a `TCastTo` followed by `GetLastTouchedObject` */ - if (TCastToConstPtr colAct = mgr.GetObjectById(uid)) { - if (TCastToConstPtr proj = mgr.GetObjectById(colAct->GetLastTouchedObject())) { - TUniqueId tmpId = kInvalidUniqueId; - bool doDamage = false; - if (xc64_aiStage == 3) { - if (!xa32_29_ && xa31_27_) { - tmpId = x98a_breastPlateId; - doDamage = true; - } else { - tmpId = x988_headId; - doDamage = true; - } - } else if (xc64_aiStage == 2 && !xa31_31_) { + if (TCastToConstPtr proj = mgr.GetObjectById(uid)) { + TUniqueId tmpId = kInvalidUniqueId; + bool doDamage = false; + if (xc64_aiStage == 3) { + if (!xa32_29_ && xa31_27_) { tmpId = x98a_breastPlateId; doDamage = true; + } else { + tmpId = x988_headId; + doDamage = true; } + } else if (xc64_aiStage == 2 && !xa31_31_) { + tmpId = x98a_breastPlateId; + doDamage = true; + } - if (doDamage) { - CDamageInfo info = proj->GetDamageInfo(); - info.SetRadius(0.f); - mgr.ApplyDamage(uid, tmpId, proj->GetOwnerId(), info, - CMaterialFilter::MakeIncludeExclude({EMaterialTypes::Solid}, {}), {}); - } + if (doDamage) { + CDamageInfo info = proj->GetDamageInfo(); + info.SetRadius(0.f); + mgr.ApplyDamage(uid, tmpId, proj->GetOwnerId(), info, + CMaterialFilter::MakeIncludeExclude({EMaterialTypes::Solid}, {}), {}); } } break; @@ -597,8 +583,9 @@ void CRidley::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateMan } void CRidley::Think(float dt, CStateManager& mgr) { - if (!GetActive()) + if (!GetActive()) { return; + } sub802560d0(dt); CPatterned::Think(dt, mgr); @@ -612,6 +599,7 @@ void CRidley::Think(float dt, CStateManager& mgr) { sub80256624(dt, mgr); xb2c_.Update(dt); } + void CRidley::PreRender(CStateManager& mgr, const zeus::CFrustum& frustum) { CPatterned::PreRender(mgr, frustum); xb2c_.PreRender(mgr, *GetModelData()->GetAnimationData(), x34_transform, GetModelData()->GetScale(), @@ -625,10 +613,11 @@ void CRidley::PreRender(CStateManager& mgr, const zeus::CFrustum& frustum) { CPlayerState::EPlayerVisor r28 = mgr.GetPlayerState()->GetActiveVisor(mgr); bool atLastMat = GetModelData()->GetNumMaterialSets() == (matSet + 1); - if (r28 == CPlayerState::EPlayerVisor::Thermal && atLastMat) + if (r28 == CPlayerState::EPlayerVisor::Thermal && atLastMat) { xb4_drawFlags.x2_flags |= 0x40; - else + } else { xb4_drawFlags.x2_flags &= 0x40; + } xb4_drawFlags.x1_matSetIdx = matSet; if (xa33_27_) { @@ -653,7 +642,7 @@ void CRidley::Render(CStateManager& mgr) { if (xb24_ > 0.f) { multiplyColor = zeus::CColor::lerp(zeus::skWhite, x430_damageColor, xb24_ / 0.33f); } - g_Renderer->SetWorldLightMultiplyColor(multiplyColor); + g_Renderer->SetGXRegister1Color(multiplyColor); const zeus::CTransform xf = GetLctrTransform(xa30_breastPlateSegId); @@ -682,24 +671,28 @@ void CRidley::AddToRenderer(const zeus::CFrustum& frustum, CStateManager& mgr) { g_Renderer->AddParticleGen(*xce0_); } } + void CRidley::DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node, EUserEventType type, float dt) { switch (type) { case EUserEventType::Projectile: { - if (xc64_aiStage != 2) + if (xc64_aiStage != 2) { return; + } if (!xc14_.Token().IsLoaded()) { xc14_.Token().GetObj(); return; } - if (!mgr.CanCreateProjectile(GetUniqueId(), EWeaponType::AI, 9)) + if (!mgr.CanCreateProjectile(GetUniqueId(), EWeaponType::AI, 9)) { return; + } + zeus::CTransform xf = GetLctrTransform(xa30_breastPlateSegId) * zeus::CTransform::RotateX(zeus::degToRad(-90.f)); xf = xf * zeus::CTransform::RotateY( std::atan2(mgr.GetActiveRandom()->Range(-1.f, 1.f), mgr.GetActiveRandom()->Range(-1.f, 1.f))); xf.origin = xf * zeus::CVector3f(0.f, 1.f, 1.f); - CEnergyProjectile* proj = + auto* proj = new CEnergyProjectile(true, xc14_.Token(), EWeaponType::AI, xf, EMaterialTypes::Character, xc14_.GetDamage(), mgr.AllocateUniqueId(), GetAreaIdAlways(), GetUniqueId(), mgr.GetPlayer().GetUniqueId(), EProjectileAttrib::None, false, zeus::skOne3f, {}, -1, false); @@ -714,14 +707,15 @@ void CRidley::DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node, EUs break; } - if (!mgr.CanCreateProjectile(GetUniqueId(), EWeaponType::AI, 6)) + if (!mgr.CanCreateProjectile(GetUniqueId(), EWeaponType::AI, 8)) { break; + } zeus::CVector3f vec = zeus::CVector3f(mgr.GetActiveRandom()->Range(-1.f, 1.f), 1.f, mgr.GetActiveRandom()->Range(-1.f, 1.f)); vec = GetLctrTransform(xa30_breastPlateSegId) * vec; - CEnergyProjectile* proj = new CEnergyProjectile( + auto* proj = new CEnergyProjectile( true, xc3c_.Token(), EWeaponType::AI, zeus::lookAt(vec + mgr.GetPlayer().GetTranslation(), vec), EMaterialTypes::Character, xc3c_.GetDamage(), mgr.AllocateUniqueId(), GetAreaIdAlways(), GetUniqueId(), mgr.GetPlayer().GetUniqueId(), EProjectileAttrib::None, false, zeus::skOne3f, {}, -1, false); @@ -736,16 +730,18 @@ void CRidley::DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node, EUs case EUserEventType::DamageOn: { if (xc64_aiStage == 3) { sub8025784c(mgr); - } else if (xc64_aiStage == 2) + } else if (xc64_aiStage == 2) { xa33_28_ = false; + } break; } case EUserEventType::DamageOff: { if (xc64_aiStage == 3) { sub80257650(mgr); - } else if (xc64_aiStage == 2 && !xa33_31_) + } else if (xc64_aiStage == 2 && !xa33_31_) { xa33_28_ = true; + } break; } @@ -760,18 +756,21 @@ void CRidley::DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node, EUs return; } case EUserEventType::ScreenShake: { - if ((mgr.GetPlayer().GetTranslation() - GetTranslation()).magnitude() >= x568_data.x388_) + if ((mgr.GetPlayer().GetTranslation() - GetTranslation()).magnitude() >= x568_data.x388_) { break; + } mgr.ApplyDamage(GetUniqueId(), mgr.GetPlayer().GetUniqueId(), GetUniqueId(), x568_data.x298_, CMaterialFilter::MakeIncludeExclude({EMaterialTypes::Solid}, {}), {}); break; } case EUserEventType::BeginAction: { - if (xa32_25_ && !xa31_29_) + if (xa32_25_ && !xa31_29_) { FirePlasma(mgr); + } - if (!xa31_31_ || !xa32_26_) + if (!xa31_31_ || !xa32_26_) { break; + } xbf0_ = xa84_.basis[0]; zeus::CVector3f ourPos = GetTranslation(); @@ -780,12 +779,13 @@ void CRidley::DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node, EUs } xbfc_ = xbf0_; xbe4_ = xa84_.origin - xabc_ * xbf0_; - xbe4_ *= zeus::CVector3f((mgr.GetPlayer().GetTranslation() - xa84_.origin).dot(xa84_.basis[1])); + xbe4_ += (mgr.GetPlayer().GetTranslation() - xa84_.origin).dot(xa84_.frontVector()) * xa84_.frontVector(); break; } case EUserEventType::EndAction: { - if (xa31_29_) + if (xa31_29_) { ResetPlasmaProjectile(mgr, false); + } break; } case EUserEventType::IkLock: { @@ -805,8 +805,9 @@ void CRidley::DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node, EUs break; } case EUserEventType::SoundPlay: { - if (xa32_25_) + if (xa32_25_) { break; + } xcac_ = CSfxManager::AddEmitter({GetTranslation(), {}, 1000.f, 0.1f, 1, x568_data.x294_, 127, 63, false, 127}, true, -1, false, kInvalidAreaId); @@ -871,7 +872,7 @@ void CRidley::FirePlasma(urde::CStateManager& mgr) { false, EProjectileAttrib::KeepInCinematic)); } - if (CPlasmaProjectile* proj = static_cast(mgr.ObjectById(xb64_plasmaProjectile))) { + if (auto* proj = static_cast(mgr.ObjectById(xb64_plasmaProjectile))) { proj->Fire(GetLctrTransform(xb91_mouthSegId), mgr, false); if (!xca8_) { xca8_ = CSfxManager::AddEmitter({GetTranslation(), {}, 1000.f, 0.1f, 1, x568_data.xa8_, 127, 63, false, 127}, @@ -914,8 +915,9 @@ void CRidley::sub802560d0(float dt) { } else if (xaec_.isMagnitudeSafe()) { const float mag = xaec_.magnitude(); float magScale = 0.2f; - if (xaf8_.magSquared() == 0.f) + if (xaf8_.magSquared() == 0.f) { magScale *= 3.f; + } xaec_ = -((zeus::clamp(0.f, dt * (magScale * mag), 0.5f) * mag) - mag) * ((1.f / mag) * xaec_); ApplyImpulseWR(GetMass() * xaec_, {}); } @@ -928,18 +930,19 @@ void CRidley::sub802563a8(float dt) { zeus::CVector3f posDiff = GetTranslation() - xa84_.origin; float mag = posDiff.magnitude(); posDiff *= zeus::CVector3f(1.f / mag); - if (xab4_ + -6.f * zeus::clamp(-1.f, posDiff.dot(xa84_.basis[1]), 0.f) < mag) - if (GetVelocity().dot(posDiff) > 0.f) - Stop(); + if (xab4_ + -6.f * zeus::clamp(-1.f, posDiff.dot(xa84_.basis[1]), 0.f) < mag && GetVelocity().dot(posDiff) > 0.f) { + Stop(); + } MoveToInOneFrameWR(GetTranslation() - posDiff, dt); } } void CRidley::sub80256b14(float dt, CStateManager& mgr) { - if (CPlasmaProjectile* proj = static_cast(mgr.ObjectById(xb64_plasmaProjectile))) { - if (!proj->GetActive()) + if (auto* proj = static_cast(mgr.ObjectById(xb64_plasmaProjectile))) { + if (!proj->GetActive()) { return; + } zeus::CTransform mouthXf = GetLctrTransform(xb91_mouthSegId); if (xc64_aiStage == 3) { @@ -1015,28 +1018,26 @@ void CRidley::Patrol(CStateManager& mgr, EStateMsg msg, float arg) { xa32_27_ = false; xa33_26_ = true; } + void CRidley::Dead(CStateManager& mgr, EStateMsg msg, float arg) { if (msg != EStateMsg::Activate) return; mgr.SetBossParams(kInvalidUniqueId, 0.f, 0); } + void CRidley::Generate(CStateManager& mgr, EStateMsg msg, float arg) { if (msg != EStateMsg::Activate) return; xa34_26_ = false; - zeus::CVector3f vec; - vec.x() = 0.f; - vec.y() = xabc_; - vec.z() = xac0_ - xadc_; - SetTranslation(xa84_ * vec); + SetTranslation(xa84_ * zeus::CVector3f{0.f, xabc_, xac0_ - xadc_}); x450_bodyController->GetCommandMgr().DeliverCmd(CBodyStateCmd(EBodyStateCmd::NextState)); } void CRidley::Attack(CStateManager& mgr, EStateMsg msg, float arg) { if (msg == EStateMsg::Activate) { - xbe4_ = (GetTranslation() + zeus::skUp) - (8.f * GetTransform().basis[0]); - xbfc_ = xbf0_ = GetTransform().basis[0]; + xbe4_ = (GetTranslation() + zeus::skUp) - (8.f * GetTransform().rightVector()); + xbfc_ = xbf0_ = GetTransform().rightVector(); xc08_ = xc0c_ = 0.f; xc10_ = 240.f; x32c_animState = EAnimState::Ready; @@ -1112,7 +1113,7 @@ void CRidley::LoopedAttack(CStateManager& mgr, EStateMsg msg, float arg) { xbe4_ += (90.f * arg) * xbf0_; } - if (xa32_24_ && xcac_ != 0) { + if (xa32_24_ && xcac_) { CSfxManager::UpdateEmitter(xca8_, GetTranslation(), {}, 127); } if (x450_bodyController->GetBodyStateInfo().GetCurrentStateId() == pas::EAnimationState::Step) @@ -1122,17 +1123,21 @@ void CRidley::LoopedAttack(CStateManager& mgr, EStateMsg msg, float arg) { zeus::CVector3f local_54 = xbc4_ - GetTranslation(); float mag = local_54.magnitude(); if (mag <= 2.f || local_54.dot(xbc4_ - x2ec_reflectedDestPos) <= 0.f) { - pas::EStepDirection dir = pas::EStepDirection::Right; - if (xa32_31_) + auto dir = pas::EStepDirection::Right; + if (xa32_31_) { dir = pas::EStepDirection::Left; - if (xcc0_ == 3) - dir = pas::EStepDirection::Up; - else if (xcc0_ == 2) - dir = pas::EStepDirection::Forward; + } - pas::EStepType type = pas::EStepType::Normal; - if (xa33_24_) + if (xcc0_ == 3) { + dir = pas::EStepDirection::Up; + } else if (xcc0_ == 2) { + dir = pas::EStepDirection::Forward; + } + + auto type = pas::EStepType::Normal; + if (xa33_24_) { type = pas::EStepType::BreakDodge; + } x450_bodyController->GetCommandMgr().DeliverCmd(CBCStepCmd(dir, type)); xa31_30_ = true; } else { @@ -1147,7 +1152,7 @@ void CRidley::LoopedAttack(CStateManager& mgr, EStateMsg msg, float arg) { } else if (msg == EStateMsg::Deactivate) { x450_bodyController->SetLocomotionType(pas::ELocomotionType::Relaxed); if (xa32_25_) { - ResetPlasmaProjectile(mgr, 1); + ResetPlasmaProjectile(mgr, true); } if (xa32_24_) { @@ -1206,7 +1211,7 @@ void CRidley::JumpBack(CStateManager& mgr, EStateMsg msg, float arg) { xc78_ = 0.f; } else if (msg == EStateMsg::Update) { - TryCommand(mgr, pas::EAnimationState::Generate, &CPatterned::TryGenerate, 4); + TryCommand(mgr, pas::EAnimationState::Generate, &CPatterned::TryGenerateNoXf, 4); if (x32c_animState == EAnimState::Repeat) { x450_bodyController->SetLocomotionType(pas::ELocomotionType::Relaxed); @@ -1242,9 +1247,11 @@ void CRidley::DoubleSnap(CStateManager& mgr, EStateMsg msg, float arg) { } else if (msg == EStateMsg::Deactivate) { x32c_animState = EAnimState::NotReady; x402_28_isMakingBigStrike = false; + x504_damageDur = 0.f; xc8c_ = GetContactDamage(); } } + void CRidley::CoverAttack(CStateManager& mgr, EStateMsg msg, float arg) { if (msg == EStateMsg::Activate) { x32c_animState = EAnimState::Ready; @@ -1277,6 +1284,7 @@ void CRidley::Crouch(urde::CStateManager& mgr, urde::EStateMsg msg, float arg) { x450_bodyController->GetCommandMgr().DeliverCmd(CBCLocomotionCmd(zeus::skZero3f, faceDir, 1.f)); } } + void CRidley::FadeOut(CStateManager& mgr, EStateMsg msg, float arg) { if (msg == EStateMsg::Activate) { x32c_animState = EAnimState::Ready; @@ -1288,12 +1296,13 @@ void CRidley::FadeOut(CStateManager& mgr, EStateMsg msg, float arg) { xb68_.SetDamage(x568_data.x3fc_); } else if (msg == EStateMsg::Update) { - TryCommand(mgr, pas::EAnimationState::KnockBack, &CPatterned::TryKnockBack, 5); + TryCommand(mgr, pas::EAnimationState::KnockBack, &CPatterned::TryKnockBack_Front, 5); } else if (msg == EStateMsg::Deactivate) { x32c_animState = EAnimState::NotReady; xcbc_ = 0.6667f * x568_data.x3c_; } } + void CRidley::Taunt(CStateManager& mgr, EStateMsg msg, float arg) { if (msg == EStateMsg::Activate) { x32c_animState = EAnimState::Ready; @@ -1304,6 +1313,7 @@ void CRidley::Taunt(CStateManager& mgr, EStateMsg msg, float arg) { x32c_animState = EAnimState::NotReady; } } + void CRidley::Flee(CStateManager& mgr, EStateMsg msg, float arg) { if (msg == EStateMsg::Activate) { zeus::CVector3f destPos = @@ -1315,6 +1325,7 @@ void CRidley::Flee(CStateManager& mgr, EStateMsg msg, float arg) { x450_bodyController->FaceDirection((x2e0_destPos - GetTranslation()).normalized(), arg); } } + void CRidley::Lurk(urde::CStateManager& mgr, urde::EStateMsg msg, float arg) { if (msg == EStateMsg::Activate) { if (!xa33_25_) { @@ -1347,6 +1358,7 @@ void CRidley::Lurk(urde::CStateManager& mgr, urde::EStateMsg msg, float arg) { FacePlayer(10.f * arg, mgr); } } + void CRidley::ProjectileAttack(CStateManager& mgr, EStateMsg msg, float arg) { if (msg == EStateMsg::Activate) { x32c_animState = EAnimState::Ready; @@ -1361,24 +1373,26 @@ void CRidley::ProjectileAttack(CStateManager& mgr, EStateMsg msg, float arg) { xa33_31_ = false; } } + void CRidley::Flinch(CStateManager& mgr, EStateMsg msg, float arg) { if (msg == EStateMsg::Activate) { sub80257744(mgr); x32c_animState = EAnimState::Ready; } else if (msg == EStateMsg::Update) { - TryCommand(mgr, pas::EAnimationState::KnockBack, &CPatterned::TryKnockBack, 3); + TryCommand(mgr, pas::EAnimationState::KnockBack, &CPatterned::TryKnockBack_Front, 3); } else if (msg == EStateMsg::Deactivate) { x32c_animState = EAnimState::NotReady; sub80257650(mgr); xa32_28_shotAt = false; } } + void CRidley::Hurled(CStateManager& mgr, EStateMsg msg, float arg) { if (msg != EStateMsg::Activate) return; sub80257650(mgr); - x450_bodyController->GetCommandMgr().DeliverCmd(CBCKnockBackCmd(GetTransform().basis[1], pas::ESeverity::Four)); + x450_bodyController->GetCommandMgr().DeliverCmd(CBCKnockBackCmd(GetTransform().frontVector(), pas::ESeverity::Four)); } void CRidley::TelegraphAttack(CStateManager& mgr, EStateMsg msg, float arg) { @@ -1396,17 +1410,20 @@ void CRidley::TelegraphAttack(CStateManager& mgr, EStateMsg msg, float arg) { xa32_25_ = false; } } + void CRidley::Jump(CStateManager& mgr, EStateMsg msg, float arg) { if (msg == EStateMsg::Activate) { x32c_animState = EAnimState::Ready; xc88_ = (mgr.GetPlayer().GetTranslation() - GetTranslation()).magnitude() <= xae4_ ? 4 : 5; x402_28_isMakingBigStrike = x568_data.x3ac_ > 0.f; + x504_damageDur = x568_data.x3ac_; xc8c_ = x568_data.x390_; sub80256580(); } else if (msg == EStateMsg::Update) { TryCommand(mgr, pas::EAnimationState::MeleeAttack, &CPatterned::TryMeleeAttack, xc88_); - if (x330_stateMachineState.GetTime() < 1.75f) + if (x330_stateMachineState.GetTime() < 1.75f) { FacePlayer(arg, mgr); + } } else if (msg == EStateMsg::Deactivate) { AddMaterial(EMaterialTypes::Orbit, EMaterialTypes::Target, mgr); x402_28_isMakingBigStrike = false; @@ -1416,24 +1433,27 @@ void CRidley::Jump(CStateManager& mgr, EStateMsg msg, float arg) { xa34_25_ = false; } } + void CRidley::Explode(CStateManager& mgr, EStateMsg msg, float arg) { if (msg == EStateMsg::Activate) { xa32_27_ = false; x32c_animState = EAnimState::Ready; } else if (msg == EStateMsg::Update) { - TryCommand(mgr, pas::EAnimationState::KnockBack, &CPatterned::TryKnockBack, 2); + TryCommand(mgr, pas::EAnimationState::KnockBack, &CPatterned::TryKnockBack_Front, 2); } else if (msg == EStateMsg::Deactivate) { x32c_animState = EAnimState::NotReady; } } + void CRidley::Dodge(CStateManager& mgr, EStateMsg msg, float arg) { if (msg == EStateMsg::Activate) { + const zeus::CVector3f vec = zeus::CVector3f{GetTranslation().toVec2f() - xa84_.origin.toVec2f()}.normalized(); + float dist = zeus::clamp(0.f, 2.f * vec.dot(xa84_.rightVector()) + 1.f, 1.f); + xc84_ = 2; - float dist = zeus::clamp( - 0.f, zeus::CVector3f(GetTranslation().toVec2f() - xa84_.origin.toVec2f()).normalized().dot(xa84_.basis[0]), - 1.f); - if (dist < mgr.GetActiveRandom()->Float()) + if (dist < mgr.GetActiveRandom()->Float()) { xc84_ = 3; + } x32c_animState = EAnimState::Ready; } else if (msg == EStateMsg::Update) { TryCommand(mgr, pas::EAnimationState::Step, &CPatterned::TryDodge, xc84_); @@ -1442,31 +1462,34 @@ void CRidley::Dodge(CStateManager& mgr, EStateMsg msg, float arg) { zeus::CVector3f someVec(((xa84_.origin.x() + xabc_) * vec.x()) - GetTranslation().x(), ((xa84_.origin.y() + xabc_) * vec.y()) - GetTranslation().y(), ((xa84_.origin.z() + xac0_) - GetTranslation().z())); - if (someVec.magnitude() > 1.f) + if (someVec.magnitude() > 1.f) { someVec.normalize(); + } sub80255fe8(10.f, arg, someVec); - } else { - x450_bodyController->FaceDirection((xa84_.origin - GetTranslation()).normalized(), arg); } + + x450_bodyController->FaceDirection((xa84_.origin - GetTranslation()).normalized(), arg); } else if (msg == EStateMsg::Deactivate) { x32c_animState = EAnimState::NotReady; } } + void CRidley::Retreat(CStateManager& mgr, EStateMsg msg, float arg) { if (msg == EStateMsg::Activate) { x32c_animState = EAnimState::Ready; } else if (msg == EStateMsg::Update) { - TryCommand(mgr, pas::EAnimationState::Step, &CPatterned::TryDodge, 5); + TryCommand(mgr, pas::EAnimationState::Step, &CPatterned::TryDodge, 5); // Down } else { x32c_animState = EAnimState::NotReady; } } + void CRidley::Approach(CStateManager& mgr, EStateMsg msg, float arg) { if (msg == EStateMsg::Activate) { zeus::CVector3f direction = (GetTranslation() - xa84_.origin).normalized(); - zeus::CVector3f destPos(xa84_.origin.x() + xab4_ * direction.x(), xa84_.origin.y() + xab4_ * direction.y(), - (xae8_ + xa84_.origin.z()) - 1.f); + zeus::CVector3f destPos = xa84_.origin.toVec2f() + xab4_ * direction.toVec2f(); + destPos.z() = (xae8_ + xa84_.origin.z()) - 1.f; SetDestPos(destPos); xa33_26_ = false; if (xc64_aiStage == 3 && !xa34_24_) { @@ -1506,6 +1529,7 @@ void CRidley::SpecialAttack(CStateManager& mgr, EStateMsg msg, float arg) { x32c_animState = EAnimState::NotReady; } } + void CRidley::Land(CStateManager& mgr, EStateMsg msg, float arg) { if (msg == EStateMsg::Activate) { zeus::CVector3f diff = zeus::CVector3f(mgr.GetPlayer().GetTranslation().x() - xa84_.origin.x(), @@ -1525,7 +1549,7 @@ void CRidley::Land(CStateManager& mgr, EStateMsg msg, float arg) { x402_28_isMakingBigStrike = x568_data.x38c_ > 0.f; x504_damageDur = x568_data.x38c_; } else if (msg == EStateMsg::Update) { - TryCommand(mgr, pas::EAnimationState::MeleeAttack, &CPatterned::TryMeleeAttack, 8); + TryCommand(mgr, pas::EAnimationState::MeleeAttack, &CPatterned::TryMeleeAttack_TargetPos, 8); if (x32c_animState == EAnimState::Repeat) { x450_bodyController->SetLocomotionType(pas::ELocomotionType::Combat); @@ -1546,6 +1570,7 @@ void CRidley::Land(CStateManager& mgr, EStateMsg msg, float arg) { } } bool CRidley::Attacked(CStateManager& mgr, float arg) { return xa31_24_ && xa31_26_; } + bool CRidley::TooClose(CStateManager& mgr, float arg) { if (xb0c_ == 4) return true; @@ -1561,24 +1586,32 @@ bool CRidley::TooClose(CStateManager& mgr, float arg) { return false; } -bool CRidley::InRange(CStateManager& mgr, float arg) { - float mag = (GetTranslation() - x2e0_destPos).magnitude(); - return mag < 2.f; -} + +bool CRidley::InRange(CStateManager& mgr, float arg) { return (GetTranslation() - x2e0_destPos).magnitude() < 2.f; } + bool CRidley::ShouldAttack(CStateManager& mgr, float arg) { return (xc64_aiStage == 3 && xb0c_ == 2) || (xc64_aiStage == 2 && xb04_ == 0); } + bool CRidley::ShouldDoubleSnap(CStateManager& mgr, float arg) { return xa33_30_; } + bool CRidley::ShouldTurn(CStateManager& mgr, float arg) { return xb04_ == 5; } + bool CRidley::HitSomething(CStateManager& mgr, float arg) { return xa32_27_ || xc64_aiStage == 3; } + bool CRidley::AttackOver(CStateManager& mgr, float arg) { return xcc4_ == 0; } + bool CRidley::ShouldTaunt(CStateManager& mgr, float arg) { return (xc64_aiStage == 3 && xb0c_ == 1) || (xc64_aiStage == 2 && xb04_ == 4); } bool CRidley::ShouldFire(CStateManager& mgr, float arg) { return xc64_aiStage == 2 && xb04_ == 2; } + bool CRidley::ShouldDodge(CStateManager& mgr, float arg) { return xb04_ == 3; } + bool CRidley::ShouldRetreat(CStateManager& mgr, float arg) { return xa34_26_; } + bool CRidley::ShouldCrouch(CStateManager& mgr, float arg) { return xb04_ == 1; } + bool CRidley::ShouldMove(urde::CStateManager& mgr, float arg) { if (xb0c_ == 5) { xa34_25_ = true; @@ -1596,12 +1629,16 @@ bool CRidley::ShouldMove(urde::CStateManager& mgr, float arg) { return false; } bool CRidley::ShotAt(CStateManager& mgr, float arg) { return xa32_28_shotAt; } + bool CRidley::SetAIStage(CStateManager& mgr, float arg) { xc64_aiStage = arg; return true; } + bool CRidley::AIStage(CStateManager& mgr, float arg) { return xc64_aiStage >= arg; } + bool CRidley::ShouldStrafe(CStateManager& mgr, float arg) { return xa33_29_doStrafe; } + bool CRidley::IsDizzy(CStateManager& mgr, float arg) { if (xb0c_ == 3) return true; @@ -1616,13 +1653,15 @@ bool CRidley::IsDizzy(CStateManager& mgr, float arg) { return false; } + void CRidley::sub80255fe8(float f1, float f2, const zeus::CVector3f& vec) { - xaf8_ = (0.2f * (f1 * f1)) * vec; + xaf8_ = (f1 * (0.2f * f1)) * vec; xaec_ += f2 * xaf8_; if (xaec_.magnitude() > f1) { xaec_ = f1 * xaec_.normalized(); } } + void CRidley::sub80255e5c(CStateManager& mgr) { zeus::CVector3f posDiff = mgr.GetPlayer().GetTranslation() - GetTranslation(); if (posDiff.magnitude() < 8.f) { @@ -1631,6 +1670,7 @@ void CRidley::sub80255e5c(CStateManager& mgr) { mgr.GetPlayer().ApplyImpulseWR(impulse, {}); } } + void CRidley::FacePlayer(float arg, CStateManager& mgr) { x450_bodyController->FaceDirection((mgr.GetPlayer().GetTranslation() - GetTranslation()).normalized(), arg); } @@ -1682,5 +1722,4 @@ void CRidley::sub80253710(urde::CStateManager& mgr) { if (frontMag > 0.f && diffMag < x2fc_minAttackRange && xb08_ != 4) xb0c_ = 4; } -} // namespace MP1 -} // namespace urde +} // namespace urde::MP1 diff --git a/Runtime/MP1/World/CRidley.hpp b/Runtime/MP1/World/CRidley.hpp index cbe30f81c..396ba8e44 100644 --- a/Runtime/MP1/World/CRidley.hpp +++ b/Runtime/MP1/World/CRidley.hpp @@ -105,11 +105,11 @@ class CRidley : public CPatterned { float xab4_ = 20.f; float xab8_ = 12.f; float xabc_ = 40.f; - float xac0_ = 10; + float xac0_ = 10.f; zeus::CAABox xac4_ = zeus::skInvertedBox; float xadc_; float xae0_; - u32 xae4_; + float xae4_; float xae8_; zeus::CVector3f xaec_; zeus::CVector3f xaf8_; @@ -195,7 +195,8 @@ class CRidley : public CPatterned { void sub80253710(CStateManager& mgr); bool sub80253960() { - return (GetTranslation() + (1.75f * GetTransform().basis[1]) - xa84_.origin).magnitude() < 1.75f * (xab4_ + xabc_); + const float mag = ((GetTranslation() + ((0.5f * xae4_) * GetTransform().frontVector())) - xa84_.origin).magnitude(); + return mag < 0.5f * (xab4_ + xabc_); } public: diff --git a/Runtime/MP1/World/CSeedling.cpp b/Runtime/MP1/World/CSeedling.cpp index 7574d3400..8b7fabc16 100644 --- a/Runtime/MP1/World/CSeedling.cpp +++ b/Runtime/MP1/World/CSeedling.cpp @@ -196,7 +196,7 @@ void CSeedling::Generate(CStateManager& mgr, EStateMsg msg, float) { if (msg == EStateMsg::Activate) x32c_animState = EAnimState::Ready; else if (msg == EStateMsg::Update) - TryCommand(mgr, pas::EAnimationState::Generate, &CPatterned::TryGenerateNoXf, 0); + TryCommand(mgr, pas::EAnimationState::Generate, &CPatterned::TryGenerate, 0); } bool CSeedling::ShouldAttack(CStateManager& mgr, float) { diff --git a/Runtime/Particle/CParticleSwoosh.cpp b/Runtime/Particle/CParticleSwoosh.cpp index 916969f7a..0d69faac4 100644 --- a/Runtime/Particle/CParticleSwoosh.cpp +++ b/Runtime/Particle/CParticleSwoosh.cpp @@ -57,7 +57,7 @@ CParticleSwoosh::CParticleSwoosh(const TToken& desc, int len 0.f, 0.f, zeus::skClear); } - SetOrientation(zeus::CTransform()); + CParticleSwoosh::SetOrientation(zeus::CTransform()); x16c_p0.resize(x1b8_SIDE); x17c_p1.resize(x1b8_SIDE); diff --git a/Runtime/RetroTypes.hpp b/Runtime/RetroTypes.hpp index 6c0c70628..a7bf1d1f0 100644 --- a/Runtime/RetroTypes.hpp +++ b/Runtime/RetroTypes.hpp @@ -66,7 +66,7 @@ struct SObjectTag { }; struct TEditorId { - u32 id = u32(-1); + u32 id = UINT32_MAX; constexpr TEditorId() noexcept = default; constexpr TEditorId(u32 idin) noexcept : id(idin) {} @@ -83,7 +83,7 @@ struct TEditorId { #define kInvalidEditorId TEditorId() struct TUniqueId { - u16 id = u16(-1); + u16 id = UINT16_MAX; constexpr TUniqueId() noexcept = default; constexpr TUniqueId(u16 value, u16 version) noexcept : id(value | (version << 10)) {} diff --git a/Runtime/Weapon/CAuxWeapon.cpp b/Runtime/Weapon/CAuxWeapon.cpp index a4fb86357..2955c8da8 100644 --- a/Runtime/Weapon/CAuxWeapon.cpp +++ b/Runtime/Weapon/CAuxWeapon.cpp @@ -24,7 +24,7 @@ constexpr CCameraShakeData skHardShake{ }; constexpr std::array skComboNames{ - "SuperMissile", "IceCombo", "WaveBuster", "FlameThrower", "SuperMissile", + "SuperMissile"sv, "IceCombo"sv, "WaveBuster"sv, "FlameThrower"sv, "SuperMissile"sv, }; constexpr std::array skSoundId{ @@ -326,16 +326,20 @@ void CAuxWeapon::RenderMuzzleFx() const { } TUniqueId CAuxWeapon::HasTarget(const CStateManager& mgr) const { - if (x74_firingBeamId == CPlayerState::EBeamId::Wave) - if (auto* wb = static_cast(mgr.GetObjectById(x70_waveBusterId))) + if (x74_firingBeamId == CPlayerState::EBeamId::Wave) { + if (const auto* wb = static_cast(mgr.GetObjectById(x70_waveBusterId))) { return wb->GetHomingTargetId(); + } + } return kInvalidUniqueId; } void CAuxWeapon::SetNewTarget(TUniqueId targetId, CStateManager& mgr) { - if (x74_firingBeamId == CPlayerState::EBeamId::Wave) - if (auto* wb = static_cast(mgr.ObjectById(x70_waveBusterId))) + if (x74_firingBeamId == CPlayerState::EBeamId::Wave) { + if (auto* wb = static_cast(mgr.ObjectById(x70_waveBusterId))) { wb->SetNewTarget(targetId); + } + } } } // namespace urde diff --git a/Runtime/Weapon/CBeamProjectile.cpp b/Runtime/Weapon/CBeamProjectile.cpp index 96c2bb52a..fb19a22d4 100644 --- a/Runtime/Weapon/CBeamProjectile.cpp +++ b/Runtime/Weapon/CBeamProjectile.cpp @@ -75,7 +75,7 @@ void CBeamProjectile::UpdateFx(const zeus::CTransform& xf, float dt, CStateManag mgr.BuildNearList(nearList, x36c_, CMaterialFilter::MakeExclude({EMaterialTypes::ProjectilePassthrough}), nullptr); TUniqueId collideId = kInvalidUniqueId; CRayCastResult res = RayCollisionCheckWithWorld(collideId, x298_previousPos, beamEnd, x300_intBeamLength, nearList, mgr); - if (TCastToPtr act = mgr.ObjectById(collideId)) { + if (TCastToConstPtr(mgr.ObjectById(collideId))) { SetCollisionResultData(EDamageType::Actor, res, collideId); if (x464_25_enableTouchDamage) ApplyDamageToActors(mgr, CDamageInfo(x12c_curDamageInfo, dt)); diff --git a/Runtime/Weapon/CFlameThrower.cpp b/Runtime/Weapon/CFlameThrower.cpp index 013ce919a..3024e6dab 100644 --- a/Runtime/Weapon/CFlameThrower.cpp +++ b/Runtime/Weapon/CFlameThrower.cpp @@ -38,7 +38,7 @@ void CFlameThrower::Accept(IVisitor& visitor) { visitor.Visit(this); } void CFlameThrower::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) { if (msg == EScriptObjectMessage::Registered) { - xe6_27_thermalVisorFlags |= 2; + xe6_27_thermalVisorFlags = 2; mgr.AddWeaponId(xec_ownerId, xf0_weaponType); } else if (msg == EScriptObjectMessage::Deleted) { mgr.RemoveWeaponId(xec_ownerId, xf0_weaponType); @@ -227,12 +227,12 @@ void CFlameThrower::Think(float dt, CStateManager& mgr) { if (r28 && x34c_flameWarp.IsProcessed()) { x318_flameBounds = x34c_flameWarp.CalculateBounds(); TUniqueId id = kInvalidUniqueId; - CRayCastResult res = DoCollisionCheck(id, x318_flameBounds, mgr); - if (TCastToPtr act = mgr.ObjectById(id)) { + const CRayCastResult res = DoCollisionCheck(id, x318_flameBounds, mgr); + if (TCastToConstPtr(mgr.ObjectById(id))) { ApplyDamageToActor(mgr, id, dt); } else if (res.IsValid()) { - CMaterialFilter useFilter = xf8_filter; - CDamageInfo useDInfo = CDamageInfo(x12c_curDamageInfo, dt); + const CMaterialFilter useFilter = xf8_filter; + const CDamageInfo useDInfo = CDamageInfo(x12c_curDamageInfo, dt); mgr.ApplyDamageToWorld(xec_ownerId, *this, res.GetPoint(), useDInfo, useFilter); } } diff --git a/Runtime/Weapon/CPlayerGun.cpp b/Runtime/Weapon/CPlayerGun.cpp index d533f78f8..dae5cd08c 100644 --- a/Runtime/Weapon/CPlayerGun.cpp +++ b/Runtime/Weapon/CPlayerGun.cpp @@ -1515,11 +1515,12 @@ void CPlayerGun::UpdateWeaponFire(float dt, const CPlayerState& playerState, CSt if (!x835_31_actorAttached) { x835_28_bombReady = true; if (x53a_powerBomb != kInvalidUniqueId && !mgr.CanCreateProjectile(x538_playerId, EWeaponType::PowerBomb, 1)) { - auto* pb = static_cast(mgr.GetObjectById(x53a_powerBomb)); - if (pb && pb->GetCurTime() <= 4.25f) + const auto* pb = static_cast(mgr.GetObjectById(x53a_powerBomb)); + if (pb && pb->GetCurTime() <= 4.25f) { x835_28_bombReady = false; - else + } else { x53a_powerBomb = kInvalidUniqueId; + } } if (((pressedStates & 0x1) != 0 || x32c_chargePhase != EChargePhase::NotCharging) && mgr.GetPlayerState()->HasPowerUp(CPlayerState::EItemType::MorphBallBombs)) { @@ -2088,9 +2089,9 @@ void CPlayerGun::PreRender(const CStateManager& mgr, const zeus::CFrustum& frust } void CPlayerGun::RenderEnergyDrainEffects(const CStateManager& mgr) const { - if (TCastToConstPtr player = mgr.GetObjectById(x538_playerId)) { + if (const TCastToConstPtr player = mgr.GetObjectById(x538_playerId)) { for (const auto& source : player->GetEnergyDrain().GetEnergyDrainSources()) { - if (auto* metroid = CPatterned::CastTo(mgr.GetObjectById(source.GetEnergyDrainSourceId()))) { + if (const auto* metroid = CPatterned::CastTo(mgr.GetObjectById(source.GetEnergyDrainSourceId()))) { metroid->RenderHitGunEffect(); return; } diff --git a/Runtime/Weapon/CWaveBuster.cpp b/Runtime/Weapon/CWaveBuster.cpp index ec69c99e4..50a59e5b4 100644 --- a/Runtime/Weapon/CWaveBuster.cpp +++ b/Runtime/Weapon/CWaveBuster.cpp @@ -3,6 +3,8 @@ #include "Runtime/CSimplePool.hpp" #include "Runtime/GameGlobalObjects.hpp" +#include "TCastTo.hpp" // Generated file, do not modify include path + namespace urde { CWaveBuster::CWaveBuster(const TToken& desc, EWeaponType type, const zeus::CTransform& xf, @@ -32,6 +34,33 @@ void CWaveBuster::ResetBeam(bool deactivate) {} void CWaveBuster::SetNewTarget(TUniqueId id) {} +void CWaveBuster::Accept(IVisitor& visitor) { visitor.Visit(this); } + +void CWaveBuster::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId senderId, CStateManager& mgr) { + if (msg == EScriptObjectMessage::Deleted) { + DeleteProjectileLight(mgr); + } else if (msg == EScriptObjectMessage::Registered) { + if (x390_busterLightGen != nullptr && x390_busterLightGen->SystemHasLight()) { + const CLight light = x390_busterLightGen->GetLight(); + CreateProjectileLight("WaveBuster_Light", light, mgr); + } + + // Thermal hot + xe6_27_thermalVisorFlags = 2; + + x318_ = x2e8_originalXf.origin; + x324_ = x34_transform.origin; + x330_ = x34_transform.origin; + } + + CGameProjectile::AcceptScriptMsg(msg, senderId, mgr); +} + +void CWaveBuster::AddToRenderer([[maybe_unused]] const zeus::CFrustum& frustum, CStateManager& mgr) { + const auto bounds = GetSortingBounds(mgr); + EnsureRendered(mgr, x2e8_originalXf.origin, bounds); +} + std::optional CWaveBuster::GetTouchBounds() const { if (x3d0_28_) { return std::nullopt; diff --git a/Runtime/Weapon/CWaveBuster.hpp b/Runtime/Weapon/CWaveBuster.hpp index 46594922e..95245c8cc 100644 --- a/Runtime/Weapon/CWaveBuster.hpp +++ b/Runtime/Weapon/CWaveBuster.hpp @@ -55,6 +55,9 @@ public: void ResetBeam(bool deactivate); void SetNewTarget(TUniqueId id); + void Accept(IVisitor& visitor) override; + void AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId senderId, CStateManager& mgr) override; + void AddToRenderer(const zeus::CFrustum& frustum, CStateManager& mgr) override; std::optional GetTouchBounds() const override; }; diff --git a/Runtime/World/CAi.cpp b/Runtime/World/CAi.cpp index 8b051bbe3..56e77bd79 100644 --- a/Runtime/World/CAi.cpp +++ b/Runtime/World/CAi.cpp @@ -78,9 +78,9 @@ void CAi::FluidFXThink(EFluidState state, CScriptWater& water, urde::CStateManag water.GetFluidPlane().AddRipple(GetMass(), GetUniqueId(), center, GetVelocity(), water, mgr, pos); } -CAiStateFunc CAi::GetStateFunc(const char* func) { return m_FuncMap->GetStateFunc(func); } +CAiStateFunc CAi::GetStateFunc(std::string_view func) { return m_FuncMap->GetStateFunc(func); } -CAiTriggerFunc CAi::GetTrigerFunc(const char* func) { return m_FuncMap->GetTriggerFunc(func); } +CAiTriggerFunc CAi::GetTriggerFunc(std::string_view func) { return m_FuncMap->GetTriggerFunc(func); } const CStateMachine* CAi::GetStateMachine() const { return x2c8_stateMachine.GetObj(); } void CAi::CreateFuncLookup(CAiFuncMap* funcMap) { m_FuncMap = funcMap; } diff --git a/Runtime/World/CAi.hpp b/Runtime/World/CAi.hpp index 6ba2be1ca..de4dd8569 100644 --- a/Runtime/World/CAi.hpp +++ b/Runtime/World/CAi.hpp @@ -36,8 +36,8 @@ public: const CMaterialList& list, CAssetId fsm, const CActorParameters&, float f1, float f2); static void CreateFuncLookup(CAiFuncMap* funcMap); - static CAiStateFunc GetStateFunc(const char* func); - static CAiTriggerFunc GetTrigerFunc(const char* func); + static CAiStateFunc GetStateFunc(std::string_view func); + static CAiTriggerFunc GetTriggerFunc(std::string_view func); const CStateMachine* GetStateMachine() const; diff --git a/Runtime/World/CAiFuncMap.cpp b/Runtime/World/CAiFuncMap.cpp index dddab5958..9518d5d10 100644 --- a/Runtime/World/CAiFuncMap.cpp +++ b/Runtime/World/CAiFuncMap.cpp @@ -6,6 +6,7 @@ namespace urde { CAiFuncMap::CAiFuncMap() { /* Ai States */ + x0_stateFuncs.reserve(55); x0_stateFuncs.emplace("Patrol", &CAi::Patrol); x0_stateFuncs.emplace("FollowPattern", &CAi::FollowPattern); x0_stateFuncs.emplace("Dead", &CAi::Dead); @@ -63,6 +64,7 @@ CAiFuncMap::CAiFuncMap() { x0_stateFuncs.emplace("PodAttack", &CAi::PodAttack); /* Ai Triggers */ + x10_triggerFuncs.reserve(68); x10_triggerFuncs.emplace("InAttackPosition", &CAi::InAttackPosition); x10_triggerFuncs.emplace("Leash", &CAi::Leash); x10_triggerFuncs.emplace("OffLine", &CAi::OffLine); @@ -135,7 +137,7 @@ CAiFuncMap::CAiFuncMap() { CAi::CreateFuncLookup(this); } -CAiStateFunc CAiFuncMap::GetStateFunc(const char* func) const { +CAiStateFunc CAiFuncMap::GetStateFunc(std::string_view func) const { const auto iter = x0_stateFuncs.find(func); if (iter == x0_stateFuncs.cend()) { @@ -145,7 +147,7 @@ CAiStateFunc CAiFuncMap::GetStateFunc(const char* func) const { return iter->second; } -CAiTriggerFunc CAiFuncMap::GetTriggerFunc(const char* func) const { +CAiTriggerFunc CAiFuncMap::GetTriggerFunc(std::string_view func) const { const auto iter = x10_triggerFuncs.find(func); if (iter == x10_triggerFuncs.cend()) { diff --git a/Runtime/World/CAiFuncMap.hpp b/Runtime/World/CAiFuncMap.hpp index 06d81a624..5c77d53eb 100644 --- a/Runtime/World/CAiFuncMap.hpp +++ b/Runtime/World/CAiFuncMap.hpp @@ -1,6 +1,6 @@ #pragma once -#include +#include #include namespace urde { @@ -13,12 +13,12 @@ using CAiStateFunc = void (CAi::*)(CStateManager&, EStateMsg, float); using CAiTriggerFunc = bool (CAi::*)(CStateManager&, float); class CAiFuncMap { - std::unordered_map x0_stateFuncs; - std::unordered_map x10_triggerFuncs; + std::unordered_map x0_stateFuncs; + std::unordered_map x10_triggerFuncs; public: CAiFuncMap(); - CAiStateFunc GetStateFunc(const char*) const; - CAiTriggerFunc GetTriggerFunc(const char*) const; + CAiStateFunc GetStateFunc(std::string_view func) const; + CAiTriggerFunc GetTriggerFunc(std::string_view func) const; }; } // namespace urde diff --git a/Runtime/World/CEnvFxManager.cpp b/Runtime/World/CEnvFxManager.cpp index 9e6b9bba1..d6e43acb9 100644 --- a/Runtime/World/CEnvFxManager.cpp +++ b/Runtime/World/CEnvFxManager.cpp @@ -178,10 +178,10 @@ void CEnvFxManager::CalculateSnowForces(const CVectorFixed8_8& zVec, void CEnvFxManager::BuildBlockObjectList(rstl::reserved_vector& list, CStateManager& mgr) { for (CEntity* ent : mgr.GetAllObjectList()) { - TCastToPtr trig = ent; + const TCastToConstPtr trig = ent; if (trig && True(trig->GetTriggerFlags() & ETriggerFlags::BlockEnvironmentalEffects)) { list.push_back(ent->GetUniqueId()); - } else if (TCastToPtr water = ent) { + } else if (TCastToConstPtr(ent)) { list.push_back(ent->GetUniqueId()); } } diff --git a/Runtime/World/CFishCloud.cpp b/Runtime/World/CFishCloud.cpp index d8633693d..125a2f7ad 100644 --- a/Runtime/World/CFishCloud.cpp +++ b/Runtime/World/CFishCloud.cpp @@ -643,7 +643,7 @@ std::optional CFishCloud::GetTouchBounds() const { void CFishCloud::CreateBoidDeathParticle(CBoid& b) const { auto it = x21c_deathParticleCounts.begin(); - for (auto& p : x1f8_particleGens) { + for (const auto& p : x1f8_particleGens) { p->SetParticleEmission(true); p->SetTranslation(b.x0_pos); p->ForceParticleCreation(*it); diff --git a/Runtime/World/CFluidPlaneCPU.cpp b/Runtime/World/CFluidPlaneCPU.cpp index c412bf1ea..5eba767cd 100644 --- a/Runtime/World/CFluidPlaneCPU.cpp +++ b/Runtime/World/CFluidPlaneCPU.cpp @@ -10,9 +10,9 @@ #include "TCastTo.hpp" // Generated file, do not modify include path -#define kTableSize 2048 - namespace urde { +constexpr u32 kTableSize = 2048; + CFluidPlaneCPU::CTurbulence::CTurbulence(float speed, float distance, float freqMax, float freqMin, float phaseMax, float phaseMin, float amplitudeMax, float amplitudeMin) : x0_speed(speed) @@ -25,27 +25,29 @@ CFluidPlaneCPU::CTurbulence::CTurbulence(float speed, float distance, float freq , x1c_amplitudeMin(amplitudeMin) , x2c_ooTurbSpeed(1.f / x0_speed) , x30_ooTurbDistance(1.f / x4_distance) { - if (x18_amplitudeMax != 0.f || x1c_amplitudeMin != 0.f) { - x24_tableCount = kTableSize; - x28_heightSelPitch = x24_tableCount; - x20_table.reset(new float[x24_tableCount]); - float anglePitch = 2.f * M_PIF / x28_heightSelPitch; - float freqConstant = 0.5f * (x8_freqMax + xc_freqMin); - float freqLinear = 0.5f * (x8_freqMax - xc_freqMin); - float phaseConstant = 0.5f * (x10_phaseMax + x14_phaseMin); - float phaseLinear = 0.5f * (x10_phaseMax - x14_phaseMin); - float amplitudeConstant = 0.5f * (x18_amplitudeMax + x1c_amplitudeMin); - float amplitudeLinear = 0.5f * (x18_amplitudeMax - x1c_amplitudeMin); - - float curAng = 0.f; - for (int i = 0; i < x24_tableCount; ++i, curAng += anglePitch) { - float angCos = std::cos(curAng); - x20_table[i] = (amplitudeLinear * angCos + amplitudeConstant) * - std::sin((freqLinear * angCos + freqConstant) * curAng + (phaseLinear * angCos + phaseConstant)); - } - - x34_hasTurbulence = true; + if (x18_amplitudeMax == 0.f && x1c_amplitudeMin == 0.f) { + return; } + + x24_tableCount = kTableSize; + x28_heightSelPitch = x24_tableCount; + x20_table.reset(new float[x24_tableCount]); + const float anglePitch = 2.f * M_PIF / x28_heightSelPitch; + const float freqConstant = 0.5f * (x8_freqMax + xc_freqMin); + const float freqLinear = 0.5f * (x8_freqMax - xc_freqMin); + const float phaseConstant = 0.5f * (x10_phaseMax + x14_phaseMin); + const float phaseLinear = 0.5f * (x10_phaseMax - x14_phaseMin); + const float amplitudeConstant = 0.5f * (x18_amplitudeMax + x1c_amplitudeMin); + const float amplitudeLinear = 0.5f * (x18_amplitudeMax - x1c_amplitudeMin); + + float curAng = 0.f; + for (size_t i = 0; i < x24_tableCount; ++i, curAng += anglePitch) { + const float angCos = std::cos(curAng); + x20_table[i] = (amplitudeLinear * angCos + amplitudeConstant) * + std::sin((freqLinear * angCos + freqConstant) * curAng + (phaseLinear * angCos + phaseConstant)); + } + + x34_hasTurbulence = true; } CFluidPlaneCPU::CFluidPlaneCPU(CAssetId texPattern1, CAssetId texPattern2, CAssetId texColor, CAssetId bumpMap, diff --git a/Runtime/World/CGameArea.cpp b/Runtime/World/CGameArea.cpp index c1853ca56..b89262d73 100644 --- a/Runtime/World/CGameArea.cpp +++ b/Runtime/World/CGameArea.cpp @@ -1199,7 +1199,7 @@ void CGameArea::SetAreaAttributes(const CScriptAreaAttributes* areaAttributes) { bool CGameArea::CAreaObjectList::IsQualified(const CEntity& ent) const { return (ent.GetAreaIdAlways() == x200c_areaIdx); } void CGameArea::WarmupShaders(const SObjectTag& mreaTag) { // Calling this version of the constructor performs warmup implicitly - CGameArea area(mreaTag.id); + [[maybe_unused]] CGameArea area(mreaTag.id); } } // namespace urde diff --git a/Runtime/World/CMorphBall.cpp b/Runtime/World/CMorphBall.cpp index c3a70df38..0ccde6073 100644 --- a/Runtime/World/CMorphBall.cpp +++ b/Runtime/World/CMorphBall.cpp @@ -286,12 +286,13 @@ CMorphBall::CMorphBall(CPlayer& player, float radius) } void CMorphBall::LoadAnimationTokens(std::string_view ancsName) { - TToken dgrp = g_SimplePool->GetObj(std::string(ancsName).append("_DGRP")); + const TToken dgrp = g_SimplePool->GetObj(std::string(ancsName).append("_DGRP")); x1958_animationTokens.clear(); x1958_animationTokens.reserve(dgrp->GetObjectTagVector().size()); for (const SObjectTag& tag : dgrp->GetObjectTagVector()) { - if (tag.type == FOURCC('CMDL') || tag.type == FOURCC('CSKR') || tag.type == FOURCC('TXTR')) + if (tag.type == FOURCC('CMDL') || tag.type == FOURCC('CSKR') || tag.type == FOURCC('TXTR')) { continue; + } x1958_animationTokens.push_back(g_SimplePool->GetObj(tag)); x1958_animationTokens.back().Lock(); } @@ -324,10 +325,11 @@ void CMorphBall::InitializeWakeEffects() { std::unique_ptr CMorphBall::GetMorphBallModel(const char* name, float radius) { const SObjectTag* tag = g_ResFactory->GetResourceIdByName(name); - if (tag->type == FOURCC('CMDL')) + if (tag->type == FOURCC('CMDL')) { return std::make_unique(CStaticRes(tag->id, zeus::CVector3f(radius * 2.f))); - else + } else { return std::make_unique(CAnimRes(tag->id, 0, zeus::CVector3f(radius * 2.f), 0, false)); + } } void CMorphBall::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId sender, CStateManager& mgr) { @@ -335,9 +337,9 @@ void CMorphBall::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId sender, CSt case EScriptObjectMessage::Registered: if (x19d0_ballInnerGlowGen && x19d0_ballInnerGlowGen->SystemHasLight()) { x1c10_ballInnerGlowLight = mgr.AllocateUniqueId(); - CGameLight* l = new CGameLight(x1c10_ballInnerGlowLight, kInvalidAreaId, false, "BallLight", GetBallToWorld(), - x0_player.GetUniqueId(), x19d0_ballInnerGlowGen->GetLight(), - u32(x1988_ballInnerGlow.GetObjectTag()->id.Value()), 0, 0.f); + auto* l = new CGameLight(x1c10_ballInnerGlowLight, kInvalidAreaId, false, "BallLight", GetBallToWorld(), + x0_player.GetUniqueId(), x19d0_ballInnerGlowGen->GetLight(), + u32(x1988_ballInnerGlow.GetObjectTag()->id.Value()), 0, 0.f); mgr.AddObject(l); } break; @@ -350,8 +352,9 @@ void CMorphBall::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId sender, CSt } void CMorphBall::DrawBallShadow(const CStateManager& mgr) { - if (!x1e50_shadow) + if (!x1e50_shadow) { return; + } float alpha = 1.f; switch (x0_player.x2f8_morphBallState) { @@ -359,14 +362,16 @@ void CMorphBall::DrawBallShadow(const CStateManager& mgr) { return; case CPlayer::EPlayerMorphBallState::Unmorphing: alpha = 0.f; - if (x0_player.x578_morphDuration != 0.f) + if (x0_player.x578_morphDuration != 0.f) { alpha = zeus::clamp(0.f, x0_player.x574_morphTime / x0_player.x578_morphDuration, 1.f); + } alpha = 1.f - alpha; break; case CPlayer::EPlayerMorphBallState::Morphing: alpha = 0.f; - if (x0_player.x578_morphDuration != 0.f) + if (x0_player.x578_morphDuration != 0.f) { alpha = zeus::clamp(0.f, x0_player.x574_morphTime / x0_player.x578_morphDuration, 1.f); + } break; default: break; @@ -379,22 +384,25 @@ void CMorphBall::DeleteBallShadow() { x1e50_shadow.reset(); } void CMorphBall::CreateBallShadow() { x1e50_shadow = std::make_unique(); } void CMorphBall::RenderToShadowTex(CStateManager& mgr) { - if (x1e50_shadow) { - zeus::CVector3f center = - x0_player.GetPrimitiveOffset() + x0_player.GetTranslation() + zeus::CVector3f(0.f, 0.f, xc_radius); - zeus::CAABox aabb(center - zeus::CVector3f(1.25f * xc_radius, 1.25f * xc_radius, 10.f), - center + zeus::CVector3f(1.25f * xc_radius, 1.25f * xc_radius, xc_radius)); - x1e50_shadow->RenderIdBuffer(aabb, mgr, x0_player); + if (!x1e50_shadow) { + return; } + + const zeus::CVector3f center = + x0_player.GetPrimitiveOffset() + x0_player.GetTranslation() + zeus::CVector3f(0.f, 0.f, xc_radius); + const zeus::CAABox aabb(center - zeus::CVector3f(1.25f * xc_radius, 1.25f * xc_radius, 10.f), + center + zeus::CVector3f(1.25f * xc_radius, 1.25f * xc_radius, xc_radius)); + x1e50_shadow->RenderIdBuffer(aabb, mgr, x0_player); } void CMorphBall::SelectMorphBallSounds(const CMaterialList& mat) { u16 rollSfx; if (x0_player.x9c5_30_selectFluidBallSound) { - if (x0_player.x82c_inLava) + if (x0_player.x82c_inLava) { rollSfx = 2186; - else + } else { rollSfx = 1481; + } } else { rollSfx = CPlayer::SfxIdFromMaterial(mat, skBallRollSfx.data(), skBallRollSfx.size(), 0xffff); } @@ -413,25 +421,27 @@ void CMorphBall::SelectMorphBallSounds(const CMaterialList& mat) { void CMorphBall::UpdateMorphBallSounds(float dt) { zeus::CVector3f velocity = x0_player.GetVelocity(); - if (x187c_spiderBallState != ESpiderBallState::Active) + if (x187c_spiderBallState != ESpiderBallState::Active) { velocity.z() = 0.f; + } switch (x0_player.GetPlayerMovementState()) { case CPlayer::EPlayerMovementState::OnGround: case CPlayer::EPlayerMovementState::FallingMorphed: { float vel = velocity.magnitude(); - if (x187c_spiderBallState == ESpiderBallState::Active) + if (x187c_spiderBallState == ESpiderBallState::Active) { vel += g_tweakBall->GetBallGravity() * dt * 4.f; + } if (vel > 0.8f) { if (!x1e2c_rollSfxHandle) { if (x1e34_rollSfx != 0xffff) { - x1e2c_rollSfxHandle = CSfxManager::AddEmitter(x1e34_rollSfx, x0_player.GetTranslation(), - zeus::skZero3f, true, true, 0x7f, kInvalidAreaId); + x1e2c_rollSfxHandle = CSfxManager::AddEmitter(x1e34_rollSfx, x0_player.GetTranslation(), zeus::skZero3f, true, + true, 0x7f, kInvalidAreaId); } x0_player.ApplySubmergedPitchBend(x1e2c_rollSfxHandle); } CSfxManager::PitchBend(x1e2c_rollSfxHandle, zeus::clamp(-1.f, vel * 0.122f - 0.831f, 1.f)); - float maxVol = zeus::clamp(0.f, 0.025f * vel + 0.5f, 1.f); + const float maxVol = zeus::clamp(0.f, 0.025f * vel + 0.5f, 1.f); CSfxManager::UpdateEmitter(x1e2c_rollSfxHandle, x0_player.GetTranslation(), zeus::skZero3f, maxVol); break; } @@ -447,8 +457,8 @@ void CMorphBall::UpdateMorphBallSounds(float dt) { if (x187c_spiderBallState == ESpiderBallState::Active) { if (!x1e30_spiderSfxHandle) { - x1e30_spiderSfxHandle = CSfxManager::AddEmitter(SFXsam_spider_lp, x0_player.GetTranslation(), - zeus::skZero3f, true, true, 0xc8, kInvalidAreaId); + x1e30_spiderSfxHandle = CSfxManager::AddEmitter(SFXsam_spider_lp, x0_player.GetTranslation(), zeus::skZero3f, + true, true, 0xc8, kInvalidAreaId); x0_player.ApplySubmergedPitchBend(x1e30_spiderSfxHandle); } CSfxManager::UpdateEmitter(x1e30_spiderSfxHandle, x0_player.GetTranslation(), zeus::skZero3f, 1.f); @@ -463,15 +473,17 @@ float CMorphBall::GetBallRadius() const { return g_tweakPlayer->GetPlayerBallHal float CMorphBall::GetBallTouchRadius() const { return g_tweakBall->GetBallTouchRadius(); } float CMorphBall::ForwardInput(const CFinalInput& input) const { - if (!IsMovementAllowed()) + if (!IsMovementAllowed()) { return 0.f; + } return ControlMapper::GetAnalogInput(ControlMapper::ECommands::Forward, input) - ControlMapper::GetAnalogInput(ControlMapper::ECommands::Backward, input); } float CMorphBall::BallTurnInput(const CFinalInput& input) const { - if (!IsMovementAllowed()) + if (!IsMovementAllowed()) { return 0.f; + } return ControlMapper::GetAnalogInput(ControlMapper::ECommands::TurnLeft, input) - ControlMapper::GetAnalogInput(ControlMapper::ECommands::TurnRight, input); } @@ -482,31 +494,37 @@ void CMorphBall::ComputeBallMovement(const CFinalInput& input, CStateManager& mg } bool CMorphBall::IsMovementAllowed() const { - if (!g_tweakPlayer->GetMoveDuringFreeLook() && (x0_player.x3dc_inFreeLook || x0_player.x3dd_lookButtonHeld)) + if (!g_tweakPlayer->GetMoveDuringFreeLook() && (x0_player.x3dc_inFreeLook || x0_player.x3dd_lookButtonHeld)) { return false; - if (x0_player.IsMorphBallTransitioning()) + } + if (x0_player.IsMorphBallTransitioning()) { return false; + } return x1e00_disableControlCooldown <= 0.f; } void CMorphBall::UpdateSpiderBall(const CFinalInput& input, CStateManager& mgr, float dt) { SetSpiderBallSwingingState(CheckForSwitchToSpiderBallSwinging(mgr)); - if (x18be_spiderBallSwinging) + if (x18be_spiderBallSwinging) { ApplySpiderBallSwingingForces(input, mgr, dt); - else + } else { ApplySpiderBallRollForces(input, mgr, dt); + } } void CMorphBall::ApplySpiderBallSwingingForces(const CFinalInput& input, CStateManager& mgr, float dt) { x18b4_linVelDamp = 0.04f; x18b8_angVelDamp = 0.99f; x1880_playerToSpiderNormal = x1890_spiderTrackPoint - x0_player.GetTranslation(); - float playerToSpiderDist = x1880_playerToSpiderNormal.magnitude(); + + const float playerToSpiderDist = x1880_playerToSpiderNormal.magnitude(); x1880_playerToSpiderNormal = x1880_playerToSpiderNormal * (-1.f / playerToSpiderDist); - float movement = GetSpiderBallControllerMovement(input); + + const float movement = GetSpiderBallControllerMovement(input); UpdateSpiderBallSwingControllerMovementTimer(movement, dt); - float swingMovement = movement * GetSpiderBallSwingControllerMovementScalar(); - float f29 = playerToSpiderDist * 110000.f / 3.7f; + + const float swingMovement = movement * GetSpiderBallSwingControllerMovementScalar(); + const float f29 = playerToSpiderDist * 110000.f / 3.7f; x0_player.ApplyForceWR( x1880_playerToSpiderNormal.cross(x18a8_spiderBetweenPoints).cross(x1880_playerToSpiderNormal).normalized() * f29 * swingMovement * 0.06f, @@ -514,12 +532,16 @@ void CMorphBall::ApplySpiderBallSwingingForces(const CFinalInput& input, CStateM x0_player.SetMomentumWR({0.f, 0.f, x0_player.GetMass() * g_tweakBall->GetBallGravity()}); x18fc_refPullVel = (1.f - x188c_spiderPullMovement) * 3.7f + 1.4f; x1900_playerToSpiderTrackDist = playerToSpiderDist; + zeus::CVector3f playerVel = x0_player.GetVelocity(); - float playerSpeed = playerVel.magnitude(); + const float playerSpeed = playerVel.magnitude(); playerVel -= x1880_playerToSpiderNormal * playerSpeed * x1880_playerToSpiderNormal.dot(playerVel.normalized()); + float maxPullVel = 0.04f; - if (x188c_spiderPullMovement == 1.f && std::fabs(x1880_playerToSpiderNormal.z()) > 0.8f) + if (x188c_spiderPullMovement == 1.f && std::fabs(x1880_playerToSpiderNormal.z()) > 0.8f) { maxPullVel = 0.3f; + } + playerVel += x1880_playerToSpiderNormal * zeus::clamp(-maxPullVel, x18fc_refPullVel - playerToSpiderDist, maxPullVel) / dt; x0_player.SetVelocityWR(playerVel); @@ -536,15 +558,18 @@ zeus::CVector3f CMorphBall::TransformSpiderBallForcesXZ(const zeus::CVector2f& f } void CMorphBall::ApplySpiderBallRollForces(const CFinalInput& input, CStateManager& mgr, float dt) { - zeus::CVector2f surfaceForces = CalculateSpiderBallAttractionSurfaceForces(input); + const zeus::CVector2f surfaceForces = CalculateSpiderBallAttractionSurfaceForces(input); zeus::CVector3f viewSurfaceForces = TransformSpiderBallForcesXZ(surfaceForces, mgr); - zeus::CTransform camXf = mgr.GetCameraManager()->GetCurrentCamera(mgr)->GetTransform(); - zeus::CVector3f spiderDirNorm = x189c_spiderInterpBetweenPoints.normalized(); - float upDot = std::fabs(spiderDirNorm.dot(camXf.basis[2])); - float foreDot = std::fabs(spiderDirNorm.dot(camXf.basis[1])); - if (x0_player.x9c4_29_spiderBallControlXY && upDot < 0.25f && foreDot > 0.25f) + const zeus::CTransform camXf = mgr.GetCameraManager()->GetCurrentCamera(mgr)->GetTransform(); + const zeus::CVector3f spiderDirNorm = x189c_spiderInterpBetweenPoints.normalized(); + const float upDot = std::fabs(spiderDirNorm.dot(camXf.basis[2])); + const float foreDot = std::fabs(spiderDirNorm.dot(camXf.basis[1])); + + if (x0_player.x9c4_29_spiderBallControlXY && upDot < 0.25f && foreDot > 0.25f) { viewSurfaceForces = TransformSpiderBallForcesXY(surfaceForces, mgr); - float forceMag = surfaceForces.magnitude(); + } + + const float forceMag = surfaceForces.magnitude(); zeus::CVector2f normSurfaceForces; float trackForceMag = x18c0_isSpiderSurface ? forceMag : viewSurfaceForces.dot(spiderDirNorm); bool forceApplied = true; @@ -555,10 +580,11 @@ void CMorphBall::ApplySpiderBallRollForces(const CFinalInput& input, CStateManag trackForceMag = x1914_spiderTrackForceMag >= 0.f ? forceMag : -forceMag; continueTrackForce = true; } else { - if (std::fabs(trackForceMag) > 0.05f) + if (std::fabs(trackForceMag) > 0.05f) { trackForceMag = trackForceMag >= 0.f ? forceMag : -forceMag; - else + } else { forceApplied = false; + } } } else { forceApplied = false; @@ -576,18 +602,20 @@ void CMorphBall::ApplySpiderBallRollForces(const CFinalInput& input, CStateManag } bool moving = true; - if (!forceApplied && x0_player.GetVelocity().magnitude() <= 6.5f) + if (!forceApplied && x0_player.GetVelocity().magnitude() <= 6.5f) { moving = false; + } zeus::CVector3f moveDelta; if (x18bd_touchingSpider && forceApplied) { - if (x18c0_isSpiderSurface) + if (x18c0_isSpiderSurface) { moveDelta = viewSurfaceForces * 0.1f; - else + } else { moveDelta = x18a8_spiderBetweenPoints.normalized() * 0.1f * (trackForceMag >= 0.f ? 1.f : -1.f); + } } - zeus::CVector3f ballPos = GetBallToWorld().origin + moveDelta; + const zeus::CVector3f ballPos = GetBallToWorld().origin + moveDelta; float distance = 0.f; if (moving || !x18bd_touchingSpider || x188c_spiderPullMovement != 1.f || x18bf_spiderSwingInAir) { if (FindClosestSpiderBallWaypoint(mgr, ballPos, x1890_spiderTrackPoint, x189c_spiderInterpBetweenPoints, @@ -604,8 +632,9 @@ void CMorphBall::ApplySpiderBallRollForces(const CFinalInput& input, CStateManag } if (x18bc_spiderNearby) { - if (distance < kSpiderBallCollisionRadius) + if (distance < kSpiderBallCollisionRadius) { x18bd_touchingSpider = true; + } if (x18bd_touchingSpider) { if (moving) { if (!x18c0_isSpiderSurface) { @@ -625,24 +654,26 @@ void CMorphBall::ApplySpiderBallRollForces(const CFinalInput& input, CStateManag finalForceMag = 0.f; ResetSpiderBallForces(); } - if (distance > 1.05f) + if (distance > 1.05f) { finalForceMag *= (1.05f - (distance - 1.05f)) / 1.05f; + } x0_player.ApplyForceWR(x18a8_spiderBetweenPoints.normalized() * 90000.f * finalForceMag, zeus::CAxisAngle()); } else { x18b4_linVelDamp = 0.3f; x18b8_angVelDamp = 0.2f; - float f31 = x18c4_spiderSurfaceTransform.basis[0].dot(viewSurfaceForces); - float f30 = x18c4_spiderSurfaceTransform.basis[2].dot(viewSurfaceForces); - zeus::CVector3f forceVec = + const float f31 = x18c4_spiderSurfaceTransform.basis[0].dot(viewSurfaceForces); + const float f30 = x18c4_spiderSurfaceTransform.basis[2].dot(viewSurfaceForces); + const zeus::CVector3f forceVec = (f31 * x18c4_spiderSurfaceTransform.basis[0] + f30 * x18c4_spiderSurfaceTransform.basis[2]) * 45000.f; x0_player.ApplyForceWR(forceVec, zeus::CAxisAngle()); if (forceVec.magSquared() > 0.f) { float angle = std::atan2(45000.f * f31, 45000.f * f30); - if (angle - x18f4_spiderSurfacePivotAngle > M_PIF / 2.f) + if (angle - x18f4_spiderSurfacePivotAngle > M_PIF / 2.f) { angle = angle - M_PIF; - else if (x18f4_spiderSurfacePivotAngle - angle > M_PIF / 2.f) + } else if (x18f4_spiderSurfacePivotAngle - angle > M_PIF / 2.f) { angle = angle + M_PIF; + } x18f8_spiderSurfacePivotTargetAngle = angle; } x18f4_spiderSurfacePivotAngle += std::copysign( @@ -664,8 +695,9 @@ void CMorphBall::ApplySpiderBallRollForces(const CFinalInput& input, CStateManag } zeus::CVector2f CMorphBall::CalculateSpiderBallAttractionSurfaceForces(const CFinalInput& input) const { - if (!IsMovementAllowed()) + if (!IsMovementAllowed()) { return zeus::CVector2f(); + } return {ControlMapper::GetAnalogInput(ControlMapper::ECommands::TurnRight, input) - ControlMapper::GetAnalogInput(ControlMapper::ECommands::TurnLeft, input), @@ -674,12 +706,13 @@ zeus::CVector2f CMorphBall::CalculateSpiderBallAttractionSurfaceForces(const CFi } bool CMorphBall::CheckForSwitchToSpiderBallSwinging(CStateManager& mgr) const { - if (!x18bd_touchingSpider) + if (!x18bd_touchingSpider) { return false; + } if (x188c_spiderPullMovement == 1.f) { if (x18be_spiderBallSwinging) { - zeus::CTransform ballToWorld = GetBallToWorld(); + const zeus::CTransform ballToWorld = GetBallToWorld(); zeus::CVector3f closestPoint, interpDeltaBetweenPoints, deltaBetweenPoints, normal; float distance = 0.f; bool isSurface; @@ -691,8 +724,9 @@ bool CMorphBall::CheckForSwitchToSpiderBallSwinging(CStateManager& mgr) const { return false; } - if (x18be_spiderBallSwinging) + if (x18be_spiderBallSwinging) { return true; + } return std::fabs(x1880_playerToSpiderNormal.z()) > 0.9f; } @@ -703,26 +737,30 @@ bool CMorphBall::FindClosestSpiderBallWaypoint(CStateManager& mgr, const zeus::C zeus::CVector3f& normal, bool& isSurface, zeus::CTransform& surfaceTransform) const { bool ret = false; - zeus::CAABox aabb(ballCenter - 2.1f, ballCenter + 2.1f); + const zeus::CAABox aabb(ballCenter - 2.1f, ballCenter + 2.1f); rstl::reserved_vector nearList; mgr.BuildNearList(nearList, aabb, CMaterialFilter::skPassEverything, nullptr); float minDist = 2.1f; - for (TUniqueId id : nearList) { - if (TCastToConstPtr surface = mgr.GetObjectById(id)) { - zeus::CUnitVector3f surfaceNorm(surface->GetTransform().basis[1]); - zeus::CPlane plane(surfaceNorm, surface->GetTranslation().dot(surfaceNorm)); + for (const TUniqueId id : nearList) { + if (const TCastToConstPtr surface = mgr.GetObjectById(id)) { + const zeus::CUnitVector3f surfaceNorm(surface->GetTransform().basis[1]); + const zeus::CPlane plane(surfaceNorm, surface->GetTranslation().dot(surfaceNorm)); zeus::CVector3f intersectPoint; + if (plane.rayPlaneIntersection(ballCenter + surfaceNorm * 2.1f, ballCenter - surfaceNorm * 2.1f, intersectPoint)) { - zeus::CVector3f halfScale = surface->GetScale() * 0.5f; + const zeus::CVector3f halfScale = surface->GetScale() * 0.5f; + zeus::CVector3f localPoint = zeus::CTransform::Scale(1.f / halfScale) * surface->GetTransform().inverse() * intersectPoint; localPoint.x() = zeus::clamp(-1.f, float(localPoint.x()), 1.f); localPoint.z() = zeus::clamp(-1.f, float(localPoint.z()), 1.f); - zeus::CVector3f worldPoint = surface->GetTransform() * zeus::CTransform::Scale(halfScale) * localPoint; - zeus::CVector3f finalDelta = worldPoint - ballCenter; - float finalMag = finalDelta.magnitude(); + + const zeus::CVector3f worldPoint = surface->GetTransform() * zeus::CTransform::Scale(halfScale) * localPoint; + const zeus::CVector3f finalDelta = worldPoint - ballCenter; + const float finalMag = finalDelta.magnitude(); + if (finalMag < minDist) { minDist = finalMag; closestPoint = worldPoint; @@ -736,8 +774,8 @@ bool CMorphBall::FindClosestSpiderBallWaypoint(CStateManager& mgr, const zeus::C } } - for (TUniqueId id : nearList) { - if (TCastToConstPtr wp = mgr.GetObjectById(id)) { + for (const TUniqueId id : nearList) { + if (const TCastToConstPtr wp = mgr.GetObjectById(id)) { const CScriptSpiderBallWaypoint* closestWp = nullptr; zeus::CVector3f worldPoint; zeus::CVector3f useDeltaBetweenPoints = deltaBetweenPoints; @@ -745,8 +783,8 @@ bool CMorphBall::FindClosestSpiderBallWaypoint(CStateManager& mgr, const zeus::C wp->GetClosestPointAlongWaypoints(mgr, ballCenter, 2.1f, closestWp, worldPoint, useDeltaBetweenPoints, 0.8f, useInterpDeltaBetweenPoints); if (closestWp) { - zeus::CVector3f ballToPoint = worldPoint - ballCenter; - float ballToPointMag = ballToPoint.magnitude(); + const zeus::CVector3f ballToPoint = worldPoint - ballCenter; + const float ballToPointMag = ballToPoint.magnitude(); if (ballToPointMag < minDist) { minDist = ballToPointMag; closestPoint = worldPoint; @@ -773,19 +811,23 @@ void CMorphBall::SetSpiderBallSwingingState(bool active) { } float CMorphBall::GetSpiderBallControllerMovement(const CFinalInput& input) const { - if (!IsMovementAllowed()) + if (!IsMovementAllowed()) { return 0.f; + } - float forward = ControlMapper::GetAnalogInput(ControlMapper::ECommands::Forward, input) - - ControlMapper::GetAnalogInput(ControlMapper::ECommands::Backward, input); - float turn = ControlMapper::GetAnalogInput(ControlMapper::ECommands::TurnRight, input) - - ControlMapper::GetAnalogInput(ControlMapper::ECommands::TurnLeft, input); - float angle = zeus::radToDeg(std::atan2(forward, turn)); - float hyp = std::sqrt(forward * forward + turn * turn); - if (angle > -35.f && angle < 125.f) + const float forward = ControlMapper::GetAnalogInput(ControlMapper::ECommands::Forward, input) - + ControlMapper::GetAnalogInput(ControlMapper::ECommands::Backward, input); + const float turn = ControlMapper::GetAnalogInput(ControlMapper::ECommands::TurnRight, input) - + ControlMapper::GetAnalogInput(ControlMapper::ECommands::TurnLeft, input); + const float angle = zeus::radToDeg(std::atan2(forward, turn)); + const float hyp = std::sqrt(forward * forward + turn * turn); + + if (angle > -35.f && angle < 125.f) { return hyp; - if (angle < -55.f || angle > 145.f) + } + if (angle < -55.f || angle > 145.f) { return -hyp; + } return 0.f; } @@ -808,18 +850,21 @@ void CMorphBall::UpdateSpiderBallSwingControllerMovementTimer(float movement, fl } float CMorphBall::GetSpiderBallSwingControllerMovementScalar() const { - if (x1908_swingControlTime < 1.2f) + if (x1908_swingControlTime < 1.2f) { return 1.f; + } return std::max(0.f, (2.4f - x1908_swingControlTime) / 1.2f); } void CMorphBall::CreateSpiderBallParticles(const zeus::CVector3f& ballPos, const zeus::CVector3f& trackPoint) { x19d4_spiderBallMagnetEffectGen->SetParticleEmission(true); + zeus::CVector3f ballToTrack = trackPoint - ballPos; - float ballToTrackMag = ballToTrack.magnitude(); - int subCount = int(ballToTrackMag / 0.2f + 1.f); - ballToTrack = ballToTrack * (1.f / float(subCount)); - int count = int(8.f * (ballToTrackMag / 2.1f)); + const float ballToTrackMag = ballToTrack.magnitude(); + const int subCount = static_cast(ballToTrackMag / 0.2f + 1.f); + ballToTrack = ballToTrack * (1.f / static_cast(subCount)); + const int count = static_cast(8.f * (ballToTrackMag / 2.1f)); + for (int i = count; i >= 0; --i) { zeus::CVector3f translation = ballPos; for (int j = 0; j < subCount; ++j) { @@ -828,6 +873,7 @@ void CMorphBall::CreateSpiderBallParticles(const zeus::CVector3f& ballPos, const translation += ballToTrack; } } + x19d4_spiderBallMagnetEffectGen->SetParticleEmission(false); } @@ -841,8 +887,9 @@ void CMorphBall::ResetSpiderBallForces() { void CMorphBall::ComputeMarioMovement(const CFinalInput& input, CStateManager& mgr, float dt) { x1c_controlForce = zeus::skZero3f; x10_boostControlForce = zeus::skZero3f; - if (!IsMovementAllowed()) + if (!IsMovementAllowed()) { return; + } x188c_spiderPullMovement = (ControlMapper::GetAnalogInput(ControlMapper::ECommands::SpiderBall, input) >= 0.5f / 100.f) ? 1.f : 0.f; @@ -865,48 +912,59 @@ void CMorphBall::ComputeMarioMovement(const CFinalInput& input, CStateManager& m } if (x187c_spiderBallState != ESpiderBallState::Active) { - float forward = ForwardInput(input); - float turn = -BallTurnInput(input); - float maxSpeed = ComputeMaxSpeed(); - float curSpeed = x0_player.GetVelocity().magnitude(); - zeus::CTransform controlXf = zeus::lookAt(zeus::skZero3f, x0_player.x54c_controlDirFlat); - zeus::CVector3f controlFrameVel = controlXf.transposeRotate(x0_player.GetVelocity()); + const float forward = ForwardInput(input); + const float turn = -BallTurnInput(input); + const float maxSpeed = ComputeMaxSpeed(); + const float curSpeed = x0_player.GetVelocity().magnitude(); + const zeus::CTransform controlXf = zeus::lookAt(zeus::skZero3f, x0_player.x54c_controlDirFlat); + const zeus::CVector3f controlFrameVel = controlXf.transposeRotate(x0_player.GetVelocity()); float fwdAcc = 0.f; float turnAcc = 0.f; + if (std::fabs(turn) > 0.1f) { - float controlTurn = turn * maxSpeed; - float controlTurnDelta = controlTurn - controlFrameVel.x(); - float accFactor = zeus::clamp(0.f, std::fabs(controlTurnDelta) / maxSpeed, 1.f); + const float controlTurn = turn * maxSpeed; + const float controlTurnDelta = controlTurn - controlFrameVel.x(); + const float accFactor = zeus::clamp(0.f, std::fabs(controlTurnDelta) / maxSpeed, 1.f); float maxAcc; - if ((controlFrameVel.x() > 0.f ? 1.f : -1.f) != (controlTurn > 0.f ? 1.f : -1.f) && curSpeed > 0.8f * maxSpeed) + + if ((controlFrameVel.x() > 0.f ? 1.f : -1.f) != (controlTurn > 0.f ? 1.f : -1.f) && curSpeed > 0.8f * maxSpeed) { maxAcc = g_tweakBall->GetBallForwardBrakingAcceleration(int(x0_player.GetSurfaceRestraint())); - else + } else { maxAcc = g_tweakBall->GetMaxBallTranslationAcceleration(int(x0_player.GetSurfaceRestraint())); - if (controlTurnDelta < 0.f) + } + + if (controlTurnDelta < 0.f) { turnAcc = -maxAcc * accFactor; - else + } else { turnAcc = maxAcc * accFactor; + } } + if (std::fabs(forward) > 0.1f) { - float controlFwd = forward * maxSpeed; - float controlFwdDelta = controlFwd - controlFrameVel.y(); - float accFactor = zeus::clamp(0.f, std::fabs(controlFwdDelta) / maxSpeed, 1.f); + const float controlFwd = forward * maxSpeed; + const float controlFwdDelta = controlFwd - controlFrameVel.y(); + const float accFactor = zeus::clamp(0.f, std::fabs(controlFwdDelta) / maxSpeed, 1.f); float maxAcc; - if ((controlFrameVel.y() > 0.f ? 1.f : -1.f) != (controlFwd > 0.f ? 1.f : -1.f) && curSpeed > 0.8f * maxSpeed) + + if ((controlFrameVel.y() > 0.f ? 1.f : -1.f) != (controlFwd > 0.f ? 1.f : -1.f) && curSpeed > 0.8f * maxSpeed) { maxAcc = g_tweakBall->GetBallForwardBrakingAcceleration(int(x0_player.GetSurfaceRestraint())); - else + } else { maxAcc = g_tweakBall->GetMaxBallTranslationAcceleration(int(x0_player.GetSurfaceRestraint())); - if (controlFwdDelta < 0.f) + } + + if (controlFwdDelta < 0.f) { fwdAcc = -maxAcc * accFactor; - else + } else { fwdAcc = maxAcc * accFactor; + } } if (fwdAcc != 0.f || turnAcc != 0.f || x1de4_24_inBoost || GetIsInHalfPipeMode()) { zeus::CVector3f controlForce = controlXf.rotate({0.f, fwdAcc, 0.f}) + controlXf.rotate({turnAcc, 0.f, 0.f}); x1c_controlForce = controlForce; - if (x1de4_24_inBoost && !GetIsInHalfPipeMode()) + if (x1de4_24_inBoost && !GetIsInHalfPipeMode()) { controlForce = x1924_surfaceToWorld.rotate({x1924_surfaceToWorld.transposeRotate(controlForce).x(), 0.f, 0.f}); + } if (GetIsInHalfPipeMode() && controlForce.magnitude() > FLT_EPSILON) { if (GetIsInHalfPipeModeInAir() && curSpeed <= 15.f && @@ -922,24 +980,25 @@ void CMorphBall::ComputeMarioMovement(const CFinalInput& input, CStateManager& m controlForceSurfaceLocal.x() *= 0.6f; controlForceSurfaceLocal.y() *= (x1de4_24_inBoost ? 0.f : 0.35f) * 1.4f; controlForce = x1924_surfaceToWorld.rotate(controlForceSurfaceLocal); - if (maxSpeed > 95.f) + if (maxSpeed > 95.f) { x0_player.SetVelocityWR(x0_player.GetVelocity() * 0.99f); + } } } if (GetTouchedHalfPipeRecently()) { - float hpNormComp = x1e08_prevHalfPipeNormal.dot(x1e14_halfPipeNormal); + const float hpNormComp = x1e08_prevHalfPipeNormal.dot(x1e14_halfPipeNormal); if (hpNormComp < 0.99f && hpNormComp > 0.5f) { - zeus::CVector3f hpRampAxis = x1e08_prevHalfPipeNormal.cross(x1e14_halfPipeNormal).normalized(); + const zeus::CVector3f hpRampAxis = x1e08_prevHalfPipeNormal.cross(x1e14_halfPipeNormal).normalized(); zeus::CVector3f newVel = x0_player.GetVelocity(); newVel -= hpRampAxis * hpRampAxis.dot(x0_player.GetVelocity()) * 0.15f; x0_player.SetVelocityWR(newVel); } } - float speedThres = 0.75f * maxSpeed; + const float speedThres = 0.75f * maxSpeed; if (curSpeed >= speedThres) { - float dot = controlForce.dot(x0_player.GetVelocity().normalized()); + const float dot = controlForce.dot(x0_player.GetVelocity().normalized()); if (dot > 0.f) { controlForce -= x0_player.GetVelocity().normalized() * zeus::clamp(0.f, (curSpeed - speedThres) / (maxSpeed - speedThres), 1.f) * dot; @@ -966,10 +1025,11 @@ zeus::CTransform CMorphBall::CalculateSurfaceToWorld(const zeus::CVector3f& trac const zeus::CVector3f& trackPoint, const zeus::CVector3f& ballDir) const { if (ballDir.canBeNormalized()) { - zeus::CVector3f forward = ballDir.normalized(); - zeus::CVector3f right = ballDir.cross(trackNormal); - if (right.canBeNormalized()) + const zeus::CVector3f forward = ballDir.normalized(); + const zeus::CVector3f right = ballDir.cross(trackNormal); + if (right.canBeNormalized()) { return zeus::CTransform(right, forward, right.cross(forward).normalized(), trackPoint); + } } return zeus::CTransform(); } @@ -992,12 +1052,14 @@ void CMorphBall::UpdateBallDynamics(CStateManager& mgr, float dt) { x1e00_disableControlCooldown = std::max(0.f, x1e00_disableControlCooldown); x191c_damageTimer -= dt; x191c_damageTimer = std::max(0.f, x191c_damageTimer); + if (x187c_spiderBallState == ESpiderBallState::Active) { x1924_surfaceToWorld = CalculateSurfaceToWorld(x1880_playerToSpiderNormal, x1890_spiderTrackPoint, x189c_spiderInterpBetweenPoints); x2c_tireLeanAngle = 0.f; - if (!x28_tireMode) + if (!x28_tireMode) { SwitchToTire(); + } x1c2c_tireInterpolating = true; x1c28_tireInterpSpeed = -1.f; UpdateMarbleDynamics(mgr, dt, x1890_spiderTrackPoint); @@ -1006,12 +1068,14 @@ void CMorphBall::UpdateBallDynamics(CStateManager& mgr, float dt) { zeus::CVector3f normal, point; if (CalculateBallContactInfo(normal, point)) { x1924_surfaceToWorld = CalculateSurfaceToWorld(normal, point, x0_player.x500_lookDir); - float speed = x0_player.GetVelocity().magnitude(); - if (speed < g_tweakBall->GetTireToMarbleThresholdSpeed() && x28_tireMode) + const float speed = x0_player.GetVelocity().magnitude(); + if (speed < g_tweakBall->GetTireToMarbleThresholdSpeed() && x28_tireMode) { SwitchToMarble(); + } if (UpdateMarbleDynamics(mgr, dt, point) && speed >= g_tweakBall->GetMarbleToTireThresholdSpeed() && - !x28_tireMode) + !x28_tireMode) { SwitchToTire(); + } if (x28_tireMode) { x2c_tireLeanAngle = x0_player.GetTransform().transposeRotate(x0_player.GetForceOR()).x() / g_tweakBall->GetMaxBallTranslationAcceleration(int(x0_player.GetSurfaceRestraint())) * @@ -1029,21 +1093,24 @@ void CMorphBall::UpdateBallDynamics(CStateManager& mgr, float dt) { } zeus::CRelAngle angle(x2c_tireLeanAngle - x30_ballTiltAngle); - float leanSpeed = std::fabs(angle) * g_tweakBall->GetMaxLeanAngle() * g_tweakBall->GetLeanTrackingGain(); - if (angle.asRadians() > 0.05f) + const float leanSpeed = std::fabs(angle) * g_tweakBall->GetMaxLeanAngle() * g_tweakBall->GetLeanTrackingGain(); + if (angle.asRadians() > 0.05f) { x30_ballTiltAngle += leanSpeed * dt; - else if (angle.asRadians() < -0.05f) + } else if (angle.asRadians() < -0.05f) { x30_ballTiltAngle -= leanSpeed * dt; - else + } else { x30_ballTiltAngle = x2c_tireLeanAngle; + } - if (x187c_spiderBallState != ESpiderBallState::Active) + if (x187c_spiderBallState != ESpiderBallState::Active) { ApplyFriction(CalculateSurfaceFriction()); - else + } else { DampLinearAndAngularVelocities(x18b4_linVelDamp, x18b8_angVelDamp); + } - if (x187c_spiderBallState != ESpiderBallState::Active) + if (x187c_spiderBallState != ESpiderBallState::Active) { ApplyGravity(mgr); + } x74_collisionInfos.Clear(); @@ -1069,11 +1136,13 @@ void CMorphBall::SwitchToTire() { } void CMorphBall::Update(float dt, CStateManager& mgr) { - if (x187c_spiderBallState == ESpiderBallState::Active) + if (x187c_spiderBallState == ESpiderBallState::Active) { CreateSpiderBallParticles(GetBallToWorld().origin, x1890_spiderTrackPoint); + } - if (x0_player.GetDeathTime() <= 0.f) + if (x0_player.GetDeathTime() <= 0.f) { UpdateEffects(dt, mgr); + } if (x1e44_damageEffect > 0.f) { x1e44_damageEffect -= x1e48_damageEffectDecaySpeed * dt; @@ -1086,8 +1155,9 @@ void CMorphBall::Update(float dt, CStateManager& mgr) { } } - if (x58_ballModel) + if (x58_ballModel) { x58_ballModel->AdvanceAnimation(dt, mgr, kInvalidAreaId, true); + } if (x1c2c_tireInterpolating) { x1c20_tireFactor += x1c28_tireInterpSpeed * dt; @@ -1100,23 +1170,30 @@ void CMorphBall::Update(float dt, CStateManager& mgr) { } } - if (x1c1c_rainSplashGen) + if (x1c1c_rainSplashGen) { x1c1c_rainSplashGen->Update(dt, mgr); + } UpdateMorphBallSounds(dt); } void CMorphBall::DeleteLight(CStateManager& mgr) { - if (x1c10_ballInnerGlowLight != kInvalidUniqueId) { - mgr.FreeScriptObject(x1c10_ballInnerGlowLight); - x1c10_ballInnerGlowLight = kInvalidUniqueId; + if (x1c10_ballInnerGlowLight == kInvalidUniqueId) { + return; } + + mgr.FreeScriptObject(x1c10_ballInnerGlowLight); + x1c10_ballInnerGlowLight = kInvalidUniqueId; } void CMorphBall::SetBallLightActive(CStateManager& mgr, bool active) { - if (x1c10_ballInnerGlowLight != kInvalidUniqueId) - if (TCastToPtr light = mgr.ObjectById(x1c10_ballInnerGlowLight)) - light->SetActive(active); + if (x1c10_ballInnerGlowLight == kInvalidUniqueId) { + return; + } + + if (const TCastToPtr light = mgr.ObjectById(x1c10_ballInnerGlowLight)) { + light->SetActive(active); + } } void CMorphBall::EnterMorphBallState(CStateManager& mgr) { @@ -1143,7 +1220,7 @@ void CMorphBall::LeaveMorphBallState(CStateManager& mgr) { } void CMorphBall::UpdateEffects(float dt, CStateManager& mgr) { - zeus::CTransform swooshToWorld = GetSwooshToWorld(); + const zeus::CTransform swooshToWorld = GetSwooshToWorld(); x19b8_slowBlueTailSwooshGen->SetTranslation(swooshToWorld.rotate({0.1f, 0.f, 0.f}) + swooshToWorld.origin); x19b8_slowBlueTailSwooshGen->SetOrientation(swooshToWorld.getRotation()); x19b8_slowBlueTailSwooshGen->DoWarmupUpdate(); @@ -1161,26 +1238,28 @@ void CMorphBall::UpdateEffects(float dt, CStateManager& mgr) { x19c8_jaggyTrailGen->DoWarmupUpdate(); x19cc_wallSparkGen->Update(dt); x1bc8_wakeEffectGens[7]->Update(dt); - bool emitRainWake = (x0_player.GetPlayerMovementState() == CPlayer::EPlayerMovementState::OnGround && + const bool emitRainWake = (x0_player.GetPlayerMovementState() == CPlayer::EPlayerMovementState::OnGround && mgr.GetWorld()->GetNeededEnvFx() == EEnvFxType::Rain && mgr.GetEnvFxManager()->GetRainMagnitude() > 0.f && mgr.GetEnvFxManager()->IsSplashActive()); x1bc8_wakeEffectGens[7]->SetParticleEmission(emitRainWake); - float rainGenRate = std::min(mgr.GetEnvFxManager()->GetRainMagnitude() * 2.f * x0_player.x4fc_flatMoveSpeed / - x0_player.GetBallMaxVelocity(), - 1.f); + const float rainGenRate = std::min(mgr.GetEnvFxManager()->GetRainMagnitude() * 2.f * x0_player.x4fc_flatMoveSpeed / + x0_player.GetBallMaxVelocity(), + 1.f); x1bc8_wakeEffectGens[7]->SetGeneratorRate(rainGenRate); x1bc8_wakeEffectGens[7]->SetTranslation(x0_player.GetTranslation()); if (emitRainWake) { - zeus::CTransform rainOrient = + const zeus::CTransform rainOrient = zeus::lookAt(x0_player.x50c_moveDir + x0_player.GetTranslation(), x0_player.GetTranslation()); x1bc8_wakeEffectGens[7]->SetOrientation(rainOrient); } - if (x1c0c_wakeEffectIdx != -1) + if (x1c0c_wakeEffectIdx != -1) { x1bc8_wakeEffectGens[x1c0c_wakeEffectIdx]->Update(dt); + } if (x1e38_wallSparkFrameCountdown > 0) { x1e38_wallSparkFrameCountdown -= 1; - if (x1e38_wallSparkFrameCountdown <= 0) + if (x1e38_wallSparkFrameCountdown <= 0) { x19cc_wallSparkGen->SetParticleEmission(false); + } } x19d0_ballInnerGlowGen->SetGlobalTranslation(swooshToWorld.origin); x19d0_ballInnerGlowGen->Update(dt); @@ -1189,10 +1268,11 @@ void CMorphBall::UpdateEffects(float dt, CStateManager& mgr) { } else { x19d8_boostBallGlowGen->SetGlobalTranslation(swooshToWorld.origin); float t; - if (x1df4_boostDrainTime == 0.f) + if (x1df4_boostDrainTime == 0.f) { t = x1de8_boostChargeTime / g_tweakBall->GetBoostBallMaxChargeTime(); - else + } else { t = 1.f - x1df4_boostDrainTime / g_tweakBall->GetBoostBallDrainTime(); + } x19d8_boostBallGlowGen->SetModulationColor( zeus::CColor::lerp(zeus::skBlack, zeus::CColor(1.f, 1.f, 0.4f, 1.f), t)); x19d8_boostBallGlowGen->Update(dt); @@ -1215,7 +1295,7 @@ void CMorphBall::UpdateEffects(float dt, CStateManager& mgr) { UpdateMorphBallTransitionFlash(dt); UpdateIceBreakEffect(dt); if (x1c10_ballInnerGlowLight != kInvalidUniqueId) { - if (TCastToPtr light = mgr.ObjectById(x1c10_ballInnerGlowLight)) { + if (const TCastToPtr light = mgr.ObjectById(x1c10_ballInnerGlowLight)) { light->SetTranslation(swooshToWorld.origin + zeus::CVector3f(0.f, 0.f, GetBallRadius())); std::optional lObj; @@ -1268,8 +1348,9 @@ void CMorphBall::UpdateEffects(float dt, CStateManager& mgr) { } void CMorphBall::ComputeBoostBallMovement(const CFinalInput& input, CStateManager& mgr, float dt) { - if (!IsMovementAllowed() || !mgr.GetPlayerState()->HasPowerUp(CPlayerState::EItemType::BoostBall)) + if (!IsMovementAllowed() || !mgr.GetPlayerState()->HasPowerUp(CPlayerState::EItemType::BoostBall)) { return; + } if (!x1de4_25_boostEnabled) { CancelBoosting(); @@ -1288,8 +1369,9 @@ void CMorphBall::ComputeBoostBallMovement(const CFinalInput& input, CStateManage x1e24_boostSfxHandle = CSfxManager::SfxStart(SFXsam_ball_charge_lp, 1.f, 0.f, true, 0x7f, true, kInvalidAreaId); } x1de8_boostChargeTime += dt; - if (x1de8_boostChargeTime > g_tweakBall->GetBoostBallMaxChargeTime()) + if (x1de8_boostChargeTime > g_tweakBall->GetBoostBallMaxChargeTime()) { x1de8_boostChargeTime = g_tweakBall->GetBoostBallMaxChargeTime(); + } } else { if (x1e20_ballAnimIdx == 1) { constexpr CAnimPlaybackParms parms(0, -1, 1.f, true); @@ -1324,31 +1406,36 @@ void CMorphBall::ComputeBoostBallMovement(const CFinalInput& input, CStateManage } } else { x1df4_boostDrainTime += dt; - if (x1df4_boostDrainTime > g_tweakBall->GetBoostBallDrainTime()) + if (x1df4_boostDrainTime > g_tweakBall->GetBoostBallDrainTime()) { LeaveBoosting(); + } if (!GetIsInHalfPipeMode() && !x1df8_27_ballCloseToCollision) { - if (x1df4_boostDrainTime / g_tweakBall->GetBoostBallDrainTime() < 0.3f) + if (x1df4_boostDrainTime / g_tweakBall->GetBoostBallDrainTime() < 0.3f) { DampLinearAndAngularVelocities(0.5f, 0.01f); - else + } else { LeaveBoosting(); + } } } } void CMorphBall::EnterBoosting(CStateManager& mgr) { x1de4_24_inBoost = true; + float incSpeed = 0.f; - if (x1de8_boostChargeTime <= g_tweakBall->GetBoostBallChargeTimeTable(0)) + if (x1de8_boostChargeTime <= g_tweakBall->GetBoostBallChargeTimeTable(0)) { incSpeed = g_tweakBall->GetBoostBallIncrementalSpeedTable(0); - else if (x1de8_boostChargeTime <= g_tweakBall->GetBoostBallChargeTimeTable(1)) + } else if (x1de8_boostChargeTime <= g_tweakBall->GetBoostBallChargeTimeTable(1)) { incSpeed = g_tweakBall->GetBoostBallIncrementalSpeedTable(1); - else if (x1de8_boostChargeTime <= g_tweakBall->GetBoostBallChargeTimeTable(2)) + } else if (x1de8_boostChargeTime <= g_tweakBall->GetBoostBallChargeTimeTable(2)) { incSpeed = g_tweakBall->GetBoostBallIncrementalSpeedTable(2); + } if (GetIsInHalfPipeMode()) { - float speedMul = x0_player.GetVelocity().magnitude() / 95.f; - if (speedMul > 0.3f) + const float speedMul = x0_player.GetVelocity().magnitude() / 95.f; + if (speedMul > 0.3f) { incSpeed -= (speedMul - 0.3f) * incSpeed; + } incSpeed = std::max(0.f, incSpeed); } @@ -1356,8 +1443,8 @@ void CMorphBall::EnterBoosting(CStateManager& mgr) { float lookMag2d = std::sqrt(lookDir.x() * lookDir.x() + lookDir.y() * lookDir.y()); float vertLookAngle = zeus::radToDeg(std::atan2(lookDir.z(), lookMag2d)); if (lookMag2d < 0.001f && x0_player.GetPlayerMovementState() == CPlayer::EPlayerMovementState::OnGround) { - float velMag2d = std::sqrt(x0_player.GetVelocity().x() * x0_player.GetVelocity().x() + - x0_player.GetVelocity().y() * x0_player.GetVelocity().y()); + const float velMag2d = std::sqrt(x0_player.GetVelocity().x() * x0_player.GetVelocity().x() + + x0_player.GetVelocity().y() * x0_player.GetVelocity().y()); if (velMag2d < 0.001f && std::fabs(x0_player.GetVelocity().z()) < 2.f) { lookDir = mgr.GetCameraManager()->GetCurrentCamera(mgr)->GetTransform().basis[1]; lookMag2d = std::sqrt(lookDir.x() * lookDir.x() + lookDir.y() * lookDir.y()); @@ -1367,7 +1454,7 @@ void CMorphBall::EnterBoosting(CStateManager& mgr) { float speedMul = 1.f; if (vertLookAngle > 40.f) { - float speedDamp = (vertLookAngle - 40.f) / 50.f; + const float speedDamp = (vertLookAngle - 40.f) / 50.f; speedMul = 0.35f * speedDamp + (1.f - speedDamp); } @@ -1385,6 +1472,7 @@ void CMorphBall::LeaveBoosting() { x1dec_timeNotInBoost = 0.f; x1de8_boostChargeTime = 0.f; } + x1de4_24_inBoost = false; x1df4_boostDrainTime = 0.f; } @@ -1392,6 +1480,7 @@ void CMorphBall::LeaveBoosting() { void CMorphBall::CancelBoosting() { x1de8_boostChargeTime = 0.f; x1df4_boostDrainTime = 0.f; + if (x1e20_ballAnimIdx == 1) { constexpr CAnimPlaybackParms parms(0, -1, 1.f, true); x58_ballModel->GetAnimationData()->SetAnimation(parms, false); @@ -1402,36 +1491,44 @@ void CMorphBall::CancelBoosting() { bool CMorphBall::UpdateMarbleDynamics(CStateManager& mgr, float dt, const zeus::CVector3f& point) { bool continueForce = false; - float maxAcc = g_tweakBall->GetMaxBallTranslationAcceleration(int(x0_player.GetSurfaceRestraint())); + const float maxAcc = g_tweakBall->GetMaxBallTranslationAcceleration(int(x0_player.GetSurfaceRestraint())); + if (x0_player.GetVelocity().magnitude() < 3.f && x10_boostControlForce.magnitude() > 0.95f * maxAcc) { zeus::CVector3f localMomentum = x1924_surfaceToWorld.transposeRotate(x0_player.GetMomentum()); localMomentum.z() = 0.f; zeus::CVector3f localControlForce = x1924_surfaceToWorld.transposeRotate(x10_boostControlForce); localControlForce.z() = 0.f; - if (localMomentum.canBeNormalized() && localControlForce.canBeNormalized()) - if (localMomentum.normalized().dot(localControlForce.normalized()) < -0.9f) + if (localMomentum.canBeNormalized() && localControlForce.canBeNormalized()) { + if (localMomentum.normalized().dot(localControlForce.normalized()) < -0.9f) { continueForce = true; + } + } } if (!continueForce) { - zeus::CVector3f vel = x0_player.GetVelocity(); - zeus::CVector3f ballToPoint = point - (x0_player.GetTranslation() + zeus::CVector3f(0.f, 0.f, GetBallRadius())); - zeus::CVector3f addVel = x0_player.GetAngularVelocityWR().getVector().cross(ballToPoint); + const zeus::CVector3f vel = x0_player.GetVelocity(); + const zeus::CVector3f ballToPoint = + point - (x0_player.GetTranslation() + zeus::CVector3f(0.f, 0.f, GetBallRadius())); + const zeus::CVector3f addVel = x0_player.GetAngularVelocityWR().getVector().cross(ballToPoint); zeus::CVector3f velDelta = vel - addVel; - float f28 = x187c_spiderBallState == ESpiderBallState::Active ? -1.f : 0.4f; + const float f28 = x187c_spiderBallState == ESpiderBallState::Active ? -1.f : 0.4f; float liftSpeed = 0.f; + if (x1cd0_liftSpeedAvg.Size() > 3) { liftSpeed = *x1cd0_liftSpeedAvg.GetEntry(0); liftSpeed = std::min(liftSpeed, *x1cd0_liftSpeedAvg.GetEntry(1)); liftSpeed = std::min(liftSpeed, *x1cd0_liftSpeedAvg.GetEntry(2)); } + if (velDelta.magSquared() > 1.f && liftSpeed > f28) { - if (velDelta.magnitude() > 25.132742f) + if (velDelta.magnitude() > 25.132742f) { velDelta = velDelta.normalized() * M_PIF * 8.f; - zeus::CVector3f newVel = vel + addVel; + } + + const zeus::CVector3f newVel = vel + addVel; if (newVel.canBeNormalized()) { - float f26 = (x28_tireMode && x187c_spiderBallState != ESpiderBallState::Active) ? 0.25f : 1.f; - zeus::CVector3f f27 = + const float f26 = (x28_tireMode && x187c_spiderBallState != ESpiderBallState::Active) ? 0.25f : 1.f; + const zeus::CVector3f f27 = newVel.normalized() * (velDelta.magnitude() * -g_tweakBall->GetBallSlipFactor(int(x0_player.GetSurfaceRestraint())) * f26 * 0.5f / GetBallRadius()); @@ -1439,16 +1536,19 @@ bool CMorphBall::UpdateMarbleDynamics(CStateManager& mgr, float dt, const zeus:: } } } else { - zeus::CVector3f rotAxis = x1924_surfaceToWorld.basis[2].cross(x10_boostControlForce); - if (rotAxis.canBeNormalized()) + const zeus::CVector3f rotAxis = x1924_surfaceToWorld.basis[2].cross(x10_boostControlForce); + if (rotAxis.canBeNormalized()) { SpinToSpeed(25.f / GetBallRadius(), rotAxis.normalized(), 800.f); + } } if (x0_player.GetVelocity().magnitude() >= GetMinimumAlignmentSpeed()) { zeus::CVector3f axis = x1924_surfaceToWorld.basis[0]; - if (x0_player.GetTransform().basis[0].dot(axis) < 0.f) + if (x0_player.GetTransform().basis[0].dot(axis) < 0.f) { axis = -axis; - zeus::CVector3f upVec = x0_player.GetTransform().basis[0].cross(axis); + } + + const zeus::CVector3f upVec = x0_player.GetTransform().basis[0].cross(axis); if (upVec.canBeNormalized()) { if (!x28_tireMode) { x0_player.SetAngularImpulse(x0_player.GetAngularImpulse().getVector() + @@ -1467,31 +1567,37 @@ bool CMorphBall::UpdateMarbleDynamics(CStateManager& mgr, float dt, const zeus:: void CMorphBall::ApplyFriction(float f) { zeus::CVector3f vel = x0_player.GetVelocity(); - if (f < vel.magnitude()) + + if (f < vel.magnitude()) { vel = vel.normalized() * (vel.magnitude() - f); - else + } else { vel = zeus::skZero3f; + } + x0_player.SetVelocityWR(vel); } void CMorphBall::DampLinearAndAngularVelocities(float linDamp, float angDamp) { - zeus::CVector3f vel = x0_player.GetVelocity() * (1.f - linDamp); + const zeus::CVector3f vel = x0_player.GetVelocity() * (1.f - linDamp); x0_player.SetVelocityWR(vel); + zeus::CAxisAngle ang = x0_player.GetAngularVelocityWR(); ang = ang * (1.f - angDamp); x0_player.SetAngularVelocityWR(ang); } float CMorphBall::GetMinimumAlignmentSpeed() const { - if (x187c_spiderBallState == ESpiderBallState::Active) + if (x187c_spiderBallState == ESpiderBallState::Active) { return 0.f; - else - return g_tweakBall->GetMinimumAlignmentSpeed(); + } + + return g_tweakBall->GetMinimumAlignmentSpeed(); } void CMorphBall::PreRender(CStateManager& mgr, const zeus::CFrustum& frustum) { - if (x1c34_boostLightFactor == 1.f) + if (x1c34_boostLightFactor == 1.f) { return; + } x0_player.GetActorLights()->SetFindShadowLight(x1e44_damageEffect < 0.25f); x0_player.GetActorLights()->SetShadowDynamicRangeThreshold(0.05f); @@ -1499,12 +1605,13 @@ void CMorphBall::PreRender(CStateManager& mgr, const zeus::CFrustum& frustum) { CCollidableSphere sphere = x38_collisionSphere; sphere.SetSphereCenter(zeus::skZero3f); - zeus::CAABox ballAABB = sphere.CalculateAABox(GetBallToWorld()); + const zeus::CAABox ballAABB = sphere.CalculateAABox(GetBallToWorld()); if (x0_player.GetAreaIdAlways() != kInvalidAreaId) { const CGameArea* area = mgr.GetWorld()->GetAreaAlways(x0_player.GetAreaIdAlways()); - if (area->IsPostConstructed()) + if (area->IsPostConstructed()) { x0_player.GetActorLights()->BuildAreaLightList(mgr, *area, ballAABB); + } } x0_player.GetActorLights()->BuildDynamicLightList(mgr, ballAABB); @@ -1528,8 +1635,9 @@ void CMorphBall::PreRender(CStateManager& mgr, const zeus::CFrustum& frustum) { x1c18_actorLights->SetAmbientColor( zeus::CColor::lerp(ambColor, zeus::skWhite, std::max(x1c38_spiderLightFactor, x1c34_boostLightFactor))); - if (CAnimData* animData = x58_ballModel->GetAnimationData()) + if (CAnimData* animData = x58_ballModel->GetAnimationData()) { animData->PreRender(); + } } void CMorphBall::PointGenerator(void* ctx, const std::vector>& vn) { @@ -1547,21 +1655,21 @@ void CMorphBall::Render(const CStateManager& mgr, const CActorLights* lights) co bool dying = x0_player.x9f4_deathTime > 0.f; if (dying) { - zeus::CColor modColor(0.f, zeus::clamp(0.f, 1.f - x0_player.x9f4_deathTime / 0.2f * 6.f, 1.f)); + const zeus::CColor modColor(0.f, zeus::clamp(0.f, 1.f - x0_player.x9f4_deathTime / 0.2f * 6.f, 1.f)); CModelFlags flags(7, u8(x5c_ballModelShader), 1, modColor); flags.m_extendedShader = EExtendedShader::LightingCubeReflection; x58_ballModel->Render(mgr, ballToWorld, nullptr, flags); } CModelFlags flags(0, 0, 3, zeus::skWhite); - - if (x1e44_damageEffect > 0.f) + if (x1e44_damageEffect > 0.f) { flags = CModelFlags(1, 0, 3, zeus::CColor(1.f, 1.f - x1e44_damageEffect, 1.f - x1e44_damageEffect, 1.f)); - + } flags.m_extendedShader = EExtendedShader::LightingCubeReflection; - if (x1c1c_rainSplashGen && x1c1c_rainSplashGen->IsRaining()) + if (x1c1c_rainSplashGen && x1c1c_rainSplashGen->IsRaining()) { CSkinnedModel::SetPointGeneratorFunc(x1c1c_rainSplashGen.get(), PointGenerator); + } if (x1c34_boostLightFactor != 1.f) { if (lights->HasShadowLight()) { @@ -1584,27 +1692,29 @@ void CMorphBall::Render(const CStateManager& mgr, const CActorLights* lights) co if (x1e44_damageEffect > 0.25f) { RenderDamageEffects(mgr, ballToWorld); } else if (x1c30_boostOverLightFactor > 0.f && !dying) { - int count = std::min(int(speed * 0.5f), 5); + const int count = std::min(int(speed * 0.5f), 5); for (int i = 0; i < count; ++i) { - zeus::CTransform xf = + const zeus::CTransform xf = zeus::CTransform::Translate(*x1c90_ballPosAvg.GetEntry(i)) * x1c3c_ballOrientAvg.GetEntry(i)->toTransform(); - float alpha = (1.f - i / 5.f) * x1c30_boostOverLightFactor * 0.2f; + const float alpha = (1.f - static_cast(i) / 5.f) * x1c30_boostOverLightFactor * 0.2f; if (x68_lowPolyBallModel) { - CModelFlags lpFlags(7, u8(x6c_lowPolyBallModelShader), 1, zeus::CColor(1.f, alpha)); + const CModelFlags lpFlags(7, u8(x6c_lowPolyBallModelShader), 1, zeus::CColor(1.f, alpha)); x68_lowPolyBallModel->Render(mgr, xf, nullptr, lpFlags); } } } ColorArray c = BallSwooshColors[x8_ballGlowColorIdx]; - float swooshAlpha = x1c20_tireFactor / x1c24_maxTireFactor; + const float swooshAlpha = x1c20_tireFactor / x1c24_maxTireFactor; zeus::CColor color0 = {c[0] / 255.f, c[1] / 255.f, c[2] / 255.f, swooshAlpha}; c = BallSwooshColorsCharged[x8_ballGlowColorIdx]; zeus::CColor color1 = {c[0] / 255.f, c[1] / 255.f, c[2] / 255.f, swooshAlpha}; float t = 0.f; - if (x1df4_boostDrainTime > 0.f) + if (x1df4_boostDrainTime > 0.f) { t = zeus::clamp(0.f, (speed - 25.f) / 15.f, 1.f); - zeus::CColor tailColor = zeus::CColor::lerp(color0, color1, t); + } + const zeus::CColor tailColor = zeus::CColor::lerp(color0, color1, t); + x19b8_slowBlueTailSwooshGen->SetModulationColor(tailColor); x19b8_slowBlueTailSwooshGen->Render(); x19bc_slowBlueTailSwooshGen2->SetModulationColor(tailColor); @@ -1615,9 +1725,9 @@ void CMorphBall::Render(const CStateManager& mgr, const CActorLights* lights) co x19c4_slowBlueTailSwoosh2Gen2->Render(); if (x1df4_boostDrainTime > 0.f && speed > 23.f && swooshAlpha > 0.5f) { - float laggyAlpha = zeus::clamp(0.f, (speed - 23.f) / 17.f, t); + const float laggyAlpha = zeus::clamp(0.f, (speed - 23.f) / 17.f, t); c = BallSwooshColorsJaggy[x8_ballGlowColorIdx]; - zeus::CColor colorJaggy = {c[0] / 255.f, c[1] / 255.f, c[2] / 255.f, laggyAlpha}; + const zeus::CColor colorJaggy = {c[0] / 255.f, c[1] / 255.f, c[2] / 255.f, laggyAlpha}; x19c8_jaggyTrailGen->SetModulationColor(colorJaggy); x19c8_jaggyTrailGen->Render(); } @@ -1625,7 +1735,7 @@ void CMorphBall::Render(const CStateManager& mgr, const CActorLights* lights) co RenderSpiderBallElectricalEffect(); if (mgr.GetPlayerState()->HasPowerUp(CPlayerState::EItemType::SpiderBall) && x60_spiderBallGlassModel) { - float tmp = std::max(x1c38_spiderLightFactor, x1c34_boostLightFactor); + const float tmp = std::max(x1c38_spiderLightFactor, x1c34_boostLightFactor); CModelFlags sflags(0, u8(x64_spiderBallGlassModelShader), 3, zeus::skWhite); sflags.m_extendedShader = EExtendedShader::LightingCubeReflection; if (tmp != 1.f) { @@ -1642,8 +1752,9 @@ void CMorphBall::Render(const CStateManager& mgr, const CActorLights* lights) co x19cc_wallSparkGen->Render(); x1bc8_wakeEffectGens[7]->Render(); - if (x1c0c_wakeEffectIdx != -1) + if (x1c0c_wakeEffectIdx != -1) { x1bc8_wakeEffectGens[x1c0c_wakeEffectIdx]->Render(); + } c = BallGlowColors[x8_ballGlowColorIdx]; zeus::CColor glowColor = {c[0] / 255.f, c[1] / 255.f, c[2] / 255.f, 1.f}; @@ -1662,8 +1773,9 @@ void CMorphBall::Render(const CStateManager& mgr, const CActorLights* lights) co x19d0_ballInnerGlowGen->Render(); x19d4_spiderBallMagnetEffectGen->Render(); RenderEnergyDrainEffects(mgr); - if (x19d8_boostBallGlowGen->GetModulationColor() != zeus::skClear) + if (x19d8_boostBallGlowGen->GetModulationColor() != zeus::skClear) { x19d8_boostBallGlowGen->Render(); + } RenderMorphBallTransitionFlash(mgr); @@ -1677,8 +1789,9 @@ void CMorphBall::Render(const CStateManager& mgr, const CActorLights* lights) co void CMorphBall::ResetMorphBallTransitionFlash() { x19a8_morphBallTransitionFlash.Lock(); - if (x19dc_morphBallTransitionFlashGen) + if (x19dc_morphBallTransitionFlashGen) { x19dc_morphBallTransitionFlashGen.reset(); + } } void CMorphBall::UpdateMorphBallTransitionFlash(float dt) { @@ -1730,8 +1843,9 @@ void CMorphBall::UpdateIceBreakEffect(float dt) { } void CMorphBall::RenderIceBreakEffect(const CStateManager& mgr) const { - if (x19e0_effect_morphBallIceBreakGen) + if (x19e0_effect_morphBallIceBreakGen) { x19e0_effect_morphBallIceBreakGen->Render(); + } } void CMorphBall::RenderDamageEffects(const CStateManager& mgr, const zeus::CTransform& xf) const { @@ -1742,8 +1856,8 @@ void CMorphBall::RenderDamageEffects(const CStateManager& mgr, const zeus::CTran flags.m_extendedShader = EExtendedShader::SolidColorAdditive; for (int i = 0; i < 5; ++i) { rand.Float(); - float translateMag = 0.15f * x1e44_damageEffect * std::sin(30.f * x1e4c_damageTime + rand.Float() * M_PIF); - zeus::CTransform modelXf = + const float translateMag = 0.15f * x1e44_damageEffect * std::sin(30.f * x1e4c_damageTime + rand.Float() * M_PIF); + const zeus::CTransform modelXf = xf * zeus::CTransform::Translate(translateMag * rand.Float(), translateMag * rand.Float(), translateMag * rand.Float()); x68_lowPolyBallModel->Render(CModelData::EWhichModel::Normal, modelXf, nullptr, flags); @@ -1756,7 +1870,7 @@ void CMorphBall::UpdateHalfPipeStatus(CStateManager& mgr, float dt) { x1e04_touchHalfPipeRecentCooldown -= dt; x1e04_touchHalfPipeRecentCooldown = std::max(0.f, x1e04_touchHalfPipeRecentCooldown); if (x1dfc_touchHalfPipeCooldown > 0.f) { - float avg = *x1cd0_liftSpeedAvg.GetAverage(); + const float avg = *x1cd0_liftSpeedAvg.GetAverage(); if (avg > 25.f || (GetIsInHalfPipeMode() && avg > 4.5f)) { SetIsInHalfPipeMode(true); SetIsInHalfPipeModeInAir(!x1df8_27_ballCloseToCollision); @@ -1772,10 +1886,11 @@ void CMorphBall::UpdateHalfPipeStatus(CStateManager& mgr, float dt) { DisableHalfPipeStatus(); } - if (GetIsInHalfPipeMode()) + if (GetIsInHalfPipeMode()) { x0_player.SetCollisionAccuracyModifier(10.f); - else + } else { x0_player.SetCollisionAccuracyModifier(1.f); + } } void CMorphBall::DisableHalfPipeStatus() { @@ -1790,19 +1905,24 @@ void CMorphBall::DisableHalfPipeStatus() { } bool CMorphBall::BallCloseToCollision(const CStateManager& mgr, float dist, const CMaterialFilter& filter) const { - CMaterialList playerOrSolid(EMaterialTypes::Player, EMaterialTypes::Solid); - CCollidableSphere sphere(zeus::CSphere(x0_player.GetTranslation() + zeus::CVector3f(0.f, 0.f, GetBallRadius()), dist), - playerOrSolid); + constexpr CMaterialList playerOrSolid(EMaterialTypes::Player, EMaterialTypes::Solid); + const CCollidableSphere sphere( + zeus::CSphere(x0_player.GetTranslation() + zeus::CVector3f(0.f, 0.f, GetBallRadius()), dist), playerOrSolid); + rstl::reserved_vector nearList; mgr.BuildColliderList(nearList, x0_player, sphere.CalculateLocalAABox()); - if (CGameCollision::DetectStaticCollisionBoolean(mgr, sphere, zeus::CTransform(), filter)) + + if (CGameCollision::DetectStaticCollisionBoolean(mgr, sphere, zeus::CTransform(), filter)) { return true; - for (TUniqueId id : nearList) { - if (TCastToConstPtr act = mgr.GetObjectById(id)) { + } + + for (const TUniqueId id : nearList) { + if (const TCastToConstPtr act = mgr.GetObjectById(id)) { if (CCollisionPrimitive::CollideBoolean( {sphere, filter, zeus::CTransform()}, - {*act->GetCollisionPrimitive(), CMaterialFilter::skPassEverything, act->GetPrimitiveTransform()})) + {*act->GetCollisionPrimitive(), CMaterialFilter::skPassEverything, act->GetPrimitiveTransform()})) { return true; + } } } return false; @@ -1810,13 +1930,15 @@ bool CMorphBall::BallCloseToCollision(const CStateManager& mgr, float dist, cons void CMorphBall::CollidedWith(TUniqueId id, const CCollisionInfoList& list, CStateManager& mgr) { x74_collisionInfos = list; - CMaterialList allMats; - for (const CCollisionInfo& info : list) - allMats.Add(info.GetMaterialLeft()); - zeus::CVector3f vel = x0_player.GetVelocity(); - float velMag = vel.magnitude(); - EMaterialTypes wakeMaterial = EMaterialTypes::NoStepLogic; + CMaterialList allMats; + for (const CCollisionInfo& info : list) { + allMats.Add(info.GetMaterialLeft()); + } + + const zeus::CVector3f vel = x0_player.GetVelocity(); + const float velMag = vel.magnitude(); + auto wakeMaterial = EMaterialTypes::NoStepLogic; if (velMag > 7.f && x0_player.GetFluidCounter() == 0) { bool hitWall = false; for (const CCollisionInfo& info : list) { @@ -1835,40 +1957,50 @@ void CMorphBall::CollidedWith(TUniqueId id, const CCollisionInfoList& list, CSta if (wakeMaterial == EMaterialTypes::NoStepLogic) { if (info.GetMaterialLeft().HasMaterial(EMaterialTypes::Floor)) { EMaterialTypes tmpMaterial; - if (info.GetMaterialLeft().HasMaterial(EMaterialTypes::Dirt)) + if (info.GetMaterialLeft().HasMaterial(EMaterialTypes::Dirt)) { tmpMaterial = EMaterialTypes::Dirt; - else + } else { tmpMaterial = wakeMaterial; + } - if (info.GetMaterialLeft().HasMaterial(EMaterialTypes::Sand)) + if (info.GetMaterialLeft().HasMaterial(EMaterialTypes::Sand)) { tmpMaterial = EMaterialTypes::Sand; + } - if (info.GetMaterialLeft().HasMaterial(EMaterialTypes::Lava)) + if (info.GetMaterialLeft().HasMaterial(EMaterialTypes::Lava)) { tmpMaterial = EMaterialTypes::Lava; + } - if (info.GetMaterialLeft().HasMaterial(EMaterialTypes::MudSlow)) + if (info.GetMaterialLeft().HasMaterial(EMaterialTypes::MudSlow)) { tmpMaterial = EMaterialTypes::MudSlow; + } - if (info.GetMaterialLeft().HasMaterial(EMaterialTypes::Snow)) + if (info.GetMaterialLeft().HasMaterial(EMaterialTypes::Snow)) { tmpMaterial = EMaterialTypes::Snow; + } - if (info.GetMaterialLeft().HasMaterial(EMaterialTypes::Phazon)) + if (info.GetMaterialLeft().HasMaterial(EMaterialTypes::Phazon)) { tmpMaterial = EMaterialTypes::Phazon; + } wakeMaterial = tmpMaterial; if (tmpMaterial != EMaterialTypes::NoStepLogic) { int mappedIdx = skWakeEffectMap[size_t(tmpMaterial)]; - if (mappedIdx == 0) // Phazon - { + + // Phazon + if (mappedIdx == 0) { const CGameArea* area = mgr.GetWorld()->GetAreaAlways(mgr.GetNextAreaId()); - if (const CScriptAreaAttributes* attribs = area->GetPostConstructed()->x10d8_areaAttributes) - if (attribs->GetPhazonType() == EPhazonType::Orange) + if (const CScriptAreaAttributes* attribs = area->GetPostConstructed()->x10d8_areaAttributes) { + if (attribs->GetPhazonType() == EPhazonType::Orange) { mappedIdx = 1; // Orange Phazon + } + } } if (x1c0c_wakeEffectIdx != mappedIdx) { - if (x1c0c_wakeEffectIdx != -1) + if (x1c0c_wakeEffectIdx != -1) { x1bc8_wakeEffectGens[x1c0c_wakeEffectIdx]->SetParticleEmission(false); + } x1c0c_wakeEffectIdx = mappedIdx; } @@ -1886,8 +2018,9 @@ void CMorphBall::CollidedWith(TUniqueId id, const CCollisionInfoList& list, CSta } } - if (wakeMaterial == EMaterialTypes::NoStepLogic && x1c0c_wakeEffectIdx != -1) + if (wakeMaterial == EMaterialTypes::NoStepLogic && x1c0c_wakeEffectIdx != -1) { x1bc8_wakeEffectGens[int(x1c0c_wakeEffectIdx)]->SetParticleEmission(false); + } x1954_isProjectile = false; @@ -1899,18 +2032,20 @@ void CMorphBall::CollidedWith(TUniqueId id, const CCollisionInfoList& list, CSta if (info.GetNormalLeft().dot(x1e14_halfPipeNormal) < 0.99) { x1e08_prevHalfPipeNormal = x1e14_halfPipeNormal; x1e14_halfPipeNormal = info.GetNormalLeft(); - if (zeus::close_enough(x1e08_prevHalfPipeNormal, zeus::skZero3f, 0.000011920929f)) + if (zeus::close_enough(x1e08_prevHalfPipeNormal, zeus::skZero3f, 0.000011920929f)) { x1e08_prevHalfPipeNormal = x1e14_halfPipeNormal; + } } } } } - if (x28_tireMode && allMats.HasMaterial(EMaterialTypes::Floor) && allMats.HasMaterial(EMaterialTypes::Wall)) + if (x28_tireMode && allMats.HasMaterial(EMaterialTypes::Floor) && allMats.HasMaterial(EMaterialTypes::Wall)) { SwitchToMarble(); + } if (!GetIsInHalfPipeMode() && x1de4_24_inBoost && velMag > 3.f) { - zeus::CVector3f velNorm = vel.normalized(); + const zeus::CVector3f velNorm = vel.normalized(); for (const CCollisionInfo& info : list) { if (!info.GetMaterialLeft().HasMaterial(EMaterialTypes::HalfPipe) && info.GetNormalLeft().dot(velNorm) < -0.4f) { LeaveBoosting(); @@ -1921,22 +2056,22 @@ void CMorphBall::CollidedWith(TUniqueId id, const CCollisionInfoList& list, CSta } if (id == kInvalidUniqueId) { - zeus::CVector3f cvel = x0_player.GetVelocity(); - float cvelMag = cvel.magnitude(); - zeus::CVector3f cforce = x1c_controlForce; + const zeus::CVector3f cvel = x0_player.GetVelocity(); + const float cvelMag = cvel.magnitude(); + const zeus::CVector3f cforce = x1c_controlForce; if (cforce.magnitude() > 1000.f && cvelMag > 8.f) { - zeus::CVector3f cforceNorm = cforce.normalized(); - zeus::CVector3f cvelNorm = cvel.normalized(); + const zeus::CVector3f cforceNorm = cforce.normalized(); + const zeus::CVector3f cvelNorm = cvel.normalized(); for (const CCollisionInfo& info : list) { if (IsClimbable(info) && info.GetNormalLeft().dot(cforceNorm) < -0.4f && info.GetNormalLeft().dot(cvelNorm) < -0.6f) { - float threeQVel = 0.75f * cvelMag; - float maxSpeed = g_tweakBall->GetBallTranslationMaxSpeed(int(x0_player.GetSurfaceRestraint())); - float f0 = maxSpeed * 0.15f; - float f3 = (threeQVel - f0) < 0.f ? threeQVel : f0; + const float threeQVel = 0.75f * cvelMag; + const float maxSpeed = g_tweakBall->GetBallTranslationMaxSpeed(int(x0_player.GetSurfaceRestraint())); + const float f0 = maxSpeed * 0.15f; + const float f3 = (threeQVel - f0) < 0.f ? threeQVel : f0; float f4 = maxSpeed * 0.25f; f4 = (f3 - f4) < 0.f ? f4 : f3; - zeus::CVector3f newVel = cvel + zeus::CVector3f(0.f, 0.f, f4); + const zeus::CVector3f newVel = cvel + zeus::CVector3f(0.f, 0.f, f4); x1dd8_ = newVel; x0_player.SetVelocityWR(newVel); x1dc8_failsafeCounter += 1; @@ -1959,22 +2094,26 @@ void CMorphBall::CollidedWith(TUniqueId id, const CCollisionInfoList& list, CSta } } - if (accum / float(count) < 0.5f) + if (accum / float(count) < 0.5f) { x1dc8_failsafeCounter += 1; + } } - if (list.GetCount() != 0) + if (list.GetCount() != 0) { SelectMorphBallSounds(list.GetItem(0).GetMaterialLeft()); + } } bool CMorphBall::IsInFrustum(const zeus::CFrustum& frustum) const { - if (x58_ballModel->IsNull()) + if (x58_ballModel->IsNull()) { return false; + } - if (x58_ballModel->IsInFrustum(GetBallToWorld(), frustum)) + if (x58_ballModel->IsInFrustum(GetBallToWorld(), frustum)) { return true; + } - auto swooshBounds = x19b8_slowBlueTailSwooshGen->GetBounds(); + const auto swooshBounds = x19b8_slowBlueTailSwooshGen->GetBounds(); return x19b8_slowBlueTailSwooshGen->GetModulationColor().a() != 0.f && swooshBounds && frustum.aabbFrustumTest(*swooshBounds); } @@ -1983,25 +2122,29 @@ void CMorphBall::ComputeLiftForces(const zeus::CVector3f& controlForce, const ze const CStateManager& mgr) { x1cd0_liftSpeedAvg.AddValue(velocity.magnitude()); x1d10_liftControlForceAvg.AddValue(controlForce); - zeus::CVector3f avgControlForce = *x1d10_liftControlForceAvg.GetAverage(); - float avgControlForceMag = avgControlForce.magnitude(); + + const zeus::CVector3f avgControlForce = *x1d10_liftControlForceAvg.GetAverage(); + const float avgControlForceMag = avgControlForce.magnitude(); + if (avgControlForceMag > 12000.f) { - float avgLiftSpeed = *x1cd0_liftSpeedAvg.GetAverage(); + const float avgLiftSpeed = *x1cd0_liftSpeedAvg.GetAverage(); + if (avgLiftSpeed < 4.f) { - zeus::CTransform xf = x0_player.GetPrimitiveTransform(); + const zeus::CTransform xf = x0_player.GetPrimitiveTransform(); zeus::CAABox aabb = x0_player.GetCollisionPrimitive()->CalculateAABox(xf); aabb.min -= zeus::CVector3f(0.1f, 0.1f, -0.05f); aabb.max += zeus::CVector3f(0.1f, 0.1f, -0.05f); - CCollidableAABox colAABB(aabb, {EMaterialTypes::Solid}); + const CCollidableAABox colAABB(aabb, {EMaterialTypes::Solid}); + if (CGameCollision::DetectStaticCollisionBoolean(mgr, colAABB, zeus::CTransform(), CMaterialFilter::skPassEverything)) { - zeus::CVector3f pos = xf.origin + zeus::CVector3f(0.f, 0.f, 1.75f * GetBallRadius()); - zeus::CVector3f dir = avgControlForce * (1.f / avgControlForceMag); - CRayCastResult result = + const zeus::CVector3f pos = xf.origin + zeus::CVector3f(0.f, 0.f, 1.75f * GetBallRadius()); + const zeus::CVector3f dir = avgControlForce * (1.f / avgControlForceMag); + const CRayCastResult result = mgr.RayStaticIntersection(pos, dir, 1.4f, CMaterialFilter::MakeInclude({EMaterialTypes::Solid})); if (result.IsInvalid()) { - float mag = 1.f - std::max(0.f, avgLiftSpeed - 3.f); - zeus::CVector3f force(0.f, 0.f, mag * 40000.f); + const float mag = 1.f - std::max(0.f, avgLiftSpeed - 3.f); + const zeus::CVector3f force(0.f, 0.f, mag * 40000.f); x0_player.ApplyForceWR(force, zeus::CAxisAngle()); x0_player.ApplyImpulseWR(zeus::skZero3f, zeus::CAxisAngle(-x1924_surfaceToWorld.basis[0] * 1000.f * mag)); @@ -2013,36 +2156,42 @@ void CMorphBall::ComputeLiftForces(const zeus::CVector3f& controlForce, const ze float CMorphBall::CalculateSurfaceFriction() const { float friction = g_tweakBall->GetBallTranslationFriction(int(x0_player.GetSurfaceRestraint())); - if (x0_player.GetAttachedActor() != kInvalidUniqueId) + if (x0_player.GetAttachedActor() != kInvalidUniqueId) { friction *= 2.f; - size_t drainSourceCount = x0_player.GetEnergyDrain().GetEnergyDrainSources().size(); - if (drainSourceCount > 0) + } + + const size_t drainSourceCount = x0_player.GetEnergyDrain().GetEnergyDrainSources().size(); + if (drainSourceCount > 0) { friction *= drainSourceCount * 1.5f; + } + return friction; } -void CMorphBall::ApplyGravity(CStateManager& mgr) { - if (x0_player.CheckSubmerged() && !mgr.GetPlayerState()->HasPowerUp(CPlayerState::EItemType::GravitySuit)) - x0_player.SetMomentumWR(zeus::CVector3f(0.f, 0.f, g_tweakBall->GetBallWaterGravity() * x0_player.GetMass())); - else - x0_player.SetMomentumWR(zeus::CVector3f(0.f, 0.f, g_tweakBall->GetBallGravity() * x0_player.GetMass())); +void CMorphBall::ApplyGravity(const CStateManager& mgr) { + const float mass = x0_player.GetMass(); + const bool hasGravitySuit = mgr.GetPlayerState()->HasPowerUp(CPlayerState::EItemType::GravitySuit); + const bool useWaterGravity = x0_player.CheckSubmerged() && !hasGravitySuit; + const float gravity = useWaterGravity ? g_tweakBall->GetBallWaterGravity() : g_tweakBall->GetBallGravity(); + + x0_player.SetMomentumWR(zeus::CVector3f(0.f, 0.f, gravity * mass)); } -void CMorphBall::SpinToSpeed(float holdMag, zeus::CVector3f torque, float mag) { +void CMorphBall::SpinToSpeed(float holdMag, const zeus::CVector3f& torque, float mag) { x0_player.ApplyTorqueWR(torque * ((holdMag - x0_player.GetAngularVelocityWR().getVector().magnitude()) * mag)); } float CMorphBall::ComputeMaxSpeed() const { - if (GetIsInHalfPipeMode()) + if (GetIsInHalfPipeMode()) { return std::min(x0_player.GetVelocity().magnitude() * 1.5f, 95.f); - else - return g_tweakBall->GetBallTranslationMaxSpeed(int(x0_player.GetSurfaceRestraint())); + } + return g_tweakBall->GetBallTranslationMaxSpeed(int(x0_player.GetSurfaceRestraint())); } constexpr CDamageInfo kBallDamage = {CWeaponMode(EWeaponType::BoostBall), 50000.f, 0.f, 0.f}; void CMorphBall::Touch(CActor& actor, CStateManager& mgr) { - if (TCastToPtr act = actor) { + if (const TCastToConstPtr act = actor) { if (x1de4_24_inBoost && (act->GetVelocity() - x0_player.GetVelocity()).magnitude() > g_tweakBall->GetBoostBallMinRelativeSpeedForDamage()) { mgr.ApplyDamage(x0_player.GetUniqueId(), actor.GetUniqueId(), x0_player.GetUniqueId(), kBallDamage, @@ -2053,9 +2202,10 @@ void CMorphBall::Touch(CActor& actor, CStateManager& mgr) { bool CMorphBall::IsClimbable(const CCollisionInfo& cinfo) const { if (std::fabs(cinfo.GetNormalLeft().z()) < 0.7f) { - float pointToBall = GetBallToWorld().origin.z() - cinfo.GetPoint().z(); - if (pointToBall > 0.1f && pointToBall < GetBallRadius() - 0.05f) + const float pointToBall = GetBallToWorld().origin.z() - cinfo.GetPoint().z(); + if (pointToBall > 0.1f && pointToBall < GetBallRadius() - 0.05f) { return true; + } } return false; } @@ -2063,16 +2213,18 @@ bool CMorphBall::IsClimbable(const CCollisionInfo& cinfo) const { void CMorphBall::FluidFXThink(CActor::EFluidState state, CScriptWater& water, CStateManager& mgr) { zeus::CVector3f vec = x0_player.GetTranslation(); vec.z() = float(water.GetTriggerBoundsWR().max.z()); + if (x0_player.x4fc_flatMoveSpeed >= 8.f) { - float maxVel = x0_player.GetBallMaxVelocity(); + const float maxVel = x0_player.GetBallMaxVelocity(); if (mgr.GetFluidPlaneManager()->GetLastSplashDeltaTime(x0_player.GetUniqueId()) >= (maxVel - x0_player.x4fc_flatMoveSpeed) / (maxVel - 8.f) * 0.1f) { mgr.GetFluidPlaneManager()->CreateSplash(x0_player.GetUniqueId(), mgr, water, vec, 0.f, state == CActor::EFluidState::EnteredFluid); } } + if (x0_player.x4fc_flatMoveSpeed >= 0.2f) { - float deltaTime = mgr.GetFluidPlaneManager()->GetLastRippleDeltaTime(x0_player.GetUniqueId()); + const float deltaTime = mgr.GetFluidPlaneManager()->GetLastRippleDeltaTime(x0_player.GetUniqueId()); float f0; if (x0_player.x4fc_flatMoveSpeed <= 15.f) { f0 = 0.13f; @@ -2088,17 +2240,20 @@ void CMorphBall::FluidFXThink(CActor::EFluidState state, CScriptWater& water, CS } void CMorphBall::LoadMorphBallModel(CStateManager& mgr) { - bool spiderBall = mgr.GetPlayerState()->HasPowerUp(CPlayerState::EItemType::SpiderBall); + const bool spiderBall = mgr.GetPlayerState()->HasPowerUp(CPlayerState::EItemType::SpiderBall); int modelIdx = int(mgr.GetPlayerState()->GetCurrentSuitRaw()); - if (mgr.GetPlayerState()->IsFusionEnabled()) + if (mgr.GetPlayerState()->IsFusionEnabled()) { modelIdx += 4; + } int loadModelId = modelIdx; - if (spiderBall) + if (spiderBall) { loadModelId += 4; - if (mgr.GetPlayerState()->IsFusionEnabled()) + } + if (mgr.GetPlayerState()->IsFusionEnabled()) { loadModelId += 100; + } if (loadModelId != x4_loadedModelId) { x4_loadedModelId = loadModelId; @@ -2143,13 +2298,13 @@ void CMorphBall::AddSpiderBallElectricalEffect() { gen.second = true; x1b6c_activeSpiderElectricList.emplace_back(idx, x1b80_rand.Range(4, 8)); - float sign = (x1b80_rand.Next() & 0x100) < 0x80 ? -1.f : 1.f; - float randDir = GetBallRadius() * 0.9f * sign; - float ang0 = zeus::degToRad(40.f - x1b80_rand.Float() * 80.f); - float ang1 = zeus::degToRad(40.f - x1b80_rand.Float() * 80.f + 90.f); + const float sign = (x1b80_rand.Next() & 0x100) < 0x80 ? -1.f : 1.f; + const float randDir = GetBallRadius() * 0.9f * sign; + const float ang0 = zeus::degToRad(40.f - x1b80_rand.Float() * 80.f); + const float ang1 = zeus::degToRad(40.f - x1b80_rand.Float() * 80.f + 90.f); zeus::CVector3f translation(std::sin(ang1) * std::cos(ang0) * sign * 0.6f + randDir * 1.32f, 0.6f * sign * std::sin(ang0), 0.6f * sign * std::cos(ang1) * std::cos(ang0)); - zeus::CVector3f transInc = (zeus::CVector3f(randDir, 0.f, 0.f) - translation) * (1.f / 6.f); + const zeus::CVector3f transInc = (zeus::CVector3f(randDir, 0.f, 0.f) - translation) * (1.f / 6.f); gen.first->DoSpiderBallWarmup(translation, transInc); break; } @@ -2157,7 +2312,7 @@ void CMorphBall::AddSpiderBallElectricalEffect() { void CMorphBall::UpdateSpiderBallElectricalEffects() { zeus::CTransform ballToWorld = GetBallToWorld(); - zeus::CVector3f ballTranslation = ballToWorld.origin; + const zeus::CVector3f ballTranslation = ballToWorld.origin; ballToWorld.origin = zeus::skZero3f; for (auto it = x1b6c_activeSpiderElectricList.begin(); it != x1b6c_activeSpiderElectricList.end();) { @@ -2178,13 +2333,14 @@ void CMorphBall::UpdateSpiderBallElectricalEffects() { } void CMorphBall::RenderSpiderBallElectricalEffect() const { - for (const CSpiderBallElectricityManager& effect : x1b6c_activeSpiderElectricList) + for (const CSpiderBallElectricityManager& effect : x1b6c_activeSpiderElectricList) { x19e4_spiderElectricGens[effect.x0_effectIdx].first->Render(); + } } void CMorphBall::RenderEnergyDrainEffects(const CStateManager& mgr) const { for (const CEnergyDrainSource& source : x0_player.x274_energyDrain.GetEnergyDrainSources()) { - if (const MP1::CMetroidBeta* metroid = + if (const auto* metroid = CPatterned::CastTo(mgr.GetObjectById(source.GetEnergyDrainSourceId()))) { metroid->RenderHitBallEffect(); break; @@ -2194,8 +2350,9 @@ void CMorphBall::RenderEnergyDrainEffects(const CStateManager& mgr) const { void CMorphBall::TouchModel(const CStateManager& mgr) const { x58_ballModel->Touch(mgr, x5c_ballModelShader); - if (mgr.GetPlayerState()->HasPowerUp(CPlayerState::EItemType::SpiderBall) && x60_spiderBallGlassModel) + if (mgr.GetPlayerState()->HasPowerUp(CPlayerState::EItemType::SpiderBall) && x60_spiderBallGlassModel) { x60_spiderBallGlassModel->Touch(mgr, x64_spiderBallGlassModelShader); + } x68_lowPolyBallModel->Touch(mgr, x6c_lowPolyBallModelShader); } @@ -2206,28 +2363,32 @@ void CMorphBall::TakeDamage(float dam) { return; } - if (dam >= 20.f) + if (dam >= 20.f) { x1e48_damageEffectDecaySpeed = 0.25f; - else if (dam > 5.f) + } else if (dam > 5.f) { x1e48_damageEffectDecaySpeed = 1.f - (dam - 5.f) / 15.f * 0.75f; - else + } else { x1e48_damageEffectDecaySpeed = 1.f; + } x1e44_damageEffect = 1.f; } void CMorphBall::StartLandingSfx() { - if (x0_player.GetVelocity().z() < -5.f && x1e36_landSfx != 0xffff) { - float vol = zeus::clamp(0.75f, 0.0125f * x0_player.GetLastVelocity().z() + 0.75f, 1.f); - CSfxHandle hnd = CSfxManager::SfxStart(x1e36_landSfx, vol, 0.f, true, 0x7f, false, kInvalidAreaId); - x0_player.ApplySubmergedPitchBend(hnd); + if (x0_player.GetVelocity().z() >= -5.f || x1e36_landSfx == 0xffff) { + return; } + + const float vol = zeus::clamp(0.75f, 0.0125f * x0_player.GetLastVelocity().z() + 0.75f, 1.f); + CSfxHandle hnd = CSfxManager::SfxStart(x1e36_landSfx, vol, 0.f, true, 0x7f, false, kInvalidAreaId); + x0_player.ApplySubmergedPitchBend(hnd); } void CMorphBall::Stop() { x19b0_effect_morphBallIceBreak.Lock(); - if (x19e0_effect_morphBallIceBreakGen) + if (x19e0_effect_morphBallIceBreakGen) { x19e0_effect_morphBallIceBreakGen.reset(); + } } void CMorphBall::StopSounds() { @@ -2244,8 +2405,9 @@ void CMorphBall::StopSounds() { void CMorphBall::StopEffects() { x19cc_wallSparkGen->SetParticleEmission(false); x1bc8_wakeEffectGens[7]->SetParticleEmission(false); - if (x1c0c_wakeEffectIdx != -1) + if (x1c0c_wakeEffectIdx != -1) { x1bc8_wakeEffectGens[x1c0c_wakeEffectIdx]->SetParticleEmission(false); + } } } // namespace urde diff --git a/Runtime/World/CMorphBall.hpp b/Runtime/World/CMorphBall.hpp index c7dfb633b..2d66e143c 100644 --- a/Runtime/World/CMorphBall.hpp +++ b/Runtime/World/CMorphBall.hpp @@ -249,8 +249,8 @@ public: void ComputeLiftForces(const zeus::CVector3f& controlForce, const zeus::CVector3f& velocity, const CStateManager& mgr); float CalculateSurfaceFriction() const; - void ApplyGravity(CStateManager& mgr); - void SpinToSpeed(float holdMag, zeus::CVector3f torque, float mag); + void ApplyGravity(const CStateManager& mgr); + void SpinToSpeed(float holdMag, const zeus::CVector3f& torque, float mag); float ComputeMaxSpeed() const; void Touch(CActor& actor, CStateManager& mgr); bool IsClimbable(const CCollisionInfo& cinfo) const; diff --git a/Runtime/World/CPathFindRegion.cpp b/Runtime/World/CPathFindRegion.cpp index 1a2f116f8..56f00621c 100644 --- a/Runtime/World/CPathFindRegion.cpp +++ b/Runtime/World/CPathFindRegion.cpp @@ -33,33 +33,43 @@ CPFRegion::CPFRegion(CMemoryInStream& in) { const CPFLink* CPFRegion::GetPathLink() const { return &xc_startLink[x4c_regionData->GetPathLink()]; } void CPFRegion::Fixup(CPFArea& area, u32& maxRegionNodes) { - if (x0_numNodes) + if (x0_numNodes != 0) { x4_startNode = &area.x140_nodes[reinterpret_cast(x4_startNode)]; - else + } else { x4_startNode = nullptr; - if (x8_numLinks) + } + + if (x8_numLinks != 0) { xc_startLink = &area.x148_links[reinterpret_cast(xc_startLink)]; - else + } else { xc_startLink = nullptr; + } + x4c_regionData = &area.x178_regionDatas[x24_regionIdx]; - if (x0_numNodes > maxRegionNodes) + if (x0_numNodes > maxRegionNodes) { maxRegionNodes = x0_numNodes; + } } bool CPFRegion::IsPointInside(const zeus::CVector3f& point) const { - if (!x34_aabb.pointInside(point)) + if (!x34_aabb.pointInside(point)) { return false; + } + u32 i; for (i = 0; i < x0_numNodes; ++i) { - CPFNode& node = x4_startNode[i]; - if ((point - node.GetPos()).dot(node.GetNormal()) < 0.f) + const CPFNode& node = x4_startNode[i]; + if ((point - node.GetPos()).dot(node.GetNormal()) < 0.f) { break; + } } - if (i != x0_numNodes) + + if (i != x0_numNodes) { return false; - zeus::CVector3f nodeToPoint = point - x4_startNode->GetPos(); - return nodeToPoint.dot(x18_normal) >= 0.f && - (nodeToPoint - x14_height * zeus::skUp).dot(x18_normal) <= 0.f; + } + + const zeus::CVector3f nodeToPoint = point - x4_startNode->GetPos(); + return nodeToPoint.dot(x18_normal) >= 0.f && (nodeToPoint - x14_height * zeus::skUp).dot(x18_normal) <= 0.f; } float CPFRegion::PointHeight(const zeus::CVector3f& point) const { @@ -73,13 +83,14 @@ bool CPFRegion::FindClosestPointOnPolygon(const std::vector& po for (i = 0; i < polyPoints.size(); ++i) { const zeus::CVector3f& p0 = polyPoints[i]; const zeus::CVector3f& p1 = polyPoints[(i + 1) % polyPoints.size()]; - if ((p1 - p0).cross(normal).dot(point - p0) < 0.f) + if ((p1 - p0).cross(normal).dot(point - p0) < 0.f) { break; + } } if (i == polyPoints.size()) { - float distToPoly = (polyPoints.front() - point).dot(normal); - float distToPolySq = distToPoly * distToPoly; + const float distToPoly = (polyPoints.front() - point).dot(normal); + const float distToPolySq = distToPoly * distToPoly; if (distToPolySq < x4c_regionData->GetBestPointDistanceSquared()) { found = true; x4c_regionData->SetBestPointDistanceSquared(distToPolySq); @@ -93,11 +104,12 @@ bool CPFRegion::FindClosestPointOnPolygon(const std::vector& po zeus::CVector3f p0ToP1 = p1 - p0; zeus::CVector3f p1ToPoint = point - p1; zeus::CVector3f sum = p1ToPoint + p0ToP1; + if (p0ToP1.cross(normal).dot(p1ToPoint) < 0.f && p0ToP1.dot(p1ToPoint) <= 0.f && sum.dot(p0ToP1) >= 0.f) { projected = true; p0ToP1.normalize(); sum -= p0ToP1.dot(sum) * p0ToP1; - float distSq = sum.magSquared(); + const float distSq = sum.magSquared(); if (distSq < x4c_regionData->GetBestPointDistanceSquared()) { found = true; x4c_regionData->SetBestPointDistanceSquared(distSq); @@ -110,7 +122,7 @@ bool CPFRegion::FindClosestPointOnPolygon(const std::vector& po if (!projected && !excludePolyPoints) { for (i = 0; i < polyPoints.size(); ++i) { const zeus::CVector3f& p0 = polyPoints[i]; - float distSq = (point - p0).magSquared(); + const float distSq = (point - p0).magSquared(); if (distSq < x4c_regionData->GetBestPointDistanceSquared()) { found = true; x4c_regionData->SetBestPointDistanceSquared(distSq); @@ -125,12 +137,14 @@ bool CPFRegion::FindClosestPointOnPolygon(const std::vector& po bool CPFRegion::FindBestPoint(std::vector& polyPoints, const zeus::CVector3f& point, u32 flags, float paddingSq) const { bool found = false; - bool isFlyer = (flags & 0x2) != 0; + const bool isFlyer = (flags & 0x2) != 0; + x4c_regionData->SetBestPointDistanceSquared(paddingSq); + if (!isFlyer) { for (u32 i = 0; i < x0_numNodes; ++i) { - CPFNode& node = x4_startNode[i]; - CPFNode& nextNode = x4_startNode[(i + 1) % x0_numNodes]; + const CPFNode& node = x4_startNode[i]; + const CPFNode& nextNode = x4_startNode[(i + 1) % x0_numNodes]; polyPoints.clear(); polyPoints.push_back(node.GetPos()); polyPoints.push_back(node.GetPos()); @@ -144,7 +158,7 @@ bool CPFRegion::FindBestPoint(std::vector& polyPoints, const ze polyPoints.clear(); for (u32 i = 0; i < x0_numNodes; ++i) { - CPFNode& node = x4_startNode[i]; + const CPFNode& node = x4_startNode[i]; polyPoints.push_back(node.GetPos()); } found |= FindClosestPointOnPolygon(polyPoints, x18_normal, point, false); @@ -152,7 +166,7 @@ bool CPFRegion::FindBestPoint(std::vector& polyPoints, const ze if (!isFlyer) { polyPoints.clear(); for (int i = int(x0_numNodes) - 1; i >= 0; --i) { - CPFNode& node = x4_startNode[i]; + const CPFNode& node = x4_startNode[i]; polyPoints.push_back(node.GetPos()); polyPoints.back().z() += x14_height; } @@ -162,14 +176,17 @@ bool CPFRegion::FindBestPoint(std::vector& polyPoints, const ze return found; } -void CPFRegion::SetLinkTo(s32 idx) { - if (x8_numLinks <= 0) +void CPFRegion::SetLinkTo(u32 idx) { + if (x8_numLinks <= 0) { return; - for (u32 i = 0; i < x8_numLinks; ++i) + } + + for (u32 i = 0; i < x8_numLinks; ++i) { if (xc_startLink[i].GetRegion() == idx) { Data()->SetPathLink(i); return; } + } } void CPFRegion::DropToGround(zeus::CVector3f& point) const { @@ -184,55 +201,59 @@ zeus::CVector3f CPFRegion::GetLinkMidPoint(const CPFLink& link) const { zeus::CVector3f CPFRegion::FitThroughLink2d(const zeus::CVector3f& p1, const CPFLink& link, const zeus::CVector3f& p2, float chRadius) const { - CPFNode& node = x4_startNode[link.GetNode()]; - CPFNode& nextNode = x4_startNode[(link.GetNode() + 1) % x0_numNodes]; - zeus::CVector3f nodeDelta = nextNode.GetPos() - node.GetPos(); + const CPFNode& node = x4_startNode[link.GetNode()]; + const CPFNode& nextNode = x4_startNode[(link.GetNode() + 1) % x0_numNodes]; + const zeus::CVector3f nodeDelta = nextNode.GetPos() - node.GetPos(); float t = 0.5f; + if (chRadius < 0.5f * link.Get2dWidth()) { zeus::CVector2f delta2d = nodeDelta.toVec2f(); delta2d *= link.GetOO2dWidth(); - zeus::CVector3f nodeToP1 = p1 - node.GetPos(); - float f27 = nodeToP1.dot(node.GetNormal()); - float f31 = delta2d.dot(nodeToP1.toVec2f()); - zeus::CVector3f nodeToP2 = p2 - node.GetPos(); - float f26 = -nodeToP2.dot(node.GetNormal()); - float f1b = delta2d.dot(nodeToP2.toVec2f()); - float f3 = f27 + f26; - if (f3 > FLT_EPSILON) + const zeus::CVector3f nodeToP1 = p1 - node.GetPos(); + const float f27 = nodeToP1.dot(node.GetNormal()); + const float f31 = delta2d.dot(nodeToP1.toVec2f()); + const zeus::CVector3f nodeToP2 = p2 - node.GetPos(); + const float f26 = -nodeToP2.dot(node.GetNormal()); + const float f1b = delta2d.dot(nodeToP2.toVec2f()); + const float f3 = f27 + f26; + if (f3 > FLT_EPSILON) { t = zeus::clamp(chRadius, 1.f / f3 * (f26 * f31 + f27 * f1b), link.Get2dWidth() - chRadius) * link.GetOO2dWidth(); + } } return nodeDelta * t + node.GetPos(); } zeus::CVector3f CPFRegion::FitThroughLink3d(const zeus::CVector3f& p1, const CPFLink& link, float regionHeight, const zeus::CVector3f& p2, float chRadius, float chHalfHeight) const { - CPFNode& node = x4_startNode[link.GetNode()]; - CPFNode& nextNode = x4_startNode[(link.GetNode() + 1) % x0_numNodes]; - zeus::CVector3f nodeDelta = nextNode.GetPos() - node.GetPos(); - float f25 = (p1 - node.GetPos()).dot(node.GetNormal()); - float f24 = (node.GetPos() - p2).dot(node.GetNormal()); - float f23 = f25 + f24; + const CPFNode& node = x4_startNode[link.GetNode()]; + const CPFNode& nextNode = x4_startNode[(link.GetNode() + 1) % x0_numNodes]; + const zeus::CVector3f nodeDelta = nextNode.GetPos() - node.GetPos(); + const float f25 = (p1 - node.GetPos()).dot(node.GetNormal()); + const float f24 = (node.GetPos() - p2).dot(node.GetNormal()); + const float f23 = f25 + f24; + #if 0 if (chRadius < 0.5f * link.Get2dWidth()) { zeus::CVector2f delta2d(nodeDelta.x, nodeDelta.y); delta2d *= link.GetOO2dWidth(); - zeus::CVector3f nodeToP1 = p1 - node.GetPos(); - float f29 = delta2d.dot(zeus::CVector2f(nodeToP1.y, nodeToP1.y)); - zeus::CVector3f nodeToP2 = p2 - node.GetPos(); - float f1b = delta2d.dot(zeus::CVector2f(nodeToP2.y, nodeToP2.y)); + const zeus::CVector3f nodeToP1 = p1 - node.GetPos(); + const float f29 = delta2d.dot(zeus::CVector2f(nodeToP1.y, nodeToP1.y)); + const zeus::CVector3f nodeToP2 = p2 - node.GetPos(); + const float f1b = delta2d.dot(zeus::CVector2f(nodeToP2.y, nodeToP2.y)); if (f23 > FLT_EPSILON) { - zeus::clamp(chRadius, 1.f / f23 * f24 * f29 + f25 * f1b, link.Get2dWidth() - chRadius) * - link.GetOO2dWidth(); + zeus::clamp(chRadius, 1.f / f23 * f24 * f29 + f25 * f1b, link.Get2dWidth() - chRadius) * link.GetOO2dWidth(); } } #endif - zeus::CVector3f midPoint = nodeDelta * 0.5f + node.GetPos(); + + const zeus::CVector3f midPoint = nodeDelta * 0.5f + node.GetPos(); float z; if (chHalfHeight < 0.5f * regionHeight) { - float minZ = chHalfHeight + midPoint.z(); + const float minZ = chHalfHeight + midPoint.z(); z = 0.5f * (p1.z() + p2.z()); - if (f23 > FLT_EPSILON) + if (f23 > FLT_EPSILON) { z = (f24 * p1.z() + f25 * p2.z()) / f23; + } z = zeus::clamp(minZ, z, regionHeight + midPoint.z() - chHalfHeight); } else { z = (p1.z() + p2.z()) * 0.5f; diff --git a/Runtime/World/CPathFindRegion.hpp b/Runtime/World/CPathFindRegion.hpp index a0cc8509e..5bb294f88 100644 --- a/Runtime/World/CPathFindRegion.hpp +++ b/Runtime/World/CPathFindRegion.hpp @@ -52,27 +52,35 @@ class CPFRegion { public: CPFRegion() = default; explicit CPFRegion(CMemoryInStream& in); + void SetData(CPFRegionData* data) { x4c_regionData = data; } - CPFRegionData* Data() const { return x4c_regionData; } + CPFRegionData* Data() { return x4c_regionData; } + const CPFRegionData* Data() const { return x4c_regionData; } + u32 GetIndex() const { return x24_regionIdx; } float GetHeight() const { return x14_height; } const CPFLink* GetPathLink() const; u32 GetNumLinks() const { return x8_numLinks; } u32 GetFlags() const { return x10_flags; } const CPFLink* GetLink(u32 i) const { return xc_startLink + i; } + void SetCentroid(const zeus::CVector3f& c) { x28_centroid = c; } const zeus::CVector3f& GetCentroid() const { return x28_centroid; } + void Fixup(CPFArea& area, u32& maxRegionNodes); bool IsPointInside(const zeus::CVector3f& point) const; + const zeus::CVector3f& GetNormal() const { return x18_normal; } u32 GetNumNodes() const { return x0_numNodes; } const CPFNode* GetNode(u32 i) const { return x4_startNode + i; } + float PointHeight(const zeus::CVector3f& point) const; bool FindClosestPointOnPolygon(const std::vector&, const zeus::CVector3f&, const zeus::CVector3f&, bool) const; bool FindBestPoint(std::vector& polyPoints, const zeus::CVector3f& point, u32 flags, float paddingSq) const; - void SetLinkTo(s32 idx); + + void SetLinkTo(u32 idx); void DropToGround(zeus::CVector3f& point) const; zeus::CVector3f GetLinkMidPoint(const CPFLink& link) const; zeus::CVector3f FitThroughLink2d(const zeus::CVector3f& p1, const CPFLink& link, const zeus::CVector3f& p2, diff --git a/Runtime/World/CPatterned.cpp b/Runtime/World/CPatterned.cpp index e1d4210f0..36a68c024 100644 --- a/Runtime/World/CPatterned.cpp +++ b/Runtime/World/CPatterned.cpp @@ -881,15 +881,20 @@ void CPatterned::TryLoopReaction(CStateManager& mgr, int arg) { void CPatterned::TryProjectileAttack(CStateManager&, int arg) { x450_bodyController->GetCommandMgr().DeliverCmd(CBCProjectileAttackCmd(pas::ESeverity(arg), x2e0_destPos, false)); } + +void CPatterned::TryMeleeAttack_TargetPos(CStateManager& mgr, int arg) { + x450_bodyController->GetCommandMgr().DeliverCmd(CBCMeleeAttackCmd(pas::ESeverity(arg), x2e0_destPos)); +} + void CPatterned::TryMeleeAttack(CStateManager& mgr, int arg) { x450_bodyController->GetCommandMgr().DeliverCmd(CBCMeleeAttackCmd(pas::ESeverity(arg))); } -void CPatterned::TryGenerate(CStateManager& mgr, int arg) { +void CPatterned::TryGenerateNoXf(CStateManager& mgr, int arg) { x450_bodyController->GetCommandMgr().DeliverCmd(CBCGenerateCmd(pas::EGenerateType(arg), x2e0_destPos, false)); } -void CPatterned::TryGenerateNoXf(CStateManager& mgr, int arg) { +void CPatterned::TryGenerate(CStateManager& mgr, int arg) { x450_bodyController->GetCommandMgr().DeliverCmd(CBCGenerateCmd(pas::EGenerateType::Zero, x2e0_destPos, true)); } @@ -941,6 +946,10 @@ void CPatterned::TryKnockBack(CStateManager& mgr, int arg) { x450_bodyController->GetCommandMgr().DeliverCmd(CBCKnockBackCmd(GetTranslation(), pas::ESeverity(arg))); } +void CPatterned::TryKnockBack_Front(CStateManager& mgr, int arg) { + x450_bodyController->GetCommandMgr().DeliverCmd(CBCKnockBackCmd(GetTransform().frontVector(), pas::ESeverity(arg))); +} + void CPatterned::TryGenerateDeactivate(urde::CStateManager& mgr, int arg) { x450_bodyController->GetCommandMgr().DeliverCmd(CBCGenerateCmd(pas::EGenerateType(arg), zeus::skZero3f)); } diff --git a/Runtime/World/CPatterned.hpp b/Runtime/World/CPatterned.hpp index a44b37634..59b55c861 100644 --- a/Runtime/World/CPatterned.hpp +++ b/Runtime/World/CPatterned.hpp @@ -320,9 +320,10 @@ public: void TryCommand(CStateManager& mgr, pas::EAnimationState state, CPatternedTryFunc func, int arg); void TryLoopReaction(CStateManager& mgr, int arg); void TryProjectileAttack(CStateManager& mgr, int arg); + void TryMeleeAttack_TargetPos(CStateManager& mgr, int arg); void TryMeleeAttack(CStateManager& mgr, int arg); - void TryGenerate(CStateManager& mgr, int arg); void TryGenerateNoXf(CStateManager& mgr, int arg); + void TryGenerate(CStateManager& mgr, int arg); void TryJump(CStateManager& mgr, int arg); void TryTurn(CStateManager& mgr, int arg); void TryGetUp(CStateManager& mgr, int arg); @@ -334,6 +335,7 @@ public: void TryCover(CStateManager& mgr, int arg); void TryWallHang(CStateManager& mgr, int arg); void TryKnockBack(CStateManager& mgr, int arg); + void TryKnockBack_Front(CStateManager& mgr, int arg); void TryGenerateDeactivate(CStateManager& mgr, int arg); void TryStep(CStateManager& mgr, int arg); diff --git a/Runtime/World/CPlayer.cpp b/Runtime/World/CPlayer.cpp index 33b8e64dd..ae83548d3 100644 --- a/Runtime/World/CPlayer.cpp +++ b/Runtime/World/CPlayer.cpp @@ -1267,7 +1267,7 @@ static CAssetId UpdatePersistentScanPercent(u32 prevLogScans, u32 logScans, u32 if (scanPercentProgStep > prevScanPercentProgStep) { const char* const messageResBase = UnlockMessageResBases[zeus::clamp(0, scanPercentProgStep - 1, 1)]; const auto message = std::string(messageResBase).append(1, firstTime ? '1' : '2'); - const auto id = g_ResFactory->GetResourceIdByName(message); + const auto* const id = g_ResFactory->GetResourceIdByName(message); if (id != nullptr) { return id->id; } @@ -2376,47 +2376,56 @@ bool CPlayer::SetAreaPlayerHint(const CScriptPlayerHint& hint, CStateManager& mg } void CPlayer::AddToPlayerHintRemoveList(TUniqueId id, CStateManager& mgr) { - if (const TCastToConstPtr hint = mgr.ObjectById(id)) { - for (const TUniqueId existId : x93c_playerHintsToRemove) { - if (id == existId) { - return; - } - } + const TCastToConstPtr hint = mgr.ObjectById(id); + if (!hint) { + return; + } - if (x93c_playerHintsToRemove.size() != 32) { - x93c_playerHintsToRemove.push_back(id); + for (const TUniqueId existId : x93c_playerHintsToRemove) { + if (id == existId) { + return; } } + + if (x93c_playerHintsToRemove.size() != 32) { + x93c_playerHintsToRemove.push_back(id); + } } void CPlayer::AddToPlayerHintAddList(TUniqueId id, CStateManager& mgr) { - if (const TCastToConstPtr hint = mgr.ObjectById(id)) { - for (const TUniqueId existId : x980_playerHintsToAdd) { - if (id == existId) { - return; - } - } + const TCastToConstPtr hint = mgr.ObjectById(id); + if (!hint) { + return; + } - if (x980_playerHintsToAdd.size() != 32) { - x980_playerHintsToAdd.push_back(id); + for (const TUniqueId existId : x980_playerHintsToAdd) { + if (id == existId) { + return; } } + + if (x980_playerHintsToAdd.size() != 32) { + x980_playerHintsToAdd.push_back(id); + } } void CPlayer::DeactivatePlayerHint(TUniqueId id, CStateManager& mgr) { - if (TCastToPtr hint = mgr.ObjectById(id)) { - for (const TUniqueId existId : x93c_playerHintsToRemove) { - if (id == existId) { - return; - } - } + const TCastToPtr hint = mgr.ObjectById(id); + if (!hint) { + return; + } - if (x93c_playerHintsToRemove.size() != 32) { - x93c_playerHintsToRemove.push_back(id); - hint->ClearObjectList(); - hint->SetDeactivated(); + for (const TUniqueId existId : x93c_playerHintsToRemove) { + if (id == existId) { + return; } } + + if (x93c_playerHintsToRemove.size() != 32) { + x93c_playerHintsToRemove.push_back(id); + hint->ClearObjectList(); + hint->SetDeactivated(); + } } void CPlayer::UpdatePlayerHints(CStateManager& mgr) { @@ -3233,7 +3242,9 @@ void CPlayer::UpdateGunTransform(const zeus::CVector3f& gunPos, CStateManager& m void CPlayer::UpdateAssistedAiming(const zeus::CTransform& xf, const CStateManager& mgr) { zeus::CTransform assistXf = xf; - if (TCastToConstPtr target = mgr.GetObjectById(x3f4_aimTarget)) { + const TCastToConstPtr target = mgr.GetObjectById(x3f4_aimTarget); + + if (target) { zeus::CVector3f gunToTarget = x480_assistedTargetAim - xf.origin; zeus::CVector3f gunToTargetFlat = gunToTarget; gunToTargetFlat.z() = 0.f; @@ -4646,7 +4657,7 @@ void CPlayer::UpdateOrbitInput(const CFinalInput& input, CStateManager& mgr) { } break; case EPlayerOrbitState::OrbitObject: - if (const TCastToConstPtr point = mgr.GetObjectById(x310_orbitTargetId)) { + if (TCastToConstPtr(mgr.GetObjectById(x310_orbitTargetId))) { if (ValidateCurrentOrbitTargetId(mgr) == EOrbitValidationResult::OK) { UpdateOrbitPosition(g_tweakPlayer->GetOrbitNormalDistance(int(x308_orbitType)), mgr); } else { @@ -4729,7 +4740,7 @@ void CPlayer::UpdateOrbitInput(const CFinalInput& input, CStateManager& mgr) { case EPlayerOrbitState::NoOrbit: break; case EPlayerOrbitState::OrbitObject: - if (TCastToConstPtr point = mgr.GetObjectById(x310_orbitTargetId)) { + if (TCastToConstPtr(mgr.GetObjectById(x310_orbitTargetId))) { BreakGrapple(EPlayerOrbitRequest::Default, mgr); } else { SetOrbitRequest(EPlayerOrbitRequest::StopOrbit, mgr); diff --git a/Runtime/World/CScriptDebris.cpp b/Runtime/World/CScriptDebris.cpp index 9dcb83f5b..f724dd40f 100644 --- a/Runtime/World/CScriptDebris.cpp +++ b/Runtime/World/CScriptDebris.cpp @@ -89,6 +89,7 @@ CScriptDebris::CScriptDebris(TUniqueId uid, std::string_view name, const CEntity , x281_27_particle2GlobalTranslation(particle2GlobalTranslation) , x281_28_deferDeleteTillParticle2Done(deferDeleteTillParticle2Done) , x281_30_debrisExtended(true) +, x281_31_dieOnProjectile(dieOnProjectile) , x282_24_noBounce(noBounce) , x288_linConeAngle(linConeAngle) , x28c_linMinMag(linMinMag) diff --git a/Runtime/World/CScriptDebris.hpp b/Runtime/World/CScriptDebris.hpp index f32d1a4ac..9d44ee853 100644 --- a/Runtime/World/CScriptDebris.hpp +++ b/Runtime/World/CScriptDebris.hpp @@ -14,9 +14,9 @@ namespace urde { class CElementGen; class CScriptDebris : public CPhysicsActor { public: - enum class EScaleType { NoScale, EndsToZero }; + enum class EScaleType : u8 { NoScale, EndsToZero }; - enum class EOrientationType { NotOriented, AlongVelocity, ToObject, AlongCollisionNormal }; + enum class EOrientationType : u8 { NotOriented, AlongVelocity, ToObject, AlongCollisionNormal }; private: zeus::CVector3f x258_velocity; diff --git a/Runtime/World/CScriptGunTurret.cpp b/Runtime/World/CScriptGunTurret.cpp index 9f26a7a41..c1a5b726a 100644 --- a/Runtime/World/CScriptGunTurret.cpp +++ b/Runtime/World/CScriptGunTurret.cpp @@ -381,8 +381,8 @@ void CScriptGunTurret::SetupCollisionManager(CStateManager& mgr) { x49c_collisionManager->SetActive(mgr, GetActive()); for (int i = 0; i < x49c_collisionManager->GetNumCollisionActors(); ++i) { - auto& desc = x49c_collisionManager->GetCollisionDescFromIndex(i); - if (TCastToPtr cAct = mgr.ObjectById(desc.GetCollisionActorId())) { + const auto& desc = x49c_collisionManager->GetCollisionDescFromIndex(i); + if (const TCastToPtr cAct = mgr.ObjectById(desc.GetCollisionActorId())) { cAct->AddMaterial(EMaterialTypes::ProjectilePassthrough, mgr); cAct->SetMaterialFilter(CMaterialFilter::MakeIncludeExclude({EMaterialTypes::Player}, {EMaterialTypes::Character, EMaterialTypes::NoStaticCollision, EMaterialTypes::NoPlatformCollision})); diff --git a/Runtime/World/CStateMachine.cpp b/Runtime/World/CStateMachine.cpp index 1208afb7b..1e4a4c034 100644 --- a/Runtime/World/CStateMachine.cpp +++ b/Runtime/World/CStateMachine.cpp @@ -14,7 +14,7 @@ CStateMachine::CStateMachine(CInputStream& in) { for (u32 i = 0; i < stateCount; ++i) { std::string name = in.readString(31, false); - CAiStateFunc func = CAi::GetStateFunc(name.c_str()); + CAiStateFunc func = CAi::GetStateFunc(name); x0_states.emplace_back(func, name.c_str()); } @@ -28,14 +28,14 @@ CStateMachine::CStateMachine(CInputStream& in) { x0_states[i].SetTriggers(firstTrig); x10_triggers.resize(x10_triggers.size() + x0_states[i].GetNumTriggers()); - for (u32 j = 0; j < x0_states[i].GetNumTriggers(); ++j) { - u32 triggerCount = in.readUint32Big(); - u32 lastTriggerIdx = triggerCount - 1; + for (s32 j = 0; j < x0_states[i].GetNumTriggers(); ++j) { + const u32 triggerCount = in.readUint32Big(); + const u32 lastTriggerIdx = triggerCount - 1; for (u32 k = 0; k < triggerCount; ++k) { std::string name = in.readString(31, false); - bool isNot = name.front() == '!'; - CAiTriggerFunc func = CAi::GetTrigerFunc(isNot ? name.c_str() + 1 : name.c_str()); - float arg = in.readFloatBig(); + const bool isNot = name.front() == '!'; + const CAiTriggerFunc func = CAi::GetTriggerFunc(isNot ? name.c_str() + 1 : name.c_str()); + const float arg = in.readFloatBig(); CAiTrigger* newTrig; if (k < lastTriggerIdx) { newTrig = &x10_triggers.emplace_back(); diff --git a/Runtime/World/CWallWalker.cpp b/Runtime/World/CWallWalker.cpp index 80cc249a8..673150ef6 100644 --- a/Runtime/World/CWallWalker.cpp +++ b/Runtime/World/CWallWalker.cpp @@ -53,11 +53,12 @@ void CWallWalker::AlignToFloor(CStateManager& mgr, float radius, const zeus::CVe zeus::CAABox aabb(newPos - margin, newPos + margin); CAreaCollisionCache ccache(aabb); CGameCollision::BuildAreaCollisionCache(mgr, ccache); - if (x5d6_25_hasAlignSurface) + if (x5d6_25_hasAlignSurface) { x5d6_25_hasAlignSurface = PointOnSurface(x568_alignNormal, newPos); + } if (!x5d6_25_hasAlignSurface || !(x5d4_thinkCounter & 0x3)) { - for (auto& leaf : ccache) { - for (auto& node : leaf) { + for (const auto& leaf : ccache) { + for (const auto& node : leaf) { CAreaOctTree::TriListReference triArr = node.GetTriangleArray(); for (u16 i = 0; i < triArr.GetSize(); ++i) { u16 triIdx = triArr.GetAt(i); diff --git a/Runtime/rstl.hpp b/Runtime/rstl.hpp index d917afb10..40bf68ff4 100644 --- a/Runtime/rstl.hpp +++ b/Runtime/rstl.hpp @@ -119,106 +119,8 @@ public: T& operator[](std::ptrdiff_t i) const { return const_cast(const_iterator::m_val)[i]; } }; - class const_reverse_iterator { - friend class _reserved_vector_base; - - protected: - const T* m_val; - - public: - explicit const_reverse_iterator(const T* val) : m_val(val) {} - using value_type = T; - using difference_type = std::ptrdiff_t; - using pointer = T*; - using reference = T&; - using iterator_category = std::random_access_iterator_tag; - - const T& operator*() const { return *m_val; } - const T* operator->() const { return m_val; } - const_reverse_iterator& operator++() { - --m_val; - return *this; - } - const_reverse_iterator& operator--() { - ++m_val; - return *this; - } - const_reverse_iterator operator++(int) { - auto ret = *this; - --m_val; - return ret; - } - const_reverse_iterator operator--(int) { - auto ret = *this; - ++m_val; - return ret; - } - bool operator!=(const const_reverse_iterator& other) const { return m_val != other.m_val; } - bool operator==(const const_reverse_iterator& other) const { return m_val == other.m_val; } - const_reverse_iterator operator+(std::ptrdiff_t i) const { return const_reverse_iterator(m_val - i); } - const_reverse_iterator operator-(std::ptrdiff_t i) const { return const_reverse_iterator(m_val + i); } - const_reverse_iterator& operator+=(std::ptrdiff_t i) { - m_val -= i; - return *this; - } - const_reverse_iterator& operator-=(std::ptrdiff_t i) { - m_val += i; - return *this; - } - std::ptrdiff_t operator-(const const_reverse_iterator& it) const { return it.m_val - m_val; } - bool operator>(const const_iterator& it) const { return it.m_val > m_val; } - bool operator<(const const_iterator& it) const { return it.m_val < m_val; } - bool operator>=(const const_iterator& it) const { return it.m_val >= m_val; } - bool operator<=(const const_iterator& it) const { return it.m_val <= m_val; } - const T& operator[](std::ptrdiff_t i) const { return m_val[-i]; } - }; - - class reverse_iterator : public const_reverse_iterator { - friend class _reserved_vector_base; - - public: - explicit reverse_iterator(T* val) : const_reverse_iterator(val) {} - T& operator*() const { return *const_cast(const_reverse_iterator::m_val); } - T* operator->() const { return const_cast(const_reverse_iterator::m_val); } - reverse_iterator& operator++() { - --const_reverse_iterator::m_val; - return *this; - } - reverse_iterator& operator--() { - ++const_reverse_iterator::m_val; - return *this; - } - reverse_iterator operator++(int) { - auto ret = *this; - --const_reverse_iterator::m_val; - return ret; - } - reverse_iterator operator--(int) { - auto ret = *this; - ++const_reverse_iterator::m_val; - return ret; - } - reverse_iterator operator+(std::ptrdiff_t i) const { - return reverse_iterator(const_cast(const_reverse_iterator::m_val) - i); - } - reverse_iterator operator-(std::ptrdiff_t i) const { - return reverse_iterator(const_cast(const_reverse_iterator::m_val) + i); - } - reverse_iterator& operator+=(std::ptrdiff_t i) { - const_reverse_iterator::m_val -= i; - return *this; - } - reverse_iterator& operator-=(std::ptrdiff_t i) { - const_reverse_iterator::m_val += i; - return *this; - } - std::ptrdiff_t operator-(const reverse_iterator& it) const { return it.m_val - const_reverse_iterator::m_val; } - bool operator>(const const_reverse_iterator& it) const { return it.m_val > const_reverse_iterator::m_val; } - bool operator<(const const_reverse_iterator& it) const { return it.m_val < const_reverse_iterator::m_val; } - bool operator>=(const const_reverse_iterator& it) const { return it.m_val >= const_reverse_iterator::m_val; } - bool operator<=(const const_reverse_iterator& it) const { return it.m_val <= const_reverse_iterator::m_val; } - T& operator[](std::ptrdiff_t i) const { return const_cast(const_reverse_iterator::m_val)[-i]; } - }; + using reverse_iterator = decltype(std::make_reverse_iterator(iterator{nullptr})); + using const_reverse_iterator = decltype(std::make_reverse_iterator(const_iterator{nullptr})); protected: static iterator _const_cast_iterator(const const_iterator& it) { return iterator(const_cast(it.m_val)); } @@ -540,16 +442,12 @@ public: [[nodiscard]] const_iterator cbegin() const noexcept { return begin(); } [[nodiscard]] const_iterator cend() const noexcept { return end(); } - [[nodiscard]] const_reverse_iterator rbegin() const noexcept { - return const_reverse_iterator(std::addressof(_value(x0_size - 1))); - } - [[nodiscard]] const_reverse_iterator rend() const noexcept { - return const_reverse_iterator(std::addressof(_value(-1))); - } - [[nodiscard]] reverse_iterator rbegin() noexcept { return reverse_iterator(std::addressof(_value(x0_size - 1))); } - [[nodiscard]] reverse_iterator rend() noexcept { return reverse_iterator(std::addressof(_value(-1))); } - [[nodiscard]] const_reverse_iterator crbegin() const noexcept { return rbegin(); } - [[nodiscard]] const_reverse_iterator crend() const noexcept { return rend(); } + [[nodiscard]] auto rbegin() const noexcept { return std::make_reverse_iterator(end()); } + [[nodiscard]] auto rend() const noexcept { return std::make_reverse_iterator(begin()); } + [[nodiscard]] auto rbegin() noexcept { return std::make_reverse_iterator(end()); } + [[nodiscard]] auto rend() noexcept { return std::make_reverse_iterator(begin()); } + [[nodiscard]] auto crbegin() const noexcept { return rbegin(); } + [[nodiscard]] auto crend() const noexcept { return rend(); } [[nodiscard]] T& operator[](size_t idx) { #ifndef NDEBUG @@ -608,16 +506,12 @@ public: [[nodiscard]] const_iterator cbegin() const noexcept { return begin(); } [[nodiscard]] const_iterator cend() const noexcept { return end(); } - [[nodiscard]] const_reverse_iterator rbegin() const noexcept { - return const_reverse_iterator(std::addressof(_value(x0_size - 1))); - } - [[nodiscard]] const_reverse_iterator rend() const noexcept { - return const_reverse_iterator(std::addressof(_value(-1))); - } - [[nodiscard]] reverse_iterator rbegin() noexcept { return reverse_iterator(std::addressof(_value(x0_size - 1))); } - [[nodiscard]] reverse_iterator rend() noexcept { return reverse_iterator(std::addressof(_value(-1))); } - [[nodiscard]] const_reverse_iterator crbegin() const noexcept { return rbegin(); } - [[nodiscard]] const_reverse_iterator crend() const noexcept { return rend(); } + [[nodiscard]] auto rbegin() const noexcept { return std::make_reverse_iterator(end()); } + [[nodiscard]] auto rend() const noexcept { return std::make_reverse_iterator(begin()); } + [[nodiscard]] auto rbegin() noexcept { return std::make_reverse_iterator(end()); } + [[nodiscard]] auto rend() noexcept { return std::make_reverse_iterator(begin()); } + [[nodiscard]] auto crbegin() const noexcept { return rbegin(); } + [[nodiscard]] auto crend() const noexcept { return rend(); } [[nodiscard]] T& operator[](size_t idx) { return _value(idx); } [[nodiscard]] const T& operator[](size_t idx) const { return _value(idx); } diff --git a/Shaders/shader_CFluidPlaneShaderMetal.cpp b/Shaders/shader_CFluidPlaneShaderMetal.cpp index f8bda5069..728d580a3 100644 --- a/Shaders/shader_CFluidPlaneShaderMetal.cpp +++ b/Shaders/shader_CFluidPlaneShaderMetal.cpp @@ -376,7 +376,7 @@ static std::string _BuildFS(const SFluidPlaneShaderInfo& info) { if (info.m_hasEnvMap) fmt::print(out, FMT_STRING(",texture2d envMap [[ texture({}) ]]"), nextTex++); if (info.m_hasEnvBumpMap) - fmt::print(out, FMT_STRING(",exture2d envBumpMap [[ texture({}) ]]"), nextTex++); + fmt::print(out, FMT_STRING(",texture2d envBumpMap [[ texture({}) ]]"), nextTex++); if (info.m_hasLightmap) fmt::print(out, FMT_STRING(",texture2d lightMap [[ texture({}) ]]"), nextTex++); out << '\n';