From f71d5ee38c1e9f4b0a7783711986fef8dbd90fd0 Mon Sep 17 00:00:00 2001 From: Maxime <672982+maximegmd@users.noreply.github.com> Date: Wed, 28 Jun 2023 20:56:54 +0200 Subject: [PATCH 1/7] Revert "Revert "Feature/its all about fonts"" This reverts commit 7f2b7e08a623cec09b17ae085f1b1b982fbf2ddf. --- .gitmodules | 5 +- scripts/IconGlyphs/icons.lua | 16 +- src/CET.cpp | 10 +- src/CET.h | 3 + src/Fonts.cpp | 505 ++++++++++++++++++++++++++ src/Fonts.h | 70 ++++ src/Options.cpp | 11 +- src/Options.h | 4 +- src/d3d12/D3D12.cpp | 3 +- src/d3d12/D3D12.h | 5 +- src/d3d12/D3D12_Functions.cpp | 146 +------- src/imgui_impl/dx12.cpp | 8 + src/imgui_impl/dx12.h | 3 + src/overlay/Overlay.cpp | 17 +- src/overlay/widgets/Bindings.cpp | 2 +- src/overlay/widgets/Console.cpp | 6 +- src/overlay/widgets/GameLog.cpp | 2 +- src/overlay/widgets/ImGuiDebug.cpp | 2 +- src/overlay/widgets/LogWindow.cpp | 5 + src/overlay/widgets/Settings.cpp | 216 ++++++++--- src/overlay/widgets/Settings.h | 12 +- src/overlay/widgets/TweakDBEditor.cpp | 2 +- src/scripting/LuaSandbox.cpp | 25 +- src/scripting/LuaSandbox.h | 3 +- src/scripting/LuaVM.h | 2 +- src/scripting/LuaVM_Hooks.cpp | 4 +- src/scripting/Scripting.cpp | 20 +- src/scripting/Scripting.h | 3 +- src/sol_imgui/sol_imgui.h | 14 + src/stdafx.h | 4 + vendor/imgui | 1 + xmake.lua | 4 +- 32 files changed, 908 insertions(+), 225 deletions(-) create mode 100644 src/Fonts.cpp create mode 100644 src/Fonts.h create mode 160000 vendor/imgui diff --git a/.gitmodules b/.gitmodules index 8b198a1b..26812505 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,9 @@ [submodule "vendor/RED4ext.SDK"] path = vendor/RED4ext.SDK - url = https://github.com/WopsS/RED4ext.SDK + url = https://github.com/WopsS/RED4ext.SDK.git +[submodule "vendor/imgui"] + path = vendor/imgui + url = ../../WSSDude/imgui.git [submodule "vendor/luasocket"] path = vendor/luasocket url = https://github.com/diegonehab/luasocket.git diff --git a/scripts/IconGlyphs/icons.lua b/scripts/IconGlyphs/icons.lua index 14285ab1..f9ea643b 100644 --- a/scripts/IconGlyphs/icons.lua +++ b/scripts/IconGlyphs/icons.lua @@ -1,7 +1,9 @@ -- Generated by https://github.com/Nats-ji/IconFontCppHeadersAndLuaTables for LuaJLT and Lua 5.3+ -- from https://raw.githubusercontent.com/Templarian/MaterialDesign-SVG/master/meta.json -- for use with https://github.com/Templarian/MaterialDesign-Webfont/blob/master/fonts/materialdesignicons-webfont.ttf -local IconGlyphs = { +local IconGlyphs = {} + +IconGlyphs.icons = { AbTesting = "\u{f01c9}", -- U+F01C9 ab-testing, tags: Developer / Languages Abacus = "\u{f16e0}", -- U+F16E0 abacus, tags: Math AbjadArabic = "\u{f1328}", -- U+F1328 abjad-arabic, aliases: writing-system-arabic, tags: Alpha / Numeric @@ -7099,4 +7101,14 @@ local IconGlyphs = { ZodiacTaurus = "\u{f0a87}", -- U+F0A87 zodiac-taurus, aliases: horoscope-taurus ZodiacVirgo = "\u{f0a88}", -- U+F0A88 zodiac-virgo, aliases: horoscope-virgo } -return IconGlyphs + +IconGlyphs.metatable = { + __index = function(table, key) + AddTextGlyphs(IconGlyphs.icons[key]) + return IconGlyphs.icons[key] + end +} + +setmetatable(IconGlyphs, IconGlyphs.metatable) + +return IconGlyphs \ No newline at end of file diff --git a/src/CET.cpp b/src/CET.cpp index db2b02a8..d791344d 100644 --- a/src/CET.cpp +++ b/src/CET.cpp @@ -60,6 +60,11 @@ LuaVM& CET::GetVM() noexcept return m_vm; } +Fonts& CET::GetFonts() noexcept +{ + return m_fonts; +} + bool CET::IsRunning() noexcept { return s_isRunning; @@ -70,8 +75,9 @@ CET::CET() , m_persistentState(m_paths, m_options) , m_bindings(m_paths, m_options) , m_window(&m_bindings, &m_d3d12) - , m_d3d12(m_window, m_paths, m_options) - , m_vm(m_paths, m_bindings, m_d3d12) + , m_fonts(m_options, m_paths) + , m_d3d12(m_window, m_paths, m_options, m_fonts) + , m_vm(m_paths, m_bindings, m_d3d12, m_fonts) , m_overlay(m_bindings, m_options, m_persistentState, m_vm) { } diff --git a/src/CET.h b/src/CET.h index e5d0940c..3ece03c0 100644 --- a/src/CET.h +++ b/src/CET.h @@ -7,6 +7,7 @@ #include "d3d12/D3D12.h" #include "overlay/Overlay.h" #include "scripting/LuaVM.h" +#include "Fonts.h" struct CET { @@ -23,6 +24,7 @@ struct CET VKBindings& GetBindings() noexcept; Overlay& GetOverlay() noexcept; LuaVM& GetVM() noexcept; + Fonts& GetFonts() noexcept; static bool IsRunning() noexcept; @@ -34,6 +36,7 @@ struct CET PersistentState m_persistentState; VKBindings m_bindings; Window m_window; + Fonts m_fonts; D3D12 m_d3d12; LuaVM m_vm; Overlay m_overlay; diff --git a/src/Fonts.cpp b/src/Fonts.cpp new file mode 100644 index 00000000..8ef2fe04 --- /dev/null +++ b/src/Fonts.cpp @@ -0,0 +1,505 @@ +#include + +#include "Fonts.h" + +#include +#include + +GlyphRangesBuilder::GlyphRangesBuilder() +{ + const ImWchar defaultRange[] = {0x0020, 0x00FF, 0}; + m_builder.AddRanges(defaultRange); + m_builder.AddChar(0xFFFD); // FallbackChar + m_builder.AddChar(0x2026); // EllipsisChar +} + +bool GlyphRangesBuilder::NeedsRebuild() const +{ + return m_needsRebuild; +} + +void GlyphRangesBuilder::AddText(const std::string& acText) +{ + auto text = acText.c_str(); + while (*text) + { + unsigned int c = 0; + int c_len = ImTextCharFromUtf8(&c, text, NULL); + text += c_len; + if (c_len == 0) + break; + if (!m_builder.GetBit(c)) + { + m_builder.AddChar((ImWchar)c); + m_needsRebuild = true; + } + } +} + +bool GlyphRangesBuilder::AddFile(const std::filesystem::path& acPath) +{ + std::ifstream file(acPath); + if (!file) + return false; + + std::stringstream buffer; + buffer << file.rdbuf(); + + AddText(buffer.str()); + + file.close(); + + return true; +} + +void GlyphRangesBuilder::BuildRanges(ImVector* apRange) +{ + m_builder.BuildRanges(apRange); + m_needsRebuild = false; +} + +Font::Font(const std::filesystem::path& acPath) + : m_path(acPath) +{ + m_name = UTF16ToUTF8(m_path.stem().native()); +} +Font::Font(const std::string& acName, const std::filesystem::path& acPath) + : m_name(acName) + , m_path(acPath) +{ +} +std::string Font::GetName() const +{ + return m_name; +} +std::filesystem::path Font::GetPath() const +{ + return m_path; +} +bool Font::Exists() +{ + return exists(m_path); +} + +// Build Fonts +// if custom font not set: +// we merge and use all the notosans fonts +// (e.g. NotoSans-Regular.ttf + NotoSansJP-Regular.otf + ...). +// +// if custom font is set: +// we use the custom font (e.g. c:/windows/fonts/Comic.ttf). +// TODO: Refactor this +void Fonts::BuildFonts(const SIZE& acOutSize) +{ + // TODO: scale also by DPI + const auto [resx, resy] = acOutSize; + const auto scaleFromReference = std::min(static_cast(resx) / 1920.0f, static_cast(resy) / 1080.0f); + + auto& io = ImGui::GetIO(); + io.Fonts->Clear(); + + const auto& fontSettings = m_options.Font; + const float fontSize = std::floorf(fontSettings.BaseSize * scaleFromReference); + // scale emoji's fontsize by 0.8 to make the glyphs roughly the same size as the main font. not sure about other font, don't really have a good solution. + const float emojiSize = fontSize * 0.8f; + + // get fontpaths + // Get custom font paths from options + const auto customMainFontPath = GetFontPathFromOption(fontSettings.MainFont); + if (customMainFontPath.empty() && !fontSettings.MainFont.empty() && fontSettings.MainFont != "Default") + Log::Warn("Can't find custom main font at path: {}", GetAbsolutePath(fontSettings.MainFont, m_paths.Fonts(), true).string()); + + const auto customMonosFontPath = GetFontPathFromOption(fontSettings.MonoFont); + if (customMonosFontPath.empty() && !fontSettings.MonoFont.empty() && fontSettings.MonoFont != "Default") + Log::Warn("Can't find custom main font at path: {}", GetAbsolutePath(fontSettings.MonoFont, m_paths.Fonts(), true).string()); + + const bool useCustomMainFont = !customMainFontPath.empty(); + const bool useCustomMonosFont = !customMonosFontPath.empty(); + + const auto defaultMainFontPath = GetAbsolutePath(m_defaultMainFont, m_paths.Fonts(), false); + const auto defaultMonoFontPath = GetAbsolutePath(m_defaultMonoFont, m_paths.Fonts(), false); + + // Set main font path to default if customMainFontPath is empty or doesnt exist. + const auto mainFontPath = useCustomMainFont ? customMainFontPath : defaultMainFontPath; + if (mainFontPath.empty()) + Log::Warn("Can't find default main font at path: {}, will use built-in font.", GetAbsolutePath(m_defaultMainFont, m_paths.Fonts(), true).string()); + + // Set monospace font path to default if customMonosFontPath is empty or doesnt exist. + const auto monoFontPath = useCustomMonosFont ? customMonosFontPath : defaultMonoFontPath; + if (monoFontPath.empty()) + Log::Warn("Can't find default monospacee font at path: {}, will use built-in font.", GetAbsolutePath(m_defaultMonoFont, m_paths.Fonts(), true).string()); + + const auto iconFontPath = GetAbsolutePath(m_defaultIconFont, m_paths.Fonts(), false); + if (iconFontPath.empty()) + Log::Warn("Can't find icon font at path: {}", GetAbsolutePath(m_defaultIconFont, m_paths.Fonts(), true).string()); + + const auto emojiFontPath = GetAbsolutePath(m_defaultEmojiFont, m_paths.Fonts(), false); + if (emojiFontPath.empty()) + Log::Warn("Can't find emoji font at path: {}", GetAbsolutePath(m_defaultEmojiFont, m_paths.Fonts(), true).string()); + + m_useEmojiFont = !emojiFontPath.empty(); + + // create config for each font + ImFontConfig fontConfig; + fontConfig.OversampleH = fontSettings.OversampleHorizontal; + fontConfig.OversampleV = fontSettings.OversampleVertical; + + static ImVector fontRange; + fontRange.clear(); + m_glyphRangesBuilder.BuildRanges(&fontRange); + + ImFontConfig iconFontConfig; + iconFontConfig.OversampleH = iconFontConfig.OversampleV = 1; + iconFontConfig.GlyphMinAdvanceX = fontSize; + + ImFontConfig emojiFontConfig; + emojiFontConfig.OversampleH = emojiFontConfig.OversampleV = 1; + emojiFontConfig.FontBuilderFlags |= ImGuiFreeTypeBuilderFlags_LoadColor; + + // load fonts without merging first, so we can calculate the offset to align the fonts. + float mainFontBaselineOffset = 0.0f; + float monoFontBaselineOffset = 0.0f; + if (!mainFontPath.empty() && !monoFontPath.empty() && !iconFontPath.empty()) + { + static const ImWchar mainFontRange[] = {0x0041, 0x0041, 0}; + static const ImWchar iconFontRange[] = {0xF01C9, 0xF01C9, 0}; + auto mainFont = io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(mainFontPath.native()).c_str(), fontSize, &fontConfig, mainFontRange); + auto monoFont = io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(monoFontPath.native()).c_str(), fontSize, &fontConfig, mainFontRange); + auto iconFont = io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(iconFontPath.native()).c_str(), fontSize, &iconFontConfig, iconFontRange); + + io.Fonts->Build(); // Build atlas, retrieve pixel data. + + // calculate font baseline differences + mainFontBaselineOffset = iconFont->Ascent - mainFont->Ascent; + monoFontBaselineOffset = iconFont->Ascent - monoFont->Ascent; + + // clear fonts then merge + io.Fonts->Clear(); + } + + // reconfig fonts for merge + iconFontConfig.MergeMode = true; + emojiFontConfig.MergeMode = true; + + // add main font + { + fontConfig.GlyphOffset.y = std::floorf(mainFontBaselineOffset * -0.5f); + iconFontConfig.GlyphOffset.y = std::ceilf(mainFontBaselineOffset * 0.5f); + + if (!mainFontPath.empty()) + MainFont = io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(mainFontPath.native()).c_str(), fontSize, &fontConfig, fontRange.Data); + else + MainFont = io.Fonts->AddFontDefault(); + + fontConfig.MergeMode = true; + // merge NotoSans-Regular as fallback font when using custom font + if (useCustomMainFont && !defaultMainFontPath.empty()) + io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(defaultMainFontPath.native()).c_str(), fontSize, &fontConfig, fontRange.Data); + + // merge the default CJK fonts + for (const auto& font : m_defaultCJKFonts) + { + const std::filesystem::path fontPath = GetAbsolutePath(font, m_paths.Fonts(), false); + if (fontPath.empty()) + { + Log::Warn("Can't find font {}.", GetAbsolutePath(font, m_paths.Fonts(), true).string()); + continue; + } + io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(fontPath.native()).c_str(), fontSize, &fontConfig, fontRange.Data); + } + fontConfig.MergeMode = false; + + // merge the icon font and emoji font + if (!iconFontPath.empty()) + io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(iconFontPath.native()).c_str(), fontSize, &iconFontConfig, fontRange.Data); + + if (m_useEmojiFont) + io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(emojiFontPath.native()).c_str(), emojiSize, &emojiFontConfig, fontRange.Data); + } + + // add monospace font + { + fontConfig.GlyphOffset.y = std::floorf(monoFontBaselineOffset * -0.5f); + iconFontConfig.GlyphOffset.y = std::ceilf(monoFontBaselineOffset * 0.5f); + + if (!monoFontPath.empty()) + MonoFont = io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(monoFontPath.native()).c_str(), fontSize, &fontConfig, fontRange.Data); + else + MonoFont = io.Fonts->AddFontDefault(); + + fontConfig.MergeMode = true; + + // merge NotoSans-Mono as fallback font when using custom monospace font + if (useCustomMonosFont && !defaultMonoFontPath.empty()) + io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(defaultMonoFontPath.native()).c_str(), fontSize, &fontConfig, fontRange.Data); + + // merge main font with monospace font + if (!mainFontPath.empty()) + io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(mainFontPath.native()).c_str(), fontSize, &fontConfig, fontRange.Data); + + // merge the default CJK fonts + for (const auto& font : m_defaultCJKFonts) + { + const std::filesystem::path fontPath = GetAbsolutePath(font, m_paths.Fonts(), false); + if (fontPath.empty()) + continue; + io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(fontPath.native()).c_str(), fontSize, &fontConfig, fontRange.Data); + } + + if (!iconFontPath.empty()) + io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(iconFontPath.native()).c_str(), fontSize, &iconFontConfig, fontRange.Data); + + if (m_useEmojiFont) + io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(emojiFontPath.native()).c_str(), emojiSize, &emojiFontConfig, fontRange.Data); + } +} + +// Rebuild font texture during runtime. +// Call before ImGui_ImplXXXX_NewFrame() +void Fonts::RebuildFonts(ID3D12CommandQueue* apCommandQueue, const SIZE& acOutSize) +{ + + if (m_rebuildFonts || m_glyphRangesBuilder.NeedsRebuild()) // Rebuild when font settings changed or glyph ranges changed + { + BuildFonts(acOutSize); + ImGui_ImplDX12_RecreateFontsTexture(apCommandQueue); + + m_rebuildFonts = false; + } +} + +// Call from imgui to trgger RebuildFonts in the next frame +void Fonts::RebuildFontNextFrame() +{ + m_rebuildFonts = true; +} + +// Check if the emoji font is loaded. +const bool Fonts::UseEmojiFont() +{ + return m_useEmojiFont; +} + +// Get system fonts and their path +void Fonts::EnumerateSystemFonts() +{ + m_systemFonts.clear(); + m_systemFonts.emplace_back(Font("Default", "")); + IDWriteFactory* pDWriteFactory = NULL; + HRESULT hresult = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast(&pDWriteFactory)); + + IDWriteFontCollection* pFontCollection = NULL; + + // Get the system font collection. + if (SUCCEEDED(hresult)) + hresult = pDWriteFactory->GetSystemFontCollection(&pFontCollection); + + UINT32 familyCount = 0; + + // Get the number of font families in the collection. + if (SUCCEEDED(hresult)) + familyCount = pFontCollection->GetFontFamilyCount(); + + for (UINT32 i = 0; i < familyCount; ++i) + { + IDWriteFontFamily* pFontFamily = NULL; + + // Get the font family. + if (SUCCEEDED(hresult)) + hresult = pFontCollection->GetFontFamily(i, &pFontFamily); + + IDWriteLocalizedStrings* pFamilyNames = NULL; + + // Get a list of localized strings for the family name. + if (SUCCEEDED(hresult)) + hresult = pFontFamily->GetFamilyNames(&pFamilyNames); + + UINT32 index = 0; + BOOL exists = false; + + wchar_t localeName[LOCALE_NAME_MAX_LENGTH]; + + if (SUCCEEDED(hresult)) + { + // Get the default locale for this user. + int defaultLocaleSuccess = GetUserDefaultLocaleName(localeName, LOCALE_NAME_MAX_LENGTH); + + // If the default locale is returned, find that locale name, otherwise use "en-us". + if (defaultLocaleSuccess) + hresult = pFamilyNames->FindLocaleName(localeName, &index, &exists); + + if (SUCCEEDED(hresult) && !exists) // if the above find did not find a match, retry with US English + hresult = pFamilyNames->FindLocaleName(L"en-us", &index, &exists); + } + + // If the specified locale doesn't exist, select the first on the list. + if (!exists) + index = 0; + + UINT32 length = 0; + + // Get the string length. + if (SUCCEEDED(hresult)) + hresult = pFamilyNames->GetStringLength(index, &length); + + // Allocate a string big enough to hold the name. + wchar_t* name = new (std::nothrow) wchar_t[length + 1]; + if (name == NULL) + hresult = E_OUTOFMEMORY; + + // Get the family name. + if (SUCCEEDED(hresult)) + hresult = pFamilyNames->GetString(index, name, length + 1); + + // Get font + IDWriteFont* pFont = NULL; + if (SUCCEEDED(hresult)) + hresult = pFontFamily->GetFont(index, &pFont); + + // Get fontface + IDWriteFontFace* pFontFace = NULL; + if (SUCCEEDED(hresult)) + hresult = pFont->CreateFontFace(&pFontFace); + + UINT32 numberOfFiles = 0; + if (SUCCEEDED(hresult)) + hresult = pFontFace->GetFiles(&numberOfFiles, NULL); + + IDWriteFontFile* pFontFiles = NULL; + if (SUCCEEDED(hresult)) + hresult = pFontFace->GetFiles(&numberOfFiles, &pFontFiles); + + if (numberOfFiles > 0) + { + IDWriteFontFileLoader* pFileLoader = NULL; + IDWriteLocalFontFileLoader* pLocalFileLoader = NULL; + const void* pFontFileReferenceKey = NULL; + UINT32 fontFileReferenceKeySize = 0; + + if (SUCCEEDED(hresult)) + hresult = pFontFiles[0].GetLoader(&pFileLoader); + + if (SUCCEEDED(hresult)) + hresult = pFontFiles[0].GetReferenceKey(&pFontFileReferenceKey, &fontFileReferenceKeySize); + + if (SUCCEEDED(hresult)) + hresult = pFileLoader->QueryInterface(__uuidof(IDWriteLocalFontFileLoader), (void**)&pLocalFileLoader); + + UINT32 filePathLength = 0; + if (SUCCEEDED(hresult)) + hresult = pLocalFileLoader->GetFilePathLengthFromKey(pFontFileReferenceKey, fontFileReferenceKeySize, &filePathLength); + + WCHAR* fontPath = new (std::nothrow) WCHAR[filePathLength + 1]; + if (SUCCEEDED(hresult)) + hresult = pLocalFileLoader->GetFilePathFromKey(pFontFileReferenceKey, fontFileReferenceKeySize, fontPath, filePathLength + 1); + + if (SUCCEEDED(hresult)) + { + m_systemFonts.emplace_back(Font(UTF16ToUTF8(name), fontPath)); + } + } + } + + // print error message if failed + if (FAILED(hresult)) + Log::Error("Error message: {}", std::system_category().message(hresult)); +} + +const std::vector& Fonts::GetSystemFonts() +{ + return m_systemFonts; +} + +Font Fonts::GetSystemFont(const std::string& acFontName) const +{ + for (const auto& systemFont : m_systemFonts) + { + if (systemFont.GetName() == acFontName) + return systemFont; + } + return Font(""); +} + +// Returns absolute path, already checked for file existence. +std::filesystem::path Fonts::GetFontPathFromOption(const std::string& acFontOption) const +{ + if (GetSystemFont(acFontOption).Exists()) + return GetSystemFont(acFontOption).GetPath(); + + if (!GetAbsolutePath(acFontOption, m_paths.Fonts(), false).empty()) + return GetAbsolutePath(acFontOption, m_paths.Fonts(), false); + + return {}; +} + +GlyphRangesBuilder& Fonts::GetGlyphRangesBuilder() +{ + return m_glyphRangesBuilder; +} + +void Fonts::PrecacheGlyphsFromMods() +{ + const auto modsRoot = m_paths.ModsRoot(); + + int fileCount = 0; + + for (const auto& modEntry : std::filesystem::directory_iterator(modsRoot)) + { + // ignore normal files + if (!modEntry.is_directory() && !modEntry.is_symlink()) + continue; + // ignore mod using preserved name + if (modEntry.path().native().starts_with(L"cet\\")) + continue; + + const auto path = GetAbsolutePath(modEntry.path(), modsRoot, false); + // ignore invalid path + if (path.empty()) + continue; + // ignore path symlinked to file + if (!is_directory(path)) + continue; + // ignore directory doesn't contain init.lua + if (!exists(path / L"init.lua")) + continue; + + // iterate all files within each mod folder recursively + for (const auto& entry : std::filesystem::recursive_directory_iterator(modEntry, std::filesystem::directory_options::follow_directory_symlink)) + { + const auto pathStr = UTF16ToUTF8(entry.path().native()); + + // add the file path to the glyph range builder + m_glyphRangesBuilder.AddText(pathStr); + + if (!entry.is_regular_file()) + continue; + + // ignore files without the following extension names: lua, txt, json, yml, yaml, toml, ini + const std::vector extensionFilter = {".lua", ".txt", ".json", ".yml", ".yaml", ".toml", ".ini"}; + const std::string entryExtension = UTF16ToUTF8(entry.path().extension().native()); + if (std::find(extensionFilter.begin(), extensionFilter.end(), entryExtension) == extensionFilter.end()) + continue; + + // open the file and add the content to the glyph range builder + bool result = m_glyphRangesBuilder.AddFile(entry.path()); + + if (!result) + { + Log::Error("Can't read file {}.", pathStr); + continue; + } + + fileCount++; + } + } + + Log::Info("Total mod files cached into glyph ranges builder: {}.", fileCount); +} + +Fonts::Fonts(Options& aOptions, Paths& aPaths) + : m_options(aOptions) + , m_paths(aPaths) +{ + EnumerateSystemFonts(); + PrecacheGlyphsFromMods(); +} \ No newline at end of file diff --git a/src/Fonts.h b/src/Fonts.h new file mode 100644 index 00000000..ce3a9cb3 --- /dev/null +++ b/src/Fonts.h @@ -0,0 +1,70 @@ +#pragma once + +// a wrapper for ImFontGlyphRangesBuilder +struct GlyphRangesBuilder +{ + GlyphRangesBuilder(); + bool NeedsRebuild() const; + void AddText(const std::string& acText); + bool AddFile(const std::filesystem::path& acPath); + void BuildRanges(ImVector* apRange); + +private: + bool m_needsRebuild{false}; + ImFontGlyphRangesBuilder m_builder; +}; + +struct Font +{ + Font(const std::filesystem::path& acPath); + Font(const std::string& acName, const std::filesystem::path& acPath); + std::string GetName() const; + std::filesystem::path GetPath() const; + bool Exists(); + +private: + std::string m_name; + std::filesystem::path m_path; +}; + +struct Fonts +{ + ~Fonts() = default; + + void BuildFonts(const SIZE& acOutSize); + void RebuildFonts(ID3D12CommandQueue* apCommandQueue, const SIZE& acOutSize); + void RebuildFontNextFrame(); + + const bool UseEmojiFont(); + + void EnumerateSystemFonts(); + const std::vector& GetSystemFonts(); + Font GetSystemFont(const std::string& acFontName) const; + std::filesystem::path GetFontPathFromOption(const std::string& acFontOption) const; + + GlyphRangesBuilder& GetGlyphRangesBuilder(); + void PrecacheGlyphsFromMods(); + + ImFont* MainFont; + ImFont* MonoFont; + +private: + friend struct CET; + Fonts(Options& aOptions, Paths& aPaths); + + Options& m_options; + Paths& m_paths; + + GlyphRangesBuilder m_glyphRangesBuilder; + + bool m_rebuildFonts{false}; + bool m_useEmojiFont{false}; + std::vector m_systemFonts; + + std::filesystem::path m_defaultMainFont{L"NotoSans-Regular.ttf"}; + std::vector m_defaultCJKFonts{ + L"NotoSansJP-Regular.otf", L"NotoSansKR-Regular.otf", L"NotoSansSC-Regular.otf", L"NotoSansTC-Regular.otf", L"NotoSansThai-Regular.ttf"}; + std::filesystem::path m_defaultMonoFont{L"NotoSansMono-Regular.ttf"}; + std::filesystem::path m_defaultIconFont{L"materialdesignicons.ttf"}; + std::filesystem::path m_defaultEmojiFont{L"C:\\Windows\\Fonts\\seguiemj.ttf"}; // tried to use noto color emoji but it wont render. only this one works +}; diff --git a/src/Options.cpp b/src/Options.cpp index 17634c92..2cc52776 100644 --- a/src/Options.cpp +++ b/src/Options.cpp @@ -36,8 +36,8 @@ void PatchesSettings::ResetToDefaults() void FontSettings::Load(const nlohmann::json& aConfig) { - Path = aConfig.value("path", Path); - Language = aConfig.value("language", Language); + MainFont = aConfig.value("main_font", MainFont); + MonoFont = aConfig.value("mono_font", MonoFont); BaseSize = aConfig.value("base_size", BaseSize); OversampleHorizontal = aConfig.value("oversample_horizontal", OversampleHorizontal); OversampleVertical = aConfig.value("oversample_vertical", OversampleVertical); @@ -45,7 +45,12 @@ void FontSettings::Load(const nlohmann::json& aConfig) nlohmann::json FontSettings::Save() const { - return {{"path", Path}, {"language", Language}, {"base_size", BaseSize}, {"oversample_horizontal", OversampleHorizontal}, {"oversample_vertical", OversampleVertical}}; + return { + {"main_font", MainFont}, + {"mono_font", MonoFont}, + {"base_size", BaseSize}, + {"oversample_horizontal", OversampleHorizontal}, + {"oversample_vertical", OversampleVertical}}; } void FontSettings::ResetToDefaults() diff --git a/src/Options.h b/src/Options.h index 7b01a506..03a7767d 100644 --- a/src/Options.h +++ b/src/Options.h @@ -30,8 +30,8 @@ struct FontSettings [[nodiscard]] auto operator<=>(const FontSettings&) const = default; - std::string Path{}; - std::string Language{"Default"}; + std::string MainFont{"Default"}; + std::string MonoFont{"Default"}; float BaseSize{18.0f}; int32_t OversampleHorizontal{3}; int32_t OversampleVertical{1}; diff --git a/src/d3d12/D3D12.cpp b/src/d3d12/D3D12.cpp index 58a99bc7..01e1558e 100644 --- a/src/d3d12/D3D12.cpp +++ b/src/d3d12/D3D12.cpp @@ -60,10 +60,11 @@ LRESULT D3D12::OnWndProc(HWND ahWnd, UINT auMsg, WPARAM awParam, LPARAM alParam) return 0; } -D3D12::D3D12(Window& aWindow, Paths& aPaths, Options& aOptions) +D3D12::D3D12(Window& aWindow, Paths& aPaths, Options& aOptions, Fonts& aFonts) : m_paths(aPaths) , m_window(aWindow) , m_options(aOptions) + , m_fonts(aFonts) { HookGame(); diff --git a/src/d3d12/D3D12.h b/src/d3d12/D3D12.h index 0c64197b..0db5eba1 100644 --- a/src/d3d12/D3D12.h +++ b/src/d3d12/D3D12.h @@ -15,11 +15,9 @@ struct D3D12 { inline static const uint32_t g_numDownlevelBackbuffersRequired = 3; // Windows 7 only: number of buffers needed before we start rendering - D3D12(Window& aWindow, Paths& aPaths, Options& aOptions); + D3D12(Window& aWindow, Paths& aPaths, Options& aOptions, Fonts& aFonts); ~D3D12(); - void ReloadFonts(); - void SetTrapInputInImGui(const bool acEnabled); void DelayedSetTrapInputInImGui(const bool acEnabled); [[nodiscard]] bool IsTrapInputInImGui() const noexcept { return m_trapInputInImGui; } @@ -95,6 +93,7 @@ struct D3D12 Paths& m_paths; Window& m_window; Options& m_options; + Fonts& m_fonts; std::recursive_mutex m_imguiLock; std::array m_imguiDrawDataBuffers; diff --git a/src/d3d12/D3D12_Functions.cpp b/src/d3d12/D3D12_Functions.cpp index 92f154fb..dcc2e08e 100644 --- a/src/d3d12/D3D12_Functions.cpp +++ b/src/d3d12/D3D12_Functions.cpp @@ -277,148 +277,6 @@ bool D3D12::InitializeDownlevel(ID3D12CommandQueue* apCommandQueue, ID3D12Resour return true; } -void D3D12::ReloadFonts() -{ - std::lock_guard _(m_imguiLock); - - // TODO - scale also by DPI - const auto [resx, resy] = m_outSize; - const auto scaleFromReference = std::min(static_cast(resx) / 1920.0f, static_cast(resy) / 1080.0f); - - auto& io = ImGui::GetIO(); - io.Fonts->Clear(); - - ImFontConfig config; - const auto& fontSettings = m_options.Font; - config.SizePixels = std::floorf(fontSettings.BaseSize * scaleFromReference); - config.OversampleH = fontSettings.OversampleHorizontal; - config.OversampleV = fontSettings.OversampleVertical; - if (config.OversampleH == 1 && config.OversampleV == 1) - config.PixelSnapH = true; - config.MergeMode = false; - - // add default font - const auto customFontPath = fontSettings.Path.empty() ? std::filesystem::path{} : GetAbsolutePath(UTF8ToUTF16(fontSettings.Path), m_paths.Fonts(), false); - auto cetFontPath = GetAbsolutePath(L"NotoSans-Regular.ttf", m_paths.Fonts(), false); - const auto* cpGlyphRanges = io.Fonts->GetGlyphRangesDefault(); - if (customFontPath.empty()) - { - if (!fontSettings.Path.empty()) - Log::Warn("D3D12::ReloadFonts() - Custom font path is invalid! Using default CET font."); - - if (cetFontPath.empty()) - { - Log::Warn("D3D12::ReloadFonts() - Missing default fonts!"); - io.Fonts->AddFontDefault(&config); - } - else - io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(cetFontPath.native()).c_str(), config.SizePixels, &config, cpGlyphRanges); - } - else - io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(customFontPath.native()).c_str(), config.SizePixels, &config, cpGlyphRanges); - - if (fontSettings.Language == "ChineseFull") - { - cetFontPath = GetAbsolutePath(m_paths.Fonts() / L"NotoSansTC-Regular.otf", m_paths.Fonts(), false); - cpGlyphRanges = io.Fonts->GetGlyphRangesChineseFull(); - } - else if (fontSettings.Language == "ChineseSimplifiedCommon") - { - cetFontPath = GetAbsolutePath(m_paths.Fonts() / L"NotoSansSC-Regular.otf", m_paths.Fonts(), false); - cpGlyphRanges = io.Fonts->GetGlyphRangesChineseSimplifiedCommon(); - } - else if (fontSettings.Language == "Japanese") - { - cetFontPath = GetAbsolutePath(m_paths.Fonts() / L"NotoSansJP-Regular.otf", m_paths.Fonts(), false); - cpGlyphRanges = io.Fonts->GetGlyphRangesJapanese(); - } - else if (fontSettings.Language == "Korean") - { - cetFontPath = GetAbsolutePath(m_paths.Fonts() / L"NotoSansKR-Regular.otf", m_paths.Fonts(), false); - cpGlyphRanges = io.Fonts->GetGlyphRangesKorean(); - } - else if (fontSettings.Language == "Cyrillic") - { - cetFontPath = GetAbsolutePath(m_paths.Fonts() / L"NotoSans-Regular.ttf", m_paths.Fonts(), false); - cpGlyphRanges = io.Fonts->GetGlyphRangesCyrillic(); - } - else if (fontSettings.Language == "Thai") - { - cetFontPath = GetAbsolutePath(m_paths.Fonts() / L"NotoSansThai-Regular.ttf", m_paths.Fonts(), false); - cpGlyphRanges = io.Fonts->GetGlyphRangesThai(); - } - else if (fontSettings.Language == "Vietnamese") - { - cetFontPath = GetAbsolutePath(m_paths.Fonts() / L"NotoSans-Regular.ttf", m_paths.Fonts(), false); - cpGlyphRanges = io.Fonts->GetGlyphRangesVietnamese(); - } - else - { - switch (GetSystemDefaultLangID()) - { - case MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL): - cetFontPath = GetAbsolutePath(L"NotoSansTC-Regular.otf", m_paths.Fonts(), false); - cpGlyphRanges = io.Fonts->GetGlyphRangesChineseFull(); - break; - - case MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED): - cetFontPath = GetAbsolutePath(m_paths.Fonts() / L"NotoSansSC-Regular.otf", m_paths.Fonts(), false); - cpGlyphRanges = io.Fonts->GetGlyphRangesChineseSimplifiedCommon(); - break; - - case MAKELANGID(LANG_JAPANESE, SUBLANG_DEFAULT): - cetFontPath = GetAbsolutePath(m_paths.Fonts() / L"NotoSansJP-Regular.otf", m_paths.Fonts(), false); - cpGlyphRanges = io.Fonts->GetGlyphRangesJapanese(); - break; - - case MAKELANGID(LANG_KOREAN, SUBLANG_DEFAULT): - cetFontPath = GetAbsolutePath(m_paths.Fonts() / L"NotoSansKR-Regular.otf", m_paths.Fonts(), false); - cpGlyphRanges = io.Fonts->GetGlyphRangesKorean(); - break; - - case MAKELANGID(LANG_BELARUSIAN, SUBLANG_DEFAULT): - case MAKELANGID(LANG_RUSSIAN, SUBLANG_DEFAULT): - cetFontPath = GetAbsolutePath(m_paths.Fonts() / L"NotoSans-Regular.ttf", m_paths.Fonts(), false); - cpGlyphRanges = io.Fonts->GetGlyphRangesCyrillic(); - break; - - case MAKELANGID(LANG_THAI, SUBLANG_DEFAULT): - cetFontPath = GetAbsolutePath(m_paths.Fonts() / L"NotoSansThai-Regular.ttf", m_paths.Fonts(), false); - cpGlyphRanges = io.Fonts->GetGlyphRangesThai(); - break; - - case MAKELANGID(LANG_VIETNAMESE, SUBLANG_DEFAULT): - cetFontPath = GetAbsolutePath(m_paths.Fonts() / L"NotoSans-Regular.ttf", m_paths.Fonts(), false); - cpGlyphRanges = io.Fonts->GetGlyphRangesVietnamese(); - break; - } - } - - // add extra glyphs from language font - config.MergeMode = true; - if (customFontPath.empty()) - { - if (!fontSettings.Path.empty()) - Log::Warn("D3D12::ReloadFonts() - Custom font path is invalid! Using default CET font."); - - if (cetFontPath.empty()) - { - Log::Warn("D3D12::ReloadFonts() - Missing fonts for extra language glyphs!"); - io.Fonts->AddFontDefault(&config); - } - else - io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(cetFontPath.native()).c_str(), config.SizePixels, &config, cpGlyphRanges); - } - else - io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(customFontPath.native()).c_str(), config.SizePixels, &config, cpGlyphRanges); - - // add icons from fontawesome4 - config.GlyphMinAdvanceX = config.SizePixels; - static const ImWchar icon_ranges[] = {ICON_MIN_MD, ICON_MAX_MD, 0}; - auto cetIconPath = GetAbsolutePath(L"materialdesignicons.ttf", m_paths.Fonts(), false); - io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(cetIconPath.native()).c_str(), config.SizePixels, &config, icon_ranges); -} - bool D3D12::InitializeImGui(size_t aBuffersCounts) { std::lock_guard _(m_imguiLock); @@ -464,7 +322,7 @@ bool D3D12::InitializeImGui(size_t aBuffersCounts) return false; } - ReloadFonts(); + m_fonts.BuildFonts(m_outSize); if (!ImGui_ImplDX12_CreateDeviceObjects(m_pCommandQueue.Get())) { @@ -484,6 +342,8 @@ void D3D12::PrepareUpdate() std::lock_guard _(m_imguiLock); + m_fonts.RebuildFonts(m_pCommandQueue.Get(), m_outSize); + ImGui_ImplWin32_NewFrame(m_outSize); ImGui::NewFrame(); diff --git a/src/imgui_impl/dx12.cpp b/src/imgui_impl/dx12.cpp index 394196c6..33e4f09f 100644 --- a/src/imgui_impl/dx12.cpp +++ b/src/imgui_impl/dx12.cpp @@ -690,3 +690,11 @@ void ImGui_ImplDX12_NewFrame(ID3D12CommandQueue* apCommandQueue) if (!g_pPipelineState || !ImGui::GetIO().Fonts->IsBuilt()) ImGui_ImplDX12_CreateDeviceObjects(apCommandQueue); } + +void ImGui_ImplDX12_RecreateFontsTexture(ID3D12CommandQueue* apCommandQueue) +{ + SafeRelease(g_pFontTextureResource); + ImGuiIO& io = ImGui::GetIO(); + io.Fonts->TexID = NULL; + ImGui_ImplDX12_CreateFontsTexture(apCommandQueue); +} \ No newline at end of file diff --git a/src/imgui_impl/dx12.h b/src/imgui_impl/dx12.h index 899afbdc..b43d44ae 100644 --- a/src/imgui_impl/dx12.h +++ b/src/imgui_impl/dx12.h @@ -38,3 +38,6 @@ IMGUI_IMPL_API void ImGui_ImplDX12_RenderDrawData(ImDrawData* apDrawData, ID3D12 // Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue); + +// Use to recreate font texture during runtime. Call before NewFrame().Should switch to https://github.com/ocornut/imgui/pull/3761 once it's implemented. +IMGUI_IMPL_API void ImGui_ImplDX12_RecreateFontsTexture(ID3D12CommandQueue* apCommandQueue); \ No newline at end of file diff --git a/src/overlay/Overlay.cpp b/src/overlay/Overlay.cpp index ea60cea0..263d23a5 100644 --- a/src/overlay/Overlay.cpp +++ b/src/overlay/Overlay.cpp @@ -286,11 +286,14 @@ Overlay::~Overlay() void Overlay::DrawToolbar() { + // add icons to glyph builder + CET::Get().GetFonts().GetGlyphRangesBuilder().AddText(ICON_MD_CONSOLE ICON_MD_KEYBOARD_SETTINGS ICON_MD_COG ICON_MD_DATABASE_EDIT ICON_MD_FILE_DOCUMENT ICON_MD_BUG ICON_MD_RESTART); + const auto itemWidth = GetAlignedItemWidth(7); auto& persistentState = m_persistentState.Overlay; ImGui::PushStyleColor(ImGuiCol_Button, persistentState.ConsoleToggled ? ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive) : ImGui::GetStyleColorVec4(ImGuiCol_Button)); - if (ImGui::Button("Console", ImVec2(itemWidth, 0))) + if (ImGui::Button(ICON_MD_CONSOLE " Console", ImVec2(itemWidth, 0))) m_console.Toggle(); if (!m_toggled) persistentState.ConsoleToggled = m_console.IsEnabled(); @@ -299,7 +302,7 @@ void Overlay::DrawToolbar() ImGui::SameLine(); ImGui::PushStyleColor(ImGuiCol_Button, persistentState.BindingsToggled ? ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive) : ImGui::GetStyleColorVec4(ImGuiCol_Button)); - if (ImGui::Button("Bindings", ImVec2(itemWidth, 0))) + if (ImGui::Button(ICON_MD_KEYBOARD_SETTINGS " Bindings", ImVec2(itemWidth, 0))) m_bindings.Toggle(); if (!m_toggled) persistentState.BindingsToggled = m_bindings.IsEnabled(); @@ -308,7 +311,7 @@ void Overlay::DrawToolbar() ImGui::SameLine(); ImGui::PushStyleColor(ImGuiCol_Button, persistentState.SettingsToggled ? ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive) : ImGui::GetStyleColorVec4(ImGuiCol_Button)); - if (ImGui::Button("Settings", ImVec2(itemWidth, 0))) + if (ImGui::Button(ICON_MD_COG " Settings", ImVec2(itemWidth, 0))) m_settings.Toggle(); if (!m_toggled) persistentState.SettingsToggled = m_settings.IsEnabled(); @@ -317,7 +320,7 @@ void Overlay::DrawToolbar() ImGui::SameLine(); ImGui::PushStyleColor(ImGuiCol_Button, persistentState.TweakDBEditorToggled ? ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive) : ImGui::GetStyleColorVec4(ImGuiCol_Button)); - if (ImGui::Button("TweakDB Editor", ImVec2(itemWidth, 0))) + if (ImGui::Button(ICON_MD_DATABASE_EDIT " TweakDB Editor", ImVec2(itemWidth, 0))) m_tweakDBEditor.Toggle(); if (!m_toggled) persistentState.TweakDBEditorToggled = m_tweakDBEditor.IsEnabled(); @@ -326,7 +329,7 @@ void Overlay::DrawToolbar() ImGui::SameLine(); ImGui::PushStyleColor(ImGuiCol_Button, persistentState.GameLogToggled ? ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive) : ImGui::GetStyleColorVec4(ImGuiCol_Button)); - if (ImGui::Button("Game Log", ImVec2(itemWidth, 0))) + if (ImGui::Button(ICON_MD_FILE_DOCUMENT " Game Log", ImVec2(itemWidth, 0))) m_gameLog.Toggle(); if (!m_toggled) persistentState.GameLogToggled = m_gameLog.IsEnabled(); @@ -335,7 +338,7 @@ void Overlay::DrawToolbar() ImGui::SameLine(); ImGui::PushStyleColor(ImGuiCol_Button, persistentState.ImGuiDebugToggled ? ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive) : ImGui::GetStyleColorVec4(ImGuiCol_Button)); - if (ImGui::Button("ImGui Debug", ImVec2(itemWidth, 0))) + if (ImGui::Button(ICON_MD_BUG " ImGui Debug", ImVec2(itemWidth, 0))) m_imguiDebug.Toggle(); if (!m_toggled) persistentState.ImGuiDebugToggled = m_imguiDebug.IsEnabled(); @@ -343,6 +346,6 @@ void Overlay::DrawToolbar() ImGui::SameLine(); - if (ImGui::Button("Reload all mods", ImVec2(itemWidth, 0))) + if (ImGui::Button(ICON_MD_RESTART " Reload all mods", ImVec2(itemWidth, 0))) m_vm.ReloadAllMods(); } diff --git a/src/overlay/widgets/Bindings.cpp b/src/overlay/widgets/Bindings.cpp index d6ba703a..b34f165d 100644 --- a/src/overlay/widgets/Bindings.cpp +++ b/src/overlay/widgets/Bindings.cpp @@ -24,7 +24,7 @@ bool VKBindInfo::operator==(const std::string& id) const } Bindings::Bindings(VKBindings& aBindings, LuaVM& aVm) - : Widget("Bindings") + : Widget(ICON_MD_KEYBOARD_SETTINGS " Bindings") , m_bindings(aBindings) , m_vm(aVm) { diff --git a/src/overlay/widgets/Console.cpp b/src/overlay/widgets/Console.cpp index ca61fe58..6131fe80 100644 --- a/src/overlay/widgets/Console.cpp +++ b/src/overlay/widgets/Console.cpp @@ -2,11 +2,12 @@ #include "Console.h" +#include #include #include Console::Console(Options& aOptions, PersistentState& aPersistentState, LuaVM& aVm) - : Widget("Console") + : Widget(ICON_MD_CONSOLE " Console") , m_options(aOptions) , m_persistentState(aPersistentState) , m_vm(aVm) @@ -90,7 +91,10 @@ void Console::OnUpdate() ImGui::SetNextItemWidth(-FLT_MIN); constexpr auto flags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AllowTabInput | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackResize; + ImGui::PushFont(CET::Get().GetFonts().MonoFont); + CET::Get().GetFonts().GetGlyphRangesBuilder().AddText(m_command); // Add text to glyph ranges const auto execute = ImGui::InputText("##InputCommand", m_command.data(), m_command.capacity(), flags, &HandleConsole, this); + ImGui::PopFont(); ImGui::SetItemDefaultFocus(); if (execute) { diff --git a/src/overlay/widgets/GameLog.cpp b/src/overlay/widgets/GameLog.cpp index 98e1a2a7..64961059 100644 --- a/src/overlay/widgets/GameLog.cpp +++ b/src/overlay/widgets/GameLog.cpp @@ -3,7 +3,7 @@ #include "GameLog.h" GameLog::GameLog() - : Widget("Game Log") + : Widget(ICON_MD_FILE_DOCUMENT " Game Log") , m_logWindow("gamelog") { } diff --git a/src/overlay/widgets/ImGuiDebug.cpp b/src/overlay/widgets/ImGuiDebug.cpp index a1ad5652..d038dea9 100644 --- a/src/overlay/widgets/ImGuiDebug.cpp +++ b/src/overlay/widgets/ImGuiDebug.cpp @@ -3,7 +3,7 @@ #include "ImGuiDebug.h" ImGuiDebug::ImGuiDebug() - : Widget("ImGui Debug", true) + : Widget(ICON_MD_BUG " ImGui Debug", true) { } diff --git a/src/overlay/widgets/LogWindow.cpp b/src/overlay/widgets/LogWindow.cpp index 08cc098f..f3c0cafa 100644 --- a/src/overlay/widgets/LogWindow.cpp +++ b/src/overlay/widgets/LogWindow.cpp @@ -2,6 +2,7 @@ #include "LogWindow.h" +#include #include LogWindow::LogWindow(const std::string& acpLoggerName) @@ -32,6 +33,7 @@ void LogWindow::Draw(const ImVec2& size) if (ImGui::BeginChildFrame(frameId, size, ImGuiWindowFlags_HorizontalScrollbar)) { std::lock_guard _{m_lock}; + ImGui::PushFont(CET::Get().GetFonts().MonoFont); if (!m_lines.empty() && (m_normalizedWidth < 0.0f || m_nextIndexToCheck < m_lines.size())) { @@ -76,6 +78,8 @@ void LogWindow::Draw(const ImVec2& size) ImGui::SetNextItemWidth(listItemWidth); ImGui::PushID(i); + + CET::Get().GetFonts().GetGlyphRangesBuilder().AddText(item); // Add text to glyph ranges ImGui::InputText(("##" + item).c_str(), item.data(), item.size(), ImGuiInputTextFlags_ReadOnly); ImGui::PopID(); @@ -93,6 +97,7 @@ void LogWindow::Draw(const ImVec2& size) } m_scroll = false; } + ImGui::PopFont(); } ImGui::EndChildFrame(); } diff --git a/src/overlay/widgets/Settings.cpp b/src/overlay/widgets/Settings.cpp index af54fb30..4685c10c 100644 --- a/src/overlay/widgets/Settings.cpp +++ b/src/overlay/widgets/Settings.cpp @@ -7,7 +7,7 @@ #include Settings::Settings(Options& aOptions, LuaVM& aVm) - : Widget("Settings") + : Widget(ICON_MD_COG " Settings") , m_options(aOptions) , m_vm(aVm) { @@ -52,60 +52,92 @@ void Settings::OnUpdate() if (ImGui::BeginChild(ImGui::GetID("Settings"), frameSize)) { m_madeChanges = false; + m_madeFontChanges = false; if (ImGui::CollapsingHeader("Patches", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::TreePush(); - if (ImGui::BeginTable("##SETTINGS_PATCHES", 2, ImGuiTableFlags_Sortable | ImGuiTableFlags_SizingStretchSame, ImVec2(-ImGui::GetStyle().IndentSpacing, 0))) + if (ImGui::BeginTable("SETTINGS", 2, ImGuiTableFlags_NoSavedSettings, ImVec2(-ImGui::GetStyle().IndentSpacing, 0))) { const auto& patchesSettings = m_options.Patches; - UpdateAndDrawSetting( - "Disable Async Compute", - "Disables async compute, this can give a boost on older GPUs like Nvidia 10xx series for example " - "(requires restart to take effect).", - m_patches.AsyncCompute, patchesSettings.AsyncCompute); - UpdateAndDrawSetting( - "Disable Anti-aliasing", "Completely disables anti-aliasing (requires restart to take effect).", m_patches.Antialiasing, patchesSettings.Antialiasing); - UpdateAndDrawSetting( - "Skip Start Menu", - "Skips the 'Breaching...' menu asking you to press space bar to continue (requires restart to take " - "effect).", - m_patches.SkipStartMenu, patchesSettings.SkipStartMenu); - UpdateAndDrawSetting( - "Suppress Intro Movies", "Disables logos played at the beginning (requires restart to take effect).", m_patches.DisableIntroMovies, + SettingItemCheckBox( + "🐌", "Disable Async Compute", + "Disables async compute, this can give a boost on older GPUs like Nvidia 10xx series for example (requires restart to take effect).", m_patches.AsyncCompute, + patchesSettings.AsyncCompute); + SettingItemCheckBox( + "🤮", "Disable Anti-aliasing", "Completely disables anti-aliasing (requires restart to take effect).", m_patches.Antialiasing, patchesSettings.Antialiasing); + SettingItemCheckBox( + "🏄", "Skip Start Menu", "Skips the 'Breaching...' menu asking you to press space bar to continue (requires restart to take effect).", m_patches.SkipStartMenu, + patchesSettings.SkipStartMenu); + SettingItemCheckBox( + "🎞", "Suppress Intro Movies", "Disables logos played at the beginning (requires restart to take effect).", m_patches.DisableIntroMovies, patchesSettings.DisableIntroMovies); - UpdateAndDrawSetting( - "Disable Vignette", "Disables vignetting along screen borders (requires restart to take effect).", m_patches.DisableVignette, patchesSettings.DisableVignette); - UpdateAndDrawSetting( - "Disable Boundary Teleport", "Allows players to access out-of-bounds locations (requires restart to take effect).", m_patches.DisableBoundaryTeleport, + SettingItemCheckBox( + "🔦", "Disable Vignette", "Disables vignetting along screen borders (requires restart to take effect).", m_patches.DisableVignette, + patchesSettings.DisableVignette); + SettingItemCheckBox( + "🗺", "Disable Boundary Teleport", "Allows players to access out-of-bounds locations (requires restart to take effect).", m_patches.DisableBoundaryTeleport, patchesSettings.DisableBoundaryTeleport); - UpdateAndDrawSetting("Disable V-Sync (Windows 7 only)", " (requires restart to take effect).", m_patches.DisableWin7Vsync, patchesSettings.DisableWin7Vsync); - UpdateAndDrawSetting( - "Fix Minimap Flicker", "Disables VSync on Windows 7 to bypass the 60 FPS limit (requires restart to take effect).", m_patches.MinimapFlicker, + SettingItemCheckBox("💨", "Disable V-Sync (Windows 7 only)", " (requires restart to take effect).", m_patches.DisableWin7Vsync, patchesSettings.DisableWin7Vsync); + SettingItemCheckBox( + "✨", "Fix Minimap Flicker", "Disables VSync on Windows 7 to bypass the 60 FPS limit (requires restart to take effect).", m_patches.MinimapFlicker, patchesSettings.MinimapFlicker); ImGui::EndTable(); } ImGui::TreePop(); } + if (ImGui::CollapsingHeader("CET Font Settings", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::TreePush(); + if (ImGui::BeginTable("SETTINGS", 2, ImGuiTableFlags_NoSavedSettings, ImVec2(-ImGui::GetStyle().IndentSpacing, 0))) + { + const auto& fontSettings = m_options.Font; + m_madeFontChanges |= + SettingItemFontCombo("🦄", "Main Font", "Main display font for CET.", m_font.MainFont, fontSettings.MainFont, CET::Get().GetFonts().GetSystemFonts()); + m_madeFontChanges |= SettingItemFontCombo( + "🪲", "Monospaced Font", "Monospaceed font, which is used for displaying texts in Console and Game Log, for CET.", m_font.MonoFont, + fontSettings.MonoFont, CET::Get().GetFonts().GetSystemFonts()); + m_madeFontChanges |= SettingItemSliderFloat( + "📏", "Font Size", "Changees the size of the font, default value is 18px.", m_font.BaseSize, fontSettings.BaseSize, 10.0f, 72.0f, "%.0fpx"); + + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + static bool openFontAdvSettings = false; + ImGui::Selectable("Advance Settings", false, ImGuiSelectableFlags_SpanAllColumns); + if (ImGui::IsItemClicked()) + openFontAdvSettings = !openFontAdvSettings; + if (openFontAdvSettings) + { + ImGui::Indent(ImGui::GetFrameHeight()); + m_madeFontChanges |= SettingItemSliderInt( + "↔", "Oversample Horizontal", "Oversamples font horizontally, default value is 3x. (May increase font clearity, at the cost of increasing memory usage.)", + m_font.OversampleHorizontal, fontSettings.OversampleHorizontal, 1, 10, "%dx"); + m_madeFontChanges |= SettingItemSliderInt( + "↕", "Oversample Vertical", "Oversamples font vertically, default value is 1x. (May increase font clearity, at the cost of increasing memory usage.)", + m_font.OversampleVertical, fontSettings.OversampleVertical, 1, 10, "%dx"); + ImGui::Unindent(ImGui::GetFrameHeight()); + } + + ImGui::EndTable(); + } + ImGui::TreePop(); + } if (ImGui::CollapsingHeader("CET Development Settings", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::TreePush(); - if (ImGui::BeginTable("##SETTINGS_DEV", 2, ImGuiTableFlags_Sortable | ImGuiTableFlags_SizingStretchSame, ImVec2(-ImGui::GetStyle().IndentSpacing, 0))) + if (ImGui::BeginTable("SETTINGS", 2, ImGuiTableFlags_NoSavedSettings, ImVec2(-ImGui::GetStyle().IndentSpacing, 0))) { const auto& developerSettings = m_options.Developer; - UpdateAndDrawSetting( - "Remove Dead Bindings", - "Removes all bindings which are no longer valid (disabling this could be useful when debugging mod " - "issues).", + SettingItemCheckBox( + "🗑", "Remove Dead Bindings", "Removes all bindings which are no longer valid (disabling this could be useful when debugging mod issues).", m_developer.RemoveDeadBindings, developerSettings.RemoveDeadBindings); - UpdateAndDrawSetting( - "Enable ImGui Assertions", - "Enables all ImGui assertions, assertions will get logged into log file of whoever triggered the " - "assertion (useful when debugging ImGui issues, should also be used to check mods before " - "shipping!).", + SettingItemCheckBox( + "💣", "Enable ImGui Assertions", + "Enables all ImGui assertions, assertions will get logged into log file of whoever triggered the assertion (useful when debugging ImGui issues, should also be " + "used to check mods before shipping!).", m_developer.EnableImGuiAssertions, developerSettings.EnableImGuiAssertions); - UpdateAndDrawSetting( - "Dump Game Options", "Dumps all game options into main log file (requires restart to take effect).", m_developer.DumpGameOptions, + SettingItemCheckBox( + "🖨", "Dump Game Options", "Dumps all game options into main log file (requires restart to take effect).", m_developer.DumpGameOptions, developerSettings.DumpGameOptions); ImGui::EndTable(); @@ -134,12 +166,16 @@ void Settings::Load() m_patches = m_options.Patches; m_developer = m_options.Developer; + m_font = m_options.Font; } void Settings::Save() const { m_options.Patches = m_patches; m_options.Developer = m_developer; + m_options.Font = m_font; + if (m_madeFontChanges) + CET::Get().GetFonts().RebuildFontNextFrame(); m_options.Save(); } @@ -150,15 +186,17 @@ void Settings::ResetToDefaults() m_patches = m_options.Patches; m_developer = m_options.Developer; + m_font = m_options.Font; + CET::Get().GetFonts().RebuildFontNextFrame(); } -void Settings::UpdateAndDrawSetting(const std::string& acLabel, const std::string& acTooltip, bool& aCurrent, const bool& acSaved) +void Settings::SettingItemTemplate(const std::string& acIcon, const std::string& acLabel, const std::string& acTooltip, const bool& aValueChanged, std::function& aImGuiFunction) { ImGui::TableNextRow(); - ImGui::TableNextColumn(); + ImGui::TableSetColumnIndex(0); ImVec4 curTextColor = ImGui::GetStyleColorVec4(ImGuiCol_Text); - if (aCurrent != acSaved) + if (aValueChanged) curTextColor = ImVec4(1.0f, 1.0f, 0.0f, 1.0f); ImGui::AlignTextToFramePadding(); @@ -166,20 +204,116 @@ void Settings::UpdateAndDrawSetting(const std::string& acLabel, const std::strin ImGui::PushStyleColor(ImGuiCol_Text, curTextColor); ImGui::PushID(&acLabel); + if (CET::Get().GetFonts().UseEmojiFont() && !acIcon.empty()) + { + CET::Get().GetFonts().GetGlyphRangesBuilder().AddText(acIcon); + ImGui::TextUnformatted(acIcon.c_str()); + ImGui::SameLine(); + } ImGui::TextUnformatted(acLabel.c_str()); ImGui::PopID(); if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && !acTooltip.empty()) ImGui::SetTooltip("%s", acTooltip.c_str()); - ImGui::TableNextColumn(); + ImGui::TableSetColumnIndex(1); + + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x / 4); + ImGui::SetNextItemWidth(-FLT_MIN); + + aImGuiFunction(); - ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (ImGui::GetContentRegionAvail().x - ImGui::GetFrameHeight()) / 2); - ImGui::Checkbox(("##" + acLabel).c_str(), &aCurrent); if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) ImGui::SetTooltip("%s", acTooltip.c_str()); ImGui::PopStyleColor(); +} + +bool Settings::SettingItemCheckBox(const std::string& acIcon, const std::string& acLabel, const std::string& acTooltip, bool& aCurrent, const bool& acSaved) +{ + std::function imguiWidget = [&]() + { + // Right align checkbox + if (ImGui::BeginTable("CheckboxItem", 2, ImGuiTableFlags_NoSavedSettings)) + { + ImGui::TableSetupColumn("Col1", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("Col2", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(1); + + ImGui::Checkbox(("##" + acLabel).c_str(), &aCurrent); + + ImGui::EndTable(); + } + }; + + const bool valueChanged = aCurrent != acSaved; + + SettingItemTemplate(acIcon, acLabel, acTooltip, valueChanged, imguiWidget); + + m_madeChanges |= aCurrent != acSaved; + + return aCurrent != acSaved; +} + +bool Settings::SettingItemSliderFloat( + const std::string& acIcon, const std::string& acLabel, const std::string& acTooltip, float& aCurrent, const float& acSaved, float aValueMin, float aValueMax, const char* aFormat) +{ + std::function imguiWidget = [&]() + { + ImGui::SliderFloat(("##" + acLabel).c_str(), &aCurrent, aValueMin, aValueMax, aFormat); + }; + + const bool valueChanged = aCurrent != acSaved; + + SettingItemTemplate(acIcon, acLabel, acTooltip, valueChanged, imguiWidget); m_madeChanges |= aCurrent != acSaved; + + return aCurrent != acSaved; } + +bool Settings::SettingItemSliderInt( + const std::string& acIcon, const std::string& acLabel, const std::string& acTooltip, int& aCurrent, const int& acSaved, int aValueMin, int aValueMax, const char* aFormat) +{ + std::function imguiWidget = [&]() + { + ImGui::SliderInt(("##" + acLabel).c_str(), &aCurrent, aValueMin, aValueMax, aFormat); + }; + + const bool valueChanged = aCurrent != acSaved; + + SettingItemTemplate(acIcon, acLabel, acTooltip, valueChanged, imguiWidget); + + m_madeChanges |= aCurrent != acSaved; + + return aCurrent != acSaved; +} + +bool Settings::SettingItemFontCombo( + const std::string& acIcon, const std::string& acLabel, const std::string& acTooltip, std::string& aCurrent, const std::string& acSaved, const std::vector& acFonts) +{ + std::function imguiWidget = [&]() + { + if (ImGui::BeginCombo(("##" + acLabel).c_str(), aCurrent.c_str())) + { + for (const auto& font : acFonts) + { + const bool isSelected = aCurrent == font.GetName(); + if (ImGui::Selectable(font.GetName().c_str(), isSelected)) + aCurrent = font.GetName(); + if (isSelected) + ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); + } + }; + + const bool valueChanged = aCurrent != acSaved; + + SettingItemTemplate(acIcon, acLabel, acTooltip, valueChanged, imguiWidget); + + m_madeChanges |= aCurrent != acSaved; + + return aCurrent != acSaved; +} \ No newline at end of file diff --git a/src/overlay/widgets/Settings.h b/src/overlay/widgets/Settings.h index 0ef4c415..3b7e93cd 100644 --- a/src/overlay/widgets/Settings.h +++ b/src/overlay/widgets/Settings.h @@ -21,15 +21,25 @@ struct Settings : Widget WidgetResult OnPopup() override; private: - void UpdateAndDrawSetting(const std::string& acLabel, const std::string& acTooltip, bool& aCurrent, const bool& acSaved); + void SettingItemTemplate(const std::string& acIcon, const std::string& acLabel, const std::string& acTooltip, const bool& aValueChanged, std::function& aImGuiFunction); + bool SettingItemCheckBox(const std::string& acIcon, const std::string& acLabel, const std::string& acTooltip, bool& aCurrent, const bool& acSaved); + bool SettingItemSliderFloat( + const std::string& acIcon, const std::string& acLabel, const std::string& acTooltip, float& aCurrent, const float& acSaved, float aValueMin, float aValueMax, + const char* aFormat = "%.1f"); + bool SettingItemSliderInt( + const std::string& acIcon, const std::string& acLabel, const std::string& acTooltip, int& aCurrent, const int& acSaved, int aValueMin, int aValueMax, const char* aFormat = "%d"); + bool SettingItemFontCombo( + const std::string& acIcon, const std::string& acLabel, const std::string& acTooltip, std::string& aCurrent, const std::string& acSaved, const std::vector& acFonts); PatchesSettings m_patches; DeveloperSettings m_developer; + FontSettings m_font; Options& m_options; LuaVM& m_vm; TChangedCBResult m_popupResult{TChangedCBResult::APPLY}; bool m_madeChanges{false}; + bool m_madeFontChanges{false}; bool m_openChangesModal{true}; }; diff --git a/src/overlay/widgets/TweakDBEditor.cpp b/src/overlay/widgets/TweakDBEditor.cpp index 5c45ff82..2932961d 100644 --- a/src/overlay/widgets/TweakDBEditor.cpp +++ b/src/overlay/widgets/TweakDBEditor.cpp @@ -123,7 +123,7 @@ bool StringContains(const std::string_view& acString, const std::string_view& ac } TweakDBEditor::TweakDBEditor(LuaVM& aVm) - : Widget("TweakDB Editor") + : Widget(ICON_MD_DATABASE_EDIT " TweakDB Editor") , m_vm(aVm) { } diff --git a/src/scripting/LuaSandbox.cpp b/src/scripting/LuaSandbox.cpp index 36cd831c..b3489eb5 100644 --- a/src/scripting/LuaSandbox.cpp +++ b/src/scripting/LuaSandbox.cpp @@ -46,6 +46,7 @@ static constexpr const char* s_cGlobalObjectsWhitelist[] = { "print", "GetVersion", "GetDisplayResolution", + "AddTextGlyphs", "ModArchiveExists", "ImGuiListClipper", @@ -110,9 +111,10 @@ static constexpr const char* s_cGlobalExtraLibsWhitelist[] = { "ImGui", }; -LuaSandbox::LuaSandbox(Scripting* apScripting, const VKBindings& acVKBindings) +LuaSandbox::LuaSandbox(Scripting* apScripting, const VKBindings& acVKBindings, Fonts& aFonts) : m_pScripting(apScripting) , m_vkBindings(acVKBindings) + , m_fonts(aFonts) { } @@ -532,9 +534,13 @@ void LuaSandbox::InitializeIOForSandbox(Sandbox& aSandbox, const sol::state& acp const auto previousCurrentPath = std::filesystem::current_path(); current_path(cSBRootPath); - const auto path = GetLuaPath(acPath, cSBRootPath, false); + auto path = GetLuaPath(acPath, cSBRootPath, false); + path = path.empty() || acPath == "db.sqlite3" ? "" : path; + + // add the file content to the glyph range builder. + m_fonts.GetGlyphRangesBuilder().AddFile(path); - auto result = cIO["lines"](path.empty() || acPath == "db.sqlite3" ? "" : UTF16ToUTF8(path.native())); + auto result = cIO["lines"](UTF16ToUTF8(path.native())); current_path(previousCurrentPath); @@ -545,9 +551,18 @@ void LuaSandbox::InitializeIOForSandbox(Sandbox& aSandbox, const sol::state& acp const auto previousCurrentPath = std::filesystem::current_path(); current_path(cSBRootPath); - const auto path = GetLuaPath(acPath, cSBRootPath, true); + auto path = GetLuaPath(acPath, cSBRootPath, true); + path = path.empty() || acPath == "db.sqlite3" ? "" : path; + + // add the file content to the glyph range builder, only in modes allow read permissions. and exclude file types not in the list + if (acMode != "w" || acMode != "a") + { + const std::vector extensionFilter = {".lua", ".txt", ".json", ".yml", ".yaml", ".toml", ".ini"}; + if (std::find(extensionFilter.begin(), extensionFilter.end(), UTF16ToUTF8(path.extension().native())) != extensionFilter.end()) + m_fonts.GetGlyphRangesBuilder().AddFile(path); + } - auto result = cIO["open"](path.empty() || acPath == "db.sqlite3" ? "" : UTF16ToUTF8(path.native()), acMode); + auto result = cIO["open"](UTF16ToUTF8(path.native()), acMode); current_path(previousCurrentPath); diff --git a/src/scripting/LuaSandbox.h b/src/scripting/LuaSandbox.h index 22dfb2cf..e34034bf 100644 --- a/src/scripting/LuaSandbox.h +++ b/src/scripting/LuaSandbox.h @@ -4,7 +4,7 @@ struct LuaSandbox { - LuaSandbox(Scripting* apScripting, const VKBindings& acVKBindings); + LuaSandbox(Scripting* apScripting, const VKBindings& acVKBindings, Fonts& aFonts); ~LuaSandbox() = default; void Initialize(); @@ -42,6 +42,7 @@ struct LuaSandbox void CloseDBForSandbox(const Sandbox& aSandbox) const; + Fonts& m_fonts; Scripting* m_pScripting; const VKBindings& m_vkBindings; sol::table m_globals{}; diff --git a/src/scripting/LuaVM.h b/src/scripting/LuaVM.h index c0881ac6..d42f5658 100644 --- a/src/scripting/LuaVM.h +++ b/src/scripting/LuaVM.h @@ -25,7 +25,7 @@ struct TDBIDLookupEntry struct Image; struct LuaVM { - LuaVM(const Paths& aPaths, VKBindings& aBindings, D3D12& aD3D12); + LuaVM(const Paths& aPaths, VKBindings& aBindings, D3D12& aD3D12, Fonts& aFonts); ~LuaVM() = default; [[nodiscard]] const VKBind* GetBind(const VKModBind& acModBind) const; diff --git a/src/scripting/LuaVM_Hooks.cpp b/src/scripting/LuaVM_Hooks.cpp index 088dd305..a44e82fd 100644 --- a/src/scripting/LuaVM_Hooks.cpp +++ b/src/scripting/LuaVM_Hooks.cpp @@ -258,8 +258,8 @@ void LuaVM::HookLogChannel(RED4ext::IScriptable*, RED4ext::CStackFrame* apStack, } } -LuaVM::LuaVM(const Paths& aPaths, VKBindings& aBindings, D3D12& aD3D12) - : m_scripting(aPaths, aBindings, aD3D12) +LuaVM::LuaVM(const Paths& aPaths, VKBindings& aBindings, D3D12& aD3D12, Fonts& aFonts) + : m_scripting(aPaths, aBindings, aD3D12, aFonts) , m_d3d12(aD3D12) { Hook(); diff --git a/src/scripting/Scripting.cpp b/src/scripting/Scripting.cpp index 1433088d..bd6662d4 100644 --- a/src/scripting/Scripting.cpp +++ b/src/scripting/Scripting.cpp @@ -32,12 +32,13 @@ static constexpr bool s_cThrowLuaErrors = true; static RTTILocator s_stringType{RED4ext::FNV1a64("String")}; static RTTILocator s_resRefType{RED4ext::FNV1a64("redResourceReferenceScriptToken")}; -Scripting::Scripting(const Paths& aPaths, VKBindings& aBindings, D3D12& aD3D12) - : m_sandbox(this, aBindings) +Scripting::Scripting(const Paths& aPaths, VKBindings& aBindings, D3D12& aD3D12, Fonts& aFonts) + : m_sandbox(this, aBindings, aFonts) , m_mapper(m_lua.AsRef(), m_sandbox) , m_store(m_sandbox, aPaths, aBindings) , m_override(this) , m_paths(aPaths) + , m_fonts(aFonts) , m_d3d12(aD3D12) { CreateLogger(aPaths.CETRoot() / "scripting.log", "scripting"); @@ -49,6 +50,9 @@ void Scripting::Initialize() auto lua = m_lua.Lock(); auto& luaVm = lua.Get(); + // putting it here so it can be called from IconGlyphs/icons.lua + luaVm.set_function("AddTextGlyphs", [this](const std::string& acString) -> void { m_fonts.GetGlyphRangesBuilder().AddText(acString); }); + luaVm.open_libraries(sol::lib::base, sol::lib::string, sol::lib::io, sol::lib::math, sol::lib::package, sol::lib::os, sol::lib::table, sol::lib::bit32); luaVm.require("sqlite3", luaopen_lsqlite3); @@ -72,6 +76,12 @@ void Scripting::Initialize() sol_ImGui::InitBindings(luaVm, globals); sol::table imgui = globals["ImGui"]; Texture::BindTexture(imgui); + + imgui["GetMonoFont"] = [this]() -> ImFont* + { + return m_fonts.MonoFont; + }; + for (auto [key, value] : imgui) { if (value.get_type() != sol::type::function) @@ -128,6 +138,11 @@ void Scripting::Initialize() return {static_cast(resolution.cx), static_cast(resolution.cy)}; }; + globals["AddTextGlyphs"] = [this](const std::string& acString) -> void + { + m_fonts.GetGlyphRangesBuilder().AddText(acString); + }; + globals["ModArchiveExists"] = [this](const std::string& acArchiveName) -> bool { const auto resourceDepot = RED4ext::ResourceDepot::Get(); @@ -609,6 +624,7 @@ void Scripting::UnloadAllMods() void Scripting::ReloadAllMods() { UnloadAllMods(); + CET::Get().GetFonts().PrecacheGlyphsFromMods(); // recache glyphs from mods in case of changes m_store.LoadAll(); diff --git a/src/scripting/Scripting.h b/src/scripting/Scripting.h index 23938306..e52cc290 100644 --- a/src/scripting/Scripting.h +++ b/src/scripting/Scripting.h @@ -11,7 +11,7 @@ struct Scripting { using LockedState = TiltedPhoques::Locked; - Scripting(const Paths& aPaths, VKBindings& aBindings, D3D12& aD3D12); + Scripting(const Paths& aPaths, VKBindings& aBindings, D3D12& aD3D12, Fonts& aFonts); ~Scripting() = default; void Initialize(); @@ -61,5 +61,6 @@ struct Scripting ScriptStore m_store; FunctionOverride m_override; const Paths& m_paths; + Fonts& m_fonts; D3D12& m_d3d12; }; diff --git a/src/sol_imgui/sol_imgui.h b/src/sol_imgui/sol_imgui.h index 66e4dd01..bf9ef214 100644 --- a/src/sol_imgui/sol_imgui.h +++ b/src/sol_imgui/sol_imgui.h @@ -1466,42 +1466,56 @@ inline void VSliderScalar() // Widgets: Input with Keyboard inline std::tuple InputText(const std::string& label, std::string text, unsigned int buf_size) { + CET::Get().GetFonts().GetGlyphRangesBuilder().AddText(text); // Add text to glyph ranges + text.resize(buf_size); bool selected = ImGui::InputText(label.c_str(), text.data(), buf_size); return std::make_tuple(text.c_str(), selected); } inline std::tuple InputText(const std::string& label, std::string text, unsigned int buf_size, int flags) { + CET::Get().GetFonts().GetGlyphRangesBuilder().AddText(text); // Add text to glyph ranges + text.resize(buf_size); bool selected = ImGui::InputText(label.c_str(), text.data(), buf_size, flags); return std::make_tuple(text.c_str(), selected); } inline std::tuple InputTextMultiline(const std::string& label, std::string text, unsigned int buf_size) { + CET::Get().GetFonts().GetGlyphRangesBuilder().AddText(text); // Add text to glyph ranges + text.resize(buf_size); bool selected = ImGui::InputTextMultiline(label.c_str(), text.data(), buf_size); return std::make_tuple(text.c_str(), selected); } inline std::tuple InputTextMultiline(const std::string& label, std::string text, unsigned int buf_size, float sizeX, float sizeY) { + CET::Get().GetFonts().GetGlyphRangesBuilder().AddText(text); // Add text to glyph ranges + text.resize(buf_size); bool selected = ImGui::InputTextMultiline(label.c_str(), text.data(), buf_size, {sizeX, sizeY}); return std::make_tuple(text.c_str(), selected); } inline std::tuple InputTextMultiline(const std::string& label, std::string text, unsigned int buf_size, float sizeX, float sizeY, int flags) { + CET::Get().GetFonts().GetGlyphRangesBuilder().AddText(text); // Add text to glyph ranges + text.resize(buf_size); bool selected = ImGui::InputTextMultiline(label.c_str(), text.data(), buf_size, {sizeX, sizeY}, flags); return std::make_tuple(text.c_str(), selected); } inline std::tuple InputTextWithHint(const std::string& label, const std::string& hint, std::string text, unsigned int buf_size) { + CET::Get().GetFonts().GetGlyphRangesBuilder().AddText(text); // Add text to glyph ranges + text.resize(buf_size); bool selected = ImGui::InputTextWithHint(label.c_str(), hint.c_str(), text.data(), buf_size); return std::make_tuple(text.c_str(), selected); } inline std::tuple InputTextWithHint(const std::string& label, const std::string& hint, std::string text, unsigned int buf_size, int flags) { + CET::Get().GetFonts().GetGlyphRangesBuilder().AddText(text); // Add text to glyph ranges + text.resize(buf_size); bool selected = ImGui::InputTextWithHint(label.c_str(), hint.c_str(), text.data(), buf_size, flags); return std::make_tuple(text.c_str(), selected); diff --git a/src/stdafx.h b/src/stdafx.h index 82100359..ce4ea787 100644 --- a/src/stdafx.h +++ b/src/stdafx.h @@ -3,6 +3,8 @@ #include #include #include +#include +#include #include #include #include @@ -44,6 +46,7 @@ #include #include #include +#include #include #include @@ -69,6 +72,7 @@ #include "common/FontMaterialDesignIcons.h" #include "Options.h" #include "Paths.h" +#include "Fonts.h" #include "PersistentState.h" #include "reverse/Addresses.h" #include "scripting/GameHooks.h" diff --git a/vendor/imgui b/vendor/imgui new file mode 160000 index 00000000..c1c910fa --- /dev/null +++ b/vendor/imgui @@ -0,0 +1 @@ +Subproject commit c1c910fab8bf655d9bce6743e17c701c5567ff76 diff --git a/xmake.lua b/xmake.lua index d4ff100a..b28749e1 100644 --- a/xmake.lua +++ b/xmake.lua @@ -66,14 +66,14 @@ target("RED4ext.SDK") on_install(function() end) target("cyber_engine_tweaks") - add_defines("WIN32_LEAN_AND_MEAN", "NOMINMAX", "WINVER=0x0601", "SOL_ALL_SAFETIES_ON", "SOL_LUAJIT=1", "SOL_EXCEPTIONS_SAFE_PROPAGATION", "SPDLOG_WCHAR_TO_UTF8_SUPPORT", "SPDLOG_WCHAR_FILENAMES", "SPDLOG_WCHAR_SUPPORT", "IMGUI_USER_CONFIG=\""..imguiUserConfig.."\"") -- WINVER=0x0601 == Windows 7xmake + add_defines("WIN32_LEAN_AND_MEAN", "NOMINMAX", "WINVER=0x0601", "SOL_ALL_SAFETIES_ON", "SOL_LUAJIT=1", "SOL_EXCEPTIONS_SAFE_PROPAGATION", "SPDLOG_WCHAR_TO_UTF8_SUPPORT", "SPDLOG_WCHAR_FILENAMES", "SPDLOG_WCHAR_SUPPORT", "IMGUI_USER_CONFIG=\""..imguiUserConfig.."\"", "SOL_IMGUI_ENABLE_FONT_MANIPULATORS") -- WINVER=0x0601 == Windows 7xmake set_pcxxheader("src/stdafx.h") set_kind("shared") set_filename("cyber_engine_tweaks.asi") add_files("src/**.cpp") add_headerfiles("src/**.h", "build/CETVersion.h") add_includedirs("src/", "build/") - add_syslinks("User32", "Version", "d3d11") + add_syslinks("User32", "Version", "d3d11", "Dwrite") add_packages("spdlog", "nlohmann_json", "minhook", "hopscotch-map", "imgui", "mem", "sol2", "tiltedcore", "sqlite3", "openrestry-luajit", "xbyak", "stb") add_deps("RED4ext.SDK") add_configfiles("src/CETVersion.h.in") From cce36ac036b15a5f87506aa659ca82af2c00d81e Mon Sep 17 00:00:00 2001 From: Mingming Cui Date: Thu, 29 Jun 2023 06:58:07 +0800 Subject: [PATCH 2/7] update dx12 backend --- src/Fonts.cpp | 4 +- src/Fonts.h | 2 +- src/d3d12/D3D12_Functions.cpp | 6 +- src/imgui_impl/dx12.cpp | 505 +++++++++++++++++++--------------- src/imgui_impl/dx12.h | 34 ++- 5 files changed, 308 insertions(+), 243 deletions(-) diff --git a/src/Fonts.cpp b/src/Fonts.cpp index 8ef2fe04..f805074f 100644 --- a/src/Fonts.cpp +++ b/src/Fonts.cpp @@ -256,13 +256,13 @@ void Fonts::BuildFonts(const SIZE& acOutSize) // Rebuild font texture during runtime. // Call before ImGui_ImplXXXX_NewFrame() -void Fonts::RebuildFonts(ID3D12CommandQueue* apCommandQueue, const SIZE& acOutSize) +void Fonts::RebuildFonts(const SIZE& acOutSize) { if (m_rebuildFonts || m_glyphRangesBuilder.NeedsRebuild()) // Rebuild when font settings changed or glyph ranges changed { BuildFonts(acOutSize); - ImGui_ImplDX12_RecreateFontsTexture(apCommandQueue); + ImGui_ImplDX12_RecreateFontsTexture(); m_rebuildFonts = false; } diff --git a/src/Fonts.h b/src/Fonts.h index ce3a9cb3..a0370e18 100644 --- a/src/Fonts.h +++ b/src/Fonts.h @@ -32,7 +32,7 @@ struct Fonts ~Fonts() = default; void BuildFonts(const SIZE& acOutSize); - void RebuildFonts(ID3D12CommandQueue* apCommandQueue, const SIZE& acOutSize); + void RebuildFonts(const SIZE& acOutSize); void RebuildFontNextFrame(); const bool UseEmojiFont(); diff --git a/src/d3d12/D3D12_Functions.cpp b/src/d3d12/D3D12_Functions.cpp index dcc2e08e..13e39d65 100644 --- a/src/d3d12/D3D12_Functions.cpp +++ b/src/d3d12/D3D12_Functions.cpp @@ -324,7 +324,7 @@ bool D3D12::InitializeImGui(size_t aBuffersCounts) m_fonts.BuildFonts(m_outSize); - if (!ImGui_ImplDX12_CreateDeviceObjects(m_pCommandQueue.Get())) + if (!ImGui_ImplDX12_CreateDeviceObjects()) { Log::Error("D3D12::InitializeImGui() - ImGui_ImplDX12_CreateDeviceObjects call failed!"); ImGui_ImplDX12_Shutdown(); @@ -342,7 +342,7 @@ void D3D12::PrepareUpdate() std::lock_guard _(m_imguiLock); - m_fonts.RebuildFonts(m_pCommandQueue.Get(), m_outSize); + m_fonts.RebuildFonts(m_outSize); ImGui_ImplWin32_NewFrame(m_outSize); ImGui::NewFrame(); @@ -376,7 +376,7 @@ void D3D12::Update() // swap staging ImGui buffer with render ImGui buffer { std::lock_guard _(m_imguiLock); - ImGui_ImplDX12_NewFrame(m_pCommandQueue.Get()); + ImGui_ImplDX12_NewFrame(); if (m_imguiDrawDataBuffers[1].Valid) { std::swap(m_imguiDrawDataBuffers[0], m_imguiDrawDataBuffers[1]); diff --git a/src/imgui_impl/dx12.cpp b/src/imgui_impl/dx12.cpp index 33e4f09f..8017a5a8 100644 --- a/src/imgui_impl/dx12.cpp +++ b/src/imgui_impl/dx12.cpp @@ -2,91 +2,114 @@ // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: -// [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about -// ImTextureID! [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. +// [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. -// This define is set in the example .vcxproj file and need to be replicated in your app or by adding it to your -// imconfig.h file. - -// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// To build this on 32-bit systems: +// - [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in the 'example_win32_direct12/example_win32_direct12.vcxproj' project file) +// - [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like. +// - [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!) +// - [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in the example_win32_direct12/build_win32.bat file) + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Read online: https://github.com/ocornut/imgui/tree/master/docs // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer -// warning. 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID. -// 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() -// function. 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable -// ImGuiBackendFlags_RendererHasVtxOffset flag. 2019-04-30: DirectX12: Added support for special -// ImDrawCallback_ResetRenderState callback to reset render state. 2019-03-29: Misc: Various minor tidying up. -// 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using -// D3DCompile(). 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. +// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). +// 2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) +// 2021-02-18: DirectX12: Change blending equation to preserve alpha in output buffer. +// 2021-01-11: DirectX12: Improve Windows 7 compatibility (for D3D12On7) by loading d3d12.dll dynamically. +// 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer warning. +// 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID. +// 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function. +// 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. +// 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. +// 2019-03-29: Misc: Various minor tidying up. +// 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). +// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-06-12: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from NewFrame() to RenderDrawData(). // 2018-06-08: Misc: Extracted imgui_impl_dx12.cpp/.h away from the old combined DX12+Win32 example. -// 2018-06-08: DirectX12: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping -// rectangle (to ease support for future multi-viewport). 2018-02-22: Merged into master with all Win32 code -// synchronized to other examples. +// 2018-06-08: DirectX12: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle (to ease support for future multi-viewport). +// 2018-02-22: Merged into master with all Win32 code synchronized to other examples. #include #include "dx12.h" // DirectX +#include +#include +#include #ifdef _MSC_VER #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below. #endif // DirectX data -static ID3D12Device* g_pd3dDevice = NULL; -static ID3D12RootSignature* g_pRootSignature = NULL; -static ID3D12PipelineState* g_pPipelineState = NULL; -static DXGI_FORMAT g_RTVFormat = DXGI_FORMAT_UNKNOWN; -static ID3D12Resource* g_pFontTextureResource = NULL; -static D3D12_CPU_DESCRIPTOR_HANDLE g_hFontSrvCpuDescHandle = {}; -static D3D12_GPU_DESCRIPTOR_HANDLE g_hFontSrvGpuDescHandle = {}; - -struct FrameResources +struct ImGui_ImplDX12_RenderBuffers; +struct ImGui_ImplDX12_Data { - ID3D12Resource* IndexBuffer; - ID3D12Resource* VertexBuffer; - int IndexBufferSize; - int VertexBufferSize; + ID3D12Device* pd3dDevice; + ID3D12RootSignature* pRootSignature; + ID3D12PipelineState* pPipelineState; + DXGI_FORMAT RTVFormat; + ID3D12Resource* pFontTextureResource; + D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle; + D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle; + ID3D12DescriptorHeap* pd3dSrvDescHeap; + UINT numFramesInFlight; + + ImGui_ImplDX12_RenderBuffers* pFrameResources; + UINT frameIndex; + + ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); frameIndex = UINT_MAX; } }; -static FrameResources* g_pFrameResources = NULL; -static UINT g_numFramesInFlight = 0; -static UINT g_frameIndex = UINT_MAX; -template static void SafeRelease(T*& apRes) +// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts +// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. +static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData() { - if (apRes) - apRes->Release(); - apRes = NULL; + return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } -struct VERTEX_CONSTANT_BUFFER +// Buffers used during the rendering of a frame +struct ImGui_ImplDX12_RenderBuffers +{ + ID3D12Resource* IndexBuffer; + ID3D12Resource* VertexBuffer; + int IndexBufferSize; + int VertexBufferSize; +}; + +struct VERTEX_CONSTANT_BUFFER_DX12 { - float mvp[4][4]; + float mvp[4][4]; }; -static void ImGui_ImplDX12_SetupRenderState(ImDrawData* apDrawData, ID3D12GraphicsCommandList* apCommandLists, FrameResources* apFrameResource) +// Functions +static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx, ImGui_ImplDX12_RenderBuffers* fr) { + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + // Setup orthographic projection matrix into our constant buffer - // Our visible imgui space lies from draw_data->DisplayPos (top left) to - // draw_data->DisplayPos+data_data->DisplaySize (bottom right). - VERTEX_CONSTANT_BUFFER vertex_constant_buffer; + // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). + VERTEX_CONSTANT_BUFFER_DX12 vertex_constant_buffer; { - float L = apDrawData->DisplayPos.x; - float R = apDrawData->DisplayPos.x + apDrawData->DisplaySize.x; - float T = apDrawData->DisplayPos.y; - float B = apDrawData->DisplayPos.y + apDrawData->DisplaySize.y; - float mvp[4][4] = { - {2.0f / (R - L), 0.0f, 0.0f, 0.0f}, - {0.0f, 2.0f / (T - B), 0.0f, 0.0f}, - {0.0f, 0.0f, 0.5f, 0.0f}, - {(R + L) / (L - R), (T + B) / (B - T), 0.5f, 1.0f}, + float L = draw_data->DisplayPos.x; + float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; + float T = draw_data->DisplayPos.y; + float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; + float mvp[4][4] = + { + { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, + { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.5f, 0.0f }, + { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f }, }; memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp)); } @@ -94,55 +117,64 @@ static void ImGui_ImplDX12_SetupRenderState(ImDrawData* apDrawData, ID3D12Graphi // Setup viewport D3D12_VIEWPORT vp; memset(&vp, 0, sizeof(D3D12_VIEWPORT)); - vp.Width = apDrawData->DisplaySize.x; - vp.Height = apDrawData->DisplaySize.y; + vp.Width = draw_data->DisplaySize.x; + vp.Height = draw_data->DisplaySize.y; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = vp.TopLeftY = 0.0f; - apCommandLists->RSSetViewports(1, &vp); + ctx->RSSetViewports(1, &vp); // Bind shader and vertex buffers unsigned int stride = sizeof(ImDrawVert); unsigned int offset = 0; D3D12_VERTEX_BUFFER_VIEW vbv; memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW)); - vbv.BufferLocation = apFrameResource->VertexBuffer->GetGPUVirtualAddress() + offset; - vbv.SizeInBytes = apFrameResource->VertexBufferSize * stride; + vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset; + vbv.SizeInBytes = fr->VertexBufferSize * stride; vbv.StrideInBytes = stride; - apCommandLists->IASetVertexBuffers(0, 1, &vbv); + ctx->IASetVertexBuffers(0, 1, &vbv); D3D12_INDEX_BUFFER_VIEW ibv; memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW)); - ibv.BufferLocation = apFrameResource->IndexBuffer->GetGPUVirtualAddress(); - ibv.SizeInBytes = apFrameResource->IndexBufferSize * sizeof(ImDrawIdx); + ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress(); + ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx); ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT; - apCommandLists->IASetIndexBuffer(&ibv); - apCommandLists->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - apCommandLists->SetPipelineState(g_pPipelineState); - apCommandLists->SetGraphicsRootSignature(g_pRootSignature); - apCommandLists->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0); + ctx->IASetIndexBuffer(&ibv); + ctx->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + ctx->SetPipelineState(bd->pPipelineState); + ctx->SetGraphicsRootSignature(bd->pRootSignature); + ctx->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0); // Setup blend factor - const float blend_factor[4] = {0.f, 0.f, 0.f, 0.f}; - apCommandLists->OMSetBlendFactor(blend_factor); + const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; + ctx->OMSetBlendFactor(blend_factor); +} + +template +static inline void SafeRelease(T*& res) +{ + if (res) + res->Release(); + res = nullptr; } // Render function -void ImGui_ImplDX12_RenderDrawData(ImDrawData* apDrawData, ID3D12GraphicsCommandList* apCommandLists) +void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx) { // Avoid rendering when minimized - if (apDrawData->DisplaySize.x <= 0.0f || apDrawData->DisplaySize.y <= 0.0f) + if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) return; // FIXME: I'm assuming that this only gets called once per frame! // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator. - g_frameIndex = g_frameIndex + 1; - FrameResources* fr = &g_pFrameResources[g_frameIndex % g_numFramesInFlight]; + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + bd->frameIndex = bd->frameIndex + 1; + ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight]; // Create and grow vertex/index buffers if needed - if (fr->VertexBuffer == NULL || fr->VertexBufferSize < apDrawData->TotalVtxCount) + if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount) { SafeRelease(fr->VertexBuffer); - fr->VertexBufferSize = apDrawData->TotalVtxCount + 5000; + fr->VertexBufferSize = draw_data->TotalVtxCount + 5000; D3D12_HEAP_PROPERTIES props; memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); props.Type = D3D12_HEAP_TYPE_UPLOAD; @@ -159,13 +191,13 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* apDrawData, ID3D12GraphicsCommand desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; desc.Flags = D3D12_RESOURCE_FLAG_NONE; - if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&fr->VertexBuffer)) < 0) + if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->VertexBuffer)) < 0) return; } - if (fr->IndexBuffer == NULL || fr->IndexBufferSize < apDrawData->TotalIdxCount) + if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount) { SafeRelease(fr->IndexBuffer); - fr->IndexBufferSize = apDrawData->TotalIdxCount + 10000; + fr->IndexBufferSize = draw_data->TotalIdxCount + 10000; D3D12_HEAP_PROPERTIES props; memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); props.Type = D3D12_HEAP_TYPE_UPLOAD; @@ -182,12 +214,12 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* apDrawData, ID3D12GraphicsCommand desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; desc.Flags = D3D12_RESOURCE_FLAG_NONE; - if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&fr->IndexBuffer)) < 0) + if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->IndexBuffer)) < 0) return; } // Upload vertex/index data into a single contiguous GPU buffer - void *vtx_resource, *idx_resource; + void* vtx_resource, *idx_resource; D3D12_RANGE range; memset(&range, 0, sizeof(D3D12_RANGE)); if (fr->VertexBuffer->Map(0, &range, &vtx_resource) != S_OK) @@ -196,9 +228,9 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* apDrawData, ID3D12GraphicsCommand return; ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource; ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource; - for (int n = 0; n < apDrawData->CmdListsCount; n++) + for (int n = 0; n < draw_data->CmdListsCount; n++) { - const ImDrawList* cmd_list = apDrawData->CmdLists[n]; + const ImDrawList* cmd_list = draw_data->CmdLists[n]; memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); vtx_dst += cmd_list->VtxBuffer.Size; @@ -208,40 +240,43 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* apDrawData, ID3D12GraphicsCommand fr->IndexBuffer->Unmap(0, &range); // Setup desired DX state - ImGui_ImplDX12_SetupRenderState(apDrawData, apCommandLists, fr); + ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr); // Render command lists // (Because we merged all buffers into a single one, we maintain our own offset into them) int global_vtx_offset = 0; int global_idx_offset = 0; - ImVec2 clip_off = apDrawData->DisplayPos; - for (int n = 0; n < apDrawData->CmdListsCount; n++) + ImVec2 clip_off = draw_data->DisplayPos; + for (int n = 0; n < draw_data->CmdListsCount; n++) { - const ImDrawList* cmd_list = apDrawData->CmdLists[n]; + const ImDrawList* cmd_list = draw_data->CmdLists[n]; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback != NULL) + if (pcmd->UserCallback != nullptr) { // User callback, registered via ImDrawList::AddCallback() - // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer - // to reset render state.) + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) - ImGui_ImplDX12_SetupRenderState(apDrawData, apCommandLists, fr); + ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr); else pcmd->UserCallback(cmd_list, pcmd); } else { - // Apply Scissor, Bind texture, Draw - const D3D12_RECT r = { - (LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y)}; - if (r.right > r.left && r.bottom > r.top) - { - apCommandLists->SetGraphicsRootDescriptorTable(1, *(D3D12_GPU_DESCRIPTOR_HANDLE*)&pcmd->TextureId); - apCommandLists->RSSetScissorRects(1, &r); - apCommandLists->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0); - } + // Project scissor/clipping rectangles into framebuffer space + ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y); + ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y); + if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) + continue; + + // Apply Scissor/clipping rectangle, Bind texture, Draw + const D3D12_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y }; + D3D12_GPU_DESCRIPTOR_HANDLE texture_handle = {}; + texture_handle.ptr = (UINT64)pcmd->GetTexID(); + ctx->SetGraphicsRootDescriptorTable(1, texture_handle); + ctx->RSSetScissorRects(1, &r); + ctx->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0); } } global_idx_offset += cmd_list->IdxBuffer.Size; @@ -249,10 +284,11 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* apDrawData, ID3D12GraphicsCommand } } -static void ImGui_ImplDX12_CreateFontsTexture(ID3D12CommandQueue* apCommandQueue) +static void ImGui_ImplDX12_CreateFontsTexture() { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); @@ -279,8 +315,9 @@ static void ImGui_ImplDX12_CreateFontsTexture(ID3D12CommandQueue* apCommandQueue desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; desc.Flags = D3D12_RESOURCE_FLAG_NONE; - ID3D12Resource* pTexture = NULL; - g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, NULL, IID_PPV_ARGS(&pTexture)); + ID3D12Resource* pTexture = nullptr; + bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pTexture)); UINT uploadPitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u); UINT uploadSize = height * uploadPitch; @@ -300,16 +337,17 @@ static void ImGui_ImplDX12_CreateFontsTexture(ID3D12CommandQueue* apCommandQueue props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; - ID3D12Resource* uploadBuffer = NULL; - HRESULT hr = g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&uploadBuffer)); + ID3D12Resource* uploadBuffer = nullptr; + HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&uploadBuffer)); IM_ASSERT(SUCCEEDED(hr)); - void* mapped = NULL; - D3D12_RANGE range = {0, uploadSize}; + void* mapped = nullptr; + D3D12_RANGE range = { 0, uploadSize }; hr = uploadBuffer->Map(0, &range, &mapped); IM_ASSERT(SUCCEEDED(hr)); for (int y = 0; y < height; y++) - memcpy((void*)((uintptr_t)mapped + y * uploadPitch), pixels + y * width * 4, width * 4); + memcpy((void*) ((uintptr_t) mapped + y * uploadPitch), pixels + y * width * 4, width * 4); uploadBuffer->Unmap(0, &range); D3D12_TEXTURE_COPY_LOCATION srcLocation = {}; @@ -329,34 +367,43 @@ static void ImGui_ImplDX12_CreateFontsTexture(ID3D12CommandQueue* apCommandQueue D3D12_RESOURCE_BARRIER barrier = {}; barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barrier.Transition.pResource = pTexture; + barrier.Transition.pResource = pTexture; barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; - barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - ID3D12Fence* fence = NULL; - hr = g_pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); + ID3D12Fence* fence = nullptr; + hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); IM_ASSERT(SUCCEEDED(hr)); HANDLE event = CreateEvent(0, 0, 0, 0); - IM_ASSERT(event != NULL); + IM_ASSERT(event != nullptr); + + D3D12_COMMAND_QUEUE_DESC queueDesc = {}; + queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; + queueDesc.NodeMask = 1; - ID3D12CommandAllocator* cmdAlloc = NULL; - hr = g_pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc)); + ID3D12CommandQueue* cmdQueue = nullptr; + hr = bd->pd3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&cmdQueue)); IM_ASSERT(SUCCEEDED(hr)); - ID3D12GraphicsCommandList* cmdList = NULL; - hr = g_pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, NULL, IID_PPV_ARGS(&cmdList)); + ID3D12CommandAllocator* cmdAlloc = nullptr; + hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc)); IM_ASSERT(SUCCEEDED(hr)); - cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, NULL); + ID3D12GraphicsCommandList* cmdList = nullptr; + hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, nullptr, IID_PPV_ARGS(&cmdList)); + IM_ASSERT(SUCCEEDED(hr)); + + cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, nullptr); cmdList->ResourceBarrier(1, &barrier); hr = cmdList->Close(); IM_ASSERT(SUCCEEDED(hr)); - apCommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList); - hr = apCommandQueue->Signal(fence, 1); + cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList); + hr = cmdQueue->Signal(fence, 1); IM_ASSERT(SUCCEEDED(hr)); fence->SetEventOnCompletion(1, event); @@ -364,6 +411,7 @@ static void ImGui_ImplDX12_CreateFontsTexture(ID3D12CommandQueue* apCommandQueue cmdList->Release(); cmdAlloc->Release(); + cmdQueue->Release(); CloseHandle(event); fence->Release(); uploadBuffer->Release(); @@ -376,21 +424,29 @@ static void ImGui_ImplDX12_CreateFontsTexture(ID3D12CommandQueue* apCommandQueue srvDesc.Texture2D.MipLevels = desc.MipLevels; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, g_hFontSrvCpuDescHandle); - SafeRelease(g_pFontTextureResource); - g_pFontTextureResource = pTexture; + bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, bd->hFontSrvCpuDescHandle); + SafeRelease(bd->pFontTextureResource); + bd->pFontTextureResource = pTexture; } // Store our identifier - static_assert(sizeof(ImTextureID) >= sizeof(g_hFontSrvGpuDescHandle.ptr), "Can't pack descriptor handle into TexID, 32-bit not supported yet."); - io.Fonts->TexID = (ImTextureID)g_hFontSrvGpuDescHandle.ptr; + // READ THIS IF THE STATIC_ASSERT() TRIGGERS: + // - Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. + // - This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. + // [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in the 'example_win32_direct12/example_win32_direct12.vcxproj' project file) + // [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like. + // [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!) + // [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in the example_win32_direct12/build_win32.bat file) + static_assert(sizeof(ImTextureID) >= sizeof(bd->hFontSrvGpuDescHandle.ptr), "Can't pack descriptor handle into TexID, 32-bit not supported yet."); + io.Fonts->SetTexID((ImTextureID)bd->hFontSrvGpuDescHandle.ptr); } -bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue) +bool ImGui_ImplDX12_CreateDeviceObjects() { - if (!g_pd3dDevice) + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + if (!bd || !bd->pd3dDevice) return false; - if (g_pPipelineState) + if (bd->pPipelineState) ImGui_ImplDX12_InvalidateDeviceObjects(); // Create the root signature @@ -415,6 +471,7 @@ bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue) param[1].DescriptorTable.pDescriptorRanges = &descRange; param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling. D3D12_STATIC_SAMPLER_DESC staticSampler = {}; staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; @@ -435,64 +492,60 @@ bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue) desc.pParameters = param; desc.NumStaticSamplers = 1; desc.pStaticSamplers = &staticSampler; - desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS | - D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS; + desc.Flags = + D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | + D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS | + D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS | + D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS; + // Load d3d12.dll and D3D12SerializeRootSignature() function address dynamically to facilitate using with D3D12On7. // See if any version of d3d12.dll is already loaded in the process. If so, give preference to that. - static HINSTANCE d3d12_dll = ::GetModuleHandle(TEXT("d3d12.dll")); - if (d3d12_dll == NULL) + static HINSTANCE d3d12_dll = ::GetModuleHandleA("d3d12.dll"); + if (d3d12_dll == nullptr) { - // Attempt to load d3d12.dll from local directories in decreasing order of likelihood. This will only - // succeed if (1) the current OS is Windows 7, and (2) there exists a version of d3d12.dll for Windows 7 - // (D3D12On7) in one of the following directories. - static const TCHAR* localD3d12Paths[] = { - TEXT(".\\d3d12on7\\d3d12.dll"), // used by some games - TEXT(".\\12on7\\d3d12.dll") // used in the Microsoft D3D12On7 sample - }; - - for (unsigned int i = 0; i < _countof(localD3d12Paths); i++) - { - d3d12_dll = LoadLibrary(localD3d12Paths[i]); - if (d3d12_dll != NULL) + // Attempt to load d3d12.dll from local directories. This will only succeed if + // (1) the current OS is Windows 7, and + // (2) there exists a version of d3d12.dll for Windows 7 (D3D12On7) in one of the following directories. + // See https://github.com/ocornut/imgui/pull/3696 for details. + const char* localD3d12Paths[] = { ".\\d3d12.dll", ".\\d3d12on7\\d3d12.dll", ".\\12on7\\d3d12.dll" }; // A. current directory, B. used by some games, C. used in Microsoft D3D12On7 sample + for (int i = 0; i < IM_ARRAYSIZE(localD3d12Paths); i++) + if ((d3d12_dll = ::LoadLibraryA(localD3d12Paths[i])) != nullptr) break; - } - // If failed, we should be on Windows 10. - if (d3d12_dll == NULL) - d3d12_dll = ::LoadLibrary(TEXT("d3d12.dll")); + // If failed, we are on Windows >= 10. + if (d3d12_dll == nullptr) + d3d12_dll = ::LoadLibraryA("d3d12.dll"); - if (d3d12_dll == NULL) + if (d3d12_dll == nullptr) return false; } PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature"); - if (D3D12SerializeRootSignatureFn == NULL) + if (D3D12SerializeRootSignatureFn == nullptr) return false; - ID3DBlob* blob = NULL; - if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, NULL) != S_OK) + ID3DBlob* blob = nullptr; + if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr) != S_OK) return false; - g_pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&g_pRootSignature)); + bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignature)); blob->Release(); } - // By using D3DCompile() from / d3dcompiler.lib, we introduce a dependency to a given version of - // d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A) If you would like to use this DX12 sample code but remove this - // dependency you can: - // 1) compile once, save the compiled shader blobs into a file or source code and pass them to - // CreateVertexShader()/CreatePixelShader() [preferred solution] 2) use code to detect any version of the DLL and - // grab a pointer to D3DCompile from the DLL. + // By using D3DCompile() from / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A) + // If you would like to use this DX12 sample code but remove this dependency you can: + // 1) compile once, save the compiled shader blobs into a file or source code and assign them to psoDesc.VS/PS [preferred solution] + // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL. // See https://github.com/ocornut/imgui/pull/638 for sources and details. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc; memset(&psoDesc, 0, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC)); psoDesc.NodeMask = 1; psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - psoDesc.pRootSignature = g_pRootSignature; + psoDesc.pRootSignature = bd->pRootSignature; psoDesc.SampleMask = UINT_MAX; psoDesc.NumRenderTargets = 1; - psoDesc.RTVFormats[0] = g_RTVFormat; + psoDesc.RTVFormats[0] = bd->RTVFormat; psoDesc.SampleDesc.Count = 1; psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; @@ -501,7 +554,8 @@ bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue) // Create the vertex shader { - static const char* vertexShader = "cbuffer vertexBuffer : register(b0) \ + static const char* vertexShader = + "cbuffer vertexBuffer : register(b0) \ {\ float4x4 ProjectionMatrix; \ };\ @@ -528,23 +582,24 @@ bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue) return output;\ }"; - if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_5_0", 0, 0, &vertexShaderBlob, NULL))) - return false; // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const - // char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! - psoDesc.VS = {vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize()}; + if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_5_0", 0, 0, &vertexShaderBlob, nullptr))) + return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() }; // Create the input layout - static D3D12_INPUT_ELEMENT_DESC local_layout[] = { - {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, - {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, - {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + static D3D12_INPUT_ELEMENT_DESC local_layout[] = + { + { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; - psoDesc.InputLayout = {local_layout, 3}; + psoDesc.InputLayout = { local_layout, 3 }; } // Create the pixel shader { - static const char* pixelShader = "struct PS_INPUT\ + static const char* pixelShader = + "struct PS_INPUT\ {\ float4 pos : SV_POSITION;\ float4 col : COLOR0;\ @@ -559,13 +614,12 @@ bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue) return out_col; \ }"; - if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &pixelShaderBlob, NULL))) + if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_5_0", 0, 0, &pixelShaderBlob, nullptr))) { vertexShaderBlob->Release(); - return false; // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const - // char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! } - psoDesc.PS = {pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize()}; + psoDesc.PS = { pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() }; } // Create the blending setup @@ -576,8 +630,8 @@ bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue) desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA; desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; - desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; - desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ZERO; + desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE; + desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; } @@ -610,62 +664,64 @@ bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue) desc.BackFace = desc.FrontFace; } - HRESULT result_pipeline_state = g_pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&g_pPipelineState)); + HRESULT result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineState)); vertexShaderBlob->Release(); pixelShaderBlob->Release(); if (result_pipeline_state != S_OK) return false; - ImGui_ImplDX12_CreateFontsTexture(apCommandQueue); + ImGui_ImplDX12_CreateFontsTexture(); return true; } -void ImGui_ImplDX12_InvalidateDeviceObjects() +void ImGui_ImplDX12_InvalidateDeviceObjects() { - if (!g_pd3dDevice) + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + if (!bd || !bd->pd3dDevice) return; - SafeRelease(g_pRootSignature); - SafeRelease(g_pPipelineState); - SafeRelease(g_pFontTextureResource); - ImGuiIO& io = ImGui::GetIO(); - io.Fonts->TexID = NULL; // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well. + SafeRelease(bd->pRootSignature); + SafeRelease(bd->pPipelineState); + SafeRelease(bd->pFontTextureResource); + io.Fonts->SetTexID(0); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. - for (UINT i = 0; i < g_numFramesInFlight; i++) + for (UINT i = 0; i < bd->numFramesInFlight; i++) { - FrameResources* fr = &g_pFrameResources[i]; + ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i]; SafeRelease(fr->IndexBuffer); SafeRelease(fr->VertexBuffer); } } -bool ImGui_ImplDX12_Init( - ID3D12Device* apDevice, int aNumFramesInFlight, DXGI_FORMAT aRTVFormat, ID3D12DescriptorHeap* apSRVHeapDesc, D3D12_CPU_DESCRIPTOR_HANDLE aFontSRVDescCPU, - D3D12_GPU_DESCRIPTOR_HANDLE aFontSRVDescGPU) +bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap, + D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle) { - // Setup backend capabilities flags ImGuiIO& io = ImGui::GetIO(); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); + + // Setup backend capabilities flags + ImGui_ImplDX12_Data* bd = IM_NEW(ImGui_ImplDX12_Data)(); + io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_dx12"; - io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing - // for large meshes. - - g_pd3dDevice = apDevice; - g_RTVFormat = aRTVFormat; - g_hFontSrvCpuDescHandle = aFontSRVDescCPU; - g_hFontSrvGpuDescHandle = aFontSRVDescGPU; - g_pFrameResources = new FrameResources[aNumFramesInFlight]; - g_numFramesInFlight = aNumFramesInFlight; - g_frameIndex = UINT_MAX; - IM_UNUSED(apSRVHeapDesc); // Unused in master branch (will be used by multi-viewports) + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + + bd->pd3dDevice = device; + bd->RTVFormat = rtv_format; + bd->hFontSrvCpuDescHandle = font_srv_cpu_desc_handle; + bd->hFontSrvGpuDescHandle = font_srv_gpu_desc_handle; + bd->pFrameResources = new ImGui_ImplDX12_RenderBuffers[num_frames_in_flight]; + bd->numFramesInFlight = num_frames_in_flight; + bd->pd3dSrvDescHeap = cbv_srv_heap; + bd->frameIndex = UINT_MAX; // Create buffers with a default size (they will later be grown as needed) - for (int i = 0; i < aNumFramesInFlight; i++) + for (int i = 0; i < num_frames_in_flight; i++) { - FrameResources* fr = &g_pFrameResources[i]; - fr->IndexBuffer = NULL; - fr->VertexBuffer = NULL; + ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i]; + fr->IndexBuffer = nullptr; + fr->VertexBuffer = nullptr; fr->IndexBufferSize = 10000; fr->VertexBufferSize = 5000; } @@ -675,26 +731,37 @@ bool ImGui_ImplDX12_Init( void ImGui_ImplDX12_Shutdown() { + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + + // Clean up windows and device objects ImGui_ImplDX12_InvalidateDeviceObjects(); - delete[] g_pFrameResources; - g_pFrameResources = NULL; - g_pd3dDevice = NULL; - g_hFontSrvCpuDescHandle.ptr = 0; - g_hFontSrvGpuDescHandle.ptr = 0; - g_numFramesInFlight = 0; - g_frameIndex = UINT_MAX; + delete[] bd->pFrameResources; + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + IM_DELETE(bd); } -void ImGui_ImplDX12_NewFrame(ID3D12CommandQueue* apCommandQueue) +void ImGui_ImplDX12_NewFrame() { - if (!g_pPipelineState || !ImGui::GetIO().Fonts->IsBuilt()) - ImGui_ImplDX12_CreateDeviceObjects(apCommandQueue); + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplDX12_Init()?"); + + if (!bd->pPipelineState) + ImGui_ImplDX12_CreateDeviceObjects(); } -void ImGui_ImplDX12_RecreateFontsTexture(ID3D12CommandQueue* apCommandQueue) +void ImGui_ImplDX12_RecreateFontsTexture() { - SafeRelease(g_pFontTextureResource); + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + + if (!bd || !bd->pd3dDevice) + return; + ImGuiIO& io = ImGui::GetIO(); - io.Fonts->TexID = NULL; - ImGui_ImplDX12_CreateFontsTexture(apCommandQueue); + SafeRelease(bd->pFontTextureResource); + io.Fonts->SetTexID(0); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. + ImGui_ImplDX12_CreateFontsTexture(); } \ No newline at end of file diff --git a/src/imgui_impl/dx12.h b/src/imgui_impl/dx12.h index b43d44ae..1bde3080 100644 --- a/src/imgui_impl/dx12.h +++ b/src/imgui_impl/dx12.h @@ -2,20 +2,20 @@ // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: -// [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about -// ImTextureID! [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. +// [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. -// This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. -// This define is set in the example .vcxproj file and need to be replicated in your app or by adding it to your -// imconfig.h file. +// See imgui_impl_dx12.cpp file for details. -// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Read online: https://github.com/ocornut/imgui/tree/master/docs #pragma once -#include "imgui.h" // IMGUI_IMPL_API +#include "imgui.h" // IMGUI_IMPL_API +#include // DXGI_FORMAT struct ID3D12Device; struct ID3D12DescriptorHeap; @@ -26,18 +26,16 @@ struct D3D12_GPU_DESCRIPTOR_HANDLE; // cmd_list is the command list that the implementation will use to render imgui draw lists. // Before calling the render function, caller must prepare cmd_list by resetting it and setting the appropriate // render target and descriptor heap that contains font_srv_cpu_desc_handle/font_srv_gpu_desc_handle. -// font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal -// font texture. -IMGUI_IMPL_API bool ImGui_ImplDX12_Init( - ID3D12Device* apDevice, int aNumFramesInFlight, DXGI_FORMAT aRTVFormat, ID3D12DescriptorHeap* apSRVHeapDesc, D3D12_CPU_DESCRIPTOR_HANDLE aFontSRVDescCPU, - D3D12_GPU_DESCRIPTOR_HANDLE aFontSRVDescGPU); -IMGUI_IMPL_API void ImGui_ImplDX12_Shutdown(); -IMGUI_IMPL_API void ImGui_ImplDX12_NewFrame(ID3D12CommandQueue* apCommandQueue); -IMGUI_IMPL_API void ImGui_ImplDX12_RenderDrawData(ImDrawData* apDrawData, ID3D12GraphicsCommandList* apCommandLists); +// font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture. +IMGUI_IMPL_API bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap, + D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle); +IMGUI_IMPL_API void ImGui_ImplDX12_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplDX12_NewFrame(); +IMGUI_IMPL_API void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* graphics_command_list); // Use if you want to reset your rendering device without losing Dear ImGui state. -IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects(); -IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue); +IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects(); +IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects(); // Use to recreate font texture during runtime. Call before NewFrame().Should switch to https://github.com/ocornut/imgui/pull/3761 once it's implemented. -IMGUI_IMPL_API void ImGui_ImplDX12_RecreateFontsTexture(ID3D12CommandQueue* apCommandQueue); \ No newline at end of file +IMGUI_IMPL_API void ImGui_ImplDX12_RecreateFontsTexture(); \ No newline at end of file From 9ffef06fe3f5a0677c7b7823e0c2d23976e34bd3 Mon Sep 17 00:00:00 2001 From: Mingming Cui Date: Thu, 29 Jun 2023 17:34:54 +0800 Subject: [PATCH 3/7] switch to a imgui fork --- .gitmodules | 4 ++++ src/imgui_impl/imgui_user_config.h | 5 ++++- xmake.lua | 18 +++++++++++++++--- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/.gitmodules b/.gitmodules index 26812505..0f74d495 100644 --- a/.gitmodules +++ b/.gitmodules @@ -7,3 +7,7 @@ [submodule "vendor/luasocket"] path = vendor/luasocket url = https://github.com/diegonehab/luasocket.git +[submodule "vendor/imgui"] + path = vendor/imgui + url = https://github.com/Nats-ji/imgui.git + branch = docking-1.89.6-texture_update diff --git a/src/imgui_impl/imgui_user_config.h b/src/imgui_impl/imgui_user_config.h index 6298b9c7..9a0eadd5 100644 --- a/src/imgui_impl/imgui_user_config.h +++ b/src/imgui_impl/imgui_user_config.h @@ -7,4 +7,7 @@ extern bool g_ImGuiAssertionsEnabled; void ImGuiAssert(wchar_t const* acpMessage, wchar_t const* acpFile, unsigned aLine); // custom assertion function macro for ImGui -#define IM_ASSERT(expression) (void)((g_ImGuiAssertionsEnabled && ((!!(expression)) || (ImGuiAssert(_CRT_WIDE(#expression), _CRT_WIDE(__FILE__), (unsigned)(__LINE__)), 0)))) \ No newline at end of file +#define IM_ASSERT(expression) (void)((g_ImGuiAssertionsEnabled && ((!!(expression)) || (ImGuiAssert(_CRT_WIDE(#expression), _CRT_WIDE(__FILE__), (unsigned)(__LINE__)), 0)))) + +#define IMGUI_USE_WCHAR32 +#define IMGUI_ENABLE_FREETYPE \ No newline at end of file diff --git a/xmake.lua b/xmake.lua index b28749e1..0cadd55f 100644 --- a/xmake.lua +++ b/xmake.lua @@ -53,9 +53,21 @@ add_requires("xbyak") add_requires("stb") add_requires("sol2", { configs = { includes_lua = false } }) add_requires("openrestry-luajit", { configs = { gc64 = true } }) +add_requires("freetype 2.13.0") local imguiUserConfig = path.absolute("src/imgui_impl/imgui_user_config.h") -add_requires("imgui v1.88-docking", { configs = { wchar32 = true, freetype = true, user_config = imguiUserConfig } }) +-- add_requires("imgui v1.88-docking", { configs = { wchar32 = true, freetype = true, user_config = imguiUserConfig } }) + +target("imgui") + add_defines("IMGUI_USER_CONFIG=\"".. imguiUserConfig .."\"") + set_kind("static") + set_group("vendor") + add_files("vendor/imgui/*.cpp", "vendor/imgui/misc/cpp/*.cpp", "vendor/imgui/misc/freetype/imgui_freetype.cpp") + add_headerfiles("vendor/imgui/*.h", "vendor/imgui/misc/cpp/*.h", "vendor/imgui/misc/freetype/imgui_freetype.h") + add_includedirs("vendor/imgui/", "vendor/imgui/misc/cpp", "vendor/imgui/misc/freetype", { public = true }) + add_headerfiles("vendor/imgui/misc/freetype/imgui_freetype.h") + add_packages("freetype") + on_install(function() end) target("RED4ext.SDK") set_kind("static") @@ -74,8 +86,8 @@ target("cyber_engine_tweaks") add_headerfiles("src/**.h", "build/CETVersion.h") add_includedirs("src/", "build/") add_syslinks("User32", "Version", "d3d11", "Dwrite") - add_packages("spdlog", "nlohmann_json", "minhook", "hopscotch-map", "imgui", "mem", "sol2", "tiltedcore", "sqlite3", "openrestry-luajit", "xbyak", "stb") - add_deps("RED4ext.SDK") + add_packages("spdlog", "nlohmann_json", "minhook", "hopscotch-map", --[["imgui",]] "mem", "sol2", "tiltedcore", "sqlite3", "openrestry-luajit", "xbyak", "stb") + add_deps("imgui","RED4ext.SDK") add_configfiles("src/CETVersion.h.in") on_package(function(target) From 3c79893dc45c0dcff25d0d042fffe76b870da768 Mon Sep 17 00:00:00 2001 From: Mingming Cui Date: Thu, 29 Jun 2023 17:37:12 +0800 Subject: [PATCH 4/7] update dx12 implementation --- src/imgui_impl/dx12.cpp | 121 ++++++++++++++++++++++++---------------- src/imgui_impl/dx12.h | 4 +- 2 files changed, 74 insertions(+), 51 deletions(-) diff --git a/src/imgui_impl/dx12.cpp b/src/imgui_impl/dx12.cpp index 8017a5a8..3db5a36c 100644 --- a/src/imgui_impl/dx12.cpp +++ b/src/imgui_impl/dx12.cpp @@ -20,6 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2021-XX-XX: *BREAKING CHANGE*: DirectX12: Changed ImGui_ImplDX12_CreateFontsTexture() to ImGui_ImplDX12_UpdateFontsTexture(), which should be called at the start of the frame when ImGui::GetIO().Fonts->IsDirty() is true to reupload the font texture. ImGuiBackendFlags_RendererHasTexReload should be set once this is implemented. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) @@ -59,6 +60,8 @@ struct ImGui_ImplDX12_Data ID3D12PipelineState* pPipelineState; DXGI_FORMAT RTVFormat; ID3D12Resource* pFontTextureResource; + int FontTextureWidth; + int FontTextureHeight; D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle; D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle; ID3D12DescriptorHeap* pd3dSrvDescHeap; @@ -86,6 +89,7 @@ struct ImGui_ImplDX12_RenderBuffers int VertexBufferSize; }; + struct VERTEX_CONSTANT_BUFFER_DX12 { float mvp[4][4]; @@ -284,7 +288,7 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL } } -static void ImGui_ImplDX12_CreateFontsTexture() +void ImGui_ImplDX12_UpdateFontsTexture() { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); @@ -292,9 +296,13 @@ static void ImGui_ImplDX12_CreateFontsTexture() unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); + io.Fonts->MarkClean(); + + bool need_barrier_before_copy = true; // Do we need a resource barrier before we copy new data in? - // Upload texture to graphics system + if ((!bd->pFontTextureResource) || (bd->FontTextureWidth != width) || (bd->FontTextureHeight != height)) { + // Either we have no texture or the size has changed, so (re-)create the texture D3D12_HEAP_PROPERTIES props; memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); props.Type = D3D12_HEAP_TYPE_DEFAULT; @@ -319,8 +327,42 @@ static void ImGui_ImplDX12_CreateFontsTexture() bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pTexture)); + // Create SRV + D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc; + ZeroMemory(&srvDesc, sizeof(srvDesc)); + srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srvDesc.Texture2D.MipLevels = desc.MipLevels; + srvDesc.Texture2D.MostDetailedMip = 0; + srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, bd->hFontSrvCpuDescHandle); + SafeRelease(bd->pFontTextureResource); + bd->pFontTextureResource = pTexture; + + bd->FontTextureWidth = width; + bd->FontTextureHeight = height; + + need_barrier_before_copy = false; // Because this is a newly-created texture it will be in D3D12_RESOURCE_STATE_COMMON and thus we don't need a barrier + } + + // Store our identifier + // READ THIS IF THE STATIC_ASSERT() TRIGGERS: + // - Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. + // - This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. + // [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in the 'example_win32_direct12/example_win32_direct12.vcxproj' project file) + // [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like. + // [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!) + // [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in the example_win32_direct12/build_win32.bat file) + static_assert(sizeof(ImTextureID) >= sizeof(bd->hFontSrvGpuDescHandle.ptr), "Can't pack descriptor handle into TexID, 32-bit not supported yet."); + io.Fonts->SetTexID((ImTextureID)bd->hFontSrvGpuDescHandle.ptr); + + // Upload texture + { UINT uploadPitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u); UINT uploadSize = height * uploadPitch; + + D3D12_RESOURCE_DESC desc; + ZeroMemory(&desc, sizeof(desc)); desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; desc.Alignment = 0; desc.Width = uploadSize; @@ -333,6 +375,8 @@ static void ImGui_ImplDX12_CreateFontsTexture() desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; desc.Flags = D3D12_RESOURCE_FLAG_NONE; + D3D12_HEAP_PROPERTIES props; + memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); props.Type = D3D12_HEAP_TYPE_UPLOAD; props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; @@ -360,17 +404,11 @@ static void ImGui_ImplDX12_CreateFontsTexture() srcLocation.PlacedFootprint.Footprint.RowPitch = uploadPitch; D3D12_TEXTURE_COPY_LOCATION dstLocation = {}; - dstLocation.pResource = pTexture; + dstLocation.pResource = bd->pFontTextureResource; dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; dstLocation.SubresourceIndex = 0; - D3D12_RESOURCE_BARRIER barrier = {}; - barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barrier.Transition.pResource = pTexture; - barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; - barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + // Create temporary command list and execute immediately ID3D12Fence* fence = nullptr; hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); @@ -396,8 +434,30 @@ static void ImGui_ImplDX12_CreateFontsTexture() hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, nullptr, IID_PPV_ARGS(&cmdList)); IM_ASSERT(SUCCEEDED(hr)); + if (need_barrier_before_copy) + { + D3D12_RESOURCE_BARRIER barrier = {}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barrier.Transition.pResource = bd->pFontTextureResource; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; + cmdList->ResourceBarrier(1, &barrier); + } + cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, nullptr); - cmdList->ResourceBarrier(1, &barrier); + + { + D3D12_RESOURCE_BARRIER barrier = {}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barrier.Transition.pResource = bd->pFontTextureResource; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + cmdList->ResourceBarrier(1, &barrier); + } hr = cmdList->Close(); IM_ASSERT(SUCCEEDED(hr)); @@ -415,30 +475,7 @@ static void ImGui_ImplDX12_CreateFontsTexture() CloseHandle(event); fence->Release(); uploadBuffer->Release(); - - // Create texture view - D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc; - ZeroMemory(&srvDesc, sizeof(srvDesc)); - srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - srvDesc.Texture2D.MipLevels = desc.MipLevels; - srvDesc.Texture2D.MostDetailedMip = 0; - srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, bd->hFontSrvCpuDescHandle); - SafeRelease(bd->pFontTextureResource); - bd->pFontTextureResource = pTexture; } - - // Store our identifier - // READ THIS IF THE STATIC_ASSERT() TRIGGERS: - // - Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. - // - This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. - // [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in the 'example_win32_direct12/example_win32_direct12.vcxproj' project file) - // [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like. - // [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!) - // [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in the example_win32_direct12/build_win32.bat file) - static_assert(sizeof(ImTextureID) >= sizeof(bd->hFontSrvGpuDescHandle.ptr), "Can't pack descriptor handle into TexID, 32-bit not supported yet."); - io.Fonts->SetTexID((ImTextureID)bd->hFontSrvGpuDescHandle.ptr); } bool ImGui_ImplDX12_CreateDeviceObjects() @@ -670,7 +707,7 @@ bool ImGui_ImplDX12_CreateDeviceObjects() if (result_pipeline_state != S_OK) return false; - ImGui_ImplDX12_CreateFontsTexture(); + ImGui_ImplDX12_UpdateFontsTexture(); return true; } @@ -706,6 +743,7 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_dx12"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + // Note that we explicitly do *not* set ImGuiBackendFlags_RendererHasTexReload here, because in DX12 that requires support in the caller as well, so we leave setting it (or not) up to that code. bd->pd3dDevice = device; bd->RTVFormat = rtv_format; @@ -752,16 +790,3 @@ void ImGui_ImplDX12_NewFrame() if (!bd->pPipelineState) ImGui_ImplDX12_CreateDeviceObjects(); } - -void ImGui_ImplDX12_RecreateFontsTexture() -{ - ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - - if (!bd || !bd->pd3dDevice) - return; - - ImGuiIO& io = ImGui::GetIO(); - SafeRelease(bd->pFontTextureResource); - io.Fonts->SetTexID(0); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. - ImGui_ImplDX12_CreateFontsTexture(); -} \ No newline at end of file diff --git a/src/imgui_impl/dx12.h b/src/imgui_impl/dx12.h index 1bde3080..de7ce298 100644 --- a/src/imgui_impl/dx12.h +++ b/src/imgui_impl/dx12.h @@ -32,10 +32,8 @@ IMGUI_IMPL_API bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames IMGUI_IMPL_API void ImGui_ImplDX12_Shutdown(); IMGUI_IMPL_API void ImGui_ImplDX12_NewFrame(); IMGUI_IMPL_API void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* graphics_command_list); +IMGUI_IMPL_API void ImGui_ImplDX12_UpdateFontsTexture(); // This should be called when the font texture needs updating (if ImGuiBackendFlags_RendererHasTexReload was set), with the GPU idle. It will perform the update using a temporary command list, and block internally until it completes. // Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects(); - -// Use to recreate font texture during runtime. Call before NewFrame().Should switch to https://github.com/ocornut/imgui/pull/3761 once it's implemented. -IMGUI_IMPL_API void ImGui_ImplDX12_RecreateFontsTexture(); \ No newline at end of file From 3235048be8932f4a3571a5fcae8500cffb0c7d14 Mon Sep 17 00:00:00 2001 From: Mingming Cui Date: Thu, 29 Jun 2023 17:38:20 +0800 Subject: [PATCH 5/7] use the new backend to update font --- src/Fonts.cpp | 8 +++++++- src/d3d12/D3D12_Functions.cpp | 4 +++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/Fonts.cpp b/src/Fonts.cpp index f805074f..c3a6ff7f 100644 --- a/src/Fonts.cpp +++ b/src/Fonts.cpp @@ -187,7 +187,10 @@ void Fonts::BuildFonts(const SIZE& acOutSize) iconFontConfig.GlyphOffset.y = std::ceilf(mainFontBaselineOffset * 0.5f); if (!mainFontPath.empty()) + { MainFont = io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(mainFontPath.native()).c_str(), fontSize, &fontConfig, fontRange.Data); + MainFont->FallbackChar = ' '; + } else MainFont = io.Fonts->AddFontDefault(); @@ -223,7 +226,10 @@ void Fonts::BuildFonts(const SIZE& acOutSize) iconFontConfig.GlyphOffset.y = std::ceilf(monoFontBaselineOffset * 0.5f); if (!monoFontPath.empty()) + { MonoFont = io.Fonts->AddFontFromFileTTF(UTF16ToUTF8(monoFontPath.native()).c_str(), fontSize, &fontConfig, fontRange.Data); + MonoFont->FallbackChar = ' '; + } else MonoFont = io.Fonts->AddFontDefault(); @@ -262,7 +268,7 @@ void Fonts::RebuildFonts(const SIZE& acOutSize) if (m_rebuildFonts || m_glyphRangesBuilder.NeedsRebuild()) // Rebuild when font settings changed or glyph ranges changed { BuildFonts(acOutSize); - ImGui_ImplDX12_RecreateFontsTexture(); + ImGui_ImplDX12_UpdateFontsTexture(); m_rebuildFonts = false; } diff --git a/src/d3d12/D3D12_Functions.cpp b/src/d3d12/D3D12_Functions.cpp index 13e39d65..68169c89 100644 --- a/src/d3d12/D3D12_Functions.cpp +++ b/src/d3d12/D3D12_Functions.cpp @@ -322,6 +322,7 @@ bool D3D12::InitializeImGui(size_t aBuffersCounts) return false; } + ImGui::GetIO().BackendFlags |= ImGuiBackendFlags_RendererHasTexReload; // Set flag to indicate that we can reload textures when requested. m_fonts.BuildFonts(m_outSize); if (!ImGui_ImplDX12_CreateDeviceObjects()) @@ -342,9 +343,10 @@ void D3D12::PrepareUpdate() std::lock_guard _(m_imguiLock); + ImGui_ImplWin32_NewFrame(m_outSize); + m_fonts.RebuildFonts(m_outSize); - ImGui_ImplWin32_NewFrame(m_outSize); ImGui::NewFrame(); CET::Get().GetOverlay().Update(); From 7c600c5add3ee083f44343625dc8125b769edfb8 Mon Sep 17 00:00:00 2001 From: Mingming Cui Date: Thu, 29 Jun 2023 17:40:03 +0800 Subject: [PATCH 6/7] update deprecated imgui calls --- src/overlay/widgets/Bindings.cpp | 2 +- src/overlay/widgets/Settings.cpp | 6 +++--- src/sol_imgui/sol_imgui.h | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/overlay/widgets/Bindings.cpp b/src/overlay/widgets/Bindings.cpp index b34f165d..4547030f 100644 --- a/src/overlay/widgets/Bindings.cpp +++ b/src/overlay/widgets/Bindings.cpp @@ -465,7 +465,7 @@ void Bindings::UpdateAndDrawModBindings(const std::string& acModName, TiltedPhoq if (!headerOpen) return; - ImGui::TreePush(); + ImGui::TreePush((void*)NULL); if (aHotkeyCount > 0) { diff --git a/src/overlay/widgets/Settings.cpp b/src/overlay/widgets/Settings.cpp index 4685c10c..5a49467a 100644 --- a/src/overlay/widgets/Settings.cpp +++ b/src/overlay/widgets/Settings.cpp @@ -55,7 +55,7 @@ void Settings::OnUpdate() m_madeFontChanges = false; if (ImGui::CollapsingHeader("Patches", ImGuiTreeNodeFlags_DefaultOpen)) { - ImGui::TreePush(); + ImGui::TreePush((void*)NULL); if (ImGui::BeginTable("SETTINGS", 2, ImGuiTableFlags_NoSavedSettings, ImVec2(-ImGui::GetStyle().IndentSpacing, 0))) { const auto& patchesSettings = m_options.Patches; @@ -88,7 +88,7 @@ void Settings::OnUpdate() } if (ImGui::CollapsingHeader("CET Font Settings", ImGuiTreeNodeFlags_DefaultOpen)) { - ImGui::TreePush(); + ImGui::TreePush((void*)NULL); if (ImGui::BeginTable("SETTINGS", 2, ImGuiTableFlags_NoSavedSettings, ImVec2(-ImGui::GetStyle().IndentSpacing, 0))) { const auto& fontSettings = m_options.Font; @@ -124,7 +124,7 @@ void Settings::OnUpdate() } if (ImGui::CollapsingHeader("CET Development Settings", ImGuiTreeNodeFlags_DefaultOpen)) { - ImGui::TreePush(); + ImGui::TreePush((void*)NULL); if (ImGui::BeginTable("SETTINGS", 2, ImGuiTableFlags_NoSavedSettings, ImVec2(-ImGui::GetStyle().IndentSpacing, 0))) { const auto& developerSettings = m_options.Developer; diff --git a/src/sol_imgui/sol_imgui.h b/src/sol_imgui/sol_imgui.h index bf9ef214..a72e7d2f 100644 --- a/src/sol_imgui/sol_imgui.h +++ b/src/sol_imgui/sol_imgui.h @@ -2932,7 +2932,7 @@ inline void InitEnums(sol::table luaGlobals) #pragma region Slider Flags luaGlobals.new_enum( - "ImGuiSliderFlags", "None", ImGuiSliderFlags_None, "ClampOnInput", ImGuiSliderFlags_ClampOnInput, "Logarithmic", ImGuiSliderFlags_Logarithmic, "NoRoundToFormat", + "ImGuiSliderFlags", "None", ImGuiSliderFlags_None, "AlwaysClamp", ImGuiSliderFlags_AlwaysClamp, "ClampOnInput", ImGuiSliderFlags_AlwaysClamp, "Logarithmic", ImGuiSliderFlags_Logarithmic, "NoRoundToFormat", ImGuiSliderFlags_NoRoundToFormat, "NoInput", ImGuiSliderFlags_NoInput); #pragma endregion Slider Flags From 492077952cecac621a8d7b7b490943d99b5b85ef Mon Sep 17 00:00:00 2001 From: Andrej Redeky Date: Wed, 4 Oct 2023 18:24:46 +0200 Subject: [PATCH 7/7] rebase, fix compilation and update imgui and backends --- src/d3d12/D3D12.cpp | 1 + src/d3d12/D3D12_Functions.cpp | 7 +- src/imgui_impl/dx12.cpp | 387 +++++++++- src/imgui_impl/dx12.h | 4 + src/imgui_impl/win32.cpp | 1356 +++++++++++++++++++++++++++------ src/imgui_impl/win32.h | 58 +- xmake.lua | 2 +- 7 files changed, 1508 insertions(+), 307 deletions(-) diff --git a/src/d3d12/D3D12.cpp b/src/d3d12/D3D12.cpp index 01e1558e..6dab5e29 100644 --- a/src/d3d12/D3D12.cpp +++ b/src/d3d12/D3D12.cpp @@ -36,6 +36,7 @@ LRESULT D3D12::OnWndProc(HWND ahWnd, UINT auMsg, WPARAM awParam, LPARAM alParam) if (d3d12.IsInitialized()) { + extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); if (const auto res = ImGui_ImplWin32_WndProcHandler(ahWnd, auMsg, awParam, alParam)) return res; diff --git a/src/d3d12/D3D12_Functions.cpp b/src/d3d12/D3D12_Functions.cpp index 68169c89..6fd43fc2 100644 --- a/src/d3d12/D3D12_Functions.cpp +++ b/src/d3d12/D3D12_Functions.cpp @@ -19,8 +19,6 @@ bool D3D12::ResetState(const bool acClearDownlevelBackbuffers, const bool acDest { for (auto i = 0; i < drawData.CmdListsCount; ++i) IM_DELETE(drawData.CmdLists[i]); - delete[] drawData.CmdLists; - drawData.CmdLists = nullptr; drawData.Clear(); } @@ -359,13 +357,12 @@ void D3D12::PrepareUpdate() for (auto i = 0; i < drawData.CmdListsCount; ++i) IM_DELETE(drawData.CmdLists[i]); - delete[] drawData.CmdLists; - drawData.CmdLists = nullptr; drawData.Clear(); drawData = *ImGui::GetDrawData(); - auto** copiedDrawLists = new ImDrawList*[drawData.CmdListsCount]; + ImVector copiedDrawLists; + copiedDrawLists.resize(drawData.CmdListsCount); for (auto i = 0; i < drawData.CmdListsCount; ++i) copiedDrawLists[i] = drawData.CmdLists[i]->CloneOutput(); drawData.CmdLists = copiedDrawLists; diff --git a/src/imgui_impl/dx12.cpp b/src/imgui_impl/dx12.cpp index 3db5a36c..f155e3af 100644 --- a/src/imgui_impl/dx12.cpp +++ b/src/imgui_impl/dx12.cpp @@ -4,6 +4,8 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. +// [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. +// FIXME: The transition from removing a viewport and moving the window in an existing hosted viewport tends to flicker. // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. @@ -20,7 +22,8 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2021-XX-XX: *BREAKING CHANGE*: DirectX12: Changed ImGui_ImplDX12_CreateFontsTexture() to ImGui_ImplDX12_UpdateFontsTexture(), which should be called at the start of the frame when ImGui::GetIO().Fonts->IsDirty() is true to reupload the font texture. ImGuiBackendFlags_RendererHasTexReload should be set once this is implemented. +// 2023-XX-XX: *BREAKING CHANGE*: DirectX12: Changed ImGui_ImplDX12_CreateFontsTexture() to ImGui_ImplDX12_UpdateFontsTexture(), which should be called at the start of the frame when ImGui::GetIO().Fonts->IsDirty() is true to reupload the font texture. ImGuiBackendFlags_RendererHasTexReload should be set once this is implemented. +// 2023-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) @@ -41,6 +44,7 @@ #include +#ifndef IMGUI_DISABLE #include "dx12.h" // DirectX @@ -52,7 +56,6 @@ #endif // DirectX data -struct ImGui_ImplDX12_RenderBuffers; struct ImGui_ImplDX12_Data { ID3D12Device* pd3dDevice; @@ -67,10 +70,7 @@ struct ImGui_ImplDX12_Data ID3D12DescriptorHeap* pd3dSrvDescHeap; UINT numFramesInFlight; - ImGui_ImplDX12_RenderBuffers* pFrameResources; - UINT frameIndex; - - ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); frameIndex = UINT_MAX; } + ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts @@ -89,12 +89,88 @@ struct ImGui_ImplDX12_RenderBuffers int VertexBufferSize; }; +// Buffers used for secondary viewports created by the multi-viewports systems +struct ImGui_ImplDX12_FrameContext +{ + ID3D12CommandAllocator* CommandAllocator; + ID3D12Resource* RenderTarget; + D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetCpuDescriptors; +}; + +// Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data. +// Main viewport created by application will only use the Resources field. +// Secondary viewports created by this backend will use all the fields (including Window fields), +struct ImGui_ImplDX12_ViewportData +{ + // Window + ID3D12CommandQueue* CommandQueue; + ID3D12GraphicsCommandList* CommandList; + ID3D12DescriptorHeap* RtvDescHeap; + IDXGISwapChain3* SwapChain; + ID3D12Fence* Fence; + UINT64 FenceSignaledValue; + HANDLE FenceEvent; + UINT NumFramesInFlight; + ImGui_ImplDX12_FrameContext* FrameCtx; + + // Render buffers + UINT FrameIndex; + ImGui_ImplDX12_RenderBuffers* FrameRenderBuffers; + + ImGui_ImplDX12_ViewportData(UINT num_frames_in_flight) + { + CommandQueue = nullptr; + CommandList = nullptr; + RtvDescHeap = nullptr; + SwapChain = nullptr; + Fence = nullptr; + FenceSignaledValue = 0; + FenceEvent = nullptr; + NumFramesInFlight = num_frames_in_flight; + FrameCtx = new ImGui_ImplDX12_FrameContext[NumFramesInFlight]; + FrameIndex = UINT_MAX; + FrameRenderBuffers = new ImGui_ImplDX12_RenderBuffers[NumFramesInFlight]; + + for (UINT i = 0; i < NumFramesInFlight; ++i) + { + FrameCtx[i].CommandAllocator = nullptr; + FrameCtx[i].RenderTarget = nullptr; + + // Create buffers with a default size (they will later be grown as needed) + FrameRenderBuffers[i].IndexBuffer = nullptr; + FrameRenderBuffers[i].VertexBuffer = nullptr; + FrameRenderBuffers[i].VertexBufferSize = 5000; + FrameRenderBuffers[i].IndexBufferSize = 10000; + } + } + ~ImGui_ImplDX12_ViewportData() + { + IM_ASSERT(CommandQueue == nullptr && CommandList == nullptr); + IM_ASSERT(RtvDescHeap == nullptr); + IM_ASSERT(SwapChain == nullptr); + IM_ASSERT(Fence == nullptr); + IM_ASSERT(FenceEvent == nullptr); + + for (UINT i = 0; i < NumFramesInFlight; ++i) + { + IM_ASSERT(FrameCtx[i].CommandAllocator == nullptr && FrameCtx[i].RenderTarget == nullptr); + IM_ASSERT(FrameRenderBuffers[i].IndexBuffer == nullptr && FrameRenderBuffers[i].VertexBuffer == nullptr); + } + + delete[] FrameCtx; FrameCtx = nullptr; + delete[] FrameRenderBuffers; FrameRenderBuffers = nullptr; + } +}; struct VERTEX_CONSTANT_BUFFER_DX12 { float mvp[4][4]; }; +// Forward Declarations +static void ImGui_ImplDX12_InitPlatformInterface(); +static void ImGui_ImplDX12_ShutdownPlatformInterface(); + // Functions static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx, ImGui_ImplDX12_RenderBuffers* fr) { @@ -168,11 +244,10 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) return; - // FIXME: I'm assuming that this only gets called once per frame! - // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - bd->frameIndex = bd->frameIndex + 1; - ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight]; + ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)draw_data->OwnerViewport->RendererUserData; + vd->FrameIndex++; + ImGui_ImplDX12_RenderBuffers* fr = &vd->FrameRenderBuffers[vd->FrameIndex % bd->numFramesInFlight]; // Create and grow vertex/index buffers if needed if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount) @@ -712,6 +787,13 @@ bool ImGui_ImplDX12_CreateDeviceObjects() return true; } +static void ImGui_ImplDX12_DestroyRenderBuffers(ImGui_ImplDX12_RenderBuffers* render_buffers) +{ + SafeRelease(render_buffers->IndexBuffer); + SafeRelease(render_buffers->VertexBuffer); + render_buffers->IndexBufferSize = render_buffers->VertexBufferSize = 0; +} + void ImGui_ImplDX12_InvalidateDeviceObjects() { ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); @@ -723,13 +805,6 @@ void ImGui_ImplDX12_InvalidateDeviceObjects() SafeRelease(bd->pPipelineState); SafeRelease(bd->pFontTextureResource); io.Fonts->SetTexID(0); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. - - for (UINT i = 0; i < bd->numFramesInFlight; i++) - { - ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i]; - SafeRelease(fr->IndexBuffer); - SafeRelease(fr->VertexBuffer); - } } bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap, @@ -744,25 +819,21 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO io.BackendRendererName = "imgui_impl_dx12"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. // Note that we explicitly do *not* set ImGuiBackendFlags_RendererHasTexReload here, because in DX12 that requires support in the caller as well, so we leave setting it (or not) up to that code. + io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + ImGui_ImplDX12_InitPlatformInterface(); bd->pd3dDevice = device; bd->RTVFormat = rtv_format; bd->hFontSrvCpuDescHandle = font_srv_cpu_desc_handle; bd->hFontSrvGpuDescHandle = font_srv_gpu_desc_handle; - bd->pFrameResources = new ImGui_ImplDX12_RenderBuffers[num_frames_in_flight]; bd->numFramesInFlight = num_frames_in_flight; bd->pd3dSrvDescHeap = cbv_srv_heap; - bd->frameIndex = UINT_MAX; - // Create buffers with a default size (they will later be grown as needed) - for (int i = 0; i < num_frames_in_flight; i++) - { - ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i]; - fr->IndexBuffer = nullptr; - fr->VertexBuffer = nullptr; - fr->IndexBufferSize = 10000; - fr->VertexBufferSize = 5000; - } + // Create a dummy ImGui_ImplDX12_ViewportData holder for the main viewport, + // Since this is created and managed by the application, we will only use the ->Resources[] fields. + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + main_viewport->RendererUserData = IM_NEW(ImGui_ImplDX12_ViewportData)(bd->numFramesInFlight); return true; } @@ -773,12 +844,24 @@ void ImGui_ImplDX12_Shutdown() IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + // Manually delete main viewport render resources in-case we haven't initialized for viewports + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + if (ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)main_viewport->RendererUserData) + { + // We could just call ImGui_ImplDX12_DestroyWindow(main_viewport) as a convenience but that would be misleading since we only use data->Resources[] + for (UINT i = 0; i < bd->numFramesInFlight; i++) + ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]); + IM_DELETE(vd); + main_viewport->RendererUserData = nullptr; + } + // Clean up windows and device objects + ImGui_ImplDX12_ShutdownPlatformInterface(); ImGui_ImplDX12_InvalidateDeviceObjects(); - delete[] bd->pFrameResources; + io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; - io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasViewports); IM_DELETE(bd); } @@ -790,3 +873,247 @@ void ImGui_ImplDX12_NewFrame() if (!bd->pPipelineState) ImGui_ImplDX12_CreateDeviceObjects(); } + +//-------------------------------------------------------------------------------------------------------- +// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT +// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously. +// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first.. +//-------------------------------------------------------------------------------------------------------- + +static void ImGui_ImplDX12_CreateWindow(ImGuiViewport* viewport) +{ + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + ImGui_ImplDX12_ViewportData* vd = IM_NEW(ImGui_ImplDX12_ViewportData)(bd->numFramesInFlight); + viewport->RendererUserData = vd; + + // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*). + // Some backends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the HWND. + HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle; + IM_ASSERT(hwnd != 0); + + vd->FrameIndex = UINT_MAX; + + // Create command queue. + D3D12_COMMAND_QUEUE_DESC queue_desc = {}; + queue_desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; + queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + + HRESULT res = S_OK; + res = bd->pd3dDevice->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&vd->CommandQueue)); + IM_ASSERT(res == S_OK); + + // Create command allocator. + for (UINT i = 0; i < bd->numFramesInFlight; ++i) + { + res = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&vd->FrameCtx[i].CommandAllocator)); + IM_ASSERT(res == S_OK); + } + + // Create command list. + res = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, vd->FrameCtx[0].CommandAllocator, nullptr, IID_PPV_ARGS(&vd->CommandList)); + IM_ASSERT(res == S_OK); + vd->CommandList->Close(); + + // Create fence. + res = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&vd->Fence)); + IM_ASSERT(res == S_OK); + + vd->FenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); + IM_ASSERT(vd->FenceEvent != nullptr); + + // Create swap chain + // FIXME-VIEWPORT: May want to copy/inherit swap chain settings from the user/application. + DXGI_SWAP_CHAIN_DESC1 sd1; + ZeroMemory(&sd1, sizeof(sd1)); + sd1.BufferCount = bd->numFramesInFlight; + sd1.Width = (UINT)viewport->Size.x; + sd1.Height = (UINT)viewport->Size.y; + sd1.Format = bd->RTVFormat; + sd1.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + sd1.SampleDesc.Count = 1; + sd1.SampleDesc.Quality = 0; + sd1.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; + sd1.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; + sd1.Scaling = DXGI_SCALING_STRETCH; + sd1.Stereo = FALSE; + + IDXGIFactory4* dxgi_factory = nullptr; + res = ::CreateDXGIFactory1(IID_PPV_ARGS(&dxgi_factory)); + IM_ASSERT(res == S_OK); + + IDXGISwapChain1* swap_chain = nullptr; + res = dxgi_factory->CreateSwapChainForHwnd(vd->CommandQueue, hwnd, &sd1, nullptr, nullptr, &swap_chain); + IM_ASSERT(res == S_OK); + + dxgi_factory->Release(); + + // Or swapChain.As(&mSwapChain) + IM_ASSERT(vd->SwapChain == nullptr); + swap_chain->QueryInterface(IID_PPV_ARGS(&vd->SwapChain)); + swap_chain->Release(); + + // Create the render targets + if (vd->SwapChain) + { + D3D12_DESCRIPTOR_HEAP_DESC desc = {}; + desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; + desc.NumDescriptors = bd->numFramesInFlight; + desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; + desc.NodeMask = 1; + + HRESULT hr = bd->pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&vd->RtvDescHeap)); + IM_ASSERT(hr == S_OK); + + SIZE_T rtv_descriptor_size = bd->pd3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + D3D12_CPU_DESCRIPTOR_HANDLE rtv_handle = vd->RtvDescHeap->GetCPUDescriptorHandleForHeapStart(); + for (UINT i = 0; i < bd->numFramesInFlight; i++) + { + vd->FrameCtx[i].RenderTargetCpuDescriptors = rtv_handle; + rtv_handle.ptr += rtv_descriptor_size; + } + + ID3D12Resource* back_buffer; + for (UINT i = 0; i < bd->numFramesInFlight; i++) + { + IM_ASSERT(vd->FrameCtx[i].RenderTarget == nullptr); + vd->SwapChain->GetBuffer(i, IID_PPV_ARGS(&back_buffer)); + bd->pd3dDevice->CreateRenderTargetView(back_buffer, nullptr, vd->FrameCtx[i].RenderTargetCpuDescriptors); + vd->FrameCtx[i].RenderTarget = back_buffer; + } + } + + for (UINT i = 0; i < bd->numFramesInFlight; i++) + ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]); +} + +static void ImGui_WaitForPendingOperations(ImGui_ImplDX12_ViewportData* vd) +{ + HRESULT hr = S_FALSE; + if (vd && vd->CommandQueue && vd->Fence && vd->FenceEvent) + { + hr = vd->CommandQueue->Signal(vd->Fence, ++vd->FenceSignaledValue); + IM_ASSERT(hr == S_OK); + ::WaitForSingleObject(vd->FenceEvent, 0); // Reset any forgotten waits + hr = vd->Fence->SetEventOnCompletion(vd->FenceSignaledValue, vd->FenceEvent); + IM_ASSERT(hr == S_OK); + ::WaitForSingleObject(vd->FenceEvent, INFINITE); + } +} + +static void ImGui_ImplDX12_DestroyWindow(ImGuiViewport* viewport) +{ + // The main viewport (owned by the application) will always have RendererUserData == 0 since we didn't create the data for it. + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + if (ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData) + { + ImGui_WaitForPendingOperations(vd); + + SafeRelease(vd->CommandQueue); + SafeRelease(vd->CommandList); + SafeRelease(vd->SwapChain); + SafeRelease(vd->RtvDescHeap); + SafeRelease(vd->Fence); + ::CloseHandle(vd->FenceEvent); + vd->FenceEvent = nullptr; + + for (UINT i = 0; i < bd->numFramesInFlight; i++) + { + SafeRelease(vd->FrameCtx[i].RenderTarget); + SafeRelease(vd->FrameCtx[i].CommandAllocator); + ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]); + } + IM_DELETE(vd); + } + viewport->RendererUserData = nullptr; +} + +static void ImGui_ImplDX12_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) +{ + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData; + + ImGui_WaitForPendingOperations(vd); + + for (UINT i = 0; i < bd->numFramesInFlight; i++) + SafeRelease(vd->FrameCtx[i].RenderTarget); + + if (vd->SwapChain) + { + ID3D12Resource* back_buffer = nullptr; + vd->SwapChain->ResizeBuffers(0, (UINT)size.x, (UINT)size.y, DXGI_FORMAT_UNKNOWN, 0); + for (UINT i = 0; i < bd->numFramesInFlight; i++) + { + vd->SwapChain->GetBuffer(i, IID_PPV_ARGS(&back_buffer)); + bd->pd3dDevice->CreateRenderTargetView(back_buffer, nullptr, vd->FrameCtx[i].RenderTargetCpuDescriptors); + vd->FrameCtx[i].RenderTarget = back_buffer; + } + } +} + +static void ImGui_ImplDX12_RenderWindow(ImGuiViewport* viewport, void*) +{ + ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); + ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData; + + ImGui_ImplDX12_FrameContext* frame_context = &vd->FrameCtx[vd->FrameIndex % bd->numFramesInFlight]; + UINT back_buffer_idx = vd->SwapChain->GetCurrentBackBufferIndex(); + + const ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); + D3D12_RESOURCE_BARRIER barrier = {}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barrier.Transition.pResource = vd->FrameCtx[back_buffer_idx].RenderTarget; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; + + // Draw + ID3D12GraphicsCommandList* cmd_list = vd->CommandList; + + frame_context->CommandAllocator->Reset(); + cmd_list->Reset(frame_context->CommandAllocator, nullptr); + cmd_list->ResourceBarrier(1, &barrier); + cmd_list->OMSetRenderTargets(1, &vd->FrameCtx[back_buffer_idx].RenderTargetCpuDescriptors, FALSE, nullptr); + if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear)) + cmd_list->ClearRenderTargetView(vd->FrameCtx[back_buffer_idx].RenderTargetCpuDescriptors, (float*)&clear_color, 0, nullptr); + cmd_list->SetDescriptorHeaps(1, &bd->pd3dSrvDescHeap); + + ImGui_ImplDX12_RenderDrawData(viewport->DrawData, cmd_list); + + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT; + cmd_list->ResourceBarrier(1, &barrier); + cmd_list->Close(); + + vd->CommandQueue->Wait(vd->Fence, vd->FenceSignaledValue); + vd->CommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmd_list); + vd->CommandQueue->Signal(vd->Fence, ++vd->FenceSignaledValue); +} + +static void ImGui_ImplDX12_SwapBuffers(ImGuiViewport* viewport, void*) +{ + ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData; + + vd->SwapChain->Present(0, 0); + while (vd->Fence->GetCompletedValue() < vd->FenceSignaledValue) + ::SwitchToThread(); +} + +void ImGui_ImplDX12_InitPlatformInterface() +{ + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Renderer_CreateWindow = ImGui_ImplDX12_CreateWindow; + platform_io.Renderer_DestroyWindow = ImGui_ImplDX12_DestroyWindow; + platform_io.Renderer_SetWindowSize = ImGui_ImplDX12_SetWindowSize; + platform_io.Renderer_RenderWindow = ImGui_ImplDX12_RenderWindow; + platform_io.Renderer_SwapBuffers = ImGui_ImplDX12_SwapBuffers; +} + +void ImGui_ImplDX12_ShutdownPlatformInterface() +{ + ImGui::DestroyPlatformWindows(); +} + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/src/imgui_impl/dx12.h b/src/imgui_impl/dx12.h index de7ce298..f8ad2ad0 100644 --- a/src/imgui_impl/dx12.h +++ b/src/imgui_impl/dx12.h @@ -4,6 +4,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. +// [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. // See imgui_impl_dx12.cpp file for details. @@ -15,6 +16,7 @@ #pragma once #include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE #include // DXGI_FORMAT struct ID3D12Device; @@ -37,3 +39,5 @@ IMGUI_IMPL_API void ImGui_ImplDX12_UpdateFontsTexture(); // This should be c // Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects(); + +#endif // #ifndef IMGUI_DISABLE diff --git a/src/imgui_impl/win32.cpp b/src/imgui_impl/win32.cpp index 2c203aa8..d951158c 100644 --- a/src/imgui_impl/win32.cpp +++ b/src/imgui_impl/win32.cpp @@ -1,110 +1,215 @@ -// dear imgui: Platform Backend for Windows (standard windows API for 32 and 64 bits applications) +// dear imgui: Platform Backend for Windows (standard windows API for 32-bits AND 64-bits applications) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // Implemented features: // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) -// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= -// ImGuiConfigFlags_NoMouseCursorChange'. [X] Platform: Keyboard arrays indexed using VK_* Virtual Key Codes, e.g. -// ImGui::IsKeyPressed(VK_SPACE). [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= -// ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] +// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. -// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Read online: https://github.com/ocornut/imgui/tree/master/docs #include +#ifndef IMGUI_DISABLE #include "win32.h" +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#include // GET_X_LPARAM(), GET_Y_LPARAM() +#include +#include + +// Configuration flags to add in your imconfig.h file: +//#define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD // Disable gamepad support. This was meaningful before <1.81 but we now load XInput dynamically so the option is now less relevant. -#include "CET.h" -#include "Utils.h" +// Using XInput for gamepad (will load DLL dynamically) +#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD +#include +typedef DWORD (WINAPI *PFN_XInputGetCapabilities)(DWORD, DWORD, XINPUT_CAPABILITIES*); +typedef DWORD (WINAPI *PFN_XInputGetState)(DWORD, XINPUT_STATE*); +#endif // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2023-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. +// 2023-04-19: Added ImGui_ImplWin32_InitForOpenGL() to facilitate combining raw Win32/Winapi with OpenGL. (#3218) +// 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen. (#2702) +// 2023-02-15: Inputs: Use WM_NCMOUSEMOVE / WM_NCMOUSELEAVE to track mouse position over non-client area (e.g. OS decorations) when app is not focused. (#6045, #6162) +// 2023-02-02: Inputs: Flipping WM_MOUSEHWHEEL (horizontal mouse-wheel) value to match other backends and offer consistent horizontal scrolling direction. (#4019, #6096, #1463) +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. +// 2022-09-28: Inputs: Convert WM_CHAR values with MultiByteToWideChar() when window class was registered as MBCS (not Unicode). +// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). +// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. +// 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[]. +// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). +// 2022-01-17: Inputs: always update key mods next and before a key event (not in NewFrame) to fix input queue with very low framerates. +// 2022-01-12: Inputs: Update mouse inputs using WM_MOUSEMOVE/WM_MOUSELEAVE + fallback to provide it when focused but not hovered/captured. More standard and will allow us to pass it to future input queue API. +// 2022-01-12: Inputs: Maintain our own copy of MouseButtonsDown mask instead of using ImGui::IsAnyMouseDown() which will be obsoleted. +// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. +// 2021-12-16: Inputs: Fill VK_LCONTROL/VK_RCONTROL/VK_LSHIFT/VK_RSHIFT/VK_LMENU/VK_RMENU for completeness. +// 2021-08-17: Calling io.AddFocusEvent() on WM_SETFOCUS/WM_KILLFOCUS messages. +// 2021-08-02: Inputs: Fixed keyboard modifiers being reported when host window doesn't have focus. +// 2021-07-29: Inputs: MousePos is correctly reported when the host platform window is hovered but not focused (using TrackMouseEvent() to receive WM_MOUSELEAVE events). +// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). +// 2021-06-08: Fixed ImGui_ImplWin32_EnableDpiAwareness() and ImGui_ImplWin32_GetDpiScaleForMonitor() to handle Windows 8.1/10 features without a manifest (per-monitor DPI, and properly calls SetProcessDpiAwareness() on 8.1). +// 2021-03-23: Inputs: Clearing keyboard down array when losing focus (WM_KILLFOCUS). +// 2021-02-18: Added ImGui_ImplWin32_EnableAlphaCompositing(). Non Visual Studio users will need to link with dwmapi.lib (MinGW/gcc: use -ldwmapi). +// 2021-02-17: Fixed ImGui_ImplWin32_EnableDpiAwareness() attempting to get SetProcessDpiAwareness from shcore.dll on Windows 8 whereas it is only supported on Windows 8.1. +// 2021-01-25: Inputs: Dynamically loading XInput DLL. // 2020-12-04: Misc: Fixed setting of io.DisplaySize to invalid/uninitialized data when after hwnd has been closed. -// 2020-03-03: Inputs: Calling AddInputCharacterUTF16() to support surrogate pairs leading to codepoint >= 0x10000 (for -// more complete CJK inputs) 2020-02-17: Added ImGui_ImplWin32_EnableDpiAwareness(), -// ImGui_ImplWin32_GetDpiScaleForHwnd(), ImGui_ImplWin32_GetDpiScaleForMonitor() helper functions. 2019-12-05: Inputs: -// Added support for ImGuiMouseCursor_NotAllowed mouse cursor. 2019-05-11: Inputs: Don't filter value from WM_CHAR -// before calling AddInputCharacter(). 2019-01-17: Misc: Using GetForegroundWindow()+IsChild() instead of -// GetActiveWindow() to be compatible with windows created in a different thread or parent. 2019-01-17: Inputs: Added -// support for mouse buttons 4 and 5 via WM_XBUTTON* messages. 2019-01-15: Inputs: Added support for XInput gamepads -// (if ImGuiConfigFlags_NavEnableGamepad is set by user application). 2018-11-30: Misc: Setting up -// io.BackendPlatformName so it can be displayed in the About Window. 2018-06-29: Inputs: Added support for the -// ImGuiMouseCursor_Hand cursor. 2018-06-10: Inputs: Fixed handling of mouse wheel messages to support fine position -// messages (typically sent by track-pads). 2018-06-08: Misc: Extracted imgui_impl_win32.cpp/.h away from the old -// combined DX9/DX10/DX11/DX12 examples. 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors and -// ImGuiBackendFlags_HasSetMousePos flags + honor ImGuiConfigFlags_NoMouseCursorChange flag. 2018-02-20: Inputs: Added -// support for mouse cursors (ImGui::GetMouseCursor() value and WM_SETCURSOR message handling). 2018-02-06: Inputs: -// Added mapping for ImGuiKey_Space. 2018-02-06: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse -// (when using navigation and ImGuiConfigFlags_NavMoveMouse is set). 2018-02-06: Misc: Removed call to -// ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. +// 2020-03-03: Inputs: Calling AddInputCharacterUTF16() to support surrogate pairs leading to codepoint >= 0x10000 (for more complete CJK inputs) +// 2020-02-17: Added ImGui_ImplWin32_EnableDpiAwareness(), ImGui_ImplWin32_GetDpiScaleForHwnd(), ImGui_ImplWin32_GetDpiScaleForMonitor() helper functions. +// 2020-01-14: Inputs: Added support for #define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD/IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT. +// 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. +// 2019-05-11: Inputs: Don't filter value from WM_CHAR before calling AddInputCharacter(). +// 2019-01-17: Misc: Using GetForegroundWindow()+IsChild() instead of GetActiveWindow() to be compatible with windows created in a different thread or parent. +// 2019-01-17: Inputs: Added support for mouse buttons 4 and 5 via WM_XBUTTON* messages. +// 2019-01-15: Inputs: Added support for XInput gamepads (if ImGuiConfigFlags_NavEnableGamepad is set by user application). +// 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. +// 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor. +// 2018-06-10: Inputs: Fixed handling of mouse wheel messages to support fine position messages (typically sent by track-pads). +// 2018-06-08: Misc: Extracted imgui_impl_win32.cpp/.h away from the old combined DX9/DX10/DX11/DX12 examples. +// 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors and ImGuiBackendFlags_HasSetMousePos flags + honor ImGuiConfigFlags_NoMouseCursorChange flag. +// 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value and WM_SETCURSOR message handling). +// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. +// 2018-02-06: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set). +// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support. // 2018-01-08: Inputs: Added mapping for ImGuiKey_Insert. // 2018-01-05: Inputs: Added WM_LBUTTONDBLCLK double-click handlers for window classes with the CS_DBLCLKS flag. // 2017-10-23: Inputs: Added WM_SYSKEYDOWN / WM_SYSKEYUP handlers so e.g. the VK_MENU key can be read. -// 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when -// dragging. 2016-11-12: Inputs: Only call Win32 ::SetCursor(NULL) when io.MouseDrawCursor is set. +// 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when dragging. +// 2016-11-12: Inputs: Only call Win32 ::SetCursor(nullptr) when io.MouseDrawCursor is set. + +// Forward Declarations +static void ImGui_ImplWin32_InitPlatformInterface(bool platformHasOwnDC); +static void ImGui_ImplWin32_ShutdownPlatformInterface(); +static void ImGui_ImplWin32_UpdateMonitors(); + +struct ImGui_ImplWin32_Data +{ + HWND hWnd; + HWND MouseHwnd; + int MouseTrackedArea; // 0: not tracked, 1: client are, 2: non-client area + int MouseButtonsDown; + INT64 Time; + INT64 TicksPerSecond; + ImGuiMouseCursor LastMouseCursor; + bool WantUpdateMonitors; + +#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD + bool HasGamepad; + bool WantUpdateHasGamepad; + HMODULE XInputDLL; + PFN_XInputGetCapabilities XInputGetCapabilities; + PFN_XInputGetState XInputGetState; +#endif -// Win32 Data -static HWND g_hWnd = NULL; -static INT64 g_Time = 0; -static INT64 g_TicksPerSecond = 0; -static ImGuiMouseCursor g_LastMouseCursor = ImGuiMouseCursor_COUNT; -static std::string g_LayoutPath = ""; + ImGui_ImplWin32_Data() { memset((void*)this, 0, sizeof(*this)); } +}; + +// Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts +// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. +// FIXME: multi-context support is not well tested and probably dysfunctional in this backend. +// FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. +static ImGui_ImplWin32_Data* ImGui_ImplWin32_GetBackendData() +{ + return ImGui::GetCurrentContext() ? (ImGui_ImplWin32_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; +} // Functions -bool ImGui_ImplWin32_Init(HWND ahWnd) +static bool ImGui_ImplWin32_InitEx(void* hwnd, bool platform_has_own_dc) { - if (!::QueryPerformanceFrequency((LARGE_INTEGER*)&g_TicksPerSecond)) + ImGuiIO& io = ImGui::GetIO(); + IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); + + INT64 perf_frequency, perf_counter; + if (!::QueryPerformanceFrequency((LARGE_INTEGER*)&perf_frequency)) return false; - if (!::QueryPerformanceCounter((LARGE_INTEGER*)&g_Time)) + if (!::QueryPerformanceCounter((LARGE_INTEGER*)&perf_counter)) return false; // Setup backend capabilities flags - g_hWnd = ahWnd; - ImGuiIO& io = ImGui::GetIO(); - io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) - io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) - io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; + ImGui_ImplWin32_Data* bd = IM_NEW(ImGui_ImplWin32_Data)(); + io.BackendPlatformUserData = (void*)bd; io.BackendPlatformName = "imgui_impl_win32"; - io.ImeWindowHandle = ahWnd; - - // Setup ini path - g_LayoutPath = UTF16ToUTF8(GetAbsolutePath(L"layout.ini", CET::Get().GetPaths().CETRoot(), true).native()); - io.IniFilename = g_LayoutPath.c_str(); - - // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array that we will update during - // the application lifetime. - io.KeyMap[ImGuiKey_Tab] = VK_TAB; - io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT; - io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT; - io.KeyMap[ImGuiKey_UpArrow] = VK_UP; - io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN; - io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR; - io.KeyMap[ImGuiKey_PageDown] = VK_NEXT; - io.KeyMap[ImGuiKey_Home] = VK_HOME; - io.KeyMap[ImGuiKey_End] = VK_END; - io.KeyMap[ImGuiKey_Insert] = VK_INSERT; - io.KeyMap[ImGuiKey_Delete] = VK_DELETE; - io.KeyMap[ImGuiKey_Backspace] = VK_BACK; - io.KeyMap[ImGuiKey_Space] = VK_SPACE; - io.KeyMap[ImGuiKey_Enter] = VK_RETURN; - io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE; - io.KeyMap[ImGuiKey_KeyPadEnter] = VK_RETURN; - io.KeyMap[ImGuiKey_A] = 'A'; - io.KeyMap[ImGuiKey_C] = 'C'; - io.KeyMap[ImGuiKey_V] = 'V'; - io.KeyMap[ImGuiKey_X] = 'X'; - io.KeyMap[ImGuiKey_Y] = 'Y'; - io.KeyMap[ImGuiKey_Z] = 'Z'; + io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) + io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) + io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional) + io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can call io.AddMouseViewportEvent() with correct data (optional) + + bd->hWnd = (HWND)hwnd; + bd->WantUpdateMonitors = true; + bd->TicksPerSecond = perf_frequency; + bd->Time = perf_counter; + bd->LastMouseCursor = ImGuiMouseCursor_COUNT; + + // Our mouse update function expect PlatformHandle to be filled for the main viewport + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + main_viewport->PlatformHandle = main_viewport->PlatformHandleRaw = (void*)bd->hWnd; + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + ImGui_ImplWin32_InitPlatformInterface(platform_has_own_dc); + + // Dynamically load XInput library +#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD + bd->WantUpdateHasGamepad = true; + const char* xinput_dll_names[] = + { + "xinput1_4.dll", // Windows 8+ + "xinput1_3.dll", // DirectX SDK + "xinput9_1_0.dll", // Windows Vista, Windows 7 + "xinput1_2.dll", // DirectX SDK + "xinput1_1.dll" // DirectX SDK + }; + for (int n = 0; n < IM_ARRAYSIZE(xinput_dll_names); n++) + if (HMODULE dll = ::LoadLibraryA(xinput_dll_names[n])) + { + bd->XInputDLL = dll; + bd->XInputGetCapabilities = (PFN_XInputGetCapabilities)::GetProcAddress(dll, "XInputGetCapabilities"); + bd->XInputGetState = (PFN_XInputGetState)::GetProcAddress(dll, "XInputGetState"); + break; + } +#endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD return true; } -void ImGui_ImplWin32_Shutdown() +IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd) +{ + return ImGui_ImplWin32_InitEx(hwnd, false); +} + +IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd) +{ + // OpenGL needs CS_OWNDC + return ImGui_ImplWin32_InitEx(hwnd, true); +} + +void ImGui_ImplWin32_Shutdown() { - g_hWnd = (HWND)0; + ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); + IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + + ImGui_ImplWin32_ShutdownPlatformInterface(); + + // Unload XInput library +#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD + if (bd->XInputDLL) + ::FreeLibrary(bd->XInputDLL); +#endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD + + io.BackendPlatformName = nullptr; + io.BackendPlatformUserData = nullptr; + io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad | ImGuiBackendFlags_PlatformHasViewports | ImGuiBackendFlags_HasMouseHoveredViewport); + IM_DELETE(bd); } static bool ImGui_ImplWin32_UpdateMouseCursor() @@ -117,7 +222,7 @@ static bool ImGui_ImplWin32_UpdateMouseCursor() if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor) { // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor - ::SetCursor(NULL); + ::SetCursor(nullptr); } else { @@ -125,137 +230,455 @@ static bool ImGui_ImplWin32_UpdateMouseCursor() LPTSTR win32_cursor = IDC_ARROW; switch (imgui_cursor) { - case ImGuiMouseCursor_Arrow: win32_cursor = IDC_ARROW; break; - case ImGuiMouseCursor_TextInput: win32_cursor = IDC_IBEAM; break; - case ImGuiMouseCursor_ResizeAll: win32_cursor = IDC_SIZEALL; break; - case ImGuiMouseCursor_ResizeEW: win32_cursor = IDC_SIZEWE; break; - case ImGuiMouseCursor_ResizeNS: win32_cursor = IDC_SIZENS; break; - case ImGuiMouseCursor_ResizeNESW: win32_cursor = IDC_SIZENESW; break; - case ImGuiMouseCursor_ResizeNWSE: win32_cursor = IDC_SIZENWSE; break; - case ImGuiMouseCursor_Hand: win32_cursor = IDC_HAND; break; - case ImGuiMouseCursor_NotAllowed: win32_cursor = IDC_NO; break; + case ImGuiMouseCursor_Arrow: win32_cursor = IDC_ARROW; break; + case ImGuiMouseCursor_TextInput: win32_cursor = IDC_IBEAM; break; + case ImGuiMouseCursor_ResizeAll: win32_cursor = IDC_SIZEALL; break; + case ImGuiMouseCursor_ResizeEW: win32_cursor = IDC_SIZEWE; break; + case ImGuiMouseCursor_ResizeNS: win32_cursor = IDC_SIZENS; break; + case ImGuiMouseCursor_ResizeNESW: win32_cursor = IDC_SIZENESW; break; + case ImGuiMouseCursor_ResizeNWSE: win32_cursor = IDC_SIZENWSE; break; + case ImGuiMouseCursor_Hand: win32_cursor = IDC_HAND; break; + case ImGuiMouseCursor_NotAllowed: win32_cursor = IDC_NO; break; } - ::SetCursor(::LoadCursor(NULL, win32_cursor)); + ::SetCursor(::LoadCursor(nullptr, win32_cursor)); } return true; } -static void ImGui_ImplWin32_UpdateMousePos(SIZE aOutSize) +static bool IsVkDown(int vk) { + return (::GetKeyState(vk) & 0x8000) != 0; +} + +static void ImGui_ImplWin32_AddKeyEvent(ImGuiKey key, bool down, int native_keycode, int native_scancode = -1) +{ + ImGuiIO& io = ImGui::GetIO(); + io.AddKeyEvent(key, down); + io.SetKeyEventNativeData(key, native_keycode, native_scancode); // To support legacy indexing (<1.87 user code) + IM_UNUSED(native_scancode); +} + +static void ImGui_ImplWin32_ProcessKeyEventsWorkarounds() +{ + // Left & right Shift keys: when both are pressed together, Windows tend to not generate the WM_KEYUP event for the first released one. + if (ImGui::IsKeyDown(ImGuiKey_LeftShift) && !IsVkDown(VK_LSHIFT)) + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftShift, false, VK_LSHIFT); + if (ImGui::IsKeyDown(ImGuiKey_RightShift) && !IsVkDown(VK_RSHIFT)) + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightShift, false, VK_RSHIFT); + + // Sometimes WM_KEYUP for Win key is not passed down to the app (e.g. for Win+V on some setups, according to GLFW). + if (ImGui::IsKeyDown(ImGuiKey_LeftSuper) && !IsVkDown(VK_LWIN)) + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftSuper, false, VK_LWIN); + if (ImGui::IsKeyDown(ImGuiKey_RightSuper) && !IsVkDown(VK_RWIN)) + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightSuper, false, VK_RWIN); +} + +static void ImGui_ImplWin32_UpdateKeyModifiers() +{ + ImGuiIO& io = ImGui::GetIO(); + io.AddKeyEvent(ImGuiMod_Ctrl, IsVkDown(VK_CONTROL)); + io.AddKeyEvent(ImGuiMod_Shift, IsVkDown(VK_SHIFT)); + io.AddKeyEvent(ImGuiMod_Alt, IsVkDown(VK_MENU)); + io.AddKeyEvent(ImGuiMod_Super, IsVkDown(VK_APPS)); +} + +// This code supports multi-viewports (multiple OS Windows mapped into different Dear ImGui viewports) +// Because of that, it is a little more complicated than your typical single-viewport binding code! +static void ImGui_ImplWin32_UpdateMouseData(SIZE resolution) +{ + ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); ImGuiIO& io = ImGui::GetIO(); + IM_ASSERT(bd->hWnd != 0); + + POINT mouse_screen_pos; + bool has_mouse_screen_pos = ::GetCursorPos(&mouse_screen_pos) != 0; - // Set OS mouse position if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by - // user) - if (io.WantSetMousePos) + HWND focused_window = ::GetForegroundWindow(); + const bool is_app_focused = (focused_window && (focused_window == bd->hWnd || ::IsChild(focused_window, bd->hWnd) || ImGui::FindViewportByPlatformHandle((void*)focused_window))); + if (is_app_focused) { - POINT pos = {(int)io.MousePos.x, (int)io.MousePos.y}; - if (::ClientToScreen(g_hWnd, &pos)) + // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) + // When multi-viewports are enabled, all Dear ImGui positions are same as OS positions. + if (io.WantSetMousePos) + { + POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y }; + if ((io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) == 0) + ::ClientToScreen(focused_window, &pos); ::SetCursorPos(pos.x, pos.y); + } + + // (Optional) Fallback to provide mouse position when focused (WM_MOUSEMOVE already provides this when hovered or captured) + // This also fills a short gap when clicking non-client area: WM_NCMOUSELEAVE -> modal OS move -> gap -> WM_NCMOUSEMOVE + if (!io.WantSetMousePos && bd->MouseTrackedArea == 0 && has_mouse_screen_pos) + { + // Single viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) + // (This is the position you can get with ::GetCursorPos() + ::ScreenToClient() or WM_MOUSEMOVE.) + // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor) + // (This is the position you can get with ::GetCursorPos() or WM_MOUSEMOVE + ::ClientToScreen(). In theory adding viewport->Pos to a client position would also be the same.) + POINT mouse_pos = mouse_screen_pos; + if (!(io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)) + ::ScreenToClient(bd->hWnd, &mouse_pos); + + RECT clientRect; + ::GetClientRect(bd->hWnd, &clientRect); + + // scale, just to make sure coords are correct (fixes issues in fullscreen) + auto xScale = io.DisplaySize.x / (clientRect.right - clientRect.left); + auto yScale = io.DisplaySize.y / (clientRect.bottom - clientRect.top); + io.AddMousePosEvent((float)mouse_pos.x * xScale, (float)mouse_pos.y * yScale); + } } - // Set mouse position - io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); - POINT pos; - if (HWND active_window = ::GetForegroundWindow()) - if (active_window == g_hWnd || ::IsChild(active_window, g_hWnd)) - if (::GetCursorPos(&pos) && ::ScreenToClient(g_hWnd, &pos)) - if (!aOutSize.cx || !aOutSize.cy) - io.MousePos = ImVec2((float)pos.x, (float)pos.y); - else - { - RECT clientRect; - ::GetClientRect(g_hWnd, &clientRect); + // (Optional) When using multiple viewports: call io.AddMouseViewportEvent() with the viewport the OS mouse cursor is hovering. + // If ImGuiBackendFlags_HasMouseHoveredViewport is not set by the backend, Dear imGui will ignore this field and infer the information using its flawed heuristic. + // - [X] Win32 backend correctly ignore viewports with the _NoInputs flag (here using ::WindowFromPoint with WM_NCHITTEST + HTTRANSPARENT in WndProc does that) + // Some backend are not able to handle that correctly. If a backend report an hovered viewport that has the _NoInputs flag (e.g. when dragging a window + // for docking, the viewport has the _NoInputs flag in order to allow us to find the viewport under), then Dear ImGui is forced to ignore the value reported + // by the backend, and use its flawed heuristic to guess the viewport behind. + // - [X] Win32 backend correctly reports this regardless of another viewport behind focused and dragged from (we need this to find a useful drag and drop target). + ImGuiID mouse_viewport_id = 0; + if (has_mouse_screen_pos) + if (HWND hovered_hwnd = ::WindowFromPoint(mouse_screen_pos)) + if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle((void*)hovered_hwnd)) + mouse_viewport_id = viewport->ID; + io.AddMouseViewportEvent(mouse_viewport_id); +} + +// Gamepad navigation mapping +static void ImGui_ImplWin32_UpdateGamepads() +{ +#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD + ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); + //if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. + // return; - // scale, just to make sure coords are correct (fixes issues in fullscreen) - auto xScale = static_cast(aOutSize.cx) / (clientRect.right - clientRect.left); - auto yScale = static_cast(aOutSize.cy) / (clientRect.bottom - clientRect.top); - io.MousePos = ImVec2(pos.x * xScale, pos.y * yScale); - } + // Calling XInputGetState() every frame on disconnected gamepads is unfortunately too slow. + // Instead we refresh gamepad availability by calling XInputGetCapabilities() _only_ after receiving WM_DEVICECHANGE. + if (bd->WantUpdateHasGamepad) + { + XINPUT_CAPABILITIES caps = {}; + bd->HasGamepad = bd->XInputGetCapabilities ? (bd->XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &caps) == ERROR_SUCCESS) : false; + bd->WantUpdateHasGamepad = false; + } + + io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; + XINPUT_STATE xinput_state; + XINPUT_GAMEPAD& gamepad = xinput_state.Gamepad; + if (!bd->HasGamepad || bd->XInputGetState == nullptr || bd->XInputGetState(0, &xinput_state) != ERROR_SUCCESS) + return; + io.BackendFlags |= ImGuiBackendFlags_HasGamepad; + + #define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f : V) + #define MAP_BUTTON(KEY_NO, BUTTON_ENUM) { io.AddKeyEvent(KEY_NO, (gamepad.wButtons & BUTTON_ENUM) != 0); } + #define MAP_ANALOG(KEY_NO, VALUE, V0, V1) { float vn = (float)(VALUE - V0) / (float)(V1 - V0); io.AddKeyAnalogEvent(KEY_NO, vn > 0.10f, IM_SATURATE(vn)); } + MAP_BUTTON(ImGuiKey_GamepadStart, XINPUT_GAMEPAD_START); + MAP_BUTTON(ImGuiKey_GamepadBack, XINPUT_GAMEPAD_BACK); + MAP_BUTTON(ImGuiKey_GamepadFaceLeft, XINPUT_GAMEPAD_X); + MAP_BUTTON(ImGuiKey_GamepadFaceRight, XINPUT_GAMEPAD_B); + MAP_BUTTON(ImGuiKey_GamepadFaceUp, XINPUT_GAMEPAD_Y); + MAP_BUTTON(ImGuiKey_GamepadFaceDown, XINPUT_GAMEPAD_A); + MAP_BUTTON(ImGuiKey_GamepadDpadLeft, XINPUT_GAMEPAD_DPAD_LEFT); + MAP_BUTTON(ImGuiKey_GamepadDpadRight, XINPUT_GAMEPAD_DPAD_RIGHT); + MAP_BUTTON(ImGuiKey_GamepadDpadUp, XINPUT_GAMEPAD_DPAD_UP); + MAP_BUTTON(ImGuiKey_GamepadDpadDown, XINPUT_GAMEPAD_DPAD_DOWN); + MAP_BUTTON(ImGuiKey_GamepadL1, XINPUT_GAMEPAD_LEFT_SHOULDER); + MAP_BUTTON(ImGuiKey_GamepadR1, XINPUT_GAMEPAD_RIGHT_SHOULDER); + MAP_ANALOG(ImGuiKey_GamepadL2, gamepad.bLeftTrigger, XINPUT_GAMEPAD_TRIGGER_THRESHOLD, 255); + MAP_ANALOG(ImGuiKey_GamepadR2, gamepad.bRightTrigger, XINPUT_GAMEPAD_TRIGGER_THRESHOLD, 255); + MAP_BUTTON(ImGuiKey_GamepadL3, XINPUT_GAMEPAD_LEFT_THUMB); + MAP_BUTTON(ImGuiKey_GamepadR3, XINPUT_GAMEPAD_RIGHT_THUMB); + MAP_ANALOG(ImGuiKey_GamepadLStickLeft, gamepad.sThumbLX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); + MAP_ANALOG(ImGuiKey_GamepadLStickRight, gamepad.sThumbLX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); + MAP_ANALOG(ImGuiKey_GamepadLStickUp, gamepad.sThumbLY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); + MAP_ANALOG(ImGuiKey_GamepadLStickDown, gamepad.sThumbLY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); + MAP_ANALOG(ImGuiKey_GamepadRStickLeft, gamepad.sThumbRX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); + MAP_ANALOG(ImGuiKey_GamepadRStickRight, gamepad.sThumbRX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); + MAP_ANALOG(ImGuiKey_GamepadRStickUp, gamepad.sThumbRY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); + MAP_ANALOG(ImGuiKey_GamepadRStickDown, gamepad.sThumbRY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); + #undef MAP_BUTTON + #undef MAP_ANALOG +#endif // #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD } -void ImGui_ImplWin32_NewFrame(SIZE aOutSize) +static BOOL CALLBACK ImGui_ImplWin32_UpdateMonitors_EnumFunc(HMONITOR monitor, HDC, LPRECT, LPARAM) +{ + MONITORINFO info = {}; + info.cbSize = sizeof(MONITORINFO); + if (!::GetMonitorInfo(monitor, &info)) + return TRUE; + ImGuiPlatformMonitor imgui_monitor; + imgui_monitor.MainPos = ImVec2((float)info.rcMonitor.left, (float)info.rcMonitor.top); + imgui_monitor.MainSize = ImVec2((float)(info.rcMonitor.right - info.rcMonitor.left), (float)(info.rcMonitor.bottom - info.rcMonitor.top)); + imgui_monitor.WorkPos = ImVec2((float)info.rcWork.left, (float)info.rcWork.top); + imgui_monitor.WorkSize = ImVec2((float)(info.rcWork.right - info.rcWork.left), (float)(info.rcWork.bottom - info.rcWork.top)); + imgui_monitor.DpiScale = ImGui_ImplWin32_GetDpiScaleForMonitor(monitor); + imgui_monitor.PlatformHandle = (void*)monitor; + ImGuiPlatformIO& io = ImGui::GetPlatformIO(); + if (info.dwFlags & MONITORINFOF_PRIMARY) + io.Monitors.push_front(imgui_monitor); + else + io.Monitors.push_back(imgui_monitor); + return TRUE; +} + +static void ImGui_ImplWin32_UpdateMonitors() +{ + ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); + ImGui::GetPlatformIO().Monitors.resize(0); + ::EnumDisplayMonitors(nullptr, nullptr, ImGui_ImplWin32_UpdateMonitors_EnumFunc, 0); + bd->WantUpdateMonitors = false; +} + +void ImGui_ImplWin32_NewFrame(const SIZE resolution) { ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT( - io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer backend. Missing call to " - "renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame()."); + ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplWin32_Init()?"); // Setup display size (every frame to accommodate for window resizing) - io.DisplaySize = {static_cast(aOutSize.cx), static_cast(aOutSize.cy)}; + io.DisplaySize = ImVec2((float)(resolution.cx), (float)(resolution.cy)); + if (bd->WantUpdateMonitors) + ImGui_ImplWin32_UpdateMonitors(); // Setup time step INT64 current_time = 0; ::QueryPerformanceCounter((LARGE_INTEGER*)¤t_time); - io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond; - g_Time = current_time; - - // Read keyboard modifiers inputs - io.KeyCtrl = (::GetKeyState(VK_CONTROL) & 0x8000) != 0; - io.KeyShift = (::GetKeyState(VK_SHIFT) & 0x8000) != 0; - io.KeyAlt = (::GetKeyState(VK_MENU) & 0x8000) != 0; - io.KeySuper = false; - // io.KeysDown[], io.MousePos, io.MouseDown[], io.MouseWheel: filled by the WndProc handler below. + io.DeltaTime = (float)(current_time - bd->Time) / bd->TicksPerSecond; + bd->Time = current_time; // Update OS mouse position - ImGui_ImplWin32_UpdateMousePos(aOutSize); + ImGui_ImplWin32_UpdateMouseData(resolution); + + // Process workarounds for known Windows key handling issues + ImGui_ImplWin32_ProcessKeyEventsWorkarounds(); // Update OS mouse cursor with the cursor requested by imgui ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor(); - if (g_LastMouseCursor != mouse_cursor) + if (bd->LastMouseCursor != mouse_cursor) { - g_LastMouseCursor = mouse_cursor; + bd->LastMouseCursor = mouse_cursor; ImGui_ImplWin32_UpdateMouseCursor(); } + + // Update game controllers (if enabled and available) + ImGui_ImplWin32_UpdateGamepads(); +} + +// There is no distinct VK_xxx for keypad enter, instead it is VK_RETURN + KF_EXTENDED, we assign it an arbitrary value to make code more readable (VK_ codes go up to 255) +#define IM_VK_KEYPAD_ENTER (VK_RETURN + 256) + +// Map VK_xxx to ImGuiKey_xxx. +static ImGuiKey ImGui_ImplWin32_VirtualKeyToImGuiKey(WPARAM wParam) +{ + switch (wParam) + { + case VK_TAB: return ImGuiKey_Tab; + case VK_LEFT: return ImGuiKey_LeftArrow; + case VK_RIGHT: return ImGuiKey_RightArrow; + case VK_UP: return ImGuiKey_UpArrow; + case VK_DOWN: return ImGuiKey_DownArrow; + case VK_PRIOR: return ImGuiKey_PageUp; + case VK_NEXT: return ImGuiKey_PageDown; + case VK_HOME: return ImGuiKey_Home; + case VK_END: return ImGuiKey_End; + case VK_INSERT: return ImGuiKey_Insert; + case VK_DELETE: return ImGuiKey_Delete; + case VK_BACK: return ImGuiKey_Backspace; + case VK_SPACE: return ImGuiKey_Space; + case VK_RETURN: return ImGuiKey_Enter; + case VK_ESCAPE: return ImGuiKey_Escape; + case VK_OEM_7: return ImGuiKey_Apostrophe; + case VK_OEM_COMMA: return ImGuiKey_Comma; + case VK_OEM_MINUS: return ImGuiKey_Minus; + case VK_OEM_PERIOD: return ImGuiKey_Period; + case VK_OEM_2: return ImGuiKey_Slash; + case VK_OEM_1: return ImGuiKey_Semicolon; + case VK_OEM_PLUS: return ImGuiKey_Equal; + case VK_OEM_4: return ImGuiKey_LeftBracket; + case VK_OEM_5: return ImGuiKey_Backslash; + case VK_OEM_6: return ImGuiKey_RightBracket; + case VK_OEM_3: return ImGuiKey_GraveAccent; + case VK_CAPITAL: return ImGuiKey_CapsLock; + case VK_SCROLL: return ImGuiKey_ScrollLock; + case VK_NUMLOCK: return ImGuiKey_NumLock; + case VK_SNAPSHOT: return ImGuiKey_PrintScreen; + case VK_PAUSE: return ImGuiKey_Pause; + case VK_NUMPAD0: return ImGuiKey_Keypad0; + case VK_NUMPAD1: return ImGuiKey_Keypad1; + case VK_NUMPAD2: return ImGuiKey_Keypad2; + case VK_NUMPAD3: return ImGuiKey_Keypad3; + case VK_NUMPAD4: return ImGuiKey_Keypad4; + case VK_NUMPAD5: return ImGuiKey_Keypad5; + case VK_NUMPAD6: return ImGuiKey_Keypad6; + case VK_NUMPAD7: return ImGuiKey_Keypad7; + case VK_NUMPAD8: return ImGuiKey_Keypad8; + case VK_NUMPAD9: return ImGuiKey_Keypad9; + case VK_DECIMAL: return ImGuiKey_KeypadDecimal; + case VK_DIVIDE: return ImGuiKey_KeypadDivide; + case VK_MULTIPLY: return ImGuiKey_KeypadMultiply; + case VK_SUBTRACT: return ImGuiKey_KeypadSubtract; + case VK_ADD: return ImGuiKey_KeypadAdd; + case IM_VK_KEYPAD_ENTER: return ImGuiKey_KeypadEnter; + case VK_LSHIFT: return ImGuiKey_LeftShift; + case VK_LCONTROL: return ImGuiKey_LeftCtrl; + case VK_LMENU: return ImGuiKey_LeftAlt; + case VK_LWIN: return ImGuiKey_LeftSuper; + case VK_RSHIFT: return ImGuiKey_RightShift; + case VK_RCONTROL: return ImGuiKey_RightCtrl; + case VK_RMENU: return ImGuiKey_RightAlt; + case VK_RWIN: return ImGuiKey_RightSuper; + case VK_APPS: return ImGuiKey_Menu; + case '0': return ImGuiKey_0; + case '1': return ImGuiKey_1; + case '2': return ImGuiKey_2; + case '3': return ImGuiKey_3; + case '4': return ImGuiKey_4; + case '5': return ImGuiKey_5; + case '6': return ImGuiKey_6; + case '7': return ImGuiKey_7; + case '8': return ImGuiKey_8; + case '9': return ImGuiKey_9; + case 'A': return ImGuiKey_A; + case 'B': return ImGuiKey_B; + case 'C': return ImGuiKey_C; + case 'D': return ImGuiKey_D; + case 'E': return ImGuiKey_E; + case 'F': return ImGuiKey_F; + case 'G': return ImGuiKey_G; + case 'H': return ImGuiKey_H; + case 'I': return ImGuiKey_I; + case 'J': return ImGuiKey_J; + case 'K': return ImGuiKey_K; + case 'L': return ImGuiKey_L; + case 'M': return ImGuiKey_M; + case 'N': return ImGuiKey_N; + case 'O': return ImGuiKey_O; + case 'P': return ImGuiKey_P; + case 'Q': return ImGuiKey_Q; + case 'R': return ImGuiKey_R; + case 'S': return ImGuiKey_S; + case 'T': return ImGuiKey_T; + case 'U': return ImGuiKey_U; + case 'V': return ImGuiKey_V; + case 'W': return ImGuiKey_W; + case 'X': return ImGuiKey_X; + case 'Y': return ImGuiKey_Y; + case 'Z': return ImGuiKey_Z; + case VK_F1: return ImGuiKey_F1; + case VK_F2: return ImGuiKey_F2; + case VK_F3: return ImGuiKey_F3; + case VK_F4: return ImGuiKey_F4; + case VK_F5: return ImGuiKey_F5; + case VK_F6: return ImGuiKey_F6; + case VK_F7: return ImGuiKey_F7; + case VK_F8: return ImGuiKey_F8; + case VK_F9: return ImGuiKey_F9; + case VK_F10: return ImGuiKey_F10; + case VK_F11: return ImGuiKey_F11; + case VK_F12: return ImGuiKey_F12; + default: return ImGuiKey_None; + } } +// Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions. +#ifndef WM_MOUSEHWHEEL +#define WM_MOUSEHWHEEL 0x020E +#endif +#ifndef DBT_DEVNODES_CHANGED +#define DBT_DEVNODES_CHANGED 0x0007 +#endif + // Win32 message handler (process Win32 mouse/keyboard inputs, etc.) -// Call from your application's message handler. -// When implementing your own backend, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if -// Dear ImGui wants to use your inputs. -// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. -// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. +// Call from your application's message handler. Keep calling your message handler unless this function returns TRUE. +// When implementing your own backend, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if Dear ImGui wants to use your inputs. +// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. +// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to Dear ImGui, and hide them from your application based on those two flags. -// PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse -// coordinates when dragging mouse outside of our window bounds. PS: We treat DBLCLK messages as regular mouse down -// messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code -// doesn't set this flag. -IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND ahWnd, UINT auMsg, WPARAM awParam, LPARAM alParam) +// PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinates when dragging mouse outside of our window bounds. +// PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag. +#if 0 +// Copy this line into your .cpp file to forward declare the function. +extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); +#endif + +// See https://learn.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages +// Prefer to call this at the top of the message handler to avoid the possibility of other Win32 calls interfering with this. +static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo() +{ + LPARAM extra_info = ::GetMessageExtraInfo(); + if ((extra_info & 0xFFFFFF80) == 0xFF515700) + return ImGuiMouseSource_Pen; + if ((extra_info & 0xFFFFFF80) == 0xFF515780) + return ImGuiMouseSource_TouchScreen; + return ImGuiMouseSource_Mouse; +} + +IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - if (ImGui::GetCurrentContext() == NULL) + if (ImGui::GetCurrentContext() == nullptr) return 0; ImGuiIO& io = ImGui::GetIO(); - switch (auMsg) + ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); + + switch (msg) { - case WM_LBUTTONDOWN: - case WM_LBUTTONDBLCLK: - case WM_RBUTTONDOWN: - case WM_RBUTTONDBLCLK: - case WM_MBUTTONDOWN: - case WM_MBUTTONDBLCLK: - case WM_XBUTTONDOWN: - case WM_XBUTTONDBLCLK: + case WM_MOUSEMOVE: + case WM_NCMOUSEMOVE: { - int button = 0; - if (auMsg == WM_LBUTTONDOWN || auMsg == WM_LBUTTONDBLCLK) + // We need to call TrackMouseEvent in order to receive WM_MOUSELEAVE events + ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo(); + const int area = (msg == WM_MOUSEMOVE) ? 1 : 2; + bd->MouseHwnd = hwnd; + if (bd->MouseTrackedArea != area) { - button = 0; + TRACKMOUSEEVENT tme_cancel = { sizeof(tme_cancel), TME_CANCEL, hwnd, 0 }; + TRACKMOUSEEVENT tme_track = { sizeof(tme_track), (DWORD)((area == 2) ? (TME_LEAVE | TME_NONCLIENT) : TME_LEAVE), hwnd, 0 }; + if (bd->MouseTrackedArea != 0) + ::TrackMouseEvent(&tme_cancel); + ::TrackMouseEvent(&tme_track); + bd->MouseTrackedArea = area; } - if (auMsg == WM_RBUTTONDOWN || auMsg == WM_RBUTTONDBLCLK) - { - button = 1; - } - if (auMsg == WM_MBUTTONDOWN || auMsg == WM_MBUTTONDBLCLK) - { - button = 2; - } - if (auMsg == WM_XBUTTONDOWN || auMsg == WM_XBUTTONDBLCLK) + POINT mouse_pos = { (LONG)GET_X_LPARAM(lParam), (LONG)GET_Y_LPARAM(lParam) }; + bool want_absolute_pos = (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) != 0; + if (msg == WM_MOUSEMOVE && want_absolute_pos) // WM_MOUSEMOVE are client-relative coordinates. + ::ClientToScreen(hwnd, &mouse_pos); + if (msg == WM_NCMOUSEMOVE && !want_absolute_pos) // WM_NCMOUSEMOVE are absolute coordinates. + ::ScreenToClient(hwnd, &mouse_pos); + io.AddMouseSourceEvent(mouse_source); + io.AddMousePosEvent((float)mouse_pos.x, (float)mouse_pos.y); + break; + } + case WM_MOUSELEAVE: + case WM_NCMOUSELEAVE: + { + const int area = (msg == WM_MOUSELEAVE) ? 1 : 2; + if (bd->MouseTrackedArea == area) { - button = (GET_XBUTTON_WPARAM(awParam) == XBUTTON1) ? 3 : 4; + if (bd->MouseHwnd == hwnd) + bd->MouseHwnd = nullptr; + bd->MouseTrackedArea = 0; + io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); } - if (!ImGui::IsAnyMouseDown() && ::GetCapture() == NULL) - ::SetCapture(ahWnd); - io.MouseDown[button] = true; + break; + } + case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: + case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: + case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: + case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: + { + ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo(); + int button = 0; + if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) { button = 0; } + if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) { button = 1; } + if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) { button = 2; } + if (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONDBLCLK) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; } + if (bd->MouseButtonsDown == 0 && ::GetCapture() == nullptr) + ::SetCapture(hwnd); + bd->MouseButtonsDown |= 1 << button; + io.AddMouseSourceEvent(mouse_source); + io.AddMouseButtonEvent(button, true); return 0; } case WM_LBUTTONUP: @@ -263,108 +686,156 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND ahWnd, UINT auMsg, WP case WM_MBUTTONUP: case WM_XBUTTONUP: { + ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo(); int button = 0; - if (auMsg == WM_LBUTTONUP) - { - button = 0; - } - if (auMsg == WM_RBUTTONUP) - { - button = 1; - } - if (auMsg == WM_MBUTTONUP) - { - button = 2; - } - if (auMsg == WM_XBUTTONUP) - { - button = (GET_XBUTTON_WPARAM(awParam) == XBUTTON1) ? 3 : 4; - } - io.MouseDown[button] = false; - if (!ImGui::IsAnyMouseDown() && ::GetCapture() == ahWnd) + if (msg == WM_LBUTTONUP) { button = 0; } + if (msg == WM_RBUTTONUP) { button = 1; } + if (msg == WM_MBUTTONUP) { button = 2; } + if (msg == WM_XBUTTONUP) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; } + bd->MouseButtonsDown &= ~(1 << button); + if (bd->MouseButtonsDown == 0 && ::GetCapture() == hwnd) ::ReleaseCapture(); + io.AddMouseSourceEvent(mouse_source); + io.AddMouseButtonEvent(button, false); return 0; } - case WM_MOUSEWHEEL: io.MouseWheel += (float)GET_WHEEL_DELTA_WPARAM(awParam) / (float)WHEEL_DELTA; return 0; - case WM_MOUSEHWHEEL: io.MouseWheelH += (float)GET_WHEEL_DELTA_WPARAM(awParam) / (float)WHEEL_DELTA; return 0; - case WM_KEYDOWN: - case WM_SYSKEYDOWN: - if (awParam < 256) - io.KeysDown[awParam] = true; + case WM_MOUSEWHEEL: + io.AddMouseWheelEvent(0.0f, (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA); + return 0; + case WM_MOUSEHWHEEL: + io.AddMouseWheelEvent(-(float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA, 0.0f); return 0; + case WM_KEYDOWN: case WM_KEYUP: + case WM_SYSKEYDOWN: case WM_SYSKEYUP: - if (awParam < 256) - io.KeysDown[awParam] = false; + { + const bool is_key_down = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN); + if (wParam < 256) + { + // Submit modifiers + ImGui_ImplWin32_UpdateKeyModifiers(); + + // Obtain virtual key code + // (keypad enter doesn't have its own... VK_RETURN with KF_EXTENDED flag means keypad enter, see IM_VK_KEYPAD_ENTER definition for details, it is mapped to ImGuiKey_KeyPadEnter.) + int vk = (int)wParam; + if ((wParam == VK_RETURN) && (HIWORD(lParam) & KF_EXTENDED)) + vk = IM_VK_KEYPAD_ENTER; + + // Submit key event + const ImGuiKey key = ImGui_ImplWin32_VirtualKeyToImGuiKey(vk); + const int scancode = (int)LOBYTE(HIWORD(lParam)); + if (key != ImGuiKey_None) + ImGui_ImplWin32_AddKeyEvent(key, is_key_down, vk, scancode); + + // Submit individual left/right modifier events + if (vk == VK_SHIFT) + { + // Important: Shift keys tend to get stuck when pressed together, missing key-up events are corrected in ImGui_ImplWin32_ProcessKeyEventsWorkarounds() + if (IsVkDown(VK_LSHIFT) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftShift, is_key_down, VK_LSHIFT, scancode); } + if (IsVkDown(VK_RSHIFT) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightShift, is_key_down, VK_RSHIFT, scancode); } + } + else if (vk == VK_CONTROL) + { + if (IsVkDown(VK_LCONTROL) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftCtrl, is_key_down, VK_LCONTROL, scancode); } + if (IsVkDown(VK_RCONTROL) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightCtrl, is_key_down, VK_RCONTROL, scancode); } + } + else if (vk == VK_MENU) + { + if (IsVkDown(VK_LMENU) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftAlt, is_key_down, VK_LMENU, scancode); } + if (IsVkDown(VK_RMENU) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightAlt, is_key_down, VK_RMENU, scancode); } + } + } + return 0; + } + case WM_SETFOCUS: + case WM_KILLFOCUS: + io.AddFocusEvent(msg == WM_SETFOCUS); return 0; case WM_CHAR: - // You can also use ToAscii()+GetKeyboardState() to retrieve characters. - if (awParam > 0 && awParam < 0x10000) - io.AddInputCharacterUTF16((unsigned short)awParam); + if (::IsWindowUnicode(hwnd)) + { + // You can also use ToAscii()+GetKeyboardState() to retrieve characters. + if (wParam > 0 && wParam < 0x10000) + io.AddInputCharacterUTF16((unsigned short)wParam); + } + else + { + wchar_t wch = 0; + ::MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (char*)&wParam, 1, &wch, 1); + io.AddInputCharacter(wch); + } return 0; case WM_SETCURSOR: - if (LOWORD(alParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor()) + // This is required to restore cursor when transitioning from e.g resize borders to client area. + if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor()) return 1; return 0; - case WM_KILLFOCUS: - std::fill_n(io.KeysDown, std::size(io.KeysDown), 0); - std::fill_n(io.MouseDown, std::size(io.MouseDown), 0); + case WM_DEVICECHANGE: +#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD + if ((UINT)wParam == DBT_DEVNODES_CHANGED) + bd->WantUpdateHasGamepad = true; +#endif + return 0; + case WM_DISPLAYCHANGE: + bd->WantUpdateMonitors = true; return 0; } return 0; } + //-------------------------------------------------------------------------------------------------------- // DPI-related helpers (optional) //-------------------------------------------------------------------------------------------------------- // - Use to enable DPI awareness without having to create an application manifest. // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps. -// - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), -// etc. -// but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at -// runtime, neither we want to require the user to have. So we dynamically select and load those functions to avoid -// dependencies. +// - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc. +// but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime, +// neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. //--------------------------------------------------------------------------------------------------------- -// This is the scheme successfully used by GLFW (from which we borrowed some of the code) and other apps aiming to be -// highly portable. ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it -// automatically. If you are trying to implement your own backend for your own engine, you may ignore that noise. +// This is the scheme successfully used by GLFW (from which we borrowed some of the code) and other apps aiming to be highly portable. +// ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it automatically. +// If you are trying to implement your own backend for your own engine, you may ignore that noise. //--------------------------------------------------------------------------------------------------------- -// Implement some of the functions and types normally declared in recent Windows SDK. -#if !defined(_versionhelpers_H_INCLUDED_) && !defined(_INC_VERSIONHELPERS) -static BOOL IsWindowsVersionOrGreater(WORD aMajor, WORD aMinor, WORD aSP) +// Perform our own check with RtlVerifyVersionInfo() instead of using functions from as they +// require a manifest to be functional for checks above 8.1. See https://github.com/ocornut/imgui/issues/4200 +static BOOL _IsWindowsVersionOrGreater(WORD major, WORD minor, WORD) { - OSVERSIONINFOEXW osvi = {sizeof(osvi), aMajor, aMinor, 0, 0, {0}, aSP, 0, 0, 0, 0}; - DWORD mask = VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR; - ULONGLONG cond = ::VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL); - cond = ::VerSetConditionMask(cond, VER_MINORVERSION, VER_GREATER_EQUAL); - cond = ::VerSetConditionMask(cond, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); - return ::VerifyVersionInfoW(&osvi, mask, cond); + typedef LONG(WINAPI* PFN_RtlVerifyVersionInfo)(OSVERSIONINFOEXW*, ULONG, ULONGLONG); + static PFN_RtlVerifyVersionInfo RtlVerifyVersionInfoFn = nullptr; + if (RtlVerifyVersionInfoFn == nullptr) + if (HMODULE ntdllModule = ::GetModuleHandleA("ntdll.dll")) + RtlVerifyVersionInfoFn = (PFN_RtlVerifyVersionInfo)GetProcAddress(ntdllModule, "RtlVerifyVersionInfo"); + if (RtlVerifyVersionInfoFn == nullptr) + return FALSE; + + RTL_OSVERSIONINFOEXW versionInfo = { }; + ULONGLONG conditionMask = 0; + versionInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW); + versionInfo.dwMajorVersion = major; + versionInfo.dwMinorVersion = minor; + VER_SET_CONDITION(conditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL); + VER_SET_CONDITION(conditionMask, VER_MINORVERSION, VER_GREATER_EQUAL); + return (RtlVerifyVersionInfoFn(&versionInfo, VER_MAJORVERSION | VER_MINORVERSION, conditionMask) == 0) ? TRUE : FALSE; } -#define IsWindows8Point1OrGreater() IsWindowsVersionOrGreater(HIBYTE(0x0602), LOBYTE(0x0602), 0) // _WIN32_WINNT_WINBLUE -#endif + +#define _IsWindowsVistaOrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0600), LOBYTE(0x0600), 0) // _WIN32_WINNT_VISTA +#define _IsWindows8OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0602), LOBYTE(0x0602), 0) // _WIN32_WINNT_WIN8 +#define _IsWindows8Point1OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0603), LOBYTE(0x0603), 0) // _WIN32_WINNT_WINBLUE +#define _IsWindows10OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0A00), LOBYTE(0x0A00), 0) // _WIN32_WINNT_WINTHRESHOLD / _WIN32_WINNT_WIN10 #ifndef DPI_ENUMS_DECLARED -typedef enum -{ - PROCESS_DPI_UNAWARE = 0, - PROCESS_SYSTEM_DPI_AWARE = 1, - PROCESS_PER_MONITOR_DPI_AWARE = 2 -} PROCESS_DPI_AWARENESS; -typedef enum -{ - MDT_EFFECTIVE_DPI = 0, - MDT_ANGULAR_DPI = 1, - MDT_RAW_DPI = 2, - MDT_DEFAULT = MDT_EFFECTIVE_DPI -} MONITOR_DPI_TYPE; +typedef enum { PROCESS_DPI_UNAWARE = 0, PROCESS_SYSTEM_DPI_AWARE = 1, PROCESS_PER_MONITOR_DPI_AWARE = 2 } PROCESS_DPI_AWARENESS; +typedef enum { MDT_EFFECTIVE_DPI = 0, MDT_ANGULAR_DPI = 1, MDT_RAW_DPI = 2, MDT_DEFAULT = MDT_EFFECTIVE_DPI } MONITOR_DPI_TYPE; #endif #ifndef _DPI_AWARENESS_CONTEXTS_ DECLARE_HANDLE(DPI_AWARENESS_CONTEXT); -#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE (DPI_AWARENESS_CONTEXT) - 3 +#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE (DPI_AWARENESS_CONTEXT)-3 #endif #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 -#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 (DPI_AWARENESS_CONTEXT) - 4 +#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 (DPI_AWARENESS_CONTEXT)-4 #endif typedef HRESULT(WINAPI* PFN_SetProcessDpiAwareness)(PROCESS_DPI_AWARENESS); // Shcore.lib + dll, Windows 8.1+ typedef HRESULT(WINAPI* PFN_GetDpiForMonitor)(HMONITOR, MONITOR_DPI_TYPE, UINT*, UINT*); // Shcore.lib + dll, Windows 8.1+ @@ -373,18 +844,22 @@ typedef DPI_AWARENESS_CONTEXT(WINAPI* PFN_SetThreadDpiAwarenessContext)(DPI_AWAR // Helper function to enable DPI awareness without setting up a manifest void ImGui_ImplWin32_EnableDpiAwareness() { - // if (IsWindows10OrGreater()) // This needs a manifest to succeed. Instead we try to grab the function pointer! + // Make sure monitors will be updated with latest correct scaling + if (ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData()) + bd->WantUpdateMonitors = true; + + if (_IsWindows10OrGreater()) { - static HINSTANCE user32_dll = ::LoadLibrary(TEXT("user32.dll")); // Reference counted per-process + static HINSTANCE user32_dll = ::LoadLibraryA("user32.dll"); // Reference counted per-process if (PFN_SetThreadDpiAwarenessContext SetThreadDpiAwarenessContextFn = (PFN_SetThreadDpiAwarenessContext)::GetProcAddress(user32_dll, "SetThreadDpiAwarenessContext")) { SetThreadDpiAwarenessContextFn(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); return; } } - if (IsWindows8Point1OrGreater()) + if (_IsWindows8Point1OrGreater()) { - static HINSTANCE shcore_dll = ::LoadLibrary(TEXT("shcore.dll")); // Reference counted per-process + static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process if (PFN_SetProcessDpiAwareness SetProcessDpiAwarenessFn = (PFN_SetProcessDpiAwareness)::GetProcAddress(shcore_dll, "SetProcessDpiAwareness")) { SetProcessDpiAwarenessFn(PROCESS_PER_MONITOR_DPI_AWARE); @@ -397,36 +872,423 @@ void ImGui_ImplWin32_EnableDpiAwareness() } #if defined(_MSC_VER) && !defined(NOGDI) -#pragma comment(lib, "gdi32") // Link with gdi32.lib for GetDeviceCaps() +#pragma comment(lib, "gdi32") // Link with gdi32.lib for GetDeviceCaps(). MinGW will require linking with '-lgdi32' #endif -float ImGui_ImplWin32_GetDpiScaleForMonitor(HMONITOR ahMonitor) +float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) { UINT xdpi = 96, ydpi = 96; - static BOOL bIsWindows8Point1OrGreater = IsWindows8Point1OrGreater(); - if (bIsWindows8Point1OrGreater) + if (_IsWindows8Point1OrGreater()) { - static HINSTANCE shcore_dll = ::LoadLibrary(TEXT("shcore.dll")); // Reference counted per-process - if (PFN_GetDpiForMonitor GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor")) - GetDpiForMonitorFn(ahMonitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi); + static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process + static PFN_GetDpiForMonitor GetDpiForMonitorFn = nullptr; + if (GetDpiForMonitorFn == nullptr && shcore_dll != nullptr) + GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor"); + if (GetDpiForMonitorFn != nullptr) + { + GetDpiForMonitorFn((HMONITOR)monitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi); + IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert! + return xdpi / 96.0f; + } } #ifndef NOGDI + const HDC dc = ::GetDC(nullptr); + xdpi = ::GetDeviceCaps(dc, LOGPIXELSX); + ydpi = ::GetDeviceCaps(dc, LOGPIXELSY); + IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert! + ::ReleaseDC(nullptr, dc); +#endif + return xdpi / 96.0f; +} + +float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd) +{ + HMONITOR monitor = ::MonitorFromWindow((HWND)hwnd, MONITOR_DEFAULTTONEAREST); + return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor); +} + +//--------------------------------------------------------------------------------------------------------- +// Transparency related helpers (optional) +//-------------------------------------------------------------------------------------------------------- + +#if defined(_MSC_VER) +#pragma comment(lib, "dwmapi") // Link with dwmapi.lib. MinGW will require linking with '-ldwmapi' +#endif + +// [experimental] +// Borrowed from GLFW's function updateFramebufferTransparency() in src/win32_window.c +// (the Dwm* functions are Vista era functions but we are borrowing logic from GLFW) +void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd) +{ + if (!_IsWindowsVistaOrGreater()) + return; + + BOOL composition; + if (FAILED(::DwmIsCompositionEnabled(&composition)) || !composition) + return; + + BOOL opaque; + DWORD color; + if (_IsWindows8OrGreater() || (SUCCEEDED(::DwmGetColorizationColor(&color, &opaque)) && !opaque)) + { + HRGN region = ::CreateRectRgn(0, 0, -1, -1); + DWM_BLURBEHIND bb = {}; + bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION; + bb.hRgnBlur = region; + bb.fEnable = TRUE; + ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb); + ::DeleteObject(region); + } + else + { + DWM_BLURBEHIND bb = {}; + bb.dwFlags = DWM_BB_ENABLE; + ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb); + } +} + +//--------------------------------------------------------------------------------------------------------- +// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT +// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously. +// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first.. +//-------------------------------------------------------------------------------------------------------- + +// Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data. +struct ImGui_ImplWin32_ViewportData +{ + HWND Hwnd; + HWND HwndParent; + bool HwndOwned; + DWORD DwStyle; + DWORD DwExStyle; + + ImGui_ImplWin32_ViewportData() { Hwnd = HwndParent = nullptr; HwndOwned = false; DwStyle = DwExStyle = 0; } + ~ImGui_ImplWin32_ViewportData() { IM_ASSERT(Hwnd == nullptr); } +}; + +static void ImGui_ImplWin32_GetWin32StyleFromViewportFlags(ImGuiViewportFlags flags, DWORD* out_style, DWORD* out_ex_style) +{ + if (flags & ImGuiViewportFlags_NoDecoration) + *out_style = WS_POPUP; + else + *out_style = WS_OVERLAPPEDWINDOW; + + if (flags & ImGuiViewportFlags_NoTaskBarIcon) + *out_ex_style = WS_EX_TOOLWINDOW; + else + *out_ex_style = WS_EX_APPWINDOW; + + if (flags & ImGuiViewportFlags_TopMost) + *out_ex_style |= WS_EX_TOPMOST; +} + +static HWND ImGui_ImplWin32_GetHwndFromViewportID(ImGuiID viewport_id) +{ + if (viewport_id != 0) + if (ImGuiViewport* viewport = ImGui::FindViewportByID(viewport_id)) + return (HWND)viewport->PlatformHandle; + return nullptr; +} + +static void ImGui_ImplWin32_CreateWindow(ImGuiViewport* viewport) +{ + ImGui_ImplWin32_ViewportData* vd = IM_NEW(ImGui_ImplWin32_ViewportData)(); + viewport->PlatformUserData = vd; + + // Select style and parent window + ImGui_ImplWin32_GetWin32StyleFromViewportFlags(viewport->Flags, &vd->DwStyle, &vd->DwExStyle); + vd->HwndParent = ImGui_ImplWin32_GetHwndFromViewportID(viewport->ParentViewportId); + + // Create window + RECT rect = { (LONG)viewport->Pos.x, (LONG)viewport->Pos.y, (LONG)(viewport->Pos.x + viewport->Size.x), (LONG)(viewport->Pos.y + viewport->Size.y) }; + ::AdjustWindowRectEx(&rect, vd->DwStyle, FALSE, vd->DwExStyle); + vd->Hwnd = ::CreateWindowEx( + vd->DwExStyle, _T("ImGui Platform"), _T("Untitled"), vd->DwStyle, // Style, class name, window name + rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, // Window area + vd->HwndParent, nullptr, ::GetModuleHandle(nullptr), nullptr); // Owner window, Menu, Instance, Param + vd->HwndOwned = true; + viewport->PlatformRequestResize = false; + viewport->PlatformHandle = viewport->PlatformHandleRaw = vd->Hwnd; +} + +static void ImGui_ImplWin32_DestroyWindow(ImGuiViewport* viewport) +{ + ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); + if (ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData) + { + if (::GetCapture() == vd->Hwnd) + { + // Transfer capture so if we started dragging from a window that later disappears, we'll still receive the MOUSEUP event. + ::ReleaseCapture(); + ::SetCapture(bd->hWnd); + } + if (vd->Hwnd && vd->HwndOwned) + ::DestroyWindow(vd->Hwnd); + vd->Hwnd = nullptr; + IM_DELETE(vd); + } + viewport->PlatformUserData = viewport->PlatformHandle = nullptr; +} + +static void ImGui_ImplWin32_ShowWindow(ImGuiViewport* viewport) +{ + ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing) + ::ShowWindow(vd->Hwnd, SW_SHOWNA); + else + ::ShowWindow(vd->Hwnd, SW_SHOW); +} + +static void ImGui_ImplWin32_UpdateWindow(ImGuiViewport* viewport) +{ + ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + + // Update Win32 parent if it changed _after_ creation + // Unlike style settings derived from configuration flags, this is more likely to change for advanced apps that are manipulating ParentViewportID manually. + HWND new_parent = ImGui_ImplWin32_GetHwndFromViewportID(viewport->ParentViewportId); + if (new_parent != vd->HwndParent) + { + // Win32 windows can either have a "Parent" (for WS_CHILD window) or an "Owner" (which among other thing keeps window above its owner). + // Our Dear Imgui-side concept of parenting only mostly care about what Win32 call "Owner". + // The parent parameter of CreateWindowEx() sets up Parent OR Owner depending on WS_CHILD flag. In our case an Owner as we never use WS_CHILD. + // Calling ::SetParent() here would be incorrect: it will create a full child relation, alter coordinate system and clipping. + // Calling ::SetWindowLongPtr() with GWLP_HWNDPARENT seems correct although poorly documented. + // https://devblogs.microsoft.com/oldnewthing/20100315-00/?p=14613 + vd->HwndParent = new_parent; + ::SetWindowLongPtr(vd->Hwnd, GWLP_HWNDPARENT, (LONG_PTR)vd->HwndParent); + } + + // (Optional) Update Win32 style if it changed _after_ creation. + // Generally they won't change unless configuration flags are changed, but advanced uses (such as manually rewriting viewport flags) make this useful. + DWORD new_style; + DWORD new_ex_style; + ImGui_ImplWin32_GetWin32StyleFromViewportFlags(viewport->Flags, &new_style, &new_ex_style); + + // Only reapply the flags that have been changed from our point of view (as other flags are being modified by Windows) + if (vd->DwStyle != new_style || vd->DwExStyle != new_ex_style) + { + // (Optional) Update TopMost state if it changed _after_ creation + bool top_most_changed = (vd->DwExStyle & WS_EX_TOPMOST) != (new_ex_style & WS_EX_TOPMOST); + HWND insert_after = top_most_changed ? ((viewport->Flags & ImGuiViewportFlags_TopMost) ? HWND_TOPMOST : HWND_NOTOPMOST) : 0; + UINT swp_flag = top_most_changed ? 0 : SWP_NOZORDER; + + // Apply flags and position (since it is affected by flags) + vd->DwStyle = new_style; + vd->DwExStyle = new_ex_style; + ::SetWindowLong(vd->Hwnd, GWL_STYLE, vd->DwStyle); + ::SetWindowLong(vd->Hwnd, GWL_EXSTYLE, vd->DwExStyle); + RECT rect = { (LONG)viewport->Pos.x, (LONG)viewport->Pos.y, (LONG)(viewport->Pos.x + viewport->Size.x), (LONG)(viewport->Pos.y + viewport->Size.y) }; + ::AdjustWindowRectEx(&rect, vd->DwStyle, FALSE, vd->DwExStyle); // Client to Screen + ::SetWindowPos(vd->Hwnd, insert_after, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, swp_flag | SWP_NOACTIVATE | SWP_FRAMECHANGED); + ::ShowWindow(vd->Hwnd, SW_SHOWNA); // This is necessary when we alter the style + viewport->PlatformRequestMove = viewport->PlatformRequestResize = true; + } +} + +static ImVec2 ImGui_ImplWin32_GetWindowPos(ImGuiViewport* viewport) +{ + ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + POINT pos = { 0, 0 }; + ::ClientToScreen(vd->Hwnd, &pos); + return ImVec2((float)pos.x, (float)pos.y); +} + +static void ImGui_ImplWin32_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos) +{ + ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + RECT rect = { (LONG)pos.x, (LONG)pos.y, (LONG)pos.x, (LONG)pos.y }; + ::AdjustWindowRectEx(&rect, vd->DwStyle, FALSE, vd->DwExStyle); + ::SetWindowPos(vd->Hwnd, nullptr, rect.left, rect.top, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE); +} + +static ImVec2 ImGui_ImplWin32_GetWindowSize(ImGuiViewport* viewport) +{ + ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + RECT rect; + ::GetClientRect(vd->Hwnd, &rect); + return ImVec2(float(rect.right - rect.left), float(rect.bottom - rect.top)); +} + +static void ImGui_ImplWin32_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) +{ + ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + RECT rect = { 0, 0, (LONG)size.x, (LONG)size.y }; + ::AdjustWindowRectEx(&rect, vd->DwStyle, FALSE, vd->DwExStyle); // Client to Screen + ::SetWindowPos(vd->Hwnd, nullptr, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE); +} + +static void ImGui_ImplWin32_SetWindowFocus(ImGuiViewport* viewport) +{ + ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + ::BringWindowToTop(vd->Hwnd); + ::SetForegroundWindow(vd->Hwnd); + ::SetFocus(vd->Hwnd); +} + +static bool ImGui_ImplWin32_GetWindowFocus(ImGuiViewport* viewport) +{ + ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + return ::GetForegroundWindow() == vd->Hwnd; +} + +static bool ImGui_ImplWin32_GetWindowMinimized(ImGuiViewport* viewport) +{ + ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + return ::IsIconic(vd->Hwnd) != 0; +} + +static void ImGui_ImplWin32_SetWindowTitle(ImGuiViewport* viewport, const char* title) +{ + // ::SetWindowTextA() doesn't properly handle UTF-8 so we explicitely convert our string. + ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + int n = ::MultiByteToWideChar(CP_UTF8, 0, title, -1, nullptr, 0); + ImVector title_w; + title_w.resize(n); + ::MultiByteToWideChar(CP_UTF8, 0, title, -1, title_w.Data, n); + ::SetWindowTextW(vd->Hwnd, title_w.Data); +} + +static void ImGui_ImplWin32_SetWindowAlpha(ImGuiViewport* viewport, float alpha) +{ + ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + IM_ASSERT(alpha >= 0.0f && alpha <= 1.0f); + if (alpha < 1.0f) + { + DWORD style = ::GetWindowLongW(vd->Hwnd, GWL_EXSTYLE) | WS_EX_LAYERED; + ::SetWindowLongW(vd->Hwnd, GWL_EXSTYLE, style); + ::SetLayeredWindowAttributes(vd->Hwnd, 0, (BYTE)(255 * alpha), LWA_ALPHA); + } else { - const HDC dc = ::GetDC(NULL); - xdpi = ::GetDeviceCaps(dc, LOGPIXELSX); - ydpi = ::GetDeviceCaps(dc, LOGPIXELSY); - ::ReleaseDC(NULL, dc); + DWORD style = ::GetWindowLongW(vd->Hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED; + ::SetWindowLongW(vd->Hwnd, GWL_EXSTYLE, style); } +} + +static float ImGui_ImplWin32_GetWindowDpiScale(ImGuiViewport* viewport) +{ + ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + return ImGui_ImplWin32_GetDpiScaleForHwnd(vd->Hwnd); +} + +// FIXME-DPI: Testing DPI related ideas +static void ImGui_ImplWin32_OnChangedViewport(ImGuiViewport* viewport) +{ + (void)viewport; +#if 0 + ImGuiStyle default_style; + //default_style.WindowPadding = ImVec2(0, 0); + //default_style.WindowBorderSize = 0.0f; + //default_style.ItemSpacing.y = 3.0f; + //default_style.FramePadding = ImVec2(0, 0); + default_style.ScaleAllSizes(viewport->DpiScale); + ImGuiStyle& style = ImGui::GetStyle(); + style = default_style; #endif - IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert! - return xdpi / 96.0f; } -float ImGui_ImplWin32_GetDpiScaleForHwnd(HWND ahWnd) +static LRESULT CALLBACK ImGui_ImplWin32_WndProcHandler_PlatformWindow(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { - HMONITOR monitor = ::MonitorFromWindow(ahWnd, MONITOR_DEFAULTTONEAREST); - return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor); + if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) + return true; + + if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle((void*)hWnd)) + { + switch (msg) + { + case WM_CLOSE: + viewport->PlatformRequestClose = true; + return 0; + case WM_MOVE: + viewport->PlatformRequestMove = true; + break; + case WM_SIZE: + viewport->PlatformRequestResize = true; + break; + case WM_MOUSEACTIVATE: + if (viewport->Flags & ImGuiViewportFlags_NoFocusOnClick) + return MA_NOACTIVATE; + break; + case WM_NCHITTEST: + // Let mouse pass-through the window. This will allow the backend to call io.AddMouseViewportEvent() correctly. (which is optional). + // The ImGuiViewportFlags_NoInputs flag is set while dragging a viewport, as want to detect the window behind the one we are dragging. + // If you cannot easily access those viewport flags from your windowing/event code: you may manually synchronize its state e.g. in + // your main loop after calling UpdatePlatformWindows(). Iterate all viewports/platform windows and pass the flag to your windowing system. + if (viewport->Flags & ImGuiViewportFlags_NoInputs) + return HTTRANSPARENT; + break; + } + } + + return DefWindowProc(hWnd, msg, wParam, lParam); +} + +static void ImGui_ImplWin32_InitPlatformInterface(bool platform_has_own_dc) +{ + WNDCLASSEX wcex; + wcex.cbSize = sizeof(WNDCLASSEX); + wcex.style = CS_HREDRAW | CS_VREDRAW | (platform_has_own_dc ? CS_OWNDC : 0); + wcex.lpfnWndProc = ImGui_ImplWin32_WndProcHandler_PlatformWindow; + wcex.cbClsExtra = 0; + wcex.cbWndExtra = 0; + wcex.hInstance = ::GetModuleHandle(nullptr); + wcex.hIcon = nullptr; + wcex.hCursor = nullptr; + wcex.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1); + wcex.lpszMenuName = nullptr; + wcex.lpszClassName = _T("ImGui Platform"); + wcex.hIconSm = nullptr; + ::RegisterClassEx(&wcex); + + ImGui_ImplWin32_UpdateMonitors(); + + // Register platform interface (will be coupled with a renderer interface) + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Platform_CreateWindow = ImGui_ImplWin32_CreateWindow; + platform_io.Platform_DestroyWindow = ImGui_ImplWin32_DestroyWindow; + platform_io.Platform_ShowWindow = ImGui_ImplWin32_ShowWindow; + platform_io.Platform_SetWindowPos = ImGui_ImplWin32_SetWindowPos; + platform_io.Platform_GetWindowPos = ImGui_ImplWin32_GetWindowPos; + platform_io.Platform_SetWindowSize = ImGui_ImplWin32_SetWindowSize; + platform_io.Platform_GetWindowSize = ImGui_ImplWin32_GetWindowSize; + platform_io.Platform_SetWindowFocus = ImGui_ImplWin32_SetWindowFocus; + platform_io.Platform_GetWindowFocus = ImGui_ImplWin32_GetWindowFocus; + platform_io.Platform_GetWindowMinimized = ImGui_ImplWin32_GetWindowMinimized; + platform_io.Platform_SetWindowTitle = ImGui_ImplWin32_SetWindowTitle; + platform_io.Platform_SetWindowAlpha = ImGui_ImplWin32_SetWindowAlpha; + platform_io.Platform_UpdateWindow = ImGui_ImplWin32_UpdateWindow; + platform_io.Platform_GetWindowDpiScale = ImGui_ImplWin32_GetWindowDpiScale; // FIXME-DPI + platform_io.Platform_OnChangedViewport = ImGui_ImplWin32_OnChangedViewport; // FIXME-DPI + + // Register main window handle (which is owned by the main application, not by us) + // This is mostly for simplicity and consistency, so that our code (e.g. mouse handling etc.) can use same logic for main and secondary viewports. + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); + ImGui_ImplWin32_ViewportData* vd = IM_NEW(ImGui_ImplWin32_ViewportData)(); + vd->Hwnd = bd->hWnd; + vd->HwndOwned = false; + main_viewport->PlatformUserData = vd; + main_viewport->PlatformHandle = (void*)bd->hWnd; +} + +static void ImGui_ImplWin32_ShutdownPlatformInterface() +{ + ::UnregisterClass(_T("ImGui Platform"), ::GetModuleHandle(nullptr)); + ImGui::DestroyPlatformWindows(); } //--------------------------------------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/src/imgui_impl/win32.h b/src/imgui_impl/win32.h index be3d8889..ee233a14 100644 --- a/src/imgui_impl/win32.h +++ b/src/imgui_impl/win32.h @@ -1,40 +1,50 @@ -// dear imgui: Platform Backend for Windows (standard windows API for 32 and 64 bits applications) +// dear imgui: Platform Backend for Windows (standard windows API for 32-bits AND 64-bits applications) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // Implemented features: // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) -// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= -// ImGuiConfigFlags_NoMouseCursorChange'. [X] Platform: Keyboard arrays indexed using VK_* Virtual Key Codes, e.g. -// ImGui::IsKeyPressed(VK_SPACE). [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= -// ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] +// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. -// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Read online: https://github.com/ocornut/imgui/tree/master/docs #pragma once -#include "imgui.h" // IMGUI_IMPL_API +#include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE -IMGUI_IMPL_API bool ImGui_ImplWin32_Init(HWND ahWnd); -IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown(); -IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame(SIZE aOutSize); - -// Configuration -// - Disable gamepad support or linking with xinput.lib -// #define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD -// #define IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT +IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd); +IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd); +IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame(SIZE resolution); // Win32 message handler your application need to call. -extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND ahWnd, UINT auMsg, WPARAM awParam, LPARAM alParam); +// - Intentionally commented out in a '#if 0' block to avoid dragging dependencies on from this helper. +// - You should COPY the line below into your .cpp code to forward declare the function and then you can call it. +// - Call from your application's message handler. Keep calling your message handler unless this function returns TRUE. + +#if 0 +extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); +#endif // DPI-related helpers (optional) // - Use to enable DPI awareness without having to create an application manifest. // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps. -// - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), -// etc. -// but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at -// runtime, neither we want to require the user to have. So we dynamically select and load those functions to avoid -// dependencies. -IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness(); -IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(HWND ahWnd); -IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(HMONITOR ahMonitor); +// - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc. +// but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime, +// neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. +IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness(); +IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd); // HWND hwnd +IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor); // HMONITOR monitor + +// Transparency related helpers (optional) [experimental] +// - Use to enable alpha compositing transparency with the desktop. +// - Use together with e.g. clearing your framebuffer with zero-alpha. +IMGUI_IMPL_API void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd); // HWND hwnd + +#endif // #ifndef IMGUI_DISABLE diff --git a/xmake.lua b/xmake.lua index 0cadd55f..70b1dc63 100644 --- a/xmake.lua +++ b/xmake.lua @@ -85,7 +85,7 @@ target("cyber_engine_tweaks") add_files("src/**.cpp") add_headerfiles("src/**.h", "build/CETVersion.h") add_includedirs("src/", "build/") - add_syslinks("User32", "Version", "d3d11", "Dwrite") + add_syslinks("User32", "Version", "d3d11", "Dwrite", "DXGI") add_packages("spdlog", "nlohmann_json", "minhook", "hopscotch-map", --[["imgui",]] "mem", "sol2", "tiltedcore", "sqlite3", "openrestry-luajit", "xbyak", "stb") add_deps("imgui","RED4ext.SDK") add_configfiles("src/CETVersion.h.in")