FontFaceBitmap.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. // Copyright (c) 2008-2022 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Core/Context.h"
  5. #include "../Graphics/Graphics.h"
  6. #include "../GraphicsAPI/Texture2D.h"
  7. #include "../IO/File.h"
  8. #include "../IO/FileSystem.h"
  9. #include "../IO/Log.h"
  10. #include "../IO/MemoryBuffer.h"
  11. #include "../Resource/ResourceCache.h"
  12. #include "../UI/Font.h"
  13. #include "../UI/FontFaceBitmap.h"
  14. #include "../UI/UI.h"
  15. #include "../DebugNew.h"
  16. namespace Urho3D
  17. {
  18. FontFaceBitmap::FontFaceBitmap(Font* font) :
  19. FontFace(font)
  20. {
  21. }
  22. FontFaceBitmap::~FontFaceBitmap() = default;
  23. // FIXME: The Load() and Save() should be refactored accordingly after the recent FontGlyph struct changes
  24. bool FontFaceBitmap::Load(const unsigned char* fontData, unsigned fontDataSize, float pointSize)
  25. {
  26. Context* context = font_->GetContext();
  27. SharedPtr<XMLFile> xmlReader(new XMLFile(context));
  28. MemoryBuffer memoryBuffer(fontData, fontDataSize);
  29. if (!xmlReader->Load(memoryBuffer))
  30. {
  31. URHO3D_LOGERROR("Could not load XML file");
  32. return false;
  33. }
  34. XMLElement root = xmlReader->GetRoot("font");
  35. if (root.IsNull())
  36. {
  37. URHO3D_LOGERROR("Could not find Font element");
  38. return false;
  39. }
  40. XMLElement pagesElem = root.GetChild("pages");
  41. if (pagesElem.IsNull())
  42. {
  43. URHO3D_LOGERROR("Could not find Pages element");
  44. return false;
  45. }
  46. XMLElement infoElem = root.GetChild("info");
  47. if (!infoElem.IsNull())
  48. pointSize_ = infoElem.GetI32("size");
  49. XMLElement commonElem = root.GetChild("common");
  50. rowHeight_ = commonElem.GetI32("lineHeight");
  51. unsigned pages = commonElem.GetU32("pages");
  52. textures_.Reserve(pages);
  53. auto* resourceCache = font_->GetSubsystem<ResourceCache>();
  54. String fontPath = GetPath(font_->GetName());
  55. unsigned totalTextureSize = 0;
  56. XMLElement pageElem = pagesElem.GetChild("page");
  57. for (unsigned i = 0; i < pages; ++i)
  58. {
  59. if (pageElem.IsNull())
  60. {
  61. URHO3D_LOGERROR("Could not find Page element for page: " + String(i));
  62. return false;
  63. }
  64. // Assume the font image is in the same directory as the font description file
  65. String textureFile = fontPath + pageElem.GetAttribute("file");
  66. // Load texture manually to allow controlling the alpha channel mode
  67. SharedPtr<File> fontFile = resourceCache->GetFile(textureFile);
  68. SharedPtr<Image> fontImage(new Image(context));
  69. if (!fontFile || !fontImage->Load(*fontFile))
  70. {
  71. URHO3D_LOGERROR("Failed to load font image file");
  72. return false;
  73. }
  74. SharedPtr<Texture2D> texture = LoadFaceTexture(fontImage);
  75. if (!texture)
  76. return false;
  77. textures_.Push(texture);
  78. // Add texture to resource cache
  79. texture->SetName(fontFile->GetName());
  80. resourceCache->AddManualResource(texture);
  81. totalTextureSize += fontImage->GetWidth() * fontImage->GetHeight() * fontImage->GetComponents();
  82. pageElem = pageElem.GetNext("page");
  83. }
  84. XMLElement charsElem = root.GetChild("chars");
  85. int count = charsElem.GetI32("count");
  86. XMLElement charElem = charsElem.GetChild("char");
  87. while (!charElem.IsNull())
  88. {
  89. int id = charElem.GetI32("id");
  90. FontGlyph glyph;
  91. glyph.x_ = (short)charElem.GetI32("x");
  92. glyph.y_ = (short)charElem.GetI32("y");
  93. glyph.width_ = glyph.texWidth_ = (short)charElem.GetI32("width");
  94. glyph.height_ = glyph.texHeight_ = (short)charElem.GetI32("height");
  95. glyph.offsetX_ = (short)charElem.GetI32("xoffset");
  96. glyph.offsetY_ = (short)charElem.GetI32("yoffset");
  97. glyph.advanceX_ = (short)charElem.GetI32("xadvance");
  98. glyph.page_ = charElem.GetI32("page");
  99. assert(glyph.page_ >= 0);
  100. glyphMapping_[id] = glyph;
  101. charElem = charElem.GetNext("char");
  102. }
  103. XMLElement kerningsElem = root.GetChild("kernings");
  104. if (kerningsElem.NotNull())
  105. {
  106. XMLElement kerningElem = kerningsElem.GetChild("kerning");
  107. while (!kerningElem.IsNull())
  108. {
  109. unsigned first = kerningElem.GetI32("first");
  110. unsigned second = kerningElem.GetI32("second");
  111. unsigned value = first << 16u | second;
  112. kerningMapping_[value] = (short)kerningElem.GetI32("amount");
  113. kerningElem = kerningElem.GetNext("kerning");
  114. }
  115. }
  116. URHO3D_LOGDEBUGF("Bitmap font face %s has %d glyphs", GetFileName(font_->GetName()).CString(), count);
  117. font_->SetMemoryUse(font_->GetMemoryUse() + totalTextureSize);
  118. return true;
  119. }
  120. bool FontFaceBitmap::Load(FontFace* fontFace, bool usedGlyphs)
  121. {
  122. if (this == fontFace)
  123. return true;
  124. if (!usedGlyphs)
  125. {
  126. glyphMapping_ = fontFace->glyphMapping_;
  127. kerningMapping_ = fontFace->kerningMapping_;
  128. textures_ = fontFace->textures_;
  129. pointSize_ = fontFace->pointSize_;
  130. rowHeight_ = fontFace->rowHeight_;
  131. return true;
  132. }
  133. pointSize_ = fontFace->pointSize_;
  134. rowHeight_ = fontFace->rowHeight_;
  135. unsigned numPages = 1;
  136. int maxTextureSize = font_->GetSubsystem<UI>()->GetMaxFontTextureSize();
  137. AreaAllocator allocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, maxTextureSize, maxTextureSize);
  138. for (HashMap<c32, FontGlyph>::ConstIterator i = fontFace->glyphMapping_.Begin(); i != fontFace->glyphMapping_.End(); ++i)
  139. {
  140. FontGlyph fontGlyph = i->second_;
  141. if (!fontGlyph.used_)
  142. continue;
  143. int x, y;
  144. if (!allocator.Allocate(fontGlyph.width_ + 1, fontGlyph.height_ + 1, x, y))
  145. {
  146. ++numPages;
  147. allocator = AreaAllocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, maxTextureSize, maxTextureSize);
  148. if (!allocator.Allocate(fontGlyph.width_ + 1, fontGlyph.height_ + 1, x, y))
  149. return false;
  150. }
  151. fontGlyph.x_ = (short)x;
  152. fontGlyph.y_ = (short)y;
  153. fontGlyph.page_ = numPages - 1;
  154. glyphMapping_[i->first_] = fontGlyph;
  155. }
  156. // Assume that format is the same for all textures and that bitmap font type may have more than one component
  157. unsigned components = ConvertFormatToNumComponents(fontFace->textures_[0]->GetFormat());
  158. // Save the existing textures as image resources
  159. Vector<SharedPtr<Image>> oldImages;
  160. for (unsigned i = 0; i < fontFace->textures_.Size(); ++i)
  161. oldImages.Push(SaveFaceTexture(fontFace->textures_[i]));
  162. Vector<SharedPtr<Image>> newImages(numPages);
  163. for (unsigned i = 0; i < numPages; ++i)
  164. {
  165. SharedPtr<Image> image(new Image(font_->GetContext()));
  166. int width = maxTextureSize;
  167. int height = maxTextureSize;
  168. if (i == numPages - 1)
  169. {
  170. width = allocator.GetWidth();
  171. height = allocator.GetHeight();
  172. }
  173. image->SetSize(width, height, components);
  174. memset(image->GetData(), 0, (size_t)width * height * components);
  175. newImages[i] = image;
  176. }
  177. for (HashMap<c32, FontGlyph>::Iterator i = glyphMapping_.Begin(); i != glyphMapping_.End(); ++i)
  178. {
  179. FontGlyph& newGlyph = i->second_;
  180. const FontGlyph& oldGlyph = fontFace->glyphMapping_[i->first_];
  181. Blit(newImages[newGlyph.page_], newGlyph.x_, newGlyph.y_, newGlyph.width_, newGlyph.height_, oldImages[oldGlyph.page_],
  182. oldGlyph.x_, oldGlyph.y_, components);
  183. }
  184. textures_.Resize(newImages.Size());
  185. for (unsigned i = 0; i < newImages.Size(); ++i)
  186. textures_[i] = LoadFaceTexture(newImages[i]);
  187. for (HashMap<u32, float>::ConstIterator i = fontFace->kerningMapping_.Begin(); i != fontFace->kerningMapping_.End(); ++i)
  188. {
  189. unsigned first = (i->first_) >> 16u;
  190. unsigned second = (i->first_) & 0xffffu;
  191. if (glyphMapping_.Find(first) != glyphMapping_.End() && glyphMapping_.Find(second) != glyphMapping_.End())
  192. kerningMapping_[i->first_] = i->second_;
  193. }
  194. return true;
  195. }
  196. bool FontFaceBitmap::Save(Serializer& dest, int pointSize, const String& indentation)
  197. {
  198. Context* context = font_->GetContext();
  199. SharedPtr<XMLFile> xml(new XMLFile(context));
  200. XMLElement rootElem = xml->CreateRoot("font");
  201. // Information
  202. XMLElement childElem = rootElem.CreateChild("info");
  203. String fileName = GetFileName(font_->GetName());
  204. childElem.SetAttribute("face", fileName);
  205. childElem.SetAttribute("size", String(pointSize));
  206. // Common
  207. childElem = rootElem.CreateChild("common");
  208. childElem.SetI32("lineHeight", rowHeight_);
  209. unsigned pages = textures_.Size();
  210. childElem.SetU32("pages", pages);
  211. // Construct the path to store the texture
  212. String pathName;
  213. auto* file = dynamic_cast<File*>(&dest);
  214. if (file)
  215. // If serialize to file, use the file's path
  216. pathName = GetPath(file->GetName());
  217. else
  218. // Otherwise, use the font resource's path
  219. pathName = "Data/" + GetPath(font_->GetName());
  220. // Pages
  221. childElem = rootElem.CreateChild("pages");
  222. for (unsigned i = 0; i < pages; ++i)
  223. {
  224. XMLElement pageElem = childElem.CreateChild("page");
  225. pageElem.SetI32("id", i);
  226. String texFileName = fileName + "_" + String(i) + ".png";
  227. pageElem.SetAttribute("file", texFileName);
  228. // Save the font face texture to image file
  229. SaveFaceTexture(textures_[i], pathName + texFileName);
  230. }
  231. // Chars and kernings
  232. XMLElement charsElem = rootElem.CreateChild("chars");
  233. unsigned numGlyphs = glyphMapping_.Size();
  234. charsElem.SetI32("count", numGlyphs);
  235. for (HashMap<c32, FontGlyph>::ConstIterator i = glyphMapping_.Begin(); i != glyphMapping_.End(); ++i)
  236. {
  237. // Char
  238. XMLElement charElem = charsElem.CreateChild("char");
  239. charElem.SetI32("id", i->first_);
  240. const FontGlyph& glyph = i->second_;
  241. charElem.SetI32("x", glyph.x_);
  242. charElem.SetI32("y", glyph.y_);
  243. charElem.SetI32("width", glyph.width_);
  244. charElem.SetI32("height", glyph.height_);
  245. charElem.SetI32("xoffset", glyph.offsetX_);
  246. charElem.SetI32("yoffset", glyph.offsetY_);
  247. charElem.SetI32("xadvance", glyph.advanceX_);
  248. charElem.SetI32("page", glyph.page_);
  249. }
  250. if (!kerningMapping_.Empty())
  251. {
  252. XMLElement kerningsElem = rootElem.CreateChild("kernings");
  253. for (HashMap<u32, float>::ConstIterator i = kerningMapping_.Begin(); i != kerningMapping_.End(); ++i)
  254. {
  255. XMLElement kerningElem = kerningsElem.CreateChild("kerning");
  256. kerningElem.SetI32("first", i->first_ >> 16u);
  257. kerningElem.SetI32("second", i->first_ & 0xffffu);
  258. kerningElem.SetI32("amount", i->second_);
  259. }
  260. }
  261. return xml->Save(dest, indentation);
  262. }
  263. unsigned FontFaceBitmap::ConvertFormatToNumComponents(unsigned format)
  264. {
  265. if (format == Graphics::GetRGBAFormat())
  266. return 4;
  267. else if (format == Graphics::GetRGBFormat())
  268. return 3;
  269. else if (format == Graphics::GetLuminanceAlphaFormat())
  270. return 2;
  271. else
  272. return 1;
  273. }
  274. SharedPtr<Image> FontFaceBitmap::SaveFaceTexture(Texture2D* texture)
  275. {
  276. SharedPtr<Image> image(new Image(font_->GetContext()));
  277. image->SetSize(texture->GetWidth(), texture->GetHeight(), ConvertFormatToNumComponents(texture->GetFormat()));
  278. if (!texture->GetData(0, image->GetData()))
  279. {
  280. URHO3D_LOGERROR("Could not save texture to image resource");
  281. return SharedPtr<Image>();
  282. }
  283. return image;
  284. }
  285. bool FontFaceBitmap::SaveFaceTexture(Texture2D* texture, const String& fileName)
  286. {
  287. SharedPtr<Image> image = SaveFaceTexture(texture);
  288. return image ? image->SavePNG(fileName) : false;
  289. }
  290. void FontFaceBitmap::Blit(Image* dest, int x, int y, int width, int height, Image* source, int sourceX, int sourceY, int components)
  291. {
  292. unsigned char* destData = dest->GetData() + (y * dest->GetWidth() + x) * components;
  293. unsigned char* sourceData = source->GetData() + (sourceY * source->GetWidth() + sourceX) * components;
  294. for (int i = 0; i < height; ++i)
  295. {
  296. memcpy(destData, sourceData, (size_t)width * components);
  297. destData += dest->GetWidth() * components;
  298. sourceData += source->GetWidth() * components;
  299. }
  300. }
  301. }