]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - image.c
fix a possible pthread crash
[xonotic/darkplaces.git] / image.c
1
2 #include "quakedef.h"
3 #include "image.h"
4 #include "jpeg.h"
5 #include "image_png.h"
6 #include "r_shadow.h"
7
8 int             image_width;
9 int             image_height;
10
11 static void Image_CopyAlphaFromBlueBGRA(unsigned char *outpixels, const unsigned char *inpixels, int w, int h)
12 {
13         int i, n;
14         n = w * h;
15         for(i = 0; i < n; ++i)
16                 outpixels[4*i+3] = inpixels[4*i]; // blue channel
17 }
18
19 #if 1
20 // written by LordHavoc in a readable way, optimized by Vic, further optimized by LordHavoc (the non-special index case), readable version preserved below this
21 void Image_CopyMux(unsigned char *outpixels, const unsigned char *inpixels, int inputwidth, int inputheight, qboolean inputflipx, qboolean inputflipy, qboolean inputflipdiagonal, int numoutputcomponents, int numinputcomponents, int *outputinputcomponentindices)
22 {
23         int index, c, x, y;
24         const unsigned char *in, *line;
25         int row_inc = (inputflipy ? -inputwidth : inputwidth) * numinputcomponents, col_inc = (inputflipx ? -1 : 1) * numinputcomponents;
26         int row_ofs = (inputflipy ? (inputheight - 1) * inputwidth * numinputcomponents : 0), col_ofs = (inputflipx ? (inputwidth - 1) * numinputcomponents : 0);
27
28         for (c = 0; c < numoutputcomponents; c++)
29                 if (outputinputcomponentindices[c] & 0x80000000)
30                         break;
31         if (c < numoutputcomponents)
32         {
33                 // special indices used
34                 if (inputflipdiagonal)
35                 {
36                         for (x = 0, line = inpixels + col_ofs; x < inputwidth; x++, line += col_inc)
37                                 for (y = 0, in = line + row_ofs; y < inputheight; y++, in += row_inc, outpixels += numoutputcomponents)
38                                         for (c = 0; c < numoutputcomponents; c++)
39                                                 outpixels[c] = ((index = outputinputcomponentindices[c]) & 0x80000000) ? index : in[index];
40                 }
41                 else
42                 {
43                         for (y = 0, line = inpixels + row_ofs; y < inputheight; y++, line += row_inc)
44                                 for (x = 0, in = line + col_ofs; x < inputwidth; x++, in += col_inc, outpixels += numoutputcomponents)
45                                         for (c = 0; c < numoutputcomponents; c++)
46                                                 outpixels[c] = ((index = outputinputcomponentindices[c]) & 0x80000000) ? index : in[index];
47                 }
48         }
49         else
50         {
51                 // special indices not used
52                 if (inputflipdiagonal)
53                 {
54                         for (x = 0, line = inpixels + col_ofs; x < inputwidth; x++, line += col_inc)
55                                 for (y = 0, in = line + row_ofs; y < inputheight; y++, in += row_inc, outpixels += numoutputcomponents)
56                                         for (c = 0; c < numoutputcomponents; c++)
57                                                 outpixels[c] = in[outputinputcomponentindices[c]];
58                 }
59                 else
60                 {
61                         for (y = 0, line = inpixels + row_ofs; y < inputheight; y++, line += row_inc)
62                                 for (x = 0, in = line + col_ofs; x < inputwidth; x++, in += col_inc, outpixels += numoutputcomponents)
63                                         for (c = 0; c < numoutputcomponents; c++)
64                                                 outpixels[c] = in[outputinputcomponentindices[c]];
65                 }
66         }
67 }
68 #else
69 // intentionally readable version
70 void Image_CopyMux(unsigned char *outpixels, const unsigned char *inpixels, int inputwidth, int inputheight, qboolean inputflipx, qboolean inputflipy, qboolean inputflipdiagonal, int numoutputcomponents, int numinputcomponents, int *outputinputcomponentindices)
71 {
72         int index, c, x, y;
73         const unsigned char *in, *inrow, *incolumn;
74         if (inputflipdiagonal)
75         {
76                 for (x = 0;x < inputwidth;x++)
77                 {
78                         for (y = 0;y < inputheight;y++)
79                         {
80                                 in = inpixels + ((inputflipy ? inputheight - 1 - y : y) * inputwidth + (inputflipx ? inputwidth - 1 - x : x)) * numinputcomponents;
81                                 for (c = 0;c < numoutputcomponents;c++)
82                                 {
83                                         index = outputinputcomponentindices[c];
84                                         if (index & 0x80000000)
85                                                 *outpixels++ = index;
86                                         else
87                                                 *outpixels++ = in[index];
88                                 }
89                         }
90                 }
91         }
92         else
93         {
94                 for (y = 0;y < inputheight;y++)
95                 {
96                         for (x = 0;x < inputwidth;x++)
97                         {
98                                 in = inpixels + ((inputflipy ? inputheight - 1 - y : y) * inputwidth + (inputflipx ? inputwidth - 1 - x : x)) * numinputcomponents;
99                                 for (c = 0;c < numoutputcomponents;c++)
100                                 {
101                                         index = outputinputcomponentindices[c];
102                                         if (index & 0x80000000)
103                                                 *outpixels++ = index;
104                                         else
105                                                 *outpixels++ = in[index];
106                                 }
107                         }
108                 }
109         }
110 }
111 #endif
112
113 void Image_GammaRemapRGB(const unsigned char *in, unsigned char *out, int pixels, const unsigned char *gammar, const unsigned char *gammag, const unsigned char *gammab)
114 {
115         while (pixels--)
116         {
117                 out[0] = gammar[in[0]];
118                 out[1] = gammag[in[1]];
119                 out[2] = gammab[in[2]];
120                 in += 3;
121                 out += 3;
122         }
123 }
124
125 // note: pal must be 32bit color
126 void Image_Copy8bitBGRA(const unsigned char *in, unsigned char *out, int pixels, const unsigned int *pal)
127 {
128         int *iout = (int *)out;
129         while (pixels >= 8)
130         {
131                 iout[0] = pal[in[0]];
132                 iout[1] = pal[in[1]];
133                 iout[2] = pal[in[2]];
134                 iout[3] = pal[in[3]];
135                 iout[4] = pal[in[4]];
136                 iout[5] = pal[in[5]];
137                 iout[6] = pal[in[6]];
138                 iout[7] = pal[in[7]];
139                 in += 8;
140                 iout += 8;
141                 pixels -= 8;
142         }
143         if (pixels & 4)
144         {
145                 iout[0] = pal[in[0]];
146                 iout[1] = pal[in[1]];
147                 iout[2] = pal[in[2]];
148                 iout[3] = pal[in[3]];
149                 in += 4;
150                 iout += 4;
151         }
152         if (pixels & 2)
153         {
154                 iout[0] = pal[in[0]];
155                 iout[1] = pal[in[1]];
156                 in += 2;
157                 iout += 2;
158         }
159         if (pixels & 1)
160                 iout[0] = pal[in[0]];
161 }
162
163 /*
164 =================================================================
165
166   PCX Loading
167
168 =================================================================
169 */
170
171 typedef struct pcx_s
172 {
173     char        manufacturer;
174     char        version;
175     char        encoding;
176     char        bits_per_pixel;
177     unsigned short      xmin,ymin,xmax,ymax;
178     unsigned short      hres,vres;
179     unsigned char       palette[48];
180     char        reserved;
181     char        color_planes;
182     unsigned short      bytes_per_line;
183     unsigned short      palette_type;
184     char        filler[58];
185 } pcx_t;
186
187 /*
188 ============
189 LoadPCX
190 ============
191 */
192 static unsigned char* LoadPCX_BGRA (const unsigned char *f, int filesize, int *miplevel)
193 {
194         pcx_t pcx;
195         unsigned char *a, *b, *image_buffer, *pbuf;
196         const unsigned char *palette, *fin, *enddata;
197         int x, y, x2, dataByte;
198
199         if (filesize < (int)sizeof(pcx) + 768)
200         {
201                 Con_Print("Bad pcx file\n");
202                 return NULL;
203         }
204
205         fin = f;
206
207         memcpy(&pcx, fin, sizeof(pcx));
208         fin += sizeof(pcx);
209
210         // LordHavoc: big-endian support ported from QF newtree
211         pcx.xmax = LittleShort (pcx.xmax);
212         pcx.xmin = LittleShort (pcx.xmin);
213         pcx.ymax = LittleShort (pcx.ymax);
214         pcx.ymin = LittleShort (pcx.ymin);
215         pcx.hres = LittleShort (pcx.hres);
216         pcx.vres = LittleShort (pcx.vres);
217         pcx.bytes_per_line = LittleShort (pcx.bytes_per_line);
218         pcx.palette_type = LittleShort (pcx.palette_type);
219
220         image_width = pcx.xmax + 1 - pcx.xmin;
221         image_height = pcx.ymax + 1 - pcx.ymin;
222         if (pcx.manufacturer != 0x0a || pcx.version != 5 || pcx.encoding != 1 || pcx.bits_per_pixel != 8 || image_width > 32768 || image_height > 32768 || image_width <= 0 || image_height <= 0)
223         {
224                 Con_Print("Bad pcx file\n");
225                 return NULL;
226         }
227
228         palette = f + filesize - 768;
229
230         image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width*image_height*4);
231         if (!image_buffer)
232         {
233                 Con_Printf("LoadPCX: not enough memory for %i by %i image\n", image_width, image_height);
234                 return NULL;
235         }
236         pbuf = image_buffer + image_width*image_height*3;
237         enddata = palette;
238
239         for (y = 0;y < image_height && fin < enddata;y++)
240         {
241                 a = pbuf + y * image_width;
242                 for (x = 0;x < image_width && fin < enddata;)
243                 {
244                         dataByte = *fin++;
245                         if(dataByte >= 0xC0)
246                         {
247                                 if (fin >= enddata)
248                                         break;
249                                 x2 = x + (dataByte & 0x3F);
250                                 dataByte = *fin++;
251                                 if (x2 > image_width)
252                                         x2 = image_width; // technically an error
253                                 while(x < x2)
254                                         a[x++] = dataByte;
255                         }
256                         else
257                                 a[x++] = dataByte;
258                 }
259                 while(x < image_width)
260                         a[x++] = 0;
261         }
262
263         a = image_buffer;
264         b = pbuf;
265
266         for(x = 0;x < image_width*image_height;x++)
267         {
268                 y = *b++ * 3;
269                 *a++ = palette[y+2];
270                 *a++ = palette[y+1];
271                 *a++ = palette[y];
272                 *a++ = 255;
273         }
274
275         return image_buffer;
276 }
277
278 /*
279 ============
280 LoadPCX
281 ============
282 */
283 qboolean LoadPCX_QWSkin(const unsigned char *f, int filesize, unsigned char *pixels, int outwidth, int outheight)
284 {
285         pcx_t pcx;
286         unsigned char *a;
287         const unsigned char *fin, *enddata;
288         int x, y, x2, dataByte, pcxwidth, pcxheight;
289
290         if (filesize < (int)sizeof(pcx) + 768)
291                 return false;
292
293         image_width = outwidth;
294         image_height = outheight;
295         fin = f;
296
297         memcpy(&pcx, fin, sizeof(pcx));
298         fin += sizeof(pcx);
299
300         // LordHavoc: big-endian support ported from QF newtree
301         pcx.xmax = LittleShort (pcx.xmax);
302         pcx.xmin = LittleShort (pcx.xmin);
303         pcx.ymax = LittleShort (pcx.ymax);
304         pcx.ymin = LittleShort (pcx.ymin);
305         pcx.hres = LittleShort (pcx.hres);
306         pcx.vres = LittleShort (pcx.vres);
307         pcx.bytes_per_line = LittleShort (pcx.bytes_per_line);
308         pcx.palette_type = LittleShort (pcx.palette_type);
309
310         pcxwidth = pcx.xmax + 1 - pcx.xmin;
311         pcxheight = pcx.ymax + 1 - pcx.ymin;
312         if (pcx.manufacturer != 0x0a || pcx.version != 5 || pcx.encoding != 1 || pcx.bits_per_pixel != 8 || pcxwidth > 4096 || pcxheight > 4096 || pcxwidth <= 0 || pcxheight <= 0)
313                 return false;
314
315         enddata = f + filesize - 768;
316
317         for (y = 0;y < outheight && fin < enddata;y++)
318         {
319                 a = pixels + y * outwidth;
320                 // pad the output with blank lines if needed
321                 if (y >= pcxheight)
322                 {
323                         memset(a, 0, outwidth);
324                         continue;
325                 }
326                 for (x = 0;x < pcxwidth;)
327                 {
328                         if (fin >= enddata)
329                                 return false;
330                         dataByte = *fin++;
331                         if(dataByte >= 0xC0)
332                         {
333                                 x2 = x + (dataByte & 0x3F);
334                                 if (fin >= enddata)
335                                         return false;
336                                 if (x2 > pcxwidth)
337                                         return false;
338                                 dataByte = *fin++;
339                                 for (;x < x2;x++)
340                                         if (x < outwidth)
341                                                 a[x] = dataByte;
342                         }
343                         else
344                         {
345                                 if (x < outwidth) // truncate to destination width
346                                         a[x] = dataByte;
347                                 x++;
348                         }
349                 }
350                 while(x < outwidth)
351                         a[x++] = 0;
352         }
353
354         return true;
355 }
356
357 /*
358 =========================================================
359
360 TARGA LOADING
361
362 =========================================================
363 */
364
365 typedef struct _TargaHeader
366 {
367         unsigned char   id_length, colormap_type, image_type;
368         unsigned short  colormap_index, colormap_length;
369         unsigned char   colormap_size;
370         unsigned short  x_origin, y_origin, width, height;
371         unsigned char   pixel_size, attributes;
372 }
373 TargaHeader;
374
375 static void PrintTargaHeader(TargaHeader *t)
376 {
377         Con_Printf("TargaHeader:\nuint8 id_length = %i;\nuint8 colormap_type = %i;\nuint8 image_type = %i;\nuint16 colormap_index = %i;\nuint16 colormap_length = %i;\nuint8 colormap_size = %i;\nuint16 x_origin = %i;\nuint16 y_origin = %i;\nuint16 width = %i;\nuint16 height = %i;\nuint8 pixel_size = %i;\nuint8 attributes = %i;\n", t->id_length, t->colormap_type, t->image_type, t->colormap_index, t->colormap_length, t->colormap_size, t->x_origin, t->y_origin, t->width, t->height, t->pixel_size, t->attributes);
378 }
379
380 /*
381 =============
382 LoadTGA
383 =============
384 */
385 unsigned char *LoadTGA_BGRA (const unsigned char *f, int filesize, int *miplevel)
386 {
387         int x, y, pix_inc, row_inci, runlen, alphabits;
388         unsigned char *image_buffer;
389         unsigned int *pixbufi;
390         const unsigned char *fin, *enddata;
391         TargaHeader targa_header;
392         unsigned int palettei[256];
393         union
394         {
395                 unsigned int i;
396                 unsigned char b[4];
397         }
398         bgra;
399
400         if (filesize < 19)
401                 return NULL;
402
403         enddata = f + filesize;
404
405         targa_header.id_length = f[0];
406         targa_header.colormap_type = f[1];
407         targa_header.image_type = f[2];
408
409         targa_header.colormap_index = f[3] + f[4] * 256;
410         targa_header.colormap_length = f[5] + f[6] * 256;
411         targa_header.colormap_size = f[7];
412         targa_header.x_origin = f[8] + f[9] * 256;
413         targa_header.y_origin = f[10] + f[11] * 256;
414         targa_header.width = image_width = f[12] + f[13] * 256;
415         targa_header.height = image_height = f[14] + f[15] * 256;
416         targa_header.pixel_size = f[16];
417         targa_header.attributes = f[17];
418
419         if (image_width > 32768 || image_height > 32768 || image_width <= 0 || image_height <= 0)
420         {
421                 Con_Print("LoadTGA: invalid size\n");
422                 PrintTargaHeader(&targa_header);
423                 return NULL;
424         }
425
426         // advance to end of header
427         fin = f + 18;
428
429         // skip TARGA image comment (usually 0 bytes)
430         fin += targa_header.id_length;
431
432         // read/skip the colormap if present (note: according to the TARGA spec it
433         // can be present even on truecolor or greyscale images, just not used by
434         // the image data)
435         if (targa_header.colormap_type)
436         {
437                 if (targa_header.colormap_length > 256)
438                 {
439                         Con_Print("LoadTGA: only up to 256 colormap_length supported\n");
440                         PrintTargaHeader(&targa_header);
441                         return NULL;
442                 }
443                 if (targa_header.colormap_index)
444                 {
445                         Con_Print("LoadTGA: colormap_index not supported\n");
446                         PrintTargaHeader(&targa_header);
447                         return NULL;
448                 }
449                 if (targa_header.colormap_size == 24)
450                 {
451                         for (x = 0;x < targa_header.colormap_length;x++)
452                         {
453                                 bgra.b[0] = *fin++;
454                                 bgra.b[1] = *fin++;
455                                 bgra.b[2] = *fin++;
456                                 bgra.b[3] = 255;
457                                 palettei[x] = bgra.i;
458                         }
459                 }
460                 else if (targa_header.colormap_size == 32)
461                 {
462                         memcpy(palettei, fin, targa_header.colormap_length*4);
463                         fin += targa_header.colormap_length * 4;
464                 }
465                 else
466                 {
467                         Con_Print("LoadTGA: Only 32 and 24 bit colormap_size supported\n");
468                         PrintTargaHeader(&targa_header);
469                         return NULL;
470                 }
471         }
472
473         // check our pixel_size restrictions according to image_type
474         switch (targa_header.image_type & ~8)
475         {
476         case 2:
477                 if (targa_header.pixel_size != 24 && targa_header.pixel_size != 32)
478                 {
479                         Con_Print("LoadTGA: only 24bit and 32bit pixel sizes supported for type 2 and type 10 images\n");
480                         PrintTargaHeader(&targa_header);
481                         return NULL;
482                 }
483                 break;
484         case 3:
485                 // set up a palette to make the loader easier
486                 for (x = 0;x < 256;x++)
487                 {
488                         bgra.b[0] = bgra.b[1] = bgra.b[2] = x;
489                         bgra.b[3] = 255;
490                         palettei[x] = bgra.i;
491                 }
492                 // fall through to colormap case
493         case 1:
494                 if (targa_header.pixel_size != 8)
495                 {
496                         Con_Print("LoadTGA: only 8bit pixel size for type 1, 3, 9, and 11 images supported\n");
497                         PrintTargaHeader(&targa_header);
498                         return NULL;
499                 }
500                 break;
501         default:
502                 Con_Printf("LoadTGA: Only type 1, 2, 3, 9, 10, and 11 targa RGB images supported, image_type = %i\n", targa_header.image_type);
503                 PrintTargaHeader(&targa_header);
504                 return NULL;
505         }
506
507         if (targa_header.attributes & 0x10)
508         {
509                 Con_Print("LoadTGA: origin must be in top left or bottom left, top right and bottom right are not supported\n");
510                 return NULL;
511         }
512
513         // number of attribute bits per pixel, we only support 0 or 8
514         alphabits = targa_header.attributes & 0x0F;
515         if (alphabits != 8 && alphabits != 0)
516         {
517                 Con_Print("LoadTGA: only 0 or 8 attribute (alpha) bits supported\n");
518                 return NULL;
519         }
520
521         image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
522         if (!image_buffer)
523         {
524                 Con_Printf("LoadTGA: not enough memory for %i by %i image\n", image_width, image_height);
525                 return NULL;
526         }
527
528         // If bit 5 of attributes isn't set, the image has been stored from bottom to top
529         if ((targa_header.attributes & 0x20) == 0)
530         {
531                 pixbufi = (unsigned int*)image_buffer + (image_height - 1)*image_width;
532                 row_inci = -image_width*2;
533         }
534         else
535         {
536                 pixbufi = (unsigned int*)image_buffer;
537                 row_inci = 0;
538         }
539
540         pix_inc = 1;
541         if ((targa_header.image_type & ~8) == 2)
542                 pix_inc = (targa_header.pixel_size + 7) / 8;
543         switch (targa_header.image_type)
544         {
545         case 1: // colormapped, uncompressed
546         case 3: // greyscale, uncompressed
547                 if (fin + image_width * image_height * pix_inc > enddata)
548                         break;
549                 for (y = 0;y < image_height;y++, pixbufi += row_inci)
550                         for (x = 0;x < image_width;x++)
551                                 *pixbufi++ = palettei[*fin++];
552                 break;
553         case 2:
554                 // BGR or BGRA, uncompressed
555                 if (fin + image_width * image_height * pix_inc > enddata)
556                         break;
557                 if (targa_header.pixel_size == 32 && alphabits)
558                 {
559                         for (y = 0;y < image_height;y++)
560                                 memcpy(pixbufi + y * (image_width + row_inci), fin + y * image_width * pix_inc, image_width*4);
561                 }
562                 else
563                 {
564                         for (y = 0;y < image_height;y++, pixbufi += row_inci)
565                         {
566                                 for (x = 0;x < image_width;x++, fin += pix_inc)
567                                 {
568                                         bgra.b[0] = fin[0];
569                                         bgra.b[1] = fin[1];
570                                         bgra.b[2] = fin[2];
571                                         bgra.b[3] = 255;
572                                         *pixbufi++ = bgra.i;
573                                 }
574                         }
575                 }
576                 break;
577         case 9: // colormapped, RLE
578         case 11: // greyscale, RLE
579                 for (y = 0;y < image_height;y++, pixbufi += row_inci)
580                 {
581                         for (x = 0;x < image_width;)
582                         {
583                                 if (fin >= enddata)
584                                         break; // error - truncated file
585                                 runlen = *fin++;
586                                 if (runlen & 0x80)
587                                 {
588                                         // RLE - all pixels the same color
589                                         runlen += 1 - 0x80;
590                                         if (fin + pix_inc > enddata)
591                                                 break; // error - truncated file
592                                         if (x + runlen > image_width)
593                                                 break; // error - line exceeds width
594                                         bgra.i = palettei[*fin++];
595                                         for (;runlen--;x++)
596                                                 *pixbufi++ = bgra.i;
597                                 }
598                                 else
599                                 {
600                                         // uncompressed - all pixels different color
601                                         runlen++;
602                                         if (fin + pix_inc * runlen > enddata)
603                                                 break; // error - truncated file
604                                         if (x + runlen > image_width)
605                                                 break; // error - line exceeds width
606                                         for (;runlen--;x++)
607                                                 *pixbufi++ = palettei[*fin++];
608                                 }
609                         }
610
611                         if (x != image_width)
612                         {
613                                 // pixbufi is useless now
614                                 Con_Printf("LoadTGA: corrupt file\n");
615                                 break;
616                         }
617                 }
618                 break;
619         case 10:
620                 // BGR or BGRA, RLE
621                 if (targa_header.pixel_size == 32 && alphabits)
622                 {
623                         for (y = 0;y < image_height;y++, pixbufi += row_inci)
624                         {
625                                 for (x = 0;x < image_width;)
626                                 {
627                                         if (fin >= enddata)
628                                                 break; // error - truncated file
629                                         runlen = *fin++;
630                                         if (runlen & 0x80)
631                                         {
632                                                 // RLE - all pixels the same color
633                                                 runlen += 1 - 0x80;
634                                                 if (fin + pix_inc > enddata)
635                                                         break; // error - truncated file
636                                                 if (x + runlen > image_width)
637                                                         break; // error - line exceeds width
638                                                 bgra.b[0] = fin[0];
639                                                 bgra.b[1] = fin[1];
640                                                 bgra.b[2] = fin[2];
641                                                 bgra.b[3] = fin[3];
642                                                 fin += pix_inc;
643                                                 for (;runlen--;x++)
644                                                         *pixbufi++ = bgra.i;
645                                         }
646                                         else
647                                         {
648                                                 // uncompressed - all pixels different color
649                                                 runlen++;
650                                                 if (fin + pix_inc * runlen > enddata)
651                                                         break; // error - truncated file
652                                                 if (x + runlen > image_width)
653                                                         break; // error - line exceeds width
654                                                 for (;runlen--;x++)
655                                                 {
656                                                         bgra.b[0] = fin[0];
657                                                         bgra.b[1] = fin[1];
658                                                         bgra.b[2] = fin[2];
659                                                         bgra.b[3] = fin[3];
660                                                         fin += pix_inc;
661                                                         *pixbufi++ = bgra.i;
662                                                 }
663                                         }
664                                 }
665
666                                 if (x != image_width)
667                                 {
668                                         // pixbufi is useless now
669                                         Con_Printf("LoadTGA: corrupt file\n");
670                                         break;
671                                 }
672                         }
673                 }
674                 else
675                 {
676                         for (y = 0;y < image_height;y++, pixbufi += row_inci)
677                         {
678                                 for (x = 0;x < image_width;)
679                                 {
680                                         if (fin >= enddata)
681                                                 break; // error - truncated file
682                                         runlen = *fin++;
683                                         if (runlen & 0x80)
684                                         {
685                                                 // RLE - all pixels the same color
686                                                 runlen += 1 - 0x80;
687                                                 if (fin + pix_inc > enddata)
688                                                         break; // error - truncated file
689                                                 if (x + runlen > image_width)
690                                                         break; // error - line exceeds width
691                                                 bgra.b[0] = fin[0];
692                                                 bgra.b[1] = fin[1];
693                                                 bgra.b[2] = fin[2];
694                                                 bgra.b[3] = 255;
695                                                 fin += pix_inc;
696                                                 for (;runlen--;x++)
697                                                         *pixbufi++ = bgra.i;
698                                         }
699                                         else
700                                         {
701                                                 // uncompressed - all pixels different color
702                                                 runlen++;
703                                                 if (fin + pix_inc * runlen > enddata)
704                                                         break; // error - truncated file
705                                                 if (x + runlen > image_width)
706                                                         break; // error - line exceeds width
707                                                 for (;runlen--;x++)
708                                                 {
709                                                         bgra.b[0] = fin[0];
710                                                         bgra.b[1] = fin[1];
711                                                         bgra.b[2] = fin[2];
712                                                         bgra.b[3] = 255;
713                                                         fin += pix_inc;
714                                                         *pixbufi++ = bgra.i;
715                                                 }
716                                         }
717                                 }
718
719                                 if (x != image_width)
720                                 {
721                                         // pixbufi is useless now
722                                         Con_Printf("LoadTGA: corrupt file\n");
723                                         break;
724                                 }
725                         }
726                 }
727                 break;
728         default:
729                 // unknown image_type
730                 break;
731         }
732
733         return image_buffer;
734 }
735
736 typedef struct q2wal_s
737 {
738         char            name[32];
739         unsigned        width, height;
740         unsigned        offsets[MIPLEVELS];             // four mip maps stored
741         char            animname[32];                   // next frame in animation chain
742         int                     flags;
743         int                     contents;
744         int                     value;
745 } q2wal_t;
746
747 static unsigned char *LoadWAL_BGRA (const unsigned char *f, int filesize, int *miplevel)
748 {
749         unsigned char *image_buffer;
750         const q2wal_t *inwal = (const q2wal_t *)f;
751
752         if (filesize < (int) sizeof(q2wal_t))
753         {
754                 Con_Print("LoadWAL: invalid WAL file\n");
755                 return NULL;
756         }
757
758         image_width = LittleLong(inwal->width);
759         image_height = LittleLong(inwal->height);
760         if (image_width > 32768 || image_height > 32768 || image_width <= 0 || image_height <= 0)
761         {
762                 Con_Printf("LoadWAL: invalid size %ix%i\n", image_width, image_height);
763                 return NULL;
764         }
765
766         if (filesize < (int) sizeof(q2wal_t) + (int) LittleLong(inwal->offsets[0]) + image_width * image_height)
767         {
768                 Con_Print("LoadWAL: invalid WAL file\n");
769                 return NULL;
770         }
771
772         image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
773         if (!image_buffer)
774         {
775                 Con_Printf("LoadWAL: not enough memory for %i by %i image\n", image_width, image_height);
776                 return NULL;
777         }
778         Image_Copy8bitBGRA(f + LittleLong(inwal->offsets[0]), image_buffer, image_width * image_height, palette_bgra_complete);
779         return image_buffer;
780 }
781
782
783 void Image_StripImageExtension (const char *in, char *out, size_t size_out)
784 {
785         const char *ext;
786
787         if (size_out == 0)
788                 return;
789
790         ext = FS_FileExtension(in);
791         if (ext && (!strcmp(ext, "tga") || !strcmp(ext, "pcx") || !strcmp(ext, "lmp") || !strcmp(ext, "png") || !strcmp(ext, "jpg")))
792                 FS_StripExtension(in, out, size_out);
793         else
794                 strlcpy(out, in, size_out);
795 }
796
797 static unsigned char image_linearfromsrgb[256];
798 static unsigned char image_srgbfromlinear_lightmap[256];
799
800 void Image_MakeLinearColorsFromsRGB(unsigned char *pout, const unsigned char *pin, int numpixels)
801 {
802         int i;
803         // this math from http://www.opengl.org/registry/specs/EXT/texture_sRGB.txt
804         if (!image_linearfromsrgb[255])
805                 for (i = 0;i < 256;i++)
806                         image_linearfromsrgb[i] = (unsigned char)floor(Image_LinearFloatFromsRGB(i) * 255.0f + 0.5f);
807         for (i = 0;i < numpixels;i++)
808         {
809                 pout[i*4+0] = image_linearfromsrgb[pin[i*4+0]];
810                 pout[i*4+1] = image_linearfromsrgb[pin[i*4+1]];
811                 pout[i*4+2] = image_linearfromsrgb[pin[i*4+2]];
812                 pout[i*4+3] = pin[i*4+3];
813         }
814 }
815
816 void Image_MakesRGBColorsFromLinear_Lightmap(unsigned char *pout, const unsigned char *pin, int numpixels)
817 {
818         int i;
819         // this math from http://www.opengl.org/registry/specs/EXT/texture_sRGB.txt
820         if (!image_srgbfromlinear_lightmap[255])
821                 for (i = 0;i < 256;i++)
822                         image_srgbfromlinear_lightmap[i] = (unsigned char)floor(bound(0.0f, Image_sRGBFloatFromLinear_Lightmap(i), 1.0f) * 255.0f + 0.5f);
823         for (i = 0;i < numpixels;i++)
824         {
825                 pout[i*4+0] = image_srgbfromlinear_lightmap[pin[i*4+0]];
826                 pout[i*4+1] = image_srgbfromlinear_lightmap[pin[i*4+1]];
827                 pout[i*4+2] = image_srgbfromlinear_lightmap[pin[i*4+2]];
828                 pout[i*4+3] = pin[i*4+3];
829         }
830 }
831
832 typedef struct imageformat_s
833 {
834         const char *formatstring;
835         unsigned char *(*loadfunc)(const unsigned char *f, int filesize, int *miplevel);
836 }
837 imageformat_t;
838
839 // GAME_TENEBRAE only
840 imageformat_t imageformats_tenebrae[] =
841 {
842         {"override/%s.tga", LoadTGA_BGRA},
843         {"override/%s.png", PNG_LoadImage_BGRA},
844         {"override/%s.jpg", JPEG_LoadImage_BGRA},
845         {"override/%s.pcx", LoadPCX_BGRA},
846         {"%s.tga", LoadTGA_BGRA},
847         {"%s.png", PNG_LoadImage_BGRA},
848         {"%s.jpg", JPEG_LoadImage_BGRA},
849         {"%s.pcx", LoadPCX_BGRA},
850         {NULL, NULL}
851 };
852
853 imageformat_t imageformats_nopath[] =
854 {
855         {"override/%s.tga", LoadTGA_BGRA},
856         {"override/%s.png", PNG_LoadImage_BGRA},
857         {"override/%s.jpg", JPEG_LoadImage_BGRA},
858         {"textures/%s.tga", LoadTGA_BGRA},
859         {"textures/%s.png", PNG_LoadImage_BGRA},
860         {"textures/%s.jpg", JPEG_LoadImage_BGRA},
861         {"%s.tga", LoadTGA_BGRA},
862         {"%s.png", PNG_LoadImage_BGRA},
863         {"%s.jpg", JPEG_LoadImage_BGRA},
864         {"%s.pcx", LoadPCX_BGRA},
865         {NULL, NULL}
866 };
867
868 // GAME_DELUXEQUAKE only
869 // VorteX: the point why i use such messy texture paths is
870 // that GtkRadiant can't detect normal/gloss textures
871 // and exclude them from texture browser
872 // so i just use additional folder to store this textures
873 imageformat_t imageformats_dq[] =
874 {
875         {"%s.tga", LoadTGA_BGRA},
876         {"%s.jpg", JPEG_LoadImage_BGRA},
877         {"texturemaps/%s.tga", LoadTGA_BGRA},
878         {"texturemaps/%s.jpg", JPEG_LoadImage_BGRA},
879         {NULL, NULL}
880 };
881
882 imageformat_t imageformats_textures[] =
883 {
884         {"%s.tga", LoadTGA_BGRA},
885         {"%s.png", PNG_LoadImage_BGRA},
886         {"%s.jpg", JPEG_LoadImage_BGRA},
887         {"%s.pcx", LoadPCX_BGRA},
888         {"%s.wal", LoadWAL_BGRA},
889         {NULL, NULL}
890 };
891
892 imageformat_t imageformats_gfx[] =
893 {
894         {"%s.tga", LoadTGA_BGRA},
895         {"%s.png", PNG_LoadImage_BGRA},
896         {"%s.jpg", JPEG_LoadImage_BGRA},
897         {"%s.pcx", LoadPCX_BGRA},
898         {NULL, NULL}
899 };
900
901 imageformat_t imageformats_other[] =
902 {
903         {"%s.tga", LoadTGA_BGRA},
904         {"%s.png", PNG_LoadImage_BGRA},
905         {"%s.jpg", JPEG_LoadImage_BGRA},
906         {"%s.pcx", LoadPCX_BGRA},
907         {NULL, NULL}
908 };
909
910 int fixtransparentpixels(unsigned char *data, int w, int h);
911 unsigned char *loadimagepixelsbgra (const char *filename, qboolean complain, qboolean allowFixtrans, qboolean convertsRGB, int *miplevel)
912 {
913         fs_offset_t filesize;
914         imageformat_t *firstformat, *format;
915         unsigned char *f, *data = NULL, *data2 = NULL;
916         char basename[MAX_QPATH], name[MAX_QPATH], name2[MAX_QPATH], *c;
917         char vabuf[1024];
918         //if (developer_memorydebug.integer)
919         //      Mem_CheckSentinelsGlobal();
920         if (developer_texturelogging.integer)
921                 Log_Printf("textures.log", "%s\n", filename);
922         Image_StripImageExtension(filename, basename, sizeof(basename)); // strip filename extensions to allow replacement by other types
923         // replace *'s with #, so commandline utils don't get confused when dealing with the external files
924         for (c = basename;*c;c++)
925                 if (*c == '*')
926                         *c = '#';
927         name[0] = 0;
928         if (strchr(basename, '/'))
929         {
930                 int i;
931                 for (i = 0;i < (int)sizeof(name)-1 && basename[i] != '/';i++)
932                         name[i] = basename[i];
933                 name[i] = 0;
934         }
935         if (gamemode == GAME_TENEBRAE)
936                 firstformat = imageformats_tenebrae;
937         else if (gamemode == GAME_DELUXEQUAKE)
938                 firstformat = imageformats_dq;
939         else if (!strcasecmp(name, "textures"))
940                 firstformat = imageformats_textures;
941         else if (!strcasecmp(name, "gfx"))
942                 firstformat = imageformats_gfx;
943         else if (!strchr(basename, '/'))
944                 firstformat = imageformats_nopath;
945         else
946                 firstformat = imageformats_other;
947         // now try all the formats in the selected list
948         for (format = firstformat;format->formatstring;format++)
949         {
950                 dpsnprintf (name, sizeof(name), format->formatstring, basename);
951                 f = FS_LoadFile(name, tempmempool, true, &filesize);
952                 if (f)
953                 {
954                         int mymiplevel = miplevel ? *miplevel : 0;
955                         data = format->loadfunc(f, (int)filesize, &mymiplevel);
956                         Mem_Free(f);
957                         if (data)
958                         {
959                                 if(format->loadfunc == JPEG_LoadImage_BGRA) // jpeg can't do alpha, so let's simulate it by loading another jpeg
960                                 {
961                                         dpsnprintf (name2, sizeof(name2), format->formatstring, va(vabuf, sizeof(vabuf), "%s_alpha", basename));
962                                         f = FS_LoadFile(name2, tempmempool, true, &filesize);
963                                         if(f)
964                                         {
965                                                 int mymiplevel2 = miplevel ? *miplevel : 0;
966                                                 data2 = format->loadfunc(f, (int)filesize, &mymiplevel2);
967                                                 if(data2 && mymiplevel == mymiplevel2)
968                                                         Image_CopyAlphaFromBlueBGRA(data, data2, image_width, image_height);
969                                                 else
970                                                         Con_Printf("loadimagepixelsrgba: corrupt or invalid alpha image %s_alpha\n", basename);
971                                                 if(data2)
972                                                         Mem_Free(data2);
973                                                 Mem_Free(f);
974                                         }
975                                 }
976                                 if (developer_loading.integer)
977                                         Con_DPrintf("loaded image %s (%dx%d)\n", name, image_width, image_height);
978                                 if(miplevel)
979                                         *miplevel = mymiplevel;
980                                 //if (developer_memorydebug.integer)
981                                 //      Mem_CheckSentinelsGlobal();
982                                 if(allowFixtrans && r_fixtrans_auto.integer)
983                                 {
984                                         int n = fixtransparentpixels(data, image_width, image_height);
985                                         if(n)
986                                         {
987                                                 Con_Printf("- had to fix %s (%d pixels changed)\n", name, n);
988                                                 if(r_fixtrans_auto.integer >= 2)
989                                                 {
990                                                         char outfilename[MAX_QPATH], buf[MAX_QPATH];
991                                                         Image_StripImageExtension(name, buf, sizeof(buf));
992                                                         dpsnprintf(outfilename, sizeof(outfilename), "fixtrans/%s.tga", buf);
993                                                         Image_WriteTGABGRA(outfilename, image_width, image_height, data);
994                                                         Con_Printf("- %s written.\n", outfilename);
995                                                 }
996                                         }
997                                 }
998                                 if (convertsRGB)
999                                         Image_MakeLinearColorsFromsRGB(data, data, image_width * image_height);
1000                                 return data;
1001                         }
1002                         else
1003                                 Con_DPrintf("Error loading image %s (file loaded but decode failed)\n", name);
1004                 }
1005         }
1006         if (complain)
1007         {
1008                 Con_Printf("Couldn't load %s using ", filename);
1009                 for (format = firstformat;format->formatstring;format++)
1010                 {
1011                         dpsnprintf (name, sizeof(name), format->formatstring, basename);
1012                         Con_Printf(format == firstformat ? "\"%s\"" : (format[1].formatstring ? ", \"%s\"" : " or \"%s\".\n"), format->formatstring);
1013                 }
1014         }
1015
1016         // texture loading can take a while, so make sure we're sending keepalives
1017         CL_KeepaliveMessage(false);
1018
1019         //if (developer_memorydebug.integer)
1020         //      Mem_CheckSentinelsGlobal();
1021         return NULL;
1022 }
1023
1024 extern cvar_t gl_picmip;
1025 rtexture_t *loadtextureimage (rtexturepool_t *pool, const char *filename, qboolean complain, int flags, qboolean allowFixtrans, qboolean sRGB)
1026 {
1027         unsigned char *data;
1028         rtexture_t *rt;
1029         int miplevel = R_PicmipForFlags(flags);
1030         if (!(data = loadimagepixelsbgra (filename, complain, allowFixtrans, false, &miplevel)))
1031                 return 0;
1032         rt = R_LoadTexture2D(pool, filename, image_width, image_height, data, sRGB ? TEXTYPE_SRGB_BGRA : TEXTYPE_BGRA, flags, miplevel, NULL);
1033         Mem_Free(data);
1034         return rt;
1035 }
1036
1037 int fixtransparentpixels(unsigned char *data, int w, int h)
1038 {
1039         int const FIXTRANS_NEEDED = 1;
1040         int const FIXTRANS_HAS_L = 2;
1041         int const FIXTRANS_HAS_R = 4;
1042         int const FIXTRANS_HAS_U = 8;
1043         int const FIXTRANS_HAS_D = 16;
1044         int const FIXTRANS_FIXED = 32;
1045         unsigned char *fixMask = (unsigned char *) Mem_Alloc(tempmempool, w * h);
1046         int fixPixels = 0;
1047         int changedPixels = 0;
1048         int x, y;
1049
1050 #define FIXTRANS_PIXEL (y*w+x)
1051 #define FIXTRANS_PIXEL_U (((y+h-1)%h)*w+x)
1052 #define FIXTRANS_PIXEL_D (((y+1)%h)*w+x)
1053 #define FIXTRANS_PIXEL_L (y*w+((x+w-1)%w))
1054 #define FIXTRANS_PIXEL_R (y*w+((x+1)%w))
1055
1056         memset(fixMask, 0, w * h);
1057         for(y = 0; y < h; ++y)
1058                 for(x = 0; x < w; ++x)
1059                 {
1060                         if(data[FIXTRANS_PIXEL * 4 + 3] == 0)
1061                         {
1062                                 fixMask[FIXTRANS_PIXEL] |= FIXTRANS_NEEDED;
1063                                 ++fixPixels;
1064                         }
1065                         else
1066                         {
1067                                 fixMask[FIXTRANS_PIXEL_D] |= FIXTRANS_HAS_U;
1068                                 fixMask[FIXTRANS_PIXEL_U] |= FIXTRANS_HAS_D;
1069                                 fixMask[FIXTRANS_PIXEL_R] |= FIXTRANS_HAS_L;
1070                                 fixMask[FIXTRANS_PIXEL_L] |= FIXTRANS_HAS_R;
1071                         }
1072                 }
1073         if(fixPixels == w * h)
1074                 return 0; // sorry, can't do anything about this
1075         while(fixPixels)
1076         {
1077                 for(y = 0; y < h; ++y)
1078                         for(x = 0; x < w; ++x)
1079                                 if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_NEEDED)
1080                                 {
1081                                         unsigned int sumR = 0, sumG = 0, sumB = 0, sumA = 0, sumRA = 0, sumGA = 0, sumBA = 0, cnt = 0;
1082                                         unsigned char r, g, b, a, r0, g0, b0;
1083                                         if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_HAS_U)
1084                                         {
1085                                                 r = data[FIXTRANS_PIXEL_U * 4 + 2];
1086                                                 g = data[FIXTRANS_PIXEL_U * 4 + 1];
1087                                                 b = data[FIXTRANS_PIXEL_U * 4 + 0];
1088                                                 a = data[FIXTRANS_PIXEL_U * 4 + 3];
1089                                                 sumR += r; sumG += g; sumB += b; sumA += a; sumRA += r*a; sumGA += g*a; sumBA += b*a; ++cnt;
1090                                         }
1091                                         if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_HAS_D)
1092                                         {
1093                                                 r = data[FIXTRANS_PIXEL_D * 4 + 2];
1094                                                 g = data[FIXTRANS_PIXEL_D * 4 + 1];
1095                                                 b = data[FIXTRANS_PIXEL_D * 4 + 0];
1096                                                 a = data[FIXTRANS_PIXEL_D * 4 + 3];
1097                                                 sumR += r; sumG += g; sumB += b; sumA += a; sumRA += r*a; sumGA += g*a; sumBA += b*a; ++cnt;
1098                                         }
1099                                         if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_HAS_L)
1100                                         {
1101                                                 r = data[FIXTRANS_PIXEL_L * 4 + 2];
1102                                                 g = data[FIXTRANS_PIXEL_L * 4 + 1];
1103                                                 b = data[FIXTRANS_PIXEL_L * 4 + 0];
1104                                                 a = data[FIXTRANS_PIXEL_L * 4 + 3];
1105                                                 sumR += r; sumG += g; sumB += b; sumA += a; sumRA += r*a; sumGA += g*a; sumBA += b*a; ++cnt;
1106                                         }
1107                                         if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_HAS_R)
1108                                         {
1109                                                 r = data[FIXTRANS_PIXEL_R * 4 + 2];
1110                                                 g = data[FIXTRANS_PIXEL_R * 4 + 1];
1111                                                 b = data[FIXTRANS_PIXEL_R * 4 + 0];
1112                                                 a = data[FIXTRANS_PIXEL_R * 4 + 3];
1113                                                 sumR += r; sumG += g; sumB += b; sumA += a; sumRA += r*a; sumGA += g*a; sumBA += b*a; ++cnt;
1114                                         }
1115                                         if(!cnt)
1116                                                 continue;
1117                                         r0 = data[FIXTRANS_PIXEL * 4 + 2];
1118                                         g0 = data[FIXTRANS_PIXEL * 4 + 1];
1119                                         b0 = data[FIXTRANS_PIXEL * 4 + 0];
1120                                         if(sumA)
1121                                         {
1122                                                 // there is a surrounding non-alpha pixel
1123                                                 r = (sumRA + sumA / 2) / sumA;
1124                                                 g = (sumGA + sumA / 2) / sumA;
1125                                                 b = (sumBA + sumA / 2) / sumA;
1126                                         }
1127                                         else
1128                                         {
1129                                                 // need to use a "regular" average
1130                                                 r = (sumR + cnt / 2) / cnt;
1131                                                 g = (sumG + cnt / 2) / cnt;
1132                                                 b = (sumB + cnt / 2) / cnt;
1133                                         }
1134                                         if(r != r0 || g != g0 || b != b0)
1135                                                 ++changedPixels;
1136                                         data[FIXTRANS_PIXEL * 4 + 2] = r;
1137                                         data[FIXTRANS_PIXEL * 4 + 1] = g;
1138                                         data[FIXTRANS_PIXEL * 4 + 0] = b;
1139                                         fixMask[FIXTRANS_PIXEL] |= FIXTRANS_FIXED;
1140                                 }
1141                 for(y = 0; y < h; ++y)
1142                         for(x = 0; x < w; ++x)
1143                                 if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_FIXED)
1144                                 {
1145                                         fixMask[FIXTRANS_PIXEL] &= ~(FIXTRANS_NEEDED | FIXTRANS_FIXED);
1146                                         fixMask[FIXTRANS_PIXEL_D] |= FIXTRANS_HAS_U;
1147                                         fixMask[FIXTRANS_PIXEL_U] |= FIXTRANS_HAS_D;
1148                                         fixMask[FIXTRANS_PIXEL_R] |= FIXTRANS_HAS_L;
1149                                         fixMask[FIXTRANS_PIXEL_L] |= FIXTRANS_HAS_R;
1150                                         --fixPixels;
1151                                 }
1152         }
1153         return changedPixels;
1154 }
1155
1156 void Image_FixTransparentPixels_f(void)
1157 {
1158         const char *filename, *filename_pattern;
1159         fssearch_t *search;
1160         int i, n;
1161         char outfilename[MAX_QPATH], buf[MAX_QPATH];
1162         unsigned char *data;
1163         if(Cmd_Argc() != 2)
1164         {
1165                 Con_Printf("Usage: %s imagefile\n", Cmd_Argv(0));
1166                 return;
1167         }
1168         filename_pattern = Cmd_Argv(1);
1169         search = FS_Search(filename_pattern, true, true);
1170         if(!search)
1171                 return;
1172         for(i = 0; i < search->numfilenames; ++i)
1173         {
1174                 filename = search->filenames[i];
1175                 Con_Printf("Processing %s... ", filename);
1176                 Image_StripImageExtension(filename, buf, sizeof(buf));
1177                 dpsnprintf(outfilename, sizeof(outfilename), "fixtrans/%s.tga", buf);
1178                 if(!(data = loadimagepixelsbgra(filename, true, false, false, NULL)))
1179                         return;
1180                 if((n = fixtransparentpixels(data, image_width, image_height)))
1181                 {
1182                         Image_WriteTGABGRA(outfilename, image_width, image_height, data);
1183                         Con_Printf("%s written (%d pixels changed).\n", outfilename, n);
1184                 }
1185                 else
1186                         Con_Printf("unchanged.\n");
1187                 Mem_Free(data);
1188         }
1189         FS_FreeSearch(search);
1190 }
1191
1192 qboolean Image_WriteTGABGR_preflipped (const char *filename, int width, int height, const unsigned char *data)
1193 {
1194         qboolean ret;
1195         unsigned char buffer[18];
1196         const void *buffers[2];
1197         fs_offset_t sizes[2];
1198
1199         memset (buffer, 0, 18);
1200         buffer[2] = 2;          // uncompressed type
1201         buffer[12] = (width >> 0) & 0xFF;
1202         buffer[13] = (width >> 8) & 0xFF;
1203         buffer[14] = (height >> 0) & 0xFF;
1204         buffer[15] = (height >> 8) & 0xFF;
1205         buffer[16] = 24;        // pixel size
1206
1207         buffers[0] = buffer;
1208         sizes[0] = 18;
1209         buffers[1] = data;
1210         sizes[1] = width*height*3;
1211         ret = FS_WriteFileInBlocks(filename, buffers, sizes, 2);
1212
1213         return ret;
1214 }
1215
1216 qboolean Image_WriteTGABGRA (const char *filename, int width, int height, const unsigned char *data)
1217 {
1218         int y;
1219         unsigned char *buffer, *out;
1220         const unsigned char *in, *end;
1221         qboolean ret;
1222
1223         buffer = (unsigned char *)Mem_Alloc(tempmempool, width*height*4 + 18);
1224
1225         memset (buffer, 0, 18);
1226         buffer[2] = 2;          // uncompressed type
1227         buffer[12] = (width >> 0) & 0xFF;
1228         buffer[13] = (width >> 8) & 0xFF;
1229         buffer[14] = (height >> 0) & 0xFF;
1230         buffer[15] = (height >> 8) & 0xFF;
1231
1232         for (y = 3;y < width*height*4;y += 4)
1233                 if (data[y] < 255)
1234                         break;
1235
1236         if (y < width*height*4)
1237         {
1238                 // save the alpha channel
1239                 buffer[16] = 32;        // pixel size
1240                 buffer[17] = 8; // 8 bits of alpha
1241
1242                 // flip upside down
1243                 out = buffer + 18;
1244                 for (y = height - 1;y >= 0;y--)
1245                 {
1246                         memcpy(out, data + y * width * 4, width * 4);
1247                         out += width*4;
1248                 }
1249         }
1250         else
1251         {
1252                 // save only the color channels
1253                 buffer[16] = 24;        // pixel size
1254                 buffer[17] = 0; // 8 bits of alpha
1255
1256                 // truncate bgra to bgr and flip upside down
1257                 out = buffer + 18;
1258                 for (y = height - 1;y >= 0;y--)
1259                 {
1260                         in = data + y * width * 4;
1261                         end = in + width * 4;
1262                         for (;in < end;in += 4)
1263                         {
1264                                 *out++ = in[0];
1265                                 *out++ = in[1];
1266                                 *out++ = in[2];
1267                         }
1268                 }
1269         }
1270         ret = FS_WriteFile (filename, buffer, out - buffer);
1271
1272         Mem_Free(buffer);
1273
1274         return ret;
1275 }
1276
1277 static void Image_Resample32LerpLine (const unsigned char *in, unsigned char *out, int inwidth, int outwidth)
1278 {
1279         int             j, xi, oldx = 0, f, fstep, endx, lerp;
1280         fstep = (int) (inwidth*65536.0f/outwidth);
1281         endx = (inwidth-1);
1282         for (j = 0,f = 0;j < outwidth;j++, f += fstep)
1283         {
1284                 xi = f >> 16;
1285                 if (xi != oldx)
1286                 {
1287                         in += (xi - oldx) * 4;
1288                         oldx = xi;
1289                 }
1290                 if (xi < endx)
1291                 {
1292                         lerp = f & 0xFFFF;
1293                         *out++ = (unsigned char) ((((in[4] - in[0]) * lerp) >> 16) + in[0]);
1294                         *out++ = (unsigned char) ((((in[5] - in[1]) * lerp) >> 16) + in[1]);
1295                         *out++ = (unsigned char) ((((in[6] - in[2]) * lerp) >> 16) + in[2]);
1296                         *out++ = (unsigned char) ((((in[7] - in[3]) * lerp) >> 16) + in[3]);
1297                 }
1298                 else // last pixel of the line has no pixel to lerp to
1299                 {
1300                         *out++ = in[0];
1301                         *out++ = in[1];
1302                         *out++ = in[2];
1303                         *out++ = in[3];
1304                 }
1305         }
1306 }
1307
1308 #define LERPBYTE(i) r = resamplerow1[i];out[i] = (unsigned char) ((((resamplerow2[i] - r) * lerp) >> 16) + r)
1309 static void Image_Resample32Lerp(const void *indata, int inwidth, int inheight, void *outdata, int outwidth, int outheight)
1310 {
1311         int i, j, r, yi, oldy, f, fstep, lerp, endy = (inheight-1), inwidth4 = inwidth*4, outwidth4 = outwidth*4;
1312         unsigned char *out;
1313         const unsigned char *inrow;
1314         unsigned char *resamplerow1;
1315         unsigned char *resamplerow2;
1316         out = (unsigned char *)outdata;
1317         fstep = (int) (inheight*65536.0f/outheight);
1318
1319         resamplerow1 = (unsigned char *)Mem_Alloc(tempmempool, outwidth*4*2);
1320         resamplerow2 = resamplerow1 + outwidth*4;
1321
1322         inrow = (const unsigned char *)indata;
1323         oldy = 0;
1324         Image_Resample32LerpLine (inrow, resamplerow1, inwidth, outwidth);
1325         Image_Resample32LerpLine (inrow + inwidth4, resamplerow2, inwidth, outwidth);
1326         for (i = 0, f = 0;i < outheight;i++,f += fstep)
1327         {
1328                 yi = f >> 16;
1329                 if (yi < endy)
1330                 {
1331                         lerp = f & 0xFFFF;
1332                         if (yi != oldy)
1333                         {
1334                                 inrow = (unsigned char *)indata + inwidth4*yi;
1335                                 if (yi == oldy+1)
1336                                         memcpy(resamplerow1, resamplerow2, outwidth4);
1337                                 else
1338                                         Image_Resample32LerpLine (inrow, resamplerow1, inwidth, outwidth);
1339                                 Image_Resample32LerpLine (inrow + inwidth4, resamplerow2, inwidth, outwidth);
1340                                 oldy = yi;
1341                         }
1342                         j = outwidth - 4;
1343                         while(j >= 0)
1344                         {
1345                                 LERPBYTE( 0);
1346                                 LERPBYTE( 1);
1347                                 LERPBYTE( 2);
1348                                 LERPBYTE( 3);
1349                                 LERPBYTE( 4);
1350                                 LERPBYTE( 5);
1351                                 LERPBYTE( 6);
1352                                 LERPBYTE( 7);
1353                                 LERPBYTE( 8);
1354                                 LERPBYTE( 9);
1355                                 LERPBYTE(10);
1356                                 LERPBYTE(11);
1357                                 LERPBYTE(12);
1358                                 LERPBYTE(13);
1359                                 LERPBYTE(14);
1360                                 LERPBYTE(15);
1361                                 out += 16;
1362                                 resamplerow1 += 16;
1363                                 resamplerow2 += 16;
1364                                 j -= 4;
1365                         }
1366                         if (j & 2)
1367                         {
1368                                 LERPBYTE( 0);
1369                                 LERPBYTE( 1);
1370                                 LERPBYTE( 2);
1371                                 LERPBYTE( 3);
1372                                 LERPBYTE( 4);
1373                                 LERPBYTE( 5);
1374                                 LERPBYTE( 6);
1375                                 LERPBYTE( 7);
1376                                 out += 8;
1377                                 resamplerow1 += 8;
1378                                 resamplerow2 += 8;
1379                         }
1380                         if (j & 1)
1381                         {
1382                                 LERPBYTE( 0);
1383                                 LERPBYTE( 1);
1384                                 LERPBYTE( 2);
1385                                 LERPBYTE( 3);
1386                                 out += 4;
1387                                 resamplerow1 += 4;
1388                                 resamplerow2 += 4;
1389                         }
1390                         resamplerow1 -= outwidth4;
1391                         resamplerow2 -= outwidth4;
1392                 }
1393                 else
1394                 {
1395                         if (yi != oldy)
1396                         {
1397                                 inrow = (unsigned char *)indata + inwidth4*yi;
1398                                 if (yi == oldy+1)
1399                                         memcpy(resamplerow1, resamplerow2, outwidth4);
1400                                 else
1401                                         Image_Resample32LerpLine (inrow, resamplerow1, inwidth, outwidth);
1402                                 oldy = yi;
1403                         }
1404                         memcpy(out, resamplerow1, outwidth4);
1405                 }
1406         }
1407
1408         Mem_Free(resamplerow1);
1409         resamplerow1 = NULL;
1410         resamplerow2 = NULL;
1411 }
1412
1413 static void Image_Resample32Nolerp(const void *indata, int inwidth, int inheight, void *outdata, int outwidth, int outheight)
1414 {
1415         int i, j;
1416         unsigned frac, fracstep;
1417         // relies on int being 4 bytes
1418         int *inrow, *out;
1419         out = (int *)outdata;
1420
1421         fracstep = inwidth*0x10000/outwidth;
1422         for (i = 0;i < outheight;i++)
1423         {
1424                 inrow = (int *)indata + inwidth*(i*inheight/outheight);
1425                 frac = fracstep >> 1;
1426                 j = outwidth - 4;
1427                 while (j >= 0)
1428                 {
1429                         out[0] = inrow[frac >> 16];frac += fracstep;
1430                         out[1] = inrow[frac >> 16];frac += fracstep;
1431                         out[2] = inrow[frac >> 16];frac += fracstep;
1432                         out[3] = inrow[frac >> 16];frac += fracstep;
1433                         out += 4;
1434                         j -= 4;
1435                 }
1436                 if (j & 2)
1437                 {
1438                         out[0] = inrow[frac >> 16];frac += fracstep;
1439                         out[1] = inrow[frac >> 16];frac += fracstep;
1440                         out += 2;
1441                 }
1442                 if (j & 1)
1443                 {
1444                         out[0] = inrow[frac >> 16];frac += fracstep;
1445                         out += 1;
1446                 }
1447         }
1448 }
1449
1450 /*
1451 ================
1452 Image_Resample
1453 ================
1454 */
1455 void Image_Resample32(const void *indata, int inwidth, int inheight, int indepth, void *outdata, int outwidth, int outheight, int outdepth, int quality)
1456 {
1457         if (indepth != 1 || outdepth != 1)
1458         {
1459                 Con_Printf ("Image_Resample: 3D resampling not supported\n");
1460                 return;
1461         }
1462         if (quality)
1463                 Image_Resample32Lerp(indata, inwidth, inheight, outdata, outwidth, outheight);
1464         else
1465                 Image_Resample32Nolerp(indata, inwidth, inheight, outdata, outwidth, outheight);
1466 }
1467
1468 // in can be the same as out
1469 void Image_MipReduce32(const unsigned char *in, unsigned char *out, int *width, int *height, int *depth, int destwidth, int destheight, int destdepth)
1470 {
1471         const unsigned char *inrow;
1472         int x, y, nextrow;
1473         if (*depth != 1 || destdepth != 1)
1474         {
1475                 Con_Printf ("Image_Resample: 3D resampling not supported\n");
1476                 if (*width > destwidth)
1477                         *width >>= 1;
1478                 if (*height > destheight)
1479                         *height >>= 1;
1480                 if (*depth > destdepth)
1481                         *depth >>= 1;
1482                 return;
1483         }
1484         // note: if given odd width/height this discards the last row/column of
1485         // pixels, rather than doing a proper box-filter scale down
1486         inrow = in;
1487         nextrow = *width * 4;
1488         if (*width > destwidth)
1489         {
1490                 *width >>= 1;
1491                 if (*height > destheight)
1492                 {
1493                         // reduce both
1494                         *height >>= 1;
1495                         for (y = 0;y < *height;y++, inrow += nextrow * 2)
1496                         {
1497                                 for (in = inrow, x = 0;x < *width;x++)
1498                                 {
1499                                         out[0] = (unsigned char) ((in[0] + in[4] + in[nextrow  ] + in[nextrow+4]) >> 2);
1500                                         out[1] = (unsigned char) ((in[1] + in[5] + in[nextrow+1] + in[nextrow+5]) >> 2);
1501                                         out[2] = (unsigned char) ((in[2] + in[6] + in[nextrow+2] + in[nextrow+6]) >> 2);
1502                                         out[3] = (unsigned char) ((in[3] + in[7] + in[nextrow+3] + in[nextrow+7]) >> 2);
1503                                         out += 4;
1504                                         in += 8;
1505                                 }
1506                         }
1507                 }
1508                 else
1509                 {
1510                         // reduce width
1511                         for (y = 0;y < *height;y++, inrow += nextrow)
1512                         {
1513                                 for (in = inrow, x = 0;x < *width;x++)
1514                                 {
1515                                         out[0] = (unsigned char) ((in[0] + in[4]) >> 1);
1516                                         out[1] = (unsigned char) ((in[1] + in[5]) >> 1);
1517                                         out[2] = (unsigned char) ((in[2] + in[6]) >> 1);
1518                                         out[3] = (unsigned char) ((in[3] + in[7]) >> 1);
1519                                         out += 4;
1520                                         in += 8;
1521                                 }
1522                         }
1523                 }
1524         }
1525         else
1526         {
1527                 if (*height > destheight)
1528                 {
1529                         // reduce height
1530                         *height >>= 1;
1531                         for (y = 0;y < *height;y++, inrow += nextrow * 2)
1532                         {
1533                                 for (in = inrow, x = 0;x < *width;x++)
1534                                 {
1535                                         out[0] = (unsigned char) ((in[0] + in[nextrow  ]) >> 1);
1536                                         out[1] = (unsigned char) ((in[1] + in[nextrow+1]) >> 1);
1537                                         out[2] = (unsigned char) ((in[2] + in[nextrow+2]) >> 1);
1538                                         out[3] = (unsigned char) ((in[3] + in[nextrow+3]) >> 1);
1539                                         out += 4;
1540                                         in += 4;
1541                                 }
1542                         }
1543                 }
1544                 else
1545                         Con_Printf ("Image_MipReduce: desired size already achieved\n");
1546         }
1547 }
1548
1549 void Image_HeightmapToNormalmap_BGRA(const unsigned char *inpixels, unsigned char *outpixels, int width, int height, int clamp, float bumpscale)
1550 {
1551         int x, y, x1, x2, y1, y2;
1552         const unsigned char *b, *row[3];
1553         int p[5];
1554         unsigned char *out;
1555         float ibumpscale, n[3];
1556         ibumpscale = (255.0f * 6.0f) / bumpscale;
1557         out = outpixels;
1558         for (y = 0, y1 = height-1;y < height;y1 = y, y++)
1559         {
1560                 y2 = y + 1;if (y2 >= height) y2 = 0;
1561                 row[0] = inpixels + (y1 * width) * 4;
1562                 row[1] = inpixels + (y  * width) * 4;
1563                 row[2] = inpixels + (y2 * width) * 4;
1564                 for (x = 0, x1 = width-1;x < width;x1 = x, x++)
1565                 {
1566                         x2 = x + 1;if (x2 >= width) x2 = 0;
1567                         // left, right
1568                         b = row[1] + x1 * 4;p[0] = (b[0] + b[1] + b[2]);
1569                         b = row[1] + x2 * 4;p[1] = (b[0] + b[1] + b[2]);
1570                         // above, below
1571                         b = row[0] + x  * 4;p[2] = (b[0] + b[1] + b[2]);
1572                         b = row[2] + x  * 4;p[3] = (b[0] + b[1] + b[2]);
1573                         // center
1574                         b = row[1] + x  * 4;p[4] = (b[0] + b[1] + b[2]);
1575                         // calculate a normal from the slopes
1576                         n[0] = p[0] - p[1];
1577                         n[1] = p[3] - p[2];
1578                         n[2] = ibumpscale;
1579                         VectorNormalize(n);
1580                         // turn it into a dot3 rgb vector texture
1581                         out[2] = (int)(128.0f + n[0] * 127.0f);
1582                         out[1] = (int)(128.0f + n[1] * 127.0f);
1583                         out[0] = (int)(128.0f + n[2] * 127.0f);
1584                         out[3] = (p[4]) / 3;
1585                         out += 4;
1586                 }
1587         }
1588 }