Add an in_releaseall command for debugging/working around stuck keys.
[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 LoadPCX
360 ============
361 */
362 qboolean LoadPCX_PaletteOnly(const unsigned char *f, int filesize, unsigned char *palette768b)
363 {
364         if (filesize < 768)
365                 return false;
366         memcpy(palette768b, f + filesize - 768, 768);
367         return true;
368 }
369
370 /*
371 =========================================================
372
373 TARGA LOADING
374
375 =========================================================
376 */
377
378 typedef struct _TargaHeader
379 {
380         unsigned char   id_length, colormap_type, image_type;
381         unsigned short  colormap_index, colormap_length;
382         unsigned char   colormap_size;
383         unsigned short  x_origin, y_origin, width, height;
384         unsigned char   pixel_size, attributes;
385 }
386 TargaHeader;
387
388 static void PrintTargaHeader(TargaHeader *t)
389 {
390         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);
391 }
392
393 /*
394 =============
395 LoadTGA
396 =============
397 */
398 unsigned char *LoadTGA_BGRA (const unsigned char *f, int filesize, int *miplevel)
399 {
400         int x, y, pix_inc, row_inci, runlen, alphabits;
401         unsigned char *image_buffer;
402         unsigned int *pixbufi;
403         const unsigned char *fin, *enddata;
404         TargaHeader targa_header;
405         unsigned int palettei[256];
406         union
407         {
408                 unsigned int i;
409                 unsigned char b[4];
410         }
411         bgra;
412
413         if (filesize < 19)
414                 return NULL;
415
416         enddata = f + filesize;
417
418         targa_header.id_length = f[0];
419         targa_header.colormap_type = f[1];
420         targa_header.image_type = f[2];
421
422         targa_header.colormap_index = f[3] + f[4] * 256;
423         targa_header.colormap_length = f[5] + f[6] * 256;
424         targa_header.colormap_size = f[7];
425         targa_header.x_origin = f[8] + f[9] * 256;
426         targa_header.y_origin = f[10] + f[11] * 256;
427         targa_header.width = image_width = f[12] + f[13] * 256;
428         targa_header.height = image_height = f[14] + f[15] * 256;
429         targa_header.pixel_size = f[16];
430         targa_header.attributes = f[17];
431
432         if (image_width > 32768 || image_height > 32768 || image_width <= 0 || image_height <= 0)
433         {
434                 Con_Print("LoadTGA: invalid size\n");
435                 PrintTargaHeader(&targa_header);
436                 return NULL;
437         }
438
439         memset(palettei, 0, sizeof(palettei));
440
441         // advance to end of header
442         fin = f + 18;
443
444         // skip TARGA image comment (usually 0 bytes)
445         fin += targa_header.id_length;
446
447         // read/skip the colormap if present (note: according to the TARGA spec it
448         // can be present even on truecolor or greyscale images, just not used by
449         // the image data)
450         if (targa_header.colormap_type)
451         {
452                 if (targa_header.colormap_length > 256)
453                 {
454                         Con_Print("LoadTGA: only up to 256 colormap_length supported\n");
455                         PrintTargaHeader(&targa_header);
456                         return NULL;
457                 }
458                 if (targa_header.colormap_index)
459                 {
460                         Con_Print("LoadTGA: colormap_index not supported\n");
461                         PrintTargaHeader(&targa_header);
462                         return NULL;
463                 }
464                 if (targa_header.colormap_size == 24)
465                 {
466                         for (x = 0;x < targa_header.colormap_length;x++)
467                         {
468                                 bgra.b[0] = *fin++;
469                                 bgra.b[1] = *fin++;
470                                 bgra.b[2] = *fin++;
471                                 bgra.b[3] = 255;
472                                 palettei[x] = bgra.i;
473                         }
474                 }
475                 else if (targa_header.colormap_size == 32)
476                 {
477                         memcpy(palettei, fin, targa_header.colormap_length*4);
478                         fin += targa_header.colormap_length * 4;
479                 }
480                 else
481                 {
482                         Con_Print("LoadTGA: Only 32 and 24 bit colormap_size supported\n");
483                         PrintTargaHeader(&targa_header);
484                         return NULL;
485                 }
486         }
487
488         // check our pixel_size restrictions according to image_type
489         switch (targa_header.image_type & ~8)
490         {
491         case 2:
492                 if (targa_header.pixel_size != 24 && targa_header.pixel_size != 32)
493                 {
494                         Con_Print("LoadTGA: only 24bit and 32bit pixel sizes supported for type 2 and type 10 images\n");
495                         PrintTargaHeader(&targa_header);
496                         return NULL;
497                 }
498                 break;
499         case 3:
500                 // set up a palette to make the loader easier
501                 for (x = 0;x < 256;x++)
502                 {
503                         bgra.b[0] = bgra.b[1] = bgra.b[2] = x;
504                         bgra.b[3] = 255;
505                         palettei[x] = bgra.i;
506                 }
507                 // fall through to colormap case
508         case 1:
509                 if (targa_header.pixel_size != 8)
510                 {
511                         Con_Print("LoadTGA: only 8bit pixel size for type 1, 3, 9, and 11 images supported\n");
512                         PrintTargaHeader(&targa_header);
513                         return NULL;
514                 }
515                 break;
516         default:
517                 Con_Printf("LoadTGA: Only type 1, 2, 3, 9, 10, and 11 targa RGB images supported, image_type = %i\n", targa_header.image_type);
518                 PrintTargaHeader(&targa_header);
519                 return NULL;
520         }
521
522         if (targa_header.attributes & 0x10)
523         {
524                 Con_Print("LoadTGA: origin must be in top left or bottom left, top right and bottom right are not supported\n");
525                 return NULL;
526         }
527
528         // number of attribute bits per pixel, we only support 0 or 8
529         alphabits = targa_header.attributes & 0x0F;
530         if (alphabits != 8 && alphabits != 0)
531         {
532                 Con_Print("LoadTGA: only 0 or 8 attribute (alpha) bits supported\n");
533                 return NULL;
534         }
535
536         image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
537         if (!image_buffer)
538         {
539                 Con_Printf("LoadTGA: not enough memory for %i by %i image\n", image_width, image_height);
540                 return NULL;
541         }
542
543         // If bit 5 of attributes isn't set, the image has been stored from bottom to top
544         if ((targa_header.attributes & 0x20) == 0)
545         {
546                 pixbufi = (unsigned int*)image_buffer + (image_height - 1)*image_width;
547                 row_inci = -image_width*2;
548         }
549         else
550         {
551                 pixbufi = (unsigned int*)image_buffer;
552                 row_inci = 0;
553         }
554
555         pix_inc = 1;
556         if ((targa_header.image_type & ~8) == 2)
557                 pix_inc = (targa_header.pixel_size + 7) / 8;
558         switch (targa_header.image_type)
559         {
560         case 1: // colormapped, uncompressed
561         case 3: // greyscale, uncompressed
562                 if (fin + image_width * image_height * pix_inc > enddata)
563                         break;
564                 for (y = 0;y < image_height;y++, pixbufi += row_inci)
565                         for (x = 0;x < image_width;x++)
566                                 *pixbufi++ = palettei[*fin++];
567                 break;
568         case 2:
569                 // BGR or BGRA, uncompressed
570                 if (fin + image_width * image_height * pix_inc > enddata)
571                         break;
572                 if (targa_header.pixel_size == 32 && alphabits)
573                 {
574                         for (y = 0;y < image_height;y++)
575                                 memcpy(pixbufi + y * (image_width + row_inci), fin + y * image_width * pix_inc, image_width*4);
576                 }
577                 else
578                 {
579                         for (y = 0;y < image_height;y++, pixbufi += row_inci)
580                         {
581                                 for (x = 0;x < image_width;x++, fin += pix_inc)
582                                 {
583                                         bgra.b[0] = fin[0];
584                                         bgra.b[1] = fin[1];
585                                         bgra.b[2] = fin[2];
586                                         bgra.b[3] = 255;
587                                         *pixbufi++ = bgra.i;
588                                 }
589                         }
590                 }
591                 break;
592         case 9: // colormapped, RLE
593         case 11: // greyscale, RLE
594                 for (y = 0;y < image_height;y++, pixbufi += row_inci)
595                 {
596                         for (x = 0;x < image_width;)
597                         {
598                                 if (fin >= enddata)
599                                         break; // error - truncated file
600                                 runlen = *fin++;
601                                 if (runlen & 0x80)
602                                 {
603                                         // RLE - all pixels the same color
604                                         runlen += 1 - 0x80;
605                                         if (fin + pix_inc > enddata)
606                                                 break; // error - truncated file
607                                         if (x + runlen > image_width)
608                                                 break; // error - line exceeds width
609                                         bgra.i = palettei[*fin++];
610                                         for (;runlen--;x++)
611                                                 *pixbufi++ = bgra.i;
612                                 }
613                                 else
614                                 {
615                                         // uncompressed - all pixels different color
616                                         runlen++;
617                                         if (fin + pix_inc * runlen > enddata)
618                                                 break; // error - truncated file
619                                         if (x + runlen > image_width)
620                                                 break; // error - line exceeds width
621                                         for (;runlen--;x++)
622                                                 *pixbufi++ = palettei[*fin++];
623                                 }
624                         }
625
626                         if (x != image_width)
627                         {
628                                 // pixbufi is useless now
629                                 Con_Printf("LoadTGA: corrupt file\n");
630                                 break;
631                         }
632                 }
633                 break;
634         case 10:
635                 // BGR or BGRA, RLE
636                 if (targa_header.pixel_size == 32 && alphabits)
637                 {
638                         for (y = 0;y < image_height;y++, pixbufi += row_inci)
639                         {
640                                 for (x = 0;x < image_width;)
641                                 {
642                                         if (fin >= enddata)
643                                                 break; // error - truncated file
644                                         runlen = *fin++;
645                                         if (runlen & 0x80)
646                                         {
647                                                 // RLE - all pixels the same color
648                                                 runlen += 1 - 0x80;
649                                                 if (fin + pix_inc > enddata)
650                                                         break; // error - truncated file
651                                                 if (x + runlen > image_width)
652                                                         break; // error - line exceeds width
653                                                 bgra.b[0] = fin[0];
654                                                 bgra.b[1] = fin[1];
655                                                 bgra.b[2] = fin[2];
656                                                 bgra.b[3] = fin[3];
657                                                 fin += pix_inc;
658                                                 for (;runlen--;x++)
659                                                         *pixbufi++ = bgra.i;
660                                         }
661                                         else
662                                         {
663                                                 // uncompressed - all pixels different color
664                                                 runlen++;
665                                                 if (fin + pix_inc * runlen > enddata)
666                                                         break; // error - truncated file
667                                                 if (x + runlen > image_width)
668                                                         break; // error - line exceeds width
669                                                 for (;runlen--;x++)
670                                                 {
671                                                         bgra.b[0] = fin[0];
672                                                         bgra.b[1] = fin[1];
673                                                         bgra.b[2] = fin[2];
674                                                         bgra.b[3] = fin[3];
675                                                         fin += pix_inc;
676                                                         *pixbufi++ = bgra.i;
677                                                 }
678                                         }
679                                 }
680
681                                 if (x != image_width)
682                                 {
683                                         // pixbufi is useless now
684                                         Con_Printf("LoadTGA: corrupt file\n");
685                                         break;
686                                 }
687                         }
688                 }
689                 else
690                 {
691                         for (y = 0;y < image_height;y++, pixbufi += row_inci)
692                         {
693                                 for (x = 0;x < image_width;)
694                                 {
695                                         if (fin >= enddata)
696                                                 break; // error - truncated file
697                                         runlen = *fin++;
698                                         if (runlen & 0x80)
699                                         {
700                                                 // RLE - all pixels the same color
701                                                 runlen += 1 - 0x80;
702                                                 if (fin + pix_inc > enddata)
703                                                         break; // error - truncated file
704                                                 if (x + runlen > image_width)
705                                                         break; // error - line exceeds width
706                                                 bgra.b[0] = fin[0];
707                                                 bgra.b[1] = fin[1];
708                                                 bgra.b[2] = fin[2];
709                                                 bgra.b[3] = 255;
710                                                 fin += pix_inc;
711                                                 for (;runlen--;x++)
712                                                         *pixbufi++ = bgra.i;
713                                         }
714                                         else
715                                         {
716                                                 // uncompressed - all pixels different color
717                                                 runlen++;
718                                                 if (fin + pix_inc * runlen > enddata)
719                                                         break; // error - truncated file
720                                                 if (x + runlen > image_width)
721                                                         break; // error - line exceeds width
722                                                 for (;runlen--;x++)
723                                                 {
724                                                         bgra.b[0] = fin[0];
725                                                         bgra.b[1] = fin[1];
726                                                         bgra.b[2] = fin[2];
727                                                         bgra.b[3] = 255;
728                                                         fin += pix_inc;
729                                                         *pixbufi++ = bgra.i;
730                                                 }
731                                         }
732                                 }
733
734                                 if (x != image_width)
735                                 {
736                                         // pixbufi is useless now
737                                         Con_Printf("LoadTGA: corrupt file\n");
738                                         break;
739                                 }
740                         }
741                 }
742                 break;
743         default:
744                 // unknown image_type
745                 break;
746         }
747
748         return image_buffer;
749 }
750
751 typedef struct q2wal_s
752 {
753         char            name[32];
754         unsigned        width, height;
755         unsigned        offsets[MIPLEVELS];             // four mip maps stored
756         char            animname[32];                   // next frame in animation chain
757         int                     flags;
758         int                     contents;
759         int                     value;
760 } q2wal_t;
761
762 static unsigned char *LoadWAL_BGRA (const unsigned char *f, int filesize, int *miplevel)
763 {
764         unsigned char *image_buffer;
765         const q2wal_t *inwal = (const q2wal_t *)f;
766
767         if (filesize < (int) sizeof(q2wal_t))
768         {
769                 Con_Print("LoadWAL: invalid WAL file\n");
770                 return NULL;
771         }
772
773         image_width = LittleLong(inwal->width);
774         image_height = LittleLong(inwal->height);
775         if (image_width > 32768 || image_height > 32768 || image_width <= 0 || image_height <= 0)
776         {
777                 Con_Printf("LoadWAL: invalid size %ix%i\n", image_width, image_height);
778                 return NULL;
779         }
780
781         if (filesize < (int) LittleLong(inwal->offsets[0]) + image_width * image_height)
782         {
783                 Con_Print("LoadWAL: invalid WAL file\n");
784                 return NULL;
785         }
786
787         image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
788         if (!image_buffer)
789         {
790                 Con_Printf("LoadWAL: not enough memory for %i by %i image\n", image_width, image_height);
791                 return NULL;
792         }
793         Image_Copy8bitBGRA(f + LittleLong(inwal->offsets[0]), image_buffer, image_width * image_height, q2palette_bgra_complete);
794         return image_buffer;
795 }
796
797 qboolean LoadWAL_GetMetadata(const unsigned char *f, int filesize, int *retwidth, int *retheight, int *retflags, int *retvalue, int *retcontents, char *retanimname32c)
798 {
799         const q2wal_t *inwal = (const q2wal_t *)f;
800
801         if (filesize < (int) sizeof(q2wal_t))
802         {
803                 Con_Print("LoadWAL: invalid WAL file\n");
804                 if (retwidth)
805                         *retwidth = 16;
806                 if (retheight)
807                         *retheight = 16;
808                 if (retflags)
809                         *retflags = 0;
810                 if (retvalue)
811                         *retvalue = 0;
812                 if (retcontents)
813                         *retcontents = 0;
814                 if (retanimname32c)
815                         memset(retanimname32c, 0, 32);
816                 return false;
817         }
818
819         if (retwidth)
820                 *retwidth = LittleLong(inwal->width);
821         if (retheight)
822                 *retheight = LittleLong(inwal->height);
823         if (retflags)
824                 *retflags = LittleLong(inwal->flags);
825         if (retvalue)
826                 *retvalue = LittleLong(inwal->value);
827         if (retcontents)
828                 *retcontents = LittleLong(inwal->contents);
829         if (retanimname32c)
830         {
831                 memcpy(retanimname32c, inwal->animname, 32);
832                 retanimname32c[31] = 0;
833         }
834         return true;
835 }
836
837
838 void Image_StripImageExtension (const char *in, char *out, size_t size_out)
839 {
840         const char *ext;
841
842         if (size_out == 0)
843                 return;
844
845         ext = FS_FileExtension(in);
846         if (ext && (!strcmp(ext, "tga") || !strcmp(ext, "pcx") || !strcmp(ext, "lmp") || !strcmp(ext, "png") || !strcmp(ext, "jpg") || !strcmp(ext, "wal")))
847                 FS_StripExtension(in, out, size_out);
848         else
849                 strlcpy(out, in, size_out);
850 }
851
852 static unsigned char image_linearfromsrgb[256];
853 static unsigned char image_srgbfromlinear_lightmap[256];
854
855 void Image_MakeLinearColorsFromsRGB(unsigned char *pout, const unsigned char *pin, int numpixels)
856 {
857         int i;
858         // this math from http://www.opengl.org/registry/specs/EXT/texture_sRGB.txt
859         if (!image_linearfromsrgb[255])
860                 for (i = 0;i < 256;i++)
861                         image_linearfromsrgb[i] = (unsigned char)floor(Image_LinearFloatFromsRGB(i) * 255.0f + 0.5f);
862         for (i = 0;i < numpixels;i++)
863         {
864                 pout[i*4+0] = image_linearfromsrgb[pin[i*4+0]];
865                 pout[i*4+1] = image_linearfromsrgb[pin[i*4+1]];
866                 pout[i*4+2] = image_linearfromsrgb[pin[i*4+2]];
867                 pout[i*4+3] = pin[i*4+3];
868         }
869 }
870
871 void Image_MakesRGBColorsFromLinear_Lightmap(unsigned char *pout, const unsigned char *pin, int numpixels)
872 {
873         int i;
874         // this math from http://www.opengl.org/registry/specs/EXT/texture_sRGB.txt
875         if (!image_srgbfromlinear_lightmap[255])
876                 for (i = 0;i < 256;i++)
877                         image_srgbfromlinear_lightmap[i] = (unsigned char)floor(bound(0.0f, Image_sRGBFloatFromLinear_Lightmap(i), 1.0f) * 255.0f + 0.5f);
878         for (i = 0;i < numpixels;i++)
879         {
880                 pout[i*4+0] = image_srgbfromlinear_lightmap[pin[i*4+0]];
881                 pout[i*4+1] = image_srgbfromlinear_lightmap[pin[i*4+1]];
882                 pout[i*4+2] = image_srgbfromlinear_lightmap[pin[i*4+2]];
883                 pout[i*4+3] = pin[i*4+3];
884         }
885 }
886
887 typedef struct imageformat_s
888 {
889         const char *formatstring;
890         unsigned char *(*loadfunc)(const unsigned char *f, int filesize, int *miplevel);
891 }
892 imageformat_t;
893
894 // GAME_TENEBRAE only
895 imageformat_t imageformats_tenebrae[] =
896 {
897         {"override/%s.tga", LoadTGA_BGRA},
898         {"override/%s.png", PNG_LoadImage_BGRA},
899         {"override/%s.jpg", JPEG_LoadImage_BGRA},
900         {"override/%s.pcx", LoadPCX_BGRA},
901         {"%s.tga", LoadTGA_BGRA},
902         {"%s.png", PNG_LoadImage_BGRA},
903         {"%s.jpg", JPEG_LoadImage_BGRA},
904         {"%s.pcx", LoadPCX_BGRA},
905         {NULL, NULL}
906 };
907
908 imageformat_t imageformats_nopath[] =
909 {
910         {"override/%s.tga", LoadTGA_BGRA},
911         {"override/%s.png", PNG_LoadImage_BGRA},
912         {"override/%s.jpg", JPEG_LoadImage_BGRA},
913         {"textures/%s.tga", LoadTGA_BGRA},
914         {"textures/%s.png", PNG_LoadImage_BGRA},
915         {"textures/%s.jpg", JPEG_LoadImage_BGRA},
916         {"%s.tga", LoadTGA_BGRA},
917         {"%s.png", PNG_LoadImage_BGRA},
918         {"%s.jpg", JPEG_LoadImage_BGRA},
919         {"%s.pcx", LoadPCX_BGRA},
920         {NULL, NULL}
921 };
922
923 // GAME_DELUXEQUAKE only
924 // VorteX: the point why i use such messy texture paths is
925 // that GtkRadiant can't detect normal/gloss textures
926 // and exclude them from texture browser
927 // so i just use additional folder to store this textures
928 imageformat_t imageformats_dq[] =
929 {
930         {"%s.tga", LoadTGA_BGRA},
931         {"%s.jpg", JPEG_LoadImage_BGRA},
932         {"texturemaps/%s.tga", LoadTGA_BGRA},
933         {"texturemaps/%s.jpg", JPEG_LoadImage_BGRA},
934         {NULL, NULL}
935 };
936
937 imageformat_t imageformats_textures[] =
938 {
939         {"%s.tga", LoadTGA_BGRA},
940         {"%s.png", PNG_LoadImage_BGRA},
941         {"%s.jpg", JPEG_LoadImage_BGRA},
942         {"%s.pcx", LoadPCX_BGRA},
943         {"%s.wal", LoadWAL_BGRA},
944         {NULL, NULL}
945 };
946
947 imageformat_t imageformats_gfx[] =
948 {
949         {"%s.tga", LoadTGA_BGRA},
950         {"%s.png", PNG_LoadImage_BGRA},
951         {"%s.jpg", JPEG_LoadImage_BGRA},
952         {"%s.pcx", LoadPCX_BGRA},
953         {NULL, NULL}
954 };
955
956 imageformat_t imageformats_other[] =
957 {
958         {"%s.tga", LoadTGA_BGRA},
959         {"%s.png", PNG_LoadImage_BGRA},
960         {"%s.jpg", JPEG_LoadImage_BGRA},
961         {"%s.pcx", LoadPCX_BGRA},
962         {NULL, NULL}
963 };
964
965 int fixtransparentpixels(unsigned char *data, int w, int h);
966 unsigned char *loadimagepixelsbgra (const char *filename, qboolean complain, qboolean allowFixtrans, qboolean convertsRGB, int *miplevel)
967 {
968         fs_offset_t filesize;
969         imageformat_t *firstformat, *format;
970         unsigned char *f, *data = NULL, *data2 = NULL;
971         char basename[MAX_QPATH], name[MAX_QPATH], name2[MAX_QPATH], *c;
972         char vabuf[1024];
973         //if (developer_memorydebug.integer)
974         //      Mem_CheckSentinelsGlobal();
975         if (developer_texturelogging.integer)
976                 Log_Printf("textures.log", "%s\n", filename);
977         Image_StripImageExtension(filename, basename, sizeof(basename)); // strip filename extensions to allow replacement by other types
978         // replace *'s with #, so commandline utils don't get confused when dealing with the external files
979         for (c = basename;*c;c++)
980                 if (*c == '*')
981                         *c = '#';
982         name[0] = 0;
983         if (strchr(basename, '/'))
984         {
985                 int i;
986                 for (i = 0;i < (int)sizeof(name)-1 && basename[i] != '/';i++)
987                         name[i] = basename[i];
988                 name[i] = 0;
989         }
990         if (gamemode == GAME_TENEBRAE)
991                 firstformat = imageformats_tenebrae;
992         else if (gamemode == GAME_DELUXEQUAKE)
993                 firstformat = imageformats_dq;
994         else if (!strcasecmp(name, "textures"))
995                 firstformat = imageformats_textures;
996         else if (!strcasecmp(name, "gfx"))
997                 firstformat = imageformats_gfx;
998         else if (!strchr(basename, '/'))
999                 firstformat = imageformats_nopath;
1000         else
1001                 firstformat = imageformats_other;
1002         // now try all the formats in the selected list
1003         for (format = firstformat;format->formatstring;format++)
1004         {
1005                 dpsnprintf (name, sizeof(name), format->formatstring, basename);
1006                 f = FS_LoadFile(name, tempmempool, true, &filesize);
1007                 if (f)
1008                 {
1009                         int mymiplevel = miplevel ? *miplevel : 0;
1010                         image_width = 0;
1011                         image_height = 0;
1012                         data = format->loadfunc(f, (int)filesize, &mymiplevel);
1013                         Mem_Free(f);
1014                         if (data)
1015                         {
1016                                 if(format->loadfunc == JPEG_LoadImage_BGRA) // jpeg can't do alpha, so let's simulate it by loading another jpeg
1017                                 {
1018                                         dpsnprintf (name2, sizeof(name2), format->formatstring, va(vabuf, sizeof(vabuf), "%s_alpha", basename));
1019                                         f = FS_LoadFile(name2, tempmempool, true, &filesize);
1020                                         if(f)
1021                                         {
1022                                                 int mymiplevel2 = miplevel ? *miplevel : 0;
1023                                                 int image_width_save = image_width;
1024                                                 int image_height_save = image_height;
1025                                                 data2 = format->loadfunc(f, (int)filesize, &mymiplevel2);
1026                                                 if(data2 && mymiplevel == mymiplevel2 && image_width == image_width_save && image_height == image_height_save)
1027                                                         Image_CopyAlphaFromBlueBGRA(data, data2, image_width, image_height);
1028                                                 else
1029                                                         Con_Printf("loadimagepixelsrgba: corrupt or invalid alpha image %s_alpha\n", basename);
1030                                                 image_width = image_width_save;
1031                                                 image_height = image_height_save;
1032                                                 if(data2)
1033                                                         Mem_Free(data2);
1034                                                 Mem_Free(f);
1035                                         }
1036                                 }
1037                                 if (developer_loading.integer)
1038                                         Con_DPrintf("loaded image %s (%dx%d)\n", name, image_width, image_height);
1039                                 if(miplevel)
1040                                         *miplevel = mymiplevel;
1041                                 //if (developer_memorydebug.integer)
1042                                 //      Mem_CheckSentinelsGlobal();
1043                                 if(allowFixtrans && r_fixtrans_auto.integer)
1044                                 {
1045                                         int n = fixtransparentpixels(data, image_width, image_height);
1046                                         if(n)
1047                                         {
1048                                                 Con_Printf("- had to fix %s (%d pixels changed)\n", name, n);
1049                                                 if(r_fixtrans_auto.integer >= 2)
1050                                                 {
1051                                                         char outfilename[MAX_QPATH], buf[MAX_QPATH];
1052                                                         Image_StripImageExtension(name, buf, sizeof(buf));
1053                                                         dpsnprintf(outfilename, sizeof(outfilename), "fixtrans/%s.tga", buf);
1054                                                         Image_WriteTGABGRA(outfilename, image_width, image_height, data);
1055                                                         Con_Printf("- %s written.\n", outfilename);
1056                                                 }
1057                                         }
1058                                 }
1059                                 if (convertsRGB)
1060                                         Image_MakeLinearColorsFromsRGB(data, data, image_width * image_height);
1061                                 return data;
1062                         }
1063                         else
1064                                 Con_DPrintf("Error loading image %s (file loaded but decode failed)\n", name);
1065                 }
1066         }
1067         if (complain)
1068         {
1069                 Con_Printf("Couldn't load %s using ", filename);
1070                 for (format = firstformat;format->formatstring;format++)
1071                 {
1072                         dpsnprintf (name, sizeof(name), format->formatstring, basename);
1073                         Con_Printf(format == firstformat ? "\"%s\"" : (format[1].formatstring ? ", \"%s\"" : " or \"%s\".\n"), format->formatstring);
1074                 }
1075         }
1076
1077         // texture loading can take a while, so make sure we're sending keepalives
1078         CL_KeepaliveMessage(false);
1079
1080         //if (developer_memorydebug.integer)
1081         //      Mem_CheckSentinelsGlobal();
1082         return NULL;
1083 }
1084
1085 extern cvar_t gl_picmip;
1086 rtexture_t *loadtextureimage (rtexturepool_t *pool, const char *filename, qboolean complain, int flags, qboolean allowFixtrans, qboolean sRGB)
1087 {
1088         unsigned char *data;
1089         rtexture_t *rt;
1090         int miplevel = R_PicmipForFlags(flags);
1091         if (!(data = loadimagepixelsbgra (filename, complain, allowFixtrans, false, &miplevel)))
1092                 return 0;
1093         rt = R_LoadTexture2D(pool, filename, image_width, image_height, data, sRGB ? TEXTYPE_SRGB_BGRA : TEXTYPE_BGRA, flags, miplevel, NULL);
1094         Mem_Free(data);
1095         return rt;
1096 }
1097
1098 int fixtransparentpixels(unsigned char *data, int w, int h)
1099 {
1100         int const FIXTRANS_NEEDED = 1;
1101         int const FIXTRANS_HAS_L = 2;
1102         int const FIXTRANS_HAS_R = 4;
1103         int const FIXTRANS_HAS_U = 8;
1104         int const FIXTRANS_HAS_D = 16;
1105         int const FIXTRANS_FIXED = 32;
1106         unsigned char *fixMask = (unsigned char *) Mem_Alloc(tempmempool, w * h);
1107         int fixPixels = 0;
1108         int changedPixels = 0;
1109         int x, y;
1110
1111 #define FIXTRANS_PIXEL (y*w+x)
1112 #define FIXTRANS_PIXEL_U (((y+h-1)%h)*w+x)
1113 #define FIXTRANS_PIXEL_D (((y+1)%h)*w+x)
1114 #define FIXTRANS_PIXEL_L (y*w+((x+w-1)%w))
1115 #define FIXTRANS_PIXEL_R (y*w+((x+1)%w))
1116
1117         memset(fixMask, 0, w * h);
1118         for(y = 0; y < h; ++y)
1119                 for(x = 0; x < w; ++x)
1120                 {
1121                         if(data[FIXTRANS_PIXEL * 4 + 3] == 0)
1122                         {
1123                                 fixMask[FIXTRANS_PIXEL] |= FIXTRANS_NEEDED;
1124                                 ++fixPixels;
1125                         }
1126                         else
1127                         {
1128                                 fixMask[FIXTRANS_PIXEL_D] |= FIXTRANS_HAS_U;
1129                                 fixMask[FIXTRANS_PIXEL_U] |= FIXTRANS_HAS_D;
1130                                 fixMask[FIXTRANS_PIXEL_R] |= FIXTRANS_HAS_L;
1131                                 fixMask[FIXTRANS_PIXEL_L] |= FIXTRANS_HAS_R;
1132                         }
1133                 }
1134         if(fixPixels == w * h)
1135                 return 0; // sorry, can't do anything about this
1136         while(fixPixels)
1137         {
1138                 for(y = 0; y < h; ++y)
1139                         for(x = 0; x < w; ++x)
1140                                 if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_NEEDED)
1141                                 {
1142                                         unsigned int sumR = 0, sumG = 0, sumB = 0, sumA = 0, sumRA = 0, sumGA = 0, sumBA = 0, cnt = 0;
1143                                         unsigned char r, g, b, a, r0, g0, b0;
1144                                         if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_HAS_U)
1145                                         {
1146                                                 r = data[FIXTRANS_PIXEL_U * 4 + 2];
1147                                                 g = data[FIXTRANS_PIXEL_U * 4 + 1];
1148                                                 b = data[FIXTRANS_PIXEL_U * 4 + 0];
1149                                                 a = data[FIXTRANS_PIXEL_U * 4 + 3];
1150                                                 sumR += r; sumG += g; sumB += b; sumA += a; sumRA += r*a; sumGA += g*a; sumBA += b*a; ++cnt;
1151                                         }
1152                                         if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_HAS_D)
1153                                         {
1154                                                 r = data[FIXTRANS_PIXEL_D * 4 + 2];
1155                                                 g = data[FIXTRANS_PIXEL_D * 4 + 1];
1156                                                 b = data[FIXTRANS_PIXEL_D * 4 + 0];
1157                                                 a = data[FIXTRANS_PIXEL_D * 4 + 3];
1158                                                 sumR += r; sumG += g; sumB += b; sumA += a; sumRA += r*a; sumGA += g*a; sumBA += b*a; ++cnt;
1159                                         }
1160                                         if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_HAS_L)
1161                                         {
1162                                                 r = data[FIXTRANS_PIXEL_L * 4 + 2];
1163                                                 g = data[FIXTRANS_PIXEL_L * 4 + 1];
1164                                                 b = data[FIXTRANS_PIXEL_L * 4 + 0];
1165                                                 a = data[FIXTRANS_PIXEL_L * 4 + 3];
1166                                                 sumR += r; sumG += g; sumB += b; sumA += a; sumRA += r*a; sumGA += g*a; sumBA += b*a; ++cnt;
1167                                         }
1168                                         if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_HAS_R)
1169                                         {
1170                                                 r = data[FIXTRANS_PIXEL_R * 4 + 2];
1171                                                 g = data[FIXTRANS_PIXEL_R * 4 + 1];
1172                                                 b = data[FIXTRANS_PIXEL_R * 4 + 0];
1173                                                 a = data[FIXTRANS_PIXEL_R * 4 + 3];
1174                                                 sumR += r; sumG += g; sumB += b; sumA += a; sumRA += r*a; sumGA += g*a; sumBA += b*a; ++cnt;
1175                                         }
1176                                         if(!cnt)
1177                                                 continue;
1178                                         r0 = data[FIXTRANS_PIXEL * 4 + 2];
1179                                         g0 = data[FIXTRANS_PIXEL * 4 + 1];
1180                                         b0 = data[FIXTRANS_PIXEL * 4 + 0];
1181                                         if(sumA)
1182                                         {
1183                                                 // there is a surrounding non-alpha pixel
1184                                                 r = (sumRA + sumA / 2) / sumA;
1185                                                 g = (sumGA + sumA / 2) / sumA;
1186                                                 b = (sumBA + sumA / 2) / sumA;
1187                                         }
1188                                         else
1189                                         {
1190                                                 // need to use a "regular" average
1191                                                 r = (sumR + cnt / 2) / cnt;
1192                                                 g = (sumG + cnt / 2) / cnt;
1193                                                 b = (sumB + cnt / 2) / cnt;
1194                                         }
1195                                         if(r != r0 || g != g0 || b != b0)
1196                                                 ++changedPixels;
1197                                         data[FIXTRANS_PIXEL * 4 + 2] = r;
1198                                         data[FIXTRANS_PIXEL * 4 + 1] = g;
1199                                         data[FIXTRANS_PIXEL * 4 + 0] = b;
1200                                         fixMask[FIXTRANS_PIXEL] |= FIXTRANS_FIXED;
1201                                 }
1202                 for(y = 0; y < h; ++y)
1203                         for(x = 0; x < w; ++x)
1204                                 if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_FIXED)
1205                                 {
1206                                         fixMask[FIXTRANS_PIXEL] &= ~(FIXTRANS_NEEDED | FIXTRANS_FIXED);
1207                                         fixMask[FIXTRANS_PIXEL_D] |= FIXTRANS_HAS_U;
1208                                         fixMask[FIXTRANS_PIXEL_U] |= FIXTRANS_HAS_D;
1209                                         fixMask[FIXTRANS_PIXEL_R] |= FIXTRANS_HAS_L;
1210                                         fixMask[FIXTRANS_PIXEL_L] |= FIXTRANS_HAS_R;
1211                                         --fixPixels;
1212                                 }
1213         }
1214         return changedPixels;
1215 }
1216
1217 void Image_FixTransparentPixels_f(void)
1218 {
1219         const char *filename, *filename_pattern;
1220         fssearch_t *search;
1221         int i, n;
1222         char outfilename[MAX_QPATH], buf[MAX_QPATH];
1223         unsigned char *data;
1224         if(Cmd_Argc() != 2)
1225         {
1226                 Con_Printf("Usage: %s imagefile\n", Cmd_Argv(0));
1227                 return;
1228         }
1229         filename_pattern = Cmd_Argv(1);
1230         search = FS_Search(filename_pattern, true, true);
1231         if(!search)
1232                 return;
1233         for(i = 0; i < search->numfilenames; ++i)
1234         {
1235                 filename = search->filenames[i];
1236                 Con_Printf("Processing %s... ", filename);
1237                 Image_StripImageExtension(filename, buf, sizeof(buf));
1238                 dpsnprintf(outfilename, sizeof(outfilename), "fixtrans/%s.tga", buf);
1239                 if(!(data = loadimagepixelsbgra(filename, true, false, false, NULL)))
1240                         return;
1241                 if((n = fixtransparentpixels(data, image_width, image_height)))
1242                 {
1243                         Image_WriteTGABGRA(outfilename, image_width, image_height, data);
1244                         Con_Printf("%s written (%d pixels changed).\n", outfilename, n);
1245                 }
1246                 else
1247                         Con_Printf("unchanged.\n");
1248                 Mem_Free(data);
1249         }
1250         FS_FreeSearch(search);
1251 }
1252
1253 qboolean Image_WriteTGABGR_preflipped (const char *filename, int width, int height, const unsigned char *data)
1254 {
1255         qboolean ret;
1256         unsigned char buffer[18];
1257         const void *buffers[2];
1258         fs_offset_t sizes[2];
1259
1260         memset (buffer, 0, 18);
1261         buffer[2] = 2;          // uncompressed type
1262         buffer[12] = (width >> 0) & 0xFF;
1263         buffer[13] = (width >> 8) & 0xFF;
1264         buffer[14] = (height >> 0) & 0xFF;
1265         buffer[15] = (height >> 8) & 0xFF;
1266         buffer[16] = 24;        // pixel size
1267
1268         buffers[0] = buffer;
1269         sizes[0] = 18;
1270         buffers[1] = data;
1271         sizes[1] = width*height*3;
1272         ret = FS_WriteFileInBlocks(filename, buffers, sizes, 2);
1273
1274         return ret;
1275 }
1276
1277 qboolean Image_WriteTGABGRA (const char *filename, int width, int height, const unsigned char *data)
1278 {
1279         int y;
1280         unsigned char *buffer, *out;
1281         const unsigned char *in, *end;
1282         qboolean ret;
1283
1284         buffer = (unsigned char *)Mem_Alloc(tempmempool, width*height*4 + 18);
1285
1286         memset (buffer, 0, 18);
1287         buffer[2] = 2;          // uncompressed type
1288         buffer[12] = (width >> 0) & 0xFF;
1289         buffer[13] = (width >> 8) & 0xFF;
1290         buffer[14] = (height >> 0) & 0xFF;
1291         buffer[15] = (height >> 8) & 0xFF;
1292
1293         for (y = 3;y < width*height*4;y += 4)
1294                 if (data[y] < 255)
1295                         break;
1296
1297         if (y < width*height*4)
1298         {
1299                 // save the alpha channel
1300                 buffer[16] = 32;        // pixel size
1301                 buffer[17] = 8; // 8 bits of alpha
1302
1303                 // flip upside down
1304                 out = buffer + 18;
1305                 for (y = height - 1;y >= 0;y--)
1306                 {
1307                         memcpy(out, data + y * width * 4, width * 4);
1308                         out += width*4;
1309                 }
1310         }
1311         else
1312         {
1313                 // save only the color channels
1314                 buffer[16] = 24;        // pixel size
1315                 buffer[17] = 0; // 8 bits of alpha
1316
1317                 // truncate bgra to bgr and flip upside down
1318                 out = buffer + 18;
1319                 for (y = height - 1;y >= 0;y--)
1320                 {
1321                         in = data + y * width * 4;
1322                         end = in + width * 4;
1323                         for (;in < end;in += 4)
1324                         {
1325                                 *out++ = in[0];
1326                                 *out++ = in[1];
1327                                 *out++ = in[2];
1328                         }
1329                 }
1330         }
1331         ret = FS_WriteFile (filename, buffer, out - buffer);
1332
1333         Mem_Free(buffer);
1334
1335         return ret;
1336 }
1337
1338 static void Image_Resample32LerpLine (const unsigned char *in, unsigned char *out, int inwidth, int outwidth)
1339 {
1340         int             j, xi, oldx = 0, f, fstep, endx, lerp;
1341         fstep = (int) (inwidth*65536.0f/outwidth);
1342         endx = (inwidth-1);
1343         for (j = 0,f = 0;j < outwidth;j++, f += fstep)
1344         {
1345                 xi = f >> 16;
1346                 if (xi != oldx)
1347                 {
1348                         in += (xi - oldx) * 4;
1349                         oldx = xi;
1350                 }
1351                 if (xi < endx)
1352                 {
1353                         lerp = f & 0xFFFF;
1354                         *out++ = (unsigned char) ((((in[4] - in[0]) * lerp) >> 16) + in[0]);
1355                         *out++ = (unsigned char) ((((in[5] - in[1]) * lerp) >> 16) + in[1]);
1356                         *out++ = (unsigned char) ((((in[6] - in[2]) * lerp) >> 16) + in[2]);
1357                         *out++ = (unsigned char) ((((in[7] - in[3]) * lerp) >> 16) + in[3]);
1358                 }
1359                 else // last pixel of the line has no pixel to lerp to
1360                 {
1361                         *out++ = in[0];
1362                         *out++ = in[1];
1363                         *out++ = in[2];
1364                         *out++ = in[3];
1365                 }
1366         }
1367 }
1368
1369 #define LERPBYTE(i) r = resamplerow1[i];out[i] = (unsigned char) ((((resamplerow2[i] - r) * lerp) >> 16) + r)
1370 static void Image_Resample32Lerp(const void *indata, int inwidth, int inheight, void *outdata, int outwidth, int outheight)
1371 {
1372         int i, j, r, yi, oldy, f, fstep, lerp, endy = (inheight-1), inwidth4 = inwidth*4, outwidth4 = outwidth*4;
1373         unsigned char *out;
1374         const unsigned char *inrow;
1375         unsigned char *resamplerow1;
1376         unsigned char *resamplerow2;
1377         out = (unsigned char *)outdata;
1378         fstep = (int) (inheight*65536.0f/outheight);
1379
1380         resamplerow1 = (unsigned char *)Mem_Alloc(tempmempool, outwidth*4*2);
1381         resamplerow2 = resamplerow1 + outwidth*4;
1382
1383         inrow = (const unsigned char *)indata;
1384         oldy = 0;
1385         Image_Resample32LerpLine (inrow, resamplerow1, inwidth, outwidth);
1386         Image_Resample32LerpLine (inrow + inwidth4, resamplerow2, inwidth, outwidth);
1387         for (i = 0, f = 0;i < outheight;i++,f += fstep)
1388         {
1389                 yi = f >> 16;
1390                 if (yi < endy)
1391                 {
1392                         lerp = f & 0xFFFF;
1393                         if (yi != oldy)
1394                         {
1395                                 inrow = (unsigned char *)indata + inwidth4*yi;
1396                                 if (yi == oldy+1)
1397                                         memcpy(resamplerow1, resamplerow2, outwidth4);
1398                                 else
1399                                         Image_Resample32LerpLine (inrow, resamplerow1, inwidth, outwidth);
1400                                 Image_Resample32LerpLine (inrow + inwidth4, resamplerow2, inwidth, outwidth);
1401                                 oldy = yi;
1402                         }
1403                         j = outwidth - 4;
1404                         while(j >= 0)
1405                         {
1406                                 LERPBYTE( 0);
1407                                 LERPBYTE( 1);
1408                                 LERPBYTE( 2);
1409                                 LERPBYTE( 3);
1410                                 LERPBYTE( 4);
1411                                 LERPBYTE( 5);
1412                                 LERPBYTE( 6);
1413                                 LERPBYTE( 7);
1414                                 LERPBYTE( 8);
1415                                 LERPBYTE( 9);
1416                                 LERPBYTE(10);
1417                                 LERPBYTE(11);
1418                                 LERPBYTE(12);
1419                                 LERPBYTE(13);
1420                                 LERPBYTE(14);
1421                                 LERPBYTE(15);
1422                                 out += 16;
1423                                 resamplerow1 += 16;
1424                                 resamplerow2 += 16;
1425                                 j -= 4;
1426                         }
1427                         if (j & 2)
1428                         {
1429                                 LERPBYTE( 0);
1430                                 LERPBYTE( 1);
1431                                 LERPBYTE( 2);
1432                                 LERPBYTE( 3);
1433                                 LERPBYTE( 4);
1434                                 LERPBYTE( 5);
1435                                 LERPBYTE( 6);
1436                                 LERPBYTE( 7);
1437                                 out += 8;
1438                                 resamplerow1 += 8;
1439                                 resamplerow2 += 8;
1440                         }
1441                         if (j & 1)
1442                         {
1443                                 LERPBYTE( 0);
1444                                 LERPBYTE( 1);
1445                                 LERPBYTE( 2);
1446                                 LERPBYTE( 3);
1447                                 out += 4;
1448                                 resamplerow1 += 4;
1449                                 resamplerow2 += 4;
1450                         }
1451                         resamplerow1 -= outwidth4;
1452                         resamplerow2 -= outwidth4;
1453                 }
1454                 else
1455                 {
1456                         if (yi != oldy)
1457                         {
1458                                 inrow = (unsigned char *)indata + inwidth4*yi;
1459                                 if (yi == oldy+1)
1460                                         memcpy(resamplerow1, resamplerow2, outwidth4);
1461                                 else
1462                                         Image_Resample32LerpLine (inrow, resamplerow1, inwidth, outwidth);
1463                                 oldy = yi;
1464                         }
1465                         memcpy(out, resamplerow1, outwidth4);
1466                 }
1467         }
1468
1469         Mem_Free(resamplerow1);
1470         resamplerow1 = NULL;
1471         resamplerow2 = NULL;
1472 }
1473
1474 static void Image_Resample32Nolerp(const void *indata, int inwidth, int inheight, void *outdata, int outwidth, int outheight)
1475 {
1476         int i, j;
1477         unsigned frac, fracstep;
1478         // relies on int being 4 bytes
1479         int *inrow, *out;
1480         out = (int *)outdata;
1481
1482         fracstep = inwidth*0x10000/outwidth;
1483         for (i = 0;i < outheight;i++)
1484         {
1485                 inrow = (int *)indata + inwidth*(i*inheight/outheight);
1486                 frac = fracstep >> 1;
1487                 j = outwidth - 4;
1488                 while (j >= 0)
1489                 {
1490                         out[0] = inrow[frac >> 16];frac += fracstep;
1491                         out[1] = inrow[frac >> 16];frac += fracstep;
1492                         out[2] = inrow[frac >> 16];frac += fracstep;
1493                         out[3] = inrow[frac >> 16];frac += fracstep;
1494                         out += 4;
1495                         j -= 4;
1496                 }
1497                 if (j & 2)
1498                 {
1499                         out[0] = inrow[frac >> 16];frac += fracstep;
1500                         out[1] = inrow[frac >> 16];frac += fracstep;
1501                         out += 2;
1502                 }
1503                 if (j & 1)
1504                 {
1505                         out[0] = inrow[frac >> 16];frac += fracstep;
1506                         out += 1;
1507                 }
1508         }
1509 }
1510
1511 /*
1512 ================
1513 Image_Resample
1514 ================
1515 */
1516 void Image_Resample32(const void *indata, int inwidth, int inheight, int indepth, void *outdata, int outwidth, int outheight, int outdepth, int quality)
1517 {
1518         if (indepth != 1 || outdepth != 1)
1519         {
1520                 Con_Printf ("Image_Resample: 3D resampling not supported\n");
1521                 return;
1522         }
1523         if (quality)
1524                 Image_Resample32Lerp(indata, inwidth, inheight, outdata, outwidth, outheight);
1525         else
1526                 Image_Resample32Nolerp(indata, inwidth, inheight, outdata, outwidth, outheight);
1527 }
1528
1529 // in can be the same as out
1530 void Image_MipReduce32(const unsigned char *in, unsigned char *out, int *width, int *height, int *depth, int destwidth, int destheight, int destdepth)
1531 {
1532         const unsigned char *inrow;
1533         int x, y, nextrow;
1534         if (*depth != 1 || destdepth != 1)
1535         {
1536                 Con_Printf ("Image_Resample: 3D resampling not supported\n");
1537                 if (*width > destwidth)
1538                         *width >>= 1;
1539                 if (*height > destheight)
1540                         *height >>= 1;
1541                 if (*depth > destdepth)
1542                         *depth >>= 1;
1543                 return;
1544         }
1545         // note: if given odd width/height this discards the last row/column of
1546         // pixels, rather than doing a proper box-filter scale down
1547         inrow = in;
1548         nextrow = *width * 4;
1549         if (*width > destwidth)
1550         {
1551                 *width >>= 1;
1552                 if (*height > destheight)
1553                 {
1554                         // reduce both
1555                         *height >>= 1;
1556                         for (y = 0;y < *height;y++, inrow += nextrow * 2)
1557                         {
1558                                 for (in = inrow, x = 0;x < *width;x++)
1559                                 {
1560                                         out[0] = (unsigned char) ((in[0] + in[4] + in[nextrow  ] + in[nextrow+4]) >> 2);
1561                                         out[1] = (unsigned char) ((in[1] + in[5] + in[nextrow+1] + in[nextrow+5]) >> 2);
1562                                         out[2] = (unsigned char) ((in[2] + in[6] + in[nextrow+2] + in[nextrow+6]) >> 2);
1563                                         out[3] = (unsigned char) ((in[3] + in[7] + in[nextrow+3] + in[nextrow+7]) >> 2);
1564                                         out += 4;
1565                                         in += 8;
1566                                 }
1567                         }
1568                 }
1569                 else
1570                 {
1571                         // reduce width
1572                         for (y = 0;y < *height;y++, inrow += nextrow)
1573                         {
1574                                 for (in = inrow, x = 0;x < *width;x++)
1575                                 {
1576                                         out[0] = (unsigned char) ((in[0] + in[4]) >> 1);
1577                                         out[1] = (unsigned char) ((in[1] + in[5]) >> 1);
1578                                         out[2] = (unsigned char) ((in[2] + in[6]) >> 1);
1579                                         out[3] = (unsigned char) ((in[3] + in[7]) >> 1);
1580                                         out += 4;
1581                                         in += 8;
1582                                 }
1583                         }
1584                 }
1585         }
1586         else
1587         {
1588                 if (*height > destheight)
1589                 {
1590                         // reduce height
1591                         *height >>= 1;
1592                         for (y = 0;y < *height;y++, inrow += nextrow * 2)
1593                         {
1594                                 for (in = inrow, x = 0;x < *width;x++)
1595                                 {
1596                                         out[0] = (unsigned char) ((in[0] + in[nextrow  ]) >> 1);
1597                                         out[1] = (unsigned char) ((in[1] + in[nextrow+1]) >> 1);
1598                                         out[2] = (unsigned char) ((in[2] + in[nextrow+2]) >> 1);
1599                                         out[3] = (unsigned char) ((in[3] + in[nextrow+3]) >> 1);
1600                                         out += 4;
1601                                         in += 4;
1602                                 }
1603                         }
1604                 }
1605                 else
1606                         Con_Printf ("Image_MipReduce: desired size already achieved\n");
1607         }
1608 }
1609
1610 void Image_HeightmapToNormalmap_BGRA(const unsigned char *inpixels, unsigned char *outpixels, int width, int height, int clamp, float bumpscale)
1611 {
1612         int x, y, x1, x2, y1, y2;
1613         const unsigned char *b, *row[3];
1614         int p[5];
1615         unsigned char *out;
1616         float ibumpscale, n[3];
1617         ibumpscale = (255.0f * 6.0f) / bumpscale;
1618         out = outpixels;
1619         for (y = 0, y1 = height-1;y < height;y1 = y, y++)
1620         {
1621                 y2 = y + 1;if (y2 >= height) y2 = 0;
1622                 row[0] = inpixels + (y1 * width) * 4;
1623                 row[1] = inpixels + (y  * width) * 4;
1624                 row[2] = inpixels + (y2 * width) * 4;
1625                 for (x = 0, x1 = width-1;x < width;x1 = x, x++)
1626                 {
1627                         x2 = x + 1;if (x2 >= width) x2 = 0;
1628                         // left, right
1629                         b = row[1] + x1 * 4;p[0] = (b[0] + b[1] + b[2]);
1630                         b = row[1] + x2 * 4;p[1] = (b[0] + b[1] + b[2]);
1631                         // above, below
1632                         b = row[0] + x  * 4;p[2] = (b[0] + b[1] + b[2]);
1633                         b = row[2] + x  * 4;p[3] = (b[0] + b[1] + b[2]);
1634                         // center
1635                         b = row[1] + x  * 4;p[4] = (b[0] + b[1] + b[2]);
1636                         // calculate a normal from the slopes
1637                         n[0] = p[0] - p[1];
1638                         n[1] = p[3] - p[2];
1639                         n[2] = ibumpscale;
1640                         VectorNormalize(n);
1641                         // turn it into a dot3 rgb vector texture
1642                         out[2] = (int)(128.0f + n[0] * 127.0f);
1643                         out[1] = (int)(128.0f + n[1] * 127.0f);
1644                         out[0] = (int)(128.0f + n[2] * 127.0f);
1645                         out[3] = (p[4]) / 3;
1646                         out += 4;
1647                 }
1648         }
1649 }