image_loader_png.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /*************************************************************************/
  2. /* image_loader_png.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "image_loader_png.h"
  31. #include "core/os/os.h"
  32. #include "core/print_string.h"
  33. #include <string.h>
  34. void ImageLoaderPNG::_read_png_data(png_structp png_ptr, png_bytep data, png_size_t p_length) {
  35. FileAccess *f = (FileAccess *)png_get_io_ptr(png_ptr);
  36. f->get_buffer((uint8_t *)data, p_length);
  37. }
  38. /*
  39. png_structp png_ptr = png_create_read_struct_2
  40. (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr,
  41. user_error_fn, user_warning_fn, (png_voidp)
  42. user_mem_ptr, user_malloc_fn, user_free_fn);
  43. */
  44. static png_voidp _png_malloc_fn(png_structp png_ptr, png_size_t size) {
  45. return memalloc(size);
  46. }
  47. static void _png_free_fn(png_structp png_ptr, png_voidp ptr) {
  48. memfree(ptr);
  49. }
  50. static void _png_error_function(png_structp, png_const_charp text) {
  51. ERR_PRINT(text);
  52. }
  53. static void _png_warn_function(png_structp, png_const_charp text) {
  54. WARN_PRINT(text);
  55. }
  56. typedef void(PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  57. Error ImageLoaderPNG::_load_image(void *rf_up, png_rw_ptr p_func, Ref<Image> p_image) {
  58. png_structp png;
  59. png_infop info;
  60. //png = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, NULL, NULL);
  61. png = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, _png_error_function, _png_warn_function, (png_voidp)NULL,
  62. _png_malloc_fn, _png_free_fn);
  63. ERR_FAIL_COND_V(!png, ERR_OUT_OF_MEMORY);
  64. info = png_create_info_struct(png);
  65. if (!info) {
  66. png_destroy_read_struct(&png, NULL, NULL);
  67. ERR_PRINT("Out of Memory");
  68. return ERR_OUT_OF_MEMORY;
  69. }
  70. if (setjmp(png_jmpbuf(png))) {
  71. png_destroy_read_struct(&png, NULL, NULL);
  72. ERR_PRINT("PNG Corrupted");
  73. return ERR_FILE_CORRUPT;
  74. }
  75. png_set_read_fn(png, (void *)rf_up, p_func);
  76. png_uint_32 width, height;
  77. int depth, color;
  78. png_read_info(png, info);
  79. png_get_IHDR(png, info, &width, &height, &depth, &color, NULL, NULL, NULL);
  80. //https://svn.gov.pt/projects/ccidadao/repository/middleware-offline/trunk/_src/eidmw/FreeImagePTEiD/Source/FreeImage/PluginPNG.cpp
  81. //png_get_text(png,info,)
  82. /*
  83. printf("Image width:%i\n", width);
  84. printf("Image Height:%i\n", height);
  85. printf("Bit depth:%i\n", depth);
  86. printf("Color type:%i\n", color);
  87. */
  88. bool update_info = false;
  89. if (depth < 8) { //only bit dept 8 per channel is handled
  90. png_set_packing(png);
  91. update_info = true;
  92. };
  93. if (png_get_color_type(png, info) == PNG_COLOR_TYPE_PALETTE) {
  94. png_set_palette_to_rgb(png);
  95. update_info = true;
  96. }
  97. if (depth > 8) {
  98. png_set_strip_16(png);
  99. update_info = true;
  100. }
  101. if (png_get_valid(png, info, PNG_INFO_tRNS)) {
  102. //png_set_expand_gray_1_2_4_to_8(png);
  103. png_set_tRNS_to_alpha(png);
  104. update_info = true;
  105. }
  106. if (update_info) {
  107. png_read_update_info(png, info);
  108. png_get_IHDR(png, info, &width, &height, &depth, &color, NULL, NULL, NULL);
  109. }
  110. int components = 0;
  111. Image::Format fmt;
  112. switch (color) {
  113. case PNG_COLOR_TYPE_GRAY: {
  114. fmt = Image::FORMAT_L8;
  115. components = 1;
  116. } break;
  117. case PNG_COLOR_TYPE_GRAY_ALPHA: {
  118. fmt = Image::FORMAT_LA8;
  119. components = 2;
  120. } break;
  121. case PNG_COLOR_TYPE_RGB: {
  122. fmt = Image::FORMAT_RGB8;
  123. components = 3;
  124. } break;
  125. case PNG_COLOR_TYPE_RGB_ALPHA: {
  126. fmt = Image::FORMAT_RGBA8;
  127. components = 4;
  128. } break;
  129. default: {
  130. ERR_PRINT("INVALID PNG TYPE");
  131. png_destroy_read_struct(&png, &info, NULL);
  132. return ERR_UNAVAILABLE;
  133. } break;
  134. }
  135. //int rowsize = png_get_rowbytes(png, info);
  136. int rowsize = components * width;
  137. PoolVector<uint8_t> dstbuff;
  138. dstbuff.resize(rowsize * height);
  139. PoolVector<uint8_t>::Write dstbuff_write = dstbuff.write();
  140. uint8_t *data = dstbuff_write.ptr();
  141. uint8_t **row_p = memnew_arr(uint8_t *, height);
  142. for (unsigned int i = 0; i < height; i++) {
  143. row_p[i] = &data[components * width * i];
  144. }
  145. png_read_image(png, (png_bytep *)row_p);
  146. memdelete_arr(row_p);
  147. p_image->create(width, height, 0, fmt, dstbuff);
  148. png_destroy_read_struct(&png, &info, NULL);
  149. return OK;
  150. }
  151. Error ImageLoaderPNG::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) {
  152. Error err = _load_image(f, _read_png_data, p_image);
  153. f->close();
  154. return err;
  155. }
  156. void ImageLoaderPNG::get_recognized_extensions(List<String> *p_extensions) const {
  157. p_extensions->push_back("png");
  158. }
  159. struct PNGReadStatus {
  160. uint32_t offset;
  161. uint32_t size;
  162. const unsigned char *image;
  163. };
  164. static void user_read_data(png_structp png_ptr, png_bytep data, png_size_t p_length) {
  165. PNGReadStatus *rstatus;
  166. rstatus = (PNGReadStatus *)png_get_io_ptr(png_ptr);
  167. png_size_t to_read = MIN(p_length, rstatus->size - rstatus->offset);
  168. memcpy(data, &rstatus->image[rstatus->offset], to_read);
  169. rstatus->offset += to_read;
  170. if (to_read < p_length) {
  171. memset(&data[to_read], 0, p_length - to_read);
  172. }
  173. }
  174. static Ref<Image> _load_mem_png(const uint8_t *p_png, int p_size) {
  175. PNGReadStatus prs;
  176. prs.image = p_png;
  177. prs.offset = 0;
  178. prs.size = p_size;
  179. Ref<Image> img;
  180. img.instance();
  181. Error err = ImageLoaderPNG::_load_image(&prs, user_read_data, img);
  182. ERR_FAIL_COND_V(err, Ref<Image>());
  183. return img;
  184. }
  185. static Ref<Image> _lossless_unpack_png(const PoolVector<uint8_t> &p_data) {
  186. int len = p_data.size();
  187. ERR_FAIL_COND_V(len < 4, Ref<Image>());
  188. PoolVector<uint8_t>::Read r = p_data.read();
  189. ERR_FAIL_COND_V(r[0] != 'P' || r[1] != 'N' || r[2] != 'G' || r[3] != ' ', Ref<Image>());
  190. return _load_mem_png(&r[4], len - 4);
  191. }
  192. static void _write_png_data(png_structp png_ptr, png_bytep data, png_size_t p_length) {
  193. PoolVector<uint8_t> &v = *(PoolVector<uint8_t> *)png_get_io_ptr(png_ptr);
  194. int vs = v.size();
  195. v.resize(vs + p_length);
  196. PoolVector<uint8_t>::Write w = v.write();
  197. copymem(&w[vs], data, p_length);
  198. }
  199. static PoolVector<uint8_t> _lossless_pack_png(const Ref<Image> &p_image) {
  200. Ref<Image> img = p_image->duplicate();
  201. if (img->is_compressed())
  202. img->decompress();
  203. ERR_FAIL_COND_V(img->is_compressed(), PoolVector<uint8_t>());
  204. png_structp png_ptr;
  205. png_infop info_ptr;
  206. png_bytep *row_pointers;
  207. /* initialize stuff */
  208. png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
  209. ERR_FAIL_COND_V(!png_ptr, PoolVector<uint8_t>());
  210. info_ptr = png_create_info_struct(png_ptr);
  211. ERR_FAIL_COND_V(!info_ptr, PoolVector<uint8_t>());
  212. if (setjmp(png_jmpbuf(png_ptr))) {
  213. ERR_FAIL_V(PoolVector<uint8_t>());
  214. }
  215. PoolVector<uint8_t> ret;
  216. ret.push_back('P');
  217. ret.push_back('N');
  218. ret.push_back('G');
  219. ret.push_back(' ');
  220. png_set_write_fn(png_ptr, &ret, _write_png_data, NULL);
  221. /* write header */
  222. if (setjmp(png_jmpbuf(png_ptr))) {
  223. ERR_FAIL_V(PoolVector<uint8_t>());
  224. }
  225. int pngf = 0;
  226. int cs = 0;
  227. switch (img->get_format()) {
  228. case Image::FORMAT_L8: {
  229. pngf = PNG_COLOR_TYPE_GRAY;
  230. cs = 1;
  231. } break;
  232. case Image::FORMAT_LA8: {
  233. pngf = PNG_COLOR_TYPE_GRAY_ALPHA;
  234. cs = 2;
  235. } break;
  236. case Image::FORMAT_RGB8: {
  237. pngf = PNG_COLOR_TYPE_RGB;
  238. cs = 3;
  239. } break;
  240. case Image::FORMAT_RGBA8: {
  241. pngf = PNG_COLOR_TYPE_RGB_ALPHA;
  242. cs = 4;
  243. } break;
  244. default: {
  245. if (img->detect_alpha()) {
  246. img->convert(Image::FORMAT_RGBA8);
  247. pngf = PNG_COLOR_TYPE_RGB_ALPHA;
  248. cs = 4;
  249. } else {
  250. img->convert(Image::FORMAT_RGB8);
  251. pngf = PNG_COLOR_TYPE_RGB;
  252. cs = 3;
  253. }
  254. }
  255. }
  256. int w = img->get_width();
  257. int h = img->get_height();
  258. png_set_IHDR(png_ptr, info_ptr, w, h,
  259. 8, pngf, PNG_INTERLACE_NONE,
  260. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  261. png_write_info(png_ptr, info_ptr);
  262. /* write bytes */
  263. if (setjmp(png_jmpbuf(png_ptr))) {
  264. ERR_FAIL_V(PoolVector<uint8_t>());
  265. }
  266. PoolVector<uint8_t>::Read r = img->get_data().read();
  267. row_pointers = (png_bytep *)memalloc(sizeof(png_bytep) * h);
  268. for (int i = 0; i < h; i++) {
  269. row_pointers[i] = (png_bytep)&r[i * w * cs];
  270. }
  271. png_write_image(png_ptr, row_pointers);
  272. memfree(row_pointers);
  273. /* end write */
  274. if (setjmp(png_jmpbuf(png_ptr))) {
  275. ERR_FAIL_V(PoolVector<uint8_t>());
  276. }
  277. png_write_end(png_ptr, NULL);
  278. return ret;
  279. }
  280. ImageLoaderPNG::ImageLoaderPNG() {
  281. Image::_png_mem_loader_func = _load_mem_png;
  282. Image::lossless_unpacker = _lossless_unpack_png;
  283. Image::lossless_packer = _lossless_pack_png;
  284. }