]> icculus.org git repositories - divverent/darkplaces.git/blob - image_png.c
make getsurface* functions shared between VMs
[divverent/darkplaces.git] / image_png.c
1 /*
2         Copyright (C) 2006  Serge "(515)" Ziryukin, Forest "LordHavoc" Hale
3
4         This program is free software; you can redistribute it and/or
5         modify it under the terms of the GNU General Public License
6         as published by the Free Software Foundation; either version 2
7         of the License, or (at your option) any later version.
8
9         This program is distributed in the hope that it will be useful,
10         but WITHOUT ANY WARRANTY; without even the implied warranty of
11         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13         See the GNU General Public License for more details.
14
15         You should have received a copy of the GNU General Public License
16         along with this program; if not, write to:
17
18                 Free Software Foundation, Inc.
19                 59 Temple Place - Suite 330
20                 Boston, MA  02111-1307, USA
21
22 */
23
24 //[515]: png implemented into DP ONLY FOR TESTING 2d stuff with csqc
25 // so delete this bullshit :D
26 //
27 //LordHavoc: rewrote most of this.
28
29 #include "quakedef.h"
30 #include "image.h"
31 #include "image_png.h"
32
33 static void                             (*qpng_set_sig_bytes)           (void*, int);
34 static int                              (*qpng_sig_cmp)                         (const unsigned char*, size_t, size_t);
35 static void*                    (*qpng_create_read_struct)      (const char*, void*, void(*)(void *png, const char *message), void(*)(void *png, const char *message));
36 static void*                    (*qpng_create_write_struct)     (const char*, void*, void(*)(void *png, const char *message), void(*)(void *png, const char *message));
37 static void*                    (*qpng_create_info_struct)      (void*);
38 static void                             (*qpng_read_info)                       (void*, void*);
39 static void                             (*qpng_set_compression_level)   (void*, int);
40 static void                             (*qpng_set_filter)                      (void*, int, int);
41 static void                             (*qpng_set_expand)                      (void*);
42 static void                             (*qpng_set_gray_1_2_4_to_8)     (void*);
43 static void                             (*qpng_set_palette_to_rgb)      (void*);
44 static void                             (*qpng_set_tRNS_to_alpha)       (void*);
45 static void                             (*qpng_set_gray_to_rgb)         (void*);
46 static void                             (*qpng_set_filler)                      (void*, unsigned int, int);
47 static void                             (*qpng_set_IHDR)                        (void*, void*, unsigned long, unsigned long, int, int, int, int, int);
48 static void                             (*qpng_set_packing)                     (void*);
49 static void                             (*qpng_set_bgr)                         (void*);
50 static int                              (*qpng_set_interlace_handling)  (void*);
51 static void                             (*qpng_read_update_info)        (void*, void*);
52 static void                             (*qpng_read_image)                      (void*, unsigned char**);
53 static void                             (*qpng_read_end)                        (void*, void*);
54 static void                             (*qpng_destroy_read_struct)     (void**, void**, void**);
55 static void                             (*qpng_destroy_write_struct)    (void**, void**);
56 static void                             (*qpng_set_read_fn)                     (void*, void*, void(*)(void *png, unsigned char *data, size_t length));
57 static void                             (*qpng_set_write_fn)            (void*, void*, void(*)(void *png, unsigned char *data, size_t length), void(*)(void *png));
58 static unsigned int             (*qpng_get_valid)                       (void*, void*, unsigned int);
59 static unsigned int             (*qpng_get_rowbytes)            (void*, void*);
60 static unsigned char    (*qpng_get_channels)            (void*, void*);
61 static unsigned char    (*qpng_get_bit_depth)           (void*, void*);
62 static unsigned int             (*qpng_get_IHDR)                        (void*, void*, unsigned long*, unsigned long*, int *, int *, int *, int *, int *);
63 static char*                    (*qpng_get_libpng_ver)          (void*);
64 static void                             (*qpng_write_info)                      (void*, void*);
65 static void                             (*qpng_write_row)                       (void*, unsigned char*);
66 static void                             (*qpng_write_end)                       (void*, void*);
67
68 static dllfunction_t pngfuncs[] =
69 {
70         {"png_set_sig_bytes",           (void **) &qpng_set_sig_bytes},
71         {"png_sig_cmp",                         (void **) &qpng_sig_cmp},
72         {"png_create_read_struct",      (void **) &qpng_create_read_struct},
73         {"png_create_write_struct",     (void **) &qpng_create_write_struct},
74         {"png_create_info_struct",      (void **) &qpng_create_info_struct},
75         {"png_read_info",                       (void **) &qpng_read_info},
76         {"png_set_compression_level",   (void **) &qpng_set_compression_level},
77         {"png_set_filter",                      (void **) &qpng_set_filter},
78         {"png_set_expand",                      (void **) &qpng_set_expand},
79         {"png_set_gray_1_2_4_to_8",     (void **) &qpng_set_gray_1_2_4_to_8},
80         {"png_set_palette_to_rgb",      (void **) &qpng_set_palette_to_rgb},
81         {"png_set_tRNS_to_alpha",       (void **) &qpng_set_tRNS_to_alpha},
82         {"png_set_gray_to_rgb",         (void **) &qpng_set_gray_to_rgb},
83         {"png_set_filler",                      (void **) &qpng_set_filler},
84         {"png_set_IHDR",                        (void **) &qpng_set_IHDR},
85         {"png_set_packing",                     (void **) &qpng_set_packing},
86         {"png_set_bgr",                         (void **) &qpng_set_bgr},
87         {"png_set_interlace_handling",  (void **) &qpng_set_interlace_handling},
88         {"png_read_update_info",        (void **) &qpng_read_update_info},
89         {"png_read_image",                      (void **) &qpng_read_image},
90         {"png_read_end",                        (void **) &qpng_read_end},
91         {"png_destroy_read_struct",     (void **) &qpng_destroy_read_struct},
92         {"png_destroy_write_struct",    (void **) &qpng_destroy_write_struct},
93         {"png_set_read_fn",                     (void **) &qpng_set_read_fn},
94         {"png_set_write_fn",            (void **) &qpng_set_write_fn},
95         {"png_get_valid",                       (void **) &qpng_get_valid},
96         {"png_get_rowbytes",            (void **) &qpng_get_rowbytes},
97         {"png_get_channels",            (void **) &qpng_get_channels},
98         {"png_get_bit_depth",           (void **) &qpng_get_bit_depth},
99         {"png_get_IHDR",                        (void **) &qpng_get_IHDR},
100         {"png_get_libpng_ver",          (void **) &qpng_get_libpng_ver},
101         {"png_write_info",                      (void **) &qpng_write_info},
102         {"png_write_row",                       (void **) &qpng_write_row},
103         {"png_write_end",                       (void **) &qpng_write_end},
104         {NULL, NULL}
105 };
106
107 // Handle for PNG DLL
108 dllhandle_t png_dll = NULL;
109
110
111 /*
112 =================================================================
113
114   DLL load & unload
115
116 =================================================================
117 */
118
119 /*
120 ====================
121 PNG_OpenLibrary
122
123 Try to load the PNG DLL
124 ====================
125 */
126 qboolean PNG_OpenLibrary (void)
127 {
128         const char* dllnames [] =
129         {
130 #if WIN32
131                 "libpng12.dll",
132 #elif defined(MACOSX)
133                 "libpng12.0.dylib",
134 #else
135                 "libpng12.so.0",
136                 "libpng.so", // FreeBSD
137 #endif
138                 NULL
139         };
140
141         // Already loaded?
142         if (png_dll)
143                 return true;
144
145         // Load the DLL
146         return Sys_LoadLibrary (dllnames, &png_dll, pngfuncs);
147 }
148
149
150 /*
151 ====================
152 PNG_CloseLibrary
153
154 Unload the PNG DLL
155 ====================
156 */
157 void PNG_CloseLibrary (void)
158 {
159         Sys_UnloadLibrary (&png_dll);
160 }
161
162 /*
163 =================================================================
164
165         PNG decompression
166
167 =================================================================
168 */
169
170 #define PNG_LIBPNG_VER_STRING "1.2.4"
171
172 #define PNG_COLOR_MASK_PALETTE    1
173 #define PNG_COLOR_MASK_COLOR      2
174 #define PNG_COLOR_MASK_ALPHA      4
175
176 #define PNG_COLOR_TYPE_GRAY 0
177 #define PNG_COLOR_TYPE_PALETTE  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
178 #define PNG_COLOR_TYPE_RGB        (PNG_COLOR_MASK_COLOR)
179 #define PNG_COLOR_TYPE_RGB_ALPHA  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
180 #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
181
182 #define PNG_COLOR_TYPE_RGBA  PNG_COLOR_TYPE_RGB_ALPHA
183 #define PNG_COLOR_TYPE_GA  PNG_COLOR_TYPE_GRAY_ALPHA
184
185 #define PNG_INFO_tRNS 0x0010
186
187 // this struct is only used for status information during loading
188 static struct
189 {
190         const unsigned char     *tmpBuf;
191         int             tmpBuflength;
192         int             tmpi;
193         //int           FBgColor;
194         //int           FTransparent;
195         unsigned int    FRowBytes;
196         //double        FGamma;
197         //double        FScreenGamma;
198         unsigned char   **FRowPtrs;
199         unsigned char   *Data;
200         //char  *Title;
201         //char  *Author;
202         //char  *Description;
203         int             BitDepth;
204         int             BytesPerPixel;
205         int             ColorType;
206         unsigned long   Height; // retarded libpng 1.2 pngconf.h uses long (64bit/32bit depending on arch)
207         unsigned long   Width; // retarded libpng 1.2 pngconf.h uses long (64bit/32bit depending on arch)
208         int             Interlace;
209         int             Compression;
210         int             Filter;
211         //double        LastModified;
212         //int           Transparent;
213         qfile_t *outfile;
214 } my_png;
215
216 //LordHavoc: removed __cdecl prefix, added overrun protection, and rewrote this to be more efficient
217 void PNG_fReadData(void *png, unsigned char *data, size_t length)
218 {
219         size_t l;
220         l = my_png.tmpBuflength - my_png.tmpi;
221         if (l < length)
222         {
223                 Con_Printf("PNG_fReadData: overrun by %i bytes\n", (int)(length - l));
224                 // a read going past the end of the file, fill in the remaining bytes
225                 // with 0 just to be consistent
226                 memset(data + l, 0, length - l);
227                 length = l;
228         }
229         memcpy(data, my_png.tmpBuf + my_png.tmpi, length);
230         my_png.tmpi += (int)length;
231         //Com_HexDumpToConsole(data, (int)length);
232 }
233
234 void PNG_fWriteData(void *png, unsigned char *data, size_t length)
235 {
236         FS_Write(my_png.outfile, data, length);
237 }
238
239 void PNG_fFlushData(void *png)
240 {
241 }
242
243 void PNG_error_fn(void *png, const char *message)
244 {
245         Con_Printf("PNG_LoadImage: error: %s\n", message);
246 }
247
248 void PNG_warning_fn(void *png, const char *message)
249 {
250         Con_Printf("PNG_LoadImage: warning: %s\n", message);
251 }
252
253 extern int      image_width;
254 extern int      image_height;
255
256 unsigned char *PNG_LoadImage_BGRA (const unsigned char *raw, int filesize)
257 {
258         unsigned int c;
259         unsigned int    y;
260         void *png, *pnginfo;
261         unsigned char *imagedata = NULL;
262         unsigned char ioBuffer[8192];
263
264         // FIXME: register an error handler so that abort() won't be called on error
265
266         // No DLL = no PNGs
267         if (!png_dll)
268                 return NULL;
269
270         if(qpng_sig_cmp(raw, 0, filesize))
271                 return NULL;
272         png = (void *)qpng_create_read_struct(PNG_LIBPNG_VER_STRING, 0, PNG_error_fn, PNG_warning_fn);
273         if(!png)
274                 return NULL;
275
276         // this must be memset before the setjmp error handler, because it relies
277         // on the fields in this struct for cleanup
278         memset(&my_png, 0, sizeof(my_png));
279
280         // NOTE: this relies on jmp_buf being the first thing in the png structure
281         // created by libpng! (this is correct for libpng 1.2.x)
282 #ifdef __cplusplus
283 #if defined(MACOSX) || defined(WIN32)
284         if (setjmp((int *)png))
285 #else
286         if (setjmp((__jmp_buf_tag *)png))
287 #endif
288 #else
289         if (setjmp(png))
290 #endif
291         {
292                 if (my_png.Data)
293                         Mem_Free(my_png.Data);
294                 my_png.Data = NULL;
295                 if (my_png.FRowPtrs)
296                         Mem_Free(my_png.FRowPtrs);
297                 my_png.FRowPtrs = NULL;
298                 qpng_destroy_read_struct(&png, &pnginfo, 0);
299                 return NULL;
300         }
301         //
302
303         pnginfo = qpng_create_info_struct(png);
304         if(!pnginfo)
305         {
306                 qpng_destroy_read_struct(&png, &pnginfo, 0);
307                 return NULL;
308         }
309         qpng_set_sig_bytes(png, 0);
310
311         my_png.tmpBuf = raw;
312         my_png.tmpBuflength = filesize;
313         my_png.tmpi = 0;
314         //my_png.Data           = NULL;
315         //my_png.FRowPtrs       = NULL;
316         //my_png.Height         = 0;
317         //my_png.Width          = 0;
318         my_png.ColorType        = PNG_COLOR_TYPE_RGB;
319         //my_png.Interlace      = 0;
320         //my_png.Compression    = 0;
321         //my_png.Filter         = 0;
322         qpng_set_read_fn(png, ioBuffer, PNG_fReadData);
323         qpng_read_info(png, pnginfo);
324         qpng_get_IHDR(png, pnginfo, &my_png.Width, &my_png.Height,&my_png.BitDepth, &my_png.ColorType, &my_png.Interlace, &my_png.Compression, &my_png.Filter);
325
326         // this check guards against pngconf.h with unsigned int *width/height parameters on big endian systems by detecting the strange values and shifting them down 32bits
327         // (if it's little endian the unwritten bytes are the most significant
328         //  ones and we don't worry about that)
329         //
330         // this is only necessary because of retarded 64bit png_uint_32 types in libpng 1.2, which can (conceivably) vary by platform
331 #if LONG_MAX > 4000000000
332         if (my_png.Width > LONG_MAX || my_png.Height > LONG_MAX)
333         {
334                 my_png.Width >>= 32;
335                 my_png.Height >>= 32;
336         }
337 #endif
338
339         if (my_png.ColorType == PNG_COLOR_TYPE_PALETTE)
340                 qpng_set_palette_to_rgb(png);
341         if (my_png.ColorType == PNG_COLOR_TYPE_GRAY || my_png.ColorType == PNG_COLOR_TYPE_GRAY_ALPHA)
342         {
343                 qpng_set_gray_to_rgb(png);
344                 if (my_png.BitDepth < 8)
345                         qpng_set_gray_1_2_4_to_8(png);
346         }
347
348         if (qpng_get_valid(png, pnginfo, PNG_INFO_tRNS))
349                 qpng_set_tRNS_to_alpha(png);
350         if (my_png.BitDepth == 8 && !(my_png.ColorType  & PNG_COLOR_MASK_ALPHA))
351                 qpng_set_filler(png, 255, 1);
352         if (( my_png.ColorType == PNG_COLOR_TYPE_GRAY) || (my_png.ColorType == PNG_COLOR_TYPE_GRAY_ALPHA ))
353                 qpng_set_gray_to_rgb(png);
354         if (my_png.BitDepth < 8)
355                 qpng_set_expand(png);
356
357         qpng_read_update_info(png, pnginfo);
358
359         my_png.FRowBytes = qpng_get_rowbytes(png, pnginfo);
360         my_png.BytesPerPixel = qpng_get_channels(png, pnginfo);
361
362         my_png.FRowPtrs = (unsigned char **)Mem_Alloc(tempmempool, my_png.Height * sizeof(*my_png.FRowPtrs));
363         if (my_png.FRowPtrs)
364         {
365                 imagedata = (unsigned char *)Mem_Alloc(tempmempool, my_png.Height * my_png.FRowBytes);
366                 if(imagedata)
367                 {
368                         my_png.Data = imagedata;
369                         for(y = 0;y < my_png.Height;y++)
370                                 my_png.FRowPtrs[y] = my_png.Data + y * my_png.FRowBytes;
371                         qpng_read_image(png, my_png.FRowPtrs);
372                 }
373                 else
374                 {
375                         Con_Printf("PNG_LoadImage : not enough memory\n");
376                         qpng_destroy_read_struct(&png, &pnginfo, 0);
377                         Mem_Free(my_png.FRowPtrs);
378                         return NULL;
379                 }
380                 Mem_Free(my_png.FRowPtrs);
381                 my_png.FRowPtrs = NULL;
382         }
383         else
384         {
385                 Con_Printf("PNG_LoadImage : not enough memory\n");
386                 qpng_destroy_read_struct(&png, &pnginfo, 0);
387                 return NULL;
388         }
389
390         qpng_read_end(png, pnginfo);
391         qpng_destroy_read_struct(&png, &pnginfo, 0);
392
393         image_width = (int)my_png.Width;
394         image_height = (int)my_png.Height;
395
396         if (my_png.BitDepth != 8)
397         {
398                 Con_Printf ("PNG_LoadImage : bad color depth\n");
399                 Mem_Free(imagedata);
400                 return NULL;
401         }
402
403         // swizzle RGBA to BGRA
404         for (y = 0;y < (unsigned int)(image_width*image_height*4);y += 4)
405         {
406                 c = imagedata[y+0];
407                 imagedata[y+0] = imagedata[y+2];
408                 imagedata[y+2] = c;
409         }
410
411         return imagedata;
412 }
413
414 /*
415 =================================================================
416
417         PNG compression
418
419 =================================================================
420 */
421
422 #define Z_BEST_SPEED 1
423 #define Z_BEST_COMPRESSION 9
424 #define PNG_INTERLACE_NONE 0
425 #define PNG_INTERLACE_ADAM7 1
426 #define PNG_FILTER_TYPE_BASE 0
427 #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
428 #define PNG_COMPRESSION_TYPE_BASE 0
429 #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
430 #define PNG_NO_FILTERS     0x00
431 #define PNG_FILTER_NONE    0x08
432 #define PNG_FILTER_SUB     0x10
433 #define PNG_FILTER_UP      0x20
434 #define PNG_FILTER_AVG     0x40
435 #define PNG_FILTER_PAETH   0x80
436 #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
437                          PNG_FILTER_AVG | PNG_FILTER_PAETH)
438
439 /*
440 ====================
441 PNG_SaveImage_preflipped
442
443 Save a preflipped PNG image to a file
444 ====================
445 */
446 qboolean PNG_SaveImage_preflipped (const char *filename, int width, int height, unsigned char *data)
447 {
448         unsigned int offset, linesize;
449         qfile_t* file = NULL;
450         void *png, *pnginfo;
451         unsigned char ioBuffer[8192];
452         int passes, i, j;
453
454         // No DLL = no JPEGs
455         if (!png_dll)
456         {
457                 Con_Print("You need the libpng library to save PNG images\n");
458                 return false;
459         }
460
461         png = (void *)qpng_create_write_struct(PNG_LIBPNG_VER_STRING, 0, PNG_error_fn, PNG_warning_fn);
462         if(!png)
463                 return false;
464         pnginfo = (void *)qpng_create_info_struct(png);
465         if(!pnginfo)
466         {
467                  qpng_destroy_write_struct(&png, NULL);
468                  return false;
469         }
470
471         // this must be memset before the setjmp error handler, because it relies
472         // on the fields in this struct for cleanup
473         memset(&my_png, 0, sizeof(my_png));
474
475         // NOTE: this relies on jmp_buf being the first thing in the png structure
476         // created by libpng! (this is correct for libpng 1.2.x)
477 #ifdef __cplusplus
478 #if defined(MACOSX) || defined(WIN32)
479         if (setjmp((int *)png))
480 #else
481         if (setjmp((__jmp_buf_tag *)png))
482 #endif
483 #else
484         if (setjmp(png))
485 #endif
486         {
487                 qpng_destroy_write_struct(&png, &pnginfo);
488                 return false;
489         }
490
491         // Open the file
492         file = FS_OpenRealFile(filename, "wb", true);
493         if (!file)
494                 return false;
495         my_png.outfile = file;
496         qpng_set_write_fn(png, ioBuffer, PNG_fWriteData, PNG_fFlushData);
497
498         //qpng_set_compression_level(png, Z_BEST_COMPRESSION);
499         qpng_set_compression_level(png, Z_BEST_SPEED);
500         qpng_set_IHDR(png, pnginfo, width, height, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_ADAM7, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
501         //qpng_set_IHDR(png, pnginfo, width, height, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
502         qpng_set_filter(png, 0, PNG_NO_FILTERS);
503         qpng_write_info(png, pnginfo);
504         qpng_set_packing(png);
505         qpng_set_bgr(png);
506
507         passes = qpng_set_interlace_handling(png);
508
509         linesize = width * 3;
510         offset = linesize * (height - 1);
511         for(i = 0; i < passes; ++i)
512                 for(j = 0; j < height; ++j)
513                         qpng_write_row(png, &data[offset - j * linesize]);
514
515         qpng_write_end(png, NULL);
516         qpng_destroy_write_struct(&png, &pnginfo);
517
518         FS_Close (file);
519
520         return true;
521 }