FontFaceFreeType.cpp 15 KB

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