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