cute_png.h 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852
  1. /*
  2. ------------------------------------------------------------------------------
  3. Licensing information can be found at the end of the file.
  4. ------------------------------------------------------------------------------
  5. cute_png.h - v1.05
  6. To create implementation (the function definitions)
  7. #define CUTE_PNG_IMPLEMENTATION
  8. in *one* C/CPP file (translation unit) that includes this file
  9. SUMMARY:
  10. This header wraps some very nice functions by Richard Mitton from his
  11. tigr (Tiny Graphics) library, with some additional features and small
  12. bug-fixes.
  13. Revision history:
  14. 1.00 (12/23/2016) initial release
  15. 1.01 (03/08/2017) tRNS chunk support for paletted images
  16. 1.02 (10/23/2017) support for explicitly loading paletted png images
  17. 1.03 (11/12/2017) construct atlas in memory
  18. 1.04 (08/23/2018) various bug fixes for filter and word decoder
  19. added `cp_load_blank`
  20. 1.05 (11/10/2022) added `cp_save_png_to_memory`
  21. EXAMPLES:
  22. Loading a PNG from disk, then freeing it
  23. cp_image_t img = cp_load_png("images/pic.png");
  24. ...
  25. free(img.pix);
  26. CUTE_PNG_MEMSET(&img, 0, sizeof(img));
  27. Loading a PNG from memory, then freeing it
  28. cp_image_t img = cp_load_png_mem(memory, sizeof(memory));
  29. ...
  30. free(img.pix);
  31. CUTE_PNG_MEMSET(&img, 0, sizeof(img));
  32. Saving a PNG to disk
  33. cp_save_png("images/example.png", &img);
  34. // img is just a raw RGBA buffer, and can come from anywhere,
  35. // not only from cp_load*** functions
  36. Creating a texture atlas in memory
  37. int w = 1024;
  38. int h = 1024;
  39. cp_atlas_image_t* imgs_out = (cp_atlas_image_t*)malloc(sizeof(cp_atlas_image_t) * my_png_count);
  40. cp_image_t atlas_img = cp_make_atlas(w, int h, my_png_array, my_png_count, imgs_out);
  41. // just pass an array of pointers to images along with the image count. Make sure to also
  42. // provide an array of `cp_atlas_image_t` for `cp_make_atlas` to output important UV info for the
  43. // images that fit into the atlas.
  44. Using the default atlas saver
  45. int errors = cp_default_save_atlas("atlas.png", "atlas.txt", atlas_img, atlas_imgs, img_count, names_of_all_images ? names_of_all_images : 0);
  46. if (errors) { ... }
  47. // Atlas info (like uv coordinates) are in "atlas.txt", and the image was writen to "atlas.png".
  48. // atlas_imgs was an array of `cp_atlas_image_t` from the `cp_make_atlas` function.
  49. Inflating a DEFLATE block (decompressing memory stored in DEFLATE format)
  50. cp_inflate(in, in_bytes, out, out_bytes);
  51. // this function requires knowledge of the un-compressed size
  52. // does *not* do any internal realloc! Will return errors if an
  53. // attempt to overwrite the out buffer is made
  54. CUSTOMIZATION
  55. There are various macros in this header you can customize by defining them before
  56. including cute_png.h. Simply define one to override the default behavior.
  57. CUTE_PNG_ALLOCA
  58. CUTE_PNG_ALLOC
  59. CUTE_PNG_FREE
  60. CUTE_PNG_CALLOC
  61. CUTE_PNG_REALLOC
  62. CUTE_PNG_MEMCPY
  63. CUTE_PNG_MEMCMP
  64. CUTE_PNG_MEMSET
  65. CUTE_PNG_ASSERT
  66. CUTE_PNG_FPRINTF
  67. CUTE_PNG_SEEK_SET
  68. CUTE_PNG_SEEK_END
  69. CUTE_PNG_FILE
  70. CUTE_PNG_FOPEN
  71. CUTE_PNG_FSEEK
  72. CUTE_PNG_FREAD
  73. CUTE_PNG_FTELL
  74. CUTE_PNG_FWRITE
  75. CUTE_PNG_FCLOSE
  76. CUTE_PNG_FERROR
  77. CUTE_PNG_ATLAS_MUST_FIT
  78. CUTE_PNG_ATLAS_FLIP_Y_AXIS_FOR_UV
  79. CUTE_PNG_ATLAS_EMPTY_COLOR
  80. */
  81. /*
  82. Contributors:
  83. Zachary Carter 1.01 - bug catch for tRNS chunk in paletted images
  84. Dennis Korpel 1.03 - fix some pointer/memory related bugs
  85. Dennis Korpel 1.04 - fix for filter on first row of pixels
  86. */
  87. #if !defined(CUTE_PNG_H)
  88. #ifdef _WIN32
  89. #if !defined(_CRT_SECURE_NO_WARNINGS)
  90. #define _CRT_SECURE_NO_WARNINGS
  91. #endif
  92. #endif
  93. #ifndef CUTE_PNG_ATLAS_MUST_FIT
  94. #define CUTE_PNG_ATLAS_MUST_FIT 1 // returns error from cp_make_atlas if *any* input image does not fit
  95. #endif // CUTE_PNG_ATLAS_MUST_FIT
  96. #ifndef CUTE_PNG_ATLAS_FLIP_Y_AXIS_FOR_UV
  97. #define CUTE_PNG_ATLAS_FLIP_Y_AXIS_FOR_UV 1 // flips output uv coordinate's y. Can be useful to "flip image on load"
  98. #endif // CUTE_PNG_ATLAS_FLIP_Y_AXIS_FOR_UV
  99. #ifndef CUTE_PNG_ATLAS_EMPTY_COLOR
  100. #define CUTE_PNG_ATLAS_EMPTY_COLOR 0x000000FF // the fill color for empty areas in a texture atlas (RGBA)
  101. #endif // CUTE_PNG_ATLAS_EMPTY_COLOR
  102. #include <stdint.h>
  103. #include <limits.h>
  104. typedef struct cp_pixel_t cp_pixel_t;
  105. typedef struct cp_image_t cp_image_t;
  106. typedef struct cp_indexed_image_t cp_indexed_image_t;
  107. typedef struct cp_atlas_image_t cp_atlas_image_t;
  108. // Read this in the event of errors from any function
  109. extern const char* cp_error_reason;
  110. // return 1 for success, 0 for failures
  111. int cp_inflate(void* in, int in_bytes, void* out, int out_bytes);
  112. int cp_save_png(const char* file_name, const cp_image_t* img);
  113. typedef struct cp_saved_png_t
  114. {
  115. int size; // Size of the `data` buffer.
  116. void* data; // Pointer to the saved png in memory.
  117. // NULL if something went wrong.
  118. // Call CUTE_PNG_FREE on `data` when done.
  119. } cp_saved_png_t;
  120. // Saves a png file to memory.
  121. // Call CUTE_PNG_FREE on .data when done.
  122. cp_saved_png_t cp_save_png_to_memory(const cp_image_t* img);
  123. // Constructs an atlas image in-memory. The atlas pixels are stored in the returned image. free the pixels
  124. // when done with them. The user must provide an array of cp_atlas_image_t for the `imgs` param. `imgs` holds
  125. // information about uv coordinates for an associated image in the `pngs` array. Output image has NULL
  126. // pixels buffer in the event of errors.
  127. cp_image_t cp_make_atlas(int atlasWidth, int atlasHeight, const cp_image_t* pngs, int png_count, cp_atlas_image_t* imgs_out);
  128. // A decent "default" function, ready to use out-of-the-box. Saves out an easy to parse text formatted info file
  129. // along with an atlas image. `names` param can be optionally NULL.
  130. int cp_default_save_atlas(const char* out_path_image, const char* out_path_atlas_txt, const cp_image_t* atlas, const cp_atlas_image_t* imgs, int img_count, const char** names);
  131. // these two functions return cp_image_t::pix as 0 in event of errors
  132. // call free on cp_image_t::pix when done, or call cp_free_png
  133. cp_image_t cp_load_png(const char *file_name);
  134. cp_image_t cp_load_png_mem(const void *png_data, int png_length);
  135. cp_image_t cp_load_blank(int w, int h); // Alloc's pixels, but `pix` memory is uninitialized.
  136. void cp_free_png(cp_image_t* img);
  137. void cp_flip_image_horizontal(cp_image_t* img);
  138. // Reads the w/h of the png without doing any other decompression or parsing.
  139. void cp_load_png_wh(const void* png_data, int png_length, int* w, int* h);
  140. // loads indexed (paletted) pngs, but does not depalette the image into RGBA pixels
  141. // these two functions return cp_indexed_image_t::pix as 0 in event of errors
  142. // call free on cp_indexed_image_t::pix when done, or call cp_free_indexed_png
  143. cp_indexed_image_t cp_load_indexed_png(const char* file_name);
  144. cp_indexed_image_t cp_load_indexed_png_mem(const void *png_data, int png_length);
  145. void cp_free_indexed_png(cp_indexed_image_t* img);
  146. // converts paletted image into a standard RGBA image
  147. // call free on cp_image_t::pix when done
  148. cp_image_t cp_depallete_indexed_image(cp_indexed_image_t* img);
  149. // Pre-process the pixels to transform the image data to a premultiplied alpha format.
  150. // Resource: http://www.essentialmath.com/GDC2015/VanVerth_Jim_DoingMathwRGB.pdf
  151. void cp_premultiply(cp_image_t* img);
  152. struct cp_pixel_t
  153. {
  154. uint8_t r;
  155. uint8_t g;
  156. uint8_t b;
  157. uint8_t a;
  158. };
  159. struct cp_image_t
  160. {
  161. int w;
  162. int h;
  163. cp_pixel_t* pix;
  164. };
  165. struct cp_indexed_image_t
  166. {
  167. int w;
  168. int h;
  169. uint8_t* pix;
  170. uint8_t palette_len;
  171. cp_pixel_t palette[256];
  172. };
  173. struct cp_atlas_image_t
  174. {
  175. int img_index; // index into the `imgs` array
  176. int w, h; // pixel w/h of original image
  177. float minx, miny; // u coordinate
  178. float maxx, maxy; // v coordinate
  179. int fit; // non-zero if image fit and was placed into the atlas
  180. };
  181. #define CUTE_PNG_H
  182. #endif
  183. #ifdef CUTE_PNG_IMPLEMENTATION
  184. #ifndef CUTE_PNG_IMPLEMENTATION_ONCE
  185. #define CUTE_PNG_IMPLEMENTATION_ONCE
  186. #if !defined(CUTE_PNG_ALLOCA)
  187. #define CUTE_PNG_ALLOCA alloca
  188. #ifdef _WIN32
  189. #include <malloc.h>
  190. #elif defined(__linux__)
  191. #include <alloca.h>
  192. #endif
  193. #endif
  194. #if !defined(CUTE_PNG_ALLOC)
  195. #include <stdlib.h>
  196. #define CUTE_PNG_ALLOC malloc
  197. #endif
  198. #if !defined(CUTE_PNG_FREE)
  199. #include <stdlib.h>
  200. #define CUTE_PNG_FREE free
  201. #endif
  202. #if !defined(CUTE_PNG_CALLOC)
  203. #include <stdlib.h>
  204. #define CUTE_PNG_CALLOC calloc
  205. #endif
  206. #if !defined(CUTE_PNG_REALLOC)
  207. #include <stdlib.h>
  208. #define CUTE_PNG_REALLOC realloc
  209. #endif
  210. #if !defined(CUTE_PNG_MEMCPY)
  211. #include <string.h>
  212. #define CUTE_PNG_MEMCPY memcpy
  213. #endif
  214. #if !defined(CUTE_PNG_MEMCMP)
  215. #include <string.h>
  216. #define CUTE_PNG_MEMCMP memcmp
  217. #endif
  218. #if !defined(CUTE_PNG_MEMSET)
  219. #include <string.h>
  220. #define CUTE_PNG_MEMSET memset
  221. #endif
  222. #if !defined(CUTE_PNG_ASSERT)
  223. #include <assert.h>
  224. #define CUTE_PNG_ASSERT assert
  225. #endif
  226. #if !defined(CUTE_PNG_FPRINTF)
  227. #include <stdio.h>
  228. #define CUTE_PNG_FPRINTF fprintf
  229. #endif
  230. #if !defined(CUTE_PNG_SEEK_SET)
  231. #include <stdio.h>
  232. #define CUTE_PNG_SEEK_SET SEEK_SET
  233. #endif
  234. #if !defined(CUTE_PNG_SEEK_END)
  235. #include <stdio.h>
  236. #define CUTE_PNG_SEEK_END SEEK_END
  237. #endif
  238. #if !defined(CUTE_PNG_FILE)
  239. #include <stdio.h>
  240. #define CUTE_PNG_FILE FILE
  241. #endif
  242. #if !defined(CUTE_PNG_FOPEN)
  243. #include <stdio.h>
  244. #define CUTE_PNG_FOPEN fopen
  245. #endif
  246. #if !defined(CUTE_PNG_FSEEK)
  247. #include <stdio.h>
  248. #define CUTE_PNG_FSEEK fseek
  249. #endif
  250. #if !defined(CUTE_PNG_FREAD)
  251. #include <stdio.h>
  252. #define CUTE_PNG_FREAD fread
  253. #endif
  254. #if !defined(CUTE_PNG_FTELL)
  255. #include <stdio.h>
  256. #define CUTE_PNG_FTELL ftell
  257. #endif
  258. #if !defined(CUTE_PNG_FWRITE)
  259. #include <stdio.h>
  260. #define CUTE_PNG_FWRITE fwrite
  261. #endif
  262. #if !defined(CUTE_PNG_FCLOSE)
  263. #include <stdio.h>
  264. #define CUTE_PNG_FCLOSE fclose
  265. #endif
  266. #if !defined(CUTE_PNG_FERROR)
  267. #include <stdio.h>
  268. #define CUTE_PNG_FERROR ferror
  269. #endif
  270. static cp_pixel_t cp_make_pixel_a(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
  271. {
  272. cp_pixel_t p;
  273. p.r = r; p.g = g; p.b = b; p.a = a;
  274. return p;
  275. }
  276. static cp_pixel_t cp_make_pixel(uint8_t r, uint8_t g, uint8_t b)
  277. {
  278. cp_pixel_t p;
  279. p.r = r; p.g = g; p.b = b; p.a = 0xFF;
  280. return p;
  281. }
  282. const char* cp_error_reason;
  283. #define CUTE_PNG_FAIL() do { goto cp_err; } while (0)
  284. #define CUTE_PNG_CHECK(X, Y) do { if (!(X)) { cp_error_reason = Y; CUTE_PNG_FAIL(); } } while (0)
  285. #define CUTE_PNG_CALL(X) do { if (!(X)) goto cp_err; } while (0)
  286. #define CUTE_PNG_LOOKUP_BITS 9
  287. #define CUTE_PNG_LOOKUP_COUNT (1 << CUTE_PNG_LOOKUP_BITS)
  288. #define CUTE_PNG_LOOKUP_MASK (CUTE_PNG_LOOKUP_COUNT - 1)
  289. #define CUTE_PNG_DEFLATE_MAX_BITLEN 15
  290. // DEFLATE tables from RFC 1951
  291. uint8_t cp_fixed_table[288 + 32] = {
  292. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  293. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  294. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
  295. 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
  296. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
  297. }; // 3.2.6
  298. uint8_t cp_permutation_order[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; // 3.2.7
  299. uint8_t cp_len_extra_bits[29 + 2] = { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0, 0,0 }; // 3.2.5
  300. uint32_t cp_len_base[29 + 2] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 0,0 }; // 3.2.5
  301. uint8_t cp_dist_extra_bits[30 + 2] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13, 0,0 }; // 3.2.5
  302. uint32_t cp_dist_base[30 + 2] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 0,0 }; // 3.2.5
  303. typedef struct cp_state_t
  304. {
  305. uint64_t bits;
  306. int count;
  307. uint32_t* words;
  308. int word_count;
  309. int word_index;
  310. int bits_left;
  311. int final_word_available;
  312. uint32_t final_word;
  313. char* out;
  314. char* out_end;
  315. char* begin;
  316. uint16_t lookup[CUTE_PNG_LOOKUP_COUNT];
  317. uint32_t lit[288];
  318. uint32_t dst[32];
  319. uint32_t len[19];
  320. uint32_t nlit;
  321. uint32_t ndst;
  322. uint32_t nlen;
  323. } cp_state_t;
  324. static int cp_would_overflow(cp_state_t* s, int num_bits)
  325. {
  326. return (s->bits_left + s->count) - num_bits < 0;
  327. }
  328. static char* cp_ptr(cp_state_t* s)
  329. {
  330. CUTE_PNG_ASSERT(!(s->bits_left & 7));
  331. return (char*)(s->words + s->word_index) - (s->count / 8);
  332. }
  333. static uint64_t cp_peak_bits(cp_state_t* s, int num_bits_to_read)
  334. {
  335. if (s->count < num_bits_to_read)
  336. {
  337. if (s->word_index < s->word_count)
  338. {
  339. uint32_t word = s->words[s->word_index++];
  340. s->bits |= (uint64_t)word << s->count;
  341. s->count += 32;
  342. CUTE_PNG_ASSERT(s->word_index <= s->word_count);
  343. }
  344. else if (s->final_word_available)
  345. {
  346. uint32_t word = s->final_word;
  347. s->bits |= (uint64_t)word << s->count;
  348. s->count += s->bits_left;
  349. s->final_word_available = 0;
  350. }
  351. }
  352. return s->bits;
  353. }
  354. static uint32_t cp_consume_bits(cp_state_t* s, int num_bits_to_read)
  355. {
  356. CUTE_PNG_ASSERT(s->count >= num_bits_to_read);
  357. uint32_t bits = s->bits & (((uint64_t)1 << num_bits_to_read) - 1);
  358. s->bits >>= num_bits_to_read;
  359. s->count -= num_bits_to_read;
  360. s->bits_left -= num_bits_to_read;
  361. return bits;
  362. }
  363. static uint32_t cp_read_bits(cp_state_t* s, int num_bits_to_read)
  364. {
  365. CUTE_PNG_ASSERT(num_bits_to_read <= 32);
  366. CUTE_PNG_ASSERT(num_bits_to_read >= 0);
  367. CUTE_PNG_ASSERT(s->bits_left > 0);
  368. CUTE_PNG_ASSERT(s->count <= 64);
  369. CUTE_PNG_ASSERT(!cp_would_overflow(s, num_bits_to_read));
  370. cp_peak_bits(s, num_bits_to_read);
  371. uint32_t bits = cp_consume_bits(s, num_bits_to_read);
  372. return bits;
  373. }
  374. static char* cp_read_file_to_memory(const char* path, int* size)
  375. {
  376. char* data = 0;
  377. CUTE_PNG_FILE* fp = CUTE_PNG_FOPEN(path, "rb");
  378. int sizeNum = 0;
  379. if (fp)
  380. {
  381. CUTE_PNG_FSEEK(fp, 0, CUTE_PNG_SEEK_END);
  382. sizeNum = CUTE_PNG_FTELL(fp);
  383. CUTE_PNG_FSEEK(fp, 0, CUTE_PNG_SEEK_SET);
  384. data = (char*)CUTE_PNG_ALLOC(sizeNum + 1);
  385. CUTE_PNG_FREAD(data, sizeNum, 1, fp);
  386. data[sizeNum] = 0;
  387. CUTE_PNG_FCLOSE(fp);
  388. }
  389. if (size) *size = sizeNum;
  390. return data;
  391. }
  392. static uint32_t cp_rev16(uint32_t a)
  393. {
  394. a = ((a & 0xAAAA) >> 1) | ((a & 0x5555) << 1);
  395. a = ((a & 0xCCCC) >> 2) | ((a & 0x3333) << 2);
  396. a = ((a & 0xF0F0) >> 4) | ((a & 0x0F0F) << 4);
  397. a = ((a & 0xFF00) >> 8) | ((a & 0x00FF) << 8);
  398. return a;
  399. }
  400. // RFC 1951 section 3.2.2
  401. static int cp_build(cp_state_t* s, uint32_t* tree, uint8_t* lens, int sym_count)
  402. {
  403. int n, codes[16], first[16], counts[16] = { 0 };
  404. // Frequency count
  405. for (n = 0; n < sym_count; n++) counts[lens[n]]++;
  406. // Distribute codes
  407. counts[0] = codes[0] = first[0] = 0;
  408. for (n = 1; n <= 15; ++n)
  409. {
  410. codes[n] = (codes[n - 1] + counts[n - 1]) << 1;
  411. first[n] = first[n - 1] + counts[n - 1];
  412. }
  413. if (s) CUTE_PNG_MEMSET(s->lookup, 0, sizeof(s->lookup));
  414. for (int i = 0; i < sym_count; ++i)
  415. {
  416. int len = lens[i];
  417. if (len != 0)
  418. {
  419. CUTE_PNG_ASSERT(len < 16);
  420. uint32_t code = codes[len]++;
  421. uint32_t slot = first[len]++;
  422. tree[slot] = (code << (32 - len)) | (i << 4) | len;
  423. if (s && len <= CUTE_PNG_LOOKUP_BITS)
  424. {
  425. int j = cp_rev16(code) >> (16 - len);
  426. while (j < (1 << CUTE_PNG_LOOKUP_BITS))
  427. {
  428. s->lookup[j] = (uint16_t)((len << CUTE_PNG_LOOKUP_BITS) | i);
  429. j += (1 << len);
  430. }
  431. }
  432. }
  433. }
  434. int max_index = first[15];
  435. return max_index;
  436. }
  437. static int cp_stored(cp_state_t* s)
  438. {
  439. char* p;
  440. // 3.2.3
  441. // skip any remaining bits in current partially processed byte
  442. cp_read_bits(s, s->count & 7);
  443. // 3.2.4
  444. // read LEN and NLEN, should complement each other
  445. uint16_t LEN = (uint16_t)cp_read_bits(s, 16);
  446. uint16_t NLEN = (uint16_t)cp_read_bits(s, 16);
  447. CUTE_PNG_CHECK(LEN == (uint16_t)(~NLEN), "Failed to find LEN and NLEN as complements within stored (uncompressed) stream.");
  448. CUTE_PNG_CHECK(s->bits_left / 8 <= (int)LEN, "Stored block extends beyond end of input stream.");
  449. p = cp_ptr(s);
  450. CUTE_PNG_MEMCPY(s->out, p, LEN);
  451. s->out += LEN;
  452. return 1;
  453. cp_err:
  454. return 0;
  455. }
  456. // 3.2.6
  457. static int cp_fixed(cp_state_t* s)
  458. {
  459. s->nlit = cp_build(s, s->lit, cp_fixed_table, 288);
  460. s->ndst = cp_build(0, s->dst, cp_fixed_table + 288, 32);
  461. return 1;
  462. }
  463. static int cp_decode(cp_state_t* s, uint32_t* tree, int hi)
  464. {
  465. uint64_t bits = cp_peak_bits(s, 16);
  466. uint32_t search = (cp_rev16((uint32_t)bits) << 16) | 0xFFFF;
  467. int lo = 0;
  468. while (lo < hi)
  469. {
  470. int guess = (lo + hi) >> 1;
  471. if (search < tree[guess]) hi = guess;
  472. else lo = guess + 1;
  473. }
  474. uint32_t key = tree[lo - 1];
  475. uint32_t len = (32 - (key & 0xF));
  476. CUTE_PNG_ASSERT((search >> len) == (key >> len));
  477. int code = cp_consume_bits(s, key & 0xF);
  478. (void)code;
  479. return (key >> 4) & 0xFFF;
  480. }
  481. // 3.2.7
  482. static int cp_dynamic(cp_state_t* s)
  483. {
  484. uint8_t lenlens[19] = { 0 };
  485. int nlit = 257 + cp_read_bits(s, 5);
  486. int ndst = 1 + cp_read_bits(s, 5);
  487. int nlen = 4 + cp_read_bits(s, 4);
  488. for (int i = 0 ; i < nlen; ++i)
  489. lenlens[cp_permutation_order[i]] = (uint8_t)cp_read_bits(s, 3);
  490. // Build the tree for decoding code lengths
  491. s->nlen = cp_build(0, s->len, lenlens, 19);
  492. uint8_t lens[288 + 32];
  493. for (int n = 0; n < nlit + ndst;)
  494. {
  495. int sym = cp_decode(s, s->len, s->nlen);
  496. switch (sym)
  497. {
  498. case 16: for (int i = 3 + cp_read_bits(s, 2); i; --i, ++n) lens[n] = lens[n - 1]; break;
  499. case 17: for (int i = 3 + cp_read_bits(s, 3); i; --i, ++n) lens[n] = 0; break;
  500. case 18: for (int i = 11 + cp_read_bits(s, 7); i; --i, ++n) lens[n] = 0; break;
  501. default: lens[n++] = (uint8_t)sym; break;
  502. }
  503. }
  504. s->nlit = cp_build(s, s->lit, lens, nlit);
  505. s->ndst = cp_build(0, s->dst, lens + nlit, ndst);
  506. return 1;
  507. }
  508. // 3.2.3
  509. static int cp_block(cp_state_t* s)
  510. {
  511. while (1)
  512. {
  513. int symbol = cp_decode(s, s->lit, s->nlit);
  514. if (symbol < 256)
  515. {
  516. CUTE_PNG_CHECK(s->out + 1 <= s->out_end, "Attempted to overwrite out buffer while outputting a symbol.");
  517. *s->out = (char)symbol;
  518. s->out += 1;
  519. }
  520. else if (symbol > 256)
  521. {
  522. symbol -= 257;
  523. int length = cp_read_bits(s, cp_len_extra_bits[symbol]) + cp_len_base[symbol];
  524. int distance_symbol = cp_decode(s, s->dst, s->ndst);
  525. int backwards_distance = cp_read_bits(s, cp_dist_extra_bits[distance_symbol]) + cp_dist_base[distance_symbol];
  526. CUTE_PNG_CHECK(s->out - backwards_distance >= s->begin, "Attempted to write before out buffer (invalid backwards distance).");
  527. CUTE_PNG_CHECK(s->out + length <= s->out_end, "Attempted to overwrite out buffer while outputting a string.");
  528. char* src = s->out - backwards_distance;
  529. char* dst = s->out;
  530. s->out += length;
  531. switch (backwards_distance)
  532. {
  533. case 1: // very common in images
  534. CUTE_PNG_MEMSET(dst, *src, length);
  535. break;
  536. default: while (length--) *dst++ = *src++;
  537. }
  538. }
  539. else break;
  540. }
  541. return 1;
  542. cp_err:
  543. return 0;
  544. }
  545. // 3.2.3
  546. int cp_inflate(void* in, int in_bytes, void* out, int out_bytes)
  547. {
  548. cp_state_t* s = (cp_state_t*)CUTE_PNG_CALLOC(1, sizeof(cp_state_t));
  549. s->bits = 0;
  550. s->count = 0;
  551. s->word_index = 0;
  552. s->bits_left = in_bytes * 8;
  553. // s->words is the in-pointer rounded up to a multiple of 4
  554. int first_bytes = (int) ((( (size_t) in + 3) & ~3) - (size_t) in);
  555. s->words = (uint32_t*)((char*)in + first_bytes);
  556. s->word_count = (in_bytes - first_bytes) / 4;
  557. int last_bytes = ((in_bytes - first_bytes) & 3);
  558. for (int i = 0; i < first_bytes; ++i)
  559. s->bits |= (uint64_t)(((uint8_t*)in)[i]) << (i * 8);
  560. s->final_word_available = last_bytes ? 1 : 0;
  561. s->final_word = 0;
  562. for(int i = 0; i < last_bytes; i++)
  563. s->final_word |= ((uint8_t*)in)[in_bytes - last_bytes+i] << (i * 8);
  564. s->count = first_bytes * 8;
  565. s->out = (char*)out;
  566. s->out_end = s->out + out_bytes;
  567. s->begin = (char*)out;
  568. int count = 0;
  569. int bfinal;
  570. do
  571. {
  572. bfinal = cp_read_bits(s, 1);
  573. int btype = cp_read_bits(s, 2);
  574. switch (btype)
  575. {
  576. case 0: CUTE_PNG_CALL(cp_stored(s)); break;
  577. case 1: cp_fixed(s); CUTE_PNG_CALL(cp_block(s)); break;
  578. case 2: cp_dynamic(s); CUTE_PNG_CALL(cp_block(s)); break;
  579. case 3: CUTE_PNG_CHECK(0, "Detected unknown block type within input stream.");
  580. }
  581. ++count;
  582. }
  583. while (!bfinal);
  584. CUTE_PNG_FREE(s);
  585. return 1;
  586. cp_err:
  587. CUTE_PNG_FREE(s);
  588. return 0;
  589. }
  590. static uint8_t cp_paeth(uint8_t a, uint8_t b, uint8_t c)
  591. {
  592. int p = a + b - c;
  593. int pa = abs(p - a);
  594. int pb = abs(p - b);
  595. int pc = abs(p - c);
  596. return (pa <= pb && pa <= pc) ? a : (pb <= pc) ? b : c;
  597. }
  598. typedef struct cp_save_png_data_t
  599. {
  600. uint32_t crc;
  601. uint32_t adler;
  602. uint32_t bits;
  603. uint32_t prev;
  604. uint32_t runlen;
  605. int buflen;
  606. int bufcap;
  607. char* buffer;
  608. } cp_save_png_data_t;
  609. uint32_t CP_CRC_TABLE[] = {
  610. 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
  611. 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c
  612. };
  613. static void cp_put8(cp_save_png_data_t* s, uint32_t a)
  614. {
  615. if (s->buflen >= s->bufcap)
  616. {
  617. s->bufcap *= 2;
  618. s->buffer = (char*)CUTE_PNG_REALLOC(s->buffer, s->bufcap);
  619. }
  620. s->buffer[s->buflen++] = a;
  621. s->crc = (s->crc >> 4) ^ CP_CRC_TABLE[(s->crc & 15) ^ (a & 15)];
  622. s->crc = (s->crc >> 4) ^ CP_CRC_TABLE[(s->crc & 15) ^ (a >> 4)];
  623. }
  624. static void cp_update_adler(cp_save_png_data_t* s, uint32_t v)
  625. {
  626. uint32_t s1 = s->adler & 0xFFFF;
  627. uint32_t s2 = (s->adler >> 16) & 0xFFFF;
  628. s1 = (s1 + v) % 65521;
  629. s2 = (s2 + s1) % 65521;
  630. s->adler = (s2 << 16) + s1;
  631. }
  632. static void cp_put32(cp_save_png_data_t* s, uint32_t v)
  633. {
  634. cp_put8(s, (v >> 24) & 0xFF);
  635. cp_put8(s, (v >> 16) & 0xFF);
  636. cp_put8(s, (v >> 8) & 0xFF);
  637. cp_put8(s, v & 0xFF);
  638. }
  639. static void cp_put_bits(cp_save_png_data_t* s, uint32_t data, uint32_t bitcount)
  640. {
  641. while (bitcount--)
  642. {
  643. uint32_t prev = s->bits;
  644. s->bits = (s->bits >> 1) | ((data & 1) << 7);
  645. data >>= 1;
  646. if (prev & 1)
  647. {
  648. cp_put8(s, s->bits);
  649. s->bits = 0x80;
  650. }
  651. }
  652. }
  653. static void cp_put_bitsr(cp_save_png_data_t* s, uint32_t data, uint32_t bitcount)
  654. {
  655. while (bitcount--)
  656. cp_put_bits(s, data >> bitcount, 1);
  657. }
  658. static void cp_begin_chunk(cp_save_png_data_t* s, const char* id, uint32_t len)
  659. {
  660. cp_put32(s, len);
  661. s->crc = 0xFFFFFFFF;
  662. cp_put8(s, (unsigned char)id[0]);
  663. cp_put8(s, (unsigned char)id[1]);
  664. cp_put8(s, (unsigned char)id[2]);
  665. cp_put8(s, (unsigned char)id[3]);
  666. }
  667. static void cp_encode_literal(cp_save_png_data_t* s, uint32_t v)
  668. {
  669. // Encode a literal/length using the built-in tables.
  670. // Could do better with a custom table but whatever.
  671. if (v < 144) cp_put_bitsr(s, 0x030 + v - 0, 8);
  672. else if (v < 256) cp_put_bitsr(s, 0x190 + v - 144, 9);
  673. else if (v < 280) cp_put_bitsr(s, 0x000 + v - 256, 7);
  674. else cp_put_bitsr(s, 0x0c0 + v - 280, 8);
  675. }
  676. static void cp_encode_len(cp_save_png_data_t* s, uint32_t code, uint32_t bits, uint32_t len)
  677. {
  678. cp_encode_literal(s, code + (len >> bits));
  679. cp_put_bits(s, len, bits);
  680. cp_put_bits(s, 0, 5);
  681. }
  682. static void cp_end_run(cp_save_png_data_t* s)
  683. {
  684. s->runlen--;
  685. cp_encode_literal(s, s->prev);
  686. if (s->runlen >= 67) cp_encode_len(s, 277, 4, s->runlen - 67);
  687. else if (s->runlen >= 35) cp_encode_len(s, 273, 3, s->runlen - 35);
  688. else if (s->runlen >= 19) cp_encode_len(s, 269, 2, s->runlen - 19);
  689. else if (s->runlen >= 11) cp_encode_len(s, 265, 1, s->runlen - 11);
  690. else if (s->runlen >= 3) cp_encode_len(s, 257, 0, s->runlen - 3);
  691. else while (s->runlen--) cp_encode_literal(s, s->prev);
  692. }
  693. static void cp_encode_byte(cp_save_png_data_t *s, uint8_t v)
  694. {
  695. cp_update_adler(s, v);
  696. // Simple RLE compression. We could do better by doing a search
  697. // to find matches, but this works pretty well TBH.
  698. if (s->prev == v && s->runlen < 115) s->runlen++;
  699. else
  700. {
  701. if (s->runlen) cp_end_run(s);
  702. s->prev = v;
  703. s->runlen = 1;
  704. }
  705. }
  706. static void cp_save_header(cp_save_png_data_t* s, cp_image_t* img)
  707. {
  708. const unsigned char* hdr = (const unsigned char*)"\211PNG\r\n\032\n";
  709. for (int i = 0; i < 8; ++i) {
  710. cp_put8(s, *hdr++);
  711. }
  712. cp_begin_chunk(s, "IHDR", 13);
  713. cp_put32(s, img->w);
  714. cp_put32(s, img->h);
  715. cp_put8(s, 8); // bit depth
  716. cp_put8(s, 6); // RGBA
  717. cp_put8(s, 0); // compression (deflate)
  718. cp_put8(s, 0); // filter (standard)
  719. cp_put8(s, 0); // interlace off
  720. cp_put32(s, ~s->crc);
  721. }
  722. static void cp_save_data(cp_save_png_data_t* s, cp_image_t* img, long dataPos, long* dataSize)
  723. {
  724. cp_begin_chunk(s, "IDAT", 0);
  725. cp_put8(s, 0x08); // zlib compression method
  726. cp_put8(s, 0x1D); // zlib compression flags
  727. cp_put_bits(s, 3, 3); // zlib last block + fixed dictionary
  728. for (int y = 0; y < img->h; ++y)
  729. {
  730. cp_pixel_t *row = &img->pix[y * img->w];
  731. cp_pixel_t prev = cp_make_pixel_a(0, 0, 0, 0);
  732. cp_encode_byte(s, 1); // sub filter
  733. for (int x = 0; x < img->w; ++x)
  734. {
  735. cp_encode_byte(s, row[x].r - prev.r);
  736. cp_encode_byte(s, row[x].g - prev.g);
  737. cp_encode_byte(s, row[x].b - prev.b);
  738. cp_encode_byte(s, row[x].a - prev.a);
  739. prev = row[x];
  740. }
  741. }
  742. cp_end_run(s);
  743. cp_encode_literal(s, 256); // terminator
  744. while (s->bits != 0x80) cp_put_bits(s, 0, 1);
  745. cp_put32(s, s->adler);
  746. *dataSize = (s->buflen - dataPos) - 8;
  747. cp_put32(s, ~s->crc);
  748. }
  749. cp_saved_png_t cp_save_png_to_memory(const cp_image_t* img)
  750. {
  751. cp_saved_png_t result = { 0 };
  752. cp_save_png_data_t s = { 0 };
  753. long dataPos, dataSize, fileSize;
  754. if (!img) return result;
  755. s.adler = 1;
  756. s.bits = 0x80;
  757. s.prev = 0xFFFF;
  758. s.bufcap = 1024;
  759. s.buffer = (char*)CUTE_PNG_ALLOC(1024);
  760. cp_save_header(&s, (cp_image_t*)img);
  761. dataPos = s.buflen;
  762. cp_save_data(&s, (cp_image_t*)img, dataPos, &dataSize);
  763. // End chunk.
  764. cp_begin_chunk(&s, "IEND", 0);
  765. cp_put32(&s, ~s.crc);
  766. // Write back payload size.
  767. fileSize = s.buflen;
  768. s.buflen = dataPos;
  769. cp_put32(&s, dataSize);
  770. result.size = fileSize;
  771. result.data = s.buffer;
  772. return result;
  773. }
  774. int cp_save_png(const char* file_name, const cp_image_t* img)
  775. {
  776. cp_saved_png_t s;
  777. long err;
  778. CUTE_PNG_FILE* fp = CUTE_PNG_FOPEN(file_name, "wb");
  779. if (!fp) return 1;
  780. s = cp_save_png_to_memory(img);
  781. CUTE_PNG_FWRITE(s.data, s.size, 1, fp);
  782. err = CUTE_PNG_FERROR(fp);
  783. CUTE_PNG_FCLOSE(fp);
  784. CUTE_PNG_FREE(s.data);
  785. return !err;
  786. }
  787. typedef struct cp_raw_png_t
  788. {
  789. const uint8_t* p;
  790. const uint8_t* end;
  791. } cp_raw_png_t;
  792. static uint32_t cp_make32(const uint8_t* s)
  793. {
  794. return (s[0] << 24) | (s[1] << 16) | (s[2] << 8) | s[3];
  795. }
  796. static const uint8_t* cp_chunk(cp_raw_png_t* png, const char* chunk, uint32_t minlen)
  797. {
  798. uint32_t len = cp_make32(png->p);
  799. const uint8_t* start = png->p;
  800. if (!CUTE_PNG_MEMCMP(start + 4, chunk, 4) && len >= minlen)
  801. {
  802. int offset = len + 12;
  803. if (png->p + offset <= png->end)
  804. {
  805. png->p += offset;
  806. return start + 8;
  807. }
  808. }
  809. return 0;
  810. }
  811. static const uint8_t* cp_find(cp_raw_png_t* png, const char* chunk, uint32_t minlen)
  812. {
  813. const uint8_t *start;
  814. while (png->p < png->end)
  815. {
  816. uint32_t len = cp_make32(png->p);
  817. start = png->p;
  818. png->p += len + 12;
  819. if (!CUTE_PNG_MEMCMP(start+4, chunk, 4) && len >= minlen && png->p <= png->end)
  820. return start + 8;
  821. }
  822. return 0;
  823. }
  824. static int cp_unfilter(int w, int h, int bpp, uint8_t* raw)
  825. {
  826. int len = w * bpp;
  827. uint8_t *prev;
  828. int x;
  829. if (h > 0)
  830. {
  831. #define FILTER_LOOP_FIRST(A) for (x = bpp; x < len; x++) raw[x] += A; break
  832. switch (*raw++)
  833. {
  834. case 0: break;
  835. case 1: FILTER_LOOP_FIRST(raw[x - bpp]);
  836. case 2: break;
  837. case 3: FILTER_LOOP_FIRST(raw[x - bpp] / 2);
  838. case 4: FILTER_LOOP_FIRST(cp_paeth(raw[x - bpp], 0, 0));
  839. default: return 0;
  840. }
  841. #undef FILTER_LOOP_FIRST
  842. }
  843. prev = raw;
  844. raw += len;
  845. for (int y = 1; y < h; y++, prev = raw, raw += len)
  846. {
  847. #define FILTER_LOOP(A, B) for (x = 0 ; x < bpp; x++) raw[x] += A; for (; x < len; x++) raw[x] += B; break
  848. switch (*raw++)
  849. {
  850. case 0: break;
  851. case 1: FILTER_LOOP(0 , raw[x - bpp] );
  852. case 2: FILTER_LOOP(prev[x] , prev[x]);
  853. case 3: FILTER_LOOP(prev[x] / 2, (raw[x - bpp] + prev[x]) / 2);
  854. case 4: FILTER_LOOP(prev[x] , cp_paeth(raw[x - bpp], prev[x], prev[x -bpp]));
  855. default: return 0;
  856. }
  857. #undef FILTER_LOOP
  858. }
  859. return 1;
  860. }
  861. static void cp_convert(int bpp, int w, int h, uint8_t* src, cp_pixel_t* dst)
  862. {
  863. for (int y = 0; y < h; y++)
  864. {
  865. // skip filter byte
  866. src++;
  867. for (int x = 0; x < w; x++, src += bpp)
  868. {
  869. switch (bpp)
  870. {
  871. case 1: *dst++ = cp_make_pixel(src[0], src[0], src[0]); break;
  872. case 2: *dst++ = cp_make_pixel_a(src[0], src[0], src[0], src[1]); break;
  873. case 3: *dst++ = cp_make_pixel(src[0], src[1], src[2]); break;
  874. case 4: *dst++ = cp_make_pixel_a(src[0], src[1], src[2], src[3]); break;
  875. }
  876. }
  877. }
  878. }
  879. // http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.tRNS
  880. static uint8_t cp_get_alpha_for_indexed_image(int index, const uint8_t* trns, uint32_t trns_len)
  881. {
  882. if (!trns) return 255;
  883. else if ((uint32_t)index >= trns_len) return 255;
  884. else return trns[index];
  885. }
  886. static void cp_depalette(int w, int h, uint8_t* src, cp_pixel_t* dst, const uint8_t* plte, const uint8_t* trns, uint32_t trns_len)
  887. {
  888. for (int y = 0; y < h; ++y)
  889. {
  890. // skip filter byte
  891. ++src;
  892. for (int x = 0; x < w; ++x, ++src)
  893. {
  894. int c = *src;
  895. uint8_t r = plte[c * 3];
  896. uint8_t g = plte[c * 3 + 1];
  897. uint8_t b = plte[c * 3 + 2];
  898. uint8_t a = cp_get_alpha_for_indexed_image(c, trns, trns_len);
  899. *dst++ = cp_make_pixel_a(r, g, b, a);
  900. }
  901. }
  902. }
  903. static uint32_t cp_get_chunk_byte_length(const uint8_t* chunk)
  904. {
  905. return cp_make32(chunk - 8);
  906. }
  907. static int cp_out_size(cp_image_t* img, int bpp)
  908. {
  909. return (img->w + 1) * img->h * bpp;
  910. }
  911. cp_image_t cp_load_png_mem(const void* png_data, int png_length)
  912. {
  913. const char* sig = "\211PNG\r\n\032\n";
  914. const uint8_t* ihdr, *first, *plte, *trns;
  915. int bit_depth, color_type, bpp, w, h, pix_bytes;
  916. int compression, filter, interlace;
  917. int datalen, offset;
  918. uint8_t* out;
  919. cp_image_t img = { 0 };
  920. uint8_t* data = 0;
  921. cp_raw_png_t png;
  922. png.p = (uint8_t*)png_data;
  923. png.end = (uint8_t*)png_data + png_length;
  924. CUTE_PNG_CHECK(!CUTE_PNG_MEMCMP(png.p, sig, 8), "incorrect file signature (is this a png file?)");
  925. png.p += 8;
  926. ihdr = cp_chunk(&png, "IHDR", 13);
  927. CUTE_PNG_CHECK(ihdr, "unable to find IHDR chunk");
  928. bit_depth = ihdr[8];
  929. color_type = ihdr[9];
  930. CUTE_PNG_CHECK(bit_depth == 8, "only bit-depth of 8 is supported");
  931. switch (color_type)
  932. {
  933. case 0: bpp = 1; break; // greyscale
  934. case 2: bpp = 3; break; // RGB
  935. case 3: bpp = 1; break; // paletted
  936. case 4: bpp = 2; break; // grey+alpha
  937. case 6: bpp = 4; break; // RGBA
  938. default: CUTE_PNG_CHECK(0, "unknown color type");
  939. }
  940. // +1 for filter byte (which is dumb! just stick this at file header...)
  941. w = cp_make32(ihdr) + 1;
  942. h = cp_make32(ihdr + 4);
  943. CUTE_PNG_CHECK(w >= 1, "invalid IHDR chunk found, image width was less than 1");
  944. CUTE_PNG_CHECK(h >= 1, "invalid IHDR chunk found, image height was less than 1");
  945. CUTE_PNG_CHECK((int64_t) w * h * sizeof(cp_pixel_t) < INT_MAX, "image too large");
  946. pix_bytes = w * h * sizeof(cp_pixel_t);
  947. img.w = w - 1;
  948. img.h = h;
  949. img.pix = (cp_pixel_t*)CUTE_PNG_ALLOC(pix_bytes);
  950. CUTE_PNG_CHECK(img.pix, "unable to allocate raw image space");
  951. compression = ihdr[10];
  952. filter = ihdr[11];
  953. interlace = ihdr[12];
  954. CUTE_PNG_CHECK(!compression, "only standard compression DEFLATE is supported");
  955. CUTE_PNG_CHECK(!filter, "only standard adaptive filtering is supported");
  956. CUTE_PNG_CHECK(!interlace, "interlacing is not supported");
  957. // PLTE must come before any IDAT chunk
  958. first = png.p;
  959. plte = cp_find(&png, "PLTE", 0);
  960. if (!plte) png.p = first;
  961. else first = png.p;
  962. // tRNS can come after PLTE
  963. trns = cp_find(&png, "tRNS", 0);
  964. if (!trns) png.p = first;
  965. else first = png.p;
  966. // Compute length of the DEFLATE stream through IDAT chunk data sizes
  967. datalen = 0;
  968. for (const uint8_t* idat = cp_find(&png, "IDAT", 0); idat; idat = cp_chunk(&png, "IDAT", 0))
  969. {
  970. uint32_t len = cp_get_chunk_byte_length(idat);
  971. datalen += len;
  972. }
  973. // Copy in IDAT chunk data sections to form the compressed DEFLATE stream
  974. png.p = first;
  975. data = (uint8_t*)CUTE_PNG_ALLOC(datalen);
  976. offset = 0;
  977. for (const uint8_t* idat = cp_find(&png, "IDAT", 0); idat; idat = cp_chunk(&png, "IDAT", 0))
  978. {
  979. uint32_t len = cp_get_chunk_byte_length(idat);
  980. CUTE_PNG_MEMCPY(data + offset, idat, len);
  981. offset += len;
  982. }
  983. // check for proper zlib structure in DEFLATE stream
  984. CUTE_PNG_CHECK(data && datalen >= 6, "corrupt zlib structure in DEFLATE stream");
  985. CUTE_PNG_CHECK((data[0] & 0x0f) == 0x08, "only zlib compression method (RFC 1950) is supported");
  986. CUTE_PNG_CHECK((data[0] & 0xf0) <= 0x70, "innapropriate window size detected");
  987. CUTE_PNG_CHECK(!(data[1] & 0x20), "preset dictionary is present and not supported");
  988. // check for integer overflow
  989. CUTE_PNG_CHECK(cp_out_size(&img, 4) >= 1, "invalid image size found");
  990. CUTE_PNG_CHECK(cp_out_size(&img, bpp) >= 1, "invalid image size found");
  991. out = (uint8_t*)img.pix + cp_out_size(&img, 4) - cp_out_size(&img, bpp);
  992. CUTE_PNG_CHECK(cp_inflate(data + 2, datalen - 6, out, pix_bytes), "DEFLATE algorithm failed");
  993. CUTE_PNG_CHECK(cp_unfilter(img.w, img.h, bpp, out), "invalid filter byte found");
  994. if (color_type == 3)
  995. {
  996. CUTE_PNG_CHECK(plte, "color type of indexed requires a PLTE chunk");
  997. uint32_t trns_len = trns ? cp_get_chunk_byte_length(trns) : 0;
  998. cp_depalette(img.w, img.h, out, img.pix, plte, trns, trns_len);
  999. }
  1000. else cp_convert(bpp, img.w, img.h, out, img.pix);
  1001. CUTE_PNG_FREE(data);
  1002. return img;
  1003. cp_err:
  1004. CUTE_PNG_FREE(data);
  1005. CUTE_PNG_FREE(img.pix);
  1006. img.pix = 0;
  1007. return img;
  1008. }
  1009. cp_image_t cp_load_blank(int w, int h)
  1010. {
  1011. cp_image_t img;
  1012. img.w = w;
  1013. img.h = h;
  1014. img.pix = (cp_pixel_t*)CUTE_PNG_ALLOC(w * h * sizeof(cp_pixel_t));
  1015. return img;
  1016. }
  1017. cp_image_t cp_load_png(const char *file_name)
  1018. {
  1019. cp_image_t img = { 0 };
  1020. int len;
  1021. void* data = cp_read_file_to_memory(file_name, &len);
  1022. if (!data) return img;
  1023. img = cp_load_png_mem(data, len);
  1024. CUTE_PNG_FREE(data);
  1025. return img;
  1026. }
  1027. void cp_free_png(cp_image_t* img)
  1028. {
  1029. CUTE_PNG_FREE(img->pix);
  1030. img->pix = 0;
  1031. img->w = img->h = 0;
  1032. }
  1033. void cp_flip_image_horizontal(cp_image_t* img)
  1034. {
  1035. cp_pixel_t* pix = img->pix;
  1036. int w = img->w;
  1037. int h = img->h;
  1038. int flips = h / 2;
  1039. for (int i = 0; i < flips; ++i)
  1040. {
  1041. cp_pixel_t* a = pix + w * i;
  1042. cp_pixel_t* b = pix + w * (h - i - 1);
  1043. for (int j = 0; j < w; ++j)
  1044. {
  1045. cp_pixel_t t = *a;
  1046. *a = *b;
  1047. *b = t;
  1048. ++a;
  1049. ++b;
  1050. }
  1051. }
  1052. }
  1053. void cp_load_png_wh(const void* png_data, int png_length, int* w_out, int* h_out)
  1054. {
  1055. const char* sig = "\211PNG\r\n\032\n";
  1056. const uint8_t* ihdr;
  1057. cp_raw_png_t png;
  1058. int w, h;
  1059. png.p = (uint8_t*)png_data;
  1060. png.end = (uint8_t*)png_data + png_length;
  1061. if (w_out) *w_out = 0;
  1062. if (h_out) *h_out = 0;
  1063. CUTE_PNG_CHECK(!CUTE_PNG_MEMCMP(png.p, sig, 8), "incorrect file signature (is this a png file?)");
  1064. png.p += 8;
  1065. ihdr = cp_chunk(&png, "IHDR", 13);
  1066. CUTE_PNG_CHECK(ihdr, "unable to find IHDR chunk");
  1067. // +1 for filter byte (which is dumb! just stick this at file header...)
  1068. w = cp_make32(ihdr) + 1;
  1069. h = cp_make32(ihdr + 4);
  1070. if (w_out) *w_out = w - 1;
  1071. if (h_out) *h_out = h;
  1072. cp_err:;
  1073. }
  1074. cp_indexed_image_t cp_load_indexed_png(const char* file_name)
  1075. {
  1076. cp_indexed_image_t img = { 0 };
  1077. int len;
  1078. void* data = cp_read_file_to_memory(file_name, &len);
  1079. if (!data) return img;
  1080. img = cp_load_indexed_png_mem(data, len);
  1081. CUTE_PNG_FREE(data);
  1082. return img;
  1083. }
  1084. static void cp_unpack_indexed_rows(int w, int h, uint8_t* src, uint8_t* dst)
  1085. {
  1086. for (int y = 0; y < h; ++y)
  1087. {
  1088. // skip filter byte
  1089. ++src;
  1090. for (int x = 0; x < w; ++x, ++src)
  1091. {
  1092. *dst++ = *src;
  1093. }
  1094. }
  1095. }
  1096. void cp_unpack_palette(cp_pixel_t* dst, const uint8_t* plte, int plte_len, const uint8_t* trns, int trns_len)
  1097. {
  1098. for (int i = 0; i < plte_len * 3; i += 3)
  1099. {
  1100. unsigned char r = plte[i];
  1101. unsigned char g = plte[i + 1];
  1102. unsigned char b = plte[i + 2];
  1103. unsigned char a = cp_get_alpha_for_indexed_image(i / 3, trns, trns_len);
  1104. cp_pixel_t p = cp_make_pixel_a(r, g, b, a);
  1105. *dst++ = p;
  1106. }
  1107. }
  1108. cp_indexed_image_t cp_load_indexed_png_mem(const void *png_data, int png_length)
  1109. {
  1110. const char* sig = "\211PNG\r\n\032\n";
  1111. const uint8_t* ihdr, *first, *plte, *trns;
  1112. int bit_depth, color_type, bpp, w, h, pix_bytes;
  1113. int compression, filter, interlace;
  1114. int datalen, offset;
  1115. int plte_len;
  1116. uint8_t* out;
  1117. cp_indexed_image_t img = { 0 };
  1118. uint8_t* data = 0;
  1119. cp_raw_png_t png;
  1120. png.p = (uint8_t*)png_data;
  1121. png.end = (uint8_t*)png_data + png_length;
  1122. CUTE_PNG_CHECK(!CUTE_PNG_MEMCMP(png.p, sig, 8), "incorrect file signature (is this a png file?)");
  1123. png.p += 8;
  1124. ihdr = cp_chunk(&png, "IHDR", 13);
  1125. CUTE_PNG_CHECK(ihdr, "unable to find IHDR chunk");
  1126. bit_depth = ihdr[8];
  1127. color_type = ihdr[9];
  1128. bpp = 1; // bytes per pixel
  1129. CUTE_PNG_CHECK(bit_depth == 8, "only bit-depth of 8 is supported");
  1130. CUTE_PNG_CHECK(color_type == 3, "only indexed png images (images with a palette) are valid for cp_load_indexed_png_mem");
  1131. // +1 for filter byte (which is dumb! just stick this at file header...)
  1132. w = cp_make32(ihdr) + 1;
  1133. h = cp_make32(ihdr + 4);
  1134. CUTE_PNG_CHECK((int64_t) w * h * sizeof(uint8_t) < INT_MAX, "image too large");
  1135. pix_bytes = w * h * sizeof(uint8_t);
  1136. img.w = w - 1;
  1137. img.h = h;
  1138. img.pix = (uint8_t*)CUTE_PNG_ALLOC(pix_bytes);
  1139. CUTE_PNG_CHECK(img.pix, "unable to allocate raw image space");
  1140. compression = ihdr[10];
  1141. filter = ihdr[11];
  1142. interlace = ihdr[12];
  1143. CUTE_PNG_CHECK(!compression, "only standard compression DEFLATE is supported");
  1144. CUTE_PNG_CHECK(!filter, "only standard adaptive filtering is supported");
  1145. CUTE_PNG_CHECK(!interlace, "interlacing is not supported");
  1146. // PLTE must come before any IDAT chunk
  1147. first = png.p;
  1148. plte = cp_find(&png, "PLTE", 0);
  1149. if (!plte) png.p = first;
  1150. else first = png.p;
  1151. // tRNS can come after PLTE
  1152. trns = cp_find(&png, "tRNS", 0);
  1153. if (!trns) png.p = first;
  1154. else first = png.p;
  1155. // Compute length of the DEFLATE stream through IDAT chunk data sizes
  1156. datalen = 0;
  1157. for (const uint8_t* idat = cp_find(&png, "IDAT", 0); idat; idat = cp_chunk(&png, "IDAT", 0))
  1158. {
  1159. uint32_t len = cp_get_chunk_byte_length(idat);
  1160. datalen += len;
  1161. }
  1162. // Copy in IDAT chunk data sections to form the compressed DEFLATE stream
  1163. png.p = first;
  1164. data = (uint8_t*)CUTE_PNG_ALLOC(datalen);
  1165. offset = 0;
  1166. for (const uint8_t* idat = cp_find(&png, "IDAT", 0); idat; idat = cp_chunk(&png, "IDAT", 0))
  1167. {
  1168. uint32_t len = cp_get_chunk_byte_length(idat);
  1169. CUTE_PNG_MEMCPY(data + offset, idat, len);
  1170. offset += len;
  1171. }
  1172. // check for proper zlib structure in DEFLATE stream
  1173. CUTE_PNG_CHECK(data && datalen >= 6, "corrupt zlib structure in DEFLATE stream");
  1174. CUTE_PNG_CHECK((data[0] & 0x0f) == 0x08, "only zlib compression method (RFC 1950) is supported");
  1175. CUTE_PNG_CHECK((data[0] & 0xf0) <= 0x70, "innapropriate window size detected");
  1176. CUTE_PNG_CHECK(!(data[1] & 0x20), "preset dictionary is present and not supported");
  1177. out = img.pix;
  1178. CUTE_PNG_CHECK(cp_inflate(data + 2, datalen - 6, out, pix_bytes), "DEFLATE algorithm failed");
  1179. CUTE_PNG_CHECK(cp_unfilter(img.w, img.h, bpp, out), "invalid filter byte found");
  1180. cp_unpack_indexed_rows(img.w, img.h, out, img.pix);
  1181. plte_len = cp_get_chunk_byte_length(plte) / 3;
  1182. cp_unpack_palette(img.palette, plte, plte_len, trns, cp_get_chunk_byte_length(trns));
  1183. img.palette_len = (uint8_t)plte_len;
  1184. CUTE_PNG_FREE(data);
  1185. return img;
  1186. cp_err:
  1187. CUTE_PNG_FREE(data);
  1188. CUTE_PNG_FREE(img.pix);
  1189. img.pix = 0;
  1190. return img;
  1191. }
  1192. void cp_free_indexed_png(cp_indexed_image_t* img)
  1193. {
  1194. CUTE_PNG_FREE(img->pix);
  1195. img->pix = 0;
  1196. img->w = img->h = 0;
  1197. }
  1198. cp_image_t cp_depallete_indexed_image(cp_indexed_image_t* img)
  1199. {
  1200. cp_image_t out = { 0 };
  1201. out.w = img->w;
  1202. out.h = img->h;
  1203. out.pix = (cp_pixel_t*)CUTE_PNG_ALLOC(sizeof(cp_pixel_t) * out.w * out.h);
  1204. cp_pixel_t* dst = out.pix;
  1205. uint8_t* src = img->pix;
  1206. for (int y = 0; y < out.h; ++y)
  1207. {
  1208. for (int x = 0; x < out.w; ++x)
  1209. {
  1210. int index = *src++;
  1211. cp_pixel_t p = img->palette[index];
  1212. *dst++ = p;
  1213. }
  1214. }
  1215. return out;
  1216. }
  1217. typedef struct cp_v2i_t
  1218. {
  1219. int x;
  1220. int y;
  1221. } cp_v2i_t;
  1222. typedef struct cp_integer_image_t
  1223. {
  1224. int img_index;
  1225. cp_v2i_t size;
  1226. cp_v2i_t min;
  1227. cp_v2i_t max;
  1228. int fit;
  1229. } cp_integer_image_t;
  1230. static cp_v2i_t cp_v2i(int x, int y)
  1231. {
  1232. cp_v2i_t v;
  1233. v.x = x;
  1234. v.y = y;
  1235. return v;
  1236. }
  1237. static cp_v2i_t cp_sub(cp_v2i_t a, cp_v2i_t b)
  1238. {
  1239. cp_v2i_t v;
  1240. v.x = a.x - b.x;
  1241. v.y = a.y - b.y;
  1242. return v;
  1243. }
  1244. static cp_v2i_t cp_add(cp_v2i_t a, cp_v2i_t b)
  1245. {
  1246. cp_v2i_t v;
  1247. v.x = a.x + b.x;
  1248. v.y = a.y + b.y;
  1249. return v;
  1250. }
  1251. typedef struct cp_atlas_node_t
  1252. {
  1253. cp_v2i_t size;
  1254. cp_v2i_t min;
  1255. cp_v2i_t max;
  1256. } cp_atlas_node_t;
  1257. static cp_atlas_node_t* cp_best_fit(int sp, const cp_image_t* png, cp_atlas_node_t* nodes)
  1258. {
  1259. int bestVolume = INT_MAX;
  1260. cp_atlas_node_t *best_node = 0;
  1261. int width = png->w;
  1262. int height = png->h;
  1263. int png_volume = width * height;
  1264. for (int i = 0; i < sp; ++i)
  1265. {
  1266. cp_atlas_node_t *node = nodes + i;
  1267. int can_contain = node->size.x >= width && node->size.y >= height;
  1268. if (can_contain)
  1269. {
  1270. int node_volume = node->size.x * node->size.y;
  1271. if (node_volume == png_volume) return node;
  1272. if (node_volume < bestVolume)
  1273. {
  1274. bestVolume = node_volume;
  1275. best_node = node;
  1276. }
  1277. }
  1278. }
  1279. return best_node;
  1280. }
  1281. static int cp_perimeter_pred(cp_integer_image_t* a, cp_integer_image_t* b)
  1282. {
  1283. int perimeterA = 2 * (a->size.x + a->size.y);
  1284. int perimeterB = 2 * (b->size.x + b->size.y);
  1285. return perimeterB < perimeterA;
  1286. }
  1287. void cp_premultiply(cp_image_t* img)
  1288. {
  1289. int w = img->w;
  1290. int h = img->h;
  1291. int stride = w * sizeof(cp_pixel_t);
  1292. uint8_t* data = (uint8_t*)img->pix;
  1293. for(int i = 0; i < (int)stride * h; i += sizeof(cp_pixel_t))
  1294. {
  1295. float a = (float)data[i + 3] / 255.0f;
  1296. float r = (float)data[i + 0] / 255.0f;
  1297. float g = (float)data[i + 1] / 255.0f;
  1298. float b = (float)data[i + 2] / 255.0f;
  1299. r *= a;
  1300. g *= a;
  1301. b *= a;
  1302. data[i + 0] = (uint8_t)(r * 255.0f);
  1303. data[i + 1] = (uint8_t)(g * 255.0f);
  1304. data[i + 2] = (uint8_t)(b * 255.0f);
  1305. }
  1306. }
  1307. static void cp_qsort(cp_integer_image_t* items, int count)
  1308. {
  1309. if (count <= 1) return;
  1310. cp_integer_image_t pivot = items[count - 1];
  1311. int low = 0;
  1312. for (int i = 0; i < count - 1; ++i)
  1313. {
  1314. if (cp_perimeter_pred(items + i, &pivot))
  1315. {
  1316. cp_integer_image_t tmp = items[i];
  1317. items[i] = items[low];
  1318. items[low] = tmp;
  1319. low++;
  1320. }
  1321. }
  1322. items[count - 1] = items[low];
  1323. items[low] = pivot;
  1324. cp_qsort(items, low);
  1325. cp_qsort(items + low + 1, count - 1 - low);
  1326. }
  1327. static void cp_write_pixel(char* mem, long color) {
  1328. mem[0] = (color >> 24) & 0xFF;
  1329. mem[1] = (color >> 16) & 0xFF;
  1330. mem[2] = (color >> 8) & 0xFF;
  1331. mem[3] = (color >> 0) & 0xFF;
  1332. }
  1333. cp_image_t cp_make_atlas(int atlas_width, int atlas_height, const cp_image_t* pngs, int png_count, cp_atlas_image_t* imgs_out)
  1334. {
  1335. float w0, h0, div, wTol, hTol;
  1336. int atlas_image_size, atlas_stride, sp;
  1337. void* atlas_pixels = 0;
  1338. int atlas_node_capacity = png_count * 2;
  1339. cp_image_t atlas_image;
  1340. cp_integer_image_t* images = 0;
  1341. cp_atlas_node_t* nodes = 0;
  1342. atlas_image.w = atlas_width;
  1343. atlas_image.h = atlas_height;
  1344. atlas_image.pix = 0;
  1345. CUTE_PNG_CHECK(pngs, "pngs array was NULL");
  1346. CUTE_PNG_CHECK(imgs_out, "imgs_out array was NULL");
  1347. images = (cp_integer_image_t*)CUTE_PNG_ALLOCA(sizeof(cp_integer_image_t) * png_count);
  1348. nodes = (cp_atlas_node_t*)CUTE_PNG_ALLOC(sizeof(cp_atlas_node_t) * atlas_node_capacity);
  1349. CUTE_PNG_CHECK(images, "out of mem");
  1350. CUTE_PNG_CHECK(nodes, "out of mem");
  1351. for (int i = 0; i < png_count; ++i)
  1352. {
  1353. const cp_image_t* png = pngs + i;
  1354. cp_integer_image_t* image = images + i;
  1355. image->fit = 0;
  1356. image->size = cp_v2i(png->w, png->h);
  1357. image->img_index = i;
  1358. }
  1359. // Sort PNGs from largest to smallest
  1360. cp_qsort(images, png_count);
  1361. // stack pointer, the stack is the nodes array which we will
  1362. // allocate nodes from as necessary.
  1363. sp = 1;
  1364. nodes[0].min = cp_v2i(0, 0);
  1365. nodes[0].max = cp_v2i(atlas_width, atlas_height);
  1366. nodes[0].size = cp_v2i(atlas_width, atlas_height);
  1367. // Nodes represent empty space in the atlas. Placing a texture into the
  1368. // atlas involves splitting a node into two smaller pieces (or, if a
  1369. // perfect fit is found, deleting the node).
  1370. for (int i = 0; i < png_count; ++i)
  1371. {
  1372. cp_integer_image_t* image = images + i;
  1373. const cp_image_t* png = pngs + image->img_index;
  1374. int width = png->w;
  1375. int height = png->h;
  1376. cp_atlas_node_t *best_fit = cp_best_fit(sp, png, nodes);
  1377. if (CUTE_PNG_ATLAS_MUST_FIT) CUTE_PNG_CHECK(best_fit, "Not enough room to place image in atlas.");
  1378. else if (!best_fit)
  1379. {
  1380. image->fit = 0;
  1381. continue;
  1382. }
  1383. image->min = best_fit->min;
  1384. image->max = cp_add(image->min, image->size);
  1385. if (best_fit->size.x == width && best_fit->size.y == height)
  1386. {
  1387. cp_atlas_node_t* last_node = nodes + --sp;
  1388. *best_fit = *last_node;
  1389. image->fit = 1;
  1390. continue;
  1391. }
  1392. image->fit = 1;
  1393. if (sp == atlas_node_capacity)
  1394. {
  1395. int new_capacity = atlas_node_capacity * 2;
  1396. cp_atlas_node_t* new_nodes = (cp_atlas_node_t*)CUTE_PNG_ALLOC(sizeof(cp_atlas_node_t) * new_capacity);
  1397. CUTE_PNG_CHECK(new_nodes, "out of mem");
  1398. CUTE_PNG_MEMCPY(new_nodes, nodes, sizeof(cp_atlas_node_t) * sp);
  1399. // best_fit became a dangling pointer, so relocate it
  1400. best_fit = new_nodes + (best_fit - nodes);
  1401. CUTE_PNG_FREE(nodes);
  1402. nodes = new_nodes;
  1403. atlas_node_capacity = new_capacity;
  1404. }
  1405. cp_atlas_node_t* new_node = nodes + sp++;
  1406. new_node->min = best_fit->min;
  1407. // Split bestFit along x or y, whichever minimizes
  1408. // fragmentation of empty space
  1409. cp_v2i_t d = cp_sub(best_fit->size, cp_v2i(width, height));
  1410. if (d.x < d.y)
  1411. {
  1412. new_node->size.x = d.x;
  1413. new_node->size.y = height;
  1414. new_node->min.x += width;
  1415. best_fit->size.y = d.y;
  1416. best_fit->min.y += height;
  1417. }
  1418. else
  1419. {
  1420. new_node->size.x = width;
  1421. new_node->size.y = d.y;
  1422. new_node->min.y += height;
  1423. best_fit->size.x = d.x;
  1424. best_fit->min.x += width;
  1425. }
  1426. new_node->max = cp_add(new_node->min, new_node->size);
  1427. }
  1428. // Write the final atlas image, use CUTE_PNG_ATLAS_EMPTY_COLOR as base color
  1429. atlas_stride = atlas_width * sizeof(cp_pixel_t);
  1430. atlas_image_size = atlas_width * atlas_height * sizeof(cp_pixel_t);
  1431. atlas_pixels = CUTE_PNG_ALLOC(atlas_image_size);
  1432. CUTE_PNG_CHECK(atlas_pixels, "out of mem");
  1433. for(int i = 0; i < atlas_image_size; i += sizeof(cp_pixel_t)) {
  1434. cp_write_pixel((char*)atlas_pixels + i, CUTE_PNG_ATLAS_EMPTY_COLOR);
  1435. }
  1436. for (int i = 0; i < png_count; ++i)
  1437. {
  1438. cp_integer_image_t* image = images + i;
  1439. if (image->fit)
  1440. {
  1441. const cp_image_t* png = pngs + image->img_index;
  1442. char* pixels = (char*)png->pix;
  1443. cp_v2i_t min = image->min;
  1444. cp_v2i_t max = image->max;
  1445. int atlas_offset = min.x * sizeof(cp_pixel_t);
  1446. int tex_stride = png->w * sizeof(cp_pixel_t);
  1447. for (int row = min.y, y = 0; row < max.y; ++row, ++y)
  1448. {
  1449. void* row_ptr = (char*)atlas_pixels + (row * atlas_stride + atlas_offset);
  1450. CUTE_PNG_MEMCPY(row_ptr, pixels + y * tex_stride, tex_stride);
  1451. }
  1452. }
  1453. }
  1454. atlas_image.pix = (cp_pixel_t*)atlas_pixels;
  1455. // squeeze UVs inward by 128th of a pixel
  1456. // this prevents atlas bleeding. tune as necessary for good results.
  1457. w0 = 1.0f / (float)(atlas_width);
  1458. h0 = 1.0f / (float)(atlas_height);
  1459. div = 1.0f / 128.0f;
  1460. wTol = w0 * div;
  1461. hTol = h0 * div;
  1462. for (int i = 0; i < png_count; ++i)
  1463. {
  1464. cp_integer_image_t* image = images + i;
  1465. cp_atlas_image_t* img_out = imgs_out + i;
  1466. img_out->img_index = image->img_index;
  1467. img_out->w = image->size.x;
  1468. img_out->h = image->size.y;
  1469. img_out->fit = image->fit;
  1470. if (image->fit)
  1471. {
  1472. cp_v2i_t min = image->min;
  1473. cp_v2i_t max = image->max;
  1474. float min_x = (float)min.x * w0 + wTol;
  1475. float min_y = (float)min.y * h0 + hTol;
  1476. float max_x = (float)max.x * w0 - wTol;
  1477. float max_y = (float)max.y * h0 - hTol;
  1478. // flip image on y axis
  1479. if (CUTE_PNG_ATLAS_FLIP_Y_AXIS_FOR_UV)
  1480. {
  1481. float tmp = min_y;
  1482. min_y = max_y;
  1483. max_y = tmp;
  1484. }
  1485. img_out->minx = min_x;
  1486. img_out->miny = min_y;
  1487. img_out->maxx = max_x;
  1488. img_out->maxy = max_y;
  1489. }
  1490. }
  1491. CUTE_PNG_FREE(nodes);
  1492. return atlas_image;
  1493. cp_err:
  1494. CUTE_PNG_FREE(atlas_pixels);
  1495. CUTE_PNG_FREE(nodes);
  1496. atlas_image.pix = 0;
  1497. return atlas_image;
  1498. }
  1499. int cp_default_save_atlas(const char* out_path_image, const char* out_path_atlas_txt, const cp_image_t* atlas, const cp_atlas_image_t* imgs, int img_count, const char** names)
  1500. {
  1501. CUTE_PNG_FILE* fp = CUTE_PNG_FOPEN(out_path_atlas_txt, "wt");
  1502. CUTE_PNG_CHECK(fp, "unable to open out_path_atlas_txt in cp_default_save_atlas");
  1503. CUTE_PNG_FPRINTF(fp, "%s\n%d\n\n", out_path_image, img_count);
  1504. for (int i = 0; i < img_count; ++i)
  1505. {
  1506. const cp_atlas_image_t* image = imgs + i;
  1507. const char* name = names ? names[image->img_index] : 0;
  1508. if (image->fit)
  1509. {
  1510. int width = image->w;
  1511. int height = image->h;
  1512. float min_x = image->minx;
  1513. float min_y = image->miny;
  1514. float max_x = image->maxx;
  1515. float max_y = image->maxy;
  1516. if (name) CUTE_PNG_FPRINTF(fp, "{ \"%s\", w = %d, h = %d, u = { %.10f, %.10f }, v = { %.10f, %.10f } }\n", name, width, height, min_x, min_y, max_x, max_y);
  1517. else CUTE_PNG_FPRINTF(fp, "{ w = %d, h = %d, u = { %.10f, %.10f }, v = { %.10f, %.10f } }\n", width, height, min_x, min_y, max_x, max_y);
  1518. }
  1519. }
  1520. // Save atlas image PNG to disk
  1521. CUTE_PNG_CHECK(cp_save_png(out_path_image, atlas), "failed to save atlas image to disk");
  1522. cp_err:
  1523. CUTE_PNG_FCLOSE(fp);
  1524. return 0;
  1525. }
  1526. #endif // CUTE_PNG_IMPLEMENTATION_ONCE
  1527. #endif // CUTE_PNG_IMPLEMENTATION
  1528. /*
  1529. ------------------------------------------------------------------------------
  1530. This software is available under 2 licenses - you may choose the one you like.
  1531. ------------------------------------------------------------------------------
  1532. ALTERNATIVE A - zlib license
  1533. Copyright (c) 2019 Randy Gaul http://www.randygaul.net
  1534. This software is provided 'as-is', without any express or implied warranty.
  1535. In no event will the authors be held liable for any damages arising from
  1536. the use of this software.
  1537. Permission is granted to anyone to use this software for any purpose,
  1538. including commercial applications, and to alter it and redistribute it
  1539. freely, subject to the following restrictions:
  1540. 1. The origin of this software must not be misrepresented; you must not
  1541. claim that you wrote the original software. If you use this software
  1542. in a product, an acknowledgment in the product documentation would be
  1543. appreciated but is not required.
  1544. 2. Altered source versions must be plainly marked as such, and must not
  1545. be misrepresented as being the original software.
  1546. 3. This notice may not be removed or altered from any source distribution.
  1547. ------------------------------------------------------------------------------
  1548. ALTERNATIVE B - Public Domain (www.unlicense.org)
  1549. This is free and unencumbered software released into the public domain.
  1550. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
  1551. software, either in source code form or as a compiled binary, for any purpose,
  1552. commercial or non-commercial, and by any means.
  1553. In jurisdictions that recognize copyright laws, the author or authors of this
  1554. software dedicate any and all copyright interest in the software to the public
  1555. domain. We make this dedication for the benefit of the public at large and to
  1556. the detriment of our heirs and successors. We intend this dedication to be an
  1557. overt act of relinquishment in perpetuity of all present and future rights to
  1558. this software under copyright law.
  1559. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1560. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1561. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1562. AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  1563. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  1564. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  1565. ------------------------------------------------------------------------------
  1566. */