]> de.git.xonotic.org Git - xonotic/darkplaces.git/blobdiff - r_shadow.c
added indirection cube map for shadowmapping and revised filtering modes
[xonotic/darkplaces.git] / r_shadow.c
index 576e4b0ebcc4dbc81e46d37b995536a38f73d6c4..d992a762555d548d1435095155e104f7b4d4a9bd 100644 (file)
@@ -140,25 +140,44 @@ demonstrated by the game Doom3.
 #include "portals.h"
 #include "image.h"
 
+#define R_SHADOW_SHADOWMAP_NUMCUBEMAPS 8
+
 extern void R_Shadow_EditLights_Init(void);
 
 typedef enum r_shadow_rendermode_e
 {
        R_SHADOW_RENDERMODE_NONE,
-       R_SHADOW_RENDERMODE_STENCIL,
-       R_SHADOW_RENDERMODE_SEPARATESTENCIL,
-       R_SHADOW_RENDERMODE_STENCILTWOSIDE,
+       R_SHADOW_RENDERMODE_ZPASS_STENCIL,
+       R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL,
+       R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE,
+       R_SHADOW_RENDERMODE_ZFAIL_STENCIL,
+       R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL,
+       R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE,
        R_SHADOW_RENDERMODE_LIGHT_VERTEX,
        R_SHADOW_RENDERMODE_LIGHT_DOT3,
        R_SHADOW_RENDERMODE_LIGHT_GLSL,
        R_SHADOW_RENDERMODE_VISIBLEVOLUMES,
        R_SHADOW_RENDERMODE_VISIBLELIGHTING,
+       R_SHADOW_RENDERMODE_SHADOWMAPRECTANGLE,
+       R_SHADOW_RENDERMODE_SHADOWMAP2D,
+       R_SHADOW_RENDERMODE_SHADOWMAPCUBESIDE,
 }
 r_shadow_rendermode_t;
 
 r_shadow_rendermode_t r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
 r_shadow_rendermode_t r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_NONE;
-r_shadow_rendermode_t r_shadow_shadowingrendermode = R_SHADOW_RENDERMODE_NONE;
+r_shadow_rendermode_t r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_NONE;
+r_shadow_rendermode_t r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_NONE;
+float r_shadow_shadowmap_texturescale[4];
+float r_shadow_shadowmap_parameters[4];
+int r_shadow_drawbuffer;
+int r_shadow_readbuffer;
+GLuint r_shadow_fborectangle;
+int r_shadow_shadowmode;
+int r_shadow_shadowmapmaxsize;
+int r_shadow_shadowmapfilter;
+int r_shadow_shadowmapborder;
+int r_shadow_lightscissor[4];
 
 int maxshadowtriangles;
 int *shadowelements;
@@ -178,6 +197,7 @@ int *vertexremap;
 int vertexupdatenum;
 
 int r_shadow_buffer_numleafpvsbytes;
+unsigned char *r_shadow_buffer_visitingleafpvs;
 unsigned char *r_shadow_buffer_leafpvs;
 int *r_shadow_buffer_leaflist;
 
@@ -195,6 +215,10 @@ rtexture_t *r_shadow_attenuationgradienttexture;
 rtexture_t *r_shadow_attenuation2dtexture;
 rtexture_t *r_shadow_attenuation3dtexture;
 rtexture_t *r_shadow_lightcorona;
+rtexture_t *r_shadow_shadowmaprectangletexture;
+rtexture_t *r_shadow_shadowmapcubeprojectiontexture[R_SHADOW_SHADOWMAP_NUMCUBEMAPS];
+int r_shadow_shadowmapsize; // changes for each light based on distance
+int r_shadow_shadowmaplod; // changes for each light based on distance
 
 // lights are reloaded when this changes
 char r_shadow_mapname[MAX_QPATH];
@@ -210,6 +234,7 @@ cvar_t r_shadow_gloss = {CVAR_SAVE, "r_shadow_gloss", "1", "0 disables gloss (sp
 cvar_t r_shadow_gloss2intensity = {0, "r_shadow_gloss2intensity", "0.125", "how bright the forced flat gloss should look if r_shadow_gloss is 2"};
 cvar_t r_shadow_glossintensity = {0, "r_shadow_glossintensity", "1", "how bright textured glossmaps should look if r_shadow_gloss is 1 or 2"};
 cvar_t r_shadow_glossexponent = {0, "r_shadow_glossexponent", "32", "how 'sharp' the gloss should appear (specular power)"};
+cvar_t r_shadow_glossexact = {0, "r_shadow_glossexact", "0", "use exact reflection math for gloss (slightly slower, but should look a tad better)"};
 cvar_t r_shadow_lightattenuationdividebias = {0, "r_shadow_lightattenuationdividebias", "1", "changes attenuation texture generation"};
 cvar_t r_shadow_lightattenuationlinearscale = {0, "r_shadow_lightattenuationlinearscale", "2", "changes attenuation texture generation"};
 cvar_t r_shadow_lightintensityscale = {0, "r_shadow_lightintensityscale", "1", "renders all world lights brighter or darker"};
@@ -229,11 +254,22 @@ cvar_t r_shadow_realtime_world_compileshadow = {0, "r_shadow_realtime_world_comp
 cvar_t r_shadow_realtime_world_compilesvbsp = {0, "r_shadow_realtime_world_compilesvbsp", "1", "enables svbsp optimization during compilation"};
 cvar_t r_shadow_realtime_world_compileportalculling = {0, "r_shadow_realtime_world_compileportalculling", "1", "enables portal-based culling optimization during compilation"};
 cvar_t r_shadow_scissor = {0, "r_shadow_scissor", "1", "use scissor optimization of light rendering (restricts rendering to the portion of the screen affected by the light)"};
+cvar_t r_shadow_shadowmapping = {CVAR_SAVE, "r_shadow_shadowmapping", "0", "enables use of shadowmapping (depth texture sampling) instead of stencil shadow volumes, requires gl_fbo 1"};
+cvar_t r_shadow_shadowmapping_filterquality = {CVAR_SAVE, "r_shadow_shadowmapping_filterquality", "0", "shadowmap filter modes: 0 = no filtering, 1 = bilinear, 2 = bilinear small blur (fast), 3 = bilinear large blur (slow)"};
+cvar_t r_shadow_shadowmapping_minsize = {CVAR_SAVE, "r_shadow_shadowmapping_minsize", "32", "shadowmap size limit"};
+cvar_t r_shadow_shadowmapping_maxsize = {CVAR_SAVE, "r_shadow_shadowmapping_maxsize", "512", "shadowmap size limit"};
+cvar_t r_shadow_shadowmapping_lod_bias = {CVAR_SAVE, "r_shadow_shadowmapping_lod_bias", "16", "shadowmap size bias"};
+cvar_t r_shadow_shadowmapping_lod_scale = {CVAR_SAVE, "r_shadow_shadowmapping_lod_scale", "128", "shadowmap size scaling parameter"};
+cvar_t r_shadow_shadowmapping_bordersize = {CVAR_SAVE, "r_shadow_shadowmapping_bordersize", "4", "shadowmap size bias for filtering"};
+cvar_t r_shadow_shadowmapping_nearclip = {CVAR_SAVE, "r_shadow_shadowmapping_nearclip", "1", "shadowmap nearclip in world units"};
+cvar_t r_shadow_shadowmapping_bias = {CVAR_SAVE, "r_shadow_shadowmapping_bias", "0.03", "shadowmap bias parameter (this is multiplied by nearclip * 1024 / lodsize)"};
 cvar_t r_shadow_culltriangles = {0, "r_shadow_culltriangles", "1", "performs more expensive tests to remove unnecessary triangles of lit surfaces"};
 cvar_t r_shadow_polygonfactor = {0, "r_shadow_polygonfactor", "0", "how much to enlarge shadow volume polygons when rendering (should be 0!)"};
 cvar_t r_shadow_polygonoffset = {0, "r_shadow_polygonoffset", "1", "how much to push shadow volumes into the distance when rendering, to reduce chances of zfighting artifacts (should not be less than 0)"};
 cvar_t r_shadow_texture3d = {0, "r_shadow_texture3d", "1", "use 3D voxel textures for spherical attenuation rather than cylindrical (does not affect r_glsl lighting)"};
 cvar_t r_coronas = {CVAR_SAVE, "r_coronas", "1", "brightness of corona flare effects around certain lights, 0 disables corona effects"};
+cvar_t r_coronas_occlusionsizescale = {CVAR_SAVE, "r_coronas_occlusionsizescale", "0.1", "size of light source for corona occlusion checksm the proportion of hidden pixels controls corona intensity"};
+cvar_t r_coronas_occlusionquery = {CVAR_SAVE, "r_coronas_occlusionquery", "1", "use GL_ARB_occlusion_query extension if supported (fades coronas according to visibility)"};
 cvar_t gl_flashblend = {CVAR_SAVE, "gl_flashblend", "0", "render bright coronas for dynamic lights instead of actual lighting, fast but ugly"};
 cvar_t gl_ext_separatestencil = {0, "gl_ext_separatestencil", "1", "make use of OpenGL 2.0 glStencilOpSeparate or GL_ATI_separate_stencil extension"};
 cvar_t gl_ext_stenciltwoside = {0, "gl_ext_stenciltwoside", "1", "make use of GL_EXT_stenciltwoside extension (NVIDIA only)"};
@@ -293,6 +329,34 @@ cachepic_t *r_editlights_sprcubemaplight;
 cachepic_t *r_editlights_sprcubemapnoshadowlight;
 cachepic_t *r_editlights_sprselection;
 
+void R_Shadow_FreeShadowMaps(void)
+{
+       int i;
+
+       r_shadow_shadowmapmaxsize = bound(1, r_shadow_shadowmapping_maxsize.integer, 2048);
+       r_shadow_shadowmode = r_shadow_shadowmapping.integer;
+    r_shadow_shadowmapfilter = r_shadow_shadowmapping_filterquality.integer;
+    r_shadow_shadowmapborder = bound(0, r_shadow_shadowmapping_bordersize.integer, 16);
+       r_shadow_shadowmaplod = -1;
+
+       CHECKGLERROR
+       if (r_shadow_fborectangle)
+               qglDeleteFramebuffersEXT(1, &r_shadow_fborectangle);
+       r_shadow_fborectangle = 0;
+       CHECKGLERROR
+
+       if (r_shadow_shadowmaprectangletexture)
+               R_FreeTexture(r_shadow_shadowmaprectangletexture);
+       r_shadow_shadowmaprectangletexture = NULL;
+
+    for (i = 0;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
+        if (r_shadow_shadowmapcubeprojectiontexture[i])
+            R_FreeTexture(r_shadow_shadowmapcubeprojectiontexture[i]);
+    memset(r_shadow_shadowmapcubeprojectiontexture, 0, sizeof(r_shadow_shadowmapcubeprojectiontexture));
+
+       CHECKGLERROR
+}
+
 void r_shadow_start(void)
 {
        // allocate vertex processing arrays
@@ -300,6 +364,17 @@ void r_shadow_start(void)
        r_shadow_attenuationgradienttexture = NULL;
        r_shadow_attenuation2dtexture = NULL;
        r_shadow_attenuation3dtexture = NULL;
+       r_shadow_shadowmode = 0;
+       r_shadow_shadowmaprectangletexture = NULL;
+    memset(r_shadow_shadowmapcubeprojectiontexture, 0, sizeof(r_shadow_shadowmapcubeprojectiontexture));
+       r_shadow_shadowmapmaxsize = 0;
+       r_shadow_shadowmapsize = 0;
+       r_shadow_shadowmaplod = 0;
+    r_shadow_shadowmapfilter = 0;
+       r_shadow_fborectangle = 0;
+
+       R_Shadow_FreeShadowMaps();
+
        r_shadow_texturepool = NULL;
        r_shadow_filters_texturepool = NULL;
        R_Shadow_ValidateCvars();
@@ -318,6 +393,7 @@ void r_shadow_start(void)
        shadowmarklist = NULL;
        shadowmarkcount = 0;
        r_shadow_buffer_numleafpvsbytes = 0;
+       r_shadow_buffer_visitingleafpvs = NULL;
        r_shadow_buffer_leafpvs = NULL;
        r_shadow_buffer_leaflist = NULL;
        r_shadow_buffer_numsurfacepvsbytes = 0;
@@ -331,7 +407,12 @@ void r_shadow_start(void)
 
 void r_shadow_shutdown(void)
 {
+       CHECKGLERROR
        R_Shadow_UncompileWorldLights();
+
+       R_Shadow_FreeShadowMaps();
+
+       CHECKGLERROR
        numcubemaps = 0;
        r_shadow_attenuationgradienttexture = NULL;
        r_shadow_attenuation2dtexture = NULL;
@@ -363,6 +444,9 @@ void r_shadow_shutdown(void)
        shadowmarklist = NULL;
        shadowmarkcount = 0;
        r_shadow_buffer_numleafpvsbytes = 0;
+       if (r_shadow_buffer_visitingleafpvs)
+               Mem_Free(r_shadow_buffer_visitingleafpvs);
+       r_shadow_buffer_visitingleafpvs = NULL;
        if (r_shadow_buffer_leafpvs)
                Mem_Free(r_shadow_buffer_leafpvs);
        r_shadow_buffer_leafpvs = NULL;
@@ -435,6 +519,7 @@ void R_Shadow_Init(void)
        Cvar_RegisterVariable(&r_shadow_gloss2intensity);
        Cvar_RegisterVariable(&r_shadow_glossintensity);
        Cvar_RegisterVariable(&r_shadow_glossexponent);
+       Cvar_RegisterVariable(&r_shadow_glossexact);
        Cvar_RegisterVariable(&r_shadow_lightattenuationdividebias);
        Cvar_RegisterVariable(&r_shadow_lightattenuationlinearscale);
        Cvar_RegisterVariable(&r_shadow_lightintensityscale);
@@ -454,11 +539,22 @@ void R_Shadow_Init(void)
        Cvar_RegisterVariable(&r_shadow_realtime_world_compilesvbsp);
        Cvar_RegisterVariable(&r_shadow_realtime_world_compileportalculling);
        Cvar_RegisterVariable(&r_shadow_scissor);
+       Cvar_RegisterVariable(&r_shadow_shadowmapping);
+       Cvar_RegisterVariable(&r_shadow_shadowmapping_filterquality);
+       Cvar_RegisterVariable(&r_shadow_shadowmapping_maxsize);
+       Cvar_RegisterVariable(&r_shadow_shadowmapping_minsize);
+       Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_bias);
+       Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_scale);
+       Cvar_RegisterVariable(&r_shadow_shadowmapping_bordersize);
+       Cvar_RegisterVariable(&r_shadow_shadowmapping_nearclip);
+       Cvar_RegisterVariable(&r_shadow_shadowmapping_bias);
        Cvar_RegisterVariable(&r_shadow_culltriangles);
        Cvar_RegisterVariable(&r_shadow_polygonfactor);
        Cvar_RegisterVariable(&r_shadow_polygonoffset);
        Cvar_RegisterVariable(&r_shadow_texture3d);
        Cvar_RegisterVariable(&r_coronas);
+       Cvar_RegisterVariable(&r_coronas_occlusionsizescale);
+       Cvar_RegisterVariable(&r_coronas_occlusionquery);
        Cvar_RegisterVariable(&gl_flashblend);
        Cvar_RegisterVariable(&gl_ext_separatestencil);
        Cvar_RegisterVariable(&gl_ext_stenciltwoside);
@@ -484,6 +580,7 @@ void R_Shadow_Init(void)
        shadowmarklist = NULL;
        shadowmarkcount = 0;
        r_shadow_buffer_numleafpvsbytes = 0;
+       r_shadow_buffer_visitingleafpvs = NULL;
        r_shadow_buffer_leafpvs = NULL;
        r_shadow_buffer_leaflist = NULL;
        r_shadow_buffer_numsurfacepvsbytes = 0;
@@ -542,11 +639,14 @@ static void R_Shadow_EnlargeLeafSurfaceTrisBuffer(int numleafs, int numsurfaces,
        int numlighttrispvsbytes = (((numlighttriangles + 7) >> 3) + 255) & ~255;
        if (r_shadow_buffer_numleafpvsbytes < numleafpvsbytes)
        {
+               if (r_shadow_buffer_visitingleafpvs)
+                       Mem_Free(r_shadow_buffer_visitingleafpvs);
                if (r_shadow_buffer_leafpvs)
                        Mem_Free(r_shadow_buffer_leafpvs);
                if (r_shadow_buffer_leaflist)
                        Mem_Free(r_shadow_buffer_leaflist);
                r_shadow_buffer_numleafpvsbytes = numleafpvsbytes;
+               r_shadow_buffer_visitingleafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
                r_shadow_buffer_leafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
                r_shadow_buffer_leaflist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes * 8 * sizeof(*r_shadow_buffer_leaflist));
        }
@@ -600,7 +700,7 @@ void R_Shadow_PrepareShadowMark(int numtris)
        numshadowmark = 0;
 }
 
-int R_Shadow_ConstructShadowVolume(int innumvertices, int innumtris, const int *inelement3i, const int *inneighbor3i, const float *invertex3f, int *outnumvertices, int *outelement3i, float *outvertex3f, const float *projectorigin, const float *projectdirection, float projectdistance, int numshadowmarktris, const int *shadowmarktris)
+static int R_Shadow_ConstructShadowVolume_ZFail(int innumvertices, int innumtris, const int *inelement3i, const int *inneighbor3i, const float *invertex3f, int *outnumvertices, int *outelement3i, float *outvertex3f, const float *projectorigin, const float *projectdirection, float projectdistance, int numshadowmarktris, const int *shadowmarktris)
 {
        int i, j;
        int outtriangles = 0, outvertices = 0;
@@ -613,28 +713,6 @@ int R_Shadow_ConstructShadowVolume(int innumvertices, int innumtris, const int *
        else
                VectorClear(projectvector);
 
-       if (maxvertexupdate < innumvertices)
-       {
-               maxvertexupdate = innumvertices;
-               if (vertexupdate)
-                       Mem_Free(vertexupdate);
-               if (vertexremap)
-                       Mem_Free(vertexremap);
-               vertexupdate = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
-               vertexremap = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
-               vertexupdatenum = 0;
-       }
-       vertexupdatenum++;
-       if (vertexupdatenum == 0)
-       {
-               vertexupdatenum = 1;
-               memset(vertexupdate, 0, maxvertexupdate * sizeof(int));
-               memset(vertexremap, 0, maxvertexupdate * sizeof(int));
-       }
-
-       for (i = 0;i < numshadowmarktris;i++)
-               shadowmark[shadowmarktris[i]] = shadowmarkcount;
-
        // create the vertices
        if (projectdirection)
        {
@@ -819,6 +897,116 @@ int R_Shadow_ConstructShadowVolume(int innumvertices, int innumtris, const int *
        return outtriangles;
 }
 
+static int R_Shadow_ConstructShadowVolume_ZPass(int innumvertices, int innumtris, const int *inelement3i, const int *inneighbor3i, const float *invertex3f, int *outnumvertices, int *outelement3i, float *outvertex3f, const float *projectorigin, const float *projectdirection, float projectdistance, int numshadowmarktris, const int *shadowmarktris)
+{
+       int i, j, k;
+       int outtriangles = 0, outvertices = 0;
+       const int *element;
+       const float *vertex;
+       float ratio, direction[3], projectvector[3];
+       qboolean side[4];
+
+       if (projectdirection)
+               VectorScale(projectdirection, projectdistance, projectvector);
+       else
+               VectorClear(projectvector);
+
+       for (i = 0;i < numshadowmarktris;i++)
+       {
+               int remappedelement[3];
+               int markindex;
+               const int *neighbortriangle;
+
+               markindex = shadowmarktris[i] * 3;
+               neighbortriangle = inneighbor3i + markindex;
+               side[0] = shadowmark[neighbortriangle[0]] == shadowmarkcount;
+               side[1] = shadowmark[neighbortriangle[1]] == shadowmarkcount;
+               side[2] = shadowmark[neighbortriangle[2]] == shadowmarkcount;
+               if (side[0] + side[1] + side[2] == 0)
+                       continue;
+
+               side[3] = side[0];
+               element = inelement3i + markindex;
+
+               // create the vertices
+               for (j = 0;j < 3;j++)
+               {
+                       if (side[j] + side[j+1] == 0)
+                               continue;
+                       k = element[j];
+                       if (vertexupdate[k] != vertexupdatenum)
+                       {
+                               vertexupdate[k] = vertexupdatenum;
+                               vertexremap[k] = outvertices;
+                               vertex = invertex3f + k * 3;
+                               VectorCopy(vertex, outvertex3f);
+                               if (projectdirection)
+                               {
+                                       // project one copy of the vertex according to projectvector
+                                       VectorAdd(vertex, projectvector, (outvertex3f + 3));
+                               }
+                               else
+                               {
+                                       // project one copy of the vertex to the sphere radius of the light
+                                       // (FIXME: would projecting it to the light box be better?)
+                                       VectorSubtract(vertex, projectorigin, direction);
+                                       ratio = projectdistance / VectorLength(direction);
+                                       VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
+                               }
+                               outvertex3f += 6;
+                               outvertices += 2;
+                       }
+               }
+
+               // output the sides (facing outward from this triangle)
+               if (!side[0])
+               {
+                       remappedelement[0] = vertexremap[element[0]];
+                       remappedelement[1] = vertexremap[element[1]];
+                       outelement3i[0] = remappedelement[1];
+                       outelement3i[1] = remappedelement[0];
+                       outelement3i[2] = remappedelement[0] + 1;
+                       outelement3i[3] = remappedelement[1];
+                       outelement3i[4] = remappedelement[0] + 1;
+                       outelement3i[5] = remappedelement[1] + 1;
+
+                       outelement3i += 6;
+                       outtriangles += 2;
+               }
+               if (!side[1])
+               {
+                       remappedelement[1] = vertexremap[element[1]];
+                       remappedelement[2] = vertexremap[element[2]];
+                       outelement3i[0] = remappedelement[2];
+                       outelement3i[1] = remappedelement[1];
+                       outelement3i[2] = remappedelement[1] + 1;
+                       outelement3i[3] = remappedelement[2];
+                       outelement3i[4] = remappedelement[1] + 1;
+                       outelement3i[5] = remappedelement[2] + 1;
+
+                       outelement3i += 6;
+                       outtriangles += 2;
+               }
+               if (!side[2])
+               {
+                       remappedelement[0] = vertexremap[element[0]];
+                       remappedelement[2] = vertexremap[element[2]];
+                       outelement3i[0] = remappedelement[0];
+                       outelement3i[1] = remappedelement[2];
+                       outelement3i[2] = remappedelement[2] + 1;
+                       outelement3i[3] = remappedelement[0];
+                       outelement3i[4] = remappedelement[2] + 1;
+                       outelement3i[5] = remappedelement[0] + 1;
+
+                       outelement3i += 6;
+                       outtriangles += 2;
+               }
+       }
+       if (outnumvertices)
+               *outnumvertices = outvertices;
+       return outtriangles;
+}
+
 void R_Shadow_MarkVolumeFromBox(int firsttriangle, int numtris, const float *invertex3f, const int *elements, const vec3_t projectorigin, const vec3_t projectdirection, const vec3_t lightmins, const vec3_t lightmaxs, const vec3_t surfacemins, const vec3_t surfacemaxs)
 {
        int t, tend;
@@ -878,36 +1066,27 @@ void R_Shadow_MarkVolumeFromBox(int firsttriangle, int numtris, const float *inv
        }
 }
 
-static void R_Shadow_RenderVolume(int numvertices, int numtriangles, const float *vertex3f, const int *element3i)
+qboolean R_Shadow_UseZPass(vec3_t mins, vec3_t maxs)
 {
-       if (r_shadow_compilingrtlight)
-       {
-               // if we're compiling an rtlight, capture the mesh
-               Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow, NULL, NULL, NULL, vertex3f, NULL, NULL, NULL, NULL, numtriangles, element3i);
-               return;
-       }
-       r_refdef.stats.lights_shadowtriangles += numtriangles;
-       CHECKGLERROR
-       R_Mesh_VertexPointer(vertex3f, 0, 0);
-       GL_LockArrays(0, numvertices);
-       if (r_shadow_rendermode == R_SHADOW_RENDERMODE_STENCIL)
-       {
-               // decrement stencil if backface is behind depthbuffer
-               GL_CullFace(r_refdef.view.cullface_front);
-               qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
-               R_Mesh_Draw(0, numvertices, 0, numtriangles, element3i, NULL, 0, 0);
-               // increment stencil if frontface is behind depthbuffer
-               GL_CullFace(r_refdef.view.cullface_back);
-               qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
-       }
-       R_Mesh_Draw(0, numvertices, 0, numtriangles, element3i, NULL, 0, 0);
-       GL_LockArrays(0, 0);
-       CHECKGLERROR
+#if 1
+       return false;
+#else
+       if (r_shadow_compilingrtlight || !r_shadow_frontsidecasting.integer || !r_shadow_usezpassifpossible.integer)
+               return false;
+       // check if the shadow volume intersects the near plane
+       //
+       // a ray between the eye and light origin may intersect the caster,
+       // indicating that the shadow may touch the eye location, however we must
+       // test the near plane (a polygon), not merely the eye location, so it is
+       // easiest to enlarge the caster bounding shape slightly for this.
+       // TODO
+       return true;
+#endif
 }
 
-void R_Shadow_VolumeFromList(int numverts, int numtris, const float *invertex3f, const int *elements, const int *neighbors, const vec3_t projectorigin, const vec3_t projectdirection, float projectdistance, int nummarktris, const int *marktris)
+void R_Shadow_VolumeFromList(int numverts, int numtris, const float *invertex3f, const int *elements, const int *neighbors, const vec3_t projectorigin, const vec3_t projectdirection, float projectdistance, int nummarktris, const int *marktris, vec3_t trismins, vec3_t trismaxs)
 {
-       int tris, outverts;
+       int i, tris, outverts;
        if (projectdistance < 0.1)
        {
                Con_Printf("R_Shadow_Volume: projectdistance %f\n", projectdistance);
@@ -918,9 +1097,103 @@ void R_Shadow_VolumeFromList(int numverts, int numtris, const float *invertex3f,
        // make sure shadowelements is big enough for this volume
        if (maxshadowtriangles < nummarktris || maxshadowvertices < numverts)
                R_Shadow_ResizeShadowArrays((numverts + 255) & ~255, (nummarktris + 255) & ~255);
-       tris = R_Shadow_ConstructShadowVolume(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
+
+       if (maxvertexupdate < numverts)
+       {
+               maxvertexupdate = numverts;
+               if (vertexupdate)
+                       Mem_Free(vertexupdate);
+               if (vertexremap)
+                       Mem_Free(vertexremap);
+               vertexupdate = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
+               vertexremap = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
+               vertexupdatenum = 0;
+       }
+       vertexupdatenum++;
+       if (vertexupdatenum == 0)
+       {
+               vertexupdatenum = 1;
+               memset(vertexupdate, 0, maxvertexupdate * sizeof(int));
+               memset(vertexremap, 0, maxvertexupdate * sizeof(int));
+       }
+
+       for (i = 0;i < nummarktris;i++)
+               shadowmark[marktris[i]] = shadowmarkcount;
+
+       if (r_shadow_compilingrtlight)
+       {
+               // if we're compiling an rtlight, capture the mesh
+               //tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
+               //Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zpass, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
+               tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
+               Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zfail, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
+       }
+       else
+       {
+               // decide which type of shadow to generate and set stencil mode
+               R_Shadow_RenderMode_StencilShadowVolumes(R_Shadow_UseZPass(trismins, trismaxs));
+               // generate the sides or a solid volume, depending on type
+               if (r_shadow_rendermode >= R_SHADOW_RENDERMODE_ZPASS_STENCIL && r_shadow_rendermode <= R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE)
+                       tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
+               else
+                       tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
+               r_refdef.stats.lights_dynamicshadowtriangles += tris;
+               r_refdef.stats.lights_shadowtriangles += tris;
+               CHECKGLERROR
+               R_Mesh_VertexPointer(shadowvertex3f, 0, 0);
+               GL_LockArrays(0, outverts);
+               if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
+               {
+                       // increment stencil if frontface is infront of depthbuffer
+                       GL_CullFace(r_refdef.view.cullface_front);
+                       qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
+                       R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, 0);
+                       // decrement stencil if backface is infront of depthbuffer
+                       GL_CullFace(r_refdef.view.cullface_back);
+                       qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
+               }
+               else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
+               {
+                       // decrement stencil if backface is behind depthbuffer
+                       GL_CullFace(r_refdef.view.cullface_front);
+                       qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
+                       R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, 0);
+                       // increment stencil if frontface is behind depthbuffer
+                       GL_CullFace(r_refdef.view.cullface_back);
+                       qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
+               }
+               R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, 0);
+               GL_LockArrays(0, 0);
+               CHECKGLERROR
+       }
+}
+
+void R_Shadow_ShadowMapFromList(int numverts, int numtris, const float *vertex3f, int vertex3f_bufferobject, int vertex3f_bufferoffset, const int *elements, int nummarktris, const int *marktris)
+{
+       int i, tris = nummarktris;
+       int *outelement3i;
+       const int *element;
+       if (!numverts || !nummarktris)
+               return;
+       // make sure shadowelements is big enough for this mesh
+       if (maxshadowtriangles < nummarktris || maxshadowvertices < numverts)
+               R_Shadow_ResizeShadowArrays((numverts + 255) & ~255, (nummarktris + 255) & ~255);
+
+       // gather up the (sparse) triangles into one array
+       outelement3i = shadowelements;
+       for (i = 0;i < nummarktris;i++)
+       {
+               element = elements + marktris[i] * 3;
+               outelement3i[0] = element[0];
+               outelement3i[1] = element[1];
+               outelement3i[2] = element[2];
+               outelement3i += 3;
+       }
+
        r_refdef.stats.lights_dynamicshadowtriangles += tris;
-       R_Shadow_RenderVolume(outverts, tris, shadowvertex3f, shadowelements);
+       r_refdef.stats.lights_shadowtriangles += tris;
+       R_Mesh_VertexPointer(vertex3f, vertex3f_bufferobject, vertex3f_bufferoffset);
+       R_Mesh_Draw(0, numverts, 0, tris, shadowelements, NULL, 0, 0);
 }
 
 static void R_Shadow_MakeTextures_MakeCorona(void)
@@ -942,7 +1215,7 @@ static void R_Shadow_MakeTextures_MakeCorona(void)
                        pixels[y][x][3] = 255;
                }
        }
-       r_shadow_lightcorona = R_LoadTexture2D(r_shadow_texturepool, "lightcorona", 32, 32, &pixels[0][0][0], TEXTYPE_BGRA, TEXF_PRECACHE, NULL);
+       r_shadow_lightcorona = R_LoadTexture2D(r_shadow_texturepool, "lightcorona", 32, 32, &pixels[0][0][0], TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_FORCELINEAR, NULL);
 }
 
 static unsigned int R_Shadow_MakeTextures_SamplePoint(float x, float y, float z)
@@ -973,12 +1246,12 @@ static void R_Shadow_MakeTextures(void)
        // 1D gradient texture
        for (x = 0;x < ATTEN1DSIZE;x++)
                data[x] = R_Shadow_MakeTextures_SamplePoint((x + 0.5f) * (1.0f / ATTEN1DSIZE) * (1.0f / 0.9375), 0, 0);
-       r_shadow_attenuationgradienttexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation1d", ATTEN1DSIZE, 1, (unsigned char *)data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA, NULL);
+       r_shadow_attenuationgradienttexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation1d", ATTEN1DSIZE, 1, (unsigned char *)data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, NULL);
        // 2D circle texture
        for (y = 0;y < ATTEN2DSIZE;y++)
                for (x = 0;x < ATTEN2DSIZE;x++)
                        data[y*ATTEN2DSIZE+x] = R_Shadow_MakeTextures_SamplePoint(((x + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375), ((y + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375), 0);
-       r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA, NULL);
+       r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, NULL);
        // 3D sphere texture
        if (r_shadow_texture3d.integer && gl_texture3d)
        {
@@ -986,7 +1259,7 @@ static void R_Shadow_MakeTextures(void)
                        for (y = 0;y < ATTEN3DSIZE;y++)
                                for (x = 0;x < ATTEN3DSIZE;x++)
                                        data[(z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x] = R_Shadow_MakeTextures_SamplePoint(((x + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375), ((y + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375), ((z + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375));
-               r_shadow_attenuation3dtexture = R_LoadTexture3D(r_shadow_texturepool, "attenuation3d", ATTEN3DSIZE, ATTEN3DSIZE, ATTEN3DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA, NULL);
+               r_shadow_attenuation3dtexture = R_LoadTexture3D(r_shadow_texturepool, "attenuation3d", ATTEN3DSIZE, ATTEN3DSIZE, ATTEN3DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, NULL);
        }
        else
                r_shadow_attenuation3dtexture = NULL;
@@ -1015,6 +1288,8 @@ void R_Shadow_ValidateCvars(void)
 
 void R_Shadow_RenderMode_Begin(void)
 {
+       GLint drawbuffer;
+       GLint readbuffer;
        R_Shadow_ValidateCvars();
 
        if (!r_shadow_attenuation2dtexture
@@ -1032,16 +1307,25 @@ void R_Shadow_RenderMode_Begin(void)
        GL_DepthTest(true);
        GL_DepthMask(false);
        GL_Color(0, 0, 0, 1);
-       GL_Scissor(r_refdef.view.x, r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
+       GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
 
        r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
 
        if (gl_ext_separatestencil.integer)
-               r_shadow_shadowingrendermode = R_SHADOW_RENDERMODE_SEPARATESTENCIL;
+       {
+               r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL;
+               r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL;
+       }
        else if (gl_ext_stenciltwoside.integer)
-               r_shadow_shadowingrendermode = R_SHADOW_RENDERMODE_STENCILTWOSIDE;
+       {
+               r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE;
+               r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE;
+       }
        else
-               r_shadow_shadowingrendermode = R_SHADOW_RENDERMODE_STENCIL;
+       {
+               r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCIL;
+               r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCIL;
+       }
 
        if (r_glsl.integer && gl_support_fragment_shader)
                r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_GLSL;
@@ -1049,9 +1333,15 @@ void R_Shadow_RenderMode_Begin(void)
                r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_DOT3;
        else
                r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX;
+
+       CHECKGLERROR
+       qglGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);CHECKGLERROR
+       qglGetIntegerv(GL_READ_BUFFER, &readbuffer);CHECKGLERROR
+       r_shadow_drawbuffer = drawbuffer;
+       r_shadow_readbuffer = readbuffer;
 }
 
-void R_Shadow_RenderMode_ActiveLight(rtlight_t *rtlight)
+void R_Shadow_RenderMode_ActiveLight(const rtlight_t *rtlight)
 {
        rsurface.rtlight = rtlight;
 }
@@ -1059,10 +1349,18 @@ void R_Shadow_RenderMode_ActiveLight(rtlight_t *rtlight)
 void R_Shadow_RenderMode_Reset(void)
 {
        CHECKGLERROR
-       if (r_shadow_rendermode == R_SHADOW_RENDERMODE_STENCILTWOSIDE)
+       if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE || r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE)
        {
                qglDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
        }
+       if (gl_support_ext_framebuffer_object)
+       {
+               qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);CHECKGLERROR
+       }
+       qglDrawBuffer(r_shadow_drawbuffer);CHECKGLERROR
+       qglReadBuffer(r_shadow_readbuffer);CHECKGLERROR
+       R_SetViewport(&r_refdef.view.viewport);
+       GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
        R_Mesh_ColorPointer(NULL, 0, 0);
        R_Mesh_ResetTextureState();
        GL_DepthRange(0, 1);
@@ -1079,10 +1377,21 @@ void R_Shadow_RenderMode_Reset(void)
        GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
        GL_BlendFunc(GL_ONE, GL_ZERO);
        R_SetupGenericShader(false);
+       CHECKGLERROR
+}
+
+void R_Shadow_ClearStencil(void)
+{
+       CHECKGLERROR
+       GL_Clear(GL_STENCIL_BUFFER_BIT);
+       r_refdef.stats.lights_clears++;
 }
 
-void R_Shadow_RenderMode_StencilShadowVolumes(qboolean clearstencil)
+void R_Shadow_RenderMode_StencilShadowVolumes(qboolean zpass)
 {
+       r_shadow_rendermode_t mode = zpass ? r_shadow_shadowingrendermode_zpass : r_shadow_shadowingrendermode_zfail;
+       if (r_shadow_rendermode == mode)
+               return;
        CHECKGLERROR
        R_Shadow_RenderMode_Reset();
        GL_ColorMask(0, 0, 0, 0);
@@ -1090,15 +1399,32 @@ void R_Shadow_RenderMode_StencilShadowVolumes(qboolean clearstencil)
        R_SetupDepthOrShadowShader();
        qglDepthFunc(GL_LESS);CHECKGLERROR
        qglEnable(GL_STENCIL_TEST);CHECKGLERROR
-       r_shadow_rendermode = r_shadow_shadowingrendermode;
-       if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SEPARATESTENCIL)
+       r_shadow_rendermode = mode;
+       switch(mode)
        {
+       default:
+               break;
+       case R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL:
+               GL_CullFace(GL_NONE);
+               qglStencilOpSeparate(r_refdef.view.cullface_front, GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
+               qglStencilOpSeparate(r_refdef.view.cullface_back, GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
+               break;
+       case R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL:
                GL_CullFace(GL_NONE);
                qglStencilOpSeparate(r_refdef.view.cullface_front, GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
                qglStencilOpSeparate(r_refdef.view.cullface_back, GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
-       }
-       else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_STENCILTWOSIDE)
-       {
+               break;
+       case R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE:
+               GL_CullFace(GL_NONE);
+               qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
+               qglActiveStencilFaceEXT(r_refdef.view.cullface_front);CHECKGLERROR
+               qglStencilMask(~0);CHECKGLERROR
+               qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
+               qglActiveStencilFaceEXT(r_refdef.view.cullface_back);CHECKGLERROR
+               qglStencilMask(~0);CHECKGLERROR
+               qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
+               break;
+       case R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE:
                GL_CullFace(GL_NONE);
                qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
                qglActiveStencilFaceEXT(r_refdef.view.cullface_front);CHECKGLERROR
@@ -1107,13 +1433,80 @@ void R_Shadow_RenderMode_StencilShadowVolumes(qboolean clearstencil)
                qglActiveStencilFaceEXT(r_refdef.view.cullface_back);CHECKGLERROR
                qglStencilMask(~0);CHECKGLERROR
                qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
+               break;
        }
-       if (clearstencil)
-               GL_Clear(GL_STENCIL_BUFFER_BIT);
-       r_refdef.stats.lights_clears++;
 }
 
-void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent)
+void R_Shadow_RenderMode_ShadowMap(int side, qboolean clear, int size)
+{
+       int status;
+       int maxsize;
+       float nearclip, farclip, bias;
+       r_viewport_t viewport;
+       CHECKGLERROR
+       maxsize = r_shadow_shadowmapmaxsize;
+       nearclip = r_shadow_shadowmapping_nearclip.value / rsurface.rtlight->radius;
+       farclip = 1.0f;
+       bias = r_shadow_shadowmapping_bias.value * nearclip * (1024.0f / size);// * rsurface.rtlight->radius;
+       // complex unrolled cube approach (more flexible)
+       if (!r_shadow_shadowmapcubeprojectiontexture[r_shadow_shadowmaplod])
+               r_shadow_shadowmapcubeprojectiontexture[r_shadow_shadowmaplod] = R_LoadTextureCubeProjection(r_shadow_texturepool, "shadowmapcubeprojection", size, r_shadow_shadowmapborder);
+       if (!r_shadow_shadowmaprectangletexture)
+       {
+#if 1
+               r_shadow_shadowmaprectangletexture = R_LoadTextureShadowMapRectangle(r_shadow_texturepool, "shadowmap", maxsize*2, maxsize*3, r_shadow_shadowmapfilter == 1 || r_shadow_shadowmapfilter == 2);
+               qglGenFramebuffersEXT(1, &r_shadow_fborectangle);CHECKGLERROR
+               qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fborectangle);CHECKGLERROR
+               qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_RECTANGLE_ARB, R_GetTexture(r_shadow_shadowmaprectangletexture), 0);CHECKGLERROR
+#endif
+       }
+       CHECKGLERROR
+       R_Shadow_RenderMode_Reset();
+       if (r_shadow_shadowmaprectangletexture)
+       {
+               // render depth into the fbo, do not render color at all
+               qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fborectangle);CHECKGLERROR
+               qglDrawBuffer(GL_NONE);CHECKGLERROR
+               qglReadBuffer(GL_NONE);CHECKGLERROR
+               status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
+               if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
+               {
+                       Con_Printf("R_Shadow_RenderMode_ShadowMap: glCheckFramebufferStatusEXT returned %i\n", status);
+                       Cvar_SetValueQuick(&r_shadow_shadowmapping, 0);
+               }
+               R_SetupDepthOrShadowShader();
+       }
+       else
+       {
+               R_SetupShowDepthShader();
+               qglClearColor(1,1,1,1);CHECKGLERROR
+       }
+       R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapborder, nearclip, farclip, NULL);
+       r_shadow_shadowmap_texturescale[0] = 2*size;
+       r_shadow_shadowmap_texturescale[1] = 3*size;
+       r_shadow_shadowmap_texturescale[2] = 0.5f + 0.5f * (farclip + nearclip) / (farclip - nearclip);
+       r_shadow_shadowmap_texturescale[3] = -nearclip * farclip / (farclip - nearclip) - 0.5f * bias;
+       // compat for ALU cubemap calcs
+    r_shadow_shadowmap_parameters[0] = 0.5f * (size - r_shadow_shadowmapborder);
+       r_shadow_shadowmap_parameters[1] = size;
+       r_shadow_shadowmap_parameters[2] = r_shadow_shadowmap_texturescale[2];
+       r_shadow_shadowmap_parameters[3] = r_shadow_shadowmap_texturescale[3];
+       r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAPRECTANGLE;
+       CHECKGLERROR
+       R_SetViewport(&viewport);
+       GL_PolygonOffset(0, 0);
+       GL_CullFace(GL_NONE); // quake is backwards
+       GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
+       GL_DepthMask(true);
+       GL_DepthTest(true);
+       qglClearDepth(1);CHECKGLERROR
+       CHECKGLERROR
+       if (clear)
+               qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT |  GL_STENCIL_BUFFER_BIT);
+       CHECKGLERROR
+}
+
+void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qboolean shadowmapping)
 {
        CHECKGLERROR
        R_Shadow_RenderMode_Reset();
@@ -1135,10 +1528,19 @@ void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent)
        {
                R_Mesh_TexBindCubeMap(GL20TU_CUBE, R_GetTexture(rsurface.rtlight->currentcubemap)); // light filter
                GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0);
+               CHECKGLERROR
+               if (shadowmapping)
+               {
+                       R_Mesh_TexBindRectangle(GL20TU_SHADOWMAPRECT, R_GetTexture(r_shadow_shadowmaprectangletexture));
+                       CHECKGLERROR
+                       R_Mesh_TexBindCubeMap(GL20TU_CUBEPROJECTION, R_GetTexture(r_shadow_shadowmapcubeprojectiontexture[r_shadow_shadowmaplod]));
+                       CHECKGLERROR
+               }
        }
        else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_VERTEX)
                R_Mesh_ColorPointer(rsurface.array_color4f, 0, 0);
        GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
+       CHECKGLERROR
 }
 
 void R_Shadow_RenderMode_VisibleShadowVolumes(void)
@@ -1180,7 +1582,7 @@ void R_Shadow_RenderMode_End(void)
        R_Shadow_RenderMode_Reset();
        R_Shadow_RenderMode_ActiveLight(NULL);
        GL_DepthMask(true);
-       GL_Scissor(r_refdef.view.x, r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
+       GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
        r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
 }
 
@@ -1217,15 +1619,17 @@ qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
        int sign[8];
        float f;
 
+       r_shadow_lightscissor[0] = r_refdef.view.viewport.x;
+       r_shadow_lightscissor[1] = r_refdef.view.viewport.y;
+       r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
+       r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
+
        if (!r_shadow_scissor.integer)
                return false;
 
        // if view is inside the light box, just say yes it's visible
        if (BoxesOverlap(r_refdef.view.origin, r_refdef.view.origin, mins, maxs))
-       {
-               GL_Scissor(r_refdef.view.x, r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
                return false;
-       }
 
        x1 = y1 = x2 = y2 = 0;
 
@@ -1273,7 +1677,7 @@ qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
        for (i = 0;i < numvertices;i++)
        {
                VectorCopy(vertex[i], v);
-               GL_TransformToScreen(v, v2);
+               R_Viewport_TransformToScreen(&r_refdef.view.viewport, v, v2);
                //Con_Printf("%.3f %.3f %.3f %.3f transformed to %.3f %.3f %.3f %.3f\n", v[0], v[1], v[2], v[3], v2[0], v2[1], v2[2], v2[3]);
                if (i)
                {
@@ -1291,25 +1695,27 @@ qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
 
        // now convert the scissor rectangle to integer screen coordinates
        ix1 = (int)(x1 - 1.0f);
-       iy1 = (int)(y1 - 1.0f);
+       iy1 = vid.height - (int)(y2 - 1.0f);
        ix2 = (int)(x2 + 1.0f);
-       iy2 = (int)(y2 + 1.0f);
+       iy2 = vid.height - (int)(y1 + 1.0f);
        //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2);
 
        // clamp it to the screen
-       if (ix1 < r_refdef.view.x) ix1 = r_refdef.view.x;
-       if (iy1 < r_refdef.view.y) iy1 = r_refdef.view.y;
-       if (ix2 > r_refdef.view.x + r_refdef.view.width) ix2 = r_refdef.view.x + r_refdef.view.width;
-       if (iy2 > r_refdef.view.y + r_refdef.view.height) iy2 = r_refdef.view.y + r_refdef.view.height;
+       if (ix1 < r_refdef.view.viewport.x) ix1 = r_refdef.view.viewport.x;
+       if (iy1 < r_refdef.view.viewport.y) iy1 = r_refdef.view.viewport.y;
+       if (ix2 > r_refdef.view.viewport.x + r_refdef.view.viewport.width) ix2 = r_refdef.view.viewport.x + r_refdef.view.viewport.width;
+       if (iy2 > r_refdef.view.viewport.y + r_refdef.view.viewport.height) iy2 = r_refdef.view.viewport.y + r_refdef.view.viewport.height;
 
        // if it is inside out, it's not visible
        if (ix2 <= ix1 || iy2 <= iy1)
                return true;
 
        // the light area is visible, set up the scissor rectangle
-       GL_Scissor(ix1, iy1, ix2 - ix1, iy2 - iy1);
-       //qglScissor(ix1, iy1, ix2 - ix1, iy2 - iy1);CHECKGLERROR
-       //qglEnable(GL_SCISSOR_TEST);CHECKGLERROR
+       r_shadow_lightscissor[0] = ix1;
+       r_shadow_lightscissor[1] = iy1;
+       r_shadow_lightscissor[2] = ix2 - ix1;
+       r_shadow_lightscissor[3] = iy2 - iy1;
+
        r_refdef.stats.lights_scissored++;
        return false;
 }
@@ -1539,6 +1945,7 @@ static void R_Shadow_RenderLighting_Light_GLSL(int firstvertex, int numvertices,
        else
                R_Mesh_ColorPointer(NULL, 0, 0);
        R_Mesh_TexMatrix(0, &rsurface.texture->currenttexmatrix);
+       R_Mesh_TexMatrix(1, &rsurface.texture->currentbackgroundtexmatrix);
        R_Mesh_TexBind(GL20TU_NORMAL, R_GetTexture(rsurface.texture->currentskinframe->nmap));
        R_Mesh_TexBind(GL20TU_COLOR, R_GetTexture(rsurface.texture->basetexture));
        R_Mesh_TexBind(GL20TU_GLOSS, R_GetTexture(rsurface.texture->glosstexture));
@@ -1547,6 +1954,7 @@ static void R_Shadow_RenderLighting_Light_GLSL(int firstvertex, int numvertices,
                R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL, R_GetTexture(rsurface.texture->backgroundcurrentskinframe->nmap));
                R_Mesh_TexBind(GL20TU_SECONDARY_COLOR, R_GetTexture(rsurface.texture->backgroundbasetexture));
                R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS, R_GetTexture(rsurface.texture->backgroundglosstexture));
+               R_Mesh_TexBind(GL20TU_SECONDARY_GLOW, R_GetTexture(rsurface.texture->backgroundcurrentskinframe->glow));
        }
        //R_Mesh_TexBindCubeMap(GL20TU_CUBE, R_GetTexture(rsurface.rtlight->currentcubemap));
        R_Mesh_TexBind(GL20TU_FOGMASK, R_GetTexture(r_texture_fogattenuation));
@@ -2396,7 +2804,7 @@ void R_Shadow_RenderLighting(int firstvertex, int numvertices, int firsttriangle
        }
 }
 
-void R_RTLight_Update(rtlight_t *rtlight, int isstatic, matrix4x4_t *matrix, vec3_t color, int style, const char *cubemapname, qboolean shadow, vec_t corona, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags)
+void R_RTLight_Update(rtlight_t *rtlight, int isstatic, matrix4x4_t *matrix, vec3_t color, int style, const char *cubemapname, int shadow, vec_t corona, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags)
 {
        matrix4x4_t tempmatrix = *matrix;
        Matrix4x4_Scale(&tempmatrix, r_shadow_lightradiusscale.value, 1);
@@ -2443,10 +2851,11 @@ void R_RTLight_Compile(rtlight_t *rtlight)
 {
        int i;
        int numsurfaces, numleafs, numleafpvsbytes, numshadowtrispvsbytes, numlighttrispvsbytes;
-       int lighttris, shadowtris, shadowmeshes, shadowmeshtris;
+       int lighttris, shadowtris, shadowzpasstris, shadowzfailtris;
        entity_render_t *ent = r_refdef.scene.worldentity;
        dp_model_t *model = r_refdef.scene.worldmodel;
        unsigned char *data;
+       shadowmesh_t *mesh;
 
        // compile the light
        rtlight->compiled = true;
@@ -2468,7 +2877,7 @@ void R_RTLight_Compile(rtlight_t *rtlight)
                // this variable must be set for the CompileShadowVolume code
                r_shadow_compilingrtlight = rtlight;
                R_Shadow_EnlargeLeafSurfaceTrisBuffer(model->brush.num_leafs, model->num_surfaces, model->brush.shadowmesh ? model->brush.shadowmesh->numtriangles : model->surfmesh.num_triangles, model->surfmesh.num_triangles);
-               model->GetLightInfo(ent, rtlight->shadoworigin, rtlight->radius, rtlight->cullmins, rtlight->cullmaxs, r_shadow_buffer_leaflist, r_shadow_buffer_leafpvs, &numleafs, r_shadow_buffer_surfacelist, r_shadow_buffer_surfacepvs, &numsurfaces, r_shadow_buffer_shadowtrispvs, r_shadow_buffer_lighttrispvs);
+               model->GetLightInfo(ent, rtlight->shadoworigin, rtlight->radius, rtlight->cullmins, rtlight->cullmaxs, r_shadow_buffer_leaflist, r_shadow_buffer_leafpvs, &numleafs, r_shadow_buffer_surfacelist, r_shadow_buffer_surfacepvs, &numsurfaces, r_shadow_buffer_shadowtrispvs, r_shadow_buffer_lighttrispvs, r_shadow_buffer_visitingleafpvs);
                numleafpvsbytes = (model->brush.num_leafs + 7) >> 3;
                numshadowtrispvsbytes = ((model->brush.shadowmesh ? model->brush.shadowmesh->numtriangles : model->surfmesh.num_triangles) + 7) >> 3;
                numlighttrispvsbytes = (model->surfmesh.num_triangles + 7) >> 3;
@@ -2504,17 +2913,15 @@ void R_RTLight_Compile(rtlight_t *rtlight)
        //rtlight->cullradius = RadiusFromBoundsAndOrigin(rtlight->cullmins, rtlight->cullmaxs, rtlight->shadoworigin);
        //rtlight->cullradius = min(rtlight->cullradius, rtlight->radius);
 
-       shadowmeshes = 0;
-       shadowmeshtris = 0;
-       if (rtlight->static_meshchain_shadow)
-       {
-               shadowmesh_t *mesh;
-               for (mesh = rtlight->static_meshchain_shadow;mesh;mesh = mesh->next)
-               {
-                       shadowmeshes++;
-                       shadowmeshtris += mesh->numtriangles;
-               }
-       }
+       shadowzpasstris = 0;
+       if (rtlight->static_meshchain_shadow_zpass)
+               for (mesh = rtlight->static_meshchain_shadow_zpass;mesh;mesh = mesh->next)
+                       shadowzpasstris += mesh->numtriangles;
+
+       shadowzfailtris = 0;
+       if (rtlight->static_meshchain_shadow_zfail)
+               for (mesh = rtlight->static_meshchain_shadow_zfail;mesh;mesh = mesh->next)
+                       shadowzfailtris += mesh->numtriangles;
 
        lighttris = 0;
        if (rtlight->static_numlighttrispvsbytes)
@@ -2529,16 +2936,19 @@ void R_RTLight_Compile(rtlight_t *rtlight)
                                shadowtris++;
 
        if (developer.integer >= 10)
-               Con_Printf("static light built: %f %f %f : %f %f %f box, %i light triangles, %i shadow triangles, %i compiled shadow volume triangles (in %i meshes)\n", rtlight->cullmins[0], rtlight->cullmins[1], rtlight->cullmins[2], rtlight->cullmaxs[0], rtlight->cullmaxs[1], rtlight->cullmaxs[2], lighttris, shadowtris, shadowmeshtris, shadowmeshes);
+               Con_Printf("static light built: %f %f %f : %f %f %f box, %i light triangles, %i shadow triangles, %i zpass/%i zfail compiled shadow volume triangles\n", rtlight->cullmins[0], rtlight->cullmins[1], rtlight->cullmins[2], rtlight->cullmaxs[0], rtlight->cullmaxs[1], rtlight->cullmaxs[2], lighttris, shadowtris, shadowzpasstris, shadowzfailtris);
 }
 
 void R_RTLight_Uncompile(rtlight_t *rtlight)
 {
        if (rtlight->compiled)
        {
-               if (rtlight->static_meshchain_shadow)
-                       Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow);
-               rtlight->static_meshchain_shadow = NULL;
+               if (rtlight->static_meshchain_shadow_zpass)
+                       Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_zpass);
+               rtlight->static_meshchain_shadow_zpass = NULL;
+               if (rtlight->static_meshchain_shadow_zfail)
+                       Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_zfail);
+               rtlight->static_meshchain_shadow_zfail = NULL;
                // these allocations are grouped
                if (rtlight->static_surfacelist)
                        Mem_Free(rtlight->static_surfacelist);
@@ -2560,9 +2970,10 @@ void R_Shadow_UncompileWorldLights(void)
 {
        size_t lightindex;
        dlight_t *light;
-       for (lightindex = 0;lightindex < Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);lightindex++)
+       size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
+       for (lightindex = 0;lightindex < range;lightindex++)
        {
-               light = Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
+               light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
                if (!light)
                        continue;
                R_RTLight_Uncompile(&light->rtlight);
@@ -2737,17 +3148,43 @@ void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight)
 
 void R_Shadow_DrawWorldShadow(int numsurfaces, int *surfacelist, const unsigned char *trispvs)
 {
+       qboolean zpass;
+       shadowmesh_t *mesh;
+       int t, tend;
+       int surfacelistindex;
+       msurface_t *surface;
+
        RSurf_ActiveWorldEntity();
+       if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAPRECTANGLE || r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAPCUBESIDE || r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAP2D)
+       {
+               if (r_refdef.scene.worldentity->model)
+                       r_refdef.scene.worldmodel->DrawShadowMap(r_refdef.scene.worldentity, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius, numsurfaces, surfacelist, rsurface.rtlight_cullmins, rsurface.rtlight_cullmaxs);
+               rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
+               return;
+       }
+
        if (rsurface.rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
        {
-               shadowmesh_t *mesh;
                CHECKGLERROR
-               for (mesh = rsurface.rtlight->static_meshchain_shadow;mesh;mesh = mesh->next)
+               zpass = R_Shadow_UseZPass(r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs);
+               R_Shadow_RenderMode_StencilShadowVolumes(zpass);
+               mesh = zpass ? rsurface.rtlight->static_meshchain_shadow_zpass : rsurface.rtlight->static_meshchain_shadow_zfail;
+               for (;mesh;mesh = mesh->next)
                {
                        r_refdef.stats.lights_shadowtriangles += mesh->numtriangles;
                        R_Mesh_VertexPointer(mesh->vertex3f, mesh->vbo, mesh->vbooffset_vertex3f);
                        GL_LockArrays(0, mesh->numverts);
-                       if (r_shadow_rendermode == R_SHADOW_RENDERMODE_STENCIL)
+                       if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
+                       {
+                               // increment stencil if frontface is infront of depthbuffer
+                               GL_CullFace(r_refdef.view.cullface_back);
+                               qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
+                               R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3s, mesh->ebo3i, mesh->ebo3s);
+                               // decrement stencil if backface is infront of depthbuffer
+                               GL_CullFace(r_refdef.view.cullface_front);
+                               qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
+                       }
+                       else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
                        {
                                // decrement stencil if backface is behind depthbuffer
                                GL_CullFace(r_refdef.view.cullface_front);
@@ -2764,9 +3201,6 @@ void R_Shadow_DrawWorldShadow(int numsurfaces, int *surfacelist, const unsigned
        }
        else if (numsurfaces && r_refdef.scene.worldmodel->brush.shadowmesh && r_shadow_culltriangles.integer)
        {
-               int t, tend;
-               int surfacelistindex;
-               msurface_t *surface;
                R_Shadow_PrepareShadowMark(r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles);
                for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
                {
@@ -2775,10 +3209,12 @@ void R_Shadow_DrawWorldShadow(int numsurfaces, int *surfacelist, const unsigned
                                if (CHECKPVSBIT(trispvs, t))
                                        shadowmarklist[numshadowmark++] = t;
                }
-               R_Shadow_VolumeFromList(r_refdef.scene.worldmodel->brush.shadowmesh->numverts, r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles, r_refdef.scene.worldmodel->brush.shadowmesh->vertex3f, r_refdef.scene.worldmodel->brush.shadowmesh->element3i, r_refdef.scene.worldmodel->brush.shadowmesh->neighbor3i, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius + r_refdef.scene.worldmodel->radius*2 + r_shadow_projectdistance.value, numshadowmark, shadowmarklist);
+               R_Shadow_VolumeFromList(r_refdef.scene.worldmodel->brush.shadowmesh->numverts, r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles, r_refdef.scene.worldmodel->brush.shadowmesh->vertex3f, r_refdef.scene.worldmodel->brush.shadowmesh->element3i, r_refdef.scene.worldmodel->brush.shadowmesh->neighbor3i, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius + r_refdef.scene.worldmodel->radius*2 + r_shadow_projectdistance.value, numshadowmark, shadowmarklist, r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs);
        }
        else if (numsurfaces)
                r_refdef.scene.worldmodel->DrawShadowVolume(r_refdef.scene.worldentity, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius, numsurfaces, surfacelist, rsurface.rtlight_cullmins, rsurface.rtlight_cullmaxs);
+
+       rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
 }
 
 void R_Shadow_DrawEntityShadow(entity_render_t *ent)
@@ -2794,7 +3230,11 @@ void R_Shadow_DrawEntityShadow(entity_render_t *ent)
        relativeshadowmaxs[0] = relativeshadoworigin[0] + relativeshadowradius;
        relativeshadowmaxs[1] = relativeshadoworigin[1] + relativeshadowradius;
        relativeshadowmaxs[2] = relativeshadoworigin[2] + relativeshadowradius;
-       ent->model->DrawShadowVolume(ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->surfacelist, relativeshadowmins, relativeshadowmaxs);
+       if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAPRECTANGLE || r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAPCUBESIDE || r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAP2D)
+               ent->model->DrawShadowMap(ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
+       else
+               ent->model->DrawShadowVolume(ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
+       rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
 }
 
 void R_Shadow_SetupEntityLight(const entity_render_t *ent)
@@ -2826,6 +3266,8 @@ void R_Shadow_DrawWorldLight(int numsurfaces, int *surfacelist, const unsigned c
                R_Mesh_TexMatrix(3, &rsurface.entitytolight);
 
        r_refdef.scene.worldmodel->DrawLight(r_refdef.scene.worldentity, numsurfaces, surfacelist, trispvs);
+
+       rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
 }
 
 void R_Shadow_DrawEntityLight(entity_render_t *ent)
@@ -2836,9 +3278,60 @@ void R_Shadow_DrawEntityLight(entity_render_t *ent)
 
        R_Shadow_SetupEntityLight(ent);
 
-       model->DrawLight(ent, model->nummodelsurfaces, model->surfacelist, NULL);
+       model->DrawLight(ent, model->nummodelsurfaces, model->sortedmodelsurfaces, NULL);
+
+       rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
 }
 
+/*
+{{  0,   0, 0}, "px",  true,  true,  true},
+{{  0,  90, 0}, "py", false,  true, false},
+{{  0, 180, 0}, "nx", false, false,  true},
+{{  0, 270, 0}, "ny",  true, false, false},
+{{-90, 180, 0}, "pz", false, false,  true},
+{{ 90, 180, 0}, "nz", false, false,  true}
+*/
+
+static const double shadowviewmat16[6][4][4] =
+{
+       {
+               {-1,  0,  0, 0},
+               { 0, -1,  0, 0},
+               { 0,  0,  1, 0},
+               { 0,  0,  0, 1},
+       },
+       {
+               { 0, -1,  0, 0},
+               {-1,  0,  0, 0},
+               { 0,  0,  1, 0},
+               { 0,  0,  0, 1},
+       },
+       {
+               {-1,  0,  0, 0},
+               { 0, -1,  0, 0},
+               { 0,  0,  1, 0},
+               { 0,  0,  0, 1},
+       },
+       {
+               { 0, -1,  0, 0},
+               {-1,  0,  0, 0},
+               { 0,  0,  1, 0},
+               { 0,  0,  0, 1},
+       },
+       {
+               { 0,  0,  1, 0},
+               { 0, -1,  0, 0},
+               { 1,  0,  0, 0},
+               { 0,  0,  0, 1},
+       },
+       {
+               { 0,  0, -1, 0},
+               { 0, -1,  0, 0},
+               {-1,  0,  0, 0},
+               { 0,  0,  0, 1},
+       },
+};
+
 void R_DrawRTLight(rtlight_t *rtlight, qboolean visible)
 {
        int i;
@@ -2850,10 +3343,14 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible)
        int numlightentities_noselfshadow;
        int numshadowentities;
        int numshadowentities_noselfshadow;
-       entity_render_t *lightentities[MAX_EDICTS];
-       entity_render_t *lightentities_noselfshadow[MAX_EDICTS];
-       entity_render_t *shadowentities[MAX_EDICTS];
-       entity_render_t *shadowentities_noselfshadow[MAX_EDICTS];
+       static entity_render_t *lightentities[MAX_EDICTS];
+       static entity_render_t *lightentities_noselfshadow[MAX_EDICTS];
+       static entity_render_t *shadowentities[MAX_EDICTS];
+       static entity_render_t *shadowentities_noselfshadow[MAX_EDICTS];
+       vec3_t nearestpoint;
+       vec_t distance;
+       qboolean castshadows;
+       int lodlinear;
 
        // skip lights that don't light because of ambientscale+diffusescale+specularscale being 0 (corona only lights)
        // skip lights that are basically invisible (color 0 0 0)
@@ -2908,7 +3405,7 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible)
                // dynamic light, world available and can receive realtime lighting
                // calculate lit surfaces and leafs
                R_Shadow_EnlargeLeafSurfaceTrisBuffer(r_refdef.scene.worldmodel->brush.num_leafs, r_refdef.scene.worldmodel->num_surfaces, r_refdef.scene.worldmodel->brush.shadowmesh ? r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles : r_refdef.scene.worldmodel->surfmesh.num_triangles, r_refdef.scene.worldmodel->surfmesh.num_triangles);
-               r_refdef.scene.worldmodel->GetLightInfo(r_refdef.scene.worldentity, rtlight->shadoworigin, rtlight->radius, rsurface.rtlight_cullmins, rsurface.rtlight_cullmaxs, r_shadow_buffer_leaflist, r_shadow_buffer_leafpvs, &numleafs, r_shadow_buffer_surfacelist, r_shadow_buffer_surfacepvs, &numsurfaces, r_shadow_buffer_shadowtrispvs, r_shadow_buffer_lighttrispvs);
+               r_refdef.scene.worldmodel->GetLightInfo(r_refdef.scene.worldentity, rtlight->shadoworigin, rtlight->radius, rsurface.rtlight_cullmins, rsurface.rtlight_cullmaxs, r_shadow_buffer_leaflist, r_shadow_buffer_leafpvs, &numleafs, r_shadow_buffer_surfacelist, r_shadow_buffer_surfacepvs, &numsurfaces, r_shadow_buffer_shadowtrispvs, r_shadow_buffer_lighttrispvs, r_shadow_buffer_visitingleafpvs);
                leaflist = r_shadow_buffer_leaflist;
                leafpvs = r_shadow_buffer_leafpvs;
                surfacelist = r_shadow_buffer_surfacelist;
@@ -3041,11 +3538,84 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible)
                        R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
        }
 
-       if (gl_stencil && numsurfaces + numshadowentities + numshadowentities_noselfshadow && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows))
+       if (r_showlighting.integer && r_refdef.view.showdebug && numsurfaces + numlightentities + numlightentities_noselfshadow)
+       {
+               // optionally draw the illuminated areas
+               // for performance analysis by level designers
+               R_Shadow_RenderMode_VisibleLighting(false, false);
+               if (numsurfaces)
+                       R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
+               for (i = 0;i < numlightentities;i++)
+                       R_Shadow_DrawEntityLight(lightentities[i]);
+               for (i = 0;i < numlightentities_noselfshadow;i++)
+                       R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
+       }
+
+       castshadows = numsurfaces + numshadowentities + numshadowentities_noselfshadow > 0 && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows);
+
+       nearestpoint[0] = bound(rtlight->cullmins[0], r_refdef.view.origin[0], rtlight->cullmaxs[0]);
+       nearestpoint[1] = bound(rtlight->cullmins[1], r_refdef.view.origin[1], rtlight->cullmaxs[1]);
+       nearestpoint[2] = bound(rtlight->cullmins[2], r_refdef.view.origin[2], rtlight->cullmaxs[2]);
+       distance = VectorDistance(nearestpoint, r_refdef.view.origin);
+       lodlinear = (int)(r_shadow_shadowmapping_lod_bias.value + r_shadow_shadowmapping_lod_scale.value * rtlight->radius / max(1.0f, distance));
+       lodlinear = bound(r_shadow_shadowmapping_minsize.integer, lodlinear, r_shadow_shadowmapping_maxsize.integer);
+
+       if (castshadows && r_shadow_shadowmode && r_glsl.integer && gl_support_fragment_shader)
+       {
+               int side;
+               int size;
+
+               r_shadow_shadowmaplod = 0;
+               for (i = 1;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
+                       if ((r_shadow_shadowmapping_maxsize.integer >> i) > lodlinear)
+                               r_shadow_shadowmaplod = i;
+
+               size = bound(1, r_shadow_shadowmapping_maxsize.integer >> r_shadow_shadowmaplod, 2048);
+
+               //Con_Printf("distance %f lodlinear %i (lod %i) size %i\n", distance, lodlinear, r_shadow_shadowmaplod, size);
+
+               // render shadow casters into 6 sided depth texture
+               for (side = 0;side < 6;side++)
+               {
+                       R_Shadow_RenderMode_ShadowMap(side, true, size);
+                       if (numsurfaces)
+                               R_Shadow_DrawWorldShadow(numsurfaces, surfacelist, shadowtrispvs);
+                       for (i = 0;i < numshadowentities;i++)
+                               R_Shadow_DrawEntityShadow(shadowentities[i]);
+               }
+
+               if (numlightentities_noselfshadow)
+               {
+                       // render lighting using the depth texture as shadowmap
+                       // draw lighting in the unmasked areas
+                       R_Shadow_RenderMode_Lighting(false, false, true);
+                       for (i = 0;i < numlightentities_noselfshadow;i++)
+                               R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
+               }
+
+               // render shadow casters into 6 sided depth texture
+               for (side = 0;side < 6;side++)
+               {
+                       R_Shadow_RenderMode_ShadowMap(side, false, size);
+                       for (i = 0;i < numshadowentities_noselfshadow;i++)
+                               R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
+               }
+
+               // render lighting using the depth texture as shadowmap
+               // draw lighting in the unmasked areas
+               R_Shadow_RenderMode_Lighting(false, false, true);
+               // draw lighting in the unmasked areas
+               if (numsurfaces)
+                       R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
+               for (i = 0;i < numlightentities;i++)
+                       R_Shadow_DrawEntityLight(lightentities[i]);
+       }
+       else if (castshadows && gl_stencil)
        {
                // draw stencil shadow volumes to mask off pixels that are in shadow
                // so that they won't receive lighting
-               R_Shadow_RenderMode_StencilShadowVolumes(true);
+               GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
+               R_Shadow_ClearStencil();
                if (numsurfaces)
                        R_Shadow_DrawWorldShadow(numsurfaces, surfacelist, shadowtrispvs);
                for (i = 0;i < numshadowentities;i++)
@@ -3053,7 +3623,7 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible)
                if (numlightentities_noselfshadow)
                {
                        // draw lighting in the unmasked areas
-                       R_Shadow_RenderMode_Lighting(true, false);
+                       R_Shadow_RenderMode_Lighting(true, false, false);
                        for (i = 0;i < numlightentities_noselfshadow;i++)
                                R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
 
@@ -3065,8 +3635,6 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible)
                                for (i = 0;i < numlightentities_noselfshadow;i++)
                                        R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
                        }
-
-                       R_Shadow_RenderMode_StencilShadowVolumes(false);
                }
                for (i = 0;i < numshadowentities_noselfshadow;i++)
                        R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
@@ -3074,22 +3642,11 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible)
                if (numsurfaces + numlightentities)
                {
                        // draw lighting in the unmasked areas
-                       R_Shadow_RenderMode_Lighting(true, false);
+                       R_Shadow_RenderMode_Lighting(true, false, false);
                        if (numsurfaces)
                                R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
                        for (i = 0;i < numlightentities;i++)
                                R_Shadow_DrawEntityLight(lightentities[i]);
-
-                       // optionally draw the illuminated areas
-                       // for performance analysis by level designers
-                       if (r_showlighting.integer && r_refdef.view.showdebug)
-                       {
-                               R_Shadow_RenderMode_VisibleLighting(!r_showdisabledepthtest.integer, false);
-                               if (numsurfaces)
-                                       R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
-                               for (i = 0;i < numlightentities;i++)
-                                       R_Shadow_DrawEntityLight(lightentities[i]);
-                       }
                }
        }
        else
@@ -3097,26 +3654,13 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible)
                if (numsurfaces + numlightentities)
                {
                        // draw lighting in the unmasked areas
-                       R_Shadow_RenderMode_Lighting(false, false);
+                       R_Shadow_RenderMode_Lighting(false, false, false);
                        if (numsurfaces)
                                R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
                        for (i = 0;i < numlightentities;i++)
                                R_Shadow_DrawEntityLight(lightentities[i]);
                        for (i = 0;i < numlightentities_noselfshadow;i++)
                                R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
-
-                       // optionally draw the illuminated areas
-                       // for performance analysis by level designers
-                       if (r_showlighting.integer && r_refdef.view.showdebug)
-                       {
-                               R_Shadow_RenderMode_VisibleLighting(false, false);
-                               if (numsurfaces)
-                                       R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
-                               for (i = 0;i < numlightentities;i++)
-                                       R_Shadow_DrawEntityLight(lightentities[i]);
-                               for (i = 0;i < numlightentities_noselfshadow;i++)
-                                       R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
-                       }
                }
        }
 }
@@ -3128,6 +3672,10 @@ void R_ShadowVolumeLighting(qboolean visible)
        int lnum;
        size_t lightindex;
        dlight_t *light;
+       size_t range;
+
+       if (r_shadow_shadowmapmaxsize != bound(1, r_shadow_shadowmapping_maxsize.integer, 2048) || r_shadow_shadowmode != r_shadow_shadowmapping.integer || r_shadow_shadowmapfilter != r_shadow_shadowmapping_filterquality.integer || r_shadow_shadowmapborder != bound(0, r_shadow_shadowmapping_bordersize.integer, 16))
+               R_Shadow_FreeShadowMaps();
 
        if (r_editlights.integer)
                R_Shadow_DrawLightSprites();
@@ -3138,28 +3686,37 @@ void R_ShadowVolumeLighting(qboolean visible)
        if (r_shadow_debuglight.integer >= 0)
        {
                lightindex = r_shadow_debuglight.integer;
-               light = Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
+               light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
                if (light && (light->flags & flag))
                        R_DrawRTLight(&light->rtlight, visible);
        }
        else
        {
-               for (lightindex = 0;lightindex < Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);lightindex++)
+               range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
+               for (lightindex = 0;lightindex < range;lightindex++)
                {
-                       light = Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
+                       light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
                        if (light && (light->flags & flag))
                                R_DrawRTLight(&light->rtlight, visible);
                }
        }
        if (r_refdef.scene.rtdlight)
                for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
-                       R_DrawRTLight(&r_refdef.scene.lights[lnum], visible);
+                       R_DrawRTLight(r_refdef.scene.lights[lnum], visible);
 
        R_Shadow_RenderMode_End();
 }
 
+extern const float r_screenvertex3f[12];
 extern void R_SetupView(qboolean allowwaterclippingplane);
+extern void R_ResetViewRendering3D(void);
+extern void R_ResetViewRendering2D(void);
+extern cvar_t r_shadows;
+extern cvar_t r_shadows_darken;
+extern cvar_t r_shadows_drawafterrtlighting;
+extern cvar_t r_shadows_castfrombmodels;
 extern cvar_t r_shadows_throwdistance;
+extern cvar_t r_shadows_throwdirection;
 void R_DrawModelShadows(void)
 {
        int i;
@@ -3168,69 +3725,103 @@ void R_DrawModelShadows(void)
        vec3_t relativelightorigin;
        vec3_t relativelightdirection;
        vec3_t relativeshadowmins, relativeshadowmaxs;
-       float vertex3f[12];
+       vec3_t tmp, shadowdir;
 
        if (!r_drawentities.integer || !gl_stencil)
                return;
 
        CHECKGLERROR
-       GL_Scissor(r_refdef.view.x, r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
-
-       r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
+       R_ResetViewRendering3D();
+       //GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
+       //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
+       R_Shadow_RenderMode_Begin();
+       R_Shadow_RenderMode_ActiveLight(NULL);
+       r_shadow_lightscissor[0] = r_refdef.view.x;
+       r_shadow_lightscissor[1] = vid.height - r_refdef.view.y - r_refdef.view.height;
+       r_shadow_lightscissor[2] = r_refdef.view.width;
+       r_shadow_lightscissor[3] = r_refdef.view.height;
+       R_Shadow_RenderMode_StencilShadowVolumes(false);
 
-       if (gl_ext_separatestencil.integer)
-               r_shadow_shadowingrendermode = R_SHADOW_RENDERMODE_SEPARATESTENCIL;
-       else if (gl_ext_stenciltwoside.integer)
-               r_shadow_shadowingrendermode = R_SHADOW_RENDERMODE_STENCILTWOSIDE;
-       else
-               r_shadow_shadowingrendermode = R_SHADOW_RENDERMODE_STENCIL;
+       // get shadow dir
+       if (r_shadows.integer == 2)
+       {
+               Math_atov(r_shadows_throwdirection.string, shadowdir);
+               VectorNormalize(shadowdir);
+       }
 
-       R_Shadow_RenderMode_StencilShadowVolumes(true);
+       R_Shadow_ClearStencil();
 
        for (i = 0;i < r_refdef.scene.numentities;i++)
        {
                ent = r_refdef.scene.entities[i];
-               // cast shadows from anything that is not a submodel of the map
-               if (ent->model && ent->model->DrawShadowVolume != NULL && !ent->model->brush.submodel && (ent->flags & RENDER_SHADOW))
+
+               // cast shadows from anything of the map (submodels are optional)
+               if (ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
                {
                        relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix);
                        VectorSet(relativeshadowmins, -relativethrowdistance, -relativethrowdistance, -relativethrowdistance);
                        VectorSet(relativeshadowmaxs, relativethrowdistance, relativethrowdistance, relativethrowdistance);
-                       VectorNegate(ent->modellight_lightdir, relativelightdirection);
+                       if (r_shadows.integer == 2) // 2: simpler mode, throw shadows always in same direction
+                               Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection);
+                       else
+                       {
+                               if(ent->entitynumber != 0)
+                               {
+                                       // networked entity - might be attached in some way (then we should use the parent's light direction, to not tear apart attached entities)
+                                       int entnum, entnum2, recursion;
+                                       entnum = entnum2 = ent->entitynumber;
+                                       for(recursion = 32; recursion > 0; --recursion)
+                                       {
+                                               entnum2 = cl.entities[entnum].state_current.tagentity;
+                                               if(entnum2 >= 1 && entnum2 < cl.num_entities && cl.entities_active[entnum2])
+                                                       entnum = entnum2;
+                                               else
+                                                       break;
+                                       }
+                                       if(recursion && recursion != 32) // if we followed a valid non-empty attachment chain
+                                       {
+                                               VectorNegate(cl.entities[entnum].render.modellight_lightdir, relativelightdirection);
+                                               // transform into modelspace of OUR entity
+                                               Matrix4x4_Transform3x3(&cl.entities[entnum].render.matrix, relativelightdirection, tmp);
+                                               Matrix4x4_Transform3x3(&ent->inversematrix, tmp, relativelightdirection);
+                                       }
+                                       else
+                                               VectorNegate(ent->modellight_lightdir, relativelightdirection);
+                               }
+                               else
+                                       VectorNegate(ent->modellight_lightdir, relativelightdirection);
+                       }
+
                        VectorScale(relativelightdirection, -relativethrowdistance, relativelightorigin);
                        RSurf_ActiveModelEntity(ent, false, false);
-                       ent->model->DrawShadowVolume(ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->surfacelist, relativeshadowmins, relativeshadowmaxs);
+                       ent->model->DrawShadowVolume(ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
+                       rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
                }
        }
 
        // not really the right mode, but this will disable any silly stencil features
-       R_Shadow_RenderMode_VisibleLighting(true, true);
-
-       // vertex coordinates for a quad that covers the screen exactly
-       vertex3f[0] = 0;vertex3f[1] = 0;vertex3f[2] = 0;
-       vertex3f[3] = 1;vertex3f[4] = 0;vertex3f[5] = 0;
-       vertex3f[6] = 1;vertex3f[7] = 1;vertex3f[8] = 0;
-       vertex3f[9] = 0;vertex3f[10] = 1;vertex3f[11] = 0;
+       R_Shadow_RenderMode_End();
 
        // set up ortho view for rendering this pass
-       GL_SetupView_Mode_Ortho(0, 0, 1, 1, -10, 100);
-       GL_Scissor(r_refdef.view.x, r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
-       GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
-       GL_ScissorTest(true);
-       R_Mesh_Matrix(&identitymatrix);
-       R_Mesh_ResetTextureState();
-       R_Mesh_VertexPointer(vertex3f, 0, 0);
+       //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
+       //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
+       //GL_ScissorTest(true);
+       //R_Mesh_Matrix(&identitymatrix);
+       //R_Mesh_ResetTextureState();
+       R_ResetViewRendering2D();
+       R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
        R_Mesh_ColorPointer(NULL, 0, 0);
+       R_SetupGenericShader(false);
 
-       // set up a 50% darkening blend on shadowed areas
+       // set up a darkening blend on shadowed areas
        GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
-       GL_DepthRange(0, 1);
-       GL_DepthTest(false);
-       GL_DepthMask(false);
-       GL_PolygonOffset(0, 0);CHECKGLERROR
-       GL_Color(0, 0, 0, 0.5);
-       GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
-       qglDepthFunc(GL_ALWAYS);CHECKGLERROR
+       //GL_DepthRange(0, 1);
+       //GL_DepthTest(false);
+       //GL_DepthMask(false);
+       //GL_PolygonOffset(0, 0);CHECKGLERROR
+       GL_Color(0, 0, 0, r_shadows_darken.value);
+       //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
+       //qglDepthFunc(GL_ALWAYS);CHECKGLERROR
        qglEnable(GL_STENCIL_TEST);CHECKGLERROR
        qglStencilMask(~0);CHECKGLERROR
        qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
@@ -3239,69 +3830,160 @@ void R_DrawModelShadows(void)
        // apply the blend to the shadowed areas
        R_Mesh_Draw(0, 4, 0, 2, NULL, polygonelements, 0, 0);
 
-       // restoring the perspective view is done by R_RenderScene
-       //R_SetupView(true);
+       // restore the viewport
+       R_SetViewport(&r_refdef.view.viewport);
 
        // restore other state to normal
-       R_Shadow_RenderMode_End();
+       //R_Shadow_RenderMode_End();
+}
+
+void R_BeginCoronaQuery(rtlight_t *rtlight, float scale, qboolean usequery)
+{
+       float zdist;
+       vec3_t centerorigin;
+       // if it's too close, skip it
+       if (VectorLength(rtlight->color) < (1.0f / 256.0f))
+               return;
+       zdist = (DotProduct(rtlight->shadoworigin, r_refdef.view.forward) - DotProduct(r_refdef.view.origin, r_refdef.view.forward));
+       if (zdist < 32)
+               return;
+       if (usequery && r_numqueries + 2 <= r_maxqueries)
+       {
+               rtlight->corona_queryindex_allpixels = r_queries[r_numqueries++];
+               rtlight->corona_queryindex_visiblepixels = r_queries[r_numqueries++];
+               VectorMA(r_refdef.view.origin, zdist, r_refdef.view.forward, centerorigin);
+
+               CHECKGLERROR
+               // NOTE: we can't disable depth testing using R_DrawSprite's depthdisable argument, which calls GL_DepthTest, as that's broken in the ATI drivers
+               qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_allpixels);
+               qglDepthFunc(GL_ALWAYS);
+               R_DrawSprite(GL_ONE, GL_ZERO, r_shadow_lightcorona, NULL, false, false, centerorigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale, 1, 1, 1, 1);
+               qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
+               qglDepthFunc(GL_LEQUAL);
+               qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_visiblepixels);
+               R_DrawSprite(GL_ONE, GL_ZERO, r_shadow_lightcorona, NULL, false, false, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale, 1, 1, 1, 1);
+               qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
+               CHECKGLERROR
+       }
+       rtlight->corona_visibility = bound(0, (zdist - 32) / 32, 1);
+}
+
+void R_DrawCorona(rtlight_t *rtlight, float cscale, float scale)
+{
+       vec3_t color;
+       GLint allpixels = 0, visiblepixels = 0;
+       // now we have to check the query result
+       if (rtlight->corona_queryindex_visiblepixels)
+       {
+               CHECKGLERROR
+               qglGetQueryObjectivARB(rtlight->corona_queryindex_visiblepixels, GL_QUERY_RESULT_ARB, &visiblepixels);
+               qglGetQueryObjectivARB(rtlight->corona_queryindex_allpixels, GL_QUERY_RESULT_ARB, &allpixels);
+               CHECKGLERROR
+               //Con_Printf("%i of %i pixels\n", (int)visiblepixels, (int)allpixels);
+               if (visiblepixels < 1 || allpixels < 1)
+                       return;
+               rtlight->corona_visibility *= bound(0, (float)visiblepixels / (float)allpixels, 1);
+               cscale *= rtlight->corona_visibility;
+       }
+       else
+       {
+               // FIXME: these traces should scan all render entities instead of cl.world
+               if (CL_Move(r_refdef.view.origin, vec3_origin, vec3_origin, rtlight->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false).fraction < 1)
+                       return;
+       }
+       VectorScale(rtlight->color, cscale, color);
+       if (VectorLength(color) > (1.0f / 256.0f))
+               R_DrawSprite(GL_ONE, GL_ONE, r_shadow_lightcorona, NULL, true, false, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale, color[0], color[1], color[2], 1);
 }
 
 void R_DrawCoronas(void)
 {
        int i, flag;
-       float cscale, scale;
+       qboolean usequery;
        size_t lightindex;
        dlight_t *light;
        rtlight_t *rtlight;
+       size_t range;
        if (r_coronas.value < (1.0f / 256.0f) && !gl_flashblend.integer)
                return;
-       R_Mesh_Matrix(&identitymatrix);
+       if (r_waterstate.renderingscene)
+               return;
        flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
-       // FIXME: these traces should scan all render entities instead of cl.world
-       for (lightindex = 0;lightindex < Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);lightindex++)
+       R_Mesh_Matrix(&identitymatrix);
+
+       range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
+
+       // check occlusion of coronas
+       // use GL_ARB_occlusion_query if available
+       // otherwise use raytraces
+       r_numqueries = 0;
+       usequery = gl_support_arb_occlusion_query && r_coronas_occlusionquery.integer;
+       if (usequery)
+       {
+               GL_ColorMask(0,0,0,0);
+               if (r_maxqueries < (range + r_refdef.scene.numlights) * 2)
+               if (r_maxqueries < R_MAX_OCCLUSION_QUERIES)
+               {
+                       i = r_maxqueries;
+                       r_maxqueries = (range + r_refdef.scene.numlights) * 4;
+                       r_maxqueries = min(r_maxqueries, R_MAX_OCCLUSION_QUERIES);
+                       CHECKGLERROR
+                       qglGenQueriesARB(r_maxqueries - i, r_queries + i);
+                       CHECKGLERROR
+               }
+       }
+       for (lightindex = 0;lightindex < range;lightindex++)
        {
-               light = Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
+               light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
                if (!light)
                        continue;
                rtlight = &light->rtlight;
+               rtlight->corona_visibility = 0;
+               rtlight->corona_queryindex_visiblepixels = 0;
+               rtlight->corona_queryindex_allpixels = 0;
                if (!(rtlight->flags & flag))
                        continue;
-               if (rtlight->corona * r_coronas.value <= 0)
+               if (rtlight->corona <= 0)
                        continue;
                if (r_shadow_debuglight.integer >= 0 && r_shadow_debuglight.integer != (int)lightindex)
                        continue;
-               cscale = rtlight->corona * r_coronas.value* 0.25f;
-               scale = rtlight->radius * rtlight->coronasizescale;
-               if (VectorDistance2(rtlight->shadoworigin, r_refdef.view.origin) < 16.0f * 16.0f)
-                       continue;
-               if (CL_Move(r_refdef.view.origin, vec3_origin, vec3_origin, rtlight->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false).fraction < 1)
-                       continue;
-               R_DrawSprite(GL_ONE, GL_ONE, r_shadow_lightcorona, NULL, true, false, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale, rtlight->color[0] * cscale, rtlight->color[1] * cscale, rtlight->color[2] * cscale, 1);
+               R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
        }
        for (i = 0;i < r_refdef.scene.numlights;i++)
        {
-               rtlight = &r_refdef.scene.lights[i];
+               rtlight = r_refdef.scene.lights[i];
+               rtlight->corona_visibility = 0;
+               rtlight->corona_queryindex_visiblepixels = 0;
+               rtlight->corona_queryindex_allpixels = 0;
                if (!(rtlight->flags & flag))
                        continue;
                if (rtlight->corona <= 0)
                        continue;
-               if (VectorDistance2(rtlight->shadoworigin, r_refdef.view.origin) < 32.0f * 32.0f)
+               R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
+       }
+       if (usequery)
+               GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
+
+       // now draw the coronas using the query data for intensity info
+       for (lightindex = 0;lightindex < range;lightindex++)
+       {
+               light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
+               if (!light)
                        continue;
-               if (gl_flashblend.integer)
-               {
-                       cscale = rtlight->corona * 1.0f;
-                       scale = rtlight->radius * rtlight->coronasizescale * 2.0f;
-               }
-               else
-               {
-                       cscale = rtlight->corona * r_coronas.value* 0.25f;
-                       scale = rtlight->radius * rtlight->coronasizescale;
-               }
-               if (VectorLength(rtlight->color) * cscale < (1.0f / 256.0f))
+               rtlight = &light->rtlight;
+               if (rtlight->corona_visibility <= 0)
                        continue;
-               if (CL_Move(r_refdef.view.origin, vec3_origin, vec3_origin, rtlight->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false).fraction < 1)
+               R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
+       }
+       for (i = 0;i < r_refdef.scene.numlights;i++)
+       {
+               rtlight = r_refdef.scene.lights[i];
+               if (rtlight->corona_visibility <= 0)
                        continue;
-               R_DrawSprite(GL_ONE, GL_ONE, r_shadow_lightcorona, NULL, true, false, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale, rtlight->color[0] * cscale, rtlight->color[1] * cscale, rtlight->color[2] * cscale, 1);
+               if (gl_flashblend.integer)
+                       R_DrawCorona(rtlight, rtlight->corona, rtlight->radius * rtlight->coronasizescale * 2.0f);
+               else
+                       R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
        }
 }
 
@@ -3394,7 +4076,7 @@ rtexture_t *R_Shadow_LoadCubemap(const char *basename)
 
                if (!r_shadow_filters_texturepool)
                        r_shadow_filters_texturepool = R_AllocTexturePool();
-               cubemaptexture = R_LoadTextureCubeMap(r_shadow_filters_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_BGRA, TEXF_PRECACHE | (gl_texturecompression_lightcubemaps.integer ? TEXF_COMPRESS : 0), NULL);
+               cubemaptexture = R_LoadTextureCubeMap(r_shadow_filters_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_BGRA, TEXF_PRECACHE | (gl_texturecompression_lightcubemaps.integer ? TEXF_COMPRESS : 0) | TEXF_FORCELINEAR, NULL);
                Mem_Free(cubemappixels);
        }
        else
@@ -3494,9 +4176,10 @@ void R_Shadow_ClearWorldLights(void)
 {
        size_t lightindex;
        dlight_t *light;
-       for (lightindex = 0;lightindex < Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);lightindex++)
+       size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
+       for (lightindex = 0;lightindex < range;lightindex++)
        {
-               light = Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
+               light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
                if (light)
                        R_Shadow_FreeWorldLight(light);
        }
@@ -3557,9 +4240,10 @@ void R_Shadow_DrawLightSprites(void)
 {
        size_t lightindex;
        dlight_t *light;
-       for (lightindex = 0;lightindex < Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);lightindex++)
+       size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
+       for (lightindex = 0;lightindex < range;lightindex++)
        {
-               light = Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
+               light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
                if (light)
                        R_MeshQueue_AddTransparent(light->origin, R_Shadow_DrawLightSprite_TransparentCallback, (entity_render_t *)light, 5, &light->rtlight);
        }
@@ -3572,11 +4256,12 @@ void R_Shadow_SelectLightInView(void)
        dlight_t *best;
        size_t lightindex;
        dlight_t *light;
+       size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
        best = NULL;
        bestrating = 0;
-       for (lightindex = 0;lightindex < Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);lightindex++)
+       for (lightindex = 0;lightindex < range;lightindex++)
        {
-               light = Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
+               light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
                if (!light)
                        continue;
                VectorSubtract(light->origin, r_refdef.view.origin, temp);
@@ -3643,7 +4328,18 @@ void R_Shadow_LoadWorldLights(void)
                                t++;
                        }
                        *s = 0;
-                       a = sscanf(t, "%f %f %f %f %f %f %f %d %s %f %f %f %f %f %f %f %f %i", &origin[0], &origin[1], &origin[2], &radius, &color[0], &color[1], &color[2], &style, cubemapname, &corona, &angles[0], &angles[1], &angles[2], &coronasizescale, &ambientscale, &diffusescale, &specularscale, &flags);
+#if _MSC_VER >= 1400
+#define sscanf sscanf_s
+#endif
+                       cubemapname[sizeof(cubemapname)-1] = 0;
+#if MAX_QPATH != 128
+#error update this code if MAX_QPATH changes
+#endif
+                       a = sscanf(t, "%f %f %f %f %f %f %f %d %127s %f %f %f %f %f %f %f %f %i", &origin[0], &origin[1], &origin[2], &radius, &color[0], &color[1], &color[2], &style, cubemapname
+#if _MSC_VER >= 1400
+, sizeof(cubemapname)
+#endif
+, &corona, &angles[0], &angles[1], &angles[2], &coronasizescale, &ambientscale, &diffusescale, &specularscale, &flags);
                        *s = tempchar;
                        if (a < 18)
                                flags = LIGHTFLAG_REALTIMEMODE;
@@ -3695,7 +4391,9 @@ void R_Shadow_SaveWorldLights(void)
        char *buf, *oldbuf;
        char name[MAX_QPATH];
        char line[MAX_INPUTLINE];
-       if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
+       size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked, assuming the dpsnprintf mess doesn't screw it up...
+       // I hate lines which are 3 times my screen size :( --blub
+       if (!range)
                return;
        if (cl.worldmodel == NULL)
        {
@@ -3706,17 +4404,17 @@ void R_Shadow_SaveWorldLights(void)
        strlcat (name, ".rtlights", sizeof (name));
        bufchars = bufmaxchars = 0;
        buf = NULL;
-       for (lightindex = 0;lightindex < Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);lightindex++)
+       for (lightindex = 0;lightindex < range;lightindex++)
        {
-               light = Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
+               light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
                if (!light)
                        continue;
                if (light->coronasizescale != 0.25f || light->ambientscale != 0 || light->diffusescale != 1 || light->specularscale != 1 || light->flags != LIGHTFLAG_REALTIMEMODE)
-                       sprintf(line, "%s%f %f %f %f %f %f %f %d \"%s\" %f %f %f %f %f %f %f %f %i\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style, light->cubemapname, light->corona, light->angles[0], light->angles[1], light->angles[2], light->coronasizescale, light->ambientscale, light->diffusescale, light->specularscale, light->flags);
+                       dpsnprintf(line, sizeof(line), "%s%f %f %f %f %f %f %f %d \"%s\" %f %f %f %f %f %f %f %f %i\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style, light->cubemapname, light->corona, light->angles[0], light->angles[1], light->angles[2], light->coronasizescale, light->ambientscale, light->diffusescale, light->specularscale, light->flags);
                else if (light->cubemapname[0] || light->corona || light->angles[0] || light->angles[1] || light->angles[2])
-                       sprintf(line, "%s%f %f %f %f %f %f %f %d \"%s\" %f %f %f %f\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style, light->cubemapname, light->corona, light->angles[0], light->angles[1], light->angles[2]);
+                       dpsnprintf(line, sizeof(line), "%s%f %f %f %f %f %f %f %d \"%s\" %f %f %f %f\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style, light->cubemapname, light->corona, light->angles[0], light->angles[1], light->angles[2]);
                else
-                       sprintf(line, "%s%f %f %f %f %f %f %f %d\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style);
+                       dpsnprintf(line, sizeof(line), "%s%f %f %f %f %f %f %f %d\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style);
                if (bufchars + strlen(line) > bufmaxchars)
                {
                        bufmaxchars = bufchars + strlen(line) + 2048;
@@ -4423,6 +5121,7 @@ void R_Shadow_EditLights_EditAll_f(void)
 {
        size_t lightindex;
        dlight_t *light;
+       size_t range;
 
        if (!r_editlights.integer)
        {
@@ -4430,9 +5129,11 @@ void R_Shadow_EditLights_EditAll_f(void)
                return;
        }
 
-       for (lightindex = 0;lightindex < Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);lightindex++)
+       // EditLights doesn't seem to have a "remove" command or something so:
+       range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
+       for (lightindex = 0;lightindex < range;lightindex++)
        {
-               light = Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
+               light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
                if (!light)
                        continue;
                R_Shadow_SelectLight(light);
@@ -4443,7 +5144,7 @@ void R_Shadow_EditLights_EditAll_f(void)
 void R_Shadow_EditLights_DrawSelectedLightProperties(void)
 {
        int lightnumber, lightcount;
-       size_t lightindex;
+       size_t lightindex, range;
        dlight_t *light;
        float x, y;
        char temp[256];
@@ -4454,35 +5155,36 @@ void R_Shadow_EditLights_DrawSelectedLightProperties(void)
        DrawQ_Pic(x-5, y-5, NULL, 250, 155, 0, 0, 0, 0.75, 0);
        lightnumber = -1;
        lightcount = 0;
-       for (lightindex = 0;lightindex < Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);lightindex++)
+       range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
+       for (lightindex = 0;lightindex < range;lightindex++)
        {
-               light = Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
+               light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
                if (!light)
                        continue;
                if (light == r_shadow_selectedlight)
                        lightnumber = lightindex;
                lightcount++;
        }
-       sprintf(temp, "Cursor origin: %.0f %.0f %.0f", r_editlights_cursorlocation[0], r_editlights_cursorlocation[1], r_editlights_cursorlocation[2]); DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, false);y += 8;
-       sprintf(temp, "Total lights : %i active (%i total)", lightcount, (int)Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray)); DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, false);y += 8;
+       dpsnprintf(temp, sizeof(temp), "Cursor origin: %.0f %.0f %.0f", r_editlights_cursorlocation[0], r_editlights_cursorlocation[1], r_editlights_cursorlocation[2]); DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, false);y += 8;
+       dpsnprintf(temp, sizeof(temp), "Total lights : %i active (%i total)", lightcount, (int)Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray)); DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, false);y += 8;
        y += 8;
        if (r_shadow_selectedlight == NULL)
                return;
-       sprintf(temp, "Light #%i properties:", lightnumber);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
-       sprintf(temp, "Origin       : %.0f %.0f %.0f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
-       sprintf(temp, "Angles       : %.0f %.0f %.0f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
-       sprintf(temp, "Color        : %.2f %.2f %.2f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
-       sprintf(temp, "Radius       : %.0f\n", r_shadow_selectedlight->radius);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
-       sprintf(temp, "Corona       : %.0f\n", r_shadow_selectedlight->corona);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
-       sprintf(temp, "Style        : %i\n", r_shadow_selectedlight->style);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
-       sprintf(temp, "Shadows      : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
-       sprintf(temp, "Cubemap      : %s\n", r_shadow_selectedlight->cubemapname);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
-       sprintf(temp, "CoronaSize   : %.2f\n", r_shadow_selectedlight->coronasizescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
-       sprintf(temp, "Ambient      : %.2f\n", r_shadow_selectedlight->ambientscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
-       sprintf(temp, "Diffuse      : %.2f\n", r_shadow_selectedlight->diffusescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
-       sprintf(temp, "Specular     : %.2f\n", r_shadow_selectedlight->specularscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
-       sprintf(temp, "NormalMode   : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
-       sprintf(temp, "RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
+       dpsnprintf(temp, sizeof(temp), "Light #%i properties:", lightnumber);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
+       dpsnprintf(temp, sizeof(temp), "Origin       : %.0f %.0f %.0f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
+       dpsnprintf(temp, sizeof(temp), "Angles       : %.0f %.0f %.0f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
+       dpsnprintf(temp, sizeof(temp), "Color        : %.2f %.2f %.2f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
+       dpsnprintf(temp, sizeof(temp), "Radius       : %.0f\n", r_shadow_selectedlight->radius);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
+       dpsnprintf(temp, sizeof(temp), "Corona       : %.0f\n", r_shadow_selectedlight->corona);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
+       dpsnprintf(temp, sizeof(temp), "Style        : %i\n", r_shadow_selectedlight->style);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
+       dpsnprintf(temp, sizeof(temp), "Shadows      : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
+       dpsnprintf(temp, sizeof(temp), "Cubemap      : %s\n", r_shadow_selectedlight->cubemapname);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
+       dpsnprintf(temp, sizeof(temp), "CoronaSize   : %.2f\n", r_shadow_selectedlight->coronasizescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
+       dpsnprintf(temp, sizeof(temp), "Ambient      : %.2f\n", r_shadow_selectedlight->ambientscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
+       dpsnprintf(temp, sizeof(temp), "Diffuse      : %.2f\n", r_shadow_selectedlight->diffusescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
+       dpsnprintf(temp, sizeof(temp), "Specular     : %.2f\n", r_shadow_selectedlight->specularscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
+       dpsnprintf(temp, sizeof(temp), "NormalMode   : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
+       dpsnprintf(temp, sizeof(temp), "RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8;
 }
 
 void R_Shadow_EditLights_ToggleShadow_f(void)
@@ -4684,7 +5386,7 @@ void R_CompleteLightPoint(vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffu
                rtlight_t *light;
                for (i = 0;i < r_refdef.scene.numlights;i++)
                {
-                       light = &r_refdef.scene.lights[i];
+                       light = r_refdef.scene.lights[i];
                        Matrix4x4_Transform(&light->matrix_worldtolight, p, v);
                        f = 1 - VectorLength2(v);
                        if (f > 0 && CL_Move(p, vec3_origin, vec3_origin, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false).fraction == 1)