]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - gl_backend.c
cleaned up backend code a bit more, added R_Mesh_Draw_GetBuffer (untested - returns...
[xonotic/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, *index;
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                 index = &buf_transtri[currenttranstriangle].index[0];
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                 index = &buf_tri[currenttriangle].index[0];
991
992                 currenttriangle += m->numtriangles;
993                 currentvertex += m->numverts;
994         }
995
996         // code shared for transparent and opaque meshs
997         memcpy(index, m->index, sizeof(int[3]) * m->numtriangles);
998         mesh->blendfunc1 = m->blendfunc1;
999         mesh->blendfunc2 = m->blendfunc2;
1000         mesh->depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite);
1001         mesh->depthtest = !m->depthdisable;
1002         mesh->triangles = m->numtriangles;
1003         mesh->verts = m->numverts;
1004
1005         overbright = false;
1006         scaler = 1;
1007         if (m->blendfunc2 == GL_SRC_COLOR)
1008         {
1009                 if (m->blendfunc1 == GL_DST_COLOR) // 2x modulate with framebuffer
1010                         scaler *= 0.5f;
1011         }
1012         else
1013         {
1014                 if (m->tex[0])
1015                 {
1016                         overbright = gl_combine.integer;
1017                         if (overbright)
1018                                 scaler *= 0.25f;
1019                 }
1020                 scaler *= overbrightscale;
1021         }
1022
1023
1024         j = -1;
1025         for (i = 0;i < backendunits;i++)
1026         {
1027                 if ((mesh->textures[i] = m->tex[i]))
1028                         j = i;
1029                 mesh->texturergbscale[i] = m->texrgbscale[i];
1030                 if (mesh->texturergbscale[i] != 1 && mesh->texturergbscale[i] != 2 && mesh->texturergbscale[i] != 4)
1031                         mesh->texturergbscale[i] = 1;
1032         }
1033         if (overbright && j >= 0)
1034                 mesh->texturergbscale[j] = 4;
1035
1036         if (m->vertexstep != sizeof(buf_vertex_t))
1037         {
1038                 for (i = 0, in = m->vertex;i < m->numverts;i++, (int)in += m->vertexstep)
1039                 {
1040                         vert[i].v[0] = in[0];
1041                         vert[i].v[1] = in[1];
1042                         vert[i].v[2] = in[2];
1043                 }
1044         }
1045         else
1046                 memcpy(vert, m->vertex, m->numverts * sizeof(buf_vertex_t));
1047
1048         if (m->color)
1049         {
1050                 for (i = 0, in = m->color;i < m->numverts;i++, (int)in += m->colorstep)
1051                 {
1052                         fcolor[i].c[0] = in[0] * scaler;
1053                         fcolor[i].c[1] = in[1] * scaler;
1054                         fcolor[i].c[2] = in[2] * scaler;
1055                         fcolor[i].c[3] = in[3];
1056                 }
1057         }
1058         else
1059         {
1060                 cr = m->cr * scaler;
1061                 cg = m->cg * scaler;
1062                 cb = m->cb * scaler;
1063                 ca = m->ca;
1064                 for (i = 0;i < m->numverts;i++)
1065                 {
1066                         fcolor[i].c[0] = cr;
1067                         fcolor[i].c[1] = cg;
1068                         fcolor[i].c[2] = cb;
1069                         fcolor[i].c[3] = ca;
1070                 }
1071         }
1072
1073         for (j = 0;j < MAX_TEXTUREUNITS && m->tex[j];j++)
1074         {
1075                 if (j >= backendunits)
1076                         Sys_Error("R_Mesh_Draw: texture %i supplied when there are only %i texture units\n", j + 1, backendunits);
1077                 if (m->texcoordstep[j] != sizeof(buf_texcoord_t))
1078                 {
1079                         for (i = 0, in = m->texcoords[j];i < m->numverts;i++, (int)in += m->texcoordstep[j])
1080                         {
1081                                 texcoord[j][i].t[0] = in[0];
1082                                 texcoord[j][i].t[1] = in[1];
1083                         }
1084                 }
1085                 else
1086                         memcpy(&texcoord[j][0].t[0], m->texcoords[j], m->numverts * sizeof(buf_texcoord_t));
1087         }
1088         #if 0
1089         for (;j < backendunits;j++)
1090                 memset(&texcoord[j][0].t[0], 0, m->numverts * sizeof(buf_texcoord_t));
1091         #endif
1092 }
1093
1094 void R_Mesh_Draw_NativeOnly(const rmeshinfo_t *m)
1095 {
1096         // these are static because gcc runs out of virtual registers otherwise
1097         static int i, j, overbright, *index;
1098         static float *in, scaler;
1099         static buf_mesh_t *mesh;
1100         static buf_vertex_t *vert;
1101         static buf_fcolor_t *fcolor;
1102         static buf_texcoord_t *texcoord[MAX_TEXTUREUNITS];
1103
1104         if (!backendactive)
1105                 Sys_Error("R_Mesh_Draw: called when backend is not active\n");
1106
1107         if (m->index == NULL
1108          || !m->numtriangles
1109          || m->vertex == NULL
1110          || !m->numverts)
1111                 Host_Error("R_Mesh_Draw: no triangles or verts\n");
1112
1113         // ignore meaningless alpha meshs
1114         if (!m->depthwrite && m->blendfunc1 == GL_SRC_ALPHA && (m->blendfunc2 == GL_ONE || m->blendfunc2 == GL_ONE_MINUS_SRC_ALPHA))
1115         {
1116                 if (m->color)
1117                 {
1118                         for (i = 0, in = m->color + 3;i < m->numverts;i++, (int)in += m->colorstep)
1119                                 if (*in >= 0.01f)
1120                                         break;
1121                         if (i == m->numverts)
1122                                 return;
1123                 }
1124                 else if (m->ca < 0.01f)
1125                         return;
1126         }
1127
1128         if (m->transparent)
1129         {
1130                 if (currenttransmesh >= max_meshs || (currenttranstriangle + m->numtriangles) > max_meshs || (currenttransvertex + m->numverts) > max_verts)
1131                 {
1132                         if (!transranout)
1133                         {
1134                                 Con_Printf("R_Mesh_Draw_NativeOnly: ran out of room for transparent meshs\n");
1135                                 transranout = true;
1136                         }
1137                         return;
1138                 }
1139
1140                 c_transmeshs++;
1141                 c_transtris += m->numtriangles;
1142                 vert = &buf_transvertex[currenttransvertex];
1143                 fcolor = &buf_transfcolor[currenttransvertex];
1144                 for (i = 0;i < backendunits;i++)
1145                         texcoord[i] = &buf_transtexcoord[i][currenttransvertex];
1146
1147                 // transmesh is only for storage of transparent meshs until they
1148                 // are inserted into the main mesh array
1149                 mesh = &buf_transmesh[currenttransmesh++];
1150                 mesh->firsttriangle = currenttranstriangle;
1151                 mesh->firstvert = currenttransvertex;
1152                 index = &buf_transtri[currenttranstriangle].index[0];
1153                 currenttranstriangle += m->numtriangles;
1154                 currenttransvertex += m->numverts;
1155         }
1156         else
1157         {
1158                 if (m->numtriangles > max_meshs || m->numverts > max_verts)
1159                 {
1160                         Con_Printf("R_Mesh_Draw_NativeOnly: mesh too big for buffers\n");
1161                         return;
1162                 }
1163
1164                 if (currentmesh >= max_meshs || (currenttriangle + m->numtriangles) > max_batch || (currentvertex + m->numverts) > max_verts)
1165                         R_Mesh_Render();
1166
1167                 c_meshs++;
1168                 c_meshtris += m->numtriangles;
1169                 vert = &buf_vertex[currentvertex];
1170                 fcolor = &buf_fcolor[currentvertex];
1171                 for (i = 0;i < backendunits;i++)
1172                         texcoord[i] = &buf_texcoord[i][currentvertex];
1173
1174                 // opaque meshs are rendered directly
1175                 mesh = &buf_mesh[currentmesh++];
1176                 mesh->firsttriangle = currenttriangle;
1177                 mesh->firstvert = currentvertex;
1178                 index = &buf_tri[currenttriangle].index[0];
1179                 currenttriangle += m->numtriangles;
1180                 currentvertex += m->numverts;
1181         }
1182
1183         // code shared for transparent and opaque meshs
1184         memcpy(index, m->index, sizeof(int[3]) * m->numtriangles);
1185         mesh->blendfunc1 = m->blendfunc1;
1186         mesh->blendfunc2 = m->blendfunc2;
1187         mesh->depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite);
1188         mesh->depthtest = !m->depthdisable;
1189         mesh->triangles = m->numtriangles;
1190         mesh->verts = m->numverts;
1191
1192         overbright = false;
1193         scaler = 1;
1194         if (m->blendfunc2 == GL_SRC_COLOR)
1195         {
1196                 if (m->blendfunc1 == GL_DST_COLOR) // 2x modulate with framebuffer
1197                         scaler *= 0.5f;
1198         }
1199         else
1200         {
1201                 if (m->tex[0])
1202                 {
1203                         overbright = gl_combine.integer;
1204                         if (overbright)
1205                                 scaler *= 0.25f;
1206                 }
1207                 scaler *= overbrightscale;
1208         }
1209
1210         j = -1;
1211         for (i = 0;i < backendunits;i++)
1212         {
1213                 if ((mesh->textures[i] = m->tex[i]))
1214                         j = i;
1215                 mesh->texturergbscale[i] = m->texrgbscale[i];
1216                 if (mesh->texturergbscale[i] != 1 && mesh->texturergbscale[i] != 2 && mesh->texturergbscale[i] != 4)
1217                         mesh->texturergbscale[i] = 1;
1218         }
1219         if (overbright && j >= 0)
1220                 mesh->texturergbscale[j] = 4;
1221
1222         if (m->vertexstep != sizeof(buf_vertex_t))
1223                 Host_Error("R_Mesh_Draw_NativeOnly: unsupported vertexstep\n");
1224         if (m->colorstep != sizeof(buf_fcolor_t))
1225                 Host_Error("R_Mesh_Draw_NativeOnly: unsupported colorstep\n");
1226         if (m->color == NULL)
1227                 Host_Error("R_Mesh_Draw_NativeOnly: must provide color array\n");
1228         for (j = 0;j < MAX_TEXTUREUNITS && m->tex[j];j++)
1229         {
1230                 if (j >= backendunits)
1231                         Sys_Error("R_Mesh_Draw_NativeOnly: texture %i supplied when there are only %i texture units\n", j + 1, backendunits);
1232                 if (m->texcoordstep[j] != sizeof(buf_texcoord_t))
1233                         Host_Error("R_Mesh_Draw_NativeOnly: unsupported texcoordstep\n");
1234         }
1235
1236         memcpy(vert, m->vertex, m->numverts * sizeof(buf_vertex_t));
1237         for (j = 0;j < MAX_TEXTUREUNITS && m->tex[j];j++)
1238                 memcpy(&texcoord[j][0].t[0], m->texcoords[j], m->numverts * sizeof(buf_texcoord_t));
1239         #if 0
1240         for (;j < backendunits;j++)
1241                 memset(&texcoord[j][0].t[0], 0, m->numverts * sizeof(buf_texcoord_t));
1242         #endif
1243
1244         memcpy(fcolor, m->color, m->numverts * sizeof(buf_fcolor_t));
1245
1246         // do this as a second step because memcpy preloaded the cache, which we can't easily do
1247         if (scaler != 1)
1248         {
1249                 for (i = 0;i < m->numverts;i++)
1250                 {
1251                         fcolor[i].c[0] *= scaler;
1252                         fcolor[i].c[1] *= scaler;
1253                         fcolor[i].c[2] *= scaler;
1254                 }
1255         }
1256 }
1257
1258 // allocates space in geometry buffers, and fills in pointers to the buffers in passsed struct
1259 // (this is used for very high speed rendering, no copying)
1260 int R_Mesh_Draw_GetBuffer(rmeshbufferinfo_t *m)
1261 {
1262         // these are static because gcc runs out of virtual registers otherwise
1263         int i, j, overbright;
1264         float scaler;
1265         buf_mesh_t *mesh;
1266
1267         if (!backendactive)
1268                 Sys_Error("R_Mesh_Draw: called when backend is not active\n");
1269
1270         if (!m->numtriangles
1271          || !m->numverts)
1272                 Host_Error("R_Mesh_Draw: no triangles or verts\n");
1273
1274         if (m->transparent)
1275         {
1276                 if (currenttransmesh >= max_meshs || (currenttranstriangle + m->numtriangles) > max_meshs || (currenttransvertex + m->numverts) > max_verts)
1277                 {
1278                         if (!transranout)
1279                         {
1280                                 Con_Printf("R_Mesh_Draw: ran out of room for transparent meshs\n");
1281                                 transranout = true;
1282                         }
1283                         return false;
1284                 }
1285
1286                 c_transmeshs++;
1287                 c_transtris += m->numtriangles;
1288                 m->index = &buf_transtri[currenttranstriangle].index[0];
1289                 m->vertex = &buf_transvertex[currenttransvertex].v[0];
1290                 m->color = &buf_transfcolor[currenttransvertex].c[0];
1291                 for (i = 0;i < backendunits;i++)
1292                         m->texcoords[i] = &buf_transtexcoord[i][currenttransvertex].t[0];
1293
1294                 // transmesh is only for storage of transparent meshs until they
1295                 // are inserted into the main mesh array
1296                 mesh = &buf_transmesh[currenttransmesh++];
1297                 mesh->firsttriangle = currenttranstriangle;
1298                 mesh->firstvert = currenttransvertex;
1299                 currenttranstriangle += m->numtriangles;
1300                 currenttransvertex += m->numverts;
1301         }
1302         else
1303         {
1304                 if (m->numtriangles > max_meshs || m->numverts > max_verts)
1305                 {
1306                         Con_Printf("R_Mesh_Draw_GetBuffer: mesh too big for buffers\n");
1307                         return false;
1308                 }
1309
1310                 if (currentmesh >= max_meshs || (currenttriangle + m->numtriangles) > max_batch || (currentvertex + m->numverts) > max_verts)
1311                         R_Mesh_Render();
1312
1313                 c_meshs++;
1314                 c_meshtris += m->numtriangles;
1315                 m->index = &buf_tri[currenttriangle].index[0];
1316                 m->vertex = &buf_vertex[currentvertex].v[0];
1317                 m->color = &buf_fcolor[currentvertex].c[0];
1318                 for (i = 0;i < backendunits;i++)
1319                         m->texcoords[i] = &buf_texcoord[i][currentvertex].t[0];
1320
1321                 // opaque meshs are rendered directly
1322                 mesh = &buf_mesh[currentmesh++];
1323                 mesh->firsttriangle = currenttriangle;
1324                 mesh->firstvert = currentvertex;
1325                 currenttriangle += m->numtriangles;
1326                 currentvertex += m->numverts;
1327         }
1328
1329         // code shared for transparent and opaque meshs
1330         mesh->blendfunc1 = m->blendfunc1;
1331         mesh->blendfunc2 = m->blendfunc2;
1332         mesh->depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite);
1333         mesh->depthtest = !m->depthdisable;
1334         mesh->triangles = m->numtriangles;
1335         mesh->verts = m->numverts;
1336
1337         overbright = false;
1338         scaler = 1;
1339         if (m->blendfunc2 == GL_SRC_COLOR)
1340         {
1341                 if (m->blendfunc1 == GL_DST_COLOR) // 2x modulate with framebuffer
1342                         scaler *= 0.5f;
1343         }
1344         else
1345         {
1346                 if (m->tex[0])
1347                 {
1348                         overbright = gl_combine.integer;
1349                         if (overbright)
1350                                 scaler *= 0.25f;
1351                 }
1352                 scaler *= overbrightscale;
1353         }
1354         m->colorscale = scaler;
1355
1356         j = -1;
1357         for (i = 0;i < MAX_TEXTUREUNITS;i++)
1358         {
1359                 if ((mesh->textures[i] = m->tex[i]))
1360                 {
1361                         j = i;
1362                         if (i >= backendunits)
1363                                 Sys_Error("R_Mesh_Draw_GetBuffer: texture %i supplied when there are only %i texture units\n", j + 1, backendunits);
1364                 }
1365                 mesh->texturergbscale[i] = m->texrgbscale[i];
1366                 if (mesh->texturergbscale[i] != 1 && mesh->texturergbscale[i] != 2 && mesh->texturergbscale[i] != 4)
1367                         mesh->texturergbscale[i] = 1;
1368         }
1369         if (overbright && j >= 0)
1370                 mesh->texturergbscale[j] = 4;
1371
1372         return true;
1373 }
1374
1375 void R_Mesh_DrawPolygon(rmeshinfo_t *m, int numverts)
1376 {
1377         m->index = polyindexarray;
1378         m->numverts = numverts;
1379         m->numtriangles = numverts - 2;
1380         if (m->numtriangles < 1)
1381         {
1382                 Con_Printf("R_Mesh_DrawPolygon: invalid vertex count\n");
1383                 return;
1384         }
1385         if (m->numtriangles >= 256)
1386         {
1387                 Con_Printf("R_Mesh_DrawPolygon: only up to 256 triangles (258 verts) supported\n");
1388                 return;
1389         }
1390         R_Mesh_Draw(m);
1391 }
1392
1393 /*
1394 ==============================================================================
1395
1396                                                 SCREEN SHOTS
1397
1398 ==============================================================================
1399 */
1400
1401 float CalcFov (float fov_x, float width, float height);
1402 void R_ClearScreen(void);
1403
1404 void SCR_ScreenShot(char *filename, int x, int y, int width, int height)
1405 {
1406         int i;
1407         byte *buffer;
1408
1409         buffer = Mem_Alloc(tempmempool, width*height*3);
1410         glReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
1411         CHECKGLERROR
1412
1413         // LordHavoc: compensate for v_overbrightbits when using hardware gamma
1414         if (v_hwgamma.integer)
1415                 for (i = 0;i < width * height * 3;i++)
1416                         buffer[i] <<= v_overbrightbits.integer;
1417
1418         Image_WriteTGARGB_preflipped(filename, width, height, buffer);
1419
1420         Mem_Free(buffer);
1421 }
1422
1423 /*
1424 ==================
1425 SCR_ScreenShot_f
1426 ==================
1427 */
1428 void SCR_ScreenShot_f (void)
1429 {
1430         int i;
1431         char filename[16];
1432         char checkname[MAX_OSPATH];
1433 //
1434 // find a file name to save it to
1435 //
1436         strcpy(filename, "dp0000.tga");
1437
1438         for (i=0 ; i<=9999 ; i++)
1439         {
1440                 filename[2] = (i/1000)%10 + '0';
1441                 filename[3] = (i/ 100)%10 + '0';
1442                 filename[4] = (i/  10)%10 + '0';
1443                 filename[5] = (i/   1)%10 + '0';
1444                 sprintf (checkname, "%s/%s", com_gamedir, filename);
1445                 if (Sys_FileTime(checkname) == -1)
1446                         break;  // file doesn't exist
1447         }
1448         if (i==10000)
1449         {
1450                 Con_Printf ("SCR_ScreenShot_f: Couldn't create a TGA file\n");
1451                 return;
1452         }
1453
1454         SCR_ScreenShot(filename, vid.realx, vid.realy, vid.realwidth, vid.realheight);
1455         Con_Printf ("Wrote %s\n", filename);
1456 }
1457
1458 /*
1459 ===============
1460 R_Envmap_f
1461
1462 Grab six views for environment mapping tests
1463 ===============
1464 */
1465 struct
1466 {
1467         float angles[3];
1468         char *name;
1469 }
1470 envmapinfo[6] =
1471 {
1472         {{  0,   0, 0}, "ft"},
1473         {{  0,  90, 0}, "rt"},
1474         {{  0, 180, 0}, "bk"},
1475         {{  0, 270, 0}, "lf"},
1476         {{-90,  90, 0}, "up"},
1477         {{ 90,  90, 0}, "dn"}
1478 };
1479 static void R_Envmap_f (void)
1480 {
1481         int j, size;
1482         char filename[256], basename[256];
1483
1484         if (Cmd_Argc() != 3)
1485         {
1486                 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");
1487                 return;
1488         }
1489
1490         if (!r_render.integer)
1491                 return;
1492
1493         strcpy(basename, Cmd_Argv(1));
1494         size = atoi(Cmd_Argv(2));
1495         if (size != 128 && size != 256 && size != 512 && size != 1024)
1496         {
1497                 Con_Printf("envmap: size must be one of 128, 256, 512, or 1024\n");
1498                 return;
1499         }
1500         if (size > vid.realwidth || size > vid.realheight)
1501         {
1502                 Con_Printf("envmap: your resolution is not big enough to render that size\n");
1503                 return;
1504         }
1505
1506         envmap = true;
1507
1508         r_refdef.x = 0;
1509         r_refdef.y = 0;
1510         r_refdef.width = size;
1511         r_refdef.height = size;
1512
1513         r_refdef.fov_x = 90;
1514         r_refdef.fov_y = 90;
1515
1516         for (j = 0;j < 6;j++)
1517         {
1518                 sprintf(filename, "env/%s%s.tga", basename, envmapinfo[j].name);
1519                 VectorCopy(envmapinfo[j].angles, r_refdef.viewangles);
1520                 R_ClearScreen();
1521                 R_RenderView ();
1522                 SCR_ScreenShot(filename, vid.realx, vid.realy, size, size);
1523         }
1524
1525         envmap = false;
1526 }
1527
1528 //=============================================================================
1529
1530 void R_ClearScreen(void)
1531 {
1532         if (r_render.integer)
1533         {
1534                 glClearColor(0,0,0,0);
1535                 CHECKGLERROR
1536                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // LordHavoc: clear the screen (around the view as well)
1537                 CHECKGLERROR
1538                 if (gl_dither.integer)
1539                         glEnable(GL_DITHER);
1540                 else
1541                         glDisable(GL_DITHER);
1542                 CHECKGLERROR
1543         }
1544 }
1545
1546 /*
1547 ==================
1548 SCR_UpdateScreen
1549
1550 This is called every frame, and can also be called explicitly to flush
1551 text to the screen.
1552 ==================
1553 */
1554 void SCR_UpdateScreen (void)
1555 {
1556         //Mem_CheckSentinelsGlobal();
1557         //R_TimeReport("memtest");
1558
1559         glFinish ();
1560         CHECKGLERROR
1561
1562         VID_Finish ();
1563
1564         R_TimeReport("finish");
1565
1566         if (gl_combine.integer && !gl_combine_extension)
1567                 Cvar_SetValue("gl_combine", 0);
1568
1569         lightscalebit = v_overbrightbits.integer;
1570         if (gl_combine.integer && r_multitexture.integer)
1571                 lightscalebit += 2;
1572
1573         lightscale = 1.0f / (float) (1 << lightscalebit);
1574         overbrightscale = 1.0f / (float) (1 << v_overbrightbits.integer);
1575
1576         R_TimeReport("setup");
1577
1578         R_ClearScreen();
1579
1580         R_TimeReport("clear");
1581
1582         if (scr_conlines < vid.conheight)
1583                 R_RenderView();
1584
1585         // draw 2D stuff
1586         R_DrawQueue();
1587 }