FontFaceHandleDefault.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. #include "FontFaceHandleDefault.h"
  2. #include "../../../Include/RmlUi/Core/Profiling.h"
  3. #include "../../../Include/RmlUi/Core/StringUtilities.h"
  4. #include "../../../Include/RmlUi/Core/StyleTypes.h"
  5. #include "../TextureLayout.h"
  6. #include "FontFaceLayer.h"
  7. #include "FontProvider.h"
  8. #include "FreeTypeInterface.h"
  9. #include <algorithm>
  10. #include <numeric>
  11. namespace Rml {
  12. static constexpr char32_t KerningCache_AsciiSubsetBegin = 32;
  13. static constexpr char32_t KerningCache_AsciiSubsetLast = 126;
  14. FontFaceHandleDefault::FontFaceHandleDefault()
  15. {
  16. base_layer = nullptr;
  17. metrics = {};
  18. ft_face = 0;
  19. }
  20. FontFaceHandleDefault::~FontFaceHandleDefault()
  21. {
  22. glyphs.clear();
  23. layers.clear();
  24. }
  25. bool FontFaceHandleDefault::Initialize(FontFaceHandleFreetype face, int font_size, bool load_default_glyphs)
  26. {
  27. ft_face = face;
  28. RMLUI_ASSERTMSG(layer_configurations.empty(), "Initialize must only be called once.");
  29. if (!FreeType::InitialiseFaceHandle(ft_face, font_size, glyphs, metrics, load_default_glyphs))
  30. return false;
  31. has_kerning = FreeType::HasKerning(ft_face);
  32. FillKerningPairCache();
  33. // Generate the default layer and layer configuration.
  34. base_layer = GetOrCreateLayer(nullptr);
  35. layer_configurations.push_back(LayerConfiguration{base_layer});
  36. return true;
  37. }
  38. const FontMetrics& FontFaceHandleDefault::GetFontMetrics() const
  39. {
  40. return metrics;
  41. }
  42. const FontGlyphMap& FontFaceHandleDefault::GetGlyphs() const
  43. {
  44. return glyphs;
  45. }
  46. int FontFaceHandleDefault::GetStringWidth(StringView string, const TextShapingContext& text_shaping_context, Character prior_character)
  47. {
  48. RMLUI_ZoneScoped;
  49. bool has_set_size = false;
  50. bool is_kerning_enabled = IsKerningEnabled(text_shaping_context);
  51. int width = 0;
  52. for (auto it_string = StringIteratorU8(string); it_string; ++it_string)
  53. {
  54. Character character = *it_string;
  55. const FontGlyph* glyph = GetOrAppendGlyph(character);
  56. if (!glyph)
  57. continue;
  58. // Adjust the cursor for the kerning between this character and the previous one.
  59. if (is_kerning_enabled)
  60. width += GetKerning(prior_character, character, has_set_size);
  61. // Adjust the cursor for this character's advance.
  62. width += glyph->advance;
  63. width += (int)text_shaping_context.letter_spacing;
  64. prior_character = character;
  65. }
  66. return Math::Max(width, 0);
  67. }
  68. int FontFaceHandleDefault::GenerateLayerConfiguration(const FontEffectList& font_effects)
  69. {
  70. if (font_effects.empty())
  71. return 0;
  72. // Check each existing configuration for a match with this arrangement of effects.
  73. int configuration_index = 1;
  74. for (; configuration_index < (int)layer_configurations.size(); ++configuration_index)
  75. {
  76. const LayerConfiguration& configuration = layer_configurations[configuration_index];
  77. // Check the size is correct. For a match, there should be one layer in the configuration
  78. // plus an extra for the base layer.
  79. if (configuration.size() != font_effects.size() + 1)
  80. continue;
  81. // Check through each layer, checking it was created by the same effect as the one we're
  82. // checking.
  83. size_t effect_index = 0;
  84. for (size_t i = 0; i < configuration.size(); ++i)
  85. {
  86. // Skip the base layer ...
  87. if (configuration[i]->GetFontEffect() == nullptr)
  88. continue;
  89. // If the ith layer's effect doesn't match the equivalent effect, then this
  90. // configuration can't match.
  91. if (configuration[i]->GetFontEffect() != font_effects[effect_index].get())
  92. break;
  93. // Check the next one ...
  94. ++effect_index;
  95. }
  96. if (effect_index == font_effects.size())
  97. return configuration_index;
  98. }
  99. // No match, so we have to generate a new layer configuration.
  100. layer_configurations.push_back(LayerConfiguration());
  101. LayerConfiguration& layer_configuration = layer_configurations.back();
  102. bool added_base_layer = false;
  103. for (size_t i = 0; i < font_effects.size(); ++i)
  104. {
  105. if (!added_base_layer && font_effects[i]->GetLayer() == FontEffect::Layer::Front)
  106. {
  107. layer_configuration.push_back(base_layer);
  108. added_base_layer = true;
  109. }
  110. FontFaceLayer* new_layer = GetOrCreateLayer(font_effects[i]);
  111. layer_configuration.push_back(new_layer);
  112. }
  113. // Add the base layer now if we still haven't added it.
  114. if (!added_base_layer)
  115. layer_configuration.push_back(base_layer);
  116. return (int)(layer_configurations.size() - 1);
  117. }
  118. bool FontFaceHandleDefault::GenerateLayerTexture(Vector<byte>& texture_data, Vector2i& texture_dimensions, const FontEffect* font_effect,
  119. int texture_id, int handle_version) const
  120. {
  121. if (handle_version != version)
  122. {
  123. RMLUI_ERRORMSG("While generating font layer texture: Handle version mismatch in texture vs font-face.");
  124. return false;
  125. }
  126. auto it = std::find_if(layers.begin(), layers.end(), [font_effect](const EffectLayerPair& pair) { return pair.font_effect == font_effect; });
  127. if (it == layers.end())
  128. {
  129. RMLUI_ERRORMSG("While generating font layer texture: Layer id not found.");
  130. return false;
  131. }
  132. return it->layer->GenerateTexture(texture_data, texture_dimensions, texture_id, glyphs);
  133. }
  134. int FontFaceHandleDefault::GenerateString(RenderManager& render_manager, TexturedMeshList& mesh_list, StringView string, const Vector2f position,
  135. const ColourbPremultiplied colour, const float opacity, const TextShapingContext& text_shaping_context, const int layer_configuration_index)
  136. {
  137. RMLUI_ASSERT(layer_configuration_index >= 0);
  138. RMLUI_ASSERT(layer_configuration_index < (int)layer_configurations.size());
  139. int geometry_index = 0;
  140. int line_width = 0;
  141. bool has_set_size = false;
  142. bool is_kerning_enabled = IsKerningEnabled(text_shaping_context);
  143. UpdateLayersOnDirty();
  144. // Fetch the requested configuration and generate the geometry for each one.
  145. const LayerConfiguration& layer_configuration = layer_configurations[layer_configuration_index];
  146. // Each texture represents one geometry.
  147. const int num_geometries = std::accumulate(layer_configuration.begin(), layer_configuration.end(), 0,
  148. [](int sum, const FontFaceLayer* layer) { return sum + layer->GetNumTextures(); });
  149. mesh_list.resize(num_geometries);
  150. for (size_t layer_index = 0; layer_index < layer_configuration.size(); ++layer_index)
  151. {
  152. FontFaceLayer* layer = layer_configuration[layer_index];
  153. ColourbPremultiplied layer_colour;
  154. if (layer == base_layer)
  155. layer_colour = colour;
  156. else
  157. layer_colour = layer->GetColour(opacity);
  158. const int num_textures = layer->GetNumTextures();
  159. if (num_textures == 0)
  160. continue;
  161. RMLUI_ASSERT(geometry_index + num_textures <= (int)mesh_list.size());
  162. line_width = 0;
  163. Character prior_character = Character::Null;
  164. // Set the mesh and textures to the geometries.
  165. for (int tex_index = 0; tex_index < num_textures; ++tex_index)
  166. mesh_list[geometry_index + tex_index].texture = layer->GetTexture(render_manager, tex_index);
  167. mesh_list[geometry_index].mesh.indices.reserve(string.size() * 6);
  168. mesh_list[geometry_index].mesh.vertices.reserve(string.size() * 4);
  169. for (auto it_string = StringIteratorU8(string); it_string; ++it_string)
  170. {
  171. Character character = *it_string;
  172. const FontGlyph* glyph = GetOrAppendGlyph(character);
  173. if (!glyph)
  174. continue;
  175. // Adjust the cursor for the kerning between this character and the previous one.
  176. if (is_kerning_enabled)
  177. line_width += GetKerning(prior_character, character, has_set_size);
  178. ColourbPremultiplied glyph_color = layer_colour;
  179. // Use white vertex colors on RGB glyphs.
  180. if (layer == base_layer && glyph->color_format == ColorFormat::RGBA8)
  181. glyph_color = ColourbPremultiplied(layer_colour.alpha, layer_colour.alpha);
  182. layer->GenerateGeometry(&mesh_list[geometry_index], character, Vector2f(position.x + line_width, position.y), glyph_color);
  183. line_width += glyph->advance;
  184. line_width += (int)text_shaping_context.letter_spacing;
  185. prior_character = character;
  186. }
  187. geometry_index += num_textures;
  188. }
  189. return Math::Max(line_width, 0);
  190. }
  191. bool FontFaceHandleDefault::UpdateLayersOnDirty()
  192. {
  193. bool result = false;
  194. // If we are dirty, regenerate all the layers and increment the version
  195. if (is_layers_dirty && base_layer)
  196. {
  197. is_layers_dirty = false;
  198. ++version;
  199. // Regenerate all the layers.
  200. // Note: The layer regeneration needs to happen in the order in which the layers were created,
  201. // otherwise we may end up cloning a layer which has not yet been regenerated. This means trouble!
  202. for (auto& pair : layers)
  203. {
  204. GenerateLayer(pair.layer.get());
  205. }
  206. result = true;
  207. }
  208. return result;
  209. }
  210. int FontFaceHandleDefault::GetVersion() const
  211. {
  212. return version;
  213. }
  214. bool FontFaceHandleDefault::AppendGlyph(Character character)
  215. {
  216. bool result = FreeType::AppendGlyph(ft_face, metrics.size, character, glyphs);
  217. return result;
  218. }
  219. void FontFaceHandleDefault::FillKerningPairCache()
  220. {
  221. if (!has_kerning)
  222. return;
  223. for (char32_t i = KerningCache_AsciiSubsetBegin; i <= KerningCache_AsciiSubsetLast; i++)
  224. {
  225. for (char32_t j = KerningCache_AsciiSubsetBegin; j <= KerningCache_AsciiSubsetLast; j++)
  226. {
  227. const bool first_iteration = (i == KerningCache_AsciiSubsetBegin && j == KerningCache_AsciiSubsetBegin);
  228. // Fetch the kerning from the font face. Submit zero font size on subsequent iterations for performance reasons.
  229. const int kerning = FreeType::GetKerning(ft_face, first_iteration ? metrics.size : 0, Character(i), Character(j));
  230. if (kerning != 0)
  231. {
  232. kerning_pair_cache.emplace(AsciiPair((i << 8) | j), KerningIntType(kerning));
  233. }
  234. }
  235. }
  236. }
  237. int FontFaceHandleDefault::GetKerning(Character lhs, Character rhs, bool& has_set_size) const
  238. {
  239. static_assert(' ' == 32, "Only ASCII/UTF8 character set supported.");
  240. // Check if we have no kerning, or if we have a control character.
  241. if (!has_kerning || char32_t(lhs) < ' ' || char32_t(rhs) < ' ')
  242. return 0;
  243. // See if the kerning pair has been cached.
  244. const bool lhs_in_cache = (char32_t(lhs) >= KerningCache_AsciiSubsetBegin && char32_t(lhs) <= KerningCache_AsciiSubsetLast);
  245. const bool rhs_in_cache = (char32_t(rhs) >= KerningCache_AsciiSubsetBegin && char32_t(rhs) <= KerningCache_AsciiSubsetLast);
  246. if (lhs_in_cache && rhs_in_cache)
  247. {
  248. const auto it = kerning_pair_cache.find(AsciiPair((int(lhs) << 8) | int(rhs)));
  249. if (it != kerning_pair_cache.end())
  250. {
  251. return it->second;
  252. }
  253. return 0;
  254. }
  255. // Fetch it from the font face instead.
  256. const int result = FreeType::GetKerning(ft_face, has_set_size ? 0 : metrics.size, lhs, rhs);
  257. // This is purely an optimization to avoid repeatedly setting the font size in FreeType, which can be a measurable performance hit.
  258. has_set_size = true;
  259. return result;
  260. }
  261. bool FontFaceHandleDefault::IsKerningEnabled(const TextShapingContext& text_shaping_context) const
  262. {
  263. return text_shaping_context.font_kerning != Style::FontKerning::None;
  264. }
  265. const FontGlyph* FontFaceHandleDefault::GetOrAppendGlyph(Character& character, bool look_in_fallback_fonts)
  266. {
  267. // Don't try to render control characters
  268. if ((char32_t)character < (char32_t)' ')
  269. return nullptr;
  270. auto it_glyph = glyphs.find(character);
  271. if (it_glyph == glyphs.end())
  272. {
  273. bool result = AppendGlyph(character);
  274. if (result)
  275. {
  276. it_glyph = glyphs.find(character);
  277. if (it_glyph == glyphs.end())
  278. {
  279. RMLUI_ERROR;
  280. return nullptr;
  281. }
  282. is_layers_dirty = true;
  283. }
  284. else if (look_in_fallback_fonts)
  285. {
  286. const int num_fallback_faces = FontProvider::CountFallbackFontFaces();
  287. for (int i = 0; i < num_fallback_faces; i++)
  288. {
  289. FontFaceHandleDefault* fallback_face = FontProvider::GetFallbackFontFace(i, metrics.size);
  290. if (!fallback_face || fallback_face == this)
  291. continue;
  292. const FontGlyph* glyph = fallback_face->GetOrAppendGlyph(character, false);
  293. if (glyph)
  294. {
  295. // Insert the new glyph into our own set of glyphs
  296. auto pair = glyphs.emplace(character, glyph->WeakCopy());
  297. it_glyph = pair.first;
  298. if (pair.second)
  299. is_layers_dirty = true;
  300. break;
  301. }
  302. }
  303. // If we still have not found a glyph, use the replacement character.
  304. if (it_glyph == glyphs.end())
  305. {
  306. character = Character::Replacement;
  307. it_glyph = glyphs.find(character);
  308. if (it_glyph == glyphs.end())
  309. return nullptr;
  310. }
  311. }
  312. else
  313. {
  314. return nullptr;
  315. }
  316. }
  317. const FontGlyph* glyph = &it_glyph->second;
  318. return glyph;
  319. }
  320. FontFaceLayer* FontFaceHandleDefault::GetOrCreateLayer(const SharedPtr<const FontEffect>& font_effect)
  321. {
  322. // Search for the font effect layer first, it may have been instanced before as part of a different configuration.
  323. const FontEffect* font_effect_ptr = font_effect.get();
  324. auto it =
  325. std::find_if(layers.begin(), layers.end(), [font_effect_ptr](const EffectLayerPair& pair) { return pair.font_effect == font_effect_ptr; });
  326. if (it != layers.end())
  327. return it->layer.get();
  328. // No existing effect matches, generate a new layer for the effect.
  329. layers.push_back(EffectLayerPair{font_effect_ptr, nullptr});
  330. auto& layer = layers.back().layer;
  331. layer = MakeUnique<FontFaceLayer>(font_effect);
  332. GenerateLayer(layer.get());
  333. return layer.get();
  334. }
  335. bool FontFaceHandleDefault::GenerateLayer(FontFaceLayer* layer)
  336. {
  337. RMLUI_ASSERT(layer);
  338. const FontEffect* font_effect = layer->GetFontEffect();
  339. bool result = false;
  340. if (!font_effect)
  341. {
  342. result = layer->Generate(this);
  343. }
  344. else
  345. {
  346. // Determine which, if any, layer the new layer should copy its geometry and textures from.
  347. FontFaceLayer* clone = nullptr;
  348. bool clone_glyph_origins = true;
  349. String generation_key;
  350. size_t fingerprint = font_effect->GetFingerprint();
  351. if (!font_effect->HasUniqueTexture())
  352. {
  353. clone = base_layer;
  354. clone_glyph_origins = false;
  355. }
  356. else
  357. {
  358. auto cache_iterator = layer_cache.find(fingerprint);
  359. if (cache_iterator != layer_cache.end() && cache_iterator->second != layer)
  360. clone = cache_iterator->second;
  361. }
  362. // Create a new layer.
  363. result = layer->Generate(this, clone, clone_glyph_origins);
  364. // Cache the layer in the layer cache if it generated its own textures (ie, didn't clone).
  365. if (!clone)
  366. layer_cache[fingerprint] = layer;
  367. }
  368. return result;
  369. }
  370. } // namespace Rml