vertex arrays renamed to varray_ and exposed to rest of engine
[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 void R_MakeResizeBufferBigger(int size)
517 {
518         if (resizebuffersize < size)
519         {
520                 resizebuffersize = size;
521                 if (resizebuffer)
522                         Mem_Free(resizebuffer);
523                 if (colorconvertbuffer)
524                         Mem_Free(colorconvertbuffer);
525                 resizebuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
526                 colorconvertbuffer = Mem_Alloc(textureprocessingmempool, resizebuffersize);
527                 if (!resizebuffer || !colorconvertbuffer)
528                         Host_Error("R_Upload: out of memory\n");
529         }
530 }
531
532 static void R_Upload(gltexture_t *glt, qbyte *data)
533 {
534         int mip, width, height, internalformat;
535         qbyte *prevbuffer;
536         prevbuffer = data;
537
538         qglBindTexture(GL_TEXTURE_2D, glt->image->texnum);
539         CHECKGLERROR
540
541         gl_backend_rebindtextures = true;
542
543         glt->flags &= ~GLTEXF_UPLOAD;
544
545         if (glt->flags & TEXF_FRAGMENT)
546         {
547                 if (glt->image->flags & GLTEXF_UPLOAD)
548                 {
549                         Con_DPrintf("uploaded new fragments image\n");
550                         R_MakeResizeBufferBigger(glt->image->width * glt->image->height * glt->image->bytesperpixel);
551                         glt->image->flags &= ~GLTEXF_UPLOAD;
552                         memset(resizebuffer, 255, glt->image->width * glt->image->height * glt->image->bytesperpixel);
553                         qglTexImage2D (GL_TEXTURE_2D, 0, glt->image->glinternalformat, glt->image->width, glt->image->height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, resizebuffer);
554                         CHECKGLERROR
555                         qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
556                         CHECKGLERROR
557                         qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
558                         CHECKGLERROR
559                 }
560
561                 if (prevbuffer == NULL)
562                 {
563                         R_MakeResizeBufferBigger(glt->image->width * glt->image->height * glt->image->bytesperpixel);
564                         memset(resizebuffer, 255, glt->width * glt->height * glt->image->bytesperpixel);
565                         prevbuffer = resizebuffer;
566                 }
567                 else if (glt->textype->textype == TEXTYPE_QPALETTE)
568                 {
569                         // promote paletted to RGBA, so we only have to worry about RGB and
570                         // RGBA in the rest of this code
571                         R_MakeResizeBufferBigger(glt->image->width * glt->image->height * glt->image->bytesperpixel);
572                         Image_Copy8bitRGBA(prevbuffer, colorconvertbuffer, glt->width * glt->height, d_8to24table);
573                         prevbuffer = colorconvertbuffer;
574                 }
575
576                 qglTexSubImage2D(GL_TEXTURE_2D, 0, glt->x, glt->y, glt->width, glt->height, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
577                 CHECKGLERROR
578                 glt->texnum = glt->image->texnum;
579                 return;
580         }
581
582         glt->image->flags &= ~GLTEXF_UPLOAD;
583
584         // these are rounded up versions of the size to do better resampling
585         for (width = 1;width < glt->width;width <<= 1);
586         for (height = 1;height < glt->height;height <<= 1);
587
588         R_MakeResizeBufferBigger(width * height * glt->image->bytesperpixel);
589
590         if (prevbuffer == NULL)
591         {
592                 width = glt->image->width;
593                 height = glt->image->height;
594                 memset(resizebuffer, 255, width * height * glt->image->bytesperpixel);
595                 prevbuffer = resizebuffer;
596         }
597         else
598         {
599                 if (glt->textype->textype == TEXTYPE_QPALETTE)
600                 {
601                         // promote paletted to RGBA, so we only have to worry about RGB and
602                         // RGBA in the rest of this code
603                         Image_Copy8bitRGBA(prevbuffer, colorconvertbuffer, glt->width * glt->height, d_8to24table);
604                         prevbuffer = colorconvertbuffer;
605                 }
606
607                 if (glt->width != width || glt->height != height)
608                 {
609                         Image_Resample(prevbuffer, glt->width, glt->height, resizebuffer, width, height, glt->image->bytesperpixel, r_lerpimages.integer);
610                         prevbuffer = resizebuffer;
611                 }
612
613                 // apply picmip/max_size limitations
614                 while (width > glt->image->width || height > glt->image->height)
615                 {
616                         Image_MipReduce(prevbuffer, resizebuffer, &width, &height, glt->image->width, glt->image->height, glt->image->bytesperpixel);
617                         prevbuffer = resizebuffer;
618                 }
619         }
620
621         // 3 and 4 are converted by the driver to it's preferred format for the current display mode
622         internalformat = 3;
623         if (glt->flags & TEXF_ALPHA)
624                 internalformat = 4;
625
626         mip = 0;
627         qglTexImage2D(GL_TEXTURE_2D, mip++, internalformat, width, height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
628         CHECKGLERROR
629         if (glt->flags & TEXF_MIPMAP)
630         {
631                 while (width > 1 || height > 1)
632                 {
633                         Image_MipReduce(prevbuffer, resizebuffer, &width, &height, 1, 1, glt->image->bytesperpixel);
634                         prevbuffer = resizebuffer;
635
636                         qglTexImage2D(GL_TEXTURE_2D, mip++, internalformat, width, height, 0, glt->image->glformat, GL_UNSIGNED_BYTE, prevbuffer);
637                         CHECKGLERROR
638                 }
639
640                 qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min);
641                 CHECKGLERROR
642                 qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
643                 CHECKGLERROR
644         }
645         else
646         {
647                 qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_mag);
648                 CHECKGLERROR
649                 qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_mag);
650                 CHECKGLERROR
651         }
652         glt->texnum = glt->image->texnum;
653 }
654
655 static void R_FindImageForTexture(gltexture_t *glt)
656 {
657         int i, j, best, best2, x, y, w, h;
658         textypeinfo_t *texinfo;
659         gltexturepool_t *pool;
660         gltextureimage_t *image, **imagechainpointer;
661         texinfo = glt->textype;
662         pool = glt->pool;
663
664         // remains -1 until uploaded
665         glt->texnum = -1;
666
667         x = 0;
668         y = 0;
669         w = glt->width;
670         h = glt->height;
671         if (glt->flags & TEXF_FRAGMENT)
672         {
673                 for (imagechainpointer = &pool->imagechain;*imagechainpointer;imagechainpointer = &(*imagechainpointer)->imagechain)
674                 {
675                         image = *imagechainpointer;
676                         if (image->type != GLIMAGETYPE_FRAGMENTS)
677                                 continue;
678                         if (image->glformat != texinfo->glformat || image->glinternalformat != texinfo->glinternalformat)
679                                 continue;
680                         if (glt->width > image->width || glt->height > image->height)
681                                 continue;
682
683                         // got a fragments texture, find a place in it if we can
684                         for (best = image->width, i = 0;i < image->width - w;i += texinfo->align)
685                         {
686                                 for (best2 = 0, j = 0;j < w;j++)
687                                 {
688                                         if (image->blockallocation[i+j] >= best)
689                                                 break;
690                                         if (best2 < image->blockallocation[i+j])
691                                                 best2 = image->blockallocation[i+j];
692                                 }
693                                 if (j == w)
694                                 {
695                                         // this is a valid spot
696                                         x = i;
697                                         y = best = best2;
698                                 }
699                         }
700
701                         if (best + h > image->height)
702                                 continue;
703
704                         for (i = 0;i < w;i++)
705                                 image->blockallocation[x + i] = best + h;
706
707                         glt->x = x;
708                         glt->y = y;
709                         glt->image = image;
710                         image->texturecount++;
711                         return;
712                 }
713
714                 image = Mem_Alloc(texturemempool, sizeof(gltextureimage_t));
715                 if (image == NULL)
716                         Sys_Error("R_FindImageForTexture: ran out of memory\n");
717                 image->type = GLIMAGETYPE_FRAGMENTS;
718                 // make sure the created image is big enough for the fragment
719                 for (image->width = block_size;image->width < glt->width;image->width <<= 1);
720                 for (image->height = block_size;image->height < glt->height;image->height <<= 1);
721                 image->blockallocation = Mem_Alloc(texturemempool, image->width * sizeof(short));
722                 memset(image->blockallocation, 0, image->width * sizeof(short));
723
724                 x = 0;
725                 y = 0;
726                 for (i = 0;i < w;i++)
727                         image->blockallocation[x + i] = y + h;
728         }
729         else
730         {
731                 for (imagechainpointer = &pool->imagechain;*imagechainpointer;imagechainpointer = &(*imagechainpointer)->imagechain);
732
733                 image = Mem_Alloc(texturemempool, sizeof(gltextureimage_t));
734                 if (image == NULL)
735                         Sys_Error("R_FindImageForTexture: ran out of memory\n");
736                 image->type = GLIMAGETYPE_TILE;
737                 image->blockallocation = NULL;
738
739                 // calculate final size
740                 if (r_max_size.integer > realmaxsize)
741                         Cvar_SetValue("r_max_size", realmaxsize);
742                 for (image->width = 1;image->width < glt->width;image->width <<= 1);
743                 for (image->height = 1;image->height < glt->height;image->height <<= 1);
744                 for (image->width >>= r_picmip.integer;image->width > r_max_size.integer;image->width >>= 1);
745                 for (image->height >>= r_picmip.integer;image->height > r_max_size.integer;image->height >>= 1);
746                 if (image->width < 1) image->width = 1;
747                 if (image->height < 1) image->height = 1;
748         }
749         image->glinternalformat = texinfo->glinternalformat;
750         image->glformat = texinfo->glformat;
751         image->flags = (glt->flags & (TEXF_MIPMAP | TEXF_ALPHA)) | GLTEXF_UPLOAD;
752         image->bytesperpixel = texinfo->internalbytesperpixel;
753         for (i = 1;i < MAX_GLTEXTURES;i++)
754                 if (!gltexnuminuse[i])
755                         break;
756         if (i < MAX_GLTEXTURES)
757                 gltexnuminuse[image->texnum = i] = true;
758         else
759                 Sys_Error("R_FindImageForTexture: ran out of GL textures\n");
760         *imagechainpointer = image;
761         image->texturecount++;
762
763         glt->x = x;
764         glt->y = y;
765         glt->image = image;
766 }
767
768 // note: R_FindImageForTexture must be called before this
769 static void R_UploadTexture (gltexture_t *glt)
770 {
771         if (!(glt->flags & GLTEXF_UPLOAD))
772                 return;
773
774         R_Upload(glt, glt->inputtexels);
775         if (glt->inputtexels)
776         {
777                 Mem_Free(glt->inputtexels);
778                 glt->inputtexels = NULL;
779                 glt->flags |= GLTEXF_DESTROYED;
780         }
781         else if (glt->flags & GLTEXF_DESTROYED)
782                 Con_Printf("R_UploadTexture: Texture %s already uploaded and destroyed.  Can not upload original image again.  Uploaded blank texture.\n", glt->identifier);
783 }
784
785 static gltexture_t *R_SetupTexture(gltexturepool_t *pool, char *identifier, int crc, int width, int height, int flags, textypeinfo_t *texinfo, qbyte *data)
786 {
787         gltexture_t *glt;
788         glt = Mem_Alloc(texturemempool, sizeof(gltexture_t));
789         if (identifier)
790         {
791                 glt->identifier = Mem_Alloc(texturemempool, strlen(identifier)+1);
792                 strcpy (glt->identifier, identifier);
793         }
794         else
795                 glt->identifier = NULL;
796         glt->pool = pool;
797         glt->chain = pool->gltchain;
798         pool->gltchain = glt;
799         glt->crc = crc;
800         glt->width = width;
801         glt->height = height;
802         glt->flags = flags;
803         glt->textype = texinfo;
804
805         if (data)
806         {
807                 glt->inputtexels = Mem_Alloc(texturedatamempool, glt->width * glt->height * texinfo->inputbytesperpixel);
808                 if (glt->inputtexels == NULL)
809                         Sys_Error("R_SetupTexture: out of memory\n");
810                 memcpy(glt->inputtexels, data, glt->width * glt->height * texinfo->inputbytesperpixel);
811         }
812         else
813                 glt->inputtexels = NULL;
814
815         R_FindImageForTexture(glt);
816         R_PrecacheTexture(glt);
817
818         return glt;
819 }
820
821 /*
822 ================
823 R_LoadTexture
824 ================
825 */
826 rtexture_t *R_LoadTexture (rtexturepool_t *rtexturepool, char *identifier, int width, int height, qbyte *data, int textype, int flags)
827 {
828         int i;
829         gltexture_t *glt;
830         gltexturepool_t *pool = (gltexturepool_t *)rtexturepool;
831         textypeinfo_t *texinfo;
832         unsigned short crc;
833
834         if (cls.state == ca_dedicated)
835                 return NULL;
836
837         texinfo = R_GetTexTypeInfo(textype, flags);
838
839         if (flags & TEXF_FRAGMENT)
840                 if ((width * texinfo->internalbytesperpixel) & 3)
841                         Host_Error("R_LoadTexture: incompatible width for fragment");
842
843         // clear the alpha flag if the texture has no transparent pixels
844         switch(textype)
845         {
846         case TEXTYPE_QPALETTE:
847                 if (flags & TEXF_ALPHA)
848                 {
849                         flags &= ~TEXF_ALPHA;
850                         for (i = 0;i < width * height;i++)
851                         {
852                                 if (data[i] == 255)
853                                 {
854                                         flags |= TEXF_ALPHA;
855                                         break;
856                                 }
857                         }
858                 }
859                 break;
860         case TEXTYPE_RGB:
861                 if (flags & TEXF_ALPHA)
862                         Host_Error("R_LoadTexture: RGB has no alpha, don't specify TEXF_ALPHA\n");
863                 break;
864         case TEXTYPE_RGBA:
865                 if (flags & TEXF_ALPHA)
866                 {
867                         flags &= ~TEXF_ALPHA;
868                         for (i = 0;i < width * height;i++)
869                         {
870                                 if (data[i * 4 + 3] < 255)
871                                 {
872                                         flags |= TEXF_ALPHA;
873                                         break;
874                                 }
875                         }
876                 }
877                 break;
878         default:
879                 Host_Error("R_LoadTexture: unknown texture type\n");
880         }
881
882         // LordHavoc: do a CRC to confirm the data really is the same as previous occurances.
883         if (data == NULL)
884                 crc = 0;
885         else
886                 crc = CRC_Block(data, width*height*texinfo->inputbytesperpixel);
887
888         // see if the texture is already present
889         if (identifier && (glt = R_FindTexture(pool, identifier)))
890         {
891                 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)
892                 {
893                         Con_Printf("R_LoadTexture: exact match with existing texture %s\n", identifier);
894                         return (rtexture_t *)glt; // exact match, use existing
895                 }
896                 Con_Printf("R_LoadTexture: cache mismatch on %s, replacing old texture\n", identifier);
897                 R_FreeTexture((rtexture_t *)glt);
898         }
899
900         return (rtexture_t *)R_SetupTexture(pool, identifier, crc, width, height, flags | GLTEXF_UPLOAD, texinfo, data);
901 }
902
903 int R_TextureHasAlpha(rtexture_t *rt)
904 {
905         gltexture_t *glt;
906         if (!rt)
907                 return false;
908         glt = (gltexture_t *)rt;
909         return (glt->flags & TEXF_ALPHA) != 0;
910 }
911
912 int R_TextureWidth(rtexture_t *rt)
913 {
914         if (!rt)
915                 return false;
916         return ((gltexture_t *)rt)->width;
917 }
918
919 int R_TextureHeight(rtexture_t *rt)
920 {
921         if (!rt)
922                 return false;
923         return ((gltexture_t *)rt)->height;
924 }
925
926 void R_FragmentLocation(rtexture_t *rt, int *x, int *y, float *fx1, float *fy1, float *fx2, float *fy2)
927 {
928         gltexture_t *glt;
929         float iwidth, iheight;
930         if (cls.state == ca_dedicated)
931         {
932                 if (x)
933                         *x = 0;
934                 if (y)
935                         *y = 0;
936                 if (fx1 || fy1 || fx2 || fy2)
937                 {
938                         if (fx1)
939                                 *fx1 = 0;
940                         if (fy1)
941                                 *fy1 = 0;
942                         if (fx2)
943                                 *fx2 = 1;
944                         if (fy2)
945                                 *fy2 = 1;
946                 }
947                 return;
948         }
949         if (!rt)
950                 Host_Error("R_FragmentLocation: no texture supplied\n");
951         glt = (gltexture_t *)rt;
952         if (glt->flags & TEXF_FRAGMENT)
953         {
954                 if (x)
955                         *x = glt->x;
956                 if (y)
957                         *y = glt->y;
958                 if (fx1 || fy1 || fx2 || fy2)
959                 {
960                         iwidth = 1.0f / glt->image->width;
961                         iheight = 1.0f / glt->image->height;
962                         if (fx1)
963                                 *fx1 = glt->x * iwidth;
964                         if (fy1)
965                                 *fy1 = glt->y * iheight;
966                         if (fx2)
967                                 *fx2 = (glt->x + glt->width) * iwidth;
968                         if (fy2)
969                                 *fy2 = (glt->y + glt->height) * iheight;
970                 }
971         }
972         else
973         {
974                 if (x)
975                         *x = 0;
976                 if (y)
977                         *y = 0;
978                 if (fx1 || fy1 || fx2 || fy2)
979                 {
980                         if (fx1)
981                                 *fx1 = 0;
982                         if (fy1)
983                                 *fy1 = 0;
984                         if (fx2)
985                                 *fx2 = 1;
986                         if (fy2)
987                                 *fy2 = 1;
988                 }
989         }
990 }
991
992 int R_CompatibleFragmentWidth(int width, int textype, int flags)
993 {
994         textypeinfo_t *texinfo = R_GetTexTypeInfo(textype, flags);
995         while ((width * texinfo->internalbytesperpixel) & 3)
996                 width++;
997         return width;
998 }
999
1000 void R_UpdateTexture(rtexture_t *rt, qbyte *data)
1001 {
1002         gltexture_t *glt;
1003         if (rt == NULL)
1004                 Host_Error("R_UpdateTexture: no texture supplied\n");
1005         if (data == NULL)
1006                 Host_Error("R_UpdateTexture: no data supplied\n");
1007         glt = (gltexture_t *)rt;
1008
1009         // if it has not been uploaded yet, update the data that will be used when it is
1010         if (glt->inputtexels)
1011                 memcpy(glt->inputtexels, data, glt->width * glt->height * glt->textype->inputbytesperpixel);
1012         else
1013                 R_Upload(glt, data);
1014 }
1015