font_manager.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. /*
  2. * Copyright 2013 Jeremie Roy. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include <bx/bx.h>
  6. #include <stb/stb_truetype.h>
  7. #include "../common.h"
  8. #include <bgfx/bgfx.h>
  9. #define SDF_IMPLEMENTATION
  10. #include <sdf/sdf.h>
  11. #include <wchar.h> // wcslen
  12. #include <tinystl/allocator.h>
  13. #include <tinystl/unordered_map.h>
  14. namespace stl = tinystl;
  15. #include "font_manager.h"
  16. #include "../cube_atlas.h"
  17. class TrueTypeFont
  18. {
  19. public:
  20. TrueTypeFont();
  21. ~TrueTypeFont();
  22. /// Initialize from an external buffer
  23. /// @remark The ownership of the buffer is external, and you must ensure it stays valid up to this object lifetime
  24. /// @return true if the initialization succeed
  25. bool init(const uint8_t* _buffer, uint32_t _bufferSize, int32_t _fontIndex, uint32_t _pixelHeight);
  26. /// return the font descriptor of the current font
  27. FontInfo getFontInfo();
  28. /// raster a glyph as 8bit alpha to a memory buffer
  29. /// update the GlyphInfo according to the raster strategy
  30. /// @ remark buffer min size: glyphInfo.m_width * glyphInfo * height * sizeof(char)
  31. bool bakeGlyphAlpha(CodePoint _codePoint, GlyphInfo& _outGlyphInfo, uint8_t* _outBuffer);
  32. /// raster a glyph as 8bit signed distance to a memory buffer
  33. /// update the GlyphInfo according to the raster strategy
  34. /// @ remark buffer min size: glyphInfo.m_width * glyphInfo * height * sizeof(char)
  35. bool bakeGlyphDistance(CodePoint _codePoint, GlyphInfo& _outGlyphInfo, uint8_t* _outBuffer);
  36. private:
  37. stbtt_fontinfo m_font;
  38. float m_scale;
  39. };
  40. TrueTypeFont::TrueTypeFont() : m_font()
  41. {
  42. }
  43. TrueTypeFont::~TrueTypeFont()
  44. {
  45. }
  46. bool TrueTypeFont::init(const uint8_t* _buffer, uint32_t _bufferSize, int32_t _fontIndex, uint32_t _pixelHeight)
  47. {
  48. BX_CHECK(m_font == NULL, "TrueTypeFont already initialized");
  49. BX_CHECK( (_bufferSize > 256 && _bufferSize < 100000000), "TrueType buffer size is suspicious");
  50. BX_CHECK( (_pixelHeight > 4 && _pixelHeight < 128), "TrueType buffer size is suspicious");
  51. BX_UNUSED(_bufferSize);
  52. int offset = stbtt_GetFontOffsetForIndex(_buffer, _fontIndex);
  53. stbtt_InitFont(&m_font, _buffer, offset);
  54. m_scale = stbtt_ScaleForMappingEmToPixels(&m_font, (float)_pixelHeight);
  55. return true;
  56. }
  57. FontInfo TrueTypeFont::getFontInfo()
  58. {
  59. BX_CHECK(m_font != NULL, "TrueTypeFont not initialized");
  60. int ascent;
  61. int descent;
  62. int lineGap;
  63. stbtt_GetFontVMetrics(&m_font, &ascent, &descent, &lineGap);
  64. float scale = m_scale;
  65. int x0, y0, x1, y1;
  66. stbtt_GetFontBoundingBox(&m_font, &x0, &y0, &x1, &y1);
  67. FontInfo outFontInfo;
  68. outFontInfo.scale = 1.0f;
  69. outFontInfo.ascender = bx::round(ascent * scale);
  70. outFontInfo.descender = bx::round(descent * scale);
  71. outFontInfo.lineGap = bx::round(lineGap * scale);
  72. outFontInfo.maxAdvanceWidth = bx::round((y1 - y0) * scale);
  73. outFontInfo.underlinePosition = (x1 - x0) * scale - ascent;
  74. outFontInfo.underlineThickness = (x1 - x0) * scale / 24.f;
  75. return outFontInfo;
  76. }
  77. bool TrueTypeFont::bakeGlyphAlpha(CodePoint _codePoint, GlyphInfo& _glyphInfo, uint8_t* _outBuffer)
  78. {
  79. BX_CHECK(m_font != NULL, "TrueTypeFont not initialized");
  80. int xx;
  81. int yy;
  82. int ww;
  83. int hh;
  84. int advance;
  85. int ascent;
  86. int descent;
  87. int lineGap;
  88. int lsb;
  89. float scale = m_scale;
  90. stbtt_GetFontVMetrics(&m_font, &ascent, &descent, &lineGap);
  91. stbtt_GetCodepointHMetrics(&m_font, _codePoint, &advance, &lsb);
  92. stbtt_GetCodepointBitmap(&m_font, scale, scale, _codePoint, &ww, &hh, &xx, &yy);
  93. _glyphInfo.offset_x = (float)xx;
  94. _glyphInfo.offset_y = (float)yy;
  95. _glyphInfo.width = (float)ww;
  96. _glyphInfo.height = (float)hh;
  97. _glyphInfo.advance_x = bx::round(((float)advance) * scale);
  98. _glyphInfo.advance_y = bx::round(((float)(ascent + descent + lineGap)) * scale);
  99. uint32_t bpp = 1;
  100. uint32_t dstPitch = ww * bpp;
  101. stbtt_MakeCodepointBitmap(&m_font, _outBuffer, ww, hh, dstPitch, scale, scale, _codePoint);
  102. return true;
  103. }
  104. bool TrueTypeFont::bakeGlyphDistance(CodePoint _codePoint, GlyphInfo& _glyphInfo, uint8_t* _outBuffer)
  105. {
  106. BX_CHECK(m_font != NULL, "TrueTypeFont not initialized");
  107. int32_t xx;
  108. int32_t yy;
  109. int32_t ww;
  110. int32_t hh;
  111. int advance;
  112. int ascent;
  113. int descent;
  114. int lineGap;
  115. int lsb;
  116. float scale = m_scale;
  117. stbtt_GetFontVMetrics(&m_font, &ascent, &descent, &lineGap);
  118. stbtt_GetCodepointHMetrics(&m_font, _codePoint, &advance, &lsb);
  119. stbtt_GetCodepointBitmap(&m_font, scale, scale, _codePoint, &ww, &hh, &xx, &yy);
  120. _glyphInfo.offset_x = (float)xx;
  121. _glyphInfo.offset_y = (float)yy;
  122. _glyphInfo.width = (float)ww;
  123. _glyphInfo.height = (float)hh;
  124. _glyphInfo.advance_x = bx::round(((float)advance) * scale);
  125. _glyphInfo.advance_y = bx::round(((float)(ascent + descent + lineGap)) * scale);
  126. uint32_t bpp = 1;
  127. uint32_t dstPitch = ww * bpp;
  128. stbtt_MakeCodepointBitmap(&m_font, _outBuffer, ww, hh, dstPitch, scale, scale, _codePoint);
  129. if (ww * hh > 0)
  130. {
  131. uint32_t dw = 6;
  132. uint32_t dh = 6;
  133. uint32_t nw = ww + dw * 2;
  134. uint32_t nh = hh + dh * 2;
  135. BX_CHECK(nw * nh < 128 * 128, "Buffer overflow (size %d)", nw * nh);
  136. uint32_t buffSize = nw * nh * sizeof(uint8_t);
  137. uint8_t* alphaImg = (uint8_t*)malloc(buffSize);
  138. bx::memSet(alphaImg, 0, nw * nh * sizeof(uint8_t) );
  139. //copy the original buffer to the temp one
  140. for (uint32_t ii = dh; ii < nh - dh; ++ii)
  141. {
  142. bx::memCopy(alphaImg + ii * nw + dw, _outBuffer + (ii - dh) * ww, ww);
  143. }
  144. // stb_truetype has some builtin sdf functionality, we can investigate using that too
  145. sdfBuild(_outBuffer, nw, 8.0f, alphaImg, nw, nh, nw);
  146. free(alphaImg);
  147. _glyphInfo.offset_x -= (float)dw;
  148. _glyphInfo.offset_y -= (float)dh;
  149. _glyphInfo.width = (float)nw;
  150. _glyphInfo.height = (float)nh;
  151. }
  152. return true;
  153. }
  154. typedef stl::unordered_map<CodePoint, GlyphInfo> GlyphHashMap;
  155. // cache font data
  156. struct FontManager::CachedFont
  157. {
  158. CachedFont()
  159. : trueTypeFont(NULL)
  160. {
  161. masterFontHandle.idx = bx::kInvalidHandle;
  162. }
  163. FontInfo fontInfo;
  164. GlyphHashMap cachedGlyphs;
  165. TrueTypeFont* trueTypeFont;
  166. // an handle to a master font in case of sub distance field font
  167. FontHandle masterFontHandle;
  168. int16_t padding;
  169. };
  170. #define MAX_FONT_BUFFER_SIZE (512 * 512 * 4)
  171. FontManager::FontManager(Atlas* _atlas)
  172. : m_ownAtlas(false)
  173. , m_atlas(_atlas)
  174. {
  175. init();
  176. }
  177. FontManager::FontManager(uint16_t _textureSideWidth)
  178. : m_ownAtlas(true)
  179. , m_atlas(new Atlas(_textureSideWidth) )
  180. {
  181. init();
  182. }
  183. void FontManager::init()
  184. {
  185. m_cachedFiles = new CachedFile[MAX_OPENED_FILES];
  186. m_cachedFonts = new CachedFont[MAX_OPENED_FONT];
  187. m_buffer = new uint8_t[MAX_FONT_BUFFER_SIZE];
  188. const uint32_t W = 3;
  189. // Create filler rectangle
  190. uint8_t buffer[W * W * 4];
  191. bx::memSet(buffer, 255, W * W * 4);
  192. m_blackGlyph.width = W;
  193. m_blackGlyph.height = W;
  194. ///make sure the black glyph doesn't bleed by using a one pixel inner outline
  195. m_blackGlyph.regionIndex = m_atlas->addRegion(W, W, buffer, AtlasRegion::TYPE_GRAY, 1);
  196. }
  197. FontManager::~FontManager()
  198. {
  199. BX_CHECK(m_fontHandles.getNumHandles() == 0, "All the fonts must be destroyed before destroying the manager");
  200. delete [] m_cachedFonts;
  201. BX_CHECK(m_filesHandles.getNumHandles() == 0, "All the font files must be destroyed before destroying the manager");
  202. delete [] m_cachedFiles;
  203. delete [] m_buffer;
  204. if (m_ownAtlas)
  205. {
  206. delete m_atlas;
  207. }
  208. }
  209. TrueTypeHandle FontManager::createTtf(const uint8_t* _buffer, uint32_t _size)
  210. {
  211. uint16_t id = m_filesHandles.alloc();
  212. BX_CHECK(id != bx::kInvalidHandle, "Invalid handle used");
  213. m_cachedFiles[id].buffer = new uint8_t[_size];
  214. m_cachedFiles[id].bufferSize = _size;
  215. bx::memCopy(m_cachedFiles[id].buffer, _buffer, _size);
  216. TrueTypeHandle ret = { id };
  217. return ret;
  218. }
  219. void FontManager::destroyTtf(TrueTypeHandle _handle)
  220. {
  221. BX_CHECK(bgfx::isValid(_handle), "Invalid handle used");
  222. delete m_cachedFiles[_handle.idx].buffer;
  223. m_cachedFiles[_handle.idx].bufferSize = 0;
  224. m_cachedFiles[_handle.idx].buffer = NULL;
  225. m_filesHandles.free(_handle.idx);
  226. }
  227. FontHandle FontManager::createFontByPixelSize(TrueTypeHandle _ttfHandle, uint32_t _typefaceIndex, uint32_t _pixelSize, uint32_t _fontType)
  228. {
  229. BX_CHECK(bgfx::isValid(_ttfHandle), "Invalid handle used");
  230. TrueTypeFont* ttf = new TrueTypeFont();
  231. if (!ttf->init(m_cachedFiles[_ttfHandle.idx].buffer, m_cachedFiles[_ttfHandle.idx].bufferSize, _typefaceIndex, _pixelSize) )
  232. {
  233. delete ttf;
  234. FontHandle invalid = { bx::kInvalidHandle };
  235. return invalid;
  236. }
  237. uint16_t fontIdx = m_fontHandles.alloc();
  238. BX_CHECK(fontIdx != bx::kInvalidHandle, "Invalid handle used");
  239. CachedFont& font = m_cachedFonts[fontIdx];
  240. font.trueTypeFont = ttf;
  241. font.fontInfo = ttf->getFontInfo();
  242. font.fontInfo.fontType = int16_t(_fontType);
  243. font.fontInfo.pixelSize = uint16_t(_pixelSize);
  244. font.cachedGlyphs.clear();
  245. font.masterFontHandle.idx = bx::kInvalidHandle;
  246. FontHandle handle = { fontIdx };
  247. return handle;
  248. }
  249. FontHandle FontManager::createScaledFontToPixelSize(FontHandle _baseFontHandle, uint32_t _pixelSize)
  250. {
  251. BX_CHECK(bgfx::isValid(_baseFontHandle), "Invalid handle used");
  252. CachedFont& baseFont = m_cachedFonts[_baseFontHandle.idx];
  253. FontInfo& fontInfo = baseFont.fontInfo;
  254. FontInfo newFontInfo = fontInfo;
  255. newFontInfo.pixelSize = uint16_t(_pixelSize);
  256. newFontInfo.scale = (float)_pixelSize / (float) fontInfo.pixelSize;
  257. newFontInfo.ascender = (newFontInfo.ascender * newFontInfo.scale);
  258. newFontInfo.descender = (newFontInfo.descender * newFontInfo.scale);
  259. newFontInfo.lineGap = (newFontInfo.lineGap * newFontInfo.scale);
  260. newFontInfo.maxAdvanceWidth = (newFontInfo.maxAdvanceWidth * newFontInfo.scale);
  261. newFontInfo.underlineThickness = (newFontInfo.underlineThickness * newFontInfo.scale);
  262. newFontInfo.underlinePosition = (newFontInfo.underlinePosition * newFontInfo.scale);
  263. uint16_t fontIdx = m_fontHandles.alloc();
  264. BX_CHECK(fontIdx != bx::kInvalidHandle, "Invalid handle used");
  265. CachedFont& font = m_cachedFonts[fontIdx];
  266. font.cachedGlyphs.clear();
  267. font.fontInfo = newFontInfo;
  268. font.trueTypeFont = NULL;
  269. font.masterFontHandle = _baseFontHandle;
  270. FontHandle handle = { fontIdx };
  271. return handle;
  272. }
  273. void FontManager::destroyFont(FontHandle _handle)
  274. {
  275. BX_CHECK(bgfx::isValid(_handle), "Invalid handle used");
  276. CachedFont& font = m_cachedFonts[_handle.idx];
  277. if (font.trueTypeFont != NULL)
  278. {
  279. delete font.trueTypeFont;
  280. font.trueTypeFont = NULL;
  281. }
  282. font.cachedGlyphs.clear();
  283. m_fontHandles.free(_handle.idx);
  284. }
  285. bool FontManager::preloadGlyph(FontHandle _handle, const wchar_t* _string)
  286. {
  287. BX_CHECK(bgfx::isValid(_handle), "Invalid handle used");
  288. CachedFont& font = m_cachedFonts[_handle.idx];
  289. if (NULL == font.trueTypeFont)
  290. {
  291. return false;
  292. }
  293. for (uint32_t ii = 0, end = (uint32_t)wcslen(_string); ii < end; ++ii)
  294. {
  295. CodePoint codePoint = _string[ii];
  296. if (!preloadGlyph(_handle, codePoint) )
  297. {
  298. return false;
  299. }
  300. }
  301. return true;
  302. }
  303. bool FontManager::preloadGlyph(FontHandle _handle, CodePoint _codePoint)
  304. {
  305. BX_CHECK(bgfx::isValid(_handle), "Invalid handle used");
  306. CachedFont& font = m_cachedFonts[_handle.idx];
  307. FontInfo& fontInfo = font.fontInfo;
  308. GlyphHashMap::iterator iter = font.cachedGlyphs.find(_codePoint);
  309. if (iter != font.cachedGlyphs.end() )
  310. {
  311. return true;
  312. }
  313. if (NULL != font.trueTypeFont)
  314. {
  315. GlyphInfo glyphInfo;
  316. switch (font.fontInfo.fontType)
  317. {
  318. case FONT_TYPE_ALPHA:
  319. font.trueTypeFont->bakeGlyphAlpha(_codePoint, glyphInfo, m_buffer);
  320. break;
  321. case FONT_TYPE_DISTANCE:
  322. font.trueTypeFont->bakeGlyphDistance(_codePoint, glyphInfo, m_buffer);
  323. break;
  324. case FONT_TYPE_DISTANCE_SUBPIXEL:
  325. font.trueTypeFont->bakeGlyphDistance(_codePoint, glyphInfo, m_buffer);
  326. break;
  327. default:
  328. BX_CHECK(false, "TextureType not supported yet");
  329. }
  330. if (!addBitmap(glyphInfo, m_buffer) )
  331. {
  332. return false;
  333. }
  334. glyphInfo.advance_x = (glyphInfo.advance_x * fontInfo.scale);
  335. glyphInfo.advance_y = (glyphInfo.advance_y * fontInfo.scale);
  336. glyphInfo.offset_x = (glyphInfo.offset_x * fontInfo.scale);
  337. glyphInfo.offset_y = (glyphInfo.offset_y * fontInfo.scale);
  338. glyphInfo.height = (glyphInfo.height * fontInfo.scale);
  339. glyphInfo.width = (glyphInfo.width * fontInfo.scale);
  340. font.cachedGlyphs[_codePoint] = glyphInfo;
  341. return true;
  342. }
  343. if (isValid(font.masterFontHandle)
  344. && preloadGlyph(font.masterFontHandle, _codePoint) )
  345. {
  346. const GlyphInfo* glyph = getGlyphInfo(font.masterFontHandle, _codePoint);
  347. GlyphInfo glyphInfo = *glyph;
  348. glyphInfo.advance_x = (glyphInfo.advance_x * fontInfo.scale);
  349. glyphInfo.advance_y = (glyphInfo.advance_y * fontInfo.scale);
  350. glyphInfo.offset_x = (glyphInfo.offset_x * fontInfo.scale);
  351. glyphInfo.offset_y = (glyphInfo.offset_y * fontInfo.scale);
  352. glyphInfo.height = (glyphInfo.height * fontInfo.scale);
  353. glyphInfo.width = (glyphInfo.width * fontInfo.scale);
  354. font.cachedGlyphs[_codePoint] = glyphInfo;
  355. return true;
  356. }
  357. return false;
  358. }
  359. const FontInfo& FontManager::getFontInfo(FontHandle _handle) const
  360. {
  361. BX_CHECK(bgfx::isValid(_handle), "Invalid handle used");
  362. return m_cachedFonts[_handle.idx].fontInfo;
  363. }
  364. const GlyphInfo* FontManager::getGlyphInfo(FontHandle _handle, CodePoint _codePoint)
  365. {
  366. const GlyphHashMap& cachedGlyphs = m_cachedFonts[_handle.idx].cachedGlyphs;
  367. GlyphHashMap::const_iterator it = cachedGlyphs.find(_codePoint);
  368. if (it == cachedGlyphs.end() )
  369. {
  370. if (!preloadGlyph(_handle, _codePoint) )
  371. {
  372. return NULL;
  373. }
  374. it = cachedGlyphs.find(_codePoint);
  375. }
  376. BX_CHECK(it != cachedGlyphs.end(), "Failed to preload glyph.");
  377. return &it->second;
  378. }
  379. bool FontManager::addBitmap(GlyphInfo& _glyphInfo, const uint8_t* _data)
  380. {
  381. _glyphInfo.regionIndex = m_atlas->addRegion(
  382. (uint16_t)bx::ceil(_glyphInfo.width)
  383. , (uint16_t)bx::ceil(_glyphInfo.height)
  384. , _data
  385. , AtlasRegion::TYPE_GRAY
  386. );
  387. return true;
  388. }