Reworked v_isometric code significantly, it now defaults to a proper isometric view...
[xonotic/darkplaces.git] / gl_backend.c
1
2 #include "quakedef.h"
3 #include "cl_collision.h"
4 #include "dpsoftrast.h"
5 #ifdef SUPPORTD3D
6 #include <d3d9.h>
7 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
8 extern D3DCAPS9 vid_d3d9caps;
9 #endif
10
11 // on GLES we have to use some proper #define's
12 #ifndef GL_FRAMEBUFFER
13 #define GL_FRAMEBUFFER                                   0x8D40
14 #define GL_DEPTH_ATTACHMENT                              0x8D00
15 #define GL_COLOR_ATTACHMENT0                             0x8CE0
16 #define GL_INVALID_FRAMEBUFFER_OPERATION                 0x0506
17 #endif
18 #ifndef GL_COLOR_ATTACHMENT1
19 #define GL_COLOR_ATTACHMENT1                             0x8CE1
20 #define GL_COLOR_ATTACHMENT2                             0x8CE2
21 #define GL_COLOR_ATTACHMENT3                             0x8CE3
22 #define GL_COLOR_ATTACHMENT4                             0x8CE4
23 #define GL_COLOR_ATTACHMENT5                             0x8CE5
24 #define GL_COLOR_ATTACHMENT6                             0x8CE6
25 #define GL_COLOR_ATTACHMENT7                             0x8CE7
26 #define GL_COLOR_ATTACHMENT8                             0x8CE8
27 #define GL_COLOR_ATTACHMENT9                             0x8CE9
28 #define GL_COLOR_ATTACHMENT10                            0x8CEA
29 #define GL_COLOR_ATTACHMENT11                            0x8CEB
30 #define GL_COLOR_ATTACHMENT12                            0x8CEC
31 #define GL_COLOR_ATTACHMENT13                            0x8CED
32 #define GL_COLOR_ATTACHMENT14                            0x8CEE
33 #define GL_COLOR_ATTACHMENT15                            0x8CEF
34 #endif
35 #ifndef GL_ARRAY_BUFFER
36 #define GL_ARRAY_BUFFER               0x8892
37 #define GL_ELEMENT_ARRAY_BUFFER       0x8893
38 #endif
39 //#ifndef GL_VERTEX_ARRAY
40 //#define GL_VERTEX_ARRAY                               0x8074
41 //#define GL_COLOR_ARRAY                                0x8076
42 //#define GL_TEXTURE_COORD_ARRAY                        0x8078
43 //#endif
44 #ifndef GL_TEXTURE0
45 #define GL_TEXTURE0                                     0x84C0
46 #define GL_TEXTURE1                                     0x84C1
47 #define GL_TEXTURE2                                     0x84C2
48 #define GL_TEXTURE3                                     0x84C3
49 #define GL_TEXTURE4                                     0x84C4
50 #define GL_TEXTURE5                                     0x84C5
51 #define GL_TEXTURE6                                     0x84C6
52 #define GL_TEXTURE7                                     0x84C7
53 #define GL_TEXTURE8                                     0x84C8
54 #define GL_TEXTURE9                                     0x84C9
55 #define GL_TEXTURE10                            0x84CA
56 #define GL_TEXTURE11                            0x84CB
57 #define GL_TEXTURE12                            0x84CC
58 #define GL_TEXTURE13                            0x84CD
59 #define GL_TEXTURE14                            0x84CE
60 #define GL_TEXTURE15                            0x84CF
61 #define GL_TEXTURE16                            0x84D0
62 #define GL_TEXTURE17                            0x84D1
63 #define GL_TEXTURE18                            0x84D2
64 #define GL_TEXTURE19                            0x84D3
65 #define GL_TEXTURE20                            0x84D4
66 #define GL_TEXTURE21                            0x84D5
67 #define GL_TEXTURE22                            0x84D6
68 #define GL_TEXTURE23                            0x84D7
69 #define GL_TEXTURE24                            0x84D8
70 #define GL_TEXTURE25                            0x84D9
71 #define GL_TEXTURE26                            0x84DA
72 #define GL_TEXTURE27                            0x84DB
73 #define GL_TEXTURE28                            0x84DC
74 #define GL_TEXTURE29                            0x84DD
75 #define GL_TEXTURE30                            0x84DE
76 #define GL_TEXTURE31                            0x84DF
77 #endif
78
79 #ifndef GL_TEXTURE_3D
80 #define GL_TEXTURE_3D                           0x806F
81 #endif
82 #ifndef GL_TEXTURE_CUBE_MAP
83 #define GL_TEXTURE_CUBE_MAP                 0x8513
84 #endif
85 //#ifndef GL_MODELVIEW
86 //#define GL_MODELVIEW                          0x1700
87 //#endif
88 //#ifndef GL_PROJECTION
89 //#define GL_PROJECTION                         0x1701
90 //#endif
91 //#ifndef GL_DECAL
92 //#define GL_DECAL                              0x2101
93 //#endif
94 //#ifndef GL_INTERPOLATE
95 //#define GL_INTERPOLATE                                0x8575
96 //#endif
97
98
99 #define MAX_RENDERTARGETS 4
100
101 cvar_t gl_mesh_drawrangeelements = {0, "gl_mesh_drawrangeelements", "1", "use glDrawRangeElements function if available instead of glDrawElements (for performance comparisons or bug testing)"};
102 cvar_t gl_mesh_testmanualfeeding = {0, "gl_mesh_testmanualfeeding", "0", "use glBegin(GL_TRIANGLES);glTexCoord2f();glVertex3f();glEnd(); primitives instead of glDrawElements (useful to test for driver bugs with glDrawElements)"};
103 cvar_t gl_paranoid = {0, "gl_paranoid", "0", "enables OpenGL error checking and other tests"};
104 cvar_t gl_printcheckerror = {0, "gl_printcheckerror", "0", "prints all OpenGL error checks, useful to identify location of driver crashes"};
105
106 cvar_t r_render = {0, "r_render", "1", "enables rendering 3D views (you want this on!)"};
107 cvar_t r_renderview = {0, "r_renderview", "1", "enables rendering 3D views (you want this on!)"};
108 cvar_t r_waterwarp = {CVAR_SAVE, "r_waterwarp", "1", "warp view while underwater"};
109 cvar_t gl_polyblend = {CVAR_SAVE, "gl_polyblend", "1", "tints view while underwater, hurt, etc"};
110 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1", "enables OpenGL dithering (16bit looks bad with this off)"};
111 cvar_t gl_vbo = {CVAR_SAVE, "gl_vbo", "3", "make use of GL_ARB_vertex_buffer_object extension to store static geometry in video memory for faster rendering, 0 disables VBO allocation or use, 1 enables VBOs for vertex and triangle data, 2 only for vertex data, 3 for vertex data and triangle data of simple meshes (ones with only one surface)"};
112 cvar_t gl_vbo_dynamicvertex = {CVAR_SAVE, "gl_vbo_dynamicvertex", "0", "make use of GL_ARB_vertex_buffer_object extension when rendering dynamic (animated/procedural) geometry such as text and particles"};
113 cvar_t gl_vbo_dynamicindex = {CVAR_SAVE, "gl_vbo_dynamicindex", "0", "make use of GL_ARB_vertex_buffer_object extension when rendering dynamic (animated/procedural) geometry such as text and particles"};
114 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"};
115
116 cvar_t v_flipped = {0, "v_flipped", "0", "mirror the screen (poor man's left handed mode)"};
117 qboolean v_flipped_state = false;
118
119 r_viewport_t gl_viewport;
120 matrix4x4_t gl_modelmatrix;
121 matrix4x4_t gl_viewmatrix;
122 matrix4x4_t gl_modelviewmatrix;
123 matrix4x4_t gl_projectionmatrix;
124 matrix4x4_t gl_modelviewprojectionmatrix;
125 float gl_modelview16f[16];
126 float gl_modelviewprojection16f[16];
127 qboolean gl_modelmatrixchanged;
128
129 int gl_maxdrawrangeelementsvertices;
130 int gl_maxdrawrangeelementsindices;
131
132 #ifdef DEBUGGL
133 int gl_errornumber = 0;
134
135 void GL_PrintError(int errornumber, const char *filename, int linenumber)
136 {
137         switch(errornumber)
138         {
139 #ifdef GL_INVALID_ENUM
140         case GL_INVALID_ENUM:
141                 Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
142                 break;
143 #endif
144 #ifdef GL_INVALID_VALUE
145         case GL_INVALID_VALUE:
146                 Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
147                 break;
148 #endif
149 #ifdef GL_INVALID_OPERATION
150         case GL_INVALID_OPERATION:
151                 Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
152                 break;
153 #endif
154 #ifdef GL_STACK_OVERFLOW
155         case GL_STACK_OVERFLOW:
156                 Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
157                 break;
158 #endif
159 #ifdef GL_STACK_UNDERFLOW
160         case GL_STACK_UNDERFLOW:
161                 Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
162                 break;
163 #endif
164 #ifdef GL_OUT_OF_MEMORY
165         case GL_OUT_OF_MEMORY:
166                 Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
167                 break;
168 #endif
169 #ifdef GL_TABLE_TOO_LARGE
170         case GL_TABLE_TOO_LARGE:
171                 Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
172                 break;
173 #endif
174 #ifdef GL_INVALID_FRAMEBUFFER_OPERATION
175         case GL_INVALID_FRAMEBUFFER_OPERATION:
176                 Con_Printf("GL_INVALID_FRAMEBUFFER_OPERATION at %s:%i\n", filename, linenumber);
177                 break;
178 #endif
179         default:
180                 Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
181                 break;
182         }
183 }
184 #endif
185
186 #define BACKENDACTIVECHECK if (!gl_state.active) Sys_Error("GL backend function called when backend is not active");
187
188 void SCR_ScreenShot_f (void);
189
190 typedef struct gltextureunit_s
191 {
192         int pointer_texcoord_components;
193         int pointer_texcoord_gltype;
194         size_t pointer_texcoord_stride;
195         const void *pointer_texcoord_pointer;
196         const r_meshbuffer_t *pointer_texcoord_vertexbuffer;
197         size_t pointer_texcoord_offset;
198
199         rtexture_t *texture;
200         int t2d, t3d, tcubemap;
201         int arrayenabled;
202         int rgbscale, alphascale;
203         int combine;
204         int combinergb, combinealpha;
205         // texmatrixenabled exists only to avoid unnecessary texmatrix compares
206         int texmatrixenabled;
207         matrix4x4_t matrix;
208 }
209 gltextureunit_t;
210
211 typedef struct gl_state_s
212 {
213         int cullface;
214         int cullfaceenable;
215         int blendfunc1;
216         int blendfunc2;
217         qboolean blend;
218         GLboolean depthmask;
219         int colormask; // stored as bottom 4 bits: r g b a (3 2 1 0 order)
220         int depthtest;
221         int depthfunc;
222         float depthrange[2];
223         float polygonoffset[2];
224         int alphatest;
225         int alphafunc;
226         float alphafuncvalue;
227         qboolean alphatocoverage;
228         int scissortest;
229         unsigned int unit;
230         unsigned int clientunit;
231         gltextureunit_t units[MAX_TEXTUREUNITS];
232         float color4f[4];
233         int lockrange_first;
234         int lockrange_count;
235         int vertexbufferobject;
236         int elementbufferobject;
237         int uniformbufferobject;
238         int framebufferobject;
239         int defaultframebufferobject; // deal with platforms that use a non-zero default fbo
240         qboolean pointer_color_enabled;
241
242         int pointer_vertex_components;
243         int pointer_vertex_gltype;
244         size_t pointer_vertex_stride;
245         const void *pointer_vertex_pointer;
246         const r_meshbuffer_t *pointer_vertex_vertexbuffer;
247         size_t pointer_vertex_offset;
248
249         int pointer_color_components;
250         int pointer_color_gltype;
251         size_t pointer_color_stride;
252         const void *pointer_color_pointer;
253         const r_meshbuffer_t *pointer_color_vertexbuffer;
254         size_t pointer_color_offset;
255
256         void *preparevertices_tempdata;
257         size_t preparevertices_tempdatamaxsize;
258         r_vertexgeneric_t *preparevertices_vertexgeneric;
259         r_vertexmesh_t *preparevertices_vertexmesh;
260         int preparevertices_numvertices;
261
262         qboolean usevbo_staticvertex;
263         qboolean usevbo_staticindex;
264         qboolean usevbo_dynamicvertex;
265         qboolean usevbo_dynamicindex;
266
267         memexpandablearray_t meshbufferarray;
268
269         qboolean active;
270
271 #ifdef SUPPORTD3D
272 //      rtexture_t *d3drt_depthtexture;
273 //      rtexture_t *d3drt_colortextures[MAX_RENDERTARGETS];
274         IDirect3DSurface9 *d3drt_depthsurface;
275         IDirect3DSurface9 *d3drt_colorsurfaces[MAX_RENDERTARGETS];
276         IDirect3DSurface9 *d3drt_backbufferdepthsurface;
277         IDirect3DSurface9 *d3drt_backbuffercolorsurface;
278         void *d3dvertexbuffer;
279         void *d3dvertexdata;
280         int d3dvertexsize;
281 #endif
282 }
283 gl_state_t;
284
285 static gl_state_t gl_state;
286
287
288 /*
289 note: here's strip order for a terrain row:
290 0--1--2--3--4
291 |\ |\ |\ |\ |
292 | \| \| \| \|
293 A--B--C--D--E
294 clockwise
295
296 A0B, 01B, B1C, 12C, C2D, 23D, D3E, 34E
297
298 *elements++ = i + row;
299 *elements++ = i;
300 *elements++ = i + row + 1;
301 *elements++ = i;
302 *elements++ = i + 1;
303 *elements++ = i + row + 1;
304
305
306 for (y = 0;y < rows - 1;y++)
307 {
308         for (x = 0;x < columns - 1;x++)
309         {
310                 i = y * rows + x;
311                 *elements++ = i + columns;
312                 *elements++ = i;
313                 *elements++ = i + columns + 1;
314                 *elements++ = i;
315                 *elements++ = i + 1;
316                 *elements++ = i + columns + 1;
317         }
318 }
319
320 alternative:
321 0--1--2--3--4
322 | /| /|\ | /|
323 |/ |/ | \|/ |
324 A--B--C--D--E
325 counterclockwise
326
327 for (y = 0;y < rows - 1;y++)
328 {
329         for (x = 0;x < columns - 1;x++)
330         {
331                 i = y * rows + x;
332                 *elements++ = i;
333                 *elements++ = i + columns;
334                 *elements++ = i + columns + 1;
335                 *elements++ = i + columns;
336                 *elements++ = i + columns + 1;
337                 *elements++ = i + 1;
338         }
339 }
340 */
341
342 int polygonelement3i[(POLYGONELEMENTS_MAXPOINTS-2)*3];
343 unsigned short polygonelement3s[(POLYGONELEMENTS_MAXPOINTS-2)*3];
344 int quadelement3i[QUADELEMENTS_MAXQUADS*6];
345 unsigned short quadelement3s[QUADELEMENTS_MAXQUADS*6];
346
347 static void GL_VBOStats_f(void)
348 {
349         GL_Mesh_ListVBOs(true);
350 }
351
352 static void GL_Backend_ResetState(void);
353
354 static void R_Mesh_InitVertexDeclarations(void);
355 static void R_Mesh_DestroyVertexDeclarations(void);
356
357 static void R_Mesh_SetUseVBO(void)
358 {
359         switch(vid.renderpath)
360         {
361         case RENDERPATH_GL11:
362         case RENDERPATH_GL13:
363         case RENDERPATH_GL20:
364         case RENDERPATH_GLES1:
365                 gl_state.usevbo_staticvertex = (vid.support.arb_vertex_buffer_object && gl_vbo.integer) || vid.forcevbo;
366                 gl_state.usevbo_staticindex = (vid.support.arb_vertex_buffer_object && (gl_vbo.integer == 1 || gl_vbo.integer == 3)) || vid.forcevbo;
367                 gl_state.usevbo_dynamicvertex = (vid.support.arb_vertex_buffer_object && gl_vbo_dynamicvertex.integer && gl_vbo.integer) || vid.forcevbo;
368                 gl_state.usevbo_dynamicindex = (vid.support.arb_vertex_buffer_object && gl_vbo_dynamicindex.integer && gl_vbo.integer) || vid.forcevbo;
369                 break;
370         case RENDERPATH_D3D9:
371                 gl_state.usevbo_staticvertex = gl_state.usevbo_staticindex = (vid.support.arb_vertex_buffer_object && gl_vbo.integer) || vid.forcevbo;
372                 gl_state.usevbo_dynamicvertex = gl_state.usevbo_dynamicindex = (vid.support.arb_vertex_buffer_object && gl_vbo_dynamicvertex.integer && gl_vbo_dynamicindex.integer && gl_vbo.integer) || vid.forcevbo;
373                 break;
374         case RENDERPATH_D3D10:
375                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
376                 break;
377         case RENDERPATH_D3D11:
378                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
379                 break;
380         case RENDERPATH_SOFT:
381                 gl_state.usevbo_staticvertex = false;
382                 gl_state.usevbo_staticindex = false;
383                 gl_state.usevbo_dynamicvertex = false;
384                 gl_state.usevbo_dynamicindex = false;
385                 break;
386         case RENDERPATH_GLES2:
387                 gl_state.usevbo_staticvertex = (vid.support.arb_vertex_buffer_object && gl_vbo.integer) || vid.forcevbo;
388                 gl_state.usevbo_staticindex = (vid.support.arb_vertex_buffer_object && gl_vbo.integer) || vid.forcevbo;
389                 gl_state.usevbo_dynamicvertex = (vid.support.arb_vertex_buffer_object && gl_vbo_dynamicvertex.integer) || vid.forcevbo;
390                 gl_state.usevbo_dynamicindex = (vid.support.arb_vertex_buffer_object && gl_vbo_dynamicindex.integer) || vid.forcevbo;
391                 break;
392         }
393 }
394
395 static void gl_backend_start(void)
396 {
397         memset(&gl_state, 0, sizeof(gl_state));
398
399         R_Mesh_InitVertexDeclarations();
400
401         R_Mesh_SetUseVBO();
402         Mem_ExpandableArray_NewArray(&gl_state.meshbufferarray, r_main_mempool, sizeof(r_meshbuffer_t), 128);
403
404         Con_DPrintf("OpenGL backend started.\n");
405
406         CHECKGLERROR
407
408         GL_Backend_ResetState();
409
410         switch(vid.renderpath)
411         {
412         case RENDERPATH_GL11:
413         case RENDERPATH_GL13:
414         case RENDERPATH_GL20:
415         case RENDERPATH_GLES1:
416         case RENDERPATH_GLES2:
417                 // fetch current fbo here (default fbo is not 0 on some GLES devices)
418                 if (vid.support.ext_framebuffer_object)
419                         qglGetIntegerv(GL_FRAMEBUFFER_BINDING, &gl_state.defaultframebufferobject);
420                 break;
421         case RENDERPATH_D3D9:
422 #ifdef SUPPORTD3D
423                 IDirect3DDevice9_GetDepthStencilSurface(vid_d3d9dev, &gl_state.d3drt_backbufferdepthsurface);
424                 IDirect3DDevice9_GetRenderTarget(vid_d3d9dev, 0, &gl_state.d3drt_backbuffercolorsurface);
425 #endif
426                 break;
427         case RENDERPATH_D3D10:
428                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
429                 break;
430         case RENDERPATH_D3D11:
431                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
432                 break;
433         case RENDERPATH_SOFT:
434                 break;
435         }
436 }
437
438 static void gl_backend_shutdown(void)
439 {
440         Con_DPrint("OpenGL Backend shutting down\n");
441
442         switch(vid.renderpath)
443         {
444         case RENDERPATH_GL11:
445         case RENDERPATH_GL13:
446         case RENDERPATH_GL20:
447         case RENDERPATH_SOFT:
448         case RENDERPATH_GLES1:
449         case RENDERPATH_GLES2:
450                 break;
451         case RENDERPATH_D3D9:
452 #ifdef SUPPORTD3D
453                 IDirect3DSurface9_Release(gl_state.d3drt_backbufferdepthsurface);
454                 IDirect3DSurface9_Release(gl_state.d3drt_backbuffercolorsurface);
455 #endif
456                 break;
457         case RENDERPATH_D3D10:
458                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
459                 break;
460         case RENDERPATH_D3D11:
461                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
462                 break;
463         }
464
465         if (gl_state.preparevertices_tempdata)
466                 Mem_Free(gl_state.preparevertices_tempdata);
467
468         Mem_ExpandableArray_FreeArray(&gl_state.meshbufferarray);
469
470         R_Mesh_DestroyVertexDeclarations();
471
472         memset(&gl_state, 0, sizeof(gl_state));
473 }
474
475 static void gl_backend_newmap(void)
476 {
477 }
478
479 static void gl_backend_devicelost(void)
480 {
481         int i, endindex;
482         r_meshbuffer_t *buffer;
483 #ifdef SUPPORTD3D
484         gl_state.d3dvertexbuffer = NULL;
485 #endif
486         switch(vid.renderpath)
487         {
488         case RENDERPATH_GL11:
489         case RENDERPATH_GL13:
490         case RENDERPATH_GL20:
491         case RENDERPATH_SOFT:
492         case RENDERPATH_GLES1:
493         case RENDERPATH_GLES2:
494                 break;
495         case RENDERPATH_D3D9:
496 #ifdef SUPPORTD3D
497                 IDirect3DSurface9_Release(gl_state.d3drt_backbufferdepthsurface);
498                 IDirect3DSurface9_Release(gl_state.d3drt_backbuffercolorsurface);
499 #endif
500                 break;
501         case RENDERPATH_D3D10:
502                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
503                 break;
504         case RENDERPATH_D3D11:
505                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
506                 break;
507         }
508         endindex = (int)Mem_ExpandableArray_IndexRange(&gl_state.meshbufferarray);
509         for (i = 0;i < endindex;i++)
510         {
511                 buffer = (r_meshbuffer_t *) Mem_ExpandableArray_RecordAtIndex(&gl_state.meshbufferarray, i);
512                 if (!buffer || !buffer->isdynamic)
513                         continue;
514                 switch(vid.renderpath)
515                 {
516                 case RENDERPATH_GL11:
517                 case RENDERPATH_GL13:
518                 case RENDERPATH_GL20:
519                 case RENDERPATH_SOFT:
520                 case RENDERPATH_GLES1:
521                 case RENDERPATH_GLES2:
522                         break;
523                 case RENDERPATH_D3D9:
524 #ifdef SUPPORTD3D
525                         if (buffer->devicebuffer)
526                         {
527                                 if (buffer->isindexbuffer)
528                                         IDirect3DIndexBuffer9_Release((IDirect3DIndexBuffer9*)buffer->devicebuffer);
529                                 else
530                                         IDirect3DVertexBuffer9_Release((IDirect3DVertexBuffer9*)buffer->devicebuffer);
531                                 buffer->devicebuffer = NULL;
532                         }
533 #endif
534                         break;
535                 case RENDERPATH_D3D10:
536                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
537                         break;
538                 case RENDERPATH_D3D11:
539                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
540                         break;
541                 }
542         }
543 }
544
545 static void gl_backend_devicerestored(void)
546 {
547         switch(vid.renderpath)
548         {
549         case RENDERPATH_GL11:
550         case RENDERPATH_GL13:
551         case RENDERPATH_GL20:
552         case RENDERPATH_SOFT:
553         case RENDERPATH_GLES1:
554         case RENDERPATH_GLES2:
555                 break;
556         case RENDERPATH_D3D9:
557 #ifdef SUPPORTD3D
558                 IDirect3DDevice9_GetDepthStencilSurface(vid_d3d9dev, &gl_state.d3drt_backbufferdepthsurface);
559                 IDirect3DDevice9_GetRenderTarget(vid_d3d9dev, 0, &gl_state.d3drt_backbuffercolorsurface);
560 #endif
561                 break;
562         case RENDERPATH_D3D10:
563                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
564                 break;
565         case RENDERPATH_D3D11:
566                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
567                 break;
568         }
569 }
570
571 void gl_backend_init(void)
572 {
573         int i;
574
575         for (i = 0;i < POLYGONELEMENTS_MAXPOINTS - 2;i++)
576         {
577                 polygonelement3s[i * 3 + 0] = 0;
578                 polygonelement3s[i * 3 + 1] = i + 1;
579                 polygonelement3s[i * 3 + 2] = i + 2;
580         }
581         // elements for rendering a series of quads as triangles
582         for (i = 0;i < QUADELEMENTS_MAXQUADS;i++)
583         {
584                 quadelement3s[i * 6 + 0] = i * 4;
585                 quadelement3s[i * 6 + 1] = i * 4 + 1;
586                 quadelement3s[i * 6 + 2] = i * 4 + 2;
587                 quadelement3s[i * 6 + 3] = i * 4;
588                 quadelement3s[i * 6 + 4] = i * 4 + 2;
589                 quadelement3s[i * 6 + 5] = i * 4 + 3;
590         }
591
592         for (i = 0;i < (POLYGONELEMENTS_MAXPOINTS - 2)*3;i++)
593                 polygonelement3i[i] = polygonelement3s[i];
594         for (i = 0;i < QUADELEMENTS_MAXQUADS*6;i++)
595                 quadelement3i[i] = quadelement3s[i];
596
597         Cvar_RegisterVariable(&r_render);
598         Cvar_RegisterVariable(&r_renderview);
599         Cvar_RegisterVariable(&r_waterwarp);
600         Cvar_RegisterVariable(&gl_polyblend);
601         Cvar_RegisterVariable(&v_flipped);
602         Cvar_RegisterVariable(&gl_dither);
603         Cvar_RegisterVariable(&gl_vbo);
604         Cvar_RegisterVariable(&gl_vbo_dynamicvertex);
605         Cvar_RegisterVariable(&gl_vbo_dynamicindex);
606         Cvar_RegisterVariable(&gl_paranoid);
607         Cvar_RegisterVariable(&gl_printcheckerror);
608
609         Cvar_RegisterVariable(&gl_mesh_drawrangeelements);
610         Cvar_RegisterVariable(&gl_mesh_testmanualfeeding);
611
612         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");
613
614         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap, gl_backend_devicelost, gl_backend_devicerestored);
615 }
616
617 void GL_SetMirrorState(qboolean state);
618
619 void R_Viewport_TransformToScreen(const r_viewport_t *v, const vec4_t in, vec4_t out)
620 {
621         vec4_t temp;
622         float iw;
623         Matrix4x4_Transform4 (&v->viewmatrix, in, temp);
624         Matrix4x4_Transform4 (&v->projectmatrix, temp, out);
625         iw = 1.0f / out[3];
626         out[0] = v->x + (out[0] * iw + 1.0f) * v->width * 0.5f;
627
628         // for an odd reason, inverting this is wrong for R_Shadow_ScissorForBBox (we then get badly scissored lights)
629         //out[1] = v->y + v->height - (out[1] * iw + 1.0f) * v->height * 0.5f;
630         out[1] = v->y + (out[1] * iw + 1.0f) * v->height * 0.5f;
631
632         out[2] = v->z + (out[2] * iw + 1.0f) * v->depth * 0.5f;
633 }
634
635 void GL_Finish(void)
636 {
637         switch(vid.renderpath)
638         {
639         case RENDERPATH_GL11:
640         case RENDERPATH_GL13:
641         case RENDERPATH_GL20:
642         case RENDERPATH_GLES1:
643         case RENDERPATH_GLES2:
644                 qglFinish();
645                 break;
646         case RENDERPATH_D3D9:
647                 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
648                 break;
649         case RENDERPATH_D3D10:
650                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
651                 break;
652         case RENDERPATH_D3D11:
653                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
654                 break;
655         case RENDERPATH_SOFT:
656                 DPSOFTRAST_Finish();
657                 break;
658         }
659 }
660
661 static int bboxedges[12][2] =
662 {
663         // top
664         {0, 1}, // +X
665         {0, 2}, // +Y
666         {1, 3}, // Y, +X
667         {2, 3}, // X, +Y
668         // bottom
669         {4, 5}, // +X
670         {4, 6}, // +Y
671         {5, 7}, // Y, +X
672         {6, 7}, // X, +Y
673         // verticals
674         {0, 4}, // +Z
675         {1, 5}, // X, +Z
676         {2, 6}, // Y, +Z
677         {3, 7}, // XY, +Z
678 };
679
680 qboolean R_ScissorForBBox(const float *mins, const float *maxs, int *scissor)
681 {
682         int i, ix1, iy1, ix2, iy2;
683         float x1, y1, x2, y2;
684         vec4_t v, v2;
685         float vertex[20][3];
686         int j, k;
687         vec4_t plane4f;
688         int numvertices;
689         float corner[8][4];
690         float dist[8];
691         int sign[8];
692         float f;
693
694         scissor[0] = r_refdef.view.viewport.x;
695         scissor[1] = r_refdef.view.viewport.y;
696         scissor[2] = r_refdef.view.viewport.width;
697         scissor[3] = r_refdef.view.viewport.height;
698
699         // if view is inside the box, just say yes it's visible
700         if (BoxesOverlap(r_refdef.view.origin, r_refdef.view.origin, mins, maxs))
701                 return false;
702
703         // transform all corners that are infront of the nearclip plane
704         VectorNegate(r_refdef.view.frustum[4].normal, plane4f);
705         plane4f[3] = r_refdef.view.frustum[4].dist;
706         numvertices = 0;
707         for (i = 0;i < 8;i++)
708         {
709                 Vector4Set(corner[i], (i & 1) ? maxs[0] : mins[0], (i & 2) ? maxs[1] : mins[1], (i & 4) ? maxs[2] : mins[2], 1);
710                 dist[i] = DotProduct4(corner[i], plane4f);
711                 sign[i] = dist[i] > 0;
712                 if (!sign[i])
713                 {
714                         VectorCopy(corner[i], vertex[numvertices]);
715                         numvertices++;
716                 }
717         }
718         // if some points are behind the nearclip, add clipped edge points to make
719         // sure that the scissor boundary is complete
720         if (numvertices > 0 && numvertices < 8)
721         {
722                 // add clipped edge points
723                 for (i = 0;i < 12;i++)
724                 {
725                         j = bboxedges[i][0];
726                         k = bboxedges[i][1];
727                         if (sign[j] != sign[k])
728                         {
729                                 f = dist[j] / (dist[j] - dist[k]);
730                                 VectorLerp(corner[j], f, corner[k], vertex[numvertices]);
731                                 numvertices++;
732                         }
733                 }
734         }
735
736         // if we have no points to check, it is behind the view plane
737         if (!numvertices)
738                 return true;
739
740         // if we have some points to transform, check what screen area is covered
741         x1 = y1 = x2 = y2 = 0;
742         v[3] = 1.0f;
743         //Con_Printf("%i vertices to transform...\n", numvertices);
744         for (i = 0;i < numvertices;i++)
745         {
746                 VectorCopy(vertex[i], v);
747                 R_Viewport_TransformToScreen(&r_refdef.view.viewport, v, v2);
748                 //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]);
749                 if (i)
750                 {
751                         if (x1 > v2[0]) x1 = v2[0];
752                         if (x2 < v2[0]) x2 = v2[0];
753                         if (y1 > v2[1]) y1 = v2[1];
754                         if (y2 < v2[1]) y2 = v2[1];
755                 }
756                 else
757                 {
758                         x1 = x2 = v2[0];
759                         y1 = y2 = v2[1];
760                 }
761         }
762
763         // now convert the scissor rectangle to integer screen coordinates
764         ix1 = (int)(x1 - 1.0f);
765         //iy1 = vid.height - (int)(y2 - 1.0f);
766         //iy1 = r_refdef.view.viewport.width + 2 * r_refdef.view.viewport.x - (int)(y2 - 1.0f);
767         iy1 = (int)(y1 - 1.0f);
768         ix2 = (int)(x2 + 1.0f);
769         //iy2 = vid.height - (int)(y1 + 1.0f);
770         //iy2 = r_refdef.view.viewport.height + 2 * r_refdef.view.viewport.y - (int)(y1 + 1.0f);
771         iy2 = (int)(y2 + 1.0f);
772         //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2);
773
774         // clamp it to the screen
775         if (ix1 < r_refdef.view.viewport.x) ix1 = r_refdef.view.viewport.x;
776         if (iy1 < r_refdef.view.viewport.y) iy1 = r_refdef.view.viewport.y;
777         if (ix2 > r_refdef.view.viewport.x + r_refdef.view.viewport.width) ix2 = r_refdef.view.viewport.x + r_refdef.view.viewport.width;
778         if (iy2 > r_refdef.view.viewport.y + r_refdef.view.viewport.height) iy2 = r_refdef.view.viewport.y + r_refdef.view.viewport.height;
779
780         // if it is inside out, it's not visible
781         if (ix2 <= ix1 || iy2 <= iy1)
782                 return true;
783
784         // the light area is visible, set up the scissor rectangle
785         scissor[0] = ix1;
786         scissor[1] = iy1;
787         scissor[2] = ix2 - ix1;
788         scissor[3] = iy2 - iy1;
789
790         // D3D Y coordinate is top to bottom, OpenGL is bottom to top, fix the D3D one
791         switch(vid.renderpath)
792         {
793         case RENDERPATH_D3D9:
794         case RENDERPATH_D3D10:
795         case RENDERPATH_D3D11:
796                 scissor[1] = vid.height - scissor[1] - scissor[3];
797                 break;
798         case RENDERPATH_GL11:
799         case RENDERPATH_GL13:
800         case RENDERPATH_GL20:
801         case RENDERPATH_SOFT:
802         case RENDERPATH_GLES1:
803         case RENDERPATH_GLES2:
804                 break;
805         }
806
807         return false;
808 }
809
810
811 static void R_Viewport_ApplyNearClipPlaneFloatGL(const r_viewport_t *v, float *m, float normalx, float normaly, float normalz, float dist)
812 {
813         float q[4];
814         float d;
815         float clipPlane[4], v3[3], v4[3];
816         float normal[3];
817
818         // This is inspired by Oblique Depth Projection from http://www.terathon.com/code/oblique.php
819
820         VectorSet(normal, normalx, normaly, normalz);
821         Matrix4x4_Transform3x3(&v->viewmatrix, normal, clipPlane);
822         VectorScale(normal, -dist, v3);
823         Matrix4x4_Transform(&v->viewmatrix, v3, v4);
824         // FIXME: LordHavoc: I think this can be done more efficiently somehow but I can't remember the technique
825         clipPlane[3] = -DotProduct(v4, clipPlane);
826
827 #if 0
828 {
829         // testing code for comparing results
830         float clipPlane2[4];
831         VectorCopy4(clipPlane, clipPlane2);
832         R_EntityMatrix(&identitymatrix);
833         VectorSet(q, normal[0], normal[1], normal[2], -dist);
834         qglClipPlane(GL_CLIP_PLANE0, q);
835         qglGetClipPlane(GL_CLIP_PLANE0, q);
836         VectorCopy4(q, clipPlane);
837 }
838 #endif
839
840         // Calculate the clip-space corner point opposite the clipping plane
841         // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and
842         // transform it into camera space by multiplying it
843         // by the inverse of the projection matrix
844         q[0] = ((clipPlane[0] < 0.0f ? -1.0f : clipPlane[0] > 0.0f ? 1.0f : 0.0f) + m[8]) / m[0];
845         q[1] = ((clipPlane[1] < 0.0f ? -1.0f : clipPlane[1] > 0.0f ? 1.0f : 0.0f) + m[9]) / m[5];
846         q[2] = -1.0f;
847         q[3] = (1.0f + m[10]) / m[14];
848
849         // Calculate the scaled plane vector
850         d = 2.0f / DotProduct4(clipPlane, q);
851
852         // Replace the third row of the projection matrix
853         m[2] = clipPlane[0] * d;
854         m[6] = clipPlane[1] * d;
855         m[10] = clipPlane[2] * d + 1.0f;
856         m[14] = clipPlane[3] * d;
857 }
858
859 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)
860 {
861         float left = x1, right = x2, bottom = y2, top = y1, zNear = nearclip, zFar = farclip;
862         float m[16];
863         memset(v, 0, sizeof(*v));
864         v->type = R_VIEWPORTTYPE_ORTHO;
865         v->cameramatrix = *cameramatrix;
866         v->x = x;
867         v->y = y;
868         v->z = 0;
869         v->width = width;
870         v->height = height;
871         v->depth = 1;
872         memset(m, 0, sizeof(m));
873         m[0]  = 2/(right - left);
874         m[5]  = 2/(top - bottom);
875         m[10] = -2/(zFar - zNear);
876         m[12] = - (right + left)/(right - left);
877         m[13] = - (top + bottom)/(top - bottom);
878         m[14] = - (zFar + zNear)/(zFar - zNear);
879         m[15] = 1;
880         switch(vid.renderpath)
881         {
882         case RENDERPATH_GL11:
883         case RENDERPATH_GL13:
884         case RENDERPATH_GL20:
885         case RENDERPATH_SOFT:
886         case RENDERPATH_GLES1:
887         case RENDERPATH_GLES2:
888                 break;
889         case RENDERPATH_D3D9:
890         case RENDERPATH_D3D10:
891         case RENDERPATH_D3D11:
892                 m[10] = -1/(zFar - zNear);
893                 m[14] = -zNear/(zFar-zNear);
894                 break;
895         }
896         v->screentodepth[0] = -farclip / (farclip - nearclip);
897         v->screentodepth[1] = farclip * nearclip / (farclip - nearclip);
898
899         Matrix4x4_Invert_Full(&v->viewmatrix, &v->cameramatrix);
900
901         if (nearplane)
902                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
903
904         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
905
906 #if 0
907         {
908                 vec4_t test1;
909                 vec4_t test2;
910                 Vector4Set(test1, (x1+x2)*0.5f, (y1+y2)*0.5f, 0.0f, 1.0f);
911                 R_Viewport_TransformToScreen(v, test1, test2);
912                 Con_Printf("%f %f %f -> %f %f %f\n", test1[0], test1[1], test1[2], test2[0], test2[1], test2[2]);
913         }
914 #endif
915 }
916
917 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)
918 {
919         matrix4x4_t tempmatrix, basematrix;
920         float m[16];
921         memset(v, 0, sizeof(*v));
922
923         v->type = R_VIEWPORTTYPE_PERSPECTIVE;
924         v->cameramatrix = *cameramatrix;
925         v->x = x;
926         v->y = y;
927         v->z = 0;
928         v->width = width;
929         v->height = height;
930         v->depth = 1;
931         memset(m, 0, sizeof(m));
932         m[0]  = 1.0 / frustumx;
933         m[5]  = 1.0 / frustumy;
934         m[10] = -2 / (farclip - nearclip);
935         m[14] = -(farclip + nearclip) / (farclip - nearclip);
936         m[15] = 1;
937         v->screentodepth[0] = -farclip / (farclip - nearclip);
938         v->screentodepth[1] = farclip * nearclip / (farclip - nearclip);
939
940         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
941         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
942         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
943         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
944
945         if (nearplane)
946                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
947
948         if(v_flipped.integer)
949         {
950                 m[0] = -m[0];
951                 m[4] = -m[4];
952                 m[8] = -m[8];
953                 m[12] = -m[12];
954         }
955
956         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
957 }
958
959 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)
960 {
961         matrix4x4_t tempmatrix, basematrix;
962         float m[16];
963         memset(v, 0, sizeof(*v));
964
965         v->type = R_VIEWPORTTYPE_PERSPECTIVE;
966         v->cameramatrix = *cameramatrix;
967         v->x = x;
968         v->y = y;
969         v->z = 0;
970         v->width = width;
971         v->height = height;
972         v->depth = 1;
973         memset(m, 0, sizeof(m));
974         m[0]  = 1.0 / frustumx;
975         m[5]  = 1.0 / frustumy;
976         m[10] = -(farclip + nearclip) / (farclip - nearclip);
977         m[11] = -1;
978         m[14] = -2 * nearclip * farclip / (farclip - nearclip);
979         v->screentodepth[0] = -farclip / (farclip - nearclip);
980         v->screentodepth[1] = farclip * nearclip / (farclip - nearclip);
981
982         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
983         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
984         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
985         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
986
987         if (nearplane)
988                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
989
990         if(v_flipped.integer)
991         {
992                 m[0] = -m[0];
993                 m[4] = -m[4];
994                 m[8] = -m[8];
995                 m[12] = -m[12];
996         }
997
998         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
999 }
1000
1001 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)
1002 {
1003         matrix4x4_t tempmatrix, basematrix;
1004         const float nudge = 1.0 - 1.0 / (1<<23);
1005         float m[16];
1006         memset(v, 0, sizeof(*v));
1007
1008         v->type = R_VIEWPORTTYPE_PERSPECTIVE_INFINITEFARCLIP;
1009         v->cameramatrix = *cameramatrix;
1010         v->x = x;
1011         v->y = y;
1012         v->z = 0;
1013         v->width = width;
1014         v->height = height;
1015         v->depth = 1;
1016         memset(m, 0, sizeof(m));
1017         m[ 0] = 1.0 / frustumx;
1018         m[ 5] = 1.0 / frustumy;
1019         m[10] = -nudge;
1020         m[11] = -1;
1021         m[14] = -2 * nearclip * nudge;
1022         v->screentodepth[0] = (m[10] + 1) * 0.5 - 1;
1023         v->screentodepth[1] = m[14] * -0.5;
1024
1025         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
1026         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
1027         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
1028         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
1029
1030         if (nearplane)
1031                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
1032
1033         if(v_flipped.integer)
1034         {
1035                 m[0] = -m[0];
1036                 m[4] = -m[4];
1037                 m[8] = -m[8];
1038                 m[12] = -m[12];
1039         }
1040
1041         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
1042 }
1043
1044 float cubeviewmatrix[6][16] =
1045 {
1046     // standard cubemap projections
1047     { // +X
1048          0, 0,-1, 0,
1049          0,-1, 0, 0,
1050         -1, 0, 0, 0,
1051          0, 0, 0, 1,
1052     },
1053     { // -X
1054          0, 0, 1, 0,
1055          0,-1, 0, 0,
1056          1, 0, 0, 0,
1057          0, 0, 0, 1,
1058     },
1059     { // +Y
1060          1, 0, 0, 0,
1061          0, 0,-1, 0,
1062          0, 1, 0, 0,
1063          0, 0, 0, 1,
1064     },
1065     { // -Y
1066          1, 0, 0, 0,
1067          0, 0, 1, 0,
1068          0,-1, 0, 0,
1069          0, 0, 0, 1,
1070     },
1071     { // +Z
1072          1, 0, 0, 0,
1073          0,-1, 0, 0,
1074          0, 0,-1, 0,
1075          0, 0, 0, 1,
1076     },
1077     { // -Z
1078         -1, 0, 0, 0,
1079          0,-1, 0, 0,
1080          0, 0, 1, 0,
1081          0, 0, 0, 1,
1082     },
1083 };
1084 float rectviewmatrix[6][16] =
1085 {
1086     // sign-preserving cubemap projections
1087     { // +X
1088          0, 0,-1, 0,
1089          0, 1, 0, 0,
1090          1, 0, 0, 0,
1091          0, 0, 0, 1,
1092     },
1093     { // -X
1094          0, 0, 1, 0,
1095          0, 1, 0, 0,
1096          1, 0, 0, 0,
1097          0, 0, 0, 1,
1098     },
1099     { // +Y
1100          1, 0, 0, 0,
1101          0, 0,-1, 0,
1102          0, 1, 0, 0,
1103          0, 0, 0, 1,
1104     },
1105     { // -Y
1106          1, 0, 0, 0,
1107          0, 0, 1, 0,
1108          0, 1, 0, 0,
1109          0, 0, 0, 1,
1110     },
1111     { // +Z
1112          1, 0, 0, 0,
1113          0, 1, 0, 0,
1114          0, 0,-1, 0,
1115          0, 0, 0, 1,
1116     },
1117     { // -Z
1118          1, 0, 0, 0,
1119          0, 1, 0, 0,
1120          0, 0, 1, 0,
1121          0, 0, 0, 1,
1122     },
1123 };
1124
1125 void R_Viewport_InitCubeSideView(r_viewport_t *v, const matrix4x4_t *cameramatrix, int side, int size, float nearclip, float farclip, const float *nearplane)
1126 {
1127         matrix4x4_t tempmatrix, basematrix;
1128         float m[16];
1129         memset(v, 0, sizeof(*v));
1130         v->type = R_VIEWPORTTYPE_PERSPECTIVECUBESIDE;
1131         v->cameramatrix = *cameramatrix;
1132         v->width = size;
1133         v->height = size;
1134         v->depth = 1;
1135         memset(m, 0, sizeof(m));
1136         m[0] = m[5] = 1.0f;
1137         m[10] = -(farclip + nearclip) / (farclip - nearclip);
1138         m[11] = -1;
1139         m[14] = -2 * nearclip * farclip / (farclip - nearclip);
1140
1141         Matrix4x4_FromArrayFloatGL(&basematrix, cubeviewmatrix[side]);
1142         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
1143         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
1144
1145         if (nearplane)
1146                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
1147
1148         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
1149 }
1150
1151 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)
1152 {
1153         matrix4x4_t tempmatrix, basematrix;
1154         float m[16];
1155         memset(v, 0, sizeof(*v));
1156         v->type = R_VIEWPORTTYPE_PERSPECTIVECUBESIDE;
1157         v->cameramatrix = *cameramatrix;
1158         v->x = offsetx + (side & 1) * size;
1159         v->y = offsety + (side >> 1) * size;
1160         v->width = size;
1161         v->height = size;
1162         v->depth = 1;
1163         memset(m, 0, sizeof(m));
1164         m[0] = m[5] = 1.0f * ((float)size - border) / size;
1165         m[10] = -(farclip + nearclip) / (farclip - nearclip);
1166         m[11] = -1;
1167         m[14] = -2 * nearclip * farclip / (farclip - nearclip);
1168
1169         Matrix4x4_FromArrayFloatGL(&basematrix, rectviewmatrix[side]);
1170         Matrix4x4_Invert_Full(&tempmatrix, &v->cameramatrix);
1171         Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
1172
1173         switch(vid.renderpath)
1174         {
1175         case RENDERPATH_GL20:
1176         case RENDERPATH_GL13:
1177         case RENDERPATH_GL11:
1178         case RENDERPATH_SOFT:
1179         case RENDERPATH_GLES1:
1180         case RENDERPATH_GLES2:
1181                 break;
1182         case RENDERPATH_D3D9:
1183                 m[5] *= -1;
1184                 break;
1185         case RENDERPATH_D3D10:
1186                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1187                 break;
1188         case RENDERPATH_D3D11:
1189                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1190                 break;
1191         }
1192
1193         if (nearplane)
1194                 R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
1195
1196         Matrix4x4_FromArrayFloatGL(&v->projectmatrix, m);
1197 }
1198
1199 void R_SetViewport(const r_viewport_t *v)
1200 {
1201         gl_viewport = *v;
1202
1203         // FIXME: v_flipped_state is evil, this probably breaks somewhere
1204         GL_SetMirrorState(v_flipped.integer && (v->type == R_VIEWPORTTYPE_PERSPECTIVE || v->type == R_VIEWPORTTYPE_PERSPECTIVE_INFINITEFARCLIP));
1205
1206         // copy over the matrices to our state
1207         gl_viewmatrix = v->viewmatrix;
1208         gl_projectionmatrix = v->projectmatrix;
1209
1210         switch(vid.renderpath)
1211         {
1212         case RENDERPATH_GL13:
1213         case RENDERPATH_GL11:
1214         case RENDERPATH_GLES1:
1215 #ifndef USE_GLES2
1216                 {
1217                         float m[16];
1218                         CHECKGLERROR
1219                         qglViewport(v->x, v->y, v->width, v->height);CHECKGLERROR
1220                         // Load the projection matrix into OpenGL
1221                         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
1222                         Matrix4x4_ToArrayFloatGL(&gl_projectionmatrix, m);
1223                         qglLoadMatrixf(m);CHECKGLERROR
1224                         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
1225                 }
1226 #endif
1227                 break;
1228         case RENDERPATH_D3D9:
1229 #ifdef SUPPORTD3D
1230                 {
1231                         D3DVIEWPORT9 d3dviewport;
1232                         d3dviewport.X = gl_viewport.x;
1233                         d3dviewport.Y = gl_viewport.y;
1234                         d3dviewport.Width = gl_viewport.width;
1235                         d3dviewport.Height = gl_viewport.height;
1236                         d3dviewport.MinZ = gl_state.depthrange[0];
1237                         d3dviewport.MaxZ = gl_state.depthrange[1];
1238                         IDirect3DDevice9_SetViewport(vid_d3d9dev, &d3dviewport);
1239                 }
1240 #endif
1241                 break;
1242         case RENDERPATH_D3D10:
1243                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1244                 break;
1245         case RENDERPATH_D3D11:
1246                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1247                 break;
1248         case RENDERPATH_SOFT:
1249                 DPSOFTRAST_Viewport(v->x, v->y, v->width, v->height);
1250                 break;
1251         case RENDERPATH_GL20:
1252         case RENDERPATH_GLES2:
1253                 CHECKGLERROR
1254                 qglViewport(v->x, v->y, v->width, v->height);CHECKGLERROR
1255                 break;
1256         }
1257
1258         // force an update of the derived matrices
1259         gl_modelmatrixchanged = true;
1260         R_EntityMatrix(&gl_modelmatrix);
1261 }
1262
1263 void R_GetViewport(r_viewport_t *v)
1264 {
1265         *v = gl_viewport;
1266 }
1267
1268 static void GL_BindVBO(int bufferobject)
1269 {
1270         if (gl_state.vertexbufferobject != bufferobject)
1271         {
1272                 gl_state.vertexbufferobject = bufferobject;
1273                 CHECKGLERROR
1274                 qglBindBufferARB(GL_ARRAY_BUFFER, bufferobject);CHECKGLERROR
1275         }
1276 }
1277
1278 static void GL_BindEBO(int bufferobject)
1279 {
1280         if (gl_state.elementbufferobject != bufferobject)
1281         {
1282                 gl_state.elementbufferobject = bufferobject;
1283                 CHECKGLERROR
1284                 qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, bufferobject);CHECKGLERROR
1285         }
1286 }
1287
1288 static void GL_BindUBO(int bufferobject)
1289 {
1290         if (gl_state.uniformbufferobject != bufferobject)
1291         {
1292                 gl_state.uniformbufferobject = bufferobject;
1293 #ifdef GL_UNIFORM_BUFFER
1294                 CHECKGLERROR
1295                 qglBindBufferARB(GL_UNIFORM_BUFFER, bufferobject);CHECKGLERROR
1296 #endif
1297         }
1298 }
1299
1300 static const GLuint drawbuffers[4] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3};
1301 int R_Mesh_CreateFramebufferObject(rtexture_t *depthtexture, rtexture_t *colortexture, rtexture_t *colortexture2, rtexture_t *colortexture3, rtexture_t *colortexture4)
1302 {
1303         switch(vid.renderpath)
1304         {
1305         case RENDERPATH_GL11:
1306         case RENDERPATH_GL13:
1307         case RENDERPATH_GL20:
1308         case RENDERPATH_GLES1:
1309         case RENDERPATH_GLES2:
1310                 if (vid.support.arb_framebuffer_object)
1311                 {
1312                         int temp;
1313                         GLuint status;
1314                         qglGenFramebuffers(1, (GLuint*)&temp);CHECKGLERROR
1315                         R_Mesh_SetRenderTargets(temp, NULL, NULL, NULL, NULL, NULL);
1316                         // GL_ARB_framebuffer_object (GL3-class hardware) - depth stencil attachment
1317 #ifdef USE_GLES2
1318                         // FIXME: separate stencil attachment on GLES
1319                         if (depthtexture  && depthtexture->texnum ) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , depthtexture->gltexturetypeenum , depthtexture->texnum , 0);CHECKGLERROR
1320                         if (depthtexture  && depthtexture->renderbuffernum ) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , GL_RENDERBUFFER, depthtexture->renderbuffernum );CHECKGLERROR
1321 #else
1322                         if (depthtexture  && depthtexture->texnum )
1323                         {
1324                                 qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , depthtexture->gltexturetypeenum , depthtexture->texnum , 0);CHECKGLERROR
1325                                 if (depthtexture->glisdepthstencil) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT  , depthtexture->gltexturetypeenum , depthtexture->texnum , 0);CHECKGLERROR
1326                         }
1327                         if (depthtexture  && depthtexture->renderbuffernum )
1328                         {
1329                                 qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , GL_RENDERBUFFER, depthtexture->renderbuffernum );CHECKGLERROR
1330                                 if (depthtexture->glisdepthstencil) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT  , GL_RENDERBUFFER, depthtexture->renderbuffernum );CHECKGLERROR
1331                         }
1332 #endif
1333                         if (colortexture  && colortexture->texnum ) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 , colortexture->gltexturetypeenum , colortexture->texnum , 0);CHECKGLERROR
1334                         if (colortexture2 && colortexture2->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1 , colortexture2->gltexturetypeenum, colortexture2->texnum, 0);CHECKGLERROR
1335                         if (colortexture3 && colortexture3->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2 , colortexture3->gltexturetypeenum, colortexture3->texnum, 0);CHECKGLERROR
1336                         if (colortexture4 && colortexture4->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3 , colortexture4->gltexturetypeenum, colortexture4->texnum, 0);CHECKGLERROR
1337                         if (colortexture  && colortexture->renderbuffernum ) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 , GL_RENDERBUFFER, colortexture->renderbuffernum );CHECKGLERROR
1338                         if (colortexture2 && colortexture2->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1 , GL_RENDERBUFFER, colortexture2->renderbuffernum);CHECKGLERROR
1339                         if (colortexture3 && colortexture3->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2 , GL_RENDERBUFFER, colortexture3->renderbuffernum);CHECKGLERROR
1340                         if (colortexture4 && colortexture4->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3 , GL_RENDERBUFFER, colortexture4->renderbuffernum);CHECKGLERROR
1341
1342 #ifndef USE_GLES2
1343                         if (colortexture4 && qglDrawBuffersARB)
1344                         {
1345                                 qglDrawBuffersARB(4, drawbuffers);CHECKGLERROR
1346                                 qglReadBuffer(GL_NONE);CHECKGLERROR
1347                         }
1348                         else if (colortexture3 && qglDrawBuffersARB)
1349                         {
1350                                 qglDrawBuffersARB(3, drawbuffers);CHECKGLERROR
1351                                 qglReadBuffer(GL_NONE);CHECKGLERROR
1352                         }
1353                         else if (colortexture2 && qglDrawBuffersARB)
1354                         {
1355                                 qglDrawBuffersARB(2, drawbuffers);CHECKGLERROR
1356                                 qglReadBuffer(GL_NONE);CHECKGLERROR
1357                         }
1358                         else if (colortexture && qglDrawBuffer)
1359                         {
1360                                 qglDrawBuffer(GL_COLOR_ATTACHMENT0);CHECKGLERROR
1361                                 qglReadBuffer(GL_COLOR_ATTACHMENT0);CHECKGLERROR
1362                         }
1363                         else if (qglDrawBuffer)
1364                         {
1365                                 qglDrawBuffer(GL_NONE);CHECKGLERROR
1366                                 qglReadBuffer(GL_NONE);CHECKGLERROR
1367                         }
1368 #endif
1369                         status = qglCheckFramebufferStatus(GL_FRAMEBUFFER);CHECKGLERROR
1370                         if (status != GL_FRAMEBUFFER_COMPLETE)
1371                         {
1372                                 Con_Printf("R_Mesh_CreateFramebufferObject: glCheckFramebufferStatus returned %i\n", status);
1373                                 gl_state.framebufferobject = 0; // GL unbinds it for us
1374                                 qglDeleteFramebuffers(1, (GLuint*)&temp);
1375                                 temp = 0;
1376                         }
1377                         return temp;
1378                 }
1379                 else if (vid.support.ext_framebuffer_object)
1380                 {
1381                         int temp;
1382                         GLuint status;
1383                         qglGenFramebuffers(1, (GLuint*)&temp);CHECKGLERROR
1384                         R_Mesh_SetRenderTargets(temp, NULL, NULL, NULL, NULL, NULL);
1385                         // GL_EXT_framebuffer_object (GL2-class hardware) - no depth stencil attachment, let it break stencil
1386                         if (depthtexture  && depthtexture->texnum ) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , depthtexture->gltexturetypeenum , depthtexture->texnum , 0);CHECKGLERROR
1387                         if (depthtexture  && depthtexture->renderbuffernum ) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT  , GL_RENDERBUFFER, depthtexture->renderbuffernum );CHECKGLERROR
1388                         if (colortexture  && colortexture->texnum ) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 , colortexture->gltexturetypeenum , colortexture->texnum , 0);CHECKGLERROR
1389                         if (colortexture2 && colortexture2->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1 , colortexture2->gltexturetypeenum, colortexture2->texnum, 0);CHECKGLERROR
1390                         if (colortexture3 && colortexture3->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2 , colortexture3->gltexturetypeenum, colortexture3->texnum, 0);CHECKGLERROR
1391                         if (colortexture4 && colortexture4->texnum) qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3 , colortexture4->gltexturetypeenum, colortexture4->texnum, 0);CHECKGLERROR
1392                         if (colortexture  && colortexture->renderbuffernum ) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 , GL_RENDERBUFFER, colortexture->renderbuffernum );CHECKGLERROR
1393                         if (colortexture2 && colortexture2->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1 , GL_RENDERBUFFER, colortexture2->renderbuffernum);CHECKGLERROR
1394                         if (colortexture3 && colortexture3->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2 , GL_RENDERBUFFER, colortexture3->renderbuffernum);CHECKGLERROR
1395                         if (colortexture4 && colortexture4->renderbuffernum) qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3 , GL_RENDERBUFFER, colortexture4->renderbuffernum);CHECKGLERROR
1396
1397 #ifndef USE_GLES2
1398                         if (colortexture4 && qglDrawBuffersARB)
1399                         {
1400                                 qglDrawBuffersARB(4, drawbuffers);CHECKGLERROR
1401                                 qglReadBuffer(GL_NONE);CHECKGLERROR
1402                         }
1403                         else if (colortexture3 && qglDrawBuffersARB)
1404                         {
1405                                 qglDrawBuffersARB(3, drawbuffers);CHECKGLERROR
1406                                 qglReadBuffer(GL_NONE);CHECKGLERROR
1407                         }
1408                         else if (colortexture2 && qglDrawBuffersARB)
1409                         {
1410                                 qglDrawBuffersARB(2, drawbuffers);CHECKGLERROR
1411                                 qglReadBuffer(GL_NONE);CHECKGLERROR
1412                         }
1413                         else if (colortexture && qglDrawBuffer)
1414                         {
1415                                 qglDrawBuffer(GL_COLOR_ATTACHMENT0);CHECKGLERROR
1416                                 qglReadBuffer(GL_COLOR_ATTACHMENT0);CHECKGLERROR
1417                         }
1418                         else if (qglDrawBuffer)
1419                         {
1420                                 qglDrawBuffer(GL_NONE);CHECKGLERROR
1421                                 qglReadBuffer(GL_NONE);CHECKGLERROR
1422                         }
1423 #endif
1424                         status = qglCheckFramebufferStatus(GL_FRAMEBUFFER);CHECKGLERROR
1425                         if (status != GL_FRAMEBUFFER_COMPLETE)
1426                         {
1427                                 Con_Printf("R_Mesh_CreateFramebufferObject: glCheckFramebufferStatus returned %i\n", status);
1428                                 gl_state.framebufferobject = 0; // GL unbinds it for us
1429                                 qglDeleteFramebuffers(1, (GLuint*)&temp);
1430                                 temp = 0;
1431                         }
1432                         return temp;
1433                 }
1434                 return 0;
1435         case RENDERPATH_D3D9:
1436         case RENDERPATH_D3D10:
1437         case RENDERPATH_D3D11:
1438                 return 1;
1439         case RENDERPATH_SOFT:
1440                 return 1;
1441         }
1442         return 0;
1443 }
1444
1445 void R_Mesh_DestroyFramebufferObject(int fbo)
1446 {
1447         switch(vid.renderpath)
1448         {
1449         case RENDERPATH_GL11:
1450         case RENDERPATH_GL13:
1451         case RENDERPATH_GL20:
1452         case RENDERPATH_GLES1:
1453         case RENDERPATH_GLES2:
1454                 if (fbo)
1455                 {
1456                         // GL clears the binding if we delete something bound
1457                         if (gl_state.framebufferobject == fbo)
1458                                 gl_state.framebufferobject = 0;
1459                         qglDeleteFramebuffers(1, (GLuint*)&fbo);
1460                 }
1461                 break;
1462         case RENDERPATH_D3D9:
1463         case RENDERPATH_D3D10:
1464         case RENDERPATH_D3D11:
1465                 break;
1466         case RENDERPATH_SOFT:
1467                 break;
1468         }
1469 }
1470
1471 #ifdef SUPPORTD3D
1472 void R_Mesh_SetRenderTargetsD3D9(IDirect3DSurface9 *depthsurface, IDirect3DSurface9 *colorsurface0, IDirect3DSurface9 *colorsurface1, IDirect3DSurface9 *colorsurface2, IDirect3DSurface9 *colorsurface3)
1473 {
1474         gl_state.framebufferobject = depthsurface != gl_state.d3drt_backbufferdepthsurface || colorsurface0 != gl_state.d3drt_backbuffercolorsurface;
1475         if (gl_state.d3drt_depthsurface != depthsurface)
1476         {
1477                 gl_state.d3drt_depthsurface = depthsurface;
1478                 IDirect3DDevice9_SetDepthStencilSurface(vid_d3d9dev, gl_state.d3drt_depthsurface);
1479         }
1480         if (gl_state.d3drt_colorsurfaces[0] != colorsurface0)
1481         {
1482                 gl_state.d3drt_colorsurfaces[0] = colorsurface0;
1483                 IDirect3DDevice9_SetRenderTarget(vid_d3d9dev, 0, gl_state.d3drt_colorsurfaces[0]);
1484         }
1485         if (gl_state.d3drt_colorsurfaces[1] != colorsurface1)
1486         {
1487                 gl_state.d3drt_colorsurfaces[1] = colorsurface1;
1488                 IDirect3DDevice9_SetRenderTarget(vid_d3d9dev, 1, gl_state.d3drt_colorsurfaces[1]);
1489         }
1490         if (gl_state.d3drt_colorsurfaces[2] != colorsurface2)
1491         {
1492                 gl_state.d3drt_colorsurfaces[2] = colorsurface2;
1493                 IDirect3DDevice9_SetRenderTarget(vid_d3d9dev, 2, gl_state.d3drt_colorsurfaces[2]);
1494         }
1495         if (gl_state.d3drt_colorsurfaces[3] != colorsurface3)
1496         {
1497                 gl_state.d3drt_colorsurfaces[3] = colorsurface3;
1498                 IDirect3DDevice9_SetRenderTarget(vid_d3d9dev, 3, gl_state.d3drt_colorsurfaces[3]);
1499         }
1500 }
1501 #endif
1502
1503 void R_Mesh_SetRenderTargets(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture, rtexture_t *colortexture2, rtexture_t *colortexture3, rtexture_t *colortexture4)
1504 {
1505         unsigned int i;
1506         unsigned int j;
1507         rtexture_t *textures[5];
1508         Vector4Set(textures, colortexture, colortexture2, colortexture3, colortexture4);
1509         textures[4] = depthtexture;
1510         // unbind any matching textures immediately, otherwise D3D will complain about a bound texture being used as a render target
1511         for (j = 0;j < 5;j++)
1512                 if (textures[j])
1513                         for (i = 0;i < vid.teximageunits;i++)
1514                                 if (gl_state.units[i].texture == textures[j])
1515                                         R_Mesh_TexBind(i, NULL);
1516         // set up framebuffer object or render targets for the active rendering API
1517         switch(vid.renderpath)
1518         {
1519         case RENDERPATH_GL11:
1520         case RENDERPATH_GL13:
1521         case RENDERPATH_GL20:
1522         case RENDERPATH_GLES1:
1523         case RENDERPATH_GLES2:
1524                 if (gl_state.framebufferobject != fbo)
1525                 {
1526                         gl_state.framebufferobject = fbo;
1527                         qglBindFramebuffer(GL_FRAMEBUFFER, gl_state.framebufferobject ? gl_state.framebufferobject : gl_state.defaultframebufferobject);
1528                 }
1529                 break;
1530         case RENDERPATH_D3D9:
1531 #ifdef SUPPORTD3D
1532                 // set up the new render targets, a NULL depthtexture intentionally binds nothing
1533                 // TODO: optimize: keep surface pointer around in rtexture_t until texture is freed or lost
1534                 if (fbo)
1535                 {
1536                         IDirect3DSurface9 *surfaces[5];
1537                         for (i = 0;i < 5;i++)
1538                         {
1539                                 surfaces[i] = NULL;
1540                                 if (textures[i])
1541                                 {
1542                                         if (textures[i]->d3dsurface)
1543                                                 surfaces[i] = (IDirect3DSurface9 *)textures[i]->d3dsurface;
1544                                         else
1545                                                 IDirect3DTexture9_GetSurfaceLevel((IDirect3DTexture9 *)textures[i]->d3dtexture, 0, &surfaces[i]);
1546                                 }
1547                         }
1548                         // set the render targets for real
1549                         R_Mesh_SetRenderTargetsD3D9(surfaces[4], surfaces[0], surfaces[1], surfaces[2], surfaces[3]);
1550                         // release the texture surface levels (they won't be lost while bound...)
1551                         for (i = 0;i < 5;i++)
1552                                 if (textures[i] && !textures[i]->d3dsurface)
1553                                         IDirect3DSurface9_Release(surfaces[i]);
1554                 }
1555                 else
1556                         R_Mesh_SetRenderTargetsD3D9(gl_state.d3drt_backbufferdepthsurface, gl_state.d3drt_backbuffercolorsurface, NULL, NULL, NULL);
1557 #endif
1558                 break;
1559         case RENDERPATH_D3D10:
1560                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1561                 break;
1562         case RENDERPATH_D3D11:
1563                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1564                 break;
1565         case RENDERPATH_SOFT:
1566                 if (fbo)
1567                 {
1568                         int width, height;
1569                         unsigned int *pointers[5];
1570                         memset(pointers, 0, sizeof(pointers));
1571                         for (i = 0;i < 5;i++)
1572                                 pointers[i] = textures[i] ? (unsigned int *)DPSOFTRAST_Texture_GetPixelPointer(textures[i]->texnum, 0) : NULL;
1573                         width = DPSOFTRAST_Texture_GetWidth(textures[0] ? textures[0]->texnum : textures[4]->texnum, 0);
1574                         height = DPSOFTRAST_Texture_GetHeight(textures[0] ? textures[0]->texnum : textures[4]->texnum, 0);
1575                         DPSOFTRAST_SetRenderTargets(width, height, pointers[4], pointers[0], pointers[1], pointers[2], pointers[3]);
1576                 }
1577                 else
1578                         DPSOFTRAST_SetRenderTargets(vid.width, vid.height, vid.softdepthpixels, vid.softpixels, NULL, NULL, NULL);
1579                 break;
1580         }
1581 }
1582
1583 #ifdef SUPPORTD3D
1584 static int d3dcmpforglfunc(int f)
1585 {
1586         switch(f)
1587         {
1588         case GL_NEVER: return D3DCMP_NEVER;
1589         case GL_LESS: return D3DCMP_LESS;
1590         case GL_EQUAL: return D3DCMP_EQUAL;
1591         case GL_LEQUAL: return D3DCMP_LESSEQUAL;
1592         case GL_GREATER: return D3DCMP_GREATER;
1593         case GL_NOTEQUAL: return D3DCMP_NOTEQUAL;
1594         case GL_GEQUAL: return D3DCMP_GREATEREQUAL;
1595         case GL_ALWAYS: return D3DCMP_ALWAYS;
1596         default: Con_DPrintf("Unknown GL_DepthFunc\n");return D3DCMP_ALWAYS;
1597         }
1598 }
1599
1600 static int d3dstencilopforglfunc(int f)
1601 {
1602         switch(f)
1603         {
1604         case GL_KEEP: return D3DSTENCILOP_KEEP;
1605         case GL_INCR: return D3DSTENCILOP_INCR; // note: GL_INCR is clamped, D3DSTENCILOP_INCR wraps
1606         case GL_DECR: return D3DSTENCILOP_DECR; // note: GL_DECR is clamped, D3DSTENCILOP_DECR wraps
1607         default: Con_DPrintf("Unknown GL_StencilFunc\n");return D3DSTENCILOP_KEEP;
1608         }
1609 }
1610 #endif
1611
1612 static void GL_Backend_ResetState(void)
1613 {
1614         unsigned int i;
1615         gl_state.active = true;
1616         gl_state.depthtest = true;
1617         gl_state.alphatest = false;
1618         gl_state.alphafunc = GL_GEQUAL;
1619         gl_state.alphafuncvalue = 0.5f;
1620         gl_state.alphatocoverage = false;
1621         gl_state.blendfunc1 = GL_ONE;
1622         gl_state.blendfunc2 = GL_ZERO;
1623         gl_state.blend = false;
1624         gl_state.depthmask = GL_TRUE;
1625         gl_state.colormask = 15;
1626         gl_state.color4f[0] = gl_state.color4f[1] = gl_state.color4f[2] = gl_state.color4f[3] = 1;
1627         gl_state.lockrange_first = 0;
1628         gl_state.lockrange_count = 0;
1629         gl_state.cullface = GL_FRONT;
1630         gl_state.cullfaceenable = false;
1631         gl_state.polygonoffset[0] = 0;
1632         gl_state.polygonoffset[1] = 0;
1633         gl_state.framebufferobject = 0;
1634         gl_state.depthfunc = GL_LEQUAL;
1635
1636         switch(vid.renderpath)
1637         {
1638         case RENDERPATH_D3D9:
1639 #ifdef SUPPORTD3D
1640                 {
1641                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_COLORWRITEENABLE, gl_state.colormask);
1642                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CULLMODE, D3DCULL_NONE);
1643                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZFUNC, d3dcmpforglfunc(gl_state.depthfunc));
1644                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZENABLE, gl_state.depthtest);
1645                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZWRITEENABLE, gl_state.depthmask);
1646                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_SLOPESCALEDEPTHBIAS, gl_state.polygonoffset[0]);
1647                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_DEPTHBIAS, gl_state.polygonoffset[1] * (1.0f / 16777216.0f));
1648                 }
1649 #endif
1650                 break;
1651         case RENDERPATH_D3D10:
1652                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1653                 break;
1654         case RENDERPATH_D3D11:
1655                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1656                 break;
1657         case RENDERPATH_GL11:
1658         case RENDERPATH_GL13:
1659         case RENDERPATH_GLES1:
1660 #ifndef USE_GLES2
1661                 CHECKGLERROR
1662
1663                 qglColorMask(1, 1, 1, 1);CHECKGLERROR
1664                 qglAlphaFunc(gl_state.alphafunc, gl_state.alphafuncvalue);CHECKGLERROR
1665                 qglDisable(GL_ALPHA_TEST);CHECKGLERROR
1666                 if (qglBlendFuncSeparate)
1667                 {
1668                         qglBlendFuncSeparate(gl_state.blendfunc1, gl_state.blendfunc2, GL_ZERO, GL_ONE);CHECKGLERROR // ELUAN: Adreno 225 (and others) compositing workaround
1669                 }
1670                 else
1671                 {
1672                         qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
1673                 }
1674                 qglDisable(GL_BLEND);CHECKGLERROR
1675                 qglCullFace(gl_state.cullface);CHECKGLERROR
1676                 qglDisable(GL_CULL_FACE);CHECKGLERROR
1677                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
1678                 qglEnable(GL_DEPTH_TEST);CHECKGLERROR
1679                 qglDepthMask(gl_state.depthmask);CHECKGLERROR
1680                 qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
1681
1682                 if (vid.support.arb_vertex_buffer_object)
1683                 {
1684                         qglBindBufferARB(GL_ARRAY_BUFFER, 0);
1685                         qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, 0);
1686                 }
1687
1688                 if (vid.support.ext_framebuffer_object)
1689                 {
1690                         //qglBindRenderbuffer(GL_RENDERBUFFER, 0);
1691                         qglBindFramebuffer(GL_FRAMEBUFFER, 0);
1692                 }
1693
1694                 qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), NULL);CHECKGLERROR
1695                 qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
1696
1697                 qglColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL);CHECKGLERROR
1698                 qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
1699                 qglColor4f(1, 1, 1, 1);CHECKGLERROR
1700
1701                 if (vid.support.ext_framebuffer_object)
1702                         qglBindFramebuffer(GL_FRAMEBUFFER, gl_state.framebufferobject);
1703
1704                 gl_state.unit = MAX_TEXTUREUNITS;
1705                 gl_state.clientunit = MAX_TEXTUREUNITS;
1706                 for (i = 0;i < vid.texunits;i++)
1707                 {
1708                         GL_ActiveTexture(i);
1709                         GL_ClientActiveTexture(i);
1710                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1711                         qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
1712                         if (vid.support.ext_texture_3d)
1713                         {
1714                                 qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1715                                 qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
1716                         }
1717                         if (vid.support.arb_texture_cube_map)
1718                         {
1719                                 qglDisable(GL_TEXTURE_CUBE_MAP);CHECKGLERROR
1720                                 qglBindTexture(GL_TEXTURE_CUBE_MAP, 0);CHECKGLERROR
1721                         }
1722                         GL_BindVBO(0);
1723                         qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), NULL);CHECKGLERROR
1724                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1725                         qglMatrixMode(GL_TEXTURE);CHECKGLERROR
1726                         qglLoadIdentity();CHECKGLERROR
1727                         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
1728                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
1729                 }
1730                 CHECKGLERROR
1731 #endif
1732                 break;
1733         case RENDERPATH_SOFT:
1734                 DPSOFTRAST_ColorMask(1,1,1,1);
1735                 DPSOFTRAST_BlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);
1736                 DPSOFTRAST_CullFace(gl_state.cullface);
1737                 DPSOFTRAST_DepthFunc(gl_state.depthfunc);
1738                 DPSOFTRAST_DepthMask(gl_state.depthmask);
1739                 DPSOFTRAST_PolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
1740                 DPSOFTRAST_SetRenderTargets(vid.width, vid.height, vid.softdepthpixels, vid.softpixels, NULL, NULL, NULL);
1741                 DPSOFTRAST_Viewport(0, 0, vid.width, vid.height);
1742                 break;
1743         case RENDERPATH_GL20:
1744         case RENDERPATH_GLES2:
1745                 CHECKGLERROR
1746                 qglColorMask(1, 1, 1, 1);CHECKGLERROR
1747                 qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
1748                 qglDisable(GL_BLEND);CHECKGLERROR
1749                 qglCullFace(gl_state.cullface);CHECKGLERROR
1750                 qglDisable(GL_CULL_FACE);CHECKGLERROR
1751                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
1752                 qglEnable(GL_DEPTH_TEST);CHECKGLERROR
1753                 qglDepthMask(gl_state.depthmask);CHECKGLERROR
1754                 qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
1755                 if (vid.support.arb_vertex_buffer_object)
1756                 {
1757                         qglBindBufferARB(GL_ARRAY_BUFFER, 0);
1758                         qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, 0);
1759                 }
1760                 if (vid.support.ext_framebuffer_object)
1761                         qglBindFramebuffer(GL_FRAMEBUFFER, gl_state.defaultframebufferobject);
1762                 qglEnableVertexAttribArray(GLSLATTRIB_POSITION);
1763                 qglVertexAttribPointer(GLSLATTRIB_POSITION, 3, GL_FLOAT, false, sizeof(float[3]), NULL);CHECKGLERROR
1764                 qglDisableVertexAttribArray(GLSLATTRIB_COLOR);
1765                 qglVertexAttribPointer(GLSLATTRIB_COLOR, 4, GL_FLOAT, false, sizeof(float[4]), NULL);CHECKGLERROR
1766                 qglVertexAttrib4f(GLSLATTRIB_COLOR, 1, 1, 1, 1);
1767                 gl_state.unit = MAX_TEXTUREUNITS;
1768                 gl_state.clientunit = MAX_TEXTUREUNITS;
1769                 for (i = 0;i < vid.teximageunits;i++)
1770                 {
1771                         GL_ActiveTexture(i);
1772                         qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
1773                         if (vid.support.ext_texture_3d)
1774                         {
1775                                 qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
1776                         }
1777                         if (vid.support.arb_texture_cube_map)
1778                         {
1779                                 qglBindTexture(GL_TEXTURE_CUBE_MAP, 0);CHECKGLERROR
1780                         }
1781                 }
1782                 for (i = 0;i < vid.texarrayunits;i++)
1783                 {
1784                         GL_BindVBO(0);
1785                         qglVertexAttribPointer(i+GLSLATTRIB_TEXCOORD0, 2, GL_FLOAT, false, sizeof(float[2]), NULL);CHECKGLERROR
1786                         qglDisableVertexAttribArray(i+GLSLATTRIB_TEXCOORD0);CHECKGLERROR
1787                 }
1788                 CHECKGLERROR
1789                 break;
1790         }
1791 }
1792
1793 void GL_ActiveTexture(unsigned int num)
1794 {
1795         if (gl_state.unit != num)
1796         {
1797                 gl_state.unit = num;
1798                 switch(vid.renderpath)
1799                 {
1800                 case RENDERPATH_GL11:
1801                 case RENDERPATH_GL13:
1802                 case RENDERPATH_GL20:
1803                 case RENDERPATH_GLES1:
1804                 case RENDERPATH_GLES2:
1805                         if (qglActiveTexture)
1806                         {
1807                                 CHECKGLERROR
1808                                 qglActiveTexture(GL_TEXTURE0 + gl_state.unit);
1809                                 CHECKGLERROR
1810                         }
1811                         break;
1812                 case RENDERPATH_D3D9:
1813                 case RENDERPATH_D3D10:
1814                 case RENDERPATH_D3D11:
1815                         break;
1816                 case RENDERPATH_SOFT:
1817                         break;
1818                 }
1819         }
1820 }
1821
1822 void GL_ClientActiveTexture(unsigned int num)
1823 {
1824         if (gl_state.clientunit != num)
1825         {
1826                 gl_state.clientunit = num;
1827                 switch(vid.renderpath)
1828                 {
1829                 case RENDERPATH_GL11:
1830                 case RENDERPATH_GL13:
1831                 case RENDERPATH_GLES1:
1832 #ifndef USE_GLES2
1833                         if (qglActiveTexture)
1834                         {
1835                                 CHECKGLERROR
1836                                 qglClientActiveTexture(GL_TEXTURE0 + gl_state.clientunit);
1837                                 CHECKGLERROR
1838                         }
1839 #endif
1840                         break;
1841                 case RENDERPATH_D3D9:
1842                 case RENDERPATH_D3D10:
1843                 case RENDERPATH_D3D11:
1844                         break;
1845                 case RENDERPATH_SOFT:
1846                         break;
1847                 case RENDERPATH_GL20:
1848                 case RENDERPATH_GLES2:
1849                         break;
1850                 }
1851         }
1852 }
1853
1854 void GL_BlendFunc(int blendfunc1, int blendfunc2)
1855 {
1856         if (gl_state.blendfunc1 != blendfunc1 || gl_state.blendfunc2 != blendfunc2)
1857         {
1858                 qboolean blendenable;
1859                 gl_state.blendfunc1 = blendfunc1;
1860                 gl_state.blendfunc2 = blendfunc2;
1861                 blendenable = (gl_state.blendfunc1 != GL_ONE || gl_state.blendfunc2 != GL_ZERO);
1862                 switch(vid.renderpath)
1863                 {
1864                 case RENDERPATH_GL11:
1865                 case RENDERPATH_GL13:
1866                 case RENDERPATH_GL20:
1867                 case RENDERPATH_GLES1:
1868                 case RENDERPATH_GLES2:
1869                         CHECKGLERROR
1870                         if (qglBlendFuncSeparate)
1871                         {
1872                                 qglBlendFuncSeparate(gl_state.blendfunc1, gl_state.blendfunc2, GL_ZERO, GL_ONE);CHECKGLERROR // ELUAN: Adreno 225 (and others) compositing workaround
1873                         }
1874                         else
1875                         {
1876                                 qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
1877                         }
1878                         if (gl_state.blend != blendenable)
1879                         {
1880                                 gl_state.blend = blendenable;
1881                                 if (!gl_state.blend)
1882                                 {
1883                                         qglDisable(GL_BLEND);CHECKGLERROR
1884                                 }
1885                                 else
1886                                 {
1887                                         qglEnable(GL_BLEND);CHECKGLERROR
1888                                 }
1889                         }
1890                         break;
1891                 case RENDERPATH_D3D9:
1892 #ifdef SUPPORTD3D
1893                         {
1894                                 int i;
1895                                 int glblendfunc[2];
1896                                 D3DBLEND d3dblendfunc[2];
1897                                 glblendfunc[0] = gl_state.blendfunc1;
1898                                 glblendfunc[1] = gl_state.blendfunc2;
1899                                 for (i = 0;i < 2;i++)
1900                                 {
1901                                         switch(glblendfunc[i])
1902                                         {
1903                                         case GL_ZERO: d3dblendfunc[i] = D3DBLEND_ZERO;break;
1904                                         case GL_ONE: d3dblendfunc[i] = D3DBLEND_ONE;break;
1905                                         case GL_SRC_COLOR: d3dblendfunc[i] = D3DBLEND_SRCCOLOR;break;
1906                                         case GL_ONE_MINUS_SRC_COLOR: d3dblendfunc[i] = D3DBLEND_INVSRCCOLOR;break;
1907                                         case GL_SRC_ALPHA: d3dblendfunc[i] = D3DBLEND_SRCALPHA;break;
1908                                         case GL_ONE_MINUS_SRC_ALPHA: d3dblendfunc[i] = D3DBLEND_INVSRCALPHA;break;
1909                                         case GL_DST_ALPHA: d3dblendfunc[i] = D3DBLEND_DESTALPHA;break;
1910                                         case GL_ONE_MINUS_DST_ALPHA: d3dblendfunc[i] = D3DBLEND_INVDESTALPHA;break;
1911                                         case GL_DST_COLOR: d3dblendfunc[i] = D3DBLEND_DESTCOLOR;break;
1912                                         case GL_ONE_MINUS_DST_COLOR: d3dblendfunc[i] = D3DBLEND_INVDESTCOLOR;break;
1913                                         }
1914                                 }
1915                                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_SRCBLEND, d3dblendfunc[0]);
1916                                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_DESTBLEND, d3dblendfunc[1]);
1917                                 if (gl_state.blend != blendenable)
1918                                 {
1919                                         gl_state.blend = blendenable;
1920                                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ALPHABLENDENABLE, gl_state.blend);
1921                                 }
1922                         }
1923 #endif
1924                         break;
1925                 case RENDERPATH_D3D10:
1926                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1927                         break;
1928                 case RENDERPATH_D3D11:
1929                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1930                         break;
1931                 case RENDERPATH_SOFT:
1932                         DPSOFTRAST_BlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);
1933                         break;
1934                 }
1935         }
1936 }
1937
1938 void GL_DepthMask(int state)
1939 {
1940         if (gl_state.depthmask != state)
1941         {
1942                 gl_state.depthmask = state;
1943                 switch(vid.renderpath)
1944                 {
1945                 case RENDERPATH_GL11:
1946                 case RENDERPATH_GL13:
1947                 case RENDERPATH_GL20:
1948                 case RENDERPATH_GLES1:
1949                 case RENDERPATH_GLES2:
1950                         CHECKGLERROR
1951                         qglDepthMask(gl_state.depthmask);CHECKGLERROR
1952                         break;
1953                 case RENDERPATH_D3D9:
1954 #ifdef SUPPORTD3D
1955                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZWRITEENABLE, gl_state.depthmask);
1956 #endif
1957                         break;
1958                 case RENDERPATH_D3D10:
1959                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1960                         break;
1961                 case RENDERPATH_D3D11:
1962                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1963                         break;
1964                 case RENDERPATH_SOFT:
1965                         DPSOFTRAST_DepthMask(gl_state.depthmask);
1966                         break;
1967                 }
1968         }
1969 }
1970
1971 void GL_DepthTest(int state)
1972 {
1973         if (gl_state.depthtest != state)
1974         {
1975                 gl_state.depthtest = state;
1976                 switch(vid.renderpath)
1977                 {
1978                 case RENDERPATH_GL11:
1979                 case RENDERPATH_GL13:
1980                 case RENDERPATH_GL20:
1981                 case RENDERPATH_GLES1:
1982                 case RENDERPATH_GLES2:
1983                         CHECKGLERROR
1984                         if (gl_state.depthtest)
1985                         {
1986                                 qglEnable(GL_DEPTH_TEST);CHECKGLERROR
1987                         }
1988                         else
1989                         {
1990                                 qglDisable(GL_DEPTH_TEST);CHECKGLERROR
1991                         }
1992                         break;
1993                 case RENDERPATH_D3D9:
1994 #ifdef SUPPORTD3D
1995                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZENABLE, gl_state.depthtest);
1996 #endif
1997                         break;
1998                 case RENDERPATH_D3D10:
1999                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2000                         break;
2001                 case RENDERPATH_D3D11:
2002                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2003                         break;
2004                 case RENDERPATH_SOFT:
2005                         DPSOFTRAST_DepthTest(gl_state.depthtest);
2006                         break;
2007                 }
2008         }
2009 }
2010
2011 void GL_DepthFunc(int state)
2012 {
2013         if (gl_state.depthfunc != state)
2014         {
2015                 gl_state.depthfunc = state;
2016                 switch(vid.renderpath)
2017                 {
2018                 case RENDERPATH_GL11:
2019                 case RENDERPATH_GL13:
2020                 case RENDERPATH_GL20:
2021                 case RENDERPATH_GLES1:
2022                 case RENDERPATH_GLES2:
2023                         CHECKGLERROR
2024                         qglDepthFunc(gl_state.depthfunc);CHECKGLERROR
2025                         break;
2026                 case RENDERPATH_D3D9:
2027 #ifdef SUPPORTD3D
2028                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZFUNC, d3dcmpforglfunc(gl_state.depthfunc));
2029 #endif
2030                         break;
2031                 case RENDERPATH_D3D10:
2032                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2033                         break;
2034                 case RENDERPATH_D3D11:
2035                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2036                         break;
2037                 case RENDERPATH_SOFT:
2038                         DPSOFTRAST_DepthFunc(gl_state.depthfunc);
2039                         break;
2040                 }
2041         }
2042 }
2043
2044 void GL_DepthRange(float nearfrac, float farfrac)
2045 {
2046         if (gl_state.depthrange[0] != nearfrac || gl_state.depthrange[1] != farfrac)
2047         {
2048                 gl_state.depthrange[0] = nearfrac;
2049                 gl_state.depthrange[1] = farfrac;
2050                 switch(vid.renderpath)
2051                 {
2052                 case RENDERPATH_GL11:
2053                 case RENDERPATH_GL13:
2054                 case RENDERPATH_GL20:
2055                 case RENDERPATH_GLES1:
2056                 case RENDERPATH_GLES2:
2057 #ifdef USE_GLES2
2058                         qglDepthRangef(gl_state.depthrange[0], gl_state.depthrange[1]);
2059 #else
2060                         qglDepthRange(gl_state.depthrange[0], gl_state.depthrange[1]);
2061 #endif
2062                         break;
2063                 case RENDERPATH_D3D9:
2064 #ifdef SUPPORTD3D
2065                         {
2066                                 D3DVIEWPORT9 d3dviewport;
2067                                 d3dviewport.X = gl_viewport.x;
2068                                 d3dviewport.Y = gl_viewport.y;
2069                                 d3dviewport.Width = gl_viewport.width;
2070                                 d3dviewport.Height = gl_viewport.height;
2071                                 d3dviewport.MinZ = gl_state.depthrange[0];
2072                                 d3dviewport.MaxZ = gl_state.depthrange[1];
2073                                 IDirect3DDevice9_SetViewport(vid_d3d9dev, &d3dviewport);
2074                         }
2075 #endif
2076                         break;
2077                 case RENDERPATH_D3D10:
2078                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2079                         break;
2080                 case RENDERPATH_D3D11:
2081                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2082                         break;
2083                 case RENDERPATH_SOFT:
2084                         DPSOFTRAST_DepthRange(gl_state.depthrange[0], gl_state.depthrange[1]);
2085                         break;
2086                 }
2087         }
2088 }
2089
2090 void R_SetStencilSeparate(qboolean enable, int writemask, int frontfail, int frontzfail, int frontzpass, int backfail, int backzfail, int backzpass, int frontcompare, int backcompare, int comparereference, int comparemask)
2091 {
2092         switch (vid.renderpath)
2093         {
2094         case RENDERPATH_GL11:
2095         case RENDERPATH_GL13:
2096         case RENDERPATH_GL20:
2097         case RENDERPATH_GLES1:
2098         case RENDERPATH_GLES2:
2099                 CHECKGLERROR
2100                 if (enable)
2101                 {
2102                         qglEnable(GL_STENCIL_TEST);CHECKGLERROR
2103                 }
2104                 else
2105                 {
2106                         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
2107                 }
2108                 if (vid.support.ati_separate_stencil)
2109                 {
2110                         qglStencilMask(writemask);CHECKGLERROR
2111                         qglStencilOpSeparate(GL_FRONT, frontfail, frontzfail, frontzpass);CHECKGLERROR
2112                         qglStencilOpSeparate(GL_BACK, backfail, backzfail, backzpass);CHECKGLERROR
2113                         qglStencilFuncSeparate(GL_FRONT, frontcompare, comparereference, comparereference);CHECKGLERROR
2114                         qglStencilFuncSeparate(GL_BACK, backcompare, comparereference, comparereference);CHECKGLERROR
2115                 }
2116                 else if (vid.support.ext_stencil_two_side)
2117                 {
2118 #if defined(GL_STENCIL_TEST_TWO_SIDE_EXT) && !defined(USE_GLES2)
2119                         qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
2120                         qglActiveStencilFaceEXT(GL_FRONT);CHECKGLERROR
2121                         qglStencilMask(writemask);CHECKGLERROR
2122                         qglStencilOp(frontfail, frontzfail, frontzpass);CHECKGLERROR
2123                         qglStencilFunc(frontcompare, comparereference, comparemask);CHECKGLERROR
2124                         qglActiveStencilFaceEXT(GL_BACK);CHECKGLERROR
2125                         qglStencilMask(writemask);CHECKGLERROR
2126                         qglStencilOp(backfail, backzfail, backzpass);CHECKGLERROR
2127                         qglStencilFunc(backcompare, comparereference, comparemask);CHECKGLERROR
2128 #endif
2129                 }
2130                 break;
2131         case RENDERPATH_D3D9:
2132 #ifdef SUPPORTD3D
2133                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_TWOSIDEDSTENCILMODE, true);
2134                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILENABLE, enable);
2135                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILWRITEMASK, writemask);
2136                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILFAIL, d3dstencilopforglfunc(frontfail));
2137                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILZFAIL, d3dstencilopforglfunc(frontzfail));
2138                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILPASS, d3dstencilopforglfunc(frontzpass));
2139                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILFUNC, d3dcmpforglfunc(frontcompare));
2140                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CCW_STENCILFAIL, d3dstencilopforglfunc(backfail));
2141                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CCW_STENCILZFAIL, d3dstencilopforglfunc(backzfail));
2142                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CCW_STENCILPASS, d3dstencilopforglfunc(backzpass));
2143                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CCW_STENCILFUNC, d3dcmpforglfunc(backcompare));
2144                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILREF, comparereference);
2145                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILMASK, comparemask);
2146 #endif
2147                 break;
2148         case RENDERPATH_D3D10:
2149                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2150                 break;
2151         case RENDERPATH_D3D11:
2152                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2153                 break;
2154         case RENDERPATH_SOFT:
2155                 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2156                 break;
2157         }
2158 }
2159
2160 void R_SetStencil(qboolean enable, int writemask, int fail, int zfail, int zpass, int compare, int comparereference, int comparemask)
2161 {
2162         switch (vid.renderpath)
2163         {
2164         case RENDERPATH_GL11:
2165         case RENDERPATH_GL13:
2166         case RENDERPATH_GL20:
2167         case RENDERPATH_GLES1:
2168         case RENDERPATH_GLES2:
2169                 CHECKGLERROR
2170                 if (enable)
2171                 {
2172                         qglEnable(GL_STENCIL_TEST);CHECKGLERROR
2173                 }
2174                 else
2175                 {
2176                         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
2177                 }
2178                 if (vid.support.ext_stencil_two_side)
2179                 {
2180 #ifdef GL_STENCIL_TEST_TWO_SIDE_EXT
2181                         qglDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
2182 #endif
2183                 }
2184                 qglStencilMask(writemask);CHECKGLERROR
2185                 qglStencilOp(fail, zfail, zpass);CHECKGLERROR
2186                 qglStencilFunc(compare, comparereference, comparemask);CHECKGLERROR
2187                 CHECKGLERROR
2188                 break;
2189         case RENDERPATH_D3D9:
2190 #ifdef SUPPORTD3D
2191                 if (vid.support.ati_separate_stencil)
2192                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_TWOSIDEDSTENCILMODE, true);
2193                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILENABLE, enable);
2194                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILWRITEMASK, writemask);
2195                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILFAIL, d3dstencilopforglfunc(fail));
2196                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILZFAIL, d3dstencilopforglfunc(zfail));
2197                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILPASS, d3dstencilopforglfunc(zpass));
2198                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILFUNC, d3dcmpforglfunc(compare));
2199                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILREF, comparereference);
2200                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILMASK, comparemask);
2201 #endif
2202                 break;
2203         case RENDERPATH_D3D10:
2204                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2205                 break;
2206         case RENDERPATH_D3D11:
2207                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2208                 break;
2209         case RENDERPATH_SOFT:
2210                 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2211                 break;
2212         }
2213 }
2214
2215 void GL_PolygonOffset(float planeoffset, float depthoffset)
2216 {
2217         if (gl_state.polygonoffset[0] != planeoffset || gl_state.polygonoffset[1] != depthoffset)
2218         {
2219                 gl_state.polygonoffset[0] = planeoffset;
2220                 gl_state.polygonoffset[1] = depthoffset;
2221                 switch(vid.renderpath)
2222                 {
2223                 case RENDERPATH_GL11:
2224                 case RENDERPATH_GL13:
2225                 case RENDERPATH_GL20:
2226                 case RENDERPATH_GLES1:
2227                 case RENDERPATH_GLES2:
2228                         qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
2229                         break;
2230                 case RENDERPATH_D3D9:
2231 #ifdef SUPPORTD3D
2232                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_SLOPESCALEDEPTHBIAS, gl_state.polygonoffset[0]);
2233                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_DEPTHBIAS, gl_state.polygonoffset[1] * (1.0f / 16777216.0f));
2234 #endif
2235                         break;
2236                 case RENDERPATH_D3D10:
2237                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2238                         break;
2239                 case RENDERPATH_D3D11:
2240                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2241                         break;
2242                 case RENDERPATH_SOFT:
2243                         DPSOFTRAST_PolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
2244                         break;
2245                 }
2246         }
2247 }
2248
2249 void GL_SetMirrorState(qboolean state)
2250 {
2251         if (v_flipped_state != state)
2252         {
2253                 v_flipped_state = state;
2254                 if (gl_state.cullface == GL_BACK)
2255                         gl_state.cullface = GL_FRONT;
2256                 else if (gl_state.cullface == GL_FRONT)
2257                         gl_state.cullface = GL_BACK;
2258                 else
2259                         return;
2260                 switch(vid.renderpath)
2261                 {
2262                 case RENDERPATH_GL11:
2263                 case RENDERPATH_GL13:
2264                 case RENDERPATH_GL20:
2265                 case RENDERPATH_GLES1:
2266                 case RENDERPATH_GLES2:
2267                         qglCullFace(gl_state.cullface);CHECKGLERROR
2268                         break;
2269                 case RENDERPATH_D3D9:
2270 #ifdef SUPPORTD3D
2271                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CULLMODE, gl_state.cullface == GL_FRONT ? D3DCULL_CCW : D3DCULL_CW);
2272 #endif
2273                         break;
2274                 case RENDERPATH_D3D10:
2275                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2276                         break;
2277                 case RENDERPATH_D3D11:
2278                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2279                         break;
2280                 case RENDERPATH_SOFT:
2281                         DPSOFTRAST_CullFace(gl_state.cullface);
2282                         break;
2283                 }
2284         }
2285 }
2286
2287 void GL_CullFace(int state)
2288 {
2289         if(v_flipped_state)
2290         {
2291                 if(state == GL_FRONT)
2292                         state = GL_BACK;
2293                 else if(state == GL_BACK)
2294                         state = GL_FRONT;
2295         }
2296
2297         switch(vid.renderpath)
2298         {
2299         case RENDERPATH_GL11:
2300         case RENDERPATH_GL13:
2301         case RENDERPATH_GL20:
2302         case RENDERPATH_GLES1:
2303         case RENDERPATH_GLES2:
2304                 CHECKGLERROR
2305
2306                 if (state != GL_NONE)
2307                 {
2308                         if (!gl_state.cullfaceenable)
2309                         {
2310                                 gl_state.cullfaceenable = true;
2311                                 qglEnable(GL_CULL_FACE);CHECKGLERROR
2312                         }
2313                         if (gl_state.cullface != state)
2314                         {
2315                                 gl_state.cullface = state;
2316                                 qglCullFace(gl_state.cullface);CHECKGLERROR
2317                         }
2318                 }
2319                 else
2320                 {
2321                         if (gl_state.cullfaceenable)
2322                         {
2323                                 gl_state.cullfaceenable = false;
2324                                 qglDisable(GL_CULL_FACE);CHECKGLERROR
2325                         }
2326                 }
2327                 break;
2328         case RENDERPATH_D3D9:
2329 #ifdef SUPPORTD3D
2330                 if (gl_state.cullface != state)
2331                 {
2332                         gl_state.cullface = state;
2333                         switch(gl_state.cullface)
2334                         {
2335                         case GL_NONE:
2336                                 gl_state.cullfaceenable = false;
2337                                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CULLMODE, D3DCULL_NONE);
2338                                 break;
2339                         case GL_FRONT:
2340                                 gl_state.cullfaceenable = true;
2341                                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CULLMODE, D3DCULL_CCW);
2342                                 break;
2343                         case GL_BACK:
2344                                 gl_state.cullfaceenable = true;
2345                                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CULLMODE, D3DCULL_CW);
2346                                 break;
2347                         }
2348                 }
2349 #endif
2350                 break;
2351         case RENDERPATH_D3D10:
2352                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2353                 break;
2354         case RENDERPATH_D3D11:
2355                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2356                 break;
2357         case RENDERPATH_SOFT:
2358                 if (gl_state.cullface != state)
2359                 {
2360                         gl_state.cullface = state;
2361                         gl_state.cullfaceenable = state != GL_NONE ? true : false;
2362                         DPSOFTRAST_CullFace(gl_state.cullface);
2363                 }
2364                 break;
2365         }
2366 }
2367
2368 void GL_AlphaTest(int state)
2369 {
2370         if (gl_state.alphatest != state)
2371         {
2372                 gl_state.alphatest = state;
2373                 switch(vid.renderpath)
2374                 {
2375                 case RENDERPATH_GL11:
2376                 case RENDERPATH_GL13:
2377                 case RENDERPATH_GLES1:
2378 #ifdef GL_ALPHA_TEST
2379                         // only fixed function uses alpha test, other paths use pixel kill capability in shaders
2380                         CHECKGLERROR
2381                         if (gl_state.alphatest)
2382                         {
2383                                 qglEnable(GL_ALPHA_TEST);CHECKGLERROR
2384                         }
2385                         else
2386                         {
2387                                 qglDisable(GL_ALPHA_TEST);CHECKGLERROR
2388                         }
2389 #endif
2390                         break;
2391                 case RENDERPATH_D3D9:
2392                 case RENDERPATH_D3D10:
2393                 case RENDERPATH_D3D11:
2394                 case RENDERPATH_SOFT:
2395                 case RENDERPATH_GL20:
2396                 case RENDERPATH_GLES2:
2397                         break;
2398                 }
2399         }
2400 }
2401
2402 void GL_AlphaToCoverage(qboolean state)
2403 {
2404         if (gl_state.alphatocoverage != state)
2405         {
2406                 gl_state.alphatocoverage = state;
2407                 switch(vid.renderpath)
2408                 {
2409                 case RENDERPATH_GL11:
2410                 case RENDERPATH_GL13:
2411                 case RENDERPATH_GLES1:
2412                 case RENDERPATH_GLES2:
2413                 case RENDERPATH_D3D9:
2414                 case RENDERPATH_D3D10:
2415                 case RENDERPATH_D3D11:
2416                 case RENDERPATH_SOFT:
2417                         break;
2418                 case RENDERPATH_GL20:
2419 #ifdef GL_SAMPLE_ALPHA_TO_COVERAGE_ARB
2420                         // alpha to coverage turns the alpha value of the pixel into 0%, 25%, 50%, 75% or 100% by masking the multisample fragments accordingly
2421                         CHECKGLERROR
2422                         if (gl_state.alphatocoverage)
2423                         {
2424                                 qglEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);CHECKGLERROR
2425 //                              qglEnable(GL_MULTISAMPLE_ARB);CHECKGLERROR
2426                         }
2427                         else
2428                         {
2429                                 qglDisable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);CHECKGLERROR
2430 //                              qglDisable(GL_MULTISAMPLE_ARB);CHECKGLERROR
2431                         }
2432 #endif
2433                         break;
2434                 }
2435         }
2436 }
2437
2438 void GL_ColorMask(int r, int g, int b, int a)
2439 {
2440         // NOTE: this matches D3DCOLORWRITEENABLE_RED, GREEN, BLUE, ALPHA
2441         int state = (r ? 1 : 0) | (g ? 2 : 0) | (b ? 4 : 0) | (a ? 8 : 0);
2442         if (gl_state.colormask != state)
2443         {
2444                 gl_state.colormask = state;
2445                 switch(vid.renderpath)
2446                 {
2447                 case RENDERPATH_GL11:
2448                 case RENDERPATH_GL13:
2449                 case RENDERPATH_GL20:
2450                 case RENDERPATH_GLES1:
2451                 case RENDERPATH_GLES2:
2452                         CHECKGLERROR
2453                         qglColorMask((GLboolean)r, (GLboolean)g, (GLboolean)b, (GLboolean)a);CHECKGLERROR
2454                         break;
2455                 case RENDERPATH_D3D9:
2456 #ifdef SUPPORTD3D
2457                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_COLORWRITEENABLE, state);
2458 #endif
2459                         break;
2460                 case RENDERPATH_D3D10:
2461                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2462                         break;
2463                 case RENDERPATH_D3D11:
2464                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2465                         break;
2466                 case RENDERPATH_SOFT:
2467                         DPSOFTRAST_ColorMask(r, g, b, a);
2468                         break;
2469                 }
2470         }
2471 }
2472
2473 void GL_Color(float cr, float cg, float cb, float ca)
2474 {
2475         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)
2476         {
2477                 gl_state.color4f[0] = cr;
2478                 gl_state.color4f[1] = cg;
2479                 gl_state.color4f[2] = cb;
2480                 gl_state.color4f[3] = ca;
2481                 switch(vid.renderpath)
2482                 {
2483                 case RENDERPATH_GL11:
2484                 case RENDERPATH_GL13:
2485                 case RENDERPATH_GLES1:
2486 #ifndef USE_GLES2
2487                         CHECKGLERROR
2488                         qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);
2489                         CHECKGLERROR
2490 #endif
2491                         break;
2492                 case RENDERPATH_D3D9:
2493                 case RENDERPATH_D3D10:
2494                 case RENDERPATH_D3D11:
2495                         // no equivalent in D3D
2496                         break;
2497                 case RENDERPATH_SOFT:
2498                         DPSOFTRAST_Color4f(cr, cg, cb, ca);
2499                         break;
2500                 case RENDERPATH_GL20:
2501                 case RENDERPATH_GLES2:
2502                         qglVertexAttrib4f(GLSLATTRIB_COLOR, cr, cg, cb, ca);
2503                         break;
2504                 }
2505         }
2506 }
2507
2508 void GL_Scissor (int x, int y, int width, int height)
2509 {
2510         switch(vid.renderpath)
2511         {
2512         case RENDERPATH_GL11:
2513         case RENDERPATH_GL13:
2514         case RENDERPATH_GL20:
2515         case RENDERPATH_GLES1:
2516         case RENDERPATH_GLES2:
2517                 CHECKGLERROR
2518                 qglScissor(x, y,width,height);
2519                 CHECKGLERROR
2520                 break;
2521         case RENDERPATH_D3D9:
2522 #ifdef SUPPORTD3D
2523                 {
2524                         RECT d3drect;
2525                         d3drect.left = x;
2526                         d3drect.top = y;
2527                         d3drect.right = x + width;
2528                         d3drect.bottom = y + height;
2529                         IDirect3DDevice9_SetScissorRect(vid_d3d9dev, &d3drect);
2530                 }
2531 #endif
2532                 break;
2533         case RENDERPATH_D3D10:
2534                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2535                 break;
2536         case RENDERPATH_D3D11:
2537                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2538                 break;
2539         case RENDERPATH_SOFT:
2540                 DPSOFTRAST_Scissor(x, y, width, height);
2541                 break;
2542         }
2543 }
2544
2545 void GL_ScissorTest(int state)
2546 {
2547         if (gl_state.scissortest != state)
2548         {
2549                 gl_state.scissortest = state;
2550                 switch(vid.renderpath)
2551                 {
2552                 case RENDERPATH_GL11:
2553                 case RENDERPATH_GL13:
2554                 case RENDERPATH_GL20:
2555                 case RENDERPATH_GLES1:
2556                 case RENDERPATH_GLES2:
2557                         CHECKGLERROR
2558                         if(gl_state.scissortest)
2559                                 qglEnable(GL_SCISSOR_TEST);
2560                         else
2561                                 qglDisable(GL_SCISSOR_TEST);
2562                         CHECKGLERROR
2563                         break;
2564                 case RENDERPATH_D3D9:
2565 #ifdef SUPPORTD3D
2566                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_SCISSORTESTENABLE, gl_state.scissortest);
2567 #endif
2568                         break;
2569                 case RENDERPATH_D3D10:
2570                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2571                         break;
2572                 case RENDERPATH_D3D11:
2573                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2574                         break;
2575                 case RENDERPATH_SOFT:
2576                         DPSOFTRAST_ScissorTest(gl_state.scissortest);
2577                         break;
2578                 }
2579         }
2580 }
2581
2582 void GL_Clear(int mask, const float *colorvalue, float depthvalue, int stencilvalue)
2583 {
2584         // opaque black - if you want transparent black, you'll need to pass in a colorvalue
2585         static const float blackcolor[4] = {0.0f, 0.0f, 0.0f, 1.0f};
2586         // prevent warnings when trying to clear a buffer that does not exist
2587         if (!colorvalue)
2588                 colorvalue = blackcolor;
2589         if (!vid.stencil)
2590         {
2591                 mask &= ~GL_STENCIL_BUFFER_BIT;
2592                 stencilvalue = 0;
2593         }
2594         switch(vid.renderpath)
2595         {
2596         case RENDERPATH_GL11:
2597         case RENDERPATH_GL13:
2598         case RENDERPATH_GL20:
2599         case RENDERPATH_GLES1:
2600         case RENDERPATH_GLES2:
2601                 CHECKGLERROR
2602                 if (mask & GL_COLOR_BUFFER_BIT)
2603                 {
2604                         qglClearColor(colorvalue[0], colorvalue[1], colorvalue[2], colorvalue[3]);CHECKGLERROR
2605                 }
2606                 if (mask & GL_DEPTH_BUFFER_BIT)
2607                 {
2608 #ifdef USE_GLES2
2609                         qglClearDepthf(depthvalue);CHECKGLERROR
2610 #else
2611                         qglClearDepth(depthvalue);CHECKGLERROR
2612 #endif
2613                 }
2614                 if (mask & GL_STENCIL_BUFFER_BIT)
2615                 {
2616                         qglClearStencil(stencilvalue);CHECKGLERROR
2617                 }
2618                 qglClear(mask);CHECKGLERROR
2619                 break;
2620         case RENDERPATH_D3D9:
2621 #ifdef SUPPORTD3D
2622                 IDirect3DDevice9_Clear(vid_d3d9dev, 0, NULL, ((mask & GL_COLOR_BUFFER_BIT) ? D3DCLEAR_TARGET : 0) | ((mask & GL_STENCIL_BUFFER_BIT) ? D3DCLEAR_STENCIL : 0) | ((mask & GL_DEPTH_BUFFER_BIT) ? D3DCLEAR_ZBUFFER : 0), D3DCOLOR_COLORVALUE(colorvalue[0], colorvalue[1], colorvalue[2], colorvalue[3]), depthvalue, stencilvalue);
2623 #endif
2624                 break;
2625         case RENDERPATH_D3D10:
2626                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2627                 break;
2628         case RENDERPATH_D3D11:
2629                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2630                 break;
2631         case RENDERPATH_SOFT:
2632                 if (mask & GL_COLOR_BUFFER_BIT)
2633                         DPSOFTRAST_ClearColor(colorvalue[0], colorvalue[1], colorvalue[2], colorvalue[3]);
2634                 if (mask & GL_DEPTH_BUFFER_BIT)
2635                         DPSOFTRAST_ClearDepth(depthvalue);
2636                 break;
2637         }
2638 }
2639
2640 void GL_ReadPixelsBGRA(int x, int y, int width, int height, unsigned char *outpixels)
2641 {
2642         switch(vid.renderpath)
2643         {
2644         case RENDERPATH_GL11:
2645         case RENDERPATH_GL13:
2646         case RENDERPATH_GL20:
2647         case RENDERPATH_GLES1:
2648         case RENDERPATH_GLES2:
2649                 CHECKGLERROR
2650 #ifndef GL_BGRA
2651                 {
2652                         int i;
2653                         int r;
2654                 //      int g;
2655                         int b;
2656                 //      int a;
2657                         qglReadPixels(x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, outpixels);CHECKGLERROR
2658                         for (i = 0;i < width * height * 4;i += 4)
2659                         {
2660                                 r = outpixels[i+0];
2661                 //              g = outpixels[i+1];
2662                                 b = outpixels[i+2];
2663                 //              a = outpixels[i+3];
2664                                 outpixels[i+0] = b;
2665                 //              outpixels[i+1] = g;
2666                                 outpixels[i+2] = r;
2667                 //              outpixels[i+3] = a;
2668                         }
2669                 }
2670 #else
2671                 qglReadPixels(x, y, width, height, GL_BGRA, GL_UNSIGNED_BYTE, outpixels);CHECKGLERROR
2672 #endif
2673                         break;
2674         case RENDERPATH_D3D9:
2675 #ifdef SUPPORTD3D
2676                 {
2677                         // LordHavoc: we can't directly download the backbuffer because it may be
2678                         // multisampled, and it may not be lockable, so we blit it to a lockable
2679                         // surface of the same dimensions (but without multisample) to resolve the
2680                         // multisample buffer to a normal image, and then lock that...
2681                         IDirect3DSurface9 *stretchsurface = NULL;
2682                         if (!FAILED(IDirect3DDevice9_CreateRenderTarget(vid_d3d9dev, vid.width, vid.height, D3DFMT_A8R8G8B8, D3DMULTISAMPLE_NONE, 0, TRUE, &stretchsurface, NULL)))
2683                         {
2684                                 D3DLOCKED_RECT lockedrect;
2685                                 if (!FAILED(IDirect3DDevice9_StretchRect(vid_d3d9dev, gl_state.d3drt_backbuffercolorsurface, NULL, stretchsurface, NULL, D3DTEXF_POINT)))
2686                                 {
2687                                         if (!FAILED(IDirect3DSurface9_LockRect(stretchsurface, &lockedrect, NULL, D3DLOCK_READONLY)))
2688                                         {
2689                                                 int line;
2690                                                 unsigned char *row = (unsigned char *)lockedrect.pBits + x * 4 + lockedrect.Pitch * (vid.height - 1 - y);
2691                                                 for (line = 0;line < height;line++, row -= lockedrect.Pitch)
2692                                                         memcpy(outpixels + line * width * 4, row, width * 4);
2693                                                 IDirect3DSurface9_UnlockRect(stretchsurface);
2694                                         }
2695                                 }
2696                                 IDirect3DSurface9_Release(stretchsurface);
2697                         }
2698                         // code scraps
2699                         //IDirect3DSurface9 *syssurface = NULL;
2700                         //if (!FAILED(IDirect3DDevice9_CreateRenderTarget(vid_d3d9dev, vid.width, vid.height, D3DFMT_A8R8G8B8, D3DMULTISAMPLE_NONE, 0, FALSE, &stretchsurface, NULL)))
2701                         //if (!FAILED(IDirect3DDevice9_CreateOffscreenPlainSurface(vid_d3d9dev, vid.width, vid.height, D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &syssurface, NULL)))
2702                         //IDirect3DDevice9_GetRenderTargetData(vid_d3d9dev, gl_state.d3drt_backbuffercolorsurface, syssurface);
2703                         //if (!FAILED(IDirect3DDevice9_GetFrontBufferData(vid_d3d9dev, 0, syssurface)))
2704                         //if (!FAILED(IDirect3DSurface9_LockRect(syssurface, &lockedrect, NULL, D3DLOCK_READONLY)))
2705                         //IDirect3DSurface9_UnlockRect(syssurface);
2706                         //IDirect3DSurface9_Release(syssurface);
2707                 }
2708 #endif
2709                 break;
2710         case RENDERPATH_D3D10:
2711                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2712                 break;
2713         case RENDERPATH_D3D11:
2714                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2715                 break;
2716         case RENDERPATH_SOFT:
2717                 DPSOFTRAST_GetPixelsBGRA(x, y, width, height, outpixels);
2718                 break;
2719         }
2720 }
2721
2722 // called at beginning of frame
2723 void R_Mesh_Start(void)
2724 {
2725         BACKENDACTIVECHECK
2726         R_Mesh_SetRenderTargets(0, NULL, NULL, NULL, NULL, NULL);
2727         R_Mesh_SetUseVBO();
2728         if (gl_printcheckerror.integer && !gl_paranoid.integer)
2729         {
2730                 Con_Printf("WARNING: gl_printcheckerror is on but gl_paranoid is off, turning it on...\n");
2731                 Cvar_SetValueQuick(&gl_paranoid, 1);
2732         }
2733 }
2734
2735 static qboolean GL_Backend_CompileShader(int programobject, GLenum shadertypeenum, const char *shadertype, int numstrings, const char **strings)
2736 {
2737         int shaderobject;
2738         int shadercompiled;
2739         char compilelog[MAX_INPUTLINE];
2740         shaderobject = qglCreateShader(shadertypeenum);CHECKGLERROR
2741         if (!shaderobject)
2742                 return false;
2743         qglShaderSource(shaderobject, numstrings, strings, NULL);CHECKGLERROR
2744         qglCompileShader(shaderobject);CHECKGLERROR
2745         qglGetShaderiv(shaderobject, GL_COMPILE_STATUS, &shadercompiled);CHECKGLERROR
2746         qglGetShaderInfoLog(shaderobject, sizeof(compilelog), NULL, compilelog);CHECKGLERROR
2747         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))
2748         {
2749                 int i, j, pretextlines = 0;
2750                 for (i = 0;i < numstrings - 1;i++)
2751                         for (j = 0;strings[i][j];j++)
2752                                 if (strings[i][j] == '\n')
2753                                         pretextlines++;
2754                 Con_Printf("%s shader compile log:\n%s\n(line offset for any above warnings/errors: %i)\n", shadertype, compilelog, pretextlines);
2755         }
2756         if (!shadercompiled)
2757         {
2758                 qglDeleteShader(shaderobject);CHECKGLERROR
2759                 return false;
2760         }
2761         qglAttachShader(programobject, shaderobject);CHECKGLERROR
2762         qglDeleteShader(shaderobject);CHECKGLERROR
2763         return true;
2764 }
2765
2766 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)
2767 {
2768         GLint programlinked;
2769         GLuint programobject = 0;
2770         char linklog[MAX_INPUTLINE];
2771         CHECKGLERROR
2772
2773         programobject = qglCreateProgram();CHECKGLERROR
2774         if (!programobject)
2775                 return 0;
2776
2777         qglBindAttribLocation(programobject, GLSLATTRIB_POSITION , "Attrib_Position" );
2778         qglBindAttribLocation(programobject, GLSLATTRIB_COLOR    , "Attrib_Color"    );
2779         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD0, "Attrib_TexCoord0");
2780         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD1, "Attrib_TexCoord1");
2781         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD2, "Attrib_TexCoord2");
2782         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD3, "Attrib_TexCoord3");
2783         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD4, "Attrib_TexCoord4");
2784         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD5, "Attrib_TexCoord5");
2785         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD6, "Attrib_SkeletalIndex");
2786         qglBindAttribLocation(programobject, GLSLATTRIB_TEXCOORD7, "Attrib_SkeletalWeight");
2787 #ifndef USE_GLES2
2788         if(vid.support.gl20shaders130)
2789                 qglBindFragDataLocation(programobject, 0, "dp_FragColor");
2790 #endif
2791
2792         if (vertexstrings_count && !GL_Backend_CompileShader(programobject, GL_VERTEX_SHADER, "vertex", vertexstrings_count, vertexstrings_list))
2793                 goto cleanup;
2794
2795 #if defined(GL_GEOMETRY_SHADER) && !defined(USE_GLES2)
2796         if (geometrystrings_count && !GL_Backend_CompileShader(programobject, GL_GEOMETRY_SHADER, "geometry", geometrystrings_count, geometrystrings_list))
2797                 goto cleanup;
2798 #endif
2799
2800         if (fragmentstrings_count && !GL_Backend_CompileShader(programobject, GL_FRAGMENT_SHADER, "fragment", fragmentstrings_count, fragmentstrings_list))
2801                 goto cleanup;
2802
2803         qglLinkProgram(programobject);CHECKGLERROR
2804         qglGetProgramiv(programobject, GL_LINK_STATUS, &programlinked);CHECKGLERROR
2805         qglGetProgramInfoLog(programobject, sizeof(linklog), NULL, linklog);CHECKGLERROR
2806
2807         if (linklog[0])
2808         {
2809
2810                 if (strstr(linklog, "error") || strstr(linklog, "ERROR") || strstr(linklog, "Error") || strstr(linklog, "WARNING") || strstr(linklog, "warning") || strstr(linklog, "Warning") || developer_extra.integer)
2811                         Con_DPrintf("program link log:\n%s\n", linklog);
2812
2813                 // software vertex shader is ok but software fragment shader is WAY
2814                 // too slow, fail program if so.
2815                 // NOTE: this string might be ATI specific, but that's ok because the
2816                 // ATI R300 chip (Radeon 9500-9800/X300) is the most likely to use a
2817                 // software fragment shader due to low instruction and dependent
2818                 // texture limits.
2819                 if (strstr(linklog, "fragment shader will run in software"))
2820                         programlinked = false;
2821         }
2822
2823         if (!programlinked)
2824                 goto cleanup;
2825
2826         return programobject;
2827 cleanup:
2828         qglDeleteProgram(programobject);CHECKGLERROR
2829         return 0;
2830 }
2831
2832 void GL_Backend_FreeProgram(unsigned int prog)
2833 {
2834         CHECKGLERROR
2835         qglDeleteProgram(prog);
2836         CHECKGLERROR
2837 }
2838
2839 // renders triangles using vertices from the active arrays
2840 int paranoidblah = 0;
2841 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)
2842 {
2843         unsigned int numelements = numtriangles * 3;
2844         int bufferobject3i;
2845         size_t bufferoffset3i;
2846         int bufferobject3s;
2847         size_t bufferoffset3s;
2848         if (numvertices < 3 || numtriangles < 1)
2849         {
2850                 if (numvertices < 0 || numtriangles < 0 || developer_extra.integer)
2851                         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);
2852                 return;
2853         }
2854         // adjust the pointers for firsttriangle
2855         if (element3i)
2856                 element3i += firsttriangle * 3;
2857         if (element3i_indexbuffer)
2858                 element3i_bufferoffset += firsttriangle * 3 * sizeof(*element3i);
2859         if (element3s)
2860                 element3s += firsttriangle * 3;
2861         if (element3s_indexbuffer)
2862                 element3s_bufferoffset += firsttriangle * 3 * sizeof(*element3s);
2863         switch(vid.renderpath)
2864         {
2865         case RENDERPATH_GL11:
2866         case RENDERPATH_GL13:
2867         case RENDERPATH_GL20:
2868         case RENDERPATH_GLES1:
2869         case RENDERPATH_GLES2:
2870                 // check if the user specified to ignore static index buffers
2871                 if (!gl_state.usevbo_staticindex || (gl_vbo.integer == 3 && !vid.forcevbo && (element3i_bufferoffset || element3s_bufferoffset)))
2872                 {
2873                         element3i_indexbuffer = NULL;
2874                         element3s_indexbuffer = NULL;
2875                 }
2876                 break;
2877         case RENDERPATH_D3D9:
2878         case RENDERPATH_D3D10:
2879         case RENDERPATH_D3D11:
2880                 break;
2881         case RENDERPATH_SOFT:
2882                 break;
2883         }
2884         // upload a dynamic index buffer if needed
2885         if (element3s)
2886         {
2887                 if (!element3s_indexbuffer && gl_state.usevbo_dynamicindex)
2888                         element3s_indexbuffer = R_BufferData_Store(numelements * sizeof(*element3s), (void *)element3s, R_BUFFERDATA_INDEX16, &element3s_bufferoffset);
2889         }
2890         else if (element3i)
2891         {
2892                 if (!element3i_indexbuffer && gl_state.usevbo_dynamicindex)
2893                         element3i_indexbuffer = R_BufferData_Store(numelements * sizeof(*element3i), (void *)element3i, R_BUFFERDATA_INDEX32, &element3i_bufferoffset);
2894         }
2895         bufferobject3i = element3i_indexbuffer ? element3i_indexbuffer->bufferobject : 0;
2896         bufferoffset3i = element3i_bufferoffset;
2897         bufferobject3s = element3s_indexbuffer ? element3s_indexbuffer->bufferobject : 0;
2898         bufferoffset3s = element3s_bufferoffset;
2899         r_refdef.stats[r_stat_draws]++;
2900         r_refdef.stats[r_stat_draws_vertices] += numvertices;
2901         r_refdef.stats[r_stat_draws_elements] += numelements;
2902         if (gl_paranoid.integer)
2903         {
2904                 unsigned int i;
2905                 // LordHavoc: disabled this - it needs to be updated to handle components and gltype and stride in each array
2906 #if 0
2907                 unsigned int j, size;
2908                 const int *p;
2909                 // note: there's no validation done here on buffer objects because it
2910                 // is somewhat difficult to get at the data, and gl_paranoid can be
2911                 // used without buffer objects if the need arises
2912                 // (the data could be gotten using glMapBuffer but it would be very
2913                 //  slow due to uncachable video memory reads)
2914                 if (!qglIsEnabled(GL_VERTEX_ARRAY))
2915                         Con_Print("R_Mesh_Draw: vertex array not enabled\n");
2916                 CHECKGLERROR
2917                 if (gl_state.pointer_vertex_pointer)
2918                         for (j = 0, size = numvertices * 3, p = (int *)((float *)gl_state.pointer_vertex + firstvertex * 3);j < size;j++, p++)
2919                                 paranoidblah += *p;
2920                 if (gl_state.pointer_color_enabled)
2921                 {
2922                         if (!qglIsEnabled(GL_COLOR_ARRAY))
2923                                 Con_Print("R_Mesh_Draw: color array set but not enabled\n");
2924                         CHECKGLERROR
2925                         if (gl_state.pointer_color && gl_state.pointer_color_enabled)
2926                                 for (j = 0, size = numvertices * 4, p = (int *)((float *)gl_state.pointer_color + firstvertex * 4);j < size;j++, p++)
2927                                         paranoidblah += *p;
2928                 }
2929                 for (i = 0;i < vid.texarrayunits;i++)
2930                 {
2931                         if (gl_state.units[i].arrayenabled)
2932                         {
2933                                 GL_ClientActiveTexture(i);
2934                                 if (!qglIsEnabled(GL_TEXTURE_COORD_ARRAY))
2935                                         Con_Print("R_Mesh_Draw: texcoord array set but not enabled\n");
2936                                 CHECKGLERROR
2937                                 if (gl_state.units[i].pointer_texcoord && gl_state.units[i].arrayenabled)
2938                                         for (j = 0, size = numvertices * gl_state.units[i].arraycomponents, p = (int *)((float *)gl_state.units[i].pointer_texcoord + firstvertex * gl_state.units[i].arraycomponents);j < size;j++, p++)
2939                                                 paranoidblah += *p;
2940                         }
2941                 }
2942 #endif
2943                 if (element3i)
2944                 {
2945                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
2946                         {
2947                                 if (element3i[i] < firstvertex || element3i[i] >= firstvertex + numvertices)
2948                                 {
2949                                         Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range %i - %i) in element3i array\n", element3i[i], firstvertex, firstvertex + numvertices);
2950                                         return;
2951                                 }
2952                         }
2953                 }
2954                 if (element3s)
2955                 {
2956                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
2957                         {
2958                                 if (element3s[i] < firstvertex || element3s[i] >= firstvertex + numvertices)
2959                                 {
2960                                         Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range %i - %i) in element3s array\n", element3s[i], firstvertex, firstvertex + numvertices);
2961                                         return;
2962                                 }
2963                         }
2964                 }
2965         }
2966         if (r_render.integer || r_refdef.draw2dstage)
2967         {
2968                 switch(vid.renderpath)
2969                 {
2970                 case RENDERPATH_GL11:
2971                 case RENDERPATH_GL13:
2972                 case RENDERPATH_GL20:
2973                         CHECKGLERROR
2974                         if (gl_mesh_testmanualfeeding.integer)
2975                         {
2976 #ifndef USE_GLES2
2977                                 unsigned int i, j, element;
2978                                 const GLfloat *p;
2979                                 qglBegin(GL_TRIANGLES);
2980                                 if(vid.renderpath == RENDERPATH_GL20)
2981                                 {
2982                                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
2983                                         {
2984                                                 if (element3i)
2985                                                         element = element3i[i];
2986                                                 else if (element3s)
2987                                                         element = element3s[i];
2988                                                 else
2989                                                         element = firstvertex + i;
2990                                                 for (j = 0;j < vid.texarrayunits;j++)
2991                                                 {
2992                                                         if (gl_state.units[j].pointer_texcoord_pointer && gl_state.units[j].arrayenabled)
2993                                                         {
2994                                                                 if (gl_state.units[j].pointer_texcoord_gltype == GL_FLOAT)
2995                                                                 {
2996                                                                         p = (const GLfloat *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
2997                                                                         if (gl_state.units[j].pointer_texcoord_components == 4)
2998                                                                                 qglVertexAttrib4f(GLSLATTRIB_TEXCOORD0 + j, p[0], p[1], p[2], p[3]);
2999                                                                         else if (gl_state.units[j].pointer_texcoord_components == 3)
3000                                                                                 qglVertexAttrib3f(GLSLATTRIB_TEXCOORD0 + j, p[0], p[1], p[2]);
3001                                                                         else if (gl_state.units[j].pointer_texcoord_components == 2)
3002                                                                                 qglVertexAttrib2f(GLSLATTRIB_TEXCOORD0 + j, p[0], p[1]);
3003                                                                         else
3004                                                                                 qglVertexAttrib1f(GLSLATTRIB_TEXCOORD0 + j, p[0]);
3005                                                                 }
3006                                                                 else if (gl_state.units[j].pointer_texcoord_gltype == (int)(GL_SHORT | 0x80000000))
3007                                                                 {
3008                                                                         const GLshort *s = (const GLshort *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
3009                                                                         if (gl_state.units[j].pointer_texcoord_components == 4)
3010                                                                                 qglVertexAttrib4f(GLSLATTRIB_TEXCOORD0 + j, s[0], s[1], s[2], s[3]);
3011                                                                         else if (gl_state.units[j].pointer_texcoord_components == 3)
3012                                                                                 qglVertexAttrib3f(GLSLATTRIB_TEXCOORD0 + j, s[0], s[1], s[2]);
3013                                                                         else if (gl_state.units[j].pointer_texcoord_components == 2)
3014                                                                                 qglVertexAttrib2f(GLSLATTRIB_TEXCOORD0 + j, s[0], s[1]);
3015                                                                         else if (gl_state.units[j].pointer_texcoord_components == 1)
3016                                                                                 qglVertexAttrib1f(GLSLATTRIB_TEXCOORD0 + j, s[0]);
3017                                                                 }
3018                                                                 else if (gl_state.units[j].pointer_texcoord_gltype == GL_BYTE)
3019                                                                 {
3020                                                                         const GLbyte *sb = (const GLbyte *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
3021                                                                         if (gl_state.units[j].pointer_texcoord_components == 4)
3022                                                                                 qglVertexAttrib4f(GLSLATTRIB_TEXCOORD0 + j, sb[0] * (1.0f / 127.0f), sb[1] * (1.0f / 127.0f), sb[2] * (1.0f / 127.0f), sb[3] * (1.0f / 127.0f));
3023                                                                         else if (gl_state.units[j].pointer_texcoord_components == 3)
3024                                                                                 qglVertexAttrib3f(GLSLATTRIB_TEXCOORD0 + j, sb[0] * (1.0f / 127.0f), sb[1] * (1.0f / 127.0f), sb[2] * (1.0f / 127.0f));
3025                                                                         else if (gl_state.units[j].pointer_texcoord_components == 2)
3026                                                                                 qglVertexAttrib2f(GLSLATTRIB_TEXCOORD0 + j, sb[0] * (1.0f / 127.0f), sb[1] * (1.0f / 127.0f));
3027                                                                         else if (gl_state.units[j].pointer_texcoord_components == 1)
3028                                                                                 qglVertexAttrib1f(GLSLATTRIB_TEXCOORD0 + j, sb[0] * (1.0f / 127.0f));
3029                                                                 }
3030                                                                 else if (gl_state.units[j].pointer_texcoord_gltype == GL_UNSIGNED_BYTE)
3031                                                                 {
3032                                                                         const GLubyte *sb = (const GLubyte *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
3033                                                                         if (gl_state.units[j].pointer_texcoord_components == 4)
3034                                                                                 qglVertexAttrib4f(GLSLATTRIB_TEXCOORD0 + j, sb[0] * (1.0f / 255.0f), sb[1] * (1.0f / 255.0f), sb[2] * (1.0f / 255.0f), sb[3] * (1.0f / 255.0f));
3035                                                                         else if (gl_state.units[j].pointer_texcoord_components == 3)
3036                                                                                 qglVertexAttrib3f(GLSLATTRIB_TEXCOORD0 + j, sb[0] * (1.0f / 255.0f), sb[1] * (1.0f / 255.0f), sb[2] * (1.0f / 255.0f));
3037                                                                         else if (gl_state.units[j].pointer_texcoord_components == 2)
3038                                                                                 qglVertexAttrib2f(GLSLATTRIB_TEXCOORD0 + j, sb[0] * (1.0f / 255.0f), sb[1] * (1.0f / 255.0f));
3039                                                                         else if (gl_state.units[j].pointer_texcoord_components == 1)
3040                                                                                 qglVertexAttrib1f(GLSLATTRIB_TEXCOORD0 + j, sb[0] * (1.0f / 255.0f));
3041                                                                 }
3042                                                                 else if (gl_state.units[j].pointer_texcoord_gltype == (int)(GL_UNSIGNED_BYTE | 0x80000000))
3043                                                                 {
3044                                                                         const GLubyte *sb = (const GLubyte *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
3045                                                                         if (gl_state.units[j].pointer_texcoord_components == 4)
3046                                                                                 qglVertexAttrib4f(GLSLATTRIB_TEXCOORD0 + j, sb[0], sb[1], sb[2], sb[3]);
3047                                                                         else if (gl_state.units[j].pointer_texcoord_components == 3)
3048                                                                                 qglVertexAttrib3f(GLSLATTRIB_TEXCOORD0 + j, sb[0], sb[1], sb[2]);
3049                                                                         else if (gl_state.units[j].pointer_texcoord_components == 2)
3050                                                                                 qglVertexAttrib2f(GLSLATTRIB_TEXCOORD0 + j, sb[0], sb[1]);
3051                                                                         else if (gl_state.units[j].pointer_texcoord_components == 1)
3052                                                                                 qglVertexAttrib1f(GLSLATTRIB_TEXCOORD0 + j, sb[0]);
3053                                                                 }
3054                                                         }
3055                                                 }
3056                                                 if (gl_state.pointer_color_pointer && gl_state.pointer_color_enabled && gl_state.pointer_color_components == 4)
3057                                                 {
3058                                                         if (gl_state.pointer_color_gltype == GL_FLOAT)
3059                                                         {
3060                                                                 p = (const GLfloat *)((const unsigned char *)gl_state.pointer_color_pointer + element * gl_state.pointer_color_stride);
3061                                                                 qglVertexAttrib4f(GLSLATTRIB_COLOR, p[0], p[1], p[2], p[3]);
3062                                                         }
3063                                                         else if (gl_state.pointer_color_gltype == GL_UNSIGNED_BYTE)
3064                                                         {
3065                                                                 const GLubyte *ub = (const GLubyte *)((const unsigned char *)gl_state.pointer_color_pointer + element * gl_state.pointer_color_stride);
3066                                                                 qglVertexAttrib4Nub(GLSLATTRIB_COLOR, ub[0], ub[1], ub[2], ub[3]);
3067                                                         }
3068                                                 }
3069                                                 if (gl_state.pointer_vertex_gltype == GL_FLOAT)
3070                                                 {
3071                                                         p = (const GLfloat *)((const unsigned char *)gl_state.pointer_vertex_pointer + element * gl_state.pointer_vertex_stride);
3072                                                         if (gl_state.pointer_vertex_components == 4)
3073                                                                 qglVertexAttrib4f(GLSLATTRIB_POSITION, p[0], p[1], p[2], p[3]);
3074                                                         else if (gl_state.pointer_vertex_components == 3)
3075                                                                 qglVertexAttrib3f(GLSLATTRIB_POSITION, p[0], p[1], p[2]);
3076                                                         else
3077                                                                 qglVertexAttrib2f(GLSLATTRIB_POSITION, p[0], p[1]);
3078                                                 }
3079                                         }
3080                                 }
3081                                 else
3082                                 {
3083                                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
3084                                         {
3085                                                 if (element3i)
3086                    &