added a lot more CHECKGLERROR macro calls, to identify precisely where any error...
[divverent/darkplaces.git] / gl_textures.c
1
2 #include "quakedef.h"
3 #include "image.h"
4 #include "jpeg.h"
5 #include "image_png.h"
6
7 cvar_t gl_max_size = {CVAR_SAVE, "gl_max_size", "2048", "maximum allowed texture size, can be used to reduce video memory usage, note: this is automatically reduced to match video card capabilities (such as 256 on 3Dfx cards before Voodoo4/5)"};
8 cvar_t gl_picmip = {CVAR_SAVE, "gl_picmip", "0", "reduces resolution of textures by powers of 2, for example 1 will halve width/height, reducing texture memory usage by 75%"};
9 cvar_t r_lerpimages = {CVAR_SAVE, "r_lerpimages", "1", "bilinear filters images when scaling them up to power of 2 size (mode 1), looks better than glquake (mode 0)"};
10 cvar_t r_precachetextures = {CVAR_SAVE, "r_precachetextures", "1", "0 = never upload textures until used, 1 = upload most textures before use (exceptions: rarely used skin colormap layers), 2 = upload all textures before use (can increase texture memory usage significantly)"};
11 cvar_t gl_texture_anisotropy = {CVAR_SAVE, "gl_texture_anisotropy", "1", "anisotropic filtering quality (if supported by hardware), 1 sample (no anisotropy) and 8 sample (8 tap anisotropy) are recommended values"};
12
13 int             gl_filter_min = GL_LINEAR_MIPMAP_LINEAR;
14 int             gl_filter_mag = GL_LINEAR;
15
16
17 static mempool_t *texturemempool;
18
19 // note: this must not conflict with TEXF_ flags in r_textures.h
20 // cleared when a texture is uploaded
21 #define GLTEXF_UPLOAD 0x00010000
22 // bitmask for mismatch checking
23 #define GLTEXF_IMPORTANTBITS (0)
24 // set when image is uploaded and freed
25 #define GLTEXF_DESTROYED 0x00040000
26
27 typedef struct textypeinfo_s
28 {
29         int textype;
30         int inputbytesperpixel;
31         int internalbytesperpixel;
32         int glformat;
33         int glinternalformat;
34 }
35 textypeinfo_t;
36
37 static textypeinfo_t textype_palette       = {TEXTYPE_PALETTE, 1, 4, GL_RGBA   , 3};
38 static textypeinfo_t textype_rgb           = {TEXTYPE_RGB    , 3, 3, GL_RGB    , 3};
39 static textypeinfo_t textype_rgba          = {TEXTYPE_RGBA   , 4, 4, GL_RGBA   , 3};
40 static textypeinfo_t textype_palette_alpha = {TEXTYPE_PALETTE, 1, 4, GL_RGBA   , 4};
41 static textypeinfo_t textype_rgba_alpha    = {TEXTYPE_RGBA   , 4, 4, GL_RGBA   , 4};
42
43 #define GLTEXTURETYPE_1D 0
44 #define GLTEXTURETYPE_2D 1
45 #define GLTEXTURETYPE_3D 2
46 #define GLTEXTURETYPE_CUBEMAP 3
47
48 static int gltexturetypeenums[4] = {GL_TEXTURE_1D, GL_TEXTURE_2D, GL_TEXTURE_3D, GL_TEXTURE_CUBE_MAP_ARB};
49 static int gltexturetypebindingenums[4] = {GL_TEXTURE_BINDING_1D, GL_TEXTURE_BINDING_2D, GL_TEXTURE_BINDING_3D, GL_TEXTURE_BINDING_CUBE_MAP_ARB};
50 static int gltexturetypedimensions[4] = {1, 2, 3, 2};
51 static int cubemapside[6] =
52 {
53         GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
54         GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB,
55         GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB,
56         GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB,
57         GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB,
58         GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB
59 };
60
61 typedef struct gltexture_s
62 {
63         // this field is exposed to the R_GetTexture macro, for speed reasons
64         // (must be identical in rtexture_t)
65         int texnum; // GL texture slot number
66
67         // pointer to texturepool (check this to see if the texture is allocated)
68         struct gltexturepool_s *pool;
69         // pointer to next texture in texturepool chain
70         struct gltexture_s *chain;
71         // name of the texture (this might be removed someday), no duplicates
72         char identifier[32];
73         // original data size in *inputtexels
74         int inputwidth, inputheight, inputdepth;
75         // copy of the original texture(s) supplied to the upload function, for
76         // delayed uploads (non-precached)
77         unsigned char *inputtexels;
78         // original data size in *inputtexels
79         int inputdatasize;
80         // flags supplied to the LoadTexture function
81         // (might be altered to remove TEXF_ALPHA), and GLTEXF_ private flags
82         int flags;
83         // pointer to one of the textype_ structs
84         textypeinfo_t *textype;
85         // one of the GLTEXTURETYPE_ values
86         int texturetype;
87         // palette if the texture is TEXTYPE_PALETTE
88         const unsigned int *palette;
89         // power of 2 size, after gl_picmip and gl_max_size are applied
90         int tilewidth, tileheight, tiledepth;
91         // 1 or 6 depending on texturetype
92         int sides;
93         // bytes per pixel
94         int bytesperpixel;
95         // GL_RGB or GL_RGBA
96         int glformat;
97         // 3 or 4
98         int glinternalformat;
99 }
100 gltexture_t;
101
102 #define TEXTUREPOOL_SENTINEL 0xC0DEDBAD
103
104 typedef struct gltexturepool_s
105 {
106         unsigned int sentinel;
107         struct gltexture_s *gltchain;
108         struct gltexturepool_s *next;
109 }
110 gltexturepool_t;
111
112 static gltexturepool_t *gltexturepoolchain = NULL;
113
114 static unsigned char *resizebuffer = NULL, *colorconvertbuffer;
115 static int resizebuffersize = 0;
116 static unsigned char *texturebuffer;
117 static int texturebuffersize = 0;
118
119 static textypeinfo_t *R_GetTexTypeInfo(int textype, int flags)
120 {
121         if (flags & TEXF_ALPHA)
122         {
123                 switch(textype)
124                 {
125                 case TEXTYPE_PALETTE:
126                         return &textype_palette_alpha;
127                 case TEXTYPE_RGB:
128                         Host_Error("R_GetTexTypeInfo: RGB format has no alpha, TEXF_ALPHA not allowed");
129                         return NULL;
130                 case TEXTYPE_RGBA:
131                         return &textype_rgba_alpha;
132                 default:
133                         Host_Error("R_GetTexTypeInfo: unknown texture format");
134                         return NULL;
135                 }
136         }
137         else
138         {
139                 switch(textype)
140                 {
141                 case TEXTYPE_PALETTE:
142                         return &textype_palette;
143                 case TEXTYPE_RGB:
144                         return &textype_rgb;
145                 case TEXTYPE_RGBA:
146                         return &textype_rgba;
147                 default:
148                         Host_Error("R_GetTexTypeInfo: unknown texture format");
149                         return NULL;
150                 }
151         }
152 }
153
154 static void R_UploadTexture(gltexture_t *t);
155
156 static void R_PrecacheTexture(gltexture_t *glt)
157 {
158         int precache;
159         precache = false;
160         if (glt->flags & TEXF_ALWAYSPRECACHE)
161                 precache = true;
162         else if (r_precachetextures.integer >= 2)
163                 precache = true;
164         else if (r_precachetextures.integer >= 1)
165                 if (glt->flags & TEXF_PRECACHE)
166                         precache = true;
167
168         if (precache)
169                 R_UploadTexture(glt);
170 }
171
172 int R_RealGetTexture(rtexture_t *rt)
173 {
174         if (rt)
175         {
176                 gltexture_t *glt;
177                 glt = (gltexture_t *)rt;
178                 if (glt->flags & GLTEXF_UPLOAD)
179                         R_UploadTexture(glt);
180                 return glt->texnum;
181         }
182         else
183                 return 0;
184 }
185
186 void R_FreeTexture(rtexture_t *rt)
187 {
188         gltexture_t *glt, **gltpointer;
189
190         glt = (gltexture_t *)rt;
191         if (glt == NULL)
192                 Host_Error("R_FreeTexture: texture == NULL");
193
194         for (gltpointer = &glt->pool->gltchain;*gltpointer && *gltpointer != glt;gltpointer = &(*gltpointer)->chain);
195         if (*gltpointer == glt)
196                 *gltpointer = glt->chain;
197         else
198                 Host_Error("R_FreeTexture: texture \"%s\" not linked in pool", glt->identifier);
199
200         if (glt->texnum)
201         {
202                 CHECKGLERROR
203                 qglDeleteTextures(1, (GLuint *)&glt->texnum);CHECKGLERROR
204         }
205
206         if (glt->inputtexels)
207                 Mem_Free(glt->inputtexels);
208         Mem_Free(glt);
209 }
210
211 rtexturepool_t *R_AllocTexturePool(void)
212 {
213         gltexturepool_t *pool;
214         if (texturemempool == NULL)
215                 return NULL;
216         pool = (gltexturepool_t *)Mem_Alloc(texturemempool, sizeof(gltexturepool_t));
217         if (pool == NULL)
218                 return NULL;
219         pool->next = gltexturepoolchain;
220         gltexturepoolchain = pool;
221         pool->sentinel = TEXTUREPOOL_SENTINEL;
222         return (rtexturepool_t *)pool;
223 }
224
225 void R_FreeTexturePool(rtexturepool_t **rtexturepool)
226 {
227         gltexturepool_t *pool, **poolpointer;
228         if (rtexturepool == NULL)
229                 return;
230         if (*rtexturepool == NULL)
231                 return;
232         pool = (gltexturepool_t *)(*rtexturepool);
233         *rtexturepool = NULL;
234         if (pool->sentinel != TEXTUREPOOL_SENTINEL)
235                 Host_Error("R_FreeTexturePool: pool already freed");
236         for (poolpointer = &gltexturepoolchain;*poolpointer && *poolpointer != pool;poolpointer = &(*poolpointer)->next);
237         if (*poolpointer == pool)
238                 *poolpointer = pool->next;
239         else
240                 Host_Error("R_FreeTexturePool: pool not linked");
241         while (pool->gltchain)
242                 R_FreeTexture((rtexture_t *)pool->gltchain);
243         Mem_Free(pool);
244 }
245
246
247 typedef struct glmode_s
248 {
249         char *name;
250         int minification, magnification;
251 }
252 glmode_t;
253
254 static glmode_t modes[6] =
255 {
256         {"GL_NEAREST", GL_NEAREST, GL_NEAREST},
257         {"GL_LINEAR", GL_LINEAR, GL_LINEAR},
258         {"GL_NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST},
259         {"GL_LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR},
260         {"GL_NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST},
261         {"GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR}
262 };
263
264 static void GL_TextureMode_f (void)
265 {
266         int i;
267         GLint oldbindtexnum;
268         gltexture_t *glt;
269         gltexturepool_t *pool;
270
271         if (Cmd_Argc() == 1)
272         {
273                 for (i = 0;i < 6;i++)
274                 {
275                         if (gl_filter_min == modes[i].minification)
276                         {
277                                 Con_Printf("%s\n", modes[i].name);
278                                 return;
279                         }
280                 }
281                 Con_Print("current filter is unknown???\n");
282                 return;
283         }
284
285         for (i = 0;i < 6;i++)
286                 if (!strcasecmp (modes[i].name, Cmd_Argv(1) ) )
287                         break;
288         if (i == 6)
289         {
290                 Con_Print("bad filter name\n");
291                 return;
292         }
293
294         gl_filter_min = modes[i].minification;
295         gl_filter_mag = modes[i].magnification;
296
297         // change all the existing mipmap texture objects
298         // FIXME: force renderer(/client/something?) restart instead?
299         CHECKGLERROR
300         for (pool = gltexturepoolchain;pool;pool = pool->next)
301         {
302                 for (glt = pool->gltchain;glt;glt = glt->chain)
303                 {
304                         // only update already uploaded images
305                         if (!(glt->flags & (GLTEXF_UPLOAD | TEXF_FORCENEAREST | TEXF_FORCELINEAR)))
306                         {
307                                 qglGetIntegerv(gltexturetypebindingenums[glt->texturetype], &oldbindtexnum);CHECKGLERROR
308                                 qglBindTexture(gltexturetypeenums[glt->texturetype], glt->texnum);CHECKGLERROR
309                                 if (glt->flags & TEXF_MIPMAP)
310                                 {
311                                         qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MIN_FILTER, gl_filter_min);CHECKGLERROR
312                                 }
313                                 else
314                                 {
315                                         qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MIN_FILTER, gl_filter_mag);CHECKGLERROR
316                                 }
317                                 qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MAG_FILTER, gl_filter_mag);CHECKGLERROR
318                                 qglBindTexture(gltexturetypeenums[glt->texturetype], oldbindtexnum);CHECKGLERROR
319                         }
320                 }
321         }
322 }
323
324 static void GL_Texture_CalcImageSize(int texturetype, int flags, int inwidth, int inheight, int indepth, int *outwidth, int *outheight, int *outdepth)
325 {
326         int picmip = 0, maxsize = 0, width2 = 1, height2 = 1, depth2 = 1;
327
328         if (gl_max_size.integer > gl_max_texture_size)
329                 Cvar_SetValue("gl_max_size", gl_max_texture_size);
330
331         switch (texturetype)
332         {
333         default:
334         case GLTEXTURETYPE_1D:
335         case GLTEXTURETYPE_2D:
336                 maxsize = gl_max_texture_size;
337                 break;
338         case GLTEXTURETYPE_3D:
339                 maxsize = gl_max_3d_texture_size;
340                 break;
341         case GLTEXTURETYPE_CUBEMAP:
342                 maxsize = gl_max_cube_map_texture_size;
343                 break;
344         }
345
346         if (flags & TEXF_PICMIP)
347         {
348                 maxsize = min(maxsize, gl_max_size.integer);
349                 picmip = gl_picmip.integer;
350         }
351
352         if (outwidth)
353         {
354                 for (width2 = 1;width2 < inwidth;width2 <<= 1);
355                 for (width2 >>= picmip;width2 > maxsize;width2 >>= 1);
356                 *outwidth = max(1, width2);
357         }
358         if (outheight)
359         {
360                 for (height2 = 1;height2 < inheight;height2 <<= 1);
361                 for (height2 >>= picmip;height2 > maxsize;height2 >>= 1);
362                 *outheight = max(1, height2);
363         }
364         if (outdepth)
365         {
366                 for (depth2 = 1;depth2 < indepth;depth2 <<= 1);
367                 for (depth2 >>= picmip;depth2 > maxsize;depth2 >>= 1);
368                 *outdepth = max(1, depth2);
369         }
370 }
371
372
373 static int R_CalcTexelDataSize (gltexture_t *glt)
374 {
375         int width2, height2, depth2, size;
376
377         GL_Texture_CalcImageSize(glt->texturetype, glt->flags, glt->inputwidth, glt->inputheight, glt->inputdepth, &width2, &height2, &depth2);
378
379         size = width2 * height2 * depth2;
380
381         if (glt->flags & TEXF_MIPMAP)
382         {
383                 while (width2 > 1 || height2 > 1 || depth2 > 1)
384                 {
385                         if (width2 > 1)
386                                 width2 >>= 1;
387                         if (height2 > 1)
388                                 height2 >>= 1;
389                         if (depth2 > 1)
390                                 depth2 >>= 1;
391                         size += width2 * height2 * depth2;
392                 }
393         }
394
395         return size * glt->textype->internalbytesperpixel * glt->sides;
396 }
397
398 void R_TextureStats_Print(qboolean printeach, qboolean printpool, qboolean printtotal)
399 {
400         int glsize;
401         int isloaded;
402         int pooltotal = 0, pooltotalt = 0, pooltotalp = 0, poolloaded = 0, poolloadedt = 0, poolloadedp = 0;
403         int sumtotal = 0, sumtotalt = 0, sumtotalp = 0, sumloaded = 0, sumloadedt = 0, sumloadedp = 0;
404         gltexture_t *glt;
405         gltexturepool_t *pool;
406         if (printeach)
407                 Con_Print("glsize input loaded mip alpha name\n");
408         for (pool = gltexturepoolchain;pool;pool = pool->next)
409         {
410                 pooltotal = 0;
411                 pooltotalt = 0;
412                 pooltotalp = 0;
413                 poolloaded = 0;
414                 poolloadedt = 0;
415                 poolloadedp = 0;
416                 for (glt = pool->gltchain;glt;glt = glt->chain)
417                 {
418                         glsize = R_CalcTexelDataSize(glt);
419                         isloaded = !(glt->flags & GLTEXF_UPLOAD);
420                         pooltotal++;
421                         pooltotalt += glsize;
422                         pooltotalp += glt->inputdatasize;
423                         if (isloaded)
424                         {
425                                 poolloaded++;
426                                 poolloadedt += glsize;
427                                 poolloadedp += glt->inputdatasize;
428                         }
429                         if (printeach)
430                                 Con_Printf("%c%4i%c%c%4i%c %s %s %s %s\n", isloaded ? '[' : ' ', (glsize + 1023) / 1024, isloaded ? ']' : ' ', glt->inputtexels ? '[' : ' ', (glt->inputdatasize + 1023) / 1024, glt->inputtexels ? ']' : ' ', isloaded ? "loaded" : "      ", (glt->flags & TEXF_MIPMAP) ? "mip" : "   ", (glt->flags & TEXF_ALPHA) ? "alpha" : "     ", glt->identifier);
431                 }
432                 if (printpool)
433                         Con_Printf("texturepool %10p total: %i (%.3fMB, %.3fMB original), uploaded %i (%.3fMB, %.3fMB original), upload on demand %i (%.3fMB, %.3fMB original)\n", pool, pooltotal, pooltotalt / 1048576.0, pooltotalp / 1048576.0, poolloaded, poolloadedt / 1048576.0, poolloadedp / 1048576.0, pooltotal - poolloaded, (pooltotalt - poolloadedt) / 1048576.0, (pooltotalp - poolloadedp) / 1048576.0);
434                 sumtotal += pooltotal;
435                 sumtotalt += pooltotalt;
436                 sumtotalp += pooltotalp;
437                 sumloaded += poolloaded;
438                 sumloadedt += poolloadedt;
439                 sumloadedp += poolloadedp;
440         }
441         if (printtotal)
442                 Con_Printf("textures total: %i (%.3fMB, %.3fMB original), uploaded %i (%.3fMB, %.3fMB original), upload on demand %i (%.3fMB, %.3fMB original)\n", sumtotal, sumtotalt / 1048576.0, sumtotalp / 1048576.0, sumloaded, sumloadedt / 1048576.0, sumloadedp / 1048576.0, sumtotal - sumloaded, (sumtotalt - sumloadedt) / 1048576.0, (sumtotalp - sumloadedp) / 1048576.0);
443 }
444
445 static void R_TextureStats_f(void)
446 {
447         R_TextureStats_Print(true, true, true);
448 }
449
450 static void r_textures_start(void)
451 {
452         // LordHavoc: allow any alignment
453         CHECKGLERROR
454         qglPixelStorei(GL_UNPACK_ALIGNMENT, 1);CHECKGLERROR
455
456         texturemempool = Mem_AllocPool("texture management", 0, NULL);
457
458         // Disable JPEG screenshots if the DLL isn't loaded
459         if (! JPEG_OpenLibrary ())
460                 Cvar_SetValueQuick (&scr_screenshot_jpeg, 0);
461         // TODO: support png screenshots?
462         PNG_OpenLibrary ();
463 }
464
465 static void r_textures_shutdown(void)
466 {
467         rtexturepool_t *temp;
468
469         JPEG_CloseLibrary ();
470
471         while(gltexturepoolchain)
472         {
473                 temp = (rtexturepool_t *) gltexturepoolchain;
474                 R_FreeTexturePool(&temp);
475         }
476
477         resizebuffersize = 0;
478         texturebuffersize = 0;
479         resizebuffer = NULL;
480         colorconvertbuffer = NULL;
481         texturebuffer = NULL;
482         Mem_FreePool(&texturemempool);
483 }
484
485 static void r_textures_newmap(void)
486 {
487 }
488
489 void R_Textures_Init (void)
490 {
491         Cmd_AddCommand("gl_texturemode", &GL_TextureMode_f, "set texture filtering mode (GL_NEAREST, GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, etc)");
492         Cmd_AddCommand("r_texturestats", R_TextureStats_f, "print information about all loaded textures and some statistics");
493         Cvar_RegisterVariable (&gl_max_size);
494         Cvar_RegisterVariable (&gl_picmip);
495         Cvar_RegisterVariable (&r_lerpimages);
496         Cvar_RegisterVariable (&r_precachetextures);
497         Cvar_RegisterVariable (&gl_texture_anisotropy);
498
499         R_RegisterModule("R_Textures", r_textures_start, r_textures_shutdown, r_textures_newmap);
500 }
501
502 void R_Textures_Frame (void)
503 {
504         static int old_aniso = 0;
505
506         // could do procedural texture animation here, if we keep track of which
507         // textures were accessed this frame...
508
509         // free the resize buffers
510         resizebuffersize = 0;
511         if (resizebuffer)
512         {
513                 Mem_Free(resizebuffer);
514                 resizebuffer = NULL;
515         }
516         if (colorconvertbuffer)
517         {
518                 Mem_Free(colorconvertbuffer);
519                 colorconvertbuffer = NULL;
520         }
521
522         if (old_aniso != gl_texture_anisotropy.integer)
523         {
524                 gltexture_t *glt;
525                 gltexturepool_t *pool;
526                 GLint oldbindtexnum;
527
528                 old_aniso = bound(1, gl_texture_anisotropy.integer, gl_max_anisotropy);
529
530                 Cvar_SetValueQuick(&gl_texture_anisotropy, old_aniso);
531
532                 CHECKGLERROR
533                 for (pool = gltexturepoolchain;pool;pool = pool->next)
534                 {
535                         for (glt = pool->gltchain;glt;glt = glt->chain)
536                         {
537                                 // only update already uploaded images
538                                 if ((glt->flags & (GLTEXF_UPLOAD | TEXF_MIPMAP)) == TEXF_MIPMAP)
539                                 {
540                                         qglGetIntegerv(gltexturetypebindingenums[glt->texturetype], &oldbindtexnum);CHECKGLERROR
541
542                                         qglBindTexture(gltexturetypeenums[glt->texturetype], glt->texnum);CHECKGLERROR
543                                         qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MAX_ANISOTROPY_EXT, old_aniso);CHECKGLERROR
544
545                                         qglBindTexture(gltexturetypeenums[glt->texturetype], oldbindtexnum);CHECKGLERROR
546                                 }
547                         }
548                 }
549         }
550 }
551
552 void R_MakeResizeBufferBigger(int size)
553 {
554         if (resizebuffersize < size)
555         {
556                 resizebuffersize = size;
557                 if (resizebuffer)
558                         Mem_Free(resizebuffer);
559                 if (colorconvertbuffer)
560                         Mem_Free(colorconvertbuffer);
561                 resizebuffer = (unsigned char *)Mem_Alloc(texturemempool, resizebuffersize);
562                 colorconvertbuffer = (unsigned char *)Mem_Alloc(texturemempool, resizebuffersize);
563                 if (!resizebuffer || !colorconvertbuffer)
564                         Host_Error("R_Upload: out of memory");
565         }
566 }
567
568 static void GL_SetupTextureParameters(int flags, int texturetype)
569 {
570         int textureenum = gltexturetypeenums[texturetype];
571         int wrapmode = ((flags & TEXF_CLAMP) && gl_support_clamptoedge) ? GL_CLAMP_TO_EDGE : GL_REPEAT;
572
573         CHECKGLERROR
574
575         if (gl_support_anisotropy && (flags & TEXF_MIPMAP))
576         {
577                 int aniso = bound(1, gl_texture_anisotropy.integer, gl_max_anisotropy);
578                 if (gl_texture_anisotropy.integer != aniso)
579                         Cvar_SetValueQuick(&gl_texture_anisotropy, aniso);
580                 qglTexParameteri(textureenum, GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso);CHECKGLERROR
581         }
582         qglTexParameteri(textureenum, GL_TEXTURE_WRAP_S, wrapmode);CHECKGLERROR
583         qglTexParameteri(textureenum, GL_TEXTURE_WRAP_T, wrapmode);CHECKGLERROR
584         if (gltexturetypedimensions[texturetype] >= 3)
585         {
586                 qglTexParameteri(textureenum, GL_TEXTURE_WRAP_R, wrapmode);CHECKGLERROR
587         }
588
589         CHECKGLERROR
590         if (flags & TEXF_FORCENEAREST)
591         {
592                 if (flags & TEXF_MIPMAP)
593                 {
594                         qglTexParameteri(textureenum, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);CHECKGLERROR
595                 }
596                 else
597                 {
598                         qglTexParameteri(textureenum, GL_TEXTURE_MIN_FILTER, GL_NEAREST);CHECKGLERROR
599                 }
600                 qglTexParameteri(textureenum, GL_TEXTURE_MAG_FILTER, GL_NEAREST);CHECKGLERROR
601         }
602         else if (flags & TEXF_FORCELINEAR)
603         {
604                 if (flags & TEXF_MIPMAP)
605                 {
606                         if (gl_filter_min == GL_NEAREST_MIPMAP_LINEAR || gl_filter_min == GL_LINEAR_MIPMAP_LINEAR)
607                         {
608                                 qglTexParameteri(textureenum, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);CHECKGLERROR
609                         }
610                         else
611                         {
612                                 qglTexParameteri(textureenum, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);CHECKGLERROR
613                         }
614                 }
615                 else
616                 {
617                         qglTexParameteri(textureenum, GL_TEXTURE_MIN_FILTER, GL_LINEAR);CHECKGLERROR
618                 }
619                 qglTexParameteri(textureenum, GL_TEXTURE_MAG_FILTER, GL_LINEAR);CHECKGLERROR
620         }
621         else
622         {
623                 if (flags & TEXF_MIPMAP)
624                 {
625                         qglTexParameteri(textureenum, GL_TEXTURE_MIN_FILTER, gl_filter_min);CHECKGLERROR
626                 }
627                 else
628                 {
629                         qglTexParameteri(textureenum, GL_TEXTURE_MIN_FILTER, gl_filter_mag);CHECKGLERROR
630                 }
631                 qglTexParameteri(textureenum, GL_TEXTURE_MAG_FILTER, gl_filter_mag);CHECKGLERROR
632         }
633
634         CHECKGLERROR
635 }
636
637 static void R_Upload(gltexture_t *glt, unsigned char *data, int fragx, int fragy, int fragz, int fragwidth, int fragheight, int fragdepth)
638 {
639         int i, mip, width, height, depth;
640         GLint oldbindtexnum;
641         unsigned char *prevbuffer;
642         prevbuffer = data;
643
644         CHECKGLERROR
645
646         // we need to restore the texture binding after finishing the upload
647         qglGetIntegerv(gltexturetypebindingenums[glt->texturetype], &oldbindtexnum);CHECKGLERROR
648         qglBindTexture(gltexturetypeenums[glt->texturetype], glt->texnum);CHECKGLERROR
649
650         // these are rounded up versions of the size to do better resampling
651         for (width  = 1;width  < glt->inputwidth ;width  <<= 1);
652         for (height = 1;height < glt->inputheight;height <<= 1);
653         for (depth  = 1;depth  < glt->inputdepth ;depth  <<= 1);
654
655         R_MakeResizeBufferBigger(width * height * depth * glt->sides * glt->bytesperpixel);
656         R_MakeResizeBufferBigger(fragwidth * fragheight * fragdepth * glt->sides * glt->bytesperpixel);
657
658         if (prevbuffer == NULL)
659         {
660                 memset(resizebuffer, 0, fragwidth * fragheight * fragdepth * glt->bytesperpixel);
661                 prevbuffer = resizebuffer;
662         }
663         else if (glt->textype->textype == TEXTYPE_PALETTE)
664         {
665                 // promote paletted to RGBA, so we only have to worry about RGB and
666                 // RGBA in the rest of this code
667                 Image_Copy8bitRGBA(prevbuffer, colorconvertbuffer, fragwidth * fragheight * fragdepth * glt->sides, glt->palette);
668                 prevbuffer = colorconvertbuffer;
669         }
670
671         if ((glt->flags & (TEXF_MIPMAP | TEXF_PICMIP | GLTEXF_UPLOAD)) == 0 && glt->inputwidth == glt->tilewidth && glt->inputheight == glt->tileheight && glt->inputdepth == glt->tiledepth)
672         {
673                 // update a portion of the image
674                 switch(glt->texturetype)
675                 {
676                 case GLTEXTURETYPE_1D:
677                         qglTexSubImage1D(GL_TEXTURE_1D, 0, fragx, fragwidth, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
678                         break;
679                 case GLTEXTURETYPE_2D:
680                         qglTexSubImage2D(GL_TEXTURE_2D, 0, fragx, fragy, fragwidth, fragheight, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
681                         break;
682                 case GLTEXTURETYPE_3D:
683                         qglTexSubImage3D(GL_TEXTURE_3D, 0, fragx, fragy, fragz, fragwidth, fragheight, fragdepth, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
684                         break;
685                 default:
686                         Host_Error("R_Upload: partial update of type other than 1D, 2D, or 3D");
687                         break;
688                 }
689         }
690         else
691         {
692                 if (fragx || fragy || fragz || glt->inputwidth != fragwidth || glt->inputheight != fragheight || glt->inputdepth != fragdepth)
693                         Host_Error("R_Upload: partial update not allowed on initial upload or in combination with PICMIP or MIPMAP\n");
694
695                 // upload the image for the first time
696                 glt->flags &= ~GLTEXF_UPLOAD;
697
698                 // cubemaps contain multiple images and thus get processed a bit differently
699                 if (glt->texturetype != GLTEXTURETYPE_CUBEMAP)
700                 {
701                         if (glt->inputwidth != width || glt->inputheight != height || glt->inputdepth != depth)
702                         {
703                                 Image_Resample(prevbuffer, glt->inputwidth, glt->inputheight, glt->inputdepth, resizebuffer, width, height, depth, glt->bytesperpixel, r_lerpimages.integer);
704                                 prevbuffer = resizebuffer;
705                         }
706                         // picmip/max_size
707                         while (width > glt->tilewidth || height > glt->tileheight || depth > glt->tiledepth)
708                         {
709                                 Image_MipReduce(prevbuffer, resizebuffer, &width, &height, &depth, glt->tilewidth, glt->tileheight, glt->tiledepth, glt->bytesperpixel);
710                                 prevbuffer = resizebuffer;
711                         }
712                 }
713                 mip = 0;
714                 switch(glt->texturetype)
715                 {
716                 case GLTEXTURETYPE_1D:
717                         qglTexImage1D(GL_TEXTURE_1D, mip++, glt->glinternalformat, width, 0, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
718                         if (glt->flags & TEXF_MIPMAP)
719                         {
720                                 while (width > 1 || height > 1 || depth > 1)
721                                 {
722                                         Image_MipReduce(prevbuffer, resizebuffer, &width, &height, &depth, 1, 1, 1, glt->bytesperpixel);
723                                         prevbuffer = resizebuffer;
724                                         qglTexImage1D(GL_TEXTURE_1D, mip++, glt->glinternalformat, width, 0, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
725                                 }
726                         }
727                         break;
728                 case GLTEXTURETYPE_2D:
729                         qglTexImage2D(GL_TEXTURE_2D, mip++, glt->glinternalformat, width, height, 0, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
730                         if (glt->flags & TEXF_MIPMAP)
731                         {
732                                 while (width > 1 || height > 1 || depth > 1)
733                                 {
734                                         Image_MipReduce(prevbuffer, resizebuffer, &width, &height, &depth, 1, 1, 1, glt->bytesperpixel);
735                                         prevbuffer = resizebuffer;
736                                         qglTexImage2D(GL_TEXTURE_2D, mip++, glt->glinternalformat, width, height, 0, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
737                                 }
738                         }
739                         break;
740                 case GLTEXTURETYPE_3D:
741                         qglTexImage3D(GL_TEXTURE_3D, mip++, glt->glinternalformat, width, height, depth, 0, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
742                         if (glt->flags & TEXF_MIPMAP)
743                         {
744                                 while (width > 1 || height > 1 || depth > 1)
745                                 {
746                                         Image_MipReduce(prevbuffer, resizebuffer, &width, &height, &depth, 1, 1, 1, glt->bytesperpixel);
747                                         prevbuffer = resizebuffer;
748                                         qglTexImage3D(GL_TEXTURE_3D, mip++, glt->glinternalformat, width, height, depth, 0, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
749                                 }
750                         }
751                         break;
752                 case GLTEXTURETYPE_CUBEMAP:
753                         // convert and upload each side in turn,
754                         // from a continuous block of input texels
755                         texturebuffer = prevbuffer;
756                         for (i = 0;i < 6;i++)
757                         {
758                                 prevbuffer = texturebuffer;
759                                 texturebuffer += glt->inputwidth * glt->inputheight * glt->inputdepth * glt->textype->inputbytesperpixel;
760                                 if (glt->inputwidth != width || glt->inputheight != height || glt->inputdepth != depth)
761                                 {
762                                         Image_Resample(prevbuffer, glt->inputwidth, glt->inputheight, glt->inputdepth, resizebuffer, width, height, depth, glt->bytesperpixel, r_lerpimages.integer);
763                                         prevbuffer = resizebuffer;
764                                 }
765                                 // picmip/max_size
766                                 while (width > glt->tilewidth || height > glt->tileheight || depth > glt->tiledepth)
767                                 {
768                                         Image_MipReduce(prevbuffer, resizebuffer, &width, &height, &depth, glt->tilewidth, glt->tileheight, glt->tiledepth, glt->bytesperpixel);
769                                         prevbuffer = resizebuffer;
770                                 }
771                                 mip = 0;
772                                 qglTexImage2D(cubemapside[i], mip++, glt->glinternalformat, width, height, 0, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
773                                 if (glt->flags & TEXF_MIPMAP)
774                                 {
775                                         while (width > 1 || height > 1 || depth > 1)
776                                         {
777                                                 Image_MipReduce(prevbuffer, resizebuffer, &width, &height, &depth, 1, 1, 1, glt->bytesperpixel);
778                                                 prevbuffer = resizebuffer;
779                                                 qglTexImage2D(cubemapside[i], mip++, glt->glinternalformat, width, height, 0, glt->glformat, GL_UNSIGNED_BYTE, prevbuffer);CHECKGLERROR
780                                         }
781                                 }
782                         }
783                         break;
784                 }
785                 GL_SetupTextureParameters(glt->flags, glt->texturetype);
786         }
787         qglBindTexture(gltexturetypeenums[glt->texturetype], oldbindtexnum);CHECKGLERROR
788 }
789
790 static void R_UploadTexture (gltexture_t *glt)
791 {
792         if (!(glt->flags & GLTEXF_UPLOAD))
793                 return;
794
795         CHECKGLERROR
796         qglGenTextures(1, (GLuint *)&glt->texnum);CHECKGLERROR
797         R_Upload(glt, glt->inputtexels, 0, 0, 0, glt->inputwidth, glt->inputheight, glt->inputdepth);
798         if (glt->inputtexels)
799         {
800                 Mem_Free(glt->inputtexels);
801                 glt->inputtexels = NULL;
802                 glt->flags |= GLTEXF_DESTROYED;
803         }
804         else if (glt->flags & GLTEXF_DESTROYED)
805                 Con_Printf("R_UploadTexture: Texture %s already uploaded and destroyed.  Can not upload original image again.  Uploaded blank texture.\n", glt->identifier);
806 }
807
808 static rtexture_t *R_SetupTexture(rtexturepool_t *rtexturepool, const char *identifier, int width, int height, int depth, int sides, int flags, int textype, int texturetype, const unsigned char *data, const unsigned int *palette)
809 {
810         int i, size;
811         gltexture_t *glt;
812         gltexturepool_t *pool = (gltexturepool_t *)rtexturepool;
813         textypeinfo_t *texinfo;
814
815         if (cls.state == ca_dedicated)
816                 return NULL;
817
818         if (texturetype == GLTEXTURETYPE_CUBEMAP && !gl_texturecubemap)
819         {
820                 Con_Printf ("R_LoadTexture: cubemap texture not supported by driver\n");
821                 return NULL;
822         }
823         if (texturetype == GLTEXTURETYPE_3D && !gl_texture3d)
824         {
825                 Con_Printf ("R_LoadTexture: 3d texture not supported by driver\n");
826                 return NULL;
827         }
828
829         texinfo = R_GetTexTypeInfo(textype, flags);
830         size = width * height * depth * sides * texinfo->inputbytesperpixel;
831         if (size < 1)
832         {
833                 Con_Printf ("R_LoadTexture: bogus texture size (%dx%dx%dx%dbppx%dsides = %d bytes)\n", width, height, depth, texinfo->inputbytesperpixel * 8, sides);
834                 return NULL;
835         }
836
837         // clear the alpha flag if the texture has no transparent pixels
838         switch(textype)
839         {
840         case TEXTYPE_PALETTE:
841                 if (flags & TEXF_ALPHA)
842                 {
843                         flags &= ~TEXF_ALPHA;
844                         if (data)
845                         {
846                                 for (i = 0;i < size;i++)
847                                 {
848                                         if (((unsigned char *)&palette[data[i]])[3] < 255)
849                                         {
850                                                 flags |= TEXF_ALPHA;
851                                                 break;
852                                         }
853                                 }
854                         }
855                 }
856                 break;
857         case TEXTYPE_RGB:
858                 if (flags & TEXF_ALPHA)
859                         Host_Error("R_LoadTexture: RGB has no alpha, don't specify TEXF_ALPHA");
860                 break;
861         case TEXTYPE_RGBA:
862                 if (flags & TEXF_ALPHA)
863                 {
864                         flags &= ~TEXF_ALPHA;
865                         if (data)
866                         {
867                                 for (i = 3;i < size;i += 4)
868                                 {
869                                         if (data[i] < 255)
870                                         {
871                                                 flags |= TEXF_ALPHA;
872                                                 break;
873                                         }
874                                 }
875                         }
876                 }
877                 break;
878         default:
879                 Host_Error("R_LoadTexture: unknown texture type");
880         }
881
882         glt = (gltexture_t *)Mem_Alloc(texturemempool, sizeof(gltexture_t));
883         if (identifier)
884                 strlcpy (glt->identifier, identifier, sizeof(glt->identifier));
885         glt->pool = pool;
886         glt->chain = pool->gltchain;
887         pool->gltchain = glt;
888         glt->inputwidth = width;
889         glt->inputheight = height;
890         glt->inputdepth = depth;
891         glt->flags = flags | GLTEXF_UPLOAD;
892         glt->textype = texinfo;
893         glt->texturetype = texturetype;
894         glt->inputdatasize = size;
895         glt->palette = palette;
896         glt->glinternalformat = texinfo->glinternalformat;
897         glt->glformat = texinfo->glformat;
898         glt->bytesperpixel = texinfo->internalbytesperpixel;
899         glt->sides = glt->texturetype == GLTEXTURETYPE_CUBEMAP ? 6 : 1;
900         glt->texnum = -1;
901
902         if (data)
903         {
904                 glt->inputtexels = (unsigned char *)Mem_Alloc(texturemempool, size);
905                 memcpy(glt->inputtexels, data, size);
906         }
907         else
908                 glt->inputtexels = NULL;
909
910         GL_Texture_CalcImageSize(glt->texturetype, glt->flags, glt->inputwidth, glt->inputheight, glt->inputdepth, &glt->tilewidth, &glt->tileheight, &glt->tiledepth);
911         R_PrecacheTexture(glt);
912
913         return (rtexture_t *)glt;
914 }
915
916 rtexture_t *R_LoadTexture1D(rtexturepool_t *rtexturepool, const char *identifier, int width, const unsigned char *data, int textype, int flags, const unsigned int *palette)
917 {
918         return R_SetupTexture(rtexturepool, identifier, width, 1, 1, 1, flags, textype, GLTEXTURETYPE_1D, data, palette);
919 }
920
921 rtexture_t *R_LoadTexture2D(rtexturepool_t *rtexturepool, const char *identifier, int width, int height, const unsigned char *data, int textype, int flags, const unsigned int *palette)
922 {
923         return R_SetupTexture(rtexturepool, identifier, width, height, 1, 1, flags, textype, GLTEXTURETYPE_2D, data, palette);
924 }
925
926 rtexture_t *R_LoadTexture3D(rtexturepool_t *rtexturepool, const char *identifier, int width, int height, int depth, const unsigned char *data, int textype, int flags, const unsigned int *palette)
927 {
928         return R_SetupTexture(rtexturepool, identifier, width, height, depth, 1, flags, textype, GLTEXTURETYPE_3D, data, palette);
929 }
930
931 rtexture_t *R_LoadTextureCubeMap(rtexturepool_t *rtexturepool, const char *identifier, int width, const unsigned char *data, int textype, int flags, const unsigned int *palette)
932 {
933         return R_SetupTexture(rtexturepool, identifier, width, width, 1, 6, flags, textype, GLTEXTURETYPE_CUBEMAP, data, palette);
934 }
935
936 int R_TextureHasAlpha(rtexture_t *rt)
937 {
938         return rt ? (((gltexture_t *)rt)->flags & TEXF_ALPHA) != 0 : false;
939 }
940
941 int R_TextureWidth(rtexture_t *rt)
942 {
943         return rt ? ((gltexture_t *)rt)->inputwidth : 0;
944 }
945
946 int R_TextureHeight(rtexture_t *rt)
947 {
948         return rt ? ((gltexture_t *)rt)->inputheight : 0;
949 }
950
951 void R_UpdateTexture(rtexture_t *rt, unsigned char *data, int x, int y, int width, int height)
952 {
953         gltexture_t *glt;
954         if (rt == NULL)
955                 Host_Error("R_UpdateTexture: no texture supplied");
956         if (data == NULL)
957                 Host_Error("R_UpdateTexture: no data supplied");
958         glt = (gltexture_t *)rt;
959
960         // we need it to be uploaded before we can update a part of it
961         if (glt->flags & GLTEXF_UPLOAD)
962                 R_UploadTexture(glt);
963
964         // update part of the texture
965         R_Upload(glt, data, x, y, 0, width, height, 1);
966 }
967