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