moved state update from R_Mesh_Render to R_Mesh_Draw_GetBuffer
[divverent/darkplaces.git] / gl_backend.c
1
2 #include "quakedef.h"
3
4 cvar_t gl_mesh_maxtriangles = {0, "gl_mesh_maxtriangles", "1024"};
5 cvar_t gl_mesh_floatcolors = {0, "gl_mesh_floatcolors", "1"};
6 cvar_t gl_mesh_drawmode = {CVAR_SAVE, "gl_mesh_drawmode", "3"};
7
8 cvar_t r_render = {0, "r_render", "1"};
9 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1"}; // whether or not to use dithering
10 cvar_t gl_lockarrays = {0, "gl_lockarrays", "1"};
11
12 // this is used to increase gl_mesh_maxtriangles automatically if a mesh was
13 // too large for the buffers in the previous frame
14 int overflowedverts = 0;
15
16 int gl_maxdrawrangeelementsvertices;
17 int gl_maxdrawrangeelementsindices;
18
19 #ifdef DEBUGGL
20 int errornumber = 0;
21
22 void GL_PrintError(int errornumber, char *filename, int linenumber)
23 {
24         switch(errornumber)
25         {
26 #ifdef GL_INVALID_ENUM
27         case GL_INVALID_ENUM:
28                 Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
29                 break;
30 #endif
31 #ifdef GL_INVALID_VALUE
32         case GL_INVALID_VALUE:
33                 Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
34                 break;
35 #endif
36 #ifdef GL_INVALID_OPERATION
37         case GL_INVALID_OPERATION:
38                 Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
39                 break;
40 #endif
41 #ifdef GL_STACK_OVERFLOW
42         case GL_STACK_OVERFLOW:
43                 Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
44                 break;
45 #endif
46 #ifdef GL_STACK_UNDERFLOW
47         case GL_STACK_UNDERFLOW:
48                 Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
49                 break;
50 #endif
51 #ifdef GL_OUT_OF_MEMORY
52         case GL_OUT_OF_MEMORY:
53                 Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
54                 break;
55 #endif
56 #ifdef GL_TABLE_TOO_LARGE
57     case GL_TABLE_TOO_LARGE:
58                 Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
59                 break;
60 #endif
61         default:
62                 Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
63                 break;
64         }
65 }
66 #endif
67
68 float r_mesh_farclip;
69
70 static float viewdist;
71 // sign bits (true if negative) for vpn[] entries, so quick integer compares can be used instead of float compares
72 static int vpnbit0, vpnbit1, vpnbit2;
73
74 int c_meshs, c_meshtris;
75
76 int lightscalebit;
77 float lightscale;
78 float overbrightscale;
79
80 void SCR_ScreenShot_f (void);
81
82 static int max_tris;
83 static int max_verts; // always max_tris * 3
84
85 typedef struct buf_mesh_s
86 {
87         int depthmask;
88         int depthtest;
89         int blendfunc1, blendfunc2;
90         int textures[MAX_TEXTUREUNITS];
91         int texturergbscale[MAX_TEXTUREUNITS];
92         int firsttriangle;
93         int triangles;
94         int firstvert;
95         int verts;
96         matrix4x4_t matrix;
97         struct buf_mesh_s *chain;
98 }
99 buf_mesh_t;
100
101 typedef struct buf_tri_s
102 {
103         int index[3];
104 }
105 buf_tri_t;
106
107 typedef struct
108 {
109         float v[4];
110 }
111 buf_vertex_t;
112
113 typedef struct
114 {
115         float c[4];
116 }
117 buf_fcolor_t;
118
119 typedef struct
120 {
121         qbyte c[4];
122 }
123 buf_bcolor_t;
124
125 typedef struct
126 {
127         float t[2];
128 }
129 buf_texcoord_t;
130
131 static int currenttriangle, currentvertex, backendunits, backendactive;
132 static buf_mesh_t buf_mesh;
133 static buf_tri_t *buf_tri;
134 static buf_vertex_t *buf_vertex;
135 static buf_fcolor_t *buf_fcolor;
136 static buf_bcolor_t *buf_bcolor;
137 static buf_texcoord_t *buf_texcoord[MAX_TEXTUREUNITS];
138
139 static mempool_t *gl_backend_mempool;
140 static int resizingbuffers = false;
141
142 static void gl_backend_start(void)
143 {
144         int i;
145
146         qglGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &gl_maxdrawrangeelementsvertices);
147         qglGetIntegerv(GL_MAX_ELEMENTS_INDICES, &gl_maxdrawrangeelementsindices);
148
149         Con_Printf("OpenGL Backend started with gl_mesh_maxtriangles %i\n", gl_mesh_maxtriangles.integer);
150         if (qglDrawRangeElements != NULL)
151                 Con_Printf("glDrawRangeElements detected (max vertices %i, max indices %i)\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
152         if (strstr(gl_renderer, "3Dfx"))
153         {
154                 Con_Printf("3Dfx driver detected, forcing gl_mesh_floatcolors to 0 to prevent crashs\n");
155                 Cvar_SetValueQuick(&gl_mesh_floatcolors, 0);
156         }
157         Con_Printf("\n");
158
159         max_verts = max_tris * 3;
160
161         if (!gl_backend_mempool)
162                 gl_backend_mempool = Mem_AllocPool("GL_Backend");
163
164 #define BACKENDALLOC(var, count, sizeofstruct, varname)\
165         {\
166                 var = Mem_Alloc(gl_backend_mempool, count * sizeof(sizeofstruct));\
167                 if (var == NULL)\
168                         Sys_Error("gl_backend_start: unable to allocate memory for %s (%d bytes)\n", (varname), count * sizeof(sizeofstruct));\
169                 memset(var, 0, count * sizeof(sizeofstruct));\
170         }
171
172         BACKENDALLOC(buf_tri, max_tris, buf_tri_t, "buf_tri")
173         BACKENDALLOC(buf_vertex, max_verts, buf_vertex_t, "buf_vertex")
174         BACKENDALLOC(buf_fcolor, max_verts, buf_fcolor_t, "buf_fcolor")
175         BACKENDALLOC(buf_bcolor, max_verts, buf_bcolor_t, "buf_bcolor")
176
177         for (i = 0;i < MAX_TEXTUREUNITS;i++)
178         {
179                 // only allocate as many texcoord arrays as we need
180                 if (i < gl_textureunits)
181                 {
182                         BACKENDALLOC(buf_texcoord[i], max_verts, buf_texcoord_t, va("buf_texcoord[%d]", i))
183                 }
184                 else
185                 {
186                         buf_texcoord[i] = NULL;
187                 }
188         }
189         backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
190         backendactive = true;
191 }
192
193 static void gl_backend_shutdown(void)
194 {
195         Con_Printf("OpenGL Backend shutting down\n");
196
197         if (resizingbuffers)
198                 Mem_EmptyPool(gl_backend_mempool);
199         else
200                 Mem_FreePool(&gl_backend_mempool);
201
202         backendunits = 0;
203         backendactive = false;
204 }
205
206 static void gl_backend_bufferchanges(int init)
207 {
208         if (overflowedverts > gl_mesh_maxtriangles.integer * 3)
209                 Cvar_SetValueQuick(&gl_mesh_maxtriangles, (int) ((overflowedverts + 2) / 3));
210         overflowedverts = 0;
211
212         if (gl_mesh_drawmode.integer < 0)
213                 Cvar_SetValueQuick(&gl_mesh_drawmode, 0);
214         if (gl_mesh_drawmode.integer > 3)
215                 Cvar_SetValueQuick(&gl_mesh_drawmode, 3);
216
217         if (gl_mesh_drawmode.integer >= 3 && qglDrawRangeElements == NULL)
218         {
219                 // change drawmode 3 to 2 if 3 won't work at all
220                 Cvar_SetValueQuick(&gl_mesh_drawmode, 2);
221         }
222
223         // 21760 is (65536 / 3) rounded off to a multiple of 128
224         if (gl_mesh_maxtriangles.integer < 1024)
225                 Cvar_SetValueQuick(&gl_mesh_maxtriangles, 1024);
226         if (gl_mesh_maxtriangles.integer > 21760)
227                 Cvar_SetValueQuick(&gl_mesh_maxtriangles, 21760);
228
229         if (max_tris != gl_mesh_maxtriangles.integer)
230         {
231                 max_tris = gl_mesh_maxtriangles.integer;
232
233                 if (!init)
234                 {
235                         resizingbuffers = true;
236                         gl_backend_shutdown();
237                         gl_backend_start();
238                         resizingbuffers = false;
239                 }
240         }
241 }
242
243 static void gl_backend_newmap(void)
244 {
245 }
246
247 void gl_backend_init(void)
248 {
249         Cvar_RegisterVariable(&r_render);
250         Cvar_RegisterVariable(&gl_dither);
251         Cvar_RegisterVariable(&gl_lockarrays);
252 #ifdef NORENDER
253         Cvar_SetValue("r_render", 0);
254 #endif
255
256         Cvar_RegisterVariable(&gl_mesh_maxtriangles);
257         Cvar_RegisterVariable(&gl_mesh_floatcolors);
258         Cvar_RegisterVariable(&gl_mesh_drawmode);
259         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
260         gl_backend_bufferchanges(true);
261 }
262
263 int arraylocked = false;
264
265 void GL_LockArray(int first, int count)
266 {
267         if (!arraylocked && gl_supportslockarrays && gl_lockarrays.integer && gl_mesh_drawmode.integer > 0)
268         {
269                 qglLockArraysEXT(first, count);
270                 CHECKGLERROR
271                 arraylocked = true;
272         }
273 }
274
275 void GL_UnlockArray(void)
276 {
277         if (arraylocked)
278         {
279                 qglUnlockArraysEXT();
280                 CHECKGLERROR
281                 arraylocked = false;
282         }
283 }
284
285 /*
286 =============
287 GL_SetupFrame
288 =============
289 */
290 static void GL_SetupFrame (void)
291 {
292         double xmax, ymax;
293         double fovx, fovy, zNear, zFar, aspect;
294
295         if (!r_render.integer)
296                 return;
297
298         qglDepthFunc (GL_LEQUAL);CHECKGLERROR
299
300         // set up viewpoint
301         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
302         qglLoadIdentity ();CHECKGLERROR
303
304         // y is weird beause OpenGL is bottom to top, we use top to bottom
305         qglViewport(r_refdef.x, vid.realheight - (r_refdef.y + r_refdef.height), r_refdef.width, r_refdef.height);CHECKGLERROR
306
307         // depth range
308         zNear = 1.0;
309         zFar = r_mesh_farclip;
310         if (zFar < 64)
311                 zFar = 64;
312
313         // fov angles
314         fovx = r_refdef.fov_x;
315         fovy = r_refdef.fov_y;
316         aspect = r_refdef.width / r_refdef.height;
317
318         // pyramid slopes
319         xmax = zNear * tan(fovx * M_PI / 360.0) * aspect;
320         ymax = zNear * tan(fovy * M_PI / 360.0);
321
322         // set view pyramid
323         qglFrustum(-xmax, xmax, -ymax, ymax, zNear, zFar);CHECKGLERROR
324
325         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
326         qglLoadIdentity ();CHECKGLERROR
327
328         // put Z going up
329         qglRotatef (-90,  1, 0, 0);CHECKGLERROR
330         qglRotatef (90,  0, 0, 1);CHECKGLERROR
331         // camera rotation
332         qglRotatef (-r_refdef.viewangles[2],  1, 0, 0);CHECKGLERROR
333         qglRotatef (-r_refdef.viewangles[0],  0, 1, 0);CHECKGLERROR
334         qglRotatef (-r_refdef.viewangles[1],  0, 0, 1);CHECKGLERROR
335         // camera location
336         qglTranslatef (-r_refdef.vieworg[0],  -r_refdef.vieworg[1],  -r_refdef.vieworg[2]);CHECKGLERROR
337 }
338
339 static struct
340 {
341         int blendfunc1;
342         int blendfunc2;
343         int blend;
344         GLboolean depthmask;
345         int depthtest;
346         int unit;
347         int clientunit;
348         int texture[MAX_TEXTUREUNITS];
349         float texturergbscale[MAX_TEXTUREUNITS];
350 }
351 gl_state;
352
353 void GL_SetupTextureState(void)
354 {
355         int i;
356         if (backendunits > 1)
357         {
358                 for (i = 0;i < backendunits;i++)
359                 {
360                         qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
361                         qglBindTexture(GL_TEXTURE_2D, gl_state.texture[i]);CHECKGLERROR
362                         if (gl_combine.integer)
363                         {
364                                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
365                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);CHECKGLERROR
366                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);CHECKGLERROR
367                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
368                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_CONSTANT_ARB);CHECKGLERROR
369                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
370                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
371                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB_ARB, GL_SRC_ALPHA);CHECKGLERROR
372                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);CHECKGLERROR
373                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE);CHECKGLERROR
374                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
375                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA_ARB, GL_CONSTANT_ARB);CHECKGLERROR
376                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
377                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
378                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
379                                 qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, gl_state.texturergbscale[i]);CHECKGLERROR
380                                 qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
381                         }
382                         else
383                         {
384                                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
385                         }
386                         if (gl_state.texture[i])
387                         {
388                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
389                         }
390                         else
391                         {
392                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
393                         }
394                         if (gl_mesh_drawmode.integer > 0)
395                         {
396                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
397                                 qglTexCoordPointer(2, GL_FLOAT, sizeof(buf_texcoord_t), buf_texcoord[i]);CHECKGLERROR
398                                 if (gl_state.texture[i])
399                                 {
400                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
401                                 }
402                                 else
403                                 {
404                                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
405                                 }
406                         }
407                 }
408         }
409         else
410         {
411                 qglBindTexture(GL_TEXTURE_2D, gl_state.texture[0]);CHECKGLERROR
412                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
413                 if (gl_state.texture[0])
414                 {
415                         qglEnable(GL_TEXTURE_2D);CHECKGLERROR
416                 }
417                 else
418                 {
419                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
420                 }
421                 if (gl_mesh_drawmode.integer > 0)
422                 {
423                         qglTexCoordPointer(2, GL_FLOAT, sizeof(buf_texcoord_t), buf_texcoord[0]);CHECKGLERROR
424                         if (gl_state.texture[0])
425                         {
426                                 qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
427                         }
428                         else
429                         {
430                                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
431                         }
432                 }
433         }
434 }
435
436 // called at beginning of frame
437 int usedarrays;
438 void R_Mesh_Start(float farclip)
439 {
440         int i;
441         if (!backendactive)
442                 Sys_Error("R_Mesh_Clear: called when backend is not active\n");
443
444         CHECKGLERROR
445
446         gl_backend_bufferchanges(false);
447
448         currenttriangle = 0;
449         currentvertex = 0;
450         r_mesh_farclip = farclip;
451         viewdist = DotProduct(r_origin, vpn);
452         vpnbit0 = vpn[0] < 0;
453         vpnbit1 = vpn[1] < 0;
454         vpnbit2 = vpn[2] < 0;
455
456         c_meshs = 0;
457         c_meshtris = 0;
458
459         GL_SetupFrame();
460
461         gl_state.unit = 0;
462         gl_state.clientunit = 0;
463
464         for (i = 0;i < backendunits;i++)
465         {
466                 gl_state.texture[i] = 0;
467                 gl_state.texturergbscale[i] = 1;
468         }
469
470         qglEnable(GL_CULL_FACE);CHECKGLERROR
471         qglCullFace(GL_FRONT);CHECKGLERROR
472
473         gl_state.depthtest = true;
474         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
475
476         gl_state.blendfunc1 = GL_ONE;
477         gl_state.blendfunc2 = GL_ZERO;
478         qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
479
480         gl_state.blend = 0;
481         qglDisable(GL_BLEND);CHECKGLERROR
482
483         gl_state.depthmask = GL_TRUE;
484         qglDepthMask(gl_state.depthmask);CHECKGLERROR
485
486         usedarrays = false;
487         if (gl_mesh_drawmode.integer > 0)
488         {
489                 usedarrays = true;
490                 qglVertexPointer(3, GL_FLOAT, sizeof(buf_vertex_t), &buf_vertex[0].v[0]);CHECKGLERROR
491                 qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
492                 if (gl_mesh_floatcolors.integer)
493                 {
494                         qglColorPointer(4, GL_FLOAT, sizeof(buf_fcolor_t), &buf_fcolor[0].c[0]);CHECKGLERROR
495                 }
496                 else
497                 {
498                         qglColorPointer(4, GL_UNSIGNED_BYTE, sizeof(buf_bcolor_t), &buf_bcolor[0].c[0]);CHECKGLERROR
499                 }
500                 qglEnableClientState(GL_COLOR_ARRAY);CHECKGLERROR
501         }
502
503         GL_SetupTextureState();
504 }
505
506 int gl_backend_rebindtextures;
507
508 void GL_ConvertColorsFloatToByte(void)
509 {
510         int i, k, total;
511         // LordHavoc: to avoid problems with aliasing (treating memory as two
512         // different types - exactly what this is doing), these must be volatile
513         // (or a union)
514         volatile int *icolor;
515         volatile float *fcolor;
516         qbyte *bcolor;
517
518         total = currentvertex * 4;
519
520         // shift float to have 8bit fraction at base of number
521         fcolor = &buf_fcolor->c[0];
522         for (i = 0;i < total;)
523         {
524                 fcolor[i    ] += 32768.0f;
525                 fcolor[i + 1] += 32768.0f;
526                 fcolor[i + 2] += 32768.0f;
527                 fcolor[i + 3] += 32768.0f;
528                 i += 4;
529         }
530
531         // then read as integer and kill float bits...
532         icolor = (int *)&buf_fcolor->c[0];
533         bcolor = &buf_bcolor->c[0];
534         for (i = 0;i < total;)
535         {
536                 k = icolor[i    ] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i    ] = (qbyte) k;
537                 k = icolor[i + 1] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 1] = (qbyte) k;
538                 k = icolor[i + 2] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 2] = (qbyte) k;
539                 k = icolor[i + 3] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 3] = (qbyte) k;
540                 i += 4;
541         }
542 }
543
544 void GL_MeshState(void)
545 {
546         int i;
547         if (backendunits > 1)
548         {
549                 for (i = 0;i < backendunits;i++)
550                 {
551                         if (gl_state.texture[i] != buf_mesh.textures[i])
552                         {
553                                 if (gl_state.unit != i)
554                                 {
555                                         qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
556                                 }
557                                 if (gl_state.texture[i] == 0)
558                                 {
559                                         qglEnable(GL_TEXTURE_2D);CHECKGLERROR
560                                         // have to disable texcoord array on disabled texture
561                                         // units due to NVIDIA driver bug with
562                                         // compiled_vertex_array
563                                         if (gl_state.clientunit != i)
564                                         {
565                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
566                                         }
567                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
568                                 }
569                                 qglBindTexture(GL_TEXTURE_2D, (gl_state.texture[i] = buf_mesh.textures[i]));CHECKGLERROR
570                                 if (gl_state.texture[i] == 0)
571                                 {
572                                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
573                                         // have to disable texcoord array on disabled texture
574                                         // units due to NVIDIA driver bug with
575                                         // compiled_vertex_array
576                                         if (gl_state.clientunit != i)
577                                         {
578                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
579                                         }
580                                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
581                                 }
582                         }
583                         if (gl_state.texturergbscale[i] != buf_mesh.texturergbscale[i])
584                         {
585                                 if (gl_state.unit != i)
586                                 {
587                                         qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
588                                 }
589                                 qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (gl_state.texturergbscale[i] = buf_mesh.texturergbscale[i]));CHECKGLERROR
590                         }
591                 }
592         }
593         else
594         {
595                 if (gl_state.texture[0] != buf_mesh.textures[0])
596                 {
597                         if (gl_state.texture[0] == 0)
598                         {
599                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
600                                 qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
601                         }
602                         qglBindTexture(GL_TEXTURE_2D, (gl_state.texture[0] = buf_mesh.textures[0]));CHECKGLERROR
603                         if (gl_state.texture[0] == 0)
604                         {
605                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
606                                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
607                         }
608                 }
609         }
610         if (gl_state.blendfunc1 != buf_mesh.blendfunc1 || gl_state.blendfunc2 != buf_mesh.blendfunc2)
611         {
612                 qglBlendFunc(gl_state.blendfunc1 = buf_mesh.blendfunc1, gl_state.blendfunc2 = buf_mesh.blendfunc2);CHECKGLERROR
613                 if (gl_state.blendfunc2 == GL_ZERO)
614                 {
615                         if (gl_state.blendfunc1 == GL_ONE)
616                         {
617                                 if (gl_state.blend)
618                                 {
619                                         gl_state.blend = 0;
620                                         qglDisable(GL_BLEND);CHECKGLERROR
621                                 }
622                         }
623                         else
624                         {
625                                 if (!gl_state.blend)
626                                 {
627                                         gl_state.blend = 1;
628                                         qglEnable(GL_BLEND);CHECKGLERROR
629                                 }
630                         }
631                 }
632                 else
633                 {
634                         if (!gl_state.blend)
635                         {
636                                 gl_state.blend = 1;
637                                 qglEnable(GL_BLEND);CHECKGLERROR
638                         }
639                 }
640         }
641         if (gl_state.depthtest != buf_mesh.depthtest)
642         {
643                 gl_state.depthtest = buf_mesh.depthtest;
644                 if (gl_state.depthtest)
645                         qglEnable(GL_DEPTH_TEST);
646                 else
647                         qglDisable(GL_DEPTH_TEST);
648         }
649         if (gl_state.depthmask != buf_mesh.depthmask)
650         {
651                 qglDepthMask(gl_state.depthmask = buf_mesh.depthmask);CHECKGLERROR
652         }
653 }
654
655 void GL_DrawRangeElements(int firstvert, int endvert, int indexcount, GLuint *index)
656 {
657         unsigned int i, j, in;
658         if (gl_mesh_drawmode.integer >= 3/* && (endvert - firstvert) <= gl_maxdrawrangeelementsvertices && (indexcount) <= gl_maxdrawrangeelementsindices*/)
659         {
660                 // GL 1.2 or GL 1.1 with extension
661                 qglDrawRangeElements(GL_TRIANGLES, firstvert, endvert, indexcount, GL_UNSIGNED_INT, index);
662         }
663         else if (gl_mesh_drawmode.integer >= 2)
664         {
665                 // GL 1.1
666                 qglDrawElements(GL_TRIANGLES, indexcount, GL_UNSIGNED_INT, index);
667         }
668         else if (gl_mesh_drawmode.integer >= 1)
669         {
670                 // GL 1.1
671                 // feed it manually using glArrayElement
672                 qglBegin(GL_TRIANGLES);
673                 for (i = 0;i < indexcount;i++)
674                         qglArrayElement(index[i]);
675                 qglEnd();
676         }
677         else
678         {
679                 // GL 1.1 but not using vertex arrays - 3dfx glquake minigl driver
680                 // feed it manually
681                 qglBegin(GL_TRIANGLES);
682                 if (gl_state.texture[1]) // if the mesh uses multiple textures
683                 {
684                         // the minigl doesn't have this (because it does not have ARB_multitexture)
685                         for (i = 0;i < indexcount;i++)
686                         {
687                                 in = index[i];
688                                 qglColor4ub(buf_bcolor[in].c[0], buf_bcolor[in].c[1], buf_bcolor[in].c[2], buf_bcolor[in].c[3]);
689                                 for (j = 0;j < backendunits;j++)
690                                         if (gl_state.texture[j])
691                                                 qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, buf_texcoord[j][in].t[0], buf_texcoord[j][in].t[1]);
692                                 qglVertex3f(buf_vertex[in].v[0], buf_vertex[in].v[1], buf_vertex[in].v[2]);
693                         }
694                 }
695                 else
696                 {
697                         for (i = 0;i < indexcount;i++)
698                         {
699                                 in = index[i];
700                                 qglColor4ub(buf_bcolor[in].c[0], buf_bcolor[in].c[1], buf_bcolor[in].c[2], buf_bcolor[in].c[3]);
701                                 if (gl_state.texture[0])
702                                         qglTexCoord2f(buf_texcoord[0][in].t[0], buf_texcoord[0][in].t[1]);
703                                 qglVertex3f(buf_vertex[in].v[0], buf_vertex[in].v[1], buf_vertex[in].v[2]);
704                         }
705                 }
706                 qglEnd();
707         }
708 }
709
710 // renders mesh buffers, called to flush buffers when full
711 void R_Mesh_Render(void)
712 {
713         int i;
714         float *v, tempv[4], m[12];
715
716         if (!backendactive)
717                 Sys_Error("R_Mesh_Render: called when backend is not active\n");
718
719         if (!r_render.integer)
720         {
721                 currenttriangle = 0;
722                 currentvertex = 0;
723                 return;
724         }
725
726         CHECKGLERROR
727
728         // drawmode 0 always uses byte colors
729         if (!gl_mesh_floatcolors.integer || gl_mesh_drawmode.integer <= 0)
730                 GL_ConvertColorsFloatToByte();
731
732         m[0] = buf_mesh.matrix.m[0][0];
733         m[1] = buf_mesh.matrix.m[0][1];
734         m[2] = buf_mesh.matrix.m[0][2];
735         m[3] = buf_mesh.matrix.m[0][3];
736         m[4] = buf_mesh.matrix.m[1][0];
737         m[5] = buf_mesh.matrix.m[1][1];
738         m[6] = buf_mesh.matrix.m[1][2];
739         m[7] = buf_mesh.matrix.m[1][3];
740         m[8] = buf_mesh.matrix.m[2][0];
741         m[9] = buf_mesh.matrix.m[2][1];
742         m[10] = buf_mesh.matrix.m[2][2];
743         m[11] = buf_mesh.matrix.m[2][3];
744         for (i = 0, v = buf_vertex[buf_mesh.firstvert].v;i < buf_mesh.verts;i++, v += 4)
745         {
746                 VectorCopy(v, tempv);
747                 //Matrix4x4_Transform(&buf_mesh.matrix, tempv, v);
748                 v[0] = tempv[0] * m[0] + tempv[1] * m[1] + tempv[2] * m[2] + m[3];
749                 v[1] = tempv[0] * m[4] + tempv[1] * m[5] + tempv[2] * m[6] + m[7];
750                 v[2] = tempv[0] * m[8] + tempv[1] * m[9] + tempv[2] * m[10] + m[11];
751         }
752         GL_LockArray(0, currentvertex);
753         GL_DrawRangeElements(buf_mesh.firstvert, buf_mesh.firstvert + buf_mesh.verts, buf_mesh.triangles * 3, (unsigned int *)&buf_tri[buf_mesh.firsttriangle].index[0]);CHECKGLERROR
754
755         currenttriangle = 0;
756         currentvertex = 0;
757
758         GL_UnlockArray();CHECKGLERROR
759 }
760
761 // restores backend state, used when done with 3D rendering
762 void R_Mesh_Finish(void)
763 {
764         int i;
765         if (backendunits > 1)
766         {
767                 for (i = backendunits - 1;i >= 0;i--)
768                 {
769                         qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
770                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
771                         if (gl_combine.integer)
772                         {
773                                 qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
774                         }
775                         if (i > 0)
776                         {
777                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
778                         }
779                         else
780                         {
781                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
782                         }
783                         qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
784
785                         if (usedarrays)
786                         {
787                                 qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
788                                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
789                         }
790                 }
791         }
792         else
793         {
794                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
795                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
796                 if (usedarrays)
797                 {
798                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
799                 }
800         }
801         if (usedarrays)
802         {
803                 qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
804                 qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
805         }
806
807         qglDisable(GL_BLEND);CHECKGLERROR
808         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
809         qglDepthMask(GL_TRUE);CHECKGLERROR
810         qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
811 }
812
813 void R_Mesh_ClearDepth(void)
814 {
815         R_Mesh_Finish();
816         qglClear(GL_DEPTH_BUFFER_BIT);
817         R_Mesh_Start(r_mesh_farclip);
818 }
819
820 // allocates space in geometry buffers, and fills in pointers to the buffers in passsed struct
821 // (this is used for very high speed rendering, no copying)
822 int R_Mesh_Draw_GetBuffer(rmeshbufferinfo_t *m, int wantoverbright)
823 {
824         // these are static because gcc runs out of virtual registers otherwise
825         int i, j, overbright;
826         float scaler;
827
828         if (!backendactive)
829                 Sys_Error("R_Mesh_Draw_GetBuffer: called when backend is not active\n");
830
831         if (!m->numtriangles
832          || !m->numverts)
833                 Host_Error("R_Mesh_Draw_GetBuffer: no triangles or verts\n");
834
835         i = max(m->numtriangles * 3, m->numverts);
836         if (overflowedverts < i)
837                 overflowedverts = i;
838
839         if (m->numtriangles > max_tris || m->numverts > max_verts)
840         {
841                 Con_Printf("R_Mesh_Draw_GetBuffer: mesh too big for current gl_mesh_maxtriangles setting, increasing limits\n");
842                 return false;
843         }
844
845         c_meshs++;
846         c_meshtris += m->numtriangles;
847         m->index = &buf_tri[currenttriangle].index[0];
848         m->vertex = &buf_vertex[currentvertex].v[0];
849         m->color = &buf_fcolor[currentvertex].c[0];
850         for (i = 0;i < backendunits;i++)
851                 m->texcoords[i] = &buf_texcoord[i][currentvertex].t[0];
852
853         // opaque meshs are rendered directly
854         buf_mesh.firsttriangle = currenttriangle;
855         buf_mesh.firstvert = currentvertex;
856         currenttriangle += m->numtriangles;
857         currentvertex += m->numverts;
858
859         buf_mesh.blendfunc1 = m->blendfunc1;
860         buf_mesh.blendfunc2 = m->blendfunc2;
861         buf_mesh.depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite);
862         buf_mesh.depthtest = !m->depthdisable;
863         buf_mesh.triangles = m->numtriangles;
864         buf_mesh.verts = m->numverts;
865         buf_mesh.matrix = m->matrix; // this copies the struct
866
867         overbright = false;
868         scaler = 1;
869         if (m->blendfunc1 == GL_DST_COLOR)
870         {
871                 // check if it is a 2x modulate with framebuffer
872                 if (m->blendfunc2 == GL_SRC_COLOR)
873                         scaler *= 0.5f;
874         }
875         else if (m->blendfunc2 != GL_SRC_COLOR)
876         {
877                 if (m->tex[0])
878                 {
879                         overbright = wantoverbright && gl_combine.integer;
880                         if (overbright)
881                                 scaler *= 0.25f;
882                 }
883                 scaler *= overbrightscale;
884         }
885         m->colorscale = scaler;
886
887         j = -1;
888         for (i = 0;i < MAX_TEXTUREUNITS;i++)
889         {
890                 if ((buf_mesh.textures[i] = m->tex[i]))
891                 {
892                         j = i;
893                         if (i >= backendunits)
894                                 Sys_Error("R_Mesh_Draw_GetBuffer: texture %i supplied when there are only %i texture units\n", j + 1, backendunits);
895                 }
896                 buf_mesh.texturergbscale[i] = m->texrgbscale[i];
897                 if (buf_mesh.texturergbscale[i] != 1 && buf_mesh.texturergbscale[i] != 2 && buf_mesh.texturergbscale[i] != 4)
898                         buf_mesh.texturergbscale[i] = 1;
899         }
900         if (overbright && j >= 0)
901                 buf_mesh.texturergbscale[j] = 4;
902
903         if (gl_backend_rebindtextures)
904         {
905                 gl_backend_rebindtextures = false;
906                 GL_SetupTextureState();
907         }
908
909         GL_MeshState();
910
911         return true;
912 }
913
914 /*
915 ==============================================================================
916
917                                                 SCREEN SHOTS
918
919 ==============================================================================
920 */
921
922 qboolean SCR_ScreenShot(char *filename, int x, int y, int width, int height)
923 {
924         qboolean ret;
925         int i;
926         qbyte *buffer;
927
928         if (!r_render.integer)
929                 return false;
930
931         buffer = Mem_Alloc(tempmempool, width*height*3);
932         qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
933         CHECKGLERROR
934
935         // LordHavoc: compensate for v_overbrightbits when using hardware gamma
936         if (v_hwgamma.integer)
937                 for (i = 0;i < width * height * 3;i++)
938                         buffer[i] <<= v_overbrightbits.integer;
939
940         ret = Image_WriteTGARGB_preflipped(filename, width, height, buffer);
941
942         Mem_Free(buffer);
943         return ret;
944 }
945
946 //=============================================================================
947
948 void R_ClearScreen(void)
949 {
950         if (r_render.integer)
951         {
952                 // clear to black
953                 qglClearColor(0,0,0,0);CHECKGLERROR
954                 // clear the screen
955                 qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);CHECKGLERROR
956                 // set dithering mode
957                 if (gl_dither.integer)
958                 {
959                         qglEnable(GL_DITHER);CHECKGLERROR
960                 }
961                 else
962                 {
963                         qglDisable(GL_DITHER);CHECKGLERROR
964                 }
965         }
966 }
967
968 /*
969 ==================
970 SCR_UpdateScreen
971
972 This is called every frame, and can also be called explicitly to flush
973 text to the screen.
974 ==================
975 */
976 void SCR_UpdateScreen (void)
977 {
978         VID_Finish ();
979
980         R_TimeReport("finish");
981
982         if (r_textureunits.integer > gl_textureunits)
983                 Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
984         if (r_textureunits.integer < 1)
985                 Cvar_SetValueQuick(&r_textureunits, 1);
986
987         if (gl_combine.integer && (!gl_combine_extension || r_textureunits.integer < 2))
988                 Cvar_SetValueQuick(&gl_combine, 0);
989
990         // lighting scale
991         overbrightscale = 1.0f / (float) (1 << v_overbrightbits.integer);
992
993         // lightmaps only
994         lightscalebit = v_overbrightbits.integer;
995         if (gl_combine.integer && r_textureunits.integer > 1)
996                 lightscalebit += 2;
997         lightscale = 1.0f / (float) (1 << lightscalebit);
998
999         R_TimeReport("setup");
1000
1001         R_ClearScreen();
1002
1003         R_TimeReport("clear");
1004
1005         if (scr_conlines < vid.conheight && cls.signon == SIGNONS)
1006                 R_RenderView();
1007
1008         // draw 2D stuff
1009         R_DrawQueue();
1010
1011         // tell driver to commit it's partially full geometry queue to the rendering queue
1012         // (this doesn't wait for the commands themselves to complete)
1013         qglFlush();
1014 }
1015