304c3074169ebbf52faec7934f17dbfe1861421f
[xonotic/darkplaces.git] / gl_rmain.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // r_main.c
21
22 #include "quakedef.h"
23 #include "cl_dyntexture.h"
24 #include "r_shadow.h"
25 #include "polygon.h"
26 #include "image.h"
27 #include "ft2.h"
28 #include "csprogs.h"
29 #include "cl_video.h"
30 #include "dpsoftrast.h"
31
32 #ifdef SUPPORTD3D
33 #include <d3d9.h>
34 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
35 #endif
36
37 mempool_t *r_main_mempool;
38 rtexturepool_t *r_main_texturepool;
39
40 static int r_textureframe = 0; ///< used only by R_GetCurrentTexture
41
42 static qboolean r_loadnormalmap;
43 static qboolean r_loadgloss;
44 qboolean r_loadfog;
45 static qboolean r_loaddds;
46 static qboolean r_savedds;
47
48 //
49 // screen size info
50 //
51 r_refdef_t r_refdef;
52
53 cvar_t r_motionblur = {CVAR_SAVE, "r_motionblur", "0", "screen motionblur - value represents intensity, somewhere around 0.5 recommended"};
54 cvar_t r_damageblur = {CVAR_SAVE, "r_damageblur", "0", "screen motionblur based on damage - value represents intensity, somewhere around 0.5 recommended"};
55 cvar_t r_motionblur_averaging = {CVAR_SAVE, "r_motionblur_averaging", "0.1", "sliding average reaction time for velocity (higher = slower adaption to change)"};
56 cvar_t r_motionblur_randomize = {CVAR_SAVE, "r_motionblur_randomize", "0.1", "randomizing coefficient to workaround ghosting"};
57 cvar_t r_motionblur_minblur = {CVAR_SAVE, "r_motionblur_minblur", "0.5", "factor of blur to apply at all times (always have this amount of blur no matter what the other factors are)"};
58 cvar_t r_motionblur_maxblur = {CVAR_SAVE, "r_motionblur_maxblur", "0.9", "maxmimum amount of blur"};
59 cvar_t r_motionblur_velocityfactor = {CVAR_SAVE, "r_motionblur_velocityfactor", "1", "factoring in of player velocity to the blur equation - the faster the player moves around the map, the more blur they get"};
60 cvar_t r_motionblur_velocityfactor_minspeed = {CVAR_SAVE, "r_motionblur_velocityfactor_minspeed", "400", "lower value of velocity when it starts to factor into blur equation"};
61 cvar_t r_motionblur_velocityfactor_maxspeed = {CVAR_SAVE, "r_motionblur_velocityfactor_maxspeed", "800", "upper value of velocity when it reaches the peak factor into blur equation"};
62 cvar_t r_motionblur_mousefactor = {CVAR_SAVE, "r_motionblur_mousefactor", "2", "factoring in of mouse acceleration to the blur equation - the faster the player turns their mouse, the more blur they get"};
63 cvar_t r_motionblur_mousefactor_minspeed = {CVAR_SAVE, "r_motionblur_mousefactor_minspeed", "0", "lower value of mouse acceleration when it starts to factor into blur equation"};
64 cvar_t r_motionblur_mousefactor_maxspeed = {CVAR_SAVE, "r_motionblur_mousefactor_maxspeed", "50", "upper value of mouse acceleration when it reaches the peak factor into blur equation"};
65
66 // TODO do we want a r_equalize_entities cvar that works on all ents, or would that be a cheat?
67 cvar_t r_equalize_entities_fullbright = {CVAR_SAVE, "r_equalize_entities_fullbright", "0", "render fullbright entities by equalizing their lightness, not by not rendering light"};
68 cvar_t r_equalize_entities_minambient = {CVAR_SAVE, "r_equalize_entities_minambient", "0.5", "light equalizing: ensure at least this ambient/diffuse ratio"};
69 cvar_t r_equalize_entities_by = {CVAR_SAVE, "r_equalize_entities_by", "0.7", "light equalizing: exponent of dynamics compression (0 = no compression, 1 = full compression)"};
70 cvar_t r_equalize_entities_to = {CVAR_SAVE, "r_equalize_entities_to", "0.8", "light equalizing: target light level"};
71
72 cvar_t r_depthfirst = {CVAR_SAVE, "r_depthfirst", "0", "renders a depth-only version of the scene before normal rendering begins to eliminate overdraw, values: 0 = off, 1 = world depth, 2 = world and model depth"};
73 cvar_t r_useinfinitefarclip = {CVAR_SAVE, "r_useinfinitefarclip", "1", "enables use of a special kind of projection matrix that has an extremely large farclip"};
74 cvar_t r_farclip_base = {0, "r_farclip_base", "65536", "farclip (furthest visible distance) for rendering when r_useinfinitefarclip is 0"};
75 cvar_t r_farclip_world = {0, "r_farclip_world", "2", "adds map size to farclip multiplied by this value"};
76 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
77 cvar_t r_deformvertexes = {0, "r_deformvertexes", "1", "allows use of deformvertexes in shader files (can be turned off to check performance impact)"};
78 cvar_t r_transparent = {0, "r_transparent", "1", "allows use of transparent surfaces (can be turned off to check performance impact)"};
79 cvar_t r_transparent_alphatocoverage = {0, "r_transparent_alphatocoverage", "1", "enables GL_ALPHA_TO_COVERAGE antialiasing technique on alphablend and alphatest surfaces when using vid_samples 2 or higher"};
80 cvar_t r_showoverdraw = {0, "r_showoverdraw", "0", "shows overlapping geometry"};
81 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%,  10 = 100%)"};
82 cvar_t r_showsurfaces = {0, "r_showsurfaces", "0", "1 shows surfaces as different colors, or a value of 2 shows triangle draw order (for analyzing whether meshes are optimized for vertex cache)"};
83 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
84 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
85 cvar_t r_showlighting = {0, "r_showlighting", "0", "shows areas lit by lights, useful for finding out why some areas of a map render slowly (bright orange = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
86 cvar_t r_showshadowvolumes = {0, "r_showshadowvolumes", "0", "shows areas shadowed by lights, useful for finding out why some areas of a map render slowly (bright blue = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
87 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
88 cvar_t r_showcollisionbrushes_polygonfactor = {0, "r_showcollisionbrushes_polygonfactor", "-1", "expands outward the brush polygons a little bit, used to make collision brushes appear infront of walls"};
89 cvar_t r_showcollisionbrushes_polygonoffset = {0, "r_showcollisionbrushes_polygonoffset", "0", "nudges brush polygon depth in hardware depth units, used to make collision brushes appear infront of walls"};
90 cvar_t r_showdisabledepthtest = {0, "r_showdisabledepthtest", "0", "disables depth testing on r_show* cvars, allowing you to see what hidden geometry the graphics card is processing"};
91 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
92 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
93 cvar_t r_draw2d = {0, "r_draw2d","1", "draw 2D stuff (dangerous to turn off)"};
94 cvar_t r_drawworld = {0, "r_drawworld","1", "draw world (most static stuff)"};
95 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
96 cvar_t r_drawexteriormodel = {0, "r_drawexteriormodel","1", "draw your player model (e.g. in chase cam, reflections)"};
97 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
98 cvar_t r_cullentities_trace_samples = {0, "r_cullentities_trace_samples", "2", "number of samples to test for entity culling (in addition to center sample)"};
99 cvar_t r_cullentities_trace_tempentitysamples = {0, "r_cullentities_trace_tempentitysamples", "-1", "number of samples to test for entity culling of temp entities (including all CSQC entities), -1 disables trace culling on these entities to prevent flicker (pvs still applies)"};
100 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
101 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
102 cvar_t r_sortentities = {0, "r_sortentities", "0", "sort entities before drawing (might be faster)"};
103 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
104 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
105
106 cvar_t r_fakelight = {0, "r_fakelight","0", "render 'fake' lighting instead of real lightmaps"};
107 cvar_t r_fakelight_intensity = {0, "r_fakelight_intensity","0.75", "fakelight intensity modifier"};
108 #define FAKELIGHT_ENABLED (r_fakelight.integer >= 2 || (r_fakelight.integer && r_refdef.scene.worldmodel && !r_refdef.scene.worldmodel->lit))
109
110 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
111 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
112 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
113 cvar_t r_shadows = {CVAR_SAVE, "r_shadows", "0", "casts fake stencil shadows from models onto the world (rtlights are unaffected by this); when set to 2, always cast the shadows in the direction set by r_shadows_throwdirection, otherwise use the model lighting."};
114 cvar_t r_shadows_darken = {CVAR_SAVE, "r_shadows_darken", "0.5", "how much shadowed areas will be darkened"};
115 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
116 cvar_t r_shadows_throwdirection = {CVAR_SAVE, "r_shadows_throwdirection", "0 0 -1", "override throwing direction for r_shadows 2"};
117 cvar_t r_shadows_drawafterrtlighting = {CVAR_SAVE, "r_shadows_drawafterrtlighting", "0", "draw fake shadows AFTER realtime lightning is drawn. May be useful for simulating fast sunlight on large outdoor maps with only one noshadow rtlight. The price is less realistic appearance of dynamic light shadows."};
118 cvar_t r_shadows_castfrombmodels = {CVAR_SAVE, "r_shadows_castfrombmodels", "0", "do cast shadows from bmodels"};
119 cvar_t r_shadows_focus = {CVAR_SAVE, "r_shadows_focus", "0 0 0", "offset the shadowed area focus"};
120 cvar_t r_shadows_shadowmapscale = {CVAR_SAVE, "r_shadows_shadowmapscale", "1", "increases shadowmap quality (multiply global shadowmap precision) for fake shadows. Needs shadowmapping ON."};
121 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
122 cvar_t r_polygonoffset_submodel_factor = {0, "r_polygonoffset_submodel_factor", "0", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
123 cvar_t r_polygonoffset_submodel_offset = {0, "r_polygonoffset_submodel_offset", "14", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
124 cvar_t r_polygonoffset_decals_factor = {0, "r_polygonoffset_decals_factor", "0", "biases depth values of decals to prevent z-fighting artifacts"};
125 cvar_t r_polygonoffset_decals_offset = {0, "r_polygonoffset_decals_offset", "-14", "biases depth values of decals to prevent z-fighting artifacts"};
126 cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
127 cvar_t r_fog_clear = {0, "r_fog_clear", "1", "clears renderbuffer with fog color before render starts"};
128 cvar_t r_drawfog = {CVAR_SAVE, "r_drawfog", "1", "allows one to disable fog rendering"};
129 cvar_t r_transparentdepthmasking = {CVAR_SAVE, "r_transparentdepthmasking", "0", "enables depth writes on transparent meshes whose materially is normally opaque, this prevents seeing the inside of a transparent mesh"};
130 cvar_t r_transparent_sortmindist = {CVAR_SAVE, "r_transparent_sortmindist", "0", "lower distance limit for transparent sorting"};
131 cvar_t r_transparent_sortmaxdist = {CVAR_SAVE, "r_transparent_sortmaxdist", "32768", "upper distance limit for transparent sorting"};
132 cvar_t r_transparent_sortarraysize = {CVAR_SAVE, "r_transparent_sortarraysize", "4096", "number of distance-sorting layers"};
133
134 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
135 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
136 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
137 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
138 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
139 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
140 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
141 cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
142
143 cvar_t r_texture_dds_load = {CVAR_SAVE, "r_texture_dds_load", "0", "load compressed dds/filename.dds texture instead of filename.tga, if the file exists (requires driver support)"};
144 cvar_t r_texture_dds_save = {CVAR_SAVE, "r_texture_dds_save", "0", "save compressed dds/filename.dds texture when filename.tga is loaded, so that it can be loaded instead next time"};
145
146 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of texture units to use in GL 1.1 and GL 1.3 rendering paths"};
147 static cvar_t gl_combine = {CVAR_READONLY, "gl_combine", "1", "indicates whether the OpenGL 1.3 rendering path is active"};
148 static cvar_t r_glsl = {CVAR_READONLY, "r_glsl", "1", "indicates whether the OpenGL 2.0 rendering path is active"};
149
150 cvar_t r_usedepthtextures = {CVAR_SAVE, "r_usedepthtextures", "1", "use depth texture instead of depth renderbuffer where possible, uses less video memory but may render slower (or faster) depending on hardware"};
151 cvar_t r_viewfbo = {CVAR_SAVE, "r_viewfbo", "0", "enables use of an 8bit (1) or 16bit (2) or 32bit (3) per component float framebuffer render, which may be at a different resolution than the video mode"};
152 cvar_t r_viewscale = {CVAR_SAVE, "r_viewscale", "1", "scaling factor for resolution of the fbo rendering method, must be > 0, can be above 1 for a costly antialiasing behavior, typical values are 0.5 for 1/4th as many pixels rendered, or 1 for normal rendering"};
153 cvar_t r_viewscale_fpsscaling = {CVAR_SAVE, "r_viewscale_fpsscaling", "0", "change resolution based on framerate"};
154 cvar_t r_viewscale_fpsscaling_min = {CVAR_SAVE, "r_viewscale_fpsscaling_min", "0.0625", "worst acceptable quality"};
155 cvar_t r_viewscale_fpsscaling_multiply = {CVAR_SAVE, "r_viewscale_fpsscaling_multiply", "5", "adjust quality up or down by the frametime difference from 1.0/target, multiplied by this factor"};
156 cvar_t r_viewscale_fpsscaling_stepsize = {CVAR_SAVE, "r_viewscale_fpsscaling_stepsize", "0.01", "smallest adjustment to hit the target framerate (this value prevents minute oscillations)"};
157 cvar_t r_viewscale_fpsscaling_stepmax = {CVAR_SAVE, "r_viewscale_fpsscaling_stepmax", "1.00", "largest adjustment to hit the target framerate (this value prevents wild overshooting of the estimate)"};
158 cvar_t r_viewscale_fpsscaling_target = {CVAR_SAVE, "r_viewscale_fpsscaling_target", "70", "desired framerate"};
159
160 cvar_t r_glsl_deluxemapping = {CVAR_SAVE, "r_glsl_deluxemapping", "1", "use per pixel lighting on deluxemap-compiled q3bsp maps (or a value of 2 forces deluxemap shading even without deluxemaps)"};
161 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
162 cvar_t r_glsl_offsetmapping_steps = {CVAR_SAVE, "r_glsl_offsetmapping_steps", "2", "offset mapping steps (note: too high values may be not supported by your GPU)"};
163 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
164 cvar_t r_glsl_offsetmapping_reliefmapping_steps = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping_steps", "10", "relief mapping steps (note: too high values may be not supported by your GPU)"};
165 cvar_t r_glsl_offsetmapping_reliefmapping_refinesteps = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping_refinesteps", "5", "relief mapping refine steps (these are a binary search executed as the last step as given by r_glsl_offsetmapping_reliefmapping_steps)"};
166 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
167 cvar_t r_glsl_offsetmapping_lod = {CVAR_SAVE, "r_glsl_offsetmapping_lod", "0", "apply distance-based level-of-detail correction to number of offsetmappig steps, effectively making it render faster on large open-area maps"};
168 cvar_t r_glsl_offsetmapping_lod_distance = {CVAR_SAVE, "r_glsl_offsetmapping_lod_distance", "32", "first LOD level distance, second level (-50% steps) is 2x of this, third (33%) - 3x etc."};
169 cvar_t r_glsl_postprocess = {CVAR_SAVE, "r_glsl_postprocess", "0", "use a GLSL postprocessing shader"};
170 cvar_t r_glsl_postprocess_uservec1 = {CVAR_SAVE, "r_glsl_postprocess_uservec1", "0 0 0 0", "a 4-component vector to pass as uservec1 to the postprocessing shader (only useful if default.glsl has been customized)"};
171 cvar_t r_glsl_postprocess_uservec2 = {CVAR_SAVE, "r_glsl_postprocess_uservec2", "0 0 0 0", "a 4-component vector to pass as uservec2 to the postprocessing shader (only useful if default.glsl has been customized)"};
172 cvar_t r_glsl_postprocess_uservec3 = {CVAR_SAVE, "r_glsl_postprocess_uservec3", "0 0 0 0", "a 4-component vector to pass as uservec3 to the postprocessing shader (only useful if default.glsl has been customized)"};
173 cvar_t r_glsl_postprocess_uservec4 = {CVAR_SAVE, "r_glsl_postprocess_uservec4", "0 0 0 0", "a 4-component vector to pass as uservec4 to the postprocessing shader (only useful if default.glsl has been customized)"};
174 cvar_t r_glsl_postprocess_uservec1_enable = {CVAR_SAVE, "r_glsl_postprocess_uservec1_enable", "1", "enables postprocessing uservec1 usage, creates USERVEC1 define (only useful if default.glsl has been customized)"};
175 cvar_t r_glsl_postprocess_uservec2_enable = {CVAR_SAVE, "r_glsl_postprocess_uservec2_enable", "1", "enables postprocessing uservec2 usage, creates USERVEC1 define (only useful if default.glsl has been customized)"};
176 cvar_t r_glsl_postprocess_uservec3_enable = {CVAR_SAVE, "r_glsl_postprocess_uservec3_enable", "1", "enables postprocessing uservec3 usage, creates USERVEC1 define (only useful if default.glsl has been customized)"};
177 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)"};
178
179 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)"};
180 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
181 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"};
182 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
183 cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "how much water reflections shimmer"};
184 cvar_t r_water_scissormode = {0, "r_water_scissormode", "3", "scissor (1) or cull (2) or both (3) water renders"};
185 cvar_t r_water_lowquality = {0, "r_water_lowquality", "0", "special option to accelerate water rendering, 1 disables shadows and particles, 2 disables all dynamic lights"};
186 cvar_t r_water_hideplayer = {CVAR_SAVE, "r_water_hideplayer", "0", "if set to 1 then player will be hidden in refraction views, if set to 2 then player will also be hidden in reflection views, player is always visible in camera views"};
187 cvar_t r_water_fbo = {CVAR_SAVE, "r_water_fbo", "1", "enables use of render to texture for water effects, otherwise copy to texture is used (slower)"};
188
189 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "0", "enables animation smoothing on sprites"};
190 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
191 cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
192 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
193
194 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
195 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
196
197 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
198 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
199 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
200 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exaggerated the glow is"};
201 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
202
203 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
204 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
205 cvar_t r_hdr_irisadaptation = {CVAR_SAVE, "r_hdr_irisadaptation", "0", "adjust scene brightness according to light intensity at player location"};
206 cvar_t r_hdr_irisadaptation_multiplier = {CVAR_SAVE, "r_hdr_irisadaptation_multiplier", "2", "brightness at which value will be 1.0"};
207 cvar_t r_hdr_irisadaptation_minvalue = {CVAR_SAVE, "r_hdr_irisadaptation_minvalue", "0.5", "minimum value that can result from multiplier / brightness"};
208 cvar_t r_hdr_irisadaptation_maxvalue = {CVAR_SAVE, "r_hdr_irisadaptation_maxvalue", "4", "maximum value that can result from multiplier / brightness"};
209 cvar_t r_hdr_irisadaptation_value = {0, "r_hdr_irisadaptation_value", "1", "current value as scenebrightness multiplier, changes continuously when irisadaptation is active"};
210 cvar_t r_hdr_irisadaptation_fade_up = {CVAR_SAVE, "r_hdr_irisadaptation_fade_up", "0.1", "fade rate at which value adjusts to darkness"};
211 cvar_t r_hdr_irisadaptation_fade_down = {CVAR_SAVE, "r_hdr_irisadaptation_fade_down", "0.5", "fade rate at which value adjusts to brightness"};
212 cvar_t r_hdr_irisadaptation_radius = {CVAR_SAVE, "r_hdr_irisadaptation_radius", "15", "lighting within this many units of the eye is averaged"};
213
214 cvar_t r_smoothnormals_areaweighting = {0, "r_smoothnormals_areaweighting", "1", "uses significantly faster (and supposedly higher quality) area-weighted vertex normals and tangent vectors rather than summing normalized triangle normals and tangents"};
215
216 cvar_t developer_texturelogging = {0, "developer_texturelogging", "0", "produces a textures.log file containing names of skins and map textures the engine tried to load"};
217
218 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
219
220 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
221
222 cvar_t r_glsl_saturation = {CVAR_SAVE, "r_glsl_saturation", "1", "saturation multiplier (only working in glsl!)"};
223 cvar_t r_glsl_saturation_redcompensate = {CVAR_SAVE, "r_glsl_saturation_redcompensate", "0", "a 'vampire sight' addition to desaturation effect, does compensation for red color, r_glsl_restart is required"};
224
225 cvar_t r_glsl_vertextextureblend_usebothalphas = {CVAR_SAVE, "r_glsl_vertextextureblend_usebothalphas", "0", "use both alpha layers on vertex blended surfaces, each alpha layer sets amount of 'blend leak' on another layer."};
226
227 cvar_t r_framedatasize = {CVAR_SAVE, "r_framedatasize", "0.5", "size of renderer data cache used during one frame (for skeletal animation caching, light processing, etc)"};
228
229 extern cvar_t v_glslgamma;
230 extern cvar_t v_glslgamma_2d;
231
232 extern qboolean v_flipped_state;
233
234 r_framebufferstate_t r_fb;
235
236 /// shadow volume bsp struct with automatically growing nodes buffer
237 svbsp_t r_svbsp;
238
239 rtexture_t *r_texture_blanknormalmap;
240 rtexture_t *r_texture_white;
241 rtexture_t *r_texture_grey128;
242 rtexture_t *r_texture_black;
243 rtexture_t *r_texture_notexture;
244 rtexture_t *r_texture_whitecube;
245 rtexture_t *r_texture_normalizationcube;
246 rtexture_t *r_texture_fogattenuation;
247 rtexture_t *r_texture_fogheighttexture;
248 rtexture_t *r_texture_gammaramps;
249 unsigned int r_texture_gammaramps_serial;
250 //rtexture_t *r_texture_fogintensity;
251 rtexture_t *r_texture_reflectcube;
252
253 // TODO: hash lookups?
254 typedef struct cubemapinfo_s
255 {
256         char basename[64];
257         rtexture_t *texture;
258 }
259 cubemapinfo_t;
260
261 int r_texture_numcubemaps;
262 cubemapinfo_t *r_texture_cubemaps[MAX_CUBEMAPS];
263
264 unsigned int r_queries[MAX_OCCLUSION_QUERIES];
265 unsigned int r_numqueries;
266 unsigned int r_maxqueries;
267
268 typedef struct r_qwskincache_s
269 {
270         char name[MAX_QPATH];
271         skinframe_t *skinframe;
272 }
273 r_qwskincache_t;
274
275 static r_qwskincache_t *r_qwskincache;
276 static int r_qwskincache_size;
277
278 /// vertex coordinates for a quad that covers the screen exactly
279 extern const float r_screenvertex3f[12];
280 extern const float r_d3dscreenvertex3f[12];
281 const float r_screenvertex3f[12] =
282 {
283         0, 0, 0,
284         1, 0, 0,
285         1, 1, 0,
286         0, 1, 0
287 };
288 const float r_d3dscreenvertex3f[12] =
289 {
290         0, 1, 0,
291         1, 1, 0,
292         1, 0, 0,
293         0, 0, 0
294 };
295
296 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
297 {
298         int i;
299         for (i = 0;i < verts;i++)
300         {
301                 out[0] = in[0] * r;
302                 out[1] = in[1] * g;
303                 out[2] = in[2] * b;
304                 out[3] = in[3];
305                 in += 4;
306                 out += 4;
307         }
308 }
309
310 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
311 {
312         int i;
313         for (i = 0;i < verts;i++)
314         {
315                 out[0] = r;
316                 out[1] = g;
317                 out[2] = b;
318                 out[3] = a;
319                 out += 4;
320         }
321 }
322
323 // FIXME: move this to client?
324 void FOG_clear(void)
325 {
326         if (gamemode == GAME_NEHAHRA)
327         {
328                 Cvar_Set("gl_fogenable", "0");
329                 Cvar_Set("gl_fogdensity", "0.2");
330                 Cvar_Set("gl_fogred", "0.3");
331                 Cvar_Set("gl_foggreen", "0.3");
332                 Cvar_Set("gl_fogblue", "0.3");
333         }
334         r_refdef.fog_density = 0;
335         r_refdef.fog_red = 0;
336         r_refdef.fog_green = 0;
337         r_refdef.fog_blue = 0;
338         r_refdef.fog_alpha = 1;
339         r_refdef.fog_start = 0;
340         r_refdef.fog_end = 16384;
341         r_refdef.fog_height = 1<<30;
342         r_refdef.fog_fadedepth = 128;
343         memset(r_refdef.fog_height_texturename, 0, sizeof(r_refdef.fog_height_texturename));
344 }
345
346 static void R_BuildBlankTextures(void)
347 {
348         unsigned char data[4];
349         data[2] = 128; // normal X
350         data[1] = 128; // normal Y
351         data[0] = 255; // normal Z
352         data[3] = 255; // height
353         r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
354         data[0] = 255;
355         data[1] = 255;
356         data[2] = 255;
357         data[3] = 255;
358         r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
359         data[0] = 128;
360         data[1] = 128;
361         data[2] = 128;
362         data[3] = 255;
363         r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
364         data[0] = 0;
365         data[1] = 0;
366         data[2] = 0;
367         data[3] = 255;
368         r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
369 }
370
371 static void R_BuildNoTexture(void)
372 {
373         int x, y;
374         unsigned char pix[16][16][4];
375         // this makes a light grey/dark grey checkerboard texture
376         for (y = 0;y < 16;y++)
377         {
378                 for (x = 0;x < 16;x++)
379                 {
380                         if ((y < 8) ^ (x < 8))
381                         {
382                                 pix[y][x][0] = 128;
383                                 pix[y][x][1] = 128;
384                                 pix[y][x][2] = 128;
385                                 pix[y][x][3] = 255;
386                         }
387                         else
388                         {
389                                 pix[y][x][0] = 64;
390                                 pix[y][x][1] = 64;
391                                 pix[y][x][2] = 64;
392                                 pix[y][x][3] = 255;
393                         }
394                 }
395         }
396         r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, -1, NULL);
397 }
398
399 static void R_BuildWhiteCube(void)
400 {
401         unsigned char data[6*1*1*4];
402         memset(data, 255, sizeof(data));
403         r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
404 }
405
406 static void R_BuildNormalizationCube(void)
407 {
408         int x, y, side;
409         vec3_t v;
410         vec_t s, t, intensity;
411 #define NORMSIZE 64
412         unsigned char *data;
413         data = (unsigned char *)Mem_Alloc(tempmempool, 6*NORMSIZE*NORMSIZE*4);
414         for (side = 0;side < 6;side++)
415         {
416                 for (y = 0;y < NORMSIZE;y++)
417                 {
418                         for (x = 0;x < NORMSIZE;x++)
419                         {
420                                 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
421                                 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
422                                 switch(side)
423                                 {
424                                 default:
425                                 case 0:
426                                         v[0] = 1;
427                                         v[1] = -t;
428                                         v[2] = -s;
429                                         break;
430                                 case 1:
431                                         v[0] = -1;
432                                         v[1] = -t;
433                                         v[2] = s;
434                                         break;
435                                 case 2:
436                                         v[0] = s;
437                                         v[1] = 1;
438                                         v[2] = t;
439                                         break;
440                                 case 3:
441                                         v[0] = s;
442                                         v[1] = -1;
443                                         v[2] = -t;
444                                         break;
445                                 case 4:
446                                         v[0] = s;
447                                         v[1] = -t;
448                                         v[2] = 1;
449                                         break;
450                                 case 5:
451                                         v[0] = -s;
452                                         v[1] = -t;
453                                         v[2] = -1;
454                                         break;
455                                 }
456                                 intensity = 127.0f / sqrt(DotProduct(v, v));
457                                 data[((side*64+y)*64+x)*4+2] = (unsigned char)(128.0f + intensity * v[0]);
458                                 data[((side*64+y)*64+x)*4+1] = (unsigned char)(128.0f + intensity * v[1]);
459                                 data[((side*64+y)*64+x)*4+0] = (unsigned char)(128.0f + intensity * v[2]);
460                                 data[((side*64+y)*64+x)*4+3] = 255;
461                         }
462                 }
463         }
464         r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
465         Mem_Free(data);
466 }
467
468 static void R_BuildFogTexture(void)
469 {
470         int x, b;
471 #define FOGWIDTH 256
472         unsigned char data1[FOGWIDTH][4];
473         //unsigned char data2[FOGWIDTH][4];
474         double d, r, alpha;
475
476         r_refdef.fogmasktable_start = r_refdef.fog_start;
477         r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
478         r_refdef.fogmasktable_range = r_refdef.fogrange;
479         r_refdef.fogmasktable_density = r_refdef.fog_density;
480
481         r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
482         for (x = 0;x < FOGMASKTABLEWIDTH;x++)
483         {
484                 d = (x * r - r_refdef.fogmasktable_start);
485                 if(developer_extra.integer)
486                         Con_DPrintf("%f ", d);
487                 d = max(0, d);
488                 if (r_fog_exp2.integer)
489                         alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
490                 else
491                         alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
492                 if(developer_extra.integer)
493                         Con_DPrintf(" : %f ", alpha);
494                 alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
495                 if(developer_extra.integer)
496                         Con_DPrintf(" = %f\n", alpha);
497                 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
498         }
499
500         for (x = 0;x < FOGWIDTH;x++)
501         {
502                 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
503                 data1[x][0] = b;
504                 data1[x][1] = b;
505                 data1[x][2] = b;
506                 data1[x][3] = 255;
507                 //data2[x][0] = 255 - b;
508                 //data2[x][1] = 255 - b;
509                 //data2[x][2] = 255 - b;
510                 //data2[x][3] = 255;
511         }
512         if (r_texture_fogattenuation)
513         {
514                 R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, 0, FOGWIDTH, 1, 1);
515                 //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, 0, FOGWIDTH, 1, 1);
516         }
517         else
518         {
519                 r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
520                 //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
521         }
522 }
523
524 static void R_BuildFogHeightTexture(void)
525 {
526         unsigned char *inpixels;
527         int size;
528         int x;
529         int y;
530         int j;
531         float c[4];
532         float f;
533         inpixels = NULL;
534         strlcpy(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename, sizeof(r_refdef.fogheighttexturename));
535         if (r_refdef.fogheighttexturename[0])
536                 inpixels = loadimagepixelsbgra(r_refdef.fogheighttexturename, true, false, false, NULL);
537         if (!inpixels)
538         {
539                 r_refdef.fog_height_tablesize = 0;
540                 if (r_texture_fogheighttexture)
541                         R_FreeTexture(r_texture_fogheighttexture);
542                 r_texture_fogheighttexture = NULL;
543                 if (r_refdef.fog_height_table2d)
544                         Mem_Free(r_refdef.fog_height_table2d);
545                 r_refdef.fog_height_table2d = NULL;
546                 if (r_refdef.fog_height_table1d)
547                         Mem_Free(r_refdef.fog_height_table1d);
548                 r_refdef.fog_height_table1d = NULL;
549                 return;
550         }
551         size = image_width;
552         r_refdef.fog_height_tablesize = size;
553         r_refdef.fog_height_table1d = (unsigned char *)Mem_Alloc(r_main_mempool, size * 4);
554         r_refdef.fog_height_table2d = (unsigned char *)Mem_Alloc(r_main_mempool, size * size * 4);
555         memcpy(r_refdef.fog_height_table1d, inpixels, size * 4);
556         Mem_Free(inpixels);
557         // LordHavoc: now the magic - what is that table2d for?  it is a cooked
558         // average fog color table accounting for every fog layer between a point
559         // and the camera.  (Note: attenuation is handled separately!)
560         for (y = 0;y < size;y++)
561         {
562                 for (x = 0;x < size;x++)
563                 {
564                         Vector4Clear(c);
565                         f = 0;
566                         if (x < y)
567                         {
568                                 for (j = x;j <= y;j++)
569                                 {
570                                         Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
571                                         f++;
572                                 }
573                         }
574                         else
575                         {
576                                 for (j = x;j >= y;j--)
577                                 {
578                                         Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
579                                         f++;
580                                 }
581                         }
582                         f = 1.0f / f;
583                         r_refdef.fog_height_table2d[(y*size+x)*4+0] = (unsigned char)(c[0] * f);
584                         r_refdef.fog_height_table2d[(y*size+x)*4+1] = (unsigned char)(c[1] * f);
585                         r_refdef.fog_height_table2d[(y*size+x)*4+2] = (unsigned char)(c[2] * f);
586                         r_refdef.fog_height_table2d[(y*size+x)*4+3] = (unsigned char)(c[3] * f);
587                 }
588         }
589         r_texture_fogheighttexture = R_LoadTexture2D(r_main_texturepool, "fogheighttable", size, size, r_refdef.fog_height_table2d, TEXTYPE_BGRA, TEXF_ALPHA | TEXF_CLAMP, -1, NULL);
590 }
591
592 //=======================================================================================================================================================
593
594 static const char *builtinshaderstring =
595 #include "shader_glsl.h"
596 ;
597
598 const char *builtinhlslshaderstring =
599 #include "shader_hlsl.h"
600 ;
601
602 char *glslshaderstring = NULL;
603 char *hlslshaderstring = NULL;
604
605 //=======================================================================================================================================================
606
607 typedef struct shaderpermutationinfo_s
608 {
609         const char *pretext;
610         const char *name;
611 }
612 shaderpermutationinfo_t;
613
614 typedef struct shadermodeinfo_s
615 {
616         const char *vertexfilename;
617         const char *geometryfilename;
618         const char *fragmentfilename;
619         const char *pretext;
620         const char *name;
621 }
622 shadermodeinfo_t;
623
624 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
625 shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
626 {
627         {"#define USEDIFFUSE\n", " diffuse"},
628         {"#define USEVERTEXTEXTUREBLEND\n", " vertextextureblend"},
629         {"#define USEVIEWTINT\n", " viewtint"},
630         {"#define USECOLORMAPPING\n", " colormapping"},
631         {"#define USESATURATION\n", " saturation"},
632         {"#define USEFOGINSIDE\n", " foginside"},
633         {"#define USEFOGOUTSIDE\n", " fogoutside"},
634         {"#define USEFOGHEIGHTTEXTURE\n", " fogheighttexture"},
635         {"#define USEFOGALPHAHACK\n", " fogalphahack"},
636         {"#define USEGAMMARAMPS\n", " gammaramps"},
637         {"#define USECUBEFILTER\n", " cubefilter"},
638         {"#define USEGLOW\n", " glow"},
639         {"#define USEBLOOM\n", " bloom"},
640         {"#define USESPECULAR\n", " specular"},
641         {"#define USEPOSTPROCESSING\n", " postprocessing"},
642         {"#define USEREFLECTION\n", " reflection"},
643         {"#define USEOFFSETMAPPING\n", " offsetmapping"},
644         {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
645         {"#define USESHADOWMAP2D\n", " shadowmap2d"},
646         {"#define USESHADOWMAPPCF 1\n", " shadowmappcf"}, // TODO make this a static parm
647         {"#define USESHADOWMAPPCF 2\n", " shadowmappcf2"}, // TODO make this a static parm
648         {"#define USESHADOWSAMPLER\n", " shadowsampler"}, // TODO make this a static parm
649         {"#define USESHADOWMAPVSDCT\n", " shadowmapvsdct"}, // TODO make this a static parm
650         {"#define USESHADOWMAPORTHO\n", " shadowmaportho"},
651         {"#define USEDEFERREDLIGHTMAP\n", " deferredlightmap"},
652         {"#define USEALPHAKILL\n", " alphakill"},
653         {"#define USEREFLECTCUBE\n", " reflectcube"},
654         {"#define USENORMALMAPSCROLLBLEND\n", " normalmapscrollblend"},
655         {"#define USEBOUNCEGRID\n", " bouncegrid"},
656         {"#define USEBOUNCEGRIDDIRECTIONAL\n", " bouncegriddirectional"}, // TODO make this a static parm
657         {"#define USETRIPPY\n", " trippy"},
658         {"#define USEDEPTHRGB\n", " depthrgb"},
659 };
660
661 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
662 shadermodeinfo_t glslshadermodeinfo[SHADERMODE_COUNT] =
663 {
664         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_GENERIC\n", " generic"},
665         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_POSTPROCESS\n", " postprocess"},
666         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
667         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
668         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
669         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTMAP\n", " lightmap"},
670         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FAKELIGHT\n", " fakelight"},
671         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
672         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
673         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_FORCED_LIGHTMAP\n", " lightdirectionmap_forced_lightmap"},
674         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_FORCED_VERTEXCOLOR\n", " lightdirectionmap_forced_vertexcolor"},
675         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
676         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
677         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_REFRACTION\n", " refraction"},
678         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_WATER\n", " water"},
679         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
680         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
681         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
682 };
683
684 shadermodeinfo_t hlslshadermodeinfo[SHADERMODE_COUNT] =
685 {
686         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_GENERIC\n", " generic"},
687         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_POSTPROCESS\n", " postprocess"},
688         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
689         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
690         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
691         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTMAP\n", " lightmap"},
692         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_FAKELIGHT\n", " fakelight"},
693         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
694         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
695         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_FORCED_LIGHTMAP\n", " lightdirectionmap_forced_lightmap"},
696         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_FORCED_VERTEXCOLOR\n", " lightdirectionmap_forced_vertexcolor"},
697         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
698         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
699         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_REFRACTION\n", " refraction"},
700         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_WATER\n", " water"},
701         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
702         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
703         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
704 };
705
706 struct r_glsl_permutation_s;
707 typedef struct r_glsl_permutation_s
708 {
709         /// hash lookup data
710         struct r_glsl_permutation_s *hashnext;
711         unsigned int mode;
712         unsigned int permutation;
713
714         /// indicates if we have tried compiling this permutation already
715         qboolean compiled;
716         /// 0 if compilation failed
717         int program;
718         // texture units assigned to each detected uniform
719         int tex_Texture_First;
720         int tex_Texture_Second;
721         int tex_Texture_GammaRamps;
722         int tex_Texture_Normal;
723         int tex_Texture_Color;
724         int tex_Texture_Gloss;
725         int tex_Texture_Glow;
726         int tex_Texture_SecondaryNormal;
727         int tex_Texture_SecondaryColor;
728         int tex_Texture_SecondaryGloss;
729         int tex_Texture_SecondaryGlow;
730         int tex_Texture_Pants;
731         int tex_Texture_Shirt;
732         int tex_Texture_FogHeightTexture;
733         int tex_Texture_FogMask;
734         int tex_Texture_Lightmap;
735         int tex_Texture_Deluxemap;
736         int tex_Texture_Attenuation;
737         int tex_Texture_Cube;
738         int tex_Texture_Refraction;
739         int tex_Texture_Reflection;
740         int tex_Texture_ShadowMap2D;
741         int tex_Texture_CubeProjection;
742         int tex_Texture_ScreenNormalMap;
743         int tex_Texture_ScreenDiffuse;
744         int tex_Texture_ScreenSpecular;
745         int tex_Texture_ReflectMask;
746         int tex_Texture_ReflectCube;
747         int tex_Texture_BounceGrid;
748         /// locations of detected uniforms in program object, or -1 if not found
749         int loc_Texture_First;
750         int loc_Texture_Second;
751         int loc_Texture_GammaRamps;
752         int loc_Texture_Normal;
753         int loc_Texture_Color;
754         int loc_Texture_Gloss;
755         int loc_Texture_Glow;
756         int loc_Texture_SecondaryNormal;
757         int loc_Texture_SecondaryColor;
758         int loc_Texture_SecondaryGloss;
759         int loc_Texture_SecondaryGlow;
760         int loc_Texture_Pants;
761         int loc_Texture_Shirt;
762         int loc_Texture_FogHeightTexture;
763         int loc_Texture_FogMask;
764         int loc_Texture_Lightmap;
765         int loc_Texture_Deluxemap;
766         int loc_Texture_Attenuation;
767         int loc_Texture_Cube;
768         int loc_Texture_Refraction;
769         int loc_Texture_Reflection;
770         int loc_Texture_ShadowMap2D;
771         int loc_Texture_CubeProjection;
772         int loc_Texture_ScreenNormalMap;
773         int loc_Texture_ScreenDiffuse;
774         int loc_Texture_ScreenSpecular;
775         int loc_Texture_ReflectMask;
776         int loc_Texture_ReflectCube;
777         int loc_Texture_BounceGrid;
778         int loc_Alpha;
779         int loc_BloomBlur_Parameters;
780         int loc_ClientTime;
781         int loc_Color_Ambient;
782         int loc_Color_Diffuse;
783         int loc_Color_Specular;
784         int loc_Color_Glow;
785         int loc_Color_Pants;
786         int loc_Color_Shirt;
787         int loc_DeferredColor_Ambient;
788         int loc_DeferredColor_Diffuse;
789         int loc_DeferredColor_Specular;
790         int loc_DeferredMod_Diffuse;
791         int loc_DeferredMod_Specular;
792         int loc_DistortScaleRefractReflect;
793         int loc_EyePosition;
794         int loc_FogColor;
795         int loc_FogHeightFade;
796         int loc_FogPlane;
797         int loc_FogPlaneViewDist;
798         int loc_FogRangeRecip;
799         int loc_LightColor;
800         int loc_LightDir;
801         int loc_LightPosition;
802         int loc_OffsetMapping_ScaleSteps;
803         int loc_OffsetMapping_LodDistance;
804         int loc_OffsetMapping_Bias;
805         int loc_PixelSize;
806         int loc_ReflectColor;
807         int loc_ReflectFactor;
808         int loc_ReflectOffset;
809         int loc_RefractColor;
810         int loc_Saturation;
811         int loc_ScreenCenterRefractReflect;
812         int loc_ScreenScaleRefractReflect;
813         int loc_ScreenToDepth;
814         int loc_ShadowMap_Parameters;
815         int loc_ShadowMap_TextureScale;
816         int loc_SpecularPower;
817         int loc_UserVec1;
818         int loc_UserVec2;
819         int loc_UserVec3;
820         int loc_UserVec4;
821         int loc_ViewTintColor;
822         int loc_ViewToLight;
823         int loc_ModelToLight;
824         int loc_TexMatrix;
825         int loc_BackgroundTexMatrix;
826         int loc_ModelViewProjectionMatrix;
827         int loc_ModelViewMatrix;
828         int loc_PixelToScreenTexCoord;
829         int loc_ModelToReflectCube;
830         int loc_ShadowMapMatrix;
831         int loc_BloomColorSubtract;
832         int loc_NormalmapScrollBlend;
833         int loc_BounceGridMatrix;
834         int loc_BounceGridIntensity;
835 }
836 r_glsl_permutation_t;
837
838 #define SHADERPERMUTATION_HASHSIZE 256
839
840
841 // non-degradable "lightweight" shader parameters to keep the permutations simpler
842 // these can NOT degrade! only use for simple stuff
843 enum
844 {
845         SHADERSTATICPARM_SATURATION_REDCOMPENSATE = 0, ///< red compensation filter for saturation
846         SHADERSTATICPARM_EXACTSPECULARMATH = 1, ///< (lightsource or deluxemapping) use exact reflection map for specular effects, as opposed to the usual OpenGL approximation
847         SHADERSTATICPARM_POSTPROCESS_USERVEC1 = 2, ///< postprocess uservec1 is enabled
848         SHADERSTATICPARM_POSTPROCESS_USERVEC2 = 3, ///< postprocess uservec2 is enabled
849         SHADERSTATICPARM_POSTPROCESS_USERVEC3 = 4, ///< postprocess uservec3 is enabled
850         SHADERSTATICPARM_POSTPROCESS_USERVEC4 = 5,  ///< postprocess uservec4 is enabled
851         SHADERSTATICPARM_VERTEXTEXTUREBLEND_USEBOTHALPHAS = 6, // use both alpha layers while blending materials, allows more advanced microblending
852         SHADERSTATICPARM_OFFSETMAPPING_USELOD = 7,  ///< LOD for offsetmapping
853 };
854 #define SHADERSTATICPARMS_COUNT 8
855
856 static const char *shaderstaticparmstrings_list[SHADERSTATICPARMS_COUNT];
857 static int shaderstaticparms_count = 0;
858
859 static unsigned int r_compileshader_staticparms[(SHADERSTATICPARMS_COUNT + 0x1F) >> 5] = {0};
860 #define R_COMPILESHADER_STATICPARM_ENABLE(p) r_compileshader_staticparms[(p) >> 5] |= (1 << ((p) & 0x1F))
861 static qboolean R_CompileShader_CheckStaticParms(void)
862 {
863         static int r_compileshader_staticparms_save[1];
864         memcpy(r_compileshader_staticparms_save, r_compileshader_staticparms, sizeof(r_compileshader_staticparms));
865         memset(r_compileshader_staticparms, 0, sizeof(r_compileshader_staticparms));
866
867         // detect all
868         if (r_glsl_saturation_redcompensate.integer)
869                 R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_SATURATION_REDCOMPENSATE);
870         if (r_glsl_vertextextureblend_usebothalphas.integer)
871                 R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_VERTEXTEXTUREBLEND_USEBOTHALPHAS);
872         if (r_shadow_glossexact.integer)
873                 R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_EXACTSPECULARMATH);
874         if (r_glsl_postprocess.integer)
875         {
876                 if (r_glsl_postprocess_uservec1_enable.integer)
877                         R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC1);
878                 if (r_glsl_postprocess_uservec2_enable.integer)
879                         R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC2);
880                 if (r_glsl_postprocess_uservec3_enable.integer)
881                         R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC3);
882                 if (r_glsl_postprocess_uservec4_enable.integer)
883                         R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC4);
884         }
885         if (r_glsl_offsetmapping_lod.integer && r_glsl_offsetmapping_lod_distance.integer > 0)
886                 R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_OFFSETMAPPING_USELOD);
887         return memcmp(r_compileshader_staticparms, r_compileshader_staticparms_save, sizeof(r_compileshader_staticparms)) != 0;
888 }
889
890 #define R_COMPILESHADER_STATICPARM_EMIT(p, n) \
891         if(r_compileshader_staticparms[(p) >> 5] & (1 << ((p) & 0x1F))) \
892                 shaderstaticparmstrings_list[shaderstaticparms_count++] = "#define " n "\n"; \
893         else \
894                 shaderstaticparmstrings_list[shaderstaticparms_count++] = "\n"
895 static void R_CompileShader_AddStaticParms(unsigned int mode, unsigned int permutation)
896 {
897         shaderstaticparms_count = 0;
898
899         // emit all
900         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_SATURATION_REDCOMPENSATE, "SATURATION_REDCOMPENSATE");
901         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_EXACTSPECULARMATH, "USEEXACTSPECULARMATH");
902         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_POSTPROCESS_USERVEC1, "USERVEC1");
903         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_POSTPROCESS_USERVEC2, "USERVEC2");
904         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_POSTPROCESS_USERVEC3, "USERVEC3");
905         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_POSTPROCESS_USERVEC4, "USERVEC4");
906         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_VERTEXTEXTUREBLEND_USEBOTHALPHAS, "USEBOTHALPHAS");
907         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_OFFSETMAPPING_USELOD, "USEOFFSETMAPPING_LOD");
908 }
909
910 /// information about each possible shader permutation
911 r_glsl_permutation_t *r_glsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
912 /// currently selected permutation
913 r_glsl_permutation_t *r_glsl_permutation;
914 /// storage for permutations linked in the hash table
915 memexpandablearray_t r_glsl_permutationarray;
916
917 static r_glsl_permutation_t *R_GLSL_FindPermutation(unsigned int mode, unsigned int permutation)
918 {
919         //unsigned int hashdepth = 0;
920         unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
921         r_glsl_permutation_t *p;
922         for (p = r_glsl_permutationhash[mode][hashindex];p;p = p->hashnext)
923         {
924                 if (p->mode == mode && p->permutation == permutation)
925                 {
926                         //if (hashdepth > 10)
927                         //      Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
928                         return p;
929                 }
930                 //hashdepth++;
931         }
932         p = (r_glsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_glsl_permutationarray);
933         p->mode = mode;
934         p->permutation = permutation;
935         p->hashnext = r_glsl_permutationhash[mode][hashindex];
936         r_glsl_permutationhash[mode][hashindex] = p;
937         //if (hashdepth > 10)
938         //      Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
939         return p;
940 }
941
942 static char *R_GLSL_GetText(const char *filename, qboolean printfromdisknotice)
943 {
944         char *shaderstring;
945         if (!filename || !filename[0])
946                 return NULL;
947         if (!strcmp(filename, "glsl/default.glsl"))
948         {
949                 if (!glslshaderstring)
950                 {
951                         glslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
952                         if (glslshaderstring)
953                                 Con_DPrintf("Loading shaders from file %s...\n", filename);
954                         else
955                                 glslshaderstring = (char *)builtinshaderstring;
956                 }
957                 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(glslshaderstring) + 1);
958                 memcpy(shaderstring, glslshaderstring, strlen(glslshaderstring) + 1);
959                 return shaderstring;
960         }
961         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
962         if (shaderstring)
963         {
964                 if (printfromdisknotice)
965                         Con_DPrintf("from disk %s... ", filename);
966                 return shaderstring;
967         }
968         return shaderstring;
969 }
970
971 static void R_GLSL_CompilePermutation(r_glsl_permutation_t *p, unsigned int mode, unsigned int permutation)
972 {
973         int i;
974         int sampler;
975         shadermodeinfo_t *modeinfo = glslshadermodeinfo + mode;
976         char *vertexstring, *geometrystring, *fragmentstring;
977         char permutationname[256];
978         int vertstrings_count = 0;
979         int geomstrings_count = 0;
980         int fragstrings_count = 0;
981         const char *vertstrings_list[32+5+SHADERSTATICPARMS_COUNT+1];
982         const char *geomstrings_list[32+5+SHADERSTATICPARMS_COUNT+1];
983         const char *fragstrings_list[32+5+SHADERSTATICPARMS_COUNT+1];
984
985         if (p->compiled)
986                 return;
987         p->compiled = true;
988         p->program = 0;
989
990         permutationname[0] = 0;
991         vertexstring   = R_GLSL_GetText(modeinfo->vertexfilename, true);
992         geometrystring = R_GLSL_GetText(modeinfo->geometryfilename, false);
993         fragmentstring = R_GLSL_GetText(modeinfo->fragmentfilename, false);
994
995         strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
996
997         // if we can do #version 130, we should (this improves quality of offset/reliefmapping thanks to textureGrad)
998         if(vid.support.gl20shaders130)
999         {
1000                 vertstrings_list[vertstrings_count++] = "#version 130\n";
1001                 geomstrings_list[geomstrings_count++] = "#version 130\n";
1002                 fragstrings_list[fragstrings_count++] = "#version 130\n";
1003                 vertstrings_list[vertstrings_count++] = "#define GLSL130\n";
1004                 geomstrings_list[geomstrings_count++] = "#define GLSL130\n";
1005                 fragstrings_list[fragstrings_count++] = "#define GLSL130\n";
1006         }
1007
1008         // the first pretext is which type of shader to compile as
1009         // (later these will all be bound together as a program object)
1010         vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
1011         geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
1012         fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
1013
1014         // the second pretext is the mode (for example a light source)
1015         vertstrings_list[vertstrings_count++] = modeinfo->pretext;
1016         geomstrings_list[geomstrings_count++] = modeinfo->pretext;
1017         fragstrings_list[fragstrings_count++] = modeinfo->pretext;
1018         strlcat(permutationname, modeinfo->name, sizeof(permutationname));
1019
1020         // now add all the permutation pretexts
1021         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1022         {
1023                 if (permutation & (1<<i))
1024                 {
1025                         vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
1026                         geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
1027                         fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
1028                         strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
1029                 }
1030                 else
1031                 {
1032                         // keep line numbers correct
1033                         vertstrings_list[vertstrings_count++] = "\n";
1034                         geomstrings_list[geomstrings_count++] = "\n";
1035                         fragstrings_list[fragstrings_count++] = "\n";
1036                 }
1037         }
1038
1039         // add static parms
1040         R_CompileShader_AddStaticParms(mode, permutation);
1041         memcpy((char *)(vertstrings_list + vertstrings_count), shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
1042         vertstrings_count += shaderstaticparms_count;
1043         memcpy((char *)(geomstrings_list + geomstrings_count), shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
1044         geomstrings_count += shaderstaticparms_count;
1045         memcpy((char *)(fragstrings_list + fragstrings_count), shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
1046         fragstrings_count += shaderstaticparms_count;
1047
1048         // now append the shader text itself
1049         vertstrings_list[vertstrings_count++] = vertexstring;
1050         geomstrings_list[geomstrings_count++] = geometrystring;
1051         fragstrings_list[fragstrings_count++] = fragmentstring;
1052
1053         // if any sources were NULL, clear the respective list
1054         if (!vertexstring)
1055                 vertstrings_count = 0;
1056         if (!geometrystring)
1057                 geomstrings_count = 0;
1058         if (!fragmentstring)
1059                 fragstrings_count = 0;
1060
1061         // compile the shader program
1062         if (vertstrings_count + geomstrings_count + fragstrings_count)
1063                 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
1064         if (p->program)
1065         {
1066                 CHECKGLERROR
1067                 qglUseProgram(p->program);CHECKGLERROR
1068                 // look up all the uniform variable names we care about, so we don't
1069                 // have to look them up every time we set them
1070
1071                 p->loc_Texture_First              = qglGetUniformLocation(p->program, "Texture_First");
1072                 p->loc_Texture_Second             = qglGetUniformLocation(p->program, "Texture_Second");
1073                 p->loc_Texture_GammaRamps         = qglGetUniformLocation(p->program, "Texture_GammaRamps");
1074                 p->loc_Texture_Normal             = qglGetUniformLocation(p->program, "Texture_Normal");
1075                 p->loc_Texture_Color              = qglGetUniformLocation(p->program, "Texture_Color");
1076                 p->loc_Texture_Gloss              = qglGetUniformLocation(p->program, "Texture_Gloss");
1077                 p->loc_Texture_Glow               = qglGetUniformLocation(p->program, "Texture_Glow");
1078                 p->loc_Texture_SecondaryNormal    = qglGetUniformLocation(p->program, "Texture_SecondaryNormal");
1079                 p->loc_Texture_SecondaryColor     = qglGetUniformLocation(p->program, "Texture_SecondaryColor");
1080                 p->loc_Texture_SecondaryGloss     = qglGetUniformLocation(p->program, "Texture_SecondaryGloss");
1081                 p->loc_Texture_SecondaryGlow      = qglGetUniformLocation(p->program, "Texture_SecondaryGlow");
1082                 p->loc_Texture_Pants              = qglGetUniformLocation(p->program, "Texture_Pants");
1083                 p->loc_Texture_Shirt              = qglGetUniformLocation(p->program, "Texture_Shirt");
1084                 p->loc_Texture_FogHeightTexture   = qglGetUniformLocation(p->program, "Texture_FogHeightTexture");
1085                 p->loc_Texture_FogMask            = qglGetUniformLocation(p->program, "Texture_FogMask");
1086                 p->loc_Texture_Lightmap           = qglGetUniformLocation(p->program, "Texture_Lightmap");
1087                 p->loc_Texture_Deluxemap          = qglGetUniformLocation(p->program, "Texture_Deluxemap");
1088                 p->loc_Texture_Attenuation        = qglGetUniformLocation(p->program, "Texture_Attenuation");
1089                 p->loc_Texture_Cube               = qglGetUniformLocation(p->program, "Texture_Cube");
1090                 p->loc_Texture_Refraction         = qglGetUniformLocation(p->program, "Texture_Refraction");
1091                 p->loc_Texture_Reflection         = qglGetUniformLocation(p->program, "Texture_Reflection");
1092                 p->loc_Texture_ShadowMap2D        = qglGetUniformLocation(p->program, "Texture_ShadowMap2D");
1093                 p->loc_Texture_CubeProjection     = qglGetUniformLocation(p->program, "Texture_CubeProjection");
1094                 p->loc_Texture_ScreenNormalMap    = qglGetUniformLocation(p->program, "Texture_ScreenNormalMap");
1095                 p->loc_Texture_ScreenDiffuse      = qglGetUniformLocation(p->program, "Texture_ScreenDiffuse");
1096                 p->loc_Texture_ScreenSpecular     = qglGetUniformLocation(p->program, "Texture_ScreenSpecular");
1097                 p->loc_Texture_ReflectMask        = qglGetUniformLocation(p->program, "Texture_ReflectMask");
1098                 p->loc_Texture_ReflectCube        = qglGetUniformLocation(p->program, "Texture_ReflectCube");
1099                 p->loc_Texture_BounceGrid         = qglGetUniformLocation(p->program, "Texture_BounceGrid");
1100                 p->loc_Alpha                      = qglGetUniformLocation(p->program, "Alpha");
1101                 p->loc_BloomBlur_Parameters       = qglGetUniformLocation(p->program, "BloomBlur_Parameters");
1102                 p->loc_ClientTime                 = qglGetUniformLocation(p->program, "ClientTime");
1103                 p->loc_Color_Ambient              = qglGetUniformLocation(p->program, "Color_Ambient");
1104                 p->loc_Color_Diffuse              = qglGetUniformLocation(p->program, "Color_Diffuse");
1105                 p->loc_Color_Specular             = qglGetUniformLocation(p->program, "Color_Specular");
1106                 p->loc_Color_Glow                 = qglGetUniformLocation(p->program, "Color_Glow");
1107                 p->loc_Color_Pants                = qglGetUniformLocation(p->program, "Color_Pants");
1108                 p->loc_Color_Shirt                = qglGetUniformLocation(p->program, "Color_Shirt");
1109                 p->loc_DeferredColor_Ambient      = qglGetUniformLocation(p->program, "DeferredColor_Ambient");
1110                 p->loc_DeferredColor_Diffuse      = qglGetUniformLocation(p->program, "DeferredColor_Diffuse");
1111                 p->loc_DeferredColor_Specular     = qglGetUniformLocation(p->program, "DeferredColor_Specular");
1112                 p->loc_DeferredMod_Diffuse        = qglGetUniformLocation(p->program, "DeferredMod_Diffuse");
1113                 p->loc_DeferredMod_Specular       = qglGetUniformLocation(p->program, "DeferredMod_Specular");
1114                 p->loc_DistortScaleRefractReflect = qglGetUniformLocation(p->program, "DistortScaleRefractReflect");
1115                 p->loc_EyePosition                = qglGetUniformLocation(p->program, "EyePosition");
1116                 p->loc_FogColor                   = qglGetUniformLocation(p->program, "FogColor");
1117                 p->loc_FogHeightFade              = qglGetUniformLocation(p->program, "FogHeightFade");
1118                 p->loc_FogPlane                   = qglGetUniformLocation(p->program, "FogPlane");
1119                 p->loc_FogPlaneViewDist           = qglGetUniformLocation(p->program, "FogPlaneViewDist");
1120                 p->loc_FogRangeRecip              = qglGetUniformLocation(p->program, "FogRangeRecip");
1121                 p->loc_LightColor                 = qglGetUniformLocation(p->program, "LightColor");
1122                 p->loc_LightDir                   = qglGetUniformLocation(p->program, "LightDir");
1123                 p->loc_LightPosition              = qglGetUniformLocation(p->program, "LightPosition");
1124                 p->loc_OffsetMapping_ScaleSteps   = qglGetUniformLocation(p->program, "OffsetMapping_ScaleSteps");
1125                 p->loc_OffsetMapping_LodDistance  = qglGetUniformLocation(p->program, "OffsetMapping_LodDistance");
1126                 p->loc_OffsetMapping_Bias         = qglGetUniformLocation(p->program, "OffsetMapping_Bias");
1127                 p->loc_PixelSize                  = qglGetUniformLocation(p->program, "PixelSize");
1128                 p->loc_ReflectColor               = qglGetUniformLocation(p->program, "ReflectColor");
1129                 p->loc_ReflectFactor              = qglGetUniformLocation(p->program, "ReflectFactor");
1130                 p->loc_ReflectOffset              = qglGetUniformLocation(p->program, "ReflectOffset");
1131                 p->loc_RefractColor               = qglGetUniformLocation(p->program, "RefractColor");
1132                 p->loc_Saturation                 = qglGetUniformLocation(p->program, "Saturation");
1133                 p->loc_ScreenCenterRefractReflect = qglGetUniformLocation(p->program, "ScreenCenterRefractReflect");
1134                 p->loc_ScreenScaleRefractReflect  = qglGetUniformLocation(p->program, "ScreenScaleRefractReflect");
1135                 p->loc_ScreenToDepth              = qglGetUniformLocation(p->program, "ScreenToDepth");
1136                 p->loc_ShadowMap_Parameters       = qglGetUniformLocation(p->program, "ShadowMap_Parameters");
1137                 p->loc_ShadowMap_TextureScale     = qglGetUniformLocation(p->program, "ShadowMap_TextureScale");
1138                 p->loc_SpecularPower              = qglGetUniformLocation(p->program, "SpecularPower");
1139                 p->loc_UserVec1                   = qglGetUniformLocation(p->program, "UserVec1");
1140                 p->loc_UserVec2                   = qglGetUniformLocation(p->program, "UserVec2");
1141                 p->loc_UserVec3                   = qglGetUniformLocation(p->program, "UserVec3");
1142                 p->loc_UserVec4                   = qglGetUniformLocation(p->program, "UserVec4");
1143                 p->loc_ViewTintColor              = qglGetUniformLocation(p->program, "ViewTintColor");
1144                 p->loc_ViewToLight                = qglGetUniformLocation(p->program, "ViewToLight");
1145                 p->loc_ModelToLight               = qglGetUniformLocation(p->program, "ModelToLight");
1146                 p->loc_TexMatrix                  = qglGetUniformLocation(p->program, "TexMatrix");
1147                 p->loc_BackgroundTexMatrix        = qglGetUniformLocation(p->program, "BackgroundTexMatrix");
1148                 p->loc_ModelViewMatrix            = qglGetUniformLocation(p->program, "ModelViewMatrix");
1149                 p->loc_ModelViewProjectionMatrix  = qglGetUniformLocation(p->program, "ModelViewProjectionMatrix");
1150                 p->loc_PixelToScreenTexCoord      = qglGetUniformLocation(p->program, "PixelToScreenTexCoord");
1151                 p->loc_ModelToReflectCube         = qglGetUniformLocation(p->program, "ModelToReflectCube");
1152                 p->loc_ShadowMapMatrix            = qglGetUniformLocation(p->program, "ShadowMapMatrix");
1153                 p->loc_BloomColorSubtract         = qglGetUniformLocation(p->program, "BloomColorSubtract");
1154                 p->loc_NormalmapScrollBlend       = qglGetUniformLocation(p->program, "NormalmapScrollBlend");
1155                 p->loc_BounceGridMatrix           = qglGetUniformLocation(p->program, "BounceGridMatrix");
1156                 p->loc_BounceGridIntensity        = qglGetUniformLocation(p->program, "BounceGridIntensity");
1157                 // initialize the samplers to refer to the texture units we use
1158                 p->tex_Texture_First = -1;
1159                 p->tex_Texture_Second = -1;
1160                 p->tex_Texture_GammaRamps = -1;
1161                 p->tex_Texture_Normal = -1;
1162                 p->tex_Texture_Color = -1;
1163                 p->tex_Texture_Gloss = -1;
1164                 p->tex_Texture_Glow = -1;
1165                 p->tex_Texture_SecondaryNormal = -1;
1166                 p->tex_Texture_SecondaryColor = -1;
1167                 p->tex_Texture_SecondaryGloss = -1;
1168                 p->tex_Texture_SecondaryGlow = -1;
1169                 p->tex_Texture_Pants = -1;
1170                 p->tex_Texture_Shirt = -1;
1171                 p->tex_Texture_FogHeightTexture = -1;
1172                 p->tex_Texture_FogMask = -1;
1173                 p->tex_Texture_Lightmap = -1;
1174                 p->tex_Texture_Deluxemap = -1;
1175                 p->tex_Texture_Attenuation = -1;
1176                 p->tex_Texture_Cube = -1;
1177                 p->tex_Texture_Refraction = -1;
1178                 p->tex_Texture_Reflection = -1;
1179                 p->tex_Texture_ShadowMap2D = -1;
1180                 p->tex_Texture_CubeProjection = -1;
1181                 p->tex_Texture_ScreenNormalMap = -1;
1182                 p->tex_Texture_ScreenDiffuse = -1;
1183                 p->tex_Texture_ScreenSpecular = -1;
1184                 p->tex_Texture_ReflectMask = -1;
1185                 p->tex_Texture_ReflectCube = -1;
1186                 p->tex_Texture_BounceGrid = -1;
1187                 sampler = 0;
1188                 if (p->loc_Texture_First           >= 0) {p->tex_Texture_First            = sampler;qglUniform1i(p->loc_Texture_First           , sampler);sampler++;}
1189                 if (p->loc_Texture_Second          >= 0) {p->tex_Texture_Second           = sampler;qglUniform1i(p->loc_Texture_Second          , sampler);sampler++;}
1190                 if (p->loc_Texture_GammaRamps      >= 0) {p->tex_Texture_GammaRamps       = sampler;qglUniform1i(p->loc_Texture_GammaRamps      , sampler);sampler++;}
1191                 if (p->loc_Texture_Normal          >= 0) {p->tex_Texture_Normal           = sampler;qglUniform1i(p->loc_Texture_Normal          , sampler);sampler++;}
1192                 if (p->loc_Texture_Color           >= 0) {p->tex_Texture_Color            = sampler;qglUniform1i(p->loc_Texture_Color           , sampler);sampler++;}
1193                 if (p->loc_Texture_Gloss           >= 0) {p->tex_Texture_Gloss            = sampler;qglUniform1i(p->loc_Texture_Gloss           , sampler);sampler++;}
1194                 if (p->loc_Texture_Glow            >= 0) {p->tex_Texture_Glow             = sampler;qglUniform1i(p->loc_Texture_Glow            , sampler);sampler++;}
1195                 if (p->loc_Texture_SecondaryNormal >= 0) {p->tex_Texture_SecondaryNormal  = sampler;qglUniform1i(p->loc_Texture_SecondaryNormal , sampler);sampler++;}
1196                 if (p->loc_Texture_SecondaryColor  >= 0) {p->tex_Texture_SecondaryColor   = sampler;qglUniform1i(p->loc_Texture_SecondaryColor  , sampler);sampler++;}
1197                 if (p->loc_Texture_SecondaryGloss  >= 0) {p->tex_Texture_SecondaryGloss   = sampler;qglUniform1i(p->loc_Texture_SecondaryGloss  , sampler);sampler++;}
1198                 if (p->loc_Texture_SecondaryGlow   >= 0) {p->tex_Texture_SecondaryGlow    = sampler;qglUniform1i(p->loc_Texture_SecondaryGlow   , sampler);sampler++;}
1199                 if (p->loc_Texture_Pants           >= 0) {p->tex_Texture_Pants            = sampler;qglUniform1i(p->loc_Texture_Pants           , sampler);sampler++;}
1200                 if (p->loc_Texture_Shirt           >= 0) {p->tex_Texture_Shirt            = sampler;qglUniform1i(p->loc_Texture_Shirt           , sampler);sampler++;}
1201                 if (p->loc_Texture_FogHeightTexture>= 0) {p->tex_Texture_FogHeightTexture = sampler;qglUniform1i(p->loc_Texture_FogHeightTexture, sampler);sampler++;}
1202                 if (p->loc_Texture_FogMask         >= 0) {p->tex_Texture_FogMask          = sampler;qglUniform1i(p->loc_Texture_FogMask         , sampler);sampler++;}
1203                 if (p->loc_Texture_Lightmap        >= 0) {p->tex_Texture_Lightmap         = sampler;qglUniform1i(p->loc_Texture_Lightmap        , sampler);sampler++;}
1204                 if (p->loc_Texture_Deluxemap       >= 0) {p->tex_Texture_Deluxemap        = sampler;qglUniform1i(p->loc_Texture_Deluxemap       , sampler);sampler++;}
1205                 if (p->loc_Texture_Attenuation     >= 0) {p->tex_Texture_Attenuation      = sampler;qglUniform1i(p->loc_Texture_Attenuation     , sampler);sampler++;}
1206                 if (p->loc_Texture_Cube            >= 0) {p->tex_Texture_Cube             = sampler;qglUniform1i(p->loc_Texture_Cube            , sampler);sampler++;}
1207                 if (p->loc_Texture_Refraction      >= 0) {p->tex_Texture_Refraction       = sampler;qglUniform1i(p->loc_Texture_Refraction      , sampler);sampler++;}
1208                 if (p->loc_Texture_Reflection      >= 0) {p->tex_Texture_Reflection       = sampler;qglUniform1i(p->loc_Texture_Reflection      , sampler);sampler++;}
1209                 if (p->loc_Texture_ShadowMap2D     >= 0) {p->tex_Texture_ShadowMap2D      = sampler;qglUniform1i(p->loc_Texture_ShadowMap2D     , sampler);sampler++;}
1210                 if (p->loc_Texture_CubeProjection  >= 0) {p->tex_Texture_CubeProjection   = sampler;qglUniform1i(p->loc_Texture_CubeProjection  , sampler);sampler++;}
1211                 if (p->loc_Texture_ScreenNormalMap >= 0) {p->tex_Texture_ScreenNormalMap  = sampler;qglUniform1i(p->loc_Texture_ScreenNormalMap , sampler);sampler++;}
1212                 if (p->loc_Texture_ScreenDiffuse   >= 0) {p->tex_Texture_ScreenDiffuse    = sampler;qglUniform1i(p->loc_Texture_ScreenDiffuse   , sampler);sampler++;}
1213                 if (p->loc_Texture_ScreenSpecular  >= 0) {p->tex_Texture_ScreenSpecular   = sampler;qglUniform1i(p->loc_Texture_ScreenSpecular  , sampler);sampler++;}
1214                 if (p->loc_Texture_ReflectMask     >= 0) {p->tex_Texture_ReflectMask      = sampler;qglUniform1i(p->loc_Texture_ReflectMask     , sampler);sampler++;}
1215                 if (p->loc_Texture_ReflectCube     >= 0) {p->tex_Texture_ReflectCube      = sampler;qglUniform1i(p->loc_Texture_ReflectCube     , sampler);sampler++;}
1216                 if (p->loc_Texture_BounceGrid      >= 0) {p->tex_Texture_BounceGrid       = sampler;qglUniform1i(p->loc_Texture_BounceGrid      , sampler);sampler++;}
1217                 CHECKGLERROR
1218                 Con_DPrintf("^5GLSL shader %s compiled (%i textures).\n", permutationname, sampler);
1219         }
1220         else
1221                 Con_Printf("^1GLSL shader %s failed!  some features may not work properly.\n", permutationname);
1222
1223         // free the strings
1224         if (vertexstring)
1225                 Mem_Free(vertexstring);
1226         if (geometrystring)
1227                 Mem_Free(geometrystring);
1228         if (fragmentstring)
1229                 Mem_Free(fragmentstring);
1230 }
1231
1232 static void R_SetupShader_SetPermutationGLSL(unsigned int mode, unsigned int permutation)
1233 {
1234         r_glsl_permutation_t *perm = R_GLSL_FindPermutation(mode, permutation);
1235         if (r_glsl_permutation != perm)
1236         {
1237                 r_glsl_permutation = perm;
1238                 if (!r_glsl_permutation->program)
1239                 {
1240                         if (!r_glsl_permutation->compiled)
1241                                 R_GLSL_CompilePermutation(perm, mode, permutation);
1242                         if (!r_glsl_permutation->program)
1243                         {
1244                                 // remove features until we find a valid permutation
1245                                 int i;
1246                                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1247                                 {
1248                                         // reduce i more quickly whenever it would not remove any bits
1249                                         int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
1250                                         if (!(permutation & j))
1251                                                 continue;
1252                                         permutation -= j;
1253                                         r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
1254                                         if (!r_glsl_permutation->compiled)
1255                                                 R_GLSL_CompilePermutation(perm, mode, permutation);
1256                                         if (r_glsl_permutation->program)
1257                                                 break;
1258                                 }
1259                                 if (i >= SHADERPERMUTATION_COUNT)
1260                                 {
1261                                         //Con_Printf("Could not find a working OpenGL 2.0 shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
1262                                         r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
1263                                         qglUseProgram(0);CHECKGLERROR
1264                                         return; // no bit left to clear, entire mode is broken
1265                                 }
1266                         }
1267                 }
1268                 CHECKGLERROR
1269                 qglUseProgram(r_glsl_permutation->program);CHECKGLERROR
1270         }
1271         if (r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
1272         if (r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
1273         if (r_glsl_permutation->loc_ClientTime >= 0) qglUniform1f(r_glsl_permutation->loc_ClientTime, cl.time);
1274 }
1275
1276 #ifdef SUPPORTD3D
1277
1278 #ifdef SUPPORTD3D
1279 #include <d3d9.h>
1280 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
1281 extern D3DCAPS9 vid_d3d9caps;
1282 #endif
1283
1284 struct r_hlsl_permutation_s;
1285 typedef struct r_hlsl_permutation_s
1286 {
1287         /// hash lookup data
1288         struct r_hlsl_permutation_s *hashnext;
1289         unsigned int mode;
1290         unsigned int permutation;
1291
1292         /// indicates if we have tried compiling this permutation already
1293         qboolean compiled;
1294         /// NULL if compilation failed
1295         IDirect3DVertexShader9 *vertexshader;
1296         IDirect3DPixelShader9 *pixelshader;
1297 }
1298 r_hlsl_permutation_t;
1299
1300 typedef enum D3DVSREGISTER_e
1301 {
1302         D3DVSREGISTER_TexMatrix = 0, // float4x4
1303         D3DVSREGISTER_BackgroundTexMatrix = 4, // float4x4
1304         D3DVSREGISTER_ModelViewProjectionMatrix = 8, // float4x4
1305         D3DVSREGISTER_ModelViewMatrix = 12, // float4x4
1306         D3DVSREGISTER_ShadowMapMatrix = 16, // float4x4
1307         D3DVSREGISTER_ModelToLight = 20, // float4x4
1308         D3DVSREGISTER_EyePosition = 24,
1309         D3DVSREGISTER_FogPlane = 25,
1310         D3DVSREGISTER_LightDir = 26,
1311         D3DVSREGISTER_LightPosition = 27,
1312 }
1313 D3DVSREGISTER_t;
1314
1315 typedef enum D3DPSREGISTER_e
1316 {
1317         D3DPSREGISTER_Alpha = 0,
1318         D3DPSREGISTER_BloomBlur_Parameters = 1,
1319         D3DPSREGISTER_ClientTime = 2,
1320         D3DPSREGISTER_Color_Ambient = 3,
1321         D3DPSREGISTER_Color_Diffuse = 4,
1322         D3DPSREGISTER_Color_Specular = 5,
1323         D3DPSREGISTER_Color_Glow = 6,
1324         D3DPSREGISTER_Color_Pants = 7,
1325         D3DPSREGISTER_Color_Shirt = 8,
1326         D3DPSREGISTER_DeferredColor_Ambient = 9,
1327         D3DPSREGISTER_DeferredColor_Diffuse = 10,
1328         D3DPSREGISTER_DeferredColor_Specular = 11,
1329         D3DPSREGISTER_DeferredMod_Diffuse = 12,
1330         D3DPSREGISTER_DeferredMod_Specular = 13,
1331         D3DPSREGISTER_DistortScaleRefractReflect = 14,
1332         D3DPSREGISTER_EyePosition = 15, // unused
1333         D3DPSREGISTER_FogColor = 16,
1334         D3DPSREGISTER_FogHeightFade = 17,
1335         D3DPSREGISTER_FogPlane = 18,
1336         D3DPSREGISTER_FogPlaneViewDist = 19,
1337         D3DPSREGISTER_FogRangeRecip = 20,
1338         D3DPSREGISTER_LightColor = 21,
1339         D3DPSREGISTER_LightDir = 22, // unused
1340         D3DPSREGISTER_LightPosition = 23,
1341         D3DPSREGISTER_OffsetMapping_ScaleSteps = 24,
1342         D3DPSREGISTER_PixelSize = 25,
1343         D3DPSREGISTER_ReflectColor = 26,
1344         D3DPSREGISTER_ReflectFactor = 27,
1345         D3DPSREGISTER_ReflectOffset = 28,
1346         D3DPSREGISTER_RefractColor = 29,
1347         D3DPSREGISTER_Saturation = 30,
1348         D3DPSREGISTER_ScreenCenterRefractReflect = 31,
1349         D3DPSREGISTER_ScreenScaleRefractReflect = 32,
1350         D3DPSREGISTER_ScreenToDepth = 33,
1351         D3DPSREGISTER_ShadowMap_Parameters = 34,
1352         D3DPSREGISTER_ShadowMap_TextureScale = 35,
1353         D3DPSREGISTER_SpecularPower = 36,
1354         D3DPSREGISTER_UserVec1 = 37,
1355         D3DPSREGISTER_UserVec2 = 38,
1356         D3DPSREGISTER_UserVec3 = 39,
1357         D3DPSREGISTER_UserVec4 = 40,
1358         D3DPSREGISTER_ViewTintColor = 41,
1359         D3DPSREGISTER_PixelToScreenTexCoord = 42,
1360         D3DPSREGISTER_BloomColorSubtract = 43,
1361         D3DPSREGISTER_ViewToLight = 44, // float4x4
1362         D3DPSREGISTER_ModelToReflectCube = 48, // float4x4
1363         D3DPSREGISTER_NormalmapScrollBlend = 52,
1364         D3DPSREGISTER_OffsetMapping_LodDistance = 53,
1365         D3DPSREGISTER_OffsetMapping_Bias = 54,
1366         // next at 54
1367 }
1368 D3DPSREGISTER_t;
1369
1370 /// information about each possible shader permutation
1371 r_hlsl_permutation_t *r_hlsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
1372 /// currently selected permutation
1373 r_hlsl_permutation_t *r_hlsl_permutation;
1374 /// storage for permutations linked in the hash table
1375 memexpandablearray_t r_hlsl_permutationarray;
1376
1377 static r_hlsl_permutation_t *R_HLSL_FindPermutation(unsigned int mode, unsigned int permutation)
1378 {
1379         //unsigned int hashdepth = 0;
1380         unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
1381         r_hlsl_permutation_t *p;
1382         for (p = r_hlsl_permutationhash[mode][hashindex];p;p = p->hashnext)
1383         {
1384                 if (p->mode == mode && p->permutation == permutation)
1385                 {
1386                         //if (hashdepth > 10)
1387                         //      Con_Printf("R_HLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
1388                         return p;
1389                 }
1390                 //hashdepth++;
1391         }
1392         p = (r_hlsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_hlsl_permutationarray);
1393         p->mode = mode;
1394         p->permutation = permutation;
1395         p->hashnext = r_hlsl_permutationhash[mode][hashindex];
1396         r_hlsl_permutationhash[mode][hashindex] = p;
1397         //if (hashdepth > 10)
1398         //      Con_Printf("R_HLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
1399         return p;
1400 }
1401
1402 static char *R_HLSL_GetText(const char *filename, qboolean printfromdisknotice)
1403 {
1404         char *shaderstring;
1405         if (!filename || !filename[0])
1406                 return NULL;
1407         if (!strcmp(filename, "hlsl/default.hlsl"))
1408         {
1409                 if (!hlslshaderstring)
1410                 {
1411                         hlslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
1412                         if (hlslshaderstring)
1413                                 Con_DPrintf("Loading shaders from file %s...\n", filename);
1414                         else
1415                                 hlslshaderstring = (char *)builtinhlslshaderstring;
1416                 }
1417                 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(hlslshaderstring) + 1);
1418                 memcpy(shaderstring, hlslshaderstring, strlen(hlslshaderstring) + 1);
1419                 return shaderstring;
1420         }
1421         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
1422         if (shaderstring)
1423         {
1424                 if (printfromdisknotice)
1425                         Con_DPrintf("from disk %s... ", filename);
1426                 return shaderstring;
1427         }
1428         return shaderstring;
1429 }
1430
1431 #include <d3dx9.h>
1432 //#include <d3dx9shader.h>
1433 //#include <d3dx9mesh.h>
1434
1435 static void R_HLSL_CacheShader(r_hlsl_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
1436 {
1437         DWORD *vsbin = NULL;
1438         DWORD *psbin = NULL;
1439         fs_offset_t vsbinsize;
1440         fs_offset_t psbinsize;
1441 //      IDirect3DVertexShader9 *vs = NULL;
1442 //      IDirect3DPixelShader9 *ps = NULL;
1443         ID3DXBuffer *vslog = NULL;
1444         ID3DXBuffer *vsbuffer = NULL;
1445         ID3DXConstantTable *vsconstanttable = NULL;
1446         ID3DXBuffer *pslog = NULL;
1447         ID3DXBuffer *psbuffer = NULL;
1448         ID3DXConstantTable *psconstanttable = NULL;
1449         int vsresult = 0;
1450         int psresult = 0;
1451         char temp[MAX_INPUTLINE];
1452         const char *vsversion = "vs_3_0", *psversion = "ps_3_0";
1453         char vabuf[1024];
1454         qboolean debugshader = gl_paranoid.integer != 0;
1455         if (p->permutation & SHADERPERMUTATION_OFFSETMAPPING) {vsversion = "vs_3_0";psversion = "ps_3_0";}
1456         if (p->permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) {vsversion = "vs_3_0";psversion = "ps_3_0";}
1457         if (!debugshader)
1458         {
1459                 vsbin = (DWORD *)FS_LoadFile(va(vabuf, sizeof(vabuf), "%s.vsbin", cachename), r_main_mempool, true, &vsbinsize);
1460                 psbin = (DWORD *)FS_LoadFile(va(vabuf, sizeof(vabuf), "%s.psbin", cachename), r_main_mempool, true, &psbinsize);
1461         }
1462         if ((!vsbin && vertstring) || (!psbin && fragstring))
1463         {
1464                 const char* dllnames_d3dx9 [] =
1465                 {
1466                         "d3dx9_43.dll",
1467                         "d3dx9_42.dll",
1468                         "d3dx9_41.dll",
1469                         "d3dx9_40.dll",
1470                         "d3dx9_39.dll",
1471                         "d3dx9_38.dll",
1472                         "d3dx9_37.dll",
1473                         "d3dx9_36.dll",
1474                         "d3dx9_35.dll",
1475                         "d3dx9_34.dll",
1476                         "d3dx9_33.dll",
1477                         "d3dx9_32.dll",
1478                         "d3dx9_31.dll",
1479                         "d3dx9_30.dll",
1480                         "d3dx9_29.dll",
1481                         "d3dx9_28.dll",
1482                         "d3dx9_27.dll",
1483                         "d3dx9_26.dll",
1484                         "d3dx9_25.dll",
1485                         "d3dx9_24.dll",
1486                         NULL
1487                 };
1488                 dllhandle_t d3dx9_dll = NULL;
1489                 HRESULT (WINAPI *qD3DXCompileShaderFromFileA)(LPCSTR pSrcFile, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPCSTR pFunctionName, LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs, LPD3DXCONSTANTTABLE* ppConstantTable);
1490                 HRESULT (WINAPI *qD3DXPreprocessShader)(LPCSTR pSrcData, UINT SrcDataSize, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPD3DXBUFFER* ppShaderText, LPD3DXBUFFER* ppErrorMsgs);
1491                 HRESULT (WINAPI *qD3DXCompileShader)(LPCSTR pSrcData, UINT SrcDataLen, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPCSTR pFunctionName, LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs, LPD3DXCONSTANTTABLE* ppConstantTable);
1492                 dllfunction_t d3dx9_dllfuncs[] =
1493                 {
1494                         {"D3DXCompileShaderFromFileA",  (void **) &qD3DXCompileShaderFromFileA},
1495                         {"D3DXPreprocessShader",                (void **) &qD3DXPreprocessShader},
1496                         {"D3DXCompileShader",                   (void **) &qD3DXCompileShader},
1497                         {NULL, NULL}
1498                 };
1499                 if (Sys_LoadLibrary(dllnames_d3dx9, &d3dx9_dll, d3dx9_dllfuncs))
1500                 {
1501                         DWORD shaderflags = 0;
1502                         if (debugshader)
1503                                 shaderflags = D3DXSHADER_DEBUG | D3DXSHADER_SKIPOPTIMIZATION;
1504                         vsbin = (DWORD *)Mem_Realloc(tempmempool, vsbin, 0);
1505                         psbin = (DWORD *)Mem_Realloc(tempmempool, psbin, 0);
1506                         if (vertstring && vertstring[0])
1507                         {
1508                                 if (debugshader)
1509                                 {
1510 //                                      vsresult = qD3DXPreprocessShader(vertstring, strlen(vertstring), NULL, NULL, &vsbuffer, &vslog);
1511 //                                      FS_WriteFile(va(vabuf, sizeof(vabuf), "%s_vs.fx", cachename), vsbuffer->GetBufferPointer(), vsbuffer->GetBufferSize());
1512                                         FS_WriteFile(va(vabuf, sizeof(vabuf), "%s_vs.fx", cachename), vertstring, strlen(vertstring));
1513                                         vsresult = qD3DXCompileShaderFromFileA(va(vabuf, sizeof(vabuf), "%s/%s_vs.fx", fs_gamedir, cachename), NULL, NULL, "main", vsversion, shaderflags, &vsbuffer, &vslog, &vsconstanttable);
1514                                 }
1515                                 else
1516                                         vsresult = qD3DXCompileShader(vertstring, strlen(vertstring), NULL, NULL, "main", vsversion, shaderflags, &vsbuffer, &vslog, &vsconstanttable);
1517                                 if (vsbuffer)
1518                                 {
1519                                         vsbinsize = vsbuffer->GetBufferSize();
1520                                         vsbin = (DWORD *)Mem_Alloc(tempmempool, vsbinsize);
1521                                         memcpy(vsbin, vsbuffer->GetBufferPointer(), vsbinsize);
1522                                         vsbuffer->Release();
1523                                 }
1524                                 if (vslog)
1525                                 {
1526                                         strlcpy(temp, (const char *)vslog->GetBufferPointer(), min(sizeof(temp), vslog->GetBufferSize()));
1527                                         Con_DPrintf("HLSL vertex shader compile output for %s follows:\n%s\n", cachename, temp);
1528                                         vslog->Release();
1529                                 }
1530                         }
1531                         if (fragstring && fragstring[0])
1532                         {
1533                                 if (debugshader)
1534                                 {
1535 //                                      psresult = qD3DXPreprocessShader(fragstring, strlen(fragstring), NULL, NULL, &psbuffer, &pslog);
1536 //                                      FS_WriteFile(va(vabuf, sizeof(vabuf), "%s_ps.fx", cachename), psbuffer->GetBufferPointer(), psbuffer->GetBufferSize());
1537                                         FS_WriteFile(va(vabuf, sizeof(vabuf), "%s_ps.fx", cachename), fragstring, strlen(fragstring));
1538                                         psresult = qD3DXCompileShaderFromFileA(va(vabuf, sizeof(vabuf), "%s/%s_ps.fx", fs_gamedir, cachename), NULL, NULL, "main", psversion, shaderflags, &psbuffer, &pslog, &psconstanttable);
1539                                 }
1540                                 else
1541                                         psresult = qD3DXCompileShader(fragstring, strlen(fragstring), NULL, NULL, "main", psversion, shaderflags, &psbuffer, &pslog, &psconstanttable);
1542                                 if (psbuffer)
1543                                 {
1544                                         psbinsize = psbuffer->GetBufferSize();
1545                                         psbin = (DWORD *)Mem_Alloc(tempmempool, psbinsize);
1546                                         memcpy(psbin, psbuffer->GetBufferPointer(), psbinsize);
1547                                         psbuffer->Release();
1548                                 }
1549                                 if (pslog)
1550                                 {
1551                                         strlcpy(temp, (const char *)pslog->GetBufferPointer(), min(sizeof(temp), pslog->GetBufferSize()));
1552                                         Con_DPrintf("HLSL pixel shader compile output for %s follows:\n%s\n", cachename, temp);
1553                                         pslog->Release();
1554                                 }
1555                         }
1556                         Sys_UnloadLibrary(&d3dx9_dll);
1557                 }
1558                 else
1559                         Con_DPrintf("Unable to compile shader - D3DXCompileShader function not found\n");
1560         }
1561         if (vsbin && psbin)
1562         {
1563                 vsresult = IDirect3DDevice9_CreateVertexShader(vid_d3d9dev, vsbin, &p->vertexshader);
1564                 if (FAILED(vsresult))
1565                         Con_DPrintf("HLSL CreateVertexShader failed for %s (hresult = %8x)\n", cachename, vsresult);
1566                 psresult = IDirect3DDevice9_CreatePixelShader(vid_d3d9dev, psbin, &p->pixelshader);
1567                 if (FAILED(psresult))
1568                         Con_DPrintf("HLSL CreatePixelShader failed for %s (hresult = %8x)\n", cachename, psresult);
1569         }
1570         // free the shader data
1571         vsbin = (DWORD *)Mem_Realloc(tempmempool, vsbin, 0);
1572         psbin = (DWORD *)Mem_Realloc(tempmempool, psbin, 0);
1573 }
1574
1575 static void R_HLSL_CompilePermutation(r_hlsl_permutation_t *p, unsigned int mode, unsigned int permutation)
1576 {
1577         int i;
1578         shadermodeinfo_t *modeinfo = hlslshadermodeinfo + mode;
1579         int vertstring_length = 0;
1580         int geomstring_length = 0;
1581         int fragstring_length = 0;
1582         char *t;
1583         char *vertexstring, *geometrystring, *fragmentstring;
1584         char *vertstring, *geomstring, *fragstring;
1585         char permutationname[256];
1586         char cachename[256];
1587         int vertstrings_count = 0;
1588         int geomstrings_count = 0;
1589         int fragstrings_count = 0;
1590         const char *vertstrings_list[32+5+SHADERSTATICPARMS_COUNT+1];
1591         const char *geomstrings_list[32+5+SHADERSTATICPARMS_COUNT+1];
1592         const char *fragstrings_list[32+5+SHADERSTATICPARMS_COUNT+1];
1593
1594         if (p->compiled)
1595                 return;
1596         p->compiled = true;
1597         p->vertexshader = NULL;
1598         p->pixelshader = NULL;
1599
1600         permutationname[0] = 0;
1601         cachename[0] = 0;
1602         vertexstring   = R_HLSL_GetText(modeinfo->vertexfilename, true);
1603         geometrystring = R_HLSL_GetText(modeinfo->geometryfilename, false);
1604         fragmentstring = R_HLSL_GetText(modeinfo->fragmentfilename, false);
1605
1606         strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
1607         strlcat(cachename, "hlsl/", sizeof(cachename));
1608
1609         // define HLSL so that the shader can tell apart the HLSL compiler and the Cg compiler
1610         vertstrings_count = 0;
1611         geomstrings_count = 0;
1612         fragstrings_count = 0;
1613         vertstrings_list[vertstrings_count++] = "#define HLSL\n";
1614         geomstrings_list[geomstrings_count++] = "#define HLSL\n";
1615         fragstrings_list[fragstrings_count++] = "#define HLSL\n";
1616
1617         // the first pretext is which type of shader to compile as
1618         // (later these will all be bound together as a program object)
1619         vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
1620         geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
1621         fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
1622
1623         // the second pretext is the mode (for example a light source)
1624         vertstrings_list[vertstrings_count++] = modeinfo->pretext;
1625         geomstrings_list[geomstrings_count++] = modeinfo->pretext;
1626         fragstrings_list[fragstrings_count++] = modeinfo->pretext;
1627         strlcat(permutationname, modeinfo->name, sizeof(permutationname));
1628         strlcat(cachename, modeinfo->name, sizeof(cachename));
1629
1630         // now add all the permutation pretexts
1631         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1632         {
1633                 if (permutation & (1<<i))
1634                 {
1635                         vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
1636                         geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
1637                         fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
1638                         strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
1639                         strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
1640                 }
1641                 else
1642                 {
1643                         // keep line numbers correct
1644                         vertstrings_list[vertstrings_count++] = "\n";
1645                         geomstrings_list[geomstrings_count++] = "\n";
1646                         fragstrings_list[fragstrings_count++] = "\n";
1647                 }
1648         }
1649
1650         // add static parms
1651         R_CompileShader_AddStaticParms(mode, permutation);
1652         memcpy(vertstrings_list + vertstrings_count, shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
1653         vertstrings_count += shaderstaticparms_count;
1654         memcpy(geomstrings_list + geomstrings_count, shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
1655         geomstrings_count += shaderstaticparms_count;
1656         memcpy(fragstrings_list + fragstrings_count, shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
1657         fragstrings_count += shaderstaticparms_count;
1658
1659         // replace spaces in the cachename with _ characters
1660         for (i = 0;cachename[i];i++)
1661                 if (cachename[i] == ' ')
1662                         cachename[i] = '_';
1663
1664         // now append the shader text itself
1665         vertstrings_list[vertstrings_count++] = vertexstring;
1666         geomstrings_list[geomstrings_count++] = geometrystring;
1667         fragstrings_list[fragstrings_count++] = fragmentstring;
1668
1669         // if any sources were NULL, clear the respective list
1670         if (!vertexstring)
1671                 vertstrings_count = 0;
1672         if (!geometrystring)
1673                 geomstrings_count = 0;
1674         if (!fragmentstring)
1675                 fragstrings_count = 0;
1676
1677         vertstring_length = 0;
1678         for (i = 0;i < vertstrings_count;i++)
1679                 vertstring_length += strlen(vertstrings_list[i]);
1680         vertstring = t = (char *)Mem_Alloc(tempmempool, vertstring_length + 1);
1681         for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
1682                 memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
1683
1684         geomstring_length = 0;
1685         for (i = 0;i < geomstrings_count;i++)
1686                 geomstring_length += strlen(geomstrings_list[i]);
1687         geomstring = t = (char *)Mem_Alloc(tempmempool, geomstring_length + 1);
1688         for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
1689                 memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
1690
1691         fragstring_length = 0;
1692         for (i = 0;i < fragstrings_count;i++)
1693                 fragstring_length += strlen(fragstrings_list[i]);
1694         fragstring = t = (char *)Mem_Alloc(tempmempool, fragstring_length + 1);
1695         for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
1696                 memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
1697
1698         // try to load the cached shader, or generate one
1699         R_HLSL_CacheShader(p, cachename, vertstring, fragstring);
1700
1701         if ((p->vertexshader || !vertstring[0]) && (p->pixelshader || !fragstring[0]))
1702                 Con_DPrintf("^5HLSL shader %s compiled.\n", permutationname);
1703         else
1704                 Con_Printf("^1HLSL shader %s failed!  some features may not work properly.\n", permutationname);
1705
1706         // free the strings
1707         if (vertstring)
1708                 Mem_Free(vertstring);
1709         if (geomstring)
1710                 Mem_Free(geomstring);
1711         if (fragstring)
1712                 Mem_Free(fragstring);
1713         if (vertexstring)
1714                 Mem_Free(vertexstring);
1715         if (geometrystring)
1716                 Mem_Free(geometrystring);
1717         if (fragmentstring)
1718                 Mem_Free(fragmentstring);
1719 }
1720
1721 static inline void hlslVSSetParameter16f(D3DVSREGISTER_t r, const float *a) {IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, a, 4);}
1722 static inline void hlslVSSetParameter4fv(D3DVSREGISTER_t r, const float *a) {IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, a, 1);}
1723 static inline void hlslVSSetParameter4f(D3DVSREGISTER_t r, float x, float y, float z, float w) {float temp[4];Vector4Set(temp, x, y, z, w);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
1724 static inline void hlslVSSetParameter3f(D3DVSREGISTER_t r, float x, float y, float z) {float temp[4];Vector4Set(temp, x, y, z, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
1725 static inline void hlslVSSetParameter2f(D3DVSREGISTER_t r, float x, float y) {float temp[4];Vector4Set(temp, x, y, 0, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
1726 static inline void hlslVSSetParameter1f(D3DVSREGISTER_t r, float x) {float temp[4];Vector4Set(temp, x, 0, 0, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
1727
1728 static inline void hlslPSSetParameter16f(D3DPSREGISTER_t r, const float *a) {IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, a, 4);}
1729 static inline void hlslPSSetParameter4fv(D3DPSREGISTER_t r, const float *a) {IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, a, 1);}
1730 static inline void hlslPSSetParameter4f(D3DPSREGISTER_t r, float x, float y, float z, float w) {float temp[4];Vector4Set(temp, x, y, z, w);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
1731 static inline void hlslPSSetParameter3f(D3DPSREGISTER_t r, float x, float y, float z) {float temp[4];Vector4Set(temp, x, y, z, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
1732 static inline void hlslPSSetParameter2f(D3DPSREGISTER_t r, float x, float y) {float temp[4];Vector4Set(temp, x, y, 0, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
1733 static inline void hlslPSSetParameter1f(D3DPSREGISTER_t r, float x) {float temp[4];Vector4Set(temp, x, 0, 0, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
1734
1735 void R_SetupShader_SetPermutationHLSL(unsigned int mode, unsigned int permutation)
1736 {
1737         r_hlsl_permutation_t *perm = R_HLSL_FindPermutation(mode, permutation);
1738         if (r_hlsl_permutation != perm)
1739         {
1740                 r_hlsl_permutation = perm;
1741                 if (!r_hlsl_permutation->vertexshader && !r_hlsl_permutation->pixelshader)
1742                 {
1743                         if (!r_hlsl_permutation->compiled)
1744                                 R_HLSL_CompilePermutation(perm, mode, permutation);
1745                         if (!r_hlsl_permutation->vertexshader && !r_hlsl_permutation->pixelshader)
1746                         {
1747                                 // remove features until we find a valid permutation
1748                                 int i;
1749                                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1750                                 {
1751                                         // reduce i more quickly whenever it would not remove any bits
1752                                         int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
1753                                         if (!(permutation & j))
1754                                                 continue;
1755                                         permutation -= j;
1756                                         r_hlsl_permutation = R_HLSL_FindPermutation(mode, permutation);
1757                                         if (!r_hlsl_permutation->compiled)
1758                                                 R_HLSL_CompilePermutation(perm, mode, permutation);
1759                                         if (r_hlsl_permutation->vertexshader || r_hlsl_permutation->pixelshader)
1760                                                 break;
1761                                 }
1762                                 if (i >= SHADERPERMUTATION_COUNT)
1763                                 {
1764                                         //Con_Printf("Could not find a working HLSL shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
1765                                         r_hlsl_permutation = R_HLSL_FindPermutation(mode, permutation);
1766                                         return; // no bit left to clear, entire mode is broken
1767                                 }
1768                         }
1769                 }
1770                 IDirect3DDevice9_SetVertexShader(vid_d3d9dev, r_hlsl_permutation->vertexshader);
1771                 IDirect3DDevice9_SetPixelShader(vid_d3d9dev, r_hlsl_permutation->pixelshader);
1772         }
1773         hlslVSSetParameter16f(D3DVSREGISTER_ModelViewProjectionMatrix, gl_modelviewprojection16f);
1774         hlslVSSetParameter16f(D3DVSREGISTER_ModelViewMatrix, gl_modelview16f);
1775         hlslPSSetParameter1f(D3DPSREGISTER_ClientTime, cl.time);
1776 }
1777 #endif
1778
1779 static void R_SetupShader_SetPermutationSoft(unsigned int mode, unsigned int permutation)
1780 {
1781         DPSOFTRAST_SetShader(mode, permutation, r_shadow_glossexact.integer);
1782         DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1, 1, false, gl_modelviewprojection16f);
1783         DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelViewMatrixM1, 1, false, gl_modelview16f);
1784         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_ClientTime, cl.time);
1785 }
1786
1787 static void R_GLSL_Restart_f(void)
1788 {
1789         unsigned int i, limit;
1790         if (glslshaderstring && glslshaderstring != builtinshaderstring)
1791                 Mem_Free(glslshaderstring);
1792         glslshaderstring = NULL;
1793         if (hlslshaderstring && hlslshaderstring != builtinhlslshaderstring)
1794                 Mem_Free(hlslshaderstring);
1795         hlslshaderstring = NULL;
1796         switch(vid.renderpath)
1797         {
1798         case RENDERPATH_D3D9:
1799 #ifdef SUPPORTD3D
1800                 {
1801                         r_hlsl_permutation_t *p;
1802                         r_hlsl_permutation = NULL;
1803                         limit = Mem_ExpandableArray_IndexRange(&r_hlsl_permutationarray);
1804                         for (i = 0;i < limit;i++)
1805                         {
1806                                 if ((p = (r_hlsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_hlsl_permutationarray, i)))
1807                                 {
1808                                         if (p->vertexshader)
1809                                                 IDirect3DVertexShader9_Release(p->vertexshader);
1810                                         if (p->pixelshader)
1811                                                 IDirect3DPixelShader9_Release(p->pixelshader);
1812                                         Mem_ExpandableArray_FreeRecord(&r_hlsl_permutationarray, (void*)p);
1813                                 }
1814                         }
1815                         memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
1816                 }
1817 #endif
1818                 break;
1819         case RENDERPATH_D3D10:
1820                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1821                 break;
1822         case RENDERPATH_D3D11:
1823                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1824                 break;
1825         case RENDERPATH_GL20:
1826         case RENDERPATH_GLES2:
1827                 {
1828                         r_glsl_permutation_t *p;
1829                         r_glsl_permutation = NULL;
1830                         limit = Mem_ExpandableArray_IndexRange(&r_glsl_permutationarray);
1831                         for (i = 0;i < limit;i++)
1832                         {
1833                                 if ((p = (r_glsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_glsl_permutationarray, i)))
1834                                 {
1835                                         GL_Backend_FreeProgram(p->program);
1836                                         Mem_ExpandableArray_FreeRecord(&r_glsl_permutationarray, (void*)p);
1837                                 }
1838                         }
1839                         memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
1840                 }
1841                 break;
1842         case RENDERPATH_GL11:
1843         case RENDERPATH_GL13:
1844         case RENDERPATH_GLES1:
1845                 break;
1846         case RENDERPATH_SOFT:
1847                 break;
1848         }
1849 }
1850
1851 static void R_GLSL_DumpShader_f(void)
1852 {
1853         int i;
1854         qfile_t *file;
1855
1856         file = FS_OpenRealFile("glsl/default.glsl", "w", false);
1857         if (file)
1858         {
1859                 FS_Print(file, "/* The engine may define the following macros:\n");
1860                 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
1861                 for (i = 0;i < SHADERMODE_COUNT;i++)
1862                         FS_Print(file, glslshadermodeinfo[i].pretext);
1863                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1864                         FS_Print(file, shaderpermutationinfo[i].pretext);
1865                 FS_Print(file, "*/\n");
1866                 FS_Print(file, builtinshaderstring);
1867                 FS_Close(file);
1868                 Con_Printf("glsl/default.glsl written\n");
1869         }
1870         else
1871                 Con_Printf("failed to write to glsl/default.glsl\n");
1872
1873         file = FS_OpenRealFile("hlsl/default.hlsl", "w", false);
1874         if (file)
1875         {
1876                 FS_Print(file, "/* The engine may define the following macros:\n");
1877                 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
1878                 for (i = 0;i < SHADERMODE_COUNT;i++)
1879                         FS_Print(file, hlslshadermodeinfo[i].pretext);
1880                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1881                         FS_Print(file, shaderpermutationinfo[i].pretext);
1882                 FS_Print(file, "*/\n");
1883                 FS_Print(file, builtinhlslshaderstring);
1884                 FS_Close(file);
1885                 Con_Printf("hlsl/default.hlsl written\n");
1886         }
1887         else
1888                 Con_Printf("failed to write to hlsl/default.hlsl\n");
1889 }
1890
1891 void R_SetupShader_Generic(rtexture_t *first, rtexture_t *second, int texturemode, int rgbscale, qboolean usegamma, qboolean notrippy, qboolean suppresstexalpha)
1892 {
1893         unsigned int permutation = 0;
1894         if (r_trippy.integer && !notrippy)
1895                 permutation |= SHADERPERMUTATION_TRIPPY;
1896         permutation |= SHADERPERMUTATION_VIEWTINT;
1897         if (first)
1898                 permutation |= SHADERPERMUTATION_DIFFUSE;
1899         if (second)
1900                 permutation |= SHADERPERMUTATION_SPECULAR;
1901         if (texturemode == GL_MODULATE)
1902                 permutation |= SHADERPERMUTATION_COLORMAPPING;
1903         else if (texturemode == GL_ADD)
1904                 permutation |= SHADERPERMUTATION_GLOW;
1905         else if (texturemode == GL_DECAL)
1906                 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
1907         if (usegamma && v_glslgamma.integer && v_glslgamma_2d.integer && !vid.sRGB2D && r_texture_gammaramps && !vid_gammatables_trivial)
1908                 permutation |= SHADERPERMUTATION_GAMMARAMPS;
1909         if (suppresstexalpha)
1910                 permutation |= SHADERPERMUTATION_REFLECTCUBE;
1911         if (!second)
1912                 texturemode = GL_MODULATE;
1913         if (vid.allowalphatocoverage)
1914                 GL_AlphaToCoverage(false);
1915         switch (vid.renderpath)
1916         {
1917         case RENDERPATH_D3D9:
1918 #ifdef SUPPORTD3D
1919                 R_SetupShader_SetPermutationHLSL(SHADERMODE_GENERIC, permutation);
1920                 R_Mesh_TexBind(GL20TU_FIRST , first );
1921                 R_Mesh_TexBind(GL20TU_SECOND, second);
1922                 if (permutation & SHADERPERMUTATION_GAMMARAMPS)
1923                         R_Mesh_TexBind(r_glsl_permutation->tex_Texture_GammaRamps, r_texture_gammaramps);
1924 #endif
1925                 break;
1926         case RENDERPATH_D3D10:
1927                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1928                 break;
1929         case RENDERPATH_D3D11:
1930                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1931                 break;
1932         case RENDERPATH_GL20:
1933         case RENDERPATH_GLES2:
1934                 R_SetupShader_SetPermutationGLSL(SHADERMODE_GENERIC, permutation);
1935                 R_Mesh_TexBind(r_glsl_permutation->tex_Texture_First , first );
1936                 R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Second, second);
1937                 if (r_glsl_permutation->tex_Texture_GammaRamps >= 0)
1938                         R_Mesh_TexBind(r_glsl_permutation->tex_Texture_GammaRamps, r_texture_gammaramps);
1939                 break;
1940         case RENDERPATH_GL13:
1941         case RENDERPATH_GLES1:
1942                 R_Mesh_TexBind(0, first );
1943                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
1944                 R_Mesh_TexBind(1, second);
1945                 if (second)
1946                         R_Mesh_TexCombine(1, texturemode, texturemode, rgbscale, 1);
1947                 break;
1948         case RENDERPATH_GL11:
1949                 R_Mesh_TexBind(0, first );
1950                 break;
1951         case RENDERPATH_SOFT:
1952                 R_SetupShader_SetPermutationSoft(SHADERMODE_GENERIC, permutation);
1953                 R_Mesh_TexBind(GL20TU_FIRST , first );
1954                 R_Mesh_TexBind(GL20TU_SECOND, second);
1955                 break;
1956         }
1957 }
1958
1959 void R_SetupShader_Generic_NoTexture(qboolean usegamma, qboolean notrippy)
1960 {
1961         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1, usegamma, notrippy, false);
1962 }
1963
1964 void R_SetupShader_DepthOrShadow(qboolean notrippy, qboolean depthrgb)
1965 {
1966         unsigned int permutation = 0;
1967         if (r_trippy.integer && !notrippy)
1968                 permutation |= SHADERPERMUTATION_TRIPPY;
1969         if (depthrgb)
1970                 permutation |= SHADERPERMUTATION_DEPTHRGB;
1971         if (vid.allowalphatocoverage)
1972                 GL_AlphaToCoverage(false);
1973         switch (vid.renderpath)
1974         {
1975         case RENDERPATH_D3D9:
1976 #ifdef SUPPORTD3D
1977                 R_SetupShader_SetPermutationHLSL(SHADERMODE_DEPTH_OR_SHADOW, permutation);
1978 #endif
1979                 break;
1980         case RENDERPATH_D3D10:
1981                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1982                 break;
1983         case RENDERPATH_D3D11:
1984                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
1985                 break;
1986         case RENDERPATH_GL20:
1987         case RENDERPATH_GLES2:
1988                 R_SetupShader_SetPermutationGLSL(SHADERMODE_DEPTH_OR_SHADOW, permutation);
1989                 break;
1990         case RENDERPATH_GL13:
1991         case RENDERPATH_GLES1:
1992                 R_Mesh_TexBind(0, 0);
1993                 R_Mesh_TexBind(1, 0);
1994                 break;
1995         case RENDERPATH_GL11:
1996                 R_Mesh_TexBind(0, 0);
1997                 break;
1998         case RENDERPATH_SOFT:
1999                 R_SetupShader_SetPermutationSoft(SHADERMODE_DEPTH_OR_SHADOW, permutation);
2000                 break;
2001         }
2002 }
2003
2004 void R_SetupShader_ShowDepth(qboolean notrippy)
2005 {
2006         int permutation = 0;
2007         if (r_trippy.integer && !notrippy)
2008                 permutation |= SHADERPERMUTATION_TRIPPY;
2009         if (vid.allowalphatocoverage)
2010                 GL_AlphaToCoverage(false);
2011         switch (vid.renderpath)
2012         {
2013         case RENDERPATH_D3D9:
2014 #ifdef SUPPORTHLSL
2015                 R_SetupShader_SetPermutationHLSL(SHADERMODE_SHOWDEPTH, permutation);
2016 #endif
2017                 break;
2018         case RENDERPATH_D3D10:
2019                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2020                 break;
2021         case RENDERPATH_D3D11:
2022                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2023                 break;
2024         case RENDERPATH_GL20:
2025         case RENDERPATH_GLES2:
2026                 R_SetupShader_SetPermutationGLSL(SHADERMODE_SHOWDEPTH, permutation);
2027                 break;
2028         case RENDERPATH_GL13:
2029         case RENDERPATH_GLES1:
2030                 break;
2031         case RENDERPATH_GL11:
2032                 break;
2033         case RENDERPATH_SOFT:
2034                 R_SetupShader_SetPermutationSoft(SHADERMODE_SHOWDEPTH, permutation);
2035                 break;
2036         }
2037 }
2038
2039 extern qboolean r_shadow_usingdeferredprepass;
2040 extern rtexture_t *r_shadow_attenuationgradienttexture;
2041 extern rtexture_t *r_shadow_attenuation2dtexture;
2042 extern rtexture_t *r_shadow_attenuation3dtexture;
2043 extern qboolean r_shadow_usingshadowmap2d;
2044 extern qboolean r_shadow_usingshadowmaportho;
2045 extern float r_shadow_shadowmap_texturescale[2];
2046 extern float r_shadow_shadowmap_parameters[4];
2047 extern qboolean r_shadow_shadowmapvsdct;
2048 extern qboolean r_shadow_shadowmapsampler;
2049 extern int r_shadow_shadowmappcf;
2050 extern rtexture_t *r_shadow_shadowmap2ddepthbuffer;
2051 extern rtexture_t *r_shadow_shadowmap2ddepthtexture;
2052 extern rtexture_t *r_shadow_shadowmapvsdcttexture;
2053 extern matrix4x4_t r_shadow_shadowmapmatrix;
2054 extern int r_shadow_shadowmaplod; // changes for each light based on distance
2055 extern int r_shadow_prepass_width;
2056 extern int r_shadow_prepass_height;
2057 extern rtexture_t *r_shadow_prepassgeometrydepthbuffer;
2058 extern rtexture_t *r_shadow_prepassgeometrynormalmaptexture;
2059 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
2060 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
2061
2062 #define BLENDFUNC_ALLOWS_COLORMOD      1
2063 #define BLENDFUNC_ALLOWS_FOG           2
2064 #define BLENDFUNC_ALLOWS_FOG_HACK0     4
2065 #define BLENDFUNC_ALLOWS_FOG_HACKALPHA 8
2066 #define BLENDFUNC_ALLOWS_ANYFOG        (BLENDFUNC_ALLOWS_FOG | BLENDFUNC_ALLOWS_FOG_HACK0 | BLENDFUNC_ALLOWS_FOG_HACKALPHA)
2067 static int R_BlendFuncFlags(int src, int dst)
2068 {
2069         int r = 0;
2070
2071         // a blendfunc allows colormod if:
2072         // a) it can never keep the destination pixel invariant, or
2073         // b) it can keep the destination pixel invariant, and still can do so if colormodded
2074         // this is to prevent unintended side effects from colormod
2075
2076         // a blendfunc allows fog if:
2077         // blend(fog(src), fog(dst)) == fog(blend(src, dst))
2078         // this is to prevent unintended side effects from fog
2079
2080         // these checks are the output of fogeval.pl
2081
2082         r |= BLENDFUNC_ALLOWS_COLORMOD;
2083         if(src == GL_DST_ALPHA && dst == GL_ONE) r |= BLENDFUNC_ALLOWS_FOG_HACK0;
2084         if(src == GL_DST_ALPHA && dst == GL_ONE_MINUS_DST_ALPHA) r |= BLENDFUNC_ALLOWS_FOG;
2085         if(src == GL_DST_COLOR && dst == GL_ONE_MINUS_SRC_ALPHA) r &= ~BLENDFUNC_ALLOWS_COLORMOD;
2086         if(src == GL_DST_COLOR && dst == GL_ONE_MINUS_SRC_COLOR) r |= BLENDFUNC_ALLOWS_FOG;
2087         if(src == GL_DST_COLOR && dst == GL_SRC_ALPHA) r &= ~BLENDFUNC_ALLOWS_COLORMOD;
2088         if(src == GL_DST_COLOR && dst == GL_SRC_COLOR) r &= ~BLENDFUNC_ALLOWS_COLORMOD;
2089         if(src == GL_DST_COLOR && dst == GL_ZERO) r &= ~BLENDFUNC_ALLOWS_COLORMOD;
2090         if(src == GL_ONE && dst == GL_ONE) r |= BLENDFUNC_ALLOWS_FOG_HACK0;
2091         if(src == GL_ONE && dst == GL_ONE_MINUS_SRC_ALPHA) r |= BLENDFUNC_ALLOWS_FOG_HACKALPHA;
2092         if(src == GL_ONE && dst == GL_ZERO) r |= BLENDFUNC_ALLOWS_FOG;
2093         if(src == GL_ONE_MINUS_DST_ALPHA && dst == GL_DST_ALPHA) r |= BLENDFUNC_ALLOWS_FOG;
2094         if(src == GL_ONE_MINUS_DST_ALPHA && dst == GL_ONE) r |= BLENDFUNC_ALLOWS_FOG_HACK0;
2095         if(src == GL_ONE_MINUS_DST_COLOR && dst == GL_SRC_COLOR) r |= BLENDFUNC_ALLOWS_FOG;
2096         if(src == GL_ONE_MINUS_SRC_ALPHA && dst == GL_ONE) r |= BLENDFUNC_ALLOWS_FOG_HACK0;
2097         if(src == GL_ONE_MINUS_SRC_ALPHA && dst == GL_SRC_ALPHA) r |= BLENDFUNC_ALLOWS_FOG;
2098         if(src == GL_ONE_MINUS_SRC_ALPHA && dst == GL_SRC_COLOR) r &= ~BLENDFUNC_ALLOWS_COLORMOD;
2099         if(src == GL_ONE_MINUS_SRC_COLOR && dst == GL_SRC_COLOR) r &= ~BLENDFUNC_ALLOWS_COLORMOD;
2100         if(src == GL_SRC_ALPHA && dst == GL_ONE) r |= BLENDFUNC_ALLOWS_FOG_HACK0;
2101         if(src == GL_SRC_ALPHA && dst == GL_ONE_MINUS_SRC_ALPHA) r |= BLENDFUNC_ALLOWS_FOG;
2102         if(src == GL_ZERO && dst == GL_ONE) r |= BLENDFUNC_ALLOWS_FOG;
2103         if(src == GL_ZERO && dst == GL_SRC_COLOR) r &= ~BLENDFUNC_ALLOWS_COLORMOD;
2104
2105         return r;
2106 }
2107
2108 void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale, rsurfacepass_t rsurfacepass, int texturenumsurfaces, const msurface_t **texturesurfacelist, void *surfacewaterplane, qboolean notrippy)
2109 {
2110         // select a permutation of the lighting shader appropriate to this
2111         // combination of texture, entity, light source, and fogging, only use the
2112         // minimum features necessary to avoid wasting rendering time in the
2113         // fragment shader on features that are not being used
2114         unsigned int permutation = 0;
2115         unsigned int mode = 0;
2116         int blendfuncflags;
2117         static float dummy_colormod[3] = {1, 1, 1};
2118         float *colormod = rsurface.colormod;
2119         float m16f[16];
2120         matrix4x4_t tempmatrix;
2121         r_waterstate_waterplane_t *waterplane = (r_waterstate_waterplane_t *)surfacewaterplane;
2122         if (r_trippy.integer && !notrippy)
2123                 permutation |= SHADERPERMUTATION_TRIPPY;
2124         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
2125                 permutation |= SHADERPERMUTATION_ALPHAKILL;
2126         if (rsurface.texture->r_water_waterscroll[0] && rsurface.texture->r_water_waterscroll[1])
2127                 permutation |= SHADERPERMUTATION_NORMALMAPSCROLLBLEND; // todo: make generic
2128         if (rsurfacepass == RSURFPASS_BACKGROUND)
2129         {
2130                 // distorted background
2131                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERSHADER)
2132                 {
2133                         mode = SHADERMODE_WATER;
2134                         if((r_wateralpha.value < 1) && (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERALPHA))
2135                         {
2136                                 // this is the right thing to do for wateralpha
2137                                 GL_BlendFunc(GL_ONE, GL_ZERO);
2138                                 blendfuncflags = R_BlendFuncFlags(GL_ONE, GL_ZERO);
2139                         }
2140                         else
2141                         {
2142                                 // this is the right thing to do for entity alpha
2143                                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2144                                 blendfuncflags = R_BlendFuncFlags(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2145                         }
2146                 }
2147                 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFRACTION)
2148                 {
2149                         mode = SHADERMODE_REFRACTION;
2150                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2151                         blendfuncflags = R_BlendFuncFlags(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2152                 }
2153                 else
2154                 {
2155                         mode = SHADERMODE_GENERIC;
2156                         permutation |= SHADERPERMUTATION_DIFFUSE;
2157                         GL_BlendFunc(GL_ONE, GL_ZERO);
2158                         blendfuncflags = R_BlendFuncFlags(GL_ONE, GL_ZERO);
2159                 }
2160                 if (vid.allowalphatocoverage)
2161                         GL_AlphaToCoverage(false);
2162         }
2163         else if (rsurfacepass == RSURFPASS_DEFERREDGEOMETRY)
2164         {
2165                 if (r_glsl_offsetmapping.integer && ((R_TextureFlags(rsurface.texture->nmaptexture) & TEXF_ALPHA) || rsurface.texture->offsetbias != 0.0f))
2166                 {
2167                         switch(rsurface.texture->offsetmapping)
2168                         {
2169                         case OFFSETMAPPING_LINEAR: permutation |= SHADERPERMUTATION_OFFSETMAPPING;break;
2170                         case OFFSETMAPPING_RELIEF: permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2171                         case OFFSETMAPPING_DEFAULT: permutation |= SHADERPERMUTATION_OFFSETMAPPING;if (r_glsl_offsetmapping_reliefmapping.integer) permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2172                         case OFFSETMAPPING_OFF: break;
2173                         }
2174                 }
2175                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2176                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2177                 // normalmap (deferred prepass), may use alpha test on diffuse
2178                 mode = SHADERMODE_DEFERREDGEOMETRY;
2179                 GL_BlendFunc(GL_ONE, GL_ZERO);
2180                 blendfuncflags = R_BlendFuncFlags(GL_ONE, GL_ZERO);
2181                 if (vid.allowalphatocoverage)
2182                         GL_AlphaToCoverage(false);
2183         }
2184         else if (rsurfacepass == RSURFPASS_RTLIGHT)
2185         {
2186                 if (r_glsl_offsetmapping.integer && ((R_TextureFlags(rsurface.texture->nmaptexture) & TEXF_ALPHA) || rsurface.texture->offsetbias != 0.0f))
2187                 {
2188                         switch(rsurface.texture->offsetmapping)
2189                         {
2190                         case OFFSETMAPPING_LINEAR: permutation |= SHADERPERMUTATION_OFFSETMAPPING;break;
2191                         case OFFSETMAPPING_RELIEF: permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2192                         case OFFSETMAPPING_DEFAULT: permutation |= SHADERPERMUTATION_OFFSETMAPPING;if (r_glsl_offsetmapping_reliefmapping.integer) permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2193                         case OFFSETMAPPING_OFF: break;
2194                         }
2195                 }
2196                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2197                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2198                 // light source
2199                 mode = SHADERMODE_LIGHTSOURCE;
2200                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2201                         permutation |= SHADERPERMUTATION_CUBEFILTER;
2202                 if (diffusescale > 0)
2203                         permutation |= SHADERPERMUTATION_DIFFUSE;
2204                 if (specularscale > 0)
2205                         permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
2206                 if (r_refdef.fogenabled)
2207                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
2208                 if (rsurface.texture->colormapping)
2209                         permutation |= SHADERPERMUTATION_COLORMAPPING;
2210                 if (r_shadow_usingshadowmap2d)
2211                 {
2212                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
2213                         if(r_shadow_shadowmapvsdct)
2214                                 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
2215
2216                         if (r_shadow_shadowmapsampler)
2217                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
2218                         if (r_shadow_shadowmappcf > 1)
2219                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
2220                         else if (r_shadow_shadowmappcf)
2221                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
2222                         if (r_shadow_shadowmap2ddepthbuffer)
2223                                 permutation |= SHADERPERMUTATION_DEPTHRGB;
2224                 }
2225                 if (rsurface.texture->reflectmasktexture)
2226                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
2227                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2228                 blendfuncflags = R_BlendFuncFlags(GL_SRC_ALPHA, GL_ONE);
2229                 if (vid.allowalphatocoverage)
2230                         GL_AlphaToCoverage(false);
2231         }
2232         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
2233         {
2234                 if (r_glsl_offsetmapping.integer && ((R_TextureFlags(rsurface.texture->nmaptexture) & TEXF_ALPHA) || rsurface.texture->offsetbias != 0.0f))
2235                 {
2236                         switch(rsurface.texture->offsetmapping)
2237                         {
2238                         case OFFSETMAPPING_LINEAR: permutation |= SHADERPERMUTATION_OFFSETMAPPING;break;
2239                         case OFFSETMAPPING_RELIEF: permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2240                         case OFFSETMAPPING_DEFAULT: permutation |= SHADERPERMUTATION_OFFSETMAPPING;if (r_glsl_offsetmapping_reliefmapping.integer) permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2241                         case OFFSETMAPPING_OFF: break;
2242                         }
2243                 }
2244                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2245                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2246                 // unshaded geometry (fullbright or ambient model lighting)
2247                 mode = SHADERMODE_FLATCOLOR;
2248                 ambientscale = diffusescale = specularscale = 0;
2249                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
2250                         permutation |= SHADERPERMUTATION_GLOW;
2251                 if (r_refdef.fogenabled)
2252                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
2253                 if (rsurface.texture->colormapping)
2254                         permutation |= SHADERPERMUTATION_COLORMAPPING;
2255                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
2256                 {
2257                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
2258                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
2259
2260                         if (r_shadow_shadowmapsampler)
2261                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
2262                         if (r_shadow_shadowmappcf > 1)
2263                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
2264                         else if (r_shadow_shadowmappcf)
2265                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
2266                         if (r_shadow_shadowmap2ddepthbuffer)
2267                                 permutation |= SHADERPERMUTATION_DEPTHRGB;
2268                 }
2269                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
2270                         permutation |= SHADERPERMUTATION_REFLECTION;
2271                 if (rsurface.texture->reflectmasktexture)
2272                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
2273                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
2274                 blendfuncflags = R_BlendFuncFlags(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
2275                 // when using alphatocoverage, we don't need alphakill
2276                 if (vid.allowalphatocoverage)
2277                 {
2278                         if (r_transparent_alphatocoverage.integer)
2279                         {
2280                                 GL_AlphaToCoverage((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
2281                                 permutation &= ~SHADERPERMUTATION_ALPHAKILL;
2282                         }
2283                         else
2284                                 GL_AlphaToCoverage(false);
2285                 }
2286         }
2287         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT_DIRECTIONAL)
2288         {
2289                 if (r_glsl_offsetmapping.integer && ((R_TextureFlags(rsurface.texture->nmaptexture) & TEXF_ALPHA) || rsurface.texture->offsetbias != 0.0f))
2290                 {
2291                         switch(rsurface.texture->offsetmapping)
2292                         {
2293                         case OFFSETMAPPING_LINEAR: permutation |= SHADERPERMUTATION_OFFSETMAPPING;break;
2294                         case OFFSETMAPPING_RELIEF: permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2295                         case OFFSETMAPPING_DEFAULT: permutation |= SHADERPERMUTATION_OFFSETMAPPING;if (r_glsl_offsetmapping_reliefmapping.integer) permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2296                         case OFFSETMAPPING_OFF: break;
2297                         }
2298                 }
2299                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2300                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2301                 // directional model lighting
2302                 mode = SHADERMODE_LIGHTDIRECTION;
2303                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
2304                         permutation |= SHADERPERMUTATION_GLOW;
2305                 permutation |= SHADERPERMUTATION_DIFFUSE;
2306                 if (specularscale > 0)
2307                         permutation |= SHADERPERMUTATION_SPECULAR;
2308                 if (r_refdef.fogenabled)
2309                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
2310                 if (rsurface.texture->colormapping)
2311                         permutation |= SHADERPERMUTATION_COLORMAPPING;
2312                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
2313                 {
2314                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
2315                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
2316
2317                         if (r_shadow_shadowmapsampler)
2318                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
2319                         if (r_shadow_shadowmappcf > 1)
2320                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
2321                         else if (r_shadow_shadowmappcf)
2322                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
2323                         if (r_shadow_shadowmap2ddepthbuffer)
2324                                 permutation |= SHADERPERMUTATION_DEPTHRGB;
2325                 }
2326                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
2327                         permutation |= SHADERPERMUTATION_REFLECTION;
2328                 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
2329                         permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
2330                 if (rsurface.texture->reflectmasktexture)
2331                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
2332                 if (r_shadow_bouncegridtexture && cl.csqc_vidvars.drawworld)
2333                 {
2334                         permutation |= SHADERPERMUTATION_BOUNCEGRID;
2335                         if (r_shadow_bouncegriddirectional)
2336                                 permutation |= SHADERPERMUTATION_BOUNCEGRIDDIRECTIONAL;
2337                 }
2338                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
2339                 blendfuncflags = R_BlendFuncFlags(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
2340                 // when using alphatocoverage, we don't need alphakill
2341                 if (vid.allowalphatocoverage)
2342                 {
2343                         if (r_transparent_alphatocoverage.integer)
2344                         {
2345                                 GL_AlphaToCoverage((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
2346                                 permutation &= ~SHADERPERMUTATION_ALPHAKILL;
2347                         }
2348                         else
2349                                 GL_AlphaToCoverage(false);
2350                 }
2351         }
2352         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
2353         {
2354                 if (r_glsl_offsetmapping.integer && ((R_TextureFlags(rsurface.texture->nmaptexture) & TEXF_ALPHA) || rsurface.texture->offsetbias != 0.0f))
2355                 {
2356                         switch(rsurface.texture->offsetmapping)
2357                         {
2358                         case OFFSETMAPPING_LINEAR: permutation |= SHADERPERMUTATION_OFFSETMAPPING;break;
2359                         case OFFSETMAPPING_RELIEF: permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2360                         case OFFSETMAPPING_DEFAULT: permutation |= SHADERPERMUTATION_OFFSETMAPPING;if (r_glsl_offsetmapping_reliefmapping.integer) permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2361                         case OFFSETMAPPING_OFF: break;
2362                         }
2363                 }
2364                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2365                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2366                 // ambient model lighting
2367                 mode = SHADERMODE_LIGHTDIRECTION;
2368                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
2369                         permutation |= SHADERPERMUTATION_GLOW;
2370                 if (r_refdef.fogenabled)
2371                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
2372                 if (rsurface.texture->colormapping)
2373                         permutation |= SHADERPERMUTATION_COLORMAPPING;
2374                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
2375                 {
2376                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
2377                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
2378
2379                         if (r_shadow_shadowmapsampler)
2380                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
2381                         if (r_shadow_shadowmappcf > 1)
2382                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
2383                         else if (r_shadow_shadowmappcf)
2384                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
2385                         if (r_shadow_shadowmap2ddepthbuffer)
2386                                 permutation |= SHADERPERMUTATION_DEPTHRGB;
2387                 }
2388                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
2389                         permutation |= SHADERPERMUTATION_REFLECTION;
2390                 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
2391                         permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
2392                 if (rsurface.texture->reflectmasktexture)
2393                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
2394                 if (r_shadow_bouncegridtexture && cl.csqc_vidvars.drawworld)
2395                 {
2396                         permutation |= SHADERPERMUTATION_BOUNCEGRID;
2397                         if (r_shadow_bouncegriddirectional)
2398                                 permutation |= SHADERPERMUTATION_BOUNCEGRIDDIRECTIONAL;
2399                 }
2400                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
2401                 blendfuncflags = R_BlendFuncFlags(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
2402                 // when using alphatocoverage, we don't need alphakill
2403                 if (vid.allowalphatocoverage)
2404                 {
2405                         if (r_transparent_alphatocoverage.integer)
2406                         {
2407                                 GL_AlphaToCoverage((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
2408                                 permutation &= ~SHADERPERMUTATION_ALPHAKILL;
2409                         }
2410                         else
2411                                 GL_AlphaToCoverage(false);
2412                 }
2413         }
2414         else
2415         {
2416                 if (r_glsl_offsetmapping.integer && ((R_TextureFlags(rsurface.texture->nmaptexture) & TEXF_ALPHA) || rsurface.texture->offsetbias != 0.0f))
2417                 {
2418                         switch(rsurface.texture->offsetmapping)
2419                         {
2420                         case OFFSETMAPPING_LINEAR: permutation |= SHADERPERMUTATION_OFFSETMAPPING;break;
2421                         case OFFSETMAPPING_RELIEF: permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2422                         case OFFSETMAPPING_DEFAULT: permutation |= SHADERPERMUTATION_OFFSETMAPPING;if (r_glsl_offsetmapping_reliefmapping.integer) permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;break;
2423                         case OFFSETMAPPING_OFF: break;
2424                         }
2425                 }
2426                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2427                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2428                 // lightmapped wall
2429                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
2430                         permutation |= SHADERPERMUTATION_GLOW;
2431                 if (r_refdef.fogenabled)
2432                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
2433                 if (rsurface.texture->colormapping)
2434                         permutation |= SHADERPERMUTATION_COLORMAPPING;
2435                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
2436                 {
2437                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
2438                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
2439
2440                         if (r_shadow_shadowmapsampler)
2441                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
2442                         if (r_shadow_shadowmappcf > 1)
2443                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
2444                         else if (r_shadow_shadowmappcf)
2445                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
2446                         if (r_shadow_shadowmap2ddepthbuffer)
2447                                 permutation |= SHADERPERMUTATION_DEPTHRGB;
2448                 }
2449                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
2450                         permutation |= SHADERPERMUTATION_REFLECTION;
2451                 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
2452                         permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
2453                 if (rsurface.texture->reflectmasktexture)
2454                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
2455                 if (FAKELIGHT_ENABLED)
2456                 {
2457                         // fake lightmapping (q1bsp, q3bsp, fullbright map)
2458                         mode = SHADERMODE_FAKELIGHT;
2459                         permutation |= SHADERPERMUTATION_DIFFUSE;
2460                         if (specularscale > 0)
2461                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
2462                 }
2463                 else if (r_glsl_deluxemapping.integer >= 1 && rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping)
2464                 {
2465                         // deluxemapping (light direction texture)
2466                         if (rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping && r_refdef.scene.worldmodel->brushq3.deluxemapping_modelspace)
2467                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE;
2468                         else
2469                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
2470                         permutation |= SHADERPERMUTATION_DIFFUSE;
2471                         if (specularscale > 0)
2472                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
2473                 }
2474                 else if (r_glsl_deluxemapping.integer >= 2)
2475                 {
2476                         // fake deluxemapping (uniform light direction in tangentspace)
2477                         if (rsurface.uselightmaptexture)
2478                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_FORCED_LIGHTMAP;
2479                         else
2480                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_FORCED_VERTEXCOLOR;
2481                         permutation |= SHADERPERMUTATION_DIFFUSE;
2482                         if (specularscale > 0)
2483                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
2484                 }
2485                 else if (rsurface.uselightmaptexture)
2486                 {
2487                         // ordinary lightmapping (q1bsp, q3bsp)
2488                         mode = SHADERMODE_LIGHTMAP;
2489                 }
2490                 else
2491                 {
2492                         // ordinary vertex coloring (q3bsp)
2493                         mode = SHADERMODE_VERTEXCOLOR;
2494                 }
2495                 if (r_shadow_bouncegridtexture && cl.csqc_vidvars.drawworld)
2496                 {
2497                         permutation |= SHADERPERMUTATION_BOUNCEGRID;
2498                         if (r_shadow_bouncegriddirectional)
2499                                 permutation |= SHADERPERMUTATION_BOUNCEGRIDDIRECTIONAL;
2500                 }
2501                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
2502                 blendfuncflags = R_BlendFuncFlags(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
2503                 // when using alphatocoverage, we don't need alphakill
2504                 if (vid.allowalphatocoverage)
2505                 {
2506                         if (r_transparent_alphatocoverage.integer)
2507                         {
2508                                 GL_AlphaToCoverage((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
2509                                 permutation &= ~SHADERPERMUTATION_ALPHAKILL;
2510                         }
2511                         else
2512                                 GL_AlphaToCoverage(false);
2513                 }
2514         }
2515         if(!(blendfuncflags & BLENDFUNC_ALLOWS_COLORMOD))
2516                 colormod = dummy_colormod;
2517         if(!(blendfuncflags & BLENDFUNC_ALLOWS_ANYFOG))
2518                 permutation &= ~(SHADERPERMUTATION_FOGHEIGHTTEXTURE | SHADERPERMUTATION_FOGOUTSIDE | SHADERPERMUTATION_FOGINSIDE);
2519         if(blendfuncflags & BLENDFUNC_ALLOWS_FOG_HACKALPHA)
2520                 permutation |= SHADERPERMUTATION_FOGALPHAHACK;
2521         switch(vid.renderpath)
2522         {
2523         case RENDERPATH_D3D9:
2524 #ifdef SUPPORTD3D
2525                 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
2526                 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
2527                 R_SetupShader_SetPermutationHLSL(mode, permutation);
2528                 Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);hlslPSSetParameter16f(D3DPSREGISTER_ModelToReflectCube, m16f);
2529                 if (mode == SHADERMODE_LIGHTSOURCE)
2530                 {
2531                         Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);hlslVSSetParameter16f(D3DVSREGISTER_ModelToLight, m16f);
2532                         hlslVSSetParameter3f(D3DVSREGISTER_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
2533                 }
2534                 else
2535                 {
2536                         if (mode == SHADERMODE_LIGHTDIRECTION)
2537                         {
2538                                 hlslVSSetParameter3f(D3DVSREGISTER_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
2539                         }
2540                 }
2541                 Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_TexMatrix, m16f);
2542                 Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_BackgroundTexMatrix, m16f);
2543                 Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_ShadowMapMatrix, m16f);
2544                 hlslVSSetParameter3f(D3DVSREGISTER_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
2545                 hlslVSSetParameter4f(D3DVSREGISTER_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
2546
2547                 if (mode == SHADERMODE_LIGHTSOURCE)
2548                 {
2549                         hlslPSSetParameter3f(D3DPSREGISTER_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
2550                         hlslPSSetParameter3f(D3DPSREGISTER_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
2551                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
2552                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
2553                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
2554
2555                         // additive passes are only darkened by fog, not tinted
2556                         hlslPSSetParameter3f(D3DPSREGISTER_FogColor, 0, 0, 0);
2557                         hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f) - 1.0f);
2558                 }
2559                 else
2560                 {
2561                         if (mode == SHADERMODE_FLATCOLOR)
2562                         {
2563                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, colormod[0], colormod[1], colormod[2]);
2564                         }
2565                         else if (mode == SHADERMODE_LIGHTDIRECTION)
2566                         {
2567                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * colormod[2]);
2568                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
2569                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
2570                                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Diffuse, colormod[0], colormod[1], colormod[2]);
2571                                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Specular, specularscale, specularscale, specularscale);
2572                                 hlslPSSetParameter3f(D3DPSREGISTER_LightColor, rsurface.modellight_diffuse[0], rsurface.modellight_diffuse[1], rsurface.modellight_diffuse[2]);
2573                                 hlslPSSetParameter3f(D3DPSREGISTER_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
2574                         }
2575                         else
2576                         {
2577                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
2578                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
2579                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
2580                                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
2581                                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Specular, specularscale, specularscale, specularscale);
2582                         }
2583                         // additive passes are only darkened by fog, not tinted
2584                         if(blendfuncflags & BLENDFUNC_ALLOWS_FOG_HACK0)
2585                                 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, 0, 0, 0);
2586                         else
2587                                 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
2588                         hlslPSSetParameter4f(D3DPSREGISTER_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);
2589                         hlslPSSetParameter4f(D3DPSREGISTER_ScreenScaleRefractReflect, r_fb.water.screenscale[0], r_fb.water.screenscale[1], r_fb.water.screenscale[0], r_fb.water.screenscale[1]);
2590                         hlslPSSetParameter4f(D3DPSREGISTER_ScreenCenterRefractReflect, r_fb.water.screencenter[0], r_fb.water.screencenter[1], r_fb.water.screencenter[0], r_fb.water.screencenter[1]);
2591                         hlslPSSetParameter4f(D3DPSREGISTER_RefractColor, rsurface.texture->refractcolor4f[0], rsurface.texture->refractcolor4f[1], rsurface.texture->refractcolor4f[2], rsurface.texture->refractcolor4f[3] * rsurface.texture->lightmapcolor[3]);
2592                         hlslPSSetParameter4f(D3DPSREGISTER_ReflectColor, rsurface.texture->reflectcolor4f[0], rsurface.texture->reflectcolor4f[1], rsurface.texture->reflectcolor4f[2], rsurface.texture->reflectcolor4f[3] * rsurface.texture->lightmapcolor[3]);
2593                         hlslPSSetParameter1f(D3DPSREGISTER_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
2594                         hlslPSSetParameter1f(D3DPSREGISTER_ReflectOffset, rsurface.texture->reflectmin);
2595                         hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, (rsurface.texture->specularpower - 1.0f) * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
2596                         if (mode == SHADERMODE_WATER)
2597                                 hlslPSSetParameter2f(D3DPSREGISTER_NormalmapScrollBlend, rsurface.texture->r_water_waterscroll[0], rsurface.texture->r_water_waterscroll[1]);
2598                 }
2599                 hlslPSSetParameter2f(D3DPSREGISTER_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
2600                 hlslPSSetParameter4f(D3DPSREGISTER_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
2601                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
2602                 hlslPSSetParameter1f(D3DPSREGISTER_Alpha, rsurface.texture->lightmapcolor[3] * ((rsurface.texture->basematerialflags & MATERIALFLAG_WATERSHADER && r_fb.water.enabled && !r_refdef.view.isoverlay) ? rsurface.texture->r_water_wateralpha : 1));
2603                 hlslPSSetParameter3f(D3DPSREGISTER_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
2604                 if (rsurface.texture->pantstexture)
2605                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
2606                 else
2607                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Pants, 0, 0, 0);
2608                 if (rsurface.texture->shirttexture)
2609                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
2610                 else
2611                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Shirt, 0, 0, 0);
2612                 hlslPSSetParameter4f(D3DPSREGISTER_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
2613                 hlslPSSetParameter1f(D3DPSREGISTER_FogPlaneViewDist, rsurface.fogplaneviewdist);
2614                 hlslPSSetParameter1f(D3DPSREGISTER_FogRangeRecip, rsurface.fograngerecip);
2615                 hlslPSSetParameter1f(D3DPSREGISTER_FogHeightFade, rsurface.fogheightfade);
2616                 hlslPSSetParameter4f(D3DPSREGISTER_OffsetMapping_ScaleSteps,
2617                                 r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale,
2618                                 max(1, (permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) ? r_glsl_offsetmapping_reliefmapping_steps.integer : r_glsl_offsetmapping_steps.integer),
2619                                 1.0 / max(1, (permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) ? r_glsl_offsetmapping_reliefmapping_steps.integer : r_glsl_offsetmapping_steps.integer),
2620                                 max(1, r_glsl_offsetmapping_reliefmapping_refinesteps.integer)
2621                         );
2622                 hlslPSSetParameter1f(D3DPSREGISTER_OffsetMapping_LodDistance, r_glsl_offsetmapping_lod_distance.integer);
2623                 hlslPSSetParameter1f(D3DPSREGISTER_OffsetMapping_Bias, rsurface.texture->offsetbias);
2624                 hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
2625                 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
2626
2627                 R_Mesh_TexBind(GL20TU_NORMAL            , rsurface.texture->nmaptexture                       );
2628                 R_Mesh_TexBind(GL20TU_COLOR             , rsurface.texture->basetexture                       );
2629                 R_Mesh_TexBind(GL20TU_GLOSS             , rsurface.texture->glosstexture                      );
2630                 R_Mesh_TexBind(GL20TU_GLOW              , rsurface.texture->glowtexture                       );
2631                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL  , rsurface.texture->backgroundnmaptexture             );
2632                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR   , rsurface.texture->backgroundbasetexture             );
2633                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS   , rsurface.texture->backgroundglosstexture            );
2634                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW    , rsurface.texture->backgroundglowtexture             );
2635                 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_PANTS             , rsurface.texture->pantstexture                      );
2636                 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_SHIRT             , rsurface.texture->shirttexture                      );
2637                 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTMASK       , rsurface.texture->reflectmasktexture                );
2638                 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTCUBE       , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
2639                 if (permutation & SHADERPERMUTATION_FOGHEIGHTTEXTURE) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE  , r_texture_fogheighttexture                          );
2640                 if (permutation & (SHADERPERMUTATION_FOGINSIDE | SHADERPERMUTATION_FOGOUTSIDE)) R_Mesh_TexBind(GL20TU_FOGMASK           , r_texture_fogattenuation                            );
2641                 R_Mesh_TexBind(GL20TU_LIGHTMAP          , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
2642                 R_Mesh_TexBind(GL20TU_DELUXEMAP         , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
2643                 if (rsurface.rtlight                                  ) R_Mesh_TexBind(GL20TU_ATTENUATION       , r_shadow_attenuationgradienttexture                 );
2644                 if (rsurfacepass == RSURFPASS_BACKGROUND)
2645                 {
2646                         R_Mesh_TexBind(GL20TU_REFRACTION        , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
2647                         if(mode == SHADERMODE_GENERIC) R_Mesh_TexBind(GL20TU_FIRST             , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
2648                         R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
2649                 }
2650                 else
2651                 {
2652                         if (permutation & SHADERPERMUTATION_REFLECTION        ) R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
2653                 }
2654 //              if (rsurfacepass == RSURFPASS_DEFERREDLIGHT           ) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP   , r_shadow_prepassgeometrynormalmaptexture            );
2655                 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP  ) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE     , r_shadow_prepasslightingdiffusetexture              );
2656                 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP  ) R_Mesh_TexBind(GL20TU_SCREENSPECULAR    , r_shadow_prepasslightingspeculartexture             );
2657                 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
2658                 {
2659                         R_Mesh_TexBind(GL20TU_SHADOWMAP2D, r_shadow_shadowmap2ddepthtexture);
2660                         if (rsurface.rtlight)
2661                         {
2662                                 if (permutation & SHADERPERMUTATION_CUBEFILTER        ) R_Mesh_TexBind(GL20TU_CUBE              , rsurface.rtlight->currentcubemap                    );
2663                                 if (permutation & SHADERPERMUTATION_SHADOWMAPVSDCT    ) R_Mesh_TexBind(GL20TU_CUBEPROJECTION    , r_shadow_shadowmapvsdcttexture                      );
2664                         }
2665                 }
2666 #endif
2667                 break;
2668         case RENDERPATH_D3D10:
2669                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2670                 break;
2671         case RENDERPATH_D3D11:
2672                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
2673                 break;
2674         case RENDERPATH_GL20:
2675         case RENDERPATH_GLES2:
2676                 if (!vid.useinterleavedarrays)
2677                 {
2678                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
2679                         R_Mesh_VertexPointer(     3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
2680                         R_Mesh_ColorPointer(      4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
2681                         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
2682                         R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
2683                         R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
2684                         R_Mesh_TexCoordPointer(3, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
2685                         R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
2686                 }
2687                 else
2688                 {
2689                         RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
2690                         R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
2691                 }
2692                 R_SetupShader_SetPermutationGLSL(mode, permutation);
2693                 if (r_glsl_permutation->loc_ModelToReflectCube >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_ModelToReflectCube, 1, false, m16f);}
2694                 if (mode == SHADERMODE_LIGHTSOURCE)
2695                 {
2696                         if (r_glsl_permutation->loc_ModelToLight >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_ModelToLight, 1, false, m16f);}
2697                         if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3f(r_glsl_permutation->loc_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
2698                         if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3f(r_glsl_permutation->loc_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
2699                         if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
2700                         if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
2701                         if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
2702         
2703                         // additive passes are only darkened by fog, not tinted
2704                         if (r_glsl_permutation->loc_FogColor >= 0)
2705                                 qglUniform3f(r_glsl_permutation->loc_FogColor, 0, 0, 0);
2706                         if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1f(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f) - 1.0f);
2707                 }
2708                 else
2709                 {
2710                         if (mode == SHADERMODE_FLATCOLOR)
2711                         {
2712                                 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Ambient, colormod[0], colormod[1], colormod[2]);
2713                         }
2714                         else if (mode == SHADERMODE_LIGHTDIRECTION)
2715                         {
2716                                 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[2]);
2717                                 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
2718                                 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
2719                                 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_DeferredMod_Diffuse, colormod[0], colormod[1], colormod[2]);
2720                                 if (r_glsl_permutation->loc_DeferredMod_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_DeferredMod_Specular, specularscale, specularscale, specularscale);
2721                                 if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3f(r_glsl_permutation->loc_LightColor, rsurface.modellight_diffuse[0] * r_refdef.scene.rtlightstylevalue[0], rsurface.modellight_diffuse[1] * r_refdef.scene.rtlightstylevalue[0], rsurface.modellight_diffuse[2] * r_refdef.scene.rtlightstylevalue[0]);
2722                                 if (r_glsl_permutation->loc_LightDir >= 0) qglUniform3f(r_glsl_permutation->loc_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
2723                         }
2724                         else
2725                         {
2726                                 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
2727                                 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
2728                                 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
2729                                 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_DeferredMod_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
2730                                 if (r_glsl_permutation->loc_DeferredMod_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_DeferredMod_Specular, specularscale, specularscale, specularscale);
2731                         }
2732                         // additive passes are only darkened by fog, not tinted
2733                         if (r_glsl_permutation->loc_FogColor >= 0)
2734                         {
2735                                 if(blendfuncflags & BLENDFUNC_ALLOWS_FOG_HACK0)
2736                                         qglUniform3f(r_glsl_permutation->loc_FogColor, 0, 0, 0);
2737                                 else
2738                                         qglUniform3f(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
2739                         }
2740                         if (r_glsl_permutation->loc_DistortScaleRefractReflect >= 0) qglUniform4f(r_glsl_permutation->loc_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);
2741                         if (r_glsl_permutation->loc_ScreenScaleRefractReflect >= 0) qglUniform4f(r_glsl_permutation->loc_ScreenScaleRefractReflect, r_fb.water.screenscale[0], r_fb.water.screenscale[1], r_fb.water.screenscale[0], r_fb.water.screenscale[1]);
2742                         if (r_glsl_permutation->loc_ScreenCenterRefractReflect >= 0) qglUniform4f(r_glsl_permutation->loc_ScreenCenterRefractReflect, r_fb.water.screencenter[0], r_fb.water.screencenter[1], r_fb.water.screencenter[0], r_fb.water.screencenter[1]);
2743                         if (r_glsl_permutation->loc_RefractColor >= 0) qglUniform4f(r_glsl_permutation->loc_RefractColor, rsurface.texture->refractcolor4f[0], rsurface.texture->refractcolor4f[1], rsurface.texture->refractcolor4f[2], rsurface.texture->refractcolor4f[3] * rsurface.texture->lightmapcolor[3]);
2744                         if (r_glsl_permutation->loc_ReflectColor >= 0) qglUniform4f(r_glsl_permutation->loc_ReflectColor, rsurface.texture->reflectcolor4f[0], rsurface.texture->reflectcolor4f[1], rsurface.texture->reflectcolor4f[2], rsurface.texture->reflectcolor4f[3] * rsurface.texture->lightmapcolor[3]);
2745                         if (r_glsl_permutation->loc_ReflectFactor >= 0) qglUniform1f(r_glsl_permutation->loc_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
2746                         if (r_glsl_permutation->loc_ReflectOffset >= 0) qglUniform1f(r_glsl_permutation->loc_ReflectOffset, rsurface.texture->reflectmin);
2747                         if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1f(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f) - 1.0f);
2748                         if (r_glsl_permutation->loc_NormalmapScrollBlend >= 0) qglUniform2f(r_glsl_permutation->loc_NormalmapScrollBlend, rsurface.texture->r_water_waterscroll[0], rsurface.texture->r_water_waterscroll[1]);
2749                 }
2750                 if (r_glsl_permutation->loc_TexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_TexMatrix, 1, false, m16f);}
2751                 if (r_glsl_permutation->loc_BackgroundTexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_BackgroundTexMatrix, 1, false, m16f);}
2752                 if (r_glsl_permutation->loc_ShadowMapMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_ShadowMapMatrix, 1, false, m16f);}
2753                 if (r_glsl_permutation->loc_ShadowMap_TextureScale >= 0) qglUniform2f(r_glsl_permutation->loc_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
2754                 if (r_glsl_permutation->loc_ShadowMap_Parameters >= 0) qglUniform4f(r_glsl_permutation->loc_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
2755
2756                 if (r_glsl_permutation->loc_Color_Glow >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
2757                 if (r_glsl_permutation->loc_Alpha >= 0) qglUniform1f(r_glsl_permutation->loc_Alpha, rsurface.texture->lightmapcolor[3] * ((rsurface.texture->basematerialflags & MATERIALFLAG_WATERSHADER && r_fb.water.enabled && !r_refdef.view.isoverlay) ? rsurface.texture->r_water_wateralpha : 1));
2758                 if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3f(r_glsl_permutation->loc_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
2759                 if (r_glsl_permutation->loc_Color_Pants >= 0)
2760                 {
2761                         if (rsurface.texture->pantstexture)
2762                                 qglUniform3f(r_glsl_permutation->loc_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
2763                         else
2764                                 qglUniform3f(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
2765                 }
2766                 if (r_glsl_permutation->loc_Color_Shirt >= 0)
2767                 {
2768                         if (rsurface.texture->shirttexture)
2769                                 qglUniform3f(r_glsl_permutation->loc_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
2770                         else
2771                                 qglUniform3f(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
2772                 }
2773                 if (r_glsl_permutation->loc_FogPlane >= 0) qglUniform4f(r_glsl_permutation->loc_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
2774                 if (r_glsl_permutation->loc_FogPlaneViewDist >= 0) qglUniform1f(r_glsl_permutation->loc_FogPlaneViewDist, rsurface.fogplaneviewdist);
2775                 if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1f(r_glsl_permutation->loc_FogRangeRecip, rsurface.fograngerecip);
2776                 if (r_glsl_permutation->loc_FogHeightFade >= 0) qglUniform1f(r_glsl_permutation->loc_FogHeightFade, rsurface.fogheightfade);
2777                 if (r_glsl_permutation->loc_OffsetMapping_ScaleSteps >= 0) qglUniform4f(r_glsl_permutation->loc_OffsetMapping_ScaleSteps,
2778                                 r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale,
2779                                 max(1, (permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) ? r_glsl_offsetmapping_reliefmapping_steps.integer : r_glsl_offsetmapping_steps.integer),
2780                                 1.0 / max(1, (permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) ? r_glsl_offsetmapping_reliefmapping_steps.integer : r_glsl_offsetmapping_steps.integer),
2781                                 max(1, r_glsl_offsetmapping_reliefmapping_refinesteps.integer)
2782                         );
2783                 if (r_glsl_permutation->loc_OffsetMapping_LodDistance >= 0) qglUniform1f(r_glsl_permutation->loc_OffsetMapping_LodDistance, r_glsl_offsetmapping_lod_distance.integer);
2784                 if (r_glsl_permutation->loc_OffsetMapping_Bias >= 0) qglUniform1f(r_glsl_permutation->loc_OffsetMapping_Bias, rsurface.texture->offsetbias);
2785                 if (r_glsl_permutation->loc_ScreenToDepth >= 0) qglUniform2f(r_glsl_permutation->loc_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
2786                 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2f(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
2787                 if (r_glsl_permutation->loc_BounceGridMatrix >= 0) {Matrix4x4_Concat(&tempmatrix, &r_shadow_bouncegridmatrix, &rsurface.matrix);Matrix4x4_ToArrayFloatGL(&tempmatrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_BounceGridMatrix, 1, false, m16f);}
2788                 if (r_glsl_permutation->loc_BounceGridIntensity >= 0) qglUniform1f(r_glsl_permutation->loc_BounceGridIntensity, r_shadow_bouncegridintensity*r_refdef.view.colorscale);
2789
2790                 if (r_glsl_permutation->tex_Texture_First           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_First            , r_texture_white                                     );
2791                 if (r_glsl_permutation->tex_Texture_Second          >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Second           , r_texture_white                                     );
2792                 if (r_glsl_permutation->tex_Texture_GammaRamps      >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_GammaRamps       , r_texture_gammaramps                                );
2793                 if (r_glsl_permutation->tex_Texture_Normal          >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Normal           , rsurface.texture->nmaptexture                       );
2794                 if (r_glsl_permutation->tex_Texture_Color           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Color            , rsurface.texture->basetexture                       );
2795                 if (r_glsl_permutation->tex_Texture_Gloss           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Gloss            , rsurface.texture->glosstexture                      );
2796                 if (r_glsl_permutation->tex_Texture_Glow            >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Glow             , rsurface.texture->glowtexture                       );
2797                 if (r_glsl_permutation->tex_Texture_SecondaryNormal >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_SecondaryNormal  , rsurface.texture->backgroundnmaptexture             );
2798                 if (r_glsl_permutation->tex_Texture_SecondaryColor  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_SecondaryColor   , rsurface.texture->backgroundbasetexture             );
2799                 if (r_glsl_permutation->tex_Texture_SecondaryGloss  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_SecondaryGloss   , rsurface.texture->backgroundglosstexture            );
2800                 if (r_glsl_permutation->tex_Texture_SecondaryGlow   >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_SecondaryGlow    , rsurface.texture->backgroundglowtexture             );
2801                 if (r_glsl_permutation->tex_Texture_Pants           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Pants            , rsurface.texture->pantstexture                      );
2802                 if (r_glsl_permutation->tex_Texture_Shirt           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Shirt            , rsurface.texture->shirttexture                      );
2803                 if (r_glsl_permutation->tex_Texture_ReflectMask     >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ReflectMask      , rsurface.texture->reflectmasktexture                );
2804                 if (r_glsl_permutation->tex_Texture_ReflectCube     >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ReflectCube      , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
2805                 if (r_glsl_permutation->tex_Texture_FogHeightTexture>= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_FogHeightTexture , r_texture_fogheighttexture                          );
2806                 if (r_glsl_permutation->tex_Texture_FogMask         >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_FogMask          , r_texture_fogattenuation                            );
2807                 if (r_glsl_permutation->tex_Texture_Lightmap        >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Lightmap         , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
2808                 if (r_glsl_permutation->tex_Texture_Deluxemap       >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Deluxemap        , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
2809                 if (r_glsl_permutation->tex_Texture_Attenuation     >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Attenuation      , r_shadow_attenuationgradienttexture                 );
2810                 if (rsurfacepass == RSURFPASS_BACKGROUND)
2811                 {
2812                         if (r_glsl_permutation->tex_Texture_Refraction  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Refraction        , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
2813                         if (r_glsl_permutation->tex_Texture_First       >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_First             , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
2814                         if (r_glsl_permutation->tex_Texture_Reflection  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Reflection        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
2815                 }
2816                 else
2817                 {
2818                         if (r_glsl_permutation->tex_Texture_Reflection >= 0 && waterplane) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Reflection        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
2819                 }
2820                 if (r_glsl_permutation->tex_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenNormalMap   , r_shadow_prepassgeometrynormalmaptexture            );
2821                 if (r_glsl_permutation->tex_Texture_ScreenDiffuse   >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenDiffuse     , r_shadow_prepasslightingdiffusetexture              );
2822                 if (r_glsl_permutation->tex_Texture_ScreenSpecular  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenSpecular    , r_shadow_prepasslightingspeculartexture             );
2823                 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
2824                 {
2825                         if (r_glsl_permutation->tex_Texture_ShadowMap2D     >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ShadowMap2D, r_shadow_shadowmap2ddepthtexture                           );
2826                         if (rsurface.rtlight)
2827                         {
2828                                 if (r_glsl_permutation->tex_Texture_Cube            >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Cube              , rsurface.rtlight->currentcubemap                    );
2829                                 if (r_glsl_permutation->tex_Texture_CubeProjection  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_CubeProjection    , r_shadow_shadowmapvsdcttexture                      );
2830                         }
2831                 }
2832                 if (r_glsl_permutation->tex_Texture_BounceGrid  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_BounceGrid, r_shadow_bouncegridtexture);
2833                 CHECKGLERROR
2834                 break;
2835         case RENDERPATH_GL11:
2836         case RENDERPATH_GL13:
2837         case RENDERPATH_GLES1:
2838                 break;
2839         case RENDERPATH_SOFT:
2840                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
2841                 R_Mesh_PrepareVertices_Mesh_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchsvector3f, rsurface.batchtvector3f, rsurface.batchnormal3f, rsurface.batchlightmapcolor4f, rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordlightmap2f);
2842                 R_SetupShader_SetPermutationSoft(mode, permutation);
2843                 {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelToReflectCubeM1, 1, false, m16f);}
2844                 if (mode == SHADERMODE_LIGHTSOURCE)
2845                 {
2846                         {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelToLightM1, 1, false, m16f);}
2847                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
2848                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
2849                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
2850                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
2851                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
2852         
2853                         // additive passes are only darkened by fog, not tinted
2854                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_FogColor, 0, 0, 0);
2855                         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f) - 1.0f);
2856                 }
2857                 else
2858                 {
2859                         if (mode == SHADERMODE_FLATCOLOR)
2860                         {
2861                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Ambient, colormod[0], colormod[1], colormod[2]);
2862                         }
2863                         else if (mode == SHADERMODE_LIGHTDIRECTION)
2864                         {
2865                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[2]);
2866                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
2867                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
2868                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_DeferredMod_Diffuse, colormod[0], colormod[1], colormod[2]);
2869                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_DeferredMod_Specular, specularscale, specularscale, specularscale);
2870                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_LightColor, rsurface.modellight_diffuse[0] * r_refdef.scene.rtlightstylevalue[0], rsurface.modellight_diffuse[1] * r_refdef.scene.rtlightstylevalue[0], rsurface.modellight_diffuse[2] * r_refdef.scene.rtlightstylevalue[0]);
2871                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
2872                         }
2873                         else
2874                         {
2875                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
2876                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
2877                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
2878                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_DeferredMod_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
2879                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_DeferredMod_Specular, specularscale, specularscale, specularscale);
2880                         }
2881                         // additive passes are only darkened by fog, not tinted
2882                         if(blendfuncflags & BLENDFUNC_ALLOWS_FOG_HACK0)
2883                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_FogColor, 0, 0, 0);
2884                         else
2885                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
2886                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);
2887                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ScreenScaleRefractReflect, r_fb.water.screenscale[0], r_fb.water.screenscale[1], r_fb.water.screenscale[0], r_fb.water.screenscale[1]);
2888                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ScreenCenterRefractReflect, r_fb.water.screencenter[0], r_fb.water.screencenter[1], r_fb.water.screencenter[0], r_fb.water.screencenter[1]);
2889                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_RefractColor, rsurface.texture->refractcolor4f[0], rsurface.texture->refractcolor4f[1], rsurface.texture->refractcolor4f[2], rsurface.texture->refractcolor4f[3] * rsurface.texture->lightmapcolor[3]);
2890                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ReflectColor, rsurface.texture->reflectcolor4f[0], rsurface.texture->reflectcolor4f[1], rsurface.texture->reflectcolor4f[2], rsurface.texture->reflectcolor4f[3] * rsurface.texture->lightmapcolor[3]);
2891                         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
2892                         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_ReflectOffset, rsurface.texture->reflectmin);
2893                         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f) - 1.0f);
2894                         DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_NormalmapScrollBlend, rsurface.texture->r_water_waterscroll[0], rsurface.texture->r_water_waterscroll[1]);
2895                 }
2896                 {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_TexMatrixM1, 1, false, m16f);}
2897                 {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_BackgroundTexMatrixM1, 1, false, m16f);}
2898                 {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ShadowMapMatrixM1, 1, false, m16f);}
2899                 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
2900                 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
2901
2902                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
2903                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_Alpha, rsurface.texture->lightmapcolor[3] * ((rsurface.texture->basematerialflags & MATERIALFLAG_WATERSHADER && r_fb.water.enabled && !r_refdef.view.isoverlay) ? rsurface.texture->r_water_wateralpha : 1));
2904                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
2905                 if (DPSOFTRAST_UNIFORM_Color_Pants >= 0)
2906                 {
2907                         if (rsurface.texture->pantstexture)
2908                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
2909                         else
2910                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Pants, 0, 0, 0);
2911                 }
2912                 if (DPSOFTRAST_UNIFORM_Color_Shirt >= 0)
2913                 {
2914                         if (rsurface.texture->shirttexture)
2915                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
2916                         else
2917                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Shirt, 0, 0, 0);
2918                 }
2919                 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
2920                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_FogPlaneViewDist, rsurface.fogplaneviewdist);
2921                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_FogRangeRecip, rsurface.fograngerecip);
2922                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_FogHeightFade, rsurface.fogheightfade);
2923                 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_OffsetMapping_ScaleSteps,
2924                                 r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale,
2925                                 max(1, (permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) ? r_glsl_offsetmapping_reliefmapping_steps.integer : r_glsl_offsetmapping_steps.integer),
2926                                 1.0 / max(1, (permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) ? r_glsl_offsetmapping_reliefmapping_steps.integer : r_glsl_offsetmapping_steps.integer),
2927                                 max(1, r_glsl_offsetmapping_reliefmapping_refinesteps.integer)
2928                         );
2929                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_OffsetMapping_LodDistance, r_glsl_offsetmapping_lod_distance.integer);
2930                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_OffsetMapping_Bias, rsurface.texture->offsetbias);
2931                 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
2932                 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
2933
2934                 R_Mesh_TexBind(GL20TU_NORMAL            , rsurface.texture->nmaptexture                       );
2935                 R_Mesh_TexBind(GL20TU_COLOR             , rsurface.texture->basetexture                       );
2936                 R_Mesh_TexBind(GL20TU_GLOSS             , rsurface.texture->glosstexture                      );
2937                 R_Mesh_TexBind(GL20TU_GLOW              , rsurface.texture->glowtexture                       );
2938                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL  , rsurface.texture->backgroundnmaptexture             );
2939                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR   , rsurface.texture->backgroundbasetexture             );
2940                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS   , rsurface.texture->backgroundglosstexture            );
2941                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW    , rsurface.texture->backgroundglowtexture             );
2942                 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_PANTS             , rsurface.texture->pantstexture                      );
2943                 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_SHIRT             , rsurface.texture->shirttexture                      );
2944                 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTMASK       , rsurface.texture->reflectmasktexture                );
2945                 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTCUBE       , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
2946                 if (permutation & SHADERPERMUTATION_FOGHEIGHTTEXTURE) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE  , r_texture_fogheighttexture                          );
2947                 if (permutation & (SHADERPERMUTATION_FOGINSIDE | SHADERPERMUTATION_FOGOUTSIDE)) R_Mesh_TexBind(GL20TU_FOGMASK           , r_texture_fogattenuation                            );
2948                 R_Mesh_TexBind(GL20TU_LIGHTMAP          , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
2949                 R_Mesh_TexBind(GL20TU_DELUXEMAP         , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
2950                 if (rsurface.rtlight                                  ) R_Mesh_TexBind(GL20TU_ATTENUATION       , r_shadow_attenuationgradienttexture                 );
2951                 if (rsurfacepass == RSURFPASS_BACKGROUND)
2952                 {
2953                         R_Mesh_TexBind(GL20TU_REFRACTION        , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
2954                         if(mode == SHADERMODE_GENERIC) R_Mesh_TexBind(GL20TU_FIRST             , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
2955                         R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
2956                 }
2957                 else
2958                 {
2959                         if (permutation & SHADERPERMUTATION_REFLECTION        ) R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
2960                 }
2961 //              if (rsurfacepass == RSURFPASS_DEFERREDLIGHT           ) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP   , r_shadow_prepassgeometrynormalmaptexture            );
2962                 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP  ) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE     , r_shadow_prepasslightingdiffusetexture              );
2963                 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP  ) R_Mesh_TexBind(GL20TU_SCREENSPECULAR    , r_shadow_prepasslightingspeculartexture             );
2964                 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
2965                 {
2966                         R_Mesh_TexBind(GL20TU_SHADOWMAP2D, r_shadow_shadowmap2ddepthtexture);
2967                         if (rsurface.rtlight)
2968                         {
2969                                 if (permutation & SHADERPERMUTATION_CUBEFILTER        ) R_Mesh_TexBind(GL20TU_CUBE              , rsurface.rtlight->currentcubemap                    );
2970                                 if (permutation & SHADERPERMUTATION_SHADOWMAPVSDCT    ) R_Mesh_TexBind(GL20TU_CUBEPROJECTION    , r_shadow_shadowmapvsdcttexture                      );
2971                         }
2972                 }
2973                 break;
2974         }
2975 }
2976
2977 void R_SetupShader_DeferredLight(const rtlight_t *rtlight)
2978 {
2979         // select a permutation of the lighting shader appropriate to this
2980         // combination of texture, entity, light source, and fogging, only use the
2981         // minimum features necessary to avoid wasting rendering time in the
2982         // fragment shader on features that are not being used
2983         unsigned int permutation = 0;
2984         unsigned int mode = 0;
2985         const float *lightcolorbase = rtlight->currentcolor;
2986         float ambientscale = rtlight->ambientscale;
2987         float diffusescale = rtlight->diffusescale;
2988         float specularscale = rtlight->specularscale;
2989         // this is the location of the light in view space
2990         vec3_t viewlightorigin;
2991         // this transforms from view space (camera) to light space (cubemap)
2992         matrix4x4_t viewtolight;
2993         matrix4x4_t lighttoview;
2994         float viewtolight16f[16];
2995         // light source
2996         mode = SHADERMODE_DEFERREDLIGHTSOURCE;
2997         if (rtlight->currentcubemap != r_texture_whitecube)
2998                 permutation |= SHADERPERMUTATION_CUBEFILTER;
2999         if (diffusescale > 0)
3000                 permutation |= SHADERPERMUTATION_DIFFUSE;
3001         if (specularscale > 0 && r_shadow_gloss.integer > 0)
3002                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
3003         if (r_shadow_usingshadowmap2d)
3004         {
3005                 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
3006                 if (r_shadow_shadowmapvsdct)
3007                         permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
3008
3009                 if (r_shadow_shadowmapsampler)
3010                         permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
3011                 if (r_shadow_shadowmappcf > 1)
3012                         permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
3013                 else if (r_shadow_shadowmappcf)
3014                         permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
3015                 if (r_shadow_shadowmap2ddepthbuffer)
3016                         permutation |= SHADERPERMUTATION_DEPTHRGB;
3017         }
3018         if (vid.allowalphatocoverage)
3019                 GL_AlphaToCoverage(false);
3020         Matrix4x4_Transform(&r_refdef.view.viewport.viewmatrix, rtlight->shadoworigin, viewlightorigin);
3021         Matrix4x4_Concat(&lighttoview, &r_refdef.view.viewport.viewmatrix, &rtlight->matrix_lighttoworld);
3022         Matrix4x4_Invert_Simple(&viewtolight, &lighttoview);
3023         Matrix4x4_ToArrayFloatGL(&viewtolight, viewtolight16f);
3024         switch(vid.renderpath)
3025         {
3026         case RENDERPATH_D3D9:
3027 #ifdef SUPPORTD3D
3028                 R_SetupShader_SetPermutationHLSL(mode, permutation);
3029                 hlslPSSetParameter3f(D3DPSREGISTER_LightPosition, viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
3030                 hlslPSSetParameter16f(D3DPSREGISTER_ViewToLight, viewtolight16f);
3031                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Ambient , lightcolorbase[0] * ambientscale , lightcolorbase[1] * ambientscale , lightcolorbase[2] * ambientscale );
3032                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Diffuse , lightcolorbase[0] * diffusescale , lightcolorbase[1] * diffusescale , lightcolorbase[2] * diffusescale );
3033                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Specular, lightcolorbase[0] * specularscale, lightcolorbase[1] * specularscale, lightcolorbase[2] * specularscale);
3034                 hlslPSSetParameter2f(D3DPSREGISTER_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
3035                 hlslPSSetParameter4f(D3DPSREGISTER_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
3036                 hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * (r_shadow_glossexact.integer ? 0.25f : 1.0f) - 1.0f);
3037                 hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
3038                 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
3039
3040                 R_Mesh_TexBind(GL20TU_ATTENUATION        , r_shadow_attenuationgradienttexture                 );
3041                 R_Mesh_TexBind(GL20TU_SCREENNORMALMAP    , r_shadow_prepassgeometrynormalmaptexture            );
3042                 R_Mesh_TexBind(GL20TU_CUBE               , rsurface.rtlight->currentcubemap                    );
3043                 R_Mesh_TexBind(GL20TU_SHADOWMAP2D        , r_shadow_shadowmap2ddepthtexture                    );
3044                 R_Mesh_TexBind(GL20TU_CUBEPROJECTION     , r_shadow_shadowmapvsdcttexture                      );
3045 #endif
3046                 break;
3047         case RENDERPATH_D3D10:
3048                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
3049                 break;
3050         case RENDERPATH_D3D11:
3051                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
3052                 break;
3053         case RENDERPATH_GL20:
3054         case RENDERPATH_GLES2:
3055                 R_SetupShader_SetPermutationGLSL(mode, permutation);
3056                 if (r_glsl_permutation->loc_LightPosition             >= 0) qglUniform3f(       r_glsl_permutation->loc_LightPosition            , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
3057                 if (r_glsl_permutation->loc_ViewToLight               >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ViewToLight              , 1, false, viewtolight16f);
3058                 if (r_glsl_permutation->loc_DeferredColor_Ambient     >= 0) qglUniform3f(       r_glsl_permutation->loc_DeferredColor_Ambient    , lightcolorbase[0] * ambientscale , lightcolorbase[1] * ambientscale , lightcolorbase[2] * ambientscale );
3059                 if (r_glsl_permutation->loc_DeferredColor_Diffuse     >= 0) qglUniform3f(       r_glsl_permutation->loc_DeferredColor_Diffuse    , lightcolorbase[0] * diffusescale , lightcolorbase[1] * diffusescale , lightcolorbase[2] * diffusescale );
3060                 if (r_glsl_permutation->loc_DeferredColor_Specular    >= 0) qglUniform3f(       r_glsl_permutation->loc_DeferredColor_Specular   , lightcolorbase[0] * specularscale, lightcolorbase[1] * specularscale, lightcolorbase[2] * specularscale);
3061                 if (r_glsl_permutation->loc_ShadowMap_TextureScale    >= 0) qglUniform2f(       r_glsl_permutation->loc_ShadowMap_TextureScale   , r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
3062                 if (r_glsl_permutation->loc_ShadowMap_Parameters      >= 0) qglUniform4f(       r_glsl_permutation->loc_ShadowMap_Parameters     , r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
3063                 if (r_glsl_permutation->loc_SpecularPower             >= 0) qglUniform1f(       r_glsl_permutation->loc_SpecularPower            , (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * (r_shadow_glossexact.integer ? 0.25f : 1.0f) - 1.0f);
3064                 if (r_glsl_permutation->loc_ScreenToDepth             >= 0) qglUniform2f(       r_glsl_permutation->loc_ScreenToDepth            , r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
3065                 if (r_glsl_permutation->loc_PixelToScreenTexCoord     >= 0) qglUniform2f(       r_glsl_permutation->loc_PixelToScreenTexCoord    , 1.0f/vid.width, 1.0f/vid.height);
3066
3067                 if (r_glsl_permutation->tex_Texture_Attenuation       >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Attenuation        , r_shadow_attenuationgradienttexture                 );
3068                 if (r_glsl_permutation->tex_Texture_ScreenNormalMap   >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenNormalMap    , r_shadow_prepassgeometrynormalmaptexture            );
3069                 if (r_glsl_permutation->tex_Texture_Cube              >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Cube               , rsurface.rtlight->currentcubemap                    );
3070                 if (r_glsl_permutation->tex_Texture_ShadowMap2D       >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ShadowMap2D        , r_shadow_shadowmap2ddepthtexture                    );
3071                 if (r_glsl_permutation->tex_Texture_CubeProjection    >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_CubeProjection     , r_shadow_shadowmapvsdcttexture                      );
3072                 break;
3073         case RENDERPATH_GL11:
3074         case RENDERPATH_GL13:
3075         case RENDERPATH_GLES1:
3076                 break;
3077         case RENDERPATH_SOFT:
3078                 R_SetupShader_SetPermutationGLSL(mode, permutation);
3079                 DPSOFTRAST_Uniform3f(       DPSOFTRAST_UNIFORM_LightPosition            , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
3080                 DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ViewToLightM1            , 1, false, viewtolight16f);
3081                 DPSOFTRAST_Uniform3f(       DPSOFTRAST_UNIFORM_DeferredColor_Ambient    , lightcolorbase[0] * ambientscale , lightcolorbase[1] * ambientscale , lightcolorbase[2] * ambientscale );
3082                 DPSOFTRAST_Uniform3f(       DPSOFTRAST_UNIFORM_DeferredColor_Diffuse    , lightcolorbase[0] * diffusescale , lightcolorbase[1] * diffusescale , lightcolorbase[2] * diffusescale );
3083                 DPSOFTRAST_Uniform3f(       DPSOFTRAST_UNIFORM_DeferredColor_Specular   , lightcolorbase[0] * specularscale, lightcolorbase[1] * specularscale, lightcolorbase[2] * specularscale);
3084                 DPSOFTRAST_Uniform2f(       DPSOFTRAST_UNIFORM_ShadowMap_TextureScale   , r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
3085                 DPSOFTRAST_Uniform4f(       DPSOFTRAST_UNIFORM_ShadowMap_Parameters     , r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
3086                 DPSOFTRAST_Uniform1f(       DPSOFTRAST_UNIFORM_SpecularPower            , (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * (r_shadow_glossexact.integer ? 0.25f : 1.0f) - 1.0f);
3087                 DPSOFTRAST_Uniform2f(       DPSOFTRAST_UNIFORM_ScreenToDepth            , r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
3088                 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
3089
3090                 R_Mesh_TexBind(GL20TU_ATTENUATION        , r_shadow_attenuationgradienttexture                 );
3091                 R_Mesh_TexBind(GL20TU_SCREENNORMALMAP    , r_shadow_prepassgeometrynormalmaptexture            );
3092                 R_Mesh_TexBind(GL20TU_CUBE               , rsurface.rtlight->currentcubemap                    );
3093                 R_Mesh_TexBind(GL20TU_SHADOWMAP2D        , r_shadow_shadowmap2ddepthtexture                    );
3094                 R_Mesh_TexBind(GL20TU_CUBEPROJECTION     , r_shadow_shadowmapvsdcttexture                      );
3095                 break;
3096         }
3097 }
3098
3099 #define SKINFRAME_HASH 1024
3100
3101 typedef struct
3102 {
3103         int loadsequence; // incremented each level change
3104         memexpandablearray_t array;
3105         skinframe_t *hash[SKINFRAME_HASH];
3106 }
3107 r_skinframe_t;
3108 r_skinframe_t r_skinframe;
3109
3110 void R_SkinFrame_PrepareForPurge(void)
3111 {
3112         r_skinframe.loadsequence++;
3113         // wrap it without hitting zero
3114         if (r_skinframe.loadsequence >= 200)
3115                 r_skinframe.loadsequence = 1;
3116 }
3117
3118 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
3119 {
3120         if (!skinframe)
3121                 return;
3122         // mark the skinframe as used for the purging code
3123         skinframe->loadsequence = r_skinframe.loadsequence;
3124 }
3125
3126 void R_SkinFrame_Purge(void)
3127 {
3128         int i;
3129         skinframe_t *s;
3130         for (i = 0;i < SKINFRAME_HASH;i++)
3131         {
3132                 for (s = r_skinframe.hash[i];s;s = s->next)
3133                 {
3134                         if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
3135                         {
3136                                 if (s->merged == s->base)
3137                                         s->merged = NULL;
3138                                 // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
3139                                 R_PurgeTexture(s->stain );s->stain  = NULL;
3140                                 R_PurgeTexture(s->merged);s->merged = NULL;
3141                                 R_PurgeTexture(s->base  );s->base   = NULL;
3142                                 R_PurgeTexture(s->pants );s->pants  = NULL;
3143                                 R_PurgeTexture(s->shirt );s->shirt  = NULL;
3144                                 R_PurgeTexture(s->nmap  );s->nmap   = NULL;
3145                                 R_PurgeTexture(s->gloss );s->gloss  = NULL;
3146                                 R_PurgeTexture(s->glow  );s->glow   = NULL;
3147                                 R_PurgeTexture(s->fog   );s->fog    = NULL;
3148                                 R_PurgeTexture(s->reflect);s->reflect = NULL;
3149                                 s->loadsequence = 0;
3150                         }
3151                 }
3152         }
3153 }
3154
3155 skinframe_t *R_SkinFrame_FindNextByName( skinframe_t *last, const char *name ) {
3156         skinframe_t *item;
3157         char basename[MAX_QPATH];
3158
3159         Image_StripImageExtension(name, basename, sizeof(basename));
3160
3161         if( last == NULL ) {
3162                 int hashindex;
3163                 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
3164                 item = r_skinframe.hash[hashindex];
3165         } else {
3166                 item = last->next;
3167         }
3168
3169         // linearly search through the hash bucket
3170         for( ; item ; item = item->next ) {
3171                 if( !strcmp( item->basename, basename ) ) {
3172                         return item;
3173                 }
3174         }
3175         return NULL;
3176 }
3177
3178 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
3179 {
3180         skinframe_t *item;
3181         int hashindex;
3182         char basename[MAX_QPATH];
3183
3184         Image_StripImageExtension(name, basename, sizeof(basename));
3185
3186         hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
3187         for (item = r_skinframe.hash[hashindex];item;item = item->next)
3188                 if (!strcmp(item->basename, basename) && (comparecrc < 0 || (item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)))
3189                         break;
3190
3191         if (!item) {
3192                 rtexture_t *dyntexture;
3193                 // check whether its a dynamic texture