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