a975133663a3ccaabec9f145d69b3ddc7c091503
[xonotic/darkplaces.git] / gl_backend.c
1
2 #include "quakedef.h"
3 #include "cl_collision.h"
4
5 // on GLES we have to use some proper #define's
6 #ifndef GL_FRAMEBUFFER
7 #define GL_FRAMEBUFFER                                   0x8D40
8 #define GL_DEPTH_ATTACHMENT                              0x8D00
9 #define GL_COLOR_ATTACHMENT0                             0x8CE0
10 #define GL_INVALID_FRAMEBUFFER_OPERATION                 0x0506
11 #endif
12 #ifndef GL_COLOR_ATTACHMENT1
13 #define GL_COLOR_ATTACHMENT1                             0x8CE1
14 #define GL_COLOR_ATTACHMENT2                             0x8CE2
15 #define GL_COLOR_ATTACHMENT3                             0x8CE3
16 #define GL_COLOR_ATTACHMENT4                             0x8CE4
17 #define GL_COLOR_ATTACHMENT5                             0x8CE5
18 #define GL_COLOR_ATTACHMENT6                             0x8CE6
19 #define GL_COLOR_ATTACHMENT7                             0x8CE7
20 #define GL_COLOR_ATTACHMENT8                             0x8CE8
21 #define GL_COLOR_ATTACHMENT9                             0x8CE9
22 #define GL_COLOR_ATTACHMENT10                            0x8CEA
23 #define GL_COLOR_ATTACHMENT11                            0x8CEB
24 #define GL_COLOR_ATTACHMENT12                            0x8CEC
25 #define GL_COLOR_ATTACHMENT13                            0x8CED
26 #define GL_COLOR_ATTACHMENT14                            0x8CEE
27 #define GL_COLOR_ATTACHMENT15                            0x8CEF
28 #endif
29 #ifndef GL_ARRAY_BUFFER
30 #define GL_ARRAY_BUFFER               0x8892
31 #define GL_ELEMENT_ARRAY_BUFFER       0x8893
32 #endif
33 #ifndef GL_TEXTURE0
34 #define GL_TEXTURE0                                     0x84C0
35 #define GL_TEXTURE1                                     0x84C1
36 #define GL_TEXTURE2                                     0x84C2
37 #define GL_TEXTURE3                                     0x84C3
38 #define GL_TEXTURE4                                     0x84C4
39 #define GL_TEXTURE5                                     0x84C5
40 #define GL_TEXTURE6                                     0x84C6
41 #define GL_TEXTURE7                                     0x84C7
42 #define GL_TEXTURE8                                     0x84C8
43 #define GL_TEXTURE9                                     0x84C9
44 #define GL_TEXTURE10                            0x84CA
45 #define GL_TEXTURE11                            0x84CB
46 #define GL_TEXTURE12                            0x84CC
47 #define GL_TEXTURE13                            0x84CD
48 #define GL_TEXTURE14                            0x84CE
49 #define GL_TEXTURE15                            0x84CF
50 #define GL_TEXTURE16                            0x84D0
51 #define GL_TEXTURE17                            0x84D1
52 #define GL_TEXTURE18                            0x84D2
53 #define GL_TEXTURE19                            0x84D3
54 #define GL_TEXTURE20                            0x84D4
55 #define GL_TEXTURE21                            0x84D5
56 #define GL_TEXTURE22                            0x84D6
57 #define GL_TEXTURE23                            0x84D7
58 #define GL_TEXTURE24                            0x84D8
59 #define GL_TEXTURE25                            0x84D9
60 #define GL_TEXTURE26                            0x84DA
61 #define GL_TEXTURE27                            0x84DB
62 #define GL_TEXTURE28                            0x84DC
63 #define GL_TEXTURE29                            0x84DD
64 #define GL_TEXTURE30                            0x84DE
65 #define GL_TEXTURE31                            0x84DF
66 #endif
67
68 #ifndef GL_TEXTURE_3D
69 #define GL_TEXTURE_3D                           0x806F
70 #endif
71 #ifndef GL_TEXTURE_CUBE_MAP
72 #define GL_TEXTURE_CUBE_MAP                 0x8513
73 #endif
74
75
76 #define MAX_RENDERTARGETS 4
77
78 cvar_t gl_paranoid = {0, "gl_paranoid", "0", "enables OpenGL error checking and other tests"};
79 cvar_t gl_printcheckerror = {0, "gl_printcheckerror", "0", "prints all OpenGL error checks, useful to identify location of driver crashes"};
80
81 cvar_t r_render = {0, "r_render", "1", "enables rendering 3D views (you want this on!)"};
82 cvar_t r_renderview = {0, "r_renderview", "1", "enables rendering 3D views (you want this on!)"};
83 cvar_t r_waterwarp = {CVAR_SAVE, "r_waterwarp", "1", "warp view while underwater"};
84 cvar_t gl_polyblend = {CVAR_SAVE, "gl_polyblend", "1", "tints view while underwater, hurt, etc"};
85 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1", "enables OpenGL dithering (16bit looks bad with this off)"};
86 cvar_t gl_fbo = {CVAR_SAVE, "gl_fbo", "1", "make use of GL_ARB_framebuffer_object extension to enable shadowmaps and other features using pixel formats different from the framebuffer"};
87
88 cvar_t v_flipped = {0, "v_flipped", "0", "mirror the screen (poor man's left handed mode)"};
89 qboolean v_flipped_state = false;
90
91 r_viewport_t gl_viewport;
92 matrix4x4_t gl_modelmatrix;
93 matrix4x4_t gl_viewmatrix;
94 matrix4x4_t gl_modelviewmatrix;
95 matrix4x4_t gl_projectionmatrix;
96 matrix4x4_t gl_modelviewprojectionmatrix;
97 float gl_modelview16f[16];
98 float gl_modelviewprojection16f[16];
99 qboolean gl_modelmatrixchanged;
100
101 int gl_maxdrawrangeelementsvertices;
102 int gl_maxdrawrangeelementsindices;
103
104 #ifdef DEBUGGL
105 int gl_errornumber = 0;
106
107 void GL_PrintError(int errornumber, const char *filename, int linenumber)
108 {
109         switch(errornumber)
110         {
111 #ifdef GL_INVALID_ENUM
112         case GL_INVALID_ENUM:
113                 Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
114                 break;
115 #endif
116 #ifdef GL_INVALID_VALUE
117         case GL_INVALID_VALUE:
118                 Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
119                 break;
120 #endif
121 #ifdef GL_INVALID_OPERATION
122         case GL_INVALID_OPERATION:
123                 Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
124                 break;
125 #endif
126 #ifdef GL_STACK_OVERFLOW
127         case GL_STACK_OVERFLOW:
128                 Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
129                 break;
130 #endif
131 #ifdef GL_STACK_UNDERFLOW
132         case GL_STACK_UNDERFLOW:
133                 Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
134                 break;
135 #endif
136 #ifdef GL_OUT_OF_MEMORY
137         case GL_OUT_OF_MEMORY:
138                 Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
139                 break;
140 #endif
141 #ifdef GL_TABLE_TOO_LARGE
142         case GL_TABLE_TOO_LARGE:
143                 Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
144                 break;
145 #endif
146 #ifdef GL_INVALID_FRAMEBUFFER_OPERATION
147         case GL_INVALID_FRAMEBUFFER_OPERATION:
148                 Con_Printf("GL_INVALID_FRAMEBUFFER_OPERATION at %s:%i\n", filename, linenumber);
149                 break;
150 #endif
151         default:
152                 Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
153                 break;
154         }
155 }
156 #endif
157
158 #define BACKENDACTIVECHECK if (!gl_state.active) Sys_Error("GL backend function called when backend is not active");
159
160 void SCR_ScreenShot_f (void);
161
162 typedef struct gltextureunit_s
163 {
164         int pointer_texcoord_components;
165         int pointer_texcoord_gltype;
166         size_t pointer_texcoord_stride;
167         const void *pointer_texcoord_pointer;
168         const r_meshbuffer_t *pointer_texcoord_vertexbuffer;
169         size_t pointer_texcoord_offset;
170
171         rtexture_t *texture;
172         int t2d, t3d, tcubemap;
173         int arrayenabled;
174         int rgbscale, alphascale;
175         int combine;
176         int combinergb, combinealpha;
177         // texmatrixenabled exists only to avoid unnecessary texmatrix compares
178         int texmatrixenabled;
179         matrix4x4_t matrix;
180 }
181 gltextureunit_t;
182
183 typedef struct gl_state_s
184 {
185         int cullface;
186         int cullfaceenable;
187         int blendfunc1;
188         int blendfunc2;
189         qboolean blend;
190         GLboolean depthmask;
191         int colormask; // stored as bottom 4 bits: r g b a (3 2 1 0 order)
192         int depthtest;
193         int depthfunc;
194         float depthrange[2];
195         float polygonoffset[2];
196         int alphatest;
197         int alphafunc;
198         float alphafuncvalue;
199         qboolean alphatocoverage;
200         int scissortest;
201         unsigned int unit;
202         unsigned int clientunit;
203         gltextureunit_t units[MAX_TEXTUREUNITS];
204         float color4f[4];
205         int lockrange_first;
206         int lockrange_count;
207         int vertexbufferobject;
208         int elementbufferobject;
209         int uniformbufferobject;
210         int framebufferobject;
211         int defaultframebufferobject; // deal with platforms that use a non-zero default fbo
212         qboolean pointer_color_enabled;
213
214         int pointer_vertex_components;
215         int pointer_vertex_gltype;
216         size_t pointer_vertex_stride;
217         const void *pointer_vertex_pointer;
218         const r_meshbuffer_t *pointer_vertex_vertexbuffer;
219         size_t pointer_vertex_offset;
220
221         int pointer_color_components;
222         int pointer_color_gltype;
223         size_t pointer_color_stride;
224         const void *pointer_color_pointer;
225         const r_meshbuffer_t *pointer_color_vertexbuffer;
226         size_t pointer_color_offset;
227
228         void *preparevertices_tempdata;
229         size_t preparevertices_tempdatamaxsize;
230         int preparevertices_numvertices;
231
232         memexpandablearray_t meshbufferarray;
233
234         qboolean active;
235 }
236 gl_state_t;
237
238 static gl_state_t gl_state;
239
240
241 /*
242 note: here's strip order for a terrain row:
243 0--1--2--3--4
244 |\ |\ |\ |\ |
245 | \| \| \| \|
246 A--B--C--D--E
247 clockwise
248
249 A0B, 01B, B1C, 12C, C2D, 23D, D3E, 34E
250
251 *elements++ = i + row;
252 *elements++ = i;
253 *elements++ = i + row + 1;
254 *elements++ = i;
255 *elements++ = i + 1;
256 *elements++ = i + row + 1;
257
258
259 for (y = 0;y < rows - 1;y++)
260 {
261         for (x = 0;x < columns - 1;x++)
262         {
263                 i = y * rows + x;
264                 *elements++ = i + columns;
265                 *elements++ = i;
266                 *elements++ = i + columns + 1;
267                 *elements++ = i;
268                 *elements++ = i + 1;
269                 *elements++ = i + columns + 1;
270         }
271 }
272
273 alternative:
274 0--1--2--3--4
275 | /| /|\ | /|
276 |/ |/ | \|/ |
277 A--B--C--D--E
278 counterclockwise
279
280 for (y = 0;y < rows - 1;y++)
281 {
282         for (x = 0;x < columns - 1;x++)
283         {
284                 i = y * rows + x;
285                 *elements++ = i;
286                 *elements++ = i + columns;
287                 *elements++ = i + columns + 1;
288                 *elements++ = i + columns;
289                 *elements++ = i + columns + 1;
290                 *elements++ = i + 1;
291         }
292 }
293 */
294
295 int polygonelement3i[(POLYGONELEMENTS_MAXPOINTS-2)*3];
296 unsigned short polygonelement3s[(POLYGONELEMENTS_MAXPOINTS-2)*3];
297 int quadelement3i[QUADELEMENTS_MAXQUADS*6];
298 unsigned short quadelement3s[QUADELEMENTS_MAXQUADS*6];
299
300 static void GL_VBOStats_f(void)
301 {
302         GL_Mesh_ListVBOs(true);
303 }
304
305 static void GL_Backend_ResetState(void);
306
307 static void gl_backend_start(void)
308 {
309         memset(&gl_state, 0, sizeof(gl_state));
310
311         Mem_ExpandableArray_NewArray(&gl_state.meshbufferarray, r_main_mempool, sizeof(r_meshbuffer_t), 128);
312
313         Con_DPrintf("OpenGL backend started.\n");
314
315         CHECKGLERROR
316
317         GL_Backend_ResetState();
318
319         switch(vid.renderpath)
320         {
321         case RENDERPATH_GL20:
322         case RENDERPATH_GLES2:
323                 // fetch current fbo here (default fbo is not 0 on some GLES devices)
324                 CHECKGLERROR
325                 qglGetIntegerv(GL_FRAMEBUFFER_BINDING, &gl_state.defaultframebufferobject);CHECKGLERROR
326                 break;
327         }
328 }
329
330 static void gl_backend_shutdown(void)
331 {
332         Con_DPrint("OpenGL Backend shutting down\n");
333
334         switch(vid.renderpath)
335         {
336         case RENDERPATH_GL20:
337         case RENDERPATH_GLES2:
338                 break;
339         }
340
341         if (gl_state.preparevertices_tempdata)
342                 Mem_Free(gl_state.preparevertices_tempdata);
343
344         Mem_ExpandableArray_FreeArray(&gl_state.meshbufferarray);
345
346         memset(&gl_state, 0, sizeof(gl_state));
347 }
348
349 static void gl_backend_newmap(void)
350 {
351 }
352
353 static void gl_backend_devicelost(void)
354 {
355         int i, endindex;
356         r_meshbuffer_t *buffer;
357         switch(vid.renderpath)
358         {
359         case RENDERPATH_GL20:
360         case RENDERPATH_GLES2:
361                 break;
362         }
363         endindex = (int)Mem_ExpandableArray_IndexRange(&gl_state.meshbufferarray);
364         for (i = 0;i < endindex;i++)
365         {
366                 buffer = (r_meshbuffer_t *) Mem_ExpandableArray_RecordAtIndex(&gl_state.meshbufferarray, i);
367                 if (!buffer || !buffer->isdynamic)
368                         continue;
369                 switch(vid.renderpath)
370                 {
371                 case RENDERPATH_GL20:
372                 case RENDERPATH_GLES2:
373                         break;
374                 }
375         }
376 }
377
378 static void gl_backend_devicerestored(void)
379 {
380         switch(vid.renderpath)
381         {
382         case RENDERPATH_GL20:
383         case RENDERPATH_GLES2:
384                 break;
385         }
386 }
387
388 void gl_backend_init(void)
389 {
390         int i;
391
392         for (i = 0;i < POLYGONELEMENTS_MAXPOINTS - 2;i++)
393         {
394                 polygonelement3s[i * 3 + 0] = 0;
395                 polygonelement3s[i * 3 + 1] = i + 1;
396                 polygonelement3s[i * 3 + 2] = i + 2;
397         }
398         // elements for rendering a series of quads as triangles
399         for (i = 0;i < QUADELEMENTS_MAXQUADS;i++)
400         {
401                 quadelement3s[i * 6 + 0] = i * 4;
402                 quadelement3s[i * 6 + 1] = i * 4 + 1;
403                 quadelement3s[i * 6 + 2] = i * 4 + 2;
404                 quadelement3s[i * 6 + 3] = i * 4;
405                 quadelement3s[i * 6 + 4] = i * 4 + 2;
406                 quadelement3s[i * 6 + 5] = i * 4 + 3;
407         }
408
409         for (i = 0;i < (POLYGONELEMENTS_MAXPOINTS - 2)*3;i++)
410                 polygonelement3i[i] = polygonelement3s[i];
411         for (i = 0;i < QUADELEMENTS_MAXQUADS*6;i++)
412                 quadelement3i[i] = quadelement3s[i];
413
414         Cvar_RegisterVariable(&r_render);
415         Cvar_RegisterVariable(&r_renderview);
416         Cvar_RegisterVariable(&r_waterwarp);
417         Cvar_RegisterVariable(&gl_polyblend);
418         Cvar_RegisterVariable(&v_flipped);
419         Cvar_RegisterVariable(&gl_dither);
420         Cvar_RegisterVariable(&gl_paranoid);
421         Cvar_RegisterVariable(&gl_printcheckerror);
422
423         Cmd_AddCommand("gl_vbostats", GL_VBOStats_f, "prints a list of all buffer objects (vertex data and triangle elements) and total video memory used by them");
424
425         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap, gl_backend_devicelost, gl_backend_devicerestored);
426 }
427
428 void GL_SetMirrorState(qboolean state);
429
430 void R_Viewport_TransformToScreen(const r_viewport_t *v, const vec4_t in, vec4_t out)
431 {
432         vec4_t temp;
433         float iw;
434         Matrix4x4_Transform4 (&v->viewmatrix, in, temp);
435         Matrix4x4_Transform4 (&v->projectmatrix, temp, out);
436         iw = 1.0f / out[3];
437         out[0] = v->x + (out[0] * iw + 1.0f) * v->width * 0.5f;
438
439         // for an odd reason, inverting this is wrong for R_Shadow_ScissorForBBox (we then get badly scissored lights)
440         //out[1] = v->y + v->height - (out[1] * iw + 1.0f) * v->height * 0.5f;
441         out[1] = v->y + (out[1] * iw + 1.0f) * v->height * 0.5f;
442
443         out[2] = v->z + (out[2] * iw + 1.0f) * v->depth * 0.5f;
444 }
445
446 void GL_Finish(void)
447 {
448         switch(vid.renderpath)
449         {
450         case RENDERPATH_GL20:
451         case RENDERPATH_GLES2:
452                 CHECKGLERROR
453                 qglFinish();CHECKGLERROR
454                 break;
455         }
456 }
457
458 static int bboxedges[12][2] =
459 {
460         // top
461         {0, 1}, // +X
462         {0, 2}, // +Y
463         {1, 3}, // Y, +X
464         {2, 3}, // X, +Y
465         // bottom
466         {4, 5}, // +X
467         {4, 6}, // +Y
468         {5, 7}, // Y, +X
469         {6, 7}, // X, +Y
470         // verticals
471         {0, 4}, // +Z
472         {1, 5}, // X, +Z
473         {2, 6}, // Y, +Z
474         {3, 7}, // XY, +Z
475 };
476
477 qboolean R_ScissorForBBox(const float *mins, const float *maxs, int *scissor)
478 {
479         int i, ix1, iy1, ix2, iy2;
480         float x1, y1, x2, y2;
481         vec4_t v, v2;
482         float vertex[20][3];
483         int j, k;
484         vec4_t plane4f;
485         int numvertices;
486         float corner[8][4];
487         float dist[8];
488         int sign[8];
489         float f;
490
491         scissor[0] = r_refdef.view.viewport.x;
492         scissor[1] = r_refdef.view.viewport.y;
493         scissor[2] = r_refdef.view.viewport.width;
494         scissor[3] = r_refdef.view.viewport.height;
495
496         // if view is inside the box, just say yes it's visible
497         if (BoxesOverlap(r_refdef.view.origin, r_refdef.view.origin, mins, maxs))
498                 return false;
499
500         // transform all corners that are infront of the nearclip plane
501         VectorNegate(r_refdef.view.frustum[4].normal, plane4f);
502         plane4f[3] = r_refdef.view.frustum[4].dist;
503         numvertices = 0;
504         for (i = 0;i < 8;i++)
505         {
506                 Vector4Set(corner[i], (i & 1) ? maxs[0] : mins[0], (i & 2) ? maxs[1] : mins[1], (i & 4) ? maxs[2] : mins[2], 1);
507                 dist[i] = DotProduct4(corner[i], plane4f);
508                 sign[i] = dist[i] > 0;
509                 if (!sign[i])
510                 {
511                         VectorCopy(corner[i], vertex[numvertices]);
512                         numvertices++;
513                 }
514         }
515         // if some points are behind the nearclip, add clipped edge points to make
516         // sure that the scissor boundary is complete
517         if (numvertices > 0 && numvertices < 8)
518         {
519                 // add clipped edge points
520                 for (i = 0;i < 12;i++)
521                 {
522                         j = bboxedges[i][0];
523                         k = bboxedges[i][1];
524                         if (sign[j] != sign[k])
525                         {
526                                 f = dist[j] / (dist[j] - dist[k]);
527                                 VectorLerp(corner[j], f, corner[k], vertex[numvertices]);
528                                 numvertices++;
529                         }
530                 }
531         }
532
533         // if we have no points to check, it is behind the view plane
534         if (!numvertices)
535                 return true;
536
537         // if we have some points to transform, check what screen area is covered
538         x1 = y1 = x2 = y2 = 0;
539         v[3] = 1.0f;
540         //Con_Printf("%i vertices to transform...\n", numvertices);
541         for (i = 0;i < numvertices;i++)
542         {
543                 VectorCopy(vertex[i], v);
544                 R_Viewport_TransformToScreen(&r_refdef.view.viewport, v, v2);
545                 //Con_Printf("%.3f %.3f %.3f %.3f transformed to %.3f %.3f %.3f %.3f\n", v[0], v[1], v[2], v[3], v2[0], v2[1], v2[2], v2[3]);
546                 if (i)
547                 {
548                         if (x1 > v2[0]) x1 = v2[0];
549                         if (x2 < v2[0]) x2 = v2[0];
550                         if (y1 > v2[1]) y1 = v2[1];
551                         if (y2 < v2[1]) y2 = v2[1];
552                 }
553                 else
554                 {
555                         x1 = x2 = v2[0];
556                         y1 = y2 = v2[1];
557                 }
558         }
559
560         // now convert the scissor rectangle to integer screen coordinates
561         ix1 = (int)(x1 - 1.0f);
562         //iy1 = vid.height - (int)(y2 - 1.0f);
563         //iy1 = r_refdef.view.viewport.width + 2 * r_refdef.view.viewport.x - (int)(y2 - 1.0f);
564         iy1 = (int)(y1 - 1.0f);
565         ix2 = (int)(x2 + 1.0f);
566         //iy2 = vid.height - (int)(y1 + 1.0f);
567         //iy2 = r_refdef.view.viewport.height + 2 * r_refdef.view.viewport.y - (int)(y1 + 1.0f);
568         iy2 = (int)(y2 + 1.0f);
569         //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2);
570
571         // clamp it to the screen
572         if (ix1 < r_refdef.view.viewport.x) ix1 = r_refdef.view.viewport.x;
573         if (iy1 < r_refdef.view.viewport.y) iy1 = r_refdef.view.viewport.y;
574         if (ix2 > r_refdef.view.viewport.x + r_refdef.view.viewport.width) ix2 = r_refdef.view.viewport.x + r_refdef.view.viewport.width;
575         if (iy2 > r_refdef.view.viewport.y + r_refdef.view.viewport.height) iy2 = r_refdef.view.viewport.y + r_refdef.view.viewport.height;
576
577         // if it is inside out, it's not visible
578         if (ix2 <= ix1 || iy2 <= iy1)
579                 return true;
580
581         // the light area is visible, set up the scissor rectangle
582         scissor[0] = ix1;
583         scissor[1] = iy1;
584         scissor[2] = ix2 - ix1;
585         scissor[3] = iy2 - iy1;
586
587         // D3D Y coordinate is top to bottom, OpenGL is bottom to top, fix the D3D one
588         switch(vid.renderpath)
589         {
590         case RENDERPATH_GL20:
591         case RENDERPATH_GLES2:
592                 break;
593         }
594
595         return false;
596 }
597
598
599 static void R_Viewport_ApplyNearClipPlaneFloatGL(const r_viewport_t *v, float *m, float normalx, float normaly, float normalz, float dist)
600 {
601         float q[4];
602         float d;
603         float clipPlane[4], v3[3], v4[3];
604         float normal[3];
605
606         // This is inspired by Oblique Depth Projection from http://www.terathon.com/code/oblique.php
607
608         VectorSet(normal, normalx, normaly, normalz);
609         Matrix4x4_Transform3x3(&v->viewmatrix, normal, clipPlane);
610         VectorScale(normal, -dist, v3);
611         Matrix4x4_Transform(&v->viewmatrix, v3, v4);
612         // FIXME: LordHavoc: I think this can be done more efficiently somehow but I can't remember the technique
613         clipPlane[3] = -DotProduct(v4, clipPlane);
614
615         // Calculate the clip-space corner point opposite the clipping plane
616         // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and
617         // transform it into camera space by multiplying it
618         // by the inverse of the projection matrix
619         q[0] = ((clipPlane[0] < 0.0f ? -1.0f : clipPlane[0] > 0.0f ? 1.0f : 0.0f) + m[8]) / m[0];
620         q[1] = ((clipPlane[1] < 0.0f ? -1.0f : clipPlane[1] > 0.0f ? 1.0f : 0.0f) + m[9]) / m[5];
621         q[2] = -1.0f;
622         q[3] = (1.0f + m[10]) / m[14];
623
624         // Calculate the scaled plane vector
625         d = 2.0f / DotProduct4(clipPlane, q);
626
627         // Replace the third row of the projection matrix
628         m[2] = clipPlane[0] * d;
629         m[6] = clipPlane[1] * d;
630         m[10] = clipPlane[2] * d + 1.0f;
631         m[14] = clipPlane[3] * d;
632 }
633
634 void R_Viewport_InitOrtho(r_viewport_t *v, const matrix4x4_t *cameramatrix, int x, int y, int width, int height, float x1, float y1, float x2, float y2, float nearclip, float farclip, const float *nearplane)
635 {
636         float left = x1, right = x2, bottom = y2, top = y1, zNear = nearclip, zFar = farclip;
637         float m[16];
638         memset(v, 0, sizeof(*v));
639         v->type = R_VIEWPORTTYPE_ORTHO;
640         v->cameramatrix = *cameramatrix;
641         v->x = x;
642         v->y = y;
643         v->z = 0;
644         v->width = width;
645         v->height = height;
646         v->depth = 1;
647         memset(m, 0, sizeof(m));
648         m[0]  = 2/(right - left);
649         m[5]  = 2/(top - bottom);
650         m[10] = -2/(zFar - zNear);
651         m[12] = - (right + left)/(right - left);
652         m[13] = - (top + bottom)/(top - bottom);
653         m[14] = - (zFar + zNear)/(zFar - zNear);
654         m[15] = 1;
655         switch(vid.renderpath)
656         {
657         case RENDERPATH_GL20:
658         case RENDERPATH_GLES2:
659                 break;
660         }
661         v->screentodepth[0] = -farclip / (farclip - nearclip);
662         v->screentodepth[1] = farclip * nearclip / (farclip - nearclip);
663
664         Matrix4x4_Invert_Full(&v->viewmatrix, &v->cameramatrix);
665
666         if (nearplane)
667                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
668
669         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
670
671 #if 0
672         {
673                 vec4_t test1;
674                 vec4_t test2;
675                 Vector4Set(test1, (x1+x2)*0.5f, (y1+y2)*0.5f, 0.0f, 1.0f);
676                 R_Viewport_TransformToScreen(v, test1, test2);
677                 Con_Printf("%f %f %f -> %f %f %f\n", test1[0], test1[1], test1[2], test2[0], test2[1], test2[2]);
678         }
679 #endif
680 }
681
682 void R_Viewport_InitOrtho3D(r_viewport_t *v, const matrix4x4_t *cameramatrix, int x, int y, int width, int height, float frustumx, float frustumy, float nearclip, float farclip, const float *nearplane)
683 {
684         matrix4x4_t tempmatrix, basematrix;
685         float m[16];
686         memset(v, 0, sizeof(*v));
687
688         v->type = R_VIEWPORTTYPE_PERSPECTIVE;
689         v->cameramatrix = *cameramatrix;
690         v->x = x;
691         v->y = y;
692         v->z = 0;
693         v->width = width;
694         v->height = height;
695         v->depth = 1;
696         memset(m, 0, sizeof(m));
697         m[0]  = 1.0 / frustumx;
698         m[5]  = 1.0 / frustumy;
699         m[10] = -2 / (farclip - nearclip);
700         m[14] = -(farclip + nearclip) / (farclip - nearclip);
701         m[15] = 1;
702         v->screentodepth[0] = -farclip / (farclip - nearclip);
703         v->screentodepth[1] = farclip * nearclip / (farclip - nearclip);
704
705         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
706         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
707         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
708         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
709
710         if (nearplane)
711                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
712
713         if(v_flipped.integer)
714         {
715                 m[0] = -m[0];
716                 m[4] = -m[4];
717                 m[8] = -m[8];
718                 m[12] = -m[12];
719         }
720
721         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
722 }
723
724 void R_Viewport_InitPerspective(r_viewport_t *v, const matrix4x4_t *cameramatrix, int x, int y, int width, int height, float frustumx, float frustumy, float nearclip, float farclip, const float *nearplane)
725 {
726         matrix4x4_t tempmatrix, basematrix;
727         float m[16];
728         memset(v, 0, sizeof(*v));
729
730         v->type = R_VIEWPORTTYPE_PERSPECTIVE;
731         v->cameramatrix = *cameramatrix;
732         v->x = x;
733         v->y = y;
734         v->z = 0;
735         v->width = width;
736         v->height = height;
737         v->depth = 1;
738         memset(m, 0, sizeof(m));
739         m[0]  = 1.0 / frustumx;
740         m[5]  = 1.0 / frustumy;
741         m[10] = -(farclip + nearclip) / (farclip - nearclip);
742         m[11] = -1;
743         m[14] = -2 * nearclip * farclip / (farclip - nearclip);
744         v->screentodepth[0] = -farclip / (farclip - nearclip);
745         v->screentodepth[1] = farclip * nearclip / (farclip - nearclip);
746
747         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
748         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
749         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
750         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
751
752         if (nearplane)
753                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
754
755         if(v_flipped.integer)
756         {
757                 m[0] = -m[0];
758                 m[4] = -m[4];
759                 m[8] = -m[8];
760                 m[12] = -m[12];
761         }
762
763         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
764 }
765
766 void R_Viewport_InitPerspectiveInfinite(r_viewport_t *v, const matrix4x4_t *cameramatrix, int x, int y, int width, int height, float frustumx, float frustumy, float nearclip, const float *nearplane)
767 {
768         matrix4x4_t tempmatrix, basematrix;
769         const float nudge = 1.0 - 1.0 / (1<<23);
770         float m[16];
771         memset(v, 0, sizeof(*v));
772
773         v->type = R_VIEWPORTTYPE_PERSPECTIVE_INFINITEFARCLIP;
774         v->cameramatrix = *cameramatrix;
775         v->x = x;
776         v->y = y;
777         v->z = 0;
778         v->width = width;
779         v->height = height;
780         v->depth = 1;
781         memset(m, 0, sizeof(m));
782         m[ 0] = 1.0 / frustumx;
783         m[ 5] = 1.0 / frustumy;
784         m[10] = -nudge;
785         m[11] = -1;
786         m[14] = -2 * nearclip * nudge;
787         v->screentodepth[0] = (m[10] + 1) * 0.5 - 1;
788         v->screentodepth[1] = m[14] * -0.5;
789
790         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
791         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
792         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
793         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
794
795         if (nearplane)
796                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
797
798         if(v_flipped.integer)
799         {
800                 m[0] = -m[0];
801                 m[4] = -m[4];
802                 m[8] = -m[8];
803                 m[12] = -m[12];
804         }
805
806         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
807 }
808
809 float cubeviewmatrix[6][16] =
810 {
811     // standard cubemap projections
812     { // +X
813          0, 0,-1, 0,
814          0,-1, 0, 0,
815         -1, 0, 0, 0,
816          0, 0, 0, 1,
817     },
818     { // -X
819          0, 0, 1, 0,
820          0,-1, 0, 0,
821          1, 0, 0, 0,
822          0, 0, 0, 1,
823     },
824     { // +Y
825          1, 0, 0, 0,
826          0, 0,-1, 0,
827          0, 1, 0, 0,
828          0, 0, 0, 1,
829     },
830     { // -Y
831          1, 0, 0, 0,
832          0, 0, 1, 0,
833          0,-1, 0, 0,
834          0, 0, 0, 1,
835     },
836     { // +Z
837          1, 0, 0, 0,
838          0,-1, 0, 0,
839          0, 0,-1, 0,
840          0, 0, 0, 1,
841     },
842     { // -Z
843         -1, 0, 0, 0,
844          0,-1, 0, 0,
845          0, 0, 1, 0,
846          0, 0, 0, 1,
847     },
848 };
849 float rectviewmatrix[6][16] =
850 {
851     // sign-preserving cubemap projections
852     { // +X
853          0, 0,-1, 0,
854          0, 1, 0, 0,
855          1, 0, 0, 0,
856          0, 0, 0, 1,
857     },
858     { // -X
859          0, 0, 1, 0,
860          0, 1, 0, 0,
861          1, 0, 0, 0,
862          0, 0, 0, 1,
863     },
864     { // +Y
865          1, 0, 0, 0,
866          0, 0,-1, 0,
867          0, 1, 0, 0,
868          0, 0, 0, 1,
869     },
870     { // -Y
871          1, 0, 0, 0,
872          0, 0, 1, 0,
873          0, 1, 0, 0,
874          0, 0, 0, 1,
875     },
876     { // +Z
877          1, 0, 0, 0,
878          0, 1, 0, 0,
879          0, 0,-1, 0,
880          0, 0, 0, 1,
881     },
882     { // -Z
883          1, 0, 0, 0,
884          0, 1, 0, 0,
885          0, 0, 1, 0,
886          0, 0, 0, 1,
887     },
888 };
889
890 void R_Viewport_InitCubeSideView(r_viewport_t *v, const matrix4x4_t *cameramatrix, int side, int size, float nearclip, float farclip, const float *nearplane)
891 {
892         matrix4x4_t tempmatrix, basematrix;
893         float m[16];
894         memset(v, 0, sizeof(*v));
895         v->type = R_VIEWPORTTYPE_PERSPECTIVECUBESIDE;
896         v->cameramatrix = *cameramatrix;
897         v->width = size;
898         v->height = size;
899         v->depth = 1;
900         memset(m, 0, sizeof(m));
901         m[0] = m[5] = 1.0f;
902         m[10] = -(farclip + nearclip) / (farclip - nearclip);
903         m[11] = -1;
904         m[14] = -2 * nearclip * farclip / (farclip - nearclip);
905
906         Matrix4x4_FromArrayFloatGL(&basematrix, cubeviewmatrix[side]);
907         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
908         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
909
910         if (nearplane)
911                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
912
913         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
914 }
915
916 void R_Viewport_InitRectSideView(r_viewport_t *v, const matrix4x4_t *cameramatrix, int side, int size, int border, float nearclip, float farclip, const float *nearplane, int offsetx, int offsety)
917 {
918         matrix4x4_t tempmatrix, basematrix;
919         float m[16];
920         memset(v, 0, sizeof(*v));
921         v->type = R_VIEWPORTTYPE_PERSPECTIVECUBESIDE;
922         v->cameramatrix = *cameramatrix;
923         v->x = offsetx + (side & 1) * size;
924         v->y = offsety + (side >> 1) * size;
925         v->width = size;
926         v->height = size;
927         v->depth = 1;
928         memset(m, 0, sizeof(m));
929         m[0] = m[5] = 1.0f * ((float)size - border) / size;
930         m[10] = -(farclip + nearclip) / (farclip - nearclip);
931         m[11] = -1;
932         m[14] = -2 * nearclip * farclip / (farclip - nearclip);
933
934         Matrix4x4_FromArrayFloatGL(&basematrix, rectviewmatrix[side]);
935         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
936         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
937
938         if (nearplane)
939                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
940
941         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
942 }
943
944 void R_SetViewport(const r_viewport_t *v)
945 {
946         gl_viewport = *v;
947
948         // FIXME: v_flipped_state is evil, this probably breaks somewhere
949         GL_SetMirrorState(v_flipped.integer && (v->type == R_VIEWPORTTYPE_PERSPECTIVE || v->type == R_VIEWPORTTYPE_PERSPECTIVE_INFINITEFARCLIP));
950
951         // copy over the matrices to our state
952         gl_viewmatrix = v->viewmatrix;
953         gl_projectionmatrix = v->projectmatrix;
954
955         switch(vid.renderpath)
956         {
957         case RENDERPATH_GL20:
958         case RENDERPATH_GLES2:
959                 CHECKGLERROR
960                 qglViewport(v->x, v->y, v->width, v->height);CHECKGLERROR
961                 break;
962         }
963
964         // force an update of the derived matrices
965         gl_modelmatrixchanged = true;
966         R_EntityMatrix(&gl_modelmatrix);
967 }
968
969 void R_GetViewport(r_viewport_t *v)
970 {
971         *v = gl_viewport;
972 }
973
974 static void GL_BindVBO(int bufferobject)
975 {
976         if (gl_state.vertexbufferobject != bufferobject)
977         {
978                 gl_state.vertexbufferobject = bufferobject;
979                 CHECKGLERROR
980                 qglBindBuffer(GL_ARRAY_BUFFER, bufferobject);CHECKGLERROR
981         }
982 }
983
984 static void GL_BindEBO(int bufferobject)
985 {
986         if (gl_state.elementbufferobject != bufferobject)
987         {
988                 gl_state.elementbufferobject = bufferobject;
989                 CHECKGLERROR
990                 qglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferobject);CHECKGLERROR
991         }
992 }
993
994 static void GL_BindUBO(int bufferobject)
995 {
996         if (gl_state.uniformbufferobject != bufferobject)
997         {
998                 gl_state.uniformbufferobject = bufferobject;
999 #ifdef GL_UNIFORM_BUFFER
1000                 CHECKGLERROR
1001                 qglBindBuffer(GL_UNIFORM_BUFFER, bufferobject);CHECKGLERROR
1002 #endif
1003         }
1004 }
1005
1006 static const GLuint drawbuffers[4] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3};
1007 int R_Mesh_CreateFramebufferObject(rtexture_t *depthtexture, rtexture_t *colortexture, rtexture_t *colortexture2, rtexture_t *colortexture3, rtexture_t *colortexture4)
1008 {
1009         int temp;
1010         GLuint status;
1011         switch(vid.renderpath)
1012         {
1013         case RENDERPATH_GL20:
1014         case RENDERPATH_GLES2:
1015                 CHECKGLERROR
1016                 qglGenFramebuffers(1, (GLuint*)&temp);CHECKGLERROR
1017                 R_Mesh_SetRenderTargets(temp, NULL, NULL, NULL, NULL, NULL);
1018                 // GL_ARB_framebuffer_object (GL3-class hardware) - depth stencil attachment
1019 #ifdef USE_GLES2
1020                 // FIXME: separate stencil attachment on GLES
1021                 if (depthtexture  && depthtexture->texnum ) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , depthtexture->gltexturetypeenum , depthtexture->texnum , 0);CHECKGLERROR
1022                 if (depthtexture  && depthtexture->renderbuffernum ) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , GL_RENDERBUFFER, depthtexture->renderbuffernum );CHECKGLERROR
1023 #else
1024                 if (depthtexture  && depthtexture->texnum )
1025                 {
1026                         qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , depthtexture->gltexturetypeenum , depthtexture->texnum , 0);CHECKGLERROR
1027                         if (depthtexture->glisdepthstencil) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT  , depthtexture->gltexturetypeenum , depthtexture->texnum , 0);CHECKGLERROR
1028                 }
1029                 if (depthtexture  && depthtexture->renderbuffernum )
1030                 {
1031                         qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , GL_RENDERBUFFER, depthtexture->renderbuffernum );CHECKGLERROR
1032                         if (depthtexture->glisdepthstencil) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT  , GL_RENDERBUFFER, depthtexture->renderbuffernum );CHECKGLERROR
1033                 }
1034 #endif
1035                 if (colortexture  && colortexture->texnum ) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 , colortexture->gltexturetypeenum , colortexture->texnum , 0);CHECKGLERROR
1036                 if (colortexture2 && colortexture2->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1 , colortexture2->gltexturetypeenum, colortexture2->texnum, 0);CHECKGLERROR
1037                 if (colortexture3 && colortexture3->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2 , colortexture3->gltexturetypeenum, colortexture3->texnum, 0);CHECKGLERROR
1038                 if (colortexture4 && colortexture4->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3 , colortexture4->gltexturetypeenum, colortexture4->texnum, 0);CHECKGLERROR
1039                 if (colortexture  && colortexture->renderbuffernum ) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 , GL_RENDERBUFFER, colortexture->renderbuffernum );CHECKGLERROR
1040                 if (colortexture2 && colortexture2->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1 , GL_RENDERBUFFER, colortexture2->renderbuffernum);CHECKGLERROR
1041                 if (colortexture3 && colortexture3->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2 , GL_RENDERBUFFER, colortexture3->renderbuffernum);CHECKGLERROR
1042                 if (colortexture4 && colortexture4->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3 , GL_RENDERBUFFER, colortexture4->renderbuffernum);CHECKGLERROR
1043
1044 #ifndef USE_GLES2
1045                 if (colortexture4 && qglDrawBuffersARB)
1046                 {
1047                         qglDrawBuffersARB(4, drawbuffers);CHECKGLERROR
1048                         qglReadBuffer(GL_NONE);CHECKGLERROR
1049                 }
1050                 else if (colortexture3 && qglDrawBuffersARB)
1051                 {
1052                         qglDrawBuffersARB(3, drawbuffers);CHECKGLERROR
1053                         qglReadBuffer(GL_NONE);CHECKGLERROR
1054                 }
1055                 else if (colortexture2 && qglDrawBuffersARB)
1056                 {
1057                         qglDrawBuffersARB(2, drawbuffers);CHECKGLERROR
1058                         qglReadBuffer(GL_NONE);CHECKGLERROR
1059                 }
1060                 else if (colortexture && qglDrawBuffer)
1061                 {
1062                         qglDrawBuffer(GL_COLOR_ATTACHMENT0);CHECKGLERROR
1063                         qglReadBuffer(GL_COLOR_ATTACHMENT0);CHECKGLERROR
1064                 }
1065                 else if (qglDrawBuffer)
1066                 {
1067                         qglDrawBuffer(GL_NONE);CHECKGLERROR
1068                         qglReadBuffer(GL_NONE);CHECKGLERROR
1069                 }
1070 #endif
1071                 status = qglCheckFramebufferStatus(GL_FRAMEBUFFER);CHECKGLERROR
1072                 if (status != GL_FRAMEBUFFER_COMPLETE)
1073                 {
1074                         Con_Printf("R_Mesh_CreateFramebufferObject: glCheckFramebufferStatus returned %i\n", status);
1075                         gl_state.framebufferobject = 0; // GL unbinds it for us
1076                         qglDeleteFramebuffers(1, (GLuint*)&temp);CHECKGLERROR
1077                         temp = 0;
1078                 }
1079                 return temp;
1080         }
1081         return 0;
1082 }
1083
1084 void R_Mesh_DestroyFramebufferObject(int fbo)
1085 {
1086         switch(vid.renderpath)
1087         {
1088         case RENDERPATH_GL20:
1089         case RENDERPATH_GLES2:
1090                 if (fbo)
1091                 {
1092                         // GL clears the binding if we delete something bound
1093                         if (gl_state.framebufferobject == fbo)
1094                                 gl_state.framebufferobject = 0;
1095                         qglDeleteFramebuffers(1, (GLuint*)&fbo);CHECKGLERROR
1096                 }
1097                 break;
1098         }
1099 }
1100
1101 void R_Mesh_SetRenderTargets(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture, rtexture_t *colortexture2, rtexture_t *colortexture3, rtexture_t *colortexture4)
1102 {
1103         unsigned int i;
1104         unsigned int j;
1105         rtexture_t *textures[5];
1106         Vector4Set(textures, colortexture, colortexture2, colortexture3, colortexture4);
1107         textures[4] = depthtexture;
1108         // unbind any matching textures immediately, otherwise D3D will complain about a bound texture being used as a render target
1109         for (j = 0;j < 5;j++)
1110                 if (textures[j])
1111                         for (i = 0;i < vid.teximageunits;i++)
1112                                 if (gl_state.units[i].texture == textures[j])
1113                                         R_Mesh_TexBind(i, NULL);
1114         // set up framebuffer object or render targets for the active rendering API
1115         switch (vid.renderpath)
1116         {
1117         case RENDERPATH_GL20:
1118         case RENDERPATH_GLES2:
1119                 if (gl_state.framebufferobject != fbo)
1120                 {
1121                         gl_state.framebufferobject = fbo;
1122                         qglBindFramebuffer(GL_FRAMEBUFFER, gl_state.framebufferobject ? gl_state.framebufferobject : gl_state.defaultframebufferobject);CHECKGLERROR
1123                 }
1124                 break;
1125         }
1126 }
1127
1128 static void GL_Backend_ResetState(void)
1129 {
1130         unsigned int i;
1131         gl_state.active = true;
1132         gl_state.depthtest = true;
1133         gl_state.alphatest = false;
1134         gl_state.alphafunc = GL_GEQUAL;
1135         gl_state.alphafuncvalue = 0.5f;
1136         gl_state.alphatocoverage = false;
1137         gl_state.blendfunc1 = GL_ONE;
1138         gl_state.blendfunc2 = GL_ZERO;
1139         gl_state.blend = false;
1140         gl_state.depthmask = GL_TRUE;
1141         gl_state.colormask = 15;
1142         gl_state.color4f[0] = gl_state.color4f[1] = gl_state.color4f[2] = gl_state.color4f[3] = 1;
1143         gl_state.lockrange_first = 0;
1144         gl_state.lockrange_count = 0;
1145         gl_state.cullface = GL_FRONT;
1146         gl_state.cullfaceenable = false;
1147         gl_state.polygonoffset[0] = 0;
1148         gl_state.polygonoffset[1] = 0;
1149         gl_state.framebufferobject = 0;
1150         gl_state.depthfunc = GL_LEQUAL;
1151
1152         switch(vid.renderpath)
1153         {
1154         case RENDERPATH_GL20:
1155         case RENDERPATH_GLES2:
1156                 CHECKGLERROR
1157                 qglColorMask(1, 1, 1, 1);CHECKGLERROR
1158                 qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
1159                 qglDisable(GL_BLEND);CHECKGLERROR
1160                 qglCullFace(gl_state.cullface);CHECKGLERROR
1161                 qglDisable(GL_CULL_FACE);CHECKGLERROR
1162                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
1163                 qglEnable(GL_DEPTH_TEST);CHECKGLERROR
1164                 qglDepthMask(gl_state.depthmask);CHECKGLERROR
1165                 qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
1166                 qglBindBuffer(GL_ARRAY_BUFFER, 0);
1167                 qglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
1168                 qglBindFramebuffer(GL_FRAMEBUFFER, gl_state.defaultframebufferobject);
1169                 qglEnableVertexAttribArray(GLSLATTRIB_POSITION);
1170                 qglDisableVertexAttribArray(GLSLATTRIB_COLOR);
1171                 qglVertexAttrib4f(GLSLATTRIB_COLOR, 1, 1, 1, 1);
1172                 gl_state.unit = MAX_TEXTUREUNITS;
1173                 gl_state.clientunit = MAX_TEXTUREUNITS;
1174                 for (i = 0;i < vid.teximageunits;i++)
1175                 {
1176                         GL_ActiveTexture(i);
1177                         qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
1178                         qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
1179                         qglBindTexture(GL_TEXTURE_CUBE_MAP, 0);CHECKGLERROR
1180                 }
1181                 for (i = 0;i < vid.texarrayunits;i++)
1182                 {
1183                         GL_BindVBO(0);
1184                         qglDisableVertexAttribArray(i+GLSLATTRIB_TEXCOORD0);CHECKGLERROR
1185                 }
1186                 CHECKGLERROR
1187                 break;
1188         }
1189 }
1190
1191 void GL_ActiveTexture(unsigned int num)
1192 {
1193         if (gl_state.unit != num)
1194         {
1195                 gl_state.unit = num;
1196                 switch(vid.renderpath)
1197                 {
1198                 case RENDERPATH_GL20:
1199                 case RENDERPATH_GLES2:
1200                         CHECKGLERROR
1201                         qglActiveTexture(GL_TEXTURE0 + gl_state.unit);CHECKGLERROR
1202                         break;
1203                 }
1204         }
1205 }
1206
1207 void GL_BlendFunc(int blendfunc1, int blendfunc2)
1208 {
1209         if (gl_state.blendfunc1 != blendfunc1 || gl_state.blendfunc2 != blendfunc2)
1210         {
1211                 qboolean blendenable;
1212                 gl_state.blendfunc1 = blendfunc1;
1213                 gl_state.blendfunc2 = blendfunc2;
1214                 blendenable = (gl_state.blendfunc1 != GL_ONE || gl_state.blendfunc2 != GL_ZERO);
1215                 switch(vid.renderpath)
1216                 {
1217                 case RENDERPATH_GL20:
1218                 case RENDERPATH_GLES2:
1219                         CHECKGLERROR
1220                         if (qglBlendFuncSeparate)
1221                         {
1222                                 qglBlendFuncSeparate(gl_state.blendfunc1, gl_state.blendfunc2, GL_ZERO, GL_ONE);CHECKGLERROR // ELUAN: Adreno 225 (and others) compositing workaround
1223                         }
1224                         else
1225                         {
1226                                 qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
1227                         }
1228                         if (gl_state.blend != blendenable)
1229                         {
1230                                 gl_state.blend = blendenable;
1231                                 if (!gl_state.blend)
1232                                 {
1233                                         qglDisable(GL_BLEND);CHECKGLERROR
1234                                 }
1235                                 else
1236                                 {
1237                                         qglEnable(GL_BLEND);CHECKGLERROR
1238                                 }
1239                         }
1240                         break;
1241                 }
1242         }
1243 }
1244
1245 void GL_DepthMask(int state)
1246 {
1247         if (gl_state.depthmask != state)
1248         {
1249                 gl_state.depthmask = state;
1250                 switch(vid.renderpath)
1251                 {
1252                 case RENDERPATH_GL20:
1253                 case RENDERPATH_GLES2:
1254                         CHECKGLERROR
1255                         qglDepthMask(gl_state.depthmask);CHECKGLERROR
1256                         break;
1257                 }
1258         }
1259 }
1260
1261 void GL_DepthTest(int state)
1262 {
1263         if (gl_state.depthtest != state)
1264         {
1265                 gl_state.depthtest = state;
1266                 switch(vid.renderpath)
1267                 {
1268                 case RENDERPATH_GL20:
1269                 case RENDERPATH_GLES2:
1270                         CHECKGLERROR
1271                         if (gl_state.depthtest)
1272                         {
1273                                 qglEnable(GL_DEPTH_TEST);CHECKGLERROR
1274                         }
1275                         else
1276                         {
1277                                 qglDisable(GL_DEPTH_TEST);CHECKGLERROR
1278                         }
1279                         break;
1280                 }
1281         }
1282 }
1283
1284 void GL_DepthFunc(int state)
1285 {
1286         if (gl_state.depthfunc != state)
1287         {
1288                 gl_state.depthfunc = state;
1289                 switch(vid.renderpath)
1290                 {
1291                 case RENDERPATH_GL20:
1292                 case RENDERPATH_GLES2:
1293                         CHECKGLERROR
1294                         qglDepthFunc(gl_state.depthfunc);CHECKGLERROR
1295                         break;
1296                 }
1297         }
1298 }
1299
1300 void GL_DepthRange(float nearfrac, float farfrac)
1301 {
1302         if (gl_state.depthrange[0] != nearfrac || gl_state.depthrange[1] != farfrac)
1303         {
1304                 gl_state.depthrange[0] = nearfrac;
1305                 gl_state.depthrange[1] = farfrac;
1306                 switch(vid.renderpath)
1307                 {
1308                 case RENDERPATH_GL20:
1309                 case RENDERPATH_GLES2:
1310                         CHECKGLERROR
1311 #ifdef USE_GLES2
1312                         qglDepthRangef(gl_state.depthrange[0], gl_state.depthrange[1]);CHECKGLERROR
1313 #else
1314                         qglDepthRange(gl_state.depthrange[0], gl_state.depthrange[1]);CHECKGLERROR
1315 #endif
1316                         break;
1317                 }
1318         }
1319 }
1320
1321 void R_SetStencil(qboolean enable, int writemask, int fail, int zfail, int zpass, int compare, int comparereference, int comparemask)
1322 {
1323         switch (vid.renderpath)
1324         {
1325         case RENDERPATH_GL20:
1326         case RENDERPATH_GLES2:
1327                 CHECKGLERROR
1328                 if (enable)
1329                 {
1330                         qglEnable(GL_STENCIL_TEST);CHECKGLERROR
1331                 }
1332                 else
1333                 {
1334                         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
1335                 }
1336                 qglStencilMask(writemask);CHECKGLERROR
1337                 qglStencilOp(fail, zfail, zpass);CHECKGLERROR
1338                 qglStencilFunc(compare, comparereference, comparemask);CHECKGLERROR
1339                 CHECKGLERROR
1340                 break;
1341         }
1342 }
1343
1344 void GL_PolygonOffset(float planeoffset, float depthoffset)
1345 {
1346         if (gl_state.polygonoffset[0] != planeoffset || gl_state.polygonoffset[1] != depthoffset)
1347         {
1348                 gl_state.polygonoffset[0] = planeoffset;
1349                 gl_state.polygonoffset[1] = depthoffset;
1350                 switch(vid.renderpath)
1351                 {
1352                 case RENDERPATH_GL20:
1353                 case RENDERPATH_GLES2:
1354                         CHECKGLERROR
1355                         qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);CHECKGLERROR
1356                         break;
1357                 }
1358         }
1359 }
1360
1361 void GL_SetMirrorState(qboolean state)
1362 {
1363         if (v_flipped_state != state)
1364         {
1365                 v_flipped_state = state;
1366                 if (gl_state.cullface == GL_BACK)
1367                         gl_state.cullface = GL_FRONT;
1368                 else if (gl_state.cullface == GL_FRONT)
1369                         gl_state.cullface = GL_BACK;
1370                 else
1371                         return;
1372                 switch(vid.renderpath)
1373                 {
1374                 case RENDERPATH_GL20:
1375                 case RENDERPATH_GLES2:
1376                         CHECKGLERROR
1377                         qglCullFace(gl_state.cullface);CHECKGLERROR
1378                         break;
1379                 }
1380         }
1381 }
1382
1383 void GL_CullFace(int state)
1384 {
1385         if(v_flipped_state)
1386         {
1387                 if(state == GL_FRONT)
1388                         state = GL_BACK;
1389                 else if(state == GL_BACK)
1390                         state = GL_FRONT;
1391         }
1392
1393         switch(vid.renderpath)
1394         {
1395         case RENDERPATH_GL20:
1396         case RENDERPATH_GLES2:
1397                 CHECKGLERROR
1398
1399                 if (state != GL_NONE)
1400                 {
1401                         if (!gl_state.cullfaceenable)
1402                         {
1403                                 gl_state.cullfaceenable = true;
1404                                 qglEnable(GL_CULL_FACE);CHECKGLERROR
1405                         }
1406                         if (gl_state.cullface != state)
1407                         {
1408                                 gl_state.cullface = state;
1409                                 qglCullFace(gl_state.cullface);CHECKGLERROR
1410                         }
1411                 }
1412                 else
1413                 {
1414                         if (gl_state.cullfaceenable)
1415                         {
1416                                 gl_state.cullfaceenable = false;
1417                                 qglDisable(GL_CULL_FACE);CHECKGLERROR
1418                         }
1419                 }
1420                 break;
1421         }
1422 }
1423
1424 void GL_AlphaToCoverage(qboolean state)
1425 {
1426         if (gl_state.alphatocoverage != state)
1427         {
1428                 gl_state.alphatocoverage = state;
1429                 switch(vid.renderpath)
1430                 {
1431                 case RENDERPATH_GLES2:
1432                         break;
1433                 case RENDERPATH_GL20:
1434 #ifdef GL_SAMPLE_ALPHA_TO_COVERAGE_ARB
1435                         // alpha to coverage turns the alpha value of the pixel into 0%, 25%, 50%, 75% or 100% by masking the multisample fragments accordingly
1436                         CHECKGLERROR
1437                         if (gl_state.alphatocoverage)
1438                         {
1439                                 qglEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);CHECKGLERROR
1440 //                              qglEnable(GL_MULTISAMPLE_ARB);CHECKGLERROR
1441                         }
1442                         else
1443                         {
1444                                 qglDisable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);CHECKGLERROR
1445 //                              qglDisable(GL_MULTISAMPLE_ARB);CHECKGLERROR
1446                         }
1447 #endif
1448                         break;
1449                 }
1450         }
1451 }
1452
1453 void GL_ColorMask(int r, int g, int b, int a)
1454 {
1455         // NOTE: this matches D3DCOLORWRITEENABLE_RED, GREEN, BLUE, ALPHA
1456         int state = (r ? 1 : 0) | (g ? 2 : 0) | (b ? 4 : 0) | (a ? 8 : 0);
1457         if (gl_state.colormask != state)
1458         {
1459                 gl_state.colormask = state;
1460                 switch(vid.renderpath)
1461                 {
1462                 case RENDERPATH_GL20:
1463                 case RENDERPATH_GLES2:
1464                         CHECKGLERROR
1465                         qglColorMask((GLboolean)r, (GLboolean)g, (GLboolean)b, (GLboolean)a);CHECKGLERROR
1466                         break;
1467                 }
1468         }
1469 }
1470
1471 void GL_Color(float cr, float cg, float cb, float ca)
1472 {
1473         if (gl_state.pointer_color_enabled || gl_state.color4f[0] != cr || gl_state.color4f[1] != cg || gl_state.color4f[2] != cb || gl_state.color4f[3] != ca)
1474         {
1475                 gl_state.color4f[0] = cr;
1476                 gl_state.color4f[1] = cg;
1477                 gl_state.color4f[2] = cb;
1478                 gl_state.color4f[3] = ca;
1479                 switch(vid.renderpath)
1480                 {
1481                 case RENDERPATH_GL20:
1482                 case RENDERPATH_GLES2:
1483                         qglVertexAttrib4f(GLSLATTRIB_COLOR, cr, cg, cb, ca);CHECKGLERROR
1484                         break;
1485                 }
1486         }
1487 }
1488
1489 void GL_Scissor (int x, int y, int width, int height)
1490 {
1491         switch(vid.renderpath)
1492         {
1493         case RENDERPATH_GL20:
1494         case RENDERPATH_GLES2:
1495                 CHECKGLERROR
1496                 qglScissor(x, y,width,height);CHECKGLERROR
1497                 break;
1498         }
1499 }
1500
1501 void GL_ScissorTest(int state)
1502 {
1503         if (gl_state.scissortest != state)
1504         {
1505                 gl_state.scissortest = state;
1506                 switch(vid.renderpath)
1507                 {
1508                 case RENDERPATH_GL20:
1509                 case RENDERPATH_GLES2:
1510                         CHECKGLERROR
1511                         if(gl_state.scissortest)
1512                                 qglEnable(GL_SCISSOR_TEST);
1513                         else
1514                                 qglDisable(GL_SCISSOR_TEST);
1515                         CHECKGLERROR
1516                         break;
1517                 }
1518         }
1519 }
1520
1521 void GL_Clear(int mask, const float *colorvalue, float depthvalue, int stencilvalue)
1522 {
1523         // opaque black - if you want transparent black, you'll need to pass in a colorvalue
1524         static const float blackcolor[4] = {0.0f, 0.0f, 0.0f, 1.0f};
1525         // prevent warnings when trying to clear a buffer that does not exist
1526         if (!colorvalue)
1527                 colorvalue = blackcolor;
1528         if (!vid.stencil)
1529         {
1530                 mask &= ~GL_STENCIL_BUFFER_BIT;
1531                 stencilvalue = 0;
1532         }
1533         switch(vid.renderpath)
1534         {
1535         case RENDERPATH_GL20:
1536         case RENDERPATH_GLES2:
1537                 CHECKGLERROR
1538                 if (mask & GL_COLOR_BUFFER_BIT)
1539                 {
1540                         qglClearColor(colorvalue[0], colorvalue[1], colorvalue[2], colorvalue[3]);CHECKGLERROR
1541                 }
1542                 if (mask & GL_DEPTH_BUFFER_BIT)
1543                 {
1544 #ifdef USE_GLES2
1545                         qglClearDepthf(depthvalue);CHECKGLERROR
1546 #else
1547                         qglClearDepth(depthvalue);CHECKGLERROR
1548 #endif
1549                 }
1550                 if (mask & GL_STENCIL_BUFFER_BIT)
1551                 {
1552                         qglClearStencil(stencilvalue);CHECKGLERROR
1553                 }
1554                 qglClear(mask);CHECKGLERROR
1555                 break;
1556         }
1557 }
1558
1559 void GL_ReadPixelsBGRA(int x, int y, int width, int height, unsigned char *outpixels)
1560 {
1561         switch(vid.renderpath)
1562         {
1563         case RENDERPATH_GL20:
1564         case RENDERPATH_GLES2:
1565                 CHECKGLERROR
1566 #ifndef GL_BGRA
1567                 {
1568                         int i;
1569                         int r;
1570                 //      int g;
1571                         int b;
1572                 //      int a;
1573                         qglReadPixels(x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, outpixels);CHECKGLERROR
1574                         for (i = 0;i < width * height * 4;i += 4)
1575                         {
1576                                 r = outpixels[i+0];
1577                 //              g = outpixels[i+1];
1578                                 b = outpixels[i+2];
1579                 //              a = outpixels[i+3];
1580                                 outpixels[i+0] = b;
1581                 //              outpixels[i+1] = g;
1582                                 outpixels[i+2] = r;
1583                 //              outpixels[i+3] = a;
1584                         }
1585                 }
1586 #else
1587                 qglReadPixels(x, y, width, height, GL_BGRA, GL_UNSIGNED_BYTE, outpixels);CHECKGLERROR
1588 #endif
1589                         break;
1590         }
1591 }
1592
1593 // called at beginning of frame
1594 void R_Mesh_Start(void)
1595 {
1596         BACKENDACTIVECHECK
1597         R_Mesh_SetRenderTargets(0, NULL, NULL, NULL, NULL, NULL);
1598         if (gl_printcheckerror.integer && !gl_paranoid.integer)
1599         {
1600                 Con_Printf("WARNING: gl_printcheckerror is on but gl_paranoid is off, turning it on...\n");
1601                 Cvar_SetValueQuick(&gl_paranoid, 1);
1602         }
1603 }
1604
1605 static qboolean GL_Backend_CompileShader(int programobject, GLenum shadertypeenum, const char *shadertype, int numstrings, const char **strings)
1606 {
1607         int shaderobject;
1608         int shadercompiled;
1609         char compilelog[MAX_INPUTLINE];
1610         shaderobject = qglCreateShader(shadertypeenum);CHECKGLERROR
1611         if (!shaderobject)
1612                 return false;
1613         qglShaderSource(shaderobject, numstrings, strings, NULL);CHECKGLERROR
1614         qglCompileShader(shaderobject);CHECKGLERROR
1615         qglGetShaderiv(shaderobject, GL_COMPILE_STATUS, &shadercompiled);CHECKGLERROR
1616         qglGetShaderInfoLog(shaderobject, sizeof(compilelog), NULL, compilelog);CHECKGLERROR
1617         if (compilelog[0] && ((strstr(compilelog, "error") || strstr(compilelog, "ERROR") || strstr(compilelog, "Error")) || ((strstr(compilelog, "WARNING") || strstr(compilelog, "warning") || strstr(compilelog, "Warning")) && developer.integer) || developer_extra.integer))
1618         {
1619                 int i, j, pretextlines = 0;
1620                 for (i = 0;i < numstrings - 1;i++)
1621                         for (j = 0;strings[i][j];j++)
1622                                 if (strings[i][j] == '\n')
1623                                         pretextlines++;
1624                 Con_Printf("%s shader compile log:\n%s\n(line offset for any above warnings/errors: %i)\n", shadertype, compilelog, pretextlines);
1625         }
1626         if (!shadercompiled)
1627         {
1628                 qglDeleteShader(shaderobject);CHECKGLERROR
1629                 return false;
1630         }
1631         qglAttachShader(programobject, shaderobject);CHECKGLERROR
1632         qglDeleteShader(shaderobject);CHECKGLERROR
1633         return true;
1634 }
1635
1636 unsigned int GL_Backend_CompileProgram(int vertexstrings_count, const char **vertexstrings_list, int geometrystrings_count, const char **geometrystrings_list, int fragmentstrings_count, const char **fragmentstrings_list)
1637 {
1638         GLint programlinked;
1639         GLuint programobject = 0;
1640         char linklog[MAX_INPUTLINE];
1641         CHECKGLERROR
1642
1643         programobject = qglCreateProgram();CHECKGLERROR
1644         if (!programobject)
1645                 return 0;
1646
1647         qglBindAttribLocation(programobject, GLSLATTRIB_POSITION , "Attrib_Position" );
1648         qglBindAttribLocation(programobject, GLSLATTRIB_COLOR    , "Attrib_Color"    );
1649         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD0, "Attrib_TexCoord0");
1650         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD1, "Attrib_TexCoord1");
1651         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD2, "Attrib_TexCoord2");
1652         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD3, "Attrib_TexCoord3");
1653         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD4, "Attrib_TexCoord4");
1654         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD5, "Attrib_TexCoord5");
1655         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD6, "Attrib_SkeletalIndex");
1656         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD7, "Attrib_SkeletalWeight");
1657 #ifndef USE_GLES2
1658         if(vid.support.gl20shaders130)
1659                 qglBindFragDataLocation(programobject, 0, "dp_FragColor");
1660 #endif
1661         CHECKGLERROR
1662
1663         if (vertexstrings_count && !GL_Backend_CompileShader(programobject, GL_VERTEX_SHADER, "vertex", vertexstrings_count, vertexstrings_list))
1664                 goto cleanup;
1665
1666 #if defined(GL_GEOMETRY_SHADER) && !defined(USE_GLES2)
1667         if (geometrystrings_count && !GL_Backend_CompileShader(programobject, GL_GEOMETRY_SHADER, "geometry", geometrystrings_count, geometrystrings_list))
1668                 goto cleanup;
1669 #endif
1670
1671         if (fragmentstrings_count && !GL_Backend_CompileShader(programobject, GL_FRAGMENT_SHADER, "fragment", fragmentstrings_count, fragmentstrings_list))
1672                 goto cleanup;
1673
1674         qglLinkProgram(programobject);CHECKGLERROR
1675         qglGetProgramiv(programobject, GL_LINK_STATUS, &programlinked);CHECKGLERROR
1676         qglGetProgramInfoLog(programobject, sizeof(linklog), NULL, linklog);CHECKGLERROR
1677
1678         if (linklog[0])
1679         {
1680
1681                 if (strstr(linklog, "error") || strstr(linklog, "ERROR") || strstr(linklog, "Error") || strstr(linklog, "WARNING") || strstr(linklog, "warning") || strstr(linklog, "Warning") || developer_extra.integer)
1682                         Con_DPrintf("program link log:\n%s\n", linklog);
1683
1684                 // software vertex shader is ok but software fragment shader is WAY
1685                 // too slow, fail program if so.
1686                 // NOTE: this string might be ATI specific, but that's ok because the
1687                 // ATI R300 chip (Radeon 9500-9800/X300) is the most likely to use a
1688                 // software fragment shader due to low instruction and dependent
1689                 // texture limits.
1690                 if (strstr(linklog, "fragment shader will run in software"))
1691                         programlinked = false;
1692         }
1693
1694         if (!programlinked)
1695                 goto cleanup;
1696
1697         return programobject;
1698 cleanup:
1699         qglDeleteProgram(programobject);CHECKGLERROR
1700         return 0;
1701 }
1702
1703 void GL_Backend_FreeProgram(unsigned int prog)
1704 {
1705         CHECKGLERROR
1706         qglDeleteProgram(prog);
1707         CHECKGLERROR
1708 }
1709
1710 // renders triangles using vertices from the active arrays
1711 void R_Mesh_Draw(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const r_meshbuffer_t *element3i_indexbuffer, int element3i_bufferoffset, const unsigned short *element3s, const r_meshbuffer_t *element3s_indexbuffer, int element3s_bufferoffset)
1712 {
1713         unsigned int numelements = numtriangles * 3;
1714         int bufferobject3i;
1715         size_t bufferoffset3i;
1716         int bufferobject3s;
1717         size_t bufferoffset3s;
1718         if (numvertices < 3 || numtriangles < 1)
1719         {
1720                 if (numvertices < 0 || numtriangles < 0 || developer_extra.integer)
1721                         Con_DPrintf("R_Mesh_Draw(%d, %d, %d, %d, %8p, %8p, %8x, %8p, %8p, %8x);\n", firstvertex, numvertices, firsttriangle, numtriangles, (void *)element3i, (void *)element3i_indexbuffer, (int)element3i_bufferoffset, (void *)element3s, (void *)element3s_indexbuffer, (int)element3s_bufferoffset);
1722                 return;
1723         }
1724         // adjust the pointers for firsttriangle
1725         if (element3i)
1726                 element3i += firsttriangle * 3;
1727         if (element3i_indexbuffer)
1728                 element3i_bufferoffset += firsttriangle * 3 * sizeof(*element3i);
1729         if (element3s)
1730                 element3s += firsttriangle * 3;
1731         if (element3s_indexbuffer)
1732                 element3s_bufferoffset += firsttriangle * 3 * sizeof(*element3s);
1733         // upload a dynamic index buffer if needed
1734         if (element3s)
1735         {
1736                 if (!element3s_indexbuffer)
1737                         element3s_indexbuffer = R_BufferData_Store(numelements * sizeof(*element3s), (void *)element3s, R_BUFFERDATA_INDEX16, &element3s_bufferoffset);
1738         }
1739         else if (element3i)
1740         {
1741                 if (!element3i_indexbuffer)
1742                         element3i_indexbuffer = R_BufferData_Store(numelements * sizeof(*element3i), (void *)element3i, R_BUFFERDATA_INDEX32, &element3i_bufferoffset);
1743         }
1744         bufferobject3i = element3i_indexbuffer ? element3i_indexbuffer->bufferobject : 0;
1745         bufferoffset3i = element3i_bufferoffset;
1746         bufferobject3s = element3s_indexbuffer ? element3s_indexbuffer->bufferobject : 0;
1747         bufferoffset3s = element3s_bufferoffset;
1748         r_refdef.stats[r_stat_draws]++;
1749         r_refdef.stats[r_stat_draws_vertices] += numvertices;
1750         r_refdef.stats[r_stat_draws_elements] += numelements;
1751         if (gl_paranoid.integer)
1752         {
1753                 unsigned int i;
1754                 if (element3i)
1755                 {
1756                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
1757                         {
1758                                 if (element3i[i] < firstvertex || element3i[i] >= firstvertex + numvertices)
1759                                 {
1760                                         Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range %i - %i) in element3i array\n", element3i[i], firstvertex, firstvertex + numvertices);
1761                                         return;
1762                                 }
1763                         }
1764                 }
1765                 if (element3s)
1766                 {
1767                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
1768                         {
1769                                 if (element3s[i] < firstvertex || element3s[i] >= firstvertex + numvertices)
1770                                 {
1771                                         Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range %i - %i) in element3s array\n", element3s[i], firstvertex, firstvertex + numvertices);
1772                                         return;
1773                                 }
1774                         }
1775                 }
1776         }
1777         if (r_render.integer || r_refdef.draw2dstage)
1778         {
1779                 switch(vid.renderpath)
1780                 {
1781                 case RENDERPATH_GL20:
1782                 case RENDERPATH_GLES2:
1783                         CHECKGLERROR
1784                         if (bufferobject3s)
1785                         {
1786                                 GL_BindEBO(bufferobject3s);
1787                                 qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_SHORT, (void *)bufferoffset3s);CHECKGLERROR
1788                         }
1789                         else if (bufferobject3i)
1790                         {
1791                                 GL_BindEBO(bufferobject3i);
1792                                 qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, (void *)bufferoffset3i);CHECKGLERROR
1793                         }
1794                         else
1795                         {
1796                                 qglDrawArrays(GL_TRIANGLES, firstvertex, numvertices);CHECKGLERROR
1797                         }
1798                         break;
1799                 }
1800         }
1801 }
1802
1803 // restores backend state, used when done with 3D rendering
1804 void R_Mesh_Finish(void)
1805 {
1806         R_Mesh_SetRenderTargets(0, NULL, NULL, NULL, NULL, NULL);
1807 }
1808
1809 r_meshbuffer_t *R_Mesh_CreateMeshBuffer(const void *data, size_t size, const char *name, qboolean isindexbuffer, qboolean isuniformbuffer, qboolean isdynamic, qboolean isindex16)
1810 {
1811         r_meshbuffer_t *buffer;
1812         buffer = (r_meshbuffer_t *)Mem_ExpandableArray_AllocRecord(&gl_state.meshbufferarray);
1813         memset(buffer, 0, sizeof(*buffer));
1814         buffer->bufferobject = 0;
1815         buffer->devicebuffer = NULL;
1816         buffer->size = size;
1817         buffer->isindexbuffer = isindexbuffer;
1818         buffer->isuniformbuffer = isuniformbuffer;
1819         buffer->isdynamic = isdynamic;
1820         buffer->isindex16 = isindex16;
1821         strlcpy(buffer->name, name, sizeof(buffer->name));
1822         R_Mesh_UpdateMeshBuffer(buffer, data, size, false, 0);
1823         return buffer;
1824 }
1825
1826 void R_Mesh_UpdateMeshBuffer(r_meshbuffer_t *buffer, const void *data, size_t size, qboolean subdata, size_t offset)
1827 {
1828         if (!buffer)
1829                 return;
1830         if (buffer->isindexbuffer)
1831         {
1832                 r_refdef.stats[r_stat_indexbufferuploadcount]++;
1833                 r_refdef.stats[r_stat_indexbufferuploadsize] += (int)size;
1834         }
1835         else
1836         {
1837                 r_refdef.stats[r_stat_vertexbufferuploadcount]++;
1838                 r_refdef.stats[r_stat_vertexbufferuploadsize] += (int)size;
1839         }
1840         if (!subdata)
1841                 buffer->size = size;
1842         switch(vid.renderpath)
1843         {
1844         case RENDERPATH_GL20:
1845         case RENDERPATH_GLES2:
1846                 if (!buffer->bufferobject)
1847                         qglGenBuffers(1, (GLuint *)&buffer->bufferobject);
1848                 CHECKGLERROR
1849                 if (buffer->isuniformbuffer)
1850                         GL_BindUBO(buffer->bufferobject);
1851                 else if (buffer->isindexbuffer)
1852                         GL_BindEBO(buffer->bufferobject);
1853                 else
1854                         GL_BindVBO(buffer->bufferobject);
1855
1856                 {
1857                         int buffertype;
1858                         buffertype = buffer->isindexbuffer ? GL_ELEMENT_ARRAY_BUFFER : GL_ARRAY_BUFFER;
1859 #ifdef GL_UNIFORM_BUFFER
1860                         if (buffer->isuniformbuffer)
1861                                 buffertype = GL_UNIFORM_BUFFER;
1862 #endif
1863                         CHECKGLERROR
1864                         if (subdata)
1865                                 qglBufferSubData(buffertype, offset, size, data);
1866                         else
1867                                 qglBufferData(buffertype, size, data, buffer->isdynamic ? GL_STREAM_DRAW : GL_STATIC_DRAW);
1868                         CHECKGLERROR
1869                 }
1870                 if (buffer->isuniformbuffer)
1871                         GL_BindUBO(0);
1872                 break;
1873         }
1874 }
1875
1876 void R_Mesh_DestroyMeshBuffer(r_meshbuffer_t *buffer)
1877 {
1878         if (!buffer)
1879                 return;
1880         switch(vid.renderpath)
1881         {
1882         case RENDERPATH_GL20:
1883         case RENDERPATH_GLES2:
1884                 // GL clears the binding if we delete something bound
1885                 if (gl_state.uniformbufferobject == buffer->bufferobject)
1886                         gl_state.uniformbufferobject = 0;
1887                 if (gl_state.vertexbufferobject == buffer->bufferobject)
1888                         gl_state.vertexbufferobject = 0;
1889                 if (gl_state.elementbufferobject == buffer->bufferobject)
1890                         gl_state.elementbufferobject = 0;
1891                 CHECKGLERROR
1892                 qglDeleteBuffers(1, (GLuint *)&buffer->bufferobject);CHECKGLERROR
1893                 break;
1894         }
1895         Mem_ExpandableArray_FreeRecord(&gl_state.meshbufferarray, (void *)buffer);
1896 }
1897
1898 static const char *buffertypename[R_BUFFERDATA_COUNT] = {"vertex", "index16", "index32", "uniform"};
1899 void GL_Mesh_ListVBOs(qboolean printeach)
1900 {
1901         int i, endindex;
1902         int type;
1903         int isdynamic;
1904         int index16count, index16mem;
1905         int index32count, index32mem;
1906         int vertexcount, vertexmem;
1907         int uniformcount, uniformmem;
1908         int totalcount, totalmem;
1909         size_t bufferstat[R_BUFFERDATA_COUNT][2][2];
1910         r_meshbuffer_t *buffer;
1911         memset(bufferstat, 0, sizeof(bufferstat));
1912         endindex = (int)Mem_ExpandableArray_IndexRange(&gl_state.meshbufferarray);
1913         for (i = 0;i < endindex;i++)
1914         {
1915                 buffer = (r_meshbuffer_t *) Mem_ExpandableArray_RecordAtIndex(&gl_state.meshbufferarray, i);
1916                 if (!buffer)
1917                         continue;
1918                 if (buffer->isuniformbuffer)
1919                         type = R_BUFFERDATA_UNIFORM;
1920                 else if (buffer->isindexbuffer && buffer->isindex16)
1921                         type = R_BUFFERDATA_INDEX16;
1922                 else if (buffer->isindexbuffer)
1923                         type = R_BUFFERDATA_INDEX32;
1924                 else
1925                         type = R_BUFFERDATA_VERTEX;
1926                 isdynamic = buffer->isdynamic;
1927                 bufferstat[type][isdynamic][0]++;
1928                 bufferstat[type][isdynamic][1] += buffer->size;
1929                 if (printeach)
1930                         Con_Printf("buffer #%i %s = %i bytes (%s %s)\n", i, buffer->name, (int)buffer->size, isdynamic ? "dynamic" : "static", buffertypename[type]);
1931         }
1932         index16count   = (int)(bufferstat[R_BUFFERDATA_INDEX16][0][0] + bufferstat[R_BUFFERDATA_INDEX16][1][0]);
1933         index16mem     = (int)(bufferstat[R_BUFFERDATA_INDEX16][0][1] + bufferstat[R_BUFFERDATA_INDEX16][1][1]);
1934         index32count   = (int)(bufferstat[R_BUFFERDATA_INDEX32][0][0] + bufferstat[R_BUFFERDATA_INDEX32][1][0]);
1935         index32mem     = (int)(bufferstat[R_BUFFERDATA_INDEX32][0][1] + bufferstat[R_BUFFERDATA_INDEX32][1][1]);
1936         vertexcount  = (int)(bufferstat[R_BUFFERDATA_VERTEX ][0][0] + bufferstat[R_BUFFERDATA_VERTEX ][1][0]);
1937         vertexmem    = (int)(bufferstat[R_BUFFERDATA_VERTEX ][0][1] + bufferstat[R_BUFFERDATA_VERTEX ][1][1]);
1938         uniformcount = (int)(bufferstat[R_BUFFERDATA_UNIFORM][0][0] + bufferstat[R_BUFFERDATA_UNIFORM][1][0]);
1939         uniformmem   = (int)(bufferstat[R_BUFFERDATA_UNIFORM][0][1] + bufferstat[R_BUFFERDATA_UNIFORM][1][1]);
1940         totalcount = index16count + index32count + vertexcount + uniformcount;
1941         totalmem = index16mem + index32mem + vertexmem + uniformmem;
1942         Con_Printf("%i 16bit indexbuffers totalling %i bytes (%.3f MB)\n%i 32bit indexbuffers totalling %i bytes (%.3f MB)\n%i vertexbuffers totalling %i bytes (%.3f MB)\n%i uniformbuffers totalling %i bytes (%.3f MB)\ncombined %i buffers totalling %i bytes (%.3fMB)\n", index16count, index16mem, index16mem / 10248576.0, index32count, index32mem, index32mem / 10248576.0, vertexcount, vertexmem, vertexmem / 10248576.0, uniformcount, uniformmem, uniformmem / 10248576.0, totalcount, totalmem, totalmem / 10248576.0);
1943 }
1944
1945
1946
1947 void R_Mesh_VertexPointer(int components, int gltype, size_t stride, const void *pointer, const r_meshbuffer_t *vertexbuffer, size_t bufferoffset)
1948 {
1949         switch(vid.renderpath)
1950         {
1951         case RENDERPATH_GL20:
1952         case RENDERPATH_GLES2:
1953                 if (gl_state.pointer_vertex_components != components || gl_state.pointer_vertex_gltype != gltype || gl_state.pointer_vertex_stride != stride || gl_state.pointer_vertex_pointer != pointer || gl_state.pointer_vertex_vertexbuffer != vertexbuffer || gl_state.pointer_vertex_offset != bufferoffset)
1954                 {
1955                         int bufferobject = vertexbuffer ? vertexbuffer->bufferobject : 0;
1956                         if (!bufferobject && gl_paranoid.integer)
1957                                 Con_DPrintf("Warning: no bufferobject in R_Mesh_VertexPointer(%i, %i, %i, %p, %p, %08x)", components, gltype, (int)stride, pointer, vertexbuffer, (unsigned int)bufferoffset);
1958                         gl_state.pointer_vertex_components = components;
1959                         gl_state.pointer_vertex_gltype = gltype;
1960                         gl_state.pointer_vertex_stride = stride;
1961                         gl_state.pointer_vertex_pointer = pointer;
1962                         gl_state.pointer_vertex_vertexbuffer = vertexbuffer;
1963                         gl_state.pointer_vertex_offset = bufferoffset;
1964                         CHECKGLERROR
1965                         GL_BindVBO(bufferobject);
1966                         // LordHavoc: special flag added to gltype for unnormalized types
1967                         qglVertexAttribPointer(GLSLATTRIB_POSITION, components, gltype & ~0x80000000, (gltype & 0x80000000) == 0, (GLsizei)stride, bufferobject ? (void *)bufferoffset : pointer);CHECKGLERROR
1968                 }
1969                 break;
1970         }
1971 }
1972
1973 void R_Mesh_ColorPointer(int components, int gltype, size_t stride, const void *pointer, const r_meshbuffer_t *vertexbuffer, size_t bufferoffset)
1974 {
1975         // note: vertexbuffer may be non-NULL even if pointer is NULL, so check
1976         // the pointer only.
1977         switch(vid.renderpath)
1978         {
1979         case RENDERPATH_GL20:
1980         case RENDERPATH_GLES2:
1981                 CHECKGLERROR
1982                 if (pointer)
1983                 {
1984                         // caller wants color array enabled
1985                         int bufferobject = vertexbuffer ? vertexbuffer->bufferobject : 0;
1986                         if (!gl_state.pointer_color_enabled)
1987                         {
1988                                 gl_state.pointer_color_enabled = true;
1989                                 CHECKGLERROR
1990                                 qglEnableVertexAttribArray(GLSLATTRIB_COLOR);CHECKGLERROR
1991                         }
1992                         if (gl_state.pointer_color_components != components || gl_state.pointer_color_gltype != gltype || gl_state.pointer_color_stride != stride || gl_state.pointer_color_pointer != pointer || gl_state.pointer_color_vertexbuffer != vertexbuffer || gl_state.pointer_color_offset != bufferoffset)
1993                         {
1994                                 gl_state.pointer_color_components = components;
1995                                 gl_state.pointer_color_gltype = gltype;
1996                                 gl_state.pointer_color_stride = stride;
1997                                 gl_state.pointer_color_pointer = pointer;
1998                                 gl_state.pointer_color_vertexbuffer = vertexbuffer;
1999                                 gl_state.pointer_color_offset = bufferoffset;
2000                                 CHECKGLERROR
2001                                 GL_BindVBO(bufferobject);
2002                                 // LordHavoc: special flag added to gltype for unnormalized types
2003                                 qglVertexAttribPointer(GLSLATTRIB_COLOR, components, gltype & ~0x80000000, (gltype & 0x80000000) == 0, (GLsizei)stride, bufferobject ? (void *)bufferoffset : pointer);CHECKGLERROR
2004                         }
2005                 }
2006                 else
2007                 {
2008                         // caller wants color array disabled
2009                         if (gl_state.pointer_color_enabled)
2010                         {
2011                                 gl_state.pointer_color_enabled = false;
2012                                 CHECKGLERROR
2013                                 qglDisableVertexAttribArray(GLSLATTRIB_COLOR);CHECKGLERROR
2014                                 // when color array is on the current color gets trashed, set it again
2015                                 qglVertexAttrib4f(GLSLATTRIB_COLOR, gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);CHECKGLERROR
2016                         }
2017                 }
2018                 break;
2019         }
2020 }
2021
2022 void R_Mesh_TexCoordPointer(unsigned int unitnum, int components, int gltype, size_t stride, const void *pointer, const r_meshbuffer_t *vertexbuffer, size_t bufferoffset)
2023 {
2024         gltextureunit_t *unit = gl_state.units + unitnum;
2025         // update array settings
2026         // note: there is no need to check bufferobject here because all cases
2027         // that involve a valid bufferobject also supply a texcoord array
2028         switch(vid.renderpath)
2029         {
2030         case RENDERPATH_GL20:
2031         case RENDERPATH_GLES2:
2032                 CHECKGLERROR
2033                 if (pointer)
2034                 {
2035                         int bufferobject = vertexbuffer ? vertexbuffer->bufferobject : 0;
2036                         // texture array unit is enabled, enable the array
2037                         if (!unit->arrayenabled)
2038                         {
2039                                 unit->arrayenabled = true;
2040                                 qglEnableVertexAttribArray(unitnum+GLSLATTRIB_TEXCOORD0);CHECKGLERROR
2041                         }
2042                         // texcoord array
2043                         if (unit->pointer_texcoord_components != components || unit->pointer_texcoord_gltype != gltype || unit->pointer_texcoord_stride != stride || unit->pointer_texcoord_pointer != pointer || unit->pointer_texcoord_vertexbuffer != vertexbuffer || unit->pointer_texcoord_offset != bufferoffset)
2044                         {
2045                                 unit->pointer_texcoord_components = components;
2046                                 unit->pointer_texcoord_gltype = gltype;
2047                                 unit->pointer_texcoord_stride = stride;
2048                                 unit->pointer_texcoord_pointer = pointer;
2049                                 unit->pointer_texcoord_vertexbuffer = vertexbuffer;
2050                                 unit->pointer_texcoord_offset = bufferoffset;
2051                                 GL_BindVBO(bufferobject);
2052                                 // LordHavoc: special flag added to gltype for unnormalized types
2053                                 qglVertexAttribPointer(unitnum+GLSLATTRIB_TEXCOORD0, components, gltype & ~0x80000000, (gltype & 0x80000000) == 0, (GLsizei)stride, bufferobject ? (void *)bufferoffset : pointer);CHECKGLERROR
2054                         }
2055                 }
2056                 else
2057                 {
2058                         // texture array unit is disabled, disable the array
2059                         if (unit->arrayenabled)
2060                         {
2061                                 unit->arrayenabled = false;
2062                                 qglDisableVertexAttribArray(unitnum+GLSLATTRIB_TEXCOORD0);CHECKGLERROR
2063                         }
2064                 }
2065                 break;
2066         }
2067 }
2068
2069 int R_Mesh_TexBound(unsigned int unitnum, int id)
2070 {
2071         gltextureunit_t *unit = gl_state.units + unitnum;
2072         if (unitnum >= vid.teximageunits)
2073                 return 0;
2074         if (id == GL_TEXTURE_2D)
2075                 return unit->t2d;
2076         if (id == GL_TEXTURE_3D)
2077                 return unit->t3d;
2078         if (id == GL_TEXTURE_CUBE_MAP)
2079                 return unit->tcubemap;
2080         return 0;
2081 }
2082
2083 void R_Mesh_CopyToTexture(rtexture_t *tex, int tx, int ty, int sx, int sy, int width, int height)
2084 {
2085         switch(vid.renderpath)
2086         {
2087         case RENDERPATH_GL20:
2088         case RENDERPATH_GLES2:
2089                 R_Mesh_TexBind(0, tex);
2090                 GL_ActiveTexture(0);CHECKGLERROR
2091                 qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, tx, ty, sx, sy, width, height);CHECKGLERROR
2092                 break;
2093         }
2094 }
2095
2096 void R_Mesh_ClearBindingsForTexture(int texnum)
2097 {
2098         gltextureunit_t *unit;
2099         unsigned int unitnum;
2100         // this doesn't really unbind the texture, but it does prevent a mistaken "do nothing" behavior on the next time this same texnum is bound on the same unit as the same type (this mainly affects r_shadow_bouncegrid because 3D textures are so rarely used)
2101         for (unitnum = 0;unitnum < vid.teximageunits;unitnum++)
2102         {
2103                 unit = gl_state.units + unitnum;
2104                 if (unit->t2d == texnum)
2105                         unit->t2d = -1;
2106                 if (unit->t3d == texnum)
2107                         unit->t3d = -1;
2108                 if (unit->tcubemap == texnum)
2109                         unit->tcubemap = -1;
2110         }
2111 }
2112
2113 void R_Mesh_TexBind(unsigned int unitnum, rtexture_t *tex)
2114 {
2115         gltextureunit_t *unit = gl_state.units + unitnum;
2116         int texnum;
2117         if (unitnum >= vid.teximageunits)
2118                 return;
2119         if (unit->texture == tex)
2120                 return;
2121         switch(vid.renderpath)
2122         {
2123         case RENDERPATH_GL20:
2124         case RENDERPATH_GLES2:
2125                 if (!tex)
2126                 {
2127                         tex = r_texture_white;
2128                         // not initialized enough yet...
2129                         if (!tex)
2130                                 return;
2131                 }
2132                 unit->texture = tex;
2133                 texnum = R_GetTexture(tex);
2134                 switch(tex->gltexturetypeenum)
2135                 {
2136                 case GL_TEXTURE_2D: if (unit->t2d != texnum) {GL_ActiveTexture(unitnum);unit->t2d = texnum;qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR}break;
2137                 case GL_TEXTURE_3D: if (unit->t3d != texnum) {GL_ActiveTexture(unitnum);unit->t3d = texnum;qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR}break;
2138                 case GL_TEXTURE_CUBE_MAP: if (unit->tcubemap != texnum) {GL_ActiveTexture(unitnum);unit->tcubemap = texnum;qglBindTexture(GL_TEXTURE_CUBE_MAP, unit->tcubemap);CHECKGLERROR}break;
2139                 }
2140                 break;
2141         }
2142 }
2143
2144 void R_Mesh_ResetTextureState(void)
2145 {
2146         unsigned int unitnum;
2147
2148         BACKENDACTIVECHECK
2149
2150         for (unitnum = 0;unitnum < vid.teximageunits;unitnum++)
2151                 R_Mesh_TexBind(unitnum, NULL);
2152         for (unitnum = 0;unitnum < vid.texarrayunits;unitnum++)
2153                 R_Mesh_TexCoordPointer(unitnum, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2154 }
2155
2156 void R_Mesh_PrepareVertices_Vertex3f(int numvertices, const float *vertex3f, const r_meshbuffer_t *vertexbuffer, int bufferoffset)
2157 {
2158         // upload temporary vertexbuffer for this rendering
2159         if (!vertexbuffer)
2160                 vertexbuffer = R_BufferData_Store(numvertices * sizeof(float[3]), (void *)vertex3f, R_BUFFERDATA_VERTEX, &bufferoffset);
2161         if (vertexbuffer)
2162         {
2163                 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), vertex3f, vertexbuffer, bufferoffset);
2164                 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, NULL, 0);
2165                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2166                 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2167                 R_Mesh_TexCoordPointer(2, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2168                 R_Mesh_TexCoordPointer(3, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2169                 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2170                 R_Mesh_TexCoordPointer(5, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2171                 R_Mesh_TexCoordPointer(6, 4, GL_UNSIGNED_BYTE, sizeof(unsigned char[4]), NULL, NULL, 0);
2172                 R_Mesh_TexCoordPointer(7, 4, GL_UNSIGNED_BYTE, sizeof(unsigned char[4]), NULL, NULL, 0);
2173         }
2174         else
2175         {
2176                 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), vertex3f, vertexbuffer, 0);
2177                 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, NULL, 0);
2178                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2179                 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2180                 R_Mesh_TexCoordPointer(2, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2181                 R_Mesh_TexCoordPointer(3, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2182                 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2183                 R_Mesh_TexCoordPointer(5, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
2184                 R_Mesh_TexCoordPointer(6, 4, GL_UNSIGNED_BYTE, sizeof(unsigned char[4]), NULL, NULL, 0);
2185                 R_Mesh_TexCoordPointer(7, 4, GL_UNSIGNED_BYTE, sizeof(unsigned char[4]), NULL, NULL, 0);
2186         }
2187 }
2188
2189 void R_Mesh_PrepareVertices_Generic_Arrays(int numvertices, const float *vertex3f, const float *color4f, const float *texcoord2f)
2190 {
2191         r_meshbuffer_t *buffer_vertex3f = NULL;
2192         r_meshbuffer_t *buffer_color4f = NULL;
2193         r_meshbuffer_t *buffer_texcoord2f = NULL;
2194         int bufferoffset_vertex3f = 0;
2195         int bufferoffset_color4f = 0;
2196         int bufferoffset_texcoord2f = 0;
2197         buffer_color4f    = R_BufferData_Store(numvertices * sizeof(float[4]), color4f   , R_BUFFERDATA_VERTEX, &bufferoffset_color4f   );
2198         buffer_vertex3f   = R_BufferData_Store(numvertices * sizeof(float[3]), vertex3f  , R_BUFFERDATA_VERTEX, &bufferoffset_vertex3f  );
2199         buffer_texcoord2f = R_BufferData_Store(numvertices * sizeof(float[2]), texcoord2f, R_BUFFERDATA_VERTEX, &bufferoffset_texcoord2f);
2200         R_Mesh_VertexPointer(     3, GL_FLOAT        , sizeof(float[3])        , vertex3f          , buffer_vertex3f          , bufferoffset_vertex3f          );
2201         R_Mesh_ColorPointer(      4, GL_FLOAT        , sizeof(float[4])        , color4f           , buffer_color4f           , bufferoffset_color4f           );
2202         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT        , sizeof(float[2])        , texcoord2f        , buffer_texcoord2f        , bufferoffset_texcoord2f        );
2203         R_Mesh_TexCoordPointer(1, 3, GL_FLOAT        , sizeof(float[3])        , NULL              , NULL                     , 0                              );
2204         R_Mesh_TexCoordPointer(2, 3, GL_FLOAT        , sizeof(float[3])        , NULL              , NULL                     , 0                              );
2205         R_Mesh_TexCoordPointer(3, 3, GL_FLOAT        , sizeof(float[3])        , NULL              , NULL                     , 0                              );
2206         R_Mesh_TexCoordPointer(4, 2, GL_FLOAT        , sizeof(float[2])        , NULL              , NULL                     , 0                              );
2207         R_Mesh_TexCoordPointer(5, 2, GL_FLOAT        , sizeof(float[2])        , NULL              , NULL                     , 0                              );
2208         R_Mesh_TexCoordPointer(6, 4, GL_UNSIGNED_BYTE, sizeof(unsigned char[4]), NULL              , NULL                     , 0                              );
2209         R_Mesh_TexCoordPointer(7, 4, GL_UNSIGNED_BYTE, sizeof(unsigned char[4]), NULL              , NULL                     , 0                              );
2210 }
2211
2212 void R_Mesh_PrepareVertices_Mesh_Arrays(int numvertices, const float *vertex3f, const float *svector3f, const float *tvector3f, const float *normal3f, const float *color4f, const float *texcoordtexture2f, const float *texcoordlightmap2f)
2213 {
2214         r_meshbuffer_t *buffer_vertex3f = NULL;
2215         r_meshbuffer_t *buffer_color4f = NULL;
2216         r_meshbuffer_t *buffer_texcoordtexture2f = NULL;
2217         r_meshbuffer_t *buffer_svector3f = NULL;
2218         r_meshbuffer_t *buffer_tvector3f = NULL;
2219         r_meshbuffer_t *buffer_normal3f = NULL;
2220         r_meshbuffer_t *buffer_texcoordlightmap2f = NULL;
2221         int bufferoffset_vertex3f = 0;
2222         int bufferoffset_color4f = 0;
2223         int bufferoffset_texcoordtexture2f = 0;
2224         int bufferoffset_svector3f = 0;
2225         int bufferoffset_tvector3f = 0;
2226         int bufferoffset_normal3f = 0;
2227         int bufferoffset_texcoordlightmap2f = 0;
2228         buffer_color4f            = R_BufferData_Store(numvertices * sizeof(float[4]), color4f           , R_BUFFERDATA_VERTEX, &bufferoffset_color4f           );
2229         buffer_vertex3f           = R_BufferData_Store(numvertices * sizeof(float[3]), vertex3f          , R_BUFFERDATA_VERTEX, &bufferoffset_vertex3f          );
2230         buffer_svector3f          = R_BufferData_Store(numvertices * sizeof(float[3]), svector3f         , R_BUFFERDATA_VERTEX, &bufferoffset_svector3f         );
2231         buffer_tvector3f          = R_BufferData_Store(numvertices * sizeof(float[3]), tvector3f         , R_BUFFERDATA_VERTEX, &bufferoffset_tvector3f         );
2232         buffer_normal3f           = R_BufferData_Store(numvertices * sizeof(float[3]), normal3f          , R_BUFFERDATA_VERTEX, &bufferoffset_normal3f          );
2233         buffer_texcoordtexture2f  = R_BufferData_Store(numvertices * sizeof(float[2]), texcoordtexture2f , R_BUFFERDATA_VERTEX, &bufferoffset_texcoordtexture2f );
2234         buffer_texcoordlightmap2f = R_BufferData_Store(numvertices * sizeof(float[2]), texcoordlightmap2f, R_BUFFERDATA_VERTEX, &bufferoffset_texcoordlightmap2f);
2235         R_Mesh_VertexPointer(     3, GL_FLOAT        , sizeof(float[3])        , vertex3f          , buffer_vertex3f          , bufferoffset_vertex3f          );
2236         R_Mesh_ColorPointer(      4, GL_FLOAT        , sizeof(float[4])        , color4f           , buffer_color4f           , bufferoffset_color4f           );
2237         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT        , sizeof(float[2])        , texcoordtexture2f , buffer_texcoordtexture2f , bufferoffset_texcoordtexture2f );
2238         R_Mesh_TexCoordPointer(1, 3, GL_FLOAT        , sizeof(float[3])        , svector3f         , buffer_svector3f         , bufferoffset_svector3f         );
2239         R_Mesh_TexCoordPointer(2, 3, GL_FLOAT        , sizeof(float[3])        , tvector3f         , buffer_tvector3f         , bufferoffset_tvector3f         );
2240         R_Mesh_TexCoordPointer(3, 3, GL_FLOAT        , sizeof(float[3])        , normal3f          , buffer_normal3f          , bufferoffset_normal3f          );
2241         R_Mesh_TexCoordPointer(4, 2, GL_FLOAT        , sizeof(float[2])        , texcoordlightmap2f, buffer_texcoordlightmap2f, bufferoffset_texcoordlightmap2f);
2242         R_Mesh_TexCoordPointer(5, 2, GL_FLOAT        , sizeof(float[2])        , NULL              , NULL                     , 0                              );
2243         R_Mesh_TexCoordPointer(6, 4, GL_UNSIGNED_BYTE, sizeof(unsigned char[4]), NULL              , NULL                     , 0                              );
2244         R_Mesh_TexCoordPointer(7, 4, GL_UNSIGNED_BYTE, sizeof(unsigned char[4]), NULL              , NULL                     , 0                              );
2245 }
2246
2247 void GL_BlendEquationSubtract(qboolean negated)
2248 {
2249         CHECKGLERROR
2250         if(negated)
2251         {
2252                 switch(vid.renderpath)
2253                 {
2254                 case RENDERPATH_GL20:
2255                 case RENDERPATH_GLES2:
2256                         qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT);CHECKGLERROR
2257                         break;
2258                 }
2259         }
2260         else
2261         {
2262                 switch(vid.renderpath)
2263                 {
2264                 case RENDERPATH_GL20:
2265                 case RENDERPATH_GLES2:
2266                         qglBlendEquationEXT(GL_FUNC_ADD);CHECKGLERROR
2267                         break;
2268                 }
2269         }
2270 }