imgui_freetype.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  1. // dear imgui: FreeType font builder (used as a replacement for the stb_truetype builder)
  2. // (code)
  3. // Get the latest version at https://github.com/ocornut/imgui/tree/master/misc/freetype
  4. // Original code by @vuhdo (Aleksei Skriabin). Improvements by @mikesart. Maintained since 2019 by @ocornut.
  5. // CHANGELOG
  6. // (minor and older changes stripped away, please see git history for details)
  7. // 2023/11/13: added support for ImFontConfig::RasterizationDensity field for scaling render density without scaling metrics.
  8. // 2023/08/01: added support for SVG fonts, enable by using '#define IMGUI_ENABLE_FREETYPE_LUNASVG' (#6591)
  9. // 2023/01/04: fixed a packing issue which in some occurrences would prevent large amount of glyphs from being packed correctly.
  10. // 2021/08/23: fixed crash when FT_Render_Glyph() fails to render a glyph and returns NULL.
  11. // 2021/03/05: added ImGuiFreeTypeBuilderFlags_Bitmap to load bitmap glyphs.
  12. // 2021/03/02: set 'atlas->TexPixelsUseColors = true' to help some backends with deciding of a preferred texture format.
  13. // 2021/01/28: added support for color-layered glyphs via ImGuiFreeTypeBuilderFlags_LoadColor (require Freetype 2.10+).
  14. // 2021/01/26: simplified integration by using '#define IMGUI_ENABLE_FREETYPE'. renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API. removed ImGuiFreeType::BuildFontAtlas().
  15. // 2020/06/04: fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails.
  16. // 2019/02/09: added RasterizerFlags::Monochrome flag to disable font anti-aliasing (combine with ::MonoHinting for best results!)
  17. // 2019/01/15: added support for imgui allocators + added FreeType only override function SetAllocatorFunctions().
  18. // 2019/01/10: re-factored to match big update in STB builder. fixed texture height waste. fixed redundant glyphs when merging. support for glyph padding.
  19. // 2018/06/08: added support for ImFontConfig::GlyphMinAdvanceX, GlyphMaxAdvanceX.
  20. // 2018/02/04: moved to main imgui repository (away from http://www.github.com/ocornut/imgui_club)
  21. // 2018/01/22: fix for addition of ImFontAtlas::TexUvscale member.
  22. // 2017/10/22: minor inconsequential change to match change in master (removed an unnecessary statement).
  23. // 2017/09/26: fixes for imgui internal changes.
  24. // 2017/08/26: cleanup, optimizations, support for ImFontConfig::RasterizerFlags, ImFontConfig::RasterizerMultiply.
  25. // 2017/08/16: imported from https://github.com/Vuhdo/imgui_freetype into http://www.github.com/ocornut/imgui_club, updated for latest changes in ImFontAtlas, minor tweaks.
  26. // About Gamma Correct Blending:
  27. // - FreeType assumes blending in linear space rather than gamma space.
  28. // - See https://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#FT_Render_Glyph
  29. // - For correct results you need to be using sRGB and convert to linear space in the pixel shader output.
  30. // - The default dear imgui styles will be impacted by this change (alpha values will need tweaking).
  31. // FIXME: cfg.OversampleH, OversampleV are not supported (but perhaps not so necessary with this rasterizer).
  32. #include "imgui.h"
  33. #ifndef IMGUI_DISABLE
  34. #include "imgui_freetype.h"
  35. #include "imgui_internal.h" // ImMin,ImMax,ImFontAtlasBuild*,
  36. #include <stdint.h>
  37. #include <ft2build.h>
  38. #include FT_FREETYPE_H // <freetype/freetype.h>
  39. #include FT_MODULE_H // <freetype/ftmodapi.h>
  40. #include FT_GLYPH_H // <freetype/ftglyph.h>
  41. #include FT_SYNTHESIS_H // <freetype/ftsynth.h>
  42. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  43. #include FT_OTSVG_H // <freetype/otsvg.h>
  44. #include FT_BBOX_H // <freetype/ftbbox.h>
  45. #include <lunasvg.h>
  46. #if !((FREETYPE_MAJOR >= 2) && (FREETYPE_MINOR >= 12))
  47. #error IMGUI_ENABLE_FREETYPE_LUNASVG requires FreeType version >= 2.12
  48. #endif
  49. #endif
  50. #ifdef _MSC_VER
  51. #pragma warning (push)
  52. #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
  53. #pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
  54. #endif
  55. #ifdef __GNUC__
  56. #pragma GCC diagnostic push
  57. #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
  58. #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
  59. #ifndef __clang__
  60. #pragma GCC diagnostic ignored "-Wsubobject-linkage" // warning: 'xxxx' has a field 'xxxx' whose type uses the anonymous namespace
  61. #endif
  62. #endif
  63. //-------------------------------------------------------------------------
  64. // Data
  65. //-------------------------------------------------------------------------
  66. // Default memory allocators
  67. static void* ImGuiFreeTypeDefaultAllocFunc(size_t size, void* user_data) { IM_UNUSED(user_data); return IM_ALLOC(size); }
  68. static void ImGuiFreeTypeDefaultFreeFunc(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_FREE(ptr); }
  69. // Current memory allocators
  70. static void* (*GImGuiFreeTypeAllocFunc)(size_t size, void* user_data) = ImGuiFreeTypeDefaultAllocFunc;
  71. static void (*GImGuiFreeTypeFreeFunc)(void* ptr, void* user_data) = ImGuiFreeTypeDefaultFreeFunc;
  72. static void* GImGuiFreeTypeAllocatorUserData = nullptr;
  73. // Lunasvg support
  74. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  75. static FT_Error ImGuiLunasvgPortInit(FT_Pointer* state);
  76. static void ImGuiLunasvgPortFree(FT_Pointer* state);
  77. static FT_Error ImGuiLunasvgPortRender(FT_GlyphSlot slot, FT_Pointer* _state);
  78. static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_Pointer* _state);
  79. #endif
  80. //-------------------------------------------------------------------------
  81. // Code
  82. //-------------------------------------------------------------------------
  83. namespace
  84. {
  85. // Glyph metrics:
  86. // --------------
  87. //
  88. // xmin xmax
  89. // | |
  90. // |<-------- width -------->|
  91. // | |
  92. // | +-------------------------+----------------- ymax
  93. // | | ggggggggg ggggg | ^ ^
  94. // | | g:::::::::ggg::::g | | |
  95. // | | g:::::::::::::::::g | | |
  96. // | | g::::::ggggg::::::gg | | |
  97. // | | g:::::g g:::::g | | |
  98. // offsetX -|-------->| g:::::g g:::::g | offsetY |
  99. // | | g:::::g g:::::g | | |
  100. // | | g::::::g g:::::g | | |
  101. // | | g:::::::ggggg:::::g | | |
  102. // | | g::::::::::::::::g | | height
  103. // | | gg::::::::::::::g | | |
  104. // baseline ---*---------|---- gggggggg::::::g-----*-------- |
  105. // / | | g:::::g | |
  106. // origin | | gggggg g:::::g | |
  107. // | | g:::::gg gg:::::g | |
  108. // | | g::::::ggg:::::::g | |
  109. // | | gg:::::::::::::g | |
  110. // | | ggg::::::ggg | |
  111. // | | gggggg | v
  112. // | +-------------------------+----------------- ymin
  113. // | |
  114. // |------------- advanceX ----------->|
  115. // A structure that describe a glyph.
  116. struct GlyphInfo
  117. {
  118. int Width; // Glyph's width in pixels.
  119. int Height; // Glyph's height in pixels.
  120. FT_Int OffsetX; // The distance from the origin ("pen position") to the left of the glyph.
  121. FT_Int OffsetY; // The distance from the origin to the top of the glyph. This is usually a value < 0.
  122. float AdvanceX; // The distance from the origin to the origin of the next glyph. This is usually a value > 0.
  123. bool IsColored; // The glyph is colored
  124. };
  125. // Font parameters and metrics.
  126. struct FontInfo
  127. {
  128. uint32_t PixelHeight; // Size this font was generated with.
  129. float Ascender; // The pixel extents above the baseline in pixels (typically positive).
  130. float Descender; // The extents below the baseline in pixels (typically negative).
  131. float LineSpacing; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate.
  132. float LineGap; // The spacing in pixels between one row's descent and the next row's ascent.
  133. float MaxAdvanceWidth; // This field gives the maximum horizontal cursor advance for all glyphs in the font.
  134. };
  135. // FreeType glyph rasterizer.
  136. // NB: No ctor/dtor, explicitly call Init()/Shutdown()
  137. struct FreeTypeFont
  138. {
  139. bool InitFont(FT_Library ft_library, const ImFontConfig& cfg, unsigned int extra_user_flags); // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime.
  140. void CloseFont();
  141. void SetPixelHeight(int pixel_height); // Change font pixel size. All following calls to RasterizeGlyph() will use this size
  142. const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint);
  143. const FT_Bitmap* RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info);
  144. void BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table = nullptr);
  145. ~FreeTypeFont() { CloseFont(); }
  146. // [Internals]
  147. FontInfo Info; // Font descriptor of the current font.
  148. FT_Face Face;
  149. unsigned int UserFlags; // = ImFontConfig::RasterizerFlags
  150. FT_Int32 LoadFlags;
  151. FT_Render_Mode RenderMode;
  152. float RasterizationDensity;
  153. float InvRasterizationDensity;
  154. };
  155. // From SDL_ttf: Handy routines for converting from fixed point
  156. #define FT_CEIL(X) (((X + 63) & -64) / 64)
  157. bool FreeTypeFont::InitFont(FT_Library ft_library, const ImFontConfig& cfg, unsigned int extra_font_builder_flags)
  158. {
  159. FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)cfg.FontData, (uint32_t)cfg.FontDataSize, (uint32_t)cfg.FontNo, &Face);
  160. if (error != 0)
  161. return false;
  162. error = FT_Select_Charmap(Face, FT_ENCODING_UNICODE);
  163. if (error != 0)
  164. return false;
  165. // Convert to FreeType flags (NB: Bold and Oblique are processed separately)
  166. UserFlags = cfg.FontBuilderFlags | extra_font_builder_flags;
  167. LoadFlags = 0;
  168. if ((UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) == 0)
  169. LoadFlags |= FT_LOAD_NO_BITMAP;
  170. if (UserFlags & ImGuiFreeTypeBuilderFlags_NoHinting)
  171. LoadFlags |= FT_LOAD_NO_HINTING;
  172. if (UserFlags & ImGuiFreeTypeBuilderFlags_NoAutoHint)
  173. LoadFlags |= FT_LOAD_NO_AUTOHINT;
  174. if (UserFlags & ImGuiFreeTypeBuilderFlags_ForceAutoHint)
  175. LoadFlags |= FT_LOAD_FORCE_AUTOHINT;
  176. if (UserFlags & ImGuiFreeTypeBuilderFlags_LightHinting)
  177. LoadFlags |= FT_LOAD_TARGET_LIGHT;
  178. else if (UserFlags & ImGuiFreeTypeBuilderFlags_MonoHinting)
  179. LoadFlags |= FT_LOAD_TARGET_MONO;
  180. else
  181. LoadFlags |= FT_LOAD_TARGET_NORMAL;
  182. if (UserFlags & ImGuiFreeTypeBuilderFlags_Monochrome)
  183. RenderMode = FT_RENDER_MODE_MONO;
  184. else
  185. RenderMode = FT_RENDER_MODE_NORMAL;
  186. if (UserFlags & ImGuiFreeTypeBuilderFlags_LoadColor)
  187. LoadFlags |= FT_LOAD_COLOR;
  188. RasterizationDensity = cfg.RasterizerDensity;
  189. InvRasterizationDensity = 1.0f / RasterizationDensity;
  190. memset(&Info, 0, sizeof(Info));
  191. SetPixelHeight((uint32_t)cfg.SizePixels);
  192. return true;
  193. }
  194. void FreeTypeFont::CloseFont()
  195. {
  196. if (Face)
  197. {
  198. FT_Done_Face(Face);
  199. Face = nullptr;
  200. }
  201. }
  202. void FreeTypeFont::SetPixelHeight(int pixel_height)
  203. {
  204. // Vuhdo: I'm not sure how to deal with font sizes properly. As far as I understand, currently ImGui assumes that the 'pixel_height'
  205. // is a maximum height of an any given glyph, i.e. it's the sum of font's ascender and descender. Seems strange to me.
  206. // NB: FT_Set_Pixel_Sizes() doesn't seem to get us the same result.
  207. FT_Size_RequestRec req;
  208. req.type = (UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM;
  209. req.width = 0;
  210. req.height = (uint32_t)(pixel_height * 64 * RasterizationDensity);
  211. req.horiResolution = 0;
  212. req.vertResolution = 0;
  213. FT_Request_Size(Face, &req);
  214. // Update font info
  215. FT_Size_Metrics metrics = Face->size->metrics;
  216. Info.PixelHeight = (uint32_t)(pixel_height * InvRasterizationDensity);
  217. Info.Ascender = (float)FT_CEIL(metrics.ascender) * InvRasterizationDensity;
  218. Info.Descender = (float)FT_CEIL(metrics.descender) * InvRasterizationDensity;
  219. Info.LineSpacing = (float)FT_CEIL(metrics.height) * InvRasterizationDensity;
  220. Info.LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender) * InvRasterizationDensity;
  221. Info.MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * InvRasterizationDensity;
  222. }
  223. const FT_Glyph_Metrics* FreeTypeFont::LoadGlyph(uint32_t codepoint)
  224. {
  225. uint32_t glyph_index = FT_Get_Char_Index(Face, codepoint);
  226. if (glyph_index == 0)
  227. return nullptr;
  228. // If this crash for you: FreeType 2.11.0 has a crash bug on some bitmap/colored fonts.
  229. // - https://gitlab.freedesktop.org/freetype/freetype/-/issues/1076
  230. // - https://github.com/ocornut/imgui/issues/4567
  231. // - https://github.com/ocornut/imgui/issues/4566
  232. // You can use FreeType 2.10, or the patched version of 2.11.0 in VcPkg, or probably any upcoming FreeType version.
  233. FT_Error error = FT_Load_Glyph(Face, glyph_index, LoadFlags);
  234. if (error)
  235. return nullptr;
  236. // Need an outline for this to work
  237. FT_GlyphSlot slot = Face->glyph;
  238. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  239. IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP || slot->format == FT_GLYPH_FORMAT_SVG);
  240. #else
  241. #if ((FREETYPE_MAJOR >= 2) && (FREETYPE_MINOR >= 12))
  242. IM_ASSERT(slot->format != FT_GLYPH_FORMAT_SVG && "The font contains SVG glyphs, you'll need to enable IMGUI_ENABLE_FREETYPE_LUNASVG in imconfig.h and install required libraries in order to use this font");
  243. #endif
  244. IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP);
  245. #endif // IMGUI_ENABLE_FREETYPE_LUNASVG
  246. // Apply convenience transform (this is not picking from real "Bold"/"Italic" fonts! Merely applying FreeType helper transform. Oblique == Slanting)
  247. if (UserFlags & ImGuiFreeTypeBuilderFlags_Bold)
  248. FT_GlyphSlot_Embolden(slot);
  249. if (UserFlags & ImGuiFreeTypeBuilderFlags_Oblique)
  250. {
  251. FT_GlyphSlot_Oblique(slot);
  252. //FT_BBox bbox;
  253. //FT_Outline_Get_BBox(&slot->outline, &bbox);
  254. //slot->metrics.width = bbox.xMax - bbox.xMin;
  255. //slot->metrics.height = bbox.yMax - bbox.yMin;
  256. }
  257. return &slot->metrics;
  258. }
  259. const FT_Bitmap* FreeTypeFont::RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info)
  260. {
  261. FT_GlyphSlot slot = Face->glyph;
  262. FT_Error error = FT_Render_Glyph(slot, RenderMode);
  263. if (error != 0)
  264. return nullptr;
  265. FT_Bitmap* ft_bitmap = &Face->glyph->bitmap;
  266. out_glyph_info->Width = (int)ft_bitmap->width;
  267. out_glyph_info->Height = (int)ft_bitmap->rows;
  268. out_glyph_info->OffsetX = Face->glyph->bitmap_left;
  269. out_glyph_info->OffsetY = -Face->glyph->bitmap_top;
  270. out_glyph_info->AdvanceX = (float)FT_CEIL(slot->advance.x);
  271. out_glyph_info->IsColored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA);
  272. return ft_bitmap;
  273. }
  274. void FreeTypeFont::BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table)
  275. {
  276. IM_ASSERT(ft_bitmap != nullptr);
  277. const uint32_t w = ft_bitmap->width;
  278. const uint32_t h = ft_bitmap->rows;
  279. const uint8_t* src = ft_bitmap->buffer;
  280. const uint32_t src_pitch = ft_bitmap->pitch;
  281. switch (ft_bitmap->pixel_mode)
  282. {
  283. case FT_PIXEL_MODE_GRAY: // Grayscale image, 1 byte per pixel.
  284. {
  285. if (multiply_table == nullptr)
  286. {
  287. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  288. for (uint32_t x = 0; x < w; x++)
  289. dst[x] = IM_COL32(255, 255, 255, src[x]);
  290. }
  291. else
  292. {
  293. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  294. for (uint32_t x = 0; x < w; x++)
  295. dst[x] = IM_COL32(255, 255, 255, multiply_table[src[x]]);
  296. }
  297. break;
  298. }
  299. case FT_PIXEL_MODE_MONO: // Monochrome image, 1 bit per pixel. The bits in each byte are ordered from MSB to LSB.
  300. {
  301. uint8_t color0 = multiply_table ? multiply_table[0] : 0;
  302. uint8_t color1 = multiply_table ? multiply_table[255] : 255;
  303. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  304. {
  305. uint8_t bits = 0;
  306. const uint8_t* bits_ptr = src;
  307. for (uint32_t x = 0; x < w; x++, bits <<= 1)
  308. {
  309. if ((x & 7) == 0)
  310. bits = *bits_ptr++;
  311. dst[x] = IM_COL32(255, 255, 255, (bits & 0x80) ? color1 : color0);
  312. }
  313. }
  314. break;
  315. }
  316. case FT_PIXEL_MODE_BGRA:
  317. {
  318. // FIXME: Converting pre-multiplied alpha to straight. Doesn't smell good.
  319. #define DE_MULTIPLY(color, alpha) (ImU32)(255.0f * (float)color / (float)alpha + 0.5f)
  320. if (multiply_table == nullptr)
  321. {
  322. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  323. for (uint32_t x = 0; x < w; x++)
  324. {
  325. uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3];
  326. dst[x] = IM_COL32(DE_MULTIPLY(r, a), DE_MULTIPLY(g, a), DE_MULTIPLY(b, a), a);
  327. }
  328. }
  329. else
  330. {
  331. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  332. {
  333. for (uint32_t x = 0; x < w; x++)
  334. {
  335. uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3];
  336. dst[x] = IM_COL32(multiply_table[DE_MULTIPLY(r, a)], multiply_table[DE_MULTIPLY(g, a)], multiply_table[DE_MULTIPLY(b, a)], multiply_table[a]);
  337. }
  338. }
  339. }
  340. #undef DE_MULTIPLY
  341. break;
  342. }
  343. default:
  344. IM_ASSERT(0 && "FreeTypeFont::BlitGlyph(): Unknown bitmap pixel mode!");
  345. }
  346. }
  347. } // namespace
  348. #ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds)
  349. #ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
  350. #define STBRP_ASSERT(x) do { IM_ASSERT(x); } while (0)
  351. #define STBRP_STATIC
  352. #define STB_RECT_PACK_IMPLEMENTATION
  353. #endif
  354. #ifdef IMGUI_STB_RECT_PACK_FILENAME
  355. #include IMGUI_STB_RECT_PACK_FILENAME
  356. #else
  357. #include "imstb_rectpack.h"
  358. #endif
  359. #endif
  360. struct ImFontBuildSrcGlyphFT
  361. {
  362. GlyphInfo Info;
  363. uint32_t Codepoint;
  364. unsigned int* BitmapData; // Point within one of the dst_tmp_bitmap_buffers[] array
  365. ImFontBuildSrcGlyphFT() { memset((void*)this, 0, sizeof(*this)); }
  366. };
  367. struct ImFontBuildSrcDataFT
  368. {
  369. FreeTypeFont Font;
  370. stbrp_rect* Rects; // Rectangle to pack. We first fill in their size and the packer will give us their position.
  371. const ImWchar* SrcRanges; // Ranges as requested by user (user is allowed to request too much, e.g. 0x0020..0xFFFF)
  372. int DstIndex; // Index into atlas->Fonts[] and dst_tmp_array[]
  373. int GlyphsHighest; // Highest requested codepoint
  374. int GlyphsCount; // Glyph count (excluding missing glyphs and glyphs already set by an earlier source font)
  375. ImBitVector GlyphsSet; // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB)
  376. ImVector<ImFontBuildSrcGlyphFT> GlyphsList;
  377. };
  378. // Temporary data for one destination ImFont* (multiple source fonts can be merged into one destination ImFont)
  379. struct ImFontBuildDstDataFT
  380. {
  381. int SrcCount; // Number of source fonts targeting this destination font.
  382. int GlyphsHighest;
  383. int GlyphsCount;
  384. ImBitVector GlyphsSet; // This is used to resolve collision when multiple sources are merged into a same destination font.
  385. };
  386. bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, unsigned int extra_flags)
  387. {
  388. IM_ASSERT(atlas->ConfigData.Size > 0);
  389. ImFontAtlasBuildInit(atlas);
  390. // Clear atlas
  391. atlas->TexID = 0;
  392. atlas->TexWidth = atlas->TexHeight = 0;
  393. atlas->TexUvScale = ImVec2(0.0f, 0.0f);
  394. atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f);
  395. atlas->ClearTexData();
  396. // Temporary storage for building
  397. bool src_load_color = false;
  398. ImVector<ImFontBuildSrcDataFT> src_tmp_array;
  399. ImVector<ImFontBuildDstDataFT> dst_tmp_array;
  400. src_tmp_array.resize(atlas->ConfigData.Size);
  401. dst_tmp_array.resize(atlas->Fonts.Size);
  402. memset((void*)src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes());
  403. memset((void*)dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes());
  404. // 1. Initialize font loading structure, check font data validity
  405. for (int src_i = 0; src_i < atlas->ConfigData.Size; src_i++)
  406. {
  407. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  408. ImFontConfig& cfg = atlas->ConfigData[src_i];
  409. FreeTypeFont& font_face = src_tmp.Font;
  410. IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == atlas));
  411. // Find index from cfg.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices)
  412. src_tmp.DstIndex = -1;
  413. for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++)
  414. if (cfg.DstFont == atlas->Fonts[output_i])
  415. src_tmp.DstIndex = output_i;
  416. IM_ASSERT(src_tmp.DstIndex != -1); // cfg.DstFont not pointing within atlas->Fonts[] array?
  417. if (src_tmp.DstIndex == -1)
  418. return false;
  419. // Load font
  420. if (!font_face.InitFont(ft_library, cfg, extra_flags))
  421. return false;
  422. // Measure highest codepoints
  423. src_load_color |= (cfg.FontBuilderFlags & ImGuiFreeTypeBuilderFlags_LoadColor) != 0;
  424. ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
  425. src_tmp.SrcRanges = cfg.GlyphRanges ? cfg.GlyphRanges : atlas->GetGlyphRangesDefault();
  426. for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)
  427. {
  428. // Check for valid range. This may also help detect *some* dangling pointers, because a common
  429. // user error is to setup ImFontConfig::GlyphRanges with a pointer to data that isn't persistent.
  430. IM_ASSERT(src_range[0] <= src_range[1]);
  431. src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]);
  432. }
  433. dst_tmp.SrcCount++;
  434. dst_tmp.GlyphsHighest = ImMax(dst_tmp.GlyphsHighest, src_tmp.GlyphsHighest);
  435. }
  436. // 2. For every requested codepoint, check for their presence in the font data, and handle redundancy or overlaps between source fonts to avoid unused glyphs.
  437. int total_glyphs_count = 0;
  438. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  439. {
  440. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  441. ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
  442. src_tmp.GlyphsSet.Create(src_tmp.GlyphsHighest + 1);
  443. if (dst_tmp.GlyphsSet.Storage.empty())
  444. dst_tmp.GlyphsSet.Create(dst_tmp.GlyphsHighest + 1);
  445. for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)
  446. for (int codepoint = src_range[0]; codepoint <= (int)src_range[1]; codepoint++)
  447. {
  448. if (dst_tmp.GlyphsSet.TestBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option (e.g. MergeOverwrite)
  449. continue;
  450. uint32_t glyph_index = FT_Get_Char_Index(src_tmp.Font.Face, codepoint); // It is actually in the font? (FIXME-OPT: We are not storing the glyph_index..)
  451. if (glyph_index == 0)
  452. continue;
  453. // Add to avail set/counters
  454. src_tmp.GlyphsCount++;
  455. dst_tmp.GlyphsCount++;
  456. src_tmp.GlyphsSet.SetBit(codepoint);
  457. dst_tmp.GlyphsSet.SetBit(codepoint);
  458. total_glyphs_count++;
  459. }
  460. }
  461. // 3. Unpack our bit map into a flat list (we now have all the Unicode points that we know are requested _and_ available _and_ not overlapping another)
  462. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  463. {
  464. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  465. src_tmp.GlyphsList.reserve(src_tmp.GlyphsCount);
  466. IM_ASSERT(sizeof(src_tmp.GlyphsSet.Storage.Data[0]) == sizeof(ImU32));
  467. const ImU32* it_begin = src_tmp.GlyphsSet.Storage.begin();
  468. const ImU32* it_end = src_tmp.GlyphsSet.Storage.end();
  469. for (const ImU32* it = it_begin; it < it_end; it++)
  470. if (ImU32 entries_32 = *it)
  471. for (ImU32 bit_n = 0; bit_n < 32; bit_n++)
  472. if (entries_32 & ((ImU32)1 << bit_n))
  473. {
  474. ImFontBuildSrcGlyphFT src_glyph;
  475. src_glyph.Codepoint = (ImWchar)(((it - it_begin) << 5) + bit_n);
  476. //src_glyph.GlyphIndex = 0; // FIXME-OPT: We had this info in the previous step and lost it..
  477. src_tmp.GlyphsList.push_back(src_glyph);
  478. }
  479. src_tmp.GlyphsSet.Clear();
  480. IM_ASSERT(src_tmp.GlyphsList.Size == src_tmp.GlyphsCount);
  481. }
  482. for (int dst_i = 0; dst_i < dst_tmp_array.Size; dst_i++)
  483. dst_tmp_array[dst_i].GlyphsSet.Clear();
  484. dst_tmp_array.clear();
  485. // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0)
  486. // (We technically don't need to zero-clear buf_rects, but let's do it for the sake of sanity)
  487. ImVector<stbrp_rect> buf_rects;
  488. buf_rects.resize(total_glyphs_count);
  489. memset(buf_rects.Data, 0, (size_t)buf_rects.size_in_bytes());
  490. // Allocate temporary rasterization data buffers.
  491. // We could not find a way to retrieve accurate glyph size without rendering them.
  492. // (e.g. slot->metrics->width not always matching bitmap->width, especially considering the Oblique transform)
  493. // We allocate in chunks of 256 KB to not waste too much extra memory ahead. Hopefully users of FreeType won't mind the temporary allocations.
  494. const int BITMAP_BUFFERS_CHUNK_SIZE = 256 * 1024;
  495. int buf_bitmap_current_used_bytes = 0;
  496. ImVector<unsigned char*> buf_bitmap_buffers;
  497. buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE));
  498. // 4. Gather glyphs sizes so we can pack them in our virtual canvas.
  499. // 8. Render/rasterize font characters into the texture
  500. int total_surface = 0;
  501. int buf_rects_out_n = 0;
  502. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  503. {
  504. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  505. ImFontConfig& cfg = atlas->ConfigData[src_i];
  506. if (src_tmp.GlyphsCount == 0)
  507. continue;
  508. src_tmp.Rects = &buf_rects[buf_rects_out_n];
  509. buf_rects_out_n += src_tmp.GlyphsCount;
  510. // Compute multiply table if requested
  511. const bool multiply_enabled = (cfg.RasterizerMultiply != 1.0f);
  512. unsigned char multiply_table[256];
  513. if (multiply_enabled)
  514. ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, cfg.RasterizerMultiply);
  515. // Gather the sizes of all rectangles we will need to pack
  516. const int padding = atlas->TexGlyphPadding;
  517. for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++)
  518. {
  519. ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i];
  520. const FT_Glyph_Metrics* metrics = src_tmp.Font.LoadGlyph(src_glyph.Codepoint);
  521. if (metrics == nullptr)
  522. continue;
  523. // Render glyph into a bitmap (currently held by FreeType)
  524. const FT_Bitmap* ft_bitmap = src_tmp.Font.RenderGlyphAndGetInfo(&src_glyph.Info);
  525. if (ft_bitmap == nullptr)
  526. continue;
  527. // Allocate new temporary chunk if needed
  528. const int bitmap_size_in_bytes = src_glyph.Info.Width * src_glyph.Info.Height * 4;
  529. if (buf_bitmap_current_used_bytes + bitmap_size_in_bytes > BITMAP_BUFFERS_CHUNK_SIZE)
  530. {
  531. buf_bitmap_current_used_bytes = 0;
  532. buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE));
  533. }
  534. IM_ASSERT(buf_bitmap_current_used_bytes + bitmap_size_in_bytes <= BITMAP_BUFFERS_CHUNK_SIZE); // We could probably allocate custom-sized buffer instead.
  535. // Blit rasterized pixels to our temporary buffer and keep a pointer to it.
  536. src_glyph.BitmapData = (unsigned int*)(buf_bitmap_buffers.back() + buf_bitmap_current_used_bytes);
  537. buf_bitmap_current_used_bytes += bitmap_size_in_bytes;
  538. src_tmp.Font.BlitGlyph(ft_bitmap, src_glyph.BitmapData, src_glyph.Info.Width, multiply_enabled ? multiply_table : nullptr);
  539. src_tmp.Rects[glyph_i].w = (stbrp_coord)(src_glyph.Info.Width + padding);
  540. src_tmp.Rects[glyph_i].h = (stbrp_coord)(src_glyph.Info.Height + padding);
  541. total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h;
  542. }
  543. }
  544. // We need a width for the skyline algorithm, any width!
  545. // The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height.
  546. // User can override TexDesiredWidth and TexGlyphPadding if they wish, otherwise we use a simple heuristic to select the width based on expected surface.
  547. const int surface_sqrt = (int)ImSqrt((float)total_surface) + 1;
  548. atlas->TexHeight = 0;
  549. if (atlas->TexDesiredWidth > 0)
  550. atlas->TexWidth = atlas->TexDesiredWidth;
  551. else
  552. atlas->TexWidth = (surface_sqrt >= 4096 * 0.7f) ? 4096 : (surface_sqrt >= 2048 * 0.7f) ? 2048 : (surface_sqrt >= 1024 * 0.7f) ? 1024 : 512;
  553. // 5. Start packing
  554. // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values).
  555. const int TEX_HEIGHT_MAX = 1024 * 32;
  556. const int num_nodes_for_packing_algorithm = atlas->TexWidth - atlas->TexGlyphPadding;
  557. ImVector<stbrp_node> pack_nodes;
  558. pack_nodes.resize(num_nodes_for_packing_algorithm);
  559. stbrp_context pack_context;
  560. stbrp_init_target(&pack_context, atlas->TexWidth - atlas->TexGlyphPadding, TEX_HEIGHT_MAX - atlas->TexGlyphPadding, pack_nodes.Data, pack_nodes.Size);
  561. ImFontAtlasBuildPackCustomRects(atlas, &pack_context);
  562. // 6. Pack each source font. No rendering yet, we are working with rectangles in an infinitely tall texture at this point.
  563. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  564. {
  565. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  566. if (src_tmp.GlyphsCount == 0)
  567. continue;
  568. stbrp_pack_rects(&pack_context, src_tmp.Rects, src_tmp.GlyphsCount);
  569. // Extend texture height and mark missing glyphs as non-packed so we won't render them.
  570. // FIXME: We are not handling packing failure here (would happen if we got off TEX_HEIGHT_MAX or if a single if larger than TexWidth?)
  571. for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
  572. if (src_tmp.Rects[glyph_i].was_packed)
  573. atlas->TexHeight = ImMax(atlas->TexHeight, src_tmp.Rects[glyph_i].y + src_tmp.Rects[glyph_i].h);
  574. }
  575. // 7. Allocate texture
  576. atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight);
  577. atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight);
  578. if (src_load_color)
  579. {
  580. size_t tex_size = (size_t)atlas->TexWidth * atlas->TexHeight * 4;
  581. atlas->TexPixelsRGBA32 = (unsigned int*)IM_ALLOC(tex_size);
  582. memset(atlas->TexPixelsRGBA32, 0, tex_size);
  583. }
  584. else
  585. {
  586. size_t tex_size = (size_t)atlas->TexWidth * atlas->TexHeight * 1;
  587. atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(tex_size);
  588. memset(atlas->TexPixelsAlpha8, 0, tex_size);
  589. }
  590. // 8. Copy rasterized font characters back into the main texture
  591. // 9. Setup ImFont and glyphs for runtime
  592. bool tex_use_colors = false;
  593. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  594. {
  595. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  596. if (src_tmp.GlyphsCount == 0)
  597. continue;
  598. // When merging fonts with MergeMode=true:
  599. // - We can have multiple input fonts writing into a same destination font.
  600. // - dst_font->ConfigData is != from cfg which is our source configuration.
  601. ImFontConfig& cfg = atlas->ConfigData[src_i];
  602. ImFont* dst_font = cfg.DstFont;
  603. const float ascent = src_tmp.Font.Info.Ascender;
  604. const float descent = src_tmp.Font.Info.Descender;
  605. ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent);
  606. const float font_off_x = cfg.GlyphOffset.x;
  607. const float font_off_y = cfg.GlyphOffset.y + IM_ROUND(dst_font->Ascent);
  608. const int padding = atlas->TexGlyphPadding;
  609. for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
  610. {
  611. ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i];
  612. stbrp_rect& pack_rect = src_tmp.Rects[glyph_i];
  613. IM_ASSERT(pack_rect.was_packed);
  614. if (pack_rect.w == 0 && pack_rect.h == 0)
  615. continue;
  616. GlyphInfo& info = src_glyph.Info;
  617. IM_ASSERT(info.Width + padding <= pack_rect.w);
  618. IM_ASSERT(info.Height + padding <= pack_rect.h);
  619. const int tx = pack_rect.x + padding;
  620. const int ty = pack_rect.y + padding;
  621. // Register glyph
  622. float x0 = info.OffsetX * src_tmp.Font.InvRasterizationDensity + font_off_x;
  623. float y0 = info.OffsetY * src_tmp.Font.InvRasterizationDensity + font_off_y;
  624. float x1 = x0 + info.Width * src_tmp.Font.InvRasterizationDensity;
  625. float y1 = y0 + info.Height * src_tmp.Font.InvRasterizationDensity;
  626. float u0 = (tx) / (float)atlas->TexWidth;
  627. float v0 = (ty) / (float)atlas->TexHeight;
  628. float u1 = (tx + info.Width) / (float)atlas->TexWidth;
  629. float v1 = (ty + info.Height) / (float)atlas->TexHeight;
  630. dst_font->AddGlyph(&cfg, (ImWchar)src_glyph.Codepoint, x0, y0, x1, y1, u0, v0, u1, v1, info.AdvanceX * src_tmp.Font.InvRasterizationDensity);
  631. ImFontGlyph* dst_glyph = &dst_font->Glyphs.back();
  632. IM_ASSERT(dst_glyph->Codepoint == src_glyph.Codepoint);
  633. if (src_glyph.Info.IsColored)
  634. dst_glyph->Colored = tex_use_colors = true;
  635. // Blit from temporary buffer to final texture
  636. size_t blit_src_stride = (size_t)src_glyph.Info.Width;
  637. size_t blit_dst_stride = (size_t)atlas->TexWidth;
  638. unsigned int* blit_src = src_glyph.BitmapData;
  639. if (atlas->TexPixelsAlpha8 != nullptr)
  640. {
  641. unsigned char* blit_dst = atlas->TexPixelsAlpha8 + (ty * blit_dst_stride) + tx;
  642. for (int y = 0; y < info.Height; y++, blit_dst += blit_dst_stride, blit_src += blit_src_stride)
  643. for (int x = 0; x < info.Width; x++)
  644. blit_dst[x] = (unsigned char)((blit_src[x] >> IM_COL32_A_SHIFT) & 0xFF);
  645. }
  646. else
  647. {
  648. unsigned int* blit_dst = atlas->TexPixelsRGBA32 + (ty * blit_dst_stride) + tx;
  649. for (int y = 0; y < info.Height; y++, blit_dst += blit_dst_stride, blit_src += blit_src_stride)
  650. for (int x = 0; x < info.Width; x++)
  651. blit_dst[x] = blit_src[x];
  652. }
  653. }
  654. src_tmp.Rects = nullptr;
  655. }
  656. atlas->TexPixelsUseColors = tex_use_colors;
  657. // Cleanup
  658. for (int buf_i = 0; buf_i < buf_bitmap_buffers.Size; buf_i++)
  659. IM_FREE(buf_bitmap_buffers[buf_i]);
  660. src_tmp_array.clear_destruct();
  661. ImFontAtlasBuildFinish(atlas);
  662. return true;
  663. }
  664. // FreeType memory allocation callbacks
  665. static void* FreeType_Alloc(FT_Memory /*memory*/, long size)
  666. {
  667. return GImGuiFreeTypeAllocFunc((size_t)size, GImGuiFreeTypeAllocatorUserData);
  668. }
  669. static void FreeType_Free(FT_Memory /*memory*/, void* block)
  670. {
  671. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  672. }
  673. static void* FreeType_Realloc(FT_Memory /*memory*/, long cur_size, long new_size, void* block)
  674. {
  675. // Implement realloc() as we don't ask user to provide it.
  676. if (block == nullptr)
  677. return GImGuiFreeTypeAllocFunc((size_t)new_size, GImGuiFreeTypeAllocatorUserData);
  678. if (new_size == 0)
  679. {
  680. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  681. return nullptr;
  682. }
  683. if (new_size > cur_size)
  684. {
  685. void* new_block = GImGuiFreeTypeAllocFunc((size_t)new_size, GImGuiFreeTypeAllocatorUserData);
  686. memcpy(new_block, block, (size_t)cur_size);
  687. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  688. return new_block;
  689. }
  690. return block;
  691. }
  692. static bool ImFontAtlasBuildWithFreeType(ImFontAtlas* atlas)
  693. {
  694. // FreeType memory management: https://www.freetype.org/freetype2/docs/design/design-4.html
  695. FT_MemoryRec_ memory_rec = {};
  696. memory_rec.user = nullptr;
  697. memory_rec.alloc = &FreeType_Alloc;
  698. memory_rec.free = &FreeType_Free;
  699. memory_rec.realloc = &FreeType_Realloc;
  700. // https://www.freetype.org/freetype2/docs/reference/ft2-module_management.html#FT_New_Library
  701. FT_Library ft_library;
  702. FT_Error error = FT_New_Library(&memory_rec, &ft_library);
  703. if (error != 0)
  704. return false;
  705. // If you don't call FT_Add_Default_Modules() the rest of code may work, but FreeType won't use our custom allocator.
  706. FT_Add_Default_Modules(ft_library);
  707. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  708. // Install svg hooks for FreeType
  709. // https://freetype.org/freetype2/docs/reference/ft2-properties.html#svg-hooks
  710. // https://freetype.org/freetype2/docs/reference/ft2-svg_fonts.html#svg_fonts
  711. SVG_RendererHooks hooks = { ImGuiLunasvgPortInit, ImGuiLunasvgPortFree, ImGuiLunasvgPortRender, ImGuiLunasvgPortPresetSlot };
  712. FT_Property_Set(ft_library, "ot-svg", "svg-hooks", &hooks);
  713. #endif // IMGUI_ENABLE_FREETYPE_LUNASVG
  714. bool ret = ImFontAtlasBuildWithFreeTypeEx(ft_library, atlas, atlas->FontBuilderFlags);
  715. FT_Done_Library(ft_library);
  716. return ret;
  717. }
  718. const ImFontBuilderIO* ImGuiFreeType::GetBuilderForFreeType()
  719. {
  720. static ImFontBuilderIO io;
  721. io.FontBuilder_Build = ImFontAtlasBuildWithFreeType;
  722. return &io;
  723. }
  724. void ImGuiFreeType::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
  725. {
  726. GImGuiFreeTypeAllocFunc = alloc_func;
  727. GImGuiFreeTypeFreeFunc = free_func;
  728. GImGuiFreeTypeAllocatorUserData = user_data;
  729. }
  730. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  731. // For more details, see https://gitlab.freedesktop.org/freetype/freetype-demos/-/blob/master/src/rsvg-port.c
  732. // The original code from the demo is licensed under CeCILL-C Free Software License Agreement (https://gitlab.freedesktop.org/freetype/freetype/-/blob/master/LICENSE.TXT)
  733. struct LunasvgPortState
  734. {
  735. FT_Error err = FT_Err_Ok;
  736. lunasvg::Matrix matrix;
  737. std::unique_ptr<lunasvg::Document> svg = nullptr;
  738. };
  739. static FT_Error ImGuiLunasvgPortInit(FT_Pointer* _state)
  740. {
  741. *_state = IM_NEW(LunasvgPortState)();
  742. return FT_Err_Ok;
  743. }
  744. static void ImGuiLunasvgPortFree(FT_Pointer* _state)
  745. {
  746. IM_DELETE(*(LunasvgPortState**)_state);
  747. }
  748. static FT_Error ImGuiLunasvgPortRender(FT_GlyphSlot slot, FT_Pointer* _state)
  749. {
  750. LunasvgPortState* state = *(LunasvgPortState**)_state;
  751. // If there was an error while loading the svg in ImGuiLunasvgPortPresetSlot(), the renderer hook still get called, so just returns the error.
  752. if (state->err != FT_Err_Ok)
  753. return state->err;
  754. // rows is height, pitch (or stride) equals to width * sizeof(int32)
  755. lunasvg::Bitmap bitmap((uint8_t*)slot->bitmap.buffer, slot->bitmap.width, slot->bitmap.rows, slot->bitmap.pitch);
  756. state->svg->setMatrix(state->svg->matrix().identity()); // Reset the svg matrix to the default value
  757. state->svg->render(bitmap, state->matrix); // state->matrix is already scaled and translated
  758. state->err = FT_Err_Ok;
  759. return state->err;
  760. }
  761. static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_Pointer* _state)
  762. {
  763. FT_SVG_Document document = (FT_SVG_Document)slot->other;
  764. LunasvgPortState* state = *(LunasvgPortState**)_state;
  765. FT_Size_Metrics& metrics = document->metrics;
  766. // This function is called twice, once in the FT_Load_Glyph() and another right before ImGuiLunasvgPortRender().
  767. // If it's the latter, don't do anything because it's // already done in the former.
  768. if (cache)
  769. return state->err;
  770. state->svg = lunasvg::Document::loadFromData((const char*)document->svg_document, document->svg_document_length);
  771. if (state->svg == nullptr)
  772. {
  773. state->err = FT_Err_Invalid_SVG_Document;
  774. return state->err;
  775. }
  776. lunasvg::Box box = state->svg->box();
  777. double scale = std::min(metrics.x_ppem / box.w, metrics.y_ppem / box.h);
  778. double xx = (double)document->transform.xx / (1 << 16);
  779. double xy = -(double)document->transform.xy / (1 << 16);
  780. double yx = -(double)document->transform.yx / (1 << 16);
  781. double yy = (double)document->transform.yy / (1 << 16);
  782. double x0 = (double)document->delta.x / 64 * box.w / metrics.x_ppem;
  783. double y0 = -(double)document->delta.y / 64 * box.h / metrics.y_ppem;
  784. // Scale and transform, we don't translate the svg yet
  785. state->matrix.identity();
  786. state->matrix.scale(scale, scale);
  787. state->matrix.transform(xx, xy, yx, yy, x0, y0);
  788. state->svg->setMatrix(state->matrix);
  789. // Pre-translate the matrix for the rendering step
  790. state->matrix.translate(-box.x, -box.y);
  791. // Get the box again after the transformation
  792. box = state->svg->box();
  793. // Calculate the bitmap size
  794. slot->bitmap_left = FT_Int(box.x);
  795. slot->bitmap_top = FT_Int(-box.y);
  796. slot->bitmap.rows = (unsigned int)(ImCeil((float)box.h));
  797. slot->bitmap.width = (unsigned int)(ImCeil((float)box.w));
  798. slot->bitmap.pitch = slot->bitmap.width * 4;
  799. slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA;
  800. // Compute all the bearings and set them correctly. The outline is scaled already, we just need to use the bounding box.
  801. double metrics_width = box.w;
  802. double metrics_height = box.h;
  803. double horiBearingX = box.x;
  804. double horiBearingY = -box.y;
  805. double vertBearingX = slot->metrics.horiBearingX / 64.0 - slot->metrics.horiAdvance / 64.0 / 2.0;
  806. double vertBearingY = (slot->metrics.vertAdvance / 64.0 - slot->metrics.height / 64.0) / 2.0;
  807. slot->metrics.width = FT_Pos(IM_ROUND(metrics_width * 64.0)); // Using IM_ROUND() assume width and height are positive
  808. slot->metrics.height = FT_Pos(IM_ROUND(metrics_height * 64.0));
  809. slot->metrics.horiBearingX = FT_Pos(horiBearingX * 64);
  810. slot->metrics.horiBearingY = FT_Pos(horiBearingY * 64);
  811. slot->metrics.vertBearingX = FT_Pos(vertBearingX * 64);
  812. slot->metrics.vertBearingY = FT_Pos(vertBearingY * 64);
  813. if (slot->metrics.vertAdvance == 0)
  814. slot->metrics.vertAdvance = FT_Pos(metrics_height * 1.2 * 64.0);
  815. state->err = FT_Err_Ok;
  816. return state->err;
  817. }
  818. #endif // #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  819. //-----------------------------------------------------------------------------
  820. #ifdef __GNUC__
  821. #pragma GCC diagnostic pop
  822. #endif
  823. #ifdef _MSC_VER
  824. #pragma warning (pop)
  825. #endif
  826. #endif // #ifndef IMGUI_DISABLE