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