a rather hefty 6% speed gain by getting rid of the R_Mesh_UpdateFarClip function...
[xonotic/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_batchtriangles = {0, "gl_mesh_batchtriangles", "0"};
6 cvar_t gl_mesh_transtriangles = {0, "gl_mesh_transtriangles", "16384"};
7 cvar_t gl_mesh_floatcolors = {0, "gl_mesh_floatcolors", "1"};
8 cvar_t gl_mesh_drawmode = {CVAR_SAVE, "gl_mesh_drawmode", "3"};
9
10 cvar_t r_render = {0, "r_render", "1"};
11 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1"}; // whether or not to use dithering
12 cvar_t gl_lockarrays = {0, "gl_lockarrays", "1"};
13
14 // this is used to increase gl_mesh_maxtriangles automatically if a mesh was
15 // too large for the buffers in the previous frame
16 int overflowedverts = 0;
17 // increase transtriangles automatically too
18 int overflowedtransverts = 0;
19
20 int gl_maxdrawrangeelementsvertices;
21 int gl_maxdrawrangeelementsindices;
22
23 #ifdef DEBUGGL
24 int errornumber = 0;
25
26 void GL_PrintError(int errornumber, char *filename, int linenumber)
27 {
28         switch(errornumber)
29         {
30 #ifdef GL_INVALID_ENUM
31         case GL_INVALID_ENUM:
32                 Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
33                 break;
34 #endif
35 #ifdef GL_INVALID_VALUE
36         case GL_INVALID_VALUE:
37                 Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
38                 break;
39 #endif
40 #ifdef GL_INVALID_OPERATION
41         case GL_INVALID_OPERATION:
42                 Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
43                 break;
44 #endif
45 #ifdef GL_STACK_OVERFLOW
46         case GL_STACK_OVERFLOW:
47                 Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
48                 break;
49 #endif
50 #ifdef GL_STACK_UNDERFLOW
51         case GL_STACK_UNDERFLOW:
52                 Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
53                 break;
54 #endif
55 #ifdef GL_OUT_OF_MEMORY
56         case GL_OUT_OF_MEMORY:
57                 Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
58                 break;
59 #endif
60 #ifdef GL_TABLE_TOO_LARGE
61     case GL_TABLE_TOO_LARGE:
62                 Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
63                 break;
64 #endif
65         default:
66                 Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
67                 break;
68         }
69 }
70 #endif
71
72 float r_mesh_farclip;
73
74 int polyindexarray[768];
75
76 static float viewdist;
77 // sign bits (true if negative) for vpn[] entries, so quick integer compares can be used instead of float compares
78 static int vpnbit0, vpnbit1, vpnbit2;
79
80 int c_meshs, c_meshtris, c_transmeshs, c_transtris;
81
82 int lightscalebit;
83 float lightscale;
84 float overbrightscale;
85
86 void SCR_ScreenShot_f (void);
87
88 static int max_meshs;
89 static int max_transmeshs;
90 static int max_batch;
91 static int max_verts; // always max_meshs * 3
92 static int max_transverts; // always max_transmeshs * 3
93 #define TRANSDEPTHRES 4096
94
95 typedef struct buf_mesh_s
96 {
97         int depthmask;
98         int depthtest;
99         int blendfunc1, blendfunc2;
100         int textures[MAX_TEXTUREUNITS];
101         int texturergbscale[MAX_TEXTUREUNITS];
102         int firsttriangle;
103         int triangles;
104         int firstvert;
105         int verts;
106         struct buf_mesh_s *chain;
107         struct buf_transtri_s *transchain;
108 }
109 buf_mesh_t;
110
111 typedef struct buf_transtri_s
112 {
113         struct buf_transtri_s *next;
114         struct buf_transtri_s *meshsortchain;
115         buf_mesh_t *mesh;
116         int index[3];
117 }
118 buf_transtri_t;
119
120 typedef struct buf_tri_s
121 {
122         int index[3];
123 }
124 buf_tri_t;
125
126 typedef struct
127 {
128         float v[4];
129 }
130 buf_vertex_t;
131
132 typedef struct
133 {
134         float c[4];
135 }
136 buf_fcolor_t;
137
138 typedef struct
139 {
140         qbyte c[4];
141 }
142 buf_bcolor_t;
143
144 typedef struct
145 {
146         float t[2];
147 }
148 buf_texcoord_t;
149
150 static int currentmesh, currenttriangle, currentvertex, backendunits, backendactive, transranout;
151 static buf_mesh_t *buf_mesh;
152 static buf_tri_t *buf_tri;
153 static buf_vertex_t *buf_vertex;
154 static buf_fcolor_t *buf_fcolor;
155 static buf_bcolor_t *buf_bcolor;
156 static buf_texcoord_t *buf_texcoord[MAX_TEXTUREUNITS];
157
158 static int currenttransmesh, currenttransvertex, currenttranstriangle;
159 static buf_mesh_t *buf_transmesh;
160 static buf_transtri_t *buf_sorttranstri;
161 static buf_transtri_t **buf_sorttranstri_list;
162 static buf_tri_t *buf_transtri;
163 static buf_vertex_t *buf_transvertex;
164 static buf_fcolor_t *buf_transfcolor;
165 static buf_texcoord_t *buf_transtexcoord[MAX_TEXTUREUNITS];
166
167 static mempool_t *gl_backend_mempool;
168 static int resizingbuffers = false;
169
170 static void gl_backend_start(void)
171 {
172         int i;
173
174         qglGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &gl_maxdrawrangeelementsvertices);
175         qglGetIntegerv(GL_MAX_ELEMENTS_INDICES, &gl_maxdrawrangeelementsindices);
176
177         Con_Printf("OpenGL Backend started with gl_mesh_maxtriangles %i, gl_mesh_transtriangles %i\n", gl_mesh_maxtriangles.integer, gl_mesh_transtriangles.integer);
178         if (qglDrawRangeElements != NULL)
179                 Con_Printf("glDrawRangeElements detected (max vertices %i, max indices %i)\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
180         if (strstr(gl_renderer, "3Dfx"))
181         {
182                 Con_Printf("3Dfx driver detected, forcing gl_mesh_floatcolors to 0 to prevent crashs\n");
183                 Cvar_SetValueQuick(&gl_mesh_floatcolors, 0);
184         }
185         Con_Printf("\n");
186
187         max_verts = max_meshs * 3;
188         max_transverts = max_transmeshs * 3;
189
190         if (!gl_backend_mempool)
191                 gl_backend_mempool = Mem_AllocPool("GL_Backend");
192
193 #define BACKENDALLOC(var, count, sizeofstruct, varname)\
194         {\
195                 var = Mem_Alloc(gl_backend_mempool, count * sizeof(sizeofstruct));\
196                 if (var == NULL)\
197                         Sys_Error("gl_backend_start: unable to allocate memory for %s (%d bytes)\n", (varname), count * sizeof(sizeofstruct));\
198                 memset(var, 0, count * sizeof(sizeofstruct));\
199         }
200
201         BACKENDALLOC(buf_mesh, max_meshs, buf_mesh_t, "buf_mesh")
202         BACKENDALLOC(buf_tri, max_meshs, buf_tri_t, "buf_tri")
203         BACKENDALLOC(buf_vertex, max_verts, buf_vertex_t, "buf_vertex")
204         BACKENDALLOC(buf_fcolor, max_verts, buf_fcolor_t, "buf_fcolor")
205         BACKENDALLOC(buf_bcolor, max_verts, buf_bcolor_t, "buf_bcolor")
206
207         BACKENDALLOC(buf_transmesh, max_transmeshs, buf_mesh_t, "buf_transmesh")
208         BACKENDALLOC(buf_sorttranstri, max_transmeshs, buf_transtri_t, "buf_sorttranstri")
209         BACKENDALLOC(buf_sorttranstri_list, TRANSDEPTHRES, buf_transtri_t *, "buf_sorttranstri_list")
210         BACKENDALLOC(buf_transtri, max_transmeshs, buf_tri_t, "buf_transtri")
211         BACKENDALLOC(buf_transvertex, max_transverts, buf_vertex_t, "buf_vertex")
212         BACKENDALLOC(buf_transfcolor, max_transverts, buf_fcolor_t, "buf_fcolor")
213
214         for (i = 0;i < MAX_TEXTUREUNITS;i++)
215         {
216                 // only allocate as many texcoord arrays as we need
217                 if (i < gl_textureunits)
218                 {
219                         BACKENDALLOC(buf_texcoord[i], max_verts, buf_texcoord_t, va("buf_texcoord[%d]", i))
220                         BACKENDALLOC(buf_transtexcoord[i], max_transverts, buf_texcoord_t, va("buf_transtexcoord[%d]", i))
221                 }
222                 else
223                 {
224                         buf_texcoord[i] = NULL;
225                         buf_transtexcoord[i] = NULL;
226                 }
227         }
228         backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
229         backendactive = true;
230 }
231
232 static void gl_backend_shutdown(void)
233 {
234         Con_Printf("OpenGL Backend shutting down\n");
235
236         if (resizingbuffers)
237                 Mem_EmptyPool(gl_backend_mempool);
238         else
239                 Mem_FreePool(&gl_backend_mempool);
240
241         backendunits = 0;
242         backendactive = false;
243 }
244
245 static void gl_backend_bufferchanges(int init)
246 {
247         if (overflowedverts > gl_mesh_maxtriangles.integer * 3)
248                 Cvar_SetValueQuick(&gl_mesh_maxtriangles, (int) ((overflowedverts + 2) / 3));
249         overflowedverts = 0;
250
251         if (overflowedtransverts > gl_mesh_transtriangles.integer * 3)
252                 Cvar_SetValueQuick(&gl_mesh_transtriangles, (int) ((overflowedtransverts + 2) / 3));
253         overflowedtransverts = 0;
254
255         if (gl_mesh_drawmode.integer < 0)
256                 Cvar_SetValueQuick(&gl_mesh_drawmode, 0);
257         if (gl_mesh_drawmode.integer > 3)
258                 Cvar_SetValueQuick(&gl_mesh_drawmode, 3);
259
260         if (gl_mesh_drawmode.integer >= 3 && qglDrawRangeElements == NULL)
261         {
262                 // change drawmode 3 to 2 if 3 won't work at all
263                 Cvar_SetValueQuick(&gl_mesh_drawmode, 2);
264         }
265
266         // 21760 is (65536 / 3) rounded off to a multiple of 128
267         if (gl_mesh_maxtriangles.integer < 1024)
268                 Cvar_SetValueQuick(&gl_mesh_maxtriangles, 1024);
269         if (gl_mesh_maxtriangles.integer > 21760)
270                 Cvar_SetValueQuick(&gl_mesh_maxtriangles, 21760);
271
272         if (gl_mesh_transtriangles.integer < 1024)
273                 Cvar_SetValueQuick(&gl_mesh_transtriangles, 1024);
274         if (gl_mesh_transtriangles.integer > 65536)
275                 Cvar_SetValueQuick(&gl_mesh_transtriangles, 65536);
276
277         if (gl_mesh_batchtriangles.integer < 1)
278                 Cvar_SetValueQuick(&gl_mesh_batchtriangles, 1);
279         if (gl_mesh_batchtriangles.integer > gl_mesh_maxtriangles.integer)
280                 Cvar_SetValueQuick(&gl_mesh_batchtriangles, gl_mesh_maxtriangles.integer);
281
282         max_batch = gl_mesh_batchtriangles.integer;
283
284         if (max_meshs != gl_mesh_maxtriangles.integer || max_transmeshs != gl_mesh_transtriangles.integer)
285         {
286                 max_meshs = gl_mesh_maxtriangles.integer;
287                 max_transmeshs = gl_mesh_transtriangles.integer;
288
289                 if (!init)
290                 {
291                         resizingbuffers = true;
292                         gl_backend_shutdown();
293                         gl_backend_start();
294                         resizingbuffers = false;
295                 }
296         }
297 }
298
299 static void gl_backend_newmap(void)
300 {
301 }
302
303 void gl_backend_init(void)
304 {
305         int i;
306
307         Cvar_RegisterVariable(&r_render);
308         Cvar_RegisterVariable(&gl_dither);
309         Cvar_RegisterVariable(&gl_lockarrays);
310 #ifdef NORENDER
311         Cvar_SetValue("r_render", 0);
312 #endif
313
314         Cvar_RegisterVariable(&gl_mesh_maxtriangles);
315         Cvar_RegisterVariable(&gl_mesh_transtriangles);
316         Cvar_RegisterVariable(&gl_mesh_batchtriangles);
317         Cvar_RegisterVariable(&gl_mesh_floatcolors);
318         Cvar_RegisterVariable(&gl_mesh_drawmode);
319         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
320         gl_backend_bufferchanges(true);
321         for (i = 0;i < 256;i++)
322         {
323                 polyindexarray[i*3+0] = 0;
324                 polyindexarray[i*3+1] = i + 1;
325                 polyindexarray[i*3+2] = i + 2;
326         }
327 }
328
329 int arraylocked = false;
330
331 void GL_LockArray(int first, int count)
332 {
333         if (!arraylocked && gl_supportslockarrays && gl_lockarrays.integer && gl_mesh_drawmode.integer > 0)
334         {
335                 qglLockArraysEXT(first, count);
336                 CHECKGLERROR
337                 arraylocked = true;
338         }
339 }
340
341 void GL_UnlockArray(void)
342 {
343         if (arraylocked)
344         {
345                 qglUnlockArraysEXT();
346                 CHECKGLERROR
347                 arraylocked = false;
348         }
349 }
350
351 /*
352 =============
353 GL_SetupFrame
354 =============
355 */
356 static void GL_SetupFrame (void)
357 {
358         double xmax, ymax;
359         double fovx, fovy, zNear, zFar, aspect;
360
361         if (!r_render.integer)
362                 return;
363
364         qglDepthFunc (GL_LEQUAL);CHECKGLERROR
365
366         // set up viewpoint
367         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
368         qglLoadIdentity ();CHECKGLERROR
369
370         // y is weird beause OpenGL is bottom to top, we use top to bottom
371         qglViewport(r_refdef.x, vid.realheight - (r_refdef.y + r_refdef.height), r_refdef.width, r_refdef.height);CHECKGLERROR
372
373         // depth range
374         zNear = 1.0;
375         zFar = r_mesh_farclip;
376
377         // fov angles
378         fovx = r_refdef.fov_x;
379         fovy = r_refdef.fov_y;
380         aspect = r_refdef.width / r_refdef.height;
381
382         // pyramid slopes
383         xmax = zNear * tan(fovx * M_PI / 360.0) * aspect;
384         ymax = zNear * tan(fovy * M_PI / 360.0);
385
386         // set view pyramid
387         qglFrustum(-xmax, xmax, -ymax, ymax, zNear, zFar);CHECKGLERROR
388
389         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
390         qglLoadIdentity ();CHECKGLERROR
391
392         // put Z going up
393         qglRotatef (-90,  1, 0, 0);CHECKGLERROR
394         qglRotatef (90,  0, 0, 1);CHECKGLERROR
395         // camera rotation
396         qglRotatef (-r_refdef.viewangles[2],  1, 0, 0);CHECKGLERROR
397         qglRotatef (-r_refdef.viewangles[0],  0, 1, 0);CHECKGLERROR
398         qglRotatef (-r_refdef.viewangles[1],  0, 0, 1);CHECKGLERROR
399         // camera location
400         qglTranslatef (-r_refdef.vieworg[0],  -r_refdef.vieworg[1],  -r_refdef.vieworg[2]);CHECKGLERROR
401 }
402
403 static int mesh_blendfunc1;
404 static int mesh_blendfunc2;
405 static int mesh_blend;
406 static GLboolean mesh_depthmask;
407 static int mesh_depthtest;
408 static int mesh_unit;
409 static int mesh_clientunit;
410 static int mesh_texture[MAX_TEXTUREUNITS];
411 static float mesh_texturergbscale[MAX_TEXTUREUNITS];
412
413 void GL_SetupTextureState(void)
414 {
415         int i;
416         if (backendunits > 1)
417         {
418                 for (i = 0;i < backendunits;i++)
419                 {
420                         qglActiveTexture(GL_TEXTURE0_ARB + (mesh_unit = i));CHECKGLERROR
421                         qglBindTexture(GL_TEXTURE_2D, mesh_texture[i]);CHECKGLERROR
422                         if (gl_combine.integer)
423                         {
424                                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
425                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);CHECKGLERROR
426                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);CHECKGLERROR
427                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
428                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_CONSTANT_ARB);CHECKGLERROR
429                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
430                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
431                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB_ARB, GL_SRC_ALPHA);CHECKGLERROR
432                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);CHECKGLERROR
433                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE);CHECKGLERROR
434                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
435                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA_ARB, GL_CONSTANT_ARB);CHECKGLERROR
436                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
437                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
438                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
439                                 qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, mesh_texturergbscale[i]);CHECKGLERROR
440                                 qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
441                         }
442                         else
443                         {
444                                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
445                         }
446                         if (mesh_texture[i])
447                         {
448                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
449                         }
450                         else
451                         {
452                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
453                         }
454                         if (gl_mesh_drawmode.integer > 0)
455                         {
456                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (mesh_clientunit = i));CHECKGLERROR
457                                 qglTexCoordPointer(2, GL_FLOAT, sizeof(buf_texcoord_t), buf_texcoord[i]);CHECKGLERROR
458                                 if (mesh_texture[i])
459                                 {
460                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
461                                 }
462                                 else
463                                 {
464                                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
465                                 }
466                         }
467                 }
468         }
469         else
470         {
471                 qglBindTexture(GL_TEXTURE_2D, mesh_texture[0]);CHECKGLERROR
472                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
473                 if (mesh_texture[0])
474                 {
475                         qglEnable(GL_TEXTURE_2D);CHECKGLERROR
476                 }
477                 else
478                 {
479                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
480                 }
481                 if (gl_mesh_drawmode.integer > 0)
482                 {
483                         qglTexCoordPointer(2, GL_FLOAT, sizeof(buf_texcoord_t), buf_texcoord[0]);CHECKGLERROR
484                         if (mesh_texture[0])
485                         {
486                                 qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
487                         }
488                         else
489                         {
490                                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
491                         }
492                 }
493         }
494 }
495
496 // called at beginning of frame
497 int usedarrays;
498 void R_Mesh_Start(float farclip)
499 {
500         int i;
501         if (!backendactive)
502                 Sys_Error("R_Mesh_Clear: called when backend is not active\n");
503
504         CHECKGLERROR
505
506         gl_backend_bufferchanges(false);
507
508         currentmesh = 0;
509         currenttriangle = 0;
510         currentvertex = 0;
511         currenttransmesh = 0;
512         currenttranstriangle = 0;
513         currenttransvertex = 0;
514         transranout = false;
515         r_mesh_farclip = farclip;
516         viewdist = DotProduct(r_origin, vpn);
517         vpnbit0 = vpn[0] < 0;
518         vpnbit1 = vpn[1] < 0;
519         vpnbit2 = vpn[2] < 0;
520
521         c_meshs = 0;
522         c_meshtris = 0;
523         c_transmeshs = 0;
524         c_transtris = 0;
525
526         GL_SetupFrame();
527
528         mesh_unit = 0;
529         mesh_clientunit = 0;
530
531         for (i = 0;i < backendunits;i++)
532         {
533                 mesh_texture[i] = 0;
534                 mesh_texturergbscale[i] = 1;
535         }
536
537         qglEnable(GL_CULL_FACE);CHECKGLERROR
538         qglCullFace(GL_FRONT);CHECKGLERROR
539
540         mesh_depthtest = true;
541         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
542
543         mesh_blendfunc1 = GL_ONE;
544         mesh_blendfunc2 = GL_ZERO;
545         qglBlendFunc(mesh_blendfunc1, mesh_blendfunc2);CHECKGLERROR
546
547         mesh_blend = 0;
548         qglDisable(GL_BLEND);CHECKGLERROR
549
550         mesh_depthmask = GL_TRUE;
551         qglDepthMask(mesh_depthmask);CHECKGLERROR
552
553         usedarrays = false;
554         if (gl_mesh_drawmode.integer > 0)
555         {
556                 usedarrays = true;
557                 qglVertexPointer(3, GL_FLOAT, sizeof(buf_vertex_t), &buf_vertex[0].v[0]);CHECKGLERROR
558                 qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
559                 if (gl_mesh_floatcolors.integer)
560                 {
561                         qglColorPointer(4, GL_FLOAT, sizeof(buf_fcolor_t), &buf_fcolor[0].c[0]);CHECKGLERROR
562                 }
563                 else
564                 {
565                         qglColorPointer(4, GL_UNSIGNED_BYTE, sizeof(buf_bcolor_t), &buf_bcolor[0].c[0]);CHECKGLERROR
566                 }
567                 qglEnableClientState(GL_COLOR_ARRAY);CHECKGLERROR
568         }
569
570         GL_SetupTextureState();
571 }
572
573 int gl_backend_rebindtextures;
574
575 void GL_ConvertColorsFloatToByte(void)
576 {
577         int i, k, total;
578         // LordHavoc: to avoid problems with aliasing (treating memory as two
579         // different types - exactly what this is doing), these must be volatile
580         // (or a union)
581         volatile int *icolor;
582         volatile float *fcolor;
583         qbyte *bcolor;
584
585         total = currentvertex * 4;
586
587         // shift float to have 8bit fraction at base of number
588         fcolor = &buf_fcolor->c[0];
589         for (i = 0;i < total;)
590         {
591                 fcolor[i    ] += 32768.0f;
592                 fcolor[i + 1] += 32768.0f;
593                 fcolor[i + 2] += 32768.0f;
594                 fcolor[i + 3] += 32768.0f;
595                 i += 4;
596         }
597
598         // then read as integer and kill float bits...
599         icolor = (int *)&buf_fcolor->c[0];
600         bcolor = &buf_bcolor->c[0];
601         for (i = 0;i < total;)
602         {
603                 k = icolor[i    ] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i    ] = (qbyte) k;
604                 k = icolor[i + 1] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 1] = (qbyte) k;
605                 k = icolor[i + 2] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 2] = (qbyte) k;
606                 k = icolor[i + 3] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 3] = (qbyte) k;
607                 i += 4;
608         }
609 }
610
611 void GL_MeshState(buf_mesh_t *mesh)
612 {
613         int i;
614         if (backendunits > 1)
615         {
616                 for (i = 0;i < backendunits;i++)
617                 {
618                         if (mesh_texture[i] != mesh->textures[i])
619                         {
620                                 if (mesh_unit != i)
621                                 {
622                                         qglActiveTexture(GL_TEXTURE0_ARB + (mesh_unit = i));CHECKGLERROR
623                                 }
624                                 if (mesh_texture[i] == 0)
625                                 {
626                                         qglEnable(GL_TEXTURE_2D);CHECKGLERROR
627                                         // have to disable texcoord array on disabled texture
628                                         // units due to NVIDIA driver bug with
629                                         // compiled_vertex_array
630                                         if (mesh_clientunit != i)
631                                         {
632                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (mesh_clientunit = i));CHECKGLERROR
633                                         }
634                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
635                                 }
636                                 qglBindTexture(GL_TEXTURE_2D, (mesh_texture[i] = mesh->textures[i]));CHECKGLERROR
637                                 if (mesh_texture[i] == 0)
638                                 {
639                                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
640                                         // have to disable texcoord array on disabled texture
641                                         // units due to NVIDIA driver bug with
642                                         // compiled_vertex_array
643                                         if (mesh_clientunit != i)
644                                         {
645                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (mesh_clientunit = i));CHECKGLERROR
646                                         }
647                                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
648                                 }
649                         }
650                         if (mesh_texturergbscale[i] != mesh->texturergbscale[i])
651                         {
652                                 if (mesh_unit != i)
653                                 {
654                                         qglActiveTexture(GL_TEXTURE0_ARB + (mesh_unit = i));CHECKGLERROR
655                                 }
656                                 qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (mesh_texturergbscale[i] = mesh->texturergbscale[i]));CHECKGLERROR
657                         }
658                 }
659         }
660         else
661         {
662                 if (mesh_texture[0] != mesh->textures[0])
663                 {
664                         if (mesh_texture[0] == 0)
665                         {
666                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
667                                 qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
668                         }
669                         qglBindTexture(GL_TEXTURE_2D, (mesh_texture[0] = mesh->textures[0]));CHECKGLERROR
670                         if (mesh_texture[0] == 0)
671                         {
672                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
673                                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
674                         }
675                 }
676         }
677         if (mesh_blendfunc1 != mesh->blendfunc1 || mesh_blendfunc2 != mesh->blendfunc2)
678         {
679                 qglBlendFunc(mesh_blendfunc1 = mesh->blendfunc1, mesh_blendfunc2 = mesh->blendfunc2);CHECKGLERROR
680                 if (mesh_blendfunc2 == GL_ZERO)
681                 {
682                         if (mesh_blendfunc1 == GL_ONE)
683                         {
684                                 if (mesh_blend)
685                                 {
686                                         mesh_blend = 0;
687                                         qglDisable(GL_BLEND);CHECKGLERROR
688                                 }
689                         }
690                         else
691                         {
692                                 if (!mesh_blend)
693                                 {
694                                         mesh_blend = 1;
695                                         qglEnable(GL_BLEND);CHECKGLERROR
696                                 }
697                         }
698                 }
699                 else
700                 {
701                         if (!mesh_blend)
702                         {
703                                 mesh_blend = 1;
704                                 qglEnable(GL_BLEND);CHECKGLERROR
705                         }
706                 }
707         }
708         if (mesh_depthtest != mesh->depthtest)
709         {
710                 mesh_depthtest = mesh->depthtest;
711                 if (mesh_depthtest)
712                         qglEnable(GL_DEPTH_TEST);
713                 else
714                         qglDisable(GL_DEPTH_TEST);
715         }
716         if (mesh_depthmask != mesh->depthmask)
717         {
718                 qglDepthMask(mesh_depthmask = mesh->depthmask);CHECKGLERROR
719         }
720 }
721
722 void GL_DrawRangeElements(int firstvert, int endvert, int indexcount, GLuint *index)
723 {
724         unsigned int i, j, in;
725         if (gl_mesh_drawmode.integer >= 3/* && (endvert - firstvert) <= gl_maxdrawrangeelementsvertices && (indexcount) <= gl_maxdrawrangeelementsindices*/)
726         {
727                 // GL 1.2 or GL 1.1 with extension
728                 qglDrawRangeElements(GL_TRIANGLES, firstvert, endvert, indexcount, GL_UNSIGNED_INT, index);
729         }
730         else if (gl_mesh_drawmode.integer >= 2)
731         {
732                 // GL 1.1
733                 qglDrawElements(GL_TRIANGLES, indexcount, GL_UNSIGNED_INT, index);
734         }
735         else if (gl_mesh_drawmode.integer >= 1)
736         {
737                 // GL 1.1
738                 // feed it manually using glArrayElement
739                 qglBegin(GL_TRIANGLES);
740                 for (i = 0;i < indexcount;i++)
741                         qglArrayElement(index[i]);
742                 qglEnd();
743         }
744         else
745         {
746                 // GL 1.1 but not using vertex arrays - 3dfx glquake minigl driver
747                 // feed it manually
748                 qglBegin(GL_TRIANGLES);
749                 if (r_multitexture.integer)
750                 {
751                         // the minigl doesn't have this (because it does not have ARB_multitexture)
752                         for (i = 0;i < indexcount;i++)
753                         {
754                                 in = index[i];
755                                 qglColor4ub(buf_bcolor[in].c[0], buf_bcolor[in].c[1], buf_bcolor[in].c[2], buf_bcolor[in].c[3]);
756                                 for (j = 0;j < backendunits;j++)
757                                         if (mesh_texture[j])
758                                                 qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, buf_texcoord[j][in].t[0], buf_texcoord[j][in].t[1]);
759                                 qglVertex3f(buf_vertex[in].v[0], buf_vertex[in].v[1], buf_vertex[in].v[2]);
760                         }
761                 }
762                 else
763                 {
764                         for (i = 0;i < indexcount;i++)
765                         {
766                                 in = index[i];
767                                 qglColor4ub(buf_bcolor[in].c[0], buf_bcolor[in].c[1], buf_bcolor[in].c[2], buf_bcolor[in].c[3]);
768                                 if (mesh_texture[0])
769                                         qglTexCoord2f(buf_texcoord[0][in].t[0], buf_texcoord[0][in].t[1]);
770                                 qglVertex3f(buf_vertex[in].v[0], buf_vertex[in].v[1], buf_vertex[in].v[2]);
771                         }
772                 }
773                 qglEnd();
774         }
775 }
776
777 // renders mesh buffers, called to flush buffers when full
778 void R_Mesh_Render(void)
779 {
780         int i;
781         int k;
782         int indexcount;
783         int firstvert;
784         buf_mesh_t *mesh;
785         unsigned int *index;
786
787         if (!backendactive)
788                 Sys_Error("R_Mesh_Render: called when backend is not active\n");
789
790         if (!currentmesh)
791                 return;
792
793         if (!r_render.integer)
794         {
795                 currentmesh = 0;
796                 currenttriangle = 0;
797                 currentvertex = 0;
798                 return;
799         }
800
801         CHECKGLERROR
802
803         // drawmode 0 always uses byte colors
804         if (!gl_mesh_floatcolors.integer || gl_mesh_drawmode.integer <= 0)
805                 GL_ConvertColorsFloatToByte();
806
807         if (gl_backend_rebindtextures)
808         {
809                 gl_backend_rebindtextures = false;
810                 GL_SetupTextureState();
811         }
812
813         GL_MeshState(buf_mesh);
814         GL_LockArray(0, currentvertex);
815         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
816
817         if (currentmesh >= 2)
818         {
819                 for (k = 1, mesh = buf_mesh + k;k < currentmesh;k++, mesh++)
820                 {
821                         GL_MeshState(mesh);
822
823                         firstvert = mesh->firstvert;
824                         indexcount = mesh->triangles * 3;
825                         index = (unsigned int *)&buf_tri[mesh->firsttriangle].index[0];
826
827                         // if not using batching, skip the index adjustment
828                         if (firstvert != 0)
829                                 for (i = 0;i < indexcount;i++)
830                                         index[i] += firstvert;
831
832                         GL_DrawRangeElements(firstvert, firstvert + mesh->verts, indexcount, index);CHECKGLERROR
833                 }
834         }
835
836         currentmesh = 0;
837         currenttriangle = 0;
838         currentvertex = 0;
839
840         GL_UnlockArray();CHECKGLERROR
841 }
842
843 // restores backend state, used when done with 3D rendering
844 void R_Mesh_Finish(void)
845 {
846         int i;
847         // flush any queued meshs
848         if (currentmesh)
849                 R_Mesh_Render();
850
851         if (backendunits > 1)
852         {
853                 for (i = backendunits - 1;i >= 0;i--)
854                 {
855                         qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
856                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
857                         if (gl_combine.integer)
858                         {
859                                 qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
860                         }
861                         if (i > 0)
862                         {
863                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
864                         }
865                         else
866                         {
867                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
868                         }
869                         qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
870
871                         if (usedarrays)
872                         {
873                                 qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
874                                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
875                         }
876                 }
877         }
878         else
879         {
880                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
881                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
882                 if (usedarrays)
883                 {
884                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
885                 }
886         }
887         if (usedarrays)
888         {
889                 qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
890                 qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
891         }
892
893         qglDisable(GL_BLEND);CHECKGLERROR
894         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
895         qglDepthMask(GL_TRUE);CHECKGLERROR
896         qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
897 }
898
899 void R_Mesh_ClearDepth(void)
900 {
901         if (currenttransmesh)
902                 R_Mesh_AddTransparent();
903         if (currentmesh)
904                 R_Mesh_Render();
905         R_Mesh_Finish();
906         qglClear(GL_DEPTH_BUFFER_BIT);
907         R_Mesh_Start(r_mesh_farclip);
908 }
909
910 void R_Mesh_AddTransparent(void)
911 {
912         int i, j, k, *index;
913         float viewdistcompare, centerscaler, dist1, dist2, dist3, center, maxdist;
914         buf_vertex_t *vert1, *vert2, *vert3;
915         buf_transtri_t *tri;
916         buf_mesh_t *mesh, *transmesh;
917
918         if (!currenttransmesh)
919                 return;
920
921         // convert index data to transtris for sorting
922         for (j = 0;j < currenttransmesh;j++)
923         {
924                 mesh = buf_transmesh + j;
925                 k = mesh->firsttriangle;
926                 index = &buf_transtri[k].index[0];
927                 for (i = 0;i < mesh->triangles;i++)
928                 {
929                         tri = &buf_sorttranstri[k++];
930                         tri->mesh = mesh;
931                         tri->index[0] = *index++;
932                         tri->index[1] = *index++;
933                         tri->index[2] = *index++;
934                 }
935         }
936
937         // map farclip to 0-4095 list range
938         centerscaler = (TRANSDEPTHRES / r_mesh_farclip) * (1.0f / 3.0f);
939         viewdistcompare = viewdist + 4.0f;
940
941         memset(buf_sorttranstri_list, 0, TRANSDEPTHRES * sizeof(buf_transtri_t *));
942
943         k = 0;
944         for (j = 0;j < currenttranstriangle;j++)
945         {
946                 tri = &buf_sorttranstri[j];
947                 i = tri->mesh->firstvert;
948
949                 vert1 = &buf_transvertex[tri->index[0] + i];
950                 vert2 = &buf_transvertex[tri->index[1] + i];
951                 vert3 = &buf_transvertex[tri->index[2] + i];
952
953                 dist1 = DotProduct(vert1->v, vpn);
954                 dist2 = DotProduct(vert2->v, vpn);
955                 dist3 = DotProduct(vert3->v, vpn);
956
957                 maxdist = max(dist1, max(dist2, dist3));
958                 if (maxdist < viewdistcompare)
959                         continue;
960
961                 center = (dist1 + dist2 + dist3) * centerscaler - viewdist;
962 #if SLOWMATH
963                 i = (int) center;
964                 i = bound(0, i, (TRANSDEPTHRES - 1));
965 #else
966                 if (center < 0.0f)
967                         center = 0.0f;
968                 center += 8388608.0f;
969                 i = *((int *)&center) & 0x7FFFFF;
970                 i = min(i, (TRANSDEPTHRES - 1));
971 #endif
972                 tri->next = buf_sorttranstri_list[i];
973                 buf_sorttranstri_list[i] = tri;
974                 k++;
975         }
976
977         for (i = 0;i < currenttransmesh;i++)
978                 buf_transmesh[i].transchain = NULL;
979         transmesh = NULL;
980         for (j = 0;j < TRANSDEPTHRES;j++)
981         {
982                 if ((tri = buf_sorttranstri_list[j]))
983                 {
984                         for (;tri;tri = tri->next)
985                         {
986                                 if (!tri->mesh->transchain)
987                                 {
988                                         tri->mesh->chain = transmesh;
989                                         transmesh = tri->mesh;
990                                 }
991                                 tri->meshsortchain = tri->mesh->transchain;
992                                 tri->mesh->transchain = tri;
993                         }
994                 }
995         }
996
997         for (;transmesh;transmesh = transmesh->chain)
998         {
999                 if (currentmesh >= max_meshs || currenttriangle + transmesh->triangles > max_batch || currenttriangle + transmesh->triangles > 1024 || currentvertex + transmesh->verts > max_verts)
1000                         R_Mesh_Render();
1001
1002                 mesh = &buf_mesh[currentmesh++];
1003                 *mesh = *transmesh; // copy mesh properties
1004
1005                 mesh->firstvert = currentvertex;
1006                 memcpy(&buf_vertex[currentvertex], &buf_transvertex[transmesh->firstvert], transmesh->verts * sizeof(buf_vertex_t));
1007                 memcpy(&buf_fcolor[currentvertex], &buf_transfcolor[transmesh->firstvert], transmesh->verts * sizeof(buf_fcolor_t));
1008                 for (i = 0;i < backendunits && transmesh->textures[i];i++)
1009                         memcpy(&buf_texcoord[i][currentvertex], &buf_transtexcoord[i][transmesh->firstvert], transmesh->verts * sizeof(buf_texcoord_t));
1010                 currentvertex += mesh->verts;
1011
1012                 mesh->firsttriangle = currenttriangle;
1013                 for (tri = transmesh->transchain;tri;tri = tri->meshsortchain)
1014                 {
1015                         buf_tri[currenttriangle].index[0] = tri->index[0];
1016                         buf_tri[currenttriangle].index[1] = tri->index[1];
1017                         buf_tri[currenttriangle].index[2] = tri->index[2];
1018                         currenttriangle++;
1019                 }
1020                 mesh->triangles = currenttriangle - mesh->firsttriangle;
1021         }
1022
1023         currenttransmesh = 0;
1024         currenttranstriangle = 0;
1025         currenttransvertex = 0;
1026 }
1027
1028 void R_Mesh_Draw(const rmeshinfo_t *m)
1029 {
1030         // these are static because gcc runs out of virtual registers otherwise
1031         static int i, j, overbright, *index;
1032         static float *in, scaler;
1033         static float cr, cg, cb, ca;
1034         static buf_mesh_t *mesh;
1035         static buf_vertex_t *vert;
1036         static buf_fcolor_t *fcolor;
1037         static buf_texcoord_t *texcoord[MAX_TEXTUREUNITS];
1038
1039         if (!backendactive)
1040                 Sys_Error("R_Mesh_Draw: called when backend is not active\n");
1041
1042         if (m->index == NULL
1043          || !m->numtriangles
1044          || m->vertex == NULL
1045          || !m->numverts)
1046                 Host_Error("R_Mesh_Draw: no triangles or verts\n");
1047
1048         // ignore meaningless alpha meshs
1049         if (!m->depthwrite && m->blendfunc1 == GL_SRC_ALPHA && (m->blendfunc2 == GL_ONE || m->blendfunc2 == GL_ONE_MINUS_SRC_ALPHA))
1050         {
1051                 if (m->color)
1052                 {
1053                         for (i = 0, in = m->color + 3;i < m->numverts;i++, (int)in += m->colorstep)
1054                                 if (*in >= 0.01f)
1055                                         break;
1056                         if (i == m->numverts)
1057                                 return;
1058                 }
1059                 else if (m->ca < 0.01f)
1060                         return;
1061         }
1062
1063         if (!backendactive)
1064                 Sys_Error("R_Mesh_Draw: called when backend is not active\n");
1065
1066 #ifdef DEBUGGL
1067         for (i = 0;i < m->numtriangles * 3;i++)
1068                 if ((unsigned int) m->index[i] >= (unsigned int) m->numverts)
1069                         Host_Error("R_Mesh_Draw: invalid index (%i of %i verts)\n", m->index, m->numverts);
1070 #endif
1071
1072         // LordHavoc: removed this error condition because with floatcolors 0,
1073         // the 3DFX driver works with very large meshs
1074         // FIXME: we can work around this by falling back on non-array renderer if buffers are too big
1075         //if (m->numtriangles > 1024 || m->numverts > 3072)
1076         //{
1077         //      Con_Printf("R_Mesh_Draw: mesh too big for 3DFX drivers, rejected\n");
1078         //      return;
1079         //}
1080
1081         i = max(m->numtriangles * 3, m->numverts);
1082         if (overflowedverts < i)
1083                 overflowedverts = i;
1084
1085         if (m->numtriangles > max_meshs || m->numverts > max_verts)
1086         {
1087                 Con_Printf("R_Mesh_Draw: mesh too big for current gl_mesh_maxtriangles setting, increasing limits\n");
1088                 return;
1089         }
1090
1091         if (m->transparent)
1092         {
1093                 overflowedtransverts += max(m->numtriangles * 3, m->numverts);
1094                 if (currenttransmesh >= max_transmeshs || (currenttranstriangle + m->numtriangles) > max_transmeshs || (currenttransvertex + m->numverts) > max_transverts)
1095                 {
1096                         if (!transranout)
1097                         {
1098                                 Con_Printf("R_Mesh_Draw: ran out of room for transparent meshs\n");
1099                                 transranout = true;
1100                         }
1101                         return;
1102                 }
1103
1104                 c_transmeshs++;
1105                 c_transtris += m->numtriangles;
1106                 vert = &buf_transvertex[currenttransvertex];
1107                 fcolor = &buf_transfcolor[currenttransvertex];
1108                 for (i = 0;i < backendunits;i++)
1109                         texcoord[i] = &buf_transtexcoord[i][currenttransvertex];
1110
1111                 // transmesh is only for storage of transparent meshs until they
1112                 // are inserted into the main mesh array
1113                 mesh = &buf_transmesh[currenttransmesh++];
1114                 mesh->firsttriangle = currenttranstriangle;
1115                 mesh->firstvert = currenttransvertex;
1116                 index = &buf_transtri[currenttranstriangle].index[0];
1117
1118                 currenttranstriangle += m->numtriangles;
1119                 currenttransvertex += m->numverts;
1120         }
1121         else
1122         {
1123                 if (currentmesh >= max_meshs || (currenttriangle + m->numtriangles) > max_batch || (currentvertex + m->numverts) > max_verts)
1124                         R_Mesh_Render();
1125
1126                 c_meshs++;
1127                 c_meshtris += m->numtriangles;
1128                 vert = &buf_vertex[currentvertex];
1129                 fcolor = &buf_fcolor[currentvertex];
1130                 for (i = 0;i < backendunits;i++)
1131                         texcoord[i] = &buf_texcoord[i][currentvertex];
1132
1133                 // opaque meshs are rendered directly
1134                 mesh = &buf_mesh[currentmesh++];
1135                 mesh->firsttriangle = currenttriangle;
1136                 mesh->firstvert = currentvertex;
1137                 index = &buf_tri[currenttriangle].index[0];
1138
1139                 currenttriangle += m->numtriangles;
1140                 currentvertex += m->numverts;
1141         }
1142
1143         // code shared for transparent and opaque meshs
1144         memcpy(index, m->index, sizeof(int[3]) * m->numtriangles);
1145         mesh->blendfunc1 = m->blendfunc1;
1146         mesh->blendfunc2 = m->blendfunc2;
1147         mesh->depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite);
1148         mesh->depthtest = !m->depthdisable;
1149         mesh->triangles = m->numtriangles;
1150         mesh->verts = m->numverts;
1151
1152         overbright = false;
1153         scaler = 1;
1154         if (m->blendfunc1 == GL_DST_COLOR)
1155         {
1156                 // check if it is a 2x modulate with framebuffer
1157                 if (m->blendfunc2 == GL_SRC_COLOR)
1158                         scaler *= 0.5f;
1159         }
1160         else if (m->blendfunc2 != GL_SRC_COLOR)
1161         {
1162                 if (m->tex[0])
1163                 {
1164                         overbright = gl_combine.integer;
1165                         if (overbright)
1166                                 scaler *= 0.25f;
1167                 }
1168                 scaler *= overbrightscale;
1169         }
1170
1171
1172         j = -1;
1173         for (i = 0;i < backendunits;i++)
1174         {
1175                 if ((mesh->textures[i] = m->tex[i]))
1176                         j = i;
1177                 mesh->texturergbscale[i] = m->texrgbscale[i];
1178                 if (mesh->texturergbscale[i] != 1 && mesh->texturergbscale[i] != 2 && mesh->texturergbscale[i] != 4)
1179                         mesh->texturergbscale[i] = 1;
1180         }
1181         if (overbright && j >= 0)
1182                 mesh->texturergbscale[j] = 4;
1183
1184         if (m->vertexstep != sizeof(buf_vertex_t))
1185         {
1186                 for (i = 0, in = m->vertex;i < m->numverts;i++, (int)in += m->vertexstep)
1187                 {
1188                         vert[i].v[0] = in[0];
1189                         vert[i].v[1] = in[1];
1190                         vert[i].v[2] = in[2];
1191                 }
1192         }
1193         else
1194                 memcpy(vert, m->vertex, m->numverts * sizeof(buf_vertex_t));
1195
1196         if (m->color)
1197         {
1198                 for (i = 0, in = m->color;i < m->numverts;i++, (int)in += m->colorstep)
1199                 {
1200                         fcolor[i].c[0] = in[0] * scaler;
1201                         fcolor[i].c[1] = in[1] * scaler;
1202                         fcolor[i].c[2] = in[2] * scaler;
1203                         fcolor[i].c[3] = in[3];
1204                 }
1205         }
1206         else
1207         {
1208                 cr = m->cr * scaler;
1209                 cg = m->cg * scaler;
1210                 cb = m->cb * scaler;
1211                 ca = m->ca;
1212                 for (i = 0;i < m->numverts;i++)
1213                 {
1214                         fcolor[i].c[0] = cr;
1215                         fcolor[i].c[1] = cg;
1216                         fcolor[i].c[2] = cb;
1217                         fcolor[i].c[3] = ca;
1218                 }
1219         }
1220
1221         for (j = 0;j < MAX_TEXTUREUNITS && m->tex[j];j++)
1222         {
1223                 if (j >= backendunits)
1224                         Sys_Error("R_Mesh_Draw: texture %i supplied when there are only %i texture units\n", j + 1, backendunits);
1225                 if (m->texcoordstep[j] != sizeof(buf_texcoord_t))
1226                 {
1227                         for (i = 0, in = m->texcoords[j];i < m->numverts;i++, (int)in += m->texcoordstep[j])
1228                         {
1229                                 texcoord[j][i].t[0] = in[0];
1230                                 texcoord[j][i].t[1] = in[1];
1231                         }
1232                 }
1233                 else
1234                         memcpy(&texcoord[j][0].t[0], m->texcoords[j], m->numverts * sizeof(buf_texcoord_t));
1235         }
1236
1237         if (currenttriangle >= max_batch)
1238                 R_Mesh_Render();
1239 }
1240
1241 // allocates space in geometry buffers, and fills in pointers to the buffers in passsed struct
1242 // (this is used for very high speed rendering, no copying)
1243 int R_Mesh_Draw_GetBuffer(rmeshbufferinfo_t *m)
1244 {
1245         // these are static because gcc runs out of virtual registers otherwise
1246         int i, j, overbright;
1247         float scaler;
1248         buf_mesh_t *mesh;
1249
1250         if (!backendactive)
1251                 Sys_Error("R_Mesh_Draw: called when backend is not active\n");
1252
1253         if (!m->numtriangles
1254          || !m->numverts)
1255                 Host_Error("R_Mesh_Draw: no triangles or verts\n");
1256
1257         // LordHavoc: removed this error condition because with floatcolors 0,
1258         // the 3DFX driver works with very large meshs
1259         // FIXME: we can work around this by falling back on non-array renderer if buffers are too big
1260         //if (m->numtriangles > 1024 || m->numverts > 3072)
1261         //{
1262         //      Con_Printf("R_Mesh_Draw_GetBuffer: mesh too big for 3DFX drivers, rejected\n");
1263         //      return false;
1264         //}
1265
1266         i = max(m->numtriangles * 3, m->numverts);
1267         if (overflowedverts < i)
1268                 overflowedverts = i;
1269
1270         if (m->numtriangles > max_meshs || m->numverts > max_verts)
1271         {
1272                 Con_Printf("R_Mesh_Draw_GetBuffer: mesh too big for current gl_mesh_maxtriangles setting, increasing limits\n");
1273                 return false;
1274         }
1275
1276         if (m->transparent)
1277         {
1278                 overflowedtransverts += max(m->numtriangles * 3, m->numverts);
1279                 if (currenttransmesh >= max_transmeshs || (currenttranstriangle + m->numtriangles) > max_transmeshs || (currenttransvertex + m->numverts) > max_transverts)
1280                 {
1281                         if (!transranout)
1282                         {
1283                                 Con_Printf("R_Mesh_Draw: ran out of room for transparent meshs\n");
1284                                 transranout = true;
1285                         }
1286                         return false;
1287                 }
1288
1289                 c_transmeshs++;
1290                 c_transtris += m->numtriangles;
1291                 m->index = &buf_transtri[currenttranstriangle].index[0];
1292                 m->vertex = &buf_transvertex[currenttransvertex].v[0];
1293                 m->color = &buf_transfcolor[currenttransvertex].c[0];
1294                 for (i = 0;i < backendunits;i++)
1295                         m->texcoords[i] = &buf_transtexcoord[i][currenttransvertex].t[0];
1296
1297                 // transmesh is only for storage of transparent meshs until they
1298                 // are inserted into the main mesh array
1299                 mesh = &buf_transmesh[currenttransmesh++];
1300                 mesh->firsttriangle = currenttranstriangle;
1301                 mesh->firstvert = currenttransvertex;
1302                 currenttranstriangle += m->numtriangles;
1303                 currenttransvertex += m->numverts;
1304         }
1305         else
1306         {
1307                 if (currentmesh >= max_meshs || (currenttriangle + m->numtriangles) > max_batch || (currentvertex + m->numverts) > max_verts)
1308                         R_Mesh_Render();
1309
1310                 c_meshs++;
1311                 c_meshtris += m->numtriangles;
1312                 m->index = &buf_tri[currenttriangle].index[0];
1313                 m->vertex = &buf_vertex[currentvertex].v[0];
1314                 m->color = &buf_fcolor[currentvertex].c[0];
1315                 for (i = 0;i < backendunits;i++)
1316                         m->texcoords[i] = &buf_texcoord[i][currentvertex].t[0];
1317
1318                 // opaque meshs are rendered directly
1319                 mesh = &buf_mesh[currentmesh++];
1320                 mesh->firsttriangle = currenttriangle;
1321                 mesh->firstvert = currentvertex;
1322                 currenttriangle += m->numtriangles;
1323                 currentvertex += m->numverts;
1324         }
1325
1326         // code shared for transparent and opaque meshs
1327         mesh->blendfunc1 = m->blendfunc1;
1328         mesh->blendfunc2 = m->blendfunc2;
1329         mesh->depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite);
1330         mesh->depthtest = !m->depthdisable;
1331         mesh->triangles = m->numtriangles;
1332         mesh->verts = m->numverts;
1333
1334         overbright = false;
1335         scaler = 1;
1336         if (m->blendfunc1 == GL_DST_COLOR)
1337         {
1338                 // check if it is a 2x modulate with framebuffer
1339                 if (m->blendfunc2 == GL_SRC_COLOR)
1340                         scaler *= 0.5f;
1341         }
1342         else if (m->blendfunc2 != GL_SRC_COLOR)
1343         {
1344                 if (m->tex[0])
1345                 {
1346                         overbright = gl_combine.integer;
1347                         if (overbright)
1348                                 scaler *= 0.25f;
1349                 }
1350                 scaler *= overbrightscale;
1351         }
1352         m->colorscale = scaler;
1353
1354         j = -1;
1355         for (i = 0;i < MAX_TEXTUREUNITS;i++)
1356         {
1357                 if ((mesh->textures[i] = m->tex[i]))
1358                 {
1359                         j = i;
1360                         if (i >= backendunits)
1361                                 Sys_Error("R_Mesh_Draw_GetBuffer: texture %i supplied when there are only %i texture units\n", j + 1, backendunits);
1362                 }
1363                 mesh->texturergbscale[i] = m->texrgbscale[i];
1364                 if (mesh->texturergbscale[i] != 1 && mesh->texturergbscale[i] != 2 && mesh->texturergbscale[i] != 4)
1365                         mesh->texturergbscale[i] = 1;
1366         }
1367         if (overbright && j >= 0)
1368                 mesh->texturergbscale[j] = 4;
1369
1370         return true;
1371 }
1372
1373 void R_Mesh_DrawPolygon(rmeshinfo_t *m, int numverts)
1374 {
1375         m->index = polyindexarray;
1376         m->numverts = numverts;
1377         m->numtriangles = numverts - 2;
1378         if (m->numtriangles < 1)
1379         {
1380                 Con_Printf("R_Mesh_DrawPolygon: invalid vertex count\n");
1381                 return;
1382         }
1383         if (m->numtriangles >= 256)
1384         {
1385                 Con_Printf("R_Mesh_DrawPolygon: only up to 256 triangles (258 verts) supported\n");
1386                 return;
1387         }
1388         R_Mesh_Draw(m);
1389 }
1390
1391 /*
1392 ==============================================================================
1393
1394                                                 SCREEN SHOTS
1395
1396 ==============================================================================
1397 */
1398
1399 qboolean SCR_ScreenShot(char *filename, int x, int y, int width, int height)
1400 {
1401         qboolean ret;
1402         int i;
1403         qbyte *buffer;
1404
1405         if (!r_render.integer)
1406                 return false;
1407
1408         buffer = Mem_Alloc(tempmempool, width*height*3);
1409         qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
1410         CHECKGLERROR
1411
1412         // LordHavoc: compensate for v_overbrightbits when using hardware gamma
1413         if (v_hwgamma.integer)
1414                 for (i = 0;i < width * height * 3;i++)
1415                         buffer[i] <<= v_overbrightbits.integer;
1416
1417         ret = Image_WriteTGARGB_preflipped(filename, width, height, buffer);
1418
1419         Mem_Free(buffer);
1420         return ret;
1421 }
1422
1423 //=============================================================================
1424
1425 void R_ClearScreen(void)
1426 {
1427         if (r_render.integer)
1428         {
1429                 // clear to black
1430                 qglClearColor(0,0,0,0);CHECKGLERROR
1431                 // clear the screen
1432                 qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);CHECKGLERROR
1433                 // set dithering mode
1434                 if (gl_dither.integer)
1435                 {
1436                         qglEnable(GL_DITHER);CHECKGLERROR
1437                 }
1438                 else
1439                 {
1440                         qglDisable(GL_DITHER);CHECKGLERROR
1441                 }
1442         }
1443 }
1444
1445 /*
1446 ==================
1447 SCR_UpdateScreen
1448
1449 This is called every frame, and can also be called explicitly to flush
1450 text to the screen.
1451 ==================
1452 */
1453 void SCR_UpdateScreen (void)
1454 {
1455         VID_Finish ();
1456
1457         R_TimeReport("finish");
1458
1459         if (gl_combine.integer && !gl_combine_extension)
1460                 Cvar_SetValue("gl_combine", 0);
1461
1462         lightscalebit = v_overbrightbits.integer;
1463         if (gl_combine.integer && r_multitexture.integer)
1464                 lightscalebit += 2;
1465
1466         lightscale = 1.0f / (float) (1 << lightscalebit);
1467         overbrightscale = 1.0f / (float) (1 << v_overbrightbits.integer);
1468
1469         R_TimeReport("setup");
1470
1471         R_ClearScreen();
1472
1473         R_TimeReport("clear");
1474
1475         if (scr_conlines < vid.conheight)
1476                 R_RenderView();
1477
1478         // draw 2D stuff
1479         R_DrawQueue();
1480
1481         // tell driver to commit it's partially full geometry queue to the rendering queue
1482         // (this doesn't wait for the commands themselves to complete)
1483         qglFlush();
1484 }
1485