FontFaceFreeType.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. //
  2. // Copyright (c) 2008-2016 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 "../Core/Context.h"
  24. #include "../Graphics/Graphics.h"
  25. #include "../Graphics/Texture2D.h"
  26. #include "../IO/FileSystem.h"
  27. #include "../IO/Log.h"
  28. #include "../IO/MemoryBuffer.h"
  29. #include "../UI/Font.h"
  30. #include "../UI/FontFaceFreeType.h"
  31. #include "../UI/UI.h"
  32. #include <ft2build.h>
  33. #include FT_FREETYPE_H
  34. #include FT_TRUETYPE_TABLES_H
  35. #include "../DebugNew.h"
  36. namespace Urho3D
  37. {
  38. inline int RoundToPixels(FT_Pos value)
  39. {
  40. return (int)(value >> 6) + (((value & 0x3f) >= 0x20) ? 1 : 0);
  41. }
  42. /// FreeType library subsystem.
  43. class FreeTypeLibrary : public Object
  44. {
  45. URHO3D_OBJECT(FreeTypeLibrary, Object);
  46. public:
  47. /// Construct.
  48. FreeTypeLibrary(Context* context) :
  49. Object(context)
  50. {
  51. FT_Error error = FT_Init_FreeType(&library_);
  52. if (error)
  53. URHO3D_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. FontFaceFreeType::FontFaceFreeType(Font* font) :
  66. FontFace(font),
  67. face_(0),
  68. loadMode_(FT_LOAD_DEFAULT)
  69. {
  70. }
  71. FontFaceFreeType::~FontFaceFreeType()
  72. {
  73. if (face_)
  74. {
  75. FT_Done_Face((FT_Face)face_);
  76. face_ = 0;
  77. }
  78. }
  79. bool FontFaceFreeType::Load(const unsigned char* fontData, unsigned fontDataSize, int pointSize)
  80. {
  81. Context* context = font_->GetContext();
  82. // Create & initialize FreeType library if it does not exist yet
  83. FreeTypeLibrary* freeType = font_->GetSubsystem<FreeTypeLibrary>();
  84. if (!freeType)
  85. context->RegisterSubsystem(freeType = new FreeTypeLibrary(context));
  86. // Ensure the FreeType library is kept alive as long as TTF font resources exist
  87. freeType_ = freeType;
  88. UI* ui = font_->GetSubsystem<UI>();
  89. int maxTextureSize = ui->GetMaxFontTextureSize();
  90. FT_Face face;
  91. FT_Error error;
  92. FT_Library library = freeType->GetLibrary();
  93. if (pointSize <= 0)
  94. {
  95. URHO3D_LOGERROR("Zero or negative point size");
  96. return false;
  97. }
  98. if (!fontDataSize)
  99. {
  100. URHO3D_LOGERROR("Could not create font face from zero size data");
  101. return false;
  102. }
  103. error = FT_New_Memory_Face(library, fontData, fontDataSize, 0, &face);
  104. if (error)
  105. {
  106. URHO3D_LOGERROR("Could not create font face");
  107. return false;
  108. }
  109. error = FT_Set_Char_Size(face, 0, pointSize * 64, FONT_DPI, FONT_DPI);
  110. if (error)
  111. {
  112. FT_Done_Face(face);
  113. URHO3D_LOGERROR("Could not set font point size " + String(pointSize));
  114. return false;
  115. }
  116. face_ = face;
  117. unsigned numGlyphs = (unsigned)face->num_glyphs;
  118. URHO3D_LOGDEBUGF("Font face %s (%dpt) has %d glyphs", GetFileName(font_->GetName()).CString(), pointSize, numGlyphs);
  119. PODVector<unsigned> charCodes(numGlyphs);
  120. for (unsigned i = 0; i < numGlyphs; ++i)
  121. charCodes[i] = 0;
  122. FT_UInt glyphIndex;
  123. FT_ULong charCode = FT_Get_First_Char(face, &glyphIndex);
  124. while (glyphIndex != 0)
  125. {
  126. if (glyphIndex < numGlyphs)
  127. charCodes[glyphIndex] = (unsigned)charCode;
  128. charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
  129. }
  130. // Load each of the glyphs to see the sizes & store other information
  131. loadMode_ = (int)(ui->GetForceAutoHint() ? FT_LOAD_FORCE_AUTOHINT : FT_LOAD_DEFAULT);
  132. ascender_ = RoundToPixels(face->size->metrics.ascender);
  133. int descender = RoundToPixels(face->size->metrics.descender);
  134. // Check if the font's OS/2 info gives different (larger) values for ascender & descender
  135. TT_OS2* os2Info = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2);
  136. if (os2Info)
  137. {
  138. ascender_ = Max(ascender_, os2Info->usWinAscent * face->size->metrics.y_ppem / face->units_per_EM);
  139. ascender_ = Max(ascender_, os2Info->sTypoAscender * face->size->metrics.y_ppem / face->units_per_EM);
  140. descender = Max(descender, os2Info->usWinDescent * face->size->metrics.y_ppem / face->units_per_EM);
  141. descender = Max(descender, os2Info->sTypoDescender * face->size->metrics.y_ppem / face->units_per_EM);
  142. }
  143. // Store point size and row height. Use the maximum of ascender + descender, or the face's stored default row height
  144. pointSize_ = pointSize;
  145. rowHeight_ = (int)Max(ascender_ + descender, RoundToPixels(face->size->metrics.height));
  146. int textureWidth = maxTextureSize;
  147. int textureHeight = maxTextureSize;
  148. bool loadAllGlyphs = CanLoadAllGlyphs(charCodes, textureWidth, textureHeight);
  149. SharedPtr<Image> image(new Image(font_->GetContext()));
  150. image->SetSize(textureWidth, textureHeight, 1);
  151. unsigned char* imageData = image->GetData();
  152. memset(imageData, 0, (size_t)(image->GetWidth() * image->GetHeight()));
  153. allocator_.Reset(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, textureWidth, textureHeight);
  154. // Attempt to load space glyph first regardless if it's listed or not
  155. // In some fonts (Consola) it is missing
  156. LoadCharGlyph(32, image);
  157. for (unsigned i = 0; i < numGlyphs; ++i)
  158. {
  159. unsigned charCode = charCodes[i];
  160. if (charCode == 0)
  161. continue;
  162. if (!loadAllGlyphs && (charCode > 0xff))
  163. break;
  164. if (!LoadCharGlyph(charCode, image))
  165. return false;
  166. }
  167. SharedPtr<Texture2D> texture = LoadFaceTexture(image);
  168. if (!texture)
  169. return false;
  170. textures_.Push(texture);
  171. font_->SetMemoryUse(font_->GetMemoryUse() + textureWidth * textureHeight);
  172. // Store kerning if face has kerning information
  173. if (FT_HAS_KERNING(face))
  174. {
  175. // Read kerning manually to be more efficient and avoid out of memory crash when use large font file, for example there
  176. // are 29354 glyphs in msyh.ttf
  177. FT_ULong tagKern = FT_MAKE_TAG('k', 'e', 'r', 'n');
  178. FT_ULong kerningTableSize = 0;
  179. FT_Error error = FT_Load_Sfnt_Table(face, tagKern, 0, NULL, &kerningTableSize);
  180. if (error)
  181. {
  182. URHO3D_LOGERROR("Could not get kerning table length");
  183. return false;
  184. }
  185. SharedArrayPtr<unsigned char> kerningTable(new unsigned char[kerningTableSize]);
  186. error = FT_Load_Sfnt_Table(face, tagKern, 0, kerningTable, &kerningTableSize);
  187. if (error)
  188. {
  189. URHO3D_LOGERROR("Could not load kerning table");
  190. return false;
  191. }
  192. // Convert big endian to little endian
  193. for (unsigned i = 0; i < kerningTableSize; i += 2)
  194. Swap(kerningTable[i], kerningTable[i + 1]);
  195. MemoryBuffer deserializer(kerningTable, (unsigned)kerningTableSize);
  196. unsigned short version = deserializer.ReadUShort();
  197. if (version == 0)
  198. {
  199. unsigned numKerningTables = deserializer.ReadUShort();
  200. for (unsigned i = 0; i < numKerningTables; ++i)
  201. {
  202. unsigned short version = deserializer.ReadUShort();
  203. unsigned short length = deserializer.ReadUShort();
  204. unsigned short coverage = deserializer.ReadUShort();
  205. if (version == 0 && coverage == 1)
  206. {
  207. unsigned numKerningPairs = deserializer.ReadUShort();
  208. // Skip searchRange, entrySelector and rangeShift
  209. deserializer.Seek((unsigned)(deserializer.GetPosition() + 3 * sizeof(unsigned short)));
  210. for (unsigned j = 0; j < numKerningPairs; ++j)
  211. {
  212. unsigned leftIndex = deserializer.ReadUShort();
  213. unsigned rightIndex = deserializer.ReadUShort();
  214. short amount = RoundToPixels(deserializer.ReadShort());
  215. unsigned leftCharCode = leftIndex < numGlyphs ? charCodes[leftIndex] : 0;
  216. unsigned rightCharCode = rightIndex < numGlyphs ? charCodes[rightIndex] : 0;
  217. if (leftCharCode != 0 && rightCharCode != 0)
  218. {
  219. unsigned value = (leftCharCode << 16) + rightCharCode;
  220. kerningMapping_[value] = amount;
  221. }
  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((unsigned)(deserializer.GetPosition() + length - 3 * sizeof(unsigned short)));
  228. }
  229. }
  230. }
  231. else
  232. URHO3D_LOGWARNING("Can not read kerning information: not version 0");
  233. }
  234. if (loadAllGlyphs)
  235. {
  236. FT_Done_Face(face);
  237. face_ = 0;
  238. hasMutableGlyph_ = false;
  239. }
  240. else
  241. hasMutableGlyph_ = true;
  242. return true;
  243. }
  244. const FontGlyph* FontFaceFreeType::GetGlyph(unsigned c)
  245. {
  246. HashMap<unsigned, FontGlyph>::Iterator i = glyphMapping_.Find(c);
  247. if (i != glyphMapping_.End())
  248. {
  249. FontGlyph& glyph = i->second_;
  250. glyph.used_ = true;
  251. return &glyph;
  252. }
  253. if (LoadCharGlyph(c))
  254. {
  255. HashMap<unsigned, FontGlyph>::Iterator i = glyphMapping_.Find(c);
  256. if (i != glyphMapping_.End())
  257. {
  258. FontGlyph& glyph = i->second_;
  259. glyph.used_ = true;
  260. return &glyph;
  261. }
  262. }
  263. return 0;
  264. }
  265. bool FontFaceFreeType::CanLoadAllGlyphs(const PODVector<unsigned>& charCodes, int& textureWidth, int& textureHeight) const
  266. {
  267. FT_Face face = (FT_Face)face_;
  268. FT_GlyphSlot slot = face->glyph;
  269. AreaAllocator allocator(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, textureWidth, textureHeight);
  270. unsigned numGlyphs = charCodes.Size();
  271. for (unsigned i = 0; i < numGlyphs; ++i)
  272. {
  273. unsigned charCode = charCodes[i];
  274. if (charCode == 0)
  275. continue;
  276. FT_Error error = FT_Load_Char(face, charCode, loadMode_);
  277. if (!error)
  278. {
  279. int width = Max(RoundToPixels(slot->metrics.width), (int)slot->bitmap.width);
  280. int height = Max(RoundToPixels(slot->metrics.height), (int)slot->bitmap.rows);
  281. int x, y;
  282. if (!allocator.Allocate(width + 1, height + 1, x, y))
  283. return false;
  284. }
  285. }
  286. textureWidth = allocator.GetWidth();
  287. textureHeight = allocator.GetHeight();
  288. return true;
  289. }
  290. bool FontFaceFreeType::SetupNextTexture(int textureWidth, int textureHeight)
  291. {
  292. SharedPtr<Image> image(new Image(font_->GetContext()));
  293. image->SetSize(textureWidth, textureHeight, 1);
  294. unsigned char* imageData = image->GetData();
  295. memset(imageData, 0, (size_t)(image->GetWidth() * image->GetHeight()));
  296. SharedPtr<Texture2D> texture = LoadFaceTexture(image);
  297. if (!texture)
  298. return false;
  299. textures_.Push(texture);
  300. allocator_.Reset(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, textureWidth, textureHeight);
  301. font_->SetMemoryUse(font_->GetMemoryUse() + textureWidth * textureHeight);
  302. return true;
  303. }
  304. bool FontFaceFreeType::LoadCharGlyph(unsigned charCode, Image* image)
  305. {
  306. if (!face_)
  307. return false;
  308. FT_Face face = (FT_Face)face_;
  309. FT_GlyphSlot slot = face->glyph;
  310. FontGlyph fontGlyph;
  311. FT_Error error = FT_Load_Char(face, charCode, loadMode_);
  312. if (!error)
  313. {
  314. // Note: position within texture will be filled later
  315. fontGlyph.width_ = (short)Max(RoundToPixels(slot->metrics.width), (int)slot->bitmap.width);
  316. fontGlyph.height_ = (short)Max(RoundToPixels(slot->metrics.height), (int)slot->bitmap.rows);
  317. fontGlyph.offsetX_ = (short)(RoundToPixels(slot->metrics.horiBearingX));
  318. fontGlyph.offsetY_ = (short)(ascender_ - RoundToPixels(slot->metrics.horiBearingY));
  319. fontGlyph.advanceX_ = (short)(slot->metrics.horiAdvance >> 6);
  320. if (fontGlyph.width_ > 0 && fontGlyph.height_ > 0)
  321. {
  322. int x, y;
  323. if (!allocator_.Allocate(fontGlyph.width_ + 1, fontGlyph.height_ + 1, x, y))
  324. {
  325. if (!SetupNextTexture(allocator_.GetWidth(), allocator_.GetHeight()))
  326. return false;
  327. if (!allocator_.Allocate(fontGlyph.width_ + 1, fontGlyph.height_ + 1, x, y))
  328. return false;
  329. }
  330. fontGlyph.x_ = (short)x;
  331. fontGlyph.y_ = (short)y;
  332. unsigned char* dest = 0;
  333. unsigned pitch = 0;
  334. if (image)
  335. {
  336. fontGlyph.page_ = 0;
  337. dest = image->GetData() + fontGlyph.y_ * image->GetWidth() + fontGlyph.x_;
  338. pitch = (unsigned)image->GetWidth();
  339. }
  340. else
  341. {
  342. fontGlyph.page_ = textures_.Size() - 1;
  343. dest = new unsigned char[fontGlyph.width_ * fontGlyph.height_];
  344. pitch = (unsigned)fontGlyph.width_;
  345. }
  346. FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
  347. if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO)
  348. {
  349. for (unsigned int y = 0; y < slot->bitmap.rows; ++y)
  350. {
  351. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  352. unsigned char* rowDest = dest + y * pitch;
  353. for (unsigned int x = 0; x < slot->bitmap.width; ++x)
  354. rowDest[x] = (unsigned char)((src[x >> 3] & (0x80 >> (x & 7))) ? 255 : 0);
  355. }
  356. }
  357. else
  358. {
  359. for (unsigned int y = 0; y < slot->bitmap.rows; ++y)
  360. {
  361. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  362. unsigned char* rowDest = dest + y * pitch;
  363. for (unsigned int x = 0; x < slot->bitmap.width; ++x)
  364. rowDest[x] = src[x];
  365. }
  366. }
  367. if (!image)
  368. {
  369. textures_.Back()->SetData(0, fontGlyph.x_, fontGlyph.y_, fontGlyph.width_, fontGlyph.height_, dest);
  370. delete[] dest;
  371. }
  372. }
  373. else
  374. {
  375. fontGlyph.x_ = 0;
  376. fontGlyph.y_ = 0;
  377. fontGlyph.page_ = 0;
  378. }
  379. }
  380. else
  381. {
  382. fontGlyph.width_ = 0;
  383. fontGlyph.height_ = 0;
  384. fontGlyph.offsetX_ = 0;
  385. fontGlyph.offsetY_ = 0;
  386. fontGlyph.advanceX_ = 0;
  387. fontGlyph.page_ = 0;
  388. }
  389. glyphMapping_[charCode] = fontGlyph;
  390. return true;
  391. }
  392. }