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