FontFaceFreeType.cpp 17 KB

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