FontEngineBitmap.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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-2023 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 "FontEngineBitmap.h"
  29. #include <RmlUi/Core/Core.h>
  30. #include <RmlUi/Core/FileInterface.h>
  31. #include <RmlUi/Core/GeometryUtilities.h>
  32. #include <RmlUi/Core/StreamMemory.h>
  33. #include <cstdio>
  34. namespace FontProviderBitmap {
  35. static Rml::Vector<Rml::UniquePtr<FontFaceBitmap>> fonts;
  36. void Initialise() {}
  37. void Shutdown()
  38. {
  39. fonts.clear();
  40. }
  41. bool LoadFontFace(const String& file_name)
  42. {
  43. // Load the xml meta file into memory
  44. Rml::UniquePtr<byte[]> data;
  45. size_t length = 0;
  46. {
  47. auto file_interface = Rml::GetFileInterface();
  48. auto handle = file_interface->Open(file_name);
  49. if (!handle)
  50. return false;
  51. length = file_interface->Length(handle);
  52. data.reset(new byte[length]);
  53. size_t read_length = file_interface->Read(data.get(), length, handle);
  54. file_interface->Close(handle);
  55. if (read_length != length || !data)
  56. return false;
  57. }
  58. // Parse the xml font description
  59. FontParserBitmap parser;
  60. {
  61. auto stream = Rml::MakeUnique<Rml::StreamMemory>(data.get(), length);
  62. stream->SetSourceURL(file_name);
  63. parser.Parse(stream.get());
  64. if (parser.family.empty() || parser.glyphs.empty() || parser.texture_name.empty() || parser.metrics.size == 0)
  65. return false;
  66. // Fill the remaining metrics
  67. parser.metrics.underline_position = 3.f;
  68. parser.metrics.underline_thickness = 1.f;
  69. }
  70. Texture texture;
  71. texture.Set(parser.texture_name, file_name);
  72. // Construct and add the font face
  73. fonts.push_back(Rml::MakeUnique<FontFaceBitmap>(parser.family, parser.style, parser.weight, parser.metrics, texture, parser.texture_dimensions,
  74. std::move(parser.glyphs), std::move(parser.kerning)));
  75. return true;
  76. }
  77. FontFaceBitmap* GetFontFaceHandle(const String& family, FontStyle style, FontWeight weight, int size)
  78. {
  79. FontFaceBitmap* best_match = nullptr;
  80. int best_score = 0;
  81. // Normally, we'd want to only match the font family exactly, but for this demo we create a very lenient heuristic.
  82. for (const auto& font : fonts)
  83. {
  84. int score = 1;
  85. if (font->GetFamily() == family)
  86. score += 100;
  87. score += 10 - std::min(10, std::abs(font->GetMetrics().size - size));
  88. if (font->GetStyle() == style)
  89. score += 2;
  90. if (font->GetWeight() == weight)
  91. score += 1;
  92. if (score > best_score)
  93. {
  94. best_match = font.get();
  95. best_score = score;
  96. }
  97. }
  98. return best_match;
  99. }
  100. } // namespace FontProviderBitmap
  101. FontFaceBitmap::FontFaceBitmap(String family, FontStyle style, FontWeight weight, FontMetrics metrics, Texture texture, Vector2f texture_dimensions,
  102. FontGlyphs&& glyphs, FontKerning&& kerning) :
  103. family(family),
  104. style(style), weight(weight), metrics(metrics), texture(texture), texture_dimensions(texture_dimensions), glyphs(std::move(glyphs)),
  105. 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(&vertices[0] + (vertices.size() - 4), &indices[0] + (indices.size() - 6),
  151. Vector2f(position + glyph.offset).Round(), glyph.dimension, colour, uv_top_left, uv_bottom_right, (int)vertices.size() - 4);
  152. width += glyph.advance;
  153. position.x += glyph.advance;
  154. previous_character = character;
  155. }
  156. return width;
  157. }
  158. int FontFaceBitmap::GetKerning(Character left, Character right) const
  159. {
  160. uint64_t key = (((uint64_t)left << 32) | (uint64_t)right);
  161. auto it = kerning.find(key);
  162. if (it != kerning.end())
  163. return it->second;
  164. return 0;
  165. }
  166. FontParserBitmap::~FontParserBitmap() {}
  167. void FontParserBitmap::HandleElementStart(const String& name, const Rml::XMLAttributes& attributes)
  168. {
  169. if (name == "info")
  170. {
  171. family = Rml::StringUtilities::ToLower(Get(attributes, "face", String()));
  172. metrics.size = Get(attributes, "size", 0);
  173. style = Get(attributes, "italic", 0) == 1 ? FontStyle::Italic : FontStyle::Normal;
  174. weight = Get(attributes, "bold", 0) == 1 ? FontWeight::Bold : FontWeight::Normal;
  175. }
  176. else if (name == "common")
  177. {
  178. metrics.line_spacing = Get(attributes, "lineHeight", 0.f);
  179. metrics.ascent = Get(attributes, "base", 0.f);
  180. metrics.descent = metrics.line_spacing - metrics.ascent;
  181. texture_dimensions.x = Get(attributes, "scaleW", 0.f);
  182. texture_dimensions.y = Get(attributes, "scaleH", 0.f);
  183. }
  184. else if (name == "page")
  185. {
  186. int id = Get(attributes, "id", -1);
  187. if (id != 0)
  188. {
  189. Rml::Log::Message(Rml::Log::LT_WARNING, "Only single font textures are supported in Bitmap Font Engine");
  190. return;
  191. }
  192. texture_name = Get(attributes, "file", String());
  193. }
  194. else if (name == "char")
  195. {
  196. Character character = (Character)Get(attributes, "id", 0);
  197. if (character == Character::Null)
  198. return;
  199. BitmapGlyph& glyph = glyphs[character];
  200. glyph.offset.x = Get(attributes, "xoffset", 0.f);
  201. glyph.offset.y = Get(attributes, "yoffset", 0.f) - metrics.ascent; // Shift y-origin from top to baseline
  202. glyph.advance = Get(attributes, "xadvance", 0);
  203. glyph.position.x = Get(attributes, "x", 0.f);
  204. glyph.position.y = Get(attributes, "y", 0.f);
  205. glyph.dimension.x = Get(attributes, "width", 0.f);
  206. glyph.dimension.y = Get(attributes, "height", 0.f);
  207. if (character == (Character)'x')
  208. metrics.x_height = glyph.dimension.y;
  209. }
  210. else if (name == "kerning")
  211. {
  212. uint64_t first = (uint64_t)Get(attributes, "first", 0);
  213. uint64_t second = (uint64_t)Get(attributes, "second", 0);
  214. int amount = Get(attributes, "amount", 0);
  215. if (first != 0 && second != 0 && amount != 0)
  216. {
  217. uint64_t key = ((first << 32) | second);
  218. kerning[key] = amount;
  219. }
  220. }
  221. }
  222. void FontParserBitmap::HandleElementEnd(const String& /*name*/) {}
  223. void FontParserBitmap::HandleData(const String& /*data*/, Rml::XMLDataType /*type*/) {}