FontEngineBitmap.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 <cstdio>
  29. #include <RmlUi/Core.h>
  30. #include <RmlUi/Core/StreamMemory.h>
  31. #include "FontEngineBitmap.h"
  32. namespace FontProviderBitmap
  33. {
  34. static Rml::Vector<Rml::UniquePtr<FontFaceBitmap>> fonts;
  35. void Initialise()
  36. {
  37. }
  38. void Shutdown()
  39. {
  40. fonts.clear();
  41. }
  42. bool LoadFontFace(const String& file_name)
  43. {
  44. // Load the xml meta file into memory
  45. Rml::UniquePtr<byte[]> data;
  46. size_t length = 0;
  47. {
  48. auto file_interface = Rml::GetFileInterface();
  49. auto handle = file_interface->Open(file_name);
  50. if (!handle)
  51. return false;
  52. length = file_interface->Length(handle);
  53. data.reset(new byte[length]);
  54. size_t read_length = file_interface->Read(data.get(), length, handle);
  55. file_interface->Close(handle);
  56. if (read_length != length || !data)
  57. return false;
  58. }
  59. // Parse the xml font description
  60. FontParserBitmap parser;
  61. {
  62. auto stream = Rml::MakeUnique<Rml::StreamMemory>(data.get(), length);
  63. stream->SetSourceURL(file_name);
  64. parser.Parse(stream.get());
  65. if (parser.family.empty() || parser.glyphs.empty() || parser.texture_name.empty() || parser.metrics.size == 0)
  66. return false;
  67. // Fill the remaining metrics
  68. parser.metrics.underline_position = -parser.metrics.baseline - 1.f;
  69. parser.metrics.underline_thickness = 1.f;
  70. }
  71. Texture texture;
  72. texture.Set(parser.texture_name, file_name);
  73. // Construct and add the font face
  74. fonts.push_back(
  75. Rml::MakeUnique<FontFaceBitmap>(
  76. parser.family, parser.style, parser.weight, parser.metrics, texture, parser.texture_dimensions, std::move(parser.glyphs), std::move(parser.kerning)
  77. ));
  78. return true;
  79. }
  80. FontFaceBitmap* GetFontFaceHandle(const String& family, FontStyle style, FontWeight weight, int size)
  81. {
  82. FontFaceBitmap* best_match = nullptr;
  83. int best_score = 0;
  84. // Normally, we'd want to only match the font family exactly, but for this demo we create a very lenient heuristic.
  85. for (const auto& font : fonts)
  86. {
  87. int score = 1;
  88. if (font->GetFamily() == family)
  89. score += 100;
  90. score += 10 - std::min(10, std::abs(font->GetMetrics().size - size));
  91. if (font->GetStyle() == style)
  92. score += 2;
  93. if (font->GetWeight() == weight)
  94. score += 1;
  95. if (score > best_score)
  96. {
  97. best_match = font.get();
  98. best_score = score;
  99. }
  100. }
  101. return best_match;
  102. }
  103. }
  104. FontFaceBitmap::FontFaceBitmap(String family, FontStyle style, FontWeight weight, FontMetrics metrics, Texture texture, Vector2f texture_dimensions, FontGlyphs&& glyphs, FontKerning&& kerning)
  105. : family(family), style(style), weight(weight), metrics(metrics), texture(texture), texture_dimensions(texture_dimensions), glyphs(std::move(glyphs)), kerning(std::move(kerning))
  106. {}
  107. int FontFaceBitmap::GetStringWidth(const String& string, Character previous_character)
  108. {
  109. int width = 0;
  110. for (auto it_char = Rml::StringIteratorU8(string); it_char; ++it_char)
  111. {
  112. Character character = *it_char;
  113. auto it_glyph = glyphs.find(character);
  114. if (it_glyph == glyphs.end())
  115. continue;
  116. const BitmapGlyph& glyph = it_glyph->second;
  117. int kerning = GetKerning(previous_character, character);
  118. width += glyph.advance + kerning;
  119. previous_character = character;
  120. }
  121. return width;
  122. }
  123. int FontFaceBitmap::GenerateString(const String& string, const Vector2f& string_position, const Colourb& colour, GeometryList& geometry_list)
  124. {
  125. int width = 0;
  126. geometry_list.resize(1);
  127. Rml::Geometry& geometry = geometry_list[0];
  128. geometry.SetTexture(&texture);
  129. auto& vertices = geometry.GetVertices();
  130. auto& indices = geometry.GetIndices();
  131. vertices.reserve(string.size() * 4);
  132. indices.reserve(string.size() * 6);
  133. Vector2f position = string_position.Round();
  134. Character previous_character = Character::Null;
  135. for (auto it_char = Rml::StringIteratorU8(string); it_char; ++it_char)
  136. {
  137. Character character = *it_char;
  138. auto it_glyph = glyphs.find(character);
  139. if (it_glyph == glyphs.end())
  140. continue;
  141. int kerning = GetKerning(previous_character, character);
  142. width += kerning;
  143. position.x += kerning;
  144. const BitmapGlyph& glyph = it_glyph->second;
  145. // Generate the geometry for the character.
  146. vertices.resize(vertices.size() + 4);
  147. indices.resize(indices.size() + 6);
  148. Vector2f uv_top_left = glyph.position / texture_dimensions;
  149. Vector2f uv_bottom_right = (glyph.position + glyph.dimension) / texture_dimensions;
  150. Rml::GeometryUtilities::GenerateQuad(
  151. &vertices[0] + (vertices.size() - 4),
  152. &indices[0] + (indices.size() - 6),
  153. Vector2f(position + glyph.offset).Round(),
  154. glyph.dimension,
  155. colour,
  156. uv_top_left,
  157. uv_bottom_right,
  158. (int)vertices.size() - 4
  159. );
  160. width += glyph.advance;
  161. position.x += glyph.advance;
  162. previous_character = character;
  163. }
  164. return width;
  165. }
  166. int FontFaceBitmap::GetKerning(Character left, Character right) const
  167. {
  168. std::uint64_t key = (((std::uint64_t)left << 32) | (std::uint64_t)right);
  169. auto it = kerning.find(key);
  170. if (it != kerning.end())
  171. return it->second;
  172. return 0;
  173. }
  174. FontParserBitmap::~FontParserBitmap()
  175. {
  176. }
  177. // Called when the parser finds the beginning of an element tag.
  178. void FontParserBitmap::HandleElementStart(const String& name, const Rml::XMLAttributes& attributes)
  179. {
  180. if (name == "info")
  181. {
  182. family = Rml::StringUtilities::ToLower( Get(attributes, "face", String()) );
  183. metrics.size = Get(attributes, "size", 0);
  184. style = Get(attributes, "italic", 0) == 1 ? FontStyle::Italic : FontStyle::Normal;
  185. weight = Get(attributes, "bold", 0) == 1 ? FontWeight::Bold : FontWeight::Normal;
  186. }
  187. else if (name == "common")
  188. {
  189. metrics.line_height = Get(attributes, "lineHeight", 0);
  190. metrics.baseline = metrics.line_height - Get(attributes, "base", 0);
  191. texture_dimensions.x = Get(attributes, "scaleW", 0.f);
  192. texture_dimensions.y = Get(attributes, "scaleH", 0.f);
  193. }
  194. else if (name == "page")
  195. {
  196. int id = Get(attributes, "id", -1);
  197. if(id != 0)
  198. {
  199. Rml::Log::Message(Rml::Log::LT_WARNING, "Only single font textures are supported in Bitmap Font Engine");
  200. return;
  201. }
  202. texture_name = Get(attributes, "file", String());
  203. }
  204. else if (name == "char")
  205. {
  206. Character character = (Character)Get(attributes, "id", 0);
  207. if (character == Character::Null)
  208. return;
  209. BitmapGlyph& glyph = glyphs[character];
  210. glyph.advance = Get(attributes, "xadvance", 0);
  211. // Shift y-origin from top to baseline
  212. float origin_shift_y = float(metrics.baseline - metrics.line_height);
  213. glyph.offset.x = Get(attributes, "xoffset", 0.f);
  214. glyph.offset.y = Get(attributes, "yoffset", 0.f) + origin_shift_y;
  215. glyph.position.x = Get(attributes, "x", 0.f);
  216. glyph.position.y = Get(attributes, "y", 0.f);
  217. glyph.dimension.x = Get(attributes, "width", 0.f);
  218. glyph.dimension.y = Get(attributes, "height", 0.f);
  219. if (character == (Character)'x')
  220. metrics.x_height = (int)glyph.dimension.y;
  221. }
  222. else if (name == "kerning")
  223. {
  224. std::uint64_t first = (std::uint64_t)Get(attributes, "first", 0);
  225. std::uint64_t second = (std::uint64_t)Get(attributes, "second", 0);
  226. int amount = Get(attributes, "amount", 0);
  227. if (first != 0 && second != 0 && amount != 0)
  228. {
  229. std::uint64_t key = ((first << 32) | second);
  230. kerning[key] = amount;
  231. }
  232. }
  233. }
  234. // Called when the parser finds the end of an element tag.
  235. void FontParserBitmap::HandleElementEnd(const String& RMLUI_UNUSED_PARAMETER(name))
  236. {
  237. RMLUI_UNUSED(name);
  238. }
  239. // Called when the parser encounters data.
  240. void FontParserBitmap::HandleData(const String& RMLUI_UNUSED_PARAMETER(data), Rml::XMLDataType RMLUI_UNUSED_PARAMETER(type))
  241. {
  242. RMLUI_UNUSED(data);
  243. RMLUI_UNUSED(type);
  244. }