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