Added in_mouse_x and in_mouse_y, which contain the rel. coords of the mouse.
[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 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(qboolean 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 /*
1007 ==============================================================================
1008
1009                                                 SCREEN SHOTS
1010
1011 ==============================================================================
1012 */
1013
1014 qboolean SCR_ScreenShot(char *filename, int x, int y, int width, int height, qboolean jpeg)
1015 {
1016         qboolean ret;
1017         qbyte *buffer;
1018
1019         if (!r_render.integer)
1020                 return false;
1021
1022         buffer = Mem_Alloc(tempmempool, width*height*3);
1023         qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
1024         CHECKGLERROR
1025
1026         if (jpeg)
1027                 ret = JPEG_SaveImage_preflipped (filename, width, height, buffer);
1028         else
1029                 ret = Image_WriteTGARGB_preflipped (filename, width, height, buffer);
1030
1031         Mem_Free(buffer);
1032         return ret;
1033 }
1034
1035 //=============================================================================
1036
1037 void R_ClearScreen(void)
1038 {
1039         if (r_render.integer)
1040         {
1041                 // clear to black
1042                 qglClearColor(0,0,0,0);CHECKGLERROR
1043                 qglClearDepth(1);CHECKGLERROR
1044                 if (gl_stencil)
1045                 {
1046                         // LordHavoc: we use a stencil centered around 128 instead of 0,
1047                         // to avoid clamping interfering with strange shadow volume
1048                         // drawing orders
1049                         qglClearStencil(128);CHECKGLERROR
1050                 }
1051                 // clear the screen
1052                 qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (gl_stencil ? GL_STENCIL_BUFFER_BIT : 0));CHECKGLERROR
1053                 // set dithering mode
1054                 if (gl_dither.integer)
1055                 {
1056                         qglEnable(GL_DITHER);CHECKGLERROR
1057                 }
1058                 else
1059                 {
1060                         qglDisable(GL_DITHER);CHECKGLERROR
1061                 }
1062         }
1063 }
1064
1065 /*
1066 ==================
1067 SCR_UpdateScreen
1068
1069 This is called every frame, and can also be called explicitly to flush
1070 text to the screen.
1071 ==================
1072 */
1073 void SCR_UpdateScreen (void)
1074 {
1075         if (gl_delayfinish.integer)
1076         {
1077                 VID_Finish ();
1078
1079                 R_TimeReport("finish");
1080         }
1081
1082         if (r_textureunits.integer > gl_textureunits)
1083                 Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
1084         if (r_textureunits.integer < 1)
1085                 Cvar_SetValueQuick(&r_textureunits, 1);
1086
1087         if (gl_combine.integer && (!gl_combine_extension || r_textureunits.integer < 2))
1088                 Cvar_SetValueQuick(&gl_combine, 0);
1089
1090         // lightmaps only
1091         r_lightmapscalebit = 0;
1092         if (gl_combine.integer && r_textureunits.integer > 1)
1093                 r_lightmapscalebit += 2;
1094
1095         R_TimeReport("setup");
1096
1097         R_ClearScreen();
1098
1099         R_TimeReport("clear");
1100
1101         if (scr_conlines < vid.conheight && cls.signon == SIGNONS)
1102                 R_RenderView();
1103
1104         // draw 2D stuff
1105         R_DrawQueue();
1106
1107         if (gl_delayfinish.integer)
1108         {
1109                 // tell driver to commit it's partially full geometry queue to the rendering queue
1110                 // (this doesn't wait for the commands themselves to complete)
1111                 qglFlush();
1112         }
1113         else
1114         {
1115                 VID_Finish ();
1116
1117                 R_TimeReport("finish");
1118         }
1119 }
1120
1121
1122 //===========================================================================
1123 // dynamic vertex array buffer subsystem
1124 //===========================================================================
1125
1126 float varray_vertex3f[65536*3];
1127 float varray_color4f[65536*4];
1128 float varray_texcoord2f[4][65536*2];
1129 float varray_texcoord3f[4][65536*3];
1130 float varray_normal3f[65536*3];
1131 int earray_element3i[65536];
1132
1133 //===========================================================================
1134 // vertex array caching subsystem
1135 //===========================================================================
1136
1137 typedef struct rcachearraylink_s
1138 {
1139         struct rcachearraylink_s *next, *prev;
1140         struct rcachearrayitem_s *data;
1141 }
1142 rcachearraylink_t;
1143
1144 typedef struct rcachearrayitem_s
1145 {
1146         // the original request structure
1147         rcachearrayrequest_t request;
1148         // active
1149         int active;
1150         // offset into r_mesh_rcachedata
1151         int offset;
1152         // for linking this into the sequential list
1153         rcachearraylink_t sequentiallink;
1154         // for linking this into the lookup list
1155         rcachearraylink_t hashlink;
1156 }
1157 rcachearrayitem_t;
1158
1159 #define RCACHEARRAY_HASHSIZE 65536
1160 #define RCACHEARRAY_ITEMS 4096
1161 #define RCACHEARRAY_DEFAULTSIZE (4 << 20)
1162
1163 // all active items are linked into this chain in sorted order
1164 static rcachearraylink_t r_mesh_rcachesequentialchain;
1165 // all inactive items are linked into this chain in unknown order
1166 static rcachearraylink_t r_mesh_rcachefreechain;
1167 // all active items are also linked into these chains (using their hashlink)
1168 static rcachearraylink_t r_mesh_rcachechain[RCACHEARRAY_HASHSIZE];
1169
1170 // all items are stored here, whether active or inactive
1171 static rcachearrayitem_t r_mesh_rcacheitems[RCACHEARRAY_ITEMS];
1172
1173 // size of data buffer
1174 static int r_mesh_rcachedata_size = RCACHEARRAY_DEFAULTSIZE;
1175 // data buffer
1176 static qbyte r_mesh_rcachedata[RCACHEARRAY_DEFAULTSIZE];
1177
1178 // current state
1179 static int r_mesh_rcachedata_offset;
1180 static rcachearraylink_t *r_mesh_rcachesequentialchain_current;
1181
1182 static void R_Mesh_CacheArray_Startup(void)
1183 {
1184         int i;
1185         rcachearraylink_t *l;
1186         // prepare all the linked lists
1187         l = &r_mesh_rcachesequentialchain;l->next = l->prev = l;l->data = NULL;
1188         l = &r_mesh_rcachefreechain;l->next = l->prev = l;l->data = NULL;
1189         memset(&r_mesh_rcachechain, 0, sizeof(r_mesh_rcachechain));
1190         for (i = 0;i < RCACHEARRAY_HASHSIZE;i++)
1191         {
1192                 l = &r_mesh_rcachechain[i];
1193                 l->next = l->prev = l;
1194                 l->data = NULL;
1195         }
1196         memset(&r_mesh_rcacheitems, 0, sizeof(r_mesh_rcacheitems));
1197         for (i = 0;i < RCACHEARRAY_ITEMS;i++)
1198         {
1199                 r_mesh_rcacheitems[i].hashlink.data = r_mesh_rcacheitems[i].sequentiallink.data = &r_mesh_rcacheitems[i];
1200                 l = &r_mesh_rcacheitems[i].sequentiallink;
1201                 l->next = &r_mesh_rcachefreechain;
1202                 l->prev = l->next->prev;
1203                 l->next->prev = l->prev->next = l;
1204         }
1205         // clear other state
1206         r_mesh_rcachedata_offset = 0;
1207         r_mesh_rcachesequentialchain_current = &r_mesh_rcachesequentialchain;
1208 }
1209
1210 static void R_Mesh_CacheArray_Shutdown(void)
1211 {
1212 }
1213
1214 /*
1215 static void R_Mesh_CacheArray_ValidateState(int num)
1216 {
1217         rcachearraylink_t *l, *lhead;
1218         lhead = &r_mesh_rcachesequentialchain;
1219         if (r_mesh_rcachesequentialchain_current == lhead)
1220                 return;
1221         for (l = lhead->next;l != lhead;l = l->next)
1222                 if (r_mesh_rcachesequentialchain_current == l)
1223                         return;
1224         Sys_Error("%i", num);
1225 }
1226 */
1227
1228 int R_Mesh_CacheArray(rcachearrayrequest_t *r)
1229 {
1230         rcachearraylink_t *l, *lhead, *lnext;
1231         rcachearrayitem_t *d;
1232         int hashindex, offset, offsetend;
1233
1234         //R_Mesh_CacheArray_ValidateState(3);
1235         // calculate a hashindex to choose a cache chain
1236         r->data = NULL;
1237         hashindex = CRC_Block((void *)r, sizeof(*r)) % RCACHEARRAY_HASHSIZE;
1238
1239         // is it already cached?
1240         for (lhead = &r_mesh_rcachechain[hashindex], l = lhead->next;l != lhead;l = l->next)
1241         {
1242                 if (!memcmp(&l->data->request, r, sizeof(l->data->request)))
1243                 {
1244                         // we have it cached already
1245                         r->data = r_mesh_rcachedata + l->data->offset;
1246                         return false;
1247                 }
1248         }
1249
1250         // we need to add a new cache item, this means finding a place for the new
1251         // data and making sure we have a free item available, lots of work...
1252
1253         // check if buffer needs to wrap
1254         if (r_mesh_rcachedata_offset + r->data_size > r_mesh_rcachedata_size)
1255         {
1256                 /*
1257                 if (r->data_size * 10 > r_mesh_rcachedata_size)
1258                 {
1259                         // realloc whole cache
1260                 }
1261                 */
1262                 // reset back to start
1263                 r_mesh_rcachedata_offset = 0;
1264                 r_mesh_rcachesequentialchain_current = &r_mesh_rcachesequentialchain;
1265         }
1266         offset = r_mesh_rcachedata_offset;
1267         r_mesh_rcachedata_offset += r->data_size;
1268         offsetend = r_mesh_rcachedata_offset;
1269         //R_Mesh_CacheArray_ValidateState(4);
1270
1271         /*
1272         {
1273                 int n;
1274                 for (lhead = &r_mesh_rcachesequentialchain, l = lhead->next, n = 0;l != lhead;l = l->next, n++);
1275                 Con_Printf("R_Mesh_CacheArray: new data range %i:%i, %i items are already linked\n", offset, offsetend, n);
1276         }
1277         */
1278
1279         // make room for the new data (remove old items)
1280         lhead = &r_mesh_rcachesequentialchain;
1281         l = r_mesh_rcachesequentialchain_current;
1282         if (l == lhead)
1283                 l = l->next;
1284         while (l != lhead && l->data->offset < offsetend && l->data->offset + l->data->request.data_size > offset)
1285         {
1286         //r_mesh_rcachesequentialchain_current = l;
1287         //R_Mesh_CacheArray_ValidateState(8);
1288                 lnext = l->next;
1289                 // if at the end of the chain, wrap around
1290                 if (lnext == lhead)
1291                         lnext = lnext->next;
1292         //r_mesh_rcachesequentialchain_current = lnext;
1293         //R_Mesh_CacheArray_ValidateState(10);
1294
1295                 // unlink from sequential chain
1296                 l->next->prev = l->prev;
1297                 l->prev->next = l->next;
1298         //R_Mesh_CacheArray_ValidateState(11);
1299                 // link into free chain
1300                 l->next = &r_mesh_rcachefreechain;
1301                 l->prev = l->next->prev;
1302                 l->next->prev = l->prev->next = l;
1303         //R_Mesh_CacheArray_ValidateState(12);
1304
1305                 l = &l->data->hashlink;
1306                 // unlink from hash chain
1307                 l->next->prev = l->prev;
1308                 l->prev->next = l->next;
1309
1310                 l = lnext;
1311         //r_mesh_rcachesequentialchain_current = l;
1312         //R_Mesh_CacheArray_ValidateState(9);
1313         }
1314         //r_mesh_rcachesequentialchain_current = l;
1315         //R_Mesh_CacheArray_ValidateState(5);
1316         // gobble an extra item if we have no free items available
1317         if (r_mesh_rcachefreechain.next == &r_mesh_rcachefreechain)
1318         {
1319                 lnext = l->next;
1320
1321                 // unlink from sequential chain
1322                 l->next->prev = l->prev;
1323                 l->prev->next = l->next;
1324                 // link into free chain
1325                 l->next = &r_mesh_rcachefreechain;
1326                 l->prev = l->next->prev;
1327                 l->next->prev = l->prev->next = l;
1328
1329                 l = &l->data->hashlink;
1330                 // unlink from hash chain
1331                 l->next->prev = l->prev;
1332                 l->prev->next = l->next;
1333
1334                 l = lnext;
1335         }
1336         r_mesh_rcachesequentialchain_current = l;
1337         //R_Mesh_CacheArray_ValidateState(6);
1338
1339         // now take an item from the free chain
1340         l = r_mesh_rcachefreechain.next;
1341         // set it up
1342         d = l->data;
1343         d->request = *r;
1344         d->offset = offset;
1345         // unlink
1346         l->next->prev = l->prev;
1347         l->prev->next = l->next;
1348         // relink to sequential
1349         l->next = r_mesh_rcachesequentialchain_current->prev;
1350         l->prev = l->next->prev;
1351         while (l->next->data && l->data && l->next->data->offset <= d->offset)
1352         {
1353                 //Con_Printf(">\n");
1354                 l->next = l->next->next;
1355                 l->prev = l->prev->next;
1356         }
1357         while (l->prev->data && l->data && l->prev->data->offset >= d->offset)
1358         {
1359                 //Con_Printf("<\n");
1360                 l->prev = l->prev->prev;
1361                 l->next = l->next->prev;
1362         }
1363         l->next->prev = l->prev->next = l;
1364         // also link into hash chain
1365         l = &l->data->hashlink;
1366         l->next = &r_mesh_rcachechain[hashindex];
1367         l->prev = l->next->prev;
1368         l->prev->next = l;
1369         l->next->prev = l->prev->next = l;
1370
1371
1372         //r_mesh_rcachesequentialchain_current = d->sequentiallink.next;
1373
1374         //R_Mesh_CacheArray_ValidateState(7);
1375         // and finally set the data pointer
1376         r->data = r_mesh_rcachedata + d->offset;
1377         // and tell the caller to fill the array
1378         return true;
1379 }
1380