]> de.git.xonotic.org Git - xonotic/darkplaces.git/blobdiff - gl_backend.c
huge audit of dprints throughout engine, all notices of successfully
[xonotic/darkplaces.git] / gl_backend.c
index 286b5452f87b03788db5f949fe03264d7365903d..fefdf7f3db32fa883290f9ca0508a9d607e187ac 100644 (file)
@@ -12,7 +12,12 @@ cvar_t r_render = {0, "r_render", "1", "enables rendering calls (you want this o
 cvar_t r_waterwarp = {CVAR_SAVE, "r_waterwarp", "1", "warp view while underwater"};
 cvar_t gl_polyblend = {CVAR_SAVE, "gl_polyblend", "1", "tints view while underwater, hurt, etc"};
 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1", "enables OpenGL dithering (16bit looks bad with this off)"};
-cvar_t gl_lockarrays = {0, "gl_lockarrays", "1", "enables use of glLockArraysEXT, may cause glitches with some broken drivers"};
+cvar_t gl_lockarrays = {0, "gl_lockarrays", "0", "enables use of glLockArraysEXT, may cause glitches with some broken drivers, and may be slower than normal"};
+cvar_t gl_lockarrays_minimumvertices = {0, "gl_lockarrays_minimumvertices", "1", "minimum number of vertices required for use of glLockArraysEXT, setting this too low may reduce performance"};
+cvar_t gl_vbo = {CVAR_SAVE, "gl_vbo", "1", "make use of GL_ARB_vertex_buffer_object extension to store static geometry in video memory for faster rendering"};
+
+cvar_t v_flipped = {0, "v_flipped", "0", "mirror the screen (poor man's left handed mode)"};
+qboolean v_flipped_state = false;
 
 int gl_maxdrawrangeelementsvertices;
 int gl_maxdrawrangeelementsindices;
@@ -142,9 +147,24 @@ void GL_Backend_FreeArrays(void)
 {
 }
 
+void GL_VBOStats_f(void)
+{
+       GL_Mesh_ListVBOs(true);
+}
+
+typedef struct gl_bufferobjectinfo_s
+{
+       int target;
+       int object;
+       size_t size;
+       char name[MAX_QPATH];
+}
+gl_bufferobjectinfo_t;
+
+memexpandablearray_t gl_bufferobjectinfoarray;
+
 static void gl_backend_start(void)
 {
-       Con_Print("OpenGL Backend starting...\n");
        CHECKGLERROR
 
        if (qglDrawRangeElements != NULL)
@@ -154,7 +174,7 @@ static void gl_backend_start(void)
                CHECKGLERROR
                qglGetIntegerv(GL_MAX_ELEMENTS_INDICES, &gl_maxdrawrangeelementsindices);
                CHECKGLERROR
-               Con_Printf("glDrawRangeElements detected (max vertices %i, max indices %i)\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
+               Con_DPrintf("GL_MAX_ELEMENTS_VERTICES = %i\nGL_MAX_ELEMENTS_INDICES = %i\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
        }
 
        backendunits = bound(1, gl_textureunits, MAX_TEXTUREUNITS);
@@ -167,18 +187,18 @@ static void gl_backend_start(void)
                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);
+               Con_DPrintf("GLSL shader support detected: texture units = %i texenv, %i image, %i array\n", backendunits, backendimageunits, backendarrayunits);
                backendimageunits = bound(1, backendimageunits, MAX_TEXTUREUNITS);
                backendarrayunits = bound(1, backendarrayunits, MAX_TEXTUREUNITS);
        }
-       else if (backendunits > 1)
-               Con_Printf("multitexture detected: texture units = %i\n", backendunits);
        else
-               Con_Printf("singletexture\n");
+               Con_DPrintf("GL_MAX_TEXTUREUNITS = %i\n", backendunits);
 
        GL_Backend_AllocArrays();
 
-       Con_Printf("OpenGL backend started.\n");
+       Mem_ExpandableArray_NewArray(&gl_bufferobjectinfoarray, r_main_mempool, sizeof(gl_bufferobjectinfo_t), 128);
+
+       Con_DPrintf("OpenGL backend started.\n");
 
        CHECKGLERROR
 
@@ -192,7 +212,9 @@ static void gl_backend_shutdown(void)
        backendarrayunits = 0;
        backendactive = false;
 
-       Con_Print("OpenGL Backend shutting down\n");
+       Con_DPrint("OpenGL Backend shutting down\n");
+
+       Mem_ExpandableArray_FreeArray(&gl_bufferobjectinfoarray);
 
        GL_Backend_FreeArrays();
 }
@@ -225,8 +247,11 @@ void gl_backend_init(void)
        Cvar_RegisterVariable(&r_render);
        Cvar_RegisterVariable(&r_waterwarp);
        Cvar_RegisterVariable(&gl_polyblend);
+       Cvar_RegisterVariable(&v_flipped);
        Cvar_RegisterVariable(&gl_dither);
        Cvar_RegisterVariable(&gl_lockarrays);
+       Cvar_RegisterVariable(&gl_lockarrays_minimumvertices);
+       Cvar_RegisterVariable(&gl_vbo);
        Cvar_RegisterVariable(&gl_paranoid);
        Cvar_RegisterVariable(&gl_printcheckerror);
 #ifdef NORENDER
@@ -237,27 +262,45 @@ void gl_backend_init(void)
        Cvar_RegisterVariable(&gl_mesh_testarrayelement);
        Cvar_RegisterVariable(&gl_mesh_testmanualfeeding);
 
+       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");
+
        R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
 }
 
+void GL_SetMirrorState(qboolean state);
+
 void GL_SetupView_Orientation_Identity (void)
 {
        backend_viewmatrix = identitymatrix;
+       GL_SetMirrorState(false);
        memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
 }
 
-void GL_SetupView_Orientation_FromEntity(matrix4x4_t *matrix)
+void GL_SetupView_Orientation_FromEntity(const matrix4x4_t *matrix)
 {
        matrix4x4_t tempmatrix, basematrix;
-       Matrix4x4_Invert_Simple(&tempmatrix, matrix);
+       Matrix4x4_Invert_Full(&tempmatrix, matrix);
        Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
        Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
        Matrix4x4_Concat(&backend_viewmatrix, &basematrix, &tempmatrix);
+
+       GL_SetMirrorState(v_flipped.integer);
+       if(v_flipped_state)
+       {
+               Matrix4x4_Transpose(&basematrix, &backend_viewmatrix);
+               Matrix4x4_ConcatScale3(&basematrix, -1, 1, 1);
+               Matrix4x4_Transpose(&backend_viewmatrix, &basematrix);
+       }
+
        //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[2], 1, 0, 0);
        //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[0], 0, 1, 0);
        //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[1], 0, 0, 1);
        //Matrix4x4_ConcatTranslate(&backend_viewmatrix, -origin[0], -origin[1], -origin[2]);
+
+       // force an update of the model matrix by copying it off, resetting it, and then calling the R_Mesh_Matrix function with it
+       tempmatrix = backend_modelmatrix;
        memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
+       R_Mesh_Matrix(&tempmatrix);
 }
 
 void GL_SetupView_Mode_Perspective (double frustumx, double frustumy, double zNear, double zFar)
@@ -326,12 +369,73 @@ void GL_SetupView_Mode_Ortho (double x1, double y1, double x2, double y2, double
        CHECKGLERROR
 }
 
+void GL_SetupView_ApplyCustomNearClipPlane(double normalx, double normaly, double normalz, double dist)
+{
+       double matrix[16];
+       double q[4];
+       double d;
+       float clipPlane[4], v3[3], v4[3];
+       float normal[3];
+
+       // This is Olique Depth Projection from http://www.terathon.com/code/oblique.php
+       // modified to fit in this codebase.
+
+       VectorSet(normal, normalx, normaly, normalz);
+       Matrix4x4_Transform3x3(&backend_viewmatrix, normal, clipPlane);
+       VectorScale(normal, dist, v3);
+       Matrix4x4_Transform(&backend_viewmatrix, v3, v4);
+       // FIXME: LordHavoc: I think this can be done more efficiently somehow but I can't remember the technique
+       clipPlane[3] = -DotProduct(v4, clipPlane);
+
+#if 0
+{
+       // testing code for comparing results
+       float clipPlane2[4];
+       VectorCopy4(clipPlane, clipPlane2);
+       R_Mesh_Matrix(&identitymatrix);
+       VectorSet(q, normal[0], normal[1], normal[2], -dist);
+       qglClipPlane(GL_CLIP_PLANE0, q);
+       qglGetClipPlane(GL_CLIP_PLANE0, q);
+       VectorCopy4(q, clipPlane);
+}
+#endif
+
+       // Calculate the clip-space corner point opposite the clipping plane
+       // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and
+       // transform it into camera space by multiplying it
+       // by the inverse of the projection matrix
+       Matrix4x4_ToArrayDoubleGL(&backend_projectmatrix, matrix);
+
+       q[0] = ((clipPlane[0] < 0.0f ? -1.0f : clipPlane[0] > 0.0f ? 1.0f : 0.0f) + matrix[8]) / matrix[0];
+       q[1] = ((clipPlane[1] < 0.0f ? -1.0f : clipPlane[1] > 0.0f ? 1.0f : 0.0f) + matrix[9]) / matrix[5];
+       q[2] = -1.0f;
+       q[3] = (1.0f + matrix[10]) / matrix[14];
+
+       // Calculate the scaled plane vector
+       d = 2.0f / DotProduct4(clipPlane, q);
+
+       // Replace the third row of the projection matrix
+       matrix[2] = clipPlane[0] * d;
+       matrix[6] = clipPlane[1] * d;
+       matrix[10] = clipPlane[2] * d + 1.0f;
+       matrix[14] = clipPlane[3] * d;
+
+       // Load it back into OpenGL
+       qglMatrixMode(GL_PROJECTION);CHECKGLERROR
+       qglLoadMatrixd(matrix);CHECKGLERROR
+       qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
+       CHECKGLERROR
+       Matrix4x4_FromArrayDoubleGL(&backend_projectmatrix, matrix);
+}
+
 typedef struct gltextureunit_s
 {
+       const void *pointer_texcoord;
+       size_t pointer_texcoord_offset;
+       int pointer_texcoord_buffer;
        int t1d, t2d, t3d, tcubemap;
        int arrayenabled;
        unsigned int arraycomponents;
-       const void *pointer_texcoord;
        int rgbscale, alphascale;
        int combinergb, combinealpha;
        // FIXME: add more combine stuff
@@ -351,6 +455,8 @@ static struct gl_state_s
        GLboolean depthmask;
        int colormask; // stored as bottom 4 bits: r g b a (3 2 1 0 order)
        int depthtest;
+       float depthrange[2];
+       float polygonoffset[2];
        int alphatest;
        int scissortest;
        unsigned int unit;
@@ -359,11 +465,40 @@ static struct gl_state_s
        float color4f[4];
        int lockrange_first;
        int lockrange_count;
+       int vertexbufferobject;
+       int elementbufferobject;
+       qboolean pointer_color_enabled;
        const void *pointer_vertex;
        const void *pointer_color;
+       size_t pointer_vertex_offset;
+       size_t pointer_color_offset;
+       int pointer_vertex_buffer;
+       int pointer_color_buffer;
 }
 gl_state;
 
+static void GL_BindVBO(int bufferobject)
+{
+       if (gl_state.vertexbufferobject != bufferobject)
+       {
+               gl_state.vertexbufferobject = bufferobject;
+               CHECKGLERROR
+               qglBindBufferARB(GL_ARRAY_BUFFER_ARB, bufferobject);
+               CHECKGLERROR
+       }
+}
+
+static void GL_BindEBO(int bufferobject)
+{
+       if (gl_state.elementbufferobject != bufferobject)
+       {
+               gl_state.elementbufferobject = bufferobject;
+               CHECKGLERROR
+               qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, bufferobject);
+               CHECKGLERROR
+       }
+}
+
 void GL_SetupTextureState(void)
 {
        unsigned int i;
@@ -381,6 +516,8 @@ void GL_SetupTextureState(void)
                unit->arrayenabled = false;
                unit->arraycomponents = 0;
                unit->pointer_texcoord = NULL;
+               unit->pointer_texcoord_buffer = 0;
+               unit->pointer_texcoord_offset = 0;
                unit->rgbscale = 1;
                unit->alphascale = 1;
                unit->combinergb = GL_MODULATE;
@@ -407,6 +544,7 @@ void GL_SetupTextureState(void)
        for (i = 0;i < backendarrayunits;i++)
        {
                GL_ClientActiveTexture(i);
+               GL_BindVBO(0);
                qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), NULL);CHECKGLERROR
                qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
        }
@@ -469,10 +607,10 @@ void GL_Backend_ResetState(void)
        gl_state.color4f[0] = gl_state.color4f[1] = gl_state.color4f[2] = gl_state.color4f[3] = 1;
        gl_state.lockrange_first = 0;
        gl_state.lockrange_count = 0;
-       gl_state.pointer_vertex = NULL;
-       gl_state.pointer_color = NULL;
-       gl_state.cullface = GL_FRONT; // quake is backwards, this culls back faces
+       gl_state.cullface = v_flipped_state ? GL_BACK : GL_FRONT; // quake is backwards, this culls back faces
        gl_state.cullfaceenable = true;
+       gl_state.polygonoffset[0] = 0;
+       gl_state.polygonoffset[1] = 0;
 
        CHECKGLERROR
 
@@ -486,6 +624,13 @@ void GL_Backend_ResetState(void)
        qglDepthFunc(GL_LEQUAL);CHECKGLERROR
        qglEnable(GL_DEPTH_TEST);CHECKGLERROR
        qglDepthMask(gl_state.depthmask);CHECKGLERROR
+       qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
+
+       if (gl_support_arb_vertex_buffer_object)
+       {
+               qglBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
+               qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
+       }
 
        qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), NULL);CHECKGLERROR
        qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
@@ -589,31 +734,70 @@ void GL_DepthTest(int state)
        }
 }
 
+void GL_DepthRange(float nearfrac, float farfrac)
+{
+       if (gl_state.depthrange[0] != nearfrac || gl_state.depthrange[1] != farfrac)
+       {
+               gl_state.depthrange[0] = nearfrac;
+               gl_state.depthrange[1] = farfrac;
+               qglDepthRange(nearfrac, farfrac);
+       }
+}
+
+void GL_PolygonOffset(float planeoffset, float depthoffset)
+{
+       if (gl_state.polygonoffset[0] != planeoffset || gl_state.polygonoffset[1] != depthoffset)
+       {
+               gl_state.polygonoffset[0] = planeoffset;
+               gl_state.polygonoffset[1] = depthoffset;
+               qglPolygonOffset(planeoffset, depthoffset);
+       }
+}
+
+void GL_SetMirrorState(qboolean state)
+{
+       if(!state != !v_flipped_state)
+       {
+               // change cull face mode!
+               if(gl_state.cullface == GL_BACK)
+                       qglCullFace((gl_state.cullface = GL_FRONT));
+               else if(gl_state.cullface == GL_FRONT)
+                       qglCullFace((gl_state.cullface = GL_BACK));
+       }
+       v_flipped_state = state;
+}
+
 void GL_CullFace(int state)
 {
-       if (gl_state.cullface != state)
+       CHECKGLERROR
+
+       if(v_flipped_state)
        {
-               CHECKGLERROR
-               if (state != GL_NONE)
+               if(state == GL_FRONT)
+                       state = GL_BACK;
+               else if(state == GL_BACK)
+                       state = GL_FRONT;
+       }
+
+       if (state != GL_NONE)
+       {
+               if (!gl_state.cullfaceenable)
                {
-                       if (!gl_state.cullfaceenable)
-                       {
-                               gl_state.cullfaceenable = true;
-                               qglEnable(GL_CULL_FACE);CHECKGLERROR
-                       }
-                       if (gl_state.cullface != state)
-                       {
-                               gl_state.cullface = state;
-                               qglCullFace(state);CHECKGLERROR
-                       }
+                       gl_state.cullfaceenable = true;
+                       qglEnable(GL_CULL_FACE);CHECKGLERROR
                }
-               else
+               if (gl_state.cullface != state)
                {
-                       if (gl_state.cullfaceenable)
-                       {
-                               gl_state.cullfaceenable = false;
-                               qglDisable(GL_CULL_FACE);CHECKGLERROR
-                       }
+                       gl_state.cullface = state;
+                       qglCullFace(gl_state.cullface);CHECKGLERROR
+               }
+       }
+       else
+       {
+               if (gl_state.cullfaceenable)
+               {
+                       gl_state.cullfaceenable = false;
+                       qglDisable(GL_CULL_FACE);CHECKGLERROR
                }
        }
 }
@@ -648,7 +832,7 @@ void GL_ColorMask(int r, int g, int b, int a)
 
 void GL_Color(float cr, float cg, float cb, float ca)
 {
-       if (gl_state.pointer_color || gl_state.color4f[0] != cr || gl_state.color4f[1] != cg || gl_state.color4f[2] != cb || gl_state.color4f[3] != ca)
+       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)
        {
                gl_state.color4f[0] = cr;
                gl_state.color4f[1] = cg;
@@ -662,6 +846,11 @@ void GL_Color(float cr, float cg, float cb, float ca)
 
 void GL_LockArrays(int first, int count)
 {
+       if (count < gl_lockarrays_minimumvertices.integer)
+       {
+               first = 0;
+               count = 0;
+       }
        if (gl_state.lockrange_count != count || gl_state.lockrange_first != first)
        {
                if (gl_state.lockrange_count)
@@ -715,9 +904,9 @@ void GL_TransformToScreen(const vec4_t in, vec4_t out)
        Matrix4x4_Transform4 (&backend_viewmatrix, in, temp);
        Matrix4x4_Transform4 (&backend_projectmatrix, temp, out);
        iw = 1.0f / out[3];
-       out[0] = r_view.x + (out[0] * iw + 1.0f) * r_view.width * 0.5f;
-       out[1] = r_view.y + r_view.height - (out[1] * iw + 1.0f) * r_view.height * 0.5f;
-       out[2] = r_view.z + (out[2] * iw + 1.0f) * r_view.depth * 0.5f;
+       out[0] = r_refdef.view.x + (out[0] * iw + 1.0f) * r_refdef.view.width * 0.5f;
+       out[1] = r_refdef.view.y + r_refdef.view.height - (out[1] * iw + 1.0f) * r_refdef.view.height * 0.5f;
+       out[2] = r_refdef.view.z + (out[2] * iw + 1.0f) * r_refdef.view.depth * 0.5f;
 }
 
 // called at beginning of frame
@@ -733,108 +922,80 @@ 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)
+qboolean GL_Backend_CompileShader(int programobject, GLenum shadertypeenum, const char *shadertype, int numstrings, const char **strings)
 {
-       GLint vertexshadercompiled, fragmentshadercompiled, programlinked;
-       GLuint vertexshaderobject, fragmentshaderobject, programobject = 0;
+       int shaderobject;
+       int shadercompiled;
        char compilelog[MAX_INPUTLINE];
+       shaderobject = qglCreateShaderObjectARB(shadertypeenum);CHECKGLERROR
+       if (!shaderobject)
+               return false;
+       qglShaderSourceARB(shaderobject, numstrings, strings, NULL);CHECKGLERROR
+       qglCompileShaderARB(shaderobject);CHECKGLERROR
+       qglGetObjectParameterivARB(shaderobject, GL_OBJECT_COMPILE_STATUS_ARB, &shadercompiled);CHECKGLERROR
+       qglGetInfoLogARB(shaderobject, sizeof(compilelog), NULL, compilelog);CHECKGLERROR
+       if (compilelog[0] && developer.integer > 0)
+       {
+               int i, j, pretextlines = 0;
+               for (i = 0;i < numstrings - 1;i++)
+                       for (j = 0;strings[i][j];j++)
+                               if (strings[i][j] == '\n')
+                                       pretextlines++;
+               Con_DPrintf("%s shader compile log:\n%s\n(line offset for any above warnings/errors: %i)\n", shadertype, compilelog, pretextlines);
+       }
+       if (!shadercompiled)
+       {
+               qglDeleteObjectARB(shaderobject);CHECKGLERROR
+               return false;
+       }
+       qglAttachObjectARB(programobject, shaderobject);CHECKGLERROR
+       qglDeleteObjectARB(shaderobject);CHECKGLERROR
+       return true;
+}
+
+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)
+{
+       GLint programlinked;
+       GLuint programobject = 0;
+       char linklog[MAX_INPUTLINE];
        CHECKGLERROR
 
        programobject = qglCreateProgramObjectARB();CHECKGLERROR
        if (!programobject)
                return 0;
 
-       if (developer.integer >= 100)
-       {
-               int i;
-               Con_Printf("Compiling shader:\n");
-               if (vertexstrings_count)
-               {
-                       Con_Printf("------ VERTEX SHADER ------\n");
-                       for (i = 0;i < vertexstrings_count;i++)
-                               Con_Print(vertexstrings_list[i]);
-                       Con_Print("\n");
-               }
-               if (fragmentstrings_count)
-               {
-                       Con_Printf("------ FRAGMENT SHADER ------\n");
-                       for (i = 0;i < fragmentstrings_count;i++)
-                               Con_Print(fragmentstrings_list[i]);
-                       Con_Print("\n");
-               }
-       }
+       if (vertexstrings_count && !GL_Backend_CompileShader(programobject, GL_VERTEX_SHADER_ARB, "vertex", vertexstrings_count, vertexstrings_list))
+               goto cleanup;
 
-       if (vertexstrings_count)
-       {
-               vertexshaderobject = qglCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);CHECKGLERROR
-               if (!vertexshaderobject)
-               {
-                       qglDeleteObjectARB(programobject);
-                       CHECKGLERROR
-                       return 0;
-               }
-               qglShaderSourceARB(vertexshaderobject, vertexstrings_count, vertexstrings_list, NULL);CHECKGLERROR
-               qglCompileShaderARB(vertexshaderobject);CHECKGLERROR
-               qglGetObjectParameterivARB(vertexshaderobject, GL_OBJECT_COMPILE_STATUS_ARB, &vertexshadercompiled);CHECKGLERROR
-               qglGetInfoLogARB(vertexshaderobject, sizeof(compilelog), NULL, compilelog);CHECKGLERROR
-               if (compilelog[0])
-                       Con_DPrintf("vertex shader compile log:\n%s\n", compilelog);
-               if (!vertexshadercompiled)
-               {
-                       qglDeleteObjectARB(programobject);CHECKGLERROR
-                       qglDeleteObjectARB(vertexshaderobject);CHECKGLERROR
-                       return 0;
-               }
-               qglAttachObjectARB(programobject, vertexshaderobject);CHECKGLERROR
-               qglDeleteObjectARB(vertexshaderobject);CHECKGLERROR
-       }
+#ifdef GL_GEOMETRY_SHADER_ARB
+       if (geometrystrings_count && !GL_Backend_CompileShader(programobject, GL_GEOMETRY_SHADER_ARB, "geometry", geometrystrings_count, geometrystrings_list))
+               goto cleanup;
+#endif
 
-       if (fragmentstrings_count)
-       {
-               fragmentshaderobject = qglCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);CHECKGLERROR
-               if (!fragmentshaderobject)
-               {
-                       qglDeleteObjectARB(programobject);CHECKGLERROR
-                       return 0;
-               }
-               qglShaderSourceARB(fragmentshaderobject, fragmentstrings_count, fragmentstrings_list, NULL);CHECKGLERROR
-               qglCompileShaderARB(fragmentshaderobject);CHECKGLERROR
-               qglGetObjectParameterivARB(fragmentshaderobject, GL_OBJECT_COMPILE_STATUS_ARB, &fragmentshadercompiled);CHECKGLERROR
-               qglGetInfoLogARB(fragmentshaderobject, sizeof(compilelog), NULL, compilelog);CHECKGLERROR
-               if (compilelog[0])
-                       Con_DPrintf("fragment shader compile log:\n%s\n", compilelog);
-               if (!fragmentshadercompiled)
-               {
-                       qglDeleteObjectARB(programobject);CHECKGLERROR
-                       qglDeleteObjectARB(fragmentshaderobject);CHECKGLERROR
-                       return 0;
-               }
-               qglAttachObjectARB(programobject, fragmentshaderobject);CHECKGLERROR
-               qglDeleteObjectARB(fragmentshaderobject);CHECKGLERROR
-       }
+       if (fragmentstrings_count && !GL_Backend_CompileShader(programobject, GL_FRAGMENT_SHADER_ARB, "fragment", fragmentstrings_count, fragmentstrings_list))
+               goto cleanup;
 
        qglLinkProgramARB(programobject);CHECKGLERROR
        qglGetObjectParameterivARB(programobject, GL_OBJECT_LINK_STATUS_ARB, &programlinked);CHECKGLERROR
-       qglGetInfoLogARB(programobject, sizeof(compilelog), NULL, compilelog);CHECKGLERROR
-       if (compilelog[0])
+       qglGetInfoLogARB(programobject, sizeof(linklog), NULL, linklog);CHECKGLERROR
+       if (linklog[0])
        {
-               Con_DPrintf("program link log:\n%s\n", compilelog);
+               Con_DPrintf("program link log:\n%s\n", linklog);
                // 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"))
+               if (strstr(linklog, "fragment shader will run in software"))
                        programlinked = false;
        }
        if (!programlinked)
-       {
-               qglDeleteObjectARB(programobject);CHECKGLERROR
-               return 0;
-       }
-       CHECKGLERROR
+               goto cleanup;
        return programobject;
+cleanup:
+       qglDeleteObjectARB(programobject);CHECKGLERROR
+       return 0;
 }
 
 void GL_Backend_FreeProgram(unsigned int prog)
@@ -860,14 +1021,16 @@ 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 firstvertex, int numvertices, int numtriangles, const int *elements)
+void R_Mesh_Draw(int firstvertex, int numvertices, int numtriangles, const int *elements, int bufferobject, size_t bufferoffset)
 {
        unsigned int numelements = numtriangles * 3;
        if (numvertices < 3 || numtriangles < 1)
        {
-               Con_Printf("R_Mesh_Draw(%d, %d, %d, %08p);\n", firstvertex, numvertices, numtriangles, elements);
+               Con_Printf("R_Mesh_Draw(%d, %d, %d, %8p, %i, %p);\n", firstvertex, numvertices, numtriangles, elements, bufferobject, (void *)bufferoffset);
                return;
        }
+       if (gl_vbo.integer != 1)
+               bufferobject = 0;
        CHECKGLERROR
        r_refdef.stats.meshes++;
        r_refdef.stats.meshes_elements += numelements;
@@ -875,18 +1038,25 @@ void R_Mesh_Draw(int firstvertex, int numvertices, int numtriangles, const int *
        {
                unsigned int i, j, size;
                const int *p;
+               // note: there's no validation done here on buffer objects because it
+               // is somewhat difficult to get at the data, and gl_paranoid can be
+               // used without buffer objects if the need arises
+               // (the data could be gotten using glMapBuffer but it would be very
+               //  slow due to uncachable video memory reads)
                if (!qglIsEnabled(GL_VERTEX_ARRAY))
                        Con_Print("R_Mesh_Draw: vertex array not enabled\n");
                CHECKGLERROR
-               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 (gl_state.pointer_vertex)
+                       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_enabled)
                {
                        if (!qglIsEnabled(GL_COLOR_ARRAY))
                                Con_Print("R_Mesh_Draw: color array set but not enabled\n");
                        CHECKGLERROR
-                       for (j = 0, size = numvertices * 4, p = (int *)((float *)gl_state.pointer_color + firstvertex * 4);j < size;j++, p++)
-                               paranoidblah += *p;
+                       if (gl_state.pointer_color && gl_state.pointer_color_enabled)
+                               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 < backendarrayunits;i++)
                {
@@ -896,8 +1066,9 @@ void R_Mesh_Draw(int firstvertex, int numvertices, int numtriangles, const int *
                                if (!qglIsEnabled(GL_TEXTURE_COORD_ARRAY))
                                        Con_Print("R_Mesh_Draw: texcoord array set but not enabled\n");
                                CHECKGLERROR
-                               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;
+                               if (gl_state.units[i].pointer_texcoord && gl_state.units[i].arrayenabled)
+                                       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 < (unsigned int) numtriangles * 3;i++)
@@ -922,7 +1093,7 @@ void R_Mesh_Draw(int firstvertex, int numvertices, int numtriangles, const int *
                        {
                                for (j = 0;j < backendarrayunits;j++)
                                {
-                                       if (gl_state.units[j].pointer_texcoord)
+                                       if (gl_state.units[j].pointer_texcoord && gl_state.units[j].arrayenabled)
                                        {
                                                if (backendarrayunits > 1)
                                                {
@@ -972,7 +1143,7 @@ void R_Mesh_Draw(int firstvertex, int numvertices, int numtriangles, const int *
                                                }
                                        }
                                }
-                               if (gl_state.pointer_color)
+                               if (gl_state.pointer_color && gl_state.pointer_color_enabled)
                                {
                                        p = ((const GLfloat *)(gl_state.pointer_color)) + elements[i] * 4;
                                        qglColor4f(p[0], p[1], p[2], p[3]);
@@ -996,12 +1167,14 @@ void R_Mesh_Draw(int firstvertex, int numvertices, int numtriangles, const int *
                }
                else if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
                {
-                       qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices, numelements, GL_UNSIGNED_INT, elements);
+                       GL_BindEBO(bufferobject);
+                       qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices, numelements, GL_UNSIGNED_INT, bufferobject ? (void *)bufferoffset : elements);
                        CHECKGLERROR
                }
                else
                {
-                       qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, elements);
+                       GL_BindEBO(bufferobject);
+                       qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, bufferobject ? (void *)bufferoffset : elements);
                        CHECKGLERROR
                }
        }
@@ -1064,6 +1237,76 @@ void R_Mesh_Finish(void)
        qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
 }
 
+int R_Mesh_CreateStaticBufferObject(unsigned int target, void *data, size_t size, const char *name)
+{
+       gl_bufferobjectinfo_t *info;
+       GLuint bufferobject;
+
+       if (!gl_vbo.integer)
+               return 0;
+
+       qglGenBuffersARB(1, &bufferobject);
+       switch(target)
+       {
+       case GL_ELEMENT_ARRAY_BUFFER_ARB: GL_BindEBO(bufferobject);break;
+       case GL_ARRAY_BUFFER_ARB: GL_BindVBO(bufferobject);break;
+       default: Sys_Error("R_Mesh_CreateStaticBufferObject: unknown target type %i\n", target);return 0;
+       }
+       qglBufferDataARB(target, size, data, GL_STATIC_DRAW_ARB);
+
+       info = Mem_ExpandableArray_AllocRecord(&gl_bufferobjectinfoarray);
+       memset(info, 0, sizeof(*info));
+       info->target = target;
+       info->object = bufferobject;
+       info->size = size;
+       strlcpy(info->name, name, sizeof(info->name));
+
+       return (int)bufferobject;
+}
+
+void R_Mesh_DestroyBufferObject(int bufferobject)
+{
+       int i, endindex;
+       gl_bufferobjectinfo_t *info;
+
+       qglDeleteBuffersARB(1, (GLuint *)&bufferobject);
+
+       endindex = Mem_ExpandableArray_IndexRange(&gl_bufferobjectinfoarray);
+       for (i = 0;i < endindex;i++)
+       {
+               info = Mem_ExpandableArray_RecordAtIndex(&gl_bufferobjectinfoarray, i);
+               if (!info)
+                       continue;
+               if (info->object == bufferobject)
+               {
+                       Mem_ExpandableArray_FreeRecord(&gl_bufferobjectinfoarray, (void *)info);
+                       break;
+               }
+       }
+}
+
+void GL_Mesh_ListVBOs(qboolean printeach)
+{
+       int i, endindex;
+       size_t ebocount = 0, ebomemory = 0;
+       size_t vbocount = 0, vbomemory = 0;
+       gl_bufferobjectinfo_t *info;
+       endindex = Mem_ExpandableArray_IndexRange(&gl_bufferobjectinfoarray);
+       for (i = 0;i < endindex;i++)
+       {
+               info = Mem_ExpandableArray_RecordAtIndex(&gl_bufferobjectinfoarray, i);
+               if (!info)
+                       continue;
+               switch(info->target)
+               {
+               case GL_ELEMENT_ARRAY_BUFFER_ARB: ebocount++;ebomemory += info->size;if (printeach) Con_Printf("EBO #%i %s = %i bytes\n", info->object, info->name, (int)info->size);break;
+               case GL_ARRAY_BUFFER_ARB: vbocount++;vbomemory += info->size;if (printeach) Con_Printf("VBO #%i %s = %i bytes\n", info->object, info->name, (int)info->size);break;
+               default: Con_Printf("gl_vbostats: unknown target type %i\n", info->target);break;
+               }
+       }
+       Con_Printf("vertex buffers: %i element buffers totalling %i bytes (%.3f MB), %i vertex buffers totalling %i bytes (%.3f MB), combined %i bytes (%.3fMB)\n", (int)ebocount, (int)ebomemory, ebomemory / 1048576.0, (int)vbocount, (int)vbomemory, vbomemory / 1048576.0, (int)(ebomemory + vbomemory), (ebomemory + vbomemory) / 1048576.0);
+}
+
 void R_Mesh_Matrix(const matrix4x4_t *matrix)
 {
        if (memcmp(matrix, &backend_modelmatrix, sizeof(matrix4x4_t)))
@@ -1077,52 +1320,72 @@ void R_Mesh_Matrix(const matrix4x4_t *matrix)
        }
 }
 
-void R_Mesh_VertexPointer(const float *vertex3f)
+void R_Mesh_VertexPointer(const float *vertex3f, int bufferobject, size_t bufferoffset)
 {
-       if (gl_state.pointer_vertex != vertex3f)
+       if (!gl_vbo.integer)
+               bufferobject = 0;
+       if (gl_state.pointer_vertex != vertex3f || gl_state.pointer_vertex_buffer != bufferobject || gl_state.pointer_vertex_offset != bufferoffset)
        {
                gl_state.pointer_vertex = vertex3f;
+               gl_state.pointer_vertex_buffer = bufferobject;
+               gl_state.pointer_vertex_offset = bufferoffset;
                CHECKGLERROR
-               qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), gl_state.pointer_vertex);
-               CHECKGLERROR
+               GL_BindVBO(bufferobject);
+               qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), bufferobject ? (void *)bufferoffset : vertex3f);CHECKGLERROR
        }
 }
 
-void R_Mesh_ColorPointer(const float *color4f)
+void R_Mesh_ColorPointer(const float *color4f, int bufferobject, size_t bufferoffset)
 {
-       if (gl_state.pointer_color != color4f)
+       // note: this can not rely on bufferobject to decide whether a color array
+       // is supplied, because surfmesh_t shares one vbo for all arrays, which
+       // means that a valid vbo may be supplied even if there is no color array.
+       if (color4f)
        {
-               CHECKGLERROR
-               if (!gl_state.pointer_color)
+               if (!gl_vbo.integer)
+                       bufferobject = 0;
+               // caller wants color array enabled
+               if (!gl_state.pointer_color_enabled)
                {
+                       gl_state.pointer_color_enabled = true;
+                       CHECKGLERROR
                        qglEnableClientState(GL_COLOR_ARRAY);CHECKGLERROR
                }
-               else if (!color4f)
+               if (gl_state.pointer_color != color4f || gl_state.pointer_color_buffer != bufferobject || gl_state.pointer_color_offset != bufferoffset)
+               {
+                       gl_state.pointer_color = color4f;
+                       gl_state.pointer_color_buffer = bufferobject;
+                       gl_state.pointer_color_offset = bufferoffset;
+                       CHECKGLERROR
+                       GL_BindVBO(bufferobject);
+                       qglColorPointer(4, GL_FLOAT, sizeof(float[4]), bufferobject ? (void *)bufferoffset : color4f);CHECKGLERROR
+               }
+       }
+       else
+       {
+               // caller wants color array disabled
+               if (gl_state.pointer_color_enabled)
                {
+                       gl_state.pointer_color_enabled = false;
+                       CHECKGLERROR
                        qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
                        // when color array is on the glColor gets trashed, set it again
                        qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);CHECKGLERROR
                }
-               gl_state.pointer_color = color4f;
-               qglColorPointer(4, GL_FLOAT, sizeof(float[4]), gl_state.pointer_color);CHECKGLERROR
        }
 }
 
-void R_Mesh_TexCoordPointer(unsigned int unitnum, unsigned int numcomponents, const float *texcoord)
+void R_Mesh_TexCoordPointer(unsigned int unitnum, unsigned int numcomponents, const float *texcoord, int bufferobject, size_t bufferoffset)
 {
        gltextureunit_t *unit = gl_state.units + unitnum;
        // update array settings
        CHECKGLERROR
+       // note: there is no need to check bufferobject here because all cases
+       // that involve a valid bufferobject also supply a texcoord array
        if (texcoord)
        {
-               // 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
-               }
+               if (!gl_vbo.integer)
+                       bufferobject = 0;
                // texture array unit is enabled, enable the array
                if (!unit->arrayenabled)
                {
@@ -1130,6 +1393,17 @@ void R_Mesh_TexCoordPointer(unsigned int unitnum, unsigned int numcomponents, co
                        GL_ClientActiveTexture(unitnum);
                        qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
                }
+               // texcoord array
+               if (unit->pointer_texcoord != texcoord || unit->pointer_texcoord_buffer != bufferobject || unit->pointer_texcoord_offset != bufferoffset || unit->arraycomponents != numcomponents)
+               {
+                       unit->pointer_texcoord = texcoord;
+                       unit->pointer_texcoord_buffer = bufferobject;
+                       unit->pointer_texcoord_offset = bufferoffset;
+                       unit->arraycomponents = numcomponents;
+                       GL_ClientActiveTexture(unitnum);
+                       GL_BindVBO(bufferobject);
+                       qglTexCoordPointer(unit->arraycomponents, GL_FLOAT, sizeof(float) * unit->arraycomponents, bufferobject ? (void *)bufferoffset : texcoord);CHECKGLERROR
+               }
        }
        else
        {
@@ -1643,9 +1917,9 @@ void R_Mesh_TextureState(const rmeshstate_t *m)
        for (i = 0;i < backendarrayunits;i++)
        {
                if (m->pointer_texcoord3f[i])
-                       R_Mesh_TexCoordPointer(i, 3, m->pointer_texcoord3f[i]);
+                       R_Mesh_TexCoordPointer(i, 3, m->pointer_texcoord3f[i], m->pointer_texcoord_bufferobject[i], m->pointer_texcoord_bufferoffset[i]);
                else
-                       R_Mesh_TexCoordPointer(i, 2, m->pointer_texcoord[i]);
+                       R_Mesh_TexCoordPointer(i, 2, m->pointer_texcoord[i], m->pointer_texcoord_bufferobject[i], m->pointer_texcoord_bufferoffset[i]);
        }
        for (i = 0;i < backendunits;i++)
        {