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: Migrate UI font system to SDF rendering

esengine3f0c9be0c4ea
diff --git a/.gitmodules b/.gitmodules
index 586cd7564..9c8192ab8 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -7,3 +7,6 @@
[submodule "third_party/quickjs"]
path = third_party/quickjs
url = https://github.com/bellard/quickjs.git
+[submodule "third_party/freetype"]
+ path = third_party/freetype
+ url = https://github.com/freetype/freetype.git
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 5d200a763..40aa6900a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -40,7 +40,7 @@ set(ESENGINE_SOURCES
# UI System
src/esengine/ui/UIContext.cpp
src/esengine/ui/rendering/UIBatchRenderer.cpp
- src/esengine/ui/font/Font.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
@@ -110,7 +110,7 @@ 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/Font.hpp
+ src/esengine/ui/font/SDFFont.hpp
src/esengine/ui/widgets/Widget.hpp
src/esengine/ui/widgets/Panel.hpp
src/esengine/ui/widgets/Label.hpp
@@ -252,12 +252,13 @@ if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
target_compile_definitions(esengine PUBLIC ES_PLATFORM_WXGAME)
endif()
else()
- # Native platform - link GLFW, GLAD, OpenGL, and QuickJS
+ # Native platform - link GLFW, GLAD, OpenGL, QuickJS, and FreeType
find_package(OpenGL REQUIRED)
target_compile_definitions(esengine PUBLIC ES_PLATFORM_NATIVE)
- target_link_libraries(esengine PUBLIC glfw glad OpenGL::GL quickjs)
+ target_link_libraries(esengine PUBLIC glfw glad OpenGL::GL quickjs freetype)
target_include_directories(esengine PUBLIC
${CMAKE_SOURCE_DIR}/third_party/glad/include
+ ${CMAKE_SOURCE_DIR}/third_party/freetype/include
)
endif()
diff --git a/assets/.esengine/assets.db b/assets/.esengine/assets.db
new file mode 100644
index 000000000..1bb05eaa2
--- /dev/null
+++ b/assets/.esengine/assets.db
@@ -0,0 +1,68 @@
+{
+ "version": "1.0",
+ "assets": [
+ {
+ "guid": "cf70754c-26ba-346d-c01d-ff9fc29a6e9e",
+ "path": "assets\\.esengine",
+ "name": ".esengine",
+ "type": 1,
+ "fileSize": 0,
+ "lastModified": 1769495856,
+ "isDirectory": true
+ },
+ {
+ "guid": "86ed9e0d-442c-a047-9b51-09011c881685",
+ "path": "assets\\audio",
+ "name": "audio",
+ "type": 1,
+ "fileSize": 0,
+ "lastModified": 1769488063,
+ "isDirectory": true
+ },
+ {
+ "guid": "08964537-6809-2c47-8997-7bbf1c75029f",
+ "path": "assets\\scripts",
+ "name": "scripts",
+ "type": 1,
+ "fileSize": 0,
+ "lastModified": 1769488063,
+ "isDirectory": true
+ },
+ {
+ "guid": "9db35f84-665c-e687-86b1-cc78a3934216",
+ "path": "assets\\test.txt",
+ "name": "test.txt",
+ "type": 0,
+ "fileSize": 5,
+ "lastModified": 1769488063,
+ "isDirectory": false
+ },
+ {
+ "guid": "44aa95ad-d460-37e0-041f-c6a4449f8b17",
+ "path": "assets\\textures\\test.png",
+ "name": "test.png",
+ "type": 2,
+ "fileSize": 6,
+ "lastModified": 1769488062,
+ "isDirectory": false
+ },
+ {
+ "guid": "a638dc81-b60d-567f-6820-13f4e9998407",
+ "path": "assets\\.esengine\\assets.db",
+ "name": "assets.db",
+ "type": 0,
+ "fileSize": 1220,
+ "lastModified": 1769495857,
+ "isDirectory": false
+ },
+ {
+ "guid": "e0220f45-6261-175f-883b-ba80783788f2",
+ "path": "assets\\textures",
+ "name": "textures",
+ "type": 1,
+ "fileSize": 0,
+ "lastModified": 1769488063,
+ "isDirectory": true
+ }
+ ]
+}
diff --git a/assets/test.txt b/assets/test.txt
new file mode 100644
index 000000000..9daeafb98
--- /dev/null
+++ b/assets/test.txt
@@ -0,0 +1 @@
+test
diff --git a/assets/textures/test.png b/assets/textures/test.png
new file mode 100644
index 000000000..180cf8328
--- /dev/null
+++ b/assets/textures/test.png
@@ -0,0 +1 @@
+test2
diff --git a/examples/hello_triangle/main.cpp b/examples/hello_triangle/main.cpp
index 6e57962fa..2c2750a20 100644
--- a/examples/hello_triangle/main.cpp
+++ b/examples/hello_triangle/main.cpp
@@ -1,20 +1,13 @@
#include <esengine/ESEngine.hpp>
+#include <esengine/ui/UIContext.hpp>
+#include <esengine/ui/rendering/UIBatchRenderer.hpp>
+#include <esengine/ui/font/SDFFont.hpp>
+#include <esengine/events/Dispatcher.hpp>
using namespace esengine;
using namespace esengine::ecs;
-// Simple movement system
-class MovementSystem : public System {
-public:
- void update(Registry& registry, f32 deltaTime) override {
- registry.each<LocalTransform, Velocity>([deltaTime](Entity entity, LocalTransform& transform, Velocity& velocity) {
- (void)entity;
- transform.position += velocity.linear * deltaTime;
- });
- }
-};
-
-// Demo application
+// Demo application with SDF font testing
class HelloTriangleApp : public Application {
public:
HelloTriangleApp() : Application(createConfig()) {}
@@ -22,7 +15,7 @@ public:
private:
static ApplicationConfig createConfig() {
ApplicationConfig config;
- config.title = "Hello Triangle";
+ config.title = "SDF Font Test - 中英文测试";
config.width = 800;
config.height = 600;
return config;
@@ -30,102 +23,143 @@ private:
protected:
void onInit() override {
- ES_LOG_INFO("Hello Triangle initialized!");
+ ES_LOG_INFO("SDF Font Test initialized!");
+
+ // Create UI context for font rendering
+ uiContext_ = makeUnique<ui::UIContext>(getRenderContext(), dispatcher_);
+ uiContext_->init();
+ uiContext_->setViewport(getWidth(), getHeight());
+
+ // Load SDF font with CJK support
+ const char* fontPaths[] = {
+#ifdef _WIN32
+ "C:/Windows/Fonts/msyh.ttc", // Microsoft YaHei (中文)
+ "C:/Windows/Fonts/simhei.ttf", // SimHei
+ "C:/Windows/Fonts/simsun.ttc", // SimSun
+ "C:/Windows/Fonts/arial.ttf", // Arial (English fallback)
+#else
+ "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
+#endif
+ nullptr
+ };
+
+ for (const char** path = fontPaths; *path != nullptr; ++path) {
+ sdfFont_ = ui::SDFFont::create(*path, 48.0f, 8.0f);
+ if (sdfFont_) {
+ ES_LOG_INFO("Loaded SDF font: {}", *path);
+ break;
+ }
+ }
- // Create some entities with the ECS
- auto& registry = getRegistry();
+ if (!sdfFont_) {
+ ES_LOG_ERROR("Failed to load any SDF font!");
+ }
- // Create a triangle entity
+ // Create some entities
+ auto& registry = getRegistry();
Entity triangle = registry.create();
- registry.emplace<LocalTransform>(triangle, glm::vec3(400.0f, 300.0f, 0.0f));
+ registry.emplace<LocalTransform>(triangle, glm::vec3(400.0f, 450.0f, 0.0f));
registry.emplace<Name>(triangle, "Triangle");
- // Create moving entities
- for (int i = 0; i < 5; ++i) {
- Entity entity = registry.create();
- registry.emplace<LocalTransform>(entity, glm::vec3(100.0f + i * 120.0f, 100.0f, 0.0f));
- registry.emplace<Velocity>(entity, glm::vec3(50.0f * (i % 2 == 0 ? 1.0f : -1.0f), 0.0f, 0.0f));
- registry.emplace<Sprite>(entity);
- }
-
- ES_LOG_INFO("Created {} entities", registry.entityCount());
+ ES_LOG_INFO("Press ESC to exit");
}
void onUpdate(f32 deltaTime) override {
- // Update entities manually (or use SystemGroup)
- auto& registry = getRegistry();
- registry.each<LocalTransform, Velocity>([deltaTime, this](LocalTransform& transform, Velocity& velocity) {
- transform.position += velocity.linear * deltaTime;
-
- // Bounce off edges
- if (transform.position.x < 0 || transform.position.x > getWidth()) {
- velocity.linear.x *= -1.0f;
- }
- });
-
- // Check for touch input
- if (getInput().isTouchPressed()) {
- auto pos = getInput().getTouchPosition();
- ES_LOG_DEBUG("Touch at ({}, {})", pos.x, pos.y);
- }
-
- // Check for key input
+ (void)deltaTime;
if (getInput().isKeyPressed(KeyCode::Escape)) {
quit();
}
}
void onRender() override {
- auto& registry = getRegistry();
auto& renderer = getRenderer();
- // Draw colored quads for entities with LocalTransform and Sprite
- auto view = registry.view<LocalTransform, Sprite>();
- for (auto entity : view) {
- auto& transform = view.get<LocalTransform>(entity);
- auto& sprite = view.get<Sprite>(entity);
+ // Draw a simple quad
+ renderer.drawQuad(
+ glm::vec2(400.0f, 450.0f),
+ glm::vec2(100.0f, 100.0f),
+ glm::vec4(1.0f, 0.5f, 0.2f, 1.0f)
+ );
+
+ // Draw SDF text
+ if (sdfFont_ && uiContext_) {
+ auto& uiRenderer = uiContext_->getRenderer();
+
+ glm::mat4 projection = glm::ortho(
+ 0.0f, static_cast<f32>(getWidth()),
+ static_cast<f32>(getHeight()), 0.0f,
+ -1.0f, 1.0f
+ );
+
+ uiRenderer.begin(projection);
- renderer.drawQuad(
- glm::vec2(transform.position.x, transform.position.y),
- sprite.size * 50.0f,
- sprite.color
+ // English text
+ uiRenderer.drawText(
+ "Hello SDF Font!",
+ {50.0f, 50.0f},
+ *sdfFont_,
+ 32.0f,
+ {1.0f, 1.0f, 1.0f, 1.0f}
);
- }
- // Draw the main triangle
- auto triangleView = registry.view<LocalTransform, Name>();
- for (auto entity : triangleView) {
- auto& transform = triangleView.get<LocalTransform>(entity);
- auto& name = triangleView.get<Name>(entity);
-
- if (name.value == "Triangle") {
- renderer.drawQuad(
- glm::vec2(transform.position.x, transform.position.y),
- glm::vec2(100.0f, 100.0f),
- glm::vec4(1.0f, 0.5f, 0.2f, 1.0f)
- );
- }
- }
- }
+ // Chinese text
+ uiRenderer.drawText(
+ "你好,世界!中文测试",
+ {50.0f, 100.0f},
+ *sdfFont_,
+ 32.0f,
+ {1.0f, 1.0f, 0.0f, 1.0f}
+ );
+
+ // Mixed text
+ uiRenderer.drawText(
+ "ESEngine 引擎 - SDF字体渲染",
+ {50.0f, 150.0f},
+ *sdfFont_,
+ 28.0f,
+ {0.5f, 1.0f, 0.5f, 1.0f}
+ );
+
+ // Different sizes to show SDF scaling
+ uiRenderer.drawText(
+ "Small 小字 16px",
+ {50.0f, 200.0f},
+ *sdfFont_,
+ 16.0f,
+ {0.8f, 0.8f, 1.0f, 1.0f}
+ );
+
+ uiRenderer.drawText(
+ "Large 大字 48px",
+ {50.0f, 240.0f},
+ *sdfFont_,
+ 48.0f,
+ {1.0f, 0.6f, 0.6f, 1.0f}
+ );
- void onTouch(TouchType type, const TouchPoint& point) override {
- if (type == TouchType::Begin) {
- // Create new entity at touch position
- auto& registry = getRegistry();
- Entity entity = registry.create();
- registry.emplace<Transform>(entity, glm::vec3(point.x, point.y, 0.0f));
- registry.emplace<Sprite>(entity);
- registry.emplace<Velocity>(entity, glm::vec3(
- (rand() % 200 - 100.0f),
- (rand() % 200 - 100.0f),
- 0.0f
- ));
+ uiRenderer.drawText(
+ "动态加载 Dynamic Loading",
+ {50.0f, 320.0f},
+ *sdfFont_,
+ 24.0f,
+ {0.6f, 0.9f, 1.0f, 1.0f}
+ );
+
+ uiRenderer.end();
}
}
void onShutdown() override {
- ES_LOG_INFO("Hello Triangle shutdown");
+ sdfFont_.reset();
+ uiContext_.reset();
+ ES_LOG_INFO("SDF Font Test shutdown");
}
+
+private:
+ Dispatcher dispatcher_;
+ Unique<ui::UIContext> uiContext_;
+ Unique<ui::SDFFont> sdfFont_;
};
// Entry point
@@ -136,6 +170,5 @@ int main() {
return 0;
}
#else
-// For web, entry is through the C API
ES_MAIN(HelloTriangleApp)
#endif
diff --git a/src/esengine/editor/EditorApplication.cpp b/src/esengine/editor/EditorApplication.cpp
index 278d2de8c..bba427827 100644
--- a/src/esengine/editor/EditorApplication.cpp
+++ b/src/esengine/editor/EditorApplication.cpp
@@ -62,17 +62,19 @@ void EditorApplication::onInit() {
const char* fontPaths[] = {
#ifdef ES_PLATFORM_WINDOWS
+ "C:/Windows/Fonts/msyh.ttc",
+ "C:/Windows/Fonts/msyhl.ttc",
+ "C:/Windows/Fonts/simhei.ttf",
"C:/Windows/Fonts/segoeui.ttf",
"C:/Windows/Fonts/arial.ttf",
- "C:/Windows/Fonts/tahoma.ttf",
#elif defined(ES_PLATFORM_MACOS)
+ "/System/Library/Fonts/PingFang.ttc",
+ "/System/Library/Fonts/Hiragino Sans GB.ttc",
"/System/Library/Fonts/SFNS.ttf",
- "/System/Library/Fonts/Helvetica.ttc",
- "/Library/Fonts/Arial.ttf",
#else
+ "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
+ "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
- "/usr/share/fonts/TTF/DejaVuSans.ttf",
- "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
#endif
"assets/fonts/default.ttf",
nullptr
@@ -80,8 +82,8 @@ void EditorApplication::onInit() {
bool fontLoaded = false;
for (const char** path = fontPaths; *path != nullptr; ++path) {
- if (uiContext_->loadFont("default", *path, 24.0f)) {
- ES_LOG_INFO("Loaded font: {}", *path);
+ if (uiContext_->loadFont("default", *path, 48.0f, 8.0f)) {
+ ES_LOG_INFO("Loaded SDF font: {}", *path);
fontLoaded = true;
break;
}
diff --git a/src/esengine/editor/panels/AssetGridItem.cpp b/src/esengine/editor/panels/AssetGridItem.cpp
index 8ab9ef279..e7c49849f 100644
--- a/src/esengine/editor/panels/AssetGridItem.cpp
+++ b/src/esengine/editor/panels/AssetGridItem.cpp
@@ -11,7 +11,7 @@
#include "AssetGridItem.hpp"
#include "../../ui/UIContext.hpp"
-#include "../../ui/font/Font.hpp"
+#include "../../ui/font/SDFFont.hpp"
#include "../../ui/rendering/UIBatchRenderer.hpp"
#include <chrono>
@@ -30,6 +30,61 @@ f64 getCurrentTimeSeconds() {
return std::chrono::duration<f64>(duration).count();
}
+std::string truncateText(const std::string& text, ui::SDFFont& font, f32 fontSize, f32 maxWidth) {
+ glm::vec2 textSize = font.measureText(text, fontSize);
+ if (textSize.x <= maxWidth) {
+ return text;
+ }
+
+ const std::string ellipsis = "...";
+ f32 ellipsisWidth = font.measureText(ellipsis, fontSize).x;
+ f32 availableWidth = maxWidth - ellipsisWidth;
+
+ if (availableWidth <= 0) {
+ return ellipsis;
+ }
+
+ std::string result;
+ f32 currentWidth = 0.0f;
+ const u8* ptr = reinterpret_cast<const u8*>(text.data());
+ const u8* end = ptr + text.size();
+
+ while (ptr < end) {
+ const u8* charStart = ptr;
+ u32 codepoint;
+
+ if ((*ptr & 0x80) == 0) {
+ codepoint = *ptr++;
+ } else if ((*ptr & 0xE0) == 0xC0) {
+ codepoint = (*ptr++ & 0x1F) << 6;
+ if (ptr < end) codepoint |= (*ptr++ & 0x3F);
+ } else if ((*ptr & 0xF0) == 0xE0) {
+ codepoint = (*ptr++ & 0x0F) << 12;
+ if (ptr < end) codepoint |= (*ptr++ & 0x3F) << 6;
+ if (ptr < end) codepoint |= (*ptr++ & 0x3F);
+ } else if ((*ptr & 0xF8) == 0xF0) {
+ codepoint = (*ptr++ & 0x07) << 18;
+ if (ptr < end) codepoint |= (*ptr++ & 0x3F) << 12;
+ if (ptr < end) codepoint |= (*ptr++ & 0x3F) << 6;
+ if (ptr < end) codepoint |= (*ptr++ & 0x3F);
+ } else {
+ ptr++;
+ continue;
+ }
+
+ f32 charWidth = font.getCharWidth(codepoint, fontSize);
+ if (currentWidth + charWidth > availableWidth) {
+ break;
+ }
+
+ currentWidth += charWidth;
+ result.append(reinterpret_cast<const char*>(charStart),
+ static_cast<usize>(ptr - charStart));
+ }
+
+ return result + ellipsis;
+}
+
} // namespace
// =============================================================================
@@ -93,18 +148,20 @@ void AssetGridItem::render(ui::UIBatchRenderer& renderer) {
glm::vec4 iconColor = getAssetTypeColor(entry_.type);
renderer.drawRoundedRect(iconBounds, iconColor, ui::CornerRadii::all(6.0f));
- ui::Font* font = ctx->getDefaultFont();
+ ui::SDFFont* font = ctx->getDefaultFont();
if (font) {
+ f32 labelWidth = bounds.width - 8.0f;
ui::Rect labelBounds{
bounds.x + 4.0f,
bounds.y + ICON_PADDING + ICON_SIZE + 4.0f,
- bounds.width - 8.0f,
+ labelWidth,
LABEL_HEIGHT
};
+ std::string displayName = truncateText(entry_.name, *font, 11.0f, labelWidth);
glm::vec4 textColor = theme.colors.textPrimary;
renderer.drawTextInBounds(
- entry_.name,
+ displayName,
labelBounds,
*font,
11.0f,
diff --git a/src/esengine/ui/UIContext.cpp b/src/esengine/ui/UIContext.cpp
index 11f69a0b6..29c43402a 100644
--- a/src/esengine/ui/UIContext.cpp
+++ b/src/esengine/ui/UIContext.cpp
@@ -14,7 +14,7 @@
#include "../events/Dispatcher.hpp"
#include "../renderer/RenderCommand.hpp"
#include "../renderer/RenderContext.hpp"
-#include "font/Font.hpp"
+#include "font/SDFFont.hpp"
#include "rendering/UIBatchRenderer.hpp"
#include "widgets/Widget.hpp"
@@ -107,24 +107,25 @@ void UIContext::setTheme(Unique<Theme> theme) {
}
// =============================================================================
-// Font Management
+// Font Management (SDF-based)
// =============================================================================
-Font* UIContext::loadFont(const std::string& name, const std::string& path, f32 baseSize) {
- auto font = Font::create(path, baseSize);
+SDFFont* UIContext::loadFont(const std::string& name, const std::string& path, f32 fontSize,
+ f32 sdfSpread) {
+ auto font = SDFFont::create(path, fontSize, sdfSpread);
if (!font) {
ES_LOG_ERROR("Failed to load font: {}", path);
return nullptr;
}
- Font* ptr = font.get();
+ SDFFont* ptr = font.get();
fonts_[name] = std::move(font);
- ES_LOG_INFO("Loaded font '{}' from {}", name, path);
+ ES_LOG_INFO("Loaded SDF font '{}' from {}", name, path);
return ptr;
}
-Font* UIContext::getFont(const std::string& name) {
+SDFFont* UIContext::getFont(const std::string& name) {
auto it = fonts_.find(name);
if (it != fonts_.end()) {
return it->second.get();
@@ -132,7 +133,7 @@ Font* UIContext::getFont(const std::string& name) {
return nullptr;
}
-Font* UIContext::getDefaultFont() {
+SDFFont* UIContext::getDefaultFont() {
return getFont(defaultFontName_);
}
diff --git a/src/esengine/ui/UIContext.hpp b/src/esengine/ui/UIContext.hpp
index 32edfd924..94a376265 100644
--- a/src/esengine/ui/UIContext.hpp
+++ b/src/esengine/ui/UIContext.hpp
@@ -33,10 +33,13 @@ class Dispatcher;
namespace ui {
-class Font;
+class SDFFont;
class UIBatchRenderer;
class Widget;
+// Alias for backward compatibility - Font now means SDFFont
+using Font = SDFFont;
+
// =============================================================================
// UIContext Class
// =============================================================================
@@ -133,30 +136,32 @@ public:
const Theme& getTheme() const { return *theme_; }
// =========================================================================
- // Font Management
+ // Font Management (SDF-based)
// =========================================================================
/**
- * @brief Loads a font from file
+ * @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 baseSize Base size for atlas generation
+ * @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
*/
- Font* loadFont(const std::string& name, const std::string& path, f32 baseSize = 32.0f);
+ 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
*/
- Font* getFont(const std::string& name);
+ SDFFont* getFont(const std::string& name);
/**
* @brief Gets the default font
* @return Pointer to the default font or nullptr
*/
- Font* getDefaultFont();
+ SDFFont* getDefaultFont();
/**
* @brief Sets the default font name
@@ -332,7 +337,7 @@ private:
Unique<Widget> root_;
Unique<Theme> theme_;
- std::unordered_map<std::string, Unique<Font>> fonts_;
+ std::unordered_map<std::string, Unique<SDFFont>> fonts_;
std::string defaultFontName_ = "default";
u32 viewportWidth_ = 0;
diff --git a/src/esengine/ui/core/Theme.hpp b/src/esengine/ui/core/Theme.hpp
index 053d19e8a..539e2b88a 100644
--- a/src/esengine/ui/core/Theme.hpp
+++ b/src/esengine/ui/core/Theme.hpp
@@ -153,12 +153,12 @@ struct ThemeSpacing {
struct ThemeTypography {
std::string defaultFont = "default";
- f32 fontSizeSmall = 14.0f;
- f32 fontSizeNormal = 16.0f;
- f32 fontSizeMedium = 20.0f;
- f32 fontSizeLarge = 24.0f;
- f32 fontSizeTitle = 28.0f;
- f32 fontSizeHeader = 36.0f;
+ f32 fontSizeSmall = 12.0f;
+ f32 fontSizeNormal = 14.0f;
+ f32 fontSizeMedium = 18.0f;
+ f32 fontSizeLarge = 22.0f;
+ f32 fontSizeTitle = 26.0f;
+ f32 fontSizeHeader = 32.0f;
f32 lineHeight = 1.4f;
f32 letterSpacing = 0.0f;
diff --git a/src/esengine/ui/docking/DockTabBar.cpp b/src/esengine/ui/docking/DockTabBar.cpp
index ecaa3da55..fe2743dbf 100644
--- a/src/esengine/ui/docking/DockTabBar.cpp
+++ b/src/esengine/ui/docking/DockTabBar.cpp
@@ -14,7 +14,7 @@
#include "DockPanel.hpp"
#include "../UIContext.hpp"
#include "../rendering/UIBatchRenderer.hpp"
-#include "../font/Font.hpp"
+#include "../font/SDFFont.hpp"
#include <cmath>
@@ -166,10 +166,10 @@ void DockTabBar::renderTab(UIBatchRenderer& renderer, const DockTabInfo& tab, us
tab.bounds.height
};
- Font* font = ctx->getDefaultFont();
+ SDFFont* font = ctx->getDefaultFont();
if (font) {
renderer.drawTextInBounds(tab.title, textBounds, *font,
- theme.typography.fontSizeNormal, textColor,
+ theme.typography.fontSizeSmall, textColor,
HAlign::Left, VAlign::Center);
}
diff --git a/src/esengine/ui/font/Font.cpp b/src/esengine/ui/font/Font.cpp
deleted file mode 100644
index 940e8748d..000000000
--- a/src/esengine/ui/font/Font.cpp
+++ /dev/null
@@ -1,384 +0,0 @@
-/**
- * @file Font.cpp
- * @brief Font loading implementation using stb_truetype
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-
-#include "Font.hpp"
-#include "../../core/Log.hpp"
-
-#define STB_TRUETYPE_IMPLEMENTATION
-#include <stb_truetype.h>
-
-#include <algorithm>
-#include <cstring>
-#include <fstream>
-
-#ifdef ES_PLATFORM_WEB
- #include <GLES3/gl3.h>
-#else
- #ifdef _WIN32
- #include <windows.h>
- #endif
- #include <glad/glad.h>
- #ifndef GL_UNPACK_ALIGNMENT
- #define GL_UNPACK_ALIGNMENT 0x0CF5
- #endif
- #ifndef GL_TEXTURE_SWIZZLE_RGBA
- #define GL_TEXTURE_SWIZZLE_RGBA 0x8E46
- #endif
-#endif
-
-namespace esengine::ui {
-
-// =============================================================================
-// Font Internal Data
-// =============================================================================
-
-struct Font::FontData {
- stbtt_fontinfo fontInfo{};
- std::vector<u8> fontBuffer;
- f32 scale = 0.0f;
-};
-
-// =============================================================================
-// Constructor / Destructor
-// =============================================================================
-
-Font::~Font() {
-#if defined(ES_PLATFORM_WEB) || defined(ES_PLATFORM_NATIVE)
- if (atlasTextureId_ != 0) {
- glDeleteTextures(1, &atlasTextureId_);
- atlasTextureId_ = 0;
- }
-#endif
-}
-
-Font::Font(Font&& other) noexcept
- : fontData_(std::move(other.fontData_)),
- baseSize_(other.baseSize_),
- ascent_(other.ascent_),
- descent_(other.descent_),
- lineHeight_(other.lineHeight_),
- atlasTextureId_(other.atlasTextureId_),
- atlasWidth_(other.atlasWidth_),
- atlasHeight_(other.atlasHeight_),
- atlasData_(std::move(other.atlasData_)),
- glyphs_(std::move(other.glyphs_)),
- atlasPackX_(other.atlasPackX_),
- atlasPackY_(other.atlasPackY_),
- atlasRowHeight_(other.atlasRowHeight_) {
- other.atlasTextureId_ = 0;
-}
-
-Font& Font::operator=(Font&& other) noexcept {
- if (this != &other) {
-#if defined(ES_PLATFORM_WEB) || defined(ES_PLATFORM_NATIVE)
- if (atlasTextureId_ != 0) {
- glDeleteTextures(1, &atlasTextureId_);
- }
-#endif
- fontData_ = std::move(other.fontData_);
- baseSize_ = other.baseSize_;
- ascent_ = other.ascent_;
- descent_ = other.descent_;
- lineHeight_ = other.lineHeight_;
- atlasTextureId_ = other.atlasTextureId_;
- atlasWidth_ = other.atlasWidth_;
- atlasHeight_ = other.atlasHeight_;
- atlasData_ = std::move(other.atlasData_);
- glyphs_ = std::move(other.glyphs_);
- atlasPackX_ = other.atlasPackX_;
- atlasPackY_ = other.atlasPackY_;
- atlasRowHeight_ = other.atlasRowHeight_;
- other.atlasTextureId_ = 0;
- }
- return *this;
-}
-
-// =============================================================================
-// Factory Methods
-// =============================================================================
-
-Unique<Font> Font::create(const std::string& path, f32 baseSize) {
- auto font = Unique<Font>(new Font());
- if (!font->loadFromFile(path, baseSize)) {
- return nullptr;
- }
- return font;
-}
-
-Unique<Font> Font::createFromMemory(const u8* data, usize dataSize, f32 baseSize) {
- auto font = Unique<Font>(new Font());
- if (!font->loadFromMemory(data, dataSize, baseSize)) {
- return nullptr;
- }
- return font;
-}
-
-// =============================================================================
-// Loading
-// =============================================================================
-
-bool Font::loadFromFile(const std::string& path, f32 baseSize) {
- std::ifstream file(path, std::ios::binary | std::ios::ate);
- if (!file.is_open()) {
- ES_LOG_ERROR("Failed to open font file: {}", path);
- return false;
- }
-
- auto fileSize = file.tellg();
- file.seekg(0, std::ios::beg);
-
- std::vector<u8> buffer(static_cast<usize>(fileSize));
- if (!file.read(reinterpret_cast<char*>(buffer.data()), fileSize)) {
- ES_LOG_ERROR("Failed to read font file: {}", path);
- return false;
- }
-
- return loadFromMemory(buffer.data(), buffer.size(), baseSize);
-}
-
-bool Font::loadFromMemory(const u8* data, usize dataSize, f32 baseSize) {
- fontData_ = makeUnique<FontData>();
- baseSize_ = baseSize;
-
- fontData_->fontBuffer.resize(dataSize);
- std::memcpy(fontData_->fontBuffer.data(), data, dataSize);
-
- if (!stbtt_InitFont(&fontData_->fontInfo, fontData_->fontBuffer.data(), 0)) {
- ES_LOG_ERROR("Failed to initialize font");
- fontData_.reset();
- return false;
- }
-
- fontData_->scale = stbtt_ScaleForPixelHeight(&fontData_->fontInfo, baseSize_);
-
- int ascent, descent, lineGap;
- stbtt_GetFontVMetrics(&fontData_->fontInfo, &ascent, &descent, &lineGap);
-
- ascent_ = static_cast<f32>(ascent) * fontData_->scale;
- descent_ = static_cast<f32>(-descent) * fontData_->scale;
- lineHeight_ = ascent_ + descent_ + static_cast<f32>(lineGap) * fontData_->scale;
-
- buildAtlas();
- createAtlasTexture();
-
- ES_LOG_INFO("Font loaded: base size {}, atlas {}x{}", baseSize_, atlasWidth_, atlasHeight_);
-
- return true;
-}
-
-// =============================================================================
-// Atlas Building
-// =============================================================================
-
-void Font::buildAtlas() {
- atlasWidth_ = 512;
- atlasHeight_ = 512;
- atlasData_.resize(atlasWidth_ * atlasHeight_, 0);
- atlasPackX_ = 1;
- atlasPackY_ = 1;
- atlasRowHeight_ = 0;
-
- for (u32 c = 32; c < 127; ++c) {
- loadGlyph(c);
- }
-}
-
-void Font::createAtlasTexture() {
-#if defined(ES_PLATFORM_WEB) || defined(ES_PLATFORM_NATIVE)
- glGenTextures(1, &atlasTextureId_);
- glBindTexture(GL_TEXTURE_2D, atlasTextureId_);
-
- 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);
-
-#ifdef ES_PLATFORM_WEB
- glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, atlasWidth_, atlasHeight_, 0, GL_LUMINANCE,
- GL_UNSIGNED_BYTE, atlasData_.data());
-#else
- glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, atlasWidth_, atlasHeight_, 0, GL_RED, GL_UNSIGNED_BYTE,
- atlasData_.data());
-#endif
-
- glBindTexture(GL_TEXTURE_2D, 0);
-#endif
-}
-
-GlyphInfo* Font::loadGlyph(u32 codepoint) {
- if (!fontData_) return nullptr;
-
- auto it = glyphs_.find(codepoint);
- if (it != glyphs_.end()) {
- return &it->second;
- }
-
- int glyphIndex = stbtt_FindGlyphIndex(&fontData_->fontInfo, static_cast<int>(codepoint));
- if (glyphIndex == 0 && codepoint != 0) {
- return nullptr;
- }
-
- int x0, y0, x1, y1;
- stbtt_GetGlyphBitmapBox(&fontData_->fontInfo, glyphIndex, fontData_->scale, fontData_->scale,
- &x0, &y0, &x1, &y1);
-
- int glyphWidth = x1 - x0;
- int glyphHeight = y1 - y0;
-
- int advance, leftBearing;
- stbtt_GetGlyphHMetrics(&fontData_->fontInfo, glyphIndex, &advance, &leftBearing);
-
- GlyphInfo glyph;
- glyph.width = static_cast<f32>(glyphWidth);
- glyph.height = static_cast<f32>(glyphHeight);
- glyph.bearingX = static_cast<f32>(x0);
- glyph.bearingY = static_cast<f32>(-y0);
- glyph.advance = static_cast<f32>(advance) * fontData_->scale;
-
- if (glyphWidth > 0 && glyphHeight > 0) {
- int padding = 1;
-
- if (atlasPackX_ + glyphWidth + padding > static_cast<int>(atlasWidth_)) {
- atlasPackX_ = 1;
- atlasPackY_ += atlasRowHeight_ + padding;
- atlasRowHeight_ = 0;
- }
-
- if (atlasPackY_ + glyphHeight + padding > static_cast<int>(atlasHeight_)) {
- u32 newHeight = atlasHeight_ * 2;
- if (newHeight > 4096) {
- ES_LOG_WARN("Font atlas exceeded maximum size");
- return nullptr;
- }
-
- atlasData_.resize(atlasWidth_ * newHeight, 0);
- atlasHeight_ = newHeight;
-
-#if defined(ES_PLATFORM_WEB) || defined(ES_PLATFORM_NATIVE)
- if (atlasTextureId_ != 0) {
- glDeleteTextures(1, &atlasTextureId_);
- atlasTextureId_ = 0;
- }
- createAtlasTexture();
-#endif
- }
-
- std::vector<u8> bitmap(static_cast<usize>(glyphWidth * glyphHeight));
- stbtt_MakeGlyphBitmap(&fontData_->fontInfo, bitmap.data(), glyphWidth, glyphHeight,
- glyphWidth, fontData_->scale, fontData_->scale, glyphIndex);
-
- for (int row = 0; row < glyphHeight; ++row) {
- int dstY = atlasPackY_ + row;
- int srcOffset = row * glyphWidth;
- int dstOffset = dstY * static_cast<int>(atlasWidth_) + atlasPackX_;
- std::memcpy(&atlasData_[static_cast<usize>(dstOffset)],
- &bitmap[static_cast<usize>(srcOffset)], static_cast<usize>(glyphWidth));
- }
-
- glyph.u0 = static_cast<f32>(atlasPackX_) / static_cast<f32>(atlasWidth_);
- glyph.v0 = static_cast<f32>(atlasPackY_) / static_cast<f32>(atlasHeight_);
- glyph.u1 = static_cast<f32>(atlasPackX_ + glyphWidth) / static_cast<f32>(atlasWidth_);
- glyph.v1 = static_cast<f32>(atlasPackY_ + glyphHeight) / static_cast<f32>(atlasHeight_);
-
- atlasPackX_ += glyphWidth + padding;
- atlasRowHeight_ = (glyphHeight > atlasRowHeight_) ? glyphHeight : atlasRowHeight_;
-
-#if defined(ES_PLATFORM_WEB) || defined(ES_PLATFORM_NATIVE)
- if (atlasTextureId_ != 0) {
- glBindTexture(GL_TEXTURE_2D, atlasTextureId_);
-#ifdef ES_PLATFORM_WEB
- glTexSubImage2D(GL_TEXTURE_2D, 0, atlasPackX_ - glyphWidth - padding, atlasPackY_,
- glyphWidth, glyphHeight, GL_LUMINANCE, GL_UNSIGNED_BYTE, bitmap.data());
-#else
- glTexSubImage2D(GL_TEXTURE_2D, 0, atlasPackX_ - glyphWidth - padding, atlasPackY_,
- glyphWidth, glyphHeight, GL_RED, GL_UNSIGNED_BYTE, bitmap.data());
-#endif
- glBindTexture(GL_TEXTURE_2D, 0);
- }
-#endif
- }
-
- auto [insertIt, inserted] = glyphs_.emplace(codepoint, glyph);
- return &insertIt->second;
-}
-
-// =============================================================================
-// Glyph Access
-// =============================================================================
-
-const GlyphInfo* Font::getGlyph(u32 codepoint) const {
- auto it = glyphs_.find(codepoint);
- if (it != glyphs_.end()) {
- return &it->second;
- }
-
- return const_cast<Font*>(this)->loadGlyph(codepoint);
-}
-
-void Font::preloadGlyphs(u32 start, u32 end) {
- for (u32 c = start; c < end; ++c) {
- loadGlyph(c);
- }
-}
-
-// =============================================================================
-// Text Measurement
-// =============================================================================
-
-glm::vec2 Font::measureText(const std::string& text, f32 fontSize) const {
- if (text.empty()) return {0.0f, 0.0f};
-
- f32 scale = fontSize / baseSize_;
- f32 width = 0.0f;
- f32 maxWidth = 0.0f;
- f32 height = fontSize;
- i32 lines = 1;
-
- for (char c : text) {
- if (c == '\n') {
- maxWidth = (width > maxWidth) ? width : maxWidth;
- width = 0.0f;
- lines++;
- continue;
- }
-
- const auto* glyph = getGlyph(static_cast<u32>(c));
- if (glyph) {
- width += glyph->advance * scale;
- }
- }
-
- maxWidth = (width > maxWidth) ? width : maxWidth;
- height = static_cast<f32>(lines) * fontSize * 1.2f;
-
- return {maxWidth, height};
-}
-
-f32 Font::getCharWidth(u32 codepoint, f32 fontSize) const {
- const auto* glyph = getGlyph(codepoint);
- if (!glyph) return 0.0f;
-
- f32 scale = fontSize / baseSize_;
- return glyph->advance * scale;
-}
-
-f32 Font::getKerning(u32 left, u32 right, f32 fontSize) const {
- if (!fontData_) return 0.0f;
-
- int kern = stbtt_GetCodepointKernAdvance(&fontData_->fontInfo, static_cast<int>(left),
- static_cast<int>(right));
-
- f32 scale = fontSize / baseSize_;
- return static_cast<f32>(kern) * fontData_->scale * scale;
-}
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/font/Font.hpp b/src/esengine/ui/font/Font.hpp
deleted file mode 100644
index 4d64a6777..000000000
--- a/src/esengine/ui/font/Font.hpp
+++ /dev/null
@@ -1,210 +0,0 @@
-/**
- * @file Font.hpp
- * @brief Font loading and text rendering support
- * @details Provides TrueType font loading using stb_truetype, glyph caching,
- * and text measurement utilities.
- *
- * @author ESEngine Team
- * @date 2026
- *
- * @copyright Copyright (c) 2026 ESEngine Team
- * Licensed under the MIT License.
- */
-#pragma once
-
-// =============================================================================
-// Includes
-// =============================================================================
-
-#include "../../core/Types.hpp"
-
-#include <glm/glm.hpp>
-
-#include <string>
-#include <unordered_map>
-#include <vector>
-
-namespace esengine::ui {
-
-// =============================================================================
-// Glyph Information
-// =============================================================================
-
-/**
- * @brief Information about a single glyph in the font atlas
- */
-struct GlyphInfo {
- 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;
-};
-
-// =============================================================================
-// Font Class
-// =============================================================================
-
-/**
- * @brief Font for text rendering
- *
- * @details Loads TrueType fonts and generates a texture atlas for efficient
- * text rendering. Supports glyph caching and text measurement.
- *
- * @code
- * auto font = Font::create("assets/fonts/Roboto.ttf", 16.0f);
- * if (font) {
- * glm::vec2 size = font->measureText("Hello World", 16.0f);
- * // Use with UIBatchRenderer::drawText()
- * }
- * @endcode
- */
-class Font {
-public:
- ~Font();
-
- // Non-copyable
- Font(const Font&) = delete;
- Font& operator=(const Font&) = delete;
-
- // Move-only
- Font(Font&& other) noexcept;
- Font& operator=(Font&& other) noexcept;
-
- // =========================================================================
- // Factory Methods
- // =========================================================================
-
- /**
- * @brief Creates a font from a file
- * @param path Path to the TTF font file
- * @param baseSize Base size in pixels for atlas generation
- * @return Font instance or nullptr on failure
- */
- static Unique<Font> create(const std::string& path, f32 baseSize = 32.0f);
-
- /**
- * @brief Creates a font from memory
- * @param data Font file data
- * @param dataSize Size of the data in bytes
- * @param baseSize Base size in pixels for atlas generation
- * @return Font instance or nullptr on failure
- */
- static Unique<Font> createFromMemory(const u8* data, usize dataSize, f32 baseSize = 32.0f);
-
- // =========================================================================
- // Properties
- // =========================================================================
-
- /**
- * @brief Gets the base size used for atlas generation
- */
- f32 getBaseSize() const { return baseSize_; }
-
- /**
- * @brief Gets the font ascent (pixels above baseline)
- */
- f32 getAscent() const { return ascent_; }
-
- /**
- * @brief Gets the font descent (pixels below baseline)
- */
- f32 getDescent() const { return descent_; }
-
- /**
- * @brief Gets the line height (ascent + descent + line gap)
- */
- f32 getLineHeight() const { return lineHeight_; }
-
- /**
- * @brief Gets the font atlas texture ID
- */
- u32 getAtlasTextureId() const { return atlasTextureId_; }
-
- /**
- * @brief Gets the atlas dimensions
- */
- glm::ivec2 getAtlasSize() const { return {atlasWidth_, atlasHeight_}; }
-
- // =========================================================================
- // Glyph Access
- // =========================================================================
-
- /**
- * @brief Gets glyph information for a character
- * @param codepoint Unicode codepoint
- * @return Glyph info or nullptr if not available
- */
- const GlyphInfo* getGlyph(u32 codepoint) const;
-
- /**
- * @brief Preloads glyphs for a range of codepoints
- * @param start Starting codepoint
- * @param end Ending codepoint (exclusive)
- */
- void preloadGlyphs(u32 start, u32 end);
-
- // =========================================================================
- // Text Measurement
- // =========================================================================
-
- /**
- * @brief Measures the size of rendered text
- * @param text Text to measure
- * @param fontSize Size to render at
- * @return Width and height in pixels
- */
- glm::vec2 measureText(const std::string& text, f32 fontSize) const;
-
- /**
- * @brief Gets the width of a single character
- * @param codepoint Unicode codepoint
- * @param fontSize Size to render at
- * @return Advance width in pixels
- */
- f32 getCharWidth(u32 codepoint, f32 fontSize) const;
-
- /**
- * @brief Gets kerning between two characters
- * @param left Left character codepoint
- * @param right Right character codepoint
- * @param fontSize Size to render at
- * @return Kerning adjustment in pixels
- */
- f32 getKerning(u32 left, u32 right, f32 fontSize) const;
-
-private:
- Font() = default;
-
- bool loadFromFile(const std::string& path, f32 baseSize);
- bool loadFromMemory(const u8* data, usize dataSize, f32 baseSize);
- void buildAtlas();
- void createAtlasTexture();
- GlyphInfo* loadGlyph(u32 codepoint);
-
- struct FontData;
- Unique<FontData> fontData_;
-
- f32 baseSize_ = 32.0f;
- f32 ascent_ = 0.0f;
- f32 descent_ = 0.0f;
- f32 lineHeight_ = 0.0f;
-
- u32 atlasTextureId_ = 0;
- u32 atlasWidth_ = 0;
- u32 atlasHeight_ = 0;
-
- std::vector<u8> atlasData_;
- std::unordered_map<u32, GlyphInfo> glyphs_;
-
- i32 atlasPackX_ = 0;
- i32 atlasPackY_ = 0;
- i32 atlasRowHeight_ = 0;
-};
-
-} // namespace esengine::ui
diff --git a/src/esengine/ui/font/SDFFont.cpp b/src/esengine/ui/font/SDFFont.cpp
new file mode 100644
index 000000000..f0543d31e
--- /dev/null
+++ b/src/esengine/ui/font/SDFFont.cpp
@@ -0,0 +1,497 @@
+/**
+ * @file SDFFont.cpp
+ * @brief SDF font rendering implementation using FreeType
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+#include "SDFFont.hpp"
+#include "../../core/Log.hpp"
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+#include FT_MODULE_H
+
+#include <algorithm>
+#include <cstring>
+#include <fstream>
+
+#ifdef ES_PLATFORM_WEB
+ #include <GLES3/gl3.h>
+#else
+ #ifdef _WIN32
+ #include <windows.h>
+ #endif
+ #include <glad/glad.h>
+ #ifndef GL_UNPACK_ALIGNMENT
+ #define GL_UNPACK_ALIGNMENT 0x0CF5
+ #endif
+#endif
+
+namespace esengine::ui {
+
+// =============================================================================
+// FreeType Data
+// =============================================================================
+
+struct SDFFont::FTData {
+ FT_Library library = nullptr;
+ FT_Face face = nullptr;
+ std::vector<u8> fontBuffer;
+};
+
+// =============================================================================
+// Constructor / Destructor
+// =============================================================================
+
+SDFFont::~SDFFont() {
+ if (atlasTextureId_ != 0) {
+ glDeleteTextures(1, &atlasTextureId_);
+ atlasTextureId_ = 0;
+ }
+
+ if (ftData_) {
+ if (ftData_->face) {
+ FT_Done_Face(ftData_->face);
+ }
+ if (ftData_->library) {
+ FT_Done_FreeType(ftData_->library);
+ }
+ }
+}
+
+SDFFont::SDFFont(SDFFont&& other) noexcept
+ : ftData_(std::move(other.ftData_)),
+ sdfSize_(other.sdfSize_),
+ sdfSpread_(other.sdfSpread_),
+ ascent_(other.ascent_),
+ descent_(other.descent_),
+ lineHeight_(other.lineHeight_),
+ atlasTextureId_(other.atlasTextureId_),
+ atlasWidth_(other.atlasWidth_),
+ atlasHeight_(other.atlasHeight_),
+ atlasData_(std::move(other.atlasData_)),
+ glyphs_(std::move(other.glyphs_)),
+ lruList_(std::move(other.lruList_)),
+ lruMap_(std::move(other.lruMap_)),
+ maxCachedGlyphs_(other.maxCachedGlyphs_),
+ packX_(other.packX_),
+ packY_(other.packY_),
+ rowHeight_(other.rowHeight_) {
+ other.atlasTextureId_ = 0;
+}
+
+SDFFont& SDFFont::operator=(SDFFont&& other) noexcept {
+ if (this != &other) {
+ if (atlasTextureId_ != 0) {
+ glDeleteTextures(1, &atlasTextureId_);
+ }
+ if (ftData_) {
+ if (ftData_->face) FT_Done_Face(ftData_->face);
+ if (ftData_->library) FT_Done_FreeType(ftData_->library);
+ }
+
+ ftData_ = std::move(other.ftData_);
+ sdfSize_ = other.sdfSize_;
+ sdfSpread_ = other.sdfSpread_;
+ ascent_ = other.ascent_;
+ descent_ = other.descent_;
+ lineHeight_ = other.lineHeight_;
+ atlasTextureId_ = other.atlasTextureId_;
+ atlasWidth_ = other.atlasWidth_;
+ atlasHeight_ = other.atlasHeight_;
+ atlasData_ = std::move(other.atlasData_);
+ glyphs_ = std::move(other.glyphs_);
+ lruList_ = std::move(other.lruList_);
+ lruMap_ = std::move(other.lruMap_);
+ maxCachedGlyphs_ = other.maxCachedGlyphs_;
+ packX_ = other.packX_;
+ packY_ = other.packY_;
+ rowHeight_ = other.rowHeight_;
+ other.atlasTextureId_ = 0;
+ }
+ return *this;
+}
+
+// =============================================================================
+// Factory Methods
+// =============================================================================
+
+Unique<SDFFont> SDFFont::create(const std::string& path, f32 sdfSize, f32 sdfSpread) {
+ auto font = Unique<SDFFont>(new SDFFont());
+ if (!font->loadFromFile(path, sdfSize, sdfSpread)) {
+ return nullptr;
+ }
+ return font;
+}
+
+// =============================================================================
+// Loading
+// =============================================================================
+
+bool SDFFont::loadFromFile(const std::string& path, f32 sdfSize, f32 sdfSpread) {
+ sdfSize_ = sdfSize;
+ sdfSpread_ = sdfSpread;
+
+ std::ifstream file(path, std::ios::binary | std::ios::ate);
+ if (!file.is_open()) {
+ ES_LOG_ERROR("SDFFont: Failed to open font file: {}", path);
+ return false;
+ }
+
+ auto fileSize = file.tellg();
+ file.seekg(0, std::ios::beg);
+
+ ftData_ = makeUnique<FTData>();
+ ftData_->fontBuffer.resize(static_cast<usize>(fileSize));
+
+ if (!file.read(reinterpret_cast<char*>(ftData_->fontBuffer.data()), fileSize)) {
+ ES_LOG_ERROR("SDFFont: Failed to read font file: {}", path);
+ ftData_.reset();
+ return false;
+ }
+
+ FT_Error error = FT_Init_FreeType(&ftData_->library);
+ if (error) {
+ ES_LOG_ERROR("SDFFont: Failed to initialize FreeType: {}", error);
+ ftData_.reset();
+ return false;
+ }
+
+ error = FT_New_Memory_Face(
+ ftData_->library,
+ ftData_->fontBuffer.data(),
+ static_cast<FT_Long>(ftData_->fontBuffer.size()),
+ 0,
+ &ftData_->face
+ );
+
+ if (error) {
+ ES_LOG_ERROR("SDFFont: Failed to create font face: {}", error);
+ FT_Done_FreeType(ftData_->library);
+ ftData_.reset();
+ return false;
+ }
+
+ error = FT_Set_Pixel_Sizes(ftData_->face, 0, static_cast<FT_UInt>(sdfSize_));
+ if (error) {
+ ES_LOG_ERROR("SDFFont: Failed to set pixel size: {}", error);
+ FT_Done_Face(ftData_->face);
+ FT_Done_FreeType(ftData_->library);
+ ftData_.reset();
+ return false;
+ }
+
+ // Set SDF spread parameter
+ FT_UInt spread = static_cast<FT_UInt>(sdfSpread_);
+ FT_Property_Set(ftData_->library, "sdf", "spread", &spread);
+
+ ascent_ = static_cast<f32>(ftData_->face->size->metrics.ascender) / 64.0f;
+ descent_ = static_cast<f32>(-ftData_->face->size->metrics.descender) / 64.0f;
+ lineHeight_ = static_cast<f32>(ftData_->face->size->metrics.height) / 64.0f;
+
+ atlasData_.resize(atlasWidth_ * atlasHeight_, 0);
+
+ glGenTextures(1, &atlasTextureId_);
+ glBindTexture(GL_TEXTURE_2D, atlasTextureId_);
+ 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);
+
+#ifdef ES_PLATFORM_WEB
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, atlasWidth_, atlasHeight_, 0,
+ GL_LUMINANCE, GL_UNSIGNED_BYTE, atlasData_.data());
+#else
+ glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, atlasWidth_, atlasHeight_, 0,
+ GL_RED, GL_UNSIGNED_BYTE, atlasData_.data());
+#endif
+
+ glBindTexture(GL_TEXTURE_2D, 0);
+
+ ES_LOG_INFO("SDFFont loaded: {} (size={}, spread={}, atlas={}x{})",
+ path, sdfSize_, sdfSpread_, atlasWidth_, atlasHeight_);
+
+ preloadASCII();
+
+ return true;
+}
+
+// =============================================================================
+// Glyph Loading
+// =============================================================================
+
+const SDFGlyphInfo* SDFFont::getGlyph(u32 codepoint) {
+ auto it = glyphs_.find(codepoint);
+ if (it != glyphs_.end()) {
+ auto lruIt = lruMap_.find(codepoint);
+ if (lruIt != lruMap_.end()) {
+ lruList_.erase(lruIt->second);
+ lruList_.push_front(codepoint);
+ lruMap_[codepoint] = lruList_.begin();
+ }
+ return &it->second;
+ }
+
+ return loadGlyph(codepoint);
+}
+
+SDFGlyphInfo* SDFFont::loadGlyph(u32 codepoint) {
+ if (!ftData_ || !ftData_->face) return nullptr;
+
+ FT_UInt glyphIndex = FT_Get_Char_Index(ftData_->face, codepoint);
+ if (glyphIndex == 0 && codepoint != 0) {
+ return nullptr;
+ }
+
+ FT_Error error = FT_Load_Glyph(ftData_->face, glyphIndex, FT_LOAD_DEFAULT);
+ if (error) {
+ ES_LOG_WARN("SDFFont: Failed to load glyph for codepoint {}: {}", codepoint, error);
+ return nullptr;
+ }
+
+ // Try SDF rendering first, fall back to normal if not available
+ error = FT_Render_Glyph(ftData_->face->glyph, FT_RENDER_MODE_SDF);
+ if (error) {
+ // Fallback to normal rendering
+ error = FT_Render_Glyph(ftData_->face->glyph, FT_RENDER_MODE_NORMAL);
+ if (error) {
+ ES_LOG_WARN("SDFFont: Failed to render glyph for codepoint {}: {}", codepoint, error);
+ return nullptr;
+ }
+ }
+
+ FT_GlyphSlot slot = ftData_->face->glyph;
+ FT_Bitmap& bitmap = slot->bitmap;
+
+ SDFGlyphInfo glyph;
+ glyph.width = static_cast<f32>(bitmap.width);
+ glyph.height = static_cast<f32>(bitmap.rows);
+ glyph.bearingX = static_cast<f32>(slot->bitmap_left);
+ glyph.bearingY = static_cast<f32>(slot->bitmap_top);
+ glyph.advance = static_cast<f32>(slot->advance.x) / 64.0f;
+
+ if (bitmap.width > 0 && bitmap.rows > 0) {
+ i32 glyphW = static_cast<i32>(bitmap.width);
+ i32 glyphH = static_cast<i32>(bitmap.rows);
+ i32 padding = 1;
+
+ while (glyphs_.size() >= maxCachedGlyphs_) {
+ evictLRU();
+ }
+
+ i32 atlasX, atlasY;
+ if (!findAtlasSpace(glyphW + padding, glyphH + padding, atlasX, atlasY)) {
+ packX_ = 1;
+ packY_ = 1;
+ rowHeight_ = 0;
+ atlasData_.assign(atlasWidth_ * atlasHeight_, 0);
+
+ for (auto& [cp, g] : glyphs_) {
+ g.u0 = g.v0 = g.u1 = g.v1 = 0.0f;
+ }
+ glyphs_.clear();
+ lruList_.clear();
+ lruMap_.clear();
+
+ if (!findAtlasSpace(glyphW + padding, glyphH + padding, atlasX, atlasY)) {
+ ES_LOG_ERROR("SDFFont: Glyph too large for atlas");
+ return nullptr;
+ }
+ }
+
+ for (i32 row = 0; row < glyphH; ++row) {
+ i32 srcOffset = row * static_cast<i32>(bitmap.pitch);
+ i32 dstOffset = (atlasY + row) * static_cast<i32>(atlasWidth_) + atlasX;
+ std::memcpy(&atlasData_[static_cast<usize>(dstOffset)],
+ &bitmap.buffer[srcOffset],
+ static_cast<usize>(glyphW));
+ }
+
+ glyph.atlasX = atlasX;
+ glyph.atlasY = atlasY;
+ glyph.atlasWidth = glyphW;
+ glyph.atlasHeight = glyphH;
+
+ glyph.u0 = static_cast<f32>(atlasX) / static_cast<f32>(atlasWidth_);
+ glyph.v0 = static_cast<f32>(atlasY) / static_cast<f32>(atlasHeight_);
+ glyph.u1 = static_cast<f32>(atlasX + glyphW) / static_cast<f32>(atlasWidth_);
+ glyph.v1 = static_cast<f32>(atlasY + glyphH) / static_cast<f32>(atlasHeight_);
+
+ glBindTexture(GL_TEXTURE_2D, atlasTextureId_);
+#ifdef ES_PLATFORM_WEB
+ glTexSubImage2D(GL_TEXTURE_2D, 0, atlasX, atlasY, glyphW, glyphH,
+ GL_LUMINANCE, GL_UNSIGNED_BYTE, bitmap.buffer);
+#else
+ glTexSubImage2D(GL_TEXTURE_2D, 0, atlasX, atlasY, glyphW, glyphH,
+ GL_RED, GL_UNSIGNED_BYTE, bitmap.buffer);
+#endif
+ glBindTexture(GL_TEXTURE_2D, 0);
+
+ markAtlasRegionUsed(atlasX, atlasY, glyphW + padding, glyphH + padding);
+ }
+
+ auto [insertIt, inserted] = glyphs_.emplace(codepoint, glyph);
+ if (inserted) {
+ lruList_.push_front(codepoint);
+ lruMap_[codepoint] = lruList_.begin();
+ }
+
+ return &insertIt->second;
+}
+
+// =============================================================================
+// LRU Cache Management
+// =============================================================================
+
+void SDFFont::evictLRU() {
+ if (lruList_.empty()) return;
+
+ u32 evictCodepoint = lruList_.back();
+ lruList_.pop_back();
+ lruMap_.erase(evictCodepoint);
+
+ auto it = glyphs_.find(evictCodepoint);
+ if (it != glyphs_.end()) {
+ markAtlasRegionFree(it->second.atlasX, it->second.atlasY,
+ it->second.atlasWidth, it->second.atlasHeight);
+ glyphs_.erase(it);
+ }
+}
+
+void SDFFont::clearCache() {
+ glyphs_.clear();
+ lruList_.clear();
+ lruMap_.clear();
+ packX_ = 1;
+ packY_ = 1;
+ rowHeight_ = 0;
+ atlasData_.assign(atlasWidth_ * atlasHeight_, 0);
+ rebuildAtlasTexture();
+}
+
+// =============================================================================
+// Atlas Space Management
+// =============================================================================
+
+bool SDFFont::findAtlasSpace(i32 width, i32 height, i32& outX, i32& outY) {
+ if (packX_ + width > static_cast<i32>(atlasWidth_)) {
+ packX_ = 1;
+ packY_ += rowHeight_ + 1;
+ rowHeight_ = 0;
+ }
+
+ if (packY_ + height > static_cast<i32>(atlasHeight_)) {
+ return false;
+ }
+
+ outX = packX_;
+ outY = packY_;
+ packX_ += width;
+ rowHeight_ = std::max(rowHeight_, height);
+
+ return true;
+}
+
+void SDFFont::markAtlasRegionUsed(i32 x, i32 y, i32 width, i32 height) {
+ (void)x; (void)y; (void)width; (void)height;
+}
+
+void SDFFont::markAtlasRegionFree(i32 x, i32 y, i32 width, i32 height) {
+ (void)x; (void)y; (void)width; (void)height;
+}
+
+void SDFFont::rebuildAtlasTexture() {
+ if (atlasTextureId_ == 0) return;
+
+ glBindTexture(GL_TEXTURE_2D, atlasTextureId_);
+#ifdef ES_PLATFORM_WEB
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, atlasWidth_, atlasHeight_, 0,
+ GL_LUMINANCE, GL_UNSIGNED_BYTE, atlasData_.data());
+#else
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, atlasWidth_, atlasHeight_, 0,
+ GL_RED, GL_UNSIGNED_BYTE, atlasData_.data());
+#endif
+ glBindTexture(GL_TEXTURE_2D, 0);
+}
+
+// =============================================================================
+// Preloading
+// =============================================================================
+
+void SDFFont::preloadASCII() {
+ for (u32 c = 32; c < 127; ++c) {
+ loadGlyph(c);
+ }
+ ES_LOG_DEBUG("SDFFont: Preloaded {} ASCII glyphs", glyphs_.size());
+}
+
+// =============================================================================
+// Text Measurement
+// =============================================================================
+
+glm::vec2 SDFFont::measureText(const std::string& text, f32 fontSize) {
+ if (text.empty()) return {0.0f, 0.0f};
+
+ f32 scale = fontSize / sdfSize_;
+ f32 width = 0.0f;
+ f32 maxWidth = 0.0f;
+ i32 lines = 1;
+
+ const u8* ptr = reinterpret_cast<const u8*>(text.data());
+ const u8* end = ptr + text.size();
+
+ while (ptr < end) {
+ u32 codepoint;
+ if ((*ptr & 0x80) == 0) {
+ codepoint = *ptr++;
+ } else if ((*ptr & 0xE0) == 0xC0) {
+ codepoint = (*ptr++ & 0x1F) << 6;
+ if (ptr < end) codepoint |= (*ptr++ & 0x3F);
+ } else if ((*ptr & 0xF0) == 0xE0) {
+ codepoint = (*ptr++ & 0x0F) << 12;
+ if (ptr < end) codepoint |= (*ptr++ & 0x3F) << 6;
+ if (ptr < end) codepoint |= (*ptr++ & 0x3F);
+ } else if ((*ptr & 0xF8) == 0xF0) {
+ codepoint = (*ptr++ & 0x07) << 18;
+ if (ptr < end) codepoint |= (*ptr++ & 0x3F) << 12;
+ if (ptr < end) codepoint |= (*ptr++ & 0x3F) << 6;
+ if (ptr < end) codepoint |= (*ptr++ & 0x3F);
+ } else {
+ ptr++;
+ continue;
+ }
+
+ 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) * fontSize * 1.2f;
+
+ return {maxWidth, height};
+}
+
+f32 SDFFont::getCharWidth(u32 codepoint, f32 fontSize) {
+ const auto* glyph = getGlyph(codepoint);
+ if (!glyph) return 0.0f;
+
+ f32 scale = fontSize / sdfSize_;
+ return glyph->advance * scale;
+}
+
+} // namespace esengine::ui
diff --git a/src/esengine/ui/font/SDFFont.hpp b/src/esengine/ui/font/SDFFont.hpp
new file mode 100644
index 000000000..6c1b80b78
--- /dev/null
+++ b/src/esengine/ui/font/SDFFont.hpp
@@ -0,0 +1,192 @@
+/**
+ * @file SDFFont.hpp
+ * @brief SDF font rendering with FreeType
+ * @details Provides Signed Distance Field font rendering using FreeType's
+ * native SDF rasterizer. Supports dynamic glyph loading with LRU
+ * cache for efficient CJK text rendering.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+#pragma once
+
+// =============================================================================
+// Includes
+// =============================================================================
+
+#include "../../core/Types.hpp"
+
+#include <glm/glm.hpp>
+
+#include <list>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+namespace esengine::ui {
+
+// =============================================================================
+// SDF Glyph Information
+// =============================================================================
+
+/**
+ * @brief Information about a single SDF glyph in the atlas
+ */
+struct SDFGlyphInfo {
+ 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;
+
+ i32 atlasX = 0;
+ i32 atlasY = 0;
+ i32 atlasWidth = 0;
+ i32 atlasHeight = 0;
+};
+
+// =============================================================================
+// SDFFont Class
+// =============================================================================
+
+/**
+ * @brief SDF font for high-quality scalable text rendering
+ *
+ * @details Uses FreeType's native SDF rasterizer to generate distance field
+ * glyphs on demand. Features:
+ * - Dynamic glyph loading (efficient for CJK)
+ * - LRU cache with atlas space reclamation
+ * - High quality at any scale
+ * - Support for outline and shadow effects
+ *
+ * @code
+ * auto font = SDFFont::create("assets/fonts/NotoSansCJK.ttf", 48.0f);
+ * if (font) {
+ * // Glyphs are loaded on demand
+ * renderer.drawTextSDF("Hello 你好", position, *font, fontSize, color);
+ * }
+ * @endcode
+ */
+class SDFFont {
+public:
+ ~SDFFont();
+
+ SDFFont(const SDFFont&) = delete;
+ SDFFont& operator=(const SDFFont&) = delete;
+
+ SDFFont(SDFFont&& other) noexcept;
+ SDFFont& operator=(SDFFont&& other) noexcept;
+
+ // =========================================================================
+ // Factory Methods
+ // =========================================================================
+
+ /**
+ * @brief Creates an SDF font from a file
+ * @param path Path to the TTF/OTF font file
+ * @param sdfSize SDF glyph size (recommended: 32-64)
+ * @param sdfSpread SDF spread in pixels (default: 8)
+ * @return Font instance or nullptr on failure
+ */
+ static Unique<SDFFont> create(const std::string& path, f32 sdfSize = 48.0f, f32 sdfSpread = 8.0f);
+
+ // =========================================================================
+ // Properties
+ // =========================================================================
+
+ f32 getSDFSize() const { return sdfSize_; }
+ f32 getSDFSpread() const { return sdfSpread_; }
+ f32 getAscent() const { return ascent_; }
+ f32 getDescent() const { return descent_; }
+ f32 getLineHeight() const { return lineHeight_; }
+ u32 getAtlasTextureId() const { return atlasTextureId_; }
+ glm::ivec2 getAtlasSize() const { return {atlasWidth_, atlasHeight_}; }
+
+ // =========================================================================
+ // Glyph Access
+ // =========================================================================
+
+ /**
+ * @brief Gets glyph information, loading if necessary
+ * @param codepoint Unicode codepoint
+ * @return Glyph info or nullptr if unavailable
+ */
+ const SDFGlyphInfo* getGlyph(u32 codepoint);
+
+ /**
+ * @brief Preloads ASCII glyphs for common use
+ */
+ void preloadASCII();
+
+ // =========================================================================
+ // Text Measurement
+ // =========================================================================
+
+ glm::vec2 measureText(const std::string& text, f32 fontSize);
+ f32 getCharWidth(u32 codepoint, f32 fontSize);
+
+ // =========================================================================
+ // Cache Management
+ // =========================================================================
+
+ /**
+ * @brief Gets the number of cached glyphs
+ */
+ usize getCachedGlyphCount() const { return glyphs_.size(); }
+
+ /**
+ * @brief Sets the maximum number of cached glyphs
+ * @param maxGlyphs Maximum glyphs (default: 2048)
+ */
+ void setMaxCachedGlyphs(usize maxGlyphs) { maxCachedGlyphs_ = maxGlyphs; }
+
+ /**
+ * @brief Clears all cached glyphs
+ */
+ void clearCache();
+
+private:
+ SDFFont() = default;
+
+ bool loadFromFile(const std::string& path, f32 sdfSize, f32 sdfSpread);
+ SDFGlyphInfo* loadGlyph(u32 codepoint);
+ void evictLRU();
+ void rebuildAtlasTexture();
+
+ bool findAtlasSpace(i32 width, i32 height, i32& outX, i32& outY);
+ void markAtlasRegionUsed(i32 x, i32 y, i32 width, i32 height);
+ void markAtlasRegionFree(i32 x, i32 y, i32 width, i32 height);
+
+ struct FTData;
+ Unique<FTData> ftData_;
+
+ f32 sdfSize_ = 48.0f;
+ f32 sdfSpread_ = 8.0f;
+ f32 ascent_ = 0.0f;
+ f32 descent_ = 0.0f;
+ f32 lineHeight_ = 0.0f;
+
+ u32 atlasTextureId_ = 0;
+ u32 atlasWidth_ = 1024;
+ u32 atlasHeight_ = 1024;
+ std::vector<u8> atlasData_;
+
+ std::unordered_map<u32, SDFGlyphInfo> glyphs_;
+ std::list<u32> lruList_;
+ std::unordered_map<u32, std::list<u32>::iterator> lruMap_;
+ usize maxCachedGlyphs_ = 2048;
+
+ i32 packX_ = 1;
+ i32 packY_ = 1;
+ i32 rowHeight_ = 0;
+};
+
+} // namespace esengine::ui
diff --git a/src/esengine/ui/rendering/UIBatchRenderer.cpp b/src/esengine/ui/rendering/UIBatchRenderer.cpp
index b09b59a52..7255a3ea8 100644
--- a/src/esengine/ui/rendering/UIBatchRenderer.cpp
+++ b/src/esengine/ui/rendering/UIBatchRenderer.cpp
@@ -15,7 +15,7 @@
#include "../../renderer/RenderCommand.hpp"
#include "../../renderer/RenderContext.hpp"
#include "../../renderer/Shader.hpp"
-#include "../font/Font.hpp"
+#include "../font/SDFFont.hpp"
#include "../layout/SizeValue.hpp"
#include <array>
@@ -133,7 +133,17 @@ static const char* UI_FRAGMENT_SHADER = R"(
else if (index == 7) texColor = texture2D(u_textures[7], v_texCoord);
vec4 color;
- if (texColor.g == 0.0 && texColor.b == 0.0 && texColor.a == 1.0) {
+
+ // SDF text rendering: borderThickness < -1.0 indicates SDF mode
+ if (v_borderThickness < -1.0) {
+ float screenPxRange = -v_borderThickness - 1.0;
+ float sd = texColor.r;
+ float edgeWidth = 0.5 / max(screenPxRange, 1.0);
+ float alpha = smoothstep(0.5 - edgeWidth, 0.5 + edgeWidth, sd);
+ color = vec4(v_color.rgb, alpha * v_color.a);
+ }
+ // Bitmap font rendering
+ else if (texColor.g == 0.0 && texColor.b == 0.0 && texColor.a == 1.0) {
color = vec4(v_color.rgb, texColor.r * v_color.a);
} else {
color = texColor * v_color;
@@ -223,7 +233,19 @@ static const char* UI_FRAGMENT_SHADER = R"(
void main() {
vec4 texColor = texture(u_textures[v_texIndex], v_texCoord);
vec4 color;
- if (texColor.g == 0.0 && texColor.b == 0.0 && texColor.a == 1.0) {
+
+ // SDF text rendering: borderThickness < -1.0 indicates SDF mode
+ // The absolute value encodes the screen pixel range
+ if (v_borderThickness < -1.0) {
+ float screenPxRange = -v_borderThickness - 1.0;
+ float sd = texColor.r;
+ // FreeType SDF: 0.5 = edge, >0.5 = inside, <0.5 = outside
+ float edgeWidth = 0.5 / max(screenPxRange, 1.0);
+ float alpha = smoothstep(0.5 - edgeWidth, 0.5 + edgeWidth, sd);
+ color = vec4(v_color.rgb, alpha * v_color.a);
+ }
+ // Bitmap font rendering (R8 texture)
+ else if (texColor.g == 0.0 && texColor.b == 0.0 && texColor.a == 1.0) {
color = vec4(v_color.rgb, texColor.r * v_color.a);
} else {
color = texColor * v_color;
@@ -517,7 +539,6 @@ void UIBatchRenderer::addQuadVertices(const Rect& rect, const glm::vec4& color,
f32 texIdx = static_cast<f32>(textureIndex);
glm::vec2 rectSize = {rect.width, rect.height};
glm::vec2 halfSize = rectSize * 0.5f;
- glm::vec2 center = rect.center();
UIVertex vertices[4];
@@ -640,16 +661,54 @@ void UIBatchRenderer::drawLine(const glm::vec2& p1, const glm::vec2& p2, const g
}
// =============================================================================
-// Text Drawing
+// Text Drawing (SDF-based)
// =============================================================================
-void UIBatchRenderer::drawText(const std::string& text, const glm::vec2& position, Font& font,
- f32 fontSize, const glm::vec4& color) {
+namespace {
+
+u32 nextCodepoint(const std::string& text, usize& i) {
+ u8 c = static_cast<u8>(text[i]);
+ u32 codepoint = 0;
+
+ if ((c & 0x80) == 0) {
+ codepoint = c;
+ i += 1;
+ } else if ((c & 0xE0) == 0xC0) {
+ codepoint = c & 0x1F;
+ if (i + 1 < text.size()) {
+ codepoint = (codepoint << 6) | (static_cast<u8>(text[i + 1]) & 0x3F);
+ }
+ i += 2;
+ } else if ((c & 0xF0) == 0xE0) {
+ codepoint = c & 0x0F;
+ if (i + 2 < text.size()) {
+ codepoint = (codepoint << 6) | (static_cast<u8>(text[i + 1]) & 0x3F);
+ codepoint = (codepoint << 6) | (static_cast<u8>(text[i + 2]) & 0x3F);
+ }
+ i += 3;
+ } else if ((c & 0xF8) == 0xF0) {
+ codepoint = c & 0x07;
+ if (i + 3 < text.size()) {
+ codepoint = (codepoint << 6) | (static_cast<u8>(text[i + 1]) & 0x3F);
+ codepoint = (codepoint << 6) | (static_cast<u8>(text[i + 2]) & 0x3F);
+ codepoint = (codepoint << 6) | (static_cast<u8>(text[i + 3]) & 0x3F);
+ }
+ i += 4;
+ } else {
+ i += 1;
+ }
+ return codepoint;
+}
+
+} // namespace
+
+void UIBatchRenderer::drawText(const std::string& text, const glm::vec2& position,
+ SDFFont& font, f32 fontSize, const glm::vec4& color) {
if (text.empty()) return;
f32 x = position.x;
f32 y = position.y;
- f32 scale = fontSize / font.getBaseSize();
+ f32 scale = fontSize / font.getSDFSize();
u32 atlasTexture = font.getAtlasTextureId();
if (atlasTexture == 0) return;
@@ -672,14 +731,23 @@ void UIBatchRenderer::drawText(const std::string& text, const glm::vec2& positio
data_->textureSlotIndex++;
}
- for (char c : text) {
- if (c == '\n') {
+ // Calculate screen pixel range for SDF sharpness
+ // screenPxRange = fontSize / sdfSize * sdfSpread
+ f32 screenPxRange = fontSize / font.getSDFSize() * font.getSDFSpread();
+ // Encode as negative borderThickness: value = -(screenPxRange + 1.0)
+ f32 sdfBorderFlag = -(screenPxRange + 1.0f);
+
+ 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(static_cast<u32>(c));
+ const auto* glyph = font.getGlyph(codepoint);
if (!glyph) continue;
f32 xPos = std::round(x + glyph->bearingX * scale);
@@ -688,9 +756,43 @@ void UIBatchRenderer::drawText(const std::string& text, const glm::vec2& positio
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);
- addQuadVertices(glyphRect, color, {0, 0, 0, 0}, 0.0f, texIndex,
- {glyph->u0, glyph->v0}, {glyph->u1, glyph->v1});
+ 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 = sdfBorderFlag;
+ data_->vertices.push_back(v);
+ }
+
+ data_->indexCount += 6;
data_->stats.textQuadCount++;
}
@@ -698,12 +800,16 @@ void UIBatchRenderer::drawText(const std::string& text, const glm::vec2& positio
}
}
-void UIBatchRenderer::drawTextInBounds(const std::string& text, const Rect& bounds, Font& font,
- f32 fontSize, const glm::vec4& color, HAlign hAlign,
- VAlign vAlign) {
+void UIBatchRenderer::drawTextInBounds(const std::string& text, const Rect& bounds,
+ SDFFont& 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.getSDFSize();
+ f32 ascent = font.getAscent() * scale;
+ f32 descent = font.getDescent() * scale;
+ f32 visualHeight = ascent + descent;
f32 x = bounds.x;
f32 y = bounds.y;
@@ -725,10 +831,10 @@ void UIBatchRenderer::drawTextInBounds(const std::string& text, const Rect& boun
case VAlign::Top:
break;
case VAlign::Center:
- y += (bounds.height - textSize.y) * 0.5f;
+ y += (bounds.height - visualHeight) * 0.5f;
break;
case VAlign::Bottom:
- y += bounds.height - textSize.y;
+ y += bounds.height - visualHeight;
break;
case VAlign::Stretch:
break;
diff --git a/src/esengine/ui/rendering/UIBatchRenderer.hpp b/src/esengine/ui/rendering/UIBatchRenderer.hpp
index 3a1049cdb..4a1cdf8dd 100644
--- a/src/esengine/ui/rendering/UIBatchRenderer.hpp
+++ b/src/esengine/ui/rendering/UIBatchRenderer.hpp
@@ -31,7 +31,10 @@ class RenderContext;
namespace ui {
-class Font;
+class SDFFont;
+
+// Font is now an alias for SDFFont
+using Font = SDFFont;
// =============================================================================
// UI Render Statistics
@@ -197,22 +200,22 @@ public:
f32 thickness = 1.0f);
// =========================================================================
- // Text Drawing
+ // Text Drawing (SDF-based)
// =========================================================================
/**
- * @brief Draws text at a position
+ * @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
*/
- void drawText(const std::string& text, const glm::vec2& position, Font& font, f32 fontSize,
+ void drawText(const std::string& text, const glm::vec2& position, SDFFont& font, f32 fontSize,
const glm::vec4& color);
/**
- * @brief Draws text with clipping to a bounds
+ * @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
@@ -221,7 +224,7 @@ public:
* @param hAlign Horizontal alignment within bounds
* @param vAlign Vertical alignment within bounds
*/
- void drawTextInBounds(const std::string& text, const Rect& bounds, Font& font, f32 fontSize,
+ 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);
diff --git a/src/esengine/ui/widgets/Button.cpp b/src/esengine/ui/widgets/Button.cpp
index e5af74f1a..47e5a2d0e 100644
--- a/src/esengine/ui/widgets/Button.cpp
+++ b/src/esengine/ui/widgets/Button.cpp
@@ -11,7 +11,7 @@
#include "Button.hpp"
#include "../UIContext.hpp"
-#include "../font/Font.hpp"
+#include "../font/SDFFont.hpp"
#include "../rendering/UIBatchRenderer.hpp"
namespace esengine::ui {
@@ -58,7 +58,7 @@ glm::vec2 Button::measure(f32 availableWidth, f32 availableHeight) {
: ctx->getTheme().getButtonStyle();
// Use regular font for measurement
- Font* font = fontName_.empty() ? ctx->getDefaultFont() : ctx->getFont(fontName_);
+ SDFFont* font = fontName_.empty() ? ctx->getDefaultFont() : ctx->getFont(fontName_);
if (font && textSizeDirty_) {
cachedTextSize_ = font->measureText(text_, fontSize_);
textSizeDirty_ = false;
@@ -117,7 +117,7 @@ void Button::render(UIBatchRenderer& renderer) {
Rect textBounds = style.padding.shrink(bounds);
// Use regular font for now
- Font* font = fontName_.empty() ? ctx->getDefaultFont() : ctx->getFont(fontName_);
+ SDFFont* font = fontName_.empty() ? ctx->getDefaultFont() : ctx->getFont(fontName_);
if (font) {
renderer.drawTextInBounds(text_, textBounds, *font, fontSize_, textColor,
HAlign::Center, VAlign::Center);
diff --git a/src/esengine/ui/widgets/Checkbox.cpp b/src/esengine/ui/widgets/Checkbox.cpp
index 88f453fdc..a227f61cf 100644
--- a/src/esengine/ui/widgets/Checkbox.cpp
+++ b/src/esengine/ui/widgets/Checkbox.cpp
@@ -11,7 +11,7 @@
#include "Checkbox.hpp"
#include "../UIContext.hpp"
-#include "../font/Font.hpp"
+#include "../font/SDFFont.hpp"
#include "../rendering/UIBatchRenderer.hpp"
#include "../../math/Math.hpp"
@@ -80,7 +80,7 @@ glm::vec2 Checkbox::measure(f32 availableWidth, f32 availableHeight) {
f32 fontSize = getContext()->getTheme().typography.fontSizeNormal;
// Use regular font for measurement
- Font* font = getContext()->getDefaultFont();
+ SDFFont* font = getContext()->getDefaultFont();
f32 labelWidth;
if (font) {
labelWidth = font->measureText(label_, fontSize).x;
diff --git a/src/esengine/ui/widgets/Label.cpp b/src/esengine/ui/widgets/Label.cpp
index 5c14ea26c..5220a5679 100644
--- a/src/esengine/ui/widgets/Label.cpp
+++ b/src/esengine/ui/widgets/Label.cpp
@@ -11,7 +11,7 @@
#include "Label.hpp"
#include "../UIContext.hpp"
-#include "../font/Font.hpp"
+#include "../font/SDFFont.hpp"
#include "../rendering/UIBatchRenderer.hpp"
namespace esengine::ui {
@@ -53,7 +53,7 @@ glm::vec2 Label::measure(f32 availableWidth, f32 availableHeight) {
return Widget::measure(availableWidth, availableHeight);
}
- Font* font = fontName_.empty() ? getContext()->getDefaultFont()
+ SDFFont* font = fontName_.empty() ? getContext()->getDefaultFont()
: getContext()->getFont(fontName_);
if (font && textSizeDirty_) {
@@ -87,7 +87,7 @@ void Label::render(UIBatchRenderer& renderer) {
glm::vec4 textColor = customColor_ ? color_ : style.getTextColor(getState());
Rect contentBounds = getContentBounds();
- Font* font = fontName_.empty() ? ctx->getDefaultFont() : ctx->getFont(fontName_);
+ SDFFont* font = fontName_.empty() ? ctx->getDefaultFont() : ctx->getFont(fontName_);
if (font) {
renderer.drawTextInBounds(text_, contentBounds, *font, fontSize_, textColor, hAlign_, vAlign_);
}
diff --git a/src/esengine/ui/widgets/TextField.cpp b/src/esengine/ui/widgets/TextField.cpp
index c5cf37c8e..c18f8a2f9 100644
--- a/src/esengine/ui/widgets/TextField.cpp
+++ b/src/esengine/ui/widgets/TextField.cpp
@@ -11,7 +11,7 @@
#include "TextField.hpp"
#include "../UIContext.hpp"
-#include "../font/Font.hpp"
+#include "../font/SDFFont.hpp"
#include "../rendering/UIBatchRenderer.hpp"
#include "../../core/Log.hpp"
#include "../../math/Math.hpp"
@@ -516,7 +516,7 @@ usize TextField::getCharIndexAtX(f32 x) const {
f32 fontSize = getContext()->getTheme().typography.fontSizeNormal;
// Use regular font for character measurement
- Font* font = getContext()->getDefaultFont();
+ SDFFont* font = getContext()->getDefaultFont();
f32 currentX = 0.0f;
for (usize i = 0; i < text_.size(); ++i) {
@@ -545,7 +545,7 @@ f32 TextField::getXForCharIndex(usize index) const {
f32 fontSize = getContext()->getTheme().typography.fontSizeNormal;
// Use regular font for character measurement
- Font* font = getContext()->getDefaultFont();
+ SDFFont* font = getContext()->getDefaultFont();
if (font) {
f32 currentX = 0.0f;
diff --git a/src/esengine/ui/widgets/TreeView.cpp b/src/esengine/ui/widgets/TreeView.cpp
index e20c05c1a..f5e984217 100644
--- a/src/esengine/ui/widgets/TreeView.cpp
+++ b/src/esengine/ui/widgets/TreeView.cpp
@@ -11,7 +11,7 @@
#include "TreeView.hpp"
#include "../UIContext.hpp"
-#include "../font/Font.hpp"
+#include "../font/SDFFont.hpp"
#include "../rendering/UIBatchRenderer.hpp"
#include "../../core/Log.hpp"
#include "../../math/Math.hpp"
diff --git a/third_party/CMakeLists.txt b/third_party/CMakeLists.txt
index 8162bc1e9..b05135b5e 100644
--- a/third_party/CMakeLists.txt
+++ b/third_party/CMakeLists.txt
@@ -91,4 +91,14 @@ if(NOT ES_BUILD_WEB AND NOT ES_BUILD_WXGAME)
endif()
target_compile_definitions(quickjs PUBLIC ES_SCRIPTING_ENABLED)
+
+ # =============================================================================
+ # FreeType - Font rendering library
+ # =============================================================================
+ set(FT_DISABLE_ZLIB ON CACHE BOOL "" FORCE)
+ set(FT_DISABLE_BZIP2 ON CACHE BOOL "" FORCE)
+ set(FT_DISABLE_PNG ON CACHE BOOL "" FORCE)
+ set(FT_DISABLE_HARFBUZZ ON CACHE BOOL "" FORCE)
+ set(FT_DISABLE_BROTLI ON CACHE BOOL "" FORCE)
+ add_subdirectory(freetype)
endif()
diff --git a/third_party/freetype b/third_party/freetype
new file mode 160000
index 000000000..42608f77f
--- /dev/null
+++ b/third_party/freetype
@@ -0,0 +1 @@
+Subproject commit 42608f77f20749dd6ddc9e0536788eaad70ea4b5