FontFaceHandle.cpp 13 KB

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