FontFaceFreeType.cpp 16 KB

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