BsFreeImgImporter.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsFreeImgImporter.h"
  4. #include "BsResource.h"
  5. #include "BsDebug.h"
  6. #include "BsDataStream.h"
  7. #include "BsTextureManager.h"
  8. #include "BsTexture.h"
  9. #include "BsTextureImportOptions.h"
  10. #include "BsFileSystem.h"
  11. #include "BsCoreApplication.h"
  12. #include "BsCoreThread.h"
  13. #include "BsCoreThreadAccessor.h"
  14. #include "FreeImage.h"
  15. using namespace std::placeholders;
  16. namespace BansheeEngine
  17. {
  18. void FreeImageLoadErrorHandler(FREE_IMAGE_FORMAT fif, const char *message)
  19. {
  20. // Callback method as required by FreeImage to report problems
  21. const char* typeName = FreeImage_GetFormatFromFIF(fif);
  22. if (typeName)
  23. {
  24. gDebug().logError("FreeImage error: '" + String(message) + "' when loading format " + typeName);
  25. }
  26. else
  27. {
  28. gDebug().logError("FreeImage error: '" + String(message) + "'");
  29. }
  30. }
  31. FreeImgImporter::FreeImgImporter()
  32. :SpecificImporter()
  33. {
  34. FreeImage_Initialise(false);
  35. // Register codecs
  36. WStringStream strExt;
  37. strExt << "Supported formats: ";
  38. bool first = true;
  39. for (int i = 0; i < FreeImage_GetFIFCount(); ++i)
  40. {
  41. // Skip DDS codec since FreeImage does not have the option
  42. // to keep DXT data compressed, we'll use our own codec
  43. if ((FREE_IMAGE_FORMAT)i == FIF_DDS)
  44. continue;
  45. WString exts = toWString(String(FreeImage_GetFIFExtensionList((FREE_IMAGE_FORMAT)i)));
  46. if (!first)
  47. {
  48. strExt << ",";
  49. }
  50. first = false;
  51. strExt << exts;
  52. // Pull off individual formats (separated by comma by FI)
  53. Vector<WString> extsVector = StringUtil::split(exts, L",");
  54. for (auto v = extsVector.begin(); v != extsVector.end(); ++v)
  55. {
  56. auto findIter = std::find(mExtensions.begin(), mExtensions.end(), *v);
  57. if(findIter == mExtensions.end())
  58. {
  59. WString ext = *v;
  60. StringUtil::toLowerCase(ext);
  61. mExtensionToFID.insert(std::make_pair(ext, i));
  62. mExtensions.push_back(ext);
  63. }
  64. }
  65. }
  66. // Set error handler
  67. FreeImage_SetOutputMessage(FreeImageLoadErrorHandler);
  68. }
  69. FreeImgImporter::~FreeImgImporter()
  70. {
  71. FreeImage_DeInitialise();
  72. }
  73. bool FreeImgImporter::isExtensionSupported(const WString& ext) const
  74. {
  75. WString lowerCaseExt = ext;
  76. StringUtil::toLowerCase(lowerCaseExt);
  77. return find(mExtensions.begin(), mExtensions.end(), lowerCaseExt) != mExtensions.end();
  78. }
  79. bool FreeImgImporter::isMagicNumberSupported(const UINT8* magicNumPtr, UINT32 numBytes) const
  80. {
  81. WString ext = magicNumToExtension(magicNumPtr, numBytes);
  82. return isExtensionSupported(ext);
  83. }
  84. WString FreeImgImporter::magicNumToExtension(const UINT8* magic, UINT32 maxBytes) const
  85. {
  86. // Set error handler
  87. FreeImage_SetOutputMessage(FreeImageLoadErrorHandler);
  88. FIMEMORY* fiMem =
  89. FreeImage_OpenMemory((BYTE*)magic, static_cast<DWORD>(maxBytes));
  90. FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(fiMem, (int)maxBytes);
  91. FreeImage_CloseMemory(fiMem);
  92. if (fif != FIF_UNKNOWN)
  93. {
  94. WString ext = toWString(String(FreeImage_GetFormatFromFIF(fif)));
  95. StringUtil::toLowerCase(ext);
  96. return ext;
  97. }
  98. else
  99. {
  100. return StringUtil::WBLANK;
  101. }
  102. }
  103. ImportOptionsPtr FreeImgImporter::createImportOptions() const
  104. {
  105. return bs_shared_ptr_new<TextureImportOptions>();
  106. }
  107. ResourcePtr FreeImgImporter::import(const Path& filePath, ConstImportOptionsPtr importOptions)
  108. {
  109. const TextureImportOptions* textureImportOptions = static_cast<const TextureImportOptions*>(importOptions.get());
  110. DataStreamPtr fileData = FileSystem::openFile(filePath, true);
  111. PixelDataPtr imgData = importRawImage(fileData);
  112. if(imgData == nullptr || imgData->getData() == nullptr)
  113. return nullptr;
  114. UINT32 numMips = 0;
  115. if (textureImportOptions->getGenerateMipmaps())
  116. {
  117. UINT32 maxPossibleMip = PixelUtil::getMaxMipmaps(imgData->getWidth(), imgData->getHeight(), imgData->getDepth(), imgData->getFormat());
  118. if (textureImportOptions->getMaxMip() == 0)
  119. {
  120. numMips = maxPossibleMip;
  121. }
  122. else
  123. {
  124. numMips = std::min(maxPossibleMip, textureImportOptions->getMaxMip());
  125. }
  126. }
  127. int usage = TU_DEFAULT;
  128. if (textureImportOptions->getCPUReadable())
  129. usage |= TU_CPUCACHED;
  130. bool sRGB = textureImportOptions->getSRGB();
  131. TexturePtr newTexture = Texture::_createPtr(TEX_TYPE_2D,
  132. imgData->getWidth(), imgData->getHeight(), numMips, textureImportOptions->getFormat(), usage, sRGB);
  133. Vector<PixelDataPtr> mipLevels;
  134. if (numMips > 0)
  135. mipLevels = PixelUtil::genMipmaps(*imgData, MipMapGenOptions());
  136. else
  137. mipLevels.insert(mipLevels.begin(), imgData);
  138. for (UINT32 mip = 0; mip < (UINT32)mipLevels.size(); ++mip)
  139. {
  140. UINT32 subresourceIdx = newTexture->getProperties().mapToSubresourceIdx(0, mip);
  141. PixelDataPtr dst = newTexture->getProperties().allocateSubresourceBuffer(subresourceIdx);
  142. PixelUtil::bulkPixelConversion(*mipLevels[mip], *dst);
  143. newTexture->writeSubresource(gCoreAccessor(), subresourceIdx, dst, false);
  144. }
  145. fileData->close();
  146. WString fileName = filePath.getWFilename(false);
  147. newTexture->setName(fileName);
  148. return newTexture;
  149. }
  150. PixelDataPtr FreeImgImporter::importRawImage(DataStreamPtr fileData)
  151. {
  152. if(fileData->size() > std::numeric_limits<UINT32>::max())
  153. {
  154. BS_EXCEPT(InternalErrorException, "File size larger than supported!");
  155. }
  156. UINT32 magicLen = std::min((UINT32)fileData->size(), 32u);
  157. UINT8 magicBuf[32];
  158. fileData->read(magicBuf, magicLen);
  159. fileData->seek(0);
  160. WString fileExtension = magicNumToExtension(magicBuf, magicLen);
  161. auto findFormat = mExtensionToFID.find(fileExtension);
  162. if(findFormat == mExtensionToFID.end())
  163. {
  164. BS_EXCEPT(InvalidParametersException, "Type of the file provided is not supported by this importer. File type: " + toString(fileExtension));
  165. }
  166. FREE_IMAGE_FORMAT imageFormat = (FREE_IMAGE_FORMAT)findFormat->second;
  167. // Set error handler
  168. FreeImage_SetOutputMessage(FreeImageLoadErrorHandler);
  169. // Buffer stream into memory (TODO: override IO functions instead?)
  170. MemoryDataStream memStream(fileData);
  171. fileData->close();
  172. FIMEMORY* fiMem = FreeImage_OpenMemory(memStream.getPtr(), static_cast<DWORD>(memStream.size()));
  173. FIBITMAP* fiBitmap = FreeImage_LoadFromMemory(
  174. (FREE_IMAGE_FORMAT)imageFormat, fiMem);
  175. if (!fiBitmap)
  176. {
  177. BS_EXCEPT(InternalErrorException, "Error decoding image");
  178. }
  179. UINT32 width = FreeImage_GetWidth(fiBitmap);
  180. UINT32 height = FreeImage_GetHeight(fiBitmap);
  181. PixelFormat format = PF_UNKNOWN;
  182. // Must derive format first, this may perform conversions
  183. FREE_IMAGE_TYPE imageType = FreeImage_GetImageType(fiBitmap);
  184. FREE_IMAGE_COLOR_TYPE colourType = FreeImage_GetColorType(fiBitmap);
  185. unsigned bpp = FreeImage_GetBPP(fiBitmap);
  186. switch(imageType)
  187. {
  188. case FIT_UNKNOWN:
  189. case FIT_COMPLEX:
  190. case FIT_UINT32:
  191. case FIT_INT32:
  192. case FIT_DOUBLE:
  193. default:
  194. BS_EXCEPT(InternalErrorException, "Unknown or unsupported image format");
  195. break;
  196. case FIT_BITMAP:
  197. // Standard image type
  198. // Perform any colour conversions for greyscale
  199. if (colourType == FIC_MINISWHITE || colourType == FIC_MINISBLACK)
  200. {
  201. FIBITMAP* newBitmap = FreeImage_ConvertToGreyscale(fiBitmap);
  202. // free old bitmap and replace
  203. FreeImage_Unload(fiBitmap);
  204. fiBitmap = newBitmap;
  205. // get new formats
  206. bpp = FreeImage_GetBPP(fiBitmap);
  207. colourType = FreeImage_GetColorType(fiBitmap);
  208. }
  209. // Perform any colour conversions for RGB
  210. else if (bpp < 8 || colourType == FIC_PALETTE || colourType == FIC_CMYK)
  211. {
  212. FIBITMAP* newBitmap = FreeImage_ConvertTo24Bits(fiBitmap);
  213. // free old bitmap and replace
  214. FreeImage_Unload(fiBitmap);
  215. fiBitmap = newBitmap;
  216. // get new formats
  217. bpp = FreeImage_GetBPP(fiBitmap);
  218. colourType = FreeImage_GetColorType(fiBitmap);
  219. }
  220. // by this stage, 8-bit is greyscale, 16/24/32 bit are RGB[A]
  221. switch(bpp)
  222. {
  223. case 8:
  224. format = PF_R8;
  225. break;
  226. case 16:
  227. // Determine 555 or 565 from green mask
  228. // cannot be 16-bit greyscale since that's FIT_UINT16
  229. if(FreeImage_GetGreenMask(fiBitmap) == FI16_565_GREEN_MASK)
  230. {
  231. assert(false && "Format not supported by the engine. TODO.");
  232. return nullptr;
  233. }
  234. else
  235. {
  236. assert(false && "Format not supported by the engine. TODO.");
  237. return nullptr;
  238. // FreeImage doesn't support 4444 format so must be 1555
  239. }
  240. break;
  241. case 24:
  242. // FreeImage differs per platform
  243. // PF_BYTE_BGR[A] for little endian (== PF_ARGB native)
  244. // PF_BYTE_RGB[A] for big endian (== PF_RGBA native)
  245. #if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_RGB
  246. format = PF_BYTE_RGB;
  247. #else
  248. format = PF_BYTE_BGR;
  249. #endif
  250. break;
  251. case 32:
  252. #if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_RGB
  253. format = PF_BYTE_RGBA;
  254. #else
  255. format = PF_BYTE_BGRA;
  256. #endif
  257. break;
  258. };
  259. break;
  260. case FIT_UINT16:
  261. case FIT_INT16:
  262. // 16-bit greyscale
  263. assert(false && "No INT pixel formats supported currently. TODO.");
  264. return nullptr;
  265. break;
  266. case FIT_FLOAT:
  267. // Single-component floating point data
  268. format = PF_FLOAT32_R;
  269. break;
  270. case FIT_RGB16:
  271. format = PF_FLOAT16_RGB;
  272. break;
  273. case FIT_RGBA16:
  274. format = PF_FLOAT16_RGBA;
  275. break;
  276. case FIT_RGBF:
  277. format = PF_FLOAT32_RGB;
  278. break;
  279. case FIT_RGBAF:
  280. format = PF_FLOAT32_RGBA;
  281. break;
  282. };
  283. unsigned char* srcData = FreeImage_GetBits(fiBitmap);
  284. unsigned srcPitch = FreeImage_GetPitch(fiBitmap);
  285. // Final data - invert image and trim pitch at the same time
  286. UINT32 dstPitch = width * PixelUtil::getNumElemBytes(format);
  287. UINT32 size = dstPitch * height;
  288. // Bind output buffer
  289. PixelDataPtr texData = bs_shared_ptr_new<PixelData>(width, height, 1, format);
  290. texData->allocateInternalBuffer();
  291. UINT8* output = texData->getData();
  292. UINT8* pSrc;
  293. UINT8* pDst = output;
  294. for (UINT32 y = 0; y < height; ++y)
  295. {
  296. pSrc = srcData + (height - y - 1) * srcPitch;
  297. memcpy(pDst, pSrc, dstPitch);
  298. pDst += dstPitch;
  299. }
  300. FreeImage_Unload(fiBitmap);
  301. FreeImage_CloseMemory(fiMem);
  302. return texData;
  303. }
  304. }