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