Font.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. //
  2. // Copyright (c) 2008-2013 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 "AreaAllocator.h"
  24. #include "Context.h"
  25. #include "Deserializer.h"
  26. #include "FileSystem.h"
  27. #include "Font.h"
  28. #include "Graphics.h"
  29. #include "Log.h"
  30. #include "MemoryBuffer.h"
  31. #include "Profiler.h"
  32. #include "ResourceCache.h"
  33. #include "Texture2D.h"
  34. #include "XMLFile.h"
  35. #include <ft2build.h>
  36. #include FT_FREETYPE_H
  37. #include "DebugNew.h"
  38. namespace Urho3D
  39. {
  40. static const int MIN_POINT_SIZE = 1;
  41. static const int MAX_POINT_SIZE = 96;
  42. /// FreeType library subsystem.
  43. class FreeTypeLibrary : public Object
  44. {
  45. OBJECT(FreeTypeLibrary);
  46. public:
  47. /// Construct.
  48. FreeTypeLibrary(Context* context) :
  49. Object(context)
  50. {
  51. FT_Error error = FT_Init_FreeType(&library_);
  52. if (error)
  53. LOGERROR("Could not initialize FreeType library");
  54. }
  55. /// Destruct.
  56. virtual ~FreeTypeLibrary()
  57. {
  58. FT_Done_FreeType(library_);
  59. }
  60. FT_Library GetLibrary() const { return library_; }
  61. private:
  62. /// FreeType library.
  63. FT_Library library_;
  64. };
  65. FontGlyph::FontGlyph() :
  66. used_(false)
  67. {
  68. }
  69. FontFace::FontFace() :
  70. hasKerning_(false)
  71. {
  72. }
  73. FontFace::~FontFace()
  74. {
  75. }
  76. const FontGlyph* FontFace::GetGlyph(unsigned c) const
  77. {
  78. HashMap<unsigned, unsigned>::ConstIterator i = glyphMapping_.Find(c);
  79. if (i != glyphMapping_.End())
  80. {
  81. const FontGlyph& glyph = glyphs_[i->second_];
  82. glyph.used_ = true;
  83. return &glyph;
  84. }
  85. else
  86. return NULL;
  87. }
  88. short FontFace::GetKerning(unsigned c, unsigned d) const
  89. {
  90. if (!hasKerning_)
  91. return 0;
  92. if (c == '\n' || d == '\n')
  93. return 0;
  94. unsigned leftIndex = 0;
  95. unsigned rightIndex = 0;
  96. HashMap<unsigned, unsigned>::ConstIterator leftIt = glyphMapping_.Find(c);
  97. if (leftIt != glyphMapping_.End())
  98. leftIndex = leftIt->second_;
  99. else
  100. return 0;
  101. HashMap<unsigned, unsigned>::ConstIterator rightIt = glyphMapping_.Find(d);
  102. if (rightIt != glyphMapping_.End())
  103. rightIndex = rightIt->second_;
  104. else
  105. return 0;
  106. HashMap<unsigned, unsigned>::ConstIterator kerningIt = glyphs_[leftIndex].kerning_.Find(rightIndex);
  107. if (kerningIt != glyphs_[leftIndex].kerning_.End())
  108. return kerningIt->second_;
  109. else
  110. return 0;
  111. }
  112. bool FontFace::IsDataLost() const
  113. {
  114. for (unsigned i = 0; i < textures_.Size(); ++i)
  115. {
  116. if (textures_[i]->IsDataLost())
  117. return true;
  118. }
  119. return false;
  120. }
  121. Font::Font(Context* context) :
  122. Resource(context),
  123. fontDataSize_(0),
  124. fontType_(FONT_NONE)
  125. {
  126. }
  127. Font::~Font()
  128. {
  129. }
  130. void Font::RegisterObject(Context* context)
  131. {
  132. context->RegisterFactory<Font>();
  133. }
  134. bool Font::Load(Deserializer& source)
  135. {
  136. PROFILE(LoadFont);
  137. // In headless mode, do not actually load, just return success
  138. Graphics* graphics = GetSubsystem<Graphics>();
  139. if (!graphics)
  140. return true;
  141. faces_.Clear();
  142. fontDataSize_ = source.GetSize();
  143. if (fontDataSize_)
  144. {
  145. fontData_ = new unsigned char[fontDataSize_];
  146. if (source.Read(&fontData_[0], fontDataSize_) != fontDataSize_)
  147. return false;
  148. }
  149. else
  150. {
  151. fontData_.Reset();
  152. return false;
  153. }
  154. String ext = GetExtension(GetName());
  155. if (ext == ".ttf")
  156. fontType_ = FONT_TTF;
  157. else if (ext == ".xml" || ext == ".fnt")
  158. fontType_ = FONT_BITMAP;
  159. SetMemoryUse(fontDataSize_);
  160. return true;
  161. }
  162. bool Font::SaveXML(Serializer& dest, int pointSize, bool usedGlyphs)
  163. {
  164. const FontFace* fontFace = GetFace(pointSize);
  165. if (!fontFace)
  166. return false;
  167. PROFILE(FontSaveXML);
  168. SharedPtr<FontFace> packedFontFace;
  169. if (usedGlyphs)
  170. {
  171. // Save used glyphs only, try to pack them first
  172. packedFontFace = Pack(fontFace);
  173. if (packedFontFace)
  174. fontFace = packedFontFace;
  175. else
  176. return false;
  177. }
  178. SharedPtr<XMLFile> xml(new XMLFile(context_));
  179. XMLElement rootElem = xml->CreateRoot("font");
  180. // Information
  181. XMLElement childElem = rootElem.CreateChild("info");
  182. String fileName = GetFileName(GetName());
  183. childElem.SetAttribute("face", fileName);
  184. childElem.SetAttribute("size", String(pointSize));
  185. // Common
  186. childElem = rootElem.CreateChild("common");
  187. childElem.SetInt("lineHeight", fontFace->rowHeight_);
  188. unsigned pages = fontFace->textures_.Size();
  189. childElem.SetInt("pages", pages);
  190. // Construct the path to store the texture
  191. String pathName;
  192. File* file = dynamic_cast<File*>(&dest);
  193. if (file)
  194. // If serialize to file, use the file's path
  195. pathName = GetPath(file->GetName());
  196. else
  197. // Otherwise, use the font resource's path
  198. pathName = "Data/" + GetPath(GetName());
  199. // Pages
  200. childElem = rootElem.CreateChild("pages");
  201. for (unsigned i = 0; i < pages; ++i)
  202. {
  203. XMLElement pageElem = childElem.CreateChild("page");
  204. pageElem.SetInt("id", i);
  205. String texFileName = fileName + "_" + String(i) + ".png";
  206. pageElem.SetAttribute("file", texFileName);
  207. // Save the font face texture to image file
  208. SaveFaceTexture(fontFace->textures_[i], pathName + texFileName);
  209. }
  210. // Chars and kernings
  211. XMLElement charsElem = rootElem.CreateChild("chars");
  212. unsigned numGlyphs = fontFace->glyphs_.Size();
  213. charsElem.SetInt("count", numGlyphs);
  214. XMLElement kerningsElem;
  215. bool hasKerning = fontFace->hasKerning_;
  216. if (hasKerning)
  217. kerningsElem = rootElem.CreateChild("kernings");
  218. for (HashMap<unsigned, unsigned>::ConstIterator i = fontFace->glyphMapping_.Begin(); i != fontFace->glyphMapping_.End(); ++i)
  219. {
  220. // Char
  221. XMLElement charElem = charsElem.CreateChild("char");
  222. charElem.SetInt("id", i->first_);
  223. FontGlyph glyph = fontFace->glyphs_[i->second_];
  224. charElem.SetInt("x", glyph.x_);
  225. charElem.SetInt("y", glyph.y_);
  226. charElem.SetInt("width", glyph.width_);
  227. charElem.SetInt("height", glyph.height_);
  228. charElem.SetInt("xoffset", glyph.offsetX_);
  229. charElem.SetInt("yoffset", glyph.offsetY_);
  230. charElem.SetInt("xadvance", glyph.advanceX_);
  231. charElem.SetInt("page", glyph.page_);
  232. // Kerning
  233. if (hasKerning)
  234. {
  235. for (HashMap<unsigned, unsigned>::ConstIterator j = glyph.kerning_.Begin(); j != glyph.kerning_.End(); ++j)
  236. {
  237. // To conserve space, only write when amount is non zero
  238. if (j->second_ == 0)
  239. continue;
  240. XMLElement kerningElem = kerningsElem.CreateChild("kerning");
  241. kerningElem.SetInt("first", i->first_);
  242. kerningElem.SetInt("second", j->first_);
  243. kerningElem.SetInt("amount", j->second_);
  244. }
  245. }
  246. }
  247. return xml->Save(dest);
  248. }
  249. const FontFace* Font::GetFace(int pointSize)
  250. {
  251. // In headless mode, always return null
  252. Graphics* graphics = GetSubsystem<Graphics>();
  253. if (!graphics)
  254. return 0;
  255. // For bitmap font type, always return the same font face provided by the font's bitmap file regardless of the actual requested point size
  256. if (fontType_ == FONT_BITMAP)
  257. pointSize = 0;
  258. else
  259. pointSize = Clamp(pointSize, MIN_POINT_SIZE, MAX_POINT_SIZE);
  260. HashMap<int, SharedPtr<FontFace> >::Iterator i = faces_.Find(pointSize);
  261. if (i != faces_.End())
  262. {
  263. if (!i->second_->IsDataLost())
  264. return i->second_;
  265. else
  266. {
  267. // Erase and reload face if texture data lost (OpenGL mode only)
  268. faces_.Erase(i);
  269. }
  270. }
  271. PROFILE(GetFontFace);
  272. switch (fontType_)
  273. {
  274. case FONT_TTF:
  275. return GetFaceTTF(pointSize);
  276. case FONT_BITMAP:
  277. return GetFaceBitmap(pointSize);
  278. default:
  279. return 0;
  280. }
  281. }
  282. const FontFace* Font::GetFaceTTF(int pointSize)
  283. {
  284. // Create & initialize FreeType library if it does not exist yet
  285. FreeTypeLibrary* freeType = GetSubsystem<FreeTypeLibrary>();
  286. if (!freeType)
  287. context_->RegisterSubsystem(freeType = new FreeTypeLibrary(context_));
  288. FT_Face face;
  289. FT_Error error;
  290. FT_Library library = freeType->GetLibrary();
  291. if (pointSize <= 0)
  292. {
  293. LOGERROR("Zero or negative point size");
  294. return 0;
  295. }
  296. if (!fontDataSize_)
  297. {
  298. LOGERROR("Font not loaded");
  299. return 0;
  300. }
  301. error = FT_New_Memory_Face(library, &fontData_[0], fontDataSize_, 0, &face);
  302. if (error)
  303. {
  304. LOGERROR("Could not create font face");
  305. return 0;
  306. }
  307. error = FT_Set_Char_Size(face, 0, pointSize * 64, FONT_DPI, FONT_DPI);
  308. if (error)
  309. {
  310. FT_Done_Face(face);
  311. LOGERROR("Could not set font point size " + String(pointSize));
  312. return 0;
  313. }
  314. SharedPtr<FontFace> newFace(new FontFace());
  315. FT_GlyphSlot slot = face->glyph;
  316. unsigned numGlyphs = 0;
  317. // Build glyph mapping
  318. FT_UInt glyphIndex;
  319. FT_ULong charCode = FT_Get_First_Char(face, &glyphIndex);
  320. while (glyphIndex != 0)
  321. {
  322. numGlyphs = Max((int)glyphIndex + 1, (int)numGlyphs);
  323. newFace->glyphMapping_[charCode] = glyphIndex;
  324. charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
  325. }
  326. LOGDEBUG("Font face has " + String(numGlyphs) + " glyphs");
  327. // Load each of the glyphs to see the sizes & store other information
  328. int maxHeight = 0;
  329. FT_Pos ascender = face->size->metrics.ascender;
  330. newFace->glyphs_.Reserve(numGlyphs);
  331. for (unsigned i = 0; i < numGlyphs; ++i)
  332. {
  333. FontGlyph newGlyph;
  334. error = FT_Load_Glyph(face, i, FT_LOAD_DEFAULT);
  335. if (!error)
  336. {
  337. // Note: position within texture will be filled later
  338. newGlyph.width_ = (short)((slot->metrics.width) >> 6);
  339. newGlyph.height_ = (short)((slot->metrics.height) >> 6);
  340. newGlyph.offsetX_ = (short)((slot->metrics.horiBearingX) >> 6);
  341. newGlyph.offsetY_ = (short)((ascender - slot->metrics.horiBearingY) >> 6);
  342. newGlyph.advanceX_ = (short)((slot->metrics.horiAdvance) >> 6);
  343. maxHeight = Max(maxHeight, newGlyph.height_);
  344. }
  345. else
  346. {
  347. newGlyph.width_ = 0;
  348. newGlyph.height_ = 0;
  349. newGlyph.offsetX_ = 0;
  350. newGlyph.offsetY_ = 0;
  351. newGlyph.advanceX_ = 0;
  352. }
  353. newFace->glyphs_.Push(newGlyph);
  354. }
  355. // Store kerning if face has kerning information
  356. if (FT_HAS_KERNING(face))
  357. {
  358. newFace->hasKerning_ = true;
  359. for (unsigned i = 0; i < numGlyphs; ++i)
  360. {
  361. for (unsigned j = 0; j < numGlyphs; ++j)
  362. {
  363. FT_Vector vector;
  364. FT_Get_Kerning(face, i, j, FT_KERNING_DEFAULT, &vector);
  365. newFace->glyphs_[i].kerning_[j] = (short)(vector.x >> 6);
  366. }
  367. }
  368. }
  369. // Store point size and the height of a row. Use the height of the tallest font if taller than the specified row height
  370. newFace->pointSize_ = pointSize;
  371. newFace->rowHeight_ = Max((face->size->metrics.height + 63) >> 6, maxHeight);
  372. // Now try to pack into the smallest possible texture(s)
  373. Vector<SharedPtr<Image> > images;
  374. unsigned totalTextureSize = 0;
  375. unsigned page = 0;
  376. unsigned startIndex = 0;
  377. unsigned index;
  378. unsigned sumMaxOpacity = 0;
  379. unsigned samples = 0;
  380. while (startIndex < numGlyphs)
  381. {
  382. AreaAllocator allocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MAX_SIZE, FONT_TEXTURE_MAX_SIZE);
  383. for (index = startIndex; index < numGlyphs; ++index)
  384. {
  385. if (newFace->glyphs_[index].width_ && newFace->glyphs_[index].height_)
  386. {
  387. int x, y;
  388. // Reserve an empty border between glyphs for filtering
  389. if (allocator.Allocate(newFace->glyphs_[index].width_ + 1, newFace->glyphs_[index].height_ + 1, x, y))
  390. {
  391. newFace->glyphs_[index].x_ = x;
  392. newFace->glyphs_[index].y_ = y;
  393. newFace->glyphs_[index].page_ = page;
  394. }
  395. else
  396. break;
  397. }
  398. else
  399. {
  400. newFace->glyphs_[index].x_ = 0;
  401. newFace->glyphs_[index].y_ = 0;
  402. newFace->glyphs_[index].page_ = 0;
  403. }
  404. }
  405. int texWidth = allocator.GetWidth();
  406. int texHeight = allocator.GetHeight();
  407. // Create the image for rendering the fonts
  408. SharedPtr<Image> image(new Image(context_));
  409. images.Push(image);
  410. image->SetSize(texWidth, texHeight, 1);
  411. // First clear the whole image
  412. unsigned char* imageData = image->GetData();
  413. for (int y = 0; y < texHeight; ++y)
  414. {
  415. unsigned char* dest = imageData + texWidth * y;
  416. memset(dest, 0, texWidth);
  417. }
  418. // Render glyphs into texture, and find out a scaling value in case font uses less than full opacity (thin outlines)
  419. for (unsigned i = startIndex; i < index; ++i)
  420. {
  421. if (!newFace->glyphs_[i].width_ || !newFace->glyphs_[i].height_)
  422. continue;
  423. FT_Load_Glyph(face, i, FT_LOAD_DEFAULT);
  424. FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
  425. unsigned char glyphOpacity = 0;
  426. for (int y = 0; y < newFace->glyphs_[i].height_; ++y)
  427. {
  428. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  429. unsigned char* dest = imageData + texWidth * (y + newFace->glyphs_[i].y_) + newFace->glyphs_[i].x_;
  430. for (int x = 0; x < newFace->glyphs_[i].width_; ++x)
  431. {
  432. dest[x] = src[x];
  433. glyphOpacity = Max(glyphOpacity, src[x]);
  434. }
  435. }
  436. if (glyphOpacity)
  437. {
  438. sumMaxOpacity += glyphOpacity;
  439. ++samples;
  440. }
  441. }
  442. ++page;
  443. startIndex = index;
  444. }
  445. // Clamp the minimum possible value to avoid overbrightening
  446. unsigned char avgMaxOpacity = 255;
  447. if (samples)
  448. avgMaxOpacity = Max(sumMaxOpacity / samples, 128);
  449. if (avgMaxOpacity < 255)
  450. {
  451. // Apply the scaling value if necessary
  452. float scale = 255.0f / avgMaxOpacity;
  453. for (unsigned i = 0; i < numGlyphs; ++i)
  454. {
  455. Image* image = images[newFace->glyphs_[i].page_];
  456. unsigned char* imageData = image->GetData();
  457. for (int y = 0; y < newFace->glyphs_[i].height_; ++y)
  458. {
  459. unsigned char* dest = imageData + image->GetWidth() * (y + newFace->glyphs_[i].y_) + newFace->glyphs_[i].x_;
  460. for (int x = 0; x < newFace->glyphs_[i].width_; ++x)
  461. {
  462. int pixel = dest[x];
  463. dest[x] = Min((int)(pixel * scale), 255);
  464. }
  465. }
  466. }
  467. }
  468. // Create the texture and load the image into it
  469. for (Vector<SharedPtr<Image> >::ConstIterator i = images.Begin(); i != images.End(); ++i)
  470. {
  471. int texWidth = i->Get()->GetWidth();
  472. int texHeight = i->Get()->GetHeight();
  473. SharedPtr<Texture> texture = LoadFaceTexture(*i);
  474. if (!texture)
  475. return 0;
  476. newFace->textures_.Push(texture);
  477. totalTextureSize += texWidth * texHeight;
  478. }
  479. FT_Done_Face(face);
  480. SetMemoryUse(GetMemoryUse() + totalTextureSize);
  481. faces_[pointSize] = newFace;
  482. return newFace;
  483. }
  484. const FontFace* Font::GetFaceBitmap(int pointSize)
  485. {
  486. SharedPtr<XMLFile> xmlReader(new XMLFile(context_));
  487. MemoryBuffer memoryBuffer(fontData_, fontDataSize_);
  488. if (!xmlReader->Load(memoryBuffer))
  489. {
  490. LOGERROR("Could not load XML file");
  491. return 0;
  492. }
  493. XMLElement root = xmlReader->GetRoot("font");
  494. if (root.IsNull())
  495. {
  496. LOGERROR("Could not find Font element");
  497. return 0;
  498. }
  499. XMLElement pagesElem = root.GetChild("pages");
  500. if (pagesElem.IsNull())
  501. {
  502. LOGERROR("Could not find Pages element");
  503. return 0;
  504. }
  505. SharedPtr<FontFace> newFace(new FontFace());
  506. XMLElement infoElem = root.GetChild("info");
  507. if (!infoElem.IsNull())
  508. newFace->pointSize_ = infoElem.GetInt("size");
  509. XMLElement commonElem = root.GetChild("common");
  510. newFace->rowHeight_ = commonElem.GetInt("lineHeight");
  511. unsigned pages = commonElem.GetInt("pages");
  512. newFace->textures_.Reserve(pages);
  513. ResourceCache* resourceCache = GetSubsystem<ResourceCache>();
  514. String fontPath = GetPath(GetName());
  515. unsigned totalTextureSize = 0;
  516. XMLElement pageElem = pagesElem.GetChild("page");
  517. for (unsigned i = 0; i < pages; ++i)
  518. {
  519. if (pageElem.IsNull())
  520. {
  521. LOGERROR("Could not find Page element for page: " + String(i));
  522. return 0;
  523. }
  524. // Assume the font image is in the same directory as the font description file
  525. String textureFile = fontPath + pageElem.GetAttribute("file");
  526. // Load texture manually to allow controlling the alpha channel mode
  527. SharedPtr<File> fontFile = resourceCache->GetFile(textureFile);
  528. SharedPtr<Image> fontImage(new Image(context_));
  529. if (!fontFile || !fontImage->Load(*fontFile))
  530. {
  531. LOGERROR("Failed to load font image file");
  532. return 0;
  533. }
  534. SharedPtr<Texture> texture = LoadFaceTexture(fontImage);
  535. if (!texture)
  536. return 0;
  537. newFace->textures_.Push(texture);
  538. totalTextureSize += fontImage->GetWidth() * fontImage->GetHeight() * fontImage->GetComponents();
  539. pageElem = pageElem.GetNext("page");
  540. }
  541. XMLElement charsElem = root.GetChild("chars");
  542. int count = charsElem.GetInt("count");
  543. newFace->glyphs_.Reserve(count);
  544. unsigned index = 0;
  545. XMLElement charElem = charsElem.GetChild("char");
  546. while (!charElem.IsNull())
  547. {
  548. int id = charElem.GetInt("id");
  549. FontGlyph glyph;
  550. glyph.x_ = charElem.GetInt("x");
  551. glyph.y_ = charElem.GetInt("y");
  552. glyph.width_ = charElem.GetInt("width");
  553. glyph.height_ = charElem.GetInt("height");
  554. glyph.offsetX_ = charElem.GetInt("xoffset");
  555. glyph.offsetY_ = charElem.GetInt("yoffset");
  556. glyph.advanceX_ = charElem.GetInt("xadvance");
  557. glyph.page_ = charElem.GetInt("page");
  558. newFace->glyphs_.Push(glyph);
  559. newFace->glyphMapping_[id] = index++;
  560. charElem = charElem.GetNext("char");
  561. }
  562. XMLElement kerningsElem = root.GetChild("kernings");
  563. if (kerningsElem.IsNull())
  564. newFace->hasKerning_ = false;
  565. else
  566. {
  567. XMLElement kerningElem = kerningsElem.GetChild("kerning");
  568. while (!kerningElem.IsNull())
  569. {
  570. int first = kerningElem.GetInt("first");
  571. HashMap<unsigned, unsigned>::Iterator i = newFace->glyphMapping_.Find(first);
  572. if (i != newFace->glyphMapping_.End())
  573. {
  574. int second = kerningElem.GetInt("second");
  575. int amount = kerningElem.GetInt("amount");
  576. FontGlyph& glyph = newFace->glyphs_[i->second_];
  577. glyph.kerning_[second] = amount;
  578. }
  579. kerningElem = kerningElem.GetNext("kerning");
  580. }
  581. }
  582. SetMemoryUse(GetMemoryUse() + totalTextureSize);
  583. faces_[pointSize] = newFace;
  584. return newFace;
  585. }
  586. unsigned Font::ConvertFormatToNumComponents(unsigned format)
  587. {
  588. if (format == Graphics::GetRGBAFormat())
  589. return 4;
  590. else if (format == Graphics::GetRGBFormat())
  591. return 3;
  592. else if (format == Graphics::GetLuminanceAlphaFormat())
  593. return 2;
  594. else
  595. return 1;
  596. }
  597. SharedPtr<FontFace> Font::Pack(const FontFace* fontFace)
  598. {
  599. SharedPtr<FontFace> packedFontFace(new FontFace());
  600. // Clone properties
  601. packedFontFace->pointSize_ = fontFace->pointSize_;
  602. packedFontFace->rowHeight_ = fontFace->rowHeight_;
  603. packedFontFace->hasKerning_ = fontFace->hasKerning_;
  604. // Assume that format is the same for all textures and that bitmap font type may have more than one component
  605. unsigned components = ConvertFormatToNumComponents(fontFace->textures_[0]->GetFormat());
  606. // Save the existing textures as image resources
  607. Vector<SharedPtr<Image> > images(fontFace->textures_.Size());
  608. for (unsigned i = 0; i < fontFace->textures_.Size(); ++i)
  609. images[i] = SaveFaceTexture(fontFace->textures_[i]);
  610. // Reallocate used glyphs to new texture(s)
  611. unsigned page = 0;
  612. unsigned index = 0;
  613. unsigned startIndex = 0;
  614. HashMap<unsigned, unsigned>::ConstIterator startIter = fontFace->glyphMapping_.Begin();
  615. HashMap<unsigned, unsigned>::ConstIterator i;
  616. while (startIter != fontFace->glyphMapping_.End())
  617. {
  618. AreaAllocator allocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MAX_SIZE, FONT_TEXTURE_MAX_SIZE);
  619. for (i = startIter; i != fontFace->glyphMapping_.End(); ++i)
  620. {
  621. FontGlyph glyph = fontFace->glyphs_[i->second_];
  622. if (!glyph.used_)
  623. continue;
  624. if (glyph.width_ && glyph.height_)
  625. {
  626. int x, y;
  627. // Reserve an empty border between glyphs for filtering
  628. if (allocator.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y))
  629. {
  630. glyph.x_ = x;
  631. glyph.y_ = y;
  632. glyph.page_ = page;
  633. }
  634. else
  635. break;
  636. }
  637. packedFontFace->glyphs_.Push(glyph);
  638. packedFontFace->glyphMapping_[i->first_] = index++;
  639. }
  640. int texWidth = allocator.GetWidth();
  641. int texHeight = allocator.GetHeight();
  642. // Create the image for rendering the fonts
  643. SharedPtr<Image> image(new Image(context_));
  644. image->SetSize(texWidth, texHeight, components);
  645. // First clear the whole image
  646. unsigned char* imageData = image->GetData();
  647. for (int y = 0; y < texHeight; ++y)
  648. {
  649. unsigned char* dest = imageData + components * texWidth * y;
  650. memset(dest, 0, components * texWidth);
  651. }
  652. // Then render the glyphs into new image
  653. for (HashMap<unsigned, unsigned>::ConstIterator j = startIter; j != i; ++j)
  654. {
  655. FontGlyph glyph = fontFace->glyphs_[j->second_];
  656. if (!glyph.used_)
  657. continue;
  658. if (!glyph.width_ || !glyph.height_)
  659. {
  660. ++startIndex;
  661. continue;
  662. }
  663. FontGlyph packedGlyph = packedFontFace->glyphs_[startIndex++];
  664. Image* image = images[glyph.page_];
  665. unsigned char* source = image->GetData() + components * (image->GetWidth() * glyph.y_ + glyph.x_);
  666. unsigned char* destination = imageData + components * (texWidth * packedGlyph.y_ + packedGlyph.x_);
  667. for (int i = 0; i < glyph.height_; ++i)
  668. {
  669. memcpy(destination, source, components * glyph.width_);
  670. source += components * image->GetWidth();
  671. destination += components * texWidth;
  672. }
  673. }
  674. // Finally load image into the texture
  675. SharedPtr<Texture> texture = LoadFaceTexture(image);
  676. if (!texture)
  677. return SharedPtr<FontFace>();
  678. packedFontFace->textures_.Push(texture);
  679. ++page;
  680. startIter = i;
  681. assert(index == startIndex);
  682. }
  683. return packedFontFace;
  684. }
  685. SharedPtr<Texture> Font::LoadFaceTexture(SharedPtr<Image> image)
  686. {
  687. Texture2D* texture = new Texture2D(context_);
  688. texture->SetMipsToSkip(QUALITY_LOW, 0); // No quality reduction
  689. texture->SetNumLevels(1); // No mipmaps
  690. texture->SetAddressMode(COORD_U, ADDRESS_BORDER);
  691. texture->SetAddressMode(COORD_V, ADDRESS_BORDER),
  692. texture->SetBorderColor(Color(0.0f, 0.0f, 0.0f, 0.0f));
  693. if (!texture->Load(image, true))
  694. {
  695. delete texture;
  696. LOGERROR("Could not load texture from image resource");
  697. return SharedPtr<Texture>();
  698. }
  699. return SharedPtr<Texture>(texture);
  700. }
  701. SharedPtr<Image> Font::SaveFaceTexture(Texture* texture)
  702. {
  703. Image* image = new Image(context_);
  704. image->SetSize(texture->GetWidth(), texture->GetHeight(), ConvertFormatToNumComponents(texture->GetFormat()));
  705. if (!static_cast<Texture2D*>(texture)->GetData(0, image->GetData()))
  706. {
  707. delete image;
  708. LOGERROR("Could not save texture to image resource");
  709. return SharedPtr<Image>();
  710. }
  711. return SharedPtr<Image>(image);
  712. }
  713. bool Font::SaveFaceTexture(Texture* texture, const String& fileName)
  714. {
  715. SharedPtr<Image> image = SaveFaceTexture(texture);
  716. return image ? image->SavePNG(fileName) : false;
  717. }
  718. }