d5123408c96141dd56849b2e5b29bc0321c53407
[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 += numoutputcomponents)
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 += numoutputcomponents)
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 += numoutputcomponents)
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 += numoutputcomponents)
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_Copy8bitBGRA(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_BGRA (const unsigned char *f, int filesize)
185 {
186         pcx_t pcx;
187         unsigned char *a, *b, *image_buffer, *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
220         palette = f + filesize - 768;
221
222         image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width*image_height*4);
223         if (!image_buffer)
224         {
225                 Con_Printf("LoadPCX: not enough memory for %i by %i image\n", image_width, image_height);
226                 return NULL;
227         }
228         pbuf = image_buffer + image_width*image_height*3;
229         enddata = palette;
230
231         for (y = 0;y < image_height && fin < enddata;y++)
232         {
233                 a = pbuf + y * image_width;
234                 for (x = 0;x < image_width && fin < enddata;)
235                 {
236                         dataByte = *fin++;
237                         if(dataByte >= 0xC0)
238                         {
239                                 if (fin >= enddata)
240                                         break;
241                                 x2 = x + (dataByte & 0x3F);
242                                 dataByte = *fin++;
243                                 if (x2 > image_width)
244                                         x2 = image_width; // technically an error
245                                 while(x < x2)
246                                         a[x++] = dataByte;
247                         }
248                         else
249                                 a[x++] = dataByte;
250                 }
251                 fin += pcx.bytes_per_line - image_width; // the number of bytes per line is always forced to an even number
252                 while(x < image_width)
253                         a[x++] = 0;
254         }
255
256         a = image_buffer;
257         b = pbuf;
258
259         for(x = 0;x < image_width*image_height;x++)
260         {
261                 y = *b++ * 3;
262                 *a++ = palette[y+2];
263                 *a++ = palette[y+1];
264                 *a++ = palette[y];
265                 *a++ = 255;
266         }
267
268         return image_buffer;
269 }
270
271 /*
272 =========================================================
273
274 TARGA LOADING
275
276 =========================================================
277 */
278
279 typedef struct _TargaHeader
280 {
281         unsigned char   id_length, colormap_type, image_type;
282         unsigned short  colormap_index, colormap_length;
283         unsigned char   colormap_size;
284         unsigned short  x_origin, y_origin, width, height;
285         unsigned char   pixel_size, attributes;
286 }
287 TargaHeader;
288
289 void PrintTargaHeader(TargaHeader *t)
290 {
291         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);
292 }
293
294 /*
295 =============
296 LoadTGA
297 =============
298 */
299 unsigned char *LoadTGA_BGRA (const unsigned char *f, int filesize)
300 {
301         int x, y, pix_inc, row_inci, runlen, alphabits;
302         unsigned char *image_buffer;
303         unsigned int *pixbufi;
304         const unsigned char *fin, *enddata;
305         TargaHeader targa_header;
306         unsigned int palettei[256];
307         union
308         {
309                 unsigned int i;
310                 unsigned char b[4];
311         }
312         bgra;
313
314         if (filesize < 19)
315                 return NULL;
316
317         enddata = f + filesize;
318
319         targa_header.id_length = f[0];
320         targa_header.colormap_type = f[1];
321         targa_header.image_type = f[2];
322
323         targa_header.colormap_index = f[3] + f[4] * 256;
324         targa_header.colormap_length = f[5] + f[6] * 256;
325         targa_header.colormap_size = f[7];
326         targa_header.x_origin = f[8] + f[9] * 256;
327         targa_header.y_origin = f[10] + f[11] * 256;
328         targa_header.width = image_width = f[12] + f[13] * 256;
329         targa_header.height = image_height = f[14] + f[15] * 256;
330         targa_header.pixel_size = f[16];
331         targa_header.attributes = f[17];
332
333         if (image_width > 4096 || image_height > 4096 || image_width <= 0 || image_height <= 0)
334         {
335                 Con_Print("LoadTGA: invalid size\n");
336                 PrintTargaHeader(&targa_header);
337                 return NULL;
338         }
339
340         // advance to end of header
341         fin = f + 18;
342
343         // skip TARGA image comment (usually 0 bytes)
344         fin += targa_header.id_length;
345
346         // read/skip the colormap if present (note: according to the TARGA spec it
347         // can be present even on truecolor or greyscale images, just not used by
348         // the image data)
349         if (targa_header.colormap_type)
350         {
351                 if (targa_header.colormap_length > 256)
352                 {
353                         Con_Print("LoadTGA: only up to 256 colormap_length supported\n");
354                         PrintTargaHeader(&targa_header);
355                         return NULL;
356                 }
357                 if (targa_header.colormap_index)
358                 {
359                         Con_Print("LoadTGA: colormap_index not supported\n");
360                         PrintTargaHeader(&targa_header);
361                         return NULL;
362                 }
363                 if (targa_header.colormap_size == 24)
364                 {
365                         for (x = 0;x < targa_header.colormap_length;x++)
366                         {
367                                 bgra.b[0] = *fin++;
368                                 bgra.b[1] = *fin++;
369                                 bgra.b[2] = *fin++;
370                                 bgra.b[3] = 255;
371                                 palettei[x] = bgra.i;
372                         }
373                 }
374                 else if (targa_header.colormap_size == 32)
375                 {
376                         memcpy(palettei, fin, targa_header.colormap_length*4);
377                         fin += targa_header.colormap_length * 4;
378                 }
379                 else
380                 {
381                         Con_Print("LoadTGA: Only 32 and 24 bit colormap_size supported\n");
382                         PrintTargaHeader(&targa_header);
383                         return NULL;
384                 }
385         }
386
387         // check our pixel_size restrictions according to image_type
388         switch (targa_header.image_type & ~8)
389         {
390         case 2:
391                 if (targa_header.pixel_size != 24 && targa_header.pixel_size != 32)
392                 {
393                         Con_Print("LoadTGA: only 24bit and 32bit pixel sizes supported for type 2 and type 10 images\n");
394                         PrintTargaHeader(&targa_header);
395                         return NULL;
396                 }
397                 break;
398         case 3:
399                 // set up a palette to make the loader easier
400                 for (x = 0;x < 256;x++)
401                 {
402                         bgra.b[0] = bgra.b[1] = bgra.b[2] = x;
403                         bgra.b[3] = 255;
404                         palettei[x] = bgra.i;
405                 }
406                 // fall through to colormap case
407         case 1:
408                 if (targa_header.pixel_size != 8)
409                 {
410                         Con_Print("LoadTGA: only 8bit pixel size for type 1, 3, 9, and 11 images supported\n");
411                         PrintTargaHeader(&targa_header);
412                         return NULL;
413                 }
414                 break;
415         default:
416                 Con_Printf("LoadTGA: Only type 1, 2, 3, 9, 10, and 11 targa RGB images supported, image_type = %i\n", targa_header.image_type);
417                 PrintTargaHeader(&targa_header);
418                 return NULL;
419         }
420
421         if (targa_header.attributes & 0x10)
422         {
423                 Con_Print("LoadTGA: origin must be in top left or bottom left, top right and bottom right are not supported\n");
424                 return NULL;
425         }
426
427         // number of attribute bits per pixel, we only support 0 or 8
428         alphabits = targa_header.attributes & 0x0F;
429         if (alphabits != 8 && alphabits != 0)
430         {
431                 Con_Print("LoadTGA: only 0 or 8 attribute (alpha) bits supported\n");
432                 return NULL;
433         }
434
435         image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
436         if (!image_buffer)
437         {
438                 Con_Printf("LoadTGA: not enough memory for %i by %i image\n", image_width, image_height);
439                 return NULL;
440         }
441
442         // If bit 5 of attributes isn't set, the image has been stored from bottom to top
443         if ((targa_header.attributes & 0x20) == 0)
444         {
445                 pixbufi = (unsigned int*)image_buffer + (image_height - 1)*image_width;
446                 row_inci = -image_width*2;
447         }
448         else
449         {
450                 pixbufi = (unsigned int*)image_buffer;
451                 row_inci = 0;
452         }
453
454         x = 0;
455         y = 0;
456         pix_inc = 1;
457         if ((targa_header.image_type & ~8) == 2)
458                 pix_inc = (targa_header.pixel_size + 7) / 8;
459         switch (targa_header.image_type)
460         {
461         case 1: // colormapped, uncompressed
462         case 3: // greyscale, uncompressed
463                 if (fin + image_width * image_height * pix_inc > enddata)
464                         break;
465                 for (y = 0;y < image_height;y++, pixbufi += row_inci)
466                         for (x = 0;x < image_width;x++)
467                                 *pixbufi++ = palettei[*fin++];
468                 break;
469         case 2:
470                 // BGR or BGRA, uncompressed
471                 if (fin + image_width * image_height * pix_inc > enddata)
472                         break;
473                 if (targa_header.pixel_size == 32 && alphabits)
474                 {
475                         for (y = 0;y < image_height;y++)
476                                 memcpy(pixbufi + y * (image_width + row_inci), fin + y * image_width * pix_inc, image_width*4);
477                 }
478                 else
479                 {
480                         for (y = 0;y < image_height;y++, pixbufi += row_inci)
481                         {
482                                 for (x = 0;x < image_width;x++, fin += pix_inc)
483                                 {
484                                         bgra.b[0] = fin[0];
485                                         bgra.b[1] = fin[1];
486                                         bgra.b[2] = fin[2];
487                                         bgra.b[3] = 255;
488                                         *pixbufi++ = bgra.i;
489                                 }
490                         }
491                 }
492                 break;
493         case 9: // colormapped, RLE
494         case 11: // greyscale, RLE
495                 for (y = 0;y < image_height;y++, pixbufi += row_inci)
496                 {
497                         for (x = 0;x < image_width;)
498                         {
499                                 if (fin >= enddata)
500                                         break; // error - truncated file
501                                 runlen = *fin++;
502                                 if (runlen & 0x80)
503                                 {
504                                         // RLE - all pixels the same color
505                                         runlen += 1 - 0x80;
506                                         if (fin + pix_inc > enddata)
507                                                 break; // error - truncated file
508                                         if (x + runlen > image_width)
509                                                 break; // error - line exceeds width
510                                         bgra.i = palettei[*fin++];
511                                         for (;runlen--;x++)
512                                                 *pixbufi++ = bgra.i;
513                                 }
514                                 else
515                                 {
516                                         // uncompressed - all pixels different color
517                                         runlen++;
518                                         if (fin + pix_inc * runlen > enddata)
519                                                 break; // error - truncated file
520                                         if (x + runlen > image_width)
521                                                 break; // error - line exceeds width
522                                         for (;runlen--;x++)
523                                                 *pixbufi++ = palettei[*fin++];
524                                 }
525                         }
526                 }
527                 break;
528         case 10:
529                 // BGR or BGRA, RLE
530                 if (targa_header.pixel_size == 32 && alphabits)
531                 {
532                         for (y = 0;y < image_height;y++, pixbufi += row_inci)
533                         {
534                                 for (x = 0;x < image_width;)
535                                 {
536                                         if (fin >= enddata)
537                                                 break; // error - truncated file
538                                         runlen = *fin++;
539                                         if (runlen & 0x80)
540                                         {
541                                                 // RLE - all pixels the same color
542                                                 runlen += 1 - 0x80;
543                                                 if (fin + pix_inc > enddata)
544                                                         break; // error - truncated file
545                                                 if (x + runlen > image_width)
546                                                         break; // error - line exceeds width
547                                                 bgra.b[0] = fin[0];
548                                                 bgra.b[1] = fin[1];
549                                                 bgra.b[2] = fin[2];
550                                                 bgra.b[3] = fin[3];
551                                                 fin += pix_inc;
552                                                 for (;runlen--;x++)
553                                                         *pixbufi++ = bgra.i;
554                                         }
555                                         else
556                                         {
557                                                 // uncompressed - all pixels different color
558                                                 runlen++;
559                                                 if (fin + pix_inc * runlen > enddata)
560                                                         break; // error - truncated file
561                                                 if (x + runlen > image_width)
562                                                         break; // error - line exceeds width
563                                                 for (;runlen--;x++)
564                                                 {
565                                                         bgra.b[0] = fin[0];
566                                                         bgra.b[1] = fin[1];
567                                                         bgra.b[2] = fin[2];
568                                                         bgra.b[3] = fin[3];
569                                                         fin += pix_inc;
570                                                         *pixbufi++ = bgra.i;
571                                                 }
572                                         }
573                                 }
574                         }
575                 }
576                 else
577                 {
578                         for (y = 0;y < image_height;y++, pixbufi += row_inci)
579                         {
580                                 for (x = 0;x < image_width;)
581                                 {
582                                         if (fin >= enddata)
583                                                 break; // error - truncated file
584                                         runlen = *fin++;
585                                         if (runlen & 0x80)
586                                         {
587                                                 // RLE - all pixels the same color
588                                                 runlen += 1 - 0x80;
589                                                 if (fin + pix_inc > enddata)
590                                                         break; // error - truncated file
591                                                 if (x + runlen > image_width)
592                                                         break; // error - line exceeds width
593                                                 bgra.b[0] = fin[0];
594                                                 bgra.b[1] = fin[1];
595                                                 bgra.b[2] = fin[2];
596                                                 bgra.b[3] = 255;
597                                                 fin += pix_inc;
598                                                 for (;runlen--;x++)
599                                                         *pixbufi++ = bgra.i;
600                                         }
601                                         else
602                                         {
603                                                 // uncompressed - all pixels different color
604                                                 runlen++;
605                                                 if (fin + pix_inc * runlen > enddata)
606                                                         break; // error - truncated file
607                                                 if (x + runlen > image_width)
608                                                         break; // error - line exceeds width
609                                                 for (;runlen--;x++)
610                                                 {
611                                                         bgra.b[0] = fin[0];
612                                                         bgra.b[1] = fin[1];
613                                                         bgra.b[2] = fin[2];
614                                                         bgra.b[3] = 255;
615                                                         fin += pix_inc;
616                                                         *pixbufi++ = bgra.i;
617                                                 }
618                                         }
619                                 }
620                         }
621                 }
622                 break;
623         default:
624                 // unknown image_type
625                 break;
626         }
627
628         return image_buffer;
629 }
630
631 typedef struct q2wal_s
632 {
633         char            name[32];
634         unsigned        width, height;
635         unsigned        offsets[MIPLEVELS];             // four mip maps stored
636         char            animname[32];                   // next frame in animation chain
637         int                     flags;
638         int                     contents;
639         int                     value;
640 } q2wal_t;
641
642 unsigned char *LoadWAL_BGRA (const unsigned char *f, int filesize)
643 {
644         unsigned char *image_buffer;
645         const q2wal_t *inwal = (const q2wal_t *)f;
646
647         if (filesize < (int) sizeof(q2wal_t))
648         {
649                 Con_Print("LoadWAL: invalid WAL file\n");
650                 return NULL;
651         }
652
653         image_width = LittleLong(inwal->width);
654         image_height = LittleLong(inwal->height);
655         if (image_width > 4096 || image_height > 4096 || image_width <= 0 || image_height <= 0)
656         {
657                 Con_Printf("LoadWAL: invalid size %ix%i\n", image_width, image_height);
658                 return NULL;
659         }
660
661         if (filesize < (int) sizeof(q2wal_t) + (int) LittleLong(inwal->offsets[0]) + image_width * image_height)
662         {
663                 Con_Print("LoadWAL: invalid WAL file\n");
664                 return NULL;
665         }
666
667         image_buffer = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
668         if (!image_buffer)
669         {
670                 Con_Printf("LoadWAL: not enough memory for %i by %i image\n", image_width, image_height);
671                 return NULL;
672         }
673         Image_Copy8bitBGRA(f + LittleLong(inwal->offsets[0]), image_buffer, image_width * image_height, palette_bgra_complete);
674         return image_buffer;
675 }
676
677
678 void Image_StripImageExtension (const char *in, char *out, size_t size_out)
679 {
680         const char *ext;
681
682         if (size_out == 0)
683                 return;
684
685         ext = FS_FileExtension(in);
686         if (ext && (!strcmp(ext, "tga") || !strcmp(ext, "pcx") || !strcmp(ext, "lmp") || !strcmp(ext, "png") || !strcmp(ext, "jpg")))
687                 FS_StripExtension(in, out, size_out);
688         else
689                 strlcpy(out, in, size_out);
690 }
691
692 typedef struct imageformat_s
693 {
694         const char *formatstring;
695         unsigned char *(*loadfunc)(const unsigned char *f, int filesize);
696 }
697 imageformat_t;
698
699 // GAME_TENEBRAE only
700 imageformat_t imageformats_tenebrae[] =
701 {
702         {"override/%s.tga", LoadTGA_BGRA},
703         {"override/%s.png", PNG_LoadImage_BGRA},
704         {"override/%s.jpg", JPEG_LoadImage_BGRA},
705         {"override/%s.pcx", LoadPCX_BGRA},
706         {"%s.tga", LoadTGA_BGRA},
707         {"%s.png", PNG_LoadImage_BGRA},
708         {"%s.jpg", JPEG_LoadImage_BGRA},
709         {"%s.pcx", LoadPCX_BGRA},
710         {NULL, NULL}
711 };
712
713 imageformat_t imageformats_nopath[] =
714 {
715         {"override/%s.tga", LoadTGA_BGRA},
716         {"override/%s.png", PNG_LoadImage_BGRA},
717         {"override/%s.jpg", JPEG_LoadImage_BGRA},
718         {"textures/%s.tga", LoadTGA_BGRA},
719         {"textures/%s.png", PNG_LoadImage_BGRA},
720         {"textures/%s.jpg", JPEG_LoadImage_BGRA},
721         {"%s.tga", LoadTGA_BGRA},
722         {"%s.png", PNG_LoadImage_BGRA},
723         {"%s.jpg", JPEG_LoadImage_BGRA},
724         {"%s.pcx", LoadPCX_BGRA},
725         {NULL, NULL}
726 };
727
728 // GAME_DELUXEQUAKE only
729 // VorteX: the point why i use such messy texture paths is
730 // that GtkRadiant can't detect normal/gloss textures
731 // and exclude them from texture browser
732 // so i just use additional folder to store this textures
733 imageformat_t imageformats_dq[] =
734 {
735         {"%s.tga", LoadTGA_BGRA},
736         {"%s.jpg", JPEG_LoadImage_BGRA},
737         {"texturemaps/%s.tga", LoadTGA_BGRA},
738         {"texturemaps/%s.jpg", JPEG_LoadImage_BGRA},
739         {NULL, NULL}
740 };
741
742 imageformat_t imageformats_textures[] =
743 {
744         {"%s.tga", LoadTGA_BGRA},
745         {"%s.png", PNG_LoadImage_BGRA},
746         {"%s.jpg", JPEG_LoadImage_BGRA},
747         {"%s.pcx", LoadPCX_BGRA},
748         {"%s.wal", LoadWAL_BGRA},
749         {NULL, NULL}
750 };
751
752 imageformat_t imageformats_gfx[] =
753 {
754         {"%s.tga", LoadTGA_BGRA},
755         {"%s.png", PNG_LoadImage_BGRA},
756         {"%s.jpg", JPEG_LoadImage_BGRA},
757         {"%s.pcx", LoadPCX_BGRA},
758         {NULL, NULL}
759 };
760
761 imageformat_t imageformats_other[] =
762 {
763         {"%s.tga", LoadTGA_BGRA},
764         {"%s.png", PNG_LoadImage_BGRA},
765         {"%s.jpg", JPEG_LoadImage_BGRA},
766         {"%s.pcx", LoadPCX_BGRA},
767         {NULL, NULL}
768 };
769
770 int fixtransparentpixels(unsigned char *data, int w, int h);
771 unsigned char *loadimagepixelsbgra (const char *filename, qboolean complain, qboolean allowFixtrans)
772 {
773         fs_offset_t filesize;
774         imageformat_t *firstformat, *format;
775         unsigned char *f, *data = NULL;
776         char basename[MAX_QPATH], name[MAX_QPATH], *c;
777         if (developer_memorydebug.integer)
778                 Mem_CheckSentinelsGlobal();
779         if (developer_texturelogging.integer)
780                 Log_Printf("textures.log", "%s\n", filename);
781         Image_StripImageExtension(filename, basename, sizeof(basename)); // strip filename extensions to allow replacement by other types
782         // replace *'s with #, so commandline utils don't get confused when dealing with the external files
783         for (c = basename;*c;c++)
784                 if (*c == '*')
785                         *c = '#';
786         name[0] = 0;
787         if (strchr(basename, '/'))
788         {
789                 int i;
790                 for (i = 0;i < (int)sizeof(name)-1 && basename[i] != '/';i++)
791                         name[i] = basename[i];
792                 name[i] = 0;
793         }
794         if (gamemode == GAME_TENEBRAE)
795                 firstformat = imageformats_tenebrae;
796         else if (gamemode == GAME_DELUXEQUAKE)
797                 firstformat = imageformats_dq;
798         else if (!strcasecmp(name, "textures"))
799                 firstformat = imageformats_textures;
800         else if (!strcasecmp(name, "gfx"))
801                 firstformat = imageformats_gfx;
802         else if (!strchr(basename, '/'))
803                 firstformat = imageformats_nopath;
804         else
805                 firstformat = imageformats_other;
806         // now try all the formats in the selected list
807         for (format = firstformat;format->formatstring;format++)
808         {
809                 dpsnprintf (name, sizeof(name), format->formatstring, basename);
810                 f = FS_LoadFile(name, tempmempool, true, &filesize);
811                 if (f)
812                 {
813                         data = format->loadfunc(f, filesize);
814                         Mem_Free(f);
815                         if (data)
816                         {
817                                 if (developer.integer >= 10)
818                                         Con_Printf("loaded image %s (%dx%d)\n", name, image_width, image_height);
819                                 if (developer_memorydebug.integer)
820                                         Mem_CheckSentinelsGlobal();
821                                 if(allowFixtrans && r_fixtrans_auto.integer)
822                                 {
823                                         int n = fixtransparentpixels(data, image_width, image_height);
824                                         if(n)
825                                         {
826                                                 Con_Printf("- had to fix %s (%d pixels changed)\n", name, n);
827                                                 if(r_fixtrans_auto.integer >= 2)
828                                                 {
829                                                         char outfilename[MAX_QPATH], buf[MAX_QPATH];
830                                                         Image_StripImageExtension(name, buf, sizeof(buf));
831                                                         dpsnprintf(outfilename, sizeof(outfilename), "fixtrans/%s.tga", buf);
832                                                         Image_WriteTGABGRA(outfilename, image_width, image_height, data);
833                                                         Con_Printf("- %s written.\n", outfilename);
834                                                 }
835                                         }
836                                 }
837                                 return data;
838                         }
839                         else
840                                 Con_DPrintf("Error loading image %s (file loaded but decode failed)\n", name);
841                 }
842         }
843         if (complain)
844         {
845                 Con_Printf("Couldn't load %s using ", filename);
846                 for (format = firstformat;format->formatstring;format++)
847                 {
848                         dpsnprintf (name, sizeof(name), format->formatstring, basename);
849                         Con_Printf(format == firstformat ? "\"%s\"" : (format[1].formatstring ? ", \"%s\"" : " or \"%s\".\n"), format->formatstring);
850                 }
851         }
852
853         // texture loading can take a while, so make sure we're sending keepalives
854         CL_KeepaliveMessage(false);
855
856         if (developer_memorydebug.integer)
857                 Mem_CheckSentinelsGlobal();
858         return NULL;
859 }
860
861 rtexture_t *loadtextureimage (rtexturepool_t *pool, const char *filename, qboolean complain, int flags, qboolean allowFixtrans)
862 {
863         unsigned char *data;
864         rtexture_t *rt;
865         if (!(data = loadimagepixelsbgra (filename, complain, allowFixtrans)))
866                 return 0;
867         rt = R_LoadTexture2D(pool, filename, image_width, image_height, data, TEXTYPE_BGRA, flags, NULL);
868         Mem_Free(data);
869         return rt;
870 }
871
872 int fixtransparentpixels(unsigned char *data, int w, int h)
873 {
874         int const FIXTRANS_NEEDED = 1;
875         int const FIXTRANS_HAS_L = 2;
876         int const FIXTRANS_HAS_R = 4;
877         int const FIXTRANS_HAS_U = 8;
878         int const FIXTRANS_HAS_D = 16;
879         int const FIXTRANS_FIXED = 32;
880         unsigned char *fixMask = (unsigned char *) Mem_Alloc(tempmempool, w * h);
881         int fixPixels = 0;
882         int changedPixels = 0;
883         int x, y;
884
885 #define FIXTRANS_PIXEL (y*w+x)
886 #define FIXTRANS_PIXEL_U (((y+h-1)%h)*w+x)
887 #define FIXTRANS_PIXEL_D (((y+1)%h)*w+x)
888 #define FIXTRANS_PIXEL_L (y*w+((x+w-1)%w))
889 #define FIXTRANS_PIXEL_R (y*w+((x+1)%w))
890
891         memset(fixMask, 0, w * h);
892         for(y = 0; y < h; ++y)
893                 for(x = 0; x < w; ++x)
894                 {
895                         if(data[FIXTRANS_PIXEL * 4 + 3] == 0)
896                         {
897                                 fixMask[FIXTRANS_PIXEL] |= FIXTRANS_NEEDED;
898                                 ++fixPixels;
899                         }
900                         else
901                         {
902                                 fixMask[FIXTRANS_PIXEL_D] |= FIXTRANS_HAS_U;
903                                 fixMask[FIXTRANS_PIXEL_U] |= FIXTRANS_HAS_D;
904                                 fixMask[FIXTRANS_PIXEL_R] |= FIXTRANS_HAS_L;
905                                 fixMask[FIXTRANS_PIXEL_L] |= FIXTRANS_HAS_R;
906                         }
907                 }
908         if(fixPixels == w * h)
909                 return 0; // sorry, can't do anything about this
910         while(fixPixels)
911         {
912                 for(y = 0; y < h; ++y)
913                         for(x = 0; x < w; ++x)
914                                 if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_NEEDED)
915                                 {
916                                         unsigned int sumR = 0, sumG = 0, sumB = 0, sumA = 0, sumRA = 0, sumGA = 0, sumBA = 0, cnt = 0;
917                                         unsigned char r, g, b, a, r0, g0, b0;
918                                         if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_HAS_U)
919                                         {
920                                                 r = data[FIXTRANS_PIXEL_U * 4 + 2];
921                                                 g = data[FIXTRANS_PIXEL_U * 4 + 1];
922                                                 b = data[FIXTRANS_PIXEL_U * 4 + 0];
923                                                 a = data[FIXTRANS_PIXEL_U * 4 + 3];
924                                                 sumR += r; sumG += g; sumB += b; sumA += a; sumRA += r*a; sumGA += g*a; sumBA += b*a; ++cnt;
925                                         }
926                                         if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_HAS_D)
927                                         {
928                                                 r = data[FIXTRANS_PIXEL_D * 4 + 2];
929                                                 g = data[FIXTRANS_PIXEL_D * 4 + 1];
930                                                 b = data[FIXTRANS_PIXEL_D * 4 + 0];
931                                                 a = data[FIXTRANS_PIXEL_D * 4 + 3];
932                                                 sumR += r; sumG += g; sumB += b; sumA += a; sumRA += r*a; sumGA += g*a; sumBA += b*a; ++cnt;
933                                         }
934                                         if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_HAS_L)
935                                         {
936                                                 r = data[FIXTRANS_PIXEL_L * 4 + 2];
937                                                 g = data[FIXTRANS_PIXEL_L * 4 + 1];
938                                                 b = data[FIXTRANS_PIXEL_L * 4 + 0];
939                                                 a = data[FIXTRANS_PIXEL_L * 4 + 3];
940                                                 sumR += r; sumG += g; sumB += b; sumA += a; sumRA += r*a; sumGA += g*a; sumBA += b*a; ++cnt;
941                                         }
942                                         if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_HAS_R)
943                                         {
944                                                 r = data[FIXTRANS_PIXEL_R * 4 + 2];
945                                                 g = data[FIXTRANS_PIXEL_R * 4 + 1];
946                                                 b = data[FIXTRANS_PIXEL_R * 4 + 0];
947                                                 a = data[FIXTRANS_PIXEL_R * 4 + 3];
948                                                 sumR += r; sumG += g; sumB += b; sumA += a; sumRA += r*a; sumGA += g*a; sumBA += b*a; ++cnt;
949                                         }
950                                         if(!cnt)
951                                                 continue;
952                                         r0 = data[FIXTRANS_PIXEL * 4 + 2];
953                                         g0 = data[FIXTRANS_PIXEL * 4 + 1];
954                                         b0 = data[FIXTRANS_PIXEL * 4 + 0];
955                                         if(sumA)
956                                         {
957                                                 // there is a surrounding non-alpha pixel
958                                                 r = (sumRA + sumA / 2) / sumA;
959                                                 g = (sumGA + sumA / 2) / sumA;
960                                                 b = (sumBA + sumA / 2) / sumA;
961                                         }
962                                         else
963                                         {
964                                                 // need to use a "regular" average
965                                                 r = (sumR + cnt / 2) / cnt;
966                                                 g = (sumG + cnt / 2) / cnt;
967                                                 b = (sumB + cnt / 2) / cnt;
968                                         }
969                                         if(r != r0 || g != g0 || b != b0)
970                                                 ++changedPixels;
971                                         data[FIXTRANS_PIXEL * 4 + 2] = r;
972                                         data[FIXTRANS_PIXEL * 4 + 1] = g;
973                                         data[FIXTRANS_PIXEL * 4 + 0] = b;
974                                         fixMask[FIXTRANS_PIXEL] |= FIXTRANS_FIXED;
975                                 }
976                 for(y = 0; y < h; ++y)
977                         for(x = 0; x < w; ++x)
978                                 if(fixMask[FIXTRANS_PIXEL] & FIXTRANS_FIXED)
979                                 {
980                                         fixMask[FIXTRANS_PIXEL] &= ~(FIXTRANS_NEEDED | FIXTRANS_FIXED);
981                                         fixMask[FIXTRANS_PIXEL_D] |= FIXTRANS_HAS_U;
982                                         fixMask[FIXTRANS_PIXEL_U] |= FIXTRANS_HAS_D;
983                                         fixMask[FIXTRANS_PIXEL_R] |= FIXTRANS_HAS_L;
984                                         fixMask[FIXTRANS_PIXEL_L] |= FIXTRANS_HAS_R;
985                                         --fixPixels;
986                                 }
987         }
988         return changedPixels;
989 }
990
991 void Image_FixTransparentPixels_f(void)
992 {
993         const char *filename, *filename_pattern;
994         fssearch_t *search;
995         int i, n;
996         char outfilename[MAX_QPATH], buf[MAX_QPATH];
997         unsigned char *data;
998         if(Cmd_Argc() != 2)
999         {
1000                 Con_Printf("Usage: %s imagefile\n", Cmd_Argv(0));
1001                 return;
1002         }
1003         filename_pattern = Cmd_Argv(1);
1004         search = FS_Search(filename_pattern, true, true);
1005         if(!search)
1006                 return;
1007         for(i = 0; i < search->numfilenames; ++i)
1008         {
1009                 filename = search->filenames[i];
1010                 Con_Printf("Processing %s... ", filename);
1011                 Image_StripImageExtension(filename, buf, sizeof(buf));
1012                 dpsnprintf(outfilename, sizeof(outfilename), "fixtrans/%s.tga", buf);
1013                 if(!(data = loadimagepixelsbgra(filename, true, false)))
1014                         return;
1015                 if((n = fixtransparentpixels(data, image_width, image_height)))
1016                 {
1017                         Image_WriteTGABGRA(outfilename, image_width, image_height, data);
1018                         Con_Printf("%s written (%d pixels changed).\n", outfilename, n);
1019                 }
1020                 else
1021                         Con_Printf("unchanged.\n");
1022                 Mem_Free(data);
1023         }
1024         FS_FreeSearch(search);
1025 }
1026
1027 qboolean Image_WriteTGABGR_preflipped (const char *filename, int width, int height, const unsigned char *data, unsigned char *buffer)
1028 {
1029         qboolean ret;
1030
1031         memset (buffer, 0, 18);
1032         buffer[2] = 2;          // uncompressed type
1033         buffer[12] = (width >> 0) & 0xFF;
1034         buffer[13] = (width >> 8) & 0xFF;
1035         buffer[14] = (height >> 0) & 0xFF;
1036         buffer[15] = (height >> 8) & 0xFF;
1037         buffer[16] = 24;        // pixel size
1038
1039         // swap rgb to bgr
1040         memcpy(buffer + 18, data, width*height*3);
1041         ret = FS_WriteFile (filename, buffer, width*height*3 + 18 );
1042
1043         return ret;
1044 }
1045
1046 void Image_WriteTGABGRA (const char *filename, int width, int height, const unsigned char *data)
1047 {
1048         int y;
1049         unsigned char *buffer, *out;
1050         const unsigned char *in, *end;
1051
1052         buffer = (unsigned char *)Mem_Alloc(tempmempool, width*height*4 + 18);
1053
1054         memset (buffer, 0, 18);
1055         buffer[2] = 2;          // uncompressed type
1056         buffer[12] = (width >> 0) & 0xFF;
1057         buffer[13] = (width >> 8) & 0xFF;
1058         buffer[14] = (height >> 0) & 0xFF;
1059         buffer[15] = (height >> 8) & 0xFF;
1060
1061         for (y = 3;y < width*height*4;y += 4)
1062                 if (data[y] < 255)
1063                         break;
1064
1065         if (y < width*height*4)
1066         {
1067                 // save the alpha channel
1068                 buffer[16] = 32;        // pixel size
1069                 buffer[17] = 8; // 8 bits of alpha
1070
1071                 // flip upside down
1072                 out = buffer + 18;
1073                 for (y = height - 1;y >= 0;y--)
1074                 {
1075                         memcpy(out, data + y * width * 4, width * 4);
1076                         out += width*4;
1077                 }
1078         }
1079         else
1080         {
1081                 // save only the color channels
1082                 buffer[16] = 24;        // pixel size
1083                 buffer[17] = 0; // 8 bits of alpha
1084
1085                 // truncate bgra to bgr and flip upside down
1086                 out = buffer + 18;
1087                 for (y = height - 1;y >= 0;y--)
1088                 {
1089                         in = data + y * width * 4;
1090                         end = in + width * 4;
1091                         for (;in < end;in += 4)
1092                         {
1093                                 *out++ = in[0];
1094                                 *out++ = in[1];
1095                                 *out++ = in[2];
1096                         }
1097                 }
1098         }
1099         FS_WriteFile (filename, buffer, out - buffer);
1100
1101         Mem_Free(buffer);
1102 }
1103
1104 static void Image_Resample32LerpLine (const unsigned char *in, unsigned char *out, int inwidth, int outwidth)
1105 {
1106         int             j, xi, oldx = 0, f, fstep, endx, lerp;
1107         fstep = (int) (inwidth*65536.0f/outwidth);
1108         endx = (inwidth-1);
1109         for (j = 0,f = 0;j < outwidth;j++, f += fstep)
1110         {
1111                 xi = f >> 16;
1112                 if (xi != oldx)
1113                 {
1114                         in += (xi - oldx) * 4;
1115                         oldx = xi;
1116                 }
1117                 if (xi < endx)
1118                 {
1119                         lerp = f & 0xFFFF;
1120                         *out++ = (unsigned char) ((((in[4] - in[0]) * lerp) >> 16) + in[0]);
1121                         *out++ = (unsigned char) ((((in[5] - in[1]) * lerp) >> 16) + in[1]);
1122                         *out++ = (unsigned char) ((((in[6] - in[2]) * lerp) >> 16) + in[2]);
1123                         *out++ = (unsigned char) ((((in[7] - in[3]) * lerp) >> 16) + in[3]);
1124                 }
1125                 else // last pixel of the line has no pixel to lerp to
1126                 {
1127                         *out++ = in[0];
1128                         *out++ = in[1];
1129                         *out++ = in[2];
1130                         *out++ = in[3];
1131                 }
1132         }
1133 }
1134
1135 #define LERPBYTE(i) r = resamplerow1[i];out[i] = (unsigned char) ((((resamplerow2[i] - r) * lerp) >> 16) + r)
1136 void Image_Resample32Lerp(const void *indata, int inwidth, int inheight, void *outdata, int outwidth, int outheight)
1137 {
1138         int i, j, r, yi, oldy, f, fstep, lerp, endy = (inheight-1), inwidth4 = inwidth*4, outwidth4 = outwidth*4;
1139         unsigned char *out;
1140         const unsigned char *inrow;
1141         unsigned char *resamplerow1;
1142         unsigned char *resamplerow2;
1143         out = (unsigned char *)outdata;
1144         fstep = (int) (inheight*65536.0f/outheight);
1145
1146         resamplerow1 = (unsigned char *)Mem_Alloc(tempmempool, outwidth*4*2);
1147         resamplerow2 = resamplerow1 + outwidth*4;
1148
1149         inrow = (const unsigned char *)indata;
1150         oldy = 0;
1151         Image_Resample32LerpLine (inrow, resamplerow1, inwidth, outwidth);
1152         Image_Resample32LerpLine (inrow + inwidth4, resamplerow2, inwidth, outwidth);
1153         for (i = 0, f = 0;i < outheight;i++,f += fstep)
1154         {
1155                 yi = f >> 16;
1156                 if (yi < endy)
1157                 {
1158                         lerp = f & 0xFFFF;
1159                         if (yi != oldy)
1160                         {
1161                                 inrow = (unsigned char *)indata + inwidth4*yi;
1162                                 if (yi == oldy+1)
1163                                         memcpy(resamplerow1, resamplerow2, outwidth4);
1164                                 else
1165                                         Image_Resample32LerpLine (inrow, resamplerow1, inwidth, outwidth);
1166                                 Image_Resample32LerpLine (inrow + inwidth4, resamplerow2, inwidth, outwidth);
1167                                 oldy = yi;
1168                         }
1169                         j = outwidth - 4;
1170                         while(j >= 0)
1171                         {
1172                                 LERPBYTE( 0);
1173                                 LERPBYTE( 1);
1174                                 LERPBYTE( 2);
1175                                 LERPBYTE( 3);
1176                                 LERPBYTE( 4);
1177                                 LERPBYTE( 5);
1178                                 LERPBYTE( 6);
1179                                 LERPBYTE( 7);
1180                                 LERPBYTE( 8);
1181                                 LERPBYTE( 9);
1182                                 LERPBYTE(10);
1183                                 LERPBYTE(11);
1184                                 LERPBYTE(12);
1185                                 LERPBYTE(13);
1186                                 LERPBYTE(14);
1187                                 LERPBYTE(15);
1188                                 out += 16;
1189                                 resamplerow1 += 16;
1190                                 resamplerow2 += 16;
1191                                 j -= 4;
1192                         }
1193                         if (j & 2)
1194                         {
1195                                 LERPBYTE( 0);
1196                                 LERPBYTE( 1);
1197                                 LERPBYTE( 2);
1198                                 LERPBYTE( 3);
1199                                 LERPBYTE( 4);
1200                                 LERPBYTE( 5);
1201                                 LERPBYTE( 6);
1202                                 LERPBYTE( 7);
1203                                 out += 8;
1204                                 resamplerow1 += 8;
1205                                 resamplerow2 += 8;
1206                         }
1207                         if (j & 1)
1208                         {
1209                                 LERPBYTE( 0);
1210                                 LERPBYTE( 1);
1211                                 LERPBYTE( 2);
1212                                 LERPBYTE( 3);
1213                                 out += 4;
1214                                 resamplerow1 += 4;
1215                                 resamplerow2 += 4;
1216                         }
1217                         resamplerow1 -= outwidth4;
1218                         resamplerow2 -= outwidth4;
1219                 }
1220                 else
1221                 {
1222                         if (yi != oldy)
1223                         {
1224                                 inrow = (unsigned char *)indata + inwidth4*yi;
1225                                 if (yi == oldy+1)
1226                                         memcpy(resamplerow1, resamplerow2, outwidth4);
1227                                 else
1228                                         Image_Resample32LerpLine (inrow, resamplerow1, inwidth, outwidth);
1229                                 oldy = yi;
1230                         }
1231                         memcpy(out, resamplerow1, outwidth4);
1232                 }
1233         }
1234
1235         Mem_Free(resamplerow1);
1236         resamplerow1 = NULL;
1237         resamplerow2 = NULL;
1238 }
1239
1240 void Image_Resample32Nolerp(const void *indata, int inwidth, int inheight, void *outdata, int outwidth, int outheight)
1241 {
1242         int i, j;
1243         unsigned frac, fracstep;
1244         // relies on int being 4 bytes
1245         int *inrow, *out;
1246         out = (int *)outdata;
1247
1248         fracstep = inwidth*0x10000/outwidth;
1249         for (i = 0;i < outheight;i++)
1250         {
1251                 inrow = (int *)indata + inwidth*(i*inheight/outheight);
1252                 frac = fracstep >> 1;
1253                 j = outwidth - 4;
1254                 while (j >= 0)
1255                 {
1256                         out[0] = inrow[frac >> 16];frac += fracstep;
1257                         out[1] = inrow[frac >> 16];frac += fracstep;
1258                         out[2] = inrow[frac >> 16];frac += fracstep;
1259                         out[3] = inrow[frac >> 16];frac += fracstep;
1260                         out += 4;
1261                         j -= 4;
1262                 }
1263                 if (j & 2)
1264                 {
1265                         out[0] = inrow[frac >> 16];frac += fracstep;
1266                         out[1] = inrow[frac >> 16];frac += fracstep;
1267                         out += 2;
1268                 }
1269                 if (j & 1)
1270                 {
1271                         out[0] = inrow[frac >> 16];frac += fracstep;
1272                         out += 1;
1273                 }
1274         }
1275 }
1276
1277 /*
1278 ================
1279 Image_Resample
1280 ================
1281 */
1282 void Image_Resample32(const void *indata, int inwidth, int inheight, int indepth, void *outdata, int outwidth, int outheight, int outdepth, int quality)
1283 {
1284         if (indepth != 1 || outdepth != 1)
1285         {
1286                 Con_Printf ("Image_Resample: 3D resampling not supported\n");
1287                 return;
1288         }
1289         if (quality)
1290                 Image_Resample32Lerp(indata, inwidth, inheight, outdata, outwidth, outheight);
1291         else
1292                 Image_Resample32Nolerp(indata, inwidth, inheight, outdata, outwidth, outheight);
1293 }
1294
1295 // in can be the same as out
1296 void Image_MipReduce32(const unsigned char *in, unsigned char *out, int *width, int *height, int *depth, int destwidth, int destheight, int destdepth)
1297 {
1298         const unsigned char *inrow;
1299         int x, y, nextrow;
1300         if (*depth != 1 || destdepth != 1)
1301         {
1302                 Con_Printf ("Image_Resample: 3D resampling not supported\n");
1303                 if (*width > destwidth)
1304                         *width >>= 1;
1305                 if (*height > destheight)
1306                         *height >>= 1;
1307                 if (*depth > destdepth)
1308                         *depth >>= 1;
1309                 return;
1310         }
1311         // note: if given odd width/height this discards the last row/column of
1312         // pixels, rather than doing a proper box-filter scale down
1313         inrow = in;
1314         nextrow = *width * 4;
1315         if (*width > destwidth)
1316         {
1317                 *width >>= 1;
1318                 if (*height > destheight)
1319                 {
1320                         // reduce both
1321                         *height >>= 1;
1322                         for (y = 0;y < *height;y++, inrow += nextrow * 2)
1323                         {
1324                                 for (in = inrow, x = 0;x < *width;x++)
1325                                 {
1326                                         out[0] = (unsigned char) ((in[0] + in[4] + in[nextrow  ] + in[nextrow+4]) >> 2);
1327                                         out[1] = (unsigned char) ((in[1] + in[5] + in[nextrow+1] + in[nextrow+5]) >> 2);
1328                                         out[2] = (unsigned char) ((in[2] + in[6] + in[nextrow+2] + in[nextrow+6]) >> 2);
1329                                         out[3] = (unsigned char) ((in[3] + in[7] + in[nextrow+3] + in[nextrow+7]) >> 2);
1330                                         out += 4;
1331                                         in += 8;
1332                                 }
1333                         }
1334                 }
1335                 else
1336                 {
1337                         // reduce width
1338                         for (y = 0;y < *height;y++, inrow += nextrow)
1339                         {
1340                                 for (in = inrow, x = 0;x < *width;x++)
1341                                 {
1342                                         out[0] = (unsigned char) ((in[0] + in[4]) >> 1);
1343                                         out[1] = (unsigned char) ((in[1] + in[5]) >> 1);
1344                                         out[2] = (unsigned char) ((in[2] + in[6]) >> 1);
1345                                         out[3] = (unsigned char) ((in[3] + in[7]) >> 1);
1346                                         out += 4;
1347                                         in += 8;
1348                                 }
1349                         }
1350                 }
1351         }
1352         else
1353         {
1354                 if (*height > destheight)
1355                 {
1356                         // reduce height
1357                         *height >>= 1;
1358                         for (y = 0;y < *height;y++, inrow += nextrow * 2)
1359                         {
1360                                 for (in = inrow, x = 0;x < *width;x++)
1361                                 {
1362                                         out[0] = (unsigned char) ((in[0] + in[nextrow  ]) >> 1);
1363                                         out[1] = (unsigned char) ((in[1] + in[nextrow+1]) >> 1);
1364                                         out[2] = (unsigned char) ((in[2] + in[nextrow+2]) >> 1);
1365                                         out[3] = (unsigned char) ((in[3] + in[nextrow+3]) >> 1);
1366                                         out += 4;
1367                                         in += 4;
1368                                 }
1369                         }
1370                 }
1371                 else
1372                         Con_Printf ("Image_MipReduce: desired size already achieved\n");
1373         }
1374 }
1375
1376 void Image_HeightmapToNormalmap_BGRA(const unsigned char *inpixels, unsigned char *outpixels, int width, int height, int clamp, float bumpscale)
1377 {
1378         int x, y, x1, x2, y1, y2;
1379         const unsigned char *b, *row[3];
1380         int p[5];
1381         unsigned char *out;
1382         float iwidth, iheight, ibumpscale, n[3];
1383         iwidth = 1.0f / width;
1384         iheight = 1.0f / height;
1385         ibumpscale = (255.0f * 6.0f) / bumpscale;
1386         out = outpixels;
1387         for (y = 0, y1 = height-1;y < height;y1 = y, y++)
1388         {
1389                 y2 = y + 1;if (y2 >= height) y2 = 0;
1390                 row[0] = inpixels + (y1 * width) * 4;
1391                 row[1] = inpixels + (y  * width) * 4;
1392                 row[2] = inpixels + (y2 * width) * 4;
1393                 for (x = 0, x1 = width-1;x < width;x1 = x, x++)
1394                 {
1395                         x2 = x + 1;if (x2 >= width) x2 = 0;
1396                         // left, right
1397                         b = row[1] + x1 * 4;p[0] = (b[0] + b[1] + b[2]);
1398                         b = row[1] + x2 * 4;p[1] = (b[0] + b[1] + b[2]);
1399                         // above, below
1400                         b = row[0] + x  * 4;p[2] = (b[0] + b[1] + b[2]);
1401                         b = row[2] + x  * 4;p[3] = (b[0] + b[1] + b[2]);
1402                         // center
1403                         b = row[1] + x  * 4;p[4] = (b[0] + b[1] + b[2]);
1404                         // calculate a normal from the slopes
1405                         n[0] = p[0] - p[1];
1406                         n[1] = p[3] - p[2];
1407                         n[2] = ibumpscale;
1408                         VectorNormalize(n);
1409                         // turn it into a dot3 rgb vector texture
1410                         out[2] = (int)(128.0f + n[0] * 127.0f);
1411                         out[1] = (int)(128.0f + n[1] * 127.0f);
1412                         out[0] = (int)(128.0f + n[2] * 127.0f);
1413                         out[3] = (p[4]) / 3;
1414                         out += 4;
1415                 }
1416         }
1417 }