FontFaceHandle.cpp 15 KB

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