FontFaceFreeType.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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 "FontFaceFreeType.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 <ft2build.h>
  35. #include FT_FREETYPE_H
  36. #include FT_TRUETYPE_TABLES_H
  37. #include "DebugNew.h"
  38. namespace Urho3D
  39. {
  40. /// FreeType library subsystem.
  41. class FreeTypeLibrary : public Object
  42. {
  43. OBJECT(FreeTypeLibrary);
  44. public:
  45. /// Construct.
  46. FreeTypeLibrary(Context* context) :
  47. Object(context)
  48. {
  49. FT_Error error = FT_Init_FreeType(&library_);
  50. if (error)
  51. LOGERROR("Could not initialize FreeType library");
  52. }
  53. /// Destruct.
  54. virtual ~FreeTypeLibrary()
  55. {
  56. FT_Done_FreeType(library_);
  57. }
  58. FT_Library GetLibrary() const { return library_; }
  59. private:
  60. /// FreeType library.
  61. FT_Library library_;
  62. };
  63. FontFaceFreeType::FontFaceFreeType(Font* font) :
  64. FontFace(font),
  65. face_(0),
  66. bitmapSize_(0)
  67. {
  68. }
  69. FontFaceFreeType::~FontFaceFreeType()
  70. {
  71. if (face_)
  72. {
  73. FT_Done_Face((FT_Face)face_);
  74. face_ = 0;
  75. }
  76. for (List<MutableGlyph*>::Iterator i = mutableGlyphs_.Begin(); i != mutableGlyphs_.End(); ++i)
  77. delete *i;
  78. mutableGlyphs_.Clear();
  79. }
  80. bool FontFaceFreeType::Load(const unsigned char* fontData, unsigned fontDataSize, int pointSize)
  81. {
  82. Context* context = font_->GetContext();
  83. // Create & initialize FreeType library if it does not exist yet
  84. FreeTypeLibrary* freeType = font_->GetSubsystem<FreeTypeLibrary>();
  85. if (!freeType)
  86. context->RegisterSubsystem(freeType = new FreeTypeLibrary(context));
  87. // Ensure the FreeType library is kept alive as long as TTF font resources exist
  88. freeType_ = freeType;
  89. UI* ui = font_->GetSubsystem<UI>();
  90. int maxTextureSize = ui->GetMaxFontTextureSize();
  91. FT_Face face;
  92. FT_Error error;
  93. FT_Library library = freeType->GetLibrary();
  94. if (pointSize <= 0)
  95. {
  96. LOGERROR("Zero or negative point size");
  97. return false;
  98. }
  99. if (!fontDataSize)
  100. {
  101. LOGERROR("Could not create font face from zero size data");
  102. return false;
  103. }
  104. error = FT_New_Memory_Face(library, fontData, fontDataSize, 0, &face);
  105. if (error)
  106. {
  107. LOGERROR("Could not create font face");
  108. return false;
  109. }
  110. error = FT_Set_Char_Size(face, 0, pointSize * 64, FONT_DPI, FONT_DPI);
  111. if (error)
  112. {
  113. FT_Done_Face(face);
  114. LOGERROR("Could not set font point size " + String(pointSize));
  115. return false;
  116. }
  117. face_ = face;
  118. FT_GlyphSlot slot = face->glyph;
  119. unsigned numGlyphs = 0;
  120. // Build glyph mapping
  121. FT_UInt glyphIndex;
  122. FT_ULong charCode = FT_Get_First_Char(face, &glyphIndex);
  123. while (glyphIndex != 0)
  124. {
  125. numGlyphs = Max((int)glyphIndex + 1, (int)numGlyphs);
  126. glyphMapping_[charCode] = glyphIndex;
  127. charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
  128. }
  129. LOGDEBUGF("Font face %s (%dpt) has %d glyphs", GetFileName(font_->GetName()).CString(), pointSize, numGlyphs);
  130. // Load each of the glyphs to see the sizes & store other information
  131. int maxWidth = 0;
  132. int maxHeight = 0;
  133. int loadMode = ui->GetForceAutoHint() ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT;
  134. int ascender = face->size->metrics.ascender >> 6;
  135. int descender = face->size->metrics.descender >> 6;
  136. // Check if the font's OS/2 info gives different (larger) values for ascender & descender
  137. TT_OS2* os2Info = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2);
  138. if (os2Info)
  139. {
  140. ascender = Max(ascender, os2Info->usWinAscent * face->size->metrics.y_ppem / face->units_per_EM);
  141. ascender = Max(ascender, os2Info->sTypoAscender * face->size->metrics.y_ppem / face->units_per_EM);
  142. descender = Max(descender, os2Info->usWinDescent * face->size->metrics.y_ppem / face->units_per_EM);
  143. descender = Max(descender, os2Info->sTypoDescender * face->size->metrics.y_ppem / face->units_per_EM);
  144. }
  145. // Store point size and row height. Use the maximum of ascender + descender, or the face's stored default row height
  146. pointSize_ = pointSize;
  147. rowHeight_ = Max(ascender + descender, face->size->metrics.height >> 6);
  148. glyphs_.Reserve(numGlyphs);
  149. for (unsigned i = 0; i < numGlyphs; ++i)
  150. {
  151. FontGlyph newGlyph;
  152. error = FT_Load_Glyph(face, i, loadMode);
  153. if (!error)
  154. {
  155. // Note: position within texture will be filled later
  156. newGlyph.width_ = (short)Max(slot->metrics.width >> 6, slot->bitmap.width);
  157. newGlyph.height_ = (short)Max(slot->metrics.height >> 6, slot->bitmap.rows);
  158. newGlyph.offsetX_ = (short)(slot->metrics.horiBearingX >> 6);
  159. newGlyph.offsetY_ = (short)(ascender - (slot->metrics.horiBearingY >> 6));
  160. newGlyph.advanceX_ = (short)(slot->metrics.horiAdvance >> 6);
  161. maxWidth = Max(maxWidth, newGlyph.width_);
  162. maxHeight = Max(maxHeight, newGlyph.height_);
  163. }
  164. else
  165. {
  166. newGlyph.width_ = 0;
  167. newGlyph.height_ = 0;
  168. newGlyph.offsetX_ = 0;
  169. newGlyph.offsetY_ = 0;
  170. newGlyph.advanceX_ = 0;
  171. }
  172. glyphs_.Push(newGlyph);
  173. }
  174. // Store kerning if face has kerning information
  175. if (FT_HAS_KERNING(face))
  176. {
  177. hasKerning_ = true;
  178. // Read kerning manually to be more efficient and avoid out of memory crash when use large font file, for example there
  179. // are 29354 glyphs in msyh.ttf
  180. FT_ULong tag = FT_MAKE_TAG('k', 'e', 'r', 'n');
  181. FT_ULong kerningTableSize = 0;
  182. FT_Error error = FT_Load_Sfnt_Table(face, tag, 0, NULL, &kerningTableSize);
  183. if (error)
  184. {
  185. LOGERROR("Could not get kerning table length");
  186. return false;
  187. }
  188. SharedArrayPtr<unsigned char> kerningTable(new unsigned char[kerningTableSize]);
  189. error = FT_Load_Sfnt_Table(face, tag, 0, kerningTable, &kerningTableSize);
  190. if (error)
  191. {
  192. LOGERROR("Could not load kerning table");
  193. return false;
  194. }
  195. // Convert big endian to little endian
  196. for (unsigned i = 0; i < kerningTableSize; i += 2)
  197. Swap(kerningTable[i], kerningTable[i + 1]);
  198. MemoryBuffer deserializer(kerningTable, kerningTableSize);
  199. unsigned short version = deserializer.ReadUShort();
  200. if (version == 0)
  201. {
  202. unsigned numKerningTables = deserializer.ReadUShort();
  203. for (unsigned i = 0; i < numKerningTables; ++i)
  204. {
  205. unsigned short version = deserializer.ReadUShort();
  206. unsigned short length = deserializer.ReadUShort();
  207. unsigned short coverage = deserializer.ReadUShort();
  208. if (version == 0 && coverage == 1)
  209. {
  210. unsigned numKerningPairs = deserializer.ReadUShort();
  211. // Skip searchRange, entrySelector and rangeShift
  212. deserializer.Seek(deserializer.GetPosition() + 3 * sizeof(unsigned short));
  213. for (unsigned j = 0; j < numKerningPairs; ++j)
  214. {
  215. unsigned leftIndex = deserializer.ReadUShort();
  216. unsigned rightIndex = deserializer.ReadUShort();
  217. short amount = (short)(deserializer.ReadShort() >> 6);
  218. if (leftIndex < numGlyphs && rightIndex < numGlyphs)
  219. glyphs_[leftIndex].kerning_[rightIndex] = amount;
  220. else
  221. LOGWARNING("Out of range glyph index in kerning information");
  222. }
  223. }
  224. else
  225. {
  226. // Kerning table contains information we do not support; skip and move to the next (length includes header)
  227. deserializer.Seek(deserializer.GetPosition() + length - 3 * sizeof(unsigned short));
  228. }
  229. }
  230. }
  231. else
  232. LOGWARNING("Can not read kerning information: not version 0");
  233. }
  234. // Now try to pack into the smallest possible texture. If face does not fit into one texture, enable dynamic mode where
  235. // glyphs are only created as necessary
  236. if (RenderAllGlyphs(maxTextureSize, maxTextureSize))
  237. {
  238. FT_Done_Face(face);
  239. face_ = 0;
  240. }
  241. else
  242. {
  243. if (ui->GetUseMutableGlyphs())
  244. SetupMutableGlyphs(maxTextureSize, maxTextureSize, maxWidth, maxHeight);
  245. else
  246. SetupNextTexture(maxTextureSize, maxTextureSize);
  247. }
  248. return true;
  249. }
  250. const FontGlyph* FontFaceFreeType::GetGlyph(unsigned c)
  251. {
  252. HashMap<unsigned, unsigned>::ConstIterator i = glyphMapping_.Find(c);
  253. if (i != glyphMapping_.End())
  254. {
  255. FontGlyph& glyph = glyphs_[i->second_];
  256. // Render glyph if not yet resident in a page texture (FreeType mode only)
  257. if (glyph.page_ == M_MAX_UNSIGNED)
  258. RenderGlyph(i->second_);
  259. // If mutable glyphs in use, move to the front of the list
  260. if (mutableGlyphs_.Size() && glyph.iterator_ != mutableGlyphs_.End())
  261. {
  262. MutableGlyph* mutableGlyph = *glyph.iterator_;
  263. mutableGlyphs_.Erase(glyph.iterator_);
  264. mutableGlyphs_.PushFront(mutableGlyph);
  265. glyph.iterator_ = mutableGlyphs_.Begin();
  266. }
  267. glyph.used_ = true;
  268. return &glyph;
  269. }
  270. else
  271. return 0;
  272. }
  273. bool FontFaceFreeType::RenderAllGlyphs(int maxWidth, int maxHeight)
  274. {
  275. assert(font_ && face_ && textures_.Empty());
  276. allocator_ = AreaAllocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, maxWidth, maxHeight);
  277. for (unsigned i = 0; i < glyphs_.Size(); ++i)
  278. {
  279. if (glyphs_[i].width_ && glyphs_[i].height_)
  280. {
  281. int x, y;
  282. // Reserve an empty border between glyphs for filtering
  283. if (allocator_.Allocate(glyphs_[i].width_ + 1, glyphs_[i].height_ + 1, x, y))
  284. {
  285. glyphs_[i].x_ = x;
  286. glyphs_[i].y_ = y;
  287. glyphs_[i].page_ = 0;
  288. }
  289. else
  290. {
  291. // When allocation fails, reset the page of all glyphs allocated so far
  292. for (unsigned j = 0; j <= i; ++j)
  293. glyphs_[j].page_ = M_MAX_UNSIGNED;
  294. return false;
  295. }
  296. }
  297. else
  298. {
  299. glyphs_[i].x_ = 0;
  300. glyphs_[i].y_ = 0;
  301. glyphs_[i].page_ = 0;
  302. }
  303. }
  304. // Create image for rendering all the glyphs, clear to black
  305. SharedPtr<Image> image(new Image(font_->GetContext()));
  306. image->SetSize(allocator_.GetWidth(), allocator_.GetHeight(), 1);
  307. unsigned char* imageData = image->GetData();
  308. memset(imageData, 0, image->GetWidth() * image->GetHeight());
  309. int loadMode = font_->GetSubsystem<UI>()->GetForceAutoHint() ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT;
  310. // Render glyphs
  311. for (unsigned i = 0; i < glyphs_.Size(); ++i)
  312. RenderGlyphBitmap(i, imageData + glyphs_[i].y_ * image->GetWidth() + glyphs_[i].x_, image->GetWidth(), loadMode);
  313. // Load image into a texture, increment memory usage of the parent font
  314. SharedPtr<Texture2D> texture = LoadFaceTexture(image);
  315. if (!texture)
  316. {
  317. for (unsigned i = 0; i < glyphs_.Size(); ++i)
  318. glyphs_[i].page_ = M_MAX_UNSIGNED;
  319. return false;
  320. }
  321. textures_.Push(texture);
  322. font_->SetMemoryUse(font_->GetMemoryUse() + image->GetWidth() * image->GetHeight());
  323. LOGDEBUGF("Font face %s (%dpt) uses a static page texture of size %dx%d", GetFileName(font_->GetName()).CString(), pointSize_, texture->GetWidth(), texture->GetHeight());
  324. return true;
  325. }
  326. void FontFaceFreeType::RenderGlyph(unsigned index)
  327. {
  328. assert(font_ && face_);
  329. FontGlyph& glyph = glyphs_[index];
  330. // If glyph is empty, just set the current page
  331. if (!glyph.width_ || !glyph.height_)
  332. {
  333. glyph.x_ = 0;
  334. glyph.y_ = 0;
  335. glyph.page_ = textures_.Size() - 1;
  336. return;
  337. }
  338. int loadMode = font_->GetSubsystem<UI>()->GetForceAutoHint() ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT;
  339. if (!mutableGlyphs_.Size())
  340. {
  341. // Not using mutable glyphs: try to allocate from current page, reserve next page if fails
  342. int x, y;
  343. if (!allocator_.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y))
  344. {
  345. SetupNextTexture(textures_[0]->GetWidth(), textures_[0]->GetHeight());
  346. // This always succeeds, as it is the first allocation of an empty page
  347. allocator_.Allocate(glyph.width_ + 1, glyph.height_ + 1, x, y);
  348. }
  349. glyph.x_ = x;
  350. glyph.y_ = y;
  351. glyph.page_ = textures_.Size() - 1;
  352. if (!bitmap_ || (int)bitmapSize_ < glyph.width_ * glyph.height_)
  353. {
  354. bitmapSize_ = glyph.width_ * glyph.height_;
  355. bitmap_ = new unsigned char[bitmapSize_];
  356. }
  357. RenderGlyphBitmap(index, bitmap_.Get(), glyph.width_, loadMode);
  358. textures_.Back()->SetData(0, glyph.x_, glyph.y_, glyph.width_, glyph.height_, bitmap_.Get());
  359. }
  360. else
  361. {
  362. // Using mutable glyphs: overwrite the least recently used glyph
  363. List<MutableGlyph*>::Iterator it = --mutableGlyphs_.End();
  364. MutableGlyph* mutableGlyph = *it;
  365. if (mutableGlyph->glyphIndex_ != M_MAX_UNSIGNED)
  366. glyphs_[mutableGlyph->glyphIndex_].page_ = M_MAX_UNSIGNED;
  367. glyph.x_ = mutableGlyph->x_;
  368. glyph.y_ = mutableGlyph->y_;
  369. glyph.page_ = 0;
  370. glyph.iterator_ = it;
  371. mutableGlyph->glyphIndex_ = index;
  372. if (!bitmap_)
  373. {
  374. bitmapSize_ = cellWidth_ * cellHeight_;
  375. bitmap_ = new unsigned char[bitmapSize_];
  376. }
  377. // Clear the cell bitmap before rendering to ensure padding
  378. memset(bitmap_.Get(), 0, cellWidth_ * cellHeight_);
  379. RenderGlyphBitmap(index, bitmap_.Get(), cellWidth_, loadMode);
  380. textures_[0]->SetData(0, glyph.x_, glyph.y_, cellWidth_, cellHeight_, bitmap_.Get());
  381. }
  382. }
  383. void FontFaceFreeType::RenderGlyphBitmap(unsigned index, unsigned char* dest, unsigned pitch, int loadMode)
  384. {
  385. const FontGlyph& glyph = glyphs_[index];
  386. if (!glyph.width_ || !glyph.height_)
  387. return;
  388. FT_Face face = (FT_Face)face_;
  389. FT_GlyphSlot slot = face->glyph;
  390. FT_Load_Glyph(face, index, loadMode);
  391. FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
  392. if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO)
  393. {
  394. for (int y = 0; y < slot->bitmap.rows; ++y)
  395. {
  396. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  397. unsigned char* rowDest = dest + y * pitch;
  398. for (int x = 0; x < slot->bitmap.width; ++x)
  399. rowDest[x] = (src[x >> 3] & (0x80 >> (x & 7))) ? 255 : 0;
  400. }
  401. }
  402. else
  403. {
  404. for (int y = 0; y < slot->bitmap.rows; ++y)
  405. {
  406. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  407. unsigned char* rowDest = dest + y * pitch;
  408. for (int x = 0; x < slot->bitmap.width; ++x)
  409. rowDest[x] = src[x];
  410. }
  411. }
  412. }
  413. void FontFaceFreeType::SetupNextTexture(int width, int height)
  414. {
  415. // If several dynamic textures are needed, use the maximum size to pack as many as possible to one texture
  416. allocator_ = AreaAllocator(width, height);
  417. SharedPtr<Texture2D> texture = CreateFaceTexture();
  418. texture->SetSize(width, height, Graphics::GetAlphaFormat());
  419. SharedArrayPtr<unsigned char> emptyBitmap(new unsigned char[width * height]);
  420. memset(emptyBitmap.Get(), 0, width * height);
  421. texture->SetData(0, 0, 0, width, height, emptyBitmap.Get());
  422. textures_.Push(texture);
  423. font_->SetMemoryUse(font_->GetMemoryUse() + width * height);
  424. LOGDEBUGF("Font face %s (%dpt) is using %d dynamic page textures of size %dx%d", GetFileName(font_->GetName()).CString(), pointSize_, textures_.Size(), width, height);
  425. }
  426. void FontFaceFreeType::SetupMutableGlyphs(int textureWidth, int textureHeight, int maxWidth, int maxHeight)
  427. {
  428. assert(mutableGlyphs_.Empty());
  429. SetupNextTexture(textureWidth, textureHeight);
  430. cellWidth_ = maxWidth + 1;
  431. cellHeight_ = maxHeight + 1;
  432. // Allocate as many mutable glyphs as possible
  433. int x, y;
  434. while (allocator_.Allocate(cellWidth_, cellHeight_, x, y))
  435. {
  436. MutableGlyph* glyph = new MutableGlyph();
  437. glyph->x_ = x;
  438. glyph->y_ = y;
  439. mutableGlyphs_.Push(glyph);
  440. }
  441. LOGDEBUGF("Font face %s (%dpt) is using %d mutable glyphs", GetFileName(font_->GetName()).CString(), pointSize_, mutableGlyphs_.Size());
  442. }
  443. }