diff --git a/openVulkanoCpp/Scene/UI/UiFont.cpp b/openVulkanoCpp/Scene/UI/UiFont.cpp new file mode 100644 index 0000000..f315a49 --- /dev/null +++ b/openVulkanoCpp/Scene/UI/UiFont.cpp @@ -0,0 +1,47 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ + +#include "UiFont.hpp" +#include +#include "Host/FontResolver.hpp" +#include +#include + +namespace OpenVulkano::Scene::UI +{ + void UiFont::SetActive() + { + if (!m_font) MakeFont(); + if (m_font) ImGui::PushFont(m_font); + } + + void UiFont::MakeFont() + { + if (m_pixelSize <= 0 || m_font) return; + auto fontData = FontResolver::GetFontData(m_name); + if (!fontData) + { + Logger::APP->warn("Failed to find font {}", m_name); + m_pixelSize = 0; + return; + } + ImFontConfig conf; + strlcpy(conf.Name, m_name.data(), std::min(m_name.size(), sizeof(conf.Name))); + conf.FontDataOwnedByAtlas = false; + conf.RasterizerDensity = 3; // TODO check window scale factor + ImGuiIO& io = ImGui::GetIO(); + m_font = io.Fonts->AddFontFromMemoryTTF(fontData.Data(), static_cast(fontData.Size()), m_pixelSize, &conf); + } + + UiFont* UiFont::GetFont(const std::string& fontName, int pixelSize) + { + static std::map, UiFont> FONTS; + UiFont& font = FONTS[{fontName, pixelSize}]; + if (font.m_pixelSize != pixelSize) font = UiFont(fontName, (float)pixelSize); + font.MakeFont(); + return &font; + } +} diff --git a/openVulkanoCpp/Scene/UI/UiFont.hpp b/openVulkanoCpp/Scene/UI/UiFont.hpp new file mode 100644 index 0000000..2c661b9 --- /dev/null +++ b/openVulkanoCpp/Scene/UI/UiFont.hpp @@ -0,0 +1,39 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +struct ImFont; + +namespace OpenVulkano::Scene::UI +{ + class UiFont final + { + ImFont* m_font = nullptr; + std::string m_name; + float m_pixelSize; + + void MakeFont(); + + public: + UiFont() : m_pixelSize(0) {} + + UiFont(const std::string& font, float pixelSize = 16) + : m_name(font), m_pixelSize(pixelSize) + {} + + void Push() { SetActive(); } + void SetActive(); + + [[nodiscard]] const std::string& GetFontName() const { return m_name; } + + [[nodiscard]] float GetPixelSize() const { return m_pixelSize; } + + [[nodiscard]] static UiFont* GetFont(const std::string& font, int pixelSize = 16); + }; +};