move R_Main_ResizeViewCache call to fix a crash
[divverent/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
28 mempool_t *r_main_mempool;
29 rtexturepool_t *r_main_texturepool;
30
31 static int r_frame = 0; ///< used only by R_GetCurrentTexture
32
33 //
34 // screen size info
35 //
36 r_refdef_t r_refdef;
37
38 cvar_t r_motionblur = {CVAR_SAVE, "r_motionblur", "0", "motionblur value scale - 0.5 recommended"};
39 cvar_t r_damageblur = {CVAR_SAVE, "r_damageblur", "0", "motionblur based on damage"};
40 cvar_t r_motionblur_vmin = {CVAR_SAVE, "r_motionblur_vmin", "300", "minimum influence from velocity"};
41 cvar_t r_motionblur_vmax = {CVAR_SAVE, "r_motionblur_vmax", "600", "maximum influence from velocity"};
42 cvar_t r_motionblur_bmin = {CVAR_SAVE, "r_motionblur_bmin", "0.5", "velocity at which there is no blur yet (may be negative to always have some blur)"};
43 cvar_t r_motionblur_vcoeff = {CVAR_SAVE, "r_motionblur_vcoeff", "0.05", "sliding average reaction time for velocity"};
44 cvar_t r_motionblur_maxblur = {CVAR_SAVE, "r_motionblur_maxblur", "0.88", "cap for motionblur alpha value"};
45 cvar_t r_motionblur_randomize = {CVAR_SAVE, "r_motionblur_randomize", "0.1", "randomizing coefficient to workaround ghosting"};
46
47 // TODO do we want a r_equalize_entities cvar that works on all ents, or would that be a cheat?
48 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"};
49 cvar_t r_equalize_entities_minambient = {CVAR_SAVE, "r_equalize_entities_minambient", "0.5", "light equalizing: ensure at least this ambient/diffuse ratio"};
50 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)"};
51 cvar_t r_equalize_entities_to = {CVAR_SAVE, "r_equalize_entities_to", "0.8", "light equalizing: target light level"};
52
53 cvar_t r_animcache = {CVAR_SAVE, "r_animcache", "1", "cache animation frames to save CPU usage, primarily optimizes shadows and reflections"};
54
55 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"};
56 cvar_t r_useinfinitefarclip = {CVAR_SAVE, "r_useinfinitefarclip", "1", "enables use of a special kind of projection matrix that has an extremely large farclip"};
57 cvar_t r_farclip_base = {0, "r_farclip_base", "65536", "farclip (furthest visible distance) for rendering when r_useinfinitefarclip is 0"};
58 cvar_t r_farclip_world = {0, "r_farclip_world", "2", "adds map size to farclip multiplied by this value"};
59 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
60 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%,  10 = 100%)"};
61 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)"};
62 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
63 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
64 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"};
65 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"};
66 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
67 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"};
68 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"};
69 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"};
70 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
71 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
72 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
73 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
74 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)"};
75 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)"};
76 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
77 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
78 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
79 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
80 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
81 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
82 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
83 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."};
84 cvar_t r_shadows_darken = {CVAR_SAVE, "r_shadows_darken", "0.5", "how much shadowed areas will be darkened"};
85 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
86 cvar_t r_shadows_throwdirection = {CVAR_SAVE, "r_shadows_throwdirection", "0 0 -1", "override throwing direction for r_shadows 2"};
87 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."};
88 cvar_t r_shadows_castfrombmodels = {CVAR_SAVE, "r_shadows_castfrombmodels", "0", "do cast shadows from bmodels"};
89 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
90 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"};
91 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"};
92 cvar_t r_polygonoffset_decals_factor = {0, "r_polygonoffset_decals_factor", "0", "biases depth values of decals to prevent z-fighting artifacts"};
93 cvar_t r_polygonoffset_decals_offset = {0, "r_polygonoffset_decals_offset", "-14", "biases depth values of decals to prevent z-fighting artifacts"};
94 cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
95 cvar_t r_drawfog = {CVAR_SAVE, "r_drawfog", "1", "allows one to disable fog rendering"};
96
97 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
98 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
99 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
100 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
101 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
102 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
103 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
104 cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
105
106 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of hardware texture units reported by driver (note: setting this to 1 turns off gl_combine)"};
107
108 cvar_t r_glsl = {CVAR_SAVE, "r_glsl", "1", "enables use of OpenGL 2.0 pixel shaders for lighting"};
109 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)"};
110 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
111 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
112 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
113 cvar_t r_glsl_postprocess = {CVAR_SAVE, "r_glsl_postprocess", "0", "use a GLSL postprocessing shader"};
114 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)"};
115 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)"};
116 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)"};
117 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)"};
118 cvar_t r_glsl_usegeneric = {CVAR_SAVE, "r_glsl_usegeneric", "1", "use shaders for rendering simple geometry (rather than conventional fixed-function rendering for this purpose)"};
119
120 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)"};
121 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
122 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"};
123 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
124 cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "how much water reflections shimmer"};
125
126 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "1", "enables animation smoothing on sprites"};
127 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
128 cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
129 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
130
131 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
132 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
133 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
134 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
135 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
136 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exagerated the glow is"};
137 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
138
139 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
140 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
141 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
142 cvar_t r_hdr_range = {CVAR_SAVE, "r_hdr_range", "4", "how much dynamic range to render bloom with (equivilant to multiplying r_bloom_brighten by this value and dividing r_bloom_colorscale by this value)"};
143
144 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"};
145
146 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"};
147
148 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
149
150 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
151 cvar_t r_batchmode = {0, "r_batchmode", "1", "selects method of rendering multiple surfaces with one driver call (values are 0, 1, 2, etc...)"};
152 cvar_t r_track_sprites = {CVAR_SAVE, "r_track_sprites", "1", "track SPR_LABEL* sprites by putting them as indicator at the screen border to rotate to"};
153 cvar_t r_track_sprites_flags = {CVAR_SAVE, "r_track_sprites_flags", "1", "1: Rotate sprites accodringly, 2: Make it a continuous rotation"};
154 cvar_t r_track_sprites_scalew = {CVAR_SAVE, "r_track_sprites_scalew", "1", "width scaling of tracked sprites"};
155 cvar_t r_track_sprites_scaleh = {CVAR_SAVE, "r_track_sprites_scaleh", "1", "height scaling of tracked sprites"};
156 cvar_t r_glsl_saturation = {CVAR_SAVE, "r_glsl_saturation", "1", "saturation multiplier (only working in glsl!)"};
157
158 extern cvar_t v_glslgamma;
159
160 extern qboolean v_flipped_state;
161
162 static struct r_bloomstate_s
163 {
164         qboolean enabled;
165         qboolean hdr;
166
167         int bloomwidth, bloomheight;
168
169         int screentexturewidth, screentextureheight;
170         rtexture_t *texture_screen; /// \note also used for motion blur if enabled!
171
172         int bloomtexturewidth, bloomtextureheight;
173         rtexture_t *texture_bloom;
174
175         // arrays for rendering the screen passes
176         float screentexcoord2f[8];
177         float bloomtexcoord2f[8];
178         float offsettexcoord2f[8];
179
180         r_viewport_t viewport;
181 }
182 r_bloomstate;
183
184 r_waterstate_t r_waterstate;
185
186 /// shadow volume bsp struct with automatically growing nodes buffer
187 svbsp_t r_svbsp;
188
189 rtexture_t *r_texture_blanknormalmap;
190 rtexture_t *r_texture_white;
191 rtexture_t *r_texture_grey128;
192 rtexture_t *r_texture_black;
193 rtexture_t *r_texture_notexture;
194 rtexture_t *r_texture_whitecube;
195 rtexture_t *r_texture_normalizationcube;
196 rtexture_t *r_texture_fogattenuation;
197 rtexture_t *r_texture_gammaramps;
198 unsigned int r_texture_gammaramps_serial;
199 //rtexture_t *r_texture_fogintensity;
200
201 unsigned int r_queries[MAX_OCCLUSION_QUERIES];
202 unsigned int r_numqueries;
203 unsigned int r_maxqueries;
204
205 typedef struct r_qwskincache_s
206 {
207         char name[MAX_QPATH];
208         skinframe_t *skinframe;
209 }
210 r_qwskincache_t;
211
212 static r_qwskincache_t *r_qwskincache;
213 static int r_qwskincache_size;
214
215 /// vertex coordinates for a quad that covers the screen exactly
216 const float r_screenvertex3f[12] =
217 {
218         0, 0, 0,
219         1, 0, 0,
220         1, 1, 0,
221         0, 1, 0
222 };
223
224 extern void R_DrawModelShadows(void);
225
226 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
227 {
228         int i;
229         for (i = 0;i < verts;i++)
230         {
231                 out[0] = in[0] * r;
232                 out[1] = in[1] * g;
233                 out[2] = in[2] * b;
234                 out[3] = in[3];
235                 in += 4;
236                 out += 4;
237         }
238 }
239
240 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
241 {
242         int i;
243         for (i = 0;i < verts;i++)
244         {
245                 out[0] = r;
246                 out[1] = g;
247                 out[2] = b;
248                 out[3] = a;
249                 out += 4;
250         }
251 }
252
253 // FIXME: move this to client?
254 void FOG_clear(void)
255 {
256         if (gamemode == GAME_NEHAHRA)
257         {
258                 Cvar_Set("gl_fogenable", "0");
259                 Cvar_Set("gl_fogdensity", "0.2");
260                 Cvar_Set("gl_fogred", "0.3");
261                 Cvar_Set("gl_foggreen", "0.3");
262                 Cvar_Set("gl_fogblue", "0.3");
263         }
264         r_refdef.fog_density = 0;
265         r_refdef.fog_red = 0;
266         r_refdef.fog_green = 0;
267         r_refdef.fog_blue = 0;
268         r_refdef.fog_alpha = 1;
269         r_refdef.fog_start = 0;
270         r_refdef.fog_end = 16384;
271         r_refdef.fog_height = 1<<30;
272         r_refdef.fog_fadedepth = 128;
273 }
274
275 static void R_BuildBlankTextures(void)
276 {
277         unsigned char data[4];
278         data[2] = 128; // normal X
279         data[1] = 128; // normal Y
280         data[0] = 255; // normal Z
281         data[3] = 128; // height
282         r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_PERSISTENT, NULL);
283         data[0] = 255;
284         data[1] = 255;
285         data[2] = 255;
286         data[3] = 255;
287         r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_PERSISTENT, NULL);
288         data[0] = 128;
289         data[1] = 128;
290         data[2] = 128;
291         data[3] = 255;
292         r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_PERSISTENT, NULL);
293         data[0] = 0;
294         data[1] = 0;
295         data[2] = 0;
296         data[3] = 255;
297         r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_PERSISTENT, NULL);
298 }
299
300 static void R_BuildNoTexture(void)
301 {
302         int x, y;
303         unsigned char pix[16][16][4];
304         // this makes a light grey/dark grey checkerboard texture
305         for (y = 0;y < 16;y++)
306         {
307                 for (x = 0;x < 16;x++)
308                 {
309                         if ((y < 8) ^ (x < 8))
310                         {
311                                 pix[y][x][0] = 128;
312                                 pix[y][x][1] = 128;
313                                 pix[y][x][2] = 128;
314                                 pix[y][x][3] = 255;
315                         }
316                         else
317                         {
318                                 pix[y][x][0] = 64;
319                                 pix[y][x][1] = 64;
320                                 pix[y][x][2] = 64;
321                                 pix[y][x][3] = 255;
322                         }
323                 }
324         }
325         r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, NULL);
326 }
327
328 static void R_BuildWhiteCube(void)
329 {
330         unsigned char data[6*1*1*4];
331         memset(data, 255, sizeof(data));
332         r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_PERSISTENT, NULL);
333 }
334
335 static void R_BuildNormalizationCube(void)
336 {
337         int x, y, side;
338         vec3_t v;
339         vec_t s, t, intensity;
340 #define NORMSIZE 64
341         unsigned char data[6][NORMSIZE][NORMSIZE][4];
342         for (side = 0;side < 6;side++)
343         {
344                 for (y = 0;y < NORMSIZE;y++)
345                 {
346                         for (x = 0;x < NORMSIZE;x++)
347                         {
348                                 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
349                                 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
350                                 switch(side)
351                                 {
352                                 default:
353                                 case 0:
354                                         v[0] = 1;
355                                         v[1] = -t;
356                                         v[2] = -s;
357                                         break;
358                                 case 1:
359                                         v[0] = -1;
360                                         v[1] = -t;
361                                         v[2] = s;
362                                         break;
363                                 case 2:
364                                         v[0] = s;
365                                         v[1] = 1;
366                                         v[2] = t;
367                                         break;
368                                 case 3:
369                                         v[0] = s;
370                                         v[1] = -1;
371                                         v[2] = -t;
372                                         break;
373                                 case 4:
374                                         v[0] = s;
375                                         v[1] = -t;
376                                         v[2] = 1;
377                                         break;
378                                 case 5:
379                                         v[0] = -s;
380                                         v[1] = -t;
381                                         v[2] = -1;
382                                         break;
383                                 }
384                                 intensity = 127.0f / sqrt(DotProduct(v, v));
385                                 data[side][y][x][2] = (unsigned char)(128.0f + intensity * v[0]);
386                                 data[side][y][x][1] = (unsigned char)(128.0f + intensity * v[1]);
387                                 data[side][y][x][0] = (unsigned char)(128.0f + intensity * v[2]);
388                                 data[side][y][x][3] = 255;
389                         }
390                 }
391         }
392         r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, &data[0][0][0][0], TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_PERSISTENT, NULL);
393 }
394
395 static void R_BuildFogTexture(void)
396 {
397         int x, b;
398 #define FOGWIDTH 256
399         unsigned char data1[FOGWIDTH][4];
400         //unsigned char data2[FOGWIDTH][4];
401         double d, r, alpha;
402
403         r_refdef.fogmasktable_start = r_refdef.fog_start;
404         r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
405         r_refdef.fogmasktable_range = r_refdef.fogrange;
406         r_refdef.fogmasktable_density = r_refdef.fog_density;
407
408         r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
409         for (x = 0;x < FOGMASKTABLEWIDTH;x++)
410         {
411                 d = (x * r - r_refdef.fogmasktable_start);
412                 if(developer.integer >= 100)
413                         Con_Printf("%f ", d);
414                 d = max(0, d);
415                 if (r_fog_exp2.integer)
416                         alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
417                 else
418                         alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
419                 if(developer.integer >= 100)
420                         Con_Printf(" : %f ", alpha);
421                 alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
422                 if(developer.integer >= 100)
423                         Con_Printf(" = %f\n", alpha);
424                 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
425         }
426
427         for (x = 0;x < FOGWIDTH;x++)
428         {
429                 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
430                 data1[x][0] = b;
431                 data1[x][1] = b;
432                 data1[x][2] = b;
433                 data1[x][3] = 255;
434                 //data2[x][0] = 255 - b;
435                 //data2[x][1] = 255 - b;
436                 //data2[x][2] = 255 - b;
437                 //data2[x][3] = 255;
438         }
439         if (r_texture_fogattenuation)
440         {
441                 R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, FOGWIDTH, 1);
442                 //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, FOGWIDTH, 1);
443         }
444         else
445         {
446                 r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, NULL);
447                 //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
448         }
449 }
450
451 static const char *builtinshaderstring =
452 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
453 "// written by Forest 'LordHavoc' Hale\n"
454 "\n"
455 "// enable various extensions depending on permutation:\n"
456 "\n"
457 "#ifdef USESHADOWMAPRECT\n"
458 "# extension GL_ARB_texture_rectangle : enable\n"
459 "#endif\n"
460 "\n"
461 "#ifdef USESHADOWMAP2D\n"
462 "# ifdef GL_EXT_gpu_shader4\n"
463 "#   extension GL_EXT_gpu_shader4 : enable\n"
464 "# endif\n"
465 "# ifdef GL_ARB_texture_gather\n"
466 "#   extension GL_ARB_texture_gather : enable\n"
467 "# else\n"
468 "#   ifdef GL_AMD_texture_texture4\n"
469 "#     extension GL_AMD_texture_texture4 : enable\n"
470 "#   endif\n"
471 "# endif\n"
472 "#endif\n"
473 "\n"
474 "#ifdef USESHADOWMAPCUBE\n"
475 "# extension GL_EXT_gpu_shader4 : enable\n"
476 "#endif\n"
477 "\n"
478 "#ifdef USESHADOWSAMPLER\n"
479 "# extension GL_ARB_shadow : enable\n"
480 "#endif\n"
481 "\n"
482 "// common definitions between vertex shader and fragment shader:\n"
483 "\n"
484 "//#ifdef __GLSL_CG_DATA_TYPES\n"
485 "//# define myhalf half\n"
486 "//# define myhalf2 half2\n"
487 "//# define myhalf3half3\n"
488 "//# define myhalf4 half4\n"
489 "//#else\n"
490 "# define myhalf float\n"
491 "# define myhalf2 vec2\n"
492 "# define myhalf3 vec3\n"
493 "# define myhalf4 vec4\n"
494 "//#endif\n"
495 "\n"
496 "#ifdef USEFOGINSIDE\n"
497 "# define USEFOG\n"
498 "#else\n"
499 "# ifdef USEFOGOUTSIDE\n"
500 "#  define USEFOG\n"
501 "# endif\n"
502 "#endif\n"
503 "\n"
504 "#ifdef MODE_DEPTH_OR_SHADOW\n"
505 "\n"
506 "# ifdef VERTEX_SHADER\n"
507 "void main(void)\n"
508 "{\n"
509 "       gl_Position = ftransform();\n"
510 "}\n"
511 "# endif\n"
512 "\n"
513 "#else\n"
514 "#ifdef MODE_SHOWDEPTH\n"
515 "# ifdef VERTEX_SHADER\n"
516 "void main(void)\n"
517 "{\n"
518 "       gl_Position = ftransform();\n"
519 "       gl_FrontColor = vec4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
520 "}\n"
521 "# endif\n"
522 "# ifdef FRAGMENT_SHADER\n"
523 "void main(void)\n"
524 "{\n"
525 "       gl_FragColor = gl_Color;\n"
526 "}\n"
527 "# endif\n"
528 "\n"
529 "#else // !MODE_SHOWDEPTH\n"
530 "\n"
531 "#ifdef MODE_POSTPROCESS\n"
532 "# ifdef VERTEX_SHADER\n"
533 "void main(void)\n"
534 "{\n"
535 "       gl_FrontColor = gl_Color;\n"
536 "       gl_Position = ftransform();\n"
537 "       gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;\n"
538 "#ifdef USEBLOOM\n"
539 "       gl_TexCoord[1] = gl_TextureMatrix[1] * gl_MultiTexCoord1;\n"
540 "#endif\n"
541 "}\n"
542 "# endif\n"
543 "# ifdef FRAGMENT_SHADER\n"
544 "\n"
545 "uniform sampler2D Texture_First;\n"
546 "#ifdef USEBLOOM\n"
547 "uniform sampler2D Texture_Second;\n"
548 "#endif\n"
549 "#ifdef USEGAMMARAMPS\n"
550 "uniform sampler2D Texture_GammaRamps;\n"
551 "#endif\n"
552 "#ifdef USESATURATION\n"
553 "uniform float Saturation;\n"
554 "#endif\n"
555 "#ifdef USEVIEWTINT\n"
556 "uniform vec4 TintColor;\n"
557 "#endif\n"
558 "//uncomment these if you want to use them:\n"
559 "uniform vec4 UserVec1;\n"
560 "// uniform vec4 UserVec2;\n"
561 "// uniform vec4 UserVec3;\n"
562 "// uniform vec4 UserVec4;\n"
563 "// uniform float ClientTime;\n"
564 "uniform vec2 PixelSize;\n"
565 "void main(void)\n"
566 "{\n"
567 "       gl_FragColor = texture2D(Texture_First, gl_TexCoord[0].xy);\n"
568 "#ifdef USEBLOOM\n"
569 "       gl_FragColor += texture2D(Texture_Second, gl_TexCoord[1].xy);\n"
570 "#endif\n"
571 "#ifdef USEVIEWTINT\n"
572 "       gl_FragColor = mix(gl_FragColor, TintColor, TintColor.a);\n"
573 "#endif\n"
574 "\n"
575 "#ifdef USEPOSTPROCESSING\n"
576 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
577 "// this code does a blur with the radius specified in the first component of r_glsl_postprocess_uservec1 and blends it using the second component\n"
578 "       gl_FragColor += texture2D(Texture_First, gl_TexCoord[0].xy + PixelSize*UserVec1.x*vec2(-0.987688, -0.156434)) * UserVec1.y;\n"
579 "       gl_FragColor += texture2D(Texture_First, gl_TexCoord[0].xy + PixelSize*UserVec1.x*vec2(-0.156434, -0.891007)) * UserVec1.y;\n"
580 "       gl_FragColor += texture2D(Texture_First, gl_TexCoord[0].xy + PixelSize*UserVec1.x*vec2( 0.891007, -0.453990)) * UserVec1.y;\n"
581 "       gl_FragColor += texture2D(Texture_First, gl_TexCoord[0].xy + PixelSize*UserVec1.x*vec2( 0.707107,  0.707107)) * UserVec1.y;\n"
582 "       gl_FragColor += texture2D(Texture_First, gl_TexCoord[0].xy + PixelSize*UserVec1.x*vec2(-0.453990,  0.891007)) * UserVec1.y;\n"
583 "       gl_FragColor /= (1 + 5 * UserVec1.y);\n"
584 "#endif\n"
585 "\n"
586 "#ifdef USESATURATION\n"
587 "       //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
588 "       myhalf y = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));\n"
589 "       //gl_FragColor = vec3(y) + (gl_FragColor.rgb - vec3(y)) * Saturation;\n"
590 "       gl_FragColor.rgb = mix(vec3(y), gl_FragColor.rgb, Saturation);\n"
591 "#endif\n"
592 "\n"
593 "#ifdef USEGAMMARAMPS\n"
594 "       gl_FragColor.r = texture2D(Texture_GammaRamps, vec2(gl_FragColor.r, 0)).r;\n"
595 "       gl_FragColor.g = texture2D(Texture_GammaRamps, vec2(gl_FragColor.g, 0)).g;\n"
596 "       gl_FragColor.b = texture2D(Texture_GammaRamps, vec2(gl_FragColor.b, 0)).b;\n"
597 "#endif\n"
598 "}\n"
599 "# endif\n"
600 "\n"
601 "\n"
602 "#else\n"
603 "#ifdef MODE_GENERIC\n"
604 "# ifdef VERTEX_SHADER\n"
605 "void main(void)\n"
606 "{\n"
607 "       gl_FrontColor = gl_Color;\n"
608 "#  ifdef USEDIFFUSE\n"
609 "       gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;\n"
610 "#  endif\n"
611 "#  ifdef USESPECULAR\n"
612 "       gl_TexCoord[1] = gl_TextureMatrix[1] * gl_MultiTexCoord1;\n"
613 "#  endif\n"
614 "       gl_Position = ftransform();\n"
615 "}\n"
616 "# endif\n"
617 "# ifdef FRAGMENT_SHADER\n"
618 "\n"
619 "#  ifdef USEDIFFUSE\n"
620 "uniform sampler2D Texture_First;\n"
621 "#  endif\n"
622 "#  ifdef USESPECULAR\n"
623 "uniform sampler2D Texture_Second;\n"
624 "#  endif\n"
625 "\n"
626 "void main(void)\n"
627 "{\n"
628 "       gl_FragColor = gl_Color;\n"
629 "#  ifdef USEDIFFUSE\n"
630 "       gl_FragColor *= texture2D(Texture_First, gl_TexCoord[0].xy);\n"
631 "#  endif\n"
632 "\n"
633 "#  ifdef USESPECULAR\n"
634 "       vec4 tex2 = texture2D(Texture_Second, gl_TexCoord[1].xy);\n"
635 "#  endif\n"
636 "#  ifdef USECOLORMAPPING\n"
637 "       gl_FragColor *= tex2;\n"
638 "#  endif\n"
639 "#  ifdef USEGLOW\n"
640 "       gl_FragColor += tex2;\n"
641 "#  endif\n"
642 "#  ifdef USEVERTEXTEXTUREBLEND\n"
643 "       gl_FragColor = mix(gl_FragColor, tex2, tex2.a);\n"
644 "#  endif\n"
645 "}\n"
646 "# endif\n"
647 "\n"
648 "#else // !MODE_GENERIC\n"
649 "#ifdef MODE_BLOOMBLUR\n"
650 "# ifdef VERTEX_SHADER\n"
651 "void main(void)\n"
652 "{\n"
653 "       gl_FrontColor = gl_Color;\n"
654 "       gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;\n"
655 "       gl_Position = ftransform();\n"
656 "}\n"
657 "# endif\n"
658 "# ifdef FRAGMENT_SHADER\n"
659 "\n"
660 "uniform sampler2D Texture_First;\n"
661 "uniform vec4 BloomBlur_Parameters;\n"
662 "\n"
663 "void main(void)\n"
664 "{\n"
665 "       int i;\n"
666 "       vec2 tc = gl_TexCoord[0].xy;\n"
667 "       vec3 color = texture2D(Texture_First, tc).rgb;\n"
668 "       tc += BloomBlur_Parameters.xy;\n"
669 "       for (i = 1;i < SAMPLES;i++)\n"
670 "       {\n"
671 "               color += texture2D(Texture_First, tc).rgb;\n"
672 "               tc += BloomBlur_Parameters.xy;\n"
673 "       }\n"
674 "       gl_FragColor = vec4(color * BloomBlur_Parameters.z + vec3(BloomBlur_Parameters.w), 1);\n"
675 "}\n"
676 "# endif\n"
677 "\n"
678 "#else // !MODE_BLOOMBLUR\n"
679 "\n"
680 "varying vec2 TexCoord;\n"
681 "#ifdef USEVERTEXTEXTUREBLEND\n"
682 "varying vec2 TexCoord2;\n"
683 "#endif\n"
684 "varying vec2 TexCoordLightmap;\n"
685 "\n"
686 "#ifdef MODE_LIGHTSOURCE\n"
687 "varying vec3 CubeVector;\n"
688 "#endif\n"
689 "\n"
690 "#ifdef MODE_LIGHTSOURCE\n"
691 "varying vec3 LightVector;\n"
692 "#endif\n"
693 "#ifdef MODE_LIGHTDIRECTION\n"
694 "varying vec3 LightVector;\n"
695 "#endif\n"
696 "\n"
697 "varying vec3 EyeVector;\n"
698 "#ifdef USEFOG\n"
699 "varying vec3 EyeVectorModelSpace;\n"
700 "varying float FogPlaneVertexDist;\n"
701 "#endif\n"
702 "\n"
703 "varying vec3 VectorS; // direction of S texcoord (sometimes crudely called tangent)\n"
704 "varying vec3 VectorT; // direction of T texcoord (sometimes crudely called binormal)\n"
705 "varying vec3 VectorR; // direction of R texcoord (surface normal)\n"
706 "\n"
707 "#ifdef MODE_WATER\n"
708 "varying vec4 ModelViewProjectionPosition;\n"
709 "#endif\n"
710 "#ifdef MODE_REFRACTION\n"
711 "varying vec4 ModelViewProjectionPosition;\n"
712 "#endif\n"
713 "#ifdef USEREFLECTION\n"
714 "varying vec4 ModelViewProjectionPosition;\n"
715 "#endif\n"
716 "\n"
717 "\n"
718 "\n"
719 "\n"
720 "\n"
721 "// vertex shader specific:\n"
722 "#ifdef VERTEX_SHADER\n"
723 "\n"
724 "uniform vec3 LightPosition;\n"
725 "uniform vec3 EyePosition;\n"
726 "uniform vec3 LightDir;\n"
727 "uniform vec4 FogPlane;\n"
728 "\n"
729 "// TODO: get rid of tangentt (texcoord2) and use a crossproduct to regenerate it from tangents (texcoord1) and normal (texcoord3), this would require sending a 4 component texcoord1 with W as 1 or -1 according to which side the texcoord2 should be on\n"
730 "\n"
731 "void main(void)\n"
732 "{\n"
733 "       gl_FrontColor = gl_Color;\n"
734 "       // copy the surface texcoord\n"
735 "       TexCoord = vec2(gl_TextureMatrix[0] * gl_MultiTexCoord0);\n"
736 "#ifdef USEVERTEXTEXTUREBLEND\n"
737 "       TexCoord2 = vec2(gl_TextureMatrix[1] * gl_MultiTexCoord0);\n"
738 "#endif\n"
739 "#ifndef MODE_LIGHTSOURCE\n"
740 "# ifndef MODE_LIGHTDIRECTION\n"
741 "       TexCoordLightmap = vec2(gl_MultiTexCoord4);\n"
742 "# endif\n"
743 "#endif\n"
744 "\n"
745 "#ifdef MODE_LIGHTSOURCE\n"
746 "       // transform vertex position into light attenuation/cubemap space\n"
747 "       // (-1 to +1 across the light box)\n"
748 "       CubeVector = vec3(gl_TextureMatrix[3] * gl_Vertex);\n"
749 "\n"
750 "       // transform unnormalized light direction into tangent space\n"
751 "       // (we use unnormalized to ensure that it interpolates correctly and then\n"
752 "       //  normalize it per pixel)\n"
753 "       vec3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
754 "       LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
755 "       LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
756 "       LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
757 "#endif\n"
758 "\n"
759 "#ifdef MODE_LIGHTDIRECTION\n"
760 "       LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
761 "       LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
762 "       LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
763 "#endif\n"
764 "\n"
765 "       // transform unnormalized eye direction into tangent space\n"
766 "#ifndef USEFOG\n"
767 "       vec3 EyeVectorModelSpace;\n"
768 "#endif\n"
769 "       EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
770 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
771 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
772 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
773 "\n"
774 "#ifdef USEFOG\n"
775 "       FogPlaneVertexDist = dot(FogPlane, gl_Vertex);\n"
776 "#endif\n"
777 "\n"
778 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
779 "       VectorS = gl_MultiTexCoord1.xyz;\n"
780 "       VectorT = gl_MultiTexCoord2.xyz;\n"
781 "       VectorR = gl_MultiTexCoord3.xyz;\n"
782 "#endif\n"
783 "\n"
784 "//#if defined(MODE_WATER) || defined(MODE_REFRACTION) || defined(USEREFLECTION)\n"
785 "//     ModelViewProjectionPosition = gl_Vertex * gl_ModelViewProjectionMatrix;\n"
786 "//     //ModelViewProjectionPosition_svector = (gl_Vertex + vec4(gl_MultiTexCoord1.xyz, 0)) * gl_ModelViewProjectionMatrix - ModelViewProjectionPosition;\n"
787 "//     //ModelViewProjectionPosition_tvector = (gl_Vertex + vec4(gl_MultiTexCoord2.xyz, 0)) * gl_ModelViewProjectionMatrix - ModelViewProjectionPosition;\n"
788 "//#endif\n"
789 "\n"
790 "// transform vertex to camera space, using ftransform to match non-VS\n"
791 "       // rendering\n"
792 "       gl_Position = ftransform();\n"
793 "\n"
794 "#ifdef MODE_WATER\n"
795 "       ModelViewProjectionPosition = gl_Position;\n"
796 "#endif\n"
797 "#ifdef MODE_REFRACTION\n"
798 "       ModelViewProjectionPosition = gl_Position;\n"
799 "#endif\n"
800 "#ifdef USEREFLECTION\n"
801 "       ModelViewProjectionPosition = gl_Position;\n"
802 "#endif\n"
803 "}\n"
804 "\n"
805 "#endif // VERTEX_SHADER\n"
806 "\n"
807 "\n"
808 "\n"
809 "\n"
810 "// fragment shader specific:\n"
811 "#ifdef FRAGMENT_SHADER\n"
812 "\n"
813 "// 13 textures, we can only use up to 16 on DX9-class hardware\n"
814 "uniform sampler2D Texture_Normal;\n"
815 "uniform sampler2D Texture_Color;\n"
816 "uniform sampler2D Texture_Gloss;\n"
817 "uniform sampler2D Texture_Glow;\n"
818 "uniform sampler2D Texture_SecondaryNormal;\n"
819 "uniform sampler2D Texture_SecondaryColor;\n"
820 "uniform sampler2D Texture_SecondaryGloss;\n"
821 "uniform sampler2D Texture_SecondaryGlow;\n"
822 "uniform sampler2D Texture_Pants;\n"
823 "uniform sampler2D Texture_Shirt;\n"
824 "uniform sampler2D Texture_FogMask;\n"
825 "uniform sampler2D Texture_Lightmap;\n"
826 "uniform sampler2D Texture_Deluxemap;\n"
827 "uniform sampler2D Texture_Refraction;\n"
828 "uniform sampler2D Texture_Reflection;\n"
829 "uniform sampler2D Texture_Attenuation;\n"
830 "uniform samplerCube Texture_Cube;\n"
831 "\n"
832 "#define showshadowmap 0\n"
833 "\n"
834 "#ifdef USESHADOWMAPRECT\n"
835 "# ifdef USESHADOWSAMPLER\n"
836 "uniform sampler2DRectShadow Texture_ShadowMapRect;\n"
837 "# else\n"
838 "uniform sampler2DRect Texture_ShadowMapRect;\n"
839 "# endif\n"
840 "#endif\n"
841 "\n"
842 "#ifdef USESHADOWMAP2D\n"
843 "# ifdef USESHADOWSAMPLER\n"
844 "uniform sampler2DShadow Texture_ShadowMap2D;\n"
845 "# else\n"
846 "uniform sampler2D Texture_ShadowMap2D;\n"
847 "# endif\n"
848 "#endif\n"
849 "\n"
850 "#ifdef USESHADOWMAPVSDCT\n"
851 "uniform samplerCube Texture_CubeProjection;\n"
852 "#endif\n"
853 "\n"
854 "#ifdef USESHADOWMAPCUBE\n"
855 "# ifdef USESHADOWSAMPLER\n"
856 "uniform samplerCubeShadow Texture_ShadowMapCube;\n"
857 "# else\n"
858 "uniform samplerCube Texture_ShadowMapCube;\n"
859 "# endif\n"
860 "#endif\n"
861 "\n"
862 "uniform myhalf3 LightColor;\n"
863 "uniform myhalf3 AmbientColor;\n"
864 "uniform myhalf3 DiffuseColor;\n"
865 "uniform myhalf3 SpecularColor;\n"
866 "uniform myhalf3 Color_Pants;\n"
867 "uniform myhalf3 Color_Shirt;\n"
868 "uniform myhalf3 FogColor;\n"
869 "\n"
870 "uniform myhalf4 TintColor;\n"
871 "\n"
872 "\n"
873 "//#ifdef MODE_WATER\n"
874 "uniform vec4 DistortScaleRefractReflect;\n"
875 "uniform vec4 ScreenScaleRefractReflect;\n"
876 "uniform vec4 ScreenCenterRefractReflect;\n"
877 "uniform myhalf4 RefractColor;\n"
878 "uniform myhalf4 ReflectColor;\n"
879 "uniform myhalf ReflectFactor;\n"
880 "uniform myhalf ReflectOffset;\n"
881 "//#else\n"
882 "//# ifdef MODE_REFRACTION\n"
883 "//uniform vec4 DistortScaleRefractReflect;\n"
884 "//uniform vec4 ScreenScaleRefractReflect;\n"
885 "//uniform vec4 ScreenCenterRefractReflect;\n"
886 "//uniform myhalf4 RefractColor;\n"
887 "//#  ifdef USEREFLECTION\n"
888 "//uniform myhalf4 ReflectColor;\n"
889 "//#  endif\n"
890 "//# else\n"
891 "//#  ifdef USEREFLECTION\n"
892 "//uniform vec4 DistortScaleRefractReflect;\n"
893 "//uniform vec4 ScreenScaleRefractReflect;\n"
894 "//uniform vec4 ScreenCenterRefractReflect;\n"
895 "//uniform myhalf4 ReflectColor;\n"
896 "//#  endif\n"
897 "//# endif\n"
898 "//#endif\n"
899 "\n"
900 "uniform myhalf3 GlowColor;\n"
901 "uniform myhalf SceneBrightness;\n"
902 "\n"
903 "uniform float OffsetMapping_Scale;\n"
904 "uniform float OffsetMapping_Bias;\n"
905 "uniform float FogRangeRecip;\n"
906 "uniform float FogPlaneViewDist;\n"
907 "uniform float FogHeightFade;\n"
908 "\n"
909 "uniform myhalf AmbientScale;\n"
910 "uniform myhalf DiffuseScale;\n"
911 "uniform myhalf SpecularScale;\n"
912 "uniform myhalf SpecularPower;\n"
913 "\n"
914 "#ifdef USEOFFSETMAPPING\n"
915 "vec2 OffsetMapping(vec2 TexCoord)\n"
916 "{\n"
917 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
918 "       // 14 sample relief mapping: linear search and then binary search\n"
919 "       // this basically steps forward a small amount repeatedly until it finds\n"
920 "       // itself inside solid, then jitters forward and back using decreasing\n"
921 "       // amounts to find the impact\n"
922 "       //vec3 OffsetVector = vec3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1), -1);\n"
923 "       //vec3 OffsetVector = vec3(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
924 "       vec3 OffsetVector = vec3(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
925 "       vec3 RT = vec3(TexCoord, 1);\n"
926 "       OffsetVector *= 0.1;\n"
927 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
928 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
929 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
930 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
931 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
932 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
933 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
934 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
935 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
936 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z)          - 0.5);\n"
937 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.5    - 0.25);\n"
938 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.25   - 0.125);\n"
939 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.125  - 0.0625);\n"
940 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
941 "       return RT.xy;\n"
942 "#else\n"
943 "       // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
944 "       // this basically moves forward the full distance, and then backs up based\n"
945 "       // on height of samples\n"
946 "       //vec2 OffsetVector = vec2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1));\n"
947 "       //vec2 OffsetVector = vec2(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1));\n"
948 "       vec2 OffsetVector = vec2(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1));\n"
949 "       TexCoord += OffsetVector;\n"
950 "       OffsetVector *= 0.333;\n"
951 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
952 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
953 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
954 "       return TexCoord;\n"
955 "#endif\n"
956 "}\n"
957 "#endif // USEOFFSETMAPPING\n"
958 "\n"
959 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
960 "uniform vec2 ShadowMap_TextureScale;\n"
961 "uniform vec4 ShadowMap_Parameters;\n"
962 "#endif\n"
963 "\n"
964 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
965 "vec3 GetShadowMapTC2D(vec3 dir)\n"
966 "{\n"
967 "       vec3 adir = abs(dir);\n"
968 "# ifndef USESHADOWMAPVSDCT\n"
969 "       vec2 tc;\n"
970 "       vec2 offset;\n"
971 "       float ma;\n"
972 "       if (adir.x > adir.y)\n"
973 "       {\n"
974 "               if (adir.x > adir.z) // X\n"
975 "               {\n"
976 "                       ma = adir.x;\n"
977 "                       tc = dir.zy;\n"
978 "                       offset = vec2(mix(0.5, 1.5, dir.x < 0.0), 0.5);\n"
979 "               }\n"
980 "               else // Z\n"
981 "               {\n"
982 "                       ma = adir.z;\n"
983 "                       tc = dir.xy;\n"
984 "                       offset = vec2(mix(0.5, 1.5, dir.z < 0.0), 2.5);\n"
985 "               }\n"
986 "       }\n"
987 "       else\n"
988 "       {\n"
989 "               if (adir.y > adir.z) // Y\n"
990 "               {\n"
991 "                       ma = adir.y;\n"
992 "                       tc = dir.xz;\n"
993 "                       offset = vec2(mix(0.5, 1.5, dir.y < 0.0), 1.5);\n"
994 "               }\n"
995 "               else // Z\n"
996 "               {\n"
997 "                       ma = adir.z;\n"
998 "                       tc = dir.xy;\n"
999 "                       offset = vec2(mix(0.5, 1.5, dir.z < 0.0), 2.5);\n"
1000 "               }\n"
1001 "       }\n"
1002 "\n"
1003 "       vec3 stc = vec3(tc * ShadowMap_Parameters.x, ShadowMap_Parameters.w) / ma;\n"
1004 "       stc.xy += offset * ShadowMap_Parameters.y;\n"
1005 "       stc.z += ShadowMap_Parameters.z;\n"
1006 "#  if showshadowmap\n"
1007 "       stc.xy *= ShadowMap_TextureScale;\n"
1008 "#  endif\n"
1009 "       return stc;\n"
1010 "# else\n"
1011 "       vec4 proj = textureCube(Texture_CubeProjection, dir);\n"
1012 "       float ma = max(max(adir.x, adir.y), adir.z);\n"
1013 "       vec3 stc = vec3(mix(dir.xy, dir.zz, proj.xy) * ShadowMap_Parameters.x, ShadowMap_Parameters.w) / ma;\n"
1014 "       stc.xy += proj.zw * ShadowMap_Parameters.y;\n"
1015 "       stc.z += ShadowMap_Parameters.z;\n"
1016 "#  if showshadowmap\n"
1017 "       stc.xy *= ShadowMap_TextureScale;\n"
1018 "#  endif\n"
1019 "       return stc;\n"
1020 "# endif\n"
1021 "}\n"
1022 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1023 "\n"
1024 "#ifdef USESHADOWMAPCUBE\n"
1025 "vec4 GetShadowMapTCCube(vec3 dir)\n"
1026 "{\n"
1027 "    vec3 adir = abs(dir);\n"
1028 "    return vec4(dir, ShadowMap_Parameters.z + ShadowMap_Parameters.w / max(max(adir.x, adir.y), adir.z));\n"
1029 "}\n"
1030 "#endif\n"
1031 "\n"
1032 "#if !showshadowmap\n"
1033 "# ifdef USESHADOWMAPRECT\n"
1034 "float ShadowMapCompare(vec3 dir)\n"
1035 "{\n"
1036 "       vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1037 "       float f;\n"
1038 "#  ifdef USESHADOWSAMPLER\n"
1039 "\n"
1040 "#    ifdef USESHADOWMAPPCF\n"
1041 "#      define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + vec3(x, y, 0.0)).r\n"
1042 "    f = dot(vec4(0.25), vec4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
1043 "#    else\n"
1044 "    f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
1045 "#    endif\n"
1046 "\n"
1047 "#  else\n"
1048 "\n"
1049 "#    ifdef USESHADOWMAPPCF\n"
1050 "#      if USESHADOWMAPPCF > 1\n"
1051 "#        define texval(x, y) texture2DRect(Texture_ShadowMapRect, center + vec2(x, y)).r\n"
1052 "    vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1053 "    vec4 row1 = step(shadowmaptc.z, vec4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
1054 "    vec4 row2 = step(shadowmaptc.z, vec4(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0), texval( 2.0,  0.0)));\n"
1055 "    vec4 row3 = step(shadowmaptc.z, vec4(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0), texval( 2.0,  1.0)));\n"
1056 "    vec4 row4 = step(shadowmaptc.z, vec4(texval(-1.0,  2.0), texval( 0.0,  2.0), texval( 1.0,  2.0), texval( 2.0,  2.0)));\n"
1057 "    vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1058 "    f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1059 "#      else\n"
1060 "#        define texval(x, y) texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy + vec2(x, y)).r\n"
1061 "    vec2 offset = fract(shadowmaptc.xy);\n"
1062 "    vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1063 "    vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0)));\n"
1064 "    vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0)));\n"
1065 "    vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1066 "    f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1067 "#      endif\n"
1068 "#    else\n"
1069 "    f = step(shadowmaptc.z, texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
1070 "#    endif\n"
1071 "\n"
1072 "#  endif\n"
1073 "       return f;\n"
1074 "}\n"
1075 "# endif\n"
1076 "\n"
1077 "# ifdef USESHADOWMAP2D\n"
1078 "float ShadowMapCompare(vec3 dir)\n"
1079 "{\n"
1080 "    vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1081 "    float f;\n"
1082 "\n"
1083 "#  ifdef USESHADOWSAMPLER\n"
1084 "#    ifdef USESHADOWMAPPCF\n"
1085 "#      define texval(x, y) shadow2D(Texture_ShadowMap2D, vec3(center + vec2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r  \n"
1086 "    vec2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
1087 "    f = dot(vec4(0.25), vec4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
1088 "#    else\n"
1089 "    f = shadow2D(Texture_ShadowMap2D, vec3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
1090 "#    endif\n"
1091 "#  else\n"
1092 "#    ifdef USESHADOWMAPPCF\n"
1093 "#     if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
1094 "#      ifdef GL_ARB_texture_gather\n"
1095 "#        define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec(x, y))\n"
1096 "#      else\n"
1097 "#        define texval(x, y) texture4(Texture_ShadowMap2D, center + vec2(x,y)*ShadowMap_TextureScale)\n"
1098 "#      endif\n"
1099 "    vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1100 "    center *= ShadowMap_TextureScale;\n"
1101 "    vec4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
1102 "    vec4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
1103 "    vec4 group3 = step(shadowmaptc.z, texval(-1.0,  1.0));\n"
1104 "    vec4 group4 = step(shadowmaptc.z, texval( 1.0,  1.0));\n"
1105 "    vec4 cols = vec4(group1.rg, group2.rg) + vec4(group3.ab, group4.ab) +\n"
1106 "                mix(vec4(group1.ab, group2.ab), vec4(group3.rg, group4.rg), offset.y);\n"
1107 "    f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1108 "#     else\n"
1109 "#      ifdef GL_EXT_gpu_shader4\n"
1110 "#        define texval(x, y) texture2DOffset(Texture_ShadowMap2D, center, ivec2(x, y)).r\n"
1111 "#      else\n"
1112 "#        define texval(x, y) texture2D(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale).r  \n"
1113 "#      endif\n"
1114 "#      if USESHADOWMAPPCF > 1\n"
1115 "    vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1116 "    center *= ShadowMap_TextureScale;\n"
1117 "    vec4 row1 = step(shadowmaptc.z, vec4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
1118 "    vec4 row2 = step(shadowmaptc.z, vec4(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0), texval( 2.0,  0.0)));\n"
1119 "    vec4 row3 = step(shadowmaptc.z, vec4(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0), texval( 2.0,  1.0)));\n"
1120 "    vec4 row4 = step(shadowmaptc.z, vec4(texval(-1.0,  2.0), texval( 0.0,  2.0), texval( 1.0,  2.0), texval( 2.0,  2.0)));\n"
1121 "    vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1122 "    f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1123 "#      else\n"
1124 "    vec2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = fract(shadowmaptc.xy);\n"
1125 "    vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1126 "    vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0)));\n"
1127 "    vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0)));\n"
1128 "    vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1129 "    f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1130 "#      endif\n"
1131 "#     endif\n"
1132 "#    else\n"
1133 "    f = step(shadowmaptc.z, texture2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
1134 "#    endif\n"
1135 "#  endif\n"
1136 "    return f;\n"
1137 "}\n"
1138 "# endif\n"
1139 "\n"
1140 "# ifdef USESHADOWMAPCUBE\n"
1141 "float ShadowMapCompare(vec3 dir)\n"
1142 "{\n"
1143 "    // apply depth texture cubemap as light filter\n"
1144 "    vec4 shadowmaptc = GetShadowMapTCCube(dir);\n"
1145 "    float f;\n"
1146 "#  ifdef USESHADOWSAMPLER\n"
1147 "    f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
1148 "#  else\n"
1149 "    f = step(shadowmaptc.w, textureCube(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
1150 "#  endif\n"
1151 "    return f;\n"
1152 "}\n"
1153 "# endif\n"
1154 "#endif\n"
1155 "\n"
1156 "#ifdef MODE_WATER\n"
1157 "\n"
1158 "// water pass\n"
1159 "void main(void)\n"
1160 "{\n"
1161 "#ifdef USEOFFSETMAPPING\n"
1162 "       // apply offsetmapping\n"
1163 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1164 "#define TexCoord TexCoordOffset\n"
1165 "#endif\n"
1166 "\n"
1167 "       vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
1168 "       //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
1169 "       vec4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
1170 "       vec4 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xyxy * DistortScaleRefractReflect;\n"
1171 "       // FIXME temporary hack to detect the case that the reflection\n"
1172 "       // gets blackened at edges due to leaving the area that contains actual\n"
1173 "       // content.\n"
1174 "       // Remove this 'ack once we have a better way to stop this thing from\n"
1175 "       // 'appening.\n"
1176 "       float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, 0.01)).rgb) / 0.05);\n"
1177 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, -0.01)).rgb) / 0.05);\n"
1178 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
1179 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
1180 "       ScreenTexCoord.xy = mix(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
1181 "       f       = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, 0.01)).rgb) / 0.05);\n"
1182 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, -0.01)).rgb) / 0.05);\n"
1183 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
1184 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
1185 "       ScreenTexCoord.zw = mix(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
1186 "       float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
1187 "       gl_FragColor = mix(texture2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, texture2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
1188 "}\n"
1189 "\n"
1190 "#else // !MODE_WATER\n"
1191 "#ifdef MODE_REFRACTION\n"
1192 "\n"
1193 "// refraction pass\n"
1194 "void main(void)\n"
1195 "{\n"
1196 "#ifdef USEOFFSETMAPPING\n"
1197 "       // apply offsetmapping\n"
1198 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1199 "#define TexCoord TexCoordOffset\n"
1200 "#endif\n"
1201 "\n"
1202 "       vec2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
1203 "       //vec2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
1204 "       vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
1205 "       vec2 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
1206 "       // FIXME temporary hack to detect the case that the reflection\n"
1207 "       // gets blackened at edges due to leaving the area that contains actual\n"
1208 "       // content.\n"
1209 "       // Remove this 'ack once we have a better way to stop this thing from\n"
1210 "       // 'appening.\n"
1211 "       float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
1212 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
1213 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
1214 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
1215 "       ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
1216 "       gl_FragColor = texture2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
1217 "}\n"
1218 "\n"
1219 "#else // !MODE_REFRACTION\n"
1220 "void main(void)\n"
1221 "{\n"
1222 "#ifdef USEOFFSETMAPPING\n"
1223 "       // apply offsetmapping\n"
1224 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1225 "#define TexCoord TexCoordOffset\n"
1226 "#endif\n"
1227 "\n"
1228 "       // combine the diffuse textures (base, pants, shirt)\n"
1229 "       myhalf4 color = myhalf4(texture2D(Texture_Color, TexCoord));\n"
1230 "#ifdef USECOLORMAPPING\n"
1231 "       color.rgb += myhalf3(texture2D(Texture_Pants, TexCoord)) * Color_Pants + myhalf3(texture2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
1232 "#endif\n"
1233 "#ifdef USEVERTEXTEXTUREBLEND\n"
1234 "       myhalf terrainblend = clamp(myhalf(gl_Color.a) * color.a * 2.0 - 0.5, myhalf(0.0), myhalf(1.0));\n"
1235 "       //myhalf terrainblend = min(myhalf(gl_Color.a) * color.a * 2.0, myhalf(1.0));\n"
1236 "       //myhalf terrainblend = myhalf(gl_Color.a) * color.a > 0.5;\n"
1237 "       color.rgb = mix(myhalf3(texture2D(Texture_SecondaryColor, TexCoord2)), color.rgb, terrainblend);\n"
1238 "       color.a = 1.0;\n"
1239 "       //color = mix(myhalf4(1, 0, 0, 1), color, terrainblend);\n"
1240 "#endif\n"
1241 "\n"
1242 "#ifdef USEDIFFUSE\n"
1243 "       // get the surface normal and the gloss color\n"
1244 "# ifdef USEVERTEXTEXTUREBLEND\n"
1245 "       myhalf3 surfacenormal = normalize(mix(myhalf3(texture2D(Texture_SecondaryNormal, TexCoord2)), myhalf3(texture2D(Texture_Normal, TexCoord)), terrainblend) - myhalf3(0.5, 0.5, 0.5));\n"
1246 "#  ifdef USESPECULAR\n"
1247 "       myhalf3 glosscolor = mix(myhalf3(texture2D(Texture_SecondaryGloss, TexCoord2)), myhalf3(texture2D(Texture_Gloss, TexCoord)), terrainblend);\n"
1248 "#  endif\n"
1249 "# else\n"
1250 "       myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5, 0.5, 0.5));\n"
1251 "#  ifdef USESPECULAR\n"
1252 "       myhalf3 glosscolor = myhalf3(texture2D(Texture_Gloss, TexCoord));\n"
1253 "#  endif\n"
1254 "# endif\n"
1255 "#endif\n"
1256 "\n"
1257 "\n"
1258 "\n"
1259 "#ifdef MODE_LIGHTSOURCE\n"
1260 "       // light source\n"
1261 "\n"
1262 "       // calculate surface normal, light normal, and specular normal\n"
1263 "       // compute color intensity for the two textures (colormap and glossmap)\n"
1264 "       // scale by light color and attenuation as efficiently as possible\n"
1265 "       // (do as much scalar math as possible rather than vector math)\n"
1266 "# ifdef USEDIFFUSE\n"
1267 "       // get the light normal\n"
1268 "       myhalf3 diffusenormal = myhalf3(normalize(LightVector));\n"
1269 "# endif\n"
1270 "# ifdef USESPECULAR\n"
1271 "#  ifndef USEEXACTSPECULARMATH\n"
1272 "       myhalf3 specularnormal = normalize(diffusenormal + myhalf3(normalize(EyeVector)));\n"
1273 "\n"
1274 "#  endif\n"
1275 "       // calculate directional shading\n"
1276 "#  ifdef USEEXACTSPECULARMATH\n"
1277 "       color.rgb = myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0))) * (color.rgb * (AmbientScale + DiffuseScale * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0))) + (SpecularScale * pow(myhalf(max(float(dot(reflect(diffusenormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower)) * glosscolor);\n"
1278 "#  else\n"
1279 "       color.rgb = myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0))) * (color.rgb * (AmbientScale + DiffuseScale * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0))) + (SpecularScale * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower)) * glosscolor);\n"
1280 "#  endif\n"
1281 "# else\n"
1282 "#  ifdef USEDIFFUSE\n"
1283 "       // calculate directional shading\n"
1284 "       color.rgb = color.rgb * (myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0))) * (AmbientScale + DiffuseScale * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0))));\n"
1285 "#  else\n"
1286 "       // calculate directionless shading\n"
1287 "       color.rgb = color.rgb * myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1288 "#  endif\n"
1289 "# endif\n"
1290 "\n"
1291 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1292 "#if !showshadowmap\n"
1293 "    color.rgb *= ShadowMapCompare(CubeVector);\n"
1294 "#endif\n"
1295 "#endif\n"
1296 "\n"
1297 "# ifdef USECUBEFILTER\n"
1298 "       // apply light cubemap filter\n"
1299 "       //color.rgb *= normalize(CubeVector) * 0.5 + 0.5;//vec3(textureCube(Texture_Cube, CubeVector));\n"
1300 "       color.rgb *= myhalf3(textureCube(Texture_Cube, CubeVector));\n"
1301 "# endif\n"
1302 "#endif // MODE_LIGHTSOURCE\n"
1303 "\n"
1304 "\n"
1305 "\n"
1306 "\n"
1307 "#ifdef MODE_LIGHTDIRECTION\n"
1308 "       // directional model lighting\n"
1309 "# ifdef USEDIFFUSE\n"
1310 "       // get the light normal\n"
1311 "       myhalf3 diffusenormal = myhalf3(normalize(LightVector));\n"
1312 "# endif\n"
1313 "# ifdef USESPECULAR\n"
1314 "       // calculate directional shading\n"
1315 "       color.rgb *= AmbientColor + DiffuseColor * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0));\n"
1316 "#  ifdef USEEXACTSPECULARMATH\n"
1317 "       color.rgb += myhalf3(texture2D(Texture_Gloss, TexCoord)) * SpecularColor * pow(myhalf(max(float(dot(reflect(diffusenormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower);\n"
1318 "#  else\n"
1319 "       myhalf3 specularnormal = normalize(diffusenormal + myhalf3(normalize(EyeVector)));\n"
1320 "       color.rgb += myhalf3(texture2D(Texture_Gloss, TexCoord)) * SpecularColor * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower);\n"
1321 "#  endif\n"
1322 "# else\n"
1323 "#  ifdef USEDIFFUSE\n"
1324 "\n"
1325 "       // calculate directional shading\n"
1326 "       color.rgb *= AmbientColor + DiffuseColor * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0));\n"
1327 "#  else\n"
1328 "       color.rgb *= AmbientColor;\n"
1329 "#  endif\n"
1330 "# endif\n"
1331 "#endif // MODE_LIGHTDIRECTION\n"
1332 "\n"
1333 "\n"
1334 "\n"
1335 "\n"
1336 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1337 "       // deluxemap lightmapping using light vectors in modelspace (evil q3map2)\n"
1338 "\n"
1339 "       // get the light normal\n"
1340 "       myhalf3 diffusenormal_modelspace = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1341 "       myhalf3 diffusenormal;\n"
1342 "       diffusenormal.x = dot(diffusenormal_modelspace, myhalf3(VectorS));\n"
1343 "       diffusenormal.y = dot(diffusenormal_modelspace, myhalf3(VectorT));\n"
1344 "       diffusenormal.z = dot(diffusenormal_modelspace, myhalf3(VectorR));\n"
1345 "       // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
1346 "       // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
1347 "       // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
1348 "       // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
1349 "       // to map the luxels to coordinates on the draw surfaces), which also causes\n"
1350 "       // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
1351 "       // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
1352 "       // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
1353 "       // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
1354 "       myhalf3 tempcolor = color.rgb * (DiffuseScale * myhalf(max(float(dot(surfacenormal, diffusenormal) / max(0.25, diffusenormal.z)), 0.0)));\n"
1355 "               // 0.25 supports up to 75.5 degrees normal/deluxe angle\n"
1356 "# ifdef USESPECULAR\n"
1357 "#  ifdef USEEXACTSPECULARMATH\n"
1358 "       tempcolor += myhalf3(texture2D(Texture_Gloss, TexCoord)) * SpecularScale * pow(myhalf(max(float(dot(reflect(normalize(diffusenormal), surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower);\n"
1359 "#  else\n"
1360 "       myhalf3 specularnormal = myhalf3(normalize(diffusenormal + myhalf3(normalize(EyeVector))));\n"
1361 "       tempcolor += myhalf3(texture2D(Texture_Gloss, TexCoord)) * SpecularScale * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower);\n"
1362 "#  endif\n"
1363 "# endif\n"
1364 "\n"
1365 "       // apply lightmap color\n"
1366 "       color.rgb = color.rgb * AmbientScale + tempcolor * myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1367 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1368 "\n"
1369 "\n"
1370 "\n"
1371 "\n"
1372 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
1373 "       // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
1374 "\n"
1375 "       // get the light normal\n"
1376 "       myhalf3 diffusenormal = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1377 "       // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
1378 "       myhalf3 tempcolor = color.rgb * (DiffuseScale * myhalf(max(float(dot(surfacenormal, diffusenormal) / diffusenormal.z), 0.0)));\n"
1379 "# ifdef USESPECULAR\n"
1380 "#  ifdef USEEXACTSPECULARMATH\n"
1381 "       tempcolor += myhalf3(texture2D(Texture_Gloss, TexCoord)) * SpecularScale * pow(myhalf(max(float(dot(reflect(diffusenormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower);\n"
1382 "#  else\n"
1383 "       myhalf3 specularnormal = myhalf3(normalize(diffusenormal + myhalf3(normalize(EyeVector))));\n"
1384 "       tempcolor += myhalf3(texture2D(Texture_Gloss, TexCoord)) * SpecularScale * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower);\n"
1385 "#  endif\n"
1386 "# endif\n"
1387 "\n"
1388 "       // apply lightmap color\n"
1389 "       color.rgb = color.rgb * AmbientScale + tempcolor * myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1390 "#endif // MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
1391 "\n"
1392 "\n"
1393 "\n"
1394 "\n"
1395 "#ifdef MODE_LIGHTMAP\n"
1396 "       // apply lightmap color\n"
1397 "       color.rgb = color.rgb * myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap)) * DiffuseScale + color.rgb * AmbientScale;\n"
1398 "#endif // MODE_LIGHTMAP\n"
1399 "\n"
1400 "\n"
1401 "\n"
1402 "\n"
1403 "#ifdef MODE_VERTEXCOLOR\n"
1404 "       // apply lightmap color\n"
1405 "       color.rgb = color.rgb * myhalf3(gl_Color.rgb) * DiffuseScale + color.rgb * AmbientScale;\n"
1406 "#endif // MODE_VERTEXCOLOR\n"
1407 "\n"
1408 "\n"
1409 "\n"
1410 "\n"
1411 "#ifdef MODE_FLATCOLOR\n"
1412 "#endif // MODE_FLATCOLOR\n"
1413 "\n"
1414 "\n"
1415 "\n"
1416 "\n"
1417 "\n"
1418 "\n"
1419 "\n"
1420 "       color *= TintColor;\n"
1421 "\n"
1422 "#ifdef USEGLOW\n"
1423 "#ifdef USEVERTEXTEXTUREBLEND\n"
1424 "       color.rgb += mix(myhalf3(texture2D(Texture_SecondaryGlow, TexCoord2)), myhalf3(texture2D(Texture_Glow, TexCoord)), terrainblend);\n"
1425 "#else\n"
1426 "       color.rgb += myhalf3(texture2D(Texture_Glow, TexCoord)) * GlowColor;\n"
1427 "#endif\n"
1428 "#endif\n"
1429 "\n"
1430 "       color.rgb *= SceneBrightness;\n"
1431 "\n"
1432 "       // apply fog after Contrastboost/SceneBrightness because its color is already modified appropriately\n"
1433 "#ifdef USEFOG\n"
1434 "       float fogfrac;\n"
1435 "#ifdef USEFOGOUTSIDE\n"
1436 "       fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
1437 "#else\n"
1438 "       fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
1439 "#endif\n"
1440 "//     float FogHeightFade1 = -0.5/1024.0;\n"
1441 "//     if (FogPlaneViewDist >= 0.0)\n"
1442 "//             fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade1);\n"
1443 "//     else\n"
1444 "//             fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade1);\n"
1445 "//# ifdef USEFOGABOVE\n"
1446 "//     if (FogPlaneViewDist >= 0.0)\n"
1447 "//             fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist);\n"
1448 "//     else\n"
1449 "//             fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist));\n"
1450 "//     fogfrac *= min(1.0, (min(0.0, FogPlaneVertexDist) + min(0.0, FogPlaneViewDist))*FogHeightFade1);\n"
1451 "//     fogfrac *= min(1.0, (max(0.0, fade*FogPlaneVertexDist) + max(0.0, fade*FogPlaneViewDist)));\n"
1452 "//     fogfrac *= min(1.0, (max(0.0, FogHeightFade1*FogPlaneVertexDist) + max(0.0, FogHeightFade1*FogPlaneViewDist)));\n"
1453 "//     fogfrac *= min(1.0, (min(0.0, FogPlaneVertexDist) + min(0.0, FogPlaneViewDist))*FogHeightFade1);\n"
1454 "\n"
1455 "       //fogfrac *= min(1.0, max(0.0, (max(-2048, min(0, FogPlaneVertexDist)) + max(-2048, min(0, FogPlaneViewDist)))/-2048.0));\n"
1456 "       //float fade = -0.5/128.0;\n"
1457 "       //fogfrac *= max(0.0, min(1.0, fade*FogPlaneVertexDist)) + max(0.0, min(1.0, fade*FogPlaneViewDist));\n"
1458 "       //fogfrac *= max(0.0, min(1.0, FogHeightFade1*FogPlaneVertexDist)) + max(0.0, min(1.0, FogHeightFade1*FogPlaneViewDist));\n"
1459 "       //fogfrac *= min(1.0, max(0.0, FogHeightFade1*FogPlaneVertexDist)) + min(1.0, max(0.0, FogHeightFade1*FogPlaneViewDist));\n"
1460 "       //fogfrac *= min(1.0, max(0.0, FogHeightFade1*FogPlaneVertexDist) + max(0.0, FogHeightFade1*FogPlaneViewDist));\n"
1461 "       //fogfrac *= min(1.0, min(1.0, max(0.0, FogHeightFade1*FogPlaneVertexDist)) + min(1.0, max(0.0, FogHeightFade1*FogPlaneViewDist)));\n"
1462 "       //fogfrac *= min(1.0, max(0.0, FogHeightFade1*FogPlaneVertexDist) + max(0.0, FogHeightFade1*FogPlaneViewDist));\n"
1463 "       //fogfrac *= min(1.0, (min(0.0, FogPlaneVertexDist) + min(0.0, FogPlaneViewDist)) * FogHeightFade1);\n"
1464 "       //fogfrac *= min(1.0, (min(0.0, FogPlaneVertexDist) + min(0.0, FogPlaneViewDist)) * FogHeightFade1);\n"
1465 "//# endif\n"
1466 "       color.rgb = mix(FogColor, color.rgb, myhalf(texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0))));\n"
1467 "#endif\n"
1468 "\n"
1469 "       // reflection must come last because it already contains exactly the correct fog (the reflection render preserves camera distance from the plane, it only flips the side) and ContrastBoost/SceneBrightness\n"
1470 "#ifdef USEREFLECTION\n"
1471 "       vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
1472 "       //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
1473 "       vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
1474 "       vec2 ScreenTexCoord = SafeScreenTexCoord + vec3(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
1475 "       // FIXME temporary hack to detect the case that the reflection\n"
1476 "       // gets blackened at edges due to leaving the area that contains actual\n"
1477 "       // content.\n"
1478 "       // Remove this 'ack once we have a better way to stop this thing from\n"
1479 "       // 'appening.\n"
1480 "       float f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
1481 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
1482 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
1483 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
1484 "       ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
1485 "       color.rgb = mix(color.rgb, myhalf3(texture2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
1486 "#endif\n"
1487 "\n"
1488 "       gl_FragColor = vec4(color);\n"
1489 "\n"
1490 "#if showshadowmap\n"
1491 "# ifdef USESHADOWMAPRECT\n"
1492 "#  ifdef USESHADOWSAMPLER\n"
1493 "       gl_FragColor = shadow2DRect(Texture_ShadowMapRect, GetShadowMapTC2D(CubeVector).xyz);\n"
1494 "#  else\n"
1495 "       gl_FragColor = texture2DRect(Texture_ShadowMapRect, GetShadowMapTC2D(CubeVector).xy);\n"
1496 "#  endif\n"
1497 "# endif\n"
1498 "# ifdef USESHADOWMAP2D\n"
1499 "#  ifdef USESHADOWSAMPLER\n"
1500 "    gl_FragColor = shadow2D(Texture_ShadowMap2D, GetShadowMapTC2D(CubeVector).xyz);\n"
1501 "#  else\n"
1502 "    gl_FragColor = texture2D(Texture_ShadowMap2D, GetShadowMapTC2D(CubeVector).xy);\n"
1503 "#  endif\n"
1504 "# endif\n"
1505 "\n"
1506 "# ifdef USESHADOWMAPCUBE\n"
1507 "#  ifdef USESHADOWSAMPLER\n"
1508 "    gl_FragColor = shadowCube(Texture_ShadowMapCube, GetShadowMapTCCube(CubeVector));\n"
1509 "#  else\n"
1510 "    gl_FragColor = textureCube(Texture_ShadowMapCube, GetShadowMapTCCube(CubeVector).xyz);\n"
1511 "#  endif\n"
1512 "# endif\n"
1513 "#endif\n"
1514 "}\n"
1515 "#endif // !MODE_REFRACTION\n"
1516 "#endif // !MODE_WATER\n"
1517 "\n"
1518 "#endif // FRAGMENT_SHADER\n"
1519 "\n"
1520 "#endif // !MODE_BLOOMBLUR\n"
1521 "#endif // !MODE_GENERIC\n"
1522 "#endif // !MODE_POSTPROCESS\n"
1523 "#endif // !MODE_SHOWDEPTH\n"
1524 "#endif // !MODE_DEPTH_OR_SHADOW\n"
1525 ;
1526
1527 typedef struct shaderpermutationinfo_s
1528 {
1529         const char *pretext;
1530         const char *name;
1531 }
1532 shaderpermutationinfo_t;
1533
1534 typedef struct shadermodeinfo_s
1535 {
1536         const char *vertexfilename;
1537         const char *geometryfilename;
1538         const char *fragmentfilename;
1539         const char *pretext;
1540         const char *name;
1541 }
1542 shadermodeinfo_t;
1543
1544 typedef enum shaderpermutation_e
1545 {
1546         SHADERPERMUTATION_DIFFUSE = 1<<0, ///< (lightsource) whether to use directional shading
1547         SHADERPERMUTATION_VERTEXTEXTUREBLEND = 1<<1, ///< indicates this is a two-layer material blend based on vertex alpha (q3bsp)
1548         SHADERPERMUTATION_VIEWTINT = 1<<2, ///< view tint (postprocessing only)
1549         SHADERPERMUTATION_COLORMAPPING = 1<<3, ///< indicates this is a colormapped skin
1550         SHADERPERMUTATION_SATURATION = 1<<4, ///< saturation (postprocessing only)
1551         SHADERPERMUTATION_FOGINSIDE = 1<<5, ///< tint the color by fog color or black if using additive blend mode
1552         SHADERPERMUTATION_FOGOUTSIDE = 1<<6, ///< tint the color by fog color or black if using additive blend mode
1553         SHADERPERMUTATION_GAMMARAMPS = 1<<7, ///< gamma (postprocessing only)
1554         SHADERPERMUTATION_CUBEFILTER = 1<<8, ///< (lightsource) use cubemap light filter
1555         SHADERPERMUTATION_GLOW = 1<<9, ///< (lightmap) blend in an additive glow texture
1556         SHADERPERMUTATION_BLOOM = 1<<10, ///< bloom (postprocessing only)
1557         SHADERPERMUTATION_SPECULAR = 1<<11, ///< (lightsource or deluxemapping) render specular effects
1558         SHADERPERMUTATION_POSTPROCESSING = 1<<12, ///< user defined postprocessing (postprocessing only)
1559         SHADERPERMUTATION_EXACTSPECULARMATH = 1<<13, ///< (lightsource or deluxemapping) use exact reflection map for specular effects, as opposed to the usual OpenGL approximation
1560         SHADERPERMUTATION_REFLECTION = 1<<14, ///< normalmap-perturbed reflection of the scene infront of the surface, preformed as an overlay on the surface
1561         SHADERPERMUTATION_OFFSETMAPPING = 1<<15, ///< adjust texcoords to roughly simulate a displacement mapped surface
1562         SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING = 1<<16, ///< adjust texcoords to accurately simulate a displacement mapped surface (requires OFFSETMAPPING to also be set!)
1563         SHADERPERMUTATION_SHADOWMAPRECT = 1<<17, ///< (lightsource) use shadowmap rectangle texture as light filter
1564         SHADERPERMUTATION_SHADOWMAPCUBE = 1<<18, ///< (lightsource) use shadowmap cubemap texture as light filter
1565         SHADERPERMUTATION_SHADOWMAP2D = 1<<19, ///< (lightsource) use shadowmap rectangle texture as light filter
1566         SHADERPERMUTATION_SHADOWMAPPCF = 1<<20, ///< (lightsource) use percentage closer filtering on shadowmap test results
1567         SHADERPERMUTATION_SHADOWMAPPCF2 = 1<<21, ///< (lightsource) use higher quality percentage closer filtering on shadowmap test results
1568         SHADERPERMUTATION_SHADOWSAMPLER = 1<<22, ///< (lightsource) use hardware shadowmap test
1569         SHADERPERMUTATION_SHADOWMAPVSDCT = 1<<23, ///< (lightsource) use virtual shadow depth cube texture for shadowmap indexing
1570         SHADERPERMUTATION_LIMIT = 1<<24, ///< size of permutations array
1571         SHADERPERMUTATION_COUNT = 24 ///< size of shaderpermutationinfo array
1572 }
1573 shaderpermutation_t;
1574
1575 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
1576 shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
1577 {
1578         {"#define USEDIFFUSE\n", " diffuse"},
1579         {"#define USEVERTEXTEXTUREBLEND\n", " vertextextureblend"},
1580         {"#define USEVIEWTINT\n", " viewtint"},
1581         {"#define USECOLORMAPPING\n", " colormapping"},
1582         {"#define USESATURATION\n", " saturation"},
1583         {"#define USEFOGINSIDE\n", " foginside"},
1584         {"#define USEFOGOUTSIDE\n", " fogoutside"},
1585         {"#define USEGAMMARAMPS\n", " gammaramps"},
1586         {"#define USECUBEFILTER\n", " cubefilter"},
1587         {"#define USEGLOW\n", " glow"},
1588         {"#define USEBLOOM\n", " bloom"},
1589         {"#define USESPECULAR\n", " specular"},
1590         {"#define USEPOSTPROCESSING\n", " postprocessing"},
1591         {"#define USEEXACTSPECULARMATH\n", " exactspecularmath"},
1592         {"#define USEREFLECTION\n", " reflection"},
1593         {"#define USEOFFSETMAPPING\n", " offsetmapping"},
1594         {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
1595         {"#define USESHADOWMAPRECT\n", " shadowmaprect"},
1596         {"#define USESHADOWMAPCUBE\n", " shadowmapcube"},
1597         {"#define USESHADOWMAP2D\n", " shadowmap2d"},
1598         {"#define USESHADOWMAPPCF 1\n", " shadowmappcf"},
1599         {"#define USESHADOWMAPPCF 2\n", " shadowmappcf2"},
1600         {"#define USESHADOWSAMPLER\n", " shadowsampler"},
1601         {"#define USESHADOWMAPVSDCT\n", " shadowmapvsdct"},
1602 };
1603
1604 /// this enum is multiplied by SHADERPERMUTATION_MODEBASE
1605 typedef enum shadermode_e
1606 {
1607         SHADERMODE_GENERIC, ///< (particles/HUD/etc) vertex color, optionally multiplied by one texture
1608         SHADERMODE_POSTPROCESS, ///< postprocessing shader (r_glsl_postprocess)
1609         SHADERMODE_DEPTH_OR_SHADOW, ///< (depthfirst/shadows) vertex shader only
1610         SHADERMODE_FLATCOLOR, ///< (lightmap) modulate texture by uniform color (q1bsp, q3bsp)
1611         SHADERMODE_VERTEXCOLOR, ///< (lightmap) modulate texture by vertex colors (q3bsp)
1612         SHADERMODE_LIGHTMAP, ///< (lightmap) modulate texture by lightmap texture (q1bsp, q3bsp)
1613         SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE, ///< (lightmap) use directional pixel shading from texture containing modelspace light directions (q3bsp deluxemap)
1614         SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE, ///< (lightmap) use directional pixel shading from texture containing tangentspace light directions (q1bsp deluxemap)
1615         SHADERMODE_LIGHTDIRECTION, ///< (lightmap) use directional pixel shading from fixed light direction (q3bsp)
1616         SHADERMODE_LIGHTSOURCE, ///< (lightsource) use directional pixel shading from light source (rtlight)
1617         SHADERMODE_REFRACTION, ///< refract background (the material is rendered normally after this pass)
1618         SHADERMODE_WATER, ///< refract background and reflection (the material is rendered normally after this pass)
1619         SHADERMODE_SHOWDEPTH, ///< (debugging) renders depth as color
1620         SHADERMODE_COUNT
1621 }
1622 shadermode_t;
1623
1624 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
1625 shadermodeinfo_t shadermodeinfo[SHADERMODE_COUNT] =
1626 {
1627         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_GENERIC\n", " generic"},
1628         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_POSTPROCESS\n", " postprocess"},
1629         {"glsl/default.glsl", NULL, NULL               , "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
1630         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
1631         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
1632         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTMAP\n", " lightmap"},
1633         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
1634         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
1635         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
1636         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
1637         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_REFRACTION\n", " refraction"},
1638         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_WATER\n", " water"},
1639         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
1640 };
1641
1642 struct r_glsl_permutation_s;
1643 typedef struct r_glsl_permutation_s
1644 {
1645         /// hash lookup data
1646         struct r_glsl_permutation_s *hashnext;
1647         unsigned int mode;
1648         unsigned int permutation;
1649
1650         /// indicates if we have tried compiling this permutation already
1651         qboolean compiled;
1652         /// 0 if compilation failed
1653         int program;
1654         /// locations of detected uniforms in program object, or -1 if not found
1655         int loc_Texture_First;
1656         int loc_Texture_Second;
1657         int loc_Texture_GammaRamps;
1658         int loc_Texture_Normal;
1659         int loc_Texture_Color;
1660         int loc_Texture_Gloss;
1661         int loc_Texture_Glow;
1662         int loc_Texture_SecondaryNormal;
1663         int loc_Texture_SecondaryColor;
1664         int loc_Texture_SecondaryGloss;
1665         int loc_Texture_SecondaryGlow;
1666         int loc_Texture_Pants;
1667         int loc_Texture_Shirt;
1668         int loc_Texture_FogMask;
1669         int loc_Texture_Lightmap;
1670         int loc_Texture_Deluxemap;
1671         int loc_Texture_Attenuation;
1672         int loc_Texture_Cube;
1673         int loc_Texture_Refraction;
1674         int loc_Texture_Reflection;
1675         int loc_Texture_ShadowMapRect;
1676         int loc_Texture_ShadowMapCube;
1677         int loc_Texture_ShadowMap2D;
1678         int loc_Texture_CubeProjection;
1679         int loc_FogColor;
1680         int loc_LightPosition;
1681         int loc_EyePosition;
1682         int loc_Color_Pants;
1683         int loc_Color_Shirt;
1684         int loc_FogPlane;
1685         int loc_FogPlaneViewDist;
1686         int loc_FogRangeRecip;
1687         int loc_FogHeightFade;
1688         int loc_AmbientScale;
1689         int loc_DiffuseScale;
1690         int loc_SpecularScale;
1691         int loc_SpecularPower;
1692         int loc_GlowColor;
1693         int loc_SceneBrightness; // or: Scenebrightness * ContrastBoost
1694         int loc_OffsetMapping_Scale;
1695         int loc_TintColor;
1696         int loc_AmbientColor;
1697         int loc_DiffuseColor;
1698         int loc_SpecularColor;
1699         int loc_LightDir;
1700         int loc_ContrastBoostCoeff; ///< 1 - 1/ContrastBoost
1701         int loc_GammaCoeff; ///< 1 / gamma
1702         int loc_DistortScaleRefractReflect;
1703         int loc_ScreenScaleRefractReflect;
1704         int loc_ScreenCenterRefractReflect;
1705         int loc_RefractColor;
1706         int loc_ReflectColor;
1707         int loc_ReflectFactor;
1708         int loc_ReflectOffset;
1709         int loc_UserVec1;
1710         int loc_UserVec2;
1711         int loc_UserVec3;
1712         int loc_UserVec4;
1713         int loc_ClientTime;
1714         int loc_PixelSize;
1715         int loc_Saturation;
1716         int loc_ShadowMap_TextureScale;
1717         int loc_ShadowMap_Parameters;
1718 }
1719 r_glsl_permutation_t;
1720
1721 #define SHADERPERMUTATION_HASHSIZE 256
1722
1723 /// information about each possible shader permutation
1724 r_glsl_permutation_t *r_glsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
1725 /// currently selected permutation
1726 r_glsl_permutation_t *r_glsl_permutation;
1727 /// storage for permutations linked in the hash table
1728 memexpandablearray_t r_glsl_permutationarray;
1729
1730 static r_glsl_permutation_t *R_GLSL_FindPermutation(unsigned int mode, unsigned int permutation)
1731 {
1732         //unsigned int hashdepth = 0;
1733         unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
1734         r_glsl_permutation_t *p;
1735         for (p = r_glsl_permutationhash[mode][hashindex];p;p = p->hashnext)
1736         {
1737                 if (p->mode == mode && p->permutation == permutation)
1738                 {
1739                         //if (hashdepth > 10)
1740                         //      Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
1741                         return p;
1742                 }
1743                 //hashdepth++;
1744         }
1745         p = (r_glsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_glsl_permutationarray);
1746         p->mode = mode;
1747         p->permutation = permutation;
1748         p->hashnext = r_glsl_permutationhash[mode][hashindex];
1749         r_glsl_permutationhash[mode][hashindex] = p;
1750         //if (hashdepth > 10)
1751         //      Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
1752         return p;
1753 }
1754
1755 static char *R_GLSL_GetText(const char *filename, qboolean printfromdisknotice)
1756 {
1757         char *shaderstring;
1758         if (!filename || !filename[0])
1759                 return NULL;
1760         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
1761         if (shaderstring)
1762         {
1763                 if (printfromdisknotice)
1764                         Con_DPrint("from disk... ");
1765                 return shaderstring;
1766         }
1767         else if (!strcmp(filename, "glsl/default.glsl"))
1768         {
1769                 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(builtinshaderstring) + 1);
1770                 memcpy(shaderstring, builtinshaderstring, strlen(builtinshaderstring) + 1);
1771         }
1772         return shaderstring;
1773 }
1774
1775 static void R_GLSL_CompilePermutation(r_glsl_permutation_t *p, unsigned int mode, unsigned int permutation)
1776 {
1777         int i;
1778         shadermodeinfo_t *modeinfo = shadermodeinfo + mode;
1779         int vertstrings_count = 0;
1780         int geomstrings_count = 0;
1781         int fragstrings_count = 0;
1782         char *vertexstring, *geometrystring, *fragmentstring;
1783         const char *vertstrings_list[32+3];
1784         const char *geomstrings_list[32+3];
1785         const char *fragstrings_list[32+3];
1786         char permutationname[256];
1787
1788         if (p->compiled)
1789                 return;
1790         p->compiled = true;
1791         p->program = 0;
1792
1793         permutationname[0] = 0;
1794         vertexstring   = R_GLSL_GetText(modeinfo->vertexfilename, true);
1795         geometrystring = R_GLSL_GetText(modeinfo->geometryfilename, false);
1796         fragmentstring = R_GLSL_GetText(modeinfo->fragmentfilename, false);
1797
1798         strlcat(permutationname, shadermodeinfo[mode].vertexfilename, sizeof(permutationname));
1799
1800         // the first pretext is which type of shader to compile as
1801         // (later these will all be bound together as a program object)
1802         vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
1803         geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
1804         fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
1805
1806         // the second pretext is the mode (for example a light source)
1807         vertstrings_list[vertstrings_count++] = shadermodeinfo[mode].pretext;
1808         geomstrings_list[geomstrings_count++] = shadermodeinfo[mode].pretext;
1809         fragstrings_list[fragstrings_count++] = shadermodeinfo[mode].pretext;
1810         strlcat(permutationname, modeinfo->name, sizeof(permutationname));
1811
1812         // now add all the permutation pretexts
1813         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1814         {
1815                 if (permutation & (1<<i))
1816                 {
1817                         vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
1818                         geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
1819                         fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
1820                         strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
1821                 }
1822                 else
1823                 {
1824                         // keep line numbers correct
1825                         vertstrings_list[vertstrings_count++] = "\n";
1826                         geomstrings_list[geomstrings_count++] = "\n";
1827                         fragstrings_list[fragstrings_count++] = "\n";
1828                 }
1829         }
1830
1831         // now append the shader text itself
1832         vertstrings_list[vertstrings_count++] = vertexstring;
1833         geomstrings_list[geomstrings_count++] = geometrystring;
1834         fragstrings_list[fragstrings_count++] = fragmentstring;
1835
1836         // if any sources were NULL, clear the respective list
1837         if (!vertexstring)
1838                 vertstrings_count = 0;
1839         if (!geometrystring)
1840                 geomstrings_count = 0;
1841         if (!fragmentstring)
1842                 fragstrings_count = 0;
1843
1844         // compile the shader program
1845         if (vertstrings_count + geomstrings_count + fragstrings_count)
1846                 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
1847         if (p->program)
1848         {
1849                 CHECKGLERROR
1850                 qglUseProgramObjectARB(p->program);CHECKGLERROR
1851                 // look up all the uniform variable names we care about, so we don't
1852                 // have to look them up every time we set them
1853                 p->loc_Texture_First              = qglGetUniformLocationARB(p->program, "Texture_First");
1854                 p->loc_Texture_Second             = qglGetUniformLocationARB(p->program, "Texture_Second");
1855                 p->loc_Texture_GammaRamps         = qglGetUniformLocationARB(p->program, "Texture_GammaRamps");
1856                 p->loc_Texture_Normal             = qglGetUniformLocationARB(p->program, "Texture_Normal");
1857                 p->loc_Texture_Color              = qglGetUniformLocationARB(p->program, "Texture_Color");
1858                 p->loc_Texture_Gloss              = qglGetUniformLocationARB(p->program, "Texture_Gloss");
1859                 p->loc_Texture_Glow               = qglGetUniformLocationARB(p->program, "Texture_Glow");
1860                 p->loc_Texture_SecondaryNormal    = qglGetUniformLocationARB(p->program, "Texture_SecondaryNormal");
1861                 p->loc_Texture_SecondaryColor     = qglGetUniformLocationARB(p->program, "Texture_SecondaryColor");
1862                 p->loc_Texture_SecondaryGloss     = qglGetUniformLocationARB(p->program, "Texture_SecondaryGloss");
1863                 p->loc_Texture_SecondaryGlow      = qglGetUniformLocationARB(p->program, "Texture_SecondaryGlow");
1864                 p->loc_Texture_FogMask            = qglGetUniformLocationARB(p->program, "Texture_FogMask");
1865                 p->loc_Texture_Pants              = qglGetUniformLocationARB(p->program, "Texture_Pants");
1866                 p->loc_Texture_Shirt              = qglGetUniformLocationARB(p->program, "Texture_Shirt");
1867                 p->loc_Texture_Lightmap           = qglGetUniformLocationARB(p->program, "Texture_Lightmap");
1868                 p->loc_Texture_Deluxemap          = qglGetUniformLocationARB(p->program, "Texture_Deluxemap");
1869                 p->loc_Texture_Refraction         = qglGetUniformLocationARB(p->program, "Texture_Refraction");
1870                 p->loc_Texture_Reflection         = qglGetUniformLocationARB(p->program, "Texture_Reflection");
1871                 p->loc_Texture_Attenuation        = qglGetUniformLocationARB(p->program, "Texture_Attenuation");
1872                 p->loc_Texture_Cube               = qglGetUniformLocationARB(p->program, "Texture_Cube");
1873                 p->loc_Texture_ShadowMapRect      = qglGetUniformLocationARB(p->program, "Texture_ShadowMapRect");
1874                 p->loc_Texture_ShadowMapCube      = qglGetUniformLocationARB(p->program, "Texture_ShadowMapCube");
1875                 p->loc_Texture_ShadowMap2D        = qglGetUniformLocationARB(p->program, "Texture_ShadowMap2D");
1876                 p->loc_Texture_CubeProjection     = qglGetUniformLocationARB(p->program, "Texture_CubeProjection");  
1877                 p->loc_FogColor                   = qglGetUniformLocationARB(p->program, "FogColor");
1878                 p->loc_LightPosition              = qglGetUniformLocationARB(p->program, "LightPosition");
1879                 p->loc_EyePosition                = qglGetUniformLocationARB(p->program, "EyePosition");
1880                 p->loc_Color_Pants                = qglGetUniformLocationARB(p->program, "Color_Pants");
1881                 p->loc_Color_Shirt                = qglGetUniformLocationARB(p->program, "Color_Shirt");
1882                 p->loc_FogPlane                   = qglGetUniformLocationARB(p->program, "FogPlane");
1883                 p->loc_FogPlaneViewDist           = qglGetUniformLocationARB(p->program, "FogPlaneViewDist");
1884                 p->loc_FogRangeRecip              = qglGetUniformLocationARB(p->program, "FogRangeRecip");
1885                 p->loc_FogHeightFade              = qglGetUniformLocationARB(p->program, "FogHeightFade");
1886                 p->loc_AmbientScale               = qglGetUniformLocationARB(p->program, "AmbientScale");
1887                 p->loc_DiffuseScale               = qglGetUniformLocationARB(p->program, "DiffuseScale");
1888                 p->loc_SpecularPower              = qglGetUniformLocationARB(p->program, "SpecularPower");
1889                 p->loc_SpecularScale              = qglGetUniformLocationARB(p->program, "SpecularScale");
1890                 p->loc_GlowColor                  = qglGetUniformLocationARB(p->program, "GlowColor");
1891                 p->loc_SceneBrightness            = qglGetUniformLocationARB(p->program, "SceneBrightness");
1892                 p->loc_OffsetMapping_Scale        = qglGetUniformLocationARB(p->program, "OffsetMapping_Scale");
1893                 p->loc_TintColor                  = qglGetUniformLocationARB(p->program, "TintColor");
1894                 p->loc_AmbientColor               = qglGetUniformLocationARB(p->program, "AmbientColor");
1895                 p->loc_DiffuseColor               = qglGetUniformLocationARB(p->program, "DiffuseColor");
1896                 p->loc_SpecularColor              = qglGetUniformLocationARB(p->program, "SpecularColor");
1897                 p->loc_LightDir                   = qglGetUniformLocationARB(p->program, "LightDir");
1898                 p->loc_ContrastBoostCoeff         = qglGetUniformLocationARB(p->program, "ContrastBoostCoeff");
1899                 p->loc_DistortScaleRefractReflect = qglGetUniformLocationARB(p->program, "DistortScaleRefractReflect");
1900                 p->loc_ScreenScaleRefractReflect  = qglGetUniformLocationARB(p->program, "ScreenScaleRefractReflect");
1901                 p->loc_ScreenCenterRefractReflect = qglGetUniformLocationARB(p->program, "ScreenCenterRefractReflect");
1902                 p->loc_RefractColor               = qglGetUniformLocationARB(p->program, "RefractColor");
1903                 p->loc_ReflectColor               = qglGetUniformLocationARB(p->program, "ReflectColor");
1904                 p->loc_ReflectFactor              = qglGetUniformLocationARB(p->program, "ReflectFactor");
1905                 p->loc_ReflectOffset              = qglGetUniformLocationARB(p->program, "ReflectOffset");
1906                 p->loc_GammaCoeff                 = qglGetUniformLocationARB(p->program, "GammaCoeff");
1907                 p->loc_UserVec1                   = qglGetUniformLocationARB(p->program, "UserVec1");
1908                 p->loc_UserVec2                   = qglGetUniformLocationARB(p->program, "UserVec2");
1909                 p->loc_UserVec3                   = qglGetUniformLocationARB(p->program, "UserVec3");
1910                 p->loc_UserVec4                   = qglGetUniformLocationARB(p->program, "UserVec4");
1911                 p->loc_ClientTime                 = qglGetUniformLocationARB(p->program, "ClientTime");
1912                 p->loc_PixelSize                  = qglGetUniformLocationARB(p->program, "PixelSize");
1913                 p->loc_Saturation                 = qglGetUniformLocationARB(p->program, "Saturation");
1914                 p->loc_ShadowMap_TextureScale     = qglGetUniformLocationARB(p->program, "ShadowMap_TextureScale");
1915                 p->loc_ShadowMap_Parameters       = qglGetUniformLocationARB(p->program, "ShadowMap_Parameters");
1916                 // initialize the samplers to refer to the texture units we use
1917                 if (p->loc_Texture_First           >= 0) qglUniform1iARB(p->loc_Texture_First          , GL20TU_FIRST);
1918                 if (p->loc_Texture_Second          >= 0) qglUniform1iARB(p->loc_Texture_Second         , GL20TU_SECOND);
1919                 if (p->loc_Texture_GammaRamps      >= 0) qglUniform1iARB(p->loc_Texture_GammaRamps     , GL20TU_GAMMARAMPS);
1920                 if (p->loc_Texture_Normal          >= 0) qglUniform1iARB(p->loc_Texture_Normal         , GL20TU_NORMAL);
1921                 if (p->loc_Texture_Color           >= 0) qglUniform1iARB(p->loc_Texture_Color          , GL20TU_COLOR);
1922                 if (p->loc_Texture_Gloss           >= 0) qglUniform1iARB(p->loc_Texture_Gloss          , GL20TU_GLOSS);
1923                 if (p->loc_Texture_Glow            >= 0) qglUniform1iARB(p->loc_Texture_Glow           , GL20TU_GLOW);
1924                 if (p->loc_Texture_SecondaryNormal >= 0) qglUniform1iARB(p->loc_Texture_SecondaryNormal, GL20TU_SECONDARY_NORMAL);
1925                 if (p->loc_Texture_SecondaryColor  >= 0) qglUniform1iARB(p->loc_Texture_SecondaryColor , GL20TU_SECONDARY_COLOR);
1926                 if (p->loc_Texture_SecondaryGloss  >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGloss , GL20TU_SECONDARY_GLOSS);
1927                 if (p->loc_Texture_SecondaryGlow   >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGlow  , GL20TU_SECONDARY_GLOW);
1928                 if (p->loc_Texture_Pants           >= 0) qglUniform1iARB(p->loc_Texture_Pants          , GL20TU_PANTS);
1929                 if (p->loc_Texture_Shirt           >= 0) qglUniform1iARB(p->loc_Texture_Shirt          , GL20TU_SHIRT);
1930                 if (p->loc_Texture_FogMask         >= 0) qglUniform1iARB(p->loc_Texture_FogMask        , GL20TU_FOGMASK);
1931                 if (p->loc_Texture_Lightmap        >= 0) qglUniform1iARB(p->loc_Texture_Lightmap       , GL20TU_LIGHTMAP);
1932                 if (p->loc_Texture_Deluxemap       >= 0) qglUniform1iARB(p->loc_Texture_Deluxemap      , GL20TU_DELUXEMAP);
1933                 if (p->loc_Texture_Attenuation     >= 0) qglUniform1iARB(p->loc_Texture_Attenuation    , GL20TU_ATTENUATION);
1934                 if (p->loc_Texture_Cube            >= 0) qglUniform1iARB(p->loc_Texture_Cube           , GL20TU_CUBE);
1935                 if (p->loc_Texture_Refraction      >= 0) qglUniform1iARB(p->loc_Texture_Refraction     , GL20TU_REFRACTION);
1936                 if (p->loc_Texture_Reflection      >= 0) qglUniform1iARB(p->loc_Texture_Reflection     , GL20TU_REFLECTION);
1937                 if (p->loc_Texture_ShadowMapRect   >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapRect  , GL20TU_SHADOWMAPRECT);
1938                 if (p->loc_Texture_ShadowMapCube   >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapCube  , GL20TU_SHADOWMAPCUBE);
1939                 if (p->loc_Texture_ShadowMap2D     >= 0) qglUniform1iARB(p->loc_Texture_ShadowMap2D    , GL20TU_SHADOWMAP2D);
1940                 if (p->loc_Texture_CubeProjection  >= 0) qglUniform1iARB(p->loc_Texture_CubeProjection , GL20TU_CUBEPROJECTION);
1941                 CHECKGLERROR
1942                 if (developer.integer)
1943                         Con_Printf("GLSL shader %s compiled.\n", permutationname);
1944         }
1945         else
1946                 Con_Printf("GLSL shader %s failed!  some features may not work properly.\n", permutationname);
1947
1948         // free the strings
1949         if (vertexstring)
1950                 Mem_Free(vertexstring);
1951         if (geometrystring)
1952                 Mem_Free(geometrystring);
1953         if (fragmentstring)
1954                 Mem_Free(fragmentstring);
1955 }
1956
1957 void R_GLSL_Restart_f(void)
1958 {
1959         unsigned int i, limit;
1960         r_glsl_permutation_t *p;
1961         limit = Mem_ExpandableArray_IndexRange(&r_glsl_permutationarray);
1962         for (i = 0;i < limit;i++)
1963         {
1964                 if ((p = (r_glsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_glsl_permutationarray, i)))
1965                 {
1966                         GL_Backend_FreeProgram(p->program);
1967                         Mem_ExpandableArray_FreeRecord(&r_glsl_permutationarray, (void*)p);
1968                 }
1969         }
1970         memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
1971 }
1972
1973 void R_GLSL_DumpShader_f(void)
1974 {
1975         int i;
1976
1977         qfile_t *file = FS_OpenRealFile("glsl/default.glsl", "w", false);
1978         if(!file)
1979         {
1980                 Con_Printf("failed to write to glsl/default.glsl\n");
1981                 return;
1982         }
1983
1984         FS_Print(file, "/* The engine may define the following macros:\n");
1985         FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
1986         for (i = 0;i < SHADERMODE_COUNT;i++)
1987                 FS_Print(file, shadermodeinfo[i].pretext);
1988         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1989                 FS_Print(file, shaderpermutationinfo[i].pretext);
1990         FS_Print(file, "*/\n");
1991         FS_Print(file, builtinshaderstring);
1992         FS_Close(file);
1993
1994         Con_Printf("glsl/default.glsl written\n");
1995 }
1996
1997 void R_SetupShader_SetPermutation(unsigned int mode, unsigned int permutation)
1998 {
1999         r_glsl_permutation_t *perm = R_GLSL_FindPermutation(mode, permutation);
2000         if (r_glsl_permutation != perm)
2001         {
2002                 r_glsl_permutation = perm;
2003                 if (!r_glsl_permutation->program)
2004                 {
2005                         if (!r_glsl_permutation->compiled)
2006                                 R_GLSL_CompilePermutation(perm, mode, permutation);
2007                         if (!r_glsl_permutation->program)
2008                         {
2009                                 // remove features until we find a valid permutation
2010                                 int i;
2011                                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
2012                                 {
2013                                         // reduce i more quickly whenever it would not remove any bits
2014                                         int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
2015                                         if (!(permutation & j))
2016                                                 continue;
2017                                         permutation -= j;
2018                                         r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
2019                                         if (!r_glsl_permutation->compiled)
2020                                                 R_GLSL_CompilePermutation(perm, mode, permutation);
2021                                         if (r_glsl_permutation->program)
2022                                                 break;
2023                                 }
2024                                 if (i >= SHADERPERMUTATION_COUNT)
2025                                 {
2026                                         Con_Printf("OpenGL 2.0 shaders disabled - unable to find a working shader permutation fallback on this driver (set r_glsl 1 if you want to try again)\n");
2027                                         Cvar_SetValueQuick(&r_glsl, 0);
2028                                         R_GLSL_Restart_f(); // unload shaders
2029                                         return; // no bit left to clear
2030                                 }
2031                         }
2032                 }
2033                 CHECKGLERROR
2034                 qglUseProgramObjectARB(r_glsl_permutation->program);CHECKGLERROR
2035         }
2036 }
2037
2038 void R_SetupGenericShader(qboolean usetexture)
2039 {
2040         if (gl_support_fragment_shader)
2041         {
2042                 if (r_glsl.integer && r_glsl_usegeneric.integer)
2043                         R_SetupShader_SetPermutation(SHADERMODE_GENERIC, usetexture ? SHADERPERMUTATION_DIFFUSE : 0);
2044                 else if (r_glsl_permutation)
2045                 {
2046                         r_glsl_permutation = NULL;
2047                         qglUseProgramObjectARB(0);CHECKGLERROR
2048                 }
2049         }
2050 }
2051
2052 void R_SetupGenericTwoTextureShader(int texturemode)
2053 {
2054         if (gl_support_fragment_shader)
2055         {
2056                 if (r_glsl.integer && r_glsl_usegeneric.integer)
2057                         R_SetupShader_SetPermutation(SHADERMODE_GENERIC, SHADERPERMUTATION_DIFFUSE | SHADERPERMUTATION_SPECULAR | (r_shadow_glossexact.integer ? SHADERPERMUTATION_EXACTSPECULARMATH : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
2058                 else if (r_glsl_permutation)
2059                 {
2060                         r_glsl_permutation = NULL;
2061                         qglUseProgramObjectARB(0);CHECKGLERROR
2062                 }
2063         }
2064         if (!r_glsl_permutation)
2065         {
2066                 if (texturemode == GL_DECAL && gl_combine.integer)
2067                         texturemode = GL_INTERPOLATE_ARB;
2068                 R_Mesh_TexCombine(1, texturemode, texturemode, 1, 1);
2069         }
2070 }
2071
2072 void R_SetupDepthOrShadowShader(void)
2073 {
2074         if (gl_support_fragment_shader)
2075         {
2076                 if (r_glsl.integer && r_glsl_usegeneric.integer)
2077                         R_SetupShader_SetPermutation(SHADERMODE_DEPTH_OR_SHADOW, 0);
2078                 else if (r_glsl_permutation)
2079                 {
2080                         r_glsl_permutation = NULL;
2081                         qglUseProgramObjectARB(0);CHECKGLERROR
2082                 }
2083         }
2084 }
2085
2086 void R_SetupShowDepthShader(void)
2087 {
2088         if (gl_support_fragment_shader)
2089         {
2090                 if (r_glsl.integer && r_glsl_usegeneric.integer)
2091                         R_SetupShader_SetPermutation(SHADERMODE_SHOWDEPTH, 0);
2092                 else if (r_glsl_permutation)
2093                 {
2094                         r_glsl_permutation = NULL;
2095                         qglUseProgramObjectARB(0);CHECKGLERROR
2096                 }
2097         }
2098 }
2099
2100 extern rtexture_t *r_shadow_attenuationgradienttexture;
2101 extern rtexture_t *r_shadow_attenuation2dtexture;
2102 extern rtexture_t *r_shadow_attenuation3dtexture;
2103 extern qboolean r_shadow_usingshadowmaprect;
2104 extern qboolean r_shadow_usingshadowmapcube;
2105 extern qboolean r_shadow_usingshadowmap2d;
2106 extern float r_shadow_shadowmap_texturescale[2];
2107 extern float r_shadow_shadowmap_parameters[4];
2108 extern qboolean r_shadow_shadowmapvsdct;
2109 extern qboolean r_shadow_shadowmapsampler;
2110 extern int r_shadow_shadowmappcf;
2111 void R_SetupSurfaceShader(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale, rsurfacepass_t rsurfacepass)
2112 {
2113         // select a permutation of the lighting shader appropriate to this
2114         // combination of texture, entity, light source, and fogging, only use the
2115         // minimum features necessary to avoid wasting rendering time in the
2116         // fragment shader on features that are not being used
2117         unsigned int permutation = 0;
2118         unsigned int mode = 0;
2119         // TODO: implement geometry-shader based shadow volumes someday
2120         if (r_glsl_offsetmapping.integer)
2121         {
2122                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
2123                 if (r_glsl_offsetmapping_reliefmapping.integer)
2124                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
2125         }
2126         if (rsurfacepass == RSURFPASS_BACKGROUND)
2127         {
2128                 // distorted background
2129                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERSHADER)
2130                         mode = SHADERMODE_WATER;
2131                 else
2132                         mode = SHADERMODE_REFRACTION;
2133         }
2134         else if (rsurfacepass == RSURFPASS_RTLIGHT)
2135         {
2136                 // light source
2137                 mode = SHADERMODE_LIGHTSOURCE;
2138                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2139                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2140                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2141                         permutation |= SHADERPERMUTATION_CUBEFILTER;
2142                 if (diffusescale > 0)
2143                         permutation |= SHADERPERMUTATION_DIFFUSE;
2144                 if (specularscale > 0)
2145                         permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
2146                 if (r_refdef.fogenabled)
2147                         permutation |= r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE;
2148                 if (rsurface.texture->colormapping)
2149                         permutation |= SHADERPERMUTATION_COLORMAPPING;
2150                 if (r_shadow_usingshadowmaprect || r_shadow_usingshadowmap2d || r_shadow_usingshadowmapcube)
2151                 {
2152                         if (r_shadow_usingshadowmaprect)
2153                                 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
2154                         if (r_shadow_usingshadowmap2d)
2155                                 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
2156                         if (r_shadow_usingshadowmapcube)
2157                                 permutation |= SHADERPERMUTATION_SHADOWMAPCUBE;
2158                         else if(r_shadow_shadowmapvsdct)
2159                                 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
2160
2161                         if (r_shadow_shadowmapsampler)
2162                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
2163                         if (r_shadow_shadowmappcf > 1)
2164                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
2165                         else if (r_shadow_shadowmappcf)
2166                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
2167                 }
2168         }
2169         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
2170         {
2171                 // unshaded geometry (fullbright or ambient model lighting)
2172                 mode = SHADERMODE_FLATCOLOR;
2173                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2174                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2175                 if (rsurface.texture->currentskinframe->glow && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
2176                         permutation |= SHADERPERMUTATION_GLOW;
2177                 if (r_refdef.fogenabled)
2178                         permutation |= r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE;
2179                 if (rsurface.texture->colormapping)
2180                         permutation |= SHADERPERMUTATION_COLORMAPPING;
2181                 if (r_glsl_offsetmapping.integer)
2182                 {
2183                         permutation |= SHADERPERMUTATION_OFFSETMAPPING;
2184                         if (r_glsl_offsetmapping_reliefmapping.integer)
2185                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
2186                 }
2187                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
2188                         permutation |= SHADERPERMUTATION_REFLECTION;
2189         }
2190         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT_DIRECTIONAL)
2191         {
2192                 // directional model lighting
2193                 mode = SHADERMODE_LIGHTDIRECTION;
2194                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2195                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2196                 if (rsurface.texture->currentskinframe->glow && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
2197                         permutation |= SHADERPERMUTATION_GLOW;
2198                 permutation |= SHADERPERMUTATION_DIFFUSE;
2199                 if (specularscale > 0)
2200                         permutation |= SHADERPERMUTATION_SPECULAR;
2201                 if (r_refdef.fogenabled)
2202                         permutation |= r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE;
2203                 if (rsurface.texture->colormapping)
2204                         permutation |= SHADERPERMUTATION_COLORMAPPING;
2205                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
2206                         permutation |= SHADERPERMUTATION_REFLECTION;
2207         }
2208         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
2209         {
2210                 // ambient model lighting
2211                 mode = SHADERMODE_LIGHTDIRECTION;
2212                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2213                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2214                 if (rsurface.texture->currentskinframe->glow && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
2215                         permutation |= SHADERPERMUTATION_GLOW;
2216                 if (r_refdef.fogenabled)
2217                         permutation |= r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE;
2218                 if (rsurface.texture->colormapping)
2219                         permutation |= SHADERPERMUTATION_COLORMAPPING;
2220                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
2221                         permutation |= SHADERPERMUTATION_REFLECTION;
2222         }
2223         else
2224         {
2225                 // lightmapped wall
2226                 if (r_glsl_deluxemapping.integer >= 1 && rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping)
2227                 {
2228                         // deluxemapping (light direction texture)
2229                         if (rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping && r_refdef.scene.worldmodel->brushq3.deluxemapping_modelspace)
2230                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE;
2231                         else
2232                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
2233                         permutation |= SHADERPERMUTATION_DIFFUSE;
2234                         if (specularscale > 0)
2235                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
2236                 }
2237                 else if (r_glsl_deluxemapping.integer >= 2)
2238                 {
2239                         // fake deluxemapping (uniform light direction in tangentspace)
2240                         mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
2241                         permutation |= SHADERPERMUTATION_DIFFUSE;
2242                         if (specularscale > 0)
2243                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
2244                 }
2245                 else if (rsurface.uselightmaptexture)
2246                 {
2247                         // ordinary lightmapping (q1bsp, q3bsp)
2248                         mode = SHADERMODE_LIGHTMAP;
2249                 }
2250                 else
2251                 {
2252                         // ordinary vertex coloring (q3bsp)
2253                         mode = SHADERMODE_VERTEXCOLOR;
2254                 }
2255                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
2256                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
2257                 if (rsurface.texture->currentskinframe->glow && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
2258                         permutation |= SHADERPERMUTATION_GLOW;
2259                 if (r_refdef.fogenabled)
2260                         permutation |= r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE;
2261                 if (rsurface.texture->colormapping)
2262                         permutation |= SHADERPERMUTATION_COLORMAPPING;
2263                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
2264                         permutation |= SHADERPERMUTATION_REFLECTION;
2265         }
2266         if(permutation & SHADERPERMUTATION_SPECULAR)
2267                 if(r_shadow_glossexact.integer)
2268                         permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
2269         R_SetupShader_SetPermutation(mode, permutation);
2270         if (mode == SHADERMODE_LIGHTSOURCE)
2271         {
2272                 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
2273                 if (permutation & SHADERPERMUTATION_DIFFUSE)
2274                 {
2275                         if (r_glsl_permutation->loc_TintColor >= 0) qglUniform4fARB(r_glsl_permutation->loc_TintColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2], rsurface.texture->lightmapcolor[3]);
2276                         if (r_glsl_permutation->loc_AmbientScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, ambientscale);
2277                         if (r_glsl_permutation->loc_DiffuseScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, diffusescale);
2278                         if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, specularscale);
2279                 }
2280                 else
2281                 {
2282                         // ambient only is simpler
2283                         if (r_glsl_permutation->loc_TintColor >= 0) qglUniform4fARB(r_glsl_permutation->loc_TintColor, lightcolorbase[0] * ambientscale, lightcolorbase[1] * ambientscale, lightcolorbase[2] * ambientscale, rsurface.texture->lightmapcolor[3]);
2284                         if (r_glsl_permutation->loc_AmbientScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, 1);
2285                         if (r_glsl_permutation->loc_DiffuseScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, 0);
2286                         if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, 0);
2287                 }
2288                 // additive passes are only darkened by fog, not tinted
2289                 if (r_glsl_permutation->loc_FogColor >= 0)
2290                         qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
2291                 if (r_glsl_permutation->loc_ShadowMap_TextureScale >= 0) qglUniform2fARB(r_glsl_permutation->loc_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
2292                 if (r_glsl_permutation->loc_ShadowMap_Parameters >= 0) qglUniform4fARB(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]);
2293         }
2294         else
2295         {
2296                 if (mode == SHADERMODE_LIGHTDIRECTION)
2297                 {
2298                         if (r_glsl_permutation->loc_AmbientColor  >= 0) qglUniform3fARB(r_glsl_permutation->loc_AmbientColor , rsurface.modellight_ambient[0] * ambientscale  * 0.5f, rsurface.modellight_ambient[1] * ambientscale  * 0.5f, rsurface.modellight_ambient[2] * ambientscale  * 0.5f);
2299                         if (r_glsl_permutation->loc_DiffuseColor  >= 0) qglUniform3fARB(r_glsl_permutation->loc_DiffuseColor , rsurface.modellight_diffuse[0] * diffusescale  * 0.5f, rsurface.modellight_diffuse[1] * diffusescale  * 0.5f, rsurface.modellight_diffuse[2] * diffusescale  * 0.5f);
2300                         if (r_glsl_permutation->loc_SpecularColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_SpecularColor, rsurface.modellight_diffuse[0] * specularscale * 0.5f, rsurface.modellight_diffuse[1] * specularscale * 0.5f, rsurface.modellight_diffuse[2] * specularscale * 0.5f);
2301                         if (r_glsl_permutation->loc_LightDir      >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
2302                 }
2303                 else
2304                 {
2305                         if (r_glsl_permutation->loc_AmbientScale  >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, r_refdef.scene.ambient * 1.0f / 128.0f);
2306                         if (r_glsl_permutation->loc_DiffuseScale  >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, r_refdef.lightmapintensity);
2307                         if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, r_refdef.lightmapintensity * specularscale);
2308                 }
2309                 if (r_glsl_permutation->loc_TintColor >= 0) qglUniform4fARB(r_glsl_permutation->loc_TintColor, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2], rsurface.texture->lightmapcolor[3]);
2310                 if (r_glsl_permutation->loc_GlowColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_GlowColor, rsurface.glowmod[0] * r_hdr_glowintensity.value, rsurface.glowmod[1] * r_hdr_glowintensity.value, rsurface.glowmod[2] * r_hdr_glowintensity.value);
2311                 // additive passes are only darkened by fog, not tinted
2312                 if (r_glsl_permutation->loc_FogColor >= 0)
2313                 {
2314                         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
2315                                 qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
2316                         else
2317                                 qglUniform3fARB(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
2318                 }
2319                 if (r_glsl_permutation->loc_DistortScaleRefractReflect >= 0) qglUniform4fARB(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);
2320                 if (r_glsl_permutation->loc_ScreenScaleRefractReflect >= 0) qglUniform4fARB(r_glsl_permutation->loc_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
2321                 if (r_glsl_permutation->loc_ScreenCenterRefractReflect >= 0) qglUniform4fARB(r_glsl_permutation->loc_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
2322                 if (r_glsl_permutation->loc_RefractColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_RefractColor, 1, rsurface.texture->refractcolor4f);
2323                 if (r_glsl_permutation->loc_ReflectColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_ReflectColor, 1, rsurface.texture->reflectcolor4f);
2324                 if (r_glsl_permutation->loc_ReflectFactor >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
2325                 if (r_glsl_permutation->loc_ReflectOffset >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectOffset, rsurface.texture->reflectmin);
2326         }
2327         if (r_glsl_permutation->loc_SceneBrightness >= 0) qglUniform1fARB(r_glsl_permutation->loc_SceneBrightness, r_refdef.view.colorscale);
2328         if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
2329         if (r_glsl_permutation->loc_Color_Pants >= 0)
2330         {
2331                 if (rsurface.texture->currentskinframe->pants)
2332                         qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
2333                 else
2334                         qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
2335         }
2336         if (r_glsl_permutation->loc_Color_Shirt >= 0)
2337         {
2338                 if (rsurface.texture->currentskinframe->shirt)
2339                         qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
2340                 else
2341                         qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
2342         }
2343         if (r_glsl_permutation->loc_FogPlane >= 0) qglUniform4fARB(r_glsl_permutation->loc_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
2344         if (r_glsl_permutation->loc_FogPlaneViewDist >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogPlaneViewDist, rsurface.fogplaneviewdist);
2345         if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogRangeRecip, rsurface.fograngerecip);
2346         if (r_glsl_permutation->loc_FogHeightFade >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogHeightFade, rsurface.fogheightfade);
2347         if(permutation & SHADERPERMUTATION_EXACTSPECULARMATH)
2348         {
2349                 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * 0.25);
2350         }
2351         else
2352         {
2353                 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower);
2354         }
2355         if (r_glsl_permutation->loc_OffsetMapping_Scale >= 0) qglUniform1fARB(r_glsl_permutation->loc_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);
2356         CHECKGLERROR
2357 }
2358
2359 #define SKINFRAME_HASH 1024
2360
2361 typedef struct
2362 {
2363         int loadsequence; // incremented each level change
2364         memexpandablearray_t array;
2365         skinframe_t *hash[SKINFRAME_HASH];
2366 }
2367 r_skinframe_t;
2368 r_skinframe_t r_skinframe;
2369
2370 void R_SkinFrame_PrepareForPurge(void)
2371 {
2372         r_skinframe.loadsequence++;
2373         // wrap it without hitting zero
2374         if (r_skinframe.loadsequence >= 200)
2375                 r_skinframe.loadsequence = 1;
2376 }
2377
2378 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
2379 {
2380         if (!skinframe)
2381                 return;
2382         // mark the skinframe as used for the purging code
2383         skinframe->loadsequence = r_skinframe.loadsequence;
2384 }
2385
2386 void R_SkinFrame_Purge(void)
2387 {
2388         int i;
2389         skinframe_t *s;
2390         for (i = 0;i < SKINFRAME_HASH;i++)
2391         {
2392                 for (s = r_skinframe.hash[i];s;s = s->next)
2393                 {
2394                         if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
2395                         {
2396                                 if (s->merged == s->base)
2397                                         s->merged = NULL;
2398                                 // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
2399                                 R_PurgeTexture(s->stain );s->stain  = NULL;
2400                                 R_PurgeTexture(s->merged);s->merged = NULL;
2401                                 R_PurgeTexture(s->base  );s->base   = NULL;
2402                                 R_PurgeTexture(s->pants );s->pants  = NULL;
2403                                 R_PurgeTexture(s->shirt );s->shirt  = NULL;
2404                                 R_PurgeTexture(s->nmap  );s->nmap   = NULL;
2405                                 R_PurgeTexture(s->gloss );s->gloss  = NULL;
2406                                 R_PurgeTexture(s->glow  );s->glow   = NULL;
2407                                 R_PurgeTexture(s->fog   );s->fog    = NULL;
2408                                 s->loadsequence = 0;
2409                         }
2410                 }
2411         }
2412 }
2413
2414 skinframe_t *R_SkinFrame_FindNextByName( skinframe_t *last, const char *name ) {
2415         skinframe_t *item;
2416         char basename[MAX_QPATH];
2417
2418         Image_StripImageExtension(name, basename, sizeof(basename));
2419
2420         if( last == NULL ) {
2421                 int hashindex;
2422                 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
2423                 item = r_skinframe.hash[hashindex];
2424         } else {
2425                 item = last->next;
2426         }
2427
2428         // linearly search through the hash bucket
2429         for( ; item ; item = item->next ) {
2430                 if( !strcmp( item->basename, basename ) ) {
2431                         return item;
2432                 }
2433         }
2434         return NULL;
2435 }
2436
2437 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
2438 {
2439         skinframe_t *item;
2440         int hashindex;
2441         char basename[MAX_QPATH];
2442
2443         Image_StripImageExtension(name, basename, sizeof(basename));
2444
2445         hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
2446         for (item = r_skinframe.hash[hashindex];item;item = item->next)
2447                 if (!strcmp(item->basename, basename) && item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)
2448                         break;
2449
2450         if (!item) {
2451                 rtexture_t *dyntexture;
2452                 // check whether its a dynamic texture
2453                 dyntexture = CL_GetDynTexture( basename );
2454                 if (!add && !dyntexture)
2455                         return NULL;
2456                 item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
2457                 memset(item, 0, sizeof(*item));
2458                 strlcpy(item->basename, basename, sizeof(item->basename));
2459                 item->base = dyntexture; // either NULL or dyntexture handle
2460                 item->textureflags = textureflags;
2461                 item->comparewidth = comparewidth;
2462                 item->compareheight = compareheight;
2463                 item->comparecrc = comparecrc;
2464                 item->next = r_skinframe.hash[hashindex];
2465                 r_skinframe.hash[hashindex] = item;
2466         }
2467         else if( item->base == NULL )
2468         {
2469                 rtexture_t *dyntexture;
2470                 // check whether its a dynamic texture
2471                 // this only needs to be done because Purge doesnt delete skinframes - only sets the texture pointers to NULL and we need to restore it before returing.. [11/29/2007 Black]
2472                 dyntexture = CL_GetDynTexture( basename );
2473                 item->base = dyntexture; // either NULL or dyntexture handle
2474         }
2475
2476         R_SkinFrame_MarkUsed(item);
2477         return item;
2478 }
2479
2480 #define R_SKINFRAME_LOAD_AVERAGE_COLORS(cnt, getpixel) \
2481         { \
2482                 unsigned long long avgcolor[5], wsum; \
2483                 int pix, comp, w; \
2484                 avgcolor[0] = 0; \
2485                 avgcolor[1] = 0; \
2486                 avgcolor[2] = 0; \
2487                 avgcolor[3] = 0; \
2488                 avgcolor[4] = 0; \
2489                 wsum = 0; \
2490                 for(pix = 0; pix < cnt; ++pix) \
2491                 { \
2492                         w = 0; \
2493                         for(comp = 0; comp < 3; ++comp) \
2494                                 w += getpixel; \
2495                         if(w) /* ignore perfectly black pixels because that is better for model skins */ \
2496                         { \
2497                                 ++wsum; \
2498                                 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
2499                                 w = getpixel; \
2500                                 for(comp = 0; comp < 3; ++comp) \
2501                                         avgcolor[comp] += getpixel * w; \
2502                                 avgcolor[3] += w; \
2503                         } \
2504                         /* comp = 3; -- not needed, comp is always 3 when we get here */ \
2505                         avgcolor[4] += getpixel; \
2506                 } \
2507                 if(avgcolor[3] == 0) /* no pixels seen? even worse */ \
2508                         avgcolor[3] = 1; \
2509                 skinframe->avgcolor[0] = avgcolor[2] / (255.0 * avgcolor[3]); \
2510                 skinframe->avgcolor[1] = avgcolor[1] / (255.0 * avgcolor[3]); \
2511                 skinframe->avgcolor[2] = avgcolor[0] / (255.0 * avgcolor[3]); \
2512                 skinframe->avgcolor[3] = avgcolor[4] / (255.0 * cnt); \
2513         }
2514
2515 skinframe_t *R_SkinFrame_LoadExternal_CheckAlpha(const char *name, int textureflags, qboolean complain, qboolean *has_alpha)
2516 {
2517         // FIXME: it should be possible to disable loading various layers using
2518         // cvars, to prevent wasted loading time and memory usage if the user does
2519         // not want them
2520         qboolean loadnormalmap = true;
2521         qboolean loadgloss = true;
2522         qboolean loadpantsandshirt = true;
2523         qboolean loadglow = true;
2524         int j;
2525         unsigned char *pixels;
2526         unsigned char *bumppixels;
2527         unsigned char *basepixels = NULL;
2528         int basepixels_width;
2529         int basepixels_height;
2530         skinframe_t *skinframe;
2531
2532         if (has_alpha)
2533                 *has_alpha = false;
2534
2535         if (cls.state == ca_dedicated)
2536                 return NULL;
2537
2538         // return an existing skinframe if already loaded
2539         // if loading of the first image fails, don't make a new skinframe as it
2540         // would cause all future lookups of this to be missing
2541         skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
2542         if (skinframe && skinframe->base)
2543                 return skinframe;
2544
2545         basepixels = loadimagepixelsbgra(name, complain, true);
2546         if (basepixels == NULL)
2547                 return NULL;
2548
2549         if (developer_loading.integer)
2550                 Con_Printf("loading skin \"%s\"\n", name);
2551
2552         // we've got some pixels to store, so really allocate this new texture now
2553         if (!skinframe)
2554                 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, true);
2555         skinframe->stain = NULL;
2556         skinframe->merged = NULL;
2557         skinframe->base = r_texture_notexture;
2558         skinframe->pants = NULL;
2559         skinframe->shirt = NULL;
2560         skinframe->nmap = r_texture_blanknormalmap;
2561         skinframe->gloss = NULL;
2562         skinframe->glow = NULL;
2563         skinframe->fog = NULL;
2564
2565         basepixels_width = image_width;
2566         basepixels_height = image_height;
2567         skinframe->base = R_LoadTexture2D (r_main_texturepool, skinframe->basename, basepixels_width, basepixels_height, basepixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
2568
2569         if (textureflags & TEXF_ALPHA)
2570         {
2571                 for (j = 3;j < basepixels_width * basepixels_height * 4;j += 4)
2572                         if (basepixels[j] < 255)
2573                                 break;
2574                 if (j < basepixels_width * basepixels_height * 4)
2575                 {
2576                         // has transparent pixels
2577                         if (has_alpha)
2578                                 *has_alpha = true;
2579                         pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
2580                         for (j = 0;j < image_width * image_height * 4;j += 4)
2581                         {
2582                                 pixels[j+0] = 255;
2583                                 pixels[j+1] = 255;
2584                                 pixels[j+2] = 255;
2585                                 pixels[j+3] = basepixels[j+3];
2586                         }
2587                         skinframe->fog = R_LoadTexture2D (r_main_texturepool, va("%s_mask", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
2588                         Mem_Free(pixels);
2589                 }
2590         }
2591
2592         R_SKINFRAME_LOAD_AVERAGE_COLORS(basepixels_width * basepixels_height, basepixels[4 * pix + comp]);
2593         //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
2594
2595         // _norm is the name used by tenebrae and has been adopted as standard
2596         if (loadnormalmap)
2597         {
2598                 if ((pixels = loadimagepixelsbgra(va("%s_norm", skinframe->basename), false, false)) != NULL)
2599                 {
2600                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | skinframe->textureflags) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
2601                         Mem_Free(pixels);
2602                         pixels = NULL;
2603                 }
2604                 else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixelsbgra(va("%s_bump", skinframe->basename), false, false)) != NULL)
2605                 {
2606                         pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
2607                         Image_HeightmapToNormalmap_BGRA(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
2608                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | skinframe->textureflags) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
2609                         Mem_Free(pixels);
2610                         Mem_Free(bumppixels);
2611                 }
2612                 else if (r_shadow_bumpscale_basetexture.value > 0)
2613                 {
2614                         pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
2615                         Image_HeightmapToNormalmap_BGRA(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
2616                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), basepixels_width, basepixels_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | skinframe->textureflags) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
2617                         Mem_Free(pixels);
2618                 }
2619         }
2620         // _luma is supported for tenebrae compatibility
2621         // (I think it's a very stupid name, but oh well)
2622         // _glow is the preferred name
2623         if (loadglow          && ((pixels = loadimagepixelsbgra(va("%s_glow", skinframe->basename), false, false)) != NULL || (pixels = loadimagepixelsbgra(va("%s_luma", skinframe->basename), false, false)) != NULL)) {skinframe->glow = R_LoadTexture2D (r_main_texturepool, va("%s_glow", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_glow.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
2624         if (loadgloss         && (pixels = loadimagepixelsbgra(va("%s_gloss", skinframe->basename), false, false)) != NULL) {skinframe->gloss = R_LoadTexture2D (r_main_texturepool, va("%s_gloss", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_gloss.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
2625         if (loadpantsandshirt && (pixels = loadimagepixelsbgra(va("%s_pants", skinframe->basename), false, false)) != NULL) {skinframe->pants = R_LoadTexture2D (r_main_texturepool, va("%s_pants", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
2626         if (loadpantsandshirt && (pixels = loadimagepixelsbgra(va("%s_shirt", skinframe->basename), false, false)) != NULL) {skinframe->shirt = R_LoadTexture2D (r_main_texturepool, va("%s_shirt", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
2627
2628         if (basepixels)
2629                 Mem_Free(basepixels);
2630
2631         return skinframe;
2632 }
2633
2634 skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboolean complain)
2635 {
2636         return R_SkinFrame_LoadExternal_CheckAlpha(name, textureflags, complain, NULL);
2637 }
2638
2639 static rtexture_t *R_SkinFrame_TextureForSkinLayer(const unsigned char *in, int width, int height, const char *name, const unsigned int *palette, int textureflags, qboolean force)
2640 {
2641         int i;
2642         if (!force)
2643         {
2644                 for (i = 0;i < width*height;i++)
2645                         if (((unsigned char *)&palette[in[i]])[3] > 0)
2646                                 break;
2647                 if (i == width*height)
2648                         return NULL;
2649         }
2650         return R_LoadTexture2D (r_main_texturepool, name, width, height, in, TEXTYPE_PALETTE, textureflags, palette);
2651 }
2652
2653 // this is only used by .spr32 sprites, HL .spr files, HL .bsp files
2654 skinframe_t *R_SkinFrame_LoadInternalBGRA(const char *name, int textureflags, const unsigned char *skindata, int width, int height)
2655 {
2656         int i;
2657         unsigned char *temp1, *temp2;
2658         skinframe_t *skinframe;
2659
2660         if (cls.state == ca_dedicated)
2661                 return NULL;
2662
2663         // if already loaded just return it, otherwise make a new skinframe
2664         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*4) : 0, true);
2665         if (skinframe && skinframe->base)
2666                 return skinframe;
2667
2668         skinframe->stain = NULL;
2669         skinframe->merged = NULL;
2670         skinframe->base = r_texture_notexture;
2671         skinframe->pants = NULL;
2672         skinframe->shirt = NULL;
2673         skinframe->nmap = r_texture_blanknormalmap;
2674         skinframe->gloss = NULL;
2675         skinframe->glow = NULL;
2676         skinframe->fog = NULL;
2677
2678         // if no data was provided, then clearly the caller wanted to get a blank skinframe
2679         if (!skindata)
2680                 return NULL;
2681
2682         if (developer_loading.integer)
2683                 Con_Printf("loading 32bit skin \"%s\"\n", name);
2684
2685         if (r_shadow_bumpscale_basetexture.value > 0)
2686         {
2687                 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
2688                 temp2 = temp1 + width * height * 4;
2689                 Image_HeightmapToNormalmap_BGRA(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
2690                 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, skinframe->textureflags | TEXF_ALPHA, NULL);
2691                 Mem_Free(temp1);
2692         }
2693         skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_BGRA, skinframe->textureflags, NULL);
2694         if (textureflags & TEXF_ALPHA)
2695         {
2696                 for (i = 3;i < width * height * 4;i += 4)
2697                         if (skindata[i] < 255)
2698                                 break;
2699                 if (i < width * height * 4)
2700                 {
2701                         unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
2702                         memcpy(fogpixels, skindata, width * height * 4);
2703                         for (i = 0;i < width * height * 4;i += 4)
2704                                 fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
2705                         skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_BGRA, skinframe->textureflags, NULL);
2706                         Mem_Free(fogpixels);
2707                 }
2708         }
2709
2710         R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, skindata[4 * pix + comp]);
2711         //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
2712
2713         return skinframe;
2714 }
2715
2716 skinframe_t *R_SkinFrame_LoadInternalQuake(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height)
2717 {
2718         int i;
2719         unsigned char *temp1, *temp2;
2720         unsigned int *palette;
2721         skinframe_t *skinframe;
2722
2723         if (cls.state == ca_dedicated)
2724                 return NULL;
2725
2726         // if already loaded just return it, otherwise make a new skinframe
2727         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
2728         if (skinframe && skinframe->base)
2729                 return skinframe;
2730
2731         palette = (loadglowtexture ? palette_bgra_nofullbrights : ((skinframe->textureflags & TEXF_ALPHA) ? palette_bgra_transparent : palette_bgra_complete));
2732
2733         skinframe->stain = NULL;
2734         skinframe->merged = NULL;
2735         skinframe->base = r_texture_notexture;
2736         skinframe->pants = NULL;
2737         skinframe->shirt = NULL;
2738         skinframe->nmap = r_texture_blanknormalmap;
2739         skinframe->gloss = NULL;
2740         skinframe->glow = NULL;
2741         skinframe->fog = NULL;
2742
2743         // if no data was provided, then clearly the caller wanted to get a blank skinframe
2744         if (!skindata)
2745                 return NULL;
2746
2747         if (developer_loading.integer)
2748                 Con_Printf("loading quake skin \"%s\"\n", name);
2749
2750         if (r_shadow_bumpscale_basetexture.value > 0)
2751         {
2752                 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
2753                 temp2 = temp1 + width * height * 4;
2754                 // use either a custom palette or the quake palette
2755                 Image_Copy8bitBGRA(skindata, temp1, width * height, palette_bgra_complete);
2756                 Image_HeightmapToNormalmap_BGRA(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
2757                 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, skinframe->textureflags | TEXF_ALPHA, NULL);
2758                 Mem_Free(temp1);
2759         }
2760         // use either a custom palette, or the quake palette
2761         skinframe->base = skinframe->merged = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_merged", skinframe->basename), palette, skinframe->textureflags, true); // all
2762         if (loadglowtexture)
2763                 skinframe->glow = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_glow", skinframe->basename), palette_bgra_onlyfullbrights, skinframe->textureflags, false); // glow
2764         if (loadpantsandshirt)
2765         {
2766                 skinframe->pants = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_pants", skinframe->basename), palette_bgra_pantsaswhite, skinframe->textureflags, false); // pants
2767                 skinframe->shirt = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_shirt", skinframe->basename), palette_bgra_shirtaswhite, skinframe->textureflags, false); // shirt
2768         }
2769         if (skinframe->pants || skinframe->shirt)
2770                 skinframe->base = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_nospecial", skinframe->basename), loadglowtexture ? palette_bgra_nocolormapnofullbrights : palette_bgra_nocolormap, skinframe->textureflags, false); // no special colors
2771         if (textureflags & TEXF_ALPHA)
2772         {
2773                 for (i = 0;i < width * height;i++)
2774                         if (((unsigned char *)palette_bgra_alpha)[skindata[i]*4+3] < 255)
2775                                 break;
2776                 if (i < width * height)
2777                         skinframe->fog = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_fog", skinframe->basename), palette_bgra_alpha, skinframe->textureflags, true); // fog mask
2778         }
2779
2780         R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette)[skindata[pix]*4 + comp]);
2781         //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
2782
2783         return skinframe;
2784 }
2785
2786 skinframe_t *R_SkinFrame_LoadInternal8bit(const char *name, int textureflags, const unsigned char *skindata, int width, int height, const unsigned int *palette, const unsigned int *alphapalette)
2787 {
2788         int i;
2789         skinframe_t *skinframe;
2790
2791         if (cls.state == ca_dedicated)
2792                 return NULL;
2793
2794         // if already loaded just return it, otherwise make a new skinframe
2795         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
2796         if (skinframe && skinframe->base)
2797                 return skinframe;
2798
2799         skinframe->stain = NULL;
2800         skinframe->merged = NULL;
2801         skinframe->base = r_texture_notexture;
2802         skinframe->pants = NULL;
2803         skinframe->shirt = NULL;
2804         skinframe->nmap = r_texture_blanknormalmap;
2805         skinframe->gloss = NULL;
2806         skinframe->glow = NULL;
2807         skinframe->fog = NULL;
2808
2809         // if no data was provided, then clearly the caller wanted to get a blank skinframe
2810         if (!skindata)
2811                 return NULL;
2812
2813         if (developer_loading.integer)
2814                 Con_Printf("loading embedded 8bit image \"%s\"\n", name);
2815
2816         skinframe->base = skinframe->merged = R_SkinFrame_TextureForSkinLayer(skindata, width, height, skinframe->basename, palette, skinframe->textureflags, true);
2817         if (textureflags & TEXF_ALPHA)
2818         {
2819                 for (i = 0;i < width * height;i++)
2820                         if (((unsigned char *)alphapalette)[skindata[i]*4+3] < 255)
2821                                 break;
2822                 if (i < width * height)
2823                         skinframe->fog = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_fog", skinframe->basename), alphapalette, skinframe->textureflags, true); // fog mask
2824         }
2825
2826         R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette)[skindata[pix]*4 + comp]);
2827         //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
2828
2829         return skinframe;
2830 }
2831
2832 skinframe_t *R_SkinFrame_LoadMissing(void)
2833 {
2834         skinframe_t *skinframe;
2835
2836         if (cls.state == ca_dedicated)
2837                 return NULL;
2838
2839         skinframe = R_SkinFrame_Find("missing", TEXF_PRECACHE | TEXF_FORCENEAREST, 0, 0, 0, true);
2840         skinframe->stain = NULL;
2841         skinframe->merged = NULL;
2842         skinframe->base = r_texture_notexture;
2843         skinframe->pants = NULL;
2844         skinframe->shirt = NULL;
2845         skinframe->nmap = r_texture_blanknormalmap;
2846         skinframe->gloss = NULL;
2847         skinframe->glow = NULL;
2848         skinframe->fog = NULL;
2849
2850         skinframe->avgcolor[0] = rand() / RAND_MAX;
2851         skinframe->avgcolor[1] = rand() / RAND_MAX;
2852         skinframe->avgcolor[2] = rand() / RAND_MAX;
2853         skinframe->avgcolor[3] = 1;
2854
2855         return skinframe;
2856 }
2857
2858 void R_Main_FreeViewCache(void)
2859 {
2860         if (r_refdef.viewcache.entityvisible)
2861                 Mem_Free(r_refdef.viewcache.entityvisible);
2862         if (r_refdef.viewcache.world_pvsbits)
2863                 Mem_Free(r_refdef.viewcache.world_pvsbits);
2864         if (r_refdef.viewcache.world_leafvisible)
2865                 Mem_Free(r_refdef.viewcache.world_leafvisible);
2866         if (r_refdef.viewcache.world_surfacevisible)
2867                 Mem_Free(r_refdef.viewcache.world_surfacevisible);
2868         memset(&r_refdef.viewcache, 0, sizeof(r_refdef.viewcache));
2869 }
2870
2871 void R_Main_ResizeViewCache(void)
2872 {
2873         int numentities = r_refdef.scene.numentities;
2874         int numclusters = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusters : 1;
2875         int numleafs = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_leafs : 1;
2876         int numsurfaces = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->num_surfaces : 1;
2877         if (r_refdef.viewcache.maxentities < numentities)
2878         {
2879                 r_refdef.viewcache.maxentities = numentities;
2880                 if (r_refdef.viewcache.entityvisible)
2881                         Mem_Free(r_refdef.viewcache.entityvisible);
2882                 r_refdef.viewcache.entityvisible = Mem_Alloc(r_main_mempool, r_refdef.viewcache.maxentities);
2883         }
2884         if (r_refdef.viewcache.world_numclusters != numclusters)
2885         {
2886                 r_refdef.viewcache.world_numclusters = numclusters;
2887                 if (r_refdef.viewcache.world_pvsbits)
2888                         Mem_Free(r_refdef.viewcache.world_pvsbits);
2889                 r_refdef.viewcache.world_pvsbits = Mem_Alloc(r_main_mempool, (r_refdef.viewcache.world_numclusters+7)>>3);
2890         }
2891         if (r_refdef.viewcache.world_numleafs != numleafs)
2892         {
2893                 r_refdef.viewcache.world_numleafs = numleafs;
2894                 if (r_refdef.viewcache.world_leafvisible)
2895                         Mem_Free(r_refdef.viewcache.world_leafvisible);
2896                 r_refdef.viewcache.world_leafvisible = Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numleafs);
2897         }
2898         if (r_refdef.viewcache.world_numsurfaces != numsurfaces)
2899         {
2900                 r_refdef.viewcache.world_numsurfaces = numsurfaces;
2901                 if (r_refdef.viewcache.world_surfacevisible)
2902                         Mem_Free(r_refdef.viewcache.world_surfacevisible);
2903                 r_refdef.viewcache.world_surfacevisible = Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numsurfaces);
2904         }
2905 }
2906
2907 void gl_main_start(void)
2908 {
2909         r_numqueries = 0;
2910         r_maxqueries = 0;
2911         memset(r_queries, 0, sizeof(r_queries));
2912
2913         r_qwskincache = NULL;
2914         r_qwskincache_size = 0;
2915
2916         // set up r_skinframe loading system for textures
2917         memset(&r_skinframe, 0, sizeof(r_skinframe));
2918         r_skinframe.loadsequence = 1;
2919         Mem_ExpandableArray_NewArray(&r_skinframe.array, r_main_mempool, sizeof(skinframe_t), 256);
2920
2921         r_main_texturepool = R_AllocTexturePool();
2922         R_BuildBlankTextures();
2923         R_BuildNoTexture();
2924         if (gl_texturecubemap)
2925         {
2926                 R_BuildWhiteCube();
2927                 R_BuildNormalizationCube();
2928         }
2929         r_texture_fogattenuation = NULL;
2930         r_texture_gammaramps = NULL;
2931         //r_texture_fogintensity = NULL;
2932         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
2933         memset(&r_waterstate, 0, sizeof(r_waterstate));
2934         memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
2935         Mem_ExpandableArray_NewArray(&r_glsl_permutationarray, r_main_mempool, sizeof(r_glsl_permutation_t), 256);
2936         memset(&r_svbsp, 0, sizeof (r_svbsp));
2937
2938         r_refdef.fogmasktable_density = 0;
2939 }
2940
2941 extern rtexture_t *loadingscreentexture;
2942 void gl_main_shutdown(void)
2943 {
2944         R_Main_FreeViewCache();
2945
2946         if (r_maxqueries)
2947                 qglDeleteQueriesARB(r_maxqueries, r_queries);
2948
2949         r_numqueries = 0;
2950         r_maxqueries = 0;
2951         memset(r_queries, 0, sizeof(r_queries));
2952
2953         r_qwskincache = NULL;
2954         r_qwskincache_size = 0;
2955
2956         // clear out the r_skinframe state
2957         Mem_ExpandableArray_FreeArray(&r_skinframe.array);
2958         memset(&r_skinframe, 0, sizeof(r_skinframe));
2959
2960         if (r_svbsp.nodes)
2961                 Mem_Free(r_svbsp.nodes);
2962         memset(&r_svbsp, 0, sizeof (r_svbsp));
2963         R_FreeTexturePool(&r_main_texturepool);
2964         loadingscreentexture = NULL;
2965         r_texture_blanknormalmap = NULL;
2966         r_texture_white = NULL;
2967         r_texture_grey128 = NULL;
2968         r_texture_black = NULL;
2969         r_texture_whitecube = NULL;
2970         r_texture_normalizationcube = NULL;
2971         r_texture_fogattenuation = NULL;
2972         r_texture_gammaramps = NULL;
2973         //r_texture_fogintensity = NULL;
2974         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
2975         memset(&r_waterstate, 0, sizeof(r_waterstate));
2976         R_GLSL_Restart_f();
2977 }
2978
2979 extern void CL_ParseEntityLump(char *entitystring);
2980 void gl_main_newmap(void)
2981 {
2982         // FIXME: move this code to client
2983         int l;
2984         char *entities, entname[MAX_QPATH];
2985         if (r_qwskincache)
2986                 Mem_Free(r_qwskincache);
2987         r_qwskincache = NULL;
2988         r_qwskincache_size = 0;
2989         if (cl.worldmodel)
2990         {
2991                 strlcpy(entname, cl.worldmodel->name, sizeof(entname));
2992                 l = (int)strlen(entname) - 4;
2993                 if (l >= 0 && !strcmp(entname + l, ".bsp"))
2994                 {
2995                         memcpy(entname + l, ".ent", 5);
2996                         if ((entities = (char *)FS_LoadFile(entname, tempmempool, true, NULL)))
2997                         {
2998                                 CL_ParseEntityLump(entities);
2999                                 Mem_Free(entities);
3000                                 return;
3001                         }
3002                 }
3003                 if (cl.worldmodel->brush.entities)
3004                         CL_ParseEntityLump(cl.worldmodel->brush.entities);
3005         }
3006         R_Main_FreeViewCache();
3007 }
3008
3009 void GL_Main_Init(void)
3010 {
3011         r_main_mempool = Mem_AllocPool("Renderer", 0, NULL);
3012
3013         Cmd_AddCommand("r_glsl_restart", R_GLSL_Restart_f, "unloads GLSL shaders, they will then be reloaded as needed");
3014         Cmd_AddCommand("r_glsl_dumpshader", R_GLSL_DumpShader_f, "dumps the engine internal default.glsl shader into glsl/default.glsl");
3015         // FIXME: the client should set up r_refdef.fog stuff including the fogmasktable
3016         if (gamemode == GAME_NEHAHRA)
3017         {
3018                 Cvar_RegisterVariable (&gl_fogenable);
3019                 Cvar_RegisterVariable (&gl_fogdensity);
3020                 Cvar_RegisterVariable (&gl_fogred);
3021                 Cvar_RegisterVariable (&gl_foggreen);
3022                 Cvar_RegisterVariable (&gl_fogblue);
3023                 Cvar_RegisterVariable (&gl_fogstart);
3024                 Cvar_RegisterVariable (&gl_fogend);
3025                 Cvar_RegisterVariable (&gl_skyclip);
3026         }
3027         Cvar_RegisterVariable(&r_motionblur);
3028         Cvar_RegisterVariable(&r_motionblur_maxblur);
3029         Cvar_RegisterVariable(&r_motionblur_bmin);
3030         Cvar_RegisterVariable(&r_motionblur_vmin);
3031         Cvar_RegisterVariable(&r_motionblur_vmax);
3032         Cvar_RegisterVariable(&r_motionblur_vcoeff);
3033         Cvar_RegisterVariable(&r_motionblur_randomize);
3034         Cvar_RegisterVariable(&r_damageblur);
3035         Cvar_RegisterVariable(&r_equalize_entities_fullbright);
3036         Cvar_RegisterVariable(&r_equalize_entities_minambient);
3037         Cvar_RegisterVariable(&r_equalize_entities_by);
3038         Cvar_RegisterVariable(&r_equalize_entities_to);
3039         Cvar_RegisterVariable(&r_animcache);
3040         Cvar_RegisterVariable(&r_depthfirst);
3041         Cvar_RegisterVariable(&r_useinfinitefarclip);
3042         Cvar_RegisterVariable(&r_farclip_base);
3043         Cvar_RegisterVariable(&r_farclip_world);
3044         Cvar_RegisterVariable(&r_nearclip);
3045         Cvar_RegisterVariable(&r_showbboxes);
3046         Cvar_RegisterVariable(&r_showsurfaces);
3047         Cvar_RegisterVariable(&r_showtris);
3048         Cvar_RegisterVariable(&r_shownormals);
3049         Cvar_RegisterVariable(&r_showlighting);
3050         Cvar_RegisterVariable(&r_showshadowvolumes);
3051         Cvar_RegisterVariable(&r_showcollisionbrushes);
3052         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonfactor);
3053         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonoffset);
3054         Cvar_RegisterVariable(&r_showdisabledepthtest);
3055         Cvar_RegisterVariable(&r_drawportals);
3056         Cvar_RegisterVariable(&r_drawentities);
3057         Cvar_RegisterVariable(&r_cullentities_trace);
3058         Cvar_RegisterVariable(&r_cullentities_trace_samples);
3059         Cvar_RegisterVariable(&r_cullentities_trace_tempentitysamples);
3060         Cvar_RegisterVariable(&r_cullentities_trace_enlarge);
3061         Cvar_RegisterVariable(&r_cullentities_trace_delay);
3062         Cvar_RegisterVariable(&r_drawviewmodel);
3063         Cvar_RegisterVariable(&r_speeds);
3064         Cvar_RegisterVariable(&r_fullbrights);
3065         Cvar_RegisterVariable(&r_wateralpha);
3066         Cvar_RegisterVariable(&r_dynamic);
3067         Cvar_RegisterVariable(&r_fullbright);
3068         Cvar_RegisterVariable(&r_shadows);
3069         Cvar_RegisterVariable(&r_shadows_darken);
3070         Cvar_RegisterVariable(&r_shadows_drawafterrtlighting);
3071         Cvar_RegisterVariable(&r_shadows_castfrombmodels);
3072         Cvar_RegisterVariable(&r_shadows_throwdistance);
3073         Cvar_RegisterVariable(&r_shadows_throwdirection);
3074         Cvar_RegisterVariable(&r_q1bsp_skymasking);
3075         Cvar_RegisterVariable(&r_polygonoffset_submodel_factor);
3076         Cvar_RegisterVariable(&r_polygonoffset_submodel_offset);
3077         Cvar_RegisterVariable(&r_polygonoffset_decals_factor);
3078         Cvar_RegisterVariable(&r_polygonoffset_decals_offset);
3079         Cvar_RegisterVariable(&r_fog_exp2);
3080         Cvar_RegisterVariable(&r_drawfog);
3081         Cvar_RegisterVariable(&r_textureunits);
3082         Cvar_RegisterVariable(&r_glsl);
3083         Cvar_RegisterVariable(&r_glsl_deluxemapping);
3084         Cvar_RegisterVariable(&r_glsl_offsetmapping);
3085         Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping);
3086         Cvar_RegisterVariable(&r_glsl_offsetmapping_scale);
3087         Cvar_RegisterVariable(&r_glsl_postprocess);
3088         Cvar_RegisterVariable(&r_glsl_postprocess_uservec1);
3089         Cvar_RegisterVariable(&r_glsl_postprocess_uservec2);
3090         Cvar_RegisterVariable(&r_glsl_postprocess_uservec3);
3091         Cvar_RegisterVariable(&r_glsl_postprocess_uservec4);
3092         Cvar_RegisterVariable(&r_glsl_usegeneric);
3093         Cvar_RegisterVariable(&r_water);
3094         Cvar_RegisterVariable(&r_water_resolutionmultiplier);
3095         Cvar_RegisterVariable(&r_water_clippingplanebias);
3096         Cvar_RegisterVariable(&r_water_refractdistort);
3097         Cvar_RegisterVariable(&r_water_reflectdistort);
3098         Cvar_RegisterVariable(&r_lerpsprites);
3099         Cvar_RegisterVariable(&r_lerpmodels);
3100         Cvar_RegisterVariable(&r_lerplightstyles);
3101         Cvar_RegisterVariable(&r_waterscroll);
3102         Cvar_RegisterVariable(&r_bloom);
3103         Cvar_RegisterVariable(&r_bloom_colorscale);
3104         Cvar_RegisterVariable(&r_bloom_brighten);
3105         Cvar_RegisterVariable(&r_bloom_blur);
3106         Cvar_RegisterVariable(&r_bloom_resolution);
3107         Cvar_RegisterVariable(&r_bloom_colorexponent);
3108         Cvar_RegisterVariable(&r_bloom_colorsubtract);
3109         Cvar_RegisterVariable(&r_hdr);
3110         Cvar_RegisterVariable(&r_hdr_scenebrightness);
3111         Cvar_RegisterVariable(&r_hdr_glowintensity);
3112         Cvar_RegisterVariable(&r_hdr_range);
3113         Cvar_RegisterVariable(&r_smoothnormals_areaweighting);
3114         Cvar_RegisterVariable(&developer_texturelogging);
3115         Cvar_RegisterVariable(&gl_lightmaps);
3116         Cvar_RegisterVariable(&r_test);
3117         Cvar_RegisterVariable(&r_batchmode);
3118         Cvar_RegisterVariable(&r_glsl_saturation);
3119         if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
3120                 Cvar_SetValue("r_fullbrights", 0);
3121         R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap);
3122
3123         Cvar_RegisterVariable(&r_track_sprites);
3124         Cvar_RegisterVariable(&r_track_sprites_flags);
3125         Cvar_RegisterVariable(&r_track_sprites_scalew);
3126         Cvar_RegisterVariable(&r_track_sprites_scaleh);
3127 }
3128
3129 extern void R_Textures_Init(void);
3130 extern void GL_Draw_Init(void);
3131 extern void GL_Main_Init(void);
3132 extern void R_Shadow_Init(void);
3133 extern void R_Sky_Init(void);
3134 extern void GL_Surf_Init(void);
3135 extern void R_Particles_Init(void);
3136 extern void R_Explosion_Init(void);
3137 extern void gl_backend_init(void);
3138 extern void Sbar_Init(void);
3139 extern void R_LightningBeams_Init(void);
3140 extern void Mod_RenderInit(void);
3141
3142 void Render_Init(void)
3143 {
3144         gl_backend_init();
3145         R_Textures_Init();
3146         GL_Main_Init();
3147         GL_Draw_Init();
3148         R_Shadow_Init();
3149         R_Sky_Init();
3150         GL_Surf_Init();
3151         Sbar_Init();
3152         R_Particles_Init();
3153         R_Explosion_Init();
3154         R_LightningBeams_Init();
3155         Mod_RenderInit();
3156 }
3157
3158 /*
3159 ===============
3160 GL_Init
3161 ===============
3162 */
3163 extern char *ENGINE_EXTENSIONS;
3164 void GL_Init (void)
3165 {
3166         gl_renderer = (const char *)qglGetString(GL_RENDERER);
3167         gl_vendor = (const char *)qglGetString(GL_VENDOR);
3168         gl_version = (const char *)qglGetString(GL_VERSION);
3169         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
3170
3171         if (!gl_extensions)
3172                 gl_extensions = "";
3173         if (!gl_platformextensions)
3174                 gl_platformextensions = "";
3175
3176         Con_Printf("GL_VENDOR: %s\n", gl_vendor);
3177         Con_Printf("GL_RENDERER: %s\n", gl_renderer);
3178         Con_Printf("GL_VERSION: %s\n", gl_version);
3179         Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
3180         Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
3181
3182         VID_CheckExtensions();
3183
3184         // LordHavoc: report supported extensions
3185         Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
3186
3187         // clear to black (loading plaque will be seen over this)
3188         CHECKGLERROR
3189         qglClearColor(0,0,0,1);CHECKGLERROR
3190         qglClear(GL_COLOR_BUFFER_BIT);CHECKGLERROR
3191 }
3192
3193 int R_CullBox(const vec3_t mins, const vec3_t maxs)
3194 {
3195         int i;
3196         mplane_t *p;
3197         for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
3198         {
3199                 // skip nearclip plane, it often culls portals when you are very close, and is almost never useful
3200                 if (i == 4)
3201                         continue;
3202                 p = r_refdef.view.frustum + i;
3203                 switch(p->signbits)
3204                 {
3205                 default:
3206                 case 0:
3207                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
3208                                 return true;
3209                         break;
3210                 case 1:
3211                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
3212                                 return true;
3213                         break;
3214                 case 2:
3215                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
3216                                 return true;
3217                         break;
3218                 case 3:
3219                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
3220                                 return true;
3221                         break;
3222                 case 4:
3223                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
3224                                 return true;
3225                         break;
3226                 case 5:
3227                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
3228                                 return true;
3229                         break;
3230                 case 6:
3231                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
3232                                 return true;
3233                         break;
3234                 case 7:
3235                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
3236                                 return true;
3237                         break;
3238                 }
3239         }
3240         return false;
3241 }
3242
3243 int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, const mplane_t *planes)
3244 {
3245         int i;
3246         const mplane_t *p;
3247         for (i = 0;i < numplanes;i++)
3248         {
3249                 p = planes + i;
3250                 switch(p->signbits)
3251                 {
3252                 default:
3253                 case 0:
3254                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
3255                                 return true;
3256                         break;
3257                 case 1:
3258                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
3259                                 return true;
3260                         break;
3261                 case 2:
3262                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
3263                                 return true;
3264                         break;
3265                 case 3:
3266                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
3267                                 return true;
3268                         break;
3269                 case 4:
3270                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
3271                                 return true;
3272                         break;
3273                 case 5:
3274                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
3275                                 return true;
3276                         break;
3277                 case 6:
3278                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
3279                                 return true;
3280                         break;
3281                 case 7:
3282                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
3283                                 return true;
3284                         break;
3285                 }
3286         }
3287         return false;
3288 }
3289
3290 //==================================================================================
3291
3292 // LordHavoc: animcache written by Echon, refactored and reformatted by me
3293
3294 /**
3295  * Animation cache helps save re-animating a player mesh if it's re-rendered again in a given frame
3296  * (reflections, lighting, etc). All animation cache becomes invalid on the next frame and is flushed
3297  * (well, over-wrote). The memory for each cache is kept around to save on allocation thrashing.
3298  */
3299
3300 typedef struct r_animcache_entity_s
3301 {
3302         float *vertex3f;
3303         float *normal3f;
3304         float *svector3f;
3305         float *tvector3f;
3306         int maxvertices;
3307         qboolean wantnormals;
3308         qboolean wanttangents;
3309 }
3310 r_animcache_entity_t;
3311
3312 typedef struct r_animcache_s
3313 {
3314         r_animcache_entity_t entity[MAX_EDICTS];
3315         int maxindex;
3316         int currentindex;
3317 }
3318 r_animcache_t;
3319
3320 static r_animcache_t r_animcachestate;
3321
3322 void R_AnimCache_Free(void)
3323 {
3324         int idx;
3325         for (idx=0 ; idx<r_animcachestate.maxindex ; idx++)
3326         {
3327                 r_animcachestate.entity[idx].maxvertices = 0;
3328                 Mem_Free(r_animcachestate.entity[idx].vertex3f);
3329                 r_animcachestate.entity[idx].vertex3f = NULL;
3330                 r_animcachestate.entity[idx].normal3f = NULL;
3331                 r_animcachestate.entity[idx].svector3f = NULL;
3332                 r_animcachestate.entity[idx].tvector3f = NULL;
3333         }
3334         r_animcachestate.currentindex = 0;
3335         r_animcachestate.maxindex = 0;
3336 }
3337
3338 void R_AnimCache_ResizeEntityCache(const int cacheIdx, const int numvertices)
3339 {
3340         int arraySize;
3341         float *base;
3342         r_animcache_entity_t *cache = &r_animcachestate.entity[cacheIdx];
3343
3344         if (cache->maxvertices >= numvertices)
3345                 return;
3346
3347         // Release existing memory
3348         if (cache->vertex3f)
3349                 Mem_Free(cache->vertex3f);
3350
3351         // Pad by 1024 verts
3352         cache->maxvertices = (numvertices + 1023) & ~1023;
3353         arraySize = cache->maxvertices * 3;
3354
3355         // Allocate, even if we don't need this memory in this instance it will get ignored and potentially used later
3356         base = (float *)Mem_Alloc(r_main_mempool, arraySize * sizeof(float) * 4);
3357         r_animcachestate.entity[cacheIdx].vertex3f = base;
3358         r_animcachestate.entity[cacheIdx].normal3f = base + arraySize;
3359         r_animcachestate.entity[cacheIdx].svector3f = base + arraySize*2;
3360         r_animcachestate.entity[cacheIdx].tvector3f = base + arraySize*3;
3361
3362 //      Con_Printf("allocated cache for %i (%f KB)\n", cacheIdx, (arraySize*sizeof(float)*4)/1024.0f);
3363 }
3364
3365 void R_AnimCache_NewFrame(void)
3366 {
3367         int i;
3368
3369         if (r_animcache.integer && r_drawentities.integer)
3370                 r_animcachestate.maxindex = sizeof(r_animcachestate.entity) / sizeof(r_animcachestate.entity[0]);
3371         else if (r_animcachestate.maxindex)
3372                 R_AnimCache_Free();
3373
3374         r_animcachestate.currentindex = 0;
3375
3376         for (i = 0;i < r_refdef.scene.numentities;i++)
3377                 r_refdef.scene.entities[i]->animcacheindex = -1;
3378 }
3379
3380 qboolean R_AnimCache_GetEntity(entity_render_t *ent, qboolean wantnormals, qboolean wanttangents)
3381 {
3382         dp_model_t *model = ent->model;
3383         r_animcache_entity_t *c;
3384         // see if it's already cached this frame
3385         if (ent->animcacheindex >= 0)
3386         {
3387                 // add normals/tangents if needed
3388                 c = r_animcachestate.entity + ent->animcacheindex;
3389                 if (c->wantnormals)
3390                         wantnormals = false;
3391                 if (c->wanttangents)
3392                         wanttangents = false;
3393                 if (wantnormals || wanttangents)
3394                         model->AnimateVertices(model, ent->frameblend, NULL, wantnormals ? c->normal3f : NULL, wanttangents ? c->svector3f : NULL, wanttangents ? c->tvector3f : NULL);
3395         }
3396         else
3397         {
3398                 // see if this ent is worth caching
3399                 if (r_animcachestate.maxindex <= r_animcachestate.currentindex)
3400                         return false;
3401                 if (!model || !model->Draw || !model->surfmesh.isanimated || !model->AnimateVertices || (ent->frameblend[0].lerp == 1 && ent->frameblend[0].subframe == 0))
3402                         return false;
3403                 // assign it a cache entry and make sure the arrays are big enough
3404                 R_AnimCache_ResizeEntityCache(r_animcachestate.currentindex, model->surfmesh.num_vertices);
3405                 ent->animcacheindex = r_animcachestate.currentindex++;
3406                 c = r_animcachestate.entity + ent->animcacheindex;
3407                 c->wantnormals = wantnormals;
3408                 c->wanttangents = wanttangents;
3409                 model->AnimateVertices(model, ent->frameblend, c->vertex3f, wantnormals ? c->normal3f : NULL, wanttangents ? c->svector3f : NULL, wanttangents ? c->tvector3f : NULL);
3410         }
3411         return true;
3412 }
3413
3414 void R_AnimCache_CacheVisibleEntities(void)
3415 {
3416         int i;
3417         qboolean wantnormals;
3418         qboolean wanttangents;
3419
3420         if (!r_animcachestate.maxindex)
3421                 return;
3422
3423         wantnormals = !r_showsurfaces.integer;
3424         wanttangents = !r_showsurfaces.integer && (r_glsl.integer || r_refdef.scene.rtworld || r_refdef.scene.rtdlight);
3425
3426         // TODO: thread this?
3427
3428         for (i = 0;i < r_refdef.scene.numentities;i++)
3429         {
3430                 if (!r_refdef.viewcache.entityvisible[i])
3431                         continue;
3432                 R_AnimCache_GetEntity(r_refdef.scene.entities[i], wantnormals, wanttangents);
3433         }
3434 }
3435
3436 //==================================================================================
3437
3438 static void R_View_UpdateEntityLighting (void)
3439 {
3440         int i;
3441         entity_render_t *ent;
3442         vec3_t tempdiffusenormal, avg;
3443         vec_t f, fa, fd, fdd;
3444
3445         for (i = 0;i < r_refdef.scene.numentities;i++)
3446         {
3447                 ent = r_refdef.scene.entities[i];
3448
3449                 // skip unseen models
3450                 if (!r_refdef.viewcache.entityvisible[i] && r_shadows.integer != 1)
3451                         continue;
3452
3453                 // skip bsp models
3454                 if (ent->model && ent->model->brush.num_leafs)
3455                 {
3456                         // TODO: use modellight for r_ambient settings on world?
3457                         VectorSet(ent->modellight_ambient, 0, 0, 0);
3458                         VectorSet(ent->modellight_diffuse, 0, 0, 0);
3459                         VectorSet(ent->modellight_lightdir, 0, 0, 1);
3460                         continue;
3461                 }
3462
3463                 // fetch the lighting from the worldmodel data
3464                 VectorSet(ent->modellight_ambient, r_refdef.scene.ambient * (2.0f / 128.0f), r_refdef.scene.ambient * (2.0f / 128.0f), r_refdef.scene.ambient * (2.0f / 128.0f));
3465                 VectorClear(ent->modellight_diffuse);
3466                 VectorClear(tempdiffusenormal);
3467                 if ((ent->flags & RENDER_LIGHT) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.LightPoint)
3468                 {
3469                         vec3_t org;
3470                         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
3471                         r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, org, ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal);
3472                         if(ent->flags & RENDER_EQUALIZE)
3473                         {
3474                                 // first fix up ambient lighting...
3475                                 if(r_equalize_entities_minambient.value > 0)
3476                                 {
3477                                         fd = 0.299f * ent->modellight_diffuse[0] + 0.587f * ent->modellight_diffuse[1] + 0.114f * ent->modellight_diffuse[2];
3478                                         if(fd > 0)
3479                                         {
3480                                                 fa = (0.299f * ent->modellight_ambient[0] + 0.587f * ent->modellight_ambient[1] + 0.114f * ent->modellight_ambient[2]);
3481                                                 if(fa < r_equalize_entities_minambient.value * fd)
3482                                                 {
3483                                                         // solve:
3484                                                         //   fa'/fd' = minambient
3485                                                         //   fa'+0.25*fd' = fa+0.25*fd
3486                                                         //   ...
3487                                                         //   fa' = fd' * minambient
3488                                                         //   fd'*(0.25+minambient) = fa+0.25*fd
3489                                                         //   ...
3490                                                         //   fd' = (fa+0.25*fd) * 1 / (0.25+minambient)
3491                                                         //   fa' = (fa+0.25*fd) * minambient / (0.25+minambient)
3492                                                         //   ...
3493                                                         fdd = (fa + 0.25f * fd) / (0.25f + r_equalize_entities_minambient.value);
3494                                                         f = fdd / fd; // f>0 because all this is additive; f<1 because fdd<fd because this follows from fa < r_equalize_entities_minambient.value * fd
3495                                                         VectorMA(ent->modellight_ambient, (1-f)*0.25f, ent->modellight_diffuse, ent->modellight_ambient);
3496                                                         VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
3497                                                 }
3498                                         }
3499                                 }
3500
3501                                 if(r_equalize_entities_to.value > 0 && r_equalize_entities_by.value != 0)
3502                                 {
3503                                         VectorMA(ent->modellight_ambient, 0.25f, ent->modellight_diffuse, avg);
3504                                         f = 0.299f * avg[0] + 0.587f * avg[1] + 0.114f * avg[2];
3505                                         if(f > 0)
3506                                         {
3507                                                 f = pow(f / r_equalize_entities_to.value, -r_equalize_entities_by.value);
3508                                                 VectorScale(ent->modellight_ambient, f, ent->modellight_ambient);
3509                                                 VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
3510                                         }
3511                                 }
3512                         }
3513                 }
3514                 else // highly rare
3515                         VectorSet(ent->modellight_ambient, 1, 1, 1);
3516
3517                 // move the light direction into modelspace coordinates for lighting code
3518                 Matrix4x4_Transform3x3(&ent->inversematrix, tempdiffusenormal, ent->modellight_lightdir);
3519                 if(VectorLength2(ent->modellight_lightdir) == 0)
3520                         VectorSet(ent->modellight_lightdir, 0, 0, 1); // have to set SOME valid vector here
3521                 VectorNormalize(ent->modellight_lightdir);
3522         }
3523 }
3524
3525 #define MAX_LINEOFSIGHTTRACES 64
3526
3527 static qboolean R_CanSeeBox(int numsamples, vec_t enlarge, vec3_t eye, vec3_t entboxmins, vec3_t entboxmaxs)
3528 {
3529         int i;
3530         vec3_t boxmins, boxmaxs;
3531         vec3_t start;
3532         vec3_t end;
3533         dp_model_t *model = r_refdef.scene.worldmodel;
3534         
3535         if (!model || !model->brush.TraceLineOfSight)
3536                 return true;
3537
3538         // expand the box a little
3539         boxmins[0] = (enlarge+1) * entboxmins[0] - enlarge * entboxmaxs[0];
3540         boxmaxs[0] = (enlarge+1) * entboxmaxs[0] - enlarge * entboxmins[0];
3541         boxmins[1] = (enlarge+1) * entboxmins[1] - enlarge * entboxmaxs[1];
3542         boxmaxs[1] = (enlarge+1) * entboxmaxs[1] - enlarge * entboxmins[1];
3543         boxmins[2] = (enlarge+1) * entboxmins[2] - enlarge * entboxmaxs[2];
3544         boxmaxs[2] = (enlarge+1) * entboxmaxs[2] - enlarge * entboxmins[2];
3545
3546         // try center
3547         VectorCopy(eye, start);
3548         VectorMAM(0.5f, boxmins, 0.5f, boxmaxs, end);
3549         if (model->brush.TraceLineOfSight(model, start, end))
3550                 return true;
3551
3552         // try various random positions
3553         for (i = 0;i < numsamples;i++)
3554         {
3555                 VectorSet(end, lhrandom(boxmins[0], boxmaxs[0]), lhrandom(boxmins[1], boxmaxs[1]), lhrandom(boxmins[2], boxmaxs[2]));
3556                 if (model->brush.TraceLineOfSight(model, start, end))
3557                         return true;
3558         }
3559
3560         return false;
3561 }
3562
3563
3564 static void R_View_UpdateEntityVisible (void)
3565 {
3566         int i;
3567         int renderimask;
3568         int samples;
3569         entity_render_t *ent;
3570
3571         if (!r_drawentities.integer)
3572                 return;
3573
3574         renderimask = r_refdef.envmap ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL) : ((chase_active.integer || r_waterstate.renderingscene) ? RENDER_VIEWMODEL : RENDER_EXTERIORMODEL);
3575         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs)
3576         {
3577                 // worldmodel can check visibility
3578                 memset(r_refdef.viewcache.entityvisible, 0, r_refdef.scene.numentities);
3579                 for (i = 0;i < r_refdef.scene.numentities;i++)
3580                 {
3581                         ent = r_refdef.scene.entities[i];
3582                         if (!(ent->flags & renderimask))
3583                         if (!R_CullBox(ent->mins, ent->maxs) || (ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)))
3584                         if ((ent->flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL)) || r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs(r_refdef.scene.worldmodel, r_refdef.viewcache.world_leafvisible, ent->mins, ent->maxs))
3585                                 r_refdef.viewcache.entityvisible[i] = true;
3586                 }
3587                 if(r_cullentities_trace.integer && r_refdef.scene.worldmodel->brush.TraceLineOfSight)
3588                 {
3589                         for (i = 0;i < r_refdef.scene.numentities;i++)
3590                         {
3591                                 ent = r_refdef.scene.entities[i];
3592                                 if(r_refdef.viewcache.entityvisible[i] && !(ent->flags & (RENDER_VIEWMODEL | RENDER_NOCULL | RENDER_NODEPTHTEST)) && !(ent->model && (ent->model->name[0] == '*')))
3593                                 {
3594                                         samples = ent->entitynumber ? r_cullentities_trace_samples.integer : r_cullentities_trace_tempentitysamples.integer;
3595                                         if (samples < 0)
3596                                                 continue; // temp entities do pvs only
3597                                         if(R_CanSeeBox(samples, r_cullentities_trace_enlarge.value, r_refdef.view.origin, ent->mins, ent->maxs))
3598                                                 ent->last_trace_visibility = realtime;
3599                                         if(ent->last_trace_visibility < realtime - r_cullentities_trace_delay.value)
3600                                                 r_refdef.viewcache.entityvisible[i] = 0;
3601                                 }
3602                         }
3603                 }
3604         }
3605         else
3606         {
3607                 // no worldmodel or it can't check visibility
3608                 for (i = 0;i < r_refdef.scene.numentities;i++)
3609                 {
3610                         ent = r_refdef.scene.entities[i];
3611                         r_refdef.viewcache.entityvisible[i] = !(ent->flags & renderimask) && ((ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)) || !R_CullBox(ent->mins, ent->maxs));
3612                 }
3613         }
3614 }
3615
3616 /// only used if skyrendermasked, and normally returns false
3617 int R_DrawBrushModelsSky (void)
3618 {
3619         int i, sky;
3620         entity_render_t *ent;
3621
3622         if (!r_drawentities.integer)
3623                 return false;
3624
3625         sky = false;
3626         for (i = 0;i < r_refdef.scene.numentities;i++)
3627         {
3628                 if (!r_refdef.viewcache.entityvisible[i])
3629                         continue;
3630                 ent = r_refdef.scene.entities[i];
3631                 if (!ent->model || !ent->model->DrawSky)
3632                         continue;
3633                 ent->model->DrawSky(ent);
3634                 sky = true;
3635         }
3636         return sky;
3637 }
3638
3639 static void R_DrawNoModel(entity_render_t *ent);
3640 static void R_DrawModels(void)
3641 {
3642         int i;
3643         entity_render_t *ent;
3644
3645         if (!r_drawentities.integer)
3646                 return;
3647
3648         for (i = 0;i < r_refdef.scene.numentities;i++)
3649         {
3650                 if (!r_refdef.viewcache.entityvisible[i])
3651                         continue;
3652                 ent = r_refdef.scene.entities[i];
3653                 r_refdef.stats.entities++;
3654                 if (ent->model && ent->model->Draw != NULL)
3655                         ent->model->Draw(ent);
3656                 else
3657                         R_DrawNoModel(ent);
3658         }
3659 }
3660
3661 static void R_DrawModelsDepth(void)
3662 {
3663         int i;
3664         entity_render_t *ent;
3665
3666         if (!r_drawentities.integer)
3667                 return;
3668
3669         for (i = 0;i < r_refdef.scene.numentities;i++)
3670         {
3671                 if (!r_refdef.viewcache.entityvisible[i])
3672                         continue;