FontFaceBitmap.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Context.h"
  24. #include "FileSystem.h"
  25. #include "Font.h"
  26. #include "FontFaceBitMap.h"
  27. #include "Graphics.h"
  28. #include "Log.h"
  29. #include "MemoryBuffer.h"
  30. #include "ResourceCache.h"
  31. #include "Texture2D.h"
  32. #include "UI.h"
  33. #include "XMLFile.h"
  34. #include "DebugNew.h"
  35. namespace Urho3D
  36. {
  37. FontFaceBitMap::FontFaceBitMap(Font* font) :
  38. FontFace(font)
  39. {
  40. }
  41. FontFaceBitMap::~FontFaceBitMap()
  42. {
  43. }
  44. bool FontFaceBitMap::Load(const unsigned char* fontData, unsigned fontDataSize, int pointSize)
  45. {
  46. Context* context = font_->GetContext();
  47. SharedPtr<XMLFile> xmlReader(new XMLFile(context));
  48. MemoryBuffer memoryBuffer(fontData, fontDataSize);
  49. if (!xmlReader->Load(memoryBuffer))
  50. {
  51. LOGERROR("Could not load XML file");
  52. return false;
  53. }
  54. XMLElement root = xmlReader->GetRoot("font");
  55. if (root.IsNull())
  56. {
  57. LOGERROR("Could not find Font element");
  58. return false;
  59. }
  60. XMLElement pagesElem = root.GetChild("pages");
  61. if (pagesElem.IsNull())
  62. {
  63. LOGERROR("Could not find Pages element");
  64. return false;
  65. }
  66. XMLElement infoElem = root.GetChild("info");
  67. if (!infoElem.IsNull())
  68. pointSize_ = infoElem.GetInt("size");
  69. XMLElement commonElem = root.GetChild("common");
  70. rowHeight_ = commonElem.GetInt("lineHeight");
  71. unsigned pages = commonElem.GetInt("pages");
  72. textures_.Reserve(pages);
  73. ResourceCache* resourceCache = font_->GetSubsystem<ResourceCache>();
  74. String fontPath = GetPath(font_->GetName());
  75. unsigned totalTextureSize = 0;
  76. XMLElement pageElem = pagesElem.GetChild("page");
  77. for (unsigned i = 0; i < pages; ++i)
  78. {
  79. if (pageElem.IsNull())
  80. {
  81. LOGERROR("Could not find Page element for page: " + String(i));
  82. return 0;
  83. }
  84. // Assume the font image is in the same directory as the font description file
  85. String textureFile = fontPath + pageElem.GetAttribute("file");
  86. // Load texture manually to allow controlling the alpha channel mode
  87. SharedPtr<File> fontFile = resourceCache->GetFile(textureFile);
  88. SharedPtr<Image> fontImage(new Image(context));
  89. if (!fontFile || !fontImage->Load(*fontFile))
  90. {
  91. LOGERROR("Failed to load font image file");
  92. return 0;
  93. }
  94. SharedPtr<Texture2D> texture = LoadFaceTexture(fontImage);
  95. if (!texture)
  96. return 0;
  97. textures_.Push(texture);
  98. totalTextureSize += fontImage->GetWidth() * fontImage->GetHeight() * fontImage->GetComponents();
  99. pageElem = pageElem.GetNext("page");
  100. }
  101. XMLElement charsElem = root.GetChild("chars");
  102. int count = charsElem.GetInt("count");
  103. glyphs_.Reserve(count);
  104. unsigned index = 0;
  105. XMLElement charElem = charsElem.GetChild("char");
  106. while (!charElem.IsNull())
  107. {
  108. int id = charElem.GetInt("id");
  109. FontGlyph glyph;
  110. glyph.x_ = charElem.GetInt("x");
  111. glyph.y_ = charElem.GetInt("y");
  112. glyph.width_ = charElem.GetInt("width");
  113. glyph.height_ = charElem.GetInt("height");
  114. glyph.offsetX_ = charElem.GetInt("xoffset");
  115. glyph.offsetY_ = charElem.GetInt("yoffset");
  116. glyph.advanceX_ = charElem.GetInt("xadvance");
  117. glyph.page_ = charElem.GetInt("page");
  118. glyphs_.Push(glyph);
  119. glyphMapping_[id] = index++;
  120. charElem = charElem.GetNext("char");
  121. }
  122. XMLElement kerningsElem = root.GetChild("kernings");
  123. if (kerningsElem.IsNull())
  124. hasKerning_ = false;
  125. else
  126. {
  127. XMLElement kerningElem = kerningsElem.GetChild("kerning");
  128. while (!kerningElem.IsNull())
  129. {
  130. int first = kerningElem.GetInt("first");
  131. HashMap<unsigned, unsigned>::Iterator i = glyphMapping_.Find(first);
  132. if (i != glyphMapping_.End())
  133. {
  134. int second = kerningElem.GetInt("second");
  135. int amount = kerningElem.GetInt("amount");
  136. FontGlyph& glyph = glyphs_[i->second_];
  137. glyph.kerning_[second] = amount;
  138. }
  139. kerningElem = kerningElem.GetNext("kerning");
  140. }
  141. }
  142. LOGDEBUGF("Bitmap font face %s has %d glyphs", GetFileName(font_->GetName()).CString(), count);
  143. font_->SetMemoryUse(font_->GetMemoryUse() + totalTextureSize);
  144. return true;
  145. }
  146. bool FontFaceBitMap::Load(FontFace* fontFace, bool usedGlyphs)
  147. {
  148. Context* context = font_->GetContext();
  149. int maxTextureSize = font_->GetSubsystem<UI>()->GetMaxFontTextureSize();
  150. // Clone properties
  151. pointSize_ = fontFace->pointSize_;
  152. rowHeight_ = fontFace->rowHeight_;
  153. hasKerning_ = fontFace->hasKerning_;
  154. // Assume that format is the same for all textures and that bitmap font type may have more than one component
  155. unsigned components = ConvertFormatToNumComponents(fontFace->textures_[0]->GetFormat());
  156. // Save the existing textures as image resources
  157. Vector<SharedPtr<Image> > images(fontFace->textures_.Size());
  158. for (unsigned i = 0; i < fontFace->textures_.Size(); ++i)
  159. images[i] = SaveFaceTexture(fontFace->textures_[i]);
  160. // Reallocate used glyphs to new texture(s)
  161. unsigned page = 0;
  162. unsigned index = 0;
  163. unsigned startIndex = 0;
  164. HashMap<unsigned, unsigned>::ConstIterator startIter = fontFace->glyphMapping_.Begin();
  165. HashMap<unsigned, unsigned>::ConstIterator i;
  166. while (startIter != fontFace->glyphMapping_.End())
  167. {
  168. AreaAllocator allocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, maxTextureSize, maxTextureSize);
  169. for (i = startIter; i != fontFace->glyphMapping_.End(); ++i)
  170. {
  171. FontGlyph glyph = fontFace->glyphs_[i->second_];
  172. if (!glyph.used_)
  173. continue;
  174. if (glyph.width_ && glyph.height_)
  175. {
  176. int x, y;
  177. // Reserve an empty border between glyphs for filtering
  178. if (allocator.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y))
  179. {
  180. glyph.x_ = x;
  181. glyph.y_ = y;
  182. glyph.page_ = page;
  183. }
  184. else
  185. break;
  186. }
  187. glyphs_.Push(glyph);
  188. glyphMapping_[i->first_] = index++;
  189. }
  190. int texWidth = allocator.GetWidth();
  191. int texHeight = allocator.GetHeight();
  192. // Create the image for rendering the fonts
  193. SharedPtr<Image> image(new Image(context));
  194. image->SetSize(texWidth, texHeight, components);
  195. // First clear the whole image
  196. unsigned char* imageData = image->GetData();
  197. for (int y = 0; y < texHeight; ++y)
  198. {
  199. unsigned char* dest = imageData + components * texWidth * y;
  200. memset(dest, 0, components * texWidth);
  201. }
  202. // Then render the glyphs into new image
  203. for (HashMap<unsigned, unsigned>::ConstIterator j = startIter; j != i; ++j)
  204. {
  205. FontGlyph glyph = fontFace->glyphs_[j->second_];
  206. if (!glyph.used_)
  207. continue;
  208. if (!glyph.width_ || !glyph.height_)
  209. {
  210. ++startIndex;
  211. continue;
  212. }
  213. FontGlyph packedGlyph = glyphs_[startIndex++];
  214. Image* image = images[glyph.page_];
  215. unsigned char* source = image->GetData() + components * (image->GetWidth() * glyph.y_ + glyph.x_);
  216. unsigned char* destination = imageData + components * (texWidth * packedGlyph.y_ + packedGlyph.x_);
  217. for (int i = 0; i < glyph.height_; ++i)
  218. {
  219. memcpy(destination, source, components * glyph.width_);
  220. source += components * image->GetWidth();
  221. destination += components * texWidth;
  222. }
  223. }
  224. // Finally load image into the texture
  225. SharedPtr<Texture2D> texture = LoadFaceTexture(image);
  226. if (!texture)
  227. return false;
  228. textures_.Push(texture);
  229. ++page;
  230. startIter = i;
  231. assert(index == startIndex);
  232. }
  233. return true;
  234. }
  235. bool FontFaceBitMap::Save(Serializer& dest, int pointSize)
  236. {
  237. Context* context = font_->GetContext();
  238. SharedPtr<XMLFile> xml(new XMLFile(context));
  239. XMLElement rootElem = xml->CreateRoot("font");
  240. // Information
  241. XMLElement childElem = rootElem.CreateChild("info");
  242. String fileName = GetFileName(font_->GetName());
  243. childElem.SetAttribute("face", fileName);
  244. childElem.SetAttribute("size", String(pointSize));
  245. // Common
  246. childElem = rootElem.CreateChild("common");
  247. childElem.SetInt("lineHeight", rowHeight_);
  248. unsigned pages = textures_.Size();
  249. childElem.SetInt("pages", pages);
  250. // Construct the path to store the texture
  251. String pathName;
  252. File* file = dynamic_cast<File*>(&dest);
  253. if (file)
  254. // If serialize to file, use the file's path
  255. pathName = GetPath(file->GetName());
  256. else
  257. // Otherwise, use the font resource's path
  258. pathName = "Data/" + GetPath(font_->GetName());
  259. // Pages
  260. childElem = rootElem.CreateChild("pages");
  261. for (unsigned i = 0; i < pages; ++i)
  262. {
  263. XMLElement pageElem = childElem.CreateChild("page");
  264. pageElem.SetInt("id", i);
  265. String texFileName = fileName + "_" + String(i) + ".png";
  266. pageElem.SetAttribute("file", texFileName);
  267. // Save the font face texture to image file
  268. SaveFaceTexture(textures_[i], pathName + texFileName);
  269. }
  270. // Chars and kernings
  271. XMLElement charsElem = rootElem.CreateChild("chars");
  272. unsigned numGlyphs = glyphs_.Size();
  273. charsElem.SetInt("count", numGlyphs);
  274. XMLElement kerningsElem;
  275. bool hasKerning = hasKerning_;
  276. if (hasKerning)
  277. kerningsElem = rootElem.CreateChild("kernings");
  278. for (HashMap<unsigned, unsigned>::ConstIterator i = glyphMapping_.Begin(); i != glyphMapping_.End(); ++i)
  279. {
  280. // Char
  281. XMLElement charElem = charsElem.CreateChild("char");
  282. charElem.SetInt("id", i->first_);
  283. FontGlyph glyph = glyphs_[i->second_];
  284. charElem.SetInt("x", glyph.x_);
  285. charElem.SetInt("y", glyph.y_);
  286. charElem.SetInt("width", glyph.width_);
  287. charElem.SetInt("height", glyph.height_);
  288. charElem.SetInt("xoffset", glyph.offsetX_);
  289. charElem.SetInt("yoffset", glyph.offsetY_);
  290. charElem.SetInt("xadvance", glyph.advanceX_);
  291. charElem.SetInt("page", glyph.page_);
  292. // Kerning
  293. if (hasKerning)
  294. {
  295. for (HashMap<unsigned, unsigned>::ConstIterator j = glyph.kerning_.Begin(); j != glyph.kerning_.End(); ++j)
  296. {
  297. // To conserve space, only write when amount is non zero
  298. if (j->second_ == 0)
  299. continue;
  300. XMLElement kerningElem = kerningsElem.CreateChild("kerning");
  301. kerningElem.SetInt("first", i->first_);
  302. kerningElem.SetInt("second", j->first_);
  303. kerningElem.SetInt("amount", j->second_);
  304. }
  305. }
  306. }
  307. return xml->Save(dest);
  308. }
  309. unsigned FontFaceBitMap::ConvertFormatToNumComponents(unsigned format)
  310. {
  311. if (format == Graphics::GetRGBAFormat())
  312. return 4;
  313. else if (format == Graphics::GetRGBFormat())
  314. return 3;
  315. else if (format == Graphics::GetLuminanceAlphaFormat())
  316. return 2;
  317. else
  318. return 1;
  319. }
  320. SharedPtr<Image> FontFaceBitMap::SaveFaceTexture(Texture2D* texture)
  321. {
  322. Image* image = new Image(font_->GetContext());
  323. image->SetSize(texture->GetWidth(), texture->GetHeight(), ConvertFormatToNumComponents(texture->GetFormat()));
  324. if (!static_cast<Texture2D*>(texture)->GetData(0, image->GetData()))
  325. {
  326. delete image;
  327. LOGERROR("Could not save texture to image resource");
  328. return SharedPtr<Image>();
  329. }
  330. return SharedPtr<Image>(image);
  331. }
  332. bool FontFaceBitMap::SaveFaceTexture(Texture2D* texture, const String& fileName)
  333. {
  334. SharedPtr<Image> image = SaveFaceTexture(texture);
  335. return image ? image->SavePNG(fileName) : false;
  336. }
  337. }