bitmapSTB.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "console/console.h"
  24. #include "core/stream/fileStream.h"
  25. #include "core/stream/memStream.h"
  26. #include "core/strings/stringFunctions.h"
  27. #include "gfx/bitmap/gBitmap.h"
  28. #include "gfx/bitmap/imageUtils.h"
  29. #include "gfx/bitmap/loaders/ies/ies_loader.h"
  30. #ifdef __clang__
  31. #define STBIWDEF static inline
  32. #endif
  33. #pragma warning( push )
  34. #pragma warning( disable : 4505 ) // unreferenced function removed.
  35. #ifndef STB_IMAGE_IMPLEMENTATION
  36. #define STB_IMAGE_IMPLEMENTATION
  37. #define STB_IMAGE_STATIC
  38. #include "stb_image.h"
  39. #endif
  40. #define STB_IMAGE_WRITE_IMPLEMENTATION
  41. #define STB_IMAGE_WRITE_STATIC
  42. #include "stb_image_write.h"
  43. #pragma warning(pop)
  44. static bool sReadSTB(const Torque::Path& path, GBitmap* bitmap);
  45. static bool sReadStreamSTB(Stream& stream, GBitmap* bitmap, U32 len);
  46. static bool sWriteSTB(const Torque::Path& path, GBitmap* bitmap, U32 compressionLevel);
  47. static bool sWriteStreamSTB(const String& bmType, Stream& stream, GBitmap* bitmap, U32 compressionLevel);
  48. // stbi_write callback / rextimmy.
  49. static void stbiWriteFunc(void* context, void* data, int size)
  50. {
  51. Stream* stream = static_cast<Stream*>(context);
  52. stream->write(size);
  53. stream->write(size, data);
  54. }
  55. static struct _privateRegisterSTB
  56. {
  57. _privateRegisterSTB()
  58. {
  59. GBitmap::Registration reg;
  60. reg.priority = 100;
  61. reg.extensions.push_back("png");
  62. reg.extensions.push_back("bmp");
  63. reg.extensions.push_back("jpg");
  64. reg.extensions.push_back("jpeg");
  65. reg.extensions.push_back("psd");
  66. reg.extensions.push_back("hdr");
  67. reg.extensions.push_back("tga");
  68. reg.extensions.push_back("ies");
  69. reg.readFunc = sReadSTB;
  70. reg.readStreamFunc = sReadStreamSTB;
  71. reg.writeFunc = sWriteSTB;
  72. reg.writeStreamFunc = sWriteStreamSTB;
  73. // for png only.
  74. reg.defaultCompression = 6;
  75. GBitmap::sRegisterFormat(reg);
  76. }
  77. } sStaticRegisterSTB;
  78. bool sReadSTB(const Torque::Path& path, GBitmap* bitmap)
  79. {
  80. PROFILE_SCOPE(sReadSTB);
  81. S32 x, y, n, channels;
  82. String ext = path.getExtension();
  83. // if this is an ies profile we need to create a texture for it.
  84. if (ext.equal("ies"))
  85. {
  86. String textureName = path.getFullPath();
  87. textureName.replace(".ies", ".png");
  88. x = 256;
  89. y = 1;
  90. n = 4;
  91. channels = 4;
  92. GFXFormat format = GFXFormatR8G8B8A8;
  93. if (Torque::FS::IsFile(textureName.c_str()))
  94. {
  95. // if the txture already exist, load it.
  96. unsigned char* data = stbi_load(textureName.c_str(), &x, &y, &n, channels);
  97. // actually allocate the bitmap space...
  98. bitmap->allocateBitmap(x, y,
  99. false, // don't extrude miplevels...
  100. format); // use determined format...
  101. U8* pBase = (U8*)bitmap->getBits();
  102. U32 rowBytes = bitmap->getByteSize();
  103. dMemcpy(pBase, data, rowBytes);
  104. stbi_image_free(data);
  105. return true;
  106. }
  107. else
  108. {
  109. FileStream* readIes = new FileStream;
  110. if (!readIes->open(path.getFullPath(), Torque::FS::File::Read))
  111. {
  112. Con::printf("Failed to open IES profile:%s", path.getFullFileName().c_str());
  113. return false;
  114. }
  115. if (readIes->getStatus() != Stream::Ok)
  116. {
  117. Con::printf("Failed to open IES profile:%s", path.getFullFileName().c_str());
  118. return false;
  119. }
  120. U32 buffSize = readIes->getStreamSize();
  121. char* buffer = new char[buffSize];
  122. readIes->read(buffSize, buffer);
  123. IESFileInfo info;
  124. IESLoadHelper IESLoader;
  125. if (!IESLoader.load(buffer, buffSize, info))
  126. {
  127. Con::printf("Failed to load IES profile:%s \n LoaderError: %s", path.getFullFileName().c_str(), info.error().c_str());
  128. return false;
  129. }
  130. float* data = new float[x*y*channels];
  131. if (!IESLoader.saveAs1D(info, data, x, channels))
  132. {
  133. Con::printf("Failed to create 2d Texture for IES profile:%s", path.getFullFileName().c_str());
  134. return false;
  135. }
  136. // use stb function to convert float data to uchar
  137. unsigned char* dataChar = stbi__hdr_to_ldr(data, x, y, channels);
  138. bitmap->deleteImage();
  139. // actually allocate the bitmap space...
  140. bitmap->allocateBitmap(x, y,
  141. false,
  142. format);
  143. U8* pBase = (U8*)bitmap->getBits();
  144. U32 rowBytes = x * y * channels;
  145. dMemcpy(pBase, dataChar, rowBytes);
  146. stbi_image_free(dataChar);
  147. sWriteSTB(textureName, bitmap, 10);
  148. return true;
  149. }
  150. }
  151. if (!stbi_info(path.getFullPath().c_str(), &x, &y, &channels))
  152. {
  153. const char* stbErr = stbi_failure_reason();
  154. if (!stbErr)
  155. stbErr = "Unknown Error!";
  156. Con::errorf("STB get file info: %s", stbErr);
  157. }
  158. // do this to map 2 channels to 4, 2 channel not supported by gbitmap yet..
  159. if (channels == 2)
  160. channels = 4;
  161. if (!ext.equal("png"))
  162. {
  163. if (stbi_is_16_bit(path.getFullPath().c_str()))
  164. {
  165. U16* data = stbi_load_16(path.getFullPath().c_str(), &x, &y, &n, channels);
  166. // if succesful deal make the bitmap, else try other loaders.
  167. if (data)
  168. {
  169. GFXFormat format;
  170. if (n == 1)
  171. format = GFXFormatL16;
  172. else
  173. format = GFXFormatR16G16B16A16; // not sure if this is correct.
  174. bitmap->deleteImage();
  175. // actually allocate the bitmap space...
  176. bitmap->allocateBitmap(x, y,
  177. false, // don't extrude miplevels...
  178. format); // use determined format...
  179. U16* pBase = (U16*)bitmap->getBits();
  180. U32 rowBytes = bitmap->getByteSize();
  181. dMemcpy(pBase, data, rowBytes);
  182. stbi_image_free(data);
  183. return true;
  184. }
  185. }
  186. }
  187. if (ext.equal("hdr"))
  188. {
  189. // force load to 4 channel.
  190. float* data = stbi_loadf(path.getFullPath().c_str(), &x, &y, &n, 0);
  191. unsigned char* dataChar = stbi__hdr_to_ldr(data, x, y, n);
  192. bitmap->deleteImage();
  193. // actually allocate the bitmap space...
  194. bitmap->allocateBitmap(x, y,
  195. false,
  196. GFXFormatR8G8B8);
  197. U8* pBase = (U8*)bitmap->getBits();
  198. U32 rowBytes = x * y * n;
  199. dMemcpy(pBase, dataChar, rowBytes);
  200. //stbi_image_free(data);
  201. stbi_image_free(dataChar);
  202. return true;
  203. }
  204. unsigned char* data = stbi_load(path.getFullPath().c_str(), &x, &y, &n, channels);
  205. bitmap->deleteImage();
  206. GFXFormat format;
  207. switch (channels) {
  208. case 1:
  209. format = GFXFormatA8;
  210. break;
  211. case 2:
  212. format = GFXFormatA8L8;
  213. break;
  214. case 3:
  215. format = GFXFormatR8G8B8;
  216. break;
  217. case 4:
  218. format = GFXFormatR8G8B8A8;
  219. break;
  220. default:
  221. return false;
  222. }
  223. // actually allocate the bitmap space...
  224. bitmap->allocateBitmap(x, y,
  225. false, // don't extrude miplevels...
  226. format); // use determined format...
  227. U8* pBase = (U8*)bitmap->getBits();
  228. U32 rowBytes = bitmap->getByteSize();
  229. dMemcpy(pBase, data, rowBytes);
  230. stbi_image_free(data);
  231. // Check this bitmap for transparency
  232. if (channels == 4)
  233. bitmap->checkForTransparency();
  234. return true;
  235. }
  236. bool sReadStreamSTB(Stream& stream, GBitmap* bitmap, U32 len)
  237. {
  238. PROFILE_SCOPE(sReadStreamSTB);
  239. // only used for font at the moment.
  240. U8* data = new U8[len];
  241. stream.read(len, data);
  242. S32 width, height, comp = 0;
  243. unsigned char* pixelData = stbi_load_from_memory((const U8*)data, (int)len, &width, &height, &comp, 0);
  244. if (!pixelData)
  245. {
  246. const char* stbErr = stbi_failure_reason();
  247. if (!stbErr)
  248. stbErr = "Unknown Error!";
  249. Con::errorf("sReadStreamSTB Error: %s", stbErr);
  250. return false;
  251. }
  252. bitmap->deleteImage();
  253. //work out what format we need to use - todo floating point?
  254. GFXFormat fmt = GFXFormat_FIRST;
  255. switch (comp)
  256. {
  257. case 1: fmt = GFXFormatA8; break;
  258. case 2: fmt = GFXFormatA8L8; break; //todo check this
  259. case 3: fmt = GFXFormatR8G8B8; break;
  260. case 4: fmt = GFXFormatR8G8B8A8; break;
  261. }
  262. bitmap->allocateBitmap(width, height, false, fmt);
  263. U8* pBase = bitmap->getWritableBits(0);
  264. U32 rowBytes = bitmap->getByteSize();
  265. dMemcpy(pBase, pixelData, rowBytes);
  266. dFree(data);
  267. dFree(pixelData);
  268. return true;
  269. }
  270. /**
  271. * Write bitmap to an image file.
  272. *
  273. * @param[in] path Destination image file path. File name extension determines image format.
  274. * ".bmp" for Microsoft Bitmap.
  275. * ".hdr" for High Dynamic Range (HDR).
  276. * ".jpg" or ".jpeg" for Joint Photographic Experts Group (JPEG).
  277. * ".png" for Portable Network Graphics (PNG).
  278. * ".tga" for Truevision TGA (TARGA).
  279. *
  280. *
  281. * @param[in] bitmap Source bitmap to encode image from.
  282. * @param compressionLevel Image format specific compression level.
  283. * For JPEG sets the quality level percentage, range 0 to 100.
  284. * Not used for other image formats.
  285. */
  286. bool sWriteSTB(const Torque::Path& path, GBitmap* bitmap, U32 compressionLevel)
  287. {
  288. PROFILE_SCOPE(sWriteSTB);
  289. // get our data to be saved.
  290. U32 width = bitmap->getWidth();
  291. U32 height = bitmap->getHeight();
  292. U32 bytes = bitmap->getBytesPerPixel();
  293. GFXFormat format = bitmap->getFormat();
  294. String ext = path.getExtension();
  295. // we always have at least 1
  296. U32 comp = 1;
  297. if (format == GFXFormatR8G8B8)
  298. {
  299. comp = 3;
  300. }
  301. else if (format == GFXFormatR8G8B8A8 || format == GFXFormatR8G8B8X8 || format == GFXFormatR8G8B8A8_LINEAR_FORCE)
  302. {
  303. comp = 4;
  304. }
  305. if (ext.equal("png"))
  306. {
  307. stbi_write_png_compression_level = compressionLevel;
  308. if (stbi_write_png(path.getFullPath().c_str(), width, height, comp, bitmap->getWritableBits(), 0))
  309. return true;
  310. }
  311. if (ext.equal("tga"))
  312. {
  313. if (stbi_write_tga(path.getFullPath().c_str(), width, height, comp, bitmap->getWritableBits()))
  314. return true;
  315. }
  316. if (ext.equal("bmp"))
  317. {
  318. if (stbi_write_bmp(path.getFullPath().c_str(), width, height, comp, bitmap->getWritableBits()))
  319. return true;
  320. }
  321. if (ext.equal("jpg") || ext.equal("jpeg"))
  322. {
  323. if (stbi_write_jpg(path.getFullPath().c_str(), width, height, comp, bitmap->getWritableBits(), compressionLevel))
  324. return true;
  325. }
  326. if (ext.equal("hdr"))
  327. {
  328. if (stbi_write_hdr(path.getFullPath().c_str(), width, height, comp, (const F32*)bitmap->getWritableBits()))
  329. return true;
  330. }
  331. return false;
  332. }
  333. bool sWriteStreamSTB(const String& bmType, Stream& stream, GBitmap* bitmap, U32 compressionLevel)
  334. {
  335. PROFILE_SCOPE(sWriteStreamSTB);
  336. S32 width = bitmap->getWidth();
  337. S32 height = bitmap->getHeight();
  338. const U8* pPixelData = bitmap->getBits();
  339. S32 channels = bitmap->getBytesPerPixel();
  340. if (bmType == String("png"))
  341. {
  342. stbi_write_png_compression_level = compressionLevel;
  343. if (stbi_write_png_to_func(stbiWriteFunc, &stream, width, height, channels, pPixelData, width * channels))
  344. return true;
  345. }
  346. else if (bmType == String("tga"))
  347. {
  348. if (stbi_write_tga_to_func(stbiWriteFunc, &stream, width, height, channels, pPixelData))
  349. return true;
  350. }
  351. else if (bmType == String("bmp"))
  352. {
  353. if (stbi_write_bmp_to_func(stbiWriteFunc, &stream, width, height, channels, pPixelData))
  354. return true;
  355. }
  356. else if (bmType == String("jpg") || bmType == String("jpeg"))
  357. {
  358. if (stbi_write_jpg_to_func(stbiWriteFunc, &stream, width, height, channels, pPixelData, compressionLevel))
  359. return true;
  360. }
  361. else if (bmType == String("hdr"))
  362. {
  363. if (stbi_write_hdr_to_func(stbiWriteFunc, &stream, width, height, channels, (const F32*)pPixelData))
  364. return true;
  365. }
  366. return false;
  367. }
  368. struct DeferredPNGWriterData
  369. {
  370. S32 width = 0;
  371. S32 height = 0;
  372. S32 channels = 0;
  373. dsize_t offset = 0;
  374. U8* pPixelData = NULL;
  375. GFXFormat format;
  376. Stream* pStream = NULL;
  377. };
  378. DeferredPNGWriter::DeferredPNGWriter() :
  379. mData(NULL),
  380. mActive(false)
  381. {
  382. mData = new DeferredPNGWriterData();
  383. }
  384. DeferredPNGWriter::~DeferredPNGWriter()
  385. {
  386. if (mData)
  387. {
  388. SAFE_DELETE_ARRAY(mData->pPixelData);
  389. }
  390. SAFE_DELETE(mData);
  391. }
  392. bool DeferredPNGWriter::begin(GFXFormat format, S32 width, S32 height, Stream& stream)
  393. {
  394. // ONLY RGB bitmap writing supported at this time!
  395. AssertFatal(format == GFXFormatR8G8B8 ||
  396. format == GFXFormatR8G8B8A8 ||
  397. format == GFXFormatR8G8B8X8 ||
  398. format == GFXFormatA8 ||
  399. format == GFXFormatR5G6B5, "DeferredPNGWriter::begin: ONLY RGB bitmap writing supported at this time.");
  400. if (format != GFXFormatR8G8B8 &&
  401. format != GFXFormatR8G8B8A8 &&
  402. format != GFXFormatR8G8B8X8 &&
  403. format != GFXFormatA8 &&
  404. format != GFXFormatR5G6B5)
  405. {
  406. return false;
  407. }
  408. mData->pStream = &stream;
  409. mData->width = width;
  410. mData->height = height;
  411. mData->format = format;
  412. const size_t dataSize = GFXFormat_getByteSize(format) * width * height;
  413. mData->pPixelData = new U8[dataSize];
  414. mActive = true;
  415. return true;
  416. }
  417. void DeferredPNGWriter::append(GBitmap* bitmap, U32 rows)
  418. {
  419. AssertFatal(mActive, "Cannot append to an inactive DeferredPNGWriter!");
  420. if (mData->channels == 0)
  421. {
  422. mData->channels = bitmap->getBytesPerPixel();
  423. }
  424. const dsize_t dataChuckSize = bitmap->getByteSize();
  425. const U8* pSrcData = bitmap->getBits();
  426. U8* pDstData = mData->pPixelData + mData->offset;
  427. dMemcpy(pDstData, pSrcData, dataChuckSize);
  428. mData->offset += dataChuckSize;
  429. }
  430. void DeferredPNGWriter::end()
  431. {
  432. AssertFatal(mActive, "Cannot end an inactive DeferredPNGWriter!");
  433. stbi_write_png_to_func(stbiWriteFunc, mData->pStream, mData->width, mData->height, mData->channels, mData->pPixelData, mData->width * mData->channels);
  434. mActive = false;
  435. }