FontFaceFreeType.cpp 17 KB

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