free texture processing buffers each frame so they don't hang around wasting memory
[divverent/darkplaces.git] / gl_textures.c
1
2 #include "quakedef.h"
3
4 cvar_t  r_max_size = {CVAR_SAVE, "r_max_size", "2048"};
5 cvar_t  r_max_scrapsize = {CVAR_SAVE, "r_max_scrapsize", "256"};
6 cvar_t  r_picmip = {CVAR_SAVE, "r_picmip", "0"};
7 cvar_t  r_lerpimages = {CVAR_SAVE, "r_lerpimages", "1"};
8 cvar_t  r_precachetextures = {CVAR_SAVE, "r_precachetextures", "1"};
9
10 int             gl_filter_min = GL_LINEAR_MIPMAP_LINEAR;
11 int             gl_filter_mag = GL_LINEAR;
12
13
14 static mempool_t *texturemempool;
15 static mempool_t *texturedatamempool;
16 static mempool_t *textureprocessingmempool;
17
18 // note: this must not conflict with TEXF_ flags in r_textures.h
19 // cleared when a texture is uploaded
20 #define GLTEXF_UPLOAD 0x00010000
21 // bitmask for mismatch checking
22 #define GLTEXF_IMPORTANTBITS (0)
23 // set when image is uploaded and freed
24 #define GLTEXF_DESTROYED 0x00040000
25
26 // size of images which hold fragment textures, ignores picmip and max_size
27 static int block_size;
28
29 // really this number only governs gltexnuminuse
30 #define MAX_GLTEXTURES 65536
31
32 // since there is only one set of GL texture numbers, we have to track them
33 // globally, everything else is per texture pool
34 static qbyte *gltexnuminuse;
35
36 typedef struct
37 {
38         int textype;
39         int inputbytesperpixel;
40         int internalbytesperpixel;
41         int glformat;
42         int glinternalformat;
43         int align;
44 }
45 textypeinfo_t;
46
47 static textypeinfo_t textype_qpalette       = {TEXTYPE_QPALETTE, 1, 4, GL_RGBA, 3, 1};
48 static textypeinfo_t textype_rgb            = {TEXTYPE_RGB     , 3, 3, GL_RGB , 3, 3};
49 static textypeinfo_t textype_rgba           = {TEXTYPE_RGBA    , 4, 4, GL_RGBA, 3, 1};
50 static textypeinfo_t textype_qpalette_alpha = {TEXTYPE_QPALETTE, 1, 4, GL_RGBA, 4, 1};
51 static textypeinfo_t textype_rgba_alpha     = {TEXTYPE_RGBA    , 4, 4, GL_RGBA, 4, 1};
52
53 // a tiling texture (most common type)
54 #define GLIMAGETYPE_TILE 0
55 // a fragments texture (contains one or more fragment textures)
56 #define GLIMAGETYPE_FRAGMENTS 1
57
58 // a gltextureimage can have one (or more if fragments) gltextures inside
59 typedef struct gltextureimage_s
60 {
61         struct gltextureimage_s *imagechain;
62         int texturecount;
63         int type; // one of the GLIMAGETYPE_ values
64         int texnum; // GL texture slot number
65         int width, height;
66         int bytesperpixel; // bytes per pixel
67         int glformat; // GL_RGB or GL_RGBA
68         int glinternalformat; // 3 or 4
69         int flags;
70         short *blockallocation; // fragment allocation
71 }
72 gltextureimage_t;
73
74 typedef struct gltexture_s
75 {
76         // this field is exposed to the R_GetTexture macro, for speed reasons
77         // (must be identical in rtexture_t)
78         int texnum; // GL texture slot number
79
80         // pointer to texturepool (check this to see if the texture is allocated)
81         struct gltexturepool_s *pool;
82         // pointer to next texture in texturepool chain
83         struct gltexture_s *chain;
84         // pointer into gltextureimage array
85         gltextureimage_t *image;
86         // name of the texture (this might be removed someday), no duplicates
87         char *identifier;
88         // location in the image, and size
89         int x, y, width, height;
90         // copy of the original texture supplied to the upload function, for re-uploading or deferred uploads (non-precached)
91         qbyte *inputtexels;
92         // to identify cache mismatchs (this might be removed someday)
93         int crc;
94         // flags supplied to the LoadTexture function
95         // (might be altered to remove TEXF_ALPHA), and GLTEXF_ private flags
96         int flags;
97         // pointer to one of the textype_ structs
98         textypeinfo_t *textype;
99 }
100 gltexture_t;
101
102 #define TEXTUREPOOL_SENTINEL 0xC0DEDBAD
103
104 typedef struct gltexturepool_s
105 {
106         int sentinel;
107         struct gltextureimage_s *imagechain;
108         struct gltexture_s *gltchain;
109         struct gltexturepool_s *next;
110 }
111 gltexturepool_t;
112
113 static gltexturepool_t *gltexturepoolchain = NULL;
114
115 static qbyte *resizebuffer = NULL, *colorconvertbuffer;
116 static int resizebuffersize = 0;
117 static qbyte *texturebuffer;
118 static int texturebuffersize = 0;
119
120 static int realmaxsize = 0;
121
122 static textypeinfo_t *R_GetTexTypeInfo(int textype, int flags)
123 {
124         if (flags & TEXF_ALPHA)
125         {
126                 switch(textype)
127                 {
128                 case TEXTYPE_QPALETTE:
129                         return &textype_qpalette_alpha;
130                 case TEXTYPE_RGB:
131                         Host_Error("R_GetTexTypeInfo: RGB format has no alpha, TEXF_ALPHA not allowed\n");
132                         return NULL;
133                 case TEXTYPE_RGBA:
134                         return &textype_rgba_alpha;
135                 default:
136                         Host_Error("R_GetTexTypeInfo: unknown texture format\n");
137                         return NULL;
138                 }
139         }
140         else
141         {
142                 switch(textype)
143                 {
144                 case TEXTYPE_QPALETTE:
145                         return &textype_qpalette;
146                 case TEXTYPE_RGB:
147                         return &textype_rgb;
148                 case TEXTYPE_RGBA:
149                         return &textype_rgba;
150                 default:
151                         Host_Error("R_GetTexTypeInfo: unknown texture format\n");
152                         return NULL;
153                 }
154         }
155 }
156
157 static void R_UploadTexture(gltexture_t *t);
158
159 static void R_PrecacheTexture(gltexture_t *glt)
160 {
161         int precache;
162         precache = false;
163         if (glt->flags & TEXF_ALWAYSPRECACHE)
164                 precache = true;
165         else if (r_precachetextures.integer >= 2)
166                 precache = true;
167         else if (r_precachetextures.integer >= 1)
168                 if (glt->flags & TEXF_PRECACHE)
169                         precache = true;
170
171         if (precache)
172                 R_UploadTexture(glt);
173 }
174
175 int R_RealGetTexture(rtexture_t *rt)
176 {
177         if (rt)
178         {
179                 gltexture_t *glt;
180                 glt = (gltexture_t *)rt;
181                 if (glt->flags & GLTEXF_UPLOAD)
182                         R_UploadTexture(glt);
183                 glt->texnum = glt->image->texnum;
184                 return glt->image->texnum;
185         }
186         else
187                 return 0;
188 }
189
190 void R_FreeTexture(rtexture_t *rt)
191 {
192         gltexture_t *glt, **gltpointer;
193         gltextureimage_t *image, **gltimagepointer;
194         GLuint texnum;
195
196         glt = (gltexture_t *)rt;
197         if (glt == NULL)
198                 Host_Error("R_FreeTexture: texture == NULL\n");
199
200         for (gltpointer = &glt->pool->gltchain;*gltpointer && *gltpointer != glt;gltpointer = &(*gltpointer)->chain);
201         if (*gltpointer == glt)
202                 *gltpointer = glt->chain;
203         else
204                 Host_Error("R_FreeTexture: texture \"%s\" not linked in pool\n", glt->identifier);
205
206         // note: if freeing a fragment texture, this will not make the claimed
207         // space available for new textures unless all other fragments in the
208         // image are also freed
209         image = glt->image;
210         image->texturecount--;
211         if (image->texturecount < 1)
212         {
213                 for (gltimagepointer = &glt->pool->imagechain;*gltimagepointer && *gltimagepointer != image;gltimagepointer = &(*gltimagepointer)->imagechain);
214                 if (*gltimagepointer == image)
215                         *gltimagepointer = image->imagechain;
216                 else
217                         Host_Error("R_FreeTexture: image not linked in pool\n");
218                 if (image->texnum)
219                 {
220                         texnum = image->texnum;
221                         gltexnuminuse[image->texnum] = 0;
222                         qglDeleteTextures(1, &texnum);
223                 }
224                 if (image->blockallocation)
225                         Mem_Free(image->blockallocation);
226                 Mem_Free(image);
227         }
228
229         if (glt->identifier)
230                 Mem_Free(glt->identifier);
231         if (glt->inputtexels)
232                 Mem_Free(glt->inputtexels);
233         Mem_Free(glt);
234 }
235
236 static gltexture_t *R_FindTexture (gltexturepool_t *pool, char *identifier)
237 {
238         gltexture_t     *glt;
239
240         if (!identifier)
241                 return NULL;
242
243         for (glt = pool->gltchain;glt;glt = glt->chain)
244                 if (glt->identifier && !strcmp (identifier, glt->identifier))
245                         return glt;
246
247         return NULL;
248 }
249
250 rtexturepool_t *R_AllocTexturePool(void)
251 {
252         gltexturepool_t *pool;
253         if (texturemempool == NULL)
254                 return NULL;
255         pool = Mem_Alloc(texturemempool, sizeof(gltexturepool_t));
256         if (pool == NULL)
257                 return NULL;
258         pool->next = gltexturepoolchain;
259         gltexturepoolchain = pool;
260         pool->sentinel = TEXTUREPOOL_SENTINEL;
261         return (rtexturepool_t *)pool;
262 }
263
264 void R_FreeTexturePool(rtexturepool_t **rtexturepool)
265 {
266         gltexturepool_t *pool, **poolpointer;
267         if (rtexturepool == NULL)
268                 return;
269         if (*rtexturepool == NULL)
270                 return;
271         pool = (gltexturepool_t *)(*rtexturepool);
272         *rtexturepool = NULL;
273         if (pool->sentinel != TEXTUREPOOL_SENTINEL)
274                 Host_Error("R_FreeTexturePool: pool already freed\n");
275         for (poolpointer = &gltexturepoolchain;*poolpointer && *poolpointer != pool;poolpointer = &(*poolpointer)->next);
276         if (*poolpointer == pool)
277                 *poolpointer = pool->next;
278         else
279                 Host_Error("R_FreeTexturePool: pool not linked\n");
280         while (pool->gltchain)
281                 R_FreeTexture((rtexture_t *)pool->gltchain);
282         if (pool->imagechain)
283                 Sys_Error("R_FreeTexturePool: not all images freed\n");
284         Mem_Free(pool);
285 }
286
287
288 typedef struct
289 {
290         char *name;
291         int minification, magnification;
292 }
293 glmode_t;
294
295 static glmode_t modes[] =
296 {
297         {"GL_NEAREST", GL_NEAREST, GL_NEAREST},
298         {"GL_LINEAR", GL_LINEAR, GL_LINEAR},
299         {"GL_NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST},
300         {"GL_LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR},
301         {"GL_NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST},
302         {"GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR}
303 };
304
305 extern int gl_backend_rebindtextures;
306
307 static void GL_TextureMode_f (void)
308 {
309         int i;
310         gltextureimage_t *image;
311         gltexturepool_t *pool;
312
313         if (Cmd_Argc() == 1)
314         {
315                 for (i = 0;i < 6;i++)
316                 {
317                         if (gl_filter_min == modes[i].minification)
318                         {
319                                 Con_Printf ("%s\n", modes[i].name);
320                                 return;
321                         }
322                 }
323                 Con_Printf ("current filter is unknown???\n");
324                 return;
325         }
326
327         for (i = 0;i < 6;i++)
328                 if (!Q_strcasecmp (modes[i].name, Cmd_Argv(1) ) )
329                         break;
330         if (i == 6)
331         {
332                 Con_Printf ("bad filter name\n");
333                 return;
334         }
335
336         gl_filter_min = modes[i].minification;
337         gl_filter_mag = modes[i].magnification;
338
339         // change all the existing mipmap texture objects
340         // FIXME: force renderer(/client/something?) restart instead?
341         for (pool = gltexturepoolchain;pool;pool = pool->next)
342         {
343                 for (image = pool->imagechain;image;image = image->imagechain)
344                 {
345                         // only update already uploaded images
346                         if (!(image->flags & GLTEXF_UPLOAD))
347                         {
348                                 qglBindTexture(GL_TEXTURE_2D, image->texnum);
349                                 if (image->flags & TEXF_MIPMAP)
350                                         qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
351                                 else
352                                         qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
353                                 qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
354                         }
355                 }
356         }
357         gl_backend_rebindtextures = true;
358 }
359
360 static int R_CalcTexelDataSize (gltexture_t *glt)
361 {
362         int width2, height2, size;
363         if (glt->flags & TEXF_FRAGMENT)
364                 size = glt->width * glt->height;
365         else
366         {
367                 if (r_max_size.integer > realmaxsize)
368                         Cvar_SetValue("r_max_size", realmaxsize);
369                 // calculate final size
370                 for (width2 = 1;width2 < glt->width;width2 <<= 1);
371                 for (height2 = 1;height2 < glt->height;height2 <<= 1);
372                 for (width2 >>= r_picmip.integer;width2 > r_max_size.integer;width2 >>= 1);
373                 for (height2 >>= r_picmip.integer;height2 > r_max_size.integer;height2 >>= 1);
374                 if (width2 < 1) width2 = 1;
375                 if (height2 < 1) height2 = 1;
376
377                 size = 0;
378                 if (glt->flags & TEXF_MIPMAP)
379                 {
380                         while (width2 > 1 || height2 > 1)
381                         {
382                                 size += width2 * height2;
383                                 if (width2 > 1)
384                                         width2 >>= 1;
385                                 if (height2 > 1)
386                                         height2 >>= 1;
387                         }
388                         size++; // count the last 1x1 mipmap
389                 }
390                 else
391                         size = width2*height2;
392         }
393         size *= glt->textype->internalbytesperpixel;
394
395         return size;
396 }
397
398 void R_TextureStats_PrintTotal(void)
399 {
400         int glsize, inputsize, total = 0, totalt = 0, totalp = 0, loaded = 0, loadedt = 0, loadedp = 0;
401         gltexture_t *glt;
402         gltexturepool_t *pool;
403         for (pool = gltexturepoolchain;pool;pool = pool->next)
404         {
405                 for (glt = pool->gltchain;glt;glt = glt->chain)
406                 {
407                         glsize = R_CalcTexelDataSize(glt);
408                         inputsize = glt->width * glt->height * glt->textype->inputbytesperpixel;
409
410                         total++;
411                         totalt += glsize;
412                         totalp += inputsize;
413                         if (!(glt->flags & GLTEXF_UPLOAD))
414                         {
415                                 loaded++;
416                                 loadedt += glsize;
417                                 loadedp += inputsize;
418                         }
419                 }
420         }
421         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);
422 }
423
424 static void R_TextureStats_f(void)
425 {
426         int loaded;
427         gltexture_t *glt;
428         gltexturepool_t *pool;
429         Con_Printf("glsize input crc  loaded mip alpha name\n");
430         for (pool = gltexturepoolchain;pool;pool = pool->next)
431         {
432                 for (glt = pool->gltchain;glt;glt = glt->chain)
433                 {
434                         loaded = !(glt->flags & GLTEXF_UPLOAD);
435                         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>");
436                 }
437                 Con_Printf("pool %10p\n", pool);
438         }
439         R_TextureStats_PrintTotal();
440 }
441
442 char engineversion[40];
443
444 static void r_textures_start(void)
445 {
446         // deal with size limits of various drivers (3dfx in particular)
447         qglGetIntegerv(GL_MAX_TEXTURE_SIZE, &realmaxsize);
448         CHECKGLERROR
449
450         // use the largest scrap texture size we can (not sure if this is really a good idea)
451         for (block_size = 1;block_size < realmaxsize && block_size < r_max_scrapsize.integer;block_size <<= 1);
452
453         texturemempool = Mem_AllocPool("Texture Info");
454         texturedatamempool = Mem_AllocPool("Texture Storage (not yet uploaded)");
455         textureprocessingmempool = Mem_AllocPool("Texture Processing Buffers");
456         gltexnuminuse = Mem_Alloc(texturemempool, MAX_GLTEXTURES);
457 }
458
459 static void r_textures_shutdown(void)
460 {
461         rtexturepool_t *temp;
462         while(gltexturepoolchain)
463         {
464                 temp = (rtexturepool_t *) gltexturepoolchain;
465                 R_FreeTexturePool(&temp);
466         }
467
468         resizebuffersize = 0;
469         texturebuffersize = 0;
470         resizebuffer = NULL;
471         colorconvertbuffer = NULL;
472         texturebuffer = NULL;
473         gltexnuminuse = NULL;
474         Mem_FreePool(&texturemempool);
475         Mem_FreePool(&texturedatamempool);
476         Mem_FreePool(&textureprocessingmempool);
477 }
478
479 static void r_textures_newmap(void)
480 {
481 }
482
483 void R_Textures_Init (void)
484 {
485         Cmd_AddCommand ("gl_texturemode", &GL_TextureMode_f);
486         Cmd_AddCommand("r_texturestats", R_TextureStats_f);
487         Cvar_RegisterVariable (&r_max_scrapsize);
488         Cvar_RegisterVariable (&r_max_size);
489         Cvar_RegisterVariable (&r_picmip);
490         Cvar_RegisterVariable (&r_lerpimages);
491         Cvar_RegisterVariable (&r_precachetextures);
492         gltexnuminuse = NULL;
493
494         R_RegisterModule("R_Textures", r_textures_start, r_textures_shutdown, r_textures_newmap);
495 }
496
497 void R_Textures_Frame (void)
498 {
499         // could do procedural texture animation here, if we keep track of which
500         // textures were accessed this frame...
501
502         // free the resize buffers
503         resizebuffersize = 0;
504         if (resizebuffer)
505         {
506                 Mem_Free(resizebuffer);
507                 resizebuffer = NULL;
508         }
509         if (colorconvertbuffer)
510         {
511                 Mem_Free(colorconvertbuffer);
512                 colorconvertbuffer = NULL;
513         }
514 }
515
516 static void R_Upload(gltexture_t *glt, qbyte *data)
517 {
518         int mip, width, height, internalformat;
519         qbyte *prevbuffer;
520         prevbuffer = data;
521
522         qglBindTexture(GL_TEXTURE_2D, glt->image->texnum);
523         CHECKGLERROR
524
525         gl_backend_rebindtextures = true;
526
527         glt->flags &= ~GLTEXF_UPLOAD;
528
529         if (glt->flags & TEXF_FRAGMENT)
530         {
531                 if (resizebuffersize < glt->image->width * glt->image->height * glt->image->bytesperpixel)
532                 {
533                         resizebuffersize = glt->image->width * glt->image->height * glt->image->bytesperpixel;
534                         if (resizebuffer)
535                                 Mem_Free(resizebuffer);
536                         if (colorconvertbuffer)
537                                 Mem_Free(colorconvertbuffer);
538                         resizebuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
539                         colorconvertbuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
540                         if (!resizebuffer || !colorconvertbuffer)
541                                 Host_Error("R_Upload: out of memory\n");
542                 }
543
544                 if (glt->image->flags & GLTEXF_UPLOAD)
545                 {
546                         Con_DPrintf("uploaded new fragments image\n");
547                         glt->image->flags &= ~GLTEXF_UPLOAD;
548                         memset(resizebuffer, 255, glt->image->width * glt->image->height * glt->image->bytesperpixel);
549                         qglTexImage2D (GL_TEXTURE_2D, 0, glt->image->glinternalformat, glt->image->width, glt->image->height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, resizebuffer);
550                         CHECKGLERROR
551                         qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
552                         CHECKGLERROR
553                         qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
554                         CHECKGLERROR
555                 }
556
557                 if (prevbuffer == NULL)
558                 {
559                         memset(resizebuffer, 255, glt->width * glt->height * glt->image->bytesperpixel);
560                         prevbuffer = resizebuffer;
561                 }
562                 else if (glt->textype->textype == TEXTYPE_QPALETTE)
563                 {
564                         // promote paletted to RGBA, so we only have to worry about RGB and
565                         // RGBA in the rest of this code
566                         Image_Copy8bitRGBA(prevbuffer, colorconvertbuffer, glt->width * glt->height, d_8to24table);
567                         prevbuffer = colorconvertbuffer;
568                 }
569
570                 qglTexSubImage2D(GL_TEXTURE_2D, 0, glt->x, glt->y, glt->width, glt->height, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
571                 CHECKGLERROR
572                 glt->texnum = glt->image->texnum;
573                 return;
574         }
575
576         glt->image->flags &= ~GLTEXF_UPLOAD;
577
578         // these are rounded up versions of the size to do better resampling
579         for (width = 1;width < glt->width;width <<= 1);
580         for (height = 1;height < glt->height;height <<= 1);
581
582         if (resizebuffersize < width * height * glt->image->bytesperpixel)
583         {
584                 resizebuffersize = width * height * glt->image->bytesperpixel;
585                 if (resizebuffer)
586                         Mem_Free(resizebuffer);
587                 if (colorconvertbuffer)
588                         Mem_Free(colorconvertbuffer);
589                 resizebuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
590                 colorconvertbuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
591                 if (!resizebuffer || !colorconvertbuffer)
592                         Host_Error("R_Upload: out of memory\n");
593         }
594
595         if (prevbuffer == NULL)
596         {
597                 width = glt->image->width;
598                 height = glt->image->height;
599                 memset(resizebuffer, 255, width * height * glt->image->bytesperpixel);
600                 prevbuffer = resizebuffer;
601         }
602         else
603         {
604                 if (glt->textype->textype == TEXTYPE_QPALETTE)
605                 {
606                         // promote paletted to RGBA, so we only have to worry about RGB and
607                         // RGBA in the rest of this code
608                         Image_Copy8bitRGBA(prevbuffer, colorconvertbuffer, glt->width * glt->height, d_8to24table);
609                         prevbuffer = colorconvertbuffer;
610                 }
611
612                 if (glt->width != width || glt->height != height)
613                 {
614                         Image_Resample(prevbuffer, glt->width, glt->height, resizebuffer, width, height, glt->image->bytesperpixel, r_lerpimages.integer);
615                         prevbuffer = resizebuffer;
616                 }
617
618                 // apply picmip/max_size limitations
619                 while (width > glt->image->width || height > glt->image->height)
620                 {
621                         Image_MipReduce(prevbuffer, resizebuffer, &width, &height, glt->image->width, glt->image->height, glt->image->bytesperpixel);
622                         prevbuffer = resizebuffer;
623                 }
624         }
625
626         // 3 and 4 are converted by the driver to it's preferred format for the current display mode
627         internalformat = 3;
628         if (glt->flags & TEXF_ALPHA)
629                 internalformat = 4;
630
631         mip = 0;
632         qglTexImage2D(GL_TEXTURE_2D, mip++, internalformat, width, height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
633         CHECKGLERROR
634         if (glt->flags & TEXF_MIPMAP)
635         {
636                 while (width > 1 || height > 1)
637                 {
638                         Image_MipReduce(prevbuffer, resizebuffer, &width, &height, 1, 1, glt->image->bytesperpixel);
639                         prevbuffer = resizebuffer;
640
641                         qglTexImage2D(GL_TEXTURE_2D, mip++, internalformat, width, height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
642                         CHECKGLERROR
643                 }
644
645                 qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
646                 CHECKGLERROR
647                 qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
648                 CHECKGLERROR
649         }
650         else
651         {
652                 qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
653                 CHECKGLERROR
654                 qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
655                 CHECKGLERROR
656         }
657         glt->texnum = glt->image->texnum;
658 }
659
660 static void R_FindImageForTexture(gltexture_t *glt)
661 {
662         int i, j, best, best2, x, y, w, h;
663         textypeinfo_t *texinfo;
664         gltexturepool_t *pool;
665         gltextureimage_t *image, **imagechainpointer;
666         texinfo = glt->textype;
667         pool = glt->pool;
668
669         // remains -1 until uploaded
670         glt->texnum = -1;
671
672         x = 0;
673         y = 0;
674         w = glt->width;
675         h = glt->height;
676         if (glt->flags & TEXF_FRAGMENT)
677         {
678                 for (imagechainpointer = &pool->imagechain;*imagechainpointer;imagechainpointer = &(*imagechainpointer)->imagechain)
679                 {
680                         image = *imagechainpointer;
681                         if (image->type != GLIMAGETYPE_FRAGMENTS)
682                                 continue;
683                         if (image->glformat != texinfo->glformat || image->glinternalformat != texinfo->glinternalformat)
684                                 continue;
685                         if (glt->width > image->width || glt->height > image->height)
686                                 continue;
687
688                         // got a fragments texture, find a place in it if we can
689                         for (best = image->width, i = 0;i < image->width - w;i += texinfo->align)
690                         {
691                                 for (best2 = 0, j = 0;j < w;j++)
692                                 {
693                                         if (image->blockallocation[i+j] >= best)
694                                                 break;
695                                         if (best2 < image->blockallocation[i+j])
696                                                 best2 = image->blockallocation[i+j];
697                                 }
698                                 if (j == w)
699                                 {
700                                         // this is a valid spot
701                                         x = i;
702                                         y = best = best2;
703                                 }
704                         }
705
706                         if (best + h > image->height)
707                                 continue;
708
709                         for (i = 0;i < w;i++)
710                                 image->blockallocation[x + i] = best + h;
711
712                         glt->x = x;
713                         glt->y = y;
714                         glt->image = image;
715                         image->texturecount++;
716                         return;
717                 }
718
719                 image = Mem_Alloc(texturemempool, sizeof(gltextureimage_t));
720                 if (image == NULL)
721                         Sys_Error("R_FindImageForTexture: ran out of memory\n");
722                 image->type = GLIMAGETYPE_FRAGMENTS;
723                 // make sure the created image is big enough for the fragment
724                 for (image->width = block_size;image->width < glt->width;image->width <<= 1);
725                 for (image->height = block_size;image->height < glt->height;image->height <<= 1);
726                 image->blockallocation = Mem_Alloc(texturemempool, image->width * sizeof(short));
727                 memset(image->blockallocation, 0, image->width * sizeof(short));
728
729                 x = 0;
730                 y = 0;
731                 for (i = 0;i < w;i++)
732                         image->blockallocation[x + i] = y + h;
733         }
734         else
735         {
736                 for (imagechainpointer = &pool->imagechain;*imagechainpointer;imagechainpointer = &(*imagechainpointer)->imagechain);
737
738                 image = Mem_Alloc(texturemempool, sizeof(gltextureimage_t));
739                 if (image == NULL)
740                         Sys_Error("R_FindImageForTexture: ran out of memory\n");
741                 image->type = GLIMAGETYPE_TILE;
742                 image->blockallocation = NULL;
743
744                 // calculate final size
745                 if (r_max_size.integer > realmaxsize)
746                         Cvar_SetValue("r_max_size", realmaxsize);
747                 for (image->width = 1;image->width < glt->width;image->width <<= 1);
748                 for (image->height = 1;image->height < glt->height;image->height <<= 1);
749                 for (image->width >>= r_picmip.integer;image->width > r_max_size.integer;image->width >>= 1);
750                 for (image->height >>= r_picmip.integer;image->height > r_max_size.integer;image->height >>= 1);
751                 if (image->width < 1) image->width = 1;
752                 if (image->height < 1) image->height = 1;
753         }
754         image->glinternalformat = texinfo->glinternalformat;
755         image->glformat = texinfo->glformat;
756         image->flags = (glt->flags & (TEXF_MIPMAP | TEXF_ALPHA)) | GLTEXF_UPLOAD;
757         image->bytesperpixel = texinfo->internalbytesperpixel;
758         for (i = 1;i < MAX_GLTEXTURES;i++)
759                 if (!gltexnuminuse[i])
760                         break;
761         if (i < MAX_GLTEXTURES)
762                 gltexnuminuse[image->texnum = i] = true;
763         else
764                 Sys_Error("R_FindImageForTexture: ran out of GL textures\n");
765         *imagechainpointer = image;
766         image->texturecount++;
767
768         glt->x = x;
769         glt->y = y;
770         glt->image = image;
771 }
772
773 // note: R_FindImageForTexture must be called before this
774 static void R_UploadTexture (gltexture_t *glt)
775 {
776         if (!(glt->flags & GLTEXF_UPLOAD))
777                 return;
778
779         R_Upload(glt, glt->inputtexels);
780         if (glt->inputtexels)
781         {
782                 Mem_Free(glt->inputtexels);
783                 glt->inputtexels = NULL;
784                 glt->flags |= GLTEXF_DESTROYED;
785         }
786         else if (glt->flags & GLTEXF_DESTROYED)
787                 Con_Printf("R_UploadTexture: Texture %s already uploaded and destroyed.  Can not upload original image again.  Uploaded blank texture.\n", glt->identifier);
788 }
789
790 static gltexture_t *R_SetupTexture(gltexturepool_t *pool, char *identifier, int crc, int width, int height, int flags, textypeinfo_t *texinfo, qbyte *data)
791 {
792         gltexture_t *glt;
793         glt = Mem_Alloc(texturemempool, sizeof(gltexture_t));
794         if (identifier)
795         {
796                 glt->identifier = Mem_Alloc(texturemempool, strlen(identifier)+1);
797                 strcpy (glt->identifier, identifier);
798         }
799         else
800                 glt->identifier = NULL;
801         glt->pool = pool;
802         glt->chain = pool->gltchain;
803         pool->gltchain = glt;
804         glt->crc = crc;
805         glt->width = width;
806         glt->height = height;
807         glt->flags = flags;
808         glt->textype = texinfo;
809
810         if (data)
811         {
812                 glt->inputtexels = Mem_Alloc(texturedatamempool, glt->width * glt->height * texinfo->inputbytesperpixel);
813                 if (glt->inputtexels == NULL)
814                         Sys_Error("R_SetupTexture: out of memory\n");
815                 memcpy(glt->inputtexels, data, glt->width * glt->height * texinfo->inputbytesperpixel);
816         }
817         else
818                 glt->inputtexels = NULL;
819
820         R_FindImageForTexture(glt);
821         R_PrecacheTexture(glt);
822
823         return glt;
824 }
825
826 /*
827 ================
828 R_LoadTexture
829 ================
830 */
831 rtexture_t *R_LoadTexture (rtexturepool_t *rtexturepool, char *identifier, int width, int height, qbyte *data, int textype, int flags)
832 {
833         int i;
834         gltexture_t *glt;
835         gltexturepool_t *pool = (gltexturepool_t *)rtexturepool;
836         textypeinfo_t *texinfo;
837         unsigned short crc;
838
839         if (cls.state == ca_dedicated)
840                 return NULL;
841
842         texinfo = R_GetTexTypeInfo(textype, flags);
843
844         if (flags & TEXF_FRAGMENT)
845                 if ((width * texinfo->internalbytesperpixel) & 3)
846                         Host_Error("R_LoadTexture: incompatible width for fragment");
847
848         // clear the alpha flag if the texture has no transparent pixels
849         switch(textype)
850         {
851         case TEXTYPE_QPALETTE:
852                 if (flags & TEXF_ALPHA)
853                 {
854                         flags &= ~TEXF_ALPHA;
855                         for (i = 0;i < width * height;i++)
856                         {
857                                 if (data[i] == 255)
858                                 {
859                                         flags |= TEXF_ALPHA;
860                                         break;
861                                 }
862                         }
863                 }
864                 break;
865         case TEXTYPE_RGB:
866                 if (flags & TEXF_ALPHA)
867                         Host_Error("R_LoadTexture: RGB has no alpha, don't specify TEXF_ALPHA\n");
868                 break;
869         case TEXTYPE_RGBA:
870                 if (flags & TEXF_ALPHA)
871                 {
872                         flags &= ~TEXF_ALPHA;
873                         for (i = 0;i < width * height;i++)
874                         {
875                                 if (data[i * 4 + 3] < 255)
876                                 {
877                                         flags |= TEXF_ALPHA;
878                                         break;
879                                 }
880                         }
881                 }
882                 break;
883         default:
884                 Host_Error("R_LoadTexture: unknown texture type\n");
885         }
886
887         // LordHavoc: do a CRC to confirm the data really is the same as previous occurances.
888         if (data == NULL)
889                 crc = 0;
890         else
891                 crc = CRC_Block(data, width*height*texinfo->inputbytesperpixel);
892
893         // see if the texture is already present
894         if (identifier && (glt = R_FindTexture(pool, identifier)))
895         {
896                 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)
897                 {
898                         Con_Printf("R_LoadTexture: exact match with existing texture %s\n", identifier);
899                         return (rtexture_t *)glt; // exact match, use existing
900                 }
901                 Con_Printf("R_LoadTexture: cache mismatch on %s, replacing old texture\n", identifier);
902                 R_FreeTexture((rtexture_t *)glt);
903         }
904
905         return (rtexture_t *)R_SetupTexture(pool, identifier, crc, width, height, flags | GLTEXF_UPLOAD, texinfo, data);
906 }
907
908 int R_TextureHasAlpha(rtexture_t *rt)
909 {
910         gltexture_t *glt;
911         if (!rt)
912                 return false;
913         glt = (gltexture_t *)rt;
914         return (glt->flags & TEXF_ALPHA) != 0;
915 }
916
917 int R_TextureWidth(rtexture_t *rt)
918 {
919         if (!rt)
920                 return false;
921         return ((gltexture_t *)rt)->width;
922 }
923
924 int R_TextureHeight(rtexture_t *rt)
925 {
926         if (!rt)
927                 return false;
928         return ((gltexture_t *)rt)->height;
929 }
930
931 void R_FragmentLocation(rtexture_t *rt, int *x, int *y, float *fx1, float *fy1, float *fx2, float *fy2)
932 {
933         gltexture_t *glt;
934         float iwidth, iheight;
935         if (cls.state == ca_dedicated)
936         {
937                 if (x)
938                         *x = 0;
939                 if (y)
940                         *y = 0;
941                 if (fx1 || fy1 || fx2 || fy2)
942                 {
943                         if (fx1)
944                                 *fx1 = 0;
945                         if (fy1)
946                                 *fy1 = 0;
947                         if (fx2)
948                                 *fx2 = 1;
949                         if (fy2)
950                                 *fy2 = 1;
951                 }
952                 return;
953         }
954         if (!rt)
955                 Host_Error("R_FragmentLocation: no texture supplied\n");
956         glt = (gltexture_t *)rt;
957         if (glt->flags & TEXF_FRAGMENT)
958         {
959                 if (x)
960                         *x = glt->x;
961                 if (y)
962                         *y = glt->y;
963                 if (fx1 || fy1 || fx2 || fy2)
964                 {
965                         iwidth = 1.0f / glt->image->width;
966                         iheight = 1.0f / glt->image->height;
967                         if (fx1)
968                                 *fx1 = glt->x * iwidth;
969                         if (fy1)
970                                 *fy1 = glt->y * iheight;
971                         if (fx2)
972                                 *fx2 = (glt->x + glt->width) * iwidth;
973                         if (fy2)
974                                 *fy2 = (glt->y + glt->height) * iheight;
975                 }
976         }
977         else
978         {
979                 if (x)
980                         *x = 0;
981                 if (y)
982                         *y = 0;
983                 if (fx1 || fy1 || fx2 || fy2)
984                 {
985                         if (fx1)
986                                 *fx1 = 0;
987                         if (fy1)
988                                 *fy1 = 0;
989                         if (fx2)
990                                 *fx2 = 1;
991                         if (fy2)
992                                 *fy2 = 1;
993                 }
994         }
995 }
996
997 int R_CompatibleFragmentWidth(int width, int textype, int flags)
998 {
999         textypeinfo_t *texinfo = R_GetTexTypeInfo(textype, flags);
1000         while ((width * texinfo->internalbytesperpixel) & 3)
1001                 width++;
1002         return width;
1003 }
1004
1005 void R_UpdateTexture(rtexture_t *rt, qbyte *data)
1006 {
1007         gltexture_t *glt;
1008         if (rt == NULL)
1009                 Host_Error("R_UpdateTexture: no texture supplied\n");
1010         if (data == NULL)
1011                 Host_Error("R_UpdateTexture: no data supplied\n");
1012         glt = (gltexture_t *)rt;
1013
1014         // if it has not been uploaded yet, update the data that will be used when it is
1015         if (glt->inputtexels)
1016                 memcpy(glt->inputtexels, data, glt->width * glt->height * glt->textype->inputbytesperpixel);
1017         else
1018                 R_Upload(glt, data);
1019 }
1020