]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - r_shadow.c
Attempt to make loading screens not stay cached, to avoid loading GPU memory when...
[xonotic/darkplaces.git] / r_shadow.c
1
2 /*
3 Terminology: Stencil Shadow Volume (sometimes called Stencil Shadows)
4 An extrusion of the lit faces, beginning at the original geometry and ending
5 further from the light source than the original geometry (presumably at least
6 as far as the light's radius, if the light has a radius at all), capped at
7 both front and back to avoid any problems (extrusion from dark faces also
8 works but has a different set of problems)
9
10 This is normally rendered using Carmack's Reverse technique, in which
11 backfaces behind zbuffer (zfail) increment the stencil, and frontfaces behind
12 zbuffer (zfail) decrement the stencil, the result is a stencil value of zero
13 where shadows did not intersect the visible geometry, suitable as a stencil
14 mask for rendering lighting everywhere but shadow.
15
16 In our case to hopefully avoid the Creative Labs patent, we draw the backfaces
17 as decrement and the frontfaces as increment, and we redefine the DepthFunc to
18 GL_LESS (the patent uses GL_GEQUAL) which causes zfail when behind surfaces
19 and zpass when infront (the patent draws where zpass with a GL_GEQUAL test),
20 additionally we clear stencil to 128 to avoid the need for the unclamped
21 incr/decr extension (not related to patent).
22
23 Patent warning:
24 This algorithm may be covered by Creative's patent (US Patent #6384822),
25 however that patent is quite specific about increment on backfaces and
26 decrement on frontfaces where zpass with GL_GEQUAL depth test, which is
27 opposite this implementation and partially opposite Carmack's Reverse paper
28 (which uses GL_LESS, but increments on backfaces and decrements on frontfaces).
29
30
31
32 Terminology: Stencil Light Volume (sometimes called Light Volumes)
33 Similar to a Stencil Shadow Volume, but inverted; rather than containing the
34 areas in shadow it contains the areas in light, this can only be built
35 quickly for certain limited cases (such as portal visibility from a point),
36 but is quite useful for some effects (sunlight coming from sky polygons is
37 one possible example, translucent occluders is another example).
38
39
40
41 Terminology: Optimized Stencil Shadow Volume
42 A Stencil Shadow Volume that has been processed sufficiently to ensure it has
43 no duplicate coverage of areas (no need to shadow an area twice), often this
44 greatly improves performance but is an operation too costly to use on moving
45 lights (however completely optimal Stencil Light Volumes can be constructed
46 in some ideal cases).
47
48
49
50 Terminology: Per Pixel Lighting (sometimes abbreviated PPL)
51 Per pixel evaluation of lighting equations, at a bare minimum this involves
52 DOT3 shading of diffuse lighting (per pixel dotproduct of negated incidence
53 vector and surface normal, using a texture of the surface bumps, called a
54 NormalMap) if supported by hardware; in our case there is support for cards
55 which are incapable of DOT3, the quality is quite poor however.  Additionally
56 it is desirable to have specular evaluation per pixel, per vertex
57 normalization of specular halfangle vectors causes noticable distortion but
58 is unavoidable on hardware without GL_ARB_fragment_program or
59 GL_ARB_fragment_shader.
60
61
62
63 Terminology: Normalization CubeMap
64 A cubemap containing normalized dot3-encoded (vectors of length 1 or less
65 encoded as RGB colors) for any possible direction, this technique allows per
66 pixel calculation of incidence vector for per pixel lighting purposes, which
67 would not otherwise be possible per pixel without GL_ARB_fragment_program or
68 GL_ARB_fragment_shader.
69
70
71
72 Terminology: 2D+1D Attenuation Texturing
73 A very crude approximation of light attenuation with distance which results
74 in cylindrical light shapes which fade vertically as a streak (some games
75 such as Doom3 allow this to be rotated to be less noticable in specific
76 cases), the technique is simply modulating lighting by two 2D textures (which
77 can be the same) on different axes of projection (XY and Z, typically), this
78 is the second best technique available without 3D Attenuation Texturing,
79 GL_ARB_fragment_program or GL_ARB_fragment_shader technology.
80
81
82
83 Terminology: 2D+1D Inverse Attenuation Texturing
84 A clever method described in papers on the Abducted engine, this has a squared
85 distance texture (bright on the outside, black in the middle), which is used
86 twice using GL_ADD blending, the result of this is used in an inverse modulate
87 (GL_ONE_MINUS_DST_ALPHA, GL_ZERO) to implement the equation
88 lighting*=(1-((X*X+Y*Y)+(Z*Z))) which is spherical (unlike 2D+1D attenuation
89 texturing).
90
91
92
93 Terminology: 3D Attenuation Texturing
94 A slightly crude approximation of light attenuation with distance, its flaws
95 are limited radius and resolution (performance tradeoffs).
96
97
98
99 Terminology: 3D Attenuation-Normalization Texturing
100 A 3D Attenuation Texture merged with a Normalization CubeMap, by making the
101 vectors shorter the lighting becomes darker, a very effective optimization of
102 diffuse lighting if 3D Attenuation Textures are already used.
103
104
105
106 Terminology: Light Cubemap Filtering
107 A technique for modeling non-uniform light distribution according to
108 direction, for example a lantern may use a cubemap to describe the light
109 emission pattern of the cage around the lantern (as well as soot buildup
110 discoloring the light in certain areas), often also used for softened grate
111 shadows and light shining through a stained glass window (done crudely by
112 texturing the lighting with a cubemap), another good example would be a disco
113 light.  This technique is used heavily in many games (Doom3 does not support
114 this however).
115
116
117
118 Terminology: Light Projection Filtering
119 A technique for modeling shadowing of light passing through translucent
120 surfaces, allowing stained glass windows and other effects to be done more
121 elegantly than possible with Light Cubemap Filtering by applying an occluder
122 texture to the lighting combined with a stencil light volume to limit the lit
123 area, this technique is used by Doom3 for spotlights and flashlights, among
124 other things, this can also be used more generally to render light passing
125 through multiple translucent occluders in a scene (using a light volume to
126 describe the area beyond the occluder, and thus mask off rendering of all
127 other areas).
128
129
130
131 Terminology: Doom3 Lighting
132 A combination of Stencil Shadow Volume, Per Pixel Lighting, Normalization
133 CubeMap, 2D+1D Attenuation Texturing, and Light Projection Filtering, as
134 demonstrated by the game Doom3.
135 */
136
137 #include "quakedef.h"
138 #include "r_shadow.h"
139 #include "cl_collision.h"
140 #include "portals.h"
141 #include "image.h"
142 #include "dpsoftrast.h"
143
144 #ifdef SUPPORTD3D
145 #include <d3d9.h>
146 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
147 #endif
148
149 extern void R_Shadow_EditLights_Init(void);
150
151 typedef enum r_shadow_rendermode_e
152 {
153         R_SHADOW_RENDERMODE_NONE,
154         R_SHADOW_RENDERMODE_ZPASS_STENCIL,
155         R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL,
156         R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE,
157         R_SHADOW_RENDERMODE_ZFAIL_STENCIL,
158         R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL,
159         R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE,
160         R_SHADOW_RENDERMODE_LIGHT_VERTEX,
161         R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN,
162         R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN,
163         R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN,
164         R_SHADOW_RENDERMODE_LIGHT_GLSL,
165         R_SHADOW_RENDERMODE_VISIBLEVOLUMES,
166         R_SHADOW_RENDERMODE_VISIBLELIGHTING,
167         R_SHADOW_RENDERMODE_SHADOWMAP2D
168 }
169 r_shadow_rendermode_t;
170
171 typedef enum r_shadow_shadowmode_e
172 {
173     R_SHADOW_SHADOWMODE_STENCIL,
174     R_SHADOW_SHADOWMODE_SHADOWMAP2D
175 }
176 r_shadow_shadowmode_t;
177
178 r_shadow_rendermode_t r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
179 r_shadow_rendermode_t r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_NONE;
180 r_shadow_rendermode_t r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_NONE;
181 r_shadow_rendermode_t r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_NONE;
182 qboolean r_shadow_usingshadowmap2d;
183 qboolean r_shadow_usingshadowmaportho;
184 int r_shadow_shadowmapside;
185 float r_shadow_shadowmap_texturescale[2];
186 float r_shadow_shadowmap_parameters[4];
187 #if 0
188 int r_shadow_drawbuffer;
189 int r_shadow_readbuffer;
190 #endif
191 int r_shadow_cullface_front, r_shadow_cullface_back;
192 GLuint r_shadow_fbo2d;
193 r_shadow_shadowmode_t r_shadow_shadowmode;
194 int r_shadow_shadowmapfilterquality;
195 int r_shadow_shadowmapdepthbits;
196 int r_shadow_shadowmapmaxsize;
197 qboolean r_shadow_shadowmapvsdct;
198 qboolean r_shadow_shadowmapsampler;
199 int r_shadow_shadowmappcf;
200 int r_shadow_shadowmapborder;
201 matrix4x4_t r_shadow_shadowmapmatrix;
202 int r_shadow_lightscissor[4];
203 qboolean r_shadow_usingdeferredprepass;
204
205 int maxshadowtriangles;
206 int *shadowelements;
207
208 int maxshadowvertices;
209 float *shadowvertex3f;
210
211 int maxshadowmark;
212 int numshadowmark;
213 int *shadowmark;
214 int *shadowmarklist;
215 int shadowmarkcount;
216
217 int maxshadowsides;
218 int numshadowsides;
219 unsigned char *shadowsides;
220 int *shadowsideslist;
221
222 int maxvertexupdate;
223 int *vertexupdate;
224 int *vertexremap;
225 int vertexupdatenum;
226
227 int r_shadow_buffer_numleafpvsbytes;
228 unsigned char *r_shadow_buffer_visitingleafpvs;
229 unsigned char *r_shadow_buffer_leafpvs;
230 int *r_shadow_buffer_leaflist;
231
232 int r_shadow_buffer_numsurfacepvsbytes;
233 unsigned char *r_shadow_buffer_surfacepvs;
234 int *r_shadow_buffer_surfacelist;
235 unsigned char *r_shadow_buffer_surfacesides;
236
237 int r_shadow_buffer_numshadowtrispvsbytes;
238 unsigned char *r_shadow_buffer_shadowtrispvs;
239 int r_shadow_buffer_numlighttrispvsbytes;
240 unsigned char *r_shadow_buffer_lighttrispvs;
241
242 rtexturepool_t *r_shadow_texturepool;
243 rtexture_t *r_shadow_attenuationgradienttexture;
244 rtexture_t *r_shadow_attenuation2dtexture;
245 rtexture_t *r_shadow_attenuation3dtexture;
246 skinframe_t *r_shadow_lightcorona;
247 rtexture_t *r_shadow_shadowmap2dtexture;
248 rtexture_t *r_shadow_shadowmap2dcolortexture;
249 rtexture_t *r_shadow_shadowmapvsdcttexture;
250 int r_shadow_shadowmapsize; // changes for each light based on distance
251 int r_shadow_shadowmaplod; // changes for each light based on distance
252
253 GLuint r_shadow_prepassgeometryfbo;
254 GLuint r_shadow_prepasslightingdiffusespecularfbo;
255 GLuint r_shadow_prepasslightingdiffusefbo;
256 int r_shadow_prepass_width;
257 int r_shadow_prepass_height;
258 rtexture_t *r_shadow_prepassgeometrydepthtexture;
259 rtexture_t *r_shadow_prepassgeometrydepthcolortexture;
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", "4", "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_usebihculling = {0, "r_shadow_usebihculling", "1", "use BIH (Bounding Interval Hierarchy) for culling lit surfaces instead of BSP (Binary Space Partitioning)"};
279 cvar_t r_shadow_usenormalmap = {CVAR_SAVE, "r_shadow_usenormalmap", "1", "enables use of directional shading on lights"};
280 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)"};
281 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"};
282 cvar_t r_shadow_glossintensity = {0, "r_shadow_glossintensity", "1", "how bright textured glossmaps should look if r_shadow_gloss is 1 or 2"};
283 cvar_t r_shadow_glossexponent = {0, "r_shadow_glossexponent", "32", "how 'sharp' the gloss should appear (specular power)"};
284 cvar_t r_shadow_gloss2exponent = {0, "r_shadow_gloss2exponent", "32", "same as r_shadow_glossexponent but for forced gloss (gloss 2) surfaces"};
285 cvar_t r_shadow_glossexact = {0, "r_shadow_glossexact", "0", "use exact reflection math for gloss (slightly slower, but should look a tad better)"};
286 cvar_t r_shadow_lightattenuationdividebias = {0, "r_shadow_lightattenuationdividebias", "1", "changes attenuation texture generation"};
287 cvar_t r_shadow_lightattenuationlinearscale = {0, "r_shadow_lightattenuationlinearscale", "2", "changes attenuation texture generation"};
288 cvar_t r_shadow_lightintensityscale = {0, "r_shadow_lightintensityscale", "1", "renders all world lights brighter or darker"};
289 cvar_t r_shadow_lightradiusscale = {0, "r_shadow_lightradiusscale", "1", "renders all world lights larger or smaller"};
290 cvar_t r_shadow_projectdistance = {0, "r_shadow_projectdistance", "0", "how far to cast shadows"};
291 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)"};
292 cvar_t r_shadow_realtime_dlight = {CVAR_SAVE, "r_shadow_realtime_dlight", "1", "enables rendering of dynamic lights such as explosions and rocket light"};
293 cvar_t r_shadow_realtime_dlight_shadows = {CVAR_SAVE, "r_shadow_realtime_dlight_shadows", "1", "enables rendering of shadows from dynamic lights"};
294 cvar_t r_shadow_realtime_dlight_svbspculling = {0, "r_shadow_realtime_dlight_svbspculling", "0", "enables svbsp optimization on dynamic lights (very slow!)"};
295 cvar_t r_shadow_realtime_dlight_portalculling = {0, "r_shadow_realtime_dlight_portalculling", "0", "enables portal optimization on dynamic lights (slow!)"};
296 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)"};
297 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"};
298 cvar_t r_shadow_realtime_world_shadows = {CVAR_SAVE, "r_shadow_realtime_world_shadows", "1", "enables rendering of shadows from world lights"};
299 cvar_t r_shadow_realtime_world_compile = {0, "r_shadow_realtime_world_compile", "1", "enables compilation of world lights for higher performance rendering"};
300 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"};
301 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)"};
302 cvar_t r_shadow_realtime_world_compileportalculling = {0, "r_shadow_realtime_world_compileportalculling", "1", "enables portal-based culling optimization during compilation (overrides compilesvbsp)"};
303 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)"};
304 cvar_t r_shadow_shadowmapping = {CVAR_SAVE, "r_shadow_shadowmapping", "1", "enables use of shadowmapping (depth texture sampling) instead of stencil shadow volumes, requires gl_fbo 1"};
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_sortsurfaces = {0, "r_shadow_sortsurfaces", "1", "improve performance by sorting illuminated surfaces by texture"};
319 cvar_t r_shadow_polygonfactor = {0, "r_shadow_polygonfactor", "0", "how much to enlarge shadow volume polygons when rendering (should be 0!)"};
320 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)"};
321 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)"};
322 cvar_t r_shadow_bouncegrid = {CVAR_SAVE, "r_shadow_bouncegrid", "0", "perform particle tracing for indirect lighting (Global Illumination / radiosity) using a 3D texture covering the scene, only active on levels with realtime lights active (r_shadow_realtime_world is usually required for these)"};
323 cvar_t r_shadow_bouncegrid_airstepmax = {CVAR_SAVE, "r_shadow_bouncegrid_airstepmax", "1024", "maximum number of photon accumulation contributions for one photon"};
324 cvar_t r_shadow_bouncegrid_airstepsize = {CVAR_SAVE, "r_shadow_bouncegrid_airstepsize", "64", "maximum spacing of photon accumulation through the air"};
325 cvar_t r_shadow_bouncegrid_bounceanglediffuse = {CVAR_SAVE, "r_shadow_bouncegrid_bounceanglediffuse", "0", "use random bounce direction rather than true reflection, makes some corner areas dark"};
326 cvar_t r_shadow_bouncegrid_directionalshading = {CVAR_SAVE, "r_shadow_bouncegrid_directionalshading", "0", "use diffuse shading rather than ambient, 3D texture becomes 8x as many pixels to hold the additional data"};
327 cvar_t r_shadow_bouncegrid_dlightparticlemultiplier = {CVAR_SAVE, "r_shadow_bouncegrid_dlightparticlemultiplier", "0", "if set to a high value like 16 this can make dlights look great, but 0 is recommended for performance reasons"};
328 cvar_t r_shadow_bouncegrid_hitmodels = {CVAR_SAVE, "r_shadow_bouncegrid_hitmodels", "0", "enables hitting character model geometry (SLOW)"};
329 cvar_t r_shadow_bouncegrid_includedirectlighting = {CVAR_SAVE, "r_shadow_bouncegrid_includedirectlighting", "0", "allows direct lighting to be recorded, not just indirect (gives an effect somewhat like r_shadow_realtime_world_lightmaps)"};
330 cvar_t r_shadow_bouncegrid_intensity = {CVAR_SAVE, "r_shadow_bouncegrid_intensity", "4", "overall brightness of bouncegrid texture"};
331 cvar_t r_shadow_bouncegrid_lightradiusscale = {CVAR_SAVE, "r_shadow_bouncegrid_lightradiusscale", "10", "particles stop at this fraction of light radius (can be more than 1)"};
332 cvar_t r_shadow_bouncegrid_maxbounce = {CVAR_SAVE, "r_shadow_bouncegrid_maxbounce", "5", "maximum number of bounces for a particle (minimum is 1)"};
333 cvar_t r_shadow_bouncegrid_particlebounceintensity = {CVAR_SAVE, "r_shadow_bouncegrid_particlebounceintensity", "4", "amount of energy carried over after each bounce, this is a multiplier of texture color and the result is clamped to 1 or less, to prevent adding energy on each bounce"};
334 cvar_t r_shadow_bouncegrid_particleintensity = {CVAR_SAVE, "r_shadow_bouncegrid_particleintensity", "1", "brightness of particles contributing to bouncegrid texture"};
335 cvar_t r_shadow_bouncegrid_photons = {CVAR_SAVE, "r_shadow_bouncegrid_photons", "2000", "total photons to shoot per update, divided proportionately between lights"};
336 cvar_t r_shadow_bouncegrid_spacingx = {CVAR_SAVE, "r_shadow_bouncegrid_spacingx", "64", "unit size of bouncegrid pixel on X axis"};
337 cvar_t r_shadow_bouncegrid_spacingy = {CVAR_SAVE, "r_shadow_bouncegrid_spacingy", "64", "unit size of bouncegrid pixel on Y axis"};
338 cvar_t r_shadow_bouncegrid_spacingz = {CVAR_SAVE, "r_shadow_bouncegrid_spacingz", "64", "unit size of bouncegrid pixel on Z axis"};
339 cvar_t r_shadow_bouncegrid_stablerandom = {CVAR_SAVE, "r_shadow_bouncegrid_stablerandom", "1", "make particle distribution consistent from frame to frame"};
340 cvar_t r_shadow_bouncegrid_static = {CVAR_SAVE, "r_shadow_bouncegrid_static", "1", "use static radiosity solution (high quality) rather than dynamic (splotchy)"};
341 cvar_t r_shadow_bouncegrid_static_directionalshading = {CVAR_SAVE, "r_shadow_bouncegrid_static_directionalshading", "1", "whether to use directionalshading when in static mode"};
342 cvar_t r_shadow_bouncegrid_static_photons = {CVAR_SAVE, "r_shadow_bouncegrid_static_photons", "25000", "photons value to use when in static mode"};
343 cvar_t r_shadow_bouncegrid_updateinterval = {CVAR_SAVE, "r_shadow_bouncegrid_updateinterval", "0", "update bouncegrid texture once per this many seconds, useful values are 0, 0.05, or 1000000"};
344 cvar_t r_shadow_bouncegrid_x = {CVAR_SAVE, "r_shadow_bouncegrid_x", "64", "maximum texture size of bouncegrid on X axis"};
345 cvar_t r_shadow_bouncegrid_y = {CVAR_SAVE, "r_shadow_bouncegrid_y", "64", "maximum texture size of bouncegrid on Y axis"};
346 cvar_t r_shadow_bouncegrid_z = {CVAR_SAVE, "r_shadow_bouncegrid_z", "32", "maximum texture size of bouncegrid on Z axis"};
347 cvar_t r_coronas = {CVAR_SAVE, "r_coronas", "1", "brightness of corona flare effects around certain lights, 0 disables corona effects"};
348 cvar_t r_coronas_occlusionsizescale = {CVAR_SAVE, "r_coronas_occlusionsizescale", "0.1", "size of light source for corona occlusion checksum the proportion of hidden pixels controls corona intensity"};
349 cvar_t r_coronas_occlusionquery = {CVAR_SAVE, "r_coronas_occlusionquery", "1", "use GL_ARB_occlusion_query extension if supported (fades coronas according to visibility)"};
350 cvar_t gl_flashblend = {CVAR_SAVE, "gl_flashblend", "0", "render bright coronas for dynamic lights instead of actual lighting, fast but ugly"};
351 cvar_t gl_ext_separatestencil = {0, "gl_ext_separatestencil", "1", "make use of OpenGL 2.0 glStencilOpSeparate or GL_ATI_separate_stencil extension"};
352 cvar_t gl_ext_stenciltwoside = {0, "gl_ext_stenciltwoside", "1", "make use of GL_EXT_stenciltwoside extension (NVIDIA only)"};
353 cvar_t r_editlights = {0, "r_editlights", "0", "enables .rtlights file editing mode"};
354 cvar_t r_editlights_cursordistance = {0, "r_editlights_cursordistance", "1024", "maximum distance of cursor from eye"};
355 cvar_t r_editlights_cursorpushback = {0, "r_editlights_cursorpushback", "0", "how far to pull the cursor back toward the eye"};
356 cvar_t r_editlights_cursorpushoff = {0, "r_editlights_cursorpushoff", "4", "how far to push the cursor off the impacted surface"};
357 cvar_t r_editlights_cursorgrid = {0, "r_editlights_cursorgrid", "4", "snaps cursor to this grid size"};
358 cvar_t r_editlights_quakelightsizescale = {CVAR_SAVE, "r_editlights_quakelightsizescale", "1", "changes size of light entities loaded from a map"};
359
360 typedef struct r_shadow_bouncegrid_settings_s
361 {
362         qboolean staticmode;
363         qboolean bounceanglediffuse;
364         qboolean directionalshading;
365         qboolean includedirectlighting;
366         float dlightparticlemultiplier;
367         qboolean hitmodels;
368         float lightradiusscale;
369         int maxbounce;
370         float particlebounceintensity;
371         float particleintensity;
372         int photons;
373         float spacing[3];
374         int stablerandom;
375         float airstepmax;
376         float airstepsize;
377 }
378 r_shadow_bouncegrid_settings_t;
379
380 r_shadow_bouncegrid_settings_t r_shadow_bouncegridsettings;
381 rtexture_t *r_shadow_bouncegridtexture;
382 matrix4x4_t r_shadow_bouncegridmatrix;
383 vec_t r_shadow_bouncegridintensity;
384 qboolean r_shadow_bouncegriddirectional;
385 static double r_shadow_bouncegridtime;
386 static int r_shadow_bouncegridresolution[3];
387 static int r_shadow_bouncegridnumpixels;
388 static unsigned char *r_shadow_bouncegridpixels;
389 static float *r_shadow_bouncegridhighpixels;
390
391 // note the table actually includes one more value, just to avoid the need to clamp the distance index due to minor math error
392 #define ATTENTABLESIZE 256
393 // 1D gradient, 2D circle and 3D sphere attenuation textures
394 #define ATTEN1DSIZE 32
395 #define ATTEN2DSIZE 64
396 #define ATTEN3DSIZE 32
397
398 static float r_shadow_attendividebias; // r_shadow_lightattenuationdividebias
399 static float r_shadow_attenlinearscale; // r_shadow_lightattenuationlinearscale
400 static float r_shadow_attentable[ATTENTABLESIZE+1];
401
402 rtlight_t *r_shadow_compilingrtlight;
403 static memexpandablearray_t r_shadow_worldlightsarray;
404 dlight_t *r_shadow_selectedlight;
405 dlight_t r_shadow_bufferlight;
406 vec3_t r_editlights_cursorlocation;
407 qboolean r_editlights_lockcursor;
408
409 extern int con_vislines;
410
411 void R_Shadow_UncompileWorldLights(void);
412 void R_Shadow_ClearWorldLights(void);
413 void R_Shadow_SaveWorldLights(void);
414 void R_Shadow_LoadWorldLights(void);
415 void R_Shadow_LoadLightsFile(void);
416 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void);
417 void R_Shadow_EditLights_Reload_f(void);
418 void R_Shadow_ValidateCvars(void);
419 static void R_Shadow_MakeTextures(void);
420
421 #define EDLIGHTSPRSIZE                  8
422 skinframe_t *r_editlights_sprcursor;
423 skinframe_t *r_editlights_sprlight;
424 skinframe_t *r_editlights_sprnoshadowlight;
425 skinframe_t *r_editlights_sprcubemaplight;
426 skinframe_t *r_editlights_sprcubemapnoshadowlight;
427 skinframe_t *r_editlights_sprselection;
428
429 void R_Shadow_SetShadowMode(void)
430 {
431         r_shadow_shadowmapmaxsize = bound(1, r_shadow_shadowmapping_maxsize.integer, (int)vid.maxtexturesize_2d / 4);
432         r_shadow_shadowmapvsdct = r_shadow_shadowmapping_vsdct.integer != 0 && vid.renderpath == RENDERPATH_GL20;
433         r_shadow_shadowmapfilterquality = r_shadow_shadowmapping_filterquality.integer;
434         r_shadow_shadowmapdepthbits = r_shadow_shadowmapping_depthbits.integer;
435         r_shadow_shadowmapborder = bound(0, r_shadow_shadowmapping_bordersize.integer, 16);
436         r_shadow_shadowmaplod = -1;
437         r_shadow_shadowmapsize = 0;
438         r_shadow_shadowmapsampler = false;
439         r_shadow_shadowmappcf = 0;
440         r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL;
441         if ((r_shadow_shadowmapping.integer || r_shadow_deferred.integer) && vid.support.ext_framebuffer_object)
442         {
443                 switch(vid.renderpath)
444                 {
445                 case RENDERPATH_GL20:
446                         if(r_shadow_shadowmapfilterquality < 0)
447                         {
448                                 if(vid.support.amd_texture_texture4 || vid.support.arb_texture_gather)
449                                         r_shadow_shadowmappcf = 1;
450                                 else if(strstr(gl_vendor, "NVIDIA") || strstr(gl_renderer, "Radeon HD")) 
451                                 {
452                                         r_shadow_shadowmapsampler = vid.support.arb_shadow;
453                                         r_shadow_shadowmappcf = 1;
454                                 }
455                                 else if(strstr(gl_vendor, "ATI")) 
456                                         r_shadow_shadowmappcf = 1;
457                                 else 
458                                         r_shadow_shadowmapsampler = vid.support.arb_shadow;
459                         }
460                         else 
461                         {
462                                 switch (r_shadow_shadowmapfilterquality)
463                                 {
464                                 case 1:
465                                         r_shadow_shadowmapsampler = vid.support.arb_shadow;
466                                         break;
467                                 case 2:
468                                         r_shadow_shadowmapsampler = vid.support.arb_shadow;
469                                         r_shadow_shadowmappcf = 1;
470                                         break;
471                                 case 3:
472                                         r_shadow_shadowmappcf = 1;
473                                         break;
474                                 case 4:
475                                         r_shadow_shadowmappcf = 2;
476                                         break;
477                                 }
478                         }
479                         r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D;
480                         break;
481                 case RENDERPATH_D3D9:
482                 case RENDERPATH_D3D10:
483                 case RENDERPATH_D3D11:
484                 case RENDERPATH_SOFT:
485                         r_shadow_shadowmapsampler = false;
486                         r_shadow_shadowmappcf = 1;
487                         r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D;
488                         break;
489                 case RENDERPATH_GL11:
490                 case RENDERPATH_GL13:
491                 case RENDERPATH_GLES1:
492                 case RENDERPATH_GLES2:
493                         break;
494                 }
495         }
496 }
497
498 qboolean R_Shadow_ShadowMappingEnabled(void)
499 {
500         switch (r_shadow_shadowmode)
501         {
502         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
503                 return true;
504         default:
505                 return false;
506         }
507 }
508
509 void R_Shadow_FreeShadowMaps(void)
510 {
511         R_Shadow_SetShadowMode();
512
513         R_Mesh_DestroyFramebufferObject(r_shadow_fbo2d);
514
515         r_shadow_fbo2d = 0;
516
517         if (r_shadow_shadowmap2dtexture)
518                 R_FreeTexture(r_shadow_shadowmap2dtexture);
519         r_shadow_shadowmap2dtexture = NULL;
520
521         if (r_shadow_shadowmap2dcolortexture)
522                 R_FreeTexture(r_shadow_shadowmap2dcolortexture);
523         r_shadow_shadowmap2dcolortexture = NULL;
524
525         if (r_shadow_shadowmapvsdcttexture)
526                 R_FreeTexture(r_shadow_shadowmapvsdcttexture);
527         r_shadow_shadowmapvsdcttexture = NULL;
528 }
529
530 void r_shadow_start(void)
531 {
532         // allocate vertex processing arrays
533         r_shadow_bouncegridpixels = NULL;
534         r_shadow_bouncegridhighpixels = NULL;
535         r_shadow_bouncegridnumpixels = 0;
536         r_shadow_bouncegridtexture = NULL;
537         r_shadow_bouncegriddirectional = false;
538         r_shadow_attenuationgradienttexture = NULL;
539         r_shadow_attenuation2dtexture = NULL;
540         r_shadow_attenuation3dtexture = NULL;
541         r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL;
542         r_shadow_shadowmap2dtexture = NULL;
543         r_shadow_shadowmap2dcolortexture = NULL;
544         r_shadow_shadowmapvsdcttexture = NULL;
545         r_shadow_shadowmapmaxsize = 0;
546         r_shadow_shadowmapsize = 0;
547         r_shadow_shadowmaplod = 0;
548         r_shadow_shadowmapfilterquality = -1;
549         r_shadow_shadowmapdepthbits = 0;
550         r_shadow_shadowmapvsdct = false;
551         r_shadow_shadowmapsampler = false;
552         r_shadow_shadowmappcf = 0;
553         r_shadow_fbo2d = 0;
554
555         R_Shadow_FreeShadowMaps();
556
557         r_shadow_texturepool = NULL;
558         r_shadow_filters_texturepool = NULL;
559         R_Shadow_ValidateCvars();
560         R_Shadow_MakeTextures();
561         maxshadowtriangles = 0;
562         shadowelements = NULL;
563         maxshadowvertices = 0;
564         shadowvertex3f = NULL;
565         maxvertexupdate = 0;
566         vertexupdate = NULL;
567         vertexremap = NULL;
568         vertexupdatenum = 0;
569         maxshadowmark = 0;
570         numshadowmark = 0;
571         shadowmark = NULL;
572         shadowmarklist = NULL;
573         shadowmarkcount = 0;
574         maxshadowsides = 0;
575         numshadowsides = 0;
576         shadowsides = NULL;
577         shadowsideslist = NULL;
578         r_shadow_buffer_numleafpvsbytes = 0;
579         r_shadow_buffer_visitingleafpvs = NULL;
580         r_shadow_buffer_leafpvs = NULL;
581         r_shadow_buffer_leaflist = NULL;
582         r_shadow_buffer_numsurfacepvsbytes = 0;
583         r_shadow_buffer_surfacepvs = NULL;
584         r_shadow_buffer_surfacelist = NULL;
585         r_shadow_buffer_surfacesides = NULL;
586         r_shadow_buffer_numshadowtrispvsbytes = 0;
587         r_shadow_buffer_shadowtrispvs = NULL;
588         r_shadow_buffer_numlighttrispvsbytes = 0;
589         r_shadow_buffer_lighttrispvs = NULL;
590
591         r_shadow_usingdeferredprepass = false;
592         r_shadow_prepass_width = r_shadow_prepass_height = 0;
593 }
594
595 static void R_Shadow_FreeDeferred(void);
596 void r_shadow_shutdown(void)
597 {
598         CHECKGLERROR
599         R_Shadow_UncompileWorldLights();
600
601         R_Shadow_FreeShadowMaps();
602
603         r_shadow_usingdeferredprepass = false;
604         if (r_shadow_prepass_width)
605                 R_Shadow_FreeDeferred();
606         r_shadow_prepass_width = r_shadow_prepass_height = 0;
607
608         CHECKGLERROR
609         r_shadow_bouncegridtexture = NULL;
610         r_shadow_bouncegridpixels = NULL;
611         r_shadow_bouncegridhighpixels = NULL;
612         r_shadow_bouncegridnumpixels = 0;
613         r_shadow_bouncegriddirectional = false;
614         r_shadow_attenuationgradienttexture = NULL;
615         r_shadow_attenuation2dtexture = NULL;
616         r_shadow_attenuation3dtexture = NULL;
617         R_FreeTexturePool(&r_shadow_texturepool);
618         R_FreeTexturePool(&r_shadow_filters_texturepool);
619         maxshadowtriangles = 0;
620         if (shadowelements)
621                 Mem_Free(shadowelements);
622         shadowelements = NULL;
623         if (shadowvertex3f)
624                 Mem_Free(shadowvertex3f);
625         shadowvertex3f = NULL;
626         maxvertexupdate = 0;
627         if (vertexupdate)
628                 Mem_Free(vertexupdate);
629         vertexupdate = NULL;
630         if (vertexremap)
631                 Mem_Free(vertexremap);
632         vertexremap = NULL;
633         vertexupdatenum = 0;
634         maxshadowmark = 0;
635         numshadowmark = 0;
636         if (shadowmark)
637                 Mem_Free(shadowmark);
638         shadowmark = NULL;
639         if (shadowmarklist)
640                 Mem_Free(shadowmarklist);
641         shadowmarklist = NULL;
642         shadowmarkcount = 0;
643         maxshadowsides = 0;
644         numshadowsides = 0;
645         if (shadowsides)
646                 Mem_Free(shadowsides);
647         shadowsides = NULL;
648         if (shadowsideslist)
649                 Mem_Free(shadowsideslist);
650         shadowsideslist = NULL;
651         r_shadow_buffer_numleafpvsbytes = 0;
652         if (r_shadow_buffer_visitingleafpvs)
653                 Mem_Free(r_shadow_buffer_visitingleafpvs);
654         r_shadow_buffer_visitingleafpvs = NULL;
655         if (r_shadow_buffer_leafpvs)
656                 Mem_Free(r_shadow_buffer_leafpvs);
657         r_shadow_buffer_leafpvs = NULL;
658         if (r_shadow_buffer_leaflist)
659                 Mem_Free(r_shadow_buffer_leaflist);
660         r_shadow_buffer_leaflist = NULL;
661         r_shadow_buffer_numsurfacepvsbytes = 0;
662         if (r_shadow_buffer_surfacepvs)
663                 Mem_Free(r_shadow_buffer_surfacepvs);
664         r_shadow_buffer_surfacepvs = NULL;
665         if (r_shadow_buffer_surfacelist)
666                 Mem_Free(r_shadow_buffer_surfacelist);
667         r_shadow_buffer_surfacelist = NULL;
668         if (r_shadow_buffer_surfacesides)
669                 Mem_Free(r_shadow_buffer_surfacesides);
670         r_shadow_buffer_surfacesides = NULL;
671         r_shadow_buffer_numshadowtrispvsbytes = 0;
672         if (r_shadow_buffer_shadowtrispvs)
673                 Mem_Free(r_shadow_buffer_shadowtrispvs);
674         r_shadow_buffer_numlighttrispvsbytes = 0;
675         if (r_shadow_buffer_lighttrispvs)
676                 Mem_Free(r_shadow_buffer_lighttrispvs);
677 }
678
679 void r_shadow_newmap(void)
680 {
681         if (r_shadow_bouncegridtexture) R_FreeTexture(r_shadow_bouncegridtexture);r_shadow_bouncegridtexture = NULL;
682         if (r_shadow_lightcorona)                 R_SkinFrame_MarkUsed(r_shadow_lightcorona);
683         if (r_editlights_sprcursor)               R_SkinFrame_MarkUsed(r_editlights_sprcursor);
684         if (r_editlights_sprlight)                R_SkinFrame_MarkUsed(r_editlights_sprlight);
685         if (r_editlights_sprnoshadowlight)        R_SkinFrame_MarkUsed(r_editlights_sprnoshadowlight);
686         if (r_editlights_sprcubemaplight)         R_SkinFrame_MarkUsed(r_editlights_sprcubemaplight);
687         if (r_editlights_sprcubemapnoshadowlight) R_SkinFrame_MarkUsed(r_editlights_sprcubemapnoshadowlight);
688         if (r_editlights_sprselection)            R_SkinFrame_MarkUsed(r_editlights_sprselection);
689         if (strncmp(cl.worldname, r_shadow_mapname, sizeof(r_shadow_mapname)))
690                 R_Shadow_EditLights_Reload_f();
691 }
692
693 void R_Shadow_Init(void)
694 {
695         Cvar_RegisterVariable(&r_shadow_bumpscale_basetexture);
696         Cvar_RegisterVariable(&r_shadow_bumpscale_bumpmap);
697         Cvar_RegisterVariable(&r_shadow_usebihculling);
698         Cvar_RegisterVariable(&r_shadow_usenormalmap);
699         Cvar_RegisterVariable(&r_shadow_debuglight);
700         Cvar_RegisterVariable(&r_shadow_deferred);
701         Cvar_RegisterVariable(&r_shadow_deferred_8bitrange);
702 //      Cvar_RegisterVariable(&r_shadow_deferred_fp);
703         Cvar_RegisterVariable(&r_shadow_gloss);
704         Cvar_RegisterVariable(&r_shadow_gloss2intensity);
705         Cvar_RegisterVariable(&r_shadow_glossintensity);
706         Cvar_RegisterVariable(&r_shadow_glossexponent);
707         Cvar_RegisterVariable(&r_shadow_gloss2exponent);
708         Cvar_RegisterVariable(&r_shadow_glossexact);
709         Cvar_RegisterVariable(&r_shadow_lightattenuationdividebias);
710         Cvar_RegisterVariable(&r_shadow_lightattenuationlinearscale);
711         Cvar_RegisterVariable(&r_shadow_lightintensityscale);
712         Cvar_RegisterVariable(&r_shadow_lightradiusscale);
713         Cvar_RegisterVariable(&r_shadow_projectdistance);
714         Cvar_RegisterVariable(&r_shadow_frontsidecasting);
715         Cvar_RegisterVariable(&r_shadow_realtime_dlight);
716         Cvar_RegisterVariable(&r_shadow_realtime_dlight_shadows);
717         Cvar_RegisterVariable(&r_shadow_realtime_dlight_svbspculling);
718         Cvar_RegisterVariable(&r_shadow_realtime_dlight_portalculling);
719         Cvar_RegisterVariable(&r_shadow_realtime_world);
720         Cvar_RegisterVariable(&r_shadow_realtime_world_lightmaps);
721         Cvar_RegisterVariable(&r_shadow_realtime_world_shadows);
722         Cvar_RegisterVariable(&r_shadow_realtime_world_compile);
723         Cvar_RegisterVariable(&r_shadow_realtime_world_compileshadow);
724         Cvar_RegisterVariable(&r_shadow_realtime_world_compilesvbsp);
725         Cvar_RegisterVariable(&r_shadow_realtime_world_compileportalculling);
726         Cvar_RegisterVariable(&r_shadow_scissor);
727         Cvar_RegisterVariable(&r_shadow_shadowmapping);
728         Cvar_RegisterVariable(&r_shadow_shadowmapping_vsdct);
729         Cvar_RegisterVariable(&r_shadow_shadowmapping_filterquality);
730         Cvar_RegisterVariable(&r_shadow_shadowmapping_depthbits);
731         Cvar_RegisterVariable(&r_shadow_shadowmapping_precision);
732         Cvar_RegisterVariable(&r_shadow_shadowmapping_maxsize);
733         Cvar_RegisterVariable(&r_shadow_shadowmapping_minsize);
734 //      Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_bias);
735 //      Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_scale);
736         Cvar_RegisterVariable(&r_shadow_shadowmapping_bordersize);
737         Cvar_RegisterVariable(&r_shadow_shadowmapping_nearclip);
738         Cvar_RegisterVariable(&r_shadow_shadowmapping_bias);
739         Cvar_RegisterVariable(&r_shadow_shadowmapping_polygonfactor);
740         Cvar_RegisterVariable(&r_shadow_shadowmapping_polygonoffset);
741         Cvar_RegisterVariable(&r_shadow_sortsurfaces);
742         Cvar_RegisterVariable(&r_shadow_polygonfactor);
743         Cvar_RegisterVariable(&r_shadow_polygonoffset);
744         Cvar_RegisterVariable(&r_shadow_texture3d);
745         Cvar_RegisterVariable(&r_shadow_bouncegrid);
746         Cvar_RegisterVariable(&r_shadow_bouncegrid_airstepmax);
747         Cvar_RegisterVariable(&r_shadow_bouncegrid_airstepsize);
748         Cvar_RegisterVariable(&r_shadow_bouncegrid_bounceanglediffuse);
749         Cvar_RegisterVariable(&r_shadow_bouncegrid_directionalshading);
750         Cvar_RegisterVariable(&r_shadow_bouncegrid_dlightparticlemultiplier);
751         Cvar_RegisterVariable(&r_shadow_bouncegrid_hitmodels);
752         Cvar_RegisterVariable(&r_shadow_bouncegrid_includedirectlighting);
753         Cvar_RegisterVariable(&r_shadow_bouncegrid_intensity);
754         Cvar_RegisterVariable(&r_shadow_bouncegrid_lightradiusscale);
755         Cvar_RegisterVariable(&r_shadow_bouncegrid_maxbounce);
756         Cvar_RegisterVariable(&r_shadow_bouncegrid_particlebounceintensity);
757         Cvar_RegisterVariable(&r_shadow_bouncegrid_particleintensity);
758         Cvar_RegisterVariable(&r_shadow_bouncegrid_photons);
759         Cvar_RegisterVariable(&r_shadow_bouncegrid_spacingx);
760         Cvar_RegisterVariable(&r_shadow_bouncegrid_spacingy);
761         Cvar_RegisterVariable(&r_shadow_bouncegrid_spacingz);
762         Cvar_RegisterVariable(&r_shadow_bouncegrid_stablerandom);
763         Cvar_RegisterVariable(&r_shadow_bouncegrid_static);
764         Cvar_RegisterVariable(&r_shadow_bouncegrid_static_directionalshading);
765         Cvar_RegisterVariable(&r_shadow_bouncegrid_static_photons);
766         Cvar_RegisterVariable(&r_shadow_bouncegrid_updateinterval);
767         Cvar_RegisterVariable(&r_shadow_bouncegrid_x);
768         Cvar_RegisterVariable(&r_shadow_bouncegrid_y);
769         Cvar_RegisterVariable(&r_shadow_bouncegrid_z);
770         Cvar_RegisterVariable(&r_coronas);
771         Cvar_RegisterVariable(&r_coronas_occlusionsizescale);
772         Cvar_RegisterVariable(&r_coronas_occlusionquery);
773         Cvar_RegisterVariable(&gl_flashblend);
774         Cvar_RegisterVariable(&gl_ext_separatestencil);
775         Cvar_RegisterVariable(&gl_ext_stenciltwoside);
776         R_Shadow_EditLights_Init();
777         Mem_ExpandableArray_NewArray(&r_shadow_worldlightsarray, r_main_mempool, sizeof(dlight_t), 128);
778         maxshadowtriangles = 0;
779         shadowelements = NULL;
780         maxshadowvertices = 0;
781         shadowvertex3f = NULL;
782         maxvertexupdate = 0;
783         vertexupdate = NULL;
784         vertexremap = NULL;
785         vertexupdatenum = 0;
786         maxshadowmark = 0;
787         numshadowmark = 0;
788         shadowmark = NULL;
789         shadowmarklist = NULL;
790         shadowmarkcount = 0;
791         maxshadowsides = 0;
792         numshadowsides = 0;
793         shadowsides = NULL;
794         shadowsideslist = NULL;
795         r_shadow_buffer_numleafpvsbytes = 0;
796         r_shadow_buffer_visitingleafpvs = NULL;
797         r_shadow_buffer_leafpvs = NULL;
798         r_shadow_buffer_leaflist = NULL;
799         r_shadow_buffer_numsurfacepvsbytes = 0;
800         r_shadow_buffer_surfacepvs = NULL;
801         r_shadow_buffer_surfacelist = NULL;
802         r_shadow_buffer_surfacesides = NULL;
803         r_shadow_buffer_shadowtrispvs = NULL;
804         r_shadow_buffer_lighttrispvs = NULL;
805         R_RegisterModule("R_Shadow", r_shadow_start, r_shadow_shutdown, r_shadow_newmap, NULL, NULL);
806 }
807
808 matrix4x4_t matrix_attenuationxyz =
809 {
810         {
811                 {0.5, 0.0, 0.0, 0.5},
812                 {0.0, 0.5, 0.0, 0.5},
813                 {0.0, 0.0, 0.5, 0.5},
814                 {0.0, 0.0, 0.0, 1.0}
815         }
816 };
817
818 matrix4x4_t matrix_attenuationz =
819 {
820         {
821                 {0.0, 0.0, 0.5, 0.5},
822                 {0.0, 0.0, 0.0, 0.5},
823                 {0.0, 0.0, 0.0, 0.5},
824                 {0.0, 0.0, 0.0, 1.0}
825         }
826 };
827
828 void R_Shadow_ResizeShadowArrays(int numvertices, int numtriangles, int vertscale, int triscale)
829 {
830         numvertices = ((numvertices + 255) & ~255) * vertscale;
831         numtriangles = ((numtriangles + 255) & ~255) * triscale;
832         // make sure shadowelements is big enough for this volume
833         if (maxshadowtriangles < numtriangles)
834         {
835                 maxshadowtriangles = numtriangles;
836                 if (shadowelements)
837                         Mem_Free(shadowelements);
838                 shadowelements = (int *)Mem_Alloc(r_main_mempool, maxshadowtriangles * sizeof(int[3]));
839         }
840         // make sure shadowvertex3f is big enough for this volume
841         if (maxshadowvertices < numvertices)
842         {
843                 maxshadowvertices = numvertices;
844                 if (shadowvertex3f)
845                         Mem_Free(shadowvertex3f);
846                 shadowvertex3f = (float *)Mem_Alloc(r_main_mempool, maxshadowvertices * sizeof(float[3]));
847         }
848 }
849
850 static void R_Shadow_EnlargeLeafSurfaceTrisBuffer(int numleafs, int numsurfaces, int numshadowtriangles, int numlighttriangles)
851 {
852         int numleafpvsbytes = (((numleafs + 7) >> 3) + 255) & ~255;
853         int numsurfacepvsbytes = (((numsurfaces + 7) >> 3) + 255) & ~255;
854         int numshadowtrispvsbytes = (((numshadowtriangles + 7) >> 3) + 255) & ~255;
855         int numlighttrispvsbytes = (((numlighttriangles + 7) >> 3) + 255) & ~255;
856         if (r_shadow_buffer_numleafpvsbytes < numleafpvsbytes)
857         {
858                 if (r_shadow_buffer_visitingleafpvs)
859                         Mem_Free(r_shadow_buffer_visitingleafpvs);
860                 if (r_shadow_buffer_leafpvs)
861                         Mem_Free(r_shadow_buffer_leafpvs);
862                 if (r_shadow_buffer_leaflist)
863                         Mem_Free(r_shadow_buffer_leaflist);
864                 r_shadow_buffer_numleafpvsbytes = numleafpvsbytes;
865                 r_shadow_buffer_visitingleafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
866                 r_shadow_buffer_leafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
867                 r_shadow_buffer_leaflist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes * 8 * sizeof(*r_shadow_buffer_leaflist));
868         }
869         if (r_shadow_buffer_numsurfacepvsbytes < numsurfacepvsbytes)
870         {
871                 if (r_shadow_buffer_surfacepvs)
872                         Mem_Free(r_shadow_buffer_surfacepvs);
873                 if (r_shadow_buffer_surfacelist)
874                         Mem_Free(r_shadow_buffer_surfacelist);
875                 if (r_shadow_buffer_surfacesides)
876                         Mem_Free(r_shadow_buffer_surfacesides);
877                 r_shadow_buffer_numsurfacepvsbytes = numsurfacepvsbytes;
878                 r_shadow_buffer_surfacepvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes);
879                 r_shadow_buffer_surfacelist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
880                 r_shadow_buffer_surfacesides = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
881         }
882         if (r_shadow_buffer_numshadowtrispvsbytes < numshadowtrispvsbytes)
883         {
884                 if (r_shadow_buffer_shadowtrispvs)
885                         Mem_Free(r_shadow_buffer_shadowtrispvs);
886                 r_shadow_buffer_numshadowtrispvsbytes = numshadowtrispvsbytes;
887                 r_shadow_buffer_shadowtrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numshadowtrispvsbytes);
888         }
889         if (r_shadow_buffer_numlighttrispvsbytes < numlighttrispvsbytes)
890         {
891                 if (r_shadow_buffer_lighttrispvs)
892                         Mem_Free(r_shadow_buffer_lighttrispvs);
893                 r_shadow_buffer_numlighttrispvsbytes = numlighttrispvsbytes;
894                 r_shadow_buffer_lighttrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numlighttrispvsbytes);
895         }
896 }
897
898 void R_Shadow_PrepareShadowMark(int numtris)
899 {
900         // make sure shadowmark is big enough for this volume
901         if (maxshadowmark < numtris)
902         {
903                 maxshadowmark = numtris;
904                 if (shadowmark)
905                         Mem_Free(shadowmark);
906                 if (shadowmarklist)
907                         Mem_Free(shadowmarklist);
908                 shadowmark = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmark));
909                 shadowmarklist = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmarklist));
910                 shadowmarkcount = 0;
911         }
912         shadowmarkcount++;
913         // if shadowmarkcount wrapped we clear the array and adjust accordingly
914         if (shadowmarkcount == 0)
915         {
916                 shadowmarkcount = 1;
917                 memset(shadowmark, 0, maxshadowmark * sizeof(*shadowmark));
918         }
919         numshadowmark = 0;
920 }
921
922 void R_Shadow_PrepareShadowSides(int numtris)
923 {
924     if (maxshadowsides < numtris)
925     {
926         maxshadowsides = numtris;
927         if (shadowsides)
928                         Mem_Free(shadowsides);
929                 if (shadowsideslist)
930                         Mem_Free(shadowsideslist);
931                 shadowsides = (unsigned char *)Mem_Alloc(r_main_mempool, maxshadowsides * sizeof(*shadowsides));
932                 shadowsideslist = (int *)Mem_Alloc(r_main_mempool, maxshadowsides * sizeof(*shadowsideslist));
933         }
934         numshadowsides = 0;
935 }
936
937 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)
938 {
939         int i, j;
940         int outtriangles = 0, outvertices = 0;
941         const int *element;
942         const float *vertex;
943         float ratio, direction[3], projectvector[3];
944
945         if (projectdirection)
946                 VectorScale(projectdirection, projectdistance, projectvector);
947         else
948                 VectorClear(projectvector);
949
950         // create the vertices
951         if (projectdirection)
952         {
953                 for (i = 0;i < numshadowmarktris;i++)
954                 {
955                         element = inelement3i + shadowmarktris[i] * 3;
956                         for (j = 0;j < 3;j++)
957                         {
958                                 if (vertexupdate[element[j]] != vertexupdatenum)
959                                 {
960                                         vertexupdate[element[j]] = vertexupdatenum;
961                                         vertexremap[element[j]] = outvertices;
962                                         vertex = invertex3f + element[j] * 3;
963                                         // project one copy of the vertex according to projectvector
964                                         VectorCopy(vertex, outvertex3f);
965                                         VectorAdd(vertex, projectvector, (outvertex3f + 3));
966                                         outvertex3f += 6;
967                                         outvertices += 2;
968                                 }
969                         }
970                 }
971         }
972         else
973         {
974                 for (i = 0;i < numshadowmarktris;i++)
975                 {
976                         element = inelement3i + shadowmarktris[i] * 3;
977                         for (j = 0;j < 3;j++)
978                         {
979                                 if (vertexupdate[element[j]] != vertexupdatenum)
980                                 {
981                                         vertexupdate[element[j]] = vertexupdatenum;
982                                         vertexremap[element[j]] = outvertices;
983                                         vertex = invertex3f + element[j] * 3;
984                                         // project one copy of the vertex to the sphere radius of the light
985                                         // (FIXME: would projecting it to the light box be better?)
986                                         VectorSubtract(vertex, projectorigin, direction);
987                                         ratio = projectdistance / VectorLength(direction);
988                                         VectorCopy(vertex, outvertex3f);
989                                         VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
990                                         outvertex3f += 6;
991                                         outvertices += 2;
992                                 }
993                         }
994                 }
995         }
996
997         if (r_shadow_frontsidecasting.integer)
998         {
999                 for (i = 0;i < numshadowmarktris;i++)
1000                 {
1001                         int remappedelement[3];
1002                         int markindex;
1003                         const int *neighbortriangle;
1004
1005                         markindex = shadowmarktris[i] * 3;
1006                         element = inelement3i + markindex;
1007                         neighbortriangle = inneighbor3i + markindex;
1008                         // output the front and back triangles
1009                         outelement3i[0] = vertexremap[element[0]];
1010                         outelement3i[1] = vertexremap[element[1]];
1011                         outelement3i[2] = vertexremap[element[2]];
1012                         outelement3i[3] = vertexremap[element[2]] + 1;
1013                         outelement3i[4] = vertexremap[element[1]] + 1;
1014                         outelement3i[5] = vertexremap[element[0]] + 1;
1015
1016                         outelement3i += 6;
1017                         outtriangles += 2;
1018                         // output the sides (facing outward from this triangle)
1019                         if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
1020                         {
1021                                 remappedelement[0] = vertexremap[element[0]];
1022                                 remappedelement[1] = vertexremap[element[1]];
1023                                 outelement3i[0] = remappedelement[1];
1024                                 outelement3i[1] = remappedelement[0];
1025                                 outelement3i[2] = remappedelement[0] + 1;
1026                                 outelement3i[3] = remappedelement[1];
1027                                 outelement3i[4] = remappedelement[0] + 1;
1028                                 outelement3i[5] = remappedelement[1] + 1;
1029
1030                                 outelement3i += 6;
1031                                 outtriangles += 2;
1032                         }
1033                         if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
1034                         {
1035                                 remappedelement[1] = vertexremap[element[1]];
1036                                 remappedelement[2] = vertexremap[element[2]];
1037                                 outelement3i[0] = remappedelement[2];
1038                                 outelement3i[1] = remappedelement[1];
1039                                 outelement3i[2] = remappedelement[1] + 1;
1040                                 outelement3i[3] = remappedelement[2];
1041                                 outelement3i[4] = remappedelement[1] + 1;
1042                                 outelement3i[5] = remappedelement[2] + 1;
1043
1044                                 outelement3i += 6;
1045                                 outtriangles += 2;
1046                         }
1047                         if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
1048                         {
1049                                 remappedelement[0] = vertexremap[element[0]];
1050                                 remappedelement[2] = vertexremap[element[2]];
1051                                 outelement3i[0] = remappedelement[0];
1052                                 outelement3i[1] = remappedelement[2];
1053                                 outelement3i[2] = remappedelement[2] + 1;
1054                                 outelement3i[3] = remappedelement[0];
1055                                 outelement3i[4] = remappedelement[2] + 1;
1056                                 outelement3i[5] = remappedelement[0] + 1;
1057
1058                                 outelement3i += 6;
1059                                 outtriangles += 2;
1060                         }
1061                 }
1062         }
1063         else
1064         {
1065                 for (i = 0;i < numshadowmarktris;i++)
1066                 {
1067                         int remappedelement[3];
1068                         int markindex;
1069                         const int *neighbortriangle;
1070
1071                         markindex = shadowmarktris[i] * 3;
1072                         element = inelement3i + markindex;
1073                         neighbortriangle = inneighbor3i + markindex;
1074                         // output the front and back triangles
1075                         outelement3i[0] = vertexremap[element[2]];
1076                         outelement3i[1] = vertexremap[element[1]];
1077                         outelement3i[2] = vertexremap[element[0]];
1078                         outelement3i[3] = vertexremap[element[0]] + 1;
1079                         outelement3i[4] = vertexremap[element[1]] + 1;
1080                         outelement3i[5] = vertexremap[element[2]] + 1;
1081
1082                         outelement3i += 6;
1083                         outtriangles += 2;
1084                         // output the sides (facing outward from this triangle)
1085                         if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
1086                         {
1087                                 remappedelement[0] = vertexremap[element[0]];
1088                                 remappedelement[1] = vertexremap[element[1]];
1089                                 outelement3i[0] = remappedelement[0];
1090                                 outelement3i[1] = remappedelement[1];
1091                                 outelement3i[2] = remappedelement[1] + 1;
1092                                 outelement3i[3] = remappedelement[0];
1093                                 outelement3i[4] = remappedelement[1] + 1;
1094                                 outelement3i[5] = remappedelement[0] + 1;
1095
1096                                 outelement3i += 6;
1097                                 outtriangles += 2;
1098                         }
1099                         if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
1100                         {
1101                                 remappedelement[1] = vertexremap[element[1]];
1102                                 remappedelement[2] = vertexremap[element[2]];
1103                                 outelement3i[0] = remappedelement[1];
1104                                 outelement3i[1] = remappedelement[2];
1105                                 outelement3i[2] = remappedelement[2] + 1;
1106                                 outelement3i[3] = remappedelement[1];
1107                                 outelement3i[4] = remappedelement[2] + 1;
1108                                 outelement3i[5] = remappedelement[1] + 1;
1109
1110                                 outelement3i += 6;
1111                                 outtriangles += 2;
1112                         }
1113                         if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
1114                         {
1115                                 remappedelement[0] = vertexremap[element[0]];
1116                                 remappedelement[2] = vertexremap[element[2]];
1117                                 outelement3i[0] = remappedelement[2];
1118                                 outelement3i[1] = remappedelement[0];
1119                                 outelement3i[2] = remappedelement[0] + 1;
1120                                 outelement3i[3] = remappedelement[2];
1121                                 outelement3i[4] = remappedelement[0] + 1;
1122                                 outelement3i[5] = remappedelement[2] + 1;
1123
1124                                 outelement3i += 6;
1125                                 outtriangles += 2;
1126                         }
1127                 }
1128         }
1129         if (outnumvertices)
1130                 *outnumvertices = outvertices;
1131         return outtriangles;
1132 }
1133
1134 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)
1135 {
1136         int i, j, k;
1137         int outtriangles = 0, outvertices = 0;
1138         const int *element;
1139         const float *vertex;
1140         float ratio, direction[3], projectvector[3];
1141         qboolean side[4];
1142
1143         if (projectdirection)
1144                 VectorScale(projectdirection, projectdistance, projectvector);
1145         else
1146                 VectorClear(projectvector);
1147
1148         for (i = 0;i < numshadowmarktris;i++)
1149         {
1150                 int remappedelement[3];
1151                 int markindex;
1152                 const int *neighbortriangle;
1153
1154                 markindex = shadowmarktris[i] * 3;
1155                 neighbortriangle = inneighbor3i + markindex;
1156                 side[0] = shadowmark[neighbortriangle[0]] == shadowmarkcount;
1157                 side[1] = shadowmark[neighbortriangle[1]] == shadowmarkcount;
1158                 side[2] = shadowmark[neighbortriangle[2]] == shadowmarkcount;
1159                 if (side[0] + side[1] + side[2] == 0)
1160                         continue;
1161
1162                 side[3] = side[0];
1163                 element = inelement3i + markindex;
1164
1165                 // create the vertices
1166                 for (j = 0;j < 3;j++)
1167                 {
1168                         if (side[j] + side[j+1] == 0)
1169                                 continue;
1170                         k = element[j];
1171                         if (vertexupdate[k] != vertexupdatenum)
1172                         {
1173                                 vertexupdate[k] = vertexupdatenum;
1174                                 vertexremap[k] = outvertices;
1175                                 vertex = invertex3f + k * 3;
1176                                 VectorCopy(vertex, outvertex3f);
1177                                 if (projectdirection)
1178                                 {
1179                                         // project one copy of the vertex according to projectvector
1180                                         VectorAdd(vertex, projectvector, (outvertex3f + 3));
1181                                 }
1182                                 else
1183                                 {
1184                                         // project one copy of the vertex to the sphere radius of the light
1185                                         // (FIXME: would projecting it to the light box be better?)
1186                                         VectorSubtract(vertex, projectorigin, direction);
1187                                         ratio = projectdistance / VectorLength(direction);
1188                                         VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
1189                                 }
1190                                 outvertex3f += 6;
1191                                 outvertices += 2;
1192                         }
1193                 }
1194
1195                 // output the sides (facing outward from this triangle)
1196                 if (!side[0])
1197                 {
1198                         remappedelement[0] = vertexremap[element[0]];
1199                         remappedelement[1] = vertexremap[element[1]];
1200                         outelement3i[0] = remappedelement[1];
1201                         outelement3i[1] = remappedelement[0];
1202                         outelement3i[2] = remappedelement[0] + 1;
1203                         outelement3i[3] = remappedelement[1];
1204                         outelement3i[4] = remappedelement[0] + 1;
1205                         outelement3i[5] = remappedelement[1] + 1;
1206
1207                         outelement3i += 6;
1208                         outtriangles += 2;
1209                 }
1210                 if (!side[1])
1211                 {
1212                         remappedelement[1] = vertexremap[element[1]];
1213                         remappedelement[2] = vertexremap[element[2]];
1214                         outelement3i[0] = remappedelement[2];
1215                         outelement3i[1] = remappedelement[1];
1216                         outelement3i[2] = remappedelement[1] + 1;
1217                         outelement3i[3] = remappedelement[2];
1218                         outelement3i[4] = remappedelement[1] + 1;
1219                         outelement3i[5] = remappedelement[2] + 1;
1220
1221                         outelement3i += 6;
1222                         outtriangles += 2;
1223                 }
1224                 if (!side[2])
1225                 {
1226                         remappedelement[0] = vertexremap[element[0]];
1227                         remappedelement[2] = vertexremap[element[2]];
1228                         outelement3i[0] = remappedelement[0];
1229                         outelement3i[1] = remappedelement[2];
1230                         outelement3i[2] = remappedelement[2] + 1;
1231                         outelement3i[3] = remappedelement[0];
1232                         outelement3i[4] = remappedelement[2] + 1;
1233                         outelement3i[5] = remappedelement[0] + 1;
1234
1235                         outelement3i += 6;
1236                         outtriangles += 2;
1237                 }
1238         }
1239         if (outnumvertices)
1240                 *outnumvertices = outvertices;
1241         return outtriangles;
1242 }
1243
1244 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)
1245 {
1246         int t, tend;
1247         const int *e;
1248         const float *v[3];
1249         float normal[3];
1250         if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1251                 return;
1252         tend = firsttriangle + numtris;
1253         if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1254         {
1255                 // surface box entirely inside light box, no box cull
1256                 if (projectdirection)
1257                 {
1258                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1259                         {
1260                                 TriangleNormal(invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3, normal);
1261                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1262                                         shadowmarklist[numshadowmark++] = t;
1263                         }
1264                 }
1265                 else
1266                 {
1267                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1268                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3))
1269                                         shadowmarklist[numshadowmark++] = t;
1270                 }
1271         }
1272         else
1273         {
1274                 // surface box not entirely inside light box, cull each triangle
1275                 if (projectdirection)
1276                 {
1277                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1278                         {
1279                                 v[0] = invertex3f + e[0] * 3;
1280                                 v[1] = invertex3f + e[1] * 3;
1281                                 v[2] = invertex3f + e[2] * 3;
1282                                 TriangleNormal(v[0], v[1], v[2], normal);
1283                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1284                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1285                                         shadowmarklist[numshadowmark++] = t;
1286                         }
1287                 }
1288                 else
1289                 {
1290                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1291                         {
1292                                 v[0] = invertex3f + e[0] * 3;
1293                                 v[1] = invertex3f + e[1] * 3;
1294                                 v[2] = invertex3f + e[2] * 3;
1295                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1296                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1297                                         shadowmarklist[numshadowmark++] = t;
1298                         }
1299                 }
1300         }
1301 }
1302
1303 qboolean R_Shadow_UseZPass(vec3_t mins, vec3_t maxs)
1304 {
1305 #if 1
1306         return false;
1307 #else
1308         if (r_shadow_compilingrtlight || !r_shadow_frontsidecasting.integer || !r_shadow_usezpassifpossible.integer)
1309                 return false;
1310         // check if the shadow volume intersects the near plane
1311         //
1312         // a ray between the eye and light origin may intersect the caster,
1313         // indicating that the shadow may touch the eye location, however we must
1314         // test the near plane (a polygon), not merely the eye location, so it is
1315         // easiest to enlarge the caster bounding shape slightly for this.
1316         // TODO
1317         return true;
1318 #endif
1319 }
1320
1321 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)
1322 {
1323         int i, tris, outverts;
1324         if (projectdistance < 0.1)
1325         {
1326                 Con_Printf("R_Shadow_Volume: projectdistance %f\n", projectdistance);
1327                 return;
1328         }
1329         if (!numverts || !nummarktris)
1330                 return;
1331         // make sure shadowelements is big enough for this volume
1332         if (maxshadowtriangles < nummarktris*8 || maxshadowvertices < numverts*2)
1333                 R_Shadow_ResizeShadowArrays(numverts, nummarktris, 2, 8);
1334
1335         if (maxvertexupdate < numverts)
1336         {
1337                 maxvertexupdate = numverts;
1338                 if (vertexupdate)
1339                         Mem_Free(vertexupdate);
1340                 if (vertexremap)
1341                         Mem_Free(vertexremap);
1342                 vertexupdate = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1343                 vertexremap = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1344                 vertexupdatenum = 0;
1345         }
1346         vertexupdatenum++;
1347         if (vertexupdatenum == 0)
1348         {
1349                 vertexupdatenum = 1;
1350                 memset(vertexupdate, 0, maxvertexupdate * sizeof(int));
1351                 memset(vertexremap, 0, maxvertexupdate * sizeof(int));
1352         }
1353
1354         for (i = 0;i < nummarktris;i++)
1355                 shadowmark[marktris[i]] = shadowmarkcount;
1356
1357         if (r_shadow_compilingrtlight)
1358         {
1359                 // if we're compiling an rtlight, capture the mesh
1360                 //tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1361                 //Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zpass, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1362                 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1363                 Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zfail, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1364         }
1365         else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_VISIBLEVOLUMES)
1366         {
1367                 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1368                 R_Mesh_PrepareVertices_Vertex3f(outverts, shadowvertex3f, NULL);
1369                 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1370         }
1371         else
1372         {
1373                 // decide which type of shadow to generate and set stencil mode
1374                 R_Shadow_RenderMode_StencilShadowVolumes(R_Shadow_UseZPass(trismins, trismaxs));
1375                 // generate the sides or a solid volume, depending on type
1376                 if (r_shadow_rendermode >= R_SHADOW_RENDERMODE_ZPASS_STENCIL && r_shadow_rendermode <= R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE)
1377                         tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1378                 else
1379                         tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1380                 r_refdef.stats.lights_dynamicshadowtriangles += tris;
1381                 r_refdef.stats.lights_shadowtriangles += tris;
1382                 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
1383                 {
1384                         // increment stencil if frontface is infront of depthbuffer
1385                         GL_CullFace(r_refdef.view.cullface_front);
1386                         R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, 128, 255);
1387                         R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1388                         // decrement stencil if backface is infront of depthbuffer
1389                         GL_CullFace(r_refdef.view.cullface_back);
1390                         R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_ALWAYS, 128, 255);
1391                 }
1392                 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
1393                 {
1394                         // decrement stencil if backface is behind depthbuffer
1395                         GL_CullFace(r_refdef.view.cullface_front);
1396                         R_SetStencil(true, 255, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, 128, 255);
1397                         R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1398                         // increment stencil if frontface is behind depthbuffer
1399                         GL_CullFace(r_refdef.view.cullface_back);
1400                         R_SetStencil(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_ALWAYS, 128, 255);
1401                 }
1402                 R_Mesh_PrepareVertices_Vertex3f(outverts, shadowvertex3f, NULL);
1403                 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1404         }
1405 }
1406
1407 int R_Shadow_CalcTriangleSideMask(const vec3_t p1, const vec3_t p2, const vec3_t p3, float bias)
1408 {
1409     // p1, p2, p3 are in the cubemap's local coordinate system
1410     // bias = border/(size - border)
1411         int mask = 0x3F;
1412
1413     float dp1 = p1[0] + p1[1], dn1 = p1[0] - p1[1], ap1 = fabs(dp1), an1 = fabs(dn1),
1414           dp2 = p2[0] + p2[1], dn2 = p2[0] - p2[1], ap2 = fabs(dp2), an2 = fabs(dn2),
1415           dp3 = p3[0] + p3[1], dn3 = p3[0] - p3[1], ap3 = fabs(dp3), an3 = fabs(dn3);
1416         if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1417         mask &= (3<<4)
1418                         | (dp1 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1419                         | (dp2 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1420                         | (dp3 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1421     if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1422         mask &= (3<<4)
1423             | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1424             | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))            
1425             | (dn3 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1426
1427     dp1 = p1[1] + p1[2], dn1 = p1[1] - p1[2], ap1 = fabs(dp1), an1 = fabs(dn1),
1428     dp2 = p2[1] + p2[2], dn2 = p2[1] - p2[2], ap2 = fabs(dp2), an2 = fabs(dn2),
1429     dp3 = p3[1] + p3[2], dn3 = p3[1] - p3[2], ap3 = fabs(dp3), an3 = fabs(dn3);
1430     if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1431         mask &= (3<<0)
1432             | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))
1433             | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))            
1434             | (dp3 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1435     if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1436         mask &= (3<<0)
1437             | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1438             | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1439             | (dn3 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1440
1441     dp1 = p1[2] + p1[0], dn1 = p1[2] - p1[0], ap1 = fabs(dp1), an1 = fabs(dn1),
1442     dp2 = p2[2] + p2[0], dn2 = p2[2] - p2[0], ap2 = fabs(dp2), an2 = fabs(dn2),
1443     dp3 = p3[2] + p3[0], dn3 = p3[2] - p3[0], ap3 = fabs(dp3), an3 = fabs(dn3);
1444     if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1445         mask &= (3<<2)
1446             | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1447             | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1448             | (dp3 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1449     if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1450         mask &= (3<<2)
1451             | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1452             | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1453             | (dn3 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1454
1455         return mask;
1456 }
1457
1458 int R_Shadow_CalcBBoxSideMask(const vec3_t mins, const vec3_t maxs, const matrix4x4_t *worldtolight, const matrix4x4_t *radiustolight, float bias)
1459 {
1460         vec3_t center, radius, lightcenter, lightradius, pmin, pmax;
1461         float dp1, dn1, ap1, an1, dp2, dn2, ap2, an2;
1462         int mask = 0x3F;
1463
1464         VectorSubtract(maxs, mins, radius);
1465     VectorScale(radius, 0.5f, radius);
1466     VectorAdd(mins, radius, center);
1467     Matrix4x4_Transform(worldtolight, center, lightcenter);
1468         Matrix4x4_Transform3x3(radiustolight, radius, lightradius);
1469         VectorSubtract(lightcenter, lightradius, pmin);
1470         VectorAdd(lightcenter, lightradius, pmax);
1471
1472     dp1 = pmax[0] + pmax[1], dn1 = pmax[0] - pmin[1], ap1 = fabs(dp1), an1 = fabs(dn1),
1473     dp2 = pmin[0] + pmin[1], dn2 = pmin[0] - pmax[1], ap2 = fabs(dp2), an2 = fabs(dn2);
1474     if(ap1 > bias*an1 && ap2 > bias*an2)
1475         mask &= (3<<4)
1476             | (dp1 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1477             | (dp2 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1478     if(an1 > bias*ap1 && an2 > bias*ap2)
1479         mask &= (3<<4)
1480             | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1481             | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1482
1483     dp1 = pmax[1] + pmax[2], dn1 = pmax[1] - pmin[2], ap1 = fabs(dp1), an1 = fabs(dn1),
1484     dp2 = pmin[1] + pmin[2], dn2 = pmin[1] - pmax[2], ap2 = fabs(dp2), an2 = fabs(dn2);
1485     if(ap1 > bias*an1 && ap2 > bias*an2)
1486         mask &= (3<<0)
1487             | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))
1488             | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1489     if(an1 > bias*ap1 && an2 > bias*ap2)
1490         mask &= (3<<0)
1491             | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1492             | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1493
1494     dp1 = pmax[2] + pmax[0], dn1 = pmax[2] - pmin[0], ap1 = fabs(dp1), an1 = fabs(dn1),
1495     dp2 = pmin[2] + pmin[0], dn2 = pmin[2] - pmax[0], ap2 = fabs(dp2), an2 = fabs(dn2);
1496     if(ap1 > bias*an1 && ap2 > bias*an2)
1497         mask &= (3<<2)
1498             | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1499             | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1500     if(an1 > bias*ap1 && an2 > bias*ap2)
1501         mask &= (3<<2)
1502             | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1503             | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1504
1505     return mask;
1506 }
1507
1508 #define R_Shadow_CalcEntitySideMask(ent, worldtolight, radiustolight, bias) R_Shadow_CalcBBoxSideMask((ent)->mins, (ent)->maxs, worldtolight, radiustolight, bias)
1509
1510 int R_Shadow_CalcSphereSideMask(const vec3_t p, float radius, float bias)
1511 {
1512     // p is in the cubemap's local coordinate system
1513     // bias = border/(size - border)
1514     float dxyp = p[0] + p[1], dxyn = p[0] - p[1], axyp = fabs(dxyp), axyn = fabs(dxyn);
1515     float dyzp = p[1] + p[2], dyzn = p[1] - p[2], ayzp = fabs(dyzp), ayzn = fabs(dyzn);
1516     float dzxp = p[2] + p[0], dzxn = p[2] - p[0], azxp = fabs(dzxp), azxn = fabs(dzxn);
1517     int mask = 0x3F;
1518     if(axyp > bias*axyn + radius) mask &= dxyp < 0 ? ~((1<<0)|(1<<2)) : ~((2<<0)|(2<<2));
1519     if(axyn > bias*axyp + radius) mask &= dxyn < 0 ? ~((1<<0)|(2<<2)) : ~((2<<0)|(1<<2));
1520     if(ayzp > bias*ayzn + radius) mask &= dyzp < 0 ? ~((1<<2)|(1<<4)) : ~((2<<2)|(2<<4));
1521     if(ayzn > bias*ayzp + radius) mask &= dyzn < 0 ? ~((1<<2)|(2<<4)) : ~((2<<2)|(1<<4));
1522     if(azxp > bias*azxn + radius) mask &= dzxp < 0 ? ~((1<<4)|(1<<0)) : ~((2<<4)|(2<<0));
1523     if(azxn > bias*azxp + radius) mask &= dzxn < 0 ? ~((1<<4)|(2<<0)) : ~((2<<4)|(1<<0));
1524     return mask;
1525 }
1526
1527 int R_Shadow_CullFrustumSides(rtlight_t *rtlight, float size, float border)
1528 {
1529         int i;
1530         vec3_t p, n;
1531         int sides = 0x3F, masks[6] = { 3<<4, 3<<4, 3<<0, 3<<0, 3<<2, 3<<2 };
1532         float scale = (size - 2*border)/size, len;
1533         float bias = border / (float)(size - border), dp, dn, ap, an;
1534         // check if cone enclosing side would cross frustum plane 
1535         scale = 2 / (scale*scale + 2);
1536         for (i = 0;i < 5;i++)
1537         {
1538                 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) > -0.03125)
1539                         continue;
1540                 Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[i].normal, n);
1541                 len = scale*VectorLength2(n);
1542                 if(n[0]*n[0] > len) sides &= n[0] < 0 ? ~(1<<0) : ~(2 << 0);
1543                 if(n[1]*n[1] > len) sides &= n[1] < 0 ? ~(1<<2) : ~(2 << 2);
1544                 if(n[2]*n[2] > len) sides &= n[2] < 0 ? ~(1<<4) : ~(2 << 4);
1545         }
1546         if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[4]) >= r_refdef.farclip - r_refdef.nearclip + 0.03125)
1547         {
1548         Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[4].normal, n);
1549         len = scale*VectorLength(n);
1550                 if(n[0]*n[0] > len) sides &= n[0] >= 0 ? ~(1<<0) : ~(2 << 0);
1551                 if(n[1]*n[1] > len) sides &= n[1] >= 0 ? ~(1<<2) : ~(2 << 2);
1552                 if(n[2]*n[2] > len) sides &= n[2] >= 0 ? ~(1<<4) : ~(2 << 4);
1553         }
1554         // this next test usually clips off more sides than the former, but occasionally clips fewer/different ones, so do both and combine results
1555         // check if frustum corners/origin cross plane sides
1556 #if 1
1557     // infinite version, assumes frustum corners merely give direction and extend to infinite distance
1558     Matrix4x4_Transform(&rtlight->matrix_worldtolight, r_refdef.view.origin, p);
1559     dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn);
1560     masks[0] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1561     masks[1] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1562     dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn);
1563     masks[2] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1564     masks[3] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1565     dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn);
1566     masks[4] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1567     masks[5] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1568     for (i = 0;i < 4;i++)
1569     {
1570         Matrix4x4_Transform(&rtlight->matrix_worldtolight, r_refdef.view.frustumcorner[i], n);
1571         VectorSubtract(n, p, n);
1572         dp = n[0] + n[1], dn = n[0] - n[1], ap = fabs(dp), an = fabs(dn);
1573         if(ap > 0) masks[0] |= dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2);
1574         if(an > 0) masks[1] |= dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2);
1575         dp = n[1] + n[2], dn = n[1] - n[2], ap = fabs(dp), an = fabs(dn);
1576         if(ap > 0) masks[2] |= dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4);
1577         if(an > 0) masks[3] |= dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4);
1578         dp = n[2] + n[0], dn = n[2] - n[0], ap = fabs(dp), an = fabs(dn);
1579         if(ap > 0) masks[4] |= dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0);
1580         if(an > 0) masks[5] |= dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0);
1581     }
1582 #else
1583     // finite version, assumes corners are a finite distance from origin dependent on far plane
1584         for (i = 0;i < 5;i++)
1585         {
1586                 Matrix4x4_Transform(&rtlight->matrix_worldtolight, !i ? r_refdef.view.origin : r_refdef.view.frustumcorner[i-1], p);
1587                 dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn);
1588                 masks[0] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1589                 masks[1] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1590                 dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn);
1591                 masks[2] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1592                 masks[3] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1593                 dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn);
1594                 masks[4] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1595                 masks[5] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1596         }
1597 #endif
1598         return sides & masks[0] & masks[1] & masks[2] & masks[3] & masks[4] & masks[5];
1599 }
1600
1601 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)
1602 {
1603         int t, tend;
1604         const int *e;
1605         const float *v[3];
1606         float normal[3];
1607         vec3_t p[3];
1608         float bias;
1609         int mask, surfacemask = 0;
1610         if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1611                 return 0;
1612         bias = r_shadow_shadowmapborder / (float)(r_shadow_shadowmapmaxsize - r_shadow_shadowmapborder);
1613         tend = firsttriangle + numtris;
1614         if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1615         {
1616                 // surface box entirely inside light box, no box cull
1617                 if (projectdirection)
1618                 {
1619                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1620                         {
1621                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1622                                 TriangleNormal(v[0], v[1], v[2], normal);
1623                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1624                                 {
1625                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1626                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1627                                         surfacemask |= mask;
1628                                         if(totals)
1629                                         {
1630                                                 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;
1631                                                 shadowsides[numshadowsides] = mask;
1632                                                 shadowsideslist[numshadowsides++] = t;
1633                                         }
1634                                 }
1635                         }
1636                 }
1637                 else
1638                 {
1639                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1640                         {
1641                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3,     v[2] = invertex3f + e[2] * 3;
1642                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2]))
1643                                 {
1644                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1645                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1646                                         surfacemask |= mask;
1647                                         if(totals)
1648                                         {
1649                                                 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;
1650                                                 shadowsides[numshadowsides] = mask;
1651                                                 shadowsideslist[numshadowsides++] = t;
1652                                         }
1653                                 }
1654                         }
1655                 }
1656         }
1657         else
1658         {
1659                 // surface box not entirely inside light box, cull each triangle
1660                 if (projectdirection)
1661                 {
1662                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1663                         {
1664                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3,     v[2] = invertex3f + e[2] * 3;
1665                                 TriangleNormal(v[0], v[1], v[2], normal);
1666                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1667                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1668                                 {
1669                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1670                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1671                                         surfacemask |= mask;
1672                                         if(totals)
1673                                         {
1674                                                 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;
1675                                                 shadowsides[numshadowsides] = mask;
1676                                                 shadowsideslist[numshadowsides++] = t;
1677                                         }
1678                                 }
1679                         }
1680                 }
1681                 else
1682                 {
1683                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1684                         {
1685                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1686                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1687                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1688                                 {
1689                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1690                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1691                                         surfacemask |= mask;
1692                                         if(totals)
1693                                         {
1694                                                 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;
1695                                                 shadowsides[numshadowsides] = mask;
1696                                                 shadowsideslist[numshadowsides++] = t;
1697                                         }
1698                                 }
1699                         }
1700                 }
1701         }
1702         return surfacemask;
1703 }
1704
1705 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)
1706 {
1707         int i, j, outtriangles = 0;
1708         int *outelement3i[6];
1709         if (!numverts || !numsidetris || !r_shadow_compilingrtlight)
1710                 return;
1711         outtriangles = sidetotals[0] + sidetotals[1] + sidetotals[2] + sidetotals[3] + sidetotals[4] + sidetotals[5];
1712         // make sure shadowelements is big enough for this mesh
1713         if (maxshadowtriangles < outtriangles)
1714                 R_Shadow_ResizeShadowArrays(0, outtriangles, 0, 1);
1715
1716         // compute the offset and size of the separate index lists for each cubemap side
1717         outtriangles = 0;
1718         for (i = 0;i < 6;i++)
1719         {
1720                 outelement3i[i] = shadowelements + outtriangles * 3;
1721                 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap->sideoffsets[i] = outtriangles;
1722                 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap->sidetotals[i] = sidetotals[i];
1723                 outtriangles += sidetotals[i];
1724         }
1725
1726         // gather up the (sparse) triangles into separate index lists for each cubemap side
1727         for (i = 0;i < numsidetris;i++)
1728         {
1729                 const int *element = elements + sidetris[i] * 3;
1730                 for (j = 0;j < 6;j++)
1731                 {
1732                         if (sides[i] & (1 << j))
1733                         {
1734                                 outelement3i[j][0] = element[0];
1735                                 outelement3i[j][1] = element[1];
1736                                 outelement3i[j][2] = element[2];
1737                                 outelement3i[j] += 3;
1738                         }
1739                 }
1740         }
1741                         
1742         Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap, NULL, NULL, NULL, vertex3f, NULL, NULL, NULL, NULL, outtriangles, shadowelements);
1743 }
1744
1745 static void R_Shadow_MakeTextures_MakeCorona(void)
1746 {
1747         float dx, dy;
1748         int x, y, a;
1749         unsigned char pixels[32][32][4];
1750         for (y = 0;y < 32;y++)
1751         {
1752                 dy = (y - 15.5f) * (1.0f / 16.0f);
1753                 for (x = 0;x < 32;x++)
1754                 {
1755                         dx = (x - 15.5f) * (1.0f / 16.0f);
1756                         a = (int)(((1.0f / (dx * dx + dy * dy + 0.2f)) - (1.0f / (1.0f + 0.2))) * 32.0f / (1.0f / (1.0f + 0.2)));
1757                         a = bound(0, a, 255);
1758                         pixels[y][x][0] = a;
1759                         pixels[y][x][1] = a;
1760                         pixels[y][x][2] = a;
1761                         pixels[y][x][3] = 255;
1762                 }
1763         }
1764         r_shadow_lightcorona = R_SkinFrame_LoadInternalBGRA("lightcorona", TEXF_FORCELINEAR, &pixels[0][0][0], 32, 32, false);
1765 }
1766
1767 static unsigned int R_Shadow_MakeTextures_SamplePoint(float x, float y, float z)
1768 {
1769         float dist = sqrt(x*x+y*y+z*z);
1770         float intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1771         // note this code could suffer byte order issues except that it is multiplying by an integer that reads the same both ways
1772         return (unsigned char)bound(0, intensity * 256.0f, 255) * 0x01010101;
1773 }
1774
1775 static void R_Shadow_MakeTextures(void)
1776 {
1777         int x, y, z;
1778         float intensity, dist;
1779         unsigned int *data;
1780         R_Shadow_FreeShadowMaps();
1781         R_FreeTexturePool(&r_shadow_texturepool);
1782         r_shadow_texturepool = R_AllocTexturePool();
1783         r_shadow_attenlinearscale = r_shadow_lightattenuationlinearscale.value;
1784         r_shadow_attendividebias = r_shadow_lightattenuationdividebias.value;
1785         data = (unsigned int *)Mem_Alloc(tempmempool, max(max(ATTEN3DSIZE*ATTEN3DSIZE*ATTEN3DSIZE, ATTEN2DSIZE*ATTEN2DSIZE), ATTEN1DSIZE) * 4);
1786         // the table includes one additional value to avoid the need to clamp indexing due to minor math errors
1787         for (x = 0;x <= ATTENTABLESIZE;x++)
1788         {
1789                 dist = (x + 0.5f) * (1.0f / ATTENTABLESIZE) * (1.0f / 0.9375);
1790                 intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1791                 r_shadow_attentable[x] = bound(0, intensity, 1);
1792         }
1793         // 1D gradient texture
1794         for (x = 0;x < ATTEN1DSIZE;x++)
1795                 data[x] = R_Shadow_MakeTextures_SamplePoint((x + 0.5f) * (1.0f / ATTEN1DSIZE) * (1.0f / 0.9375), 0, 0);
1796         r_shadow_attenuationgradienttexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation1d", ATTEN1DSIZE, 1, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1797         // 2D circle texture
1798         for (y = 0;y < ATTEN2DSIZE;y++)
1799                 for (x = 0;x < ATTEN2DSIZE;x++)
1800                         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);
1801         r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1802         // 3D sphere texture
1803         if (r_shadow_texture3d.integer && vid.support.ext_texture_3d)
1804         {
1805                 for (z = 0;z < ATTEN3DSIZE;z++)
1806                         for (y = 0;y < ATTEN3DSIZE;y++)
1807                                 for (x = 0;x < ATTEN3DSIZE;x++)
1808                                         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));
1809                 r_shadow_attenuation3dtexture = R_LoadTexture3D(r_shadow_texturepool, "attenuation3d", ATTEN3DSIZE, ATTEN3DSIZE, ATTEN3DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1810         }
1811         else
1812                 r_shadow_attenuation3dtexture = NULL;
1813         Mem_Free(data);
1814
1815         R_Shadow_MakeTextures_MakeCorona();
1816
1817         // Editor light sprites
1818         r_editlights_sprcursor = R_SkinFrame_LoadInternal8bit("gfx/editlights/cursor", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1819         "................"
1820         ".3............3."
1821         "..5...2332...5.."
1822         "...7.3....3.7..."
1823         "....7......7...."
1824         "...3.7....7.3..."
1825         "..2...7..7...2.."
1826         "..3..........3.."
1827         "..3..........3.."
1828         "..2...7..7...2.."
1829         "...3.7....7.3..."
1830         "....7......7...."
1831         "...7.3....3.7..."
1832         "..5...2332...5.."
1833         ".3............3."
1834         "................"
1835         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1836         r_editlights_sprlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/light", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1837         "................"
1838         "................"
1839         "......1111......"
1840         "....11233211...."
1841         "...1234554321..."
1842         "...1356776531..."
1843         "..124677776421.."
1844         "..135777777531.."
1845         "..135777777531.."
1846         "..124677776421.."
1847         "...1356776531..."
1848         "...1234554321..."
1849         "....11233211...."
1850         "......1111......"
1851         "................"
1852         "................"
1853         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1854         r_editlights_sprnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/noshadow", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1855         "................"
1856         "................"
1857         "......1111......"
1858         "....11233211...."
1859         "...1234554321..."
1860         "...1356226531..."
1861         "..12462..26421.."
1862         "..1352....2531.."
1863         "..1352....2531.."
1864         "..12462..26421.."
1865         "...1356226531..."
1866         "...1234554321..."
1867         "....11233211...."
1868         "......1111......"
1869         "................"
1870         "................"
1871         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1872         r_editlights_sprcubemaplight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemaplight", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1873         "................"
1874         "................"
1875         "......2772......"
1876         "....27755772...."
1877         "..277533335772.."
1878         "..753333333357.."
1879         "..777533335777.."
1880         "..735775577537.."
1881         "..733357753337.."
1882         "..733337733337.."
1883         "..753337733357.."
1884         "..277537735772.."
1885         "....27777772...."
1886         "......2772......"
1887         "................"
1888         "................"
1889         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1890         r_editlights_sprcubemapnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemapnoshadowlight", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1891         "................"
1892         "................"
1893         "......2772......"
1894         "....27722772...."
1895         "..2772....2772.."
1896         "..72........27.."
1897         "..7772....2777.."
1898         "..7.27722772.7.."
1899         "..7...2772...7.."
1900         "..7....77....7.."
1901         "..72...77...27.."
1902         "..2772.77.2772.."
1903         "....27777772...."
1904         "......2772......"
1905         "................"
1906         "................"
1907         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1908         r_editlights_sprselection = R_SkinFrame_LoadInternal8bit("gfx/editlights/selection", TEXF_ALPHA | TEXF_CLAMP, (unsigned char *)
1909         "................"
1910         ".777752..257777."
1911         ".742........247."
1912         ".72..........27."
1913         ".7............7."
1914         ".5............5."
1915         ".2............2."
1916         "................"
1917         "................"
1918         ".2............2."
1919         ".5............5."
1920         ".7............7."
1921         ".72..........27."
1922         ".742........247."
1923         ".777752..257777."
1924         "................"
1925         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1926 }
1927
1928 void R_Shadow_ValidateCvars(void)
1929 {
1930         if (r_shadow_texture3d.integer && !vid.support.ext_texture_3d)
1931                 Cvar_SetValueQuick(&r_shadow_texture3d, 0);
1932         if (gl_ext_separatestencil.integer && !vid.support.ati_separate_stencil)
1933                 Cvar_SetValueQuick(&gl_ext_separatestencil, 0);
1934         if (gl_ext_stenciltwoside.integer && !vid.support.ext_stencil_two_side)
1935                 Cvar_SetValueQuick(&gl_ext_stenciltwoside, 0);
1936 }
1937
1938 void R_Shadow_RenderMode_Begin(void)
1939 {
1940 #if 0
1941         GLint drawbuffer;
1942         GLint readbuffer;
1943 #endif
1944         R_Shadow_ValidateCvars();
1945
1946         if (!r_shadow_attenuation2dtexture
1947          || (!r_shadow_attenuation3dtexture && r_shadow_texture3d.integer)
1948          || r_shadow_lightattenuationdividebias.value != r_shadow_attendividebias
1949          || r_shadow_lightattenuationlinearscale.value != r_shadow_attenlinearscale)
1950                 R_Shadow_MakeTextures();
1951
1952         CHECKGLERROR
1953         R_Mesh_ResetTextureState();
1954         GL_BlendFunc(GL_ONE, GL_ZERO);
1955         GL_DepthRange(0, 1);
1956         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
1957         GL_DepthTest(true);
1958         GL_DepthMask(false);
1959         GL_Color(0, 0, 0, 1);
1960         GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
1961         
1962         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
1963
1964         if (gl_ext_separatestencil.integer && vid.support.ati_separate_stencil)
1965         {
1966                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL;
1967                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL;
1968         }
1969         else if (gl_ext_stenciltwoside.integer && vid.support.ext_stencil_two_side)
1970         {
1971                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE;
1972                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE;
1973         }
1974         else
1975         {
1976                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCIL;
1977                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCIL;
1978         }
1979
1980         switch(vid.renderpath)
1981         {
1982         case RENDERPATH_GL20:
1983         case RENDERPATH_D3D9:
1984         case RENDERPATH_D3D10:
1985         case RENDERPATH_D3D11:
1986         case RENDERPATH_SOFT:
1987         case RENDERPATH_GLES2:
1988                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_GLSL;
1989                 break;
1990         case RENDERPATH_GL11:
1991         case RENDERPATH_GL13:
1992         case RENDERPATH_GLES1:
1993                 if (r_textureunits.integer >= 2 && vid.texunits >= 2 && r_shadow_texture3d.integer && r_shadow_attenuation3dtexture)
1994                         r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN;
1995                 else if (r_textureunits.integer >= 3 && vid.texunits >= 3)
1996                         r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN;
1997                 else if (r_textureunits.integer >= 2 && vid.texunits >= 2)
1998                         r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN;
1999                 else
2000                         r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX;
2001                 break;
2002         }
2003
2004         CHECKGLERROR
2005 #if 0
2006         qglGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);CHECKGLERROR
2007         qglGetIntegerv(GL_READ_BUFFER, &readbuffer);CHECKGLERROR
2008         r_shadow_drawbuffer = drawbuffer;
2009         r_shadow_readbuffer = readbuffer;
2010 #endif
2011         r_shadow_cullface_front = r_refdef.view.cullface_front;
2012         r_shadow_cullface_back = r_refdef.view.cullface_back;
2013 }
2014
2015 void R_Shadow_RenderMode_ActiveLight(const rtlight_t *rtlight)
2016 {
2017         rsurface.rtlight = rtlight;
2018 }
2019
2020 void R_Shadow_RenderMode_Reset(void)
2021 {
2022         R_Mesh_SetMainRenderTargets();
2023         R_SetViewport(&r_refdef.view.viewport);
2024         GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
2025         R_Mesh_ResetTextureState();
2026         GL_DepthRange(0, 1);
2027         GL_DepthTest(true);
2028         GL_DepthMask(false);
2029         GL_DepthFunc(GL_LEQUAL);
2030         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
2031         r_refdef.view.cullface_front = r_shadow_cullface_front;
2032         r_refdef.view.cullface_back = r_shadow_cullface_back;
2033         GL_CullFace(r_refdef.view.cullface_back);
2034         GL_Color(1, 1, 1, 1);
2035         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
2036         GL_BlendFunc(GL_ONE, GL_ZERO);
2037         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
2038         r_shadow_usingshadowmap2d = false;
2039         r_shadow_usingshadowmaportho = false;
2040         R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
2041 }
2042
2043 void R_Shadow_ClearStencil(void)
2044 {
2045         GL_Clear(GL_STENCIL_BUFFER_BIT, NULL, 1.0f, 128);
2046         r_refdef.stats.lights_clears++;
2047 }
2048
2049 void R_Shadow_RenderMode_StencilShadowVolumes(qboolean zpass)
2050 {
2051         r_shadow_rendermode_t mode = zpass ? r_shadow_shadowingrendermode_zpass : r_shadow_shadowingrendermode_zfail;
2052         if (r_shadow_rendermode == mode)
2053                 return;
2054         R_Shadow_RenderMode_Reset();
2055         GL_DepthFunc(GL_LESS);
2056         GL_ColorMask(0, 0, 0, 0);
2057         GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
2058         GL_CullFace(GL_NONE);
2059         R_SetupShader_DepthOrShadow();
2060         r_shadow_rendermode = mode;
2061         switch(mode)
2062         {
2063         default:
2064                 break;
2065         case R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE:
2066         case R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL:
2067                 R_SetStencilSeparate(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, GL_ALWAYS, 128, 255);
2068                 break;
2069         case R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE:
2070         case R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL:
2071                 R_SetStencilSeparate(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, GL_ALWAYS, 128, 255);
2072                 break;
2073         }
2074 }
2075
2076 static void R_Shadow_MakeVSDCT(void)
2077 {
2078         // maps to a 2x3 texture rectangle with normalized coordinates
2079         // +-
2080         // XX
2081         // YY
2082         // ZZ
2083         // stores abs(dir.xy), offset.xy/2.5
2084         unsigned char data[4*6] =
2085         {
2086                 255, 0, 0x33, 0x33, // +X: <1, 0>, <0.5, 0.5>
2087                 255, 0, 0x99, 0x33, // -X: <1, 0>, <1.5, 0.5>
2088                 0, 255, 0x33, 0x99, // +Y: <0, 1>, <0.5, 1.5>
2089                 0, 255, 0x99, 0x99, // -Y: <0, 1>, <1.5, 1.5>
2090                 0,   0, 0x33, 0xFF, // +Z: <0, 0>, <0.5, 2.5>
2091                 0,   0, 0x99, 0xFF, // -Z: <0, 0>, <1.5, 2.5>
2092         };
2093         r_shadow_shadowmapvsdcttexture = R_LoadTextureCubeMap(r_shadow_texturepool, "shadowmapvsdct", 1, data, TEXTYPE_RGBA, TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, -1, NULL);
2094 }
2095
2096 static void R_Shadow_MakeShadowMap(int side, int size)
2097 {
2098         switch (r_shadow_shadowmode)
2099         {
2100         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
2101                 if (r_shadow_shadowmap2dtexture) return;
2102                 r_shadow_shadowmap2dtexture = R_LoadTextureShadowMap2D(r_shadow_texturepool, "shadowmap", size*2, size*(vid.support.arb_texture_non_power_of_two ? 3 : 4), r_shadow_shadowmapdepthbits, r_shadow_shadowmapsampler);
2103                 r_shadow_shadowmap2dcolortexture = NULL;
2104                 switch(vid.renderpath)
2105                 {
2106 #ifdef SUPPORTD3D
2107                 case RENDERPATH_D3D9:
2108                         r_shadow_shadowmap2dcolortexture = R_LoadTexture2D(r_shadow_texturepool, "shadowmaprendertarget", size*2, size*(vid.support.arb_texture_non_power_of_two ? 3 : 4), NULL, TEXTYPE_BGRA, TEXF_RENDERTARGET | TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, -1, NULL);
2109                         r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2dtexture, r_shadow_shadowmap2dcolortexture, NULL, NULL, NULL);
2110                         break;
2111 #endif
2112                 default:
2113                         r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2dtexture, NULL, NULL, NULL, NULL);
2114                         break;
2115                 }
2116                 break;
2117         default:
2118                 return;
2119         }
2120
2121         // render depth into the fbo, do not render color at all
2122         // validate the fbo now
2123         if (qglDrawBuffer)
2124         {
2125                 int status;
2126                 qglDrawBuffer(GL_NONE);CHECKGLERROR
2127                 qglReadBuffer(GL_NONE);CHECKGLERROR
2128                 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
2129                 if (status != GL_FRAMEBUFFER_COMPLETE_EXT && (r_shadow_shadowmapping.integer || r_shadow_deferred.integer))
2130                 {
2131                         Con_Printf("R_Shadow_MakeShadowMap: glCheckFramebufferStatusEXT returned %i\n", status);
2132                         Cvar_SetValueQuick(&r_shadow_shadowmapping, 0);
2133                         Cvar_SetValueQuick(&r_shadow_deferred, 0);
2134                 }
2135         }
2136 }
2137
2138 void R_Shadow_RenderMode_ShadowMap(int side, int clear, int size)
2139 {
2140         float nearclip, farclip, bias;
2141         r_viewport_t viewport;
2142         int flipped;
2143         GLuint fbo = 0;
2144         float clearcolor[4];
2145         nearclip = r_shadow_shadowmapping_nearclip.value / rsurface.rtlight->radius;
2146         farclip = 1.0f;
2147         bias = r_shadow_shadowmapping_bias.value * nearclip * (1024.0f / size);// * rsurface.rtlight->radius;
2148         r_shadow_shadowmap_parameters[1] = -nearclip * farclip / (farclip - nearclip) - 0.5f * bias;
2149         r_shadow_shadowmap_parameters[3] = 0.5f + 0.5f * (farclip + nearclip) / (farclip - nearclip);
2150         r_shadow_shadowmapside = side;
2151         r_shadow_shadowmapsize = size;
2152
2153         r_shadow_shadowmap_parameters[0] = 0.5f * (size - r_shadow_shadowmapborder);
2154         r_shadow_shadowmap_parameters[2] = r_shadow_shadowmapvsdct ? 2.5f*size : size;
2155         R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapborder, nearclip, farclip, NULL);
2156         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAP2D) goto init_done;
2157
2158         // complex unrolled cube approach (more flexible)
2159         if (r_shadow_shadowmapvsdct && !r_shadow_shadowmapvsdcttexture)
2160                 R_Shadow_MakeVSDCT();
2161         if (!r_shadow_shadowmap2dtexture)
2162                 R_Shadow_MakeShadowMap(side, r_shadow_shadowmapmaxsize);
2163         if (r_shadow_shadowmap2dtexture) fbo = r_shadow_fbo2d;
2164         r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2dtexture);
2165         r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2dtexture);
2166         r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
2167
2168         R_Mesh_ResetTextureState();
2169         R_Shadow_RenderMode_Reset();
2170         R_Mesh_SetRenderTargets(fbo, r_shadow_shadowmap2dtexture, r_shadow_shadowmap2dcolortexture, NULL, NULL, NULL);
2171         R_SetupShader_DepthOrShadow();
2172         GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
2173         GL_DepthMask(true);
2174         GL_DepthTest(true);
2175
2176 init_done:
2177         R_SetViewport(&viewport);
2178         flipped = (side & 1) ^ (side >> 2);
2179         r_refdef.view.cullface_front = flipped ? r_shadow_cullface_back : r_shadow_cullface_front;
2180         r_refdef.view.cullface_back = flipped ? r_shadow_cullface_front : r_shadow_cullface_back;
2181         switch(vid.renderpath)
2182         {
2183         case RENDERPATH_GL11:
2184         case RENDERPATH_GL13:
2185         case RENDERPATH_GL20:
2186         case RENDERPATH_SOFT:
2187         case RENDERPATH_GLES1:
2188         case RENDERPATH_GLES2:
2189                 GL_CullFace(r_refdef.view.cullface_back);
2190                 // OpenGL lets us scissor larger than the viewport, so go ahead and clear all views at once
2191                 if ((clear & ((2 << side) - 1)) == (1 << side)) // only clear if the side is the first in the mask
2192                 {
2193                         // get tightest scissor rectangle that encloses all viewports in the clear mask
2194                         int x1 = clear & 0x15 ? 0 : size;
2195                         int x2 = clear & 0x2A ? 2 * size : size;
2196                         int y1 = clear & 0x03 ? 0 : (clear & 0xC ? size : 2 * size);
2197                         int y2 = clear & 0x30 ? 3 * size : (clear & 0xC ? 2 * size : size);
2198                         GL_Scissor(x1, y1, x2 - x1, y2 - y1);
2199                         GL_Clear(GL_DEPTH_BUFFER_BIT, NULL, 1.0f, 0);
2200                 }
2201                 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
2202                 break;
2203         case RENDERPATH_D3D9:
2204         case RENDERPATH_D3D10:
2205         case RENDERPATH_D3D11:
2206                 Vector4Set(clearcolor, 1,1,1,1);
2207                 // completely different meaning than in OpenGL path
2208                 r_shadow_shadowmap_parameters[1] = 0;
2209                 r_shadow_shadowmap_parameters[3] = -bias;
2210                 // we invert the cull mode because we flip the projection matrix
2211                 // NOTE: this actually does nothing because the DrawShadowMap code sets it to doublesided...
2212                 GL_CullFace(r_refdef.view.cullface_front);
2213                 // D3D considers it an error to use a scissor larger than the viewport...  clear just this view
2214                 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
2215                 if (r_shadow_shadowmapsampler)
2216                 {
2217                         GL_ColorMask(0,0,0,0);
2218                         if (clear)
2219                                 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
2220                 }
2221                 else
2222                 {
2223                         GL_ColorMask(1,1,1,1);
2224                         if (clear)
2225                                 GL_Clear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
2226                 }
2227                 break;
2228         }
2229 }
2230
2231 void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qboolean shadowmapping)
2232 {
2233         R_Mesh_ResetTextureState();
2234         R_Mesh_SetMainRenderTargets();
2235         if (transparent)
2236         {
2237                 r_shadow_lightscissor[0] = r_refdef.view.viewport.x;
2238                 r_shadow_lightscissor[1] = r_refdef.view.viewport.y;
2239                 r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
2240                 r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
2241         }
2242         R_Shadow_RenderMode_Reset();
2243         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2244         if (!transparent)
2245                 GL_DepthFunc(GL_EQUAL);
2246         // do global setup needed for the chosen lighting mode
2247         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
2248                 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0);
2249         r_shadow_usingshadowmap2d = shadowmapping;
2250         r_shadow_rendermode = r_shadow_lightingrendermode;
2251         // only draw light where this geometry was already rendered AND the
2252         // stencil is 128 (values other than this mean shadow)
2253         if (stenciltest)
2254                 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2255         else
2256                 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
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 // do global setup needed for the chosen lighting mode
2287         R_Shadow_RenderMode_Reset();
2288         r_shadow_rendermode = r_shadow_lightingrendermode;
2289         R_EntityMatrix(&identitymatrix);
2290         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2291         // only draw light where this geometry was already rendered AND the
2292         // stencil is 128 (values other than this mean shadow)
2293         R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2294         if (rsurface.rtlight->specularscale > 0 && r_shadow_gloss.integer > 0)
2295                 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
2296         else
2297                 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
2298
2299         r_shadow_usingshadowmap2d = shadowmapping;
2300
2301         // render the lighting
2302         R_SetupShader_DeferredLight(rsurface.rtlight);
2303         for (i = 0;i < 8;i++)
2304                 Matrix4x4_Transform(matrix, bboxpoints[i], vertex3f + i*3);
2305         GL_ColorMask(1,1,1,1);
2306         GL_DepthMask(false);
2307         GL_DepthRange(0, 1);
2308         GL_PolygonOffset(0, 0);
2309         GL_DepthTest(true);
2310         GL_DepthFunc(GL_GREATER);
2311         GL_CullFace(r_refdef.view.cullface_back);
2312         R_Mesh_PrepareVertices_Vertex3f(8, vertex3f, NULL);
2313         R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
2314 }
2315
2316 static void R_Shadow_UpdateBounceGridTexture(void)
2317 {
2318 #define MAXBOUNCEGRIDPARTICLESPERLIGHT 1048576
2319         dlight_t *light;
2320         int flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
2321         int bouncecount;
2322         int hitsupercontentsmask;
2323         int maxbounce;
2324         int numpixels;
2325         int resolution[3];
2326         int shootparticles;
2327         int shotparticles;
2328         int photoncount;
2329         int tex[3];
2330         trace_t cliptrace;
2331         //trace_t cliptrace2;
2332         //trace_t cliptrace3;
2333         unsigned char *pixel;
2334         unsigned char *pixels;
2335         float *highpixel;
2336         float *highpixels;
2337         unsigned int lightindex;
2338         unsigned int range;
2339         unsigned int range1;
2340         unsigned int range2;
2341         unsigned int seed = (unsigned int)(realtime * 1000.0f);
2342         vec3_t shotcolor;
2343         vec3_t baseshotcolor;
2344         vec3_t surfcolor;
2345         vec3_t clipend;
2346         vec3_t clipstart;
2347         vec3_t clipdiff;
2348         vec3_t ispacing;
2349         vec3_t maxs;
2350         vec3_t mins;
2351         vec3_t size;
2352         vec3_t spacing;
2353         vec3_t lightcolor;
2354         vec3_t steppos;
2355         vec3_t stepdelta;
2356         vec_t radius;
2357         vec_t s;
2358         vec_t lightintensity;
2359         vec_t photonscaling;
2360         vec_t photonresidual;
2361         float m[16];
2362         float texlerp[2][3];
2363         float splatcolor[32];
2364         float pixelweight[8];
2365         float w;
2366         int c[4];
2367         int pixelindex[8];
2368         int corner;
2369         int pixelsperband;
2370         int pixelband;
2371         int pixelbands;
2372         int numsteps;
2373         int step;
2374         int x, y, z;
2375         rtlight_t *rtlight;
2376         r_shadow_bouncegrid_settings_t settings;
2377         qboolean enable = r_shadow_bouncegrid.integer != 0 && r_refdef.scene.worldmodel;
2378         qboolean allowdirectionalshading = false;
2379         switch(vid.renderpath)
2380         {
2381         case RENDERPATH_GL20:
2382                 allowdirectionalshading = true;
2383                 if (!vid.support.ext_texture_3d)
2384                         return;
2385                 break;
2386         case RENDERPATH_GLES2:
2387                 // for performance reasons, do not use directional shading on GLES devices
2388                 if (!vid.support.ext_texture_3d)
2389                         return;
2390                 break;
2391                 // these renderpaths do not currently have the code to display the bouncegrid, so disable it on them...
2392         case RENDERPATH_GL11:
2393         case RENDERPATH_GL13:
2394         case RENDERPATH_GLES1:
2395         case RENDERPATH_SOFT:
2396         case RENDERPATH_D3D9:
2397         case RENDERPATH_D3D10:
2398         case RENDERPATH_D3D11:
2399                 return;
2400         }
2401
2402         r_shadow_bouncegridintensity = r_shadow_bouncegrid_intensity.value;
2403
2404         // see if there are really any lights to render...
2405         if (enable && r_shadow_bouncegrid_static.integer)
2406         {
2407                 enable = false;
2408                 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
2409                 for (lightindex = 0;lightindex < range;lightindex++)
2410                 {
2411                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2412                         if (!light || !(light->flags & flag))
2413                                 continue;
2414                         rtlight = &light->rtlight;
2415                         // when static, we skip styled lights because they tend to change...
2416                         if (rtlight->style > 0)
2417                                 continue;
2418                         VectorScale(rtlight->color, (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale), lightcolor);
2419                         if (!VectorLength2(lightcolor))
2420                                 continue;
2421                         enable = true;
2422                         break;
2423                 }
2424         }
2425
2426         if (!enable)
2427         {
2428                 if (r_shadow_bouncegridtexture)
2429                 {
2430                         R_FreeTexture(r_shadow_bouncegridtexture);
2431                         r_shadow_bouncegridtexture = NULL;
2432                 }
2433                 if (r_shadow_bouncegridpixels)
2434                         Mem_Free(r_shadow_bouncegridpixels);
2435                 r_shadow_bouncegridpixels = NULL;
2436                 if (r_shadow_bouncegridhighpixels)
2437                         Mem_Free(r_shadow_bouncegridhighpixels);
2438                 r_shadow_bouncegridhighpixels = NULL;
2439                 r_shadow_bouncegridnumpixels = 0;
2440                 r_shadow_bouncegriddirectional = false;
2441                 return;
2442         }
2443
2444         // build up a complete collection of the desired settings, so that memcmp can be used to compare parameters
2445         memset(&settings, 0, sizeof(settings));
2446         settings.staticmode                    = r_shadow_bouncegrid_static.integer != 0;
2447         settings.airstepmax                    = bound(1, r_shadow_bouncegrid_airstepmax.integer, 1048576);
2448         settings.airstepsize                   = bound(1.0f, r_shadow_bouncegrid_airstepsize.value, 1024.0f);
2449         settings.bounceanglediffuse            = r_shadow_bouncegrid_bounceanglediffuse.integer != 0;
2450         settings.directionalshading            = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_directionalshading.integer != 0 : r_shadow_bouncegrid_directionalshading.integer != 0) && allowdirectionalshading;
2451         settings.dlightparticlemultiplier      = r_shadow_bouncegrid_dlightparticlemultiplier.value;
2452         settings.hitmodels                     = r_shadow_bouncegrid_hitmodels.integer != 0;
2453         settings.includedirectlighting         = r_shadow_bouncegrid_includedirectlighting.integer != 0;
2454         settings.lightradiusscale              = r_shadow_bouncegrid_lightradiusscale.value;
2455         settings.maxbounce                     = r_shadow_bouncegrid_maxbounce.integer;
2456         settings.particlebounceintensity       = r_shadow_bouncegrid_particlebounceintensity.value;
2457         settings.particleintensity             = r_shadow_bouncegrid_particleintensity.value;
2458         settings.photons                       = r_shadow_bouncegrid_static.integer ? r_shadow_bouncegrid_static_photons.integer : r_shadow_bouncegrid_photons.integer;
2459         settings.spacing[0]                    = r_shadow_bouncegrid_spacingx.value;
2460         settings.spacing[1]                    = r_shadow_bouncegrid_spacingy.value;
2461         settings.spacing[2]                    = r_shadow_bouncegrid_spacingz.value;
2462         settings.stablerandom                  = r_shadow_bouncegrid_stablerandom.integer;
2463
2464         // bound the values for sanity
2465         settings.photons = bound(1, settings.photons, 1048576);
2466         settings.lightradiusscale = bound(0.0001f, settings.lightradiusscale, 1024.0f);
2467         settings.maxbounce = bound(0, settings.maxbounce, 16);
2468         settings.spacing[0] = bound(1, settings.spacing[0], 512);
2469         settings.spacing[1] = bound(1, settings.spacing[1], 512);
2470         settings.spacing[2] = bound(1, settings.spacing[2], 512);
2471
2472         // get the spacing values
2473         spacing[0] = settings.spacing[0];
2474         spacing[1] = settings.spacing[1];
2475         spacing[2] = settings.spacing[2];
2476         ispacing[0] = 1.0f / spacing[0];
2477         ispacing[1] = 1.0f / spacing[1];
2478         ispacing[2] = 1.0f / spacing[2];
2479
2480         // calculate texture size enclosing entire world bounds at the spacing
2481         VectorMA(r_refdef.scene.worldmodel->normalmins, -2.0f, spacing, mins);
2482         VectorMA(r_refdef.scene.worldmodel->normalmaxs, 2.0f, spacing, maxs);
2483         VectorSubtract(maxs, mins, size);
2484         // now we can calculate the resolution we want
2485         c[0] = (int)floor(size[0] / spacing[0] + 0.5f);
2486         c[1] = (int)floor(size[1] / spacing[1] + 0.5f);
2487         c[2] = (int)floor(size[2] / spacing[2] + 0.5f);
2488         // figure out the exact texture size (honoring power of 2 if required)
2489         c[0] = bound(4, c[0], (int)vid.maxtexturesize_3d);
2490         c[1] = bound(4, c[1], (int)vid.maxtexturesize_3d);
2491         c[2] = bound(4, c[2], (int)vid.maxtexturesize_3d);
2492         if (vid.support.arb_texture_non_power_of_two)
2493         {
2494                 resolution[0] = c[0];
2495                 resolution[1] = c[1];
2496                 resolution[2] = c[2];
2497         }
2498         else
2499         {
2500                 for (resolution[0] = 4;resolution[0] < c[0];resolution[0]*=2) ;
2501                 for (resolution[1] = 4;resolution[1] < c[1];resolution[1]*=2) ;
2502                 for (resolution[2] = 4;resolution[2] < c[2];resolution[2]*=2) ;
2503         }
2504         size[0] = spacing[0] * resolution[0];
2505         size[1] = spacing[1] * resolution[1];
2506         size[2] = spacing[2] * resolution[2];
2507
2508         // if dynamic we may or may not want to use the world bounds
2509         // if the dynamic size is smaller than the world bounds, use it instead
2510         if (!settings.staticmode && (r_shadow_bouncegrid_x.integer * r_shadow_bouncegrid_y.integer * r_shadow_bouncegrid_z.integer < resolution[0] * resolution[1] * resolution[2]))
2511         {
2512                 // we know the resolution we want
2513                 c[0] = r_shadow_bouncegrid_x.integer;
2514                 c[1] = r_shadow_bouncegrid_y.integer;
2515                 c[2] = r_shadow_bouncegrid_z.integer;
2516                 // now we can calculate the texture size (power of 2 if required)
2517                 c[0] = bound(4, c[0], (int)vid.maxtexturesize_3d);
2518                 c[1] = bound(4, c[1], (int)vid.maxtexturesize_3d);
2519                 c[2] = bound(4, c[2], (int)vid.maxtexturesize_3d);
2520                 if (vid.support.arb_texture_non_power_of_two)
2521                 {
2522                         resolution[0] = c[0];
2523                         resolution[1] = c[1];
2524                         resolution[2] = c[2];
2525                 }
2526                 else
2527                 {
2528                         for (resolution[0] = 4;resolution[0] < c[0];resolution[0]*=2) ;
2529                         for (resolution[1] = 4;resolution[1] < c[1];resolution[1]*=2) ;
2530                         for (resolution[2] = 4;resolution[2] < c[2];resolution[2]*=2) ;
2531                 }
2532                 size[0] = spacing[0] * resolution[0];
2533                 size[1] = spacing[1] * resolution[1];
2534                 size[2] = spacing[2] * resolution[2];
2535                 // center the rendering on the view
2536                 mins[0] = floor(r_refdef.view.origin[0] * ispacing[0] + 0.5f) * spacing[0] - 0.5f * size[0];
2537                 mins[1] = floor(r_refdef.view.origin[1] * ispacing[1] + 0.5f) * spacing[1] - 0.5f * size[1];
2538                 mins[2] = floor(r_refdef.view.origin[2] * ispacing[2] + 0.5f) * spacing[2] - 0.5f * size[2];
2539         }
2540
2541         // recalculate the maxs in case the resolution was not satisfactory
2542         VectorAdd(mins, size, maxs);
2543
2544         // if all the settings seem identical to the previous update, return
2545         if (r_shadow_bouncegridtexture && (settings.staticmode || realtime < r_shadow_bouncegridtime + r_shadow_bouncegrid_updateinterval.value) && !memcmp(&r_shadow_bouncegridsettings, &settings, sizeof(settings)))
2546                 return;
2547
2548         // store the new settings
2549         r_shadow_bouncegridsettings = settings;
2550
2551         pixelbands = settings.directionalshading ? 8 : 1;
2552         pixelsperband = resolution[0]*resolution[1]*resolution[2];
2553         numpixels = pixelsperband*pixelbands;
2554
2555         // we're going to update the bouncegrid, update the matrix...
2556         memset(m, 0, sizeof(m));
2557         m[0] = 1.0f / size[0];
2558         m[3] = -mins[0] * m[0];
2559         m[5] = 1.0f / size[1];
2560         m[7] = -mins[1] * m[5];
2561         m[10] = 1.0f / size[2];
2562         m[11] = -mins[2] * m[10];
2563         m[15] = 1.0f;
2564         Matrix4x4_FromArrayFloatD3D(&r_shadow_bouncegridmatrix, m);
2565         // reallocate pixels for this update if needed...
2566         if (r_shadow_bouncegridnumpixels != numpixels || !r_shadow_bouncegridpixels || !r_shadow_bouncegridhighpixels)
2567         {
2568                 if (r_shadow_bouncegridtexture)
2569                 {
2570                         R_FreeTexture(r_shadow_bouncegridtexture);
2571                         r_shadow_bouncegridtexture = NULL;
2572                 }
2573                 r_shadow_bouncegridpixels = (unsigned char *)Mem_Realloc(r_main_mempool, r_shadow_bouncegridpixels, numpixels * sizeof(unsigned char[4]));
2574                 r_shadow_bouncegridhighpixels = (float *)Mem_Realloc(r_main_mempool, r_shadow_bouncegridhighpixels, numpixels * sizeof(float[4]));
2575         }
2576         r_shadow_bouncegridnumpixels = numpixels;
2577         pixels = r_shadow_bouncegridpixels;
2578         highpixels = r_shadow_bouncegridhighpixels;
2579         x = pixelsperband*4;
2580         for (pixelband = 0;pixelband < pixelbands;pixelband++)
2581         {
2582                 if (pixelband == 1)
2583                         memset(pixels + pixelband * x, 128, x);
2584                 else
2585                         memset(pixels + pixelband * x, 0, x);
2586         }
2587         memset(highpixels, 0, numpixels * sizeof(float[4]));
2588         // figure out what we want to interact with
2589         if (settings.hitmodels)
2590                 hitsupercontentsmask = SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY;// | SUPERCONTENTS_LIQUIDSMASK;
2591         else
2592                 hitsupercontentsmask = SUPERCONTENTS_SOLID;// | SUPERCONTENTS_LIQUIDSMASK;
2593         maxbounce = settings.maxbounce;
2594         // clear variables that produce warnings otherwise
2595         memset(splatcolor, 0, sizeof(splatcolor));
2596         // iterate world rtlights
2597         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
2598         range1 = settings.staticmode ? 0 : r_refdef.scene.numlights;
2599         range2 = range + range1;
2600         photoncount = 0;
2601         for (lightindex = 0;lightindex < range2;lightindex++)
2602         {
2603                 if (settings.staticmode)
2604                 {
2605                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2606                         if (!light || !(light->flags & flag))
2607                                 continue;
2608                         rtlight = &light->rtlight;
2609                         // when static, we skip styled lights because they tend to change...
2610                         if (rtlight->style > 0)
2611                                 continue;
2612                         VectorScale(rtlight->color, (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) * (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1), lightcolor);
2613                 }
2614                 else
2615                 {
2616                         if (lightindex < range)
2617                         {
2618                                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2619                                 rtlight = &light->rtlight;
2620                         }
2621                         else
2622                                 rtlight = r_refdef.scene.lights[lightindex - range];
2623                         // draw only visible lights (major speedup)
2624                         if (!rtlight->draw)
2625                                 continue;
2626                         VectorScale(rtlight->currentcolor, rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale, lightcolor);
2627                 }
2628                 if (!VectorLength2(lightcolor))
2629                         continue;
2630                 // shoot particles from this light
2631                 // use a calculation for the number of particles that will not
2632                 // vary with lightstyle, otherwise we get randomized particle
2633                 // distribution, the seeded random is only consistent for a
2634                 // consistent number of particles on this light...
2635                 radius = rtlight->radius * settings.lightradiusscale;
2636                 s = rtlight->radius;
2637                 lightintensity = VectorLength(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale);
2638                 if (lightindex >= range)
2639                         lightintensity *= settings.dlightparticlemultiplier;
2640                 photoncount += max(0.0f, lightintensity * s * s);
2641         }
2642         photonscaling = (float)settings.photons / max(1, photoncount);
2643         photonresidual = 0.0f;
2644         for (lightindex = 0;lightindex < range2;lightindex++)
2645         {
2646                 if (settings.staticmode)
2647                 {
2648                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2649                         if (!light || !(light->flags & flag))
2650                                 continue;
2651                         rtlight = &light->rtlight;
2652                         // when static, we skip styled lights because they tend to change...
2653                         if (rtlight->style > 0)
2654                                 continue;
2655                         VectorScale(rtlight->color, (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) * (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1), lightcolor);
2656                 }
2657                 else
2658                 {
2659                         if (lightindex < range)
2660                         {
2661                                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2662                                 rtlight = &light->rtlight;
2663                         }
2664                         else
2665                                 rtlight = r_refdef.scene.lights[lightindex - range];
2666                         // draw only visible lights (major speedup)
2667                         if (!rtlight->draw)
2668                                 continue;
2669                         VectorScale(rtlight->currentcolor, rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale, lightcolor);
2670                 }
2671                 if (!VectorLength2(lightcolor))
2672                         continue;
2673                 // shoot particles from this light
2674                 // use a calculation for the number of particles that will not
2675                 // vary with lightstyle, otherwise we get randomized particle
2676                 // distribution, the seeded random is only consistent for a
2677                 // consistent number of particles on this light...
2678                 radius = rtlight->radius * settings.lightradiusscale;
2679                 s = rtlight->radius;
2680                 lightintensity = VectorLength(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale);
2681                 if (lightindex >= range)
2682                         lightintensity *= settings.dlightparticlemultiplier;
2683                 photonresidual += lightintensity * s * s * photonscaling;
2684                 shootparticles = (int)bound(0, photonresidual, MAXBOUNCEGRIDPARTICLESPERLIGHT);
2685                 if (!shootparticles)
2686                         continue;
2687                 photonresidual -= shootparticles;
2688                 s = settings.particleintensity / shootparticles;
2689                 VectorScale(lightcolor, s, baseshotcolor);
2690                 if (VectorLength2(baseshotcolor) == 0.0f)
2691                         break;
2692                 r_refdef.stats.bouncegrid_lights++;
2693                 r_refdef.stats.bouncegrid_particles += shootparticles;
2694                 for (shotparticles = 0;shotparticles < shootparticles;shotparticles++)
2695                 {
2696                         if (settings.stablerandom > 0)
2697                                 seed = lightindex * 11937 + shotparticles;
2698                         VectorCopy(baseshotcolor, shotcolor);
2699                         VectorCopy(rtlight->shadoworigin, clipstart);
2700                         if (settings.stablerandom < 0)
2701                                 VectorRandom(clipend);
2702                         else
2703                                 VectorCheeseRandom(clipend);
2704                         VectorMA(clipstart, radius, clipend, clipend);
2705                         for (bouncecount = 0;;bouncecount++)
2706                         {
2707                                 r_refdef.stats.bouncegrid_traces++;
2708                                 //r_refdef.scene.worldmodel->TraceLineAgainstSurfaces(r_refdef.scene.worldmodel, NULL, NULL, &cliptrace, clipstart, clipend, hitsupercontentsmask);
2709                                 //r_refdef.scene.worldmodel->TraceLine(r_refdef.scene.worldmodel, NULL, NULL, &cliptrace2, clipstart, clipend, hitsupercontentsmask);
2710                                 if (settings.staticmode)
2711                                         Collision_ClipLineToWorld(&cliptrace, cl.worldmodel, clipstart, clipend, hitsupercontentsmask, true);
2712                                 else
2713                                         cliptrace = CL_TraceLine(clipstart, clipend, settings.hitmodels ? MOVE_HITMODEL : MOVE_NOMONSTERS, NULL, hitsupercontentsmask, true, false, NULL, true, true);
2714                                 if (bouncecount > 0 || settings.includedirectlighting)
2715                                 {
2716                                         // calculate second order spherical harmonics values (average, slopeX, slopeY, slopeZ)
2717                                         // accumulate average shotcolor
2718                                         w = VectorLength(shotcolor);
2719                                         splatcolor[ 0] = shotcolor[0];
2720                                         splatcolor[ 1] = shotcolor[1];
2721                                         splatcolor[ 2] = shotcolor[2];
2722                                         splatcolor[ 3] = 0.0f;
2723                                         if (pixelbands > 1)
2724                                         {
2725                                                 VectorSubtract(clipstart, cliptrace.endpos, clipdiff);
2726                                                 VectorNormalize(clipdiff);
2727                                                 // store bentnormal in case the shader has a use for it
2728                                                 splatcolor[ 4] = clipdiff[0] * w;
2729                                                 splatcolor[ 5] = clipdiff[1] * w;
2730                                                 splatcolor[ 6] = clipdiff[2] * w;
2731                                                 splatcolor[ 7] = w;
2732                                                 // accumulate directional contributions (+X, +Y, +Z, -X, -Y, -Z)
2733                                                 splatcolor[ 8] = shotcolor[0] * max(0.0f, clipdiff[0]);
2734                                                 splatcolor[ 9] = shotcolor[0] * max(0.0f, clipdiff[1]);
2735                                                 splatcolor[10] = shotcolor[0] * max(0.0f, clipdiff[2]);
2736                                                 splatcolor[11] = 0.0f;
2737                                                 splatcolor[12] = shotcolor[1] * max(0.0f, clipdiff[0]);
2738                                                 splatcolor[13] = shotcolor[1] * max(0.0f, clipdiff[1]);
2739                                                 splatcolor[14] = shotcolor[1] * max(0.0f, clipdiff[2]);
2740                                                 splatcolor[15] = 0.0f;
2741                                                 splatcolor[16] = shotcolor[2] * max(0.0f, clipdiff[0]);
2742                                                 splatcolor[17] = shotcolor[2] * max(0.0f, clipdiff[1]);
2743                                                 splatcolor[18] = shotcolor[2] * max(0.0f, clipdiff[2]);
2744                                                 splatcolor[19] = 0.0f;
2745                                                 splatcolor[20] = shotcolor[0] * max(0.0f, -clipdiff[0]);
2746                                                 splatcolor[21] = shotcolor[0] * max(0.0f, -clipdiff[1]);
2747                                                 splatcolor[22] = shotcolor[0] * max(0.0f, -clipdiff[2]);
2748                                                 splatcolor[23] = 0.0f;
2749                                                 splatcolor[24] = shotcolor[1] * max(0.0f, -clipdiff[0]);
2750                                                 splatcolor[25] = shotcolor[1] * max(0.0f, -clipdiff[1]);
2751                                                 splatcolor[26] = shotcolor[1] * max(0.0f, -clipdiff[2]);
2752                                                 splatcolor[27] = 0.0f;
2753                                                 splatcolor[28] = shotcolor[2] * max(0.0f, -clipdiff[0]);
2754                                                 splatcolor[29] = shotcolor[2] * max(0.0f, -clipdiff[1]);
2755                                                 splatcolor[30] = shotcolor[2] * max(0.0f, -clipdiff[2]);
2756                                                 splatcolor[31] = 0.0f;
2757                                         }
2758                                         // calculate the number of steps we need to traverse this distance
2759                                         VectorSubtract(cliptrace.endpos, clipstart, stepdelta);
2760                                         numsteps = (int)(VectorLength(stepdelta) / settings.airstepsize);
2761                                         numsteps = bound(1, numsteps, settings.airstepmax);
2762                                         w = 1.0f / numsteps;
2763                                         VectorScale(stepdelta, w, stepdelta);
2764                                         VectorMA(clipstart, 0.5f, stepdelta, steppos);
2765                                         if (settings.airstepmax == 1)
2766                                                 VectorCopy(cliptrace.endpos, steppos);
2767                                         for (step = 0;step < numsteps;step++)
2768                                         {
2769                                                 r_refdef.stats.bouncegrid_splats++;
2770                                                 // figure out which texture pixel this is in
2771                                                 texlerp[1][0] = ((steppos[0] - mins[0]) * ispacing[0]);
2772                                                 texlerp[1][1] = ((steppos[1] - mins[1]) * ispacing[1]);
2773                                                 texlerp[1][2] = ((steppos[2] - mins[2]) * ispacing[2]);
2774                                                 tex[0] = (int)floor(texlerp[1][0]);
2775                                                 tex[1] = (int)floor(texlerp[1][1]);
2776                                                 tex[2] = (int)floor(texlerp[1][2]);
2777                                                 if (tex[0] >= 1 && tex[1] >= 1 && tex[2] >= 1 && tex[0] < resolution[0] - 2 && tex[1] < resolution[1] - 2 && tex[2] < resolution[2] - 2)
2778                                                 {
2779                                                         // it is within bounds...  do the real work now
2780                                                         // calculate the lerp factors
2781                                                         texlerp[1][0] -= tex[0];
2782                                                         texlerp[1][1] -= tex[1];
2783                                                         texlerp[1][2] -= tex[2];
2784                                                         texlerp[0][0] = 1.0f - texlerp[1][0];
2785                                                         texlerp[0][1] = 1.0f - texlerp[1][1];
2786                                                         texlerp[0][2] = 1.0f - texlerp[1][2];
2787                                                         // calculate individual pixel indexes and weights
2788                                                         pixelindex[0] = (((tex[2]  )*resolution[1]+tex[1]  )*resolution[0]+tex[0]  );pixelweight[0] = (texlerp[0][0]*texlerp[0][1]*texlerp[0][2]);
2789                                                         pixelindex[1] = (((tex[2]  )*resolution[1]+tex[1]  )*resolution[0]+tex[0]+1);pixelweight[1] = (texlerp[1][0]*texlerp[0][1]*texlerp[0][2]);
2790                                                         pixelindex[2] = (((tex[2]  )*resolution[1]+tex[1]+1)*resolution[0]+tex[0]  );pixelweight[2] = (texlerp[0][0]*texlerp[1][1]*texlerp[0][2]);
2791                                                         pixelindex[3] = (((tex[2]  )*resolution[1]+tex[1]+1)*resolution[0]+tex[0]+1);pixelweight[3] = (texlerp[1][0]*texlerp[1][1]*texlerp[0][2]);
2792                                                         pixelindex[4] = (((tex[2]+1)*resolution[1]+tex[1]  )*resolution[0]+tex[0]  );pixelweight[4] = (texlerp[0][0]*texlerp[0][1]*texlerp[1][2]);
2793                                                         pixelindex[5] = (((tex[2]+1)*resolution[1]+tex[1]  )*resolution[0]+tex[0]+1);pixelweight[5] = (texlerp[1][0]*texlerp[0][1]*texlerp[1][2]);
2794                                                         pixelindex[6] = (((tex[2]+1)*resolution[1]+tex[1]+1)*resolution[0]+tex[0]  );pixelweight[6] = (texlerp[0][0]*texlerp[1][1]*texlerp[1][2]);
2795                                                         pixelindex[7] = (((tex[2]+1)*resolution[1]+tex[1]+1)*resolution[0]+tex[0]+1);pixelweight[7] = (texlerp[1][0]*texlerp[1][1]*texlerp[1][2]);
2796                                                         // update the 8 pixels...
2797                                                         for (pixelband = 0;pixelband < pixelbands;pixelband++)
2798                                                         {
2799                                                                 for (corner = 0;corner < 8;corner++)
2800                                                                 {
2801                                                                         // calculate address for pixel
2802                                                                         w = pixelweight[corner];
2803                                                                         pixel = pixels + 4 * pixelindex[corner] + pixelband * pixelsperband * 4;
2804                                                                         highpixel = highpixels + 4 * pixelindex[corner] + pixelband * pixelsperband * 4;
2805                                                                         // add to the high precision pixel color
2806                                                                         highpixel[0] += (splatcolor[pixelband*4+0]*w);
2807                                                                         highpixel[1] += (splatcolor[pixelband*4+1]*w);
2808                                                                         highpixel[2] += (splatcolor[pixelband*4+2]*w);
2809                                                                         highpixel[3] += (splatcolor[pixelband*4+3]*w);
2810                                                                         // flag the low precision pixel as needing to be updated
2811                                                                         pixel[3] = 255;
2812                                                                         // advance to next band of coefficients
2813                                                                         //pixel += pixelsperband*4;
2814                                                                         //highpixel += pixelsperband*4;
2815                                                                 }
2816                                                         }
2817                                                 }
2818                                                 VectorAdd(steppos, stepdelta, steppos);
2819                                         }
2820                                 }
2821                                 if (cliptrace.fraction >= 1.0f)
2822                                         break;
2823                                 r_refdef.stats.bouncegrid_hits++;
2824                                 if (bouncecount >= maxbounce)
2825                                         break;
2826                                 // scale down shot color by bounce intensity and texture color (or 50% if no texture reported)
2827                                 // also clamp the resulting color to never add energy, even if the user requests extreme values
2828                                 if (cliptrace.hittexture && cliptrace.hittexture->currentskinframe)
2829                                         VectorCopy(cliptrace.hittexture->currentskinframe->avgcolor, surfcolor);
2830                                 else
2831                                         VectorSet(surfcolor, 0.5f, 0.5f, 0.5f);
2832                                 VectorScale(surfcolor, settings.particlebounceintensity, surfcolor);
2833                                 surfcolor[0] = min(surfcolor[0], 1.0f);
2834                                 surfcolor[1] = min(surfcolor[1], 1.0f);
2835                                 surfcolor[2] = min(surfcolor[2], 1.0f);
2836                                 VectorMultiply(shotcolor, surfcolor, shotcolor);
2837                                 if (VectorLength2(baseshotcolor) == 0.0f)
2838                                         break;
2839                                 r_refdef.stats.bouncegrid_bounces++;
2840                                 if (settings.bounceanglediffuse)
2841                                 {
2842                                         // random direction, primarily along plane normal
2843                                         s = VectorDistance(cliptrace.endpos, clipend);
2844                                         if (settings.stablerandom < 0)
2845                                                 VectorRandom(clipend);
2846                                         else
2847                                                 VectorCheeseRandom(clipend);
2848                                         VectorMA(cliptrace.plane.normal, 0.95f, clipend, clipend);
2849                                         VectorNormalize(clipend);
2850                                         VectorScale(clipend, s, clipend);
2851                                 }
2852                                 else
2853                                 {
2854                                         // reflect the remaining portion of the line across plane normal
2855                                         VectorSubtract(clipend, cliptrace.endpos, clipdiff);
2856                                         VectorReflect(clipdiff, 1.0, cliptrace.plane.normal, clipend);
2857                                 }
2858                                 // calculate the new line start and end
2859                                 VectorCopy(cliptrace.endpos, clipstart);
2860                                 VectorAdd(clipstart, clipend, clipend);
2861                         }
2862                 }
2863         }
2864         // generate pixels array from highpixels array
2865         // skip first and last columns, rows, and layers as these are blank
2866         // the pixel[3] value was written above, so we can use it to detect only pixels that need to be calculated
2867         for (pixelband = 0;pixelband < pixelbands;pixelband++)
2868         {
2869                 for (z = 1;z < resolution[2]-1;z++)
2870                 {
2871                         for (y = 1;y < resolution[1]-1;y++)
2872                         {
2873                                 for (x = 1, pixelindex[0] = ((pixelband*resolution[2]+z)*resolution[1]+y)*resolution[0]+x, pixel = pixels + 4*pixelindex[0], highpixel = highpixels + 4*pixelindex[0];x < resolution[0]-1;x++, pixel += 4, highpixel += 4)
2874                                 {
2875                                         // only convert pixels that were hit by photons
2876                                         if (pixel[3] == 255)
2877                                         {
2878                                                 // normalize the bentnormal...
2879                                                 if (pixelband == 1)
2880                                                 {
2881                                                         VectorNormalize(highpixel);
2882                                                         c[0] = (int)(highpixel[0]*128.0f+128.0f);
2883                                                         c[1] = (int)(highpixel[1]*128.0f+128.0f);
2884                                                         c[2] = (int)(highpixel[2]*128.0f+128.0f);
2885                                                         c[3] = (int)(highpixel[3]*128.0f+128.0f);
2886                                                 }
2887                                                 else
2888                                                 {
2889                                                         c[0] = (int)(highpixel[0]*256.0f);
2890                                                         c[1] = (int)(highpixel[1]*256.0f);
2891                                                         c[2] = (int)(highpixel[2]*256.0f);
2892                                                         c[3] = (int)(highpixel[3]*256.0f);
2893                                                 }
2894                                                 pixel[2] = (unsigned char)bound(0, c[0], 255);
2895                                                 pixel[1] = (unsigned char)bound(0, c[1], 255);
2896                                                 pixel[0] = (unsigned char)bound(0, c[2], 255);
2897                                                 pixel[3] = (unsigned char)bound(0, c[3], 255);
2898                                         }
2899                                 }
2900                         }
2901                 }
2902         }
2903         if (r_shadow_bouncegridtexture && r_shadow_bouncegridresolution[0] == resolution[0] && r_shadow_bouncegridresolution[1] == resolution[1] && r_shadow_bouncegridresolution[2] == resolution[2] && r_shadow_bouncegriddirectional == settings.directionalshading)
2904                 R_UpdateTexture(r_shadow_bouncegridtexture, pixels, 0, 0, 0, resolution[0], resolution[1], resolution[2]*pixelbands);
2905         else
2906         {
2907                 VectorCopy(resolution, r_shadow_bouncegridresolution);
2908                 r_shadow_bouncegriddirectional = settings.directionalshading;
2909                 if (r_shadow_bouncegridtexture)
2910                         R_FreeTexture(r_shadow_bouncegridtexture);
2911                 r_shadow_bouncegridtexture = R_LoadTexture3D(r_shadow_texturepool, "bouncegrid", resolution[0], resolution[1], resolution[2]*pixelbands, pixels, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, 0, NULL);
2912         }
2913         r_shadow_bouncegridtime = realtime;
2914 }
2915
2916 void R_Shadow_RenderMode_VisibleShadowVolumes(void)
2917 {
2918         R_Shadow_RenderMode_Reset();
2919         GL_BlendFunc(GL_ONE, GL_ONE);
2920         GL_DepthRange(0, 1);
2921         GL_DepthTest(r_showshadowvolumes.integer < 2);
2922         GL_Color(0.0, 0.0125 * r_refdef.view.colorscale, 0.1 * r_refdef.view.colorscale, 1);
2923         GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
2924         GL_CullFace(GL_NONE);
2925         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLEVOLUMES;
2926 }
2927
2928 void R_Shadow_RenderMode_VisibleLighting(qboolean stenciltest, qboolean transparent)
2929 {
2930         R_Shadow_RenderMode_Reset();
2931         GL_BlendFunc(GL_ONE, GL_ONE);
2932         GL_DepthRange(0, 1);
2933         GL_DepthTest(r_showlighting.integer < 2);
2934         GL_Color(0.1 * r_refdef.view.colorscale, 0.0125 * r_refdef.view.colorscale, 0, 1);
2935         if (!transparent)
2936                 GL_DepthFunc(GL_EQUAL);
2937         R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2938         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLELIGHTING;
2939 }
2940
2941 void R_Shadow_RenderMode_End(void)
2942 {
2943         R_Shadow_RenderMode_Reset();
2944         R_Shadow_RenderMode_ActiveLight(NULL);
2945         GL_DepthMask(true);
2946         GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
2947         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
2948 }
2949
2950 int bboxedges[12][2] =
2951 {
2952         // top
2953         {0, 1}, // +X
2954         {0, 2}, // +Y
2955         {1, 3}, // Y, +X
2956         {2, 3}, // X, +Y
2957         // bottom
2958         {4, 5}, // +X
2959         {4, 6}, // +Y
2960         {5, 7}, // Y, +X
2961         {6, 7}, // X, +Y
2962         // verticals
2963         {0, 4}, // +Z
2964         {1, 5}, // X, +Z
2965         {2, 6}, // Y, +Z
2966         {3, 7}, // XY, +Z
2967 };
2968
2969 qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
2970 {
2971         if (!r_shadow_scissor.integer || r_shadow_usingdeferredprepass)
2972         {
2973                 r_shadow_lightscissor[0] = r_refdef.view.viewport.x;
2974                 r_shadow_lightscissor[1] = r_refdef.view.viewport.y;
2975                 r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
2976                 r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
2977                 return false;
2978         }
2979         if(R_ScissorForBBox(mins, maxs, r_shadow_lightscissor))
2980                 return true; // invisible
2981         if(r_shadow_lightscissor[0] != r_refdef.view.viewport.x
2982         || r_shadow_lightscissor[1] != r_refdef.view.viewport.y
2983         || r_shadow_lightscissor[2] != r_refdef.view.viewport.width
2984         || r_shadow_lightscissor[3] != r_refdef.view.viewport.height)
2985                 r_refdef.stats.lights_scissored++;
2986         return false;
2987 }
2988
2989 static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int numverts, const float *diffusecolor, const float *ambientcolor)
2990 {
2991         int i;
2992         const float *vertex3f;
2993         const float *normal3f;
2994         float *color4f;
2995         float dist, dot, distintensity, shadeintensity, v[3], n[3];
2996         switch (r_shadow_rendermode)
2997         {
2998         case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
2999         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
3000                 if (VectorLength2(diffusecolor) > 0)
3001                 {
3002                         for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, normal3f = rsurface.batchnormal3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, normal3f += 3, color4f += 4)
3003                         {
3004                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3005                                 Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
3006                                 if ((dot = DotProduct(n, v)) < 0)
3007                                 {
3008                                         shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
3009                                         VectorMA(ambientcolor, shadeintensity, diffusecolor, color4f);
3010                                 }
3011                                 else
3012                                         VectorCopy(ambientcolor, color4f);
3013                                 if (r_refdef.fogenabled)
3014                                 {
3015                                         float f;
3016                                         f = RSurf_FogVertex(vertex3f);
3017                                         VectorScale(color4f, f, color4f);
3018                                 }
3019                                 color4f[3] = 1;
3020                         }
3021                 }
3022                 else
3023                 {
3024                         for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3025                         {
3026                                 VectorCopy(ambientcolor, color4f);
3027                                 if (r_refdef.fogenabled)
3028                                 {
3029                                         float f;
3030                                         Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3031                                         f = RSurf_FogVertex(vertex3f);
3032                                         VectorScale(color4f + 4*i, f, color4f);
3033                                 }
3034                                 color4f[3] = 1;
3035                         }
3036                 }
3037                 break;
3038         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3039                 if (VectorLength2(diffusecolor) > 0)
3040                 {
3041                         for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, normal3f = rsurface.batchnormal3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, normal3f += 3, color4f += 4)
3042                         {
3043                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3044                                 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3045                                 {
3046                                         Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
3047                                         if ((dot = DotProduct(n, v)) < 0)
3048                                         {
3049                                                 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
3050                                                 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
3051                                                 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
3052                                                 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
3053                                         }
3054                                         else
3055                                         {
3056                                                 color4f[0] = ambientcolor[0] * distintensity;
3057                                                 color4f[1] = ambientcolor[1] * distintensity;
3058                                                 color4f[2] = ambientcolor[2] * distintensity;
3059                                         }
3060                                         if (r_refdef.fogenabled)
3061                                         {
3062                                                 float f;
3063                                                 f = RSurf_FogVertex(vertex3f);
3064                                                 VectorScale(color4f, f, color4f);
3065                                         }
3066                                 }
3067                                 else
3068                                         VectorClear(color4f);
3069                                 color4f[3] = 1;
3070                         }
3071                 }
3072                 else
3073                 {
3074                         for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3075                         {
3076                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3077                                 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3078                                 {
3079                                         color4f[0] = ambientcolor[0] * distintensity;
3080                                         color4f[1] = ambientcolor[1] * distintensity;
3081                                         color4f[2] = ambientcolor[2] * distintensity;
3082                                         if (r_refdef.fogenabled)
3083                                         {
3084                                                 float f;
3085                                                 f = RSurf_FogVertex(vertex3f);
3086                                                 VectorScale(color4f, f, color4f);
3087                                         }
3088                                 }
3089                                 else
3090                                         VectorClear(color4f);
3091                                 color4f[3] = 1;
3092                         }
3093                 }
3094                 break;
3095         case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3096                 if (VectorLength2(diffusecolor) > 0)
3097                 {
3098                         for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, normal3f = rsurface.batchnormal3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, normal3f += 3, color4f += 4)
3099                         {
3100                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3101                                 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3102                                 {
3103                                         distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
3104                                         Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
3105                                         if ((dot = DotProduct(n, v)) < 0)
3106                                         {
3107                                                 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
3108                                                 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
3109                                                 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
3110                                                 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
3111                                         }
3112                                         else
3113                                         {
3114                                                 color4f[0] = ambientcolor[0] * distintensity;
3115                                                 color4f[1] = ambientcolor[1] * distintensity;
3116                                                 color4f[2] = ambientcolor[2] * distintensity;
3117                                         }
3118                                         if (r_refdef.fogenabled)
3119                                         {
3120                                                 float f;
3121                                                 f = RSurf_FogVertex(vertex3f);
3122                                                 VectorScale(color4f, f, color4f);
3123                                         }
3124                                 }
3125                                 else
3126                                         VectorClear(color4f);
3127                                 color4f[3] = 1;
3128                         }
3129                 }
3130                 else
3131                 {
3132                         for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3133                         {
3134                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3135                                 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3136                                 {
3137                                         distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
3138                                         color4f[0] = ambientcolor[0] * distintensity;
3139                                         color4f[1] = ambientcolor[1] * distintensity;
3140                                         color4f[2] = ambientcolor[2] * distintensity;
3141                                         if (r_refdef.fogenabled)
3142                                         {
3143                                                 float f;
3144                                                 f = RSurf_FogVertex(vertex3f);
3145                                                 VectorScale(color4f, f, color4f);
3146                                         }
3147                                 }
3148                                 else
3149                                         VectorClear(color4f);
3150                                 color4f[3] = 1;
3151                         }
3152                 }
3153                 break;
3154         default:
3155                 break;
3156         }
3157 }
3158
3159 static void R_Shadow_RenderLighting_VisibleLighting(int texturenumsurfaces, const msurface_t **texturesurfacelist)
3160 {
3161         // used to display how many times a surface is lit for level design purposes
3162         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
3163         R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
3164         RSurf_DrawBatch();
3165 }
3166
3167 static void R_Shadow_RenderLighting_Light_GLSL(int texturenumsurfaces, const msurface_t **texturesurfacelist, const vec3_t lightcolor, float ambientscale, float diffusescale, float specularscale)
3168 {
3169         // ARB2 GLSL shader path (GFFX5200, Radeon 9500)
3170         R_SetupShader_Surface(lightcolor, false, ambientscale, diffusescale, specularscale, RSURFPASS_RTLIGHT, texturenumsurfaces, texturesurfacelist, NULL);
3171         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
3172         {
3173                 GL_DepthFunc(GL_EQUAL);
3174                 GL_AlphaTest(true);
3175         }
3176         RSurf_DrawBatch();
3177         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
3178         {
3179                 GL_DepthFunc(GL_LEQUAL);
3180                 GL_AlphaTest(false);
3181         }
3182 }
3183
3184 static void R_Shadow_RenderLighting_Light_Vertex_Pass(int firstvertex, int numvertices, int numtriangles, const int *element3i, vec3_t diffusecolor2, vec3_t ambientcolor2)
3185 {
3186         int renders;
3187         int i;
3188         int stop;
3189         int newfirstvertex;
3190         int newlastvertex;
3191         int newnumtriangles;
3192         int *newe;
3193         const int *e;
3194         float *c;
3195         int maxtriangles = 4096;
3196         static int newelements[4096*3];
3197         R_Shadow_RenderLighting_Light_Vertex_Shading(firstvertex, numvertices, diffusecolor2, ambientcolor2);
3198         for (renders = 0;renders < 4;renders++)
3199         {
3200                 stop = true;
3201                 newfirstvertex = 0;
3202                 newlastvertex = 0;
3203                 newnumtriangles = 0;
3204                 newe = newelements;
3205                 // due to low fillrate on the cards this vertex lighting path is
3206                 // designed for, we manually cull all triangles that do not
3207                 // contain a lit vertex
3208                 // this builds batches of triangles from multiple surfaces and
3209                 // renders them at once
3210                 for (i = 0, e = element3i;i < numtriangles;i++, e += 3)
3211                 {
3212                         if (VectorLength2(rsurface.passcolor4f + e[0] * 4) + VectorLength2(rsurface.passcolor4f + e[1] * 4) + VectorLength2(rsurface.passcolor4f + e[2] * 4) >= 0.01)
3213                         {
3214                                 if (newnumtriangles)
3215                                 {
3216                                         newfirstvertex = min(newfirstvertex, e[0]);
3217                                         newlastvertex  = max(newlastvertex, e[0]);
3218                                 }
3219                                 else
3220                                 {
3221                                         newfirstvertex = e[0];
3222                                         newlastvertex = e[0];
3223                                 }
3224                                 newfirstvertex = min(newfirstvertex, e[1]);
3225                                 newlastvertex  = max(newlastvertex, e[1]);
3226                                 newfirstvertex = min(newfirstvertex, e[2]);
3227                                 newlastvertex  = max(newlastvertex, e[2]);
3228                                 newe[0] = e[0];
3229                                 newe[1] = e[1];
3230                                 newe[2] = e[2];
3231                                 newnumtriangles++;
3232                                 newe += 3;
3233                                 if (newnumtriangles >= maxtriangles)
3234                                 {
3235                                         R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, NULL, NULL, 0);
3236                                         newnumtriangles = 0;
3237                                         newe = newelements;
3238                                         stop = false;
3239                                 }
3240                         }
3241                 }
3242                 if (newnumtriangles >= 1)
3243                 {
3244                         R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, NULL, NULL, 0);
3245                         stop = false;
3246                 }
3247                 // if we couldn't find any lit triangles, exit early
3248                 if (stop)
3249                         break;
3250                 // now reduce the intensity for the next overbright pass
3251                 // we have to clamp to 0 here incase the drivers have improper
3252                 // handling of negative colors
3253                 // (some old drivers even have improper handling of >1 color)
3254                 stop = true;
3255                 for (i = 0, c = rsurface.passcolor4f + 4 * firstvertex;i < numvertices;i++, c += 4)
3256                 {
3257                         if (c[0] > 1 || c[1] > 1 || c[2] > 1)
3258                         {
3259                                 c[0] = max(0, c[0] - 1);
3260                                 c[1] = max(0, c[1] - 1);
3261                                 c[2] = max(0, c[2] - 1);
3262                                 stop = false;
3263                         }
3264                         else
3265                                 VectorClear(c);
3266                 }
3267                 // another check...
3268                 if (stop)
3269                         break;
3270         }
3271 }
3272
3273 static void R_Shadow_RenderLighting_Light_Vertex(int texturenumsurfaces, const msurface_t **texturesurfacelist, const vec3_t lightcolor, float ambientscale, float diffusescale)
3274 {
3275         // OpenGL 1.1 path (anything)
3276         float ambientcolorbase[3], diffusecolorbase[3];
3277         float ambientcolorpants[3], diffusecolorpants[3];
3278         float ambientcolorshirt[3], diffusecolorshirt[3];
3279         const float *surfacecolor = rsurface.texture->dlightcolor;
3280         const float *surfacepants = rsurface.colormap_pantscolor;
3281         const float *surfaceshirt = rsurface.colormap_shirtcolor;
3282         rtexture_t *basetexture = rsurface.texture->basetexture;
3283         rtexture_t *pantstexture = rsurface.texture->pantstexture;
3284         rtexture_t *shirttexture = rsurface.texture->shirttexture;
3285         qboolean dopants = pantstexture && VectorLength2(surfacepants) >= (1.0f / 1048576.0f);
3286         qboolean doshirt = shirttexture && VectorLength2(surfaceshirt) >= (1.0f / 1048576.0f);
3287         ambientscale *= 2 * r_refdef.view.colorscale;
3288         diffusescale *= 2 * r_refdef.view.colorscale;
3289         ambientcolorbase[0] = lightcolor[0] * ambientscale * surfacecolor[0];ambientcolorbase[1] = lightcolor[1] * ambientscale * surfacecolor[1];ambientcolorbase[2] = lightcolor[2] * ambientscale * surfacecolor[2];
3290         diffusecolorbase[0] = lightcolor[0] * diffusescale * surfacecolor[0];diffusecolorbase[1] = lightcolor[1] * diffusescale * surfacecolor[1];diffusecolorbase[2] = lightcolor[2] * diffusescale * surfacecolor[2];
3291         ambientcolorpants[0] = ambientcolorbase[0] * surfacepants[0];ambientcolorpants[1] = ambientcolorbase[1] * surfacepants[1];ambientcolorpants[2] = ambientcolorbase[2] * surfacepants[2];
3292         diffusecolorpants[0] = diffusecolorbase[0] * surfacepants[0];diffusecolorpants[1] = diffusecolorbase[1] * surfacepants[1];diffusecolorpants[2] = diffusecolorbase[2] * surfacepants[2];
3293         ambientcolorshirt[0] = ambientcolorbase[0] * surfaceshirt[0];ambientcolorshirt[1] = ambientcolorbase[1] * surfaceshirt[1];ambientcolorshirt[2] = ambientcolorbase[2] * surfaceshirt[2];
3294         diffusecolorshirt[0] = diffusecolorbase[0] * surfaceshirt[0];diffusecolorshirt[1] = diffusecolorbase[1] * surfaceshirt[1];diffusecolorshirt[2] = diffusecolorbase[2] * surfaceshirt[2];
3295         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | (diffusescale > 0 ? BATCHNEED_ARRAY_NORMAL : 0) | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
3296         rsurface.passcolor4f = (float *)R_FrameData_Alloc((rsurface.batchfirstvertex + rsurface.batchnumvertices) * sizeof(float[4]));
3297         R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3298         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, 0, 0);
3299         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
3300         R_Mesh_TexBind(0, basetexture);
3301         R_Mesh_TexMatrix(0, &rsurface.texture->currenttexmatrix);
3302         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
3303         switch(r_shadow_rendermode)
3304         {
3305         case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
3306                 R_Mesh_TexBind(1, r_shadow_attenuation3dtexture);
3307                 R_Mesh_TexMatrix(1, &rsurface.entitytoattenuationxyz);
3308                 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, 1, 1);
3309                 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3310                 break;
3311         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
3312                 R_Mesh_TexBind(2, r_shadow_attenuation2dtexture);
3313                 R_Mesh_TexMatrix(2, &rsurface.entitytoattenuationz);
3314                 R_Mesh_TexCombine(2, GL_MODULATE, GL_MODULATE, 1, 1);
3315                 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3316                 // fall through
3317         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3318                 R_Mesh_TexBind(1, r_shadow_attenuation2dtexture);
3319                 R_Mesh_TexMatrix(1, &rsurface.entitytoattenuationxyz);
3320                 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, 1, 1);
3321                 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3322                 break;
3323         case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3324                 break;
3325         default:
3326                 break;
3327         }
3328         //R_Mesh_TexBind(0, basetexture);
3329         R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorbase, ambientcolorbase);
3330         if (dopants)
3331         {
3332                 R_Mesh_TexBind(0, pantstexture);
3333                 R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorpants, ambientcolorpants);
3334         }
3335         if (doshirt)
3336         {
3337                 R_Mesh_TexBind(0, shirttexture);
3338                 R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorshirt, ambientcolorshirt);
3339         }
3340 }
3341
3342 extern cvar_t gl_lightmaps;
3343 void R_Shadow_RenderLighting(int texturenumsurfaces, const msurface_t **texturesurfacelist)
3344 {
3345         float ambientscale, diffusescale, specularscale;
3346         qboolean negated;
3347         float lightcolor[3];
3348         VectorCopy(rsurface.rtlight->currentcolor, lightcolor);
3349         ambientscale = rsurface.rtlight->ambientscale;
3350         diffusescale = rsurface.rtlight->diffusescale;
3351         specularscale = rsurface.rtlight->specularscale * rsurface.texture->specularscale;
3352         if (!r_shadow_usenormalmap.integer)
3353         {
3354                 ambientscale += 1.0f * diffusescale;
3355                 diffusescale = 0;
3356                 specularscale = 0;
3357         }
3358         if ((ambientscale + diffusescale) * VectorLength2(lightcolor) + specularscale * VectorLength2(lightcolor) < (1.0f / 1048576.0f))
3359                 return;
3360         negated = (lightcolor[0] + lightcolor[1] + lightcolor[2] < 0) && vid.support.ext_blend_subtract;
3361         if(negated)
3362         {
3363                 VectorNegate(lightcolor, lightcolor);
3364                 switch(vid.renderpath)
3365                 {
3366                 case RENDERPATH_GL11:
3367                 case RENDERPATH_GL13:
3368                 case RENDERPATH_GL20:
3369                 case RENDERPATH_GLES1:
3370                 case RENDERPATH_GLES2:
3371                         qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
3372                         break;
3373                 case RENDERPATH_D3D9:
3374 #ifdef SUPPORTD3D
3375                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_BLENDOP, D3DBLENDOP_SUBTRACT);
3376 #endif
3377                         break;
3378                 case RENDERPATH_D3D10:
3379                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
3380                         break;
3381                 case RENDERPATH_D3D11:
3382                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
3383                         break;
3384                 case RENDERPATH_SOFT:
3385                         DPSOFTRAST_BlendSubtract(true);
3386                         break;
3387                 }
3388         }
3389         RSurf_SetupDepthAndCulling();
3390         switch (r_shadow_rendermode)
3391         {
3392         case R_SHADOW_RENDERMODE_VISIBLELIGHTING:
3393                 GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST) && !r_showdisabledepthtest.integer);
3394                 R_Shadow_RenderLighting_VisibleLighting(texturenumsurfaces, texturesurfacelist);
3395                 break;
3396         case R_SHADOW_RENDERMODE_LIGHT_GLSL:
3397                 R_Shadow_RenderLighting_Light_GLSL(texturenumsurfaces, texturesurfacelist, lightcolor, ambientscale, diffusescale, specularscale);
3398                 break;
3399         case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
3400         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
3401         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3402         case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3403                 R_Shadow_RenderLighting_Light_Vertex(texturenumsurfaces, texturesurfacelist, lightcolor, ambientscale, diffusescale);
3404                 break;
3405         default:
3406                 Con_Printf("R_Shadow_RenderLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode);
3407                 break;
3408         }
3409         if(negated)
3410         {
3411                 switch(vid.renderpath)
3412                 {
3413                 case RENDERPATH_GL11:
3414                 case RENDERPATH_GL13:
3415                 case RENDERPATH_GL20:
3416                 case RENDERPATH_GLES1:
3417                 case RENDERPATH_GLES2:
3418                         qglBlendEquationEXT(GL_FUNC_ADD_EXT);
3419                         break;
3420                 case RENDERPATH_D3D9:
3421 #ifdef SUPPORTD3D
3422                         IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_BLENDOP, D3DBLENDOP_ADD);
3423 #endif
3424                         break;
3425                 case RENDERPATH_D3D10:
3426                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
3427                         break;
3428                 case RENDERPATH_D3D11:
3429                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
3430                         break;
3431                 case RENDERPATH_SOFT:
3432                         DPSOFTRAST_BlendSubtract(false);
3433                         break;
3434                 }
3435         }
3436 }
3437
3438 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)
3439 {
3440         matrix4x4_t tempmatrix = *matrix;
3441         Matrix4x4_Scale(&tempmatrix, r_shadow_lightradiusscale.value, 1);
3442
3443         // if this light has been compiled before, free the associated data
3444         R_RTLight_Uncompile(rtlight);
3445
3446         // clear it completely to avoid any lingering data
3447         memset(rtlight, 0, sizeof(*rtlight));
3448
3449         // copy the properties
3450         rtlight->matrix_lighttoworld = tempmatrix;
3451         Matrix4x4_Invert_Simple(&rtlight->matrix_worldtolight, &tempmatrix);
3452         Matrix4x4_OriginFromMatrix(&tempmatrix, rtlight->shadoworigin);
3453         rtlight->radius = Matrix4x4_ScaleFromMatrix(&tempmatrix);
3454         VectorCopy(color, rtlight->color);
3455         rtlight->cubemapname[0] = 0;
3456         if (cubemapname && cubemapname[0])
3457                 strlcpy(rtlight->cubemapname, cubemapname, sizeof(rtlight->cubemapname));
3458         rtlight->shadow = shadow;
3459         rtlight->corona = corona;
3460         rtlight->style = style;
3461         rtlight->isstatic = isstatic;
3462         rtlight->coronasizescale = coronasizescale;
3463         rtlight->ambientscale = ambientscale;
3464         rtlight->diffusescale = diffusescale;
3465         rtlight->specularscale = specularscale;
3466         rtlight->flags = flags;
3467
3468         // compute derived data
3469         //rtlight->cullradius = rtlight->radius;
3470         //rtlight->cullradius2 = rtlight->radius * rtlight->radius;
3471         rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
3472         rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
3473         rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
3474         rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
3475         rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
3476         rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
3477 }
3478
3479 // compiles rtlight geometry
3480 // (undone by R_FreeCompiledRTLight, which R_UpdateLight calls)
3481 void R_RTLight_Compile(rtlight_t *rtlight)
3482 {
3483         int i;
3484         int numsurfaces, numleafs, numleafpvsbytes, numshadowtrispvsbytes, numlighttrispvsbytes;
3485         int lighttris, shadowtris, shadowzpasstris, shadowzfailtris;
3486         entity_render_t *ent = r_refdef.scene.worldentity;
3487         dp_model_t *model = r_refdef.scene.worldmodel;
3488         unsigned char *data;
3489         shadowmesh_t *mesh;
3490
3491         // compile the light
3492         rtlight->compiled = true;
3493         rtlight->shadowmode = rtlight->shadow ? (int)r_shadow_shadowmode : -1;
3494         rtlight->static_numleafs = 0;
3495         rtlight->static_numleafpvsbytes = 0;
3496         rtlight->static_leaflist = NULL;
3497         rtlight->static_leafpvs = NULL;
3498         rtlight->static_numsurfaces = 0;
3499         rtlight->static_surfacelist = NULL;
3500         rtlight->static_shadowmap_receivers = 0x3F;
3501         rtlight->static_shadowmap_casters = 0x3F;
3502         rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
3503         rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
3504         rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
3505         rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
3506         rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
3507         rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
3508
3509         if (model && model->GetLightInfo)
3510         {
3511                 // this variable must be set for the CompileShadowVolume/CompileShadowMap code
3512                 r_shadow_compilingrtlight = rtlight;
3513                 R_FrameData_SetMark();
3514                 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);
3515                 R_FrameData_ReturnToMark();
3516                 numleafpvsbytes = (model->brush.num_leafs + 7) >> 3;
3517                 numshadowtrispvsbytes = ((model->brush.shadowmesh ? model->brush.shadowmesh->numtriangles : model->surfmesh.num_triangles) + 7) >> 3;
3518                 numlighttrispvsbytes = (model->surfmesh.num_triangles + 7) >> 3;
3519                 data = (unsigned char *)Mem_Alloc(r_main_mempool, sizeof(int) * numsurfaces + sizeof(int) * numleafs + numleafpvsbytes + numshadowtrispvsbytes + numlighttrispvsbytes);
3520                 rtlight->static_numsurfaces = numsurfaces;
3521                 rtlight->static_surfacelist = (int *)data;data += sizeof(int) * numsurfaces;
3522                 rtlight->static_numleafs = numleafs;
3523                 rtlight->static_leaflist = (int *)data;data += sizeof(int) * numleafs;
3524                 rtlight->static_numleafpvsbytes = numleafpvsbytes;
3525                 rtlight->static_leafpvs = (unsigned char *)data;data += numleafpvsbytes;
3526                 rtlight->static_numshadowtrispvsbytes = numshadowtrispvsbytes;
3527                 rtlight->static_shadowtrispvs = (unsigned char *)data;data += numshadowtrispvsbytes;
3528                 rtlight->static_numlighttrispvsbytes = numlighttrispvsbytes;
3529                 rtlight->static_lighttrispvs = (unsigned char *)data;data += numlighttrispvsbytes;
3530                 if (rtlight->static_numsurfaces)
3531                         memcpy(rtlight->static_surfacelist, r_shadow_buffer_surfacelist, rtlight->static_numsurfaces * sizeof(*rtlight->static_surfacelist));
3532                 if (rtlight->static_numleafs)
3533                         memcpy(rtlight->static_leaflist, r_shadow_buffer_leaflist, rtlight->static_numleafs * sizeof(*rtlight->static_leaflist));
3534                 if (rtlight->static_numleafpvsbytes)
3535                         memcpy(rtlight->static_leafpvs, r_shadow_buffer_leafpvs, rtlight->static_numleafpvsbytes);
3536                 if (rtlight->static_numshadowtrispvsbytes)
3537                         memcpy(rtlight->static_shadowtrispvs, r_shadow_buffer_shadowtrispvs, rtlight->static_numshadowtrispvsbytes);
3538                 if (rtlight->static_numlighttrispvsbytes)
3539                         memcpy(rtlight->static_lighttrispvs, r_shadow_buffer_lighttrispvs, rtlight->static_numlighttrispvsbytes);
3540                 R_FrameData_SetMark();
3541                 switch (rtlight->shadowmode)
3542                 {
3543                 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
3544                         if (model->CompileShadowMap && rtlight->shadow)
3545                                 model->CompileShadowMap(ent, rtlight->shadoworigin, NULL, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist);
3546                         break;
3547                 default:
3548                         if (model->CompileShadowVolume && rtlight->shadow)
3549                                 model->CompileShadowVolume(ent, rtlight->shadoworigin, NULL, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist);
3550                         break;
3551                 }
3552                 R_FrameData_ReturnToMark();
3553                 // now we're done compiling the rtlight
3554                 r_shadow_compilingrtlight = NULL;
3555         }
3556
3557
3558         // use smallest available cullradius - box radius or light radius
3559         //rtlight->cullradius = RadiusFromBoundsAndOrigin(rtlight->cullmins, rtlight->cullmaxs, rtlight->shadoworigin);
3560         //rtlight->cullradius = min(rtlight->cullradius, rtlight->radius);
3561
3562         shadowzpasstris = 0;
3563         if (rtlight->static_meshchain_shadow_zpass)
3564                 for (mesh = rtlight->static_meshchain_shadow_zpass;mesh;mesh = mesh->next)
3565                         shadowzpasstris += mesh->numtriangles;
3566
3567         shadowzfailtris = 0;
3568         if (rtlight->static_meshchain_shadow_zfail)
3569                 for (mesh = rtlight->static_meshchain_shadow_zfail;mesh;mesh = mesh->next)
3570                         shadowzfailtris += mesh->numtriangles;
3571
3572         lighttris = 0;
3573         if (rtlight->static_numlighttrispvsbytes)
3574                 for (i = 0;i < rtlight->static_numlighttrispvsbytes*8;i++)
3575                         if (CHECKPVSBIT(rtlight->static_lighttrispvs, i))
3576                                 lighttris++;
3577
3578         shadowtris = 0;
3579         if (rtlight->static_numlighttrispvsbytes)
3580                 for (i = 0;i < rtlight->static_numshadowtrispvsbytes*8;i++)
3581                         if (CHECKPVSBIT(rtlight->static_shadowtrispvs, i))
3582                                 shadowtris++;
3583
3584         if (developer_extra.integer)
3585                 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);
3586 }
3587
3588 void R_RTLight_Uncompile(rtlight_t *rtlight)
3589 {
3590         if (rtlight->compiled)
3591         {
3592                 if (rtlight->static_meshchain_shadow_zpass)
3593                         Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_zpass);
3594                 rtlight->static_meshchain_shadow_zpass = NULL;
3595                 if (rtlight->static_meshchain_shadow_zfail)
3596                         Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_zfail);
3597                 rtlight->static_meshchain_shadow_zfail = NULL;
3598                 if (rtlight->static_meshchain_shadow_shadowmap)
3599                         Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_shadowmap);
3600                 rtlight->static_meshchain_shadow_shadowmap = NULL;
3601                 // these allocations are grouped
3602                 if (rtlight->static_surfacelist)
3603                         Mem_Free(rtlight->static_surfacelist);
3604                 rtlight->static_numleafs = 0;
3605                 rtlight->static_numleafpvsbytes = 0;
3606                 rtlight->static_leaflist = NULL;
3607                 rtlight->static_leafpvs = NULL;
3608                 rtlight->static_numsurfaces = 0;
3609                 rtlight->static_surfacelist = NULL;
3610                 rtlight->static_numshadowtrispvsbytes = 0;
3611                 rtlight->static_shadowtrispvs = NULL;
3612                 rtlight->static_numlighttrispvsbytes = 0;
3613                 rtlight->static_lighttrispvs = NULL;
3614                 rtlight->compiled = false;
3615         }
3616 }
3617
3618 void R_Shadow_UncompileWorldLights(void)
3619 {
3620         size_t lightindex;
3621         dlight_t *light;
3622         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
3623         for (lightindex = 0;lightindex < range;lightindex++)
3624         {
3625                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
3626                 if (!light)
3627                         continue;
3628                 R_RTLight_Uncompile(&light->rtlight);
3629         }
3630 }
3631
3632 void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight)
3633 {
3634         int i, j;
3635         mplane_t plane;
3636         // reset the count of frustum planes
3637         // see rtlight->cached_frustumplanes definition for how much this array
3638         // can hold
3639         rtlight->cached_numfrustumplanes = 0;
3640
3641         // haven't implemented a culling path for ortho rendering
3642         if (!r_refdef.view.useperspective)
3643         {
3644                 // check if the light is on screen and copy the 4 planes if it is
3645                 for (i = 0;i < 4;i++)
3646                         if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) < -0.03125)
3647                                 break;
3648                 if (i == 4)
3649                         for (i = 0;i < 4;i++)
3650                                 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = r_refdef.view.frustum[i];
3651                 return;
3652         }
3653
3654 #if 1
3655         // generate a deformed frustum that includes the light origin, this is
3656         // used to cull shadow casting surfaces that can not possibly cast a
3657         // shadow onto the visible light-receiving surfaces, which can be a
3658         // performance gain
3659         //
3660         // if the light origin is onscreen the result will be 4 planes exactly
3661         // if the light origin is offscreen on only one axis the result will
3662         // be exactly 5 planes (split-side case)
3663         // if the light origin is offscreen on two axes the result will be
3664         // exactly 4 planes (stretched corner case)
3665         for (i = 0;i < 4;i++)
3666         {
3667                 // quickly reject standard frustum planes that put the light
3668                 // origin outside the frustum
3669                 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) < -0.03125)
3670                         continue;
3671                 // copy the plane
3672                 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = r_refdef.view.frustum[i];
3673         }
3674         // if all the standard frustum planes were accepted, the light is onscreen
3675         // otherwise we need to generate some more planes below...
3676         if (rtlight->cached_numfrustumplanes < 4)
3677         {
3678                 // at least one of the stock frustum planes failed, so we need to
3679                 // create one or two custom planes to enclose the light origin
3680                 for (i = 0;i < 4;i++)
3681                 {
3682                         // create a plane using the view origin and light origin, and a
3683                         // single point from the frustum corner set
3684                         TriangleNormal(r_refdef.view.origin, r_refdef.view.frustumcorner[i], rtlight->shadoworigin, plane.normal);
3685                         VectorNormalize(plane.normal);
3686                         plane.dist = DotProduct(r_refdef.view.origin, plane.normal);
3687                         // see if this plane is backwards and flip it if so
3688                         for (j = 0;j < 4;j++)
3689                                 if (j != i && DotProduct(r_refdef.view.frustumcorner[j], plane.normal) - plane.dist < -0.03125)
3690                                         break;
3691                         if (j < 4)
3692                         {
3693                                 VectorNegate(plane.normal, plane.normal);
3694                                 plane.dist *= -1;
3695                                 // flipped plane, test again to see if it is now valid
3696                                 for (j = 0;j < 4;j++)
3697                                         if (j != i && DotProduct(r_refdef.view.frustumcorner[j], plane.normal) - plane.dist < -0.03125)
3698                                                 break;
3699                                 // if the plane is still not valid, then it is dividing the
3700                                 // frustum and has to be rejected
3701                                 if (j < 4)
3702                                         continue;
3703                         }
3704                         // we have created a valid plane, compute extra info
3705                         PlaneClassify(&plane);
3706                         // copy the plane
3707                         rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3708 #if 1
3709                         // if we've found 5 frustum planes then we have constructed a
3710                         // proper split-side case and do not need to keep searching for
3711                         // planes to enclose the light origin
3712                         if (rtlight->cached_numfrustumplanes == 5)
3713                                 break;
3714 #endif
3715                 }
3716         }
3717 #endif
3718
3719 #if 0
3720         for (i = 0;i < rtlight->cached_numfrustumplanes;i++)
3721         {
3722                 plane = rtlight->cached_frustumplanes[i];
3723                 Con_Printf("light %p plane #%i %f %f %f : %f (%f %f %f %f %f)\n", rtlight, i, plane.normal[0], plane.normal[1], plane.normal[2], plane.dist, PlaneDiff(r_refdef.view.frustumcorner[0], &plane), PlaneDiff(r_refdef.view.frustumcorner[1], &plane), PlaneDiff(r_refdef.view.frustumcorner[2], &plane), PlaneDiff(r_refdef.view.frustumcorner[3], &plane), PlaneDiff(rtlight->shadoworigin, &plane));
3724         }
3725 #endif
3726
3727 #if 0
3728         // now add the light-space box planes if the light box is rotated, as any
3729         // caster outside the oriented light box is irrelevant (even if it passed
3730         // the worldspace light box, which is axial)
3731         if (rtlight->matrix_lighttoworld.m[0][0] != 1 || rtlight->matrix_lighttoworld.m[1][1] != 1 || rtlight->matrix_lighttoworld.m[2][2] != 1)
3732         {
3733                 for (i = 0;i < 6;i++)
3734                 {
3735                         vec3_t v;
3736                         VectorClear(v);
3737                         v[i >> 1] = (i & 1) ? -1 : 1;
3738                         Matrix4x4_Transform(&rtlight->matrix_lighttoworld, v, plane.normal);
3739                         VectorSubtract(plane.normal, rtlight->shadoworigin, plane.normal);
3740                         plane.dist = VectorNormalizeLength(plane.normal);
3741                         plane.dist += DotProduct(plane.normal, rtlight->shadoworigin);
3742                         rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3743                 }
3744         }
3745 #endif
3746
3747 #if 0
3748         // add the world-space reduced box planes
3749         for (i = 0;i < 6;i++)
3750         {
3751                 VectorClear(plane.normal);
3752                 plane.normal[i >> 1] = (i & 1) ? -1 : 1;
3753                 plane.dist = (i & 1) ? -rtlight->cached_cullmaxs[i >> 1] : rtlight->cached_cullmins[i >> 1];
3754                 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3755         }
3756 #endif
3757
3758 #if 0
3759         {
3760         int j, oldnum;
3761         vec3_t points[8];
3762         vec_t bestdist;
3763         // reduce all plane distances to tightly fit the rtlight cull box, which
3764         // is in worldspace
3765         VectorSet(points[0], rtlight->cached_cullmins[0], rtlight->cached_cullmins[1], rtlight->cached_cullmins[2]);
3766         VectorSet(points[1], rtlight->cached_cullmaxs[0], rtlight->cached_cullmins[1], rtlight->cached_cullmins[2]);
3767         VectorSet(points[2], rtlight->cached_cullmins[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmins[2]);
3768         VectorSet(points[3], rtlight->cached_cullmaxs[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmins[2]);
3769         VectorSet(points[4], rtlight->cached_cullmins[0], rtlight->cached_cullmins[1], rtlight->cached_cullmaxs[2]);
3770         VectorSet(points[5], rtlight->cached_cullmaxs[0], rtlight->cached_cullmins[1], rtlight->cached_cullmaxs[2]);
3771         VectorSet(points[6], rtlight->cached_cullmins[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmaxs[2]);
3772         VectorSet(points[7], rtlight->cached_cullmaxs[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmaxs[2]);
3773         oldnum = rtlight->cached_numfrustumplanes;
3774         rtlight->cached_numfrustumplanes = 0;
3775         for (j = 0;j < oldnum;j++)
3776         {
3777                 // find the nearest point on the box to this plane
3778                 bestdist = DotProduct(rtlight->cached_frustumplanes[j].normal, points[0]);
3779                 for (i = 1;i < 8;i++)
3780                 {
3781                         dist = DotProduct(rtlight->cached_frustumplanes[j].normal, points[i]);
3782                         if (bestdist > dist)
3783                                 bestdist = dist;
3784                 }
3785                 Con_Printf("light %p %splane #%i %f %f %f : %f < %f\n", rtlight, rtlight->cached_frustumplanes[j].dist < bestdist + 0.03125 ? "^2" : "^1", j, rtlight->cached_frustumplanes[j].normal[0], rtlight->cached_frustumplanes[j].normal[1], rtlight->cached_frustumplanes[j].normal[2], rtlight->cached_frustumplanes[j].dist, bestdist);
3786                 // if the nearest point is near or behind the plane, we want this
3787                 // plane, otherwise the plane is useless as it won't cull anything
3788                 if (rtlight->cached_frustumplanes[j].dist < bestdist + 0.03125)
3789                 {
3790                         PlaneClassify(&rtlight->cached_frustumplanes[j]);
3791                         rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = rtlight->cached_frustumplanes[j];
3792                 }
3793         }
3794         }
3795 #endif
3796 }
3797
3798 void R_Shadow_DrawWorldShadow_ShadowMap(int numsurfaces, int *surfacelist, const unsigned char *trispvs, const unsigned char *surfacesides)
3799 {
3800         shadowmesh_t *mesh;
3801
3802         RSurf_ActiveWorldEntity();
3803
3804         if (rsurface.rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
3805         {
3806                 CHECKGLERROR
3807                 GL_CullFace(GL_NONE);
3808                 mesh = rsurface.rtlight->static_meshchain_shadow_shadowmap;
3809                 for (;mesh;mesh = mesh->next)
3810                 {
3811                         if (!mesh->sidetotals[r_shadow_shadowmapside])
3812                                 continue;
3813                         r_refdef.stats.lights_shadowtriangles += mesh->sidetotals[r_shadow_shadowmapside];
3814                         if (mesh->vertex3fbuffer)
3815                                 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vertex3fbuffer);
3816                         else
3817                                 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vbo_vertexbuffer);
3818                         R_Mesh_Draw(0, mesh->numverts, mesh->sideoffsets[r_shadow_shadowmapside], mesh->sidetotals[r_shadow_shadowmapside], mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset);
3819                 }
3820                 CHECKGLERROR
3821         }
3822         else if (r_refdef.scene.worldentity->model)
3823                 r_refdef.scene.worldmodel->DrawShadowMap(r_shadow_shadowmapside, r_refdef.scene.worldentity, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius, numsurfaces, surfacelist, surfacesides, rsurface.rtlight->cached_cullmins, rsurface.rtlight->cached_cullmaxs);
3824
3825         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3826 }
3827
3828 void R_Shadow_DrawWorldShadow_ShadowVolume(int numsurfaces, int *surfacelist, const unsigned char *trispvs)
3829 {
3830         qboolean zpass = false;
3831         shadowmesh_t *mesh;
3832         int t, tend;
3833         int surfacelistindex;
3834         msurface_t *surface;
3835
3836         // if triangle neighbors are disabled, shadowvolumes are disabled
3837         if (r_refdef.scene.worldmodel->brush.shadowmesh ? !r_refdef.scene.worldmodel->brush.shadowmesh->neighbor3i : !r_refdef.scene.worldmodel->surfmesh.data_neighbor3i)
3838                 return;
3839
3840         RSurf_ActiveWorldEntity();
3841
3842         if (rsurface.rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
3843         {
3844                 CHECKGLERROR
3845                 if (r_shadow_rendermode != R_SHADOW_RENDERMODE_VISIBLEVOLUMES)
3846                 {
3847                         zpass = R_Shadow_UseZPass(r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs);
3848                         R_Shadow_RenderMode_StencilShadowVolumes(zpass);
3849                 }
3850                 mesh = zpass ? rsurface.rtlight->static_meshchain_shadow_zpass : rsurface.rtlight->static_meshchain_shadow_zfail;
3851                 for (;mesh;mesh = mesh->next)
3852                 {
3853                         r_refdef.stats.lights_shadowtriangles += mesh->numtriangles;
3854                         if (mesh->vertex3fbuffer)
3855                                 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vertex3fbuffer);
3856                         else
3857                                 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vbo_vertexbuffer);
3858                         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
3859                         {
3860                                 // increment stencil if frontface is infront of depthbuffer
3861                                 GL_CullFace(r_refdef.view.cullface_back);
3862                                 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_ALWAYS, 128, 255);
3863                                 R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset);
3864                                 // decrement stencil if backface is infront of depthbuffer
3865                                 GL_CullFace(r_refdef.view.cullface_front);
3866                                 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, 128, 255);
3867                         }
3868                         else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
3869                         {
3870                                 // decrement stencil if backface is behind depthbuffer
3871                                 GL_CullFace(r_refdef.view.cullface_front);
3872                                 R_SetStencil(true, 255, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, 128, 255);
3873                                 R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset);
3874                                 // increment stencil if frontface is behind depthbuffer
3875                                 GL_CullFace(r_refdef.view.cullface_back);
3876                                 R_SetStencil(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_ALWAYS, 128, 255);
3877                         }
3878                         R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset);
3879                 }
3880                 CHECKGLERROR
3881         }
3882         else if (numsurfaces && r_refdef.scene.worldmodel->brush.shadowmesh)
3883         {
3884                 // use the shadow trispvs calculated earlier by GetLightInfo to cull world triangles on this dynamic light
3885                 R_Shadow_PrepareShadowMark(r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles);
3886                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
3887                 {
3888                         surface = r_refdef.scene.worldmodel->data_surfaces + surfacelist[surfacelistindex];
3889                         for (t = surface->num_firstshadowmeshtriangle, tend = t + surface->num_triangles;t < tend;t++)
3890                                 if (CHECKPVSBIT(trispvs, t))
3891                                         shadowmarklist[numshadowmark++] = t;
3892                 }
3893                 R_Shadow_VolumeFromList(r_refdef.scene.worldmodel->brush.shadowmesh->numverts, r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles, r_refdef.scene.worldmodel->brush.shadowmesh->vertex3f, r_refdef.scene.worldmodel->brush.shadowmesh->element3i, r_refdef.scene.worldmodel->brush.shadowmesh->neighbor3i, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius + r_refdef.scene.worldmodel->radius*2 + r_shadow_projectdistance.value, numshadowmark, shadowmarklist, r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs);
3894         }
3895         else if (numsurfaces)
3896         {
3897                 r_refdef.scene.worldmodel->DrawShadowVolume(r_refdef.scene.worldentity, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius, numsurfaces, surfacelist, rsurface.rtlight->cached_cullmins, rsurface.rtlight->cached_cullmaxs);
3898         }
3899
3900         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3901 }
3902
3903 void R_Shadow_DrawEntityShadow(entity_render_t *ent)
3904 {
3905         vec3_t relativeshadoworigin, relativeshadowmins, relativeshadowmaxs;
3906         vec_t relativeshadowradius;
3907         RSurf_ActiveModelEntity(ent, false, false, false);
3908         Matrix4x4_Transform(&ent->inversematrix, rsurface.rtlight->shadoworigin, relativeshadoworigin);
3909         // we need to re-init the shader for each entity because the matrix changed
3910         relativeshadowradius = rsurface.rtlight->radius / ent->scale;
3911         relativeshadowmins[0] = relativeshadoworigin[0] - relativeshadowradius;
3912         relativeshadowmins[1] = relativeshadoworigin[1] - relativeshadowradius;
3913         relativeshadowmins[2] = relativeshadoworigin[2] - relativeshadowradius;
3914         relativeshadowmaxs[0] = relativeshadoworigin[0] + relativeshadowradius;
3915         relativeshadowmaxs[1] = relativeshadoworigin[1] + relativeshadowradius;
3916         relativeshadowmaxs[2] = relativeshadoworigin[2] + relativeshadowradius;
3917         switch (r_shadow_rendermode)
3918         {
3919         case R_SHADOW_RENDERMODE_SHADOWMAP2D:
3920                 ent->model->DrawShadowMap(r_shadow_shadowmapside, ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, NULL, relativeshadowmins, relativeshadowmaxs);
3921                 break;
3922         default:
3923                 ent->model->DrawShadowVolume(ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
3924                 break;
3925         }
3926         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3927 }
3928
3929 void R_Shadow_SetupEntityLight(const entity_render_t *ent)
3930 {
3931         // set up properties for rendering light onto this entity
3932         RSurf_ActiveModelEntity(ent, true, true, false);
3933         Matrix4x4_Concat(&rsurface.entitytolight, &rsurface.rtlight->matrix_worldtolight, &ent->matrix);
3934         Matrix4x4_Concat(&rsurface.entitytoattenuationxyz, &matrix_attenuationxyz, &rsurface.entitytolight);
3935         Matrix4x4_Concat(&rsurface.entitytoattenuationz, &matrix_attenuationz, &rsurface.entitytolight);
3936         Matrix4x4_Transform(&ent->inversematrix, rsurface.rtlight->shadoworigin, rsurface.entitylightorigin);
3937 }
3938
3939 void R_Shadow_DrawWorldLight(int numsurfaces, int *surfacelist, const unsigned char *lighttrispvs)
3940 {
3941         if (!r_refdef.scene.worldmodel->DrawLight)
3942                 return;
3943
3944         // set up properties for rendering light onto this entity
3945         RSurf_ActiveWorldEntity();
3946         rsurface.entitytolight = rsurface.rtlight->matrix_worldtolight;
3947         Matrix4x4_Concat(&rsurface.entitytoattenuationxyz, &matrix_attenuationxyz, &rsurface.entitytolight);
3948         Matrix4x4_Concat(&rsurface.entitytoattenuationz, &matrix_attenuationz, &rsurface.entitytolight);
3949         VectorCopy(rsurface.rtlight->shadoworigin, rsurface.entitylightorigin);
3950
3951         r_refdef.scene.worldmodel->DrawLight(r_refdef.scene.worldentity, numsurfaces, surfacelist, lighttrispvs);
3952
3953         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3954 }
3955
3956 void R_Shadow_DrawEntityLight(entity_render_t *ent)
3957 {
3958         dp_model_t *model = ent->model;
3959         if (!model->DrawLight)
3960                 return;
3961
3962         R_Shadow_SetupEntityLight(ent);
3963
3964         model->DrawLight(ent, model->nummodelsurfaces, model->sortedmodelsurfaces, NULL);
3965
3966         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3967 }
3968
3969 void R_Shadow_PrepareLight(rtlight_t *rtlight)
3970 {
3971         int i;
3972         float f;
3973         int numleafs, numsurfaces;
3974         int *leaflist, *surfacelist;
3975         unsigned char *leafpvs;
3976         unsigned char *shadowtrispvs;
3977         unsigned char *lighttrispvs;
3978         //unsigned char *surfacesides;
3979         int numlightentities;
3980         int numlightentities_noselfshadow;
3981         int numshadowentities;
3982         int numshadowentities_noselfshadow;
3983         static entity_render_t *lightentities[MAX_EDICTS];
3984         static entity_render_t *lightentities_noselfshadow[MAX_EDICTS];
3985         static entity_render_t *shadowentities[MAX_EDICTS];
3986         static entity_render_t *shadowentities_noselfshadow[MAX_EDICTS];
3987         qboolean nolight;
3988
3989         rtlight->draw = false;
3990
3991         // skip lights that don't light because of ambientscale+diffusescale+specularscale being 0 (corona only lights)
3992         // skip lights that are basically invisible (color 0 0 0)
3993         nolight = VectorLength2(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) < (1.0f / 1048576.0f);
3994
3995         // loading is done before visibility checks because loading should happen
3996         // all at once at the start of a level, not when it stalls gameplay.
3997         // (especially important to benchmarks)
3998         // compile light
3999         if (rtlight->isstatic && !nolight && (!rtlight->compiled || (rtlight->shadow && rtlight->shadowmode != (int)r_shadow_shadowmode)) && r_shadow_realtime_world_compile.integer)
4000         {
4001                 if (rtlight->compiled)
4002                         R_RTLight_Uncompile(rtlight);
4003                 R_RTLight_Compile(rtlight);
4004         }
4005
4006         // load cubemap
4007         rtlight->currentcubemap = rtlight->cubemapname[0] ? R_GetCubemap(rtlight->cubemapname) : r_texture_whitecube;
4008
4009         // look up the light style value at this time
4010         f = (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value;
4011         VectorScale(rtlight->color, f, rtlight->currentcolor);
4012         /*
4013         if (rtlight->selected)
4014         {
4015                 f = 2 + sin(realtime * M_PI * 4.0);
4016                 VectorScale(rtlight->currentcolor, f, rtlight->currentcolor);
4017         }
4018         */
4019
4020         // if lightstyle is currently off, don't draw the light
4021         if (VectorLength2(rtlight->currentcolor) < (1.0f / 1048576.0f))
4022                 return;
4023
4024         // skip processing on corona-only lights
4025         if (nolight)
4026                 return;
4027
4028         // if the light box is offscreen, skip it
4029         if (R_CullBox(rtlight->cullmins, rtlight->cullmaxs))
4030                 return;
4031
4032         VectorCopy(rtlight->cullmins, rtlight->cached_cullmins);
4033         VectorCopy(rtlight->cullmaxs, rtlight->cached_cullmaxs);
4034
4035         R_Shadow_ComputeShadowCasterCullingPlanes(rtlight);
4036
4037         if (rtlight->compiled && r_shadow_realtime_world_compile.integer)
4038         {
4039                 // compiled light, world available and can receive realtime lighting
4040                 // retrieve leaf information
4041                 numleafs = rtlight->static_numleafs;
4042                 leaflist = rtlight->static_leaflist;
4043                 leafpvs = rtlight->static_leafpvs;
4044                 numsurfaces = rtlight->static_numsurfaces;
4045                 surfacelist = rtlight->static_surfacelist;
4046                 //surfacesides = NULL;
4047                 shadowtrispvs = rtlight->static_shadowtrispvs;
4048                 lighttrispvs = rtlight->static_lighttrispvs;
4049         }
4050         else if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->GetLightInfo)
4051         {
4052                 // dynamic light, world available and can receive realtime lighting
4053                 // calculate lit surfaces and leafs
4054                 r_refdef.scene.worldmodel->GetLightInfo(r_refdef.scene.worldentity, rtlight->shadoworigin, rtlight->radius, rtlight->cached_cullmins, rtlight->cached_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, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes);
4055                 R_Shadow_ComputeShadowCasterCullingPlanes(rtlight);
4056                 leaflist = r_shadow_buffer_leaflist;
4057                 leafpvs = r_shadow_buffer_leafpvs;
4058                 surfacelist = r_shadow_buffer_surfacelist;
4059                 //surfacesides = r_shadow_buffer_surfacesides;
4060                 shadowtrispvs = r_shadow_buffer_shadowtrispvs;
4061                 lighttrispvs = r_shadow_buffer_lighttrispvs;
4062                 // if the reduced leaf bounds are offscreen, skip it
4063                 if (R_CullBox(rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4064                         return;
4065         }
4066         else
4067         {
4068                 // no world
4069                 numleafs = 0;
4070                 leaflist = NULL;
4071                 leafpvs = NULL;
4072                 numsurfaces = 0;
4073                 surfacelist = NULL;
4074                 //surfacesides = NULL;
4075                 shadowtrispvs = NULL;
4076                 lighttrispvs = NULL;
4077         }
4078         // check if light is illuminating any visible leafs
4079         if (numleafs)
4080         {
4081                 for (i = 0;i < numleafs;i++)
4082                         if (r_refdef.viewcache.world_leafvisible[leaflist[i]])
4083                                 break;
4084                 if (i == numleafs)
4085                         return;
4086         }
4087
4088         // make a list of lit entities and shadow casting entities
4089         numlightentities = 0;
4090         numlightentities_noselfshadow = 0;
4091         numshadowentities = 0;
4092         numshadowentities_noselfshadow = 0;
4093
4094         // add dynamic entities that are lit by the light
4095         for (i = 0;i < r_refdef.scene.numentities;i++)
4096         {
4097                 dp_model_t *model;
4098                 entity_render_t *ent = r_refdef.scene.entities[i];
4099                 vec3_t org;
4100                 if (!BoxesOverlap(ent->mins, ent->maxs, rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4101                         continue;
4102                 // skip the object entirely if it is not within the valid
4103                 // shadow-casting region (which includes the lit region)
4104                 if (R_CullBoxCustomPlanes(ent->mins, ent->maxs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes))
4105                         continue;
4106                 if (!(model = ent->model))
4107                         continue;
4108                 if (r_refdef.viewcache.entityvisible[i] && model->DrawLight && (ent->flags & RENDER_LIGHT))
4109                 {
4110                         // this entity wants to receive light, is visible, and is
4111                         // inside the light box
4112                         // TODO: check if the surfaces in the model can receive light
4113                         // so now check if it's in a leaf seen by the light
4114                         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS && !r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS(r_refdef.scene.worldmodel, leafpvs, ent->mins, ent->maxs))
4115                                 continue;
4116                         if (ent->flags & RENDER_NOSELFSHADOW)
4117                                 lightentities_noselfshadow[numlightentities_noselfshadow++] = ent;
4118                         else
4119                                 lightentities[numlightentities++] = ent;
4120                         // since it is lit, it probably also casts a shadow...
4121                         // about the VectorDistance2 - light emitting entities should not cast their own shadow
4122                         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
4123                         if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1)
4124                         {
4125                                 // note: exterior models without the RENDER_NOSELFSHADOW
4126                                 // flag still create a RENDER_NOSELFSHADOW shadow but
4127                                 // are lit normally, this means that they are
4128                                 // self-shadowing but do not shadow other
4129                                 // RENDER_NOSELFSHADOW entities such as the gun
4130                                 // (very weird, but keeps the player shadow off the gun)
4131                                 if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL))
4132                                         shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent;
4133                                 else
4134                                         shadowentities[numshadowentities++] = ent;
4135                         }
4136                 }
4137                 else if (ent->flags & RENDER_SHADOW)
4138                 {
4139                         // this entity is not receiving light, but may still need to
4140                         // cast a shadow...
4141                         // TODO: check if the surfaces in the model can cast shadow
4142                         // now check if it is in a leaf seen by the light
4143                         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS && !r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS(r_refdef.scene.worldmodel, leafpvs, ent->mins, ent->maxs))
4144                                 continue;
4145                         // about the VectorDistance2 - light emitting entities should not cast their own shadow
4146                         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
4147                         if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1)
4148                         {
4149                                 if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL))
4150                                         shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent;
4151                                 else
4152                                         shadowentities[numshadowentities++] = ent;
4153                         }
4154                 }
4155         }
4156
4157         // return if there's nothing at all to light
4158         if (numsurfaces + numlightentities + numlightentities_noselfshadow == 0)
4159                 return;
4160
4161         // count this light in the r_speeds
4162         r_refdef.stats.lights++;
4163
4164         // flag it as worth drawing later
4165         rtlight->draw = true;
4166
4167         // cache all the animated entities that cast a shadow but are not visible
4168         for (i = 0;i < numshadowentities;i++)
4169                 if (!shadowentities[i]->animcache_vertex3f)
4170                         R_AnimCache_GetEntity(shadowentities[i], false, false);
4171         for (i = 0;i < numshadowentities_noselfshadow;i++)
4172                 if (!shadowentities_noselfshadow[i]->animcache_vertex3f)
4173                         R_AnimCache_GetEntity(shadowentities_noselfshadow[i], false, false);
4174
4175         // allocate some temporary memory for rendering this light later in the frame
4176         // reusable buffers need to be copied, static data can be used as-is
4177         rtlight->cached_numlightentities               = numlightentities;
4178         rtlight->cached_numlightentities_noselfshadow  = numlightentities_noselfshadow;
4179         rtlight->cached_numshadowentities              = numshadowentities;
4180         rtlight->cached_numshadowentities_noselfshadow = numshadowentities_noselfshadow;
4181         rtlight->cached_numsurfaces                    = numsurfaces;
4182         rtlight->cached_lightentities                  = (entity_render_t**)R_FrameData_Store(numlightentities*sizeof(entity_render_t*), (void*)lightentities);
4183         rtlight->cached_lightentities_noselfshadow     = (entity_render_t**)R_FrameData_Store(numlightentities_noselfshadow*sizeof(entity_render_t*), (void*)lightentities_noselfshadow);
4184         rtlight->cached_shadowentities                 = (entity_render_t**)R_FrameData_Store(numshadowentities*sizeof(entity_render_t*), (void*)shadowentities);
4185         rtlight->cached_shadowentities_noselfshadow    = (entity_render_t**)R_FrameData_Store(numshadowentities_noselfshadow*sizeof(entity_render_t *), (void*)shadowentities_noselfshadow);
4186         if (shadowtrispvs == r_shadow_buffer_shadowtrispvs)
4187         {
4188                 int numshadowtrispvsbytes = (((r_refdef.scene.worldmodel->brush.shadowmesh ? r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles : r_refdef.scene.worldmodel->surfmesh.num_triangles) + 7) >> 3);
4189                 int numlighttrispvsbytes = ((r_refdef.scene.worldmodel->surfmesh.num_triangles + 7) >> 3);
4190                 rtlight->cached_shadowtrispvs                  =   (unsigned char *)R_FrameData_Store(numshadowtrispvsbytes, shadowtrispvs);
4191                 rtlight->cached_lighttrispvs                   =   (unsigned char *)R_FrameData_Store(numlighttrispvsbytes, lighttrispvs);
4192                 rtlight->cached_surfacelist                    =              (int*)R_FrameData_Store(numsurfaces*sizeof(int), (void*)surfacelist);
4193         }
4194         else
4195         {
4196                 // compiled light data
4197                 rtlight->cached_shadowtrispvs = shadowtrispvs;
4198                 rtlight->cached_lighttrispvs = lighttrispvs;
4199                 rtlight->cached_surfacelist = surfacelist;
4200         }
4201 }
4202
4203 void R_Shadow_DrawLight(rtlight_t *rtlight)
4204 {
4205         int i;
4206         int numsurfaces;
4207         unsigned char *shadowtrispvs, *lighttrispvs, *surfacesides;
4208         int numlightentities;
4209         int numlightentities_noselfshadow;
4210         int numshadowentities;
4211         int numshadowentities_noselfshadow;
4212         entity_render_t **lightentities;
4213         entity_render_t **lightentities_noselfshadow;
4214         entity_render_t **shadowentities;
4215         entity_render_t **shadowentities_noselfshadow;
4216         int *surfacelist;
4217         static unsigned char entitysides[MAX_EDICTS];
4218         static unsigned char entitysides_noselfshadow[MAX_EDICTS];
4219         vec3_t nearestpoint;
4220         vec_t distance;
4221         qboolean castshadows;
4222         int lodlinear;
4223
4224         // check if we cached this light this frame (meaning it is worth drawing)
4225         if (!rtlight->draw)
4226                 return;
4227
4228         numlightentities = rtlight->cached_numlightentities;
4229         numlightentities_noselfshadow = rtlight->cached_numlightentities_noselfshadow;
4230         numshadowentities = rtlight->cached_numshadowentities;
4231         numshadowentities_noselfshadow = rtlight->cached_numshadowentities_noselfshadow;
4232         numsurfaces = rtlight->cached_numsurfaces;
4233         lightentities = rtlight->cached_lightentities;
4234         lightentities_noselfshadow = rtlight->cached_lightentities_noselfshadow;
4235         shadowentities = rtlight->cached_shadowentities;
4236         shadowentities_noselfshadow = rtlight->cached_shadowentities_noselfshadow;
4237         shadowtrispvs = rtlight->cached_shadowtrispvs;
4238         lighttrispvs = rtlight->cached_lighttrispvs;
4239         surfacelist = rtlight->cached_surfacelist;
4240
4241         // set up a scissor rectangle for this light
4242         if (R_Shadow_ScissorForBBox(rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4243                 return;
4244
4245         // don't let sound skip if going slow
4246         if (r_refdef.scene.extraupdate)
4247                 S_ExtraUpdate ();
4248
4249         // make this the active rtlight for rendering purposes
4250         R_Shadow_RenderMode_ActiveLight(rtlight);
4251
4252         if (r_showshadowvolumes.integer && r_refdef.view.showdebug && numsurfaces + numshadowentities + numshadowentities_noselfshadow && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows))
4253         {
4254                 // optionally draw visible shape of the shadow volumes
4255                 // for performance analysis by level designers
4256                 R_Shadow_RenderMode_VisibleShadowVolumes();
4257                 if (numsurfaces)
4258                         R_Shadow_DrawWorldShadow_ShadowVolume(numsurfaces, surfacelist, shadowtrispvs);
4259                 for (i = 0;i < numshadowentities;i++)
4260                         R_Shadow_DrawEntityShadow(shadowentities[i]);
4261                 for (i = 0;i < numshadowentities_noselfshadow;i++)
4262                         R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4263                 R_Shadow_RenderMode_VisibleLighting(false, false);
4264         }
4265
4266         if (r_showlighting.integer && r_refdef.view.showdebug && numsurfaces + numlightentities + numlightentities_noselfshadow)
4267         {
4268                 // optionally draw the illuminated areas
4269                 // for performance analysis by level designers
4270                 R_Shadow_RenderMode_VisibleLighting(false, false);
4271                 if (numsurfaces)
4272                         R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4273                 for (i = 0;i < numlightentities;i++)
4274                         R_Shadow_DrawEntityLight(lightentities[i]);
4275                 for (i = 0;i < numlightentities_noselfshadow;i++)
4276                         R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4277         }
4278
4279         castshadows = numsurfaces + numshadowentities + numshadowentities_noselfshadow > 0 && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows);
4280
4281         nearestpoint[0] = bound(rtlight->cullmins[0], r_refdef.view.origin[0], rtlight->cullmaxs[0]);
4282         nearestpoint[1] = bound(rtlight->cullmins[1], r_refdef.view.origin[1], rtlight->cullmaxs[1]);
4283         nearestpoint[2] = bound(rtlight->cullmins[2], r_refdef.view.origin[2], rtlight->cullmaxs[2]);
4284         distance = VectorDistance(nearestpoint, r_refdef.view.origin);
4285
4286         lodlinear = (rtlight->radius * r_shadow_shadowmapping_precision.value) / sqrt(max(1.0f, distance/rtlight->radius));
4287         //lodlinear = (int)(r_shadow_shadowmapping_lod_bias.value + r_shadow_shadowmapping_lod_scale.value * rtlight->radius / max(1.0f, distance));
4288         lodlinear = bound(r_shadow_shadowmapping_minsize.integer, lodlinear, r_shadow_shadowmapmaxsize);
4289
4290         if (castshadows && r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D)
4291         {
4292                 float borderbias;
4293                 int side;
4294                 int size;
4295                 int castermask = 0;
4296                 int receivermask = 0;
4297                 matrix4x4_t radiustolight = rtlight->matrix_worldtolight;
4298                 Matrix4x4_Abs(&radiustolight);
4299
4300                 r_shadow_shadowmaplod = 0;
4301                 for (i = 1;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
4302                         if ((r_shadow_shadowmapmaxsize >> i) > lodlinear)
4303                                 r_shadow_shadowmaplod = i;
4304
4305                 size = bound(r_shadow_shadowmapborder, lodlinear, r_shadow_shadowmapmaxsize);
4306                         
4307                 borderbias = r_shadow_shadowmapborder / (float)(size - r_shadow_shadowmapborder);
4308
4309                 surfacesides = NULL;
4310                 if (numsurfaces)
4311                 {
4312                         if (rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
4313                         {
4314                                 castermask = rtlight->static_shadowmap_casters;
4315                                 receivermask = rtlight->static_shadowmap_receivers;
4316                         }
4317                         else
4318                         {
4319                                 surfacesides = r_shadow_buffer_surfacesides;
4320                                 for(i = 0;i < numsurfaces;i++)
4321                                 {
4322                                         msurface_t *surface = r_refdef.scene.worldmodel->data_surfaces + surfacelist[i];
4323                                         surfacesides[i] = R_Shadow_CalcBBoxSideMask(surface->mins, surface->maxs, &rtlight->matrix_worldtolight, &radiustolight, borderbias);           
4324                                         castermask |= surfacesides[i];
4325                                         receivermask |= surfacesides[i];
4326                                 }
4327                         }
4328                 }
4329                 if (receivermask < 0x3F) 
4330                 {
4331                         for (i = 0;i < numlightentities;i++)
4332                                 receivermask |= R_Shadow_CalcEntitySideMask(lightentities[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias);
4333                         if (receivermask < 0x3F)
4334                                 for(i = 0; i < numlightentities_noselfshadow;i++)
4335                                         receivermask |= R_Shadow_CalcEntitySideMask(lightentities_noselfshadow[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias);
4336                 }
4337
4338                 receivermask &= R_Shadow_CullFrustumSides(rtlight, size, r_shadow_shadowmapborder);
4339
4340                 if (receivermask)
4341                 {
4342                         for (i = 0;i < numshadowentities;i++)
4343                                 castermask |= (entitysides[i] = R_Shadow_CalcEntitySideMask(shadowentities[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias));
4344                         for (i = 0;i < numshadowentities_noselfshadow;i++)
4345                                 castermask |= (entitysides_noselfshadow[i] = R_Shadow_CalcEntitySideMask(shadowentities_noselfshadow[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias)); 
4346                 }
4347
4348                 //Con_Printf("distance %f lodlinear %i (lod %i) size %i\n", distance, lodlinear, r_shadow_shadowmaplod, size);
4349
4350                 // render shadow casters into 6 sided depth texture
4351                 for (side = 0;side < 6;side++) if (receivermask & (1 << side))
4352                 {
4353                         R_Shadow_RenderMode_ShadowMap(side, receivermask, size);
4354                         if (! (castermask & (1 << side))) continue;
4355                         if (numsurfaces)
4356                                 R_Shadow_DrawWorldShadow_ShadowMap(numsurfaces, surfacelist, shadowtrispvs, surfacesides);
4357                         for (i = 0;i < numshadowentities;i++) if (entitysides[i] & (1 << side))
4358                                 R_Shadow_DrawEntityShadow(shadowentities[i]);
4359                 }
4360
4361                 if (numlightentities_noselfshadow)
4362                 {
4363                         // render lighting using the depth texture as shadowmap
4364                         // draw lighting in the unmasked areas
4365                         R_Shadow_RenderMode_Lighting(false, false, true);
4366                         for (i = 0;i < numlightentities_noselfshadow;i++)
4367                                 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4368                 }
4369
4370                 // render shadow casters into 6 sided depth texture
4371                 if (numshadowentities_noselfshadow)
4372                 {
4373                         for (side = 0;side < 6;side++) if ((receivermask & castermask) & (1 << side))
4374                         {
4375                                 R_Shadow_RenderMode_ShadowMap(side, 0, size);
4376                                 for (i = 0;i < numshadowentities_noselfshadow;i++) if (entitysides_noselfshadow[i] & (1 << side))
4377                                         R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4378                         }
4379                 }
4380
4381                 // render lighting using the depth texture as shadowmap
4382                 // draw lighting in the unmasked areas
4383                 R_Shadow_RenderMode_Lighting(false, false, true);
4384                 // draw lighting in the unmasked areas
4385                 if (numsurfaces)
4386                         R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4387                 for (i = 0;i < numlightentities;i++)
4388                         R_Shadow_DrawEntityLight(lightentities[i]);
4389         }
4390         else if (castshadows && vid.stencil)
4391         {
4392                 // draw stencil shadow volumes to mask off pixels that are in shadow
4393                 // so that they won't receive lighting
4394                 GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
4395                 R_Shadow_ClearStencil();
4396
4397                 if (numsurfaces)
4398                         R_Shadow_DrawWorldShadow_ShadowVolume(numsurfaces, surfacelist, shadowtrispvs);
4399                 for (i = 0;i < numshadowentities;i++)
4400                         R_Shadow_DrawEntityShadow(shadowentities[i]);
4401
4402                 // draw lighting in the unmasked areas
4403                 R_Shadow_RenderMode_Lighting(true, false, false);
4404                 for (i = 0;i < numlightentities_noselfshadow;i++)
4405                         R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4406
4407                 for (i = 0;i < numshadowentities_noselfshadow;i++)
4408                         R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4409
4410                 // draw lighting in the unmasked areas
4411                 R_Shadow_RenderMode_Lighting(true, false, false);
4412                 if (numsurfaces)
4413                         R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4414                 for (i = 0;i < numlightentities;i++)
4415                         R_Shadow_DrawEntityLight(lightentities[i]);
4416         }
4417         else
4418         {
4419                 // draw lighting in the unmasked areas
4420                 R_Shadow_RenderMode_Lighting(false, false, false);
4421                 if (numsurfaces)
4422                         R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4423                 for (i = 0;i < numlightentities;i++)
4424                         R_Shadow_DrawEntityLight(lightentities[i]);
4425                 for (i = 0;i < numlightentities_noselfshadow;i++)
4426                         R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4427         }
4428
4429         if (r_shadow_usingdeferredprepass)
4430         {
4431                 // when rendering deferred lighting, we simply rasterize the box
4432                 if (castshadows && r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D)
4433                         R_Shadow_RenderMode_DrawDeferredLight(false, true);
4434                 else if (castshadows && vid.stencil)
4435                         R_Shadow_RenderMode_DrawDeferredLight(true, false);
4436                 else
4437                         R_Shadow_RenderMode_DrawDeferredLight(false, false);
4438         }
4439 }
4440
4441 static void R_Shadow_FreeDeferred(void)
4442 {
4443         R_Mesh_DestroyFramebufferObject(r_shadow_prepassgeometryfbo);
4444         r_shadow_prepassgeometryfbo = 0;
4445
4446         R_Mesh_DestroyFramebufferObject(r_shadow_prepasslightingdiffusespecularfbo);
4447         r_shadow_prepasslightingdiffusespecularfbo = 0;
4448
4449         R_Mesh_DestroyFramebufferObject(r_shadow_prepasslightingdiffusefbo);
4450         r_shadow_prepasslightingdiffusefbo = 0;
4451
4452         if (r_shadow_prepassgeometrydepthtexture)
4453                 R_FreeTexture(r_shadow_prepassgeometrydepthtexture);
4454         r_shadow_prepassgeometrydepthtexture = NULL;
4455
4456         if (r_shadow_prepassgeometrydepthcolortexture)
4457                 R_FreeTexture(r_shadow_prepassgeometrydepthcolortexture);
4458         r_shadow_prepassgeometrydepthcolortexture = NULL;
4459
4460         if (r_shadow_prepassgeometrynormalmaptexture)
4461                 R_FreeTexture(r_shadow_prepassgeometrynormalmaptexture);
4462         r_shadow_prepassgeometrynormalmaptexture = NULL;
4463
4464         if (r_shadow_prepasslightingdiffusetexture)
4465                 R_FreeTexture(r_shadow_prepasslightingdiffusetexture);
4466         r_shadow_prepasslightingdiffusetexture = NULL;
4467
4468         if (r_shadow_prepasslightingspeculartexture)
4469                 R_FreeTexture(r_shadow_prepasslightingspeculartexture);
4470         r_shadow_prepasslightingspeculartexture = NULL;
4471 }
4472
4473 void R_Shadow_DrawPrepass(void)
4474 {
4475         int i;
4476         int flag;
4477         int lnum;
4478         size_t lightindex;
4479         dlight_t *light;
4480         size_t range;
4481         entity_render_t *ent;
4482         float clearcolor[4];
4483
4484         R_Mesh_ResetTextureState();
4485         GL_DepthMask(true);
4486         GL_ColorMask(1,1,1,1);
4487         GL_BlendFunc(GL_ONE, GL_ZERO);
4488         GL_Color(1,1,1,1);
4489         GL_DepthTest(true);
4490         R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepassgeometrynormalmaptexture, r_shadow_prepassgeometrydepthcolortexture, NULL, NULL);
4491         Vector4Set(clearcolor, 0.5f,0.5f,0.5f,1.0f);
4492         GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4493         if (r_timereport_active)
4494                 R_TimeReport("prepasscleargeom");
4495
4496         if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawPrepass)
4497                 r_refdef.scene.worldmodel->DrawPrepass(r_refdef.scene.worldentity);
4498         if (r_timereport_active)
4499                 R_TimeReport("prepassworld");
4500
4501         for (i = 0;i < r_refdef.scene.numentities;i++)
4502         {
4503                 if (!r_refdef.viewcache.entityvisible[i])
4504                         continue;
4505                 ent = r_refdef.scene.entities[i];
4506                 if (ent->model && ent->model->DrawPrepass != NULL)
4507                         ent->model->DrawPrepass(ent);
4508         }
4509
4510         if (r_timereport_active)
4511                 R_TimeReport("prepassmodels");
4512
4513         GL_DepthMask(false);
4514         GL_ColorMask(1,1,1,1);
4515         GL_Color(1,1,1,1);
4516         GL_DepthTest(true);
4517         R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4518         Vector4Set(clearcolor, 0, 0, 0, 0);
4519         GL_Clear(GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
4520         if (r_timereport_active)
4521                 R_TimeReport("prepassclearlit");
4522
4523         R_Shadow_RenderMode_Begin();
4524
4525         flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4526         if (r_shadow_debuglight.integer >= 0)
4527         {
4528                 lightindex = r_shadow_debuglight.integer;
4529                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4530                 if (light && (light->flags & flag) && light->rtlight.draw)
4531                         R_Shadow_DrawLight(&light->rtlight);
4532         }
4533         else
4534         {
4535                 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4536                 for (lightindex = 0;lightindex < range;lightindex++)
4537                 {
4538                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4539                         if (light && (light->flags & flag) && light->rtlight.draw)
4540                                 R_Shadow_DrawLight(&light->rtlight);
4541                 }
4542         }
4543         if (r_refdef.scene.rtdlight)
4544                 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4545                         if (r_refdef.scene.lights[lnum]->draw)
4546                                 R_Shadow_DrawLight(r_refdef.scene.lights[lnum]);
4547
4548         R_Mesh_SetMainRenderTargets();
4549
4550         R_Shadow_RenderMode_End();
4551
4552         if (r_timereport_active)
4553                 R_TimeReport("prepasslights");
4554 }
4555
4556 void R_Shadow_DrawLightSprites(void);
4557 void R_Shadow_PrepareLights(void)
4558 {
4559         int flag;
4560         int lnum;
4561         size_t lightindex;
4562         dlight_t *light;
4563         size_t range;
4564         float f;
4565         GLenum status;
4566
4567         if (r_shadow_shadowmapmaxsize != bound(1, r_shadow_shadowmapping_maxsize.integer, (int)vid.maxtexturesize_2d / 4) ||
4568                 (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL) != (r_shadow_shadowmapping.integer || r_shadow_deferred.integer) ||
4569                 r_shadow_shadowmapvsdct != (r_shadow_shadowmapping_vsdct.integer != 0 && vid.renderpath == RENDERPATH_GL20) || 
4570                 r_shadow_shadowmapfilterquality != r_shadow_shadowmapping_filterquality.integer || 
4571                 r_shadow_shadowmapdepthbits != r_shadow_shadowmapping_depthbits.integer || 
4572                 r_shadow_shadowmapborder != bound(0, r_shadow_shadowmapping_bordersize.integer, 16))
4573                 R_Shadow_FreeShadowMaps();
4574
4575         r_shadow_usingshadowmaportho = false;
4576
4577         switch (vid.renderpath)
4578         {
4579         case RENDERPATH_GL20:
4580         case RENDERPATH_D3D9:
4581         case RENDERPATH_D3D10:
4582         case RENDERPATH_D3D11:
4583         case RENDERPATH_SOFT:
4584         case RENDERPATH_GLES2:
4585                 if (!r_shadow_deferred.integer || r_shadow_shadowmode == R_SHADOW_SHADOWMODE_STENCIL || !vid.support.ext_framebuffer_object || vid.maxdrawbuffers < 2)
4586                 {
4587                         r_shadow_usingdeferredprepass = false;
4588                         if (r_shadow_prepass_width)
4589                                 R_Shadow_FreeDeferred();
4590                         r_shadow_prepass_width = r_shadow_prepass_height = 0;
4591                         break;
4592                 }
4593
4594                 if (r_shadow_prepass_width != vid.width || r_shadow_prepass_height != vid.height)
4595                 {
4596                         R_Shadow_FreeDeferred();
4597
4598                         r_shadow_usingdeferredprepass = true;
4599                         r_shadow_prepass_width = vid.width;
4600                         r_shadow_prepass_height = vid.height;
4601                         r_shadow_prepassgeometrydepthtexture = R_LoadTextureShadowMap2D(r_shadow_texturepool, "prepassgeometrydepthmap", vid.width, vid.height, 24, false);
4602                         switch (vid.renderpath)
4603                         {
4604                         case RENDERPATH_D3D9:
4605                                 r_shadow_prepassgeometrydepthcolortexture = R_LoadTexture2D(r_shadow_texturepool, "prepassgeometrydepthcolormap", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4606                                 break;
4607                         default:
4608                                 break;
4609                         }
4610                         r_shadow_prepassgeometrynormalmaptexture = R_LoadTexture2D(r_shadow_texturepool, "prepassgeometrynormalmap", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4611                         r_shadow_prepasslightingdiffusetexture = R_LoadTexture2D(r_shadow_texturepool, "prepasslightingdiffuse", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4612                         r_shadow_prepasslightingspeculartexture = R_LoadTexture2D(r_shadow_texturepool, "prepasslightingspecular", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4613
4614                         // set up the geometry pass fbo (depth + normalmap)
4615                         r_shadow_prepassgeometryfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthtexture, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL);
4616                         R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepassgeometrynormalmaptexture, r_shadow_prepassgeometrydepthcolortexture, NULL, NULL);
4617                         // render depth into one texture and normalmap into the other
4618                         if (qglDrawBuffersARB)
4619                         {
4620                                 qglDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);CHECKGLERROR
4621                                 qglReadBuffer(GL_NONE);CHECKGLERROR
4622                                 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
4623                                 if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
4624                                 {
4625                                         Con_Printf("R_PrepareRTLights: glCheckFramebufferStatusEXT returned %i\n", status);
4626                                         Cvar_SetValueQuick(&r_shadow_deferred, 0);
4627                                         r_shadow_usingdeferredprepass = false;
4628                                 }
4629                         }
4630
4631                         // set up the lighting pass fbo (diffuse + specular)
4632                         r_shadow_prepasslightingdiffusespecularfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4633                         R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4634                         // render diffuse into one texture and specular into another,
4635                         // with depth and normalmap bound as textures,
4636                         // with depth bound as attachment as well
4637                         if (qglDrawBuffersARB)
4638                         {
4639                                 qglDrawBuffersARB(2, r_shadow_prepasslightingdrawbuffers);CHECKGLERROR
4640                                 qglReadBuffer(GL_NONE);CHECKGLERROR
4641                                 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
4642                                 if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
4643                                 {
4644                                         Con_Printf("R_PrepareRTLights: glCheckFramebufferStatusEXT returned %i\n", status);
4645                                         Cvar_SetValueQuick(&r_shadow_deferred, 0);
4646                                         r_shadow_usingdeferredprepass = false;
4647                                 }
4648                         }
4649
4650                         // set up the lighting pass fbo (diffuse)
4651                         r_shadow_prepasslightingdiffusefbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
4652                         R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
4653                         // render diffuse into one texture,
4654                         // with depth and normalmap bound as textures,
4655                         // with depth bound as attachment as well
4656                         if (qglDrawBuffersARB)
4657                         {
4658                                 qglDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);CHECKGLERROR
4659                                 qglReadBuffer(GL_NONE);CHECKGLERROR
4660                                 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
4661                                 if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
4662                                 {
4663                                         Con_Printf("R_PrepareRTLights: glCheckFramebufferStatusEXT returned %i\n", status);
4664                                         Cvar_SetValueQuick(&r_shadow_deferred, 0);
4665                                         r_shadow_usingdeferredprepass = false;
4666                                 }
4667                         }
4668                 }
4669                 break;
4670         case RENDERPATH_GL11:
4671         case RENDERPATH_GL13:
4672         case RENDERPATH_GLES1:
4673                 r_shadow_usingdeferredprepass = false;
4674                 break;
4675         }
4676
4677         R_Shadow_EnlargeLeafSurfaceTrisBuffer(r_refdef.scene.worldmodel->brush.num_leafs, r_refdef.scene.worldmodel->num_surfaces, r_refdef.scene.worldmodel->brush.shadowmesh ? r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles : r_refdef.scene.worldmodel->surfmesh.num_triangles, r_refdef.scene.worldmodel->surfmesh.num_triangles);
4678
4679         flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4680         if (r_shadow_debuglight.integer >= 0)
4681         {
4682                 lightindex = r_shadow_debuglight.integer;
4683                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4684                 if (light && (light->flags & flag))
4685                         R_Shadow_PrepareLight(&light->rtlight);
4686         }
4687         else
4688         {
4689                 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4690                 for (lightindex = 0;lightindex < range;lightindex++)
4691                 {
4692                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4693                         if (light && (light->flags & flag))
4694                                 R_Shadow_PrepareLight(&light->rtlight);
4695                 }
4696         }
4697         if (r_refdef.scene.rtdlight)
4698         {
4699                 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4700                         R_Shadow_PrepareLight(r_refdef.scene.lights[lnum]);
4701         }
4702         else if(gl_flashblend.integer)
4703         {
4704                 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4705                 {
4706                         rtlight_t *rtlight = r_refdef.scene.lights[lnum];
4707                         f = (rtlight->style >= 0 ? r_refdef.scene.lightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value;
4708                         VectorScale(rtlight->color, f, rtlight->currentcolor);
4709                 }
4710         }
4711
4712         if (r_editlights.integer)
4713                 R_Shadow_DrawLightSprites();
4714
4715         R_Shadow_UpdateBounceGridTexture();
4716 }
4717
4718 void R_Shadow_DrawLights(void)
4719 {
4720         int flag;
4721         int lnum;
4722         size_t lightindex;
4723         dlight_t *light;
4724         size_t range;
4725
4726         R_Shadow_RenderMode_Begin();
4727
4728         flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4729         if (r_shadow_debuglight.integer >= 0)
4730         {
4731                 lightindex = r_shadow_debuglight.integer;
4732                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4733                 if (light && (light->flags & flag))
4734                         R_Shadow_DrawLight(&light->rtlight);
4735         }
4736         else
4737         {
4738                 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4739                 for (lightindex = 0;lightindex < range;lightindex++)
4740                 {
4741                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4742                         if (light && (light->flags & flag))
4743                                 R_Shadow_DrawLight(&light->rtlight);
4744                 }
4745         }
4746         if (r_refdef.scene.rtdlight)
4747                 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4748                         R_Shadow_DrawLight(r_refdef.scene.lights[lnum]);
4749
4750         R_Shadow_RenderMode_End();
4751 }
4752
4753 extern const float r_screenvertex3f[12];
4754 extern void R_SetupView(qboolean allowwaterclippingplane);
4755 extern void R_ResetViewRendering3D(void);
4756 extern void R_ResetViewRendering2D(void);
4757 extern cvar_t r_shadows;
4758 extern cvar_t r_shadows_darken;
4759 extern cvar_t r_shadows_drawafterrtlighting;
4760 extern cvar_t r_shadows_castfrombmodels;
4761 extern cvar_t r_shadows_throwdistance;
4762 extern cvar_t r_shadows_throwdirection;
4763 extern cvar_t r_shadows_focus;
4764 extern cvar_t r_shadows_shadowmapscale;
4765
4766 void R_Shadow_PrepareModelShadows(void)
4767 {
4768         int i;
4769         float scale, size, radius, dot1, dot2;
4770         vec3_t shadowdir, shadowforward, shadowright, shadoworigin, shadowfocus, shadowmins, shadowmaxs;
4771         entity_render_t *ent;
4772
4773         if (!r_refdef.scene.numentities)
4774                 return;
4775
4776         switch (r_shadow_shadowmode)
4777         {
4778         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4779                 if (r_shadows.integer >= 2) 
4780                         break;
4781                 // fall through
4782         case R_SHADOW_SHADOWMODE_STENCIL:
4783                 for (i = 0;i < r_refdef.scene.numentities;i++)
4784                 {
4785                         ent = r_refdef.scene.entities[i];
4786                         if (!ent->animcache_vertex3f && ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4787                                 R_AnimCache_GetEntity(ent, false, false);
4788                 }
4789                 return;
4790         default:
4791                 return;
4792         }
4793
4794         size = 2*r_shadow_shadowmapmaxsize;
4795         scale = r_shadow_shadowmapping_precision.value * r_shadows_shadowmapscale.value;
4796         radius = 0.5f * size / scale;
4797
4798         Math_atov(r_shadows_throwdirection.string, shadowdir);
4799         VectorNormalize(shadowdir);
4800         dot1 = DotProduct(r_refdef.view.forward, shadowdir);
4801         dot2 = DotProduct(r_refdef.view.up, shadowdir);
4802         if (fabs(dot1) <= fabs(dot2))
4803                 VectorMA(r_refdef.view.forward, -dot1, shadowdir, shadowforward);
4804         else
4805                 VectorMA(r_refdef.view.up, -dot2, shadowdir, shadowforward);
4806         VectorNormalize(shadowforward);
4807         CrossProduct(shadowdir, shadowforward, shadowright);
4808         Math_atov(r_shadows_focus.string, shadowfocus);
4809         VectorM(shadowfocus[0], r_refdef.view.right, shadoworigin);
4810         VectorMA(shadoworigin, shadowfocus[1], r_refdef.view.up, shadoworigin);
4811         VectorMA(shadoworigin, -shadowfocus[2], r_refdef.view.forward, shadoworigin);
4812         VectorAdd(shadoworigin, r_refdef.view.origin, shadoworigin);
4813         if (shadowfocus[0] || shadowfocus[1] || shadowfocus[2])
4814                 dot1 = 1;
4815         VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin);
4816
4817         shadowmins[0] = shadoworigin[0] - r_shadows_throwdistance.value * fabs(shadowdir[0]) - radius * (fabs(shadowforward[0]) + fabs(shadowright[0]));
4818         shadowmins[1] = shadoworigin[1] - r_shadows_throwdistance.value * fabs(shadowdir[1]) - radius * (fabs(shadowforward[1]) + fabs(shadowright[1]));
4819         shadowmins[2] = shadoworigin[2] - r_shadows_throwdistance.value * fabs(shadowdir[2]) - radius * (fabs(shadowforward[2]) + fabs(shadowright[2]));
4820         shadowmaxs[0] = shadoworigin[0] + r_shadows_throwdistance.value * fabs(shadowdir[0]) + radius * (fabs(shadowforward[0]) + fabs(shadowright[0]));
4821         shadowmaxs[1] = shadoworigin[1] + r_shadows_throwdistance.value * fabs(shadowdir[1]) + radius * (fabs(shadowforward[1]) + fabs(shadowright[1]));
4822         shadowmaxs[2] = shadoworigin[2] + r_shadows_throwdistance.value * fabs(shadowdir[2]) + radius * (fabs(shadowforward[2]) + fabs(shadowright[2]));
4823
4824         for (i = 0;i < r_refdef.scene.numentities;i++)
4825         {
4826                 ent = r_refdef.scene.entities[i];
4827                 if (!BoxesOverlap(ent->mins, ent->maxs, shadowmins, shadowmaxs))
4828                         continue;
4829                 // cast shadows from anything of the map (submodels are optional)
4830                 if (!ent->animcache_vertex3f && ent->model && ent->model->DrawShadowMap != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4831                         R_AnimCache_GetEntity(ent, false, false);
4832         }
4833 }
4834
4835 void R_DrawModelShadowMaps(void)
4836 {
4837         int i;
4838         float relativethrowdistance, scale, size, radius, nearclip, farclip, bias, dot1, dot2;
4839         entity_render_t *ent;
4840         vec3_t relativelightorigin;
4841         vec3_t relativelightdirection, relativeforward, relativeright;
4842         vec3_t relativeshadowmins, relativeshadowmaxs;
4843         vec3_t shadowdir, shadowforward, shadowright, shadoworigin, shadowfocus;
4844         float m[12];
4845         matrix4x4_t shadowmatrix, cameramatrix, mvpmatrix, invmvpmatrix, scalematrix, texmatrix;
4846         r_viewport_t viewport;
4847         GLuint fbo = 0;
4848         float clearcolor[4];
4849
4850         if (!r_refdef.scene.numentities)
4851                 return;
4852
4853         switch (r_shadow_shadowmode)
4854         {
4855         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4856                 break;
4857         default:
4858                 return;
4859         }
4860
4861         R_ResetViewRendering3D();
4862         R_Shadow_RenderMode_Begin();
4863         R_Shadow_RenderMode_ActiveLight(NULL);
4864
4865         switch (r_shadow_shadowmode)
4866         {
4867         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4868                 if (!r_shadow_shadowmap2dtexture)
4869                         R_Shadow_MakeShadowMap(0, r_shadow_shadowmapmaxsize);
4870                 fbo = r_shadow_fbo2d;
4871                 r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2dtexture);
4872                 r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2dtexture);
4873                 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
4874                 break;
4875         default:
4876                 break;
4877         }
4878
4879         size = 2*r_shadow_shadowmapmaxsize;
4880         scale = (r_shadow_shadowmapping_precision.value * r_shadows_shadowmapscale.value) / size;
4881         radius = 0.5f / scale;
4882         nearclip = -r_shadows_throwdistance.value;
4883         farclip = r_shadows_throwdistance.value;
4884         bias = r_shadow_shadowmapping_bias.value * r_shadow_shadowmapping_nearclip.value / (2 * r_shadows_throwdistance.value) * (1024.0f / size);
4885
4886         r_shadow_shadowmap_parameters[0] = size;
4887         r_shadow_shadowmap_parameters[1] = size;
4888         r_shadow_shadowmap_parameters[2] = 1.0;
4889         r_shadow_shadowmap_parameters[3] = bound(0.0f, 1.0f - r_shadows_darken.value, 1.0f);
4890
4891         Math_atov(r_shadows_throwdirection.string, shadowdir);
4892         VectorNormalize(shadowdir);
4893         Math_atov(r_shadows_focus.string, shadowfocus);
4894         VectorM(shadowfocus[0], r_refdef.view.right, shadoworigin);
4895         VectorMA(shadoworigin, shadowfocus[1], r_refdef.view.up, shadoworigin);
4896         VectorMA(shadoworigin, -shadowfocus[2], r_refdef.view.forward, shadoworigin);
4897         VectorAdd(shadoworigin, r_refdef.view.origin, shadoworigin);
4898         dot1 = DotProduct(r_refdef.view.forward, shadowdir);
4899         dot2 = DotProduct(r_refdef.view.up, shadowdir);
4900         if (fabs(dot1) <= fabs(dot2)) 
4901                 VectorMA(r_refdef.view.forward, -dot1, shadowdir, shadowforward);
4902         else
4903                 VectorMA(r_refdef.view.up, -dot2, shadowdir, shadowforward);
4904         VectorNormalize(shadowforward);
4905         VectorM(scale, shadowforward, &m[0]);
4906         if (shadowfocus[0] || shadowfocus[1] || shadowfocus[2])
4907                 dot1 = 1;
4908         m[3] = fabs(dot1) * 0.5f - DotProduct(shadoworigin, &m[0]);
4909         CrossProduct(shadowdir, shadowforward, shadowright);
4910         VectorM(scale, shadowright, &m[4]);
4911         m[7] = 0.5f - DotProduct(shadoworigin, &m[4]);
4912         VectorM(1.0f / (farclip - nearclip), shadowdir, &m[8]);
4913         m[11] = 0.5f - DotProduct(shadoworigin, &m[8]);
4914         Matrix4x4_FromArray12FloatD3D(&shadowmatrix, m);
4915         Matrix4x4_Invert_Full(&cameramatrix, &shadowmatrix);
4916         R_Viewport_InitOrtho(&viewport, &cameramatrix, 0, 0, size, size, 0, 0, 1, 1, 0, -1, NULL); 
4917
4918         VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin);
4919
4920         R_Mesh_SetRenderTargets(fbo, r_shadow_shadowmap2dtexture, r_shadow_shadowmap2dcolortexture, NULL, NULL, NULL);
4921         R_SetupShader_DepthOrShadow();
4922         GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
4923         GL_DepthMask(true);
4924         GL_DepthTest(true);
4925         R_SetViewport(&viewport);
4926         GL_Scissor(viewport.x, viewport.y, min(viewport.width + r_shadow_shadowmapborder, 2*r_shadow_shadowmapmaxsize), viewport.height + r_shadow_shadowmapborder);
4927         Vector4Set(clearcolor, 1,1,1,1);
4928         // in D3D9 we have to render to a color texture shadowmap
4929         // in GL we render directly to a depth texture only
4930         if (r_shadow_shadowmap2dtexture)
4931                 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4932         else
4933                 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4934         // render into a slightly restricted region so that the borders of the
4935         // shadowmap area fade away, rather than streaking across everything
4936         // outside the usable area
4937         GL_Scissor(viewport.x + r_shadow_shadowmapborder, viewport.y + r_shadow_shadowmapborder, viewport.width - 2*r_shadow_shadowmapborder, viewport.height - 2*r_shadow_shadowmapborder);
4938
4939 #if 0
4940         // debugging
4941         R_Mesh_SetMainRenderTargets();
4942         R_SetupShader_ShowDepth();
4943         GL_ColorMask(1,1,1,1);
4944         GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4945 #endif
4946
4947         for (i = 0;i < r_refdef.scene.numentities;i++)
4948         {
4949                 ent = r_refdef.scene.entities[i];
4950
4951                 // cast shadows from anything of the map (submodels are optional)
4952                 if (ent->model && ent->model->DrawShadowMap != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4953                 {
4954                         relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix);
4955                         Matrix4x4_Transform(&ent->inversematrix, shadoworigin, relativelightorigin);
4956                         Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection);
4957                         Matrix4x4_Transform3x3(&ent->inversematrix, shadowforward, relativeforward);
4958                         Matrix4x4_Transform3x3(&ent->inversematrix, shadowright, relativeright);
4959                         relativeshadowmins[0] = relativelightorigin[0] - r_shadows_throwdistance.value * fabs(relativelightdirection[0]) - radius * (fabs(relativeforward[0]) + fabs(relativeright[0]));
4960                         relativeshadowmins[1] = relativelightorigin[1] - r_shadows_throwdistance.value * fabs(relativelightdirection[1]) - radius * (fabs(relativeforward[1]) + fabs(relativeright[1]));
4961                         relativeshadowmins[2] = relativelightorigin[2] - r_shadows_throwdistance.value * fabs(relativelightdirection[2]) - radius * (fabs(relativeforward[2]) + fabs(relativeright[2]));
4962                         relativeshadowmaxs[0] = relativelightorigin[0] + r_shadows_throwdistance.value * fabs(relativelightdirection[0]) + radius * (fabs(relativeforward[0]) + fabs(relativeright[0]));
4963                         relativeshadowmaxs[1] = relativelightorigin[1] + r_shadows_throwdistance.value * fabs(relativelightdirection[1]) + radius * (fabs(relativeforward[1]) + fabs(relativeright[1]));
4964                         relativeshadowmaxs[2] = relativelightorigin[2] + r_shadows_throwdistance.value * fabs(relativelightdirection[2]) + radius * (fabs(relativeforward[2]) + fabs(relativeright[2]));
4965                         RSurf_ActiveModelEntity(ent, false, false, false);
4966                         ent->model->DrawShadowMap(0, ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, NULL, relativeshadowmins, relativeshadowmaxs);
4967                         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
4968                 }
4969         }
4970
4971 #if 0
4972         if (r_test.integer)
4973         {
4974                 unsigned char *rawpixels = Z_Malloc(viewport.width*viewport.height*4);
4975                 CHECKGLERROR
4976                 qglReadPixels(viewport.x, viewport.y, viewport.width, viewport.height, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, rawpixels);
4977                 CHECKGLERROR
4978                 Image_WriteTGABGRA("r_shadows_2.tga", viewport.width, viewport.height, rawpixels);
4979                 Cvar_SetValueQuick(&r_test, 0);
4980                 Z_Free(rawpixels);
4981         }
4982 #endif
4983
4984         R_Shadow_RenderMode_End();
4985
4986         Matrix4x4_Concat(&mvpmatrix, &r_refdef.view.viewport.projectmatrix, &r_refdef.view.viewport.viewmatrix);
4987         Matrix4x4_Invert_Full(&invmvpmatrix, &mvpmatrix);
4988         Matrix4x4_CreateScale3(&scalematrix, size, -size, 1); 
4989         Matrix4x4_AdjustOrigin(&scalematrix, 0, size, -0.5f * bias);
4990         Matrix4x4_Concat(&texmatrix, &scalematrix, &shadowmatrix);
4991         Matrix4x4_Concat(&r_shadow_shadowmapmatrix, &texmatrix, &invmvpmatrix);
4992
4993         switch (vid.renderpath)
4994         {
4995         case RENDERPATH_GL11:
4996         case RENDERPATH_GL13:
4997         case RENDERPATH_GL20:
4998         case RENDERPATH_SOFT:
4999         case RENDERPATH_GLES1:
5000         case RENDERPATH_GLES2:
5001                 break;
5002         case RENDERPATH_D3D9:
5003         case RENDERPATH_D3D10:
5004         case RENDERPATH_D3D11:
5005 #ifdef OPENGL_ORIENTATION
5006                 r_shadow_shadowmapmatrix.m[0][0]        *= -1.0f;
5007                 r_shadow_shadowmapmatrix.m[0][1]        *= -1.0f;
5008                 r_shadow_shadowmapmatrix.m[0][2]        *= -1.0f;
5009                 r_shadow_shadowmapmatrix.m[0][3]        *= -1.0f;
5010 #else
5011                 r_shadow_shadowmapmatrix.m[0][0]        *= -1.0f;
5012                 r_shadow_shadowmapmatrix.m[1][0]        *= -1.0f;
5013                 r_shadow_shadowmapmatrix.m[2][0]        *= -1.0f;
5014                 r_shadow_shadowmapmatrix.m[3][0]        *= -1.0f;
5015 #endif
5016                 break;
5017         }
5018
5019         r_shadow_usingshadowmaportho = true;
5020         switch (r_shadow_shadowmode)
5021         {
5022         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
5023                 r_shadow_usingshadowmap2d = true;
5024                 break;
5025         default:
5026                 break;
5027         }
5028 }
5029
5030 void R_DrawModelShadows(void)
5031 {
5032         int i;
5033         float relativethrowdistance;
5034         entity_render_t *ent;
5035         vec3_t relativelightorigin;
5036         vec3_t relativelightdirection;
5037         vec3_t relativeshadowmins, relativeshadowmaxs;
5038         vec3_t tmp, shadowdir;
5039
5040         if (!r_refdef.scene.numentities || !vid.stencil || (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL && r_shadows.integer != 1))
5041                 return;
5042
5043         R_ResetViewRendering3D();
5044         //GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
5045         //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
5046         R_Shadow_RenderMode_Begin();
5047         R_Shadow_RenderMode_ActiveLight(NULL);
5048         r_shadow_lightscissor[0] = r_refdef.view.x;
5049         r_shadow_lightscissor[1] = vid.height - r_refdef.view.y - r_refdef.view.height;
5050         r_shadow_lightscissor[2] = r_refdef.view.width;
5051         r_shadow_lightscissor[3] = r_refdef.view.height;
5052         R_Shadow_RenderMode_StencilShadowVolumes(false);
5053
5054         // get shadow dir
5055         if (r_shadows.integer == 2)
5056         {
5057                 Math_atov(r_shadows_throwdirection.string, shadowdir);
5058                 VectorNormalize(shadowdir);
5059         }
5060
5061         R_Shadow_ClearStencil();
5062
5063         for (i = 0;i < r_refdef.scene.numentities;i++)
5064         {
5065                 ent = r_refdef.scene.entities[i];
5066
5067                 // cast shadows from anything of the map (submodels are optional)
5068                 if (ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
5069                 {
5070                         relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix);
5071                         VectorSet(relativeshadowmins, -relativethrowdistance, -relativethrowdistance, -relativethrowdistance);
5072                         VectorSet(relativeshadowmaxs, relativethrowdistance, relativethrowdistance, relativethrowdistance);
5073                         if (r_shadows.integer == 2) // 2: simpler mode, throw shadows always in same direction
5074                                 Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection);
5075                         else
5076                         {
5077                                 if(ent->entitynumber != 0)
5078                                 {
5079                                         if(ent->entitynumber >= MAX_EDICTS) // csqc entity
5080                                         {
5081                                                 // FIXME handle this
5082                                                 VectorNegate(ent->modellight_lightdir, relativelightdirection);
5083                                         }
5084                                         else
5085                                         {
5086                                                 // networked entity - might be attached in some way (then we should use the parent's light direction, to not tear apart attached entities)
5087                                                 int entnum, entnum2, recursion;
5088                                                 entnum = entnum2 = ent->entitynumber;
5089                                                 for(recursion = 32; recursion > 0; --recursion)
5090                                                 {
5091                                                         entnum2 = cl.entities[entnum].state_current.tagentity;
5092                                                         if(entnum2 >= 1 && entnum2 < cl.num_entities && cl.entities_active[entnum2])
5093                                                                 entnum = entnum2;
5094                                                         else
5095                                                                 break;
5096                                                 }
5097                                                 if(recursion && recursion != 32) // if we followed a valid non-empty attachment chain
5098                                                 {
5099                                                         VectorNegate(cl.entities[entnum].render.modellight_lightdir, relativelightdirection);
5100                                                         // transform into modelspace of OUR entity
5101                                                         Matrix4x4_Transform3x3(&cl.entities[entnum].render.matrix, relativelightdirection, tmp);
5102                                                         Matrix4x4_Transform3x3(&ent->inversematrix, tmp, relativelightdirection);
5103                                                 }
5104                                                 else
5105                                                         VectorNegate(ent->modellight_lightdir, relativelightdirection);
5106                                         }
5107                                 }
5108                                 else
5109                                         VectorNegate(ent->modellight_lightdir, relativelightdirection);
5110                         }
5111
5112                         VectorScale(relativelightdirection, -relativethrowdistance, relativelightorigin);
5113                         RSurf_ActiveModelEntity(ent, false, false, false);
5114                         ent->model->DrawShadowVolume(ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
5115                         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
5116                 }
5117         }
5118
5119         // not really the right mode, but this will disable any silly stencil features
5120         R_Shadow_RenderMode_End();
5121
5122         // set up ortho view for rendering this pass
5123         //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
5124         //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5125         //GL_ScissorTest(true);
5126         //R_EntityMatrix(&identitymatrix);
5127         //R_Mesh_ResetTextureState();
5128         R_ResetViewRendering2D();
5129
5130         // set up a darkening blend on shadowed areas
5131         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
5132         //GL_DepthRange(0, 1);
5133         //GL_DepthTest(false);
5134         //GL_DepthMask(false);
5135         //GL_PolygonOffset(0, 0);CHECKGLERROR
5136         GL_Color(0, 0, 0, r_shadows_darken.value);
5137         //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5138         //GL_DepthFunc(GL_ALWAYS);
5139         R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_NOTEQUAL, 128, 255);
5140
5141         // apply the blend to the shadowed areas
5142         R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
5143         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
5144         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5145
5146         // restore the viewport
5147         R_SetViewport(&r_refdef.view.viewport);
5148
5149         // restore other state to normal
5150         //R_Shadow_RenderMode_End();
5151 }
5152
5153 void R_BeginCoronaQuery(rtlight_t *rtlight, float scale, qboolean usequery)
5154 {
5155         float zdist;
5156         vec3_t centerorigin;
5157         float vertex3f[12];
5158         // if it's too close, skip it
5159         if (VectorLength(rtlight->currentcolor) < (1.0f / 256.0f))
5160                 return;
5161         zdist = (DotProduct(rtlight->shadoworigin, r_refdef.view.forward) - DotProduct(r_refdef.view.origin, r_refdef.view.forward));
5162         if (zdist < 32)
5163                 return;
5164         if (usequery && r_numqueries + 2 <= r_maxqueries)
5165         {
5166                 rtlight->corona_queryindex_allpixels = r_queries[r_numqueries++];
5167                 rtlight->corona_queryindex_visiblepixels = r_queries[r_numqueries++];
5168                 // we count potential samples in the middle of the screen, we count actual samples at the light location, this allows counting potential samples of off-screen lights
5169                 VectorMA(r_refdef.view.origin, zdist, r_refdef.view.forward, centerorigin);
5170
5171                 switch(vid.renderpath)
5172                 {
5173                 case RENDERPATH_GL11:
5174                 case RENDERPATH_GL13:
5175                 case RENDERPATH_GL20:
5176                 case RENDERPATH_GLES1:
5177                 case RENDERPATH_GLES2:
5178                         CHECKGLERROR
5179                         // NOTE: GL_DEPTH_TEST must be enabled or ATI won't count samples, so use GL_DepthFunc instead
5180                         qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_allpixels);
5181                         GL_DepthFunc(GL_ALWAYS);
5182                         R_CalcSprite_Vertex3f(vertex3f, centerorigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5183                         R_Mesh_PrepareVertices_Vertex3f(4, vertex3f, NULL);
5184                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5185                         qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
5186                         GL_DepthFunc(GL_LEQUAL);
5187                         qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_visiblepixels);
5188                         R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5189                         R_Mesh_PrepareVertices_Vertex3f(4, vertex3f, NULL);
5190                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5191                         qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
5192                         CHECKGLERROR
5193                         break;
5194                 case RENDERPATH_D3D9:
5195                         Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5196                         break;
5197                 case RENDERPATH_D3D10:
5198                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5199                         break;
5200                 case RENDERPATH_D3D11:
5201                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5202                         break;
5203                 case RENDERPATH_SOFT:
5204                         //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5205                         break;
5206                 }
5207         }
5208         rtlight->corona_visibility = bound(0, (zdist - 32) / 32, 1);
5209 }
5210
5211 static float spritetexcoord2f[4*2] = {0, 1, 0, 0, 1, 0, 1, 1};
5212
5213 void R_DrawCorona(rtlight_t *rtlight, float cscale, float scale)
5214 {
5215         vec3_t color;
5216         GLint allpixels = 0, visiblepixels = 0;
5217         // now we have to check the query result
5218         if (rtlight->corona_queryindex_visiblepixels)
5219         {
5220                 switch(vid.renderpath)
5221                 {
5222                 case RENDERPATH_GL11:
5223                 case RENDERPATH_GL13:
5224                 case RENDERPATH_GL20:
5225                 case RENDERPATH_GLES1:
5226                 case RENDERPATH_GLES2:
5227                         CHECKGLERROR
5228                         qglGetQueryObjectivARB(rtlight->corona_queryindex_visiblepixels, GL_QUERY_RESULT_ARB, &visiblepixels);
5229                         qglGetQueryObjectivARB(rtlight->corona_queryindex_allpixels, GL_QUERY_RESULT_ARB, &allpixels);
5230                         CHECKGLERROR
5231                         break;
5232                 case RENDERPATH_D3D9:
5233                         Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5234                         break;
5235                 case RENDERPATH_D3D10:
5236                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5237                         break;
5238                 case RENDERPATH_D3D11:
5239                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5240                         break;
5241                 case RENDERPATH_SOFT:
5242                         //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5243                         break;
5244                 }
5245                 //Con_Printf("%i of %i pixels\n", (int)visiblepixels, (int)allpixels);
5246                 if (visiblepixels < 1 || allpixels < 1)
5247                         return;
5248                 rtlight->corona_visibility *= bound(0, (float)visiblepixels / (float)allpixels, 1);
5249                 cscale *= rtlight->corona_visibility;
5250         }
5251         else
5252         {
5253                 // FIXME: these traces should scan all render entities instead of cl.world
5254                 if (CL_TraceLine(r_refdef.view.origin, rtlight->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
5255                         return;
5256         }
5257         VectorScale(rtlight->currentcolor, cscale, color);
5258         if (VectorLength(color) > (1.0f / 256.0f))
5259         {
5260                 float vertex3f[12];
5261                 qboolean negated = (color[0] + color[1] + color[2] < 0) && vid.support.ext_blend_subtract;
5262                 if(negated)
5263                 {
5264                         VectorNegate(color, color);
5265                         switch(vid.renderpath)
5266                         {
5267                         case RENDERPATH_GL11:
5268                         case RENDERPATH_GL13:
5269                         case RENDERPATH_GL20:
5270                         case RENDERPATH_GLES1:
5271                         case RENDERPATH_GLES2:
5272                                 qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
5273                                 break;
5274                         case RENDERPATH_D3D9:
5275 #ifdef SUPPORTD3D
5276                                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_BLENDOP, D3DBLENDOP_SUBTRACT);
5277 #endif
5278                                 break;
5279                         case RENDERPATH_D3D10:
5280                                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5281                                 break;
5282                         case RENDERPATH_D3D11:
5283                                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5284                                 break;
5285                         case RENDERPATH_SOFT:
5286                                 DPSOFTRAST_BlendSubtract(true);
5287                                 break;
5288                         }
5289                 }
5290                 R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5291                 RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, RENDER_NODEPTHTEST, 0, color[0], color[1], color[2], 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5292                 R_DrawCustomSurface(r_shadow_lightcorona, &identitymatrix, MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5293                 if(negated)
5294                 {
5295                         switch(vid.renderpath)
5296                         {
5297                         case RENDERPATH_GL11:
5298                         case RENDERPATH_GL13:
5299                         case RENDERPATH_GL20:
5300                         case RENDERPATH_GLES1:
5301                         case RENDERPATH_GLES2:
5302                                 qglBlendEquationEXT(GL_FUNC_ADD_EXT);
5303                                 break;
5304                         case RENDERPATH_D3D9:
5305 #ifdef SUPPORTD3D
5306                                 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_BLENDOP, D3DBLENDOP_ADD);
5307 #endif
5308                                 break;
5309                         case RENDERPATH_D3D10:
5310                                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5311                                 break;
5312                         case RENDERPATH_D3D11:
5313                                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5314                                 break;
5315                         case RENDERPATH_SOFT:
5316                                 DPSOFTRAST_BlendSubtract(false);
5317                                 break;
5318                         }
5319                 }
5320         }
5321 }
5322
5323 void R_Shadow_DrawCoronas(void)
5324 {
5325         int i, flag;
5326         qboolean usequery = false;
5327         size_t lightindex;
5328         dlight_t *light;
5329         rtlight_t *rtlight;
5330         size_t range;
5331         if (r_coronas.value < (1.0f / 256.0f) && !gl_flashblend.integer)
5332                 return;
5333         if (r_waterstate.renderingscene)
5334                 return;
5335         flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
5336         R_EntityMatrix(&identitymatrix);
5337
5338         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5339
5340         // check occlusion of coronas
5341         // use GL_ARB_occlusion_query if available
5342         // otherwise use raytraces
5343         r_numqueries = 0;
5344         switch (vid.renderpath)
5345         {
5346         case RENDERPATH_GL11:
5347         case RENDERPATH_GL13:
5348         case RENDERPATH_GL20:
5349         case RENDERPATH_GLES1:
5350         case RENDERPATH_GLES2:
5351                 usequery = vid.support.arb_occlusion_query && r_coronas_occlusionquery.integer;
5352                 if (usequery)
5353                 {
5354                         GL_ColorMask(0,0,0,0);
5355                         if (r_maxqueries < (range + r_refdef.scene.numlights) * 2)
5356                         if (r_maxqueries < MAX_OCCLUSION_QUERIES)
5357                         {
5358                                 i = r_maxqueries;
5359                                 r_maxqueries = (range + r_refdef.scene.numlights) * 4;
5360                                 r_maxqueries = min(r_maxqueries, MAX_OCCLUSION_QUERIES);
5361                                 CHECKGLERROR
5362                                 qglGenQueriesARB(r_maxqueries - i, r_queries + i);
5363                                 CHECKGLERROR
5364                         }
5365                         RSurf_ActiveWorldEntity();
5366                         GL_BlendFunc(GL_ONE, GL_ZERO);
5367                         GL_CullFace(GL_NONE);
5368                         GL_DepthMask(false);
5369                         GL_DepthRange(0, 1);
5370                         GL_PolygonOffset(0, 0);
5371                         GL_DepthTest(true);
5372                         R_Mesh_ResetTextureState();
5373                         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
5374                 }
5375                 break;
5376         case RENDERPATH_D3D9:
5377                 usequery = false;
5378                 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5379                 break;
5380         case RENDERPATH_D3D10:
5381                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5382                 break;
5383         case RENDERPATH_D3D11:
5384                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5385                 break;
5386         case RENDERPATH_SOFT:
5387                 usequery = false;
5388                 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5389                 break;
5390         }
5391         for (lightindex = 0;lightindex < range;lightindex++)
5392         {
5393                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5394                 if (!light)
5395                         continue;
5396                 rtlight = &light->rtlight;
5397                 rtlight->corona_visibility = 0;
5398                 rtlight->corona_queryindex_visiblepixels = 0;
5399                 rtlight->corona_queryindex_allpixels = 0;
5400                 if (!(rtlight->flags & flag))
5401                         continue;
5402                 if (rtlight->corona <= 0)
5403                         continue;
5404                 if (r_shadow_debuglight.integer >= 0 && r_shadow_debuglight.integer != (int)lightindex)
5405                         continue;
5406                 R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
5407         }
5408         for (i = 0;i < r_refdef.scene.numlights;i++)
5409         {
5410                 rtlight = r_refdef.scene.lights[i];
5411                 rtlight->corona_visibility = 0;
5412                 rtlight->corona_queryindex_visiblepixels = 0;
5413                 rtlight->corona_queryindex_allpixels = 0;
5414                 if (!(rtlight->flags & flag))
5415                         continue;
5416                 if (rtlight->corona <= 0)
5417                         continue;
5418                 R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
5419         }
5420         if (usequery)
5421                 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5422
5423         // now draw the coronas using the query data for intensity info
5424         for (lightindex = 0;lightindex < range;lightindex++)
5425         {
5426                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5427                 if (!light)
5428                         continue;
5429                 rtlight = &light->rtlight;
5430                 if (rtlight->corona_visibility <= 0)
5431                         continue;
5432                 R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
5433         }
5434         for (i = 0;i < r_refdef.scene.numlights;i++)
5435         {
5436                 rtlight = r_refdef.scene.lights[i];
5437                 if (rtlight->corona_visibility <= 0)
5438                         continue;
5439                 if (gl_flashblend.integer)
5440                         R_DrawCorona(rtlight, rtlight->corona, rtlight->radius * rtlight->coronasizescale * 2.0f);
5441                 else
5442                         R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
5443         }
5444 }
5445
5446
5447
5448 dlight_t *R_Shadow_NewWorldLight(void)
5449 {
5450         return (dlight_t *)Mem_ExpandableArray_AllocRecord(&r_shadow_worldlightsarray);
5451 }
5452
5453 void R_Shadow_UpdateWorldLight(dlight_t *light, vec3_t origin, vec3_t angles, vec3_t color, vec_t radius, vec_t corona, int style, int shadowenable, const char *cubemapname, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags)
5454 {
5455         matrix4x4_t matrix;
5456         // validate parameters
5457         if (style < 0 || style >= MAX_LIGHTSTYLES)
5458         {
5459                 Con_Printf("R_Shadow_NewWorldLight: invalid light style number %i, must be >= 0 and < %i\n", light->style, MAX_LIGHTSTYLES);
5460                 style = 0;
5461         }
5462         if (!cubemapname)
5463                 cubemapname = "";
5464
5465         // copy to light properties
5466         VectorCopy(origin, light->origin);
5467         light->angles[0] = angles[0] - 360 * floor(angles[0] / 360);
5468         light->angles[1] = angles[1] - 360 * floor(angles[1] / 360);
5469         light->angles[2] = angles[2] - 360 * floor(angles[2] / 360);
5470         /*
5471         light->color[0] = max(color[0], 0);
5472         light->color[1] = max(color[1], 0);
5473         light->color[2] = max(color[2], 0);
5474         */
5475         light->color[0] = color[0];
5476         light->color[1] = color[1];
5477         light->color[2] = color[2];
5478         light->radius = max(radius, 0);
5479         light->style = style;
5480         light->shadow = shadowenable;
5481         light->corona = corona;
5482         strlcpy(light->cubemapname, cubemapname, sizeof(light->cubemapname));
5483         light->coronasizescale = coronasizescale;
5484         light->ambientscale = ambientscale;
5485         light->diffusescale = diffusescale;
5486         light->specularscale = specularscale;
5487         light->flags = flags;
5488
5489         // update renderable light data
5490         Matrix4x4_CreateFromQuakeEntity(&matrix, light->origin[0], light->origin[1], light->origin[2], light->angles[0], light->angles[1], light->angles[2], light->radius);
5491         R_RTLight_Update(&light->rtlight, true, &matrix, light->color, light->style, light->cubemapname[0] ? light->cubemapname : NULL, light->shadow, light->corona, light->coronasizescale, light->ambientscale, light->diffusescale, light->specularscale, light->flags);
5492 }
5493
5494 void R_Shadow_FreeWorldLight(dlight_t *light)
5495 {
5496         if (r_shadow_selectedlight == light)
5497                 r_shadow_selectedlight = NULL;
5498         R_RTLight_Uncompile(&light->rtlight);
5499         Mem_ExpandableArray_FreeRecord(&r_shadow_worldlightsarray, light);
5500 }
5501
5502 void R_Shadow_ClearWorldLights(void)
5503 {
5504         size_t lightindex;
5505         dlight_t *light;
5506         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5507         for (lightindex = 0;lightindex < range;lightindex++)
5508         {
5509                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5510                 if (light)
5511                         R_Shadow_FreeWorldLight(light);
5512         }
5513         r_shadow_selectedlight = NULL;
5514 }
5515
5516 void R_Shadow_SelectLight(dlight_t *light)
5517 {
5518         if (r_shadow_selectedlight)
5519                 r_shadow_selectedlight->selected = false;
5520         r_shadow_selectedlight = light;
5521         if (r_shadow_selectedlight)
5522                 r_shadow_selectedlight->selected = true;
5523 }
5524
5525 void R_Shadow_DrawCursor_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
5526 {
5527         // this is never batched (there can be only one)
5528         float vertex3f[12];
5529         R_CalcSprite_Vertex3f(vertex3f, r_editlights_cursorlocation, r_refdef.view.right, r_refdef.view.up, EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, EDLIGHTSPRSIZE);
5530         RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, 1, 1, 1, 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5531         R_DrawCustomSurface(r_editlights_sprcursor, &identitymatrix, MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5532 }
5533
5534 void R_Shadow_DrawLightSprite_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
5535 {
5536         float intensity;
5537         float s;
5538         vec3_t spritecolor;
5539         skinframe_t *skinframe;
5540         float vertex3f[12];
5541
5542         // this is never batched (due to the ent parameter changing every time)
5543         // so numsurfaces == 1 and surfacelist[0] == lightnumber
5544         const dlight_t *light = (dlight_t *)ent;
5545         s = EDLIGHTSPRSIZE;
5546
5547         R_CalcSprite_Vertex3f(vertex3f, light->origin, r_refdef.view.right, r_refdef.view.up, s, -s, -s, s);
5548
5549         intensity = 0.5f;
5550         VectorScale(light->color, intensity, spritecolor);
5551         if (VectorLength(spritecolor) < 0.1732f)
5552                 VectorSet(spritecolor, 0.1f, 0.1f, 0.1f);
5553         if (VectorLength(spritecolor) > 1.0f)
5554                 VectorNormalize(spritecolor);
5555
5556         // draw light sprite
5557         if (light->cubemapname[0] && !light->shadow)
5558                 skinframe = r_editlights_sprcubemapnoshadowlight;
5559         else if (light->cubemapname[0])
5560                 skinframe = r_editlights_sprcubemaplight;
5561         else if (!light->shadow)
5562                 skinframe = r_editlights_sprnoshadowlight;
5563         else
5564                 skinframe = r_editlights_sprlight;
5565
5566         RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, spritecolor[0], spritecolor[1], spritecolor[2], 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5567         R_DrawCustomSurface(skinframe, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5568
5569         // draw selection sprite if light is selected
5570         if (light->selected)
5571         {
5572                 RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, 1, 1, 1, 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5573                 R_DrawCustomSurface(r_editlights_sprselection, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5574                 // VorteX todo: add normalmode/realtime mode light overlay sprites?
5575         }
5576 }
5577
5578 void R_Shadow_DrawLightSprites(void)
5579 {
5580         size_t lightindex;
5581         dlight_t *light;
5582         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5583         for (lightindex = 0;lightindex < range;lightindex++)
5584         {
5585                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5586                 if (light)
5587                         R_MeshQueue_AddTransparent(light->origin, R_Shadow_DrawLightSprite_TransparentCallback, (entity_render_t *)light, 5, &light->rtlight);
5588         }
5589         if (!r_editlights_lockcursor)
5590                 R_MeshQueue_AddTransparent(r_editlights_cursorlocation, R_Shadow_DrawCursor_TransparentCallback, NULL, 0, NULL);
5591 }
5592
5593 int R_Shadow_GetRTLightInfo(unsigned int lightindex, float *origin, float *radius, float *color)
5594 {
5595         unsigned int range;
5596         dlight_t *light;
5597         rtlight_t *rtlight;
5598         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
5599         if (lightindex >= range)
5600                 return -1;
5601         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5602         if (!light)
5603                 return 0;
5604         rtlight = &light->rtlight;
5605         //if (!(rtlight->flags & flag))
5606         //      return 0;
5607         VectorCopy(rtlight->shadoworigin, origin);
5608         *radius = rtlight->radius;
5609         VectorCopy(rtlight->color, color);
5610         return 1;
5611 }
5612
5613 void R_Shadow_SelectLightInView(void)
5614 {
5615         float bestrating, rating, temp[3];
5616         dlight_t *best;
5617         size_t lightindex;
5618         dlight_t *light;
5619         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5620         best = NULL;
5621         bestrating = 0;
5622
5623         if (r_editlights_lockcursor)
5624                 return;
5625         for (lightindex = 0;lightindex < range;lightindex++)
5626         {
5627                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5628                 if (!light)
5629                         continue;
5630                 VectorSubtract(light->origin, r_refdef.view.origin, temp);
5631                 rating = (DotProduct(temp, r_refdef.view.forward) / sqrt(DotProduct(temp, temp)));
5632                 if (rating >= 0.95)
5633                 {
5634                         rating /= (1 + 0.0625f * sqrt(DotProduct(temp, temp)));
5635                         if (bestrating < rating && CL_TraceLine(light->origin, r_refdef.view.origin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1.0f)
5636                         {
5637                                 bestrating = rating;
5638                                 best = light;
5639                         }
5640                 }
5641         }
5642         R_Shadow_SelectLight(best);
5643 }
5644
5645 void R_Shadow_LoadWorldLights(void)
5646 {
5647         int n, a, style, shadow, flags;
5648         char tempchar, *lightsstring, *s, *t, name[MAX_QPATH], cubemapname[MAX_QPATH];
5649         float origin[3], radius, color[3], angles[3], corona, coronasizescale, ambientscale, diffusescale, specularscale;
5650         if (cl.worldmodel == NULL)
5651         {
5652                 Con_Print("No map loaded.\n");
5653                 return;
5654         }
5655         dpsnprintf(name, sizeof(name), "%s.rtlights", cl.worldnamenoextension);
5656         lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
5657         if (lightsstring)
5658         {
5659                 s = lightsstring;
5660                 n = 0;
5661                 while (*s)
5662                 {
5663                         t = s;
5664                         /*
5665                         shadow = true;
5666                         for (;COM_Parse(t, true) && strcmp(
5667                         if (COM_Parse(t, true))
5668                         {
5669                                 if (com_token[0] == '!')
5670                                 {
5671                                         shadow = false;
5672                                         origin[0] = atof(com_token+1);
5673                                 }
5674                                 else
5675                                         origin[0] = atof(com_token);
5676                                 if (Com_Parse(t
5677                         }
5678                         */
5679                         t = s;
5680                         while (*s && *s != '\n' && *s != '\r')
5681                                 s++;
5682                         if (!*s)
5683                                 break;
5684                         tempchar = *s;
5685                         shadow = true;
5686                         // check for modifier flags
5687                         if (*t == '!')
5688                         {
5689                                 shadow = false;
5690                                 t++;
5691                         }
5692                         *s = 0;
5693 #if _MSC_VER >= 1400
5694 #define sscanf sscanf_s
5695 #endif
5696                         cubemapname[sizeof(cubemapname)-1] = 0;
5697 #if MAX_QPATH != 128
5698 #error update this code if MAX_QPATH changes
5699 #endif
5700                         a = sscanf(t, "%f %f %f %f %f %f %f %d %127s %f %f %f %f %f %f %f %f %i", &origin[0], &origin[1], &origin[2], &radius, &color[0], &color[1], &color[2], &style, cubemapname
5701 #if _MSC_VER >= 1400
5702 , sizeof(cubemapname)
5703 #endif
5704 , &corona, &angles[0], &angles[1], &angles[2], &coronasizescale, &ambientscale, &diffusescale, &specularscale, &flags);
5705                         *s = tempchar;
5706                         if (a < 18)
5707                                 flags = LIGHTFLAG_REALTIMEMODE;
5708                         if (a < 17)
5709                                 specularscale = 1;
5710                         if (a < 16)
5711                                 diffusescale = 1;
5712                         if (a < 15)
5713                                 ambientscale = 0;
5714                         if (a < 14)
5715                                 coronasizescale = 0.25f;
5716                         if (a < 13)
5717                                 VectorClear(angles);
5718                         if (a < 10)
5719                                 corona = 0;
5720                         if (a < 9 || !strcmp(cubemapname, "\"\""))
5721                                 cubemapname[0] = 0;
5722                         // remove quotes on cubemapname
5723                         if (cubemapname[0] == '"' && cubemapname[strlen(cubemapname) - 1] == '"')
5724                         {
5725                                 size_t namelen;
5726                                 namelen = strlen(cubemapname) - 2;
5727                                 memmove(cubemapname, cubemapname + 1, namelen);
5728                                 cubemapname[namelen] = '\0';
5729                         }
5730                         if (a < 8)
5731                         {
5732                                 Con_Printf("found %d parameters on line %i, should be 8 or more parameters (origin[0] origin[1] origin[2] radius color[0] color[1] color[2] style \"cubemapname\" corona angles[0] angles[1] angles[2] coronasizescale ambientscale diffusescale specularscale flags)\n", a, n + 1);
5733                                 break;
5734                         }
5735                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, corona, style, shadow, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
5736                         if (*s == '\r')
5737                                 s++;
5738                         if (*s == '\n')
5739                                 s++;
5740                         n++;
5741                 }
5742                 if (*s)
5743                         Con_Printf("invalid rtlights file \"%s\"\n", name);
5744                 Mem_Free(lightsstring);
5745         }
5746 }
5747
5748 void R_Shadow_SaveWorldLights(void)
5749 {
5750         size_t lightindex;
5751         dlight_t *light;
5752         size_t bufchars, bufmaxchars;
5753         char *buf, *oldbuf;
5754         char name[MAX_QPATH];
5755         char line[MAX_INPUTLINE];
5756         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked, assuming the dpsnprintf mess doesn't screw it up...
5757         // I hate lines which are 3 times my screen size :( --blub
5758         if (!range)
5759                 return;
5760         if (cl.worldmodel == NULL)
5761         {
5762                 Con_Print("No map loaded.\n");
5763                 return;
5764         }
5765         dpsnprintf(name, sizeof(name), "%s.rtlights", cl.worldnamenoextension);
5766         bufchars = bufmaxchars = 0;
5767         buf = NULL;
5768         for (lightindex = 0;lightindex < range;lightindex++)
5769         {
5770                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5771                 if (!light)
5772                         continue;
5773                 if (light->coronasizescale != 0.25f || light->ambientscale != 0 || light->diffusescale != 1 || light->specularscale != 1 || light->flags != LIGHTFLAG_REALTIMEMODE)
5774                         dpsnprintf(line, sizeof(line), "%s%f %f %f %f %f %f %f %d \"%s\" %f %f %f %f %f %f %f %f %i\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style, light->cubemapname, light->corona, light->angles[0], light->angles[1], light->angles[2], light->coronasizescale, light->ambientscale, light->diffusescale, light->specularscale, light->flags);
5775                 else if (light->cubemapname[0] || light->corona || light->angles[0] || light->angles[1] || light->angles[2])
5776                         dpsnprintf(line, sizeof(line), "%s%f %f %f %f %f %f %f %d \"%s\" %f %f %f %f\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style, light->cubemapname, light->corona, light->angles[0], light->angles[1], light->angles[2]);
5777                 else
5778                         dpsnprintf(line, sizeof(line), "%s%f %f %f %f %f %f %f %d\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style);
5779                 if (bufchars + strlen(line) > bufmaxchars)
5780                 {
5781                         bufmaxchars = bufchars + strlen(line) + 2048;
5782                         oldbuf = buf;
5783                         buf = (char *)Mem_Alloc(tempmempool, bufmaxchars);
5784                         if (oldbuf)
5785                         {
5786                                 if (bufchars)
5787                                         memcpy(buf, oldbuf, bufchars);
5788                                 Mem_Free(oldbuf);
5789                         }
5790                 }
5791                 if (strlen(line))
5792                 {
5793                         memcpy(buf + bufchars, line, strlen(line));
5794                         bufchars += strlen(line);
5795                 }
5796         }
5797         if (bufchars)
5798                 FS_WriteFile(name, buf, (fs_offset_t)bufchars);
5799         if (buf)
5800                 Mem_Free(buf);
5801 }
5802
5803 void R_Shadow_LoadLightsFile(void)
5804 {
5805         int n, a, style;
5806         char tempchar, *lightsstring, *s, *t, name[MAX_QPATH];
5807         float origin[3], radius, color[3], subtract, spotdir[3], spotcone, falloff, distbias;
5808         if (cl.worldmodel == NULL)
5809         {
5810                 Con_Print("No map loaded.\n");
5811                 return;
5812         }
5813         dpsnprintf(name, sizeof(name), "%s.lights", cl.worldnamenoextension);
5814         lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
5815         if (lightsstring)
5816         {
5817                 s = lightsstring;
5818                 n = 0;
5819                 while (*s)
5820                 {
5821                         t = s;
5822                         while (*s && *s != '\n' && *s != '\r')
5823                                 s++;
5824                         if (!*s)
5825                                 break;
5826                         tempchar = *s;
5827                         *s = 0;
5828                         a = sscanf(t, "%f %f %f %f %f %f %f %f %f %f %f %f %f %d", &origin[0], &origin[1], &origin[2], &falloff, &color[0], &color[1], &color[2], &subtract, &spotdir[0], &spotdir[1], &spotdir[2], &spotcone, &distbias, &style);
5829                         *s = tempchar;
5830                         if (a < 14)
5831                         {
5832                                 Con_Printf("invalid lights file, found %d parameters on line %i, should be 14 parameters (origin[0] origin[1] origin[2] falloff light[0] light[1] light[2] subtract spotdir[0] spotdir[1] spotdir[2] spotcone distancebias style)\n", a, n + 1);
5833                                 break;
5834                         }
5835                         radius = sqrt(DotProduct(color, color) / (falloff * falloff * 8192.0f * 8192.0f));
5836                         radius = bound(15, radius, 4096);
5837                         VectorScale(color, (2.0f / (8388608.0f)), color);
5838                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, vec3_origin, color, radius, 0, style, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
5839                         if (*s == '\r')
5840                                 s++;
5841                         if (*s == '\n')
5842                                 s++;
5843                         n++;
5844                 }
5845                 if (*s)
5846                         Con_Printf("invalid lights file \"%s\"\n", name);
5847                 Mem_Free(lightsstring);
5848         }
5849 }
5850
5851 // tyrlite/hmap2 light types in the delay field
5852 typedef enum lighttype_e {LIGHTTYPE_MINUSX, LIGHTTYPE_RECIPX, LIGHTTYPE_RECIPXX, LIGHTTYPE_NONE, LIGHTTYPE_SUN, LIGHTTYPE_MINUSXX} lighttype_t;
5853
5854 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void)
5855 {
5856         int entnum;
5857         int style;
5858         int islight;
5859         int skin;
5860         int pflags;
5861         //int effects;
5862         int type;
5863         int n;
5864         char *entfiledata;
5865         const char *data;
5866         float origin[3], angles[3], radius, color[3], light[4], fadescale, lightscale, originhack[3], overridecolor[3], vec[4];
5867         char key[256], value[MAX_INPUTLINE];
5868
5869         if (cl.worldmodel == NULL)
5870         {
5871                 Con_Print("No map loaded.\n");
5872                 return;
5873         }
5874         // try to load a .ent file first
5875         dpsnprintf(key, sizeof(key), "%s.ent", cl.worldnamenoextension);
5876         data = entfiledata = (char *)FS_LoadFile(key, tempmempool, true, NULL);
5877         // and if that is not found, fall back to the bsp file entity string
5878         if (!data)
5879                 data = cl.worldmodel->brush.entities;
5880         if (!data)
5881                 return;
5882         for (entnum = 0;COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{';entnum++)
5883         {
5884                 type = LIGHTTYPE_MINUSX;
5885                 origin[0] = origin[1] = origin[2] = 0;
5886                 originhack[0] = originhack[1] = originhack[2] = 0;
5887                 angles[0] = angles[1] = angles[2] = 0;
5888                 color[0] = color[1] = color[2] = 1;
5889                 light[0] = light[1] = light[2] = 1;light[3] = 300;
5890                 overridecolor[0] = overridecolor[1] = overridecolor[2] = 1;
5891                 fadescale = 1;
5892                 lightscale = 1;
5893                 style = 0;
5894                 skin = 0;
5895                 pflags = 0;
5896                 //effects = 0;
5897                 islight = false;
5898                 while (1)
5899                 {
5900                         if (!COM_ParseToken_Simple(&data, false, false))
5901                                 break; // error
5902                         if (com_token[0] == '}')
5903                                 break; // end of entity
5904                         if (com_token[0] == '_')
5905                                 strlcpy(key, com_token + 1, sizeof(key));
5906                         else
5907                                 strlcpy(key, com_token, sizeof(key));
5908                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
5909                                 key[strlen(key)-1] = 0;
5910                         if (!COM_ParseToken_Simple(&data, false, false))
5911                                 break; // error
5912                         strlcpy(value, com_token, sizeof(value));
5913
5914                         // now that we have the key pair worked out...
5915                         if (!strcmp("light", key))
5916                         {
5917                                 n = sscanf(value, "%f %f %f %f", &vec[0], &vec[1], &vec[2], &vec[3]);
5918                                 if (n == 1)
5919                                 {
5920                                         // quake
5921                                         light[0] = vec[0] * (1.0f / 256.0f);
5922                                         light[1] = vec[0] * (1.0f / 256.0f);
5923                                         light[2] = vec[0] * (1.0f / 256.0f);
5924                                         light[3] = vec[0];
5925                                 }
5926                                 else if (n == 4)
5927                                 {
5928                                         // halflife
5929                                         light[0] = vec[0] * (1.0f / 255.0f);
5930                                         light[1] = vec[1] * (1.0f / 255.0f);
5931                                         light[2] = vec[2] * (1.0f / 255.0f);
5932                                         light[3] = vec[3];
5933                                 }
5934                         }
5935                         else if (!strcmp("delay", key))
5936                                 type = atoi(value);
5937                         else if (!strcmp("origin", key))
5938                                 sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]);
5939                         else if (!strcmp("angle", key))
5940                                 angles[0] = 0, angles[1] = atof(value), angles[2] = 0;
5941                         else if (!strcmp("angles", key))
5942                                 sscanf(value, "%f %f %f", &angles[0], &angles[1], &angles[2]);
5943                         else if (!strcmp("color", key))
5944                                 sscanf(value, "%f %f %f", &color[0], &color[1], &color[2]);
5945                         else if (!strcmp("wait", key))
5946                                 fadescale = atof(value);
5947                         else if (!strcmp("classname", key))
5948                         {
5949                                 if (!strncmp(value, "light", 5))
5950                                 {
5951                                         islight = true;
5952                                         if (!strcmp(value, "light_fluoro"))
5953                                         {
5954                                                 originhack[0] = 0;
5955                                                 originhack[1] = 0;
5956                                                 originhack[2] = 0;
5957                                                 overridecolor[0] = 1;
5958                                                 overridecolor[1] = 1;
5959                                                 overridecolor[2] = 1;
5960                                         }
5961                                         if (!strcmp(value, "light_fluorospark"))
5962                                         {
5963                                                 originhack[0] = 0;
5964                                                 originhack[1] = 0;
5965                                                 originhack[2] = 0;
5966                                                 overridecolor[0] = 1;
5967                                                 overridecolor[1] = 1;
5968                                                 overridecolor[2] = 1;
5969                                         }
5970                                         if (!strcmp(value, "light_globe"))
5971                                         {
5972                                                 originhack[0] = 0;
5973                                                 originhack[1] = 0;
5974                                                 originhack[2] = 0;
5975                                                 overridecolor[0] = 1;
5976                                                 overridecolor[1] = 0.8;
5977                                                 overridecolor[2] = 0.4;
5978                                         }
5979                                         if (!strcmp(value, "light_flame_large_yellow"))
5980                                         {
5981                                                 originhack[0] = 0;
5982                                                 originhack[1] = 0;
5983                                                 originhack[2] = 0;
5984                                                 overridecolor[0] = 1;
5985                                                 overridecolor[1] = 0.5;
5986                                                 overridecolor[2] = 0.1;
5987                                         }
5988                                         if (!strcmp(value, "light_flame_small_yellow"))
5989                                         {
5990                                                 originhack[0] = 0;
5991                                                 originhack[1] = 0;
5992                                                 originhack[2] = 0;
5993                                                 overridecolor[0] = 1;
5994                                                 overridecolor[1] = 0.5;
5995                                                 overridecolor[2] = 0.1;
5996                                         }
5997                                         if (!strcmp(value, "light_torch_small_white"))
5998                                         {
5999                                                 originhack[0] = 0;
6000                                                 originhack[1] = 0;
6001                                                 originhack[2] = 0;
6002                                                 overridecolor[0] = 1;
6003                                                 overridecolor[1] = 0.5;
6004                                                 overridecolor[2] = 0.1;
6005                                         }
6006                                         if (!strcmp(value, "light_torch_small_walltorch"))
6007                                         {
6008                                                 originhack[0] = 0;
6009                                                 originhack[1] = 0;
6010                                                 originhack[2] = 0;
6011                                                 overridecolor[0] = 1;
6012                                                 overridecolor[1] = 0.5;
6013                                                 overridecolor[2] = 0.1;
6014                                         }
6015                                 }
6016                         }
6017                         else if (!strcmp("style", key))
6018                                 style = atoi(value);
6019                         else if (!strcmp("skin", key))
6020                                 skin = (int)atof(value);
6021                         else if (!strcmp("pflags", key))
6022                                 pflags = (int)atof(value);
6023                         //else if (!strcmp("effects", key))
6024                         //      effects = (int)atof(value);
6025                         else if (cl.worldmodel->type == mod_brushq3)
6026                         {
6027                                 if (!strcmp("scale", key))
6028                                         lightscale = atof(value);
6029                                 if (!strcmp("fade", key))
6030                                         fadescale = atof(value);
6031                         }
6032                 }
6033                 if (!islight)
6034                         continue;
6035                 if (lightscale <= 0)
6036                         lightscale = 1;
6037                 if (fadescale <= 0)
6038                         fadescale = 1;
6039                 if (color[0] == color[1] && color[0] == color[2])
6040                 {
6041                         color[0] *= overridecolor[0];
6042                         color[1] *= overridecolor[1];
6043                         color[2] *= overridecolor[2];
6044                 }
6045                 radius = light[3] * r_editlights_quakelightsizescale.value * lightscale / fadescale;
6046                 color[0] = color[0] * light[0];
6047                 color[1] = color[1] * light[1];
6048                 color[2] = color[2] * light[2];
6049                 switch (type)
6050                 {
6051                 case LIGHTTYPE_MINUSX:
6052                         break;
6053                 case LIGHTTYPE_RECIPX:
6054                         radius *= 2;
6055                         VectorScale(color, (1.0f / 16.0f), color);
6056                         break;
6057                 case LIGHTTYPE_RECIPXX:
6058                         radius *= 2;
6059                         VectorScale(color, (1.0f / 16.0f), color);
6060                         break;
6061                 default:
6062                 case LIGHTTYPE_NONE:
6063                         break;
6064                 case LIGHTTYPE_SUN:
6065                         break;
6066                 case LIGHTTYPE_MINUSXX:
6067                         break;
6068                 }
6069                 VectorAdd(origin, originhack, origin);
6070                 if (radius >= 1)
6071                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, (pflags & PFLAGS_CORONA) != 0, style, (pflags & PFLAGS_NOSHADOW) == 0, skin >= 16 ? va("cubemaps/%i", skin) : NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
6072         }
6073         if (entfiledata)
6074                 Mem_Free(entfiledata);
6075 }
6076
6077
6078 void R_Shadow_SetCursorLocationForView(void)
6079 {
6080         vec_t dist, push;
6081         vec3_t dest, endpos;
6082         trace_t trace;
6083         VectorMA(r_refdef.view.origin, r_editlights_cursordistance.value, r_refdef.view.forward, dest);
6084         trace = CL_TraceLine(r_refdef.view.origin, dest, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true);
6085         if (trace.fraction < 1)
6086         {
6087                 dist = trace.fraction * r_editlights_cursordistance.value;
6088                 push = r_editlights_cursorpushback.value;
6089                 if (push > dist)
6090                         push = dist;
6091                 push = -push;
6092                 VectorMA(trace.endpos, push, r_refdef.view.forward, endpos);
6093                 VectorMA(endpos, r_editlights_cursorpushoff.value, trace.plane.normal, endpos);
6094         }
6095         else
6096         {
6097                 VectorClear( endpos );
6098         }
6099         r_editlights_cursorlocation[0] = floor(endpos[0] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
6100         r_editlights_cursorlocation[1] = floor(endpos[1] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
6101         r_editlights_cursorlocation[2] = floor(endpos[2] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
6102 }
6103
6104 void R_Shadow_UpdateWorldLightSelection(void)
6105 {
6106         if (r_editlights.integer)
6107         {
6108                 R_Shadow_SetCursorLocationForView();
6109                 R_Shadow_SelectLightInView();
6110         }
6111         else
6112                 R_Shadow_SelectLight(NULL);
6113 }
6114
6115 void R_Shadow_EditLights_Clear_f(void)
6116 {
6117         R_Shadow_ClearWorldLights();
6118 }
6119
6120 void R_Shadow_EditLights_Reload_f(void)
6121 {
6122         if (!cl.worldmodel)
6123                 return;
6124         strlcpy(r_shadow_mapname, cl.worldname, sizeof(r_shadow_mapname));
6125         R_Shadow_ClearWorldLights();
6126         R_Shadow_LoadWorldLights();
6127         if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
6128         {
6129                 R_Shadow_LoadLightsFile();
6130                 if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
6131                         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
6132         }
6133 }
6134
6135 void R_Shadow_EditLights_Save_f(void)
6136 {
6137         if (!cl.worldmodel)
6138                 return;
6139         R_Shadow_SaveWorldLights();
6140 }
6141
6142 void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void)
6143 {
6144         R_Shadow_ClearWorldLights();
6145         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
6146 }
6147
6148 void R_Shadow_EditLights_ImportLightsFile_f(void)
6149 {
6150         R_Shadow_ClearWorldLights();
6151         R_Shadow_LoadLightsFile();
6152 }
6153
6154 void R_Shadow_EditLights_Spawn_f(void)
6155 {
6156         vec3_t color;
6157         if (!r_editlights.integer)
6158         {
6159                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
6160                 return;
6161         }
6162         if (Cmd_Argc() != 1)
6163         {
6164                 Con_Print("r_editlights_spawn does not take parameters\n");
6165                 return;
6166         }
6167         color[0] = color[1] = color[2] = 1;
6168         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), r_editlights_cursorlocation, vec3_origin, color, 200, 0, 0, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
6169 }
6170
6171 void R_Shadow_EditLights_Edit_f(void)
6172 {
6173         vec3_t origin, angles, color;
6174         vec_t radius, corona, coronasizescale, ambientscale, diffusescale, specularscale;
6175         int style, shadows, flags, normalmode, realtimemode;
6176         char cubemapname[MAX_INPUTLINE];
6177         if (!r_editlights.integer)
6178         {
6179                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
6180                 return;
6181         }
6182         if (!r_shadow_selectedlight)
6183         {
6184                 Con_Print("No selected light.\n");
6185                 return;
6186         }
6187         VectorCopy(r_shadow_selectedlight->origin, origin);
6188         VectorCopy(r_shadow_selectedlight->angles, angles);
6189         VectorCopy(r_shadow_selectedlight->color, color);
6190         radius = r_shadow_selectedlight->radius;
6191         style = r_shadow_selectedlight->style;
6192         if (r_shadow_selectedlight->cubemapname)
6193                 strlcpy(cubemapname, r_shadow_selectedlight->cubemapname, sizeof(cubemapname));
6194         else
6195                 cubemapname[0] = 0;
6196         shadows = r_shadow_selectedlight->shadow;
6197         corona = r_shadow_selectedlight->corona;
6198         coronasizescale = r_shadow_selectedlight->coronasizescale;
6199         ambientscale = r_shadow_selectedlight->ambientscale;
6200         diffusescale = r_shadow_selectedlight->diffusescale;
6201         specularscale = r_shadow_selectedlight->specularscale;
6202         flags = r_shadow_selectedlight->flags;
6203         normalmode = (flags & LIGHTFLAG_NORMALMODE) != 0;
6204         realtimemode = (flags & LIGHTFLAG_REALTIMEMODE) != 0;
6205         if (!strcmp(Cmd_Argv(1), "origin"))
6206         {
6207                 if (Cmd_Argc() != 5)
6208                 {
6209                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6210                         return;
6211                 }
6212                 origin[0] = atof(Cmd_Argv(2));
6213                 origin[1] = atof(Cmd_Argv(3));
6214                 origin[2] = atof(Cmd_Argv(4));
6215         }
6216         else if (!strcmp(Cmd_Argv(1), "originscale"))
6217         {
6218                 if (Cmd_Argc() != 5)
6219                 {
6220                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6221                         return;
6222                 }
6223                 origin[0] *= atof(Cmd_Argv(2));
6224                 origin[1] *= atof(Cmd_Argv(3));
6225                 origin[2] *= atof(Cmd_Argv(4));
6226         }
6227         else if (!strcmp(Cmd_Argv(1), "originx"))
6228         {
6229                 if (Cmd_Argc() != 3)
6230                 {
6231                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6232                         return;
6233                 }
6234                 origin[0] = atof(Cmd_Argv(2));
6235         }
6236         else if (!strcmp(Cmd_Argv(1), "originy"))
6237         {
6238                 if (Cmd_Argc() != 3)
6239                 {
6240                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6241                         return;
6242                 }
6243                 origin[1] = atof(Cmd_Argv(2));
6244         }
6245         else if (!strcmp(Cmd_Argv(1), "originz"))
6246         {
6247                 if (Cmd_Argc() != 3)
6248                 {
6249                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6250                         return;
6251                 }
6252                 origin[2] = atof(Cmd_Argv(2));
6253         }
6254         else if (!strcmp(Cmd_Argv(1), "move"))
6255         {
6256                 if (Cmd_Argc() != 5)
6257                 {
6258                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6259                         return;
6260                 }
6261                 origin[0] += atof(Cmd_Argv(2));
6262                 origin[1] += atof(Cmd_Argv(3));
6263                 origin[2] += atof(Cmd_Argv(4));
6264         }
6265         else if (!strcmp(Cmd_Argv(1), "movex"))
6266         {
6267                 if (Cmd_Argc() != 3)
6268                 {
6269                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6270                         return;
6271                 }
6272                 origin[0] += atof(Cmd_Argv(2));
6273         }
6274         else if (!strcmp(Cmd_Argv(1), "movey"))
6275         {
6276                 if (Cmd_Argc() != 3)
6277                 {
6278                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6279                         return;
6280                 }
6281                 origin[1] += atof(Cmd_Argv(2));
6282         }
6283         else if (!strcmp(Cmd_Argv(1), "movez"))
6284         {
6285                 if (Cmd_Argc() != 3)
6286                 {
6287                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6288                         return;
6289                 }
6290                 origin[2] += atof(Cmd_Argv(2));
6291         }
6292         else if (!strcmp(Cmd_Argv(1), "angles"))
6293         {
6294                 if (Cmd_Argc() != 5)
6295                 {
6296                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6297                         return;
6298                 }
6299                 angles[0] = atof(Cmd_Argv(2));
6300                 angles[1] = atof(Cmd_Argv(3));
6301                 angles[2] = atof(Cmd_Argv(4));
6302         }
6303         else if (!strcmp(Cmd_Argv(1), "anglesx"))
6304         {
6305                 if (Cmd_Argc() != 3)
6306                 {
6307                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6308                         return;
6309                 }
6310                 angles[0] = atof(Cmd_Argv(2));
6311         }
6312         else if (!strcmp(Cmd_Argv(1), "anglesy"))
6313         {
6314                 if (Cmd_Argc() != 3)
6315                 {
6316                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6317                         return;
6318                 }
6319                 angles[1] = atof(Cmd_Argv(2));
6320         }
6321         else if (!strcmp(Cmd_Argv(1), "anglesz"))
6322         {
6323                 if (Cmd_Argc() != 3)
6324                 {
6325                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6326                         return;
6327                 }
6328                 angles[2] = atof(Cmd_Argv(2));
6329         }
6330         else if (!strcmp(Cmd_Argv(1), "color"))
6331         {
6332                 if (Cmd_Argc() != 5)
6333                 {
6334                         Con_Printf("usage: r_editlights_edit %s red green blue\n", Cmd_Argv(1));
6335                         return;
6336                 }
6337                 color[0] = atof(Cmd_Argv(2));
6338                 color[1] = atof(Cmd_Argv(3));
6339                 color[2] = atof(Cmd_Argv(4));
6340         }
6341         else if (!strcmp(Cmd_Argv(1), "radius"))
6342         {
6343                 if (Cmd_Argc() != 3)
6344                 {
6345                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6346                         return;
6347                 }
6348                 radius = atof(Cmd_Argv(2));
6349         }
6350         else if (!strcmp(Cmd_Argv(1), "colorscale"))
6351         {
6352                 if (Cmd_Argc() == 3)
6353                 {
6354                         double scale = atof(Cmd_Argv(2));
6355                         color[0] *= scale;
6356                         color[1] *= scale;
6357                         color[2] *= scale;
6358                 }
6359                 else
6360                 {
6361                         if (Cmd_Argc() != 5)
6362                         {
6363                                 Con_Printf("usage: r_editlights_edit %s red green blue  (OR grey instead of red green blue)\n", Cmd_Argv(1));
6364                                 return;
6365                         }
6366                         color[0] *= atof(Cmd_Argv(2));
6367                         color[1] *= atof(Cmd_Argv(3));
6368                         color[2] *= atof(Cmd_Argv(4));
6369                 }
6370         }
6371         else if (!strcmp(Cmd_Argv(1), "radiusscale") || !strcmp(Cmd_Argv(1), "sizescale"))
6372         {
6373                 if (Cmd_Argc() != 3)
6374                 {
6375                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6376                         return;
6377                 }
6378                 radius *= atof(Cmd_Argv(2));
6379         }
6380         else if (!strcmp(Cmd_Argv(1), "style"))
6381         {
6382                 if (Cmd_Argc() != 3)
6383                 {
6384                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6385                         return;
6386                 }
6387                 style = atoi(Cmd_Argv(2));
6388         }
6389         else if (!strcmp(Cmd_Argv(1), "cubemap"))
6390         {
6391                 if (Cmd_Argc() > 3)
6392                 {
6393                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6394                         return;
6395                 }
6396                 if (Cmd_Argc() == 3)
6397                         strlcpy(cubemapname, Cmd_Argv(2), sizeof(cubemapname));
6398                 else
6399                         cubemapname[0] = 0;
6400         }
6401         else if (!strcmp(Cmd_Argv(1), "shadows"))
6402         {
6403                 if (Cmd_Argc() != 3)
6404                 {
6405                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6406                         return;
6407                 }
6408                 shadows = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6409         }
6410         else if (!strcmp(Cmd_Argv(1), "corona"))
6411         {
6412                 if (Cmd_Argc() != 3)
6413                 {
6414                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6415                         return;
6416                 }
6417                 corona = atof(Cmd_Argv(2));
6418         }
6419         else if (!strcmp(Cmd_Argv(1), "coronasize"))
6420         {
6421                 if (Cmd_Argc() != 3)
6422                 {
6423                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6424                         return;
6425                 }
6426                 coronasizescale = atof(Cmd_Argv(2));
6427         }
6428         else if (!strcmp(Cmd_Argv(1), "ambient"))
6429         {
6430                 if (Cmd_Argc() != 3)
6431                 {
6432                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6433                         return;
6434                 }
6435                 ambientscale = atof(Cmd_Argv(2));
6436         }
6437         else if (!strcmp(Cmd_Argv(1), "diffuse"))
6438         {
6439                 if (Cmd_Argc() != 3)
6440                 {
6441                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6442                         return;
6443                 }
6444                 diffusescale = atof(Cmd_Argv(2));
6445         }
6446         else if (!strcmp(Cmd_Argv(1), "specular"))
6447         {
6448                 if (Cmd_Argc() != 3)
6449                 {
6450                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6451                         return;
6452                 }
6453                 specularscale = atof(Cmd_Argv(2));
6454         }
6455         else if (!strcmp(Cmd_Argv(1), "normalmode"))
6456         {
6457                 if (Cmd_Argc() != 3)
6458                 {
6459                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6460                         return;
6461                 }
6462                 normalmode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6463         }
6464         else if (!strcmp(Cmd_Argv(1), "realtimemode"))
6465         {
6466                 if (Cmd_Argc() != 3)
6467                 {
6468                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6469                         return;
6470                 }
6471                 realtimemode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6472         }
6473         else
6474         {
6475                 Con_Print("usage: r_editlights_edit [property] [value]\n");
6476                 Con_Print("Selected light's properties:\n");
6477                 Con_Printf("Origin       : %f %f %f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);
6478                 Con_Printf("Angles       : %f %f %f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);
6479                 Con_Printf("Color        : %f %f %f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);
6480                 Con_Printf("Radius       : %f\n", r_shadow_selectedlight->radius);
6481                 Con_Printf("Corona       : %f\n", r_shadow_selectedlight->corona);
6482                 Con_Printf("Style        : %i\n", r_shadow_selectedlight->style);
6483                 Con_Printf("Shadows      : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");
6484                 Con_Printf("Cubemap      : %s\n", r_shadow_selectedlight->cubemapname);
6485                 Con_Printf("CoronaSize   : %f\n", r_shadow_selectedlight->coronasizescale);
6486                 Con_Printf("Ambient      : %f\n", r_shadow_selectedlight->ambientscale);
6487                 Con_Printf("Diffuse      : %f\n", r_shadow_selectedlight->diffusescale);
6488                 Con_Printf("Specular     : %f\n", r_shadow_selectedlight->specularscale);
6489                 Con_Printf("NormalMode   : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");
6490                 Con_Printf("RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");
6491                 return;
6492         }
6493         flags = (normalmode ? LIGHTFLAG_NORMALMODE : 0) | (realtimemode ? LIGHTFLAG_REALTIMEMODE : 0);
6494         R_Shadow_UpdateWorldLight(r_shadow_selectedlight, origin, angles, color, radius, corona, style, shadows, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
6495 }
6496
6497 void R_Shadow_EditLights_EditAll_f(void)
6498 {
6499         size_t lightindex;
6500         dlight_t *light, *oldselected;
6501         size_t range;
6502
6503         if (!r_editlights.integer)
6504         {
6505                 Con_Print("Cannot edit lights when not in editing mode. Set r_editlights to 1.\n");
6506                 return;
6507         }
6508
6509         oldselected = r_shadow_selectedlight;
6510         // EditLights doesn't seem to have a "remove" command or something so:
6511         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
6512         for (lightindex = 0;lightindex < range;lightindex++)
6513         {
6514                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
6515                 if (!light)
6516                         continue;
6517                 R_Shadow_SelectLight(light);
6518                 R_Shadow_EditLights_Edit_f();
6519         }
6520         // return to old selected (to not mess editing once selection is locked)
6521         R_Shadow_SelectLight(oldselected);
6522 }
6523
6524 void R_Shadow_EditLights_DrawSelectedLightProperties(void)
6525 {
6526         int lightnumber, lightcount;
6527         size_t lightindex, range;
6528         dlight_t *light;
6529         float x, y;
6530         char temp[256];
6531         if (!r_editlights.integer)
6532                 return;
6533         x = vid_conwidth.value - 240;
6534         y = 5;
6535         DrawQ_Pic(x-5, y-5, NULL, 250, 155, 0, 0, 0, 0.75, 0);
6536         lightnumber = -1;
6537         lightcount = 0;
6538         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
6539         for (lightindex = 0;lightindex < range;lightindex++)
6540         {
6541                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
6542                 if (!light)
6543                         continue;
6544                 if (light == r_shadow_selectedlight)
6545                         lightnumber = lightindex;
6546                 lightcount++;
6547         }
6548         dpsnprintf(temp, sizeof(temp), "Cursor origin: %.0f %.0f %.0f", r_editlights_cursorlocation[0], r_editlights_cursorlocation[1], r_editlights_cursorlocation[2]); DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, false, FONT_DEFAULT);y += 8;
6549         dpsnprintf(temp, sizeof(temp), "Total lights : %i active (%i total)", lightcount, (int)Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray)); DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, false, FONT_DEFAULT);y += 8;
6550         y += 8;
6551         if (r_shadow_selectedlight == NULL)
6552                 return;
6553         dpsnprintf(temp, sizeof(temp), "Light #%i properties:", lightnumber);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6554         dpsnprintf(temp, sizeof(temp), "Origin       : %.0f %.0f %.0f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6555         dpsnprintf(temp, sizeof(temp), "Angles       : %.0f %.0f %.0f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6556         dpsnprintf(temp, sizeof(temp), "Color        : %.2f %.2f %.2f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6557         dpsnprintf(temp, sizeof(temp), "Radius       : %.0f\n", r_shadow_selectedlight->radius);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6558         dpsnprintf(temp, sizeof(temp), "Corona       : %.0f\n", r_shadow_selectedlight->corona);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6559         dpsnprintf(temp, sizeof(temp), "Style        : %i\n", r_shadow_selectedlight->style);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6560         dpsnprintf(temp, sizeof(temp), "Shadows      : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6561         dpsnprintf(temp, sizeof(temp), "Cubemap      : %s\n", r_shadow_selectedlight->cubemapname);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6562         dpsnprintf(temp, sizeof(temp), "CoronaSize   : %.2f\n", r_shadow_selectedlight->coronasizescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6563         dpsnprintf(temp, sizeof(temp), "Ambient      : %.2f\n", r_shadow_selectedlight->ambientscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6564         dpsnprintf(temp, sizeof(temp), "Diffuse      : %.2f\n", r_shadow_selectedlight->diffusescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6565         dpsnprintf(temp, sizeof(temp), "Specular     : %.2f\n", r_shadow_selectedlight->specularscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6566         dpsnprintf(temp, sizeof(temp), "NormalMode   : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6567         dpsnprintf(temp, sizeof(temp), "RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6568 }
6569
6570 void R_Shadow_EditLights_ToggleShadow_f(void)
6571 {
6572         if (!r_editlights.integer)
6573         {
6574                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
6575                 return;
6576         }
6577         if (!r_shadow_selectedlight)
6578         {
6579                 Con_Print("No selected light.\n");
6580                 return;
6581         }
6582         R_Shadow_UpdateWorldLight(r_shadow_selectedlight, r_shadow_selectedlight->origin, r_shadow_selectedlight->angles, r_shadow_selectedlight->color, r_shadow_selectedlight->radius, r_shadow_selectedlight->corona, r_shadow_selectedlight->style, !r_shadow_selectedlight->shadow, r_shadow_selectedlight->cubemapname, r_shadow_selectedlight->coronasizescale, r_shadow_selectedlight->ambientscale, r_shadow_selectedlight->diffusescale, r_shadow_selectedlight->specularscale, r_shadow_selectedlight->flags);
6583 }
6584
6585 void R_Shadow_EditLights_ToggleCorona_f(void)
6586 {
6587         if (!r_editlights.integer)
6588         {
6589                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
6590                 return;
6591         }
6592         if (!r_shadow_selectedlight)
6593         {
6594                 Con_Print("No selected light.\n");
6595                 return;
6596         }
6597         R_Shadow_UpdateWorldLight(r_shadow_selectedlight, r_shadow_selectedlight->origin, r_shadow_selectedlight->angles, r_shadow_selectedlight->color, r_shadow_selectedlight->radius, !r_shadow_selectedlight->corona, r_shadow_selectedlight->style, r_shadow_selectedlight->shadow, r_shadow_selectedlight->cubemapname, r_shadow_selectedlight->coronasizescale, r_shadow_selectedlight->ambientscale, r_shadow_selectedlight->diffusescale, r_shadow_selectedlight->specularscale, r_shadow_selectedlight->flags);
6598 }
6599
6600 void R_Shadow_EditLights_Remove_f(void)
6601 {
6602         if (!r_editlights.integer)
6603         {
6604                 Con_Print("Cannot remove light when not in editing mode.  Set r_editlights to 1.\n");
6605                 return;
6606         }
6607         if (!r_shadow_selectedlight)
6608         {
6609                 Con_Print("No selected light.\n");
6610                 return;
6611         }
6612         R_Shadow_FreeWorldLight(r_shadow_selectedlight);
6613         r_shadow_selectedlight = NULL;
6614 }
6615
6616 void R_Shadow_EditLights_Help_f(void)
6617 {
6618         Con_Print(
6619 "Documentation on r_editlights system:\n"
6620 "Settings:\n"
6621 "r_editlights : enable/disable editing mode\n"
6622 "r_editlights_cursordistance : maximum distance of cursor from eye\n"
6623 "r_editlights_cursorpushback : push back cursor this far from surface\n"
6624 "r_editlights_cursorpushoff : push cursor off surface this far\n"
6625 "r_editlights_cursorgrid : snap cursor to grid of this size\n"
6626 "r_editlights_quakelightsizescale : imported quake light entity size scaling\n"
6627 "Commands:\n"
6628 "r_editlights_help : this help\n"
6629 "r_editlights_clear : remove all lights\n"
6630 "r_editlights_reload : reload .rtlights, .lights file, or entities\n"
6631 "r_editlights_lock : lock selection to current light, if already locked - unlock\n"
6632 "r_editlights_save : save to .rtlights file\n"
6633 "r_editlights_spawn : create a light with default settings\n"
6634 "r_editlights_edit command : edit selected light - more documentation below\n"
6635 "r_editlights_remove : remove selected light\n"
6636 "r_editlights_toggleshadow : toggles on/off selected light's shadow property\n"
6637 "r_editlights_importlightentitiesfrommap : reload light entities\n"
6638 "r_editlights_importlightsfile : reload .light file (produced by hlight)\n"
6639 "Edit commands:\n"
6640 "origin x y z : set light location\n"
6641 "originx x: set x component of light location\n"
6642 "originy y: set y component of light location\n"
6643 "originz z: set z component of light location\n"
6644 "move x y z : adjust light location\n"
6645 "movex x: adjust x component of light location\n"
6646 "movey y: adjust y component of light location\n"
6647 "movez z: adjust z component of light location\n"
6648 "angles x y z : set light angles\n"
6649 "anglesx x: set x component of light angles\n"
6650 "anglesy y: set y component of light angles\n"
6651 "anglesz z: set z component of light angles\n"
6652 "color r g b : set color of light (can be brighter than 1 1 1)\n"
6653 "radius radius : set radius (size) of light\n"
6654 "colorscale grey : multiply color of light (1 does nothing)\n"
6655 "colorscale r g b : multiply color of light (1 1 1 does nothing)\n"
6656 "radiusscale scale : multiply radius (size) of light (1 does nothing)\n"
6657 "sizescale scale : multiply radius (size) of light (1 does nothing)\n"
6658 "originscale x y z : multiply origin of light (1 1 1 does nothing)\n"
6659 "style style : set lightstyle of light (flickering patterns, switches, etc)\n"
6660 "cubemap basename : set filter cubemap of light (not yet supported)\n"
6661 "shadows 1/0 : turn on/off shadows\n"
6662 "corona n : set corona intensity\n"
6663 "coronasize n : set corona size (0-1)\n"
6664 "ambient n : set ambient intensity (0-1)\n"
6665 "diffuse n : set diffuse intensity (0-1)\n"
6666 "specular n : set specular intensity (0-1)\n"
6667 "normalmode 1/0 : turn on/off rendering of this light in rtworld 0 mode\n"
6668 "realtimemode 1/0 : turn on/off rendering of this light in rtworld 1 mode\n"
6669 "<nothing> : print light properties to console\n"
6670         );
6671 }
6672
6673 void R_Shadow_EditLights_CopyInfo_f(void)
6674 {
6675         if (!r_editlights.integer)
6676         {
6677                 Con_Print("Cannot copy light info when not in editing mode.  Set r_editlights to 1.\n");
6678                 return;
6679         }
6680         if (!r_shadow_selectedlight)
6681         {
6682                 Con_Print("No selected light.\n");
6683                 return;
6684         }
6685         VectorCopy(r_shadow_selectedlight->angles, r_shadow_bufferlight.angles);
6686         VectorCopy(r_shadow_selectedlight->color, r_shadow_bufferlight.color);
6687         r_shadow_bufferlight.radius = r_shadow_selectedlight->radius;
6688         r_shadow_bufferlight.style = r_shadow_selectedlight->style;
6689         if (r_shadow_selectedlight->cubemapname)
6690                 strlcpy(r_shadow_bufferlight.cubemapname, r_shadow_selectedlight->cubemapname, sizeof(r_shadow_bufferlight.cubemapname));
6691         else
6692                 r_shadow_bufferlight.cubemapname[0] = 0;
6693         r_shadow_bufferlight.shadow = r_shadow_selectedlight->shadow;
6694         r_shadow_bufferlight.corona = r_shadow_selectedlight->corona;
6695         r_shadow_bufferlight.coronasizescale = r_shadow_selectedlight->coronasizescale;
6696         r_shadow_bufferlight.ambientscale = r_shadow_selectedlight->ambientscale;
6697         r_shadow_bufferlight.diffusescale = r_shadow_selectedlight->diffusescale;
6698         r_shadow_bufferlight.specularscale = r_shadow_selectedlight->specularscale;
6699         r_shadow_bufferlight.flags = r_shadow_selectedlight->flags;
6700 }
6701
6702 void R_Shadow_EditLights_PasteInfo_f(void)
6703 {
6704         if (!r_editlights.integer)
6705         {
6706                 Con_Print("Cannot paste light info when not in editing mode.  Set r_editlights to 1.\n");
6707                 return;
6708         }
6709         if (!r_shadow_selectedlight)
6710         {
6711                 Con_Print("No selected light.\n");
6712                 return;
6713         }
6714         R_Shadow_UpdateWorldLight(r_shadow_selectedlight, r_shadow_selectedlight->origin, r_shadow_bufferlight.angles, r_shadow_bufferlight.color, r_shadow_bufferlight.radius, r_shadow_bufferlight.corona, r_shadow_bufferlight.style, r_shadow_bufferlight.shadow, r_shadow_bufferlight.cubemapname, r_shadow_bufferlight.coronasizescale, r_shadow_bufferlight.ambientscale, r_shadow_bufferlight.diffusescale, r_shadow_bufferlight.specularscale, r_shadow_bufferlight.flags);
6715 }
6716
6717 void R_Shadow_EditLights_Lock_f(void)
6718 {
6719         if (!r_editlights.integer)
6720         {
6721                 Con_Print("Cannot lock on light when not in editing mode.  Set r_editlights to 1.\n");
6722                 return;
6723         }
6724         if (r_editlights_lockcursor)
6725         {
6726                 r_editlights_lockcursor = false;
6727                 return;
6728         }
6729         if (!r_shadow_selectedlight)
6730         {
6731                 Con_Print("No selected light to lock on.\n");
6732                 return;
6733         }
6734         r_editlights_lockcursor = true;
6735 }
6736
6737 void R_Shadow_EditLights_Init(void)
6738 {
6739         Cvar_RegisterVariable(&r_editlights);
6740         Cvar_RegisterVariable(&r_editlights_cursordistance);
6741         Cvar_RegisterVariable(&r_editlights_cursorpushback);
6742         Cvar_RegisterVariable(&r_editlights_cursorpushoff);
6743         Cvar_RegisterVariable(&r_editlights_cursorgrid);
6744         Cvar_RegisterVariable(&r_editlights_quakelightsizescale);
6745         Cmd_AddCommand("r_editlights_help", R_Shadow_EditLights_Help_f, "prints documentation on console commands and variables in rtlight editing system");
6746         Cmd_AddCommand("r_editlights_clear", R_Shadow_EditLights_Clear_f, "removes all world lights (let there be darkness!)");
6747         Cmd_AddCommand("r_editlights_reload", R_Shadow_EditLights_Reload_f, "reloads rtlights file (or imports from .lights file or .ent file or the map itself)");
6748         Cmd_AddCommand("r_editlights_save", R_Shadow_EditLights_Save_f, "save .rtlights file for current level");
6749         Cmd_AddCommand("r_editlights_spawn", R_Shadow_EditLights_Spawn_f, "creates a light with default properties (let there be light!)");
6750         Cmd_AddCommand("r_editlights_edit", R_Shadow_EditLights_Edit_f, "changes a property on the selected light");
6751         Cmd_AddCommand("r_editlights_editall", R_Shadow_EditLights_EditAll_f, "changes a property on ALL lights at once (tip: use radiusscale and colorscale to alter these properties)");
6752         Cmd_AddCommand("r_editlights_remove", R_Shadow_EditLights_Remove_f, "remove selected light");
6753         Cmd_AddCommand("r_editlights_toggleshadow", R_Shadow_EditLights_ToggleShadow_f, "toggle on/off the shadow option on the selected light");
6754         Cmd_AddCommand("r_editlights_togglecorona", R_Shadow_EditLights_ToggleCorona_f, "toggle on/off the corona option on the selected light");
6755         Cmd_AddCommand("r_editlights_importlightentitiesfrommap", R_Shadow_EditLights_ImportLightEntitiesFromMap_f, "load lights from .ent file or map entities (ignoring .rtlights or .lights file)");
6756         Cmd_AddCommand("r_editlights_importlightsfile", R_Shadow_EditLights_ImportLightsFile_f, "load lights from .lights file (ignoring .rtlights or .ent files and map entities)");
6757         Cmd_AddCommand("r_editlights_copyinfo", R_Shadow_EditLights_CopyInfo_f, "store a copy of all properties (except origin) of the selected light");
6758         Cmd_AddCommand("r_editlights_pasteinfo", R_Shadow_EditLights_PasteInfo_f, "apply the stored properties onto the selected light (making it exactly identical except for origin)");
6759         Cmd_AddCommand("r_editlights_lock", R_Shadow_EditLights_Lock_f, "lock selection to current light, if already locked - unlock");
6760 }
6761
6762
6763
6764 /*
6765 =============================================================================
6766
6767 LIGHT SAMPLING
6768
6769 =============================================================================
6770 */
6771
6772 void R_LightPoint(vec3_t color, const vec3_t p, const int flags)
6773 {
6774         int i, numlights, flag;
6775         float f, relativepoint[3], dist, dist2, lightradius2;
6776         vec3_t diffuse, n;
6777         rtlight_t *light;
6778         dlight_t *dlight;
6779
6780         if (r_fullbright.integer)
6781         {
6782                 VectorSet(color, 1, 1, 1);
6783                 return;
6784         }
6785
6786         VectorClear(color);
6787
6788         if (flags & LP_LIGHTMAP)
6789         {
6790                 if (!r_fullbright.integer && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6791                 {
6792                         VectorClear(diffuse);
6793                         r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, color, diffuse, n);
6794                         VectorAdd(color, diffuse, color);
6795                 }
6796                 else
6797                         VectorSet(color, 1, 1, 1);
6798                 color[0] += r_refdef.scene.ambient;
6799                 color[1] += r_refdef.scene.ambient;
6800                 color[2] += r_refdef.scene.ambient;
6801         }
6802
6803         if (flags & LP_RTWORLD)
6804         {
6805                 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
6806                 numlights = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
6807                 for (i = 0; i < numlights; i++)
6808                 {
6809                         dlight = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, i);
6810                         if (!dlight)
6811                                 continue;
6812                         light = &dlight->rtlight;
6813                         if (!(light->flags & flag))
6814                                 continue;
6815                         // sample
6816                         lightradius2 = light->radius * light->radius;
6817                         VectorSubtract(light->shadoworigin, p, relativepoint);
6818                         dist2 = VectorLength2(relativepoint);
6819                         if (dist2 >= lightradius2)
6820                                 continue;
6821                         dist = sqrt(dist2) / light->radius;
6822                         f = dist < 1 ? (r_shadow_lightintensityscale.value * ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist))) : 0;
6823                         if (f <= 0)
6824                                 continue;
6825                         // todo: add to both ambient and diffuse
6826                         if (!light->shadow || CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1)
6827                                 VectorMA(color, f, light->currentcolor, color);
6828                 }
6829         }
6830         if (flags & LP_DYNLIGHT)
6831         {
6832                 // sample dlights
6833                 for (i = 0;i < r_refdef.scene.numlights;i++)
6834                 {
6835                         light = r_refdef.scene.lights[i];
6836                         // sample
6837                         lightradius2 = light->radius * light->radius;
6838                         VectorSubtract(light->shadoworigin, p, relativepoint);
6839                         dist2 = VectorLength2(relativepoint);
6840                         if (dist2 >= lightradius2)
6841                                 continue;
6842                         dist = sqrt(dist2) / light->radius;
6843                         f = dist < 1 ? (r_shadow_lightintensityscale.value * ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist))) : 0;
6844                         if (f <= 0)
6845                                 continue;
6846                         // todo: add to both ambient and diffuse
6847                         if (!light->shadow || CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1)
6848                                 VectorMA(color, f, light->color, color);
6849                 }
6850         }
6851 }
6852
6853 void R_CompleteLightPoint(vec3_t ambient, vec3_t diffuse, vec3_t lightdir, const vec3_t p, const int flags)
6854 {
6855         int i, numlights, flag;
6856         rtlight_t *light;
6857         dlight_t *dlight;
6858         float relativepoint[3];
6859         float color[3];
6860         float dir[3];
6861         float dist;
6862         float dist2;
6863         float intensity;
6864         float sample[5*3];
6865         float lightradius2;
6866
6867         if (r_fullbright.integer)
6868         {
6869                 VectorSet(ambient, 1, 1, 1);
6870                 VectorClear(diffuse);
6871                 VectorClear(lightdir);
6872                 return;
6873         }
6874
6875         if (flags == LP_LIGHTMAP)
6876         {
6877                 VectorSet(ambient, r_refdef.scene.ambient, r_refdef.scene.ambient, r_refdef.scene.ambient);
6878                 VectorClear(diffuse);
6879                 VectorClear(lightdir);
6880                 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6881                         r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, ambient, diffuse, lightdir);
6882                 else
6883                         VectorSet(ambient, 1, 1, 1);
6884                 return;
6885         }
6886
6887         memset(sample, 0, sizeof(sample));
6888         VectorSet(sample, r_refdef.scene.ambient, r_refdef.scene.ambient, r_refdef.scene.ambient);
6889
6890         if ((flags & LP_LIGHTMAP) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6891         {
6892                 vec3_t tempambient;
6893                 VectorClear(tempambient);
6894                 VectorClear(color);
6895                 VectorClear(relativepoint);
6896                 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, tempambient, color, relativepoint);
6897                 VectorScale(tempambient, r_refdef.lightmapintensity, tempambient);
6898                 VectorScale(color, r_refdef.lightmapintensity, color);
6899                 VectorAdd(sample, tempambient, sample);
6900                 VectorMA(sample    , 0.5f            , color, sample    );
6901                 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6902                 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6903                 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6904                 // calculate a weighted average light direction as well
6905                 intensity = VectorLength(color);
6906                 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6907         }
6908
6909         if (flags & LP_RTWORLD)
6910         {
6911                 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
6912                 numlights = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
6913                 for (i = 0; i < numlights; i++)
6914                 {
6915                         dlight = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, i);
6916                         if (!dlight)
6917                                 continue;
6918                         light = &dlight->rtlight;
6919                         if (!(light->flags & flag))
6920                                 continue;
6921                         // sample
6922                         lightradius2 = light->radius * light->radius;
6923                         VectorSubtract(light->shadoworigin, p, relativepoint);
6924                         dist2 = VectorLength2(relativepoint);
6925                         if (dist2 >= lightradius2)
6926                                 continue;
6927                         dist = sqrt(dist2) / light->radius;
6928                         intensity = min(1.0f, (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) * r_shadow_lightintensityscale.value;
6929                         if (intensity <= 0.0f)
6930                                 continue;
6931                         if (light->shadow && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
6932                                 continue;
6933                         // scale down intensity to add to both ambient and diffuse
6934                         //intensity *= 0.5f;
6935                         VectorNormalize(relativepoint);
6936                         VectorScale(light->currentcolor, intensity, color);
6937                         VectorMA(sample    , 0.5f            , color, sample    );
6938                         VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6939                         VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6940                         VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6941                         // calculate a weighted average light direction as well
6942                         intensity *= VectorLength(color);
6943                         VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6944                 }
6945         }
6946
6947         if (flags & LP_DYNLIGHT)
6948         {
6949                 // sample dlights
6950                 for (i = 0;i < r_refdef.scene.numlights;i++)
6951                 {
6952                         light = r_refdef.scene.lights[i];
6953                         // sample
6954                         lightradius2 = light->radius * light->radius;
6955                         VectorSubtract(light->shadoworigin, p, relativepoint);
6956                         dist2 = VectorLength2(relativepoint);
6957                         if (dist2 >= lightradius2)
6958                                 continue;
6959                         dist = sqrt(dist2) / light->radius;
6960                         intensity = (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist) * r_shadow_lightintensityscale.value;
6961                         if (intensity <= 0.0f)
6962                                 continue;
6963                         if (light->shadow && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
6964                                 continue;
6965                         // scale down intensity to add to both ambient and diffuse
6966                         //intensity *= 0.5f;
6967                         VectorNormalize(relativepoint);
6968                         VectorScale(light->currentcolor, intensity, color);
6969                         VectorMA(sample    , 0.5f            , color, sample    );
6970                         VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6971                         VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6972                         VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6973                         // calculate a weighted average light direction as well
6974                         intensity *= VectorLength(color);
6975                         VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6976                 }
6977         }
6978
6979         // calculate the direction we'll use to reduce the sample to a directional light source
6980         VectorCopy(sample + 12, dir);
6981         //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
6982         VectorNormalize(dir);
6983         // extract the diffuse color along the chosen direction and scale it
6984         diffuse[0] = (dir[0]*sample[3] + dir[1]*sample[6] + dir[2]*sample[ 9] + sample[ 0]);
6985         diffuse[1] = (dir[0]*sample[4] + dir[1]*sample[7] + dir[2]*sample[10] + sample[ 1]);
6986         diffuse[2] = (dir[0]*sample[5] + dir[1]*sample[8] + dir[2]*sample[11] + sample[ 2]);
6987         // subtract some of diffuse from ambient
6988         VectorMA(sample, -0.333f, diffuse, ambient);
6989         // store the normalized lightdir
6990         VectorCopy(dir, lightdir);
6991 }