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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat: Add MSDF font rendering support
esengine016b46c1c53e
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 0fb501c52..eff54ce1c 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -74,7 +74,10 @@ set(ESENGINE_SOURCES# Font sources (conditional)if(ES_FEATURE_SDF_FONT)- list(APPEND ESENGINE_SOURCES src/esengine/ui/font/SDFFont.cpp)+ list(APPEND ESENGINE_SOURCES+ src/esengine/ui/font/SDFFont.cpp+ src/esengine/ui/font/MSDFFont.cpp+ )endif()if(ES_FEATURE_BITMAP_FONT)@@ -154,7 +157,10 @@ set(ESENGINE_HEADERS# Font headers (conditional)if(ES_FEATURE_SDF_FONT)- list(APPEND ESENGINE_HEADERS src/esengine/ui/font/SDFFont.hpp)+ list(APPEND ESENGINE_HEADERS+ src/esengine/ui/font/SDFFont.hpp+ src/esengine/ui/font/MSDFFont.hpp+ )endif()if(ES_FEATURE_BITMAP_FONT)@@ -279,8 +285,11 @@ 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_link_libraries(esengine PUBLIC freetype msdfgen-core msdfgen-ext)+ target_include_directories(esengine PUBLIC+ ${CMAKE_SOURCE_DIR}/third_party/freetype/include+ ${CMAKE_SOURCE_DIR}/third_party/msdfgen+ )target_compile_definitions(esengine PUBLIC ES_FEATURE_SDF_FONT=1)endif()diff --git a/examples/hello_triangle/main.cpp b/examples/hello_triangle/main.cppindex 9bf0f7224..79c46cf55 100644--- a/examples/hello_triangle/main.cpp+++ b/examples/hello_triangle/main.cpp@@ -2,12 +2,14 @@#include <esengine/ui/UIContext.hpp>#include <esengine/ui/rendering/UIBatchRenderer.hpp>#include <esengine/ui/font/SDFFont.hpp>+#include <esengine/ui/font/MSDFFont.hpp>#include <esengine/events/Dispatcher.hpp>+#include <cstdio>using namespace esengine;using namespace esengine::ecs;-// Demo application with SDF font testing+// Demo application with MSDF font testingclass HelloTriangleApp : public Application {public:HelloTriangleApp() : Application(createConfig()) {}@@ -15,7 +17,7 @@ public:private:static ApplicationConfig createConfig() {ApplicationConfig config;- config.title = "SDF Font Test - 中英文测试";+ config.title = "MSDF Font Test - 中英文测试";config.width = 800;config.height = 600;return config;@@ -23,14 +25,14 @@ private:protected:void onInit() override {- ES_LOG_INFO("SDF Font Test initialized!");+ ES_LOG_INFO("MSDF Font Test initialized!");// Create UI context for font renderinguiContext_ = makeUnique<ui::UIContext>(getRenderContext(), dispatcher_);uiContext_->init();uiContext_->setViewport(getWidth(), getHeight());- // Load SDF font with CJK support+ // Load MSDF font with CJK supportconst char* fontPaths[] = {#ifdef ES_PLATFORM_WEB"/assets/fonts/msyh.ttc", // Embedded font for web@@ -46,6 +48,20 @@ protected:nullptr};+ // Load MSDF font+ for (const char** path = fontPaths; *path != nullptr; ++path) {+ msdfFont_ = ui::MSDFFont::create(*path, 32.0f, 4.0f);+ if (msdfFont_) {+ ES_LOG_INFO("Loaded MSDF font: {}", *path);+ break;+ }+ }++ if (!msdfFont_) {+ ES_LOG_ERROR("Failed to load any MSDF font!");+ }++ // Also load SDF font for comparisonfor (const char** path = fontPaths; *path != nullptr; ++path) {sdfFont_ = ui::SDFFont::create(*path, 48.0f, 8.0f);if (sdfFont_) {@@ -54,10 +70,6 @@ protected:}}- if (!sdfFont_) {- ES_LOG_ERROR("Failed to load any SDF font!");- }-// Create some entitiesauto& registry = getRegistry();Entity triangle = registry.create();@@ -79,13 +91,12 @@ protected:// Draw a simple quadrenderer.drawQuad(- glm::vec2(400.0f, 450.0f),- glm::vec2(100.0f, 100.0f),- glm::vec4(1.0f, 0.5f, 0.2f, 1.0f)+ glm::vec2(400.0f, 550.0f),+ glm::vec2(100.0f, 50.0f),+ glm::vec4(0.2f, 0.2f, 0.3f, 1.0f));- // Draw SDF text- if (sdfFont_ && uiContext_) {+ if (uiContext_) {auto& uiRenderer = uiContext_->getRenderer();glm::mat4 projection = glm::ortho(@@ -96,71 +107,126 @@ protected:uiRenderer.begin(projection);- // English text- uiRenderer.drawText(- "Hello SDF Font!",- {50.0f, 50.0f},- *sdfFont_,- 32.0f,- {1.0f, 1.0f, 1.0f, 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}- );+ if (sdfFont_) {+ uiRenderer.drawText(+ "SDF: Hello World 123",+ {50.0f, 30.0f},+ *sdfFont_,+ 32.0f,+ {0.0f, 1.0f, 1.0f, 1.0f}+ );+ }+ if (msdfFont_) {+ uiRenderer.drawText(+ "MSDF: Hello World 123",+ {50.0f, 70.0f},+ *msdfFont_,+ 32.0f,+ {1.0f, 0.5f, 0.0f, 1.0f}+ );+ }- uiRenderer.drawText(- "Large 大字 48px",- {50.0f, 240.0f},- *sdfFont_,- 48.0f,- {1.0f, 0.6f, 0.6f, 1.0f}- );+ // Draw MSDF text (left side)+ if (msdfFont_) {+ uiRenderer.drawText(+ "MSDF Font:",+ {50.0f, 80.0f},+ *msdfFont_,+ 24.0f,+ {1.0f, 0.8f, 0.0f, 1.0f}+ );++ uiRenderer.drawText(+ "Hello MSDF!",+ {50.0f, 120.0f},+ *msdfFont_,+ 32.0f,+ {1.0f, 1.0f, 1.0f, 1.0f}+ );++ uiRenderer.drawText(+ "你好世界 中文",+ {50.0f, 170.0f},+ *msdfFont_,+ 32.0f,+ {1.0f, 1.0f, 0.0f, 1.0f}+ );++ uiRenderer.drawText(+ "Small 14px",+ {50.0f, 220.0f},+ *msdfFont_,+ 14.0f,+ {0.8f, 0.8f, 1.0f, 1.0f}+ );++ uiRenderer.drawText(+ "Large 48px",+ {50.0f, 250.0f},+ *msdfFont_,+ 48.0f,+ {1.0f, 0.6f, 0.6f, 1.0f}+ );+ }- uiRenderer.drawText(- "动态加载 Dynamic Loading",- {50.0f, 320.0f},- *sdfFont_,- 24.0f,- {0.6f, 0.9f, 1.0f, 1.0f}- );+ // Draw SDF text (right side) for comparison+ if (sdfFont_) {+ uiRenderer.drawText(+ "SDF Font:",+ {420.0f, 30.0f},+ *sdfFont_,+ 24.0f,+ {0.0f, 0.8f, 1.0f, 1.0f}+ );++ uiRenderer.drawText(+ "Hello SDF!",+ {420.0f, 70.0f},+ *sdfFont_,+ 32.0f,+ {1.0f, 1.0f, 1.0f, 1.0f}+ );++ uiRenderer.drawText(+ "你好世界 中文",+ {420.0f, 120.0f},+ *sdfFont_,+ 32.0f,+ {1.0f, 1.0f, 0.0f, 1.0f}+ );++ uiRenderer.drawText(+ "Small 14px",+ {420.0f, 170.0f},+ *sdfFont_,+ 14.0f,+ {0.8f, 0.8f, 1.0f, 1.0f}+ );++ uiRenderer.drawText(+ "Large 48px",+ {420.0f, 200.0f},+ *sdfFont_,+ 48.0f,+ {1.0f, 0.6f, 0.6f, 1.0f}+ );+ }uiRenderer.end();}}void onShutdown() override {+ msdfFont_.reset();sdfFont_.reset();uiContext_.reset();- ES_LOG_INFO("SDF Font Test shutdown");+ ES_LOG_INFO("MSDF Font Test shutdown");}private:Dispatcher dispatcher_;Unique<ui::UIContext> uiContext_;+ Unique<ui::MSDFFont> msdfFont_;Unique<ui::SDFFont> sdfFont_;};diff --git a/src/esengine/editor/EditorApplication.cpp b/src/esengine/editor/EditorApplication.cppindex 2a2aacdc1..6e5329ccc 100644--- a/src/esengine/editor/EditorApplication.cpp+++ b/src/esengine/editor/EditorApplication.cpp@@ -86,8 +86,8 @@ void EditorApplication::onInit() {bool fontLoaded = false;for (const char** path = fontPaths; *path != nullptr; ++path) {- if (uiContext_->loadFont("default", *path, 48.0f, 8.0f)) {- ES_LOG_INFO("Loaded SDF font: {}", *path);+ if (uiContext_->loadMSDFFont("default", *path, 32.0f, 4.0f)) {+ ES_LOG_INFO("Loaded MSDF font: {}", *path);fontLoaded = true;break;}@@ -95,8 +95,8 @@ void EditorApplication::onInit() {if (!fontLoaded) {std::string fallbackFont = PathResolver::editorPath("assets/fonts/default.ttf");- if (uiContext_->loadFont("default", fallbackFont, 48.0f, 8.0f)) {- ES_LOG_INFO("Loaded SDF font: {}", fallbackFont);+ if (uiContext_->loadMSDFFont("default", fallbackFont, 32.0f, 4.0f)) {+ ES_LOG_INFO("Loaded MSDF font: {}", fallbackFont);fontLoaded = true;}}@@ -106,7 +106,7 @@ void EditorApplication::onInit() {}std::string iconFontPath = PathResolver::editorPath("assets/fonts/lucide.ttf");- if (!uiContext_->loadFont("icons", iconFontPath, 48.0f, 4.0f)) {+ if (!uiContext_->loadMSDFFont("icons", iconFontPath, 32.0f, 4.0f)) {ES_LOG_WARN("Icon font not loaded, icons will not render");}diff --git a/src/esengine/editor/panels/AssetGridItem.cpp b/src/esengine/editor/panels/AssetGridItem.cppindex 6f5dd4e73..610ad0c7c 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/SDFFont.hpp"+#include "../../ui/font/MSDFFont.hpp"#include "../../ui/icons/Icons.hpp"#include "../../ui/rendering/UIBatchRenderer.hpp"@@ -46,7 +46,7 @@ const char* getAssetTypeIcon(AssetType type) {}}-std::string truncateText(const std::string& text, ui::SDFFont& font, f32 fontSize, f32 maxWidth) {+std::string truncateText(const std::string& text, ui::MSDFFont& font, f32 fontSize, f32 maxWidth) {glm::vec2 textSize = font.measureText(text, fontSize);if (textSize.x <= maxWidth) {return text;@@ -165,7 +165,7 @@ void AssetGridItem::render(ui::UIBatchRenderer& renderer) {bgColor.a = 0.15f;renderer.drawRoundedRect(iconBounds, bgColor, ui::CornerRadii::all(6.0f));- ui::SDFFont* iconFont = ctx->getIconFont();+ ui::MSDFFont* iconFont = ctx->getIconMSDFFont();if (iconFont) {glm::vec4 iconColor = getAssetTypeColor(entry_.type);const char* icon = getAssetTypeIcon(entry_.type);@@ -173,7 +173,7 @@ void AssetGridItem::render(ui::UIBatchRenderer& renderer) {ui::HAlign::Center, ui::VAlign::Center);}- ui::SDFFont* font = ctx->getDefaultFont();+ ui::MSDFFont* font = ctx->getDefaultMSDFFont();if (font) {f32 labelWidth = bounds.width - 8.0f;ui::Rect labelBounds{diff --git a/src/esengine/ui/UIContext.cpp b/src/esengine/ui/UIContext.cppindex 255ee88bd..9d191ca2e 100644--- a/src/esengine/ui/UIContext.cpp+++ b/src/esengine/ui/UIContext.cpp@@ -19,6 +19,7 @@#if ES_FEATURE_SDF_FONT#include "font/SDFFont.hpp"+#include "font/MSDFFont.hpp"#endif#if ES_FEATURE_BITMAP_FONT@@ -64,6 +65,7 @@ void UIContext::shutdown() {root_.reset();#if ES_FEATURE_SDF_FONTfonts_.clear();+ msdfFonts_.clear();#endif#if ES_FEATURE_BITMAP_FONTbitmapFonts_.clear();@@ -153,6 +155,37 @@ SDFFont* UIContext::getDefaultFont() {SDFFont* UIContext::getIconFont() {return getFont("icons");}++MSDFFont* UIContext::loadMSDFFont(const std::string& name, const std::string& path, f32 fontSize,+ f32 pixelRange) {+ auto font = MSDFFont::create(path, fontSize, pixelRange);+ if (!font) {+ ES_LOG_ERROR("Failed to load MSDF font: {}", path);+ return nullptr;+ }++ MSDFFont* ptr = font.get();+ msdfFonts_[name] = std::move(font);++ ES_LOG_INFO("Loaded MSDF font '{}' from {}", name, path);+ return ptr;+}++MSDFFont* UIContext::getMSDFFont(const std::string& name) {+ auto it = msdfFonts_.find(name);+ if (it != msdfFonts_.end()) {+ return it->second.get();+ }+ return nullptr;+}++MSDFFont* UIContext::getDefaultMSDFFont() {+ return getMSDFFont(defaultFontName_);+}++MSDFFont* UIContext::getIconMSDFFont() {+ return getMSDFFont("icons");+}#endif // ES_FEATURE_SDF_FONT#if ES_FEATURE_BITMAP_FONTdiff --git a/src/esengine/ui/UIContext.hpp b/src/esengine/ui/UIContext.hppindex 2fc68caa0..6e97e7076 100644--- a/src/esengine/ui/UIContext.hpp+++ b/src/esengine/ui/UIContext.hpp@@ -35,6 +35,7 @@ namespace ui {#if ES_FEATURE_SDF_FONTclass SDFFont;+class MSDFFont;#endif#if ES_FEATURE_BITMAP_FONT@@ -159,6 +160,16 @@ public:SDFFont* getFont(const std::string& name);SDFFont* getDefaultFont();SDFFont* getIconFont();++ /**+ * @brief Loads a font from file (uses MSDF rendering for sharper text)+ */+ MSDFFont* loadMSDFFont(const std::string& name, const std::string& path, f32 fontSize = 32.0f,+ f32 pixelRange = 4.0f);++ MSDFFont* getMSDFFont(const std::string& name);+ MSDFFont* getDefaultMSDFFont();+ MSDFFont* getIconMSDFFont();#endif#if ES_FEATURE_BITMAP_FONT@@ -345,6 +356,7 @@ private:#if ES_FEATURE_SDF_FONTstd::unordered_map<std::string, Unique<SDFFont>> fonts_;+ std::unordered_map<std::string, Unique<MSDFFont>> msdfFonts_;#endif#if ES_FEATURE_BITMAP_FONTdiff --git a/src/esengine/ui/docking/DockTabBar.cpp b/src/esengine/ui/docking/DockTabBar.cppindex e00f5c201..28da35971 100644--- a/src/esengine/ui/docking/DockTabBar.cpp+++ b/src/esengine/ui/docking/DockTabBar.cpp@@ -16,7 +16,7 @@#include "../rendering/UIBatchRenderer.hpp"#if ES_FEATURE_SDF_FONT-#include "../font/SDFFont.hpp"+#include "../font/MSDFFont.hpp"#endif#if ES_FEATURE_BITMAP_FONT@@ -174,7 +174,7 @@ void DockTabBar::renderTab(UIBatchRenderer& renderer, const DockTabInfo& tab, us};#if ES_FEATURE_SDF_FONT- SDFFont* font = ctx->getDefaultFont();+ MSDFFont* font = ctx->getDefaultMSDFFont();if (font) {renderer.drawTextInBounds(tab.title, textBounds, *font,theme.typography.fontSizeSmall, textColor,diff --git a/src/esengine/ui/font/MSDFFont.cpp b/src/esengine/ui/font/MSDFFont.cppnew file mode 100644index 000000000..ec5665f65--- /dev/null+++ b/src/esengine/ui/font/MSDFFont.cpp@@ -0,0 +1,411 @@+/**+ * @file MSDFFont.cpp+ * @brief MSDF font rendering implementation using msdfgen+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */++#include "MSDFFont.hpp"+#include "../../core/Log.hpp"++#include <msdfgen.h>+#include <msdfgen-ext.h>++#include <algorithm>+#include <cstdio>+#include <cstring>+#include <fstream>++#ifdef ES_PLATFORM_WEB+ #include <GLES3/gl3.h>+#else+ #ifdef _WIN32+ #include <windows.h>+ #endif+ #include <glad/glad.h>+#endif++#ifndef GL_UNPACK_ALIGNMENT+ #define GL_UNPACK_ALIGNMENT 0x0CF5+#endif++namespace esengine::ui {++// =============================================================================+// Font Data+// =============================================================================++struct MSDFFont::FontData {+ msdfgen::FreetypeHandle* ft = nullptr;+ msdfgen::FontHandle* font = nullptr;+ std::vector<u8> fontBuffer;+};++// =============================================================================+// Constructor / Destructor+// =============================================================================++MSDFFont::~MSDFFont() {+ if (atlasTextureId_ != 0) {+ glDeleteTextures(1, &atlasTextureId_);+ atlasTextureId_ = 0;+ }++ if (fontData_) {+ if (fontData_->font) {+ msdfgen::destroyFont(fontData_->font);+ }+ if (fontData_->ft) {+ msdfgen::deinitializeFreetype(fontData_->ft);+ }+ }+}++MSDFFont::MSDFFont(MSDFFont&& other) noexcept+ : fontData_(std::move(other.fontData_)),+ fontSize_(other.fontSize_),+ pixelRange_(other.pixelRange_),+ 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;+}++MSDFFont& MSDFFont::operator=(MSDFFont&& other) noexcept {+ if (this != &other) {+ if (atlasTextureId_ != 0) {+ glDeleteTextures(1, &atlasTextureId_);+ }+ if (fontData_) {+ if (fontData_->font) msdfgen::destroyFont(fontData_->font);+ if (fontData_->ft) msdfgen::deinitializeFreetype(fontData_->ft);+ }++ fontData_ = std::move(other.fontData_);+ fontSize_ = other.fontSize_;+ pixelRange_ = other.pixelRange_;+ 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+// =============================================================================++Unique<MSDFFont> MSDFFont::create(const std::string& path, f32 fontSize, f32 pixelRange) {+ auto font = Unique<MSDFFont>(new MSDFFont());+ if (!font->loadFromFile(path, fontSize, pixelRange)) {+ return nullptr;+ }+ return font;+}++// =============================================================================+// Loading+// =============================================================================++bool MSDFFont::loadFromFile(const std::string& path, f32 fontSize, f32 pixelRange) {+ fontSize_ = fontSize;+ pixelRange_ = pixelRange;++ std::ifstream file(path, std::ios::binary | std::ios::ate);+ if (!file.is_open()) {+ ES_LOG_ERROR("MSDFFont: Failed to open file: {}", path);+ return false;+ }++ fontData_ = makeUnique<FontData>();++ fontData_->ft = msdfgen::initializeFreetype();+ if (!fontData_->ft) {+ ES_LOG_ERROR("MSDFFont: Failed to initialize FreeType");+ return false;+ }++ fontData_->font = msdfgen::loadFont(fontData_->ft, path.c_str());+ if (!fontData_->font) {+ ES_LOG_ERROR("MSDFFont: Failed to load font: {}", path);+ return false;+ }++ msdfgen::FontMetrics metrics;+ msdfgen::getFontMetrics(metrics, fontData_->font);++ f32 scale = fontSize_ / static_cast<f32>(metrics.emSize);+ ascent_ = static_cast<f32>(metrics.ascenderY) * scale;+ descent_ = static_cast<f32>(-metrics.descenderY) * scale;+ lineHeight_ = static_cast<f32>(metrics.lineHeight) * scale;++ atlasData_.resize(atlasWidth_ * atlasHeight_ * 3, 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);+ glPixelStorei(GL_UNPACK_ALIGNMENT, 1);+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, atlasWidth_, atlasHeight_, 0, GL_RGB, GL_UNSIGNED_BYTE, atlasData_.data());++ ES_LOG_INFO("MSDFFont loaded: {} (size={}, range={}, atlas={}x{})",+ path, fontSize_, pixelRange_, atlasWidth_, atlasHeight_);++ preloadASCII();+ return true;+}++// =============================================================================+// Glyph Loading+// =============================================================================++MSDFGlyphInfo* MSDFFont::loadGlyph(u32 codepoint) {+ if (!fontData_ || !fontData_->font) return nullptr;++ msdfgen::Shape shape;+ double advance;+ if (!msdfgen::loadGlyph(shape, fontData_->font, codepoint, msdfgen::FONT_SCALING_EM_NORMALIZED, &advance)) {+ return nullptr;+ }++ if (shape.contours.empty()) {+ MSDFGlyphInfo& info = glyphs_[codepoint];+ info.width = 0;+ info.height = 0;+ info.bearingX = 0;+ info.bearingY = 0;+ info.advance = static_cast<f32>(advance) * fontSize_;+ info.u0 = info.v0 = info.u1 = info.v1 = 0;+ return &info;+ }++ shape.normalize();+ msdfgen::edgeColoringSimple(shape, 3.0);++ msdfgen::Shape::Bounds bounds = shape.getBounds(pixelRange_ / fontSize_);++ i32 glyphWidth = static_cast<i32>(std::ceil((bounds.r - bounds.l) * fontSize_)) + 2;+ i32 glyphHeight = static_cast<i32>(std::ceil((bounds.t - bounds.b) * fontSize_)) + 2;++ glyphWidth = std::max(glyphWidth, 1);+ glyphHeight = std::max(glyphHeight, 1);++ if (glyphs_.size() >= maxCachedGlyphs_) {+ evictLRU();+ }++ i32 atlasX, atlasY;+ if (!findAtlasSpace(glyphWidth, glyphHeight, atlasX, atlasY)) {+ ES_LOG_WARN("MSDFFont: Atlas full, clearing cache");+ clearCache();+ packX_ = 1;+ packY_ = 1;+ rowHeight_ = 0;+ if (!findAtlasSpace(glyphWidth, glyphHeight, atlasX, atlasY)) {+ return nullptr;+ }+ }++ msdfgen::Bitmap<float, 3> msdf(glyphWidth, glyphHeight);++ msdfgen::Vector2 scale(fontSize_, fontSize_);+ msdfgen::Vector2 translate(1.0 / fontSize_ - bounds.l, 1.0 / fontSize_ - bounds.b);++ double rangeInEm = pixelRange_ / fontSize_;+ msdfgen::Range range(-rangeInEm / 2.0, rangeInEm / 2.0);++ msdfgen::generateMSDF(msdf, shape, range, scale, translate);++ for (i32 y = 0; y < glyphHeight; ++y) {+ for (i32 x = 0; x < glyphWidth; ++x) {+ i32 atlasIdx = ((atlasY + y) * atlasWidth_ + (atlasX + x)) * 3;+ float* pixel = msdf(x, glyphHeight - 1 - y);+ atlasData_[atlasIdx + 0] = static_cast<u8>(std::clamp(pixel[0], 0.0f, 1.0f) * 255.0f);+ atlasData_[atlasIdx + 1] = static_cast<u8>(std::clamp(pixel[1], 0.0f, 1.0f) * 255.0f);+ atlasData_[atlasIdx + 2] = static_cast<u8>(std::clamp(pixel[2], 0.0f, 1.0f) * 255.0f);+ }+ }++ glBindTexture(GL_TEXTURE_2D, atlasTextureId_);++ std::vector<u8> subImage(glyphWidth * glyphHeight * 3);+ for (i32 y = 0; y < glyphHeight; ++y) {+ std::memcpy(&subImage[y * glyphWidth * 3],+ &atlasData_[((atlasY + y) * atlasWidth_ + atlasX) * 3],+ glyphWidth * 3);+ }+ glTexSubImage2D(GL_TEXTURE_2D, 0, atlasX, atlasY, glyphWidth, glyphHeight,+ GL_RGB, GL_UNSIGNED_BYTE, subImage.data());++ MSDFGlyphInfo& info = glyphs_[codepoint];+ info.width = static_cast<f32>(glyphWidth);+ info.height = static_cast<f32>(glyphHeight);+ info.bearingX = static_cast<f32>(bounds.l) * fontSize_ - 1.0f;+ info.bearingY = static_cast<f32>(bounds.t) * fontSize_ + 1.0f;+ info.advance = static_cast<f32>(advance) * fontSize_;++ info.atlasX = atlasX;+ info.atlasY = atlasY;+ info.atlasWidth = glyphWidth;+ info.atlasHeight = glyphHeight;++ info.u0 = static_cast<f32>(atlasX) / atlasWidth_;+ info.v0 = static_cast<f32>(atlasY) / atlasHeight_;+ info.u1 = static_cast<f32>(atlasX + glyphWidth) / atlasWidth_;+ info.v1 = static_cast<f32>(atlasY + glyphHeight) / atlasHeight_;++ lruList_.push_front(codepoint);+ lruMap_[codepoint] = lruList_.begin();++ return &info;+}++const MSDFGlyphInfo* MSDFFont::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);+}++void MSDFFont::preloadASCII() {+ for (u32 c = 32; c < 127; ++c) {+ getGlyph(c);+ }+ ES_LOG_DEBUG("MSDFFont: Preloaded {} ASCII glyphs", 127 - 32);+}++// =============================================================================+// Cache Management+// =============================================================================++void MSDFFont::evictLRU() {+ if (lruList_.empty()) return;++ u32 lruCodepoint = lruList_.back();+ lruList_.pop_back();+ lruMap_.erase(lruCodepoint);+ glyphs_.erase(lruCodepoint);+}++void MSDFFont::clearCache() {+ glyphs_.clear();+ lruList_.clear();+ lruMap_.clear();+ std::fill(atlasData_.begin(), atlasData_.end(), 0);+ rebuildAtlasTexture();+}++void MSDFFont::rebuildAtlasTexture() {+ glBindTexture(GL_TEXTURE_2D, atlasTextureId_);+ glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, atlasWidth_, atlasHeight_,+ GL_RGB, GL_UNSIGNED_BYTE, atlasData_.data());+}++bool MSDFFont::findAtlasSpace(i32 width, i32 height, i32& outX, i32& outY) {+ if (packX_ + width + 1 > static_cast<i32>(atlasWidth_)) {+ packX_ = 1;+ packY_ += rowHeight_ + 1;+ rowHeight_ = 0;+ }++ if (packY_ + height + 1 > static_cast<i32>(atlasHeight_)) {+ return false;+ }++ outX = packX_;+ outY = packY_;+ packX_ += width + 1;+ rowHeight_ = std::max(rowHeight_, height);+ return true;+}++// =============================================================================+// Text Measurement+// =============================================================================++glm::vec2 MSDFFont::measureText(const std::string& text, f32 fontSize) {+ f32 scale = fontSize / fontSize_;+ f32 width = 0.0f;++ usize i = 0;+ while (i < text.size()) {+ u32 codepoint;+ u8 c = static_cast<u8>(text[i]);+ if ((c & 0x80) == 0) {+ codepoint = c;+ i += 1;+ } else if ((c & 0xE0) == 0xC0) {+ codepoint = (c & 0x1F) << 6;+ if (i + 1 < text.size()) codepoint |= (static_cast<u8>(text[i + 1]) & 0x3F);+ i += 2;+ } else if ((c & 0xF0) == 0xE0) {+ codepoint = (c & 0x0F) << 12;+ if (i + 1 < text.size()) codepoint |= (static_cast<u8>(text[i + 1]) & 0x3F) << 6;+ if (i + 2 < text.size()) codepoint |= (static_cast<u8>(text[i + 2]) & 0x3F);+ i += 3;+ } else if ((c & 0xF8) == 0xF0) {+ codepoint = (c & 0x07) << 18;+ if (i + 1 < text.size()) codepoint |= (static_cast<u8>(text[i + 1]) & 0x3F) << 12;+ if (i + 2 < text.size()) codepoint |= (static_cast<u8>(text[i + 2]) & 0x3F) << 6;+ if (i + 3 < text.size()) codepoint |= (static_cast<u8>(text[i + 3]) & 0x3F);+ i += 4;+ } else {+ i += 1;+ continue;+ }++ const MSDFGlyphInfo* glyph = getGlyph(codepoint);+ if (glyph) {+ width += glyph->advance * scale;+ }+ }++ return glm::vec2(width, lineHeight_ * scale);+}++f32 MSDFFont::getCharWidth(u32 codepoint, f32 fontSize) {+ f32 scale = fontSize / fontSize_;+ const MSDFGlyphInfo* glyph = getGlyph(codepoint);+ if (glyph) {+ return glyph->advance * scale;+ }+ return 0.0f;+}++} // namespace esengine::uidiff --git a/src/esengine/ui/font/MSDFFont.hpp b/src/esengine/ui/font/MSDFFont.hppnew file mode 100644index 000000000..135badf13--- /dev/null+++ b/src/esengine/ui/font/MSDFFont.hpp@@ -0,0 +1,136 @@+/**+ * @file MSDFFont.hpp+ * @brief MSDF font rendering with msdfgen+ * @details Provides Multi-channel Signed Distance Field font rendering using+ * msdfgen library. Produces sharper text than single-channel SDF.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */+#pragma once++#include "../../core/Types.hpp"++#include <glm/glm.hpp>++#include <list>+#include <string>+#include <unordered_map>+#include <vector>++namespace esengine::ui {++// =============================================================================+// MSDF Glyph Information+// =============================================================================++struct MSDFGlyphInfo {+ 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;+};++// =============================================================================+// MSDFFont Class+// =============================================================================++class MSDFFont {+public:+ ~MSDFFont();++ MSDFFont(const MSDFFont&) = delete;+ MSDFFont& operator=(const MSDFFont&) = delete;++ MSDFFont(MSDFFont&& other) noexcept;+ MSDFFont& operator=(MSDFFont&& other) noexcept;++ // =========================================================================+ // Factory Methods+ // =========================================================================++ static Unique<MSDFFont> create(const std::string& path, f32 fontSize = 32.0f, f32 pixelRange = 4.0f);++ // =========================================================================+ // Properties+ // =========================================================================++ f32 getFontSize() const { return fontSize_; }+ f32 getPixelRange() const { return pixelRange_; }+ 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+ // =========================================================================++ const MSDFGlyphInfo* getGlyph(u32 codepoint);+ void preloadASCII();++ // =========================================================================+ // Text Measurement+ // =========================================================================++ glm::vec2 measureText(const std::string& text, f32 fontSize);+ f32 getCharWidth(u32 codepoint, f32 fontSize);++ // =========================================================================+ // Cache Management+ // =========================================================================++ usize getCachedGlyphCount() const { return glyphs_.size(); }+ void setMaxCachedGlyphs(usize maxGlyphs) { maxCachedGlyphs_ = maxGlyphs; }+ void clearCache();++private:+ MSDFFont() = default;++ bool loadFromFile(const std::string& path, f32 fontSize, f32 pixelRange);+ MSDFGlyphInfo* loadGlyph(u32 codepoint);+ void evictLRU();+ void rebuildAtlasTexture();++ bool findAtlasSpace(i32 width, i32 height, i32& outX, i32& outY);++ struct FontData;+ Unique<FontData> fontData_;++ f32 fontSize_ = 32.0f;+ f32 pixelRange_ = 4.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_; // RGB format (3 bytes per pixel)++ std::unordered_map<u32, MSDFGlyphInfo> 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::uidiff --git a/src/esengine/ui/font/SDFFont.cpp b/src/esengine/ui/font/SDFFont.cppindex 7491f328e..d20411f3c 100644--- a/src/esengine/ui/font/SDFFont.cpp+++ b/src/esengine/ui/font/SDFFont.cpp@@ -244,6 +244,10 @@ const SDFGlyphInfo* SDFFont::getGlyph(u32 codepoint) {SDFGlyphInfo* SDFFont::loadGlyph(u32 codepoint) {if (!ftData_ || !ftData_->face) return nullptr;+ if (codepoint == 'H') {+ ES_LOG_INFO("SDF: Loading glyph 'H'");+ }+FT_UInt glyphIndex = FT_Get_Char_Index(ftData_->face, codepoint);if (glyphIndex == 0 && codepoint != 0) {return nullptr;@@ -274,6 +278,12 @@ SDFGlyphInfo* SDFFont::loadGlyph(u32 codepoint) {glyph.bearingY = static_cast<f32>(slot->bitmap_top);glyph.advance = static_cast<f32>(slot->advance.x) / 64.0f;+ if (codepoint == 'H') {+ ES_LOG_INFO("SDF 'H': bearingX={:.1f} bearingY={:.1f} advance={:.1f} w={} h={}",+ glyph.bearingX, glyph.bearingY, glyph.advance,+ bitmap.width, bitmap.rows);+ }+if (bitmap.width > 0 && bitmap.rows > 0) {i32 glyphW = static_cast<i32>(bitmap.width);i32 glyphH = static_cast<i32>(bitmap.rows);diff --git a/src/esengine/ui/rendering/UIBatchRenderer.cpp b/src/esengine/ui/rendering/UIBatchRenderer.cppindex 3d5b26178..d86c54913 100644--- a/src/esengine/ui/rendering/UIBatchRenderer.cpp+++ b/src/esengine/ui/rendering/UIBatchRenderer.cpp@@ -19,6 +19,7 @@#if ES_FEATURE_SDF_FONT#include "../font/SDFFont.hpp"+#include "../font/MSDFFont.hpp"#endif#if ES_FEATURE_BITMAP_FONT@@ -27,6 +28,7 @@#include <array>#include <cmath>+#include <cstdio>#include <vector>#ifdef ES_PLATFORM_WEB@@ -126,6 +128,10 @@ static const char* UI_FRAGMENT_SHADER = R"(return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r.x;}+ float median(float r, float g, float b) {+ return max(min(r, g), min(max(r, g), b));+ }+void main() {vec4 texColor = vec4(1.0);int index = int(v_texIndex);@@ -141,8 +147,16 @@ static const char* UI_FRAGMENT_SHADER = R"(vec4 color;+ // MSDF text rendering: borderThickness < -100.0 indicates MSDF mode+ if (v_borderThickness < -100.0) {+ float screenPxRange = -v_borderThickness - 100.0 - 1.0;+ float sd = median(texColor.r, texColor.g, texColor.b);+ 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);+ }// SDF text rendering: borderThickness < -1.0 indicates SDF mode- if (v_borderThickness < -1.0) {+ else if (v_borderThickness < -1.0) {float screenPxRange = -v_borderThickness - 1.0;float sd = texColor.r;float edgeWidth = 0.5 / max(screenPxRange, 1.0);@@ -237,16 +251,26 @@ static const char* UI_FRAGMENT_SHADER = R"(return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r.x;}+ float median(float r, float g, float b) {+ return max(min(r, g), min(max(r, g), b));+ }+void main() {vec4 texColor = texture(u_textures[v_texIndex], v_texCoord);vec4 color;+ // MSDF text rendering: borderThickness < -100.0 indicates MSDF mode+ if (v_borderThickness < -100.0) {+ float screenPxRange = -v_borderThickness - 100.0 - 1.0;+ float sd = median(texColor.r, texColor.g, texColor.b);+ 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);+ }// SDF text rendering: borderThickness < -1.0 indicates SDF mode- // The absolute value encodes the screen pixel range- if (v_borderThickness < -1.0) {+ else 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 = outsidefloat 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);@@ -742,10 +766,7 @@ void UIBatchRenderer::drawText(const std::string& text, const glm::vec2& positiodata_->textureSlotIndex++;}- // Calculate screen pixel range for SDF sharpness- // screenPxRange = fontSize / sdfSize * sdfSpreadf32 screenPxRange = fontSize / font.getSDFSize() * font.getSDFSpread();- // Encode as negative borderThickness: value = -(screenPxRange + 1.0)f32 sdfBorderFlag = -(screenPxRange + 1.0f);usize i = 0;@@ -855,6 +876,146 @@ void UIBatchRenderer::drawTextInBounds(const std::string& text, const Rect& bouny = std::round(y);drawText(text, {x, y}, font, fontSize, color);}++void UIBatchRenderer::drawText(const std::string& text, const glm::vec2& position,+ MSDFFont& 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.getAtlasTextureId();+ 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++;+ }++ f32 screenPxRange = fontSize / font.getFontSize() * font.getPixelRange();+ f32 msdfBorderFlag = -(screenPxRange + 100.0f + 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(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 = msdfBorderFlag;+ 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,+ MSDFFont& 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_SDF_FONT#if ES_FEATURE_BITMAP_FONTdiff --git a/src/esengine/ui/rendering/UIBatchRenderer.hpp b/src/esengine/ui/rendering/UIBatchRenderer.hppindex 44d3a9e5f..7950581ff 100644--- a/src/esengine/ui/rendering/UIBatchRenderer.hpp+++ b/src/esengine/ui/rendering/UIBatchRenderer.hpp@@ -33,6 +33,7 @@ namespace ui {#if ES_FEATURE_SDF_FONTclass SDFFont;+class MSDFFont;#endif#if ES_FEATURE_BITMAP_FONT@@ -223,6 +224,16 @@ public: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);++ /**+ * @brief Draws text using MSDF font for sharper rendering (UTF-8 supported)+ */+ void drawText(const std::string& text, const glm::vec2& position, MSDFFont& font, f32 fontSize,+ const glm::vec4& color);++ void drawTextInBounds(const std::string& text, const Rect& bounds, MSDFFont& font, f32 fontSize,+ const glm::vec4& color, HAlign hAlign = HAlign::Left,+ VAlign vAlign = VAlign::Top);#endif#if ES_FEATURE_BITMAP_FONTdiff --git a/src/esengine/ui/widgets/Button.cpp b/src/esengine/ui/widgets/Button.cppindex 546778983..63dfb059e 100644--- a/src/esengine/ui/widgets/Button.cpp+++ b/src/esengine/ui/widgets/Button.cpp@@ -14,7 +14,7 @@#include "../rendering/UIBatchRenderer.hpp"#if ES_FEATURE_SDF_FONT-#include "../font/SDFFont.hpp"+#include "../font/MSDFFont.hpp"#endif#if ES_FEATURE_BITMAP_FONT@@ -66,7 +66,7 @@ glm::vec2 Button::measure(f32 availableWidth, f32 availableHeight) {if (textSizeDirty_) {#if ES_FEATURE_SDF_FONT- SDFFont* font = fontName_.empty() ? ctx->getDefaultFont() : ctx->getFont(fontName_);+ MSDFFont* font = fontName_.empty() ? ctx->getDefaultMSDFFont() : ctx->getMSDFFont(fontName_);if (font) {cachedTextSize_ = font->measureText(text_, fontSize_);textSizeDirty_ = false;@@ -133,7 +133,7 @@ void Button::render(UIBatchRenderer& renderer) {Rect textBounds = style.padding.shrink(bounds);#if ES_FEATURE_SDF_FONT- SDFFont* font = fontName_.empty() ? ctx->getDefaultFont() : ctx->getFont(fontName_);+ MSDFFont* font = fontName_.empty() ? ctx->getDefaultMSDFFont() : ctx->getMSDFFont(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.cppindex 4795bb466..4ca102bce 100644--- a/src/esengine/ui/widgets/Checkbox.cpp+++ b/src/esengine/ui/widgets/Checkbox.cpp@@ -15,7 +15,7 @@#include "../../math/Math.hpp"#if ES_FEATURE_SDF_FONT-#include "../font/SDFFont.hpp"+#include "../font/MSDFFont.hpp"#endif#if ES_FEATURE_BITMAP_FONT@@ -88,7 +88,7 @@ glm::vec2 Checkbox::measure(f32 availableWidth, f32 availableHeight) {f32 labelWidth = static_cast<f32>(label_.length()) * fontSize * 0.6f;#if ES_FEATURE_SDF_FONT- SDFFont* font = getContext()->getDefaultFont();+ MSDFFont* font = getContext()->getDefaultMSDFFont();if (font) {labelWidth = font->measureText(label_, fontSize).x;}@@ -186,9 +186,9 @@ void Checkbox::render(UIBatchRenderer& renderer) {f32 labelY = bounds.y + (bounds.height - fontSize) * 0.5f;#if ES_FEATURE_SDF_FONT- if (getContext() && getContext()->getDefaultFont()) {+ if (getContext() && getContext()->getDefaultMSDFFont()) {renderer.drawText(label_, glm::vec2(labelX, labelY),- *getContext()->getDefaultFont(), fontSize, textColor);+ *getContext()->getDefaultMSDFFont(), fontSize, textColor);}#elif ES_FEATURE_BITMAP_FONTif (getContext() && getContext()->getDefaultBitmapFont()) {diff --git a/src/esengine/ui/widgets/Label.cpp b/src/esengine/ui/widgets/Label.cppindex 485e79514..0df2324a6 100644--- a/src/esengine/ui/widgets/Label.cpp+++ b/src/esengine/ui/widgets/Label.cpp@@ -14,7 +14,7 @@#include "../rendering/UIBatchRenderer.hpp"#if ES_FEATURE_SDF_FONT-#include "../font/SDFFont.hpp"+#include "../font/MSDFFont.hpp"#endif#if ES_FEATURE_BITMAP_FONT@@ -62,8 +62,8 @@ glm::vec2 Label::measure(f32 availableWidth, f32 availableHeight) {if (textSizeDirty_) {#if ES_FEATURE_SDF_FONT- SDFFont* font = fontName_.empty() ? getContext()->getDefaultFont()- : getContext()->getFont(fontName_);+ MSDFFont* font = fontName_.empty() ? getContext()->getDefaultMSDFFont()+ : getContext()->getMSDFFont(fontName_);if (font) {cachedTextSize_ = font->measureText(text_, fontSize_);textSizeDirty_ = false;@@ -105,7 +105,7 @@ void Label::render(UIBatchRenderer& renderer) {Rect contentBounds = getContentBounds();#if ES_FEATURE_SDF_FONT- SDFFont* font = fontName_.empty() ? ctx->getDefaultFont() : ctx->getFont(fontName_);+ MSDFFont* font = fontName_.empty() ? ctx->getDefaultMSDFFont() : ctx->getMSDFFont(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.cppindex 1d534ec21..cf4f16a95 100644--- a/src/esengine/ui/widgets/TextField.cpp+++ b/src/esengine/ui/widgets/TextField.cpp@@ -16,7 +16,7 @@#include "../../math/Math.hpp"#if ES_FEATURE_SDF_FONT-#include "../font/SDFFont.hpp"+#include "../font/MSDFFont.hpp"#endif#if ES_FEATURE_BITMAP_FONT@@ -152,9 +152,9 @@ void TextField::render(UIBatchRenderer& renderer) {placeholderColor.a *= 0.5f;#if ES_FEATURE_SDF_FONT- if (getContext() && getContext()->getDefaultFont()) {+ if (getContext() && getContext()->getDefaultMSDFFont()) {renderer.drawText(placeholder_, glm::vec2(textX, textY),- *getContext()->getDefaultFont(), fontSize, placeholderColor);+ *getContext()->getDefaultMSDFFont(), fontSize, placeholderColor);}#elif ES_FEATURE_BITMAP_FONTif (getContext() && getContext()->getDefaultBitmapFont()) {@@ -185,9 +185,9 @@ void TextField::render(UIBatchRenderer& renderer) {}#if ES_FEATURE_SDF_FONT- if (getContext() && getContext()->getDefaultFont()) {+ if (getContext() && getContext()->getDefaultMSDFFont()) {renderer.drawText(text_, glm::vec2(textX, textY),- *getContext()->getDefaultFont(), fontSize, textColor);+ *getContext()->getDefaultMSDFFont(), fontSize, textColor);}#elif ES_FEATURE_BITMAP_FONTif (getContext() && getContext()->getDefaultBitmapFont()) {@@ -541,7 +541,7 @@ usize TextField::getCharIndexAtX(f32 x) const {for (usize i = 0; i < text_.size(); ++i) {f32 charWidth = fontSize * 0.6f;#if ES_FEATURE_SDF_FONT- SDFFont* font = getContext()->getDefaultFont();+ MSDFFont* font = getContext()->getDefaultMSDFFont();if (font) {charWidth = font->getCharWidth(static_cast<u32>(text_[i]), fontSize);}@@ -570,7 +570,7 @@ f32 TextField::getXForCharIndex(usize index) const {f32 fontSize = getContext()->getTheme().typography.fontSizeNormal;#if ES_FEATURE_SDF_FONT- SDFFont* font = getContext()->getDefaultFont();+ MSDFFont* font = getContext()->getDefaultMSDFFont();if (font) {f32 currentX = 0.0f;for (usize i = 0; i < index && i < text_.size(); ++i) {diff --git a/src/esengine/ui/widgets/TreeView.cpp b/src/esengine/ui/widgets/TreeView.cppindex eac6da76a..80938d21a 100644--- a/src/esengine/ui/widgets/TreeView.cpp+++ b/src/esengine/ui/widgets/TreeView.cpp@@ -17,7 +17,7 @@#include "../../math/Math.hpp"#if ES_FEATURE_SDF_FONT-#include "../font/SDFFont.hpp"+#include "../font/MSDFFont.hpp"#endif#if ES_FEATURE_BITMAP_FONT@@ -309,7 +309,7 @@ void TreeView::renderNode(UIBatchRenderer& renderer, const TreeNode& node, f32 y}#if ES_FEATURE_SDF_FONT- SDFFont* iconFont = getContext() ? getContext()->getIconFont() : nullptr;+ MSDFFont* iconFont = getContext() ? getContext()->getIconMSDFFont() : nullptr;if (iconFont) {const char* icon = node.expanded ? icons::ChevronDown : icons::ChevronRight;renderer.drawTextInBounds(icon, iconBounds, *iconFont, iconSize_, iconColor,@@ -335,8 +335,8 @@ void TreeView::renderNode(UIBatchRenderer& renderer, const TreeNode& node, f32 yf32 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(),+ if (getContext() && getContext()->getDefaultMSDFFont()) {+ renderer.drawText(node.label, glm::vec2(x, textY), *getContext()->getDefaultMSDFFont(),fontSize, textColor);}#elif ES_FEATURE_BITMAP_FONTdiff --git a/third_party/CMakeLists.txt b/third_party/CMakeLists.txtindex 81e04744b..eed210bad 100644--- a/third_party/CMakeLists.txt+++ b/third_party/CMakeLists.txt@@ -103,3 +103,23 @@ 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)++# Create alias for FreeType to match msdfgen's expected target name+if(NOT TARGET Freetype::Freetype)+ add_library(Freetype::Freetype ALIAS freetype)+endif()++# =============================================================================+# msdfgen - Multi-channel Signed Distance Field generator+# =============================================================================+if(ES_FEATURE_SDF_FONT)+ set(MSDFGEN_CORE_ONLY OFF CACHE BOOL "" FORCE)+ set(MSDFGEN_BUILD_STANDALONE OFF CACHE BOOL "" FORCE)+ set(MSDFGEN_USE_VCPKG OFF CACHE BOOL "" FORCE)+ set(MSDFGEN_USE_OPENMP OFF CACHE BOOL "" FORCE)+ set(MSDFGEN_USE_SKIA OFF CACHE BOOL "" FORCE)+ set(MSDFGEN_DISABLE_SVG ON CACHE BOOL "" FORCE)+ set(MSDFGEN_DISABLE_PNG ON CACHE BOOL "" FORCE)+ set(MSDFGEN_INSTALL OFF CACHE BOOL "" FORCE)+ add_subdirectory(msdfgen)+endif()diff --git a/third_party/msdfgen/.gitattributes b/third_party/msdfgen/.gitattributesnew file mode 100644index 000000000..176a458f9--- /dev/null+++ b/third_party/msdfgen/.gitattributes@@ -0,0 +1 @@+* text=autodiff --git a/third_party/msdfgen/.gitignore b/third_party/msdfgen/.gitignorenew file mode 100644index 000000000..007846a36--- /dev/null+++ b/third_party/msdfgen/.gitignore@@ -0,0 +1,32 @@+/build/+/Debug/+/Release/+/Release OpenMP/+/Debug Library/+/Release Library/+/Release Library OpenMP/+/x86/+/x64/+.vs/+.vscode/+.DS_Store+*.exe+*.zip+*.user+*.sdf+*.pdb+*.ipdb+*.iobj+*.suo+*.VC.opendb+*.VC.db+/bin/*.lib+/bin/msdfgen+output.png+render.png+CMakeUserPresets.json+out/+/all-in-one/+/build_xcode/+/cmake-gen.bat+/line-ending-check.batdiff --git a/third_party/msdfgen/CHANGELOG.md b/third_party/msdfgen/CHANGELOG.mdnew file mode 100644index 000000000..4bbb5c1cc--- /dev/null+++ b/third_party/msdfgen/CHANGELOG.md@@ -0,0 +1,153 @@++## Version 1.13 (2025-11-30)++- Improved BMP file output - support for BGRA (`mtsdf` mode), optimized size of grayscale files+ - For builds without PNG support, BMP replaces TIFF as the default output format+- Fixed incorrect output with asymmetrical distance range when inversion occurs due to winding correction (`-guesswinding` / `-reversewinding`) or scanline pass (`-scanline`)+- The library now operates on bitmap section references (instead of contiguous bitmap references), which makes it possible to generate a distance field directly into a subsection of a larger bitmap or a bitmap with the opposite row ordering+- Improved semantics of specifying Y-axis orientation (upward / downward)+- Improved precision of cubic curve distance computation+- Fixed a bug incorrectly adjusting convergent edge segments in shape normalization+- Renamed options `-guesswinding`, `-reversewinding`, `-keepwinding` from `-guessorder`, ... for clarity (old names kept for compatibility)+- Adjusted the Readme example shader to improve anti-aliasing in a rotated frame+- Minor CMake fixes++### Version 1.12.1 (2025-05-31)++- Fixed a bug applying error correction incorrectly if shape's Y-axis is inverted (mainly affected SVG input)+- Fixed error correction not being applied in the standalone executable in MTSDF mode with the `-scanline` option (default in non-Skia builds)+- Minor CMake adjustments and warning fixes++## Version 1.12 (2024-05-18)++- Added the possibility to specify asymmetrical distance range (`-arange`, `-apxrange`)+- Added the ability to export the shape into an SVG file (`-exportsvg`)+- Edge coloring no longer colors smooth contours white, which has been found suboptimal+- Fixed incorrect scaling of font glyph coordinates. To preserve backwards compatibility, the user has to enable the fix with an explicit additional argument:+ - `-emnormalize` in standalone, `FONT_SCALING_EM_NORMALIZED` in API for coordinates in ems+ - `-noemnormalize` in standalone, `FONT_SCALING_NONE` in API for raw integer coordinates+ - The default (backwards-compatible) behavior will change in a future version; a warning will be displayed if neither option is set+- Added two new developer-friendly export image formats: RGBA and FL32+- `-size` parameter renamed to `-dimensions` for clarity (old one will be kept for compatibility)+- `generate*SDF` functions now combine projection and range into a single argument (`SDFTransformation`)+- Conversion of floating point color values to 8-bit integers adjusted to match graphics hardware+- Improved edge deconvergence procedure and made sure that calling `Shape::normalize` a second time has no effect+- Fixed certain edge cases where Skia geometry preprocessing wouldn't make the geometry fully compliant+- The term "perpendicular distance" now used instead of "pseudo-distance" (PSDF instead of PseudoSDF in API)+- Fixed a bug in `savePng` where `fclose` could be called on null pointer+- Minor code improvements++## Version 1.11 (2023-11-11)++- Reworked SVG parser, which now supports multiple paths and other shapes - requires Skia+- Major performance improvements due to inlining certain low-level classes+- A limited version of the standalone executable can now be built without any dependencies+- Fixed `listFontVariationAxes` which previously reported incorrectly scaled values+- Fixed potential crash when generating SDF from an empty `Shape`+- Fixed a small bug in the error correction routine+- Errors now reported to `stderr` rather than `stdout`+- All command line arguments can now also be passed with two dashes instead of one+- Added `-version` argument to print the program's version+- `Shape` can now be loaded from a pointer to FreeType's `FT_Outline`+- Added hidden CMake options to selectively disable PNG, SVG, or variable font support+- Added CMake presets+- Other minor bug fixes++## Version 1.10 (2023-01-15)++- Switched to vcpkg as the primary dependency management system+- Switched to libpng as the primary PNG file encoder+- Parameters of variable fonts can be specified+- Fixed a bug that prevented glyph 0 to be specified in a glyphset++### Version 1.9.2 (2021-12-01)++- Improved detection of numerical errors in cubic equation solver+- Added -windingpreprocess option+- Fixed edge coloring not restored if lost during preprocessing++### Version 1.9.1 (2021-07-09)++- Fixed an edge case bug in the new MSDF error correction algorithm++## Version 1.9 (2021-05-28)++- Error correction of multi-channel distance fields has been completely reworked+- Added new edge coloring strategy that optimizes colors based on distances between edges+- Added some minor functions for the library API+- Minor code refactor and optimizations++## Version 1.8 (2020-10-17)++- Integrated the Skia library into the project, which is used to preprocess the shape geometry and eliminate any self-intersections and other irregularities previously unsupported by the software+ - The scanline pass and overlapping contour mode is made obsolete by this step and has been disabled by default. The preprocess step can be disabled by the new `-nopreprocess` switch and the former enabled by `-scanline` and `-overlap` respectively.+ - The project can be built without the Skia library, forgoing the geometry preprocessing feature. This is controlled by the macro definition `MSDFGEN_USE_SKIA`+- Significantly improved performance of the core algorithm by reusing results from previously computed pixels+- Introduced an additional error correction routine which eliminates MSDF artifacts by analytically predicting results of bilinear interpolation+- Added the possibility to load font glyphs by their index rather than a Unicode value (use the prefix `g` before the character code in `-font` argument)+- Added `-distanceshift` argument that can be used to adjust the center of the distance range in the output distance field+- Fixed several errors in the evaluation of curve distances+- Fixed an issue with paths containing convergent corners (those whose inner angle is zero)+- The algorithm for pseudo-distance computation slightly changed, fixing certain rare edge cases and improving consistency+- Added the ability to supply own `FT_Face` handle to the msdfgen library+- Minor refactor of the core algorithm++### Version 1.7.1 (2020-03-09)++- Fixed an edge case bug in scanline rasterization++## Version 1.7 (2020-03-07)++- Added `mtsdf` mode - a combination of `msdf` with `sdf` in the alpha channel+- Distance fields can now be stored as uncompressed TIFF image files with floating point precision+- Bitmap class refactor - template argument split into data type and number of channels, bitmap reference classes introduced+- Added a secondary "ink trap" edge coloring heuristic, can be selected using `-coloringstrategy inktrap`+- Added computation of estimated rendering error for a given SDF+- Added computation of bounding box that includes sharp mitered corners+- The API for bounds computation of the `Shape` class changed for clarity+- Fixed several edge case bugs++## Version 1.6 (2019-04-08)++- Core algorithm rewritten to split up advanced edge selection logic into modular template arguments.+- Pseudo-distance evaluation reworked to eliminate discontinuities at the midpoint between edges.+- MSDF error correction reworked to also fix distances away from edges and consider diagonal pairs. Code simplified.+- Added scanline rasterization support for `Shape`.+- Added a scanline pass in the standalone version, which corrects the signs in the distance field according to the selected fill rule (`-fillrule`). Can be disabled using `-noscanline`.+- Fixed autoframe scaling, which previously caused the output to have unnecessary empty border.+- `-guessorder` switch no longer enabled by default, as the functionality is now provided by the scanline pass.+- Updated FreeType and other libraries, changed to static linkage+- Added 64-bit and static library builds to the Visual Studio solution++## Version 1.5 (2017-07-23)++- Fixed rounding error in cubic curve splitting.+- SVG parser fixes and support for additional path commands.+- Added CMake build script.++## Version 1.4 (2017-02-09)++- Reworked contour combining logic to support overlapping contours. Original algorithm preserved in functions with `_legacy` suffix, which are invoked by the new `-legacy` switch.+- Fixed a severe bug in cubic curve distance computation, where a control point lies at the endpoint.+- Standalone version now automatically detects if the input has the wrong orientation and adjusts the distance field accordingly. Can be disabled by `-keeporder` or `-reverseorder` switch.+- SVG parser fixes and improvements.++## Version 1.3 (2016-12-07)++- Fixed `-reverseorder` switch.+- Fixed glyph loading to use the proper method of acquiring outlines from FreeType.++## Version 1.2 (2016-07-20)++- Added option to specify that shape vertices are listed in reverse order (`-reverseorder`).+- Added option to set a seed for the edge coloring heuristic (-seed \<n\>), which can be used to adjust the output.+- Fixed parsing of glyph contours that start with a curve control point.++## Version 1.1 (2016-05-08)++- Switched to MIT license due to popular demand.+- Fixed SDF rendering anti-aliasing when the output is smaller than the distance field.++## Version 1.0 (2016-04-28)++- Project published.diff --git a/third_party/msdfgen/CMakeLists.txt b/third_party/msdfgen/CMakeLists.txtnew file mode 100644index 000000000..d2218395a--- /dev/null+++ b/third_party/msdfgen/CMakeLists.txt@@ -0,0 +1,344 @@++cmake_minimum_required(VERSION 3.15)+include(cmake/version.cmake)++option(MSDFGEN_CORE_ONLY "Only build the core library with no dependencies" OFF)+option(MSDFGEN_BUILD_STANDALONE "Build the msdfgen standalone executable" ON)+option(MSDFGEN_USE_VCPKG "Use vcpkg package manager to link project dependencies" ON)+option(MSDFGEN_USE_OPENMP "Build with OpenMP support for multithreaded code" OFF)+option(MSDFGEN_USE_CPP11 "Build with C++11 enabled" ON)+option(MSDFGEN_USE_SKIA "Build with the Skia library" ON)+option(MSDFGEN_DISABLE_SVG "Disable SVG support" OFF)+option(MSDFGEN_DISABLE_PNG "Disable PNG support" OFF)+option(MSDFGEN_INSTALL "Generate installation target" OFF)+option(MSDFGEN_DYNAMIC_RUNTIME "Link dynamic runtime library instead of static" OFF)+option(BUILD_SHARED_LIBS "Generate dynamic library files instead of static" OFF)++if(MSDFGEN_CORE_ONLY AND MSDFGEN_USE_VCPKG)+ message(STATUS "Option MSDFGEN_USE_VCPKG ignored due to MSDFGEN_CORE_ONLY - core has no dependencies")+ set(MSDFGEN_USE_VCPKG OFF)+endif()++get_property(MULTI_CONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)+if(NOT MULTI_CONFIG AND NOT CMAKE_BUILD_TYPE)+ message(STATUS "CMAKE_BUILD_TYPE not set, defaulting to Release")+ set(CMAKE_BUILD_TYPE Release)+endif()++if(MSDFGEN_USE_VCPKG)+ # Make sure that vcpkg toolchain file is set+ if(NOT CMAKE_TOOLCHAIN_FILE)+ if(DEFINED ENV{VCPKG_ROOT})+ set(CMAKE_TOOLCHAIN_FILE "$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake")+ else()+ message(SEND_ERROR "Vcpkg toolchain not configured. Either set VCPKG_ROOT environment variable or pass -DCMAKE_TOOLCHAIN_FILE=VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake to cmake")+ endif()+ endif()+ # Default to statically linked vcpkg triplet on Windows+ if(WIN32 AND NOT VCPKG_TARGET_TRIPLET AND NOT MSDFGEN_DYNAMIC_RUNTIME)+ if(CMAKE_GENERATOR_PLATFORM MATCHES "64$" AND NOT CMAKE_GENERATOR_PLATFORM STREQUAL "ARM64")+ set(VCPKG_TARGET_TRIPLET "x64-windows-static")+ elseif(CMAKE_GENERATOR_PLATFORM MATCHES "32$" OR CMAKE_GENERATOR_PLATFORM STREQUAL "x86")+ set(VCPKG_TARGET_TRIPLET "x86-windows-static")+ else()+ if(CMAKE_GENERATOR_PLATFORM)+ message(WARNING "Vcpkg triplet not explicitly specified and could not be deduced. Recommend using -DVCPKG_TARGET_TRIPLET=x64-windows-static or similar")+ else()+ message(WARNING "Vcpkg triplet not explicitly specified and could not be deduced. Recommend using -A to explicitly select platform (Win32 or x64)")+ endif()+ endif()+ endif()+ # Select project features+ if(NOT MSDFGEN_VCPKG_FEATURES_SET)+ set(VCPKG_MANIFEST_NO_DEFAULT_FEATURES ON)+ if(NOT MSDFGEN_CORE_ONLY)+ list(APPEND VCPKG_MANIFEST_FEATURES "extensions")+ endif()+ if(MSDFGEN_BUILD_STANDALONE)+ list(APPEND VCPKG_MANIFEST_FEATURES "standalone")+ endif()+ if(MSDFGEN_USE_SKIA)+ list(APPEND VCPKG_MANIFEST_FEATURES "geometry-preprocessing")+ endif()+ if(MSDFGEN_USE_OPENMP)+ list(APPEND VCPKG_MANIFEST_FEATURES "openmp")+ endif()+ endif()+endif()++if(MSDFGEN_INSTALL)+ include(GNUInstallDirs)+ include(CMakePackageConfigHelpers)+endif()++# Version is specified in vcpkg.json+project(msdfgen VERSION ${MSDFGEN_VERSION} LANGUAGES CXX)++if(MSDFGEN_DYNAMIC_RUNTIME)+ set(MSDFGEN_MSVC_RUNTIME "MultiThreaded$<$<CONFIG:Debug>:Debug>DLL")+else()+ set(MSDFGEN_MSVC_RUNTIME "MultiThreaded$<$<CONFIG:Debug>:Debug>")+endif()++if(BUILD_SHARED_LIBS)+ set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)+endif()++if(MAX_WARNING_LEVEL)+ if (MSVC)+ add_compile_options(/W4)+ else()+ add_compile_options(-Wall -Wextra -Wpedantic)+ endif()+endif()++file(GLOB_RECURSE MSDFGEN_CORE_HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "core/*.h" "core/*.hpp")+file(GLOB_RECURSE MSDFGEN_CORE_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "core/*.cpp")+file(GLOB_RECURSE MSDFGEN_EXT_HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "ext/*.h" "ext/*.hpp")+file(GLOB_RECURSE MSDFGEN_EXT_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "ext/*.cpp" "lib/*.cpp")++# Core library+add_library(msdfgen-core "${CMAKE_CURRENT_SOURCE_DIR}/msdfgen.h" ${MSDFGEN_CORE_HEADERS} ${MSDFGEN_CORE_SOURCES})+add_library(msdfgen::msdfgen-core ALIAS msdfgen-core)+set_target_properties(msdfgen-core PROPERTIES PUBLIC_HEADER "${MSDFGEN_CORE_HEADERS}")+set_property(TARGET msdfgen-core PROPERTY MSVC_RUNTIME_LIBRARY "${MSDFGEN_MSVC_RUNTIME}")+target_compile_definitions(msdfgen-core PUBLIC+ MSDFGEN_VERSION=${MSDFGEN_VERSION}+ MSDFGEN_VERSION_MAJOR=${MSDFGEN_VERSION_MAJOR}+ MSDFGEN_VERSION_MINOR=${MSDFGEN_VERSION_MINOR}+ MSDFGEN_VERSION_REVISION=${MSDFGEN_VERSION_REVISION}+ MSDFGEN_COPYRIGHT_YEAR=${MSDFGEN_COPYRIGHT_YEAR}+)+target_include_directories(msdfgen-core INTERFACE+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/msdfgen>+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/>+)+set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT msdfgen-core)++if(MSDFGEN_USE_CPP11)+ target_compile_features(msdfgen-core PUBLIC cxx_std_11)+ target_compile_definitions(msdfgen-core PUBLIC MSDFGEN_USE_CPP11)+endif()++if(MSDFGEN_USE_OPENMP)+ # Note: Clang doesn't support OpenMP by default...+ find_package(OpenMP REQUIRED COMPONENTS CXX)+ target_compile_definitions(msdfgen-core PUBLIC MSDFGEN_USE_OPENMP)+ target_link_libraries(msdfgen-core PUBLIC OpenMP::OpenMP_CXX)+endif()++if(BUILD_SHARED_LIBS AND WIN32)+ target_compile_definitions(msdfgen-core PRIVATE "MSDFGEN_PUBLIC=__declspec(dllexport)")+ target_compile_definitions(msdfgen-core INTERFACE "MSDFGEN_PUBLIC=__declspec(dllimport)")+else()+ target_compile_definitions(msdfgen-core PUBLIC MSDFGEN_PUBLIC=)+endif()++# Extensions library+if(NOT MSDFGEN_CORE_ONLY)+ if(NOT TARGET Freetype::Freetype)+ find_package(Freetype REQUIRED)+ endif()+ if(NOT MSDFGEN_DISABLE_SVG AND NOT TARGET tinyxml2::tinyxml2)+ find_package(tinyxml2 REQUIRED)+ endif()+ if(NOT MSDFGEN_DISABLE_PNG AND NOT TARGET PNG::PNG)+ find_package(PNG REQUIRED)+ endif()++ add_library(msdfgen-ext "${CMAKE_CURRENT_SOURCE_DIR}/msdfgen-ext.h" ${MSDFGEN_EXT_HEADERS} ${MSDFGEN_EXT_SOURCES})+ add_library(msdfgen::msdfgen-ext ALIAS msdfgen-ext)+ set_target_properties(msdfgen-ext PROPERTIES PUBLIC_HEADER "${MSDFGEN_EXT_HEADERS}")+ set_property(TARGET msdfgen-ext PROPERTY MSVC_RUNTIME_LIBRARY "${MSDFGEN_MSVC_RUNTIME}")+ target_compile_definitions(msdfgen-ext INTERFACE MSDFGEN_EXTENSIONS)+ if(NOT MSDFGEN_DISABLE_SVG)+ target_compile_definitions(msdfgen-ext PUBLIC MSDFGEN_USE_TINYXML2)+ target_link_libraries(msdfgen-ext PRIVATE tinyxml2::tinyxml2)+ else()+ target_compile_definitions(msdfgen-ext PUBLIC MSDFGEN_DISABLE_SVG)+ endif()+ if(NOT MSDFGEN_DISABLE_PNG)+ target_compile_definitions(msdfgen-ext PUBLIC MSDFGEN_USE_LIBPNG)+ target_link_libraries(msdfgen-ext PRIVATE PNG::PNG)+ else()+ target_compile_definitions(msdfgen-ext PUBLIC MSDFGEN_DISABLE_PNG)+ endif()+ if(MSDFGEN_DISABLE_VARIABLE_FONTS)+ target_compile_definitions(msdfgen-ext PUBLIC MSDFGEN_DISABLE_VARIABLE_FONTS)+ endif()+ target_link_libraries(msdfgen-ext PRIVATE Freetype::Freetype msdfgen::msdfgen-core)+ target_include_directories(msdfgen-ext+ PUBLIC+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/msdfgen>+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>+ PRIVATE+ ${CMAKE_CURRENT_SOURCE_DIR}/include+ )+ set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT msdfgen-ext)++ if(MSDFGEN_USE_SKIA)+ set(MSDFGEN_SKIA_LIB skia)+ set(CMAKE_THREAD_PREFER_PTHREAD TRUE)+ set(THREADS_PREFER_PTHREAD_FLAG TRUE)+ find_package(Threads REQUIRED)+ if(NOT TARGET skia)+ if(MSDFGEN_USE_VCPKG)+ find_package(unofficial-skia REQUIRED)+ set(MSDFGEN_SKIA_LIB unofficial::skia::skia)+ else()+ find_package(skia REQUIRED)+ endif()+ endif()+ target_compile_features(msdfgen-ext PUBLIC cxx_std_17)+ target_compile_definitions(msdfgen-ext PUBLIC MSDFGEN_USE_SKIA)+ target_link_libraries(msdfgen-ext PRIVATE Threads::Threads ${MSDFGEN_SKIA_LIB})+ endif()++ if(BUILD_SHARED_LIBS AND WIN32)+ target_compile_definitions(msdfgen-ext PRIVATE "MSDFGEN_EXT_PUBLIC=__declspec(dllexport)")+ target_compile_definitions(msdfgen-ext INTERFACE "MSDFGEN_EXT_PUBLIC=__declspec(dllimport)")+ else()+ target_compile_definitions(msdfgen-ext PUBLIC MSDFGEN_EXT_PUBLIC=)+ endif()++ add_library(msdfgen-full INTERFACE)+ add_library(msdfgen::msdfgen ALIAS msdfgen-full)+ target_link_libraries(msdfgen-full INTERFACE msdfgen::msdfgen-core msdfgen::msdfgen-ext)+else()+ add_library(msdfgen::msdfgen ALIAS msdfgen-core)+endif()++# Standalone executable+if(MSDFGEN_BUILD_STANDALONE)+ set(MSDFGEN_STANDALONE_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/main.cpp")+ if(MSVC)+ set(MSDFGEN_STANDALONE_SOURCES ${MSDFGEN_STANDALONE_SOURCES} "${CMAKE_CURRENT_SOURCE_DIR}/msdfgen.rc")+ endif()+ add_executable(msdfgen ${MSDFGEN_STANDALONE_SOURCES})+ target_compile_definitions(msdfgen PUBLIC MSDFGEN_STANDALONE)+ target_compile_definitions(msdfgen PRIVATE MSDFGEN_VERSION_UNDERLINE=${MSDFGEN_VERSION_UNDERLINE})+ set_property(TARGET msdfgen PROPERTY MSVC_RUNTIME_LIBRARY "${MSDFGEN_MSVC_RUNTIME}")+ target_link_libraries(msdfgen PRIVATE msdfgen::msdfgen)+ set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT msdfgen)+endif()++# Hide ZERO_CHECK and ALL_BUILD targets+set_property(GLOBAL PROPERTY USE_FOLDERS ON)+set_property(GLOBAL PROPERTY PREDEFINED_TARGETS_FOLDER meta)++# Installation+if(MSDFGEN_INSTALL)+ set(MSDFGEN_CONFIG_PATH "lib/cmake/msdfgen")++ # Generate msdfgen-config.h+ if(BUILD_SHARED_LIBS AND WIN32)+ set(MSDFGEN_PUBLIC_MACRO_VALUE " __declspec(dllimport)")+ else()+ set(MSDFGEN_PUBLIC_MACRO_VALUE "")+ endif()+ set(MSDFGEN_ADDITIONAL_DEFINES "")+ if(MSDFGEN_USE_CPP11)+ set(MSDFGEN_ADDITIONAL_DEFINES "${MSDFGEN_ADDITIONAL_DEFINES}\n#define MSDFGEN_USE_CPP11")+ endif()+ if(MSDFGEN_USE_OPENMP)+ set(MSDFGEN_ADDITIONAL_DEFINES "${MSDFGEN_ADDITIONAL_DEFINES}\n#define MSDFGEN_USE_OPENMP")+ endif()+ if(NOT MSDFGEN_CORE_ONLY)+ set(MSDFGEN_ADDITIONAL_DEFINES "${MSDFGEN_ADDITIONAL_DEFINES}\n#define MSDFGEN_EXTENSIONS")+ if(MSDFGEN_USE_SKIA)+ set(MSDFGEN_ADDITIONAL_DEFINES "${MSDFGEN_ADDITIONAL_DEFINES}\n#define MSDFGEN_USE_SKIA")+ endif()+ if(NOT MSDFGEN_DISABLE_SVG)+ set(MSDFGEN_ADDITIONAL_DEFINES "${MSDFGEN_ADDITIONAL_DEFINES}\n#define MSDFGEN_USE_TINYXML2")+ else()+ set(MSDFGEN_ADDITIONAL_DEFINES "${MSDFGEN_ADDITIONAL_DEFINES}\n#define MSDFGEN_DISABLE_SVG")+ endif()+ if(NOT MSDFGEN_DISABLE_PNG)+ set(MSDFGEN_ADDITIONAL_DEFINES "${MSDFGEN_ADDITIONAL_DEFINES}\n#define MSDFGEN_USE_LIBPNG")+ else()+ set(MSDFGEN_ADDITIONAL_DEFINES "${MSDFGEN_ADDITIONAL_DEFINES}\n#define MSDFGEN_DISABLE_PNG")+ endif()+ if(MSDFGEN_DISABLE_VARIABLE_FONTS)+ set(MSDFGEN_ADDITIONAL_DEFINES "${MSDFGEN_ADDITIONAL_DEFINES}\n#define MSDFGEN_DISABLE_VARIABLE_FONTS")+ endif()+ endif()+ configure_file("${CMAKE_CURRENT_SOURCE_DIR}/cmake/msdfgen-config.h.in" msdfgen-config.h)++ if (NOT MSDFGEN_INSTALL_NO_GLOBAL_INCLUDE)+ write_file("${CMAKE_CURRENT_BINARY_DIR}/msdfgen.h" "\n#pragma once\n\n#include \"msdfgen/msdfgen.h\"")+ write_file("${CMAKE_CURRENT_BINARY_DIR}/msdfgen-ext.h" "\n#pragma once\n\n#include \"msdfgen/msdfgen-ext.h\"")+ endif()++ write_basic_package_version_file(+ "${CMAKE_CURRENT_BINARY_DIR}/msdfgenConfigVersion.cmake"+ VERSION ${PROJECT_VERSION}+ COMPATIBILITY SameMajorVersion+ )++ configure_package_config_file(+ "${CMAKE_CURRENT_SOURCE_DIR}/cmake/msdfgenConfig.cmake.in"+ ${MSDFGEN_CONFIG_PATH}/msdfgenConfig.cmake+ INSTALL_DESTINATION ${MSDFGEN_CONFIG_PATH}+ NO_CHECK_REQUIRED_COMPONENTS_MACRO+ )++ configure_file(+ "${CMAKE_CURRENT_SOURCE_DIR}/cmake/msdfgenConfig.cmake.in"+ msdfgenConfig.cmake+ @ONLY+ )++ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/msdfgen-config.h" DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/msdfgen)+ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/msdfgen-config.h" DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/msdfgen/msdfgen)+ install(TARGETS msdfgen-core EXPORT msdfgenTargets+ RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}+ FRAMEWORK DESTINATION ${CMAKE_INSTALL_LIBDIR}+ PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/msdfgen/core+ )+ install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/msdfgen.h" DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/msdfgen)+ if (NOT MSDFGEN_INSTALL_NO_GLOBAL_INCLUDE)+ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/msdfgen.h" DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})+ endif()+ if(MSVC AND BUILD_SHARED_LIBS)+ install(FILES $<TARGET_PDB_FILE:msdfgen-core> DESTINATION ${CMAKE_INSTALL_BINDIR} OPTIONAL)+ endif()++ if(NOT MSDFGEN_CORE_ONLY)+ install(TARGETS msdfgen-ext EXPORT msdfgenTargets+ RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}+ FRAMEWORK DESTINATION ${CMAKE_INSTALL_LIBDIR}+ PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/msdfgen/ext+ )+ install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/msdfgen-ext.h" DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/msdfgen)+ if (NOT MSDFGEN_INSTALL_NO_GLOBAL_INCLUDE)+ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/msdfgen-ext.h" DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})+ endif()+ if(MSVC AND BUILD_SHARED_LIBS)+ install(FILES $<TARGET_PDB_FILE:msdfgen-ext> DESTINATION ${CMAKE_INSTALL_BINDIR} OPTIONAL)+ endif()+ install(TARGETS msdfgen-full EXPORT msdfgenTargets)+ endif()++ export(EXPORT msdfgenTargets NAMESPACE msdfgen:: FILE "${CMAKE_CURRENT_BINARY_DIR}/msdfgenTargets.cmake")+ install(EXPORT msdfgenTargets FILE msdfgenTargets.cmake NAMESPACE msdfgen:: DESTINATION ${MSDFGEN_CONFIG_PATH})++ if(MSDFGEN_BUILD_STANDALONE)+ install(TARGETS msdfgen EXPORT msdfgenBinaryTargets DESTINATION ${CMAKE_INSTALL_BINDIR})+ if(MSVC)+ install(FILES $<TARGET_PDB_FILE:msdfgen> DESTINATION ${CMAKE_INSTALL_BINDIR} OPTIONAL)+ endif()+ export(EXPORT msdfgenBinaryTargets NAMESPACE msdfgen-standalone:: FILE "${CMAKE_CURRENT_BINARY_DIR}/msdfgenBinaryTargets.cmake")+ install(EXPORT msdfgenBinaryTargets FILE msdfgenBinaryTargets.cmake NAMESPACE msdfgen-standalone:: DESTINATION ${MSDFGEN_CONFIG_PATH})+ endif()++ install(+ FILES+ "${CMAKE_CURRENT_BINARY_DIR}/${MSDFGEN_CONFIG_PATH}/msdfgenConfig.cmake"+ "${CMAKE_CURRENT_BINARY_DIR}/msdfgenConfigVersion.cmake"+ DESTINATION ${MSDFGEN_CONFIG_PATH}+ )+endif()diff --git a/third_party/msdfgen/CMakePresets.json b/third_party/msdfgen/CMakePresets.jsonnew file mode 100644index 000000000..f6f242412--- /dev/null+++ b/third_party/msdfgen/CMakePresets.json@@ -0,0 +1,239 @@+{+ "version": 4,+ "cmakeMinimumRequired": {+ "major": 3,+ "minor": 23,+ "patch": 0+ },+ "include": [+ "cmake/CMakePresets.json"+ ],+ "configurePresets": [+ {+ "name": "win64",+ "displayName": "Windows x64 default config (static, vcpkg, Skia)",+ "inherits": [ "win64-base", "vcpkg", "skia" ]+ }, {+ "name": "win32",+ "displayName": "Windows x86 default config (static, vcpkg, Skia)",+ "inherits": [ "win32-base", "vcpkg", "skia" ]+ }, {+ "name": "win64-omp",+ "displayName": "Windows x64 config with OpenMP (static, vcpkg, Skia)",+ "inherits": [ "win64-base", "openmp", "vcpkg", "skia" ],+ "binaryDir": "${sourceDir}/build/win64-omp"+ }, {+ "name": "win32-omp",+ "displayName": "Windows x86 config with OpenMP (static, vcpkg, Skia)",+ "inherits": [ "win32-base", "openmp", "vcpkg", "skia" ],+ "binaryDir": "${sourceDir}/build/win32-omp"+ }, {+ "name": "win64-dynamic",+ "displayName": "Windows x64 dynamic config (vcpkg, Skia)",+ "inherits": [ "win64-base", "vcpkg", "skia", "dynamic-runtime", "dynamic-lib" ],+ "binaryDir": "${sourceDir}/build/win64-dynamic"+ }, {+ "name": "win32-dynamic",+ "displayName": "Windows x86 dynamic config (vcpkg, Skia)",+ "inherits": [ "win32-base", "vcpkg", "skia", "dynamic-runtime", "dynamic-lib" ],+ "binaryDir": "${sourceDir}/build/win32-dynamic"+ }, {+ "name": "win64-no-skia",+ "displayName": "Windows x64 config without Skia (static, vcpkg)",+ "inherits": [ "win64-base", "vcpkg", "no-skia" ]+ }, {+ "name": "win32-no-skia",+ "displayName": "Windows x86 config without Skia (static, vcpkg)",+ "inherits": [ "win32-base", "vcpkg", "no-skia" ]+ }, {+ "name": "win64-core",+ "displayName": "Windows x64 core-only config (static)",+ "inherits": [ "win64-base", "core-only" ],+ "binaryDir": "${sourceDir}/build/win64-core"+ }, {+ "name": "win32-core",+ "displayName": "Windows x86 core-only config (static)",+ "inherits": [ "win32-base", "core-only" ],+ "binaryDir": "${sourceDir}/build/win32-core"+ },++ {+ "name": "osx-vcpkg-rel",+ "displayName": "Mac OS release config with vcpkg and Skia (static)",+ "inherits": [ "osx-rel-base", "vcpkg", "skia" ]+ }, {+ "name": "osx-vcpkg-dbg",+ "displayName": "Mac OS debug config with vcpkg and Skia (static)",+ "inherits": [ "osx-dbg-base", "vcpkg", "skia" ]+ }, {+ "name": "osx-no-skia-rel",+ "displayName": "Mac OS release config with system libraries and no Skia (static, install)",+ "inherits": [ "osx-rel-base", "no-vcpkg", "no-skia", "install" ]+ }, {+ "name": "osx-no-skia-dbg",+ "displayName": "Mac OS debug config with system libraries and no Skia (static, install)",+ "inherits": [ "osx-dbg-base", "no-vcpkg", "no-skia", "install" ]+ }, {+ "name": "osx-core-rel",+ "displayName": "Mac OS release core-only config (static, install)",+ "inherits": [ "osx-rel-base", "core-only", "install" ],+ "binaryDir": "${sourceDir}/build/osx-core-rel"+ }, {+ "name": "osx-core-dbg",+ "displayName": "Mac OS debug core-only config (static, install)",+ "inherits": [ "osx-dbg-base", "core-only", "install" ],+ "binaryDir": "${sourceDir}/build/osx-core-dbg"+ },++ {+ "name": "linux-vcpkg-rel",+ "displayName": "Linux release config with vcpkg and Skia (static)",+ "inherits": [ "linux-rel-base", "vcpkg", "skia" ]+ }, {+ "name": "linux-vcpkg-dbg",+ "displayName": "Linux debug config with vcpkg and Skia (static)",+ "inherits": [ "linux-dbg-base", "vcpkg", "skia" ]+ }, {+ "name": "linux-no-skia-rel",+ "displayName": "Linux release config with system libraries and no Skia (static, install)",+ "inherits": [ "linux-rel-base", "no-vcpkg", "no-skia", "install" ]+ }, {+ "name": "linux-no-skia-dbg",+ "displayName": "Linux debug config with system libraries and no Skia (static, install)",+ "inherits": [ "linux-dbg-base", "no-vcpkg", "no-skia", "install" ]+ }, {+ "name": "linux-core-rel",+ "displayName": "Linux release core-only config (static, install)",+ "inherits": [ "linux-rel-base", "core-only", "install" ],+ "binaryDir": "${sourceDir}/build/linux-core-rel"+ }, {+ "name": "linux-core-dbg",+ "displayName": "Linux debug core-only config (static, install)",+ "inherits": [ "linux-dbg-base", "core-only", "install" ],+ "binaryDir": "${sourceDir}/build/linux-core-dbg"+ }+ ],+ "buildPresets": [+ {+ "name": "win64-rel",+ "configurePreset": "win64",+ "configuration": "Release"+ }, {+ "name": "win64-dbg",+ "configurePreset": "win64",+ "configuration": "Debug"+ }, {+ "name": "win32-rel",+ "configurePreset": "win32",+ "configuration": "Release"+ }, {+ "name": "win32-dbg",+ "configurePreset": "win32",+ "configuration": "Debug"+ }, {+ "name": "win64-omp-rel",+ "configurePreset": "win64-omp",+ "configuration": "Release"+ }, {+ "name": "win64-omp-dbg",+ "configurePreset": "win64-omp",+ "configuration": "Debug"+ }, {+ "name": "win32-omp-rel",+ "configurePreset": "win32-omp",+ "configuration": "Release"+ }, {+ "name": "win32-omp-dbg",+ "configurePreset": "win32-omp",+ "configuration": "Debug"+ }, {+ "name": "win64-dynamic-rel",+ "configurePreset": "win64-dynamic",+ "configuration": "Release"+ }, {+ "name": "win64-dynamic-dbg",+ "configurePreset": "win64-dynamic",+ "configuration": "Debug"+ }, {+ "name": "win32-dynamic-rel",+ "configurePreset": "win32-dynamic",+ "configuration": "Release"+ }, {+ "name": "win32-dynamic-dbg",+ "configurePreset": "win32-dynamic",+ "configuration": "Debug"+ }, {+ "name": "win64-no-skia-rel",+ "configurePreset": "win64-no-skia",+ "configuration": "Release"+ }, {+ "name": "win64-no-skia-dbg",+ "configurePreset": "win64-no-skia",+ "configuration": "Debug"+ }, {+ "name": "win32-no-skia-rel",+ "configurePreset": "win32-no-skia",+ "configuration": "Release"+ }, {+ "name": "win32-no-skia-dbg",+ "configurePreset": "win32-no-skia",+ "configuration": "Debug"+ }, {+ "name": "win64-core-rel",+ "configurePreset": "win64-core",+ "configuration": "Release"+ }, {+ "name": "win64-core-dbg",+ "configurePreset": "win64-core",+ "configuration": "Debug"+ }, {+ "name": "win32-core-rel",+ "configurePreset": "win32-core",+ "configuration": "Release"+ }, {+ "name": "win32-core-dbg",+ "configurePreset": "win32-core",+ "configuration": "Debug"+ },++ {+ "name": "osx-vcpkg-rel",+ "configurePreset": "osx-vcpkg-rel"+ }, {+ "name": "osx-vcpkg-dbg",+ "configurePreset": "osx-vcpkg-dbg"+ }, {+ "name": "osx-no-skia-rel",+ "configurePreset": "osx-no-skia-rel"+ }, {+ "name": "osx-no-skia-dbg",+ "configurePreset": "osx-no-skia-dbg"+ }, {+ "name": "osx-core-rel",+ "configurePreset": "osx-core-rel"+ }, {+ "name": "osx-core-dbg",+ "configurePreset": "osx-core-dbg"+ },++ {+ "name": "linux-vcpkg-rel",+ "configurePreset": "linux-vcpkg-rel"+ }, {+ "name": "linux-vcpkg-dbg",+ "configurePreset": "linux-vcpkg-dbg"+ }, {+ "name": "linux-no-skia-rel",+ "configurePreset": "linux-no-skia-rel"+ }, {+ "name": "linux-no-skia-dbg",+ "configurePreset": "linux-no-skia-dbg"+ }, {+ "name": "linux-core-rel",+ "configurePreset": "linux-core-rel"+ }, {+ "name": "linux-core-dbg",+ "configurePreset": "linux-core-dbg"+ }+ ]+}diff --git a/third_party/msdfgen/LICENSE.txt b/third_party/msdfgen/LICENSE.txtnew file mode 100644index 000000000..fbea359b2--- /dev/null+++ b/third_party/msdfgen/LICENSE.txt@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2014 - 2025 Viktor Chlumsky++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/third_party/msdfgen/README.md b/third_party/msdfgen/README.mdnew file mode 100644index 000000000..71ac1c0ec--- /dev/null+++ b/third_party/msdfgen/README.md@@ -0,0 +1,220 @@+# Multi-channel signed distance field generator++This is a utility for generating signed distance fields from vector shapes and font glyphs,+which serve as a texture representation that can be used in real-time graphics to efficiently reproduce said shapes.+Although it can also be used to generate conventional signed distance fields best known from+[this Valve paper](https://steamcdn-a.akamaihd.net/apps/valve/2007/SIGGRAPH2007_AlphaTestedMagnification.pdf)+and perpendicular distance fields, its primary purpose is to generate multi-channel distance fields,+using a method I have developed. Unlike monochrome distance fields, they have the ability+to reproduce sharp corners almost perfectly by utilizing all three color channels.++The following comparison demonstrates the improvement in image quality.++++++- To learn more about this method, you can read my [Master's thesis](https://github.com/Chlumsky/msdfgen/files/3050967/thesis.pdf).+- Check out my [MSDF-Atlas-Gen](https://github.com/Chlumsky/msdf-atlas-gen) if you want to generate entire font atlases for text rendering.+- See what's new in the [changelog](CHANGELOG.md).++## Getting started++The project can be used either as a library or as a console program. It is divided into two parts, **[core](core)**+and **[extensions](ext)**. The core module has no dependencies and only uses bare C++. It contains all+key data structures and algorithms, which can be accessed through the [msdfgen.h](msdfgen.h) header.+Extensions contain utilities for loading fonts and SVG files, as well as saving PNG images.+Those are exposed by the [msdfgen-ext.h](msdfgen-ext.h) header. This module uses+[FreeType](https://freetype.org/),+[TinyXML2](https://www.grinninglizard.com/tinyxml2/),+[libpng](http://www.libpng.org/pub/png/libpng.html),+and (optionally) [Skia](https://skia.org/).++Additionally, there is the [main.cpp](main.cpp), which wraps the functionality into+a comprehensive standalone console program. To start using the program immediately,+there is a Windows binary available for download in the ["Releases" section](https://github.com/Chlumsky/msdfgen/releases).+To use the project as a library, you may install it via the [vcpkg](https://vcpkg.io) package manager as+```+vcpkg install msdfgen+```+Or, to build the project from source, you may use the included [CMake script](CMakeLists.txt).+In its default configuration, it requires [vcpkg](https://vcpkg.io) as the provider for third-party library dependencies.+If you set the environment variable `VCPKG_ROOT` to the vcpkg directory,+the CMake configuration will take care of fetching all required packages from vcpkg.++## Console commands++The standalone program is executed as+```+msdfgen.exe <mode> <input> <options>+```+where only the input specification is required.++Mode can be one of:+ - **sdf** – generates a conventional monochrome (true) signed distance field.+ - **psdf** – generates a monochrome signed perpendicular distance field.+ - **msdf** (default) – generates a multi-channel signed distance field using my new method.+ - **mtsdf** – generates a combined multi-channel and true signed distance field in the alpha channel.++The input can be specified as one of:+ - **-font \<filename.ttf\> \<character code\>** – to load a glyph from a font file.+ Character code can be expressed as either a decimal (63) or hexadecimal (0x3F) Unicode value, or an ASCII character+ in single quotes ('?').+ - **-svg \<filename.svg\>** – to load an SVG file. Note that only the last vector path in the file will be used.+ - **-shapedesc \<filename.txt\>**, -defineshape \<definition\>, -stdin – to load a text description of the shape+ from either a file, the next argument, or the standard input, respectively. Its syntax is documented further down.++The complete list of available options can be printed with **-help**.+Some of the important ones are:+ - **-o \<filename\>** – specifies the output file name. The desired format will be deduced from the extension+ (png, bmp, tiff, rgba, fl32, txt, bin). Otherwise, use -format.+ - **-dimensions \<width\> \<height\>** – specifies the dimensions of the output distance field (in pixels).+ - **-range \<range\>**, **-pxrange \<range\>** – specifies the width of the range around the shape+ between the minimum and maximum representable signed distance in shape units or distance field pixels, respectivelly.+ - **-scale \<scale\>** – sets the scale used to convert shape units to distance field pixels.+ - **-translate \<x\> \<y\>** – sets the translation of the shape in shape units. Otherwise the origin (0, 0)+ lies in the bottom left corner.+ - **-autoframe** – automatically frames the shape to fit the distance field. If the output must be precisely aligned,+ you should manually position it using -translate and -scale instead.+ - **-angle \<angle\>** – specifies the maximum angle to be considered a corner.+ Can be expressed in radians (3.0) or degrees with D at the end (171.9D).+ - **-testrender \<filename.png\> \<width\> \<height\>** - tests the generated distance field by using it to render an image+ of the original shape into a PNG file with the specified dimensions. Alternatively, -testrendermulti renders+ an image without combining the color channels, and may give you an insight in how the multi-channel distance field works.+ - **-exportshape \<filename.txt\>** - saves the text description of the shape with edge coloring to the specified file.+ This can be later edited and used as input through -shapedesc.+ - **-printmetrics** – prints some useful information about the shape's layout.++For example,+```+msdfgen.exe msdf -font C:\Windows\Fonts\arialbd.ttf 'M' -o msdf.png -dimensions 32 32 -pxrange 4 -autoframe -testrender render.png 1024 1024+```++will take the glyph capital M from the Arial Bold typeface, generate a 32×32 multi-channel distance field+with a 4 pixels wide distance range, store it into msdf.png, and create a test render of the glyph as render.png.++**Note:** Do not use `-autoframe` to generate character maps! It is intended as a quick preview only.++## Library API++If you choose to use this utility inside your own program, there are a few simple steps you need to perform+in order to generate a distance field. Please note that all classes and functions are in the `msdfgen` namespace.++ - Acquire a `Shape` object. You can either load it via `loadGlyph` or `loadSvgShape`, or construct it manually.+ It consists of closed contours, which in turn consist of edges. An edge is represented by a `LinearEdge`, `QuadraticEdge`,+ or `CubicEdge`. You can construct them from two endpoints and 0 to 2 Bézier control points.+ - Normalize the shape using its `normalize` method and assign colors to edges if you need a multi-channel SDF.+ This can be performed automatically using the `edgeColoringSimple` (or other) heuristic, or manually by setting each edge's+ `color` member. Keep in mind that at least two color channels must be turned on in each edge.+ - Call `generateSDF`, `generatePSDF`, `generateMSDF`, or `generateMTSDF` to generate a distance field into a floating point+ `Bitmap` object. This can then be worked with further or saved to a file using `saveBmp`, `savePng`, `saveTiff`, etc.+ - You may also render an image from the distance field using `renderSDF`. Consider calling `simulate8bit`+ on the distance field beforehand to simulate the standard 8 bits/channel image format.++Example:+```c+++#include <msdfgen.h>+#include <msdfgen-ext.h>++using namespace msdfgen;++int main() {+ if (FreetypeHandle *ft = initializeFreetype()) {+ if (FontHandle *font = loadFont(ft, "C:\\Windows\\Fonts\\arialbd.ttf")) {+ Shape shape;+ if (loadGlyph(shape, font, 'A', FONT_SCALING_EM_NORMALIZED)) {+ shape.normalize();+ // max. angle+ edgeColoringSimple(shape, 3.0);+ // output width, height+ Bitmap<float, 3> msdf(32, 32);+ // scale, translation (in em's)+ SDFTransformation t(Projection(32.0, Vector2(0.125, 0.125)), Range(0.125));+ generateMSDF(msdf, shape, t);+ savePng(msdf, "output.png");+ }+ destroyFont(font);+ }+ deinitializeFreetype(ft);+ }+ return 0;+}+```++## Using a multi-channel distance field++Using a multi-channel distance field generated by this program is similarly simple to how a monochrome distance field is used.+The only additional operation is computing the **median** of the three channels inside the fragment shader,+right after sampling the distance field. This signed distance value can then be used the same way as usual.++**Important:** Make sure to interpret the MSDF color channels in linear space just like the alpha channel and not as sRGB,+even if the image format (PNG, BMP) may suggest otherwise.++The following is an example GLSL fragment shader with anti-aliasing:++```glsl+in vec2 texCoord;+out vec4 color;+uniform sampler2D msdf;+uniform vec4 bgColor;+uniform vec4 fgColor;++float median(float r, float g, float b) {+ return max(min(r, g), min(max(r, g), b));+}++void main() {+ vec3 msd = texture(msdf, texCoord).rgb;+ float sd = median(msd.r, msd.g, msd.b);+ float screenPxDistance = screenPxRange()*(sd - 0.5);+ float opacity = clamp(screenPxDistance + 0.5, 0.0, 1.0);+ color = mix(bgColor, fgColor, opacity);+}+```++Here, `screenPxRange()` represents the distance field range in output screen pixels. For example, if the pixel range was set to 2+when generating a 32x32 distance field, and it is used to draw a quad that is 72x72 pixels on the screen,+it should return 4.5 (because 72/32 * 2 = 4.5).+**For 2D rendering, this can generally be replaced by a precomputed uniform value.**++For rendering in a **3D perspective only**, where the texture scale varies across the screen,+you may want to implement this function with fragment derivatives in the following way.+I would suggest precomputing `unitRange` as a uniform variable instead of `pxRange` for better performance.++```glsl+uniform float pxRange; // set to distance field's pixel range++vec2 sqr(vec2 x) { return x*x; } // squares vector components++float screenPxRange() {+ vec2 unitRange = vec2(pxRange)/vec2(textureSize(msdf, 0));+ // If inversesqrt is not available, use vec2(1.0)/sqrt+ vec2 screenTexSize = inversesqrt(sqr(dFdx(texCoord))+sqr(dFdy(texCoord)));+ // Can also be approximated as screenTexSize = vec2(1.0)/fwidth(texCoord);+ return max(0.5*dot(unitRange, screenTexSize), 1.0);+}+```++`screenPxRange()` must never be lower than 1. If it is lower than 2, there is a high probability that the anti-aliasing will fail+and you may want to re-generate your distance field with a wider range.++## Shape description syntax++The text shape description has the following syntax.+ - Each closed contour is enclosed by braces: `{ <contour 1> } { <contour 2> }`+ - Each point (and control point) is written as two real numbers separated by a comma.+ - Points in a contour are separated with semicolons.+ - The last point of each contour must be equal to the first, or the symbol `#` can be used, which represents the first point.+ - There can be an edge segment specification between any two points, also separated by semicolons.+ This can include the edge's color (`c`, `m`, `y` or `w`) and/or one or two Bézier curve control points inside parentheses.+ - At the beginning, there may be an Y-axis direction specifier `@y-up` or `@y-down`.++For example,+```+{ -1, -1; m; -1, +1; y; +1, +1; m; +1, -1; y; # }+```+would represent a square with magenta and yellow edges,+```+{ 0, 1; (+1.6, -0.8; -1.6, -0.8); # }+```+is a teardrop shape formed by a single cubic Bézier curve.diff --git a/third_party/msdfgen/build-release.bat b/third_party/msdfgen/build-release.batnew file mode 100644index 000000000..855da8023--- /dev/null+++ b/third_party/msdfgen/build-release.bat@@ -0,0 +1,96 @@+@echo off+setlocal+pushd "%~dp0"++if "%VCVARSALL%"=="" set "VCVARSALL=C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvarsall.bat"+if "%VCTOOLSET%"=="" set "VCTOOLSET=VC143"++if not exist "%VCVARSALL%" (+ echo vcvarsall.bat not found, set VCVARSALL to its path+ exit /b 1+)++if "%1"=="" (+ echo No version specified, using current+ set "version=current"+) else (+ set "version=%1"+)+set "builddir=%~dp0\build\release-%version%"++if exist "%builddir%" (+ echo Deleting contents of %builddir%+ rd /s /q "%builddir%"+)++cmake --preset win32 -B "%builddir%\build-win32"+cmake --preset win32-omp -B "%builddir%\build-win32-omp"+cmake --preset win64 -B "%builddir%\build-win64"+cmake --preset win64-omp -B "%builddir%\build-win64-omp"++cmake --build "%builddir%\build-win32" --config Release+cmake --build "%builddir%\build-win32-omp" --config Release+cmake --build "%builddir%\build-win64" --config Release+cmake --build "%builddir%\build-win64-omp" --config Release++mkdir "%builddir%\rel-win32\msdfgen"+mkdir "%builddir%\rel-win32-omp\msdfgen"+mkdir "%builddir%\rel-win64\msdfgen"+mkdir "%builddir%\rel-win64-omp\msdfgen"++copy "%builddir%\build-win32\Release\msdfgen.exe" "%builddir%\rel-win32\msdfgen"+copy "%builddir%\build-win32-omp\Release\msdfgen.exe" "%builddir%\rel-win32-omp\msdfgen"+copy "%builddir%\build-win64\Release\msdfgen.exe" "%builddir%\rel-win64\msdfgen"+copy "%builddir%\build-win64-omp\Release\msdfgen.exe" "%builddir%\rel-win64-omp\msdfgen"++echo msdfgen.exe -defineshape "{ 1471,0; 1149,0; 1021,333; 435,333; 314,0; 0,0; 571,1466; 884,1466; # }{ 926,580; 724,1124; 526,580; # }" -size 16 16 -autoframe -testrender render.png 1024 1024 > "%builddir%\example.bat"++copy "%builddir%\example.bat" "%builddir%\rel-win32\msdfgen"+copy "%builddir%\example.bat" "%builddir%\rel-win32-omp\msdfgen"+copy "%builddir%\example.bat" "%builddir%\rel-win64\msdfgen"+copy "%builddir%\example.bat" "%builddir%\rel-win64-omp\msdfgen"++call "%VCVARSALL%" x64++set "omp32dll=%VCToolsRedistDir%\x86\Microsoft.%VCTOOLSET%.OPENMP\vcomp140.dll"+set "omp64dll=%VCToolsRedistDir%\x64\Microsoft.%VCTOOLSET%.OPENMP\vcomp140.dll"++if not exist "%omp32dll%" (+ echo vcomp140.dll [x86] not found, make sure to set VCTOOLSET or update this script+ exit /b 1+)+if not exist "%omp64dll%" (+ echo vcomp140.dll [x64] not found, make sure to set VCTOOLSET or update this script+ exit /b 1+)++copy "%omp32dll%" "%builddir%\rel-win32-omp\msdfgen"+copy "%omp64dll%" "%builddir%\rel-win64-omp\msdfgen"++if not exist "C:\Program Files\7-Zip\7z.exe" (+ echo 7-Zip not found, you have to package it manually+ exit /b 0+)++pushd "%builddir%\rel-win32"+"C:\Program Files\7-Zip\7z.exe" a "..\msdfgen-%version%-win32.zip" msdfgen+cd msdfgen+call example.bat+popd+pushd "%builddir%\rel-win32-omp"+"C:\Program Files\7-Zip\7z.exe" a "..\msdfgen-%version%-win32-openmp.zip" msdfgen+cd msdfgen+call example.bat+popd+pushd "%builddir%\rel-win64"+"C:\Program Files\7-Zip\7z.exe" a "..\msdfgen-%version%-win64.zip" msdfgen+cd msdfgen+call example.bat+popd+pushd "%builddir%\rel-win64-omp"+"C:\Program Files\7-Zip\7z.exe" a "..\msdfgen-%version%-win64-openmp.zip" msdfgen+cd msdfgen+call example.bat+popd++popddiff --git a/third_party/msdfgen/cmake/CMakePresets.json b/third_party/msdfgen/cmake/CMakePresets.jsonnew file mode 100644index 000000000..e30f167ae--- /dev/null+++ b/third_party/msdfgen/cmake/CMakePresets.json@@ -0,0 +1,170 @@+{+ "version": 4,+ "cmakeMinimumRequired": {+ "major": 3,+ "minor": 23,+ "patch": 0+ },+ "configurePresets": [+ {+ "name": "release-only",+ "displayName": "Release only configuration",+ "hidden": true,+ "cacheVariables": {+ "CMAKE_BUILD_TYPE": "Release"+ }+ }, {+ "name": "debug-only",+ "displayName": "Debug only configuration",+ "hidden": true,+ "cacheVariables": {+ "CMAKE_BUILD_TYPE": "Debug"+ }+ }, {+ "name": "win64-base",+ "displayName": "Windows 64-bit base configuration",+ "hidden": true,+ "architecture": "x64",+ "binaryDir": "${sourceDir}/build/win64",+ "condition": {+ "type": "equals",+ "lhs": "${hostSystemName}",+ "rhs": "Windows"+ }+ }, {+ "name": "win32-base",+ "displayName": "Windows 32-bit base configuration",+ "hidden": true,+ "architecture": "Win32",+ "binaryDir": "${sourceDir}/build/win32",+ "condition": {+ "type": "equals",+ "lhs": "${hostSystemName}",+ "rhs": "Windows"+ }+ }, {+ "name": "osx-base",+ "displayName": "Mac OS base configuration",+ "hidden": true,+ "binaryDir": "${sourceDir}/build/osx",+ "condition": {+ "type": "equals",+ "lhs": "${hostSystemName}",+ "rhs": "Darwin"+ }+ }, {+ "name": "osx-rel-base",+ "displayName": "Mac OS base release configuration",+ "inherits": [ "osx-base", "release-only" ],+ "hidden": true,+ "binaryDir": "${sourceDir}/build/osx-rel"+ }, {+ "name": "osx-dbg-base",+ "displayName": "Mac OS base debug configuration",+ "inherits": [ "osx-base", "debug-only" ],+ "hidden": true,+ "binaryDir": "${sourceDir}/build/osx-dbg"+ }, {+ "name": "linux-base",+ "displayName": "Linux base configuration",+ "hidden": true,+ "binaryDir": "${sourceDir}/build/linux",+ "condition": {+ "type": "equals",+ "lhs": "${hostSystemName}",+ "rhs": "Linux"+ }+ }, {+ "name": "linux-rel-base",+ "displayName": "Linux base release configuration",+ "inherits": [ "linux-base", "release-only" ],+ "hidden": true,+ "binaryDir": "${sourceDir}/build/linux-rel"+ }, {+ "name": "linux-dbg-base",+ "displayName": "Linux base debug configuration",+ "inherits": [ "linux-base", "debug-only" ],+ "hidden": true,+ "binaryDir": "${sourceDir}/build/linux-dbg"+ }, {+ "name": "core-only",+ "displayName": "Configuration with extensions disabled",+ "hidden": true,+ "cacheVariables": {+ "MSDFGEN_CORE_ONLY": "ON",+ "MSDFGEN_USE_VCPKG": "OFF",+ "MSDFGEN_USE_SKIA": "OFF"+ }+ }, {+ "name": "vcpkg",+ "displayName": "Configuration with vcpkg as dependency management system",+ "hidden": true,+ "cacheVariables": {+ "MSDFGEN_USE_VCPKG": "ON"+ }+ }, {+ "name": "no-vcpkg",+ "displayName": "Configuration with dependencies not managed by vcpkg",+ "hidden": true,+ "cacheVariables": {+ "MSDFGEN_USE_VCPKG": "OFF"+ }+ }, {+ "name": "openmp",+ "displayName": "Configuration with OpenMP enabled",+ "hidden": true,+ "cacheVariables": {+ "MSDFGEN_USE_OPENMP": "ON"+ }+ }, {+ "name": "skia",+ "displayName": "Configuration with Skia geometry preprocessing",+ "hidden": true,+ "cacheVariables": {+ "MSDFGEN_USE_SKIA": "ON"+ }+ }, {+ "name": "no-skia",+ "displayName": "Configuration without Skia geometry preprocessing",+ "hidden": true,+ "cacheVariables": {+ "MSDFGEN_USE_SKIA": "OFF"+ }+ }, {+ "name": "install",+ "displayName": "Configuration with installation targets",+ "hidden": true,+ "cacheVariables": {+ "MSDFGEN_INSTALL": "ON"+ }+ }, {+ "name": "static-runtime",+ "displayName": "Configuration that links against the static runtime",+ "hidden": true,+ "cacheVariables": {+ "MSDFGEN_DYNAMIC_RUNTIME": "OFF"+ }+ }, {+ "name": "dynamic-runtime",+ "displayName": "Configuration that links against the dynamic runtime",+ "hidden": true,+ "cacheVariables": {+ "MSDFGEN_DYNAMIC_RUNTIME": "ON"+ }+ }, {+ "name": "static-lib",+ "displayName": "Configuration that builds and links msdfgen statically",+ "hidden": true,+ "cacheVariables": {+ "BUILD_SHARED_LIBS": "OFF"+ }+ }, {+ "name": "dynamic-lib",+ "displayName": "Configuration that builds and links msdfgen dynamically",+ "hidden": true,+ "cacheVariables": {+ "BUILD_SHARED_LIBS": "ON"+ }+ }+ ]+}diff --git a/third_party/msdfgen/cmake/msdfgen-config.h.in b/third_party/msdfgen/cmake/msdfgen-config.h.innew file mode 100644index 000000000..4959f6b27--- /dev/null+++ b/third_party/msdfgen/cmake/msdfgen-config.h.in@@ -0,0 +1,12 @@++#pragma once++#define MSDFGEN_PUBLIC${MSDFGEN_PUBLIC_MACRO_VALUE}+#define MSDFGEN_EXT_PUBLIC${MSDFGEN_PUBLIC_MACRO_VALUE}++#define MSDFGEN_VERSION ${MSDFGEN_VERSION}+#define MSDFGEN_VERSION_MAJOR ${MSDFGEN_VERSION_MAJOR}+#define MSDFGEN_VERSION_MINOR ${MSDFGEN_VERSION_MINOR}+#define MSDFGEN_VERSION_REVISION ${MSDFGEN_VERSION_REVISION}+#define MSDFGEN_COPYRIGHT_YEAR ${MSDFGEN_COPYRIGHT_YEAR}+${MSDFGEN_ADDITIONAL_DEFINES}diff --git a/third_party/msdfgen/cmake/msdfgenConfig.cmake.in b/third_party/msdfgen/cmake/msdfgenConfig.cmake.innew file mode 100644index 000000000..b47d00066--- /dev/null+++ b/third_party/msdfgen/cmake/msdfgenConfig.cmake.in@@ -0,0 +1,58 @@++include(CMakeFindDependencyMacro)++set(MSDFGEN_CORE_ONLY @MSDFGEN_CORE_ONLY@)+set(MSDFGEN_USE_VCPKG @MSDFGEN_USE_VCPKG@)+set(MSDFGEN_USE_OPENMP @MSDFGEN_USE_OPENMP@)+set(MSDFGEN_USE_SKIA @MSDFGEN_USE_SKIA@)+set(MSDFGEN_STANDALONE_AVAILABLE @MSDFGEN_BUILD_STANDALONE@)+set(MSDFGEN_DISABLE_SVG @MSDFGEN_DISABLE_SVG@)+set(MSDFGEN_DISABLE_PNG @MSDFGEN_DISABLE_PNG@)++if(NOT MSDFGEN_CORE_ONLY)+ find_dependency(Freetype REQUIRED)+ if(NOT MSDFGEN_DISABLE_SVG)+ find_dependency(tinyxml2 REQUIRED)+ endif()+ if(NOT MSDFGEN_DISABLE_PNG)+ find_dependency(PNG REQUIRED)+ endif()+endif()+if(MSDFGEN_USE_SKIA)+ find_dependency(Threads REQUIRED)+ if(MSDFGEN_USE_VCPKG)+ find_dependency(unofficial-skia REQUIRED)+ else()+ find_dependency(skia REQUIRED)+ endif()+endif()+if(MSDFGEN_USE_OPENMP)+ find_dependency(OpenMP REQUIRED COMPONENTS CXX)+endif()++include("${CMAKE_CURRENT_LIST_DIR}/msdfgenTargets.cmake")++if(MSDFGEN_CORE_ONLY)+ if(${CMAKE_VERSION} VERSION_LESS "3.18.0")+ set_target_properties(msdfgen::msdfgen-core PROPERTIES IMPORTED_GLOBAL TRUE)+ endif()+ if(NOT TARGET msdfgen::msdfgen)+ add_library(msdfgen::msdfgen ALIAS msdfgen::msdfgen-core)+ endif()+else()+ if(${CMAKE_VERSION} VERSION_LESS "3.18.0")+ set_target_properties(msdfgen::msdfgen-full PROPERTIES IMPORTED_GLOBAL TRUE)+ endif()+ if(NOT TARGET msdfgen::msdfgen)+ add_library(msdfgen::msdfgen ALIAS msdfgen::msdfgen-full)+ endif()+endif()++if(MSDFGEN_STANDALONE_AVAILABLE)+ include("${CMAKE_CURRENT_LIST_DIR}/msdfgenBinaryTargets.cmake")+ if(${CMAKE_VERSION} VERSION_LESS "3.18.0")+ set_target_properties(msdfgen-standalone::msdfgen PROPERTIES IMPORTED_GLOBAL TRUE)+ endif()+ add_executable(msdfgen::msdfgen-run ALIAS msdfgen-standalone::msdfgen)+ set(MSDFGEN_EXECUTABLE "@CMAKE_INSTALL_PREFIX@/@CMAKE_INSTALL_BINDIR@/msdfgen@CMAKE_EXECUTABLE_SUFFIX@")+endif()diff --git a/third_party/msdfgen/cmake/version.cmake b/third_party/msdfgen/cmake/version.cmakenew file mode 100644index 000000000..279ace30e--- /dev/null+++ b/third_party/msdfgen/cmake/version.cmake@@ -0,0 +1,19 @@++# This script reads version from vcpkg.json and sets it to ${MSDFGEN_VERSION} etc.++cmake_minimum_required(VERSION 3.15)++file(STRINGS "${CMAKE_CURRENT_LIST_DIR}/../vcpkg.json" MSDFGEN_VCPKG_JSON)++string(REGEX MATCH "\"version\"[ \t\n\r]*:[ \t\n\r]*\"[^\"]*\"" MSDFGEN_TMP_VERSION_PAIR ${MSDFGEN_VCPKG_JSON})+string(REGEX REPLACE "\"version\"[ \t\n\r]*:[ \t\n\r]*\"([^\"]*)\"" "\\1" MSDFGEN_VERSION ${MSDFGEN_TMP_VERSION_PAIR})+string(REGEX REPLACE "^([0-9]*)\\.([0-9]*)\\.([0-9]*)" "\\1" MSDFGEN_VERSION_MAJOR ${MSDFGEN_VERSION})+string(REGEX REPLACE "^([0-9]*)\\.([0-9]*)\\.([0-9]*)" "\\2" MSDFGEN_VERSION_MINOR ${MSDFGEN_VERSION})+string(REGEX REPLACE "^([0-9]*)\\.([0-9]*)\\.([0-9]*)" "\\3" MSDFGEN_VERSION_REVISION ${MSDFGEN_VERSION})+string(LENGTH ${MSDFGEN_VERSION} MSDFGEN_VERSION_LENGTH)+string(REPEAT "-" ${MSDFGEN_VERSION_LENGTH} MSDFGEN_VERSION_UNDERLINE)+string(TIMESTAMP MSDFGEN_COPYRIGHT_YEAR "%Y")++unset(MSDFGEN_TMP_VERSION_PAIR)+unset(MSDFGEN_VERSION_LENGTH)+unset(MSDFGEN_VCPKG_JSON)diff --git a/third_party/msdfgen/core/Bitmap.h b/third_party/msdfgen/core/Bitmap.hnew file mode 100644index 000000000..05c305d64--- /dev/null+++ b/third_party/msdfgen/core/Bitmap.h@@ -0,0 +1,60 @@++#pragma once++#include "YAxisOrientation.h"+#include "BitmapRef.hpp"++namespace msdfgen {++/// A 2D image bitmap with N channels of type T. Pixel memory is managed by the class.+template <typename T, int N = 1>+class Bitmap {++public:+ Bitmap();+ Bitmap(int width, int height, YAxisOrientation yOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION);+ explicit Bitmap(const BitmapConstRef<T, N> &orig);+ explicit Bitmap(const BitmapConstSection<T, N> &orig);+ Bitmap(const Bitmap<T, N> &orig);+#ifdef MSDFGEN_USE_CPP11+ Bitmap(Bitmap<T, N> &&orig);+#endif+ ~Bitmap();+ Bitmap<T, N> &operator=(const BitmapConstRef<T, N> &orig);+ Bitmap<T, N> &operator=(const BitmapConstSection<T, N> &orig);+ Bitmap<T, N> &operator=(const Bitmap<T, N> &orig);+#ifdef MSDFGEN_USE_CPP11+ Bitmap<T, N> &operator=(Bitmap<T, N> &&orig);+#endif+ /// Bitmap width in pixels.+ int width() const;+ /// Bitmap height in pixels.+ int height() const;+ T *operator()(int x, int y);+ const T *operator()(int x, int y) const;+#ifdef MSDFGEN_USE_CPP11+ explicit operator T *();+ explicit operator const T *() const;+#else+ operator T *();+ operator const T *() const;+#endif+ operator BitmapRef<T, N>();+ operator BitmapConstRef<T, N>() const;+ operator BitmapSection<T, N>();+ operator BitmapConstSection<T, N>() const;+ /// Returns a reference to a rectangular section of the bitmap specified by bounds (excluding xMax, yMax).+ BitmapSection<T, N> getSection(int xMin, int yMin, int xMax, int yMax);+ /// Returns a constant reference to a rectangular section of the bitmap specified by bounds (excluding xMax, yMax).+ BitmapConstSection<T, N> getConstSection(int xMin, int yMin, int xMax, int yMax) const;++private:+ T *pixels;+ int w, h;+ YAxisOrientation yOrientation;++};++}++#include "Bitmap.hpp"diff --git a/third_party/msdfgen/core/Bitmap.hpp b/third_party/msdfgen/core/Bitmap.hppnew file mode 100644index 000000000..afb53942f--- /dev/null+++ b/third_party/msdfgen/core/Bitmap.hpp@@ -0,0 +1,172 @@++#include "Bitmap.h"++#include <cstdlib>+#include <cstring>++namespace msdfgen {++template <typename T, int N>+Bitmap<T, N>::Bitmap() : pixels(NULL), w(0), h(0), yOrientation(MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) { }++template <typename T, int N>+Bitmap<T, N>::Bitmap(int width, int height, YAxisOrientation yOrientation) : w(width), h(height), yOrientation(yOrientation) {+ pixels = new T[N*w*h];+}++template <typename T, int N>+Bitmap<T, N>::Bitmap(const BitmapConstRef<T, N> &orig) : w(orig.width), h(orig.height), yOrientation(orig.yOrientation) {+ pixels = new T[N*w*h];+ memcpy(pixels, orig.pixels, sizeof(T)*N*w*h);+}++template <typename T, int N>+Bitmap<T, N>::Bitmap(const BitmapConstSection<T, N> &orig) : w(orig.width), h(orig.height), yOrientation(orig.yOrientation) {+ pixels = new T[N*w*h];+ T *dst = pixels;+ const T *src = orig.pixels;+ int rowLength = N*w;+ for (int y = 0; y < h; ++y) {+ memcpy(dst, src, sizeof(T)*rowLength);+ dst += rowLength;+ src += orig.rowStride;+ }+}++template <typename T, int N>+Bitmap<T, N>::Bitmap(const Bitmap<T, N> &orig) : w(orig.w), h(orig.h), yOrientation(orig.yOrientation) {+ pixels = new T[N*w*h];+ memcpy(pixels, orig.pixels, sizeof(T)*N*w*h);+}++#ifdef MSDFGEN_USE_CPP11+template <typename T, int N>+Bitmap<T, N>::Bitmap(Bitmap<T, N> &&orig) : pixels(orig.pixels), w(orig.w), h(orig.h), yOrientation(orig.yOrientation) {+ orig.pixels = NULL;+ orig.w = 0, orig.h = 0;+}+#endif++template <typename T, int N>+Bitmap<T, N>::~Bitmap() {+ delete[] pixels;+}++template <typename T, int N>+Bitmap<T, N> &Bitmap<T, N>::operator=(const BitmapConstRef<T, N> &orig) {+ if (pixels != orig.pixels) {+ delete[] pixels;+ w = orig.width, h = orig.height;+ yOrientation = orig.yOrientation;+ pixels = new T[N*w*h];+ memcpy(pixels, orig.pixels, sizeof(T)*N*w*h);+ }+ return *this;+}++template <typename T, int N>+Bitmap<T, N> &Bitmap<T, N>::operator=(const BitmapConstSection<T, N> &orig) {+ if (orig.pixels && orig.pixels >= pixels && orig.pixels < pixels+N*w*h)+ return *this = Bitmap<T, N>(orig);+ delete[] pixels;+ w = orig.width, h = orig.height;+ yOrientation = orig.yOrientation;+ pixels = new T[N*w*h];+ T *dst = pixels;+ const T *src = orig.pixels;+ int rowLength = N*w;+ for (int y = 0; y < h; ++y) {+ memcpy(dst, src, sizeof(T)*rowLength);+ dst += rowLength;+ src += orig.rowStride;+ }+ return *this;+}++template <typename T, int N>+Bitmap<T, N> &Bitmap<T, N>::operator=(const Bitmap<T, N> &orig) {+ if (this != &orig) {+ delete[] pixels;+ w = orig.w, h = orig.h;+ yOrientation = orig.yOrientation;+ pixels = new T[N*w*h];+ memcpy(pixels, orig.pixels, sizeof(T)*N*w*h);+ }+ return *this;+}++#ifdef MSDFGEN_USE_CPP11+template <typename T, int N>+Bitmap<T, N> &Bitmap<T, N>::operator=(Bitmap<T, N> &&orig) {+ if (this != &orig) {+ delete[] pixels;+ pixels = orig.pixels;+ w = orig.w, h = orig.h;+ yOrientation = orig.yOrientation;+ orig.pixels = NULL;+ }+ return *this;+}+#endif++template <typename T, int N>+int Bitmap<T, N>::width() const {+ return w;+}++template <typename T, int N>+int Bitmap<T, N>::height() const {+ return h;+}++template <typename T, int N>+T *Bitmap<T, N>::operator()(int x, int y) {+ return pixels+N*(w*y+x);+}++template <typename T, int N>+const T *Bitmap<T, N>::operator()(int x, int y) const {+ return pixels+N*(w*y+x);+}++template <typename T, int N>+Bitmap<T, N>::operator T *() {+ return pixels;+}++template <typename T, int N>+Bitmap<T, N>::operator const T *() const {+ return pixels;+}++template <typename T, int N>+Bitmap<T, N>::operator BitmapRef<T, N>() {+ return BitmapRef<T, N>(pixels, w, h, yOrientation);+}++template <typename T, int N>+Bitmap<T, N>::operator BitmapConstRef<T, N>() const {+ return BitmapConstRef<T, N>(pixels, w, h, yOrientation);+}++template <typename T, int N>+Bitmap<T, N>::operator BitmapSection<T, N>() {+ return BitmapSection<T, N>(pixels, w, h, yOrientation);+}++template <typename T, int N>+Bitmap<T, N>::operator BitmapConstSection<T, N>() const {+ return BitmapConstSection<T, N>(pixels, w, h, yOrientation);+}++template <typename T, int N>+BitmapSection<T, N> Bitmap<T, N>::getSection(int xMin, int yMin, int xMax, int yMax) {+ return BitmapSection<T, N>(pixels+N*(w*yMin+xMin), xMax-xMin, yMax-yMin, N*w, yOrientation);+}++template <typename T, int N>+BitmapConstSection<T, N> Bitmap<T, N>::getConstSection(int xMin, int yMin, int xMax, int yMax) const {+ return BitmapConstSection<T, N>(pixels+N*(w*yMin+xMin), xMax-xMin, yMax-yMin, N*w, yOrientation);+}++}diff --git a/third_party/msdfgen/core/BitmapRef.hpp b/third_party/msdfgen/core/BitmapRef.hppnew file mode 100644index 000000000..6e93fe983--- /dev/null+++ b/third_party/msdfgen/core/BitmapRef.hpp@@ -0,0 +1,154 @@++#pragma once++#include "YAxisOrientation.h"++namespace msdfgen {++/// Reference to a 2D image bitmap or a buffer acting as one. Pixel storage not owned or managed by the object.+template <typename T, int N = 1>+struct BitmapRef;+/// Constant reference to a 2D image bitmap or a buffer acting as one. Pixel storage not owned or managed by the object.+template <typename T, int N = 1>+struct BitmapConstRef;+/// Reference to a 2D image bitmap with non-contiguous rows of pixels. Pixel storage not owned or managed by the object. Can represent e.g. a section of a larger bitmap, bitmap with padded rows, or vertically flipped bitmap (rowStride can be negative).+template <typename T, int N = 1>+struct BitmapSection;+/// Constant reference to a 2D image bitmap with non-contiguous rows of pixels. Pixel storage not owned or managed by the object. Can represent e.g. a section of a larger bitmap, bitmap with padded rows, or vertically flipped bitmap (rowStride can be negative).+template <typename T, int N = 1>+struct BitmapConstSection;++template <typename T, int N>+struct BitmapRef {++ T *pixels;+ int width, height;+ YAxisOrientation yOrientation;++ inline BitmapRef() : pixels(NULL), width(0), height(0), yOrientation(MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) { }+ inline BitmapRef(T *pixels, int width, int height, YAxisOrientation yOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) : pixels(pixels), width(width), height(height), yOrientation(yOrientation) { }++ inline T *operator()(int x, int y) const {+ return pixels+N*(width*y+x);+ }++ /// Returns a reference to a rectangular section of the bitmap specified by bounds (excluding xMax, yMax).+ inline BitmapSection<T, N> getSection(int xMin, int yMin, int xMax, int yMax) const {+ return BitmapSection<T, N>(pixels+N*(width*yMin+xMin), xMax-xMin, yMax-yMin, N*width, yOrientation);+ }++ /// Returns a constant reference to a rectangular section of the bitmap specified by bounds (excluding xMax, yMax).+ inline BitmapConstSection<T, N> getConstSection(int xMin, int yMin, int xMax, int yMax) const {+ return BitmapConstSection<T, N>(pixels+N*(width*yMin+xMin), xMax-xMin, yMax-yMin, N*width, yOrientation);+ }++};++template <typename T, int N>+struct BitmapConstRef {++ const T *pixels;+ int width, height;+ YAxisOrientation yOrientation;++ inline BitmapConstRef() : pixels(NULL), width(0), height(0), yOrientation(MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) { }+ inline BitmapConstRef(const T *pixels, int width, int height, YAxisOrientation yOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) : pixels(pixels), width(width), height(height), yOrientation(yOrientation) { }+ inline BitmapConstRef(const BitmapRef<T, N> &orig) : pixels(orig.pixels), width(orig.width), height(orig.height), yOrientation(orig.yOrientation) { }++ inline const T *operator()(int x, int y) const {+ return pixels+N*(width*y+x);+ }++ /// Returns a constant reference to a rectangular section of the bitmap specified by bounds (excluding xMax, yMax).+ inline BitmapConstSection<T, N> getSection(int xMin, int yMin, int xMax, int yMax) const {+ return BitmapConstSection<T, N>(pixels+N*(width*yMin+xMin), xMax-xMin, yMax-yMin, N*width, yOrientation);+ }++ /// Returns a constant reference to a rectangular section of the bitmap specified by bounds (excluding xMax, yMax).+ inline BitmapConstSection<T, N> getConstSection(int xMin, int yMin, int xMax, int yMax) const {+ return getSection(xMin, yMin, xMax, yMax);+ }++};++template <typename T, int N>+struct BitmapSection {++ T *pixels;+ int width, height;+ /// Specifies the difference between the beginnings of adjacent pixel rows as the number of T elements, can be negative.+ int rowStride;+ YAxisOrientation yOrientation;++ inline BitmapSection() : pixels(NULL), width(0), height(0), rowStride(0), yOrientation(MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) { }+ inline BitmapSection(T *pixels, int width, int height, YAxisOrientation yOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) : pixels(pixels), width(width), height(height), rowStride(N*width), yOrientation(yOrientation) { }+ inline BitmapSection(T *pixels, int width, int height, int rowStride, YAxisOrientation yOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) : pixels(pixels), width(width), height(height), rowStride(rowStride), yOrientation(yOrientation) { }+ inline BitmapSection(const BitmapRef<T, N> &orig) : pixels(orig.pixels), width(orig.width), height(orig.height), rowStride(N*orig.width), yOrientation(orig.yOrientation) { }++ inline T *operator()(int x, int y) const {+ return pixels+rowStride*y+N*x;+ }++ /// Returns a reference to a rectangular subsection of the bitmap specified by bounds (excluding xMax, yMax).+ inline BitmapSection<T, N> getSection(int xMin, int yMin, int xMax, int yMax) const {+ return BitmapSection<T, N>(pixels+rowStride*yMin+N*xMin, xMax-xMin, yMax-yMin, rowStride, yOrientation);+ }++ /// Returns a constant reference to a rectangular subsection of the bitmap specified by bounds (excluding xMax, yMax).+ inline BitmapConstSection<T, N> getConstSection(int xMin, int yMin, int xMax, int yMax) const {+ return BitmapConstSection<T, N>(pixels+rowStride*yMin+N*xMin, xMax-xMin, yMax-yMin, rowStride, yOrientation);+ }++ /// Makes sure that the section's Y-axis orientation matches the argument by potentially reordering its rows.+ inline void reorient(YAxisOrientation newYAxisOrientation) {+ if (yOrientation != newYAxisOrientation) {+ pixels += rowStride*(height-1);+ rowStride = -rowStride;+ yOrientation = newYAxisOrientation;+ }+ }++};++template <typename T, int N>+struct BitmapConstSection {++ const T *pixels;+ int width, height;+ /// Specifies the difference between the beginnings of adjacent pixel rows as the number of T elements, can be negative.+ int rowStride;+ YAxisOrientation yOrientation;++ inline BitmapConstSection() : pixels(NULL), width(0), height(0), rowStride(0), yOrientation(MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) { }+ inline BitmapConstSection(const T *pixels, int width, int height, YAxisOrientation yOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) : pixels(pixels), width(width), height(height), rowStride(N*width), yOrientation(yOrientation) { }+ inline BitmapConstSection(const T *pixels, int width, int height, int rowStride, YAxisOrientation yOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION) : pixels(pixels), width(width), height(height), rowStride(rowStride), yOrientation(yOrientation) { }+ inline BitmapConstSection(const BitmapRef<T, N> &orig) : pixels(orig.pixels), width(orig.width), height(orig.height), rowStride(N*orig.width), yOrientation(orig.yOrientation) { }+ inline BitmapConstSection(const BitmapConstRef<T, N> &orig) : pixels(orig.pixels), width(orig.width), height(orig.height), rowStride(N*orig.width), yOrientation(orig.yOrientation) { }+ inline BitmapConstSection(const BitmapSection<T, N> &orig) : pixels(orig.pixels), width(orig.width), height(orig.height), rowStride(orig.rowStride), yOrientation(orig.yOrientation) { }++ inline const T *operator()(int x, int y) const {+ return pixels+rowStride*y+N*x;+ }++ /// Returns a constant reference to a rectangular subsection of the bitmap specified by bounds (excluding xMax, yMax).+ inline BitmapConstSection<T, N> getSection(int xMin, int yMin, int xMax, int yMax) const {+ return BitmapConstSection<T, N>(pixels+rowStride*yMin+N*xMin, xMax-xMin, yMax-yMin, rowStride, yOrientation);+ }++ /// Returns a constant reference to a rectangular subsection of the bitmap specified by bounds (excluding xMax, yMax).+ inline BitmapConstSection<T, N> getConstSection(int xMin, int yMin, int xMax, int yMax) const {+ return getSection(xMin, yMin, xMax, yMax);+ }++ /// Makes sure that the section's Y-axis orientation matches the argument by potentially reordering its rows.+ inline void reorient(YAxisOrientation newYAxisOrientation) {+ if (yOrientation != newYAxisOrientation) {+ pixels += rowStride*(height-1);+ rowStride = -rowStride;+ yOrientation = newYAxisOrientation;+ }+ }++};++}diff --git a/third_party/msdfgen/core/Contour.cpp b/third_party/msdfgen/core/Contour.cppnew file mode 100644index 000000000..aade65e59--- /dev/null+++ b/third_party/msdfgen/core/Contour.cpp@@ -0,0 +1,90 @@++#include "Contour.h"++#include "arithmetics.hpp"++namespace msdfgen {++static double shoelace(const Point2 &a, const Point2 &b) {+ return (b.x-a.x)*(a.y+b.y);+}++void Contour::addEdge(const EdgeHolder &edge) {+ edges.push_back(edge);+}++#ifdef MSDFGEN_USE_CPP11+void Contour::addEdge(EdgeHolder &&edge) {+ edges.push_back((EdgeHolder &&) edge);+}+#endif++EdgeHolder &Contour::addEdge() {+ edges.resize(edges.size()+1);+ return edges.back();+}++static void boundPoint(double &xMin, double &yMin, double &xMax, double &yMax, Point2 p) {+ if (p.x < xMin) xMin = p.x;+ if (p.y < yMin) yMin = p.y;+ if (p.x > xMax) xMax = p.x;+ if (p.y > yMax) yMax = p.y;+}++void Contour::bound(double &xMin, double &yMin, double &xMax, double &yMax) const {+ for (std::vector<EdgeHolder>::const_iterator edge = edges.begin(); edge != edges.end(); ++edge)+ (*edge)->bound(xMin, yMin, xMax, yMax);+}++void Contour::boundMiters(double &xMin, double &yMin, double &xMax, double &yMax, double border, double miterLimit, int polarity) const {+ if (edges.empty())+ return;+ Vector2 prevDir = edges.back()->direction(1).normalize(true);+ for (std::vector<EdgeHolder>::const_iterator edge = edges.begin(); edge != edges.end(); ++edge) {+ Vector2 dir = -(*edge)->direction(0).normalize(true);+ if (polarity*crossProduct(prevDir, dir) >= 0) {+ double miterLength = miterLimit;+ double q = .5*(1-dotProduct(prevDir, dir));+ if (q > 0)+ miterLength = min(1/sqrt(q), miterLimit);+ Point2 miter = (*edge)->point(0)+border*miterLength*(prevDir+dir).normalize(true);+ boundPoint(xMin, yMin, xMax, yMax, miter);+ }+ prevDir = (*edge)->direction(1).normalize(true);+ }+}++int Contour::winding() const {+ if (edges.empty())+ return 0;+ double total = 0;+ if (edges.size() == 1) {+ Point2 a = edges[0]->point(0), b = edges[0]->point(1/3.), c = edges[0]->point(2/3.);+ total += shoelace(a, b);+ total += shoelace(b, c);+ total += shoelace(c, a);+ } else if (edges.size() == 2) {+ Point2 a = edges[0]->point(0), b = edges[0]->point(.5), c = edges[1]->point(0), d = edges[1]->point(.5);+ total += shoelace(a, b);+ total += shoelace(b, c);+ total += shoelace(c, d);+ total += shoelace(d, a);+ } else {+ Point2 prev = edges.back()->point(0);+ for (std::vector<EdgeHolder>::const_iterator edge = edges.begin(); edge != edges.end(); ++edge) {+ Point2 cur = (*edge)->point(0);+ total += shoelace(prev, cur);+ prev = cur;+ }+ }+ return sign(total);+}++void Contour::reverse() {+ for (int i = (int) edges.size()/2; i > 0; --i)+ EdgeHolder::swap(edges[i-1], edges[edges.size()-i]);+ for (std::vector<EdgeHolder>::iterator edge = edges.begin(); edge != edges.end(); ++edge)+ (*edge)->reverse();+}++}diff --git a/third_party/msdfgen/core/Contour.h b/third_party/msdfgen/core/Contour.hnew file mode 100644index 000000000..53ceb8eda--- /dev/null+++ b/third_party/msdfgen/core/Contour.h@@ -0,0 +1,34 @@++#pragma once++#include <vector>+#include "EdgeHolder.h"++namespace msdfgen {++/// A single closed contour of a shape.+class Contour {++public:+ /// The sequence of edges that make up the contour.+ std::vector<EdgeHolder> edges;++ /// Adds an edge to the contour.+ void addEdge(const EdgeHolder &edge);+#ifdef MSDFGEN_USE_CPP11+ void addEdge(EdgeHolder &&edge);+#endif+ /// Creates a new edge in the contour and returns its reference.+ EdgeHolder &addEdge();+ /// Adjusts the bounding box to fit the contour.+ void bound(double &xMin, double &yMin, double &xMax, double &yMax) const;+ /// Adjusts the bounding box to fit the contour border's mitered corners.+ void boundMiters(double &xMin, double &yMin, double &xMax, double &yMax, double border, double miterLimit, int polarity) const;+ /// Computes the winding of the contour. Returns 1 if positive, -1 if negative.+ int winding() const;+ /// Reverses the sequence of edges on the contour.+ void reverse();++};++}diff --git a/third_party/msdfgen/core/DistanceMapping.cpp b/third_party/msdfgen/core/DistanceMapping.cppnew file mode 100644index 000000000..526e12905--- /dev/null+++ b/third_party/msdfgen/core/DistanceMapping.cpp@@ -0,0 +1,27 @@++#include "DistanceMapping.h"++namespace msdfgen {++DistanceMapping DistanceMapping::inverse(Range range) {+ double rangeWidth = range.upper-range.lower;+ return DistanceMapping(rangeWidth, range.lower/(rangeWidth ? rangeWidth : 1));+}++DistanceMapping::DistanceMapping() : scale(1), translate(0) { }++DistanceMapping::DistanceMapping(Range range) : scale(1/(range.upper-range.lower)), translate(-range.lower) { }++double DistanceMapping::operator()(double d) const {+ return scale*(d+translate);+}++double DistanceMapping::operator()(Delta d) const {+ return scale*d.value;+}++DistanceMapping DistanceMapping::inverse() const {+ return DistanceMapping(1/scale, -scale*translate);+}++}diff --git a/third_party/msdfgen/core/DistanceMapping.h b/third_party/msdfgen/core/DistanceMapping.hnew file mode 100644index 000000000..fadbefa54--- /dev/null+++ b/third_party/msdfgen/core/DistanceMapping.h@@ -0,0 +1,36 @@++#pragma once++#include "Range.hpp"++namespace msdfgen {++/// Linear transformation of signed distance values.+class DistanceMapping {++public:+ /// Explicitly designates value as distance delta rather than an absolute distance.+ class Delta {+ public:+ double value;+ inline explicit Delta(double distanceDelta) : value(distanceDelta) { }+ inline operator double() const { return value; }+ };++ static DistanceMapping inverse(Range range);++ DistanceMapping();+ DistanceMapping(Range range);+ double operator()(double d) const;+ double operator()(Delta d) const;+ DistanceMapping inverse() const;++private:+ double scale;+ double translate;++ inline DistanceMapping(double scale, double translate) : scale(scale), translate(translate) { }++};++}diff --git a/third_party/msdfgen/core/EdgeColor.h b/third_party/msdfgen/core/EdgeColor.hnew file mode 100644index 000000000..5d3730c9a--- /dev/null+++ b/third_party/msdfgen/core/EdgeColor.h@@ -0,0 +1,20 @@++#pragma once++#include "base.h"++namespace msdfgen {++/// Edge color specifies which color channels an edge belongs to.+enum EdgeColor {+ BLACK = 0,+ RED = 1,+ GREEN = 2,+ YELLOW = 3,+ BLUE = 4,+ MAGENTA = 5,+ CYAN = 6,+ WHITE = 7+};++}diff --git a/third_party/msdfgen/core/EdgeHolder.cpp b/third_party/msdfgen/core/EdgeHolder.cppnew file mode 100644index 000000000..f552e98fa--- /dev/null+++ b/third_party/msdfgen/core/EdgeHolder.cpp@@ -0,0 +1,67 @@++#include "EdgeHolder.h"++namespace msdfgen {++void EdgeHolder::swap(EdgeHolder &a, EdgeHolder &b) {+ EdgeSegment *tmp = a.edgeSegment;+ a.edgeSegment = b.edgeSegment;+ b.edgeSegment = tmp;+}++EdgeHolder::EdgeHolder(const EdgeHolder &orig) : edgeSegment(orig.edgeSegment ? orig.edgeSegment->clone() : NULL) { }++#ifdef MSDFGEN_USE_CPP11+EdgeHolder::EdgeHolder(EdgeHolder &&orig) : edgeSegment(orig.edgeSegment) {+ orig.edgeSegment = NULL;+}+#endif++EdgeHolder::~EdgeHolder() {+ delete edgeSegment;+}++EdgeHolder &EdgeHolder::operator=(const EdgeHolder &orig) {+ if (this != &orig) {+ delete edgeSegment;+ edgeSegment = orig.edgeSegment ? orig.edgeSegment->clone() : NULL;+ }+ return *this;+}++#ifdef MSDFGEN_USE_CPP11+EdgeHolder &EdgeHolder::operator=(EdgeHolder &&orig) {+ if (this != &orig) {+ delete edgeSegment;+ edgeSegment = orig.edgeSegment;+ orig.edgeSegment = NULL;+ }+ return *this;+}+#endif++EdgeSegment &EdgeHolder::operator*() {+ return *edgeSegment;+}++const EdgeSegment &EdgeHolder::operator*() const {+ return *edgeSegment;+}++EdgeSegment *EdgeHolder::operator->() {+ return edgeSegment;+}++const EdgeSegment *EdgeHolder::operator->() const {+ return edgeSegment;+}++EdgeHolder::operator EdgeSegment *() {+ return edgeSegment;+}++EdgeHolder::operator const EdgeSegment *() const {+ return edgeSegment;+}++}diff --git a/third_party/msdfgen/core/EdgeHolder.h b/third_party/msdfgen/core/EdgeHolder.hnew file mode 100644index 000000000..5ae2dc231--- /dev/null+++ b/third_party/msdfgen/core/EdgeHolder.h@@ -0,0 +1,41 @@++#pragma once++#include "edge-segments.h"++namespace msdfgen {++/// Container for a single edge of dynamic type.+class EdgeHolder {++public:+ /// Swaps the edges held by a and b.+ static void swap(EdgeHolder &a, EdgeHolder &b);++ inline EdgeHolder() : edgeSegment() { }+ inline EdgeHolder(EdgeSegment *segment) : edgeSegment(segment) { }+ inline EdgeHolder(Point2 p0, Point2 p1, EdgeColor edgeColor = WHITE) : edgeSegment(EdgeSegment::create(p0, p1, edgeColor)) { }+ inline EdgeHolder(Point2 p0, Point2 p1, Point2 p2, EdgeColor edgeColor = WHITE) : edgeSegment(EdgeSegment::create(p0, p1, p2, edgeColor)) { }+ inline EdgeHolder(Point2 p0, Point2 p1, Point2 p2, Point2 p3, EdgeColor edgeColor = WHITE) : edgeSegment(EdgeSegment::create(p0, p1, p2, p3, edgeColor)) { }+ EdgeHolder(const EdgeHolder &orig);+#ifdef MSDFGEN_USE_CPP11+ EdgeHolder(EdgeHolder &&orig);+#endif+ ~EdgeHolder();+ EdgeHolder &operator=(const EdgeHolder &orig);+#ifdef MSDFGEN_USE_CPP11+ EdgeHolder &operator=(EdgeHolder &&orig);+#endif+ EdgeSegment &operator*();+ const EdgeSegment &operator*() const;+ EdgeSegment *operator->();+ const EdgeSegment *operator->() const;+ operator EdgeSegment *();+ operator const EdgeSegment *() const;++private:+ EdgeSegment *edgeSegment;++};++}diff --git a/third_party/msdfgen/core/MSDFErrorCorrection.cpp b/third_party/msdfgen/core/MSDFErrorCorrection.cppnew file mode 100644index 000000000..940db3d49--- /dev/null+++ b/third_party/msdfgen/core/MSDFErrorCorrection.cpp@@ -0,0 +1,496 @@++#include "MSDFErrorCorrection.h"++#include <cstring>+#include "arithmetics.hpp"+#include "equation-solver.h"+#include "EdgeColor.h"+#include "bitmap-interpolation.hpp"+#include "edge-selectors.h"+#include "contour-combiners.h"+#include "ShapeDistanceFinder.h"+#include "generator-config.h"++namespace msdfgen {++#define ARTIFACT_T_EPSILON .01+#define PROTECTION_RADIUS_TOLERANCE 1.001++#define CLASSIFIER_FLAG_CANDIDATE 0x01+#define CLASSIFIER_FLAG_ARTIFACT 0x02++MSDFGEN_PUBLIC const double ErrorCorrectionConfig::defaultMinDeviationRatio = 1.11111111111111111;+MSDFGEN_PUBLIC const double ErrorCorrectionConfig::defaultMinImproveRatio = 1.11111111111111111;++/// The base artifact classifier recognizes artifacts based on the contents of the SDF alone.+class BaseArtifactClassifier {+public:+ inline BaseArtifactClassifier(double span, bool protectedFlag) : span(span), protectedFlag(protectedFlag) { }+ /// Evaluates if the median value xm interpolated at xt in the range between am at at and bm at bt indicates an artifact.+ inline int rangeTest(double at, double bt, double xt, float am, float bm, float xm) const {+ // For protected texels, only consider inversion artifacts (interpolated median has different sign than boundaries). For the rest, it is sufficient that the interpolated median is outside its boundaries.+ if ((am > .5f && bm > .5f && xm <= .5f) || (am < .5f && bm < .5f && xm >= .5f) || (!protectedFlag && median(am, bm, xm) != xm)) {+ double axSpan = (xt-at)*span, bxSpan = (bt-xt)*span;+ // Check if the interpolated median's value is in the expected range based on its distance (span) from boundaries a, b.+ if (!(xm >= am-axSpan && xm <= am+axSpan && xm >= bm-bxSpan && xm <= bm+bxSpan))+ return CLASSIFIER_FLAG_CANDIDATE|CLASSIFIER_FLAG_ARTIFACT;+ return CLASSIFIER_FLAG_CANDIDATE;+ }+ return 0;+ }+ /// Returns true if the combined results of the tests performed on the median value m interpolated at t indicate an artifact.+ inline bool evaluate(double t, float m, int flags) const {+ return (flags&2) != 0;+ }+private:+ double span;+ bool protectedFlag;+};++/// The shape distance checker evaluates the exact shape distance to find additional artifacts at a significant performance cost.+template <template <typename> class ContourCombiner, int N>+class ShapeDistanceChecker {+public:+ class ArtifactClassifier : public BaseArtifactClassifier {+ public:+ inline ArtifactClassifier(ShapeDistanceChecker *parent, const Vector2 &direction, double span) : BaseArtifactClassifier(span, parent->protectedFlag), parent(parent), direction(direction) { }+ /// Returns true if the combined results of the tests performed on the median value m interpolated at t indicate an artifact.+ inline bool evaluate(double t, float m, int flags) const {+ if (flags&CLASSIFIER_FLAG_CANDIDATE) {+ // Skip expensive distance evaluation if the point has already been classified as an artifact by the base classifier.+ if (flags&CLASSIFIER_FLAG_ARTIFACT)+ return true;+ Vector2 tVector = t*direction;+ float oldMSD[N], newMSD[3];+ // Compute the color that would be currently interpolated at the artifact candidate's position.+ Point2 sdfCoord = parent->sdfCoord+tVector;+ interpolate(oldMSD, parent->sdf, sdfCoord);+ // Compute the color that would be interpolated at the artifact candidate's position if error correction was applied on the current texel.+ double aWeight = (1-fabs(tVector.x))*(1-fabs(tVector.y));+ float aPSD = median(parent->msd[0], parent->msd[1], parent->msd[2]);+ newMSD[0] = float(oldMSD[0]+aWeight*(aPSD-parent->msd[0]));+ newMSD[1] = float(oldMSD[1]+aWeight*(aPSD-parent->msd[1]));+ newMSD[2] = float(oldMSD[2]+aWeight*(aPSD-parent->msd[2]));+ // Compute the evaluated distance (interpolated median) before and after error correction, as well as the exact shape distance.+ float oldPSD = median(oldMSD[0], oldMSD[1], oldMSD[2]);+ float newPSD = median(newMSD[0], newMSD[1], newMSD[2]);+ float refPSD = float(parent->distanceMapping(parent->distanceFinder.distance(parent->shapeCoord+tVector*parent->texelSize)));+ // Compare the differences of the exact distance and the before and after distances.+ return parent->minImproveRatio*fabsf(newPSD-refPSD) < double(fabsf(oldPSD-refPSD));+ }+ return false;+ }+ private:+ ShapeDistanceChecker *parent;+ Vector2 direction;+ };+ Point2 shapeCoord, sdfCoord;+ const float *msd;+ bool protectedFlag;+ inline ShapeDistanceChecker(const BitmapConstSection<float, N> &sdf, const Shape &shape, const Projection &projection, DistanceMapping distanceMapping, double minImproveRatio) : distanceFinder(shape), sdf(sdf), distanceMapping(distanceMapping), minImproveRatio(minImproveRatio) {+ texelSize = projection.unprojectVector(Vector2(1));+ }+ inline ArtifactClassifier classifier(const Vector2 &direction, double span) {+ return ArtifactClassifier(this, direction, span);+ }+private:+ ShapeDistanceFinder<ContourCombiner<PerpendicularDistanceSelector> > distanceFinder;+ BitmapConstSection<float, N> sdf;+ DistanceMapping distanceMapping;+ Vector2 texelSize;+ double minImproveRatio;+};++MSDFErrorCorrection::MSDFErrorCorrection() { }++MSDFErrorCorrection::MSDFErrorCorrection(const BitmapSection<byte, 1> &stencil, const SDFTransformation &transformation) : stencil(stencil), transformation(transformation) {+ minDeviationRatio = ErrorCorrectionConfig::defaultMinDeviationRatio;+ minImproveRatio = ErrorCorrectionConfig::defaultMinImproveRatio;+ for (int y = 0; y < stencil.height; ++y)+ memset(stencil(0, y), 0, sizeof(byte)*stencil.width);+}++void MSDFErrorCorrection::setMinDeviationRatio(double minDeviationRatio) {+ this->minDeviationRatio = minDeviationRatio;+}++void MSDFErrorCorrection::setMinImproveRatio(double minImproveRatio) {+ this->minImproveRatio = minImproveRatio;+}++void MSDFErrorCorrection::protectCorners(const Shape &shape) {+ stencil.reorient(shape.getYAxisOrientation());+ for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)+ if (!contour->edges.empty()) {+ const EdgeSegment *prevEdge = contour->edges.back();+ for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {+ int commonColor = prevEdge->color&(*edge)->color;+ // If the color changes from prevEdge to edge, this is a corner.+ if (!(commonColor&(commonColor-1))) {+ // Find the four texels that envelop the corner and mark them as protected.+ Point2 p = transformation.project((*edge)->point(0));+ int l = (int) floor(p.x-.5);+ int b = (int) floor(p.y-.5);+ int r = l+1;+ int t = b+1;+ // Check that the positions are within bounds.+ if (l < stencil.width && b < stencil.height && r >= 0 && t >= 0) {+ if (l >= 0 && b >= 0)+ *stencil(l, b) |= (byte) PROTECTED;+ if (r < stencil.width && b >= 0)+ *stencil(r, b) |= (byte) PROTECTED;+ if (l >= 0 && t < stencil.height)+ *stencil(l, t) |= (byte) PROTECTED;+ if (r < stencil.width && t < stencil.height)+ *stencil(r, t) |= (byte) PROTECTED;+ }+ }+ prevEdge = *edge;+ }+ }+}++/// Determines if the channel contributes to an edge between the two texels a, b.+static bool edgeBetweenTexelsChannel(const float *a, const float *b, int channel) {+ // Find interpolation ratio t (0 < t < 1) where an edge is expected (mix(a[channel], b[channel], t) == 0.5).+ double t = (a[channel]-.5)/(a[channel]-b[channel]);+ if (t > 0 && t < 1) {+ // Interpolate channel values at t.+ float c[3] = {+ mix(a[0], b[0], t),+ mix(a[1], b[1], t),+ mix(a[2], b[2], t)+ };+ // This is only an edge if the zero-distance channel is the median.+ return median(c[0], c[1], c[2]) == c[channel];+ }+ return false;+}++/// Returns a bit mask of which channels contribute to an edge between the two texels a, b.+static int edgeBetweenTexels(const float *a, const float *b) {+ return (+ RED*edgeBetweenTexelsChannel(a, b, 0)++ GREEN*edgeBetweenTexelsChannel(a, b, 1)++ BLUE*edgeBetweenTexelsChannel(a, b, 2)+ );+}++/// Marks texel as protected if one of its non-median channels is present in the channel mask.+static void protectExtremeChannels(byte *stencil, const float *msd, float m, int mask) {+ if (+ (mask&RED && msd[0] != m) ||+ (mask&GREEN && msd[1] != m) ||+ (mask&BLUE && msd[2] != m)+ )+ *stencil |= (byte) MSDFErrorCorrection::PROTECTED;+}++template <int N>+void MSDFErrorCorrection::protectEdges(const BitmapConstSection<float, N> &sdf) {+ float radius;+ stencil.reorient(sdf.yOrientation);+ // Horizontal texel pairs+ radius = float(PROTECTION_RADIUS_TOLERANCE*transformation.unprojectVector(Vector2(transformation.distanceMapping(DistanceMapping::Delta(1)), 0)).length());+ for (int y = 0; y < sdf.height; ++y) {+ const float *left = sdf(0, y);+ const float *right = sdf(1, y);+ for (int x = 0; x < sdf.width-1; ++x) {+ float lm = median(left[0], left[1], left[2]);+ float rm = median(right[0], right[1], right[2]);+ if (fabsf(lm-.5f)+fabsf(rm-.5f) < radius) {+ int mask = edgeBetweenTexels(left, right);+ protectExtremeChannels(stencil(x, y), left, lm, mask);+ protectExtremeChannels(stencil(x+1, y), right, rm, mask);+ }+ left += N, right += N;+ }+ }+ // Vertical texel pairs+ radius = float(PROTECTION_RADIUS_TOLERANCE*transformation.unprojectVector(Vector2(0, transformation.distanceMapping(DistanceMapping::Delta(1)))).length());+ for (int y = 0; y < sdf.height-1; ++y) {+ const float *bottom = sdf(0, y);+ const float *top = sdf(0, y+1);+ for (int x = 0; x < sdf.width; ++x) {+ float bm = median(bottom[0], bottom[1], bottom[2]);+ float tm = median(top[0], top[1], top[2]);+ if (fabsf(bm-.5f)+fabsf(tm-.5f) < radius) {+ int mask = edgeBetweenTexels(bottom, top);+ protectExtremeChannels(stencil(x, y), bottom, bm, mask);+ protectExtremeChannels(stencil(x, y+1), top, tm, mask);+ }+ bottom += N, top += N;+ }+ }+ // Diagonal texel pairs+ radius = float(PROTECTION_RADIUS_TOLERANCE*transformation.unprojectVector(Vector2(transformation.distanceMapping(DistanceMapping::Delta(1)))).length());+ for (int y = 0; y < sdf.height-1; ++y) {+ const float *lb = sdf(0, y);+ const float *rb = sdf(1, y);+ const float *lt = sdf(0, y+1);+ const float *rt = sdf(1, y+1);+ for (int x = 0; x < sdf.width-1; ++x) {+ float mlb = median(lb[0], lb[1], lb[2]);+ float mrb = median(rb[0], rb[1], rb[2]);+ float mlt = median(lt[0], lt[1], lt[2]);+ float mrt = median(rt[0], rt[1], rt[2]);+ if (fabsf(mlb-.5f)+fabsf(mrt-.5f) < radius) {+ int mask = edgeBetweenTexels(lb, rt);+ protectExtremeChannels(stencil(x, y), lb, mlb, mask);+ protectExtremeChannels(stencil(x+1, y+1), rt, mrt, mask);+ }+ if (fabsf(mrb-.5f)+fabsf(mlt-.5f) < radius) {+ int mask = edgeBetweenTexels(rb, lt);+ protectExtremeChannels(stencil(x+1, y), rb, mrb, mask);+ protectExtremeChannels(stencil(x, y+1), lt, mlt, mask);+ }+ lb += N, rb += N, lt += N, rt += N;+ }+ }+}++void MSDFErrorCorrection::protectAll() {+ for (int y = 0; y < stencil.height; ++y) {+ byte *mask = stencil(0, y);+ for (int x = 0; x < stencil.width; ++x)+ *mask++ |= (byte) PROTECTED;+ }+}++/// Returns the median of the linear interpolation of texels a, b at t.+static float interpolatedMedian(const float *a, const float *b, double t) {+ return median(+ mix(a[0], b[0], t),+ mix(a[1], b[1], t),+ mix(a[2], b[2], t)+ );+}+/// Returns the median of the bilinear interpolation with the given constant, linear, and quadratic terms at t.+static float interpolatedMedian(const float *a, const float *l, const float *q, double t) {+ return float(median(+ t*(t*q[0]+l[0])+a[0],+ t*(t*q[1]+l[1])+a[1],+ t*(t*q[2]+l[2])+a[2]+ ));+}++/// Checks if a linear interpolation artifact will occur at a point where two specific color channels are equal - such points have extreme median values.+template <class ArtifactClassifier>+static bool hasLinearArtifactInner(const ArtifactClassifier &artifactClassifier, float am, float bm, const float *a, const float *b, float dA, float dB) {+ // Find interpolation ratio t (0 < t < 1) where two color channels are equal (mix(dA, dB, t) == 0).+ double t = (double) dA/(dA-dB);+ if (t > ARTIFACT_T_EPSILON && t < 1-ARTIFACT_T_EPSILON) {+ // Interpolate median at t and let the classifier decide if its value indicates an artifact.+ float xm = interpolatedMedian(a, b, t);+ return artifactClassifier.evaluate(t, xm, artifactClassifier.rangeTest(0, 1, t, am, bm, xm));+ }+ return false;+}++/// Checks if a bilinear interpolation artifact will occur at a point where two specific color channels are equal - such points have extreme median values.+template <class ArtifactClassifier>+static bool hasDiagonalArtifactInner(const ArtifactClassifier &artifactClassifier, float am, float dm, const float *a, const float *l, const float *q, float dA, float dBC, float dD, double tEx0, double tEx1) {+ // Find interpolation ratios t (0 < t[i] < 1) where two color channels are equal.+ double t[2];+ int solutions = solveQuadratic(t, dD-dBC+dA, dBC-dA-dA, dA);+ for (int i = 0; i < solutions; ++i) {+ // Solutions t[i] == 0 and t[i] == 1 are singularities and occur very often because two channels are usually equal at texels.+ if (t[i] > ARTIFACT_T_EPSILON && t[i] < 1-ARTIFACT_T_EPSILON) {+ // Interpolate median xm at t.+ float xm = interpolatedMedian(a, l, q, t[i]);+ // Determine if xm deviates too much from medians of a, d.+ int rangeFlags = artifactClassifier.rangeTest(0, 1, t[i], am, dm, xm);+ // Additionally, check xm against the interpolated medians at the local extremes tEx0, tEx1.+ double tEnd[2];+ float em[2];+ // tEx0+ if (tEx0 > 0 && tEx0 < 1) {+ tEnd[0] = 0, tEnd[1] = 1;+ em[0] = am, em[1] = dm;+ tEnd[tEx0 > t[i]] = tEx0;+ em[tEx0 > t[i]] = interpolatedMedian(a, l, q, tEx0);+ rangeFlags |= artifactClassifier.rangeTest(tEnd[0], tEnd[1], t[i], em[0], em[1], xm);+ }+ // tEx1+ if (tEx1 > 0 && tEx1 < 1) {+ tEnd[0] = 0, tEnd[1] = 1;+ em[0] = am, em[1] = dm;+ tEnd[tEx1 > t[i]] = tEx1;+ em[tEx1 > t[i]] = interpolatedMedian(a, l, q, tEx1);+ rangeFlags |= artifactClassifier.rangeTest(tEnd[0], tEnd[1], t[i], em[0], em[1], xm);+ }+ if (artifactClassifier.evaluate(t[i], xm, rangeFlags))+ return true;+ }+ }+ return false;+}++/// Checks if a linear interpolation artifact will occur inbetween two horizontally or vertically adjacent texels a, b.+template <class ArtifactClassifier>+static bool hasLinearArtifact(const ArtifactClassifier &artifactClassifier, float am, const float *a, const float *b) {+ float bm = median(b[0], b[1], b[2]);+ return (+ // Out of the pair, only report artifacts for the texel further from the edge to minimize side effects.+ fabsf(am-.5f) >= fabsf(bm-.5f) && (+ // Check points where each pair of color channels meets.+ hasLinearArtifactInner(artifactClassifier, am, bm, a, b, a[1]-a[0], b[1]-b[0]) ||+ hasLinearArtifactInner(artifactClassifier, am, bm, a, b, a[2]-a[1], b[2]-b[1]) ||+ hasLinearArtifactInner(artifactClassifier, am, bm, a, b, a[0]-a[2], b[0]-b[2])+ )+ );+}++/// Checks if a bilinear interpolation artifact will occur inbetween two diagonally adjacent texels a, d (with b, c forming the other diagonal).+template <class ArtifactClassifier>+static bool hasDiagonalArtifact(const ArtifactClassifier &artifactClassifier, float am, const float *a, const float *b, const float *c, const float *d) {+ float dm = median(d[0], d[1], d[2]);+ // Out of the pair, only report artifacts for the texel further from the edge to minimize side effects.+ if (fabsf(am-.5f) >= fabsf(dm-.5f)) {+ float abc[3] = {+ a[0]-b[0]-c[0],+ a[1]-b[1]-c[1],+ a[2]-b[2]-c[2]+ };+ // Compute the linear terms for bilinear interpolation.+ float l[3] = {+ -a[0]-abc[0],+ -a[1]-abc[1],+ -a[2]-abc[2]+ };+ // Compute the quadratic terms for bilinear interpolation.+ float q[3] = {+ d[0]+abc[0],+ d[1]+abc[1],+ d[2]+abc[2]+ };+ // Compute interpolation ratios tEx (0 < tEx[i] < 1) for the local extremes of each color channel (the derivative 2*q[i]*tEx[i]+l[i] == 0).+ double tEx[3] = {+ -.5*l[0]/q[0],+ -.5*l[1]/q[1],+ -.5*l[2]/q[2]+ };+ // Check points where each pair of color channels meets.+ return (+ hasDiagonalArtifactInner(artifactClassifier, am, dm, a, l, q, a[1]-a[0], b[1]-b[0]+c[1]-c[0], d[1]-d[0], tEx[0], tEx[1]) ||+ hasDiagonalArtifactInner(artifactClassifier, am, dm, a, l, q, a[2]-a[1], b[2]-b[1]+c[2]-c[1], d[2]-d[1], tEx[1], tEx[2]) ||+ hasDiagonalArtifactInner(artifactClassifier, am, dm, a, l, q, a[0]-a[2], b[0]-b[2]+c[0]-c[2], d[0]-d[2], tEx[2], tEx[0])+ );+ }+ return false;+}++template <int N>+void MSDFErrorCorrection::findErrors(const BitmapConstSection<float, N> &sdf) {+ stencil.reorient(sdf.yOrientation);+ // Compute the expected deltas between values of horizontally, vertically, and diagonally adjacent texels.+ double hSpan = minDeviationRatio*transformation.unprojectVector(Vector2(transformation.distanceMapping(DistanceMapping::Delta(1)), 0)).length();+ double vSpan = minDeviationRatio*transformation.unprojectVector(Vector2(0, transformation.distanceMapping(DistanceMapping::Delta(1)))).length();+ double dSpan = minDeviationRatio*transformation.unprojectVector(Vector2(transformation.distanceMapping(DistanceMapping::Delta(1)))).length();+ // Inspect all texels.+ for (int y = 0; y < sdf.height; ++y) {+ for (int x = 0; x < sdf.width; ++x) {+ const float *c = sdf(x, y);+ float cm = median(c[0], c[1], c[2]);+ bool protectedFlag = (*stencil(x, y)&PROTECTED) != 0;+ const float *l = NULL, *b = NULL, *r = NULL, *t = NULL;+ // Mark current texel c with the error flag if an artifact occurs when it's interpolated with any of its 8 neighbors.+ *stencil(x, y) |= (byte) (ERROR*(+ (x > 0 && ((l = sdf(x-1, y)), hasLinearArtifact(BaseArtifactClassifier(hSpan, protectedFlag), cm, c, l))) ||+ (y > 0 && ((b = sdf(x, y-1)), hasLinearArtifact(BaseArtifactClassifier(vSpan, protectedFlag), cm, c, b))) ||+ (x < sdf.width-1 && ((r = sdf(x+1, y)), hasLinearArtifact(BaseArtifactClassifier(hSpan, protectedFlag), cm, c, r))) ||+ (y < sdf.height-1 && ((t = sdf(x, y+1)), hasLinearArtifact(BaseArtifactClassifier(vSpan, protectedFlag), cm, c, t))) ||+ (x > 0 && y > 0 && hasDiagonalArtifact(BaseArtifactClassifier(dSpan, protectedFlag), cm, c, l, b, sdf(x-1, y-1))) ||+ (x < sdf.width-1 && y > 0 && hasDiagonalArtifact(BaseArtifactClassifier(dSpan, protectedFlag), cm, c, r, b, sdf(x+1, y-1))) ||+ (x > 0 && y < sdf.height-1 && hasDiagonalArtifact(BaseArtifactClassifier(dSpan, protectedFlag), cm, c, l, t, sdf(x-1, y+1))) ||+ (x < sdf.width-1 && y < sdf.height-1 && hasDiagonalArtifact(BaseArtifactClassifier(dSpan, protectedFlag), cm, c, r, t, sdf(x+1, y+1)))+ ));+ }+ }+}++template <template <typename> class ContourCombiner, int N>+void MSDFErrorCorrection::findErrors(BitmapConstSection<float, N> sdf, const Shape &shape) {+ sdf.reorient(shape.getYAxisOrientation());+ stencil.reorient(sdf.yOrientation);+ // Compute the expected deltas between values of horizontally, vertically, and diagonally adjacent texels.+ double hSpan = minDeviationRatio*transformation.unprojectVector(Vector2(transformation.distanceMapping(DistanceMapping::Delta(1)), 0)).length();+ double vSpan = minDeviationRatio*transformation.unprojectVector(Vector2(0, transformation.distanceMapping(DistanceMapping::Delta(1)))).length();+ double dSpan = minDeviationRatio*transformation.unprojectVector(Vector2(transformation.distanceMapping(DistanceMapping::Delta(1)))).length();+#ifdef MSDFGEN_USE_OPENMP+ #pragma omp parallel+#endif+ {+ ShapeDistanceChecker<ContourCombiner, N> shapeDistanceChecker(sdf, shape, transformation, transformation.distanceMapping, minImproveRatio);+ int xDirection = 1;+ // Inspect all texels.+#ifdef MSDFGEN_USE_OPENMP+ #pragma omp for+#endif+ for (int y = 0; y < sdf.height; ++y) {+ int x = xDirection < 0 ? sdf.width-1 : 0;+ for (int col = 0; col < sdf.width; ++col, x += xDirection) {+ if ((*stencil(x, y)&ERROR))+ continue;+ const float *c = sdf(x, y);+ shapeDistanceChecker.shapeCoord = transformation.unproject(Point2(x+.5, y+.5));+ shapeDistanceChecker.sdfCoord = Point2(x+.5, y+.5);+ shapeDistanceChecker.msd = c;+ shapeDistanceChecker.protectedFlag = (*stencil(x, y)&PROTECTED) != 0;+ float cm = median(c[0], c[1], c[2]);+ const float *l = NULL, *b = NULL, *r = NULL, *t = NULL;+ // Mark current texel c with the error flag if an artifact occurs when it's interpolated with any of its 8 neighbors.+ *stencil(x, y) |= (byte) (ERROR*(+ (x > 0 && ((l = sdf(x-1, y)), hasLinearArtifact(shapeDistanceChecker.classifier(Vector2(-1, 0), hSpan), cm, c, l))) ||+ (y > 0 && ((b = sdf(x, y-1)), hasLinearArtifact(shapeDistanceChecker.classifier(Vector2(0, -1), vSpan), cm, c, b))) ||+ (x < sdf.width-1 && ((r = sdf(x+1, y)), hasLinearArtifact(shapeDistanceChecker.classifier(Vector2(+1, 0), hSpan), cm, c, r))) ||+ (y < sdf.height-1 && ((t = sdf(x, y+1)), hasLinearArtifact(shapeDistanceChecker.classifier(Vector2(0, +1), vSpan), cm, c, t))) ||+ (x > 0 && y > 0 && hasDiagonalArtifact(shapeDistanceChecker.classifier(Vector2(-1, -1), dSpan), cm, c, l, b, sdf(x-1, y-1))) ||+ (x < sdf.width-1 && y > 0 && hasDiagonalArtifact(shapeDistanceChecker.classifier(Vector2(+1, -1), dSpan), cm, c, r, b, sdf(x+1, y-1))) ||+ (x > 0 && y < sdf.height-1 && hasDiagonalArtifact(shapeDistanceChecker.classifier(Vector2(-1, +1), dSpan), cm, c, l, t, sdf(x-1, y+1))) ||+ (x < sdf.width-1 && y < sdf.height-1 && hasDiagonalArtifact(shapeDistanceChecker.classifier(Vector2(+1, +1), dSpan), cm, c, r, t, sdf(x+1, y+1)))+ ));+ }+ xDirection = -xDirection;+ }+ }+}++template <int N>+void MSDFErrorCorrection::apply(BitmapSection<float, N> sdf) const {+ sdf.reorient(stencil.yOrientation);+ const byte *stencilRow = stencil.pixels;+ float *rowStart = sdf.pixels;+ for (int y = 0; y < sdf.height; ++y) {+ const byte *mask = stencilRow;+ float *pixel = rowStart;+ for (int x = 0; x < sdf.width; ++x) {+ if (*mask&ERROR) {+ // Set all color channels to the median.+ float m = median(pixel[0], pixel[1], pixel[2]);+ pixel[0] = m, pixel[1] = m, pixel[2] = m;+ }+ ++mask;+ pixel += N;+ }+ stencilRow += stencil.rowStride;+ rowStart += sdf.rowStride;+ }+}++BitmapConstSection<byte, 1> MSDFErrorCorrection::getStencil() const {+ return stencil;+}++template void MSDFErrorCorrection::protectEdges(const BitmapConstSection<float, 3> &sdf);+template void MSDFErrorCorrection::protectEdges(const BitmapConstSection<float, 4> &sdf);+template void MSDFErrorCorrection::findErrors(const BitmapConstSection<float, 3> &sdf);+template void MSDFErrorCorrection::findErrors(const BitmapConstSection<float, 4> &sdf);+template void MSDFErrorCorrection::findErrors<SimpleContourCombiner>(BitmapConstSection<float, 3> sdf, const Shape &shape);+template void MSDFErrorCorrection::findErrors<SimpleContourCombiner>(BitmapConstSection<float, 4> sdf, const Shape &shape);+template void MSDFErrorCorrection::findErrors<OverlappingContourCombiner>(BitmapConstSection<float, 3> sdf, const Shape &shape);+template void MSDFErrorCorrection::findErrors<OverlappingContourCombiner>(BitmapConstSection<float, 4> sdf, const Shape &shape);+template void MSDFErrorCorrection::apply(BitmapSection<float, 3> sdf) const;+template void MSDFErrorCorrection::apply(BitmapSection<float, 4> sdf) const;++}diff --git a/third_party/msdfgen/core/MSDFErrorCorrection.h b/third_party/msdfgen/core/MSDFErrorCorrection.hnew file mode 100644index 000000000..995b1d614--- /dev/null+++ b/third_party/msdfgen/core/MSDFErrorCorrection.h@@ -0,0 +1,55 @@++#pragma once++#include "SDFTransformation.h"+#include "Shape.h"+#include "BitmapRef.hpp"++namespace msdfgen {++/// Performs error correction on a computed MSDF to eliminate interpolation artifacts. This is a low-level class, you may want to use the API in msdf-error-correction.h instead.+class MSDFErrorCorrection {++public:+ /// Stencil flags.+ enum Flags {+ /// Texel marked as potentially causing interpolation errors.+ ERROR = 1,+ /// Texel marked as protected. Protected texels are only given the error flag if they cause inversion artifacts.+ PROTECTED = 2+ };++ MSDFErrorCorrection();+ explicit MSDFErrorCorrection(const BitmapSection<byte, 1> &stencil, const SDFTransformation &transformation);+ /// Sets the minimum ratio between the actual and maximum expected distance delta to be considered an error.+ void setMinDeviationRatio(double minDeviationRatio);+ /// Sets the minimum ratio between the pre-correction distance error and the post-correction distance error.+ void setMinImproveRatio(double minImproveRatio);+ /// Flags all texels that are interpolated at corners as protected.+ void protectCorners(const Shape &shape);+ /// Flags all texels that contribute to edges as protected.+ template <int N>+ void protectEdges(const BitmapConstSection<float, N> &sdf);+ /// Flags all texels as protected.+ void protectAll();+ /// Flags texels that are expected to cause interpolation artifacts based on analysis of the SDF only.+ template <int N>+ void findErrors(const BitmapConstSection<float, N> &sdf);+ /// Flags texels that are expected to cause interpolation artifacts based on analysis of the SDF and comparison with the exact shape distance.+ template <template <typename> class ContourCombiner, int N>+ void findErrors(BitmapConstSection<float, N> sdf, const Shape &shape);+ /// Modifies the MSDF so that all texels with the error flag are converted to single-channel.+ template <int N>+ void apply(BitmapSection<float, N> sdf) const;+ /// Returns the stencil in its current state (see Flags).+ BitmapConstSection<byte, 1> getStencil() const;++private:+ BitmapSection<byte, 1> stencil;+ SDFTransformation transformation;+ double minDeviationRatio;+ double minImproveRatio;++};++}diff --git a/third_party/msdfgen/core/Projection.cpp b/third_party/msdfgen/core/Projection.cppnew file mode 100644index 000000000..fa2f5e259--- /dev/null+++ b/third_party/msdfgen/core/Projection.cpp@@ -0,0 +1,42 @@++#include "Projection.h"++namespace msdfgen {++Projection::Projection() : scale(1), translate(0) { }++Projection::Projection(const Vector2 &scale, const Vector2 &translate) : scale(scale), translate(translate) { }++Point2 Projection::project(const Point2 &coord) const {+ return scale*(coord+translate);+}++Point2 Projection::unproject(const Point2 &coord) const {+ return coord/scale-translate;+}++Vector2 Projection::projectVector(const Vector2 &vector) const {+ return scale*vector;+}++Vector2 Projection::unprojectVector(const Vector2 &vector) const {+ return vector/scale;+}++double Projection::projectX(double x) const {+ return scale.x*(x+translate.x);+}++double Projection::projectY(double y) const {+ return scale.y*(y+translate.y);+}++double Projection::unprojectX(double x) const {+ return x/scale.x-translate.x;+}++double Projection::unprojectY(double y) const {+ return y/scale.y-translate.y;+}++}diff --git a/third_party/msdfgen/core/Projection.h b/third_party/msdfgen/core/Projection.hnew file mode 100644index 000000000..3c457776a--- /dev/null+++ b/third_party/msdfgen/core/Projection.h@@ -0,0 +1,37 @@++#pragma once++#include "Vector2.hpp"++namespace msdfgen {++/// A transformation from shape coordinates to pixel coordinates.+class Projection {++public:+ Projection();+ Projection(const Vector2 &scale, const Vector2 &translate);+ /// Converts the shape coordinate to pixel coordinate.+ Point2 project(const Point2 &coord) const;+ /// Converts the pixel coordinate to shape coordinate.+ Point2 unproject(const Point2 &coord) const;+ /// Converts the vector to pixel coordinate space.+ Vector2 projectVector(const Vector2 &vector) const;+ /// Converts the vector from pixel coordinate space.+ Vector2 unprojectVector(const Vector2 &vector) const;+ /// Converts the X-coordinate from shape to pixel coordinate space.+ double projectX(double x) const;+ /// Converts the Y-coordinate from shape to pixel coordinate space.+ double projectY(double y) const;+ /// Converts the X-coordinate from pixel to shape coordinate space.+ double unprojectX(double x) const;+ /// Converts the Y-coordinate from pixel to shape coordinate space.+ double unprojectY(double y) const;++private:+ Vector2 scale;+ Vector2 translate;++};++}diff --git a/third_party/msdfgen/core/Range.hpp b/third_party/msdfgen/core/Range.hppnew file mode 100644index 000000000..e145647b1--- /dev/null+++ b/third_party/msdfgen/core/Range.hpp@@ -0,0 +1,46 @@++#pragma once++#include "base.h"++namespace msdfgen {++/**+ * Represents the range between two real values.+ * For example, the range of representable signed distances.+ */+struct Range {++ double lower, upper;++ inline Range(double symmetricalWidth = 0) : lower(-.5*symmetricalWidth), upper(.5*symmetricalWidth) { }++ inline Range(double lowerBound, double upperBound) : lower(lowerBound), upper(upperBound) { }++ inline Range &operator*=(double factor) {+ lower *= factor;+ upper *= factor;+ return *this;+ }++ inline Range &operator/=(double divisor) {+ lower /= divisor;+ upper /= divisor;+ return *this;+ }++ inline Range operator*(double factor) const {+ return Range(lower*factor, upper*factor);+ }++ inline Range operator/(double divisor) const {+ return Range(lower/divisor, upper/divisor);+ }++};++inline Range operator*(double factor, const Range &range) {+ return Range(factor*range.lower, factor*range.upper);+}++}diff --git a/third_party/msdfgen/core/SDFTransformation.h b/third_party/msdfgen/core/SDFTransformation.hnew file mode 100644index 000000000..b056414f5--- /dev/null+++ b/third_party/msdfgen/core/SDFTransformation.h@@ -0,0 +1,24 @@++#pragma once++#include "Projection.h"+#include "DistanceMapping.h"++namespace msdfgen {++/**+ * Full signed distance field transformation specifies both spatial transformation (Projection)+ * as well as distance value transformation (DistanceMapping).+ */+class SDFTransformation : public Projection {++public:+ DistanceMapping distanceMapping;++ inline SDFTransformation() { }++ inline SDFTransformation(const Projection &projection, const DistanceMapping &distanceMapping) : Projection(projection), distanceMapping(distanceMapping) { }++};++}diff --git a/third_party/msdfgen/core/Scanline.cpp b/third_party/msdfgen/core/Scanline.cppnew file mode 100644index 000000000..7407be41b--- /dev/null+++ b/third_party/msdfgen/core/Scanline.cpp@@ -0,0 +1,125 @@++#include "Scanline.h"++#include <cstdlib>+#include "arithmetics.hpp"++namespace msdfgen {++static int compareIntersections(const void *a, const void *b) {+ return sign(reinterpret_cast<const Scanline::Intersection *>(a)->x-reinterpret_cast<const Scanline::Intersection *>(b)->x);+}++bool interpretFillRule(int intersections, FillRule fillRule) {+ switch (fillRule) {+ case FILL_NONZERO:+ return intersections != 0;+ case FILL_ODD:+ return intersections&1;+ case FILL_POSITIVE:+ return intersections > 0;+ case FILL_NEGATIVE:+ return intersections < 0;+ }+ return false;+}++double Scanline::overlap(const Scanline &a, const Scanline &b, double xFrom, double xTo, FillRule fillRule) {+ double total = 0;+ bool aInside = false, bInside = false;+ int ai = 0, bi = 0;+ double ax = !a.intersections.empty() ? a.intersections[ai].x : xTo;+ double bx = !b.intersections.empty() ? b.intersections[bi].x : xTo;+ while (ax < xFrom || bx < xFrom) {+ double xNext = min(ax, bx);+ if (ax == xNext && ai < (int) a.intersections.size()) {+ aInside = interpretFillRule(a.intersections[ai].direction, fillRule);+ ax = ++ai < (int) a.intersections.size() ? a.intersections[ai].x : xTo;+ }+ if (bx == xNext && bi < (int) b.intersections.size()) {+ bInside = interpretFillRule(b.intersections[bi].direction, fillRule);+ bx = ++bi < (int) b.intersections.size() ? b.intersections[bi].x : xTo;+ }+ }+ double x = xFrom;+ while (ax < xTo || bx < xTo) {+ double xNext = min(ax, bx);+ if (aInside == bInside)+ total += xNext-x;+ if (ax == xNext && ai < (int) a.intersections.size()) {+ aInside = interpretFillRule(a.intersections[ai].direction, fillRule);+ ax = ++ai < (int) a.intersections.size() ? a.intersections[ai].x : xTo;+ }+ if (bx == xNext && bi < (int) b.intersections.size()) {+ bInside = interpretFillRule(b.intersections[bi].direction, fillRule);+ bx = ++bi < (int) b.intersections.size() ? b.intersections[bi].x : xTo;+ }+ x = xNext;+ }+ if (aInside == bInside)+ total += xTo-x;+ return total;+}++Scanline::Scanline() : lastIndex(0) { }++void Scanline::preprocess() {+ lastIndex = 0;+ if (!intersections.empty()) {+ qsort(&intersections[0], intersections.size(), sizeof(Intersection), compareIntersections);+ int totalDirection = 0;+ for (std::vector<Intersection>::iterator intersection = intersections.begin(); intersection != intersections.end(); ++intersection) {+ totalDirection += intersection->direction;+ intersection->direction = totalDirection;+ }+ }+}++void Scanline::setIntersections(const std::vector<Intersection> &intersections) {+ this->intersections = intersections;+ preprocess();+}++#ifdef MSDFGEN_USE_CPP11+void Scanline::setIntersections(std::vector<Intersection> &&intersections) {+ this->intersections = (std::vector<Intersection> &&) intersections;+ preprocess();+}+#endif++int Scanline::moveTo(double x) const {+ if (intersections.empty())+ return -1;+ int index = lastIndex;+ if (x < intersections[index].x) {+ do {+ if (index == 0) {+ lastIndex = 0;+ return -1;+ }+ --index;+ } while (x < intersections[index].x);+ } else {+ while (index < (int) intersections.size()-1 && x >= intersections[index+1].x)+ ++index;+ }+ lastIndex = index;+ return index;+}++int Scanline::countIntersections(double x) const {+ return moveTo(x)+1;+}++int Scanline::sumIntersections(double x) const {+ int index = moveTo(x);+ if (index >= 0)+ return intersections[index].direction;+ return 0;+}++bool Scanline::filled(double x, FillRule fillRule) const {+ return interpretFillRule(sumIntersections(x), fillRule);+}++}diff --git a/third_party/msdfgen/core/Scanline.h b/third_party/msdfgen/core/Scanline.hnew file mode 100644index 000000000..c0abc6864--- /dev/null+++ b/third_party/msdfgen/core/Scanline.h@@ -0,0 +1,56 @@++#pragma once++#include <vector>+#include "base.h"++namespace msdfgen {++/// Fill rule dictates how intersection total is interpreted during rasterization.+enum FillRule {+ FILL_NONZERO,+ FILL_ODD, // "even-odd"+ FILL_POSITIVE,+ FILL_NEGATIVE+};++/// Resolves the number of intersection into a binary fill value based on fill rule.+bool interpretFillRule(int intersections, FillRule fillRule);++/// Represents a horizontal scanline intersecting a shape.+class Scanline {++public:+ /// An intersection with the scanline.+ struct Intersection {+ /// X coordinate.+ double x;+ /// Normalized Y direction of the oriented edge at the point of intersection.+ int direction;+ };++ static double overlap(const Scanline &a, const Scanline &b, double xFrom, double xTo, FillRule fillRule);++ Scanline();+ /// Populates the intersection list.+ void setIntersections(const std::vector<Intersection> &intersections);+#ifdef MSDFGEN_USE_CPP11+ void setIntersections(std::vector<Intersection> &&intersections);+#endif+ /// Returns the number of intersections left of x.+ int countIntersections(double x) const;+ /// Returns the total sign of intersections left of x.+ int sumIntersections(double x) const;+ /// Decides whether the scanline is filled at x based on fill rule.+ bool filled(double x, FillRule fillRule) const;++private:+ std::vector<Intersection> intersections;+ mutable int lastIndex;++ void preprocess();+ int moveTo(double x) const;++};++}diff --git a/third_party/msdfgen/core/Shape.cpp b/third_party/msdfgen/core/Shape.cppnew file mode 100644index 000000000..504d706de--- /dev/null+++ b/third_party/msdfgen/core/Shape.cpp@@ -0,0 +1,208 @@++#include "Shape.h"++#include <cstdlib>+#include "arithmetics.hpp"+#include "convergent-curve-ordering.h"++#define DECONVERGE_OVERSHOOT 1.11111111111111111 // moves control points slightly more than necessary to account for floating-point errors++namespace msdfgen {++Shape::Shape() : inverseYAxis(false) { }++void Shape::addContour(const Contour &contour) {+ contours.push_back(contour);+}++#ifdef MSDFGEN_USE_CPP11+void Shape::addContour(Contour &&contour) {+ contours.push_back((Contour &&) contour);+}+#endif++Contour &Shape::addContour() {+ contours.resize(contours.size()+1);+ return contours.back();+}++bool Shape::validate() const {+ for (std::vector<Contour>::const_iterator contour = contours.begin(); contour != contours.end(); ++contour) {+ if (!contour->edges.empty()) {+ Point2 corner = contour->edges.back()->point(1);+ for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {+ if (!*edge)+ return false;+ if ((*edge)->point(0) != corner)+ return false;+ corner = (*edge)->point(1);+ }+ }+ }+ return true;+}++static void deconvergeEdge(EdgeHolder &edgeHolder, int param, Vector2 vector) {+ switch (edgeHolder->type()) {+ case (int) QuadraticSegment::EDGE_TYPE:+ edgeHolder = static_cast<const QuadraticSegment *>(&*edgeHolder)->convertToCubic();+ // fallthrough+ case (int) CubicSegment::EDGE_TYPE:+ {+ Point2 *p = static_cast<CubicSegment *>(&*edgeHolder)->p;+ switch (param) {+ case 0:+ p[1] += (p[1]-p[0]).length()*vector;+ break;+ case 1:+ p[2] += (p[2]-p[3]).length()*vector;+ break;+ }+ }+ }+}++void Shape::normalize() {+ for (std::vector<Contour>::iterator contour = contours.begin(); contour != contours.end(); ++contour) {+ if (contour->edges.size() == 1) {+ EdgeSegment *parts[3] = { };+ contour->edges[0]->splitInThirds(parts[0], parts[1], parts[2]);+ contour->edges.clear();+ contour->edges.push_back(EdgeHolder(parts[0]));+ contour->edges.push_back(EdgeHolder(parts[1]));+ contour->edges.push_back(EdgeHolder(parts[2]));+ } else if (!contour->edges.empty()) {+ // Push apart convergent edge segments+ EdgeHolder *prevEdge = &contour->edges.back();+ for (std::vector<EdgeHolder>::iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {+ Vector2 prevDir = (*prevEdge)->direction(1).normalize();+ Vector2 curDir = (*edge)->direction(0).normalize();+ if (dotProduct(prevDir, curDir) < MSDFGEN_CORNER_DOT_EPSILON-1) {+ double factor = DECONVERGE_OVERSHOOT*sqrt(1-(MSDFGEN_CORNER_DOT_EPSILON-1)*(MSDFGEN_CORNER_DOT_EPSILON-1))/(MSDFGEN_CORNER_DOT_EPSILON-1);+ Vector2 axis = factor*(curDir-prevDir).normalize();+ if (convergentCurveOrdering(*prevEdge, *edge) < 0)+ axis = -axis;+ deconvergeEdge(*prevEdge, 1, axis.getOrthogonal(true));+ deconvergeEdge(*edge, 0, axis.getOrthogonal(false));+ }+ prevEdge = &*edge;+ }+ }+ }+}++void Shape::bound(double &xMin, double &yMin, double &xMax, double &yMax) const {+ for (std::vector<Contour>::const_iterator contour = contours.begin(); contour != contours.end(); ++contour)+ contour->bound(xMin, yMin, xMax, yMax);+}++void Shape::boundMiters(double &xMin, double &yMin, double &xMax, double &yMax, double border, double miterLimit, int polarity) const {+ for (std::vector<Contour>::const_iterator contour = contours.begin(); contour != contours.end(); ++contour)+ contour->boundMiters(xMin, yMin, xMax, yMax, border, miterLimit, polarity);+}++Shape::Bounds Shape::getBounds(double border, double miterLimit, int polarity) const {+ static const double LARGE_VALUE = 1e240;+ Shape::Bounds bounds = { +LARGE_VALUE, +LARGE_VALUE, -LARGE_VALUE, -LARGE_VALUE };+ bound(bounds.l, bounds.b, bounds.r, bounds.t);+ if (border > 0) {+ bounds.l -= border, bounds.b -= border;+ bounds.r += border, bounds.t += border;+ if (miterLimit > 0)+ boundMiters(bounds.l, bounds.b, bounds.r, bounds.t, border, miterLimit, polarity);+ }+ return bounds;+}++void Shape::scanline(Scanline &line, double y) const {+ std::vector<Scanline::Intersection> intersections;+ double x[3];+ int dy[3];+ for (std::vector<Contour>::const_iterator contour = contours.begin(); contour != contours.end(); ++contour) {+ for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {+ int n = (*edge)->scanlineIntersections(x, dy, y);+ for (int i = 0; i < n; ++i) {+ Scanline::Intersection intersection = { x[i], dy[i] };+ intersections.push_back(intersection);+ }+ }+ }+#ifdef MSDFGEN_USE_CPP11+ line.setIntersections((std::vector<Scanline::Intersection> &&) intersections);+#else+ line.setIntersections(intersections);+#endif+}++int Shape::edgeCount() const {+ int total = 0;+ for (std::vector<Contour>::const_iterator contour = contours.begin(); contour != contours.end(); ++contour)+ total += (int) contour->edges.size();+ return total;+}++void Shape::orientContours() {+ struct Intersection {+ double x;+ int direction;+ int contourIndex;++ static int compare(const void *a, const void *b) {+ return sign(reinterpret_cast<const Intersection *>(a)->x-reinterpret_cast<const Intersection *>(b)->x);+ }+ };++ const double ratio = .5*(sqrt(5)-1); // an irrational number to minimize chance of intersecting a corner or other point of interest+ std::vector<int> orientations(contours.size());+ std::vector<Intersection> intersections;+ for (int i = 0; i < (int) contours.size(); ++i) {+ if (!orientations[i] && !contours[i].edges.empty()) {+ // Find an Y that crosses the contour+ double y0 = contours[i].edges.front()->point(0).y;+ double y1 = y0;+ for (std::vector<EdgeHolder>::const_iterator edge = contours[i].edges.begin(); edge != contours[i].edges.end() && y0 == y1; ++edge)+ y1 = (*edge)->point(1).y;+ for (std::vector<EdgeHolder>::const_iterator edge = contours[i].edges.begin(); edge != contours[i].edges.end() && y0 == y1; ++edge)+ y1 = (*edge)->point(ratio).y; // in case all endpoints are in a horizontal line+ double y = mix(y0, y1, ratio);+ // Scanline through whole shape at Y+ double x[3];+ int dy[3];+ for (int j = 0; j < (int) contours.size(); ++j) {+ for (std::vector<EdgeHolder>::const_iterator edge = contours[j].edges.begin(); edge != contours[j].edges.end(); ++edge) {+ int n = (*edge)->scanlineIntersections(x, dy, y);+ for (int k = 0; k < n; ++k) {+ Intersection intersection = { x[k], dy[k], j };+ intersections.push_back(intersection);+ }+ }+ }+ if (!intersections.empty()) {+ qsort(&intersections[0], intersections.size(), sizeof(Intersection), &Intersection::compare);+ // Disqualify multiple intersections+ for (int j = 1; j < (int) intersections.size(); ++j)+ if (intersections[j].x == intersections[j-1].x)+ intersections[j].direction = intersections[j-1].direction = 0;+ // Inspect scanline and deduce orientations of intersected contours+ for (int j = 0; j < (int) intersections.size(); ++j)+ if (intersections[j].direction)+ orientations[intersections[j].contourIndex] += 2*((j&1)^(intersections[j].direction > 0))-1;+ intersections.clear();+ }+ }+ }+ // Reverse contours that have the opposite orientation+ for (int i = 0; i < (int) contours.size(); ++i)+ if (orientations[i] < 0)+ contours[i].reverse();+}++YAxisOrientation Shape::getYAxisOrientation() const {+ return inverseYAxis ? MSDFGEN_Y_AXIS_NONDEFAULT_ORIENTATION : MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION;+}++void Shape::setYAxisOrientation(YAxisOrientation yAxisOrientation) {+ inverseYAxis = yAxisOrientation != MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION;+}++}diff --git a/third_party/msdfgen/core/Shape.h b/third_party/msdfgen/core/Shape.hnew file mode 100644index 000000000..d47b43ac1--- /dev/null+++ b/third_party/msdfgen/core/Shape.h@@ -0,0 +1,60 @@++#pragma once++#include <vector>+#include "Contour.h"+#include "YAxisOrientation.h"+#include "Scanline.h"++namespace msdfgen {++// Threshold of the dot product of adjacent edge directions to be considered convergent.+#define MSDFGEN_CORNER_DOT_EPSILON .000001++/// Vector shape representation.+class Shape {++public:+ struct Bounds {+ // NOTE: b is actually the lower Y-coordinate and t the higher Y-coordinate. For Y_DOWNWARD orientation, b is actually the top and t the bottom. May be renamed in a future version.+ double l, b, r, t;+ };++ /// The list of contours the shape consists of.+ std::vector<Contour> contours;+ /// Specifies whether the shape uses bottom-to-top (false) or top-to-bottom (true) Y coordinates.+ /// DEPRECATED - use getYAxisOrientation / setYAxisOrientation instead.+ bool inverseYAxis;++ Shape();+ /// Adds a contour.+ void addContour(const Contour &contour);+#ifdef MSDFGEN_USE_CPP11+ void addContour(Contour &&contour);+#endif+ /// Adds a blank contour and returns its reference.+ Contour &addContour();+ /// Normalizes the shape geometry for distance field generation.+ void normalize();+ /// Performs basic checks to determine if the object represents a valid shape.+ bool validate() const;+ /// Adjusts the bounding box to fit the shape.+ void bound(double &xMin, double &yMin, double &xMax, double &yMax) const;+ /// Adjusts the bounding box to fit the shape border's mitered corners.+ void boundMiters(double &xMin, double &yMin, double &xMax, double &yMax, double border, double miterLimit, int polarity) const;+ /// Computes the minimum bounding box that fits the shape, optionally with a (mitered) border.+ Bounds getBounds(double border = 0, double miterLimit = 0, int polarity = 0) const;+ /// Outputs the scanline that intersects the shape at y.+ void scanline(Scanline &line, double y) const;+ /// Returns the total number of edge segments+ int edgeCount() const;+ /// Assumes its contours are unoriented (even-odd fill rule). Attempts to orient them to conform to the non-zero winding rule.+ void orientContours();+ /// Returns the orientation of the axis of the shape's Y coordinates.+ YAxisOrientation getYAxisOrientation() const;+ /// Sets the orientation of the axis of the shape's Y coordinates.+ void setYAxisOrientation(YAxisOrientation yAxisOrientation);++};++}diff --git a/third_party/msdfgen/core/ShapeDistanceFinder.h b/third_party/msdfgen/core/ShapeDistanceFinder.hnew file mode 100644index 000000000..d8a584f64--- /dev/null+++ b/third_party/msdfgen/core/ShapeDistanceFinder.h@@ -0,0 +1,37 @@++#pragma once++#include <vector>+#include "Vector2.hpp"+#include "edge-selectors.h"+#include "contour-combiners.h"++namespace msdfgen {++/// Finds the distance between a point and a Shape. ContourCombiner dictates the distance metric and its data type.+template <class ContourCombiner>+class ShapeDistanceFinder {++public:+ typedef typename ContourCombiner::DistanceType DistanceType;++ // Passed shape object must persist until the distance finder is destroyed!+ explicit ShapeDistanceFinder(const Shape &shape);+ /// Finds the distance from origin. Not thread-safe! Is fastest when subsequent queries are close together.+ DistanceType distance(const Point2 &origin);++ /// Finds the distance between shape and origin. Does not allocate result cache used to optimize performance of multiple queries.+ static DistanceType oneShotDistance(const Shape &shape, const Point2 &origin);++private:+ const Shape &shape;+ ContourCombiner contourCombiner;+ std::vector<typename ContourCombiner::EdgeSelectorType::EdgeCache> shapeEdgeCache;++};++typedef ShapeDistanceFinder<SimpleContourCombiner<TrueDistanceSelector> > SimpleTrueShapeDistanceFinder;++}++#include "ShapeDistanceFinder.hpp"diff --git a/third_party/msdfgen/core/ShapeDistanceFinder.hpp b/third_party/msdfgen/core/ShapeDistanceFinder.hppnew file mode 100644index 000000000..07fb5cdc0--- /dev/null+++ b/third_party/msdfgen/core/ShapeDistanceFinder.hpp@@ -0,0 +1,60 @@++#include "ShapeDistanceFinder.h"++namespace msdfgen {++template <class ContourCombiner>+ShapeDistanceFinder<ContourCombiner>::ShapeDistanceFinder(const Shape &shape) : shape(shape), contourCombiner(shape), shapeEdgeCache(shape.edgeCount()) { }++template <class ContourCombiner>+typename ShapeDistanceFinder<ContourCombiner>::DistanceType ShapeDistanceFinder<ContourCombiner>::distance(const Point2 &origin) {+ contourCombiner.reset(origin);+#ifdef MSDFGEN_USE_CPP11+ typename ContourCombiner::EdgeSelectorType::EdgeCache *edgeCache = shapeEdgeCache.data();+#else+ typename ContourCombiner::EdgeSelectorType::EdgeCache *edgeCache = shapeEdgeCache.empty() ? NULL : &shapeEdgeCache[0];+#endif++ for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour) {+ if (!contour->edges.empty()) {+ typename ContourCombiner::EdgeSelectorType &edgeSelector = contourCombiner.edgeSelector(int(contour-shape.contours.begin()));++ const EdgeSegment *prevEdge = contour->edges.size() >= 2 ? *(contour->edges.end()-2) : *contour->edges.begin();+ const EdgeSegment *curEdge = contour->edges.back();+ for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {+ const EdgeSegment *nextEdge = *edge;+ edgeSelector.addEdge(*edgeCache++, prevEdge, curEdge, nextEdge);+ prevEdge = curEdge;+ curEdge = nextEdge;+ }+ }+ }++ return contourCombiner.distance();+}++template <class ContourCombiner>+typename ShapeDistanceFinder<ContourCombiner>::DistanceType ShapeDistanceFinder<ContourCombiner>::oneShotDistance(const Shape &shape, const Point2 &origin) {+ ContourCombiner contourCombiner(shape);+ contourCombiner.reset(origin);++ for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour) {+ if (!contour->edges.empty()) {+ typename ContourCombiner::EdgeSelectorType &edgeSelector = contourCombiner.edgeSelector(int(contour-shape.contours.begin()));++ const EdgeSegment *prevEdge = contour->edges.size() >= 2 ? *(contour->edges.end()-2) : *contour->edges.begin();+ const EdgeSegment *curEdge = contour->edges.back();+ for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {+ const EdgeSegment *nextEdge = *edge;+ typename ContourCombiner::EdgeSelectorType::EdgeCache dummy;+ edgeSelector.addEdge(dummy, prevEdge, curEdge, nextEdge);+ prevEdge = curEdge;+ curEdge = nextEdge;+ }+ }+ }++ return contourCombiner.distance();+}++}diff --git a/third_party/msdfgen/core/SignedDistance.hpp b/third_party/msdfgen/core/SignedDistance.hppnew file mode 100644index 000000000..62e73c03a--- /dev/null+++ b/third_party/msdfgen/core/SignedDistance.hpp@@ -0,0 +1,38 @@++#pragma once++#include <cmath>+#include <cfloat>+#include "base.h"++namespace msdfgen {++/// Represents a signed distance and alignment, which together can be compared to uniquely determine the closest edge segment.+class SignedDistance {++public:+ double distance;+ double dot;++ inline SignedDistance() : distance(-DBL_MAX), dot(0) { }+ inline SignedDistance(double dist, double d) : distance(dist), dot(d) { }++};++inline bool operator<(const SignedDistance a, const SignedDistance b) {+ return fabs(a.distance) < fabs(b.distance) || (fabs(a.distance) == fabs(b.distance) && a.dot < b.dot);+}++inline bool operator>(const SignedDistance a, const SignedDistance b) {+ return fabs(a.distance) > fabs(b.distance) || (fabs(a.distance) == fabs(b.distance) && a.dot > b.dot);+}++inline bool operator<=(const SignedDistance a, const SignedDistance b) {+ return fabs(a.distance) < fabs(b.distance) || (fabs(a.distance) == fabs(b.distance) && a.dot <= b.dot);+}++inline bool operator>=(const SignedDistance a, const SignedDistance b) {+ return fabs(a.distance) > fabs(b.distance) || (fabs(a.distance) == fabs(b.distance) && a.dot >= b.dot);+}++}diff --git a/third_party/msdfgen/core/Vector2.hpp b/third_party/msdfgen/core/Vector2.hppnew file mode 100644index 000000000..03759bcc1--- /dev/null+++ b/third_party/msdfgen/core/Vector2.hpp@@ -0,0 +1,167 @@++#pragma once++#include <cmath>+#include "base.h"++namespace msdfgen {++/**+ * A 2-dimensional euclidean floating-point vector.+ * @author Viktor Chlumsky+ */+struct Vector2 {++ double x, y;++ inline Vector2(double val = 0) : x(val), y(val) { }++ inline Vector2(double x, double y) : x(x), y(y) { }++ /// Sets the vector to zero.+ inline void reset() {+ x = 0, y = 0;+ }++ /// Sets individual elements of the vector.+ inline void set(double newX, double newY) {+ x = newX, y = newY;+ }++ /// Returns the vector's squared length.+ inline double squaredLength() const {+ return x*x+y*y;+ }++ /// Returns the vector's length.+ inline double length() const {+ return sqrt(x*x+y*y);+ }++ /// Returns the normalized vector - one that has the same direction but unit length.+ inline Vector2 normalize(bool allowZero = false) const {+ if (double len = length())+ return Vector2(x/len, y/len);+ return Vector2(0, !allowZero);+ }++ /// Returns a vector with the same length that is orthogonal to this one.+ inline Vector2 getOrthogonal(bool polarity = true) const {+ return polarity ? Vector2(-y, x) : Vector2(y, -x);+ }++ /// Returns a vector with unit length that is orthogonal to this one.+ inline Vector2 getOrthonormal(bool polarity = true, bool allowZero = false) const {+ if (double len = length())+ return polarity ? Vector2(-y/len, x/len) : Vector2(y/len, -x/len);+ return polarity ? Vector2(0, !allowZero) : Vector2(0, -!allowZero);+ }++#ifdef MSDFGEN_USE_CPP11+ inline explicit operator bool() const {+ return x || y;+ }+#else+ inline operator const void *() const {+ return x || y ? this : NULL;+ }+#endif++ inline Vector2 &operator+=(const Vector2 other) {+ x += other.x, y += other.y;+ return *this;+ }++ inline Vector2 &operator-=(const Vector2 other) {+ x -= other.x, y -= other.y;+ return *this;+ }++ inline Vector2 &operator*=(const Vector2 other) {+ x *= other.x, y *= other.y;+ return *this;+ }++ inline Vector2 &operator/=(const Vector2 other) {+ x /= other.x, y /= other.y;+ return *this;+ }++ inline Vector2 &operator*=(double value) {+ x *= value, y *= value;+ return *this;+ }++ inline Vector2 &operator/=(double value) {+ x /= value, y /= value;+ return *this;+ }++};++/// A vector may also represent a point, which shall be differentiated semantically using the alias Point2.+typedef Vector2 Point2;++/// Dot product of two vectors.+inline double dotProduct(const Vector2 a, const Vector2 b) {+ return a.x*b.x+a.y*b.y;+}++/// A special version of the cross product for 2D vectors (returns scalar value).+inline double crossProduct(const Vector2 a, const Vector2 b) {+ return a.x*b.y-a.y*b.x;+}++inline bool operator==(const Vector2 a, const Vector2 b) {+ return a.x == b.x && a.y == b.y;+}++inline bool operator!=(const Vector2 a, const Vector2 b) {+ return a.x != b.x || a.y != b.y;+}++inline Vector2 operator+(const Vector2 v) {+ return v;+}++inline Vector2 operator-(const Vector2 v) {+ return Vector2(-v.x, -v.y);+}++inline bool operator!(const Vector2 v) {+ return !v.x && !v.y;+}++inline Vector2 operator+(const Vector2 a, const Vector2 b) {+ return Vector2(a.x+b.x, a.y+b.y);+}++inline Vector2 operator-(const Vector2 a, const Vector2 b) {+ return Vector2(a.x-b.x, a.y-b.y);+}++inline Vector2 operator*(const Vector2 a, const Vector2 b) {+ return Vector2(a.x*b.x, a.y*b.y);+}++inline Vector2 operator/(const Vector2 a, const Vector2 b) {+ return Vector2(a.x/b.x, a.y/b.y);+}++inline Vector2 operator*(double a, const Vector2 b) {+ return Vector2(a*b.x, a*b.y);+}++inline Vector2 operator/(double a, const Vector2 b) {+ return Vector2(a/b.x, a/b.y);+}++inline Vector2 operator*(const Vector2 a, double b) {+ return Vector2(a.x*b, a.y*b);+}++inline Vector2 operator/(const Vector2 a, double b) {+ return Vector2(a.x/b, a.y/b);+}++}diff --git a/third_party/msdfgen/core/YAxisOrientation.h b/third_party/msdfgen/core/YAxisOrientation.hnew file mode 100644index 000000000..803acdce4--- /dev/null+++ b/third_party/msdfgen/core/YAxisOrientation.h@@ -0,0 +1,17 @@++#pragma once++#include "base.h"++namespace msdfgen {++/// Specifies whether the Y component of the coordinate system increases in the upward or downward direction.+enum YAxisOrientation {+ Y_UPWARD,+ Y_DOWNWARD+};++}++#define MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION msdfgen::Y_UPWARD+#define MSDFGEN_Y_AXIS_NONDEFAULT_ORIENTATION (MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION == msdfgen::Y_DOWNWARD ? msdfgen::Y_UPWARD : msdfgen::Y_DOWNWARD)diff --git a/third_party/msdfgen/core/arithmetics.hpp b/third_party/msdfgen/core/arithmetics.hppnew file mode 100644index 000000000..d5158ad0d--- /dev/null+++ b/third_party/msdfgen/core/arithmetics.hpp@@ -0,0 +1,63 @@++#pragma once++#include <cmath>+#include "base.h"++namespace msdfgen {++/// Returns the smaller of the arguments.+template <typename T>+inline T min(T a, T b) {+ return b < a ? b : a;+}++/// Returns the larger of the arguments.+template <typename T>+inline T max(T a, T b) {+ return a < b ? b : a;+}++/// Returns the middle out of three values+template <typename T>+inline T median(T a, T b, T c) {+ return max(min(a, b), min(max(a, b), c));+}++/// Returns the weighted average of a and b.+template <typename T, typename S>+inline T mix(T a, T b, S weight) {+ return T((S(1)-weight)*a+weight*b);+}++/// Clamps the number to the interval from 0 to 1.+template <typename T>+inline T clamp(T n) {+ return n >= T(0) && n <= T(1) ? n : T(n > T(0));+}++/// Clamps the number to the interval from 0 to b.+template <typename T>+inline T clamp(T n, T b) {+ return n >= T(0) && n <= b ? n : T(n > T(0))*b;+}++/// Clamps the number to the interval from a to b.+template <typename T>+inline T clamp(T n, T a, T b) {+ return n >= a && n <= b ? n : n < a ? a : b;+}++/// Returns 1 for positive values, -1 for negative values, and 0 for zero.+template <typename T>+inline int sign(T n) {+ return (T(0) < n)-(n < T(0));+}++/// Returns 1 for non-negative values and -1 for negative values.+template <typename T>+inline int nonZeroSign(T n) {+ return 2*(n > T(0))-1;+}++}diff --git a/third_party/msdfgen/core/base.h b/third_party/msdfgen/core/base.hnew file mode 100644index 000000000..ab85c136e--- /dev/null+++ b/third_party/msdfgen/core/base.h@@ -0,0 +1,16 @@++#pragma once++// This file needs to be included first for all MSDFgen sources++#ifndef MSDFGEN_PUBLIC+#include <msdfgen/msdfgen-config.h>+#endif++#include <cstddef>++namespace msdfgen {++typedef unsigned char byte;++}diff --git a/third_party/msdfgen/core/bitmap-interpolation.hpp b/third_party/msdfgen/core/bitmap-interpolation.hppnew file mode 100644index 000000000..3e2576f7b--- /dev/null+++ b/third_party/msdfgen/core/bitmap-interpolation.hpp@@ -0,0 +1,27 @@++#pragma once++#include "arithmetics.hpp"+#include "Vector2.hpp"+#include "BitmapRef.hpp"++namespace msdfgen {++template <typename T, int N>+inline void interpolate(T *output, const BitmapConstSection<T, N> &bitmap, Point2 pos) {+ pos.x = clamp(pos.x, double(bitmap.width));+ pos.y = clamp(pos.y, double(bitmap.height));+ pos -= .5;+ int l = (int) floor(pos.x);+ int b = (int) floor(pos.y);+ int r = l+1;+ int t = b+1;+ double lr = pos.x-l;+ double bt = pos.y-b;+ l = clamp(l, bitmap.width-1), r = clamp(r, bitmap.width-1);+ b = clamp(b, bitmap.height-1), t = clamp(t, bitmap.height-1);+ for (int i = 0; i < N; ++i)+ output[i] = mix(mix(bitmap(l, b)[i], bitmap(r, b)[i], lr), mix(bitmap(l, t)[i], bitmap(r, t)[i], lr), bt);+}++}diff --git a/third_party/msdfgen/core/contour-combiners.cpp b/third_party/msdfgen/core/contour-combiners.cppnew file mode 100644index 000000000..64146d5a6--- /dev/null+++ b/third_party/msdfgen/core/contour-combiners.cpp@@ -0,0 +1,141 @@++#include "contour-combiners.h"++#include <cfloat>+#include "arithmetics.hpp"++namespace msdfgen {++static void initDistance(double &distance) {+ distance = -DBL_MAX;+}++static void initDistance(MultiDistance &distance) {+ distance.r = -DBL_MAX;+ distance.g = -DBL_MAX;+ distance.b = -DBL_MAX;+}++static void initDistance(MultiAndTrueDistance &distance) {+ distance.r = -DBL_MAX;+ distance.g = -DBL_MAX;+ distance.b = -DBL_MAX;+ distance.a = -DBL_MAX;+}++static double resolveDistance(double distance) {+ return distance;+}++static double resolveDistance(const MultiDistance &distance) {+ return median(distance.r, distance.g, distance.b);+}++template <class EdgeSelector>+SimpleContourCombiner<EdgeSelector>::SimpleContourCombiner(const Shape &) { }++template <class EdgeSelector>+void SimpleContourCombiner<EdgeSelector>::reset(const Point2 &p) {+ shapeEdgeSelector.reset(p);+}++template <class EdgeSelector>+EdgeSelector &SimpleContourCombiner<EdgeSelector>::edgeSelector(int) {+ return shapeEdgeSelector;+}++template <class EdgeSelector>+typename SimpleContourCombiner<EdgeSelector>::DistanceType SimpleContourCombiner<EdgeSelector>::distance() const {+ return shapeEdgeSelector.distance();+}++template class SimpleContourCombiner<TrueDistanceSelector>;+template class SimpleContourCombiner<PerpendicularDistanceSelector>;+template class SimpleContourCombiner<MultiDistanceSelector>;+template class SimpleContourCombiner<MultiAndTrueDistanceSelector>;++template <class EdgeSelector>+OverlappingContourCombiner<EdgeSelector>::OverlappingContourCombiner(const Shape &shape) {+ windings.reserve(shape.contours.size());+ for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)+ windings.push_back(contour->winding());+ edgeSelectors.resize(shape.contours.size());+}++template <class EdgeSelector>+void OverlappingContourCombiner<EdgeSelector>::reset(const Point2 &p) {+ this->p = p;+ for (typename std::vector<EdgeSelector>::iterator contourEdgeSelector = edgeSelectors.begin(); contourEdgeSelector != edgeSelectors.end(); ++contourEdgeSelector)+ contourEdgeSelector->reset(p);+}++template <class EdgeSelector>+EdgeSelector &OverlappingContourCombiner<EdgeSelector>::edgeSelector(int i) {+ return edgeSelectors[i];+}++template <class EdgeSelector>+typename OverlappingContourCombiner<EdgeSelector>::DistanceType OverlappingContourCombiner<EdgeSelector>::distance() const {+ int contourCount = (int) edgeSelectors.size();+ EdgeSelector shapeEdgeSelector;+ EdgeSelector innerEdgeSelector;+ EdgeSelector outerEdgeSelector;+ shapeEdgeSelector.reset(p);+ innerEdgeSelector.reset(p);+ outerEdgeSelector.reset(p);+ for (int i = 0; i < contourCount; ++i) {+ DistanceType edgeDistance = edgeSelectors[i].distance();+ shapeEdgeSelector.merge(edgeSelectors[i]);+ if (windings[i] > 0 && resolveDistance(edgeDistance) >= 0)+ innerEdgeSelector.merge(edgeSelectors[i]);+ if (windings[i] < 0 && resolveDistance(edgeDistance) <= 0)+ outerEdgeSelector.merge(edgeSelectors[i]);+ }++ DistanceType shapeDistance = shapeEdgeSelector.distance();+ DistanceType innerDistance = innerEdgeSelector.distance();+ DistanceType outerDistance = outerEdgeSelector.distance();+ double innerScalarDistance = resolveDistance(innerDistance);+ double outerScalarDistance = resolveDistance(outerDistance);+ DistanceType distance;+ initDistance(distance);++ int winding = 0;+ if (innerScalarDistance >= 0 && fabs(innerScalarDistance) <= fabs(outerScalarDistance)) {+ distance = innerDistance;+ winding = 1;+ for (int i = 0; i < contourCount; ++i)+ if (windings[i] > 0) {+ DistanceType contourDistance = edgeSelectors[i].distance();+ if (fabs(resolveDistance(contourDistance)) < fabs(outerScalarDistance) && resolveDistance(contourDistance) > resolveDistance(distance))+ distance = contourDistance;+ }+ } else if (outerScalarDistance <= 0 && fabs(outerScalarDistance) < fabs(innerScalarDistance)) {+ distance = outerDistance;+ winding = -1;+ for (int i = 0; i < contourCount; ++i)+ if (windings[i] < 0) {+ DistanceType contourDistance = edgeSelectors[i].distance();+ if (fabs(resolveDistance(contourDistance)) < fabs(innerScalarDistance) && resolveDistance(contourDistance) < resolveDistance(distance))+ distance = contourDistance;+ }+ } else+ return shapeDistance;++ for (int i = 0; i < contourCount; ++i)+ if (windings[i] != winding) {+ DistanceType contourDistance = edgeSelectors[i].distance();+ if (resolveDistance(contourDistance)*resolveDistance(distance) >= 0 && fabs(resolveDistance(contourDistance)) < fabs(resolveDistance(distance)))+ distance = contourDistance;+ }+ if (resolveDistance(distance) == resolveDistance(shapeDistance))+ distance = shapeDistance;+ return distance;+}++template class OverlappingContourCombiner<TrueDistanceSelector>;+template class OverlappingContourCombiner<PerpendicularDistanceSelector>;+template class OverlappingContourCombiner<MultiDistanceSelector>;+template class OverlappingContourCombiner<MultiAndTrueDistanceSelector>;++}diff --git a/third_party/msdfgen/core/contour-combiners.h b/third_party/msdfgen/core/contour-combiners.hnew file mode 100644index 000000000..04dbc3423--- /dev/null+++ b/third_party/msdfgen/core/contour-combiners.h@@ -0,0 +1,47 @@++#pragma once++#include "Shape.h"+#include "edge-selectors.h"++namespace msdfgen {++/// Simply selects the nearest contour.+template <class EdgeSelector>+class SimpleContourCombiner {++public:+ typedef EdgeSelector EdgeSelectorType;+ typedef typename EdgeSelector::DistanceType DistanceType;++ explicit SimpleContourCombiner(const Shape &shape);+ void reset(const Point2 &p);+ EdgeSelector &edgeSelector(int i);+ DistanceType distance() const;++private:+ EdgeSelector shapeEdgeSelector;++};++/// Selects the nearest contour that actually forms a border between filled and unfilled area.+template <class EdgeSelector>+class OverlappingContourCombiner {++public:+ typedef EdgeSelector EdgeSelectorType;+ typedef typename EdgeSelector::DistanceType DistanceType;++ explicit OverlappingContourCombiner(const Shape &shape);+ void reset(const Point2 &p);+ EdgeSelector &edgeSelector(int i);+ DistanceType distance() const;++private:+ Point2 p;+ std::vector<int> windings;+ std::vector<EdgeSelector> edgeSelectors;++};++}diff --git a/third_party/msdfgen/core/convergent-curve-ordering.cpp b/third_party/msdfgen/core/convergent-curve-ordering.cppnew file mode 100644index 000000000..7639cce95--- /dev/null+++ b/third_party/msdfgen/core/convergent-curve-ordering.cpp@@ -0,0 +1,140 @@++#include "convergent-curve-ordering.h"++#include "arithmetics.hpp"+#include "Vector2.hpp"++/*+ * For non-degenerate curves A(t), B(t) (ones where all control points are distinct) both originating at P = A(0) = B(0) = *corner,+ * we are computing the limit of+ *+ * sign(crossProduct( A(t / |A'(0)|) - P, B(t / |B'(0)|) - P ))+ *+ * for t -> 0 from 1. Of note is that the curves' parameter has to be normed by the first derivative at P,+ * which ensures that the limit approaches P at the same rate along both curves - omitting this was the main error of earlier versions of deconverge.+ *+ * For degenerate cubic curves (ones where the first control point equals the origin point), the denominator |A'(0)| is zero,+ * so to address that, we approach with the square root of t and use the derivative of A(sqrt(t)), which at t = 0 equals A''(0)/2+ * Therefore, in these cases, we replace one factor of the cross product with A(sqrt(2*t / |A''(0)|)) - P+ *+ * The cross product results in a polynomial (in respect to t or t^2 in the degenerate case),+ * the limit of sign of which at zero can be determined by the lowest order non-zero derivative,+ * which equals to the sign of the first non-zero polynomial coefficient in the order of increasing exponents.+ *+ * The polynomial's constant and linear terms are zero, so the first derivative is definitely zero as well.+ * The second derivative is assumed to be zero (or near zero) due to the curves being convergent - this is an input requirement+ * (otherwise the correct result is the sign of the cross product of their directions at t = 0).+ * Therefore, we skip the first and second derivatives.+ */++namespace msdfgen {++static void simplifyDegenerateCurve(Point2 *controlPoints, int &order) {+ if (order == 3 && (controlPoints[1] == controlPoints[0] || controlPoints[1] == controlPoints[3]) && (controlPoints[2] == controlPoints[0] || controlPoints[2] == controlPoints[3])) {+ controlPoints[1] = controlPoints[3];+ order = 1;+ }+ if (order == 2 && (controlPoints[1] == controlPoints[0] || controlPoints[1] == controlPoints[2])) {+ controlPoints[1] = controlPoints[2];+ order = 1;+ }+ if (order == 1 && controlPoints[0] == controlPoints[1])+ order = 0;+}++int convergentCurveOrdering(const Point2 *corner, int controlPointsBefore, int controlPointsAfter) {+ if (!(controlPointsBefore > 0 && controlPointsAfter > 0))+ return 0;+ Vector2 a1, a2, a3, b1, b2, b3;+ a1 = *(corner-1)-*corner;+ b1 = *(corner+1)-*corner;+ if (controlPointsBefore >= 2)+ a2 = *(corner-2)-*(corner-1)-a1;+ if (controlPointsAfter >= 2)+ b2 = *(corner+2)-*(corner+1)-b1;+ if (controlPointsBefore >= 3) {+ a3 = *(corner-3)-*(corner-2)-(*(corner-2)-*(corner-1))-a2;+ a2 *= 3;+ }+ if (controlPointsAfter >= 3) {+ b3 = *(corner+3)-*(corner+2)-(*(corner+2)-*(corner+1))-b2;+ b2 *= 3;+ }+ a1 *= controlPointsBefore;+ b1 *= controlPointsAfter;+ // Non-degenerate case+ if (a1 && b1) {+ double as = a1.length();+ double bs = b1.length();+ // Third derivative+ if (double d = as*crossProduct(a1, b2) + bs*crossProduct(a2, b1))+ return sign(d);+ // Fourth derivative+ if (double d = as*as*crossProduct(a1, b3) + as*bs*crossProduct(a2, b2) + bs*bs*crossProduct(a3, b1))+ return sign(d);+ // Fifth derivative+ if (double d = as*crossProduct(a2, b3) + bs*crossProduct(a3, b2))+ return sign(d);+ // Sixth derivative+ return sign(crossProduct(a3, b3));+ }+ // Degenerate curve after corner (control point after corner equals corner)+ int s = 1;+ if (a1) { // !b1+ // Swap aN <-> bN and handle in if (b1)+ b1 = a1;+ a1 = b2, b2 = a2, a2 = a1;+ a1 = b3, b3 = a3, a3 = a1;+ s = -1; // make sure to also flip output+ }+ // Degenerate curve before corner (control point before corner equals corner)+ if (b1) { // !a1+ // Two-and-a-half-th derivative+ if (double d = crossProduct(a3, b1))+ return s*sign(d);+ // Third derivative+ if (double d = crossProduct(a2, b2))+ return s*sign(d);+ // Three-and-a-half-th derivative+ if (double d = crossProduct(a3, b2))+ return s*sign(d);+ // Fourth derivative+ if (double d = crossProduct(a2, b3))+ return s*sign(d);+ // Four-and-a-half-th derivative+ return s*sign(crossProduct(a3, b3));+ }+ // Degenerate curves on both sides of the corner (control point before and after corner equals corner)+ { // !a1 && !b1+ // Two-and-a-half-th derivative+ if (double d = sqrt(a2.length())*crossProduct(a2, b3) + sqrt(b2.length())*crossProduct(a3, b2))+ return sign(d);+ // Third derivative+ return sign(crossProduct(a3, b3));+ }+}++int convergentCurveOrdering(const EdgeSegment *a, const EdgeSegment *b) {+ Point2 controlPoints[12];+ Point2 *corner = controlPoints+4;+ Point2 *aCpTmp = controlPoints+8;+ int aOrder = int(a->type());+ int bOrder = int(b->type());+ if (!(aOrder >= 1 && aOrder <= 3 && bOrder >= 1 && bOrder <= 3)) {+ // Not implemented - only linear, quadratic, and cubic curves supported+ return 0;+ }+ for (int i = 0; i <= aOrder; ++i)+ aCpTmp[i] = a->controlPoints()[i];+ for (int i = 0; i <= bOrder; ++i)+ corner[i] = b->controlPoints()[i];+ if (aCpTmp[aOrder] != *corner)+ return 0;+ simplifyDegenerateCurve(aCpTmp, aOrder);+ simplifyDegenerateCurve(corner, bOrder);+ for (int i = 0; i < aOrder; ++i)+ corner[i-aOrder] = aCpTmp[i];+ return convergentCurveOrdering(corner, aOrder, bOrder);+}++}diff --git a/third_party/msdfgen/core/convergent-curve-ordering.h b/third_party/msdfgen/core/convergent-curve-ordering.hnew file mode 100644index 000000000..e5bbf29c8--- /dev/null+++ b/third_party/msdfgen/core/convergent-curve-ordering.h@@ -0,0 +1,11 @@++#pragma once++#include "edge-segments.h"++namespace msdfgen {++/// For curves a, b converging at P = a->point(1) = b->point(0) with the same (opposite) direction, determines the relative ordering in which they exit P (i.e. whether a is to the left or right of b at the smallest positive radius around P)+int convergentCurveOrdering(const EdgeSegment *a, const EdgeSegment *b);++}diff --git a/third_party/msdfgen/core/edge-coloring.cpp b/third_party/msdfgen/core/edge-coloring.cppnew file mode 100644index 000000000..6cd9e47be--- /dev/null+++ b/third_party/msdfgen/core/edge-coloring.cpp@@ -0,0 +1,531 @@++#include "edge-coloring.h"++#include <cstdlib>+#include <cmath>+#include <cstring>+#include <cfloat>+#include <vector>+#include <queue>+#include "arithmetics.hpp"++namespace msdfgen {++/**+ * For each position < n, this function will return -1, 0, or 1,+ * depending on whether the position is closer to the beginning, middle, or end, respectively.+ * It is guaranteed that the output will be balanced in that the total for positions 0 through n-1 will be zero.+ */+static int symmetricalTrichotomy(int position, int n) {+ return int(3+2.875*position/(n-1)-1.4375+.5)-3;+}++static bool isCorner(const Vector2 &aDir, const Vector2 &bDir, double crossThreshold) {+ return dotProduct(aDir, bDir) <= 0 || fabs(crossProduct(aDir, bDir)) > crossThreshold;+}++static double estimateEdgeLength(const EdgeSegment *edge) {+ double len = 0;+ Point2 prev = edge->point(0);+ for (int i = 1; i <= MSDFGEN_EDGE_LENGTH_PRECISION; ++i) {+ Point2 cur = edge->point(1./MSDFGEN_EDGE_LENGTH_PRECISION*i);+ len += (cur-prev).length();+ prev = cur;+ }+ return len;+}++static int seedExtract2(unsigned long long &seed) {+ int v = int(seed)&1;+ seed >>= 1;+ return v;+}++static int seedExtract3(unsigned long long &seed) {+ int v = int(seed%3);+ seed /= 3;+ return v;+}++static EdgeColor initColor(unsigned long long &seed) {+ static const EdgeColor colors[3] = { CYAN, MAGENTA, YELLOW };+ return colors[seedExtract3(seed)];+}++static void switchColor(EdgeColor &color, unsigned long long &seed) {+ int shifted = color<<(1+seedExtract2(seed));+ color = EdgeColor((shifted|shifted>>3)&WHITE);+}++static void switchColor(EdgeColor &color, unsigned long long &seed, EdgeColor banned) {+ EdgeColor combined = EdgeColor(color&banned);+ if (combined == RED || combined == GREEN || combined == BLUE)+ color = EdgeColor(combined^WHITE);+ else+ switchColor(color, seed);+}++void edgeColoringSimple(Shape &shape, double angleThreshold, unsigned long long seed) {+ double crossThreshold = sin(angleThreshold);+ EdgeColor color = initColor(seed);+ std::vector<int> corners;+ for (std::vector<Contour>::iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour) {+ if (contour->edges.empty())+ continue;+ { // Identify corners+ corners.clear();+ Vector2 prevDirection = contour->edges.back()->direction(1);+ int index = 0;+ for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge, ++index) {+ if (isCorner(prevDirection.normalize(), (*edge)->direction(0).normalize(), crossThreshold))+ corners.push_back(index);+ prevDirection = (*edge)->direction(1);+ }+ }++ // Smooth contour+ if (corners.empty()) {+ switchColor(color, seed);+ for (std::vector<EdgeHolder>::iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge)+ (*edge)->color = color;+ }+ // "Teardrop" case+ else if (corners.size() == 1) {+ EdgeColor colors[3];+ switchColor(color, seed);+ colors[0] = color;+ colors[1] = WHITE;+ switchColor(color, seed);+ colors[2] = color;+ int corner = corners[0];+ if (contour->edges.size() >= 3) {+ int m = (int) contour->edges.size();+ for (int i = 0; i < m; ++i)+ contour->edges[(corner+i)%m]->color = colors[1+symmetricalTrichotomy(i, m)];+ } else if (contour->edges.size() >= 1) {+ // Less than three edge segments for three colors => edges must be split+ EdgeSegment *parts[7] = { };+ contour->edges[0]->splitInThirds(parts[0+3*corner], parts[1+3*corner], parts[2+3*corner]);+ if (contour->edges.size() >= 2) {+ contour->edges[1]->splitInThirds(parts[3-3*corner], parts[4-3*corner], parts[5-3*corner]);+ parts[0]->color = parts[1]->color = colors[0];+ parts[2]->color = parts[3]->color = colors[1];+ parts[4]->color = parts[5]->color = colors[2];+ } else {+ parts[0]->color = colors[0];+ parts[1]->color = colors[1];+ parts[2]->color = colors[2];+ }+ contour->edges.clear();+ for (int i = 0; parts[i]; ++i)+ contour->edges.push_back(EdgeHolder(parts[i]));+ }+ }+ // Multiple corners+ else {+ int cornerCount = (int) corners.size();+ int spline = 0;+ int start = corners[0];+ int m = (int) contour->edges.size();+ switchColor(color, seed);+ EdgeColor initialColor = color;+ for (int i = 0; i < m; ++i) {+ int index = (start+i)%m;+ if (spline+1 < cornerCount && corners[spline+1] == index) {+ ++spline;+ switchColor(color, seed, EdgeColor((spline == cornerCount-1)*initialColor));+ }+ contour->edges[index]->color = color;+ }+ }+ }+}++struct EdgeColoringInkTrapCorner {+ int index;+ double prevEdgeLengthEstimate;+ bool minor;+ EdgeColor color;+};++void edgeColoringInkTrap(Shape &shape, double angleThreshold, unsigned long long seed) {+ typedef EdgeColoringInkTrapCorner Corner;+ double crossThreshold = sin(angleThreshold);+ EdgeColor color = initColor(seed);+ std::vector<Corner> corners;+ for (std::vector<Contour>::iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour) {+ if (contour->edges.empty())+ continue;+ double splineLength = 0;+ { // Identify corners+ corners.clear();+ Vector2 prevDirection = contour->edges.back()->direction(1);+ int index = 0;+ for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge, ++index) {+ if (isCorner(prevDirection.normalize(), (*edge)->direction(0).normalize(), crossThreshold)) {+ Corner corner = { index, splineLength };+ corners.push_back(corner);+ splineLength = 0;+ }+ splineLength += estimateEdgeLength(*edge);+ prevDirection = (*edge)->direction(1);+ }+ }++ // Smooth contour+ if (corners.empty()) {+ switchColor(color, seed);+ for (std::vector<EdgeHolder>::iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge)+ (*edge)->color = color;+ }+ // "Teardrop" case+ else if (corners.size() == 1) {+ EdgeColor colors[3];+ switchColor(color, seed);+ colors[0] = color;+ colors[1] = WHITE;+ switchColor(color, seed);+ colors[2] = color;+ int corner = corners[0].index;+ if (contour->edges.size() >= 3) {+ int m = (int) contour->edges.size();+ for (int i = 0; i < m; ++i)+ contour->edges[(corner+i)%m]->color = colors[1+symmetricalTrichotomy(i, m)];+ } else if (contour->edges.size() >= 1) {+ // Less than three edge segments for three colors => edges must be split+ EdgeSegment *parts[7] = { };+ contour->edges[0]->splitInThirds(parts[0+3*corner], parts[1+3*corner], parts[2+3*corner]);+ if (contour->edges.size() >= 2) {+ contour->edges[1]->splitInThirds(parts[3-3*corner], parts[4-3*corner], parts[5-3*corner]);+ parts[0]->color = parts[1]->color = colors[0];+ parts[2]->color = parts[3]->color = colors[1];+ parts[4]->color = parts[5]->color = colors[2];+ } else {+ parts[0]->color = colors[0];+ parts[1]->color = colors[1];+ parts[2]->color = colors[2];+ }+ contour->edges.clear();+ for (int i = 0; parts[i]; ++i)+ contour->edges.push_back(EdgeHolder(parts[i]));+ }+ }+ // Multiple corners+ else {+ int cornerCount = (int) corners.size();+ int majorCornerCount = cornerCount;+ if (cornerCount > 3) {+ corners.begin()->prevEdgeLengthEstimate += splineLength;+ for (int i = 0; i < cornerCount; ++i) {+ if (+ corners[i].prevEdgeLengthEstimate > corners[(i+1)%cornerCount].prevEdgeLengthEstimate &&+ corners[(i+1)%cornerCount].prevEdgeLengthEstimate < corners[(i+2)%cornerCount].prevEdgeLengthEstimate+ ) {+ corners[i].minor = true;+ --majorCornerCount;+ }+ }+ }+ EdgeColor initialColor = BLACK;+ for (int i = 0; i < cornerCount; ++i) {+ if (!corners[i].minor) {+ --majorCornerCount;+ switchColor(color, seed, EdgeColor(!majorCornerCount*initialColor));+ corners[i].color = color;+ if (!initialColor)+ initialColor = color;+ }+ }+ for (int i = 0; i < cornerCount; ++i) {+ if (corners[i].minor) {+ EdgeColor nextColor = corners[(i+1)%cornerCount].color;+ corners[i].color = EdgeColor((color&nextColor)^WHITE);+ } else+ color = corners[i].color;+ }+ int spline = 0;+ int start = corners[0].index;+ color = corners[0].color;+ int m = (int) contour->edges.size();+ for (int i = 0; i < m; ++i) {+ int index = (start+i)%m;+ if (spline+1 < cornerCount && corners[spline+1].index == index)+ color = corners[++spline].color;+ contour->edges[index]->color = color;+ }+ }+ }+}++// EDGE COLORING BY DISTANCE - EXPERIMENTAL IMPLEMENTATION - WORK IN PROGRESS+#define MAX_RECOLOR_STEPS 16+#define EDGE_DISTANCE_PRECISION 16++static double edgeToEdgeDistance(const EdgeSegment &a, const EdgeSegment &b, int precision) {+ if (a.point(0) == b.point(0) || a.point(0) == b.point(1) || a.point(1) == b.point(0) || a.point(1) == b.point(1))+ return 0;+ double iFac = 1./precision;+ double minDistance = (b.point(0)-a.point(0)).length();+ for (int i = 0; i <= precision; ++i) {+ double t = iFac*i;+ double d = fabs(a.signedDistance(b.point(t), t).distance);+ minDistance = min(minDistance, d);+ }+ for (int i = 0; i <= precision; ++i) {+ double t = iFac*i;+ double d = fabs(b.signedDistance(a.point(t), t).distance);+ minDistance = min(minDistance, d);+ }+ return minDistance;+}++static double splineToSplineDistance(EdgeSegment *const *edgeSegments, int aStart, int aEnd, int bStart, int bEnd, int precision) {+ double minDistance = DBL_MAX;+ for (int ai = aStart; ai < aEnd; ++ai)+ for (int bi = bStart; bi < bEnd && minDistance; ++bi) {+ double d = edgeToEdgeDistance(*edgeSegments[ai], *edgeSegments[bi], precision);+ minDistance = min(minDistance, d);+ }+ return minDistance;+}++static void colorSecondDegreeGraph(int *coloring, const int *const *edgeMatrix, int vertexCount, unsigned long long seed) {+ for (int i = 0; i < vertexCount; ++i) {+ int possibleColors = 7;+ for (int j = 0; j < i; ++j) {+ if (edgeMatrix[i][j])+ possibleColors &= ~(1<<coloring[j]);+ }+ int color = 0;+ switch (possibleColors) {+ case 1:+ color = 0;+ break;+ case 2:+ color = 1;+ break;+ case 3:+ color = seedExtract2(seed); // 0 or 1+ break;+ case 4:+ color = 2;+ break;+ case 5:+ color = (int) !seedExtract2(seed)<<1; // 2 or 0+ break;+ case 6:+ color = seedExtract2(seed)+1; // 1 or 2+ break;+ case 7:+ color = (seedExtract3(seed)+i)%3; // 0 or 1 or 2+ break;+ }+ coloring[i] = color;+ }+}++static int vertexPossibleColors(const int *coloring, const int *edgeVector, int vertexCount) {+ int usedColors = 0;+ for (int i = 0; i < vertexCount; ++i)+ if (edgeVector[i])+ usedColors |= 1<<coloring[i];+ return 7&~usedColors;+}++static void uncolorSameNeighbors(std::queue<int> &uncolored, int *coloring, const int *const *edgeMatrix, int vertex, int vertexCount) {+ for (int i = vertex+1; i < vertexCount; ++i) {+ if (edgeMatrix[vertex][i] && coloring[i] == coloring[vertex]) {+ coloring[i] = -1;+ uncolored.push(i);+ }+ }+ for (int i = 0; i < vertex; ++i) {+ if (edgeMatrix[vertex][i] && coloring[i] == coloring[vertex]) {+ coloring[i] = -1;+ uncolored.push(i);+ }+ }+}++static bool tryAddEdge(int *coloring, int *const *edgeMatrix, int vertexCount, int vertexA, int vertexB, int *coloringBuffer) {+ static const int FIRST_POSSIBLE_COLOR[8] = { -1, 0, 1, 0, 2, 2, 1, 0 };+ edgeMatrix[vertexA][vertexB] = 1;+ edgeMatrix[vertexB][vertexA] = 1;+ if (coloring[vertexA] != coloring[vertexB])+ return true;+ int bPossibleColors = vertexPossibleColors(coloring, edgeMatrix[vertexB], vertexCount);+ if (bPossibleColors) {+ coloring[vertexB] = FIRST_POSSIBLE_COLOR[bPossibleColors];+ return true;+ }+ memcpy(coloringBuffer, coloring, sizeof(int)*vertexCount);+ std::queue<int> uncolored;+ {+ int *coloring = coloringBuffer;+ coloring[vertexB] = FIRST_POSSIBLE_COLOR[7&~(1<<coloring[vertexA])];+ uncolorSameNeighbors(uncolored, coloring, edgeMatrix, vertexB, vertexCount);+ int step = 0;+ while (!uncolored.empty() && step < MAX_RECOLOR_STEPS) {+ int i = uncolored.front();+ uncolored.pop();+ int possibleColors = vertexPossibleColors(coloring, edgeMatrix[i], vertexCount);+ if (possibleColors) {+ coloring[i] = FIRST_POSSIBLE_COLOR[possibleColors];+ continue;+ }+ do {+ coloring[i] = step++%3;+ } while (edgeMatrix[i][vertexA] && coloring[i] == coloring[vertexA]);+ uncolorSameNeighbors(uncolored, coloring, edgeMatrix, i, vertexCount);+ }+ }+ if (!uncolored.empty()) {+ edgeMatrix[vertexA][vertexB] = 0;+ edgeMatrix[vertexB][vertexA] = 0;+ return false;+ }+ memcpy(coloring, coloringBuffer, sizeof(int)*vertexCount);+ return true;+}++static int cmpDoublePtr(const void *a, const void *b) {+ return sign(**reinterpret_cast<const double *const *>(a)-**reinterpret_cast<const double *const *>(b));+}++void edgeColoringByDistance(Shape &shape, double angleThreshold, unsigned long long seed) {++ std::vector<EdgeSegment *> edgeSegments;+ std::vector<int> splineStarts;++ double crossThreshold = sin(angleThreshold);+ std::vector<int> corners;+ for (std::vector<Contour>::iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)+ if (!contour->edges.empty()) {+ // Identify corners+ corners.clear();+ Vector2 prevDirection = contour->edges.back()->direction(1);+ int index = 0;+ for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge, ++index) {+ if (isCorner(prevDirection.normalize(), (*edge)->direction(0).normalize(), crossThreshold))+ corners.push_back(index);+ prevDirection = (*edge)->direction(1);+ }++ splineStarts.push_back((int) edgeSegments.size());+ // Smooth contour+ if (corners.empty())+ for (std::vector<EdgeHolder>::iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge)+ edgeSegments.push_back(&**edge);+ // "Teardrop" case+ else if (corners.size() == 1) {+ int corner = corners[0];+ if (contour->edges.size() >= 3) {+ int m = (int) contour->edges.size();+ for (int i = 0; i < m; ++i) {+ if (i == m/2)+ splineStarts.push_back((int) edgeSegments.size());+ if (symmetricalTrichotomy(i, m))+ edgeSegments.push_back(&*contour->edges[(corner+i)%m]);+ else+ contour->edges[(corner+i)%m]->color = WHITE;+ }+ } else if (contour->edges.size() >= 1) {+ // Less than three edge segments for three colors => edges must be split+ EdgeSegment *parts[7] = { };+ contour->edges[0]->splitInThirds(parts[0+3*corner], parts[1+3*corner], parts[2+3*corner]);+ if (contour->edges.size() >= 2) {+ contour->edges[1]->splitInThirds(parts[3-3*corner], parts[4-3*corner], parts[5-3*corner]);+ edgeSegments.push_back(parts[0]);+ edgeSegments.push_back(parts[1]);+ parts[2]->color = parts[3]->color = WHITE;+ splineStarts.push_back((int) edgeSegments.size());+ edgeSegments.push_back(parts[4]);+ edgeSegments.push_back(parts[5]);+ } else {+ edgeSegments.push_back(parts[0]);+ parts[1]->color = WHITE;+ splineStarts.push_back((int) edgeSegments.size());+ edgeSegments.push_back(parts[2]);+ }+ contour->edges.clear();+ for (int i = 0; parts[i]; ++i)+ contour->edges.push_back(EdgeHolder(parts[i]));+ }+ }+ // Multiple corners+ else {+ int cornerCount = (int) corners.size();+ int spline = 0;+ int start = corners[0];+ int m = (int) contour->edges.size();+ for (int i = 0; i < m; ++i) {+ int index = (start+i)%m;+ if (spline+1 < cornerCount && corners[spline+1] == index) {+ splineStarts.push_back((int) edgeSegments.size());+ ++spline;+ }+ edgeSegments.push_back(&*contour->edges[index]);+ }+ }+ }+ splineStarts.push_back((int) edgeSegments.size());++ int segmentCount = (int) edgeSegments.size();+ int splineCount = (int) splineStarts.size()-1;+ if (!splineCount)+ return;++ std::vector<double> distanceMatrixStorage(splineCount*splineCount);+ std::vector<double *> distanceMatrix(splineCount);+ for (int i = 0; i < splineCount; ++i)+ distanceMatrix[i] = &distanceMatrixStorage[i*splineCount];+ const double *distanceMatrixBase = &distanceMatrixStorage[0];++ for (int i = 0; i < splineCount; ++i) {+ distanceMatrix[i][i] = -1;+ for (int j = i+1; j < splineCount; ++j) {+ double dist = splineToSplineDistance(&edgeSegments[0], splineStarts[i], splineStarts[i+1], splineStarts[j], splineStarts[j+1], EDGE_DISTANCE_PRECISION);+ distanceMatrix[i][j] = dist;+ distanceMatrix[j][i] = dist;+ }+ }++ std::vector<const double *> graphEdgeDistances;+ graphEdgeDistances.reserve(splineCount*(splineCount-1)/2);+ for (int i = 0; i < splineCount; ++i)+ for (int j = i+1; j < splineCount; ++j)+ graphEdgeDistances.push_back(&distanceMatrix[i][j]);+ int graphEdgeCount = (int) graphEdgeDistances.size();+ if (!graphEdgeDistances.empty())+ qsort(&graphEdgeDistances[0], graphEdgeDistances.size(), sizeof(const double *), &cmpDoublePtr);++ std::vector<int> edgeMatrixStorage(splineCount*splineCount);+ std::vector<int *> edgeMatrix(splineCount);+ for (int i = 0; i < splineCount; ++i)+ edgeMatrix[i] = &edgeMatrixStorage[i*splineCount];+ int nextEdge = 0;+ for (; nextEdge < graphEdgeCount && !*graphEdgeDistances[nextEdge]; ++nextEdge) {+ int elem = (int) (graphEdgeDistances[nextEdge]-distanceMatrixBase);+ int row = elem/splineCount;+ int col = elem%splineCount;+ edgeMatrix[row][col] = 1;+ edgeMatrix[col][row] = 1;+ }++ std::vector<int> coloring(2*splineCount);+ colorSecondDegreeGraph(&coloring[0], &edgeMatrix[0], splineCount, seed);+ for (; nextEdge < graphEdgeCount; ++nextEdge) {+ int elem = (int) (graphEdgeDistances[nextEdge]-distanceMatrixBase);+ tryAddEdge(&coloring[0], &edgeMatrix[0], splineCount, elem/splineCount, elem%splineCount, &coloring[splineCount]);+ }++ const EdgeColor colors[3] = { YELLOW, CYAN, MAGENTA };+ int spline = -1;+ for (int i = 0; i < segmentCount; ++i) {+ if (splineStarts[spline+1] == i)+ ++spline;+ edgeSegments[i]->color = colors[coloring[spline]];+ }+}++}diff --git a/third_party/msdfgen/core/edge-coloring.h b/third_party/msdfgen/core/edge-coloring.hnew file mode 100644index 000000000..ffd5e6dce--- /dev/null+++ b/third_party/msdfgen/core/edge-coloring.h@@ -0,0 +1,29 @@++#pragma once++#include "Shape.h"++#define MSDFGEN_EDGE_LENGTH_PRECISION 4++namespace msdfgen {++/** Assigns colors to edges of the shape in accordance to the multi-channel distance field technique.+ * May split some edges if necessary.+ * angleThreshold specifies the maximum angle (in radians) to be considered a corner, for example 3 (~172 degrees).+ * Values below 1/2 PI will be treated as the external angle.+ */+void edgeColoringSimple(Shape &shape, double angleThreshold, unsigned long long seed = 0);++/** The alternative "ink trap" coloring strategy is designed for better results with typefaces+ * that use ink traps as a design feature. It guarantees that even if all edges that are shorter than+ * both their neighboring edges are removed, the coloring remains consistent with the established rules.+ */+void edgeColoringInkTrap(Shape &shape, double angleThreshold, unsigned long long seed = 0);++/** The alternative coloring by distance tries to use different colors for edges that are close together.+ * This should theoretically be the best strategy on average. However, since it needs to compute the distance+ * between all pairs of edges, and perform a graph optimization task, it is much slower than the rest.+ */+void edgeColoringByDistance(Shape &shape, double angleThreshold, unsigned long long seed = 0);++}diff --git a/third_party/msdfgen/core/edge-segments.cpp b/third_party/msdfgen/core/edge-segments.cppnew file mode 100644index 000000000..582c6f8b4--- /dev/null+++ b/third_party/msdfgen/core/edge-segments.cpp@@ -0,0 +1,533 @@++#include "edge-segments.h"++#include "arithmetics.hpp"+#include "equation-solver.h"++namespace msdfgen {++EdgeSegment *EdgeSegment::create(Point2 p0, Point2 p1, EdgeColor edgeColor) {+ return new LinearSegment(p0, p1, edgeColor);+}++EdgeSegment *EdgeSegment::create(Point2 p0, Point2 p1, Point2 p2, EdgeColor edgeColor) {+ if (!crossProduct(p1-p0, p2-p1))+ return new LinearSegment(p0, p2, edgeColor);+ return new QuadraticSegment(p0, p1, p2, edgeColor);+}++EdgeSegment *EdgeSegment::create(Point2 p0, Point2 p1, Point2 p2, Point2 p3, EdgeColor edgeColor) {+ Vector2 p12 = p2-p1;+ if (!crossProduct(p1-p0, p12) && !crossProduct(p12, p3-p2))+ return new LinearSegment(p0, p3, edgeColor);+ if ((p12 = 1.5*p1-.5*p0) == 1.5*p2-.5*p3)+ return new QuadraticSegment(p0, p12, p3, edgeColor);+ return new CubicSegment(p0, p1, p2, p3, edgeColor);+}++void EdgeSegment::distanceToPerpendicularDistance(SignedDistance &distance, Point2 origin, double param) const {+ if (param < 0) {+ Vector2 dir = direction(0).normalize();+ Vector2 aq = origin-point(0);+ double ts = dotProduct(aq, dir);+ if (ts < 0) {+ double perpendicularDistance = crossProduct(aq, dir);+ if (fabs(perpendicularDistance) <= fabs(distance.distance)) {+ distance.distance = perpendicularDistance;+ distance.dot = 0;+ }+ }+ } else if (param > 1) {+ Vector2 dir = direction(1).normalize();+ Vector2 bq = origin-point(1);+ double ts = dotProduct(bq, dir);+ if (ts > 0) {+ double perpendicularDistance = crossProduct(bq, dir);+ if (fabs(perpendicularDistance) <= fabs(distance.distance)) {+ distance.distance = perpendicularDistance;+ distance.dot = 0;+ }+ }+ }+}++LinearSegment::LinearSegment(Point2 p0, Point2 p1, EdgeColor edgeColor) : EdgeSegment(edgeColor) {+ p[0] = p0;+ p[1] = p1;+}++QuadraticSegment::QuadraticSegment(Point2 p0, Point2 p1, Point2 p2, EdgeColor edgeColor) : EdgeSegment(edgeColor) {+ p[0] = p0;+ p[1] = p1;+ p[2] = p2;+}++CubicSegment::CubicSegment(Point2 p0, Point2 p1, Point2 p2, Point2 p3, EdgeColor edgeColor) : EdgeSegment(edgeColor) {+ p[0] = p0;+ p[1] = p1;+ p[2] = p2;+ p[3] = p3;+}++LinearSegment *LinearSegment::clone() const {+ return new LinearSegment(p[0], p[1], color);+}++QuadraticSegment *QuadraticSegment::clone() const {+ return new QuadraticSegment(p[0], p[1], p[2], color);+}++CubicSegment *CubicSegment::clone() const {+ return new CubicSegment(p[0], p[1], p[2], p[3], color);+}++int LinearSegment::type() const {+ return (int) EDGE_TYPE;+}++int QuadraticSegment::type() const {+ return (int) EDGE_TYPE;+}++int CubicSegment::type() const {+ return (int) EDGE_TYPE;+}++const Point2 *LinearSegment::controlPoints() const {+ return p;+}++const Point2 *QuadraticSegment::controlPoints() const {+ return p;+}++const Point2 *CubicSegment::controlPoints() const {+ return p;+}++Point2 LinearSegment::point(double param) const {+ return mix(p[0], p[1], param);+}++Point2 QuadraticSegment::point(double param) const {+ return mix(mix(p[0], p[1], param), mix(p[1], p[2], param), param);+}++Point2 CubicSegment::point(double param) const {+ Vector2 p12 = mix(p[1], p[2], param);+ return mix(mix(mix(p[0], p[1], param), p12, param), mix(p12, mix(p[2], p[3], param), param), param);+}++Vector2 LinearSegment::direction(double param) const {+ return p[1]-p[0];+}++Vector2 QuadraticSegment::direction(double param) const {+ Vector2 tangent = mix(p[1]-p[0], p[2]-p[1], param);+ if (!tangent)+ return p[2]-p[0];+ return tangent;+}++Vector2 CubicSegment::direction(double param) const {+ Vector2 tangent = mix(mix(p[1]-p[0], p[2]-p[1], param), mix(p[2]-p[1], p[3]-p[2], param), param);+ if (!tangent) {+ if (param == 0) return p[2]-p[0];+ if (param == 1) return p[3]-p[1];+ }+ return tangent;+}++Vector2 LinearSegment::directionChange(double param) const {+ return Vector2();+}++Vector2 QuadraticSegment::directionChange(double param) const {+ return (p[2]-p[1])-(p[1]-p[0]);+}++Vector2 CubicSegment::directionChange(double param) const {+ return mix((p[2]-p[1])-(p[1]-p[0]), (p[3]-p[2])-(p[2]-p[1]), param);+}++double LinearSegment::length() const {+ return (p[1]-p[0]).length();+}++double QuadraticSegment::length() const {+ Vector2 ab = p[1]-p[0];+ Vector2 br = p[2]-p[1]-ab;+ double abab = dotProduct(ab, ab);+ double abbr = dotProduct(ab, br);+ double brbr = dotProduct(br, br);+ double abLen = sqrt(abab);+ double brLen = sqrt(brbr);+ double crs = crossProduct(ab, br);+ double h = sqrt(abab+abbr+abbr+brbr);+ return (+ brLen*((abbr+brbr)*h-abbr*abLen)++ crs*crs*log((brLen*h+abbr+brbr)/(brLen*abLen+abbr))+ )/(brbr*brLen);+}++SignedDistance LinearSegment::signedDistance(Point2 origin, double ¶m) const {+ Vector2 aq = origin-p[0];+ Vector2 ab = p[1]-p[0];+ param = dotProduct(aq, ab)/dotProduct(ab, ab);+ Vector2 eq = p[param > .5]-origin;+ double endpointDistance = eq.length();+ if (param > 0 && param < 1) {+ double orthoDistance = dotProduct(ab.getOrthonormal(false), aq);+ if (fabs(orthoDistance) < endpointDistance)+ return SignedDistance(orthoDistance, 0);+ }+ return SignedDistance(nonZeroSign(crossProduct(aq, ab))*endpointDistance, fabs(dotProduct(ab.normalize(), eq.normalize())));+}++SignedDistance QuadraticSegment::signedDistance(Point2 origin, double ¶m) const {+ Vector2 qa = p[0]-origin;+ Vector2 ab = p[1]-p[0];+ Vector2 br = p[2]-p[1]-ab;+ double a = dotProduct(br, br);+ double b = 3*dotProduct(ab, br);+ double c = 2*dotProduct(ab, ab)+dotProduct(qa, br);+ double d = dotProduct(qa, ab);+ double t[3];+ int solutions = solveCubic(t, a, b, c, d);++ Vector2 epDir = direction(0);+ double minDistance = nonZeroSign(crossProduct(epDir, qa))*qa.length(); // distance from A+ param = -dotProduct(qa, epDir)/dotProduct(epDir, epDir);+ {+ double distance = (p[2]-origin).length(); // distance from B+ if (distance < fabs(minDistance)) {+ epDir = direction(1);+ minDistance = nonZeroSign(crossProduct(epDir, p[2]-origin))*distance;+ param = dotProduct(origin-p[1], epDir)/dotProduct(epDir, epDir);+ }+ }+ for (int i = 0; i < solutions; ++i) {+ if (t[i] > 0 && t[i] < 1) {+ Point2 qe = qa+2*t[i]*ab+t[i]*t[i]*br;+ double distance = qe.length();+ if (distance <= fabs(minDistance)) {+ minDistance = nonZeroSign(crossProduct(ab+t[i]*br, qe))*distance;+ param = t[i];+ }+ }+ }++ if (param >= 0 && param <= 1)+ return SignedDistance(minDistance, 0);+ if (param < .5)+ return SignedDistance(minDistance, fabs(dotProduct(direction(0).normalize(), qa.normalize())));+ else+ return SignedDistance(minDistance, fabs(dotProduct(direction(1).normalize(), (p[2]-origin).normalize())));+}++SignedDistance CubicSegment::signedDistance(Point2 origin, double ¶m) const {+ Vector2 qa = p[0]-origin;+ Vector2 ab = p[1]-p[0];+ Vector2 br = p[2]-p[1]-ab;+ Vector2 as = (p[3]-p[2])-(p[2]-p[1])-br;++ Vector2 epDir = direction(0);+ double minDistance = nonZeroSign(crossProduct(epDir, qa))*qa.length(); // distance from A+ param = -dotProduct(qa, epDir)/dotProduct(epDir, epDir);+ {+ double distance = (p[3]-origin).length(); // distance from B+ if (distance < fabs(minDistance)) {+ epDir = direction(1);+ minDistance = nonZeroSign(crossProduct(epDir, p[3]-origin))*distance;+ param = dotProduct(epDir-(p[3]-origin), epDir)/dotProduct(epDir, epDir);+ }+ }+ // Iterative minimum distance search+ for (int i = 0; i <= MSDFGEN_CUBIC_SEARCH_STARTS; ++i) {+ double t = 1./MSDFGEN_CUBIC_SEARCH_STARTS*i;+ Vector2 qe = qa+3*t*ab+3*t*t*br+t*t*t*as;+ Vector2 d1 = 3*ab+6*t*br+3*t*t*as;+ Vector2 d2 = 6*br+6*t*as;+ double improvedT = t-dotProduct(qe, d1)/(dotProduct(d1, d1)+dotProduct(qe, d2));+ if (improvedT > 0 && improvedT < 1) {+ int remainingSteps = MSDFGEN_CUBIC_SEARCH_STEPS;+ do {+ t = improvedT;+ qe = qa+3*t*ab+3*t*t*br+t*t*t*as;+ d1 = 3*ab+6*t*br+3*t*t*as;+ if (!--remainingSteps)+ break;+ d2 = 6*br+6*t*as;+ improvedT = t-dotProduct(qe, d1)/(dotProduct(d1, d1)+dotProduct(qe, d2));+ } while (improvedT > 0 && improvedT < 1);+ double distance = qe.length();+ if (distance < fabs(minDistance)) {+ minDistance = nonZeroSign(crossProduct(d1, qe))*distance;+ param = t;+ }+ }+ }++ if (param >= 0 && param <= 1)+ return SignedDistance(minDistance, 0);+ if (param < .5)+ return SignedDistance(minDistance, fabs(dotProduct(direction(0).normalize(), qa.normalize())));+ else+ return SignedDistance(minDistance, fabs(dotProduct(direction(1).normalize(), (p[3]-origin).normalize())));+}++int LinearSegment::scanlineIntersections(double x[3], int dy[3], double y) const {+ if ((y >= p[0].y && y < p[1].y) || (y >= p[1].y && y < p[0].y)) {+ double param = (y-p[0].y)/(p[1].y-p[0].y);+ x[0] = mix(p[0].x, p[1].x, param);+ dy[0] = sign(p[1].y-p[0].y);+ return 1;+ }+ return 0;+}++int QuadraticSegment::scanlineIntersections(double x[3], int dy[3], double y) const {+ int total = 0;+ int nextDY = y > p[0].y ? 1 : -1;+ x[total] = p[0].x;+ if (p[0].y == y) {+ if (p[0].y < p[1].y || (p[0].y == p[1].y && p[0].y < p[2].y))+ dy[total++] = 1;+ else+ nextDY = 1;+ }+ {+ Vector2 ab = p[1]-p[0];+ Vector2 br = p[2]-p[1]-ab;+ double t[2];+ int solutions = solveQuadratic(t, br.y, 2*ab.y, p[0].y-y);+ // Sort solutions+ double tmp;+ if (solutions >= 2 && t[0] > t[1])+ tmp = t[0], t[0] = t[1], t[1] = tmp;+ for (int i = 0; i < solutions && total < 2; ++i) {+ if (t[i] >= 0 && t[i] <= 1) {+ x[total] = p[0].x+2*t[i]*ab.x+t[i]*t[i]*br.x;+ if (nextDY*(ab.y+t[i]*br.y) >= 0) {+ dy[total++] = nextDY;+ nextDY = -nextDY;+ }+ }+ }+ }+ if (p[2].y == y) {+ if (nextDY > 0 && total > 0) {+ --total;+ nextDY = -1;+ }+ if ((p[2].y < p[1].y || (p[2].y == p[1].y && p[2].y < p[0].y)) && total < 2) {+ x[total] = p[2].x;+ if (nextDY < 0) {+ dy[total++] = -1;+ nextDY = 1;+ }+ }+ }+ if (nextDY != (y >= p[2].y ? 1 : -1)) {+ if (total > 0)+ --total;+ else {+ if (fabs(p[2].y-y) < fabs(p[0].y-y))+ x[total] = p[2].x;+ dy[total++] = nextDY;+ }+ }+ return total;+}++int CubicSegment::scanlineIntersections(double x[3], int dy[3], double y) const {+ int total = 0;+ int nextDY = y > p[0].y ? 1 : -1;+ x[total] = p[0].x;+ if (p[0].y == y) {+ if (p[0].y < p[1].y || (p[0].y == p[1].y && (p[0].y < p[2].y || (p[0].y == p[2].y && p[0].y < p[3].y))))+ dy[total++] = 1;+ else+ nextDY = 1;+ }+ {+ Vector2 ab = p[1]-p[0];+ Vector2 br = p[2]-p[1]-ab;+ Vector2 as = (p[3]-p[2])-(p[2]-p[1])-br;+ double t[3];+ int solutions = solveCubic(t, as.y, 3*br.y, 3*ab.y, p[0].y-y);+ // Sort solutions+ double tmp;+ if (solutions >= 2) {+ if (t[0] > t[1])+ tmp = t[0], t[0] = t[1], t[1] = tmp;+ if (solutions >= 3 && t[1] > t[2]) {+ tmp = t[1], t[1] = t[2], t[2] = tmp;+ if (t[0] > t[1])+ tmp = t[0], t[0] = t[1], t[1] = tmp;+ }+ }+ for (int i = 0; i < solutions && total < 3; ++i) {+ if (t[i] >= 0 && t[i] <= 1) {+ x[total] = p[0].x+3*t[i]*ab.x+3*t[i]*t[i]*br.x+t[i]*t[i]*t[i]*as.x;+ if (nextDY*(ab.y+2*t[i]*br.y+t[i]*t[i]*as.y) >= 0) {+ dy[total++] = nextDY;+ nextDY = -nextDY;+ }+ }+ }+ }+ if (p[3].y == y) {+ if (nextDY > 0 && total > 0) {+ --total;+ nextDY = -1;+ }+ if ((p[3].y < p[2].y || (p[3].y == p[2].y && (p[3].y < p[1].y || (p[3].y == p[1].y && p[3].y < p[0].y)))) && total < 3) {+ x[total] = p[3].x;+ if (nextDY < 0) {+ dy[total++] = -1;+ nextDY = 1;+ }+ }+ }+ if (nextDY != (y >= p[3].y ? 1 : -1)) {+ if (total > 0)+ --total;+ else {+ if (fabs(p[3].y-y) < fabs(p[0].y-y))+ x[total] = p[3].x;+ dy[total++] = nextDY;+ }+ }+ return total;+}++static void pointBounds(Point2 p, double &xMin, double &yMin, double &xMax, double &yMax) {+ if (p.x < xMin) xMin = p.x;+ if (p.y < yMin) yMin = p.y;+ if (p.x > xMax) xMax = p.x;+ if (p.y > yMax) yMax = p.y;+}++void LinearSegment::bound(double &xMin, double &yMin, double &xMax, double &yMax) const {+ pointBounds(p[0], xMin, yMin, xMax, yMax);+ pointBounds(p[1], xMin, yMin, xMax, yMax);+}++void QuadraticSegment::bound(double &xMin, double &yMin, double &xMax, double &yMax) const {+ pointBounds(p[0], xMin, yMin, xMax, yMax);+ pointBounds(p[2], xMin, yMin, xMax, yMax);+ Vector2 bot = (p[1]-p[0])-(p[2]-p[1]);+ if (bot.x) {+ double param = (p[1].x-p[0].x)/bot.x;+ if (param > 0 && param < 1)+ pointBounds(point(param), xMin, yMin, xMax, yMax);+ }+ if (bot.y) {+ double param = (p[1].y-p[0].y)/bot.y;+ if (param > 0 && param < 1)+ pointBounds(point(param), xMin, yMin, xMax, yMax);+ }+}++void CubicSegment::bound(double &xMin, double &yMin, double &xMax, double &yMax) const {+ pointBounds(p[0], xMin, yMin, xMax, yMax);+ pointBounds(p[3], xMin, yMin, xMax, yMax);+ Vector2 a0 = p[1]-p[0];+ Vector2 a1 = 2*(p[2]-p[1]-a0);+ Vector2 a2 = p[3]-3*p[2]+3*p[1]-p[0];+ double params[2];+ int solutions;+ solutions = solveQuadratic(params, a2.x, a1.x, a0.x);+ for (int i = 0; i < solutions; ++i)+ if (params[i] > 0 && params[i] < 1)+ pointBounds(point(params[i]), xMin, yMin, xMax, yMax);+ solutions = solveQuadratic(params, a2.y, a1.y, a0.y);+ for (int i = 0; i < solutions; ++i)+ if (params[i] > 0 && params[i] < 1)+ pointBounds(point(params[i]), xMin, yMin, xMax, yMax);+}++void LinearSegment::reverse() {+ Point2 tmp = p[0];+ p[0] = p[1];+ p[1] = tmp;+}++void QuadraticSegment::reverse() {+ Point2 tmp = p[0];+ p[0] = p[2];+ p[2] = tmp;+}++void CubicSegment::reverse() {+ Point2 tmp = p[0];+ p[0] = p[3];+ p[3] = tmp;+ tmp = p[1];+ p[1] = p[2];+ p[2] = tmp;+}++void LinearSegment::moveStartPoint(Point2 to) {+ p[0] = to;+}++void QuadraticSegment::moveStartPoint(Point2 to) {+ Vector2 origSDir = p[0]-p[1];+ Point2 origP1 = p[1];+ p[1] += crossProduct(p[0]-p[1], to-p[0])/crossProduct(p[0]-p[1], p[2]-p[1])*(p[2]-p[1]);+ p[0] = to;+ if (dotProduct(origSDir, p[0]-p[1]) < 0)+ p[1] = origP1;+}++void CubicSegment::moveStartPoint(Point2 to) {+ p[1] += to-p[0];+ p[0] = to;+}++void LinearSegment::moveEndPoint(Point2 to) {+ p[1] = to;+}++void QuadraticSegment::moveEndPoint(Point2 to) {+ Vector2 origEDir = p[2]-p[1];+ Point2 origP1 = p[1];+ p[1] += crossProduct(p[2]-p[1], to-p[2])/crossProduct(p[2]-p[1], p[0]-p[1])*(p[0]-p[1]);+ p[2] = to;+ if (dotProduct(origEDir, p[2]-p[1]) < 0)+ p[1] = origP1;+}++void CubicSegment::moveEndPoint(Point2 to) {+ p[2] += to-p[3];+ p[3] = to;+}++void LinearSegment::splitInThirds(EdgeSegment *&part0, EdgeSegment *&part1, EdgeSegment *&part2) const {+ part0 = new LinearSegment(p[0], point(1/3.), color);+ part1 = new LinearSegment(point(1/3.), point(2/3.), color);+ part2 = new LinearSegment(point(2/3.), p[1], color);+}++void QuadraticSegment::splitInThirds(EdgeSegment *&part0, EdgeSegment *&part1, EdgeSegment *&part2) const {+ part0 = new QuadraticSegment(p[0], mix(p[0], p[1], 1/3.), point(1/3.), color);+ part1 = new QuadraticSegment(point(1/3.), mix(mix(p[0], p[1], 5/9.), mix(p[1], p[2], 4/9.), .5), point(2/3.), color);+ part2 = new QuadraticSegment(point(2/3.), mix(p[1], p[2], 2/3.), p[2], color);+}++void CubicSegment::splitInThirds(EdgeSegment *&part0, EdgeSegment *&part1, EdgeSegment *&part2) const {+ part0 = new CubicSegment(p[0], p[0] == p[1] ? p[0] : mix(p[0], p[1], 1/3.), mix(mix(p[0], p[1], 1/3.), mix(p[1], p[2], 1/3.), 1/3.), point(1/3.), color);+ part1 = new CubicSegment(point(1/3.),+ mix(mix(mix(p[0], p[1], 1/3.), mix(p[1], p[2], 1/3.), 1/3.), mix(mix(p[1], p[2], 1/3.), mix(p[2], p[3], 1/3.), 1/3.), 2/3.),+ mix(mix(mix(p[0], p[1], 2/3.), mix(p[1], p[2], 2/3.), 2/3.), mix(mix(p[1], p[2], 2/3.), mix(p[2], p[3], 2/3.), 2/3.), 1/3.),+ point(2/3.), color);+ part2 = new CubicSegment(point(2/3.), mix(mix(p[1], p[2], 2/3.), mix(p[2], p[3], 2/3.), 2/3.), p[2] == p[3] ? p[3] : mix(p[2], p[3], 2/3.), p[3], color);+}++EdgeSegment *QuadraticSegment::convertToCubic() const {+ return new CubicSegment(p[0], mix(p[0], p[1], 2/3.), mix(p[1], p[2], 1/3.), p[2], color);+}++}diff --git a/third_party/msdfgen/core/edge-segments.h b/third_party/msdfgen/core/edge-segments.hnew file mode 100644index 000000000..10b803a28--- /dev/null+++ b/third_party/msdfgen/core/edge-segments.h@@ -0,0 +1,146 @@++#pragma once++#include "Vector2.hpp"+#include "SignedDistance.hpp"+#include "EdgeColor.h"++namespace msdfgen {++// Parameters for iterative search of closest point on a cubic Bezier curve. Increase for higher precision.+#define MSDFGEN_CUBIC_SEARCH_STARTS 4+#define MSDFGEN_CUBIC_SEARCH_STEPS 4++/// An abstract edge segment.+class EdgeSegment {++public:+ EdgeColor color;++ static EdgeSegment *create(Point2 p0, Point2 p1, EdgeColor edgeColor = WHITE);+ static EdgeSegment *create(Point2 p0, Point2 p1, Point2 p2, EdgeColor edgeColor = WHITE);+ static EdgeSegment *create(Point2 p0, Point2 p1, Point2 p2, Point2 p3, EdgeColor edgeColor = WHITE);++ EdgeSegment(EdgeColor edgeColor = WHITE) : color(edgeColor) { }+ virtual ~EdgeSegment() { }+ /// Creates a copy of the edge segment.+ virtual EdgeSegment *clone() const = 0;+ /// Returns the numeric code of the edge segment's type.+ virtual int type() const = 0;+ /// Returns the array of control points.+ virtual const Point2 *controlPoints() const = 0;+ /// Returns the point on the edge specified by the parameter (between 0 and 1).+ virtual Point2 point(double param) const = 0;+ /// Returns the direction the edge has at the point specified by the parameter.+ virtual Vector2 direction(double param) const = 0;+ /// Returns the change of direction (second derivative) at the point specified by the parameter.+ virtual Vector2 directionChange(double param) const = 0;+ /// Returns the minimum signed distance between origin and the edge.+ virtual SignedDistance signedDistance(Point2 origin, double ¶m) const = 0;+ /// Converts a previously retrieved signed distance from origin to perpendicular distance.+ virtual void distanceToPerpendicularDistance(SignedDistance &distance, Point2 origin, double param) const;+ /// Outputs a list of (at most three) intersections (their X coordinates) with an infinite horizontal scanline at y and returns how many there are.+ virtual int scanlineIntersections(double x[3], int dy[3], double y) const = 0;+ /// Adjusts the bounding box to fit the edge segment.+ virtual void bound(double &xMin, double &yMin, double &xMax, double &yMax) const = 0;++ /// Reverses the edge (swaps its start point and end point).+ virtual void reverse() = 0;+ /// Moves the start point of the edge segment.+ virtual void moveStartPoint(Point2 to) = 0;+ /// Moves the end point of the edge segment.+ virtual void moveEndPoint(Point2 to) = 0;+ /// Splits the edge segments into thirds which together represent the original edge.+ virtual void splitInThirds(EdgeSegment *&part0, EdgeSegment *&part1, EdgeSegment *&part2) const = 0;++};++/// A line segment.+class LinearSegment : public EdgeSegment {++public:+ enum EdgeType {+ EDGE_TYPE = 1+ };++ Point2 p[2];++ LinearSegment(Point2 p0, Point2 p1, EdgeColor edgeColor = WHITE);+ LinearSegment *clone() const;+ int type() const;+ const Point2 *controlPoints() const;+ Point2 point(double param) const;+ Vector2 direction(double param) const;+ Vector2 directionChange(double param) const;+ double length() const;+ SignedDistance signedDistance(Point2 origin, double ¶m) const;+ int scanlineIntersections(double x[3], int dy[3], double y) const;+ void bound(double &xMin, double &yMin, double &xMax, double &yMax) const;++ void reverse();+ void moveStartPoint(Point2 to);+ void moveEndPoint(Point2 to);+ void splitInThirds(EdgeSegment *&part0, EdgeSegment *&part1, EdgeSegment *&part2) const;++};++/// A quadratic Bezier curve.+class QuadraticSegment : public EdgeSegment {++public:+ enum EdgeType {+ EDGE_TYPE = 2+ };++ Point2 p[3];++ QuadraticSegment(Point2 p0, Point2 p1, Point2 p2, EdgeColor edgeColor = WHITE);+ QuadraticSegment *clone() const;+ int type() const;+ const Point2 *controlPoints() const;+ Point2 point(double param) const;+ Vector2 direction(double param) const;+ Vector2 directionChange(double param) const;+ double length() const;+ SignedDistance signedDistance(Point2 origin, double ¶m) const;+ int scanlineIntersections(double x[3], int dy[3], double y) const;+ void bound(double &xMin, double &yMin, double &xMax, double &yMax) const;++ void reverse();+ void moveStartPoint(Point2 to);+ void moveEndPoint(Point2 to);+ void splitInThirds(EdgeSegment *&part0, EdgeSegment *&part1, EdgeSegment *&part2) const;++ EdgeSegment *convertToCubic() const;++};++/// A cubic Bezier curve.+class CubicSegment : public EdgeSegment {++public:+ enum EdgeType {+ EDGE_TYPE = 3+ };++ Point2 p[4];++ CubicSegment(Point2 p0, Point2 p1, Point2 p2, Point2 p3, EdgeColor edgeColor = WHITE);+ CubicSegment *clone() const;+ int type() const;+ const Point2 *controlPoints() const;+ Point2 point(double param) const;+ Vector2 direction(double param) const;+ Vector2 directionChange(double param) const;+ SignedDistance signedDistance(Point2 origin, double ¶m) const;+ int scanlineIntersections(double x[3], int dy[3], double y) const;+ void bound(double &xMin, double &yMin, double &xMax, double &yMax) const;++ void reverse();+ void moveStartPoint(Point2 to);+ void moveEndPoint(Point2 to);+ void splitInThirds(EdgeSegment *&part0, EdgeSegment *&part1, EdgeSegment *&part2) const;++};++}diff --git a/third_party/msdfgen/core/edge-selectors.cpp b/third_party/msdfgen/core/edge-selectors.cppnew file mode 100644index 000000000..f3559ea35--- /dev/null+++ b/third_party/msdfgen/core/edge-selectors.cpp@@ -0,0 +1,262 @@++#include "edge-selectors.h"++#include "arithmetics.hpp"++namespace msdfgen {++#define DISTANCE_DELTA_FACTOR 1.001++TrueDistanceSelector::EdgeCache::EdgeCache() : absDistance(0) { }++void TrueDistanceSelector::reset(const Point2 &p) {+ double delta = DISTANCE_DELTA_FACTOR*(p-this->p).length();+ // Since minDistance.distance is initialized to -DBL_MAX, at first glance this seems like it could make it underflow to -infinity, but in practice delta would have to be extremely high for this to happen (above 9e291)+ minDistance.distance += nonZeroSign(minDistance.distance)*delta;+ this->p = p;+}++void TrueDistanceSelector::addEdge(EdgeCache &cache, const EdgeSegment *prevEdge, const EdgeSegment *edge, const EdgeSegment *nextEdge) {+ double delta = DISTANCE_DELTA_FACTOR*(p-cache.point).length();+ if (cache.absDistance-delta <= fabs(minDistance.distance)) {+ double dummy;+ SignedDistance distance = edge->signedDistance(p, dummy);+ if (distance < minDistance)+ minDistance = distance;+ cache.point = p;+ cache.absDistance = fabs(distance.distance);+ }+}++void TrueDistanceSelector::merge(const TrueDistanceSelector &other) {+ if (other.minDistance < minDistance)+ minDistance = other.minDistance;+}++TrueDistanceSelector::DistanceType TrueDistanceSelector::distance() const {+ return minDistance.distance;+}++PerpendicularDistanceSelectorBase::EdgeCache::EdgeCache() : absDistance(0), aDomainDistance(0), bDomainDistance(0), aPerpendicularDistance(0), bPerpendicularDistance(0) { }++bool PerpendicularDistanceSelectorBase::getPerpendicularDistance(double &distance, const Vector2 &ep, const Vector2 &edgeDir) {+ double ts = dotProduct(ep, edgeDir);+ if (ts > 0) {+ double perpendicularDistance = crossProduct(ep, edgeDir);+ if (fabs(perpendicularDistance) < fabs(distance)) {+ distance = perpendicularDistance;+ return true;+ }+ }+ return false;+}++PerpendicularDistanceSelectorBase::PerpendicularDistanceSelectorBase() : minNegativePerpendicularDistance(-fabs(minTrueDistance.distance)), minPositivePerpendicularDistance(fabs(minTrueDistance.distance)), nearEdge(NULL), nearEdgeParam(0) { }++void PerpendicularDistanceSelectorBase::reset(double delta) {+ minTrueDistance.distance += nonZeroSign(minTrueDistance.distance)*delta;+ minNegativePerpendicularDistance = -fabs(minTrueDistance.distance);+ minPositivePerpendicularDistance = fabs(minTrueDistance.distance);+ nearEdge = NULL;+ nearEdgeParam = 0;+}++bool PerpendicularDistanceSelectorBase::isEdgeRelevant(const EdgeCache &cache, const EdgeSegment *, const Point2 &p) const {+ double delta = DISTANCE_DELTA_FACTOR*(p-cache.point).length();+ return (+ cache.absDistance-delta <= fabs(minTrueDistance.distance) ||+ fabs(cache.aDomainDistance) < delta ||+ fabs(cache.bDomainDistance) < delta ||+ (cache.aDomainDistance > 0 && (cache.aPerpendicularDistance < 0 ?+ cache.aPerpendicularDistance+delta >= minNegativePerpendicularDistance :+ cache.aPerpendicularDistance-delta <= minPositivePerpendicularDistance+ )) ||+ (cache.bDomainDistance > 0 && (cache.bPerpendicularDistance < 0 ?+ cache.bPerpendicularDistance+delta >= minNegativePerpendicularDistance :+ cache.bPerpendicularDistance-delta <= minPositivePerpendicularDistance+ ))+ );+}++void PerpendicularDistanceSelectorBase::addEdgeTrueDistance(const EdgeSegment *edge, const SignedDistance &distance, double param) {+ if (distance < minTrueDistance) {+ minTrueDistance = distance;+ nearEdge = edge;+ nearEdgeParam = param;+ }+}++void PerpendicularDistanceSelectorBase::addEdgePerpendicularDistance(double distance) {+ if (distance <= 0 && distance > minNegativePerpendicularDistance)+ minNegativePerpendicularDistance = distance;+ if (distance >= 0 && distance < minPositivePerpendicularDistance)+ minPositivePerpendicularDistance = distance;+}++void PerpendicularDistanceSelectorBase::merge(const PerpendicularDistanceSelectorBase &other) {+ if (other.minTrueDistance < minTrueDistance) {+ minTrueDistance = other.minTrueDistance;+ nearEdge = other.nearEdge;+ nearEdgeParam = other.nearEdgeParam;+ }+ if (other.minNegativePerpendicularDistance > minNegativePerpendicularDistance)+ minNegativePerpendicularDistance = other.minNegativePerpendicularDistance;+ if (other.minPositivePerpendicularDistance < minPositivePerpendicularDistance)+ minPositivePerpendicularDistance = other.minPositivePerpendicularDistance;+}++double PerpendicularDistanceSelectorBase::computeDistance(const Point2 &p) const {+ double minDistance = minTrueDistance.distance < 0 ? minNegativePerpendicularDistance : minPositivePerpendicularDistance;+ if (nearEdge) {+ SignedDistance distance = minTrueDistance;+ nearEdge->distanceToPerpendicularDistance(distance, p, nearEdgeParam);+ if (fabs(distance.distance) < fabs(minDistance))+ minDistance = distance.distance;+ }+ return minDistance;+}++SignedDistance PerpendicularDistanceSelectorBase::trueDistance() const {+ return minTrueDistance;+}++void PerpendicularDistanceSelector::reset(const Point2 &p) {+ double delta = DISTANCE_DELTA_FACTOR*(p-this->p).length();+ PerpendicularDistanceSelectorBase::reset(delta);+ this->p = p;+}++void PerpendicularDistanceSelector::addEdge(EdgeCache &cache, const EdgeSegment *prevEdge, const EdgeSegment *edge, const EdgeSegment *nextEdge) {+ if (isEdgeRelevant(cache, edge, p)) {+ double param;+ SignedDistance distance = edge->signedDistance(p, param);+ addEdgeTrueDistance(edge, distance, param);+ cache.point = p;+ cache.absDistance = fabs(distance.distance);++ Vector2 ap = p-edge->point(0);+ Vector2 bp = p-edge->point(1);+ Vector2 aDir = edge->direction(0).normalize(true);+ Vector2 bDir = edge->direction(1).normalize(true);+ Vector2 prevDir = prevEdge->direction(1).normalize(true);+ Vector2 nextDir = nextEdge->direction(0).normalize(true);+ double add = dotProduct(ap, (prevDir+aDir).normalize(true));+ double bdd = -dotProduct(bp, (bDir+nextDir).normalize(true));+ if (add > 0) {+ double pd = distance.distance;+ if (getPerpendicularDistance(pd, ap, -aDir))+ addEdgePerpendicularDistance(pd = -pd);+ cache.aPerpendicularDistance = pd;+ }+ if (bdd > 0) {+ double pd = distance.distance;+ if (getPerpendicularDistance(pd, bp, bDir))+ addEdgePerpendicularDistance(pd);+ cache.bPerpendicularDistance = pd;+ }+ cache.aDomainDistance = add;+ cache.bDomainDistance = bdd;+ }+}++PerpendicularDistanceSelector::DistanceType PerpendicularDistanceSelector::distance() const {+ return computeDistance(p);+}++void MultiDistanceSelector::reset(const Point2 &p) {+ double delta = DISTANCE_DELTA_FACTOR*(p-this->p).length();+ r.reset(delta);+ g.reset(delta);+ b.reset(delta);+ this->p = p;+}++void MultiDistanceSelector::addEdge(EdgeCache &cache, const EdgeSegment *prevEdge, const EdgeSegment *edge, const EdgeSegment *nextEdge) {+ if (+ (edge->color&RED && r.isEdgeRelevant(cache, edge, p)) ||+ (edge->color&GREEN && g.isEdgeRelevant(cache, edge, p)) ||+ (edge->color&BLUE && b.isEdgeRelevant(cache, edge, p))+ ) {+ double param;+ SignedDistance distance = edge->signedDistance(p, param);+ if (edge->color&RED)+ r.addEdgeTrueDistance(edge, distance, param);+ if (edge->color&GREEN)+ g.addEdgeTrueDistance(edge, distance, param);+ if (edge->color&BLUE)+ b.addEdgeTrueDistance(edge, distance, param);+ cache.point = p;+ cache.absDistance = fabs(distance.distance);++ Vector2 ap = p-edge->point(0);+ Vector2 bp = p-edge->point(1);+ Vector2 aDir = edge->direction(0).normalize(true);+ Vector2 bDir = edge->direction(1).normalize(true);+ Vector2 prevDir = prevEdge->direction(1).normalize(true);+ Vector2 nextDir = nextEdge->direction(0).normalize(true);+ double add = dotProduct(ap, (prevDir+aDir).normalize(true));+ double bdd = -dotProduct(bp, (bDir+nextDir).normalize(true));+ if (add > 0) {+ double pd = distance.distance;+ if (PerpendicularDistanceSelectorBase::getPerpendicularDistance(pd, ap, -aDir)) {+ pd = -pd;+ if (edge->color&RED)+ r.addEdgePerpendicularDistance(pd);+ if (edge->color&GREEN)+ g.addEdgePerpendicularDistance(pd);+ if (edge->color&BLUE)+ b.addEdgePerpendicularDistance(pd);+ }+ cache.aPerpendicularDistance = pd;+ }+ if (bdd > 0) {+ double pd = distance.distance;+ if (PerpendicularDistanceSelectorBase::getPerpendicularDistance(pd, bp, bDir)) {+ if (edge->color&RED)+ r.addEdgePerpendicularDistance(pd);+ if (edge->color&GREEN)+ g.addEdgePerpendicularDistance(pd);+ if (edge->color&BLUE)+ b.addEdgePerpendicularDistance(pd);+ }+ cache.bPerpendicularDistance = pd;+ }+ cache.aDomainDistance = add;+ cache.bDomainDistance = bdd;+ }+}++void MultiDistanceSelector::merge(const MultiDistanceSelector &other) {+ r.merge(other.r);+ g.merge(other.g);+ b.merge(other.b);+}++MultiDistanceSelector::DistanceType MultiDistanceSelector::distance() const {+ MultiDistance multiDistance;+ multiDistance.r = r.computeDistance(p);+ multiDistance.g = g.computeDistance(p);+ multiDistance.b = b.computeDistance(p);+ return multiDistance;+}++SignedDistance MultiDistanceSelector::trueDistance() const {+ SignedDistance distance = r.trueDistance();+ if (g.trueDistance() < distance)+ distance = g.trueDistance();+ if (b.trueDistance() < distance)+ distance = b.trueDistance();+ return distance;+}++MultiAndTrueDistanceSelector::DistanceType MultiAndTrueDistanceSelector::distance() const {+ MultiDistance multiDistance = MultiDistanceSelector::distance();+ MultiAndTrueDistance mtd;+ mtd.r = multiDistance.r;+ mtd.g = multiDistance.g;+ mtd.b = multiDistance.b;+ mtd.a = trueDistance().distance;+ return mtd;+}++}diff --git a/third_party/msdfgen/core/edge-selectors.h b/third_party/msdfgen/core/edge-selectors.hnew file mode 100644index 000000000..59337141d--- /dev/null+++ b/third_party/msdfgen/core/edge-selectors.h@@ -0,0 +1,117 @@++#pragma once++#include "Vector2.hpp"+#include "SignedDistance.hpp"+#include "edge-segments.h"++namespace msdfgen {++struct MultiDistance {+ double r, g, b;+};+struct MultiAndTrueDistance : MultiDistance {+ double a;+};++/// Selects the nearest edge by its true distance.+class TrueDistanceSelector {++public:+ typedef double DistanceType;++ struct EdgeCache {+ Point2 point;+ double absDistance;++ EdgeCache();+ };++ void reset(const Point2 &p);+ void addEdge(EdgeCache &cache, const EdgeSegment *prevEdge, const EdgeSegment *edge, const EdgeSegment *nextEdge);+ void merge(const TrueDistanceSelector &other);+ DistanceType distance() const;++private:+ Point2 p;+ SignedDistance minDistance;++};++class PerpendicularDistanceSelectorBase {++public:+ struct EdgeCache {+ Point2 point;+ double absDistance;+ double aDomainDistance, bDomainDistance;+ double aPerpendicularDistance, bPerpendicularDistance;++ EdgeCache();+ };++ static bool getPerpendicularDistance(double &distance, const Vector2 &ep, const Vector2 &edgeDir);++ PerpendicularDistanceSelectorBase();+ void reset(double delta);+ bool isEdgeRelevant(const EdgeCache &cache, const EdgeSegment *edge, const Point2 &p) const;+ void addEdgeTrueDistance(const EdgeSegment *edge, const SignedDistance &distance, double param);+ void addEdgePerpendicularDistance(double distance);+ void merge(const PerpendicularDistanceSelectorBase &other);+ double computeDistance(const Point2 &p) const;+ SignedDistance trueDistance() const;++private:+ SignedDistance minTrueDistance;+ double minNegativePerpendicularDistance;+ double minPositivePerpendicularDistance;+ const EdgeSegment *nearEdge;+ double nearEdgeParam;++};++/// Selects the nearest edge by its perpendicular distance.+class PerpendicularDistanceSelector : public PerpendicularDistanceSelectorBase {++public:+ typedef double DistanceType;++ void reset(const Point2 &p);+ void addEdge(EdgeCache &cache, const EdgeSegment *prevEdge, const EdgeSegment *edge, const EdgeSegment *nextEdge);+ DistanceType distance() const;++private:+ Point2 p;++};++/// Selects the nearest edge for each of the three channels by its perpendicular distance.+class MultiDistanceSelector {++public:+ typedef MultiDistance DistanceType;+ typedef PerpendicularDistanceSelectorBase::EdgeCache EdgeCache;++ void reset(const Point2 &p);+ void addEdge(EdgeCache &cache, const EdgeSegment *prevEdge, const EdgeSegment *edge, const EdgeSegment *nextEdge);+ void merge(const MultiDistanceSelector &other);+ DistanceType distance() const;+ SignedDistance trueDistance() const;++private:+ Point2 p;+ PerpendicularDistanceSelectorBase r, g, b;++};++/// Selects the nearest edge for each of the three color channels by its perpendicular distance and by true distance for the alpha channel.+class MultiAndTrueDistanceSelector : public MultiDistanceSelector {++public:+ typedef MultiAndTrueDistance DistanceType;++ DistanceType distance() const;++};++}diff --git a/third_party/msdfgen/core/equation-solver.cpp b/third_party/msdfgen/core/equation-solver.cppnew file mode 100644index 000000000..7c1cbb39f--- /dev/null+++ b/third_party/msdfgen/core/equation-solver.cpp@@ -0,0 +1,72 @@++#include "equation-solver.h"++#define _USE_MATH_DEFINES+#include <cmath>++namespace msdfgen {++int solveQuadratic(double x[2], double a, double b, double c) {+ // a == 0 -> linear equation+ if (a == 0 || fabs(b) > 1e12*fabs(a)) {+ // a == 0, b == 0 -> no solution+ if (b == 0) {+ if (c == 0)+ return -1; // 0 == 0+ return 0;+ }+ x[0] = -c/b;+ return 1;+ }+ double dscr = b*b-4*a*c;+ if (dscr > 0) {+ dscr = sqrt(dscr);+ x[0] = (-b+dscr)/(2*a);+ x[1] = (-b-dscr)/(2*a);+ return 2;+ } else if (dscr == 0) {+ x[0] = -b/(2*a);+ return 1;+ } else+ return 0;+}++static int solveCubicNormed(double x[3], double a, double b, double c) {+ double a2 = a*a;+ double q = 1/9.*(a2-3*b);+ double r = 1/54.*(a*(2*a2-9*b)+27*c);+ double r2 = r*r;+ double q3 = q*q*q;+ a *= 1/3.;+ if (r2 < q3) {+ double t = r/sqrt(q3);+ if (t < -1) t = -1;+ if (t > 1) t = 1;+ t = acos(t);+ q = -2*sqrt(q);+ x[0] = q*cos(1/3.*t)-a;+ x[1] = q*cos(1/3.*(t+2*M_PI))-a;+ x[2] = q*cos(1/3.*(t-2*M_PI))-a;+ return 3;+ } else {+ double u = (r < 0 ? 1 : -1)*pow(fabs(r)+sqrt(r2-q3), 1/3.);+ double v = u == 0 ? 0 : q/u;+ x[0] = (u+v)-a;+ if (u == v || fabs(u-v) < 1e-12*fabs(u+v)) {+ x[1] = -.5*(u+v)-a;+ return 2;+ }+ return 1;+ }+}++int solveCubic(double x[3], double a, double b, double c, double d) {+ if (a != 0) {+ double bn = b/a;+ if (fabs(bn) < 1e6) // Above this ratio, the numerical error gets larger than if we treated a as zero+ return solveCubicNormed(x, bn, c/a, d/a);+ }+ return solveQuadratic(x, b, c, d);+}++}diff --git a/third_party/msdfgen/core/equation-solver.h b/third_party/msdfgen/core/equation-solver.hnew file mode 100644index 000000000..bfeeb1582--- /dev/null+++ b/third_party/msdfgen/core/equation-solver.h@@ -0,0 +1,14 @@++#pragma once++#include "base.h"++namespace msdfgen {++// ax^2 + bx + c = 0+int solveQuadratic(double x[2], double a, double b, double c);++// ax^3 + bx^2 + cx + d = 0+int solveCubic(double x[3], double a, double b, double c, double d);++}diff --git a/third_party/msdfgen/core/export-svg.cpp b/third_party/msdfgen/core/export-svg.cppnew file mode 100644index 000000000..0a2770857--- /dev/null+++ b/third_party/msdfgen/core/export-svg.cpp@@ -0,0 +1,79 @@++#include "export-svg.h"++#include <cstdio>+#include "edge-segments.h"++namespace msdfgen {++static void writeSvgCoord(FILE *f, Point2 coord) {+ fprintf(f, "%.17g %.17g", coord.x, coord.y);+}++static void writeSvgPathDef(FILE *f, const Shape &shape) {+ bool beginning = true;+ for (const Contour &c : shape.contours) {+ if (c.edges.empty())+ continue;+ if (beginning)+ beginning = false;+ else+ fputc(' ', f);+ fputs("M ", f);+ writeSvgCoord(f, c.edges[0]->controlPoints()[0]);+ for (const EdgeHolder &e : c.edges) {+ const Point2 *cp = e->controlPoints();+ switch (e->type()) {+ case (int) LinearSegment::EDGE_TYPE:+ fputs(" L ", f);+ writeSvgCoord(f, cp[1]);+ break;+ case (int) QuadraticSegment::EDGE_TYPE:+ fputs(" Q ", f);+ writeSvgCoord(f, cp[1]);+ fputc(' ', f);+ writeSvgCoord(f, cp[2]);+ break;+ case (int) CubicSegment::EDGE_TYPE:+ fputs(" C ", f);+ writeSvgCoord(f, cp[1]);+ fputc(' ', f);+ writeSvgCoord(f, cp[2]);+ fputc(' ', f);+ writeSvgCoord(f, cp[3]);+ break;+ }+ }+ fputs(" Z", f);+ }+}++bool saveSvgShape(const Shape &shape, const char *filename) {+ if (FILE *f = fopen(filename, "w")) {+ fputs("<svg xmlns=\"http://www.w3.org/2000/svg\"><path", f);+ if (shape.getYAxisOrientation() == Y_UPWARD)+ fputs(" transform=\"scale(1 -1)\"", f);+ fputs(" d=\"", f);+ writeSvgPathDef(f, shape);+ fputs("\"/></svg>\n", f);+ fclose(f);+ return true;+ }+ return false;+}++bool saveSvgShape(const Shape &shape, const Shape::Bounds &bounds, const char *filename) {+ if (FILE *f = fopen(filename, "w")) {+ fprintf(f, "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"%.17g %.17g %.17g %.17g\"><path", bounds.l, bounds.b, bounds.r-bounds.l, bounds.t-bounds.b);+ if (shape.getYAxisOrientation() == Y_UPWARD)+ fprintf(f, " transform=\"translate(0 %.17g) scale(1 -1)\"", bounds.b+bounds.t);+ fputs(" d=\"", f);+ writeSvgPathDef(f, shape);+ fputs("\"/></svg>\n", f);+ fclose(f);+ return true;+ }+ return false;+}++}diff --git a/third_party/msdfgen/core/export-svg.h b/third_party/msdfgen/core/export-svg.hnew file mode 100644index 000000000..64b45531f--- /dev/null+++ b/third_party/msdfgen/core/export-svg.h@@ -0,0 +1,11 @@++#pragma once++#include "Shape.h"++namespace msdfgen {++bool saveSvgShape(const Shape &shape, const char *filename);+bool saveSvgShape(const Shape &shape, const Shape::Bounds &bounds, const char *filename);++}diff --git a/third_party/msdfgen/core/generator-config.h b/third_party/msdfgen/core/generator-config.hnew file mode 100644index 000000000..b7b153477--- /dev/null+++ b/third_party/msdfgen/core/generator-config.h@@ -0,0 +1,66 @@++#pragma once++#include "BitmapRef.hpp"++#ifndef MSDFGEN_PUBLIC+#define MSDFGEN_PUBLIC // for DLL import/export+#endif++namespace msdfgen {++/// The configuration of the MSDF error correction pass.+struct ErrorCorrectionConfig {+ /// The default value of minDeviationRatio.+ static MSDFGEN_PUBLIC const double defaultMinDeviationRatio;+ /// The default value of minImproveRatio.+ static MSDFGEN_PUBLIC const double defaultMinImproveRatio;++ /// Mode of operation.+ enum Mode {+ /// Skips error correction pass.+ DISABLED,+ /// Corrects all discontinuities of the distance field regardless if edges are adversely affected.+ INDISCRIMINATE,+ /// Corrects artifacts at edges and other discontinuous distances only if it does not affect edges or corners.+ EDGE_PRIORITY,+ /// Only corrects artifacts at edges.+ EDGE_ONLY+ } mode;+ /// Configuration of whether to use an algorithm that computes the exact shape distance at the positions of suspected artifacts. This algorithm can be much slower.+ enum DistanceCheckMode {+ /// Never computes exact shape distance.+ DO_NOT_CHECK_DISTANCE,+ /// Only computes exact shape distance at edges. Provides a good balance between speed and precision.+ CHECK_DISTANCE_AT_EDGE,+ /// Computes and compares the exact shape distance for each suspected artifact.+ ALWAYS_CHECK_DISTANCE+ } distanceCheckMode;+ /// The minimum ratio between the actual and maximum expected distance delta to be considered an error.+ double minDeviationRatio;+ /// The minimum ratio between the pre-correction distance error and the post-correction distance error. Has no effect for DO_NOT_CHECK_DISTANCE.+ double minImproveRatio;+ /// An optional buffer to avoid dynamic allocation. Must have at least as many bytes as the MSDF has pixels.+ byte *buffer;++ inline explicit ErrorCorrectionConfig(Mode mode = EDGE_PRIORITY, DistanceCheckMode distanceCheckMode = CHECK_DISTANCE_AT_EDGE, double minDeviationRatio = defaultMinDeviationRatio, double minImproveRatio = defaultMinImproveRatio, byte *buffer = NULL) : mode(mode), distanceCheckMode(distanceCheckMode), minDeviationRatio(minDeviationRatio), minImproveRatio(minImproveRatio), buffer(buffer) { }+};++/// The configuration of the distance field generator algorithm.+struct GeneratorConfig {+ /// Specifies whether to use the version of the algorithm that supports overlapping contours with the same winding. May be set to false to improve performance when no such contours are present.+ bool overlapSupport;++ inline explicit GeneratorConfig(bool overlapSupport = true) : overlapSupport(overlapSupport) { }+};++/// The configuration of the multi-channel distance field generator algorithm.+struct MSDFGeneratorConfig : GeneratorConfig {+ /// Configuration of the error correction pass.+ ErrorCorrectionConfig errorCorrection;++ inline MSDFGeneratorConfig() { }+ inline explicit MSDFGeneratorConfig(bool overlapSupport, const ErrorCorrectionConfig &errorCorrection = ErrorCorrectionConfig()) : GeneratorConfig(overlapSupport), errorCorrection(errorCorrection) { }+};++}diff --git a/third_party/msdfgen/core/msdf-error-correction.cpp b/third_party/msdfgen/core/msdf-error-correction.cppnew file mode 100644index 000000000..43de1a095--- /dev/null+++ b/third_party/msdfgen/core/msdf-error-correction.cpp@@ -0,0 +1,183 @@++#include "msdf-error-correction.h"++#include <vector>+#include "arithmetics.hpp"+#include "Bitmap.h"+#include "contour-combiners.h"+#include "MSDFErrorCorrection.h"++namespace msdfgen {++template <int N>+static void msdfErrorCorrectionInner(const BitmapSection<float, N> &sdf, const Shape &shape, const SDFTransformation &transformation, const MSDFGeneratorConfig &config) {+ if (config.errorCorrection.mode == ErrorCorrectionConfig::DISABLED)+ return;+ Bitmap<byte, 1> stencilBuffer;+ if (!config.errorCorrection.buffer)+ stencilBuffer = Bitmap<byte, 1>(sdf.width, sdf.height);+ BitmapSection<byte, 1> stencil(NULL, sdf.width, sdf.height);+ stencil.pixels = config.errorCorrection.buffer ? config.errorCorrection.buffer : (byte *) stencilBuffer;+ MSDFErrorCorrection ec(stencil, transformation);+ ec.setMinDeviationRatio(config.errorCorrection.minDeviationRatio);+ ec.setMinImproveRatio(config.errorCorrection.minImproveRatio);+ switch (config.errorCorrection.mode) {+ case ErrorCorrectionConfig::DISABLED:+ case ErrorCorrectionConfig::INDISCRIMINATE:+ break;+ case ErrorCorrectionConfig::EDGE_PRIORITY:+ ec.protectCorners(shape);+ ec.protectEdges<N>(sdf);+ break;+ case ErrorCorrectionConfig::EDGE_ONLY:+ ec.protectAll();+ break;+ }+ if (config.errorCorrection.distanceCheckMode == ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE || (config.errorCorrection.distanceCheckMode == ErrorCorrectionConfig::CHECK_DISTANCE_AT_EDGE && config.errorCorrection.mode != ErrorCorrectionConfig::EDGE_ONLY)) {+ ec.findErrors<N>(sdf);+ if (config.errorCorrection.distanceCheckMode == ErrorCorrectionConfig::CHECK_DISTANCE_AT_EDGE)+ ec.protectAll();+ }+ if (config.errorCorrection.distanceCheckMode == ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE || config.errorCorrection.distanceCheckMode == ErrorCorrectionConfig::CHECK_DISTANCE_AT_EDGE) {+ if (config.overlapSupport)+ ec.findErrors<OverlappingContourCombiner, N>(sdf, shape);+ else+ ec.findErrors<SimpleContourCombiner, N>(sdf, shape);+ }+ ec.apply(sdf);+}++template <int N>+static void msdfErrorCorrectionShapeless(const BitmapSection<float, N> &sdf, const SDFTransformation &transformation, double minDeviationRatio, bool protectAll) {+ Bitmap<byte, 1> stencilBuffer(sdf.width, sdf.height);+ MSDFErrorCorrection ec(stencilBuffer, transformation);+ ec.setMinDeviationRatio(minDeviationRatio);+ if (protectAll)+ ec.protectAll();+ ec.findErrors<N>(sdf);+ ec.apply(sdf);+}++void msdfErrorCorrection(const BitmapSection<float, 3> &sdf, const Shape &shape, const SDFTransformation &transformation, const MSDFGeneratorConfig &config) {+ msdfErrorCorrectionInner(sdf, shape, transformation, config);+}+void msdfErrorCorrection(const BitmapSection<float, 4> &sdf, const Shape &shape, const SDFTransformation &transformation, const MSDFGeneratorConfig &config) {+ msdfErrorCorrectionInner(sdf, shape, transformation, config);+}+void msdfErrorCorrection(const BitmapSection<float, 3> &sdf, const Shape &shape, const Projection &projection, Range range, const MSDFGeneratorConfig &config) {+ msdfErrorCorrectionInner(sdf, shape, SDFTransformation(projection, range), config);+}+void msdfErrorCorrection(const BitmapSection<float, 4> &sdf, const Shape &shape, const Projection &projection, Range range, const MSDFGeneratorConfig &config) {+ msdfErrorCorrectionInner(sdf, shape, SDFTransformation(projection, range), config);+}++void msdfFastDistanceErrorCorrection(const BitmapSection<float, 3> &sdf, const SDFTransformation &transformation, double minDeviationRatio) {+ msdfErrorCorrectionShapeless(sdf, transformation, minDeviationRatio, false);+}+void msdfFastDistanceErrorCorrection(const BitmapSection<float, 4> &sdf, const SDFTransformation &transformation, double minDeviationRatio) {+ msdfErrorCorrectionShapeless(sdf, transformation, minDeviationRatio, false);+}+void msdfFastDistanceErrorCorrection(const BitmapSection<float, 3> &sdf, const Projection &projection, Range range, double minDeviationRatio) {+ msdfErrorCorrectionShapeless(sdf, SDFTransformation(projection, range), minDeviationRatio, false);+}+void msdfFastDistanceErrorCorrection(const BitmapSection<float, 4> &sdf, const Projection &projection, Range range, double minDeviationRatio) {+ msdfErrorCorrectionShapeless(sdf, SDFTransformation(projection, range), minDeviationRatio, false);+}+void msdfFastDistanceErrorCorrection(const BitmapSection<float, 3> &sdf, Range pxRange, double minDeviationRatio) {+ msdfErrorCorrectionShapeless(sdf, SDFTransformation(Projection(), pxRange), minDeviationRatio, false);+}+void msdfFastDistanceErrorCorrection(const BitmapSection<float, 4> &sdf, Range pxRange, double minDeviationRatio) {+ msdfErrorCorrectionShapeless(sdf, SDFTransformation(Projection(), pxRange), minDeviationRatio, false);+}++void msdfFastEdgeErrorCorrection(const BitmapSection<float, 3> &sdf, const SDFTransformation &transformation, double minDeviationRatio) {+ msdfErrorCorrectionShapeless(sdf, transformation, minDeviationRatio, true);+}+void msdfFastEdgeErrorCorrection(const BitmapSection<float, 4> &sdf, const SDFTransformation &transformation, double minDeviationRatio) {+ msdfErrorCorrectionShapeless(sdf, transformation, minDeviationRatio, true);+}+void msdfFastEdgeErrorCorrection(const BitmapSection<float, 3> &sdf, const Projection &projection, Range range, double minDeviationRatio) {+ msdfErrorCorrectionShapeless(sdf, SDFTransformation(projection, range), minDeviationRatio, true);+}+void msdfFastEdgeErrorCorrection(const BitmapSection<float, 4> &sdf, const Projection &projection, Range range, double minDeviationRatio) {+ msdfErrorCorrectionShapeless(sdf, SDFTransformation(projection, range), minDeviationRatio, true);+}+void msdfFastEdgeErrorCorrection(const BitmapSection<float, 3> &sdf, Range pxRange, double minDeviationRatio) {+ msdfErrorCorrectionShapeless(sdf, SDFTransformation(Projection(), pxRange), minDeviationRatio, true);+}+void msdfFastEdgeErrorCorrection(const BitmapSection<float, 4> &sdf, Range pxRange, double minDeviationRatio) {+ msdfErrorCorrectionShapeless(sdf, SDFTransformation(Projection(), pxRange), minDeviationRatio, true);+}+++// Legacy version++inline static bool detectClash(const float *a, const float *b, double threshold) {+ // Sort channels so that pairs (a0, b0), (a1, b1), (a2, b2) go from biggest to smallest absolute difference+ float a0 = a[0], a1 = a[1], a2 = a[2];+ float b0 = b[0], b1 = b[1], b2 = b[2];+ float tmp;+ if (fabsf(b0-a0) < fabsf(b1-a1)) {+ tmp = a0, a0 = a1, a1 = tmp;+ tmp = b0, b0 = b1, b1 = tmp;+ }+ if (fabsf(b1-a1) < fabsf(b2-a2)) {+ tmp = a1, a1 = a2, a2 = tmp;+ tmp = b1, b1 = b2, b2 = tmp;+ if (fabsf(b0-a0) < fabsf(b1-a1)) {+ tmp = a0, a0 = a1, a1 = tmp;+ tmp = b0, b0 = b1, b1 = tmp;+ }+ }+ return (fabsf(b1-a1) >= threshold) &&+ !(b0 == b1 && b0 == b2) && // Ignore if other pixel has been equalized+ fabsf(a2-.5f) >= fabsf(b2-.5f); // Out of the pair, only flag the pixel farther from a shape edge+}++template <int N>+static void msdfErrorCorrectionInner_legacy(const BitmapSection<float, N> &output, const Vector2 &threshold) {+ std::vector<std::pair<int, int> > clashes;+ int w = output.width, h = output.height;+ for (int y = 0; y < h; ++y)+ for (int x = 0; x < w; ++x) {+ if (+ (x > 0 && detectClash(output(x, y), output(x-1, y), threshold.x)) ||+ (x < w-1 && detectClash(output(x, y), output(x+1, y), threshold.x)) ||+ (y > 0 && detectClash(output(x, y), output(x, y-1), threshold.y)) ||+ (y < h-1 && detectClash(output(x, y), output(x, y+1), threshold.y))+ )+ clashes.push_back(std::make_pair(x, y));+ }+ for (std::vector<std::pair<int, int> >::const_iterator clash = clashes.begin(); clash != clashes.end(); ++clash) {+ float *pixel = output(clash->first, clash->second);+ float med = median(pixel[0], pixel[1], pixel[2]);+ pixel[0] = med, pixel[1] = med, pixel[2] = med;+ }+#ifndef MSDFGEN_NO_DIAGONAL_CLASH_DETECTION+ clashes.clear();+ for (int y = 0; y < h; ++y)+ for (int x = 0; x < w; ++x) {+ if (+ (x > 0 && y > 0 && detectClash(output(x, y), output(x-1, y-1), threshold.x+threshold.y)) ||+ (x < w-1 && y > 0 && detectClash(output(x, y), output(x+1, y-1), threshold.x+threshold.y)) ||+ (x > 0 && y < h-1 && detectClash(output(x, y), output(x-1, y+1), threshold.x+threshold.y)) ||+ (x < w-1 && y < h-1 && detectClash(output(x, y), output(x+1, y+1), threshold.x+threshold.y))+ )+ clashes.push_back(std::make_pair(x, y));+ }+ for (std::vector<std::pair<int, int> >::const_iterator clash = clashes.begin(); clash != clashes.end(); ++clash) {+ float *pixel = output(clash->first, clash->second);+ float med = median(pixel[0], pixel[1], pixel[2]);+ pixel[0] = med, pixel[1] = med, pixel[2] = med;+ }+#endif+}++void msdfErrorCorrection_legacy(const BitmapSection<float, 3> &output, const Vector2 &threshold) {+ msdfErrorCorrectionInner_legacy(output, threshold);+}+void msdfErrorCorrection_legacy(const BitmapSection<float, 4> &output, const Vector2 &threshold) {+ msdfErrorCorrectionInner_legacy(output, threshold);+}++}diff --git a/third_party/msdfgen/core/msdf-error-correction.h b/third_party/msdfgen/core/msdf-error-correction.hnew file mode 100644index 000000000..3edc2510f--- /dev/null+++ b/third_party/msdfgen/core/msdf-error-correction.h@@ -0,0 +1,40 @@++#pragma once++#include "Vector2.hpp"+#include "Range.hpp"+#include "Projection.h"+#include "SDFTransformation.h"+#include "Shape.h"+#include "BitmapRef.hpp"+#include "generator-config.h"++namespace msdfgen {++/// Predicts potential artifacts caused by the interpolation of the MSDF and corrects them by converting nearby texels to single-channel.+void msdfErrorCorrection(const BitmapSection<float, 3> &sdf, const Shape &shape, const SDFTransformation &transformation, const MSDFGeneratorConfig &config = MSDFGeneratorConfig());+void msdfErrorCorrection(const BitmapSection<float, 4> &sdf, const Shape &shape, const SDFTransformation &transformation, const MSDFGeneratorConfig &config = MSDFGeneratorConfig());+void msdfErrorCorrection(const BitmapSection<float, 3> &sdf, const Shape &shape, const Projection &projection, Range range, const MSDFGeneratorConfig &config = MSDFGeneratorConfig());+void msdfErrorCorrection(const BitmapSection<float, 4> &sdf, const Shape &shape, const Projection &projection, Range range, const MSDFGeneratorConfig &config = MSDFGeneratorConfig());++/// Applies the simplified error correction to all discontiunous distances (INDISCRIMINATE mode). Does not need shape or translation.+void msdfFastDistanceErrorCorrection(const BitmapSection<float, 3> &sdf, const SDFTransformation &transformation, double minDeviationRatio = ErrorCorrectionConfig::defaultMinDeviationRatio);+void msdfFastDistanceErrorCorrection(const BitmapSection<float, 4> &sdf, const SDFTransformation &transformation, double minDeviationRatio = ErrorCorrectionConfig::defaultMinDeviationRatio);+void msdfFastDistanceErrorCorrection(const BitmapSection<float, 3> &sdf, const Projection &projection, Range range, double minDeviationRatio = ErrorCorrectionConfig::defaultMinDeviationRatio);+void msdfFastDistanceErrorCorrection(const BitmapSection<float, 4> &sdf, const Projection &projection, Range range, double minDeviationRatio = ErrorCorrectionConfig::defaultMinDeviationRatio);+void msdfFastDistanceErrorCorrection(const BitmapSection<float, 3> &sdf, Range pxRange, double minDeviationRatio = ErrorCorrectionConfig::defaultMinDeviationRatio);+void msdfFastDistanceErrorCorrection(const BitmapSection<float, 4> &sdf, Range pxRange, double minDeviationRatio = ErrorCorrectionConfig::defaultMinDeviationRatio);++/// Applies the simplified error correction to edges only (EDGE_ONLY mode). Does not need shape or translation.+void msdfFastEdgeErrorCorrection(const BitmapSection<float, 3> &sdf, const SDFTransformation &transformation, double minDeviationRatio = ErrorCorrectionConfig::defaultMinDeviationRatio);+void msdfFastEdgeErrorCorrection(const BitmapSection<float, 4> &sdf, const SDFTransformation &transformation, double minDeviationRatio = ErrorCorrectionConfig::defaultMinDeviationRatio);+void msdfFastEdgeErrorCorrection(const BitmapSection<float, 3> &sdf, const Projection &projection, Range range, double minDeviationRatio = ErrorCorrectionConfig::defaultMinDeviationRatio);+void msdfFastEdgeErrorCorrection(const BitmapSection<float, 4> &sdf, const Projection &projection, Range range, double minDeviationRatio = ErrorCorrectionConfig::defaultMinDeviationRatio);+void msdfFastEdgeErrorCorrection(const BitmapSection<float, 3> &sdf, Range pxRange, double minDeviationRatio = ErrorCorrectionConfig::defaultMinDeviationRatio);+void msdfFastEdgeErrorCorrection(const BitmapSection<float, 4> &sdf, Range pxRange, double minDeviationRatio = ErrorCorrectionConfig::defaultMinDeviationRatio);++/// The original version of the error correction algorithm.+void msdfErrorCorrection_legacy(const BitmapSection<float, 3> &output, const Vector2 &threshold);+void msdfErrorCorrection_legacy(const BitmapSection<float, 4> &output, const Vector2 &threshold);++}diff --git a/third_party/msdfgen/core/msdfgen.cpp b/third_party/msdfgen/core/msdfgen.cppnew file mode 100644index 000000000..6681c5314--- /dev/null+++ b/third_party/msdfgen/core/msdfgen.cpp@@ -0,0 +1,335 @@++#include "../msdfgen.h"++#include <vector>+#include "edge-selectors.h"+#include "contour-combiners.h"+#include "ShapeDistanceFinder.h"++namespace msdfgen {++template <typename DistanceType>+class DistancePixelConversion;++template <>+class DistancePixelConversion<double> {+ DistanceMapping mapping;+public:+ typedef BitmapSection<float, 1> BitmapSectionType;+ inline explicit DistancePixelConversion(DistanceMapping mapping) : mapping(mapping) { }+ inline void operator()(float *pixels, double distance) const {+ *pixels = float(mapping(distance));+ }+};++template <>+class DistancePixelConversion<MultiDistance> {+ DistanceMapping mapping;+public:+ typedef BitmapSection<float, 3> BitmapSectionType;+ inline explicit DistancePixelConversion(DistanceMapping mapping) : mapping(mapping) { }+ inline void operator()(float *pixels, const MultiDistance &distance) const {+ pixels[0] = float(mapping(distance.r));+ pixels[1] = float(mapping(distance.g));+ pixels[2] = float(mapping(distance.b));+ }+};++template <>+class DistancePixelConversion<MultiAndTrueDistance> {+ DistanceMapping mapping;+public:+ typedef BitmapSection<float, 4> BitmapSectionType;+ inline explicit DistancePixelConversion(DistanceMapping mapping) : mapping(mapping) { }+ inline void operator()(float *pixels, const MultiAndTrueDistance &distance) const {+ pixels[0] = float(mapping(distance.r));+ pixels[1] = float(mapping(distance.g));+ pixels[2] = float(mapping(distance.b));+ pixels[3] = float(mapping(distance.a));+ }+};++template <class ContourCombiner>+void generateDistanceField(typename DistancePixelConversion<typename ContourCombiner::DistanceType>::BitmapSectionType output, const Shape &shape, const SDFTransformation &transformation) {+ DistancePixelConversion<typename ContourCombiner::DistanceType> distancePixelConversion(transformation.distanceMapping);+ output.reorient(shape.getYAxisOrientation());+#ifdef MSDFGEN_USE_OPENMP+ #pragma omp parallel+#endif+ {+ ShapeDistanceFinder<ContourCombiner> distanceFinder(shape);+ int xDirection = 1;+#ifdef MSDFGEN_USE_OPENMP+ #pragma omp for+#endif+ for (int y = 0; y < output.height; ++y) {+ int x = xDirection < 0 ? output.width-1 : 0;+ for (int col = 0; col < output.width; ++col) {+ Point2 p = transformation.unproject(Point2(x+.5, y+.5));+ typename ContourCombiner::DistanceType distance = distanceFinder.distance(p);+ distancePixelConversion(output(x, y), distance);+ x += xDirection;+ }+ xDirection = -xDirection;+ }+ }+}++void generateSDF(const BitmapSection<float, 1> &output, const Shape &shape, const SDFTransformation &transformation, const GeneratorConfig &config) {+ if (config.overlapSupport)+ generateDistanceField<OverlappingContourCombiner<TrueDistanceSelector> >(output, shape, transformation);+ else+ generateDistanceField<SimpleContourCombiner<TrueDistanceSelector> >(output, shape, transformation);+}++void generatePSDF(const BitmapSection<float, 1> &output, const Shape &shape, const SDFTransformation &transformation, const GeneratorConfig &config) {+ if (config.overlapSupport)+ generateDistanceField<OverlappingContourCombiner<PerpendicularDistanceSelector> >(output, shape, transformation);+ else+ generateDistanceField<SimpleContourCombiner<PerpendicularDistanceSelector> >(output, shape, transformation);+}++void generateMSDF(const BitmapSection<float, 3> &output, const Shape &shape, const SDFTransformation &transformation, const MSDFGeneratorConfig &config) {+ if (config.overlapSupport)+ generateDistanceField<OverlappingContourCombiner<MultiDistanceSelector> >(output, shape, transformation);+ else+ generateDistanceField<SimpleContourCombiner<MultiDistanceSelector> >(output, shape, transformation);+ msdfErrorCorrection(output, shape, transformation, config);+}++void generateMTSDF(const BitmapSection<float, 4> &output, const Shape &shape, const SDFTransformation &transformation, const MSDFGeneratorConfig &config) {+ if (config.overlapSupport)+ generateDistanceField<OverlappingContourCombiner<MultiAndTrueDistanceSelector> >(output, shape, transformation);+ else+ generateDistanceField<SimpleContourCombiner<MultiAndTrueDistanceSelector> >(output, shape, transformation);+ msdfErrorCorrection(output, shape, transformation, config);+}++void generateSDF(const BitmapSection<float, 1> &output, const Shape &shape, const Projection &projection, Range range, const GeneratorConfig &config) {+ if (config.overlapSupport)+ generateDistanceField<OverlappingContourCombiner<TrueDistanceSelector> >(output, shape, SDFTransformation(projection, range));+ else+ generateDistanceField<SimpleContourCombiner<TrueDistanceSelector> >(output, shape, SDFTransformation(projection, range));+}++void generatePSDF(const BitmapSection<float, 1> &output, const Shape &shape, const Projection &projection, Range range, const GeneratorConfig &config) {+ if (config.overlapSupport)+ generateDistanceField<OverlappingContourCombiner<PerpendicularDistanceSelector> >(output, shape, SDFTransformation(projection, range));+ else+ generateDistanceField<SimpleContourCombiner<PerpendicularDistanceSelector> >(output, shape, SDFTransformation(projection, range));+}++void generateMSDF(const BitmapSection<float, 3> &output, const Shape &shape, const Projection &projection, Range range, const MSDFGeneratorConfig &config) {+ if (config.overlapSupport)+ generateDistanceField<OverlappingContourCombiner<MultiDistanceSelector> >(output, shape, SDFTransformation(projection, range));+ else+ generateDistanceField<SimpleContourCombiner<MultiDistanceSelector> >(output, shape, SDFTransformation(projection, range));+ msdfErrorCorrection(output, shape, SDFTransformation(projection, range), config);+}++void generateMTSDF(const BitmapSection<float, 4> &output, const Shape &shape, const Projection &projection, Range range, const MSDFGeneratorConfig &config) {+ if (config.overlapSupport)+ generateDistanceField<OverlappingContourCombiner<MultiAndTrueDistanceSelector> >(output, shape, SDFTransformation(projection, range));+ else+ generateDistanceField<SimpleContourCombiner<MultiAndTrueDistanceSelector> >(output, shape, SDFTransformation(projection, range));+ msdfErrorCorrection(output, shape, SDFTransformation(projection, range), config);+}++// Legacy API++void generatePseudoSDF(const BitmapSection<float, 1> &output, const Shape &shape, const Projection &projection, Range range, const GeneratorConfig &config) {+ generatePSDF(output, shape, SDFTransformation(projection, range), config);+}++void generateSDF(const BitmapSection<float, 1> &output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate, bool overlapSupport) {+ generateSDF(output, shape, Projection(scale, translate), range, GeneratorConfig(overlapSupport));+}++void generatePSDF(const BitmapSection<float, 1> &output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate, bool overlapSupport) {+ generatePSDF(output, shape, Projection(scale, translate), range, GeneratorConfig(overlapSupport));+}++void generatePseudoSDF(const BitmapSection<float, 1> &output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate, bool overlapSupport) {+ generatePSDF(output, shape, Projection(scale, translate), range, GeneratorConfig(overlapSupport));+}++void generateMSDF(const BitmapSection<float, 3> &output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate, const ErrorCorrectionConfig &errorCorrectionConfig, bool overlapSupport) {+ generateMSDF(output, shape, Projection(scale, translate), range, MSDFGeneratorConfig(overlapSupport, errorCorrectionConfig));+}++void generateMTSDF(const BitmapSection<float, 4> &output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate, const ErrorCorrectionConfig &errorCorrectionConfig, bool overlapSupport) {+ generateMTSDF(output, shape, Projection(scale, translate), range, MSDFGeneratorConfig(overlapSupport, errorCorrectionConfig));+}++// Legacy version++void generateSDF_legacy(BitmapSection<float, 1> output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate) {+ DistanceMapping distanceMapping(range);+ output.reorient(shape.getYAxisOrientation());+#ifdef MSDFGEN_USE_OPENMP+ #pragma omp parallel for+#endif+ for (int y = 0; y < output.height; ++y) {+ for (int x = 0; x < output.width; ++x) {+ double dummy;+ Point2 p = Vector2(x+.5, y+.5)/scale-translate;+ SignedDistance minDistance;+ for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)+ for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {+ SignedDistance distance = (*edge)->signedDistance(p, dummy);+ if (distance < minDistance)+ minDistance = distance;+ }+ *output(x, y) = float(distanceMapping(minDistance.distance));+ }+ }+}++void generatePSDF_legacy(BitmapSection<float, 1> output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate) {+ DistanceMapping distanceMapping(range);+ output.reorient(shape.getYAxisOrientation());+#ifdef MSDFGEN_USE_OPENMP+ #pragma omp parallel for+#endif+ for (int y = 0; y < output.height; ++y) {+ for (int x = 0; x < output.width; ++x) {+ Point2 p = Vector2(x+.5, y+.5)/scale-translate;+ SignedDistance minDistance;+ const EdgeHolder *nearEdge = NULL;+ double nearParam = 0;+ for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)+ for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {+ double param;+ SignedDistance distance = (*edge)->signedDistance(p, param);+ if (distance < minDistance) {+ minDistance = distance;+ nearEdge = &*edge;+ nearParam = param;+ }+ }+ if (nearEdge)+ (*nearEdge)->distanceToPerpendicularDistance(minDistance, p, nearParam);+ *output(x, y) = float(distanceMapping(minDistance.distance));+ }+ }+}++void generatePseudoSDF_legacy(BitmapSection<float, 1> output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate) {+ generatePSDF_legacy(output, shape, range, scale, translate);+}++void generateMSDF_legacy(BitmapSection<float, 3> output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate, ErrorCorrectionConfig errorCorrectionConfig) {+ DistanceMapping distanceMapping(range);+ output.reorient(shape.getYAxisOrientation());+#ifdef MSDFGEN_USE_OPENMP+ #pragma omp parallel for+#endif+ for (int y = 0; y < output.height; ++y) {+ for (int x = 0; x < output.width; ++x) {+ Point2 p = Vector2(x+.5, y+.5)/scale-translate;++ struct {+ SignedDistance minDistance;+ const EdgeHolder *nearEdge;+ double nearParam;+ } r, g, b;+ r.nearEdge = g.nearEdge = b.nearEdge = NULL;+ r.nearParam = g.nearParam = b.nearParam = 0;++ for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)+ for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {+ double param;+ SignedDistance distance = (*edge)->signedDistance(p, param);+ if ((*edge)->color&RED && distance < r.minDistance) {+ r.minDistance = distance;+ r.nearEdge = &*edge;+ r.nearParam = param;+ }+ if ((*edge)->color&GREEN && distance < g.minDistance) {+ g.minDistance = distance;+ g.nearEdge = &*edge;+ g.nearParam = param;+ }+ if ((*edge)->color&BLUE && distance < b.minDistance) {+ b.minDistance = distance;+ b.nearEdge = &*edge;+ b.nearParam = param;+ }+ }++ if (r.nearEdge)+ (*r.nearEdge)->distanceToPerpendicularDistance(r.minDistance, p, r.nearParam);+ if (g.nearEdge)+ (*g.nearEdge)->distanceToPerpendicularDistance(g.minDistance, p, g.nearParam);+ if (b.nearEdge)+ (*b.nearEdge)->distanceToPerpendicularDistance(b.minDistance, p, b.nearParam);+ output(x, y)[0] = float(distanceMapping(r.minDistance.distance));+ output(x, y)[1] = float(distanceMapping(g.minDistance.distance));+ output(x, y)[2] = float(distanceMapping(b.minDistance.distance));+ }+ }++ errorCorrectionConfig.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;+ msdfErrorCorrection(output, shape, Projection(scale, translate), range, MSDFGeneratorConfig(false, errorCorrectionConfig));+}++void generateMTSDF_legacy(BitmapSection<float, 4> output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate, ErrorCorrectionConfig errorCorrectionConfig) {+ DistanceMapping distanceMapping(range);+ output.reorient(shape.getYAxisOrientation());+#ifdef MSDFGEN_USE_OPENMP+ #pragma omp parallel for+#endif+ for (int y = 0; y < output.height; ++y) {+ for (int x = 0; x < output.width; ++x) {+ Point2 p = Vector2(x+.5, y+.5)/scale-translate;++ SignedDistance minDistance;+ struct {+ SignedDistance minDistance;+ const EdgeHolder *nearEdge;+ double nearParam;+ } r, g, b;+ r.nearEdge = g.nearEdge = b.nearEdge = NULL;+ r.nearParam = g.nearParam = b.nearParam = 0;++ for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)+ for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {+ double param;+ SignedDistance distance = (*edge)->signedDistance(p, param);+ if (distance < minDistance)+ minDistance = distance;+ if ((*edge)->color&RED && distance < r.minDistance) {+ r.minDistance = distance;+ r.nearEdge = &*edge;+ r.nearParam = param;+ }+ if ((*edge)->color&GREEN && distance < g.minDistance) {+ g.minDistance = distance;+ g.nearEdge = &*edge;+ g.nearParam = param;+ }+ if ((*edge)->color&BLUE && distance < b.minDistance) {+ b.minDistance = distance;+ b.nearEdge = &*edge;+ b.nearParam = param;+ }+ }++ if (r.nearEdge)+ (*r.nearEdge)->distanceToPerpendicularDistance(r.minDistance, p, r.nearParam);+ if (g.nearEdge)+ (*g.nearEdge)->distanceToPerpendicularDistance(g.minDistance, p, g.nearParam);+ if (b.nearEdge)+ (*b.nearEdge)->distanceToPerpendicularDistance(b.minDistance, p, b.nearParam);+ output(x, y)[0] = float(distanceMapping(r.minDistance.distance));+ output(x, y)[1] = float(distanceMapping(g.minDistance.distance));+ output(x, y)[2] = float(distanceMapping(b.minDistance.distance));+ output(x, y)[3] = float(distanceMapping(minDistance.distance));+ }+ }++ errorCorrectionConfig.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;+ msdfErrorCorrection(output, shape, Projection(scale, translate), range, MSDFGeneratorConfig(false, errorCorrectionConfig));+}++}diff --git a/third_party/msdfgen/core/pixel-conversion.hpp b/third_party/msdfgen/core/pixel-conversion.hppnew file mode 100644index 000000000..1ab636f0d--- /dev/null+++ b/third_party/msdfgen/core/pixel-conversion.hpp@@ -0,0 +1,16 @@++#pragma once++#include "arithmetics.hpp"++namespace msdfgen {++inline byte pixelFloatToByte(float x) {+ return byte(~int(255.5f-255.f*clamp(x)));+}++inline float pixelByteToFloat(byte x) {+ return 1.f/255.f*float(x);+}++}diff --git a/third_party/msdfgen/core/rasterization.cpp b/third_party/msdfgen/core/rasterization.cppnew file mode 100644index 000000000..01896ed9a--- /dev/null+++ b/third_party/msdfgen/core/rasterization.cpp@@ -0,0 +1,128 @@++#include "rasterization.h"++#include <vector>+#include "arithmetics.hpp"++namespace msdfgen {++void rasterize(BitmapSection<float, 1> output, const Shape &shape, const Projection &projection, FillRule fillRule) {+ output.reorient(shape.getYAxisOrientation());+ Scanline scanline;+ for (int y = 0; y < output.height; ++y) {+ shape.scanline(scanline, projection.unprojectY(y+.5));+ for (int x = 0; x < output.width; ++x)+ *output(x, y) = (float) scanline.filled(projection.unprojectX(x+.5), fillRule);+ }+}++void distanceSignCorrection(BitmapSection<float, 1> sdf, const Shape &shape, const Projection &projection, float sdfZeroValue, FillRule fillRule) {+ sdf.reorient(shape.getYAxisOrientation());+ float doubleSdfZeroValue = sdfZeroValue+sdfZeroValue;+ Scanline scanline;+ for (int y = 0; y < sdf.height; ++y) {+ shape.scanline(scanline, projection.unprojectY(y+.5));+ for (int x = 0; x < sdf.width; ++x) {+ bool fill = scanline.filled(projection.unprojectX(x+.5), fillRule);+ float &sd = *sdf(x, y);+ if ((sd > sdfZeroValue) != fill)+ sd = doubleSdfZeroValue-sd;+ }+ }+}++template <int N>+static void multiDistanceSignCorrection(BitmapSection<float, N> sdf, const Shape &shape, const Projection &projection, float sdfZeroValue, FillRule fillRule) {+ int w = sdf.width, h = sdf.height;+ if (!(w && h))+ return;+ sdf.reorient(shape.getYAxisOrientation());+ float doubleSdfZeroValue = sdfZeroValue+sdfZeroValue;+ Scanline scanline;+ bool ambiguous = false;+ std::vector<char> matchMap;+ matchMap.resize(w*h);+ char *match = &matchMap[0];+ for (int y = 0; y < h; ++y) {+ shape.scanline(scanline, projection.unprojectY(y+.5));+ for (int x = 0; x < w; ++x) {+ bool fill = scanline.filled(projection.unprojectX(x+.5), fillRule);+ float *msd = sdf(x, y);+ float sd = median(msd[0], msd[1], msd[2]);+ if (sd == sdfZeroValue)+ ambiguous = true;+ else if ((sd > sdfZeroValue) != fill) {+ msd[0] = doubleSdfZeroValue-msd[0];+ msd[1] = doubleSdfZeroValue-msd[1];+ msd[2] = doubleSdfZeroValue-msd[2];+ *match = -1;+ } else+ *match = 1;+ if (N >= 4 && (msd[3] > sdfZeroValue) != fill)+ msd[3] = doubleSdfZeroValue-msd[3];+ ++match;+ }+ }+ // This step is necessary to avoid artifacts when whole shape is inverted+ if (ambiguous) {+ match = &matchMap[0];+ for (int y = 0; y < h; ++y) {+ for (int x = 0; x < w; ++x) {+ if (!*match) {+ int neighborMatch = 0;+ if (x > 0) neighborMatch += *(match-1);+ if (x < w-1) neighborMatch += *(match+1);+ if (y > 0) neighborMatch += *(match-w);+ if (y < h-1) neighborMatch += *(match+w);+ if (neighborMatch < 0) {+ float *msd = sdf(x, y);+ msd[0] = doubleSdfZeroValue-msd[0];+ msd[1] = doubleSdfZeroValue-msd[1];+ msd[2] = doubleSdfZeroValue-msd[2];+ }+ }+ ++match;+ }+ }+ }+}++void distanceSignCorrection(BitmapSection<float, 3> sdf, const Shape &shape, const Projection &projection, float sdfZeroValue, FillRule fillRule) {+ multiDistanceSignCorrection(sdf, shape, projection, sdfZeroValue, fillRule);+}++void distanceSignCorrection(BitmapSection<float, 4> sdf, const Shape &shape, const Projection &projection, float sdfZeroValue, FillRule fillRule) {+ multiDistanceSignCorrection(sdf, shape, projection, sdfZeroValue, fillRule);+}++// Legacy API++void rasterize(const BitmapSection<float, 1> &output, const Shape &shape, const Vector2 &scale, const Vector2 &translate, FillRule fillRule) {+ rasterize(output, shape, Projection(scale, translate), fillRule);+}++void distanceSignCorrection(BitmapSection<float, 1> sdf, const Shape &shape, const Projection &projection, FillRule fillRule) {+ distanceSignCorrection(sdf, shape, projection, .5f, fillRule);+}++void distanceSignCorrection(BitmapSection<float, 3> sdf, const Shape &shape, const Projection &projection, FillRule fillRule) {+ distanceSignCorrection(sdf, shape, projection, .5f, fillRule);+}++void distanceSignCorrection(BitmapSection<float, 4> sdf, const Shape &shape, const Projection &projection, FillRule fillRule) {+ distanceSignCorrection(sdf, shape, projection, .5f, fillRule);+}++void distanceSignCorrection(const BitmapSection<float, 1> &sdf, const Shape &shape, const Vector2 &scale, const Vector2 &translate, FillRule fillRule) {+ distanceSignCorrection(sdf, shape, Projection(scale, translate), fillRule);+}++void distanceSignCorrection(const BitmapSection<float, 3> &sdf, const Shape &shape, const Vector2 &scale, const Vector2 &translate, FillRule fillRule) {+ distanceSignCorrection(sdf, shape, Projection(scale, translate), fillRule);+}++void distanceSignCorrection(const BitmapSection<float, 4> &sdf, const Shape &shape, const Vector2 &scale, const Vector2 &translate, FillRule fillRule) {+ distanceSignCorrection(sdf, shape, Projection(scale, translate), fillRule);+}++}diff --git a/third_party/msdfgen/core/rasterization.h b/third_party/msdfgen/core/rasterization.hnew file mode 100644index 000000000..876a87bdc--- /dev/null+++ b/third_party/msdfgen/core/rasterization.h@@ -0,0 +1,28 @@++#pragma once++#include "Vector2.hpp"+#include "Shape.h"+#include "Projection.h"+#include "Scanline.h"+#include "BitmapRef.hpp"++namespace msdfgen {++/// Rasterizes the shape into a monochrome bitmap.+void rasterize(BitmapSection<float, 1> output, const Shape &shape, const Projection &projection, FillRule fillRule = FILL_NONZERO);+/// Fixes the sign of the input signed distance field, so that it matches the shape's rasterized fill.+void distanceSignCorrection(BitmapSection<float, 1> sdf, const Shape &shape, const Projection &projection, float sdfZeroValue = .5f, FillRule fillRule = FILL_NONZERO);+void distanceSignCorrection(BitmapSection<float, 3> sdf, const Shape &shape, const Projection &projection, float sdfZeroValue = .5f, FillRule fillRule = FILL_NONZERO);+void distanceSignCorrection(BitmapSection<float, 4> sdf, const Shape &shape, const Projection &projection, float sdfZeroValue = .5f, FillRule fillRule = FILL_NONZERO);++// Old versions of the function API's kept for backwards compatibility+void rasterize(const BitmapSection<float, 1> &output, const Shape &shape, const Vector2 &scale, const Vector2 &translate, FillRule fillRule = FILL_NONZERO);+void distanceSignCorrection(BitmapSection<float, 1> sdf, const Shape &shape, const Projection &projection, FillRule fillRule);+void distanceSignCorrection(BitmapSection<float, 3> sdf, const Shape &shape, const Projection &projection, FillRule fillRule);+void distanceSignCorrection(BitmapSection<float, 4> sdf, const Shape &shape, const Projection &projection, FillRule fillRule);+void distanceSignCorrection(const BitmapSection<float, 1> &sdf, const Shape &shape, const Vector2 &scale, const Vector2 &translate, FillRule fillRule = FILL_NONZERO);+void distanceSignCorrection(const BitmapSection<float, 3> &sdf, const Shape &shape, const Vector2 &scale, const Vector2 &translate, FillRule fillRule = FILL_NONZERO);+void distanceSignCorrection(const BitmapSection<float, 4> &sdf, const Shape &shape, const Vector2 &scale, const Vector2 &translate, FillRule fillRule = FILL_NONZERO);++}diff --git a/third_party/msdfgen/core/render-sdf.cpp b/third_party/msdfgen/core/render-sdf.cppnew file mode 100644index 000000000..59c8180b9--- /dev/null+++ b/third_party/msdfgen/core/render-sdf.cpp@@ -0,0 +1,194 @@++#include "render-sdf.h"++#include "arithmetics.hpp"+#include "DistanceMapping.h"+#include "pixel-conversion.hpp"+#include "bitmap-interpolation.hpp"++namespace msdfgen {++static float distVal(float dist, DistanceMapping mapping) {+ return (float) clamp(mapping(dist)+.5);+}++void renderSDF(const BitmapSection<float, 1> &output, const BitmapConstSection<float, 1> &sdf, Range sdfPxRange, float sdThreshold) {+ Vector2 scale((double) sdf.width/output.width, (double) sdf.height/output.height);+ if (sdfPxRange.lower == sdfPxRange.upper) {+ for (int y = 0; y < output.height; ++y) {+ for (int x = 0; x < output.width; ++x) {+ float sd;+ interpolate(&sd, sdf, scale*Point2(x+.5, y+.5));+ *output(x, y) = float(sd >= sdThreshold);+ }+ }+ } else {+ sdfPxRange *= (double) (output.width+output.height)/(sdf.width+sdf.height);+ DistanceMapping distanceMapping = DistanceMapping::inverse(sdfPxRange);+ float sdBias = .5f-sdThreshold;+ for (int y = 0; y < output.height; ++y) {+ for (int x = 0; x < output.width; ++x) {+ float sd;+ interpolate(&sd, sdf, scale*Point2(x+.5, y+.5));+ *output(x, y) = distVal(sd+sdBias, distanceMapping);+ }+ }+ }++}++void renderSDF(const BitmapSection<float, 3> &output, const BitmapConstSection<float, 1> &sdf, Range sdfPxRange, float sdThreshold) {+ Vector2 scale((double) sdf.width/output.width, (double) sdf.height/output.height);+ if (sdfPxRange.lower == sdfPxRange.upper) {+ for (int y = 0; y < output.height; ++y) {+ for (int x = 0; x < output.width; ++x) {+ float sd;+ interpolate(&sd, sdf, scale*Point2(x+.5, y+.5));+ float v = float(sd >= sdThreshold);+ output(x, y)[0] = v;+ output(x, y)[1] = v;+ output(x, y)[2] = v;+ }+ }+ } else {+ sdfPxRange *= (double) (output.width+output.height)/(sdf.width+sdf.height);+ DistanceMapping distanceMapping = DistanceMapping::inverse(sdfPxRange);+ float sdBias = .5f-sdThreshold;+ for (int y = 0; y < output.height; ++y) {+ for (int x = 0; x < output.width; ++x) {+ float sd;+ interpolate(&sd, sdf, scale*Point2(x+.5, y+.5));+ float v = distVal(sd+sdBias, distanceMapping);+ output(x, y)[0] = v;+ output(x, y)[1] = v;+ output(x, y)[2] = v;+ }+ }+ }+}++void renderSDF(const BitmapSection<float, 1> &output, const BitmapConstSection<float, 3> &sdf, Range sdfPxRange, float sdThreshold) {+ Vector2 scale((double) sdf.width/output.width, (double) sdf.height/output.height);+ if (sdfPxRange.lower == sdfPxRange.upper) {+ for (int y = 0; y < output.height; ++y) {+ for (int x = 0; x < output.width; ++x) {+ float sd[3];+ interpolate(sd, sdf, scale*Point2(x+.5, y+.5));+ *output(x, y) = float(median(sd[0], sd[1], sd[2]) >= sdThreshold);+ }+ }+ } else {+ sdfPxRange *= (double) (output.width+output.height)/(sdf.width+sdf.height);+ DistanceMapping distanceMapping = DistanceMapping::inverse(sdfPxRange);+ float sdBias = .5f-sdThreshold;+ for (int y = 0; y < output.height; ++y) {+ for (int x = 0; x < output.width; ++x) {+ float sd[3];+ interpolate(sd, sdf, scale*Point2(x+.5, y+.5));+ *output(x, y) = distVal(median(sd[0], sd[1], sd[2])+sdBias, distanceMapping);+ }+ }+ }+}++void renderSDF(const BitmapSection<float, 3> &output, const BitmapConstSection<float, 3> &sdf, Range sdfPxRange, float sdThreshold) {+ Vector2 scale((double) sdf.width/output.width, (double) sdf.height/output.height);+ if (sdfPxRange.lower == sdfPxRange.upper) {+ for (int y = 0; y < output.height; ++y) {+ for (int x = 0; x < output.width; ++x) {+ float sd[3];+ interpolate(sd, sdf, scale*Point2(x+.5, y+.5));+ output(x, y)[0] = float(sd[0] >= sdThreshold);+ output(x, y)[1] = float(sd[1] >= sdThreshold);+ output(x, y)[2] = float(sd[2] >= sdThreshold);+ }+ }+ } else {+ sdfPxRange *= (double) (output.width+output.height)/(sdf.width+sdf.height);+ DistanceMapping distanceMapping = DistanceMapping::inverse(sdfPxRange);+ float sdBias = .5f-sdThreshold;+ for (int y = 0; y < output.height; ++y) {+ for (int x = 0; x < output.width; ++x) {+ float sd[3];+ interpolate(sd, sdf, scale*Point2(x+.5, y+.5));+ output(x, y)[0] = distVal(sd[0]+sdBias, distanceMapping);+ output(x, y)[1] = distVal(sd[1]+sdBias, distanceMapping);+ output(x, y)[2] = distVal(sd[2]+sdBias, distanceMapping);+ }+ }+ }+}++void renderSDF(const BitmapSection<float, 1> &output, const BitmapConstSection<float, 4> &sdf, Range sdfPxRange, float sdThreshold) {+ Vector2 scale((double) sdf.width/output.width, (double) sdf.height/output.height);+ if (sdfPxRange.lower == sdfPxRange.upper) {+ for (int y = 0; y < output.height; ++y) {+ for (int x = 0; x < output.width; ++x) {+ float sd[4];+ interpolate(sd, sdf, scale*Point2(x+.5, y+.5));+ *output(x, y) = float(median(sd[0], sd[1], sd[2]) >= sdThreshold);+ }+ }+ } else {+ sdfPxRange *= (double) (output.width+output.height)/(sdf.width+sdf.height);+ DistanceMapping distanceMapping = DistanceMapping::inverse(sdfPxRange);+ float sdBias = .5f-sdThreshold;+ for (int y = 0; y < output.height; ++y) {+ for (int x = 0; x < output.width; ++x) {+ float sd[4];+ interpolate(sd, sdf, scale*Point2(x+.5, y+.5));+ *output(x, y) = distVal(median(sd[0], sd[1], sd[2])+sdBias, distanceMapping);+ }+ }+ }+}++void renderSDF(const BitmapSection<float, 4> &output, const BitmapConstSection<float, 4> &sdf, Range sdfPxRange, float sdThreshold) {+ Vector2 scale((double) sdf.width/output.width, (double) sdf.height/output.height);+ if (sdfPxRange.lower == sdfPxRange.upper) {+ for (int y = 0; y < output.height; ++y) {+ for (int x = 0; x < output.width; ++x) {+ float sd[4];+ interpolate(sd, sdf, scale*Point2(x+.5, y+.5));+ output(x, y)[0] = float(sd[0] >= sdThreshold);+ output(x, y)[1] = float(sd[1] >= sdThreshold);+ output(x, y)[2] = float(sd[2] >= sdThreshold);+ output(x, y)[3] = float(sd[3] >= sdThreshold);+ }+ }+ } else {+ sdfPxRange *= (double) (output.width+output.height)/(sdf.width+sdf.height);+ DistanceMapping distanceMapping = DistanceMapping::inverse(sdfPxRange);+ float sdBias = .5f-sdThreshold;+ for (int y = 0; y < output.height; ++y) {+ for (int x = 0; x < output.width; ++x) {+ float sd[4];+ interpolate(sd, sdf, scale*Point2(x+.5, y+.5));+ output(x, y)[0] = distVal(sd[0]+sdBias, distanceMapping);+ output(x, y)[1] = distVal(sd[1]+sdBias, distanceMapping);+ output(x, y)[2] = distVal(sd[2]+sdBias, distanceMapping);+ output(x, y)[3] = distVal(sd[3]+sdBias, distanceMapping);+ }+ }+ }+}++void simulate8bit(const BitmapSection<float, 1> &bitmap) {+ const float *end = bitmap.pixels+1*bitmap.width*bitmap.height;+ for (float *p = bitmap.pixels; p < end; ++p)+ *p = pixelByteToFloat(pixelFloatToByte(*p));+}++void simulate8bit(const BitmapSection<float, 3> &bitmap) {+ const float *end = bitmap.pixels+3*bitmap.width*bitmap.height;+ for (float *p = bitmap.pixels; p < end; ++p)+ *p = pixelByteToFloat(pixelFloatToByte(*p));+}++void simulate8bit(const BitmapSection<float, 4> &bitmap) {+ const float *end = bitmap.pixels+4*bitmap.width*bitmap.height;+ for (float *p = bitmap.pixels; p < end; ++p)+ *p = pixelByteToFloat(pixelFloatToByte(*p));+}++}diff --git a/third_party/msdfgen/core/render-sdf.h b/third_party/msdfgen/core/render-sdf.hnew file mode 100644index 000000000..b61823ad0--- /dev/null+++ b/third_party/msdfgen/core/render-sdf.h@@ -0,0 +1,23 @@++#pragma once++#include "Vector2.hpp"+#include "Range.hpp"+#include "BitmapRef.hpp"++namespace msdfgen {++/// Reconstructs the shape's appearance into output from the distance field sdf.+void renderSDF(const BitmapSection<float, 1> &output, const BitmapConstSection<float, 1> &sdf, Range sdfPxRange = 0, float sdThreshold = .5f);+void renderSDF(const BitmapSection<float, 3> &output, const BitmapConstSection<float, 1> &sdf, Range sdfPxRange = 0, float sdThreshold = .5f);+void renderSDF(const BitmapSection<float, 1> &output, const BitmapConstSection<float, 3> &sdf, Range sdfPxRange = 0, float sdThreshold = .5f);+void renderSDF(const BitmapSection<float, 3> &output, const BitmapConstSection<float, 3> &sdf, Range sdfPxRange = 0, float sdThreshold = .5f);+void renderSDF(const BitmapSection<float, 1> &output, const BitmapConstSection<float, 4> &sdf, Range sdfPxRange = 0, float sdThreshold = .5f);+void renderSDF(const BitmapSection<float, 4> &output, const BitmapConstSection<float, 4> &sdf, Range sdfPxRange = 0, float sdThreshold = .5f);++/// Snaps the values of the floating-point bitmaps into one of the 256 values representable in a standard 8-bit bitmap.+void simulate8bit(const BitmapSection<float, 1> &bitmap);+void simulate8bit(const BitmapSection<float, 3> &bitmap);+void simulate8bit(const BitmapSection<float, 4> &bitmap);++}diff --git a/third_party/msdfgen/core/save-bmp.cpp b/third_party/msdfgen/core/save-bmp.cppnew file mode 100644index 000000000..5e4aceaa9--- /dev/null+++ b/third_party/msdfgen/core/save-bmp.cpp@@ -0,0 +1,233 @@++#ifndef _CRT_SECURE_NO_WARNINGS+#define _CRT_SECURE_NO_WARNINGS+#endif++#include "save-bmp.h"++#include <cstdio>++#ifdef MSDFGEN_USE_CPP11+ #include <cstdint>+#else+namespace msdfgen {+ typedef int int32_t;+ typedef unsigned uint32_t;+ typedef unsigned short uint16_t;+}+#endif++#include "pixel-conversion.hpp"++namespace msdfgen {++static const byte BMP_LINEAR_COLOR_SPACE_SPECIFICATION[48] = {+ 0xf8, 0xc2, 0x64, 0x1a, 0x08, 0x3d, 0x9b, 0x0d, 0x11, 0x36, 0x3c, 0x01,+ 0x1c, 0xeb, 0xe2, 0x16, 0x39, 0xd6, 0xc5, 0x2d, 0x09, 0xf9, 0xa0, 0x07,+ 0xdf, 0x4f, 0x8d, 0x0b, 0xc0, 0xec, 0x9e, 0x04, 0xf4, 0xfd, 0xd4, 0x3c,+ 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00,+};++template <typename T>+bool writeLE(FILE *file, T value);++template <>+bool writeLE(FILE *f, uint16_t value) {+ byte bytes[2] = { byte(value), byte(value>>8) };+ return fwrite(bytes, 1, 2, f) == 2;+}+template <>+bool writeLE(FILE *f, uint32_t value) {+ byte bytes[4] = { byte(value), byte(value>>8), byte(value>>16), byte(value>>24) };+ return fwrite(bytes, 1, 4, f) == 4;+}+template <>+bool writeLE(FILE *f, int32_t value) {+ byte bytes[4] = { byte(value), byte(value>>8), byte(value>>16), byte(value>>24) };+ return fwrite(bytes, 1, 4, f) == 4;+}++static bool writeBmpHeader(FILE *file, int bytesPerPixel, int width, int height, int &paddedWidth) {+ paddedWidth = (bytesPerPixel*width+3)&~3; // Ceil to multiple of 4 bytes+ uint32_t colorTableEntries = bytesPerPixel == 1 ? 256 : 0;+ uint32_t bitmapStart = 14+108+4*colorTableEntries;+ uint32_t bitmapSize = paddedWidth*height;+ uint32_t fileSize = bitmapStart+bitmapSize;++ // BMP file header+ writeLE<uint16_t>(file, 0x4d42u); // "BM"+ writeLE<uint32_t>(file, fileSize);+ writeLE<uint16_t>(file, 0);+ writeLE<uint16_t>(file, 0);+ writeLE<uint32_t>(file, bitmapStart);++ // DIB header (BITMAPV4HEADER)+ writeLE<uint32_t>(file, 108);+ writeLE<int32_t>(file, width);+ writeLE<int32_t>(file, height);+ writeLE<uint16_t>(file, 1); // planes+ writeLE<uint16_t>(file, uint16_t(8*bytesPerPixel));+ writeLE<uint32_t>(file, bytesPerPixel == 4 ? 3 : 0); // 0 = BI_RGB, 3 = BI_BITFIELDS+ writeLE<uint32_t>(file, bitmapSize);+ writeLE<uint32_t>(file, 2835); // 72 dpi as pixels/meter+ writeLE<uint32_t>(file, 2835);+ writeLE<uint32_t>(file, colorTableEntries);+ writeLE<uint32_t>(file, colorTableEntries);+ writeLE<uint32_t>(file, 0x00ff0000u); // Red channel bit mask+ writeLE<uint32_t>(file, 0x0000ff00u); // Green channel bit mask+ writeLE<uint32_t>(file, 0x000000ffu); // Blue channel bit mask+ writeLE<uint32_t>(file, bytesPerPixel == 4 ? 0xff000000u : 0u); // Alpha channel bit mask+ writeLE<uint32_t>(file, 0); // LCS_CALIBRATED_RGB+ fwrite(BMP_LINEAR_COLOR_SPACE_SPECIFICATION, 1, 48, file);++ // Use indexed color for single channel - color table just lists grayscale colors (#000000, #010101, ... #FFFFFF)+ if (bytesPerPixel == 1) {+ for (uint32_t grayColor = 0; grayColor < 0x01000000u; grayColor += 0x00010101u)+ writeLE<uint32_t>(file, grayColor|0xff000000u);+ }++ return true;+}++bool saveBmp(BitmapConstSection<byte, 1> bitmap, const char *filename) {+ FILE *file = fopen(filename, "wb");+ if (!file)+ return false;++ int paddedWidth;+ bitmap.reorient(Y_UPWARD);+ writeBmpHeader(file, 1, bitmap.width, bitmap.height, paddedWidth);++ byte padding[4] = { };+ int padLength = paddedWidth-bitmap.width;+ for (int y = 0; y < bitmap.height; ++y) {+ fwrite(bitmap(0, y), sizeof(byte), bitmap.width, file);+ fwrite(padding, 1, padLength, file);+ }++ return !fclose(file);+}++bool saveBmp(BitmapConstSection<byte, 3> bitmap, const char *filename) {+ FILE *file = fopen(filename, "wb");+ if (!file)+ return false;++ int paddedWidth;+ bitmap.reorient(Y_UPWARD);+ writeBmpHeader(file, 3, bitmap.width, bitmap.height, paddedWidth);++ byte padding[4] = { };+ int padLength = paddedWidth-3*bitmap.width;+ for (int y = 0; y < bitmap.height; ++y) {+ for (int x = 0; x < bitmap.width; ++x) {+ byte bgr[3] = {+ bitmap(x, y)[2],+ bitmap(x, y)[1],+ bitmap(x, y)[0]+ };+ fwrite(bgr, sizeof(byte), 3, file);+ }+ fwrite(padding, 1, padLength, file);+ }++ return !fclose(file);+}++bool saveBmp(BitmapConstSection<byte, 4> bitmap, const char *filename) {+ FILE *file = fopen(filename, "wb");+ if (!file)+ return false;++ int dummyPaddedWidth;+ bitmap.reorient(Y_UPWARD);+ writeBmpHeader(file, 4, bitmap.width, bitmap.height, dummyPaddedWidth);++ for (int y = 0; y < bitmap.height; ++y) {+ for (int x = 0; x < bitmap.width; ++x) {+ byte bgra[4] = {+ bitmap(x, y)[2],+ bitmap(x, y)[1],+ bitmap(x, y)[0],+ bitmap(x, y)[3]+ };+ fwrite(bgra, sizeof(byte), 4, file);+ }+ }++ return !fclose(file);+}++bool saveBmp(BitmapConstSection<float, 1> bitmap, const char *filename) {+ FILE *file = fopen(filename, "wb");+ if (!file)+ return false;++ int paddedWidth;+ bitmap.reorient(Y_UPWARD);+ writeBmpHeader(file, 1, bitmap.width, bitmap.height, paddedWidth);++ byte padding[4] = { };+ int padLength = paddedWidth-bitmap.width;+ for (int y = 0; y < bitmap.height; ++y) {+ for (int x = 0; x < bitmap.width; ++x) {+ byte px = pixelFloatToByte(*bitmap(x, y));+ fwrite(&px, sizeof(byte), 1, file);+ }+ fwrite(padding, 1, padLength, file);+ }++ return !fclose(file);+}++bool saveBmp(BitmapConstSection<float, 3> bitmap, const char *filename) {+ FILE *file = fopen(filename, "wb");+ if (!file)+ return false;++ int paddedWidth;+ bitmap.reorient(Y_UPWARD);+ writeBmpHeader(file, 3, bitmap.width, bitmap.height, paddedWidth);++ byte padding[4] = { };+ int padLength = paddedWidth-3*bitmap.width;+ for (int y = 0; y < bitmap.height; ++y) {+ for (int x = 0; x < bitmap.width; ++x) {+ byte bgr[3] = {+ pixelFloatToByte(bitmap(x, y)[2]),+ pixelFloatToByte(bitmap(x, y)[1]),+ pixelFloatToByte(bitmap(x, y)[0])+ };+ fwrite(bgr, sizeof(byte), 3, file);+ }+ fwrite(padding, 1, padLength, file);+ }++ return !fclose(file);+}++bool saveBmp(BitmapConstSection<float, 4> bitmap, const char *filename) {+ FILE *file = fopen(filename, "wb");+ if (!file)+ return false;++ int dummyPaddedWidth;+ bitmap.reorient(Y_UPWARD);+ writeBmpHeader(file, 4, bitmap.width, bitmap.height, dummyPaddedWidth);++ for (int y = 0; y < bitmap.height; ++y) {+ for (int x = 0; x < bitmap.width; ++x) {+ byte bgra[4] = {+ pixelFloatToByte(bitmap(x, y)[2]),+ pixelFloatToByte(bitmap(x, y)[1]),+ pixelFloatToByte(bitmap(x, y)[0]),+ pixelFloatToByte(bitmap(x, y)[3])+ };+ fwrite(bgra, sizeof(byte), 4, file);+ }+ }++ return !fclose(file);+}++}diff --git a/third_party/msdfgen/core/save-bmp.h b/third_party/msdfgen/core/save-bmp.hnew file mode 100644index 000000000..286727558--- /dev/null+++ b/third_party/msdfgen/core/save-bmp.h@@ -0,0 +1,16 @@++#pragma once++#include "BitmapRef.hpp"++namespace msdfgen {++/// Saves the bitmap as a BMP file.+bool saveBmp(BitmapConstSection<byte, 1> bitmap, const char *filename);+bool saveBmp(BitmapConstSection<byte, 3> bitmap, const char *filename);+bool saveBmp(BitmapConstSection<byte, 4> bitmap, const char *filename);+bool saveBmp(BitmapConstSection<float, 1> bitmap, const char *filename);+bool saveBmp(BitmapConstSection<float, 3> bitmap, const char *filename);+bool saveBmp(BitmapConstSection<float, 4> bitmap, const char *filename);++}diff --git a/third_party/msdfgen/core/save-fl32.cpp b/third_party/msdfgen/core/save-fl32.cppnew file mode 100644index 000000000..937dd945b--- /dev/null+++ b/third_party/msdfgen/core/save-fl32.cpp@@ -0,0 +1,41 @@++#include "save-fl32.h"++#include <cstdio>++namespace msdfgen {++// Requires byte reversal for floats on big-endian platform+#ifndef __BIG_ENDIAN__++template <int N>+bool saveFl32(BitmapConstSection<float, N> bitmap, const char *filename) {+ if (FILE *f = fopen(filename, "wb")) {+ bitmap.reorient(Y_UPWARD);+ byte header[16] = { byte('F'), byte('L'), byte('3'), byte('2') };+ header[4] = byte(bitmap.height);+ header[5] = byte(bitmap.height>>8);+ header[6] = byte(bitmap.height>>16);+ header[7] = byte(bitmap.height>>24);+ header[8] = byte(bitmap.width);+ header[9] = byte(bitmap.width>>8);+ header[10] = byte(bitmap.width>>16);+ header[11] = byte(bitmap.width>>24);+ header[12] = byte(N);+ fwrite(header, 1, 16, f);+ for (int y = 0; y < bitmap.height; ++y)+ fwrite(bitmap(0, y), sizeof(float), N*bitmap.width, f);+ fclose(f);+ return true;+ }+ return false;+}++template bool saveFl32(BitmapConstSection<float, 1> bitmap, const char *filename);+template bool saveFl32(BitmapConstSection<float, 2> bitmap, const char *filename);+template bool saveFl32(BitmapConstSection<float, 3> bitmap, const char *filename);+template bool saveFl32(BitmapConstSection<float, 4> bitmap, const char *filename);++#endif++}diff --git a/third_party/msdfgen/core/save-fl32.h b/third_party/msdfgen/core/save-fl32.hnew file mode 100644index 000000000..473e0c04f--- /dev/null+++ b/third_party/msdfgen/core/save-fl32.h@@ -0,0 +1,12 @@++#pragma once++#include "BitmapRef.hpp"++namespace msdfgen {++/// Saves the bitmap as an uncompressed floating-point FL32 file, which can be decoded trivially.+template <int N>+bool saveFl32(BitmapConstSection<float, N> bitmap, const char *filename);++}diff --git a/third_party/msdfgen/core/save-rgba.cpp b/third_party/msdfgen/core/save-rgba.cppnew file mode 100644index 000000000..0d8aad344--- /dev/null+++ b/third_party/msdfgen/core/save-rgba.cpp@@ -0,0 +1,139 @@++#include "save-rgba.h"++#include <cstdio>+#include "pixel-conversion.hpp"++namespace msdfgen {++class RgbaFileOutput {+ FILE *file;++public:+ RgbaFileOutput(const char *filename, unsigned width, unsigned height) {+ if ((file = fopen(filename, "wb"))) {+ byte header[12] = { byte('R'), byte('G'), byte('B'), byte('A') };+ header[4] = byte(width>>24);+ header[5] = byte(width>>16);+ header[6] = byte(width>>8);+ header[7] = byte(width);+ header[8] = byte(height>>24);+ header[9] = byte(height>>16);+ header[10] = byte(height>>8);+ header[11] = byte(height);+ fwrite(header, 1, 12, file);+ }+ }++ ~RgbaFileOutput() {+ if (file)+ fclose(file);+ }++ void writePixel(const byte rgba[4]) {+ fwrite(rgba, 1, 4, file);+ }++ operator FILE *() {+ return file;+ }++};++bool saveRgba(BitmapConstSection<byte, 1> bitmap, const char *filename) {+ RgbaFileOutput output(filename, bitmap.width, bitmap.height);+ if (output) {+ byte rgba[4] = { byte(0), byte(0), byte(0), byte(0xff) };+ bitmap.reorient(Y_DOWNWARD);+ for (int y = 0; y < bitmap.height; ++y) {+ for (const byte *p = bitmap(0, y), *end = p+bitmap.width; p < end; ++p) {+ rgba[0] = rgba[1] = rgba[2] = *p;+ output.writePixel(rgba);+ }+ }+ return true;+ }+ return false;+}++bool saveRgba(BitmapConstSection<byte, 3> bitmap, const char *filename) {+ RgbaFileOutput output(filename, bitmap.width, bitmap.height);+ if (output) {+ byte rgba[4] = { byte(0), byte(0), byte(0), byte(0xff) };+ bitmap.reorient(Y_DOWNWARD);+ for (int y = 0; y < bitmap.height; ++y) {+ for (const byte *p = bitmap(0, y), *end = p+3*bitmap.width; p < end; p += 3) {+ rgba[0] = p[0], rgba[1] = p[1], rgba[2] = p[2];+ output.writePixel(rgba);+ }+ }+ return true;+ }+ return false;+}++bool saveRgba(BitmapConstSection<byte, 4> bitmap, const char *filename) {+ RgbaFileOutput output(filename, bitmap.width, bitmap.height);+ if (output) {+ bitmap.reorient(Y_DOWNWARD);+ for (int y = 0; y < bitmap.height; ++y)+ fwrite(bitmap(0, y), 1, 4*bitmap.width, output);+ return true;+ }+ return false;+}++bool saveRgba(BitmapConstSection<float, 1> bitmap, const char *filename) {+ RgbaFileOutput output(filename, bitmap.width, bitmap.height);+ if (output) {+ byte rgba[4] = { byte(0), byte(0), byte(0), byte(0xff) };+ bitmap.reorient(Y_DOWNWARD);+ for (int y = 0; y < bitmap.height; ++y) {+ for (const float *p = bitmap(0, y), *end = p+bitmap.width; p < end; ++p) {+ rgba[0] = rgba[1] = rgba[2] = pixelFloatToByte(*p);+ output.writePixel(rgba);+ }+ }+ return true;+ }+ return false;+}++bool saveRgba(BitmapConstSection<float, 3> bitmap, const char *filename) {+ RgbaFileOutput output(filename, bitmap.width, bitmap.height);+ if (output) {+ byte rgba[4] = { byte(0), byte(0), byte(0), byte(0xff) };+ bitmap.reorient(Y_DOWNWARD);+ for (int y = 0; y < bitmap.height; ++y) {+ for (const float *p = bitmap(0, y), *end = p+3*bitmap.width; p < end; p += 3) {+ rgba[0] = pixelFloatToByte(p[0]);+ rgba[1] = pixelFloatToByte(p[1]);+ rgba[2] = pixelFloatToByte(p[2]);+ output.writePixel(rgba);+ }+ }+ return true;+ }+ return false;+}++bool saveRgba(BitmapConstSection<float, 4> bitmap, const char *filename) {+ RgbaFileOutput output(filename, bitmap.width, bitmap.height);+ if (output) {+ byte rgba[4];+ bitmap.reorient(Y_DOWNWARD);+ for (int y = 0; y < bitmap.height; ++y) {+ for (const float *p = bitmap(0, y), *end = p+4*bitmap.width; p < end; p += 4) {+ rgba[0] = pixelFloatToByte(p[0]);+ rgba[1] = pixelFloatToByte(p[1]);+ rgba[2] = pixelFloatToByte(p[2]);+ rgba[3] = pixelFloatToByte(p[3]);+ output.writePixel(rgba);+ }+ }+ return true;+ }+ return false;+}++}diff --git a/third_party/msdfgen/core/save-rgba.h b/third_party/msdfgen/core/save-rgba.hnew file mode 100644index 000000000..45a6bb6ac--- /dev/null+++ b/third_party/msdfgen/core/save-rgba.h@@ -0,0 +1,16 @@++#pragma once++#include "BitmapRef.hpp"++namespace msdfgen {++/// Saves the bitmap as a simple RGBA file, which can be decoded trivially.+bool saveRgba(BitmapConstSection<byte, 1> bitmap, const char *filename);+bool saveRgba(BitmapConstSection<byte, 3> bitmap, const char *filename);+bool saveRgba(BitmapConstSection<byte, 4> bitmap, const char *filename);+bool saveRgba(BitmapConstSection<float, 1> bitmap, const char *filename);+bool saveRgba(BitmapConstSection<float, 3> bitmap, const char *filename);+bool saveRgba(BitmapConstSection<float, 4> bitmap, const char *filename);++}diff --git a/third_party/msdfgen/core/save-tiff.cpp b/third_party/msdfgen/core/save-tiff.cppnew file mode 100644index 000000000..da9c52339--- /dev/null+++ b/third_party/msdfgen/core/save-tiff.cpp@@ -0,0 +1,195 @@++#ifndef _CRT_SECURE_NO_WARNINGS+#define _CRT_SECURE_NO_WARNINGS+#endif++#include "save-tiff.h"++#include <cstdio>++#ifdef MSDFGEN_USE_CPP11+ #include <cstdint>+#else+namespace msdfgen {+ typedef int int32_t;+ typedef unsigned uint32_t;+ typedef unsigned short uint16_t;+ typedef unsigned char uint8_t;+}+#endif++namespace msdfgen {++template <typename T>+static bool writeValue(FILE *file, T value) {+ return fwrite(&value, sizeof(T), 1, file) == 1;+}+template <typename T>+static void writeValueRepeated(FILE *file, T value, int times) {+ for (int i = 0; i < times; ++i)+ writeValue(file, value);+}++static bool writeTiffHeader(FILE *file, int width, int height, int channels) {+ #ifdef __BIG_ENDIAN__+ writeValue<uint16_t>(file, 0x4d4du);+ #else+ writeValue<uint16_t>(file, 0x4949u);+ #endif+ writeValue<uint16_t>(file, 42);+ writeValue<uint32_t>(file, 0x0008u); // Offset of first IFD+ // Offset = 0x0008++ writeValue<uint16_t>(file, 15); // Number of IFD entries++ // ImageWidth+ writeValue<uint16_t>(file, 0x0100u);+ writeValue<uint16_t>(file, 0x0004u);+ writeValue<uint32_t>(file, 1);+ writeValue<int32_t>(file, width);+ // ImageLength+ writeValue<uint16_t>(file, 0x0101u);+ writeValue<uint16_t>(file, 0x0004u);+ writeValue<uint32_t>(file, 1);+ writeValue<int32_t>(file, height);+ // BitsPerSample+ writeValue<uint16_t>(file, 0x0102u);+ writeValue<uint16_t>(file, 0x0003u);+ writeValue<uint32_t>(file, channels);+ if (channels > 1)+ writeValue<uint32_t>(file, 0x00c2u); // Offset of 32, 32, ...+ else {+ writeValue<uint16_t>(file, 32);+ writeValue<uint16_t>(file, 0);+ }+ // Compression+ writeValue<uint16_t>(file, 0x0103u);+ writeValue<uint16_t>(file, 0x0003u);+ writeValue<uint32_t>(file, 1);+ writeValue<uint16_t>(file, 1);+ writeValue<uint16_t>(file, 0);+ // PhotometricInterpretation+ writeValue<uint16_t>(file, 0x0106u);+ writeValue<uint16_t>(file, 0x0003u);+ writeValue<uint32_t>(file, 1);+ writeValue<uint16_t>(file, channels >= 3 ? 2 : 1);+ writeValue<uint16_t>(file, 0);+ // StripOffsets+ writeValue<uint16_t>(file, 0x0111u);+ writeValue<uint16_t>(file, 0x0004u);+ writeValue<uint32_t>(file, 1);+ writeValue<uint32_t>(file, 0x00d2u+(channels > 1)*channels*12); // Offset of pixel data+ // SamplesPerPixel+ writeValue<uint16_t>(file, 0x0115u);+ writeValue<uint16_t>(file, 0x0003u);+ writeValue<uint32_t>(file, 1);+ writeValue<uint16_t>(file, channels);+ writeValue<uint16_t>(file, 0);+ // RowsPerStrip+ writeValue<uint16_t>(file, 0x0116u);+ writeValue<uint16_t>(file, 0x0004u);+ writeValue<uint32_t>(file, 1);+ writeValue<int32_t>(file, height);+ // StripByteCounts+ writeValue<uint16_t>(file, 0x0117u);+ writeValue<uint16_t>(file, 0x0004u);+ writeValue<uint32_t>(file, 1);+ writeValue<int32_t>(file, sizeof(float)*channels*width*height);+ // XResolution+ writeValue<uint16_t>(file, 0x011au);+ writeValue<uint16_t>(file, 0x0005u);+ writeValue<uint32_t>(file, 1);+ writeValue<uint32_t>(file, 0x00c2u+(channels > 1)*channels*2); // Offset of 300, 1+ // YResolution+ writeValue<uint16_t>(file, 0x011bu);+ writeValue<uint16_t>(file, 0x0005u);+ writeValue<uint32_t>(file, 1);+ writeValue<uint32_t>(file, 0x00cau+(channels > 1)*channels*2); // Offset of 300, 1+ // ResolutionUnit+ writeValue<uint16_t>(file, 0x0128u);+ writeValue<uint16_t>(file, 0x0003u);+ writeValue<uint32_t>(file, 1);+ writeValue<uint16_t>(file, 2);+ writeValue<uint16_t>(file, 0);+ // SampleFormat+ writeValue<uint16_t>(file, 0x0153u);+ writeValue<uint16_t>(file, 0x0003u);+ writeValue<uint32_t>(file, channels);+ if (channels > 1)+ writeValue<uint32_t>(file, 0x00d2u+channels*2); // Offset of 3, 3, ...+ else {+ writeValue<uint16_t>(file, 3);+ writeValue<uint16_t>(file, 0);+ }+ // SMinSampleValue+ writeValue<uint16_t>(file, 0x0154u);+ writeValue<uint16_t>(file, 0x000bu);+ writeValue<uint32_t>(file, channels);+ if (channels > 1)+ writeValue<uint32_t>(file, 0x00d2u+channels*4); // Offset of 0.f, 0.f, ...+ else+ writeValue<float>(file, 0.f);+ // SMaxSampleValue+ writeValue<uint16_t>(file, 0x0155u);+ writeValue<uint16_t>(file, 0x000bu);+ writeValue<uint32_t>(file, channels);+ if (channels > 1)+ writeValue<uint32_t>(file, 0x00d2u+channels*8); // Offset of 1.f, 1.f, ...+ else+ writeValue<float>(file, 1.f);+ // Offset = 0x00be++ writeValue<uint32_t>(file, 0);++ if (channels > 1) {+ // 0x00c2 BitsPerSample data+ writeValueRepeated<uint16_t>(file, 32, channels);+ // 0x00c2 + 2*N XResolution data+ writeValue<uint32_t>(file, 300);+ writeValue<uint32_t>(file, 1);+ // 0x00ca + 2*N YResolution data+ writeValue<uint32_t>(file, 300);+ writeValue<uint32_t>(file, 1);+ // 0x00d2 + 2*N SampleFormat data+ writeValueRepeated<uint16_t>(file, 3, channels);+ // 0x00d2 + 4*N SMinSampleValue data+ writeValueRepeated<float>(file, 0.f, channels);+ // 0x00d2 + 8*N SMaxSampleValue data+ writeValueRepeated<float>(file, 1.f, channels);+ // Offset = 0x00d2 + 12*N+ } else {+ // 0x00c2 XResolution data+ writeValue<uint32_t>(file, 300);+ writeValue<uint32_t>(file, 1);+ // 0x00ca YResolution data+ writeValue<uint32_t>(file, 300);+ writeValue<uint32_t>(file, 1);+ // Offset = 0x00d2+ }++ return true;+}++template <int N>+bool saveTiffFloat(BitmapConstSection<float, N> bitmap, const char *filename) {+ FILE *file = fopen(filename, "wb");+ if (!file)+ return false;+ bitmap.reorient(Y_DOWNWARD);+ writeTiffHeader(file, bitmap.width, bitmap.height, N);+ for (int y = 0; y < bitmap.height; ++y)+ fwrite(bitmap(0, y), sizeof(float), N*bitmap.width, file);+ return !fclose(file);+}++bool saveTiff(const BitmapConstSection<float, 1> &bitmap, const char *filename) {+ return saveTiffFloat(bitmap, filename);+}+bool saveTiff(const BitmapConstSection<float, 3> &bitmap, const char *filename) {+ return saveTiffFloat(bitmap, filename);+}+bool saveTiff(const BitmapConstSection<float, 4> &bitmap, const char *filename) {+ return saveTiffFloat(bitmap, filename);+}++}diff --git a/third_party/msdfgen/core/save-tiff.h b/third_party/msdfgen/core/save-tiff.hnew file mode 100644index 000000000..7884fc9a3--- /dev/null+++ b/third_party/msdfgen/core/save-tiff.h@@ -0,0 +1,13 @@++#pragma once++#include "BitmapRef.hpp"++namespace msdfgen {++/// Saves the bitmap as an uncompressed floating-point TIFF file.+bool saveTiff(const BitmapConstSection<float, 1> &bitmap, const char *filename);+bool saveTiff(const BitmapConstSection<float, 3> &bitmap, const char *filename);+bool saveTiff(const BitmapConstSection<float, 4> &bitmap, const char *filename);++}diff --git a/third_party/msdfgen/core/sdf-error-estimation.cpp b/third_party/msdfgen/core/sdf-error-estimation.cppnew file mode 100644index 000000000..65af66494--- /dev/null+++ b/third_party/msdfgen/core/sdf-error-estimation.cpp@@ -0,0 +1,204 @@++#include "sdf-error-estimation.h"++#include <cmath>+#include "arithmetics.hpp"++namespace msdfgen {++void scanlineSDF(Scanline &line, const BitmapConstSection<float, 1> &sdf, const Projection &projection, double y, YAxisOrientation yAxisOrientation) {+ if (!(sdf.width > 0 && sdf.height > 0))+ return line.setIntersections(std::vector<Scanline::Intersection>());+ double pixelY = clamp(projection.projectY(y)-.5, double(sdf.height-1));+ if (yAxisOrientation == Y_DOWNWARD)+ pixelY = sdf.height-1-pixelY;+ int b = (int) floor(pixelY);+ int t = b+1;+ double bt = pixelY-b;+ if (t >= sdf.height) {+ b = sdf.height-1;+ t = sdf.height-1;+ bt = 1;+ }+ bool inside = false;+ std::vector<Scanline::Intersection> intersections;+ float lv, rv = mix(*sdf(0, b), *sdf(0, t), bt);+ if ((inside = rv > .5f)) {+ Scanline::Intersection intersection = { -1e240, 1 };+ intersections.push_back(intersection);+ }+ for (int l = 0, r = 1; r < sdf.width; ++l, ++r) {+ lv = rv;+ rv = mix(*sdf(r, b), *sdf(r, t), bt);+ if (lv != rv) {+ double lr = double(.5f-lv)/double(rv-lv);+ if (lr >= 0 && lr <= 1) {+ Scanline::Intersection intersection = { projection.unprojectX(l+lr+.5), sign(rv-lv) };+ intersections.push_back(intersection);+ }+ }+ }+#ifdef MSDFGEN_USE_CPP11+ line.setIntersections((std::vector<Scanline::Intersection> &&) intersections);+#else+ line.setIntersections(intersections);+#endif+}++template <int N>+void scanlineMSDF(Scanline &line, const BitmapConstSection<float, N> &sdf, const Projection &projection, double y, YAxisOrientation yAxisOrientation) {+ if (!(sdf.width > 0 && sdf.height > 0))+ return line.setIntersections(std::vector<Scanline::Intersection>());+ double pixelY = clamp(projection.projectY(y)-.5, double(sdf.height-1));+ if (yAxisOrientation == Y_DOWNWARD)+ pixelY = sdf.height-1-pixelY;+ int b = (int) floor(pixelY);+ int t = b+1;+ double bt = pixelY-b;+ if (t >= sdf.height) {+ b = sdf.height-1;+ t = sdf.height-1;+ bt = 1;+ }+ bool inside = false;+ std::vector<Scanline::Intersection> intersections;+ float lv[3], rv[3];+ rv[0] = mix(sdf(0, b)[0], sdf(0, t)[0], bt);+ rv[1] = mix(sdf(0, b)[1], sdf(0, t)[1], bt);+ rv[2] = mix(sdf(0, b)[2], sdf(0, t)[2], bt);+ if ((inside = median(rv[0], rv[1], rv[2]) > .5f)) {+ Scanline::Intersection intersection = { -1e240, 1 };+ intersections.push_back(intersection);+ }+ for (int l = 0, r = 1; r < sdf.width; ++l, ++r) {+ lv[0] = rv[0], lv[1] = rv[1], lv[2] = rv[2];+ rv[0] = mix(sdf(r, b)[0], sdf(r, t)[0], bt);+ rv[1] = mix(sdf(r, b)[1], sdf(r, t)[1], bt);+ rv[2] = mix(sdf(r, b)[2], sdf(r, t)[2], bt);+ Scanline::Intersection newIntersections[4];+ int newIntersectionCount = 0;+ for (int i = 0; i < 3; ++i) {+ if (lv[i] != rv[i]) {+ double lr = double(.5f-lv[i])/double(rv[i]-lv[i]);+ if (lr >= 0 && lr <= 1) {+ float v[3] = {+ mix(lv[0], rv[0], lr),+ mix(lv[1], rv[1], lr),+ mix(lv[2], rv[2], lr)+ };+ if (median(v[0], v[1], v[2]) == v[i]) {+ newIntersections[newIntersectionCount].x = projection.unprojectX(l+lr+.5);+ newIntersections[newIntersectionCount].direction = sign(rv[i]-lv[i]);+ ++newIntersectionCount;+ }+ }+ }+ }+ // Sort new intersections+ if (newIntersectionCount >= 2) {+ if (newIntersections[0].x > newIntersections[1].x)+ newIntersections[3] = newIntersections[0], newIntersections[0] = newIntersections[1], newIntersections[1] = newIntersections[3];+ if (newIntersectionCount >= 3 && newIntersections[1].x > newIntersections[2].x) {+ newIntersections[3] = newIntersections[1], newIntersections[1] = newIntersections[2], newIntersections[2] = newIntersections[3];+ if (newIntersections[0].x > newIntersections[1].x)+ newIntersections[3] = newIntersections[0], newIntersections[0] = newIntersections[1], newIntersections[1] = newIntersections[3];+ }+ }+ for (int i = 0; i < newIntersectionCount; ++i) {+ if ((newIntersections[i].direction > 0) == !inside) {+ intersections.push_back(newIntersections[i]);+ inside = !inside;+ }+ }+ // Consistency check+ float rvScalar = median(rv[0], rv[1], rv[2]);+ if ((rvScalar > .5f) != inside && rvScalar != .5f && !intersections.empty()) {+ intersections.pop_back();+ inside = !inside;+ }+ }+#ifdef MSDFGEN_USE_CPP11+ line.setIntersections((std::vector<Scanline::Intersection> &&) intersections);+#else+ line.setIntersections(intersections);+#endif+}++void scanlineSDF(Scanline &line, const BitmapConstSection<float, 3> &sdf, const Projection &projection, double y, YAxisOrientation yAxisOrientation) {+ scanlineMSDF(line, sdf, projection, y, yAxisOrientation);+}+void scanlineSDF(Scanline &line, const BitmapConstSection<float, 4> &sdf, const Projection &projection, double y, YAxisOrientation yAxisOrientation) {+ scanlineMSDF(line, sdf, projection, y, yAxisOrientation);+}++template <int N>+double estimateSDFErrorInner(const BitmapConstSection<float, N> &sdf, const Shape &shape, const Projection &projection, int scanlinesPerRow, FillRule fillRule) {+ if (sdf.width <= 1 || sdf.height <= 1 || scanlinesPerRow < 1)+ return 0;+ double subRowSize = 1./scanlinesPerRow;+ double xFrom = projection.unprojectX(.5);+ double xTo = projection.unprojectX(sdf.width-.5);+ double overlapFactor = 1/(xTo-xFrom);+ double error = 0;+ Scanline refScanline, sdfScanline;+ for (int row = 0; row < sdf.height-1; ++row) {+ for (int subRow = 0; subRow < scanlinesPerRow; ++subRow) {+ double bt = (subRow+.5)*subRowSize;+ double y = projection.unprojectY(row+bt+.5);+ shape.scanline(refScanline, y);+ scanlineSDF(sdfScanline, sdf, projection, y, shape.getYAxisOrientation());+ error += 1-overlapFactor*Scanline::overlap(refScanline, sdfScanline, xFrom, xTo, fillRule);+ }+ }+ return error/((sdf.height-1)*scanlinesPerRow);+}++double estimateSDFError(const BitmapConstSection<float, 1> &sdf, const Shape &shape, const Projection &projection, int scanlinesPerRow, FillRule fillRule) {+ return estimateSDFErrorInner(sdf, shape, projection, scanlinesPerRow, fillRule);+}+double estimateSDFError(const BitmapConstSection<float, 3> &sdf, const Shape &shape, const Projection &projection, int scanlinesPerRow, FillRule fillRule) {+ return estimateSDFErrorInner(sdf, shape, projection, scanlinesPerRow, fillRule);+}+double estimateSDFError(const BitmapConstSection<float, 4> &sdf, const Shape &shape, const Projection &projection, int scanlinesPerRow, FillRule fillRule) {+ return estimateSDFErrorInner(sdf, shape, projection, scanlinesPerRow, fillRule);+}++// Legacy API++void scanlineSDF(Scanline &line, const BitmapConstSection<float, 1> &sdf, const Projection &projection, double y, bool inverseYAxis) {+ scanlineSDF(line, sdf, projection, y, inverseYAxis ? MSDFGEN_Y_AXIS_NONDEFAULT_ORIENTATION : MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION);+}++void scanlineSDF(Scanline &line, const BitmapConstSection<float, 3> &sdf, const Projection &projection, double y, bool inverseYAxis) {+ scanlineSDF(line, sdf, projection, y, inverseYAxis ? MSDFGEN_Y_AXIS_NONDEFAULT_ORIENTATION : MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION);+}++void scanlineSDF(Scanline &line, const BitmapConstSection<float, 4> &sdf, const Projection &projection, double y, bool inverseYAxis) {+ scanlineSDF(line, sdf, projection, y, inverseYAxis ? MSDFGEN_Y_AXIS_NONDEFAULT_ORIENTATION : MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION);+}++void scanlineSDF(Scanline &line, const BitmapConstSection<float, 1> &sdf, const Vector2 &scale, const Vector2 &translate, bool inverseYAxis, double y) {+ scanlineSDF(line, sdf, Projection(scale, translate), y, inverseYAxis);+}++void scanlineSDF(Scanline &line, const BitmapConstSection<float, 3> &sdf, const Vector2 &scale, const Vector2 &translate, bool inverseYAxis, double y) {+ scanlineSDF(line, sdf, Projection(scale, translate), y, inverseYAxis);+}++void scanlineSDF(Scanline &line, const BitmapConstSection<float, 4> &sdf, const Vector2 &scale, const Vector2 &translate, bool inverseYAxis, double y) {+ scanlineSDF(line, sdf, Projection(scale, translate), y, inverseYAxis);+}++double estimateSDFError(const BitmapConstSection<float, 1> &sdf, const Shape &shape, const Vector2 &scale, const Vector2 &translate, int scanlinesPerRow, FillRule fillRule) {+ return estimateSDFError(sdf, shape, Projection(scale, translate), scanlinesPerRow, fillRule);+}++double estimateSDFError(const BitmapConstSection<float, 3> &sdf, const Shape &shape, const Vector2 &scale, const Vector2 &translate, int scanlinesPerRow, FillRule fillRule) {+ return estimateSDFError(sdf, shape, Projection(scale, translate), scanlinesPerRow, fillRule);+}++double estimateSDFError(const BitmapConstSection<float, 4> &sdf, const Shape &shape, const Vector2 &scale, const Vector2 &translate, int scanlinesPerRow, FillRule fillRule) {+ return estimateSDFError(sdf, shape, Projection(scale, translate), scanlinesPerRow, fillRule);+}++}diff --git a/third_party/msdfgen/core/sdf-error-estimation.h b/third_party/msdfgen/core/sdf-error-estimation.hnew file mode 100644index 000000000..a669c5955--- /dev/null+++ b/third_party/msdfgen/core/sdf-error-estimation.h@@ -0,0 +1,33 @@++#pragma once++#include "Vector2.hpp"+#include "Shape.h"+#include "Projection.h"+#include "Scanline.h"+#include "BitmapRef.hpp"++namespace msdfgen {++/// Analytically constructs a scanline at y evaluating fill by linear interpolation of the SDF.+void scanlineSDF(Scanline &line, const BitmapConstSection<float, 1> &sdf, const Projection &projection, double y, YAxisOrientation yAxisOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION);+void scanlineSDF(Scanline &line, const BitmapConstSection<float, 3> &sdf, const Projection &projection, double y, YAxisOrientation yAxisOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION);+void scanlineSDF(Scanline &line, const BitmapConstSection<float, 4> &sdf, const Projection &projection, double y, YAxisOrientation yAxisOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION);++/// Estimates the portion of the area that will be filled incorrectly when rendering using the SDF.+double estimateSDFError(const BitmapConstSection<float, 1> &sdf, const Shape &shape, const Projection &projection, int scanlinesPerRow, FillRule fillRule = FILL_NONZERO);+double estimateSDFError(const BitmapConstSection<float, 3> &sdf, const Shape &shape, const Projection &projection, int scanlinesPerRow, FillRule fillRule = FILL_NONZERO);+double estimateSDFError(const BitmapConstSection<float, 4> &sdf, const Shape &shape, const Projection &projection, int scanlinesPerRow, FillRule fillRule = FILL_NONZERO);++// Old version of the function API's kept for backwards compatibility+void scanlineSDF(Scanline &line, const BitmapConstSection<float, 1> &sdf, const Projection &projection, double y, bool inverseYAxis);+void scanlineSDF(Scanline &line, const BitmapConstSection<float, 3> &sdf, const Projection &projection, double y, bool inverseYAxis);+void scanlineSDF(Scanline &line, const BitmapConstSection<float, 4> &sdf, const Projection &projection, double y, bool inverseYAxis);+void scanlineSDF(Scanline &line, const BitmapConstSection<float, 1> &sdf, const Vector2 &scale, const Vector2 &translate, bool inverseYAxis, double y);+void scanlineSDF(Scanline &line, const BitmapConstSection<float, 3> &sdf, const Vector2 &scale, const Vector2 &translate, bool inverseYAxis, double y);+void scanlineSDF(Scanline &line, const BitmapConstSection<float, 4> &sdf, const Vector2 &scale, const Vector2 &translate, bool inverseYAxis, double y);+double estimateSDFError(const BitmapConstSection<float, 1> &sdf, const Shape &shape, const Vector2 &scale, const Vector2 &translate, int scanlinesPerRow, FillRule fillRule = FILL_NONZERO);+double estimateSDFError(const BitmapConstSection<float, 3> &sdf, const Shape &shape, const Vector2 &scale, const Vector2 &translate, int scanlinesPerRow, FillRule fillRule = FILL_NONZERO);+double estimateSDFError(const BitmapConstSection<float, 4> &sdf, const Shape &shape, const Vector2 &scale, const Vector2 &translate, int scanlinesPerRow, FillRule fillRule = FILL_NONZERO);++}diff --git a/third_party/msdfgen/core/shape-description.cpp b/third_party/msdfgen/core/shape-description.cppnew file mode 100644index 000000000..6d081a957--- /dev/null+++ b/third_party/msdfgen/core/shape-description.cpp@@ -0,0 +1,335 @@++#ifndef _CRT_SECURE_NO_WARNINGS+#define _CRT_SECURE_NO_WARNINGS+#endif++#include "shape-description.h"++#include <cstdlib>++namespace msdfgen {++int readCharF(FILE *input) {+ int c = '\0';+ do {+ c = fgetc(input);+ } while (c == ' ' || c == '\t' || c == '\r' || c == '\n');+ return c;+}++int readCharS(const char **input) {+ int c = '\0';+ do {+ c = *(*input)++;+ } while (c == ' ' || c == '\t' || c == '\r' || c == '\n');+ if (!c) {+ --c;+ return EOF;+ }+ return c;+}++int readCoordF(FILE *input, Point2 &coord) {+ return fscanf(input, "%lf , %lf", &coord.x, &coord.y);+}++int readCoordS(const char **input, Point2 &coord) {+ char *end = NULL;+ coord.x = strtod(*input, &end);+ if (end <= *input)+ return 0;+ *input = end;+ while (**input == ' ' || **input == '\t' || **input == '\n' || **input == '\r')+ ++*input;+ if (**input != ',')+ return 1;+ ++*input;+ coord.y = strtod(*input, &end);+ if (end <= *input)+ return 1;+ *input = end;+ return 2;+}++bool matchStringS(const char **input, const char *str) {+ const char *cur = *input;+ while (*cur && *str && *cur == *str)+ ++cur, ++str;+ if (!*str) {+ *input = cur;+ return true;+ }+ return false;+}++static bool writeCoord(FILE *output, Point2 coord) {+ fprintf(output, "%.12g, %.12g", coord.x, coord.y);+ return true;+}++template <typename T, int (*readChar)(T *), int (*readCoord)(T *, Point2 &)>+static int readControlPoints(T *input, Point2 *output) {+ int result = readCoord(input, output[0]);+ if (result == 2) {+ switch (readChar(input)) {+ case ')':+ return 1;+ case ';':+ break;+ default:+ return -1;+ }+ result = readCoord(input, output[1]);+ if (result == 2 && readChar(input) == ')')+ return 2;+ } else if (result != 1 && readChar(input) == ')')+ return 0;+ return -1;+}++template <typename T, int (*readChar)(T *), int (*readCoord)(T *, Point2 &)>+static bool readContour(T *input, Contour &output, const Point2 *first, int terminator, bool &colorsSpecified) {+ Point2 p[4], start;+ if (first)+ p[0] = *first;+ else {+ int result = readCoord(input, p[0]);+ if (result != 2)+ return result != 1 && readChar(input) == terminator;+ }+ start = p[0];+ int c = '\0';+ while ((c = readChar(input)) != terminator) {+ if (c != ';')+ return false;+ EdgeColor color = WHITE;+ int result = readCoord(input, p[1]);+ if (result == 2) {+ output.addEdge(EdgeHolder(p[0], p[1], color));+ p[0] = p[1];+ continue;+ } else if (result == 1)+ return false;+ else {+ int controlPoints = 0;+ switch ((c = readChar(input))) {+ case '#':+ output.addEdge(EdgeHolder(p[0], start, color));+ p[0] = start;+ continue;+ case ';':+ goto FINISH_EDGE;+ case '(':+ goto READ_CONTROL_POINTS;+ case 'C': case 'c':+ color = CYAN;+ colorsSpecified = true;+ break;+ case 'M': case 'm':+ color = MAGENTA;+ colorsSpecified = true;+ break;+ case 'Y': case 'y':+ color = YELLOW;+ colorsSpecified = true;+ break;+ case 'W': case 'w':+ color = WHITE;+ colorsSpecified = true;+ break;+ default:+ return c == terminator;+ }+ switch (readChar(input)) {+ case ';':+ goto FINISH_EDGE;+ case '(':+ READ_CONTROL_POINTS:+ if ((controlPoints = readControlPoints<T, readChar, readCoord>(input, p+1)) < 0)+ return false;+ break;+ default:+ return false;+ }+ if (readChar(input) != ';')+ return false;+ FINISH_EDGE:+ result = readCoord(input, p[1+controlPoints]);+ if (result != 2) {+ if (result == 1)+ return false;+ else {+ if (readChar(input) == '#')+ p[1+controlPoints] = start;+ else+ return false;+ }+ }+ switch (controlPoints) {+ case 0:+ output.addEdge(EdgeHolder(p[0], p[1], color));+ p[0] = p[1];+ continue;+ case 1:+ output.addEdge(EdgeHolder(p[0], p[1], p[2], color));+ p[0] = p[2];+ continue;+ case 2:+ output.addEdge(EdgeHolder(p[0], p[1], p[2], p[3], color));+ p[0] = p[3];+ continue;+ }+ }+ }+ return true;+}++bool readShapeDescription(FILE *input, Shape &output, bool *colorsSpecified) {+ bool locColorsSpec = false;+ output.contours.clear();+ output.setYAxisOrientation(MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION);+ Point2 p;+ int result = readCoordF(input, p);+ if (result == 2) {+ return readContour<FILE, readCharF, readCoordF>(input, output.addContour(), &p, EOF, locColorsSpec);+ } else if (result == 1)+ return false;+ else {+ int c = readCharF(input);+ if (c == '@') {+ char after = '\0';+ if (fscanf(input, "y-%c", &after) == 1 && (after == 'u' || after == 'd')) {+ switch (after) {+ case 'u':+ output.setYAxisOrientation(Y_UPWARD);+ break;+ case 'd':+ output.setYAxisOrientation(Y_DOWNWARD);+ break;+ }+ if (fscanf(input, after == 'u' ? "p%c" : "own%c", &after) != 1)+ return feof(input) != 0;+ } else if (fscanf(input, "invert-y%c", &after) == 1)+ output.inverseYAxis = true;+ else+ return feof(input) != 0;+ c = after;+ if (c == ' ' || c == '\t' || c == '\r' || c == '\n')+ c = readCharF(input);+ }+ for (; c == '{'; c = readCharF(input))+ if (!readContour<FILE, readCharF, readCoordF>(input, output.addContour(), NULL, '}', locColorsSpec))+ return false;+ if (colorsSpecified)+ *colorsSpecified = locColorsSpec;+ return c == EOF && feof(input);+ }+}++bool readShapeDescription(const char *input, Shape &output, bool *colorsSpecified) {+ bool locColorsSpec = false;+ output.contours.clear();+ output.setYAxisOrientation(MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION);+ Point2 p;+ int result = readCoordS(&input, p);+ if (result == 2) {+ return readContour<const char *, readCharS, readCoordS>(&input, output.addContour(), &p, EOF, locColorsSpec);+ } else if (result == 1)+ return false;+ else {+ int c = readCharS(&input);+ if (c == '@') {+ if (matchStringS(&input, "y-down"))+ output.setYAxisOrientation(Y_DOWNWARD);+ else if (matchStringS(&input, "y-up"))+ output.setYAxisOrientation(Y_UPWARD);+ else if (matchStringS(&input, "invert-y"))+ output.inverseYAxis = true;+ else+ return false;+ c = readCharS(&input);+ }+ for (; c == '{'; c = readCharS(&input))+ if (!readContour<const char *, readCharS, readCoordS>(&input, output.addContour(), NULL, '}', locColorsSpec))+ return false;+ if (colorsSpecified)+ *colorsSpecified = locColorsSpec;+ return c == EOF;+ }+}++static bool isColored(const Shape &shape) {+ for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)+ for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge)+ if ((*edge)->color != WHITE)+ return true;+ return false;+}++bool writeShapeDescription(FILE *output, const Shape &shape) {+ if (!shape.validate())+ return false;+ bool writeColors = isColored(shape);+ switch (shape.getYAxisOrientation()) {+ case Y_UPWARD:+ fprintf(output, "@y-up\n");+ break;+ case Y_DOWNWARD:+ fprintf(output, "@y-down\n");+ break;+ }+ for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour) {+ fprintf(output, "{\n");+ if (!contour->edges.empty()) {+ for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {+ char colorCode = '\0';+ if (writeColors) {+ switch ((*edge)->color) {+ case YELLOW: colorCode = 'y'; break;+ case MAGENTA: colorCode = 'm'; break;+ case CYAN: colorCode = 'c'; break;+ case WHITE: colorCode = 'w'; break;+ default:;+ }+ }+ const Point2 *p = (*edge)->controlPoints();+ switch ((*edge)->type()) {+ case (int) LinearSegment::EDGE_TYPE:+ fprintf(output, "\t");+ writeCoord(output, p[0]);+ fprintf(output, ";\n");+ if (colorCode)+ fprintf(output, "\t\t%c;\n", colorCode);+ break;+ case (int) QuadraticSegment::EDGE_TYPE:+ fprintf(output, "\t");+ writeCoord(output, p[0]);+ fprintf(output, ";\n\t\t");+ if (colorCode)+ fprintf(output, "%c", colorCode);+ fprintf(output, "(");+ writeCoord(output, p[1]);+ fprintf(output, ");\n");+ break;+ case (int) CubicSegment::EDGE_TYPE:+ fprintf(output, "\t");+ writeCoord(output, p[0]);+ fprintf(output, ";\n\t\t");+ if (colorCode)+ fprintf(output, "%c", colorCode);+ fprintf(output, "(");+ writeCoord(output, p[1]);+ fprintf(output, "; ");+ writeCoord(output, p[2]);+ fprintf(output, ");\n");+ break;+ }+ }+ fprintf(output, "\t#\n");+ }+ fprintf(output, "}\n");+ }+ return true;+}++}diff --git a/third_party/msdfgen/core/shape-description.h b/third_party/msdfgen/core/shape-description.hnew file mode 100644index 000000000..6e2e22367--- /dev/null+++ b/third_party/msdfgen/core/shape-description.h@@ -0,0 +1,15 @@++#pragma once++#include <cstdio>+#include "Shape.h"++namespace msdfgen {++/// Deserializes a text description of a vector shape into output.+bool readShapeDescription(FILE *input, Shape &output, bool *colorsSpecified = NULL);+bool readShapeDescription(const char *input, Shape &output, bool *colorsSpecified = NULL);+/// Serializes a shape object into a text description.+bool writeShapeDescription(FILE *output, const Shape &shape);++}diff --git a/third_party/msdfgen/ext/import-font.cpp b/third_party/msdfgen/ext/import-font.cppnew file mode 100644index 000000000..37a426f51--- /dev/null+++ b/third_party/msdfgen/ext/import-font.cpp@@ -0,0 +1,315 @@++#include "import-font.h"++#include <cstring>+#include <vector>+#include <ft2build.h>+#include FT_FREETYPE_H+#include FT_OUTLINE_H+#ifndef MSDFGEN_DISABLE_VARIABLE_FONTS+#include FT_MULTIPLE_MASTERS_H+#endif++namespace msdfgen {++#define F16DOT16_TO_DOUBLE(x) (1/65536.*double(x))+#define DOUBLE_TO_F16DOT16(x) FT_Fixed(65536.*x)++class FreetypeHandle {+ friend FreetypeHandle *initializeFreetype();+ friend void deinitializeFreetype(FreetypeHandle *library);+ friend FontHandle *loadFont(FreetypeHandle *library, const char *filename);+ friend FontHandle *loadFontData(FreetypeHandle *library, const byte *data, int length);+#ifndef MSDFGEN_DISABLE_VARIABLE_FONTS+ friend bool setFontVariationAxis(FreetypeHandle *library, FontHandle *font, const char *name, double coordinate);+ friend bool listFontVariationAxes(std::vector<FontVariationAxis> &axes, FreetypeHandle *library, FontHandle *font);+#endif++ FT_Library library;++};++class FontHandle {+ friend FontHandle *adoptFreetypeFont(FT_Face ftFace);+ friend FontHandle *loadFont(FreetypeHandle *library, const char *filename);+ friend FontHandle *loadFontData(FreetypeHandle *library, const byte *data, int length);+ friend void destroyFont(FontHandle *font);+ friend bool getFontMetrics(FontMetrics &metrics, FontHandle *font, FontCoordinateScaling coordinateScaling);+ friend bool getFontWhitespaceWidth(double &spaceAdvance, double &tabAdvance, FontHandle *font, FontCoordinateScaling coordinateScaling);+ friend bool getGlyphCount(unsigned &output, FontHandle *font);+ friend bool getGlyphIndex(GlyphIndex &glyphIndex, FontHandle *font, unicode_t unicode);+ friend bool loadGlyph(Shape &output, FontHandle *font, GlyphIndex glyphIndex, FontCoordinateScaling coordinateScaling, double *outAdvance);+ friend bool loadGlyph(Shape &output, FontHandle *font, unicode_t unicode, FontCoordinateScaling coordinateScaling, double *outAdvance);+ friend bool getKerning(double &output, FontHandle *font, GlyphIndex glyphIndex0, GlyphIndex glyphIndex1, FontCoordinateScaling coordinateScaling);+ friend bool getKerning(double &output, FontHandle *font, unicode_t unicode0, unicode_t unicode1, FontCoordinateScaling coordinateScaling);+#ifndef MSDFGEN_DISABLE_VARIABLE_FONTS+ friend bool setFontVariationAxis(FreetypeHandle *library, FontHandle *font, const char *name, double coordinate);+ friend bool listFontVariationAxes(std::vector<FontVariationAxis> &axes, FreetypeHandle *library, FontHandle *font);+#endif++ FT_Face face;+ bool ownership;++};++struct FtContext {+ double scale;+ Point2 position;+ Shape *shape;+ Contour *contour;+};++static Point2 ftPoint2(const FT_Vector &vector, double scale) {+ return Point2(scale*vector.x, scale*vector.y);+}++static int ftMoveTo(const FT_Vector *to, void *user) {+ FtContext *context = reinterpret_cast<FtContext *>(user);+ if (!(context->contour && context->contour->edges.empty()))+ context->contour = &context->shape->addContour();+ context->position = ftPoint2(*to, context->scale);+ return 0;+}++static int ftLineTo(const FT_Vector *to, void *user) {+ FtContext *context = reinterpret_cast<FtContext *>(user);+ Point2 endpoint = ftPoint2(*to, context->scale);+ if (endpoint != context->position) {+ context->contour->addEdge(EdgeHolder(context->position, endpoint));+ context->position = endpoint;+ }+ return 0;+}++static int ftConicTo(const FT_Vector *control, const FT_Vector *to, void *user) {+ FtContext *context = reinterpret_cast<FtContext *>(user);+ Point2 endpoint = ftPoint2(*to, context->scale);+ if (endpoint != context->position) {+ context->contour->addEdge(EdgeHolder(context->position, ftPoint2(*control, context->scale), endpoint));+ context->position = endpoint;+ }+ return 0;+}++static int ftCubicTo(const FT_Vector *control1, const FT_Vector *control2, const FT_Vector *to, void *user) {+ FtContext *context = reinterpret_cast<FtContext *>(user);+ Point2 endpoint = ftPoint2(*to, context->scale);+ if (endpoint != context->position || crossProduct(ftPoint2(*control1, context->scale)-endpoint, ftPoint2(*control2, context->scale)-endpoint)) {+ context->contour->addEdge(EdgeHolder(context->position, ftPoint2(*control1, context->scale), ftPoint2(*control2, context->scale), endpoint));+ context->position = endpoint;+ }+ return 0;+}++static double getFontCoordinateScale(const FT_Face &face, FontCoordinateScaling coordinateScaling) {+ switch (coordinateScaling) {+ case FONT_SCALING_NONE:+ return 1;+ case FONT_SCALING_EM_NORMALIZED:+ return 1./(face->units_per_EM ? face->units_per_EM : 1);+ case FONT_SCALING_LEGACY:+ return MSDFGEN_LEGACY_FONT_COORDINATE_SCALE;+ }+ return 1;+}++GlyphIndex::GlyphIndex(unsigned index) : index(index) { }++unsigned GlyphIndex::getIndex() const {+ return index;+}++FreetypeHandle *initializeFreetype() {+ FreetypeHandle *handle = new FreetypeHandle;+ FT_Error error = FT_Init_FreeType(&handle->library);+ if (error) {+ delete handle;+ return NULL;+ }+ return handle;+}++void deinitializeFreetype(FreetypeHandle *library) {+ FT_Done_FreeType(library->library);+ delete library;+}++FontHandle *adoptFreetypeFont(FT_Face ftFace) {+ FontHandle *handle = new FontHandle;+ handle->face = ftFace;+ handle->ownership = false;+ return handle;+}++FT_Error readFreetypeOutline(Shape &output, FT_Outline *outline, double scale) {+ output.contours.clear();+ output.setYAxisOrientation(Y_UPWARD);+ FtContext context = { };+ context.scale = scale;+ context.shape = &output;+ FT_Outline_Funcs ftFunctions;+ ftFunctions.move_to = &ftMoveTo;+ ftFunctions.line_to = &ftLineTo;+ ftFunctions.conic_to = &ftConicTo;+ ftFunctions.cubic_to = &ftCubicTo;+ ftFunctions.shift = 0;+ ftFunctions.delta = 0;+ FT_Error error = FT_Outline_Decompose(outline, &ftFunctions, &context);+ if (!output.contours.empty() && output.contours.back().edges.empty())+ output.contours.pop_back();+ return error;+}++FontHandle *loadFont(FreetypeHandle *library, const char *filename) {+ if (!library)+ return NULL;+ FontHandle *handle = new FontHandle;+ FT_Error error = FT_New_Face(library->library, filename, 0, &handle->face);+ if (error) {+ delete handle;+ return NULL;+ }+ handle->ownership = true;+ return handle;+}++FontHandle *loadFontData(FreetypeHandle *library, const byte *data, int length) {+ if (!library)+ return NULL;+ FontHandle *handle = new FontHandle;+ FT_Error error = FT_New_Memory_Face(library->library, data, length, 0, &handle->face);+ if (error) {+ delete handle;+ return NULL;+ }+ handle->ownership = true;+ return handle;+}++void destroyFont(FontHandle *font) {+ if (font->ownership)+ FT_Done_Face(font->face);+ delete font;+}++bool getFontMetrics(FontMetrics &metrics, FontHandle *font, FontCoordinateScaling coordinateScaling) {+ double scale = getFontCoordinateScale(font->face, coordinateScaling);+ metrics.emSize = scale*font->face->units_per_EM;+ metrics.ascenderY = scale*font->face->ascender;+ metrics.descenderY = scale*font->face->descender;+ metrics.lineHeight = scale*font->face->height;+ metrics.underlineY = scale*font->face->underline_position;+ metrics.underlineThickness = scale*font->face->underline_thickness;+ return true;+}++bool getFontWhitespaceWidth(double &spaceAdvance, double &tabAdvance, FontHandle *font, FontCoordinateScaling coordinateScaling) {+ double scale = getFontCoordinateScale(font->face, coordinateScaling);+ FT_Error error = FT_Load_Char(font->face, ' ', FT_LOAD_NO_SCALE);+ if (error)+ return false;+ spaceAdvance = scale*font->face->glyph->advance.x;+ error = FT_Load_Char(font->face, '\t', FT_LOAD_NO_SCALE);+ if (error)+ return false;+ tabAdvance = scale*font->face->glyph->advance.x;+ return true;+}++bool getGlyphCount(unsigned &output, FontHandle *font) {+ output = (unsigned) font->face->num_glyphs;+ return true;+}++bool getGlyphIndex(GlyphIndex &glyphIndex, FontHandle *font, unicode_t unicode) {+ glyphIndex = GlyphIndex(FT_Get_Char_Index(font->face, unicode));+ return glyphIndex.getIndex() != 0;+}++bool loadGlyph(Shape &output, FontHandle *font, GlyphIndex glyphIndex, FontCoordinateScaling coordinateScaling, double *outAdvance) {+ if (!font)+ return false;+ FT_Error error = FT_Load_Glyph(font->face, glyphIndex.getIndex(), FT_LOAD_NO_SCALE);+ if (error)+ return false;+ double scale = getFontCoordinateScale(font->face, coordinateScaling);+ if (outAdvance)+ *outAdvance = scale*font->face->glyph->advance.x;+ return !readFreetypeOutline(output, &font->face->glyph->outline, scale);+}++bool loadGlyph(Shape &output, FontHandle *font, unicode_t unicode, FontCoordinateScaling coordinateScaling, double *outAdvance) {+ return loadGlyph(output, font, GlyphIndex(FT_Get_Char_Index(font->face, unicode)), coordinateScaling, outAdvance);+}++bool loadGlyph(Shape &output, FontHandle *font, GlyphIndex glyphIndex, double *outAdvance) {+ return loadGlyph(output, font, glyphIndex, FONT_SCALING_LEGACY, outAdvance);+}++bool loadGlyph(Shape &output, FontHandle *font, unicode_t unicode, double *outAdvance) {+ return loadGlyph(output, font, unicode, FONT_SCALING_LEGACY, outAdvance);+}++bool getKerning(double &output, FontHandle *font, GlyphIndex glyphIndex0, GlyphIndex glyphIndex1, FontCoordinateScaling coordinateScaling) {+ FT_Vector kerning;+ if (FT_Get_Kerning(font->face, glyphIndex0.getIndex(), glyphIndex1.getIndex(), FT_KERNING_UNSCALED, &kerning)) {+ output = 0;+ return false;+ }+ output = getFontCoordinateScale(font->face, coordinateScaling)*kerning.x;+ return true;+}++bool getKerning(double &output, FontHandle *font, unicode_t unicode0, unicode_t unicode1, FontCoordinateScaling coordinateScaling) {+ return getKerning(output, font, GlyphIndex(FT_Get_Char_Index(font->face, unicode0)), GlyphIndex(FT_Get_Char_Index(font->face, unicode1)), coordinateScaling);+}++#ifndef MSDFGEN_DISABLE_VARIABLE_FONTS++bool setFontVariationAxis(FreetypeHandle *library, FontHandle *font, const char *name, double coordinate) {+ bool success = false;+ if (font->face->face_flags&FT_FACE_FLAG_MULTIPLE_MASTERS) {+ FT_MM_Var *master = NULL;+ if (FT_Get_MM_Var(font->face, &master))+ return false;+ if (master && master->num_axis) {+ std::vector<FT_Fixed> coords(master->num_axis);+ if (!FT_Get_Var_Design_Coordinates(font->face, FT_UInt(coords.size()), &coords[0])) {+ for (FT_UInt i = 0; i < master->num_axis; ++i) {+ if (!strcmp(name, master->axis[i].name)) {+ coords[i] = DOUBLE_TO_F16DOT16(coordinate);+ success = true;+ break;+ }+ }+ }+ if (FT_Set_Var_Design_Coordinates(font->face, FT_UInt(coords.size()), &coords[0]))+ success = false;+ }+ FT_Done_MM_Var(library->library, master);+ }+ return success;+}++bool listFontVariationAxes(std::vector<FontVariationAxis> &axes, FreetypeHandle *library, FontHandle *font) {+ if (font->face->face_flags&FT_FACE_FLAG_MULTIPLE_MASTERS) {+ FT_MM_Var *master = NULL;+ if (FT_Get_MM_Var(font->face, &master))+ return false;+ axes.resize(master->num_axis);+ for (FT_UInt i = 0; i < master->num_axis; ++i) {+ FontVariationAxis &axis = axes[i];+ axis.name = master->axis[i].name;+ axis.minValue = F16DOT16_TO_DOUBLE(master->axis[i].minimum);+ axis.maxValue = F16DOT16_TO_DOUBLE(master->axis[i].maximum);+ axis.defaultValue = F16DOT16_TO_DOUBLE(master->axis[i].def);+ }+ FT_Done_MM_Var(library->library, master);+ return true;+ }+ return false;+}++#endif++}diff --git a/third_party/msdfgen/ext/import-font.h b/third_party/msdfgen/ext/import-font.hnew file mode 100644index 000000000..c2bd81ae6--- /dev/null+++ b/third_party/msdfgen/ext/import-font.h@@ -0,0 +1,103 @@++#pragma once++#include "../core/Shape.h"++namespace msdfgen {++#define MSDFGEN_LEGACY_FONT_COORDINATE_SCALE (1/64.)++typedef unsigned unicode_t;++class FreetypeHandle;+class FontHandle;++class GlyphIndex {++public:+ explicit GlyphIndex(unsigned index = 0);+ unsigned getIndex() const;++private:+ unsigned index;++};++/// Global metrics of a typeface (in font units).+struct FontMetrics {+ /// The size of one EM.+ double emSize;+ /// The vertical position of the ascender and descender relative to the baseline.+ double ascenderY, descenderY;+ /// The vertical difference between consecutive baselines.+ double lineHeight;+ /// The vertical position and thickness of the underline.+ double underlineY, underlineThickness;+};++/// A structure to model a given axis of a variable font.+struct FontVariationAxis {+ /// The name of the variation axis.+ const char *name;+ /// The axis's minimum coordinate value.+ double minValue;+ /// The axis's maximum coordinate value.+ double maxValue;+ /// The axis's default coordinate value. FreeType computes meaningful default values for Adobe MM fonts.+ double defaultValue;+};++/// The scaling applied to font glyph coordinates when loading a glyph+enum FontCoordinateScaling {+ /// The coordinates are kept as the integer values native to the font file+ FONT_SCALING_NONE,+ /// The coordinates will be normalized to the em size, i.e. 1 = 1 em+ FONT_SCALING_EM_NORMALIZED,+ /// The incorrect legacy version that was in effect before version 1.12, coordinate values are divided by 64 - DO NOT USE - for backwards compatibility only+ FONT_SCALING_LEGACY+};++/// Initializes the FreeType library.+FreetypeHandle *initializeFreetype();+/// Deinitializes the FreeType library.+void deinitializeFreetype(FreetypeHandle *library);++#ifdef FT_LOAD_DEFAULT // FreeType included+/// Creates a FontHandle from FT_Face that was loaded by the user. destroyFont must still be called but will not affect the FT_Face.+FontHandle *adoptFreetypeFont(FT_Face ftFace);+/// Converts the geometry of FreeType's FT_Outline to a Shape object.+FT_Error readFreetypeOutline(Shape &output, FT_Outline *outline, double scale = MSDFGEN_LEGACY_FONT_COORDINATE_SCALE);+#endif++/// Loads a font file and returns its handle.+FontHandle *loadFont(FreetypeHandle *library, const char *filename);+/// Loads a font from binary data and returns its handle.+FontHandle *loadFontData(FreetypeHandle *library, const byte *data, int length);+/// Unloads a font.+void destroyFont(FontHandle *font);+/// Outputs the metrics of a font.+bool getFontMetrics(FontMetrics &metrics, FontHandle *font, FontCoordinateScaling coordinateScaling = FONT_SCALING_LEGACY);+/// Outputs the width of the space and tab characters.+bool getFontWhitespaceWidth(double &spaceAdvance, double &tabAdvance, FontHandle *font, FontCoordinateScaling coordinateScaling = FONT_SCALING_LEGACY);+/// Outputs the total number of glyphs available in the font.+bool getGlyphCount(unsigned &output, FontHandle *font);+/// Outputs the glyph index corresponding to the specified Unicode character.+bool getGlyphIndex(GlyphIndex &glyphIndex, FontHandle *font, unicode_t unicode);+/// Loads the geometry of a glyph from a font.+bool loadGlyph(Shape &output, FontHandle *font, GlyphIndex glyphIndex, FontCoordinateScaling coordinateScaling, double *outAdvance = NULL);+bool loadGlyph(Shape &output, FontHandle *font, unicode_t unicode, FontCoordinateScaling coordinateScaling, double *outAdvance = NULL);+// Legacy API - FontCoordinateScaling is LEGACY+bool loadGlyph(Shape &output, FontHandle *font, GlyphIndex glyphIndex, double *outAdvance = NULL);+bool loadGlyph(Shape &output, FontHandle *font, unicode_t unicode, double *outAdvance = NULL);+/// Outputs the kerning distance adjustment between two specific glyphs.+bool getKerning(double &output, FontHandle *font, GlyphIndex glyphIndex0, GlyphIndex glyphIndex1, FontCoordinateScaling coordinateScaling = FONT_SCALING_LEGACY);+bool getKerning(double &output, FontHandle *font, unicode_t unicode0, unicode_t unicode1, FontCoordinateScaling coordinateScaling = FONT_SCALING_LEGACY);++#ifndef MSDFGEN_DISABLE_VARIABLE_FONTS+/// Sets a single variation axis of a variable font.+bool setFontVariationAxis(FreetypeHandle *library, FontHandle *font, const char *name, double coordinate);+/// Lists names and ranges of variation axes of a variable font.+bool listFontVariationAxes(std::vector<FontVariationAxis> &axes, FreetypeHandle *library, FontHandle *font);+#endif++}diff --git a/third_party/msdfgen/ext/import-svg.cpp b/third_party/msdfgen/ext/import-svg.cppnew file mode 100644index 000000000..752f798b3--- /dev/null+++ b/third_party/msdfgen/ext/import-svg.cpp@@ -0,0 +1,1065 @@++#ifndef _USE_MATH_DEFINES+#define _USE_MATH_DEFINES+#endif+#ifndef _CRT_SECURE_NO_WARNINGS+#define _CRT_SECURE_NO_WARNINGS+#endif++#include "import-svg.h"++#ifndef MSDFGEN_DISABLE_SVG++#include <cstdlib>+#include <cstdio>+#include <cstring>+#include <vector>+#include <string>+#include <stack>++#ifdef MSDFGEN_USE_TINYXML2+#include <tinyxml2.h>+#endif+#ifdef MSDFGEN_USE_DROPXML+#include <dropXML.hpp>+#endif++#ifdef MSDFGEN_USE_SKIA+#include <skia/core/SkPath.h>+#include <skia/utils/SkParsePath.h>+#include <skia/pathops/SkPathOps.h>+#endif++#include "../core/arithmetics.hpp"++#define ARC_SEGMENTS_PER_PI 2+#define ENDPOINT_SNAP_RANGE_PROPORTION (1/16384.)++namespace msdfgen {++#if defined(_DEBUG) || !NDEBUG+#define REQUIRE(cond) { if (!(cond)) { fprintf(stderr, "SVG Parse Error (%s:%d): " #cond "\n", __FILE__, __LINE__); return false; } }+#else+#define REQUIRE(cond) { if (!(cond)) return false; }+#endif++MSDFGEN_EXT_PUBLIC const int SVG_IMPORT_FAILURE = 0x00;+MSDFGEN_EXT_PUBLIC const int SVG_IMPORT_SUCCESS_FLAG = 0x01;+MSDFGEN_EXT_PUBLIC const int SVG_IMPORT_PARTIAL_FAILURE_FLAG = 0x02;+MSDFGEN_EXT_PUBLIC const int SVG_IMPORT_INCOMPLETE_FLAG = 0x04;+MSDFGEN_EXT_PUBLIC const int SVG_IMPORT_UNSUPPORTED_FEATURE_FLAG = 0x08;+MSDFGEN_EXT_PUBLIC const int SVG_IMPORT_TRANSFORMATION_IGNORED_FLAG = 0x10;++#define FLAGS_FINAL(flags) (((flags)&(SVG_IMPORT_SUCCESS_FLAG|SVG_IMPORT_INCOMPLETE_FLAG|SVG_IMPORT_UNSUPPORTED_FEATURE_FLAG)) == (SVG_IMPORT_SUCCESS_FLAG|SVG_IMPORT_INCOMPLETE_FLAG|SVG_IMPORT_UNSUPPORTED_FEATURE_FLAG))++static void skipExtraChars(const char *&pathDef) {+ while (*pathDef == ',' || *pathDef == ' ' || *pathDef == '\t' || *pathDef == '\r' || *pathDef == '\n')+ ++pathDef;+}++static bool readNodeType(char &output, const char *&pathDef) {+ skipExtraChars(pathDef);+ char nodeType = *pathDef;+ if (nodeType && nodeType != '+' && nodeType != '-' && nodeType != '.' && nodeType != ',' && (nodeType < '0' || nodeType > '9')) {+ ++pathDef;+ output = nodeType;+ return true;+ }+ return false;+}++static bool readDouble(double &output, const char *&pathDef) {+ skipExtraChars(pathDef);+ char *end = NULL;+ output = strtod(pathDef, &end);+ if (end > pathDef) {+ pathDef = end;+ return true;+ }+ return false;+}++static bool readCoord(Point2 &output, const char *&pathDef) {+ return readDouble(output.x, pathDef) && readDouble(output.y, pathDef);+}++static bool readBool(bool &output, const char *&pathDef) {+ skipExtraChars(pathDef);+ char *end = NULL;+ long v = strtol(pathDef, &end, 10);+ if (end > pathDef) {+ pathDef = end;+ output = v != 0;+ return true;+ }+ return false;+}++static double arcAngle(Vector2 u, Vector2 v) {+ return nonZeroSign(crossProduct(u, v))*acos(clamp(dotProduct(u, v)/(u.length()*v.length()), -1., +1.));+}++static Vector2 rotateVector(Vector2 v, Vector2 direction) {+ return Vector2(direction.x*v.x-direction.y*v.y, direction.y*v.x+direction.x*v.y);+}++static void addArcApproximate(Contour &contour, Point2 startPoint, Point2 endPoint, Vector2 radius, double rotation, bool largeArc, bool sweep) {+ if (endPoint == startPoint)+ return;+ if (radius.x == 0 || radius.y == 0)+ return contour.addEdge(EdgeHolder(startPoint, endPoint));++ radius.x = fabs(radius.x);+ radius.y = fabs(radius.y);+ Vector2 axis(cos(rotation), sin(rotation));++ Vector2 rm = rotateVector(.5*(startPoint-endPoint), Vector2(axis.x, -axis.y));+ Vector2 rm2 = rm*rm;+ Vector2 radius2 = radius*radius;+ double radiusGap = rm2.x/radius2.x+rm2.y/radius2.y;+ if (radiusGap > 1) {+ radius *= sqrt(radiusGap);+ radius2 = radius*radius;+ }+ double dq = (radius2.x*rm2.y+radius2.y*rm2.x);+ double pq = radius2.x*radius2.y/dq-1;+ double q = (largeArc == sweep ? -1 : +1)*sqrt(max(pq, 0.));+ Vector2 rc(q*radius.x*rm.y/radius.y, -q*radius.y*rm.x/radius.x);+ Point2 center = .5*(startPoint+endPoint)+rotateVector(rc, axis);++ double angleStart = arcAngle(Vector2(1, 0), (rm-rc)/radius);+ double angleExtent = arcAngle((rm-rc)/radius, (-rm-rc)/radius);+ if (!sweep && angleExtent > 0)+ angleExtent -= 2*M_PI;+ else if (sweep && angleExtent < 0)+ angleExtent += 2*M_PI;++ int segments = (int) ceil(ARC_SEGMENTS_PER_PI/M_PI*fabs(angleExtent));+ double angleIncrement = angleExtent/segments;+ double cl = 4/3.*sin(.5*angleIncrement)/(1+cos(.5*angleIncrement));++ Point2 prevNode = startPoint;+ double angle = angleStart;+ for (int i = 0; i < segments; ++i) {+ Point2 controlPoint[2];+ Vector2 d(cos(angle), sin(angle));+ controlPoint[0] = center+rotateVector(Vector2(d.x-cl*d.y, d.y+cl*d.x)*radius, axis);+ angle += angleIncrement;+ d.set(cos(angle), sin(angle));+ controlPoint[1] = center+rotateVector(Vector2(d.x+cl*d.y, d.y-cl*d.x)*radius, axis);+ Point2 node = i == segments-1 ? endPoint : center+rotateVector(d*radius, axis);+ contour.addEdge(EdgeHolder(prevNode, controlPoint[0], controlPoint[1], node));+ prevNode = node;+ }+}++bool buildShapeFromSvgPath(Shape &shape, const char *pathDef, double endpointSnapRange) {+ char nodeType = '\0';+ char prevNodeType = '\0';+ Point2 prevNode(0, 0);+ bool nodeTypePreread = false;+ while (nodeTypePreread || readNodeType(nodeType, pathDef)) {+ nodeTypePreread = false;+ Contour &contour = shape.addContour();+ bool contourStart = true;++ Point2 startPoint;+ Point2 controlPoint[2];+ Point2 node;++ while (*pathDef) {+ switch (nodeType) {+ case 'M': case 'm':+ if (!contourStart) {+ nodeTypePreread = true;+ goto NEXT_CONTOUR;+ }+ REQUIRE(readCoord(node, pathDef));+ if (nodeType == 'm')+ node += prevNode;+ startPoint = node;+ --nodeType; // to 'L' or 'l'+ break;+ case 'Z': case 'z':+ REQUIRE(!contourStart);+ goto NEXT_CONTOUR;+ case 'L': case 'l':+ REQUIRE(readCoord(node, pathDef));+ if (nodeType == 'l')+ node += prevNode;+ contour.addEdge(EdgeHolder(prevNode, node));+ break;+ case 'H': case 'h':+ REQUIRE(readDouble(node.x, pathDef));+ if (nodeType == 'h')+ node.x += prevNode.x;+ contour.addEdge(EdgeHolder(prevNode, node));+ break;+ case 'V': case 'v':+ REQUIRE(readDouble(node.y, pathDef));+ if (nodeType == 'v')+ node.y += prevNode.y;+ contour.addEdge(EdgeHolder(prevNode, node));+ break;+ case 'Q': case 'q':+ REQUIRE(readCoord(controlPoint[0], pathDef));+ REQUIRE(readCoord(node, pathDef));+ if (nodeType == 'q') {+ controlPoint[0] += prevNode;+ node += prevNode;+ }+ contour.addEdge(EdgeHolder(prevNode, controlPoint[0], node));+ break;+ case 'T': case 't':+ if (prevNodeType == 'Q' || prevNodeType == 'q' || prevNodeType == 'T' || prevNodeType == 't')+ controlPoint[0] = node+node-controlPoint[0];+ else+ controlPoint[0] = node;+ REQUIRE(readCoord(node, pathDef));+ if (nodeType == 't')+ node += prevNode;+ contour.addEdge(EdgeHolder(prevNode, controlPoint[0], node));+ break;+ case 'C': case 'c':+ REQUIRE(readCoord(controlPoint[0], pathDef));+ REQUIRE(readCoord(controlPoint[1], pathDef));+ REQUIRE(readCoord(node, pathDef));+ if (nodeType == 'c') {+ controlPoint[0] += prevNode;+ controlPoint[1] += prevNode;+ node += prevNode;+ }+ contour.addEdge(EdgeHolder(prevNode, controlPoint[0], controlPoint[1], node));+ break;+ case 'S': case 's':+ if (prevNodeType == 'C' || prevNodeType == 'c' || prevNodeType == 'S' || prevNodeType == 's')+ controlPoint[0] = node+node-controlPoint[1];+ else+ controlPoint[0] = node;+ REQUIRE(readCoord(controlPoint[1], pathDef));+ REQUIRE(readCoord(node, pathDef));+ if (nodeType == 's') {+ controlPoint[1] += prevNode;+ node += prevNode;+ }+ contour.addEdge(EdgeHolder(prevNode, controlPoint[0], controlPoint[1], node));+ break;+ case 'A': case 'a':+ {+ Vector2 radius;+ double angle;+ bool largeArg;+ bool sweep;+ REQUIRE(readCoord(radius, pathDef));+ REQUIRE(readDouble(angle, pathDef));+ REQUIRE(readBool(largeArg, pathDef));+ REQUIRE(readBool(sweep, pathDef));+ REQUIRE(readCoord(node, pathDef));+ if (nodeType == 'a')+ node += prevNode;+ angle *= M_PI/180.0;+ addArcApproximate(contour, prevNode, node, radius, angle, largeArg, sweep);+ }+ break;+ default:+ REQUIRE(!"Unknown node type");+ }+ contourStart &= nodeType == 'M' || nodeType == 'm';+ prevNode = node;+ prevNodeType = nodeType;+ readNodeType(nodeType, pathDef);+ }+ NEXT_CONTOUR:+ // Fix contour if it isn't properly closed+ if (!contour.edges.empty() && prevNode != startPoint) {+ if ((contour.edges.back()->point(1)-contour.edges[0]->point(0)).length() < endpointSnapRange)+ contour.edges.back()->moveEndPoint(contour.edges[0]->point(0));+ else+ contour.addEdge(EdgeHolder(prevNode, startPoint));+ }+ prevNode = startPoint;+ prevNodeType = '\0';+ }+ return true;+}++#ifdef MSDFGEN_USE_TINYXML2++static void findPathByForwardIndex(tinyxml2::XMLElement *&path, int &flags, int &skips, tinyxml2::XMLElement *parent, bool hasTransformation) {+ for (tinyxml2::XMLElement *cur = parent->FirstChildElement(); cur && !FLAGS_FINAL(flags); cur = cur->NextSiblingElement()) {+ if (!strcmp(cur->Name(), "path")) {+ if (!skips--) {+ path = cur;+ flags |= SVG_IMPORT_SUCCESS_FLAG;+ if (hasTransformation || cur->Attribute("transform"))+ flags |= SVG_IMPORT_TRANSFORMATION_IGNORED_FLAG;+ } else if (flags&SVG_IMPORT_SUCCESS_FLAG)+ flags |= SVG_IMPORT_INCOMPLETE_FLAG;+ } else if (!strcmp(cur->Name(), "g"))+ findPathByForwardIndex(path, flags, skips, cur, hasTransformation || cur->Attribute("transform"));+ else if (!strcmp(cur->Name(), "rect") || !strcmp(cur->Name(), "circle") || !strcmp(cur->Name(), "ellipse") || !strcmp(cur->Name(), "polygon"))+ flags |= SVG_IMPORT_INCOMPLETE_FLAG;+ else if (!strcmp(cur->Name(), "mask") || !strcmp(cur->Name(), "use"))+ flags |= SVG_IMPORT_UNSUPPORTED_FEATURE_FLAG;+ }+}++static void findPathByBackwardIndex(tinyxml2::XMLElement *&path, int &flags, int &skips, tinyxml2::XMLElement *parent, bool hasTransformation) {+ for (tinyxml2::XMLElement *cur = parent->LastChildElement(); cur && !FLAGS_FINAL(flags); cur = cur->PreviousSiblingElement()) {+ if (!strcmp(cur->Name(), "path")) {+ if (!skips--) {+ path = cur;+ flags |= SVG_IMPORT_SUCCESS_FLAG;+ if (hasTransformation || cur->Attribute("transform"))+ flags |= SVG_IMPORT_TRANSFORMATION_IGNORED_FLAG;+ } else if (flags&SVG_IMPORT_SUCCESS_FLAG)+ flags |= SVG_IMPORT_INCOMPLETE_FLAG;+ } else if (!strcmp(cur->Name(), "g"))+ findPathByBackwardIndex(path, flags, skips, cur, hasTransformation || cur->Attribute("transform"));+ else if (!strcmp(cur->Name(), "rect") || !strcmp(cur->Name(), "circle") || !strcmp(cur->Name(), "ellipse") || !strcmp(cur->Name(), "polygon"))+ flags |= SVG_IMPORT_INCOMPLETE_FLAG;+ else if (!strcmp(cur->Name(), "mask") || !strcmp(cur->Name(), "use"))+ flags |= SVG_IMPORT_UNSUPPORTED_FEATURE_FLAG;+ }+}++bool loadSvgShape(Shape &output, const char *filename, int pathIndex, Vector2 *dimensions) {+ tinyxml2::XMLDocument doc;+ if (doc.LoadFile(filename))+ return false;+ tinyxml2::XMLElement *root = doc.FirstChildElement("svg");+ if (!root)+ return false;++ tinyxml2::XMLElement *path = NULL;+ int flags = 0;+ int skippedPaths = abs(pathIndex)-(pathIndex != 0);+ if (pathIndex > 0)+ findPathByForwardIndex(path, flags, skippedPaths, root, false);+ else+ findPathByBackwardIndex(path, flags, skippedPaths, root, false);+ if (!path)+ return false;+ const char *pd = path->Attribute("d");+ if (!pd)+ return false;++ Vector2 dims(root->DoubleAttribute("width"), root->DoubleAttribute("height"));+ if (const char *viewBox = root->Attribute("viewBox")) {+ double left = 0, top = 0;+ readDouble(left, viewBox) && readDouble(top, viewBox) && readDouble(dims.x, viewBox) && readDouble(dims.y, viewBox);+ }+ if (dimensions)+ *dimensions = dims;+ output.contours.clear();+ output.setYAxisOrientation(Y_DOWNWARD);+ return buildShapeFromSvgPath(output, pd, ENDPOINT_SNAP_RANGE_PROPORTION*dims.length());+}++#endif++#ifdef MSDFGEN_USE_DROPXML++struct StrRange {+ const char *start, *end;+ inline StrRange() : start(), end() { }+ inline StrRange(const char *start, const char *end) : start(start), end(end) { }+ inline std::string str() const { return std::string(start, end); }+};++static bool matchName(const char *start, const char *end, const char *value) {+ for (const char *c = start; c < end; ++c, ++value) {+ if (*c != *value)+ return false;+ }+ return !*value;+}++static std::string xmlDecode(const char *start, const char *end) {+ if (!dropXML::decode(start, end, nullptr, nullptr)) {+ std::string buffer(end-start+1, '\0');+ if (!dropXML::decode(start, end, &buffer[0], &buffer[buffer.size()-1]))+ return std::string();+ if (start == buffer.data()) {+ buffer.resize(end-start, '\0');+ return (std::string &&) buffer;+ }+ }+ return std::string(start, end);+}++static double xmlGetDouble(const char *start, const char *end) {+ double x = 0;+ std::string decodedStr(xmlDecode(start, end));+ const char *strPtr = decodedStr.c_str();+ readDouble(x, strPtr);+ return x;+}++#define SVG_NAME_IS(x) matchName(nameStart, nameEnd, x)+#define SVG_DEC_VAL() xmlDecode(valueStart, valueEnd)+#define SVG_DOUBLEVAL() xmlGetDouble(valueStart, valueEnd)++static bool readFile(std::vector<char> &output, const char *filename) {+ if (FILE *f = fopen(filename, "rb")) {+ struct FileGuard {+ FILE *f;+ ~FileGuard() {+ fclose(f);+ }+ } fileGuard = { f };+ if (fseek(f, 0, SEEK_END))+ return false;+ long size = ftell(f);+ if (size < 0)+ return false;+ output.resize(size);+ if (!size)+ return true;+ if (fseek(f, 0, SEEK_SET))+ return false;+ return fread(&output[0], 1, size, f) == (size_t) size;+ }+ return false;+}++class BaseSvgConsumer {+public:+ inline bool processingInstruction(const char *, const char *) { return true; }+ inline bool doctype(const char *, const char *) { return true; }+ inline bool text(const char *, const char *) { return true; }+ inline bool cdata(const char *, const char *) { return true; }+};++class SvgPathAggregator : public BaseSvgConsumer {+ enum {+ IGNORED,+ SVG,+ G,+ PATH+ } curElement;+ int ignoredDepth;++public:+ int flags;+ Vector2 dimensions;+ StrRange viewBox;+ std::vector<StrRange> pathDefs;++ inline SvgPathAggregator() : curElement(IGNORED), ignoredDepth(0), flags(0) { }++ inline bool enterElement(const char *nameStart, const char *nameEnd) {+ curElement = IGNORED;+ if (ignoredDepth)+ ++ignoredDepth;+ else if (SVG_NAME_IS("svg"))+ curElement = SVG;+ else if (SVG_NAME_IS("g"))+ curElement = G;+ else if (SVG_NAME_IS("path"))+ curElement = PATH;+ else {+ if (SVG_NAME_IS("rect") || SVG_NAME_IS("circle") || SVG_NAME_IS("ellipse") || SVG_NAME_IS("polygon"))+ flags |= SVG_IMPORT_INCOMPLETE_FLAG;+ else if (SVG_NAME_IS("mask") || SVG_NAME_IS("use"))+ flags |= SVG_IMPORT_UNSUPPORTED_FEATURE_FLAG;+ ++ignoredDepth;+ }+ return true;+ }++ inline bool leaveElement(const char *, const char *) {+ if (ignoredDepth)+ --ignoredDepth;+ return true;+ }++ inline bool elementAttribute(const char *nameStart, const char *nameEnd, const char *valueStart, const char *valueEnd) {+ switch (curElement) {+ case IGNORED:+ break;+ case SVG:+ if (SVG_NAME_IS("width"))+ dimensions.x = xmlGetDouble(valueStart, valueEnd);+ else if (SVG_NAME_IS("height"))+ dimensions.y = xmlGetDouble(valueStart, valueEnd);+ else if (SVG_NAME_IS("viewBox"))+ viewBox = StrRange(valueStart, valueEnd);+ break;+ case PATH:+ if (SVG_NAME_IS("d"))+ pathDefs.push_back(StrRange(valueStart, valueEnd));+ // fallthrough+ case G:+ if (SVG_NAME_IS("transform"))+ flags |= SVG_IMPORT_TRANSFORMATION_IGNORED_FLAG;+ break;+ }+ return true;+ }++ inline bool finishAttributes() { return true; }+ inline bool finish() { return !ignoredDepth; }++};++bool loadSvgShape(Shape &output, const char *filename, int pathIndex, Vector2 *dimensions) {+ std::vector<char> svgData;+ if (!(readFile(svgData, filename) && !svgData.empty()))+ return false;++ SvgPathAggregator pathAggregator;+ if (!dropXML::parse(pathAggregator, &svgData[0], &svgData[0]+svgData.size()))+ return false;++ if (pathIndex <= 0) {+ if (pathIndex == 0)+ pathIndex = -1;+ pathIndex = pathAggregator.pathDefs.size()+pathIndex;+ } else+ --pathIndex;+ if (!(pathIndex > 0 && pathIndex < (int) pathAggregator.pathDefs.size()))+ return false;++ Vector2 dims(pathAggregator.dimensions);+ if (pathAggregator.viewBox.start < pathAggregator.viewBox.end) {+ std::string viewBoxStr = xmlDecode(pathAggregator.viewBox.start, pathAggregator.viewBox.end);+ const char *viewBoxPtr = viewBoxStr.c_str();+ double left = 0, top = 0;+ readDouble(left, viewBoxPtr) && readDouble(top, viewBoxPtr) && readDouble(dims.x, viewBoxPtr) && readDouble(dims.y, viewBoxPtr);+ }+ if (dimensions)+ *dimensions = dims;+ output.contours.clear();+ output.setYAxisOrientation(Y_DOWNWARD);+ return buildShapeFromSvgPath(output, xmlDecode(pathAggregator.pathDefs[pathIndex].start, pathAggregator.pathDefs[pathIndex].end).c_str(), ENDPOINT_SNAP_RANGE_PROPORTION*dims.length());+}++#endif++#ifndef MSDFGEN_USE_SKIA++#ifdef MSDFGEN_USE_TINYXML2+int loadSvgShape(Shape &output, Shape::Bounds &viewBox, const char *filename) {+ tinyxml2::XMLDocument doc;+ if (doc.LoadFile(filename))+ return SVG_IMPORT_FAILURE;+ tinyxml2::XMLElement *root = doc.FirstChildElement("svg");+ if (!root)+ return SVG_IMPORT_FAILURE;++ tinyxml2::XMLElement *path = NULL;+ int flags = 0;+ int skippedPaths = 0;+ findPathByBackwardIndex(path, flags, skippedPaths, root, false);+ if (!(path && (flags&SVG_IMPORT_SUCCESS_FLAG)))+ return SVG_IMPORT_FAILURE;+ const char *pd = path->Attribute("d");+ if (!pd)+ return SVG_IMPORT_FAILURE;++ viewBox.l = 0, viewBox.b = 0;+ Vector2 dims(root->DoubleAttribute("width"), root->DoubleAttribute("height"));+ if (const char *viewBoxStr = root->Attribute("viewBox"))+ readDouble(viewBox.l, viewBoxStr) && readDouble(viewBox.b, viewBoxStr) && readDouble(dims.x, viewBoxStr) && readDouble(dims.y, viewBoxStr);+ viewBox.r = viewBox.l+dims.x;+ viewBox.t = viewBox.b+dims.y;+ output.contours.clear();+ output.setYAxisOrientation(Y_DOWNWARD);+ if (!buildShapeFromSvgPath(output, pd, ENDPOINT_SNAP_RANGE_PROPORTION*dims.length()))+ return SVG_IMPORT_FAILURE;+ return flags;+}+#endif++#ifdef MSDFGEN_USE_DROPXML+int loadSvgShape(Shape &output, Shape::Bounds &viewBox, const char *filename) {+ std::vector<char> svgData;+ if (!(readFile(svgData, filename) && !svgData.empty()))+ return SVG_IMPORT_FAILURE;++ SvgPathAggregator pathAggregator;+ if (!dropXML::parse(pathAggregator, &svgData[0], &svgData[0]+svgData.size()) || pathAggregator.pathDefs.empty())+ return SVG_IMPORT_FAILURE;++ viewBox.l = 0, viewBox.b = 0;+ Vector2 dims(pathAggregator.dimensions);+ if (pathAggregator.viewBox.start < pathAggregator.viewBox.end) {+ std::string viewBoxStr = xmlDecode(pathAggregator.viewBox.start, pathAggregator.viewBox.end);+ const char *viewBoxPtr = viewBoxStr.c_str();+ readDouble(viewBox.l, viewBoxPtr) && readDouble(viewBox.b, viewBoxPtr) && readDouble(dims.x, viewBoxPtr) && readDouble(dims.y, viewBoxPtr);+ }+ viewBox.r = viewBox.l+dims.x;+ viewBox.t = viewBox.b+dims.y;+ output.contours.clear();+ output.setYAxisOrientation(Y_DOWNWARD);+ if (!buildShapeFromSvgPath(output, xmlDecode(pathAggregator.pathDefs.back().start, pathAggregator.pathDefs.back().end).c_str(), ENDPOINT_SNAP_RANGE_PROPORTION*dims.length()))+ return SVG_IMPORT_FAILURE;+ return SVG_IMPORT_SUCCESS_FLAG|pathAggregator.flags;+}+#endif++#else++void shapeFromSkiaPath(Shape &shape, const SkPath &skPath); // defined in resolve-shape-geometry.cpp++static bool readTransformationOp(SkScalar dst[6], int &count, const char *&str, const char *name) {+ int nameLen = int(strlen(name));+ if (!memcmp(str, name, nameLen)) {+ const char *curStr = str+nameLen;+ skipExtraChars(curStr);+ if (*curStr == '(') {+ skipExtraChars(++curStr);+ count = 0;+ while (*curStr && *curStr != ')') {+ double x;+ if (!(count < 6 && readDouble(x, curStr)))+ return false;+ dst[count++] = SkScalar(x);+ skipExtraChars(curStr);+ }+ if (*curStr == ')') {+ str = curStr+1;+ return true;+ }+ }+ }+ return false;+}++static SkMatrix parseTransformation(int &flags, const char *str) {+ SkMatrix transformation;+ skipExtraChars(str);+ while (*str) {+ SkScalar values[6];+ int count;+ SkMatrix partial;+ if (readTransformationOp(values, count, str, "matrix") && count == 6) {+ partial.setAll(values[0], values[2], values[4], values[1], values[3], values[5], SkScalar(0), SkScalar(0), SkScalar(1));+ } else if (readTransformationOp(values, count, str, "translate") && (count == 1 || count == 2)) {+ if (count == 1)+ values[1] = SkScalar(0);+ partial.setTranslate(values[0], values[1]);+ } else if (readTransformationOp(values, count, str, "scale") && (count == 1 || count == 2)) {+ if (count == 1)+ values[1] = values[0];+ partial.setScale(values[0], values[1]);+ } else if (readTransformationOp(values, count, str, "rotate") && (count == 1 || count == 3)) {+ if (count == 3)+ partial.setRotate(values[0], values[1], values[2]);+ else+ partial.setRotate(values[0]);+ } else if (readTransformationOp(values, count, str, "skewX") && count == 1) {+ partial.setSkewX(SkScalar(tan(M_PI/180*values[0])));+ } else if (readTransformationOp(values, count, str, "skewY") && count == 1) {+ partial.setSkewY(SkScalar(tan(M_PI/180*values[0])));+ } else {+ flags |= SVG_IMPORT_PARTIAL_FAILURE_FLAG;+ break;+ }+ transformation = transformation*partial;+ skipExtraChars(str);+ }+ return transformation;+}++static SkMatrix combineTransformation(int &flags, const SkMatrix &parentTransformation, const char *transformationString, const char *transformationOriginString) {+ if (transformationString && *transformationString) {+ SkMatrix transformation = parseTransformation(flags, transformationString);+ if (transformationOriginString && *transformationOriginString) {+ Point2 origin;+ if (readCoord(origin, transformationOriginString))+ transformation = SkMatrix::Translate(SkScalar(origin.x), SkScalar(origin.y))*transformation*SkMatrix::Translate(SkScalar(-origin.x), SkScalar(-origin.y));+ else+ flags |= SVG_IMPORT_PARTIAL_FAILURE_FLAG;+ }+ return parentTransformation*transformation;+ }+ return parentTransformation;+}++#ifdef MSDFGEN_USE_TINYXML2++static void gatherPaths(SkPath &fullPath, int &flags, tinyxml2::XMLElement *parent, const SkMatrix &transformation) {+ for (tinyxml2::XMLElement *cur = parent->FirstChildElement(); cur && !FLAGS_FINAL(flags); cur = cur->NextSiblingElement()) {+ if (!strcmp(cur->Name(), "g"))+ gatherPaths(fullPath, flags, cur, combineTransformation(flags, transformation, cur->Attribute("transform"), cur->Attribute("transform-origin")));+ else if (!strcmp(cur->Name(), "mask") || !strcmp(cur->Name(), "use"))+ flags |= SVG_IMPORT_UNSUPPORTED_FEATURE_FLAG;+ else {+ SkPath curPath;+ if (!strcmp(cur->Name(), "path")) {+ const char *pd = cur->Attribute("d");+ if (!(pd && SkParsePath::FromSVGString(pd, &curPath))) {+ flags |= SVG_IMPORT_PARTIAL_FAILURE_FLAG;+ continue;+ }+ } else if (!strcmp(cur->Name(), "rect")) {+ SkScalar x = SkScalar(cur->DoubleAttribute("x")), y = SkScalar(cur->DoubleAttribute("y"));+ SkScalar width = SkScalar(cur->DoubleAttribute("width")), height = SkScalar(cur->DoubleAttribute("height"));+ SkScalar rx = SkScalar(cur->DoubleAttribute("rx")), ry = SkScalar(cur->DoubleAttribute("ry"));+ if (!(width && height))+ continue;+ SkRect rect = SkRect::MakeLTRB(x, y, x+width, y+height);+ if (rx || ry) {+ SkScalar radii[] = { rx, ry, rx, ry, rx, ry, rx, ry };+ curPath.addRoundRect(rect, radii);+ } else+ curPath.addRect(rect);+ } else if (!strcmp(cur->Name(), "circle")) {+ SkScalar cx = SkScalar(cur->DoubleAttribute("cx")), cy = SkScalar(cur->DoubleAttribute("cy"));+ SkScalar r = SkScalar(cur->DoubleAttribute("r"));+ if (!r)+ continue;+ curPath.addCircle(cx, cy, r);+ } else if (!strcmp(cur->Name(), "ellipse")) {+ SkScalar cx = SkScalar(cur->DoubleAttribute("cx")), cy = SkScalar(cur->DoubleAttribute("cy"));+ SkScalar rx = SkScalar(cur->DoubleAttribute("rx")), ry = SkScalar(cur->DoubleAttribute("ry"));+ if (!(rx && ry))+ continue;+ curPath.addOval(SkRect::MakeLTRB(cx-rx, cy-ry, cx+rx, cy+ry));+ } else if (!strcmp(cur->Name(), "polygon")) {+ const char *pd = cur->Attribute("points");+ if (!pd) {+ flags |= SVG_IMPORT_PARTIAL_FAILURE_FLAG;+ continue;+ }+ Point2 point;+ if (!readCoord(point, pd))+ continue;+ curPath.moveTo(SkScalar(point.x), SkScalar(point.y));+ if (!readCoord(point, pd))+ continue;+ do {+ curPath.lineTo(SkScalar(point.x), SkScalar(point.y));+ } while (readCoord(point, pd));+ curPath.close();+ } else+ continue;+ const char *fillRule = cur->Attribute("fill-rule");+ if (fillRule && !strcmp(fillRule, "evenodd"))+ curPath.setFillType(SkPathFillType::kEvenOdd);+ curPath.transform(combineTransformation(flags, transformation, cur->Attribute("transform"), cur->Attribute("transform-origin")));+ if (Op(fullPath, curPath, kUnion_SkPathOp, &fullPath))+ flags |= SVG_IMPORT_SUCCESS_FLAG;+ else+ flags |= SVG_IMPORT_PARTIAL_FAILURE_FLAG;+ }+ }+}++int loadSvgShape(Shape &output, Shape::Bounds &viewBox, const char *filename) {+ tinyxml2::XMLDocument doc;+ if (doc.LoadFile(filename))+ return SVG_IMPORT_FAILURE;+ tinyxml2::XMLElement *root = doc.FirstChildElement("svg");+ if (!root)+ return SVG_IMPORT_FAILURE;++ SkPath fullPath;+ int flags = 0;+ gatherPaths(fullPath, flags, root, SkMatrix());+ if (!((flags&SVG_IMPORT_SUCCESS_FLAG) && Simplify(fullPath, &fullPath)))+ return SVG_IMPORT_FAILURE;+ shapeFromSkiaPath(output, fullPath);+ output.setYAxisOrientation(Y_DOWNWARD);+ output.orientContours();++ viewBox.l = 0, viewBox.b = 0;+ Vector2 dims(root->DoubleAttribute("width"), root->DoubleAttribute("height"));+ if (const char *viewBoxStr = root->Attribute("viewBox"))+ readDouble(viewBox.l, viewBoxStr) && readDouble(viewBox.b, viewBoxStr) && readDouble(dims.x, viewBoxStr) && readDouble(dims.y, viewBoxStr);+ viewBox.r = viewBox.l+dims.x;+ viewBox.t = viewBox.b+dims.y;+ return flags;+}++#endif++#ifdef MSDFGEN_USE_DROPXML++int parseSvgShape(Shape &output, Shape::Bounds &viewBox, const char *svgData, size_t svgLength) {++ class SvgConsumer : public BaseSvgConsumer {+ enum Element {+ BEGINNING,+ IGNORED,+ SVG,+ G,+ PATH,+ RECT,+ CIRCLE,+ ELLIPSE,+ POLYGON+ } curElement;++ // Current element attributes+ struct ElementData {+ StrRange transform, transformOrigin;+ Vector2 pos, dims, radius;+ StrRange pathDef;+ bool fillRuleEvenOdd;+ ElementData() : fillRuleEvenOdd(false) { }+ } elem;++ int ignoredDepth;+ SkMatrix transformation;+ std::stack<SkMatrix> transformationStack;++ public:+ int flags;+ Vector2 dimensions;+ Shape::Bounds viewBox;+ SkPath fullPath;++ SvgConsumer() : curElement(BEGINNING), ignoredDepth(0), flags(0), viewBox() { }++ bool enterElement(const char *nameStart, const char *nameEnd) {+ if (ignoredDepth) {+ ++ignoredDepth;+ return true;+ }+ if (curElement == BEGINNING && SVG_NAME_IS("svg"))+ curElement = SVG;+ else if (SVG_NAME_IS("g"))+ curElement = G;+ else if (SVG_NAME_IS("path"))+ curElement = PATH;+ else if (SVG_NAME_IS("rect"))+ curElement = RECT;+ else if (SVG_NAME_IS("circle"))+ curElement = CIRCLE;+ else if (SVG_NAME_IS("ellipse"))+ curElement = ELLIPSE;+ else if (SVG_NAME_IS("polygon"))+ curElement = POLYGON;+ else {+ curElement = IGNORED;+ ++ignoredDepth;+ if (SVG_NAME_IS("mask") || SVG_NAME_IS("use"))+ flags |= SVG_IMPORT_UNSUPPORTED_FEATURE_FLAG;+ }+ if (curElement != IGNORED)+ elem = ElementData();+ return true;+ }++ bool leaveElement(const char *nameStart, const char *nameEnd) {+ if (ignoredDepth) {+ --ignoredDepth;+ return true;+ }+ if (SVG_NAME_IS("g")) {+ if (transformationStack.empty())+ return false;+ transformation = transformationStack.top();+ transformationStack.pop();+ }+ return true;+ }++ bool elementAttribute(const char *nameStart, const char *nameEnd, const char *valueStart, const char *valueEnd) {+ switch (curElement) {+ case BEGINNING:+ case IGNORED:+ break;+ case SVG:+ if (SVG_NAME_IS("width"))+ dimensions.x = SVG_DOUBLEVAL();+ else if (SVG_NAME_IS("height"))+ dimensions.y = SVG_DOUBLEVAL();+ else if (SVG_NAME_IS("viewBox")) {+ std::string viewBoxStr(SVG_DEC_VAL());+ const char *strPtr = viewBoxStr.c_str();+ double w = 0, h = 0;+ readDouble(viewBox.l, strPtr) && readDouble(viewBox.b, strPtr) && readDouble(w, strPtr) && readDouble(h, strPtr);+ viewBox.r = viewBox.l+w;+ viewBox.t = viewBox.b+h;+ }+ break;+ case G:+ break;+ case PATH:+ if (SVG_NAME_IS("d"))+ elem.pathDef = StrRange(valueStart, valueEnd);+ break;+ case RECT:+ if (SVG_NAME_IS("x"))+ elem.pos.x = SVG_DOUBLEVAL();+ else if (SVG_NAME_IS("y"))+ elem.pos.y = SVG_DOUBLEVAL();+ else if (SVG_NAME_IS("width"))+ elem.dims.x = SVG_DOUBLEVAL();+ else if (SVG_NAME_IS("height"))+ elem.dims.y = SVG_DOUBLEVAL();+ else if (SVG_NAME_IS("rx"))+ elem.radius.x = SVG_DOUBLEVAL();+ else if (SVG_NAME_IS("ry"))+ elem.radius.y = SVG_DOUBLEVAL();+ break;+ case CIRCLE:+ if (SVG_NAME_IS("cx"))+ elem.pos.x = SVG_DOUBLEVAL();+ else if (SVG_NAME_IS("cy"))+ elem.pos.y = SVG_DOUBLEVAL();+ else if (SVG_NAME_IS("r"))+ elem.radius.x = SVG_DOUBLEVAL();+ break;+ case ELLIPSE:+ if (SVG_NAME_IS("cx"))+ elem.pos.x = SVG_DOUBLEVAL();+ else if (SVG_NAME_IS("cy"))+ elem.pos.y = SVG_DOUBLEVAL();+ else if (SVG_NAME_IS("rx"))+ elem.radius.x = SVG_DOUBLEVAL();+ else if (SVG_NAME_IS("ry"))+ elem.radius.y = SVG_DOUBLEVAL();+ break;+ case POLYGON:+ if (SVG_NAME_IS("points"))+ elem.pathDef = StrRange(valueStart, valueEnd);+ break;+ }+ switch (curElement) {+ case PATH:+ case RECT:+ case CIRCLE:+ case ELLIPSE:+ case POLYGON:+ if (SVG_NAME_IS("fill-rule"))+ elem.fillRuleEvenOdd = SVG_DEC_VAL() == "evenodd";+ // fallthrough+ case G:+ if (SVG_NAME_IS("transform"))+ elem.transform = StrRange(valueStart, valueEnd);+ else if (SVG_NAME_IS("transform-origin"))+ elem.transformOrigin = StrRange(valueStart, valueEnd);+ break;+ default:;+ }+ return true;+ }++ bool finishAttributes() {+ switch (curElement) {+ case BEGINNING:+ case IGNORED:+ case SVG:+ break;+ case G:+ transformationStack.push(transformation);+ transformation = combineTransformation(flags, transformation, elem.transform.str().c_str(), elem.transformOrigin.str().c_str());+ break;+ case PATH:+ case RECT:+ case CIRCLE:+ case ELLIPSE:+ case POLYGON:+ {+ SkPath curPath;+ switch (curElement) {+ case PATH:+ if (!SkParsePath::FromSVGString(elem.pathDef.str().c_str(), &curPath)) {+ flags |= SVG_IMPORT_PARTIAL_FAILURE_FLAG;+ return true;+ }+ break;+ case RECT:+ {+ if (!(elem.dims.x && elem.dims.y))+ return true;+ SkRect rect = SkRect::MakeLTRB(elem.pos.x, elem.pos.y, elem.pos.x+elem.dims.x, elem.pos.y+elem.dims.y);+ if (elem.radius.x || elem.radius.y) {+ SkScalar rx = SkScalar(elem.radius.x), ry = SkScalar(elem.radius.y);+ SkScalar radii[] = { rx, ry, rx, ry, rx, ry, rx, ry };+ curPath.addRoundRect(rect, radii);+ } else+ curPath.addRect(rect);+ }+ break;+ case CIRCLE:+ if (!elem.radius.x)+ return true;+ curPath.addCircle(elem.pos.x, elem.pos.y, elem.radius.x);+ break;+ case ELLIPSE:+ if (!(elem.radius.x && elem.radius.y))+ return true;+ curPath.addOval(SkRect::MakeLTRB(elem.pos.x-elem.radius.x, elem.pos.y-elem.radius.y, elem.pos.x+elem.radius.x, elem.pos.y+elem.radius.y));+ break;+ case POLYGON:+ {+ if (elem.pathDef.start == elem.pathDef.end) {+ flags |= SVG_IMPORT_PARTIAL_FAILURE_FLAG;+ return true;+ }+ std::string pdStr = elem.pathDef.str();+ const char *pd = pdStr.c_str();+ Point2 point;+ if (!readCoord(point, pd))+ return true;+ curPath.moveTo(SkScalar(point.x), SkScalar(point.y));+ if (!readCoord(point, pd))+ return true;+ do {+ curPath.lineTo(SkScalar(point.x), SkScalar(point.y));+ } while (readCoord(point, pd));+ curPath.close();+ }+ break;+ default:+ return true;+ }+ if (elem.fillRuleEvenOdd)+ curPath.setFillType(SkPathFillType::kEvenOdd);+ curPath.transform(combineTransformation(flags, transformation, elem.transform.str().c_str(), elem.transformOrigin.str().c_str()));+ if (Op(fullPath, curPath, kUnion_SkPathOp, &fullPath))+ flags |= SVG_IMPORT_SUCCESS_FLAG;+ else+ flags |= SVG_IMPORT_PARTIAL_FAILURE_FLAG;+ }+ break;+ }+ return true;+ }++ bool finish() {+ return !ignoredDepth && transformationStack.empty();+ }++ };++ SvgConsumer svg;+ if (!(+ dropXML::parse(svg, svgData, svgData+svgLength) &&+ (svg.flags&SVG_IMPORT_SUCCESS_FLAG) &&+ Simplify(svg.fullPath, &svg.fullPath)+ ))+ return SVG_IMPORT_FAILURE;++ shapeFromSkiaPath(output, svg.fullPath);+ output.setYAxisOrientation(Y_DOWNWARD);+ output.orientContours();++ viewBox = svg.viewBox;+ if (svg.dimensions.x > 0 && viewBox.r == viewBox.l)+ viewBox.r += svg.dimensions.x;+ if (svg.dimensions.y > 0 && viewBox.t == viewBox.b)+ viewBox.t += svg.dimensions.y;+ return svg.flags;+}++int loadSvgShape(Shape &output, Shape::Bounds &viewBox, const char *filename) {+ std::vector<char> svgData;+ if (!readFile(svgData, filename))+ return SVG_IMPORT_FAILURE;+ return parseSvgShape(output, viewBox, svgData.empty() ? NULL : &svgData[0], svgData.size());+}++#endif++#endif++}++#endifdiff --git a/third_party/msdfgen/ext/import-svg.h b/third_party/msdfgen/ext/import-svg.hnew file mode 100644index 000000000..ec409a9e8--- /dev/null+++ b/third_party/msdfgen/ext/import-svg.h@@ -0,0 +1,32 @@++#pragma once++#include "../core/Shape.h"++#ifndef MSDFGEN_DISABLE_SVG++#ifndef MSDFGEN_EXT_PUBLIC+#define MSDFGEN_EXT_PUBLIC // for DLL import/export+#endif++namespace msdfgen {++extern MSDFGEN_EXT_PUBLIC const int SVG_IMPORT_FAILURE;+extern MSDFGEN_EXT_PUBLIC const int SVG_IMPORT_SUCCESS_FLAG;+extern MSDFGEN_EXT_PUBLIC const int SVG_IMPORT_PARTIAL_FAILURE_FLAG;+extern MSDFGEN_EXT_PUBLIC const int SVG_IMPORT_INCOMPLETE_FLAG;+extern MSDFGEN_EXT_PUBLIC const int SVG_IMPORT_UNSUPPORTED_FEATURE_FLAG;+extern MSDFGEN_EXT_PUBLIC const int SVG_IMPORT_TRANSFORMATION_IGNORED_FLAG;++/// Builds a shape from an SVG path string+bool buildShapeFromSvgPath(Shape &shape, const char *pathDef, double endpointSnapRange = 0);++/// Reads a single <path> element found in the specified SVG file and converts it to output Shape+bool loadSvgShape(Shape &output, const char *filename, int pathIndex = 0, Vector2 *dimensions = NULL);++/// New version - if Skia is available, reads the entire geometry of the SVG file into the output Shape, otherwise may only read one path, returns SVG import flags+int loadSvgShape(Shape &output, Shape::Bounds &viewBox, const char *filename);++}++#endifdiff --git a/third_party/msdfgen/ext/resolve-shape-geometry.cpp b/third_party/msdfgen/ext/resolve-shape-geometry.cppnew file mode 100644index 000000000..a24dbeb67--- /dev/null+++ b/third_party/msdfgen/ext/resolve-shape-geometry.cpp@@ -0,0 +1,130 @@++#include "resolve-shape-geometry.h"++#ifdef MSDFGEN_USE_SKIA++#include <skia/core/SkPath.h>+#include <skia/pathops/SkPathOps.h>+#include "../core/arithmetics.hpp"+#include "../core/Vector2.hpp"+#include "../core/edge-segments.h"+#include "../core/Contour.h"++namespace msdfgen {++SkPoint pointToSkiaPoint(Point2 p) {+ return SkPoint::Make((SkScalar) p.x, (SkScalar) p.y);+}++Point2 pointFromSkiaPoint(const SkPoint p) {+ return Point2((double) p.x(), (double) p.y());+}++void shapeToSkiaPath(SkPath &skPath, const Shape &shape) {+ for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour) {+ if (!contour->edges.empty()) {+ const EdgeSegment *edge = contour->edges.back();+ skPath.moveTo(pointToSkiaPoint(*edge->controlPoints()));+ for (std::vector<EdgeHolder>::const_iterator nextEdge = contour->edges.begin(); nextEdge != contour->edges.end(); edge = *nextEdge++) {+ const Point2 *p = edge->controlPoints();+ switch (edge->type()) {+ case (int) LinearSegment::EDGE_TYPE:+ skPath.lineTo(pointToSkiaPoint(p[1]));+ break;+ case (int) QuadraticSegment::EDGE_TYPE:+ skPath.quadTo(pointToSkiaPoint(p[1]), pointToSkiaPoint(p[2]));+ break;+ case (int) CubicSegment::EDGE_TYPE:+ skPath.cubicTo(pointToSkiaPoint(p[1]), pointToSkiaPoint(p[2]), pointToSkiaPoint(p[3]));+ break;+ }+ }+ }+ }+}++void shapeFromSkiaPath(Shape &shape, const SkPath &skPath) {+ shape.contours.clear();+ Contour *contour = &shape.addContour();+ SkPath::Iter pathIterator(skPath, true);+ SkPoint edgePoints[4];+ for (SkPath::Verb op; (op = pathIterator.next(edgePoints)) != SkPath::kDone_Verb;) {+ switch (op) {+ case SkPath::kMove_Verb:+ if (!contour->edges.empty())+ contour = &shape.addContour();+ break;+ case SkPath::kLine_Verb:+ contour->addEdge(EdgeHolder(pointFromSkiaPoint(edgePoints[0]), pointFromSkiaPoint(edgePoints[1])));+ break;+ case SkPath::kQuad_Verb:+ contour->addEdge(EdgeHolder(pointFromSkiaPoint(edgePoints[0]), pointFromSkiaPoint(edgePoints[1]), pointFromSkiaPoint(edgePoints[2])));+ break;+ case SkPath::kCubic_Verb:+ contour->addEdge(EdgeHolder(pointFromSkiaPoint(edgePoints[0]), pointFromSkiaPoint(edgePoints[1]), pointFromSkiaPoint(edgePoints[2]), pointFromSkiaPoint(edgePoints[3])));+ break;+ case SkPath::kConic_Verb:+ {+ SkPoint quadPoints[5];+ SkPath::ConvertConicToQuads(edgePoints[0], edgePoints[1], edgePoints[2], pathIterator.conicWeight(), quadPoints, 1);+ contour->addEdge(EdgeHolder(pointFromSkiaPoint(quadPoints[0]), pointFromSkiaPoint(quadPoints[1]), pointFromSkiaPoint(quadPoints[2])));+ contour->addEdge(EdgeHolder(pointFromSkiaPoint(quadPoints[2]), pointFromSkiaPoint(quadPoints[3]), pointFromSkiaPoint(quadPoints[4])));+ }+ break;+ case SkPath::kClose_Verb:+ case SkPath::kDone_Verb:+ break;+ }+ }+ if (contour->edges.empty())+ shape.contours.pop_back();+}++static void pruneCrossedQuadrilaterals(Shape &shape) {+ int n = 0;+ for (int i = 0; i < (int) shape.contours.size(); ++i) {+ Contour &contour = shape.contours[i];+ if (+ contour.edges.size() == 4 &&+ contour.edges[0]->type() == (int) LinearSegment::EDGE_TYPE &&+ contour.edges[1]->type() == (int) LinearSegment::EDGE_TYPE &&+ contour.edges[2]->type() == (int) LinearSegment::EDGE_TYPE &&+ contour.edges[3]->type() == (int) LinearSegment::EDGE_TYPE && (+ sign(crossProduct(contour.edges[0]->direction(1), contour.edges[1]->direction(0)))++ sign(crossProduct(contour.edges[1]->direction(1), contour.edges[2]->direction(0)))++ sign(crossProduct(contour.edges[2]->direction(1), contour.edges[3]->direction(0)))++ sign(crossProduct(contour.edges[3]->direction(1), contour.edges[0]->direction(0)))+ ) == 0+ ) {+ contour.edges.clear();+ } else {+ if (i != n) {+ #ifdef MSDFGEN_USE_CPP11+ shape.contours[n] = (Contour &&) contour;+ #else+ shape.contours[n] = contour;+ #endif+ }+ ++n;+ }+ }+ shape.contours.resize(n);+}++bool resolveShapeGeometry(Shape &shape) {+ SkPath skPath;+ shape.normalize();+ shapeToSkiaPath(skPath, shape);+ if (!Simplify(skPath, &skPath))+ return false;+ // Skia's AsWinding doesn't seem to work for unknown reasons+ shapeFromSkiaPath(shape, skPath);+ // In some rare cases, Skia produces tiny residual crossed quadrilateral contours, which are not valid geometry, so they must be removed.+ pruneCrossedQuadrilaterals(shape);+ shape.orientContours();+ return true;+}++}++#endifdiff --git a/third_party/msdfgen/ext/resolve-shape-geometry.h b/third_party/msdfgen/ext/resolve-shape-geometry.hnew file mode 100644index 000000000..1ab0a633f--- /dev/null+++ b/third_party/msdfgen/ext/resolve-shape-geometry.h@@ -0,0 +1,15 @@++#pragma once++#include "../core/Shape.h"++#ifdef MSDFGEN_USE_SKIA++namespace msdfgen {++/// Resolves any intersections within the shape by subdividing its contours using the Skia library and makes sure its contours have a consistent winding.+bool resolveShapeGeometry(Shape &shape);++}++#endifdiff --git a/third_party/msdfgen/ext/save-png.cpp b/third_party/msdfgen/ext/save-png.cppnew file mode 100644index 000000000..75b186352--- /dev/null+++ b/third_party/msdfgen/ext/save-png.cpp@@ -0,0 +1,195 @@++#ifndef _CRT_SECURE_NO_WARNINGS+#define _CRT_SECURE_NO_WARNINGS+#endif++#include "save-png.h"++#include <cstdio>+#include <cstring>+#include <vector>+#include "../core/pixel-conversion.hpp"++#ifdef MSDFGEN_USE_LIBPNG++#include <png.h>++namespace msdfgen {++class PngGuard {+ png_structp png;+ png_infop info;+ FILE *file;++public:+ inline PngGuard(png_structp png, png_infop info) : png(png), info(info), file(NULL) { }+ inline ~PngGuard() {+ png_destroy_write_struct(&png, &info);+ if (file)+ fclose(file);+ }+ inline void setFile(FILE *file) {+ this->file = file;+ }++};++static void pngIgnoreError(png_structp, png_const_charp) { }++static void pngWrite(png_structp png, png_bytep data, png_size_t length) {+ if (fwrite(data, 1, length, reinterpret_cast<FILE *>(png_get_io_ptr(png))) != length)+ png_error(png, "File write error");+}++static void pngFlush(png_structp png) {+ fflush(reinterpret_cast<FILE *>(png_get_io_ptr(png)));+}++static bool pngSave(const byte *pixels, int width, int height, int rowStride, int colorType, const char *filename) {+ if (!(pixels && width && height))+ return false;+ png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, &pngIgnoreError, &pngIgnoreError);+ if (!png)+ return false;+ png_infop info = png_create_info_struct(png);+ PngGuard guard(png, info);+ if (!info)+ return false;+ FILE *file = fopen(filename, "wb");+ if (!file)+ return false;+ guard.setFile(file);+ std::vector<const byte *> rows(height);+ for (int y = 0; y < height; ++y)+ rows[y] = pixels+rowStride*y;+ if (setjmp(png_jmpbuf(png)))+ return false;+ png_set_write_fn(png, file, &pngWrite, &pngFlush);+ png_set_IHDR(png, info, width, height, 8, colorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);+ png_set_compression_level(png, 9);+ png_set_rows(png, info, const_cast<png_bytepp>(&rows[0]));+ png_write_png(png, info, PNG_TRANSFORM_IDENTITY, NULL);+ return true;+}++static bool pngSave(const float *pixels, int width, int height, int rowStride, int channels, int colorType, const char *filename) {+ if (!(pixels && width && height))+ return false;+ std::vector<byte> bytePixels(channels*width*height);+ byte *dst = &bytePixels[0];+ const float *rowStart = pixels;+ for (int y = 0; y < height; ++y) {+ for (const float *src = rowStart, *end = rowStart+channels*width; src < end; ++src)+ *dst++ = pixelFloatToByte(*src);+ rowStart += rowStride;+ }+ return pngSave(&bytePixels[0], width, height, channels*width, colorType, filename);+}++bool savePng(BitmapConstSection<byte, 1> bitmap, const char *filename) {+ bitmap.reorient(Y_DOWNWARD);+ return pngSave(bitmap.pixels, bitmap.width, bitmap.height, bitmap.rowStride, PNG_COLOR_TYPE_GRAY, filename);+}++bool savePng(BitmapConstSection<byte, 3> bitmap, const char *filename) {+ bitmap.reorient(Y_DOWNWARD);+ return pngSave(bitmap.pixels, bitmap.width, bitmap.height, bitmap.rowStride, PNG_COLOR_TYPE_RGB, filename);+}++bool savePng(BitmapConstSection<byte, 4> bitmap, const char *filename) {+ bitmap.reorient(Y_DOWNWARD);+ return pngSave(bitmap.pixels, bitmap.width, bitmap.height, bitmap.rowStride, PNG_COLOR_TYPE_RGB_ALPHA, filename);+}++bool savePng(BitmapConstSection<float, 1> bitmap, const char *filename) {+ bitmap.reorient(Y_DOWNWARD);+ return pngSave(bitmap.pixels, bitmap.width, bitmap.height, bitmap.rowStride, 1, PNG_COLOR_TYPE_GRAY, filename);+}++bool savePng(BitmapConstSection<float, 3> bitmap, const char *filename) {+ bitmap.reorient(Y_DOWNWARD);+ return pngSave(bitmap.pixels, bitmap.width, bitmap.height, bitmap.rowStride, 3, PNG_COLOR_TYPE_RGB, filename);+}++bool savePng(BitmapConstSection<float, 4> bitmap, const char *filename) {+ bitmap.reorient(Y_DOWNWARD);+ return pngSave(bitmap.pixels, bitmap.width, bitmap.height, bitmap.rowStride, 4, PNG_COLOR_TYPE_RGB_ALPHA, filename);+}++}++#endif++#ifdef MSDFGEN_USE_LODEPNG++#include <lodepng.h>++namespace msdfgen {++bool savePng(BitmapConstSection<byte, 1> bitmap, const char *filename) {+ std::vector<byte> pixels(bitmap.width*bitmap.height);+ bitmap.reorient(Y_DOWNWARD);+ for (int y = 0; y < bitmap.height; ++y)+ memcpy(&pixels[bitmap.width*y], bitmap(0, y), 1*bitmap.width);+ return !lodepng::encode(filename, pixels, bitmap.width, bitmap.height, LCT_GREY);+}++bool savePng(BitmapConstSection<byte, 3> bitmap, const char *filename) {+ std::vector<byte> pixels(3*bitmap.width*bitmap.height);+ bitmap.reorient(Y_DOWNWARD);+ for (int y = 0; y < bitmap.height; ++y)+ memcpy(&pixels[3*bitmap.width*y], bitmap(0, y), 3*bitmap.width);+ return !lodepng::encode(filename, pixels, bitmap.width, bitmap.height, LCT_RGB);+}++bool savePng(BitmapConstSection<byte, 4> bitmap, const char *filename) {+ std::vector<byte> pixels(4*bitmap.width*bitmap.height);+ bitmap.reorient(Y_DOWNWARD);+ for (int y = 0; y < bitmap.height; ++y)+ memcpy(&pixels[4*bitmap.width*y], bitmap(0, y), 4*bitmap.width);+ return !lodepng::encode(filename, pixels, bitmap.width, bitmap.height, LCT_RGBA);+}++bool savePng(BitmapConstSection<float, 1> bitmap, const char *filename) {+ std::vector<byte> pixels(bitmap.width*bitmap.height);+ std::vector<byte>::iterator it = pixels.begin();+ bitmap.reorient(Y_DOWNWARD);+ for (int y = 0; y < bitmap.height; ++y) {+ for (int x = 0; x < bitmap.width; ++x)+ *it++ = pixelFloatToByte(*bitmap(x, y));+ }+ return !lodepng::encode(filename, pixels, bitmap.width, bitmap.height, LCT_GREY);+}++bool savePng(BitmapConstSection<float, 3> bitmap, const char *filename) {+ std::vector<byte> pixels(3*bitmap.width*bitmap.height);+ std::vector<byte>::iterator it = pixels.begin();+ bitmap.reorient(Y_DOWNWARD);+ for (int y = 0; y < bitmap.height; ++y) {+ for (int x = 0; x < bitmap.width; ++x) {+ *it++ = pixelFloatToByte(bitmap(x, y)[0]);+ *it++ = pixelFloatToByte(bitmap(x, y)[1]);+ *it++ = pixelFloatToByte(bitmap(x, y)[2]);+ }+ }+ return !lodepng::encode(filename, pixels, bitmap.width, bitmap.height, LCT_RGB);+}++bool savePng(BitmapConstSection<float, 4> bitmap, const char *filename) {+ std::vector<byte> pixels(4*bitmap.width*bitmap.height);+ std::vector<byte>::iterator it = pixels.begin();+ bitmap.reorient(Y_DOWNWARD);+ for (int y = 0; y < bitmap.height; ++y) {+ for (int x = 0; x < bitmap.width; ++x) {+ *it++ = pixelFloatToByte(bitmap(x, y)[0]);+ *it++ = pixelFloatToByte(bitmap(x, y)[1]);+ *it++ = pixelFloatToByte(bitmap(x, y)[2]);+ *it++ = pixelFloatToByte(bitmap(x, y)[3]);+ }+ }+ return !lodepng::encode(filename, pixels, bitmap.width, bitmap.height, LCT_RGBA);+}++}++#endifdiff --git a/third_party/msdfgen/ext/save-png.h b/third_party/msdfgen/ext/save-png.hnew file mode 100644index 000000000..306fe2527--- /dev/null+++ b/third_party/msdfgen/ext/save-png.h@@ -0,0 +1,20 @@++#pragma once++#include "../core/BitmapRef.hpp"++#ifndef MSDFGEN_DISABLE_PNG++namespace msdfgen {++/// Saves the bitmap as a PNG file.+bool savePng(BitmapConstSection<byte, 1> bitmap, const char *filename);+bool savePng(BitmapConstSection<byte, 3> bitmap, const char *filename);+bool savePng(BitmapConstSection<byte, 4> bitmap, const char *filename);+bool savePng(BitmapConstSection<float, 1> bitmap, const char *filename);+bool savePng(BitmapConstSection<float, 3> bitmap, const char *filename);+bool savePng(BitmapConstSection<float, 4> bitmap, const char *filename);++}++#endifdiff --git a/third_party/msdfgen/icon.ico b/third_party/msdfgen/icon.iconew file mode 100644index 000000000..a43b2d7baBinary files /dev/null and b/third_party/msdfgen/icon.ico differdiff --git a/third_party/msdfgen/main.cpp b/third_party/msdfgen/main.cppnew file mode 100644index 000000000..e2693b35e--- /dev/null+++ b/third_party/msdfgen/main.cpp@@ -0,0 +1,1405 @@++/*+ * MULTI-CHANNEL SIGNED DISTANCE FIELD GENERATOR - standalone console program+ * --------------------------------------------------------------------------+ * A utility by Viktor Chlumsky, (c) 2014 - 2025+ *+ */++#ifdef MSDFGEN_STANDALONE++#ifndef _USE_MATH_DEFINES+#define _USE_MATH_DEFINES+#endif+#ifndef _CRT_SECURE_NO_WARNINGS+#define _CRT_SECURE_NO_WARNINGS+#endif++#include <cstdlib>+#include <cstdio>+#include <cmath>+#include <cstring>+#include <string>++#include "msdfgen.h"+#ifdef MSDFGEN_EXTENSIONS+#include "msdfgen-ext.h"+#endif++#include "core/ShapeDistanceFinder.h"++#define SDF_ERROR_ESTIMATE_PRECISION 19+#define DEFAULT_ANGLE_THRESHOLD 3.++#if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)+#define DEFAULT_IMAGE_EXTENSION "png"+#define SAVE_DEFAULT_IMAGE_FORMAT savePng+#else+#define DEFAULT_IMAGE_EXTENSION "bmp"+#define SAVE_DEFAULT_IMAGE_FORMAT saveBmp+#endif++using namespace msdfgen;++enum Format {+ AUTO,+ PNG,+ BMP,+ TIFF,+ RGBA,+ FL32,+ TEXT,+ TEXT_FLOAT,+ BINARY,+ BINARY_FLOAT,+ BINARY_FLOAT_BE+};++static bool is8bitFormat(Format format) {+ return format == PNG || format == BMP || format == RGBA || format == TEXT || format == BINARY;+}++static char toupper(char c) {+ return c >= 'a' && c <= 'z' ? c-'a'+'A' : c;+}++static bool parseUnsigned(unsigned &value, const char *arg) {+ char *end = NULL;+ value = (unsigned) strtoul(arg, &end, 10);+ return end > arg && !*end;+}++static bool parseUnsignedDecOrHex(unsigned &value, const char *arg) {+ char *end = NULL;+ if (arg[0] == '0' && (arg[1] == 'x' || arg[1] == 'X')) {+ arg += 2;+ value = (unsigned) strtoul(arg, &end, 16);+ } else+ value = (unsigned) strtoul(arg, &end, 10);+ return end > arg && !*end;+ }++static bool parseUnsignedLL(unsigned long long &value, const char *arg) {+ if (*arg >= '0' && *arg <= '9') {+ value = 0;+ do {+ value = 10*value+(*arg++-'0');+ } while (*arg >= '0' && *arg <= '9');+ return !*arg;+}+ return false;+}++static bool parseDouble(double &value, const char *arg) {+ char *end = NULL;+ value = strtod(arg, &end);+ return end > arg && !*end;+}++static bool parseAngle(double &value, const char *arg) {+ char *end = NULL;+ value = strtod(arg, &end);+ if (end > arg) {+ arg = end;+ if (*arg == 'd' || *arg == 'D') {+ ++arg;+ value *= M_PI/180;+ }+ return !*arg;+ }+ return false;+}++static void parseColoring(Shape &shape, const char *edgeAssignment) {+ unsigned c = 0, e = 0;+ if (shape.contours.size() < c) return;+ Contour *contour = &shape.contours[c];+ bool change = false;+ bool clear = true;+ for (const char *in = edgeAssignment; *in; ++in) {+ switch (*in) {+ case ',':+ if (change)+ ++e;+ if (clear)+ while (e < contour->edges.size()) {+ contour->edges[e]->color = WHITE;+ ++e;+ }+ ++c, e = 0;+ if (shape.contours.size() <= c) return;+ contour = &shape.contours[c];+ change = false;+ clear = true;+ break;+ case '?':+ clear = false;+ break;+ case 'C': case 'M': case 'W': case 'Y': case 'c': case 'm': case 'w': case 'y':+ if (change) {+ ++e;+ change = false;+ }+ if (e < contour->edges.size()) {+ contour->edges[e]->color = EdgeColor(+ (*in == 'C' || *in == 'c')*CYAN|+ (*in == 'M' || *in == 'm')*MAGENTA|+ (*in == 'Y' || *in == 'y')*YELLOW|+ (*in == 'W' || *in == 'w')*WHITE);+ change = true;+ }+ break;+ }+ }+}++#ifdef MSDFGEN_EXTENSIONS+static bool parseUnicode(unicode_t &unicode, const char *arg) {+ unsigned uuc;+ if (parseUnsignedDecOrHex(uuc, arg)) {+ unicode = uuc;+ return true;+ }+ if (arg[0] == '\'' && arg[1] && arg[2] == '\'' && !arg[3]) {+ unicode = (unicode_t) (unsigned char) arg[1];+ return true;+ }+ return false;+}++#ifndef MSDFGEN_DISABLE_VARIABLE_FONTS+static FontHandle *loadVarFont(FreetypeHandle *library, const char *filename) {+ std::string buffer;+ while (*filename && *filename != '?')+ buffer.push_back(*filename++);+ FontHandle *font = loadFont(library, buffer.c_str());+ if (font && *filename++ == '?') {+ do {+ buffer.clear();+ while (*filename && *filename != '=')+ buffer.push_back(*filename++);+ if (*filename == '=') {+ char *end = NULL;+ double value = strtod(++filename, &end);+ if (end > filename) {+ filename = end;+ setFontVariationAxis(library, font, buffer.c_str(), value);+ }+ }+ } while (*filename++ == '&');+ }+ return font;+}+#endif+#endif++static bool writeTextBitmap(FILE *file, const float *values, int cols, int rows, int rowStride) {+ for (int row = 0; row < rows; ++row) {+ const float *cur = values;+ for (int col = 0; col < cols; ++col)+ fprintf(file, col ? " %02X" : "%02X", int(pixelFloatToByte(*cur++)));+ fprintf(file, "\n");+ values += rowStride;+ }+ return true;+}++static bool writeTextBitmapFloat(FILE *file, const float *values, int cols, int rows, int rowStride) {+ for (int row = 0; row < rows; ++row) {+ const float *cur = values;+ for (int col = 0; col < cols; ++col)+ fprintf(file, col ? " %.9g" : "%.9g", *cur++);+ fprintf(file, "\n");+ values += rowStride;+ }+ return true;+}++static bool writeBinBitmap(FILE *file, const float *values, int cols, int rows, int rowStride) {+ for (int row = 0; row < rows; ++row) {+ const float *cur = values;+ for (int col = 0; col < cols; ++col) {+ byte v = pixelFloatToByte(*cur++);+ fwrite(&v, 1, 1, file);+ }+ values += rowStride;+ }+ return true;+}++#ifdef __BIG_ENDIAN__+static bool writeBinBitmapFloatBE(FILE *file, const float *values, int cols, int rows, int rowStride)+#else+static bool writeBinBitmapFloat(FILE *file, const float *values, int cols, int rows, int rowStride)+#endif+{+ for (int row = 0; row < rows; ++row) {+ fwrite(values, sizeof(float), cols, file);+ values += rowStride;+ }+ return true;+}++#ifdef __BIG_ENDIAN__+static bool writeBinBitmapFloat(FILE *file, const float *values, int cols, int rows, int rowStride)+#else+static bool writeBinBitmapFloatBE(FILE *file, const float *values, int cols, int rows, int rowStride)+#endif+{+ for (int row = 0; row < rows; ++row) {+ const float *cur = values;+ for (int col = 0; col < cols; ++col) {+ const unsigned char *b = reinterpret_cast<const unsigned char *>(cur++);+ for (int i = int(sizeof(float)); i--;)+ fwrite(b+i, 1, 1, file);+ }+ values += rowStride;+ }+ return true;+}++static bool cmpExtension(const char *path, const char *ext) {+ for (const char *a = path+strlen(path)-1, *b = ext+strlen(ext)-1; b >= ext; --a, --b)+ if (a < path || toupper(*a) != toupper(*b))+ return false;+ return true;+}++template <int N>+static const char *writeOutput(const BitmapConstSection<float, N> &bitmap, const char *filename, Format &format) {+ if (filename) {+ if (format == AUTO) {+ #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)+ if (cmpExtension(filename, ".png")) format = PNG;+ #else+ if (cmpExtension(filename, ".png"))+ return "PNG format is not available in core-only version.";+ #endif+ else if (cmpExtension(filename, ".bmp")) format = BMP;+ else if (cmpExtension(filename, ".tiff") || cmpExtension(filename, ".tif")) format = TIFF;+ else if (cmpExtension(filename, ".rgba")) format = RGBA;+ else if (cmpExtension(filename, ".fl32")) format = FL32;+ else if (cmpExtension(filename, ".txt")) format = TEXT;+ else if (cmpExtension(filename, ".bin")) format = BINARY;+ else+ return "Could not deduce format from output file name.";+ }+ switch (format) {+ #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)+ case PNG: return savePng(bitmap, filename) ? NULL : "Failed to write output PNG image.";+ #endif+ case BMP: return saveBmp(bitmap, filename) ? NULL : "Failed to write output BMP image.";+ case TIFF: return saveTiff(bitmap, filename) ? NULL : "Failed to write output TIFF image.";+ case RGBA: return saveRgba(bitmap, filename) ? NULL : "Failed to write output RGBA image.";+ case FL32: return saveFl32(bitmap, filename) ? NULL : "Failed to write output FL32 image.";+ case TEXT: case TEXT_FLOAT: {+ FILE *file = fopen(filename, "w");+ if (!file) return "Failed to write output text file.";+ if (format == TEXT)+ writeTextBitmap(file, bitmap.pixels, N*bitmap.width, bitmap.height, bitmap.rowStride);+ else if (format == TEXT_FLOAT)+ writeTextBitmapFloat(file, bitmap.pixels, N*bitmap.width, bitmap.height, bitmap.rowStride);+ fclose(file);+ return NULL;+ }+ case BINARY: case BINARY_FLOAT: case BINARY_FLOAT_BE: {+ FILE *file = fopen(filename, "wb");+ if (!file) return "Failed to write output binary file.";+ if (format == BINARY)+ writeBinBitmap(file, bitmap.pixels, N*bitmap.width, bitmap.height, bitmap.rowStride);+ else if (format == BINARY_FLOAT)+ writeBinBitmapFloat(file, bitmap.pixels, N*bitmap.width, bitmap.height, bitmap.rowStride);+ else if (format == BINARY_FLOAT_BE)+ writeBinBitmapFloatBE(file, bitmap.pixels, N*bitmap.width, bitmap.height, bitmap.rowStride);+ fclose(file);+ return NULL;+ }+ default:;+ }+ } else {+ if (format == AUTO || format == TEXT)+ writeTextBitmap(stdout, bitmap.pixels, N*bitmap.width, bitmap.height, bitmap.rowStride);+ else if (format == TEXT_FLOAT)+ writeTextBitmapFloat(stdout, bitmap.pixels, N*bitmap.width, bitmap.height, bitmap.rowStride);+ else+ return "Unsupported format for standard output.";+ }+ return NULL;+}++#define STRINGIZE_(x) #x+#define STRINGIZE(x) STRINGIZE_(x)+#define MSDFGEN_VERSION_STRING STRINGIZE(MSDFGEN_VERSION)+#ifdef MSDFGEN_VERSION_UNDERLINE+ #define VERSION_UNDERLINE STRINGIZE(MSDFGEN_VERSION_UNDERLINE)+#else+ #define VERSION_UNDERLINE "--------"+#endif++#if defined(MSDFGEN_EXTENSIONS) && (defined(MSDFGEN_DISABLE_SVG) || defined(MSDFGEN_DISABLE_PNG) || defined(MSDFGEN_DISABLE_VARIABLE_FONTS))+ #define TITLE_SUFFIX " - custom config"+ #define SUFFIX_UNDERLINE "----------------"+#elif !defined(MSDFGEN_EXTENSIONS) && defined(MSDFGEN_USE_OPENMP)+ #define TITLE_SUFFIX " - core with OpenMP"+ #define SUFFIX_UNDERLINE "-------------------"+#elif !defined(MSDFGEN_EXTENSIONS)+ #define TITLE_SUFFIX " - core only"+ #define SUFFIX_UNDERLINE "------------"+#elif defined(MSDFGEN_USE_SKIA) && defined(MSDFGEN_USE_OPENMP)+ #define TITLE_SUFFIX " with Skia & OpenMP"+ #define SUFFIX_UNDERLINE "-------------------"+#elif defined(MSDFGEN_USE_SKIA)+ #define TITLE_SUFFIX " with Skia"+ #define SUFFIX_UNDERLINE "----------"+#elif defined(MSDFGEN_USE_OPENMP)+ #define TITLE_SUFFIX " with OpenMP"+ #define SUFFIX_UNDERLINE "------------"+#else+ #define TITLE_SUFFIX+ #define SUFFIX_UNDERLINE+#endif++static const char *const versionText =+ "MSDFgen v" MSDFGEN_VERSION_STRING TITLE_SUFFIX "\n"+ "(c) 2014 - " STRINGIZE(MSDFGEN_COPYRIGHT_YEAR) " Viktor Chlumsky";++static const char *const helpText =+ "\n"+ "Multi-channel signed distance field generator by Viktor Chlumsky v" MSDFGEN_VERSION_STRING TITLE_SUFFIX "\n"+ "------------------------------------------------------------------" VERSION_UNDERLINE SUFFIX_UNDERLINE "\n"+ " Usage: msdfgen"+ #ifdef _WIN32+ ".exe"+ #endif+ " <mode> <input specification> <options>\n"+ "\n"+ "MODES\n"+ " sdf - Generate conventional monochrome (true) signed distance field.\n"+ " psdf - Generate monochrome signed perpendicular distance field.\n"+ " msdf - Generate multi-channel signed distance field. This is used by default if no mode is specified.\n"+ " mtsdf - Generate combined multi-channel and true signed distance field in the alpha channel.\n"+ " metrics - Report shape metrics only.\n"+ "\n"+ "INPUT SPECIFICATION\n"+ " -defineshape <definition>\n"+ "\tDefines input shape using the ad-hoc text definition.\n"+#ifdef MSDFGEN_EXTENSIONS+ " -font <filename.ttf> <character code>\n"+ "\tLoads a single glyph from the specified font file.\n"+ "\tFormat of character code is '?', 63, 0x3F (Unicode value), or g34 (glyph index).\n"+#endif+ " -shapedesc <filename.txt>\n"+ "\tLoads text shape description from a file.\n"+ " -stdin\n"+ "\tReads text shape description from the standard input.\n"+#if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_SVG)+ " -svg <filename.svg>\n"+ "\tLoads the last vector path found in the specified SVG file.\n"+#endif+#if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_VARIABLE_FONTS)+ " -varfont <filename and variables> <character code>\n"+ "\tLoads a single glyph from a variable font. Specify variable values as x.ttf?var1=0.5&var2=1\n"+#endif+ "\n"+ // Keep alphabetical order!+ "OPTIONS\n"+ " -angle <angle>\n"+ "\tSpecifies the minimum angle between adjacent edges to be considered a corner. Append D for degrees.\n"+ " -apxrange <outermost distance> <innermost distance>\n"+ "\tSpecifies the outermost (negative) and innermost representable distance in pixels.\n"+ " -arange <outermost distance> <innermost distance>\n"+ "\tSpecifies the outermost (negative) and innermost representable distance in shape units.\n"+ " -ascale <x scale> <y scale>\n"+ "\tSets the scale used to convert shape units to pixels asymmetrically.\n"+ " -autoframe\n"+ "\tAutomatically scales (unless specified) and translates the shape to fit.\n"+ " -coloringstrategy <simple / inktrap / distance>\n"+ "\tSelects the strategy of the edge coloring heuristic.\n"+ " -dimensions <width> <height>\n"+ "\tSets the dimensions of the output image.\n"+ " -edgecolors <sequence>\n"+ "\tOverrides automatic edge coloring with the specified color sequence.\n"+#ifdef MSDFGEN_EXTENSIONS+ " -emnormalize\n"+ "\tBefore applying scale, normalizes font glyph coordinates so that 1 = 1 em.\n"+#endif+ " -errorcorrection <mode>\n"+ "\tChanges the MSDF/MTSDF error correction mode. Use -errorcorrection help for a list of valid modes.\n"+ " -errordeviationratio <ratio>\n"+ "\tSets the minimum ratio between the actual and maximum expected distance delta to be considered an error.\n"+ " -errorimproveratio <ratio>\n"+ "\tSets the minimum ratio between the pre-correction distance error and the post-correction distance error.\n"+ " -estimateerror\n"+ "\tComputes and prints the distance field's estimated fill error to the standard output.\n"+ " -exportshape <filename.txt>\n"+ "\tSaves the shape description into a text file that can be edited and loaded using -shapedesc.\n"+ " -exportsvg <filename.svg>\n"+ "\tSaves the shape geometry into a simple SVG file.\n"+ " -fillrule <nonzero / evenodd / positive / negative>\n"+ "\tSets the fill rule for the scanline pass. Default is nonzero.\n"+#if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)+ " -format <png / bmp / tiff / rgba / fl32 / text / textfloat / bin / binfloat / binfloatbe>\n"+#else+ " -format <bmp / tiff / rgba / fl32 / text / textfloat / bin / binfloat / binfloatbe>\n"+#endif+ "\tSpecifies the output format of the distance field. Otherwise it is chosen based on output file extension.\n"+ " -guesswinding\n"+ "\tAttempts to detect if shape contours have the wrong winding and generates the SDF with the right one.\n"+ " -help\n"+ "\tDisplays this help.\n"+ " -legacy\n"+ "\tUses the original (legacy) distance field algorithms.\n"+#ifdef MSDFGEN_EXTENSIONS+ " -noemnormalize\n"+ "\tRaw integer font glyph coordinates will be used. Without this option, legacy scaling will be applied.\n"+#endif+#ifdef MSDFGEN_USE_SKIA+ " -nopreprocess\n"+ "\tDisables path preprocessing which resolves self-intersections and overlapping contours.\n"+#else+ " -nooverlap\n"+ "\tDisables resolution of overlapping contours.\n"+ " -noscanline\n"+ "\tDisables the scanline pass, which corrects the distance field's signs according to the selected fill rule.\n"+#endif+ " -o <filename>\n"+ "\tSets the output file name. The default value is \"output." DEFAULT_IMAGE_EXTENSION "\".\n"+#ifdef MSDFGEN_USE_SKIA+ " -overlap\n"+ "\tSwitches to distance field generator with support for overlapping contours.\n"+#endif+ " -printmetrics\n"+ "\tPrints relevant metrics of the shape to the standard output.\n"+ " -pxrange <range>\n"+ "\tSets the width of the range between the lowest and highest signed distance in pixels.\n"+ " -range <range>\n"+ "\tSets the width of the range between the lowest and highest signed distance in shape units.\n"+ " -reversewinding\n"+ "\tGenerates the distance field as if the shape's vertices were in reverse order.\n"+ " -scale <scale>\n"+ "\tSets the scale used to convert shape units to pixels.\n"+#ifdef MSDFGEN_USE_SKIA+ " -scanline\n"+ "\tPerforms an additional scanline pass to fix the signs of the distances.\n"+#endif+ " -seed <n>\n"+ "\tSets the random seed for edge coloring heuristic.\n"+ " -stdout\n"+ "\tPrints the output instead of storing it in a file. Only text formats are supported.\n"+ " -testrender <filename." DEFAULT_IMAGE_EXTENSION "> <width> <height>\n"+#if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)+ "\tRenders an image preview using the generated distance field and saves it as a PNG file.\n"+#else+ "\tRenders an image preview using the generated distance field and saves it as a BMP file.\n"+#endif+ " -testrendermulti <filename." DEFAULT_IMAGE_EXTENSION "> <width> <height>\n"+ "\tRenders an image preview without resolving the color channels.\n"+ " -translate <x> <y>\n"+ "\tSets the translation of the shape in shape units.\n"+ " -version\n"+ "\tPrints the version of the program.\n"+ " -windingpreprocess\n"+ "\tAttempts to fix only the contour windings assuming no self-intersections and even-odd fill rule.\n"+ " -yflip\n"+ "\tInverts the Y-axis in the output distance field. The default orientation is upward.\n"+ "\n";++static const char *errorCorrectionHelpText =+ "\n"+ "ERROR CORRECTION MODES\n"+ " auto-fast\n"+ "\tDetects inversion artifacts and distance errors that do not affect edges by range testing.\n"+ " auto-full\n"+ "\tDetects inversion artifacts and distance errors that do not affect edges by exact distance evaluation.\n"+ " auto-mixed (default)\n"+ "\tDetects inversions by distance evaluation and distance errors that do not affect edges by range testing.\n"+ " disabled\n"+ "\tDisables error correction.\n"+ " distance-fast\n"+ "\tDetects distance errors by range testing. Does not care if edges and corners are affected.\n"+ " distance-full\n"+ "\tDetects distance errors by exact distance evaluation. Does not care if edges and corners are affected, slow.\n"+ " edge-fast\n"+ "\tDetects inversion artifacts only by range testing.\n"+ " edge-full\n"+ "\tDetects inversion artifacts only by exact distance evaluation.\n"+ " help\n"+ "\tDisplays this help.\n"+ "\n";++int main(int argc, const char *const *argv) {+ #define ABORT(msg) do { fputs(msg "\n", stderr); return 1; } while (false)++ // Parse command line arguments+ enum {+ NONE,+ SVG,+ FONT,+ VAR_FONT,+ DESCRIPTION_ARG,+ DESCRIPTION_STDIN,+ DESCRIPTION_FILE+ } inputType = NONE;+ enum {+ SINGLE,+ PERPENDICULAR,+ MULTI,+ MULTI_AND_TRUE,+ METRICS+ } mode = MULTI;+ enum {+ NO_PREPROCESS,+ WINDING_PREPROCESS,+ FULL_PREPROCESS+ } geometryPreproc = (+ #ifdef MSDFGEN_USE_SKIA+ FULL_PREPROCESS+ #else+ NO_PREPROCESS+ #endif+ );+ bool legacyMode = false;+ MSDFGeneratorConfig generatorConfig;+ generatorConfig.overlapSupport = geometryPreproc == NO_PREPROCESS;+ bool scanlinePass = geometryPreproc == NO_PREPROCESS;+ FillRule fillRule = FILL_NONZERO;+ Format format = AUTO;+ const char *input = NULL;+ const char *output = "output." DEFAULT_IMAGE_EXTENSION;+ const char *shapeExport = NULL;+ const char *svgExport = NULL;+ const char *testRender = NULL;+ const char *testRenderMulti = NULL;+ bool outputSpecified = false;+#ifdef MSDFGEN_EXTENSIONS+ bool glyphIndexSpecified = false;+ GlyphIndex glyphIndex;+ unicode_t unicode = 0;+ FontCoordinateScaling fontCoordinateScaling = FONT_SCALING_LEGACY;+ bool fontCoordinateScalingSpecified = false;+#endif++ int width = 64, height = 64;+ int testWidth = 0, testHeight = 0;+ int testWidthM = 0, testHeightM = 0;+ bool autoFrame = false;+ enum {+ RANGE_UNIT,+ RANGE_PX+ } rangeMode = RANGE_PX;+ Range range(1);+ Range pxRange(2);+ Vector2 translate;+ Vector2 scale = 1;+ bool scaleSpecified = false;+ double angleThreshold = DEFAULT_ANGLE_THRESHOLD;+ float outputDistanceShift = 0.f;+ const char *edgeAssignment = NULL;+ bool yFlip = false;+ bool printMetrics = false;+ bool estimateError = false;+ bool skipColoring = false;+ enum {+ KEEP,+ REVERSE,+ GUESS+ } winding = KEEP;+ unsigned long long coloringSeed = 0;+ void (*edgeColoring)(Shape &, double, unsigned long long) = &edgeColoringSimple;+ bool explicitErrorCorrectionMode = false;++ int argPos = 1;+ bool suggestHelp = false;+ while (argPos < argc) {+ const char *arg = argv[argPos];+ #define ARG_CASE(s, p) if ((!strcmp(arg, s)) && argPos+(p) < argc && (++argPos, true))+ #define ARG_CASE_OR ) || !strcmp(arg,+ #define ARG_MODE(s, m) if (!strcmp(arg, s)) { mode = m; ++argPos; continue; }+ #define ARG_IS(s) (!strcmp(argv[argPos], s))+ #define SET_FORMAT(fmt, ext) do { format = fmt; if (!outputSpecified) output = "output." ext; } while (false)++ // Accept arguments prefixed with -- instead of -+ if (arg[0] == '-' && arg[1] == '-')+ ++arg;++ ARG_MODE("sdf", SINGLE)+ ARG_MODE("psdf", PERPENDICULAR)+ ARG_MODE("msdf", MULTI)+ ARG_MODE("mtsdf", MULTI_AND_TRUE)+ ARG_MODE("metrics", METRICS)++ #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_SVG)+ ARG_CASE("-svg", 1) {+ inputType = SVG;+ input = argv[argPos++];+ continue;+ }+ #endif+ #ifdef MSDFGEN_EXTENSIONS+ //ARG_CASE -font, -varfont+ if (argPos+2 < argc && (+ (!strcmp(arg, "-font") && (inputType = FONT, true))+ #ifndef MSDFGEN_DISABLE_VARIABLE_FONTS+ || (!strcmp(arg, "-varfont") && (inputType = VAR_FONT, true))+ #endif+ ) && (++argPos, true)) {+ input = argv[argPos++];+ const char *charArg = argv[argPos++];+ unsigned gi;+ switch (charArg[0]) {+ case 'G': case 'g':+ if (parseUnsignedDecOrHex(gi, charArg+1)) {+ glyphIndex = GlyphIndex(gi);+ glyphIndexSpecified = true;+ }+ break;+ case 'U': case 'u':+ ++charArg;+ // fallthrough+ default:+ parseUnicode(unicode, charArg);+ }+ continue;+ }+ ARG_CASE("-noemnormalize", 0) {+ fontCoordinateScaling = FONT_SCALING_NONE;+ fontCoordinateScalingSpecified = true;+ continue;+ }+ ARG_CASE("-emnormalize", 0) {+ fontCoordinateScaling = FONT_SCALING_EM_NORMALIZED;+ fontCoordinateScalingSpecified = true;+ continue;+ }+ ARG_CASE("-legacyfontscaling", 0) {+ fontCoordinateScaling = FONT_SCALING_LEGACY;+ fontCoordinateScalingSpecified = true;+ continue;+ }+ #else+ ARG_CASE("-svg", 1) {+ ABORT("SVG input is not available in core-only version.");+ }+ ARG_CASE("-font", 2) {+ ABORT("Font input is not available in core-only version.");+ }+ ARG_CASE("-varfont", 2) {+ ABORT("Variable font input is not available in core-only version.");+ }+ #endif+ ARG_CASE("-defineshape", 1) {+ inputType = DESCRIPTION_ARG;+ input = argv[argPos++];+ continue;+ }+ ARG_CASE("-stdin", 0) {+ inputType = DESCRIPTION_STDIN;+ input = "stdin";+ continue;+ }+ ARG_CASE("-shapedesc", 1) {+ inputType = DESCRIPTION_FILE;+ input = argv[argPos++];+ continue;+ }+ ARG_CASE("-o" ARG_CASE_OR "-out" ARG_CASE_OR "-output" ARG_CASE_OR "-imageout", 1) {+ output = argv[argPos++];+ outputSpecified = true;+ continue;+ }+ ARG_CASE("-stdout", 0) {+ output = NULL;+ continue;+ }+ ARG_CASE("-legacy", 0) {+ legacyMode = true;+ #ifdef MSDFGEN_EXTENSIONS+ fontCoordinateScaling = FONT_SCALING_LEGACY;+ fontCoordinateScalingSpecified = true;+ #endif+ continue;+ }+ ARG_CASE("-nopreprocess", 0) {+ geometryPreproc = NO_PREPROCESS;+ continue;+ }+ ARG_CASE("-windingpreprocess", 0) {+ geometryPreproc = WINDING_PREPROCESS;+ continue;+ }+ ARG_CASE("-preprocess", 0) {+ geometryPreproc = FULL_PREPROCESS;+ continue;+ }+ ARG_CASE("-nooverlap", 0) {+ generatorConfig.overlapSupport = false;+ continue;+ }+ ARG_CASE("-overlap", 0) {+ generatorConfig.overlapSupport = true;+ continue;+ }+ ARG_CASE("-noscanline", 0) {+ scanlinePass = false;+ continue;+ }+ ARG_CASE("-scanline", 0) {+ scanlinePass = true;+ continue;+ }+ ARG_CASE("-fillrule", 1) {+ scanlinePass = true;+ if (ARG_IS("nonzero")) fillRule = FILL_NONZERO;+ else if (ARG_IS("evenodd") || ARG_IS("odd")) fillRule = FILL_ODD;+ else if (ARG_IS("positive")) fillRule = FILL_POSITIVE;+ else if (ARG_IS("negative")) fillRule = FILL_NEGATIVE;+ else+ fputs("Unknown fill rule specified.\n", stderr);+ ++argPos;+ continue;+ }+ ARG_CASE("-format", 1) {+ if (ARG_IS("auto")) format = AUTO;+ #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)+ else if (ARG_IS("png")) SET_FORMAT(PNG, "png");+ #else+ else if (ARG_IS("png"))+ fputs("PNG format is not available in core-only version.\n", stderr);+ #endif+ else if (ARG_IS("bmp")) SET_FORMAT(BMP, "bmp");+ else if (ARG_IS("tiff") || ARG_IS("tif")) SET_FORMAT(TIFF, "tiff");+ else if (ARG_IS("rgba")) SET_FORMAT(RGBA, "rgba");+ else if (ARG_IS("fl32")) SET_FORMAT(FL32, "fl32");+ else if (ARG_IS("text") || ARG_IS("txt")) SET_FORMAT(TEXT, "txt");+ else if (ARG_IS("textfloat") || ARG_IS("txtfloat")) SET_FORMAT(TEXT_FLOAT, "txt");+ else if (ARG_IS("bin") || ARG_IS("binary")) SET_FORMAT(BINARY, "bin");+ else if (ARG_IS("binfloat") || ARG_IS("binfloatle")) SET_FORMAT(BINARY_FLOAT, "bin");+ else if (ARG_IS("binfloatbe")) SET_FORMAT(BINARY_FLOAT_BE, "bin");+ else+ fputs("Unknown format specified.\n", stderr);+ ++argPos;+ continue;+ }+ ARG_CASE("-dimensions" ARG_CASE_OR "-size", 2) {+ unsigned w, h;+ if (!(parseUnsigned(w, argv[argPos++]) && parseUnsigned(h, argv[argPos++]) && w && h))+ ABORT("Invalid dimensions. Use -dimensions <width> <height> with two positive integers.");+ width = w, height = h;+ continue;+ }+ ARG_CASE("-autoframe", 0) {+ autoFrame = true;+ continue;+ }+ ARG_CASE("-range" ARG_CASE_OR "-unitrange", 1) {+ double r;+ if (!parseDouble(r, argv[argPos++]))+ ABORT("Invalid range argument. Use -range <range> with a real number.");+ if (r == 0)+ ABORT("Range must be non-zero.");+ rangeMode = RANGE_UNIT;+ range = Range(r);+ continue;+ }+ ARG_CASE("-pxrange", 1) {+ double r;+ if (!parseDouble(r, argv[argPos++]))+ ABORT("Invalid range argument. Use -pxrange <range> with a real number.");+ if (r == 0)+ ABORT("Range must be non-zero.");+ rangeMode = RANGE_PX;+ pxRange = Range(r);+ continue;+ }+ ARG_CASE("-arange" ARG_CASE_OR "-aunitrange", 2) {+ double r0, r1;+ if (!(parseDouble(r0, argv[argPos++]) && parseDouble(r1, argv[argPos++])))+ ABORT("Invalid range arguments. Use -arange <minimum> <maximum> with two real numbers.");+ if (r0 == r1)+ ABORT("Range must be non-empty.");+ rangeMode = RANGE_UNIT;+ range = Range(r0, r1);+ continue;+ }+ ARG_CASE("-apxrange", 2) {+ double r0, r1;+ if (!(parseDouble(r0, argv[argPos++]) && parseDouble(r1, argv[argPos++])))+ ABORT("Invalid range arguments. Use -apxrange <minimum> <maximum> with two real numbers.");+ if (r0 == r1)+ ABORT("Range must be non-empty.");+ rangeMode = RANGE_PX;+ pxRange = Range(r0, r1);+ continue;+ }+ ARG_CASE("-scale", 1) {+ double s;+ if (!(parseDouble(s, argv[argPos++]) && s > 0))+ ABORT("Invalid scale argument. Use -scale <scale> with a positive real number.");+ scale = s;+ scaleSpecified = true;+ continue;+ }+ ARG_CASE("-ascale", 2) {+ double sx, sy;+ if (!(parseDouble(sx, argv[argPos++]) && parseDouble(sy, argv[argPos++]) && sx > 0 && sy > 0))+ ABORT("Invalid scale arguments. Use -ascale <x> <y> with two positive real numbers.");+ scale.set(sx, sy);+ scaleSpecified = true;+ continue;+ }+ ARG_CASE("-translate", 2) {+ double tx, ty;+ if (!(parseDouble(tx, argv[argPos++]) && parseDouble(ty, argv[argPos++])))+ ABORT("Invalid translate arguments. Use -translate <x> <y> with two real numbers.");+ translate.set(tx, ty);+ continue;+ }+ ARG_CASE("-angle", 1) {+ double at;+ if (!parseAngle(at, argv[argPos++]))+ ABORT("Invalid angle threshold. Use -angle <min angle> with a positive real number less than PI or a value in degrees followed by 'd' below 180d.");+ angleThreshold = at;+ continue;+ }+ ARG_CASE("-errorcorrection", 1) {+ if (ARG_IS("disable") || ARG_IS("disabled") || ARG_IS("0") || ARG_IS("none") || ARG_IS("false")) {+ generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::DISABLED;+ generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;+ } else if (ARG_IS("default") || ARG_IS("auto") || ARG_IS("auto-mixed") || ARG_IS("mixed")) {+ generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;+ generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::CHECK_DISTANCE_AT_EDGE;+ } else if (ARG_IS("auto-fast") || ARG_IS("fast")) {+ generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;+ generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;+ } else if (ARG_IS("auto-full") || ARG_IS("full")) {+ generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;+ generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;+ } else if (ARG_IS("distance") || ARG_IS("distance-fast") || ARG_IS("indiscriminate") || ARG_IS("indiscriminate-fast")) {+ generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::INDISCRIMINATE;+ generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;+ } else if (ARG_IS("distance-full") || ARG_IS("indiscriminate-full")) {+ generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::INDISCRIMINATE;+ generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;+ } else if (ARG_IS("edge-fast")) {+ generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_ONLY;+ generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;+ } else if (ARG_IS("edge") || ARG_IS("edge-full")) {+ generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_ONLY;+ generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;+ } else if (ARG_IS("help")) {+ puts(errorCorrectionHelpText);+ return 0;+ } else+ fputs("Unknown error correction mode. Use -errorcorrection help for more information.\n", stderr);+ ++argPos;+ explicitErrorCorrectionMode = true;+ continue;+ }+ ARG_CASE("-errordeviationratio", 1) {+ double edr;+ if (!(parseDouble(edr, argv[argPos++]) && edr > 0))+ ABORT("Invalid error deviation ratio. Use -errordeviationratio <ratio> with a positive real number.");+ generatorConfig.errorCorrection.minDeviationRatio = edr;+ continue;+ }+ ARG_CASE("-errorimproveratio", 1) {+ double eir;+ if (!(parseDouble(eir, argv[argPos++]) && eir > 0))+ ABORT("Invalid error improvement ratio. Use -errorimproveratio <ratio> with a positive real number.");+ generatorConfig.errorCorrection.minImproveRatio = eir;+ continue;+ }+ ARG_CASE("-coloringstrategy" ARG_CASE_OR "-edgecoloring", 1) {+ if (ARG_IS("simple")) edgeColoring = &edgeColoringSimple;+ else if (ARG_IS("inktrap")) edgeColoring = &edgeColoringInkTrap;+ else if (ARG_IS("distance")) edgeColoring = &edgeColoringByDistance;+ else+ fputs("Unknown coloring strategy specified.\n", stderr);+ ++argPos;+ continue;+ }+ ARG_CASE("-edgecolors", 1) {+ static const char *allowed = " ?,cmwyCMWY";+ for (int i = 0; argv[argPos][i]; ++i) {+ for (int j = 0; allowed[j]; ++j)+ if (argv[argPos][i] == allowed[j])+ goto EDGE_COLOR_VERIFIED;+ ABORT("Invalid edge coloring sequence. Use -edgecolors <color sequence> with only the colors C, M, Y, and W. Separate contours by commas and use ? to keep the default assigment for a contour.");+ EDGE_COLOR_VERIFIED:;+ }+ edgeAssignment = argv[argPos++];+ continue;+ }+ ARG_CASE("-distanceshift", 1) {+ double ds;+ if (!parseDouble(ds, argv[argPos++]))+ ABORT("Invalid distance shift. Use -distanceshift <shift> with a real value.");+ outputDistanceShift = (float) ds;+ continue;+ }+ ARG_CASE("-exportshape", 1) {+ shapeExport = argv[argPos++];+ continue;+ }+ ARG_CASE("-exportsvg", 1) {+ svgExport = argv[argPos++];+ continue;+ }+ ARG_CASE("-testrender", 3) {+ unsigned w, h;+ testRender = argv[argPos++];+ if (!(parseUnsigned(w, argv[argPos++]) && parseUnsigned(h, argv[argPos++]) && (int) w > 0 && (int) h > 0))+ ABORT("Invalid arguments for test render. Use -testrender <output." DEFAULT_IMAGE_EXTENSION "> <width> <height>.");+ testWidth = w, testHeight = h;+ continue;+ }+ ARG_CASE("-testrendermulti", 3) {+ unsigned w, h;+ testRenderMulti = argv[argPos++];+ if (!(parseUnsigned(w, argv[argPos++]) && parseUnsigned(h, argv[argPos++]) && (int) w > 0 && (int) h > 0))+ ABORT("Invalid arguments for test render. Use -testrendermulti <output." DEFAULT_IMAGE_EXTENSION "> <width> <height>.");+ testWidthM = w, testHeightM = h;+ continue;+ }+ ARG_CASE("-yflip", 0) {+ yFlip = true;+ continue;+ }+ ARG_CASE("-printmetrics", 0) {+ printMetrics = true;+ continue;+ }+ ARG_CASE("-estimateerror", 0) {+ estimateError = true;+ continue;+ }+ ARG_CASE("-keepwinding" ARG_CASE_OR "-keeporder", 0) {+ winding = KEEP;+ continue;+ }+ ARG_CASE("-reversewinding" ARG_CASE_OR "-reverseorder", 0) {+ winding = REVERSE;+ continue;+ }+ ARG_CASE("-guesswinding" ARG_CASE_OR "-guessorder", 0) {+ winding = GUESS;+ continue;+ }+ ARG_CASE("-seed", 1) {+ if (!parseUnsignedLL(coloringSeed, argv[argPos++]))+ ABORT("Invalid seed. Use -seed <N> with N being a non-negative integer.");+ continue;+ }+ ARG_CASE("-version", 0) {+ puts(versionText);+ return 0;+ }+ ARG_CASE("-help", 0) {+ puts(helpText);+ return 0;+ }+ fprintf(stderr, "Unknown setting or insufficient parameters: %s\n", argv[argPos++]);+ suggestHelp = true;+ }+ if (suggestHelp)+ fprintf(stderr, "Use -help for more information.\n");++ // Load input+ Shape::Bounds svgViewBox = { };+ double glyphAdvance = 0;+ if (!inputType || !input) {+ #ifdef MSDFGEN_EXTENSIONS+ #ifdef MSDFGEN_DISABLE_SVG+ ABORT("No input specified! Use -font <file.ttf/otf> <character code> or see -help.");+ #else+ ABORT("No input specified! Use either -svg <file.svg> or -font <file.ttf/otf> <character code>, or see -help.");+ #endif+ #else+ ABORT("No input specified! See -help.");+ #endif+ }+ Shape shape;+ switch (inputType) {+ #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_SVG)+ case SVG: {+ int svgImportFlags = loadSvgShape(shape, svgViewBox, input);+ if (!(svgImportFlags&SVG_IMPORT_SUCCESS_FLAG))+ ABORT("Failed to load shape from SVG file.");+ if (svgImportFlags&SVG_IMPORT_PARTIAL_FAILURE_FLAG)+ fputs("Warning: Failed to load part of SVG file.\n", stderr);+ if (svgImportFlags&SVG_IMPORT_INCOMPLETE_FLAG)+ fputs("Warning: SVG file contains multiple paths or shapes but this version is only able to load one.\n", stderr);+ else if (svgImportFlags&SVG_IMPORT_UNSUPPORTED_FEATURE_FLAG)+ fputs("Warning: SVG file likely contains elements that are unsupported.\n", stderr);+ if (svgImportFlags&SVG_IMPORT_TRANSFORMATION_IGNORED_FLAG)+ fputs("Warning: SVG path transformation ignored.\n", stderr);+ break;+ }+ #endif+ #ifdef MSDFGEN_EXTENSIONS+ case FONT: case VAR_FONT: {+ if (!glyphIndexSpecified && !unicode)+ ABORT("No character specified! Use -font <file.ttf/otf> <character code>. Character code can be a Unicode index (65, 0x41), a character in apostrophes ('A'), or a glyph index prefixed by g (g36, g0x24).");+ struct FreetypeFontGuard {+ FreetypeHandle *ft;+ FontHandle *font;+ FreetypeFontGuard() : ft(), font() { }+ ~FreetypeFontGuard() {+ if (ft) {+ if (font)+ destroyFont(font);+ deinitializeFreetype(ft);+ }+ }+ } guard;+ if (!(guard.ft = initializeFreetype()))+ ABORT("Failed to initialize FreeType library.");+ if (!(guard.font = (+ #ifndef MSDFGEN_DISABLE_VARIABLE_FONTS+ inputType == VAR_FONT ? loadVarFont(guard.ft, input) :+ #endif+ loadFont(guard.ft, input)+ )))+ ABORT("Failed to load font file.");+ if (unicode)+ getGlyphIndex(glyphIndex, guard.font, unicode);+ if (!loadGlyph(shape, guard.font, glyphIndex, fontCoordinateScaling, &glyphAdvance))+ ABORT("Failed to load glyph from font file.");+ if (!fontCoordinateScalingSpecified && (!autoFrame || scaleSpecified || rangeMode == RANGE_UNIT || mode == METRICS || printMetrics || shapeExport || svgExport)) {+ fputs(+ "Warning: Using legacy font coordinate conversion for compatibility reasons.\n"+ " The implicit scaling behavior will likely change in a future version resulting in different output.\n"+ " To silence this warning, use one of the following options:\n"+ " -noemnormalize to switch to the correct native font coordinates,\n"+ " -emnormalize to switch to coordinates normalized to 1 em, or\n"+ " -legacyfontscaling to keep current behavior and make sure it will not change.\n", stderr);+ }+ break;+ }+ #endif+ case DESCRIPTION_ARG: {+ if (!readShapeDescription(input, shape, &skipColoring))+ ABORT("Parse error in shape description.");+ break;+ }+ case DESCRIPTION_STDIN: {+ if (!readShapeDescription(stdin, shape, &skipColoring))+ ABORT("Parse error in shape description.");+ break;+ }+ case DESCRIPTION_FILE: {+ FILE *file = fopen(input, "r");+ if (!file)+ ABORT("Failed to load shape description file.");+ bool readSuccessful = readShapeDescription(file, shape, &skipColoring);+ fclose(file);+ if (!readSuccessful)+ ABORT("Parse error in shape description.");+ break;+ }+ default:;+ }++ // Validate and normalize shape+ if (!shape.validate())+ ABORT("The geometry of the loaded shape is invalid.");+ switch (geometryPreproc) {+ case NO_PREPROCESS:+ break;+ case WINDING_PREPROCESS:+ shape.orientContours();+ break;+ case FULL_PREPROCESS:+ #ifdef MSDFGEN_USE_SKIA+ if (!resolveShapeGeometry(shape))+ fputs("Shape geometry preprocessing failed, skipping.\n", stderr);+ else if (skipColoring) {+ skipColoring = false;+ fputs("Note: Input shape coloring won't be preserved due to geometry preprocessing.\n", stderr);+ }+ #else+ ABORT("Shape geometry preprocessing (-preprocess) is not available in this version because the Skia library is not present.");+ #endif+ break;+ }+ shape.normalize();+ if (yFlip)+ shape.inverseYAxis = !shape.inverseYAxis;++ double avgScale = .5*(scale.x+scale.y);+ Shape::Bounds bounds = { };+ if (autoFrame || mode == METRICS || printMetrics || winding == GUESS || svgExport)+ bounds = shape.getBounds();++ if (winding == GUESS) {+ // Get sign of signed distance outside bounds+ Point2 p(bounds.l-(bounds.r-bounds.l)-1, bounds.b-(bounds.t-bounds.b)-1);+ double distance = SimpleTrueShapeDistanceFinder::oneShotDistance(shape, p);+ winding = distance <= 0 ? KEEP : REVERSE;+ }+ if (winding == REVERSE) {+ for (std::vector<Contour>::iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)+ contour->reverse();+ }++ if (outputDistanceShift) {+ Range &rangeRef = rangeMode == RANGE_PX ? pxRange : range;+ double rangeShift = -outputDistanceShift*(rangeRef.upper-rangeRef.lower);+ rangeRef.lower += rangeShift;+ rangeRef.upper += rangeShift;+ }++ // Auto-frame+ if (autoFrame) {+ double l = bounds.l, b = bounds.b, r = bounds.r, t = bounds.t;+ Vector2 frame(width, height);+ if (!scaleSpecified) {+ if (rangeMode == RANGE_UNIT)+ l += range.lower, b += range.lower, r -= range.lower, t -= range.lower;+ else+ frame += 2*pxRange.lower;+ }+ if (l >= r || b >= t)+ l = 0, b = 0, r = 1, t = 1;+ if (frame.x <= 0 || frame.y <= 0)+ ABORT("Cannot fit the specified pixel range.");+ Vector2 dims(r-l, t-b);+ if (scaleSpecified)+ translate = .5*(frame/scale-dims)-Vector2(l, b);+ else {+ if (dims.x*frame.y < dims.y*frame.x) {+ translate.set(.5*(frame.x/frame.y*dims.y-dims.x)-l, -b);+ scale = avgScale = frame.y/dims.y;+ } else {+ translate.set(-l, .5*(frame.y/frame.x*dims.x-dims.y)-b);+ scale = avgScale = frame.x/dims.x;+ }+ }+ if (rangeMode == RANGE_PX && !scaleSpecified)+ translate -= pxRange.lower/scale;+ }++ if (rangeMode == RANGE_PX)+ range = pxRange/min(scale.x, scale.y);++ // Print metrics+ if (mode == METRICS || printMetrics) {+ FILE *out = stdout;+ if (mode == METRICS && outputSpecified)+ out = fopen(output, "w");+ if (!out)+ ABORT("Failed to write output file.");+ switch (shape.getYAxisOrientation()) {+ case Y_UPWARD:+ fprintf(out, "Y-axis upward\n");+ break;+ case Y_DOWNWARD:+ fprintf(out, "Y-axis downward\n");+ break;+ }+ if (svgViewBox.l < svgViewBox.r && svgViewBox.b < svgViewBox.t)+ fprintf(out, "view box = %.17g, %.17g, %.17g, %.17g\n", svgViewBox.l, svgViewBox.b, svgViewBox.r, svgViewBox.t);+ if (bounds.l < bounds.r && bounds.b < bounds.t)+ fprintf(out, "bounds = %.17g, %.17g, %.17g, %.17g\n", bounds.l, bounds.b, bounds.r, bounds.t);+ if (glyphAdvance != 0)+ fprintf(out, "advance = %.17g\n", glyphAdvance);+ if (autoFrame) {+ if (!scaleSpecified)+ fprintf(out, "scale = %.17g\n", avgScale);+ fprintf(out, "translate = %.17g, %.17g\n", translate.x, translate.y);+ }+ if (rangeMode == RANGE_PX)+ fprintf(out, "range %.17g to %.17g\n", range.lower, range.upper);+ if (mode == METRICS && outputSpecified)+ fclose(out);+ }++ // Compute output+ SDFTransformation transformation(Projection(scale, translate), range);+ Bitmap<float, 1> sdf;+ Bitmap<float, 3> msdf;+ Bitmap<float, 4> mtsdf;+ MSDFGeneratorConfig postErrorCorrectionConfig(generatorConfig);+ if (scanlinePass) {+ if (explicitErrorCorrectionMode && generatorConfig.errorCorrection.distanceCheckMode != ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE) {+ const char *fallbackModeName = "unknown";+ switch (generatorConfig.errorCorrection.mode) {+ case ErrorCorrectionConfig::DISABLED: fallbackModeName = "disabled"; break;+ case ErrorCorrectionConfig::INDISCRIMINATE: fallbackModeName = "distance-fast"; break;+ case ErrorCorrectionConfig::EDGE_PRIORITY: fallbackModeName = "auto-fast"; break;+ case ErrorCorrectionConfig::EDGE_ONLY: fallbackModeName = "edge-fast"; break;+ }+ fprintf(stderr, "Selected error correction mode not compatible with scanline pass, falling back to %s.\n", fallbackModeName);+ }+ generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::DISABLED;+ postErrorCorrectionConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;+ }+ switch (mode) {+ case SINGLE: {+ sdf = Bitmap<float, 1>(width, height);+ if (legacyMode)+ generateSDF_legacy(sdf, shape, range, scale, translate);+ else+ generateSDF(sdf, shape, transformation, generatorConfig);+ break;+ }+ case PERPENDICULAR: {+ sdf = Bitmap<float, 1>(width, height);+ if (legacyMode)+ generatePSDF_legacy(sdf, shape, range, scale, translate);+ else+ generatePSDF(sdf, shape, transformation, generatorConfig);+ break;+ }+ case MULTI: {+ if (!skipColoring)+ edgeColoring(shape, angleThreshold, coloringSeed);+ if (edgeAssignment)+ parseColoring(shape, edgeAssignment);+ msdf = Bitmap<float, 3>(width, height);+ if (legacyMode)+ generateMSDF_legacy(msdf, shape, range, scale, translate, generatorConfig.errorCorrection);+ else+ generateMSDF(msdf, shape, transformation, generatorConfig);+ break;+ }+ case MULTI_AND_TRUE: {+ if (!skipColoring)+ edgeColoring(shape, angleThreshold, coloringSeed);+ if (edgeAssignment)+ parseColoring(shape, edgeAssignment);+ mtsdf = Bitmap<float, 4>(width, height);+ if (legacyMode)+ generateMTSDF_legacy(mtsdf, shape, range, scale, translate, generatorConfig.errorCorrection);+ else+ generateMTSDF(mtsdf, shape, transformation, generatorConfig);+ break;+ }+ default:;+ }++ if (scanlinePass) {+ float sdfZeroValue = range.lower != range.upper ? float(range.lower/(range.lower-range.upper)) : .5f;+ switch (mode) {+ case SINGLE:+ case PERPENDICULAR:+ distanceSignCorrection(sdf, shape, transformation, sdfZeroValue, fillRule);+ break;+ case MULTI:+ distanceSignCorrection(msdf, shape, transformation, sdfZeroValue, fillRule);+ msdfErrorCorrection(msdf, shape, transformation, postErrorCorrectionConfig);+ break;+ case MULTI_AND_TRUE:+ distanceSignCorrection(mtsdf, shape, transformation, sdfZeroValue, fillRule);+ msdfErrorCorrection(mtsdf, shape, transformation, postErrorCorrectionConfig);+ break;+ default:;+ }+ }++ // Save output+ if (shapeExport) {+ if (FILE *file = fopen(shapeExport, "w")) {+ writeShapeDescription(file, shape);+ fclose(file);+ } else+ fputs("Failed to write shape export file.\n", stderr);+ }+ if (svgExport) {+ if (!saveSvgShape(shape, bounds, svgExport))+ fputs("Failed to write shape SVG file.\n", stderr);+ }+ const char *error = NULL;+ switch (mode) {+ case SINGLE:+ case PERPENDICULAR:+ if ((error = writeOutput<1>(sdf, output, format))) {+ fprintf(stderr, "%s\n", error);+ return 1;+ }+ if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))+ simulate8bit(sdf);+ if (estimateError) {+ double sdfError = estimateSDFError(sdf, shape, transformation, SDF_ERROR_ESTIMATE_PRECISION, fillRule);+ printf("SDF error ~ %e\n", sdfError);+ }+ if (testRenderMulti) {+ Bitmap<float, 3> render(testWidthM, testHeightM);+ renderSDF(render, sdf, avgScale*range);+ if (!cmpExtension(testRenderMulti, "." DEFAULT_IMAGE_EXTENSION))+ fputs("Warning: -testrendermulti specified with an extension other than ." DEFAULT_IMAGE_EXTENSION " but will be saved in that format anyway.\n", stderr);+ if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRenderMulti))+ fputs("Failed to write test render file.\n", stderr);+ }+ if (testRender) {+ Bitmap<float, 1> render(testWidth, testHeight);+ renderSDF(render, sdf, avgScale*range);+ if (!cmpExtension(testRender, "." DEFAULT_IMAGE_EXTENSION))+ fputs("Warning: -testrender specified with an extension other than ." DEFAULT_IMAGE_EXTENSION " but will be saved in that format anyway.\n", stderr);+ if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRender))+ fputs("Failed to write test render file.\n", stderr);+ }+ break;+ case MULTI:+ if ((error = writeOutput<3>(msdf, output, format))) {+ fprintf(stderr, "%s\n", error);+ return 1;+ }+ if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))+ simulate8bit(msdf);+ if (estimateError) {+ double sdfError = estimateSDFError(msdf, shape, transformation, SDF_ERROR_ESTIMATE_PRECISION, fillRule);+ printf("SDF error ~ %e\n", sdfError);+ }+ if (testRenderMulti) {+ Bitmap<float, 3> render(testWidthM, testHeightM);+ renderSDF(render, msdf, avgScale*range);+ if (!cmpExtension(testRenderMulti, "." DEFAULT_IMAGE_EXTENSION))+ fputs("Warning: -testrendermulti specified with an extension other than ." DEFAULT_IMAGE_EXTENSION " but will be saved in that format anyway.\n", stderr);+ if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRenderMulti))+ fputs("Failed to write test render file.\n", stderr);+ }+ if (testRender) {+ Bitmap<float, 1> render(testWidth, testHeight);+ renderSDF(render, msdf, avgScale*range);+ if (!cmpExtension(testRender, "." DEFAULT_IMAGE_EXTENSION))+ fputs("Warning: -testrender specified with an extension other than ." DEFAULT_IMAGE_EXTENSION " but will be saved in that format anyway.\n", stderr);+ if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRender))+ fputs("Failed to write test render file.\n", stderr);+ }+ break;+ case MULTI_AND_TRUE:+ if ((error = writeOutput<4>(mtsdf, output, format))) {+ fprintf(stderr, "%s\n", error);+ return 1;+ }+ if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))+ simulate8bit(mtsdf);+ if (estimateError) {+ double sdfError = estimateSDFError(mtsdf, shape, transformation, SDF_ERROR_ESTIMATE_PRECISION, fillRule);+ printf("SDF error ~ %e\n", sdfError);+ }+ if (testRenderMulti) {+ Bitmap<float, 4> render(testWidthM, testHeightM);+ renderSDF(render, mtsdf, avgScale*range);+ if (!cmpExtension(testRenderMulti, "." DEFAULT_IMAGE_EXTENSION))+ fputs("Warning: -testrendermulti specified with an extension other than ." DEFAULT_IMAGE_EXTENSION " but will be saved in that format anyway.\n", stderr);+ if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRenderMulti))+ fputs("Failed to write test render file.\n", stderr);+ }+ if (testRender) {+ Bitmap<float, 1> render(testWidth, testHeight);+ renderSDF(render, mtsdf, avgScale*range);+ if (!cmpExtension(testRender, "." DEFAULT_IMAGE_EXTENSION))+ fputs("Warning: -testrender specified with an extension other than ." DEFAULT_IMAGE_EXTENSION " but will be saved in that format anyway.\n", stderr);+ if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRender))+ fputs("Failed to write test render file.\n", stderr);+ }+ break;+ default:;+ }++ return 0;+}++#endifdiff --git a/third_party/msdfgen/msdfgen-ext.h b/third_party/msdfgen/msdfgen-ext.hnew file mode 100644index 000000000..2a1647ff5--- /dev/null+++ b/third_party/msdfgen/msdfgen-ext.h@@ -0,0 +1,27 @@++#pragma once++/*+ * MULTI-CHANNEL SIGNED DISTANCE FIELD GENERATOR+ * ---------------------------------------------+ * A utility by Viktor Chlumsky, (c) 2014 - 2025+ *+ * The extension module provides ways to easily load input and save output using popular formats.+ *+ * Third party dependencies in extension module:+ * - Skia by Google+ * (to resolve self-intersecting paths)+ * - FreeType 2+ * (to load input font files)+ * - TinyXML 2 by Lee Thomason+ * (to aid in parsing input SVG files)+ * - libpng by the PNG Development Group+ * - or LodePNG by Lode Vandevenne+ * (to save output PNG images)+ *+ */++#include "ext/resolve-shape-geometry.h"+#include "ext/save-png.h"+#include "ext/import-svg.h"+#include "ext/import-font.h"diff --git a/third_party/msdfgen/msdfgen.h b/third_party/msdfgen/msdfgen.hnew file mode 100644index 000000000..bf0ae2bad--- /dev/null+++ b/third_party/msdfgen/msdfgen.h@@ -0,0 +1,78 @@++#pragma once++/*+ * MULTI-CHANNEL SIGNED DISTANCE FIELD GENERATOR+ * ---------------------------------------------+ * A utility by Viktor Chlumsky, (c) 2014 - 2025+ *+ * The technique used to generate multi-channel distance fields in this code+ * has been developed by Viktor Chlumsky in 2014 for his master's thesis,+ * "Shape Decomposition for Multi-Channel Distance Fields". It provides improved+ * quality of sharp corners in glyphs and other 2D shapes compared to monochrome+ * distance fields. To reconstruct an image of the shape, apply the median of three+ * operation on the triplet of sampled signed distance values.+ *+ */++#include "core/base.h"+#include "core/arithmetics.hpp"+#include "core/Vector2.hpp"+#include "core/Range.hpp"+#include "core/Projection.h"+#include "core/DistanceMapping.h"+#include "core/SDFTransformation.h"+#include "core/Scanline.h"+#include "core/Shape.h"+#include "core/BitmapRef.hpp"+#include "core/Bitmap.h"+#include "core/bitmap-interpolation.hpp"+#include "core/pixel-conversion.hpp"+#include "core/edge-coloring.h"+#include "core/generator-config.h"+#include "core/msdf-error-correction.h"+#include "core/render-sdf.h"+#include "core/rasterization.h"+#include "core/sdf-error-estimation.h"+#include "core/save-bmp.h"+#include "core/save-tiff.h"+#include "core/save-rgba.h"+#include "core/save-fl32.h"+#include "core/shape-description.h"+#include "core/export-svg.h"++namespace msdfgen {++/// Generates a conventional single-channel signed distance field.+void generateSDF(const BitmapSection<float, 1> &output, const Shape &shape, const SDFTransformation &transformation, const GeneratorConfig &config = GeneratorConfig());++/// Generates a single-channel signed perpendicular distance field.+void generatePSDF(const BitmapSection<float, 1> &output, const Shape &shape, const SDFTransformation &transformation, const GeneratorConfig &config = GeneratorConfig());++/// Generates a multi-channel signed distance field. Edge colors must be assigned first! (See edgeColoringSimple)+void generateMSDF(const BitmapSection<float, 3> &output, const Shape &shape, const SDFTransformation &transformation, const MSDFGeneratorConfig &config = MSDFGeneratorConfig());++/// Generates a multi-channel signed distance field with true distance in the alpha channel. Edge colors must be assigned first.+void generateMTSDF(const BitmapSection<float, 4> &output, const Shape &shape, const SDFTransformation &transformation, const MSDFGeneratorConfig &config = MSDFGeneratorConfig());++// Old version of the function API's kept for backwards compatibility+void generateSDF(const BitmapSection<float, 1> &output, const Shape &shape, const Projection &projection, Range range, const GeneratorConfig &config = GeneratorConfig());+void generatePSDF(const BitmapSection<float, 1> &output, const Shape &shape, const Projection &projection, Range range, const GeneratorConfig &config = GeneratorConfig());+void generatePseudoSDF(const BitmapSection<float, 1> &output, const Shape &shape, const Projection &projection, Range range, const GeneratorConfig &config = GeneratorConfig());+void generateMSDF(const BitmapSection<float, 3> &output, const Shape &shape, const Projection &projection, Range range, const MSDFGeneratorConfig &config = MSDFGeneratorConfig());+void generateMTSDF(const BitmapSection<float, 4> &output, const Shape &shape, const Projection &projection, Range range, const MSDFGeneratorConfig &config = MSDFGeneratorConfig());++void generateSDF(const BitmapSection<float, 1> &output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate, bool overlapSupport = true);+void generatePSDF(const BitmapSection<float, 1> &output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate, bool overlapSupport = true);+void generatePseudoSDF(const BitmapSection<float, 1> &output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate, bool overlapSupport = true);+void generateMSDF(const BitmapSection<float, 3> &output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate, const ErrorCorrectionConfig &errorCorrectionConfig = ErrorCorrectionConfig(), bool overlapSupport = true);+void generateMTSDF(const BitmapSection<float, 4> &output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate, const ErrorCorrectionConfig &errorCorrectionConfig = ErrorCorrectionConfig(), bool overlapSupport = true);++// Original simpler versions of the previous functions, which work well under normal circumstances, but cannot deal with overlapping contours.+void generateSDF_legacy(BitmapSection<float, 1> output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate);+void generatePSDF_legacy(BitmapSection<float, 1> output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate);+void generatePseudoSDF_legacy(BitmapSection<float, 1> output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate);+void generateMSDF_legacy(BitmapSection<float, 3> output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate, ErrorCorrectionConfig errorCorrectionConfig = ErrorCorrectionConfig());+void generateMTSDF_legacy(BitmapSection<float, 4> output, const Shape &shape, Range range, const Vector2 &scale, const Vector2 &translate, ErrorCorrectionConfig errorCorrectionConfig = ErrorCorrectionConfig());++}diff --git a/third_party/msdfgen/msdfgen.rc b/third_party/msdfgen/msdfgen.rcnew file mode 100644index 000000000..b8bd78198Binary files /dev/null and b/third_party/msdfgen/msdfgen.rc differdiff --git a/third_party/msdfgen/resource.h b/third_party/msdfgen/resource.hnew file mode 100644index 000000000..3c5a0b0e1Binary files /dev/null and b/third_party/msdfgen/resource.h differdiff --git a/third_party/msdfgen/vcpkg.json b/third_party/msdfgen/vcpkg.jsonnew file mode 100644index 000000000..d75de2aba--- /dev/null+++ b/third_party/msdfgen/vcpkg.json@@ -0,0 +1,38 @@+{+ "$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/master/docs/vcpkg.schema.json",+ "name": "msdfgen",+ "version": "1.13.0",+ "default-features": [+ "extensions",+ "geometry-preprocessing",+ "standalone"+ ],+ "features": {+ "openmp": {+ "description": "Parallelization of the core algorithm via the OpenMP framework"+ },+ "extensions": {+ "description": "Extended functionality that depends on external libraries - loading fonts and SVG files, generating PNG images",+ "dependencies": [+ "freetype",+ "tinyxml2",+ "libpng"+ ]+ },+ "geometry-preprocessing": {+ "description": "Preprocessing of non-compliant vector geometry via the Skia library",+ "dependencies": [ {+ "name": "msdfgen",+ "default-features": false,+ "features": [ "extensions" ]+ }, {+ "name": "skia",+ "default-features": false,+ "version>=": "0.36.0#3"+ } ]+ },+ "standalone": {+ "description": "Build a command line utility that wraps the library's functionality"+ }+ }+}