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