]> de.git.xonotic.org Git - xonotic/darkplaces.git/blobdiff - gl_backend.c
gave names to nearly all structs and enums which should make for better C++ error...
[xonotic/darkplaces.git] / gl_backend.c
index f5117ecedb65f46bacc3a56ddcd377894bfdab9a..57372862ce74073896f3affd21929106b458be53 100644 (file)
@@ -7,9 +7,13 @@
 cvar_t gl_mesh_drawrangeelements = {0, "gl_mesh_drawrangeelements", "1"};
 cvar_t gl_mesh_testarrayelement = {0, "gl_mesh_testarrayelement", "0"};
 cvar_t gl_mesh_testmanualfeeding = {0, "gl_mesh_testmanualfeeding", "0"};
-cvar_t gl_delayfinish = {CVAR_SAVE, "gl_delayfinish", "0"};
 cvar_t gl_paranoid = {0, "gl_paranoid", "0"};
 cvar_t gl_printcheckerror = {0, "gl_printcheckerror", "0"};
+cvar_t r_stereo_separation = {0, "r_stereo_separation", "4"};
+cvar_t r_stereo_sidebyside = {0, "r_stereo_sidebyside", "0"};
+cvar_t r_stereo_redblue = {0, "r_stereo_redblue", "0"};
+cvar_t r_stereo_redcyan = {0, "r_stereo_redcyan", "0"};
+cvar_t r_stereo_redgreen = {0, "r_stereo_redgreen", "0"};
 
 cvar_t r_render = {0, "r_render", "1"};
 cvar_t r_waterwarp = {CVAR_SAVE, "r_waterwarp", "1"};
@@ -71,8 +75,6 @@ void GL_PrintError(int errornumber, char *filename, int linenumber)
 
 #define BACKENDACTIVECHECK if (!backendactive) Sys_Error("GL backend function called when backend is not active\n");
 
-int c_meshs, c_meshelements;
-
 void SCR_ScreenShot_f (void);
 
 static matrix4x4_t backend_viewmatrix;
@@ -81,8 +83,7 @@ static matrix4x4_t backend_modelviewmatrix;
 static matrix4x4_t backend_glmodelviewmatrix;
 static matrix4x4_t backend_projectmatrix;
 
-static int backendunits, backendactive;
-static mempool_t *gl_backend_mempool;
+static unsigned int backendunits, backendimageunits, backendarrayunits, backendactive;
 
 /*
 note: here's strip order for a terrain row:
@@ -144,20 +145,19 @@ static void R_Mesh_CacheArray_Startup(void);
 static void R_Mesh_CacheArray_Shutdown(void);
 void GL_Backend_AllocArrays(void)
 {
-       if (!gl_backend_mempool)
-               gl_backend_mempool = Mem_AllocPool("GL_Backend");
        R_Mesh_CacheArray_Startup();
 }
 
 void GL_Backend_FreeArrays(void)
 {
        R_Mesh_CacheArray_Shutdown();
-       Mem_FreePool(&gl_backend_mempool);
 }
 
 static void gl_backend_start(void)
 {
-       Con_DPrint("OpenGL Backend started\n");
+       Con_Print("OpenGL Backend starting...\n");
+       CHECKGLERROR
+
        if (qglDrawRangeElements != NULL)
        {
                CHECKGLERROR
@@ -165,22 +165,43 @@ static void gl_backend_start(void)
                CHECKGLERROR
                qglGetIntegerv(GL_MAX_ELEMENTS_INDICES, &gl_maxdrawrangeelementsindices);
                CHECKGLERROR
-               Con_DPrintf("glDrawRangeElements detected (max vertices %i, max indices %i)\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
+               Con_Printf("glDrawRangeElements detected (max vertices %i, max indices %i)\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
        }
 
        backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
+       backendimageunits = backendunits;
+       backendarrayunits = backendunits;
+       if (gl_support_fragment_shader)
+       {
+               CHECKGLERROR
+               qglGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, (int *)&backendimageunits);
+               CHECKGLERROR
+               qglGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, (int *)&backendarrayunits);
+               CHECKGLERROR
+               Con_Printf("GLSL shader support detected: texture units = %i texenv, %i image, %i array\n", backendunits, backendimageunits, backendarrayunits);
+       }
+       else if (backendunits > 1)
+               Con_Printf("multitexture detected: texture units = %i\n", backendunits);
+       else
+               Con_Printf("singletexture\n");
 
        GL_Backend_AllocArrays();
 
+       Con_Printf("OpenGL backend started.\n");
+
+       CHECKGLERROR
+
        backendactive = true;
 }
 
 static void gl_backend_shutdown(void)
 {
        backendunits = 0;
+       backendimageunits = 0;
+       backendarrayunits = 0;
        backendactive = false;
 
-       Con_DPrint("OpenGL Backend shutting down\n");
+       Con_Print("OpenGL Backend shutting down\n");
 
        GL_Backend_FreeArrays();
 }
@@ -207,10 +228,14 @@ void gl_backend_init(void)
 
        Cvar_RegisterVariable(&r_render);
        Cvar_RegisterVariable(&r_waterwarp);
+       Cvar_RegisterVariable(&r_stereo_separation);
+       Cvar_RegisterVariable(&r_stereo_sidebyside);
+       Cvar_RegisterVariable(&r_stereo_redblue);
+       Cvar_RegisterVariable(&r_stereo_redcyan);
+       Cvar_RegisterVariable(&r_stereo_redgreen);
        Cvar_RegisterVariable(&gl_polyblend);
        Cvar_RegisterVariable(&gl_dither);
        Cvar_RegisterVariable(&gl_lockarrays);
-       Cvar_RegisterVariable(&gl_delayfinish);
        Cvar_RegisterVariable(&gl_paranoid);
        Cvar_RegisterVariable(&gl_printcheckerror);
 #ifdef NORENDER
@@ -371,7 +396,7 @@ typedef struct gltextureunit_s
 {
        int t1d, t2d, t3d, tcubemap;
        int arrayenabled;
-       int arrayis3d;
+       unsigned int arraycomponents;
        const void *pointer_texcoord;
        float rgbscale, alphascale;
        int combinergb, combinealpha;
@@ -382,7 +407,7 @@ typedef struct gltextureunit_s
 }
 gltextureunit_t;
 
-static struct
+static struct gl_state_s
 {
        int blendfunc1;
        int blendfunc2;
@@ -391,8 +416,8 @@ static struct
        int colormask; // stored as bottom 4 bits: r g b a (3 2 1 0 order)
        int depthtest;
        int scissortest;
-       int unit;
-       int clientunit;
+       unsigned int unit;
+       unsigned int clientunit;
        gltextureunit_t units[MAX_TEXTUREUNITS];
        float color4f[4];
        int lockrange_first;
@@ -404,22 +429,20 @@ gl_state;
 
 void GL_SetupTextureState(void)
 {
-       int i;
+       unsigned int i;
        gltextureunit_t *unit;
        CHECKGLERROR
-       gl_state.unit = -1;
-       gl_state.clientunit = -1;
-       for (i = 0;i < backendunits;i++)
+       gl_state.unit = MAX_TEXTUREUNITS;
+       gl_state.clientunit = MAX_TEXTUREUNITS;
+       for (i = 0;i < MAX_TEXTUREUNITS;i++)
        {
-               GL_ActiveTexture(i);
-               GL_ClientActiveTexture(i);
                unit = gl_state.units + i;
                unit->t1d = 0;
                unit->t2d = 0;
                unit->t3d = 0;
                unit->tcubemap = 0;
                unit->arrayenabled = false;
-               unit->arrayis3d = false;
+               unit->arraycomponents = 0;
                unit->pointer_texcoord = NULL;
                unit->rgbscale = 1;
                unit->alphascale = 1;
@@ -427,13 +450,33 @@ void GL_SetupTextureState(void)
                unit->combinealpha = GL_MODULATE;
                unit->texmatrixenabled = false;
                unit->matrix = r_identitymatrix;
-               qglMatrixMode(GL_TEXTURE);
-               qglLoadIdentity();
-               qglMatrixMode(GL_MODELVIEW);
+       }
 
+       for (i = 0;i < backendimageunits;i++)
+       {
+               GL_ActiveTexture(i);
+               qglBindTexture(GL_TEXTURE_1D, 0);CHECKGLERROR
+               qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
+               if (gl_texture3d)
+               {
+                       qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
+               }
+               if (gl_texturecubemap)
+               {
+                       qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, 0);CHECKGLERROR
+               }
+       }
+
+       for (i = 0;i < backendarrayunits;i++)
+       {
+               GL_ClientActiveTexture(i);
                qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), NULL);CHECKGLERROR
                qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+       }
 
+       for (i = 0;i < backendunits;i++)
+       {
+               GL_ActiveTexture(i);
                qglDisable(GL_TEXTURE_1D);CHECKGLERROR
                qglDisable(GL_TEXTURE_2D);CHECKGLERROR
                if (gl_texture3d)
@@ -444,6 +487,9 @@ void GL_SetupTextureState(void)
                {
                        qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
                }
+               qglMatrixMode(GL_TEXTURE);
+               qglLoadIdentity();
+               qglMatrixMode(GL_MODELVIEW);
                if (gl_combine.integer)
                {
                        qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
@@ -509,7 +555,7 @@ void GL_Backend_ResetState(void)
        GL_SetupTextureState();
 }
 
-void GL_ActiveTexture(int num)
+void GL_ActiveTexture(unsigned int num)
 {
        if (gl_state.unit != num)
        {
@@ -522,7 +568,7 @@ void GL_ActiveTexture(int num)
        }
 }
 
-void GL_ClientActiveTexture(int num)
+void GL_ClientActiveTexture(unsigned int num)
 {
        if (gl_state.clientunit != num)
        {
@@ -663,7 +709,7 @@ void GL_LockArrays(int first, int count)
 void GL_Scissor (int x, int y, int width, int height)
 {
        CHECKGLERROR
-       qglScissor(x, vid.realheight - (y + height),width,height);
+       qglScissor(x, vid.height - (y + height),width,height);
        CHECKGLERROR
 }
 
@@ -707,6 +753,109 @@ void R_Mesh_Start(void)
        GL_Backend_ResetState();
 }
 
+unsigned int GL_Backend_CompileProgram(int vertexstrings_count, const char **vertexstrings_list, int fragmentstrings_count, const char **fragmentstrings_list)
+{
+       GLint vertexshadercompiled, fragmentshadercompiled, programlinked;
+       GLuint vertexshaderobject, fragmentshaderobject, programobject = 0;
+       char compilelog[4096];
+       CHECKGLERROR
+
+       programobject = qglCreateProgramObjectARB();
+       CHECKGLERROR
+       if (!programobject)
+               return 0;
+
+       if (vertexstrings_count)
+       {
+               CHECKGLERROR
+               vertexshaderobject = qglCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
+               if (!vertexshaderobject)
+               {
+                       qglDeleteObjectARB(programobject);
+                       CHECKGLERROR
+                       return 0;
+               }
+               qglShaderSourceARB(vertexshaderobject, vertexstrings_count, vertexstrings_list, NULL);
+               qglCompileShaderARB(vertexshaderobject);
+               CHECKGLERROR
+               qglGetObjectParameterivARB(vertexshaderobject, GL_OBJECT_COMPILE_STATUS_ARB, &vertexshadercompiled);
+               qglGetInfoLogARB(vertexshaderobject, sizeof(compilelog), NULL, compilelog);
+               if (compilelog[0])
+                       Con_Printf("vertex shader compile log:\n%s\n", compilelog);
+               if (!vertexshadercompiled)
+               {
+                       qglDeleteObjectARB(programobject);
+                       qglDeleteObjectARB(vertexshaderobject);
+                       CHECKGLERROR
+                       return 0;
+               }
+               qglAttachObjectARB(programobject, vertexshaderobject);
+               qglDeleteObjectARB(vertexshaderobject);
+               CHECKGLERROR
+       }
+
+       if (fragmentstrings_count)
+       {
+               CHECKGLERROR
+               fragmentshaderobject = qglCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
+               if (!fragmentshaderobject)
+               {
+                       qglDeleteObjectARB(programobject);
+                       CHECKGLERROR
+                       return 0;
+               }
+               qglShaderSourceARB(fragmentshaderobject, fragmentstrings_count, fragmentstrings_list, NULL);
+               qglCompileShaderARB(fragmentshaderobject);
+               CHECKGLERROR
+               qglGetObjectParameterivARB(fragmentshaderobject, GL_OBJECT_COMPILE_STATUS_ARB, &fragmentshadercompiled);
+               qglGetInfoLogARB(fragmentshaderobject, sizeof(compilelog), NULL, compilelog);
+               if (compilelog[0])
+                       Con_Printf("fragment shader compile log:\n%s\n", compilelog);
+               if (!fragmentshadercompiled)
+               {
+                       qglDeleteObjectARB(programobject);
+                       qglDeleteObjectARB(fragmentshaderobject);
+                       CHECKGLERROR
+                       return 0;
+               }
+               qglAttachObjectARB(programobject, fragmentshaderobject);
+               qglDeleteObjectARB(fragmentshaderobject);
+               CHECKGLERROR
+       }
+
+       qglLinkProgramARB(programobject);
+       CHECKGLERROR
+       qglGetObjectParameterivARB(programobject, GL_OBJECT_LINK_STATUS_ARB, &programlinked);
+       qglGetInfoLogARB(programobject, sizeof(compilelog), NULL, compilelog);
+       if (compilelog[0])
+       {
+               Con_Printf("program link log:\n%s\n", compilelog);
+               // software vertex shader is ok but software fragment shader is WAY
+               // too slow, fail program if so.
+               // NOTE: this string might be ATI specific, but that's ok because the
+               // ATI R300 chip (Radeon 9500-9800/X300) is the most likely to use a
+               // software fragment shader due to low instruction and dependent
+               // texture limits.
+               if (strstr(compilelog, "fragment shader will run in software"))
+                       programlinked = false;
+       }
+       CHECKGLERROR
+       if (!programlinked)
+       {
+               qglDeleteObjectARB(programobject);
+               return 0;
+       }
+       CHECKGLERROR
+       return programobject;
+}
+
+void GL_Backend_FreeProgram(unsigned int prog)
+{
+       CHECKGLERROR
+       qglDeleteObjectARB(prog);
+       CHECKGLERROR
+}
+
 int gl_backend_rebindtextures;
 
 void GL_Backend_RenumberElements(int *out, int count, const int *in, int offset)
@@ -723,55 +872,53 @@ void GL_Backend_RenumberElements(int *out, int count, const int *in, int offset)
 
 // renders triangles using vertices from the active arrays
 int paranoidblah = 0;
-void R_Mesh_Draw(int numverts, int numtriangles, const int *elements)
+void R_Mesh_Draw(int firstvertex, int numvertices, int numtriangles, const int *elements)
 {
-       int numelements = numtriangles * 3;
-       if (numverts == 0 || numtriangles == 0)
+       unsigned int numelements = numtriangles * 3;
+       if (numvertices < 3 || numtriangles < 1)
        {
-               Con_Printf("R_Mesh_Draw(%d, %d, %08p);\n", numverts, numtriangles, elements);
+               Con_Printf("R_Mesh_Draw(%d, %d, %d, %08p);\n", firstvertex, numvertices, numtriangles, elements);
                return;
        }
-       CHECKGLERROR
+       //CHECKGLERROR
        if (r_showtrispass)
        {
-               R_Mesh_Draw_ShowTris(numverts, numtriangles, elements);
+               R_Mesh_Draw_ShowTris(firstvertex, numvertices, numtriangles, elements);
                return;
        }
        c_meshs++;
        c_meshelements += numelements;
        if (gl_paranoid.integer)
        {
-               int i, j, size;
+               unsigned int i, j, size;
                const int *p;
                if (!qglIsEnabled(GL_VERTEX_ARRAY))
                        Con_Print("R_Mesh_Draw: vertex array not enabled\n");
-               for (j = 0, size = numverts * (int)sizeof(float[3]), p = gl_state.pointer_vertex;j < size;j += sizeof(int), p++)
+               for (j = 0, size = numvertices * 3, p = (int *)((float *)gl_state.pointer_vertex + firstvertex * 3);j < size;j++, p++)
                        paranoidblah += *p;
                if (gl_state.pointer_color)
                {
                        if (!qglIsEnabled(GL_COLOR_ARRAY))
                                Con_Print("R_Mesh_Draw: color array set but not enabled\n");
-                       for (j = 0, size = numverts * (int)sizeof(float[4]), p = gl_state.pointer_color;j < size;j += sizeof(int), p++)
+                       for (j = 0, size = numvertices * 4, p = (int *)((float *)gl_state.pointer_color + firstvertex * 4);j < size;j++, p++)
                                paranoidblah += *p;
                }
-               for (i = 0;i < backendunits;i++)
+               for (i = 0;i < backendarrayunits;i++)
                {
-                       if (gl_state.units[i].t1d || gl_state.units[i].t2d || gl_state.units[i].t3d || gl_state.units[i].tcubemap || gl_state.units[i].arrayenabled)
+                       if (gl_state.units[i].arrayenabled)
                        {
-                               if (gl_state.units[i].arrayenabled && !(gl_state.units[i].t1d || gl_state.units[i].t2d || gl_state.units[i].t3d || gl_state.units[i].tcubemap))
-                                       Con_Print("R_Mesh_Draw: array enabled but no texture bound\n");
                                GL_ClientActiveTexture(i);
                                if (!qglIsEnabled(GL_TEXTURE_COORD_ARRAY))
                                        Con_Print("R_Mesh_Draw: texcoord array set but not enabled\n");
-                               for (j = 0, size = numverts * ((gl_state.units[i].t3d || gl_state.units[i].tcubemap) ? (int)sizeof(float[3]) : (int)sizeof(float[2])), p = gl_state.units[i].pointer_texcoord;j < size;j += sizeof(int), p++)
+                               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++)
                                        paranoidblah += *p;
                        }
                }
-               for (i = 0;i < numtriangles * 3;i++)
+               for (i = 0;i < (unsigned int) numtriangles * 3;i++)
                {
-                       if (elements[i] < 0 || elements[i] >= numverts)
+                       if (elements[i] < firstvertex || elements[i] >= firstvertex + numvertices)
                        {
-                               Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range 0 - %i) in elements list\n", elements[i], numverts);
+                               Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range %i - %i) in elements list\n", elements[i], firstvertex, firstvertex + numvertices);
                                return;
                        }
                }
@@ -782,40 +929,60 @@ void R_Mesh_Draw(int numverts, int numtriangles, const int *elements)
                CHECKGLERROR
                if (gl_mesh_testmanualfeeding.integer)
                {
-                       int i, j;
+                       unsigned int i, j;
                        const GLfloat *p;
                        qglBegin(GL_TRIANGLES);
-                       for (i = 0;i < numtriangles * 3;i++)
+                       for (i = 0;i < (unsigned int) numtriangles * 3;i++)
                        {
-                               for (j = 0;j < backendunits;j++)
+                               for (j = 0;j < backendarrayunits;j++)
                                {
                                        if (gl_state.units[j].pointer_texcoord)
                                        {
-                                               if (backendunits > 1)
+                                               if (backendarrayunits > 1)
                                                {
-                                                       if (gl_state.units[j].t3d || gl_state.units[j].tcubemap)
+                                                       if (gl_state.units[j].arraycomponents == 4)
+                                                       {
+                                                               p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 4;
+                                                               qglMultiTexCoord4f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2], p[3]);
+                                                       }
+                                                       else if (gl_state.units[j].arraycomponents == 3)
                                                        {
                                                                p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
                                                                qglMultiTexCoord3f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2]);
                                                        }
-                                                       else
+                                                       else if (gl_state.units[j].arraycomponents == 2)
                                                        {
                                                                p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
                                                                qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, p[0], p[1]);
                                                        }
+                                                       else
+                                                       {
+                                                               p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 1;
+                                                               qglMultiTexCoord1f(GL_TEXTURE0_ARB + j, p[0]);
+                                                       }
                                                }
                                                else
                                                {
-                                                       if (gl_state.units[j].t3d || gl_state.units[j].tcubemap)
+                                                       if (gl_state.units[j].arraycomponents == 4)
+                                                       {
+                                                               p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 4;
+                                                               qglTexCoord4f(p[0], p[1], p[2], p[3]);
+                                                       }
+                                                       else if (gl_state.units[j].arraycomponents == 3)
                                                        {
                                                                p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
                                                                qglTexCoord3f(p[0], p[1], p[2]);
                                                        }
-                                                       else
+                                                       else if (gl_state.units[j].arraycomponents == 2)
                                                        {
                                                                p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
                                                                qglTexCoord2f(p[0], p[1]);
                                                        }
+                                                       else
+                                                       {
+                                                               p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 1;
+                                                               qglTexCoord1f(p[0]);
+                                                       }
                                                }
                                        }
                                }
@@ -843,32 +1010,48 @@ void R_Mesh_Draw(int numverts, int numtriangles, const int *elements)
                }
                else if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
                {
-                       qglDrawRangeElements(GL_TRIANGLES, 0, numverts, numelements, GL_UNSIGNED_INT, elements);CHECKGLERROR
+                       qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices, numelements, GL_UNSIGNED_INT, elements);
+                       CHECKGLERROR
                }
                else
                {
-                       qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, elements);CHECKGLERROR
+                       qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, elements);
+                       CHECKGLERROR
                }
-               CHECKGLERROR
        }
 }
 
 // restores backend state, used when done with 3D rendering
 void R_Mesh_Finish(void)
 {
-       int i;
+       unsigned int i;
        BACKENDACTIVECHECK
        CHECKGLERROR
        GL_LockArrays(0, 0);
        CHECKGLERROR
 
-       for (i = backendunits - 1;i >= 0;i--)
+       for (i = 0;i < backendimageunits;i++)
        {
-               if (qglActiveTexture)
-                       qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
-               if (qglClientActiveTexture)
-                       qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
+               GL_ActiveTexture(i);
+               qglBindTexture(GL_TEXTURE_1D, 0);CHECKGLERROR
+               qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
+               if (gl_texture3d)
+               {
+                       qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
+               }
+               if (gl_texturecubemap)
+               {
+                       qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, 0);CHECKGLERROR
+               }
+       }
+       for (i = 0;i < backendarrayunits;i++)
+       {
+               GL_ActiveTexture(backendarrayunits - 1 - i);
                qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+       }
+       for (i = 0;i < backendunits;i++)
+       {
+               GL_ActiveTexture(backendunits - 1 - i);
                qglDisable(GL_TEXTURE_1D);CHECKGLERROR
                qglDisable(GL_TEXTURE_2D);CHECKGLERROR
                if (gl_texture3d)
@@ -906,26 +1089,22 @@ void R_Mesh_Matrix(const matrix4x4_t *matrix)
        }
 }
 
-void R_Mesh_State(const rmeshstate_t *m)
+void R_Mesh_VertexPointer(const float *vertex3f)
 {
-       int i, combinergb, combinealpha, scale;
-       gltextureunit_t *unit;
-       matrix4x4_t tempmatrix;
-
-       BACKENDACTIVECHECK
-
-       if (gl_state.pointer_vertex != m->pointer_vertex)
+       if (gl_state.pointer_vertex != vertex3f)
        {
-               gl_state.pointer_vertex = m->pointer_vertex;
+               gl_state.pointer_vertex = vertex3f;
                CHECKGLERROR
                qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), gl_state.pointer_vertex);
                CHECKGLERROR
        }
+}
 
+void R_Mesh_ColorPointer(const float *color4f)
+{
        if (r_showtrispass)
                return;
-
-       if (gl_state.pointer_color != m->pointer_color)
+       if (gl_state.pointer_color != color4f)
        {
                CHECKGLERROR
                if (!gl_state.pointer_color)
@@ -933,7 +1112,7 @@ void R_Mesh_State(const rmeshstate_t *m)
                        qglEnableClientState(GL_COLOR_ARRAY);
                        CHECKGLERROR
                }
-               else if (!m->pointer_color)
+               else if (!color4f)
                {
                        qglDisableClientState(GL_COLOR_ARRAY);
                        CHECKGLERROR
@@ -941,235 +1120,489 @@ void R_Mesh_State(const rmeshstate_t *m)
                        qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);
                        CHECKGLERROR
                }
-               gl_state.pointer_color = m->pointer_color;
+               gl_state.pointer_color = color4f;
                qglColorPointer(4, GL_FLOAT, sizeof(float[4]), gl_state.pointer_color);
                CHECKGLERROR
        }
+}
 
-       if (gl_backend_rebindtextures)
+void R_Mesh_TexCoordPointer(unsigned int unitnum, unsigned int numcomponents, const float *texcoord)
+{
+       gltextureunit_t *unit = gl_state.units + unitnum;
+       if (r_showtrispass)
+               return;
+       // update array settings
+       if (texcoord)
        {
-               gl_backend_rebindtextures = false;
-               GL_SetupTextureState();
+               // texcoord array
+               if (unit->pointer_texcoord != texcoord || unit->arraycomponents != numcomponents)
+               {
+                       unit->pointer_texcoord = texcoord;
+                       unit->arraycomponents = numcomponents;
+                       GL_ClientActiveTexture(unitnum);
+                       qglTexCoordPointer(unit->arraycomponents, GL_FLOAT, sizeof(float) * unit->arraycomponents, unit->pointer_texcoord);
+                       CHECKGLERROR
+               }
+               // texture array unit is enabled, enable the array
+               if (!unit->arrayenabled)
+               {
+                       unit->arrayenabled = true;
+                       GL_ClientActiveTexture(unitnum);
+                       qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+               }
+       }
+       else
+       {
+               // texture array unit is disabled, disable the array
+               if (unit->arrayenabled)
+               {
+                       unit->arrayenabled = false;
+                       GL_ClientActiveTexture(unitnum);
+                       qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+               }
        }
+}
 
-       for (i = 0, unit = gl_state.units;i < backendunits;i++, unit++)
+void R_Mesh_TexBindAll(unsigned int unitnum, int tex1d, int tex2d, int tex3d, int texcubemap)
+{
+       gltextureunit_t *unit = gl_state.units + unitnum;
+       if (unitnum >= backendunits)
+               return;
+       if (r_showtrispass)
+               return;
+       // update 1d texture binding
+       if (unit->t1d != tex1d)
        {
-               // update 1d texture binding
-               if (unit->t1d != m->tex1d[i])
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
                {
-                       if (m->tex1d[i])
+                       if (tex1d)
                        {
                                if (unit->t1d == 0)
-                               {
-                                       GL_ActiveTexture(i);
-                                       qglEnable(GL_TEXTURE_1D);CHECKGLERROR
-                               }
-                               unit->t1d = m->tex1d[i];
-                               GL_ActiveTexture(i);
-                               qglBindTexture(GL_TEXTURE_1D, unit->t1d);CHECKGLERROR
+                                       qglEnable(GL_TEXTURE_1D);
                        }
                        else
                        {
                                if (unit->t1d)
-                               {
-                                       unit->t1d = 0;
-                                       GL_ActiveTexture(i);
-                                       qglDisable(GL_TEXTURE_1D);CHECKGLERROR
-                               }
+                                       qglDisable(GL_TEXTURE_1D);
                        }
                }
-               // update 2d texture binding
-               if (unit->t2d != m->tex[i])
+               unit->t1d = tex1d;
+               qglBindTexture(GL_TEXTURE_1D, unit->t1d);
+               CHECKGLERROR
+       }
+       // update 2d texture binding
+       if (unit->t2d != tex2d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
                {
-                       if (m->tex[i])
+                       if (tex2d)
                        {
                                if (unit->t2d == 0)
-                               {
-                                       GL_ActiveTexture(i);
-                                       qglEnable(GL_TEXTURE_2D);CHECKGLERROR
-                               }
-                               unit->t2d = m->tex[i];
-                               GL_ActiveTexture(i);
-                               qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR
+                                       qglEnable(GL_TEXTURE_2D);
                        }
                        else
                        {
                                if (unit->t2d)
-                               {
-                                       unit->t2d = 0;
-                                       GL_ActiveTexture(i);
-                                       qglDisable(GL_TEXTURE_2D);CHECKGLERROR
-                               }
+                                       qglDisable(GL_TEXTURE_2D);
                        }
                }
-               // update 3d texture binding
-               if (unit->t3d != m->tex3d[i])
+               unit->t2d = tex2d;
+               qglBindTexture(GL_TEXTURE_2D, unit->t2d);
+               CHECKGLERROR
+       }
+       // update 3d texture binding
+       if (unit->t3d != tex3d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
                {
-                       if (m->tex3d[i])
+                       if (tex3d)
                        {
                                if (unit->t3d == 0)
-                               {
-                                       GL_ActiveTexture(i);
-                                       qglEnable(GL_TEXTURE_3D);CHECKGLERROR
-                               }
-                               unit->t3d = m->tex3d[i];
-                               GL_ActiveTexture(i);
-                               qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR
+                                       qglEnable(GL_TEXTURE_3D);
                        }
                        else
                        {
                                if (unit->t3d)
-                               {
-                                       unit->t3d = 0;
-                                       GL_ActiveTexture(i);
-                                       qglDisable(GL_TEXTURE_3D);CHECKGLERROR
-                               }
+                                       qglDisable(GL_TEXTURE_3D);
                        }
                }
-               // update cubemap texture binding
-               if (unit->tcubemap != m->texcubemap[i])
+               unit->t3d = tex3d;
+               qglBindTexture(GL_TEXTURE_3D, unit->t3d);
+               CHECKGLERROR
+       }
+       // update cubemap texture binding
+       if (unit->tcubemap != texcubemap)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
                {
-                       if (m->texcubemap[i])
+                       if (texcubemap)
                        {
                                if (unit->tcubemap == 0)
-                               {
-                                       GL_ActiveTexture(i);
-                                       qglEnable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
-                               }
-                               unit->tcubemap = m->texcubemap[i];
-                               GL_ActiveTexture(i);
-                               qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);CHECKGLERROR
+                                       qglEnable(GL_TEXTURE_CUBE_MAP_ARB);
                        }
                        else
                        {
                                if (unit->tcubemap)
-                               {
-                                       unit->tcubemap = 0;
-                                       GL_ActiveTexture(i);
-                                       qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
-                               }
+                                       qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
                        }
                }
-               // update texture unit settings if the unit is enabled
-               if (unit->t1d || unit->t2d || unit->t3d || unit->tcubemap)
+               unit->tcubemap = texcubemap;
+               qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
+               CHECKGLERROR
+       }
+}
+
+void R_Mesh_TexBind1D(unsigned int unitnum, int texnum)
+{
+       gltextureunit_t *unit = gl_state.units + unitnum;
+       if (unitnum >= backendunits)
+               return;
+       if (r_showtrispass)
+               return;
+       // update 1d texture binding
+       if (unit->t1d != texnum)
+       {
+               GL_ActiveTexture(unitnum);
+               if (texnum)
                {
-                       // texture unit is enabled, enable the array
-                       if (!unit->arrayenabled)
-                       {
-                               unit->arrayenabled = true;
-                               GL_ClientActiveTexture(i);
-                               qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
-                       }
-                       // update combine settings
-                       if (gl_combine.integer)
-                       {
-                               // GL_ARB_texture_env_combine
-                               combinergb = m->texcombinergb[i] ? m->texcombinergb[i] : GL_MODULATE;
-                               if (unit->combinergb != combinergb)
-                               {
-                                       unit->combinergb = combinergb;
-                                       GL_ActiveTexture(i);
-                                       qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
-                               }
-                               combinealpha = m->texcombinealpha[i] ? m->texcombinealpha[i] : GL_MODULATE;
-                               if (unit->combinealpha != combinealpha)
-                               {
-                                       unit->combinealpha = combinealpha;
-                                       GL_ActiveTexture(i);
-                                       qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
-                               }
-                               scale = max(m->texrgbscale[i], 1);
-                               if (unit->rgbscale != scale)
-                               {
-                                       GL_ActiveTexture(i);
-                                       qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (unit->rgbscale = scale));CHECKGLERROR
-                               }
-                               scale = max(m->texalphascale[i], 1);
-                               if (unit->alphascale != scale)
-                               {
-                                       GL_ActiveTexture(i);
-                                       qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (unit->alphascale = scale));CHECKGLERROR
-                               }
-                       }
-                       else
-                       {
-                               // normal GL texenv
-                               combinergb = m->texcombinergb[i] ? m->texcombinergb[i] : GL_MODULATE;
-                               if (unit->combinergb != combinergb)
-                               {
-                                       unit->combinergb = combinergb;
-                                       GL_ActiveTexture(i);
-                                       qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
-                               }
-                       }
-                       // update array settings
-                       if (m->pointer_texcoord3f[i])
-                       {
-                               // 3d texcoord array
-                               if (unit->pointer_texcoord != m->pointer_texcoord3f[i] || !unit->arrayis3d)
-                               {
-                                       unit->pointer_texcoord = m->pointer_texcoord3f[i];
-                                       unit->arrayis3d = true;
-                                       GL_ClientActiveTexture(i);
-                                       qglTexCoordPointer(3, GL_FLOAT, sizeof(float[3]), unit->pointer_texcoord);
-                                       CHECKGLERROR
-                               }
-                       }
-                       else
-                       {
-                               // 2d texcoord array
-                               if (unit->pointer_texcoord != m->pointer_texcoord[i] || unit->arrayis3d)
-                               {
-                                       unit->pointer_texcoord = m->pointer_texcoord[i];
-                                       unit->arrayis3d = false;
-                                       GL_ClientActiveTexture(i);
-                                       qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), unit->pointer_texcoord);
-                                       CHECKGLERROR
-                               }
-                       }
-                       // update texmatrix
-                       if (m->texmatrix[i].m[3][3])
-                       {
-                               // texmatrix specified, check if it is different
-                               if (!unit->texmatrixenabled || memcmp(&unit->matrix, &m->texmatrix[i], sizeof(matrix4x4_t)))
-                               {
-                                       unit->texmatrixenabled = true;
-                                       unit->matrix = m->texmatrix[i];
-                                       Matrix4x4_Transpose(&tempmatrix, &unit->matrix);
-                                       qglMatrixMode(GL_TEXTURE);
-                                       GL_ActiveTexture(i);
-                                       qglLoadMatrixf(&tempmatrix.m[0][0]);
-                                       qglMatrixMode(GL_MODELVIEW);
-                               }
-                       }
-                       else
-                       {
-                               // no texmatrix specified, revert to identity
-                               if (unit->texmatrixenabled)
-                               {
-                                       unit->texmatrixenabled = false;
-                                       qglMatrixMode(GL_TEXTURE);
-                                       GL_ActiveTexture(i);
-                                       qglLoadIdentity();
-                                       qglMatrixMode(GL_MODELVIEW);
-                               }
-                       }
+                       if (unit->t1d == 0)
+                               qglEnable(GL_TEXTURE_1D);
                }
                else
                {
-                       // texture unit is disabled, disable the array
-                       if (unit->arrayenabled)
-                       {
-                               unit->arrayenabled = false;
-                               GL_ClientActiveTexture(i);
-                               qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
-                       }
-                       // no need to update most settings on a disabled texture unit
+                       if (unit->t1d)
+                               qglDisable(GL_TEXTURE_1D);
+               }
+               unit->t1d = texnum;
+               qglBindTexture(GL_TEXTURE_1D, unit->t1d);
+               CHECKGLERROR
+       }
+       // update 2d texture binding
+       if (unit->t2d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unit->t2d)
+                       qglDisable(GL_TEXTURE_2D);
+               unit->t2d = 0;
+               qglBindTexture(GL_TEXTURE_2D, unit->t2d);
+               CHECKGLERROR
+       }
+       // update 3d texture binding
+       if (unit->t3d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unit->t3d)
+                       qglDisable(GL_TEXTURE_3D);
+               unit->t3d = 0;
+               qglBindTexture(GL_TEXTURE_3D, unit->t3d);
+               CHECKGLERROR
+       }
+       // update cubemap texture binding
+       if (unit->tcubemap)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unit->tcubemap)
+                       qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
+               unit->tcubemap = 0;
+               qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
+               CHECKGLERROR
+       }
+}
+
+void R_Mesh_TexBind(unsigned int unitnum, int texnum)
+{
+       gltextureunit_t *unit = gl_state.units + unitnum;
+       if (unitnum >= backendunits)
+               return;
+       if (r_showtrispass)
+               return;
+       // update 1d texture binding
+       if (unit->t1d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unit->t1d)
+                       qglDisable(GL_TEXTURE_1D);
+               unit->t1d = 0;
+               qglBindTexture(GL_TEXTURE_1D, unit->t1d);
+               CHECKGLERROR
+       }
+       // update 2d texture binding
+       if (unit->t2d != texnum)
+       {
+               GL_ActiveTexture(unitnum);
+               if (texnum)
+               {
+                       if (unit->t2d == 0)
+                               qglEnable(GL_TEXTURE_2D);
+               }
+               else
+               {
+                       if (unit->t2d)
+                               qglDisable(GL_TEXTURE_2D);
+               }
+               unit->t2d = texnum;
+               qglBindTexture(GL_TEXTURE_2D, unit->t2d);
+               CHECKGLERROR
+       }
+       // update 3d texture binding
+       if (unit->t3d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unit->t3d)
+                       qglDisable(GL_TEXTURE_3D);
+               unit->t3d = 0;
+               qglBindTexture(GL_TEXTURE_3D, unit->t3d);
+               CHECKGLERROR
+       }
+       // update cubemap texture binding
+       if (unit->tcubemap != 0)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unit->tcubemap)
+                       qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
+               unit->tcubemap = 0;
+               qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
+               CHECKGLERROR
+       }
+}
+
+void R_Mesh_TexBind3D(unsigned int unitnum, int texnum)
+{
+       gltextureunit_t *unit = gl_state.units + unitnum;
+       if (unitnum >= backendunits)
+               return;
+       if (r_showtrispass)
+               return;
+       // update 1d texture binding
+       if (unit->t1d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unit->t1d)
+                       qglDisable(GL_TEXTURE_1D);
+               unit->t1d = 0;
+               qglBindTexture(GL_TEXTURE_1D, unit->t1d);
+               CHECKGLERROR
+       }
+       // update 2d texture binding
+       if (unit->t2d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unit->t2d)
+                       qglDisable(GL_TEXTURE_2D);
+               unit->t2d = 0;
+               qglBindTexture(GL_TEXTURE_2D, unit->t2d);
+               CHECKGLERROR
+       }
+       // update 3d texture binding
+       if (unit->t3d != texnum)
+       {
+               GL_ActiveTexture(unitnum);
+               if (texnum)
+               {
+                       if (unit->t3d == 0)
+                               qglEnable(GL_TEXTURE_3D);
+               }
+               else
+               {
+                       if (unit->t3d)
+                               qglDisable(GL_TEXTURE_3D);
+               }
+               unit->t3d = texnum;
+               qglBindTexture(GL_TEXTURE_3D, unit->t3d);
+               CHECKGLERROR
+       }
+       // update cubemap texture binding
+       if (unit->tcubemap != 0)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unit->tcubemap)
+                       qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
+               unit->tcubemap = 0;
+               qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
+               CHECKGLERROR
+       }
+}
+
+void R_Mesh_TexBindCubeMap(unsigned int unitnum, int texnum)
+{
+       gltextureunit_t *unit = gl_state.units + unitnum;
+       if (unitnum >= backendunits)
+               return;
+       if (r_showtrispass)
+               return;
+       // update 1d texture binding
+       if (unit->t1d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unit->t1d)
+                       qglDisable(GL_TEXTURE_1D);
+               unit->t1d = 0;
+               qglBindTexture(GL_TEXTURE_1D, unit->t1d);
+               CHECKGLERROR
+       }
+       // update 2d texture binding
+       if (unit->t2d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unit->t2d)
+                       qglDisable(GL_TEXTURE_2D);
+               unit->t2d = 0;
+               qglBindTexture(GL_TEXTURE_2D, unit->t2d);
+               CHECKGLERROR
+       }
+       // update 3d texture binding
+       if (unit->t3d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unit->t3d)
+                       qglDisable(GL_TEXTURE_3D);
+               unit->t3d = 0;
+               qglBindTexture(GL_TEXTURE_3D, unit->t3d);
+               CHECKGLERROR
+       }
+       // update cubemap texture binding
+       if (unit->tcubemap != texnum)
+       {
+               GL_ActiveTexture(unitnum);
+               if (texnum)
+               {
+                       if (unit->tcubemap == 0)
+                               qglEnable(GL_TEXTURE_CUBE_MAP_ARB);
+               }
+               else
+               {
+                       if (unit->tcubemap)
+                               qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
                }
+               unit->tcubemap = texnum;
+               qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
+               CHECKGLERROR
        }
 }
 
-void R_Mesh_Draw_ShowTris(int numverts, int numtriangles, const int *elements)
+void R_Mesh_TexMatrix(unsigned int unitnum, const matrix4x4_t *matrix)
+{
+       gltextureunit_t *unit = gl_state.units + unitnum;
+       if (r_showtrispass)
+               return;
+       if (matrix->m[3][3])
+       {
+               // texmatrix specified, check if it is different
+               if (!unit->texmatrixenabled || memcmp(&unit->matrix, matrix, sizeof(matrix4x4_t)))
+               {
+                       matrix4x4_t tempmatrix;
+                       unit->texmatrixenabled = true;
+                       unit->matrix = *matrix;
+                       Matrix4x4_Transpose(&tempmatrix, &unit->matrix);
+                       qglMatrixMode(GL_TEXTURE);
+                       GL_ActiveTexture(unitnum);
+                       qglLoadMatrixf(&tempmatrix.m[0][0]);
+                       qglMatrixMode(GL_MODELVIEW);
+               }
+       }
+       else
+       {
+               // no texmatrix specified, revert to identity
+               if (unit->texmatrixenabled)
+               {
+                       unit->texmatrixenabled = false;
+                       qglMatrixMode(GL_TEXTURE);
+                       GL_ActiveTexture(unitnum);
+                       qglLoadIdentity();
+                       qglMatrixMode(GL_MODELVIEW);
+               }
+       }
+}
+
+void R_Mesh_TexCombine(unsigned int unitnum, int combinergb, int combinealpha, int rgbscale, int alphascale)
+{
+       gltextureunit_t *unit = gl_state.units + unitnum;
+       if (r_showtrispass)
+               return;
+       if (gl_combine.integer)
+       {
+               // GL_ARB_texture_env_combine
+               if (!combinergb)
+                       combinergb = GL_MODULATE;
+               if (!combinealpha)
+                       combinealpha = GL_MODULATE;
+               if (!rgbscale)
+                       rgbscale = 1;
+               if (!alphascale)
+                       alphascale = 1;
+               if (unit->combinergb != combinergb)
+               {
+                       unit->combinergb = combinergb;
+                       GL_ActiveTexture(unitnum);
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
+               }
+               if (unit->combinealpha != combinealpha)
+               {
+                       unit->combinealpha = combinealpha;
+                       GL_ActiveTexture(unitnum);
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
+               }
+               if (unit->rgbscale != rgbscale)
+               {
+                       GL_ActiveTexture(unitnum);
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (unit->rgbscale = rgbscale));CHECKGLERROR
+               }
+               if (unit->alphascale != alphascale)
+               {
+                       GL_ActiveTexture(unitnum);
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (unit->alphascale = alphascale));CHECKGLERROR
+               }
+       }
+       else
+       {
+               // normal GL texenv
+               if (!combinergb)
+                       combinergb = GL_MODULATE;
+               if (unit->combinergb != combinergb)
+               {
+                       unit->combinergb = combinergb;
+                       GL_ActiveTexture(unitnum);
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
+               }
+       }
+}
+
+void R_Mesh_State(const rmeshstate_t *m)
+{
+       unsigned int i;
+
+       BACKENDACTIVECHECK
+
+       R_Mesh_VertexPointer(m->pointer_vertex);
+       R_Mesh_ColorPointer(m->pointer_color);
+
+       if (gl_backend_rebindtextures)
+       {
+               gl_backend_rebindtextures = false;
+               GL_SetupTextureState();
+       }
+
+       for (i = 0;i < backendimageunits;i++)
+               R_Mesh_TexBindAll(i, m->tex1d[i], m->tex[i], m->tex3d[i], m->texcubemap[i]);
+       for (i = 0;i < backendarrayunits;i++)
+       {
+               if (m->pointer_texcoord3f[i])
+                       R_Mesh_TexCoordPointer(i, 3, m->pointer_texcoord3f[i]);
+               else
+                       R_Mesh_TexCoordPointer(i, 2, m->pointer_texcoord[i]);
+       }
+       for (i = 0;i < backendunits;i++)
+       {
+               R_Mesh_TexMatrix(i, &m->texmatrix[i]);
+               R_Mesh_TexCombine(i, m->texcombinergb[i], m->texcombinealpha[i], m->texrgbscale[i], m->texalphascale[i]);
+       }
+}
+
+void R_Mesh_Draw_ShowTris(int firstvertex, int numvertices, int numtriangles, const int *elements)
 {
        qglBegin(GL_LINES);
        for (;numtriangles;numtriangles--, elements += 3)
@@ -1190,7 +1623,7 @@ void R_Mesh_Draw_ShowTris(int numverts, int numtriangles, const int *elements)
 ==============================================================================
 */
 
-qboolean SCR_ScreenShot(char *filename, qbyte *buffer1, qbyte *buffer2, qbyte *buffer3, int x, int y, int width, int height, qboolean flipx, qboolean flipy, qboolean flipdiagonal, qboolean jpeg)
+qboolean SCR_ScreenShot(char *filename, qbyte *buffer1, qbyte *buffer2, qbyte *buffer3, int x, int y, int width, int height, qboolean flipx, qboolean flipy, qboolean flipdiagonal, qboolean jpeg, qboolean gammacorrect)
 {
        int     indices[3] = {0,1,2};
        qboolean ret;
@@ -1201,6 +1634,17 @@ qboolean SCR_ScreenShot(char *filename, qbyte *buffer1, qbyte *buffer2, qbyte *b
        qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer1);
        CHECKGLERROR
 
+       if (scr_screenshot_gamma.value != 1 && gammacorrect)
+       {
+               int i;
+               double igamma = 1.0 / scr_screenshot_gamma.value;
+               unsigned char ramp[256];
+               for (i = 0;i < 256;i++)
+                       ramp[i] = (unsigned char) (pow(i * (1.0 / 255.0), igamma) * 255.0);
+               for (i = 0;i < width*height*3;i++)
+                       buffer1[i] = ramp[buffer1[i]];
+       }
+
        Image_CopyMux (buffer2, buffer1, width, height, flipx, flipy, flipdiagonal, 3, 3, indices);
 
        if (jpeg)
@@ -1218,7 +1662,11 @@ void R_ClearScreen(void)
        if (r_render.integer)
        {
                // clear to black
-               qglClearColor(0,0,0,0);CHECKGLERROR
+               if (fogenabled)
+                       qglClearColor(fogcolor[0],fogcolor[1],fogcolor[2],0);
+               else
+                       qglClearColor(0,0,0,0);
+               CHECKGLERROR
                qglClearDepth(1);CHECKGLERROR
                if (gl_stencil)
                {
@@ -1249,7 +1697,146 @@ CalcFov
 float CalcFov (float fov_x, float width, float height)
 {
        // calculate vision size and alter by aspect, then convert back to angle
-       return atan (((height/width)/vid_pixelaspect.value)*tan(fov_x/360.*M_PI))*360./M_PI; 
+       return atan (((height/width)/vid_pixelaspect.value)*tan(fov_x/360.0*M_PI))*360.0/M_PI;
+}
+
+int r_stereo_side;
+
+void SCR_DrawScreen (void)
+{
+       for (r_showtrispass = 0;r_showtrispass <= (r_showtris.value > 0);r_showtrispass++)
+       {
+               R_Mesh_Start();
+
+               R_TimeReport("setup");
+
+               if (r_showtrispass)
+               {
+                       rmeshstate_t m;
+                       r_showtrispass = 0;
+                       GL_BlendFunc(GL_ONE, GL_ONE);
+                       GL_DepthTest(GL_FALSE);
+                       GL_DepthMask(GL_FALSE);
+                       memset(&m, 0, sizeof(m));
+                       R_Mesh_State(&m);
+                       //qglEnable(GL_LINE_SMOOTH);
+                       GL_ShowTrisColor(0.2,0.2,0.2,1);
+                       r_showtrispass = 1;
+               }
+
+               if (cls.signon == SIGNONS)
+               {
+                       float size;
+
+                       size = scr_viewsize.value * (1.0 / 100.0);
+                       size = min(size, 1);
+
+                       if (r_stereo_sidebyside.integer)
+                       {
+                               r_refdef.width = vid.width * size / 2.5;
+                               r_refdef.height = vid.height * size / 2.5 * (1 - bound(0, r_letterbox.value, 100) / 100);
+                               r_refdef.x = (vid.width - r_refdef.width * 2.5) * 0.5;
+                               r_refdef.y = (vid.height - r_refdef.height)/2;
+                               if (r_stereo_side)
+                                       r_refdef.x += r_refdef.width * 1.5;
+                       }
+                       else
+                       {
+                               r_refdef.width = vid.width * size;
+                               r_refdef.height = vid.height * size * (1 - bound(0, r_letterbox.value, 100) / 100);
+                               r_refdef.x = (vid.width - r_refdef.width)/2;
+                               r_refdef.y = (vid.height - r_refdef.height)/2;
+                       }
+
+                       // LordHavoc: viewzoom (zoom in for sniper rifles, etc)
+                       r_refdef.fov_x = scr_fov.value * r_refdef.fovscale_x;
+                       r_refdef.fov_y = CalcFov (scr_fov.value, r_refdef.width, r_refdef.height) * r_refdef.fovscale_y;
+
+                       R_RenderView();
+
+                       if (scr_zoomwindow.integer)
+                       {
+                               float sizex = bound(10, scr_zoomwindow_viewsizex.value, 100) / 100.0;
+                               float sizey = bound(10, scr_zoomwindow_viewsizey.value, 100) / 100.0;
+                               r_refdef.width = vid.width * sizex;
+                               r_refdef.height = vid.height * sizey;
+                               r_refdef.x = (vid.width - r_refdef.width)/2;
+                               r_refdef.y = 0;
+                               r_refdef.fov_x = scr_zoomwindow_fov.value * r_refdef.fovscale_x;
+                               r_refdef.fov_y = CalcFov(scr_zoomwindow_fov.value, r_refdef.width, r_refdef.height) * r_refdef.fovscale_y;
+
+                               R_RenderView();
+                       }
+               }
+
+               if (!r_stereo_sidebyside.integer)
+               {
+                       r_refdef.width = vid.width;
+                       r_refdef.height = vid.height;
+                       r_refdef.x = 0;
+                       r_refdef.y = 0;
+               }
+
+               // draw 2D stuff
+               R_DrawQueue();
+
+               R_Mesh_Finish();
+
+               R_TimeReport("meshfinish");
+       }
+       r_showtrispass = 0;
+       //qglDisable(GL_LINE_SMOOTH);
+}
+
+void SCR_UpdateLoadingScreen (void)
+{
+       float x, y;
+       cachepic_t *pic;
+       rmeshstate_t m;
+       // don't do anything if not initialized yet
+       if (vid_hidden)
+               return;
+       r_showtrispass = 0;
+       VID_UpdateGamma(false);
+       qglViewport(0, 0, vid.width, vid.height);
+       //qglDisable(GL_SCISSOR_TEST);
+       //qglDepthMask(1);
+       qglColorMask(1,1,1,1);
+       //qglClearColor(0,0,0,0);
+       //qglClear(GL_COLOR_BUFFER_BIT);
+       //qglCullFace(GL_FRONT);
+       //qglDisable(GL_CULL_FACE);
+       //R_ClearScreen();
+       R_Textures_Frame();
+       GL_SetupView_Mode_Ortho(0, 0, vid_conwidth.integer, vid_conheight.integer, -10, 100);
+       R_Mesh_Start();
+       R_Mesh_Matrix(&r_identitymatrix);
+       // draw the loading plaque
+       pic = Draw_CachePic("gfx/loading", false);
+       x = (vid_conwidth.integer - pic->width)/2;
+       y = (vid_conheight.integer - pic->height)/2;
+       GL_Color(1,1,1,1);
+       GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+       GL_DepthTest(false);
+       memset(&m, 0, sizeof(m));
+       m.pointer_vertex = varray_vertex3f;
+       m.pointer_texcoord[0] = varray_texcoord2f[0];
+       m.tex[0] = R_GetTexture(pic->tex);
+       R_Mesh_State(&m);
+       varray_vertex3f[0] = varray_vertex3f[9] = x;
+       varray_vertex3f[1] = varray_vertex3f[4] = y;
+       varray_vertex3f[3] = varray_vertex3f[6] = x + pic->width;
+       varray_vertex3f[7] = varray_vertex3f[10] = y + pic->height;
+       varray_texcoord2f[0][0] = 0;varray_texcoord2f[0][1] = 0;
+       varray_texcoord2f[0][2] = 1;varray_texcoord2f[0][3] = 0;
+       varray_texcoord2f[0][4] = 1;varray_texcoord2f[0][5] = 1;
+       varray_texcoord2f[0][6] = 0;varray_texcoord2f[0][7] = 1;
+       GL_LockArrays(0, 4);
+       R_Mesh_Draw(0, 4, 2, polygonelements);
+       GL_LockArrays(0, 0);
+       R_Mesh_Finish();
+       // refresh
+       VID_Finish();
 }
 
 /*
@@ -1262,137 +1849,87 @@ text to the screen.
 */
 void SCR_UpdateScreen (void)
 {
-       if (gl_delayfinish.integer)
-       {
-               R_Mesh_Finish();
-               R_TimeReport("meshfinish");
-               VID_Finish();
-               R_TimeReport("finish");
-       }
-
-       R_Mesh_Start();
+       if (vid_hidden)
+               return;
 
        if (r_textureunits.integer > gl_textureunits)
                Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
        if (r_textureunits.integer < 1)
                Cvar_SetValueQuick(&r_textureunits, 1);
 
-       if (gl_combine.integer && (!gl_combine_extension || r_textureunits.integer < 2))
+       if (gl_combine.integer && !gl_combine_extension)
                Cvar_SetValueQuick(&gl_combine, 0);
 
-showtris:
-       R_TimeReport("setup");
-
-       R_ClearScreen();
+       CHECKGLERROR
+       qglViewport(0, 0, vid.width, vid.height);
+       qglDisable(GL_SCISSOR_TEST);
+       qglDepthMask(1);
+       qglColorMask(1,1,1,1);
+       qglClearColor(0,0,0,0);
+       qglClear(GL_COLOR_BUFFER_BIT);
+       CHECKGLERROR
 
        R_TimeReport("clear");
 
-       if (scr_conlines < vid.conheight && cls.signon == SIGNONS)
-       {
-               float size;
-               int contents;
-
-               // bound viewsize
-               if (scr_viewsize.value < 30)
-                       Cvar_Set ("viewsize","30");
-               if (scr_viewsize.value > 120)
-                       Cvar_Set ("viewsize","120");
-               
-               // bound field of view
-               if (scr_fov.value < 1)
-                       Cvar_Set ("fov","1");
-               if (scr_fov.value > 170)
-                       Cvar_Set ("fov","170");
-       
-               // intermission is always full screen
-               if (cl.intermission)
-               {
-                       size = 1;
-                       sb_lines = 0;
-               }
-               else
-               {
-                       if (scr_viewsize.value >= 120)
-                               sb_lines = 0;           // no status bar at all
-                       else if (scr_viewsize.value >= 110)
-                               sb_lines = 24;          // no inventory
-                       else
-                               sb_lines = 24+16+8;
-                       size = scr_viewsize.value * (1.0 / 100.0);
-                       size = min(size, 1);
-               }
-       
-               r_refdef.width = vid.realwidth * size;
-               r_refdef.height = vid.realheight * size;
-               r_refdef.x = (vid.realwidth - r_refdef.width)/2;
-               r_refdef.y = (vid.realheight - r_refdef.height)/2;
-       
-               // LordHavoc: viewzoom (zoom in for sniper rifles, etc)
-               r_refdef.fov_x = scr_fov.value * cl.viewzoom;
-               r_refdef.fov_y = CalcFov (r_refdef.fov_x, r_refdef.width, r_refdef.height);
+       if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer || r_stereo_sidebyside.integer)
+       {
+               matrix4x4_t originalmatrix = r_refdef.viewentitymatrix;
+               r_refdef.viewentitymatrix.m[0][3] = originalmatrix.m[0][3] + r_stereo_separation.value * -0.5f * r_refdef.viewentitymatrix.m[0][1];
+               r_refdef.viewentitymatrix.m[1][3] = originalmatrix.m[1][3] + r_stereo_separation.value * -0.5f * r_refdef.viewentitymatrix.m[1][1];
+               r_refdef.viewentitymatrix.m[2][3] = originalmatrix.m[2][3] + r_stereo_separation.value * -0.5f * r_refdef.viewentitymatrix.m[2][1];
 
-               if (r_waterwarp.value > 0)
+               if (r_stereo_sidebyside.integer)
+                       r_stereo_side = 0;
+
+               if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer)
                {
-                       if (cl.worldmodel)
-                       {
-                               Mod_CheckLoaded(cl.worldmodel);
-                               contents = CL_PointSuperContents(r_vieworigin);
-                               if (contents & SUPERCONTENTS_LIQUIDSMASK)
-                               {
-                                       r_refdef.fov_x *= 1 - (((sin(cl.time * 4.7) + 1) * 0.015) * r_waterwarp.value);
-                                       r_refdef.fov_y *= 1 - (((sin(cl.time * 3.0) + 1) * 0.015) * r_waterwarp.value);
-                               }
-                       }
+                       r_refdef.colormask[0] = 1;
+                       r_refdef.colormask[1] = 0;
+                       r_refdef.colormask[2] = 0;
                }
 
-               R_RenderView();
+               SCR_DrawScreen();
 
-               if (scr_zoomwindow.integer)
-               {
-                       float sizex = bound(10, scr_zoomwindow_viewsizex.value, 100) / 100.0;
-                       float sizey = bound(10, scr_zoomwindow_viewsizey.value, 100) / 100.0;
-                       r_refdef.width = vid.realwidth * sizex;
-                       r_refdef.height = vid.realheight * sizey;
-                       r_refdef.x = (vid.realwidth - r_refdef.width)/2;
-                       r_refdef.y = 0;
-                       r_refdef.fov_x = scr_zoomwindow_fov.value;
-                       r_refdef.fov_y = CalcFov(r_refdef.fov_x, r_refdef.width, r_refdef.height);
+               r_refdef.viewentitymatrix.m[0][3] = originalmatrix.m[0][3] + r_stereo_separation.value * 0.5f * r_refdef.viewentitymatrix.m[0][1];
+               r_refdef.viewentitymatrix.m[1][3] = originalmatrix.m[1][3] + r_stereo_separation.value * 0.5f * r_refdef.viewentitymatrix.m[1][1];
+               r_refdef.viewentitymatrix.m[2][3] = originalmatrix.m[2][3] + r_stereo_separation.value * 0.5f * r_refdef.viewentitymatrix.m[2][1];
 
-                       R_RenderView();
-               }
-       }
+               if (r_stereo_sidebyside.integer)
+                       r_stereo_side = 1;
 
-       // draw 2D stuff
-       R_DrawQueue();
+               if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer)
+               {
+                       r_refdef.colormask[0] = 0;
+                       r_refdef.colormask[1] = r_stereo_redcyan.integer || r_stereo_redgreen.integer;
+                       r_refdef.colormask[2] = r_stereo_redcyan.integer || r_stereo_redblue.integer;
+               }
 
-       if (r_showtrispass)
-               r_showtrispass = false;
-       else if (r_showtris.value > 0)
-       {
-               rmeshstate_t m;
-               GL_BlendFunc(GL_ONE, GL_ONE);
-               GL_DepthTest(GL_FALSE);
-               GL_DepthMask(GL_FALSE);
-               memset(&m, 0, sizeof(m));
-               R_Mesh_State(&m);
-               r_showtrispass = true;
-               GL_ShowTrisColor(0.2,0.2,0.2,1);
-               goto showtris;
-       }
+               SCR_DrawScreen();
 
-       if (gl_delayfinish.integer)
-       {
-               // tell driver to commit it's partially full geometry queue to the rendering queue
-               // (this doesn't wait for the commands themselves to complete)
-               qglFlush();
+               r_refdef.viewentitymatrix = originalmatrix;
        }
        else
        {
-               R_Mesh_Finish();
-               R_TimeReport("meshfinish");
-               VID_Finish();
-               R_TimeReport("finish");
+               r_showtrispass = false;
+               SCR_DrawScreen();
+
+               if (r_showtris.value > 0)
+               {
+                       rmeshstate_t m;
+                       GL_BlendFunc(GL_ONE, GL_ONE);
+                       GL_DepthTest(GL_FALSE);
+                       GL_DepthMask(GL_FALSE);
+                       memset(&m, 0, sizeof(m));
+                       R_Mesh_State(&m);
+                       r_showtrispass = true;
+                       GL_ShowTrisColor(0.2,0.2,0.2,1);
+                       SCR_DrawScreen();
+                       r_showtrispass = false;
+               }
        }
+
+       VID_Finish();
+       R_TimeReport("finish");
 }
 
 
@@ -1400,12 +1937,16 @@ showtris:
 // dynamic vertex array buffer subsystem
 //===========================================================================
 
+// FIXME: someday this should be dynamically allocated and resized?
 float varray_vertex3f[65536*3];
+float varray_svector3f[65536*3];
+float varray_tvector3f[65536*3];
+float varray_normal3f[65536*3];
 float varray_color4f[65536*4];
 float varray_texcoord2f[4][65536*2];
 float varray_texcoord3f[4][65536*3];
-float varray_normal3f[65536*3];
 int earray_element3i[65536];
+float varray_vertex3f2[65536*3];
 
 //===========================================================================
 // vertex array caching subsystem
@@ -1511,7 +2052,7 @@ int R_Mesh_CacheArray(rcachearrayrequest_t *r)
        //R_Mesh_CacheArray_ValidateState(3);
        // calculate a hashindex to choose a cache chain
        r->data = NULL;
-       hashindex = CRC_Block((void *)r, sizeof(*r)) % RCACHEARRAY_HASHSIZE;
+       hashindex = CRC_Block((qbyte *)r, sizeof(*r)) % RCACHEARRAY_HASHSIZE;
 
        // is it already cached?
        for (lhead = &r_mesh_rcachechain[hashindex], l = lhead->next;l != lhead;l = l->next)