made r_showtris transparent (quite faint actually), color coded different types of...
[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_DPrintf("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_DPrintf("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(r, g, b, a);CHECKGLERROR
560         }
561 }
562
563 void GL_VertexPointer(const float *p)
564 {
565         if (gl_state.pointer_vertex != p)
566         {
567                 gl_state.pointer_vertex = p;
568                 CHECKGLERROR
569                 qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), gl_state.pointer_vertex);
570                 CHECKGLERROR
571         }
572 }
573
574 void GL_ColorPointer(const float *p)
575 {
576         if (gl_state.pointer_color != p)
577         {
578                 if (r_showtrispass)
579                         return;
580                 CHECKGLERROR
581                 if (!gl_state.pointer_color)
582                 {
583                         qglEnableClientState(GL_COLOR_ARRAY);
584                         CHECKGLERROR
585                 }
586                 else if (!p)
587                 {
588                         qglDisableClientState(GL_COLOR_ARRAY);
589                         CHECKGLERROR
590                 }
591                 gl_state.pointer_color = p;
592                 qglColorPointer(4, GL_FLOAT, sizeof(float[4]), gl_state.pointer_color);
593                 CHECKGLERROR
594         }
595 }
596
597 void GL_Color(float cr, float cg, float cb, float ca)
598 {
599         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)
600         {
601                 if (r_showtrispass)
602                         return;
603                 GL_ColorPointer(NULL);
604                 gl_state.color4f[0] = cr;
605                 gl_state.color4f[1] = cg;
606                 gl_state.color4f[2] = cb;
607                 gl_state.color4f[3] = ca;
608                 CHECKGLERROR
609                 qglColor4f(cr, cg, cb, ca);
610                 CHECKGLERROR
611         }
612 }
613
614 void GL_ShowTrisColor(float cr, float cg, float cb, float ca)
615 {
616         if (!r_showtrispass)
617                 return;
618         r_showtrispass = false;
619         GL_Color(cr,cg,cb,ca);
620         r_showtrispass = true;
621 }
622
623
624 void GL_LockArrays(int first, int count)
625 {
626         if (gl_state.lockrange_count != count || gl_state.lockrange_first != first)
627         {
628                 if (gl_state.lockrange_count)
629                 {
630                         gl_state.lockrange_count = 0;
631                         CHECKGLERROR
632                         qglUnlockArraysEXT();
633                         CHECKGLERROR
634                 }
635                 if (count && gl_supportslockarrays && gl_lockarrays.integer)
636                 {
637                         gl_state.lockrange_first = first;
638                         gl_state.lockrange_count = count;
639                         CHECKGLERROR
640                         qglLockArraysEXT(first, count);
641                         CHECKGLERROR
642                 }
643         }
644 }
645
646 void GL_Scissor (int x, int y, int width, int height)
647 {
648         CHECKGLERROR
649         qglScissor(x, vid.realheight - (y + height),width,height);
650         CHECKGLERROR
651 }
652
653 void GL_ScissorTest(int state)
654 {
655         if(gl_state.scissortest == state)
656                 return;
657
658         CHECKGLERROR
659         if((gl_state.scissortest = state))
660                 qglEnable(GL_SCISSOR_TEST);
661         else
662                 qglDisable(GL_SCISSOR_TEST);
663         CHECKGLERROR
664 }
665
666 void GL_Clear(int mask)
667 {
668         if (r_showtrispass)
669                 return;
670         qglClear(mask);CHECKGLERROR
671 }
672
673 void GL_TransformToScreen(const vec4_t in, vec4_t out)
674 {
675         vec4_t temp;
676         float iw;
677         Matrix4x4_Transform4 (&backend_viewmatrix, in, temp);
678         Matrix4x4_Transform4 (&backend_projectmatrix, temp, out);
679         iw = 1.0f / out[3];
680         out[0] = r_view_x + (out[0] * iw + 1.0f) * r_view_width * 0.5f;
681         out[1] = r_view_y + (out[1] * iw + 1.0f) * r_view_height * 0.5f;
682         out[2] = out[2] * iw;
683 }
684
685 // called at beginning of frame
686 void R_Mesh_Start(void)
687 {
688         BACKENDACTIVECHECK
689         CHECKGLERROR
690         GL_Backend_ResetState();
691 }
692
693 int gl_backend_rebindtextures;
694
695 void GL_Backend_RenumberElements(int *out, int count, const int *in, int offset)
696 {
697         int i;
698         if (offset)
699         {
700                 for (i = 0;i < count;i++)
701                         *out++ = *in++ + offset;
702         }
703         else
704                 memcpy(out, in, sizeof(*out) * count);
705 }
706
707 // renders triangles using vertices from the active arrays
708 int paranoidblah = 0;
709 void R_Mesh_Draw(int numverts, int numtriangles, const int *elements)
710 {
711         int numelements = numtriangles * 3;
712         if (numverts == 0 || numtriangles == 0)
713         {
714                 Con_Printf("R_Mesh_Draw(%d, %d, %08p);\n", numverts, numtriangles, elements);
715                 return;
716         }
717         if (r_showtrispass)
718         {
719                 R_Mesh_Draw_ShowTris(numverts, numtriangles, elements);
720                 return;
721         }
722         c_meshs++;
723         c_meshelements += numelements;
724         CHECKGLERROR
725         if (r_render.integer)
726         {
727                 if (gl_paranoid.integer)
728                 {
729                         int i, j, size;
730                         const int *p;
731                         if (!qglIsEnabled(GL_VERTEX_ARRAY))
732                                 Con_Printf("R_Mesh_Draw: vertex array not enabled\n");
733                         for (j = 0, size = numverts * (int)sizeof(float[3]), p = gl_state.pointer_vertex;j < size;j += sizeof(int), p++)
734                                 paranoidblah += *p;
735                         if (gl_state.pointer_color)
736                         {
737                                 if (!qglIsEnabled(GL_COLOR_ARRAY))
738                                         Con_Printf("R_Mesh_Draw: color array set but not enabled\n");
739                                 for (j = 0, size = numverts * (int)sizeof(float[4]), p = gl_state.pointer_color;j < size;j += sizeof(int), p++)
740                                         paranoidblah += *p;
741                         }
742                         for (i = 0;i < backendunits;i++)
743                         {
744                                 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)
745                                 {
746                                         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))
747                                                 Con_Printf("R_Mesh_Draw: array enabled but no texture bound\n");
748                                         GL_ActiveTexture(i);
749                                         if (!qglIsEnabled(GL_TEXTURE_COORD_ARRAY))
750                                                 Con_Printf("R_Mesh_Draw: texcoord array set but not enabled\n");
751                                         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++)
752                                                 paranoidblah += *p;
753                                 }
754                         }
755                         for (i = 0;i < numtriangles * 3;i++)
756                         {
757                                 if (elements[i] < 0 || elements[i] >= numverts)
758                                 {
759                                         Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range 0 - %i) in elements list\n", elements[i], numverts);
760                                         return;
761                                 }
762                         }
763                 }
764                 CHECKGLERROR
765                 GL_LockArrays(0, numverts);
766                 CHECKGLERROR
767                 if (gl_mesh_testmanualfeeding.integer)
768                 {
769                         int i, j;
770                         const GLfloat *p;
771                         qglBegin(GL_TRIANGLES);
772                         for (i = 0;i < numtriangles * 3;i++)
773                         {
774                                 for (j = 0;j < backendunits;j++)
775                                 {
776                                         if (gl_state.units[j].pointer_texcoord)
777                                         {
778                                                 if (backendunits > 1)
779                                                 {
780                                                         if (gl_state.units[j].t3d || gl_state.units[j].tcubemap)
781                                                         {
782                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
783                                                                 qglMultiTexCoord3f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2]);
784                                                         }
785                                                         else
786                                                         {
787                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
788                                                                 qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, p[0], p[1]);
789                                                         }
790                                                 }
791                                                 else
792                                                 {
793                                                         if (gl_state.units[j].t3d || gl_state.units[j].tcubemap)
794                                                         {
795                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
796                                                                 qglTexCoord3f(p[0], p[1], p[2]);
797                                                         }
798                                                         else
799                                                         {
800                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
801                                                                 qglTexCoord2f(p[0], p[1]);
802                                                         }
803                                                 }
804                                         }
805                                 }
806                                 if (gl_state.pointer_color)
807                                 {
808                                         p = ((const GLfloat *)(gl_state.pointer_color)) + elements[i] * 4;
809                                         qglColor4f(p[0], p[1], p[2], p[3]);
810                                 }
811                                 p = ((const GLfloat *)(gl_state.pointer_vertex)) + elements[i] * 3;
812                                 qglVertex3f(p[0], p[1], p[2]);
813                         }
814                         qglEnd();
815                         CHECKGLERROR
816                 }
817                 else if (gl_mesh_testarrayelement.integer)
818                 {
819                         int i;
820                         qglBegin(GL_TRIANGLES);
821                         for (i = 0;i < numtriangles * 3;i++)
822                         {
823                                 qglArrayElement(elements[i]);
824                         }
825                         qglEnd();
826                         CHECKGLERROR
827                 }
828                 else if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
829                 {
830                         qglDrawRangeElements(GL_TRIANGLES, 0, numverts, numelements, GL_UNSIGNED_INT, elements);CHECKGLERROR
831                 }
832                 else
833                 {
834                         qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, elements);CHECKGLERROR
835                 }
836                 CHECKGLERROR
837                 GL_LockArrays(0, 0);
838                 CHECKGLERROR
839         }
840 }
841
842 // restores backend state, used when done with 3D rendering
843 void R_Mesh_Finish(void)
844 {
845         int i;
846         BACKENDACTIVECHECK
847         CHECKGLERROR
848         GL_LockArrays(0, 0);
849         CHECKGLERROR
850
851         for (i = backendunits - 1;i >= 0;i--)
852         {
853                 if (qglActiveTexture)
854                         qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
855                 if (qglClientActiveTexture)
856                         qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
857                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
858                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
859                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
860                 if (gl_texture3d)
861                 {
862                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
863                 }
864                 if (gl_texturecubemap)
865                 {
866                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
867                 }
868                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
869                 if (gl_combine.integer)
870                 {
871                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
872                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
873                 }
874         }
875         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
876         qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
877
878         qglDisable(GL_BLEND);CHECKGLERROR
879         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
880         qglDepthMask(GL_TRUE);CHECKGLERROR
881         qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
882 }
883
884 void R_Mesh_Matrix(const matrix4x4_t *matrix)
885 {
886         if (memcmp(matrix, &backend_modelmatrix, sizeof(matrix4x4_t)))
887         {
888                 backend_modelmatrix = *matrix;
889                 Matrix4x4_Concat(&backend_modelviewmatrix, &backend_viewmatrix, matrix);
890                 Matrix4x4_Transpose(&backend_glmodelviewmatrix, &backend_modelviewmatrix);
891                 qglLoadMatrixf(&backend_glmodelviewmatrix.m[0][0]);
892         }
893 }
894
895 void R_Mesh_TextureMatrix(int unitnumber, const matrix4x4_t *matrix)
896 {
897         if (memcmp(&gl_state.units[unitnumber].matrix, matrix, sizeof(matrix4x4_t)))
898         {
899                 matrix4x4_t tempmatrix;
900                 gl_state.units[unitnumber].matrix = *matrix;
901                 Matrix4x4_Transpose(&tempmatrix, &gl_state.units[unitnumber].matrix);
902                 qglMatrixMode(GL_TEXTURE);
903                 GL_ActiveTexture(unitnumber);
904                 qglLoadMatrixf(&tempmatrix.m[0][0]);
905                 qglMatrixMode(GL_MODELVIEW);
906         }
907 }
908
909 void R_Mesh_State_Texture(const rmeshstate_t *m)
910 {
911         int i, combinergb, combinealpha, scale, arrayis3d;
912         gltextureunit_t *unit;
913
914         BACKENDACTIVECHECK
915
916         if (gl_backend_rebindtextures)
917         {
918                 gl_backend_rebindtextures = false;
919                 GL_SetupTextureState();
920         }
921
922         if (r_showtrispass)
923                 return;
924         for (i = 0, unit = gl_state.units;i < backendunits;i++, unit++)
925         {
926                 if (unit->t1d != m->tex1d[i])
927                 {
928                         GL_ActiveTexture(i);
929                         if (m->tex1d[i])
930                         {
931                                 if (unit->t1d == 0)
932                                         qglEnable(GL_TEXTURE_1D);CHECKGLERROR
933                         }
934                         else
935                         {
936                                 if (unit->t1d)
937                                         qglDisable(GL_TEXTURE_1D);CHECKGLERROR
938                         }
939                         qglBindTexture(GL_TEXTURE_1D, (unit->t1d = m->tex1d[i]));CHECKGLERROR
940                 }
941                 if (unit->t2d != m->tex[i])
942                 {
943                         GL_ActiveTexture(i);
944                         if (m->tex[i])
945                         {
946                                 if (unit->t2d == 0)
947                                         qglEnable(GL_TEXTURE_2D);CHECKGLERROR
948                         }
949                         else
950                         {
951                                 if (unit->t2d)
952                                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
953                         }
954                         qglBindTexture(GL_TEXTURE_2D, (unit->t2d = m->tex[i]));CHECKGLERROR
955                 }
956                 if (unit->t3d != m->tex3d[i])
957                 {
958                         GL_ActiveTexture(i);
959                         if (m->tex3d[i])
960                         {
961                                 if (unit->t3d == 0)
962                                         qglEnable(GL_TEXTURE_3D);CHECKGLERROR
963                         }
964                         else
965                         {
966                                 if (unit->t3d)
967                                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
968                         }
969                         qglBindTexture(GL_TEXTURE_3D, (unit->t3d = m->tex3d[i]));CHECKGLERROR
970                 }
971                 if (unit->tcubemap != m->texcubemap[i])
972                 {
973                         GL_ActiveTexture(i);
974                         if (m->texcubemap[i])
975                         {
976                                 if (unit->tcubemap == 0)
977                                         qglEnable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
978                         }
979                         else
980                         {
981                                 if (unit->tcubemap)
982                                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
983                         }
984                         qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, (unit->tcubemap = m->texcubemap[i]));CHECKGLERROR
985                 }
986                 combinergb = m->texcombinergb[i];
987                 if (!combinergb)
988                         combinergb = GL_MODULATE;
989                 if (unit->combinergb != combinergb)
990                 {
991                         GL_ActiveTexture(i);
992                         unit->combinergb = combinergb;
993                         if (gl_combine.integer) 
994                         {
995                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
996                         }
997                         else
998                         {
999                                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
1000                         }
1001                 }
1002                 combinealpha = m->texcombinealpha[i];
1003                 if (!combinealpha)
1004                         combinealpha = GL_MODULATE;
1005                 if (unit->combinealpha != combinealpha)
1006                 {
1007                         GL_ActiveTexture(i);
1008                         unit->combinealpha = combinealpha;
1009                         if (gl_combine.integer)
1010                         {
1011                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
1012                         }
1013                 }
1014                 scale = max(m->texrgbscale[i], 1);
1015                 if (unit->rgbscale != scale)
1016                 {
1017                         GL_ActiveTexture(i);
1018                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (unit->rgbscale = scale));CHECKGLERROR
1019                 }
1020                 scale = max(m->texalphascale[i], 1);
1021                 if (unit->alphascale != scale)
1022                 {
1023                         GL_ActiveTexture(i);
1024                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (unit->alphascale = scale));CHECKGLERROR
1025                 }
1026                 arrayis3d = unit->t3d || unit->tcubemap;
1027                 if (unit->pointer_texcoord != m->pointer_texcoord[i] || unit->arrayis3d != arrayis3d)
1028                 {
1029                         GL_ClientActiveTexture(i);
1030                         if (m->pointer_texcoord[i])
1031                         {
1032                                 if (!unit->arrayenabled)
1033                                 {
1034                                         unit->arrayenabled = true;
1035                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1036                                 }
1037                         }
1038                         else
1039                         {
1040                                 if (unit->arrayenabled)
1041                                 {
1042                                         unit->arrayenabled = false;
1043                                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1044                                 }
1045                         }
1046                         unit->pointer_texcoord = m->pointer_texcoord[i];
1047                         unit->arrayis3d = arrayis3d;
1048                         if (unit->arrayis3d)
1049                                 qglTexCoordPointer(3, GL_FLOAT, sizeof(float[3]), unit->pointer_texcoord);
1050                         else
1051                                 qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), unit->pointer_texcoord);
1052                         CHECKGLERROR
1053                 }
1054         }
1055 }
1056
1057 void R_Mesh_Draw_ShowTris(int numverts, int numtriangles, const int *elements)
1058 {
1059         qglBegin(GL_LINES);
1060         for (;numtriangles;numtriangles--, elements += 3)
1061         {
1062                 qglArrayElement(elements[0]);qglArrayElement(elements[1]);
1063                 qglArrayElement(elements[1]);qglArrayElement(elements[2]);
1064                 qglArrayElement(elements[2]);qglArrayElement(elements[0]);
1065         }
1066         qglEnd();
1067         CHECKGLERROR
1068 }
1069
1070 /*
1071 ==============================================================================
1072
1073                                                 SCREEN SHOTS
1074
1075 ==============================================================================
1076 */
1077
1078 qboolean SCR_ScreenShot(char *filename, int x, int y, int width, int height, qboolean jpeg)
1079 {
1080         qboolean ret;
1081         qbyte *buffer;
1082
1083         if (!r_render.integer)
1084                 return false;
1085
1086         buffer = Mem_Alloc(tempmempool, width*height*3);
1087         qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
1088         CHECKGLERROR
1089
1090         if (jpeg)
1091                 ret = JPEG_SaveImage_preflipped (filename, width, height, buffer);
1092         else
1093                 ret = Image_WriteTGARGB_preflipped (filename, width, height, buffer);
1094
1095         Mem_Free(buffer);
1096         return ret;
1097 }
1098
1099 //=============================================================================
1100
1101 void R_ClearScreen(void)
1102 {
1103         if (r_render.integer)
1104         {
1105                 // clear to black
1106                 qglClearColor(0,0,0,0);CHECKGLERROR
1107                 qglClearDepth(1);CHECKGLERROR
1108                 if (gl_stencil)
1109                 {
1110                         // LordHavoc: we use a stencil centered around 128 instead of 0,
1111                         // to avoid clamping interfering with strange shadow volume
1112                         // drawing orders
1113                         qglClearStencil(128);CHECKGLERROR
1114                 }
1115                 // clear the screen
1116                 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (gl_stencil ? GL_STENCIL_BUFFER_BIT : 0));
1117                 // set dithering mode
1118                 if (gl_dither.integer)
1119                 {
1120                         qglEnable(GL_DITHER);CHECKGLERROR
1121                 }
1122                 else
1123                 {
1124                         qglDisable(GL_DITHER);CHECKGLERROR
1125                 }
1126         }
1127 }
1128
1129 /*
1130 ====================
1131 CalcFov
1132 ====================
1133 */
1134 float CalcFov (float fov_x, float width, float height)
1135 {
1136         // calculate vision size and alter by aspect, then convert back to angle
1137         return atan (height / (width / tan(fov_x/360*M_PI))) * 360 / M_PI;
1138 }
1139
1140 /*
1141 ==================
1142 SCR_UpdateScreen
1143
1144 This is called every frame, and can also be called explicitly to flush
1145 text to the screen.
1146 ==================
1147 */
1148 void SCR_UpdateScreen (void)
1149 {
1150         if (gl_delayfinish.integer)
1151         {
1152                 R_Mesh_Finish();
1153                 R_TimeReport("meshfinish");
1154                 VID_Finish();
1155                 R_TimeReport("finish");
1156         }
1157
1158         R_Mesh_Start();
1159
1160         if (r_textureunits.integer > gl_textureunits)
1161                 Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
1162         if (r_textureunits.integer < 1)
1163                 Cvar_SetValueQuick(&r_textureunits, 1);
1164
1165         if (gl_combine.integer && (!gl_combine_extension || r_textureunits.integer < 2))
1166                 Cvar_SetValueQuick(&gl_combine, 0);
1167
1168 showtris:
1169         R_TimeReport("setup");
1170
1171         R_ClearScreen();
1172
1173         R_TimeReport("clear");
1174
1175         if (scr_conlines < vid.conheight && cls.signon == SIGNONS)
1176         {
1177                 float size;
1178                 int contents;
1179
1180                 // bound viewsize
1181                 if (scr_viewsize.value < 30)
1182                         Cvar_Set ("viewsize","30");
1183                 if (scr_viewsize.value > 120)
1184                         Cvar_Set ("viewsize","120");
1185                 
1186                 // bound field of view
1187                 if (scr_fov.value < 1)
1188                         Cvar_Set ("fov","1");
1189                 if (scr_fov.value > 170)
1190                         Cvar_Set ("fov","170");
1191         
1192                 // intermission is always full screen
1193                 if (cl.intermission)
1194                 {
1195                         size = 1;
1196                         sb_lines = 0;
1197                 }
1198                 else
1199                 {
1200                         if (scr_viewsize.value >= 120)
1201                                 sb_lines = 0;           // no status bar at all
1202                         else if (scr_viewsize.value >= 110)
1203                                 sb_lines = 24;          // no inventory
1204                         else
1205                                 sb_lines = 24+16+8;
1206                         size = scr_viewsize.value * (1.0 / 100.0);
1207                         size = min(size, 1);
1208                 }
1209         
1210                 r_refdef.width = vid.realwidth * size;
1211                 r_refdef.height = vid.realheight * size;
1212                 r_refdef.x = (vid.realwidth - r_refdef.width)/2;
1213                 r_refdef.y = (vid.realheight - r_refdef.height)/2;
1214         
1215                 // LordHavoc: viewzoom (zoom in for sniper rifles, etc)
1216                 r_refdef.fov_x = scr_fov.value * cl.viewzoom;
1217                 r_refdef.fov_y = CalcFov (r_refdef.fov_x, r_refdef.width, r_refdef.height);
1218         
1219                 if (cl.worldmodel)
1220                 {
1221                         Mod_CheckLoaded(cl.worldmodel);
1222                         contents = CL_PointSuperContents(r_vieworigin);
1223                         if (contents & SUPERCONTENTS_LIQUIDSMASK)
1224                         {
1225                                 r_refdef.fov_x *= (sin(cl.time * 4.7) * 0.015 + 0.985);
1226                                 r_refdef.fov_y *= (sin(cl.time * 3.0) * 0.015 + 0.985);
1227                         }
1228                 }
1229
1230                 R_RenderView();
1231
1232                 if (scr_zoomwindow.integer)
1233                 {
1234                         float sizex = bound(10, scr_zoomwindow_viewsizex.value, 100) / 100.0;
1235                         float sizey = bound(10, scr_zoomwindow_viewsizey.value, 100) / 100.0;
1236                         r_refdef.width = vid.realwidth * sizex;
1237                         r_refdef.height = vid.realheight * sizey;
1238                         r_refdef.x = (vid.realwidth - r_refdef.width)/2;
1239                         r_refdef.y = 0;
1240                         r_refdef.fov_x = scr_zoomwindow_fov.value;
1241                         r_refdef.fov_y = CalcFov(r_refdef.fov_x, r_refdef.width, r_refdef.height);
1242
1243                         R_RenderView();
1244                 }
1245         }
1246
1247         // draw 2D stuff
1248         R_DrawQueue();
1249
1250         if (r_showtrispass)
1251                 r_showtrispass = false;
1252         else if (r_showtris.integer)
1253         {
1254                 rmeshstate_t m;
1255                 GL_BlendFunc(GL_ONE, GL_ONE);
1256                 GL_DepthTest(GL_FALSE);
1257                 GL_DepthMask(GL_FALSE);
1258                 memset(&m, 0, sizeof(m));
1259                 R_Mesh_State_Texture(&m);
1260                 r_showtrispass = true;
1261                 GL_ShowTrisColor(0.2,0.2,0.2,1);
1262                 goto showtris;
1263         }
1264
1265         if (gl_delayfinish.integer)
1266         {
1267                 // tell driver to commit it's partially full geometry queue to the rendering queue
1268                 // (this doesn't wait for the commands themselves to complete)
1269                 qglFlush();
1270         }
1271         else
1272         {
1273                 R_Mesh_Finish();
1274                 R_TimeReport("meshfinish");
1275                 VID_Finish();
1276                 R_TimeReport("finish");
1277         }
1278 }
1279
1280
1281 //===========================================================================
1282 // dynamic vertex array buffer subsystem
1283 //===========================================================================
1284
1285 float varray_vertex3f[65536*3];
1286 float varray_color4f[65536*4];
1287 float varray_texcoord2f[4][65536*2];
1288 float varray_texcoord3f[4][65536*3];
1289 float varray_normal3f[65536*3];
1290 int earray_element3i[65536];
1291
1292 //===========================================================================
1293 // vertex array caching subsystem
1294 //===========================================================================
1295
1296 typedef struct rcachearraylink_s
1297 {
1298         struct rcachearraylink_s *next, *prev;
1299         struct rcachearrayitem_s *data;
1300 }
1301 rcachearraylink_t;
1302
1303 typedef struct rcachearrayitem_s
1304 {
1305         // the original request structure
1306         rcachearrayrequest_t request;
1307         // active
1308         int active;
1309         // offset into r_mesh_rcachedata
1310         int offset;
1311         // for linking this into the sequential list
1312         rcachearraylink_t sequentiallink;
1313         // for linking this into the lookup list
1314         rcachearraylink_t hashlink;
1315 }
1316 rcachearrayitem_t;
1317
1318 #define RCACHEARRAY_HASHSIZE 65536
1319 #define RCACHEARRAY_ITEMS 4096
1320 #define RCACHEARRAY_DEFAULTSIZE (4 << 20)
1321
1322 // all active items are linked into this chain in sorted order
1323 static rcachearraylink_t r_mesh_rcachesequentialchain;
1324 // all inactive items are linked into this chain in unknown order
1325 static rcachearraylink_t r_mesh_rcachefreechain;
1326 // all active items are also linked into these chains (using their hashlink)
1327 static rcachearraylink_t r_mesh_rcachechain[RCACHEARRAY_HASHSIZE];
1328
1329 // all items are stored here, whether active or inactive
1330 static rcachearrayitem_t r_mesh_rcacheitems[RCACHEARRAY_ITEMS];
1331
1332 // size of data buffer
1333 static int r_mesh_rcachedata_size = RCACHEARRAY_DEFAULTSIZE;
1334 // data buffer
1335 static qbyte r_mesh_rcachedata[RCACHEARRAY_DEFAULTSIZE];
1336
1337 // current state
1338 static int r_mesh_rcachedata_offset;
1339 static rcachearraylink_t *r_mesh_rcachesequentialchain_current;
1340
1341 static void R_Mesh_CacheArray_Startup(void)
1342 {
1343         int i;
1344         rcachearraylink_t *l;
1345         // prepare all the linked lists
1346         l = &r_mesh_rcachesequentialchain;l->next = l->prev = l;l->data = NULL;
1347         l = &r_mesh_rcachefreechain;l->next = l->prev = l;l->data = NULL;
1348         memset(&r_mesh_rcachechain, 0, sizeof(r_mesh_rcachechain));
1349         for (i = 0;i < RCACHEARRAY_HASHSIZE;i++)
1350         {
1351                 l = &r_mesh_rcachechain[i];
1352                 l->next = l->prev = l;
1353                 l->data = NULL;
1354         }
1355         memset(&r_mesh_rcacheitems, 0, sizeof(r_mesh_rcacheitems));
1356         for (i = 0;i < RCACHEARRAY_ITEMS;i++)
1357         {
1358                 r_mesh_rcacheitems[i].hashlink.data = r_mesh_rcacheitems[i].sequentiallink.data = &r_mesh_rcacheitems[i];
1359                 l = &r_mesh_rcacheitems[i].sequentiallink;
1360                 l->next = &r_mesh_rcachefreechain;
1361                 l->prev = l->next->prev;
1362                 l->next->prev = l->prev->next = l;
1363         }
1364         // clear other state
1365         r_mesh_rcachedata_offset = 0;
1366         r_mesh_rcachesequentialchain_current = &r_mesh_rcachesequentialchain;
1367 }
1368
1369 static void R_Mesh_CacheArray_Shutdown(void)
1370 {
1371 }
1372
1373 /*
1374 static void R_Mesh_CacheArray_ValidateState(int num)
1375 {
1376         rcachearraylink_t *l, *lhead;
1377         lhead = &r_mesh_rcachesequentialchain;
1378         if (r_mesh_rcachesequentialchain_current == lhead)
1379                 return;
1380         for (l = lhead->next;l != lhead;l = l->next)
1381                 if (r_mesh_rcachesequentialchain_current == l)
1382                         return;
1383         Sys_Error("%i", num);
1384 }
1385 */
1386
1387 int R_Mesh_CacheArray(rcachearrayrequest_t *r)
1388 {
1389         rcachearraylink_t *l, *lhead, *lnext;
1390         rcachearrayitem_t *d;
1391         int hashindex, offset, offsetend;
1392
1393         //R_Mesh_CacheArray_ValidateState(3);
1394         // calculate a hashindex to choose a cache chain
1395         r->data = NULL;
1396         hashindex = CRC_Block((void *)r, sizeof(*r)) % RCACHEARRAY_HASHSIZE;
1397
1398         // is it already cached?
1399         for (lhead = &r_mesh_rcachechain[hashindex], l = lhead->next;l != lhead;l = l->next)
1400         {
1401                 if (!memcmp(&l->data->request, r, sizeof(l->data->request)))
1402                 {
1403                         // we have it cached already
1404                         r->data = r_mesh_rcachedata + l->data->offset;
1405                         return false;
1406                 }
1407         }
1408
1409         // we need to add a new cache item, this means finding a place for the new
1410         // data and making sure we have a free item available, lots of work...
1411
1412         // check if buffer needs to wrap
1413         if (r_mesh_rcachedata_offset + r->data_size > r_mesh_rcachedata_size)
1414         {
1415                 /*
1416                 if (r->data_size * 10 > r_mesh_rcachedata_size)
1417                 {
1418                         // realloc whole cache
1419                 }
1420                 */
1421                 // reset back to start
1422                 r_mesh_rcachedata_offset = 0;
1423                 r_mesh_rcachesequentialchain_current = &r_mesh_rcachesequentialchain;
1424         }
1425         offset = r_mesh_rcachedata_offset;
1426         r_mesh_rcachedata_offset += r->data_size;
1427         offsetend = r_mesh_rcachedata_offset;
1428         //R_Mesh_CacheArray_ValidateState(4);
1429
1430         /*
1431         {
1432                 int n;
1433                 for (lhead = &r_mesh_rcachesequentialchain, l = lhead->next, n = 0;l != lhead;l = l->next, n++);
1434                 Con_Printf("R_Mesh_CacheArray: new data range %i:%i, %i items are already linked\n", offset, offsetend, n);
1435         }
1436         */
1437
1438         // make room for the new data (remove old items)
1439         lhead = &r_mesh_rcachesequentialchain;
1440         l = r_mesh_rcachesequentialchain_current;
1441         if (l == lhead)
1442                 l = l->next;
1443         while (l != lhead && l->data->offset < offsetend && l->data->offset + l->data->request.data_size > offset)
1444         {
1445         //r_mesh_rcachesequentialchain_current = l;
1446         //R_Mesh_CacheArray_ValidateState(8);
1447                 lnext = l->next;
1448                 // if at the end of the chain, wrap around
1449                 if (lnext == lhead)
1450                         lnext = lnext->next;
1451         //r_mesh_rcachesequentialchain_current = lnext;
1452         //R_Mesh_CacheArray_ValidateState(10);
1453
1454                 // unlink from sequential chain
1455                 l->next->prev = l->prev;
1456                 l->prev->next = l->next;
1457         //R_Mesh_CacheArray_ValidateState(11);
1458                 // link into free chain
1459                 l->next = &r_mesh_rcachefreechain;
1460                 l->prev = l->next->prev;
1461                 l->next->prev = l->prev->next = l;
1462         //R_Mesh_CacheArray_ValidateState(12);
1463
1464                 l = &l->data->hashlink;
1465                 // unlink from hash chain
1466                 l->next->prev = l->prev;
1467                 l->prev->next = l->next;
1468
1469                 l = lnext;
1470         //r_mesh_rcachesequentialchain_current = l;
1471         //R_Mesh_CacheArray_ValidateState(9);
1472         }
1473         //r_mesh_rcachesequentialchain_current = l;
1474         //R_Mesh_CacheArray_ValidateState(5);
1475         // gobble an extra item if we have no free items available
1476         if (r_mesh_rcachefreechain.next == &r_mesh_rcachefreechain)
1477         {
1478                 lnext = l->next;
1479
1480                 // unlink from sequential chain
1481                 l->next->prev = l->prev;
1482                 l->prev->next = l->next;
1483                 // link into free chain
1484                 l->next = &r_mesh_rcachefreechain;
1485                 l->prev = l->next->prev;
1486                 l->next->prev = l->prev->next = l;
1487
1488                 l = &l->data->hashlink;
1489                 // unlink from hash chain
1490                 l->next->prev = l->prev;
1491                 l->prev->next = l->next;
1492
1493                 l = lnext;
1494         }
1495         r_mesh_rcachesequentialchain_current = l;
1496         //R_Mesh_CacheArray_ValidateState(6);
1497
1498         // now take an item from the free chain
1499         l = r_mesh_rcachefreechain.next;
1500         // set it up
1501         d = l->data;
1502         d->request = *r;
1503         d->offset = offset;
1504         // unlink
1505         l->next->prev = l->prev;
1506         l->prev->next = l->next;
1507         // relink to sequential
1508         l->next = r_mesh_rcachesequentialchain_current->prev;
1509         l->prev = l->next->prev;
1510         while (l->next->data && l->data && l->next->data->offset <= d->offset)
1511         {
1512                 //Con_Printf(">\n");
1513                 l->next = l->next->next;
1514                 l->prev = l->prev->next;
1515         }
1516         while (l->prev->data && l->data && l->prev->data->offset >= d->offset)
1517         {
1518                 //Con_Printf("<\n");
1519                 l->prev = l->prev->prev;
1520                 l->next = l->next->prev;
1521         }
1522         l->next->prev = l->prev->next = l;
1523         // also link into hash chain
1524         l = &l->data->hashlink;
1525         l->next = &r_mesh_rcachechain[hashindex];
1526         l->prev = l->next->prev;
1527         l->prev->next = l;
1528         l->next->prev = l->prev->next = l;
1529
1530
1531         //r_mesh_rcachesequentialchain_current = d->sequentiallink.next;
1532
1533         //R_Mesh_CacheArray_ValidateState(7);
1534         // and finally set the data pointer
1535         r->data = r_mesh_rcachedata + d->offset;
1536         // and tell the caller to fill the array
1537         return true;
1538 }
1539