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