Font.cpp 29 KB

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