improved shadowmap side culling
[xonotic/darkplaces.git] / r_shadow.c
1
2 /*
3 Terminology: Stencil Shadow Volume (sometimes called Stencil Shadows)
4 An extrusion of the lit faces, beginning at the original geometry and ending
5 further from the light source than the original geometry (presumably at least
6 as far as the light's radius, if the light has a radius at all), capped at
7 both front and back to avoid any problems (extrusion from dark faces also
8 works but has a different set of problems)
9
10 This is normally rendered using Carmack's Reverse technique, in which
11 backfaces behind zbuffer (zfail) increment the stencil, and frontfaces behind
12 zbuffer (zfail) decrement the stencil, the result is a stencil value of zero
13 where shadows did not intersect the visible geometry, suitable as a stencil
14 mask for rendering lighting everywhere but shadow.
15
16 In our case to hopefully avoid the Creative Labs patent, we draw the backfaces
17 as decrement and the frontfaces as increment, and we redefine the DepthFunc to
18 GL_LESS (the patent uses GL_GEQUAL) which causes zfail when behind surfaces
19 and zpass when infront (the patent draws where zpass with a GL_GEQUAL test),
20 additionally we clear stencil to 128 to avoid the need for the unclamped
21 incr/decr extension (not related to patent).
22
23 Patent warning:
24 This algorithm may be covered by Creative's patent (US Patent #6384822),
25 however that patent is quite specific about increment on backfaces and
26 decrement on frontfaces where zpass with GL_GEQUAL depth test, which is
27 opposite this implementation and partially opposite Carmack's Reverse paper
28 (which uses GL_LESS, but increments on backfaces and decrements on frontfaces).
29
30
31
32 Terminology: Stencil Light Volume (sometimes called Light Volumes)
33 Similar to a Stencil Shadow Volume, but inverted; rather than containing the
34 areas in shadow it contains the areas in light, this can only be built
35 quickly for certain limited cases (such as portal visibility from a point),
36 but is quite useful for some effects (sunlight coming from sky polygons is
37 one possible example, translucent occluders is another example).
38
39
40
41 Terminology: Optimized Stencil Shadow Volume
42 A Stencil Shadow Volume that has been processed sufficiently to ensure it has
43 no duplicate coverage of areas (no need to shadow an area twice), often this
44 greatly improves performance but is an operation too costly to use on moving
45 lights (however completely optimal Stencil Light Volumes can be constructed
46 in some ideal cases).
47
48
49
50 Terminology: Per Pixel Lighting (sometimes abbreviated PPL)
51 Per pixel evaluation of lighting equations, at a bare minimum this involves
52 DOT3 shading of diffuse lighting (per pixel dotproduct of negated incidence
53 vector and surface normal, using a texture of the surface bumps, called a
54 NormalMap) if supported by hardware; in our case there is support for cards
55 which are incapable of DOT3, the quality is quite poor however.  Additionally
56 it is desirable to have specular evaluation per pixel, per vertex
57 normalization of specular halfangle vectors causes noticable distortion but
58 is unavoidable on hardware without GL_ARB_fragment_program or
59 GL_ARB_fragment_shader.
60
61
62
63 Terminology: Normalization CubeMap
64 A cubemap containing normalized dot3-encoded (vectors of length 1 or less
65 encoded as RGB colors) for any possible direction, this technique allows per
66 pixel calculation of incidence vector for per pixel lighting purposes, which
67 would not otherwise be possible per pixel without GL_ARB_fragment_program or
68 GL_ARB_fragment_shader.
69
70
71
72 Terminology: 2D+1D Attenuation Texturing
73 A very crude approximation of light attenuation with distance which results
74 in cylindrical light shapes which fade vertically as a streak (some games
75 such as Doom3 allow this to be rotated to be less noticable in specific
76 cases), the technique is simply modulating lighting by two 2D textures (which
77 can be the same) on different axes of projection (XY and Z, typically), this
78 is the second best technique available without 3D Attenuation Texturing,
79 GL_ARB_fragment_program or GL_ARB_fragment_shader technology.
80
81
82
83 Terminology: 2D+1D Inverse Attenuation Texturing
84 A clever method described in papers on the Abducted engine, this has a squared
85 distance texture (bright on the outside, black in the middle), which is used
86 twice using GL_ADD blending, the result of this is used in an inverse modulate
87 (GL_ONE_MINUS_DST_ALPHA, GL_ZERO) to implement the equation
88 lighting*=(1-((X*X+Y*Y)+(Z*Z))) which is spherical (unlike 2D+1D attenuation
89 texturing).
90
91
92
93 Terminology: 3D Attenuation Texturing
94 A slightly crude approximation of light attenuation with distance, its flaws
95 are limited radius and resolution (performance tradeoffs).
96
97
98
99 Terminology: 3D Attenuation-Normalization Texturing
100 A 3D Attenuation Texture merged with a Normalization CubeMap, by making the
101 vectors shorter the lighting becomes darker, a very effective optimization of
102 diffuse lighting if 3D Attenuation Textures are already used.
103
104
105
106 Terminology: Light Cubemap Filtering
107 A technique for modeling non-uniform light distribution according to
108 direction, for example a lantern may use a cubemap to describe the light
109 emission pattern of the cage around the lantern (as well as soot buildup
110 discoloring the light in certain areas), often also used for softened grate
111 shadows and light shining through a stained glass window (done crudely by
112 texturing the lighting with a cubemap), another good example would be a disco
113 light.  This technique is used heavily in many games (Doom3 does not support
114 this however).
115
116
117
118 Terminology: Light Projection Filtering
119 A technique for modeling shadowing of light passing through translucent
120 surfaces, allowing stained glass windows and other effects to be done more
121 elegantly than possible with Light Cubemap Filtering by applying an occluder
122 texture to the lighting combined with a stencil light volume to limit the lit
123 area, this technique is used by Doom3 for spotlights and flashlights, among
124 other things, this can also be used more generally to render light passing
125 through multiple translucent occluders in a scene (using a light volume to
126 describe the area beyond the occluder, and thus mask off rendering of all
127 other areas).
128
129
130
131 Terminology: Doom3 Lighting
132 A combination of Stencil Shadow Volume, Per Pixel Lighting, Normalization
133 CubeMap, 2D+1D Attenuation Texturing, and Light Projection Filtering, as
134 demonstrated by the game Doom3.
135 */
136
137 #include "quakedef.h"
138 #include "r_shadow.h"
139 #include "cl_collision.h"
140 #include "portals.h"
141 #include "image.h"
142
143 #define R_SHADOW_SHADOWMAP_NUMCUBEMAPS 8
144
145 extern void R_Shadow_EditLights_Init(void);
146
147 typedef enum r_shadow_rendermode_e
148 {
149         R_SHADOW_RENDERMODE_NONE,
150         R_SHADOW_RENDERMODE_ZPASS_STENCIL,
151         R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL,
152         R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE,
153         R_SHADOW_RENDERMODE_ZFAIL_STENCIL,
154         R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL,
155         R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE,
156         R_SHADOW_RENDERMODE_LIGHT_VERTEX,
157         R_SHADOW_RENDERMODE_LIGHT_DOT3,
158         R_SHADOW_RENDERMODE_LIGHT_GLSL,
159         R_SHADOW_RENDERMODE_VISIBLEVOLUMES,
160         R_SHADOW_RENDERMODE_VISIBLELIGHTING,
161         R_SHADOW_RENDERMODE_SHADOWMAPRECTANGLE,
162         R_SHADOW_RENDERMODE_SHADOWMAP2D,
163         R_SHADOW_RENDERMODE_SHADOWMAPCUBESIDE,
164 }
165 r_shadow_rendermode_t;
166
167 r_shadow_rendermode_t r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
168 r_shadow_rendermode_t r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_NONE;
169 r_shadow_rendermode_t r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_NONE;
170 r_shadow_rendermode_t r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_NONE;
171 qboolean r_shadow_usingshadowmaprect;
172 qboolean r_shadow_usingshadowmap2d;
173 qboolean r_shadow_usingshadowmapcube;
174 int r_shadow_shadowmapside;
175 float r_shadow_shadowmap_texturescale[2];
176 float r_shadow_shadowmap_parameters[4];
177 int r_shadow_drawbuffer;
178 int r_shadow_readbuffer;
179 int r_shadow_cullface;
180 GLuint r_shadow_fborectangle;
181 GLuint r_shadow_fbocubeside[R_SHADOW_SHADOWMAP_NUMCUBEMAPS][6];
182 GLuint r_shadow_fbo2d;
183 int r_shadow_shadowmode;
184 int r_shadow_shadowmapfilterquality;
185 int r_shadow_shadowmaptexturetype;
186 int r_shadow_shadowmapprecision;
187 int r_shadow_shadowmapmaxsize;
188 qboolean r_shadow_shadowmapvsdct;
189 qboolean r_shadow_shadowmapsampler;
190 int r_shadow_shadowmappcf;
191 int r_shadow_shadowmapborder;
192 int r_shadow_lightscissor[4];
193
194 int maxshadowtriangles;
195 int *shadowelements;
196
197 int maxshadowvertices;
198 float *shadowvertex3f;
199
200 int maxshadowmark;
201 int numshadowmark;
202 int *shadowmark;
203 int *shadowmarklist;
204 int shadowmarkcount;
205
206 int maxshadowsides;
207 int numshadowsides;
208 unsigned char *shadowsides;
209 int *shadowsideslist;
210
211 int maxvertexupdate;
212 int *vertexupdate;
213 int *vertexremap;
214 int vertexupdatenum;
215
216 int r_shadow_buffer_numleafpvsbytes;
217 unsigned char *r_shadow_buffer_visitingleafpvs;
218 unsigned char *r_shadow_buffer_leafpvs;
219 int *r_shadow_buffer_leaflist;
220
221 int r_shadow_buffer_numsurfacepvsbytes;
222 unsigned char *r_shadow_buffer_surfacepvs;
223 int *r_shadow_buffer_surfacelist;
224
225 int r_shadow_buffer_numshadowtrispvsbytes;
226 unsigned char *r_shadow_buffer_shadowtrispvs;
227 int r_shadow_buffer_numlighttrispvsbytes;
228 unsigned char *r_shadow_buffer_lighttrispvs;
229
230 rtexturepool_t *r_shadow_texturepool;
231 rtexture_t *r_shadow_attenuationgradienttexture;
232 rtexture_t *r_shadow_attenuation2dtexture;
233 rtexture_t *r_shadow_attenuation3dtexture;
234 rtexture_t *r_shadow_lightcorona;
235 rtexture_t *r_shadow_shadowmaprectangletexture;
236 rtexture_t *r_shadow_shadowmap2dtexture;
237 rtexture_t *r_shadow_shadowmapcubetexture[R_SHADOW_SHADOWMAP_NUMCUBEMAPS];
238 rtexture_t *r_shadow_shadowmapvsdcttexture;
239 int r_shadow_shadowmapsize; // changes for each light based on distance
240 int r_shadow_shadowmaplod; // changes for each light based on distance
241
242 // lights are reloaded when this changes
243 char r_shadow_mapname[MAX_QPATH];
244
245 // used only for light filters (cubemaps)
246 rtexturepool_t *r_shadow_filters_texturepool;
247
248 cvar_t r_shadow_bumpscale_basetexture = {0, "r_shadow_bumpscale_basetexture", "0", "generate fake bumpmaps from diffuse textures at this bumpyness, try 4 to match tenebrae, higher values increase depth, requires r_restart to take effect"};
249 cvar_t r_shadow_bumpscale_bumpmap = {0, "r_shadow_bumpscale_bumpmap", "4", "what magnitude to interpret _bump.tga textures as, higher values increase depth, requires r_restart to take effect"};
250 cvar_t r_shadow_debuglight = {0, "r_shadow_debuglight", "-1", "renders only one light, for level design purposes or debugging"};
251 cvar_t r_shadow_usenormalmap = {CVAR_SAVE, "r_shadow_usenormalmap", "1", "enables use of directional shading on lights"};
252 cvar_t r_shadow_gloss = {CVAR_SAVE, "r_shadow_gloss", "1", "0 disables gloss (specularity) rendering, 1 uses gloss if textures are found, 2 forces a flat metallic specular effect on everything without textures (similar to tenebrae)"};
253 cvar_t r_shadow_gloss2intensity = {0, "r_shadow_gloss2intensity", "0.125", "how bright the forced flat gloss should look if r_shadow_gloss is 2"};
254 cvar_t r_shadow_glossintensity = {0, "r_shadow_glossintensity", "1", "how bright textured glossmaps should look if r_shadow_gloss is 1 or 2"};
255 cvar_t r_shadow_glossexponent = {0, "r_shadow_glossexponent", "32", "how 'sharp' the gloss should appear (specular power)"};
256 cvar_t r_shadow_gloss2exponent = {0, "r_shadow_gloss2exponent", "32", "same as r_shadow_glossexponent but for forced gloss (gloss 2) surfaces"};
257 cvar_t r_shadow_glossexact = {0, "r_shadow_glossexact", "0", "use exact reflection math for gloss (slightly slower, but should look a tad better)"};
258 cvar_t r_shadow_lightattenuationdividebias = {0, "r_shadow_lightattenuationdividebias", "1", "changes attenuation texture generation"};
259 cvar_t r_shadow_lightattenuationlinearscale = {0, "r_shadow_lightattenuationlinearscale", "2", "changes attenuation texture generation"};
260 cvar_t r_shadow_lightintensityscale = {0, "r_shadow_lightintensityscale", "1", "renders all world lights brighter or darker"};
261 cvar_t r_shadow_lightradiusscale = {0, "r_shadow_lightradiusscale", "1", "renders all world lights larger or smaller"};
262 cvar_t r_shadow_portallight = {0, "r_shadow_portallight", "1", "use portal culling to exactly determine lit triangles when compiling world lights"};
263 cvar_t r_shadow_projectdistance = {0, "r_shadow_projectdistance", "1000000", "how far to cast shadows"};
264 cvar_t r_shadow_frontsidecasting = {0, "r_shadow_frontsidecasting", "1", "whether to cast shadows from illuminated triangles (front side of model) or unlit triangles (back side of model)"};
265 cvar_t r_shadow_realtime_dlight = {CVAR_SAVE, "r_shadow_realtime_dlight", "1", "enables rendering of dynamic lights such as explosions and rocket light"};
266 cvar_t r_shadow_realtime_dlight_shadows = {CVAR_SAVE, "r_shadow_realtime_dlight_shadows", "1", "enables rendering of shadows from dynamic lights"};
267 cvar_t r_shadow_realtime_dlight_svbspculling = {0, "r_shadow_realtime_dlight_svbspculling", "0", "enables svbsp optimization on dynamic lights (very slow!)"};
268 cvar_t r_shadow_realtime_dlight_portalculling = {0, "r_shadow_realtime_dlight_portalculling", "0", "enables portal optimization on dynamic lights (slow!)"};
269 cvar_t r_shadow_realtime_world = {CVAR_SAVE, "r_shadow_realtime_world", "0", "enables rendering of full world lighting (whether loaded from the map, or a .rtlights file, or a .ent file, or a .lights file produced by hlight)"};
270 cvar_t r_shadow_realtime_world_lightmaps = {CVAR_SAVE, "r_shadow_realtime_world_lightmaps", "0", "brightness to render lightmaps when using full world lighting, try 0.5 for a tenebrae-like appearance"};
271 cvar_t r_shadow_realtime_world_shadows = {CVAR_SAVE, "r_shadow_realtime_world_shadows", "1", "enables rendering of shadows from world lights"};
272 cvar_t r_shadow_realtime_world_compile = {0, "r_shadow_realtime_world_compile", "1", "enables compilation of world lights for higher performance rendering"};
273 cvar_t r_shadow_realtime_world_compileshadow = {0, "r_shadow_realtime_world_compileshadow", "1", "enables compilation of shadows from world lights for higher performance rendering"};
274 cvar_t r_shadow_realtime_world_compilesvbsp = {0, "r_shadow_realtime_world_compilesvbsp", "1", "enables svbsp optimization during compilation"};
275 cvar_t r_shadow_realtime_world_compileportalculling = {0, "r_shadow_realtime_world_compileportalculling", "1", "enables portal-based culling optimization during compilation"};
276 cvar_t r_shadow_scissor = {0, "r_shadow_scissor", "1", "use scissor optimization of light rendering (restricts rendering to the portion of the screen affected by the light)"};
277 cvar_t r_shadow_shadowmapping = {CVAR_SAVE, "r_shadow_shadowmapping", "0", "enables use of shadowmapping (depth texture sampling) instead of stencil shadow volumes, requires gl_fbo 1"};
278 cvar_t r_shadow_shadowmapping_texturetype = {CVAR_SAVE, "r_shadow_shadowmapping_texturetype", "0", "shadowmap texture types: 0 = auto-select, 1 = 2D, 2 = rectangle, 3 = cubemap"};
279 cvar_t r_shadow_shadowmapping_filterquality = {CVAR_SAVE, "r_shadow_shadowmapping_filterquality", "-1", "shadowmap filter modes: -1 = auto-select, 0 = no filtering, 1 = bilinear, 2 = bilinear 2x2 blur (fast), 3 = 3x3 blur (moderate), 4 = 4x4 blur (slow)"};
280 cvar_t r_shadow_shadowmapping_precision = {CVAR_SAVE, "r_shadow_shadowmapping_precision", "24", "requested minimum shadowmap texture precision"};
281 cvar_t r_shadow_shadowmapping_vsdct = {CVAR_SAVE, "r_shadow_shadowmapping_vsdct", "1", "enables use of virtual shadow depth cube texture"};
282 cvar_t r_shadow_shadowmapping_minsize = {CVAR_SAVE, "r_shadow_shadowmapping_minsize", "32", "shadowmap size limit"};
283 cvar_t r_shadow_shadowmapping_maxsize = {CVAR_SAVE, "r_shadow_shadowmapping_maxsize", "512", "shadowmap size limit"};
284 cvar_t r_shadow_shadowmapping_lod_bias = {CVAR_SAVE, "r_shadow_shadowmapping_lod_bias", "16", "shadowmap size bias"};
285 cvar_t r_shadow_shadowmapping_lod_scale = {CVAR_SAVE, "r_shadow_shadowmapping_lod_scale", "128", "shadowmap size scaling parameter"};
286 cvar_t r_shadow_shadowmapping_bordersize = {CVAR_SAVE, "r_shadow_shadowmapping_bordersize", "4", "shadowmap size bias for filtering"};
287 cvar_t r_shadow_shadowmapping_nearclip = {CVAR_SAVE, "r_shadow_shadowmapping_nearclip", "1", "shadowmap nearclip in world units"};
288 cvar_t r_shadow_shadowmapping_bias = {CVAR_SAVE, "r_shadow_shadowmapping_bias", "0.03", "shadowmap bias parameter (this is multiplied by nearclip * 1024 / lodsize)"};
289 cvar_t r_shadow_culltriangles = {0, "r_shadow_culltriangles", "1", "performs more expensive tests to remove unnecessary triangles of lit surfaces"};
290 cvar_t r_shadow_polygonfactor = {0, "r_shadow_polygonfactor", "0", "how much to enlarge shadow volume polygons when rendering (should be 0!)"};
291 cvar_t r_shadow_polygonoffset = {0, "r_shadow_polygonoffset", "1", "how much to push shadow volumes into the distance when rendering, to reduce chances of zfighting artifacts (should not be less than 0)"};
292 cvar_t r_shadow_texture3d = {0, "r_shadow_texture3d", "1", "use 3D voxel textures for spherical attenuation rather than cylindrical (does not affect r_glsl lighting)"};
293 cvar_t r_coronas = {CVAR_SAVE, "r_coronas", "1", "brightness of corona flare effects around certain lights, 0 disables corona effects"};
294 cvar_t r_coronas_occlusionsizescale = {CVAR_SAVE, "r_coronas_occlusionsizescale", "0.1", "size of light source for corona occlusion checksm the proportion of hidden pixels controls corona intensity"};
295 cvar_t r_coronas_occlusionquery = {CVAR_SAVE, "r_coronas_occlusionquery", "1", "use GL_ARB_occlusion_query extension if supported (fades coronas according to visibility)"};
296 cvar_t gl_flashblend = {CVAR_SAVE, "gl_flashblend", "0", "render bright coronas for dynamic lights instead of actual lighting, fast but ugly"};
297 cvar_t gl_ext_separatestencil = {0, "gl_ext_separatestencil", "1", "make use of OpenGL 2.0 glStencilOpSeparate or GL_ATI_separate_stencil extension"};
298 cvar_t gl_ext_stenciltwoside = {0, "gl_ext_stenciltwoside", "1", "make use of GL_EXT_stenciltwoside extension (NVIDIA only)"};
299 cvar_t r_editlights = {0, "r_editlights", "0", "enables .rtlights file editing mode"};
300 cvar_t r_editlights_cursordistance = {0, "r_editlights_cursordistance", "1024", "maximum distance of cursor from eye"};
301 cvar_t r_editlights_cursorpushback = {0, "r_editlights_cursorpushback", "0", "how far to pull the cursor back toward the eye"};
302 cvar_t r_editlights_cursorpushoff = {0, "r_editlights_cursorpushoff", "4", "how far to push the cursor off the impacted surface"};
303 cvar_t r_editlights_cursorgrid = {0, "r_editlights_cursorgrid", "4", "snaps cursor to this grid size"};
304 cvar_t r_editlights_quakelightsizescale = {CVAR_SAVE, "r_editlights_quakelightsizescale", "1", "changes size of light entities loaded from a map"};
305
306 // note the table actually includes one more value, just to avoid the need to clamp the distance index due to minor math error
307 #define ATTENTABLESIZE 256
308 // 1D gradient, 2D circle and 3D sphere attenuation textures
309 #define ATTEN1DSIZE 32
310 #define ATTEN2DSIZE 64
311 #define ATTEN3DSIZE 32
312
313 static float r_shadow_attendividebias; // r_shadow_lightattenuationdividebias
314 static float r_shadow_attenlinearscale; // r_shadow_lightattenuationlinearscale
315 static float r_shadow_attentable[ATTENTABLESIZE+1];
316
317 rtlight_t *r_shadow_compilingrtlight;
318 static memexpandablearray_t r_shadow_worldlightsarray;
319 dlight_t *r_shadow_selectedlight;
320 dlight_t r_shadow_bufferlight;
321 vec3_t r_editlights_cursorlocation;
322
323 extern int con_vislines;
324
325 typedef struct cubemapinfo_s
326 {
327         char basename[64];
328         rtexture_t *texture;
329 }
330 cubemapinfo_t;
331
332 #define MAX_CUBEMAPS 256
333 static int numcubemaps;
334 static cubemapinfo_t cubemaps[MAX_CUBEMAPS];
335
336 void R_Shadow_UncompileWorldLights(void);
337 void R_Shadow_ClearWorldLights(void);
338 void R_Shadow_SaveWorldLights(void);
339 void R_Shadow_LoadWorldLights(void);
340 void R_Shadow_LoadLightsFile(void);
341 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void);
342 void R_Shadow_EditLights_Reload_f(void);
343 void R_Shadow_ValidateCvars(void);
344 static void R_Shadow_MakeTextures(void);
345
346 // VorteX: custom editor light sprites
347 #define EDLIGHTSPRSIZE                  8
348 cachepic_t *r_editlights_sprcursor;
349 cachepic_t *r_editlights_sprlight;
350 cachepic_t *r_editlights_sprnoshadowlight;
351 cachepic_t *r_editlights_sprcubemaplight;
352 cachepic_t *r_editlights_sprcubemapnoshadowlight;
353 cachepic_t *r_editlights_sprselection;
354
355 void R_Shadow_SetShadowMode(void)
356 {
357         r_shadow_shadowmapmaxsize = bound(1, r_shadow_shadowmapping_maxsize.integer, 2048);
358         r_shadow_shadowmapvsdct = r_shadow_shadowmapping_vsdct.integer != 0;
359         r_shadow_shadowmapfilterquality = r_shadow_shadowmapping_filterquality.integer;
360         r_shadow_shadowmaptexturetype = r_shadow_shadowmapping_texturetype.integer;
361         r_shadow_shadowmapprecision = r_shadow_shadowmapping_precision.integer;
362         r_shadow_shadowmapborder = bound(0, r_shadow_shadowmapping_bordersize.integer, 16);
363         r_shadow_shadowmaplod = -1;
364         r_shadow_shadowmapsize = 0;
365         r_shadow_shadowmapsampler = false;
366         r_shadow_shadowmappcf = 0;
367         r_shadow_shadowmode = 0;
368         if(r_shadow_shadowmapping.integer)
369         {
370                 if(r_shadow_shadowmapfilterquality < 0)
371                 {
372                         if(strstr(gl_vendor, "NVIDIA")) 
373                         {
374                                 r_shadow_shadowmapsampler = gl_support_arb_shadow;
375                                 r_shadow_shadowmappcf = 1;
376                         }
377                         else if(gl_support_amd_texture_texture4 || gl_support_arb_texture_gather) 
378                                 r_shadow_shadowmappcf = 1;
379                         else if(strstr(gl_vendor, "ATI")) 
380                                 r_shadow_shadowmappcf = 1;
381                         else 
382                                 r_shadow_shadowmapsampler = gl_support_arb_shadow;
383                 }
384                 else 
385                 {
386                         switch (r_shadow_shadowmapfilterquality)
387                         {
388                         case 1:
389                                 r_shadow_shadowmapsampler = gl_support_arb_shadow;
390                                 break;
391                         case 2:
392                                 r_shadow_shadowmapsampler = gl_support_arb_shadow;
393                                 r_shadow_shadowmappcf = 1;
394                                 break;
395                         case 3:
396                                 r_shadow_shadowmappcf = 1;
397                                 break;
398                         case 4:
399                                 r_shadow_shadowmappcf = 2;
400                                 break;
401                         }
402                 }
403                 r_shadow_shadowmode = r_shadow_shadowmaptexturetype;
404                 if(r_shadow_shadowmode <= 0)
405                 {
406                         if((gl_support_amd_texture_texture4 || gl_support_arb_texture_gather) && r_shadow_shadowmappcf && !r_shadow_shadowmapsampler)
407                                 r_shadow_shadowmode = 1;
408                         else if(gl_texturerectangle) 
409                                 r_shadow_shadowmode = 2;
410                         else
411                                 r_shadow_shadowmode = 1;
412                 }
413         }
414 }
415
416 void R_Shadow_FreeShadowMaps(void)
417 {
418         int i;
419
420         R_Shadow_SetShadowMode();
421
422         if (r_shadow_fborectangle)
423                 qglDeleteFramebuffersEXT(1, &r_shadow_fborectangle);
424         r_shadow_fborectangle = 0;
425         CHECKGLERROR
426
427         if (r_shadow_fbo2d)
428                 qglDeleteFramebuffersEXT(1, &r_shadow_fbo2d);
429         r_shadow_fbo2d = 0;
430         CHECKGLERROR
431         for (i = 0;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
432                 if (r_shadow_fbocubeside[i][0])
433                         qglDeleteFramebuffersEXT(6, r_shadow_fbocubeside[i]);
434         memset(r_shadow_fbocubeside, 0, sizeof(r_shadow_fbocubeside));
435         CHECKGLERROR
436
437         if (r_shadow_shadowmaprectangletexture)
438                 R_FreeTexture(r_shadow_shadowmaprectangletexture);
439         r_shadow_shadowmaprectangletexture = NULL;
440
441         if (r_shadow_shadowmap2dtexture)
442                 R_FreeTexture(r_shadow_shadowmap2dtexture);
443         r_shadow_shadowmap2dtexture = NULL;
444
445         for (i = 0;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
446                 if (r_shadow_shadowmapcubetexture[i])
447                         R_FreeTexture(r_shadow_shadowmapcubetexture[i]);
448         memset(r_shadow_shadowmapcubetexture, 0, sizeof(r_shadow_shadowmapcubetexture));
449
450         if (r_shadow_shadowmapvsdcttexture)
451                 R_FreeTexture(r_shadow_shadowmapvsdcttexture);
452         r_shadow_shadowmapvsdcttexture = NULL;
453
454         CHECKGLERROR
455 }
456
457 void r_shadow_start(void)
458 {
459         // allocate vertex processing arrays
460         numcubemaps = 0;
461         r_shadow_attenuationgradienttexture = NULL;
462         r_shadow_attenuation2dtexture = NULL;
463         r_shadow_attenuation3dtexture = NULL;
464         r_shadow_shadowmode = 0;
465         r_shadow_shadowmaprectangletexture = NULL;
466         r_shadow_shadowmap2dtexture = NULL;
467         memset(r_shadow_shadowmapcubetexture, 0, sizeof(r_shadow_shadowmapcubetexture));
468         r_shadow_shadowmapvsdcttexture = NULL;
469         r_shadow_shadowmapmaxsize = 0;
470         r_shadow_shadowmapsize = 0;
471         r_shadow_shadowmaplod = 0;
472         r_shadow_shadowmapfilterquality = 0;
473         r_shadow_shadowmaptexturetype = 0;
474         r_shadow_shadowmapprecision = 0;
475         r_shadow_shadowmapvsdct = false;
476         r_shadow_shadowmapsampler = false;
477         r_shadow_shadowmappcf = 0;
478         r_shadow_fborectangle = 0;
479         r_shadow_fbo2d = 0;
480         memset(r_shadow_fbocubeside, 0, sizeof(r_shadow_fbocubeside));
481
482         R_Shadow_FreeShadowMaps();
483
484         r_shadow_texturepool = NULL;
485         r_shadow_filters_texturepool = NULL;
486         R_Shadow_ValidateCvars();
487         R_Shadow_MakeTextures();
488         maxshadowtriangles = 0;
489         shadowelements = NULL;
490         maxshadowvertices = 0;
491         shadowvertex3f = NULL;
492         maxvertexupdate = 0;
493         vertexupdate = NULL;
494         vertexremap = NULL;
495         vertexupdatenum = 0;
496         maxshadowmark = 0;
497         numshadowmark = 0;
498         shadowmark = NULL;
499         shadowmarklist = NULL;
500         shadowmarkcount = 0;
501         maxshadowsides = 0;
502         numshadowsides = 0;
503         shadowsides = NULL;
504         shadowsideslist = NULL;
505         r_shadow_buffer_numleafpvsbytes = 0;
506         r_shadow_buffer_visitingleafpvs = NULL;
507         r_shadow_buffer_leafpvs = NULL;
508         r_shadow_buffer_leaflist = NULL;
509         r_shadow_buffer_numsurfacepvsbytes = 0;
510         r_shadow_buffer_surfacepvs = NULL;
511         r_shadow_buffer_surfacelist = NULL;
512         r_shadow_buffer_numshadowtrispvsbytes = 0;
513         r_shadow_buffer_shadowtrispvs = NULL;
514         r_shadow_buffer_numlighttrispvsbytes = 0;
515         r_shadow_buffer_lighttrispvs = NULL;
516 }
517
518 void r_shadow_shutdown(void)
519 {
520         CHECKGLERROR
521         R_Shadow_UncompileWorldLights();
522
523         R_Shadow_FreeShadowMaps();
524
525         CHECKGLERROR
526         numcubemaps = 0;
527         r_shadow_attenuationgradienttexture = NULL;
528         r_shadow_attenuation2dtexture = NULL;
529         r_shadow_attenuation3dtexture = NULL;
530         R_FreeTexturePool(&r_shadow_texturepool);
531         R_FreeTexturePool(&r_shadow_filters_texturepool);
532         maxshadowtriangles = 0;
533         if (shadowelements)
534                 Mem_Free(shadowelements);
535         shadowelements = NULL;
536         if (shadowvertex3f)
537                 Mem_Free(shadowvertex3f);
538         shadowvertex3f = NULL;
539         maxvertexupdate = 0;
540         if (vertexupdate)
541                 Mem_Free(vertexupdate);
542         vertexupdate = NULL;
543         if (vertexremap)
544                 Mem_Free(vertexremap);
545         vertexremap = NULL;
546         vertexupdatenum = 0;
547         maxshadowmark = 0;
548         numshadowmark = 0;
549         if (shadowmark)
550                 Mem_Free(shadowmark);
551         shadowmark = NULL;
552         if (shadowmarklist)
553                 Mem_Free(shadowmarklist);
554         shadowmarklist = NULL;
555         shadowmarkcount = 0;
556         maxshadowsides = 0;
557         numshadowsides = 0;
558         if (shadowsides)
559                 Mem_Free(shadowsides);
560         shadowsides = NULL;
561         if (shadowsideslist)
562                 Mem_Free(shadowsideslist);
563         shadowsideslist = NULL;
564         r_shadow_buffer_numleafpvsbytes = 0;
565         if (r_shadow_buffer_visitingleafpvs)
566                 Mem_Free(r_shadow_buffer_visitingleafpvs);
567         r_shadow_buffer_visitingleafpvs = NULL;
568         if (r_shadow_buffer_leafpvs)
569                 Mem_Free(r_shadow_buffer_leafpvs);
570         r_shadow_buffer_leafpvs = NULL;
571         if (r_shadow_buffer_leaflist)
572                 Mem_Free(r_shadow_buffer_leaflist);
573         r_shadow_buffer_leaflist = NULL;
574         r_shadow_buffer_numsurfacepvsbytes = 0;
575         if (r_shadow_buffer_surfacepvs)
576                 Mem_Free(r_shadow_buffer_surfacepvs);
577         r_shadow_buffer_surfacepvs = NULL;
578         if (r_shadow_buffer_surfacelist)
579                 Mem_Free(r_shadow_buffer_surfacelist);
580         r_shadow_buffer_surfacelist = NULL;
581         r_shadow_buffer_numshadowtrispvsbytes = 0;
582         if (r_shadow_buffer_shadowtrispvs)
583                 Mem_Free(r_shadow_buffer_shadowtrispvs);
584         r_shadow_buffer_numlighttrispvsbytes = 0;
585         if (r_shadow_buffer_lighttrispvs)
586                 Mem_Free(r_shadow_buffer_lighttrispvs);
587 }
588
589 void r_shadow_newmap(void)
590 {
591         if (cl.worldmodel && strncmp(cl.worldmodel->name, r_shadow_mapname, sizeof(r_shadow_mapname)))
592                 R_Shadow_EditLights_Reload_f();
593 }
594
595 void R_Shadow_Help_f(void)
596 {
597         Con_Printf(
598 "Documentation on r_shadow system:\n"
599 "Settings:\n"
600 "r_shadow_bumpscale_basetexture : base texture as bumpmap with this scale\n"
601 "r_shadow_bumpscale_bumpmap : depth scale for bumpmap conversion\n"
602 "r_shadow_debuglight : render only this light number (-1 = all)\n"
603 "r_shadow_gloss 0/1/2 : no gloss, gloss textures only, force gloss\n"
604 "r_shadow_gloss2intensity : brightness of forced gloss\n"
605 "r_shadow_glossintensity : brightness of textured gloss\n"
606 "r_shadow_lightattenuationlinearscale : used to generate attenuation texture\n"
607 "r_shadow_lightattenuationdividebias : used to generate attenuation texture\n"
608 "r_shadow_lightintensityscale : scale rendering brightness of all lights\n"
609 "r_shadow_lightradiusscale : scale rendering radius of all lights\n"
610 "r_shadow_portallight : use portal visibility for static light precomputation\n"
611 "r_shadow_projectdistance : shadow volume projection distance\n"
612 "r_shadow_realtime_dlight : use high quality dynamic lights in normal mode\n"
613 "r_shadow_realtime_dlight_shadows : cast shadows from dlights\n"
614 "r_shadow_realtime_world : use high quality world lighting mode\n"
615 "r_shadow_realtime_world_lightmaps : use lightmaps in addition to lights\n"
616 "r_shadow_realtime_world_shadows : cast shadows from world lights\n"
617 "r_shadow_realtime_world_compile : compile surface/visibility information\n"
618 "r_shadow_realtime_world_compileshadow : compile shadow geometry\n"
619 "r_shadow_scissor : use scissor optimization\n"
620 "r_shadow_polygonfactor : nudge shadow volumes closer/further\n"
621 "r_shadow_polygonoffset : nudge shadow volumes closer/further\n"
622 "r_shadow_texture3d : use 3d attenuation texture (if hardware supports)\n"
623 "r_showlighting : useful for performance testing; bright = slow!\n"
624 "r_showshadowvolumes : useful for performance testing; bright = slow!\n"
625 "Commands:\n"
626 "r_shadow_help : this help\n"
627         );
628 }
629
630 void R_Shadow_Init(void)
631 {
632         Cvar_RegisterVariable(&r_shadow_bumpscale_basetexture);
633         Cvar_RegisterVariable(&r_shadow_bumpscale_bumpmap);
634         Cvar_RegisterVariable(&r_shadow_usenormalmap);
635         Cvar_RegisterVariable(&r_shadow_debuglight);
636         Cvar_RegisterVariable(&r_shadow_gloss);
637         Cvar_RegisterVariable(&r_shadow_gloss2intensity);
638         Cvar_RegisterVariable(&r_shadow_glossintensity);
639         Cvar_RegisterVariable(&r_shadow_glossexponent);
640         Cvar_RegisterVariable(&r_shadow_gloss2exponent);
641         Cvar_RegisterVariable(&r_shadow_glossexact);
642         Cvar_RegisterVariable(&r_shadow_lightattenuationdividebias);
643         Cvar_RegisterVariable(&r_shadow_lightattenuationlinearscale);
644         Cvar_RegisterVariable(&r_shadow_lightintensityscale);
645         Cvar_RegisterVariable(&r_shadow_lightradiusscale);
646         Cvar_RegisterVariable(&r_shadow_portallight);
647         Cvar_RegisterVariable(&r_shadow_projectdistance);
648         Cvar_RegisterVariable(&r_shadow_frontsidecasting);
649         Cvar_RegisterVariable(&r_shadow_realtime_dlight);
650         Cvar_RegisterVariable(&r_shadow_realtime_dlight_shadows);
651         Cvar_RegisterVariable(&r_shadow_realtime_dlight_svbspculling);
652         Cvar_RegisterVariable(&r_shadow_realtime_dlight_portalculling);
653         Cvar_RegisterVariable(&r_shadow_realtime_world);
654         Cvar_RegisterVariable(&r_shadow_realtime_world_lightmaps);
655         Cvar_RegisterVariable(&r_shadow_realtime_world_shadows);
656         Cvar_RegisterVariable(&r_shadow_realtime_world_compile);
657         Cvar_RegisterVariable(&r_shadow_realtime_world_compileshadow);
658         Cvar_RegisterVariable(&r_shadow_realtime_world_compilesvbsp);
659         Cvar_RegisterVariable(&r_shadow_realtime_world_compileportalculling);
660         Cvar_RegisterVariable(&r_shadow_scissor);
661         Cvar_RegisterVariable(&r_shadow_shadowmapping);
662         Cvar_RegisterVariable(&r_shadow_shadowmapping_vsdct);
663         Cvar_RegisterVariable(&r_shadow_shadowmapping_texturetype);
664         Cvar_RegisterVariable(&r_shadow_shadowmapping_filterquality);
665         Cvar_RegisterVariable(&r_shadow_shadowmapping_precision);
666         Cvar_RegisterVariable(&r_shadow_shadowmapping_maxsize);
667         Cvar_RegisterVariable(&r_shadow_shadowmapping_minsize);
668         Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_bias);
669         Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_scale);
670         Cvar_RegisterVariable(&r_shadow_shadowmapping_bordersize);
671         Cvar_RegisterVariable(&r_shadow_shadowmapping_nearclip);
672         Cvar_RegisterVariable(&r_shadow_shadowmapping_bias);
673         Cvar_RegisterVariable(&r_shadow_culltriangles);
674         Cvar_RegisterVariable(&r_shadow_polygonfactor);
675         Cvar_RegisterVariable(&r_shadow_polygonoffset);
676         Cvar_RegisterVariable(&r_shadow_texture3d);
677         Cvar_RegisterVariable(&r_coronas);
678         Cvar_RegisterVariable(&r_coronas_occlusionsizescale);
679         Cvar_RegisterVariable(&r_coronas_occlusionquery);
680         Cvar_RegisterVariable(&gl_flashblend);
681         Cvar_RegisterVariable(&gl_ext_separatestencil);
682         Cvar_RegisterVariable(&gl_ext_stenciltwoside);
683         if (gamemode == GAME_TENEBRAE)
684         {
685                 Cvar_SetValue("r_shadow_gloss", 2);
686                 Cvar_SetValue("r_shadow_bumpscale_basetexture", 4);
687         }
688         Cmd_AddCommand("r_shadow_help", R_Shadow_Help_f, "prints documentation on console commands and variables used by realtime lighting and shadowing system");
689         R_Shadow_EditLights_Init();
690         Mem_ExpandableArray_NewArray(&r_shadow_worldlightsarray, r_main_mempool, sizeof(dlight_t), 128);
691         maxshadowtriangles = 0;
692         shadowelements = NULL;
693         maxshadowvertices = 0;
694         shadowvertex3f = NULL;
695         maxvertexupdate = 0;
696         vertexupdate = NULL;
697         vertexremap = NULL;
698         vertexupdatenum = 0;
699         maxshadowmark = 0;
700         numshadowmark = 0;
701         shadowmark = NULL;
702         shadowmarklist = NULL;
703         shadowmarkcount = 0;
704         maxshadowsides = 0;
705         numshadowsides = 0;
706         shadowsides = NULL;
707         shadowsideslist = NULL;
708         r_shadow_buffer_numleafpvsbytes = 0;
709         r_shadow_buffer_visitingleafpvs = NULL;
710         r_shadow_buffer_leafpvs = NULL;
711         r_shadow_buffer_leaflist = NULL;
712         r_shadow_buffer_numsurfacepvsbytes = 0;
713         r_shadow_buffer_surfacepvs = NULL;
714         r_shadow_buffer_surfacelist = NULL;
715         r_shadow_buffer_shadowtrispvs = NULL;
716         r_shadow_buffer_lighttrispvs = NULL;
717         R_RegisterModule("R_Shadow", r_shadow_start, r_shadow_shutdown, r_shadow_newmap);
718 }
719
720 matrix4x4_t matrix_attenuationxyz =
721 {
722         {
723                 {0.5, 0.0, 0.0, 0.5},
724                 {0.0, 0.5, 0.0, 0.5},
725                 {0.0, 0.0, 0.5, 0.5},
726                 {0.0, 0.0, 0.0, 1.0}
727         }
728 };
729
730 matrix4x4_t matrix_attenuationz =
731 {
732         {
733                 {0.0, 0.0, 0.5, 0.5},
734                 {0.0, 0.0, 0.0, 0.5},
735                 {0.0, 0.0, 0.0, 0.5},
736                 {0.0, 0.0, 0.0, 1.0}
737         }
738 };
739
740 void R_Shadow_ResizeShadowArrays(int numvertices, int numtriangles, int vertscale, int triscale)
741 {
742         numvertices = ((numvertices + 255) & ~255) * vertscale;
743         numtriangles = ((numtriangles + 255) & ~255) * triscale;
744         // make sure shadowelements is big enough for this volume
745         if (maxshadowtriangles < numtriangles)
746         {
747                 maxshadowtriangles = numtriangles;
748                 if (shadowelements)
749                         Mem_Free(shadowelements);
750                 shadowelements = (int *)Mem_Alloc(r_main_mempool, maxshadowtriangles * sizeof(int[3]));
751         }
752         // make sure shadowvertex3f is big enough for this volume
753         if (maxshadowvertices < numvertices)
754         {
755                 maxshadowvertices = numvertices;
756                 if (shadowvertex3f)
757                         Mem_Free(shadowvertex3f);
758                 shadowvertex3f = (float *)Mem_Alloc(r_main_mempool, maxshadowvertices * sizeof(float[3]));
759         }
760 }
761
762 static void R_Shadow_EnlargeLeafSurfaceTrisBuffer(int numleafs, int numsurfaces, int numshadowtriangles, int numlighttriangles)
763 {
764         int numleafpvsbytes = (((numleafs + 7) >> 3) + 255) & ~255;
765         int numsurfacepvsbytes = (((numsurfaces + 7) >> 3) + 255) & ~255;
766         int numshadowtrispvsbytes = (((numshadowtriangles + 7) >> 3) + 255) & ~255;
767         int numlighttrispvsbytes = (((numlighttriangles + 7) >> 3) + 255) & ~255;
768         if (r_shadow_buffer_numleafpvsbytes < numleafpvsbytes)
769         {
770                 if (r_shadow_buffer_visitingleafpvs)
771                         Mem_Free(r_shadow_buffer_visitingleafpvs);
772                 if (r_shadow_buffer_leafpvs)
773                         Mem_Free(r_shadow_buffer_leafpvs);
774                 if (r_shadow_buffer_leaflist)
775                         Mem_Free(r_shadow_buffer_leaflist);
776                 r_shadow_buffer_numleafpvsbytes = numleafpvsbytes;
777                 r_shadow_buffer_visitingleafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
778                 r_shadow_buffer_leafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
779                 r_shadow_buffer_leaflist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes * 8 * sizeof(*r_shadow_buffer_leaflist));
780         }
781         if (r_shadow_buffer_numsurfacepvsbytes < numsurfacepvsbytes)
782         {
783                 if (r_shadow_buffer_surfacepvs)
784                         Mem_Free(r_shadow_buffer_surfacepvs);
785                 if (r_shadow_buffer_surfacelist)
786                         Mem_Free(r_shadow_buffer_surfacelist);
787                 r_shadow_buffer_numsurfacepvsbytes = numsurfacepvsbytes;
788                 r_shadow_buffer_surfacepvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes);
789                 r_shadow_buffer_surfacelist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
790         }
791         if (r_shadow_buffer_numshadowtrispvsbytes < numshadowtrispvsbytes)
792         {
793                 if (r_shadow_buffer_shadowtrispvs)
794                         Mem_Free(r_shadow_buffer_shadowtrispvs);
795                 r_shadow_buffer_numshadowtrispvsbytes = numshadowtrispvsbytes;
796                 r_shadow_buffer_shadowtrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numshadowtrispvsbytes);
797         }
798         if (r_shadow_buffer_numlighttrispvsbytes < numlighttrispvsbytes)
799         {
800                 if (r_shadow_buffer_lighttrispvs)
801                         Mem_Free(r_shadow_buffer_lighttrispvs);
802                 r_shadow_buffer_numlighttrispvsbytes = numlighttrispvsbytes;
803                 r_shadow_buffer_lighttrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numlighttrispvsbytes);
804         }
805 }
806
807 void R_Shadow_PrepareShadowMark(int numtris)
808 {
809         // make sure shadowmark is big enough for this volume
810         if (maxshadowmark < numtris)
811         {
812                 maxshadowmark = numtris;
813                 if (shadowmark)
814                         Mem_Free(shadowmark);
815                 if (shadowmarklist)
816                         Mem_Free(shadowmarklist);
817                 shadowmark = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmark));
818                 shadowmarklist = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmarklist));
819                 shadowmarkcount = 0;
820         }
821         shadowmarkcount++;
822         // if shadowmarkcount wrapped we clear the array and adjust accordingly
823         if (shadowmarkcount == 0)
824         {
825                 shadowmarkcount = 1;
826                 memset(shadowmark, 0, maxshadowmark * sizeof(*shadowmark));
827         }
828         numshadowmark = 0;
829 }
830
831 void R_Shadow_PrepareShadowSides(int numtris)
832 {
833     if (maxshadowsides < numtris)
834     {
835         maxshadowsides = numtris;
836         if (shadowsides)
837                         Mem_Free(shadowsides);
838                 if (shadowsideslist)
839                         Mem_Free(shadowsideslist);
840                 shadowsides = (unsigned char *)Mem_Alloc(r_main_mempool, maxshadowsides * sizeof(*shadowsides));
841                 shadowsideslist = (int *)Mem_Alloc(r_main_mempool, maxshadowsides * sizeof(*shadowsideslist));
842         }
843         numshadowsides = 0;
844 }
845
846 static int R_Shadow_ConstructShadowVolume_ZFail(int innumvertices, int innumtris, const int *inelement3i, const int *inneighbor3i, const float *invertex3f, int *outnumvertices, int *outelement3i, float *outvertex3f, const float *projectorigin, const float *projectdirection, float projectdistance, int numshadowmarktris, const int *shadowmarktris)
847 {
848         int i, j;
849         int outtriangles = 0, outvertices = 0;
850         const int *element;
851         const float *vertex;
852         float ratio, direction[3], projectvector[3];
853
854         if (projectdirection)
855                 VectorScale(projectdirection, projectdistance, projectvector);
856         else
857                 VectorClear(projectvector);
858
859         // create the vertices
860         if (projectdirection)
861         {
862                 for (i = 0;i < numshadowmarktris;i++)
863                 {
864                         element = inelement3i + shadowmarktris[i] * 3;
865                         for (j = 0;j < 3;j++)
866                         {
867                                 if (vertexupdate[element[j]] != vertexupdatenum)
868                                 {
869                                         vertexupdate[element[j]] = vertexupdatenum;
870                                         vertexremap[element[j]] = outvertices;
871                                         vertex = invertex3f + element[j] * 3;
872                                         // project one copy of the vertex according to projectvector
873                                         VectorCopy(vertex, outvertex3f);
874                                         VectorAdd(vertex, projectvector, (outvertex3f + 3));
875                                         outvertex3f += 6;
876                                         outvertices += 2;
877                                 }
878                         }
879                 }
880         }
881         else
882         {
883                 for (i = 0;i < numshadowmarktris;i++)
884                 {
885                         element = inelement3i + shadowmarktris[i] * 3;
886                         for (j = 0;j < 3;j++)
887                         {
888                                 if (vertexupdate[element[j]] != vertexupdatenum)
889                                 {
890                                         vertexupdate[element[j]] = vertexupdatenum;
891                                         vertexremap[element[j]] = outvertices;
892                                         vertex = invertex3f + element[j] * 3;
893                                         // project one copy of the vertex to the sphere radius of the light
894                                         // (FIXME: would projecting it to the light box be better?)
895                                         VectorSubtract(vertex, projectorigin, direction);
896                                         ratio = projectdistance / VectorLength(direction);
897                                         VectorCopy(vertex, outvertex3f);
898                                         VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
899                                         outvertex3f += 6;
900                                         outvertices += 2;
901                                 }
902                         }
903                 }
904         }
905
906         if (r_shadow_frontsidecasting.integer)
907         {
908                 for (i = 0;i < numshadowmarktris;i++)
909                 {
910                         int remappedelement[3];
911                         int markindex;
912                         const int *neighbortriangle;
913
914                         markindex = shadowmarktris[i] * 3;
915                         element = inelement3i + markindex;
916                         neighbortriangle = inneighbor3i + markindex;
917                         // output the front and back triangles
918                         outelement3i[0] = vertexremap[element[0]];
919                         outelement3i[1] = vertexremap[element[1]];
920                         outelement3i[2] = vertexremap[element[2]];
921                         outelement3i[3] = vertexremap[element[2]] + 1;
922                         outelement3i[4] = vertexremap[element[1]] + 1;
923                         outelement3i[5] = vertexremap[element[0]] + 1;
924
925                         outelement3i += 6;
926                         outtriangles += 2;
927                         // output the sides (facing outward from this triangle)
928                         if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
929                         {
930                                 remappedelement[0] = vertexremap[element[0]];
931                                 remappedelement[1] = vertexremap[element[1]];
932                                 outelement3i[0] = remappedelement[1];
933                                 outelement3i[1] = remappedelement[0];
934                                 outelement3i[2] = remappedelement[0] + 1;
935                                 outelement3i[3] = remappedelement[1];
936                                 outelement3i[4] = remappedelement[0] + 1;
937                                 outelement3i[5] = remappedelement[1] + 1;
938
939                                 outelement3i += 6;
940                                 outtriangles += 2;
941                         }
942                         if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
943                         {
944                                 remappedelement[1] = vertexremap[element[1]];
945                                 remappedelement[2] = vertexremap[element[2]];
946                                 outelement3i[0] = remappedelement[2];
947                                 outelement3i[1] = remappedelement[1];
948                                 outelement3i[2] = remappedelement[1] + 1;
949                                 outelement3i[3] = remappedelement[2];
950                                 outelement3i[4] = remappedelement[1] + 1;
951                                 outelement3i[5] = remappedelement[2] + 1;
952
953                                 outelement3i += 6;
954                                 outtriangles += 2;
955                         }
956                         if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
957                         {
958                                 remappedelement[0] = vertexremap[element[0]];
959                                 remappedelement[2] = vertexremap[element[2]];
960                                 outelement3i[0] = remappedelement[0];
961                                 outelement3i[1] = remappedelement[2];
962                                 outelement3i[2] = remappedelement[2] + 1;
963                                 outelement3i[3] = remappedelement[0];
964                                 outelement3i[4] = remappedelement[2] + 1;
965                                 outelement3i[5] = remappedelement[0] + 1;
966
967                                 outelement3i += 6;
968                                 outtriangles += 2;
969                         }
970                 }
971         }
972         else
973         {
974                 for (i = 0;i < numshadowmarktris;i++)
975                 {
976                         int remappedelement[3];
977                         int markindex;
978                         const int *neighbortriangle;
979
980                         markindex = shadowmarktris[i] * 3;
981                         element = inelement3i + markindex;
982                         neighbortriangle = inneighbor3i + markindex;
983                         // output the front and back triangles
984                         outelement3i[0] = vertexremap[element[2]];
985                         outelement3i[1] = vertexremap[element[1]];
986                         outelement3i[2] = vertexremap[element[0]];
987                         outelement3i[3] = vertexremap[element[0]] + 1;
988                         outelement3i[4] = vertexremap[element[1]] + 1;
989                         outelement3i[5] = vertexremap[element[2]] + 1;
990
991                         outelement3i += 6;
992                         outtriangles += 2;
993                         // output the sides (facing outward from this triangle)
994                         if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
995                         {
996                                 remappedelement[0] = vertexremap[element[0]];
997                                 remappedelement[1] = vertexremap[element[1]];
998                                 outelement3i[0] = remappedelement[0];
999                                 outelement3i[1] = remappedelement[1];
1000                                 outelement3i[2] = remappedelement[1] + 1;
1001                                 outelement3i[3] = remappedelement[0];
1002                                 outelement3i[4] = remappedelement[1] + 1;
1003                                 outelement3i[5] = remappedelement[0] + 1;
1004
1005                                 outelement3i += 6;
1006                                 outtriangles += 2;
1007                         }
1008                         if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
1009                         {
1010                                 remappedelement[1] = vertexremap[element[1]];
1011                                 remappedelement[2] = vertexremap[element[2]];
1012                                 outelement3i[0] = remappedelement[1];
1013                                 outelement3i[1] = remappedelement[2];
1014                                 outelement3i[2] = remappedelement[2] + 1;
1015                                 outelement3i[3] = remappedelement[1];
1016                                 outelement3i[4] = remappedelement[2] + 1;
1017                                 outelement3i[5] = remappedelement[1] + 1;
1018
1019                                 outelement3i += 6;
1020                                 outtriangles += 2;
1021                         }
1022                         if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
1023                         {
1024                                 remappedelement[0] = vertexremap[element[0]];
1025                                 remappedelement[2] = vertexremap[element[2]];
1026                                 outelement3i[0] = remappedelement[2];
1027                                 outelement3i[1] = remappedelement[0];
1028                                 outelement3i[2] = remappedelement[0] + 1;
1029                                 outelement3i[3] = remappedelement[2];
1030                                 outelement3i[4] = remappedelement[0] + 1;
1031                                 outelement3i[5] = remappedelement[2] + 1;
1032
1033                                 outelement3i += 6;
1034                                 outtriangles += 2;
1035                         }
1036                 }
1037         }
1038         if (outnumvertices)
1039                 *outnumvertices = outvertices;
1040         return outtriangles;
1041 }
1042
1043 static int R_Shadow_ConstructShadowVolume_ZPass(int innumvertices, int innumtris, const int *inelement3i, const int *inneighbor3i, const float *invertex3f, int *outnumvertices, int *outelement3i, float *outvertex3f, const float *projectorigin, const float *projectdirection, float projectdistance, int numshadowmarktris, const int *shadowmarktris)
1044 {
1045         int i, j, k;
1046         int outtriangles = 0, outvertices = 0;
1047         const int *element;
1048         const float *vertex;
1049         float ratio, direction[3], projectvector[3];
1050         qboolean side[4];
1051
1052         if (projectdirection)
1053                 VectorScale(projectdirection, projectdistance, projectvector);
1054         else
1055                 VectorClear(projectvector);
1056
1057         for (i = 0;i < numshadowmarktris;i++)
1058         {
1059                 int remappedelement[3];
1060                 int markindex;
1061                 const int *neighbortriangle;
1062
1063                 markindex = shadowmarktris[i] * 3;
1064                 neighbortriangle = inneighbor3i + markindex;
1065                 side[0] = shadowmark[neighbortriangle[0]] == shadowmarkcount;
1066                 side[1] = shadowmark[neighbortriangle[1]] == shadowmarkcount;
1067                 side[2] = shadowmark[neighbortriangle[2]] == shadowmarkcount;
1068                 if (side[0] + side[1] + side[2] == 0)
1069                         continue;
1070
1071                 side[3] = side[0];
1072                 element = inelement3i + markindex;
1073
1074                 // create the vertices
1075                 for (j = 0;j < 3;j++)
1076                 {
1077                         if (side[j] + side[j+1] == 0)
1078                                 continue;
1079                         k = element[j];
1080                         if (vertexupdate[k] != vertexupdatenum)
1081                         {
1082                                 vertexupdate[k] = vertexupdatenum;
1083                                 vertexremap[k] = outvertices;
1084                                 vertex = invertex3f + k * 3;
1085                                 VectorCopy(vertex, outvertex3f);
1086                                 if (projectdirection)
1087                                 {
1088                                         // project one copy of the vertex according to projectvector
1089                                         VectorAdd(vertex, projectvector, (outvertex3f + 3));
1090                                 }
1091                                 else
1092                                 {
1093                                         // project one copy of the vertex to the sphere radius of the light
1094                                         // (FIXME: would projecting it to the light box be better?)
1095                                         VectorSubtract(vertex, projectorigin, direction);
1096                                         ratio = projectdistance / VectorLength(direction);
1097                                         VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
1098                                 }
1099                                 outvertex3f += 6;
1100                                 outvertices += 2;
1101                         }
1102                 }
1103
1104                 // output the sides (facing outward from this triangle)
1105                 if (!side[0])
1106                 {
1107                         remappedelement[0] = vertexremap[element[0]];
1108                         remappedelement[1] = vertexremap[element[1]];
1109                         outelement3i[0] = remappedelement[1];
1110                         outelement3i[1] = remappedelement[0];
1111                         outelement3i[2] = remappedelement[0] + 1;
1112                         outelement3i[3] = remappedelement[1];
1113                         outelement3i[4] = remappedelement[0] + 1;
1114                         outelement3i[5] = remappedelement[1] + 1;
1115
1116                         outelement3i += 6;
1117                         outtriangles += 2;
1118                 }
1119                 if (!side[1])
1120                 {
1121                         remappedelement[1] = vertexremap[element[1]];
1122                         remappedelement[2] = vertexremap[element[2]];
1123                         outelement3i[0] = remappedelement[2];
1124                         outelement3i[1] = remappedelement[1];
1125                         outelement3i[2] = remappedelement[1] + 1;
1126                         outelement3i[3] = remappedelement[2];
1127                         outelement3i[4] = remappedelement[1] + 1;
1128                         outelement3i[5] = remappedelement[2] + 1;
1129
1130                         outelement3i += 6;
1131                         outtriangles += 2;
1132                 }
1133                 if (!side[2])
1134                 {
1135                         remappedelement[0] = vertexremap[element[0]];
1136                         remappedelement[2] = vertexremap[element[2]];
1137                         outelement3i[0] = remappedelement[0];
1138                         outelement3i[1] = remappedelement[2];
1139                         outelement3i[2] = remappedelement[2] + 1;
1140                         outelement3i[3] = remappedelement[0];
1141                         outelement3i[4] = remappedelement[2] + 1;
1142                         outelement3i[5] = remappedelement[0] + 1;
1143
1144                         outelement3i += 6;
1145                         outtriangles += 2;
1146                 }
1147         }
1148         if (outnumvertices)
1149                 *outnumvertices = outvertices;
1150         return outtriangles;
1151 }
1152
1153 void R_Shadow_MarkVolumeFromBox(int firsttriangle, int numtris, const float *invertex3f, const int *elements, const vec3_t projectorigin, const vec3_t projectdirection, const vec3_t lightmins, const vec3_t lightmaxs, const vec3_t surfacemins, const vec3_t surfacemaxs)
1154 {
1155         int t, tend;
1156         const int *e;
1157         const float *v[3];
1158         float normal[3];
1159         if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1160                 return;
1161         tend = firsttriangle + numtris;
1162         if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1163         {
1164                 // surface box entirely inside light box, no box cull
1165                 if (projectdirection)
1166                 {
1167                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1168                         {
1169                                 TriangleNormal(invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3, normal);
1170                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1171                                         shadowmarklist[numshadowmark++] = t;
1172                         }
1173                 }
1174                 else
1175                 {
1176                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1177                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3))
1178                                         shadowmarklist[numshadowmark++] = t;
1179                 }
1180         }
1181         else
1182         {
1183                 // surface box not entirely inside light box, cull each triangle
1184                 if (projectdirection)
1185                 {
1186                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1187                         {
1188                                 v[0] = invertex3f + e[0] * 3;
1189                                 v[1] = invertex3f + e[1] * 3;
1190                                 v[2] = invertex3f + e[2] * 3;
1191                                 TriangleNormal(v[0], v[1], v[2], normal);
1192                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1193                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1194                                         shadowmarklist[numshadowmark++] = t;
1195                         }
1196                 }
1197                 else
1198                 {
1199                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1200                         {
1201                                 v[0] = invertex3f + e[0] * 3;
1202                                 v[1] = invertex3f + e[1] * 3;
1203                                 v[2] = invertex3f + e[2] * 3;
1204                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1205                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1206                                         shadowmarklist[numshadowmark++] = t;
1207                         }
1208                 }
1209         }
1210 }
1211
1212 qboolean R_Shadow_UseZPass(vec3_t mins, vec3_t maxs)
1213 {
1214 #if 1
1215         return false;
1216 #else
1217         if (r_shadow_compilingrtlight || !r_shadow_frontsidecasting.integer || !r_shadow_usezpassifpossible.integer)
1218                 return false;
1219         // check if the shadow volume intersects the near plane
1220         //
1221         // a ray between the eye and light origin may intersect the caster,
1222         // indicating that the shadow may touch the eye location, however we must
1223         // test the near plane (a polygon), not merely the eye location, so it is
1224         // easiest to enlarge the caster bounding shape slightly for this.
1225         // TODO
1226         return true;
1227 #endif
1228 }
1229
1230 void R_Shadow_VolumeFromList(int numverts, int numtris, const float *invertex3f, const int *elements, const int *neighbors, const vec3_t projectorigin, const vec3_t projectdirection, float projectdistance, int nummarktris, const int *marktris, vec3_t trismins, vec3_t trismaxs)
1231 {
1232         int i, tris, outverts;
1233         if (projectdistance < 0.1)
1234         {
1235                 Con_Printf("R_Shadow_Volume: projectdistance %f\n", projectdistance);
1236                 return;
1237         }
1238         if (!numverts || !nummarktris)
1239                 return;
1240         // make sure shadowelements is big enough for this volume
1241         if (maxshadowtriangles < nummarktris*8 || maxshadowvertices < numverts*2)
1242                 R_Shadow_ResizeShadowArrays(numverts, nummarktris, 2, 8);
1243
1244         if (maxvertexupdate < numverts)
1245         {
1246                 maxvertexupdate = numverts;
1247                 if (vertexupdate)
1248                         Mem_Free(vertexupdate);
1249                 if (vertexremap)
1250                         Mem_Free(vertexremap);
1251                 vertexupdate = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1252                 vertexremap = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1253                 vertexupdatenum = 0;
1254         }
1255         vertexupdatenum++;
1256         if (vertexupdatenum == 0)
1257         {
1258                 vertexupdatenum = 1;
1259                 memset(vertexupdate, 0, maxvertexupdate * sizeof(int));
1260                 memset(vertexremap, 0, maxvertexupdate * sizeof(int));
1261         }
1262
1263         for (i = 0;i < nummarktris;i++)
1264                 shadowmark[marktris[i]] = shadowmarkcount;
1265
1266         if (r_shadow_compilingrtlight)
1267         {
1268                 // if we're compiling an rtlight, capture the mesh
1269                 //tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1270                 //Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zpass, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1271                 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1272                 Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zfail, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1273         }
1274         else
1275         {
1276                 // decide which type of shadow to generate and set stencil mode
1277                 R_Shadow_RenderMode_StencilShadowVolumes(R_Shadow_UseZPass(trismins, trismaxs));
1278                 // generate the sides or a solid volume, depending on type
1279                 if (r_shadow_rendermode >= R_SHADOW_RENDERMODE_ZPASS_STENCIL && r_shadow_rendermode <= R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE)
1280                         tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1281                 else
1282                         tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1283                 r_refdef.stats.lights_dynamicshadowtriangles += tris;
1284                 r_refdef.stats.lights_shadowtriangles += tris;
1285                 CHECKGLERROR
1286                 R_Mesh_VertexPointer(shadowvertex3f, 0, 0);
1287                 GL_LockArrays(0, outverts);
1288                 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
1289                 {
1290                         // increment stencil if frontface is infront of depthbuffer
1291                         GL_CullFace(r_refdef.view.cullface_front);
1292                         qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
1293                         R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, 0);
1294                         // decrement stencil if backface is infront of depthbuffer
1295                         GL_CullFace(r_refdef.view.cullface_back);
1296                         qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
1297                 }
1298                 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
1299                 {
1300                         // decrement stencil if backface is behind depthbuffer
1301                         GL_CullFace(r_refdef.view.cullface_front);
1302                         qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
1303                         R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, 0);
1304                         // increment stencil if frontface is behind depthbuffer
1305                         GL_CullFace(r_refdef.view.cullface_back);
1306                         qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
1307                 }
1308                 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, 0);
1309                 GL_LockArrays(0, 0);
1310                 CHECKGLERROR
1311         }
1312 }
1313
1314 int R_Shadow_CalcTriangleSideMask(const vec3_t p1, const vec3_t p2, const vec3_t p3, float bias)
1315 {
1316     // p1, p2, p3 are in the cubemap's local coordinate system
1317     // bias = border/(size - border)
1318         int mask = 0x3F;
1319
1320     float dp1 = p1[0] + p1[1], dn1 = p1[0] - p1[1], ap1 = fabs(dp1), an1 = fabs(dn1),
1321           dp2 = p2[0] + p2[1], dn2 = p2[0] - p2[1], ap2 = fabs(dp2), an2 = fabs(dn2),
1322           dp3 = p3[0] + p3[1], dn3 = p3[0] - p3[1], ap3 = fabs(dp3), an3 = fabs(dn3);
1323         if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1324         mask &= (3<<4)
1325                         | (dp1 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1326                         | (dp2 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1327                         | (dp3 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1328     if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1329         mask &= (3<<4)
1330             | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1331             | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))            
1332             | (dn3 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1333
1334     dp1 = p1[1] + p1[2], dn1 = p1[1] - p1[2], ap1 = fabs(dp1), an1 = fabs(dn1),
1335     dp2 = p2[1] + p2[2], dn2 = p2[1] - p2[2], ap2 = fabs(dp2), an2 = fabs(dn2),
1336     dp3 = p3[1] + p3[2], dn3 = p3[1] - p3[2], ap3 = fabs(dp3), an3 = fabs(dn3);
1337     if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1338         mask &= (3<<0)
1339             | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))
1340             | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))            
1341             | (dp3 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1342     if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1343         mask &= (3<<0)
1344             | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1345             | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1346             | (dn3 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1347
1348     dp1 = p1[2] + p1[0], dn1 = p1[2] - p1[0], ap1 = fabs(dp1), an1 = fabs(dn1),
1349     dp2 = p2[2] + p2[0], dn2 = p2[2] - p2[0], ap2 = fabs(dp2), an2 = fabs(dn2),
1350     dp3 = p3[2] + p3[0], dn3 = p3[2] - p3[0], ap3 = fabs(dp3), an3 = fabs(dn3);
1351     if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1352         mask &= (3<<2)
1353             | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1354             | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1355             | (dp3 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1356     if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1357         mask &= (3<<2)
1358             | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1359             | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1360             | (dn3 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1361
1362         return mask;
1363 }
1364
1365 int R_Shadow_CalcSphereSideMask(const vec3_t p, float radius, float bias)
1366 {
1367     // p is in the cubemap's local coordinate system
1368     // bias = border/(size - border)
1369     float dxyp = p[0] + p[1], dxyn = p[0] - p[1], axyp = fabs(dxyp), axyn = fabs(dxyn);
1370     float dyzp = p[1] + p[2], dyzn = p[1] - p[2], ayzp = fabs(dyzp), ayzn = fabs(dyzn);
1371     float dzxp = p[2] + p[0], dzxn = p[2] - p[0], azxp = fabs(dzxp), azxn = fabs(dzxn);
1372     int mask = 0x3F;
1373     if(axyp > bias*axyn + radius) mask &= dxyp < 0 ? ~((1<<0)|(1<<2)) : ~((2<<0)|(2<<2));
1374     if(axyn > bias*axyp + radius) mask &= dxyn < 0 ? ~((1<<0)|(2<<2)) : ~((2<<0)|(1<<2));
1375     if(ayzp > bias*ayzn + radius) mask &= dyzp < 0 ? ~((1<<2)|(1<<4)) : ~((2<<2)|(2<<4));
1376     if(ayzn > bias*ayzp + radius) mask &= dyzn < 0 ? ~((1<<2)|(2<<4)) : ~((2<<2)|(1<<4));
1377     if(azxp > bias*azxn + radius) mask &= dzxp < 0 ? ~((1<<4)|(1<<0)) : ~((2<<4)|(2<<0));
1378     if(azxn > bias*azxp + radius) mask &= dzxn < 0 ? ~((1<<4)|(2<<0)) : ~((2<<4)|(1<<0));
1379     return mask;
1380 }
1381
1382 int R_Shadow_FrustumCullSides(rtlight_t *rtlight, float size, float border)
1383 {
1384         static const vec3_t lightnormals[6] = { { 1, 0, 0 }, { -1, 0, 0 }, { 0, 1, 0 }, { 0, -1, 0 }, { 0, 0, 1 }, { 0, 0, -1 } };
1385         vec3_t frustumdir;
1386         int i, j;
1387         int sides = 0x3F;
1388         // cos(45 + bias)
1389         float scale = 0.707106781186548*(size - 2*border)/size;
1390         for (i = 0;i < 5;i++)
1391         {
1392                 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) > -0.03125)
1393                         continue;
1394                 Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[i].normal, frustumdir);
1395                 VectorNormalize(frustumdir);
1396                 for (j = 0;j < 6;j++)
1397                         if(DotProduct(frustumdir, lightnormals[j]) < -scale)
1398                                 sides &= ~(1 << j);
1399         }
1400     if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[4]) > r_refdef.farclip - r_refdef.nearclip + 0.03125)
1401         {
1402         Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[4].normal, frustumdir);
1403         VectorNormalize(frustumdir);
1404                 for (j = 0;j < 6;j++)
1405                 if (DotProduct(frustumdir, lightnormals[j]) > scale) 
1406                 sides &= ~(1 << j);
1407         }
1408         return sides;
1409 }
1410
1411 int R_Shadow_ChooseSidesFromBox(int firsttriangle, int numtris, const float *invertex3f, const int *elements, const matrix4x4_t *worldtolight, const vec3_t projectorigin, const vec3_t projectdirection, const vec3_t lightmins, const vec3_t lightmaxs, const vec3_t surfacemins, const vec3_t surfacemaxs, int *totals)
1412 {
1413         int t, tend;
1414         const int *e;
1415         const float *v[3];
1416         float normal[3];
1417         vec3_t p[3];
1418         float bias;
1419         int mask, surfacemask = 0;
1420         if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1421                 return 0;
1422         bias = r_shadow_shadowmapborder / (float)(r_shadow_shadowmapmaxsize - r_shadow_shadowmapborder);
1423         tend = firsttriangle + numtris;
1424         if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1425         {
1426                 // surface box entirely inside light box, no box cull
1427                 if (projectdirection)
1428                 {
1429                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1430                         {
1431                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1432                                 TriangleNormal(v[0], v[1], v[2], normal);
1433                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1434                                 {
1435                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1436                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1437                                         surfacemask |= mask;
1438                                         if(totals)
1439                                         {
1440                                                 totals[0] += mask&1, totals[1] += (mask>>1)&1, totals[2] += (mask>>2)&1, totals[3] += (mask>>3)&1, totals[4] += (mask>>4)&1, totals[5] += mask>>5;
1441                                                 shadowsides[numshadowsides] = mask;
1442                                                 shadowsideslist[numshadowsides++] = t;
1443                                         }
1444                                 }
1445                         }
1446                 }
1447                 else
1448                 {
1449                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1450                         {
1451                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3,     v[2] = invertex3f + e[2] * 3;
1452                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2]))
1453                                 {
1454                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1455                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1456                                         surfacemask |= mask;
1457                                         if(totals)
1458                                         {
1459                                                 totals[0] += mask&1, totals[1] += (mask>>1)&1, totals[2] += (mask>>2)&1, totals[3] += (mask>>3)&1, totals[4] += (mask>>4)&1, totals[5] += mask>>5;
1460                                                 shadowsides[numshadowsides] = mask;
1461                                                 shadowsideslist[numshadowsides++] = t;
1462                                         }
1463                                 }
1464                         }
1465                 }
1466         }
1467         else
1468         {
1469                 // surface box not entirely inside light box, cull each triangle
1470                 if (projectdirection)
1471                 {
1472                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1473                         {
1474                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3,     v[2] = invertex3f + e[2] * 3;
1475                                 TriangleNormal(v[0], v[1], v[2], normal);
1476                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1477                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1478                                 {
1479                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1480                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1481                                         surfacemask |= mask;
1482                                         if(totals)
1483                                         {
1484                                                 totals[0] += mask&1, totals[1] += (mask>>1)&1, totals[2] += (mask>>2)&1, totals[3] += (mask>>3)&1, totals[4] += (mask>>4)&1, totals[5] += mask>>5;
1485                                                 shadowsides[numshadowsides] = mask;
1486                                                 shadowsideslist[numshadowsides++] = t;
1487                                         }
1488                                 }
1489                         }
1490                 }
1491                 else
1492                 {
1493                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1494                         {
1495                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1496                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1497                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1498                                 {
1499                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1500                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1501                                         surfacemask |= mask;
1502                                         if(totals)
1503                                         {
1504                                                 totals[0] += mask&1, totals[1] += (mask>>1)&1, totals[2] += (mask>>2)&1, totals[3] += (mask>>3)&1, totals[4] += (mask>>4)&1, totals[5] += mask>>5;
1505                                                 shadowsides[numshadowsides] = mask;
1506                                                 shadowsideslist[numshadowsides++] = t;
1507                                         }
1508                                 }
1509                         }
1510                 }
1511         }
1512         return surfacemask;
1513 }
1514
1515 void R_Shadow_ShadowMapFromList(int numverts, int numtris, const float *vertex3f, const int *elements, int numsidetris, const int *sidetotals, const unsigned char *sides, const int *sidetris)
1516 {
1517         int i, j, outtriangles = 0;
1518         int *outelement3i[6];
1519         if (!numverts || !numsidetris || !r_shadow_compilingrtlight)
1520                 return;
1521         outtriangles = sidetotals[0] + sidetotals[1] + sidetotals[2] + sidetotals[3] + sidetotals[4] + sidetotals[5];
1522         // make sure shadowelements is big enough for this mesh
1523         if (maxshadowtriangles < outtriangles)
1524                 R_Shadow_ResizeShadowArrays(0, outtriangles, 0, 1);
1525
1526         // compute the offset and size of the separate index lists for each cubemap side
1527         outtriangles = 0;
1528         for (i = 0;i < 6;i++)
1529         {
1530                 outelement3i[i] = shadowelements + outtriangles * 3;
1531                 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap->sideoffsets[i] = outtriangles;
1532                 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap->sidetotals[i] = sidetotals[i];
1533                 outtriangles += sidetotals[i];
1534         }
1535
1536         // gather up the (sparse) triangles into separate index lists for each cubemap side
1537         for (i = 0;i < numsidetris;i++)
1538         {
1539                 const int *element = elements + sidetris[i] * 3;
1540                 for (j = 0;j < 6;j++)
1541                 {
1542                         if (sides[i] & (1 << j))
1543                         {
1544                                 outelement3i[j][0] = element[0];
1545                                 outelement3i[j][1] = element[1];
1546                                 outelement3i[j][2] = element[2];
1547                                 outelement3i[j] += 3;
1548                         }
1549                 }
1550         }
1551                         
1552         Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap, NULL, NULL, NULL, vertex3f, NULL, NULL, NULL, NULL, outtriangles, shadowelements);
1553 }
1554
1555 static void R_Shadow_MakeTextures_MakeCorona(void)
1556 {
1557         float dx, dy;
1558         int x, y, a;
1559         unsigned char pixels[32][32][4];
1560         for (y = 0;y < 32;y++)
1561         {
1562                 dy = (y - 15.5f) * (1.0f / 16.0f);
1563                 for (x = 0;x < 32;x++)
1564                 {
1565                         dx = (x - 15.5f) * (1.0f / 16.0f);
1566                         a = (int)(((1.0f / (dx * dx + dy * dy + 0.2f)) - (1.0f / (1.0f + 0.2))) * 32.0f / (1.0f / (1.0f + 0.2)));
1567                         a = bound(0, a, 255);
1568                         pixels[y][x][0] = a;
1569                         pixels[y][x][1] = a;
1570                         pixels[y][x][2] = a;
1571                         pixels[y][x][3] = 255;
1572                 }
1573         }
1574         r_shadow_lightcorona = R_LoadTexture2D(r_shadow_texturepool, "lightcorona", 32, 32, &pixels[0][0][0], TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_FORCELINEAR, NULL);
1575 }
1576
1577 static unsigned int R_Shadow_MakeTextures_SamplePoint(float x, float y, float z)
1578 {
1579         float dist = sqrt(x*x+y*y+z*z);
1580         float intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1581         // note this code could suffer byte order issues except that it is multiplying by an integer that reads the same both ways
1582         return (unsigned char)bound(0, intensity * 256.0f, 255) * 0x01010101;
1583 }
1584
1585 static void R_Shadow_MakeTextures(void)
1586 {
1587         int x, y, z;
1588         float intensity, dist;
1589         unsigned int *data;
1590         R_FreeTexturePool(&r_shadow_texturepool);
1591         r_shadow_texturepool = R_AllocTexturePool();
1592         r_shadow_attenlinearscale = r_shadow_lightattenuationlinearscale.value;
1593         r_shadow_attendividebias = r_shadow_lightattenuationdividebias.value;
1594         data = (unsigned int *)Mem_Alloc(tempmempool, max(max(ATTEN3DSIZE*ATTEN3DSIZE*ATTEN3DSIZE, ATTEN2DSIZE*ATTEN2DSIZE), ATTEN1DSIZE) * 4);
1595         // the table includes one additional value to avoid the need to clamp indexing due to minor math errors
1596         for (x = 0;x <= ATTENTABLESIZE;x++)
1597         {
1598                 dist = (x + 0.5f) * (1.0f / ATTENTABLESIZE) * (1.0f / 0.9375);
1599                 intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1600                 r_shadow_attentable[x] = bound(0, intensity, 1);
1601         }
1602         // 1D gradient texture
1603         for (x = 0;x < ATTEN1DSIZE;x++)
1604                 data[x] = R_Shadow_MakeTextures_SamplePoint((x + 0.5f) * (1.0f / ATTEN1DSIZE) * (1.0f / 0.9375), 0, 0);
1605         r_shadow_attenuationgradienttexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation1d", ATTEN1DSIZE, 1, (unsigned char *)data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, NULL);
1606         // 2D circle texture
1607         for (y = 0;y < ATTEN2DSIZE;y++)
1608                 for (x = 0;x < ATTEN2DSIZE;x++)
1609                         data[y*ATTEN2DSIZE+x] = R_Shadow_MakeTextures_SamplePoint(((x + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375), ((y + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375), 0);
1610         r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, NULL);
1611         // 3D sphere texture
1612         if (r_shadow_texture3d.integer && gl_texture3d)
1613         {
1614                 for (z = 0;z < ATTEN3DSIZE;z++)
1615                         for (y = 0;y < ATTEN3DSIZE;y++)
1616                                 for (x = 0;x < ATTEN3DSIZE;x++)
1617                                         data[(z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x] = R_Shadow_MakeTextures_SamplePoint(((x + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375), ((y + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375), ((z + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375));
1618                 r_shadow_attenuation3dtexture = R_LoadTexture3D(r_shadow_texturepool, "attenuation3d", ATTEN3DSIZE, ATTEN3DSIZE, ATTEN3DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, NULL);
1619         }
1620         else
1621                 r_shadow_attenuation3dtexture = NULL;
1622         Mem_Free(data);
1623
1624         R_Shadow_MakeTextures_MakeCorona();
1625
1626         // Editor light sprites
1627         r_editlights_sprcursor = Draw_CachePic ("gfx/editlights/cursor");
1628         r_editlights_sprlight = Draw_CachePic ("gfx/editlights/light");
1629         r_editlights_sprnoshadowlight = Draw_CachePic ("gfx/editlights/noshadow");
1630         r_editlights_sprcubemaplight = Draw_CachePic ("gfx/editlights/cubemaplight");
1631         r_editlights_sprcubemapnoshadowlight = Draw_CachePic ("gfx/editlights/cubemapnoshadowlight");
1632         r_editlights_sprselection = Draw_CachePic ("gfx/editlights/selection");
1633 }
1634
1635 void R_Shadow_ValidateCvars(void)
1636 {
1637         if (r_shadow_texture3d.integer && !gl_texture3d)
1638                 Cvar_SetValueQuick(&r_shadow_texture3d, 0);
1639         if (gl_ext_separatestencil.integer && !gl_support_separatestencil)
1640                 Cvar_SetValueQuick(&gl_ext_separatestencil, 0);
1641         if (gl_ext_stenciltwoside.integer && !gl_support_stenciltwoside)
1642                 Cvar_SetValueQuick(&gl_ext_stenciltwoside, 0);
1643 }
1644
1645 void R_Shadow_RenderMode_Begin(void)
1646 {
1647         GLint drawbuffer;
1648         GLint readbuffer;
1649         R_Shadow_ValidateCvars();
1650
1651         if (!r_shadow_attenuation2dtexture
1652          || (!r_shadow_attenuation3dtexture && r_shadow_texture3d.integer)
1653          || r_shadow_lightattenuationdividebias.value != r_shadow_attendividebias
1654          || r_shadow_lightattenuationlinearscale.value != r_shadow_attenlinearscale)
1655                 R_Shadow_MakeTextures();
1656
1657         CHECKGLERROR
1658         R_Mesh_ColorPointer(NULL, 0, 0);
1659         R_Mesh_ResetTextureState();
1660         GL_BlendFunc(GL_ONE, GL_ZERO);
1661         GL_DepthRange(0, 1);
1662         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
1663         GL_DepthTest(true);
1664         GL_DepthMask(false);
1665         GL_Color(0, 0, 0, 1);
1666         GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
1667
1668         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
1669
1670         if (gl_ext_separatestencil.integer)
1671         {
1672                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL;
1673                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL;
1674         }
1675         else if (gl_ext_stenciltwoside.integer)
1676         {
1677                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE;
1678                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE;
1679         }
1680         else
1681         {
1682                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCIL;
1683                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCIL;
1684         }
1685
1686         if (r_glsl.integer && gl_support_fragment_shader)
1687                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_GLSL;
1688         else if (gl_dot3arb && gl_texturecubemap && r_textureunits.integer >= 2 && gl_combine.integer && gl_stencil)
1689                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_DOT3;
1690         else
1691                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX;
1692
1693         CHECKGLERROR
1694         qglGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);CHECKGLERROR
1695         qglGetIntegerv(GL_READ_BUFFER, &readbuffer);CHECKGLERROR
1696         r_shadow_drawbuffer = drawbuffer;
1697         r_shadow_readbuffer = readbuffer;
1698         r_shadow_cullface = r_refdef.view.cullface_back;
1699 }
1700
1701 void R_Shadow_RenderMode_ActiveLight(const rtlight_t *rtlight)
1702 {
1703         rsurface.rtlight = rtlight;
1704 }
1705
1706 void R_Shadow_RenderMode_Reset(void)
1707 {
1708         CHECKGLERROR
1709         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE || r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE)
1710         {
1711                 qglDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
1712         }
1713         if (gl_support_ext_framebuffer_object)
1714         {
1715                 qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);CHECKGLERROR
1716         }
1717         qglDrawBuffer(r_shadow_drawbuffer);CHECKGLERROR
1718         qglReadBuffer(r_shadow_readbuffer);CHECKGLERROR
1719         R_SetViewport(&r_refdef.view.viewport);
1720         GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
1721         R_Mesh_ColorPointer(NULL, 0, 0);
1722         R_Mesh_ResetTextureState();
1723         GL_DepthRange(0, 1);
1724         GL_DepthTest(true);
1725         GL_DepthMask(false);
1726         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
1727         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
1728         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
1729         qglStencilMask(~0);CHECKGLERROR
1730         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
1731         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
1732         r_refdef.view.cullface_back = r_shadow_cullface;
1733         GL_CullFace(r_refdef.view.cullface_back);
1734         GL_Color(1, 1, 1, 1);
1735         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
1736         GL_BlendFunc(GL_ONE, GL_ZERO);
1737         R_SetupGenericShader(false);
1738         r_shadow_usingshadowmaprect = false;
1739         r_shadow_usingshadowmapcube = false;
1740         r_shadow_usingshadowmap2d = false;
1741         CHECKGLERROR
1742 }
1743
1744 void R_Shadow_ClearStencil(void)
1745 {
1746         CHECKGLERROR
1747         GL_Clear(GL_STENCIL_BUFFER_BIT);
1748         r_refdef.stats.lights_clears++;
1749 }
1750
1751 void R_Shadow_RenderMode_StencilShadowVolumes(qboolean zpass)
1752 {
1753         r_shadow_rendermode_t mode = zpass ? r_shadow_shadowingrendermode_zpass : r_shadow_shadowingrendermode_zfail;
1754         if (r_shadow_rendermode == mode)
1755                 return;
1756         CHECKGLERROR
1757         R_Shadow_RenderMode_Reset();
1758         GL_ColorMask(0, 0, 0, 0);
1759         GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
1760         R_SetupDepthOrShadowShader();
1761         qglDepthFunc(GL_LESS);CHECKGLERROR
1762         qglEnable(GL_STENCIL_TEST);CHECKGLERROR
1763         r_shadow_rendermode = mode;
1764         switch(mode)
1765         {
1766         default:
1767                 break;
1768         case R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL:
1769                 GL_CullFace(GL_NONE);
1770                 qglStencilOpSeparate(r_refdef.view.cullface_front, GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
1771                 qglStencilOpSeparate(r_refdef.view.cullface_back, GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
1772                 break;
1773         case R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL:
1774                 GL_CullFace(GL_NONE);
1775                 qglStencilOpSeparate(r_refdef.view.cullface_front, GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
1776                 qglStencilOpSeparate(r_refdef.view.cullface_back, GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
1777                 break;
1778         case R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE:
1779                 GL_CullFace(GL_NONE);
1780                 qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
1781                 qglActiveStencilFaceEXT(r_refdef.view.cullface_front);CHECKGLERROR
1782                 qglStencilMask(~0);CHECKGLERROR
1783                 qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
1784                 qglActiveStencilFaceEXT(r_refdef.view.cullface_back);CHECKGLERROR
1785                 qglStencilMask(~0);CHECKGLERROR
1786                 qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
1787                 break;
1788         case R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE:
1789                 GL_CullFace(GL_NONE);
1790                 qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
1791                 qglActiveStencilFaceEXT(r_refdef.view.cullface_front);CHECKGLERROR
1792                 qglStencilMask(~0);CHECKGLERROR
1793                 qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
1794                 qglActiveStencilFaceEXT(r_refdef.view.cullface_back);CHECKGLERROR
1795                 qglStencilMask(~0);CHECKGLERROR
1796                 qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
1797                 break;
1798         }
1799 }
1800
1801 static void R_Shadow_MakeVSDCT(void)
1802 {
1803         // maps to a 2x3 texture rectangle with normalized coordinates
1804         // +-
1805         // XX
1806         // YY
1807         // ZZ
1808         // stores abs(dir.xy), offset.xy/2.5
1809         unsigned char data[4*6] =
1810         {
1811                 255, 0, 0x33, 0x33, // +X: <1, 0>, <0.5, 0.5>
1812                 255, 0, 0x99, 0x33, // -X: <1, 0>, <1.5, 0.5>
1813                 0, 255, 0x33, 0x99, // +Y: <0, 1>, <0.5, 1.5>
1814                 0, 255, 0x99, 0x99, // -Y: <0, 1>, <1.5, 1.5>
1815                 0,   0, 0x33, 0xFF, // +Z: <0, 0>, <0.5, 2.5>
1816                 0,   0, 0x99, 0xFF, // -Z: <0, 0>, <1.5, 2.5>
1817         };
1818         r_shadow_shadowmapvsdcttexture = R_LoadTextureCubeMap(r_shadow_texturepool, "shadowmapvsdct", 1, data, TEXTYPE_RGBA, TEXF_ALWAYSPRECACHE | TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, NULL); 
1819 }
1820
1821 void R_Shadow_RenderMode_ShadowMap(int side, qboolean clear, int size)
1822 {
1823         int i;
1824         int status;
1825         int maxsize;
1826         float nearclip, farclip, bias;
1827         r_viewport_t viewport;
1828         CHECKGLERROR
1829         maxsize = r_shadow_shadowmapmaxsize;
1830         nearclip = r_shadow_shadowmapping_nearclip.value / rsurface.rtlight->radius;
1831         farclip = 1.0f;
1832         bias = r_shadow_shadowmapping_bias.value * nearclip * (1024.0f / size);// * rsurface.rtlight->radius;
1833         r_shadow_shadowmap_parameters[2] = 0.5f + 0.5f * (farclip + nearclip) / (farclip - nearclip);
1834         r_shadow_shadowmap_parameters[3] = -nearclip * farclip / (farclip - nearclip) - 0.5f * bias;
1835         r_shadow_shadowmapside = side;
1836         r_shadow_shadowmapsize = size;
1837         if (r_shadow_shadowmode == 1)
1838         {
1839                 // complex unrolled cube approach (more flexible)
1840                 if (r_shadow_shadowmapvsdct && !r_shadow_shadowmapvsdcttexture)
1841                         R_Shadow_MakeVSDCT();
1842                 if (!r_shadow_shadowmap2dtexture)
1843                 {
1844 #if 1
1845                         int w = maxsize*2, h = gl_support_arb_texture_non_power_of_two ? maxsize*3 : maxsize*4;
1846                         r_shadow_shadowmap2dtexture = R_LoadTextureShadowMap2D(r_shadow_texturepool, "shadowmap", w, h, r_shadow_shadowmapprecision, r_shadow_shadowmapsampler);
1847                         qglGenFramebuffersEXT(1, &r_shadow_fbo2d);CHECKGLERROR
1848                         qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fbo2d);CHECKGLERROR
1849                         qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, R_GetTexture(r_shadow_shadowmap2dtexture), 0);CHECKGLERROR
1850 #endif
1851                 }
1852                 CHECKGLERROR
1853                 R_Shadow_RenderMode_Reset();
1854                 if (r_shadow_shadowmap2dtexture)
1855                 {
1856                         // render depth into the fbo, do not render color at all
1857                         qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fbo2d);CHECKGLERROR
1858                         qglDrawBuffer(GL_NONE);CHECKGLERROR
1859                         qglReadBuffer(GL_NONE);CHECKGLERROR
1860                         status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
1861                         if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
1862                         {
1863                                 Con_Printf("R_Shadow_RenderMode_ShadowMap: glCheckFramebufferStatusEXT returned %i\n", status);
1864                                 Cvar_SetValueQuick(&r_shadow_shadowmapping, 0);
1865                         }
1866                         R_SetupDepthOrShadowShader();
1867                 }
1868                 else
1869                 {
1870                         R_SetupShowDepthShader();
1871                         qglClearColor(1,1,1,1);CHECKGLERROR
1872                 }
1873                 R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapborder, nearclip, farclip, NULL);
1874                 r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2dtexture);
1875                 r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2dtexture);
1876                 r_shadow_shadowmap_parameters[0] = 0.5f * (size - r_shadow_shadowmapborder);
1877                 r_shadow_shadowmap_parameters[1] = r_shadow_shadowmapvsdct ? 2.5f*size : size;
1878                 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
1879         }
1880         else if (r_shadow_shadowmode == 2)
1881         {
1882                 // complex unrolled cube approach (more flexible)
1883                 if (r_shadow_shadowmapvsdct && !r_shadow_shadowmapvsdcttexture)
1884                         R_Shadow_MakeVSDCT();
1885                 if (!r_shadow_shadowmaprectangletexture)
1886                 {
1887 #if 1
1888                         r_shadow_shadowmaprectangletexture = R_LoadTextureShadowMapRectangle(r_shadow_texturepool, "shadowmap", maxsize*2, maxsize*3, r_shadow_shadowmapprecision, r_shadow_shadowmapsampler);
1889                         qglGenFramebuffersEXT(1, &r_shadow_fborectangle);CHECKGLERROR
1890                         qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fborectangle);CHECKGLERROR
1891                         qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_RECTANGLE_ARB, R_GetTexture(r_shadow_shadowmaprectangletexture), 0);CHECKGLERROR
1892 #endif
1893                 }
1894                 CHECKGLERROR
1895                 R_Shadow_RenderMode_Reset();
1896                 if (r_shadow_shadowmaprectangletexture)
1897                 {
1898                         // render depth into the fbo, do not render color at all
1899                         qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fborectangle);CHECKGLERROR
1900                         qglDrawBuffer(GL_NONE);CHECKGLERROR
1901                         qglReadBuffer(GL_NONE);CHECKGLERROR
1902                         status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
1903                         if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
1904                         {
1905                                 Con_Printf("R_Shadow_RenderMode_ShadowMap: glCheckFramebufferStatusEXT returned %i\n", status);
1906                                 Cvar_SetValueQuick(&r_shadow_shadowmapping, 0);
1907                         }
1908                         R_SetupDepthOrShadowShader();
1909                 }
1910                 else
1911                 {
1912                         R_SetupShowDepthShader();
1913                         qglClearColor(1,1,1,1);CHECKGLERROR
1914                 }
1915                 R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapborder, nearclip, farclip, NULL);
1916                 r_shadow_shadowmap_texturescale[0] = 1.0f;
1917                 r_shadow_shadowmap_texturescale[1] = 1.0f;
1918                 r_shadow_shadowmap_parameters[0] = 0.5f * (size - r_shadow_shadowmapborder);
1919                 r_shadow_shadowmap_parameters[1] = r_shadow_shadowmapvsdct ? 2.5f*size : size;
1920                 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAPRECTANGLE;
1921         }
1922         else if (r_shadow_shadowmode == 3)
1923         {
1924                 // simple cube approach
1925                 if (!r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod])
1926                 {
1927  #if 1
1928                         r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod] = R_LoadTextureShadowMapCube(r_shadow_texturepool, "shadowmapcube", size, r_shadow_shadowmapprecision, r_shadow_shadowmapsampler);
1929                         qglGenFramebuffersEXT(6, r_shadow_fbocubeside[r_shadow_shadowmaplod]);CHECKGLERROR
1930                         for (i = 0;i < 6;i++)
1931                         {
1932                                 qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fbocubeside[r_shadow_shadowmaplod][i]);CHECKGLERROR
1933                                 qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB + i, R_GetTexture(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]), 0);CHECKGLERROR
1934                         }
1935  #endif
1936                 }
1937                 CHECKGLERROR
1938                 R_Shadow_RenderMode_Reset();
1939                 if (r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod])
1940                 {
1941                         // render depth into the fbo, do not render color at all
1942                         qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fbocubeside[r_shadow_shadowmaplod][side]);CHECKGLERROR
1943                         qglDrawBuffer(GL_NONE);CHECKGLERROR
1944                         qglReadBuffer(GL_NONE);CHECKGLERROR
1945                         status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
1946                         if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
1947                         {
1948                                 Con_Printf("R_Shadow_RenderMode_ShadowMap: glCheckFramebufferStatusEXT returned %i\n", status);
1949                                 Cvar_SetValueQuick(&r_shadow_shadowmapping, 0);
1950                         }
1951                         R_SetupDepthOrShadowShader();
1952                 }
1953                 else
1954                 {
1955                         R_SetupShowDepthShader();
1956                         qglClearColor(1,1,1,1);CHECKGLERROR
1957                 }
1958                 R_Viewport_InitCubeSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, nearclip, farclip, NULL);
1959                 r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
1960                 r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureWidth(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
1961                 r_shadow_shadowmap_parameters[0] = 1.0f;
1962                 r_shadow_shadowmap_parameters[1] = 1.0f;
1963                 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAPCUBESIDE;
1964         }
1965         CHECKGLERROR
1966         R_SetViewport(&viewport);
1967         GL_PolygonOffset(0, 0);
1968         if(r_shadow_shadowmode >= 1 && r_shadow_shadowmode <= 2)
1969         {
1970                 static qboolean cullfront[6] = { false, true, false, true, true, false };
1971                 if(cullfront[side]) r_refdef.view.cullface_back = r_refdef.view.cullface_front;
1972         }
1973         GL_CullFace(r_refdef.view.cullface_back);
1974         GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
1975         GL_DepthMask(true);
1976         GL_DepthTest(true);
1977         qglClearDepth(1);CHECKGLERROR
1978         CHECKGLERROR
1979         if (clear)
1980                 qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT |  GL_STENCIL_BUFFER_BIT);
1981         CHECKGLERROR
1982 }
1983
1984 void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qboolean shadowmapping)
1985 {
1986         CHECKGLERROR
1987         R_Shadow_RenderMode_Reset();
1988         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
1989         if (!transparent)
1990         {
1991                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
1992         }
1993         if (stenciltest)
1994         {
1995                 qglEnable(GL_STENCIL_TEST);CHECKGLERROR
1996                 // only draw light where this geometry was already rendered AND the
1997                 // stencil is 128 (values other than this mean shadow)
1998                 qglStencilFunc(GL_EQUAL, 128, ~0);CHECKGLERROR
1999         }
2000         r_shadow_rendermode = r_shadow_lightingrendermode;
2001         // do global setup needed for the chosen lighting mode
2002         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
2003         {
2004                 R_Mesh_TexBindCubeMap(GL20TU_CUBE, R_GetTexture(rsurface.rtlight->currentcubemap)); // light filter
2005                 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0);
2006                 CHECKGLERROR
2007                 if (shadowmapping)
2008                 {
2009                         if (r_shadow_shadowmode == 1)
2010                         {
2011                                 r_shadow_usingshadowmap2d = true;
2012                                 R_Mesh_TexBind(GL20TU_SHADOWMAP2D, R_GetTexture(r_shadow_shadowmap2dtexture));
2013                                 CHECKGLERROR
2014                         }
2015                         else if (r_shadow_shadowmode == 2)
2016                         {
2017                                 r_shadow_usingshadowmaprect = true;
2018                                 R_Mesh_TexBindRectangle(GL20TU_SHADOWMAPRECT, R_GetTexture(r_shadow_shadowmaprectangletexture));
2019                                 CHECKGLERROR
2020                         }
2021                         else if (r_shadow_shadowmode == 3)
2022                         {
2023                                 r_shadow_usingshadowmapcube = true;
2024                                 R_Mesh_TexBindCubeMap(GL20TU_SHADOWMAPCUBE, R_GetTexture(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]));
2025                                 CHECKGLERROR
2026                         }
2027
2028                         if (r_shadow_shadowmapvsdct && (r_shadow_usingshadowmap2d || r_shadow_usingshadowmaprect))
2029                         {
2030                                 R_Mesh_TexBindCubeMap(GL20TU_CUBEPROJECTION, R_GetTexture(r_shadow_shadowmapvsdcttexture));
2031                                 CHECKGLERROR
2032                         }
2033                 }
2034         }
2035         else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_VERTEX)
2036                 R_Mesh_ColorPointer(rsurface.array_color4f, 0, 0);
2037         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2038         CHECKGLERROR
2039 }
2040
2041 void R_Shadow_RenderMode_VisibleShadowVolumes(void)
2042 {
2043         CHECKGLERROR
2044         R_Shadow_RenderMode_Reset();
2045         GL_BlendFunc(GL_ONE, GL_ONE);
2046         GL_DepthRange(0, 1);
2047         GL_DepthTest(r_showshadowvolumes.integer < 2);
2048         GL_Color(0.0, 0.0125 * r_refdef.view.colorscale, 0.1 * r_refdef.view.colorscale, 1);
2049         GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
2050         GL_CullFace(GL_NONE);
2051         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLEVOLUMES;
2052 }
2053
2054 void R_Shadow_RenderMode_VisibleLighting(qboolean stenciltest, qboolean transparent)
2055 {
2056         CHECKGLERROR
2057         R_Shadow_RenderMode_Reset();
2058         GL_BlendFunc(GL_ONE, GL_ONE);
2059         GL_DepthRange(0, 1);
2060         GL_DepthTest(r_showlighting.integer < 2);
2061         GL_Color(0.1 * r_refdef.view.colorscale, 0.0125 * r_refdef.view.colorscale, 0, 1);
2062         if (!transparent)
2063         {
2064                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
2065         }
2066         if (stenciltest)
2067         {
2068                 qglEnable(GL_STENCIL_TEST);CHECKGLERROR
2069                 qglStencilFunc(GL_EQUAL, 128, ~0);CHECKGLERROR
2070         }
2071         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLELIGHTING;
2072 }
2073
2074 void R_Shadow_RenderMode_End(void)
2075 {
2076         CHECKGLERROR
2077         R_Shadow_RenderMode_Reset();
2078         R_Shadow_RenderMode_ActiveLight(NULL);
2079         GL_DepthMask(true);
2080         GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
2081         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
2082 }
2083
2084 int bboxedges[12][2] =
2085 {
2086         // top
2087         {0, 1}, // +X
2088         {0, 2}, // +Y
2089         {1, 3}, // Y, +X
2090         {2, 3}, // X, +Y
2091         // bottom
2092         {4, 5}, // +X
2093         {4, 6}, // +Y
2094         {5, 7}, // Y, +X
2095         {6, 7}, // X, +Y
2096         // verticals
2097         {0, 4}, // +Z
2098         {1, 5}, // X, +Z
2099         {2, 6}, // Y, +Z
2100         {3, 7}, // XY, +Z
2101 };
2102
2103 qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
2104 {
2105         int i, ix1, iy1, ix2, iy2;
2106         float x1, y1, x2, y2;
2107         vec4_t v, v2;
2108         float vertex[20][3];
2109         int j, k;
2110         vec4_t plane4f;
2111         int numvertices;
2112         float corner[8][4];
2113         float dist[8];
2114         int sign[8];
2115         float f;
2116
2117         r_shadow_lightscissor[0] = r_refdef.view.viewport.x;
2118         r_shadow_lightscissor[1] = r_refdef.view.viewport.y;
2119         r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
2120         r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
2121
2122         if (!r_shadow_scissor.integer)
2123                 return false;
2124
2125         // if view is inside the light box, just say yes it's visible
2126         if (BoxesOverlap(r_refdef.view.origin, r_refdef.view.origin, mins, maxs))
2127                 return false;
2128
2129         x1 = y1 = x2 = y2 = 0;
2130
2131         // transform all corners that are infront of the nearclip plane
2132         VectorNegate(r_refdef.view.frustum[4].normal, plane4f);
2133         plane4f[3] = r_refdef.view.frustum[4].dist;
2134         numvertices = 0;
2135         for (i = 0;i < 8;i++)
2136         {
2137                 Vector4Set(corner[i], (i & 1) ? maxs[0] : mins[0], (i & 2) ? maxs[1] : mins[1], (i & 4) ? maxs[2] : mins[2], 1);
2138                 dist[i] = DotProduct4(corner[i], plane4f);
2139                 sign[i] = dist[i] > 0;
2140                 if (!sign[i])
2141                 {
2142                         VectorCopy(corner[i], vertex[numvertices]);
2143                         numvertices++;
2144                 }
2145         }
2146         // if some points are behind the nearclip, add clipped edge points to make
2147         // sure that the scissor boundary is complete
2148         if (numvertices > 0 && numvertices < 8)
2149         {
2150                 // add clipped edge points
2151                 for (i = 0;i < 12;i++)
2152                 {
2153                         j = bboxedges[i][0];
2154                         k = bboxedges[i][1];
2155                         if (sign[j] != sign[k])
2156                         {
2157                                 f = dist[j] / (dist[j] - dist[k]);
2158                                 VectorLerp(corner[j], f, corner[k], vertex[numvertices]);
2159                                 numvertices++;
2160                         }
2161                 }
2162         }
2163
2164         // if we have no points to check, the light is behind the view plane
2165         if (!numvertices)
2166                 return true;
2167
2168         // if we have some points to transform, check what screen area is covered
2169         x1 = y1 = x2 = y2 = 0;
2170         v[3] = 1.0f;
2171         //Con_Printf("%i vertices to transform...\n", numvertices);
2172         for (i = 0;i < numvertices;i++)
2173         {
2174                 VectorCopy(vertex[i], v);
2175                 R_Viewport_TransformToScreen(&r_refdef.view.viewport, v, v2);
2176                 //Con_Printf("%.3f %.3f %.3f %.3f transformed to %.3f %.3f %.3f %.3f\n", v[0], v[1], v[2], v[3], v2[0], v2[1], v2[2], v2[3]);
2177                 if (i)
2178                 {
2179                         if (x1 > v2[0]) x1 = v2[0];
2180                         if (x2 < v2[0]) x2 = v2[0];
2181                         if (y1 > v2[1]) y1 = v2[1];
2182                         if (y2 < v2[1]) y2 = v2[1];
2183                 }
2184                 else
2185                 {
2186                         x1 = x2 = v2[0];
2187                         y1 = y2 = v2[1];
2188                 }
2189         }
2190
2191         // now convert the scissor rectangle to integer screen coordinates
2192         ix1 = (int)(x1 - 1.0f);
2193         iy1 = vid.height - (int)(y2 - 1.0f);
2194         ix2 = (int)(x2 + 1.0f);
2195         iy2 = vid.height - (int)(y1 + 1.0f);
2196         //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2);
2197
2198         // clamp it to the screen
2199         if (ix1 < r_refdef.view.viewport.x) ix1 = r_refdef.view.viewport.x;
2200         if (iy1 < r_refdef.view.viewport.y) iy1 = r_refdef.view.viewport.y;
2201         if (ix2 > r_refdef.view.viewport.x + r_refdef.view.viewport.width) ix2 = r_refdef.view.viewport.x + r_refdef.view.viewport.width;
2202         if (iy2 > r_refdef.view.viewport.y + r_refdef.view.viewport.height) iy2 = r_refdef.view.viewport.y + r_refdef.view.viewport.height;
2203
2204         // if it is inside out, it's not visible
2205         if (ix2 <= ix1 || iy2 <= iy1)
2206                 return true;
2207
2208         // the light area is visible, set up the scissor rectangle
2209         r_shadow_lightscissor[0] = ix1;
2210         r_shadow_lightscissor[1] = iy1;
2211         r_shadow_lightscissor[2] = ix2 - ix1;
2212         r_shadow_lightscissor[3] = iy2 - iy1;
2213
2214         r_refdef.stats.lights_scissored++;
2215         return false;
2216 }
2217
2218 static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int numverts, int numtriangles, const int *element3i, const float *diffusecolor, const float *ambientcolor)
2219 {
2220         float *vertex3f = rsurface.vertex3f + 3 * firstvertex;
2221         float *normal3f = rsurface.normal3f + 3 * firstvertex;
2222         float *color4f = rsurface.array_color4f + 4 * firstvertex;
2223         float dist, dot, distintensity, shadeintensity, v[3], n[3];
2224         if (r_textureunits.integer >= 3)
2225         {
2226                 if (VectorLength2(diffusecolor) > 0)
2227                 {
2228                         for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
2229                         {
2230                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
2231                                 Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
2232                                 if ((dot = DotProduct(n, v)) < 0)
2233                                 {
2234                                         shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
2235                                         VectorMA(ambientcolor, shadeintensity, diffusecolor, color4f);
2236                                 }
2237                                 else
2238                                         VectorCopy(ambientcolor, color4f);
2239                                 if (r_refdef.fogenabled)
2240                                 {
2241                                         float f;
2242                                         f = FogPoint_Model(vertex3f);
2243                                         VectorScale(color4f, f, color4f);
2244                                 }
2245                                 color4f[3] = 1;
2246                         }
2247                 }
2248                 else
2249                 {
2250                         for (;numverts > 0;numverts--, vertex3f += 3, color4f += 4)
2251                         {
2252                                 VectorCopy(ambientcolor, color4f);
2253                                 if (r_refdef.fogenabled)
2254                                 {
2255                                         float f;
2256                                         Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
2257                                         f = FogPoint_Model(vertex3f);
2258                                         VectorScale(color4f, f, color4f);
2259                                 }
2260                                 color4f[3] = 1;
2261                         }
2262                 }
2263         }
2264         else if (r_textureunits.integer >= 2)
2265         {
2266                 if (VectorLength2(diffusecolor) > 0)
2267                 {
2268                         for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
2269                         {
2270                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
2271                                 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
2272                                 {
2273                                         Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
2274                                         if ((dot = DotProduct(n, v)) < 0)
2275                                         {
2276                                                 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
2277                                                 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
2278                                                 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
2279                                                 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
2280                                         }
2281                                         else
2282                                         {
2283                                                 color4f[0] = ambientcolor[0] * distintensity;
2284                                                 color4f[1] = ambientcolor[1] * distintensity;
2285                                                 color4f[2] = ambientcolor[2] * distintensity;
2286                                         }
2287                                         if (r_refdef.fogenabled)
2288                                         {
2289                                                 float f;
2290                                                 f = FogPoint_Model(vertex3f);
2291                                                 VectorScale(color4f, f, color4f);
2292                                         }
2293                                 }
2294                                 else
2295                                         VectorClear(color4f);
2296                                 color4f[3] = 1;
2297                         }
2298                 }
2299                 else
2300                 {
2301                         for (;numverts > 0;numverts--, vertex3f += 3, color4f += 4)
2302                         {
2303                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
2304                                 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
2305                                 {
2306                                         color4f[0] = ambientcolor[0] * distintensity;
2307                                         color4f[1] = ambientcolor[1] * distintensity;
2308                                         color4f[2] = ambientcolor[2] * distintensity;
2309                                         if (r_refdef.fogenabled)
2310                                         {
2311                                                 float f;
2312                                                 f = FogPoint_Model(vertex3f);
2313                                                 VectorScale(color4f, f, color4f);
2314                                         }
2315                                 }
2316                                 else
2317                                         VectorClear(color4f);
2318                                 color4f[3] = 1;
2319                         }
2320                 }
2321         }
2322         else
2323         {
2324                 if (VectorLength2(diffusecolor) > 0)
2325                 {
2326                         for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
2327                         {
2328                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
2329                                 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
2330                                 {
2331                                         distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
2332                                         Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
2333                                         if ((dot = DotProduct(n, v)) < 0)
2334                                         {
2335                                                 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
2336                                                 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
2337                                                 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
2338                                                 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
2339                                         }
2340                                         else
2341                                         {
2342                                                 color4f[0] = ambientcolor[0] * distintensity;
2343                                                 color4f[1] = ambientcolor[1] * distintensity;
2344                                                 color4f[2] = ambientcolor[2] * distintensity;
2345                                         }
2346                                         if (r_refdef.fogenabled)
2347                                         {
2348                                                 float f;
2349                                                 f = FogPoint_Model(vertex3f);
2350                                                 VectorScale(color4f, f, color4f);
2351                                         }
2352                                 }
2353                                 else
2354                                         VectorClear(color4f);
2355                                 color4f[3] = 1;
2356                         }
2357                 }
2358                 else
2359                 {
2360                         for (;numverts > 0;numverts--, vertex3f += 3, color4f += 4)
2361                         {
2362                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
2363                                 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
2364                                 {
2365                                         distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
2366                                         color4f[0] = ambientcolor[0] * distintensity;
2367                                         color4f[1] = ambientcolor[1] * distintensity;
2368                                         color4f[2] = ambientcolor[2] * distintensity;
2369                                         if (r_refdef.fogenabled)
2370                                         {
2371                                                 float f;
2372                                                 f = FogPoint_Model(vertex3f);
2373                                                 VectorScale(color4f, f, color4f);
2374                                         }
2375                                 }
2376                                 else
2377                                         VectorClear(color4f);
2378                                 color4f[3] = 1;
2379                         }
2380                 }
2381         }
2382 }
2383
2384 // TODO: use glTexGen instead of feeding vertices to texcoordpointer?
2385
2386 static void R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(int firstvertex, int numvertices, int numtriangles, const int *element3i)
2387 {
2388         int i;
2389         float       *out3f     = rsurface.array_texcoord3f + 3 * firstvertex;
2390         const float *vertex3f  = rsurface.vertex3f         + 3 * firstvertex;
2391         const float *svector3f = rsurface.svector3f        + 3 * firstvertex;
2392         const float *tvector3f = rsurface.tvector3f        + 3 * firstvertex;
2393         const float *normal3f  = rsurface.normal3f         + 3 * firstvertex;
2394         float lightdir[3];
2395         for (i = 0;i < numvertices;i++, vertex3f += 3, svector3f += 3, tvector3f += 3, normal3f += 3, out3f += 3)
2396         {
2397                 VectorSubtract(rsurface.entitylightorigin, vertex3f, lightdir);
2398                 // the cubemap normalizes this for us
2399                 out3f[0] = DotProduct(svector3f, lightdir);
2400                 out3f[1] = DotProduct(tvector3f, lightdir);
2401                 out3f[2] = DotProduct(normal3f, lightdir);
2402         }
2403 }
2404
2405 static void R_Shadow_GenTexCoords_Specular_NormalCubeMap(int firstvertex, int numvertices, int numtriangles, const int *element3i)
2406 {
2407         int i;
2408         float       *out3f     = rsurface.array_texcoord3f + 3 * firstvertex;
2409         const float *vertex3f  = rsurface.vertex3f         + 3 * firstvertex;
2410         const float *svector3f = rsurface.svector3f        + 3 * firstvertex;
2411         const float *tvector3f = rsurface.tvector3f        + 3 * firstvertex;
2412         const float *normal3f  = rsurface.normal3f         + 3 * firstvertex;
2413         float lightdir[3], eyedir[3], halfdir[3];
2414         for (i = 0;i < numvertices;i++, vertex3f += 3, svector3f += 3, tvector3f += 3, normal3f += 3, out3f += 3)
2415         {
2416                 VectorSubtract(rsurface.entitylightorigin, vertex3f, lightdir);
2417                 VectorNormalize(lightdir);
2418                 VectorSubtract(rsurface.modelorg, vertex3f, eyedir);
2419                 VectorNormalize(eyedir);
2420                 VectorAdd(lightdir, eyedir, halfdir);
2421                 // the cubemap normalizes this for us
2422                 out3f[0] = DotProduct(svector3f, halfdir);
2423                 out3f[1] = DotProduct(tvector3f, halfdir);
2424                 out3f[2] = DotProduct(normal3f, halfdir);
2425         }
2426 }
2427
2428 static void R_Shadow_RenderLighting_VisibleLighting(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float ambientscale, float diffusescale, float specularscale, qboolean dopants, qboolean doshirt)
2429 {
2430         // used to display how many times a surface is lit for level design purposes
2431         R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2432 }
2433
2434 static void R_Shadow_RenderLighting_Light_GLSL(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float ambientscale, float diffusescale, float specularscale, qboolean dopants, qboolean doshirt)
2435 {
2436         // ARB2 GLSL shader path (GFFX5200, Radeon 9500)
2437         R_SetupSurfaceShader(lightcolorbase, false, ambientscale, diffusescale, specularscale, RSURFPASS_RTLIGHT);
2438         if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND))
2439                 R_Mesh_ColorPointer(rsurface.modellightmapcolor4f, rsurface.modellightmapcolor4f_bufferobject, rsurface.modellightmapcolor4f_bufferoffset);
2440         else
2441                 R_Mesh_ColorPointer(NULL, 0, 0);
2442         R_Mesh_TexMatrix(0, &rsurface.texture->currenttexmatrix);
2443         R_Mesh_TexMatrix(1, &rsurface.texture->currentbackgroundtexmatrix);
2444         R_Mesh_TexBind(GL20TU_NORMAL, R_GetTexture(rsurface.texture->currentskinframe->nmap));
2445         R_Mesh_TexBind(GL20TU_COLOR, R_GetTexture(rsurface.texture->basetexture));
2446         R_Mesh_TexBind(GL20TU_GLOSS, R_GetTexture(rsurface.texture->glosstexture));
2447         if (rsurface.texture->backgroundcurrentskinframe)
2448         {
2449                 R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL, R_GetTexture(rsurface.texture->backgroundcurrentskinframe->nmap));
2450                 R_Mesh_TexBind(GL20TU_SECONDARY_COLOR, R_GetTexture(rsurface.texture->backgroundbasetexture));
2451                 R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS, R_GetTexture(rsurface.texture->backgroundglosstexture));
2452                 R_Mesh_TexBind(GL20TU_SECONDARY_GLOW, R_GetTexture(rsurface.texture->backgroundcurrentskinframe->glow));
2453         }
2454         //R_Mesh_TexBindCubeMap(GL20TU_CUBE, R_GetTexture(rsurface.rtlight->currentcubemap));
2455         R_Mesh_TexBind(GL20TU_FOGMASK, R_GetTexture(r_texture_fogattenuation));
2456         if(rsurface.texture->colormapping)
2457         {
2458                 R_Mesh_TexBind(GL20TU_PANTS, R_GetTexture(rsurface.texture->currentskinframe->pants));
2459                 R_Mesh_TexBind(GL20TU_SHIRT, R_GetTexture(rsurface.texture->currentskinframe->shirt));
2460         }
2461         R_Mesh_TexBind(GL20TU_ATTENUATION, R_GetTexture(r_shadow_attenuationgradienttexture));
2462         R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
2463         R_Mesh_TexCoordPointer(1, 3, rsurface.svector3f, rsurface.svector3f_bufferobject, rsurface.svector3f_bufferoffset);
2464         R_Mesh_TexCoordPointer(2, 3, rsurface.tvector3f, rsurface.tvector3f_bufferobject, rsurface.tvector3f_bufferoffset);
2465         R_Mesh_TexCoordPointer(3, 3, rsurface.normal3f, rsurface.normal3f_bufferobject, rsurface.normal3f_bufferoffset);
2466         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
2467         {
2468                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
2469         }
2470         R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2471         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
2472         {
2473                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
2474         }
2475 }
2476
2477 static void R_Shadow_RenderLighting_Light_Dot3_Finalize(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, float r, float g, float b)
2478 {
2479         // shared final code for all the dot3 layers
2480         int renders;
2481         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0);
2482         for (renders = 0;renders < 64 && (r > 0 || g > 0 || b > 0);renders++, r--, g--, b--)
2483         {
2484                 GL_Color(bound(0, r, 1), bound(0, g, 1), bound(0, b, 1), 1);
2485                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2486         }
2487 }
2488
2489 static void R_Shadow_RenderLighting_Light_Dot3_AmbientPass(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, rtexture_t *basetexture, float colorscale)
2490 {
2491         rmeshstate_t m;
2492         // colorscale accounts for how much we multiply the brightness
2493         // during combine.
2494         //
2495         // mult is how many times the final pass of the lighting will be
2496         // performed to get more brightness than otherwise possible.
2497         //
2498         // Limit mult to 64 for sanity sake.
2499         GL_Color(1,1,1,1);
2500         if (r_shadow_texture3d.integer && rsurface.rtlight->currentcubemap != r_texture_whitecube && r_textureunits.integer >= 4)
2501         {
2502                 // 3 3D combine path (Geforce3, Radeon 8500)
2503                 memset(&m, 0, sizeof(m));
2504                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
2505                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2506                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2507                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2508                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2509                 m.tex[1] = R_GetTexture(basetexture);
2510                 m.pointer_texcoord[1] = rsurface.texcoordtexture2f;
2511                 m.pointer_texcoord_bufferobject[1] = rsurface.texcoordtexture2f_bufferobject;
2512                 m.pointer_texcoord_bufferoffset[1] = rsurface.texcoordtexture2f_bufferoffset;
2513                 m.texmatrix[1] = rsurface.texture->currenttexmatrix;
2514                 m.texcubemap[2] = R_GetTexture(rsurface.rtlight->currentcubemap);
2515                 m.pointer_texcoord3f[2] = rsurface.vertex3f;
2516                 m.pointer_texcoord_bufferobject[2] = rsurface.vertex3f_bufferobject;
2517                 m.pointer_texcoord_bufferoffset[2] = rsurface.vertex3f_bufferoffset;
2518                 m.texmatrix[2] = rsurface.entitytolight;
2519                 GL_BlendFunc(GL_ONE, GL_ONE);
2520         }
2521         else if (r_shadow_texture3d.integer && rsurface.rtlight->currentcubemap == r_texture_whitecube && r_textureunits.integer >= 2)
2522         {
2523                 // 2 3D combine path (Geforce3, original Radeon)
2524                 memset(&m, 0, sizeof(m));
2525                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
2526                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2527                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2528                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2529                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2530                 m.tex[1] = R_GetTexture(basetexture);
2531                 m.pointer_texcoord[1] = rsurface.texcoordtexture2f;
2532                 m.pointer_texcoord_bufferobject[1] = rsurface.texcoordtexture2f_bufferobject;
2533                 m.pointer_texcoord_bufferoffset[1] = rsurface.texcoordtexture2f_bufferoffset;
2534                 m.texmatrix[1] = rsurface.texture->currenttexmatrix;
2535                 GL_BlendFunc(GL_ONE, GL_ONE);
2536         }
2537         else if (r_textureunits.integer >= 4 && rsurface.rtlight->currentcubemap != r_texture_whitecube)
2538         {
2539                 // 4 2D combine path (Geforce3, Radeon 8500)
2540                 memset(&m, 0, sizeof(m));
2541                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
2542                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2543                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2544                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2545                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2546                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
2547                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2548                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2549                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2550                 m.texmatrix[1] = rsurface.entitytoattenuationz;
2551                 m.tex[2] = R_GetTexture(basetexture);
2552                 m.pointer_texcoord[2] = rsurface.texcoordtexture2f;
2553                 m.pointer_texcoord_bufferobject[2] = rsurface.texcoordtexture2f_bufferobject;
2554                 m.pointer_texcoord_bufferoffset[2] = rsurface.texcoordtexture2f_bufferoffset;
2555                 m.texmatrix[2] = rsurface.texture->currenttexmatrix;
2556                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2557                 {
2558                         m.texcubemap[3] = R_GetTexture(rsurface.rtlight->currentcubemap);
2559                         m.pointer_texcoord3f[3] = rsurface.vertex3f;
2560                         m.pointer_texcoord_bufferobject[3] = rsurface.vertex3f_bufferobject;
2561                         m.pointer_texcoord_bufferoffset[3] = rsurface.vertex3f_bufferoffset;
2562                         m.texmatrix[3] = rsurface.entitytolight;
2563                 }
2564                 GL_BlendFunc(GL_ONE, GL_ONE);
2565         }
2566         else if (r_textureunits.integer >= 3 && rsurface.rtlight->currentcubemap == r_texture_whitecube)
2567         {
2568                 // 3 2D combine path (Geforce3, original Radeon)
2569                 memset(&m, 0, sizeof(m));
2570                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
2571                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2572                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2573                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2574                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2575                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
2576                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2577                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2578                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2579                 m.texmatrix[1] = rsurface.entitytoattenuationz;
2580                 m.tex[2] = R_GetTexture(basetexture);
2581                 m.pointer_texcoord[2] = rsurface.texcoordtexture2f;
2582                 m.pointer_texcoord_bufferobject[2] = rsurface.texcoordtexture2f_bufferobject;
2583                 m.pointer_texcoord_bufferoffset[2] = rsurface.texcoordtexture2f_bufferoffset;
2584                 m.texmatrix[2] = rsurface.texture->currenttexmatrix;
2585                 GL_BlendFunc(GL_ONE, GL_ONE);
2586         }
2587         else
2588         {
2589                 // 2/2/2 2D combine path (any dot3 card)
2590                 memset(&m, 0, sizeof(m));
2591                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
2592                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2593                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2594                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2595                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2596                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
2597                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2598                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2599                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2600                 m.texmatrix[1] = rsurface.entitytoattenuationz;
2601                 R_Mesh_TextureState(&m);
2602                 GL_ColorMask(0,0,0,1);
2603                 GL_BlendFunc(GL_ONE, GL_ZERO);
2604                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2605
2606                 // second pass
2607                 memset(&m, 0, sizeof(m));
2608                 m.tex[0] = R_GetTexture(basetexture);
2609                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2610                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2611                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2612                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2613                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2614                 {
2615                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2616                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2617                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2618                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2619                         m.texmatrix[1] = rsurface.entitytolight;
2620                 }
2621                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2622         }
2623         // this final code is shared
2624         R_Mesh_TextureState(&m);
2625         R_Shadow_RenderLighting_Light_Dot3_Finalize(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase[0] * colorscale, lightcolorbase[1] * colorscale, lightcolorbase[2] * colorscale);
2626 }
2627
2628 static void R_Shadow_RenderLighting_Light_Dot3_DiffusePass(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, rtexture_t *basetexture, rtexture_t *normalmaptexture, float colorscale)
2629 {
2630         rmeshstate_t m;
2631         // colorscale accounts for how much we multiply the brightness
2632         // during combine.
2633         //
2634         // mult is how many times the final pass of the lighting will be
2635         // performed to get more brightness than otherwise possible.
2636         //
2637         // Limit mult to 64 for sanity sake.
2638         GL_Color(1,1,1,1);
2639         // generate normalization cubemap texcoords
2640         R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(firstvertex, numvertices, numtriangles, element3i);
2641         if (r_shadow_texture3d.integer && r_textureunits.integer >= 4)
2642         {
2643                 // 3/2 3D combine path (Geforce3, Radeon 8500)
2644                 memset(&m, 0, sizeof(m));
2645                 m.tex[0] = R_GetTexture(normalmaptexture);
2646                 m.texcombinergb[0] = GL_REPLACE;
2647                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2648                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2649                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2650                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2651                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2652                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2653                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2654                 m.pointer_texcoord_bufferobject[1] = 0;
2655                 m.pointer_texcoord_bufferoffset[1] = 0;
2656                 m.tex3d[2] = R_GetTexture(r_shadow_attenuation3dtexture);
2657                 m.pointer_texcoord3f[2] = rsurface.vertex3f;
2658                 m.pointer_texcoord_bufferobject[2] = rsurface.vertex3f_bufferobject;
2659                 m.pointer_texcoord_bufferoffset[2] = rsurface.vertex3f_bufferoffset;
2660                 m.texmatrix[2] = rsurface.entitytoattenuationxyz;
2661                 R_Mesh_TextureState(&m);
2662                 GL_ColorMask(0,0,0,1);
2663                 GL_BlendFunc(GL_ONE, GL_ZERO);
2664                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2665
2666                 // second pass
2667                 memset(&m, 0, sizeof(m));
2668                 m.tex[0] = R_GetTexture(basetexture);
2669                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2670                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2671                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2672                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2673                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2674                 {
2675                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2676                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2677                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2678                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2679                         m.texmatrix[1] = rsurface.entitytolight;
2680                 }
2681                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2682         }
2683         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && rsurface.rtlight->currentcubemap != r_texture_whitecube)
2684         {
2685                 // 1/2/2 3D combine path (original Radeon)
2686                 memset(&m, 0, sizeof(m));
2687                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
2688                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2689                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2690                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2691                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2692                 R_Mesh_TextureState(&m);
2693                 GL_ColorMask(0,0,0,1);
2694                 GL_BlendFunc(GL_ONE, GL_ZERO);
2695                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2696
2697                 // second pass
2698                 memset(&m, 0, sizeof(m));
2699                 m.tex[0] = R_GetTexture(normalmaptexture);
2700                 m.texcombinergb[0] = GL_REPLACE;
2701                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2702                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2703                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2704                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2705                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2706                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2707                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2708                 m.pointer_texcoord_bufferobject[1] = 0;
2709                 m.pointer_texcoord_bufferoffset[1] = 0;
2710                 R_Mesh_TextureState(&m);
2711                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
2712                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2713
2714                 // second pass
2715                 memset(&m, 0, sizeof(m));
2716                 m.tex[0] = R_GetTexture(basetexture);
2717                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2718                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2719                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2720                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2721                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2722                 {
2723                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2724                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2725                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2726                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2727                         m.texmatrix[1] = rsurface.entitytolight;
2728                 }
2729                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2730         }
2731         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && rsurface.rtlight->currentcubemap == r_texture_whitecube)
2732         {
2733                 // 2/2 3D combine path (original Radeon)
2734                 memset(&m, 0, sizeof(m));
2735                 m.tex[0] = R_GetTexture(normalmaptexture);
2736                 m.texcombinergb[0] = GL_REPLACE;
2737                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2738                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2739                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2740                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2741                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2742                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2743                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2744                 m.pointer_texcoord_bufferobject[1] = 0;
2745                 m.pointer_texcoord_bufferoffset[1] = 0;
2746                 R_Mesh_TextureState(&m);
2747                 GL_ColorMask(0,0,0,1);
2748                 GL_BlendFunc(GL_ONE, GL_ZERO);
2749                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2750
2751                 // second pass
2752                 memset(&m, 0, sizeof(m));
2753                 m.tex[0] = R_GetTexture(basetexture);
2754                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2755                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2756                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2757                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2758                 m.tex3d[1] = R_GetTexture(r_shadow_attenuation3dtexture);
2759                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2760                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2761                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2762                 m.texmatrix[1] = rsurface.entitytoattenuationxyz;
2763                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2764         }
2765         else if (r_textureunits.integer >= 4)
2766         {
2767                 // 4/2 2D combine path (Geforce3, Radeon 8500)
2768                 memset(&m, 0, sizeof(m));
2769                 m.tex[0] = R_GetTexture(normalmaptexture);
2770                 m.texcombinergb[0] = GL_REPLACE;
2771                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2772                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2773                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2774                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2775                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2776                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2777                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2778                 m.pointer_texcoord_bufferobject[1] = 0;
2779                 m.pointer_texcoord_bufferoffset[1] = 0;
2780                 m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture);
2781                 m.pointer_texcoord3f[2] = rsurface.vertex3f;
2782                 m.pointer_texcoord_bufferobject[2] = rsurface.vertex3f_bufferobject;
2783                 m.pointer_texcoord_bufferoffset[2] = rsurface.vertex3f_bufferoffset;
2784                 m.texmatrix[2] = rsurface.entitytoattenuationxyz;
2785                 m.tex[3] = R_GetTexture(r_shadow_attenuation2dtexture);
2786                 m.pointer_texcoord3f[3] = rsurface.vertex3f;
2787                 m.pointer_texcoord_bufferobject[3] = rsurface.vertex3f_bufferobject;
2788                 m.pointer_texcoord_bufferoffset[3] = rsurface.vertex3f_bufferoffset;
2789                 m.texmatrix[3] = rsurface.entitytoattenuationz;
2790                 R_Mesh_TextureState(&m);
2791                 GL_ColorMask(0,0,0,1);
2792                 GL_BlendFunc(GL_ONE, GL_ZERO);
2793                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2794
2795                 // second pass
2796                 memset(&m, 0, sizeof(m));
2797                 m.tex[0] = R_GetTexture(basetexture);
2798                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2799                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2800                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2801                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2802                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2803                 {
2804                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2805                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2806                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2807                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2808                         m.texmatrix[1] = rsurface.entitytolight;
2809                 }
2810                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2811         }
2812         else
2813         {
2814                 // 2/2/2 2D combine path (any dot3 card)
2815                 memset(&m, 0, sizeof(m));
2816                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
2817                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2818                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2819                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2820                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2821                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
2822                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2823                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2824                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2825                 m.texmatrix[1] = rsurface.entitytoattenuationz;
2826                 R_Mesh_TextureState(&m);
2827                 GL_ColorMask(0,0,0,1);
2828                 GL_BlendFunc(GL_ONE, GL_ZERO);
2829                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2830
2831                 // second pass
2832                 memset(&m, 0, sizeof(m));
2833                 m.tex[0] = R_GetTexture(normalmaptexture);
2834                 m.texcombinergb[0] = GL_REPLACE;
2835                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2836                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2837                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2838                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2839                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2840                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2841                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2842                 m.pointer_texcoord_bufferobject[1] = 0;
2843                 m.pointer_texcoord_bufferoffset[1] = 0;
2844                 R_Mesh_TextureState(&m);
2845                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
2846                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2847
2848                 // second pass
2849                 memset(&m, 0, sizeof(m));
2850                 m.tex[0] = R_GetTexture(basetexture);
2851                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2852                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2853                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2854                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2855                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2856                 {
2857                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2858                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2859                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2860                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2861                         m.texmatrix[1] = rsurface.entitytolight;
2862                 }
2863                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2864         }
2865         // this final code is shared
2866         R_Mesh_TextureState(&m);
2867         R_Shadow_RenderLighting_Light_Dot3_Finalize(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase[0] * colorscale, lightcolorbase[1] * colorscale, lightcolorbase[2] * colorscale);
2868 }
2869
2870 static void R_Shadow_RenderLighting_Light_Dot3_SpecularPass(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, rtexture_t *glosstexture, rtexture_t *normalmaptexture, float colorscale)
2871 {
2872         float glossexponent;
2873         rmeshstate_t m;
2874         // FIXME: detect blendsquare!
2875         //if (!gl_support_blendsquare)
2876         //      return;
2877         GL_Color(1,1,1,1);
2878         // generate normalization cubemap texcoords
2879         R_Shadow_GenTexCoords_Specular_NormalCubeMap(firstvertex, numvertices, numtriangles, element3i);
2880         if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && rsurface.rtlight->currentcubemap != r_texture_whitecube)
2881         {
2882                 // 2/0/0/1/2 3D combine blendsquare path
2883                 memset(&m, 0, sizeof(m));
2884                 m.tex[0] = R_GetTexture(normalmaptexture);
2885                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2886                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2887                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2888                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2889                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2890                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2891                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2892                 m.pointer_texcoord_bufferobject[1] = 0;
2893                 m.pointer_texcoord_bufferoffset[1] = 0;
2894                 R_Mesh_TextureState(&m);
2895                 GL_ColorMask(0,0,0,1);
2896                 // this squares the result
2897                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
2898                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2899
2900                 // second and third pass
2901                 R_Mesh_ResetTextureState();
2902                 // square alpha in framebuffer a few times to make it shiny
2903                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
2904                 for (glossexponent = 2;glossexponent * 2 <= r_shadow_glossexponent.value;glossexponent *= 2)
2905                         R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2906
2907                 // fourth pass
2908                 memset(&m, 0, sizeof(m));
2909                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
2910                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
2911                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
2912                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
2913                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
2914                 R_Mesh_TextureState(&m);
2915                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
2916                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2917
2918                 // fifth pass
2919                 memset(&m, 0, sizeof(m));
2920                 m.tex[0] = R_GetTexture(glosstexture);
2921                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2922                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2923                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2924                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2925                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
2926                 {
2927                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
2928                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
2929                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2930                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2931                         m.texmatrix[1] = rsurface.entitytolight;
2932                 }
2933                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2934         }
2935         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && rsurface.rtlight->currentcubemap == r_texture_whitecube /* && gl_support_blendsquare*/) // FIXME: detect blendsquare!
2936         {
2937                 // 2/0/0/2 3D combine blendsquare path
2938                 memset(&m, 0, sizeof(m));
2939                 m.tex[0] = R_GetTexture(normalmaptexture);
2940                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2941                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2942                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2943                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2944                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2945                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2946                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2947                 m.pointer_texcoord_bufferobject[1] = 0;
2948                 m.pointer_texcoord_bufferoffset[1] = 0;
2949                 R_Mesh_TextureState(&m);
2950                 GL_ColorMask(0,0,0,1);
2951                 // this squares the result
2952                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
2953                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2954
2955                 // second and third pass
2956                 R_Mesh_ResetTextureState();
2957                 // square alpha in framebuffer a few times to make it shiny
2958                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
2959                 for (glossexponent = 2;glossexponent * 2 <= r_shadow_glossexponent.value;glossexponent *= 2)
2960                         R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2961
2962                 // fourth pass
2963                 memset(&m, 0, sizeof(m));
2964                 m.tex[0] = R_GetTexture(glosstexture);
2965                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2966                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2967                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2968                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2969                 m.tex3d[1] = R_GetTexture(r_shadow_attenuation3dtexture);
2970                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
2971                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
2972                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
2973                 m.texmatrix[1] = rsurface.entitytoattenuationxyz;
2974                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
2975         }
2976         else
2977         {
2978                 // 2/0/0/2/2 2D combine blendsquare path
2979                 memset(&m, 0, sizeof(m));
2980                 m.tex[0] = R_GetTexture(normalmaptexture);
2981                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
2982                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
2983                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
2984                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
2985                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
2986                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
2987                 m.pointer_texcoord3f[1] = rsurface.array_texcoord3f;
2988                 m.pointer_texcoord_bufferobject[1] = 0;
2989                 m.pointer_texcoord_bufferoffset[1] = 0;
2990                 R_Mesh_TextureState(&m);
2991                 GL_ColorMask(0,0,0,1);
2992                 // this squares the result
2993                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
2994                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
2995
2996                 // second and third pass
2997                 R_Mesh_ResetTextureState();
2998                 // square alpha in framebuffer a few times to make it shiny
2999                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
3000                 for (glossexponent = 2;glossexponent * 2 <= r_shadow_glossexponent.value;glossexponent *= 2)
3001                         R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
3002
3003                 // fourth pass
3004                 memset(&m, 0, sizeof(m));
3005                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
3006                 m.pointer_texcoord3f[0] = rsurface.vertex3f;
3007                 m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject;
3008                 m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset;
3009                 m.texmatrix[0] = rsurface.entitytoattenuationxyz;
3010                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
3011                 m.pointer_texcoord3f[1] = rsurface.vertex3f;
3012                 m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
3013                 m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
3014                 m.texmatrix[1] = rsurface.entitytoattenuationz;
3015                 R_Mesh_TextureState(&m);
3016                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
3017                 R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject);
3018
3019                 // fifth pass
3020                 memset(&m, 0, sizeof(m));
3021                 m.tex[0] = R_GetTexture(glosstexture);
3022                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
3023                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
3024                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
3025                 m.texmatrix[0] = rsurface.texture->currenttexmatrix;
3026                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
3027                 {
3028                         m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap);
3029                         m.pointer_texcoord3f[1] = rsurface.vertex3f;
3030                         m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject;
3031                         m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset;
3032                         m.texmatrix[1] = rsurface.entitytolight;
3033                 }
3034                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
3035         }
3036         // this final code is shared