imgui_freetype.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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) in 2017, with improvements by @mikesart.
  5. // Maintained since 2019 by @ocornut.
  6. // CHANGELOG
  7. // (minor and older changes stripped away, please see git history for details)
  8. // 2025/XX/XX: refactored for the new ImFontLoader architecture, and ImGuiBackendFlags_RendererHasTextures support.
  9. // 2024/10/17: added plutosvg support for SVG Fonts (seems faster/better than lunasvg). Enable by using '#define IMGUI_ENABLE_FREETYPE_PLUTOSVG'. (#7927)
  10. // 2023/11/13: added support for ImFontConfig::RasterizationDensity field for scaling render density without scaling metrics.
  11. // 2023/08/01: added support for SVG fonts, enable by using '#define IMGUI_ENABLE_FREETYPE_LUNASVG'. (#6591)
  12. // 2023/01/04: fixed a packing issue which in some occurrences would prevent large amount of glyphs from being packed correctly.
  13. // 2021/08/23: fixed crash when FT_Render_Glyph() fails to render a glyph and returns nullptr.
  14. // 2021/03/05: added ImGuiFreeTypeBuilderFlags_Bitmap to load bitmap glyphs.
  15. // 2021/03/02: set 'atlas->TexPixelsUseColors = true' to help some backends with deciding of a preferred texture format.
  16. // 2021/01/28: added support for color-layered glyphs via ImGuiFreeTypeBuilderFlags_LoadColor (require Freetype 2.10+).
  17. // 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().
  18. // 2020/06/04: fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails.
  19. // 2019/02/09: added RasterizerFlags::Monochrome flag to disable font anti-aliasing (combine with ::MonoHinting for best results!)
  20. // 2019/01/15: added support for imgui allocators + added FreeType only override function SetAllocatorFunctions().
  21. // 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.
  22. // 2018/06/08: added support for ImFontConfig::GlyphMinAdvanceX, GlyphMaxAdvanceX.
  23. // 2018/02/04: moved to main imgui repository (away from http://www.github.com/ocornut/imgui_club)
  24. // 2018/01/22: fix for addition of ImFontAtlas::TexUvscale member.
  25. // 2017/10/22: minor inconsequential change to match change in master (removed an unnecessary statement).
  26. // 2017/09/26: fixes for imgui internal changes.
  27. // 2017/08/26: cleanup, optimizations, support for ImFontConfig::RasterizerFlags, ImFontConfig::RasterizerMultiply.
  28. // 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.
  29. // About Gamma Correct Blending:
  30. // - FreeType assumes blending in linear space rather than gamma space.
  31. // - See https://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#FT_Render_Glyph
  32. // - For correct results you need to be using sRGB and convert to linear space in the pixel shader output.
  33. // - The default dear imgui styles will be impacted by this change (alpha values will need tweaking).
  34. // FIXME: cfg.OversampleH, OversampleV are not supported, but generally not necessary with this rasterizer because Hinting makes everything look better.
  35. #include "imgui.h"
  36. #ifndef IMGUI_DISABLE
  37. #include "imgui_freetype.h"
  38. #include "imgui_internal.h" // ImMin,ImMax,ImFontAtlasBuild*,
  39. #include <stdint.h>
  40. #include <ft2build.h>
  41. #include FT_FREETYPE_H // <freetype/freetype.h>
  42. #include FT_MODULE_H // <freetype/ftmodapi.h>
  43. #include FT_GLYPH_H // <freetype/ftglyph.h>
  44. #include FT_SIZES_H // <freetype/ftsizes.h>
  45. #include FT_SYNTHESIS_H // <freetype/ftsynth.h>
  46. // Handle LunaSVG and PlutoSVG
  47. #if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) && defined(IMGUI_ENABLE_FREETYPE_PLUTOSVG)
  48. #error "Cannot enable both IMGUI_ENABLE_FREETYPE_LUNASVG and IMGUI_ENABLE_FREETYPE_PLUTOSVG"
  49. #endif
  50. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  51. #include FT_OTSVG_H // <freetype/otsvg.h>
  52. #include FT_BBOX_H // <freetype/ftbbox.h>
  53. #include <lunasvg.h>
  54. #endif
  55. #ifdef IMGUI_ENABLE_FREETYPE_PLUTOSVG
  56. #include <plutosvg.h>
  57. #endif
  58. #if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) || defined (IMGUI_ENABLE_FREETYPE_PLUTOSVG)
  59. #if !((FREETYPE_MAJOR >= 2) && (FREETYPE_MINOR >= 12))
  60. #error IMGUI_ENABLE_FREETYPE_PLUTOSVG or IMGUI_ENABLE_FREETYPE_LUNASVG requires FreeType version >= 2.12
  61. #endif
  62. #endif
  63. #ifdef _MSC_VER
  64. #pragma warning (push)
  65. #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
  66. #pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
  67. #endif
  68. #ifdef __GNUC__
  69. #pragma GCC diagnostic push
  70. #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
  71. #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
  72. #ifndef __clang__
  73. #pragma GCC diagnostic ignored "-Wsubobject-linkage" // warning: 'xxxx' has a field 'xxxx' whose type uses the anonymous namespace
  74. #endif
  75. #endif
  76. //-------------------------------------------------------------------------
  77. // Data
  78. //-------------------------------------------------------------------------
  79. // Default memory allocators
  80. static void* ImGuiFreeTypeDefaultAllocFunc(size_t size, void* user_data) { IM_UNUSED(user_data); return IM_ALLOC(size); }
  81. static void ImGuiFreeTypeDefaultFreeFunc(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_FREE(ptr); }
  82. // Current memory allocators
  83. static void* (*GImGuiFreeTypeAllocFunc)(size_t size, void* user_data) = ImGuiFreeTypeDefaultAllocFunc;
  84. static void (*GImGuiFreeTypeFreeFunc)(void* ptr, void* user_data) = ImGuiFreeTypeDefaultFreeFunc;
  85. static void* GImGuiFreeTypeAllocatorUserData = nullptr;
  86. // Lunasvg support
  87. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  88. static FT_Error ImGuiLunasvgPortInit(FT_Pointer* state);
  89. static void ImGuiLunasvgPortFree(FT_Pointer* state);
  90. static FT_Error ImGuiLunasvgPortRender(FT_GlyphSlot slot, FT_Pointer* _state);
  91. static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_Pointer* _state);
  92. #endif
  93. //-------------------------------------------------------------------------
  94. // Code
  95. //-------------------------------------------------------------------------
  96. #define FT_CEIL(X) (((X + 63) & -64) / 64) // From SDL_ttf: Handy routines for converting from fixed point
  97. #define FT_SCALEFACTOR 64.0f
  98. namespace
  99. {
  100. // Glyph metrics:
  101. // --------------
  102. //
  103. // xmin xmax
  104. // | |
  105. // |<-------- width -------->|
  106. // | |
  107. // | +-------------------------+----------------- ymax
  108. // | | ggggggggg ggggg | ^ ^
  109. // | | g:::::::::ggg::::g | | |
  110. // | | g:::::::::::::::::g | | |
  111. // | | g::::::ggggg::::::gg | | |
  112. // | | g:::::g g:::::g | | |
  113. // offsetX -|-------->| g:::::g g:::::g | offsetY |
  114. // | | g:::::g g:::::g | | |
  115. // | | g::::::g g:::::g | | |
  116. // | | g:::::::ggggg:::::g | | |
  117. // | | g::::::::::::::::g | | height
  118. // | | gg::::::::::::::g | | |
  119. // baseline ---*---------|---- gggggggg::::::g-----*-------- |
  120. // / | | g:::::g | |
  121. // origin | | gggggg g:::::g | |
  122. // | | g:::::gg gg:::::g | |
  123. // | | g::::::ggg:::::::g | |
  124. // | | gg:::::::::::::g | |
  125. // | | ggg::::::ggg | |
  126. // | | gggggg | v
  127. // | +-------------------------+----------------- ymin
  128. // | |
  129. // |------------- advanceX ----------->|
  130. // Stored in ImFontAtlas::FontLoaderData. ALLOCATED BY US.
  131. struct ImGui_ImplFreeType_Data
  132. {
  133. FT_Library Library;
  134. FT_MemoryRec_ MemoryManager;
  135. ImGui_ImplFreeType_Data() { memset((void*)this, 0, sizeof(*this)); }
  136. };
  137. // Stored in ImFontBaked::FontLoaderDatas: pointer to SourcesCount instances of this. ALLOCATED BY CORE.
  138. struct ImGui_ImplFreeType_FontSrcBakedData
  139. {
  140. FT_Size FtSize; // This represent a FT_Face with a given size.
  141. ImGui_ImplFreeType_FontSrcBakedData() { memset((void*)this, 0, sizeof(*this)); }
  142. };
  143. // Stored in ImFontConfig::FontLoaderData. ALLOCATED BY US.
  144. struct ImGui_ImplFreeType_FontSrcData
  145. {
  146. bool InitFont(FT_Library ft_library, ImFontConfig* src, 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.
  147. void CloseFont();
  148. const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint);
  149. void BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch);
  150. ImGui_ImplFreeType_FontSrcData() { memset((void*)this, 0, sizeof(*this)); }
  151. ~ImGui_ImplFreeType_FontSrcData() { CloseFont(); }
  152. // Members
  153. FT_Face FtFace;
  154. unsigned int UserFlags; // = ImFontConfig::RasterizerFlags
  155. FT_Int32 LoadFlags;
  156. FT_Render_Mode RenderMode;
  157. float RasterizationDensity;
  158. float InvRasterizationDensity;
  159. ImFontBaked* BakedLastActivated;
  160. };
  161. bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfig* src, unsigned int extra_font_builder_flags)
  162. {
  163. FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src->FontData, (uint32_t)src->FontDataSize, (uint32_t)src->FontNo, &FtFace);
  164. if (error != 0)
  165. return false;
  166. error = FT_Select_Charmap(FtFace, FT_ENCODING_UNICODE);
  167. if (error != 0)
  168. return false;
  169. // Convert to FreeType flags (NB: Bold and Oblique are processed separately)
  170. UserFlags = src->FontBuilderFlags | extra_font_builder_flags;
  171. LoadFlags = 0;
  172. if ((UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) == 0)
  173. LoadFlags |= FT_LOAD_NO_BITMAP;
  174. if (UserFlags & ImGuiFreeTypeBuilderFlags_NoHinting)
  175. LoadFlags |= FT_LOAD_NO_HINTING;
  176. else
  177. src->PixelSnapH = true; // FIXME: A bit weird to do this this way.
  178. if (UserFlags & ImGuiFreeTypeBuilderFlags_NoAutoHint)
  179. LoadFlags |= FT_LOAD_NO_AUTOHINT;
  180. if (UserFlags & ImGuiFreeTypeBuilderFlags_ForceAutoHint)
  181. LoadFlags |= FT_LOAD_FORCE_AUTOHINT;
  182. if (UserFlags & ImGuiFreeTypeBuilderFlags_LightHinting)
  183. LoadFlags |= FT_LOAD_TARGET_LIGHT;
  184. else if (UserFlags & ImGuiFreeTypeBuilderFlags_MonoHinting)
  185. LoadFlags |= FT_LOAD_TARGET_MONO;
  186. else
  187. LoadFlags |= FT_LOAD_TARGET_NORMAL;
  188. if (UserFlags & ImGuiFreeTypeBuilderFlags_Monochrome)
  189. RenderMode = FT_RENDER_MODE_MONO;
  190. else
  191. RenderMode = FT_RENDER_MODE_NORMAL;
  192. if (UserFlags & ImGuiFreeTypeBuilderFlags_LoadColor)
  193. LoadFlags |= FT_LOAD_COLOR;
  194. RasterizationDensity = src->RasterizerDensity;
  195. InvRasterizationDensity = 1.0f / RasterizationDensity;
  196. return true;
  197. }
  198. void ImGui_ImplFreeType_FontSrcData::CloseFont()
  199. {
  200. if (FtFace)
  201. {
  202. FT_Done_Face(FtFace);
  203. FtFace = nullptr;
  204. }
  205. }
  206. const FT_Glyph_Metrics* ImGui_ImplFreeType_FontSrcData::LoadGlyph(uint32_t codepoint)
  207. {
  208. uint32_t glyph_index = FT_Get_Char_Index(FtFace, codepoint);
  209. if (glyph_index == 0)
  210. return nullptr;
  211. // If this crash for you: FreeType 2.11.0 has a crash bug on some bitmap/colored fonts.
  212. // - https://gitlab.freedesktop.org/freetype/freetype/-/issues/1076
  213. // - https://github.com/ocornut/imgui/issues/4567
  214. // - https://github.com/ocornut/imgui/issues/4566
  215. // You can use FreeType 2.10, or the patched version of 2.11.0 in VcPkg, or probably any upcoming FreeType version.
  216. FT_Error error = FT_Load_Glyph(FtFace, glyph_index, LoadFlags);
  217. if (error)
  218. return nullptr;
  219. // Need an outline for this to work
  220. FT_GlyphSlot slot = FtFace->glyph;
  221. #if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) || defined(IMGUI_ENABLE_FREETYPE_PLUTOSVG)
  222. IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP || slot->format == FT_GLYPH_FORMAT_SVG);
  223. #else
  224. #if ((FREETYPE_MAJOR >= 2) && (FREETYPE_MINOR >= 12))
  225. IM_ASSERT(slot->format != FT_GLYPH_FORMAT_SVG && "The font contains SVG glyphs, you'll need to enable IMGUI_ENABLE_FREETYPE_PLUTOSVG or IMGUI_ENABLE_FREETYPE_LUNASVG in imconfig.h and install required libraries in order to use this font");
  226. #endif
  227. IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP);
  228. #endif // IMGUI_ENABLE_FREETYPE_LUNASVG
  229. // Apply convenience transform (this is not picking from real "Bold"/"Italic" fonts! Merely applying FreeType helper transform. Oblique == Slanting)
  230. if (UserFlags & ImGuiFreeTypeBuilderFlags_Bold)
  231. FT_GlyphSlot_Embolden(slot);
  232. if (UserFlags & ImGuiFreeTypeBuilderFlags_Oblique)
  233. {
  234. FT_GlyphSlot_Oblique(slot);
  235. //FT_BBox bbox;
  236. //FT_Outline_Get_BBox(&slot->outline, &bbox);
  237. //slot->metrics.width = bbox.xMax - bbox.xMin;
  238. //slot->metrics.height = bbox.yMax - bbox.yMin;
  239. }
  240. return &slot->metrics;
  241. }
  242. void ImGui_ImplFreeType_FontSrcData::BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch)
  243. {
  244. IM_ASSERT(ft_bitmap != nullptr);
  245. const uint32_t w = ft_bitmap->width;
  246. const uint32_t h = ft_bitmap->rows;
  247. const uint8_t* src = ft_bitmap->buffer;
  248. const uint32_t src_pitch = ft_bitmap->pitch;
  249. switch (ft_bitmap->pixel_mode)
  250. {
  251. case FT_PIXEL_MODE_GRAY: // Grayscale image, 1 byte per pixel.
  252. {
  253. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  254. for (uint32_t x = 0; x < w; x++)
  255. dst[x] = IM_COL32(255, 255, 255, src[x]);
  256. break;
  257. }
  258. case FT_PIXEL_MODE_MONO: // Monochrome image, 1 bit per pixel. The bits in each byte are ordered from MSB to LSB.
  259. {
  260. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  261. {
  262. uint8_t bits = 0;
  263. const uint8_t* bits_ptr = src;
  264. for (uint32_t x = 0; x < w; x++, bits <<= 1)
  265. {
  266. if ((x & 7) == 0)
  267. bits = *bits_ptr++;
  268. dst[x] = IM_COL32(255, 255, 255, (bits & 0x80) ? 255 : 0);
  269. }
  270. }
  271. break;
  272. }
  273. case FT_PIXEL_MODE_BGRA:
  274. {
  275. // FIXME: Converting pre-multiplied alpha to straight. Doesn't smell good.
  276. #define DE_MULTIPLY(color, alpha) ImMin((ImU32)(255.0f * (float)color / (float)(alpha + FLT_MIN) + 0.5f), 255u)
  277. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  278. for (uint32_t x = 0; x < w; x++)
  279. {
  280. uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3];
  281. dst[x] = IM_COL32(DE_MULTIPLY(r, a), DE_MULTIPLY(g, a), DE_MULTIPLY(b, a), a);
  282. }
  283. #undef DE_MULTIPLY
  284. break;
  285. }
  286. default:
  287. IM_ASSERT(0 && "FreeTypeFont::BlitGlyph(): Unknown bitmap pixel mode!");
  288. }
  289. }
  290. } // namespace
  291. // FreeType memory allocation callbacks
  292. static void* FreeType_Alloc(FT_Memory /*memory*/, long size)
  293. {
  294. return GImGuiFreeTypeAllocFunc((size_t)size, GImGuiFreeTypeAllocatorUserData);
  295. }
  296. static void FreeType_Free(FT_Memory /*memory*/, void* block)
  297. {
  298. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  299. }
  300. static void* FreeType_Realloc(FT_Memory /*memory*/, long cur_size, long new_size, void* block)
  301. {
  302. // Implement realloc() as we don't ask user to provide it.
  303. if (block == nullptr)
  304. return GImGuiFreeTypeAllocFunc((size_t)new_size, GImGuiFreeTypeAllocatorUserData);
  305. if (new_size == 0)
  306. {
  307. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  308. return nullptr;
  309. }
  310. if (new_size > cur_size)
  311. {
  312. void* new_block = GImGuiFreeTypeAllocFunc((size_t)new_size, GImGuiFreeTypeAllocatorUserData);
  313. memcpy(new_block, block, (size_t)cur_size);
  314. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  315. return new_block;
  316. }
  317. return block;
  318. }
  319. bool ImGui_ImplFreeType_LoaderInit(ImFontAtlas* atlas)
  320. {
  321. IM_ASSERT(atlas->FontLoaderData == NULL);
  322. ImGui_ImplFreeType_Data* bd = IM_NEW(ImGui_ImplFreeType_Data)();
  323. // FreeType memory management: https://www.freetype.org/freetype2/docs/design/design-4.html
  324. bd->MemoryManager.user = nullptr;
  325. bd->MemoryManager.alloc = &FreeType_Alloc;
  326. bd->MemoryManager.free = &FreeType_Free;
  327. bd->MemoryManager.realloc = &FreeType_Realloc;
  328. // https://www.freetype.org/freetype2/docs/reference/ft2-module_management.html#FT_New_Library
  329. FT_Error error = FT_New_Library(&bd->MemoryManager, &bd->Library);
  330. if (error != 0)
  331. {
  332. IM_DELETE(bd);
  333. return false;
  334. }
  335. // If you don't call FT_Add_Default_Modules() the rest of code may work, but FreeType won't use our custom allocator.
  336. FT_Add_Default_Modules(bd->Library);
  337. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  338. // Install svg hooks for FreeType
  339. // https://freetype.org/freetype2/docs/reference/ft2-properties.html#svg-hooks
  340. // https://freetype.org/freetype2/docs/reference/ft2-svg_fonts.html#svg_fonts
  341. SVG_RendererHooks hooks = { ImGuiLunasvgPortInit, ImGuiLunasvgPortFree, ImGuiLunasvgPortRender, ImGuiLunasvgPortPresetSlot };
  342. FT_Property_Set(bd->Library, "ot-svg", "svg-hooks", &hooks);
  343. #endif // IMGUI_ENABLE_FREETYPE_LUNASVG
  344. #ifdef IMGUI_ENABLE_FREETYPE_PLUTOSVG
  345. // With plutosvg, use provided hooks
  346. FT_Property_Set(bd->Library, "ot-svg", "svg-hooks", plutosvg_ft_svg_hooks());
  347. #endif // IMGUI_ENABLE_FREETYPE_PLUTOSVG
  348. // Store our data
  349. atlas->FontLoaderData = (void*)bd;
  350. return true;
  351. }
  352. void ImGui_ImplFreeType_LoaderShutdown(ImFontAtlas* atlas)
  353. {
  354. ImGui_ImplFreeType_Data* bd = (ImGui_ImplFreeType_Data*)atlas->FontLoaderData;
  355. IM_ASSERT(bd != NULL);
  356. FT_Done_Library(bd->Library);
  357. IM_DELETE(bd);
  358. atlas->FontLoaderData = NULL;
  359. }
  360. bool ImGui_ImplFreeType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src)
  361. {
  362. ImGui_ImplFreeType_Data* bd = (ImGui_ImplFreeType_Data*)atlas->FontLoaderData;
  363. ImGui_ImplFreeType_FontSrcData* bd_font_data = IM_NEW(ImGui_ImplFreeType_FontSrcData);
  364. IM_ASSERT(src->FontLoaderData == NULL);
  365. src->FontLoaderData = bd_font_data;
  366. if (!bd_font_data->InitFont(bd->Library, src, atlas->FontBuilderFlags))
  367. {
  368. IM_DELETE(bd_font_data);
  369. src->FontLoaderData = NULL;
  370. return false;
  371. }
  372. return true;
  373. }
  374. void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src)
  375. {
  376. IM_UNUSED(atlas);
  377. ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData;
  378. IM_DELETE(bd_font_data);
  379. src->FontLoaderData = NULL;
  380. }
  381. bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src)
  382. {
  383. IM_UNUSED(atlas);
  384. const float size = baked->Size * (src->SizePixels / baked->ContainerFont->Sources[0].SizePixels); // FIXME-NEWATLAS: Should tidy up that a bit
  385. ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData;
  386. bd_font_data->BakedLastActivated = baked;
  387. // We use one FT_Size per (source + baked) combination.
  388. ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src;
  389. IM_ASSERT(bd_baked_data != NULL);
  390. IM_PLACEMENT_NEW(bd_baked_data) ImGui_ImplFreeType_FontSrcBakedData();
  391. FT_New_Size(bd_font_data->FtFace, &bd_baked_data->FtSize);
  392. FT_Activate_Size(bd_baked_data->FtSize);
  393. // Vuhdo 2017: "I'm not sure how to deal with font sizes properly. As far as I understand, currently ImGui assumes that the 'pixel_height'
  394. // 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.
  395. // FT_Set_Pixel_Sizes() doesn't seem to get us the same result."
  396. // (FT_Set_Pixel_Sizes() essentially calls FT_Request_Size() with FT_SIZE_REQUEST_TYPE_NOMINAL)
  397. FT_Size_RequestRec req;
  398. req.type = (bd_font_data->UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM;
  399. req.width = 0;
  400. req.height = (uint32_t)(size * 64 * bd_font_data->RasterizationDensity);
  401. req.horiResolution = 0;
  402. req.vertResolution = 0;
  403. FT_Request_Size(bd_font_data->FtFace, &req);
  404. // Output
  405. if (src->MergeMode == false)
  406. {
  407. // Read metrics
  408. FT_Size_Metrics metrics = bd_baked_data->FtSize->metrics;
  409. const float scale = bd_font_data->InvRasterizationDensity;
  410. baked->Ascent = (float)FT_CEIL(metrics.ascender) * scale; // The pixel extents above the baseline in pixels (typically positive).
  411. baked->Descent = (float)FT_CEIL(metrics.descender) * scale; // The extents below the baseline in pixels (typically negative).
  412. //LineSpacing = (float)FT_CEIL(metrics.height) * scale; // 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.
  413. //LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender) * scale; // The spacing in pixels between one row's descent and the next row's ascent.
  414. //MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * scale; // This field gives the maximum horizontal cursor advance for all glyphs in the font.
  415. }
  416. return true;
  417. }
  418. void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src)
  419. {
  420. IM_UNUSED(atlas);
  421. IM_UNUSED(baked);
  422. IM_UNUSED(src);
  423. ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src;
  424. IM_ASSERT(bd_baked_data != NULL);
  425. FT_Done_Size(bd_baked_data->FtSize);
  426. bd_baked_data->~ImGui_ImplFreeType_FontSrcBakedData(); // ~IM_PLACEMENT_DELETE()
  427. }
  428. ImFontGlyph* ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint)
  429. {
  430. ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData;
  431. uint32_t glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint);
  432. if (glyph_index == 0)
  433. return NULL;
  434. if (bd_font_data->BakedLastActivated != baked) // <-- could use id
  435. {
  436. // Activate current size
  437. ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src;
  438. FT_Activate_Size(bd_baked_data->FtSize);
  439. bd_font_data->BakedLastActivated = baked;
  440. }
  441. const FT_Glyph_Metrics* metrics = bd_font_data->LoadGlyph(codepoint);
  442. if (metrics == NULL)
  443. return NULL;
  444. // Render glyph into a bitmap (currently held by FreeType)
  445. FT_Face face = bd_font_data->FtFace;
  446. FT_GlyphSlot slot = face->glyph;
  447. FT_Error error = FT_Render_Glyph(slot, bd_font_data->RenderMode);
  448. const FT_Bitmap* ft_bitmap = &slot->bitmap;
  449. if (error != 0 || ft_bitmap == nullptr)
  450. return NULL;
  451. const int w = (int)ft_bitmap->width;
  452. const int h = (int)ft_bitmap->rows;
  453. const bool is_visible = (w != 0 && h != 0);
  454. // Prepare glyph
  455. ImFontGlyph glyph_in = {};
  456. ImFontGlyph* glyph = &glyph_in;
  457. glyph->Codepoint = codepoint;
  458. glyph->AdvanceX = (slot->advance.x / FT_SCALEFACTOR) * bd_font_data->InvRasterizationDensity;
  459. // Pack and retrieve position inside texture atlas
  460. if (is_visible)
  461. {
  462. ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, w, h);
  463. if (pack_id < 0)
  464. {
  465. // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?)
  466. IM_ASSERT_USER_ERROR(pack_id >= 0, "Out of texture memory.");
  467. return NULL;
  468. }
  469. ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id);
  470. // Render pixels to our temporary buffer
  471. atlas->Builder->TempBuffer.resize(w * h * 4);
  472. uint32_t* temp_buffer = (uint32_t*)atlas->Builder->TempBuffer.Data;
  473. bd_font_data->BlitGlyph(ft_bitmap, temp_buffer, w);
  474. const float offsets_scale = baked->Size / baked->ContainerFont->Sources[0].SizePixels;
  475. float font_off_x = (src->GlyphOffset.x * offsets_scale);
  476. float font_off_y = (src->GlyphOffset.y * offsets_scale) + baked->Ascent;
  477. if (src->PixelSnapH) // Snap scaled offset. This is to mitigate backward compatibility issues for GlyphOffset, but a better design would be welcome.
  478. font_off_x = IM_ROUND(font_off_x);
  479. if (src->PixelSnapV)
  480. font_off_y = IM_ROUND(font_off_y);
  481. float recip_h = 1.0f / src->RasterizerDensity;
  482. float recip_v = 1.0f / src->RasterizerDensity;
  483. // Register glyph
  484. float glyph_off_x = (float)face->glyph->bitmap_left;
  485. float glyph_off_y = (float)-face->glyph->bitmap_top;
  486. glyph->X0 = glyph_off_x * recip_h + font_off_x;
  487. glyph->Y0 = glyph_off_y * recip_v + font_off_y;
  488. glyph->X1 = (glyph_off_x + w) * recip_h + font_off_x;
  489. glyph->Y1 = (glyph_off_y + h) * recip_v + font_off_y;
  490. glyph->Visible = true;
  491. glyph->Colored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA);
  492. glyph->PackId = pack_id;
  493. glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, src, glyph);
  494. ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, glyph, r, (const unsigned char*)temp_buffer, ImTextureFormat_RGBA32, w * 4);
  495. }
  496. else
  497. {
  498. glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, src, glyph);
  499. }
  500. return glyph;
  501. }
  502. bool ImGui_ImplFreetype_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint)
  503. {
  504. IM_UNUSED(atlas);
  505. ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData;
  506. int glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint);
  507. return glyph_index != 0;
  508. }
  509. const ImFontLoader* ImGuiFreeType::GetFontLoader()
  510. {
  511. static ImFontLoader loader;
  512. loader.Name = "FreeType";
  513. loader.LoaderInit = ImGui_ImplFreeType_LoaderInit;
  514. loader.LoaderShutdown = ImGui_ImplFreeType_LoaderShutdown;
  515. loader.FontSrcInit = ImGui_ImplFreeType_FontSrcInit;
  516. loader.FontSrcDestroy = ImGui_ImplFreeType_FontSrcDestroy;
  517. loader.FontSrcContainsGlyph = ImGui_ImplFreetype_FontSrcContainsGlyph;
  518. loader.FontBakedInit = ImGui_ImplFreeType_FontBakedInit;
  519. loader.FontBakedDestroy = ImGui_ImplFreeType_FontBakedDestroy;
  520. loader.FontBakedLoadGlyph = ImGui_ImplFreeType_FontBakedLoadGlyph;
  521. loader.FontBakedSrcLoaderDataSize = sizeof(ImGui_ImplFreeType_FontSrcBakedData);
  522. return &loader;
  523. }
  524. void ImGuiFreeType::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
  525. {
  526. GImGuiFreeTypeAllocFunc = alloc_func;
  527. GImGuiFreeTypeFreeFunc = free_func;
  528. GImGuiFreeTypeAllocatorUserData = user_data;
  529. }
  530. bool ImGuiFreeType::DebugEditFontBuilderFlags(unsigned int* p_font_loader_flags)
  531. {
  532. bool edited = false;
  533. edited |= ImGui::CheckboxFlags("NoHinting", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_NoHinting);
  534. edited |= ImGui::CheckboxFlags("NoAutoHint", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_NoAutoHint);
  535. edited |= ImGui::CheckboxFlags("ForceAutoHint",p_font_loader_flags, ImGuiFreeTypeBuilderFlags_ForceAutoHint);
  536. edited |= ImGui::CheckboxFlags("LightHinting", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_LightHinting);
  537. edited |= ImGui::CheckboxFlags("MonoHinting", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_MonoHinting);
  538. edited |= ImGui::CheckboxFlags("Bold", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_Bold);
  539. edited |= ImGui::CheckboxFlags("Oblique", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_Oblique);
  540. edited |= ImGui::CheckboxFlags("Monochrome", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_Monochrome);
  541. edited |= ImGui::CheckboxFlags("LoadColor", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_LoadColor);
  542. edited |= ImGui::CheckboxFlags("Bitmap", p_font_loader_flags, ImGuiFreeTypeBuilderFlags_Bitmap);
  543. return edited;
  544. }
  545. #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  546. // For more details, see https://gitlab.freedesktop.org/freetype/freetype-demos/-/blob/master/src/rsvg-port.c
  547. // 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)
  548. struct LunasvgPortState
  549. {
  550. FT_Error err = FT_Err_Ok;
  551. lunasvg::Matrix matrix;
  552. std::unique_ptr<lunasvg::Document> svg = nullptr;
  553. };
  554. static FT_Error ImGuiLunasvgPortInit(FT_Pointer* _state)
  555. {
  556. *_state = IM_NEW(LunasvgPortState)();
  557. return FT_Err_Ok;
  558. }
  559. static void ImGuiLunasvgPortFree(FT_Pointer* _state)
  560. {
  561. IM_DELETE(*(LunasvgPortState**)_state);
  562. }
  563. static FT_Error ImGuiLunasvgPortRender(FT_GlyphSlot slot, FT_Pointer* _state)
  564. {
  565. LunasvgPortState* state = *(LunasvgPortState**)_state;
  566. // If there was an error while loading the svg in ImGuiLunasvgPortPresetSlot(), the renderer hook still get called, so just returns the error.
  567. if (state->err != FT_Err_Ok)
  568. return state->err;
  569. // rows is height, pitch (or stride) equals to width * sizeof(int32)
  570. lunasvg::Bitmap bitmap((uint8_t*)slot->bitmap.buffer, slot->bitmap.width, slot->bitmap.rows, slot->bitmap.pitch);
  571. #if LUNASVG_VERSION_MAJOR >= 3
  572. state->svg->render(bitmap, state->matrix); // state->matrix is already scaled and translated
  573. #else
  574. state->svg->setMatrix(state->svg->matrix().identity()); // Reset the svg matrix to the default value
  575. state->svg->render(bitmap, state->matrix); // state->matrix is already scaled and translated
  576. #endif
  577. state->err = FT_Err_Ok;
  578. return state->err;
  579. }
  580. static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_Pointer* _state)
  581. {
  582. FT_SVG_Document document = (FT_SVG_Document)slot->other;
  583. LunasvgPortState* state = *(LunasvgPortState**)_state;
  584. FT_Size_Metrics& metrics = document->metrics;
  585. // This function is called twice, once in the FT_Load_Glyph() and another right before ImGuiLunasvgPortRender().
  586. // If it's the latter, don't do anything because it's // already done in the former.
  587. if (cache)
  588. return state->err;
  589. state->svg = lunasvg::Document::loadFromData((const char*)document->svg_document, document->svg_document_length);
  590. if (state->svg == nullptr)
  591. {
  592. state->err = FT_Err_Invalid_SVG_Document;
  593. return state->err;
  594. }
  595. #if LUNASVG_VERSION_MAJOR >= 3
  596. lunasvg::Box box = state->svg->boundingBox();
  597. #else
  598. lunasvg::Box box = state->svg->box();
  599. #endif
  600. double scale = std::min(metrics.x_ppem / box.w, metrics.y_ppem / box.h);
  601. double xx = (double)document->transform.xx / (1 << 16);
  602. double xy = -(double)document->transform.xy / (1 << 16);
  603. double yx = -(double)document->transform.yx / (1 << 16);
  604. double yy = (double)document->transform.yy / (1 << 16);
  605. double x0 = (double)document->delta.x / 64 * box.w / metrics.x_ppem;
  606. double y0 = -(double)document->delta.y / 64 * box.h / metrics.y_ppem;
  607. #if LUNASVG_VERSION_MAJOR >= 3
  608. // Scale, transform and pre-translate the matrix for the rendering step
  609. state->matrix = lunasvg::Matrix::translated(-box.x, -box.y);
  610. state->matrix.multiply(lunasvg::Matrix(xx, xy, yx, yy, x0, y0));
  611. state->matrix.scale(scale, scale);
  612. // Apply updated transformation to the bounding box
  613. box.transform(state->matrix);
  614. #else
  615. // Scale and transform, we don't translate the svg yet
  616. state->matrix.identity();
  617. state->matrix.scale(scale, scale);
  618. state->matrix.transform(xx, xy, yx, yy, x0, y0);
  619. state->svg->setMatrix(state->matrix);
  620. // Pre-translate the matrix for the rendering step
  621. state->matrix.translate(-box.x, -box.y);
  622. // Get the box again after the transformation
  623. box = state->svg->box();
  624. #endif
  625. // Calculate the bitmap size
  626. slot->bitmap_left = FT_Int(box.x);
  627. slot->bitmap_top = FT_Int(-box.y);
  628. slot->bitmap.rows = (unsigned int)(ImCeil((float)box.h));
  629. slot->bitmap.width = (unsigned int)(ImCeil((float)box.w));
  630. slot->bitmap.pitch = slot->bitmap.width * 4;
  631. slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA;
  632. // Compute all the bearings and set them correctly. The outline is scaled already, we just need to use the bounding box.
  633. double metrics_width = box.w;
  634. double metrics_height = box.h;
  635. double horiBearingX = box.x;
  636. double horiBearingY = -box.y;
  637. double vertBearingX = slot->metrics.horiBearingX / 64.0 - slot->metrics.horiAdvance / 64.0 / 2.0;
  638. double vertBearingY = (slot->metrics.vertAdvance / 64.0 - slot->metrics.height / 64.0) / 2.0;
  639. slot->metrics.width = FT_Pos(IM_ROUND(metrics_width * 64.0)); // Using IM_ROUND() assume width and height are positive
  640. slot->metrics.height = FT_Pos(IM_ROUND(metrics_height * 64.0));
  641. slot->metrics.horiBearingX = FT_Pos(horiBearingX * 64);
  642. slot->metrics.horiBearingY = FT_Pos(horiBearingY * 64);
  643. slot->metrics.vertBearingX = FT_Pos(vertBearingX * 64);
  644. slot->metrics.vertBearingY = FT_Pos(vertBearingY * 64);
  645. if (slot->metrics.vertAdvance == 0)
  646. slot->metrics.vertAdvance = FT_Pos(metrics_height * 1.2 * 64.0);
  647. state->err = FT_Err_Ok;
  648. return state->err;
  649. }
  650. #endif // #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG
  651. //-----------------------------------------------------------------------------
  652. #ifdef __GNUC__
  653. #pragma GCC diagnostic pop
  654. #endif
  655. #ifdef _MSC_VER
  656. #pragma warning (pop)
  657. #endif
  658. #endif // #ifndef IMGUI_DISABLE