BsFontImporter.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsFontImporter.h"
  4. #include "Text/BsFontImportOptions.h"
  5. #include "Image/BsPixelData.h"
  6. #include "Image/BsTexture.h"
  7. #include "Image/BsTextureAtlasLayout.h"
  8. #include "BsCoreApplication.h"
  9. #include "CoreThread/BsCoreThread.h"
  10. #include <ft2build.h>
  11. #include <freetype/freetype.h>
  12. #include FT_FREETYPE_H
  13. using namespace std::placeholders;
  14. namespace bs
  15. {
  16. FontImporter::FontImporter()
  17. :SpecificImporter()
  18. {
  19. mExtensions.push_back(L"ttf");
  20. mExtensions.push_back(L"otf");
  21. }
  22. FontImporter::~FontImporter()
  23. {
  24. }
  25. bool FontImporter::isExtensionSupported(const WString& ext) const
  26. {
  27. WString lowerCaseExt = ext;
  28. StringUtil::toLowerCase(lowerCaseExt);
  29. return find(mExtensions.begin(), mExtensions.end(), lowerCaseExt) != mExtensions.end();
  30. }
  31. bool FontImporter::isMagicNumberSupported(const UINT8* magicNumPtr, UINT32 numBytes) const
  32. {
  33. // TODO
  34. return false;
  35. }
  36. SPtr<ImportOptions> FontImporter::createImportOptions() const
  37. {
  38. return bs_shared_ptr_new<FontImportOptions>();
  39. }
  40. SPtr<Resource> FontImporter::import(const Path& filePath, SPtr<const ImportOptions> importOptions)
  41. {
  42. const FontImportOptions* fontImportOptions = static_cast<const FontImportOptions*>(importOptions.get());
  43. FT_Library library;
  44. FT_Error error = FT_Init_FreeType(&library);
  45. if (error)
  46. BS_EXCEPT(InternalErrorException, "Error occurred during FreeType library initialization.");
  47. FT_Face face;
  48. error = FT_New_Face(library, filePath.toString().c_str(), 0, &face);
  49. if (error == FT_Err_Unknown_File_Format)
  50. {
  51. BS_EXCEPT(InternalErrorException, "Failed to load font file: " + filePath.toString() + ". Unsupported file format.");
  52. }
  53. else if (error)
  54. {
  55. BS_EXCEPT(InternalErrorException, "Failed to load font file: " + filePath.toString() + ". Unknown error.");
  56. }
  57. Vector<std::pair<UINT32, UINT32>> charIndexRanges = fontImportOptions->getCharIndexRanges();
  58. Vector<UINT32> fontSizes = fontImportOptions->getFontSizes();
  59. UINT32 dpi = fontImportOptions->getDPI();
  60. FT_Int32 loadFlags;
  61. switch (fontImportOptions->getRenderMode())
  62. {
  63. case FontRenderMode::Smooth:
  64. loadFlags = FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING;
  65. break;
  66. case FontRenderMode::Raster:
  67. loadFlags = FT_LOAD_TARGET_MONO | FT_LOAD_NO_HINTING;
  68. break;
  69. case FontRenderMode::HintedSmooth:
  70. loadFlags = FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_AUTOHINT;
  71. break;
  72. case FontRenderMode::HintedRaster:
  73. loadFlags = FT_LOAD_TARGET_MONO | FT_LOAD_NO_AUTOHINT;
  74. break;
  75. default:
  76. loadFlags = FT_LOAD_TARGET_NORMAL;
  77. break;
  78. }
  79. FT_Render_Mode renderMode = FT_LOAD_TARGET_MODE(loadFlags);
  80. Vector<SPtr<FontBitmap>> dataPerSize;
  81. for(size_t i = 0; i < fontSizes.size(); i++)
  82. {
  83. // Note: Disabled as its not working and I have bigger issues to handle than to figure this out atm
  84. //FT_Matrix m;
  85. //if (fontImportOptions->getBold())
  86. // m.xx = (long)(1.25f * (1 << 16));
  87. //else
  88. // m.xx = (long)(1 * (1 << 16));
  89. //if (fontImportOptions->getItalic())
  90. // m.xy = (long)(0.25f * (1 << 16));
  91. //else
  92. // m.xy = (long)(0 * (1 << 16));
  93. //m.yx = (long)(0 * (1 << 16));
  94. //m.yy = (long)(1 * (1 << 16));
  95. //FT_Set_Transform(face, &m, nullptr);
  96. FT_F26Dot6 ftSize = (FT_F26Dot6)(fontSizes[i] * (1 << 6));
  97. if (FT_Set_Char_Size(face, ftSize, 0, dpi, dpi))
  98. BS_EXCEPT(InternalErrorException, "Could not set character size.");
  99. SPtr<FontBitmap> fontData = bs_shared_ptr_new<FontBitmap>();
  100. // Get all char sizes so we can generate texture layout
  101. Vector<TextureAtlasUtility::Element> atlasElements;
  102. Map<UINT32, UINT32> seqIdxToCharIdx;
  103. for(auto iter = charIndexRanges.begin(); iter != charIndexRanges.end(); ++iter)
  104. {
  105. for(UINT32 charIdx = iter->first; charIdx <= iter->second; charIdx++)
  106. {
  107. error = FT_Load_Char(face, (FT_ULong)charIdx, loadFlags);
  108. if(error)
  109. BS_EXCEPT(InternalErrorException, "Failed to load a character");
  110. FT_Render_Glyph(face->glyph, renderMode);
  111. if (error)
  112. BS_EXCEPT(InternalErrorException, "Failed to render a character");
  113. FT_GlyphSlot slot = face->glyph;
  114. TextureAtlasUtility::Element atlasElement;
  115. atlasElement.input.width = slot->bitmap.width;
  116. atlasElement.input.height = slot->bitmap.rows;
  117. atlasElements.push_back(atlasElement);
  118. seqIdxToCharIdx[(UINT32)atlasElements.size() - 1] = charIdx;
  119. }
  120. }
  121. // Add missing glyph
  122. {
  123. error = FT_Load_Glyph(face, (FT_ULong)0, loadFlags);
  124. if(error)
  125. BS_EXCEPT(InternalErrorException, "Failed to load a character");
  126. FT_Render_Glyph(face->glyph, renderMode);
  127. if (error)
  128. BS_EXCEPT(InternalErrorException, "Failed to render a character");
  129. FT_GlyphSlot slot = face->glyph;
  130. TextureAtlasUtility::Element atlasElement;
  131. atlasElement.input.width = slot->bitmap.width;
  132. atlasElement.input.height = slot->bitmap.rows;
  133. atlasElements.push_back(atlasElement);
  134. }
  135. // Create an optimal layout for character bitmaps
  136. Vector<TextureAtlasUtility::Page> pages = TextureAtlasUtility::createAtlasLayout(atlasElements, 64, 64,
  137. MAXIMUM_TEXTURE_SIZE, MAXIMUM_TEXTURE_SIZE, true);
  138. INT32 baselineOffset = 0;
  139. UINT32 lineHeight = 0;
  140. // Create char bitmap atlas textures and load character information
  141. UINT32 pageIdx = 0;
  142. for(auto pageIter = pages.begin(); pageIter != pages.end(); ++pageIter)
  143. {
  144. UINT32 bufferSize = pageIter->width * pageIter->height * 2;
  145. // TODO - I don't actually need a 2 channel texture
  146. SPtr<PixelData> pixelData = bs_shared_ptr_new<PixelData>(pageIter->width, pageIter->height, 1, PF_RG8);
  147. pixelData->allocateInternalBuffer();
  148. UINT8* pixelBuffer = pixelData->getData();
  149. memset(pixelBuffer, 0, bufferSize);
  150. for(size_t i = 0; i < atlasElements.size(); i++)
  151. {
  152. // Copy character bitmap
  153. if(atlasElements[i].output.page != pageIdx)
  154. continue;
  155. TextureAtlasUtility::Element curElement = atlasElements[i];
  156. UINT32 elementIdx = curElement.output.idx;
  157. bool isMissingGlypth = elementIdx == (atlasElements.size() - 1); // It's always the last element
  158. UINT32 charIdx = 0;
  159. if(!isMissingGlypth)
  160. {
  161. charIdx = seqIdxToCharIdx[(UINT32)elementIdx];
  162. error = FT_Load_Char(face, charIdx, loadFlags);
  163. }
  164. else
  165. {
  166. error = FT_Load_Glyph(face, 0, loadFlags);
  167. }
  168. if(error)
  169. BS_EXCEPT(InternalErrorException, "Failed to load a character");
  170. FT_Render_Glyph(face->glyph, renderMode);
  171. if (error)
  172. BS_EXCEPT(InternalErrorException, "Failed to render a character");
  173. FT_GlyphSlot slot = face->glyph;
  174. if(slot->bitmap.buffer == nullptr && slot->bitmap.rows > 0 && slot->bitmap.width > 0)
  175. BS_EXCEPT(InternalErrorException, "Failed to render glyph bitmap");
  176. UINT8* sourceBuffer = slot->bitmap.buffer;
  177. UINT8* dstBuffer = pixelBuffer + (curElement.output.y * pageIter->width * 2) + curElement.output.x * 2;
  178. if(slot->bitmap.pixel_mode == ft_pixel_mode_grays)
  179. {
  180. for(INT32 bitmapRow = 0; bitmapRow < slot->bitmap.rows; bitmapRow++)
  181. {
  182. for(INT32 bitmapColumn = 0; bitmapColumn < slot->bitmap.width; bitmapColumn++)
  183. {
  184. dstBuffer[bitmapColumn * 2 + 0] = sourceBuffer[bitmapColumn];
  185. dstBuffer[bitmapColumn * 2 + 1] = sourceBuffer[bitmapColumn];
  186. }
  187. dstBuffer += pageIter->width * 2;
  188. sourceBuffer += slot->bitmap.pitch;
  189. }
  190. }
  191. else if(slot->bitmap.pixel_mode == ft_pixel_mode_mono)
  192. {
  193. // 8 pixels are packed into a byte, so do some unpacking
  194. for(INT32 bitmapRow = 0; bitmapRow < slot->bitmap.rows; bitmapRow++)
  195. {
  196. for(INT32 bitmapColumn = 0; bitmapColumn < slot->bitmap.width; bitmapColumn++)
  197. {
  198. UINT8 srcValue = sourceBuffer[bitmapColumn >> 3];
  199. UINT8 dstValue = (srcValue & (128 >> (bitmapColumn & 7))) != 0 ? 255 : 0;
  200. dstBuffer[bitmapColumn * 2 + 0] = dstValue;
  201. dstBuffer[bitmapColumn * 2 + 1] = dstValue;
  202. }
  203. dstBuffer += pageIter->width * 2;
  204. sourceBuffer += slot->bitmap.pitch;
  205. }
  206. }
  207. else
  208. BS_EXCEPT(InternalErrorException, "Unsupported pixel mode for a FreeType bitmap.");
  209. // Store character information
  210. CHAR_DESC charDesc;
  211. float invTexWidth = 1.0f / pageIter->width;
  212. float invTexHeight = 1.0f / pageIter->height;
  213. charDesc.charId = charIdx;
  214. charDesc.width = curElement.input.width;
  215. charDesc.height = curElement.input.height;
  216. charDesc.page = curElement.output.page;
  217. charDesc.uvWidth = invTexWidth * curElement.input.width;
  218. charDesc.uvHeight = invTexHeight * curElement.input.height;
  219. charDesc.uvX = invTexWidth * curElement.output.x;
  220. charDesc.uvY = invTexHeight * curElement.output.y;
  221. charDesc.xOffset = slot->bitmap_left;
  222. charDesc.yOffset = slot->bitmap_top;
  223. charDesc.xAdvance = slot->advance.x >> 6;
  224. charDesc.yAdvance = slot->advance.y >> 6;
  225. baselineOffset = std::max(baselineOffset, (INT32)(slot->metrics.horiBearingY >> 6));
  226. lineHeight = std::max(lineHeight, charDesc.height);
  227. // Load kerning and store char
  228. if(!isMissingGlypth)
  229. {
  230. FT_Vector resultKerning;
  231. for(auto kerningIter = charIndexRanges.begin(); kerningIter != charIndexRanges.end(); ++kerningIter)
  232. {
  233. for(UINT32 kerningCharIdx = kerningIter->first; kerningCharIdx <= kerningIter->second; kerningCharIdx++)
  234. {
  235. if(kerningCharIdx == charIdx)
  236. continue;
  237. error = FT_Get_Kerning(face, charIdx, kerningCharIdx, FT_KERNING_DEFAULT, &resultKerning);
  238. if(error)
  239. BS_EXCEPT(InternalErrorException, "Failed to get kerning information for character: " + toString(charIdx));
  240. INT32 kerningX = (INT32)(resultKerning.x >> 6); // Y kerning is ignored because it is so rare
  241. if(kerningX == 0) // We don't store 0 kerning, this is assumed default
  242. continue;
  243. KerningPair pair;
  244. pair.amount = kerningX;
  245. pair.otherCharId = kerningCharIdx;
  246. charDesc.kerningPairs.push_back(pair);
  247. }
  248. }
  249. fontData->fontDesc.characters[charIdx] = charDesc;
  250. }
  251. else
  252. {
  253. fontData->fontDesc.missingGlyph = charDesc;
  254. }
  255. }
  256. TEXTURE_DESC texDesc;
  257. texDesc.width = pageIter->width;
  258. texDesc.height = pageIter->height;
  259. texDesc.format = PF_RG8;
  260. HTexture newTex = Texture::create(texDesc);
  261. // It's possible the formats no longer match
  262. if (newTex->getProperties().getFormat() != pixelData->getFormat())
  263. {
  264. SPtr<PixelData> temp = newTex->getProperties().allocBuffer(0, 0);
  265. PixelUtil::bulkPixelConversion(*pixelData, *temp);
  266. newTex->writeData(temp);
  267. }
  268. else
  269. {
  270. newTex->writeData(pixelData);
  271. }
  272. newTex->setName(L"FontPage" + toWString((UINT32)fontData->texturePages.size()));
  273. fontData->texturePages.push_back(newTex);
  274. pageIdx++;
  275. }
  276. fontData->size = fontSizes[i];
  277. fontData->fontDesc.baselineOffset = baselineOffset;
  278. fontData->fontDesc.lineHeight = lineHeight;
  279. // Get space size
  280. error = FT_Load_Char(face, 32, loadFlags);
  281. if(error)
  282. BS_EXCEPT(InternalErrorException, "Failed to load a character");
  283. fontData->fontDesc.spaceWidth = face->glyph->advance.x >> 6;
  284. dataPerSize.push_back(fontData);
  285. }
  286. SPtr<Font> newFont = Font::_createPtr(dataPerSize);
  287. FT_Done_FreeType(library);
  288. WString fileName = filePath.getWFilename(false);
  289. newFont->setName(fileName);
  290. return newFont;
  291. }
  292. }