Merge pull request #22816 from CastagnaIT/fix_tx3g
[xbmc.git] / xbmc / guilib / GUIFontTTF.cpp
blob6b38fb0cbbc0c28ef709d8ddfc7d806f3f6b3cd3
1 /*
2 * Copyright (C) 2005-2018 Team Kodi
3 * This file is part of Kodi - https://kodi.tv
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 * See LICENSES/README.md for more information.
7 */
9 #include "GUIFontTTF.h"
11 #include "GUIFontManager.h"
12 #include "ServiceBroker.h"
13 #include "Texture.h"
14 #include "URL.h"
15 #include "filesystem/File.h"
16 #include "filesystem/SpecialProtocol.h"
17 #include "rendering/RenderSystem.h"
18 #include "threads/SystemClock.h"
19 #include "utils/MathUtils.h"
20 #include "utils/log.h"
21 #include "windowing/GraphicContext.h"
22 #include "windowing/WinSystem.h"
24 #include <math.h>
25 #include <memory>
26 #include <queue>
27 #include <utility>
29 // stuff for freetype
30 #include <ft2build.h>
31 #include <harfbuzz/hb-ft.h>
32 #if defined(HAS_GL) || defined(HAS_GLES)
33 #include "utils/GLUtils.h"
35 #include "system_gl.h"
36 #endif
38 #if defined(HAS_DX)
39 #include "guilib/D3DResource.h"
40 #endif
42 #ifdef TARGET_WINDOWS_STORE
43 #define generic GenericFromFreeTypeLibrary
44 #endif
46 #include FT_FREETYPE_H
47 #include FT_GLYPH_H
48 #include FT_OUTLINE_H
49 #include FT_STROKER_H
51 namespace
53 constexpr int VERTEX_PER_GLYPH = 4; // number of vertex for each glyph
54 constexpr int CHARS_PER_TEXTURE_LINE = 20; // number characters to cache per texture line
55 constexpr int MAX_TRANSLATED_VERTEX = 32; // max number of structs CTranslatedVertices expect to use
56 constexpr int MAX_GLYPHS_PER_TEXT_LINE = 1024; // max number of glyphs per text line expect to use
57 constexpr unsigned int SPACING_BETWEEN_CHARACTERS_IN_TEXTURE = 1;
58 constexpr int CHAR_CHUNK = 64; // 64 chars allocated at a time (2048 bytes)
59 constexpr int GLYPH_STRENGTH_BOLD = 24;
60 constexpr int GLYPH_STRENGTH_LIGHT = -48;
61 constexpr int TAB_SPACE_LENGTH = 4;
62 } /* namespace */
64 class CFreeTypeLibrary
66 public:
67 CFreeTypeLibrary() = default;
68 virtual ~CFreeTypeLibrary()
70 if (m_library)
71 FT_Done_FreeType(m_library);
74 FT_Face GetFont(const std::string& filename,
75 float size,
76 float aspect,
77 std::vector<uint8_t>& memoryBuf)
79 // don't have it yet - create it
80 if (!m_library)
81 FT_Init_FreeType(&m_library);
82 if (!m_library)
84 CLog::LogF(LOGERROR, "Unable to initialize freetype library");
85 return nullptr;
88 FT_Face face;
90 // ok, now load the font face
91 CURL realFile(CSpecialProtocol::TranslatePath(filename));
92 if (realFile.GetFileName().empty())
93 return nullptr;
95 memoryBuf.clear();
96 #ifndef TARGET_WINDOWS
97 if (!realFile.GetProtocol().empty())
98 #endif // ! TARGET_WINDOWS
100 // load file into memory if it is not on local drive
101 // in case of win32: always load file into memory as filename is in UTF-8,
102 // but freetype expect filename in ANSI encoding
103 XFILE::CFile f;
104 if (f.LoadFile(realFile, memoryBuf) <= 0)
105 return nullptr;
107 if (FT_New_Memory_Face(m_library, reinterpret_cast<const FT_Byte*>(memoryBuf.data()),
108 memoryBuf.size(), 0, &face) != 0)
109 return nullptr;
111 #ifndef TARGET_WINDOWS
112 else if (FT_New_Face(m_library, realFile.GetFileName().c_str(), 0, &face))
113 return nullptr;
114 #endif // ! TARGET_WINDOWS
116 unsigned int ydpi = 72; // 72 points to the inch is the freetype default
117 unsigned int xdpi =
118 static_cast<unsigned int>(MathUtils::round_int(static_cast<double>(ydpi * aspect)));
120 // we set our screen res currently to 96dpi in both directions (windows default)
121 // we cache our characters (for rendering speed) so it's probably
122 // not a good idea to allow free scaling of fonts - rather, just
123 // scaling to pixel ratio on screen perhaps?
124 if (FT_Set_Char_Size(face, 0, static_cast<int>(size * 64 + 0.5f), xdpi, ydpi))
126 FT_Done_Face(face);
127 return nullptr;
130 return face;
133 FT_Stroker GetStroker()
135 if (!m_library)
136 return nullptr;
138 FT_Stroker stroker;
139 if (FT_Stroker_New(m_library, &stroker))
140 return nullptr;
142 return stroker;
145 static void ReleaseFont(FT_Face face)
147 assert(face);
148 FT_Done_Face(face);
151 static void ReleaseStroker(FT_Stroker stroker)
153 assert(stroker);
154 FT_Stroker_Done(stroker);
157 private:
158 FT_Library m_library{nullptr};
161 XBMC_GLOBAL_REF(CFreeTypeLibrary, g_freeTypeLibrary); // our freetype library
162 #define g_freeTypeLibrary XBMC_GLOBAL_USE(CFreeTypeLibrary)
164 CGUIFontTTF::CGUIFontTTF(const std::string& fontIdent)
165 : m_fontIdent(fontIdent),
166 m_staticCache(*this),
167 m_dynamicCache(*this),
168 m_renderSystem(CServiceBroker::GetRenderSystem())
172 CGUIFontTTF::~CGUIFontTTF(void)
174 Clear();
177 void CGUIFontTTF::AddReference()
179 m_referenceCount++;
182 void CGUIFontTTF::RemoveReference()
184 // delete this object when it's reference count hits zero
185 m_referenceCount--;
186 if (!m_referenceCount)
187 g_fontManager.FreeFontFile(this);
191 void CGUIFontTTF::ClearCharacterCache()
193 m_texture.reset();
195 DeleteHardwareTexture();
197 m_texture = nullptr;
198 m_char.clear();
199 m_char.reserve(CHAR_CHUNK);
200 memset(m_charquick, 0, sizeof(m_charquick));
201 // set the posX and posY so that our texture will be created on first character write.
202 m_posX = m_textureWidth;
203 m_posY = -static_cast<int>(GetTextureLineHeight());
204 m_textureHeight = 0;
207 void CGUIFontTTF::Clear()
209 m_texture.reset();
210 m_texture = nullptr;
211 memset(m_charquick, 0, sizeof(m_charquick));
212 m_posX = 0;
213 m_posY = 0;
214 m_nestedBeginCount = 0;
216 if (m_hbFont)
217 hb_font_destroy(m_hbFont);
218 m_hbFont = nullptr;
219 if (m_face)
220 g_freeTypeLibrary.ReleaseFont(m_face);
221 m_face = nullptr;
222 if (m_stroker)
223 g_freeTypeLibrary.ReleaseStroker(m_stroker);
224 m_stroker = nullptr;
226 m_vertexTrans.clear();
227 m_vertex.clear();
229 m_fontFileInMemory.clear();
232 bool CGUIFontTTF::Load(
233 const std::string& strFilename, float height, float aspect, float lineSpacing, bool border)
235 // we now know that this object is unique - only the GUIFont objects are non-unique, so no need
236 // for reference tracking these fonts
237 m_face = g_freeTypeLibrary.GetFont(strFilename, height, aspect, m_fontFileInMemory);
238 if (!m_face)
239 return false;
241 m_hbFont = hb_ft_font_create(m_face, 0);
242 if (!m_hbFont)
243 return false;
245 the values used are described below
247 XBMC coords Freetype coords
249 0 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ bbox.yMax, ascender
251 A A |
252 A A |
253 AAAAA pppp cellAscender
254 A A p p |
255 A A p p |
256 m_cellBaseLine _ _A_ _A_ pppp_ _ _ _ _/_ _ _ _ _ 0, base line.
258 p cellDescender
259 m_cellHeight _ _ _ _ _ p _ _ _ _ _ _/_ _ _ _ _ bbox.yMin, descender
262 int cellDescender = std::min<int>(m_face->bbox.yMin, m_face->descender);
263 int cellAscender = std::max<int>(m_face->bbox.yMax, m_face->ascender);
265 if (border)
268 add on the strength of any border - the non-bordered font needs
269 aligning with the bordered font by utilising GetTextBaseLine()
271 FT_Pos strength = FT_MulFix(m_face->units_per_EM, m_face->size->metrics.y_scale) / 12;
272 if (strength < 128)
273 strength = 128;
275 cellDescender -= strength;
276 cellAscender += strength;
278 m_stroker = g_freeTypeLibrary.GetStroker();
279 if (m_stroker)
280 FT_Stroker_Set(m_stroker, strength, FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0);
283 // scale to pixel sizing, rounding so that maximal extent is obtained
284 float scaler = height / m_face->units_per_EM;
285 cellDescender =
286 MathUtils::round_int(cellDescender * static_cast<double>(scaler) - 0.5); // round down
287 cellAscender = MathUtils::round_int(cellAscender * static_cast<double>(scaler) + 0.5); // round up
289 m_cellBaseLine = cellAscender;
290 m_cellHeight = cellAscender - cellDescender;
292 m_height = height;
294 m_texture.reset();
295 m_texture = nullptr;
297 m_textureHeight = 0;
298 m_textureWidth = ((m_cellHeight * CHARS_PER_TEXTURE_LINE) & ~63) + 64;
300 m_textureWidth = CTexture::PadPow2(m_textureWidth);
302 if (m_textureWidth > m_renderSystem->GetMaxTextureSize())
303 m_textureWidth = m_renderSystem->GetMaxTextureSize();
304 m_textureScaleX = 1.0f / m_textureWidth;
306 // set the posX and posY so that our texture will be created on first character write.
307 m_posX = m_textureWidth;
308 m_posY = -static_cast<int>(GetTextureLineHeight());
310 return true;
313 void CGUIFontTTF::Begin()
315 if (m_nestedBeginCount == 0 && m_texture && FirstBegin())
317 m_vertexTrans.clear();
318 m_vertex.clear();
320 // Keep track of the nested begin/end calls.
321 m_nestedBeginCount++;
324 void CGUIFontTTF::End()
326 if (m_nestedBeginCount == 0)
327 return;
329 if (--m_nestedBeginCount > 0)
330 return;
332 LastEnd();
335 void CGUIFontTTF::DrawTextInternal(CGraphicContext& context,
336 float x,
337 float y,
338 const std::vector<UTILS::COLOR::Color>& colors,
339 const vecText& text,
340 uint32_t alignment,
341 float maxPixelWidth,
342 bool scrolling)
344 if (text.empty())
346 return;
349 Begin();
350 uint32_t rawAlignment = alignment;
351 bool dirtyCache(false);
352 const bool hardwareClipping = m_renderSystem->ScissorsCanEffectClipping();
353 CGUIFontCacheStaticPosition staticPos(x, y);
354 CGUIFontCacheDynamicPosition dynamicPos;
355 if (hardwareClipping)
357 dynamicPos =
358 CGUIFontCacheDynamicPosition(context.ScaleFinalXCoord(x, y), context.ScaleFinalYCoord(x, y),
359 context.ScaleFinalZCoord(x, y));
361 CVertexBuffer unusedVertexBuffer;
362 CVertexBuffer& vertexBuffer =
363 hardwareClipping
364 ? m_dynamicCache.Lookup(context, dynamicPos, colors, text, alignment, maxPixelWidth,
365 scrolling, std::chrono::steady_clock::now(), dirtyCache)
366 : unusedVertexBuffer;
367 std::shared_ptr<std::vector<SVertex>> tempVertices = std::make_shared<std::vector<SVertex>>();
368 std::shared_ptr<std::vector<SVertex>>& vertices =
369 hardwareClipping ? tempVertices
370 : static_cast<std::shared_ptr<std::vector<SVertex>>&>(m_staticCache.Lookup(
371 context, staticPos, colors, text, alignment, maxPixelWidth, scrolling,
372 std::chrono::steady_clock::now(), dirtyCache));
374 // reserves vertex vector capacity, only the ones that are going to be used
375 if (hardwareClipping)
377 if (m_vertexTrans.capacity() == 0)
378 m_vertexTrans.reserve(MAX_TRANSLATED_VERTEX);
380 else
382 if (m_vertex.capacity() == 0)
383 m_vertex.reserve(VERTEX_PER_GLYPH * MAX_GLYPHS_PER_TEXT_LINE);
386 if (dirtyCache)
388 const std::vector<Glyph> glyphs = GetHarfBuzzShapedGlyphs(text);
389 // save the origin, which is scaled separately
390 m_originX = x;
391 m_originY = y;
393 // cache the ellipses width
394 if (!m_ellipseCached)
396 m_ellipseCached = true;
397 Character* ellipse = GetCharacter(L'.', 0);
398 if (ellipse)
399 m_ellipsesWidth = ellipse->m_advance;
402 // Check if we will really need to truncate or justify the text
403 if (alignment & XBFONT_TRUNCATED)
405 if (maxPixelWidth <= 0.0f || GetTextWidthInternal(text, glyphs) <= maxPixelWidth)
406 alignment &= ~XBFONT_TRUNCATED;
408 else if (alignment & XBFONT_JUSTIFIED)
410 if (maxPixelWidth <= 0.0f)
411 alignment &= ~XBFONT_JUSTIFIED;
414 // calculate sizing information
415 float startX = 0;
416 float startY = (alignment & XBFONT_CENTER_Y) ? -0.5f * m_cellHeight : 0; // vertical centering
418 if (alignment & (XBFONT_RIGHT | XBFONT_CENTER_X))
420 // Get the extent of this line
421 float w = GetTextWidthInternal(text, glyphs);
423 if (alignment & XBFONT_TRUNCATED && w > maxPixelWidth + 0.5f) // + 0.5f due to rounding issues
424 w = maxPixelWidth;
426 if (alignment & XBFONT_CENTER_X)
427 w *= 0.5f;
428 // Offset this line's starting position
429 startX -= w;
432 float spacePerSpaceCharacter = 0; // for justification effects
433 if (alignment & XBFONT_JUSTIFIED)
435 // first compute the size of the text to render in both characters and pixels
436 unsigned int numSpaces = 0;
437 float linePixels = 0;
438 for (const auto& glyph : glyphs)
440 Character* ch = GetCharacter(text[glyph.m_glyphInfo.cluster], glyph.m_glyphInfo.codepoint);
441 if (ch)
443 if ((text[glyph.m_glyphInfo.cluster] & 0xffff) == L' ')
444 numSpaces += 1;
445 linePixels += ch->m_advance;
448 if (numSpaces > 0)
449 spacePerSpaceCharacter = (maxPixelWidth - linePixels) / numSpaces;
452 float cursorX = 0; // current position along the line
453 float offsetX = 0;
454 float offsetY = 0;
456 // Collect all the Character info in a first pass, in case any of them
457 // are not currently cached and cause the texture to be enlarged, which
458 // would invalidate the texture coordinates.
459 std::queue<Character> characters;
460 if (alignment & XBFONT_TRUNCATED)
461 GetCharacter(L'.', 0);
462 for (const auto& glyph : glyphs)
464 Character* ch = GetCharacter(text[glyph.m_glyphInfo.cluster], glyph.m_glyphInfo.codepoint);
465 if (!ch)
467 Character null = {};
468 characters.push(null);
469 continue;
471 characters.push(*ch);
473 if (maxPixelWidth > 0 &&
474 cursorX + ((alignment & XBFONT_TRUNCATED) ? ch->m_advance + 3 * m_ellipsesWidth : 0) >
475 maxPixelWidth)
476 break;
477 cursorX += ch->m_advance;
480 // Reserve vector space: 4 vertex for each glyph
481 tempVertices->reserve(VERTEX_PER_GLYPH * glyphs.size());
482 cursorX = 0;
484 for (const auto& glyph : glyphs)
486 // If starting text on a new line, determine justification effects
487 // Get the current letter in the CStdString
488 UTILS::COLOR::Color color = (text[glyph.m_glyphInfo.cluster] & 0xff0000) >> 16;
489 if (color >= colors.size())
490 color = 0;
491 color = colors[color];
493 // grab the next character
494 Character* ch = &characters.front();
496 if ((text[glyph.m_glyphInfo.cluster] & 0xffff) == static_cast<character_t>('\t'))
498 const float tabwidth = GetTabSpaceLength();
499 const float a = cursorX / tabwidth;
500 cursorX += tabwidth - ((a - floorf(a)) * tabwidth);
501 characters.pop();
502 continue;
505 if (alignment & XBFONT_TRUNCATED)
507 // Check if we will be exceeded the max allowed width
508 if (cursorX + ch->m_advance + 3 * m_ellipsesWidth > maxPixelWidth)
510 // Yup. Let's draw the ellipses, then bail
511 // Perhaps we should really bail to the next line in this case??
512 Character* period = GetCharacter(L'.', 0);
513 if (!period)
514 break;
516 for (int i = 0; i < 3; i++)
518 RenderCharacter(context, startX + cursorX, startY, period, color, !scrolling,
519 *tempVertices);
520 cursorX += period->m_advance;
522 break;
525 else if (maxPixelWidth > 0 && cursorX > maxPixelWidth)
526 break; // exceeded max allowed width - stop rendering
528 offsetX = static_cast<float>(
529 MathUtils::round_int(static_cast<double>(glyph.m_glyphPosition.x_offset) / 64));
530 offsetY = static_cast<float>(
531 MathUtils::round_int(static_cast<double>(glyph.m_glyphPosition.y_offset) / 64));
532 RenderCharacter(context, startX + cursorX + offsetX, startY - offsetY, ch, color, !scrolling,
533 *tempVertices);
534 if (alignment & XBFONT_JUSTIFIED)
536 if ((text[glyph.m_glyphInfo.cluster] & 0xffff) == L' ')
537 cursorX += ch->m_advance + spacePerSpaceCharacter;
538 else
539 cursorX += ch->m_advance;
541 else
542 cursorX += ch->m_advance;
543 characters.pop();
545 if (hardwareClipping)
547 CVertexBuffer& vertexBuffer =
548 m_dynamicCache.Lookup(context, dynamicPos, colors, text, rawAlignment, maxPixelWidth,
549 scrolling, std::chrono::steady_clock::now(), dirtyCache);
550 CVertexBuffer newVertexBuffer = CreateVertexBuffer(*tempVertices);
551 vertexBuffer = newVertexBuffer;
552 m_vertexTrans.emplace_back(.0f, .0f, .0f, &vertexBuffer, context.GetClipRegion());
554 else
556 m_staticCache.Lookup(context, staticPos, colors, text, rawAlignment, maxPixelWidth, scrolling,
557 std::chrono::steady_clock::now(), dirtyCache) =
558 *static_cast<CGUIFontCacheStaticValue*>(&tempVertices);
559 /* Append the new vertices to the set collected since the first Begin() call */
560 m_vertex.insert(m_vertex.end(), tempVertices->begin(), tempVertices->end());
563 else
565 if (hardwareClipping)
566 m_vertexTrans.emplace_back(dynamicPos.m_x, dynamicPos.m_y, dynamicPos.m_z, &vertexBuffer,
567 context.GetClipRegion());
568 else
569 /* Append the vertices from the cache to the set collected since the first Begin() call */
570 m_vertex.insert(m_vertex.end(), vertices->begin(), vertices->end());
573 End();
577 float CGUIFontTTF::GetTextWidthInternal(const vecText& text)
579 const std::vector<Glyph> glyphs = GetHarfBuzzShapedGlyphs(text);
580 return GetTextWidthInternal(text, glyphs);
583 // this routine assumes a single line (i.e. it was called from GUITextLayout)
584 float CGUIFontTTF::GetTextWidthInternal(const vecText& text, const std::vector<Glyph>& glyphs)
586 float width = 0;
587 for (auto it = glyphs.begin(); it != glyphs.end(); it++)
589 const character_t ch = text[(*it).m_glyphInfo.cluster];
590 Character* c = GetCharacter(ch, (*it).m_glyphInfo.codepoint);
591 if (c)
593 // If last character in line, we want to add render width
594 // and not advance distance - this makes sure that italic text isn't
595 // choped on the end (as render width is larger than advance then).
596 if (std::next(it) == glyphs.end())
597 width += std::max(c->m_right - c->m_left + c->m_offsetX, c->m_advance);
598 else if ((ch & 0xffff) == static_cast<character_t>('\t'))
599 width += GetTabSpaceLength();
600 else
601 width += c->m_advance;
605 return width;
608 float CGUIFontTTF::GetCharWidthInternal(character_t ch)
610 Character* c = GetCharacter(ch, 0);
611 if (c)
613 if ((ch & 0xffff) == static_cast<character_t>('\t'))
614 return GetTabSpaceLength();
615 else
616 return c->m_advance;
619 return 0;
622 float CGUIFontTTF::GetTextHeight(float lineSpacing, int numLines) const
624 return static_cast<float>(numLines - 1) * GetLineHeight(lineSpacing) + m_cellHeight;
627 float CGUIFontTTF::GetLineHeight(float lineSpacing) const
629 if (!m_face)
630 return 0.0f;
632 return lineSpacing * m_face->size->metrics.height / 64.0f;
635 unsigned int CGUIFontTTF::GetTextureLineHeight() const
637 return m_cellHeight + SPACING_BETWEEN_CHARACTERS_IN_TEXTURE;
640 unsigned int CGUIFontTTF::GetMaxFontHeight() const
642 return m_maxFontHeight + SPACING_BETWEEN_CHARACTERS_IN_TEXTURE;
645 std::vector<CGUIFontTTF::Glyph> CGUIFontTTF::GetHarfBuzzShapedGlyphs(const vecText& text)
647 std::vector<Glyph> glyphs;
648 if (text.empty())
650 return glyphs;
653 std::vector<hb_script_t> scripts;
654 std::vector<RunInfo> runs;
655 hb_unicode_funcs_t* ufuncs = hb_unicode_funcs_get_default();
656 hb_script_t lastScript;
657 int lastScriptIndex = -1;
658 int lastSetIndex = -1;
660 for (const auto& character : text)
662 scripts.emplace_back(hb_unicode_script(ufuncs, static_cast<wchar_t>(0xffff & character)));
665 // HB_SCRIPT_COMMON or HB_SCRIPT_INHERITED should be replaced with previous script
666 for (size_t i = 0; i < scripts.size(); ++i)
668 if (scripts[i] == HB_SCRIPT_COMMON || scripts[i] == HB_SCRIPT_INHERITED)
670 if (lastScriptIndex != -1)
672 scripts[i] = lastScript;
673 lastSetIndex = i;
676 else
678 for (size_t j = lastSetIndex + 1; j < i; ++j)
679 scripts[j] = scripts[i];
680 lastScript = scripts[i];
681 lastScriptIndex = i;
682 lastSetIndex = i;
686 lastScript = scripts[0];
687 int lastRunStart = 0;
689 for (unsigned int i = 0; i <= static_cast<unsigned int>(scripts.size()); ++i)
691 if (i == scripts.size() || scripts[i] != lastScript)
693 RunInfo run{};
694 run.m_startOffset = lastRunStart;
695 run.m_endOffset = i;
696 run.m_script = lastScript;
697 runs.emplace_back(run);
699 if (i < scripts.size())
701 lastScript = scripts[i];
702 lastRunStart = i;
704 else
706 break;
711 for (auto& run : runs)
713 run.m_buffer = hb_buffer_create();
714 hb_buffer_set_direction(run.m_buffer, static_cast<hb_direction_t>(HB_DIRECTION_LTR));
715 hb_buffer_set_script(run.m_buffer, run.m_script);
717 for (unsigned int j = run.m_startOffset; j < run.m_endOffset; j++)
719 hb_buffer_add(run.m_buffer, static_cast<wchar_t>(0xffff & text[j]), j);
722 hb_buffer_set_content_type(run.m_buffer, HB_BUFFER_CONTENT_TYPE_UNICODE);
723 hb_shape(m_hbFont, run.m_buffer, nullptr, 0);
724 unsigned int glyphCount;
725 run.m_glyphInfos = hb_buffer_get_glyph_infos(run.m_buffer, &glyphCount);
726 run.m_glyphPositions = hb_buffer_get_glyph_positions(run.m_buffer, &glyphCount);
728 for (size_t k = 0; k < glyphCount; k++)
730 glyphs.emplace_back(run.m_glyphInfos[k], run.m_glyphPositions[k]);
733 hb_buffer_destroy(run.m_buffer);
736 return glyphs;
739 CGUIFontTTF::Character* CGUIFontTTF::GetCharacter(character_t chr, FT_UInt glyphIndex)
741 const wchar_t letter = static_cast<wchar_t>(chr & 0xffff);
743 // ignore linebreaks
744 if (letter == L'\r')
745 return nullptr;
747 const character_t style = (chr & 0x7000000) >> 24; // style = 0 - 6
749 if (!glyphIndex)
750 glyphIndex = FT_Get_Char_Index(m_face, letter);
752 // quick access to the most frequently used glyphs
753 if (glyphIndex < MAX_GLYPH_IDX)
755 character_t ch = (style << 12) | glyphIndex; // 2^12 = 4096
757 if (ch < LOOKUPTABLE_SIZE && m_charquick[ch])
758 return m_charquick[ch];
761 // letters are stored based on style and glyph
762 character_t ch = (style << 16) | glyphIndex;
764 // perform binary search on sorted array by m_glyphAndStyle and
765 // if not found obtains position to insert the new m_char to keep sorted
766 int low = 0;
767 int high = m_char.size() - 1;
768 while (low <= high)
770 int mid = (low + high) >> 1;
771 if (ch > m_char[mid].m_glyphAndStyle)
772 low = mid + 1;
773 else if (ch < m_char[mid].m_glyphAndStyle)
774 high = mid - 1;
775 else
776 return &m_char[mid];
778 // if we get to here, then low is where we should insert the new character
780 int startIndex = low;
782 // increase the size of the buffer if we need it
783 if (m_char.size() == m_char.capacity())
785 m_char.reserve(m_char.capacity() + CHAR_CHUNK);
786 startIndex = 0;
789 // render the character to our texture
790 // must End() as we can't render text to our texture during a Begin(), End() block
791 unsigned int nestedBeginCount = m_nestedBeginCount;
792 m_nestedBeginCount = 1;
793 if (nestedBeginCount)
794 End();
796 m_char.emplace(m_char.begin() + low);
797 if (!CacheCharacter(glyphIndex, style, m_char.data() + low))
798 { // unable to cache character - try clearing them all out and starting over
799 CLog::LogF(LOGDEBUG, "Unable to cache character. Clearing character cache of {} characters",
800 m_char.size());
801 ClearCharacterCache();
802 low = 0;
803 startIndex = 0;
804 m_char.emplace(m_char.begin());
805 if (!CacheCharacter(glyphIndex, style, m_char.data()))
807 CLog::LogF(LOGERROR, "Unable to cache character (out of memory?)");
808 if (nestedBeginCount)
809 Begin();
810 m_nestedBeginCount = nestedBeginCount;
811 return nullptr;
815 if (nestedBeginCount)
816 Begin();
817 m_nestedBeginCount = nestedBeginCount;
819 // update the lookup table with only the m_char addresses that have changed
820 for (size_t i = startIndex; i < m_char.size(); ++i)
822 if (m_char[i].m_glyphIndex < MAX_GLYPH_IDX)
824 // >> 16 is style (0-6), then 16 - 12 (>> 4) is equivalent to style * 4096
825 character_t ch = ((m_char[i].m_glyphAndStyle & 0xffff0000) >> 4) | m_char[i].m_glyphIndex;
827 if (ch < LOOKUPTABLE_SIZE)
828 m_charquick[ch] = m_char.data() + i;
832 return m_char.data() + low;
835 bool CGUIFontTTF::CacheCharacter(FT_UInt glyphIndex, uint32_t style, Character* ch)
837 FT_Glyph glyph = nullptr;
838 if (FT_Load_Glyph(m_face, glyphIndex, FT_LOAD_TARGET_LIGHT))
840 CLog::LogF(LOGDEBUG, "Failed to load glyph {:x}", glyphIndex);
841 return false;
844 // make bold if applicable
845 if (style & FONT_STYLE_BOLD)
846 SetGlyphStrength(m_face->glyph, GLYPH_STRENGTH_BOLD);
847 // and italics if applicable
848 if (style & FONT_STYLE_ITALICS)
849 ObliqueGlyph(m_face->glyph);
850 // and light if applicable
851 if (style & FONT_STYLE_LIGHT)
852 SetGlyphStrength(m_face->glyph, GLYPH_STRENGTH_LIGHT);
853 // grab the glyph
854 if (FT_Get_Glyph(m_face->glyph, &glyph))
856 CLog::LogF(LOGDEBUG, "Failed to get glyph {:x}", glyphIndex);
857 return false;
859 if (m_stroker)
860 FT_Glyph_StrokeBorder(&glyph, m_stroker, 0, 1);
861 // render the glyph
862 if (FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, nullptr, 1))
864 CLog::LogF(LOGDEBUG, "Failed to render glyph {:x} to a bitmap", glyphIndex);
865 return false;
868 FT_BitmapGlyph bitGlyph = (FT_BitmapGlyph)glyph;
869 FT_Bitmap bitmap = bitGlyph->bitmap;
870 bool isEmptyGlyph = (bitmap.width == 0 || bitmap.rows == 0);
872 if (!isEmptyGlyph)
874 if (bitGlyph->left < 0)
875 m_posX += -bitGlyph->left;
877 // check we have enough room for the character.
878 // cast-fest is here to avoid warnings due to freeetype version differences (signedness of width).
879 if (static_cast<int>(m_posX + bitGlyph->left + bitmap.width +
880 SPACING_BETWEEN_CHARACTERS_IN_TEXTURE) > static_cast<int>(m_textureWidth))
881 { // no space - gotta drop to the next line (which means creating a new texture and copying it across)
882 m_posX = 1;
883 m_posY += GetTextureLineHeight();
884 if (bitGlyph->left < 0)
885 m_posX += -bitGlyph->left;
887 if (m_posY + GetTextureLineHeight() >= m_textureHeight)
889 // create the new larger texture
890 unsigned int newHeight = m_posY + GetTextureLineHeight();
891 // check for max height
892 if (newHeight > m_renderSystem->GetMaxTextureSize())
894 CLog::LogF(LOGDEBUG, "New cache texture is too large ({} > {} pixels long)", newHeight,
895 m_renderSystem->GetMaxTextureSize());
896 FT_Done_Glyph(glyph);
897 return false;
900 std::unique_ptr<CTexture> newTexture = ReallocTexture(newHeight);
901 if (!newTexture)
903 FT_Done_Glyph(glyph);
904 CLog::LogF(LOGDEBUG, "Failed to allocate new texture of height {}", newHeight);
905 return false;
907 m_texture = std::move(newTexture);
909 m_posY = GetMaxFontHeight();
912 if (!m_texture)
914 FT_Done_Glyph(glyph);
915 CLog::LogF(LOGDEBUG, "no texture to cache character to");
916 return false;
920 // set the character in our table
921 ch->m_glyphAndStyle = (style << 16) | glyphIndex;
922 ch->m_glyphIndex = glyphIndex;
923 ch->m_offsetX = static_cast<short>(bitGlyph->left);
924 ch->m_offsetY = static_cast<short>(m_cellBaseLine - bitGlyph->top);
925 ch->m_left = isEmptyGlyph ? 0.0f : (static_cast<float>(m_posX));
926 ch->m_top = isEmptyGlyph ? 0.0f : (static_cast<float>(m_posY));
927 ch->m_right = ch->m_left + bitmap.width;
928 ch->m_bottom = ch->m_top + bitmap.rows;
929 ch->m_advance =
930 static_cast<float>(MathUtils::round_int(static_cast<double>(m_face->glyph->advance.x) / 64));
932 // we need only render if we actually have some pixels
933 if (!isEmptyGlyph)
935 // ensure our rect will stay inside the texture (it *should* but we need to be certain)
936 unsigned int x1 = std::max(m_posX, 0);
937 unsigned int y1 = std::max(m_posY, 0);
938 unsigned int x2 = std::min(x1 + bitmap.width, m_textureWidth);
939 unsigned int y2 = std::min(y1 + bitmap.rows, m_textureHeight);
940 m_maxFontHeight = std::max(m_maxFontHeight, y2);
941 CopyCharToTexture(bitGlyph, x1, y1, x2, y2);
943 m_posX += SPACING_BETWEEN_CHARACTERS_IN_TEXTURE +
944 static_cast<unsigned short>(ch->m_right - ch->m_left);
947 // free the glyph
948 FT_Done_Glyph(glyph);
950 return true;
953 void CGUIFontTTF::RenderCharacter(CGraphicContext& context,
954 float posX,
955 float posY,
956 const Character* ch,
957 UTILS::COLOR::Color color,
958 bool roundX,
959 std::vector<SVertex>& vertices)
961 // actual image width isn't same as the character width as that is
962 // just baseline width and height should include the descent
963 const float width = ch->m_right - ch->m_left;
964 const float height = ch->m_bottom - ch->m_top;
966 // return early if nothing to render
967 if (width == 0 || height == 0)
968 return;
970 // posX and posY are relative to our origin, and the textcell is offset
971 // from our (posX, posY). Plus, these are unscaled quantities compared to the underlying GUI resolution
972 CRect vertex((posX + ch->m_offsetX) * context.GetGUIScaleX(),
973 (posY + ch->m_offsetY) * context.GetGUIScaleY(),
974 (posX + ch->m_offsetX + width) * context.GetGUIScaleX(),
975 (posY + ch->m_offsetY + height) * context.GetGUIScaleY());
976 vertex += CPoint(m_originX, m_originY);
977 CRect texture(ch->m_left, ch->m_top, ch->m_right, ch->m_bottom);
978 if (!m_renderSystem->ScissorsCanEffectClipping())
979 context.ClipRect(vertex, texture);
981 // transform our positions - note, no scaling due to GUI calibration/resolution occurs
982 float x[VERTEX_PER_GLYPH] = {context.ScaleFinalXCoord(vertex.x1, vertex.y1),
983 context.ScaleFinalXCoord(vertex.x2, vertex.y1),
984 context.ScaleFinalXCoord(vertex.x2, vertex.y2),
985 context.ScaleFinalXCoord(vertex.x1, vertex.y2)};
987 if (roundX)
989 // We only round the "left" side of the character, and then use the direction of rounding to
990 // move the "right" side of the character. This ensures that a constant width is kept when rendering
991 // the same letter at the same size at different places of the screen, avoiding the problem
992 // of the "left" side rounding one way while the "right" side rounds the other way, thus getting
993 // altering the width of thin characters substantially. This only really works for positive
994 // coordinates (due to the direction of truncation for negatives) but this is the only case that
995 // really interests us anyway.
996 float rx0 = static_cast<float>(MathUtils::round_int(static_cast<double>(x[0])));
997 float rx3 = static_cast<float>(MathUtils::round_int(static_cast<double>(x[3])));
998 x[1] = static_cast<float>(MathUtils::truncate_int(static_cast<double>(x[1])));
999 x[2] = static_cast<float>(MathUtils::truncate_int(static_cast<double>(x[2])));
1000 if (x[0] > 0.0f && rx0 > x[0])
1001 x[1] += 1;
1002 else if (x[0] < 0.0f && rx0 < x[0])
1003 x[1] -= 1;
1004 if (x[3] > 0.0f && rx3 > x[3])
1005 x[2] += 1;
1006 else if (x[3] < 0.0f && rx3 < x[3])
1007 x[2] -= 1;
1008 x[0] = rx0;
1009 x[3] = rx3;
1012 const float y[VERTEX_PER_GLYPH] = {
1013 static_cast<float>(MathUtils::round_int(
1014 static_cast<double>(context.ScaleFinalYCoord(vertex.x1, vertex.y1)))),
1015 static_cast<float>(MathUtils::round_int(
1016 static_cast<double>(context.ScaleFinalYCoord(vertex.x2, vertex.y1)))),
1017 static_cast<float>(MathUtils::round_int(
1018 static_cast<double>(context.ScaleFinalYCoord(vertex.x2, vertex.y2)))),
1019 static_cast<float>(MathUtils::round_int(
1020 static_cast<double>(context.ScaleFinalYCoord(vertex.x1, vertex.y2))))};
1022 const float z[VERTEX_PER_GLYPH] = {
1023 static_cast<float>(MathUtils::round_int(
1024 static_cast<double>(context.ScaleFinalZCoord(vertex.x1, vertex.y1)))),
1025 static_cast<float>(MathUtils::round_int(
1026 static_cast<double>(context.ScaleFinalZCoord(vertex.x2, vertex.y1)))),
1027 static_cast<float>(MathUtils::round_int(
1028 static_cast<double>(context.ScaleFinalZCoord(vertex.x2, vertex.y2)))),
1029 static_cast<float>(MathUtils::round_int(
1030 static_cast<double>(context.ScaleFinalZCoord(vertex.x1, vertex.y2))))};
1032 // tex coords converted to 0..1 range
1033 const float tl = texture.x1 * m_textureScaleX;
1034 const float tr = texture.x2 * m_textureScaleX;
1035 const float tt = texture.y1 * m_textureScaleY;
1036 const float tb = texture.y2 * m_textureScaleY;
1038 vertices.resize(vertices.size() + VERTEX_PER_GLYPH);
1039 SVertex* v = &vertices[vertices.size() - VERTEX_PER_GLYPH];
1040 m_color = color;
1042 #if !defined(HAS_DX)
1043 uint8_t r = KODI::UTILS::GL::GetChannelFromARGB(KODI::UTILS::GL::ColorChannel::R, color);
1044 uint8_t g = KODI::UTILS::GL::GetChannelFromARGB(KODI::UTILS::GL::ColorChannel::G, color);
1045 uint8_t b = KODI::UTILS::GL::GetChannelFromARGB(KODI::UTILS::GL::ColorChannel::B, color);
1046 uint8_t a = KODI::UTILS::GL::GetChannelFromARGB(KODI::UTILS::GL::ColorChannel::A, color);
1047 #endif
1049 for (int i = 0; i < VERTEX_PER_GLYPH; i++)
1051 #ifdef HAS_DX
1052 CD3DHelper::XMStoreColor(&v[i].col, color);
1053 #else
1054 v[i].r = r;
1055 v[i].g = g;
1056 v[i].b = b;
1057 v[i].a = a;
1058 #endif
1061 #if defined(HAS_DX)
1062 for (int i = 0; i < VERTEX_PER_GLYPH; i++)
1064 v[i].x = x[i];
1065 v[i].y = y[i];
1066 v[i].z = z[i];
1069 v[0].u = tl;
1070 v[0].v = tt;
1072 v[1].u = tr;
1073 v[1].v = tt;
1075 v[2].u = tr;
1076 v[2].v = tb;
1078 v[3].u = tl;
1079 v[3].v = tb;
1080 #else
1081 // GL / GLES uses triangle strips, not quads, so have to rearrange the vertex order
1082 v[0].u = tl;
1083 v[0].v = tt;
1084 v[0].x = x[0];
1085 v[0].y = y[0];
1086 v[0].z = z[0];
1088 v[1].u = tl;
1089 v[1].v = tb;
1090 v[1].x = x[3];
1091 v[1].y = y[3];
1092 v[1].z = z[3];
1094 v[2].u = tr;
1095 v[2].v = tt;
1096 v[2].x = x[1];
1097 v[2].y = y[1];
1098 v[2].z = z[1];
1100 v[3].u = tr;
1101 v[3].v = tb;
1102 v[3].x = x[2];
1103 v[3].y = y[2];
1104 v[3].z = z[2];
1105 #endif
1108 // Oblique code - original taken from freetype2 (ftsynth.c)
1109 void CGUIFontTTF::ObliqueGlyph(FT_GlyphSlot slot)
1111 /* only oblique outline glyphs */
1112 if (slot->format != FT_GLYPH_FORMAT_OUTLINE)
1113 return;
1115 /* we don't touch the advance width */
1117 /* For italic, simply apply a shear transform, with an angle */
1118 /* of about 12 degrees. */
1120 FT_Matrix transform;
1121 transform.xx = 0x10000L;
1122 transform.yx = 0x00000L;
1124 transform.xy = 0x06000L;
1125 transform.yy = 0x10000L;
1127 FT_Outline_Transform(&slot->outline, &transform);
1130 // Embolden code - original taken from freetype2 (ftsynth.c)
1131 void CGUIFontTTF::SetGlyphStrength(FT_GlyphSlot slot, int glyphStrength)
1133 if (slot->format != FT_GLYPH_FORMAT_OUTLINE)
1134 return;
1136 /* some reasonable strength */
1137 FT_Pos strength = FT_MulFix(m_face->units_per_EM, m_face->size->metrics.y_scale) / glyphStrength;
1139 FT_BBox bbox_before, bbox_after;
1140 FT_Outline_Get_CBox(&slot->outline, &bbox_before);
1141 FT_Outline_Embolden(&slot->outline, strength); // ignore error
1142 FT_Outline_Get_CBox(&slot->outline, &bbox_after);
1144 FT_Pos dx = bbox_after.xMax - bbox_before.xMax;
1145 FT_Pos dy = bbox_after.yMax - bbox_before.yMax;
1147 if (slot->advance.x)
1148 slot->advance.x += dx;
1150 if (slot->advance.y)
1151 slot->advance.y += dy;
1153 slot->metrics.width += dx;
1154 slot->metrics.height += dy;
1155 slot->metrics.horiBearingY += dy;
1156 slot->metrics.horiAdvance += dx;
1157 slot->metrics.vertBearingX -= dx / 2;
1158 slot->metrics.vertBearingY += dy;
1159 slot->metrics.vertAdvance += dy;
1162 float CGUIFontTTF::GetTabSpaceLength()
1164 const Character* c = GetCharacter(static_cast<character_t>('X'), 0);
1165 return c ? c->m_advance * TAB_SPACE_LENGTH : 28.0f * TAB_SPACE_LENGTH;