CmFontImporter.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. #include "CmFontImporter.h"
  2. #include "CmFontImportOptions.h"
  3. #include "CmPixelData.h"
  4. #include "CmTexture.h"
  5. #include "CmResources.h"
  6. #include "CmDebug.h"
  7. #include "CmTexAtlasGenerator.h"
  8. #include <ft2build.h>
  9. #include <freetype/freetype.h>
  10. #include FT_FREETYPE_H
  11. namespace CamelotEngine
  12. {
  13. FontImporter::FontImporter()
  14. :SpecificImporter()
  15. {
  16. mExtensions.push_back("ttf");
  17. mExtensions.push_back("otf");
  18. }
  19. FontImporter::~FontImporter()
  20. {
  21. }
  22. bool FontImporter::isExtensionSupported(const String& ext) const
  23. {
  24. String lowerCaseExt = ext;
  25. StringUtil::toLowerCase(lowerCaseExt);
  26. return find(mExtensions.begin(), mExtensions.end(), lowerCaseExt) != mExtensions.end();
  27. }
  28. bool FontImporter::isMagicNumberSupported(const UINT8* magicNumPtr, UINT32 numBytes) const
  29. {
  30. // TODO
  31. return false;
  32. }
  33. ImportOptionsPtr FontImporter::createImportOptions() const
  34. {
  35. return ImportOptionsPtr(new FontImportOptions());
  36. }
  37. BaseResourceHandle FontImporter::import(const String& filePath, ConstImportOptionsPtr importOptions)
  38. {
  39. const FontImportOptions* gpuProgImportOptions = static_cast<const FontImportOptions*>(importOptions.get());
  40. FT_Library library;
  41. FT_Error error = FT_Init_FreeType(&library);
  42. if (error)
  43. CM_EXCEPT(InternalErrorException, "Error occurred during FreeType library initialization.");
  44. FT_Face face;
  45. error = FT_New_Face(library, filePath.c_str(), 0, &face);
  46. if (error == FT_Err_Unknown_File_Format)
  47. {
  48. CM_EXCEPT(InternalErrorException, "Failed to load font file: " + filePath + ". Unsupported file format.");
  49. }
  50. else if (error)
  51. {
  52. CM_EXCEPT(InternalErrorException, "Failed to load font file: " + filePath + ". Unknown error.");
  53. }
  54. vector<std::pair<UINT32, UINT32>>::type charIndexRanges = gpuProgImportOptions->getCharIndexRanges();
  55. vector<UINT32>::type fontSizes = gpuProgImportOptions->getFontSizes();
  56. UINT32 dpi = gpuProgImportOptions->getDPI();
  57. vector<FontData>::type dataPerSize;
  58. for(size_t i = 0; i < fontSizes.size(); i++)
  59. {
  60. FT_F26Dot6 ftSize = (FT_F26Dot6)(fontSizes[i] * (1 << 6));
  61. if(FT_Set_Char_Size( face, ftSize, 0, dpi, dpi))
  62. CM_EXCEPT(InternalErrorException, "Could not set character size." );
  63. FontData fontData;
  64. // Get all char sizes so we can generate texture layout
  65. vector<TexAtlasElementDesc>::type atlasElements;
  66. map<UINT32, UINT32>::type seqIdxToCharIdx;
  67. for(auto iter = charIndexRanges.begin(); iter != charIndexRanges.end(); ++iter)
  68. {
  69. for(UINT32 charIdx = iter->first; charIdx <= iter->second; charIdx++)
  70. {
  71. error = FT_Load_Char(face, (FT_ULong)charIdx, FT_LOAD_RENDER);
  72. if(error)
  73. CM_EXCEPT(InternalErrorException, "Failed to load a character");
  74. FT_GlyphSlot slot = face->glyph;
  75. TexAtlasElementDesc atlasElement;
  76. atlasElement.input.width = slot->bitmap.width;
  77. atlasElement.input.height = slot->bitmap.rows;
  78. atlasElements.push_back(atlasElement);
  79. seqIdxToCharIdx[(UINT32)atlasElements.size() - 1] = charIdx;
  80. }
  81. }
  82. // Add missing glyph
  83. {
  84. error = FT_Load_Glyph(face, (FT_ULong)0, FT_LOAD_RENDER);
  85. if(error)
  86. CM_EXCEPT(InternalErrorException, "Failed to load a character");
  87. FT_GlyphSlot slot = face->glyph;
  88. TexAtlasElementDesc atlasElement;
  89. atlasElement.input.width = slot->bitmap.width;
  90. atlasElement.input.height = slot->bitmap.rows;
  91. atlasElements.push_back(atlasElement);
  92. }
  93. // Create an optimal layout for character bitmaps
  94. TexAtlasGenerator texAtlasGen(false, MAXIMUM_TEXTURE_SIZE, MAXIMUM_TEXTURE_SIZE);
  95. vector<TexAtlasPageDesc>::type pages = texAtlasGen.createAtlasLayout(atlasElements);
  96. INT32 baselineOffset = 0;
  97. UINT32 lineHeight = 0;
  98. // Create char bitmap atlas textures and load character information
  99. UINT32 pageIdx = 0;
  100. for(auto pageIter = pages.begin(); pageIter != pages.end(); ++pageIter)
  101. {
  102. UINT32 bufferSize = pageIter->width * pageIter->height * 2;
  103. UINT8* pixelBuffer = new UINT8[bufferSize];
  104. memset(pixelBuffer, 0, bufferSize);
  105. PixelData pixelData(pageIter->width, pageIter->height, 1, PF_R8G8, pixelBuffer, true);
  106. for(size_t elementIdx = 0; elementIdx < atlasElements.size(); elementIdx++)
  107. {
  108. // Copy character bitmap
  109. if(atlasElements[elementIdx].output.page != pageIdx)
  110. continue;
  111. TexAtlasElementDesc curElement = atlasElements[elementIdx];
  112. bool isMissingGlypth = elementIdx == (atlasElements.size() - 1); // It's always the last element
  113. UINT32 charIdx = 0;
  114. if(!isMissingGlypth)
  115. {
  116. charIdx = seqIdxToCharIdx[(UINT32)elementIdx];
  117. error = FT_Load_Char(face, charIdx, FT_LOAD_RENDER);
  118. }
  119. else
  120. {
  121. error = FT_Load_Glyph(face, 0, FT_LOAD_RENDER);
  122. }
  123. if(error)
  124. CM_EXCEPT(InternalErrorException, "Failed to load a character");
  125. FT_GlyphSlot slot = face->glyph;
  126. if(slot->bitmap.buffer == nullptr && slot->bitmap.rows > 0 && slot->bitmap.width > 0)
  127. CM_EXCEPT(InternalErrorException, "Failed to render glyph bitmap");
  128. UINT8* sourceBuffer = slot->bitmap.buffer;
  129. UINT8* dstBuffer = pixelBuffer + (curElement.output.y * pageIter->width * 2) + curElement.output.x * 2;
  130. for(INT32 bitmapRow = 0; bitmapRow < slot->bitmap.rows; bitmapRow++)
  131. {
  132. for(INT32 bitmapColumn = 0; bitmapColumn < slot->bitmap.width; bitmapColumn++)
  133. {
  134. dstBuffer[bitmapColumn * 2 + 0] = sourceBuffer[bitmapColumn];
  135. dstBuffer[bitmapColumn * 2 + 1] = sourceBuffer[bitmapColumn];
  136. }
  137. dstBuffer += pageIter->width * 2;
  138. sourceBuffer += slot->bitmap.pitch;
  139. }
  140. // Store character information
  141. CHAR_DESC charDesc;
  142. float invTexWidth = 1.0f / pageIter->width;
  143. float invTexHeight = 1.0f / pageIter->height;
  144. charDesc.charId = charIdx;
  145. charDesc.width = curElement.input.width;
  146. charDesc.height = curElement.input.height;
  147. charDesc.page = curElement.output.page;
  148. charDesc.uvWidth = invTexWidth * curElement.input.width;
  149. charDesc.uvHeight = invTexHeight * curElement.input.height;
  150. charDesc.uvX = invTexWidth * curElement.output.x;
  151. charDesc.uvY = invTexHeight * curElement.output.y;
  152. charDesc.xOffset = slot->bitmap_left;
  153. charDesc.yOffset = slot->bitmap_top;
  154. charDesc.xAdvance = slot->advance.x >> 6;
  155. charDesc.yAdvance = slot->advance.y >> 6;
  156. baselineOffset = std::max(baselineOffset, (INT32)(slot->metrics.horiBearingY >> 6));
  157. lineHeight = std::max(lineHeight, charDesc.height);
  158. // Load kerning and store char
  159. if(!isMissingGlypth)
  160. {
  161. FT_Vector resultKerning;
  162. for(auto kerningIter = charIndexRanges.begin(); kerningIter != charIndexRanges.end(); ++kerningIter)
  163. {
  164. for(UINT32 kerningCharIdx = kerningIter->first; kerningCharIdx <= kerningIter->second; kerningCharIdx++)
  165. {
  166. if(kerningCharIdx == charIdx)
  167. continue;
  168. error = FT_Get_Kerning(face, charIdx, kerningCharIdx, FT_KERNING_DEFAULT, &resultKerning);
  169. if(error)
  170. CM_EXCEPT(InternalErrorException, "Failed to get kerning information for character: " + toString(charIdx));
  171. INT32 kerningX = (INT32)(resultKerning.x >> 6); // Y kerning is ignored because it is so rare
  172. if(kerningX == 0) // We don't store 0 kerning, this is assumed default
  173. continue;
  174. KerningPair pair;
  175. pair.amount = kerningX;
  176. pair.otherCharId = kerningCharIdx;
  177. charDesc.kerningPairs.push_back(pair);
  178. }
  179. }
  180. fontData.fontDesc.characters[charIdx] = charDesc;
  181. }
  182. else
  183. {
  184. fontData.fontDesc.missingGlyph = charDesc;
  185. }
  186. }
  187. TextureHandle newTex = Texture::create(TEX_TYPE_2D, pageIter->width, pageIter->height, 0, PF_R8G8);
  188. newTex.waitUntilLoaded();
  189. newTex->setRawPixels(pixelData);
  190. fontData.texturePages.push_back(newTex);
  191. pageIdx++;
  192. }
  193. fontData.size = fontSizes[i];
  194. fontData.fontDesc.baselineOffset = baselineOffset;
  195. fontData.fontDesc.lineHeight = lineHeight;
  196. // Get space size
  197. error = FT_Load_Char(face, 32, FT_LOAD_RENDER);
  198. if(error)
  199. CM_EXCEPT(InternalErrorException, "Failed to load a character");
  200. fontData.fontDesc.spaceWidth = face->glyph->advance.x >> 6;
  201. dataPerSize.push_back(fontData);
  202. }
  203. FontHandle newFont = Font::create(dataPerSize);
  204. FT_Done_FreeType(library);
  205. return newFont;
  206. }
  207. }