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