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