FontFaceHandle.cpp 16 KB

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