FontFaceHandleDefault.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019-2023 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "FontFaceHandleDefault.h"
  29. #include "../../../Include/RmlUi/Core/Profiling.h"
  30. #include "../../../Include/RmlUi/Core/StringUtilities.h"
  31. #include "../TextureLayout.h"
  32. #include "FontFaceLayer.h"
  33. #include "FontProvider.h"
  34. #include "FreeTypeInterface.h"
  35. #include <algorithm>
  36. #include <numeric>
  37. namespace Rml {
  38. static constexpr char32_t KerningCache_AsciiSubsetBegin = 32;
  39. static constexpr char32_t KerningCache_AsciiSubsetLast = 126;
  40. FontFaceHandleDefault::FontFaceHandleDefault()
  41. {
  42. base_layer = nullptr;
  43. metrics = {};
  44. ft_face = 0;
  45. }
  46. FontFaceHandleDefault::~FontFaceHandleDefault()
  47. {
  48. glyphs.clear();
  49. layers.clear();
  50. }
  51. bool FontFaceHandleDefault::Initialize(FontFaceHandleFreetype face, int font_size, bool load_default_glyphs)
  52. {
  53. ft_face = face;
  54. RMLUI_ASSERTMSG(layer_configurations.empty(), "Initialize must only be called once.");
  55. if (!FreeType::InitialiseFaceHandle(ft_face, font_size, glyphs, metrics, load_default_glyphs))
  56. return false;
  57. for (auto iterator = glyphs.begin(); iterator != glyphs.end(); ++iterator)
  58. new_glyphs.push_back(&*iterator);
  59. has_kerning = FreeType::HasKerning(ft_face);
  60. FillKerningPairCache();
  61. // Generate the default layer and layer configuration.
  62. base_layer = GetOrCreateLayer(nullptr);
  63. layer_configurations.push_back(LayerConfiguration{base_layer});
  64. new_glyphs.clear();
  65. return true;
  66. }
  67. const FontMetrics& FontFaceHandleDefault::GetFontMetrics() const
  68. {
  69. return metrics;
  70. }
  71. const FontGlyphMap& FontFaceHandleDefault::GetGlyphs() const
  72. {
  73. return glyphs;
  74. }
  75. void FontFaceHandleDefault::PurgeUnusedGlyphs() {
  76. glyph_lru_list.tick();
  77. Vector<Character> purged_characters;
  78. while (glyph_lru_list.getLastEntryAge() > 600) {
  79. const Character character = *glyph_lru_list.getLast();
  80. glyphs.erase(character);
  81. glyph_lru_list_handle_map.erase(character);
  82. glyph_lru_list.evictLast();
  83. purged_characters.push_back(character);
  84. }
  85. if (!purged_characters.empty())
  86. for (auto& pair : layers)
  87. pair.layer->RemoveGlyphs(purged_characters);
  88. }
  89. int FontFaceHandleDefault::GetStringWidth(StringView string, float letter_spacing, Character prior_character)
  90. {
  91. RMLUI_ZoneScoped;
  92. bool has_set_size = false;
  93. int width = 0;
  94. for (auto it_string = StringIteratorU8(string); it_string; ++it_string)
  95. {
  96. Character character = *it_string;
  97. const FontGlyph* glyph = GetOrAppendGlyph(character);
  98. if (!glyph)
  99. continue;
  100. // Adjust the cursor for the kerning between this character and the previous one.
  101. width += GetKerning(prior_character, character, has_set_size);
  102. // Adjust the cursor for this character's advance.
  103. width += glyph->advance;
  104. width += (int)letter_spacing;
  105. prior_character = character;
  106. }
  107. return Math::Max(width, 0);
  108. }
  109. int FontFaceHandleDefault::GenerateLayerConfiguration(const FontEffectList& font_effects)
  110. {
  111. if (font_effects.empty())
  112. return 0;
  113. // Check each existing configuration for a match with this arrangement of effects.
  114. int configuration_index = 1;
  115. for (; configuration_index < (int)layer_configurations.size(); ++configuration_index)
  116. {
  117. const LayerConfiguration& configuration = layer_configurations[configuration_index];
  118. // Check the size is correct. For a match, there should be one layer in the configuration
  119. // plus an extra for the base layer.
  120. if (configuration.size() != font_effects.size() + 1)
  121. continue;
  122. // Check through each layer, checking it was created by the same effect as the one we're
  123. // checking.
  124. size_t effect_index = 0;
  125. for (size_t i = 0; i < configuration.size(); ++i)
  126. {
  127. // Skip the base layer ...
  128. if (configuration[i]->GetFontEffect() == nullptr)
  129. continue;
  130. // If the ith layer's effect doesn't match the equivalent effect, then this
  131. // configuration can't match.
  132. if (configuration[i]->GetFontEffect() != font_effects[effect_index].get())
  133. break;
  134. // Check the next one ...
  135. ++effect_index;
  136. }
  137. if (effect_index == font_effects.size())
  138. return configuration_index;
  139. }
  140. // No match, so we have to generate a new layer configuration.
  141. layer_configurations.push_back(LayerConfiguration());
  142. LayerConfiguration& layer_configuration = layer_configurations.back();
  143. bool added_base_layer = false;
  144. for (size_t i = 0; i < font_effects.size(); ++i)
  145. {
  146. if (!added_base_layer && font_effects[i]->GetLayer() == FontEffect::Layer::Front)
  147. {
  148. layer_configuration.push_back(base_layer);
  149. added_base_layer = true;
  150. }
  151. FontFaceLayer* new_layer = GetOrCreateLayer(font_effects[i]);
  152. layer_configuration.push_back(new_layer);
  153. }
  154. // Add the base layer now if we still haven't added it.
  155. if (!added_base_layer)
  156. layer_configuration.push_back(base_layer);
  157. return (int)(layer_configurations.size() - 1);
  158. }
  159. bool FontFaceHandleDefault::GenerateLayerTexture(Span<const byte>& texture_data, Vector2i& texture_dimensions, const FontEffect* font_effect,
  160. int texture_id, int handle_version) const
  161. {
  162. if (handle_version != version)
  163. {
  164. RMLUI_ERRORMSG("While generating font layer texture: Handle version mismatch in texture vs font-face.");
  165. return false;
  166. }
  167. auto it = std::find_if(layers.begin(), layers.end(), [font_effect](const EffectLayerPair& pair) { return pair.font_effect == font_effect; });
  168. if (it == layers.end())
  169. {
  170. RMLUI_ERRORMSG("While generating font layer texture: Layer id not found.");
  171. return false;
  172. }
  173. return it->layer->GenerateTexture(texture_data, texture_dimensions, texture_id, glyphs);
  174. }
  175. int FontFaceHandleDefault::GenerateString(RenderManager& render_manager, TexturedMeshList& mesh_list, StringView string, const Vector2f position,
  176. const ColourbPremultiplied colour, const float opacity, const float letter_spacing, const int layer_configuration_index)
  177. {
  178. RMLUI_ASSERT(layer_configuration_index >= 0);
  179. RMLUI_ASSERT(layer_configuration_index < (int)layer_configurations.size());
  180. int geometry_index = 0;
  181. int line_width = 0;
  182. bool has_set_size = false;
  183. UpdateLayersOnDirty();
  184. // Fetch the requested configuration and generate the geometry for each one.
  185. const LayerConfiguration& layer_configuration = layer_configurations[layer_configuration_index];
  186. // Each texture represents one geometry.
  187. const int num_geometries = std::accumulate(layer_configuration.begin(), layer_configuration.end(), 0,
  188. [](int sum, const FontFaceLayer* layer) { return sum + layer->GetNumTextures(); });
  189. mesh_list.resize(num_geometries);
  190. for (size_t layer_index = 0; layer_index < layer_configuration.size(); ++layer_index)
  191. {
  192. FontFaceLayer* layer = layer_configuration[layer_index];
  193. ColourbPremultiplied layer_colour;
  194. if (layer == base_layer)
  195. layer_colour = colour;
  196. else
  197. layer_colour = layer->GetColour(opacity);
  198. const int num_textures = layer->GetNumTextures();
  199. if (num_textures == 0)
  200. continue;
  201. RMLUI_ASSERT(geometry_index + num_textures <= (int)mesh_list.size());
  202. line_width = 0;
  203. Character prior_character = Character::Null;
  204. // Set the mesh and textures to the geometries.
  205. for (int tex_index = 0; tex_index < num_textures; ++tex_index)
  206. mesh_list[geometry_index + tex_index].texture = layer->GetTexture(render_manager, tex_index);
  207. mesh_list[geometry_index].mesh.indices.reserve(string.size() * 6);
  208. mesh_list[geometry_index].mesh.vertices.reserve(string.size() * 4);
  209. for (auto it_string = StringIteratorU8(string); it_string; ++it_string)
  210. {
  211. Character character = *it_string;
  212. const FontGlyph* glyph = GetOrAppendGlyph(character);
  213. if (!glyph)
  214. continue;
  215. // Adjust the cursor for the kerning between this character and the previous one.
  216. line_width += GetKerning(prior_character, character, has_set_size);
  217. ColourbPremultiplied glyph_color = layer_colour;
  218. // Use white vertex colors on RGB glyphs.
  219. if (layer == base_layer && glyph->color_format == ColorFormat::RGBA8)
  220. glyph_color = ColourbPremultiplied(layer_colour.alpha, layer_colour.alpha);
  221. layer->GenerateGeometry(&mesh_list[geometry_index], character, Vector2f(position.x + line_width, position.y), glyph_color);
  222. line_width += glyph->advance;
  223. line_width += (int)letter_spacing;
  224. prior_character = character;
  225. }
  226. geometry_index += num_textures;
  227. }
  228. return Math::Max(line_width, 0);
  229. }
  230. bool FontFaceHandleDefault::EnsureGlyphs(StringView string)
  231. {
  232. bool all_alive = true;
  233. for (auto it_string = StringIteratorU8(string); it_string; ++it_string)
  234. {
  235. Character character = *it_string;
  236. if ((char32_t)character < (char32_t)' ')
  237. continue;
  238. if (glyphs.find(character) == glyphs.end())
  239. {
  240. new_characters.push_back(character);
  241. all_alive = false;
  242. }
  243. else
  244. {
  245. glyph_lru_list.ping(glyph_lru_list_handle_map[character]);
  246. }
  247. }
  248. if (!all_alive)
  249. is_layers_dirty = true;
  250. return all_alive;
  251. }
  252. bool FontFaceHandleDefault::UpdateLayersOnDirty()
  253. {
  254. bool result = false;
  255. // If we are dirty, regenerate all the layers and increment the version
  256. if (is_layers_dirty && base_layer)
  257. {
  258. is_layers_dirty = false;
  259. ++version;
  260. // Regenerate all the layers.
  261. // Note: The layer regeneration needs to happen in the order in which the layers were created,
  262. // otherwise we may end up cloning a layer which has not yet been regenerated. This means trouble!
  263. for (const auto character : new_characters)
  264. new_glyphs.push_back(&*glyphs.find(character));
  265. for (auto& pair : layers)
  266. {
  267. GenerateLayer(pair.layer.get());
  268. }
  269. new_characters.clear();
  270. new_glyphs.clear();
  271. result = true;
  272. }
  273. return result;
  274. }
  275. int FontFaceHandleDefault::GetVersion() const
  276. {
  277. return version;
  278. }
  279. bool FontFaceHandleDefault::AppendGlyph(Character character)
  280. {
  281. if (!FreeType::AppendGlyph(ft_face, metrics.size, character, glyphs))
  282. return false;
  283. return true;
  284. }
  285. void FontFaceHandleDefault::FillKerningPairCache()
  286. {
  287. if (!has_kerning)
  288. return;
  289. for (char32_t i = KerningCache_AsciiSubsetBegin; i <= KerningCache_AsciiSubsetLast; i++)
  290. {
  291. for (char32_t j = KerningCache_AsciiSubsetBegin; j <= KerningCache_AsciiSubsetLast; j++)
  292. {
  293. const bool first_iteration = (i == KerningCache_AsciiSubsetBegin && j == KerningCache_AsciiSubsetBegin);
  294. // Fetch the kerning from the font face. Submit zero font size on subsequent iterations for performance reasons.
  295. const int kerning = FreeType::GetKerning(ft_face, first_iteration ? metrics.size : 0, Character(i), Character(j));
  296. if (kerning != 0)
  297. {
  298. kerning_pair_cache.emplace(AsciiPair((i << 8) | j), KerningIntType(kerning));
  299. }
  300. }
  301. }
  302. }
  303. int FontFaceHandleDefault::GetKerning(Character lhs, Character rhs, bool& has_set_size) const
  304. {
  305. static_assert(' ' == 32, "Only ASCII/UTF8 character set supported.");
  306. // Check if we have no kerning, or if we have a control character.
  307. if (!has_kerning || char32_t(lhs) < ' ' || char32_t(rhs) < ' ')
  308. return 0;
  309. // See if the kerning pair has been cached.
  310. const bool lhs_in_cache = (char32_t(lhs) >= KerningCache_AsciiSubsetBegin && char32_t(lhs) <= KerningCache_AsciiSubsetLast);
  311. const bool rhs_in_cache = (char32_t(rhs) >= KerningCache_AsciiSubsetBegin && char32_t(rhs) <= KerningCache_AsciiSubsetLast);
  312. if (lhs_in_cache && rhs_in_cache)
  313. {
  314. const auto it = kerning_pair_cache.find(AsciiPair((int(lhs) << 8) | int(rhs)));
  315. if (it != kerning_pair_cache.end())
  316. {
  317. return it->second;
  318. }
  319. return 0;
  320. }
  321. // Fetch it from the font face instead.
  322. const int result = FreeType::GetKerning(ft_face, has_set_size ? 0 : metrics.size, lhs, rhs);
  323. // This is purely an optimization to avoid repeatedly setting the font size in FreeType, which can be a measurable performance hit.
  324. has_set_size = true;
  325. return result;
  326. }
  327. const FontGlyph* FontFaceHandleDefault::GetOrAppendGlyph(Character& character, bool look_in_fallback_fonts)
  328. {
  329. // Don't try to render control characters
  330. if ((char32_t)character < (char32_t)' ')
  331. return nullptr;
  332. auto it_glyph = glyphs.find(character);
  333. if (it_glyph == glyphs.end())
  334. {
  335. bool result = AppendGlyph(character);
  336. if (result)
  337. {
  338. it_glyph = glyphs.find(character);
  339. if (it_glyph == glyphs.end())
  340. {
  341. RMLUI_ERROR;
  342. return nullptr;
  343. }
  344. glyph_lru_list_handle_map.emplace(character, glyph_lru_list.add(character));
  345. new_characters.push_back(character);
  346. is_layers_dirty = true;
  347. }
  348. else if (look_in_fallback_fonts)
  349. {
  350. const int num_fallback_faces = FontProvider::CountFallbackFontFaces();
  351. for (int i = 0; i < num_fallback_faces; i++)
  352. {
  353. FontFaceHandleDefault* fallback_face = FontProvider::GetFallbackFontFace(i, metrics.size);
  354. if (!fallback_face || fallback_face == this)
  355. continue;
  356. const FontGlyph* glyph = fallback_face->GetOrAppendGlyph(character, false);
  357. if (glyph)
  358. {
  359. // Insert the new glyph into our own set of glyphs
  360. auto pair = glyphs.emplace(character, glyph->WeakCopy());
  361. it_glyph = pair.first;
  362. if (pair.second)
  363. is_layers_dirty = true;
  364. break;
  365. }
  366. }
  367. // If we still have not found a glyph, use the replacement character.
  368. if (it_glyph == glyphs.end())
  369. {
  370. character = Character::Replacement;
  371. it_glyph = glyphs.find(character);
  372. if (it_glyph == glyphs.end())
  373. return nullptr;
  374. }
  375. glyph_lru_list_handle_map.emplace(character, glyph_lru_list.add(character));
  376. new_characters.push_back(character);
  377. }
  378. else
  379. {
  380. return nullptr;
  381. }
  382. }
  383. const FontGlyph* glyph = &it_glyph->second;
  384. return glyph;
  385. }
  386. FontFaceLayer* FontFaceHandleDefault::GetOrCreateLayer(const SharedPtr<const FontEffect>& font_effect)
  387. {
  388. // Search for the font effect layer first, it may have been instanced before as part of a different configuration.
  389. const FontEffect* font_effect_ptr = font_effect.get();
  390. auto it =
  391. std::find_if(layers.begin(), layers.end(), [font_effect_ptr](const EffectLayerPair& pair) { return pair.font_effect == font_effect_ptr; });
  392. if (it != layers.end())
  393. return it->layer.get();
  394. // No existing effect matches, generate a new layer for the effect.
  395. layers.push_back(EffectLayerPair{font_effect_ptr, nullptr});
  396. auto& layer = layers.back().layer;
  397. layer = MakeUnique<FontFaceLayer>(font_effect);
  398. GenerateLayer(layer.get());
  399. return layer.get();
  400. }
  401. bool FontFaceHandleDefault::GenerateLayer(FontFaceLayer* layer)
  402. {
  403. RMLUI_ASSERT(layer);
  404. const FontEffect* font_effect = layer->GetFontEffect();
  405. bool result = false;
  406. if (!font_effect)
  407. {
  408. result = layer->Generate(this, new_glyphs);
  409. }
  410. else
  411. {
  412. // Determine which, if any, layer the new layer should copy its geometry and textures from.
  413. FontFaceLayer* clone = nullptr;
  414. bool clone_glyph_origins = true;
  415. String generation_key;
  416. size_t fingerprint = font_effect->GetFingerprint();
  417. if (!font_effect->HasUniqueTexture())
  418. {
  419. clone = base_layer;
  420. clone_glyph_origins = false;
  421. }
  422. else
  423. {
  424. auto cache_iterator = layer_cache.find(fingerprint);
  425. if (cache_iterator != layer_cache.end() && cache_iterator->second != layer)
  426. clone = cache_iterator->second;
  427. }
  428. // Create a new layer.
  429. result = layer->Generate(this, new_glyphs, clone, clone_glyph_origins);
  430. // Cache the layer in the layer cache if it generated its own textures (ie, didn't clone).
  431. if (!clone)
  432. layer_cache[fingerprint] = layer;
  433. }
  434. return result;
  435. }
  436. } // namespace Rml