Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat: Add BitmapFont support and modular font compilation

esengine67ccd1789468
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 57f14cd11..d5c1a9ef2 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -12,6 +12,10 @@ option(ES_BUILD_EXAMPLES "Build examples" ON)
option(ES_BUILD_TESTS "Build tests" ON)
option(ES_BUILD_EDITOR "Build editor (native only)" OFF)
+# Feature options (modular compilation)
+option(ES_FEATURE_SDF_FONT "Enable SDF font rendering (requires FreeType)" ON)
+option(ES_FEATURE_BITMAP_FONT "Enable bitmap font rendering (lightweight)" ON)
+
# Include custom CMake modules
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
include(ESEngineConfig)
@@ -41,7 +45,6 @@ set(ESENGINE_SOURCES
# UI System
src/esengine/ui/UIContext.cpp
src/esengine/ui/rendering/UIBatchRenderer.cpp
- src/esengine/ui/font/SDFFont.cpp
src/esengine/ui/layout/StackLayout.cpp
src/esengine/ui/layout/WrapLayout.cpp
src/esengine/ui/widgets/Widget.cpp
@@ -62,6 +65,15 @@ set(ESENGINE_SOURCES
src/esengine/ui/docking/DockLayoutSerializer.cpp
)
+# Font sources (conditional)
+if(ES_FEATURE_SDF_FONT)
+ list(APPEND ESENGINE_SOURCES src/esengine/ui/font/SDFFont.cpp)
+endif()
+
+if(ES_FEATURE_BITMAP_FONT)
+ list(APPEND ESENGINE_SOURCES src/esengine/ui/font/BitmapFont.cpp)
+endif()
+
set(ESENGINE_HEADERS
src/esengine/ESEngine.hpp
src/esengine/core/Types.hpp
@@ -111,7 +123,6 @@ set(ESENGINE_HEADERS
src/esengine/ui/layout/Layout.hpp
src/esengine/ui/layout/StackLayout.hpp
src/esengine/ui/rendering/UIBatchRenderer.hpp
- src/esengine/ui/font/SDFFont.hpp
src/esengine/ui/icons/Icons.hpp
src/esengine/ui/widgets/Widget.hpp
src/esengine/ui/widgets/Panel.hpp
@@ -133,6 +144,15 @@ set(ESENGINE_HEADERS
src/esengine/ui/docking/DockLayoutSerializer.hpp
)
+# Font headers (conditional)
+if(ES_FEATURE_SDF_FONT)
+ list(APPEND ESENGINE_HEADERS src/esengine/ui/font/SDFFont.hpp)
+endif()
+
+if(ES_FEATURE_BITMAP_FONT)
+ list(APPEND ESENGINE_HEADERS src/esengine/ui/font/BitmapFont.hpp)
+endif()
+
# Platform-specific sources
if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
list(APPEND ESENGINE_SOURCES
@@ -244,8 +264,19 @@ if(NOT ES_BUILD_WEB AND NOT ES_BUILD_WXGAME)
target_include_directories(esengine SYSTEM PRIVATE ${QUICKJS_INCLUDE_DIR})
endif()
-target_link_libraries(esengine PUBLIC glm freetype)
-target_include_directories(esengine PUBLIC ${CMAKE_SOURCE_DIR}/third_party/freetype/include)
+# Core dependencies
+target_link_libraries(esengine PUBLIC glm)
+
+# FreeType dependency (only needed for SDF fonts)
+if(ES_FEATURE_SDF_FONT)
+ target_link_libraries(esengine PUBLIC freetype)
+ target_include_directories(esengine PUBLIC ${CMAKE_SOURCE_DIR}/third_party/freetype/include)
+ target_compile_definitions(esengine PUBLIC ES_FEATURE_SDF_FONT=1)
+endif()
+
+if(ES_FEATURE_BITMAP_FONT)
+ target_compile_definitions(esengine PUBLIC ES_FEATURE_BITMAP_FONT=1)
+endif()
# Platform-specific settings
if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
diff --git a/src/esengine/ui/UIContext.cpp b/src/esengine/ui/UIContext.cpp
index e8ad402ea..255ee88bd 100644
--- a/src/esengine/ui/UIContext.cpp
+++ b/src/esengine/ui/UIContext.cpp
@@ -14,10 +14,17 @@
#include "../events/Dispatcher.hpp"
#include "../renderer/RenderCommand.hpp"
#include "../renderer/RenderContext.hpp"
-#include "font/SDFFont.hpp"
#include "rendering/UIBatchRenderer.hpp"
#include "widgets/Widget.hpp"
+#if ES_FEATURE_SDF_FONT
+#include "font/SDFFont.hpp"
+#endif
+
+#if ES_FEATURE_BITMAP_FONT
+#include "font/BitmapFont.hpp"
+#endif
+
#include <glm/gtc/matrix_transform.hpp>
namespace esengine::ui {
@@ -55,7 +62,12 @@ void UIContext::shutdown() {
if (!initialized_) return;
root_.reset();
+#if ES_FEATURE_SDF_FONT
fonts_.clear();
+#endif
+#if ES_FEATURE_BITMAP_FONT
+ bitmapFonts_.clear();
+#endif
theme_.reset();
if (renderer_) {
@@ -107,9 +119,10 @@ void UIContext::setTheme(Unique<Theme> theme) {
}
// =============================================================================
-// Font Management (SDF-based)
+// Font Management
// =============================================================================
+#if ES_FEATURE_SDF_FONT
SDFFont* UIContext::loadFont(const std::string& name, const std::string& path, f32 fontSize,
f32 sdfSpread) {
auto font = SDFFont::create(path, fontSize, sdfSpread);
@@ -140,6 +153,36 @@ SDFFont* UIContext::getDefaultFont() {
SDFFont* UIContext::getIconFont() {
return getFont("icons");
}
+#endif // ES_FEATURE_SDF_FONT
+
+#if ES_FEATURE_BITMAP_FONT
+BitmapFont* UIContext::loadBitmapFont(const std::string& name, const std::string& atlasPath,
+ const std::string& metricsPath) {
+ auto font = BitmapFont::load(atlasPath, metricsPath);
+ if (!font) {
+ ES_LOG_ERROR("Failed to load bitmap font: {} / {}", atlasPath, metricsPath);
+ return nullptr;
+ }
+
+ BitmapFont* ptr = font.get();
+ bitmapFonts_[name] = std::move(font);
+
+ ES_LOG_INFO("Loaded bitmap font '{}' from {}", name, atlasPath);
+ return ptr;
+}
+
+BitmapFont* UIContext::getBitmapFont(const std::string& name) {
+ auto it = bitmapFonts_.find(name);
+ if (it != bitmapFonts_.end()) {
+ return it->second.get();
+ }
+ return nullptr;
+}
+
+BitmapFont* UIContext::getDefaultBitmapFont() {
+ return getBitmapFont(defaultFontName_);
+}
+#endif // ES_FEATURE_BITMAP_FONT
// =============================================================================
// Update and Render
diff --git a/src/esengine/ui/UIContext.hpp b/src/esengine/ui/UIContext.hpp
index b7ad484d5..2fc68caa0 100644
--- a/src/esengine/ui/UIContext.hpp
+++ b/src/esengine/ui/UIContext.hpp
@@ -33,12 +33,22 @@ class Dispatcher;
namespace ui {
+#if ES_FEATURE_SDF_FONT
class SDFFont;
+#endif
+
+#if ES_FEATURE_BITMAP_FONT
+class BitmapFont;
+#endif
+
class UIBatchRenderer;
class Widget;
-// Alias for backward compatibility - Font now means SDFFont
+#if ES_FEATURE_SDF_FONT
using Font = SDFFont;
+#elif ES_FEATURE_BITMAP_FONT
+using Font = BitmapFont;
+#endif
// =============================================================================
// UIContext Class
@@ -136,42 +146,32 @@ public:
const Theme& getTheme() const { return *theme_; }
// =========================================================================
- // Font Management (SDF-based)
+ // Font Management
// =========================================================================
+#if ES_FEATURE_SDF_FONT
/**
* @brief Loads a font from file (uses SDF rendering)
- * @param name Name to register the font as
- * @param path Path to the TTF font file
- * @param fontSize SDF glyph size (recommended: 32-64)
- * @param sdfSpread SDF spread in pixels (default: 8)
- * @return Pointer to the loaded font or nullptr on failure
*/
SDFFont* loadFont(const std::string& name, const std::string& path, f32 fontSize = 48.0f,
f32 sdfSpread = 8.0f);
- /**
- * @brief Gets a loaded font by name
- * @param name Font name
- * @return Pointer to the font or nullptr if not found
- */
SDFFont* getFont(const std::string& name);
-
- /**
- * @brief Gets the default font
- * @return Pointer to the default font or nullptr
- */
SDFFont* getDefaultFont();
-
- /**
- * @brief Gets the icon font (Lucide icons)
- * @return Pointer to the icon font or nullptr
- */
SDFFont* getIconFont();
+#endif
+#if ES_FEATURE_BITMAP_FONT
/**
- * @brief Sets the default font name
+ * @brief Loads a bitmap font from atlas and metrics files
*/
+ BitmapFont* loadBitmapFont(const std::string& name, const std::string& atlasPath,
+ const std::string& metricsPath);
+
+ BitmapFont* getBitmapFont(const std::string& name);
+ BitmapFont* getDefaultBitmapFont();
+#endif
+
void setDefaultFontName(const std::string& name) { defaultFontName_ = name; }
// =========================================================================
@@ -343,7 +343,14 @@ private:
Unique<Widget> root_;
Unique<Theme> theme_;
+#if ES_FEATURE_SDF_FONT
std::unordered_map<std::string, Unique<SDFFont>> fonts_;
+#endif
+
+#if ES_FEATURE_BITMAP_FONT
+ std::unordered_map<std::string, Unique<BitmapFont>> bitmapFonts_;
+#endif
+
std::string defaultFontName_ = "default";
u32 viewportWidth_ = 0;
diff --git a/src/esengine/ui/docking/DockTabBar.cpp b/src/esengine/ui/docking/DockTabBar.cpp
index fe2743dbf..e00f5c201 100644
--- a/src/esengine/ui/docking/DockTabBar.cpp
+++ b/src/esengine/ui/docking/DockTabBar.cpp
@@ -14,7 +14,14 @@
#include "DockPanel.hpp"
#include "../UIContext.hpp"
#include "../rendering/UIBatchRenderer.hpp"
+
+#if ES_FEATURE_SDF_FONT
#include "../font/SDFFont.hpp"
+#endif
+
+#if ES_FEATURE_BITMAP_FONT
+#include "../font/BitmapFont.hpp"
+#endif
#include <cmath>
@@ -166,12 +173,21 @@ void DockTabBar::renderTab(UIBatchRenderer& renderer, const DockTabInfo& tab, us
tab.bounds.height
};
+#if ES_FEATURE_SDF_FONT
SDFFont* font = ctx->getDefaultFont();
if (font) {
renderer.drawTextInBounds(tab.title, textBounds, *font,
theme.typography.fontSizeSmall, textColor,
HAlign::Left, VAlign::Center);
}
+#elif ES_FEATURE_BITMAP_FONT
+ BitmapFont* font = ctx->getDefaultBitmapFont();
+ if (font) {
+ renderer.drawTextInBounds(tab.title, textBounds, *font,
+ theme.typography.fontSizeSmall, textColor,
+ HAlign::Left, VAlign::Center);
+ }
+#endif
if (tab.closable) {
glm::vec4 closeColor = tab.closeHovered
diff --git a/src/esengine/ui/font/BitmapFont.cpp b/src/esengine/ui/font/BitmapFont.cpp
new file mode 100644
index 000000000..460dda91e
--- /dev/null
+++ b/src/esengine/ui/font/BitmapFont.cpp
@@ -0,0 +1,372 @@
+/**
+ * @file BitmapFont.cpp
+ * @brief Bitmap font rendering implementation
+ *
+ * @author ESEngine Team
+ * @date 2026
+ */
+
+#include "BitmapFont.hpp"
+#include "../../core/Log.hpp"
+#include "../../platform/FileSystem.hpp"
+
+#ifdef ES_PLATFORM_WEB
+ #include <GLES3/gl3.h>
+#else
+ #ifdef _WIN32
+ #include <windows.h>
+ #endif
+ #include <glad/glad.h>
+#endif
+
+#define STB_IMAGE_IMPLEMENTATION_INCLUDED
+#include <stb_image.h>
+
+#include <cstring>
+#include <sstream>
+
+namespace esengine::ui {
+
+// =============================================================================
+// Simple JSON Parser (minimal, no external deps)
+// =============================================================================
+
+namespace {
+
+std::string trim(const std::string& s) {
+ auto start = s.find_first_not_of(" \t\n\r");
+ if (start == std::string::npos) return "";
+ auto end = s.find_last_not_of(" \t\n\r");
+ return s.substr(start, end - start + 1);
+}
+
+std::string extractString(const std::string& json, const std::string& key) {
+ std::string search = "\"" + key + "\"";
+ auto pos = json.find(search);
+ if (pos == std::string::npos) return "";
+
+ pos = json.find(':', pos);
+ if (pos == std::string::npos) return "";
+
+ pos = json.find('"', pos + 1);
+ if (pos == std::string::npos) return "";
+
+ auto endPos = json.find('"', pos + 1);
+ if (endPos == std::string::npos) return "";
+
+ return json.substr(pos + 1, endPos - pos - 1);
+}
+
+f32 extractFloat(const std::string& json, const std::string& key, f32 defaultVal = 0.0f) {
+ std::string search = "\"" + key + "\"";
+ auto pos = json.find(search);
+ if (pos == std::string::npos) return defaultVal;
+
+ pos = json.find(':', pos);
+ if (pos == std::string::npos) return defaultVal;
+
+ pos++;
+ while (pos < json.size() && (json[pos] == ' ' || json[pos] == '\t')) pos++;
+
+ std::string numStr;
+ while (pos < json.size() && (std::isdigit(json[pos]) || json[pos] == '.' || json[pos] == '-')) {
+ numStr += json[pos++];
+ }
+
+ if (numStr.empty()) return defaultVal;
+ return std::stof(numStr);
+}
+
+i32 extractInt(const std::string& json, const std::string& key, i32 defaultVal = 0) {
+ return static_cast<i32>(extractFloat(json, key, static_cast<f32>(defaultVal)));
+}
+
+u32 nextCodepoint(const std::string& text, usize& i) {
+ u32 codepoint = 0;
+ const u8* ptr = reinterpret_cast<const u8*>(text.data()) + i;
+ const u8* end = reinterpret_cast<const u8*>(text.data()) + text.size();
+
+ if (ptr >= end) return 0;
+
+ if ((*ptr & 0x80) == 0) {
+ codepoint = *ptr;
+ i += 1;
+ } else if ((*ptr & 0xE0) == 0xC0) {
+ codepoint = (*ptr & 0x1F) << 6;
+ if (ptr + 1 < end) codepoint |= (*(ptr + 1) & 0x3F);
+ i += 2;
+ } else if ((*ptr & 0xF0) == 0xE0) {
+ codepoint = (*ptr & 0x0F) << 12;
+ if (ptr + 1 < end) codepoint |= (*(ptr + 1) & 0x3F) << 6;
+ if (ptr + 2 < end) codepoint |= (*(ptr + 2) & 0x3F);
+ i += 3;
+ } else if ((*ptr & 0xF8) == 0xF0) {
+ codepoint = (*ptr & 0x07) << 18;
+ if (ptr + 1 < end) codepoint |= (*(ptr + 1) & 0x3F) << 12;
+ if (ptr + 2 < end) codepoint |= (*(ptr + 2) & 0x3F) << 6;
+ if (ptr + 3 < end) codepoint |= (*(ptr + 3) & 0x3F);
+ i += 4;
+ } else {
+ i += 1;
+ }
+ return codepoint;
+}
+
+} // namespace
+
+// =============================================================================
+// Constructor / Destructor
+// =============================================================================
+
+BitmapFont::~BitmapFont() {
+ if (textureId_ != 0) {
+ glDeleteTextures(1, &textureId_);
+ textureId_ = 0;
+ }
+}
+
+BitmapFont::BitmapFont(BitmapFont&& other) noexcept
+ : textureId_(other.textureId_),
+ atlasWidth_(other.atlasWidth_),
+ atlasHeight_(other.atlasHeight_),
+ fontSize_(other.fontSize_),
+ lineHeight_(other.lineHeight_),
+ ascent_(other.ascent_),
+ descent_(other.descent_),
+ glyphs_(std::move(other.glyphs_)) {
+ other.textureId_ = 0;
+}
+
+BitmapFont& BitmapFont::operator=(BitmapFont&& other) noexcept {
+ if (this != &other) {
+ if (textureId_ != 0) {
+ glDeleteTextures(1, &textureId_);
+ }
+
+ textureId_ = other.textureId_;
+ atlasWidth_ = other.atlasWidth_;
+ atlasHeight_ = other.atlasHeight_;
+ fontSize_ = other.fontSize_;
+ lineHeight_ = other.lineHeight_;
+ ascent_ = other.ascent_;
+ descent_ = other.descent_;
+ glyphs_ = std::move(other.glyphs_);
+
+ other.textureId_ = 0;
+ }
+ return *this;
+}
+
+// =============================================================================
+// Factory Methods
+// =============================================================================
+
+Unique<BitmapFont> BitmapFont::load(const std::string& atlasPath,
+ const std::string& metricsPath) {
+ auto font = makeUnique<BitmapFont>();
+
+ if (!font->loadAtlasTexture(atlasPath)) {
+ ES_LOG_ERROR("BitmapFont: Failed to load atlas: {}", atlasPath);
+ return nullptr;
+ }
+
+ std::string metricsJson = FileSystem::readTextFile(metricsPath);
+ if (metricsJson.empty()) {
+ ES_LOG_ERROR("BitmapFont: Failed to read metrics: {}", metricsPath);
+ return nullptr;
+ }
+
+ if (!font->parseMetrics(metricsJson)) {
+ ES_LOG_ERROR("BitmapFont: Failed to parse metrics: {}", metricsPath);
+ return nullptr;
+ }
+
+ ES_LOG_INFO("BitmapFont loaded: {} ({} glyphs, {}x{})",
+ atlasPath, font->glyphs_.size(), font->atlasWidth_, font->atlasHeight_);
+
+ return font;
+}
+
+Unique<BitmapFont> BitmapFont::loadFromMemory(const u8* atlasData, usize atlasSize,
+ const std::string& metricsJson) {
+ auto font = makeUnique<BitmapFont>();
+
+ if (!font->loadAtlasFromMemory(atlasData, atlasSize)) {
+ ES_LOG_ERROR("BitmapFont: Failed to load atlas from memory");
+ return nullptr;
+ }
+
+ if (!font->parseMetrics(metricsJson)) {
+ ES_LOG_ERROR("BitmapFont: Failed to parse metrics");
+ return nullptr;
+ }
+
+ ES_LOG_INFO("BitmapFont loaded from memory ({} glyphs, {}x{})",
+ font->glyphs_.size(), font->atlasWidth_, font->atlasHeight_);
+
+ return font;
+}
+
+// =============================================================================
+// Atlas Loading
+// =============================================================================
+
+bool BitmapFont::loadAtlasTexture(const std::string& path) {
+ auto data = FileSystem::readBinaryFile(path);
+ if (data.empty()) {
+ return false;
+ }
+ return loadAtlasFromMemory(data.data(), data.size());
+}
+
+bool BitmapFont::loadAtlasFromMemory(const u8* data, usize size) {
+ int width, height, channels;
+ stbi_set_flip_vertically_on_load(false);
+
+ u8* pixels = stbi_load_from_memory(data, static_cast<int>(size),
+ &width, &height, &channels, 4);
+ if (!pixels) {
+ ES_LOG_ERROR("BitmapFont: Failed to decode atlas image");
+ return false;
+ }
+
+ atlasWidth_ = static_cast<u32>(width);
+ atlasHeight_ = static_cast<u32>(height);
+
+ glGenTextures(1, &textureId_);
+ glBindTexture(GL_TEXTURE_2D, textureId_);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0,
+ GL_RGBA, GL_UNSIGNED_BYTE, pixels);
+ glBindTexture(GL_TEXTURE_2D, 0);
+
+ stbi_image_free(pixels);
+ return true;
+}
+
+// =============================================================================
+// Metrics Parsing
+// =============================================================================
+
+bool BitmapFont::parseMetrics(const std::string& json) {
+ fontSize_ = extractFloat(json, "fontSize", 32.0f);
+ lineHeight_ = extractFloat(json, "lineHeight", fontSize_ * 1.2f);
+ ascent_ = extractFloat(json, "ascent", fontSize_ * 0.8f);
+ descent_ = extractFloat(json, "descent", fontSize_ * 0.2f);
+
+ // Parse glyphs array
+ auto glyphsStart = json.find("\"glyphs\"");
+ if (glyphsStart == std::string::npos) {
+ ES_LOG_ERROR("BitmapFont: No glyphs array in metrics");
+ return false;
+ }
+
+ auto arrayStart = json.find('[', glyphsStart);
+ if (arrayStart == std::string::npos) return false;
+
+ auto arrayEnd = json.find(']', arrayStart);
+ if (arrayEnd == std::string::npos) return false;
+
+ std::string glyphsArray = json.substr(arrayStart + 1, arrayEnd - arrayStart - 1);
+
+ // Parse each glyph object
+ usize pos = 0;
+ while (pos < glyphsArray.size()) {
+ auto objStart = glyphsArray.find('{', pos);
+ if (objStart == std::string::npos) break;
+
+ auto objEnd = glyphsArray.find('}', objStart);
+ if (objEnd == std::string::npos) break;
+
+ std::string glyphJson = glyphsArray.substr(objStart, objEnd - objStart + 1);
+
+ u32 codepoint = static_cast<u32>(extractInt(glyphJson, "codepoint", 0));
+ if (codepoint == 0) {
+ // Try "char" field for ASCII character
+ std::string charStr = extractString(glyphJson, "char");
+ if (!charStr.empty()) {
+ usize idx = 0;
+ codepoint = nextCodepoint(charStr, idx);
+ }
+ }
+
+ if (codepoint != 0) {
+ BitmapGlyphInfo glyph;
+ glyph.width = extractFloat(glyphJson, "width");
+ glyph.height = extractFloat(glyphJson, "height");
+ glyph.bearingX = extractFloat(glyphJson, "bearingX");
+ glyph.bearingY = extractFloat(glyphJson, "bearingY");
+ glyph.advance = extractFloat(glyphJson, "advance");
+ glyph.u0 = extractFloat(glyphJson, "u0");
+ glyph.v0 = extractFloat(glyphJson, "v0");
+ glyph.u1 = extractFloat(glyphJson, "u1");
+ glyph.v1 = extractFloat(glyphJson, "v1");
+
+ glyphs_[codepoint] = glyph;
+ }
+
+ pos = objEnd + 1;
+ }
+
+ return !glyphs_.empty();
+}
+
+// =============================================================================
+// Glyph Access
+// =============================================================================
+
+const BitmapGlyphInfo* BitmapFont::getGlyph(u32 codepoint) const {
+ auto it = glyphs_.find(codepoint);
+ if (it != glyphs_.end()) {
+ return &it->second;
+ }
+ return nullptr;
+}
+
+// =============================================================================
+// Text Measurement
+// =============================================================================
+
+glm::vec2 BitmapFont::measureText(const std::string& text, f32 fontSize) const {
+ if (text.empty() || fontSize_ == 0.0f) return {0.0f, 0.0f};
+
+ f32 scale = fontSize / fontSize_;
+ f32 width = 0.0f;
+ f32 maxWidth = 0.0f;
+ i32 lines = 1;
+
+ usize i = 0;
+ while (i < text.size()) {
+ u32 codepoint = nextCodepoint(text, i);
+
+ if (codepoint == '\n') {
+ maxWidth = std::max(maxWidth, width);
+ width = 0.0f;
+ lines++;
+ continue;
+ }
+
+ const auto* glyph = getGlyph(codepoint);
+ if (glyph) {
+ width += glyph->advance * scale;
+ }
+ }
+
+ maxWidth = std::max(maxWidth, width);
+ f32 height = static_cast<f32>(lines) * lineHeight_ * scale;
+
+ return {maxWidth, height};
+}
+
+f32 BitmapFont::getCharWidth(u32 codepoint, f32 fontSize) const {
+ const auto* glyph = getGlyph(codepoint);
+ if (!glyph || fontSize_ == 0.0f) return 0.0f;
+
+ f32 scale = fontSize / fontSize_;
+ return glyph->advance * scale;
+}
+
+} // namespace esengine::ui
diff --git a/src/esengine/ui/font/BitmapFont.hpp b/src/esengine/ui/font/BitmapFont.hpp
new file mode 100644
index 000000000..2f4537671
--- /dev/null
+++ b/src/esengine/ui/font/BitmapFont.hpp
@@ -0,0 +1,121 @@
+/**
+ * @file BitmapFont.hpp
+ * @brief Bitmap font rendering for lightweight deployments
+ *
+ * @details Pre-rendered bitmap fonts for scenarios where FreeType is not
+ * available or package size is critical (e.g., playable ads).
+ *
+ * @author ESEngine Team
+ * @date 2026
+ */
+#pragma once
+
+#include "../../core/Types.hpp"
+#include <glm/glm.hpp>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+namespace esengine::ui {
+
+/**
+ * @brief Glyph information for bitmap fonts
+ */
+struct BitmapGlyphInfo {
+ f32 width = 0.0f;
+ f32 height = 0.0f;
+ f32 bearingX = 0.0f;
+ f32 bearingY = 0.0f;
+ f32 advance = 0.0f;
+ f32 u0 = 0.0f;
+ f32 v0 = 0.0f;
+ f32 u1 = 0.0f;
+ f32 v1 = 0.0f;
+};
+
+/**
+ * @brief Lightweight bitmap font for size-constrained deployments
+ *
+ * @details Uses pre-rendered font atlas and metrics file.
+ * No FreeType dependency, minimal runtime overhead.
+ *
+ * @code
+ * auto font = BitmapFont::load("font_atlas.png", "font_metrics.json");
+ * if (font) {
+ * renderer.drawText("Hello", {10, 10}, *font, 32.0f, {1,1,1,1});
+ * }
+ * @endcode
+ */
+class BitmapFont {
+public:
+ BitmapFont() = default;
+ ~BitmapFont();
+
+ BitmapFont(const BitmapFont&) = delete;
+ BitmapFont& operator=(const BitmapFont&) = delete;
+ BitmapFont(BitmapFont&& other) noexcept;
+ BitmapFont& operator=(BitmapFont&& other) noexcept;
+
+ /**
+ * @brief Load bitmap font from atlas image and metrics file
+ * @param atlasPath Path to the font atlas texture (PNG)
+ * @param metricsPath Path to the glyph metrics file (JSON)
+ * @return Font instance or nullptr on failure
+ */
+ static Unique<BitmapFont> load(const std::string& atlasPath,
+ const std::string& metricsPath);
+
+ /**
+ * @brief Load bitmap font from embedded data
+ * @param atlasData Raw PNG data
+ * @param atlasSize Size of PNG data
+ * @param metricsJson JSON string with glyph metrics
+ * @return Font instance or nullptr on failure
+ */
+ static Unique<BitmapFont> loadFromMemory(const u8* atlasData, usize atlasSize,
+ const std::string& metricsJson);
+
+ /**
+ * @brief Get glyph information for a codepoint
+ * @param codepoint Unicode codepoint
+ * @return Pointer to glyph info, or nullptr if not found
+ */
+ const BitmapGlyphInfo* getGlyph(u32 codepoint) const;
+
+ /** @brief Get the atlas texture ID */
+ u32 getTextureId() const { return textureId_; }
+
+ /** @brief Get the base font size (pixels) */
+ f32 getFontSize() const { return fontSize_; }
+
+ /** @brief Get line height */
+ f32 getLineHeight() const { return lineHeight_; }
+
+ /** @brief Get ascent (baseline to top) */
+ f32 getAscent() const { return ascent_; }
+
+ /** @brief Get descent (baseline to bottom) */
+ f32 getDescent() const { return descent_; }
+
+ /** @brief Measure text dimensions */
+ glm::vec2 measureText(const std::string& text, f32 fontSize) const;
+
+ /** @brief Get character width */
+ f32 getCharWidth(u32 codepoint, f32 fontSize) const;
+
+private:
+ bool loadAtlasTexture(const std::string& path);
+ bool loadAtlasFromMemory(const u8* data, usize size);
+ bool parseMetrics(const std::string& json);
+
+ u32 textureId_ = 0;
+ u32 atlasWidth_ = 0;
+ u32 atlasHeight_ = 0;
+ f32 fontSize_ = 0.0f;
+ f32 lineHeight_ = 0.0f;
+ f32 ascent_ = 0.0f;
+ f32 descent_ = 0.0f;
+ std::unordered_map<u32, BitmapGlyphInfo> glyphs_;
+};
+
+} // namespace esengine::ui
diff --git a/src/esengine/ui/rendering/UIBatchRenderer.cpp b/src/esengine/ui/rendering/UIBatchRenderer.cpp
index 3eec60326..3d5b26178 100644
--- a/src/esengine/ui/rendering/UIBatchRenderer.cpp
+++ b/src/esengine/ui/rendering/UIBatchRenderer.cpp
@@ -15,9 +15,16 @@
#include "../../renderer/RenderCommand.hpp"
#include "../../renderer/RenderContext.hpp"
#include "../../renderer/Shader.hpp"
-#include "../font/SDFFont.hpp"
#include "../layout/SizeValue.hpp"
+#if ES_FEATURE_SDF_FONT
+#include "../font/SDFFont.hpp"
+#endif
+
+#if ES_FEATURE_BITMAP_FONT
+#include "../font/BitmapFont.hpp"
+#endif
+
#include <array>
#include <cmath>
#include <vector>
@@ -664,7 +671,7 @@ void UIBatchRenderer::drawLine(const glm::vec2& p1, const glm::vec2& p2, const g
}
// =============================================================================
-// Text Drawing (SDF-based)
+// Text Drawing
// =============================================================================
namespace {
@@ -705,6 +712,7 @@ u32 nextCodepoint(const std::string& text, usize& i) {
} // namespace
+#if ES_FEATURE_SDF_FONT
void UIBatchRenderer::drawText(const std::string& text, const glm::vec2& position,
SDFFont& font, f32 fontSize, const glm::vec4& color) {
if (text.empty()) return;
@@ -847,6 +855,146 @@ void UIBatchRenderer::drawTextInBounds(const std::string& text, const Rect& boun
y = std::round(y);
drawText(text, {x, y}, font, fontSize, color);
}
+#endif // ES_FEATURE_SDF_FONT
+
+#if ES_FEATURE_BITMAP_FONT
+void UIBatchRenderer::drawText(const std::string& text, const glm::vec2& position,
+ BitmapFont& font, f32 fontSize, const glm::vec4& color) {
+ if (text.empty()) return;
+
+ f32 x = position.x;
+ f32 y = position.y;
+ f32 scale = fontSize / font.getFontSize();
+
+ u32 atlasTexture = font.getTextureId();
+ if (atlasTexture == 0) return;
+
+ u32 texIndex = 0;
+ bool found = false;
+ for (u32 i = 0; i < data_->textureSlotIndex; ++i) {
+ if (data_->textureSlots[i] == atlasTexture) {
+ texIndex = i;
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ if (data_->textureSlotIndex >= MAX_TEXTURE_SLOTS) {
+ flush();
+ }
+ data_->textureSlots[data_->textureSlotIndex] = atlasTexture;
+ texIndex = data_->textureSlotIndex;
+ data_->textureSlotIndex++;
+ }
+
+ usize i = 0;
+ while (i < text.size()) {
+ u32 codepoint = nextCodepoint(text, i);
+
+ if (codepoint == '\n') {
+ x = position.x;
+ y += fontSize * 1.2f;
+ continue;
+ }
+
+ const auto* glyph = font.getGlyph(codepoint);
+ if (!glyph) continue;
+
+ f32 xPos = std::round(x + glyph->bearingX * scale);
+ f32 yPos = std::round(y + (font.getAscent() - glyph->bearingY) * scale);
+ f32 w = glyph->width * scale;
+ f32 h = glyph->height * scale;
+
+ if (w > 0 && h > 0) {
+ if (data_->vertices.size() >= MAX_VERTICES) {
+ flush();
+ }
+
+ f32 texIdx = static_cast<f32>(texIndex);
+ Rect glyphRect(xPos, yPos, w, h);
+ glm::vec2 rectSize = {w, h};
+ glm::vec2 halfSize = rectSize * 0.5f;
+
+ UIVertex vertices[4];
+
+ vertices[0].position = {glyphRect.x, glyphRect.y, 0.0f};
+ vertices[0].texCoord = {glyph->u0, glyph->v0};
+ vertices[0].localPos = {-halfSize.x, -halfSize.y};
+
+ vertices[1].position = {glyphRect.right(), glyphRect.y, 0.0f};
+ vertices[1].texCoord = {glyph->u1, glyph->v0};
+ vertices[1].localPos = {halfSize.x, -halfSize.y};
+
+ vertices[2].position = {glyphRect.right(), glyphRect.bottom(), 0.0f};
+ vertices[2].texCoord = {glyph->u1, glyph->v1};
+ vertices[2].localPos = halfSize;
+
+ vertices[3].position = {glyphRect.x, glyphRect.bottom(), 0.0f};
+ vertices[3].texCoord = {glyph->u0, glyph->v1};
+ vertices[3].localPos = {-halfSize.x, halfSize.y};
+
+ for (auto& v : vertices) {
+ v.color = color;
+ v.cornerRadii = {0, 0, 0, 0};
+ v.rectSize = rectSize;
+ v.texIndex = texIdx;
+ v.borderThickness = 0.0f; // Bitmap font uses regular texture sampling
+ data_->vertices.push_back(v);
+ }
+
+ data_->indexCount += 6;
+ data_->stats.textQuadCount++;
+ }
+
+ x += glyph->advance * scale;
+ }
+}
+
+void UIBatchRenderer::drawTextInBounds(const std::string& text, const Rect& bounds,
+ BitmapFont& font, f32 fontSize, const glm::vec4& color,
+ HAlign hAlign, VAlign vAlign) {
+ if (text.empty()) return;
+
+ glm::vec2 textSize = font.measureText(text, fontSize);
+ f32 scale = fontSize / font.getFontSize();
+ f32 ascent = font.getAscent() * scale;
+ f32 descent = font.getDescent() * scale;
+ f32 visualHeight = ascent + descent;
+
+ f32 x = bounds.x;
+ f32 y = bounds.y;
+
+ switch (hAlign) {
+ case HAlign::Left:
+ break;
+ case HAlign::Center:
+ x += (bounds.width - textSize.x) * 0.5f;
+ break;
+ case HAlign::Right:
+ x += bounds.width - textSize.x;
+ break;
+ case HAlign::Stretch:
+ break;
+ }
+
+ switch (vAlign) {
+ case VAlign::Top:
+ break;
+ case VAlign::Center:
+ y += (bounds.height - visualHeight) * 0.5f;
+ break;
+ case VAlign::Bottom:
+ y += bounds.height - visualHeight;
+ break;
+ case VAlign::Stretch:
+ break;
+ }
+
+ x = std::round(x);
+ y = std::round(y);
+ drawText(text, {x, y}, font, fontSize, color);
+}
+#endif // ES_FEATURE_BITMAP_FONT
// =============================================================================
// Statistics
diff --git a/src/esengine/ui/rendering/UIBatchRenderer.hpp b/src/esengine/ui/rendering/UIBatchRenderer.hpp
index 223a02572..44d3a9e5f 100644
--- a/src/esengine/ui/rendering/UIBatchRenderer.hpp
+++ b/src/esengine/ui/rendering/UIBatchRenderer.hpp
@@ -31,10 +31,19 @@ class RenderContext;
namespace ui {
+#if ES_FEATURE_SDF_FONT
class SDFFont;
+#endif
-// Font is now an alias for SDFFont
+#if ES_FEATURE_BITMAP_FONT
+class BitmapFont;
+#endif
+
+#if ES_FEATURE_SDF_FONT
using Font = SDFFont;
+#elif ES_FEATURE_BITMAP_FONT
+using Font = BitmapFont;
+#endif
// =============================================================================
// UI Render Statistics
@@ -201,33 +210,32 @@ public:
f32 thickness = 1.0f);
// =========================================================================
- // Text Drawing (SDF-based)
+ // Text Drawing
// =========================================================================
+#if ES_FEATURE_SDF_FONT
/**
- * @brief Draws text at a position (UTF-8 supported)
- * @param text Text string to draw
- * @param position Top-left position
- * @param font Font to use
- * @param fontSize Font size in pixels
- * @param color Text color
+ * @brief Draws text using SDF font (UTF-8 supported)
*/
void drawText(const std::string& text, const glm::vec2& position, SDFFont& font, f32 fontSize,
const glm::vec4& color);
+ void drawTextInBounds(const std::string& text, const Rect& bounds, SDFFont& font, f32 fontSize,
+ const glm::vec4& color, HAlign hAlign = HAlign::Left,
+ VAlign vAlign = VAlign::Top);
+#endif
+
+#if ES_FEATURE_BITMAP_FONT
/**
- * @brief Draws text with clipping to a bounds (UTF-8 supported)
- * @param text Text string to draw
- * @param bounds Bounding rectangle for text
- * @param font Font to use
- * @param fontSize Font size in pixels
- * @param color Text color
- * @param hAlign Horizontal alignment within bounds
- * @param vAlign Vertical alignment within bounds
+ * @brief Draws text using bitmap font (UTF-8 supported)
*/
- void drawTextInBounds(const std::string& text, const Rect& bounds, SDFFont& font, f32 fontSize,
+ void drawText(const std::string& text, const glm::vec2& position, BitmapFont& font, f32 fontSize,
+ const glm::vec4& color);
+
+ void drawTextInBounds(const std::string& text, const Rect& bounds, BitmapFont& font, f32 fontSize,
const glm::vec4& color, HAlign hAlign = HAlign::Left,
VAlign vAlign = VAlign::Top);
+#endif
// =========================================================================
// Statistics
diff --git a/src/esengine/ui/widgets/Button.cpp b/src/esengine/ui/widgets/Button.cpp
index 47e5a2d0e..546778983 100644
--- a/src/esengine/ui/widgets/Button.cpp
+++ b/src/esengine/ui/widgets/Button.cpp
@@ -11,9 +11,16 @@
#include "Button.hpp"
#include "../UIContext.hpp"
-#include "../font/SDFFont.hpp"
#include "../rendering/UIBatchRenderer.hpp"
+#if ES_FEATURE_SDF_FONT
+#include "../font/SDFFont.hpp"
+#endif
+
+#if ES_FEATURE_BITMAP_FONT
+#include "../font/BitmapFont.hpp"
+#endif
+
namespace esengine::ui {
// =============================================================================
@@ -57,11 +64,20 @@ glm::vec2 Button::measure(f32 availableWidth, f32 availableHeight) {
? ctx->getTheme().getPrimaryButtonStyle()
: ctx->getTheme().getButtonStyle();
- // Use regular font for measurement
- SDFFont* font = fontName_.empty() ? ctx->getDefaultFont() : ctx->getFont(fontName_);
- if (font && textSizeDirty_) {
- cachedTextSize_ = font->measureText(text_, fontSize_);
- textSizeDirty_ = false;
+ if (textSizeDirty_) {
+#if ES_FEATURE_SDF_FONT
+ SDFFont* font = fontName_.empty() ? ctx->getDefaultFont() : ctx->getFont(fontName_);
+ if (font) {
+ cachedTextSize_ = font->measureText(text_, fontSize_);
+ textSizeDirty_ = false;
+ }
+#elif ES_FEATURE_BITMAP_FONT
+ BitmapFont* font = fontName_.empty() ? ctx->getDefaultBitmapFont() : ctx->getBitmapFont(fontName_);
+ if (font) {
+ cachedTextSize_ = font->measureText(text_, fontSize_);
+ textSizeDirty_ = false;
+ }
+#endif
}
f32 contentWidth = cachedTextSize_.x + style.padding.totalHorizontal() +
@@ -116,12 +132,19 @@ void Button::render(UIBatchRenderer& renderer) {
glm::vec4 textColor = style.getTextColor(state);
Rect textBounds = style.padding.shrink(bounds);
- // Use regular font for now
+#if ES_FEATURE_SDF_FONT
SDFFont* font = fontName_.empty() ? ctx->getDefaultFont() : ctx->getFont(fontName_);
if (font) {
renderer.drawTextInBounds(text_, textBounds, *font, fontSize_, textColor,
HAlign::Center, VAlign::Center);
}
+#elif ES_FEATURE_BITMAP_FONT
+ BitmapFont* font = fontName_.empty() ? ctx->getDefaultBitmapFont() : ctx->getBitmapFont(fontName_);
+ if (font) {
+ renderer.drawTextInBounds(text_, textBounds, *font, fontSize_, textColor,
+ HAlign::Center, VAlign::Center);
+ }
+#endif
}
}
diff --git a/src/esengine/ui/widgets/Checkbox.cpp b/src/esengine/ui/widgets/Checkbox.cpp
index a227f61cf..4795bb466 100644
--- a/src/esengine/ui/widgets/Checkbox.cpp
+++ b/src/esengine/ui/widgets/Checkbox.cpp
@@ -11,10 +11,17 @@
#include "Checkbox.hpp"
#include "../UIContext.hpp"
-#include "../font/SDFFont.hpp"
#include "../rendering/UIBatchRenderer.hpp"
#include "../../math/Math.hpp"
+#if ES_FEATURE_SDF_FONT
+#include "../font/SDFFont.hpp"
+#endif
+
+#if ES_FEATURE_BITMAP_FONT
+#include "../font/BitmapFont.hpp"
+#endif
+
namespace esengine::ui {
// =============================================================================
@@ -78,15 +85,20 @@ glm::vec2 Checkbox::measure(f32 availableWidth, f32 availableHeight) {
if (!label_.empty() && getContext()) {
f32 fontSize = getContext()->getTheme().typography.fontSizeNormal;
+ f32 labelWidth = static_cast<f32>(label_.length()) * fontSize * 0.6f;
- // Use regular font for measurement
+#if ES_FEATURE_SDF_FONT
SDFFont* font = getContext()->getDefaultFont();
- f32 labelWidth;
if (font) {
labelWidth = font->measureText(label_, fontSize).x;
- } else {
- labelWidth = static_cast<f32>(label_.length()) * fontSize * 0.6f;
}
+#elif ES_FEATURE_BITMAP_FONT
+ BitmapFont* font = getContext()->getDefaultBitmapFont();
+ if (font) {
+ labelWidth = font->measureText(label_, fontSize).x;
+ }
+#endif
+
width += LABEL_SPACING + labelWidth;
height = glm::max(height, fontSize);
}
@@ -173,10 +185,17 @@ void Checkbox::render(UIBatchRenderer& renderer) {
f32 labelX = checkboxX + checkboxSize_ + LABEL_SPACING;
f32 labelY = bounds.y + (bounds.height - fontSize) * 0.5f;
+#if ES_FEATURE_SDF_FONT
if (getContext() && getContext()->getDefaultFont()) {
renderer.drawText(label_, glm::vec2(labelX, labelY),
*getContext()->getDefaultFont(), fontSize, textColor);
}
+#elif ES_FEATURE_BITMAP_FONT
+ if (getContext() && getContext()->getDefaultBitmapFont()) {
+ renderer.drawText(label_, glm::vec2(labelX, labelY),
+ *getContext()->getDefaultBitmapFont(), fontSize, textColor);
+ }
+#endif
}
}
diff --git a/src/esengine/ui/widgets/Label.cpp b/src/esengine/ui/widgets/Label.cpp
index 5220a5679..485e79514 100644
--- a/src/esengine/ui/widgets/Label.cpp
+++ b/src/esengine/ui/widgets/Label.cpp
@@ -11,9 +11,16 @@
#include "Label.hpp"
#include "../UIContext.hpp"
-#include "../font/SDFFont.hpp"
#include "../rendering/UIBatchRenderer.hpp"
+#if ES_FEATURE_SDF_FONT
+#include "../font/SDFFont.hpp"
+#endif
+
+#if ES_FEATURE_BITMAP_FONT
+#include "../font/BitmapFont.hpp"
+#endif
+
namespace esengine::ui {
// =============================================================================
@@ -53,12 +60,22 @@ glm::vec2 Label::measure(f32 availableWidth, f32 availableHeight) {
return Widget::measure(availableWidth, availableHeight);
}
- SDFFont* font = fontName_.empty() ? getContext()->getDefaultFont()
- : getContext()->getFont(fontName_);
-
- if (font && textSizeDirty_) {
- cachedTextSize_ = font->measureText(text_, fontSize_);
- textSizeDirty_ = false;
+ if (textSizeDirty_) {
+#if ES_FEATURE_SDF_FONT
+ SDFFont* font = fontName_.empty() ? getContext()->getDefaultFont()
+ : getContext()->getFont(fontName_);
+ if (font) {
+ cachedTextSize_ = font->measureText(text_, fontSize_);
+ textSizeDirty_ = false;
+ }
+#elif ES_FEATURE_BITMAP_FONT
+ BitmapFont* font = fontName_.empty() ? getContext()->getDefaultBitmapFont()
+ : getContext()->getBitmapFont(fontName_);
+ if (font) {
+ cachedTextSize_ = font->measureText(text_, fontSize_);
+ textSizeDirty_ = false;
+ }
+#endif
}
f32 contentWidth = cachedTextSize_.x + getPadding().totalHorizontal();
@@ -87,10 +104,17 @@ void Label::render(UIBatchRenderer& renderer) {
glm::vec4 textColor = customColor_ ? color_ : style.getTextColor(getState());
Rect contentBounds = getContentBounds();
+#if ES_FEATURE_SDF_FONT
SDFFont* font = fontName_.empty() ? ctx->getDefaultFont() : ctx->getFont(fontName_);
if (font) {
renderer.drawTextInBounds(text_, contentBounds, *font, fontSize_, textColor, hAlign_, vAlign_);
}
+#elif ES_FEATURE_BITMAP_FONT
+ BitmapFont* font = fontName_.empty() ? ctx->getDefaultBitmapFont() : ctx->getBitmapFont(fontName_);
+ if (font) {
+ renderer.drawTextInBounds(text_, contentBounds, *font, fontSize_, textColor, hAlign_, vAlign_);
+ }
+#endif
}
} // namespace esengine::ui
diff --git a/src/esengine/ui/widgets/TextField.cpp b/src/esengine/ui/widgets/TextField.cpp
index c18f8a2f9..7d3f776e6 100644
--- a/src/esengine/ui/widgets/TextField.cpp
+++ b/src/esengine/ui/widgets/TextField.cpp
@@ -11,11 +11,18 @@
#include "TextField.hpp"
#include "../UIContext.hpp"
-#include "../font/SDFFont.hpp"
#include "../rendering/UIBatchRenderer.hpp"
#include "../../core/Log.hpp"
#include "../../math/Math.hpp"
+#if ES_FEATURE_SDF_FONT
+#include "../font/SDFFont.hpp"
+#endif
+
+#if ES_FEATURE_BITMAP_FONT
+#include "../font/BitmapFont.hpp"
+#endif
+
#include <algorithm>
namespace esengine::ui {
@@ -143,10 +150,17 @@ void TextField::render(UIBatchRenderer& renderer) {
glm::vec4 placeholderColor = textColor;
placeholderColor.a *= 0.5f;
+#if ES_FEATURE_SDF_FONT
if (getContext() && getContext()->getDefaultFont()) {
renderer.drawText(placeholder_, glm::vec2(textX, textY),
*getContext()->getDefaultFont(), fontSize, placeholderColor);
}
+#elif ES_FEATURE_BITMAP_FONT
+ if (getContext() && getContext()->getDefaultBitmapFont()) {
+ renderer.drawText(placeholder_, glm::vec2(textX, textY),
+ *getContext()->getDefaultBitmapFont(), fontSize, placeholderColor);
+ }
+#endif
} else if (!text_.empty()) {
if (hasSelection()) {
usize start = glm::min(selectionStart_, selectionEnd_);
@@ -169,10 +183,17 @@ void TextField::render(UIBatchRenderer& renderer) {
renderer.drawRect(selRect, selectionColor);
}
+#if ES_FEATURE_SDF_FONT
if (getContext() && getContext()->getDefaultFont()) {
renderer.drawText(text_, glm::vec2(textX, textY),
*getContext()->getDefaultFont(), fontSize, textColor);
}
+#elif ES_FEATURE_BITMAP_FONT
+ if (getContext() && getContext()->getDefaultBitmapFont()) {
+ renderer.drawText(text_, glm::vec2(textX, textY),
+ *getContext()->getDefaultBitmapFont(), fontSize, textColor);
+ }
+#endif
}
if (isFocused()) {
@@ -515,17 +536,20 @@ usize TextField::getCharIndexAtX(f32 x) const {
f32 fontSize = getContext()->getTheme().typography.fontSizeNormal;
- // Use regular font for character measurement
- SDFFont* font = getContext()->getDefaultFont();
-
f32 currentX = 0.0f;
for (usize i = 0; i < text_.size(); ++i) {
- f32 charWidth;
+ f32 charWidth = fontSize * 0.6f;
+#if ES_FEATURE_SDF_FONT
+ SDFFont* font = getContext()->getDefaultFont();
if (font) {
charWidth = font->getCharWidth(static_cast<u32>(text_[i]), fontSize);
- } else {
- charWidth = fontSize * 0.6f;
}
+#elif ES_FEATURE_BITMAP_FONT
+ BitmapFont* font = getContext()->getDefaultBitmapFont();
+ if (font) {
+ charWidth = font->getCharWidth(static_cast<u32>(text_[i]), fontSize);
+ }
+#endif
if (relativeX < currentX + charWidth * 0.5f) {
return i;
@@ -544,9 +568,8 @@ f32 TextField::getXForCharIndex(usize index) const {
f32 fontSize = getContext()->getTheme().typography.fontSizeNormal;
- // Use regular font for character measurement
+#if ES_FEATURE_SDF_FONT
SDFFont* font = getContext()->getDefaultFont();
-
if (font) {
f32 currentX = 0.0f;
for (usize i = 0; i < index && i < text_.size(); ++i) {
@@ -554,6 +577,16 @@ f32 TextField::getXForCharIndex(usize index) const {
}
return currentX;
}
+#elif ES_FEATURE_BITMAP_FONT
+ BitmapFont* font = getContext()->getDefaultBitmapFont();
+ if (font) {
+ f32 currentX = 0.0f;
+ for (usize i = 0; i < index && i < text_.size(); ++i) {
+ currentX += font->getCharWidth(static_cast<u32>(text_[i]), fontSize);
+ }
+ return currentX;
+ }
+#endif
f32 charWidth = fontSize * 0.6f;
return static_cast<f32>(index) * charWidth;
diff --git a/src/esengine/ui/widgets/TreeView.cpp b/src/esengine/ui/widgets/TreeView.cpp
index 0efc7320b..eac6da76a 100644
--- a/src/esengine/ui/widgets/TreeView.cpp
+++ b/src/esengine/ui/widgets/TreeView.cpp
@@ -11,12 +11,19 @@
#include "TreeView.hpp"
#include "../UIContext.hpp"
-#include "../font/SDFFont.hpp"
#include "../icons/Icons.hpp"
#include "../rendering/UIBatchRenderer.hpp"
#include "../../core/Log.hpp"
#include "../../math/Math.hpp"
+#if ES_FEATURE_SDF_FONT
+#include "../font/SDFFont.hpp"
+#endif
+
+#if ES_FEATURE_BITMAP_FONT
+#include "../font/BitmapFont.hpp"
+#endif
+
#include <algorithm>
namespace esengine::ui {
@@ -301,12 +308,14 @@ void TreeView::renderNode(UIBatchRenderer& renderer, const TreeNode& node, f32 y
iconColor = getContext()->getTheme().colors.textSecondary;
}
+#if ES_FEATURE_SDF_FONT
SDFFont* iconFont = getContext() ? getContext()->getIconFont() : nullptr;
if (iconFont) {
const char* icon = node.expanded ? icons::ChevronDown : icons::ChevronRight;
renderer.drawTextInBounds(icon, iconBounds, *iconFont, iconSize_, iconColor,
HAlign::Center, VAlign::Center);
}
+#endif
x += iconSize_ + 4.0f;
} else {
@@ -325,10 +334,17 @@ void TreeView::renderNode(UIBatchRenderer& renderer, const TreeNode& node, f32 y
f32 textY = y + (rowHeight_ - fontSize) * 0.5f;
+#if ES_FEATURE_SDF_FONT
if (getContext() && getContext()->getDefaultFont()) {
renderer.drawText(node.label, glm::vec2(x, textY), *getContext()->getDefaultFont(),
fontSize, textColor);
}
+#elif ES_FEATURE_BITMAP_FONT
+ if (getContext() && getContext()->getDefaultBitmapFont()) {
+ renderer.drawText(node.label, glm::vec2(x, textY), *getContext()->getDefaultBitmapFont(),
+ fontSize, textColor);
+ }
+#endif
}
// =============================================================================
diff --git a/tools/pack_bitmap_font.py b/tools/pack_bitmap_font.py
new file mode 100644
index 000000000..fabc6a965
--- /dev/null
+++ b/tools/pack_bitmap_font.py
@@ -0,0 +1,241 @@
+#!/usr/bin/env python3
+"""
+Bitmap Font Packer for ESEngine
+
+Generates a font atlas (PNG) and metrics file (JSON) from a TTF font.
+Only includes specified characters to minimize file size.
+
+Usage:
+ python pack_bitmap_font.py --font font.ttf --size 32 --chars chars.txt --output output_prefix
+
+Requirements:
+ pip install Pillow freetype-py
+"""
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+
+try:
+ from PIL import Image, ImageDraw
+ import freetype
+except ImportError:
+ print("Error: Required packages not installed.")
+ print("Run: pip install Pillow freetype-py")
+ sys.exit(1)
+
+
+# Common Chinese characters (most frequently used ~500)
+COMMON_CHINESE = """
+的一是不了在人有我他这为之大来以个中上们到说国和地也子时道出而要于就下得可你年生自会那后能对着事其里所去行过家十用发天如然作方成者多日都三小军二无同主经长儿母开看起五当已从心进动战么定现并系由问表所向间位与变使关十化法务高外政美全何济体建各明记力史样合接治电办点代新期活式特程通等门应反今共因解运第五外科员直象利文气军程取九原平代美安名回做基任入名至结党声各调组展空求路务员级教海完带象体月明便处象界权表电加即反
+"""
+
+# ASCII printable characters
+ASCII_CHARS = ''.join(chr(i) for i in range(32, 127))
+
+
+def get_default_chars():
+ """Get default character set: ASCII + common Chinese"""
+ return ASCII_CHARS + COMMON_CHINESE.replace('\n', '').replace(' ', '')
+
+
+def load_chars_from_file(filepath):
+ """Load characters from a text file"""
+ with open(filepath, 'r', encoding='utf-8') as f:
+ chars = f.read()
+ # Remove whitespace and duplicates while preserving order
+ seen = set()
+ result = []
+ for c in chars:
+ if c not in seen and c.strip():
+ seen.add(c)
+ result.append(c)
+ return ''.join(result)
+
+
+def pack_font(font_path, font_size, chars, output_prefix, padding=2, atlas_size=1024):
+ """
+ Pack font glyphs into an atlas
+
+ Args:
+ font_path: Path to TTF font
+ font_size: Font size in pixels
+ chars: String of characters to include
+ output_prefix: Output path prefix (will create .png and .json)
+ padding: Padding between glyphs
+ atlas_size: Maximum atlas size
+ """
+ # Load font
+ face = freetype.Face(font_path)
+ face.set_pixel_sizes(0, font_size)
+
+ # Calculate metrics
+ ascent = face.size.ascender >> 6
+ descent = -(face.size.descender >> 6)
+ line_height = (face.size.height >> 6)
+
+ # First pass: measure all glyphs
+ glyph_data = []
+ for char in chars:
+ try:
+ face.load_char(char, freetype.FT_LOAD_RENDER)
+ glyph = face.glyph
+ bitmap = glyph.bitmap
+
+ glyph_data.append({
+ 'char': char,
+ 'codepoint': ord(char),
+ 'width': bitmap.width,
+ 'height': bitmap.rows,
+ 'bearingX': glyph.bitmap_left,
+ 'bearingY': glyph.bitmap_top,
+ 'advance': glyph.advance.x >> 6,
+ 'buffer': bytes(bitmap.buffer) if bitmap.buffer else b'',
+ 'pitch': bitmap.pitch
+ })
+ except Exception as e:
+ print(f"Warning: Failed to load glyph '{char}' (U+{ord(char):04X}): {e}")
+
+ if not glyph_data:
+ print("Error: No glyphs loaded")
+ return False
+
+ # Sort by height for better packing
+ glyph_data.sort(key=lambda g: -g['height'])
+
+ # Calculate atlas size needed
+ total_area = sum((g['width'] + padding) * (g['height'] + padding) for g in glyph_data)
+ min_size = int(math.sqrt(total_area) * 1.2)
+ atlas_width = min(atlas_size, max(256, 2 ** math.ceil(math.log2(min_size))))
+ atlas_height = atlas_width
+
+ # Pack glyphs (simple row-based packing)
+ atlas = Image.new('RGBA', (atlas_width, atlas_height), (0, 0, 0, 0))
+
+ x, y = padding, padding
+ row_height = 0
+
+ metrics = {
+ 'fontSize': font_size,
+ 'lineHeight': line_height,
+ 'ascent': ascent,
+ 'descent': descent,
+ 'atlasWidth': atlas_width,
+ 'atlasHeight': atlas_height,
+ 'glyphs': []
+ }
+
+ for glyph in glyph_data:
+ w, h = glyph['width'], glyph['height']
+
+ # Check if we need to move to next row
+ if x + w + padding > atlas_width:
+ x = padding
+ y += row_height + padding
+ row_height = 0
+
+ # Check if atlas is full
+ if y + h + padding > atlas_height:
+ # Try larger atlas
+ if atlas_width < atlas_size:
+ print(f"Warning: Atlas full, increasing size from {atlas_width} to {atlas_width * 2}")
+ return pack_font(font_path, font_size, chars, output_prefix,
+ padding, min(atlas_size, atlas_width * 2))
+ else:
+ print(f"Error: Atlas full, couldn't fit all glyphs")
+ break
+
+ # Draw glyph
+ if w > 0 and h > 0 and glyph['buffer']:
+ glyph_img = Image.new('L', (w, h))
+ # Copy bitmap data row by row
+ for row in range(h):
+ for col in range(w):
+ idx = row * glyph['pitch'] + col
+ if idx < len(glyph['buffer']):
+ glyph_img.putpixel((col, row), glyph['buffer'][idx])
+
+ # Convert to RGBA (white text with alpha)
+ rgba_img = Image.new('RGBA', (w, h))
+ for py in range(h):
+ for px in range(w):
+ alpha = glyph_img.getpixel((px, py))
+ rgba_img.putpixel((px, py), (255, 255, 255, alpha))
+
+ atlas.paste(rgba_img, (x, y))
+
+ # Store metrics
+ metrics['glyphs'].append({
+ 'char': glyph['char'],
+ 'codepoint': glyph['codepoint'],
+ 'width': float(w),
+ 'height': float(h),
+ 'bearingX': float(glyph['bearingX']),
+ 'bearingY': float(glyph['bearingY']),
+ 'advance': float(glyph['advance']),
+ 'u0': x / atlas_width,
+ 'v0': y / atlas_height,
+ 'u1': (x + w) / atlas_width,
+ 'v1': (y + h) / atlas_height
+ })
+
+ # Move position
+ x += w + padding
+ row_height = max(row_height, h)
+
+ # Save outputs
+ atlas_path = f"{output_prefix}.png"
+ metrics_path = f"{output_prefix}.json"
+
+ atlas.save(atlas_path, 'PNG', optimize=True)
+
+ with open(metrics_path, 'w', encoding='utf-8') as f:
+ json.dump(metrics, f, ensure_ascii=False, indent=2)
+
+ print(f"Generated: {atlas_path} ({atlas_width}x{atlas_height})")
+ print(f"Generated: {metrics_path} ({len(metrics['glyphs'])} glyphs)")
+ print(f"Atlas size: {Path(atlas_path).stat().st_size / 1024:.1f} KB")
+
+ return True
+
+
+def main():
+ parser = argparse.ArgumentParser(description='Pack bitmap font for ESEngine')
+ parser.add_argument('--font', '-f', required=True, help='Input TTF font path')
+ parser.add_argument('--size', '-s', type=int, default=32, help='Font size in pixels')
+ parser.add_argument('--chars', '-c', help='File containing characters to include')
+ parser.add_argument('--output', '-o', required=True, help='Output path prefix')
+ parser.add_argument('--padding', '-p', type=int, default=2, help='Padding between glyphs')
+ parser.add_argument('--atlas-size', type=int, default=2048, help='Maximum atlas size')
+ parser.add_argument('--ascii-only', action='store_true', help='Only include ASCII characters')
+
+ args = parser.parse_args()
+
+ # Determine character set
+ if args.ascii_only:
+ chars = ASCII_CHARS
+ elif args.chars:
+ chars = load_chars_from_file(args.chars)
+ else:
+ chars = get_default_chars()
+
+ print(f"Font: {args.font}")
+ print(f"Size: {args.size}px")
+ print(f"Characters: {len(chars)}")
+
+ success = pack_font(
+ args.font,
+ args.size,
+ chars,
+ args.output,
+ args.padding,
+ args.atlas_size
+ )
+
+ sys.exit(0 if success else 1)
+
+
+if __name__ == '__main__':
+ main()