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