GL_NV_vertex_array_range support added, but disabled by default because for some...
[divverent/darkplaces.git] / gl_backend.c
1
2 #include "quakedef.h"
3 #include "image.h"
4
5 cvar_t gl_mesh_maxverts = {0, "gl_mesh_maxverts", "21760"};
6 cvar_t gl_mesh_floatcolors = {0, "gl_mesh_floatcolors", "1"};
7 cvar_t gl_mesh_drawrangeelements = {0, "gl_mesh_drawrangeelements", "1"};
8 cvar_t gl_mesh_vertex_array_range = {0, "gl_mesh_vertex_array_range", "0"};
9 cvar_t gl_mesh_vertex_array_range_readfrequency = {0, "gl_mesh_vertex_array_range_readfrequency", "0.3"};
10 cvar_t gl_mesh_vertex_array_range_writefrequency = {0, "gl_mesh_vertex_array_range_writefrequency", "1"};
11 cvar_t gl_mesh_vertex_array_range_priority = {0, "gl_mesh_vertex_array_range_priority", "0.7"};
12 cvar_t gl_delayfinish = {CVAR_SAVE, "gl_delayfinish", "0"};
13
14 cvar_t r_render = {0, "r_render", "1"};
15 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1"}; // whether or not to use dithering
16 cvar_t gl_lockarrays = {0, "gl_lockarrays", "1"};
17
18 int gl_maxdrawrangeelementsvertices;
19 int gl_maxdrawrangeelementsindices;
20
21 #ifdef DEBUGGL
22 int errornumber = 0;
23
24 void GL_PrintError(int errornumber, char *filename, int linenumber)
25 {
26         switch(errornumber)
27         {
28 #ifdef GL_INVALID_ENUM
29         case GL_INVALID_ENUM:
30                 Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
31                 break;
32 #endif
33 #ifdef GL_INVALID_VALUE
34         case GL_INVALID_VALUE:
35                 Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
36                 break;
37 #endif
38 #ifdef GL_INVALID_OPERATION
39         case GL_INVALID_OPERATION:
40                 Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
41                 break;
42 #endif
43 #ifdef GL_STACK_OVERFLOW
44         case GL_STACK_OVERFLOW:
45                 Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
46                 break;
47 #endif
48 #ifdef GL_STACK_UNDERFLOW
49         case GL_STACK_UNDERFLOW:
50                 Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
51                 break;
52 #endif
53 #ifdef GL_OUT_OF_MEMORY
54         case GL_OUT_OF_MEMORY:
55                 Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
56                 break;
57 #endif
58 #ifdef GL_TABLE_TOO_LARGE
59         case GL_TABLE_TOO_LARGE:
60                 Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
61                 break;
62 #endif
63         default:
64                 Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
65                 break;
66         }
67 }
68 #endif
69
70 #define BACKENDACTIVECHECK if (!backendactive) Sys_Error("GL backend function called when backend is not active\n");
71
72 int c_meshs, c_meshelements;
73
74 void SCR_ScreenShot_f (void);
75
76 // these are externally accessible
77 int r_lightmapscalebit;
78 float r_colorscale;
79 GLfloat *varray_vertex, *varray_buf_vertex;
80 GLfloat *varray_color, *varray_buf_color;
81 GLfloat *varray_texcoord[MAX_TEXTUREUNITS], *varray_buf_texcoord[MAX_TEXTUREUNITS];
82 int mesh_maxverts;
83 int mesh_var;
84 float mesh_var_readfrequency;
85 float mesh_var_writefrequency;
86 float mesh_var_priority;
87 int varray_offset = 0, varray_offsetnext = 0;
88 GLuint *varray_buf_elements;
89 int mesh_maxelements = 3072;
90
91 static matrix4x4_t backend_viewmatrix;
92 static matrix4x4_t backend_modelmatrix;
93 static matrix4x4_t backend_modelviewmatrix;
94 static matrix4x4_t backend_glmodelviewmatrix;
95 static matrix4x4_t backend_projectmatrix;
96
97 static int backendunits, backendactive;
98 static GLubyte *varray_bcolor, *varray_buf_bcolor;
99 static mempool_t *gl_backend_mempool;
100
101 /*
102 note: here's strip order for a terrain row:
103 0--1--2--3--4
104 |\ |\ |\ |\ |
105 | \| \| \| \|
106 A--B--C--D--E
107
108 A0B, 01B, B1C, 12C, C2D, 23D, D3E, 34E
109
110 *elements++ = i + row;
111 *elements++ = i;
112 *elements++ = i + row + 1;
113 *elements++ = i;
114 *elements++ = i + 1;
115 *elements++ = i + row + 1;
116 */
117
118 void GL_Backend_AllocElementsArray(void)
119 {
120         if (varray_buf_elements)
121                 Mem_Free(varray_buf_elements);
122         varray_buf_elements = Mem_Alloc(gl_backend_mempool, mesh_maxelements * sizeof(GLuint));
123 }
124
125 void GL_Backend_FreeElementArray(void)
126 {
127         if (varray_buf_elements)
128                 Mem_Free(varray_buf_elements);
129         varray_buf_elements = NULL;
130 }
131
132 void GL_Backend_CheckCvars(void)
133 {
134         // 21760 is (65536 / 3) rounded off to a multiple of 128
135         if (gl_mesh_maxverts.integer < 1024)
136                 Cvar_SetValueQuick(&gl_mesh_maxverts, 1024);
137         if (gl_mesh_maxverts.integer > 21760)
138                 Cvar_SetValueQuick(&gl_mesh_maxverts, 21760);
139         if (gl_mesh_vertex_array_range.integer && !gl_support_var)
140                 Cvar_SetValueQuick(&gl_mesh_vertex_array_range, 0);
141         if (gl_mesh_vertex_array_range_readfrequency.value < 0)
142                 Cvar_SetValueQuick(&gl_mesh_vertex_array_range_readfrequency, 0);
143         if (gl_mesh_vertex_array_range_readfrequency.value > 1)
144                 Cvar_SetValueQuick(&gl_mesh_vertex_array_range_readfrequency, 1);
145         if (gl_mesh_vertex_array_range_writefrequency.value < 0)
146                 Cvar_SetValueQuick(&gl_mesh_vertex_array_range_writefrequency, 0);
147         if (gl_mesh_vertex_array_range_writefrequency.value > 1)
148                 Cvar_SetValueQuick(&gl_mesh_vertex_array_range_writefrequency, 1);
149         if (gl_mesh_vertex_array_range_priority.value < 0)
150                 Cvar_SetValueQuick(&gl_mesh_vertex_array_range_priority, 0);
151         if (gl_mesh_vertex_array_range_priority.value > 1)
152                 Cvar_SetValueQuick(&gl_mesh_vertex_array_range_priority, 1);
153 }
154
155 int polygonelements[768];
156
157 void GL_Backend_AllocArrays(void)
158 {
159         int i, size;
160
161         if (!gl_backend_mempool)
162         {
163                 gl_backend_mempool = Mem_AllocPool("GL_Backend");
164                 varray_buf_vertex = NULL;
165                 varray_buf_color = NULL;
166                 varray_buf_bcolor = NULL;
167                 varray_buf_elements = NULL;
168                 for (i = 0;i < MAX_TEXTUREUNITS;i++)
169                         varray_buf_texcoord[i] = NULL;
170         }
171
172         mesh_maxverts = gl_mesh_maxverts.integer;
173         mesh_var = gl_mesh_vertex_array_range.integer;
174         mesh_var_readfrequency = gl_mesh_vertex_array_range_readfrequency.value;
175         mesh_var_writefrequency = gl_mesh_vertex_array_range_writefrequency.value;
176         mesh_var_priority = gl_mesh_vertex_array_range_priority.value;
177
178         if (varray_buf_vertex)
179                 VID_FreeVertexArrays(varray_buf_vertex);
180         varray_buf_vertex = NULL;
181         varray_buf_color = NULL;
182         varray_buf_bcolor = NULL;
183         for (i = 0;i < MAX_TEXTUREUNITS;i++)
184                 varray_buf_texcoord[i] = NULL;
185
186         size = mesh_maxverts * (sizeof(GLfloat[4]) + sizeof(GLfloat[4]) + sizeof(GLfloat[4]) * backendunits + sizeof(GLubyte[4]));
187         varray_buf_vertex = VID_AllocVertexArrays(gl_backend_mempool, size, gl_mesh_vertex_array_range.integer, gl_mesh_vertex_array_range_readfrequency.value, gl_mesh_vertex_array_range_writefrequency.value, gl_mesh_vertex_array_range_priority.value);
188         varray_buf_color = varray_buf_vertex + 4 * mesh_maxverts;
189         for (i = 0;i < backendunits;i++)
190                 varray_buf_texcoord[i] = varray_buf_vertex + (i + 2) * 4 * mesh_maxverts;
191         for (;i < MAX_TEXTUREUNITS;i++)
192                 varray_buf_texcoord[i] = NULL;
193         varray_buf_bcolor = (GLubyte *)(varray_buf_vertex + (backendunits + 2) * 4 * mesh_maxverts);
194
195         GL_Backend_AllocElementsArray();
196
197         if (gl_support_var)
198         {
199                 CHECKGLERROR
200                 qglVertexArrayRangeNV(size, varray_buf_vertex);
201                 CHECKGLERROR
202                 qglEnableClientState(GL_VERTEX_ARRAY_RANGE_NV);
203                 CHECKGLERROR
204         }
205 }
206
207 void GL_Backend_FreeArrays(void)
208 {
209         int i;
210
211         if (gl_support_var)
212         {
213                 CHECKGLERROR
214                 qglDisableClientState(GL_VERTEX_ARRAY_RANGE_NV);
215                 CHECKGLERROR
216         }
217
218         if (varray_buf_vertex)
219                 VID_FreeVertexArrays(varray_buf_vertex);
220         varray_buf_vertex = NULL;
221         varray_buf_color = NULL;
222         varray_buf_bcolor = NULL;
223         for (i = 0;i < MAX_TEXTUREUNITS;i++)
224                 varray_buf_texcoord[i] = NULL;
225
226         Mem_FreePool(&gl_backend_mempool);
227
228         varray_buf_elements = NULL;
229 }
230
231 static void gl_backend_start(void)
232 {
233         GL_Backend_CheckCvars();
234
235         Con_Printf("OpenGL Backend started with gl_mesh_maxverts %i\n", gl_mesh_maxverts.integer);
236         if (qglDrawRangeElements != NULL)
237         {
238                 CHECKGLERROR
239                 qglGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &gl_maxdrawrangeelementsvertices);
240                 CHECKGLERROR
241                 qglGetIntegerv(GL_MAX_ELEMENTS_INDICES, &gl_maxdrawrangeelementsindices);
242                 CHECKGLERROR
243                 Con_Printf("glDrawRangeElements detected (max vertices %i, max indices %i)\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
244         }
245         if (strstr(gl_renderer, "3Dfx"))
246         {
247                 Con_Printf("3Dfx driver detected, forcing gl_mesh_floatcolors to 0 to prevent crashs\n");
248                 Cvar_SetValueQuick(&gl_mesh_floatcolors, 0);
249         }
250
251         backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
252
253         GL_Backend_AllocArrays();
254
255         backendactive = true;
256 }
257
258 static void gl_backend_shutdown(void)
259 {
260         backendunits = 0;
261         backendactive = false;
262
263         Con_Printf("OpenGL Backend shutting down\n");
264
265         GL_Backend_FreeArrays();
266 }
267
268 void GL_Backend_ResizeArrays(int numvertices)
269 {
270         Cvar_SetValueQuick(&gl_mesh_maxverts, numvertices);
271         GL_Backend_CheckCvars();
272         mesh_maxverts = gl_mesh_maxverts.integer;
273         GL_Backend_AllocArrays();
274 }
275
276 static void gl_backend_newmap(void)
277 {
278 }
279
280 void gl_backend_init(void)
281 {
282         int i;
283
284         for (i = 0;i < POLYGONELEMENTS_MAXPOINTS - 2;i++)
285         {
286                 polygonelements[i * 3 + 0] = 0;
287                 polygonelements[i * 3 + 1] = i + 1;
288                 polygonelements[i * 3 + 2] = i + 2;
289         }
290
291         Cvar_RegisterVariable(&r_render);
292         Cvar_RegisterVariable(&gl_dither);
293         Cvar_RegisterVariable(&gl_lockarrays);
294         Cvar_RegisterVariable(&gl_delayfinish);
295 #ifdef NORENDER
296         Cvar_SetValue("r_render", 0);
297 #endif
298
299         Cvar_RegisterVariable(&gl_mesh_maxverts);
300         Cvar_RegisterVariable(&gl_mesh_floatcolors);
301         Cvar_RegisterVariable(&gl_mesh_drawrangeelements);
302         Cvar_RegisterVariable(&gl_mesh_vertex_array_range);
303         Cvar_RegisterVariable(&gl_mesh_vertex_array_range_readfrequency);
304         Cvar_RegisterVariable(&gl_mesh_vertex_array_range_writefrequency);
305         Cvar_RegisterVariable(&gl_mesh_vertex_array_range_priority);
306         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
307 }
308
309 void GL_SetupView_ViewPort (int x, int y, int width, int height)
310 {
311         if (!r_render.integer)
312                 return;
313
314         // y is weird beause OpenGL is bottom to top, we use top to bottom
315         qglViewport(x, vid.realheight - (y + height), width, height);
316         CHECKGLERROR
317 }
318
319 void GL_SetupView_Orientation_Identity (void)
320 {
321         Matrix4x4_CreateIdentity(&backend_viewmatrix);
322         memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
323 }
324
325 void GL_SetupView_Orientation_FromEntity (vec3_t origin, vec3_t angles)
326 {
327         Matrix4x4_CreateRotate(&backend_viewmatrix, -90, 1, 0, 0);
328         Matrix4x4_ConcatRotate(&backend_viewmatrix, 90, 0, 0, 1);
329         Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[2], 1, 0, 0);
330         Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[0], 0, 1, 0);
331         Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[1], 0, 0, 1);
332         Matrix4x4_ConcatTranslate(&backend_viewmatrix, -origin[0], -origin[1], -origin[2]);
333         memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
334 }
335
336 void GL_SetupView_Mode_Perspective (double fovx, double fovy, double zNear, double zFar)
337 {
338         double xmax, ymax;
339
340         if (!r_render.integer)
341                 return;
342
343         // set up viewpoint
344         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
345         qglLoadIdentity();CHECKGLERROR
346         // pyramid slopes
347         xmax = zNear * tan(fovx * M_PI / 360.0);
348         ymax = zNear * tan(fovy * M_PI / 360.0);
349         // set view pyramid
350         qglFrustum(-xmax, xmax, -ymax, ymax, zNear, zFar);CHECKGLERROR
351         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
352         GL_SetupView_Orientation_Identity();
353 }
354
355 void GL_SetupView_Mode_PerspectiveInfiniteFarClip (double fovx, double fovy, double zNear)
356 {
357         float nudge, m[16];
358
359         if (!r_render.integer)
360                 return;
361
362         // set up viewpoint
363         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
364         qglLoadIdentity();CHECKGLERROR
365         // set view pyramid
366         nudge = 1.0 - 1.0 / (1<<23);
367         m[ 0] = 1.0 / tan(fovx * M_PI / 360.0);
368         m[ 1] = 0;
369         m[ 2] = 0;
370         m[ 3] = 0;
371         m[ 4] = 0;
372         m[ 5] = 1.0 / tan(fovy * M_PI / 360.0);
373         m[ 6] = 0;
374         m[ 7] = 0;
375         m[ 8] = 0;
376         m[ 9] = 0;
377         m[10] = -1 * nudge;
378         m[11] = -1 * nudge;
379         m[12] = 0;
380         m[13] = 0;
381         m[14] = -2 * zNear * nudge;
382         m[15] = 0;
383         qglLoadMatrixf(m);
384         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
385         GL_SetupView_Orientation_Identity();
386         backend_projectmatrix.m[0][0] = m[0];
387         backend_projectmatrix.m[1][0] = m[1];
388         backend_projectmatrix.m[2][0] = m[2];
389         backend_projectmatrix.m[3][0] = m[3];
390         backend_projectmatrix.m[0][1] = m[4];
391         backend_projectmatrix.m[1][1] = m[5];
392         backend_projectmatrix.m[2][1] = m[6];
393         backend_projectmatrix.m[3][1] = m[7];
394         backend_projectmatrix.m[0][2] = m[8];
395         backend_projectmatrix.m[1][2] = m[9];
396         backend_projectmatrix.m[2][2] = m[10];
397         backend_projectmatrix.m[3][2] = m[11];
398         backend_projectmatrix.m[0][3] = m[12];
399         backend_projectmatrix.m[1][3] = m[13];
400         backend_projectmatrix.m[2][3] = m[14];
401         backend_projectmatrix.m[3][3] = m[15];
402 }
403
404 void GL_SetupView_Mode_Ortho (double x1, double y1, double x2, double y2, double zNear, double zFar)
405 {
406         if (!r_render.integer)
407                 return;
408
409         // set up viewpoint
410         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
411         qglLoadIdentity();CHECKGLERROR
412         qglOrtho(x1, x2, y2, y1, zNear, zFar);
413         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
414         GL_SetupView_Orientation_Identity();
415 }
416
417 typedef struct gltextureunit_s
418 {
419         int t1d, t2d, t3d, tcubemap;
420         int arrayenabled;
421         float rgbscale, alphascale;
422         int combinergb, combinealpha;
423         // FIXME: add more combine stuff
424 }
425 gltextureunit_t;
426
427 static struct
428 {
429         int blendfunc1;
430         int blendfunc2;
431         int blend;
432         GLboolean depthmask;
433         int depthdisable;
434         int unit;
435         int clientunit;
436         gltextureunit_t units[MAX_TEXTUREUNITS];
437         int colorarray;
438 }
439 gl_state;
440
441 void GL_SetupTextureState(void)
442 {
443         int i;
444         gltextureunit_t *unit;
445         for (i = 0;i < backendunits;i++)
446         {
447                 if (qglActiveTexture)
448                         qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
449                 if (qglClientActiveTexture)
450                         qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
451                 unit = gl_state.units + i;
452                 unit->t1d = 0;
453                 unit->t2d = 0;
454                 unit->t3d = 0;
455                 unit->tcubemap = 0;
456                 unit->rgbscale = 1;
457                 unit->alphascale = 1;
458                 unit->combinergb = GL_MODULATE;
459                 unit->combinealpha = GL_MODULATE;
460                 unit->arrayenabled = false;
461                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
462                 if (gl_texture3d || gl_texturecubemap)
463                 {
464                         qglTexCoordPointer(3, GL_FLOAT, sizeof(float[4]), varray_buf_texcoord[i]);CHECKGLERROR
465                 }
466                 else
467                 {
468                         qglTexCoordPointer(2, GL_FLOAT, sizeof(float[4]), varray_buf_texcoord[i]);CHECKGLERROR
469                 }
470                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
471                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
472                 if (gl_texture3d)
473                 {
474                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
475                 }
476                 if (gl_texturecubemap)
477                 {
478                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
479                 }
480                 if (gl_combine.integer)
481                 {
482                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
483                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);CHECKGLERROR
484                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);CHECKGLERROR
485                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
486                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_CONSTANT_ARB);CHECKGLERROR
487                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
488                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
489                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB_ARB, GL_SRC_ALPHA);CHECKGLERROR
490                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);CHECKGLERROR
491                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE);CHECKGLERROR
492                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
493                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA_ARB, GL_CONSTANT_ARB);CHECKGLERROR
494                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
495                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
496                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
497                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
498                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
499                 }
500                 else
501                 {
502                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
503                 }
504         }
505 }
506
507 void GL_Backend_ResetState(void)
508 {
509         memset(&gl_state, 0, sizeof(gl_state));
510         gl_state.depthdisable = false;
511         gl_state.blendfunc1 = GL_ONE;
512         gl_state.blendfunc2 = GL_ZERO;
513         gl_state.blend = false;
514         gl_state.depthmask = GL_TRUE;
515         gl_state.colorarray = false;
516
517         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
518         qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
519
520         qglEnable(GL_CULL_FACE);CHECKGLERROR
521         qglCullFace(GL_FRONT);CHECKGLERROR
522         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
523         qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
524         qglDisable(GL_BLEND);CHECKGLERROR
525         qglDepthMask(gl_state.depthmask);CHECKGLERROR
526         qglVertexPointer(3, GL_FLOAT, sizeof(GLfloat[4]), varray_buf_vertex);CHECKGLERROR
527         qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
528         if (gl_mesh_floatcolors.integer)
529         {
530                 qglColorPointer(4, GL_FLOAT, sizeof(GLfloat[4]), varray_buf_color);CHECKGLERROR
531         }
532         else
533         {
534                 qglColorPointer(4, GL_UNSIGNED_BYTE, sizeof(GLubyte[4]), varray_buf_bcolor);CHECKGLERROR
535         }
536         GL_Color(1, 1, 1, 1);
537
538         GL_SetupTextureState();
539 }
540
541 void GL_UseColorArray(void)
542 {
543         if (!gl_state.colorarray)
544         {
545                 gl_state.colorarray = true;
546                 qglEnableClientState(GL_COLOR_ARRAY);CHECKGLERROR
547         }
548 }
549
550 void GL_Color(float cr, float cg, float cb, float ca)
551 {
552         if (gl_state.colorarray)
553         {
554                 gl_state.colorarray = false;
555                 qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
556         }
557         qglColor4f(cr, cg, cb, ca);
558 }
559
560 void GL_TransformToScreen(const vec4_t in, vec4_t out)
561 {
562         vec4_t temp;
563         float iw;
564         Matrix4x4_Transform4 (&backend_viewmatrix, in, temp);
565         Matrix4x4_Transform4 (&backend_projectmatrix, temp, out);
566         iw = 1.0f / out[3];
567         out[0] = r_refdef.x + (out[0] * iw + 1.0f) * r_refdef.width * 0.5f;
568         out[1] = r_refdef.y + (out[1] * iw + 1.0f) * r_refdef.height * 0.5f;
569         out[2] = out[2] * iw;
570 }
571
572 // called at beginning of frame
573 void R_Mesh_Start(void)
574 {
575         BACKENDACTIVECHECK
576
577         CHECKGLERROR
578
579         GL_Backend_CheckCvars();
580         if (mesh_maxverts != gl_mesh_maxverts.integer
581          || mesh_var != gl_mesh_vertex_array_range.integer
582          || mesh_var_readfrequency != gl_mesh_vertex_array_range_readfrequency.value
583          || mesh_var_writefrequency != gl_mesh_vertex_array_range_writefrequency.value
584          || mesh_var_priority != gl_mesh_vertex_array_range_priority.value)
585                 GL_Backend_ResizeArrays(gl_mesh_maxverts.integer);
586
587         GL_Backend_ResetState();
588
589         if (mesh_var)
590         {
591                 CHECKGLERROR
592                 qglFlushVertexArrayRangeNV();
593                 CHECKGLERROR
594         }
595         varray_offset = 0;
596 }
597
598 int gl_backend_rebindtextures;
599
600 void GL_ConvertColorsFloatToByte(int numverts)
601 {
602         int i, k, total;
603         // LordHavoc: to avoid problems with aliasing (treating memory as two
604         // different types - exactly what this is doing), these must be volatile
605         // (or a union)
606         volatile int *icolor;
607         volatile float *fcolor;
608         GLubyte *bcolor;
609
610         total = numverts * 4;
611
612         // shift float to have 8bit fraction at base of number
613         fcolor = varray_buf_color;
614         for (i = 0;i < total;)
615         {
616                 fcolor[i    ] += 32768.0f;
617                 fcolor[i + 1] += 32768.0f;
618                 fcolor[i + 2] += 32768.0f;
619                 fcolor[i + 3] += 32768.0f;
620                 i += 4;
621         }
622
623         // then read as integer and kill float bits...
624         icolor = (int *)varray_buf_color;
625         bcolor = varray_buf_bcolor;
626         for (i = 0;i < total;)
627         {
628                 k = icolor[i    ] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i    ] = (GLubyte) k;
629                 k = icolor[i + 1] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 1] = (GLubyte) k;
630                 k = icolor[i + 2] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 2] = (GLubyte) k;
631                 k = icolor[i + 3] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 3] = (GLubyte) k;
632                 i += 4;
633         }
634 }
635
636 /*
637 // enlarges geometry buffers if they are too small
638 void _R_Mesh_ResizeCheck(int numverts)
639 {
640         if (numverts > mesh_maxverts)
641         {
642                 BACKENDACTIVECHECK
643                 GL_Backend_ResizeArrays(numverts + 100);
644                 GL_Backend_ResetState();
645         }
646 }
647 */
648
649 void GL_Backend_RenumberElements(int numelements, const int *in, int offset)
650 {
651         int i;
652         for (i = 0;i < numelements;i++)
653                 varray_buf_elements[i] = in[i] + offset;
654 }
655
656 // gets geometry space for a mesh
657 void R_Mesh_GetSpace(int numverts)
658 {
659         int i;
660
661         varray_offset = varray_offsetnext;
662         if (varray_offset + numverts > mesh_maxverts)
663                 varray_offset = 0;
664         if (numverts > mesh_maxverts)
665         {
666                 BACKENDACTIVECHECK
667                 GL_Backend_ResizeArrays(numverts + 100);
668                 GL_Backend_ResetState();
669                 varray_offset = 0;
670         }
671
672         if (varray_offset == 0 && mesh_var)
673         {
674                 CHECKGLERROR
675                 qglFlushVertexArrayRangeNV();
676                 CHECKGLERROR
677         }
678
679         // for debugging
680         //if (!mesh_var)
681         //      varray_offset = rand() % (mesh_maxverts - numverts);
682
683         varray_vertex = varray_buf_vertex + varray_offset * 4;
684         varray_color = varray_buf_color + varray_offset * 4;
685         varray_bcolor = varray_buf_bcolor + varray_offset * 4;
686         for (i = 0;i < backendunits;i++)
687                 varray_texcoord[i] = varray_buf_texcoord[i] + varray_offset * 4;
688
689         varray_offsetnext = varray_offset + numverts;
690 }
691
692 // renders the current mesh
693 void R_Mesh_Draw(int numverts, int numtriangles, const int *elements)
694 {
695         int numelements;
696         if (numtriangles == 0 || numverts == 0)
697         {
698                 Con_Printf("R_Mesh_Draw(%d, %d, %08p);\n", numverts, numtriangles, elements);
699                 return;
700         }
701         numelements = numtriangles * 3;
702         if (mesh_maxelements < numelements)
703         {
704                 mesh_maxelements = numelements;
705                 GL_Backend_AllocElementsArray();
706         }
707         GL_Backend_RenumberElements(numelements, elements, varray_offset);
708         c_meshs++;
709         c_meshelements += numelements;
710         if (gl_state.colorarray && !gl_mesh_floatcolors.integer)
711                 GL_ConvertColorsFloatToByte(numverts);
712         if (r_render.integer)
713         {
714                 if (gl_supportslockarrays && gl_lockarrays.integer)
715                 {
716                         qglLockArraysEXT(varray_offset, numverts);
717                         CHECKGLERROR
718                         if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
719                         {
720                                 qglDrawRangeElements(GL_TRIANGLES, varray_offset, varray_offset + numverts, numelements, GL_UNSIGNED_INT, (const GLuint *) varray_buf_elements);
721                                 CHECKGLERROR
722                         }
723                         else
724                         {
725                                 qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, (const GLuint *) varray_buf_elements);
726                                 CHECKGLERROR
727                         }
728                         qglUnlockArraysEXT();
729                         CHECKGLERROR
730                 }
731                 else
732                 {
733                         qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, (const GLuint *) varray_buf_elements);
734                         CHECKGLERROR
735                 }
736         }
737 }
738
739 // restores backend state, used when done with 3D rendering
740 void R_Mesh_Finish(void)
741 {
742         int i;
743         BACKENDACTIVECHECK
744         if (mesh_var)
745         {
746                 CHECKGLERROR
747                 qglFlushVertexArrayRangeNV();
748                 CHECKGLERROR
749         }
750         varray_offset = 0;
751
752         for (i = backendunits - 1;i >= 0;i--)
753         {
754                 if (qglActiveTexture)
755                         qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
756                 if (qglClientActiveTexture)
757                         qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
758                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
759                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
760                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
761                 if (gl_texture3d)
762                 {
763                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
764                 }
765                 if (gl_texturecubemap)
766                 {
767                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
768                 }
769                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
770                 if (gl_combine.integer)
771                 {
772                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
773                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
774                 }
775         }
776         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
777         qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
778
779         qglDisable(GL_BLEND);CHECKGLERROR
780         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
781         qglDepthMask(GL_TRUE);CHECKGLERROR
782         qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
783 }
784
785 void R_Mesh_Matrix(const matrix4x4_t *matrix)
786 {
787         if (memcmp(matrix, &backend_modelmatrix, sizeof(matrix4x4_t)))
788         {
789                 backend_modelmatrix = *matrix;
790                 Matrix4x4_Concat(&backend_modelviewmatrix, &backend_viewmatrix, matrix);
791                 Matrix4x4_Transpose(&backend_glmodelviewmatrix, &backend_modelviewmatrix);
792                 qglLoadMatrixf(&backend_glmodelviewmatrix.m[0][0]);
793         }
794 }
795
796 // sets up the requested state
797 void R_Mesh_MainState(const rmeshstate_t *m)
798 {
799         BACKENDACTIVECHECK
800
801         if (gl_state.blendfunc1 != m->blendfunc1 || gl_state.blendfunc2 != m->blendfunc2)
802         {
803                 qglBlendFunc(gl_state.blendfunc1 = m->blendfunc1, gl_state.blendfunc2 = m->blendfunc2);CHECKGLERROR
804                 if (gl_state.blendfunc2 == GL_ZERO)
805                 {
806                         if (gl_state.blendfunc1 == GL_ONE)
807                         {
808                                 if (gl_state.blend)
809                                 {
810                                         gl_state.blend = 0;
811                                         qglDisable(GL_BLEND);CHECKGLERROR
812                                 }
813                         }
814                         else
815                         {
816                                 if (!gl_state.blend)
817                                 {
818                                         gl_state.blend = 1;
819                                         qglEnable(GL_BLEND);CHECKGLERROR
820                                 }
821                         }
822                 }
823                 else
824                 {
825                         if (!gl_state.blend)
826                         {
827                                 gl_state.blend = 1;
828                                 qglEnable(GL_BLEND);CHECKGLERROR
829                         }
830                 }
831         }
832         if (gl_state.depthdisable != m->depthdisable)
833         {
834                 gl_state.depthdisable = m->depthdisable;
835                 if (gl_state.depthdisable)
836                         qglDisable(GL_DEPTH_TEST);
837                 else
838                         qglEnable(GL_DEPTH_TEST);
839         }
840         if (gl_state.depthmask != (m->blendfunc2 == GL_ZERO || m->depthwrite))
841         {
842                 qglDepthMask(gl_state.depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite));CHECKGLERROR
843         }
844 }
845
846 void R_Mesh_TextureState(const rmeshstate_t *m)
847 {
848         int i, combinergb, combinealpha;
849         float scale;
850         gltextureunit_t *unit;
851
852         BACKENDACTIVECHECK
853
854         if (gl_backend_rebindtextures)
855         {
856                 gl_backend_rebindtextures = false;
857                 GL_SetupTextureState();
858         }
859
860         for (i = 0;i < backendunits;i++)
861         {
862                 unit = gl_state.units + i;
863                 if (unit->t1d != m->tex1d[i] || unit->t2d != m->tex[i] || unit->t3d != m->tex3d[i] || unit->tcubemap != m->texcubemap[i])
864                 {
865                         if (gl_state.unit != i)
866                         {
867                                 qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
868                         }
869                         if (m->tex1d[i] || m->tex[i] || m->tex3d[i] || m->texcubemap[i])
870                         {
871                                 if (!unit->arrayenabled)
872                                 {
873                                         unit->arrayenabled = true;
874                                         if (gl_state.clientunit != i)
875                                         {
876                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
877                                         }
878                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
879                                 }
880                         }
881                         else
882                         {
883                                 if (unit->arrayenabled)
884                                 {
885                                         unit->arrayenabled = false;
886                                         if (gl_state.clientunit != i)
887                                         {
888                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
889                                         }
890                                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
891                                 }
892                         }
893                         combinergb = m->texcombinergb[i];
894                         combinealpha = m->texcombinealpha[i];
895                         if (!combinergb)
896                                 combinergb = GL_MODULATE;
897                         if (!combinealpha)
898                                 combinealpha = GL_MODULATE;
899                         if (unit->combinergb != combinergb)
900                         {
901                                 unit->combinergb = combinergb;
902                                 if (gl_combine.integer)
903                                 {
904                                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
905                                 }
906                                 else
907                                 {
908                                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
909                                 }
910                         }
911                         if (unit->combinealpha != combinealpha)
912                         {
913                                 unit->combinealpha = combinealpha;
914                                 if (gl_combine.integer)
915                                 {
916                                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
917                                 }
918                         }
919                         if (unit->t1d != m->tex1d[i])
920                         {
921                                 if (m->tex1d[i])
922                                 {
923                                         if (unit->t1d == 0)
924                                                 qglEnable(GL_TEXTURE_1D);CHECKGLERROR
925                                 }
926                                 else
927                                 {
928                                         if (unit->t1d)
929                                                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
930                                 }
931                                 qglBindTexture(GL_TEXTURE_1D, (unit->t1d = m->tex1d[i]));CHECKGLERROR
932                         }
933                         if (unit->t2d != m->tex[i])
934                         {
935                                 if (m->tex[i])
936                                 {
937                                         if (unit->t2d == 0)
938                                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
939                                 }
940                                 else
941                                 {
942                                         if (unit->t2d)
943                                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
944                                 }
945                                 qglBindTexture(GL_TEXTURE_2D, (unit->t2d = m->tex[i]));CHECKGLERROR
946                         }
947                         if (unit->t3d != m->tex3d[i])
948                         {
949                                 if (m->tex3d[i])
950                                 {
951                                         if (unit->t3d == 0)
952                                                 qglEnable(GL_TEXTURE_3D);CHECKGLERROR
953                                 }
954                                 else
955                                 {
956                                         if (unit->t3d)
957                                                 qglDisable(GL_TEXTURE_3D);CHECKGLERROR
958                                 }
959                                 qglBindTexture(GL_TEXTURE_3D, (unit->t3d = m->tex3d[i]));CHECKGLERROR
960                         }
961                         if (unit->tcubemap != m->texcubemap[i])
962                         {
963                                 if (m->texcubemap[i])
964                                 {
965                                         if (unit->tcubemap == 0)
966                                                 qglEnable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
967                                 }
968                                 else
969                                 {
970                                         if (unit->tcubemap)
971                                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
972                                 }
973                                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, (unit->tcubemap = m->texcubemap[i]));CHECKGLERROR
974                         }
975                 }
976                 scale = max(m->texrgbscale[i], 1);
977                 if (gl_state.units[i].rgbscale != scale)
978                 {
979                         if (gl_state.unit != i)
980                         {
981                                 qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
982                         }
983                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (gl_state.units[i].rgbscale = scale));CHECKGLERROR
984                 }
985                 scale = max(m->texalphascale[i], 1);
986                 if (gl_state.units[i].alphascale != scale)
987                 {
988                         if (gl_state.unit != i)
989                         {
990                                 qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
991                         }
992                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (gl_state.units[i].alphascale = scale));CHECKGLERROR
993                 }
994         }
995 }
996
997 void R_Mesh_State(const rmeshstate_t *m)
998 {
999         R_Mesh_MainState(m);
1000         R_Mesh_TextureState(m);
1001 }
1002
1003 /*
1004 ==============================================================================
1005
1006                                                 SCREEN SHOTS
1007
1008 ==============================================================================
1009 */
1010
1011 qboolean SCR_ScreenShot(char *filename, int x, int y, int width, int height)
1012 {
1013         qboolean ret;
1014         int i, j;
1015         qbyte *buffer;
1016
1017         if (!r_render.integer)
1018                 return false;
1019
1020         buffer = Mem_Alloc(tempmempool, width*height*3);
1021         qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
1022         CHECKGLERROR
1023
1024         // LordHavoc: compensate for v_overbrightbits when using hardware gamma
1025         if (v_hwgamma.integer)
1026         {
1027                 for (i = 0;i < width * height * 3;i++)
1028                 {
1029                         j = buffer[i] << v_overbrightbits.integer;
1030                         buffer[i] = (qbyte) (bound(0, j, 255));
1031                 }
1032         }
1033
1034         ret = Image_WriteTGARGB_preflipped(filename, width, height, buffer);
1035
1036         Mem_Free(buffer);
1037         return ret;
1038 }
1039
1040 //=============================================================================
1041
1042 void R_ClearScreen(void)
1043 {
1044         if (r_render.integer)
1045         {
1046                 // clear to black
1047                 qglClearColor(0,0,0,0);CHECKGLERROR
1048                 qglClearDepth(1);CHECKGLERROR
1049                 if (gl_stencil)
1050                 {
1051                         // LordHavoc: we use a stencil centered around 128 instead of 0,
1052                         // to avoid clamping interfering with strange shadow volume
1053                         // drawing orders
1054                         qglClearStencil(128);CHECKGLERROR
1055                 }
1056                 // clear the screen
1057                 qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (gl_stencil ? GL_STENCIL_BUFFER_BIT : 0));CHECKGLERROR
1058                 // set dithering mode
1059                 if (gl_dither.integer)
1060                 {
1061                         qglEnable(GL_DITHER);CHECKGLERROR
1062                 }
1063                 else
1064                 {
1065                         qglDisable(GL_DITHER);CHECKGLERROR
1066                 }
1067         }
1068 }
1069
1070 /*
1071 ==================
1072 SCR_UpdateScreen
1073
1074 This is called every frame, and can also be called explicitly to flush
1075 text to the screen.
1076 ==================
1077 */
1078 void SCR_UpdateScreen (void)
1079 {
1080         if (gl_delayfinish.integer)
1081         {
1082                 VID_Finish ();
1083
1084                 R_TimeReport("finish");
1085         }
1086
1087         if (r_textureunits.integer > gl_textureunits)
1088                 Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
1089         if (r_textureunits.integer < 1)
1090                 Cvar_SetValueQuick(&r_textureunits, 1);
1091
1092         if (gl_combine.integer && (!gl_combine_extension || r_textureunits.integer < 2))
1093                 Cvar_SetValueQuick(&gl_combine, 0);
1094
1095         // lighting scale
1096         r_colorscale = 1.0f / (float) (1 << v_overbrightbits.integer);
1097
1098         // lightmaps only
1099         r_lightmapscalebit = v_overbrightbits.integer;
1100         if (gl_combine.integer && r_textureunits.integer > 1)
1101                 r_lightmapscalebit += 2;
1102
1103         R_TimeReport("setup");
1104
1105         R_ClearScreen();
1106
1107         R_TimeReport("clear");
1108
1109         if (scr_conlines < vid.conheight && cls.signon == SIGNONS)
1110                 R_RenderView();
1111
1112         // draw 2D stuff
1113         R_DrawQueue();
1114
1115         if (gl_delayfinish.integer)
1116         {
1117                 // tell driver to commit it's partially full geometry queue to the rendering queue
1118                 // (this doesn't wait for the commands themselves to complete)
1119                 qglFlush();
1120         }
1121         else
1122         {
1123                 VID_Finish ();
1124
1125                 R_TimeReport("finish");
1126         }
1127 }
1128