rewrote memory system entirely (hunk, cache, and zone are gone, memory pools replaced...
[xonotic/darkplaces.git] / gl_textures.c
1 #include "quakedef.h"
2
3 cvar_t  r_max_size = {0, "r_max_size", "2048"};
4 cvar_t  r_picmip = {0, "r_picmip", "0"};
5 cvar_t  r_lerpimages = {CVAR_SAVE, "r_lerpimages", "1"};
6 cvar_t  r_precachetextures = {CVAR_SAVE, "r_precachetextures", "1"};
7
8 int             gl_filter_min = GL_LINEAR_MIPMAP_LINEAR; //NEAREST;
9 int             gl_filter_mag = GL_LINEAR;
10
11
12 static mempool_t *texturemempool;
13
14 // note: this must not conflict with TEXF_ flags in r_textures.h
15 // cleared when a texture is uploaded
16 #define GLTEXF_UPLOAD 0x00010000
17 // texture generated by code, also causes permanent GLTEXF_UPLOAD effect
18 #define GLTEXF_PROCEDURAL 0x00020000
19 // bitmask for mismatch checking
20 #define GLTEXF_IMPORTANTBITS (GLTEXF_PROCEDURAL)
21 // set when image is uploaded and freed
22 #define GLTEXF_DESTROYED 0x00040000
23
24 // size of images which hold fragment textures, ignores picmip and max_size
25 #define BLOCK_SIZE 256
26
27 // really this number only governs gltexnuminuse
28 #define MAX_GLTEXTURES 65536
29
30 // since there is only one set of GL texture numbers, we have to track them
31 // globally, everything else is per texture pool
32 static byte *gltexnuminuse;
33
34 typedef struct
35 {
36         int textype;
37         int inputbytesperpixel;
38         int internalbytesperpixel;
39         int glformat;
40         int glinternalformat;
41         int align;
42 }
43 textypeinfo_t;
44
45 static textypeinfo_t textype_qpalette       = {TEXTYPE_QPALETTE, 1, 4, GL_RGBA, 3, 1};
46 static textypeinfo_t textype_rgb            = {TEXTYPE_RGB     , 3, 3, GL_RGB , 3, 3};
47 static textypeinfo_t textype_rgba           = {TEXTYPE_RGBA    , 4, 4, GL_RGBA, 3, 1};
48 static textypeinfo_t textype_qpalette_alpha = {TEXTYPE_QPALETTE, 1, 4, GL_RGBA, 4, 1};
49 static textypeinfo_t textype_rgba_alpha     = {TEXTYPE_RGBA    , 4, 4, GL_RGBA, 4, 1};
50
51 // a tiling texture (most common type)
52 #define GLIMAGETYPE_TILE 0
53 // a fragments texture (contains one or more fragment textures)
54 #define GLIMAGETYPE_FRAGMENTS 1
55
56 // a gltextureimage can have one (or more if fragments) gltextures inside
57 typedef struct gltextureimage_s
58 {
59         struct gltextureimage_s *imagechain;
60         int texturecount;
61         int type; // one of the GLIMAGETYPE_ values
62         int texnum; // GL texture slot number
63         int width, height;
64         int bytesperpixel; // bytes per pixel
65         int glformat; // GL_RGB or GL_RGBA
66         int glinternalformat; // 3 or 4
67         int flags;
68         short *blockallocation; // fragment allocation
69 }
70 gltextureimage_t;
71
72 typedef struct gltexture_s
73 {
74         // pointer to texturepool (check this to see if the texture is allocated)
75         struct gltexturepool_s *pool;
76         // pointer to next texture in texturepool chain
77         struct gltexture_s *chain;
78         // pointer into gltextureimage array
79         gltextureimage_t *image;
80         // name of the texture (this might be removed someday), no duplicates
81         char *identifier;
82         // location in the image, and size
83         int x, y, width, height;
84         // copy of the original texture supplied to the upload function, for re-uploading or deferred uploads (non-precached)
85         byte *inputtexels;
86         // to identify cache mismatchs (this might be removed someday)
87         int crc;
88         // flags supplied to the LoadTexture/ProceduralTexture functions
89         // (might be altered to remove TEXF_ALPHA), and GLTEXF_ private flags
90         int flags;
91         // procedural texture generation function, called once per frame if the texture is used
92         int (*generate)(byte *buffer, int width, int height, void *parameterdata, int parameterdatasize);
93         // data provided to generate, persistent from call to call
94         byte *proceduraldata;
95         // size of data
96         int proceduraldatasize;
97         // used only to avoid updating the texture more than once per frame
98         int proceduralframecount;
99         // pointer to one of the textype_ structs
100         textypeinfo_t *textype;
101 }
102 gltexture_t;
103
104 #define TEXTUREPOOL_SENTINEL 0xC0DEDBAD
105
106 typedef struct gltexturepool_s
107 {
108         int sentinel;
109         struct gltextureimage_s *imagechain;
110         struct gltexture_s *gltchain;
111         struct gltexturepool_s *next;
112 }
113 gltexturepool_t;
114
115 static gltexturepool_t *gltexturepoolchain = NULL;
116
117 static byte *resamplerow1 = NULL, *resamplerow2 = NULL;
118 static int resamplerowsize = 0;
119 static byte *resizebuffer = NULL, *colorconvertbuffer;
120 static int resizebuffersize = 0;
121 static byte *texturebuffer;
122 static int texturebuffersize = 0;
123
124 static int realmaxsize = 0;
125
126 static textypeinfo_t *R_GetTexTypeInfo(int textype, int flags)
127 {
128         if (flags & TEXF_ALPHA)
129         {
130                 switch(textype)
131                 {
132                 case TEXTYPE_QPALETTE:
133                         return &textype_qpalette_alpha;
134                 case TEXTYPE_RGB:
135                         Host_Error("R_GetTexTypeInfo: RGB format has no alpha, TEXF_ALPHA not allowed\n");
136                         return NULL;
137                 case TEXTYPE_RGBA:
138                         return &textype_rgba_alpha;
139                 default:
140                         Host_Error("R_GetTexTypeInfo: unknown texture format\n");
141                         return NULL;
142                 }
143         }
144         else
145         {
146                 switch(textype)
147                 {
148                 case TEXTYPE_QPALETTE:
149                         return &textype_qpalette;
150                 case TEXTYPE_RGB:
151                         return &textype_rgb;
152                 case TEXTYPE_RGBA:
153                         return &textype_rgba;
154                 default:
155                         Host_Error("R_GetTexTypeInfo: unknown texture format\n");
156                         return NULL;
157                 }
158         }
159 }
160
161 static void R_UploadTexture(gltexture_t *t);
162
163 static void R_PrecacheTexture(gltexture_t *glt)
164 {
165         int precache;
166         precache = false;
167         if (glt->flags & TEXF_ALWAYSPRECACHE)
168                 precache = true;
169         else if (r_precachetextures.integer >= 2)
170                 precache = true;
171         else if (r_precachetextures.integer >= 1)
172                 if (glt->flags & TEXF_PRECACHE)
173                         precache = true;
174
175         if (precache)
176                 R_UploadTexture(glt);
177 }
178
179 int R_GetTexture(rtexture_t *rt)
180 {
181         gltexture_t *glt;
182         if (!rt)
183                 return 0;
184         glt = (gltexture_t *)rt;
185         if (glt->flags & (GLTEXF_UPLOAD | GLTEXF_PROCEDURAL))
186         {
187                 if (glt->flags & GLTEXF_PROCEDURAL)
188                 {
189                         if (glt->proceduralframecount != r_framecount)
190                         {
191                                 glt->proceduralframecount = r_framecount;
192                                 R_UploadTexture(glt);
193                         }
194                 }
195                 else
196                         R_UploadTexture(glt);
197         }
198         return glt->image->texnum;
199 }
200
201 static void R_FreeTexture(gltexture_t *glt)
202 {
203         gltexture_t **gltpointer;
204         gltextureimage_t *image, **gltimagepointer;
205         GLuint texnum;
206
207         for (gltpointer = &glt->pool->gltchain;*gltpointer && *gltpointer != glt;gltpointer = &(*gltpointer)->chain);
208         if (*gltpointer == glt)
209                 *gltpointer = glt->chain;
210         else
211                 Host_Error("R_FreeTexture: texture not linked in pool\n");
212
213         // note: if freeing a fragment texture, this will not make the claimed
214         // space available for new textures unless all other fragments in the
215         // image are also freed
216         image = glt->image;
217         image->texturecount--;
218         if (image->texturecount < 1)
219         {
220                 for (gltimagepointer = &glt->pool->imagechain;*gltimagepointer && *gltimagepointer != image;gltimagepointer = &(*gltimagepointer)->imagechain);
221                 if (*gltimagepointer == image)
222                         *gltimagepointer = image->imagechain;
223                 else
224                         Host_Error("R_FreeTexture: image not linked in pool\n");
225                 if (image->texnum)
226                 {
227                         texnum = image->texnum;
228                         gltexnuminuse[image->texnum] = 0;
229                         glDeleteTextures(1, &texnum);
230                 }
231                 if (image->blockallocation)
232                         Mem_Free(image->blockallocation);
233                 Mem_Free(image);
234         }
235
236         if (glt->identifier)
237                 Mem_Free(glt->identifier);
238         if (glt->inputtexels)
239                 Mem_Free(glt->inputtexels);
240         if (glt->proceduraldata)
241                 Mem_Free(glt->proceduraldata);
242         Mem_Free(glt);
243 }
244
245 static gltexture_t *R_FindTexture (gltexturepool_t *pool, char *identifier)
246 {
247         gltexture_t     *glt;
248
249         if (!identifier)
250                 return NULL;
251
252         for (glt = pool->gltchain;glt;glt = glt->chain)
253                 if (glt->identifier && !strcmp (identifier, glt->identifier))
254                         return glt;
255
256         return NULL;
257 }
258
259 rtexturepool_t *R_AllocTexturePool(void)
260 {
261         gltexturepool_t *pool;
262         pool = Mem_Alloc(texturemempool, sizeof(gltexturepool_t));
263         if (pool == NULL)
264                 return NULL;
265         //memset(pool, 0, sizeof(gltexturepool_t));
266         pool->next = gltexturepoolchain;
267         gltexturepoolchain = pool;
268         pool->sentinel = TEXTUREPOOL_SENTINEL;
269         return (rtexturepool_t *)pool;
270 }
271
272 void R_FreeTexturePool(rtexturepool_t **rtexturepool)
273 {
274         gltexturepool_t *pool, **poolpointer;
275         if (rtexturepool == NULL)
276                 return;
277         if (*rtexturepool == NULL)
278                 return;
279         pool = (gltexturepool_t *)(*rtexturepool);
280         *rtexturepool = NULL;
281         if (pool->sentinel != TEXTUREPOOL_SENTINEL)
282                 Host_Error("R_FreeTexturePool: pool already freed\n");
283         for (poolpointer = &gltexturepoolchain;*poolpointer && *poolpointer != pool;poolpointer = &(*poolpointer)->next);
284         if (*poolpointer == pool)
285                 *poolpointer = pool->next;
286         else
287                 Host_Error("R_FreeTexturePool: pool not linked\n");
288         while (pool->gltchain)
289                 R_FreeTexture(pool->gltchain);
290         Mem_Free(pool);
291 }
292
293
294 typedef struct
295 {
296         char *name;
297         int minification, magnification;
298 }
299 glmode_t;
300
301 static glmode_t modes[] =
302 {
303         {"GL_NEAREST", GL_NEAREST, GL_NEAREST},
304         {"GL_LINEAR", GL_LINEAR, GL_LINEAR},
305         {"GL_NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST},
306         {"GL_LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR},
307         {"GL_NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST},
308         {"GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR}
309 };
310
311 static void GL_TextureMode_f (void)
312 {
313         int i;
314         gltextureimage_t *image;
315         gltexturepool_t *pool;
316
317         if (Cmd_Argc() == 1)
318         {
319                 for (i = 0;i < 6;i++)
320                 {
321                         if (gl_filter_min == modes[i].minification)
322                         {
323                                 Con_Printf ("%s\n", modes[i].name);
324                                 return;
325                         }
326                 }
327                 Con_Printf ("current filter is unknown???\n");
328                 return;
329         }
330
331         for (i = 0;i < 6;i++)
332                 if (!Q_strcasecmp (modes[i].name, Cmd_Argv(1) ) )
333                         break;
334         if (i == 6)
335         {
336                 Con_Printf ("bad filter name\n");
337                 return;
338         }
339
340         gl_filter_min = modes[i].minification;
341         gl_filter_mag = modes[i].magnification;
342
343         // change all the existing mipmap texture objects
344         // FIXME: force renderer(/client/something?) restart instead?
345         for (pool = gltexturepoolchain;pool;pool = pool->next)
346         {
347                 for (image = pool->imagechain;image;image = image->imagechain)
348                 {
349                         // only update already uploaded images
350                         if (!(image->flags & GLTEXF_UPLOAD))
351                         {
352                                 glBindTexture(GL_TEXTURE_2D, image->texnum);
353                                 if (image->flags & TEXF_MIPMAP)
354                                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
355                                 else
356                                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
357                                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
358                         }
359                 }
360         }
361 }
362
363 static int R_CalcTexelDataSize (gltexture_t *glt)
364 {
365         int width2, height2, size;
366         if (glt->flags & TEXF_FRAGMENT)
367                 size = glt->width * glt->height;
368         else
369         {
370                 if (r_max_size.integer > realmaxsize)
371                         Cvar_SetValue("r_max_size", realmaxsize);
372                 // calculate final size
373                 width2 = 1;while (width2 < glt->width) width2 <<= 1;
374                 height2 = 1;while (height2 < glt->height) height2 <<= 1;
375                 width2 >>= (int) r_picmip.integer;
376                 height2 >>= (int) r_picmip.integer;
377                 while (width2 > (int) r_max_size.integer) width2 >>= 1;
378                 while (height2 > (int) r_max_size.integer) height2 >>= 1;
379                 if (width2 < 1) width2 = 1;
380                 if (height2 < 1) height2 = 1;
381
382                 size = 0;
383                 if (glt->flags & TEXF_MIPMAP)
384                 {
385                         while (width2 > 1 || height2 > 1)
386                         {
387                                 size += width2 * height2;
388                                 if (width2 > 1)
389                                         width2 >>= 1;
390                                 if (height2 > 1)
391                                         height2 >>= 1;
392                         }
393                         size++; // count the last 1x1 mipmap
394                 }
395                 else
396                         size = width2*height2;
397         }
398         size *= glt->textype->internalbytesperpixel;
399
400         return size;
401 }
402
403 void R_TextureStats_PrintTotal(void)
404 {
405         int glsize, inputsize, total = 0, totalt = 0, totalp = 0, loaded = 0, loadedt = 0, loadedp = 0;
406         gltexture_t *glt;
407         gltexturepool_t *pool;
408         for (pool = gltexturepoolchain;pool;pool = pool->next)
409         {
410                 for (glt = pool->gltchain;glt;glt = glt->chain)
411                 {
412                         glsize = R_CalcTexelDataSize(glt);
413                         inputsize = glt->width * glt->height * glt->textype->inputbytesperpixel;
414
415                         total++;
416                         totalt += glsize;
417                         totalp += inputsize;
418                         if (!(glt->flags & GLTEXF_UPLOAD))
419                         {
420                                 loaded++;
421                                 loadedt += glsize;
422                                 loadedp += inputsize;
423                         }
424                 }
425         }
426         Con_Printf("total: %i (%.3fMB, %.3fMB original), uploaded %i (%.3fMB, %.3fMB original), upload on demand %i (%.3fMB, %.3fMB original)\n", total, totalt / 1048576.0, totalp / 1048576.0, loaded, loadedt / 1048576.0, loadedp / 1048576.0, total - loaded, (totalt - loadedt) / 1048576.0, (totalp - loadedp) / 1048576.0);
427 }
428
429 static void R_TextureStats_f(void)
430 {
431         int loaded;
432         gltexture_t *glt;
433         gltexturepool_t *pool;
434         Con_Printf("glsize input crc  loaded mip alpha name\n");
435         for (pool = gltexturepoolchain;pool;pool = pool->next)
436         {
437                 for (glt = pool->gltchain;glt;glt = glt->chain)
438                 {
439                         loaded = !(glt->flags & GLTEXF_UPLOAD);
440                         if (glt->flags & GLTEXF_PROCEDURAL)
441                                 Con_Printf("%c%4i%c %4i  PROC %s %s %s %s\n"  , loaded ? '[' : ' ', (R_CalcTexelDataSize(glt) + 1023) / 1024, loaded ? ']' : ' ',                               (glt->width * glt->height * glt->textype->inputbytesperpixel + 1023) / 1024,                                         loaded ? "loaded" : "      ", (glt->flags & TEXF_MIPMAP) ? "mip" : "   ", (glt->flags & TEXF_ALPHA) ? "alpha" : "     ", glt->identifier ? glt->identifier : "<unnamed>");
442                         else
443                                 Con_Printf("%c%4i%c%c%4i%c %04X %s %s %s %s\n", loaded ? '[' : ' ', (R_CalcTexelDataSize(glt) + 1023) / 1024, loaded ? ']' : ' ', glt->inputtexels ? '[' : ' ', (glt->width * glt->height * glt->textype->inputbytesperpixel + 1023) / 1024, glt->inputtexels ? ']' : ' ', glt->crc, loaded ? "loaded" : "      ", (glt->flags & TEXF_MIPMAP) ? "mip" : "   ", (glt->flags & TEXF_ALPHA) ? "alpha" : "     ", glt->identifier ? glt->identifier : "<unnamed>");
444                 }
445                 Con_Printf("pool %10p\n", pool);
446         }
447         R_TextureStats_PrintTotal();
448 }
449
450 char engineversion[40];
451
452 static void r_textures_start(void)
453 {
454         // deal with size limits of various drivers (3dfx in particular)
455         glGetIntegerv(GL_MAX_TEXTURE_SIZE, &realmaxsize);
456         CHECKGLERROR
457
458         texturemempool = Mem_AllocPool("Textures");
459         gltexnuminuse = Mem_Alloc(texturemempool, MAX_GLTEXTURES);
460         //memset(gltexnuminuse, 0, MAX_GLTEXTURES);
461 }
462
463 static void r_textures_shutdown(void)
464 {
465         rtexturepool_t *temp;
466         while(gltexturepoolchain)
467         {
468                 temp = (rtexturepool_t *) gltexturepoolchain;
469                 R_FreeTexturePool(&temp);
470         }
471
472         /*
473         if (resizebuffer) Mem_Free(resizebuffer);resizebuffer = NULL;
474         if (colorconvertbuffer) Mem_Free(colorconvertbuffer);colorconvertbuffer = NULL;
475         if (resamplerow1) Mem_Free(resamplerow1);resamplerow1 = NULL;
476         if (resamplerow2) Mem_Free(resamplerow2);resamplerow2 = NULL;
477         if (texturebuffer) Mem_Free(texturebuffer);texturebuffer = NULL;
478         if (gltexnuminuse) Mem_Free(gltexnuminuse);gltexnuminuse = NULL;
479         */
480         resizebuffersize = 0;
481         resamplerowsize = 0;
482         texturebuffersize = 0;
483         resizebuffer = NULL;
484         colorconvertbuffer = NULL;
485         resamplerow1 = NULL;
486         resamplerow2 = NULL;
487         texturebuffer = NULL;
488         gltexnuminuse = NULL;
489         Mem_FreePool(&texturemempool);
490 }
491
492 static void r_textures_newmap(void)
493 {
494 }
495
496 void R_Textures_Init (void)
497 {
498         Cmd_AddCommand ("gl_texturemode", &GL_TextureMode_f);
499         Cmd_AddCommand("r_texturestats", R_TextureStats_f);
500         Cvar_RegisterVariable (&r_max_size);
501         Cvar_RegisterVariable (&r_picmip);
502         Cvar_RegisterVariable (&r_lerpimages);
503         Cvar_RegisterVariable (&r_precachetextures);
504         gltexnuminuse = NULL;
505
506         R_RegisterModule("R_Textures", r_textures_start, r_textures_shutdown, r_textures_newmap);
507 }
508
509 static void R_ResampleTextureLerpLine (byte *in, byte *out, int inwidth, int outwidth, int bytesperpixel)
510 {
511         int             j, xi, oldx = 0, f, fstep, endx, lerp;
512         fstep = (int) (inwidth*65536.0f/outwidth);
513         endx = (inwidth-1);
514         if (bytesperpixel == 4)
515         {
516                 for (j = 0,f = 0;j < outwidth;j++, f += fstep)
517                 {
518                         xi = f >> 16;
519                         if (xi != oldx)
520                         {
521                                 in += (xi - oldx) * 4;
522                                 oldx = xi;
523                         }
524                         if (xi < endx)
525                         {
526                                 lerp = f & 0xFFFF;
527                                 *out++ = (byte) ((((in[4] - in[0]) * lerp) >> 16) + in[0]);
528                                 *out++ = (byte) ((((in[5] - in[1]) * lerp) >> 16) + in[1]);
529                                 *out++ = (byte) ((((in[6] - in[2]) * lerp) >> 16) + in[2]);
530                                 *out++ = (byte) ((((in[7] - in[3]) * lerp) >> 16) + in[3]);
531                         }
532                         else // last pixel of the line has no pixel to lerp to
533                         {
534                                 *out++ = in[0];
535                                 *out++ = in[1];
536                                 *out++ = in[2];
537                                 *out++ = in[3];
538                         }
539                 }
540         }
541         else if (bytesperpixel == 3)
542         {
543                 for (j = 0,f = 0;j < outwidth;j++, f += fstep)
544                 {
545                         xi = f >> 16;
546                         if (xi != oldx)
547                         {
548                                 in += (xi - oldx) * 3;
549                                 oldx = xi;
550                         }
551                         if (xi < endx)
552                         {
553                                 lerp = f & 0xFFFF;
554                                 *out++ = (byte) ((((in[3] - in[0]) * lerp) >> 16) + in[0]);
555                                 *out++ = (byte) ((((in[4] - in[1]) * lerp) >> 16) + in[1]);
556                                 *out++ = (byte) ((((in[5] - in[2]) * lerp) >> 16) + in[2]);
557                         }
558                         else // last pixel of the line has no pixel to lerp to
559                         {
560                                 *out++ = in[0];
561                                 *out++ = in[1];
562                                 *out++ = in[2];
563                         }
564                 }
565         }
566         else
567                 Sys_Error("R_ResampleTextureLerpLine: unsupported bytesperpixel %i\n", bytesperpixel);
568 }
569
570 /*
571 ================
572 R_ResampleTexture
573 ================
574 */
575 static void R_ResampleTexture (void *indata, int inwidth, int inheight, void *outdata,  int outwidth, int outheight, int bytesperpixel)
576 {
577         if (resamplerowsize < outwidth*4)
578         {
579                 if (resamplerow1)
580                         Mem_Free(resamplerow1);
581                 if (resamplerow2)
582                         Mem_Free(resamplerow2);
583                 resamplerowsize = outwidth*4;
584                 resamplerow1 = Mem_Alloc(texturemempool, resamplerowsize);
585                 resamplerow2 = Mem_Alloc(texturemempool, resamplerowsize);
586         }
587 #define row1 resamplerow1
588 #define row2 resamplerow2
589         if (bytesperpixel == 4)
590         {
591                 if (r_lerpimages.integer)
592                 {
593                         int             i, j, yi, oldy, f, fstep, lerp, endy = (inheight-1), inwidth4 = inwidth*4, outwidth4 = outwidth*4;
594                         byte    *inrow, *out;
595                         out = outdata;
596                         fstep = (int) (inheight*65536.0f/outheight);
597
598                         inrow = indata;
599                         oldy = 0;
600                         R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel);
601                         R_ResampleTextureLerpLine (inrow + inwidth4, row2, inwidth, outwidth, bytesperpixel);
602                         for (i = 0, f = 0;i < outheight;i++,f += fstep)
603                         {
604                                 yi = f >> 16;
605                                 if (yi < endy)
606                                 {
607                                         lerp = f & 0xFFFF;
608                                         if (yi != oldy)
609                                         {
610                                                 inrow = (byte *)indata + inwidth4*yi;
611                                                 if (yi == oldy+1)
612                                                         memcpy(row1, row2, outwidth4);
613                                                 else
614                                                         R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel);
615                                                 R_ResampleTextureLerpLine (inrow + inwidth4, row2, inwidth, outwidth, bytesperpixel);
616                                                 oldy = yi;
617                                         }
618                                         j = outwidth - 4;
619                                         while(j >= 0)
620                                         {
621 #define LERPBYTE(i) out[i] = (byte) ((((row2[i] - row1[i]) * lerp) >> 16) + row1[i])
622                                                 LERPBYTE( 0);
623                                                 LERPBYTE( 1);
624                                                 LERPBYTE( 2);
625                                                 LERPBYTE( 3);
626                                                 LERPBYTE( 4);
627                                                 LERPBYTE( 5);
628                                                 LERPBYTE( 6);
629                                                 LERPBYTE( 7);
630                                                 LERPBYTE( 8);
631                                                 LERPBYTE( 9);
632                                                 LERPBYTE(10);
633                                                 LERPBYTE(11);
634                                                 LERPBYTE(12);
635                                                 LERPBYTE(13);
636                                                 LERPBYTE(14);
637                                                 LERPBYTE(15);
638                                                 out += 16;
639                                                 row1 += 16;
640                                                 row2 += 16;
641                                                 j -= 4;
642                                         }
643                                         if (j & 2)
644                                         {
645                                                 LERPBYTE( 0);
646                                                 LERPBYTE( 1);
647                                                 LERPBYTE( 2);
648                                                 LERPBYTE( 3);
649                                                 LERPBYTE( 4);
650                                                 LERPBYTE( 5);
651                                                 LERPBYTE( 6);
652                                                 LERPBYTE( 7);
653                                                 out += 8;
654                                                 row1 += 8;
655                                                 row2 += 8;
656                                         }
657                                         if (j & 1)
658                                         {
659                                                 LERPBYTE( 0);
660                                                 LERPBYTE( 1);
661                                                 LERPBYTE( 2);
662                                                 LERPBYTE( 3);
663                                                 out += 4;
664                                                 row1 += 4;
665                                                 row2 += 4;
666                                         }
667                                         row1 -= outwidth4;
668                                         row2 -= outwidth4;
669                                 }
670                                 else
671                                 {
672                                         if (yi != oldy)
673                                         {
674                                                 inrow = (byte *)indata + inwidth4*yi;
675                                                 if (yi == oldy+1)
676                                                         memcpy(row1, row2, outwidth4);
677                                                 else
678                                                         R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel);
679                                                 oldy = yi;
680                                         }
681                                         memcpy(out, row1, outwidth4);
682                                 }
683                         }
684                 }
685                 else
686                 {
687                         int i, j;
688                         unsigned frac, fracstep;
689                         // relies on int being 4 bytes
690                         int *inrow, *out;
691                         out = outdata;
692
693                         fracstep = inwidth*0x10000/outwidth;
694                         for (i = 0;i < outheight;i++)
695                         {
696                                 inrow = (int *)indata + inwidth*(i*inheight/outheight);
697                                 frac = fracstep >> 1;
698                                 j = outwidth - 4;
699                                 while (j >= 0)
700                                 {
701                                         out[0] = inrow[frac >> 16];frac += fracstep;
702                                         out[1] = inrow[frac >> 16];frac += fracstep;
703                                         out[2] = inrow[frac >> 16];frac += fracstep;
704                                         out[3] = inrow[frac >> 16];frac += fracstep;
705                                         out += 4;
706                                         j -= 4;
707                                 }
708                                 if (j & 2)
709                                 {
710                                         out[0] = inrow[frac >> 16];frac += fracstep;
711                                         out[1] = inrow[frac >> 16];frac += fracstep;
712                                         out += 2;
713                                 }
714                                 if (j & 1)
715                                 {
716                                         out[0] = inrow[frac >> 16];frac += fracstep;
717                                         out += 1;
718                                 }
719                         }
720                 }
721         }
722         else if (bytesperpixel == 3)
723         {
724                 if (r_lerpimages.integer)
725                 {
726                         int             i, j, yi, oldy, f, fstep, lerp, endy = (inheight-1), inwidth3 = inwidth * 3, outwidth3 = outwidth * 3;
727                         byte    *inrow, *out;
728                         out = outdata;
729                         fstep = (int) (inheight*65536.0f/outheight);
730
731                         inrow = indata;
732                         oldy = 0;
733                         R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel);
734                         R_ResampleTextureLerpLine (inrow + inwidth3, row2, inwidth, outwidth, bytesperpixel);
735                         for (i = 0, f = 0;i < outheight;i++,f += fstep)
736                         {
737                                 yi = f >> 16;
738                                 if (yi < endy)
739                                 {
740                                         lerp = f & 0xFFFF;
741                                         if (yi != oldy)
742                                         {
743                                                 inrow = (byte *)indata + inwidth3*yi;
744                                                 if (yi == oldy+1)
745                                                         memcpy(row1, row2, outwidth3);
746                                                 else
747                                                         R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel);
748                                                 R_ResampleTextureLerpLine (inrow + inwidth3, row2, inwidth, outwidth, bytesperpixel);
749                                                 oldy = yi;
750                                         }
751                                         j = outwidth - 4;
752                                         while(j >= 0)
753                                         {
754 #define LERPBYTE(i) out[i] = (byte) ((((row2[i] - row1[i]) * lerp) >> 16) + row1[i])
755                                                 LERPBYTE( 0);
756                                                 LERPBYTE( 1);
757                                                 LERPBYTE( 2);
758                                                 LERPBYTE( 3);
759                                                 LERPBYTE( 4);
760                                                 LERPBYTE( 5);
761                                                 LERPBYTE( 6);
762                                                 LERPBYTE( 7);
763                                                 LERPBYTE( 8);
764                                                 LERPBYTE( 9);
765                                                 LERPBYTE(10);
766                                                 LERPBYTE(11);
767                                                 out += 12;
768                                                 row1 += 12;
769                                                 row2 += 12;
770                                                 j -= 4;
771                                         }
772                                         if (j & 2)
773                                         {
774                                                 LERPBYTE( 0);
775                                                 LERPBYTE( 1);
776                                                 LERPBYTE( 2);
777                                                 LERPBYTE( 3);
778                                                 LERPBYTE( 4);
779                                                 LERPBYTE( 5);
780                                                 out += 6;
781                                                 row1 += 6;
782                                                 row2 += 6;
783                                         }
784                                         if (j & 1)
785                                         {
786                                                 LERPBYTE( 0);
787                                                 LERPBYTE( 1);
788                                                 LERPBYTE( 2);
789                                                 out += 3;
790                                                 row1 += 3;
791                                                 row2 += 3;
792                                         }
793                                         row1 -= outwidth3;
794                                         row2 -= outwidth3;
795                                 }
796                                 else
797                                 {
798                                         if (yi != oldy)
799                                         {
800                                                 inrow = (byte *)indata + inwidth3*yi;
801                                                 if (yi == oldy+1)
802                                                         memcpy(row1, row2, outwidth3);
803                                                 else
804                                                         R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel);
805                                                 oldy = yi;
806                                         }
807                                         memcpy(out, row1, outwidth3);
808                                 }
809                         }
810                 }
811                 else
812                 {
813                         int i, j, f, inwidth3 = inwidth * 3;
814                         unsigned frac, fracstep;
815                         byte *inrow, *out;
816                         out = outdata;
817
818                         fracstep = inwidth*0x10000/outwidth;
819                         for (i = 0;i < outheight;i++)
820                         {
821                                 inrow = indata + inwidth3*(i*inheight/outheight);
822                                 frac = fracstep >> 1;
823                                 j = outwidth - 4;
824                                 while (j >= 0)
825                                 {
826                                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
827                                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
828                                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
829                                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
830                                         j -= 4;
831                                 }
832                                 if (j & 2)
833                                 {
834                                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
835                                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
836                                         out += 2;
837                                 }
838                                 if (j & 1)
839                                 {
840                                         f = (frac >> 16)*3;*out++ = inrow[f+0];*out++ = inrow[f+1];*out++ = inrow[f+2];frac += fracstep;
841                                         out += 1;
842                                 }
843                         }
844                 }
845         }
846         else
847                 Sys_Error("R_ResampleTexture: unsupported bytesperpixel %i\n", bytesperpixel);
848 #undef row1
849 #undef row2
850 }
851
852 // in can be the same as out
853 static void R_MipReduce(byte *in, byte *out, int *width, int *height, int destwidth, int destheight, int bytesperpixel)
854 {
855         int x, y, nextrow;
856         nextrow = *width * bytesperpixel;
857         if (*width > destwidth)
858         {
859                 *width >>= 1;
860                 if (*height > destheight)
861                 {
862                         // reduce both
863                         *height >>= 1;
864                         if (bytesperpixel == 4)
865                         {
866                                 for (y = 0;y < *height;y++)
867                                 {
868                                         for (x = 0;x < *width;x++)
869                                         {
870                                                 out[0] = (byte) ((in[0] + in[4] + in[nextrow  ] + in[nextrow+4]) >> 2);
871                                                 out[1] = (byte) ((in[1] + in[5] + in[nextrow+1] + in[nextrow+5]) >> 2);
872                                                 out[2] = (byte) ((in[2] + in[6] + in[nextrow+2] + in[nextrow+6]) >> 2);
873                                                 out[3] = (byte) ((in[3] + in[7] + in[nextrow+3] + in[nextrow+7]) >> 2);
874                                                 out += 4;
875                                                 in += 8;
876                                         }
877                                         in += nextrow; // skip a line
878                                 }
879                         }
880                         else if (bytesperpixel == 3)
881                         {
882                                 for (y = 0;y < *height;y++)
883                                 {
884                                         for (x = 0;x < *width;x++)
885                                         {
886                                                 out[0] = (byte) ((in[0] + in[3] + in[nextrow  ] + in[nextrow+3]) >> 2);
887                                                 out[1] = (byte) ((in[1] + in[4] + in[nextrow+1] + in[nextrow+4]) >> 2);
888                                                 out[2] = (byte) ((in[2] + in[5] + in[nextrow+2] + in[nextrow+5]) >> 2);
889                                                 out += 3;
890                                                 in += 6;
891                                         }
892                                         in += nextrow; // skip a line
893                                 }
894                         }
895                         else
896                                 Sys_Error("R_MipReduce: unsupported bytesperpixel %i\n", bytesperpixel);
897                 }
898                 else
899                 {
900                         // reduce width
901                         if (bytesperpixel == 4)
902                         {
903                                 for (y = 0;y < *height;y++)
904                                 {
905                                         for (x = 0;x < *width;x++)
906                                         {
907                                                 out[0] = (byte) ((in[0] + in[4]) >> 1);
908                                                 out[1] = (byte) ((in[1] + in[5]) >> 1);
909                                                 out[2] = (byte) ((in[2] + in[6]) >> 1);
910                                                 out[3] = (byte) ((in[3] + in[7]) >> 1);
911                                                 out += 4;
912                                                 in += 8;
913                                         }
914                                 }
915                         }
916                         else if (bytesperpixel == 3)
917                         {
918                                 for (y = 0;y < *height;y++)
919                                 {
920                                         for (x = 0;x < *width;x++)
921                                         {
922                                                 out[0] = (byte) ((in[0] + in[3]) >> 1);
923                                                 out[1] = (byte) ((in[1] + in[4]) >> 1);
924                                                 out[2] = (byte) ((in[2] + in[5]) >> 1);
925                                                 out += 3;
926                                                 in += 6;
927                                         }
928                                 }
929                         }
930                         else
931                                 Sys_Error("R_MipReduce: unsupported bytesperpixel %i\n", bytesperpixel);
932                 }
933         }
934         else
935         {
936                 if (*height > destheight)
937                 {
938                         // reduce height
939                         *height >>= 1;
940                         if (bytesperpixel == 4)
941                         {
942                                 for (y = 0;y < *height;y++)
943                                 {
944                                         for (x = 0;x < *width;x++)
945                                         {
946                                                 out[0] = (byte) ((in[0] + in[nextrow  ]) >> 1);
947                                                 out[1] = (byte) ((in[1] + in[nextrow+1]) >> 1);
948                                                 out[2] = (byte) ((in[2] + in[nextrow+2]) >> 1);
949                                                 out[3] = (byte) ((in[3] + in[nextrow+3]) >> 1);
950                                                 out += 4;
951                                                 in += 4;
952                                         }
953                                         in += nextrow; // skip a line
954                                 }
955                         }
956                         else if (bytesperpixel == 3)
957                         {
958                                 for (y = 0;y < *height;y++)
959                                 {
960                                         for (x = 0;x < *width;x++)
961                                         {
962                                                 out[0] = (byte) ((in[0] + in[nextrow  ]) >> 1);
963                                                 out[1] = (byte) ((in[1] + in[nextrow+1]) >> 1);
964                                                 out[2] = (byte) ((in[2] + in[nextrow+2]) >> 1);
965                                                 out += 3;
966                                                 in += 3;
967                                         }
968                                         in += nextrow; // skip a line
969                                 }
970                         }
971                         else
972                                 Sys_Error("R_MipReduce: unsupported bytesperpixel %i\n", bytesperpixel);
973                 }
974                 else
975                         Sys_Error("R_MipReduce: desired size already achieved\n");
976         }
977 }
978
979 static void R_Upload(gltexture_t *glt, byte *data)
980 {
981         int mip, width, height, internalformat;
982         byte *prevbuffer;
983         prevbuffer = data;
984
985         glBindTexture(GL_TEXTURE_2D, glt->image->texnum);
986         CHECKGLERROR
987
988         glt->flags &= ~GLTEXF_UPLOAD;
989
990         if (glt->flags & TEXF_FRAGMENT)
991         {
992                 if (resizebuffersize < glt->image->width * glt->image->height * glt->image->bytesperpixel)
993                 {
994                         resizebuffersize = glt->image->width * glt->image->height * glt->image->bytesperpixel;
995                         if (resizebuffer)
996                                 Mem_Free(resizebuffer);
997                         if (colorconvertbuffer)
998                                 Mem_Free(colorconvertbuffer);
999                         resizebuffer = Mem_Alloc(texturemempool, resizebuffersize);
1000                         colorconvertbuffer = Mem_Alloc(texturemempool, resizebuffersize);
1001                         if (!resizebuffer || !colorconvertbuffer)
1002                                 Host_Error("R_Upload: out of memory\n");
1003                 }
1004
1005                 if (glt->image->flags & GLTEXF_UPLOAD)
1006                 {
1007                         glt->image->flags &= ~GLTEXF_UPLOAD;
1008                         memset(resizebuffer, 255, glt->image->width * glt->image->height * glt->image->bytesperpixel);
1009                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
1010                         CHECKGLERROR
1011                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
1012                         CHECKGLERROR
1013                         glTexImage2D (GL_TEXTURE_2D, 0, glt->image->glinternalformat, glt->image->width, glt->image->height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, resizebuffer);
1014                         CHECKGLERROR
1015                 }
1016
1017                 if (prevbuffer == NULL)
1018                 {
1019                         memset(resizebuffer, 255, glt->width * glt->height * glt->image->bytesperpixel);
1020                         prevbuffer = resizebuffer;
1021                 }
1022                 else if (glt->textype->textype == TEXTYPE_QPALETTE)
1023                 {
1024                         // promote paletted to RGBA, so we only have to worry about RGB and
1025                         // RGBA in the rest of this code
1026                         Image_Copy8bitRGBA(prevbuffer, colorconvertbuffer, glt->width * glt->height, d_8to24table);
1027                         prevbuffer = colorconvertbuffer;
1028                 }
1029
1030                 glTexSubImage2D(GL_TEXTURE_2D, 0, glt->x, glt->y, glt->width, glt->height, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
1031                 CHECKGLERROR
1032                 return;
1033         }
1034
1035         glt->image->flags &= ~GLTEXF_UPLOAD;
1036
1037         // these are rounded up versions of the size to do better resampling
1038         width = 1;while(width < glt->width) width *= 2;
1039         height = 1;while(height < glt->height) height *= 2;
1040
1041         if (resizebuffersize < width * height * glt->image->bytesperpixel)
1042         {
1043                 resizebuffersize = width * height * glt->image->bytesperpixel;
1044                 if (resizebuffer)
1045                         Mem_Free(resizebuffer);
1046                 if (colorconvertbuffer)
1047                         Mem_Free(colorconvertbuffer);
1048                 resizebuffer = Mem_Alloc(texturemempool, resizebuffersize);
1049                 colorconvertbuffer = Mem_Alloc(texturemempool, resizebuffersize);
1050                 if (!resizebuffer || !colorconvertbuffer)
1051                         Host_Error("R_Upload: out of memory\n");
1052         }
1053
1054         if (prevbuffer == NULL)
1055         {
1056                 width = glt->image->width;
1057                 height = glt->image->height;
1058                 memset(resizebuffer, 255, width * height * glt->image->bytesperpixel);
1059                 prevbuffer = resizebuffer;
1060         }
1061         else
1062         {
1063                 if (glt->textype->textype == TEXTYPE_QPALETTE)
1064                 {
1065                         // promote paletted to RGBA, so we only have to worry about RGB and
1066                         // RGBA in the rest of this code
1067                         Image_Copy8bitRGBA(prevbuffer, colorconvertbuffer, glt->width * glt->height, d_8to24table);
1068                         prevbuffer = colorconvertbuffer;
1069                 }
1070
1071                 if (glt->width != width || glt->height != height)
1072                 {
1073                         R_ResampleTexture(prevbuffer, glt->width, glt->height, resizebuffer, width, height, glt->image->bytesperpixel);
1074                         prevbuffer = resizebuffer;
1075                 }
1076
1077                 // apply picmip/max_size limitations
1078                 while (width > glt->image->width || height > glt->image->height)
1079                 {
1080                         R_MipReduce(prevbuffer, resizebuffer, &width, &height, glt->image->width, glt->image->height, glt->image->bytesperpixel);
1081                         prevbuffer = resizebuffer;
1082                 }
1083         }
1084
1085         // 3 and 4 are converted by the driver to it's preferred format for the current display mode
1086         internalformat = 3;
1087         if (glt->flags & TEXF_ALPHA)
1088                 internalformat = 4;
1089
1090         mip = 0;
1091         glTexImage2D(GL_TEXTURE_2D, mip++, internalformat, width, height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
1092         CHECKGLERROR
1093         if (glt->flags & TEXF_MIPMAP)
1094         {
1095                 while (width > 1 || height > 1)
1096                 {
1097                         R_MipReduce(prevbuffer, resizebuffer, &width, &height, 1, 1, glt->image->bytesperpixel);
1098                         prevbuffer = resizebuffer;
1099
1100                         glTexImage2D(GL_TEXTURE_2D, mip++, internalformat, width, height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
1101                         CHECKGLERROR
1102                 }
1103
1104                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
1105                 CHECKGLERROR
1106                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
1107                 CHECKGLERROR
1108         }
1109         else
1110         {
1111                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
1112                 CHECKGLERROR
1113                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
1114                 CHECKGLERROR
1115         }
1116 }
1117
1118 static void R_FindImageForTexture(gltexture_t *glt)
1119 {
1120         int i, j, best, best2, x, y, w, h;
1121         textypeinfo_t *texinfo;
1122         gltexturepool_t *pool;
1123         gltextureimage_t *image, **imagechainpointer;
1124         texinfo = glt->textype;
1125         pool = glt->pool;
1126
1127         x = 0;
1128         y = 0;
1129         w = glt->width;
1130         h = glt->height;
1131         if (glt->flags & TEXF_FRAGMENT)
1132         {
1133                 for (imagechainpointer = &pool->imagechain;*imagechainpointer;imagechainpointer = &(*imagechainpointer)->imagechain)
1134                 {
1135                         image = *imagechainpointer;
1136                         if (image->type != GLIMAGETYPE_FRAGMENTS)
1137                                 continue;
1138                         if (image->glformat != texinfo->glformat || image->glinternalformat != texinfo->glinternalformat)
1139                                 continue;
1140
1141                         // got a fragments texture, find a place in it if we can
1142                         best = BLOCK_SIZE;
1143                         for (best = BLOCK_SIZE, i = 0;i < BLOCK_SIZE - w;i += texinfo->align)
1144                         {
1145                                 for (best2 = 0, j = 0;j < w;j++)
1146                                 {
1147                                         if (image->blockallocation[i+j] >= best)
1148                                                 break;
1149                                         if (best2 < image->blockallocation[i+j])
1150                                                 best2 = image->blockallocation[i+j];
1151                                 }
1152                                 if (j == w)
1153                                 {
1154                                         // this is a valid spot
1155                                         x = i;
1156                                         y = best = best2;
1157                                 }
1158                         }
1159
1160                         if (best + h > BLOCK_SIZE)
1161                                 continue;
1162
1163                         for (i = 0;i < w;i++)
1164                                 image->blockallocation[x + i] = best + h;
1165
1166                         glt->x = x;
1167                         glt->y = y;
1168                         glt->image = image;
1169                         image->texturecount++;
1170                         return;
1171                 }
1172
1173                 image = Mem_Alloc(texturemempool, sizeof(gltextureimage_t));
1174                 if (image == NULL)
1175                         Sys_Error("R_FindImageForTexture: ran out of memory\n");
1176                 //memset(image, 0, sizeof(*image));
1177                 image->type = GLIMAGETYPE_FRAGMENTS;
1178                 image->width = BLOCK_SIZE;
1179                 image->height = BLOCK_SIZE;
1180                 image->blockallocation = Mem_Alloc(texturemempool, BLOCK_SIZE * sizeof(short));
1181                 memset(image->blockallocation, 0, BLOCK_SIZE * sizeof(short));
1182
1183                 x = 0;
1184                 y = 0;
1185                 for (i = 0;i < w;i++)
1186                         image->blockallocation[x + i] = y + h;
1187         }
1188         else
1189         {
1190                 for (imagechainpointer = &pool->imagechain;*imagechainpointer;imagechainpointer = &(*imagechainpointer)->imagechain);
1191
1192                 image = Mem_Alloc(texturemempool, sizeof(gltextureimage_t));
1193                 if (image == NULL)
1194                         Sys_Error("R_FindImageForTexture: ran out of memory\n");
1195                 //memset(image, 0, sizeof(*image));
1196                 image->type = GLIMAGETYPE_TILE;
1197                 image->blockallocation = NULL;
1198
1199                 // calculate final size
1200                 if (r_max_size.integer > realmaxsize)
1201                         Cvar_SetValue("r_max_size", realmaxsize);
1202                 image->width = 1;while (image->width < glt->width) image->width <<= 1;
1203                 image->height = 1;while (image->height < glt->height) image->height <<= 1;
1204                 image->width >>= r_picmip.integer;while (image->width > r_max_size.integer) image->width >>= 1;
1205                 image->height >>= r_picmip.integer;while (image->height > r_max_size.integer) image->height >>= 1;
1206                 if (image->width < 1) image->width = 1;
1207                 if (image->height < 1) image->height = 1;
1208         }
1209         image->glinternalformat = texinfo->glinternalformat;
1210         image->glformat = texinfo->glformat;
1211         image->flags = (glt->flags & (TEXF_MIPMAP | TEXF_ALPHA)) | GLTEXF_UPLOAD;
1212         image->bytesperpixel = texinfo->internalbytesperpixel;
1213         for (i = 1;i < MAX_GLTEXTURES;i++)
1214                 if (!gltexnuminuse[i])
1215                         break;
1216         if (i < MAX_GLTEXTURES)
1217                 gltexnuminuse[image->texnum = i] = true;
1218         else
1219                 Sys_Error("R_FindImageForTexture: ran out of GL textures\n");
1220         *imagechainpointer = image;
1221         image->texturecount++;
1222
1223         glt->x = x;
1224         glt->y = y;
1225         glt->image = image;
1226 }
1227
1228 // note: R_FindImageForTexture must be called before this
1229 static void R_UploadTexture (gltexture_t *glt)
1230 {
1231         if (!(glt->flags & (GLTEXF_UPLOAD | GLTEXF_PROCEDURAL)))
1232                 return;
1233
1234         if (glt->flags & GLTEXF_PROCEDURAL)
1235         {
1236                 if (glt->generate)
1237                 {
1238                         if (texturebuffersize < glt->width * glt->height * glt->textype->inputbytesperpixel)
1239                         {
1240                                 if (texturebuffer)
1241                                         Mem_Free(texturebuffer);
1242                                 texturebuffersize = glt->width * glt->height * glt->textype->inputbytesperpixel;
1243                                 texturebuffer = Mem_Alloc(texturemempool, texturebuffersize);
1244                         }
1245
1246                         glt->generate(texturebuffer, glt->width, glt->height, (void *)glt->proceduraldata, glt->proceduraldatasize);
1247                 }
1248         }
1249         else
1250         {
1251                 R_Upload(glt, glt->inputtexels);
1252                 if (glt->inputtexels)
1253                 {
1254                         Mem_Free(glt->inputtexels);
1255                         glt->inputtexels = NULL;
1256                         glt->flags |= GLTEXF_DESTROYED;
1257                 }
1258                 else if (glt->flags & GLTEXF_DESTROYED)
1259                         Con_Printf("R_UploadTexture: Texture %s already uploaded and destroyed.  Can not upload original image again.  Uploaded blank texture.\n", glt->identifier);
1260         }
1261 }
1262
1263 static gltexture_t *R_SetupTexture(gltexturepool_t *pool, char *identifier, int crc, int width, int height, int flags, textypeinfo_t *texinfo, byte *data, int (*generate)(byte *buffer, int width, int height, void *proceduraldata, int proceduraldatasize), void *proceduraldata, int proceduraldatasize)
1264 {
1265         gltexture_t *glt;
1266         glt = Mem_Alloc(texturemempool, sizeof(gltexture_t));
1267         //memset(glt, 0, sizeof(gltexture_t));
1268         if (identifier)
1269         {
1270                 glt->identifier = Mem_Alloc(texturemempool, strlen(identifier)+1);
1271                 strcpy (glt->identifier, identifier);
1272         }
1273         else
1274                 glt->identifier = NULL;
1275         glt->pool = pool;
1276         glt->chain = pool->gltchain;
1277         pool->gltchain = glt;
1278         glt->crc = crc;
1279         glt->width = width;
1280         glt->height = height;
1281         glt->flags = flags;
1282         glt->textype = texinfo;
1283
1284         if (data)
1285         {
1286                 glt->inputtexels = Mem_Alloc(texturemempool, glt->width * glt->height * texinfo->inputbytesperpixel);
1287                 if (glt->inputtexels == NULL)
1288                         Sys_Error("R_SetupTexture: out of memory\n");
1289                 memcpy(glt->inputtexels, data, glt->width * glt->height * texinfo->inputbytesperpixel);
1290         }
1291         else
1292                 glt->inputtexels = NULL;
1293
1294         glt->generate = generate;
1295         glt->proceduraldatasize = proceduraldatasize;
1296         if (proceduraldatasize)
1297         {
1298                 glt->proceduraldata = Mem_Alloc(texturemempool, proceduraldatasize);
1299                 if (glt->proceduraldata == NULL)
1300                         Sys_Error("R_SetupTexture: out of memory\n");
1301         }
1302         else
1303                 glt->proceduraldata = NULL;
1304
1305         R_FindImageForTexture(glt);
1306         R_PrecacheTexture(glt);
1307
1308         return glt;
1309 }
1310
1311 /*
1312 ================
1313 R_LoadTexture
1314 ================
1315 */
1316 rtexture_t *R_LoadTexture (rtexturepool_t *rtexturepool, char *identifier, int width, int height, byte *data, int textype, int flags)
1317 {
1318         int i;
1319         gltexture_t *glt;
1320         gltexturepool_t *pool = (gltexturepool_t *)rtexturepool;
1321         textypeinfo_t *texinfo;
1322         unsigned short crc;
1323
1324         if (cls.state == ca_dedicated)
1325                 return NULL;
1326
1327         texinfo = R_GetTexTypeInfo(textype, flags);
1328
1329         // data can be NULL
1330 //      if (data == NULL)
1331 //              Host_Error("R_LoadTexture: \"%s\" has no data\n", identifier);
1332
1333         if (flags & TEXF_FRAGMENT)
1334         {
1335                 if (width > BLOCK_SIZE || height > BLOCK_SIZE)
1336                         Host_Error("R_LoadTexture: fragment too big, must be no more than %dx%d\n", BLOCK_SIZE, BLOCK_SIZE);
1337                 if ((width * texinfo->internalbytesperpixel) & 3)
1338                         Host_Error("R_LoadTexture: incompatible width for fragment");
1339         }
1340
1341         // clear the alpha flag if the texture has no transparent pixels
1342         switch(textype)
1343         {
1344         case TEXTYPE_QPALETTE:
1345                 if (flags & TEXF_ALPHA)
1346                 {
1347                         flags &= ~TEXF_ALPHA;
1348                         for (i = 0;i < width * height;i++)
1349                         {
1350                                 if (data[i] == 255)
1351                                 {
1352                                         flags |= TEXF_ALPHA;
1353                                         break;
1354                                 }
1355                         }
1356                 }
1357                 break;
1358         case TEXTYPE_RGB:
1359                 if (flags & TEXF_ALPHA)
1360                         Host_Error("R_LoadTexture: RGB has no alpha, don't specify TEXF_ALPHA\n");
1361                 break;
1362         case TEXTYPE_RGBA:
1363                 if (flags & TEXF_ALPHA)
1364                 {
1365                         flags &= ~TEXF_ALPHA;
1366                         for (i = 0;i < width * height;i++)
1367                         {
1368                                 if (data[i * 4 + 3] < 255)
1369                                 {
1370                                         flags |= TEXF_ALPHA;
1371                                         break;
1372                                 }
1373                         }
1374                 }
1375                 break;
1376         default:
1377                 Host_Error("R_LoadTexture: unknown texture type\n");
1378         }
1379
1380         // LordHavoc: do a CRC to confirm the data really is the same as previous occurances.
1381         if (data == NULL)
1382                 crc = 0;
1383         else
1384                 crc = CRC_Block(data, width*height*texinfo->inputbytesperpixel);
1385
1386         // see if the texture is already present
1387         if (identifier && (glt = R_FindTexture(pool, identifier)))
1388         {
1389                 if (crc == glt->crc && width == glt->width && height == glt->height && texinfo == glt->textype && ((flags ^ glt->flags) & TEXF_IMPORTANTBITS) == 0 && ((flags ^ glt->flags) & GLTEXF_IMPORTANTBITS) == 0)
1390                         return (rtexture_t *)glt; // exact match, use existing
1391                 Con_Printf("R_LoadTexture: cache mismatch on %s, replacing old texture\n", identifier);
1392                 R_FreeTexture(glt);
1393         }
1394
1395         return (rtexture_t *)R_SetupTexture(pool, identifier, crc, width, height, flags | GLTEXF_UPLOAD, texinfo, data, NULL, NULL, 0);
1396 }
1397
1398 rtexture_t *R_ProceduralTexture (rtexturepool_t *rtexturepool, char *identifier, int width, int height, int textype, int flags, int (*generate)(byte *buffer, int width, int height, void *proceduraldata, int proceduraldatasize), void *proceduraldata, int proceduraldatasize)
1399 {
1400         gltexture_t             *glt;
1401         gltexturepool_t *pool = (gltexturepool_t *)rtexturepool;
1402         textypeinfo_t   *texinfo;
1403
1404         if (cls.state == ca_dedicated)
1405                 return NULL;
1406
1407         texinfo = R_GetTexTypeInfo(textype, flags);
1408
1409         // no function is supported, for odd uses
1410 //      if (generate == NULL)
1411 //              Host_Error("R_ProceduralTexture: \"%s\" has no generate function\n", identifier);
1412         if (flags & TEXF_FRAGMENT)
1413         {
1414                 if (width > BLOCK_SIZE || height > BLOCK_SIZE)
1415                         Host_Error("R_ProceduralTexture: fragment too big, must be no more than %dx%d\n", BLOCK_SIZE, BLOCK_SIZE);
1416                 if ((width * texinfo->internalbytesperpixel) & 3)
1417                         Host_Error("R_ProceduralTexture: incompatible width for fragment");
1418         }
1419
1420         // see if the texture is already present
1421         if (identifier && (glt = R_FindTexture(pool, identifier)))
1422         {
1423                 if (width == glt->width && height == glt->height && texinfo == glt->textype && ((flags ^ glt->flags) & TEXF_IMPORTANTBITS) == 0 && ((flags ^ glt->flags) & GLTEXF_IMPORTANTBITS) == 0)
1424                         return (rtexture_t *)glt; // exact match, use existing
1425                 Con_DPrintf("R_LoadTexture: cache mismatch, replacing old texture\n");
1426                 R_FreeTexture(glt);
1427         }
1428
1429         return (rtexture_t *)R_SetupTexture(pool, identifier, 0, width, height, flags | GLTEXF_PROCEDURAL | GLTEXF_UPLOAD, texinfo, NULL, generate, proceduraldata, proceduraldatasize);
1430 }
1431
1432 int R_TextureHasAlpha(rtexture_t *rt)
1433 {
1434         gltexture_t *glt;
1435         if (!rt)
1436                 return false;
1437         glt = (gltexture_t *)rt;
1438         return (glt->flags & TEXF_ALPHA) != 0;
1439 }
1440
1441 int R_TextureWidth(rtexture_t *rt)
1442 {
1443         if (!rt)
1444                 return false;
1445         return ((gltexture_t *)rt)->width;
1446 }
1447
1448 int R_TextureHeight(rtexture_t *rt)
1449 {
1450         if (!rt)
1451                 return false;
1452         return ((gltexture_t *)rt)->height;
1453 }
1454
1455 void R_GetFragmentLocation(rtexture_t *rt, int *x, int *y, float *fx1, float *fy1, float *fx2, float *fy2)
1456 {
1457         gltexture_t *glt;
1458         float iwidth, iheight;
1459         if (!rt)
1460                 Host_Error("R_GetFragmentLocation: no texture supplied\n");
1461         glt = (gltexture_t *)rt;
1462         if (glt->flags & TEXF_FRAGMENT)
1463         {
1464                 if (x)
1465                         *x = glt->x;
1466                 if (y)
1467                         *y = glt->y;
1468                 if (fx1 || fy1 || fx2 || fy2)
1469                 {
1470                         iwidth = 1.0f / glt->image->width;
1471                         iheight = 1.0f / glt->image->height;
1472                         if (fx1)
1473                                 *fx1 = glt->x * iwidth;
1474                         if (fy1)
1475                                 *fy1 = glt->y * iheight;
1476                         if (fx2)
1477                                 *fx2 = (glt->x + glt->width) * iwidth;
1478                         if (fy2)
1479                                 *fy2 = (glt->y + glt->height) * iheight;
1480                 }
1481         }
1482         else
1483         {
1484                 if (x)
1485                         *x = 0;
1486                 if (y)
1487                         *y = 0;
1488                 if (fx1 || fy1 || fx2 || fy2)
1489                 {
1490                         if (fx1)
1491                                 *fx1 = 0;
1492                         if (fy1)
1493                                 *fy1 = 0;
1494                         if (fx2)
1495                                 *fx2 = 1;
1496                         if (fy2)
1497                                 *fy2 = 1;
1498                 }
1499         }
1500 }
1501
1502 int R_CompatibleFragmentWidth(int width, int textype, int flags)
1503 {
1504         textypeinfo_t *texinfo = R_GetTexTypeInfo(textype, flags);
1505         while ((width * texinfo->internalbytesperpixel) & 3)
1506                 width++;
1507         return width;
1508 }
1509
1510 void R_UpdateTexture(rtexture_t *rt, byte *data)
1511 {
1512         gltexture_t *glt;
1513         if (rt == NULL)
1514                 Host_Error("R_UpdateTexture: no texture supplied\n");
1515         if (data == NULL)
1516                 Host_Error("R_UpdateTexture: no data supplied\n");
1517         glt = (gltexture_t *)rt;
1518         if (!(glt->flags & GLTEXF_PROCEDURAL))
1519         {
1520                 if (glt->inputtexels == NULL)
1521                 {
1522                         glt->inputtexels = Mem_Alloc(texturemempool, glt->width * glt->height * glt->textype->inputbytesperpixel);
1523                         if (glt->inputtexels == NULL)
1524                                 Host_Error("R_UpdateTexture: ran out of memory\n");
1525                 }
1526                 memcpy(glt->inputtexels, data, glt->width * glt->height * glt->textype->inputbytesperpixel);
1527         }
1528         R_Upload(glt, data);
1529 }
1530