]> git.xonotic.org Git - xonotic/darkplaces.git/blobdiff - gl_rmain.c
Oops. Add more ifdeffery to the NvOptimus stuff :)
[xonotic/darkplaces.git] / gl_rmain.c
index 76931c357033927c4a79cf27b092438d881776ba..3f8ba42d408d3c827dd787a72abbb30f1b9ebf54 100644 (file)
@@ -34,6 +34,17 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
 #endif
 
+#ifdef WIN32
+// Enable NVIDIA High Performance Graphics while using Integrated Graphics.
+#ifdef __cplusplus
+extern "C" {
+#endif
+__declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
+#ifdef __cplusplus
+}
+#endif
+#endif
+
 mempool_t *r_main_mempool;
 rtexturepool_t *r_main_texturepool;
 
@@ -184,6 +195,7 @@ cvar_t r_glsl_postprocess_uservec3_enable = {CVAR_SAVE, "r_glsl_postprocess_user
 cvar_t r_glsl_postprocess_uservec4_enable = {CVAR_SAVE, "r_glsl_postprocess_uservec4_enable", "1", "enables postprocessing uservec4 usage, creates USERVEC1 define (only useful if default.glsl has been customized)"};
 
 cvar_t r_water = {CVAR_SAVE, "r_water", "0", "whether to use reflections and refraction on water surfaces (note: r_wateralpha must be set below 1)"};
+cvar_t r_water_cameraentitiesonly = {CVAR_SAVE, "r_water_cameraentitiesonly", "0", "whether to only show QC-defined reflections/refractions (typically used for camera- or portal-like effects)"};
 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
 cvar_t r_water_resolutionmultiplier = {CVAR_SAVE, "r_water_resolutionmultiplier", "0.5", "multiplier for screen resolution when rendering refracted/reflected scenes, 1 is full quality, lower values are faster"};
 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
@@ -678,7 +690,8 @@ shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
        {"#define USETRIPPY\n", " trippy"},
        {"#define USEDEPTHRGB\n", " depthrgb"},
        {"#define USEALPHAGENVERTEX\n", " alphagenvertex"},
-       {"#define USESKELETAL\n", " skeletal"}
+       {"#define USESKELETAL\n", " skeletal"},
+       {"#define USEOCCLUDE\n", " occlude"}
 };
 
 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
@@ -881,8 +894,9 @@ enum
        SHADERSTATICPARM_SHADOWSAMPLER = 10, ///< sampler
        SHADERSTATICPARM_CELSHADING = 11, ///< celshading (alternative diffuse and specular math)
        SHADERSTATICPARM_CELOUTLINES = 12, ///< celoutline (depth buffer analysis to produce outlines)
+       SHADERSTATICPARM_FXAA = 13 ///< fast approximate anti aliasing
 };
-#define SHADERSTATICPARMS_COUNT 13
+#define SHADERSTATICPARMS_COUNT 14
 
 static const char *shaderstaticparmstrings_list[SHADERSTATICPARMS_COUNT];
 static int shaderstaticparms_count = 0;
@@ -894,7 +908,7 @@ extern qboolean r_shadow_shadowmapsampler;
 extern int r_shadow_shadowmappcf;
 qboolean R_CompileShader_CheckStaticParms(void)
 {
-       static int r_compileshader_staticparms_save[1];
+       static int r_compileshader_staticparms_save[(SHADERSTATICPARMS_COUNT + 0x1F) >> 5];
        memcpy(r_compileshader_staticparms_save, r_compileshader_staticparms, sizeof(r_compileshader_staticparms));
        memset(r_compileshader_staticparms, 0, sizeof(r_compileshader_staticparms));
 
@@ -916,6 +930,8 @@ qboolean R_CompileShader_CheckStaticParms(void)
                if (r_glsl_postprocess_uservec4_enable.integer)
                        R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC4);
        }
+       if (r_fxaa.integer)
+               R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_FXAA);
        if (r_glsl_offsetmapping_lod.integer && r_glsl_offsetmapping_lod_distance.integer > 0)
                R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_OFFSETMAPPING_USELOD);
 
@@ -956,6 +972,7 @@ static void R_CompileShader_AddStaticParms(unsigned int mode, unsigned int permu
        R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_SHADOWSAMPLER, "USESHADOWSAMPLER");
        R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_CELSHADING, "USECELSHADING");
        R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_CELOUTLINES, "USECELOUTLINES");
+       R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_FXAA, "USEFXAA");
 }
 
 /// information about each possible shader permutation
@@ -1625,7 +1642,7 @@ static void R_HLSL_CacheShader(r_hlsl_permutation_t *p, const char *cachename, c
                                        vsresult = qD3DXCompileShaderFromFileA(va(vabuf, sizeof(vabuf), "%s/%s_vs.fx", fs_gamedir, cachename), NULL, NULL, "main", vsversion, shaderflags, &vsbuffer, &vslog, &vsconstanttable);
                                }
                                else
-                                       vsresult = qD3DXCompileShader(vertstring, strlen(vertstring), NULL, NULL, "main", vsversion, shaderflags, &vsbuffer, &vslog, &vsconstanttable);
+                                       vsresult = qD3DXCompileShader(vertstring, (unsigned int)strlen(vertstring), NULL, NULL, "main", vsversion, shaderflags, &vsbuffer, &vslog, &vsconstanttable);
                                if (vsbuffer)
                                {
                                        vsbinsize = ID3DXBuffer_GetBufferSize(vsbuffer);
@@ -1648,7 +1665,7 @@ static void R_HLSL_CacheShader(r_hlsl_permutation_t *p, const char *cachename, c
                                        psresult = qD3DXCompileShaderFromFileA(va(vabuf, sizeof(vabuf), "%s/%s_ps.fx", fs_gamedir, cachename), NULL, NULL, "main", psversion, shaderflags, &psbuffer, &pslog, &psconstanttable);
                                }
                                else
-                                       psresult = qD3DXCompileShader(fragstring, strlen(fragstring), NULL, NULL, "main", psversion, shaderflags, &psbuffer, &pslog, &psconstanttable);
+                                       psresult = qD3DXCompileShader(fragstring, (unsigned int)strlen(fragstring), NULL, NULL, "main", psversion, shaderflags, &psbuffer, &pslog, &psconstanttable);
                                if (psbuffer)
                                {
                                        psbinsize = ID3DXBuffer_GetBufferSize(psbuffer);
@@ -1776,23 +1793,23 @@ static void R_HLSL_CompilePermutation(r_hlsl_permutation_t *p, unsigned int mode
 
        vertstring_length = 0;
        for (i = 0;i < vertstrings_count;i++)
-               vertstring_length += strlen(vertstrings_list[i]);
+               vertstring_length += (int)strlen(vertstrings_list[i]);
        vertstring = t = (char *)Mem_Alloc(tempmempool, vertstring_length + 1);
-       for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
+       for (i = 0;i < vertstrings_count;t += (int)strlen(vertstrings_list[i]), i++)
                memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
 
        geomstring_length = 0;
        for (i = 0;i < geomstrings_count;i++)
-               geomstring_length += strlen(geomstrings_list[i]);
+               geomstring_length += (int)strlen(geomstrings_list[i]);
        geomstring = t = (char *)Mem_Alloc(tempmempool, geomstring_length + 1);
-       for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
+       for (i = 0;i < geomstrings_count;t += (int)strlen(geomstrings_list[i]), i++)
                memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
 
        fragstring_length = 0;
        for (i = 0;i < fragstrings_count;i++)
-               fragstring_length += strlen(fragstrings_list[i]);
+               fragstring_length += (int)strlen(fragstrings_list[i]);
        fragstring = t = (char *)Mem_Alloc(tempmempool, fragstring_length + 1);
-       for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
+       for (i = 0;i < fragstrings_count;t += (int)strlen(fragstrings_list[i]), i++)
                memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
 
        // try to load the cached shader, or generate one
@@ -1896,7 +1913,7 @@ void R_GLSL_Restart_f(void)
                {
                        r_hlsl_permutation_t *p;
                        r_hlsl_permutation = NULL;
-                       limit = Mem_ExpandableArray_IndexRange(&r_hlsl_permutationarray);
+                       limit = (unsigned int)Mem_ExpandableArray_IndexRange(&r_hlsl_permutationarray);
                        for (i = 0;i < limit;i++)
                        {
                                if ((p = (r_hlsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_hlsl_permutationarray, i)))
@@ -1923,7 +1940,7 @@ void R_GLSL_Restart_f(void)
                {
                        r_glsl_permutation_t *p;
                        r_glsl_permutation = NULL;
-                       limit = Mem_ExpandableArray_IndexRange(&r_glsl_permutationarray);
+                       limit = (unsigned int)Mem_ExpandableArray_IndexRange(&r_glsl_permutationarray);
                        for (i = 0;i < limit;i++)
                        {
                                if ((p = (r_glsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_glsl_permutationarray, i)))
@@ -2198,6 +2215,8 @@ void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting,
                permutation |= SHADERPERMUTATION_TRIPPY;
        if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
                permutation |= SHADERPERMUTATION_ALPHAKILL;
+       if (rsurface.texture->currentmaterialflags & MATERIALFLAG_OCCLUDE)
+               permutation |= SHADERPERMUTATION_OCCLUDE;
        if (rsurface.texture->r_water_waterscroll[0] && rsurface.texture->r_water_waterscroll[1])
                permutation |= SHADERPERMUTATION_NORMALMAPSCROLLBLEND; // todo: make generic
        if (rsurfacepass == RSURFPASS_BACKGROUND)
@@ -3162,7 +3181,7 @@ void R_SetupShader_DeferredLight(const rtlight_t *rtlight)
 
 typedef struct
 {
-       int loadsequence; // incremented each level change
+       unsigned int loadsequence; // incremented each level change
        memexpandablearray_t array;
        skinframe_t *hash[SKINFRAME_HASH];
 }
@@ -3396,6 +3415,7 @@ skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboole
        skinframe->fog = NULL;
        skinframe->reflect = NULL;
        skinframe->hasalpha = false;
+       // we could store the q2animname here too
 
        if (ddsbase)
        {
@@ -4367,6 +4387,7 @@ void GL_Main_Init(void)
        Cvar_RegisterVariable(&r_celoutlines);
 
        Cvar_RegisterVariable(&r_water);
+       Cvar_RegisterVariable(&r_water_cameraentitiesonly);
        Cvar_RegisterVariable(&r_water_resolutionmultiplier);
        Cvar_RegisterVariable(&r_water_clippingplanebias);
        Cvar_RegisterVariable(&r_water_refractdistort);
@@ -4489,9 +4510,6 @@ int R_CullBox(const vec3_t mins, const vec3_t maxs)
                return false;
        for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
        {
-               // skip nearclip plane, it often culls portals when you are very close, and is almost never useful
-               if (i == 4)
-                       continue;
                p = r_refdef.view.frustum + i;
                switch(p->signbits)
                {
@@ -4831,7 +4849,7 @@ r_meshbuffer_t *R_BufferData_Store(size_t datasize, const void *data, r_bufferda
                Sys_Error("R_BufferData_Store: failed to create a new buffer of sufficient size\n");
 
        mem = r_bufferdata_buffer[r_bufferdata_cycle][type];
-       offset = mem->current;
+       offset = (int)mem->current;
        mem->current += padsize;
 
        // upload the data to the buffer at the chosen offset
@@ -5209,18 +5227,20 @@ static void R_View_UpdateEntityVisible (void)
        int samples;
        entity_render_t *ent;
 
-       renderimask = r_refdef.envmap                                    ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
-               : r_fb.water.hideplayer                                      ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
-               : (chase_active.integer || r_fb.water.renderingscene)  ? RENDER_VIEWMODEL
-               :                                                          RENDER_EXTERIORMODEL;
+       if (r_refdef.envmap || r_fb.water.hideplayer)
+               renderimask = RENDER_EXTERIORMODEL | RENDER_VIEWMODEL;
+       else if (chase_active.integer || r_fb.water.renderingscene)
+               renderimask = RENDER_VIEWMODEL;
+       else
+               renderimask = RENDER_EXTERIORMODEL;
        if (!r_drawviewmodel.integer)
                renderimask |= RENDER_VIEWMODEL;
        if (!r_drawexteriormodel.integer)
                renderimask |= RENDER_EXTERIORMODEL;
+       memset(r_refdef.viewcache.entityvisible, 0, r_refdef.scene.numentities);
        if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs)
        {
                // worldmodel can check visibility
-               memset(r_refdef.viewcache.entityvisible, 0, r_refdef.scene.numentities);
                for (i = 0;i < r_refdef.scene.numentities;i++)
                {
                        ent = r_refdef.scene.entities[i];
@@ -5236,10 +5256,12 @@ static void R_View_UpdateEntityVisible (void)
                for (i = 0;i < r_refdef.scene.numentities;i++)
                {
                        ent = r_refdef.scene.entities[i];
-                       r_refdef.viewcache.entityvisible[i] = !(ent->flags & renderimask) && ((ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)) || !R_CullBox(ent->mins, ent->maxs));
+                       if (!(ent->flags & renderimask))
+                       if (!R_CullBox(ent->mins, ent->maxs) || (ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)))
+                               r_refdef.viewcache.entityvisible[i] = true;
                }
        }
-       if(r_cullentities_trace.integer && r_refdef.scene.worldmodel->brush.TraceLineOfSight && !r_refdef.view.useclipplane && !r_trippy.integer)
+       if(r_cullentities_trace.integer && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.TraceLineOfSight && !r_refdef.view.useclipplane && !r_trippy.integer)
                // sorry, this check doesn't work for portal/reflection/refraction renders as the view origin is not useful for culling
        {
                for (i = 0;i < r_refdef.scene.numentities;i++)
@@ -5992,25 +6014,33 @@ void R_Water_AddWaterPlane(msurface_t *surface, int entno)
                }
        }
        planeindex = bestplaneindex;
-       p = r_fb.water.waterplanes + planeindex;
 
        // if this surface does not fit any known plane rendered this frame, add one
-       if ((planeindex < 0 || bestplanescore > 0.001f) && r_fb.water.numwaterplanes < r_fb.water.maxwaterplanes)
+       if (planeindex < 0 || bestplanescore > 0.001f)
        {
-               // store the new plane
-               planeindex = r_fb.water.numwaterplanes++;
-               p = r_fb.water.waterplanes + planeindex;
-               p->plane = plane;
-               // clear materialflags and pvs
-               p->materialflags = 0;
-               p->pvsvalid = false;
-               p->camera_entity = t->camera_entity;
-               VectorCopy(mins, p->mins);
-               VectorCopy(maxs, p->maxs);
+               if (r_fb.water.numwaterplanes < r_fb.water.maxwaterplanes)
+               {
+                       // store the new plane
+                       planeindex = r_fb.water.numwaterplanes++;
+                       p = r_fb.water.waterplanes + planeindex;
+                       p->plane = plane;
+                       // clear materialflags and pvs
+                       p->materialflags = 0;
+                       p->pvsvalid = false;
+                       p->camera_entity = t->camera_entity;
+                       VectorCopy(mins, p->mins);
+                       VectorCopy(maxs, p->maxs);
+               }
+               else
+               {
+                       // We're totally screwed.
+                       return;
+               }
        }
        else
        {
                // merge mins/maxs when we're adding this surface to the plane
+               p = r_fb.water.waterplanes + planeindex;
                p->mins[0] = min(p->mins[0], mins[0]);
                p->mins[1] = min(p->mins[1], mins[1]);
                p->mins[2] = min(p->mins[2], mins[2]);
@@ -6023,7 +6053,7 @@ void R_Water_AddWaterPlane(msurface_t *surface, int entno)
        if(!(p->materialflags & MATERIALFLAG_CAMERA))
        {
                // merge this surface's PVS into the waterplane
-               if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS
+               if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS
                 && r_refdef.scene.worldmodel->brush.PointInLeaf && r_refdef.scene.worldmodel->brush.PointInLeaf(r_refdef.scene.worldmodel, center)->clusterindex >= 0)
                {
                        r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, center, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
@@ -6075,6 +6105,8 @@ static void R_Water_ProcessPlanes(int fbo, rtexture_t *depthtexture, rtexture_t
        // make sure enough textures are allocated
        for (planeindex = 0, p = r_fb.water.waterplanes;planeindex < r_fb.water.numwaterplanes;planeindex++, p++)
        {
+               if (r_water_cameraentitiesonly.value != 0 && !p->camera_entity)
+                       continue;
                if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
                {
                        if (!p->texture_refraction)
@@ -6130,6 +6162,8 @@ static void R_Water_ProcessPlanes(int fbo, rtexture_t *depthtexture, rtexture_t
        r_fb.water.renderingscene = true;
        for (planeindex = 0, p = r_fb.water.waterplanes;planeindex < r_fb.water.numwaterplanes;planeindex++, p++)
        {
+               if (r_water_cameraentitiesonly.value != 0 && !p->camera_entity)
+                       continue;
                if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
                {
                        r_refdef.view = myview;
@@ -6157,7 +6191,7 @@ static void R_Water_ProcessPlanes(int fbo, rtexture_t *depthtexture, rtexture_t
                                        memset(r_refdef.viewcache.world_pvsbits, 0xFF, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
                        }
 
-                       r_fb.water.hideplayer = r_water_hideplayer.integer >= 2;
+                       r_fb.water.hideplayer = ((r_water_hideplayer.integer >= 2) && !chase_active.integer);
                        R_ResetViewRendering3D(p->fbo_reflection, r_fb.water.depthtexture, p->texture_reflection);
                        R_ClearScreen(r_refdef.fogenabled);
                        if(r_water_scissormode.integer & 2)
@@ -6186,7 +6220,7 @@ static void R_Water_ProcessPlanes(int fbo, rtexture_t *depthtexture, rtexture_t
                                        continue; // FIXME the plane then still may get rendered but with broken texture, but it sure won't be visible
                        }
 
-                       r_fb.water.hideplayer = r_water_hideplayer.integer >= 1;
+                       r_fb.water.hideplayer = ((r_water_hideplayer.integer >= 1) && !chase_active.integer);
 
                        r_refdef.view.clipplane = p->plane;
                        VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
@@ -6407,7 +6441,7 @@ static void R_Bloom_StartFrame(void)
                Cvar_SetValueQuick(&r_damageblur, 0);
        }
 
-       if (!(r_glsl_postprocess.integer || (!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) || (v_glslgamma.integer && !vid_gammatables_trivial))
+       if (!((r_glsl_postprocess.integer || r_fxaa.integer) || (!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) || (v_glslgamma.integer && !vid_gammatables_trivial))
         && !r_bloom.integer
         && (R_Stereo_Active() || (r_motionblur.value <= 0 && r_damageblur.value <= 0))
         && !useviewfbo
@@ -8003,6 +8037,7 @@ static void R_tcMod_ApplyToMatrix(matrix4x4_t *texmatrix, q3shaderinfo_layer_tcm
        int w, h, idx;
        float shadertime;
        float f;
+       float offsetd[2];
        float tcmat[12];
        matrix4x4_t matrix, temp;
        // if shadertime exceeds about 9 hours (32768 seconds), just wrap it,
@@ -8039,10 +8074,12 @@ static void R_tcMod_ApplyToMatrix(matrix4x4_t *texmatrix, q3shaderinfo_layer_tcm
                        Matrix4x4_CreateScale3(&matrix, tcmod->parms[0], tcmod->parms[1], 1);
                        break;
                case Q3TCMOD_SCROLL:
-                       // this particular tcmod is the most prone to precision breakdown
-                       // at large values, but as we wrap shadertime it won't be obvious
-                       // in practice.
-                       Matrix4x4_CreateTranslate(&matrix, tcmod->parms[0] * rsurface.shadertime, tcmod->parms[1] * rsurface.shadertime, 0);
+                       // this particular tcmod is a "bug for bug" compatible one with regards to
+                       // Quake3, the wrapping is unnecessary with our shadetime fix but quake3
+                       // specifically did the wrapping and so we must mimic that...
+                       offsetd[0] = tcmod->parms[0] * rsurface.shadertime;
+                       offsetd[1] = tcmod->parms[1] * rsurface.shadertime;
+                       Matrix4x4_CreateTranslate(&matrix, offsetd[0] - floor(offsetd[0]), offsetd[1] - floor(offsetd[1]), 0);
                        break;
                case Q3TCMOD_PAGE: // poor man's animmap (to store animations into a single file, useful for HTTP downloaded textures)
                        w = (int) tcmod->parms[0];
@@ -8135,7 +8172,9 @@ texture_t *R_GetCurrentTexture(texture_t *t)
                {
                        // use an alternate animation if the entity's frame is not 0,
                        // and only if the texture has an alternate animation
-                       if (rsurface.ent_alttextures && t->anim_total[1])
+                       if (t->animated == 2) // q2bsp
+                               t = t->anim_frames[0][ent->framegroupblend[0].frame % t->anim_total[0]];
+                       else if (rsurface.ent_alttextures && t->anim_total[1])
                                t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(rsurface.shadertime * 5.0f) % t->anim_total[1]) : 0];
                        else
                                t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(rsurface.shadertime * 5.0f) % t->anim_total[0]) : 0];
@@ -8166,7 +8205,7 @@ texture_t *R_GetCurrentTexture(texture_t *t)
                t->backgroundcurrentskinframe = t->backgroundskinframes[LoopingFrameNumberFromDouble(rsurface.shadertime * t->backgroundskinframerate, t->backgroundnumskinframes)];
 
        t->currentmaterialflags = t->basematerialflags;
-       t->currentalpha = rsurface.colormod[3];
+       t->currentalpha = rsurface.colormod[3] * t->basealpha;
        if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer || r_trippy.integer))
                t->currentalpha *= r_wateralpha.value;
        if(t->basematerialflags & MATERIALFLAG_WATERSHADER && r_fb.water.enabled && !r_refdef.view.isoverlay)
@@ -8409,7 +8448,7 @@ texture_t *R_GetCurrentTexture(texture_t *t)
                }
        }
 
-       return t->currentframe;
+       return t;
 }
 
 rsurfacestate_t rsurface;
@@ -10087,77 +10126,80 @@ void RSurf_PrepareVerticesForBatch(int batchneed, int texturenumsurfaces, const
                }
        }
 
-       // generate texcoords based on the chosen texcoord source
-       switch(rsurface.texture->tcgen.tcgen)
+       if (rsurface.batchtexcoordtexture2f)
        {
-       default:
-       case Q3TCGEN_TEXTURE:
-               break;
-       case Q3TCGEN_LIGHTMAP:
-//             rsurface.batchtexcoordtexture2f = R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
-//             rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
-//             rsurface.batchtexcoordtexture2f_bufferoffset = 0;
-               if (rsurface.batchtexcoordlightmap2f)
-                       memcpy(rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordtexture2f, batchnumvertices * sizeof(float[2]));
-               break;
-       case Q3TCGEN_VECTOR:
-//             rsurface.batchtexcoordtexture2f = R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
-//             rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
-//             rsurface.batchtexcoordtexture2f_bufferoffset = 0;
-               for (j = 0;j < batchnumvertices;j++)
-               {
-                       rsurface.batchtexcoordtexture2f[j*2+0] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms);
-                       rsurface.batchtexcoordtexture2f[j*2+1] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms + 3);
-               }
-               break;
-       case Q3TCGEN_ENVIRONMENT:
-               // make environment reflections using a spheremap
-               rsurface.batchtexcoordtexture2f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
-               rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
-               rsurface.batchtexcoordtexture2f_bufferoffset = 0;
-               for (j = 0;j < batchnumvertices;j++)
+       // generate texcoords based on the chosen texcoord source
+               switch(rsurface.texture->tcgen.tcgen)
                {
-                       // identical to Q3A's method, but executed in worldspace so
-                       // carried models can be shiny too
+               default:
+               case Q3TCGEN_TEXTURE:
+                       break;
+               case Q3TCGEN_LIGHTMAP:
+       //              rsurface.batchtexcoordtexture2f = R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
+       //              rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
+       //              rsurface.batchtexcoordtexture2f_bufferoffset = 0;
+                       if (rsurface.batchtexcoordlightmap2f)
+                               memcpy(rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordlightmap2f, batchnumvertices * sizeof(float[2]));
+                       break;
+               case Q3TCGEN_VECTOR:
+       //              rsurface.batchtexcoordtexture2f = R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
+       //              rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
+       //              rsurface.batchtexcoordtexture2f_bufferoffset = 0;
+                       for (j = 0;j < batchnumvertices;j++)
+                       {
+                               rsurface.batchtexcoordtexture2f[j*2+0] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms);
+                               rsurface.batchtexcoordtexture2f[j*2+1] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms + 3);
+                       }
+                       break;
+               case Q3TCGEN_ENVIRONMENT:
+                       // make environment reflections using a spheremap
+                       rsurface.batchtexcoordtexture2f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
+                       rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
+                       rsurface.batchtexcoordtexture2f_bufferoffset = 0;
+                       for (j = 0;j < batchnumvertices;j++)
+                       {
+                               // identical to Q3A's method, but executed in worldspace so
+                               // carried models can be shiny too
 
-                       float viewer[3], d, reflected[3], worldreflected[3];
+                               float viewer[3], d, reflected[3], worldreflected[3];
 
-                       VectorSubtract(rsurface.localvieworigin, rsurface.batchvertex3f + 3*j, viewer);
-                       // VectorNormalize(viewer);
+                               VectorSubtract(rsurface.localvieworigin, rsurface.batchvertex3f + 3*j, viewer);
+                               // VectorNormalize(viewer);
 
-                       d = DotProduct(rsurface.batchnormal3f + 3*j, viewer);
+                               d = DotProduct(rsurface.batchnormal3f + 3*j, viewer);
 
-                       reflected[0] = rsurface.batchnormal3f[j*3+0]*2*d - viewer[0];
-                       reflected[1] = rsurface.batchnormal3f[j*3+1]*2*d - viewer[1];
-                       reflected[2] = rsurface.batchnormal3f[j*3+2]*2*d - viewer[2];
-                       // note: this is proportinal to viewer, so we can normalize later
+                               reflected[0] = rsurface.batchnormal3f[j*3+0]*2*d - viewer[0];
+                               reflected[1] = rsurface.batchnormal3f[j*3+1]*2*d - viewer[1];
+                               reflected[2] = rsurface.batchnormal3f[j*3+2]*2*d - viewer[2];
+                               // note: this is proportinal to viewer, so we can normalize later
 
-                       Matrix4x4_Transform3x3(&rsurface.matrix, reflected, worldreflected);
-                       VectorNormalize(worldreflected);
+                               Matrix4x4_Transform3x3(&rsurface.matrix, reflected, worldreflected);
+                               VectorNormalize(worldreflected);
 
-                       // note: this sphere map only uses world x and z!
-                       // so positive and negative y will LOOK THE SAME.
-                       rsurface.batchtexcoordtexture2f[j*2+0] = 0.5 + 0.5 * worldreflected[1];
-                       rsurface.batchtexcoordtexture2f[j*2+1] = 0.5 - 0.5 * worldreflected[2];
+                               // note: this sphere map only uses world x and z!
+                               // so positive and negative y will LOOK THE SAME.
+                               rsurface.batchtexcoordtexture2f[j*2+0] = 0.5 + 0.5 * worldreflected[1];
+                               rsurface.batchtexcoordtexture2f[j*2+1] = 0.5 - 0.5 * worldreflected[2];
+                       }
+                       break;
                }
-               break;
-       }
-       // the only tcmod that needs software vertex processing is turbulent, so
-       // check for it here and apply the changes if needed
-       // and we only support that as the first one
-       // (handling a mixture of turbulent and other tcmods would be problematic
-       //  without punting it entirely to a software path)
-       if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
-       {
-               amplitude = rsurface.texture->tcmods[0].parms[1];
-               animpos = rsurface.texture->tcmods[0].parms[2] + rsurface.shadertime * rsurface.texture->tcmods[0].parms[3];
-//             rsurface.batchtexcoordtexture2f = R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
-//             rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
-//             rsurface.batchtexcoordtexture2f_bufferoffset = 0;
-               for (j = 0;j < batchnumvertices;j++)
-               {
-                       rsurface.batchtexcoordtexture2f[j*2+0] += amplitude * sin(((rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+2]) * 1.0 / 1024.0f + animpos) * M_PI * 2);
-                       rsurface.batchtexcoordtexture2f[j*2+1] += amplitude * sin(((rsurface.batchvertex3f[j*3+1]                                ) * 1.0 / 1024.0f + animpos) * M_PI * 2);
+               // the only tcmod that needs software vertex processing is turbulent, so
+               // check for it here and apply the changes if needed
+               // and we only support that as the first one
+               // (handling a mixture of turbulent and other tcmods would be problematic
+               //  without punting it entirely to a software path)
+               if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
+               {
+                       amplitude = rsurface.texture->tcmods[0].parms[1];
+                       animpos = rsurface.texture->tcmods[0].parms[2] + rsurface.shadertime * rsurface.texture->tcmods[0].parms[3];
+       //              rsurface.batchtexcoordtexture2f = R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
+       //              rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
+       //              rsurface.batchtexcoordtexture2f_bufferoffset = 0;
+                       for (j = 0;j < batchnumvertices;j++)
+                       {
+                               rsurface.batchtexcoordtexture2f[j*2+0] += amplitude * sin(((rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+2]) * 1.0 / 1024.0f + animpos) * M_PI * 2);
+                               rsurface.batchtexcoordtexture2f[j*2+1] += amplitude * sin(((rsurface.batchvertex3f[j*3+1]                                ) * 1.0 / 1024.0f + animpos) * M_PI * 2);
+                       }
                }
        }
 
@@ -10647,7 +10689,7 @@ static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, const msurface_
        // in Quake3 maps as it causes problems with q3map2 sky tricks,
        // and skymasking also looks very bad when noclipping outside the
        // level, so don't use it then either.
-       if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_refdef.viewcache.world_novis && !r_trippy.integer)
+       if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.skymasking && r_q1bsp_skymasking.integer && !r_refdef.viewcache.world_novis && !r_trippy.integer)
        {
                R_Mesh_ResetTextureState();
                if (skyrendermasked)
@@ -11609,7 +11651,7 @@ void R_DecalSystem_Reset(decalsystem_t *decalsystem)
        memset(decalsystem, 0, sizeof(*decalsystem));
 }
 
-static void R_DecalSystem_SpawnTriangle(decalsystem_t *decalsystem, const float *v0, const float *v1, const float *v2, const float *t0, const float *t1, const float *t2, const float *c0, const float *c1, const float *c2, int triangleindex, int surfaceindex, int decalsequence)
+static void R_DecalSystem_SpawnTriangle(decalsystem_t *decalsystem, const float *v0, const float *v1, const float *v2, const float *t0, const float *t1, const float *t2, const float *c0, const float *c1, const float *c2, int triangleindex, int surfaceindex, unsigned int decalsequence)
 {
        tridecal_t *decal;
        tridecal_t *decals;
@@ -11689,7 +11731,7 @@ extern cvar_t cl_decals_bias;
 extern cvar_t cl_decals_models;
 extern cvar_t cl_decals_newsystem_intensitymultiplier;
 // baseparms, parms, temps
-static void R_DecalSystem_SplatTriangle(decalsystem_t *decalsystem, float r, float g, float b, float a, float s1, float t1, float s2, float t2, int decalsequence, qboolean dynamic, float (*planes)[4], matrix4x4_t *projection, int triangleindex, int surfaceindex)
+static void R_DecalSystem_SplatTriangle(decalsystem_t *decalsystem, float r, float g, float b, float a, float s1, float t1, float s2, float t2, unsigned int decalsequence, qboolean dynamic, float (*planes)[4], matrix4x4_t *projection, int triangleindex, int surfaceindex)
 {
        int cornerindex;
        int index;
@@ -11782,7 +11824,7 @@ static void R_DecalSystem_SplatTriangle(decalsystem_t *decalsystem, float r, flo
                for (cornerindex = 0;cornerindex < numpoints-2;cornerindex++)
                        R_DecalSystem_SpawnTriangle(decalsystem, v[0], v[cornerindex+1], v[cornerindex+2], tc[0], tc[cornerindex+1], tc[cornerindex+2], c[0], c[cornerindex+1], c[cornerindex+2], -1, surfaceindex, decalsequence);
 }
-static void R_DecalSystem_SplatEntity(entity_render_t *ent, const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize, int decalsequence)
+static void R_DecalSystem_SplatEntity(entity_render_t *ent, const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize, unsigned int decalsequence)
 {
        matrix4x4_t projection;
        decalsystem_t *decalsystem;
@@ -11943,7 +11985,7 @@ static void R_DecalSystem_SplatEntity(entity_render_t *ent, const vec3_t worldor
 }
 
 // do not call this outside of rendering code - use R_DecalSystem_SplatEntities instead
-static void R_DecalSystem_ApplySplatEntities(const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize, int decalsequence)
+static void R_DecalSystem_ApplySplatEntities(const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize, unsigned int decalsequence)
 {
        int renderentityindex;
        float worldmins[3];
@@ -11979,7 +12021,7 @@ typedef struct r_decalsystem_splatqueue_s
        float color[4];
        float tcrange[4];
        float worldsize;
-       int decalsequence;
+       unsigned int decalsequence;
 }
 r_decalsystem_splatqueue_t;
 
@@ -12018,7 +12060,7 @@ static void R_DrawModelDecals_FadeEntity(entity_render_t *ent)
        int i;
        decalsystem_t *decalsystem = &ent->decalsystem;
        int numdecals;
-       int killsequence;
+       unsigned int killsequence;
        tridecal_t *decal;
        float frametime;
        float lifetime;
@@ -12035,7 +12077,7 @@ static void R_DrawModelDecals_FadeEntity(entity_render_t *ent)
                return;
        }
 
-       killsequence = cl.decalsequence - max(1, cl_decals_max.integer);
+       killsequence = cl.decalsequence - bound(1, (unsigned int) cl_decals_max.integer, cl.decalsequence);
        lifetime = cl_decals_time.value + cl_decals_fadetime.value;
 
        if (decalsystem->lastupdatetime)
@@ -12050,7 +12092,7 @@ static void R_DrawModelDecals_FadeEntity(entity_render_t *ent)
                if (decal->color4f[0][3])
                {
                        decal->lived += frametime;
-                       if (killsequence - decal->decalsequence > 0 || decal->lived >= lifetime)
+                       if (killsequence > decal->decalsequence || decal->lived >= lifetime)
                        {
                                memset(decal, 0, sizeof(*decal));
                                if (decalsystem->freedecal > i)
@@ -12710,6 +12752,7 @@ void R_DrawCustomSurface(skinframe_t *skinframe, const matrix4x4_t *texmatrix, i
 
        texture.update_lastrenderframe = -1; // regenerate this texture
        texture.basematerialflags = materialflags | MATERIALFLAG_CUSTOMSURFACE | MATERIALFLAG_WALL;
+       texture.basealpha = 1.0f;
        texture.currentskinframe = skinframe;
        texture.currenttexmatrix = *texmatrix; // requires MATERIALFLAG_CUSTOMSURFACE
        texture.offsetmapping = OFFSETMAPPING_OFF;