diff --git a/run-clang-format.ps1 b/run-clang-format.ps1 index 28a20c8d..ec7b1785 100644 --- a/run-clang-format.ps1 +++ b/run-clang-format.ps1 @@ -34,11 +34,11 @@ if (-not (Test-Path $clangFormatFilePath) -or ($currentVersion -ne $requiredVers Remove-Item $llvmInstallerPath -Force } -$basePath = (Resolve-Path .).Path +$basePath = Join-Path (Get-Location).Path "src/port" $files = Get-ChildItem -Path $basePath -Recurse -File ` | Where-Object { ($_.Extension -eq '.c' -or $_.Extension -eq '.cpp' -or ` (($_.Extension -eq '.h' -or $_.Extension -eq '.hpp') -and ` - (-not ($_.FullName -like "*\src/port\*" -or $_.FullName -like "*\include\*")))) -and ` + (-not ($_.FullName -like "*\src\*" -or $_.FullName -like "*\include\*")))) -and ` (-not ($_.FullName -like "*\assets\*" -or $_.FullName -like "*\build\*")) } for ($i = 0; $i -lt $files.Length; $i++) { diff --git a/run-clang-format.sh b/run-clang-format.sh old mode 100644 new mode 100755 index 32351e37..679b14ca --- a/run-clang-format.sh +++ b/run-clang-format.sh @@ -33,4 +33,4 @@ else CLANG_FORMAT="clang-format" fi -find src -type f \( -name "*.c" -o -name "*.cpp" -o \( \( -name "*.h" -o -name "*.hpp" \) ! -path "src/port/*" ! -path "include/*" \) \) ! -path "assets/*" -print0 | xargs -0 $CLANG_FORMAT -i --verbose +find src/port -type f \( -name "*.c" -o -name "*.cpp" -o \( \( -name "*.h" -o -name "*.hpp" \) ! -path "src/*" ! -path "include/*" \) \) ! -path "assets/*" -print0 | xargs -0 $CLANG_FORMAT -i --verbose diff --git a/src/port/Engine.cpp b/src/port/Engine.cpp index 5ad17f5e..73593f56 100644 --- a/src/port/Engine.cpp +++ b/src/port/Engine.cpp @@ -53,7 +53,6 @@ float previousImGuiScale = defaultImGuiScale; namespace fs = std::filesystem; - extern "C" { #include "sm64.h" #include "audio/external.h" @@ -64,7 +63,7 @@ bool prevAltAssets = false; GameEngine* GameEngine::Instance; -GameEngine::GameEngine(): dictionary(nullptr) { +GameEngine::GameEngine() : dictionary(nullptr) { this->context = Ship::Context::CreateUninitializedInstance("Ghostship", "sm64", "ghostship.cfg.json"); #ifdef __SWITCH__ @@ -83,8 +82,10 @@ GameEngine::GameEngine(): dictionary(nullptr) { if (std::filesystem::exists(main_path)) { archiveFiles.push_back(main_path); } else { - if (ShowYesNoBox("Ghostship - Asset Extraction", "Please provide a Super Mario 64 ROM.\n\nSupported Versions:\nUS\nJP\n\nAssets will be extracted into an O2R file.") == IDYES) { - if(!GenAssetFile()){ + if (ShowYesNoBox("Ghostship - Asset Extraction", + "Please provide a Super Mario 64 ROM.\n\nSupported Versions:\nUS\nJP\n\nAssets will be " + "extracted into an O2R file.") == IDYES) { + if (!GenAssetFile()) { ShowMessage("Error", "An error occured, no O2R file was generated.\n\nExiting..."); exit(1); } else { @@ -99,8 +100,7 @@ GameEngine::GameEngine(): dictionary(nullptr) { archiveFiles.push_back(assets_path); } - if (const std::string patches_path = Ship::Context::GetPathRelativeToAppDirectory("mods"); - !patches_path.empty()) { + if (const std::string patches_path = Ship::Context::GetPathRelativeToAppDirectory("mods"); !patches_path.empty()) { if (!std::filesystem::exists(patches_path)) { std::filesystem::create_directories(patches_path); } @@ -135,12 +135,12 @@ GameEngine::GameEngine(): dictionary(nullptr) { #ifndef __SWITCH__ Ship::Context::GetInstance()->GetLogger()->set_level( - (spdlog::level::level_enum) CVarGetInteger("gDeveloperTools.LogLevel", 1)); + (spdlog::level::level_enum)CVarGetInteger("gDeveloperTools.LogLevel", 1)); Ship::Context::GetInstance()->GetLogger()->set_pattern("[%H:%M:%S.%e] [%s:%#] [%l] %v"); #endif Ship::Context::GetInstance()->GetLogger()->set_level( - (spdlog::level::level_enum) CVarGetInteger("gDeveloperTools.LogLevel", 1)); + (spdlog::level::level_enum)CVarGetInteger("gDeveloperTools.LogLevel", 1)); Ship::Context::GetInstance()->GetLogger()->set_pattern("[%H:%M:%S.%e] [%s:%#] [%l] %v"); window->SetTargetFps(60); @@ -149,31 +149,55 @@ GameEngine::GameEngine(): dictionary(nullptr) { auto loader = context->GetResourceManager()->GetResourceLoader(); auto blobFactory = std::make_shared(); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Animation", static_cast(SM64::ResourceType::Anim), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "AudioBank", static_cast(SM64::ResourceType::Bank), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "AudioSample", static_cast(SM64::ResourceType::Sample), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "AudioSequence", static_cast(SM64::ResourceType::Sequence), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Dialog", static_cast(SM64::ResourceType::SDialog), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Dictionary", static_cast(SM64::ResourceType::Dictionary), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Texture", static_cast(Fast::ResourceType::Texture), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Texture", static_cast(Fast::ResourceType::Texture), 1); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Vertex", static_cast(Fast::ResourceType::Vertex), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "DisplayList", static_cast(Fast::ResourceType::DisplayList), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Matrix", static_cast(Fast::ResourceType::Matrix), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Light", static_cast(Fast::ResourceType::Light), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "AssetArray", static_cast(SM64::ResourceType::AssetArray), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Trajectory", static_cast(SM64::ResourceType::Trajectory), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Movtex", static_cast(SM64::ResourceType::Movtex), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Animation", + static_cast(SM64::ResourceType::Anim), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "AudioBank", + static_cast(SM64::ResourceType::Bank), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, + "AudioSample", static_cast(SM64::ResourceType::Sample), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, + "AudioSequence", static_cast(SM64::ResourceType::Sequence), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Dialog", + static_cast(SM64::ResourceType::SDialog), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Dictionary", + static_cast(SM64::ResourceType::Dictionary), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, + "Texture", static_cast(Fast::ResourceType::Texture), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, + "Texture", static_cast(Fast::ResourceType::Texture), 1); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, + "Vertex", static_cast(Fast::ResourceType::Vertex), 0); + loader->RegisterResourceFactory(std::make_shared(), + RESOURCE_FORMAT_BINARY, "DisplayList", + static_cast(Fast::ResourceType::DisplayList), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, + "Matrix", static_cast(Fast::ResourceType::Matrix), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, + "Light", static_cast(Fast::ResourceType::Light), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, + "AssetArray", static_cast(SM64::ResourceType::AssetArray), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Trajectory", + static_cast(SM64::ResourceType::Trajectory), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Movtex", + static_cast(SM64::ResourceType::Movtex), 0); // TODO: This shit needs to change, i mean why i have 5 factories doing the same thing xD - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "GenericArray", static_cast(SM64::ResourceType::GenericArray), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Collision", static_cast(SM64::ResourceType::Collision), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "PaintingData", static_cast(SM64::ResourceType::PaintingData), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "MacroObject", static_cast(SM64::ResourceType::MacroObject), 0); + loader->RegisterResourceFactory(std::make_shared(), + RESOURCE_FORMAT_BINARY, "GenericArray", + static_cast(SM64::ResourceType::GenericArray), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Collision", + static_cast(SM64::ResourceType::Collision), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "PaintingData", + static_cast(SM64::ResourceType::PaintingData), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "MacroObject", + static_cast(SM64::ResourceType::MacroObject), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "MovtexQuad", static_cast(SM64::ResourceType::MovtexQuad), 0); - loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Painting", static_cast(SM64::ResourceType::Painting), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "MovtexQuad", + static_cast(SM64::ResourceType::MovtexQuad), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Painting", + static_cast(SM64::ResourceType::Painting), 0); - loader->RegisterResourceFactory(blobFactory, RESOURCE_FORMAT_BINARY, "Blob", static_cast(Ship::ResourceType::Blob), 0); + loader->RegisterResourceFactory(blobFactory, RESOURCE_FORMAT_BINARY, "Blob", + static_cast(Ship::ResourceType::Blob), 0); prevAltAssets = CVarGetInteger("gEnhancements.Mods.AlternateAssets", 0); context->GetResourceManager()->SetAltAssetsEnabled(prevAltAssets); @@ -200,7 +224,8 @@ bool GameEngine::GenAssetFile(bool exitOnFail) { auto game = extractor->ValidateChecksum(); if (!game.has_value()) { - ShowMessage("Unsupported ROM", "The provided ROM is not supported.\n\nCheck the readme for a list of supported versions."); + ShowMessage("Unsupported ROM", + "The provided ROM is not supported.\n\nCheck the readme for a list of supported versions."); if (exitOnFail) { exit(1); } else { @@ -208,7 +233,8 @@ bool GameEngine::GenAssetFile(bool exitOnFail) { } } - ShowMessage(("Ghostship - Extraction - Found " + game.value()).c_str(), "The extraction process will now begin.\n\nThis may take a few minutes.", SDL_MESSAGEBOX_INFORMATION); + ShowMessage(("Ghostship - Extraction - Found " + game.value()).c_str(), + "The extraction process will now begin.\n\nThis may take a few minutes.", SDL_MESSAGEBOX_INFORMATION); return extractor->GenerateOTR(); } @@ -249,9 +275,9 @@ int GameEngine::ShowYesNoBox(const char* title, const char* box) { return ret; } -ImFont *GameEngine::CreateFontWithSize(float size, std::string fontPath) { +ImFont* GameEngine::CreateFontWithSize(float size, std::string fontPath) { auto mImGuiIo = &ImGui::GetIO(); - ImFont *font; + ImFont* font; if (fontPath == "") { ImFontConfig fontCfg = ImFontConfig(); fontCfg.OversampleH = fontCfg.OversampleV = 1; @@ -268,8 +294,7 @@ ImFont *GameEngine::CreateFontWithSize(float size, std::string fontPath) { initData->ResourceVersion = 0; initData->Path = fontPath; std::shared_ptr fontData = std::static_pointer_cast( - Ship::Context::GetInstance()->GetResourceManager()->LoadResource(fontPath, false, - initData)); + Ship::Context::GetInstance()->GetResourceManager()->LoadResource(fontPath, false, initData)); font = mImGuiIo->Fonts->AddFontFromMemoryTTF(fontData->Data, fontData->DataSize, size, &config); } // FontAwesome fonts need to have their sizes reduced by 2.0f/3.0f in order to align correctly @@ -279,8 +304,8 @@ ImFont *GameEngine::CreateFontWithSize(float size, std::string fontPath) { iconsConfig.MergeMode = true; iconsConfig.PixelSnapH = true; iconsConfig.GlyphMinAdvanceX = iconFontSize; - mImGuiIo->Fonts->AddFontFromMemoryCompressedBase85TTF(fontawesome_compressed_data_base85, - iconFontSize, &iconsConfig, sIconsRanges); + mImGuiIo->Fonts->AddFontFromMemoryCompressedBase85TTF(fontawesome_compressed_data_base85, iconFontSize, + &iconsConfig, sIconsRanges); return font; } @@ -299,7 +324,7 @@ void GameEngine::ScaleImGui() { previousImGuiScaleIndex = imGuiScaleIndex; } -void GameEngine::Create(){ +void GameEngine::Create() { const auto instance = Instance = new GameEngine(); GhostshipGui::SetupGuiElements(); instance->AudioInit(); @@ -312,7 +337,7 @@ void GameEngine::Create(){ DevConsole_Init(); } -void GameEngine::Destroy(){ +void GameEngine::Destroy() { PortEnhancements_Exit(); AudioExit(); #ifdef __SWITCH__ @@ -328,7 +353,8 @@ void GameEngine::StartFrame() const { switch (dwScancode) { case KbScancode::LUS_KB_TAB: { // Toggle HD Assets - CVarSetInteger("gEnhancements.Mods.AlternateAssets", !CVarGetInteger("gEnhancements.Mods.AlternateAssets", 0)); + CVarSetInteger("gEnhancements.Mods.AlternateAssets", + !CVarGetInteger("gEnhancements.Mods.AlternateAssets", 0)); break; } default: @@ -345,12 +371,13 @@ uint32_t GameEngine::GetInterpolationFPS() { return Ship::Context::GetInstance()->GetWindow()->GetCurrentRefreshRate(); } - return std::min(Ship::Context::GetInstance()->GetWindow()->GetCurrentRefreshRate(), CVarGetInteger("gInterpolationFPS", 30)); + return std::min(Ship::Context::GetInstance()->GetWindow()->GetCurrentRefreshRate(), + CVarGetInteger("gInterpolationFPS", 30)); } // Audio -void GameEngine::HandleAudioThread(){ +void GameEngine::HandleAudioThread() { while (audio.running) { { std::unique_lock Lock(audio.mutex); @@ -372,14 +399,14 @@ void GameEngine::HandleAudioThread(){ create_next_audio_buffer(audio_buffer + i * (num_audio_samples * 2), num_audio_samples); } - AudioPlayerPlayFrame((u8 *) audio_buffer, 2 * num_audio_samples * 4); + AudioPlayerPlayFrame((u8*)audio_buffer, 2 * num_audio_samples * 4); audio.processing = false; audio.cv_from_thread.notify_one(); } } -void GameEngine::StartAudioFrame(){ +void GameEngine::StartAudioFrame() { { std::unique_lock Lock(audio.mutex); audio.processing = true; @@ -388,7 +415,7 @@ void GameEngine::StartAudioFrame(){ audio.cv_to_thread.notify_one(); } -void GameEngine::EndAudioFrame(){ +void GameEngine::EndAudioFrame() { { std::unique_lock Lock(audio.mutex); while (audio.processing) { @@ -407,15 +434,15 @@ void GameEngine::AudioInit() { Instance->audioSequenceTable.resize(512); Instance->banksTable.resize(512); - for(auto& bank : *banksFiles){ + for (auto& bank : *banksFiles) { auto path = "__OTR__" + bank; - const auto ctl = static_cast(ResourceGetDataByName(path.c_str())); + const auto ctl = static_cast(ResourceGetDataByName(path.c_str())); this->bankMapTable[bank] = ctl->bankId; } - for( auto& sequence : *sequences_files){ + for (auto& sequence : *sequences_files) { auto path = "__OTR__" + sequence; - auto seq = static_cast(ResourceGetDataByName(path.c_str())); + auto seq = static_cast(ResourceGetDataByName(path.c_str())); Instance->sequenceTable[seq->id] = path; } @@ -437,7 +464,8 @@ void GameEngine::AudioExit() { } void GameEngine::LoadDictionary() { - this->dictionary = static_cast> *>(ResourceGetDataByName("__OTR__texts/strings/global")); + this->dictionary = static_cast>*>( + ResourceGetDataByName("__OTR__texts/strings/global")); } void GameEngine::LoadPlayerAnims() { @@ -446,14 +474,14 @@ void GameEngine::LoadPlayerAnims() { auto anims = archiveMgr->ListFiles("assets/anims/*"); this->animationsTable.resize(anims->size()); - for(auto& anim : *anims){ + for (auto& anim : *anims) { const auto id = std::stoi(anim.substr(anim.find('_') + 1, anim.length()), nullptr, 16); - this->animationsTable[id] = static_cast(ResourceGetDataByName(anim.c_str())); + this->animationsTable[id] = static_cast(ResourceGetDataByName(anim.c_str())); } } uint8_t GameEngine::GetBankIdByName(const std::string& name) { - if(Instance->bankMapTable.contains(name)){ + if (Instance->bankMapTable.contains(name)) { return Instance->bankMapTable[name]; } return 0; @@ -511,7 +539,7 @@ void GameEngine::ProcessGfxCommands(Gfx* commands) { while (time + original_fps <= next_original_frame) { time += original_fps; if (time != next_original_frame) { - mtx_replacements.push_back(FrameInterpolation_Interpolate((float) time / next_original_frame)); + mtx_replacements.push_back(FrameInterpolation_Interpolate((float)time / next_original_frame)); } else { mtx_replacements.emplace_back(); // No interpolation for key frames } @@ -545,7 +573,7 @@ extern "C" uint32_t GameEngine_GetSampleRate() { return player->GetSampleRate(); } -extern "C" uint32_t GameEngine_GetSamplesPerFrame(){ +extern "C" uint32_t GameEngine_GetSamplesPerFrame() { return SAMPLES_PER_FRAME; } @@ -553,9 +581,9 @@ extern "C" uint32_t GameEngine_GetSamplesPerFrame(){ Fast::Interpreter* GameEngine_GetInterpreter() { return static_pointer_cast(Ship::Context::GetInstance()->GetWindow()) - ->GetInterpreterWeak() - .lock() - .get(); + ->GetInterpreterWeak() + .lock() + .get(); } extern "C" float GameEngine_GetAspectRatio() { @@ -566,17 +594,17 @@ extern "C" float GameEngine_GetAspectRatio() { extern "C" CtlEntry* GameEngine_LoadBank(const uint8_t bankId) { const auto engine = GameEngine::Instance; - if(bankId >= engine->bankMapTable.size()){ + if (bankId >= engine->bankMapTable.size()) { return nullptr; } - if(engine->banksTable[bankId] != nullptr){ + if (engine->banksTable[bankId] != nullptr) { return engine->banksTable[bankId]; } - for(auto& bank : engine->bankMapTable){ - if(bank.second == bankId){ - const auto ctl = static_cast(ResourceGetDataByName(("__OTR__" + bank.first).c_str())); + for (auto& bank : engine->bankMapTable) { + if (bank.second == bankId) { + const auto ctl = static_cast(ResourceGetDataByName(("__OTR__" + bank.first).c_str())); engine->banksTable[bankId] = ctl; return ctl; } @@ -598,20 +626,20 @@ extern "C" void GameEngine_UnloadBank(const uint8_t bankId) { extern "C" AudioSequenceData* GameEngine_LoadSequence(const uint8_t seqId) { auto engine = GameEngine::Instance; - if(engine->sequenceTable[seqId].empty()){ + if (engine->sequenceTable[seqId].empty()) { return nullptr; } - if(engine->audioSequenceTable[seqId] != nullptr){ + if (engine->audioSequenceTable[seqId] != nullptr) { return engine->audioSequenceTable[seqId]; } - auto sequences = static_cast(ResourceGetDataByName(engine->sequenceTable[seqId].c_str())); + auto sequences = static_cast(ResourceGetDataByName(engine->sequenceTable[seqId].c_str())); engine->audioSequenceTable[seqId] = sequences; return sequences; } -extern "C" uint32_t GameEngine_GetSequenceCount(){ +extern "C" uint32_t GameEngine_GetSequenceCount() { auto engine = GameEngine::Instance; return engine->sequenceTable.size(); } @@ -629,16 +657,17 @@ extern "C" uint32_t GameEngine_GetGameVersion() { return Ship::Context::GetInstance()->GetResourceManager()->GetArchiveManager()->GetGameVersions()[0]; } -extern "C" uint8_t* GameEngine_LoadActName(const uint32_t actId){ - return static_cast(ResourceGetDataByName(StringHelper::Sprintf(gActRoot, actId).c_str())); +extern "C" uint8_t* GameEngine_LoadActName(const uint32_t actId) { + return static_cast(ResourceGetDataByName(StringHelper::Sprintf(gActRoot, actId).c_str())); } -extern "C" uint8_t* GameEngine_LoadLevelName(const uint32_t courseId){ - return static_cast(ResourceGetDataByName(StringHelper::Sprintf(gCourseRoot, courseId).c_str())); +extern "C" uint8_t* GameEngine_LoadLevelName(const uint32_t courseId) { + return static_cast(ResourceGetDataByName(StringHelper::Sprintf(gCourseRoot, courseId).c_str())); } -extern "C" DialogEntry* GameEngine_LoadDialog(const uint32_t dialogId){ - auto dialog = static_cast(ResourceGetDataByName(StringHelper::Sprintf(gDialogRoot, dialogId).c_str())); +extern "C" DialogEntry* GameEngine_LoadDialog(const uint32_t dialogId) { + auto dialog = + static_cast(ResourceGetDataByName(StringHelper::Sprintf(gDialogRoot, dialogId).c_str())); return dialog; } @@ -658,7 +687,7 @@ extern "C" int GameEngine_OTRSigCheck(const char* data) { extern "C" Animation* GameEngine_LoadAnimation(const uint32_t animId) { auto engine = GameEngine::Instance; - if(animId >= engine->animationsTable.size()){ + if (animId >= engine->animationsTable.size()) { return nullptr; } return engine->animationsTable[animId]; @@ -675,7 +704,8 @@ extern "C" uint32_t OTRGetCurrentHeight() { } extern "C" float OTRGetHUDAspectRatio() { - if (CVarGetInteger("gHUDAspectRatio.Enabled", 0) == 0 || CVarGetInteger("gHUDAspectRatio.X", 0) == 0 || CVarGetInteger("gHUDAspectRatio.Y", 0) == 0) { + if (CVarGetInteger("gHUDAspectRatio.Enabled", 0) == 0 || CVarGetInteger("gHUDAspectRatio.X", 0) == 0 || + CVarGetInteger("gHUDAspectRatio.Y", 0) == 0) { return GameEngine_GetAspectRatio(); } return ((float)CVarGetInteger("gHUDAspectRatio.X", 1) / (float)CVarGetInteger("gHUDAspectRatio.Y", 1)); @@ -683,22 +713,30 @@ extern "C" float OTRGetHUDAspectRatio() { extern "C" float OTRGetDimensionFromLeftEdge(float v) { auto interpreter = GameEngine_GetInterpreter(); - return (interpreter->mNativeDimensions.width / 2 - interpreter->mNativeDimensions.height / 2 * interpreter->mCurDimensions.aspect_ratio + (v)); + return (interpreter->mNativeDimensions.width / 2 - + interpreter->mNativeDimensions.height / 2 * interpreter->mCurDimensions.aspect_ratio + (v)); } extern "C" float OTRGetDimensionFromRightEdge(float v) { auto interpreter = GameEngine_GetInterpreter(); - return (interpreter->mNativeDimensions.width / 2 + interpreter->mNativeDimensions.height / 2 * interpreter->mCurDimensions.aspect_ratio - (v)); + return (interpreter->mNativeDimensions.width / 2 + + interpreter->mNativeDimensions.height / 2 * interpreter->mCurDimensions.aspect_ratio - (v)); } extern "C" float OTRGetDimensionFromLeftEdgeForcedAspect(float v, float aspectRatio) { auto interpreter = GameEngine_GetInterpreter(); - return (interpreter->mNativeDimensions.width / 2 - interpreter->mNativeDimensions.height / 2 * (aspectRatio > 0 ? aspectRatio : interpreter->mCurDimensions.aspect_ratio) + (v)); + return (interpreter->mNativeDimensions.width / 2 - + interpreter->mNativeDimensions.height / 2 * + (aspectRatio > 0 ? aspectRatio : interpreter->mCurDimensions.aspect_ratio) + + (v)); } extern "C" float OTRGetDimensionFromRightEdgeForcedAspect(float v, float aspectRatio) { auto interpreter = GameEngine_GetInterpreter(); - return (interpreter->mNativeDimensions.width / 2 + interpreter->mNativeDimensions.height / 2 * (aspectRatio > 0 ? aspectRatio : interpreter->mCurDimensions.aspect_ratio) - (v)); + return (interpreter->mNativeDimensions.width / 2 + + interpreter->mNativeDimensions.height / 2 * + (aspectRatio > 0 ? aspectRatio : interpreter->mCurDimensions.aspect_ratio) - + (v)); } extern "C" float OTRGetDimensionFromLeftEdgeOverride(float v) { @@ -722,19 +760,19 @@ extern "C" uint32_t OTRGetGameRenderHeight() { } extern "C" int16_t OTRGetRectDimensionFromLeftEdge(float v) { - return ((int) floorf(OTRGetDimensionFromLeftEdge(v))); + return ((int)floorf(OTRGetDimensionFromLeftEdge(v))); } extern "C" int16_t OTRGetRectDimensionFromRightEdge(float v) { - return ((int) ceilf(OTRGetDimensionFromRightEdge(v))); + return ((int)ceilf(OTRGetDimensionFromRightEdge(v))); } extern "C" int16_t OTRGetRectDimensionFromLeftEdgeForcedAspect(float v, float aspectRatio) { - return ((int) floorf(OTRGetDimensionFromLeftEdgeForcedAspect(v, aspectRatio))); + return ((int)floorf(OTRGetDimensionFromLeftEdgeForcedAspect(v, aspectRatio))); } extern "C" int16_t OTRGetRectDimensionFromRightEdgeForcedAspect(float v, float aspectRatio) { - return ((int) ceilf(OTRGetDimensionFromRightEdgeForcedAspect(v, aspectRatio))); + return ((int)ceilf(OTRGetDimensionFromRightEdgeForcedAspect(v, aspectRatio))); } extern "C" int16_t OTRGetRectDimensionFromLeftEdgeOverride(float v) { diff --git a/src/port/GBIMiddleware.cpp b/src/port/GBIMiddleware.cpp index 45642edb..381313cf 100644 --- a/src/port/GBIMiddleware.cpp +++ b/src/port/GBIMiddleware.cpp @@ -37,7 +37,7 @@ extern "C" void ResourceMgr_PatchGfxByName(const char* path, const char* patchNa return; } - for(int i = 0; i < patchCount; i++) { + for (int i = 0; i < patchCount; i++) { GfxPatch patch = patches[i]; // Store original gfx if not already stored @@ -77,7 +77,7 @@ extern "C" void gSPDisplayList(Gfx* pkt, Gfx* dl) { extern "C" void gSPVertex(Gfx* pkt, uintptr_t v, int n, int v0) { if (GameEngine_OTRSigCheck((char*)v) == 1) { - v = (uintptr_t) ResourceGetDataByName((char *) v); + v = (uintptr_t)ResourceGetDataByName((char*)v); } __gSPVertex(pkt, v, n, v0); @@ -89,10 +89,10 @@ extern "C" void gSPInvalidateTexCache(Gfx* pkt, uintptr_t texAddr) { if (texAddr != 0 && GameEngine_OTRSigCheck(imgData)) { auto res = Ship::Context::GetInstance()->GetResourceManager()->LoadResource(imgData); - if (res->GetInitData()->Type == (uint32_t) Fast::ResourceType::DisplayList) - texAddr = (uintptr_t)&((std::static_pointer_cast(res))->Instructions[0]); + if (res->GetInitData()->Type == (uint32_t)Fast::ResourceType::DisplayList) + texAddr = (uintptr_t) & ((std::static_pointer_cast(res))->Instructions[0]); else { - texAddr = (uintptr_t) res->GetRawPointer(); + texAddr = (uintptr_t)res->GetRawPointer(); } } __gSPInvalidateTexCache(pkt, texAddr); diff --git a/src/port/Game.cpp b/src/port/Game.cpp index d128d2c8..1d396197 100644 --- a/src/port/Game.cpp +++ b/src/port/Game.cpp @@ -15,9 +15,8 @@ void alloc_pool() { gEffectsMemoryPool = mem_pool_init(0x4000, MEMORY_POOL_LEFT); } -extern "C" -void exec_display_list(SPTask *spTask) { - GameEngine::ProcessGfxCommands((Gfx *) spTask->task.t.data_ptr); +extern "C" void exec_display_list(SPTask* spTask) { + GameEngine::ProcessGfxCommands((Gfx*)spTask->task.t.data_ptr); } void push_frame() { @@ -28,9 +27,9 @@ void push_frame() { } #ifdef _WIN32 -int SDL_main(int argc, char **argv) { +int SDL_main(int argc, char** argv) { #else -int main(){ +int main() { #endif GameEngine::Create(); alloc_pool(); diff --git a/src/port/GameExtractor.cpp b/src/port/GameExtractor.cpp index 9c1cd5da..a1c1cc53 100644 --- a/src/port/GameExtractor.cpp +++ b/src/port/GameExtractor.cpp @@ -43,7 +43,8 @@ bool GameExtractor::SelectGameFromUI() { // Auto detect first baserom with valid hash for (const auto& rom : roms) { - if (!std::filesystem::exists(rom)) continue; + if (!std::filesystem::exists(rom)) + continue; std::ifstream inFile(rom, std::ios::binary); if (!inFile.is_open()) { @@ -76,14 +77,13 @@ bool GameExtractor::SelectGameFromUI() { // Desktop: fallback to file dialogue if no baserom found if (!foundGame) { if (!pfd::settings::available()) { - SPDLOG_ERROR( - "portable-file-dialogs is not available on this system." - ); + SPDLOG_ERROR("portable-file-dialogs is not available on this system."); return false; } auto selection = pfd::open_file("Select a file", ".", { "N64 Roms", "*.z64" }).result(); - if (selection.empty()) return false; + if (selection.empty()) + return false; romPath = selection[0]; } @@ -107,7 +107,8 @@ bool GameExtractor::SelectGameFromUI() { } std::ifstream inFile(romPath, std::ios::binary); - if (!inFile.is_open()) return false; + if (!inFile.is_open()) + return false; romData = std::vector(std::istreambuf_iterator(inFile), {}); inFile.close(); @@ -178,7 +179,7 @@ std::optional GameExtractor::ValidateChecksum() const { const auto rom = new N64::Cartridge(this->mGameData); rom->Initialize(); auto hash = rom->GetHash(); - + if (mGameList.find(hash) == mGameList.end()) { return std::nullopt; } diff --git a/src/port/Matrix.cpp b/src/port/Matrix.cpp index 9ae2e454..659d5002 100644 --- a/src/port/Matrix.cpp +++ b/src/port/Matrix.cpp @@ -10,16 +10,15 @@ extern "C" { struct Matrix { Mtx Screen2D; // Orthogonal projection for UI, skybox, and such Mtx Ortho; - std::array Persp; - std::array LookAt; - std::array Karts; // Eight players * four screens + std::array Persp; + std::array LookAt; + std::array Karts; // Eight players * four screens std::array Shadows; // Eight players * four screens std::deque Hud; std::deque Objects; - Matrix() - : Hud(200), Objects(1000) - {} + Matrix() : Hud(200), Objects(1000) { + } }; Matrix gMatrix; @@ -90,7 +89,7 @@ void ApplyMatrixTransformations(Mat4 mtx, FVector pos, IRotator rot, FVector sca f32 sine1, cosine1; f32 sine2, cosine2; f32 sine3, cosine3; - //FrameInterpolation_ApplyMatrixTransformations((Mat4*)mtx, pos, rot, scale); + // FrameInterpolation_ApplyMatrixTransformations((Mat4*)mtx, pos, rot, scale); // Compute the sine and cosine of the orientation (Euler angles) sine1 = sins(rot.pitch); @@ -126,7 +125,7 @@ void ApplyMatrixTransformations(Mat4 mtx, FVector pos, IRotator rot, FVector sca mtx[0][2] *= scale.z; mtx[1][2] *= scale.z; mtx[2][2] *= scale.z; - + // Set the last row and column for the homogeneous coordinate system mtx[0][3] = 0.0f; mtx[1][3] = 0.0f; @@ -134,7 +133,7 @@ void ApplyMatrixTransformations(Mat4 mtx, FVector pos, IRotator rot, FVector sca mtx[3][3] = 1.0f; } -/* +/* * Spherical billboarding * Rotates the object to face the camera * Rotates on all three axis @@ -196,11 +195,11 @@ void AddLocalRotation(Mat4 mat, IRotator rot) { mat[0][0] = (cos_yaw * cos_roll) + (sin_pitch * sin_yaw * sin_roll); mat[0][1] = (cos_pitch * sin_roll); mat[0][2] = (-sin_yaw * cos_roll) + (sin_pitch * cos_yaw * sin_roll); - + mat[1][0] = (-cos_yaw * sin_roll) + (sin_pitch * sin_yaw * cos_roll); mat[1][1] = (cos_pitch * cos_roll); mat[1][2] = (sin_yaw * sin_roll) + (sin_pitch * cos_yaw * cos_roll); - + mat[2][0] = (cos_pitch * sin_yaw); mat[2][1] = -sin_pitch; mat[2][2] = (cos_pitch * cos_yaw); @@ -208,69 +207,67 @@ void AddLocalRotation(Mat4 mat, IRotator rot) { // API extern "C" { - void AddHudMatrix(Mat4 mtx, s32 flags) { - AddMatrix(gMatrix.Objects, mtx, flags); - } - - Mtx* GetScreenMatrix(void) { - return &gMatrix.Screen2D; - } - - Mtx* GetOrthoMatrix(void) { - return &gMatrix.Ortho; - } - - Mtx* GetPerspMatrix(size_t cameraId) { - return &gMatrix.Persp[cameraId]; - } - - Mtx* GetLookAtMatrix(size_t cameraId) { - return &gMatrix.LookAt[cameraId]; - } - - void AddObjectMatrix(Mat4 mtx, s32 flags) { - AddMatrix(gMatrix.Objects, mtx, flags); - } - - Mtx* GetShadowMatrix(size_t playerId) { - return &gMatrix.Shadows[playerId]; - } - - Mtx* GetKartMatrix(size_t playerId) { - return &gMatrix.Karts[playerId]; - } - - void AddEffectMatrix(Mat4 mtx, s32 flags) { - AddMatrix(gMatrix.Objects, mtx, flags); - } - - void AddEffectMatrixOrtho(void) { - auto& stack = gMatrix.Objects; - stack.emplace_back(); - - guOrtho(&stack.back(), 0.0f, SCREEN_WIDTH - 1, SCREEN_HEIGHT - 1, 0.0f, -100.0f, 100.0f, 1.0f); - - gSPMatrix(gDisplayListHead++, &stack.back(), G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_PROJECTION); - } - - Mtx* GetEffectMatrix(void) { - return GetMatrix(gMatrix.Objects); - } - - - /** - * Note that the game doesn't seem to clear all of these at the beginning of a new frame. - * We might need to adjust which ones we clear. - */ - void ClearMatrixPools(void) { - gMatrix.Objects.clear(); - // gMatrix.Shadows.clear(); - //gMatrix.Karts.clear(); - // gMatrix.Effects.clear(); - } - - void ClearObjectsMatrixPool(void) { - gMatrix.Objects.clear(); - } +void AddHudMatrix(Mat4 mtx, s32 flags) { + AddMatrix(gMatrix.Objects, mtx, flags); } +Mtx* GetScreenMatrix(void) { + return &gMatrix.Screen2D; +} + +Mtx* GetOrthoMatrix(void) { + return &gMatrix.Ortho; +} + +Mtx* GetPerspMatrix(size_t cameraId) { + return &gMatrix.Persp[cameraId]; +} + +Mtx* GetLookAtMatrix(size_t cameraId) { + return &gMatrix.LookAt[cameraId]; +} + +void AddObjectMatrix(Mat4 mtx, s32 flags) { + AddMatrix(gMatrix.Objects, mtx, flags); +} + +Mtx* GetShadowMatrix(size_t playerId) { + return &gMatrix.Shadows[playerId]; +} + +Mtx* GetKartMatrix(size_t playerId) { + return &gMatrix.Karts[playerId]; +} + +void AddEffectMatrix(Mat4 mtx, s32 flags) { + AddMatrix(gMatrix.Objects, mtx, flags); +} + +void AddEffectMatrixOrtho(void) { + auto& stack = gMatrix.Objects; + stack.emplace_back(); + + guOrtho(&stack.back(), 0.0f, SCREEN_WIDTH - 1, SCREEN_HEIGHT - 1, 0.0f, -100.0f, 100.0f, 1.0f); + + gSPMatrix(gDisplayListHead++, &stack.back(), G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_PROJECTION); +} + +Mtx* GetEffectMatrix(void) { + return GetMatrix(gMatrix.Objects); +} + +/** + * Note that the game doesn't seem to clear all of these at the beginning of a new frame. + * We might need to adjust which ones we clear. + */ +void ClearMatrixPools(void) { + gMatrix.Objects.clear(); + // gMatrix.Shadows.clear(); + // gMatrix.Karts.clear(); + // gMatrix.Effects.clear(); +} + +void ClearObjectsMatrixPool(void) { + gMatrix.Objects.clear(); +} +} diff --git a/src/port/game/GeoLayoutParser.cpp b/src/port/game/GeoLayoutParser.cpp index bd602e62..666dee72 100644 --- a/src/port/game/GeoLayoutParser.cpp +++ b/src/port/game/GeoLayoutParser.cpp @@ -35,7 +35,10 @@ struct GraphNodeEntry { GraphNodeFunc function; }; -#define FUNC(f) GraphNodeEntry { #f, reinterpret_cast(f) } +#define FUNC(f) \ + GraphNodeEntry { \ + #f, reinterpret_cast(f) \ + } std::unordered_map mUSFunctionTable = { { 0x8016f670, FUNC(geo_intro_super_mario_64_logo) }, @@ -152,19 +155,18 @@ std::unordered_map mJPFunctionTable = { }; std::unordered_map> mFunctionTable = { - { 0xFF2B5A63, mUSFunctionTable }, - { 0xE3DAA4E, mJPFunctionTable } + { 0xFF2B5A63, mUSFunctionTable }, { 0xE3DAA4E, mJPFunctionTable } }; GraphNodeFunc GetFunctionByAddr(const uint32_t addr, std::string opcode) { const auto version = GameEngine::Instance->GetGameVersion(); auto table = mFunctionTable[version]; - if(addr == 0){ + if (addr == 0) { return nullptr; } - if(!table.contains(addr)) { + if (!table.contains(addr)) { SPDLOG_ERROR("Function table does not contain address: 0x{:X} on {}", addr, opcode); return nullptr; } @@ -303,7 +305,7 @@ void process_cmd_node_root() { GraphNodeRoot* graphNode = init_graph_node_root(gGraphNodePool, nullptr, 0, x, y, width, height); - gGeoViews = static_cast(alloc_only_pool_alloc(gGraphNodePool, gGeoNumViews * sizeof(GraphNode *))); + gGeoViews = static_cast(alloc_only_pool_alloc(gGraphNodePool, gGeoNumViews * sizeof(GraphNode*))); graphNode->nodeId = generate_uuid64(); graphNode->views = gGeoViews; @@ -337,7 +339,8 @@ void process_cmd_node_perspective() { frustumFunc = GetFunctionByAddr(func, "NODE_PERSPECTIVE"); } - GraphNodePerspective* graphNode = init_graph_node_perspective(gGraphNodePool, nullptr, (f32) fov, _near, _far, frustumFunc, 0); + GraphNodePerspective* graphNode = + init_graph_node_perspective(gGraphNodePool, nullptr, (f32)fov, _near, _far, frustumFunc, 0); register_scene_graph_node(&graphNode->fnNode.node); } @@ -372,11 +375,10 @@ void process_cmd_node_switch_case() { const auto cs = GeoLayoutParser::mReader->ReadInt16(); const auto func = GeoLayoutParser::mReader->ReadUInt32(); - GraphNodeSwitchCase *graphNode = + GraphNodeSwitchCase* graphNode = init_graph_node_switch_case(gGraphNodePool, nullptr, - cs, // case which is initially selected - 0, - GetFunctionByAddr(func, "NODE_SWITCH_CASE"), // case update function + cs, // case which is initially selected + 0, GetFunctionByAddr(func, "NODE_SWITCH_CASE"), // case update function 0); register_scene_graph_node(&graphNode->fnNode.node); @@ -392,8 +394,8 @@ void process_cmd_node_camera() { const auto addr = GeoLayoutParser::mReader->ReadUInt32(); - GraphNodeCamera* graphNode = init_graph_node_camera(gGraphNodePool, nullptr, pos, focus, - GetFunctionByAddr(addr, "NODE_CAMERA"), type); + GraphNodeCamera* graphNode = + init_graph_node_camera(gGraphNodePool, nullptr, pos, focus, GetFunctionByAddr(addr, "NODE_CAMERA"), type); register_scene_graph_node(&graphNode->fnNode.node); @@ -433,11 +435,8 @@ void process_cmd_node_translation_rotation() { drawingLayer = params & 0x0F; } - GraphNodeTranslationRotation* graphNode = init_graph_node_translation_rotation( - gGraphNodePool, nullptr, - drawingLayer, displayList, - translation, rotation - ); + GraphNodeTranslationRotation* graphNode = + init_graph_node_translation_rotation(gGraphNodePool, nullptr, drawingLayer, displayList, translation, rotation); register_scene_graph_node(&graphNode->node); } @@ -447,7 +446,7 @@ void process_cmd_node_translation() { const auto params = GeoLayoutParser::mReader->ReadUByte(); s16 drawingLayer = 0; - void *displayList = nullptr; + void* displayList = nullptr; ReadVec3s(translation); @@ -468,7 +467,7 @@ void process_cmd_node_rotation() { const auto params = GeoLayoutParser::mReader->ReadUByte(); s16 drawingLayer = 0; - void *displayList = nullptr; + void* displayList = nullptr; ReadVec3sAngle(rotation); @@ -487,7 +486,7 @@ void process_cmd_node_scale() { s16 drawingLayer = 0; const auto params = GeoLayoutParser::mReader->ReadUByte(); const auto scale = GeoLayoutParser::mReader->ReadUInt32() / 65536.0f; - void *displayList = nullptr; + void* displayList = nullptr; if (params & 0x80) { displayList = ResourceGetDataByCrc(ReadSafeCrc()); @@ -499,7 +498,8 @@ void process_cmd_node_scale() { register_scene_graph_node(&graphNode->node); } -void process_cmd_nop2() {} +void process_cmd_nop2() { +} void process_cmd_node_animated_part() { Vec3s translation; @@ -529,14 +529,15 @@ void process_cmd_node_billboard() { drawingLayer = params & 0x0F; } - GraphNodeBillboard* graphNode = init_graph_node_billboard(gGraphNodePool, nullptr, drawingLayer, displayList, translation); + GraphNodeBillboard* graphNode = + init_graph_node_billboard(gGraphNodePool, nullptr, drawingLayer, displayList, translation); register_scene_graph_node(&graphNode->node); } void process_cmd_node_display_list() { const auto drawingLayer = GeoLayoutParser::mReader->ReadUByte(); - void *displayList = ResourceGetDataByCrc(ReadSafeCrc()); + void* displayList = ResourceGetDataByCrc(ReadSafeCrc()); GraphNodeDisplayList* graphNode = init_graph_node_display_list(gGraphNodePool, nullptr, drawingLayer, displayList); @@ -563,9 +564,9 @@ void process_cmd_node_generated() { const auto param = GeoLayoutParser::mReader->ReadInt16(); const auto addr = GeoLayoutParser::mReader->ReadUInt32(); - GraphNodeGenerated* graphNode = init_graph_node_generated(gGraphNodePool, nullptr, - GetFunctionByAddr(addr, "NODE_ASM"), // asm function - param); // parameter + GraphNodeGenerated* graphNode = + init_graph_node_generated(gGraphNodePool, nullptr, GetFunctionByAddr(addr, "NODE_ASM"), // asm function + param); // parameter register_scene_graph_node(&graphNode->fnNode.node); } @@ -574,26 +575,27 @@ void process_cmd_node_background() { const auto param = GeoLayoutParser::mReader->ReadInt16(); const auto addr = GeoLayoutParser::mReader->ReadUInt32(); - GraphNodeBackground* graphNode = init_graph_node_background( - gGraphNodePool, nullptr, - param, // background ID, or RGBA5551 color if asm function is null - GetFunctionByAddr(addr, "NODE_BACKGROUND"), // asm function - 0); + GraphNodeBackground* graphNode = + init_graph_node_background(gGraphNodePool, nullptr, + param, // background ID, or RGBA5551 color if asm function is null + GetFunctionByAddr(addr, "NODE_BACKGROUND"), // asm function + 0); register_scene_graph_node(&graphNode->fnNode.node); } -void process_cmd_nop() {} +void process_cmd_nop() { +} void process_cmd_copy_view() { - GraphNode *node = nullptr; + GraphNode* node = nullptr; const auto index = GeoLayoutParser::mReader->ReadInt16(); if (index >= 0) { node = gGeoViews[index]; if (node->type == GRAPH_NODE_TYPE_OBJECT_PARENT) { - node = reinterpret_cast(node)->sharedChild; + node = reinterpret_cast(node)->sharedChild; } else { node = nullptr; } @@ -612,12 +614,8 @@ void process_cmd_node_held_obj() { ReadVec3s(offset); - GraphNodeHeldObject *graphNode = init_graph_node_held_object( - gGraphNodePool, nullptr, nullptr, - offset, - GetFunctionByAddr(addr, "NODE_HELD_OBJ"), - player - ); + GraphNodeHeldObject* graphNode = init_graph_node_held_object(gGraphNodePool, nullptr, nullptr, offset, + GetFunctionByAddr(addr, "NODE_HELD_OBJ"), player); register_scene_graph_node(&graphNode->fnNode.node); } @@ -664,7 +662,6 @@ GeoCommandFunction GeoLayoutFunctionTable[] = { process_cmd_node_culling_radius, }; - void GeoLayoutParser::execute(const char* path) { const auto data = static_cast(ResourceGetDataByName(path)); const auto size = ResourceGetSizeByName(path); @@ -679,7 +676,7 @@ void GeoLayoutParser::execute(const char* path) { } delete mReader; - mReader = nullptr; + mReader = nullptr; } extern "C" void GeoLayoutExecute(char const* path) { diff --git a/src/port/hooks/impl/EventSystem.cpp b/src/port/hooks/impl/EventSystem.cpp index 3418b6ef..1157378f 100644 --- a/src/port/hooks/impl/EventSystem.cpp +++ b/src/port/hooks/impl/EventSystem.cpp @@ -9,24 +9,22 @@ EventID EventSystem::RegisterEvent() { } ListenerID EventSystem::RegisterListener(EventID id, EventCallback callback, EventPriority priority) { - if(id == -1) { + if (id == -1) { throw std::runtime_error("Trying to register listener for unregistered event"); } auto& listeners = this->mEventListeners[id]; - if(std::find_if(listeners.begin(), listeners.end(), [callback](EventListener listener) { - return listener.function == callback; - }) != listeners.end()) { + if (std::find_if(listeners.begin(), listeners.end(), + [callback](EventListener listener) { return listener.function == callback; }) != listeners.end()) { throw std::runtime_error("Listener already registered"); } listeners.push_back({ priority, callback }); // Sort by priority - std::sort(listeners.begin(), listeners.end(), [](EventListener a, EventListener b) { - return a.priority < b.priority; - }); + std::sort(listeners.begin(), listeners.end(), + [](EventListener a, EventListener b) { return a.priority < b.priority; }); return listeners.size() - 1; } diff --git a/src/port/importer/AnimationFactory.cpp b/src/port/importer/AnimationFactory.cpp index a24dfe33..6d18131f 100644 --- a/src/port/importer/AnimationFactory.cpp +++ b/src/port/importer/AnimationFactory.cpp @@ -2,8 +2,9 @@ #include "port/importer/types/Animation.h" #include "spdlog/spdlog.h" -std::shared_ptr SM64::AnimationFactoryV0::ReadResource(std::shared_ptr file, - std::shared_ptr initData) { +std::shared_ptr +SM64::AnimationFactoryV0::ReadResource(std::shared_ptr file, + std::shared_ptr initData) { if (!FileHasValidFormatAndReader(file, initData)) { return nullptr; } @@ -31,7 +32,7 @@ std::shared_ptr SM64::AnimationFactoryV0::ReadResource(std::sha animation->values.push_back(reader->ReadInt16()); } - animation->mData.index = animation->indices.data(); + animation->mData.index = animation->indices.data(); animation->mData.values = animation->values.data(); return animation; diff --git a/src/port/importer/AssetArrayFactory.cpp b/src/port/importer/AssetArrayFactory.cpp index d2acfc04..5af3a610 100644 --- a/src/port/importer/AssetArrayFactory.cpp +++ b/src/port/importer/AssetArrayFactory.cpp @@ -5,8 +5,9 @@ #include "ResourceUtil.h" namespace SM64 { -std::shared_ptr ResourceFactoryBinaryAssetArrayV0::ReadResource(std::shared_ptr file, - std::shared_ptr initData) { +std::shared_ptr +ResourceFactoryBinaryAssetArrayV0::ReadResource(std::shared_ptr file, + std::shared_ptr initData) { if (!FileHasValidFormatAndReader(file, initData)) { return nullptr; } @@ -15,10 +16,10 @@ std::shared_ptr ResourceFactoryBinaryAssetArrayV0::ReadResource auto reader = std::get>(file->Reader); auto count = reader->ReadUInt32(); - for(size_t i = 0; i < count; i++) { + for (size_t i = 0; i < count; i++) { asset->mPtrs.push_back(reinterpret_cast(ResourceGetDataByCrc(reader->ReadUInt64()))); } return asset; } -} // namespace LUS +} // namespace SM64 diff --git a/src/port/importer/AudioBankFactory.cpp b/src/port/importer/AudioBankFactory.cpp index 4bdd333c..975bc573 100644 --- a/src/port/importer/AudioBankFactory.cpp +++ b/src/port/importer/AudioBankFactory.cpp @@ -3,8 +3,9 @@ #include #include "ResourceUtil.h" -std::shared_ptr SM64::AudioBankFactoryV0::ReadResource(std::shared_ptr file, - std::shared_ptr initData) { +std::shared_ptr +SM64::AudioBankFactoryV0::ReadResource(std::shared_ptr file, + std::shared_ptr initData) { if (!FileHasValidFormatAndReader(file, initData)) { return nullptr; } @@ -15,10 +16,10 @@ std::shared_ptr SM64::AudioBankFactoryV0::ReadResource(std::sha uint8_t bankId = reader->ReadUInt32(); uint32_t instrumentCount = reader->ReadUInt32(); - for(size_t i = 0; i < instrumentCount; i++){ + for (size_t i = 0; i < instrumentCount; i++) { auto* instrument = new Instrument(); bool valid = reader->ReadUByte(); - if(!valid){ + if (!valid) { bank->instruments.push_back(nullptr); continue; } @@ -28,9 +29,9 @@ std::shared_ptr SM64::AudioBankFactoryV0::ReadResource(std::sha instrument->normalRangeHi = reader->ReadUByte(); uint32_t envelopeSize = reader->ReadUInt32(); - if(envelopeSize != 0){ + if (envelopeSize != 0) { instrument->envelope = new AdsrEnvelope[envelopeSize]; - for(size_t j = 0; j < envelopeSize; j++){ + for (size_t j = 0; j < envelopeSize; j++) { instrument->envelope[j].delay = BSWAP16(reader->ReadInt16()); instrument->envelope[j].arg = BSWAP16(reader->ReadInt16()); } @@ -41,19 +42,19 @@ std::shared_ptr SM64::AudioBankFactoryV0::ReadResource(std::sha bool hasMed = soundFlags & (1 << 1); bool hasHi = soundFlags & (1 << 2); - if(hasLo){ + if (hasLo) { std::string lowSampleName = reader->ReadString(); instrument->lowNotesSound.sample = LoadChild(lowSampleName.c_str()); instrument->lowNotesSound.tuning = reader->ReadFloat(); } - if(hasMed){ + if (hasMed) { std::string normalSampleName = reader->ReadString(); instrument->normalNotesSound.sample = LoadChild(normalSampleName.c_str()); instrument->normalNotesSound.tuning = reader->ReadFloat(); } - if(hasHi){ + if (hasHi) { std::string highSampleName = reader->ReadString(); instrument->highNotesSound.sample = LoadChild(highSampleName.c_str()); instrument->highNotesSound.tuning = reader->ReadFloat(); @@ -64,16 +65,16 @@ std::shared_ptr SM64::AudioBankFactoryV0::ReadResource(std::sha uint32_t drumCount = reader->ReadUInt32(); - for(size_t i = 0; i < drumCount; i++){ + for (size_t i = 0; i < drumCount; i++) { auto* drum = new Drum(); drum->releaseRate = reader->ReadUByte(); drum->pan = reader->ReadUByte(); drum->loaded = 1; uint32_t envelopeSize = reader->ReadUInt32(); - if(envelopeSize != 0){ + if (envelopeSize != 0) { drum->envelope = new AdsrEnvelope[envelopeSize]; - for(size_t j = 0; j < envelopeSize; j++){ + for (size_t j = 0; j < envelopeSize; j++) { drum->envelope[j].delay = BSWAP16(reader->ReadInt16()); drum->envelope[j].arg = BSWAP16(reader->ReadInt16()); } diff --git a/src/port/importer/AudioSampleFactory.cpp b/src/port/importer/AudioSampleFactory.cpp index 461f4c99..8ce13956 100644 --- a/src/port/importer/AudioSampleFactory.cpp +++ b/src/port/importer/AudioSampleFactory.cpp @@ -3,8 +3,9 @@ #include "port/importer/types/AudioSample.h" #include "spdlog/spdlog.h" -std::shared_ptr SM64::AudioSampleFactoryV0::ReadResource(std::shared_ptr file, - std::shared_ptr initData) { +std::shared_ptr +SM64::AudioSampleFactoryV0::ReadResource(std::shared_ptr file, + std::shared_ptr initData) { if (!FileHasValidFormatAndReader(file, initData)) { return nullptr; } @@ -19,9 +20,9 @@ std::shared_ptr SM64::AudioSampleFactoryV0::ReadResource(std::s uint32_t stateSize = reader->ReadUInt32(); std::vector state; - if(stateSize > 0){ + if (stateSize > 0) { bank->loop.state = new int16_t[stateSize]; - reader->Read((char*) bank->loop.state, stateSize * sizeof(int16_t)); + reader->Read((char*)bank->loop.state, stateSize * sizeof(int16_t)); } else { bank->loop.state = nullptr; } @@ -31,7 +32,7 @@ std::shared_ptr SM64::AudioSampleFactoryV0::ReadResource(std::s uint32_t tableSize = reader->ReadUInt32(); bank->book.book = new int16_t[tableSize]; - reader->Read((char*) bank->book.book, tableSize * sizeof(int16_t)); + reader->Read((char*)bank->book.book, tableSize * sizeof(int16_t)); int32_t sampleSize = reader->ReadInt32(); char* sampleData = new char[sampleSize]; @@ -41,7 +42,7 @@ std::shared_ptr SM64::AudioSampleFactoryV0::ReadResource(std::s bank->mData.loaded = 1; bank->mData.loop = &bank->loop; bank->mData.book = &bank->book; - bank->mData.sampleAddr = (uint8_t*) sampleData; + bank->mData.sampleAddr = (uint8_t*)sampleData; bank->mData.sampleSize = sampleSize; return bank; diff --git a/src/port/importer/AudioSequenceFactory.cpp b/src/port/importer/AudioSequenceFactory.cpp index d759dad2..a0300d60 100644 --- a/src/port/importer/AudioSequenceFactory.cpp +++ b/src/port/importer/AudioSequenceFactory.cpp @@ -4,8 +4,9 @@ #include "port/Engine.h" #include "port/importer/types/AudioBank.h" -std::shared_ptr SM64::AudioSequenceFactoryV0::ReadResource(std::shared_ptr file, - std::shared_ptr initData) { +std::shared_ptr +SM64::AudioSequenceFactoryV0::ReadResource(std::shared_ptr file, + std::shared_ptr initData) { if (!FileHasValidFormatAndReader(file, initData)) { return nullptr; } @@ -15,13 +16,13 @@ std::shared_ptr SM64::AudioSequenceFactoryV0::ReadResource(std: uint8_t id = reader->ReadUInt32(); size_t bankCount = reader->ReadUInt32(); - for(size_t i = 0; i < bankCount; i++){ + for (size_t i = 0; i < bankCount; i++) { std::string bankName = reader->ReadString(); bank->banks.push_back(GameEngine::GetBankIdByName(bankName)); } size_t sampleSize = reader->ReadUInt32(); - for(size_t i = 0; i < sampleSize; i++){ + for (size_t i = 0; i < sampleSize; i++) { bank->sampleData.push_back(reader->ReadUByte()); } diff --git a/src/port/importer/DialogFactory.cpp b/src/port/importer/DialogFactory.cpp index 0ec3aa8b..19b4c4a2 100644 --- a/src/port/importer/DialogFactory.cpp +++ b/src/port/importer/DialogFactory.cpp @@ -3,7 +3,7 @@ #include "spdlog/spdlog.h" std::shared_ptr SM64::DialogFactoryV0::ReadResource(std::shared_ptr file, - std::shared_ptr initData) { + std::shared_ptr initData) { if (!FileHasValidFormatAndReader(file, initData)) { return nullptr; } @@ -17,7 +17,7 @@ std::shared_ptr SM64::DialogFactoryV0::ReadResource(std::shared dialog->mData.width = reader->ReadInt16(); size_t textSize = reader->ReadUInt32(); - for(size_t i = 0; i < textSize; i++){ + for (size_t i = 0; i < textSize; i++) { dialog->mText.push_back(reader->ReadUByte()); } diff --git a/src/port/importer/DictionaryFactory.cpp b/src/port/importer/DictionaryFactory.cpp index f719b462..408c6c4d 100644 --- a/src/port/importer/DictionaryFactory.cpp +++ b/src/port/importer/DictionaryFactory.cpp @@ -2,9 +2,9 @@ #include "port/importer/types/Dictionary.h" #include "spdlog/spdlog.h" - -std::shared_ptr SM64::DictionaryFactoryV0::ReadResource(std::shared_ptr file, - std::shared_ptr initData) { +std::shared_ptr +SM64::DictionaryFactoryV0::ReadResource(std::shared_ptr file, + std::shared_ptr initData) { if (!FileHasValidFormatAndReader(file, initData)) { return nullptr; } @@ -13,11 +13,11 @@ std::shared_ptr SM64::DictionaryFactoryV0::ReadResource(std::sh auto reader = std::get>(file->Reader); size_t numEntries = reader->ReadUInt32(); - for(size_t i = 0; i < numEntries; i++){ + for (size_t i = 0; i < numEntries; i++) { std::string key = reader->ReadString(); size_t valueSize = reader->ReadUInt32(); std::vector value; - for(size_t j = 0; j < valueSize; j++){ + for (size_t j = 0; j < valueSize; j++) { value.push_back(reader->ReadUByte()); } dictionary->mData[key] = value; diff --git a/src/port/importer/GenericArrayFactory.cpp b/src/port/importer/GenericArrayFactory.cpp index 665ff342..67059c39 100644 --- a/src/port/importer/GenericArrayFactory.cpp +++ b/src/port/importer/GenericArrayFactory.cpp @@ -3,8 +3,9 @@ #include "spdlog/spdlog.h" namespace SF64 { -std::shared_ptr ResourceFactoryBinaryGenericArrayV0::ReadResource(std::shared_ptr file, - std::shared_ptr initData) { +std::shared_ptr +ResourceFactoryBinaryGenericArrayV0::ReadResource(std::shared_ptr file, + std::shared_ptr initData) { if (!FileHasValidFormatAndReader(file, initData)) { return nullptr; } @@ -107,4 +108,4 @@ std::shared_ptr ResourceFactoryBinaryGenericArrayV0::ReadResour return arr; } -} // namespace LUS +} // namespace SF64 diff --git a/src/port/importer/MacroObjectFactory.cpp b/src/port/importer/MacroObjectFactory.cpp index 6e9c6530..cd43ad54 100644 --- a/src/port/importer/MacroObjectFactory.cpp +++ b/src/port/importer/MacroObjectFactory.cpp @@ -3,8 +3,9 @@ #define MACRO_OBJECT_END() 0x001E -std::shared_ptr SM64::MacroObjectFactoryV0::ReadResource(std::shared_ptr file, - std::shared_ptr initData) { +std::shared_ptr +SM64::MacroObjectFactoryV0::ReadResource(std::shared_ptr file, + std::shared_ptr initData) { if (!FileHasValidFormatAndReader(file, initData)) { return nullptr; } @@ -14,7 +15,7 @@ std::shared_ptr SM64::MacroObjectFactoryV0::ReadResource(std::s uint32_t count = reader->ReadUInt32(); - for(size_t i = 0; i < count; i++){ + for (size_t i = 0; i < count; i++) { macro->mData.push_back(reader->ReadInt16()); macro->mData.push_back(reader->ReadInt16()); macro->mData.push_back(reader->ReadInt16()); diff --git a/src/port/importer/MovtexFactory.cpp b/src/port/importer/MovtexFactory.cpp index f592a48d..77a4e16c 100644 --- a/src/port/importer/MovtexFactory.cpp +++ b/src/port/importer/MovtexFactory.cpp @@ -2,7 +2,7 @@ #include "port/importer/types/Movtex.h" std::shared_ptr SM64::MovtexFactoryV0::ReadResource(std::shared_ptr file, - std::shared_ptr initData) { + std::shared_ptr initData) { if (!FileHasValidFormatAndReader(file, initData)) { return nullptr; } @@ -12,7 +12,7 @@ std::shared_ptr SM64::MovtexFactoryV0::ReadResource(std::shared uint32_t count = reader->ReadUInt32(); - for(size_t i = 0; i < count; i++){ + for (size_t i = 0; i < count; i++) { movtex->mData.push_back(reader->ReadInt16()); } diff --git a/src/port/importer/MovtexQuadFactory.cpp b/src/port/importer/MovtexQuadFactory.cpp index b2306a20..b30306f6 100644 --- a/src/port/importer/MovtexQuadFactory.cpp +++ b/src/port/importer/MovtexQuadFactory.cpp @@ -2,8 +2,9 @@ #include "ResourceUtil.h" #include "port/importer/types/MovtexQuad.h" -std::shared_ptr SM64::MovtexQuadFactoryV0::ReadResource(std::shared_ptr file, - std::shared_ptr initData) { +std::shared_ptr +SM64::MovtexQuadFactoryV0::ReadResource(std::shared_ptr file, + std::shared_ptr initData) { if (!FileHasValidFormatAndReader(file, initData)) { return nullptr; } @@ -13,11 +14,8 @@ std::shared_ptr SM64::MovtexQuadFactoryV0::ReadResource(std::sh uint32_t count = reader->ReadUInt32(); - for(size_t i = 0; i < count; i++){ - movtex->mData.push_back({ - reader->ReadInt16(), - LoadChild(reader->ReadUInt64()) - }); + for (size_t i = 0; i < count; i++) { + movtex->mData.push_back({ reader->ReadInt16(), LoadChild(reader->ReadUInt64()) }); } return movtex; diff --git a/src/port/importer/PaintingFactory.cpp b/src/port/importer/PaintingFactory.cpp index 93315e5c..f48955cf 100644 --- a/src/port/importer/PaintingFactory.cpp +++ b/src/port/importer/PaintingFactory.cpp @@ -2,8 +2,9 @@ #include "ResourceUtil.h" #include "port/importer/types/Painting.h" -std::shared_ptr SM64::PaintingFactoryV0::ReadResource(std::shared_ptr file, - std::shared_ptr initData) { +std::shared_ptr +SM64::PaintingFactoryV0::ReadResource(std::shared_ptr file, + std::shared_ptr initData) { if (!FileHasValidFormatAndReader(file, initData)) { return nullptr; } diff --git a/src/port/importer/TrajectoryFactory.cpp b/src/port/importer/TrajectoryFactory.cpp index 289c25dd..61247384 100644 --- a/src/port/importer/TrajectoryFactory.cpp +++ b/src/port/importer/TrajectoryFactory.cpp @@ -1,8 +1,9 @@ #include "TrajectoryFactory.h" #include "port/importer/types/Trajectory.h" -std::shared_ptr SM64::TrajectoryFactoryV0::ReadResource(std::shared_ptr file, - std::shared_ptr initData) { +std::shared_ptr +SM64::TrajectoryFactoryV0::ReadResource(std::shared_ptr file, + std::shared_ptr initData) { if (!FileHasValidFormatAndReader(file, initData)) { return nullptr; } @@ -12,13 +13,9 @@ std::shared_ptr SM64::TrajectoryFactoryV0::ReadResource(std::sh uint32_t count = reader->ReadUInt32(); - for(size_t i = 0; i < count; i++){ - trajectory->mData.push_back({ - reader->ReadInt16(), - reader->ReadInt16(), - reader->ReadInt16(), - reader->ReadInt16() - }); + for (size_t i = 0; i < count; i++) { + trajectory->mData.push_back( + { reader->ReadInt16(), reader->ReadInt16(), reader->ReadInt16(), reader->ReadInt16() }); } return trajectory; diff --git a/src/port/importer/types/Animation.cpp b/src/port/importer/types/Animation.cpp index 14153247..dcb3656d 100644 --- a/src/port/importer/types/Animation.cpp +++ b/src/port/importer/types/Animation.cpp @@ -8,4 +8,4 @@ AnimationData* Animation::GetPointer() { size_t Animation::GetPointerSize() { return sizeof(mData); } -} \ No newline at end of file +} // namespace SM64 \ No newline at end of file diff --git a/src/port/importer/types/AssetArray.cpp b/src/port/importer/types/AssetArray.cpp index bfb8102f..e28d32a8 100644 --- a/src/port/importer/types/AssetArray.cpp +++ b/src/port/importer/types/AssetArray.cpp @@ -1,11 +1,11 @@ #include "AssetArray.h" namespace SM64 { - uintptr_t* AssetArray::GetPointer() { - return mPtrs.data(); - } +uintptr_t* AssetArray::GetPointer() { + return mPtrs.data(); +} - size_t AssetArray::GetPointerSize() { - return mPtrs.size() * sizeof(uintptr_t); - } -} \ No newline at end of file +size_t AssetArray::GetPointerSize() { + return mPtrs.size() * sizeof(uintptr_t); +} +} // namespace SM64 \ No newline at end of file diff --git a/src/port/importer/types/AudioBank.cpp b/src/port/importer/types/AudioBank.cpp index f91b767d..c2e14e03 100644 --- a/src/port/importer/types/AudioBank.cpp +++ b/src/port/importer/types/AudioBank.cpp @@ -8,4 +8,4 @@ CtlEntry* AudioBank::GetPointer() { size_t AudioBank::GetPointerSize() { return sizeof(mData); } -} \ No newline at end of file +} // namespace SM64 \ No newline at end of file diff --git a/src/port/importer/types/AudioSample.cpp b/src/port/importer/types/AudioSample.cpp index cbdbd657..112e6757 100644 --- a/src/port/importer/types/AudioSample.cpp +++ b/src/port/importer/types/AudioSample.cpp @@ -8,4 +8,4 @@ AudioBankSample* AudioSample::GetPointer() { size_t AudioSample::GetPointerSize() { return sizeof(mData); } -} \ No newline at end of file +} // namespace SM64 \ No newline at end of file diff --git a/src/port/importer/types/AudioSequence.cpp b/src/port/importer/types/AudioSequence.cpp index 263530cf..e215cd40 100644 --- a/src/port/importer/types/AudioSequence.cpp +++ b/src/port/importer/types/AudioSequence.cpp @@ -8,4 +8,4 @@ AudioSequenceData* AudioSequence::GetPointer() { size_t AudioSequence::GetPointerSize() { return sizeof(mData); } -} \ No newline at end of file +} // namespace SM64 \ No newline at end of file diff --git a/src/port/importer/types/Dialog.cpp b/src/port/importer/types/Dialog.cpp index 10919e3c..8e14ac57 100644 --- a/src/port/importer/types/Dialog.cpp +++ b/src/port/importer/types/Dialog.cpp @@ -8,4 +8,4 @@ DialogEntry* Dialog::GetPointer() { size_t Dialog::GetPointerSize() { return sizeof(mData); } -} \ No newline at end of file +} // namespace SM64 \ No newline at end of file diff --git a/src/port/importer/types/Dictionary.cpp b/src/port/importer/types/Dictionary.cpp index 7becc5b1..fd861999 100644 --- a/src/port/importer/types/Dictionary.cpp +++ b/src/port/importer/types/Dictionary.cpp @@ -8,4 +8,4 @@ GameDictionary* Dictionary::GetPointer() { size_t Dictionary::GetPointerSize() { return sizeof(mData); } -} \ No newline at end of file +} // namespace SM64 \ No newline at end of file diff --git a/src/port/importer/types/GenericArray.cpp b/src/port/importer/types/GenericArray.cpp index 74332a7e..5c5d2b74 100644 --- a/src/port/importer/types/GenericArray.cpp +++ b/src/port/importer/types/GenericArray.cpp @@ -8,4 +8,4 @@ uint8_t* GenericArray::GetPointer() { size_t GenericArray::GetPointerSize() { return mData.size(); } -} \ No newline at end of file +} // namespace SF64 \ No newline at end of file diff --git a/src/port/importer/types/MacroObject.cpp b/src/port/importer/types/MacroObject.cpp index 0f55157a..307861cf 100644 --- a/src/port/importer/types/MacroObject.cpp +++ b/src/port/importer/types/MacroObject.cpp @@ -8,4 +8,4 @@ int16_t* MacroObject::GetPointer() { size_t MacroObject::GetPointerSize() { return sizeof(mData.size()) * sizeof(int16_t); } -} \ No newline at end of file +} // namespace SM64 \ No newline at end of file diff --git a/src/port/importer/types/Movtex.cpp b/src/port/importer/types/Movtex.cpp index 9f717a02..c3e93968 100644 --- a/src/port/importer/types/Movtex.cpp +++ b/src/port/importer/types/Movtex.cpp @@ -8,4 +8,4 @@ int16_t* Movtex::GetPointer() { size_t Movtex::GetPointerSize() { return mData.size() * sizeof(int16_t); } -} \ No newline at end of file +} // namespace SM64 \ No newline at end of file diff --git a/src/port/importer/types/MovtexQuad.cpp b/src/port/importer/types/MovtexQuad.cpp index 3461e49d..3d0b0b79 100644 --- a/src/port/importer/types/MovtexQuad.cpp +++ b/src/port/importer/types/MovtexQuad.cpp @@ -8,4 +8,4 @@ MovtexQuadData* MovtexQuad::GetPointer() { size_t MovtexQuad::GetPointerSize() { return sizeof(mData.size()) * sizeof(MovtexQuadData); } -} \ No newline at end of file +} // namespace SM64 \ No newline at end of file diff --git a/src/port/importer/types/Painting.cpp b/src/port/importer/types/Painting.cpp index 5d40c5b8..d7407048 100644 --- a/src/port/importer/types/Painting.cpp +++ b/src/port/importer/types/Painting.cpp @@ -8,4 +8,4 @@ PaintingData* Painting::GetPointer() { size_t Painting::GetPointerSize() { return sizeof(mData); } -} \ No newline at end of file +} // namespace SM64 \ No newline at end of file diff --git a/src/port/importer/types/Trajectory.cpp b/src/port/importer/types/Trajectory.cpp index 934044ba..04bf06f2 100644 --- a/src/port/importer/types/Trajectory.cpp +++ b/src/port/importer/types/Trajectory.cpp @@ -8,4 +8,4 @@ TrajectoryData* Trajectory::GetPointer() { size_t Trajectory::GetPointerSize() { return sizeof(mData.size()) * sizeof(TrajectoryData); } -} \ No newline at end of file +} // namespace SM64 \ No newline at end of file diff --git a/src/port/interpolation/FrameInterpolation.cpp b/src/port/interpolation/FrameInterpolation.cpp index 9e15fad5..d2125b99 100644 --- a/src/port/interpolation/FrameInterpolation.cpp +++ b/src/port/interpolation/FrameInterpolation.cpp @@ -49,7 +49,6 @@ static bool invert_matrix(const float m[16], float invOut[16]); using namespace std; - namespace { enum class Op { @@ -271,7 +270,7 @@ Data& append(Op op) { } MtxF* Matrix_GetCurrent() { - return (MtxF*) gInterpolationMatrix; + return (MtxF*)gInterpolationMatrix; } struct InterpolateCtx { @@ -355,15 +354,15 @@ struct InterpolateCtx { s16 interpolate_angle(s16 os, s16 ns) { if (os == ns) return ns; - int o = (u16) os; - int n = (u16) ns; + int o = (u16)os; + int n = (u16)ns; u16 res; int diff = o - n; if (-0x8000 <= diff && diff <= 0x8000) { if (diff < -0x4000 || diff > 0x4000) { return ns; } - res = (u16) (w * o + step * n); + res = (u16)(w * o + step * n); } else { if (o < n) { o += 0x10000; @@ -374,7 +373,7 @@ struct InterpolateCtx { if (diff < -0x4000 || diff > 0x4000) { return ns; } - res = (u16) (w * o + step * n); + res = (u16)(w * o + step * n); } return res; } @@ -417,11 +416,11 @@ struct InterpolateCtx { break; case Op::MatrixPush: - Matrix_Push((Matrix**) &gInterpolationMatrix); + Matrix_Push((Matrix**)&gInterpolationMatrix); break; case Op::MatrixPop: - Matrix_Pop((Matrix**) &gInterpolationMatrix); + Matrix_Pop((Matrix**)&gInterpolationMatrix); break; // Unused on SF64 @@ -454,11 +453,11 @@ struct InterpolateCtx { tempF[2] = lerp(old_op.matrix_pos_rot_xyz.pos.z, new_op.matrix_pos_rot_xyz.pos.z); tempS[0] = - lerp(old_op.matrix_pos_rot_xyz.orientation.x, new_op.matrix_pos_rot_xyz.orientation.x); + lerp(old_op.matrix_pos_rot_xyz.orientation.x, new_op.matrix_pos_rot_xyz.orientation.x); tempS[1] = - lerp(old_op.matrix_pos_rot_xyz.orientation.y, new_op.matrix_pos_rot_xyz.orientation.y); + lerp(old_op.matrix_pos_rot_xyz.orientation.y, new_op.matrix_pos_rot_xyz.orientation.y); tempS[2] = - lerp(old_op.matrix_pos_rot_xyz.orientation.z, new_op.matrix_pos_rot_xyz.orientation.z); + lerp(old_op.matrix_pos_rot_xyz.orientation.z, new_op.matrix_pos_rot_xyz.orientation.z); mtxf_rotate_xyz_and_translate(*gInterpolationMatrix, tempF, tempS); break; @@ -472,43 +471,44 @@ struct InterpolateCtx { tempF[2] = lerp(old_op.matrix_pos_rot_xyz.pos.z, new_op.matrix_pos_rot_xyz.pos.z); tempS[0] = - lerp(old_op.matrix_pos_rot_xyz.orientation.x, new_op.matrix_pos_rot_xyz.orientation.x); + lerp(old_op.matrix_pos_rot_xyz.orientation.x, new_op.matrix_pos_rot_xyz.orientation.x); tempS[1] = - lerp(old_op.matrix_pos_rot_xyz.orientation.y, new_op.matrix_pos_rot_xyz.orientation.y); + lerp(old_op.matrix_pos_rot_xyz.orientation.y, new_op.matrix_pos_rot_xyz.orientation.y); tempS[2] = - lerp(old_op.matrix_pos_rot_xyz.orientation.z, new_op.matrix_pos_rot_xyz.orientation.z); + lerp(old_op.matrix_pos_rot_xyz.orientation.z, new_op.matrix_pos_rot_xyz.orientation.z); mtxf_rotate_zxy_and_translate(*gInterpolationMatrix, tempF, tempS); break; } case Op::MatrixScale: - // mtxf_scale(*gInterpolationMatrix, lerp(old_op.matrix_scale.scale, new_op.matrix_scale.scale)); + // mtxf_scale(*gInterpolationMatrix, lerp(old_op.matrix_scale.scale, + // new_op.matrix_scale.scale)); break; case Op::MatrixRotate1Coord: { -// s16 v = interpolate_angle(old_op.matrix_rotate_1_coord.value, -// new_op.matrix_rotate_1_coord.value); -// switch (new_op.matrix_rotate_1_coord.coord) { -// case 0: -// mtxf_rotate_x(*gInterpolationMatrix, v); -// break; -// -// case 1: -// mtxf_rotate_y(*gInterpolationMatrix, v); -// break; -// -// case 2: -// mtxf_s16_rotate_z(*gInterpolationMatrix, v); -// break; -// } + // s16 v = interpolate_angle(old_op.matrix_rotate_1_coord.value, + // new_op.matrix_rotate_1_coord.value); + // switch (new_op.matrix_rotate_1_coord.coord) { + // case 0: + // mtxf_rotate_x(*gInterpolationMatrix, v); + // break; + // + // case 1: + // mtxf_rotate_y(*gInterpolationMatrix, v); + // break; + // + // case 2: + // mtxf_s16_rotate_z(*gInterpolationMatrix, v); + // break; + // } break; } case Op::MatrixRotateXYCoords: { - s16 x = interpolate_angle(old_op.matrix_rotate_xy_coords.x, - new_op.matrix_rotate_xy_coords.x); - s16 y = interpolate_angle(old_op.matrix_rotate_xy_coords.y, - new_op.matrix_rotate_xy_coords.y); + s16 x = + interpolate_angle(old_op.matrix_rotate_xy_coords.x, new_op.matrix_rotate_xy_coords.x); + s16 y = + interpolate_angle(old_op.matrix_rotate_xy_coords.y, new_op.matrix_rotate_xy_coords.y); // mtxf_rotate_xy(*gInterpolationMatrix, y); break; } @@ -564,10 +564,12 @@ struct InterpolateCtx { &new_op.set_transform_matrix_data.positionVector); u16 rotationAngleTemp = lerp_s16(old_op.set_transform_matrix_data.rotationAngle, - new_op.set_transform_matrix_data.rotationAngle); - f32 scaleFactorTemp = lerp(old_op.set_transform_matrix_data.scaleFactor, new_op.set_transform_matrix_data.scaleFactor); + new_op.set_transform_matrix_data.rotationAngle); + f32 scaleFactorTemp = lerp(old_op.set_transform_matrix_data.scaleFactor, + new_op.set_transform_matrix_data.scaleFactor); - // set_transform_matrix(*gInterpolationMatrix, tmp_vec3f, tmp_vec3f2, rotationAngleTemp, scaleFactorTemp); + // set_transform_matrix(*gInterpolationMatrix, tmp_vec3f, tmp_vec3f2, rotationAngleTemp, + // scaleFactorTemp); break; } @@ -578,20 +580,22 @@ struct InterpolateCtx { &new_op.set_matrix_transformation_data.location); lerp_vec3s(&tmp_vec3s, *(Vec3s*)&old_op.set_matrix_transformation_data.rotation, - *(Vec3s*)&new_op.set_matrix_transformation_data.rotation); + *(Vec3s*)&new_op.set_matrix_transformation_data.rotation); - f32 scaleFactorTemp = lerp(old_op.set_matrix_transformation_data.scale, new_op.set_matrix_transformation_data.scale); + f32 scaleFactorTemp = lerp(old_op.set_matrix_transformation_data.scale, + new_op.set_matrix_transformation_data.scale); -// mtxf_set_matrix_transformation(*gInterpolationMatrix, tmp_vec3f, *(Vec3su*)&tmp_vec3s, scaleFactorTemp); + // mtxf_set_matrix_transformation(*gInterpolationMatrix, + // tmp_vec3f, *(Vec3su*)&tmp_vec3s, scaleFactorTemp); break; } - + case Op::SetTranslateRotate: { lerp_vec3f(&tmp_vec3f, &old_op.set_translate_rotate_data.location, &new_op.set_translate_rotate_data.location); lerp_vec3s(&tmp_vec3s, old_op.set_translate_rotate_data.rotation, - new_op.set_translate_rotate_data.rotation); + new_op.set_translate_rotate_data.rotation); // mtxf_translate_rotate(*gInterpolationMatrix, tmp_vec3f, tmp_vec3s); break; @@ -600,11 +604,14 @@ struct InterpolateCtx { tmp32[0] = lerp_s32(old_op.matrix_pos_rot_scale_xy.x, new_op.matrix_pos_rot_scale_xy.x); tmp32[1] = lerp_s32(old_op.matrix_pos_rot_scale_xy.y, new_op.matrix_pos_rot_scale_xy.y); - tmp_vec3s[0] = lerp_s16(old_op.matrix_pos_rot_scale_xy.angle, new_op.matrix_pos_rot_scale_xy.angle); + tmp_vec3s[0] = + lerp_s16(old_op.matrix_pos_rot_scale_xy.angle, new_op.matrix_pos_rot_scale_xy.angle); - tmp_vec3f[0] = lerp(old_op.matrix_pos_rot_scale_xy.scale, new_op.matrix_pos_rot_scale_xy.scale); + tmp_vec3f[0] = + lerp(old_op.matrix_pos_rot_scale_xy.scale, new_op.matrix_pos_rot_scale_xy.scale); - // mtxf_translation_x_y_rotate_z_scale_x_y(*gInterpolationMatrix, tmp32[0], tmp32[1], tmp_vec3s[0], tmp_vec3f[0]); + // mtxf_translation_x_y_rotate_z_scale_x_y(*gInterpolationMatrix, tmp32[0], tmp32[1], + // tmp_vec3s[0], tmp_vec3f[0]); break; } } @@ -682,14 +689,14 @@ void FrameInterpolation_DontInterpolateCamera(void) { } int FrameInterpolation_GetCameraEpoch(void) { - return (int) camera_epoch; + return (int)camera_epoch; } void FrameInterpolation_Record_SetTextMatrix(Mat4* matrix, f32 x, f32 y, f32 arg3, f32 arg4) { if (!check_if_recording()) { return; } - append(Op::SetTextMatrix).matrix_text = {matrix, x, y, arg3, arg4}; + append(Op::SetTextMatrix).matrix_text = { matrix, x, y, arg3, arg4 }; } void FrameInterpolation_RecordActorPosRotMatrix(void) { @@ -699,13 +706,13 @@ void FrameInterpolation_RecordActorPosRotMatrix(void) { next_is_actor_pos_rot_matrix = true; } -//void FrameInterpolation_RecordMatrixPush(Mat4* matrix) { -// if (!check_if_recording()) { -// return; -// } +// void FrameInterpolation_RecordMatrixPush(Mat4* matrix) { +// if (!check_if_recording()) { +// return; +// } // -// append(Op::MatrixPush).matrix_ptr = { (Mat4**) matrix }; -//} +// append(Op::MatrixPush).matrix_ptr = { (Mat4**) matrix }; +// } void FrameInterpolation_RecordMarker(const char* file, int line) { if (!check_if_recording()) { @@ -715,12 +722,12 @@ void FrameInterpolation_RecordMarker(const char* file, int line) { append(Op::Marker).marker = { file, line }; } -//void FrameInterpolation_RecordMatrixPop(Mat4* matrix) { -// if (!check_if_recording()) { -// return; -// } -// append(Op::MatrixPop).matrix_ptr = { (Mat4**) matrix }; -//} +// void FrameInterpolation_RecordMatrixPop(Mat4* matrix) { +// if (!check_if_recording()) { +// return; +// } +// append(Op::MatrixPop).matrix_ptr = { (Mat4**) matrix }; +// } void FrameInterpolation_RecordMatrixPut(MtxF* src) { if (!check_if_recording()) { @@ -748,7 +755,7 @@ void FrameInterpolation_RecordMatrixTranslate(Mat4* matrix, Vec3f b) { return; } // Note: Vec3f decays to pointer when passed as parameter. Cast directly, not &b. - append(Op::MatrixTranslate).matrix_translate = { matrix, *((Vec3fInterp*) b) }; + append(Op::MatrixTranslate).matrix_translate = { matrix, *((Vec3fInterp*)b) }; } void FrameInterpolation_RecordMatrixScale(Mat4* matrix, f32 scale) { @@ -765,25 +772,37 @@ void FrameInterpolation_RecordMatrixMultVec3fNoTranslate(Mat4* matrix, Vec3f src // append(Op::MatrixMultVec3fNoTranslate).matrix_vec_no_translate = { matrix, src, dest }; } -void FrameInterpolation_RecordSetTransformMatrix(Mat4* dest, Vec3f orientationVector, Vec3f positionVector, u16 rotationAngle, - f32 scaleFactor) { +void FrameInterpolation_RecordSetTransformMatrix(Mat4* dest, Vec3f orientationVector, Vec3f positionVector, + u16 rotationAngle, f32 scaleFactor) { if (!check_if_recording()) { return; } - append(Op::SetTransformMatrix).set_transform_matrix_data = { dest, {orientationVector[0], orientationVector[1], orientationVector[2]}, { positionVector[0], positionVector[1], positionVector[2] }, rotationAngle, scaleFactor}; + append(Op::SetTransformMatrix).set_transform_matrix_data = { + dest, + { orientationVector[0], orientationVector[1], orientationVector[2] }, + { positionVector[0], positionVector[1], positionVector[2] }, + rotationAngle, + scaleFactor + }; } void FrameInterpolation_RecordTranslateRotate(Mat4* dest, Vec3f pos, Vec3s rotation) { - if (!check_if_recording()) { return; } + if (!check_if_recording()) { + return; + } - append(Op::SetTranslateRotate).set_translate_rotate_data = { dest, {pos[0], pos[1], pos[2]}, { rotation[0], rotation[1], rotation[2] }}; + append(Op::SetTranslateRotate).set_translate_rotate_data = { dest, + { pos[0], pos[1], pos[2] }, + { rotation[0], rotation[1], rotation[2] } }; } void FrameInterpolation_RecordSetMatrixTransformation(Mat4* dest, Vec3f location, Vec3su rotation, f32 scale) { if (!check_if_recording()) { return; } - append(Op::SetMatrixTransformation).set_matrix_transformation_data = { dest, {location[0], location[1], location[2]}, { rotation[0], rotation[1], rotation[2] }, scale}; + append(Op::SetMatrixTransformation).set_matrix_transformation_data = { + dest, { location[0], location[1], location[2] }, { rotation[0], rotation[1], rotation[2] }, scale + }; } void FrameInterpolation_RecordCalculateOrientationMatrix(Mat3* dest, f32 x, f32 y, f32 z, s16 rot) { @@ -791,7 +810,7 @@ void FrameInterpolation_RecordCalculateOrientationMatrix(Mat3* dest, f32 x, f32 return; } - // append(Op::SetMatrixTransformation).set_calculate_orientation_matrix_data = { dest, x, y, z, rot}; + // append(Op::SetMatrixTransformation).set_calculate_orientation_matrix_data = { dest, x, y, z, rot}; } // Make a template for deref @@ -802,7 +821,7 @@ void FrameInterpolation_RecordMatrixPosRotXYZ(Mat4* out, Vec3f pos, Vec3s orient } // Note: Vec3f and Vec3s decay to pointers when passed as parameters. // We cast the pointer directly (not &pos which would be pointer-to-pointer). - append(Op::MatrixPosRotXYZ).matrix_pos_rot_xyz = { out, *((Vec3fInterp*) pos), *((Vec3sInterp*) orientation) }; + append(Op::MatrixPosRotXYZ).matrix_pos_rot_xyz = { out, *((Vec3fInterp*)pos), *((Vec3sInterp*)orientation) }; } void FrameInterpolation_RecordMatrixPosRotZXY(Mat4* out, Vec3f pos, Vec3s orientation) { @@ -811,7 +830,7 @@ void FrameInterpolation_RecordMatrixPosRotZXY(Mat4* out, Vec3f pos, Vec3s orient } // Note: Vec3f and Vec3s decay to pointers when passed as parameters. // We cast the pointer directly (not &pos which would be pointer-to-pointer). - append(Op::MatrixPosRotXYZ).matrix_pos_rot_xyz = { out, *((Vec3fInterp*) pos), *((Vec3sInterp*) orientation) }; + append(Op::MatrixPosRotXYZ).matrix_pos_rot_xyz = { out, *((Vec3fInterp*)pos), *((Vec3sInterp*)orientation) }; } void FrameInterpolation_RecordMatrixPosRotScaleXY(Mat4* matrix, s32 x, s32 y, u16 angle, f32 scale) { diff --git a/src/port/interpolation/matrix.c b/src/port/interpolation/matrix.c index 7f739409..0874acc9 100644 --- a/src/port/interpolation/matrix.c +++ b/src/port/interpolation/matrix.c @@ -3,7 +3,8 @@ #include "matrix.h" #include "FrameInterpolation.h" -Mtx gIdentityMtx = gdSPDefMtx(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); +Mtx gIdentityMtx = + gdSPDefMtx(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); Matrix gIdentityMatrix = { { { 1.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f, 0.0f }, @@ -44,7 +45,6 @@ void Matrix_InitOrtho(Gfx** dList) { FrameInterpolation_RecordCloseChild(); } - // Copies src Matrix into dst void Matrix_Copy(Matrix* dst, Matrix* src) { int32_t i; diff --git a/src/port/mods/PortEnhancements.c b/src/port/mods/PortEnhancements.c index 6aaa4cd6..94aff8d1 100644 --- a/src/port/mods/PortEnhancements.c +++ b/src/port/mods/PortEnhancements.c @@ -7,24 +7,18 @@ #include "assets/bin/segment2.h" -static const Mtx matrix_patch_identity = {{ - { 1.0f, 0.0f, 0.0f, 0.0f }, - { 0.0f, 1.0f, 0.0f, 0.0f }, - { 0.0f, 0.0f, 1.0f, 0.0f }, - { 0.0f, 0.0f, 0.0f, 1.0f } -}}; - +static const Mtx matrix_patch_identity = { + { { 1.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } } +}; // 0x020144B0 - 0x020144F0 -static const Mtx matrix_patch_fullscreen = {{ - { 2.0f / SCREEN_WIDTH, 0.0f, 0.0f, 0.0f }, - { 0.0f, 2.0f / SCREEN_HEIGHT, 0.0f, 0.0f }, - { 0.0f, 0.0f, -1.0f, 0.0f }, - { -1.0f, -1.0f, -1.0f, 1.0f } -}}; +static const Mtx matrix_patch_fullscreen = { { { 2.0f / SCREEN_WIDTH, 0.0f, 0.0f, 0.0f }, + { 0.0f, 2.0f / SCREEN_HEIGHT, 0.0f, 0.0f }, + { 0.0f, 0.0f, -1.0f, 0.0f }, + { -1.0f, -1.0f, -1.0f, 1.0f } } }; void OnLivesChange(IEvent* event) { - PlayerLivesChange* ev = (PlayerLivesChange*) event; + PlayerLivesChange* ev = (PlayerLivesChange*)event; if (CVarGetInteger("gCheats.InfiniteLives", 0) == 0 || ev->lives > 0) { return; } @@ -33,7 +27,7 @@ void OnLivesChange(IEvent* event) { } void OnHealthChange(IEvent* event) { - PlayerHealthChange* ev = (PlayerHealthChange*) event; + PlayerHealthChange* ev = (PlayerHealthChange*)event; if (CVarGetInteger("gCheats.InfiniteHealth", 0) == 0 || ev->health > 0) { return; } @@ -57,35 +51,22 @@ void PatchSetupDList() { Gfx nop = gsSPNoOp(); // 0 - GfxPatch pt_mtx_fullscreen[] = { - { 4, identity }, - { 5, nop }, - { 6, fullscreen }, - { 7, nop }, - { 8, model }, - { 9, nop } - }; - ResourceMgr_PatchGfxByName(dl_proj_mtx_fullscreen, "SetupFullscreenProjMtx", pt_mtx_fullscreen, ARRAY_COUNT(pt_mtx_fullscreen)); + GfxPatch pt_mtx_fullscreen[] = { { 4, identity }, { 5, nop }, { 6, fullscreen }, + { 7, nop }, { 8, model }, { 9, nop } }; + ResourceMgr_PatchGfxByName(dl_proj_mtx_fullscreen, "SetupFullscreenProjMtx", pt_mtx_fullscreen, + ARRAY_COUNT(pt_mtx_fullscreen)); // 1 - GfxPatch pt_skybox_begin[] = { - { 6, identity }, - { 7, nop } - }; + GfxPatch pt_skybox_begin[] = { { 6, identity }, { 7, nop } }; ResourceMgr_PatchGfxByName(dl_skybox_begin, "SetupSkyboxBegin", pt_skybox_begin, ARRAY_COUNT(pt_skybox_begin)); - + // 2 - GfxPatch pt_skybox_tile_settings[] = { - { 0, model }, - { 1, nop } - }; - ResourceMgr_PatchGfxByName(dl_skybox_tile_tex_settings, "SetupSkyboxTileTexSettings", pt_skybox_tile_settings, ARRAY_COUNT(pt_skybox_tile_settings)); + GfxPatch pt_skybox_tile_settings[] = { { 0, model }, { 1, nop } }; + ResourceMgr_PatchGfxByName(dl_skybox_tile_tex_settings, "SetupSkyboxTileTexSettings", pt_skybox_tile_settings, + ARRAY_COUNT(pt_skybox_tile_settings)); // 3 - GfxPatch pt_up_arrow[] = { - { 7, identity }, - { 8, nop } - }; + GfxPatch pt_up_arrow[] = { { 7, identity }, { 8, nop } }; ResourceMgr_PatchGfxByName(dl_ia8_up_arrow_begin, "SetupUpArrowBegin", pt_up_arrow, ARRAY_COUNT(pt_up_arrow)); } diff --git a/src/port/ui/GhostshipGui.cpp b/src/port/ui/GhostshipGui.cpp index 425537f5..c60fbb42 100644 --- a/src/port/ui/GhostshipGui.cpp +++ b/src/port/ui/GhostshipGui.cpp @@ -46,8 +46,8 @@ void SetupGuiElements() { mSaveEditorWindow = std::make_shared(CVAR_WINDOW("SaveEditor"), "Save Editor"); gui->AddGuiWindow(mSaveEditorWindow); - mInputEditorWindow = std::make_shared( - CVAR_WINDOW("ControllerConfiguration"), "Configure Controller"); + mInputEditorWindow = + std::make_shared(CVAR_WINDOW("ControllerConfiguration"), "Configure Controller"); gui->AddGuiWindow(mInputEditorWindow); mNotificationWindow = std::make_shared(CVAR_WINDOW("Notifications"), "Notifications Window"); diff --git a/src/port/ui/GhostshipInputEditorWindow.cpp b/src/port/ui/GhostshipInputEditorWindow.cpp index 4c6dae81..ab2433ea 100644 --- a/src/port/ui/GhostshipInputEditorWindow.cpp +++ b/src/port/ui/GhostshipInputEditorWindow.cpp @@ -180,7 +180,7 @@ void GhostshipInputEditorWindow::DrawAnalogPreview(const char* label, ImVec2 sti #define BUTTON_COLOR_GAMEPAD_PURPLE_HOVERED ImVec4(0.431f, 0.369f, 0.706f, 1.0f) void GhostshipInputEditorWindow::GetButtonColorsForDeviceType(Ship::PhysicalDeviceType lusIndex, ImVec4& buttonColor, - ImVec4& buttonHoveredColor) { + ImVec4& buttonHoveredColor) { switch (lusIndex) { case Ship::PhysicalDeviceType::Keyboard: buttonColor = BUTTON_COLOR_KEYBOARD_BEIGE; @@ -439,7 +439,7 @@ void GhostshipInputEditorWindow::DrawButtonLineEditMappingButton(uint8_t port, N } void GhostshipInputEditorWindow::DrawButtonLine(const char* buttonName, uint8_t port, N64ButtonMask bitmask, - ImVec4 color = CHIP_COLOR_N64_GREY) { + ImVec4 color = CHIP_COLOR_N64_GREY) { ImGui::NewLine(); ImGui::SameLine(SCALE_IMGUI_SIZE(32.0f)); DrawInputChip(buttonName, color); @@ -451,7 +451,7 @@ void GhostshipInputEditorWindow::DrawButtonLine(const char* buttonName, uint8_t } void GhostshipInputEditorWindow::DrawStickDirectionLineAddMappingButton(uint8_t port, uint8_t stick, - Ship::Direction direction) { + Ship::Direction direction) { ImGui::PushStyleVar(ImGuiStyleVar_ButtonTextAlign, ImVec2(1.0f, 0.5f)); auto popupId = StringHelper::Sprintf("addStickDirectionMappingPopup##%d-%d-%d", port, stick, direction); if (ImGui::Button( @@ -495,7 +495,7 @@ void GhostshipInputEditorWindow::DrawStickDirectionLineAddMappingButton(uint8_t } void GhostshipInputEditorWindow::DrawStickDirectionLineEditMappingButton(uint8_t port, uint8_t stick, - Ship::Direction direction, std::string id) { + Ship::Direction direction, std::string id) { std::shared_ptr mapping = nullptr; if (stick == Ship::LEFT) { mapping = Ship::Context::GetInstance() @@ -610,8 +610,7 @@ void GhostshipInputEditorWindow::DrawStickDirectionLineEditMappingButton(uint8_t } void GhostshipInputEditorWindow::DrawStickDirectionLine(const char* axisDirectionName, uint8_t port, uint8_t stick, - Ship::Direction direction, - ImVec4 color = CHIP_COLOR_N64_GREY) { + Ship::Direction direction, ImVec4 color = CHIP_COLOR_N64_GREY) { ImGui::NewLine(); ImGui::SameLine(); ImGui::BeginDisabled(); @@ -1234,7 +1233,7 @@ void GhostshipInputEditorWindow::addButtonName(N64ButtonMask mask, const char* n // Draw a button mapping setting consisting of a padded label and button dropdown. // excludedButtons indicates which buttons are unavailable to choose from. void GhostshipInputEditorWindow::DrawMapping(CustomButtonMap& mapping, float labelWidth, - N64ButtonMask excludedButtons) { + N64ButtonMask excludedButtons) { N64ButtonMask currentButton = CVarGetInteger(mapping.cVarName, mapping.defaultBtn); const char* preview; diff --git a/src/port/ui/GhostshipMenuDevTools.cpp b/src/port/ui/GhostshipMenuDevTools.cpp index 4c51b476..5b6378f7 100644 --- a/src/port/ui/GhostshipMenuDevTools.cpp +++ b/src/port/ui/GhostshipMenuDevTools.cpp @@ -41,38 +41,36 @@ void GhostshipMenu::AddMenuDevTools() { " This does not affect the log file output") .ComboMap(logLevels) .DefaultIndex(defaultLogLevel)) - .Callback([](WidgetInfo &info) { + .Callback([](WidgetInfo& info) { Ship::Context::GetInstance()->GetLogger()->set_level( - (spdlog::level::level_enum) CVarGetInteger(CVAR_DEVELOPER_TOOLS("LogLevel"), - defaultLogLevel)); + (spdlog::level::level_enum)CVarGetInteger(CVAR_DEVELOPER_TOOLS("LogLevel"), defaultLogLevel)); }) - .PreFunc([](WidgetInfo &info) { + .PreFunc([](WidgetInfo& info) { info.isHidden = mGhostshipMenu->disabledMap.at(DISABLE_FOR_DEBUG_MODE_OFF).active; }); #ifdef USE_GBI_TRACE AddWidget(path, "GFX Trace Mode", WIDGET_CVAR_CHECKBOX) .CVar(CVAR_DEVELOPER_TOOLS("GFXTrace")) - .Options(CheckboxOptions().Tooltip("Enables the Gfx trace mode, which will output information about the Gfx commands being run.")); + .Options(CheckboxOptions().Tooltip( + "Enables the Gfx trace mode, which will output information about the Gfx commands being run.")); #endif AddWidget(path, "Debug Mode", WIDGET_CVAR_CHECKBOX) .CVar(CVAR_DEVELOPER_TOOLS("DebugMode")) .Options(CheckboxOptions().Tooltip("Various debug features, including a level selector from the main menu.")); AddWidget(path, "Better Level Select", WIDGET_CVAR_CHECKBOX) .CVar(CVAR_DEVELOPER_TOOLS("BetterLevelSelect")) - .Options(CheckboxOptions().Tooltip("Tweaks to the level select screen, like naming and allowing C-buttons to be used.")) - .PreFunc([](WidgetInfo &info) { - info.options->Disabled(!CVarGetInteger(CVAR_DEVELOPER_TOOLS("DebugMode"), 0)); - }); + .Options(CheckboxOptions().Tooltip( + "Tweaks to the level select screen, like naming and allowing C-buttons to be used.")) + .PreFunc( + [](WidgetInfo& info) { info.options->Disabled(!CVarGetInteger(CVAR_DEVELOPER_TOOLS("DebugMode"), 0)); }); AddWidget(path, "Draw Debug Info", WIDGET_CVAR_CHECKBOX) .CVar(CVAR_DEVELOPER_TOOLS("DrawDebugInfo")) .Options(CheckboxOptions().Tooltip("Draws Debug Related Information")); AddWidget(path, "Debug Info Mode", WIDGET_CVAR_COMBOBOX) .CVar(CVAR_DEVELOPER_TOOLS("DebugInfoPage")) - .Options(ComboboxOptions() - .Tooltip("Select Debug Page") - .ComboMap(debugInfoPages) - .DefaultIndex(DEBUG_PAGE_OBJECTINFO)) - .PreFunc([](WidgetInfo &info) { + .Options( + ComboboxOptions().Tooltip("Select Debug Page").ComboMap(debugInfoPages).DefaultIndex(DEBUG_PAGE_OBJECTINFO)) + .PreFunc([](WidgetInfo& info) { info.options->Disabled(!CVarGetInteger(CVAR_DEVELOPER_TOOLS("DrawDebugInfo"), 0)); }); @@ -84,7 +82,6 @@ void GhostshipMenu::AddMenuDevTools() { .WindowName("Save Editor") .HideInSearch(true) .Options(WindowButtonOptions().Tooltip("Enables the separate Save Editor Window.")); - } } // namespace GhostshipGui diff --git a/src/port/ui/GhostshipMenuSettings.cpp b/src/port/ui/GhostshipMenuSettings.cpp index ab213f75..b0418470 100644 --- a/src/port/ui/GhostshipMenuSettings.cpp +++ b/src/port/ui/GhostshipMenuSettings.cpp @@ -124,7 +124,7 @@ void GhostshipMenu::AddMenuSettings() { .DefaultIndex(1) .ComponentAlignment(ComponentAlignments::Right) .LabelPosition(LabelPositions::Far)) - .Callback([](WidgetInfo& info) { GameEngine::Instance->ScaleImGui(); }); + .Callback([](WidgetInfo& info) { GameEngine::Instance->ScaleImGui(); }); // General - About path.column = SECTION_COLUMN_2; @@ -171,8 +171,7 @@ void GhostshipMenu::AddMenuSettings() { .RaceDisable(false) .Options(IntSliderOptions().Min(0).Max(100).DefaultValue(100).ShowButtons(true).Format("")) .Callback([](WidgetInfo& info) { - audio_set_player_volume(SEQ_PLAYER_SFX, - ((float) CVarGetInteger(CVAR_SETTING("Volume.SFX"), 100) / 100.0f)); + audio_set_player_volume(SEQ_PLAYER_SFX, ((float)CVarGetInteger(CVAR_SETTING("Volume.SFX"), 100) / 100.0f)); }); AddWidget(path, "Audio API (Needs reload)", WIDGET_AUDIO_BACKEND).RaceDisable(false); diff --git a/src/port/ui/GhostshipModals.cpp b/src/port/ui/GhostshipModals.cpp index 58d1bc64..7a217218 100644 --- a/src/port/ui/GhostshipModals.cpp +++ b/src/port/ui/GhostshipModals.cpp @@ -69,8 +69,8 @@ void GhostshipModalWindow::DrawElement() { } void GhostshipModalWindow::RegisterPopup(std::string title, std::string message, std::string button1, - std::string button2, std::function button1callback, - std::function button2callback) { + std::string button2, std::function button1callback, + std::function button2callback) { modals.push_back({ title, message, button1, button2, button1callback, button2callback }); } diff --git a/src/port/ui/Notification.cpp b/src/port/ui/Notification.cpp index 58d97518..79f7a105 100644 --- a/src/port/ui/Notification.cpp +++ b/src/port/ui/Notification.cpp @@ -21,7 +21,7 @@ void Window::Draw() { switch (position) { case 0: // Top Left basePosition = ImVec2(vp->Pos.x + margin, vp->Pos.y + margin); - break; + break; case 1: // Top Right basePosition = ImVec2(vp->Pos.x + vp->Size.x - margin, vp->Pos.y + margin); break; @@ -38,8 +38,10 @@ void Window::Draw() { ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0, 0, 0, CVarGetFloat("gSettings.Notifications.BgOpacity", 0.5f))); ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0, 0, 0, 0)); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 4.0f); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(8.0f * CVarGetFloat("gSettings.Notifications.Size", 1.8f), 6.0f)); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8.0f * CVarGetFloat("gSettings.Notifications.Size", 1.8f), 8.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, + ImVec2(8.0f * CVarGetFloat("gSettings.Notifications.Size", 1.8f), 6.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, + ImVec2(8.0f * CVarGetFloat("gSettings.Notifications.Size", 1.8f), 8.0f)); for (int index = 0; index < notifications.size(); ++index) { auto& notification = notifications[index]; @@ -53,33 +55,30 @@ void Window::Draw() { } ImGui::Begin(("notification#" + std::to_string(notification.id)).c_str(), nullptr, - ImGuiWindowFlags_AlwaysAutoResize | - ImGuiWindowFlags_NoNav | - ImGuiWindowFlags_NoFocusOnAppearing | - ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoDocking | - ImGuiWindowFlags_NoTitleBar | - ImGuiWindowFlags_NoScrollWithMouse | - ImGuiWindowFlags_NoInputs | - ImGuiWindowFlags_NoMove | - ImGuiWindowFlags_NoScrollbar - ); + ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoFocusOnAppearing | + ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | + ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoScrollbar); ImGui::SetWindowFontScale(CVarGetFloat("gSettings.Notifications.Size", 1.8f)); ImVec2 notificationPos; switch (position) { case 0: // Top Left - notificationPos = ImVec2(basePosition.x, basePosition.y + ((ImGui::GetWindowSize().y + padding) * inverseIndex)); + notificationPos = + ImVec2(basePosition.x, basePosition.y + ((ImGui::GetWindowSize().y + padding) * inverseIndex)); break; case 1: // Top Right - notificationPos = ImVec2(basePosition.x - ImGui::GetWindowSize().x, basePosition.y + ((ImGui::GetWindowSize().y + padding) * inverseIndex)); + notificationPos = ImVec2(basePosition.x - ImGui::GetWindowSize().x, + basePosition.y + ((ImGui::GetWindowSize().y + padding) * inverseIndex)); break; case 2: // Bottom Left - notificationPos = ImVec2(basePosition.x, basePosition.y - ((ImGui::GetWindowSize().y + padding) * (inverseIndex + 1))); + notificationPos = ImVec2(basePosition.x, + basePosition.y - ((ImGui::GetWindowSize().y + padding) * (inverseIndex + 1))); break; case 3: // Bottom Right - notificationPos = ImVec2(basePosition.x - ImGui::GetWindowSize().x, basePosition.y - ((ImGui::GetWindowSize().y + padding) * (inverseIndex + 1))); + notificationPos = ImVec2(basePosition.x - ImGui::GetWindowSize().x, + basePosition.y - ((ImGui::GetWindowSize().y + padding) * (inverseIndex + 1))); break; } @@ -87,9 +86,9 @@ void Window::Draw() { ImGui::AlignTextToFramePadding(); if (notification.itemIcon != nullptr) { - ImGui::Image( - Ship::Context::GetInstance()->GetWindow()->GetGui()->GetTextureByName(notification.itemIcon), - ImVec2(24 * CVarGetFloat("gSettings.Notifications.Size", 1.8f), 24 * CVarGetFloat("gSettings.Notifications.Size", 1.8f))); + ImGui::Image(Ship::Context::GetInstance()->GetWindow()->GetGui()->GetTextureByName(notification.itemIcon), + ImVec2(24 * CVarGetFloat("gSettings.Notifications.Size", 1.8f), + 24 * CVarGetFloat("gSettings.Notifications.Size", 1.8f))); ImGui::SameLine(); } if (!notification.prefix.empty()) { @@ -110,7 +109,6 @@ void Window::Draw() { ImGui::PopStyleColor(2); } - void Window::UpdateElement() { for (int index = 0; index < notifications.size(); ++index) { auto& notification = notifications[index]; diff --git a/src/port/ui/ResolutionEditor.cpp b/src/port/ui/ResolutionEditor.cpp index 755400cd..3ea166f2 100644 --- a/src/port/ui/ResolutionEditor.cpp +++ b/src/port/ui/ResolutionEditor.cpp @@ -35,20 +35,19 @@ namespace GhostshipGui { extern std::shared_ptr mGhostshipMenu; enum setting { UPDATE_aspectRatioX, UPDATE_aspectRatioY, UPDATE_verticalPixelCount }; -std::unordered_map aspectRatioPresetLabels = { { 0, "Off" }, - { 1, "Custom" }, - { 2, "Original (4:3)" }, - { 3, "Widescreen (16:9)" }, - { 4, "Nintendo 3DS (5:3)" }, - { 5, "16:10 (8:5)" }, - { 6, "Ultrawide (21:9)" } }; +std::unordered_map aspectRatioPresetLabels = { { 0, "Off" }, + { 1, "Custom" }, + { 2, "Original (4:3)" }, + { 3, "Widescreen (16:9)" }, + { 4, "Nintendo 3DS (5:3)" }, + { 5, "16:10 (8:5)" }, + { 6, "Ultrawide (21:9)" } }; const float aspectRatioPresetsX[] = { 0.0f, 16.0f, 4.0f, 16.0f, 5.0f, 16.0f, 21.0f }; const float aspectRatioPresetsY[] = { 0.0f, 9.0f, 3.0f, 9.0f, 3.0f, 10.0f, 9.0f }; const int default_aspectRatio = 1; // Default combo list option -const char *pixelCountPresetLabels[] = { "Custom", "Native N64 (240p)", "2x (480p)", - "3x (720p)", "4x (960p)", "5x (1200p)", - "6x (1440p)", "Full HD (1080p)", "4K (2160p)" }; +const char* pixelCountPresetLabels[] = { "Custom", "Native N64 (240p)", "2x (480p)", "3x (720p)", "4x (960p)", + "5x (1200p)", "6x (1440p)", "Full HD (1080p)", "4K (2160p)" }; const int pixelCountPresets[] = { 480, 240, 480, 720, 960, 1200, 1440, 1080, 2160 }; const int default_pixelCount = 0; // Default combo list option @@ -56,7 +55,7 @@ const int default_pixelCount = 0; // Default combo list option const uint32_t minVerticalPixelCount = SCREEN_HEIGHT; const uint32_t maxVerticalPixelCount = 4320; // 18x native, or 8K TV resolution - const unsigned short default_maxIntegerScaleFactor = 6; // Default size of Integer scale factor slider. +const unsigned short default_maxIntegerScaleFactor = 6; // Default size of Integer scale factor slider. enum messageType { MESSAGE_ERROR, MESSAGE_WARNING, MESSAGE_QUESTION, MESSAGE_INFO, MESSAGE_GRAY_75 }; const ImVec4 messageColor[]{ @@ -71,9 +70,8 @@ static const float enhancementSpacerHeight = 19.0f; static bool update[3]; // Initialise integer scale bounds. -static short max_integerScaleFactor = - default_maxIntegerScaleFactor; // default value, which may or may not get - // overridden depending on viewport res +static short max_integerScaleFactor = default_maxIntegerScaleFactor; // default value, which may or may not get + // overridden depending on viewport res static short integerScale_maximumBounds = 1; // can change when window is resized @@ -103,7 +101,7 @@ std::shared_ptr GetInterpreter() { return intP; } -void ResolutionCustomWidget(WidgetInfo &info) { +void ResolutionCustomWidget(WidgetInfo& info) { ImGui::BeginDisabled(disabled_everything); // Vertical Resolution UIWidgets::CVarCheckbox("Set fixed vertical resolution (disables resolution slider)", @@ -117,8 +115,8 @@ void ResolutionCustomWidget(WidgetInfo &info) { // } UIWidgets::PushStyleCombobox(THEME_COLOR); if (ImGui::Combo("Pixel Count Presets", &item_pixelCount, pixelCountPresetLabels, - IM_ARRAYSIZE(pixelCountPresetLabels)) - && item_pixelCount != default_pixelCount) { // don't change anything if "Custom" is selected. + IM_ARRAYSIZE(pixelCountPresetLabels)) && + item_pixelCount != default_pixelCount) { // don't change anything if "Custom" is selected. verticalPixelCount = pixelCountPresets[item_pixelCount]; if (showHorizontalResField) { @@ -183,22 +181,19 @@ void ResolutionCustomWidget(WidgetInfo &info) { // Integer scaling settings group (Pixel Perfect Mode) static const ImGuiTreeNodeFlags IntegerScalingResolvedImGuiFlag = - CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".PixelPerfectMode", 0) - ? ImGuiTreeNodeFlags_DefaultOpen - : ImGuiTreeNodeFlags_None; + CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".PixelPerfectMode", 0) ? ImGuiTreeNodeFlags_DefaultOpen + : ImGuiTreeNodeFlags_None; UIWidgets::PushStyleHeader(THEME_COLOR); if (ImGui::CollapsingHeader("Integer Scaling Settings", IntegerScalingResolvedImGuiFlag)) { const bool disabled_pixelPerfectMode = - !CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".PixelPerfectMode", 0) - || disabled_everything; + !CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".PixelPerfectMode", 0) || disabled_everything; // Pixel Perfect Mode UIWidgets::CVarCheckbox( "Pixel Perfect Mode", CVAR_PREFIX_ADVANCED_RESOLUTION ".PixelPerfectMode", UIWidgets::CheckboxOptions({ { .disabled = disabled_pixelCount || disabled_everything } }) .Tooltip("Don't scale image to fill window.") .Color(THEME_COLOR)); - if (disabled_pixelCount - && CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".PixelPerfectMode", 0)) { + if (disabled_pixelCount && CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".PixelPerfectMode", 0)) { CVarSetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".PixelPerfectMode", 0); Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); } @@ -208,38 +203,32 @@ void ResolutionCustomWidget(WidgetInfo &info) { fmt::format("Integer scale factor: {}", max_integerScaleFactor).c_str(), CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.Factor", UIWidgets::IntSliderOptions( - { { .disabled = disabled_pixelPerfectMode - || CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION - ".IntegerScale.FitAutomatically", - 0) } }) + { { .disabled = disabled_pixelPerfectMode || + CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.FitAutomatically", 0) } }) .Min(1) .Max(max_integerScaleFactor) .DefaultValue(1) .Tooltip("Integer scales the image. Only available in Pixel Perfect Mode.") .Color(THEME_COLOR)); // Display warning if size is being clamped or if framebuffer is larger than viewport. - if (!disabled_pixelPerfectMode - && (CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.NeverExceedBounds", 1) - && CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.Factor", 1) - > integerScale_maximumBounds)) { + if (!disabled_pixelPerfectMode && + (CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.NeverExceedBounds", 1) && + CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.Factor", 1) > integerScale_maximumBounds)) { ImGui::SameLine(); - ImGui::TextColored(messageColor[MESSAGE_WARNING], - ICON_FA_EXCLAMATION_TRIANGLE " Window exceeded."); + ImGui::TextColored(messageColor[MESSAGE_WARNING], ICON_FA_EXCLAMATION_TRIANGLE " Window exceeded."); } - UIWidgets::CVarCheckbox( - "Automatically scale image to fit viewport", - CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.FitAutomatically", - UIWidgets::CheckboxOptions({ { .disabled = disabled_pixelPerfectMode } }) - .DefaultValue(true) - .Color(THEME_COLOR) - .Tooltip("Automatically sets scale factor to fit window. Only available in Pixel " - "Perfect Mode.")); + UIWidgets::CVarCheckbox("Automatically scale image to fit viewport", + CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.FitAutomatically", + UIWidgets::CheckboxOptions({ { .disabled = disabled_pixelPerfectMode } }) + .DefaultValue(true) + .Color(THEME_COLOR) + .Tooltip("Automatically sets scale factor to fit window. Only available in Pixel " + "Perfect Mode.")); if (CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.FitAutomatically", 0)) { // This is just here to update the value shown on the slider. // The function in LUS to handle this setting will ignore IntegerScaleFactor while active. - CVarSetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.Factor", - integerScale_maximumBounds); + CVarSetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.Factor", integerScale_maximumBounds); Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); } } // End of integer scaling settings @@ -259,8 +248,8 @@ void ResolutionCustomWidget(WidgetInfo &info) { "Not available in Pixel Perfect Mode.", CVAR_PREFIX_ADVANCED_RESOLUTION ".IgnoreAspectCorrection", UIWidgets::CheckboxOptions( - { { .disabled = CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".PixelPerfectMode", 0) - || disabled_everything } }) + { { .disabled = CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".PixelPerfectMode", 0) || + disabled_everything } }) .Color(THEME_COLOR)); #else if (CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IgnoreAspectCorrection", 0)) { @@ -278,8 +267,7 @@ void ResolutionCustomWidget(WidgetInfo &info) { #endif // A requested addition; an alternative way of displaying the resolution field. - if (UIWidgets::Checkbox("Show a horizontal resolution field, instead of aspect ratio.", - &showHorizontalResField, + if (UIWidgets::Checkbox("Show a horizontal resolution field, instead of aspect ratio.", &showHorizontalResField, UIWidgets::CheckboxOptions().Color(THEME_COLOR))) { if (!showHorizontalResField && (aspectRatioX > 0.0f)) { // when turning this setting off // Refresh relevant values @@ -302,9 +290,9 @@ void ResolutionCustomWidget(WidgetInfo &info) { // Integer Scaling - Never Exceed Bounds. const bool disabled_neverExceedBounds = - !CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".PixelPerfectMode", 0) - || CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.FitAutomatically", 0) - || disabled_everything; + !CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".PixelPerfectMode", 0) || + CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.FitAutomatically", 0) || + disabled_everything; if (UIWidgets::CVarCheckbox( "Prevent integer scaling from exceeding screen bounds.\n" "(Makes screen bounds take priority over specified factor.)", @@ -318,17 +306,14 @@ void ResolutionCustomWidget(WidgetInfo &info) { "want to crop " "overscan.\n\n" " " ICON_FA_INFO_CIRCLE " Please note that exceeding screen bounds " - "may show a scroll bar on-screen.") + "may show a scroll bar on-screen.") .Color(THEME_COLOR) .DefaultValue(true))) { // Initialise the (currently unused) "Exceed Bounds By" cvar if it's been changed. if (CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.ExceedBoundsBy", 0)) { CVarSetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.ExceedBoundsBy", 0); - Ship::Context::GetInstance() - ->GetWindow() - ->GetGui() - ->SaveConsoleVariablesNextFrame(); + Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); } } @@ -339,9 +324,8 @@ void ResolutionCustomWidget(WidgetInfo &info) { "Allow integer scale factor to go +1 above maximum screen bounds.", CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.ExceedBoundsBy", UIWidgets::CheckboxOptions( - { { .disabled = - !CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".PixelPerfectMode", 0) - || disabled_everything } }) + { { .disabled = !CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".PixelPerfectMode", 0) || + disabled_everything } }) .Color(THEME_COLOR)); // It does actually function as expected, but exceeding the bottom of the screen shows a @@ -349,8 +333,8 @@ void ResolutionCustomWidget(WidgetInfo &info) { // simplicity. // Display an info message about the scroll bar. - if (!CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.NeverExceedBounds", 1) - || CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.ExceedBoundsBy", 0)) { + if (!CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.NeverExceedBounds", 1) || + CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.ExceedBoundsBy", 0)) { ImGui::TextColored(messageColor[MESSAGE_INFO], " " ICON_FA_INFO_CIRCLE " A scroll bar may become visible if screen bounds are exceeded."); @@ -360,12 +344,8 @@ void ResolutionCustomWidget(WidgetInfo &info) { if (CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.ExceedBoundsBy", 0)) { if (UIWidgets::Button("Click to reset a console variable that may be causing this.", UIWidgets::ButtonOptions().Color(THEME_COLOR))) { - CVarSetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.ExceedBoundsBy", - 0); - Ship::Context::GetInstance() - ->GetWindow() - ->GetGui() - ->SaveConsoleVariablesNextFrame(); + CVarSetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.ExceedBoundsBy", 0); + Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); } UIWidgets::Spacer(2); } @@ -388,12 +368,12 @@ void ResolutionCustomWidget(WidgetInfo &info) { } UIWidgets::PaddedEnhancementCheckbox( - "Don't allow integer scaling to exceed screen bounds.\n" - "(Makes screen bounds take priority over specified factor.)", - "gAdvancedResolution.IntegerScale.NeverExceedBounds", true, false, - !CVarGetInteger("gAdvancedResolution.PixelPerfectMode", 0) || + "Don't allow integer scaling to exceed screen bounds.\n" + "(Makes screen bounds take priority over specified factor.)", + "gAdvancedResolution.IntegerScale.NeverExceedBounds", true, false, + !CVarGetInteger("gAdvancedResolution.PixelPerfectMode", 0) || CVarGetInteger("gAdvancedResolution.IntegerScale.FitAutomatically", 0), - "", UIWidgets::CheckboxGraphics::Cross, true); + "", UIWidgets::CheckboxGraphics::Cross, true); if (!CVarGetInteger("gAdvancedResolution.IntegerScale.NeverExceedBounds", 1) || CVarGetInteger("gAdvancedResolution.IntegerScale.ExceedBoundsBy", 0)) { @@ -465,8 +445,7 @@ void ResolutionCustomWidget(WidgetInfo &info) { UIWidgets::PopStyleHeader(); // Clamp and update the cvars that don't use UIWidgets - if (update[UPDATE_aspectRatioX] || update[UPDATE_aspectRatioY] - || update[UPDATE_verticalPixelCount]) { + if (update[UPDATE_aspectRatioX] || update[UPDATE_aspectRatioY] || update[UPDATE_verticalPixelCount]) { if (update[UPDATE_aspectRatioX]) { if (aspectRatioX < 0.0f) { aspectRatioX = 0.0f; @@ -505,15 +484,14 @@ void RegisterResolutionWidgets() { // Resolution visualiser mGhostshipMenu->AddWidget(path, "Viewport dimensions: {} x {}", WIDGET_TEXT) .RaceDisable(false) - .PreFunc([](WidgetInfo &info) { + .PreFunc([](WidgetInfo& info) { auto gfx_current_game_window_viewport = GetInterpreter().get()->mGameWindowViewport; - info.name = - fmt::format("Viewport dimensions: {} x {}", gfx_current_game_window_viewport.width, - gfx_current_game_window_viewport.height); + info.name = fmt::format("Viewport dimensions: {} x {}", gfx_current_game_window_viewport.width, + gfx_current_game_window_viewport.height); }); mGhostshipMenu->AddWidget(path, "Internal resolution: {} x {}", WIDGET_TEXT) .RaceDisable(false) - .PreFunc([](WidgetInfo &info) { + .PreFunc([](WidgetInfo& info) { auto gfx_current_dimensions = GetInterpreter().get()->mCurDimensions; info.name = fmt::format("Internal resolution: {} x {}", gfx_current_dimensions.width, gfx_current_dimensions.height); @@ -525,46 +503,40 @@ void RegisterResolutionWidgets() { .RaceDisable(false); // Error/Warning display mGhostshipMenu - ->AddWidget(path, - ICON_FA_EXCLAMATION_TRIANGLE " Significant frame rate (FPS) drops may be occuring.", + ->AddWidget(path, ICON_FA_EXCLAMATION_TRIANGLE " Significant frame rate (FPS) drops may be occuring.", WIDGET_TEXT) .RaceDisable(false) - .PreFunc([](WidgetInfo &info) { - info.isHidden = !(!CVarGetInteger(CVAR_LOW_RES_MODE, 0) && IsDroppingFrames()); - }) + .PreFunc( + [](WidgetInfo& info) { info.isHidden = !(!CVarGetInteger(CVAR_LOW_RES_MODE, 0) && IsDroppingFrames()); }) .Options(TextOptions().Color(Colors::Orange)); - mGhostshipMenu - ->AddWidget(path, ICON_FA_QUESTION_CIRCLE " \"N64 Mode\" is overriding these settings.", - WIDGET_TEXT) + mGhostshipMenu->AddWidget(path, ICON_FA_QUESTION_CIRCLE " \"N64 Mode\" is overriding these settings.", WIDGET_TEXT) .RaceDisable(false) - .PreFunc([](WidgetInfo &info) { info.isHidden = !CVarGetInteger(CVAR_LOW_RES_MODE, 0); }) + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger(CVAR_LOW_RES_MODE, 0); }) .Options(TextOptions().Color(Colors::LightBlue)); mGhostshipMenu->AddWidget(path, "Click to disable N64 mode", WIDGET_BUTTON) .RaceDisable(false) - .PreFunc([](WidgetInfo &info) { info.isHidden = !CVarGetInteger(CVAR_LOW_RES_MODE, 0); }) - .Callback([](WidgetInfo &info) { + .PreFunc([](WidgetInfo& info) { info.isHidden = !CVarGetInteger(CVAR_LOW_RES_MODE, 0); }) + .Callback([](WidgetInfo& info) { CVarSetInteger(CVAR_LOW_RES_MODE, 0); Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); }); // Aspect Ratio - mGhostshipMenu->AddWidget(path, "AspectSep", WIDGET_SEPARATOR) - .RaceDisable(false) - .PreFunc([](WidgetInfo &info) { - if (mGhostshipMenu->GetDisabledMap().at(DISABLE_FOR_ADVANCED_RESOLUTION_OFF).active) { - info.activeDisables.push_back(DISABLE_FOR_ADVANCED_RESOLUTION_OFF); - } - }); + mGhostshipMenu->AddWidget(path, "AspectSep", WIDGET_SEPARATOR).RaceDisable(false).PreFunc([](WidgetInfo& info) { + if (mGhostshipMenu->GetDisabledMap().at(DISABLE_FOR_ADVANCED_RESOLUTION_OFF).active) { + info.activeDisables.push_back(DISABLE_FOR_ADVANCED_RESOLUTION_OFF); + } + }); mGhostshipMenu->AddWidget(path, "Force aspect ratio:", WIDGET_TEXT) .RaceDisable(false) - .PreFunc([](WidgetInfo &info) { + .PreFunc([](WidgetInfo& info) { if (mGhostshipMenu->GetDisabledMap().at(DISABLE_FOR_ADVANCED_RESOLUTION_OFF).active) { info.activeDisables.push_back(DISABLE_FOR_ADVANCED_RESOLUTION_OFF); } }); mGhostshipMenu->AddWidget(path, "(Select \"Off\" to disable.)", WIDGET_TEXT) .RaceDisable(false) - .PreFunc([](WidgetInfo &info) { + .PreFunc([](WidgetInfo& info) { if (mGhostshipMenu->GetDisabledMap().at(DISABLE_FOR_ADVANCED_RESOLUTION_OFF).active) { info.activeDisables.push_back(DISABLE_FOR_ADVANCED_RESOLUTION_OFF); } @@ -575,14 +547,13 @@ void RegisterResolutionWidgets() { mGhostshipMenu->AddWidget(path, "Aspect Ratio", WIDGET_COMBOBOX) .ValuePointer(&item_aspectRatio) .RaceDisable(false) - .PreFunc([](WidgetInfo &info) { + .PreFunc([](WidgetInfo& info) { if (mGhostshipMenu->GetDisabledMap().at(DISABLE_FOR_ADVANCED_RESOLUTION_OFF).active) { info.activeDisables.push_back(DISABLE_FOR_ADVANCED_RESOLUTION_OFF); } }) - .Callback([](WidgetInfo &info) { - if (item_aspectRatio - != default_aspectRatio) { // don't change anything if "Custom" is selected. + .Callback([](WidgetInfo& info) { + if (item_aspectRatio != default_aspectRatio) { // don't change anything if "Custom" is selected. aspectRatioX = aspectRatioPresetsX[item_aspectRatio]; aspectRatioY = aspectRatioPresetsY[item_aspectRatio]; @@ -593,38 +564,37 @@ void RegisterResolutionWidgets() { CVarSetFloat(CVAR_PREFIX_ADVANCED_RESOLUTION ".AspectRatioX", aspectRatioX); CVarSetFloat(CVAR_PREFIX_ADVANCED_RESOLUTION ".AspectRatioY", aspectRatioY); } - CVarSetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".UIComboItem.AspectRatio", - item_aspectRatio); + CVarSetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".UIComboItem.AspectRatio", item_aspectRatio); Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); }) .Options(ComboboxOptions().ComboMap(aspectRatioPresetLabels)); mGhostshipMenu->AddWidget(path, "AspectRatioCustom", WIDGET_CUSTOM) .RaceDisable(false) - .CustomFunction([](WidgetInfo &info) { + .CustomFunction([](WidgetInfo& info) { // Hide aspect ratio input fields if using one of the presets. if (item_aspectRatio == default_aspectRatio && !showHorizontalResField) { // Declare input interaction bools outside of IF statement to prevent Y field from // disappearing. - const bool input_X = UIWidgets::SliderFloat( - "X", &aspectRatioX, - UIWidgets::FloatSliderOptions({ { .disabled = disabled_everything } }) - .Min(0.1f) - .Max(32.0f) - .Step(0.001f) - .Format("%3f") - .Color(THEME_COLOR) - .LabelPosition(UIWidgets::LabelPositions::Near) - .ComponentAlignment(UIWidgets::ComponentAlignments::Right)); - const bool input_Y = UIWidgets::SliderFloat( - "Y", &aspectRatioY, - UIWidgets::FloatSliderOptions({ { .disabled = disabled_everything } }) - .Min(0.1f) - .Max(24.0f) - .Step(0.001f) - .Format("%3f") - .Color(THEME_COLOR) - .LabelPosition(UIWidgets::LabelPositions::Near) - .ComponentAlignment(UIWidgets::ComponentAlignments::Right)); + const bool input_X = + UIWidgets::SliderFloat("X", &aspectRatioX, + UIWidgets::FloatSliderOptions({ { .disabled = disabled_everything } }) + .Min(0.1f) + .Max(32.0f) + .Step(0.001f) + .Format("%3f") + .Color(THEME_COLOR) + .LabelPosition(UIWidgets::LabelPositions::Near) + .ComponentAlignment(UIWidgets::ComponentAlignments::Right)); + const bool input_Y = + UIWidgets::SliderFloat("Y", &aspectRatioY, + UIWidgets::FloatSliderOptions({ { .disabled = disabled_everything } }) + .Min(0.1f) + .Max(24.0f) + .Step(0.001f) + .Format("%3f") + .Color(THEME_COLOR) + .LabelPosition(UIWidgets::LabelPositions::Near) + .ComponentAlignment(UIWidgets::ComponentAlignments::Right)); if (input_X || input_Y) { item_aspectRatio = default_aspectRatio; update[UPDATE_aspectRatioX] = true; @@ -635,7 +605,7 @@ void RegisterResolutionWidgets() { auto gfx_current_dimensions = GetInterpreter().get()->mCurDimensions; ImGui::Dummy({ 0, 2 }); const float resolvedAspectRatio = - (float) gfx_current_dimensions.width / gfx_current_dimensions.height; + (float)gfx_current_dimensions.width / gfx_current_dimensions.height; ImGui::Text("Aspect ratio: %.2f:1", resolvedAspectRatio); } } @@ -647,8 +617,7 @@ void RegisterResolutionWidgets() { void UpdateResolutionVars() { // Clamp and update the cvars that don't use UIWidgets - if (update[UPDATE_aspectRatioX] || update[UPDATE_aspectRatioY] - || update[UPDATE_verticalPixelCount]) { + if (update[UPDATE_aspectRatioX] || update[UPDATE_aspectRatioY] || update[UPDATE_verticalPixelCount]) { if (update[UPDATE_aspectRatioX]) { if (aspectRatioX < 0.0f) { aspectRatioX = 0.0f; @@ -682,50 +651,42 @@ void UpdateResolutionVars() { } // Initialise integer scale bounds. - short max_integerScaleFactor = - default_maxIntegerScaleFactor; // default value, which may or may not get + short max_integerScaleFactor = default_maxIntegerScaleFactor; // default value, which may or may not get // overridden depending on viewport res short integerScale_maximumBounds = 1; // can change when window is resized // This is mostly just for UX purposes, as Fit Automatically logic is part of LUS. auto gfx_current_game_window_viewport = GetInterpreter().get()->mGameWindowViewport; auto gfx_current_dimensions = GetInterpreter().get()->mCurDimensions; - if (((float) gfx_current_game_window_viewport.width / gfx_current_game_window_viewport.height) - > ((float) gfx_current_dimensions.width / gfx_current_dimensions.height)) { + if (((float)gfx_current_game_window_viewport.width / gfx_current_game_window_viewport.height) > + ((float)gfx_current_dimensions.width / gfx_current_dimensions.height)) { // Scale to window height - integerScale_maximumBounds = - gfx_current_game_window_viewport.height / gfx_current_dimensions.height; + integerScale_maximumBounds = gfx_current_game_window_viewport.height / gfx_current_dimensions.height; } else { // Scale to window width - integerScale_maximumBounds = - gfx_current_game_window_viewport.width / gfx_current_dimensions.width; + integerScale_maximumBounds = gfx_current_game_window_viewport.width / gfx_current_dimensions.width; } // Lower-clamping maximum bounds value to 1 is no-longer necessary as that's accounted for in LUS. // Letting it go below 1 in this Editor will even allow for checking if screen bounds are being // exceeded. if (default_maxIntegerScaleFactor < integerScale_maximumBounds) { - max_integerScaleFactor = - integerScale_maximumBounds - + CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.ExceedBoundsBy", 0); + max_integerScaleFactor = integerScale_maximumBounds + + CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".IntegerScale.ExceedBoundsBy", 0); } // Combo List defaults item_aspectRatio = CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".UIComboItem.AspectRatio", 3); - item_pixelCount = - CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".UIComboItem.PixelCount", default_pixelCount); + item_pixelCount = CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".UIComboItem.PixelCount", default_pixelCount); // Stored Values for non-UIWidgets elements - aspectRatioX = CVarGetFloat(CVAR_PREFIX_ADVANCED_RESOLUTION ".AspectRatioX", - aspectRatioPresetsX[item_aspectRatio]); - aspectRatioY = CVarGetFloat(CVAR_PREFIX_ADVANCED_RESOLUTION ".AspectRatioY", - aspectRatioPresetsY[item_aspectRatio]); - verticalPixelCount = CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".VerticalPixelCount", - pixelCountPresets[item_pixelCount]); + aspectRatioX = CVarGetFloat(CVAR_PREFIX_ADVANCED_RESOLUTION ".AspectRatioX", aspectRatioPresetsX[item_aspectRatio]); + aspectRatioY = CVarGetFloat(CVAR_PREFIX_ADVANCED_RESOLUTION ".AspectRatioY", aspectRatioPresetsY[item_aspectRatio]); + verticalPixelCount = + CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".VerticalPixelCount", pixelCountPresets[item_pixelCount]); // Additional settings horizontalPixelCount = (verticalPixelCount / aspectRatioY) * aspectRatioX; // Disabling flags disabled_everything = !CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".Enabled", 0); - disabled_pixelCount = - !CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".VerticalResolutionToggle", 0); + disabled_pixelCount = !CVarGetInteger(CVAR_PREFIX_ADVANCED_RESOLUTION ".VerticalResolutionToggle", 0); } bool IsDroppingFrames() { diff --git a/src/port/ui/SaveEditor.cpp b/src/port/ui/SaveEditor.cpp index e03b3d07..1bd84881 100644 --- a/src/port/ui/SaveEditor.cpp +++ b/src/port/ui/SaveEditor.cpp @@ -18,7 +18,7 @@ extern MarioState* gMarioState; #define DEFINE_COURSES_END() #define DEFINE_BONUS_COURSE(_0, _1, name) name, static char courseNames[][31] = { - #include "levels/course_defines.h" +#include "levels/course_defines.h" }; #undef DEFINE_COURSE #undef DEFINE_COURSES_END @@ -28,12 +28,13 @@ void DrawFlagTableArray32(const FlagTable& flagTable, uint16_t row, uint32_t& fl ImGui::PushID((std::to_string(row) + flagTable.name).c_str()); for (int32_t flagIndex = 0; flagIndex < 32; flagIndex++) { if ((flagIndex % 8) != 0) { - ImGui::SameLine(); + ImGui::SameLine(); } ImGui::PushID(flagIndex); bool hasDescription = !!flagTable.flagDescriptions.contains(flagIndex); uint32_t bitMask = 1 << flagIndex; - ImGui::PushStyleColor(ImGuiCol_FrameBg, hasDescription ? ImVec4(0.16f, 0.29f, 0.48f, 0.54f) : ImVec4(0.16f, 0.29f, 0.48f, 0.24f)); + ImGui::PushStyleColor(ImGuiCol_FrameBg, + hasDescription ? ImVec4(0.16f, 0.29f, 0.48f, 0.54f) : ImVec4(0.16f, 0.29f, 0.48f, 0.24f)); bool flag = (flags & bitMask) != 0; if (ImGui::Checkbox("##check", &flag)) { if (flag) { @@ -63,8 +64,7 @@ void SaveEditorWindow::DrawElement() { ImGui::Text("Mario Flags"); DrawFlagTableArray32(flagTables[1], 0, gMarioState->flags); ImGui::Text("Save File Flags"); - DrawFlagTableArray32(flagTables[0], 0, - gSaveBuffer.files[gCurrSaveFileNum - 1][0].flags); + DrawFlagTableArray32(flagTables[0], 0, gSaveBuffer.files[gCurrSaveFileNum - 1][0].flags); ImGui::EndTabItem(); } @@ -72,19 +72,18 @@ void SaveEditorWindow::DrawElement() { for (int i = 0; i < COURSE_COUNT; i++) { ImGui::Text("%s", courseNames[i]); std::string invisibleLabelStr = "##courseStars" + std::string(courseNames[i]); - const char *invisibleLabel = invisibleLabelStr.c_str(); + const char* invisibleLabel = invisibleLabelStr.c_str(); UIWidgets::DrawFlagArray8( - invisibleLabel, - gSaveBuffer.files[gCurrSaveFileNum - 1][0].courseStars[COURSE_NUM_TO_INDEX(i)]); + invisibleLabel, gSaveBuffer.files[gCurrSaveFileNum - 1][0].courseStars[COURSE_NUM_TO_INDEX(i)]); if (i < COURSE_STAGES_COUNT) { ImGui::SameLine(); std::string invisibleLabelStr2 = "##courseCoins" + std::string(courseNames[i]); - const char *invisibleLabel2 = invisibleLabelStr2.c_str(); + const char* invisibleLabel2 = invisibleLabelStr2.c_str(); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 4); - ImGui::InputScalar(invisibleLabel2, ImGuiDataType_U8, - &gSaveBuffer.files[gCurrSaveFileNum - 1][0] - .courseCoinScores[COURSE_NUM_TO_INDEX(i)], - NULL, NULL, "%u"); + ImGui::InputScalar( + invisibleLabel2, ImGuiDataType_U8, + &gSaveBuffer.files[gCurrSaveFileNum - 1][0].courseCoinScores[COURSE_NUM_TO_INDEX(i)], NULL, + NULL, "%u"); } } ImGui::EndTabItem(); diff --git a/src/port/ui/UIWidgets.cpp b/src/port/ui/UIWidgets.cpp index 106162ad..b8b7e596 100644 --- a/src/port/ui/UIWidgets.cpp +++ b/src/port/ui/UIWidgets.cpp @@ -47,12 +47,11 @@ std::string WrappedText(const char* text, unsigned int charactersPerLine) { return newText; } -std::string WrappedText(const std::string &text, unsigned int charactersPerLine) { +std::string WrappedText(const std::string& text, unsigned int charactersPerLine) { return WrappedText(text.c_str(), charactersPerLine); } -void PaddedSeparator(bool padTop, bool padBottom, float extraVerticalTopPadding, - float extraVerticalBottomPadding) { +void PaddedSeparator(bool padTop, bool padBottom, float extraVerticalTopPadding, float extraVerticalBottomPadding) { if (padTop) { Spacer(extraVerticalTopPadding); } @@ -62,13 +61,13 @@ void PaddedSeparator(bool padTop, bool padBottom, float extraVerticalTopPadding, } } -void Tooltip(const char *text) { +void Tooltip(const char* text) { if (ImGui::IsItemHovered()) { ImGui::SetTooltip("%s", WrappedText(text).c_str()); } } -void PushStyleMenu(const ImVec4 &color) { +void PushStyleMenu(const ImVec4& color) { ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(color.x, color.y, color.z, 0.5f)); ImGui::PushStyleColor(ImGuiCol_HeaderHovered, ImVec4(color.x, color.y, color.z, 1.0f)); ImGui::PushStyleColor(ImGuiCol_PopupBg, ColorValues.at(Colors::DarkGray)); @@ -97,7 +96,7 @@ bool BeginMenu(const char* label, Colors color) { return dirty; } -void PushStyleMenuItem(const ImVec4 &color) { +void PushStyleMenuItem(const ImVec4& color) { ImGui::PushStyleColor(ImGuiCol_HeaderHovered, color); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(20.0f, 15.0f)); } @@ -121,7 +120,7 @@ bool MenuItem(const char* label, const char* shortcut, Colors color) { return dirty; } -void PushStyleButton(const ImVec4 &color, const ImVec2 padding) { +void PushStyleButton(const ImVec4& color, const ImVec2 padding) { ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(color.x, color.y, color.z, 1.0f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(color.x, color.y, color.z, 0.8f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(color.x, color.y, color.z, 0.6f)); @@ -140,7 +139,7 @@ void PopStyleButton() { ImGui::PopStyleColor(4); } -void PushStyleInput(const ImVec4 &color) { +void PushStyleInput(const ImVec4& color) { ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(color.x, color.y, color.z, 1.0f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(color.x, color.y, color.z, 0.8f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(color.x, color.y, color.z, 0.6f)); @@ -162,7 +161,7 @@ void PopStyleInput() { ImGui::PopStyleColor(7); } -void PushStyleHeader(const ImVec4 &color) { +void PushStyleHeader(const ImVec4& color) { ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(color.x, color.y, color.z, 1.0f)); ImGui::PushStyleColor(ImGuiCol_HeaderHovered, ImVec4(color.x, color.y, color.z, 0.8f)); ImGui::PushStyleColor(ImGuiCol_HeaderActive, ImVec4(color.x, color.y, color.z, 0.6f)); @@ -176,24 +175,23 @@ void PopStyleHeader() { ImGui::PopStyleColor(3); } -bool Button(const char* label, const ButtonOptions &options) { +bool Button(const char* label, const ButtonOptions& options) { ImGui::BeginDisabled(options.disabled); PushStyleButton(options.color, options.padding); bool dirty = ImGui::Button(label, options.size); PopStyleButton(); ImGui::EndDisabled(); - if (options.disabled && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) - && !Ship_IsCStringEmpty(options.disabledTooltip)) { + if (options.disabled && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && + !Ship_IsCStringEmpty(options.disabledTooltip)) { ImGui::SetTooltip("%s", WrappedText(options.disabledTooltip).c_str()); - } else if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) - && !Ship_IsCStringEmpty(options.tooltip)) { + } else if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && !Ship_IsCStringEmpty(options.tooltip)) { ImGui::SetTooltip("%s", WrappedText(options.tooltip).c_str()); } return dirty; } bool WindowButton(const char* label, const char* cvarName, std::shared_ptr windowPtr, - const WindowButtonOptions &options) { + const WindowButtonOptions& options) { ImGui::PushStyleVar(ImGuiStyleVar_ButtonTextAlign, ImVec2(0, 0)); std::string buttonText = label; bool dirty = false; @@ -213,7 +211,7 @@ bool WindowButton(const char* label, const char* cvarName, std::shared_ptrDrawList->AddText(g.Font, g.FontSize, pos, ImGui::GetColorU32(ImGuiCol_Text), text, - text_display_end); + window->DrawList->AddText(g.Font, g.FontSize, pos, ImGui::GetColorU32(ImGuiCol_Text), text, text_display_end); if (g.LogEnabled) ImGui::LogRenderedText(&pos, text, text_display_end); } } -bool Checkbox(const char *_label, bool *value, const CheckboxOptions &options) { - ImGuiWindow *window = ImGui::GetCurrentWindow(); +bool Checkbox(const char* _label, bool* value, const CheckboxOptions& options) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); if (window->SkipItems) return false; @@ -306,11 +302,11 @@ bool Checkbox(const char *_label, bool *value, const CheckboxOptions &options) { std::string labelStr = (none ? "##" : ""); labelStr.append(_label); - const char *label = labelStr.c_str(); + const char* label = labelStr.c_str(); PushStyleCheckbox(options.color, options.padding); - ImGuiContext &g = *GImGui; - const ImGuiStyle &style = g.Style; + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = ImGui::CalcTextSize(label, NULL, true); const float square_sz = ImGui::GetFrameHeight(); @@ -322,9 +318,8 @@ bool Checkbox(const char *_label, bool *value, const CheckboxOptions &options) { pos.x += ImGui::GetContentRegionAvail().x - (label_size.x + labelOffsetX); } } - float bbAboveX = lpFar - ? ImGui::GetContentRegionAvail().x - : (label_size.x + (above ? 0 : (style.ItemInnerSpacing.x * 2.0f) + square_sz)); + float bbAboveX = lpFar ? ImGui::GetContentRegionAvail().x + : (label_size.x + (above ? 0 : (style.ItemInnerSpacing.x * 2.0f) + square_sz)); float bbAboveY = label_size.y + (above ? square_sz : 0) + (style.FramePadding.y * 2.0f); const ImRect total_bb(pos, pos + ImVec2(bbAboveX, bbAboveY)); @@ -352,8 +347,7 @@ bool Checkbox(const char *_label, bool *value, const CheckboxOptions &options) { checkPos.x = total_bb.Max.x - square_sz; } else { float labelFarOffset = ImGui::GetContentRegionAvail().x - label_size.x; - float labelOffsetX = - above ? 0 : (lpFar ? labelFarOffset : (style.ItemInnerSpacing.x * 2.0f) + square_sz); + float labelOffsetX = above ? 0 : (lpFar ? labelFarOffset : (style.ItemInnerSpacing.x * 2.0f) + square_sz); labelPos.x += labelOffsetX; } const ImRect check_bb(checkPos, checkPos + ImVec2(square_sz, square_sz)); @@ -370,29 +364,26 @@ bool Checkbox(const char *_label, bool *value, const CheckboxOptions &options) { // This may seem awkwardly designed because the aim is to make ImGuiItemFlags_MixedValue // supported by all widgets (not just checkbox) ImVec2 pad(ImMax(1.0f, IM_TRUNC(square_sz / 3.6f)), ImMax(1.0f, IM_TRUNC(square_sz / 3.6f))); - window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, - style.FrameRounding); + window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding); } else if (*value) { const float pad = ImMax(1.0f, IM_TRUNC(square_sz / 6.0f)); - ImGui::RenderCheckMark(window->DrawList, check_bb.Min + ImVec2(pad, pad), check_col, - square_sz - pad * 2.0f); + ImGui::RenderCheckMark(window->DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad * 2.0f); } RenderText(labelPos, label, ImGui::FindRenderedTextEnd(label), true); PopStyleCheckbox(); ImGui::EndDisabled(); - if (options.disabled && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) - && !Ship_IsCStringEmpty(options.disabledTooltip)) { + if (options.disabled && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && + !Ship_IsCStringEmpty(options.disabledTooltip)) { ImGui::SetTooltip("%s", WrappedText(options.disabledTooltip).c_str()); - } else if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) - && !Ship_IsCStringEmpty(options.tooltip)) { + } else if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && !Ship_IsCStringEmpty(options.tooltip)) { ImGui::SetTooltip("%s", WrappedText(options.tooltip).c_str()); } return pressed; } -bool CVarCheckbox(const char *label, const char *cvarName, const CheckboxOptions &options) { +bool CVarCheckbox(const char* label, const char* cvarName, const CheckboxOptions& options) { bool dirty = false; - bool value = (bool) CVarGetInteger(cvarName, options.defaultValue); + bool value = (bool)CVarGetInteger(cvarName, options.defaultValue); if (Checkbox(label, &value, options)) { CVarSetInteger(cvarName, value); Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); @@ -402,16 +393,15 @@ bool CVarCheckbox(const char *label, const char *cvarName, const CheckboxOptions return dirty; } -bool StateButton(const char *str_id, const char *label, ImVec2 size, ButtonOptions options, - ImGuiButtonFlags flags) { +bool StateButton(const char* str_id, const char* label, ImVec2 size, ButtonOptions options, ImGuiButtonFlags flags) { - ImGuiContext &g = *GImGui; - ImGuiWindow *window = ImGui::GetCurrentWindow(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = ImGui::GetCurrentWindow(); if (window->SkipItems) { return false; } - const ImGuiStyle &style = g.Style; + const ImGuiStyle& style = g.Style; const ImVec2 label_size = ImGui::CalcTextSize(label, NULL, true); const ImGuiID id = window->GetID(str_id); @@ -439,8 +429,8 @@ bool StateButton(const char *str_id, const char *label, ImVec2 size, ButtonOptio // const ImU32 text_col = ImGui::GetColorU32(ImGuiCol_Text); ImGui::RenderNavHighlight(bb, id); ImGui::RenderFrame(bb.Min, bb.Max, bg_col, true, g.Style.FrameRounding); - ImGui::RenderTextClipped(bb.Min + (style.FramePadding * 0.35f), bb.Max - (style.FramePadding / 4), - label, NULL, &label_size, style.ButtonTextAlign, &bb); + ImGui::RenderTextClipped(bb.Min + (style.FramePadding * 0.35f), bb.Max - (style.FramePadding / 4), label, NULL, + &label_size, style.ButtonTextAlign, &bb); PopStyleButton(); /*ImGui::RenderArrow(window->DrawList, bb.Min + @@ -451,17 +441,14 @@ bool StateButton(const char *str_id, const char *label, ImVec2 size, ButtonOptio return pressed; } -float CalcComboWidth(const char *preview_value, ImGuiComboFlags flags) { - ImGuiContext &g = *GImGui; +float CalcComboWidth(const char* preview_value, ImGuiComboFlags flags) { + ImGuiContext& g = *GImGui; - const ImGuiStyle &style = g.Style; - IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) - != (ImGuiComboFlags_NoArrowButton - | ImGuiComboFlags_NoPreview)); // Can't use both flags together + const ImGuiStyle& style = g.Style; + IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) != + (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)); // Can't use both flags together if (flags & ImGuiComboFlags_WidthFitPreview) - IM_ASSERT( - (flags & (ImGuiComboFlags_NoPreview | (ImGuiComboFlags) ImGuiComboFlags_CustomPreview)) - == 0); + IM_ASSERT((flags & (ImGuiComboFlags_NoPreview | (ImGuiComboFlags)ImGuiComboFlags_CustomPreview)) == 0); const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : ImGui::GetFrameHeight(); const float preview_width = ImGui::CalcTextSize(preview_value, NULL, true).x; @@ -469,7 +456,7 @@ float CalcComboWidth(const char *preview_value, ImGuiComboFlags flags) { return w; } -void PushStyleCombobox(const ImVec4 &color) { +void PushStyleCombobox(const ImVec4& color) { ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(color.x, color.y, color.z, 0.8f)); ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImVec4(color.x, color.y, color.z, 0.6f)); ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImVec4(color.x, color.y, color.z, 0.6f)); @@ -494,7 +481,7 @@ void PopStyleCombobox() { ImGui::PopStyleColor(9); } -void PushStyleTabs(const ImVec4 &color) { +void PushStyleTabs(const ImVec4& color) { ImGui::PushStyleColor(ImGuiCol_Tab, ImVec4(color.x, color.y, color.z, 0.8f)); ImGui::PushStyleColor(ImGuiCol_TabHovered, ImVec4(color.x, color.y, color.z, 0.6f)); ImGui::PushStyleColor(ImGuiCol_TabActive, ImVec4(color.x, color.y, color.z, 0.6f)); @@ -517,7 +504,7 @@ void PopStyleTabs() { } void PushStyleSlider(Colors color_) { - const ImVec4 &color = ColorValues.at(color_); + const ImVec4& color = ColorValues.at(color_); ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(color.x, color.y, color.z, 1.0f)); ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImVec4(color.x, color.y, color.z, 1.0f)); ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImVec4(color.x, color.y, color.z, 1.0f)); @@ -535,10 +522,10 @@ void PopStyleSlider() { ImGui::PopStyleColor(6); } -bool SliderInt(const char *label, int32_t *value, const IntSliderOptions &options) { +bool SliderInt(const char* label, int32_t* value, const IntSliderOptions& options) { bool dirty = false; std::string invisibleLabelStr = "##" + std::string(label); - const char *invisibleLabel = invisibleLabelStr.c_str(); + const char* invisibleLabel = invisibleLabelStr.c_str(); ImGui::PushID(label); ImGui::BeginGroup(); ImGui::BeginDisabled(options.disabled); @@ -555,8 +542,7 @@ bool SliderInt(const char *label, int32_t *value, const IntSliderOptions &option ImGui::SameLine(ImGui::GetContentRegionAvail().x - width); } else if (options.labelPosition == LabelPositions::Near) { ImGui::SameLine(); - } else if (options.labelPosition == LabelPositions::Far - || options.labelPosition == LabelPositions::None) { + } else if (options.labelPosition == LabelPositions::Far || options.labelPosition == LabelPositions::None) { ImGui::SameLine(ImGui::GetContentRegionAvail().x - width); } } else if (options.alignment == ComponentAlignments::Left) { @@ -565,8 +551,7 @@ bool SliderInt(const char *label, int32_t *value, const IntSliderOptions &option } } if (options.showButtons) { - if (Button("-", ButtonOptions{ .color = options.color }.Size(Sizes::Inline)) - && *value > options.min) { + if (Button("-", ButtonOptions{ .color = options.color }.Size(Sizes::Inline)) && *value > options.min) { *value -= options.step; if (options.clamp) { if (*value < options.min) { @@ -576,13 +561,12 @@ bool SliderInt(const char *label, int32_t *value, const IntSliderOptions &option dirty = true; } ImGui::SameLine(0, 3.0f); - ImGui::SetNextItemWidth( - width - (ImGui::CalcTextSize("+").x + ImGui::GetStyle().FramePadding.x * 2 + 3) * 2); + ImGui::SetNextItemWidth(width - (ImGui::CalcTextSize("+").x + ImGui::GetStyle().FramePadding.x * 2 + 3) * 2); } else { ImGui::SetNextItemWidth(width); } - if (ImGui::SliderScalar(invisibleLabel, ImGuiDataType_S32, value, &options.min, &options.max, - options.format, options.flags)) { + if (ImGui::SliderScalar(invisibleLabel, ImGuiDataType_S32, value, &options.min, &options.max, options.format, + options.flags)) { if (options.clamp) { if (*value < options.min) { *value = options.min; @@ -595,8 +579,7 @@ bool SliderInt(const char *label, int32_t *value, const IntSliderOptions &option if (options.showButtons) { ImGui::SameLine(0, 3.0f); ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x); - if (Button("+", ButtonOptions{ .color = options.color }.Size(Sizes::Inline)) - && *value < options.max) { + if (Button("+", ButtonOptions{ .color = options.color }.Size(Sizes::Inline)) && *value < options.max) { *value += options.step; if (options.clamp) { if (*value > options.max) @@ -611,28 +594,26 @@ bool SliderInt(const char *label, int32_t *value, const IntSliderOptions &option if (options.labelPosition == LabelPositions::Near) { ImGui::SameLine(); ImGui::Text(label, *value); - } else if (options.labelPosition == LabelPositions::Far - || options.labelPosition == LabelPositions::None) { - ImGui::SameLine(ImGui::GetContentRegionAvail().x - ImGui::CalcTextSize(label).x - + ImGui::GetStyle().ItemSpacing.x); + } else if (options.labelPosition == LabelPositions::Far || options.labelPosition == LabelPositions::None) { + ImGui::SameLine(ImGui::GetContentRegionAvail().x - ImGui::CalcTextSize(label).x + + ImGui::GetStyle().ItemSpacing.x); ImGui::Text(label, *value); } } PopStyleSlider(); ImGui::EndDisabled(); ImGui::EndGroup(); - if (options.disabled && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) - && !Ship_IsCStringEmpty(options.disabledTooltip)) { + if (options.disabled && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && + !Ship_IsCStringEmpty(options.disabledTooltip)) { ImGui::SetTooltip("%s", WrappedText(options.disabledTooltip).c_str()); - } else if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) - && !Ship_IsCStringEmpty(options.tooltip)) { + } else if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && !Ship_IsCStringEmpty(options.tooltip)) { ImGui::SetTooltip("%s", WrappedText(options.tooltip).c_str()); } ImGui::PopID(); return dirty; } -bool CVarSliderInt(const char *label, const char *cvarName, const IntSliderOptions &options) { +bool CVarSliderInt(const char* label, const char* cvarName, const IntSliderOptions& options) { bool dirty = false; int32_t value = CVarGetInteger(cvarName, options.defaultValue); if (SliderInt(label, &value, options)) { @@ -642,562 +623,544 @@ bool CVarSliderInt(const char *label, const char *cvarName, const IntSliderOptio dirty = true; } -void ClampFloat(float *value, float min, float max, float step) { - int factor = 1; - if (step < 1.0f) { - factor *= 10; + void ClampFloat(float* value, float min, float max, float step) { + int factor = 1; + if (step < 1.0f) { + factor *= 10; + } + if (step < 0.1f) { + factor *= 10; + } + if (step < 0.01f) { + factor *= 10; + } + if (step < 0.001f) { + factor *= 10; + } + if (step < 0.0001f) { + factor *= 10; + } + if (step < 0.00001f) { + factor *= 10; + } + if (*value < min) { + *value = min; + } else if (*value > max) { + *value = max; + } else { + int trunc = (int)std::round(*value * factor); + *value = (float)trunc / factor; + } } - if (step < 0.1f) { - factor *= 10; - } - if (step < 0.01f) { - factor *= 10; - } - if (step < 0.001f) { - factor *= 10; - } - if (step < 0.0001f) { - factor *= 10; - } - if (step < 0.00001f) { - factor *= 10; - } - if (*value < min) { - *value = min; - } else if (*value > max) { - *value = max; - } else { - int trunc = (int) std::round(*value * factor); - *value = (float) trunc / factor; - } -} -bool SliderFloat(const char *label, float *value, const FloatSliderOptions &options) { - bool dirty = false; - std::string invisibleLabelStr = "##" + std::string(label); - const char *invisibleLabel = invisibleLabelStr.c_str(); - float valueToDisplay = options.isPercentage ? *value * 100.0f : *value; - float maxToDisplay = options.isPercentage ? options.max * 100.0f : options.max; - float minToDisplay = options.isPercentage ? options.min * 100.0f : options.min; - ImGui::PushID(label); - ImGui::BeginGroup(); - ImGui::BeginDisabled(options.disabled); - PushStyleSlider(options.color); - float labelSpacing = ImGui::CalcTextSize(label).x + ImGui::GetStyle().ItemSpacing.x; - float width = (options.size == ImVec2(0, 0)) ? ImGui::GetContentRegionAvail().x : options.size.x; - if (options.labelPosition == LabelPositions::Near || options.labelPosition == LabelPositions::Far) { - width = width - (ImGui::CalcTextSize(label).x + ImGui::GetStyle().FramePadding.x); - } - ImGui::AlignTextToFramePadding(); - if (options.alignment == ComponentAlignments::Right) { - ImGui::Text(label, *value); - if (options.labelPosition == LabelPositions::Above) { - ImGui::NewLine(); - ImGui::SameLine(ImGui::GetContentRegionAvail().x - width); - } else if (options.labelPosition == LabelPositions::Near) { - width -= labelSpacing; - ImGui::SameLine(); - } else if (options.labelPosition == LabelPositions::Far - || options.labelPosition == LabelPositions::None) { - width -= labelSpacing; - ImGui::SameLine(ImGui::GetContentRegionAvail().x - width); + bool SliderFloat(const char* label, float* value, const FloatSliderOptions& options) { + bool dirty = false; + std::string invisibleLabelStr = "##" + std::string(label); + const char* invisibleLabel = invisibleLabelStr.c_str(); + float valueToDisplay = options.isPercentage ? *value * 100.0f : *value; + float maxToDisplay = options.isPercentage ? options.max * 100.0f : options.max; + float minToDisplay = options.isPercentage ? options.min * 100.0f : options.min; + ImGui::PushID(label); + ImGui::BeginGroup(); + ImGui::BeginDisabled(options.disabled); + PushStyleSlider(options.color); + float labelSpacing = ImGui::CalcTextSize(label).x + ImGui::GetStyle().ItemSpacing.x; + float width = (options.size == ImVec2(0, 0)) ? ImGui::GetContentRegionAvail().x : options.size.x; + if (options.labelPosition == LabelPositions::Near || options.labelPosition == LabelPositions::Far) { + width = width - (ImGui::CalcTextSize(label).x + ImGui::GetStyle().FramePadding.x); } - } else if (options.alignment == ComponentAlignments::Left) { - if (options.labelPosition == LabelPositions::Above) { + ImGui::AlignTextToFramePadding(); + if (options.alignment == ComponentAlignments::Right) { ImGui::Text(label, *value); + if (options.labelPosition == LabelPositions::Above) { + ImGui::NewLine(); + ImGui::SameLine(ImGui::GetContentRegionAvail().x - width); + } else if (options.labelPosition == LabelPositions::Near) { + width -= labelSpacing; + ImGui::SameLine(); + } else if (options.labelPosition == LabelPositions::Far || options.labelPosition == LabelPositions::None) { + width -= labelSpacing; + ImGui::SameLine(ImGui::GetContentRegionAvail().x - width); + } + } else if (options.alignment == ComponentAlignments::Left) { + if (options.labelPosition == LabelPositions::Above) { + ImGui::Text(label, *value); + } } - } - if (options.showButtons) { - if (Button("-", ButtonOptions{ .color = options.color }.Size(Sizes::Inline)) - && *value > options.min) { - *value -= options.step; + if (options.showButtons) { + if (Button("-", ButtonOptions{ .color = options.color }.Size(Sizes::Inline)) && *value > options.min) { + *value -= options.step; + if (options.clamp) { + ClampFloat(value, options.min, options.max, options.step); + } + dirty = true; + } + ImGui::SameLine(0, 3.0f); + ImGui::SetNextItemWidth(width - + (ImGui::CalcTextSize("+").x + ImGui::GetStyle().FramePadding.x * 2 + 3) * 2); + } else { + ImGui::SetNextItemWidth(width); + } + if (ImGui::SliderScalar(invisibleLabel, ImGuiDataType_Float, &valueToDisplay, &minToDisplay, &maxToDisplay, + options.format, options.flags)) { + *value = options.isPercentage ? valueToDisplay / 100.0f : valueToDisplay; if (options.clamp) { ClampFloat(value, options.min, options.max, options.step); } dirty = true; } - ImGui::SameLine(0, 3.0f); - ImGui::SetNextItemWidth( - width - (ImGui::CalcTextSize("+").x + ImGui::GetStyle().FramePadding.x * 2 + 3) * 2); - } else { - ImGui::SetNextItemWidth(width); - } - if (ImGui::SliderScalar(invisibleLabel, ImGuiDataType_Float, &valueToDisplay, &minToDisplay, - &maxToDisplay, options.format, options.flags)) { - *value = options.isPercentage ? valueToDisplay / 100.0f : valueToDisplay; - if (options.clamp) { - ClampFloat(value, options.min, options.max, options.step); - } - dirty = true; - } - if (options.showButtons) { - ImGui::SameLine(0, 3.0f); - ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x); - if (Button("+", ButtonOptions{ .color = options.color }.Size(Sizes::Inline)) - && *value < options.max) { - *value += options.step; - if (options.clamp) { - ClampFloat(value, options.min, options.max, options.step); + if (options.showButtons) { + ImGui::SameLine(0, 3.0f); + ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x); + if (Button("+", ButtonOptions{ .color = options.color }.Size(Sizes::Inline)) && *value < options.max) { + *value += options.step; + if (options.clamp) { + ClampFloat(value, options.min, options.max, options.step); + } + dirty = true; } + return dirty; + } + + if (options.alignment == ComponentAlignments::Left) { + if (options.labelPosition == LabelPositions::Near) { + ImGui::SameLine(); + ImGui::Text(label, *value); + } else if (options.labelPosition == LabelPositions::Far || options.labelPosition == LabelPositions::None) { + ImGui::SameLine(ImGui::GetContentRegionAvail().x - labelSpacing); + ImGui::Text(label, *value); + } + } + PopStyleSlider(); + ImGui::EndDisabled(); + ImGui::EndGroup(); + if (options.disabled && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && + !Ship_IsCStringEmpty(options.disabledTooltip)) { + ImGui::SetTooltip("%s", WrappedText(options.disabledTooltip).c_str()); + } else if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && !Ship_IsCStringEmpty(options.tooltip)) { + ImGui::SetTooltip("%s", WrappedText(options.tooltip).c_str()); + } + ImGui::PopID(); + return dirty; + } + + bool CVarSliderFloat(const char* label, const char* cvarName, const FloatSliderOptions& options) { + bool dirty = false; + float value = CVarGetFloat(cvarName, options.defaultValue); + if (SliderFloat(label, &value, options)) { + CVarSetFloat(cvarName, value); + Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); + ShipInit::Init(cvarName); + dirty = true; + } + } + + int InputTextResizeCallback(ImGuiInputTextCallbackData * data) { + std::string* value = (std::string*)data->UserData; + if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) { + value->resize(data->BufTextLen); + data->Buf = (char*)value->c_str(); + } + return 0; + } + + bool InputString(const char* label, std::string* value, const InputOptions& options) { + bool dirty = false; + ImGui::PushID(label); + ImGui::BeginGroup(); + ImGui::BeginDisabled(options.disabled); + PushStyleInput(options.color); + if (options.hasError) { + ImGui::PushStyleColor(ImGuiCol_Border, ColorValues.at(Colors::Red)); + } + float width = (options.size == ImVec2(0, 0)) ? ImGui::GetContentRegionAvail().x : options.size.x; + ImVec2 labelSize = ImGui::CalcTextSize(label, NULL, true); + if (labelSize.x != 0) { + if (options.alignment == ComponentAlignments::Left) { + if (options.labelPosition == LabelPositions::Above) { + ImGui::Text(label, *value->c_str()); + } + } else if (options.alignment == ComponentAlignments::Right) { + if (options.labelPosition == LabelPositions::Above) { + ImGui::NewLine(); + ImGui::SameLine(width - ImGui::CalcTextSize(label).x); + ImGui::Text(label, *value->c_str()); + } + } + } + ImGui::SetNextItemWidth(width); + ImGuiInputTextFlags flags = ImGuiInputTextFlags_CallbackResize; + if (options.secret) { + flags |= ImGuiInputTextFlags_Password; + } + flags |= options.addedFlags; + if (ImGui::InputText(label, (char*)value->c_str(), value->capacity() + 1, flags, InputTextResizeCallback, + value)) { + dirty = true; + } + if (value->empty() && !options.placeholder.empty()) { + ImGui::SameLine(17.0f); + ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 0.4f), "%s", options.placeholder.c_str()); + } + if (options.hasError) { + ImGui::PopStyleColor(); + } + PopStyleInput(); + ImGui::EndDisabled(); + ImGui::EndGroup(); + if (options.hasError && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && + !Ship_IsCStringEmpty(options.errorText)) { + ImGui::SetTooltip("%s", WrappedText(options.errorText).c_str()); + } else if (options.disabled && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && + !Ship_IsCStringEmpty(options.disabledTooltip)) { + ImGui::SetTooltip("%s", WrappedText(options.disabledTooltip).c_str()); + } else if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && !Ship_IsCStringEmpty(options.tooltip)) { + ImGui::SetTooltip("%s", WrappedText(options.tooltip).c_str()); + } + ImGui::PopID(); + return dirty; + } + + bool CVarInputString(const char* label, const char* cvarName, const InputOptions& options) { + bool dirty = false; + std::string value = CVarGetString(cvarName, options.defaultValue.c_str()); + if (InputString(label, &value, options)) { + CVarSetString(cvarName, value.c_str()); + Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); + ShipInit::Init(cvarName); dirty = true; } return dirty; } - if (options.alignment == ComponentAlignments::Left) { - if (options.labelPosition == LabelPositions::Near) { - ImGui::SameLine(); - ImGui::Text(label, *value); - } else if (options.labelPosition == LabelPositions::Far - || options.labelPosition == LabelPositions::None) { - ImGui::SameLine(ImGui::GetContentRegionAvail().x - labelSpacing); - ImGui::Text(label, *value); - } - } - PopStyleSlider(); - ImGui::EndDisabled(); - ImGui::EndGroup(); - if (options.disabled && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) - && !Ship_IsCStringEmpty(options.disabledTooltip)) { - ImGui::SetTooltip("%s", WrappedText(options.disabledTooltip).c_str()); - } else if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) - && !Ship_IsCStringEmpty(options.tooltip)) { - ImGui::SetTooltip("%s", WrappedText(options.tooltip).c_str()); - } - ImGui::PopID(); - return dirty; -} - -bool CVarSliderFloat(const char *label, const char *cvarName, const FloatSliderOptions &options) { - bool dirty = false; - float value = CVarGetFloat(cvarName, options.defaultValue); - if (SliderFloat(label, &value, options)) { - CVarSetFloat(cvarName, value); - Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); - ShipInit::Init(cvarName); - dirty = true; - } -} - -int InputTextResizeCallback(ImGuiInputTextCallbackData *data) { - std::string *value = (std::string *) data->UserData; - if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) { - value->resize(data->BufTextLen); - data->Buf = (char *) value->c_str(); - } - return 0; -} - -bool InputString(const char *label, std::string *value, const InputOptions &options) { - bool dirty = false; - ImGui::PushID(label); - ImGui::BeginGroup(); - ImGui::BeginDisabled(options.disabled); - PushStyleInput(options.color); - if (options.hasError) { - ImGui::PushStyleColor(ImGuiCol_Border, ColorValues.at(Colors::Red)); - } - float width = (options.size == ImVec2(0, 0)) ? ImGui::GetContentRegionAvail().x : options.size.x; - ImVec2 labelSize = ImGui::CalcTextSize(label, NULL, true); - if (labelSize.x != 0) { + bool InputInt(const char* label, int32_t* value, const InputOptions& options) { + bool dirty = false; + ImGui::PushID(label); + ImGui::BeginGroup(); + ImGui::BeginDisabled(options.disabled); + PushStyleInput(options.color); + float width = (options.size == ImVec2(0, 0)) ? ImGui::GetContentRegionAvail().x : options.size.x; if (options.alignment == ComponentAlignments::Left) { if (options.labelPosition == LabelPositions::Above) { - ImGui::Text(label, *value->c_str()); + ImGui::Text(label, *value); } } else if (options.alignment == ComponentAlignments::Right) { if (options.labelPosition == LabelPositions::Above) { ImGui::NewLine(); ImGui::SameLine(width - ImGui::CalcTextSize(label).x); - ImGui::Text(label, *value->c_str()); + ImGui::Text(label, *value); } } - } - ImGui::SetNextItemWidth(width); - ImGuiInputTextFlags flags = ImGuiInputTextFlags_CallbackResize; - if (options.secret) { - flags |= ImGuiInputTextFlags_Password; - } - flags |= options.addedFlags; - if (ImGui::InputText(label, (char *) value->c_str(), value->capacity() + 1, flags, - InputTextResizeCallback, value)) { - dirty = true; - } - if (value->empty() && !options.placeholder.empty()) { - ImGui::SameLine(17.0f); - ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 0.4f), "%s", options.placeholder.c_str()); - } - if (options.hasError) { - ImGui::PopStyleColor(); - } - PopStyleInput(); - ImGui::EndDisabled(); - ImGui::EndGroup(); - if (options.hasError && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) - && !Ship_IsCStringEmpty(options.errorText)) { - ImGui::SetTooltip("%s", WrappedText(options.errorText).c_str()); - } else if (options.disabled && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) - && !Ship_IsCStringEmpty(options.disabledTooltip)) { - ImGui::SetTooltip("%s", WrappedText(options.disabledTooltip).c_str()); - } else if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) - && !Ship_IsCStringEmpty(options.tooltip)) { - ImGui::SetTooltip("%s", WrappedText(options.tooltip).c_str()); - } - ImGui::PopID(); - return dirty; -} - -bool CVarInputString(const char *label, const char *cvarName, const InputOptions &options) { - bool dirty = false; - std::string value = CVarGetString(cvarName, options.defaultValue.c_str()); - if (InputString(label, &value, options)) { - CVarSetString(cvarName, value.c_str()); - Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); - ShipInit::Init(cvarName); - dirty = true; - } - return dirty; -} - -bool InputInt(const char *label, int32_t *value, const InputOptions &options) { - bool dirty = false; - ImGui::PushID(label); - ImGui::BeginGroup(); - ImGui::BeginDisabled(options.disabled); - PushStyleInput(options.color); - float width = (options.size == ImVec2(0, 0)) ? ImGui::GetContentRegionAvail().x : options.size.x; - if (options.alignment == ComponentAlignments::Left) { - if (options.labelPosition == LabelPositions::Above) { - ImGui::Text(label, *value); + ImGui::SetNextItemWidth(width); + if (ImGui::InputScalar(label, ImGuiDataType_S32, value, nullptr, nullptr, nullptr, options.addedFlags)) { + dirty = true; } - } else if (options.alignment == ComponentAlignments::Right) { - if (options.labelPosition == LabelPositions::Above) { - ImGui::NewLine(); - ImGui::SameLine(width - ImGui::CalcTextSize(label).x); - ImGui::Text(label, *value); + if ((ImGui::GetItemStatusFlags() & ImGuiItemStatusFlags_Edited) && !options.placeholder.empty()) { + ImGui::SameLine(17.0f); + ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 0.4f), "%s", options.placeholder.c_str()); } + PopStyleInput(); + ImGui::EndDisabled(); + ImGui::EndGroup(); + if (options.disabled && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && + !Ship_IsCStringEmpty(options.disabledTooltip)) { + ImGui::SetTooltip("%s", WrappedText(options.disabledTooltip).c_str()); + } else if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && !Ship_IsCStringEmpty(options.tooltip)) { + ImGui::SetTooltip("%s", WrappedText(options.tooltip).c_str()); + } + ImGui::PopID(); + return dirty; } - ImGui::SetNextItemWidth(width); - if (ImGui::InputScalar(label, ImGuiDataType_S32, value, nullptr, nullptr, nullptr, - options.addedFlags)) { - dirty = true; - } - if ((ImGui::GetItemStatusFlags() & ImGuiItemStatusFlags_Edited) && !options.placeholder.empty()) { - ImGui::SameLine(17.0f); - ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 0.4f), "%s", options.placeholder.c_str()); - } - PopStyleInput(); - ImGui::EndDisabled(); - ImGui::EndGroup(); - if (options.disabled && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) - && !Ship_IsCStringEmpty(options.disabledTooltip)) { - ImGui::SetTooltip("%s", WrappedText(options.disabledTooltip).c_str()); - } else if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) - && !Ship_IsCStringEmpty(options.tooltip)) { - ImGui::SetTooltip("%s", WrappedText(options.tooltip).c_str()); - } - ImGui::PopID(); - return dirty; -} -bool CVarInputInt(const char *label, const char *cvarName, const InputOptions &options) { - bool dirty = false; - int32_t defaultValue = std::stoi(options.defaultValue); - int32_t value = CVarGetInteger(cvarName, defaultValue); - if (InputInt(label, &value, options)) { - CVarSetInteger(cvarName, value); - Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); - ShipInit::Init(cvarName); - dirty = true; - } - return dirty; -} - -bool CVarColorPicker(const char *label, const char *cvarName, Color_RGBA8 defaultColor, bool hasAlpha, - uint8_t modifiers, UIWidgets::Colors themeColor) { - std::string valueCVar = std::string(cvarName) + ".Value"; - std::string rainbowCVar = std::string(cvarName) + ".Rainbow"; - std::string lockedCVar = std::string(cvarName) + ".Locked"; - Color_RGBA8 color = CVarGetColor(valueCVar.c_str(), defaultColor); - ImVec4 colorVec = ImVec4(color.r / 255.0f, color.g / 255.0f, color.b / 255.0f, color.a / 255.0f); - bool changed = false; - bool showReset = modifiers & ColorPickerResetButton; - bool showRandom = modifiers & ColorPickerRandomButton; - bool showRainbow = modifiers & ColorPickerRainbowCheck; - bool showLock = modifiers & ColorPickerLockCheck; - bool locked = CVarGetInteger(lockedCVar.c_str(), 0); - ImGuiColorEditFlags flags = ImGuiColorEditFlags_NoInputs; - ImGui::BeginDisabled(locked); - PushStyleCombobox(UIWidgets::Colors::DarkGray); - if (hasAlpha) { - changed = - ImGui::ColorEdit4(label, (float *) &colorVec, - flags | ImGuiColorEditFlags_AlphaBar | ImGuiColorEditFlags_AlphaPreview); - } else { - changed = ImGui::ColorEdit3(label, (float *) &colorVec, flags | ImGuiColorEditFlags_NoAlpha); - } - PopStyleCombobox(); - ImGui::AlignTextToFramePadding(); - if (showReset) { - ImGui::SameLine(); - std::string uniqueTag = "Reset##" + std::string(label); - if (UIWidgets::Button( - uniqueTag.c_str(), - UIWidgets::ButtonOptions({ { .tooltip = "Resets this color to its default value" } }) - .Color(themeColor) - .Size(UIWidgets::Sizes::Inline))) { - // TODO: Remove for next minor or major version, temporary fix for already migrated configs - // to 3 for 9.0.0 - CVarClear((std::string(cvarName) + ".R").c_str()); - CVarClear((std::string(cvarName) + ".G").c_str()); - CVarClear((std::string(cvarName) + ".B").c_str()); - CVarClear((std::string(cvarName) + ".A").c_str()); - CVarClear((std::string(cvarName) + ".Type").c_str()); - CVarClearBlock(valueCVar.c_str()); + bool CVarInputInt(const char* label, const char* cvarName, const InputOptions& options) { + bool dirty = false; + int32_t defaultValue = std::stoi(options.defaultValue); + int32_t value = CVarGetInteger(cvarName, defaultValue); + if (InputInt(label, &value, options)) { + CVarSetInteger(cvarName, value); Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); + ShipInit::Init(cvarName); + dirty = true; } + return dirty; } - if (showRandom) { - ImGui::SameLine(); - std::string uniqueTag = "Random##" + std::string(label); - if (UIWidgets::Button( - uniqueTag.c_str(), - UIWidgets::ButtonOptions({ { .tooltip = "Generates a random color value to use" } }) - .Color(themeColor) - .Size(UIWidgets::Sizes::Inline))) { - colorVec = GetRandomValue(); - color.r = fmin(fmax(colorVec.x * 255, 0), 255); - color.g = fmin(fmax(colorVec.y * 255, 0), 255); - color.b = fmin(fmax(colorVec.z * 255, 0), 255); + + bool CVarColorPicker(const char* label, const char* cvarName, Color_RGBA8 defaultColor, bool hasAlpha, + uint8_t modifiers, UIWidgets::Colors themeColor) { + std::string valueCVar = std::string(cvarName) + ".Value"; + std::string rainbowCVar = std::string(cvarName) + ".Rainbow"; + std::string lockedCVar = std::string(cvarName) + ".Locked"; + Color_RGBA8 color = CVarGetColor(valueCVar.c_str(), defaultColor); + ImVec4 colorVec = ImVec4(color.r / 255.0f, color.g / 255.0f, color.b / 255.0f, color.a / 255.0f); + bool changed = false; + bool showReset = modifiers & ColorPickerResetButton; + bool showRandom = modifiers & ColorPickerRandomButton; + bool showRainbow = modifiers & ColorPickerRainbowCheck; + bool showLock = modifiers & ColorPickerLockCheck; + bool locked = CVarGetInteger(lockedCVar.c_str(), 0); + ImGuiColorEditFlags flags = ImGuiColorEditFlags_NoInputs; + ImGui::BeginDisabled(locked); + PushStyleCombobox(UIWidgets::Colors::DarkGray); + if (hasAlpha) { + changed = ImGui::ColorEdit4(label, (float*)&colorVec, + flags | ImGuiColorEditFlags_AlphaBar | ImGuiColorEditFlags_AlphaPreview); + } else { + changed = ImGui::ColorEdit3(label, (float*)&colorVec, flags | ImGuiColorEditFlags_NoAlpha); + } + PopStyleCombobox(); + ImGui::AlignTextToFramePadding(); + if (showReset) { + ImGui::SameLine(); + std::string uniqueTag = "Reset##" + std::string(label); + if (UIWidgets::Button(uniqueTag.c_str(), + UIWidgets::ButtonOptions({ { .tooltip = "Resets this color to its default value" } }) + .Color(themeColor) + .Size(UIWidgets::Sizes::Inline))) { + // TODO: Remove for next minor or major version, temporary fix for already migrated configs + // to 3 for 9.0.0 + CVarClear((std::string(cvarName) + ".R").c_str()); + CVarClear((std::string(cvarName) + ".G").c_str()); + CVarClear((std::string(cvarName) + ".B").c_str()); + CVarClear((std::string(cvarName) + ".A").c_str()); + CVarClear((std::string(cvarName) + ".Type").c_str()); + CVarClearBlock(valueCVar.c_str()); + Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); + } + } + if (showRandom) { + ImGui::SameLine(); + std::string uniqueTag = "Random##" + std::string(label); + if (UIWidgets::Button(uniqueTag.c_str(), + UIWidgets::ButtonOptions({ { .tooltip = "Generates a random color value to use" } }) + .Color(themeColor) + .Size(UIWidgets::Sizes::Inline))) { + colorVec = GetRandomValue(); + color.r = fmin(fmax(colorVec.x * 255, 0), 255); + color.g = fmin(fmax(colorVec.y * 255, 0), 255); + color.b = fmin(fmax(colorVec.z * 255, 0), 255); + CVarSetColor(valueCVar.c_str(), color); + CVarSetInteger(rainbowCVar.c_str(), 0); // On click disable rainbow mode. + ShipInit::Init(rainbowCVar.c_str()); + Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); + } + } + if (showRainbow) { + ImGui::SameLine(); + std::string uniqueTag = "Rainbow##" + std::string(cvarName) + "Rainbow"; + + UIWidgets::CVarCheckbox( + uniqueTag.c_str(), rainbowCVar.c_str(), + UIWidgets::CheckboxOptions( + { { .tooltip = "Cycles through colors on a timer\nOverwrites previously chosen color" } }) + .Color(themeColor)); + } + ImGui::EndDisabled(); + if (showLock) { + ImGui::SameLine(); + std::string uniqueTag = "Lock##" + std::string(cvarName) + "Locked"; + + UIWidgets::CVarCheckbox( + uniqueTag.c_str(), lockedCVar.c_str(), + UIWidgets::CheckboxOptions({ { .tooltip = "Prevents this color from being changed" } }) + .Color(themeColor)); + } + if (changed) { + color.r = (uint8_t)(colorVec.x * 255.0f); + color.g = (uint8_t)(colorVec.y * 255.0f); + color.b = (uint8_t)(colorVec.z * 255.0f); + color.a = (uint8_t)(colorVec.w * 255.0f); CVarSetColor(valueCVar.c_str(), color); - CVarSetInteger(rainbowCVar.c_str(), 0); // On click disable rainbow mode. - ShipInit::Init(rainbowCVar.c_str()); Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); + ShipInit::Init(valueCVar.c_str()); + changed = true; } + + return changed; } - if (showRainbow) { + + bool RadioButton(const char* label, bool active, const RadioButtonsOptions& options) { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = ImGui::CalcTextSize(label, NULL, true); + + const float square_sz = ImGui::GetFrameHeight(); + const ImVec2 pos = window->DC.CursorPos; + const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz)); + const ImRect total_bb( + pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), + label_size.y + style.FramePadding.y * 2.0f)); + ImGui::ItemSize(total_bb, style.FramePadding.y); + if (!ImGui::ItemAdd(total_bb, id)) + return false; + + ImVec2 center = check_bb.GetCenter(); + center.x = IM_ROUND(center.x); + center.y = IM_ROUND(center.y); + const float radius = (square_sz - 1.0f) * 0.5f; + + bool hovered, held; + bool pressed = ImGui::ButtonBehavior(total_bb, id, &hovered, &held); + if (pressed) + ImGui::MarkItemEdited(id); + + ImGui::RenderNavCursor(total_bb, id); + const int num_segment = window->DrawList->_CalcCircleAutoSegmentCount(radius); + window->DrawList->AddCircleFilled(center, radius, + ImGui::GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive + : hovered ? ImGuiCol_FrameBgHovered + : ImGuiCol_FrameBg), + num_segment); + if (active) { + const float pad = ImMax(1.0f, IM_TRUNC(square_sz / 6.0f)); + window->DrawList->AddCircleFilled(center, radius - pad, ImGui::GetColorU32(ImGuiCol_CheckMark)); + } + + if (style.FrameBorderSize > 0.0f) { + window->DrawList->AddCircle(center + ImVec2(1, 1), radius, ImGui::GetColorU32(ImGuiCol_BorderShadow), + num_segment, style.FrameBorderSize); + window->DrawList->AddCircle(center, radius, ImGui::GetColorU32(ImGuiCol_Border), num_segment, + style.FrameBorderSize); + } + + ImVec2 label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y); + if (g.LogEnabled) + ImGui::LogRenderedText(&label_pos, active ? "(x)" : "( )"); + if (label_size.x > 0.0f) + RenderText(label_pos, label, ImGui::FindRenderedTextEnd(label), true); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); + return pressed; + } + + bool CVarRadioButton(const char* text, const char* cvarName, int32_t id, const RadioButtonsOptions& options) { + std::string make_invisible = "##" + std::string(text) + std::string(cvarName); + + bool ret = false; + int val = CVarGetInteger(cvarName, options.defaultIndex); + PushStyleCheckbox(options.color); + if (ImGui::RadioButton(make_invisible.c_str(), id == val)) { + CVarSetInteger(cvarName, id); + Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); + ret = true; + } ImGui::SameLine(); - std::string uniqueTag = "Rainbow##" + std::string(cvarName) + "Rainbow"; - - UIWidgets::CVarCheckbox( - uniqueTag.c_str(), rainbowCVar.c_str(), - UIWidgets::CheckboxOptions( - { { .tooltip = - "Cycles through colors on a timer\nOverwrites previously chosen color" } }) - .Color(themeColor)); - } - ImGui::EndDisabled(); - if (showLock) { - ImGui::SameLine(); - std::string uniqueTag = "Lock##" + std::string(cvarName) + "Locked"; - - UIWidgets::CVarCheckbox( - uniqueTag.c_str(), lockedCVar.c_str(), - UIWidgets::CheckboxOptions({ { .tooltip = "Prevents this color from being changed" } }) - .Color(themeColor)); - } - if (changed) { - color.r = (uint8_t) (colorVec.x * 255.0f); - color.g = (uint8_t) (colorVec.y * 255.0f); - color.b = (uint8_t) (colorVec.z * 255.0f); - color.a = (uint8_t) (colorVec.w * 255.0f); - CVarSetColor(valueCVar.c_str(), color); - Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); - ShipInit::Init(valueCVar.c_str()); - changed = true; - } - - return changed; -} - -bool RadioButton(const char *label, bool active, const RadioButtonsOptions &options) { - ImGuiWindow *window = ImGui::GetCurrentWindow(); - if (window->SkipItems) - return false; - - ImGuiContext &g = *GImGui; - const ImGuiStyle &style = g.Style; - const ImGuiID id = window->GetID(label); - const ImVec2 label_size = ImGui::CalcTextSize(label, NULL, true); - - const float square_sz = ImGui::GetFrameHeight(); - const ImVec2 pos = window->DC.CursorPos; - const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz)); - const ImRect total_bb( - pos, - pos - + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), - label_size.y + style.FramePadding.y * 2.0f)); - ImGui::ItemSize(total_bb, style.FramePadding.y); - if (!ImGui::ItemAdd(total_bb, id)) - return false; - - ImVec2 center = check_bb.GetCenter(); - center.x = IM_ROUND(center.x); - center.y = IM_ROUND(center.y); - const float radius = (square_sz - 1.0f) * 0.5f; - - bool hovered, held; - bool pressed = ImGui::ButtonBehavior(total_bb, id, &hovered, &held); - if (pressed) - ImGui::MarkItemEdited(id); - - ImGui::RenderNavCursor(total_bb, id); - const int num_segment = window->DrawList->_CalcCircleAutoSegmentCount(radius); - window->DrawList->AddCircleFilled(center, radius, - ImGui::GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive - : hovered ? ImGuiCol_FrameBgHovered - : ImGuiCol_FrameBg), - num_segment); - if (active) { - const float pad = ImMax(1.0f, IM_TRUNC(square_sz / 6.0f)); - window->DrawList->AddCircleFilled(center, radius - pad, ImGui::GetColorU32(ImGuiCol_CheckMark)); - } - - if (style.FrameBorderSize > 0.0f) { - window->DrawList->AddCircle(center + ImVec2(1, 1), radius, - ImGui::GetColorU32(ImGuiCol_BorderShadow), num_segment, - style.FrameBorderSize); - window->DrawList->AddCircle(center, radius, ImGui::GetColorU32(ImGuiCol_Border), num_segment, - style.FrameBorderSize); - } - - ImVec2 label_pos = - ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y); - if (g.LogEnabled) - ImGui::LogRenderedText(&label_pos, active ? "(x)" : "( )"); - if (label_size.x > 0.0f) - RenderText(label_pos, label, ImGui::FindRenderedTextEnd(label), true); - - IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); - return pressed; -} - -bool CVarRadioButton(const char *text, const char *cvarName, int32_t id, - const RadioButtonsOptions &options) { - std::string make_invisible = "##" + std::string(text) + std::string(cvarName); - - bool ret = false; - int val = CVarGetInteger(cvarName, options.defaultIndex); - PushStyleCheckbox(options.color); - if (ImGui::RadioButton(make_invisible.c_str(), id == val)) { - CVarSetInteger(cvarName, id); - Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); - ret = true; - } - ImGui::SameLine(); - ImGui::Text("%s", text); - PopStyleCheckbox(); - if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) - && !Ship_IsCStringEmpty(options.tooltip)) { - ImGui::SetTooltip("%s", WrappedText(options.tooltip).c_str()); - } - - return ret; -} - -void DrawFlagArray32(const std::string &name, uint32_t &flags, Colors color) { - ImGui::PushID(name.c_str()); - for (int32_t flagIndex = 0; flagIndex < 32; flagIndex++) { - if ((flagIndex % 8) != 0) { - ImGui::SameLine(); - } - ImGui::PushID(flagIndex); - uint32_t bitMask = 1 << flagIndex; - bool flag = (flags & bitMask) != 0; - PushStyleCheckbox(color); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4.0f, 3.0f)); - std::string id = fmt::format("##{}{}", name, flagIndex); - if (ImGui::Checkbox(id.c_str(), &flag)) { - if (flag) { - flags |= bitMask; - } else { - flags &= ~bitMask; - } - } - ImGui::PopStyleVar(); + ImGui::Text("%s", text); PopStyleCheckbox(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && !Ship_IsCStringEmpty(options.tooltip)) { + ImGui::SetTooltip("%s", WrappedText(options.tooltip).c_str()); + } + + return ret; + } + + void DrawFlagArray32(const std::string& name, uint32_t& flags, Colors color) { + ImGui::PushID(name.c_str()); + for (int32_t flagIndex = 0; flagIndex < 32; flagIndex++) { + if ((flagIndex % 8) != 0) { + ImGui::SameLine(); + } + ImGui::PushID(flagIndex); + uint32_t bitMask = 1 << flagIndex; + bool flag = (flags & bitMask) != 0; + PushStyleCheckbox(color); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4.0f, 3.0f)); + std::string id = fmt::format("##{}{}", name, flagIndex); + if (ImGui::Checkbox(id.c_str(), &flag)) { + if (flag) { + flags |= bitMask; + } else { + flags &= ~bitMask; + } + } + ImGui::PopStyleVar(); + PopStyleCheckbox(); + ImGui::PopID(); + } ImGui::PopID(); } - ImGui::PopID(); -} -void DrawFlagArray16(const std::string &name, uint16_t &flags, Colors color) { - ImGui::PushID(name.c_str()); - for (int16_t flagIndex = 0; flagIndex < 16; flagIndex++) { - if ((flagIndex % 8) != 0) { - ImGui::SameLine(); - } - ImGui::PushID(flagIndex); - uint16_t bitMask = 1 << flagIndex; - bool flag = (flags & bitMask) != 0; - PushStyleCheckbox(color); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4.0f, 3.0f)); - std::string id = fmt::format("##{}{}", name, flagIndex); - if (ImGui::Checkbox(id.c_str(), &flag)) { - if (flag) { - flags |= bitMask; - } else { - flags &= ~bitMask; + void DrawFlagArray16(const std::string& name, uint16_t& flags, Colors color) { + ImGui::PushID(name.c_str()); + for (int16_t flagIndex = 0; flagIndex < 16; flagIndex++) { + if ((flagIndex % 8) != 0) { + ImGui::SameLine(); } + ImGui::PushID(flagIndex); + uint16_t bitMask = 1 << flagIndex; + bool flag = (flags & bitMask) != 0; + PushStyleCheckbox(color); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4.0f, 3.0f)); + std::string id = fmt::format("##{}{}", name, flagIndex); + if (ImGui::Checkbox(id.c_str(), &flag)) { + if (flag) { + flags |= bitMask; + } else { + flags &= ~bitMask; + } + } + ImGui::PopStyleVar(); + PopStyleCheckbox(); + ImGui::PopID(); } - ImGui::PopStyleVar(); - PopStyleCheckbox(); ImGui::PopID(); } - ImGui::PopID(); -} -void DrawFlagArray8(const std::string &name, uint8_t &flags, Colors color) { - ImGui::PushID(name.c_str()); - for (int8_t flagIndex = 0; flagIndex < 8; flagIndex++) { - if ((flagIndex % 8) != 0) { - ImGui::SameLine(); - } - ImGui::PushID(flagIndex); - uint8_t bitMask = 1 << flagIndex; - bool flag = (flags & bitMask) != 0; - PushStyleCheckbox(color); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4.0f, 3.0f)); - std::string id = fmt::format("##{}{}", name, flagIndex); - if (ImGui::Checkbox(id.c_str(), &flag)) { - if (flag) { - flags |= bitMask; - } else { - flags &= ~bitMask; + void DrawFlagArray8(const std::string& name, uint8_t& flags, Colors color) { + ImGui::PushID(name.c_str()); + for (int8_t flagIndex = 0; flagIndex < 8; flagIndex++) { + if ((flagIndex % 8) != 0) { + ImGui::SameLine(); } + ImGui::PushID(flagIndex); + uint8_t bitMask = 1 << flagIndex; + bool flag = (flags & bitMask) != 0; + PushStyleCheckbox(color); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4.0f, 3.0f)); + std::string id = fmt::format("##{}{}", name, flagIndex); + if (ImGui::Checkbox(id.c_str(), &flag)) { + if (flag) { + flags |= bitMask; + } else { + flags &= ~bitMask; + } + } + ImGui::PopStyleVar(); + PopStyleCheckbox(); + ImGui::PopID(); } - ImGui::PopStyleVar(); - PopStyleCheckbox(); ImGui::PopID(); } - ImGui::PopID(); -} -void DrawFlagArray8Mask(const std::string &name, uint8_t &flags, Colors color) { - ImGui::PushID(name.c_str()); - for (int8_t flagIndex = 0; flagIndex < 8; flagIndex++) { - if ((flagIndex % 8) != 0) { - ImGui::SameLine(); - } - ImGui::PushID(flagIndex); - uint8_t bitMask = 1 << flagIndex; - bool flag = (flags & bitMask) != 0; - PushStyleCheckbox(color); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4.0f, 3.0f)); - std::string id = fmt::format("##{}{}", name, flagIndex); - if (ImGui::Checkbox(id.c_str(), &flag)) { - if (flag) { - flags |= bitMask; - } else { - flags &= ~bitMask; + void DrawFlagArray8Mask(const std::string& name, uint8_t& flags, Colors color) { + ImGui::PushID(name.c_str()); + for (int8_t flagIndex = 0; flagIndex < 8; flagIndex++) { + if ((flagIndex % 8) != 0) { + ImGui::SameLine(); } + ImGui::PushID(flagIndex); + uint8_t bitMask = 1 << flagIndex; + bool flag = (flags & bitMask) != 0; + PushStyleCheckbox(color); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4.0f, 3.0f)); + std::string id = fmt::format("##{}{}", name, flagIndex); + if (ImGui::Checkbox(id.c_str(), &flag)) { + if (flag) { + flags |= bitMask; + } else { + flags &= ~bitMask; + } + } + ImGui::PopStyleVar(); + PopStyleCheckbox(); + ImGui::PopID(); } - ImGui::PopStyleVar(); - PopStyleCheckbox(); ImGui::PopID(); } - ImGui::PopID(); -} } // namespace UIWidgets ImVec4 GetRandomValue() { @@ -1211,9 +1174,9 @@ ImVec4 GetRandomValue() { std::uniform_int_distribution dist(0, 255 - 1); ImVec4 NewColor; - NewColor.x = (float) (dist(rng)) / 255.0f; - NewColor.y = (float) (dist(rng)) / 255.0f; - NewColor.z = (float) (dist(rng)) / 255.0f; + NewColor.x = (float)(dist(rng)) / 255.0f; + NewColor.y = (float)(dist(rng)) / 255.0f; + NewColor.z = (float)(dist(rng)) / 255.0f; return NewColor; }