FontFaceHandle.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 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 "precompiled.h"
  29. #include "FontFaceHandle.h"
  30. #include "FontFaceLayer.h"
  31. #include <algorithm>
  32. #include "../TextureLayout.h"
  33. namespace Rml {
  34. namespace Core {
  35. namespace BitmapFont {
  36. class FontEffectSort
  37. {
  38. public:
  39. bool operator()(const Rml::Core::FontEffect* lhs, const Rml::Core::FontEffect* rhs)
  40. {
  41. return lhs->GetZIndex() < rhs->GetZIndex();
  42. }
  43. };
  44. FontFaceHandle::FontFaceHandle()
  45. {
  46. size = 0;
  47. average_advance = 0;
  48. x_height = 0;
  49. line_height = 0;
  50. baseline = 0;
  51. underline_position = 0;
  52. underline_thickness = 0;
  53. base_layer = NULL;
  54. }
  55. FontFaceHandle::~FontFaceHandle()
  56. {
  57. }
  58. // Initialises the handle so it is able to render text.
  59. bool FontFaceHandle::Initialise(BitmapFontDefinitions *bm_face, const String& _charset, int _size)
  60. {
  61. this->bm_face = bm_face;
  62. size = _size;
  63. line_height = _size;
  64. texture_width = bm_face->CommonCharactersInfo.ScaleWidth;
  65. texture_height = bm_face->CommonCharactersInfo.ScaleHeight;
  66. raw_charset = _charset;
  67. // Construct proper path to texture
  68. URL fnt_source = bm_face->Face.Source;
  69. URL bitmap_source = bm_face->Face.BitmapSource;
  70. if(bitmap_source.GetPath().Empty())
  71. {
  72. texture_source = fnt_source.GetPath() + bitmap_source.GetFileName();
  73. if(!bitmap_source.GetExtension().Empty())
  74. {
  75. texture_source += "." + bitmap_source.GetExtension();
  76. }
  77. }
  78. else
  79. {
  80. texture_source = bitmap_source.GetPathedFileName();
  81. }
  82. if (!UnicodeRange::BuildList(charset, raw_charset))
  83. {
  84. Log::Message(Log::LT_ERROR, "Invalid font charset '%s'.", raw_charset.CString());
  85. return false;
  86. }
  87. // Construct the list of the characters specified by the charset.
  88. for (size_t i = 0; i < charset.size(); ++i)
  89. BuildGlyphMap(bm_face, charset[i]);
  90. // Generate the metrics for the handle.
  91. GenerateMetrics(bm_face);
  92. // Generate the default layer and layer configuration.
  93. base_layer = GenerateLayer(NULL);
  94. layer_configurations.push_back(LayerConfiguration());
  95. layer_configurations.back().push_back(base_layer);
  96. return true;
  97. }
  98. // Returns the width a string will take up if rendered with this handle.
  99. int FontFaceHandle::GetStringWidth(const WString& string, word prior_character) const
  100. {
  101. int width = 0;
  102. for (size_t i = 0; i < string.Length(); i++)
  103. {
  104. word character_code = string[i];
  105. if (character_code >= glyphs.size())
  106. continue;
  107. const FontGlyph &glyph = glyphs[character_code];
  108. // Adjust the cursor for the kerning between this character and the previous one.
  109. if (prior_character != 0)
  110. width += GetKerning(prior_character, string[i]);
  111. // Adjust the cursor for this character's advance.
  112. width += glyph.advance;
  113. prior_character = character_code;
  114. }
  115. return width;
  116. }
  117. // Generates, if required, the layer configuration for a given array of font effects.
  118. int FontFaceHandle::GenerateLayerConfiguration(FontEffectMap& font_effects)
  119. {
  120. if (font_effects.empty())
  121. return 0;
  122. // Prepare a list of effects, sorted by z-index.
  123. FontEffectList sorted_effects;
  124. for (FontEffectMap::const_iterator i = font_effects.begin(); i != font_effects.end(); ++i)
  125. sorted_effects.push_back(i->second);
  126. std::sort(sorted_effects.begin(), sorted_effects.end(), FontEffectSort());
  127. // Check each existing configuration for a match with this arrangement of effects.
  128. int configuration_index = 1;
  129. for (; configuration_index < (int) layer_configurations.size(); ++configuration_index)
  130. {
  131. const LayerConfiguration& configuration = layer_configurations[configuration_index];
  132. // Check the size is correct. For a math, there should be one layer in the configuration
  133. // plus an extra for the base layer.
  134. if (configuration.size() != sorted_effects.size() + 1)
  135. continue;
  136. // Check through each layer, checking it was created by the same effect as the one we're
  137. // checking.
  138. size_t effect_index = 0;
  139. for (size_t i = 0; i < configuration.size(); ++i)
  140. {
  141. // Skip the base layer ...
  142. if (configuration[i]->GetFontEffect() == NULL)
  143. continue;
  144. // If the ith layer's effect doesn't match the equivalent effect, then this
  145. // configuration can't match.
  146. if (configuration[i]->GetFontEffect() != sorted_effects[effect_index])
  147. break;
  148. // Check the next one ...
  149. ++effect_index;
  150. }
  151. if (effect_index == sorted_effects.size())
  152. return configuration_index;
  153. }
  154. // No match, so we have to generate a new layer configuration.
  155. layer_configurations.push_back(LayerConfiguration());
  156. LayerConfiguration& layer_configuration = layer_configurations.back();
  157. bool added_base_layer = false;
  158. for (size_t i = 0; i < sorted_effects.size(); ++i)
  159. {
  160. if (!added_base_layer &&
  161. sorted_effects[i]->GetZIndex() >= 0)
  162. {
  163. layer_configuration.push_back(base_layer);
  164. added_base_layer = true;
  165. }
  166. layer_configuration.push_back(GenerateLayer(sorted_effects[i]));
  167. }
  168. // Add the base layer now if we still haven't added it.
  169. if (!added_base_layer)
  170. layer_configuration.push_back(base_layer);
  171. return (int) (layer_configurations.size() - 1);
  172. }
  173. // Generates the texture data for a layer (for the texture database).
  174. bool FontFaceHandle::GenerateLayerTexture(const byte*& texture_data, Vector2i& texture_dimensions, Rml::Core::FontEffect* layer_id, int texture_id)
  175. {
  176. FontLayerMap::iterator layer_iterator = layers.find(layer_id);
  177. if (layer_iterator == layers.end())
  178. return false;
  179. return layer_iterator->second->GenerateTexture(texture_data, texture_dimensions, texture_id);
  180. }
  181. // Generates the geometry required to render a single line of text.
  182. int FontFaceHandle::GenerateString(GeometryList& geometry, const WString& string, const Vector2f& position, const Colourb& colour, int layer_configuration_index) const
  183. {
  184. int geometry_index = 0;
  185. int line_width = 0;
  186. RMLUI_ASSERT(layer_configuration_index >= 0);
  187. RMLUI_ASSERT(layer_configuration_index < (int) layer_configurations.size());
  188. // Fetch the requested configuration and generate the geometry for each one.
  189. const LayerConfiguration& layer_configuration = layer_configurations[layer_configuration_index];
  190. for (size_t i = 0; i < layer_configuration.size(); ++i)
  191. {
  192. Rml::Core::FontFaceLayer* layer = layer_configuration[i];
  193. Colourb layer_colour;
  194. if (layer == base_layer)
  195. layer_colour = colour;
  196. else
  197. layer_colour = layer->GetColour();
  198. // Resize the geometry list if required.
  199. if ((int) geometry.size() < geometry_index + layer->GetNumTextures())
  200. geometry.resize(geometry_index + layer->GetNumTextures());
  201. // Bind the textures to the geometries.
  202. for (int i = 0; i < layer->GetNumTextures(); ++i)
  203. geometry[geometry_index + i].SetTexture(layer->GetTexture(i));
  204. line_width = 0;
  205. word prior_character = 0;
  206. const word* string_iterator = string.CString();
  207. const word* string_end = string.CString() + string.Length();
  208. for (; string_iterator != string_end; string_iterator++)
  209. {
  210. if (*string_iterator >= glyphs.size())
  211. continue;
  212. const FontGlyph &glyph = glyphs[*string_iterator];
  213. // Adjust the cursor for the kerning between this character and the previous one.
  214. if (prior_character != 0)
  215. line_width += GetKerning(prior_character, *string_iterator);
  216. layer->GenerateGeometry(&geometry[geometry_index], *string_iterator, Vector2f(position.x + line_width, position.y), layer_colour);
  217. line_width += glyph.advance;
  218. prior_character = *string_iterator;
  219. }
  220. geometry_index += layer->GetNumTextures();
  221. }
  222. // Cull any excess geometry from a previous generation.
  223. geometry.resize(geometry_index);
  224. return line_width;
  225. }
  226. // Generates the geometry required to render a line above, below or through a line of text.
  227. void FontFaceHandle::GenerateLine(Geometry* geometry, const Vector2f& position, int width, Font::Line height, const Colourb& colour) const
  228. {
  229. std::vector< Vertex >& line_vertices = geometry->GetVertices();
  230. std::vector< int >& line_indices = geometry->GetIndices();
  231. float offset;
  232. switch (height)
  233. {
  234. case Font::UNDERLINE: offset = -underline_position; break;
  235. case Font::OVERLINE: // where to place? offset = -line_height - underline_position; break;
  236. case Font::STRIKE_THROUGH: // where to place? offset = -line_height * 0.5f; break;
  237. default: return;
  238. }
  239. line_vertices.resize(line_vertices.size() + 4);
  240. line_indices.resize(line_indices.size() + 6);
  241. GeometryUtilities::GenerateQuad(
  242. &line_vertices[0] + ((int)line_vertices.size() - 4),
  243. &line_indices[0] + ((int)line_indices.size() - 6),
  244. Vector2f(position.x, position.y + offset),
  245. Vector2f((float) width, underline_thickness),
  246. colour,
  247. (int)line_vertices.size() - 4
  248. );
  249. }
  250. // Destroys the handle.
  251. void FontFaceHandle::OnReferenceDeactivate()
  252. {
  253. delete this;
  254. }
  255. void FontFaceHandle::GenerateMetrics(BitmapFontDefinitions *bm_face)
  256. {
  257. line_height = bm_face->CommonCharactersInfo.LineHeight;
  258. baseline = bm_face->CommonCharactersInfo.BaseLine;
  259. underline_position = (float)line_height - bm_face->CommonCharactersInfo.BaseLine;
  260. baseline += int( underline_position / 1.6f );
  261. underline_thickness = 1.0f;
  262. average_advance = 0;
  263. for (FontGlyphList::iterator i = glyphs.begin(); i != glyphs.end(); ++i)
  264. average_advance += i->advance;
  265. // Bring the total advance down to the average advance, but scaled up 10%, just to be on the safe side.
  266. average_advance = Math::RealToInteger((float) average_advance / (glyphs.size() * 0.9f));
  267. // Determine the x-height of this font face.
  268. word x = (word) 'x';
  269. int index = bm_face->BM_Helper_GetCharacterTableIndex( x );// FT_Get_Char_Index(ft_face, x);
  270. if ( index >= 0)
  271. x_height = bm_face->CharactersInfo[ index ].Height;
  272. else
  273. x_height = 0;
  274. }
  275. void FontFaceHandle::BuildGlyphMap(BitmapFontDefinitions *bm_face, const UnicodeRange& unicode_range)
  276. {
  277. glyphs.resize(unicode_range.max_codepoint + 1);
  278. for (word character_code = (word) (Math::Max< unsigned int >(unicode_range.min_codepoint, 32)); character_code <= unicode_range.max_codepoint; ++character_code)
  279. {
  280. int index = bm_face->BM_Helper_GetCharacterTableIndex( character_code );
  281. if ( index < 0 )
  282. {
  283. continue;
  284. }
  285. FontGlyph glyph;
  286. glyph.character = character_code;
  287. BuildGlyph(glyph, &bm_face->CharactersInfo[ index ] );
  288. glyphs[character_code] = glyph;
  289. }
  290. }
  291. void Rml::Core::BitmapFont::FontFaceHandle::BuildGlyph(FontGlyph& glyph, CharacterInfo *bm_glyph)
  292. {
  293. // Set the glyph's dimensions.
  294. glyph.dimensions.x = bm_glyph->Width;
  295. glyph.dimensions.y = bm_glyph->Height;
  296. // Set the glyph's bearing.
  297. glyph.bearing.x = bm_glyph->XOffset;
  298. glyph.bearing.y = bm_glyph->YOffset;
  299. // Set the glyph's advance.
  300. glyph.advance = bm_glyph->Advance;
  301. // Set the glyph's bitmap position.
  302. glyph.bitmap_dimensions.x = bm_glyph->X;
  303. glyph.bitmap_dimensions.y = bm_glyph->Y;
  304. glyph.bitmap_data = NULL;
  305. }
  306. int Rml::Core::BitmapFont::FontFaceHandle::GetKerning(word lhs, word rhs) const
  307. {
  308. if( bm_face != NULL)
  309. {
  310. return bm_face->BM_Helper_GetXKerning(lhs, rhs);
  311. }
  312. return 0;
  313. }
  314. // Generates (or shares) a layer derived from a font effect.
  315. Rml::Core::FontFaceLayer* FontFaceHandle::GenerateLayer( FontEffect* font_effect)
  316. {
  317. // See if this effect has been instanced before, as part of a different configuration.
  318. FontLayerMap::iterator i = layers.find(font_effect);
  319. if (i != layers.end())
  320. return i->second;
  321. Rml::Core::FontFaceLayer* layer = new Rml::Core::BitmapFont::FontFaceLayer();
  322. layers[font_effect] = layer;
  323. if (font_effect == NULL)
  324. {
  325. layer->Initialise(this);
  326. }
  327. else
  328. {
  329. // Determine which, if any, layer the new layer should copy its geometry and textures from.
  330. Rml::Core::FontFaceLayer* clone = NULL;
  331. bool deep_clone = true;
  332. String generation_key;
  333. if (!font_effect->HasUniqueTexture())
  334. {
  335. clone = base_layer;
  336. deep_clone = false;
  337. }
  338. else
  339. {
  340. generation_key = font_effect->GetName() + ";" + font_effect->GetGenerationKey();
  341. FontLayerCache::iterator cache_iterator = layer_cache.find(generation_key);
  342. if (cache_iterator != layer_cache.end())
  343. clone = cache_iterator->second;
  344. }
  345. // Create a new layer.
  346. layer->Initialise(this, font_effect, clone, deep_clone);
  347. // Cache the layer in the layer cache if it generated its own textures (ie, didn't clone).
  348. if (clone == NULL)
  349. layer_cache[generation_key] = (Rml::Core::FontFaceLayer*) layer;
  350. }
  351. return (Rml::Core::FontFaceLayer*)layer;
  352. }
  353. }
  354. }
  355. }