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