CmFontImporter.cpp 11 KB

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