fixed gl_paranoid warnings in R_DrawQueue
[xonotic/darkplaces.git] / gl_backend.c
1
2 #include "quakedef.h"
3 #include "image.h"
4 #include "jpeg.h"
5 #include "cl_collision.h"
6
7 cvar_t gl_mesh_drawrangeelements = {0, "gl_mesh_drawrangeelements", "1"};
8 cvar_t gl_mesh_testarrayelement = {0, "gl_mesh_testarrayelement", "0"};
9 cvar_t gl_mesh_testmanualfeeding = {0, "gl_mesh_testmanualfeeding", "0"};
10 cvar_t gl_delayfinish = {CVAR_SAVE, "gl_delayfinish", "0"};
11 cvar_t gl_paranoid = {0, "gl_paranoid", "0"};
12 cvar_t gl_printcheckerror = {0, "gl_printcheckerror", "0"};
13
14 cvar_t r_render = {0, "r_render", "1"};
15 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1"}; // whether or not to use dithering
16 cvar_t gl_lockarrays = {0, "gl_lockarrays", "1"};
17
18 int gl_maxdrawrangeelementsvertices;
19 int gl_maxdrawrangeelementsindices;
20
21 #ifdef DEBUGGL
22 int errornumber = 0;
23
24 void GL_PrintError(int errornumber, char *filename, int linenumber)
25 {
26         switch(errornumber)
27         {
28 #ifdef GL_INVALID_ENUM
29         case GL_INVALID_ENUM:
30                 Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
31                 break;
32 #endif
33 #ifdef GL_INVALID_VALUE
34         case GL_INVALID_VALUE:
35                 Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
36                 break;
37 #endif
38 #ifdef GL_INVALID_OPERATION
39         case GL_INVALID_OPERATION:
40                 Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
41                 break;
42 #endif
43 #ifdef GL_STACK_OVERFLOW
44         case GL_STACK_OVERFLOW:
45                 Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
46                 break;
47 #endif
48 #ifdef GL_STACK_UNDERFLOW
49         case GL_STACK_UNDERFLOW:
50                 Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
51                 break;
52 #endif
53 #ifdef GL_OUT_OF_MEMORY
54         case GL_OUT_OF_MEMORY:
55                 Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
56                 break;
57 #endif
58 #ifdef GL_TABLE_TOO_LARGE
59         case GL_TABLE_TOO_LARGE:
60                 Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
61                 break;
62 #endif
63         default:
64                 Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
65                 break;
66         }
67 }
68 #endif
69
70 #define BACKENDACTIVECHECK if (!backendactive) Sys_Error("GL backend function called when backend is not active\n");
71
72 int c_meshs, c_meshelements;
73
74 void SCR_ScreenShot_f (void);
75
76 static matrix4x4_t backend_viewmatrix;
77 static matrix4x4_t backend_modelmatrix;
78 static matrix4x4_t backend_modelviewmatrix;
79 static matrix4x4_t backend_glmodelviewmatrix;
80 static matrix4x4_t backend_projectmatrix;
81
82 static int backendunits, backendactive;
83 static mempool_t *gl_backend_mempool;
84
85 /*
86 note: here's strip order for a terrain row:
87 0--1--2--3--4
88 |\ |\ |\ |\ |
89 | \| \| \| \|
90 A--B--C--D--E
91 clockwise
92
93 A0B, 01B, B1C, 12C, C2D, 23D, D3E, 34E
94
95 *elements++ = i + row;
96 *elements++ = i;
97 *elements++ = i + row + 1;
98 *elements++ = i;
99 *elements++ = i + 1;
100 *elements++ = i + row + 1;
101
102
103 for (y = 0;y < rows - 1;y++)
104 {
105         for (x = 0;x < columns - 1;x++)
106         {
107                 i = y * rows + x;
108                 *elements++ = i + columns;
109                 *elements++ = i;
110                 *elements++ = i + columns + 1;
111                 *elements++ = i;
112                 *elements++ = i + 1;
113                 *elements++ = i + columns + 1;
114         }
115 }
116
117 alternative:
118 0--1--2--3--4
119 | /| /|\ | /|
120 |/ |/ | \|/ |
121 A--B--C--D--E
122 counterclockwise
123
124 for (y = 0;y < rows - 1;y++)
125 {
126         for (x = 0;x < columns - 1;x++)
127         {
128                 i = y * rows + x;
129                 *elements++ = i;
130                 *elements++ = i + columns;
131                 *elements++ = i + columns + 1;
132                 *elements++ = i + columns;
133                 *elements++ = i + columns + 1;
134                 *elements++ = i + 1;
135         }
136 }
137 */
138
139 int polygonelements[768];
140
141 static void R_Mesh_CacheArray_Startup(void);
142 static void R_Mesh_CacheArray_Shutdown(void);
143 void GL_Backend_AllocArrays(void)
144 {
145         if (!gl_backend_mempool)
146                 gl_backend_mempool = Mem_AllocPool("GL_Backend");
147         R_Mesh_CacheArray_Startup();
148 }
149
150 void GL_Backend_FreeArrays(void)
151 {
152         R_Mesh_CacheArray_Shutdown();
153         Mem_FreePool(&gl_backend_mempool);
154 }
155
156 static void gl_backend_start(void)
157 {
158         Con_DPrint("OpenGL Backend started\n");
159         if (qglDrawRangeElements != NULL)
160         {
161                 CHECKGLERROR
162                 qglGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &gl_maxdrawrangeelementsvertices);
163                 CHECKGLERROR
164                 qglGetIntegerv(GL_MAX_ELEMENTS_INDICES, &gl_maxdrawrangeelementsindices);
165                 CHECKGLERROR
166                 Con_DPrintf("glDrawRangeElements detected (max vertices %i, max indices %i)\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
167         }
168
169         backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
170
171         GL_Backend_AllocArrays();
172
173         backendactive = true;
174 }
175
176 static void gl_backend_shutdown(void)
177 {
178         backendunits = 0;
179         backendactive = false;
180
181         Con_DPrint("OpenGL Backend shutting down\n");
182
183         GL_Backend_FreeArrays();
184 }
185
186 static void gl_backend_newmap(void)
187 {
188 }
189
190 cvar_t scr_zoomwindow = {CVAR_SAVE, "scr_zoomwindow", "0"};
191 cvar_t scr_zoomwindow_viewsizex = {CVAR_SAVE, "scr_zoomwindow_viewsizex", "20"};
192 cvar_t scr_zoomwindow_viewsizey = {CVAR_SAVE, "scr_zoomwindow_viewsizey", "20"};
193 cvar_t scr_zoomwindow_fov = {CVAR_SAVE, "scr_zoomwindow_fov", "20"};
194
195 void gl_backend_init(void)
196 {
197         int i;
198
199         for (i = 0;i < POLYGONELEMENTS_MAXPOINTS - 2;i++)
200         {
201                 polygonelements[i * 3 + 0] = 0;
202                 polygonelements[i * 3 + 1] = i + 1;
203                 polygonelements[i * 3 + 2] = i + 2;
204         }
205
206         Cvar_RegisterVariable(&r_render);
207         Cvar_RegisterVariable(&gl_dither);
208         Cvar_RegisterVariable(&gl_lockarrays);
209         Cvar_RegisterVariable(&gl_delayfinish);
210         Cvar_RegisterVariable(&gl_paranoid);
211         Cvar_RegisterVariable(&gl_printcheckerror);
212 #ifdef NORENDER
213         Cvar_SetValue("r_render", 0);
214 #endif
215
216         Cvar_RegisterVariable(&gl_mesh_drawrangeelements);
217         Cvar_RegisterVariable(&gl_mesh_testarrayelement);
218         Cvar_RegisterVariable(&gl_mesh_testmanualfeeding);
219
220         Cvar_RegisterVariable(&scr_zoomwindow);
221         Cvar_RegisterVariable(&scr_zoomwindow_viewsizex);
222         Cvar_RegisterVariable(&scr_zoomwindow_viewsizey);
223         Cvar_RegisterVariable(&scr_zoomwindow_fov);
224
225         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
226 }
227
228 void GL_SetupView_Orientation_Identity (void)
229 {
230         Matrix4x4_CreateIdentity(&backend_viewmatrix);
231         memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
232 }
233
234 void GL_SetupView_Orientation_FromEntity(matrix4x4_t *matrix)
235 {
236         matrix4x4_t tempmatrix, basematrix;
237         Matrix4x4_Invert_Simple(&tempmatrix, matrix);
238         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
239         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
240         Matrix4x4_Concat(&backend_viewmatrix, &basematrix, &tempmatrix);
241         //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[2], 1, 0, 0);
242         //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[0], 0, 1, 0);
243         //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[1], 0, 0, 1);
244         //Matrix4x4_ConcatTranslate(&backend_viewmatrix, -origin[0], -origin[1], -origin[2]);
245         memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
246 }
247
248 void GL_SetupView_Mode_Perspective (double fovx, double fovy, double zNear, double zFar)
249 {
250         double xmax, ymax;
251
252         if (!r_render.integer)
253                 return;
254
255         // set up viewpoint
256         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
257         qglLoadIdentity();CHECKGLERROR
258         // pyramid slopes
259         xmax = zNear * tan(fovx * M_PI / 360.0);
260         ymax = zNear * tan(fovy * M_PI / 360.0);
261         // set view pyramid
262         qglFrustum(-xmax, xmax, -ymax, ymax, zNear, zFar);CHECKGLERROR
263         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
264         GL_SetupView_Orientation_Identity();
265 }
266
267 void GL_SetupView_Mode_PerspectiveInfiniteFarClip (double fovx, double fovy, double zNear)
268 {
269         float nudge, m[16];
270
271         if (!r_render.integer)
272                 return;
273
274         // set up viewpoint
275         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
276         qglLoadIdentity();CHECKGLERROR
277         // set view pyramid
278         nudge = 1.0 - 1.0 / (1<<23);
279         m[ 0] = 1.0 / tan(fovx * M_PI / 360.0);
280         m[ 1] = 0;
281         m[ 2] = 0;
282         m[ 3] = 0;
283         m[ 4] = 0;
284         m[ 5] = 1.0 / tan(fovy * M_PI / 360.0);
285         m[ 6] = 0;
286         m[ 7] = 0;
287         m[ 8] = 0;
288         m[ 9] = 0;
289         m[10] = -nudge;
290         m[11] = -1;
291         m[12] = 0;
292         m[13] = 0;
293         m[14] = -2 * zNear * nudge;
294         m[15] = 0;
295         qglLoadMatrixf(m);
296         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
297         GL_SetupView_Orientation_Identity();
298         backend_projectmatrix.m[0][0] = m[0];
299         backend_projectmatrix.m[1][0] = m[1];
300         backend_projectmatrix.m[2][0] = m[2];
301         backend_projectmatrix.m[3][0] = m[3];
302         backend_projectmatrix.m[0][1] = m[4];
303         backend_projectmatrix.m[1][1] = m[5];
304         backend_projectmatrix.m[2][1] = m[6];
305         backend_projectmatrix.m[3][1] = m[7];
306         backend_projectmatrix.m[0][2] = m[8];
307         backend_projectmatrix.m[1][2] = m[9];
308         backend_projectmatrix.m[2][2] = m[10];
309         backend_projectmatrix.m[3][2] = m[11];
310         backend_projectmatrix.m[0][3] = m[12];
311         backend_projectmatrix.m[1][3] = m[13];
312         backend_projectmatrix.m[2][3] = m[14];
313         backend_projectmatrix.m[3][3] = m[15];
314 }
315
316 void GL_SetupView_Mode_Ortho (double x1, double y1, double x2, double y2, double zNear, double zFar)
317 {
318         if (!r_render.integer)
319                 return;
320
321         // set up viewpoint
322         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
323         qglLoadIdentity();CHECKGLERROR
324         qglOrtho(x1, x2, y2, y1, zNear, zFar);
325         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
326         GL_SetupView_Orientation_Identity();
327 }
328
329 typedef struct gltextureunit_s
330 {
331         int t1d, t2d, t3d, tcubemap;
332         int arrayenabled;
333         int arrayis3d;
334         const void *pointer_texcoord;
335         float rgbscale, alphascale;
336         int combinergb, combinealpha;
337         // FIXME: add more combine stuff
338         matrix4x4_t matrix;
339 }
340 gltextureunit_t;
341
342 static struct
343 {
344         int blendfunc1;
345         int blendfunc2;
346         int blend;
347         GLboolean depthmask;
348         int colormask; // stored as bottom 4 bits: r g b a (3 2 1 0 order)
349         int depthtest;
350         int scissortest;
351         int unit;
352         int clientunit;
353         gltextureunit_t units[MAX_TEXTUREUNITS];
354         float color4f[4];
355         int lockrange_first;
356         int lockrange_count;
357         const void *pointer_vertex;
358         const void *pointer_color;
359 }
360 gl_state;
361
362 void GL_SetupTextureState(void)
363 {
364         int i;
365         gltextureunit_t *unit;
366         gl_state.unit = -1;
367         gl_state.clientunit = -1;
368         for (i = 0;i < backendunits;i++)
369         {
370                 GL_ActiveTexture(i);
371                 GL_ClientActiveTexture(i);
372                 unit = gl_state.units + i;
373                 unit->t1d = 0;
374                 unit->t2d = 0;
375                 unit->t3d = 0;
376                 unit->tcubemap = 0;
377                 unit->pointer_texcoord = NULL;
378                 unit->rgbscale = 1;
379                 unit->alphascale = 1;
380                 unit->combinergb = GL_MODULATE;
381                 unit->combinealpha = GL_MODULATE;
382
383                 qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), NULL);CHECKGLERROR
384                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
385
386                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
387                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
388                 if (gl_texture3d)
389                 {
390                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
391                 }
392                 if (gl_texturecubemap)
393                 {
394                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
395                 }
396                 if (gl_combine.integer)
397                 {
398                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
399                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);CHECKGLERROR
400                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);CHECKGLERROR
401                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
402                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_TEXTURE);CHECKGLERROR // for GL_INTERPOLATE_ARB mode
403                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
404                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
405                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB_ARB, GL_SRC_ALPHA);CHECKGLERROR
406                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);CHECKGLERROR
407                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE);CHECKGLERROR
408                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
409                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA_ARB, GL_CONSTANT_ARB);CHECKGLERROR
410                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
411                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
412                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
413                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
414                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
415                 }
416                 else
417                 {
418                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
419                 }
420         }
421 }
422
423 void GL_Backend_ResetState(void)
424 {
425         memset(&gl_state, 0, sizeof(gl_state));
426         gl_state.depthtest = true;
427         gl_state.blendfunc1 = GL_ONE;
428         gl_state.blendfunc2 = GL_ZERO;
429         gl_state.blend = false;
430         gl_state.depthmask = GL_TRUE;
431         gl_state.colormask = 15;
432         gl_state.color4f[0] = gl_state.color4f[1] = gl_state.color4f[2] = gl_state.color4f[3] = 1;
433         gl_state.lockrange_first = 0;
434         gl_state.lockrange_count = 0;
435         gl_state.pointer_vertex = NULL;
436         gl_state.pointer_color = NULL;
437
438         CHECKGLERROR
439
440         qglColorMask(1, 1, 1, 1);
441         qglEnable(GL_CULL_FACE);CHECKGLERROR
442         qglCullFace(GL_FRONT);CHECKGLERROR
443         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
444         qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
445         qglDisable(GL_BLEND);CHECKGLERROR
446         qglDepthMask(gl_state.depthmask);CHECKGLERROR
447
448         qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), NULL);CHECKGLERROR
449         qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
450
451         qglColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL);CHECKGLERROR
452         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
453
454         GL_Color(0, 0, 0, 0);
455         GL_Color(1, 1, 1, 1);
456
457         GL_SetupTextureState();
458 }
459
460 void GL_ActiveTexture(int num)
461 {
462         if (gl_state.unit != num)
463         {
464                 gl_state.unit = num;
465                 if (qglActiveTexture)
466                 {
467                         qglActiveTexture(GL_TEXTURE0_ARB + gl_state.unit);
468                         CHECKGLERROR
469                 }
470         }
471 }
472
473 void GL_ClientActiveTexture(int num)
474 {
475         if (gl_state.clientunit != num)
476         {
477                 gl_state.clientunit = num;
478                 if (qglActiveTexture)
479                 {
480                         qglClientActiveTexture(GL_TEXTURE0_ARB + gl_state.clientunit);
481                         CHECKGLERROR
482                 }
483         }
484 }
485
486 void GL_BlendFunc(int blendfunc1, int blendfunc2)
487 {
488         if (gl_state.blendfunc1 != blendfunc1 || gl_state.blendfunc2 != blendfunc2)
489         {
490                 if (r_showtrispass)
491                         return;
492                 qglBlendFunc(gl_state.blendfunc1 = blendfunc1, gl_state.blendfunc2 = blendfunc2);CHECKGLERROR
493                 if (gl_state.blendfunc2 == GL_ZERO)
494                 {
495                         if (gl_state.blendfunc1 == GL_ONE)
496                         {
497                                 if (gl_state.blend)
498                                 {
499                                         gl_state.blend = 0;
500                                         qglDisable(GL_BLEND);CHECKGLERROR
501                                 }
502                         }
503                         else
504                         {
505                                 if (!gl_state.blend)
506                                 {
507                                         gl_state.blend = 1;
508                                         qglEnable(GL_BLEND);CHECKGLERROR
509                                 }
510                         }
511                 }
512                 else
513                 {
514                         if (!gl_state.blend)
515                         {
516                                 gl_state.blend = 1;
517                                 qglEnable(GL_BLEND);CHECKGLERROR
518                         }
519                 }
520         }
521 }
522
523 void GL_DepthMask(int state)
524 {
525         if (gl_state.depthmask != state)
526         {
527                 if (r_showtrispass)
528                         return;
529                 qglDepthMask(gl_state.depthmask = state);CHECKGLERROR
530         }
531 }
532
533 void GL_DepthTest(int state)
534 {
535         if (gl_state.depthtest != state)
536         {
537                 if (r_showtrispass)
538                         return;
539                 gl_state.depthtest = state;
540                 if (gl_state.depthtest)
541                 {
542                         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
543                 }
544                 else
545                 {
546                         qglDisable(GL_DEPTH_TEST);CHECKGLERROR
547                 }
548         }
549 }
550
551 void GL_ColorMask(int r, int g, int b, int a)
552 {
553         int state = r*8 + g*4 + b*2 + a*1;
554         if (gl_state.colormask != state)
555         {
556                 if (r_showtrispass)
557                         return;
558                 gl_state.colormask = state;
559                 qglColorMask((GLboolean)r, (GLboolean)g, (GLboolean)b, (GLboolean)a);CHECKGLERROR
560         }
561 }
562
563 void GL_Color(float cr, float cg, float cb, float ca)
564 {
565         if (gl_state.pointer_color || gl_state.color4f[0] != cr || gl_state.color4f[1] != cg || gl_state.color4f[2] != cb || gl_state.color4f[3] != ca)
566         {
567                 if (r_showtrispass)
568                         return;
569                 gl_state.color4f[0] = cr;
570                 gl_state.color4f[1] = cg;
571                 gl_state.color4f[2] = cb;
572                 gl_state.color4f[3] = ca;
573                 CHECKGLERROR
574                 qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);
575                 CHECKGLERROR
576         }
577 }
578
579 void GL_ShowTrisColor(float cr, float cg, float cb, float ca)
580 {
581         if (!r_showtrispass)
582                 return;
583         r_showtrispass = false;
584         GL_Color(cr * r_showtris.value, cg * r_showtris.value, cb * r_showtris.value, ca);
585         r_showtrispass = true;
586 }
587
588
589 void GL_LockArrays(int first, int count)
590 {
591         if (gl_state.lockrange_count != count || gl_state.lockrange_first != first)
592         {
593                 if (gl_state.lockrange_count)
594                 {
595                         gl_state.lockrange_count = 0;
596                         CHECKGLERROR
597                         qglUnlockArraysEXT();
598                         CHECKGLERROR
599                 }
600                 if (count && gl_supportslockarrays && gl_lockarrays.integer && r_render.integer)
601                 {
602                         gl_state.lockrange_first = first;
603                         gl_state.lockrange_count = count;
604                         CHECKGLERROR
605                         qglLockArraysEXT(first, count);
606                         CHECKGLERROR
607                 }
608         }
609 }
610
611 void GL_Scissor (int x, int y, int width, int height)
612 {
613         CHECKGLERROR
614         qglScissor(x, vid.realheight - (y + height),width,height);
615         CHECKGLERROR
616 }
617
618 void GL_ScissorTest(int state)
619 {
620         if(gl_state.scissortest == state)
621                 return;
622
623         CHECKGLERROR
624         if((gl_state.scissortest = state))
625                 qglEnable(GL_SCISSOR_TEST);
626         else
627                 qglDisable(GL_SCISSOR_TEST);
628         CHECKGLERROR
629 }
630
631 void GL_Clear(int mask)
632 {
633         if (r_showtrispass)
634                 return;
635         qglClear(mask);CHECKGLERROR
636 }
637
638 void GL_TransformToScreen(const vec4_t in, vec4_t out)
639 {
640         vec4_t temp;
641         float iw;
642         Matrix4x4_Transform4 (&backend_viewmatrix, in, temp);
643         Matrix4x4_Transform4 (&backend_projectmatrix, temp, out);
644         iw = 1.0f / out[3];
645         out[0] = r_view_x + (out[0] * iw + 1.0f) * r_view_width * 0.5f;
646         out[1] = r_view_y + (out[1] * iw + 1.0f) * r_view_height * 0.5f;
647         out[2] = out[2] * iw;
648 }
649
650 // called at beginning of frame
651 void R_Mesh_Start(void)
652 {
653         BACKENDACTIVECHECK
654         CHECKGLERROR
655         GL_Backend_ResetState();
656 }
657
658 int gl_backend_rebindtextures;
659
660 void GL_Backend_RenumberElements(int *out, int count, const int *in, int offset)
661 {
662         int i;
663         if (offset)
664         {
665                 for (i = 0;i < count;i++)
666                         *out++ = *in++ + offset;
667         }
668         else
669                 memcpy(out, in, sizeof(*out) * count);
670 }
671
672 // renders triangles using vertices from the active arrays
673 int paranoidblah = 0;
674 void R_Mesh_Draw(int numverts, int numtriangles, const int *elements)
675 {
676         int numelements = numtriangles * 3;
677         if (numverts == 0 || numtriangles == 0)
678         {
679                 Con_Printf("R_Mesh_Draw(%d, %d, %08p);\n", numverts, numtriangles, elements);
680                 return;
681         }
682         CHECKGLERROR
683         if (r_showtrispass)
684         {
685                 R_Mesh_Draw_ShowTris(numverts, numtriangles, elements);
686                 return;
687         }
688         c_meshs++;
689         c_meshelements += numelements;
690         if (gl_paranoid.integer)
691         {
692                 int i, j, size;
693                 const int *p;
694                 if (!qglIsEnabled(GL_VERTEX_ARRAY))
695                         Con_Print("R_Mesh_Draw: vertex array not enabled\n");
696                 for (j = 0, size = numverts * (int)sizeof(float[3]), p = gl_state.pointer_vertex;j < size;j += sizeof(int), p++)
697                         paranoidblah += *p;
698                 if (gl_state.pointer_color)
699                 {
700                         if (!qglIsEnabled(GL_COLOR_ARRAY))
701                                 Con_Print("R_Mesh_Draw: color array set but not enabled\n");
702                         for (j = 0, size = numverts * (int)sizeof(float[4]), p = gl_state.pointer_color;j < size;j += sizeof(int), p++)
703                                 paranoidblah += *p;
704                 }
705                 for (i = 0;i < backendunits;i++)
706                 {
707                         if (gl_state.units[i].t1d || gl_state.units[i].t2d || gl_state.units[i].t3d || gl_state.units[i].tcubemap || gl_state.units[i].arrayenabled)
708                         {
709                                 if (gl_state.units[i].arrayenabled && !(gl_state.units[i].t1d || gl_state.units[i].t2d || gl_state.units[i].t3d || gl_state.units[i].tcubemap))
710                                         Con_Print("R_Mesh_Draw: array enabled but no texture bound\n");
711                                 GL_ActiveTexture(i);
712                                 if (!qglIsEnabled(GL_TEXTURE_COORD_ARRAY))
713                                         Con_Print("R_Mesh_Draw: texcoord array set but not enabled\n");
714                                 for (j = 0, size = numverts * ((gl_state.units[i].t3d || gl_state.units[i].tcubemap) ? (int)sizeof(float[3]) : (int)sizeof(float[2])), p = gl_state.units[i].pointer_texcoord;j < size;j += sizeof(int), p++)
715                                         paranoidblah += *p;
716                         }
717                 }
718                 for (i = 0;i < numtriangles * 3;i++)
719                 {
720                         if (elements[i] < 0 || elements[i] >= numverts)
721                         {
722                                 Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range 0 - %i) in elements list\n", elements[i], numverts);
723                                 return;
724                         }
725                 }
726                 CHECKGLERROR
727         }
728         if (r_render.integer)
729         {
730                 CHECKGLERROR
731                 if (gl_mesh_testmanualfeeding.integer)
732                 {
733                         int i, j;
734                         const GLfloat *p;
735                         qglBegin(GL_TRIANGLES);
736                         for (i = 0;i < numtriangles * 3;i++)
737                         {
738                                 for (j = 0;j < backendunits;j++)
739                                 {
740                                         if (gl_state.units[j].pointer_texcoord)
741                                         {
742                                                 if (backendunits > 1)
743                                                 {
744                                                         if (gl_state.units[j].t3d || gl_state.units[j].tcubemap)
745                                                         {
746                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
747                                                                 qglMultiTexCoord3f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2]);
748                                                         }
749                                                         else
750                                                         {
751                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
752                                                                 qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, p[0], p[1]);
753                                                         }
754                                                 }
755                                                 else
756                                                 {
757                                                         if (gl_state.units[j].t3d || gl_state.units[j].tcubemap)
758                                                         {
759                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
760                                                                 qglTexCoord3f(p[0], p[1], p[2]);
761                                                         }
762                                                         else
763                                                         {
764                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
765                                                                 qglTexCoord2f(p[0], p[1]);
766                                                         }
767                                                 }
768                                         }
769                                 }
770                                 if (gl_state.pointer_color)
771                                 {
772                                         p = ((const GLfloat *)(gl_state.pointer_color)) + elements[i] * 4;
773                                         qglColor4f(p[0], p[1], p[2], p[3]);
774                                 }
775                                 p = ((const GLfloat *)(gl_state.pointer_vertex)) + elements[i] * 3;
776                                 qglVertex3f(p[0], p[1], p[2]);
777                         }
778                         qglEnd();
779                         CHECKGLERROR
780                 }
781                 else if (gl_mesh_testarrayelement.integer)
782                 {
783                         int i;
784                         qglBegin(GL_TRIANGLES);
785                         for (i = 0;i < numtriangles * 3;i++)
786                         {
787                                 qglArrayElement(elements[i]);
788                         }
789                         qglEnd();
790                         CHECKGLERROR
791                 }
792                 else if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
793                 {
794                         qglDrawRangeElements(GL_TRIANGLES, 0, numverts, numelements, GL_UNSIGNED_INT, elements);CHECKGLERROR
795                 }
796                 else
797                 {
798                         qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, elements);CHECKGLERROR
799                 }
800                 CHECKGLERROR
801         }
802 }
803
804 // restores backend state, used when done with 3D rendering
805 void R_Mesh_Finish(void)
806 {
807         int i;
808         BACKENDACTIVECHECK
809         CHECKGLERROR
810         GL_LockArrays(0, 0);
811         CHECKGLERROR
812
813         for (i = backendunits - 1;i >= 0;i--)
814         {
815                 if (qglActiveTexture)
816                         qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
817                 if (qglClientActiveTexture)
818                         qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
819                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
820                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
821                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
822                 if (gl_texture3d)
823                 {
824                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
825                 }
826                 if (gl_texturecubemap)
827                 {
828                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
829                 }
830                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
831                 if (gl_combine.integer)
832                 {
833                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
834                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
835                 }
836         }
837         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
838         qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
839
840         qglDisable(GL_BLEND);CHECKGLERROR
841         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
842         qglDepthMask(GL_TRUE);CHECKGLERROR
843         qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
844 }
845
846 void R_Mesh_Matrix(const matrix4x4_t *matrix)
847 {
848         if (memcmp(matrix, &backend_modelmatrix, sizeof(matrix4x4_t)))
849         {
850                 backend_modelmatrix = *matrix;
851                 Matrix4x4_Concat(&backend_modelviewmatrix, &backend_viewmatrix, matrix);
852                 Matrix4x4_Transpose(&backend_glmodelviewmatrix, &backend_modelviewmatrix);
853                 qglLoadMatrixf(&backend_glmodelviewmatrix.m[0][0]);
854         }
855 }
856
857 void R_Mesh_TextureMatrix(int unitnumber, const matrix4x4_t *matrix)
858 {
859         if (memcmp(&gl_state.units[unitnumber].matrix, matrix, sizeof(matrix4x4_t)))
860         {
861                 matrix4x4_t tempmatrix;
862                 gl_state.units[unitnumber].matrix = *matrix;
863                 Matrix4x4_Transpose(&tempmatrix, &gl_state.units[unitnumber].matrix);
864                 qglMatrixMode(GL_TEXTURE);
865                 GL_ActiveTexture(unitnumber);
866                 qglLoadMatrixf(&tempmatrix.m[0][0]);
867                 qglMatrixMode(GL_MODELVIEW);
868         }
869 }
870
871 void R_Mesh_State(const rmeshstate_t *m)
872 {
873         int i, combinergb, combinealpha, scale, arrayis3d;
874         gltextureunit_t *unit;
875
876         BACKENDACTIVECHECK
877
878         if (gl_state.pointer_vertex != m->pointer_vertex)
879         {
880                 gl_state.pointer_vertex = m->pointer_vertex;
881                 CHECKGLERROR
882                 qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), gl_state.pointer_vertex);
883                 CHECKGLERROR
884         }
885
886         if (r_showtrispass)
887                 return;
888
889         if (gl_state.pointer_color != m->pointer_color)
890         {
891                 CHECKGLERROR
892                 if (!gl_state.pointer_color)
893                 {
894                         qglEnableClientState(GL_COLOR_ARRAY);
895                         CHECKGLERROR
896                 }
897                 else if (!m->pointer_color)
898                 {
899                         qglDisableClientState(GL_COLOR_ARRAY);
900                         CHECKGLERROR
901                         // when color array is on the glColor gets trashed, set it again
902                         qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);
903                         CHECKGLERROR
904                 }
905                 gl_state.pointer_color = m->pointer_color;
906                 qglColorPointer(4, GL_FLOAT, sizeof(float[4]), gl_state.pointer_color);
907                 CHECKGLERROR
908         }
909
910         if (gl_backend_rebindtextures)
911         {
912                 gl_backend_rebindtextures = false;
913                 GL_SetupTextureState();
914         }
915
916         for (i = 0, unit = gl_state.units;i < backendunits;i++, unit++)
917         {
918                 if (unit->t1d != m->tex1d[i])
919                 {
920                         GL_ActiveTexture(i);
921                         if (m->tex1d[i])
922                         {
923                                 if (unit->t1d == 0)
924                                         qglEnable(GL_TEXTURE_1D);CHECKGLERROR
925                         }
926                         else
927                         {
928                                 if (unit->t1d)
929                                         qglDisable(GL_TEXTURE_1D);CHECKGLERROR
930                         }
931                         qglBindTexture(GL_TEXTURE_1D, (unit->t1d = m->tex1d[i]));CHECKGLERROR
932                 }
933                 if (unit->t2d != m->tex[i])
934                 {
935                         GL_ActiveTexture(i);
936                         if (m->tex[i])
937                         {
938                                 if (unit->t2d == 0)
939                                         qglEnable(GL_TEXTURE_2D);CHECKGLERROR
940                         }
941                         else
942                         {
943                                 if (unit->t2d)
944                                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
945                         }
946                         qglBindTexture(GL_TEXTURE_2D, (unit->t2d = m->tex[i]));CHECKGLERROR
947                 }
948                 if (unit->t3d != m->tex3d[i])
949                 {
950                         GL_ActiveTexture(i);
951                         if (m->tex3d[i])
952                         {
953                                 if (unit->t3d == 0)
954                                         qglEnable(GL_TEXTURE_3D);CHECKGLERROR
955                         }
956                         else
957                         {
958                                 if (unit->t3d)
959                                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
960                         }
961                         qglBindTexture(GL_TEXTURE_3D, (unit->t3d = m->tex3d[i]));CHECKGLERROR
962                 }
963                 if (unit->tcubemap != m->texcubemap[i])
964                 {
965                         GL_ActiveTexture(i);
966                         if (m->texcubemap[i])
967                         {
968                                 if (unit->tcubemap == 0)
969                                         qglEnable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
970                         }
971                         else
972                         {
973                                 if (unit->tcubemap)
974                                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
975                         }
976                         qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, (unit->tcubemap = m->texcubemap[i]));CHECKGLERROR
977                 }
978                 combinergb = m->texcombinergb[i];
979                 if (!combinergb)
980                         combinergb = GL_MODULATE;
981                 if (unit->combinergb != combinergb)
982                 {
983                         GL_ActiveTexture(i);
984                         unit->combinergb = combinergb;
985                         if (gl_combine.integer) 
986                         {
987                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
988                         }
989                         else
990                         {
991                                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
992                         }
993                 }
994                 combinealpha = m->texcombinealpha[i];
995                 if (!combinealpha)
996                         combinealpha = GL_MODULATE;
997                 if (unit->combinealpha != combinealpha)
998                 {
999                         GL_ActiveTexture(i);
1000                         unit->combinealpha = combinealpha;
1001                         if (gl_combine.integer)
1002                         {
1003                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
1004                         }
1005                 }
1006                 scale = max(m->texrgbscale[i], 1);
1007                 if (unit->rgbscale != scale)
1008                 {
1009                         GL_ActiveTexture(i);
1010                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (unit->rgbscale = scale));CHECKGLERROR
1011                 }
1012                 scale = max(m->texalphascale[i], 1);
1013                 if (unit->alphascale != scale)
1014                 {
1015                         GL_ActiveTexture(i);
1016                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (unit->alphascale = scale));CHECKGLERROR
1017                 }
1018                 arrayis3d = unit->t3d || unit->tcubemap;
1019                 if (unit->pointer_texcoord != m->pointer_texcoord[i] || unit->arrayis3d != arrayis3d)
1020                 {
1021                         GL_ClientActiveTexture(i);
1022                         if (m->pointer_texcoord[i])
1023                         {
1024                                 if (!unit->arrayenabled)
1025                                 {
1026                                         unit->arrayenabled = true;
1027                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1028                                 }
1029                         }
1030                         else
1031                         {
1032                                 if (unit->arrayenabled)
1033                                 {
1034                                         unit->arrayenabled = false;
1035                                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1036                                 }
1037                         }
1038                         unit->pointer_texcoord = m->pointer_texcoord[i];
1039                         unit->arrayis3d = arrayis3d;
1040                         if (unit->arrayis3d)
1041                                 qglTexCoordPointer(3, GL_FLOAT, sizeof(float[3]), unit->pointer_texcoord);
1042                         else
1043                                 qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), unit->pointer_texcoord);
1044                         CHECKGLERROR
1045                 }
1046         }
1047 }
1048
1049 void R_Mesh_Draw_ShowTris(int numverts, int numtriangles, const int *elements)
1050 {
1051         qglBegin(GL_LINES);
1052         for (;numtriangles;numtriangles--, elements += 3)
1053         {
1054                 qglArrayElement(elements[0]);qglArrayElement(elements[1]);
1055                 qglArrayElement(elements[1]);qglArrayElement(elements[2]);
1056                 qglArrayElement(elements[2]);qglArrayElement(elements[0]);
1057         }
1058         qglEnd();
1059         CHECKGLERROR
1060 }
1061
1062 /*
1063 ==============================================================================
1064
1065                                                 SCREEN SHOTS
1066
1067 ==============================================================================
1068 */
1069
1070 qboolean SCR_ScreenShot(char *filename, int x, int y, int width, int height, qboolean jpeg)
1071 {
1072         qboolean ret;
1073         qbyte *buffer;
1074
1075         if (!r_render.integer)
1076                 return false;
1077
1078         buffer = Mem_Alloc(tempmempool, width*height*3);
1079         qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
1080         CHECKGLERROR
1081
1082         if (jpeg)
1083                 ret = JPEG_SaveImage_preflipped (filename, width, height, buffer);
1084         else
1085                 ret = Image_WriteTGARGB_preflipped (filename, width, height, buffer);
1086
1087         Mem_Free(buffer);
1088         return ret;
1089 }
1090
1091 //=============================================================================
1092
1093 void R_ClearScreen(void)
1094 {
1095         if (r_render.integer)
1096         {
1097                 // clear to black
1098                 qglClearColor(0,0,0,0);CHECKGLERROR
1099                 qglClearDepth(1);CHECKGLERROR
1100                 if (gl_stencil)
1101                 {
1102                         // LordHavoc: we use a stencil centered around 128 instead of 0,
1103                         // to avoid clamping interfering with strange shadow volume
1104                         // drawing orders
1105                         qglClearStencil(128);CHECKGLERROR
1106                 }
1107                 // clear the screen
1108                 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (gl_stencil ? GL_STENCIL_BUFFER_BIT : 0));
1109                 // set dithering mode
1110                 if (gl_dither.integer)
1111                 {
1112                         qglEnable(GL_DITHER);CHECKGLERROR
1113                 }
1114                 else
1115                 {
1116                         qglDisable(GL_DITHER);CHECKGLERROR
1117                 }
1118         }
1119 }
1120
1121 /*
1122 ====================
1123 CalcFov
1124 ====================
1125 */
1126 float CalcFov (float fov_x, float width, float height)
1127 {
1128         // calculate vision size and alter by aspect, then convert back to angle
1129         return atan (height / (width / tan(fov_x/360*M_PI))) * 360 / M_PI;
1130 }
1131
1132 /*
1133 ==================
1134 SCR_UpdateScreen
1135
1136 This is called every frame, and can also be called explicitly to flush
1137 text to the screen.
1138 ==================
1139 */
1140 void SCR_UpdateScreen (void)
1141 {
1142         if (gl_delayfinish.integer)
1143         {
1144                 R_Mesh_Finish();
1145                 R_TimeReport("meshfinish");
1146                 VID_Finish();
1147                 R_TimeReport("finish");
1148         }
1149
1150         R_Mesh_Start();
1151
1152         if (r_textureunits.integer > gl_textureunits)
1153                 Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
1154         if (r_textureunits.integer < 1)
1155                 Cvar_SetValueQuick(&r_textureunits, 1);
1156
1157         if (gl_combine.integer && (!gl_combine_extension || r_textureunits.integer < 2))
1158                 Cvar_SetValueQuick(&gl_combine, 0);
1159
1160 showtris:
1161         R_TimeReport("setup");
1162
1163         R_ClearScreen();
1164
1165         R_TimeReport("clear");
1166
1167         if (scr_conlines < vid.conheight && cls.signon == SIGNONS)
1168         {
1169                 float size;
1170                 int contents;
1171
1172                 // bound viewsize
1173                 if (scr_viewsize.value < 30)
1174                         Cvar_Set ("viewsize","30");
1175                 if (scr_viewsize.value > 120)
1176                         Cvar_Set ("viewsize","120");
1177                 
1178                 // bound field of view
1179                 if (scr_fov.value < 1)
1180                         Cvar_Set ("fov","1");
1181                 if (scr_fov.value > 170)
1182                         Cvar_Set ("fov","170");
1183         
1184                 // intermission is always full screen
1185                 if (cl.intermission)
1186                 {
1187                         size = 1;
1188                         sb_lines = 0;
1189                 }
1190                 else
1191                 {
1192                         if (scr_viewsize.value >= 120)
1193                                 sb_lines = 0;           // no status bar at all
1194                         else if (scr_viewsize.value >= 110)
1195                                 sb_lines = 24;          // no inventory
1196                         else
1197                                 sb_lines = 24+16+8;
1198                         size = scr_viewsize.value * (1.0 / 100.0);
1199                         size = min(size, 1);
1200                 }
1201         
1202                 r_refdef.width = vid.realwidth * size;
1203                 r_refdef.height = vid.realheight * size;
1204                 r_refdef.x = (vid.realwidth - r_refdef.width)/2;
1205                 r_refdef.y = (vid.realheight - r_refdef.height)/2;
1206         
1207                 // LordHavoc: viewzoom (zoom in for sniper rifles, etc)
1208                 r_refdef.fov_x = scr_fov.value * cl.viewzoom;
1209                 r_refdef.fov_y = CalcFov (r_refdef.fov_x, r_refdef.width, r_refdef.height);
1210         
1211                 if (cl.worldmodel)
1212                 {
1213                         Mod_CheckLoaded(cl.worldmodel);
1214                         contents = CL_PointSuperContents(r_vieworigin);
1215                         if (contents & SUPERCONTENTS_LIQUIDSMASK)
1216                         {
1217                                 r_refdef.fov_x *= (sin(cl.time * 4.7) * 0.015 + 0.985);
1218                                 r_refdef.fov_y *= (sin(cl.time * 3.0) * 0.015 + 0.985);
1219                         }
1220                 }
1221
1222                 R_RenderView();
1223
1224                 if (scr_zoomwindow.integer)
1225                 {
1226                         float sizex = bound(10, scr_zoomwindow_viewsizex.value, 100) / 100.0;
1227                         float sizey = bound(10, scr_zoomwindow_viewsizey.value, 100) / 100.0;
1228                         r_refdef.width = vid.realwidth * sizex;
1229                         r_refdef.height = vid.realheight * sizey;
1230                         r_refdef.x = (vid.realwidth - r_refdef.width)/2;
1231                         r_refdef.y = 0;
1232                         r_refdef.fov_x = scr_zoomwindow_fov.value;
1233                         r_refdef.fov_y = CalcFov(r_refdef.fov_x, r_refdef.width, r_refdef.height);
1234
1235                         R_RenderView();
1236                 }
1237         }
1238
1239         // draw 2D stuff
1240         R_DrawQueue();
1241
1242         if (r_showtrispass)
1243                 r_showtrispass = false;
1244         else if (r_showtris.value > 0)
1245         {
1246                 rmeshstate_t m;
1247                 GL_BlendFunc(GL_ONE, GL_ONE);
1248                 GL_DepthTest(GL_FALSE);
1249                 GL_DepthMask(GL_FALSE);
1250                 memset(&m, 0, sizeof(m));
1251                 R_Mesh_State(&m);
1252                 r_showtrispass = true;
1253                 GL_ShowTrisColor(0.2,0.2,0.2,1);
1254                 goto showtris;
1255         }
1256
1257         if (gl_delayfinish.integer)
1258         {
1259                 // tell driver to commit it's partially full geometry queue to the rendering queue
1260                 // (this doesn't wait for the commands themselves to complete)
1261                 qglFlush();
1262         }
1263         else
1264         {
1265                 R_Mesh_Finish();
1266                 R_TimeReport("meshfinish");
1267                 VID_Finish();
1268                 R_TimeReport("finish");
1269         }
1270 }
1271
1272
1273 //===========================================================================
1274 // dynamic vertex array buffer subsystem
1275 //===========================================================================
1276
1277 float varray_vertex3f[65536*3];
1278 float varray_color4f[65536*4];
1279 float varray_texcoord2f[4][65536*2];
1280 float varray_texcoord3f[4][65536*3];
1281 float varray_normal3f[65536*3];
1282 int earray_element3i[65536];
1283
1284 //===========================================================================
1285 // vertex array caching subsystem
1286 //===========================================================================
1287
1288 typedef struct rcachearraylink_s
1289 {
1290         struct rcachearraylink_s *next, *prev;
1291         struct rcachearrayitem_s *data;
1292 }
1293 rcachearraylink_t;
1294
1295 typedef struct rcachearrayitem_s
1296 {
1297         // the original request structure
1298         rcachearrayrequest_t request;
1299         // active
1300         int active;
1301         // offset into r_mesh_rcachedata
1302         int offset;
1303         // for linking this into the sequential list
1304         rcachearraylink_t sequentiallink;
1305         // for linking this into the lookup list
1306         rcachearraylink_t hashlink;
1307 }
1308 rcachearrayitem_t;
1309
1310 #define RCACHEARRAY_HASHSIZE 65536
1311 #define RCACHEARRAY_ITEMS 4096
1312 #define RCACHEARRAY_DEFAULTSIZE (4 << 20)
1313
1314 // all active items are linked into this chain in sorted order
1315 static rcachearraylink_t r_mesh_rcachesequentialchain;
1316 // all inactive items are linked into this chain in unknown order
1317 static rcachearraylink_t r_mesh_rcachefreechain;
1318 // all active items are also linked into these chains (using their hashlink)
1319 static rcachearraylink_t r_mesh_rcachechain[RCACHEARRAY_HASHSIZE];
1320
1321 // all items are stored here, whether active or inactive
1322 static rcachearrayitem_t r_mesh_rcacheitems[RCACHEARRAY_ITEMS];
1323
1324 // size of data buffer
1325 static int r_mesh_rcachedata_size = RCACHEARRAY_DEFAULTSIZE;
1326 // data buffer
1327 static qbyte r_mesh_rcachedata[RCACHEARRAY_DEFAULTSIZE];
1328
1329 // current state
1330 static int r_mesh_rcachedata_offset;
1331 static rcachearraylink_t *r_mesh_rcachesequentialchain_current;
1332
1333 static void R_Mesh_CacheArray_Startup(void)
1334 {
1335         int i;
1336         rcachearraylink_t *l;
1337         // prepare all the linked lists
1338         l = &r_mesh_rcachesequentialchain;l->next = l->prev = l;l->data = NULL;
1339         l = &r_mesh_rcachefreechain;l->next = l->prev = l;l->data = NULL;
1340         memset(&r_mesh_rcachechain, 0, sizeof(r_mesh_rcachechain));
1341         for (i = 0;i < RCACHEARRAY_HASHSIZE;i++)
1342         {
1343                 l = &r_mesh_rcachechain[i];
1344                 l->next = l->prev = l;
1345                 l->data = NULL;
1346         }
1347         memset(&r_mesh_rcacheitems, 0, sizeof(r_mesh_rcacheitems));
1348         for (i = 0;i < RCACHEARRAY_ITEMS;i++)
1349         {
1350                 r_mesh_rcacheitems[i].hashlink.data = r_mesh_rcacheitems[i].sequentiallink.data = &r_mesh_rcacheitems[i];
1351                 l = &r_mesh_rcacheitems[i].sequentiallink;
1352                 l->next = &r_mesh_rcachefreechain;
1353                 l->prev = l->next->prev;
1354                 l->next->prev = l->prev->next = l;
1355         }
1356         // clear other state
1357         r_mesh_rcachedata_offset = 0;
1358         r_mesh_rcachesequentialchain_current = &r_mesh_rcachesequentialchain;
1359 }
1360
1361 static void R_Mesh_CacheArray_Shutdown(void)
1362 {
1363 }
1364
1365 /*
1366 static void R_Mesh_CacheArray_ValidateState(int num)
1367 {
1368         rcachearraylink_t *l, *lhead;
1369         lhead = &r_mesh_rcachesequentialchain;
1370         if (r_mesh_rcachesequentialchain_current == lhead)
1371                 return;
1372         for (l = lhead->next;l != lhead;l = l->next)
1373                 if (r_mesh_rcachesequentialchain_current == l)
1374                         return;
1375         Sys_Error("%i", num);
1376 }
1377 */
1378
1379 int R_Mesh_CacheArray(rcachearrayrequest_t *r)
1380 {
1381         rcachearraylink_t *l, *lhead, *lnext;
1382         rcachearrayitem_t *d;
1383         int hashindex, offset, offsetend;
1384
1385         //R_Mesh_CacheArray_ValidateState(3);
1386         // calculate a hashindex to choose a cache chain
1387         r->data = NULL;
1388         hashindex = CRC_Block((void *)r, sizeof(*r)) % RCACHEARRAY_HASHSIZE;
1389
1390         // is it already cached?
1391         for (lhead = &r_mesh_rcachechain[hashindex], l = lhead->next;l != lhead;l = l->next)
1392         {
1393                 if (!memcmp(&l->data->request, r, sizeof(l->data->request)))
1394                 {
1395                         // we have it cached already
1396                         r->data = r_mesh_rcachedata + l->data->offset;
1397                         return false;
1398                 }
1399         }
1400
1401         // we need to add a new cache item, this means finding a place for the new
1402         // data and making sure we have a free item available, lots of work...
1403
1404         // check if buffer needs to wrap
1405         if (r_mesh_rcachedata_offset + r->data_size > r_mesh_rcachedata_size)
1406         {
1407                 /*
1408                 if (r->data_size * 10 > r_mesh_rcachedata_size)
1409                 {
1410                         // realloc whole cache
1411                 }
1412                 */
1413                 // reset back to start
1414                 r_mesh_rcachedata_offset = 0;
1415                 r_mesh_rcachesequentialchain_current = &r_mesh_rcachesequentialchain;
1416         }
1417         offset = r_mesh_rcachedata_offset;
1418         r_mesh_rcachedata_offset += r->data_size;
1419         offsetend = r_mesh_rcachedata_offset;
1420         //R_Mesh_CacheArray_ValidateState(4);
1421
1422         /*
1423         {
1424                 int n;
1425                 for (lhead = &r_mesh_rcachesequentialchain, l = lhead->next, n = 0;l != lhead;l = l->next, n++);
1426                 Con_Printf("R_Mesh_CacheArray: new data range %i:%i, %i items are already linked\n", offset, offsetend, n);
1427         }
1428         */
1429
1430         // make room for the new data (remove old items)
1431         lhead = &r_mesh_rcachesequentialchain;
1432         l = r_mesh_rcachesequentialchain_current;
1433         if (l == lhead)
1434                 l = l->next;
1435         while (l != lhead && l->data->offset < offsetend && l->data->offset + l->data->request.data_size > offset)
1436         {
1437         //r_mesh_rcachesequentialchain_current = l;
1438         //R_Mesh_CacheArray_ValidateState(8);
1439                 lnext = l->next;
1440                 // if at the end of the chain, wrap around
1441                 if (lnext == lhead)
1442                         lnext = lnext->next;
1443         //r_mesh_rcachesequentialchain_current = lnext;
1444         //R_Mesh_CacheArray_ValidateState(10);
1445
1446                 // unlink from sequential chain
1447                 l->next->prev = l->prev;
1448                 l->prev->next = l->next;
1449         //R_Mesh_CacheArray_ValidateState(11);
1450                 // link into free chain
1451                 l->next = &r_mesh_rcachefreechain;
1452                 l->prev = l->next->prev;
1453                 l->next->prev = l->prev->next = l;
1454         //R_Mesh_CacheArray_ValidateState(12);
1455
1456                 l = &l->data->hashlink;
1457                 // unlink from hash chain
1458                 l->next->prev = l->prev;
1459                 l->prev->next = l->next;
1460
1461                 l = lnext;
1462         //r_mesh_rcachesequentialchain_current = l;
1463         //R_Mesh_CacheArray_ValidateState(9);
1464         }
1465         //r_mesh_rcachesequentialchain_current = l;
1466         //R_Mesh_CacheArray_ValidateState(5);
1467         // gobble an extra item if we have no free items available
1468         if (r_mesh_rcachefreechain.next == &r_mesh_rcachefreechain)
1469         {
1470                 lnext = l->next;
1471
1472                 // unlink from sequential chain
1473                 l->next->prev = l->prev;
1474                 l->prev->next = l->next;
1475                 // link into free chain
1476                 l->next = &r_mesh_rcachefreechain;
1477                 l->prev = l->next->prev;
1478                 l->next->prev = l->prev->next = l;
1479
1480                 l = &l->data->hashlink;
1481                 // unlink from hash chain
1482                 l->next->prev = l->prev;
1483                 l->prev->next = l->next;
1484
1485                 l = lnext;
1486         }
1487         r_mesh_rcachesequentialchain_current = l;
1488         //R_Mesh_CacheArray_ValidateState(6);
1489
1490         // now take an item from the free chain
1491         l = r_mesh_rcachefreechain.next;
1492         // set it up
1493         d = l->data;
1494         d->request = *r;
1495         d->offset = offset;
1496         // unlink
1497         l->next->prev = l->prev;
1498         l->prev->next = l->next;
1499         // relink to sequential
1500         l->next = r_mesh_rcachesequentialchain_current->prev;
1501         l->prev = l->next->prev;
1502         while (l->next->data && l->data && l->next->data->offset <= d->offset)
1503         {
1504                 //Con_Print(">\n");
1505                 l->next = l->next->next;
1506                 l->prev = l->prev->next;
1507         }
1508         while (l->prev->data && l->data && l->prev->data->offset >= d->offset)
1509         {
1510                 //Con_Print("<\n");
1511                 l->prev = l->prev->prev;
1512                 l->next = l->next->prev;
1513         }
1514         l->next->prev = l->prev->next = l;
1515         // also link into hash chain
1516         l = &l->data->hashlink;
1517         l->next = &r_mesh_rcachechain[hashindex];
1518         l->prev = l->next->prev;
1519         l->prev->next = l;
1520         l->next->prev = l->prev->next = l;
1521
1522
1523         //r_mesh_rcachesequentialchain_current = d->sequentiallink.next;
1524
1525         //R_Mesh_CacheArray_ValidateState(7);
1526         // and finally set the data pointer
1527         r->data = r_mesh_rcachedata + d->offset;
1528         // and tell the caller to fill the array
1529         return true;
1530 }
1531