]> icculus.org git repositories - divverent/darkplaces.git/blob - image_png.c
notice the input data has no useful data on the alpha channel, and fall back to RGB...
[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_info_struct)      (void*);
37 static void                             (*qpng_read_info)                       (void*, void*);
38 static void                             (*qpng_set_expand)                      (void*);
39 static void                             (*qpng_set_gray_1_2_4_to_8)     (void*);
40 static void                             (*qpng_set_palette_to_rgb)      (void*);
41 static void                             (*qpng_set_tRNS_to_alpha)       (void*);
42 static void                             (*qpng_set_gray_to_rgb)         (void*);
43 static void                             (*qpng_set_filler)                      (void*, unsigned int, int);
44 static void                             (*qpng_read_update_info)        (void*, void*);
45 static void                             (*qpng_read_image)                      (void*, unsigned char**);
46 static void                             (*qpng_read_end)                        (void*, void*);
47 static void                             (*qpng_destroy_read_struct)     (void**, void**, void**);
48 static void                             (*qpng_set_read_fn)                     (void*, void*, void(*)(void *png, unsigned char *data, size_t length));
49 static unsigned int             (*qpng_get_valid)                       (void*, void*, unsigned int);
50 static unsigned int             (*qpng_get_rowbytes)            (void*, void*);
51 static unsigned char    (*qpng_get_channels)            (void*, void*);
52 static unsigned char    (*qpng_get_bit_depth)           (void*, void*);
53 static unsigned int             (*qpng_get_IHDR)                        (void*, void*, unsigned long*, unsigned long*, int *, int *, int *, int *, int *);
54 static char*                    (*qpng_get_libpng_ver)          (void*);
55
56 static dllfunction_t pngfuncs[] =
57 {
58         {"png_set_sig_bytes",           (void **) &qpng_set_sig_bytes},
59         {"png_sig_cmp",                         (void **) &qpng_sig_cmp},
60         {"png_create_read_struct",      (void **) &qpng_create_read_struct},
61         {"png_create_info_struct",      (void **) &qpng_create_info_struct},
62         {"png_read_info",                       (void **) &qpng_read_info},
63         {"png_set_expand",                      (void **) &qpng_set_expand},
64         {"png_set_gray_1_2_4_to_8",     (void **) &qpng_set_gray_1_2_4_to_8},
65         {"png_set_palette_to_rgb",      (void **) &qpng_set_palette_to_rgb},
66         {"png_set_tRNS_to_alpha",       (void **) &qpng_set_tRNS_to_alpha},
67         {"png_set_gray_to_rgb",         (void **) &qpng_set_gray_to_rgb},
68         {"png_set_filler",                      (void **) &qpng_set_filler},
69         {"png_read_update_info",        (void **) &qpng_read_update_info},
70         {"png_read_image",                      (void **) &qpng_read_image},
71         {"png_read_end",                        (void **) &qpng_read_end},
72         {"png_destroy_read_struct",     (void **) &qpng_destroy_read_struct},
73         {"png_set_read_fn",                     (void **) &qpng_set_read_fn},
74         {"png_get_valid",                       (void **) &qpng_get_valid},
75         {"png_get_rowbytes",            (void **) &qpng_get_rowbytes},
76         {"png_get_channels",            (void **) &qpng_get_channels},
77         {"png_get_bit_depth",           (void **) &qpng_get_bit_depth},
78         {"png_get_IHDR",                        (void **) &qpng_get_IHDR},
79         {"png_get_libpng_ver",          (void **) &qpng_get_libpng_ver},
80         {NULL, NULL}
81 };
82
83 // Handle for PNG DLL
84 dllhandle_t png_dll = NULL;
85
86
87 /*
88 =================================================================
89
90   DLL load & unload
91
92 =================================================================
93 */
94
95 /*
96 ====================
97 PNG_OpenLibrary
98
99 Try to load the PNG DLL
100 ====================
101 */
102 qboolean PNG_OpenLibrary (void)
103 {
104         const char* dllnames [] =
105         {
106 #if WIN32
107                 "libpng12.dll",
108 #elif defined(MACOSX)
109                 "libpng12.0.dylib",
110 #else
111                 "libpng12.so.0",
112                 "libpng.so", // FreeBSD
113 #endif
114                 NULL
115         };
116
117         // Already loaded?
118         if (png_dll)
119                 return true;
120
121         // Load the DLL
122         return Sys_LoadLibrary (dllnames, &png_dll, pngfuncs);
123 }
124
125
126 /*
127 ====================
128 PNG_CloseLibrary
129
130 Unload the PNG DLL
131 ====================
132 */
133 void PNG_CloseLibrary (void)
134 {
135         Sys_UnloadLibrary (&png_dll);
136 }
137
138
139 /*
140 =================================================================
141
142         PNG decompression
143
144 =================================================================
145 */
146
147 #define PNG_LIBPNG_VER_STRING "1.2.4"
148
149 #define PNG_COLOR_MASK_PALETTE    1
150 #define PNG_COLOR_MASK_COLOR      2
151 #define PNG_COLOR_MASK_ALPHA      4
152
153 #define PNG_COLOR_TYPE_GRAY 0
154 #define PNG_COLOR_TYPE_PALETTE  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
155 #define PNG_COLOR_TYPE_RGB        (PNG_COLOR_MASK_COLOR)
156 #define PNG_COLOR_TYPE_RGB_ALPHA  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
157 #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
158
159 #define PNG_COLOR_TYPE_RGBA  PNG_COLOR_TYPE_RGB_ALPHA
160 #define PNG_COLOR_TYPE_GA  PNG_COLOR_TYPE_GRAY_ALPHA
161
162 #define PNG_INFO_tRNS 0x0010
163
164 // this struct is only used for status information during loading
165 static struct
166 {
167         const unsigned char     *tmpBuf;
168         int             tmpBuflength;
169         int             tmpi;
170         //int           FBgColor;
171         //int           FTransparent;
172         unsigned int    FRowBytes;
173         //double        FGamma;
174         //double        FScreenGamma;
175         unsigned char   **FRowPtrs;
176         unsigned char   *Data;
177         //char  *Title;
178         //char  *Author;
179         //char  *Description;
180         int             BitDepth;
181         int             BytesPerPixel;
182         int             ColorType;
183         unsigned long   Height; // retarded libpng 1.2 pngconf.h uses long (64bit/32bit depending on arch)
184         unsigned long   Width; // retarded libpng 1.2 pngconf.h uses long (64bit/32bit depending on arch)
185         int             Interlace;
186         int             Compression;
187         int             Filter;
188         //double        LastModified;
189         //int           Transparent;
190 } my_png;
191
192 //LordHavoc: removed __cdecl prefix, added overrun protection, and rewrote this to be more efficient
193 void PNG_fReadData(void *png, unsigned char *data, size_t length)
194 {
195         size_t l;
196         l = my_png.tmpBuflength - my_png.tmpi;
197         if (l < length)
198         {
199                 Con_Printf("PNG_fReadData: overrun by %i bytes\n", (int)(length - l));
200                 // a read going past the end of the file, fill in the remaining bytes
201                 // with 0 just to be consistent
202                 memset(data + l, 0, length - l);
203                 length = l;
204         }
205         memcpy(data, my_png.tmpBuf + my_png.tmpi, length);
206         my_png.tmpi += (int)length;
207         //Com_HexDumpToConsole(data, (int)length);
208 }
209
210 void PNG_error_fn(void *png, const char *message)
211 {
212         Con_Printf("PNG_LoadImage: error: %s\n", message);
213 }
214
215 void PNG_warning_fn(void *png, const char *message)
216 {
217         Con_Printf("PNG_LoadImage: warning: %s\n", message);
218 }
219
220 extern int      image_width;
221 extern int      image_height;
222
223 unsigned char *PNG_LoadImage_BGRA (const unsigned char *raw, int filesize)
224 {
225         unsigned int c;
226         unsigned int    y;
227         void *png, *pnginfo;
228         unsigned char *imagedata = NULL;
229         unsigned char ioBuffer[8192];
230
231         // FIXME: register an error handler so that abort() won't be called on error
232
233         // No DLL = no PNGs
234         if (!png_dll)
235                 return NULL;
236
237         if(qpng_sig_cmp(raw, 0, filesize))
238                 return NULL;
239         png = (void *)qpng_create_read_struct(PNG_LIBPNG_VER_STRING, 0, PNG_error_fn, PNG_warning_fn);
240         if(!png)
241                 return NULL;
242
243         // this must be memset before the setjmp error handler, because it relies
244         // on the fields in this struct for cleanup
245         memset(&my_png, 0, sizeof(my_png));
246
247         // NOTE: this relies on jmp_buf being the first thing in the png structure
248         // created by libpng! (this is correct for libpng 1.2.x)
249 #ifdef __cplusplus
250 #if defined(MACOSX) || defined(WIN32)
251         if (setjmp((int *)png))
252 #else
253         if (setjmp((__jmp_buf_tag *)png))
254 #endif
255 #else
256         if (setjmp(png))
257 #endif
258         {
259                 if (my_png.Data)
260                         Mem_Free(my_png.Data);
261                 my_png.Data = NULL;
262                 if (my_png.FRowPtrs)
263                         Mem_Free(my_png.FRowPtrs);
264                 my_png.FRowPtrs = NULL;
265                 qpng_destroy_read_struct(&png, &pnginfo, 0);
266                 return NULL;
267         }
268         //
269
270         pnginfo = qpng_create_info_struct(png);
271         if(!pnginfo)
272         {
273                 qpng_destroy_read_struct(&png, &pnginfo, 0);
274                 return NULL;
275         }
276         qpng_set_sig_bytes(png, 0);
277
278         my_png.tmpBuf = raw;
279         my_png.tmpBuflength = filesize;
280         my_png.tmpi = 0;
281         //my_png.Data           = NULL;
282         //my_png.FRowPtrs       = NULL;
283         //my_png.Height         = 0;
284         //my_png.Width          = 0;
285         my_png.ColorType        = PNG_COLOR_TYPE_RGB;
286         //my_png.Interlace      = 0;
287         //my_png.Compression    = 0;
288         //my_png.Filter         = 0;
289         qpng_set_read_fn(png, ioBuffer, PNG_fReadData);
290         qpng_read_info(png, pnginfo);
291         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);
292
293         // 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
294         // (if it's little endian the unwritten bytes are the most significant
295         //  ones and we don't worry about that)
296         //
297         // this is only necessary because of retarded 64bit png_uint_32 types in libpng 1.2, which can (conceivably) vary by platform
298 #if LONG_MAX > 4000000000
299         if (my_png.Width > LONG_MAX || my_png.Height > LONG_MAX)
300         {
301                 my_png.Width >>= 32;
302                 my_png.Height >>= 32;
303         }
304 #endif
305
306         if (my_png.ColorType == PNG_COLOR_TYPE_PALETTE)
307                 qpng_set_palette_to_rgb(png);
308         if (my_png.ColorType == PNG_COLOR_TYPE_GRAY || my_png.ColorType == PNG_COLOR_TYPE_GRAY_ALPHA)
309         {
310                 qpng_set_gray_to_rgb(png);
311                 if (my_png.BitDepth < 8)
312                         qpng_set_gray_1_2_4_to_8(png);
313         }
314
315         if (qpng_get_valid(png, pnginfo, PNG_INFO_tRNS))
316                 qpng_set_tRNS_to_alpha(png);
317         if (my_png.BitDepth == 8 && !(my_png.ColorType  & PNG_COLOR_MASK_ALPHA))
318                 qpng_set_filler(png, 255, 1);
319         if (( my_png.ColorType == PNG_COLOR_TYPE_GRAY) || (my_png.ColorType == PNG_COLOR_TYPE_GRAY_ALPHA ))
320                 qpng_set_gray_to_rgb(png);
321         if (my_png.BitDepth < 8)
322                 qpng_set_expand(png);
323
324         qpng_read_update_info(png, pnginfo);
325
326         my_png.FRowBytes = qpng_get_rowbytes(png, pnginfo);
327         my_png.BytesPerPixel = qpng_get_channels(png, pnginfo);
328
329         my_png.FRowPtrs = (unsigned char **)Mem_Alloc(tempmempool, my_png.Height * sizeof(*my_png.FRowPtrs));
330         if (my_png.FRowPtrs)
331         {
332                 imagedata = (unsigned char *)Mem_Alloc(tempmempool, my_png.Height * my_png.FRowBytes);
333                 if(imagedata)
334                 {
335                         my_png.Data = imagedata;
336                         for(y = 0;y < my_png.Height;y++)
337                                 my_png.FRowPtrs[y] = my_png.Data + y * my_png.FRowBytes;
338                         qpng_read_image(png, my_png.FRowPtrs);
339                 }
340                 else
341                 {
342                         Con_Printf("PNG_LoadImage : not enough memory\n");
343                         qpng_destroy_read_struct(&png, &pnginfo, 0);
344                         Mem_Free(my_png.FRowPtrs);
345                         return NULL;
346                 }
347                 Mem_Free(my_png.FRowPtrs);
348                 my_png.FRowPtrs = NULL;
349         }
350         else
351         {
352                 Con_Printf("PNG_LoadImage : not enough memory\n");
353                 qpng_destroy_read_struct(&png, &pnginfo, 0);
354                 return NULL;
355         }
356
357         qpng_read_end(png, pnginfo);
358         qpng_destroy_read_struct(&png, &pnginfo, 0);
359
360         image_width = (int)my_png.Width;
361         image_height = (int)my_png.Height;
362
363         if (my_png.BitDepth != 8)
364         {
365                 Con_Printf ("PNG_LoadImage : bad color depth\n");
366                 Mem_Free(imagedata);
367                 return NULL;
368         }
369
370         // swizzle RGBA to BGRA
371         for (y = 0;y < (unsigned int)(image_width*image_height*4);y += 4)
372         {
373                 c = imagedata[y+0];
374                 imagedata[y+0] = imagedata[y+2];
375                 imagedata[y+2] = c;
376         }
377
378         return imagedata;
379 }
380