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