imgui_freetype.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. // dear imgui: FreeType font builder (used as a replacement for the stb_truetype builder)
  2. // (code)
  3. // Get 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. // 2021/03/02: set 'atlas->TexPixelsUseColors = true' to help some backends with deciding of a prefered texture format.
  8. // 2021/01/28: added support for color-layered glyphs via ImGuiFreeTypeBuilderFlags_LoadColor (require Freetype 2.10+).
  9. // 2021/01/26: simplified integration by using '#define IMGUI_ENABLE_FREETYPE'.
  10. // renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API. removed ImGuiFreeType::BuildFontAtlas().
  11. // 2020/06/04: fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails.
  12. // 2019/02/09: added RasterizerFlags::Monochrome flag to disable font anti-aliasing (combine with ::MonoHinting for best results!)
  13. // 2019/01/15: added support for imgui allocators + added FreeType only override function SetAllocatorFunctions().
  14. // 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.
  15. // 2018/06/08: added support for ImFontConfig::GlyphMinAdvanceX, GlyphMaxAdvanceX.
  16. // 2018/02/04: moved to main imgui repository (away from http://www.github.com/ocornut/imgui_club)
  17. // 2018/01/22: fix for addition of ImFontAtlas::TexUvscale member.
  18. // 2017/10/22: minor inconsequential change to match change in master (removed an unnecessary statement).
  19. // 2017/09/26: fixes for imgui internal changes.
  20. // 2017/08/26: cleanup, optimizations, support for ImFontConfig::RasterizerFlags, ImFontConfig::RasterizerMultiply.
  21. // 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.
  22. // About Gamma Correct Blending:
  23. // - FreeType assumes blending in linear space rather than gamma space.
  24. // - See https://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#FT_Render_Glyph
  25. // - For correct results you need to be using sRGB and convert to linear space in the pixel shader output.
  26. // - The default dear imgui styles will be impacted by this change (alpha values will need tweaking).
  27. // FIXME: cfg.OversampleH, OversampleV are not supported (but perhaps not so necessary with this rasterizer).
  28. #include "imgui_freetype.h"
  29. #include "imgui_internal.h" // ImMin,ImMax,ImFontAtlasBuild*,
  30. #include <stdint.h>
  31. #include <ft2build.h>
  32. #include FT_FREETYPE_H // <freetype/freetype.h>
  33. #include FT_MODULE_H // <freetype/ftmodapi.h>
  34. #include FT_GLYPH_H // <freetype/ftglyph.h>
  35. #include FT_SYNTHESIS_H // <freetype/ftsynth.h>
  36. #ifdef _MSC_VER
  37. #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
  38. #endif
  39. #if defined(__GNUC__)
  40. #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
  41. #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
  42. #endif
  43. //-------------------------------------------------------------------------
  44. // Data
  45. //-------------------------------------------------------------------------
  46. // Default memory allocators
  47. static void* ImGuiFreeTypeDefaultAllocFunc(size_t size, void* user_data) { IM_UNUSED(user_data); return IM_ALLOC(size); }
  48. static void ImGuiFreeTypeDefaultFreeFunc(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_FREE(ptr); }
  49. // Current memory allocators
  50. static void* (*GImGuiFreeTypeAllocFunc)(size_t size, void* user_data) = ImGuiFreeTypeDefaultAllocFunc;
  51. static void (*GImGuiFreeTypeFreeFunc)(void* ptr, void* user_data) = ImGuiFreeTypeDefaultFreeFunc;
  52. static void* GImGuiFreeTypeAllocatorUserData = NULL;
  53. //-------------------------------------------------------------------------
  54. // Code
  55. //-------------------------------------------------------------------------
  56. namespace
  57. {
  58. // Glyph metrics:
  59. // --------------
  60. //
  61. // xmin xmax
  62. // | |
  63. // |<-------- width -------->|
  64. // | |
  65. // | +-------------------------+----------------- ymax
  66. // | | ggggggggg ggggg | ^ ^
  67. // | | g:::::::::ggg::::g | | |
  68. // | | g:::::::::::::::::g | | |
  69. // | | g::::::ggggg::::::gg | | |
  70. // | | g:::::g g:::::g | | |
  71. // offsetX -|-------->| g:::::g g:::::g | offsetY |
  72. // | | g:::::g g:::::g | | |
  73. // | | g::::::g g:::::g | | |
  74. // | | g:::::::ggggg:::::g | | |
  75. // | | g::::::::::::::::g | | height
  76. // | | gg::::::::::::::g | | |
  77. // baseline ---*---------|---- gggggggg::::::g-----*-------- |
  78. // / | | g:::::g | |
  79. // origin | | gggggg g:::::g | |
  80. // | | g:::::gg gg:::::g | |
  81. // | | g::::::ggg:::::::g | |
  82. // | | gg:::::::::::::g | |
  83. // | | ggg::::::ggg | |
  84. // | | gggggg | v
  85. // | +-------------------------+----------------- ymin
  86. // | |
  87. // |------------- advanceX ----------->|
  88. // A structure that describe a glyph.
  89. struct GlyphInfo
  90. {
  91. int Width; // Glyph's width in pixels.
  92. int Height; // Glyph's height in pixels.
  93. FT_Int OffsetX; // The distance from the origin ("pen position") to the left of the glyph.
  94. FT_Int OffsetY; // The distance from the origin to the top of the glyph. This is usually a value < 0.
  95. float AdvanceX; // The distance from the origin to the origin of the next glyph. This is usually a value > 0.
  96. bool IsColored; // The glyph is colored
  97. };
  98. // Font parameters and metrics.
  99. struct FontInfo
  100. {
  101. uint32_t PixelHeight; // Size this font was generated with.
  102. float Ascender; // The pixel extents above the baseline in pixels (typically positive).
  103. float Descender; // The extents below the baseline in pixels (typically negative).
  104. 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.
  105. float LineGap; // The spacing in pixels between one row's descent and the next row's ascent.
  106. float MaxAdvanceWidth; // This field gives the maximum horizontal cursor advance for all glyphs in the font.
  107. };
  108. // FreeType glyph rasterizer.
  109. // NB: No ctor/dtor, explicitly call Init()/Shutdown()
  110. struct FreeTypeFont
  111. {
  112. 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.
  113. void CloseFont();
  114. void SetPixelHeight(int pixel_height); // Change font pixel size. All following calls to RasterizeGlyph() will use this size
  115. const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint);
  116. const FT_Bitmap* RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info);
  117. void BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table = NULL);
  118. ~FreeTypeFont() { CloseFont(); }
  119. // [Internals]
  120. FontInfo Info; // Font descriptor of the current font.
  121. FT_Face Face;
  122. unsigned int UserFlags; // = ImFontConfig::RasterizerFlags
  123. FT_Int32 LoadFlags;
  124. FT_Render_Mode RenderMode;
  125. };
  126. // From SDL_ttf: Handy routines for converting from fixed point
  127. #define FT_CEIL(X) (((X + 63) & -64) / 64)
  128. bool FreeTypeFont::InitFont(FT_Library ft_library, const ImFontConfig& cfg, unsigned int extra_font_builder_flags)
  129. {
  130. FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)cfg.FontData, (uint32_t)cfg.FontDataSize, (uint32_t)cfg.FontNo, &Face);
  131. if (error != 0)
  132. return false;
  133. error = FT_Select_Charmap(Face, FT_ENCODING_UNICODE);
  134. if (error != 0)
  135. return false;
  136. memset(&Info, 0, sizeof(Info));
  137. SetPixelHeight((uint32_t)cfg.SizePixels);
  138. // Convert to FreeType flags (NB: Bold and Oblique are processed separately)
  139. UserFlags = cfg.FontBuilderFlags | extra_font_builder_flags;
  140. LoadFlags = FT_LOAD_NO_BITMAP;
  141. if (UserFlags & ImGuiFreeTypeBuilderFlags_NoHinting)
  142. LoadFlags |= FT_LOAD_NO_HINTING;
  143. if (UserFlags & ImGuiFreeTypeBuilderFlags_NoAutoHint)
  144. LoadFlags |= FT_LOAD_NO_AUTOHINT;
  145. if (UserFlags & ImGuiFreeTypeBuilderFlags_ForceAutoHint)
  146. LoadFlags |= FT_LOAD_FORCE_AUTOHINT;
  147. if (UserFlags & ImGuiFreeTypeBuilderFlags_LightHinting)
  148. LoadFlags |= FT_LOAD_TARGET_LIGHT;
  149. else if (UserFlags & ImGuiFreeTypeBuilderFlags_MonoHinting)
  150. LoadFlags |= FT_LOAD_TARGET_MONO;
  151. else
  152. LoadFlags |= FT_LOAD_TARGET_NORMAL;
  153. if (UserFlags & ImGuiFreeTypeBuilderFlags_Monochrome)
  154. RenderMode = FT_RENDER_MODE_MONO;
  155. else
  156. RenderMode = FT_RENDER_MODE_NORMAL;
  157. if (UserFlags & ImGuiFreeTypeBuilderFlags_LoadColor)
  158. LoadFlags |= FT_LOAD_COLOR;
  159. return true;
  160. }
  161. void FreeTypeFont::CloseFont()
  162. {
  163. if (Face)
  164. {
  165. FT_Done_Face(Face);
  166. Face = NULL;
  167. }
  168. }
  169. void FreeTypeFont::SetPixelHeight(int pixel_height)
  170. {
  171. // Vuhdo: I'm not sure how to deal with font sizes properly. As far as I understand, currently ImGui assumes that the 'pixel_height'
  172. // 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.
  173. // NB: FT_Set_Pixel_Sizes() doesn't seem to get us the same result.
  174. FT_Size_RequestRec req;
  175. req.type = FT_SIZE_REQUEST_TYPE_REAL_DIM;
  176. req.width = 0;
  177. req.height = (uint32_t)pixel_height * 64;
  178. req.horiResolution = 0;
  179. req.vertResolution = 0;
  180. FT_Request_Size(Face, &req);
  181. // Update font info
  182. FT_Size_Metrics metrics = Face->size->metrics;
  183. Info.PixelHeight = (uint32_t)pixel_height;
  184. Info.Ascender = (float)FT_CEIL(metrics.ascender);
  185. Info.Descender = (float)FT_CEIL(metrics.descender);
  186. Info.LineSpacing = (float)FT_CEIL(metrics.height);
  187. Info.LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender);
  188. Info.MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance);
  189. }
  190. const FT_Glyph_Metrics* FreeTypeFont::LoadGlyph(uint32_t codepoint)
  191. {
  192. uint32_t glyph_index = FT_Get_Char_Index(Face, codepoint);
  193. if (glyph_index == 0)
  194. return NULL;
  195. FT_Error error = FT_Load_Glyph(Face, glyph_index, LoadFlags);
  196. if (error)
  197. return NULL;
  198. // Need an outline for this to work
  199. FT_GlyphSlot slot = Face->glyph;
  200. IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE);
  201. // Apply convenience transform (this is not picking from real "Bold"/"Italic" fonts! Merely applying FreeType helper transform. Oblique == Slanting)
  202. if (UserFlags & ImGuiFreeTypeBuilderFlags_Bold)
  203. FT_GlyphSlot_Embolden(slot);
  204. if (UserFlags & ImGuiFreeTypeBuilderFlags_Oblique)
  205. {
  206. FT_GlyphSlot_Oblique(slot);
  207. //FT_BBox bbox;
  208. //FT_Outline_Get_BBox(&slot->outline, &bbox);
  209. //slot->metrics.width = bbox.xMax - bbox.xMin;
  210. //slot->metrics.height = bbox.yMax - bbox.yMin;
  211. }
  212. return &slot->metrics;
  213. }
  214. const FT_Bitmap* FreeTypeFont::RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info)
  215. {
  216. FT_GlyphSlot slot = Face->glyph;
  217. FT_Error error = FT_Render_Glyph(slot, RenderMode);
  218. if (error != 0)
  219. return NULL;
  220. FT_Bitmap* ft_bitmap = &Face->glyph->bitmap;
  221. out_glyph_info->Width = (int)ft_bitmap->width;
  222. out_glyph_info->Height = (int)ft_bitmap->rows;
  223. out_glyph_info->OffsetX = Face->glyph->bitmap_left;
  224. out_glyph_info->OffsetY = -Face->glyph->bitmap_top;
  225. out_glyph_info->AdvanceX = (float)FT_CEIL(slot->advance.x);
  226. out_glyph_info->IsColored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA);
  227. return ft_bitmap;
  228. }
  229. void FreeTypeFont::BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table)
  230. {
  231. IM_ASSERT(ft_bitmap != NULL);
  232. const uint32_t w = ft_bitmap->width;
  233. const uint32_t h = ft_bitmap->rows;
  234. const uint8_t* src = ft_bitmap->buffer;
  235. const uint32_t src_pitch = ft_bitmap->pitch;
  236. switch (ft_bitmap->pixel_mode)
  237. {
  238. case FT_PIXEL_MODE_GRAY: // Grayscale image, 1 byte per pixel.
  239. {
  240. if (multiply_table == NULL)
  241. {
  242. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  243. for (uint32_t x = 0; x < w; x++)
  244. dst[x] = IM_COL32(255, 255, 255, src[x]);
  245. }
  246. else
  247. {
  248. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  249. for (uint32_t x = 0; x < w; x++)
  250. dst[x] = IM_COL32(255, 255, 255, multiply_table[src[x]]);
  251. }
  252. break;
  253. }
  254. case FT_PIXEL_MODE_MONO: // Monochrome image, 1 bit per pixel. The bits in each byte are ordered from MSB to LSB.
  255. {
  256. uint8_t color0 = multiply_table ? multiply_table[0] : 0;
  257. uint8_t color1 = multiply_table ? multiply_table[255] : 255;
  258. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  259. {
  260. uint8_t bits = 0;
  261. const uint8_t* bits_ptr = src;
  262. for (uint32_t x = 0; x < w; x++, bits <<= 1)
  263. {
  264. if ((x & 7) == 0)
  265. bits = *bits_ptr++;
  266. dst[x] = IM_COL32(255, 255, 255, (bits & 0x80) ? color1 : color0);
  267. }
  268. }
  269. break;
  270. }
  271. case FT_PIXEL_MODE_BGRA:
  272. {
  273. // FIXME: Converting pre-multiplied alpha to straight. Doesn't smell good.
  274. #define DE_MULTIPLY(color, alpha) (ImU32)(255.0f * (float)color / (float)alpha + 0.5f)
  275. if (multiply_table == NULL)
  276. {
  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. }
  284. else
  285. {
  286. for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
  287. {
  288. for (uint32_t x = 0; x < w; x++)
  289. {
  290. uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3];
  291. 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]);
  292. }
  293. }
  294. }
  295. #undef DE_MULTIPLY
  296. break;
  297. }
  298. default:
  299. IM_ASSERT(0 && "FreeTypeFont::BlitGlyph(): Unknown bitmap pixel mode!");
  300. }
  301. }
  302. }
  303. #ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds)
  304. #ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
  305. #define STBRP_ASSERT(x) do { IM_ASSERT(x); } while (0)
  306. #define STBRP_STATIC
  307. #define STB_RECT_PACK_IMPLEMENTATION
  308. #endif
  309. #ifdef IMGUI_STB_RECT_PACK_FILENAME
  310. #include IMGUI_STB_RECT_PACK_FILENAME
  311. #else
  312. #include "imstb_rectpack.h"
  313. #endif
  314. #endif
  315. struct ImFontBuildSrcGlyphFT
  316. {
  317. GlyphInfo Info;
  318. uint32_t Codepoint;
  319. unsigned int* BitmapData; // Point within one of the dst_tmp_bitmap_buffers[] array
  320. ImFontBuildSrcGlyphFT() { memset(this, 0, sizeof(*this)); }
  321. };
  322. struct ImFontBuildSrcDataFT
  323. {
  324. FreeTypeFont Font;
  325. stbrp_rect* Rects; // Rectangle to pack. We first fill in their size and the packer will give us their position.
  326. const ImWchar* SrcRanges; // Ranges as requested by user (user is allowed to request too much, e.g. 0x0020..0xFFFF)
  327. int DstIndex; // Index into atlas->Fonts[] and dst_tmp_array[]
  328. int GlyphsHighest; // Highest requested codepoint
  329. int GlyphsCount; // Glyph count (excluding missing glyphs and glyphs already set by an earlier source font)
  330. ImBitVector GlyphsSet; // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB)
  331. ImVector<ImFontBuildSrcGlyphFT> GlyphsList;
  332. };
  333. // Temporary data for one destination ImFont* (multiple source fonts can be merged into one destination ImFont)
  334. struct ImFontBuildDstDataFT
  335. {
  336. int SrcCount; // Number of source fonts targeting this destination font.
  337. int GlyphsHighest;
  338. int GlyphsCount;
  339. ImBitVector GlyphsSet; // This is used to resolve collision when multiple sources are merged into a same destination font.
  340. };
  341. bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, unsigned int extra_flags)
  342. {
  343. IM_ASSERT(atlas->ConfigData.Size > 0);
  344. ImFontAtlasBuildInit(atlas);
  345. // Clear atlas
  346. atlas->TexID = (ImTextureID)NULL;
  347. atlas->TexWidth = atlas->TexHeight = 0;
  348. atlas->TexUvScale = ImVec2(0.0f, 0.0f);
  349. atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f);
  350. atlas->ClearTexData();
  351. // Temporary storage for building
  352. bool src_load_color = false;
  353. ImVector<ImFontBuildSrcDataFT> src_tmp_array;
  354. ImVector<ImFontBuildDstDataFT> dst_tmp_array;
  355. src_tmp_array.resize(atlas->ConfigData.Size);
  356. dst_tmp_array.resize(atlas->Fonts.Size);
  357. memset((void*)src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes());
  358. memset((void*)dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes());
  359. // 1. Initialize font loading structure, check font data validity
  360. for (int src_i = 0; src_i < atlas->ConfigData.Size; src_i++)
  361. {
  362. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  363. ImFontConfig& cfg = atlas->ConfigData[src_i];
  364. FreeTypeFont& font_face = src_tmp.Font;
  365. IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == atlas));
  366. // Find index from cfg.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices)
  367. src_tmp.DstIndex = -1;
  368. for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++)
  369. if (cfg.DstFont == atlas->Fonts[output_i])
  370. src_tmp.DstIndex = output_i;
  371. IM_ASSERT(src_tmp.DstIndex != -1); // cfg.DstFont not pointing within atlas->Fonts[] array?
  372. if (src_tmp.DstIndex == -1)
  373. return false;
  374. // Load font
  375. if (!font_face.InitFont(ft_library, cfg, extra_flags))
  376. return false;
  377. // Measure highest codepoints
  378. src_load_color |= (cfg.FontBuilderFlags & ImGuiFreeTypeBuilderFlags_LoadColor) != 0;
  379. ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
  380. src_tmp.SrcRanges = cfg.GlyphRanges ? cfg.GlyphRanges : atlas->GetGlyphRangesDefault();
  381. for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)
  382. src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]);
  383. dst_tmp.SrcCount++;
  384. dst_tmp.GlyphsHighest = ImMax(dst_tmp.GlyphsHighest, src_tmp.GlyphsHighest);
  385. }
  386. // 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.
  387. int total_glyphs_count = 0;
  388. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  389. {
  390. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  391. ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
  392. src_tmp.GlyphsSet.Create(src_tmp.GlyphsHighest + 1);
  393. if (dst_tmp.GlyphsSet.Storage.empty())
  394. dst_tmp.GlyphsSet.Create(dst_tmp.GlyphsHighest + 1);
  395. for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)
  396. for (int codepoint = src_range[0]; codepoint <= (int)src_range[1]; codepoint++)
  397. {
  398. if (dst_tmp.GlyphsSet.TestBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option (e.g. MergeOverwrite)
  399. continue;
  400. 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..)
  401. if (glyph_index == 0)
  402. continue;
  403. // Add to avail set/counters
  404. src_tmp.GlyphsCount++;
  405. dst_tmp.GlyphsCount++;
  406. src_tmp.GlyphsSet.SetBit(codepoint);
  407. dst_tmp.GlyphsSet.SetBit(codepoint);
  408. total_glyphs_count++;
  409. }
  410. }
  411. // 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)
  412. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  413. {
  414. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  415. src_tmp.GlyphsList.reserve(src_tmp.GlyphsCount);
  416. IM_ASSERT(sizeof(src_tmp.GlyphsSet.Storage.Data[0]) == sizeof(ImU32));
  417. const ImU32* it_begin = src_tmp.GlyphsSet.Storage.begin();
  418. const ImU32* it_end = src_tmp.GlyphsSet.Storage.end();
  419. for (const ImU32* it = it_begin; it < it_end; it++)
  420. if (ImU32 entries_32 = *it)
  421. for (ImU32 bit_n = 0; bit_n < 32; bit_n++)
  422. if (entries_32 & ((ImU32)1 << bit_n))
  423. {
  424. ImFontBuildSrcGlyphFT src_glyph;
  425. src_glyph.Codepoint = (ImWchar)(((it - it_begin) << 5) + bit_n);
  426. //src_glyph.GlyphIndex = 0; // FIXME-OPT: We had this info in the previous step and lost it..
  427. src_tmp.GlyphsList.push_back(src_glyph);
  428. }
  429. src_tmp.GlyphsSet.Clear();
  430. IM_ASSERT(src_tmp.GlyphsList.Size == src_tmp.GlyphsCount);
  431. }
  432. for (int dst_i = 0; dst_i < dst_tmp_array.Size; dst_i++)
  433. dst_tmp_array[dst_i].GlyphsSet.Clear();
  434. dst_tmp_array.clear();
  435. // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0)
  436. // (We technically don't need to zero-clear buf_rects, but let's do it for the sake of sanity)
  437. ImVector<stbrp_rect> buf_rects;
  438. buf_rects.resize(total_glyphs_count);
  439. memset(buf_rects.Data, 0, (size_t)buf_rects.size_in_bytes());
  440. // Allocate temporary rasterization data buffers.
  441. // We could not find a way to retrieve accurate glyph size without rendering them.
  442. // (e.g. slot->metrics->width not always matching bitmap->width, especially considering the Oblique transform)
  443. // We allocate in chunks of 256 KB to not waste too much extra memory ahead. Hopefully users of FreeType won't find the temporary allocations.
  444. const int BITMAP_BUFFERS_CHUNK_SIZE = 256 * 1024;
  445. int buf_bitmap_current_used_bytes = 0;
  446. ImVector<unsigned char*> buf_bitmap_buffers;
  447. buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE));
  448. // 4. Gather glyphs sizes so we can pack them in our virtual canvas.
  449. // 8. Render/rasterize font characters into the texture
  450. int total_surface = 0;
  451. int buf_rects_out_n = 0;
  452. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  453. {
  454. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  455. ImFontConfig& cfg = atlas->ConfigData[src_i];
  456. if (src_tmp.GlyphsCount == 0)
  457. continue;
  458. src_tmp.Rects = &buf_rects[buf_rects_out_n];
  459. buf_rects_out_n += src_tmp.GlyphsCount;
  460. // Compute multiply table if requested
  461. const bool multiply_enabled = (cfg.RasterizerMultiply != 1.0f);
  462. unsigned char multiply_table[256];
  463. if (multiply_enabled)
  464. ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, cfg.RasterizerMultiply);
  465. // Gather the sizes of all rectangles we will need to pack
  466. const int padding = atlas->TexGlyphPadding;
  467. for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++)
  468. {
  469. ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i];
  470. const FT_Glyph_Metrics* metrics = src_tmp.Font.LoadGlyph(src_glyph.Codepoint);
  471. if (metrics == NULL)
  472. continue;
  473. // Render glyph into a bitmap (currently held by FreeType)
  474. const FT_Bitmap* ft_bitmap = src_tmp.Font.RenderGlyphAndGetInfo(&src_glyph.Info);
  475. IM_ASSERT(ft_bitmap);
  476. // Allocate new temporary chunk if needed
  477. const int bitmap_size_in_bytes = src_glyph.Info.Width * src_glyph.Info.Height * 4;
  478. if (buf_bitmap_current_used_bytes + bitmap_size_in_bytes > BITMAP_BUFFERS_CHUNK_SIZE)
  479. {
  480. buf_bitmap_current_used_bytes = 0;
  481. buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE));
  482. }
  483. // Blit rasterized pixels to our temporary buffer and keep a pointer to it.
  484. src_glyph.BitmapData = (unsigned int*)(buf_bitmap_buffers.back() + buf_bitmap_current_used_bytes);
  485. buf_bitmap_current_used_bytes += bitmap_size_in_bytes;
  486. src_tmp.Font.BlitGlyph(ft_bitmap, src_glyph.BitmapData, src_glyph.Info.Width, multiply_enabled ? multiply_table : NULL);
  487. src_tmp.Rects[glyph_i].w = (stbrp_coord)(src_glyph.Info.Width + padding);
  488. src_tmp.Rects[glyph_i].h = (stbrp_coord)(src_glyph.Info.Height + padding);
  489. total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h;
  490. }
  491. }
  492. // We need a width for the skyline algorithm, any width!
  493. // The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height.
  494. // User can override TexDesiredWidth and TexGlyphPadding if they wish, otherwise we use a simple heuristic to select the width based on expected surface.
  495. const int surface_sqrt = (int)ImSqrt((float)total_surface) + 1;
  496. atlas->TexHeight = 0;
  497. if (atlas->TexDesiredWidth > 0)
  498. atlas->TexWidth = atlas->TexDesiredWidth;
  499. else
  500. atlas->TexWidth = (surface_sqrt >= 4096 * 0.7f) ? 4096 : (surface_sqrt >= 2048 * 0.7f) ? 2048 : (surface_sqrt >= 1024 * 0.7f) ? 1024 : 512;
  501. // 5. Start packing
  502. // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values).
  503. const int TEX_HEIGHT_MAX = 1024 * 32;
  504. const int num_nodes_for_packing_algorithm = atlas->TexWidth - atlas->TexGlyphPadding;
  505. ImVector<stbrp_node> pack_nodes;
  506. pack_nodes.resize(num_nodes_for_packing_algorithm);
  507. stbrp_context pack_context;
  508. stbrp_init_target(&pack_context, atlas->TexWidth, TEX_HEIGHT_MAX, pack_nodes.Data, pack_nodes.Size);
  509. ImFontAtlasBuildPackCustomRects(atlas, &pack_context);
  510. // 6. Pack each source font. No rendering yet, we are working with rectangles in an infinitely tall texture at this point.
  511. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  512. {
  513. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  514. if (src_tmp.GlyphsCount == 0)
  515. continue;
  516. stbrp_pack_rects(&pack_context, src_tmp.Rects, src_tmp.GlyphsCount);
  517. // Extend texture height and mark missing glyphs as non-packed so we won't render them.
  518. // 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?)
  519. for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
  520. if (src_tmp.Rects[glyph_i].was_packed)
  521. atlas->TexHeight = ImMax(atlas->TexHeight, src_tmp.Rects[glyph_i].y + src_tmp.Rects[glyph_i].h);
  522. }
  523. // 7. Allocate texture
  524. atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight);
  525. atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight);
  526. if (src_load_color)
  527. {
  528. atlas->TexPixelsRGBA32 = (unsigned int*)IM_ALLOC(atlas->TexWidth * atlas->TexHeight * 4);
  529. memset(atlas->TexPixelsRGBA32, 0, atlas->TexWidth * atlas->TexHeight * 4);
  530. }
  531. else
  532. {
  533. atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(atlas->TexWidth * atlas->TexHeight);
  534. memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight);
  535. }
  536. // 8. Copy rasterized font characters back into the main texture
  537. // 9. Setup ImFont and glyphs for runtime
  538. bool tex_use_colors = false;
  539. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  540. {
  541. ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
  542. if (src_tmp.GlyphsCount == 0)
  543. continue;
  544. // When merging fonts with MergeMode=true:
  545. // - We can have multiple input fonts writing into a same destination font.
  546. // - dst_font->ConfigData is != from cfg which is our source configuration.
  547. ImFontConfig& cfg = atlas->ConfigData[src_i];
  548. ImFont* dst_font = cfg.DstFont;
  549. const float ascent = src_tmp.Font.Info.Ascender;
  550. const float descent = src_tmp.Font.Info.Descender;
  551. ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent);
  552. const float font_off_x = cfg.GlyphOffset.x;
  553. const float font_off_y = cfg.GlyphOffset.y + IM_ROUND(dst_font->Ascent);
  554. const int padding = atlas->TexGlyphPadding;
  555. for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
  556. {
  557. ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i];
  558. stbrp_rect& pack_rect = src_tmp.Rects[glyph_i];
  559. IM_ASSERT(pack_rect.was_packed);
  560. if (pack_rect.w == 0 && pack_rect.h == 0)
  561. continue;
  562. GlyphInfo& info = src_glyph.Info;
  563. IM_ASSERT(info.Width + padding <= pack_rect.w);
  564. IM_ASSERT(info.Height + padding <= pack_rect.h);
  565. const int tx = pack_rect.x + padding;
  566. const int ty = pack_rect.y + padding;
  567. // Blit from temporary buffer to final texture
  568. size_t blit_src_stride = (size_t)src_glyph.Info.Width;
  569. size_t blit_dst_stride = (size_t)atlas->TexWidth;
  570. unsigned int* blit_src = src_glyph.BitmapData;
  571. if (atlas->TexPixelsAlpha8 != NULL)
  572. {
  573. unsigned char* blit_dst = atlas->TexPixelsAlpha8 + (ty * blit_dst_stride) + tx;
  574. for (int y = 0; y < info.Height; y++, blit_dst += blit_dst_stride, blit_src += blit_src_stride)
  575. for (int x = 0; x < info.Width; x++)
  576. blit_dst[x] = (unsigned char)((blit_src[x] >> IM_COL32_A_SHIFT) & 0xFF);
  577. }
  578. else
  579. {
  580. unsigned int* blit_dst = atlas->TexPixelsRGBA32 + (ty * blit_dst_stride) + tx;
  581. for (int y = 0; y < info.Height; y++, blit_dst += blit_dst_stride, blit_src += blit_src_stride)
  582. for (int x = 0; x < info.Width; x++)
  583. blit_dst[x] = blit_src[x];
  584. }
  585. // Register glyph
  586. float x0 = info.OffsetX + font_off_x;
  587. float y0 = info.OffsetY + font_off_y;
  588. float x1 = x0 + info.Width;
  589. float y1 = y0 + info.Height;
  590. float u0 = (tx) / (float)atlas->TexWidth;
  591. float v0 = (ty) / (float)atlas->TexHeight;
  592. float u1 = (tx + info.Width) / (float)atlas->TexWidth;
  593. float v1 = (ty + info.Height) / (float)atlas->TexHeight;
  594. dst_font->AddGlyph(&cfg, (ImWchar)src_glyph.Codepoint, x0, y0, x1, y1, u0, v0, u1, v1, info.AdvanceX);
  595. ImFontGlyph* dst_glyph = &dst_font->Glyphs.back();
  596. IM_ASSERT(dst_glyph->Codepoint == src_glyph.Codepoint);
  597. if (src_glyph.Info.IsColored)
  598. dst_glyph->Colored = tex_use_colors = true;
  599. }
  600. src_tmp.Rects = NULL;
  601. }
  602. atlas->TexPixelsUseColors = tex_use_colors;
  603. // Cleanup
  604. for (int buf_i = 0; buf_i < buf_bitmap_buffers.Size; buf_i++)
  605. IM_FREE(buf_bitmap_buffers[buf_i]);
  606. for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
  607. src_tmp_array[src_i].~ImFontBuildSrcDataFT();
  608. ImFontAtlasBuildFinish(atlas);
  609. return true;
  610. }
  611. // FreeType memory allocation callbacks
  612. static void* FreeType_Alloc(FT_Memory /*memory*/, long size)
  613. {
  614. return GImGuiFreeTypeAllocFunc((size_t)size, GImGuiFreeTypeAllocatorUserData);
  615. }
  616. static void FreeType_Free(FT_Memory /*memory*/, void* block)
  617. {
  618. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  619. }
  620. static void* FreeType_Realloc(FT_Memory /*memory*/, long cur_size, long new_size, void* block)
  621. {
  622. // Implement realloc() as we don't ask user to provide it.
  623. if (block == NULL)
  624. return GImGuiFreeTypeAllocFunc((size_t)new_size, GImGuiFreeTypeAllocatorUserData);
  625. if (new_size == 0)
  626. {
  627. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  628. return NULL;
  629. }
  630. if (new_size > cur_size)
  631. {
  632. void* new_block = GImGuiFreeTypeAllocFunc((size_t)new_size, GImGuiFreeTypeAllocatorUserData);
  633. memcpy(new_block, block, (size_t)cur_size);
  634. GImGuiFreeTypeFreeFunc(block, GImGuiFreeTypeAllocatorUserData);
  635. return new_block;
  636. }
  637. return block;
  638. }
  639. static bool ImFontAtlasBuildWithFreeType(ImFontAtlas* atlas)
  640. {
  641. // FreeType memory management: https://www.freetype.org/freetype2/docs/design/design-4.html
  642. FT_MemoryRec_ memory_rec = {};
  643. memory_rec.user = NULL;
  644. memory_rec.alloc = &FreeType_Alloc;
  645. memory_rec.free = &FreeType_Free;
  646. memory_rec.realloc = &FreeType_Realloc;
  647. // https://www.freetype.org/freetype2/docs/reference/ft2-module_management.html#FT_New_Library
  648. FT_Library ft_library;
  649. FT_Error error = FT_New_Library(&memory_rec, &ft_library);
  650. if (error != 0)
  651. return false;
  652. // If you don't call FT_Add_Default_Modules() the rest of code may work, but FreeType won't use our custom allocator.
  653. FT_Add_Default_Modules(ft_library);
  654. bool ret = ImFontAtlasBuildWithFreeTypeEx(ft_library, atlas, atlas->FontBuilderFlags);
  655. FT_Done_Library(ft_library);
  656. return ret;
  657. }
  658. const ImFontBuilderIO* ImGuiFreeType::GetBuilderForFreeType()
  659. {
  660. static ImFontBuilderIO io;
  661. io.FontBuilder_Build = ImFontAtlasBuildWithFreeType;
  662. return &io;
  663. }
  664. void ImGuiFreeType::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
  665. {
  666. GImGuiFreeTypeAllocFunc = alloc_func;
  667. GImGuiFreeTypeFreeFunc = free_func;
  668. GImGuiFreeTypeAllocatorUserData = user_data;
  669. }