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