font_manager.cpp 14 KB

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