e4dc975586631741c790c9fafc1c4b1fc5725ff3
[xonotic/darkplaces.git] / gl_backend.c
1
2 #include "quakedef.h"
3 #include "cl_collision.h"
4
5 cvar_t gl_mesh_drawrangeelements = {0, "gl_mesh_drawrangeelements", "1", "use glDrawRangeElements function if available instead of glDrawElements (for performance comparisons or bug testing)"};
6 cvar_t gl_mesh_testarrayelement = {0, "gl_mesh_testarrayelement", "0", "use glBegin(GL_TRIANGLES);glArrayElement();glEnd(); primitives instead of glDrawElements (useful to test for driver bugs with glDrawElements)"};
7 cvar_t gl_mesh_testmanualfeeding = {0, "gl_mesh_testmanualfeeding", "0", "use glBegin(GL_TRIANGLES);glTexCoord2f();glVertex3f();glEnd(); primitives instead of glDrawElements (useful to test for driver bugs with glDrawElements)"};
8 cvar_t gl_mesh_prefer_short_elements = {0, "gl_mesh_prefer_short_elements", "1", "use GL_UNSIGNED_SHORT element arrays instead of GL_UNSIGNED_INT"};
9 cvar_t gl_paranoid = {0, "gl_paranoid", "0", "enables OpenGL error checking and other tests"};
10 cvar_t gl_printcheckerror = {0, "gl_printcheckerror", "0", "prints all OpenGL error checks, useful to identify location of driver crashes"};
11
12 cvar_t r_render = {0, "r_render", "1", "enables rendering calls (you want this on!)"};
13 cvar_t r_waterwarp = {CVAR_SAVE, "r_waterwarp", "1", "warp view while underwater"};
14 cvar_t gl_polyblend = {CVAR_SAVE, "gl_polyblend", "1", "tints view while underwater, hurt, etc"};
15 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1", "enables OpenGL dithering (16bit looks bad with this off)"};
16 cvar_t gl_lockarrays = {0, "gl_lockarrays", "0", "enables use of glLockArraysEXT, may cause glitches with some broken drivers, and may be slower than normal"};
17 cvar_t gl_lockarrays_minimumvertices = {0, "gl_lockarrays_minimumvertices", "1", "minimum number of vertices required for use of glLockArraysEXT, setting this too low may reduce performance"};
18 cvar_t gl_vbo = {CVAR_SAVE, "gl_vbo", "3", "make use of GL_ARB_vertex_buffer_object extension to store static geometry in video memory for faster rendering, 0 disables VBO allocation or use, 1 enables VBOs for vertex and triangle data, 2 only for vertex data, 3 for vertex data and triangle data of simple meshes (ones with only one surface)"};
19 cvar_t gl_fbo = {CVAR_SAVE, "gl_fbo", "1", "make use of GL_ARB_framebuffer_object extension to enable shadowmaps and other features using pixel formats different from the framebuffer"};
20
21 cvar_t v_flipped = {0, "v_flipped", "0", "mirror the screen (poor man's left handed mode)"};
22 qboolean v_flipped_state = false;
23
24 int gl_maxdrawrangeelementsvertices;
25 int gl_maxdrawrangeelementsindices;
26
27 #ifdef DEBUGGL
28 int errornumber = 0;
29
30 void GL_PrintError(int errornumber, char *filename, int linenumber)
31 {
32         switch(errornumber)
33         {
34 #ifdef GL_INVALID_ENUM
35         case GL_INVALID_ENUM:
36                 Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
37                 break;
38 #endif
39 #ifdef GL_INVALID_VALUE
40         case GL_INVALID_VALUE:
41                 Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
42                 break;
43 #endif
44 #ifdef GL_INVALID_OPERATION
45         case GL_INVALID_OPERATION:
46                 Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
47                 break;
48 #endif
49 #ifdef GL_STACK_OVERFLOW
50         case GL_STACK_OVERFLOW:
51                 Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
52                 break;
53 #endif
54 #ifdef GL_STACK_UNDERFLOW
55         case GL_STACK_UNDERFLOW:
56                 Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
57                 break;
58 #endif
59 #ifdef GL_OUT_OF_MEMORY
60         case GL_OUT_OF_MEMORY:
61                 Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
62                 break;
63 #endif
64 #ifdef GL_TABLE_TOO_LARGE
65         case GL_TABLE_TOO_LARGE:
66                 Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
67                 break;
68 #endif
69 #ifdef GL_INVALID_FRAMEBUFFER_OPERATION_EXT
70         case GL_INVALID_FRAMEBUFFER_OPERATION_EXT:
71                 Con_Printf("GL_INVALID_FRAMEBUFFER_OPERATION at %s:%i\n", filename, linenumber);
72                 break;
73 #endif
74         default:
75                 Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
76                 break;
77         }
78 }
79 #endif
80
81 #define BACKENDACTIVECHECK if (!backendactive) Sys_Error("GL backend function called when backend is not active");
82
83 void SCR_ScreenShot_f (void);
84
85 static r_viewport_t backend_viewport;
86 static matrix4x4_t backend_modelmatrix;
87 static matrix4x4_t backend_modelviewmatrix;
88
89 static unsigned int backendunits, backendimageunits, backendarrayunits, backendactive;
90
91 /*
92 note: here's strip order for a terrain row:
93 0--1--2--3--4
94 |\ |\ |\ |\ |
95 | \| \| \| \|
96 A--B--C--D--E
97 clockwise
98
99 A0B, 01B, B1C, 12C, C2D, 23D, D3E, 34E
100
101 *elements++ = i + row;
102 *elements++ = i;
103 *elements++ = i + row + 1;
104 *elements++ = i;
105 *elements++ = i + 1;
106 *elements++ = i + row + 1;
107
108
109 for (y = 0;y < rows - 1;y++)
110 {
111         for (x = 0;x < columns - 1;x++)
112         {
113                 i = y * rows + x;
114                 *elements++ = i + columns;
115                 *elements++ = i;
116                 *elements++ = i + columns + 1;
117                 *elements++ = i;
118                 *elements++ = i + 1;
119                 *elements++ = i + columns + 1;
120         }
121 }
122
123 alternative:
124 0--1--2--3--4
125 | /| /|\ | /|
126 |/ |/ | \|/ |
127 A--B--C--D--E
128 counterclockwise
129
130 for (y = 0;y < rows - 1;y++)
131 {
132         for (x = 0;x < columns - 1;x++)
133         {
134                 i = y * rows + x;
135                 *elements++ = i;
136                 *elements++ = i + columns;
137                 *elements++ = i + columns + 1;
138                 *elements++ = i + columns;
139                 *elements++ = i + columns + 1;
140                 *elements++ = i + 1;
141         }
142 }
143 */
144
145 unsigned short polygonelements[(POLYGONELEMENTS_MAXPOINTS-2)*3];
146 unsigned short quadelements[QUADELEMENTS_MAXQUADS*6];
147
148 void GL_Backend_AllocArrays(void)
149 {
150 }
151
152 void GL_Backend_FreeArrays(void)
153 {
154 }
155
156 void GL_VBOStats_f(void)
157 {
158         GL_Mesh_ListVBOs(true);
159 }
160
161 typedef struct gl_bufferobjectinfo_s
162 {
163         int target;
164         int object;
165         size_t size;
166         char name[MAX_QPATH];
167 }
168 gl_bufferobjectinfo_t;
169
170 memexpandablearray_t gl_bufferobjectinfoarray;
171
172 static void gl_backend_start(void)
173 {
174         CHECKGLERROR
175
176         if (qglDrawRangeElements != NULL)
177         {
178                 CHECKGLERROR
179                 qglGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &gl_maxdrawrangeelementsvertices);
180                 CHECKGLERROR
181                 qglGetIntegerv(GL_MAX_ELEMENTS_INDICES, &gl_maxdrawrangeelementsindices);
182                 CHECKGLERROR
183                 Con_DPrintf("GL_MAX_ELEMENTS_VERTICES = %i\nGL_MAX_ELEMENTS_INDICES = %i\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
184         }
185
186         backendunits = bound(1, gl_textureunits, MAX_TEXTUREUNITS);
187         backendimageunits = backendunits;
188         backendarrayunits = backendunits;
189         if (gl_support_fragment_shader)
190         {
191                 CHECKGLERROR
192                 qglGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, (int *)&backendimageunits);
193                 CHECKGLERROR
194                 qglGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, (int *)&backendarrayunits);
195                 CHECKGLERROR
196                 Con_DPrintf("GLSL shader support detected: texture units = %i texenv, %i image, %i array\n", backendunits, backendimageunits, backendarrayunits);
197                 backendimageunits = bound(1, backendimageunits, MAX_TEXTUREUNITS);
198                 backendarrayunits = bound(1, backendarrayunits, MAX_TEXTUREUNITS);
199         }
200         else
201                 Con_DPrintf("GL_MAX_TEXTUREUNITS = %i\n", backendunits);
202
203         GL_Backend_AllocArrays();
204
205         Mem_ExpandableArray_NewArray(&gl_bufferobjectinfoarray, r_main_mempool, sizeof(gl_bufferobjectinfo_t), 128);
206
207         Con_DPrintf("OpenGL backend started.\n");
208
209         CHECKGLERROR
210
211         backendactive = true;
212 }
213
214 static void gl_backend_shutdown(void)
215 {
216         backendunits = 0;
217         backendimageunits = 0;
218         backendarrayunits = 0;
219         backendactive = false;
220
221         Con_DPrint("OpenGL Backend shutting down\n");
222
223         Mem_ExpandableArray_FreeArray(&gl_bufferobjectinfoarray);
224
225         GL_Backend_FreeArrays();
226 }
227
228 static void gl_backend_newmap(void)
229 {
230 }
231
232 void gl_backend_init(void)
233 {
234         int i;
235
236         for (i = 0;i < POLYGONELEMENTS_MAXPOINTS - 2;i++)
237         {
238                 polygonelements[i * 3 + 0] = 0;
239                 polygonelements[i * 3 + 1] = i + 1;
240                 polygonelements[i * 3 + 2] = i + 2;
241         }
242         // elements for rendering a series of quads as triangles
243         for (i = 0;i < QUADELEMENTS_MAXQUADS;i++)
244         {
245                 quadelements[i * 6 + 0] = i * 4;
246                 quadelements[i * 6 + 1] = i * 4 + 1;
247                 quadelements[i * 6 + 2] = i * 4 + 2;
248                 quadelements[i * 6 + 3] = i * 4;
249                 quadelements[i * 6 + 4] = i * 4 + 2;
250                 quadelements[i * 6 + 5] = i * 4 + 3;
251         }
252
253         Cvar_RegisterVariable(&r_render);
254         Cvar_RegisterVariable(&r_waterwarp);
255         Cvar_RegisterVariable(&gl_polyblend);
256         Cvar_RegisterVariable(&v_flipped);
257         Cvar_RegisterVariable(&gl_dither);
258         Cvar_RegisterVariable(&gl_lockarrays);
259         Cvar_RegisterVariable(&gl_lockarrays_minimumvertices);
260         Cvar_RegisterVariable(&gl_vbo);
261         Cvar_RegisterVariable(&gl_paranoid);
262         Cvar_RegisterVariable(&gl_printcheckerror);
263 #ifdef NORENDER
264         Cvar_SetValue("r_render", 0);
265 #endif
266
267         Cvar_RegisterVariable(&gl_mesh_drawrangeelements);
268         Cvar_RegisterVariable(&gl_mesh_testarrayelement);
269         Cvar_RegisterVariable(&gl_mesh_testmanualfeeding);
270         Cvar_RegisterVariable(&gl_mesh_prefer_short_elements);
271
272         Cmd_AddCommand("gl_vbostats", GL_VBOStats_f, "prints a list of all buffer objects (vertex data and triangle elements) and total video memory used by them");
273
274         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
275 }
276
277 void GL_SetMirrorState(qboolean state);
278
279 void R_Viewport_TransformToScreen(const r_viewport_t *v, const vec4_t in, vec4_t out)
280 {
281         vec4_t temp;
282         float iw;
283         Matrix4x4_Transform4 (&v->viewmatrix, in, temp);
284         Matrix4x4_Transform4 (&v->projectmatrix, temp, out);
285         iw = 1.0f / out[3];
286         out[0] = v->x + (out[0] * iw + 1.0f) * v->width * 0.5f;
287         out[1] = v->y + v->height - (out[1] * iw + 1.0f) * v->height * 0.5f;
288         out[2] = v->z + (out[2] * iw + 1.0f) * v->depth * 0.5f;
289 }
290
291 static void R_Viewport_ApplyNearClipPlane(r_viewport_t *v, double normalx, double normaly, double normalz, double dist)
292 {
293         double q[4];
294         double d;
295         float clipPlane[4], v3[3], v4[3];
296         float normal[3];
297
298         // This is inspired by Oblique Depth Projection from http://www.terathon.com/code/oblique.php
299
300         VectorSet(normal, normalx, normaly, normalz);
301         Matrix4x4_Transform3x3(&v->viewmatrix, normal, clipPlane);
302         VectorScale(normal, dist, v3);
303         Matrix4x4_Transform(&v->viewmatrix, v3, v4);
304         // FIXME: LordHavoc: I think this can be done more efficiently somehow but I can't remember the technique
305         clipPlane[3] = -DotProduct(v4, clipPlane);
306
307 #if 0
308 {
309         // testing code for comparing results
310         float clipPlane2[4];
311         VectorCopy4(clipPlane, clipPlane2);
312         R_Mesh_Matrix(&identitymatrix);
313         VectorSet(q, normal[0], normal[1], normal[2], -dist);
314         qglClipPlane(GL_CLIP_PLANE0, q);
315         qglGetClipPlane(GL_CLIP_PLANE0, q);
316         VectorCopy4(q, clipPlane);
317 }
318 #endif
319
320         // Calculate the clip-space corner point opposite the clipping plane
321         // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and
322         // transform it into camera space by multiplying it
323         // by the inverse of the projection matrix
324         q[0] = ((clipPlane[0] < 0.0f ? -1.0f : clipPlane[0] > 0.0f ? 1.0f : 0.0f) + v->m[8]) / v->m[0];
325         q[1] = ((clipPlane[1] < 0.0f ? -1.0f : clipPlane[1] > 0.0f ? 1.0f : 0.0f) + v->m[9]) / v->m[5];
326         q[2] = -1.0f;
327         q[3] = (1.0f + v->m[10]) / v->m[14];
328
329         // Calculate the scaled plane vector
330         d = 2.0f / DotProduct4(clipPlane, q);
331
332         // Replace the third row of the projection matrix
333         v->m[2] = clipPlane[0] * d;
334         v->m[6] = clipPlane[1] * d;
335         v->m[10] = clipPlane[2] * d + 1.0f;
336         v->m[14] = clipPlane[3] * d;
337 }
338
339 void R_Viewport_InitOrtho(r_viewport_t *v, const matrix4x4_t *cameramatrix, int x, int y, int width, int height, double x1, double y1, double x2, double y2, double nearclip, double farclip, const double *nearplane)
340 {
341         float left = x1, right = x2, bottom = y2, top = y1, zNear = nearclip, zFar = farclip;
342         memset(v, 0, sizeof(*v));
343         v->type = R_VIEWPORTTYPE_ORTHO;
344         v->cameramatrix = *cameramatrix;
345         v->x = x;
346         v->y = y;
347         v->z = 0;
348         v->width = width;
349         v->height = height;
350         v->depth = 1;
351         v->m[0]  = 2/(right - left);
352         v->m[5]  = 2/(top - bottom);
353         v->m[10] = -2/(zFar - zNear);
354         v->m[12] = - (right + left)/(right - left);
355         v->m[13] = - (top + bottom)/(top - bottom);
356         v->m[14] = - (zFar + zNear)/(zFar - zNear);
357         v->m[15] = 1;
358
359         Matrix4x4_Invert_Full(&v->viewmatrix, &v->cameramatrix);
360         Matrix4x4_FromArrayDoubleGL(&v->projectmatrix, v->m);
361
362         if (nearplane)
363                 R_Viewport_ApplyNearClipPlane(v, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
364
365 #if 0
366         {
367                 vec4_t test1;
368                 vec4_t test2;
369                 Vector4Set(test1, (x1+x2)*0.5f, (y1+y2)*0.5f, 0.0f, 1.0f);
370                 R_Viewport_TransformToScreen(v, test1, test2);
371                 Con_Printf("%f %f %f -> %f %f %f\n", test1[0], test1[1], test1[2], test2[0], test2[1], test2[2]);
372         }
373 #endif
374 }
375
376 void R_Viewport_InitPerspective(r_viewport_t *v, const matrix4x4_t *cameramatrix, int x, int y, int width, int height, double frustumx, double frustumy, double nearclip, double farclip, const double *nearplane)
377 {
378         matrix4x4_t tempmatrix, basematrix;
379         memset(v, 0, sizeof(*v));
380
381         if(v_flipped.integer)
382                 frustumx = -frustumx;
383
384         v->type = R_VIEWPORTTYPE_PERSPECTIVE;
385         v->cameramatrix = *cameramatrix;
386         v->x = x;
387         v->y = y;
388         v->z = 0;
389         v->width = width;
390         v->height = height;
391         v->depth = 1;
392         v->m[0]  = 1.0 / frustumx;
393         v->m[5]  = 1.0 / frustumy;
394         v->m[10] = -(farclip + nearclip) / (farclip - nearclip);
395         v->m[11] = -1;
396         v->m[14] = -2 * nearclip * farclip / (farclip - nearclip);
397
398         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
399         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
400         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
401         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
402
403         Matrix4x4_FromArrayDoubleGL(&v->projectmatrix, v->m);
404
405         if (nearplane)
406                 R_Viewport_ApplyNearClipPlane(v, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
407 }
408
409 void R_Viewport_InitPerspectiveInfinite(r_viewport_t *v, const matrix4x4_t *cameramatrix, int x, int y, int width, int height, double frustumx, double frustumy, double nearclip, const double *nearplane)
410 {
411         matrix4x4_t tempmatrix, basematrix;
412         const double nudge = 1.0 - 1.0 / (1<<23);
413         memset(v, 0, sizeof(*v));
414
415         if(v_flipped.integer)
416                 frustumx = -frustumx;
417
418         v->type = R_VIEWPORTTYPE_PERSPECTIVE_INFINITEFARCLIP;
419         v->cameramatrix = *cameramatrix;
420         v->x = x;
421         v->y = y;
422         v->z = 0;
423         v->width = width;
424         v->height = height;
425         v->depth = 1;
426         v->m[ 0] = 1.0 / frustumx;
427         v->m[ 5] = 1.0 / frustumy;
428         v->m[10] = -nudge;
429         v->m[11] = -1;
430         v->m[14] = -2 * nearclip * nudge;
431
432         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
433         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
434         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
435         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
436
437         Matrix4x4_FromArrayDoubleGL(&v->projectmatrix, v->m);
438
439         if (nearplane)
440                 R_Viewport_ApplyNearClipPlane(v, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
441 }
442
443 float cubeviewmatrix[6][16] =
444 {
445     // standard cubemap projections
446     { // +X
447          0, 0,-1, 0,
448          0,-1, 0, 0,
449         -1, 0, 0, 0,
450          0, 0, 0, 1,
451     },
452     { // -X
453          0, 0, 1, 0,
454          0,-1, 0, 0,
455          1, 0, 0, 0,
456          0, 0, 0, 1,
457     },
458     { // +Y
459          1, 0, 0, 0,
460          0, 0,-1, 0,
461          0, 1, 0, 0,
462          0, 0, 0, 1,
463     },
464     { // -Y
465          1, 0, 0, 0,
466          0, 0, 1, 0,
467          0,-1, 0, 0,
468          0, 0, 0, 1,
469     },
470     { // +Z
471          1, 0, 0, 0,
472          0,-1, 0, 0,
473          0, 0,-1, 0,
474          0, 0, 0, 1,
475     },
476     { // -Z
477         -1, 0, 0, 0,
478          0,-1, 0, 0,
479          0, 0, 1, 0,
480          0, 0, 0, 1,
481     },
482 };
483 float rectviewmatrix[6][16] =
484 {
485     // sign-preserving cubemap projections
486     { // +X
487          0, 0,-1, 0,
488          0, 1, 0, 0,
489          1, 0, 0, 0,
490          0, 0, 0, 1,
491     },
492     { // -X
493          0, 0, 1, 0,
494          0, 1, 0, 0,
495          1, 0, 0, 0,
496          0, 0, 0, 1,
497     },
498     { // +Y
499          1, 0, 0, 0,
500          0, 0,-1, 0,
501          0, 1, 0, 0,
502          0, 0, 0, 1,
503     },
504     { // -Y
505          1, 0, 0, 0,
506          0, 0, 1, 0,
507          0, 1, 0, 0,
508          0, 0, 0, 1,
509     },
510     { // +Z
511          1, 0, 0, 0,
512          0, 1, 0, 0,
513          0, 0,-1, 0,
514          0, 0, 0, 1,
515     },
516     { // -Z
517          1, 0, 0, 0,
518          0, 1, 0, 0,
519          0, 0, 1, 0,
520          0, 0, 0, 1,
521     },
522 };
523
524 void R_Viewport_InitCubeSideView(r_viewport_t *v, const matrix4x4_t *cameramatrix, int side, int size, float nearclip, float farclip, const float *nearplane)
525 {
526         matrix4x4_t tempmatrix, basematrix;
527         memset(v, 0, sizeof(*v));
528         v->type = R_VIEWPORTTYPE_PERSPECTIVECUBESIDE;
529         v->cameramatrix = *cameramatrix;
530         v->width = size;
531         v->height = size;
532         v->depth = 1;
533         v->m[0] = v->m[5] = 1.0f;
534         v->m[10] = -(farclip + nearclip) / (farclip - nearclip);
535         v->m[11] = -1;
536         v->m[14] = -2 * nearclip * farclip / (farclip - nearclip);
537
538         Matrix4x4_FromArrayFloatGL(&basematrix, cubeviewmatrix[side]);
539         Matrix4x4_Invert_Simple(&tempmatrix, &v->cameramatrix);
540         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
541         Matrix4x4_FromArrayDoubleGL(&v->projectmatrix, v->m);
542
543         if (nearplane)
544                 R_Viewport_ApplyNearClipPlane(v, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
545 }
546
547 void R_Viewport_InitRectSideView(r_viewport_t *v, const matrix4x4_t *cameramatrix, int side, int size, int border, float nearclip, float farclip, const float *nearplane)
548 {
549         matrix4x4_t tempmatrix, basematrix;
550         if (border > size - 2)
551                 border = size - 2;
552         memset(v, 0, sizeof(*v));
553         v->type = R_VIEWPORTTYPE_PERSPECTIVECUBESIDE;
554         v->cameramatrix = *cameramatrix;
555         v->x = (side & 1) * size;
556         v->y = (side >> 1) * size;
557         v->width = size;
558         v->height = size;
559         v->depth = 1;
560         v->m[0] = v->m[5] = 1.0f * ((float)size - border) / size;
561         v->m[10] = -(farclip + nearclip) / (farclip - nearclip);
562         v->m[11] = -1;
563         v->m[14] = -2 * nearclip * farclip / (farclip - nearclip);
564
565         Matrix4x4_FromArrayFloatGL(&basematrix, rectviewmatrix[side]);
566         Matrix4x4_Invert_Simple(&tempmatrix, &v->cameramatrix);
567         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
568         Matrix4x4_FromArrayDoubleGL(&v->projectmatrix, v->m);
569
570         if (nearplane)
571                 R_Viewport_ApplyNearClipPlane(v, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
572 }
573
574 void R_SetViewport(const r_viewport_t *v)
575 {
576         float glmatrix[16];
577         backend_viewport = *v;
578
579         CHECKGLERROR
580         qglViewport(v->x, v->y, v->width, v->height);CHECKGLERROR
581
582         // Load the projection matrix into OpenGL
583         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
584         qglLoadMatrixd(backend_viewport.m);CHECKGLERROR
585         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
586
587         // FIXME: v_flipped_state is evil, this probably breaks somewhere
588         GL_SetMirrorState(v_flipped.integer && (v->type == R_VIEWPORTTYPE_PERSPECTIVE || v->type == R_VIEWPORTTYPE_PERSPECTIVE_INFINITEFARCLIP));
589
590         // directly force an update of the modelview matrix
591         Matrix4x4_Concat(&backend_modelviewmatrix, &backend_viewport.viewmatrix, &backend_modelmatrix);
592         Matrix4x4_ToArrayFloatGL(&backend_modelviewmatrix, glmatrix);
593         qglLoadMatrixf(glmatrix);CHECKGLERROR
594 }
595
596 void R_GetViewport(r_viewport_t *v)
597 {
598         *v = backend_viewport;
599 }
600
601 typedef struct gltextureunit_s
602 {
603         const void *pointer_texcoord;
604         size_t pointer_texcoord_offset;
605         int pointer_texcoord_buffer;
606         int t1d, t2d, t3d, tcubemap, trectangle;
607         int arrayenabled;
608         unsigned int arraycomponents;
609         int rgbscale, alphascale;
610         int combinergb, combinealpha;
611         // FIXME: add more combine stuff
612         // texmatrixenabled exists only to avoid unnecessary texmatrix compares
613         int texmatrixenabled;
614         matrix4x4_t matrix;
615 }
616 gltextureunit_t;
617
618 static struct gl_state_s
619 {
620         int cullface;
621         int cullfaceenable;
622         int blendfunc1;
623         int blendfunc2;
624         int blend;
625         GLboolean depthmask;
626         int colormask; // stored as bottom 4 bits: r g b a (3 2 1 0 order)
627         int depthtest;
628         float depthrange[2];
629         float polygonoffset[2];
630         int alphatest;
631         int scissortest;
632         unsigned int unit;
633         unsigned int clientunit;
634         gltextureunit_t units[MAX_TEXTUREUNITS];
635         float color4f[4];
636         int lockrange_first;
637         int lockrange_count;
638         int vertexbufferobject;
639         int elementbufferobject;
640         qboolean pointer_color_enabled;
641         const void *pointer_vertex;
642         const void *pointer_color;
643         size_t pointer_vertex_offset;
644         size_t pointer_color_offset;
645         int pointer_vertex_buffer;
646         int pointer_color_buffer;
647 }
648 gl_state;
649
650 static void GL_BindVBO(int bufferobject)
651 {
652         if (gl_state.vertexbufferobject != bufferobject)
653         {
654                 gl_state.vertexbufferobject = bufferobject;
655                 CHECKGLERROR
656                 qglBindBufferARB(GL_ARRAY_BUFFER_ARB, bufferobject);
657                 CHECKGLERROR
658         }
659 }
660
661 static void GL_BindEBO(int bufferobject)
662 {
663         if (gl_state.elementbufferobject != bufferobject)
664         {
665                 gl_state.elementbufferobject = bufferobject;
666                 CHECKGLERROR
667                 qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, bufferobject);
668                 CHECKGLERROR
669         }
670 }
671
672 void GL_SetupTextureState(void)
673 {
674         unsigned int i;
675         gltextureunit_t *unit;
676         CHECKGLERROR
677         gl_state.unit = MAX_TEXTUREUNITS;
678         gl_state.clientunit = MAX_TEXTUREUNITS;
679         for (i = 0;i < MAX_TEXTUREUNITS;i++)
680         {
681                 unit = gl_state.units + i;
682                 unit->t1d = 0;
683                 unit->t2d = 0;
684                 unit->t3d = 0;
685                 unit->tcubemap = 0;
686                 unit->arrayenabled = false;
687                 unit->arraycomponents = 0;
688                 unit->pointer_texcoord = NULL;
689                 unit->pointer_texcoord_buffer = 0;
690                 unit->pointer_texcoord_offset = 0;
691                 unit->rgbscale = 1;
692                 unit->alphascale = 1;
693                 unit->combinergb = GL_MODULATE;
694                 unit->combinealpha = GL_MODULATE;
695                 unit->texmatrixenabled = false;
696                 unit->matrix = identitymatrix;
697         }
698
699         for (i = 0;i < backendimageunits;i++)
700         {
701                 GL_ActiveTexture(i);
702                 qglBindTexture(GL_TEXTURE_1D, 0);CHECKGLERROR
703                 qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
704                 if (gl_texture3d)
705                 {
706                         qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
707                 }
708                 if (gl_texturecubemap)
709                 {
710                         qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, 0);CHECKGLERROR
711                 }
712                 if (gl_texturerectangle)
713                 {
714                         qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);CHECKGLERROR
715                 }
716         }
717
718         for (i = 0;i < backendarrayunits;i++)
719         {
720                 GL_ClientActiveTexture(i);
721                 GL_BindVBO(0);
722                 qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), NULL);CHECKGLERROR
723                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
724         }
725
726         for (i = 0;i < backendunits;i++)
727         {
728                 GL_ActiveTexture(i);
729                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
730                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
731                 if (gl_texture3d)
732                 {
733                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
734                 }
735                 if (gl_texturecubemap)
736                 {
737                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
738                 }
739                 if (gl_texturerectangle)
740                 {
741                         qglDisable(GL_TEXTURE_RECTANGLE_ARB);CHECKGLERROR
742                 }
743                 qglMatrixMode(GL_TEXTURE);CHECKGLERROR
744                 qglLoadIdentity();CHECKGLERROR
745                 qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
746                 if (gl_combine.integer)
747                 {
748                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
749                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);CHECKGLERROR
750                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);CHECKGLERROR
751                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
752                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_TEXTURE);CHECKGLERROR // for GL_INTERPOLATE_ARB mode
753                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
754                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
755                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB_ARB, GL_SRC_ALPHA);CHECKGLERROR
756                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);CHECKGLERROR
757                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE);CHECKGLERROR
758                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
759                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA_ARB, GL_CONSTANT_ARB);CHECKGLERROR
760                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
761                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
762                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
763                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
764                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
765                 }
766                 else
767                 {
768                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
769                 }
770                 CHECKGLERROR
771         }
772         CHECKGLERROR
773 }
774
775 void GL_Backend_ResetState(void)
776 {
777         memset(&gl_state, 0, sizeof(gl_state));
778         gl_state.depthtest = true;
779         gl_state.alphatest = false;
780         gl_state.blendfunc1 = GL_ONE;
781         gl_state.blendfunc2 = GL_ZERO;
782         gl_state.blend = false;
783         gl_state.depthmask = GL_TRUE;
784         gl_state.colormask = 15;
785         gl_state.color4f[0] = gl_state.color4f[1] = gl_state.color4f[2] = gl_state.color4f[3] = 1;
786         gl_state.lockrange_first = 0;
787         gl_state.lockrange_count = 0;
788         gl_state.cullface = v_flipped_state ? GL_BACK : GL_FRONT; // quake is backwards, this culls back faces
789         gl_state.cullfaceenable = true;
790         gl_state.polygonoffset[0] = 0;
791         gl_state.polygonoffset[1] = 0;
792
793         CHECKGLERROR
794
795         qglColorMask(1, 1, 1, 1);
796         qglAlphaFunc(GL_GEQUAL, 0.5);CHECKGLERROR
797         qglDisable(GL_ALPHA_TEST);CHECKGLERROR
798         qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
799         qglDisable(GL_BLEND);CHECKGLERROR
800         qglCullFace(gl_state.cullface);CHECKGLERROR
801         qglEnable(GL_CULL_FACE);CHECKGLERROR
802         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
803         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
804         qglDepthMask(gl_state.depthmask);CHECKGLERROR
805         qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
806
807         if (gl_support_arb_vertex_buffer_object)
808         {
809                 qglBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
810                 qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
811         }
812
813         if (gl_support_ext_framebuffer_object)
814         {
815                 qglBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
816                 qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
817         }
818
819         qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), NULL);CHECKGLERROR
820         qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
821
822         qglColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL);CHECKGLERROR
823         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
824
825         GL_Color(0, 0, 0, 0);
826         GL_Color(1, 1, 1, 1);
827
828         GL_SetupTextureState();
829 }
830
831 void GL_ActiveTexture(unsigned int num)
832 {
833         if (gl_state.unit != num)
834         {
835                 gl_state.unit = num;
836                 if (qglActiveTexture)
837                 {
838                         CHECKGLERROR
839                         qglActiveTexture(GL_TEXTURE0_ARB + gl_state.unit);
840                         CHECKGLERROR
841                 }
842         }
843 }
844
845 void GL_ClientActiveTexture(unsigned int num)
846 {
847         if (gl_state.clientunit != num)
848         {
849                 gl_state.clientunit = num;
850                 if (qglActiveTexture)
851                 {
852                         CHECKGLERROR
853                         qglClientActiveTexture(GL_TEXTURE0_ARB + gl_state.clientunit);
854                         CHECKGLERROR
855                 }
856         }
857 }
858
859 void GL_BlendFunc(int blendfunc1, int blendfunc2)
860 {
861         if (gl_state.blendfunc1 != blendfunc1 || gl_state.blendfunc2 != blendfunc2)
862         {
863                 CHECKGLERROR
864                 qglBlendFunc(gl_state.blendfunc1 = blendfunc1, gl_state.blendfunc2 = blendfunc2);CHECKGLERROR
865                 if (gl_state.blendfunc2 == GL_ZERO)
866                 {
867                         if (gl_state.blendfunc1 == GL_ONE)
868                         {
869                                 if (gl_state.blend)
870                                 {
871                                         gl_state.blend = 0;
872                                         qglDisable(GL_BLEND);CHECKGLERROR
873                                 }
874                         }
875                         else
876                         {
877                                 if (!gl_state.blend)
878                                 {
879                                         gl_state.blend = 1;
880                                         qglEnable(GL_BLEND);CHECKGLERROR
881                                 }
882                         }
883                 }
884                 else
885                 {
886                         if (!gl_state.blend)
887                         {
888                                 gl_state.blend = 1;
889                                 qglEnable(GL_BLEND);CHECKGLERROR
890                         }
891                 }
892         }
893 }
894
895 void GL_DepthMask(int state)
896 {
897         if (gl_state.depthmask != state)
898         {
899                 CHECKGLERROR
900                 qglDepthMask(gl_state.depthmask = state);CHECKGLERROR
901         }
902 }
903
904 void GL_DepthTest(int state)
905 {
906         if (gl_state.depthtest != state)
907         {
908                 gl_state.depthtest = state;
909                 CHECKGLERROR
910                 if (gl_state.depthtest)
911                 {
912                         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
913                 }
914                 else
915                 {
916                         qglDisable(GL_DEPTH_TEST);CHECKGLERROR
917                 }
918         }
919 }
920
921 void GL_DepthRange(float nearfrac, float farfrac)
922 {
923         if (gl_state.depthrange[0] != nearfrac || gl_state.depthrange[1] != farfrac)
924         {
925                 gl_state.depthrange[0] = nearfrac;
926                 gl_state.depthrange[1] = farfrac;
927                 qglDepthRange(nearfrac, farfrac);
928         }
929 }
930
931 void GL_PolygonOffset(float planeoffset, float depthoffset)
932 {
933         if (gl_state.polygonoffset[0] != planeoffset || gl_state.polygonoffset[1] != depthoffset)
934         {
935                 gl_state.polygonoffset[0] = planeoffset;
936                 gl_state.polygonoffset[1] = depthoffset;
937                 qglPolygonOffset(planeoffset, depthoffset);
938         }
939 }
940
941 void GL_SetMirrorState(qboolean state)
942 {
943         if(!state != !v_flipped_state)
944         {
945                 // change cull face mode!
946                 if(gl_state.cullface == GL_BACK)
947                         qglCullFace((gl_state.cullface = GL_FRONT));
948                 else if(gl_state.cullface == GL_FRONT)
949                         qglCullFace((gl_state.cullface = GL_BACK));
950         }
951         v_flipped_state = state;
952 }
953
954 void GL_CullFace(int state)
955 {
956         CHECKGLERROR
957
958         if(v_flipped_state)
959         {
960                 if(state == GL_FRONT)
961                         state = GL_BACK;
962                 else if(state == GL_BACK)
963                         state = GL_FRONT;
964         }
965
966         if (state != GL_NONE)
967         {
968                 if (!gl_state.cullfaceenable)
969                 {
970                         gl_state.cullfaceenable = true;
971                         qglEnable(GL_CULL_FACE);CHECKGLERROR
972                 }
973                 if (gl_state.cullface != state)
974                 {
975                         gl_state.cullface = state;
976                         qglCullFace(gl_state.cullface);CHECKGLERROR
977                 }
978         }
979         else
980         {
981                 if (gl_state.cullfaceenable)
982                 {
983                         gl_state.cullfaceenable = false;
984                         qglDisable(GL_CULL_FACE);CHECKGLERROR
985                 }
986         }
987 }
988
989 void GL_AlphaTest(int state)
990 {
991         if (gl_state.alphatest != state)
992         {
993                 gl_state.alphatest = state;
994                 CHECKGLERROR
995                 if (gl_state.alphatest)
996                 {
997                         qglEnable(GL_ALPHA_TEST);CHECKGLERROR
998                 }
999                 else
1000                 {
1001                         qglDisable(GL_ALPHA_TEST);CHECKGLERROR
1002                 }
1003         }
1004 }
1005
1006 void GL_ColorMask(int r, int g, int b, int a)
1007 {
1008         int state = r*8 + g*4 + b*2 + a*1;
1009         if (gl_state.colormask != state)
1010         {
1011                 gl_state.colormask = state;
1012                 CHECKGLERROR
1013                 qglColorMask((GLboolean)r, (GLboolean)g, (GLboolean)b, (GLboolean)a);CHECKGLERROR
1014         }
1015 }
1016
1017 void GL_Color(float cr, float cg, float cb, float ca)
1018 {
1019         if (gl_state.pointer_color_enabled || gl_state.color4f[0] != cr || gl_state.color4f[1] != cg || gl_state.color4f[2] != cb || gl_state.color4f[3] != ca)
1020         {
1021                 gl_state.color4f[0] = cr;
1022                 gl_state.color4f[1] = cg;
1023                 gl_state.color4f[2] = cb;
1024                 gl_state.color4f[3] = ca;
1025                 CHECKGLERROR
1026                 qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);
1027                 CHECKGLERROR
1028         }
1029 }
1030
1031 void GL_LockArrays(int first, int count)
1032 {
1033         if (count < gl_lockarrays_minimumvertices.integer)
1034         {
1035                 first = 0;
1036                 count = 0;
1037         }
1038         if (gl_state.lockrange_count != count || gl_state.lockrange_first != first)
1039         {
1040                 if (gl_state.lockrange_count)
1041                 {
1042                         gl_state.lockrange_count = 0;
1043                         CHECKGLERROR
1044                         qglUnlockArraysEXT();
1045                         CHECKGLERROR
1046                 }
1047                 if (count && gl_supportslockarrays && gl_lockarrays.integer && r_render.integer)
1048                 {
1049                         gl_state.lockrange_first = first;
1050                         gl_state.lockrange_count = count;
1051                         CHECKGLERROR
1052                         qglLockArraysEXT(first, count);
1053                         CHECKGLERROR
1054                 }
1055         }
1056 }
1057
1058 void GL_Scissor (int x, int y, int width, int height)
1059 {
1060         CHECKGLERROR
1061         qglScissor(x, y,width,height);
1062         CHECKGLERROR
1063 }
1064
1065 void GL_ScissorTest(int state)
1066 {
1067         if(gl_state.scissortest == state)
1068                 return;
1069
1070         CHECKGLERROR
1071         if((gl_state.scissortest = state))
1072                 qglEnable(GL_SCISSOR_TEST);
1073         else
1074                 qglDisable(GL_SCISSOR_TEST);
1075         CHECKGLERROR
1076 }
1077
1078 void GL_Clear(int mask)
1079 {
1080         CHECKGLERROR
1081         qglClear(mask);CHECKGLERROR
1082 }
1083
1084 // called at beginning of frame
1085 void R_Mesh_Start(void)
1086 {
1087         BACKENDACTIVECHECK
1088         CHECKGLERROR
1089         if (gl_printcheckerror.integer && !gl_paranoid.integer)
1090         {
1091                 Con_Printf("WARNING: gl_printcheckerror is on but gl_paranoid is off, turning it on...\n");
1092                 Cvar_SetValueQuick(&gl_paranoid, 1);
1093         }
1094         GL_Backend_ResetState();
1095 }
1096
1097 qboolean GL_Backend_CompileShader(int programobject, GLenum shadertypeenum, const char *shadertype, int numstrings, const char **strings)
1098 {
1099         int shaderobject;
1100         int shadercompiled;
1101         char compilelog[MAX_INPUTLINE];
1102         shaderobject = qglCreateShaderObjectARB(shadertypeenum);CHECKGLERROR
1103         if (!shaderobject)
1104                 return false;
1105         qglShaderSourceARB(shaderobject, numstrings, strings, NULL);CHECKGLERROR
1106         qglCompileShaderARB(shaderobject);CHECKGLERROR
1107         qglGetObjectParameterivARB(shaderobject, GL_OBJECT_COMPILE_STATUS_ARB, &shadercompiled);CHECKGLERROR
1108         qglGetInfoLogARB(shaderobject, sizeof(compilelog), NULL, compilelog);CHECKGLERROR
1109         if (compilelog[0] && developer.integer > 0)
1110         {
1111                 int i, j, pretextlines = 0;
1112                 for (i = 0;i < numstrings - 1;i++)
1113                         for (j = 0;strings[i][j];j++)
1114                                 if (strings[i][j] == '\n')
1115                                         pretextlines++;
1116                 Con_DPrintf("%s shader compile log:\n%s\n(line offset for any above warnings/errors: %i)\n", shadertype, compilelog, pretextlines);
1117         }
1118         if (!shadercompiled)
1119         {
1120                 qglDeleteObjectARB(shaderobject);CHECKGLERROR
1121                 return false;
1122         }
1123         qglAttachObjectARB(programobject, shaderobject);CHECKGLERROR
1124         qglDeleteObjectARB(shaderobject);CHECKGLERROR
1125         return true;
1126 }
1127
1128 unsigned int GL_Backend_CompileProgram(int vertexstrings_count, const char **vertexstrings_list, int geometrystrings_count, const char **geometrystrings_list, int fragmentstrings_count, const char **fragmentstrings_list)
1129 {
1130         GLint programlinked;
1131         GLuint programobject = 0;
1132         char linklog[MAX_INPUTLINE];
1133         CHECKGLERROR
1134
1135         programobject = qglCreateProgramObjectARB();CHECKGLERROR
1136         if (!programobject)
1137                 return 0;
1138
1139         if (vertexstrings_count && !GL_Backend_CompileShader(programobject, GL_VERTEX_SHADER_ARB, "vertex", vertexstrings_count, vertexstrings_list))
1140                 goto cleanup;
1141
1142 #ifdef GL_GEOMETRY_SHADER_ARB
1143         if (geometrystrings_count && !GL_Backend_CompileShader(programobject, GL_GEOMETRY_SHADER_ARB, "geometry", geometrystrings_count, geometrystrings_list))
1144                 goto cleanup;
1145 #endif
1146
1147         if (fragmentstrings_count && !GL_Backend_CompileShader(programobject, GL_FRAGMENT_SHADER_ARB, "fragment", fragmentstrings_count, fragmentstrings_list))
1148                 goto cleanup;
1149
1150         qglLinkProgramARB(programobject);CHECKGLERROR
1151         qglGetObjectParameterivARB(programobject, GL_OBJECT_LINK_STATUS_ARB, &programlinked);CHECKGLERROR
1152         qglGetInfoLogARB(programobject, sizeof(linklog), NULL, linklog);CHECKGLERROR
1153         if (linklog[0])
1154         {
1155                 Con_DPrintf("program link log:\n%s\n", linklog);
1156                 // software vertex shader is ok but software fragment shader is WAY
1157                 // too slow, fail program if so.
1158                 // NOTE: this string might be ATI specific, but that's ok because the
1159                 // ATI R300 chip (Radeon 9500-9800/X300) is the most likely to use a
1160                 // software fragment shader due to low instruction and dependent
1161                 // texture limits.
1162                 if (strstr(linklog, "fragment shader will run in software"))
1163                         programlinked = false;
1164         }
1165         if (!programlinked)
1166                 goto cleanup;
1167         return programobject;
1168 cleanup:
1169         qglDeleteObjectARB(programobject);CHECKGLERROR
1170         return 0;
1171 }
1172
1173 void GL_Backend_FreeProgram(unsigned int prog)
1174 {
1175         CHECKGLERROR
1176         qglDeleteObjectARB(prog);
1177         CHECKGLERROR
1178 }
1179
1180 int gl_backend_rebindtextures;
1181
1182 void GL_Backend_RenumberElements(int *out, int count, const int *in, int offset)
1183 {
1184         int i;
1185         if (offset)
1186         {
1187                 for (i = 0;i < count;i++)
1188                         *out++ = *in++ + offset;
1189         }
1190         else
1191                 memcpy(out, in, sizeof(*out) * count);
1192 }
1193
1194 // renders triangles using vertices from the active arrays
1195 int paranoidblah = 0;
1196 void R_Mesh_Draw(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int bufferobject3i, int bufferobject3s)
1197 {
1198         unsigned int numelements = numtriangles * 3;
1199         if (numvertices < 3 || numtriangles < 1)
1200         {
1201                 if (numvertices < 0 || numtriangles < 0 || developer.integer >= 100)
1202                         Con_Printf("R_Mesh_Draw(%d, %d, %d, %d, %8p, %8p, %i, %i);\n", firstvertex, numvertices, firsttriangle, numtriangles, (void *)element3i, (void *)element3s, bufferobject3i, bufferobject3s);
1203                 return;
1204         }
1205         if (!gl_mesh_prefer_short_elements.integer)
1206         {
1207                 if (element3i)
1208                         element3s = NULL;
1209                 if (bufferobject3i)
1210                         bufferobject3s = 0;
1211         }
1212         if (element3i)
1213                 element3i += firsttriangle * 3;
1214         if (element3s)
1215                 element3s += firsttriangle * 3;
1216         switch (gl_vbo.integer)
1217         {
1218         default:
1219         case 0:
1220         case 2:
1221                 bufferobject3i = bufferobject3s = 0;
1222                 break;
1223         case 1:
1224                 break;
1225         case 3:
1226                 if (firsttriangle)
1227                         bufferobject3i = bufferobject3s = 0;
1228                 break;
1229         }
1230         CHECKGLERROR
1231         r_refdef.stats.meshes++;
1232         r_refdef.stats.meshes_elements += numelements;
1233         if (gl_paranoid.integer)
1234         {
1235                 unsigned int i, j, size;
1236                 const int *p;
1237                 // note: there's no validation done here on buffer objects because it
1238                 // is somewhat difficult to get at the data, and gl_paranoid can be
1239                 // used without buffer objects if the need arises
1240                 // (the data could be gotten using glMapBuffer but it would be very
1241                 //  slow due to uncachable video memory reads)
1242                 if (!qglIsEnabled(GL_VERTEX_ARRAY))
1243                         Con_Print("R_Mesh_Draw: vertex array not enabled\n");
1244                 CHECKGLERROR
1245                 if (gl_state.pointer_vertex)
1246                         for (j = 0, size = numvertices * 3, p = (int *)((float *)gl_state.pointer_vertex + firstvertex * 3);j < size;j++, p++)
1247                                 paranoidblah += *p;
1248                 if (gl_state.pointer_color_enabled)
1249                 {
1250                         if (!qglIsEnabled(GL_COLOR_ARRAY))
1251                                 Con_Print("R_Mesh_Draw: color array set but not enabled\n");
1252                         CHECKGLERROR
1253                         if (gl_state.pointer_color && gl_state.pointer_color_enabled)
1254                                 for (j = 0, size = numvertices * 4, p = (int *)((float *)gl_state.pointer_color + firstvertex * 4);j < size;j++, p++)
1255                                         paranoidblah += *p;
1256                 }
1257                 for (i = 0;i < backendarrayunits;i++)
1258                 {
1259                         if (gl_state.units[i].arrayenabled)
1260                         {
1261                                 GL_ClientActiveTexture(i);
1262                                 if (!qglIsEnabled(GL_TEXTURE_COORD_ARRAY))
1263                                         Con_Print("R_Mesh_Draw: texcoord array set but not enabled\n");
1264                                 CHECKGLERROR
1265                                 if (gl_state.units[i].pointer_texcoord && gl_state.units[i].arrayenabled)
1266                                         for (j = 0, size = numvertices * gl_state.units[i].arraycomponents, p = (int *)((float *)gl_state.units[i].pointer_texcoord + firstvertex * gl_state.units[i].arraycomponents);j < size;j++, p++)
1267                                                 paranoidblah += *p;
1268                         }
1269                 }
1270                 if (element3i)
1271                 {
1272                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
1273                         {
1274                                 if (element3i[i] < firstvertex || element3i[i] >= firstvertex + numvertices)
1275                                 {
1276                                         Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range %i - %i) in element3i array\n", element3i[i], firstvertex, firstvertex + numvertices);
1277                                         return;
1278                                 }
1279                         }
1280                 }
1281                 if (element3s)
1282                 {
1283                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
1284                         {
1285                                 if (element3s[i] < firstvertex || element3s[i] >= firstvertex + numvertices)
1286                                 {
1287                                         Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range %i - %i) in element3s array\n", element3s[i], firstvertex, firstvertex + numvertices);
1288                                         return;
1289                                 }
1290                         }
1291                 }
1292                 CHECKGLERROR
1293         }
1294         if (r_render.integer)
1295         {
1296                 CHECKGLERROR
1297                 if (gl_mesh_testmanualfeeding.integer)
1298                 {
1299                         unsigned int i, j, element;
1300                         const GLfloat *p;
1301                         qglBegin(GL_TRIANGLES);
1302                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
1303                         {
1304                                 element = element3i ? element3i[i] : element3s[i];
1305                                 for (j = 0;j < backendarrayunits;j++)
1306                                 {
1307                                         if (gl_state.units[j].pointer_texcoord && gl_state.units[j].arrayenabled)
1308                                         {
1309                                                 if (backendarrayunits > 1)
1310                                                 {
1311                                                         if (gl_state.units[j].arraycomponents == 4)
1312                                                         {
1313                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + element * 4;
1314                                                                 qglMultiTexCoord4f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2], p[3]);
1315                                                         }
1316                                                         else if (gl_state.units[j].arraycomponents == 3)
1317                                                         {
1318                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + element * 3;
1319                                                                 qglMultiTexCoord3f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2]);
1320                                                         }
1321                                                         else if (gl_state.units[j].arraycomponents == 2)
1322                                                         {
1323                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + element * 2;
1324                                                                 qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, p[0], p[1]);
1325                                                         }
1326                                                         else
1327                                                         {
1328                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + element * 1;
1329                                                                 qglMultiTexCoord1f(GL_TEXTURE0_ARB + j, p[0]);
1330                                                         }
1331                                                 }
1332                                                 else
1333                                                 {
1334                                                         if (gl_state.units[j].arraycomponents == 4)
1335                                                         {
1336                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + element * 4;
1337                                                                 qglTexCoord4f(p[0], p[1], p[2], p[3]);
1338                                                         }
1339                                                         else if (gl_state.units[j].arraycomponents == 3)
1340                                                         {
1341                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + element * 3;
1342                                                                 qglTexCoord3f(p[0], p[1], p[2]);
1343                                                         }
1344                                                         else if (gl_state.units[j].arraycomponents == 2)
1345                                                         {
1346                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + element * 2;
1347                                                                 qglTexCoord2f(p[0], p[1]);
1348                                                         }
1349                                                         else
1350                                                         {
1351                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + element * 1;
1352                                                                 qglTexCoord1f(p[0]);
1353                                                         }
1354                                                 }
1355                                         }
1356                                 }
1357                                 if (gl_state.pointer_color && gl_state.pointer_color_enabled)
1358                                 {
1359                                         p = ((const GLfloat *)(gl_state.pointer_color)) + element * 4;
1360                                         qglColor4f(p[0], p[1], p[2], p[3]);
1361                                 }
1362                                 p = ((const GLfloat *)(gl_state.pointer_vertex)) + element * 3;
1363                                 qglVertex3f(p[0], p[1], p[2]);
1364                         }
1365                         qglEnd();
1366                         CHECKGLERROR
1367                 }
1368                 else if (gl_mesh_testarrayelement.integer)
1369                 {
1370                         int i;
1371                         qglBegin(GL_TRIANGLES);
1372                         if (element3i)
1373                         {
1374                                 for (i = 0;i < numtriangles * 3;i++)
1375                                         qglArrayElement(element3i[i]);
1376                         }
1377                         else if (element3s)
1378                         {
1379                                 for (i = 0;i < numtriangles * 3;i++)
1380                                         qglArrayElement(element3s[i]);
1381                         }
1382                         qglEnd();
1383                         CHECKGLERROR
1384                 }
1385                 else if (bufferobject3s)
1386                 {
1387                         GL_BindEBO(bufferobject3s);
1388                         if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
1389                         {
1390                                 qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices - 1, numelements, GL_UNSIGNED_SHORT, (void *)(firsttriangle * sizeof(unsigned short[3])));
1391                                 CHECKGLERROR
1392                         }
1393                         else
1394                         {
1395                                 qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_SHORT, (void *)(firsttriangle * sizeof(unsigned short[3])));
1396                                 CHECKGLERROR
1397                         }
1398                 }
1399                 else if (bufferobject3i)
1400                 {
1401                         GL_BindEBO(bufferobject3i);
1402                         if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
1403                         {
1404                                 qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices - 1, numelements, GL_UNSIGNED_INT, (void *)(firsttriangle * sizeof(unsigned int[3])));
1405                                 CHECKGLERROR
1406                         }
1407                         else
1408                         {
1409                                 qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, (void *)(firsttriangle * sizeof(unsigned int[3])));
1410                                 CHECKGLERROR
1411                         }
1412                 }
1413                 else if (element3s)
1414                 {
1415                         GL_BindEBO(0);
1416                         if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
1417                         {
1418                                 qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices - 1, numelements, GL_UNSIGNED_SHORT, element3s);
1419                                 CHECKGLERROR
1420                         }
1421                         else
1422                         {
1423                                 qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_SHORT, element3s);
1424                                 CHECKGLERROR
1425                         }
1426                 }
1427                 else if (element3i)
1428                 {
1429                         GL_BindEBO(0);
1430                         if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
1431                         {
1432                                 qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices - 1, numelements, GL_UNSIGNED_INT, element3i);
1433                                 CHECKGLERROR
1434                         }
1435                         else
1436                         {
1437                                 qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, element3i);
1438                                 CHECKGLERROR
1439                         }
1440                 }
1441         }
1442 }
1443
1444 // restores backend state, used when done with 3D rendering
1445 void R_Mesh_Finish(void)
1446 {
1447         unsigned int i;
1448         BACKENDACTIVECHECK
1449         CHECKGLERROR
1450         GL_LockArrays(0, 0);
1451         CHECKGLERROR
1452
1453         for (i = 0;i < backendimageunits;i++)
1454         {
1455                 GL_ActiveTexture(i);
1456                 qglBindTexture(GL_TEXTURE_1D, 0);CHECKGLERROR
1457                 qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
1458                 if (gl_texture3d)
1459                 {
1460                         qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
1461                 }
1462                 if (gl_texturecubemap)
1463                 {
1464                         qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, 0);CHECKGLERROR
1465                 }
1466                 if (gl_texturerectangle)
1467                 {
1468                         qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);CHECKGLERROR
1469                 }
1470         }
1471         for (i = 0;i < backendarrayunits;i++)
1472         {
1473                 GL_ActiveTexture(backendarrayunits - 1 - i);
1474                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1475         }
1476         for (i = 0;i < backendunits;i++)
1477         {
1478                 GL_ActiveTexture(backendunits - 1 - i);
1479                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
1480                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1481                 if (gl_texture3d)
1482                 {
1483                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1484                 }
1485                 if (gl_texturecubemap)
1486                 {
1487                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1488                 }
1489                 if (gl_texturerectangle)
1490                 {
1491                         qglDisable(GL_TEXTURE_RECTANGLE_ARB);CHECKGLERROR
1492                 }
1493                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
1494                 if (gl_combine.integer)
1495                 {
1496                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
1497                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
1498                 }
1499         }
1500         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
1501         qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
1502
1503         qglDisable(GL_BLEND);CHECKGLERROR
1504         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
1505         qglDepthMask(GL_TRUE);CHECKGLERROR
1506         qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
1507 }
1508
1509 int R_Mesh_CreateStaticBufferObject(unsigned int target, void *data, size_t size, const char *name)
1510 {
1511         gl_bufferobjectinfo_t *info;
1512         GLuint bufferobject;
1513
1514         if (!gl_vbo.integer)
1515                 return 0;
1516
1517         qglGenBuffersARB(1, &bufferobject);
1518         switch(target)
1519         {
1520         case GL_ELEMENT_ARRAY_BUFFER_ARB: GL_BindEBO(bufferobject);break;
1521         case GL_ARRAY_BUFFER_ARB: GL_BindVBO(bufferobject);break;
1522         default: Sys_Error("R_Mesh_CreateStaticBufferObject: unknown target type %i\n", target);return 0;
1523         }
1524         qglBufferDataARB(target, size, data, GL_STATIC_DRAW_ARB);
1525
1526         info = (gl_bufferobjectinfo_t *) Mem_ExpandableArray_AllocRecord(&gl_bufferobjectinfoarray);
1527         memset(info, 0, sizeof(*info));
1528         info->target = target;
1529         info->object = bufferobject;
1530         info->size = size;
1531         strlcpy(info->name, name, sizeof(info->name));
1532
1533         return (int)bufferobject;
1534 }
1535
1536 void R_Mesh_DestroyBufferObject(int bufferobject)
1537 {
1538         int i, endindex;
1539         gl_bufferobjectinfo_t *info;
1540
1541         qglDeleteBuffersARB(1, (GLuint *)&bufferobject);
1542
1543         endindex = Mem_ExpandableArray_IndexRange(&gl_bufferobjectinfoarray);
1544         for (i = 0;i < endindex;i++)
1545         {
1546                 info = (gl_bufferobjectinfo_t *) Mem_ExpandableArray_RecordAtIndex(&gl_bufferobjectinfoarray, i);
1547                 if (!info)
1548                         continue;
1549                 if (info->object == bufferobject)
1550                 {
1551                         Mem_ExpandableArray_FreeRecord(&gl_bufferobjectinfoarray, (void *)info);
1552                         break;
1553                 }
1554         }
1555 }
1556
1557 void GL_Mesh_ListVBOs(qboolean printeach)
1558 {
1559         int i, endindex;
1560         size_t ebocount = 0, ebomemory = 0;
1561         size_t vbocount = 0, vbomemory = 0;
1562         gl_bufferobjectinfo_t *info;
1563         endindex = Mem_ExpandableArray_IndexRange(&gl_bufferobjectinfoarray);
1564         for (i = 0;i < endindex;i++)
1565         {
1566                 info = (gl_bufferobjectinfo_t *) Mem_ExpandableArray_RecordAtIndex(&gl_bufferobjectinfoarray, i);
1567                 if (!info)
1568                         continue;
1569                 switch(info->target)
1570                 {
1571                 case GL_ELEMENT_ARRAY_BUFFER_ARB: ebocount++;ebomemory += info->size;if (printeach) Con_Printf("EBO #%i %s = %i bytes\n", info->object, info->name, (int)info->size);break;
1572                 case GL_ARRAY_BUFFER_ARB: vbocount++;vbomemory += info->size;if (printeach) Con_Printf("VBO #%i %s = %i bytes\n", info->object, info->name, (int)info->size);break;
1573                 default: Con_Printf("gl_vbostats: unknown target type %i\n", info->target);break;
1574                 }
1575         }
1576         Con_Printf("vertex buffers: %i element buffers totalling %i bytes (%.3f MB), %i vertex buffers totalling %i bytes (%.3f MB), combined %i bytes (%.3fMB)\n", (int)ebocount, (int)ebomemory, ebomemory / 1048576.0, (int)vbocount, (int)vbomemory, vbomemory / 1048576.0, (int)(ebomemory + vbomemory), (ebomemory + vbomemory) / 1048576.0);
1577 }
1578
1579 void R_Mesh_Matrix(const matrix4x4_t *matrix)
1580 {
1581         if (memcmp(matrix, &backend_modelmatrix, sizeof(matrix4x4_t)))
1582         {
1583                 float glmatrix[16];
1584                 backend_modelmatrix = *matrix;
1585                 Matrix4x4_Concat(&backend_modelviewmatrix, &backend_viewport.viewmatrix, &backend_modelmatrix);
1586                 Matrix4x4_ToArrayFloatGL(&backend_modelviewmatrix, glmatrix);
1587                 CHECKGLERROR
1588                 qglLoadMatrixf(glmatrix);CHECKGLERROR
1589         }
1590 }
1591
1592 void R_Mesh_VertexPointer(const float *vertex3f, int bufferobject, size_t bufferoffset)
1593 {
1594         if (!gl_vbo.integer)
1595                 bufferobject = 0;
1596         if (gl_state.pointer_vertex != vertex3f || gl_state.pointer_vertex_buffer != bufferobject || gl_state.pointer_vertex_offset != bufferoffset)
1597         {
1598                 gl_state.pointer_vertex = vertex3f;
1599                 gl_state.pointer_vertex_buffer = bufferobject;
1600                 gl_state.pointer_vertex_offset = bufferoffset;
1601                 CHECKGLERROR
1602                 GL_BindVBO(bufferobject);
1603                 qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), bufferobject ? (void *)bufferoffset : vertex3f);CHECKGLERROR
1604         }
1605 }
1606
1607 void R_Mesh_ColorPointer(const float *color4f, int bufferobject, size_t bufferoffset)
1608 {
1609         // note: this can not rely on bufferobject to decide whether a color array
1610         // is supplied, because surfmesh_t shares one vbo for all arrays, which
1611         // means that a valid vbo may be supplied even if there is no color array.
1612         if (color4f)
1613         {
1614                 if (!gl_vbo.integer)
1615                         bufferobject = 0;
1616                 // caller wants color array enabled
1617                 if (!gl_state.pointer_color_enabled)
1618                 {
1619                         gl_state.pointer_color_enabled = true;
1620                         CHECKGLERROR
1621                         qglEnableClientState(GL_COLOR_ARRAY);CHECKGLERROR
1622                 }
1623                 if (gl_state.pointer_color != color4f || gl_state.pointer_color_buffer != bufferobject || gl_state.pointer_color_offset != bufferoffset)
1624                 {
1625                         gl_state.pointer_color = color4f;
1626                         gl_state.pointer_color_buffer = bufferobject;
1627                         gl_state.pointer_color_offset = bufferoffset;
1628                         CHECKGLERROR
1629                         GL_BindVBO(bufferobject);
1630                         qglColorPointer(4, GL_FLOAT, sizeof(float[4]), bufferobject ? (void *)bufferoffset : color4f);CHECKGLERROR
1631                 }
1632         }
1633         else
1634         {
1635                 // caller wants color array disabled
1636                 if (gl_state.pointer_color_enabled)
1637                 {
1638                         gl_state.pointer_color_enabled = false;
1639                         CHECKGLERROR
1640                         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
1641                         // when color array is on the glColor gets trashed, set it again
1642                         qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);CHECKGLERROR
1643                 }
1644         }
1645 }
1646
1647 void R_Mesh_TexCoordPointer(unsigned int unitnum, unsigned int numcomponents, const float *texcoord, int bufferobject, size_t bufferoffset)
1648 {
1649         gltextureunit_t *unit = gl_state.units + unitnum;
1650         // update array settings
1651         CHECKGLERROR
1652         // note: there is no need to check bufferobject here because all cases
1653         // that involve a valid bufferobject also supply a texcoord array
1654         if (texcoord)
1655         {
1656                 if (!gl_vbo.integer)
1657                         bufferobject = 0;
1658                 // texture array unit is enabled, enable the array
1659                 if (!unit->arrayenabled)
1660                 {
1661                         unit->arrayenabled = true;
1662                         GL_ClientActiveTexture(unitnum);
1663                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1664                 }
1665                 // texcoord array
1666                 if (unit->pointer_texcoord != texcoord || unit->pointer_texcoord_buffer != bufferobject || unit->pointer_texcoord_offset != bufferoffset || unit->arraycomponents != numcomponents)
1667                 {
1668                         unit->pointer_texcoord = texcoord;
1669                         unit->pointer_texcoord_buffer = bufferobject;
1670                         unit->pointer_texcoord_offset = bufferoffset;
1671                         unit->arraycomponents = numcomponents;
1672                         GL_ClientActiveTexture(unitnum);
1673                         GL_BindVBO(bufferobject);
1674                         qglTexCoordPointer(unit->arraycomponents, GL_FLOAT, sizeof(float) * unit->arraycomponents, bufferobject ? (void *)bufferoffset : texcoord);CHECKGLERROR
1675                 }
1676         }
1677         else
1678         {
1679                 // texture array unit is disabled, disable the array
1680                 if (unit->arrayenabled)
1681                 {
1682                         unit->arrayenabled = false;
1683                         GL_ClientActiveTexture(unitnum);
1684                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1685                 }
1686         }
1687 }
1688
1689 void R_Mesh_TexBindAll(unsigned int unitnum, int tex1d, int tex2d, int tex3d, int texcubemap, int texrectangle)
1690 {
1691         gltextureunit_t *unit = gl_state.units + unitnum;
1692         if (unitnum >= backendimageunits)
1693                 return;
1694         // update 1d texture binding
1695         if (unit->t1d != tex1d)
1696         {
1697                 GL_ActiveTexture(unitnum);
1698                 if (unitnum < backendunits)
1699                 {
1700                         if (tex1d)
1701                         {
1702                                 if (unit->t1d == 0)
1703                                 {
1704                                         qglEnable(GL_TEXTURE_1D);CHECKGLERROR
1705                                 }
1706                         }
1707                         else
1708                         {
1709                                 if (unit->t1d)
1710                                 {
1711                                         qglDisable(GL_TEXTURE_1D);CHECKGLERROR
1712                                 }
1713                         }
1714                 }
1715                 unit->t1d = tex1d;
1716                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);CHECKGLERROR
1717         }
1718         // update 2d texture binding
1719         if (unit->t2d != tex2d)
1720         {
1721                 GL_ActiveTexture(unitnum);
1722                 if (unitnum < backendunits)
1723                 {
1724                         if (tex2d)
1725                         {
1726                                 if (unit->t2d == 0)
1727                                 {
1728                                         qglEnable(GL_TEXTURE_2D);CHECKGLERROR
1729                                 }
1730                         }
1731                         else
1732                         {
1733                                 if (unit->t2d)
1734                                 {
1735                                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1736                                 }
1737                         }
1738                 }
1739                 unit->t2d = tex2d;
1740                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR
1741         }
1742         // update 3d texture binding
1743         if (unit->t3d != tex3d)
1744         {
1745                 GL_ActiveTexture(unitnum);
1746                 if (unitnum < backendunits)
1747                 {
1748                         if (tex3d)
1749                         {
1750                                 if (unit->t3d == 0)
1751                                 {
1752                                         qglEnable(GL_TEXTURE_3D);CHECKGLERROR
1753                                 }
1754                         }
1755                         else
1756                         {
1757                                 if (unit->t3d)
1758                                 {
1759                                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1760                                 }
1761                         }
1762                 }
1763                 unit->t3d = tex3d;
1764                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR
1765         }
1766         // update cubemap texture binding
1767         if (unit->tcubemap != texcubemap)
1768         {
1769                 GL_ActiveTexture(unitnum);
1770                 if (unitnum < backendunits)
1771                 {
1772                         if (texcubemap)
1773                         {
1774                                 if (unit->tcubemap == 0)
1775                                 {
1776                                         qglEnable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1777                                 }
1778                         }
1779                         else
1780                         {
1781                                 if (unit->tcubemap)
1782                                 {
1783                                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1784                                 }
1785                         }
1786                 }
1787                 unit->tcubemap = texcubemap;
1788                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);CHECKGLERROR
1789         }
1790         // update rectangle texture binding
1791         if (unit->trectangle != texrectangle)
1792         {
1793                 GL_ActiveTexture(unitnum);
1794                 if (unitnum < backendunits)
1795                 {
1796                         if (texrectangle)
1797                         {
1798                                 if (unit->trectangle == 0)
1799                                 {
1800                                         qglEnable(GL_TEXTURE_RECTANGLE_ARB);CHECKGLERROR
1801                                 }
1802                         }
1803                         else
1804                         {
1805                                 if (unit->trectangle)
1806                                 {
1807                                         qglDisable(GL_TEXTURE_RECTANGLE_ARB);CHECKGLERROR
1808                                 }
1809                         }
1810                 }
1811                 unit->trectangle = texrectangle;
1812                 qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, unit->trectangle);CHECKGLERROR
1813         }
1814 }
1815
1816 void R_Mesh_TexBind1D(unsigned int unitnum, int texnum)
1817 {
1818         gltextureunit_t *unit = gl_state.units + unitnum;
1819         if (unitnum >= backendimageunits)
1820                 return;
1821         // update 1d texture binding
1822         if (unit->t1d != texnum)
1823         {
1824                 GL_ActiveTexture(unitnum);
1825                 if (unitnum < backendunits)
1826                 {
1827                         if (texnum)
1828                         {
1829                                 if (unit->t1d == 0)
1830                                 {
1831                                         qglEnable(GL_TEXTURE_1D);CHECKGLERROR
1832                                 }
1833                         }
1834                         else
1835                         {
1836                                 if (unit->t1d)
1837                                 {
1838                                         qglDisable(GL_TEXTURE_1D);CHECKGLERROR
1839                                 }
1840                         }
1841                 }
1842                 unit->t1d = texnum;
1843                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);CHECKGLERROR
1844         }
1845         // update 2d texture binding
1846         if (unit->t2d)
1847         {
1848                 GL_ActiveTexture(unitnum);
1849                 if (unitnum < backendunits)
1850                 {
1851                         if (unit->t2d)
1852                         {
1853                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1854                         }
1855                 }
1856                 unit->t2d = 0;
1857                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR
1858         }
1859         // update 3d texture binding
1860         if (unit->t3d)
1861         {
1862                 GL_ActiveTexture(unitnum);
1863                 if (unitnum < backendunits)
1864                 {
1865                         if (unit->t3d)
1866                         {
1867                                 qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1868                         }
1869                 }
1870                 unit->t3d = 0;
1871                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR
1872         }
1873         // update cubemap texture binding
1874         if (unit->tcubemap)
1875         {
1876                 GL_ActiveTexture(unitnum);
1877                 if (unitnum < backendunits)
1878                 {
1879                         if (unit->tcubemap)
1880                         {
1881                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1882                         }
1883                 }
1884                 unit->tcubemap = 0;
1885                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);CHECKGLERROR
1886         }
1887         // update rectangle texture binding
1888         if (unit->trectangle)
1889         {
1890                 GL_ActiveTexture(unitnum);
1891                 if (unitnum < backendunits)
1892                 {
1893                         if (unit->trectangle)
1894                         {
1895                                 qglDisable(GL_TEXTURE_RECTANGLE_ARB);CHECKGLERROR
1896                         }
1897                 }
1898                 unit->trectangle = 0;
1899                 qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, unit->trectangle);CHECKGLERROR
1900         }
1901 }
1902
1903 void R_Mesh_TexBind(unsigned int unitnum, int texnum)
1904 {
1905         gltextureunit_t *unit = gl_state.units + unitnum;
1906         if (unitnum >= backendimageunits)
1907                 return;
1908         // update 1d texture binding
1909         if (unit->t1d)
1910         {
1911                 GL_ActiveTexture(unitnum);
1912                 if (unitnum < backendunits)
1913                 {
1914                         if (unit->t1d)
1915                         {
1916                                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
1917                         }
1918                 }
1919                 unit->t1d = 0;
1920                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);CHECKGLERROR
1921         }
1922         // update 2d texture binding
1923         if (unit->t2d != texnum)
1924         {
1925                 GL_ActiveTexture(unitnum);
1926                 if (unitnum < backendunits)
1927                 {
1928                         if (texnum)
1929                         {
1930                                 if (unit->t2d == 0)
1931                                 {
1932                                         qglEnable(GL_TEXTURE_2D);CHECKGLERROR
1933                                 }
1934                         }
1935                         else
1936                         {
1937                                 if (unit->t2d)
1938                                 {
1939                                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1940                                 }
1941                         }
1942                 }
1943                 unit->t2d = texnum;
1944                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR
1945         }
1946         // update 3d texture binding
1947         if (unit->t3d)
1948         {
1949                 GL_ActiveTexture(unitnum);
1950                 if (unitnum < backendunits)
1951                 {
1952                         if (unit->t3d)
1953                         {
1954                                 qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1955                         }
1956                 }
1957                 unit->t3d = 0;
1958                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR
1959         }
1960         // update cubemap texture binding
1961         if (unit->tcubemap != 0)
1962         {
1963                 GL_ActiveTexture(unitnum);
1964                 if (unitnum < backendunits)
1965                 {
1966                         if (unit->tcubemap)
1967                         {
1968                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1969                         }
1970                 }
1971                 unit->tcubemap = 0;
1972                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);CHECKGLERROR
1973         }
1974         // update rectangle texture binding
1975         if (unit->trectangle != 0)
1976         {
1977                 GL_ActiveTexture(unitnum);
1978                 if (unitnum < backendunits)
1979                 {
1980                         if (unit->trectangle)
1981                         {
1982                                 qglDisable(GL_TEXTURE_RECTANGLE_ARB);CHECKGLERROR
1983                         }
1984                 }
1985                 unit->trectangle = 0;
1986                 qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, unit->trectangle);CHECKGLERROR
1987         }
1988 }
1989
1990 void R_Mesh_TexBind3D(unsigned int unitnum, int texnum)
1991 {
1992         gltextureunit_t *unit = gl_state.units + unitnum;
1993         if (unitnum >= backendimageunits)
1994                 return;
1995         // update 1d texture binding
1996         if (unit->t1d)
1997         {
1998                 GL_ActiveTexture(unitnum);
1999                 if (unitnum < backendunits)
2000                 {
2001                         if (unit->t1d)
2002                         {
2003                                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
2004                         }
2005                 }
2006                 unit->t1d = 0;
2007                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);CHECKGLERROR
2008         }
2009         // update 2d texture binding
2010         if (unit->t2d)
2011         {
2012                 GL_ActiveTexture(unitnum);
2013                 if (unitnum < backendunits)
2014                 {
2015                         if (unit->t2d)
2016                         {
2017                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
2018                         }
2019                 }
2020                 unit->t2d = 0;
2021                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR
2022         }
2023         // update 3d texture binding
2024         if (unit->t3d != texnum)
2025         {
2026                 GL_ActiveTexture(unitnum);
2027                 if (unitnum < backendunits)
2028                 {
2029                         if (texnum)
2030                         {
2031                                 if (unit->t3d == 0)
2032                                 {
2033                                         qglEnable(GL_TEXTURE_3D);CHECKGLERROR
2034                                 }
2035                         }
2036                         else
2037                         {
2038                                 if (unit->t3d)
2039                                 {
2040                                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
2041                                 }
2042                         }
2043                 }
2044                 unit->t3d = texnum;
2045                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR
2046         }
2047         // update cubemap texture binding
2048         if (unit->tcubemap != 0)
2049         {
2050                 GL_ActiveTexture(unitnum);
2051                 if (unitnum < backendunits)
2052                 {
2053                         if (unit->tcubemap)
2054                         {
2055                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
2056                         }
2057                 }
2058                 unit->tcubemap = 0;
2059                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);CHECKGLERROR
2060         }
2061         // update rectangle texture binding
2062         if (unit->trectangle != 0)
2063         {
2064                 GL_ActiveTexture(unitnum);
2065                 if (unitnum < backendunits)
2066                 {
2067                         if (unit->trectangle)
2068                         {
2069                                 qglDisable(GL_TEXTURE_RECTANGLE_ARB);CHECKGLERROR
2070                         }
2071                 }
2072                 unit->trectangle = 0;
2073                 qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, unit->trectangle);CHECKGLERROR
2074         }
2075 }
2076
2077 void R_Mesh_TexBindCubeMap(unsigned int unitnum, int texnum)
2078 {
2079         gltextureunit_t *unit = gl_state.units + unitnum;
2080         if (unitnum >= backendimageunits)
2081                 return;
2082         // update 1d texture binding
2083         if (unit->t1d)
2084         {
2085                 GL_ActiveTexture(unitnum);
2086                 if (unitnum < backendunits)
2087                 {
2088                         if (unit->t1d)
2089                         {
2090                                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
2091                         }
2092                 }
2093                 unit->t1d = 0;
2094                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);CHECKGLERROR
2095         }
2096         // update 2d texture binding
2097         if (unit->t2d)
2098         {
2099                 GL_ActiveTexture(unitnum);
2100                 if (unitnum < backendunits)
2101                 {
2102                         if (unit->t2d)
2103                         {
2104                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
2105                         }
2106                 }
2107                 unit->t2d = 0;
2108                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR
2109         }
2110         // update 3d texture binding
2111         if (unit->t3d)
2112         {
2113                 GL_ActiveTexture(unitnum);
2114                 if (unitnum < backendunits)
2115                 {
2116                         if (unit->t3d)
2117                         {
2118                                 qglDisable(GL_TEXTURE_3D);CHECKGLERROR
2119                         }
2120                 }
2121                 unit->t3d = 0;
2122                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR
2123         }
2124         // update cubemap texture binding
2125         if (unit->tcubemap != texnum)
2126         {
2127                 GL_ActiveTexture(unitnum);
2128                 if (unitnum < backendunits)
2129                 {
2130                         if (texnum)
2131                         {
2132                                 if (unit->tcubemap == 0)
2133                                 {
2134                                         qglEnable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
2135                                 }
2136                         }
2137                         else
2138                         {
2139                                 if (unit->tcubemap)
2140                                 {
2141                                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
2142                                 }
2143                         }
2144                 }
2145                 unit->tcubemap = texnum;
2146                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);CHECKGLERROR
2147         }
2148         // update rectangle texture binding
2149         if (unit->trectangle != 0)
2150         {
2151                 GL_ActiveTexture(unitnum);
2152                 if (unitnum < backendunits)
2153                 {
2154                         if (unit->trectangle)
2155                         {
2156                                 qglDisable(GL_TEXTURE_RECTANGLE_ARB);CHECKGLERROR
2157                         }
2158                 }
2159                 unit->trectangle = 0;
2160                 qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, unit->trectangle);CHECKGLERROR
2161         }
2162 }
2163
2164 void R_Mesh_TexBindRectangle(unsigned int unitnum, int texnum)
2165 {
2166         gltextureunit_t *unit = gl_state.units + unitnum;
2167         if (unitnum >= backendimageunits)
2168                 return;
2169         // update 1d texture binding
2170         if (unit->t1d)
2171         {
2172                 GL_ActiveTexture(unitnum);
2173                 if (unitnum < backendunits)
2174                 {
2175                         if (unit->t1d)
2176                         {
2177                                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
2178                         }
2179                 }
2180                 unit->t1d = 0;
2181                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);CHECKGLERROR
2182         }
2183         // update 2d texture binding
2184         if (unit->t2d)
2185         {
2186                 GL_ActiveTexture(unitnum);
2187                 if (unitnum < backendunits)
2188                 {
2189                         if (unit->t2d)
2190                         {
2191                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
2192                         }
2193                 }
2194                 unit->t2d = 0;
2195                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR
2196         }
2197         // update 3d texture binding
2198         if (unit->t3d)
2199         {
2200                 GL_ActiveTexture(unitnum);
2201                 if (unitnum < backendunits)
2202                 {
2203                         if (unit->t3d)
2204                         {
2205                                 qglDisable(GL_TEXTURE_3D);CHECKGLERROR
2206                         }
2207                 }
2208                 unit->t3d = 0;
2209                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR
2210         }
2211         // update cubemap texture binding
2212         if (unit->tcubemap != 0)
2213         {
2214                 GL_ActiveTexture(unitnum);
2215                 if (unitnum < backendunits)
2216                 {
2217                         if (unit->tcubemap)
2218                         {
2219                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
2220                         }
2221                 }
2222                 unit->tcubemap = 0;
2223                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);CHECKGLERROR
2224         }
2225         // update rectangle texture binding
2226         if (unit->trectangle != texnum)
2227         {
2228                 GL_ActiveTexture(unitnum);
2229                 if (unitnum < backendunits)
2230                 {
2231                         if (texnum)
2232                         {
2233                                 if (unit->trectangle == 0)
2234                                 {
2235                                         qglEnable(GL_TEXTURE_RECTANGLE_ARB);CHECKGLERROR
2236                                 }
2237                         }
2238                         else
2239                         {
2240                                 if (unit->trectangle)
2241                                 {
2242                                         qglDisable(GL_TEXTURE_RECTANGLE_ARB);CHECKGLERROR
2243                                 }
2244                         }
2245                 }
2246                 unit->trectangle = texnum;
2247                 qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, unit->trectangle);CHECKGLERROR
2248         }
2249 }
2250
2251 static const double gl_identitymatrix[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
2252
2253 void R_Mesh_TexMatrix(unsigned int unitnum, const matrix4x4_t *matrix)
2254 {
2255         gltextureunit_t *unit = gl_state.units + unitnum;
2256         if (matrix->m[3][3])
2257         {
2258                 // texmatrix specified, check if it is different
2259                 if (!unit->texmatrixenabled || memcmp(&unit->matrix, matrix, sizeof(matrix4x4_t)))
2260                 {
2261                         double glmatrix[16];
2262                         unit->texmatrixenabled = true;
2263                         unit->matrix = *matrix;
2264                         CHECKGLERROR
2265                         Matrix4x4_ToArrayDoubleGL(&unit->matrix, glmatrix);
2266                         GL_ActiveTexture(unitnum);
2267                         qglMatrixMode(GL_TEXTURE);CHECKGLERROR
2268                         qglLoadMatrixd(glmatrix);CHECKGLERROR
2269                         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
2270                 }
2271         }
2272         else
2273         {
2274                 // no texmatrix specified, revert to identity
2275                 if (unit->texmatrixenabled)
2276                 {
2277                         unit->texmatrixenabled = false;
2278                         unit->matrix = identitymatrix;
2279                         CHECKGLERROR
2280                         GL_ActiveTexture(unitnum);
2281                         qglMatrixMode(GL_TEXTURE);CHECKGLERROR
2282                         qglLoadIdentity();CHECKGLERROR
2283                         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
2284                 }
2285         }
2286 }
2287
2288 void R_Mesh_TexCombine(unsigned int unitnum, int combinergb, int combinealpha, int rgbscale, int alphascale)
2289 {
2290         gltextureunit_t *unit = gl_state.units + unitnum;
2291         CHECKGLERROR
2292         if (gl_combine.integer)
2293         {
2294                 // GL_ARB_texture_env_combine
2295                 if (!combinergb)
2296                         combinergb = GL_MODULATE;
2297                 if (!combinealpha)
2298                         combinealpha = GL_MODULATE;
2299                 if (!rgbscale)
2300                         rgbscale = 1;
2301                 if (!alphascale)
2302                         alphascale = 1;
2303                 if (unit->combinergb != combinergb)
2304                 {
2305                         unit->combinergb = combinergb;
2306                         GL_ActiveTexture(unitnum);
2307                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
2308                 }
2309                 if (unit->combinealpha != combinealpha)
2310                 {
2311                         unit->combinealpha = combinealpha;
2312                         GL_ActiveTexture(unitnum);
2313                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
2314                 }
2315                 if (unit->rgbscale != rgbscale)
2316                 {
2317                         GL_ActiveTexture(unitnum);
2318                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (unit->rgbscale = rgbscale));CHECKGLERROR
2319                 }
2320                 if (unit->alphascale != alphascale)
2321                 {
2322                         GL_ActiveTexture(unitnum);
2323                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (unit->alphascale = alphascale));CHECKGLERROR
2324                 }
2325         }
2326         else
2327         {
2328                 // normal GL texenv
2329                 if (!combinergb)
2330                         combinergb = GL_MODULATE;
2331                 if (unit->combinergb != combinergb)
2332                 {
2333                         unit->combinergb = combinergb;
2334                         GL_ActiveTexture(unitnum);
2335                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
2336                 }
2337         }
2338 }
2339
2340 void R_Mesh_TextureState(const rmeshstate_t *m)
2341 {
2342         unsigned int i;
2343
2344         BACKENDACTIVECHECK
2345
2346         CHECKGLERROR
2347         if (gl_backend_rebindtextures)
2348         {
2349                 gl_backend_rebindtextures = false;
2350                 GL_SetupTextureState();
2351                 CHECKGLERROR
2352         }
2353
2354         for (i = 0;i < backendimageunits;i++)
2355                 R_Mesh_TexBindAll(i, m->tex1d[i], m->tex[i], m->tex3d[i], m->texcubemap[i], m->texrectangle[i]);
2356         for (i = 0;i < backendarrayunits;i++)
2357         {
2358                 if (m->pointer_texcoord3f[i])
2359                         R_Mesh_TexCoordPointer(i, 3, m->pointer_texcoord3f[i], m->pointer_texcoord_bufferobject[i], m->pointer_texcoord_bufferoffset[i]);
2360                 else
2361                         R_Mesh_TexCoordPointer(i, 2, m->pointer_texcoord[i], m->pointer_texcoord_bufferobject[i], m->pointer_texcoord_bufferoffset[i]);
2362         }
2363         for (i = 0;i < backendunits;i++)
2364         {
2365                 R_Mesh_TexMatrix(i, &m->texmatrix[i]);
2366                 R_Mesh_TexCombine(i, m->texcombinergb[i], m->texcombinealpha[i], m->texrgbscale[i], m->texalphascale[i]);
2367         }
2368         CHECKGLERROR
2369 }
2370
2371 void R_Mesh_ResetTextureState(void)
2372 {
2373         unsigned int unitnum;
2374
2375         BACKENDACTIVECHECK
2376
2377         CHECKGLERROR
2378         if (gl_backend_rebindtextures)
2379         {
2380                 gl_backend_rebindtextures = false;
2381                 GL_SetupTextureState();
2382                 CHECKGLERROR
2383         }
2384
2385         for (unitnum = 0;unitnum < backendimageunits;unitnum++)
2386         {
2387                 gltextureunit_t *unit = gl_state.units + unitnum;
2388                 // update 1d texture binding
2389                 if (unit->t1d)
2390                 {
2391                         GL_ActiveTexture(unitnum);
2392                         if (unitnum < backendunits)
2393                         {
2394                                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
2395                         }
2396                         unit->t1d = 0;
2397                         qglBindTexture(GL_TEXTURE_1D, unit->t1d);CHECKGLERROR
2398                 }
2399                 // update 2d texture binding
2400                 if (unit->t2d)
2401                 {
2402                         GL_ActiveTexture(unitnum);
2403                         if (unitnum < backendunits)
2404                         {
2405                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
2406                         }
2407                         unit->t2d = 0;
2408                         qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR
2409                 }
2410                 // update 3d texture binding
2411                 if (unit->t3d)
2412                 {
2413                         GL_ActiveTexture(unitnum);
2414                         if (unitnum < backendunits)
2415                         {
2416                                 qglDisable(GL_TEXTURE_3D);CHECKGLERROR
2417                         }
2418                         unit->t3d = 0;
2419                         qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR
2420                 }
2421                 // update cubemap texture binding
2422                 if (unit->tcubemap)
2423                 {
2424                         GL_ActiveTexture(unitnum);
2425                         if (unitnum < backendunits)
2426                         {
2427                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
2428                         }
2429                         unit->tcubemap = 0;
2430                         qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);CHECKGLERROR
2431                 }
2432                 // update rectangle texture binding
2433                 if (unit->trectangle)
2434                 {
2435                         GL_ActiveTexture(unitnum);
2436                         if (unitnum < backendunits)
2437                         {
2438                                 qglDisable(GL_TEXTURE_RECTANGLE_ARB);CHECKGLERROR
2439                         }
2440                         unit->trectangle = 0;
2441                         qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, unit->trectangle);CHECKGLERROR
2442                 }
2443         }
2444         for (unitnum = 0;unitnum < backendarrayunits;unitnum++)
2445         {
2446                 gltextureunit_t *unit = gl_state.units + unitnum;
2447                 // texture array unit is disabled, disable the array
2448                 if (unit->arrayenabled)
2449                 {
2450                         unit->arrayenabled = false;
2451                         GL_ClientActiveTexture(unitnum);
2452                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
2453                 }
2454         }
2455         for (unitnum = 0;unitnum < backendunits;unitnum++)
2456         {
2457                 gltextureunit_t *unit = gl_state.units + unitnum;
2458                 // no texmatrix specified, revert to identity
2459                 if (unit->texmatrixenabled)
2460                 {
2461                         unit->texmatrixenabled = false;
2462                         unit->matrix = identitymatrix;
2463                         CHECKGLERROR
2464                         GL_ActiveTexture(unitnum);
2465                         qglMatrixMode(GL_TEXTURE);CHECKGLERROR
2466                         qglLoadIdentity();CHECKGLERROR
2467                         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
2468                 }
2469                 if (gl_combine.integer)
2470                 {
2471                         // GL_ARB_texture_env_combine
2472                         if (unit->combinergb != GL_MODULATE)
2473                         {
2474                                 unit->combinergb = GL_MODULATE;
2475                                 GL_ActiveTexture(unitnum);
2476                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
2477                         }
2478                         if (unit->combinealpha != GL_MODULATE)
2479                         {
2480                                 unit->combinealpha = GL_MODULATE;
2481                                 GL_ActiveTexture(unitnum);
2482                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
2483                         }
2484                         if (unit->rgbscale != 1)
2485                         {
2486                                 GL_ActiveTexture(unitnum);
2487                                 qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (unit->rgbscale = 1));CHECKGLERROR
2488                         }
2489                         if (unit->alphascale != 1)
2490                         {
2491                                 GL_ActiveTexture(unitnum);
2492                                 qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (unit->alphascale = 1));CHECKGLERROR
2493                         }
2494                 }
2495                 else
2496                 {
2497                         // normal GL texenv
2498                         if (unit->combinergb != GL_MODULATE)
2499                         {
2500                                 unit->combinergb = GL_MODULATE;
2501                                 GL_ActiveTexture(unitnum);
2502                                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
2503                         }
2504                 }
2505         }
2506 }