added gl_delayfinish cvar (default off, used to always be on)
[xonotic/darkplaces.git] / gl_backend.c
1
2 #include "quakedef.h"
3 #include "image.h"
4
5 cvar_t gl_mesh_maxverts = {0, "gl_mesh_maxverts", "1024"};
6 cvar_t gl_mesh_floatcolors = {0, "gl_mesh_floatcolors", "1"};
7 cvar_t gl_mesh_drawrangeelements = {0, "gl_mesh_drawrangeelements", "1"};
8 cvar_t gl_delayfinish = {CVAR_SAVE, "gl_delayfinish", "0"};
9
10 cvar_t r_render = {0, "r_render", "1"};
11 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1"}; // whether or not to use dithering
12 cvar_t gl_lockarrays = {0, "gl_lockarrays", "1"};
13
14 int gl_maxdrawrangeelementsvertices;
15 int gl_maxdrawrangeelementsindices;
16
17 #ifdef DEBUGGL
18 int errornumber = 0;
19
20 void GL_PrintError(int errornumber, char *filename, int linenumber)
21 {
22         switch(errornumber)
23         {
24 #ifdef GL_INVALID_ENUM
25         case GL_INVALID_ENUM:
26                 Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
27                 break;
28 #endif
29 #ifdef GL_INVALID_VALUE
30         case GL_INVALID_VALUE:
31                 Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
32                 break;
33 #endif
34 #ifdef GL_INVALID_OPERATION
35         case GL_INVALID_OPERATION:
36                 Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
37                 break;
38 #endif
39 #ifdef GL_STACK_OVERFLOW
40         case GL_STACK_OVERFLOW:
41                 Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
42                 break;
43 #endif
44 #ifdef GL_STACK_UNDERFLOW
45         case GL_STACK_UNDERFLOW:
46                 Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
47                 break;
48 #endif
49 #ifdef GL_OUT_OF_MEMORY
50         case GL_OUT_OF_MEMORY:
51                 Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
52                 break;
53 #endif
54 #ifdef GL_TABLE_TOO_LARGE
55         case GL_TABLE_TOO_LARGE:
56                 Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
57                 break;
58 #endif
59         default:
60                 Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
61                 break;
62         }
63 }
64 #endif
65
66 #define BACKENDACTIVECHECK if (!backendactive) Sys_Error("GL backend function called when backend is not active\n");
67
68 int c_meshs, c_meshelements;
69
70 void SCR_ScreenShot_f (void);
71
72 // these are externally accessible
73 int r_lightmapscalebit;
74 float r_colorscale;
75 float *varray_vertex;
76 float *varray_color;
77 float *varray_texcoord[MAX_TEXTUREUNITS];
78 int mesh_maxverts;
79
80 static matrix4x4_t backend_viewmatrix;
81 static matrix4x4_t backend_modelmatrix;
82 static matrix4x4_t backend_modelviewmatrix;
83 static matrix4x4_t backend_glmodelviewmatrix;
84 static matrix4x4_t backend_projectmatrix;
85
86 static int backendunits, backendactive;
87 static qbyte *varray_bcolor;
88 static mempool_t *gl_backend_mempool;
89
90 /*
91 note: here's strip order for a terrain row:
92 0--1--2--3--4
93 |\ |\ |\ |\ |
94 | \| \| \| \|
95 A--B--C--D--E
96
97 A0B, 01B, B1C, 12C, C2D, 23D, D3E, 34E
98
99 *elements++ = i + row;
100 *elements++ = i;
101 *elements++ = i + row + 1;
102 *elements++ = i;
103 *elements++ = i + 1;
104 *elements++ = i + row + 1;
105 */
106
107 int polygonelements[768];
108
109 void GL_Backend_AllocArrays(void)
110 {
111         int i;
112
113         for (i = 0;i < POLYGONELEMENTS_MAXPOINTS - 2;i++)
114         {
115                 polygonelements[i * 3 + 0] = 0;
116                 polygonelements[i * 3 + 1] = i + 1;
117                 polygonelements[i * 3 + 2] = i + 2;
118         }
119
120         if (!gl_backend_mempool)
121                 gl_backend_mempool = Mem_AllocPool("GL_Backend");
122
123         varray_vertex = Mem_Alloc(gl_backend_mempool, mesh_maxverts * sizeof(float[4]));
124         varray_color = Mem_Alloc(gl_backend_mempool, mesh_maxverts * sizeof(float[4]));
125         varray_bcolor = Mem_Alloc(gl_backend_mempool, mesh_maxverts * sizeof(qbyte[4]));
126         for (i = 0;i < backendunits;i++)
127                 varray_texcoord[i] = Mem_Alloc(gl_backend_mempool, mesh_maxverts * sizeof(float[4]));
128         for (;i < MAX_TEXTUREUNITS;i++)
129                 varray_texcoord[i] = NULL;
130 }
131
132 void GL_Backend_FreeArrays(int resizingbuffers)
133 {
134         int i;
135         if (resizingbuffers)
136                 Mem_EmptyPool(gl_backend_mempool);
137         else
138                 Mem_FreePool(&gl_backend_mempool);
139         varray_vertex = NULL;
140         varray_color = NULL;
141         varray_bcolor = NULL;
142         for (i = 0;i < MAX_TEXTUREUNITS;i++)
143                 varray_texcoord[i] = NULL;
144 }
145
146 static void gl_backend_start(void)
147 {
148         Con_Printf("OpenGL Backend started with gl_mesh_maxverts %i\n", gl_mesh_maxverts.integer);
149         if (qglDrawRangeElements != NULL)
150         {
151                 qglGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &gl_maxdrawrangeelementsvertices);
152                 qglGetIntegerv(GL_MAX_ELEMENTS_INDICES, &gl_maxdrawrangeelementsindices);
153                 CHECKGLERROR
154                 Con_Printf("glDrawRangeElements detected (max vertices %i, max indices %i)\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
155         }
156         if (strstr(gl_renderer, "3Dfx"))
157         {
158                 Con_Printf("3Dfx driver detected, forcing gl_mesh_floatcolors to 0 to prevent crashs\n");
159                 Cvar_SetValueQuick(&gl_mesh_floatcolors, 0);
160         }
161
162         backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
163
164         GL_Backend_AllocArrays();
165
166         backendactive = true;
167 }
168
169 static void gl_backend_shutdown(void)
170 {
171         backendunits = 0;
172         backendactive = false;
173
174         Con_Printf("OpenGL Backend shutting down\n");
175
176         GL_Backend_FreeArrays(false);
177 }
178
179 void GL_Backend_CheckCvars(void)
180 {
181         // 21760 is (65536 / 3) rounded off to a multiple of 128
182         if (gl_mesh_maxverts.integer < 1024)
183                 Cvar_SetValueQuick(&gl_mesh_maxverts, 1024);
184         if (gl_mesh_maxverts.integer > 21760)
185                 Cvar_SetValueQuick(&gl_mesh_maxverts, 21760);
186 }
187
188 void GL_Backend_ResizeArrays(int numtriangles)
189 {
190         Cvar_SetValueQuick(&gl_mesh_maxverts, numtriangles);
191         GL_Backend_CheckCvars();
192         mesh_maxverts = gl_mesh_maxverts.integer;
193         GL_Backend_FreeArrays(true);
194         GL_Backend_AllocArrays();
195 }
196
197 static void gl_backend_newmap(void)
198 {
199 }
200
201 void gl_backend_init(void)
202 {
203         Cvar_RegisterVariable(&r_render);
204         Cvar_RegisterVariable(&gl_dither);
205         Cvar_RegisterVariable(&gl_lockarrays);
206         Cvar_RegisterVariable(&gl_delayfinish);
207 #ifdef NORENDER
208         Cvar_SetValue("r_render", 0);
209 #endif
210
211         Cvar_RegisterVariable(&gl_mesh_maxverts);
212         Cvar_RegisterVariable(&gl_mesh_floatcolors);
213         Cvar_RegisterVariable(&gl_mesh_drawrangeelements);
214         GL_Backend_CheckCvars();
215         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
216 }
217
218 void GL_SetupView_ViewPort (int x, int y, int width, int height)
219 {
220         if (!r_render.integer)
221                 return;
222
223         // y is weird beause OpenGL is bottom to top, we use top to bottom
224         qglViewport(x, vid.realheight - (y + height), width, height);
225         CHECKGLERROR
226 }
227
228 void GL_SetupView_Orientation_Identity (void)
229 {
230         Matrix4x4_CreateIdentity(&backend_viewmatrix);
231         memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
232 }
233
234 void GL_SetupView_Orientation_FromEntity (vec3_t origin, vec3_t angles)
235 {
236         Matrix4x4_CreateRotate(&backend_viewmatrix, -90, 1, 0, 0);
237         Matrix4x4_ConcatRotate(&backend_viewmatrix, 90, 0, 0, 1);
238         Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[2], 1, 0, 0);
239         Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[0], 0, 1, 0);
240         Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[1], 0, 0, 1);
241         Matrix4x4_ConcatTranslate(&backend_viewmatrix, -origin[0], -origin[1], -origin[2]);
242         memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
243 }
244
245 void GL_SetupView_Mode_Perspective (double fovx, double fovy, double zNear, double zFar)
246 {
247         double xmax, ymax;
248
249         if (!r_render.integer)
250                 return;
251
252         // set up viewpoint
253         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
254         qglLoadIdentity();CHECKGLERROR
255         // pyramid slopes
256         xmax = zNear * tan(fovx * M_PI / 360.0);
257         ymax = zNear * tan(fovy * M_PI / 360.0);
258         // set view pyramid
259         qglFrustum(-xmax, xmax, -ymax, ymax, zNear, zFar);CHECKGLERROR
260         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
261         GL_SetupView_Orientation_Identity();
262 }
263
264 void GL_SetupView_Mode_PerspectiveInfiniteFarClip (double fovx, double fovy, double zNear)
265 {
266         float nudge, m[16];
267
268         if (!r_render.integer)
269                 return;
270
271         // set up viewpoint
272         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
273         qglLoadIdentity();CHECKGLERROR
274         // set view pyramid
275         nudge = 1.0 - 1.0 / (1<<23);
276         m[ 0] = 1.0 / tan(fovx * M_PI / 360.0);
277         m[ 1] = 0;
278         m[ 2] = 0;
279         m[ 3] = 0;
280         m[ 4] = 0;
281         m[ 5] = 1.0 / tan(fovy * M_PI / 360.0);
282         m[ 6] = 0;
283         m[ 7] = 0;
284         m[ 8] = 0;
285         m[ 9] = 0;
286         m[10] = -1 * nudge;
287         m[11] = -1 * nudge;
288         m[12] = 0;
289         m[13] = 0;
290         m[14] = -2 * zNear * nudge;
291         m[15] = 0;
292         qglLoadMatrixf(m);
293         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
294         GL_SetupView_Orientation_Identity();
295         backend_projectmatrix.m[0][0] = m[0];
296         backend_projectmatrix.m[1][0] = m[1];
297         backend_projectmatrix.m[2][0] = m[2];
298         backend_projectmatrix.m[3][0] = m[3];
299         backend_projectmatrix.m[0][1] = m[4];
300         backend_projectmatrix.m[1][1] = m[5];
301         backend_projectmatrix.m[2][1] = m[6];
302         backend_projectmatrix.m[3][1] = m[7];
303         backend_projectmatrix.m[0][2] = m[8];
304         backend_projectmatrix.m[1][2] = m[9];
305         backend_projectmatrix.m[2][2] = m[10];
306         backend_projectmatrix.m[3][2] = m[11];
307         backend_projectmatrix.m[0][3] = m[12];
308         backend_projectmatrix.m[1][3] = m[13];
309         backend_projectmatrix.m[2][3] = m[14];
310         backend_projectmatrix.m[3][3] = m[15];
311 }
312
313 void GL_SetupView_Mode_Ortho (double x1, double y1, double x2, double y2, double zNear, double zFar)
314 {
315         if (!r_render.integer)
316                 return;
317
318         // set up viewpoint
319         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
320         qglLoadIdentity();CHECKGLERROR
321         qglOrtho(x1, x2, y2, y1, zNear, zFar);
322         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
323         GL_SetupView_Orientation_Identity();
324 }
325
326 typedef struct gltextureunit_s
327 {
328         int t1d, t2d, t3d, tcubemap;
329         int arrayenabled;
330         float rgbscale, alphascale;
331         int combinergb, combinealpha;
332         // FIXME: add more combine stuff
333 }
334 gltextureunit_t;
335
336 static struct
337 {
338         int blendfunc1;
339         int blendfunc2;
340         int blend;
341         GLboolean depthmask;
342         int depthdisable;
343         int unit;
344         int clientunit;
345         gltextureunit_t units[MAX_TEXTUREUNITS];
346         int colorarray;
347 }
348 gl_state;
349
350 void GL_SetupTextureState(void)
351 {
352         int i;
353         gltextureunit_t *unit;
354         for (i = 0;i < backendunits;i++)
355         {
356                 if (qglActiveTexture)
357                         qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
358                 if (qglClientActiveTexture)
359                         qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
360                 unit = gl_state.units + i;
361                 unit->t1d = 0;
362                 unit->t2d = 0;
363                 unit->t3d = 0;
364                 unit->tcubemap = 0;
365                 unit->rgbscale = 1;
366                 unit->alphascale = 1;
367                 unit->combinergb = GL_MODULATE;
368                 unit->combinealpha = GL_MODULATE;
369                 unit->arrayenabled = false;
370                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
371                 if (gl_texture3d || gl_texturecubemap)
372                 {
373                         qglTexCoordPointer(3, GL_FLOAT, sizeof(float[4]), varray_texcoord[i]);CHECKGLERROR
374                 }
375                 else
376                 {
377                         qglTexCoordPointer(2, GL_FLOAT, sizeof(float[4]), varray_texcoord[i]);CHECKGLERROR
378                 }
379                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
380                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
381                 if (gl_texture3d)
382                 {
383                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
384                 }
385                 if (gl_texturecubemap)
386                 {
387                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
388                 }
389                 if (gl_combine.integer)
390                 {
391                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
392                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);CHECKGLERROR
393                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);CHECKGLERROR
394                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
395                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_CONSTANT_ARB);CHECKGLERROR
396                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
397                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
398                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB_ARB, GL_SRC_ALPHA);CHECKGLERROR
399                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);CHECKGLERROR
400                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE);CHECKGLERROR
401                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
402                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA_ARB, GL_CONSTANT_ARB);CHECKGLERROR
403                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
404                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
405                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
406                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
407                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
408                 }
409                 else
410                 {
411                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
412                 }
413         }
414 }
415
416 void GL_Backend_ResetState(void)
417 {
418         memset(&gl_state, 0, sizeof(gl_state));
419         gl_state.depthdisable = false;
420         gl_state.blendfunc1 = GL_ONE;
421         gl_state.blendfunc2 = GL_ZERO;
422         gl_state.blend = false;
423         gl_state.depthmask = GL_TRUE;
424         gl_state.colorarray = false;
425
426         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
427         qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
428
429         qglEnable(GL_CULL_FACE);CHECKGLERROR
430         qglCullFace(GL_FRONT);CHECKGLERROR
431         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
432         qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
433         qglDisable(GL_BLEND);CHECKGLERROR
434         qglDepthMask(gl_state.depthmask);CHECKGLERROR
435         qglVertexPointer(3, GL_FLOAT, sizeof(float[4]), varray_vertex);CHECKGLERROR
436         qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
437         if (gl_mesh_floatcolors.integer)
438         {
439                 qglColorPointer(4, GL_FLOAT, sizeof(float[4]), varray_color);CHECKGLERROR
440         }
441         else
442         {
443                 qglColorPointer(4, GL_UNSIGNED_BYTE, sizeof(qbyte[4]), varray_bcolor);CHECKGLERROR
444         }
445         GL_Color(1, 1, 1, 1);
446
447         GL_SetupTextureState();
448 }
449
450 void GL_UseColorArray(void)
451 {
452         if (!gl_state.colorarray)
453         {
454                 gl_state.colorarray = true;
455                 qglEnableClientState(GL_COLOR_ARRAY);CHECKGLERROR
456         }
457 }
458
459 void GL_Color(float cr, float cg, float cb, float ca)
460 {
461         if (gl_state.colorarray)
462         {
463                 gl_state.colorarray = false;
464                 qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
465         }
466         qglColor4f(cr, cg, cb, ca);
467 }
468
469 void GL_TransformToScreen(const vec4_t in, vec4_t out)
470 {
471         vec4_t temp;
472         float iw;
473         Matrix4x4_Transform4 (&backend_viewmatrix, in, temp);
474         Matrix4x4_Transform4 (&backend_projectmatrix, temp, out);
475         iw = 1.0f / out[3];
476         out[0] = r_refdef.x + (out[0] * iw + 1.0f) * r_refdef.width * 0.5f;
477         out[1] = r_refdef.y + (out[1] * iw + 1.0f) * r_refdef.height * 0.5f;
478         out[2] = out[2] * iw;
479 }
480
481 // called at beginning of frame
482 void R_Mesh_Start(void)
483 {
484         BACKENDACTIVECHECK
485
486         CHECKGLERROR
487
488         GL_Backend_CheckCvars();
489         if (mesh_maxverts != gl_mesh_maxverts.integer)
490                 GL_Backend_ResizeArrays(gl_mesh_maxverts.integer);
491
492         GL_Backend_ResetState();
493 }
494
495 int gl_backend_rebindtextures;
496
497 void GL_ConvertColorsFloatToByte(int numverts)
498 {
499         int i, k, total;
500         // LordHavoc: to avoid problems with aliasing (treating memory as two
501         // different types - exactly what this is doing), these must be volatile
502         // (or a union)
503         volatile int *icolor;
504         volatile float *fcolor;
505         qbyte *bcolor;
506
507         total = numverts * 4;
508
509         // shift float to have 8bit fraction at base of number
510         fcolor = varray_color;
511         for (i = 0;i < total;)
512         {
513                 fcolor[i    ] += 32768.0f;
514                 fcolor[i + 1] += 32768.0f;
515                 fcolor[i + 2] += 32768.0f;
516                 fcolor[i + 3] += 32768.0f;
517                 i += 4;
518         }
519
520         // then read as integer and kill float bits...
521         icolor = (int *)varray_color;
522         bcolor = varray_bcolor;
523         for (i = 0;i < total;)
524         {
525                 k = icolor[i    ] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i    ] = (qbyte) k;
526                 k = icolor[i + 1] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 1] = (qbyte) k;
527                 k = icolor[i + 2] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 2] = (qbyte) k;
528                 k = icolor[i + 3] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 3] = (qbyte) k;
529                 i += 4;
530         }
531 }
532
533 // enlarges geometry buffers if they are too small
534 void _R_Mesh_ResizeCheck(int numverts)
535 {
536         if (numverts > mesh_maxverts)
537         {
538                 BACKENDACTIVECHECK
539                 GL_Backend_ResizeArrays(numverts + 100);
540                 GL_Backend_ResetState();
541         }
542 }
543
544 // renders the mesh
545 void R_Mesh_Draw(int numverts, int numtriangles, const int *elements)
546 {
547         int numelements;
548         if (numtriangles == 0 || numverts == 0)
549         {
550                 Con_Printf("R_Mesh_Draw(%d, %d, %08p);\n", numverts, numtriangles, elements);
551                 return;
552         }
553         numelements = numtriangles * 3;
554         c_meshs++;
555         c_meshelements += numelements;
556         if (gl_state.colorarray && !gl_mesh_floatcolors.integer)
557                 GL_ConvertColorsFloatToByte(numverts);
558         if (!r_render.integer)
559                 return;
560         if (gl_supportslockarrays && gl_lockarrays.integer)
561         {
562                 qglLockArraysEXT(0, numverts);
563                 CHECKGLERROR
564                 if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
565                         qglDrawRangeElements(GL_TRIANGLES, 0, numverts, numelements, GL_UNSIGNED_INT, (const GLuint *) elements);
566                 else
567                         qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, (const GLuint *) elements);
568                 CHECKGLERROR
569                 qglUnlockArraysEXT();
570                 CHECKGLERROR
571         }
572         else
573         {
574                 qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, (const GLuint *) elements);
575                 CHECKGLERROR
576         }
577 }
578
579 // restores backend state, used when done with 3D rendering
580 void R_Mesh_Finish(void)
581 {
582         int i;
583         BACKENDACTIVECHECK
584
585         for (i = backendunits - 1;i >= 0;i--)
586         {
587                 if (qglActiveTexture)
588                         qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
589                 if (qglClientActiveTexture)
590                         qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
591                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
592                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
593                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
594                 if (gl_texture3d)
595                 {
596                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
597                 }
598                 if (gl_texturecubemap)
599                 {
600                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
601                 }
602                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
603                 if (gl_combine.integer)
604                 {
605                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
606                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
607                 }
608         }
609         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
610         qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
611
612         qglDisable(GL_BLEND);CHECKGLERROR
613         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
614         qglDepthMask(GL_TRUE);CHECKGLERROR
615         qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
616 }
617
618 void R_Mesh_Matrix(const matrix4x4_t *matrix)
619 {
620         if (memcmp(matrix, &backend_modelmatrix, sizeof(matrix4x4_t)))
621         {
622                 backend_modelmatrix = *matrix;
623                 Matrix4x4_Concat(&backend_modelviewmatrix, &backend_viewmatrix, matrix);
624                 Matrix4x4_Transpose(&backend_glmodelviewmatrix, &backend_modelviewmatrix);
625                 qglLoadMatrixf(&backend_glmodelviewmatrix.m[0][0]);
626         }
627 }
628
629 // sets up the requested state
630 void R_Mesh_MainState(const rmeshstate_t *m)
631 {
632         BACKENDACTIVECHECK
633
634         if (gl_state.blendfunc1 != m->blendfunc1 || gl_state.blendfunc2 != m->blendfunc2)
635         {
636                 qglBlendFunc(gl_state.blendfunc1 = m->blendfunc1, gl_state.blendfunc2 = m->blendfunc2);CHECKGLERROR
637                 if (gl_state.blendfunc2 == GL_ZERO)
638                 {
639                         if (gl_state.blendfunc1 == GL_ONE)
640                         {
641                                 if (gl_state.blend)
642                                 {
643                                         gl_state.blend = 0;
644                                         qglDisable(GL_BLEND);CHECKGLERROR
645                                 }
646                         }
647                         else
648                         {
649                                 if (!gl_state.blend)
650                                 {
651                                         gl_state.blend = 1;
652                                         qglEnable(GL_BLEND);CHECKGLERROR
653                                 }
654                         }
655                 }
656                 else
657                 {
658                         if (!gl_state.blend)
659                         {
660                                 gl_state.blend = 1;
661                                 qglEnable(GL_BLEND);CHECKGLERROR
662                         }
663                 }
664         }
665         if (gl_state.depthdisable != m->depthdisable)
666         {
667                 gl_state.depthdisable = m->depthdisable;
668                 if (gl_state.depthdisable)
669                         qglDisable(GL_DEPTH_TEST);
670                 else
671                         qglEnable(GL_DEPTH_TEST);
672         }
673         if (gl_state.depthmask != (m->blendfunc2 == GL_ZERO || m->depthwrite))
674         {
675                 qglDepthMask(gl_state.depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite));CHECKGLERROR
676         }
677 }
678
679 void R_Mesh_TextureState(const rmeshstate_t *m)
680 {
681         int i, combinergb, combinealpha;
682         float scale;
683         gltextureunit_t *unit;
684
685         BACKENDACTIVECHECK
686
687         if (gl_backend_rebindtextures)
688         {
689                 gl_backend_rebindtextures = false;
690                 GL_SetupTextureState();
691         }
692
693         for (i = 0;i < backendunits;i++)
694         {
695                 unit = gl_state.units + i;
696                 if (unit->t1d != m->tex1d[i] || unit->t2d != m->tex[i] || unit->t3d != m->tex3d[i] || unit->tcubemap != m->texcubemap[i])
697                 {
698                         if (gl_state.unit != i)
699                         {
700                                 qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
701                         }
702                         if (m->tex1d[i] || m->tex[i] || m->tex3d[i] || m->texcubemap[i])
703                         {
704                                 if (!unit->arrayenabled)
705                                 {
706                                         unit->arrayenabled = true;
707                                         if (gl_state.clientunit != i)
708                                         {
709                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
710                                         }
711                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
712                                 }
713                         }
714                         else
715                         {
716                                 if (unit->arrayenabled)
717                                 {
718                                         unit->arrayenabled = false;
719                                         if (gl_state.clientunit != i)
720                                         {
721                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
722                                         }
723                                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
724                                 }
725                         }
726                         combinergb = m->texcombinergb[i];
727                         combinealpha = m->texcombinealpha[i];
728                         if (!combinergb)
729                                 combinergb = GL_MODULATE;
730                         if (!combinealpha)
731                                 combinealpha = GL_MODULATE;
732                         if (unit->combinergb != combinergb)
733                         {
734                                 unit->combinergb = combinergb;
735                                 if (gl_combine.integer)
736                                 {
737                                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
738                                 }
739                                 else
740                                 {
741                                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
742                                 }
743                         }
744                         if (unit->combinealpha != combinealpha)
745                         {
746                                 unit->combinealpha = combinealpha;
747                                 if (gl_combine.integer)
748                                 {
749                                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
750                                 }
751                         }
752                         if (unit->t1d != m->tex1d[i])
753                         {
754                                 if (m->tex1d[i])
755                                 {
756                                         if (unit->t1d == 0)
757                                                 qglEnable(GL_TEXTURE_1D);CHECKGLERROR
758                                 }
759                                 else
760                                 {
761                                         if (unit->t1d)
762                                                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
763                                 }
764                                 qglBindTexture(GL_TEXTURE_1D, (unit->t1d = m->tex1d[i]));CHECKGLERROR
765                         }
766                         if (unit->t2d != m->tex[i])
767                         {
768                                 if (m->tex[i])
769                                 {
770                                         if (unit->t2d == 0)
771                                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
772                                 }
773                                 else
774                                 {
775                                         if (unit->t2d)
776                                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
777                                 }
778                                 qglBindTexture(GL_TEXTURE_2D, (unit->t2d = m->tex[i]));CHECKGLERROR
779                         }
780                         if (unit->t3d != m->tex3d[i])
781                         {
782                                 if (m->tex3d[i])
783                                 {
784                                         if (unit->t3d == 0)
785                                                 qglEnable(GL_TEXTURE_3D);CHECKGLERROR
786                                 }
787                                 else
788                                 {
789                                         if (unit->t3d)
790                                                 qglDisable(GL_TEXTURE_3D);CHECKGLERROR
791                                 }
792                                 qglBindTexture(GL_TEXTURE_3D, (unit->t3d = m->tex3d[i]));CHECKGLERROR
793                         }
794                         if (unit->tcubemap != m->texcubemap[i])
795                         {
796                                 if (m->texcubemap[i])
797                                 {
798                                         if (unit->tcubemap == 0)
799                                                 qglEnable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
800                                 }
801                                 else
802                                 {
803                                         if (unit->tcubemap)
804                                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
805                                 }
806                                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, (unit->tcubemap = m->texcubemap[i]));CHECKGLERROR
807                         }
808                 }
809                 scale = max(m->texrgbscale[i], 1);
810                 if (gl_state.units[i].rgbscale != scale)
811                 {
812                         if (gl_state.unit != i)
813                         {
814                                 qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
815                         }
816                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (gl_state.units[i].rgbscale = scale));CHECKGLERROR
817                 }
818                 scale = max(m->texalphascale[i], 1);
819                 if (gl_state.units[i].alphascale != scale)
820                 {
821                         if (gl_state.unit != i)
822                         {
823                                 qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
824                         }
825                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (gl_state.units[i].alphascale = scale));CHECKGLERROR
826                 }
827         }
828 }
829
830 void R_Mesh_State(const rmeshstate_t *m)
831 {
832         R_Mesh_MainState(m);
833         R_Mesh_TextureState(m);
834 }
835
836 /*
837 ==============================================================================
838
839                                                 SCREEN SHOTS
840
841 ==============================================================================
842 */
843
844 qboolean SCR_ScreenShot(char *filename, int x, int y, int width, int height)
845 {
846         qboolean ret;
847         int i, j;
848         qbyte *buffer;
849
850         if (!r_render.integer)
851                 return false;
852
853         buffer = Mem_Alloc(tempmempool, width*height*3);
854         qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
855         CHECKGLERROR
856
857         // LordHavoc: compensate for v_overbrightbits when using hardware gamma
858         if (v_hwgamma.integer)
859         {
860                 for (i = 0;i < width * height * 3;i++)
861                 {
862                         j = buffer[i] << v_overbrightbits.integer;
863                         buffer[i] = (qbyte) (bound(0, j, 255));
864                 }
865         }
866
867         ret = Image_WriteTGARGB_preflipped(filename, width, height, buffer);
868
869         Mem_Free(buffer);
870         return ret;
871 }
872
873 //=============================================================================
874
875 void R_ClearScreen(void)
876 {
877         if (r_render.integer)
878         {
879                 // clear to black
880                 qglClearColor(0,0,0,0);CHECKGLERROR
881                 qglClearDepth(1);CHECKGLERROR
882                 if (gl_stencil)
883                 {
884                         // LordHavoc: we use a stencil centered around 128 instead of 0,
885                         // to avoid clamping interfering with strange shadow volume
886                         // drawing orders
887                         qglClearStencil(128);CHECKGLERROR
888                 }
889                 // clear the screen
890                 qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (gl_stencil ? GL_STENCIL_BUFFER_BIT : 0));CHECKGLERROR
891                 // set dithering mode
892                 if (gl_dither.integer)
893                 {
894                         qglEnable(GL_DITHER);CHECKGLERROR
895                 }
896                 else
897                 {
898                         qglDisable(GL_DITHER);CHECKGLERROR
899                 }
900         }
901 }
902
903 /*
904 ==================
905 SCR_UpdateScreen
906
907 This is called every frame, and can also be called explicitly to flush
908 text to the screen.
909 ==================
910 */
911 void SCR_UpdateScreen (void)
912 {
913         if (gl_delayfinish.integer)
914         {
915                 VID_Finish ();
916
917                 R_TimeReport("finish");
918         }
919
920         if (r_textureunits.integer > gl_textureunits)
921                 Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
922         if (r_textureunits.integer < 1)
923                 Cvar_SetValueQuick(&r_textureunits, 1);
924
925         if (gl_combine.integer && (!gl_combine_extension || r_textureunits.integer < 2))
926                 Cvar_SetValueQuick(&gl_combine, 0);
927
928         // lighting scale
929         r_colorscale = 1.0f / (float) (1 << v_overbrightbits.integer);
930
931         // lightmaps only
932         r_lightmapscalebit = v_overbrightbits.integer;
933         if (gl_combine.integer && r_textureunits.integer > 1)
934                 r_lightmapscalebit += 2;
935
936         R_TimeReport("setup");
937
938         R_ClearScreen();
939
940         R_TimeReport("clear");
941
942         if (scr_conlines < vid.conheight && cls.signon == SIGNONS)
943                 R_RenderView();
944
945         // draw 2D stuff
946         R_DrawQueue();
947
948         if (gl_delayfinish.integer)
949         {
950                 // tell driver to commit it's partially full geometry queue to the rendering queue
951                 // (this doesn't wait for the commands themselves to complete)
952                 qglFlush();
953         }
954         else
955         {
956                 VID_Finish ();
957
958                 R_TimeReport("finish");
959         }
960 }
961