bitmapSTB.cpp 16 KB

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