added a firstvertex parameter to R_Mesh_DrawMesh
[xonotic/darkplaces.git] / gl_backend.c
1
2 #include "quakedef.h"
3 #include "image.h"
4 #include "jpeg.h"
5 #include "cl_collision.h"
6
7 cvar_t gl_mesh_drawrangeelements = {0, "gl_mesh_drawrangeelements", "1"};
8 cvar_t gl_mesh_testarrayelement = {0, "gl_mesh_testarrayelement", "0"};
9 cvar_t gl_mesh_testmanualfeeding = {0, "gl_mesh_testmanualfeeding", "0"};
10 cvar_t gl_paranoid = {0, "gl_paranoid", "0"};
11 cvar_t gl_printcheckerror = {0, "gl_printcheckerror", "0"};
12 cvar_t r_stereo_separation = {0, "r_stereo_separation", "4"};
13 cvar_t r_stereo_sidebyside = {0, "r_stereo_sidebyside", "0"};
14 cvar_t r_stereo_redblue = {0, "r_stereo_redblue", "0"};
15 cvar_t r_stereo_redcyan = {0, "r_stereo_redcyan", "0"};
16 cvar_t r_stereo_redgreen = {0, "r_stereo_redgreen", "0"};
17
18 cvar_t r_render = {0, "r_render", "1"};
19 cvar_t r_waterwarp = {CVAR_SAVE, "r_waterwarp", "1"};
20 cvar_t gl_polyblend = {CVAR_SAVE, "gl_polyblend", "1"};
21 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1"}; // whether or not to use dithering
22 cvar_t gl_lockarrays = {0, "gl_lockarrays", "1"};
23
24 int gl_maxdrawrangeelementsvertices;
25 int gl_maxdrawrangeelementsindices;
26
27 #ifdef DEBUGGL
28 int errornumber = 0;
29
30 void GL_PrintError(int errornumber, char *filename, int linenumber)
31 {
32         switch(errornumber)
33         {
34 #ifdef GL_INVALID_ENUM
35         case GL_INVALID_ENUM:
36                 Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
37                 break;
38 #endif
39 #ifdef GL_INVALID_VALUE
40         case GL_INVALID_VALUE:
41                 Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
42                 break;
43 #endif
44 #ifdef GL_INVALID_OPERATION
45         case GL_INVALID_OPERATION:
46                 Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
47                 break;
48 #endif
49 #ifdef GL_STACK_OVERFLOW
50         case GL_STACK_OVERFLOW:
51                 Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
52                 break;
53 #endif
54 #ifdef GL_STACK_UNDERFLOW
55         case GL_STACK_UNDERFLOW:
56                 Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
57                 break;
58 #endif
59 #ifdef GL_OUT_OF_MEMORY
60         case GL_OUT_OF_MEMORY:
61                 Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
62                 break;
63 #endif
64 #ifdef GL_TABLE_TOO_LARGE
65         case GL_TABLE_TOO_LARGE:
66                 Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
67                 break;
68 #endif
69         default:
70                 Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
71                 break;
72         }
73 }
74 #endif
75
76 #define BACKENDACTIVECHECK if (!backendactive) Sys_Error("GL backend function called when backend is not active\n");
77
78 void SCR_ScreenShot_f (void);
79
80 static matrix4x4_t backend_viewmatrix;
81 static matrix4x4_t backend_modelmatrix;
82 static matrix4x4_t backend_modelviewmatrix;
83 static matrix4x4_t backend_glmodelviewmatrix;
84 static matrix4x4_t backend_projectmatrix;
85
86 static unsigned int backendunits, backendimageunits, backendarrayunits, backendactive;
87 static mempool_t *gl_backend_mempool;
88
89 /*
90 note: here's strip order for a terrain row:
91 0--1--2--3--4
92 |\ |\ |\ |\ |
93 | \| \| \| \|
94 A--B--C--D--E
95 clockwise
96
97 A0B, 01B, B1C, 12C, C2D, 23D, D3E, 34E
98
99 *elements++ = i + row;
100 *elements++ = i;
101 *elements++ = i + row + 1;
102 *elements++ = i;
103 *elements++ = i + 1;
104 *elements++ = i + row + 1;
105
106
107 for (y = 0;y < rows - 1;y++)
108 {
109         for (x = 0;x < columns - 1;x++)
110         {
111                 i = y * rows + x;
112                 *elements++ = i + columns;
113                 *elements++ = i;
114                 *elements++ = i + columns + 1;
115                 *elements++ = i;
116                 *elements++ = i + 1;
117                 *elements++ = i + columns + 1;
118         }
119 }
120
121 alternative:
122 0--1--2--3--4
123 | /| /|\ | /|
124 |/ |/ | \|/ |
125 A--B--C--D--E
126 counterclockwise
127
128 for (y = 0;y < rows - 1;y++)
129 {
130         for (x = 0;x < columns - 1;x++)
131         {
132                 i = y * rows + x;
133                 *elements++ = i;
134                 *elements++ = i + columns;
135                 *elements++ = i + columns + 1;
136                 *elements++ = i + columns;
137                 *elements++ = i + columns + 1;
138                 *elements++ = i + 1;
139         }
140 }
141 */
142
143 int polygonelements[768];
144
145 static void R_Mesh_CacheArray_Startup(void);
146 static void R_Mesh_CacheArray_Shutdown(void);
147 void GL_Backend_AllocArrays(void)
148 {
149         if (!gl_backend_mempool)
150                 gl_backend_mempool = Mem_AllocPool("GL_Backend", 0, NULL);
151         R_Mesh_CacheArray_Startup();
152 }
153
154 void GL_Backend_FreeArrays(void)
155 {
156         R_Mesh_CacheArray_Shutdown();
157         Mem_FreePool(&gl_backend_mempool);
158 }
159
160 static void gl_backend_start(void)
161 {
162         Con_Print("OpenGL Backend starting...\n");
163         CHECKGLERROR
164
165         if (qglDrawRangeElements != NULL)
166         {
167                 CHECKGLERROR
168                 qglGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &gl_maxdrawrangeelementsvertices);
169                 CHECKGLERROR
170                 qglGetIntegerv(GL_MAX_ELEMENTS_INDICES, &gl_maxdrawrangeelementsindices);
171                 CHECKGLERROR
172                 Con_Printf("glDrawRangeElements detected (max vertices %i, max indices %i)\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
173         }
174
175         backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
176         backendimageunits = backendunits;
177         backendarrayunits = backendunits;
178         if (gl_support_fragment_shader)
179         {
180                 CHECKGLERROR
181                 qglGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &backendimageunits);
182                 CHECKGLERROR
183                 qglGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, &backendarrayunits);
184                 CHECKGLERROR
185                 Con_Printf("GLSL shader support detected: texture units = %i texenv, %i image, %i array\n", backendunits, backendimageunits, backendarrayunits);
186         }
187         else if (backendunits > 1)
188                 Con_Printf("multitexture detected: texture units = %i\n", backendunits);
189         else
190                 Con_Printf("singletexture\n");
191
192         GL_Backend_AllocArrays();
193
194         Con_Printf("OpenGL backend started.\n");
195
196         CHECKGLERROR
197
198         backendactive = true;
199 }
200
201 static void gl_backend_shutdown(void)
202 {
203         backendunits = 0;
204         backendimageunits = 0;
205         backendarrayunits = 0;
206         backendactive = false;
207
208         Con_Print("OpenGL Backend shutting down\n");
209
210         GL_Backend_FreeArrays();
211 }
212
213 static void gl_backend_newmap(void)
214 {
215 }
216
217 cvar_t scr_zoomwindow = {CVAR_SAVE, "scr_zoomwindow", "0"};
218 cvar_t scr_zoomwindow_viewsizex = {CVAR_SAVE, "scr_zoomwindow_viewsizex", "20"};
219 cvar_t scr_zoomwindow_viewsizey = {CVAR_SAVE, "scr_zoomwindow_viewsizey", "20"};
220 cvar_t scr_zoomwindow_fov = {CVAR_SAVE, "scr_zoomwindow_fov", "20"};
221
222 void gl_backend_init(void)
223 {
224         int i;
225
226         for (i = 0;i < POLYGONELEMENTS_MAXPOINTS - 2;i++)
227         {
228                 polygonelements[i * 3 + 0] = 0;
229                 polygonelements[i * 3 + 1] = i + 1;
230                 polygonelements[i * 3 + 2] = i + 2;
231         }
232
233         Cvar_RegisterVariable(&r_render);
234         Cvar_RegisterVariable(&r_waterwarp);
235         Cvar_RegisterVariable(&r_stereo_separation);
236         Cvar_RegisterVariable(&r_stereo_sidebyside);
237         Cvar_RegisterVariable(&r_stereo_redblue);
238         Cvar_RegisterVariable(&r_stereo_redcyan);
239         Cvar_RegisterVariable(&r_stereo_redgreen);
240         Cvar_RegisterVariable(&gl_polyblend);
241         Cvar_RegisterVariable(&gl_dither);
242         Cvar_RegisterVariable(&gl_lockarrays);
243         Cvar_RegisterVariable(&gl_paranoid);
244         Cvar_RegisterVariable(&gl_printcheckerror);
245 #ifdef NORENDER
246         Cvar_SetValue("r_render", 0);
247 #endif
248
249         Cvar_RegisterVariable(&gl_mesh_drawrangeelements);
250         Cvar_RegisterVariable(&gl_mesh_testarrayelement);
251         Cvar_RegisterVariable(&gl_mesh_testmanualfeeding);
252
253         Cvar_RegisterVariable(&scr_zoomwindow);
254         Cvar_RegisterVariable(&scr_zoomwindow_viewsizex);
255         Cvar_RegisterVariable(&scr_zoomwindow_viewsizey);
256         Cvar_RegisterVariable(&scr_zoomwindow_fov);
257
258         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
259 }
260
261 void GL_SetupView_Orientation_Identity (void)
262 {
263         Matrix4x4_CreateIdentity(&backend_viewmatrix);
264         memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
265 }
266
267 void GL_SetupView_Orientation_FromEntity(matrix4x4_t *matrix)
268 {
269         matrix4x4_t tempmatrix, basematrix;
270         Matrix4x4_Invert_Simple(&tempmatrix, matrix);
271         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
272         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
273         Matrix4x4_Concat(&backend_viewmatrix, &basematrix, &tempmatrix);
274         //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[2], 1, 0, 0);
275         //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[0], 0, 1, 0);
276         //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[1], 0, 0, 1);
277         //Matrix4x4_ConcatTranslate(&backend_viewmatrix, -origin[0], -origin[1], -origin[2]);
278         memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
279 }
280
281 void GL_SetupView_Mode_Perspective (double fovx, double fovy, double zNear, double zFar)
282 {
283         double xmax, ymax;
284         double m[16];
285
286         if (!r_render.integer)
287                 return;
288
289         // set up viewpoint
290         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
291         qglLoadIdentity();CHECKGLERROR
292         // pyramid slopes
293         xmax = zNear * tan(fovx * M_PI / 360.0);
294         ymax = zNear * tan(fovy * M_PI / 360.0);
295         // set view pyramid
296         qglFrustum(-xmax, xmax, -ymax, ymax, zNear, zFar);CHECKGLERROR
297         qglGetDoublev(GL_PROJECTION_MATRIX, m);
298         backend_projectmatrix.m[0][0] = m[0];
299         backend_projectmatrix.m[1][0] = m[1];
300         backend_projectmatrix.m[2][0] = m[2];
301         backend_projectmatrix.m[3][0] = m[3];
302         backend_projectmatrix.m[0][1] = m[4];
303         backend_projectmatrix.m[1][1] = m[5];
304         backend_projectmatrix.m[2][1] = m[6];
305         backend_projectmatrix.m[3][1] = m[7];
306         backend_projectmatrix.m[0][2] = m[8];
307         backend_projectmatrix.m[1][2] = m[9];
308         backend_projectmatrix.m[2][2] = m[10];
309         backend_projectmatrix.m[3][2] = m[11];
310         backend_projectmatrix.m[0][3] = m[12];
311         backend_projectmatrix.m[1][3] = m[13];
312         backend_projectmatrix.m[2][3] = m[14];
313         backend_projectmatrix.m[3][3] = m[15];
314         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
315         GL_SetupView_Orientation_Identity();
316 }
317
318 void GL_SetupView_Mode_PerspectiveInfiniteFarClip (double fovx, double fovy, double zNear)
319 {
320         double nudge, m[16];
321
322         if (!r_render.integer)
323                 return;
324
325         // set up viewpoint
326         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
327         qglLoadIdentity();CHECKGLERROR
328         // set view pyramid
329         nudge = 1.0 - 1.0 / (1<<23);
330         m[ 0] = 1.0 / tan(fovx * M_PI / 360.0);
331         m[ 1] = 0;
332         m[ 2] = 0;
333         m[ 3] = 0;
334         m[ 4] = 0;
335         m[ 5] = 1.0 / tan(fovy * M_PI / 360.0);
336         m[ 6] = 0;
337         m[ 7] = 0;
338         m[ 8] = 0;
339         m[ 9] = 0;
340         m[10] = -nudge;
341         m[11] = -1;
342         m[12] = 0;
343         m[13] = 0;
344         m[14] = -2 * zNear * nudge;
345         m[15] = 0;
346         qglLoadMatrixd(m);
347         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
348         GL_SetupView_Orientation_Identity();
349         backend_projectmatrix.m[0][0] = m[0];
350         backend_projectmatrix.m[1][0] = m[1];
351         backend_projectmatrix.m[2][0] = m[2];
352         backend_projectmatrix.m[3][0] = m[3];
353         backend_projectmatrix.m[0][1] = m[4];
354         backend_projectmatrix.m[1][1] = m[5];
355         backend_projectmatrix.m[2][1] = m[6];
356         backend_projectmatrix.m[3][1] = m[7];
357         backend_projectmatrix.m[0][2] = m[8];
358         backend_projectmatrix.m[1][2] = m[9];
359         backend_projectmatrix.m[2][2] = m[10];
360         backend_projectmatrix.m[3][2] = m[11];
361         backend_projectmatrix.m[0][3] = m[12];
362         backend_projectmatrix.m[1][3] = m[13];
363         backend_projectmatrix.m[2][3] = m[14];
364         backend_projectmatrix.m[3][3] = m[15];
365 }
366
367 void GL_SetupView_Mode_Ortho (double x1, double y1, double x2, double y2, double zNear, double zFar)
368 {
369         double m[16];
370
371         if (!r_render.integer)
372                 return;
373
374         // set up viewpoint
375         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
376         qglLoadIdentity();CHECKGLERROR
377         qglOrtho(x1, x2, y2, y1, zNear, zFar);
378         qglGetDoublev(GL_PROJECTION_MATRIX, m);
379         backend_projectmatrix.m[0][0] = m[0];
380         backend_projectmatrix.m[1][0] = m[1];
381         backend_projectmatrix.m[2][0] = m[2];
382         backend_projectmatrix.m[3][0] = m[3];
383         backend_projectmatrix.m[0][1] = m[4];
384         backend_projectmatrix.m[1][1] = m[5];
385         backend_projectmatrix.m[2][1] = m[6];
386         backend_projectmatrix.m[3][1] = m[7];
387         backend_projectmatrix.m[0][2] = m[8];
388         backend_projectmatrix.m[1][2] = m[9];
389         backend_projectmatrix.m[2][2] = m[10];
390         backend_projectmatrix.m[3][2] = m[11];
391         backend_projectmatrix.m[0][3] = m[12];
392         backend_projectmatrix.m[1][3] = m[13];
393         backend_projectmatrix.m[2][3] = m[14];
394         backend_projectmatrix.m[3][3] = m[15];
395         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
396         GL_SetupView_Orientation_Identity();
397 }
398
399 typedef struct gltextureunit_s
400 {
401         int t1d, t2d, t3d, tcubemap;
402         int arrayenabled;
403         unsigned int arraycomponents;
404         const void *pointer_texcoord;
405         float rgbscale, alphascale;
406         int combinergb, combinealpha;
407         // FIXME: add more combine stuff
408         // texmatrixenabled exists only to avoid unnecessary texmatrix compares
409         int texmatrixenabled;
410         matrix4x4_t matrix;
411 }
412 gltextureunit_t;
413
414 static struct
415 {
416         int blendfunc1;
417         int blendfunc2;
418         int blend;
419         GLboolean depthmask;
420         int colormask; // stored as bottom 4 bits: r g b a (3 2 1 0 order)
421         int depthtest;
422         int scissortest;
423         unsigned int unit;
424         unsigned int clientunit;
425         gltextureunit_t units[MAX_TEXTUREUNITS];
426         float color4f[4];
427         int lockrange_first;
428         int lockrange_count;
429         const void *pointer_vertex;
430         const void *pointer_color;
431 }
432 gl_state;
433
434 void GL_SetupTextureState(void)
435 {
436         unsigned int i;
437         gltextureunit_t *unit;
438         CHECKGLERROR
439         gl_state.unit = -1;
440         gl_state.clientunit = -1;
441         for (i = 0;i < MAX_TEXTUREUNITS;i++)
442         {
443                 unit = gl_state.units + i;
444                 unit->t1d = 0;
445                 unit->t2d = 0;
446                 unit->t3d = 0;
447                 unit->tcubemap = 0;
448                 unit->arrayenabled = false;
449                 unit->arraycomponents = 0;
450                 unit->pointer_texcoord = NULL;
451                 unit->rgbscale = 1;
452                 unit->alphascale = 1;
453                 unit->combinergb = GL_MODULATE;
454                 unit->combinealpha = GL_MODULATE;
455                 unit->texmatrixenabled = false;
456                 unit->matrix = r_identitymatrix;
457         }
458
459         for (i = 0;i < backendimageunits;i++)
460         {
461                 GL_ActiveTexture(i);
462                 qglBindTexture(GL_TEXTURE_1D, 0);CHECKGLERROR
463                 qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
464                 if (gl_texture3d)
465                 {
466                         qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
467                 }
468                 if (gl_texturecubemap)
469                 {
470                         qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, 0);CHECKGLERROR
471                 }
472         }
473
474         for (i = 0;i < backendarrayunits;i++)
475         {
476                 GL_ClientActiveTexture(i);
477                 qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), NULL);CHECKGLERROR
478                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
479         }
480
481         for (i = 0;i < backendunits;i++)
482         {
483                 GL_ActiveTexture(i);
484                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
485                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
486                 if (gl_texture3d)
487                 {
488                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
489                 }
490                 if (gl_texturecubemap)
491                 {
492                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
493                 }
494                 qglMatrixMode(GL_TEXTURE);
495                 qglLoadIdentity();
496                 qglMatrixMode(GL_MODELVIEW);
497                 if (gl_combine.integer)
498                 {
499                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
500                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);CHECKGLERROR
501                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);CHECKGLERROR
502                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
503                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_TEXTURE);CHECKGLERROR // for GL_INTERPOLATE_ARB mode
504                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
505                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
506                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB_ARB, GL_SRC_ALPHA);CHECKGLERROR
507                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);CHECKGLERROR
508                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE);CHECKGLERROR
509                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
510                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA_ARB, GL_CONSTANT_ARB);CHECKGLERROR
511                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
512                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
513                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
514                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
515                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
516                 }
517                 else
518                 {
519                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
520                 }
521         }
522         CHECKGLERROR
523 }
524
525 void GL_Backend_ResetState(void)
526 {
527         memset(&gl_state, 0, sizeof(gl_state));
528         gl_state.depthtest = true;
529         gl_state.blendfunc1 = GL_ONE;
530         gl_state.blendfunc2 = GL_ZERO;
531         gl_state.blend = false;
532         gl_state.depthmask = GL_TRUE;
533         gl_state.colormask = 15;
534         gl_state.color4f[0] = gl_state.color4f[1] = gl_state.color4f[2] = gl_state.color4f[3] = 1;
535         gl_state.lockrange_first = 0;
536         gl_state.lockrange_count = 0;
537         gl_state.pointer_vertex = NULL;
538         gl_state.pointer_color = NULL;
539
540         CHECKGLERROR
541
542         qglColorMask(1, 1, 1, 1);
543         qglEnable(GL_CULL_FACE);CHECKGLERROR
544         qglCullFace(GL_FRONT);CHECKGLERROR
545         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
546         qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
547         qglDisable(GL_BLEND);CHECKGLERROR
548         qglDepthMask(gl_state.depthmask);CHECKGLERROR
549
550         qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), NULL);CHECKGLERROR
551         qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
552
553         qglColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL);CHECKGLERROR
554         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
555
556         GL_Color(0, 0, 0, 0);
557         GL_Color(1, 1, 1, 1);
558
559         GL_SetupTextureState();
560 }
561
562 void GL_ActiveTexture(unsigned int num)
563 {
564         if (gl_state.unit != num)
565         {
566                 gl_state.unit = num;
567                 if (qglActiveTexture)
568                 {
569                         qglActiveTexture(GL_TEXTURE0_ARB + gl_state.unit);
570                         CHECKGLERROR
571                 }
572         }
573 }
574
575 void GL_ClientActiveTexture(unsigned int num)
576 {
577         if (gl_state.clientunit != num)
578         {
579                 gl_state.clientunit = num;
580                 if (qglActiveTexture)
581                 {
582                         qglClientActiveTexture(GL_TEXTURE0_ARB + gl_state.clientunit);
583                         CHECKGLERROR
584                 }
585         }
586 }
587
588 void GL_BlendFunc(int blendfunc1, int blendfunc2)
589 {
590         if (gl_state.blendfunc1 != blendfunc1 || gl_state.blendfunc2 != blendfunc2)
591         {
592                 if (r_showtrispass)
593                         return;
594                 qglBlendFunc(gl_state.blendfunc1 = blendfunc1, gl_state.blendfunc2 = blendfunc2);CHECKGLERROR
595                 if (gl_state.blendfunc2 == GL_ZERO)
596                 {
597                         if (gl_state.blendfunc1 == GL_ONE)
598                         {
599                                 if (gl_state.blend)
600                                 {
601                                         gl_state.blend = 0;
602                                         qglDisable(GL_BLEND);CHECKGLERROR
603                                 }
604                         }
605                         else
606                         {
607                                 if (!gl_state.blend)
608                                 {
609                                         gl_state.blend = 1;
610                                         qglEnable(GL_BLEND);CHECKGLERROR
611                                 }
612                         }
613                 }
614                 else
615                 {
616                         if (!gl_state.blend)
617                         {
618                                 gl_state.blend = 1;
619                                 qglEnable(GL_BLEND);CHECKGLERROR
620                         }
621                 }
622         }
623 }
624
625 void GL_DepthMask(int state)
626 {
627         if (gl_state.depthmask != state)
628         {
629                 if (r_showtrispass)
630                         return;
631                 qglDepthMask(gl_state.depthmask = state);CHECKGLERROR
632         }
633 }
634
635 void GL_DepthTest(int state)
636 {
637         if (gl_state.depthtest != state)
638         {
639                 if (r_showtrispass)
640                         return;
641                 gl_state.depthtest = state;
642                 if (gl_state.depthtest)
643                 {
644                         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
645                 }
646                 else
647                 {
648                         qglDisable(GL_DEPTH_TEST);CHECKGLERROR
649                 }
650         }
651 }
652
653 void GL_ColorMask(int r, int g, int b, int a)
654 {
655         int state = r*8 + g*4 + b*2 + a*1;
656         if (gl_state.colormask != state)
657         {
658                 if (r_showtrispass)
659                         return;
660                 gl_state.colormask = state;
661                 qglColorMask((GLboolean)r, (GLboolean)g, (GLboolean)b, (GLboolean)a);CHECKGLERROR
662         }
663 }
664
665 void GL_Color(float cr, float cg, float cb, float ca)
666 {
667         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)
668         {
669                 if (r_showtrispass)
670                         return;
671                 gl_state.color4f[0] = cr;
672                 gl_state.color4f[1] = cg;
673                 gl_state.color4f[2] = cb;
674                 gl_state.color4f[3] = ca;
675                 CHECKGLERROR
676                 qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);
677                 CHECKGLERROR
678         }
679 }
680
681 void GL_ShowTrisColor(float cr, float cg, float cb, float ca)
682 {
683         if (!r_showtrispass)
684                 return;
685         r_showtrispass = false;
686         GL_Color(cr * r_showtris.value, cg * r_showtris.value, cb * r_showtris.value, ca);
687         r_showtrispass = true;
688 }
689
690
691 void GL_LockArrays(int first, int count)
692 {
693         if (gl_state.lockrange_count != count || gl_state.lockrange_first != first)
694         {
695                 if (gl_state.lockrange_count)
696                 {
697                         gl_state.lockrange_count = 0;
698                         CHECKGLERROR
699                         qglUnlockArraysEXT();
700                         CHECKGLERROR
701                 }
702                 if (count && gl_supportslockarrays && gl_lockarrays.integer && r_render.integer)
703                 {
704                         gl_state.lockrange_first = first;
705                         gl_state.lockrange_count = count;
706                         CHECKGLERROR
707                         qglLockArraysEXT(first, count);
708                         CHECKGLERROR
709                 }
710         }
711 }
712
713 void GL_Scissor (int x, int y, int width, int height)
714 {
715         CHECKGLERROR
716         qglScissor(x, vid.realheight - (y + height),width,height);
717         CHECKGLERROR
718 }
719
720 void GL_ScissorTest(int state)
721 {
722         if(gl_state.scissortest == state)
723                 return;
724
725         CHECKGLERROR
726         if((gl_state.scissortest = state))
727                 qglEnable(GL_SCISSOR_TEST);
728         else
729                 qglDisable(GL_SCISSOR_TEST);
730         CHECKGLERROR
731 }
732
733 void GL_Clear(int mask)
734 {
735         if (r_showtrispass)
736                 return;
737         qglClear(mask);CHECKGLERROR
738 }
739
740 void GL_TransformToScreen(const vec4_t in, vec4_t out)
741 {
742         vec4_t temp;
743         float iw;
744         Matrix4x4_Transform4 (&backend_viewmatrix, in, temp);
745         Matrix4x4_Transform4 (&backend_projectmatrix, temp, out);
746         iw = 1.0f / out[3];
747         out[0] = r_view_x + (out[0] * iw + 1.0f) * r_view_width * 0.5f;
748         out[1] = r_view_y + (out[1] * iw + 1.0f) * r_view_height * 0.5f;
749         out[2] = r_view_z + (out[2] * iw + 1.0f) * r_view_depth * 0.5f;
750 }
751
752 // called at beginning of frame
753 void R_Mesh_Start(void)
754 {
755         BACKENDACTIVECHECK
756         CHECKGLERROR
757         GL_Backend_ResetState();
758 }
759
760 unsigned int GL_Backend_CompileProgram(int vertexstrings_count, const char **vertexstrings_list, int fragmentstrings_count, const char **fragmentstrings_list)
761 {
762         GLint vertexshadercompiled, fragmentshadercompiled, programlinked;
763         GLuint vertexshaderobject, fragmentshaderobject, programobject = 0;
764         char compilelog[4096];
765         CHECKGLERROR
766
767         programobject = qglCreateProgramObjectARB();
768         CHECKGLERROR
769         if (!programobject)
770                 return 0;
771
772         if (vertexstrings_count)
773         {
774                 CHECKGLERROR
775                 vertexshaderobject = qglCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
776                 if (!vertexshaderobject)
777                 {
778                         qglDeleteObjectARB(programobject);
779                         CHECKGLERROR
780                         return 0;
781                 }
782                 qglShaderSourceARB(vertexshaderobject, vertexstrings_count, vertexstrings_list, NULL);
783                 qglCompileShaderARB(vertexshaderobject);
784                 CHECKGLERROR
785                 qglGetObjectParameterivARB(vertexshaderobject, GL_OBJECT_COMPILE_STATUS_ARB, &vertexshadercompiled);
786                 qglGetInfoLogARB(vertexshaderobject, sizeof(compilelog), NULL, compilelog);
787                 if (compilelog[0])
788                         Con_Printf("vertex shader compile log:\n%s\n", compilelog);
789                 if (!vertexshadercompiled)
790                 {
791                         qglDeleteObjectARB(programobject);
792                         qglDeleteObjectARB(vertexshaderobject);
793                         CHECKGLERROR
794                         return 0;
795                 }
796                 qglAttachObjectARB(programobject, vertexshaderobject);
797                 qglDeleteObjectARB(vertexshaderobject);
798                 CHECKGLERROR
799         }
800
801         if (fragmentstrings_count)
802         {
803                 CHECKGLERROR
804                 fragmentshaderobject = qglCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
805                 if (!fragmentshaderobject)
806                 {
807                         qglDeleteObjectARB(programobject);
808                         CHECKGLERROR
809                         return 0;
810                 }
811                 qglShaderSourceARB(fragmentshaderobject, fragmentstrings_count, fragmentstrings_list, NULL);
812                 qglCompileShaderARB(fragmentshaderobject);
813                 CHECKGLERROR
814                 qglGetObjectParameterivARB(fragmentshaderobject, GL_OBJECT_COMPILE_STATUS_ARB, &fragmentshadercompiled);
815                 qglGetInfoLogARB(fragmentshaderobject, sizeof(compilelog), NULL, compilelog);
816                 if (compilelog[0])
817                         Con_Printf("fragment shader compile log:\n%s\n", compilelog);
818                 if (!fragmentshadercompiled)
819                 {
820                         qglDeleteObjectARB(programobject);
821                         qglDeleteObjectARB(fragmentshaderobject);
822                         CHECKGLERROR
823                         return 0;
824                 }
825                 qglAttachObjectARB(programobject, fragmentshaderobject);
826                 qglDeleteObjectARB(fragmentshaderobject);
827                 CHECKGLERROR
828         }
829
830         qglLinkProgramARB(programobject);
831         CHECKGLERROR
832         qglGetObjectParameterivARB(programobject, GL_OBJECT_LINK_STATUS_ARB, &programlinked);
833         qglGetInfoLogARB(programobject, sizeof(compilelog), NULL, compilelog);
834         if (compilelog[0])
835         {
836                 Con_Printf("program link log:\n%s\n", compilelog);
837                 // software vertex shader is ok but software fragment shader is WAY
838                 // too slow, fail program if so.
839                 // NOTE: this string might be ATI specific, but that's ok because the
840                 // ATI R300 chip (Radeon 9500-9800/X300) is the most likely to use a
841                 // software fragment shader due to low instruction and dependent
842                 // texture limits.
843                 if (strstr(compilelog, "fragment shader will run in software"))
844                         programlinked = false;
845         }
846         CHECKGLERROR
847         if (!programlinked)
848         {
849                 qglDeleteObjectARB(programobject);
850                 return 0;
851         }
852         CHECKGLERROR
853         return programobject;
854 }
855
856 void GL_Backend_FreeProgram(unsigned int prog)
857 {
858         CHECKGLERROR
859         qglDeleteObjectARB(prog);
860         CHECKGLERROR
861 }
862
863 int gl_backend_rebindtextures;
864
865 void GL_Backend_RenumberElements(int *out, int count, const int *in, int offset)
866 {
867         int i;
868         if (offset)
869         {
870                 for (i = 0;i < count;i++)
871                         *out++ = *in++ + offset;
872         }
873         else
874                 memcpy(out, in, sizeof(*out) * count);
875 }
876
877 // renders triangles using vertices from the active arrays
878 int paranoidblah = 0;
879 void R_Mesh_Draw(int firstvertex, int numvertices, int numtriangles, const int *elements)
880 {
881         unsigned int numelements = numtriangles * 3;
882         if (numvertices < 3 || numtriangles < 1)
883         {
884                 Con_Printf("R_Mesh_Draw(%d, %d, %d, %08p);\n", firstvertex, numvertices, numtriangles, elements);
885                 return;
886         }
887         //CHECKGLERROR
888         if (r_showtrispass)
889         {
890                 R_Mesh_Draw_ShowTris(firstvertex, numvertices, numtriangles, elements);
891                 return;
892         }
893         c_meshs++;
894         c_meshelements += numelements;
895         if (gl_paranoid.integer)
896         {
897                 unsigned int i, j, size;
898                 const int *p;
899                 if (!qglIsEnabled(GL_VERTEX_ARRAY))
900                         Con_Print("R_Mesh_Draw: vertex array not enabled\n");
901                 for (j = 0, size = numvertices * 3, p = gl_state.pointer_vertex + firstvertex * 3;j < size;j++, p++)
902                         paranoidblah += *p;
903                 if (gl_state.pointer_color)
904                 {
905                         if (!qglIsEnabled(GL_COLOR_ARRAY))
906                                 Con_Print("R_Mesh_Draw: color array set but not enabled\n");
907                         for (j = 0, size = numvertices * 4, p = gl_state.pointer_color + firstvertex * 4;j < size;j++, p++)
908                                 paranoidblah += *p;
909                 }
910                 for (i = 0;i < backendarrayunits;i++)
911                 {
912                         if (gl_state.units[i].arrayenabled)
913                         {
914                                 GL_ClientActiveTexture(i);
915                                 if (!qglIsEnabled(GL_TEXTURE_COORD_ARRAY))
916                                         Con_Print("R_Mesh_Draw: texcoord array set but not enabled\n");
917                                 for (j = 0, size = numvertices * gl_state.units[i].arraycomponents, p = gl_state.units[i].pointer_texcoord + firstvertex * gl_state.units[i].arraycomponents;j < size;j++, p++)
918                                         paranoidblah += *p;
919                         }
920                 }
921                 for (i = 0;i < (unsigned int) numtriangles * 3;i++)
922                 {
923                         if (elements[i] < firstvertex || elements[i] >= firstvertex + numvertices)
924                         {
925                                 Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range %i - %i) in elements list\n", elements[i], firstvertex, firstvertex + numvertices);
926                                 return;
927                         }
928                 }
929                 CHECKGLERROR
930         }
931         if (r_render.integer)
932         {
933                 CHECKGLERROR
934                 if (gl_mesh_testmanualfeeding.integer)
935                 {
936                         unsigned int i, j;
937                         const GLfloat *p;
938                         qglBegin(GL_TRIANGLES);
939                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
940                         {
941                                 for (j = 0;j < backendarrayunits;j++)
942                                 {
943                                         if (gl_state.units[j].pointer_texcoord)
944                                         {
945                                                 if (backendarrayunits > 1)
946                                                 {
947                                                         if (gl_state.units[j].arraycomponents == 4)
948                                                         {
949                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 4;
950                                                                 qglMultiTexCoord4f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2], p[3]);
951                                                         }
952                                                         else if (gl_state.units[j].arraycomponents == 3)
953                                                         {
954                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
955                                                                 qglMultiTexCoord3f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2]);
956                                                         }
957                                                         else if (gl_state.units[j].arraycomponents == 2)
958                                                         {
959                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
960                                                                 qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, p[0], p[1]);
961                                                         }
962                                                         else
963                                                         {
964                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 1;
965                                                                 qglMultiTexCoord1f(GL_TEXTURE0_ARB + j, p[0]);
966                                                         }
967                                                 }
968                                                 else
969                                                 {
970                                                         if (gl_state.units[j].arraycomponents == 4)
971                                                         {
972                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 4;
973                                                                 qglTexCoord4f(p[0], p[1], p[2], p[3]);
974                                                         }
975                                                         else if (gl_state.units[j].arraycomponents == 3)
976                                                         {
977                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
978                                                                 qglTexCoord3f(p[0], p[1], p[2]);
979                                                         }
980                                                         else if (gl_state.units[j].arraycomponents == 2)
981                                                         {
982                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
983                                                                 qglTexCoord2f(p[0], p[1]);
984                                                         }
985                                                         else
986                                                         {
987                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 1;
988                                                                 qglTexCoord1f(p[0]);
989                                                         }
990                                                 }
991                                         }
992                                 }
993                                 if (gl_state.pointer_color)
994                                 {
995                                         p = ((const GLfloat *)(gl_state.pointer_color)) + elements[i] * 4;
996                                         qglColor4f(p[0], p[1], p[2], p[3]);
997                                 }
998                                 p = ((const GLfloat *)(gl_state.pointer_vertex)) + elements[i] * 3;
999                                 qglVertex3f(p[0], p[1], p[2]);
1000                         }
1001                         qglEnd();
1002                         CHECKGLERROR
1003                 }
1004                 else if (gl_mesh_testarrayelement.integer)
1005                 {
1006                         int i;
1007                         qglBegin(GL_TRIANGLES);
1008                         for (i = 0;i < numtriangles * 3;i++)
1009                         {
1010                                 qglArrayElement(elements[i]);
1011                         }
1012                         qglEnd();
1013                         CHECKGLERROR
1014                 }
1015                 else if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
1016                 {
1017                         qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices, numelements, GL_UNSIGNED_INT, elements);
1018                         CHECKGLERROR
1019                 }
1020                 else
1021                 {
1022                         qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, elements);
1023                         CHECKGLERROR
1024                 }
1025         }
1026 }
1027
1028 // restores backend state, used when done with 3D rendering
1029 void R_Mesh_Finish(void)
1030 {
1031         unsigned int i;
1032         BACKENDACTIVECHECK
1033         CHECKGLERROR
1034         GL_LockArrays(0, 0);
1035         CHECKGLERROR
1036
1037         for (i = 0;i < backendimageunits;i++)
1038         {
1039                 GL_ActiveTexture(i);
1040                 qglBindTexture(GL_TEXTURE_1D, 0);CHECKGLERROR
1041                 qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
1042                 if (gl_texture3d)
1043                 {
1044                         qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
1045                 }
1046                 if (gl_texturecubemap)
1047                 {
1048                         qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, 0);CHECKGLERROR
1049                 }
1050         }
1051         for (i = 0;i < backendarrayunits;i++)
1052         {
1053                 GL_ActiveTexture(backendarrayunits - 1 - i);
1054                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1055         }
1056         for (i = 0;i < backendunits;i++)
1057         {
1058                 GL_ActiveTexture(backendunits - 1 - i);
1059                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
1060                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1061                 if (gl_texture3d)
1062                 {
1063                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1064                 }
1065                 if (gl_texturecubemap)
1066                 {
1067                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1068                 }
1069                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
1070                 if (gl_combine.integer)
1071                 {
1072                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
1073                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
1074                 }
1075         }
1076         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
1077         qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
1078
1079         qglDisable(GL_BLEND);CHECKGLERROR
1080         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
1081         qglDepthMask(GL_TRUE);CHECKGLERROR
1082         qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
1083 }
1084
1085 void R_Mesh_Matrix(const matrix4x4_t *matrix)
1086 {
1087         if (memcmp(matrix, &backend_modelmatrix, sizeof(matrix4x4_t)))
1088         {
1089                 backend_modelmatrix = *matrix;
1090                 Matrix4x4_Concat(&backend_modelviewmatrix, &backend_viewmatrix, matrix);
1091                 Matrix4x4_Transpose(&backend_glmodelviewmatrix, &backend_modelviewmatrix);
1092                 qglLoadMatrixf(&backend_glmodelviewmatrix.m[0][0]);
1093         }
1094 }
1095
1096 void R_Mesh_VertexPointer(const float *vertex3f)
1097 {
1098         if (gl_state.pointer_vertex != vertex3f)
1099         {
1100                 gl_state.pointer_vertex = vertex3f;
1101                 CHECKGLERROR
1102                 qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), gl_state.pointer_vertex);
1103                 CHECKGLERROR
1104         }
1105 }
1106
1107 void R_Mesh_ColorPointer(const float *color4f)
1108 {
1109         if (gl_state.pointer_color != color4f)
1110         {
1111                 CHECKGLERROR
1112                 if (!gl_state.pointer_color)
1113                 {
1114                         qglEnableClientState(GL_COLOR_ARRAY);
1115                         CHECKGLERROR
1116                 }
1117                 else if (!color4f)
1118                 {
1119                         qglDisableClientState(GL_COLOR_ARRAY);
1120                         CHECKGLERROR
1121                         // when color array is on the glColor gets trashed, set it again
1122                         qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);
1123                         CHECKGLERROR
1124                 }
1125                 gl_state.pointer_color = color4f;
1126                 qglColorPointer(4, GL_FLOAT, sizeof(float[4]), gl_state.pointer_color);
1127                 CHECKGLERROR
1128         }
1129 }
1130
1131 void R_Mesh_TexCoordPointer(unsigned int unitnum, unsigned int numcomponents, const float *texcoord)
1132 {
1133         gltextureunit_t *unit = gl_state.units + unitnum;
1134         // update array settings
1135         if (texcoord)
1136         {
1137                 // texcoord array
1138                 if (unit->pointer_texcoord != texcoord || unit->arraycomponents != numcomponents)
1139                 {
1140                         unit->pointer_texcoord = texcoord;
1141                         unit->arraycomponents = numcomponents;
1142                         GL_ClientActiveTexture(unitnum);
1143                         qglTexCoordPointer(unit->arraycomponents, GL_FLOAT, sizeof(float) * unit->arraycomponents, unit->pointer_texcoord);
1144                         CHECKGLERROR
1145                 }
1146                 // texture array unit is enabled, enable the array
1147                 if (!unit->arrayenabled)
1148                 {
1149                         unit->arrayenabled = true;
1150                         GL_ClientActiveTexture(unitnum);
1151                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1152                 }
1153         }
1154         else
1155         {
1156                 // texture array unit is disabled, disable the array
1157                 if (unit->arrayenabled)
1158                 {
1159                         unit->arrayenabled = false;
1160                         GL_ClientActiveTexture(unitnum);
1161                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1162                 }
1163         }
1164 }
1165
1166 void R_Mesh_TexBindAll(unsigned int unitnum, int tex1d, int tex2d, int tex3d, int texcubemap)
1167 {
1168         gltextureunit_t *unit = gl_state.units + unitnum;
1169         if (unitnum >= backendunits)
1170                 return;
1171         // update 1d texture binding
1172         if (unit->t1d != tex1d)
1173         {
1174                 GL_ActiveTexture(unitnum);
1175                 if (unitnum < backendunits)
1176                 {
1177                         if (tex1d)
1178                         {
1179                                 if (unit->t1d == 0)
1180                                         qglEnable(GL_TEXTURE_1D);
1181                         }
1182                         else
1183                         {
1184                                 if (unit->t1d)
1185                                         qglDisable(GL_TEXTURE_1D);
1186                         }
1187                 }
1188                 unit->t1d = tex1d;
1189                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);
1190                 CHECKGLERROR
1191         }
1192         // update 2d texture binding
1193         if (unit->t2d != tex2d)
1194         {
1195                 GL_ActiveTexture(unitnum);
1196                 if (unitnum < backendunits)
1197                 {
1198                         if (tex2d)
1199                         {
1200                                 if (unit->t2d == 0)
1201                                         qglEnable(GL_TEXTURE_2D);
1202                         }
1203                         else
1204                         {
1205                                 if (unit->t2d)
1206                                         qglDisable(GL_TEXTURE_2D);
1207                         }
1208                 }
1209                 unit->t2d = tex2d;
1210                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);
1211                 CHECKGLERROR
1212         }
1213         // update 3d texture binding
1214         if (unit->t3d != tex3d)
1215         {
1216                 GL_ActiveTexture(unitnum);
1217                 if (unitnum < backendunits)
1218                 {
1219                         if (tex3d)
1220                         {
1221                                 if (unit->t3d == 0)
1222                                         qglEnable(GL_TEXTURE_3D);
1223                         }
1224                         else
1225                         {
1226                                 if (unit->t3d)
1227                                         qglDisable(GL_TEXTURE_3D);
1228                         }
1229                 }
1230                 unit->t3d = tex3d;
1231                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);
1232                 CHECKGLERROR
1233         }
1234         // update cubemap texture binding
1235         if (unit->tcubemap != texcubemap)
1236         {
1237                 GL_ActiveTexture(unitnum);
1238                 if (unitnum < backendunits)
1239                 {
1240                         if (texcubemap)
1241                         {
1242                                 if (unit->tcubemap == 0)
1243                                         qglEnable(GL_TEXTURE_CUBE_MAP_ARB);
1244                         }
1245                         else
1246                         {
1247                                 if (unit->tcubemap)
1248                                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
1249                         }
1250                 }
1251                 unit->tcubemap = texcubemap;
1252                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
1253                 CHECKGLERROR
1254         }
1255 }
1256
1257 void R_Mesh_TexBind1D(unsigned int unitnum, int texnum)
1258 {
1259         gltextureunit_t *unit = gl_state.units + unitnum;
1260         if (unitnum >= backendunits)
1261                 return;
1262         // update 1d texture binding
1263         if (unit->t1d != texnum)
1264         {
1265                 GL_ActiveTexture(unitnum);
1266                 if (texnum)
1267                 {
1268                         if (unit->t1d == 0)
1269                                 qglEnable(GL_TEXTURE_1D);
1270                 }
1271                 else
1272                 {
1273                         if (unit->t1d)
1274                                 qglDisable(GL_TEXTURE_1D);
1275                 }
1276                 unit->t1d = texnum;
1277                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);
1278                 CHECKGLERROR
1279         }
1280         // update 2d texture binding
1281         if (unit->t2d)
1282         {
1283                 GL_ActiveTexture(unitnum);
1284                 if (unit->t2d)
1285                         qglDisable(GL_TEXTURE_2D);
1286                 unit->t2d = 0;
1287                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);
1288                 CHECKGLERROR
1289         }
1290         // update 3d texture binding
1291         if (unit->t3d)
1292         {
1293                 GL_ActiveTexture(unitnum);
1294                 if (unit->t3d)
1295                         qglDisable(GL_TEXTURE_3D);
1296                 unit->t3d = 0;
1297                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);
1298                 CHECKGLERROR
1299         }
1300         // update cubemap texture binding
1301         if (unit->tcubemap)
1302         {
1303                 GL_ActiveTexture(unitnum);
1304                 if (unit->tcubemap)
1305                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
1306                 unit->tcubemap = 0;
1307                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
1308                 CHECKGLERROR
1309         }
1310 }
1311
1312 void R_Mesh_TexBind(unsigned int unitnum, int texnum)
1313 {
1314         gltextureunit_t *unit = gl_state.units + unitnum;
1315         if (unitnum >= backendunits)
1316                 return;
1317         // update 1d texture binding
1318         if (unit->t1d)
1319         {
1320                 GL_ActiveTexture(unitnum);
1321                 if (unit->t1d)
1322                         qglDisable(GL_TEXTURE_1D);
1323                 unit->t1d = 0;
1324                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);
1325                 CHECKGLERROR
1326         }
1327         // update 2d texture binding
1328         if (unit->t2d != texnum)
1329         {
1330                 GL_ActiveTexture(unitnum);
1331                 if (texnum)
1332                 {
1333                         if (unit->t2d == 0)
1334                                 qglEnable(GL_TEXTURE_2D);
1335                 }
1336                 else
1337                 {
1338                         if (unit->t2d)
1339                                 qglDisable(GL_TEXTURE_2D);
1340                 }
1341                 unit->t2d = texnum;
1342                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);
1343                 CHECKGLERROR
1344         }
1345         // update 3d texture binding
1346         if (unit->t3d)
1347         {
1348                 GL_ActiveTexture(unitnum);
1349                 if (unit->t3d)
1350                         qglDisable(GL_TEXTURE_3D);
1351                 unit->t3d = 0;
1352                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);
1353                 CHECKGLERROR
1354         }
1355         // update cubemap texture binding
1356         if (unit->tcubemap != 0)
1357         {
1358                 GL_ActiveTexture(unitnum);
1359                 if (unit->tcubemap)
1360                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
1361                 unit->tcubemap = 0;
1362                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
1363                 CHECKGLERROR
1364         }
1365 }
1366
1367 void R_Mesh_TexBind3D(unsigned int unitnum, int texnum)
1368 {
1369         gltextureunit_t *unit = gl_state.units + unitnum;
1370         if (unitnum >= backendunits)
1371                 return;
1372         // update 1d texture binding
1373         if (unit->t1d)
1374         {
1375                 GL_ActiveTexture(unitnum);
1376                 if (unit->t1d)
1377                         qglDisable(GL_TEXTURE_1D);
1378                 unit->t1d = 0;
1379                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);
1380                 CHECKGLERROR
1381         }
1382         // update 2d texture binding
1383         if (unit->t2d)
1384         {
1385                 GL_ActiveTexture(unitnum);
1386                 if (unit->t2d)
1387                         qglDisable(GL_TEXTURE_2D);
1388                 unit->t2d = 0;
1389                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);
1390                 CHECKGLERROR
1391         }
1392         // update 3d texture binding
1393         if (unit->t3d != texnum)
1394         {
1395                 GL_ActiveTexture(unitnum);
1396                 if (texnum)
1397                 {
1398                         if (unit->t3d == 0)
1399                                 qglEnable(GL_TEXTURE_3D);
1400                 }
1401                 else
1402                 {
1403                         if (unit->t3d)
1404                                 qglDisable(GL_TEXTURE_3D);
1405                 }
1406                 unit->t3d = texnum;
1407                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);
1408                 CHECKGLERROR
1409         }
1410         // update cubemap texture binding
1411         if (unit->tcubemap != 0)
1412         {
1413                 GL_ActiveTexture(unitnum);
1414                 if (unit->tcubemap)
1415                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
1416                 unit->tcubemap = 0;
1417                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
1418                 CHECKGLERROR
1419         }
1420 }
1421
1422 void R_Mesh_TexBindCubeMap(unsigned int unitnum, int texnum)
1423 {
1424         gltextureunit_t *unit = gl_state.units + unitnum;
1425         if (unitnum >= backendunits)
1426                 return;
1427         // update 1d texture binding
1428         if (unit->t1d)
1429         {
1430                 GL_ActiveTexture(unitnum);
1431                 if (unit->t1d)
1432                         qglDisable(GL_TEXTURE_1D);
1433                 unit->t1d = 0;
1434                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);
1435                 CHECKGLERROR
1436         }
1437         // update 2d texture binding
1438         if (unit->t2d)
1439         {
1440                 GL_ActiveTexture(unitnum);
1441                 if (unit->t2d)
1442                         qglDisable(GL_TEXTURE_2D);
1443                 unit->t2d = 0;
1444                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);
1445                 CHECKGLERROR
1446         }
1447         // update 3d texture binding
1448         if (unit->t3d)
1449         {
1450                 GL_ActiveTexture(unitnum);
1451                 if (unit->t3d)
1452                         qglDisable(GL_TEXTURE_3D);
1453                 unit->t3d = 0;
1454                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);
1455                 CHECKGLERROR
1456         }
1457         // update cubemap texture binding
1458         if (unit->tcubemap != texnum)
1459         {
1460                 GL_ActiveTexture(unitnum);
1461                 if (texnum)
1462                 {
1463                         if (unit->tcubemap == 0)
1464                                 qglEnable(GL_TEXTURE_CUBE_MAP_ARB);
1465                 }
1466                 else
1467                 {
1468                         if (unit->tcubemap)
1469                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
1470                 }
1471                 unit->tcubemap = texnum;
1472                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
1473                 CHECKGLERROR
1474         }
1475 }
1476
1477 void R_Mesh_TexMatrix(unsigned int unitnum, const matrix4x4_t *matrix)
1478 {
1479         gltextureunit_t *unit = gl_state.units + unitnum;
1480         if (matrix->m[3][3])
1481         {
1482                 // texmatrix specified, check if it is different
1483                 if (!unit->texmatrixenabled || memcmp(&unit->matrix, matrix, sizeof(matrix4x4_t)))
1484                 {
1485                         matrix4x4_t tempmatrix;
1486                         unit->texmatrixenabled = true;
1487                         unit->matrix = *matrix;
1488                         Matrix4x4_Transpose(&tempmatrix, &unit->matrix);
1489                         qglMatrixMode(GL_TEXTURE);
1490                         GL_ActiveTexture(unitnum);
1491                         qglLoadMatrixf(&tempmatrix.m[0][0]);
1492                         qglMatrixMode(GL_MODELVIEW);
1493                 }
1494         }
1495         else
1496         {
1497                 // no texmatrix specified, revert to identity
1498                 if (unit->texmatrixenabled)
1499                 {
1500                         unit->texmatrixenabled = false;
1501                         qglMatrixMode(GL_TEXTURE);
1502                         GL_ActiveTexture(unitnum);
1503                         qglLoadIdentity();
1504                         qglMatrixMode(GL_MODELVIEW);
1505                 }
1506         }
1507 }
1508
1509 void R_Mesh_TexCombine(unsigned int unitnum, int combinergb, int combinealpha, int rgbscale, int alphascale)
1510 {
1511         gltextureunit_t *unit = gl_state.units + unitnum;
1512         if (gl_combine.integer)
1513         {
1514                 // GL_ARB_texture_env_combine
1515                 if (!combinergb)
1516                         combinergb = GL_MODULATE;
1517                 if (!combinealpha)
1518                         combinealpha = GL_MODULATE;
1519                 if (!rgbscale)
1520                         rgbscale = 1;
1521                 if (!alphascale)
1522                         alphascale = 1;
1523                 if (unit->combinergb != combinergb)
1524                 {
1525                         unit->combinergb = combinergb;
1526                         GL_ActiveTexture(unitnum);
1527                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
1528                 }
1529                 if (unit->combinealpha != combinealpha)
1530                 {
1531                         unit->combinealpha = combinealpha;
1532                         GL_ActiveTexture(unitnum);
1533                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
1534                 }
1535                 if (unit->rgbscale != rgbscale)
1536                 {
1537                         GL_ActiveTexture(unitnum);
1538                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (unit->rgbscale = rgbscale));CHECKGLERROR
1539                 }
1540                 if (unit->alphascale != alphascale)
1541                 {
1542                         GL_ActiveTexture(unitnum);
1543                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (unit->alphascale = alphascale));CHECKGLERROR
1544                 }
1545         }
1546         else
1547         {
1548                 // normal GL texenv
1549                 if (!combinergb)
1550                         combinergb = GL_MODULATE;
1551                 if (unit->combinergb != combinergb)
1552                 {
1553                         unit->combinergb = combinergb;
1554                         GL_ActiveTexture(unitnum);
1555                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
1556                 }
1557         }
1558 }
1559
1560 void R_Mesh_State(const rmeshstate_t *m)
1561 {
1562         unsigned int i;
1563
1564         BACKENDACTIVECHECK
1565
1566         R_Mesh_VertexPointer(m->pointer_vertex);
1567
1568         if (r_showtrispass)
1569                 return;
1570
1571         R_Mesh_ColorPointer(m->pointer_color);
1572
1573         if (gl_backend_rebindtextures)
1574         {
1575                 gl_backend_rebindtextures = false;
1576                 GL_SetupTextureState();
1577         }
1578
1579         for (i = 0;i < backendimageunits;i++)
1580                 R_Mesh_TexBindAll(i, m->tex1d[i], m->tex[i], m->tex3d[i], m->texcubemap[i]);
1581         for (i = 0;i < backendarrayunits;i++)
1582         {
1583                 if (m->pointer_texcoord3f[i])
1584                         R_Mesh_TexCoordPointer(i, 3, m->pointer_texcoord3f[i]);
1585                 else
1586                         R_Mesh_TexCoordPointer(i, 2, m->pointer_texcoord[i]);
1587         }
1588         for (i = 0;i < backendunits;i++)
1589         {
1590                 R_Mesh_TexMatrix(i, &m->texmatrix[i]);
1591                 R_Mesh_TexCombine(i, m->texcombinergb[i], m->texcombinealpha[i], m->texrgbscale[i], m->texalphascale[i]);
1592         }
1593 }
1594
1595 void R_Mesh_Draw_ShowTris(int firstvertex, int numvertices, int numtriangles, const int *elements)
1596 {
1597         qglBegin(GL_LINES);
1598         for (;numtriangles;numtriangles--, elements += 3)
1599         {
1600                 qglArrayElement(elements[0]);qglArrayElement(elements[1]);
1601                 qglArrayElement(elements[1]);qglArrayElement(elements[2]);
1602                 qglArrayElement(elements[2]);qglArrayElement(elements[0]);
1603         }
1604         qglEnd();
1605         CHECKGLERROR
1606 }
1607
1608 /*
1609 ==============================================================================
1610
1611                                                 SCREEN SHOTS
1612
1613 ==============================================================================
1614 */
1615
1616 qboolean SCR_ScreenShot(char *filename, qbyte *buffer1, qbyte *buffer2, qbyte *buffer3, int x, int y, int width, int height, qboolean flipx, qboolean flipy, qboolean flipdiagonal, qboolean jpeg)
1617 {
1618         int     indices[3] = {0,1,2};
1619         qboolean ret;
1620
1621         if (!r_render.integer)
1622                 return false;
1623
1624         qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer1);
1625         CHECKGLERROR
1626
1627         if (scr_screenshot_gamma.value != 1)
1628         {
1629                 int i;
1630                 double igamma = 1.0 / scr_screenshot_gamma.value;
1631                 unsigned char ramp[256];
1632                 for (i = 0;i < 256;i++)
1633                         ramp[i] = (unsigned char) (pow(i * (1.0 / 255.0), igamma) * 255.0);
1634                 for (i = 0;i < width*height*3;i++)
1635                         buffer1[i] = ramp[buffer1[i]];
1636         }
1637
1638         Image_CopyMux (buffer2, buffer1, width, height, flipx, flipy, flipdiagonal, 3, 3, indices);
1639
1640         if (jpeg)
1641                 ret = JPEG_SaveImage_preflipped (filename, width, height, buffer2);
1642         else
1643                 ret = Image_WriteTGARGB_preflipped (filename, width, height, buffer2, buffer3);
1644
1645         return ret;
1646 }
1647
1648 //=============================================================================
1649
1650 void R_ClearScreen(void)
1651 {
1652         if (r_render.integer)
1653         {
1654                 // clear to black
1655                 qglClearColor(0,0,0,0);CHECKGLERROR
1656                 qglClearDepth(1);CHECKGLERROR
1657                 if (gl_stencil)
1658                 {
1659                         // LordHavoc: we use a stencil centered around 128 instead of 0,
1660                         // to avoid clamping interfering with strange shadow volume
1661                         // drawing orders
1662                         qglClearStencil(128);CHECKGLERROR
1663                 }
1664                 // clear the screen
1665                 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (gl_stencil ? GL_STENCIL_BUFFER_BIT : 0));
1666                 // set dithering mode
1667                 if (gl_dither.integer)
1668                 {
1669                         qglEnable(GL_DITHER);CHECKGLERROR
1670                 }
1671                 else
1672                 {
1673                         qglDisable(GL_DITHER);CHECKGLERROR
1674                 }
1675         }
1676 }
1677
1678 /*
1679 ====================
1680 CalcFov
1681 ====================
1682 */
1683 float CalcFov (float fov_x, float width, float height)
1684 {
1685         // calculate vision size and alter by aspect, then convert back to angle
1686         return atan (((height/width)/vid_pixelaspect.value)*tan(fov_x/360.0*M_PI))*360.0/M_PI;
1687 }
1688
1689 int r_stereo_side;
1690
1691 void SCR_DrawScreen (void)
1692 {
1693         for (r_showtrispass = 0;r_showtrispass <= (r_showtris.value > 0);r_showtrispass++)
1694         {
1695                 R_Mesh_Start();
1696
1697                 R_TimeReport("setup");
1698
1699                 if (r_showtrispass)
1700                 {
1701                         rmeshstate_t m;
1702                         r_showtrispass = 0;
1703                         GL_BlendFunc(GL_ONE, GL_ONE);
1704                         GL_DepthTest(GL_FALSE);
1705                         GL_DepthMask(GL_FALSE);
1706                         memset(&m, 0, sizeof(m));
1707                         R_Mesh_State(&m);
1708                         GL_ShowTrisColor(0.2,0.2,0.2,1);
1709                         r_showtrispass = 1;
1710                 }
1711
1712                 if (cls.signon == SIGNONS)
1713                 {
1714                         float size;
1715
1716                         size = scr_viewsize.value * (1.0 / 100.0);
1717                         size = min(size, 1);
1718
1719                         if (r_stereo_sidebyside.integer)
1720                         {
1721                                 r_refdef.width = vid.realwidth * size / 2.5;
1722                                 r_refdef.height = vid.realheight * size / 2.5 * (1 - bound(0, r_letterbox.value, 100) / 100);
1723                                 r_refdef.x = (vid.realwidth - r_refdef.width * 2.5) * 0.5;
1724                                 r_refdef.y = (vid.realheight - r_refdef.height)/2;
1725                                 if (r_stereo_side)
1726                                         r_refdef.x += r_refdef.width * 1.5;
1727                         }
1728                         else
1729                         {
1730                                 r_refdef.width = vid.realwidth * size;
1731                                 r_refdef.height = vid.realheight * size * (1 - bound(0, r_letterbox.value, 100) / 100);
1732                                 r_refdef.x = (vid.realwidth - r_refdef.width)/2;
1733                                 r_refdef.y = (vid.realheight - r_refdef.height)/2;
1734                         }
1735
1736                         // LordHavoc: viewzoom (zoom in for sniper rifles, etc)
1737                         r_refdef.fov_x = scr_fov.value * r_refdef.fovscale_x;
1738                         r_refdef.fov_y = CalcFov (scr_fov.value, r_refdef.width, r_refdef.height) * r_refdef.fovscale_y;
1739
1740                         R_RenderView();
1741
1742                         if (scr_zoomwindow.integer)
1743                         {
1744                                 float sizex = bound(10, scr_zoomwindow_viewsizex.value, 100) / 100.0;
1745                                 float sizey = bound(10, scr_zoomwindow_viewsizey.value, 100) / 100.0;
1746                                 r_refdef.width = vid.realwidth * sizex;
1747                                 r_refdef.height = vid.realheight * sizey;
1748                                 r_refdef.x = (vid.realwidth - r_refdef.width)/2;
1749                                 r_refdef.y = 0;
1750                                 r_refdef.fov_x = scr_zoomwindow_fov.value * r_refdef.fovscale_x;
1751                                 r_refdef.fov_y = CalcFov(scr_zoomwindow_fov.value, r_refdef.width, r_refdef.height) * r_refdef.fovscale_y;
1752
1753                                 R_RenderView();
1754                         }
1755                 }
1756
1757                 if (!r_stereo_sidebyside.integer)
1758                 {
1759                         r_refdef.width = vid.realwidth;
1760                         r_refdef.height = vid.realheight;
1761                         r_refdef.x = 0;
1762                         r_refdef.y = 0;
1763                 }
1764
1765                 // draw 2D stuff
1766                 R_DrawQueue();
1767
1768                 R_Mesh_Finish();
1769
1770                 R_TimeReport("meshfinish");
1771         }
1772         r_showtrispass = 0;
1773 }
1774
1775 void SCR_UpdateLoadingScreen (void)
1776 {
1777         float x, y;
1778         cachepic_t *pic;
1779         rmeshstate_t m;
1780         // don't do anything if not initialized yet
1781         if (vid_hidden)
1782                 return;
1783         r_showtrispass = 0;
1784         VID_GetWindowSize(&vid.realx, &vid.realy, &vid.realwidth, &vid.realheight);
1785         VID_UpdateGamma(false);
1786         qglViewport(0, 0, vid.realwidth, vid.realheight);
1787         //qglDisable(GL_SCISSOR_TEST);
1788         //qglDepthMask(1);
1789         qglColorMask(1,1,1,1);
1790         //qglClearColor(0,0,0,0);
1791         //qglClear(GL_COLOR_BUFFER_BIT);
1792         //qglCullFace(GL_FRONT);
1793         //qglDisable(GL_CULL_FACE);
1794         //R_ClearScreen();
1795         R_Textures_Frame();
1796         GL_SetupView_Mode_Ortho(0, 0, vid_conwidth.integer, vid_conheight.integer, -10, 100);
1797         R_Mesh_Start();
1798         R_Mesh_Matrix(&r_identitymatrix);
1799         // draw the loading plaque
1800         pic = Draw_CachePic("gfx/loading.lmp");
1801         x = (vid_conwidth.integer - pic->width)/2;
1802         y = (vid_conheight.integer - pic->height)/2;
1803         GL_Color(1,1,1,1);
1804         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1805         GL_DepthTest(false);
1806         memset(&m, 0, sizeof(m));
1807         m.pointer_vertex = varray_vertex3f;
1808         m.pointer_texcoord[0] = varray_texcoord2f[0];
1809         m.tex[0] = R_GetTexture(pic->tex);
1810         R_Mesh_State(&m);
1811         varray_vertex3f[0] = varray_vertex3f[9] = x;
1812         varray_vertex3f[1] = varray_vertex3f[4] = y;
1813         varray_vertex3f[3] = varray_vertex3f[6] = x + pic->width;
1814         varray_vertex3f[7] = varray_vertex3f[10] = y + pic->height;
1815         varray_texcoord2f[0][0] = 0;varray_texcoord2f[0][1] = 0;
1816         varray_texcoord2f[0][2] = 1;varray_texcoord2f[0][3] = 0;
1817         varray_texcoord2f[0][4] = 1;varray_texcoord2f[0][5] = 1;
1818         varray_texcoord2f[0][6] = 0;varray_texcoord2f[0][7] = 1;
1819         GL_LockArrays(0, 4);
1820         R_Mesh_Draw(0, 4, 2, polygonelements);
1821         GL_LockArrays(0, 0);
1822         R_Mesh_Finish();
1823         // refresh
1824         VID_Finish();
1825 }
1826
1827 /*
1828 ==================
1829 SCR_UpdateScreen
1830
1831 This is called every frame, and can also be called explicitly to flush
1832 text to the screen.
1833 ==================
1834 */
1835 void SCR_UpdateScreen (void)
1836 {
1837         if (vid_hidden)
1838                 return;
1839
1840         if (r_textureunits.integer > gl_textureunits)
1841                 Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
1842         if (r_textureunits.integer < 1)
1843                 Cvar_SetValueQuick(&r_textureunits, 1);
1844
1845         if (gl_combine.integer && (!gl_combine_extension || r_textureunits.integer < 2))
1846                 Cvar_SetValueQuick(&gl_combine, 0);
1847
1848         CHECKGLERROR
1849         qglViewport(0, 0, vid.realwidth, vid.realheight);
1850         qglDisable(GL_SCISSOR_TEST);
1851         qglDepthMask(1);
1852         qglColorMask(1,1,1,1);
1853         qglClearColor(0,0,0,0);
1854         qglClear(GL_COLOR_BUFFER_BIT);
1855         CHECKGLERROR
1856
1857         R_TimeReport("clear");
1858
1859         if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer || r_stereo_sidebyside.integer)
1860         {
1861                 matrix4x4_t originalmatrix = r_refdef.viewentitymatrix;
1862                 r_refdef.viewentitymatrix.m[0][3] = originalmatrix.m[0][3] + r_stereo_separation.value * -0.5f * r_refdef.viewentitymatrix.m[0][1];
1863                 r_refdef.viewentitymatrix.m[1][3] = originalmatrix.m[1][3] + r_stereo_separation.value * -0.5f * r_refdef.viewentitymatrix.m[1][1];
1864                 r_refdef.viewentitymatrix.m[2][3] = originalmatrix.m[2][3] + r_stereo_separation.value * -0.5f * r_refdef.viewentitymatrix.m[2][1];
1865
1866                 if (r_stereo_sidebyside.integer)
1867                         r_stereo_side = 0;
1868
1869                 if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer)
1870                 {
1871                         r_refdef.colormask[0] = 1;
1872                         r_refdef.colormask[1] = 0;
1873                         r_refdef.colormask[2] = 0;
1874                 }
1875
1876                 SCR_DrawScreen();
1877
1878                 r_refdef.viewentitymatrix.m[0][3] = originalmatrix.m[0][3] + r_stereo_separation.value * 0.5f * r_refdef.viewentitymatrix.m[0][1];
1879                 r_refdef.viewentitymatrix.m[1][3] = originalmatrix.m[1][3] + r_stereo_separation.value * 0.5f * r_refdef.viewentitymatrix.m[1][1];
1880                 r_refdef.viewentitymatrix.m[2][3] = originalmatrix.m[2][3] + r_stereo_separation.value * 0.5f * r_refdef.viewentitymatrix.m[2][1];
1881
1882                 if (r_stereo_sidebyside.integer)
1883                         r_stereo_side = 1;
1884
1885                 if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer)
1886                 {
1887                         r_refdef.colormask[0] = 0;
1888                         r_refdef.colormask[1] = r_stereo_redcyan.integer || r_stereo_redgreen.integer;
1889                         r_refdef.colormask[2] = r_stereo_redcyan.integer || r_stereo_redblue.integer;
1890                 }
1891
1892                 SCR_DrawScreen();
1893
1894                 r_refdef.viewentitymatrix = originalmatrix;
1895         }
1896         else
1897         {
1898                 r_showtrispass = false;
1899                 SCR_DrawScreen();
1900
1901                 if (r_showtris.value > 0)
1902                 {
1903                         rmeshstate_t m;
1904                         GL_BlendFunc(GL_ONE, GL_ONE);
1905                         GL_DepthTest(GL_FALSE);
1906                         GL_DepthMask(GL_FALSE);
1907                         memset(&m, 0, sizeof(m));
1908                         R_Mesh_State(&m);
1909                         r_showtrispass = true;
1910                         GL_ShowTrisColor(0.2,0.2,0.2,1);
1911                         SCR_DrawScreen();
1912                         r_showtrispass = false;
1913                 }
1914         }
1915
1916         VID_Finish();
1917         R_TimeReport("finish");
1918 }
1919
1920
1921 //===========================================================================
1922 // dynamic vertex array buffer subsystem
1923 //===========================================================================
1924
1925 // FIXME: someday this should be dynamically allocated and resized?
1926 float varray_vertex3f[65536*3];
1927 float varray_svector3f[65536*3];
1928 float varray_tvector3f[65536*3];
1929 float varray_normal3f[65536*3];
1930 float varray_color4f[65536*4];
1931 float varray_texcoord2f[4][65536*2];
1932 float varray_texcoord3f[4][65536*3];
1933 int earray_element3i[65536];
1934 float varray_vertex3f2[65536*3];
1935
1936 //===========================================================================
1937 // vertex array caching subsystem
1938 //===========================================================================
1939
1940 typedef struct rcachearraylink_s
1941 {
1942         struct rcachearraylink_s *next, *prev;
1943         struct rcachearrayitem_s *data;
1944 }
1945 rcachearraylink_t;
1946
1947 typedef struct rcachearrayitem_s
1948 {
1949         // the original request structure
1950         rcachearrayrequest_t request;
1951         // active
1952         int active;
1953         // offset into r_mesh_rcachedata
1954         int offset;
1955         // for linking this into the sequential list
1956         rcachearraylink_t sequentiallink;
1957         // for linking this into the lookup list
1958         rcachearraylink_t hashlink;
1959 }
1960 rcachearrayitem_t;
1961
1962 #define RCACHEARRAY_HASHSIZE 65536
1963 #define RCACHEARRAY_ITEMS 4096
1964 #define RCACHEARRAY_DEFAULTSIZE (4 << 20)
1965
1966 // all active items are linked into this chain in sorted order
1967 static rcachearraylink_t r_mesh_rcachesequentialchain;
1968 // all inactive items are linked into this chain in unknown order
1969 static rcachearraylink_t r_mesh_rcachefreechain;
1970 // all active items are also linked into these chains (using their hashlink)
1971 static rcachearraylink_t r_mesh_rcachechain[RCACHEARRAY_HASHSIZE];
1972
1973 // all items are stored here, whether active or inactive
1974 static rcachearrayitem_t r_mesh_rcacheitems[RCACHEARRAY_ITEMS];
1975
1976 // size of data buffer
1977 static int r_mesh_rcachedata_size = RCACHEARRAY_DEFAULTSIZE;
1978 // data buffer
1979 static qbyte r_mesh_rcachedata[RCACHEARRAY_DEFAULTSIZE];
1980
1981 // current state
1982 static int r_mesh_rcachedata_offset;
1983 static rcachearraylink_t *r_mesh_rcachesequentialchain_current;
1984
1985 static void R_Mesh_CacheArray_Startup(void)
1986 {
1987         int i;
1988         rcachearraylink_t *l;
1989         // prepare all the linked lists
1990         l = &r_mesh_rcachesequentialchain;l->next = l->prev = l;l->data = NULL;
1991         l = &r_mesh_rcachefreechain;l->next = l->prev = l;l->data = NULL;
1992         memset(&r_mesh_rcachechain, 0, sizeof(r_mesh_rcachechain));
1993         for (i = 0;i < RCACHEARRAY_HASHSIZE;i++)
1994         {
1995                 l = &r_mesh_rcachechain[i];
1996                 l->next = l->prev = l;
1997                 l->data = NULL;
1998         }
1999         memset(&r_mesh_rcacheitems, 0, sizeof(r_mesh_rcacheitems));
2000         for (i = 0;i < RCACHEARRAY_ITEMS;i++)
2001         {
2002                 r_mesh_rcacheitems[i].hashlink.data = r_mesh_rcacheitems[i].sequentiallink.data = &r_mesh_rcacheitems[i];
2003                 l = &r_mesh_rcacheitems[i].sequentiallink;
2004                 l->next = &r_mesh_rcachefreechain;
2005                 l->prev = l->next->prev;
2006                 l->next->prev = l->prev->next = l;
2007         }
2008         // clear other state
2009         r_mesh_rcachedata_offset = 0;
2010         r_mesh_rcachesequentialchain_current = &r_mesh_rcachesequentialchain;
2011 }
2012
2013 static void R_Mesh_CacheArray_Shutdown(void)
2014 {
2015 }
2016
2017 /*
2018 static void R_Mesh_CacheArray_ValidateState(int num)
2019 {
2020         rcachearraylink_t *l, *lhead;
2021         lhead = &r_mesh_rcachesequentialchain;
2022         if (r_mesh_rcachesequentialchain_current == lhead)
2023                 return;
2024         for (l = lhead->next;l != lhead;l = l->next)
2025                 if (r_mesh_rcachesequentialchain_current == l)
2026                         return;
2027         Sys_Error("%i", num);
2028 }
2029 */
2030
2031 int R_Mesh_CacheArray(rcachearrayrequest_t *r)
2032 {
2033         rcachearraylink_t *l, *lhead, *lnext;
2034         rcachearrayitem_t *d;
2035         int hashindex, offset, offsetend;
2036
2037         //R_Mesh_CacheArray_ValidateState(3);
2038         // calculate a hashindex to choose a cache chain
2039         r->data = NULL;
2040         hashindex = CRC_Block((void *)r, sizeof(*r)) % RCACHEARRAY_HASHSIZE;
2041
2042         // is it already cached?
2043         for (lhead = &r_mesh_rcachechain[hashindex], l = lhead->next;l != lhead;l = l->next)
2044         {
2045                 if (!memcmp(&l->data->request, r, sizeof(l->data->request)))
2046                 {
2047                         // we have it cached already
2048                         r->data = r_mesh_rcachedata + l->data->offset;
2049                         return false;
2050                 }
2051         }
2052
2053         // we need to add a new cache item, this means finding a place for the new
2054         // data and making sure we have a free item available, lots of work...
2055
2056         // check if buffer needs to wrap
2057         if (r_mesh_rcachedata_offset + r->data_size > r_mesh_rcachedata_size)
2058         {
2059                 /*
2060                 if (r->data_size * 10 > r_mesh_rcachedata_size)
2061                 {
2062                         // realloc whole cache
2063                 }
2064                 */
2065                 // reset back to start
2066                 r_mesh_rcachedata_offset = 0;
2067                 r_mesh_rcachesequentialchain_current = &r_mesh_rcachesequentialchain;
2068         }
2069         offset = r_mesh_rcachedata_offset;
2070         r_mesh_rcachedata_offset += r->data_size;
2071         offsetend = r_mesh_rcachedata_offset;
2072         //R_Mesh_CacheArray_ValidateState(4);
2073
2074         /*
2075         {
2076                 int n;
2077                 for (lhead = &r_mesh_rcachesequentialchain, l = lhead->next, n = 0;l != lhead;l = l->next, n++);
2078                 Con_Printf("R_Mesh_CacheArray: new data range %i:%i, %i items are already linked\n", offset, offsetend, n);
2079         }
2080         */
2081
2082         // make room for the new data (remove old items)
2083         lhead = &r_mesh_rcachesequentialchain;
2084         l = r_mesh_rcachesequentialchain_current;
2085         if (l == lhead)
2086                 l = l->next;
2087         while (l != lhead && l->data->offset < offsetend && l->data->offset + l->data->request.data_size > offset)
2088         {
2089         //r_mesh_rcachesequentialchain_current = l;
2090         //R_Mesh_CacheArray_ValidateState(8);
2091                 lnext = l->next;
2092                 // if at the end of the chain, wrap around
2093                 if (lnext == lhead)
2094                         lnext = lnext->next;
2095         //r_mesh_rcachesequentialchain_current = lnext;
2096         //R_Mesh_CacheArray_ValidateState(10);
2097
2098                 // unlink from sequential chain
2099                 l->next->prev = l->prev;
2100                 l->prev->next = l->next;
2101         //R_Mesh_CacheArray_ValidateState(11);
2102                 // link into free chain
2103                 l->next = &r_mesh_rcachefreechain;
2104                 l->prev = l->next->prev;
2105                 l->next->prev = l->prev->next = l;
2106         //R_Mesh_CacheArray_ValidateState(12);
2107
2108                 l = &l->data->hashlink;
2109                 // unlink from hash chain
2110                 l->next->prev = l->prev;
2111                 l->prev->next = l->next;
2112
2113                 l = lnext;
2114         //r_mesh_rcachesequentialchain_current = l;
2115         //R_Mesh_CacheArray_ValidateState(9);
2116         }
2117         //r_mesh_rcachesequentialchain_current = l;
2118         //R_Mesh_CacheArray_ValidateState(5);
2119         // gobble an extra item if we have no free items available
2120         if (r_mesh_rcachefreechain.next == &r_mesh_rcachefreechain)
2121         {
2122                 lnext = l->next;
2123
2124                 // unlink from sequential chain
2125                 l->next->prev = l->prev;
2126                 l->prev->next = l->next;
2127                 // link into free chain
2128                 l->next = &r_mesh_rcachefreechain;
2129                 l->prev = l->next->prev;
2130                 l->next->prev = l->prev->next = l;
2131
2132                 l = &l->data->hashlink;
2133                 // unlink from hash chain
2134                 l->next->prev = l->prev;
2135                 l->prev->next = l->next;
2136
2137                 l = lnext;
2138         }
2139         r_mesh_rcachesequentialchain_current = l;
2140         //R_Mesh_CacheArray_ValidateState(6);
2141
2142         // now take an item from the free chain
2143         l = r_mesh_rcachefreechain.next;
2144         // set it up
2145         d = l->data;
2146         d->request = *r;
2147         d->offset = offset;
2148         // unlink
2149         l->next->prev = l->prev;
2150         l->prev->next = l->next;
2151         // relink to sequential
2152         l->next = r_mesh_rcachesequentialchain_current->prev;
2153         l->prev = l->next->prev;
2154         while (l->next->data && l->data && l->next->data->offset <= d->offset)
2155         {
2156                 //Con_Print(">\n");
2157                 l->next = l->next->next;
2158                 l->prev = l->prev->next;
2159         }
2160         while (l->prev->data && l->data && l->prev->data->offset >= d->offset)
2161         {
2162                 //Con_Print("<\n");
2163                 l->prev = l->prev->prev;
2164                 l->next = l->next->prev;
2165         }
2166         l->next->prev = l->prev->next = l;
2167         // also link into hash chain
2168         l = &l->data->hashlink;
2169         l->next = &r_mesh_rcachechain[hashindex];
2170         l->prev = l->next->prev;
2171         l->prev->next = l;
2172         l->next->prev = l->prev->next = l;
2173
2174
2175         //r_mesh_rcachesequentialchain_current = d->sequentiallink.next;
2176
2177         //R_Mesh_CacheArray_ValidateState(7);
2178         // and finally set the data pointer
2179         r->data = r_mesh_rcachedata + d->offset;
2180         // and tell the caller to fill the array
2181         return true;
2182 }
2183