FontFaceBitmap.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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 "File.h"
  25. #include "FileSystem.h"
  26. #include "Font.h"
  27. #include "FontFaceBitMap.h"
  28. #include "Graphics.h"
  29. #include "Image.h"
  30. #include "Log.h"
  31. #include "MemoryBuffer.h"
  32. #include "ResourceCache.h"
  33. #include "Texture2D.h"
  34. #include "UI.h"
  35. #include "XMLFile.h"
  36. #include "DebugNew.h"
  37. namespace Urho3D
  38. {
  39. FontFaceBitMap::FontFaceBitMap(Font* font) :
  40. FontFace(font)
  41. {
  42. }
  43. FontFaceBitMap::~FontFaceBitMap()
  44. {
  45. }
  46. bool FontFaceBitMap::Load(const unsigned char* fontData, unsigned fontDataSize, int pointSize)
  47. {
  48. Context* context = font_->GetContext();
  49. SharedPtr<XMLFile> xmlReader(new XMLFile(context));
  50. MemoryBuffer memoryBuffer(fontData, fontDataSize);
  51. if (!xmlReader->Load(memoryBuffer))
  52. {
  53. LOGERROR("Could not load XML file");
  54. return false;
  55. }
  56. XMLElement root = xmlReader->GetRoot("font");
  57. if (root.IsNull())
  58. {
  59. LOGERROR("Could not find Font element");
  60. return false;
  61. }
  62. XMLElement pagesElem = root.GetChild("pages");
  63. if (pagesElem.IsNull())
  64. {
  65. LOGERROR("Could not find Pages element");
  66. return false;
  67. }
  68. XMLElement infoElem = root.GetChild("info");
  69. if (!infoElem.IsNull())
  70. pointSize_ = infoElem.GetInt("size");
  71. XMLElement commonElem = root.GetChild("common");
  72. rowHeight_ = commonElem.GetInt("lineHeight");
  73. unsigned pages = commonElem.GetInt("pages");
  74. textures_.Reserve(pages);
  75. ResourceCache* resourceCache = font_->GetSubsystem<ResourceCache>();
  76. String fontPath = GetPath(font_->GetName());
  77. unsigned totalTextureSize = 0;
  78. XMLElement pageElem = pagesElem.GetChild("page");
  79. for (unsigned i = 0; i < pages; ++i)
  80. {
  81. if (pageElem.IsNull())
  82. {
  83. LOGERROR("Could not find Page element for page: " + String(i));
  84. return 0;
  85. }
  86. // Assume the font image is in the same directory as the font description file
  87. String textureFile = fontPath + pageElem.GetAttribute("file");
  88. // Load texture manually to allow controlling the alpha channel mode
  89. SharedPtr<File> fontFile = resourceCache->GetFile(textureFile);
  90. SharedPtr<Image> fontImage(new Image(context));
  91. if (!fontFile || !fontImage->Load(*fontFile))
  92. {
  93. LOGERROR("Failed to load font image file");
  94. return 0;
  95. }
  96. SharedPtr<Texture2D> texture = LoadFaceTexture(fontImage);
  97. if (!texture)
  98. return 0;
  99. textures_.Push(texture);
  100. totalTextureSize += fontImage->GetWidth() * fontImage->GetHeight() * fontImage->GetComponents();
  101. pageElem = pageElem.GetNext("page");
  102. }
  103. XMLElement charsElem = root.GetChild("chars");
  104. int count = charsElem.GetInt("count");
  105. glyphs_.Reserve(count);
  106. unsigned index = 0;
  107. XMLElement charElem = charsElem.GetChild("char");
  108. while (!charElem.IsNull())
  109. {
  110. int id = charElem.GetInt("id");
  111. FontGlyph glyph;
  112. glyph.x_ = charElem.GetInt("x");
  113. glyph.y_ = charElem.GetInt("y");
  114. glyph.width_ = charElem.GetInt("width");
  115. glyph.height_ = charElem.GetInt("height");
  116. glyph.offsetX_ = charElem.GetInt("xoffset");
  117. glyph.offsetY_ = charElem.GetInt("yoffset");
  118. glyph.advanceX_ = charElem.GetInt("xadvance");
  119. glyph.page_ = charElem.GetInt("page");
  120. glyphs_.Push(glyph);
  121. glyphMapping_[id] = index++;
  122. charElem = charElem.GetNext("char");
  123. }
  124. XMLElement kerningsElem = root.GetChild("kernings");
  125. if (kerningsElem.IsNull())
  126. hasKerning_ = false;
  127. else
  128. {
  129. XMLElement kerningElem = kerningsElem.GetChild("kerning");
  130. while (!kerningElem.IsNull())
  131. {
  132. int first = kerningElem.GetInt("first");
  133. HashMap<unsigned, unsigned>::Iterator i = glyphMapping_.Find(first);
  134. if (i != glyphMapping_.End())
  135. {
  136. int second = kerningElem.GetInt("second");
  137. int amount = kerningElem.GetInt("amount");
  138. FontGlyph& glyph = glyphs_[i->second_];
  139. glyph.kerning_[second] = amount;
  140. }
  141. kerningElem = kerningElem.GetNext("kerning");
  142. }
  143. }
  144. LOGDEBUGF("Bitmap font face %s has %d glyphs", GetFileName(font_->GetName()).CString(), count);
  145. font_->SetMemoryUse(font_->GetMemoryUse() + totalTextureSize);
  146. return true;
  147. }
  148. bool FontFaceBitMap::Load(FontFace* fontFace, bool usedGlyphs)
  149. {
  150. Context* context = font_->GetContext();
  151. int maxTextureSize = font_->GetSubsystem<UI>()->GetMaxFontTextureSize();
  152. // Clone properties
  153. pointSize_ = fontFace->pointSize_;
  154. rowHeight_ = fontFace->rowHeight_;
  155. hasKerning_ = fontFace->hasKerning_;
  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> > images(fontFace->textures_.Size());
  160. for (unsigned i = 0; i < fontFace->textures_.Size(); ++i)
  161. images[i] = SaveFaceTexture(fontFace->textures_[i]);
  162. // Reallocate used glyphs to new texture(s)
  163. unsigned page = 0;
  164. unsigned index = 0;
  165. unsigned startIndex = 0;
  166. HashMap<unsigned, unsigned>::ConstIterator startIter = fontFace->glyphMapping_.Begin();
  167. HashMap<unsigned, unsigned>::ConstIterator i;
  168. while (startIter != fontFace->glyphMapping_.End())
  169. {
  170. AreaAllocator allocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, maxTextureSize, maxTextureSize);
  171. for (i = startIter; i != fontFace->glyphMapping_.End(); ++i)
  172. {
  173. FontGlyph glyph = fontFace->glyphs_[i->second_];
  174. if (!glyph.used_)
  175. continue;
  176. if (glyph.width_ && glyph.height_)
  177. {
  178. int x, y;
  179. // Reserve an empty border between glyphs for filtering
  180. if (allocator.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y))
  181. {
  182. glyph.x_ = x;
  183. glyph.y_ = y;
  184. glyph.page_ = page;
  185. }
  186. else
  187. break;
  188. }
  189. glyphs_.Push(glyph);
  190. glyphMapping_[i->first_] = index++;
  191. }
  192. int texWidth = allocator.GetWidth();
  193. int texHeight = allocator.GetHeight();
  194. // Create the image for rendering the fonts
  195. SharedPtr<Image> image(new Image(context));
  196. image->SetSize(texWidth, texHeight, components);
  197. // First clear the whole image
  198. unsigned char* imageData = image->GetData();
  199. for (int y = 0; y < texHeight; ++y)
  200. {
  201. unsigned char* dest = imageData + components * texWidth * y;
  202. memset(dest, 0, components * texWidth);
  203. }
  204. // Then render the glyphs into new image
  205. for (HashMap<unsigned, unsigned>::ConstIterator j = startIter; j != i; ++j)
  206. {
  207. FontGlyph glyph = fontFace->glyphs_[j->second_];
  208. if (!glyph.used_)
  209. continue;
  210. if (!glyph.width_ || !glyph.height_)
  211. {
  212. ++startIndex;
  213. continue;
  214. }
  215. FontGlyph packedGlyph = glyphs_[startIndex++];
  216. Image* image = images[glyph.page_];
  217. unsigned char* source = image->GetData() + components * (image->GetWidth() * glyph.y_ + glyph.x_);
  218. unsigned char* destination = imageData + components * (texWidth * packedGlyph.y_ + packedGlyph.x_);
  219. for (int i = 0; i < glyph.height_; ++i)
  220. {
  221. memcpy(destination, source, components * glyph.width_);
  222. source += components * image->GetWidth();
  223. destination += components * texWidth;
  224. }
  225. }
  226. // Finally load image into the texture
  227. SharedPtr<Texture2D> texture = LoadFaceTexture(image);
  228. if (!texture)
  229. return false;
  230. textures_.Push(texture);
  231. ++page;
  232. startIter = i;
  233. assert(index == startIndex);
  234. }
  235. return true;
  236. }
  237. bool FontFaceBitMap::Save(Serializer& dest, int pointSize)
  238. {
  239. Context* context = font_->GetContext();
  240. SharedPtr<XMLFile> xml(new XMLFile(context));
  241. XMLElement rootElem = xml->CreateRoot("font");
  242. // Information
  243. XMLElement childElem = rootElem.CreateChild("info");
  244. String fileName = GetFileName(font_->GetName());
  245. childElem.SetAttribute("face", fileName);
  246. childElem.SetAttribute("size", String(pointSize));
  247. // Common
  248. childElem = rootElem.CreateChild("common");
  249. childElem.SetInt("lineHeight", rowHeight_);
  250. unsigned pages = textures_.Size();
  251. childElem.SetInt("pages", pages);
  252. // Construct the path to store the texture
  253. String pathName;
  254. File* file = dynamic_cast<File*>(&dest);
  255. if (file)
  256. // If serialize to file, use the file's path
  257. pathName = GetPath(file->GetName());
  258. else
  259. // Otherwise, use the font resource's path
  260. pathName = "Data/" + GetPath(font_->GetName());
  261. // Pages
  262. childElem = rootElem.CreateChild("pages");
  263. for (unsigned i = 0; i < pages; ++i)
  264. {
  265. XMLElement pageElem = childElem.CreateChild("page");
  266. pageElem.SetInt("id", i);
  267. String texFileName = fileName + "_" + String(i) + ".png";
  268. pageElem.SetAttribute("file", texFileName);
  269. // Save the font face texture to image file
  270. SaveFaceTexture(textures_[i], pathName + texFileName);
  271. }
  272. // Chars and kernings
  273. XMLElement charsElem = rootElem.CreateChild("chars");
  274. unsigned numGlyphs = glyphs_.Size();
  275. charsElem.SetInt("count", numGlyphs);
  276. XMLElement kerningsElem;
  277. bool hasKerning = hasKerning_;
  278. if (hasKerning)
  279. kerningsElem = rootElem.CreateChild("kernings");
  280. for (HashMap<unsigned, unsigned>::ConstIterator i = glyphMapping_.Begin(); i != glyphMapping_.End(); ++i)
  281. {
  282. // Char
  283. XMLElement charElem = charsElem.CreateChild("char");
  284. charElem.SetInt("id", i->first_);
  285. FontGlyph glyph = glyphs_[i->second_];
  286. charElem.SetInt("x", glyph.x_);
  287. charElem.SetInt("y", glyph.y_);
  288. charElem.SetInt("width", glyph.width_);
  289. charElem.SetInt("height", glyph.height_);
  290. charElem.SetInt("xoffset", glyph.offsetX_);
  291. charElem.SetInt("yoffset", glyph.offsetY_);
  292. charElem.SetInt("xadvance", glyph.advanceX_);
  293. charElem.SetInt("page", glyph.page_);
  294. // Kerning
  295. if (hasKerning)
  296. {
  297. for (HashMap<unsigned, unsigned>::ConstIterator j = glyph.kerning_.Begin(); j != glyph.kerning_.End(); ++j)
  298. {
  299. // To conserve space, only write when amount is non zero
  300. if (j->second_ == 0)
  301. continue;
  302. XMLElement kerningElem = kerningsElem.CreateChild("kerning");
  303. kerningElem.SetInt("first", i->first_);
  304. kerningElem.SetInt("second", j->first_);
  305. kerningElem.SetInt("amount", j->second_);
  306. }
  307. }
  308. }
  309. return xml->Save(dest);
  310. }
  311. unsigned FontFaceBitMap::ConvertFormatToNumComponents(unsigned format)
  312. {
  313. if (format == Graphics::GetRGBAFormat())
  314. return 4;
  315. else if (format == Graphics::GetRGBFormat())
  316. return 3;
  317. else if (format == Graphics::GetLuminanceAlphaFormat())
  318. return 2;
  319. else
  320. return 1;
  321. }
  322. SharedPtr<Image> FontFaceBitMap::SaveFaceTexture(Texture2D* texture)
  323. {
  324. Image* image = new Image(font_->GetContext());
  325. image->SetSize(texture->GetWidth(), texture->GetHeight(), ConvertFormatToNumComponents(texture->GetFormat()));
  326. if (!static_cast<Texture2D*>(texture)->GetData(0, image->GetData()))
  327. {
  328. delete image;
  329. LOGERROR("Could not save texture to image resource");
  330. return SharedPtr<Image>();
  331. }
  332. return SharedPtr<Image>(image);
  333. }
  334. bool FontFaceBitMap::SaveFaceTexture(Texture2D* texture, const String& fileName)
  335. {
  336. SharedPtr<Image> image = SaveFaceTexture(texture);
  337. return image ? image->SavePNG(fileName) : false;
  338. }
  339. }