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