BsFontImporter.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. #include "BsFontImporter.h"
  2. #include "BsFontImportOptions.h"
  3. #include "BsPixelData.h"
  4. #include "BsTexture.h"
  5. #include "BsResources.h"
  6. #include "BsDebug.h"
  7. #include "BsTexAtlasGenerator.h"
  8. #include "BsCoreApplication.h"
  9. #include "BsCoreThread.h"
  10. #include "BsCoreThreadAccessor.h"
  11. #include <ft2build.h>
  12. #include <freetype/freetype.h>
  13. #include FT_FREETYPE_H
  14. using namespace std::placeholders;
  15. namespace BansheeEngine
  16. {
  17. FontImporter::FontImporter()
  18. :SpecificImporter()
  19. {
  20. mExtensions.push_back(L"ttf");
  21. mExtensions.push_back(L"otf");
  22. }
  23. FontImporter::~FontImporter()
  24. {
  25. }
  26. bool FontImporter::isExtensionSupported(const WString& ext) const
  27. {
  28. WString lowerCaseExt = ext;
  29. StringUtil::toLowerCase(lowerCaseExt);
  30. return find(mExtensions.begin(), mExtensions.end(), lowerCaseExt) != mExtensions.end();
  31. }
  32. bool FontImporter::isMagicNumberSupported(const UINT8* magicNumPtr, UINT32 numBytes) const
  33. {
  34. // TODO
  35. return false;
  36. }
  37. ImportOptionsPtr FontImporter::createImportOptions() const
  38. {
  39. return bs_shared_ptr_new<FontImportOptions>();
  40. }
  41. ResourcePtr FontImporter::import(const Path& filePath, ConstImportOptionsPtr importOptions)
  42. {
  43. const FontImportOptions* fontImportOptions = static_cast<const FontImportOptions*>(importOptions.get());
  44. FT_Library library;
  45. FT_Error error = FT_Init_FreeType(&library);
  46. if (error)
  47. BS_EXCEPT(InternalErrorException, "Error occurred during FreeType library initialization.");
  48. FT_Face face;
  49. error = FT_New_Face(library, filePath.toString().c_str(), 0, &face);
  50. if (error == FT_Err_Unknown_File_Format)
  51. {
  52. BS_EXCEPT(InternalErrorException, "Failed to load font file: " + filePath.toString() + ". Unsupported file format.");
  53. }
  54. else if (error)
  55. {
  56. BS_EXCEPT(InternalErrorException, "Failed to load font file: " + filePath.toString() + ". Unknown error.");
  57. }
  58. Vector<std::pair<UINT32, UINT32>> charIndexRanges = fontImportOptions->getCharIndexRanges();
  59. Vector<UINT32> fontSizes = fontImportOptions->getFontSizes();
  60. UINT32 dpi = fontImportOptions->getDPI();
  61. FT_Int32 loadFlags = FT_LOAD_RENDER;
  62. if(!fontImportOptions->getAntialiasing())
  63. loadFlags |= FT_LOAD_TARGET_MONO | FT_LOAD_NO_AUTOHINT;
  64. Vector<FontData> dataPerSize;
  65. for(size_t i = 0; i < fontSizes.size(); i++)
  66. {
  67. FT_F26Dot6 ftSize = (FT_F26Dot6)(fontSizes[i] * (1 << 6));
  68. if(FT_Set_Char_Size( face, ftSize, 0, dpi, dpi))
  69. BS_EXCEPT(InternalErrorException, "Could not set character size." );
  70. FontData fontData;
  71. // Get all char sizes so we can generate texture layout
  72. Vector<TexAtlasElementDesc> atlasElements;
  73. Map<UINT32, UINT32> seqIdxToCharIdx;
  74. for(auto iter = charIndexRanges.begin(); iter != charIndexRanges.end(); ++iter)
  75. {
  76. for(UINT32 charIdx = iter->first; charIdx <= iter->second; charIdx++)
  77. {
  78. error = FT_Load_Char(face, (FT_ULong)charIdx, loadFlags);
  79. if(error)
  80. BS_EXCEPT(InternalErrorException, "Failed to load a character");
  81. FT_GlyphSlot slot = face->glyph;
  82. TexAtlasElementDesc atlasElement;
  83. atlasElement.input.width = slot->bitmap.width;
  84. atlasElement.input.height = slot->bitmap.rows;
  85. atlasElements.push_back(atlasElement);
  86. seqIdxToCharIdx[(UINT32)atlasElements.size() - 1] = charIdx;
  87. }
  88. }
  89. // Add missing glyph
  90. {
  91. error = FT_Load_Glyph(face, (FT_ULong)0, loadFlags);
  92. if(error)
  93. BS_EXCEPT(InternalErrorException, "Failed to load a character");
  94. FT_GlyphSlot slot = face->glyph;
  95. TexAtlasElementDesc atlasElement;
  96. atlasElement.input.width = slot->bitmap.width;
  97. atlasElement.input.height = slot->bitmap.rows;
  98. atlasElements.push_back(atlasElement);
  99. }
  100. // Create an optimal layout for character bitmaps
  101. TexAtlasGenerator texAtlasGen(false, MAXIMUM_TEXTURE_SIZE, MAXIMUM_TEXTURE_SIZE);
  102. Vector<TexAtlasPageDesc> pages = texAtlasGen.createAtlasLayout(atlasElements);
  103. INT32 baselineOffset = 0;
  104. UINT32 lineHeight = 0;
  105. // Create char bitmap atlas textures and load character information
  106. UINT32 pageIdx = 0;
  107. for(auto pageIter = pages.begin(); pageIter != pages.end(); ++pageIter)
  108. {
  109. UINT32 bufferSize = pageIter->width * pageIter->height * 2;
  110. // TODO - I don't actually need a 2 channel texture
  111. PixelDataPtr pixelData = bs_shared_ptr_new<PixelData>(pageIter->width, pageIter->height, 1, PF_R8G8);
  112. pixelData->allocateInternalBuffer();
  113. UINT8* pixelBuffer = pixelData->getData();
  114. memset(pixelBuffer, 0, bufferSize);
  115. for(size_t elementIdx = 0; elementIdx < atlasElements.size(); elementIdx++)
  116. {
  117. // Copy character bitmap
  118. if(atlasElements[elementIdx].output.page != pageIdx)
  119. continue;
  120. TexAtlasElementDesc curElement = atlasElements[elementIdx];
  121. bool isMissingGlypth = elementIdx == (atlasElements.size() - 1); // It's always the last element
  122. UINT32 charIdx = 0;
  123. if(!isMissingGlypth)
  124. {
  125. charIdx = seqIdxToCharIdx[(UINT32)elementIdx];
  126. error = FT_Load_Char(face, charIdx, loadFlags);
  127. }
  128. else
  129. {
  130. error = FT_Load_Glyph(face, 0, loadFlags);
  131. }
  132. if(error)
  133. BS_EXCEPT(InternalErrorException, "Failed to load a character");
  134. FT_GlyphSlot slot = face->glyph;
  135. if(slot->bitmap.buffer == nullptr && slot->bitmap.rows > 0 && slot->bitmap.width > 0)
  136. BS_EXCEPT(InternalErrorException, "Failed to render glyph bitmap");
  137. UINT8* sourceBuffer = slot->bitmap.buffer;
  138. UINT8* dstBuffer = pixelBuffer + (curElement.output.y * pageIter->width * 2) + curElement.output.x * 2;
  139. if(slot->bitmap.pixel_mode == ft_pixel_mode_grays)
  140. {
  141. for(INT32 bitmapRow = 0; bitmapRow < slot->bitmap.rows; bitmapRow++)
  142. {
  143. for(INT32 bitmapColumn = 0; bitmapColumn < slot->bitmap.width; bitmapColumn++)
  144. {
  145. dstBuffer[bitmapColumn * 2 + 0] = sourceBuffer[bitmapColumn];
  146. dstBuffer[bitmapColumn * 2 + 1] = sourceBuffer[bitmapColumn];
  147. }
  148. dstBuffer += pageIter->width * 2;
  149. sourceBuffer += slot->bitmap.pitch;
  150. }
  151. }
  152. else if(slot->bitmap.pixel_mode == ft_pixel_mode_mono)
  153. {
  154. // 8 pixels are packed into a byte, so do some unpacking
  155. for(INT32 bitmapRow = 0; bitmapRow < slot->bitmap.rows; bitmapRow++)
  156. {
  157. for(INT32 bitmapColumn = 0; bitmapColumn < slot->bitmap.width; bitmapColumn++)
  158. {
  159. UINT8 srcValue = sourceBuffer[bitmapColumn >> 3];
  160. UINT8 dstValue = (srcValue & (128 >> (bitmapColumn & 7))) != 0 ? 255 : 0;
  161. dstBuffer[bitmapColumn * 2 + 0] = dstValue;
  162. dstBuffer[bitmapColumn * 2 + 1] = dstValue;
  163. }
  164. dstBuffer += pageIter->width * 2;
  165. sourceBuffer += slot->bitmap.pitch;
  166. }
  167. }
  168. else
  169. BS_EXCEPT(InternalErrorException, "Unsupported pixel mode for a FreeType bitmap.");
  170. // Store character information
  171. CHAR_DESC charDesc;
  172. float invTexWidth = 1.0f / pageIter->width;
  173. float invTexHeight = 1.0f / pageIter->height;
  174. charDesc.charId = charIdx;
  175. charDesc.width = curElement.input.width;
  176. charDesc.height = curElement.input.height;
  177. charDesc.page = curElement.output.page;
  178. charDesc.uvWidth = invTexWidth * curElement.input.width;
  179. charDesc.uvHeight = invTexHeight * curElement.input.height;
  180. charDesc.uvX = invTexWidth * curElement.output.x;
  181. charDesc.uvY = invTexHeight * curElement.output.y;
  182. charDesc.xOffset = slot->bitmap_left;
  183. charDesc.yOffset = slot->bitmap_top;
  184. charDesc.xAdvance = slot->advance.x >> 6;
  185. charDesc.yAdvance = slot->advance.y >> 6;
  186. baselineOffset = std::max(baselineOffset, (INT32)(slot->metrics.horiBearingY >> 6));
  187. lineHeight = std::max(lineHeight, charDesc.height);
  188. // Load kerning and store char
  189. if(!isMissingGlypth)
  190. {
  191. FT_Vector resultKerning;
  192. for(auto kerningIter = charIndexRanges.begin(); kerningIter != charIndexRanges.end(); ++kerningIter)
  193. {
  194. for(UINT32 kerningCharIdx = kerningIter->first; kerningCharIdx <= kerningIter->second; kerningCharIdx++)
  195. {
  196. if(kerningCharIdx == charIdx)
  197. continue;
  198. error = FT_Get_Kerning(face, charIdx, kerningCharIdx, FT_KERNING_DEFAULT, &resultKerning);
  199. if(error)
  200. BS_EXCEPT(InternalErrorException, "Failed to get kerning information for character: " + toString(charIdx));
  201. INT32 kerningX = (INT32)(resultKerning.x >> 6); // Y kerning is ignored because it is so rare
  202. if(kerningX == 0) // We don't store 0 kerning, this is assumed default
  203. continue;
  204. KerningPair pair;
  205. pair.amount = kerningX;
  206. pair.otherCharId = kerningCharIdx;
  207. charDesc.kerningPairs.push_back(pair);
  208. }
  209. }
  210. fontData.fontDesc.characters[charIdx] = charDesc;
  211. }
  212. else
  213. {
  214. fontData.fontDesc.missingGlyph = charDesc;
  215. }
  216. }
  217. HTexture newTex = Texture::create(TEX_TYPE_2D, pageIter->width, pageIter->height, 0, PF_R8G8);
  218. UINT32 subresourceIdx = newTex->getProperties().mapToSubresourceIdx(0, 0);
  219. // It's possible the formats no longer match
  220. if (newTex->getProperties().getFormat() != pixelData->getFormat())
  221. {
  222. PixelDataPtr temp = newTex->getProperties().allocateSubresourceBuffer(subresourceIdx);
  223. PixelUtil::bulkPixelConversion(*pixelData, *temp);
  224. newTex->writeSubresource(gCoreAccessor(), subresourceIdx, temp, false);
  225. }
  226. else
  227. {
  228. newTex->writeSubresource(gCoreAccessor(), subresourceIdx, pixelData, false);
  229. }
  230. newTex->setName(L"FontPage" + toWString((UINT32)fontData.texturePages.size()));
  231. fontData.texturePages.push_back(newTex);
  232. pageIdx++;
  233. }
  234. fontData.size = fontSizes[i];
  235. fontData.fontDesc.baselineOffset = baselineOffset;
  236. fontData.fontDesc.lineHeight = lineHeight;
  237. // Get space size
  238. error = FT_Load_Char(face, 32, loadFlags);
  239. if(error)
  240. BS_EXCEPT(InternalErrorException, "Failed to load a character");
  241. fontData.fontDesc.spaceWidth = face->glyph->advance.x >> 6;
  242. dataPerSize.push_back(fontData);
  243. }
  244. FontPtr newFont = Font::_createPtr(dataPerSize);
  245. FT_Done_FreeType(library);
  246. WString fileName = filePath.getWFilename(false);
  247. newFont->setName(fileName);
  248. return newFont;
  249. }
  250. }