FontFaceHandle.cpp 16 KB

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