MyGUI 3.5.3
MyGUI_ResourceTrueTypeFont.cpp
Go to the documentation of this file.
1/*
2 * This source file is part of MyGUI. For the latest info, see http://mygui.info/
3 * Distributed under the MIT License
4 * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
5 */
6
7#include "MyGUI_Precompiled.h"
9#include "MyGUI_DataManager.h"
11#include "MyGUI_RenderManager.h"
12#include "MyGUI_Bitwise.h"
13#include "MyGUI_Gui.h"
14
15#ifdef MYGUI_USE_FREETYPE
16
17 #include <ft2build.h>
18 #include FT_FREETYPE_H
19 #include FT_GLYPH_H
20 #include FT_TRUETYPE_TABLES_H
21 #include FT_BITMAP_H
22 #include FT_WINFONTS_H
23
24 #ifdef MYGUI_MSDF_FONTS
25 #include "msdfgen.h"
26 #include "msdfgen-ext.h"
27 #endif
28
29#endif // MYGUI_USE_FREETYPE
30
31#include <pugixml.hpp>
32
33namespace MyGUI
34{
35
36#ifndef MYGUI_USE_FREETYPE
37 ResourceTrueTypeFont::~ResourceTrueTypeFont() = default;
38
39 void ResourceTrueTypeFont::deserialization(xml::ElementPtr _node, Version _version)
40 {
41 Base::deserialization(_node, _version);
43 Error,
44 "ResourceTrueTypeFont: TrueType font '"
45 << getResourceName() << "' disabled. Define MYGUI_USE_FREETYPE if you need TrueType fonts.");
46 }
47
48 const GlyphInfo* ResourceTrueTypeFont::getGlyphInfo(Char _id) const
49 {
50 return nullptr;
51 }
52
53 ITexture* ResourceTrueTypeFont::getTextureFont() const
54 {
55 return nullptr;
56 }
57
58 int ResourceTrueTypeFont::getDefaultHeight() const
59 {
60 return 0;
61 }
62
63 void ResourceTrueTypeFont::textureInvalidate(ITexture* _texture)
64 {
65 }
66
67 std::vector<std::pair<Char, Char>> ResourceTrueTypeFont::getCodePointRanges() const
68 {
69 return std::vector<std::pair<Char, Char>>();
70 }
71
72 Char ResourceTrueTypeFont::getSubstituteCodePoint() const
73 {
74 return Char();
75 }
76
77 void ResourceTrueTypeFont::initialise()
78 {
79 }
80
81 void ResourceTrueTypeFont::setSource(std::string_view _value)
82 {
83 }
84
85 void ResourceTrueTypeFont::setShader(std::string_view _value)
86 {
87 }
88
89 void ResourceTrueTypeFont::setSize(float _value)
90 {
91 }
92
93 void ResourceTrueTypeFont::setResolution(unsigned int _value)
94 {
95 }
96
97 void ResourceTrueTypeFont::setHinting(std::string_view _value)
98 {
99 }
100
101 void ResourceTrueTypeFont::setAntialias(bool _value)
102 {
103 }
104
105 void ResourceTrueTypeFont::setTabWidth(float _value)
106 {
107 }
108
109 void ResourceTrueTypeFont::setOffsetHeight(int _value)
110 {
111 }
112
113 void ResourceTrueTypeFont::setSubstituteCode(int _value)
114 {
115 }
116
117 void ResourceTrueTypeFont::setDistance(int _value)
118 {
119 }
120
121 void ResourceTrueTypeFont::setMsdfMode(bool _value)
122 {
123 }
124
125 void ResourceTrueTypeFont::setMsdfRange(int _value)
126 {
127 }
128
129 void ResourceTrueTypeFont::addCodePointRange(Char _first, Char _second)
130 {
131 }
132
133 void ResourceTrueTypeFont::removeCodePointRange(Char _first, Char _second)
134 {
135 }
136
137 void ResourceTrueTypeFont::setKerningEnabled(bool _value)
138 {
139 }
140
141 void ResourceTrueTypeFont::setDpiScale(float _value)
142 {
143 }
144
145 void ResourceTrueTypeFont::setAutoDpi(bool _value)
146 {
147 }
148
149 float ResourceTrueTypeFont::getKerning(Char _left, Char _right) const
150 {
151 return 0.0f;
152 }
153
154#else // MYGUI_USE_FREETYPE
155 namespace
156 {
157
158 template<typename T>
159 void setMax(T& _var, const T& _newValue)
160 {
161 if (_var < _newValue)
162 _var = _newValue;
163 }
164
165 const std::map<const Char, const uint8> charMask{
168 {FontCodeType::Cursor, 0xFF},
169 {FontCodeType::Tab, 0x00}};
170 const uint8 charMaskBlack = 0x00;
171 const uint8 charMaskWhite = 0xFF;
172
173 std::pair<int, int> integerGlyphSize(const GlyphInfo& _info, float _scale)
174 {
175 return {(int)std::ceil(_info.width * _scale), (int)std::ceil(_info.height * _scale)};
176 }
177
178 template<bool LAMode>
179 struct PixelBase
180 {
181 static PixelFormat::Enum getFormat()
182 {
183 if constexpr (LAMode)
184 return PixelFormat::L8A8;
185 else
186 return PixelFormat::R8G8B8A8;
187 }
188
189 static size_t getNumBytes()
190 {
191 if constexpr (LAMode)
192 return 2;
193 else
194 return 4;
195 }
196
197 protected:
198 // Sets a pixel in _dest as 4 or 2 bytes: L8L8L8A8 if LAMode is false, or L8A8 if LAMode is true.
199 // Automatically advances _dest just past the pixel written.
200 static void set(uint8*& _dest, uint8 _luminance, uint8 _alpha)
201 {
202 if constexpr (LAMode)
203 {
204 *_dest++ = _luminance;
205 *_dest++ = _alpha;
206 }
207 else
208 {
209 *_dest++ = _luminance;
210 *_dest++ = _luminance;
211 *_dest++ = _luminance;
212 *_dest++ = _alpha;
213 }
214 }
215 };
216
217 template<bool LAMode, bool FromSource = false, bool Antialias = false>
218 struct Pixel : PixelBase<LAMode>
219 {
220 // Sets a pixel in _dest as 4 or 2 bytes: L8L8L8A8 if LAMode is false, or L8A8 if LAMode is true.
221 // Sets luminance from _source if both FromSource and Antialias are true; otherwise, uses the specified value.
222 // Sets alpha from _source if FromSource is true; otherwise, uses the specified value.
223 // Automatically advances _source just past the pixel read if FromSource is true.
224 // Automatically advances _dest just past the pixel written.
225 static void set(uint8*& _dest, uint8 _luminance, uint8 _alpha, uint8*& _source)
226 {
227 if constexpr (FromSource)
228 {
229 (void)_alpha;
230 if constexpr (Antialias)
231 {
232 (void)_luminance;
233 // Sets the destination pixel using both the luminance and alpha from the specified source.
234 PixelBase<LAMode>::set(_dest, *_source, *_source);
235 }
236 else
237 {
238 // Sets the destination pixel using the specified _luminance and alpha from the specified source.
239 PixelBase<LAMode>::set(_dest, _luminance, *_source);
240 }
241 ++_source;
242 }
243 else
244 {
245 (void)_source;
246 // Sets the destination pixel using the specified luminance and alpha. Source is ignored.
247 PixelBase<LAMode>::set(_dest, _luminance, _alpha);
248 }
249 }
250 };
251
252 }
253
254 const int ResourceTrueTypeFont::mDefaultGlyphSpacing = 1;
255 const float ResourceTrueTypeFont::mDefaultTabWidth = 8.0f;
256 const float ResourceTrueTypeFont::mSelectedWidth = 1.0f;
257 const float ResourceTrueTypeFont::mCursorWidth = 2.0f;
258
259 ResourceTrueTypeFont::~ResourceTrueTypeFont()
260 {
261 if (mTexture != nullptr)
262 {
263 RenderManager::getInstance().destroyTexture(mTexture);
264 mTexture = nullptr;
265 }
266 }
267
268 void ResourceTrueTypeFont::deserialization(xml::ElementPtr _node, Version _version)
269 {
270 Base::deserialization(_node, _version);
271
272 for (auto node : _node.node())
273 {
274 if (node.name() == std::string_view("Property"))
275 {
276 std::string_view key = node.attribute("key").value();
277 std::string_view value = node.attribute("value").value();
278 if (key == "Source")
279 setSource(value);
280 else if (key == "Shader")
281 setShader(value);
282 else if (key == "Size")
283 setSize(utility::parseFloat(value));
284 else if (key == "Resolution")
285 setResolution(utility::parseUInt(value));
286 else if (key == "Antialias")
287 setAntialias(utility::parseBool(value));
288 else if (key == "TabWidth")
289 setTabWidth(utility::parseFloat(value));
290 else if (key == "OffsetHeight")
291 setOffsetHeight(utility::parseInt(value));
292 else if (key == "SubstituteCode")
293 setSubstituteCode(utility::parseInt(value));
294 else if (key == "Distance")
295 setDistance(utility::parseInt(value));
296 else if (key == "Hinting")
297 setHinting(value);
298 else if (key == "SpaceWidth")
299 {
300 mSpaceWidth = utility::parseFloat(value);
301 MYGUI_LOG(
302 Warning,
303 _node.node().attribute("type").value()
304 << ": Property '" << key << "' in font '" << _node.node().attribute("name").value()
305 << "' is deprecated; remove it to use automatic calculation.");
306 }
307 else if (key == "CursorWidth")
308 {
309 MYGUI_LOG(
310 Warning,
311 _node.node().attribute("type").value()
312 << ": Property '" << key << "' in font '" << _node.node().attribute("name").value()
313 << "' is deprecated; value ignored.");
314 }
315 else if (key == "MsdfMode")
316 setMsdfMode(utility::parseBool(value));
317 else if (key == "MsdfRange")
318 setMsdfRange(utility::parseInt(value));
319 else if (key == "Kerning")
320 setKerningEnabled(utility::parseBool(value));
321 else if (key == "DpiScale")
322 setDpiScale(utility::parseFloat(value));
323 else if (key == "AutoDpi")
324 setAutoDpi(utility::parseBool(value));
325 }
326 else if (node.name() == std::string_view("Codes"))
327 {
328 // Range of inclusions.
329 for (auto range : node.children("Code"))
330 {
331 std::string_view range_value{range.attribute("range").value()};
332 if (!range_value.empty())
333 {
334 std::vector<std::string> parse_range = utility::split(range_value);
335 if (!parse_range.empty())
336 {
337 Char first = utility::parseUInt(parse_range[0]);
338 Char last = parse_range.size() > 1 ? utility::parseUInt(parse_range[1]) : first;
339 addCodePointRange(first, last);
340 }
341 }
342 }
343
344 // If no code points have been included, include the Unicode Basic Multilingual Plane by default before processing
345 // any exclusions.
346 if (mCharMap.empty())
347 addCodePointRange(0, 0xFFFF);
348
349 // Range of exclusions.
350 for (auto range : node.children("Code"))
351 {
352 std::string_view range_value{range.attribute("hide").value()};
353 if (!range_value.empty())
354 {
355 std::vector<std::string> parse_range = utility::split(range_value);
356 if (!parse_range.empty())
357 {
358 Char first = utility::parseUInt(parse_range[0]);
359 Char last = parse_range.size() > 1 ? utility::parseUInt(parse_range[1]) : first;
360 removeCodePointRange(first, last);
361 }
362 }
363 }
364 }
365 }
366
367 initialise();
368 }
369
370 const GlyphInfo* ResourceTrueTypeFont::getGlyphInfo(Char _id) const
371 {
372 auto glyphIter = mGlyphMap.find(_id);
373
374 if (glyphIter != mGlyphMap.end())
375 {
376 return &glyphIter->second;
377 }
378
379 return mSubstituteGlyphInfo;
380 }
381
382 ITexture* ResourceTrueTypeFont::getTextureFont() const
383 {
384 return mTexture;
385 }
386
387 int ResourceTrueTypeFont::getDefaultHeight() const
388 {
389 return mDefaultHeight;
390 }
391
392 void ResourceTrueTypeFont::textureInvalidate(ITexture* _texture)
393 {
394 mGlyphMap.clear();
395 initialise();
396 }
397
398 std::vector<std::pair<Char, Char>> ResourceTrueTypeFont::getCodePointRanges() const
399 {
400 std::vector<std::pair<Char, Char>> result;
401
402 if (!mCharMap.empty())
403 {
404 auto iter = mCharMap.begin();
405 auto endIter = mCharMap.end();
406
407 // Start the first range with the first code point in the map.
408 Char rangeBegin = iter->first;
409 Char rangeEnd = rangeBegin;
410
411 // Loop over the rest of the map and find the contiguous ranges.
412 for (++iter; iter != endIter; ++iter)
413 {
414 if (iter->first == rangeEnd + 1)
415 {
416 // Extend the current range.
417 ++rangeEnd;
418 }
419 else
420 {
421 // Found the start of a new range. First, save the current range.
422 result.emplace_back(rangeBegin, rangeEnd);
423
424 // Then start the new range.
425 rangeBegin = rangeEnd = iter->first;
426 }
427 }
428
429 // Save the final range.
430 result.emplace_back(rangeBegin, rangeEnd);
431 }
432
433 return result;
434 }
435
436 Char ResourceTrueTypeFont::getSubstituteCodePoint() const
437 {
438 return mSubstituteCodePoint;
439 }
440
441 void ResourceTrueTypeFont::addCodePoint(Char _codePoint)
442 {
443 mCharMap.try_emplace(_codePoint, 0);
444 }
445
446 void ResourceTrueTypeFont::addCodePointRange(Char _first, Char _second)
447 {
448 CharMap::iterator positionHint = mCharMap.lower_bound(_first);
449
450 if (positionHint != mCharMap.begin())
451 --positionHint;
452
453 for (Char i = _first; i <= _second; ++i)
454 positionHint = mCharMap.insert(positionHint, CharMap::value_type(i, 0));
455 }
456
457 void ResourceTrueTypeFont::removeCodePointRange(Char _first, Char _second)
458 {
459 mCharMap.erase(mCharMap.lower_bound(_first), mCharMap.upper_bound(_second));
460 }
461
462 void ResourceTrueTypeFont::initialise()
463 {
464 if (mAutoDpi)
465 mDpiScale = Gui::getInstance().getDpiScale();
466
467 if (mMsdfMode)
468 mDpiScale = 1.0f;
469
470 if (mGlyphSpacing == -1)
471 mGlyphSpacing = mDefaultGlyphSpacing;
472
473 // If L8A8 (2 bytes per pixel) is supported, use it; otherwise, use R8G8B8A8 (4 bytes per pixel) as L8L8L8A8.
474 bool laMode = MyGUI::RenderManager::getInstance().isFormatSupported(
475 Pixel<true>::getFormat(),
476 TextureUsage::Static | TextureUsage::Write);
477 if (mMsdfMode)
478 laMode = false;
479
480 // Select and call an appropriate initialisation method. By making this decision up front, we avoid having to branch on
481 // these variables many thousands of times inside tight nested loops later. From this point on, the various function
482 // templates ensure that all the necessary branching is done purely at compile time for all combinations.
483 if (laMode)
484 {
485 if (mAntialias)
486 ResourceTrueTypeFont::initialiseFreeType<true, true>();
487 else
488 ResourceTrueTypeFont::initialiseFreeType<true, false>();
489 }
490 else
491 {
492 if (mAntialias)
493 ResourceTrueTypeFont::initialiseFreeType<false, true>();
494 else
495 ResourceTrueTypeFont::initialiseFreeType<false, false>();
496 }
497 }
498
499 template<bool LAMode, bool Antialias>
500 void ResourceTrueTypeFont::initialiseFreeType()
501 {
502 //-------------------------------------------------------------------//
503 // Initialise FreeType and load the font.
504 //-------------------------------------------------------------------//
505
506 FT_Library ftLibrary;
507
508 if (FT_Init_FreeType(&ftLibrary) != 0)
509 MYGUI_EXCEPT("ResourceTrueTypeFont: Could not init the FreeType library!");
510
511 std::vector<std::byte> fontBuffer;
512
513 FT_Face ftFace = loadFace(ftLibrary, fontBuffer);
514
515 if (ftFace == nullptr)
516 {
517 MYGUI_LOG(Error, "ResourceTrueTypeFont: Could not load the font '" << getResourceName() << "'!");
518 FT_Done_FreeType(ftLibrary);
519 return;
520 }
521
522 #ifdef MYGUI_MSDF_FONTS
523 msdfgen::FontHandle* msdfFont = nullptr;
524
525 if (mMsdfMode)
526 {
527 msdfFont = msdfgen::adoptFreetypeFont(ftFace);
528 mMsdfScale = (double)ftFace->size->metrics.x_ppem;
529 }
530 #endif
531
532 //-------------------------------------------------------------------//
533 // Calculate the font metrics.
534 //-------------------------------------------------------------------//
535
536 // The font's overall ascent and descent are defined in three different places in a TrueType font, and with different
537 // values in each place. The most reliable source for these metrics is usually the "usWinAscent" and "usWinDescent" pair of
538 // values in the OS/2 header; however, some fonts contain inaccurate data there. To be safe, we use the highest of the set
539 // of values contained in the face metrics and the two sets of values contained in the OS/2 header.
540 int fontAscent = ftFace->size->metrics.ascender >> 6;
541 int fontDescent = -ftFace->size->metrics.descender >> 6;
542
543 TT_OS2* os2 = (TT_OS2*)FT_Get_Sfnt_Table(ftFace, ft_sfnt_os2);
544
545 if (os2 != nullptr)
546 {
547 setMax(fontAscent, os2->usWinAscent * ftFace->size->metrics.y_ppem / ftFace->units_per_EM);
548 setMax(fontDescent, os2->usWinDescent * ftFace->size->metrics.y_ppem / ftFace->units_per_EM);
549
550 setMax(fontAscent, os2->sTypoAscender * ftFace->size->metrics.y_ppem / ftFace->units_per_EM);
551 setMax(fontDescent, -os2->sTypoDescender * ftFace->size->metrics.y_ppem / ftFace->units_per_EM);
552 }
553
554 // The nominal font height is calculated as the sum of its ascent and descent as specified by the font designer. Previously
555 // it was defined by MyGUI in terms of the maximum ascent and descent of the glyphs currently in use, but this caused the
556 // font's line spacing to change whenever glyphs were added to or removed from the font definition. Doing it this way
557 // instead prevents a lot of layout problems, and it is also more typographically correct and more aesthetically pleasing.
558 mDefaultHeight = fontAscent + fontDescent;
559
560 if (mDpiScale != 1.0f)
561 mDefaultHeight = static_cast<int>(std::ceil(mDefaultHeight / mDpiScale));
562
563 // Set the load flags based on the specified type of hinting.
564 FT_Int32 ftLoadFlags = FT_LOAD_DEFAULT;
565
566 switch (mHinting)
567 {
568 case HintingUseNative: ftLoadFlags = FT_LOAD_DEFAULT; break;
569 case HintingForceAuto: ftLoadFlags = FT_LOAD_FORCE_AUTOHINT; break;
570 case HintingDisableAuto: ftLoadFlags = FT_LOAD_NO_AUTOHINT; break;
571 case HintingMonochrome: ftLoadFlags = FT_LOAD_TARGET_MONO; break;
572 case HintingDisableAll:
573 // When hinting is completely disabled, glyphs must always be rendered -- even during layout calculations -- due to
574 // discrepancies between the glyph metrics and the actual rendered bitmap metrics.
575 ftLoadFlags = FT_LOAD_NO_HINTING | FT_LOAD_RENDER;
576 break;
577 }
578
579 //-------------------------------------------------------------------//
580 // Create the glyphs and calculate their metrics.
581 //-------------------------------------------------------------------//
582
583 GlyphHeightMap glyphHeightMap;
584 int texWidth = 0;
585
586 // Before creating the glyphs, add the "Space" code point to force that glyph to be created. For historical reasons, MyGUI
587 // users are accustomed to omitting this code point in their font definitions.
588 addCodePoint(FontCodeType::Space);
589
590 // Create the standard glyphs.
591 for (auto iter = mCharMap.begin(); iter != mCharMap.end();)
592 {
593 const Char& codePoint = iter->first;
594 FT_UInt glyphIndex = FT_Get_Char_Index(ftFace, codePoint);
595 // Leave unsupported characters to our substitute glyph. This also removes
596 // synthetic code points left by a previous atlas before recreating them below.
597 if (glyphIndex == 0)
598 {
599 iter = mCharMap.erase(iter);
600 continue;
601 }
602
603 if (!mMsdfMode)
604 texWidth += createFaceGlyph(glyphIndex, codePoint, fontAscent, ftFace, ftLoadFlags, glyphHeightMap);
605 #ifdef MYGUI_MSDF_FONTS
606 else
607 texWidth += createMsdfFaceGlyph(glyphIndex, codePoint, fontAscent, msdfFont, glyphHeightMap);
608 #endif
609
610 // If glyph creation failed, do not advertise the code point as supported.
611 if (iter->second != 0)
612 ++iter;
613 else
614 mCharMap.erase(iter++);
615 }
616
617 // Do some special handling for the "Space" and "Tab" glyphs.
618 auto spaceGlyphIter = mGlyphMap.find(FontCodeType::Space);
619
620 if (spaceGlyphIter != mGlyphMap.end())
621 {
622 // Adjust the width of the "Space" glyph if it has been customized.
623 if (mSpaceWidth != 0.0f)
624 {
625 texWidth += (int)std::ceil(mSpaceWidth) - (int)std::ceil(spaceGlyphIter->second.width);
626 spaceGlyphIter->second.width = mSpaceWidth;
627 spaceGlyphIter->second.advance = mSpaceWidth;
628 }
629
630 // If the width of the "Tab" glyph hasn't been customized, make it eight spaces wide.
631 if (mTabWidth == 0.0f)
632 mTabWidth = mDefaultTabWidth * spaceGlyphIter->second.advance;
633 }
634
635 // Create the special glyphs. They must be created after the standard glyphs so that they take precedence in case of a
636 // collision. To make sure that the indices of the special glyphs don't collide with any glyph indices in the font, we must
637 // use glyph indices higher than the highest glyph index in the font.
638 FT_UInt nextGlyphIndex = (FT_UInt)ftFace->num_glyphs;
639
640 float height = (float)mDefaultHeight;
641
642 texWidth += createGlyph(
643 nextGlyphIndex++,
644 GlyphInfo(static_cast<Char>(FontCodeType::Tab), 0.0f, 0.0f, mTabWidth, 0.0f, 0.0f),
645 glyphHeightMap);
646 texWidth += createGlyph(
647 nextGlyphIndex++,
648 GlyphInfo(static_cast<Char>(FontCodeType::Selected), mSelectedWidth, height, 0.0f, 0.0f, 0.0f),
649 glyphHeightMap);
650 texWidth += createGlyph(
651 nextGlyphIndex++,
652 GlyphInfo(static_cast<Char>(FontCodeType::SelectedBack), mSelectedWidth, height, 0.0f, 0.0f, 0.0f),
653 glyphHeightMap);
654 texWidth += createGlyph(
655 nextGlyphIndex++,
656 GlyphInfo(static_cast<Char>(FontCodeType::Cursor), mCursorWidth, height, 0.0f, 0.0f, 0.0f),
657 glyphHeightMap);
658
659 // If a substitute code point has been specified, check to make sure that it exists in the character map. If it doesn't,
660 // revert to the default "Not Defined" code point. This is not a real code point but rather an invalid Unicode value that
661 // is guaranteed to cause the "Not Defined" special glyph to be created.
662 if (mSubstituteCodePoint != FontCodeType::NotDefined && mCharMap.find(mSubstituteCodePoint) == mCharMap.end())
663 mSubstituteCodePoint = static_cast<Char>(FontCodeType::NotDefined);
664
665 // Create the "Not Defined" code point (and its corresponding glyph) if it's in use as the substitute code point.
666 if (mSubstituteCodePoint == FontCodeType::NotDefined)
667 {
668 if (!mMsdfMode)
669 texWidth += createFaceGlyph(
670 0,
671 static_cast<Char>(FontCodeType::NotDefined),
672 fontAscent,
673 ftFace,
674 ftLoadFlags,
675 glyphHeightMap);
676 #ifdef MYGUI_MSDF_FONTS
677 else
678 texWidth += createMsdfFaceGlyph(
679 0,
680 static_cast<Char>(FontCodeType::NotDefined),
681 fontAscent,
682 msdfFont,
683 glyphHeightMap);
684 #endif
685 }
686
687 // Cache a pointer to the substitute glyph info for fast lookup.
688 mSubstituteGlyphInfo = &mGlyphMap.find(mSubstituteCodePoint)->second;
689
690 // Load kerning pairs from the font.
691 loadKerning(ftFace);
692
693 // Calculate the average height of all of the glyphs that are in use. This value will be used for estimating how large the
694 // texture needs to be.
695 double averageGlyphHeight = 0.0;
696
697 for (const auto& heightItem : glyphHeightMap)
698 averageGlyphHeight += heightItem.first * heightItem.second.size();
699
700 averageGlyphHeight /= mGlyphMap.size();
701
702 //-------------------------------------------------------------------//
703 // Calculate the final texture size.
704 //-------------------------------------------------------------------//
705
706 // Round the current texture width and height up to the nearest powers of two.
707 texWidth = Bitwise::firstPO2From(texWidth);
708 int texHeight = Bitwise::firstPO2From((int)ceil(averageGlyphHeight) + mGlyphSpacing);
709
710 // At this point, the texture is only one glyph high and is probably very wide. For efficiency reasons, we need to make the
711 // texture as square as possible. If the texture cannot be made perfectly square, make it taller than it is wide, because
712 // the height may decrease in the final layout due to height packing.
713 while (texWidth > texHeight)
714 {
715 texWidth /= 2;
716 texHeight *= 2;
717 }
718
719 // Calculate the final layout of all of the glyphs in the texture, packing them tightly by first arranging them by height.
720 // We assume that the texture width is fixed but that the texture height can be adjusted up or down depending on how much
721 // space is actually needed.
722 // In most cases, the final texture will end up square or almost square. In some rare cases, however, we can end up with a
723 // texture that's more than twice as high as it is wide; when this happens, we double the width and try again.
724 do
725 {
726 if (texHeight > texWidth * 2)
727 texWidth *= 2;
728
729 int texX = mGlyphSpacing;
730 int texY = mGlyphSpacing;
731
732 for (const auto& heightItem : glyphHeightMap)
733 {
734 for (const auto& [key, info] : heightItem.second)
735 {
736 auto [glyphWidth, glyphHeight] = integerGlyphSize(*info, mDpiScale);
737
738 autoWrapGlyphPos(glyphWidth, texWidth, glyphHeight, texX, texY);
739
740 if (glyphWidth > 0)
741 texX += mGlyphSpacing + glyphWidth;
742 }
743 }
744
745 texHeight = Bitwise::firstPO2From(texY + glyphHeightMap.rbegin()->first);
746 } while (texHeight > texWidth * 2);
747
748 //-------------------------------------------------------------------//
749 // Create the texture and render the glyphs onto it.
750 //-------------------------------------------------------------------//
751
752 if (mTexture)
753 {
754 RenderManager::getInstance().destroyTexture(mTexture);
755 mTexture = nullptr;
756 }
757
758 mTexture = RenderManager::getInstance().createTexture(MyGUI::utility::toString((size_t)this, "_TrueTypeFont"));
759
760 mTexture
761 ->createManual(texWidth, texHeight, TextureUsage::Static | TextureUsage::Write, Pixel<LAMode>::getFormat());
762 mTexture->setInvalidateListener(this);
763
764 if (!mShader.empty())
765 mTexture->setShader(mShader);
766
767 uint8* texBuffer = static_cast<uint8*>(mTexture->lock(TextureUsage::Write));
768
769 if (texBuffer != nullptr)
770 {
771 // Make the texture background transparent white (or black for msdf mode).
772 for (uint8 *dest = texBuffer, *endDest = dest + texWidth * texHeight * Pixel<LAMode>::getNumBytes();
773 dest != endDest;)
774 Pixel<LAMode, false, false>::set(dest, mMsdfMode ? charMaskBlack : charMaskWhite, charMaskBlack, dest);
775
776 if (!mMsdfMode)
777 renderGlyphs<LAMode, Antialias>(
778 glyphHeightMap,
779 ftLibrary,
780 ftFace,
781 ftLoadFlags,
782 texBuffer,
783 texWidth,
784 texHeight);
785 #ifdef MYGUI_MSDF_FONTS
786 else
787 renderMsdfGlyphs(glyphHeightMap, msdfFont, texBuffer, texWidth, texHeight);
788 #endif
789
790 mTexture->unlock();
791
792 MYGUI_LOG(
793 Info,
794 "ResourceTrueTypeFont: Font '"
795 << getResourceName() << "' using texture size " << texWidth << " x " << texHeight << ".");
796 MYGUI_LOG(
797 Info,
798 "ResourceTrueTypeFont: Font '"
799 << getResourceName() << "' using real height " << mDefaultHeight << " pixels.");
800 }
801 else
802 {
803 MYGUI_LOG(Error, "ResourceTrueTypeFont: Error locking texture; pointer is nullptr.");
804 }
805
806 #ifdef MYGUI_MSDF_FONTS
807 if (mMsdfMode)
808 {
809 msdfgen::destroyFont(msdfFont);
810 }
811 #endif
812
813 FT_Done_Face(ftFace);
814 FT_Done_FreeType(ftLibrary);
815 }
816
817 FT_Face ResourceTrueTypeFont::loadFace(const FT_Library& _ftLibrary, std::vector<std::byte>& _fontBuffer)
818 {
819 FT_Face result = nullptr;
820
821 // Load the font file.
822 {
823 auto datastream = DataManager::getInstance().getDataHolder(mSource);
824 if (!datastream)
825 return result;
826 _fontBuffer = datastream->readAll();
827 }
828 const auto* fontData = reinterpret_cast<const FT_Byte*>(_fontBuffer.data());
829 const auto fontBufferSize = static_cast<FT_Long>(_fontBuffer.size());
830
831 // Determine how many faces the font contains.
832 if (FT_New_Memory_Face(_ftLibrary, fontData, fontBufferSize, -1, &result) != 0)
833 MYGUI_EXCEPT("ResourceTrueTypeFont: Could not load the font '" << getResourceName() << "'!");
834
835 FT_Long numFaces = result->num_faces;
836 FT_Long faceIndex = 0;
837
838 FT_Done_Face(result);
839
840 // Load the first face.
841 if (FT_New_Memory_Face(_ftLibrary, fontData, fontBufferSize, faceIndex, &result) != 0)
842 MYGUI_EXCEPT("ResourceTrueTypeFont: Could not load the font '" << getResourceName() << "'!");
843
844 if (result->face_flags & FT_FACE_FLAG_SCALABLE)
845 {
846 // The font is scalable, so set the font size by first converting the requested size to FreeType's 26.6 fixed-point
847 // format.
848 FT_F26Dot6 ftSize = (FT_F26Dot6)(mSize * mDpiScale * (1 << 6));
849
850 if (FT_Set_Char_Size(result, ftSize, 0, mResolution, mResolution) != 0)
851 MYGUI_EXCEPT("ResourceTrueTypeFont: Could not set the font size for '" << getResourceName() << "'!");
852
853 // If no code points have been specified, use the Unicode Basic Multilingual Plane by default.
854 if (mCharMap.empty())
855 addCodePointRange(0, 0xFFFF);
856 }
857 else
858 {
859 // The font isn't scalable, so try to load it as a Windows FNT/FON file.
860 FT_WinFNT_HeaderRec fnt;
861
862 // Enumerate all of the faces in the font and select the smallest one that's at least as large as the requested size
863 // (after adjusting for resolution). If none of the faces are large enough, use the largest one.
864 std::map<float, FT_Long> faceSizes;
865
866 do
867 {
868 if (FT_Get_WinFNT_Header(result, &fnt) != 0)
869 MYGUI_EXCEPT("ResourceTrueTypeFont: Could not load the font '" << getResourceName() << "'!");
870
871 faceSizes.insert(
872 std::make_pair((float)fnt.nominal_point_size * fnt.vertical_resolution / mResolution, faceIndex));
873
874 FT_Done_Face(result);
875
876 if (++faceIndex < numFaces)
877 if (FT_New_Memory_Face(_ftLibrary, fontData, fontBufferSize, faceIndex, &result) != 0)
878 MYGUI_EXCEPT("ResourceTrueTypeFont: Could not load the font '" << getResourceName() << "'!");
879 } while (faceIndex < numFaces);
880
881 auto iter = faceSizes.lower_bound(mSize);
882
883 faceIndex = (iter != faceSizes.end()) ? iter->second : faceSizes.rbegin()->second;
884
885 if (FT_New_Memory_Face(_ftLibrary, fontData, fontBufferSize, faceIndex, &result) != 0)
886 MYGUI_EXCEPT("ResourceTrueTypeFont: Could not load the font '" << getResourceName() << "'!");
887
888 // Select the first bitmap strike available in the selected face. This needs to be done explicitly even though Windows
889 // FNT/FON files contain only one bitmap strike per face.
890 if (FT_Select_Size(result, 0) != 0)
891 MYGUI_EXCEPT("ResourceTrueTypeFont: Could not set the font size for '" << getResourceName() << "'!");
892
893 // Windows FNT/FON files do not support Unicode, so restrict the code-point range to either ISO-8859-1 or ASCII,
894 // depending on the font's encoding.
895 if (mCharMap.empty())
896 {
897 // No code points have been specified, so add the printable ASCII range by default.
898 addCodePointRange(0x20, 0x7E);
899
900 // Additionally, if the font's character set is CP-1252, add the range of non-ASCII 8-bit code points that are
901 // common between CP-1252 and ISO-8859-1; i.e., everything but 0x80 through 0x9F.
902 if (fnt.charset == FT_WinFNT_ID_CP1252)
903 addCodePointRange(0xA0, 0xFF);
904 }
905 else
906 {
907 // Some code points have been specified, so remove anything in the non-printable ASCII range as well as anything
908 // over 8 bits.
909 removeCodePointRange(0, 0x1F);
910 removeCodePointRange(0x100, std::numeric_limits<Char>::max());
911
912 // Additionally, remove non-ASCII 8-bit code points (plus ASCII DEL, 0x7F). If the font's character set is CP-1252,
913 // remove only the code points that differ between CP-1252 and ISO-8859-1; otherwise, remove all of them.
914 if (fnt.charset == FT_WinFNT_ID_CP1252)
915 removeCodePointRange(0x7F, 0x9F);
916 else
917 removeCodePointRange(0x7F, 0xFF);
918 }
919 }
920
921 return result;
922 }
923
924 float ResourceTrueTypeFont::getKerning(Char _left, Char _right) const
925 {
926 auto iter = mKerningMap.find(std::make_pair(_left, _right));
927 if (iter != mKerningMap.end())
928 return iter->second;
929 return 0.0f;
930 }
931
932 void ResourceTrueTypeFont::loadKerning(const FT_Face& _ftFace)
933 {
934 mKerningMap.clear();
935
936 if (!mKerningEnabled)
937 return;
938
939 if (!FT_HAS_KERNING(_ftFace))
940 return;
941
942 for (const auto& [leftChar, leftIndex] : mCharMap)
943 {
944 for (const auto& [rightChar, rightIndex] : mCharMap)
945 {
946 FT_Vector kerning;
947 if (FT_Get_Kerning(_ftFace, leftIndex, rightIndex, FT_KERNING_DEFAULT, &kerning) == 0)
948 {
949 if (kerning.x != 0)
950 {
951 mKerningMap[std::make_pair(leftChar, rightChar)] = kerning.x / 64.0f / mDpiScale;
952 }
953 }
954 }
955 }
956 }
957
958 void ResourceTrueTypeFont::autoWrapGlyphPos(int _glyphWidth, int _texWidth, int _lineHeight, int& _texX, int& _texY)
959 const
960 {
961 if (_glyphWidth > 0 && _texX + mGlyphSpacing + _glyphWidth > _texWidth)
962 {
963 _texX = mGlyphSpacing;
964 _texY += mGlyphSpacing + _lineHeight;
965 }
966 }
967
968 GlyphInfo ResourceTrueTypeFont::createFaceGlyphInfo(Char _codePoint, int _fontAscent, FT_GlyphSlot _glyph) const
969 {
970 float scale = 1.0f / mDpiScale;
971 return {
972 _codePoint,
973 std::max((float)_glyph->bitmap.width, _glyph->metrics.width / 64.0f) * scale,
974 std::max((float)_glyph->bitmap.rows, _glyph->metrics.height / 64.0f) * scale,
975 _glyph->advance.x / 64.0f * scale,
976 _glyph->metrics.horiBearingX / 64.0f * scale,
977 (_fontAscent - (_glyph->metrics.horiBearingY / 64.0f)) * scale - mOffsetHeight};
978 }
979
980 int ResourceTrueTypeFont::createGlyph(
981 FT_UInt _glyphIndex,
982 const GlyphInfo& _glyphInfo,
983 GlyphHeightMap& _glyphHeightMap,
984 float _scale)
985 {
986 auto [width, height] = integerGlyphSize(_glyphInfo, _scale < 0 ? mDpiScale : _scale);
987
988 mCharMap[_glyphInfo.codePoint] = _glyphIndex;
989 GlyphInfo& info = mGlyphMap.insert(GlyphMap::value_type(_glyphInfo.codePoint, _glyphInfo)).first->second;
990 _glyphHeightMap[height].insert(std::make_pair(_glyphIndex, &info));
991
992 return (width > 0) ? mGlyphSpacing + width : 0;
993 }
994
995 int ResourceTrueTypeFont::createFaceGlyph(
996 FT_UInt _glyphIndex,
997 Char _codePoint,
998 int _fontAscent,
999 const FT_Face& _ftFace,
1000 FT_Int32 _ftLoadFlags,
1001 GlyphHeightMap& _glyphHeightMap)
1002 {
1003 if (mGlyphMap.find(_codePoint) == mGlyphMap.end())
1004 {
1005 if (FT_Load_Glyph(_ftFace, _glyphIndex, _ftLoadFlags) == 0)
1006 return createGlyph(
1007 _glyphIndex,
1008 createFaceGlyphInfo(_codePoint, _fontAscent, _ftFace->glyph),
1009 _glyphHeightMap);
1010 MYGUI_LOG(
1011 Warning,
1012 "ResourceTrueTypeFont: Cannot load glyph "
1013 << _glyphIndex << " for character " << _codePoint << " in font '" << getResourceName() << "'.");
1014 }
1015 else
1016 {
1017 mCharMap[_codePoint] = _glyphIndex;
1018 }
1019
1020 return 0;
1021 }
1022
1023 template<bool LAMode, bool Antialias>
1024 void ResourceTrueTypeFont::renderGlyphs(
1025 const GlyphHeightMap& _glyphHeightMap,
1026 const FT_Library& _ftLibrary,
1027 const FT_Face& _ftFace,
1028 FT_Int32 _ftLoadFlags,
1029 uint8* _texBuffer,
1030 int _texWidth,
1031 int _texHeight)
1032 {
1033 FT_Bitmap ftBitmap;
1034 FT_Bitmap_New(&ftBitmap);
1035
1036 int texX = mGlyphSpacing;
1037 int texY = mGlyphSpacing;
1038
1039 for (const auto& sameHeightGlyphs : _glyphHeightMap)
1040 {
1041 int glyphHeight = sameHeightGlyphs.first;
1042 for (const auto& glyph : sameHeightGlyphs.second)
1043 {
1044 GlyphInfo& info = *glyph.second;
1045 auto [intWidth, intHeight] = integerGlyphSize(info, mDpiScale);
1046
1047 switch (info.codePoint)
1048 {
1051 {
1052 renderGlyph<LAMode, false, false>(
1053 info,
1054 charMaskWhite,
1055 charMaskBlack,
1056 charMask.find(info.codePoint)->second,
1057 glyphHeight,
1058 _texBuffer,
1059 _texWidth,
1060 _texHeight,
1061 texX,
1062 texY,
1063 intWidth,
1064 intHeight);
1065
1066 // Manually adjust the glyph's width to zero. This prevents artifacts from appearing at the seams when
1067 // rendering multi-character selections.
1068 auto glyphIter = mGlyphMap.find(info.codePoint);
1069 if (glyphIter != mGlyphMap.end())
1070 {
1071 glyphIter->second.width = 0.0f;
1072 glyphIter->second.uvRect.right = glyphIter->second.uvRect.left;
1073 }
1074 }
1075 break;
1076
1078 case FontCodeType::Tab:
1079 renderGlyph<LAMode, false, false>(
1080 info,
1081 charMaskWhite,
1082 charMaskBlack,
1083 charMask.find(info.codePoint)->second,
1084 glyphHeight,
1085 _texBuffer,
1086 _texWidth,
1087 _texHeight,
1088 texX,
1089 texY,
1090 intWidth,
1091 intHeight);
1092 break;
1093
1094 default:
1095 if (FT_Load_Glyph(_ftFace, glyph.first, _ftLoadFlags) != 0)
1096 {
1097 MYGUI_LOG(
1098 Warning,
1099 "ResourceTrueTypeFont: Cannot load glyph "
1100 << glyph.first << " for character " << info.codePoint << " in font '"
1101 << getResourceName() << "'.");
1102 break;
1103 }
1104 if (FT_Render_Glyph(_ftFace->glyph, FT_RENDER_MODE_NORMAL) != 0)
1105 {
1106 MYGUI_LOG(
1107 Warning,
1108 "ResourceTrueTypeFont: Cannot render glyph "
1109 << glyph.first << " for character " << info.codePoint << " in font '"
1110 << getResourceName() << "'.");
1111 break;
1112 }
1113 {
1114 if (_ftFace->glyph->bitmap.buffer != nullptr)
1115 {
1116 uint8* glyphBuffer = nullptr;
1117
1118 switch (_ftFace->glyph->bitmap.pixel_mode)
1119 {
1120 case FT_PIXEL_MODE_GRAY: glyphBuffer = _ftFace->glyph->bitmap.buffer; break;
1121
1122 case FT_PIXEL_MODE_MONO:
1123 // Convert the monochrome bitmap to 8-bit before rendering it.
1124 if (FT_Bitmap_Convert(_ftLibrary, &_ftFace->glyph->bitmap, &ftBitmap, 1) == 0)
1125 {
1126 // Go through the bitmap and convert all of the nonzero values to 0xFF (white).
1127 for (uint8 *p = ftBitmap.buffer, *endP = p + ftBitmap.width * ftBitmap.rows;
1128 p != endP;
1129 ++p)
1130 *p = *p ? 0xFF : 0;
1131
1132 glyphBuffer = ftBitmap.buffer;
1133 }
1134 break;
1135 }
1136
1137 if (glyphBuffer != nullptr)
1138 renderGlyph<LAMode, true, Antialias>(
1139 info,
1140 charMaskWhite,
1141 charMaskWhite,
1142 charMaskWhite,
1143 glyphHeight,
1144 _texBuffer,
1145 _texWidth,
1146 _texHeight,
1147 texX,
1148 texY,
1149 _ftFace->glyph->bitmap.width,
1150 _ftFace->glyph->bitmap.rows,
1151 glyphBuffer);
1152 }
1153 }
1154 break;
1155 }
1156 }
1157 }
1158
1159 FT_Bitmap_Done(_ftLibrary, &ftBitmap);
1160 }
1161
1162 template<bool LAMode, bool UseBuffer, bool Antialias>
1163 void ResourceTrueTypeFont::renderGlyph(
1164 GlyphInfo& _info,
1165 uint8 _luminance0,
1166 uint8 _luminance1,
1167 uint8 _alpha,
1168 int _lineHeight,
1169 uint8* _texBuffer,
1170 int _texWidth,
1171 int _texHeight,
1172 int& _texX,
1173 int& _texY,
1174 int _bitmapWidth,
1175 int _bitmapHeight,
1176 uint8* _glyphBuffer)
1177 {
1178 autoWrapGlyphPos(_bitmapWidth, _texWidth, _lineHeight, _texX, _texY);
1179
1180 uint8* dest = _texBuffer + (_texY * _texWidth + _texX) * Pixel<LAMode>::getNumBytes();
1181
1182 // Calculate how much to advance the destination pointer after each row to get to the start of the next row.
1183 ptrdiff_t destNextRow = (_texWidth - _bitmapWidth) * Pixel<LAMode>::getNumBytes();
1184
1185 if (!mMsdfMode || !UseBuffer)
1186 {
1187 for (int j = _bitmapHeight; j > 0; --j)
1188 {
1189 int i;
1190 for (i = _bitmapWidth; i > 1; i -= 2)
1191 {
1192 Pixel<LAMode, UseBuffer, Antialias>::set(dest, _luminance0, _alpha, _glyphBuffer);
1193 Pixel<LAMode, UseBuffer, Antialias>::set(dest, _luminance1, _alpha, _glyphBuffer);
1194 }
1195
1196 if (i > 0)
1197 Pixel<LAMode, UseBuffer, Antialias>::set(dest, _luminance0, _alpha, _glyphBuffer);
1198
1199 dest += destNextRow;
1200 }
1201 }
1202 else
1203 {
1204 for (int y = 0; y < _bitmapHeight; ++y)
1205 {
1206 for (int x = 0; x < _bitmapWidth; ++x)
1207 {
1208 for (int i = 0; i < 3; ++i)
1209 {
1210 *dest++ = *_glyphBuffer++;
1211 }
1212 *dest++ = 255;
1213 }
1214
1215 dest += destNextRow;
1216 }
1217 }
1218
1219 // Calculate and store the glyph's UV coordinates within the texture.
1220 _info.uvRect.left = (float)_texX / _texWidth; // u1
1221 _info.uvRect.top = (float)_texY / _texHeight; // v1
1222 _info.uvRect.right = (float)(_texX + _info.width * mDpiScale) / _texWidth; // u2
1223 _info.uvRect.bottom = (float)(_texY + _info.height * mDpiScale) / _texHeight; // v2
1224
1225 if (_bitmapWidth > 0)
1226 _texX += mGlyphSpacing + _bitmapWidth;
1227 }
1228
1229 #ifdef MYGUI_MSDF_FONTS
1230 GlyphInfo ResourceTrueTypeFont::createMsdfFaceGlyphInfo(
1231 Char _codePoint,
1232 const msdfgen::Shape& _shape,
1233 double _advance,
1234 int _fontAscent)
1235 {
1236 msdfgen::Shape::Bounds bounds = _shape.getBounds();
1237 double range = mMsdfRange / 2.0;
1238 if (_shape.contours.empty())
1239 {
1240 bounds = {0, 0, 0, 0};
1241 range = 0;
1242 }
1243
1244 return GlyphInfo(
1245 _codePoint,
1246 (bounds.r - bounds.l) * mMsdfScale + 2 * range,
1247 (bounds.t - bounds.b) * mMsdfScale + 2 * range,
1248 _advance * mMsdfScale,
1249 bounds.l * mMsdfScale - range,
1250 _fontAscent - bounds.t * mMsdfScale - mOffsetHeight - range);
1251 }
1252
1253 int ResourceTrueTypeFont::createMsdfFaceGlyph(
1254 FT_UInt _glyphIndex,
1255 Char _codePoint,
1256 int _fontAscent,
1257 msdfgen::FontHandle* _fontHandle,
1258 GlyphHeightMap& _glyphHeightMap)
1259 {
1260 if (mGlyphMap.find(_codePoint) == mGlyphMap.end())
1261 {
1262 msdfgen::Shape shape;
1263 double advance;
1264 if (msdfgen::loadGlyph(shape, _fontHandle, _codePoint, msdfgen::FONT_SCALING_EM_NORMALIZED, &advance))
1265 return createGlyph(
1266 _glyphIndex,
1267 createMsdfFaceGlyphInfo(_codePoint, shape, advance, _fontAscent),
1268 _glyphHeightMap,
1269 1.0f);
1270 MYGUI_LOG(
1271 Warning,
1272 "ResourceTrueTypeFont: Cannot load msdf glyph for character "
1273 << _codePoint << " in font '" << getResourceName() << "'.");
1274 }
1275 else
1276 {
1277 mCharMap[_codePoint] = _glyphIndex;
1278 }
1279
1280 return 0;
1281 }
1282
1283 void ResourceTrueTypeFont::renderMsdfGlyphs(
1284 const GlyphHeightMap& _glyphHeightMap,
1285 msdfgen::FontHandle* _fontHandle,
1286 uint8* _texBuffer,
1287 int _texWidth,
1288 int _texHeight)
1289 {
1290 int texX = mGlyphSpacing, texY = mGlyphSpacing;
1291
1292 for (const auto& sameHeightGlyphs : _glyphHeightMap)
1293 {
1294 int glyphHeight = sameHeightGlyphs.first;
1295 for (const auto& glyph : sameHeightGlyphs.second)
1296 {
1297 GlyphInfo& info = *glyph.second;
1298
1299 switch (info.codePoint)
1300 {
1303 {
1304 renderGlyph<false, false, false>(
1305 info,
1306 charMaskWhite,
1307 charMaskBlack,
1308 charMask.find(info.codePoint)->second,
1309 glyphHeight,
1310 _texBuffer,
1311 _texWidth,
1312 _texHeight,
1313 texX,
1314 texY,
1315 (int)std::ceil(info.width),
1316 (int)std::ceil(info.height));
1317
1318 // Manually adjust the glyph's width to zero. This prevents artifacts from appearing at the seams when
1319 // rendering multi-character selections.
1320 auto glyphIter = mGlyphMap.find(info.codePoint);
1321 if (glyphIter != mGlyphMap.end())
1322 {
1323 glyphIter->second.width = 0.0f;
1324 glyphIter->second.uvRect.right = glyphIter->second.uvRect.left;
1325 // avoid using data from borders to fix 2 pixels gap between selected lines
1326 glyphIter->second.height = glyphIter->second.height / 2;
1327 float uvHeight = glyphIter->second.uvRect.bottom - glyphIter->second.uvRect.top;
1328 glyphIter->second.uvRect.top += uvHeight / 4;
1329 glyphIter->second.uvRect.bottom -= uvHeight / 4;
1330 }
1331 }
1332 break;
1333
1335 case FontCodeType::Tab:
1336 renderGlyph<false, false, false>(
1337 info,
1338 charMaskWhite,
1339 charMaskBlack,
1340 charMask.find(info.codePoint)->second,
1341 glyphHeight,
1342 _texBuffer,
1343 _texWidth,
1344 _texHeight,
1345 texX,
1346 texY,
1347 (int)std::ceil(info.width),
1348 (int)std::ceil(info.height));
1349 break;
1350
1351 default:
1352 msdfgen::Shape shape;
1353 if (msdfgen::loadGlyph(shape, _fontHandle, info.codePoint, msdfgen::FONT_SCALING_EM_NORMALIZED))
1354 {
1355 msdfgen::Shape::Bounds bounds = shape.getBounds();
1356 double range = mMsdfRange / 2.0;
1357 if (shape.contours.empty())
1358 {
1359 bounds = {0, 0, 0, 0};
1360 range = 0;
1361 }
1362
1363 shape.normalize();
1364 msdfgen::edgeColoringSimple(shape, 3.0);
1365
1366 msdfgen::Bitmap<float, 3> msdf(
1367 (int)std::ceil((bounds.r - bounds.l) * mMsdfScale + 2 * range),
1368 (int)std::ceil((bounds.t - bounds.b) * mMsdfScale + 2 * range));
1369 msdfgen::generateMSDF(
1370 msdf,
1371 shape,
1372 mMsdfRange / mMsdfScale,
1373 msdfgen::Vector2(mMsdfScale, mMsdfScale),
1374 msdfgen::Vector2(-bounds.l + range / mMsdfScale, -bounds.b + range / mMsdfScale));
1375 // double error = msdfgen::estimateSDFError(
1376 // msdfgen::BitmapConstRef<float, 3>{(float*)msdf, msdf.width(), msdf.height()},
1377 // shape,
1378 // 1,
1379 // msdfgen::Vector2(-bounds.l + range, -bounds.b + range),
1380 // 33);
1381 // if (100000 * error > 1)
1382 // MYGUI_LOG(Warning, "Error for '" << char(info.codePoint) << "' is :" << (int) 100000 * error);
1383
1384 uint8* glyphBuffer = new uint8[msdf.width() * msdf.height() * 3];
1385 uint8* glyphBufferPointer = glyphBuffer;
1386 for (int y = 0; y < msdf.height(); ++y)
1387 {
1388 for (int x = 0; x < msdf.width(); ++x)
1389 {
1390 for (int i = 0; i < 3; ++i)
1391 {
1392 // upside-down and RGB->BGR
1393 *glyphBufferPointer++ =
1394 msdfgen::pixelFloatToByte(msdf(x, msdf.height() - y - 1)[2 - i]);
1395 }
1396 }
1397 }
1398
1399 renderGlyph<false, true, false>(
1400 info,
1401 charMaskWhite,
1402 charMaskWhite,
1403 charMaskWhite,
1404 glyphHeight,
1405 _texBuffer,
1406 _texWidth,
1407 _texHeight,
1408 texX,
1409 texY,
1410 msdf.width(),
1411 msdf.height(),
1412 glyphBuffer);
1413 delete[] glyphBuffer;
1414 }
1415 else
1416 {
1417 MYGUI_LOG(
1418 Warning,
1419 "ResourceTrueTypeFont: Cannot render glyph for character "
1420 << info.codePoint << " in font '" << getResourceName() << "'.");
1421 }
1422 break;
1423 }
1424 }
1425 }
1426 }
1427 #endif
1428
1429 void ResourceTrueTypeFont::setSource(std::string_view _value)
1430 {
1431 mSource = _value;
1432 }
1433
1434 void ResourceTrueTypeFont::setShader(std::string_view _value)
1435 {
1436 mShader = _value;
1437 }
1438
1439 void ResourceTrueTypeFont::setSize(float _value)
1440 {
1441 mSize = _value;
1442 }
1443
1444 void ResourceTrueTypeFont::setResolution(unsigned int _value)
1445 {
1446 mResolution = _value;
1447 }
1448
1449 void ResourceTrueTypeFont::setHinting(std::string_view _value)
1450 {
1451 if (_value == "use_native")
1452 mHinting = HintingUseNative;
1453 else if (_value == "force_auto")
1454 mHinting = HintingForceAuto;
1455 else if (_value == "disable_auto")
1456 mHinting = HintingDisableAuto;
1457 else if (_value == "disable_all")
1458 mHinting = HintingDisableAll;
1459 else if (_value == "monochrome")
1460 mHinting = HintingMonochrome;
1461 else
1462 mHinting = HintingUseNative;
1463 }
1464
1465 void ResourceTrueTypeFont::setAntialias(bool _value)
1466 {
1467 mAntialias = _value;
1468 }
1469
1470 void ResourceTrueTypeFont::setTabWidth(float _value)
1471 {
1472 mTabWidth = _value;
1473 }
1474
1475 void ResourceTrueTypeFont::setOffsetHeight(int _value)
1476 {
1477 mOffsetHeight = _value;
1478 }
1479
1480 void ResourceTrueTypeFont::setSubstituteCode(int _value)
1481 {
1482 mSubstituteCodePoint = _value;
1483 }
1484
1485 void ResourceTrueTypeFont::setDistance(int _value)
1486 {
1487 mGlyphSpacing = _value;
1488 }
1489
1490 void ResourceTrueTypeFont::setMsdfMode(bool _value)
1491 {
1492 #ifndef MYGUI_MSDF_FONTS
1493 if (_value)
1494 MYGUI_LOG(
1495 Error,
1496 "MsdfMode flag ignored Define MYGUI_MSDF_FONTS if you need msdf fonts, msdf mode ignored.");
1497 #else
1498 mMsdfMode = _value;
1499 #endif
1500 }
1501
1502 void ResourceTrueTypeFont::setMsdfRange(int _value)
1503 {
1504 mMsdfRange = _value;
1505 }
1506
1507 void ResourceTrueTypeFont::setKerningEnabled(bool _value)
1508 {
1509 mKerningEnabled = _value;
1510 }
1511
1512 void ResourceTrueTypeFont::setDpiScale(float _value)
1513 {
1514 mDpiScale = _value;
1515 }
1516
1517 void ResourceTrueTypeFont::setAutoDpi(bool _value)
1518 {
1519 mAutoDpi = _value;
1520 }
1521
1522#endif // MYGUI_USE_FREETYPE
1523
1524} // namespace MyGUI
#define MYGUI_EXCEPT(dest)
#define MYGUI_LOG(level, text)
unsigned int parseUInt(std::string_view _value)
bool parseBool(std::string_view _value)
float parseFloat(std::string_view _value)
__attribute__((visibility("default"))) void trim(std std::string toString(T _value)
std::vector< std::string > split(std::string_view _source, std::string_view _delims)
int parseInt(std::string_view _value)
uint8_t uint8
Definition MyGUI_Types.h:45
unsigned int Char
Definition MyGUI_Types.h:49
GlyphInfo(Char _codePoint=0U, float _width=0.0f, float _height=0.0f, float _advance=0.0f, float _bearingX=0.0f, float _bearingY=0.0f, const FloatRect &_uvRect=FloatRect())