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