FontFaceFreeType.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. //
  2. // Copyright (c) 2008-2017 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 <assert.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. inline float FixedToFloat(FT_Pos value)
  40. {
  41. return value / 64.0f;
  42. }
  43. /// FreeType library subsystem.
  44. class FreeTypeLibrary : public Object
  45. {
  46. URHO3D_OBJECT(FreeTypeLibrary, Object);
  47. public:
  48. /// Construct.
  49. FreeTypeLibrary(Context* context) :
  50. Object(context)
  51. {
  52. FT_Error error = FT_Init_FreeType(&library_);
  53. if (error)
  54. URHO3D_LOGERROR("Could not initialize FreeType library");
  55. }
  56. /// Destruct.
  57. virtual ~FreeTypeLibrary() override
  58. {
  59. FT_Done_FreeType(library_);
  60. }
  61. FT_Library GetLibrary() const { return library_; }
  62. private:
  63. /// FreeType library.
  64. FT_Library library_;
  65. };
  66. FontFaceFreeType::FontFaceFreeType(Font* font) :
  67. FontFace(font),
  68. face_(nullptr),
  69. loadMode_(FT_LOAD_DEFAULT),
  70. hasMutableGlyph_(false)
  71. {
  72. }
  73. FontFaceFreeType::~FontFaceFreeType()
  74. {
  75. if (face_)
  76. {
  77. FT_Done_Face((FT_Face)face_);
  78. face_ = nullptr;
  79. }
  80. }
  81. bool FontFaceFreeType::Load(const unsigned char* fontData, unsigned fontDataSize, float pointSize)
  82. {
  83. Context* context = font_->GetContext();
  84. // Create & initialize FreeType library if it does not exist yet
  85. FreeTypeLibrary* freeType = font_->GetSubsystem<FreeTypeLibrary>();
  86. if (!freeType)
  87. context->RegisterSubsystem(freeType = new FreeTypeLibrary(context));
  88. // Ensure the FreeType library is kept alive as long as TTF font resources exist
  89. freeType_ = freeType;
  90. UI* ui = font_->GetSubsystem<UI>();
  91. const int maxTextureSize = ui->GetMaxFontTextureSize();
  92. const FontHintLevel hintLevel = ui->GetFontHintLevel();
  93. const float subpixelThreshold = ui->GetFontSubpixelThreshold();
  94. subpixel_ = (hintLevel <= FONT_HINT_LEVEL_LIGHT) && (pointSize <= subpixelThreshold);
  95. oversampling_ = subpixel_ ? ui->GetFontOversampling() : 1;
  96. FT_Face face;
  97. FT_Error error;
  98. FT_Library library = freeType->GetLibrary();
  99. if (pointSize <= 0)
  100. {
  101. URHO3D_LOGERROR("Zero or negative point size");
  102. return false;
  103. }
  104. if (!fontDataSize)
  105. {
  106. URHO3D_LOGERROR("Could not create font face from zero size data");
  107. return false;
  108. }
  109. error = FT_New_Memory_Face(library, fontData, fontDataSize, 0, &face);
  110. if (error)
  111. {
  112. URHO3D_LOGERROR("Could not create font face");
  113. return false;
  114. }
  115. error = FT_Set_Char_Size(face, 0, pointSize * 64, oversampling_ * FONT_DPI, FONT_DPI);
  116. if (error)
  117. {
  118. FT_Done_Face(face);
  119. URHO3D_LOGERROR("Could not set font point size " + String(pointSize));
  120. return false;
  121. }
  122. face_ = face;
  123. unsigned numGlyphs = (unsigned)face->num_glyphs;
  124. URHO3D_LOGDEBUGF("Font face %s (%fpt) has %d glyphs", GetFileName(font_->GetName()).CString(), pointSize, numGlyphs);
  125. PODVector<unsigned> charCodes(numGlyphs + 1, 0);
  126. // Attempt to load space glyph first regardless if it's listed or not
  127. // In some fonts (Consola) it is missing
  128. charCodes[0] = 32;
  129. FT_UInt glyphIndex;
  130. FT_ULong charCode = FT_Get_First_Char(face, &glyphIndex);
  131. while (glyphIndex != 0)
  132. {
  133. if (glyphIndex < numGlyphs)
  134. charCodes[glyphIndex + 1] = (unsigned)charCode;
  135. charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
  136. }
  137. // Load each of the glyphs to see the sizes & store other information
  138. loadMode_ = FT_LOAD_DEFAULT;
  139. if (ui->GetForceAutoHint())
  140. {
  141. loadMode_ |= FT_LOAD_FORCE_AUTOHINT;
  142. }
  143. if (ui->GetFontHintLevel() == FONT_HINT_LEVEL_NONE)
  144. {
  145. loadMode_ |= FT_LOAD_NO_HINTING;
  146. }
  147. if (ui->GetFontHintLevel() == FONT_HINT_LEVEL_LIGHT)
  148. {
  149. loadMode_ |= FT_LOAD_TARGET_LIGHT;
  150. }
  151. ascender_ = FixedToFloat(face->size->metrics.ascender);
  152. rowHeight_ = FixedToFloat(face->size->metrics.height);
  153. pointSize_ = pointSize;
  154. // Check if the font's OS/2 info gives different (larger) values for ascender & descender
  155. TT_OS2* os2Info = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2);
  156. if (os2Info)
  157. {
  158. float descender = FixedToFloat(face->size->metrics.descender);
  159. float unitsPerEm = face->units_per_EM;
  160. ascender_ = Max(ascender_, os2Info->usWinAscent * face->size->metrics.y_ppem / unitsPerEm);
  161. ascender_ = Max(ascender_, os2Info->sTypoAscender * face->size->metrics.y_ppem / unitsPerEm);
  162. descender = Max(descender, os2Info->usWinDescent * face->size->metrics.y_ppem / unitsPerEm);
  163. descender = Max(descender, os2Info->sTypoDescender * face->size->metrics.y_ppem / unitsPerEm);
  164. rowHeight_ = Max(rowHeight_, ascender_ + descender);
  165. }
  166. int textureWidth = maxTextureSize;
  167. int textureHeight = maxTextureSize;
  168. hasMutableGlyph_ = false;
  169. SharedPtr<Image> image(new Image(font_->GetContext()));
  170. image->SetSize(textureWidth, textureHeight, 1);
  171. unsigned char* imageData = image->GetData();
  172. memset(imageData, 0, (size_t)(image->GetWidth() * image->GetHeight()));
  173. allocator_.Reset(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, textureWidth, textureHeight);
  174. for (unsigned i = 0; i < charCodes.Size(); ++i)
  175. {
  176. unsigned charCode = charCodes[i];
  177. if (charCode == 0)
  178. continue;
  179. if (!LoadCharGlyph(charCode, image))
  180. {
  181. hasMutableGlyph_ = true;
  182. break;
  183. }
  184. }
  185. SharedPtr<Texture2D> texture = LoadFaceTexture(image);
  186. if (!texture)
  187. return false;
  188. textures_.Push(texture);
  189. font_->SetMemoryUse(font_->GetMemoryUse() + textureWidth * textureHeight);
  190. // Store kerning if face has kerning information
  191. if (FT_HAS_KERNING(face))
  192. {
  193. // Read kerning manually to be more efficient and avoid out of memory crash when use large font file, for example there
  194. // are 29354 glyphs in msyh.ttf
  195. FT_ULong tagKern = FT_MAKE_TAG('k', 'e', 'r', 'n');
  196. FT_ULong kerningTableSize = 0;
  197. FT_Error error = FT_Load_Sfnt_Table(face, tagKern, 0, nullptr, &kerningTableSize);
  198. if (error)
  199. {
  200. URHO3D_LOGERROR("Could not get kerning table length");
  201. return false;
  202. }
  203. SharedArrayPtr<unsigned char> kerningTable(new unsigned char[kerningTableSize]);
  204. error = FT_Load_Sfnt_Table(face, tagKern, 0, kerningTable, &kerningTableSize);
  205. if (error)
  206. {
  207. URHO3D_LOGERROR("Could not load kerning table");
  208. return false;
  209. }
  210. // Convert big endian to little endian
  211. for (unsigned i = 0; i < kerningTableSize; i += 2)
  212. Swap(kerningTable[i], kerningTable[i + 1]);
  213. MemoryBuffer deserializer(kerningTable, (unsigned)kerningTableSize);
  214. unsigned short version = deserializer.ReadUShort();
  215. if (version == 0)
  216. {
  217. unsigned numKerningTables = deserializer.ReadUShort();
  218. for (unsigned i = 0; i < numKerningTables; ++i)
  219. {
  220. unsigned short version = deserializer.ReadUShort();
  221. unsigned short length = deserializer.ReadUShort();
  222. unsigned short coverage = deserializer.ReadUShort();
  223. if (version == 0 && coverage == 1)
  224. {
  225. unsigned numKerningPairs = deserializer.ReadUShort();
  226. // Skip searchRange, entrySelector and rangeShift
  227. deserializer.Seek((unsigned)(deserializer.GetPosition() + 3 * sizeof(unsigned short)));
  228. // x_scale is a 16.16 fixed-point value that converts font units -> 26.6 pixels (oversampled!)
  229. float xScale = face->size->metrics.x_scale / float(1 << 22) / oversampling_;
  230. for (unsigned j = 0; j < numKerningPairs; ++j)
  231. {
  232. unsigned leftIndex = deserializer.ReadUShort();
  233. unsigned rightIndex = deserializer.ReadUShort();
  234. float amount = deserializer.ReadShort() * xScale;
  235. unsigned leftCharCode = leftIndex < numGlyphs ? charCodes[leftIndex + 1] : 0;
  236. unsigned rightCharCode = rightIndex < numGlyphs ? charCodes[rightIndex + 1] : 0;
  237. if (leftCharCode != 0 && rightCharCode != 0)
  238. {
  239. unsigned value = (leftCharCode << 16) + rightCharCode;
  240. kerningMapping_[value] = amount;
  241. }
  242. }
  243. }
  244. else
  245. {
  246. // Kerning table contains information we do not support; skip and move to the next (length includes header)
  247. deserializer.Seek((unsigned)(deserializer.GetPosition() + length - 3 * sizeof(unsigned short)));
  248. }
  249. }
  250. }
  251. else
  252. URHO3D_LOGWARNING("Can not read kerning information: not version 0");
  253. }
  254. if (!hasMutableGlyph_)
  255. {
  256. FT_Done_Face(face);
  257. face_ = nullptr;
  258. }
  259. return true;
  260. }
  261. const FontGlyph* FontFaceFreeType::GetGlyph(unsigned c)
  262. {
  263. HashMap<unsigned, FontGlyph>::Iterator i = glyphMapping_.Find(c);
  264. if (i != glyphMapping_.End())
  265. {
  266. FontGlyph& glyph = i->second_;
  267. glyph.used_ = true;
  268. return &glyph;
  269. }
  270. if (LoadCharGlyph(c))
  271. {
  272. HashMap<unsigned, FontGlyph>::Iterator i = glyphMapping_.Find(c);
  273. if (i != glyphMapping_.End())
  274. {
  275. FontGlyph& glyph = i->second_;
  276. glyph.used_ = true;
  277. return &glyph;
  278. }
  279. }
  280. return nullptr;
  281. }
  282. bool FontFaceFreeType::SetupNextTexture(int textureWidth, int textureHeight)
  283. {
  284. SharedPtr<Image> image(new Image(font_->GetContext()));
  285. image->SetSize(textureWidth, textureHeight, 1);
  286. unsigned char* imageData = image->GetData();
  287. memset(imageData, 0, (size_t)(image->GetWidth() * image->GetHeight()));
  288. SharedPtr<Texture2D> texture = LoadFaceTexture(image);
  289. if (!texture)
  290. return false;
  291. textures_.Push(texture);
  292. allocator_.Reset(FONT_TEXTURE_MIN_SIZE, FONT_TEXTURE_MIN_SIZE, textureWidth, textureHeight);
  293. font_->SetMemoryUse(font_->GetMemoryUse() + textureWidth * textureHeight);
  294. return true;
  295. }
  296. void FontFaceFreeType::BoxFilter(unsigned char* dest, size_t destSize, const unsigned char* src, size_t srcSize)
  297. {
  298. const int filterSize = oversampling_;
  299. assert(filterSize > 0);
  300. assert(destSize == srcSize + filterSize - 1);
  301. if (filterSize == 1)
  302. {
  303. memcpy(dest, src, srcSize);
  304. return;
  305. }
  306. // "accumulator" holds the total value of filterSize samples. We add one sample
  307. // and remove one sample per step (with special cases for left and right edges).
  308. int accumulator = 0;
  309. // The divide might make these inner loops slow. If so, some possible optimizations:
  310. // a) Turn it into a fixed-point multiply-and-shift rather than an integer divide;
  311. // b) Make this function a template, with the filter size a compile-time constant.
  312. int i = 0;
  313. if (srcSize < filterSize)
  314. {
  315. for (; i < srcSize; ++i)
  316. {
  317. accumulator += src[i];
  318. dest[i] = accumulator / filterSize;
  319. }
  320. for (; i < filterSize; ++i)
  321. {
  322. dest[i] = accumulator / filterSize;
  323. }
  324. }
  325. else
  326. {
  327. for ( ; i < filterSize; ++i)
  328. {
  329. accumulator += src[i];
  330. dest[i] = accumulator / filterSize;
  331. }
  332. for (; i < srcSize; ++i)
  333. {
  334. accumulator += src[i];
  335. accumulator -= src[i - filterSize];
  336. dest[i] = accumulator / filterSize;
  337. }
  338. }
  339. for (; i < srcSize + filterSize - 1; ++i)
  340. {
  341. accumulator -= src[i - filterSize];
  342. dest[i] = accumulator / filterSize;
  343. }
  344. }
  345. bool FontFaceFreeType::LoadCharGlyph(unsigned charCode, Image* image)
  346. {
  347. if (!face_)
  348. return false;
  349. FT_Face face = (FT_Face)face_;
  350. FT_GlyphSlot slot = face->glyph;
  351. FontGlyph fontGlyph;
  352. FT_Error error = FT_Load_Char(face, charCode, loadMode_ | FT_LOAD_RENDER);
  353. if (error)
  354. {
  355. const char* family = face->family_name ? face->family_name : "NULL";
  356. URHO3D_LOGERRORF("FT_Load_Char failed (family: %s, char code: %u)", family, charCode);
  357. fontGlyph.texWidth_ = 0;
  358. fontGlyph.texHeight_ = 0;
  359. fontGlyph.width_ = 0;
  360. fontGlyph.height_ = 0;
  361. fontGlyph.offsetX_ = 0;
  362. fontGlyph.offsetY_ = 0;
  363. fontGlyph.advanceX_ = 0;
  364. fontGlyph.page_ = 0;
  365. }
  366. else
  367. {
  368. // Note: position within texture will be filled later
  369. fontGlyph.texWidth_ = slot->bitmap.width + oversampling_ - 1;
  370. fontGlyph.texHeight_ = slot->bitmap.rows;
  371. fontGlyph.width_ = slot->bitmap.width + oversampling_ - 1;
  372. fontGlyph.height_ = slot->bitmap.rows;
  373. fontGlyph.offsetX_ = slot->bitmap_left - (oversampling_ - 1) / 2.0f;
  374. fontGlyph.offsetY_ = floorf(ascender_ + 0.5f) - slot->bitmap_top;
  375. if (subpixel_ && slot->linearHoriAdvance)
  376. {
  377. // linearHoriAdvance is stored in 16.16 fixed point, not the usual 26.6
  378. fontGlyph.advanceX_ = slot->linearHoriAdvance / 65536.0;
  379. }
  380. else
  381. {
  382. // Round to nearest pixel (only necessary when hinting is disabled)
  383. fontGlyph.advanceX_ = floorf(FixedToFloat(slot->metrics.horiAdvance) + 0.5f);
  384. }
  385. fontGlyph.width_ /= oversampling_;
  386. fontGlyph.offsetX_ /= oversampling_;
  387. fontGlyph.advanceX_ /= oversampling_;
  388. }
  389. int x = 0, y = 0;
  390. if (fontGlyph.texWidth_ > 0 && fontGlyph.texHeight_ > 0)
  391. {
  392. if (!allocator_.Allocate(fontGlyph.texWidth_ + 1, fontGlyph.texHeight_ + 1, x, y))
  393. {
  394. if (image)
  395. {
  396. // We're rendering into a fixed image and we ran out of room.
  397. return false;
  398. }
  399. int w = allocator_.GetWidth();
  400. int h = allocator_.GetHeight();
  401. if (!SetupNextTexture(w, h))
  402. {
  403. URHO3D_LOGWARNINGF("FontFaceFreeType::LoadCharGlyph: failed to allocate new %dx%d texture", w, h);
  404. return false;
  405. }
  406. if (!allocator_.Allocate(fontGlyph.texWidth_ + 1, fontGlyph.texHeight_ + 1, x, y))
  407. {
  408. URHO3D_LOGWARNINGF("FontFaceFreeType::LoadCharGlyph: failed to position char code %u in blank page", charCode);
  409. return false;
  410. }
  411. }
  412. fontGlyph.x_ = (short)x;
  413. fontGlyph.y_ = (short)y;
  414. unsigned char* dest = nullptr;
  415. unsigned pitch = 0;
  416. if (image)
  417. {
  418. fontGlyph.page_ = 0;
  419. dest = image->GetData() + fontGlyph.y_ * image->GetWidth() + fontGlyph.x_;
  420. pitch = (unsigned)image->GetWidth();
  421. }
  422. else
  423. {
  424. fontGlyph.page_ = textures_.Size() - 1;
  425. dest = new unsigned char[fontGlyph.texWidth_ * fontGlyph.texHeight_];
  426. pitch = (unsigned)fontGlyph.texWidth_;
  427. }
  428. if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO)
  429. {
  430. for (unsigned y = 0; y < (unsigned)slot->bitmap.rows; ++y)
  431. {
  432. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  433. unsigned char* rowDest = dest + (oversampling_ - 1)/2 + y * pitch;
  434. // Don't do any oversampling, just unpack the bits directly.
  435. for (unsigned x = 0; x < (unsigned)slot->bitmap.width; ++x)
  436. rowDest[x] = (unsigned char)((src[x >> 3] & (0x80 >> (x & 7))) ? 255 : 0);
  437. }
  438. }
  439. else
  440. {
  441. for (unsigned y = 0; y < (unsigned)slot->bitmap.rows; ++y)
  442. {
  443. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  444. unsigned char* rowDest = dest + y * pitch;
  445. BoxFilter(rowDest, fontGlyph.texWidth_, src, slot->bitmap.width);
  446. }
  447. }
  448. if (!image)
  449. {
  450. textures_.Back()->SetData(0, fontGlyph.x_, fontGlyph.y_, fontGlyph.texWidth_, fontGlyph.texHeight_, dest);
  451. delete[] dest;
  452. }
  453. }
  454. else
  455. {
  456. fontGlyph.x_ = 0;
  457. fontGlyph.y_ = 0;
  458. fontGlyph.page_ = 0;
  459. }
  460. glyphMapping_[charCode] = fontGlyph;
  461. return true;
  462. }
  463. }