most of the framework for hardware accelerated transforms is back, just the actual...
[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_meshs;
83 static int max_verts; // always max_meshs * 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 currentmesh, 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_meshs * 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_mesh, max_meshs, buf_mesh_t, "buf_mesh")
173         BACKENDALLOC(buf_tri, max_meshs, buf_tri_t, "buf_tri")
174         BACKENDALLOC(buf_vertex, max_verts, buf_vertex_t, "buf_vertex")
175         BACKENDALLOC(buf_fcolor, max_verts, buf_fcolor_t, "buf_fcolor")
176         BACKENDALLOC(buf_bcolor, max_verts, buf_bcolor_t, "buf_bcolor")
177
178         for (i = 0;i < MAX_TEXTUREUNITS;i++)
179         {
180                 // only allocate as many texcoord arrays as we need
181                 if (i < gl_textureunits)
182                 {
183                         BACKENDALLOC(buf_texcoord[i], max_verts, buf_texcoord_t, va("buf_texcoord[%d]", i))
184                 }
185                 else
186                 {
187                         buf_texcoord[i] = NULL;
188                 }
189         }
190         backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
191         backendactive = true;
192 }
193
194 static void gl_backend_shutdown(void)
195 {
196         Con_Printf("OpenGL Backend shutting down\n");
197
198         if (resizingbuffers)
199                 Mem_EmptyPool(gl_backend_mempool);
200         else
201                 Mem_FreePool(&gl_backend_mempool);
202
203         backendunits = 0;
204         backendactive = false;
205 }
206
207 static void gl_backend_bufferchanges(int init)
208 {
209         if (overflowedverts > gl_mesh_maxtriangles.integer * 3)
210                 Cvar_SetValueQuick(&gl_mesh_maxtriangles, (int) ((overflowedverts + 2) / 3));
211         overflowedverts = 0;
212
213         if (gl_mesh_drawmode.integer < 0)
214                 Cvar_SetValueQuick(&gl_mesh_drawmode, 0);
215         if (gl_mesh_drawmode.integer > 3)
216                 Cvar_SetValueQuick(&gl_mesh_drawmode, 3);
217
218         if (gl_mesh_drawmode.integer >= 3 && qglDrawRangeElements == NULL)
219         {
220                 // change drawmode 3 to 2 if 3 won't work at all
221                 Cvar_SetValueQuick(&gl_mesh_drawmode, 2);
222         }
223
224         // 21760 is (65536 / 3) rounded off to a multiple of 128
225         if (gl_mesh_maxtriangles.integer < 1024)
226                 Cvar_SetValueQuick(&gl_mesh_maxtriangles, 1024);
227         if (gl_mesh_maxtriangles.integer > 21760)
228                 Cvar_SetValueQuick(&gl_mesh_maxtriangles, 21760);
229
230         if (max_meshs != gl_mesh_maxtriangles.integer)
231         {
232                 max_meshs = gl_mesh_maxtriangles.integer;
233
234                 if (!init)
235                 {
236                         resizingbuffers = true;
237                         gl_backend_shutdown();
238                         gl_backend_start();
239                         resizingbuffers = false;
240                 }
241         }
242 }
243
244 static void gl_backend_newmap(void)
245 {
246 }
247
248 void gl_backend_init(void)
249 {
250         Cvar_RegisterVariable(&r_render);
251         Cvar_RegisterVariable(&gl_dither);
252         Cvar_RegisterVariable(&gl_lockarrays);
253 #ifdef NORENDER
254         Cvar_SetValue("r_render", 0);
255 #endif
256
257         Cvar_RegisterVariable(&gl_mesh_maxtriangles);
258         Cvar_RegisterVariable(&gl_mesh_floatcolors);
259         Cvar_RegisterVariable(&gl_mesh_drawmode);
260         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
261         gl_backend_bufferchanges(true);
262 }
263
264 int arraylocked = false;
265
266 void GL_LockArray(int first, int count)
267 {
268         if (!arraylocked && gl_supportslockarrays && gl_lockarrays.integer && gl_mesh_drawmode.integer > 0)
269         {
270                 qglLockArraysEXT(first, count);
271                 CHECKGLERROR
272                 arraylocked = true;
273         }
274 }
275
276 void GL_UnlockArray(void)
277 {
278         if (arraylocked)
279         {
280                 qglUnlockArraysEXT();
281                 CHECKGLERROR
282                 arraylocked = false;
283         }
284 }
285
286 /*
287 =============
288 GL_SetupFrame
289 =============
290 */
291 static void GL_SetupFrame (void)
292 {
293         double xmax, ymax;
294         double fovx, fovy, zNear, zFar, aspect;
295
296         if (!r_render.integer)
297                 return;
298
299         qglDepthFunc (GL_LEQUAL);CHECKGLERROR
300
301         // set up viewpoint
302         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
303         qglLoadIdentity ();CHECKGLERROR
304
305         // y is weird beause OpenGL is bottom to top, we use top to bottom
306         qglViewport(r_refdef.x, vid.realheight - (r_refdef.y + r_refdef.height), r_refdef.width, r_refdef.height);CHECKGLERROR
307
308         // depth range
309         zNear = 1.0;
310         zFar = r_mesh_farclip;
311
312         // fov angles
313         fovx = r_refdef.fov_x;
314         fovy = r_refdef.fov_y;
315         aspect = r_refdef.width / r_refdef.height;
316
317         // pyramid slopes
318         xmax = zNear * tan(fovx * M_PI / 360.0) * aspect;
319         ymax = zNear * tan(fovy * M_PI / 360.0);
320
321         // set view pyramid
322         qglFrustum(-xmax, xmax, -ymax, ymax, zNear, zFar);CHECKGLERROR
323
324         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
325         qglLoadIdentity ();CHECKGLERROR
326
327         // put Z going up
328         qglRotatef (-90,  1, 0, 0);CHECKGLERROR
329         qglRotatef (90,  0, 0, 1);CHECKGLERROR
330         // camera rotation
331         qglRotatef (-r_refdef.viewangles[2],  1, 0, 0);CHECKGLERROR
332         qglRotatef (-r_refdef.viewangles[0],  0, 1, 0);CHECKGLERROR
333         qglRotatef (-r_refdef.viewangles[1],  0, 0, 1);CHECKGLERROR
334         // camera location
335         qglTranslatef (-r_refdef.vieworg[0],  -r_refdef.vieworg[1],  -r_refdef.vieworg[2]);CHECKGLERROR
336 }
337
338 static struct
339 {
340         int blendfunc1;
341         int blendfunc2;
342         int blend;
343         GLboolean depthmask;
344         int depthtest;
345         int unit;
346         int clientunit;
347         int texture[MAX_TEXTUREUNITS];
348         float texturergbscale[MAX_TEXTUREUNITS];
349 }
350 gl_state;
351
352 void GL_SetupTextureState(void)
353 {
354         int i;
355         if (backendunits > 1)
356         {
357                 for (i = 0;i < backendunits;i++)
358                 {
359                         qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
360                         qglBindTexture(GL_TEXTURE_2D, gl_state.texture[i]);CHECKGLERROR
361                         if (gl_combine.integer)
362                         {
363                                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
364                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);CHECKGLERROR
365                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);CHECKGLERROR
366                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
367                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_CONSTANT_ARB);CHECKGLERROR
368                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
369                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
370                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB_ARB, GL_SRC_ALPHA);CHECKGLERROR
371                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);CHECKGLERROR
372                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE);CHECKGLERROR
373                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
374                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA_ARB, GL_CONSTANT_ARB);CHECKGLERROR
375                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
376                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
377                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
378                                 qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, gl_state.texturergbscale[i]);CHECKGLERROR
379                                 qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
380                         }
381                         else
382                         {
383                                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
384                         }
385                         if (gl_state.texture[i])
386                         {
387                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
388                         }
389                         else
390                         {
391                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
392                         }
393                         if (gl_mesh_drawmode.integer > 0)
394                         {
395                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
396                                 qglTexCoordPointer(2, GL_FLOAT, sizeof(buf_texcoord_t), buf_texcoord[i]);CHECKGLERROR
397                                 if (gl_state.texture[i])
398                                 {
399                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
400                                 }
401                                 else
402                                 {
403                                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
404                                 }
405                         }
406                 }
407         }
408         else
409         {
410                 qglBindTexture(GL_TEXTURE_2D, gl_state.texture[0]);CHECKGLERROR
411                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
412                 if (gl_state.texture[0])
413                 {
414                         qglEnable(GL_TEXTURE_2D);CHECKGLERROR
415                 }
416                 else
417                 {
418                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
419                 }
420                 if (gl_mesh_drawmode.integer > 0)
421                 {
422                         qglTexCoordPointer(2, GL_FLOAT, sizeof(buf_texcoord_t), buf_texcoord[0]);CHECKGLERROR
423                         if (gl_state.texture[0])
424                         {
425                                 qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
426                         }
427                         else
428                         {
429                                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
430                         }
431                 }
432         }
433 }
434
435 // called at beginning of frame
436 int usedarrays;
437 void R_Mesh_Start(float farclip)
438 {
439         int i;
440         if (!backendactive)
441                 Sys_Error("R_Mesh_Clear: called when backend is not active\n");
442
443         CHECKGLERROR
444
445         gl_backend_bufferchanges(false);
446
447         currentmesh = 0;
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(buf_mesh_t *mesh)
545 {
546         int i;
547         if (backendunits > 1)
548         {
549                 for (i = 0;i < backendunits;i++)
550                 {
551                         if (gl_state.texture[i] != 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] = 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] != 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] = mesh->texturergbscale[i]));CHECKGLERROR
590                         }
591                 }
592         }
593         else
594         {
595                 if (gl_state.texture[0] != 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] = 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 != mesh->blendfunc1 || gl_state.blendfunc2 != mesh->blendfunc2)
611         {
612                 qglBlendFunc(gl_state.blendfunc1 = mesh->blendfunc1, gl_state.blendfunc2 = 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 != mesh->depthtest)
642         {
643                 gl_state.depthtest = 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 != mesh->depthmask)
650         {
651                 qglDepthMask(gl_state.depthmask = 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, k;
714         float *v, tempv[4];
715         buf_mesh_t *mesh;
716
717         if (!backendactive)
718                 Sys_Error("R_Mesh_Render: called when backend is not active\n");
719
720         if (!currentmesh)
721                 return;
722
723         if (!r_render.integer)
724         {
725                 currentmesh = 0;
726                 currenttriangle = 0;
727                 currentvertex = 0;
728                 return;
729         }
730
731         CHECKGLERROR
732
733         // drawmode 0 always uses byte colors
734         if (!gl_mesh_floatcolors.integer || gl_mesh_drawmode.integer <= 0)
735                 GL_ConvertColorsFloatToByte();
736
737         if (gl_backend_rebindtextures)
738         {
739                 gl_backend_rebindtextures = false;
740                 GL_SetupTextureState();
741         }
742
743         GL_MeshState(buf_mesh);
744         for (k = 0, mesh = buf_mesh;k < currentmesh;k++, mesh++)
745         {
746                 for (i = 0, v = buf_vertex[mesh->firstvert].v;i < mesh->verts;i++, v += 4)
747                 {
748                         VectorCopy(v, tempv);
749                         Matrix4x4_Transform(&mesh->matrix, tempv, v);
750                 }
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         if (currentmesh >= 2)
756         {
757                 for (k = 1, mesh = buf_mesh + k;k < currentmesh;k++, mesh++)
758                 {
759                         GL_MeshState(mesh);
760                         GL_DrawRangeElements(mesh->firstvert, mesh->firstvert + mesh->verts, mesh->triangles * 3, buf_tri[mesh->firsttriangle].index);CHECKGLERROR
761                 }
762         }
763
764         currentmesh = 0;
765         currenttriangle = 0;
766         currentvertex = 0;
767
768         GL_UnlockArray();CHECKGLERROR
769 }
770
771 // restores backend state, used when done with 3D rendering
772 void R_Mesh_Finish(void)
773 {
774         int i;
775         // flush any queued meshs
776         if (currentmesh)
777                 R_Mesh_Render();
778
779         if (backendunits > 1)
780         {
781                 for (i = backendunits - 1;i >= 0;i--)
782                 {
783                         qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
784                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
785                         if (gl_combine.integer)
786                         {
787                                 qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
788                         }
789                         if (i > 0)
790                         {
791                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
792                         }
793                         else
794                         {
795                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
796                         }
797                         qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
798
799                         if (usedarrays)
800                         {
801                                 qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
802                                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
803                         }
804                 }
805         }
806         else
807         {
808                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
809                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
810                 if (usedarrays)
811                 {
812                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
813                 }
814         }
815         if (usedarrays)
816         {
817                 qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
818                 qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
819         }
820
821         qglDisable(GL_BLEND);CHECKGLERROR
822         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
823         qglDepthMask(GL_TRUE);CHECKGLERROR
824         qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
825 }
826
827 void R_Mesh_ClearDepth(void)
828 {
829         if (currentmesh)
830                 R_Mesh_Render();
831         R_Mesh_Finish();
832         qglClear(GL_DEPTH_BUFFER_BIT);
833         R_Mesh_Start(r_mesh_farclip);
834 }
835
836 // allocates space in geometry buffers, and fills in pointers to the buffers in passsed struct
837 // (this is used for very high speed rendering, no copying)
838 int R_Mesh_Draw_GetBuffer(rmeshbufferinfo_t *m, int wantoverbright)
839 {
840         // these are static because gcc runs out of virtual registers otherwise
841         int i, j, overbright;
842         float scaler;
843         buf_mesh_t *mesh;
844
845         if (!backendactive)
846                 Sys_Error("R_Mesh_Draw_GetBuffer: called when backend is not active\n");
847
848         if (!m->numtriangles
849          || !m->numverts)
850                 Host_Error("R_Mesh_Draw_GetBuffer: no triangles or verts\n");
851
852         // LordHavoc: removed this error condition because with floatcolors 0,
853         // the 3DFX driver works with very large meshs
854         // FIXME: we can work around this by falling back on non-array renderer if buffers are too big
855         //if (m->numtriangles > 1024 || m->numverts > 3072)
856         //{
857         //      Con_Printf("R_Mesh_Draw_GetBuffer: mesh too big for 3DFX drivers, rejected\n");
858         //      return false;
859         //}
860
861         i = max(m->numtriangles * 3, m->numverts);
862         if (overflowedverts < i)
863                 overflowedverts = i;
864
865         if (m->numtriangles > max_meshs || m->numverts > max_verts)
866         {
867                 Con_Printf("R_Mesh_Draw_GetBuffer: mesh too big for current gl_mesh_maxtriangles setting, increasing limits\n");
868                 return false;
869         }
870
871         if (m->transparent)
872                 Con_Printf("R_Mesh_Draw_GetBuffer: m.transparent is no longer supported\n");
873
874         if (currentmesh)
875         {
876                 R_Mesh_Render();
877                 Con_Printf("mesh queue not empty, flushing.\n");
878         }
879
880         c_meshs++;
881         c_meshtris += m->numtriangles;
882         m->index = &buf_tri[currenttriangle].index[0];
883         m->vertex = &buf_vertex[currentvertex].v[0];
884         m->color = &buf_fcolor[currentvertex].c[0];
885         for (i = 0;i < backendunits;i++)
886                 m->texcoords[i] = &buf_texcoord[i][currentvertex].t[0];
887
888         // opaque meshs are rendered directly
889         mesh = &buf_mesh[currentmesh++];
890         mesh->firsttriangle = currenttriangle;
891         mesh->firstvert = currentvertex;
892         currenttriangle += m->numtriangles;
893         currentvertex += m->numverts;
894
895         mesh->blendfunc1 = m->blendfunc1;
896         mesh->blendfunc2 = m->blendfunc2;
897         mesh->depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite);
898         mesh->depthtest = !m->depthdisable;
899         mesh->triangles = m->numtriangles;
900         mesh->verts = m->numverts;
901         mesh->matrix = m->matrix; // this copies the struct
902
903         overbright = false;
904         scaler = 1;
905         if (m->blendfunc1 == GL_DST_COLOR)
906         {
907                 // check if it is a 2x modulate with framebuffer
908                 if (m->blendfunc2 == GL_SRC_COLOR)
909                         scaler *= 0.5f;
910         }
911         else if (m->blendfunc2 != GL_SRC_COLOR)
912         {
913                 if (m->tex[0])
914                 {
915                         overbright = wantoverbright && gl_combine.integer;
916                         if (overbright)
917                                 scaler *= 0.25f;
918                 }
919                 scaler *= overbrightscale;
920         }
921         m->colorscale = scaler;
922
923         j = -1;
924         for (i = 0;i < MAX_TEXTUREUNITS;i++)
925         {
926                 if ((mesh->textures[i] = m->tex[i]))
927                 {
928                         j = i;
929                         if (i >= backendunits)
930                                 Sys_Error("R_Mesh_Draw_GetBuffer: texture %i supplied when there are only %i texture units\n", j + 1, backendunits);
931                 }
932                 mesh->texturergbscale[i] = m->texrgbscale[i];
933                 if (mesh->texturergbscale[i] != 1 && mesh->texturergbscale[i] != 2 && mesh->texturergbscale[i] != 4)
934                         mesh->texturergbscale[i] = 1;
935         }
936         if (overbright && j >= 0)
937                 mesh->texturergbscale[j] = 4;
938
939         return true;
940 }
941
942 /*
943 ==============================================================================
944
945                                                 SCREEN SHOTS
946
947 ==============================================================================
948 */
949
950 qboolean SCR_ScreenShot(char *filename, int x, int y, int width, int height)
951 {
952         qboolean ret;
953         int i;
954         qbyte *buffer;
955
956         if (!r_render.integer)
957                 return false;
958
959         buffer = Mem_Alloc(tempmempool, width*height*3);
960         qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
961         CHECKGLERROR
962
963         // LordHavoc: compensate for v_overbrightbits when using hardware gamma
964         if (v_hwgamma.integer)
965                 for (i = 0;i < width * height * 3;i++)
966                         buffer[i] <<= v_overbrightbits.integer;
967
968         ret = Image_WriteTGARGB_preflipped(filename, width, height, buffer);
969
970         Mem_Free(buffer);
971         return ret;
972 }
973
974 //=============================================================================
975
976 void R_ClearScreen(void)
977 {
978         if (r_render.integer)
979         {
980                 // clear to black
981                 qglClearColor(0,0,0,0);CHECKGLERROR
982                 // clear the screen
983                 qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);CHECKGLERROR
984                 // set dithering mode
985                 if (gl_dither.integer)
986                 {
987                         qglEnable(GL_DITHER);CHECKGLERROR
988                 }
989                 else
990                 {
991                         qglDisable(GL_DITHER);CHECKGLERROR
992                 }
993         }
994 }
995
996 /*
997 ==================
998 SCR_UpdateScreen
999
1000 This is called every frame, and can also be called explicitly to flush
1001 text to the screen.
1002 ==================
1003 */
1004 void SCR_UpdateScreen (void)
1005 {
1006         VID_Finish ();
1007
1008         R_TimeReport("finish");
1009
1010         if (r_textureunits.integer > gl_textureunits)
1011                 Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
1012         if (r_textureunits.integer < 1)
1013                 Cvar_SetValueQuick(&r_textureunits, 1);
1014
1015         if (gl_combine.integer && (!gl_combine_extension || r_textureunits.integer < 2))
1016                 Cvar_SetValueQuick(&gl_combine, 0);
1017
1018         // lighting scale
1019         overbrightscale = 1.0f / (float) (1 << v_overbrightbits.integer);
1020
1021         // lightmaps only
1022         lightscalebit = v_overbrightbits.integer;
1023         if (gl_combine.integer && r_textureunits.integer > 1)
1024                 lightscalebit += 2;
1025         lightscale = 1.0f / (float) (1 << lightscalebit);
1026
1027         R_TimeReport("setup");
1028
1029         R_ClearScreen();
1030
1031         R_TimeReport("clear");
1032
1033         if (scr_conlines < vid.conheight)
1034                 R_RenderView();
1035
1036         // draw 2D stuff
1037         R_DrawQueue();
1038
1039         // tell driver to commit it's partially full geometry queue to the rendering queue
1040         // (this doesn't wait for the commands themselves to complete)
1041         qglFlush();
1042 }
1043