]> git.xonotic.org Git - xonotic/darkplaces.git/blob - r_shadow.c
Implement GPU-side corona fading
[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 qboolean r_shadow_shadowmapdepthtexture;
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", "0", "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", "0", "use GL_ARB_occlusion_query extension if supported (fades coronas according to visibility) - bad performance (synchronous rendering) - worse on multi-gpu!"};
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_shadowmapdepthtexture = r_fb.usedepthtextures;
456         r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL;
457         if ((r_shadow_shadowmapping.integer || r_shadow_deferred.integer) && vid.support.ext_framebuffer_object)
458         {
459                 switch(vid.renderpath)
460                 {
461                 case RENDERPATH_GL20:
462                         if(r_shadow_shadowmapfilterquality < 0)
463                         {
464                                 if (!r_fb.usedepthtextures)
465                                         r_shadow_shadowmappcf = 1;
466                                 else if((strstr(gl_vendor, "NVIDIA") || strstr(gl_renderer, "Radeon HD")) && vid.support.arb_shadow && r_shadow_shadowmapshadowsampler) 
467                                 {
468                                         r_shadow_shadowmapsampler = true;
469                                         r_shadow_shadowmappcf = 1;
470                                 }
471                                 else if(vid.support.amd_texture_texture4 || vid.support.arb_texture_gather)
472                                         r_shadow_shadowmappcf = 1;
473                                 else if((strstr(gl_vendor, "ATI") || strstr(gl_vendor, "Advanced Micro Devices")) && !strstr(gl_renderer, "Mesa") && !strstr(gl_version, "Mesa")) 
474                                         r_shadow_shadowmappcf = 1;
475                                 else 
476                                         r_shadow_shadowmapsampler = vid.support.arb_shadow && r_shadow_shadowmapshadowsampler;
477                         }
478                         else 
479                         {
480                 r_shadow_shadowmapsampler = vid.support.arb_shadow && r_shadow_shadowmapshadowsampler;
481                                 switch (r_shadow_shadowmapfilterquality)
482                                 {
483                                 case 1:
484                                         break;
485                                 case 2:
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                                  && TriangleBBoxOverlapsBox(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                                  && TriangleBBoxOverlapsBox(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, 0);
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[r_stat_lights_dynamicshadowtriangles] += tris;
1400                 r_refdef.stats[r_stat_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, 0);
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 o, 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         Matrix4x4_OriginFromMatrix(&rtlight->matrix_lighttoworld, o);
1556         for (i = 0;i < 5;i++)
1557         {
1558                 if (PlaneDiff(o, &r_refdef.view.frustum[i]) > -0.03125)
1559                         continue;
1560                 Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[i].normal, n);
1561                 len = scale*VectorLength2(n);
1562                 if(n[0]*n[0] > len) sides &= n[0] < 0 ? ~(1<<0) : ~(2 << 0);
1563                 if(n[1]*n[1] > len) sides &= n[1] < 0 ? ~(1<<2) : ~(2 << 2);
1564                 if(n[2]*n[2] > len) sides &= n[2] < 0 ? ~(1<<4) : ~(2 << 4);
1565         }
1566         if (PlaneDiff(o, &r_refdef.view.frustum[4]) >= r_refdef.farclip - r_refdef.nearclip + 0.03125)
1567         {
1568                 Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[4].normal, n);
1569                 len = scale*VectorLength2(n);
1570                 if(n[0]*n[0] > len) sides &= n[0] >= 0 ? ~(1<<0) : ~(2 << 0);
1571                 if(n[1]*n[1] > len) sides &= n[1] >= 0 ? ~(1<<2) : ~(2 << 2);
1572                 if(n[2]*n[2] > len) sides &= n[2] >= 0 ? ~(1<<4) : ~(2 << 4);
1573         }
1574         // this next test usually clips off more sides than the former, but occasionally clips fewer/different ones, so do both and combine results
1575         // check if frustum corners/origin cross plane sides
1576 #if 1
1577         // infinite version, assumes frustum corners merely give direction and extend to infinite distance
1578         Matrix4x4_Transform(&rtlight->matrix_worldtolight, r_refdef.view.origin, p);
1579         dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn);
1580         masks[0] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1581         masks[1] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1582         dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn);
1583         masks[2] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1584         masks[3] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1585         dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn);
1586         masks[4] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1587         masks[5] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1588         for (i = 0;i < 4;i++)
1589         {
1590                 Matrix4x4_Transform(&rtlight->matrix_worldtolight, r_refdef.view.frustumcorner[i], n);
1591                 VectorSubtract(n, p, n);
1592                 dp = n[0] + n[1], dn = n[0] - n[1], ap = fabs(dp), an = fabs(dn);
1593                 if(ap > 0) masks[0] |= dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2);
1594                 if(an > 0) masks[1] |= dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2);
1595                 dp = n[1] + n[2], dn = n[1] - n[2], ap = fabs(dp), an = fabs(dn);
1596                 if(ap > 0) masks[2] |= dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4);
1597                 if(an > 0) masks[3] |= dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4);
1598                 dp = n[2] + n[0], dn = n[2] - n[0], ap = fabs(dp), an = fabs(dn);
1599                 if(ap > 0) masks[4] |= dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0);
1600                 if(an > 0) masks[5] |= dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0);
1601         }
1602 #else
1603         // finite version, assumes corners are a finite distance from origin dependent on far plane
1604         for (i = 0;i < 5;i++)
1605         {
1606                 Matrix4x4_Transform(&rtlight->matrix_worldtolight, !i ? r_refdef.view.origin : r_refdef.view.frustumcorner[i-1], p);
1607                 dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn);
1608                 masks[0] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1609                 masks[1] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1610                 dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn);
1611                 masks[2] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1612                 masks[3] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1613                 dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn);
1614                 masks[4] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1615                 masks[5] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1616         }
1617 #endif
1618         return sides & masks[0] & masks[1] & masks[2] & masks[3] & masks[4] & masks[5];
1619 }
1620
1621 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)
1622 {
1623         int t, tend;
1624         const int *e;
1625         const float *v[3];
1626         float normal[3];
1627         vec3_t p[3];
1628         float bias;
1629         int mask, surfacemask = 0;
1630         if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1631                 return 0;
1632         bias = r_shadow_shadowmapborder / (float)(r_shadow_shadowmapmaxsize - r_shadow_shadowmapborder);
1633         tend = firsttriangle + numtris;
1634         if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1635         {
1636                 // surface box entirely inside light box, no box cull
1637                 if (projectdirection)
1638                 {
1639                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1640                         {
1641                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1642                                 TriangleNormal(v[0], v[1], v[2], normal);
1643                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1644                                 {
1645                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1646                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1647                                         surfacemask |= mask;
1648                                         if(totals)
1649                                         {
1650                                                 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;
1651                                                 shadowsides[numshadowsides] = mask;
1652                                                 shadowsideslist[numshadowsides++] = t;
1653                                         }
1654                                 }
1655                         }
1656                 }
1657                 else
1658                 {
1659                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1660                         {
1661                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3,     v[2] = invertex3f + e[2] * 3;
1662                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2]))
1663                                 {
1664                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1665                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1666                                         surfacemask |= mask;
1667                                         if(totals)
1668                                         {
1669                                                 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;
1670                                                 shadowsides[numshadowsides] = mask;
1671                                                 shadowsideslist[numshadowsides++] = t;
1672                                         }
1673                                 }
1674                         }
1675                 }
1676         }
1677         else
1678         {
1679                 // surface box not entirely inside light box, cull each triangle
1680                 if (projectdirection)
1681                 {
1682                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1683                         {
1684                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3,     v[2] = invertex3f + e[2] * 3;
1685                                 TriangleNormal(v[0], v[1], v[2], normal);
1686                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1687                                  && TriangleBBoxOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1688                                 {
1689                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1690                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1691                                         surfacemask |= mask;
1692                                         if(totals)
1693                                         {
1694                                                 totals[0] += mask&1, totals[1] += (mask>>1)&1, totals[2] += (mask>>2)&1, totals[3] += (mask>>3)&1, totals[4] += (mask>>4)&1, totals[5] += mask>>5;
1695                                                 shadowsides[numshadowsides] = mask;
1696                                                 shadowsideslist[numshadowsides++] = t;
1697                                         }
1698                                 }
1699                         }
1700                 }
1701                 else
1702                 {
1703                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1704                         {
1705                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1706                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1707                                  && TriangleBBoxOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1708                                 {
1709                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1710                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1711                                         surfacemask |= mask;
1712                                         if(totals)
1713                                         {
1714                                                 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;
1715                                                 shadowsides[numshadowsides] = mask;
1716                                                 shadowsideslist[numshadowsides++] = t;
1717                                         }
1718                                 }
1719                         }
1720                 }
1721         }
1722         return surfacemask;
1723 }
1724
1725 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)
1726 {
1727         int i, j, outtriangles = 0;
1728         int *outelement3i[6];
1729         if (!numverts || !numsidetris || !r_shadow_compilingrtlight)
1730                 return;
1731         outtriangles = sidetotals[0] + sidetotals[1] + sidetotals[2] + sidetotals[3] + sidetotals[4] + sidetotals[5];
1732         // make sure shadowelements is big enough for this mesh
1733         if (maxshadowtriangles < outtriangles)
1734                 R_Shadow_ResizeShadowArrays(0, outtriangles, 0, 1);
1735
1736         // compute the offset and size of the separate index lists for each cubemap side
1737         outtriangles = 0;
1738         for (i = 0;i < 6;i++)
1739         {
1740                 outelement3i[i] = shadowelements + outtriangles * 3;
1741                 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap->sideoffsets[i] = outtriangles;
1742                 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap->sidetotals[i] = sidetotals[i];
1743                 outtriangles += sidetotals[i];
1744         }
1745
1746         // gather up the (sparse) triangles into separate index lists for each cubemap side
1747         for (i = 0;i < numsidetris;i++)
1748         {
1749                 const int *element = elements + sidetris[i] * 3;
1750                 for (j = 0;j < 6;j++)
1751                 {
1752                         if (sides[i] & (1 << j))
1753                         {
1754                                 outelement3i[j][0] = element[0];
1755                                 outelement3i[j][1] = element[1];
1756                                 outelement3i[j][2] = element[2];
1757                                 outelement3i[j] += 3;
1758                         }
1759                 }
1760         }
1761                         
1762         Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap, NULL, NULL, NULL, vertex3f, NULL, NULL, NULL, NULL, outtriangles, shadowelements);
1763 }
1764
1765 static void R_Shadow_MakeTextures_MakeCorona(void)
1766 {
1767         float dx, dy;
1768         int x, y, a;
1769         unsigned char pixels[32][32][4];
1770         for (y = 0;y < 32;y++)
1771         {
1772                 dy = (y - 15.5f) * (1.0f / 16.0f);
1773                 for (x = 0;x < 32;x++)
1774                 {
1775                         dx = (x - 15.5f) * (1.0f / 16.0f);
1776                         a = (int)(((1.0f / (dx * dx + dy * dy + 0.2f)) - (1.0f / (1.0f + 0.2))) * 32.0f / (1.0f / (1.0f + 0.2)));
1777                         a = bound(0, a, 255);
1778                         pixels[y][x][0] = a;
1779                         pixels[y][x][1] = a;
1780                         pixels[y][x][2] = a;
1781                         pixels[y][x][3] = 255;
1782                 }
1783         }
1784         r_shadow_lightcorona = R_SkinFrame_LoadInternalBGRA("lightcorona", TEXF_FORCELINEAR, &pixels[0][0][0], 32, 32, false);
1785 }
1786
1787 static unsigned int R_Shadow_MakeTextures_SamplePoint(float x, float y, float z)
1788 {
1789         float dist = sqrt(x*x+y*y+z*z);
1790         float intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1791         // note this code could suffer byte order issues except that it is multiplying by an integer that reads the same both ways
1792         return (unsigned char)bound(0, intensity * 256.0f, 255) * 0x01010101;
1793 }
1794
1795 static void R_Shadow_MakeTextures(void)
1796 {
1797         int x, y, z;
1798         float intensity, dist;
1799         unsigned int *data;
1800         R_Shadow_FreeShadowMaps();
1801         R_FreeTexturePool(&r_shadow_texturepool);
1802         r_shadow_texturepool = R_AllocTexturePool();
1803         r_shadow_attenlinearscale = r_shadow_lightattenuationlinearscale.value;
1804         r_shadow_attendividebias = r_shadow_lightattenuationdividebias.value;
1805         data = (unsigned int *)Mem_Alloc(tempmempool, max(max(ATTEN3DSIZE*ATTEN3DSIZE*ATTEN3DSIZE, ATTEN2DSIZE*ATTEN2DSIZE), ATTEN1DSIZE) * 4);
1806         // the table includes one additional value to avoid the need to clamp indexing due to minor math errors
1807         for (x = 0;x <= ATTENTABLESIZE;x++)
1808         {
1809                 dist = (x + 0.5f) * (1.0f / ATTENTABLESIZE) * (1.0f / 0.9375);
1810                 intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1811                 r_shadow_attentable[x] = bound(0, intensity, 1);
1812         }
1813         // 1D gradient texture
1814         for (x = 0;x < ATTEN1DSIZE;x++)
1815                 data[x] = R_Shadow_MakeTextures_SamplePoint((x + 0.5f) * (1.0f / ATTEN1DSIZE) * (1.0f / 0.9375), 0, 0);
1816         r_shadow_attenuationgradienttexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation1d", ATTEN1DSIZE, 1, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1817         // 2D circle texture
1818         for (y = 0;y < ATTEN2DSIZE;y++)
1819                 for (x = 0;x < ATTEN2DSIZE;x++)
1820                         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);
1821         r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1822         // 3D sphere texture
1823         if (r_shadow_texture3d.integer && vid.support.ext_texture_3d)
1824         {
1825                 for (z = 0;z < ATTEN3DSIZE;z++)
1826                         for (y = 0;y < ATTEN3DSIZE;y++)
1827                                 for (x = 0;x < ATTEN3DSIZE;x++)
1828                                         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));
1829                 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);
1830         }
1831         else
1832                 r_shadow_attenuation3dtexture = NULL;
1833         Mem_Free(data);
1834
1835         R_Shadow_MakeTextures_MakeCorona();
1836
1837         // Editor light sprites
1838         r_editlights_sprcursor = R_SkinFrame_LoadInternal8bit("gfx/editlights/cursor", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1839         "................"
1840         ".3............3."
1841         "..5...2332...5.."
1842         "...7.3....3.7..."
1843         "....7......7...."
1844         "...3.7....7.3..."
1845         "..2...7..7...2.."
1846         "..3..........3.."
1847         "..3..........3.."
1848         "..2...7..7...2.."
1849         "...3.7....7.3..."
1850         "....7......7...."
1851         "...7.3....3.7..."
1852         "..5...2332...5.."
1853         ".3............3."
1854         "................"
1855         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1856         r_editlights_sprlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/light", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1857         "................"
1858         "................"
1859         "......1111......"
1860         "....11233211...."
1861         "...1234554321..."
1862         "...1356776531..."
1863         "..124677776421.."
1864         "..135777777531.."
1865         "..135777777531.."
1866         "..124677776421.."
1867         "...1356776531..."
1868         "...1234554321..."
1869         "....11233211...."
1870         "......1111......"
1871         "................"
1872         "................"
1873         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1874         r_editlights_sprnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/noshadow", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1875         "................"
1876         "................"
1877         "......1111......"
1878         "....11233211...."
1879         "...1234554321..."
1880         "...1356226531..."
1881         "..12462..26421.."
1882         "..1352....2531.."
1883         "..1352....2531.."
1884         "..12462..26421.."
1885         "...1356226531..."
1886         "...1234554321..."
1887         "....11233211...."
1888         "......1111......"
1889         "................"
1890         "................"
1891         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1892         r_editlights_sprcubemaplight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemaplight", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1893         "................"
1894         "................"
1895         "......2772......"
1896         "....27755772...."
1897         "..277533335772.."
1898         "..753333333357.."
1899         "..777533335777.."
1900         "..735775577537.."
1901         "..733357753337.."
1902         "..733337733337.."
1903         "..753337733357.."
1904         "..277537735772.."
1905         "....27777772...."
1906         "......2772......"
1907         "................"
1908         "................"
1909         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1910         r_editlights_sprcubemapnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemapnoshadowlight", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1911         "................"
1912         "................"
1913         "......2772......"
1914         "....27722772...."
1915         "..2772....2772.."
1916         "..72........27.."
1917         "..7772....2777.."
1918         "..7.27722772.7.."
1919         "..7...2772...7.."
1920         "..7....77....7.."
1921         "..72...77...27.."
1922         "..2772.77.2772.."
1923         "....27777772...."
1924         "......2772......"
1925         "................"
1926         "................"
1927         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1928         r_editlights_sprselection = R_SkinFrame_LoadInternal8bit("gfx/editlights/selection", TEXF_ALPHA | TEXF_CLAMP, (unsigned char *)
1929         "................"
1930         ".777752..257777."
1931         ".742........247."
1932         ".72..........27."
1933         ".7............7."
1934         ".5............5."
1935         ".2............2."
1936         "................"
1937         "................"
1938         ".2............2."
1939         ".5............5."
1940         ".7............7."
1941         ".72..........27."
1942         ".742........247."
1943         ".777752..257777."
1944         "................"
1945         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1946 }
1947
1948 void R_Shadow_ValidateCvars(void)
1949 {
1950         if (r_shadow_texture3d.integer && !vid.support.ext_texture_3d)
1951                 Cvar_SetValueQuick(&r_shadow_texture3d, 0);
1952         if (gl_ext_separatestencil.integer && !vid.support.ati_separate_stencil)
1953                 Cvar_SetValueQuick(&gl_ext_separatestencil, 0);
1954         if (gl_ext_stenciltwoside.integer && !vid.support.ext_stencil_two_side)
1955                 Cvar_SetValueQuick(&gl_ext_stenciltwoside, 0);
1956 }
1957
1958 void R_Shadow_RenderMode_Begin(void)
1959 {
1960 #if 0
1961         GLint drawbuffer;
1962         GLint readbuffer;
1963 #endif
1964         R_Shadow_ValidateCvars();
1965
1966         if (!r_shadow_attenuation2dtexture
1967          || (!r_shadow_attenuation3dtexture && r_shadow_texture3d.integer)
1968          || r_shadow_lightattenuationdividebias.value != r_shadow_attendividebias
1969          || r_shadow_lightattenuationlinearscale.value != r_shadow_attenlinearscale)
1970                 R_Shadow_MakeTextures();
1971
1972         CHECKGLERROR
1973         R_Mesh_ResetTextureState();
1974         GL_BlendFunc(GL_ONE, GL_ZERO);
1975         GL_DepthRange(0, 1);
1976         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
1977         GL_DepthTest(true);
1978         GL_DepthMask(false);
1979         GL_Color(0, 0, 0, 1);
1980         GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
1981         
1982         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
1983
1984         if (gl_ext_separatestencil.integer && vid.support.ati_separate_stencil)
1985         {
1986                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL;
1987                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL;
1988         }
1989         else if (gl_ext_stenciltwoside.integer && vid.support.ext_stencil_two_side)
1990         {
1991                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE;
1992                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE;
1993         }
1994         else
1995         {
1996                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCIL;
1997                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCIL;
1998         }
1999
2000         switch(vid.renderpath)
2001         {
2002         case RENDERPATH_GL20:
2003         case RENDERPATH_D3D9:
2004         case RENDERPATH_D3D10:
2005         case RENDERPATH_D3D11:
2006         case RENDERPATH_SOFT:
2007         case RENDERPATH_GLES2:
2008                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_GLSL;
2009                 break;
2010         case RENDERPATH_GL11:
2011         case RENDERPATH_GL13:
2012         case RENDERPATH_GLES1:
2013                 if (r_textureunits.integer >= 2 && vid.texunits >= 2 && r_shadow_texture3d.integer && r_shadow_attenuation3dtexture)
2014                         r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN;
2015                 else if (r_textureunits.integer >= 3 && vid.texunits >= 3)
2016                         r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN;
2017                 else if (r_textureunits.integer >= 2 && vid.texunits >= 2)
2018                         r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN;
2019                 else
2020                         r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX;
2021                 break;
2022         }
2023
2024         CHECKGLERROR
2025 #if 0
2026         qglGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);CHECKGLERROR
2027         qglGetIntegerv(GL_READ_BUFFER, &readbuffer);CHECKGLERROR
2028         r_shadow_drawbuffer = drawbuffer;
2029         r_shadow_readbuffer = readbuffer;
2030 #endif
2031         r_shadow_cullface_front = r_refdef.view.cullface_front;
2032         r_shadow_cullface_back = r_refdef.view.cullface_back;
2033 }
2034
2035 void R_Shadow_RenderMode_ActiveLight(const rtlight_t *rtlight)
2036 {
2037         rsurface.rtlight = rtlight;
2038 }
2039
2040 void R_Shadow_RenderMode_Reset(void)
2041 {
2042         R_Mesh_ResetTextureState();
2043         R_Mesh_SetRenderTargets(r_shadow_fb_fbo, r_shadow_fb_depthtexture, r_shadow_fb_colortexture, NULL, NULL, NULL);
2044         R_SetViewport(&r_refdef.view.viewport);
2045         GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
2046         GL_DepthRange(0, 1);
2047         GL_DepthTest(true);
2048         GL_DepthMask(false);
2049         GL_DepthFunc(GL_LEQUAL);
2050         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
2051         r_refdef.view.cullface_front = r_shadow_cullface_front;
2052         r_refdef.view.cullface_back = r_shadow_cullface_back;
2053         GL_CullFace(r_refdef.view.cullface_back);
2054         GL_Color(1, 1, 1, 1);
2055         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
2056         GL_BlendFunc(GL_ONE, GL_ZERO);
2057         R_SetupShader_Generic_NoTexture(false, false);
2058         r_shadow_usingshadowmap2d = false;
2059         r_shadow_usingshadowmaportho = false;
2060         R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
2061 }
2062
2063 void R_Shadow_ClearStencil(void)
2064 {
2065         GL_Clear(GL_STENCIL_BUFFER_BIT, NULL, 1.0f, 128);
2066         r_refdef.stats[r_stat_lights_clears]++;
2067 }
2068
2069 void R_Shadow_RenderMode_StencilShadowVolumes(qboolean zpass)
2070 {
2071         r_shadow_rendermode_t mode = zpass ? r_shadow_shadowingrendermode_zpass : r_shadow_shadowingrendermode_zfail;
2072         if (r_shadow_rendermode == mode)
2073                 return;
2074         R_Shadow_RenderMode_Reset();
2075         GL_DepthFunc(GL_LESS);
2076         GL_ColorMask(0, 0, 0, 0);
2077         GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
2078         GL_CullFace(GL_NONE);
2079         R_SetupShader_DepthOrShadow(false, false, false); // FIXME test if we have a skeletal model?
2080         r_shadow_rendermode = mode;
2081         switch(mode)
2082         {
2083         default:
2084                 break;
2085         case R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE:
2086         case R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL:
2087                 R_SetStencilSeparate(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, GL_ALWAYS, 128, 255);
2088                 break;
2089         case R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE:
2090         case R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL:
2091                 R_SetStencilSeparate(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, GL_ALWAYS, 128, 255);
2092                 break;
2093         }
2094 }
2095
2096 static void R_Shadow_MakeVSDCT(void)
2097 {
2098         // maps to a 2x3 texture rectangle with normalized coordinates
2099         // +-
2100         // XX
2101         // YY
2102         // ZZ
2103         // stores abs(dir.xy), offset.xy/2.5
2104         unsigned char data[4*6] =
2105         {
2106                 255, 0, 0x33, 0x33, // +X: <1, 0>, <0.5, 0.5>
2107                 255, 0, 0x99, 0x33, // -X: <1, 0>, <1.5, 0.5>
2108                 0, 255, 0x33, 0x99, // +Y: <0, 1>, <0.5, 1.5>
2109                 0, 255, 0x99, 0x99, // -Y: <0, 1>, <1.5, 1.5>
2110                 0,   0, 0x33, 0xFF, // +Z: <0, 0>, <0.5, 2.5>
2111                 0,   0, 0x99, 0xFF, // -Z: <0, 0>, <1.5, 2.5>
2112         };
2113         r_shadow_shadowmapvsdcttexture = R_LoadTextureCubeMap(r_shadow_texturepool, "shadowmapvsdct", 1, data, TEXTYPE_RGBA, TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, -1, NULL);
2114 }
2115
2116 static void R_Shadow_MakeShadowMap(int side, int size)
2117 {
2118         switch (r_shadow_shadowmode)
2119         {
2120         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
2121                 if (r_shadow_shadowmap2ddepthtexture) return;
2122                 if (r_fb.usedepthtextures)
2123                 {
2124                         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);
2125                         r_shadow_shadowmap2ddepthbuffer = NULL;
2126                         r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL, NULL);
2127                 }
2128                 else
2129                 {
2130                         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);
2131                         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);
2132                         r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2ddepthbuffer, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL);
2133                 }
2134                 break;
2135         default:
2136                 return;
2137         }
2138 }
2139
2140 static void R_Shadow_RenderMode_ShadowMap(int side, int clear, int size)
2141 {
2142         float nearclip, farclip, bias;
2143         r_viewport_t viewport;
2144         int flipped;
2145         GLuint fbo2d = 0;
2146         float clearcolor[4];
2147         nearclip = r_shadow_shadowmapping_nearclip.value / rsurface.rtlight->radius;
2148         farclip = 1.0f;
2149         bias = r_shadow_shadowmapping_bias.value * nearclip * (1024.0f / size);// * rsurface.rtlight->radius;
2150         r_shadow_shadowmap_parameters[1] = -nearclip * farclip / (farclip - nearclip) - 0.5f * bias;
2151         r_shadow_shadowmap_parameters[3] = 0.5f + 0.5f * (farclip + nearclip) / (farclip - nearclip);
2152         r_shadow_shadowmapside = side;
2153         r_shadow_shadowmapsize = size;
2154
2155         r_shadow_shadowmap_parameters[0] = 0.5f * (size - r_shadow_shadowmapborder);
2156         r_shadow_shadowmap_parameters[2] = r_shadow_shadowmapvsdct ? 2.5f*size : size;
2157         R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapborder, nearclip, farclip, NULL);
2158         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAP2D) goto init_done;
2159
2160         // complex unrolled cube approach (more flexible)
2161         if (r_shadow_shadowmapvsdct && !r_shadow_shadowmapvsdcttexture)
2162                 R_Shadow_MakeVSDCT();
2163         if (!r_shadow_shadowmap2ddepthtexture)
2164                 R_Shadow_MakeShadowMap(side, r_shadow_shadowmapmaxsize);
2165         fbo2d = r_shadow_fbo2d;
2166         r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2ddepthtexture);
2167         r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2ddepthtexture);
2168         r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
2169
2170         R_Mesh_ResetTextureState();
2171         R_Shadow_RenderMode_Reset();
2172         if (r_shadow_shadowmap2ddepthbuffer)
2173                 R_Mesh_SetRenderTargets(fbo2d, r_shadow_shadowmap2ddepthbuffer, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL);
2174         else
2175                 R_Mesh_SetRenderTargets(fbo2d, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL, NULL);
2176         R_SetupShader_DepthOrShadow(true, r_shadow_shadowmap2ddepthbuffer != NULL, false); // FIXME test if we have a skeletal model?
2177         GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
2178         GL_DepthMask(true);
2179         GL_DepthTest(true);
2180
2181 init_done:
2182         R_SetViewport(&viewport);
2183         flipped = (side & 1) ^ (side >> 2);
2184         r_refdef.view.cullface_front = flipped ? r_shadow_cullface_back : r_shadow_cullface_front;
2185         r_refdef.view.cullface_back = flipped ? r_shadow_cullface_front : r_shadow_cullface_back;
2186         if (r_shadow_shadowmap2ddepthbuffer)
2187         {
2188                 // completely different meaning than in depthtexture approach
2189                 r_shadow_shadowmap_parameters[1] = 0;
2190                 r_shadow_shadowmap_parameters[3] = -bias;
2191         }
2192         Vector4Set(clearcolor, 1,1,1,1);
2193         if (r_shadow_shadowmap2ddepthbuffer)
2194                 GL_ColorMask(1,1,1,1);
2195         else
2196                 GL_ColorMask(0,0,0,0);
2197         switch(vid.renderpath)
2198         {
2199         case RENDERPATH_GL11:
2200         case RENDERPATH_GL13:
2201         case RENDERPATH_GL20:
2202         case RENDERPATH_SOFT:
2203         case RENDERPATH_GLES1:
2204         case RENDERPATH_GLES2:
2205                 GL_CullFace(r_refdef.view.cullface_back);
2206                 // OpenGL lets us scissor larger than the viewport, so go ahead and clear all views at once
2207                 if ((clear & ((2 << side) - 1)) == (1 << side)) // only clear if the side is the first in the mask
2208                 {
2209                         // get tightest scissor rectangle that encloses all viewports in the clear mask
2210                         int x1 = clear & 0x15 ? 0 : size;
2211                         int x2 = clear & 0x2A ? 2 * size : size;
2212                         int y1 = clear & 0x03 ? 0 : (clear & 0xC ? size : 2 * size);
2213                         int y2 = clear & 0x30 ? 3 * size : (clear & 0xC ? 2 * size : size);
2214                         GL_Scissor(x1, y1, x2 - x1, y2 - y1);
2215                         if (clear)
2216                         {
2217                                 if (r_shadow_shadowmap2ddepthbuffer)
2218                                         GL_Clear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
2219                                 else
2220                                         GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
2221                         }
2222                 }
2223                 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
2224                 break;
2225         case RENDERPATH_D3D9:
2226         case RENDERPATH_D3D10:
2227         case RENDERPATH_D3D11:
2228                 // we invert the cull mode because we flip the projection matrix
2229                 // NOTE: this actually does nothing because the DrawShadowMap code sets it to doublesided...
2230                 GL_CullFace(r_refdef.view.cullface_front);
2231                 // D3D considers it an error to use a scissor larger than the viewport...  clear just this view
2232                 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
2233                 if (clear)
2234                 {
2235                         if (r_shadow_shadowmap2ddepthbuffer)
2236                                 GL_Clear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
2237                         else
2238                                 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
2239                 }
2240                 break;
2241         }
2242 }
2243
2244 void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qboolean shadowmapping)
2245 {
2246         R_Mesh_ResetTextureState();
2247         if (transparent)
2248         {
2249                 r_shadow_lightscissor[0] = r_refdef.view.viewport.x;
2250                 r_shadow_lightscissor[1] = r_refdef.view.viewport.y;
2251                 r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
2252                 r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
2253         }
2254         R_Shadow_RenderMode_Reset();
2255         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2256         if (!transparent)
2257                 GL_DepthFunc(GL_EQUAL);
2258         // do global setup needed for the chosen lighting mode
2259         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
2260                 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0);
2261         r_shadow_usingshadowmap2d = shadowmapping;
2262         r_shadow_rendermode = r_shadow_lightingrendermode;
2263         // only draw light where this geometry was already rendered AND the
2264         // stencil is 128 (values other than this mean shadow)
2265         if (stenciltest)
2266                 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2267         else
2268                 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
2269 }
2270
2271 static const unsigned short bboxelements[36] =
2272 {
2273         5, 1, 3, 5, 3, 7,
2274         6, 2, 0, 6, 0, 4,
2275         7, 3, 2, 7, 2, 6,
2276         4, 0, 1, 4, 1, 5,
2277         4, 5, 7, 4, 7, 6,
2278         1, 0, 2, 1, 2, 3,
2279 };
2280
2281 static const float bboxpoints[8][3] =
2282 {
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         { 1, 1, 1},
2291 };
2292
2293 void R_Shadow_RenderMode_DrawDeferredLight(qboolean stenciltest, qboolean shadowmapping)
2294 {
2295         int i;
2296         float vertex3f[8*3];
2297         const matrix4x4_t *matrix = &rsurface.rtlight->matrix_lighttoworld;
2298 // do global setup needed for the chosen lighting mode
2299         R_Shadow_RenderMode_Reset();
2300         r_shadow_rendermode = r_shadow_lightingrendermode;
2301         R_EntityMatrix(&identitymatrix);
2302         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2303         // only draw light where this geometry was already rendered AND the
2304         // stencil is 128 (values other than this mean shadow)
2305         R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2306         if (rsurface.rtlight->specularscale > 0 && r_shadow_gloss.integer > 0)
2307                 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
2308         else
2309                 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
2310
2311         r_shadow_usingshadowmap2d = shadowmapping;
2312
2313         // render the lighting
2314         R_SetupShader_DeferredLight(rsurface.rtlight);
2315         for (i = 0;i < 8;i++)
2316                 Matrix4x4_Transform(matrix, bboxpoints[i], vertex3f + i*3);
2317         GL_ColorMask(1,1,1,1);
2318         GL_DepthMask(false);
2319         GL_DepthRange(0, 1);
2320         GL_PolygonOffset(0, 0);
2321         GL_DepthTest(true);
2322         GL_DepthFunc(GL_GREATER);
2323         GL_CullFace(r_refdef.view.cullface_back);
2324         R_Mesh_PrepareVertices_Vertex3f(8, vertex3f, NULL, 0);
2325         R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
2326 }
2327
2328 void R_Shadow_UpdateBounceGridTexture(void)
2329 {
2330 #define MAXBOUNCEGRIDPARTICLESPERLIGHT 1048576
2331         dlight_t *light;
2332         int flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
2333         int bouncecount;
2334         int hitsupercontentsmask;
2335         int maxbounce;
2336         int numpixels;
2337         int resolution[3];
2338         int shootparticles;
2339         int shotparticles;
2340         int photoncount;
2341         int tex[3];
2342         trace_t cliptrace;
2343         //trace_t cliptrace2;
2344         //trace_t cliptrace3;
2345         unsigned char *pixel;
2346         unsigned char *pixels;
2347         float *highpixel;
2348         float *highpixels;
2349         unsigned int lightindex;
2350         unsigned int range;
2351         unsigned int range1;
2352         unsigned int range2;
2353         unsigned int seed = (unsigned int)(realtime * 1000.0f);
2354         vec3_t shotcolor;
2355         vec3_t baseshotcolor;
2356         vec3_t surfcolor;
2357         vec3_t clipend;
2358         vec3_t clipstart;
2359         vec3_t clipdiff;
2360         vec3_t ispacing;
2361         vec3_t maxs;
2362         vec3_t mins;
2363         vec3_t size;
2364         vec3_t spacing;
2365         vec3_t lightcolor;
2366         vec3_t steppos;
2367         vec3_t stepdelta;
2368         vec3_t cullmins, cullmaxs;
2369         vec_t radius;
2370         vec_t s;
2371         vec_t lightintensity;
2372         vec_t photonscaling;
2373         vec_t photonresidual;
2374         float m[16];
2375         float texlerp[2][3];
2376         float splatcolor[32];
2377         float pixelweight[8];
2378         float w;
2379         int c[4];
2380         int pixelindex[8];
2381         int corner;
2382         int pixelsperband;
2383         int pixelband;
2384         int pixelbands;
2385         int numsteps;
2386         int step;
2387         int x, y, z;
2388         rtlight_t *rtlight;
2389         r_shadow_bouncegrid_settings_t settings;
2390         qboolean enable = r_shadow_bouncegrid.integer != 0 && r_refdef.scene.worldmodel;
2391         qboolean allowdirectionalshading = false;
2392         switch(vid.renderpath)
2393         {
2394         case RENDERPATH_GL20:
2395                 allowdirectionalshading = true;
2396                 if (!vid.support.ext_texture_3d)
2397                         return;
2398                 break;
2399         case RENDERPATH_GLES2:
2400                 // for performance reasons, do not use directional shading on GLES devices
2401                 if (!vid.support.ext_texture_3d)
2402                         return;
2403                 break;
2404                 // these renderpaths do not currently have the code to display the bouncegrid, so disable it on them...
2405         case RENDERPATH_GL11:
2406         case RENDERPATH_GL13:
2407         case RENDERPATH_GLES1:
2408         case RENDERPATH_SOFT:
2409         case RENDERPATH_D3D9:
2410         case RENDERPATH_D3D10:
2411         case RENDERPATH_D3D11:
2412                 return;
2413         }
2414
2415         r_shadow_bouncegridintensity = r_shadow_bouncegrid_intensity.value;
2416
2417         // see if there are really any lights to render...
2418         if (enable && r_shadow_bouncegrid_static.integer)
2419         {
2420                 enable = false;
2421                 range = (unsigned int)Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
2422                 for (lightindex = 0;lightindex < range;lightindex++)
2423                 {
2424                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2425                         if (!light || !(light->flags & flag))
2426                                 continue;
2427                         rtlight = &light->rtlight;
2428                         // when static, we skip styled lights because they tend to change...
2429                         if (rtlight->style > 0)
2430                                 continue;
2431                         VectorScale(rtlight->color, (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale), lightcolor);
2432                         if (!VectorLength2(lightcolor))
2433                                 continue;
2434                         enable = true;
2435                         break;
2436                 }
2437         }
2438
2439         if (!enable)
2440         {
2441                 if (r_shadow_bouncegridtexture)
2442                 {
2443                         R_FreeTexture(r_shadow_bouncegridtexture);
2444                         r_shadow_bouncegridtexture = NULL;
2445                 }
2446                 if (r_shadow_bouncegridpixels)
2447                         Mem_Free(r_shadow_bouncegridpixels);
2448                 r_shadow_bouncegridpixels = NULL;
2449                 if (r_shadow_bouncegridhighpixels)
2450                         Mem_Free(r_shadow_bouncegridhighpixels);
2451                 r_shadow_bouncegridhighpixels = NULL;
2452                 r_shadow_bouncegridnumpixels = 0;
2453                 r_shadow_bouncegriddirectional = false;
2454                 return;
2455         }
2456
2457         // build up a complete collection of the desired settings, so that memcmp can be used to compare parameters
2458         memset(&settings, 0, sizeof(settings));
2459         settings.staticmode                    = r_shadow_bouncegrid_static.integer != 0;
2460         settings.bounceanglediffuse            = r_shadow_bouncegrid_bounceanglediffuse.integer != 0;
2461         settings.directionalshading            = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_directionalshading.integer != 0 : r_shadow_bouncegrid_directionalshading.integer != 0) && allowdirectionalshading;
2462         settings.dlightparticlemultiplier      = r_shadow_bouncegrid_dlightparticlemultiplier.value;
2463         settings.hitmodels                     = r_shadow_bouncegrid_hitmodels.integer != 0;
2464         settings.includedirectlighting         = r_shadow_bouncegrid_includedirectlighting.integer != 0 || r_shadow_bouncegrid.integer == 2;
2465         settings.lightradiusscale              = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_lightradiusscale.value : r_shadow_bouncegrid_lightradiusscale.value);
2466         settings.maxbounce                     = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_maxbounce.integer : r_shadow_bouncegrid_maxbounce.integer);
2467         settings.particlebounceintensity       = r_shadow_bouncegrid_particlebounceintensity.value;
2468         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);
2469         settings.photons                       = r_shadow_bouncegrid_static.integer ? r_shadow_bouncegrid_static_photons.integer : r_shadow_bouncegrid_photons.integer;
2470         settings.spacing[0]                    = r_shadow_bouncegrid_spacing.value;
2471         settings.spacing[1]                    = r_shadow_bouncegrid_spacing.value;
2472         settings.spacing[2]                    = r_shadow_bouncegrid_spacing.value;
2473         settings.stablerandom                  = r_shadow_bouncegrid_stablerandom.integer;
2474
2475         // bound the values for sanity
2476         settings.photons = bound(1, settings.photons, 1048576);
2477         settings.lightradiusscale = bound(0.0001f, settings.lightradiusscale, 1024.0f);
2478         settings.maxbounce = bound(0, settings.maxbounce, 16);
2479         settings.spacing[0] = bound(1, settings.spacing[0], 512);
2480         settings.spacing[1] = bound(1, settings.spacing[1], 512);
2481         settings.spacing[2] = bound(1, settings.spacing[2], 512);
2482
2483         // get the spacing values
2484         spacing[0] = settings.spacing[0];
2485         spacing[1] = settings.spacing[1];
2486         spacing[2] = settings.spacing[2];
2487         ispacing[0] = 1.0f / spacing[0];
2488         ispacing[1] = 1.0f / spacing[1];
2489         ispacing[2] = 1.0f / spacing[2];
2490
2491         // calculate texture size enclosing entire world bounds at the spacing
2492         VectorMA(r_refdef.scene.worldmodel->normalmins, -2.0f, spacing, mins);
2493         VectorMA(r_refdef.scene.worldmodel->normalmaxs, 2.0f, spacing, maxs);
2494         VectorSubtract(maxs, mins, size);
2495         // now we can calculate the resolution we want
2496         c[0] = (int)floor(size[0] / spacing[0] + 0.5f);
2497         c[1] = (int)floor(size[1] / spacing[1] + 0.5f);
2498         c[2] = (int)floor(size[2] / spacing[2] + 0.5f);
2499         // figure out the exact texture size (honoring power of 2 if required)
2500         c[0] = bound(4, c[0], (int)vid.maxtexturesize_3d);
2501         c[1] = bound(4, c[1], (int)vid.maxtexturesize_3d);
2502         c[2] = bound(4, c[2], (int)vid.maxtexturesize_3d);
2503         if (vid.support.arb_texture_non_power_of_two)
2504         {
2505                 resolution[0] = c[0];
2506                 resolution[1] = c[1];
2507                 resolution[2] = c[2];
2508         }
2509         else
2510         {
2511                 for (resolution[0] = 4;resolution[0] < c[0];resolution[0]*=2) ;
2512                 for (resolution[1] = 4;resolution[1] < c[1];resolution[1]*=2) ;
2513                 for (resolution[2] = 4;resolution[2] < c[2];resolution[2]*=2) ;
2514         }
2515         size[0] = spacing[0] * resolution[0];
2516         size[1] = spacing[1] * resolution[1];
2517         size[2] = spacing[2] * resolution[2];
2518
2519         // if dynamic we may or may not want to use the world bounds
2520         // if the dynamic size is smaller than the world bounds, use it instead
2521         if (!settings.staticmode && (r_shadow_bouncegrid_x.integer * r_shadow_bouncegrid_y.integer * r_shadow_bouncegrid_z.integer < resolution[0] * resolution[1] * resolution[2]))
2522         {
2523                 // we know the resolution we want
2524                 c[0] = r_shadow_bouncegrid_x.integer;
2525                 c[1] = r_shadow_bouncegrid_y.integer;
2526                 c[2] = r_shadow_bouncegrid_z.integer;
2527                 // now we can calculate the texture size (power of 2 if required)
2528                 c[0] = bound(4, c[0], (int)vid.maxtexturesize_3d);
2529                 c[1] = bound(4, c[1], (int)vid.maxtexturesize_3d);
2530                 c[2] = bound(4, c[2], (int)vid.maxtexturesize_3d);
2531                 if (vid.support.arb_texture_non_power_of_two)
2532                 {
2533                         resolution[0] = c[0];
2534                         resolution[1] = c[1];
2535                         resolution[2] = c[2];
2536                 }
2537                 else
2538                 {
2539                         for (resolution[0] = 4;resolution[0] < c[0];resolution[0]*=2) ;
2540                         for (resolution[1] = 4;resolution[1] < c[1];resolution[1]*=2) ;
2541                         for (resolution[2] = 4;resolution[2] < c[2];resolution[2]*=2) ;
2542                 }
2543                 size[0] = spacing[0] * resolution[0];
2544                 size[1] = spacing[1] * resolution[1];
2545                 size[2] = spacing[2] * resolution[2];
2546                 // center the rendering on the view
2547                 mins[0] = floor(r_refdef.view.origin[0] * ispacing[0] + 0.5f) * spacing[0] - 0.5f * size[0];
2548                 mins[1] = floor(r_refdef.view.origin[1] * ispacing[1] + 0.5f) * spacing[1] - 0.5f * size[1];
2549                 mins[2] = floor(r_refdef.view.origin[2] * ispacing[2] + 0.5f) * spacing[2] - 0.5f * size[2];
2550         }
2551
2552         // recalculate the maxs in case the resolution was not satisfactory
2553         VectorAdd(mins, size, maxs);
2554
2555         // if all the settings seem identical to the previous update, return
2556         if (r_shadow_bouncegridtexture && (settings.staticmode || realtime < r_shadow_bouncegridtime + r_shadow_bouncegrid_updateinterval.value) && !memcmp(&r_shadow_bouncegridsettings, &settings, sizeof(settings)))
2557                 return;
2558
2559         // store the new settings
2560         r_shadow_bouncegridsettings = settings;
2561
2562         pixelbands = settings.directionalshading ? 8 : 1;
2563         pixelsperband = resolution[0]*resolution[1]*resolution[2];
2564         numpixels = pixelsperband*pixelbands;
2565
2566         // we're going to update the bouncegrid, update the matrix...
2567         memset(m, 0, sizeof(m));
2568         m[0] = 1.0f / size[0];
2569         m[3] = -mins[0] * m[0];
2570         m[5] = 1.0f / size[1];
2571         m[7] = -mins[1] * m[5];
2572         m[10] = 1.0f / size[2];
2573         m[11] = -mins[2] * m[10];
2574         m[15] = 1.0f;
2575         Matrix4x4_FromArrayFloatD3D(&r_shadow_bouncegridmatrix, m);
2576         // reallocate pixels for this update if needed...
2577         if (r_shadow_bouncegridnumpixels != numpixels || !r_shadow_bouncegridpixels || !r_shadow_bouncegridhighpixels)
2578         {
2579                 if (r_shadow_bouncegridtexture)
2580                 {
2581                         R_FreeTexture(r_shadow_bouncegridtexture);
2582                         r_shadow_bouncegridtexture = NULL;
2583                 }
2584                 r_shadow_bouncegridpixels = (unsigned char *)Mem_Realloc(r_main_mempool, r_shadow_bouncegridpixels, numpixels * sizeof(unsigned char[4]));
2585                 r_shadow_bouncegridhighpixels = (float *)Mem_Realloc(r_main_mempool, r_shadow_bouncegridhighpixels, numpixels * sizeof(float[4]));
2586         }
2587         r_shadow_bouncegridnumpixels = numpixels;
2588         pixels = r_shadow_bouncegridpixels;
2589         highpixels = r_shadow_bouncegridhighpixels;
2590         x = pixelsperband*4;
2591         for (pixelband = 0;pixelband < pixelbands;pixelband++)
2592         {
2593                 if (pixelband == 1)
2594                         memset(pixels + pixelband * x, 128, x);
2595                 else
2596                         memset(pixels + pixelband * x, 0, x);
2597         }
2598         memset(highpixels, 0, numpixels * sizeof(float[4]));
2599         // figure out what we want to interact with
2600         if (settings.hitmodels)
2601                 hitsupercontentsmask = SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY;// | SUPERCONTENTS_LIQUIDSMASK;
2602         else
2603                 hitsupercontentsmask = SUPERCONTENTS_SOLID;// | SUPERCONTENTS_LIQUIDSMASK;
2604         maxbounce = settings.maxbounce;
2605         // clear variables that produce warnings otherwise
2606         memset(splatcolor, 0, sizeof(splatcolor));
2607         // iterate world rtlights
2608         range = (unsigned int)Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
2609         range1 = settings.staticmode ? 0 : r_refdef.scene.numlights;
2610         range2 = range + range1;
2611         photoncount = 0;
2612         for (lightindex = 0;lightindex < range2;lightindex++)
2613         {
2614                 if (lightindex < range)
2615                 {
2616                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2617                         if (!light)
2618                                 continue;
2619                         rtlight = &light->rtlight;
2620                         VectorClear(rtlight->photoncolor);
2621                         rtlight->photons = 0;
2622                         if (!(light->flags & flag))
2623                                 continue;
2624                         if (settings.staticmode)
2625                         {
2626                                 // when static, we skip styled lights because they tend to change...
2627                                 if (rtlight->style > 0 && r_shadow_bouncegrid.integer != 2)
2628                                         continue;
2629                         }
2630                 }
2631                 else
2632                 {
2633                         rtlight = r_refdef.scene.lights[lightindex - range];
2634                         VectorClear(rtlight->photoncolor);
2635                         rtlight->photons = 0;
2636                 }
2637                 // draw only visible lights (major speedup)
2638                 radius = rtlight->radius * settings.lightradiusscale;
2639                 cullmins[0] = rtlight->shadoworigin[0] - radius;
2640                 cullmins[1] = rtlight->shadoworigin[1] - radius;
2641                 cullmins[2] = rtlight->shadoworigin[2] - radius;
2642                 cullmaxs[0] = rtlight->shadoworigin[0] + radius;
2643                 cullmaxs[1] = rtlight->shadoworigin[1] + radius;
2644                 cullmaxs[2] = rtlight->shadoworigin[2] + radius;
2645                 if (R_CullBox(cullmins, cullmaxs))
2646                         continue;
2647                 if (r_refdef.scene.worldmodel
2648                  && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs
2649                  && !r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs(r_refdef.scene.worldmodel, r_refdef.viewcache.world_leafvisible, cullmins, cullmaxs))
2650                         continue;
2651                 w = r_shadow_lightintensityscale.value * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale);
2652                 if (w * VectorLength2(rtlight->color) == 0.0f)
2653                         continue;
2654                 w *= ((rtlight->style >= 0 && rtlight->style < MAX_LIGHTSTYLES) ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1);
2655                 VectorScale(rtlight->color, w, rtlight->photoncolor);
2656                 //if (!VectorLength2(rtlight->photoncolor))
2657                 //      continue;
2658                 // shoot particles from this light
2659                 // use a calculation for the number of particles that will not
2660                 // vary with lightstyle, otherwise we get randomized particle
2661                 // distribution, the seeded random is only consistent for a
2662                 // consistent number of particles on this light...
2663                 s = rtlight->radius;
2664                 lightintensity = VectorLength(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale);
2665                 if (lightindex >= range)
2666                         lightintensity *= settings.dlightparticlemultiplier;
2667                 rtlight->photons = max(0.0f, lightintensity * s * s);
2668                 photoncount += rtlight->photons;
2669         }
2670         photonscaling = (float)settings.photons / max(1, photoncount);
2671         photonresidual = 0.0f;
2672         for (lightindex = 0;lightindex < range2;lightindex++)
2673         {
2674                 if (lightindex < range)
2675                 {
2676                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2677                         if (!light)
2678                                 continue;
2679                         rtlight = &light->rtlight;
2680                 }
2681                 else
2682                         rtlight = r_refdef.scene.lights[lightindex - range];
2683                 // skip a light with no photons
2684                 if (rtlight->photons == 0.0f)
2685                         continue;
2686                 // skip a light with no photon color)
2687                 if (VectorLength2(rtlight->photoncolor) == 0.0f)
2688                         continue;
2689                 photonresidual += rtlight->photons * photonscaling;
2690                 shootparticles = (int)bound(0, photonresidual, MAXBOUNCEGRIDPARTICLESPERLIGHT);
2691                 if (!shootparticles)
2692                         continue;
2693                 photonresidual -= shootparticles;
2694                 radius = rtlight->radius * settings.lightradiusscale;
2695                 s = settings.particleintensity / shootparticles;
2696                 VectorScale(rtlight->photoncolor, s, baseshotcolor);
2697                 r_refdef.stats[r_stat_bouncegrid_lights]++;
2698                 r_refdef.stats[r_stat_bouncegrid_particles] += shootparticles;
2699                 for (shotparticles = 0;shotparticles < shootparticles;shotparticles++)
2700                 {
2701                         if (settings.stablerandom > 0)
2702                                 seed = lightindex * 11937 + shotparticles;
2703                         VectorCopy(baseshotcolor, shotcolor);
2704                         VectorCopy(rtlight->shadoworigin, clipstart);
2705                         if (settings.stablerandom < 0)
2706                                 VectorRandom(clipend);
2707                         else
2708                                 VectorCheeseRandom(clipend);
2709                         VectorMA(clipstart, radius, clipend, clipend);
2710                         for (bouncecount = 0;;bouncecount++)
2711                         {
2712                                 r_refdef.stats[r_stat_bouncegrid_traces]++;
2713                                 //r_refdef.scene.worldmodel->TraceLineAgainstSurfaces(r_refdef.scene.worldmodel, NULL, NULL, &cliptrace, clipstart, clipend, hitsupercontentsmask);
2714                                 //r_refdef.scene.worldmodel->TraceLine(r_refdef.scene.worldmodel, NULL, NULL, &cliptrace2, clipstart, clipend, hitsupercontentsmask);
2715                                 if (settings.staticmode)
2716                                 {
2717                                         // static mode fires a LOT of rays but none of them are identical, so they are not cached
2718                                         cliptrace = CL_TraceLine(clipstart, clipend, settings.staticmode ? MOVE_WORLDONLY : (settings.hitmodels ? MOVE_HITMODEL : MOVE_NOMONSTERS), NULL, hitsupercontentsmask, collision_extendmovelength.value, true, false, NULL, true, true);
2719                                 }
2720                                 else
2721                                 {
2722                                         // dynamic mode fires many rays and most will match the cache from the previous frame
2723                                         cliptrace = CL_Cache_TraceLineSurfaces(clipstart, clipend, settings.staticmode ? MOVE_WORLDONLY : (settings.hitmodels ? MOVE_HITMODEL : MOVE_NOMONSTERS), hitsupercontentsmask);
2724                                 }
2725                                 if (bouncecount > 0 || settings.includedirectlighting)
2726                                 {
2727                                         // calculate second order spherical harmonics values (average, slopeX, slopeY, slopeZ)
2728                                         // accumulate average shotcolor
2729                                         w = VectorLength(shotcolor);
2730                                         splatcolor[ 0] = shotcolor[0];
2731                                         splatcolor[ 1] = shotcolor[1];
2732                                         splatcolor[ 2] = shotcolor[2];
2733                                         splatcolor[ 3] = 0.0f;
2734                                         if (pixelbands > 1)
2735                                         {
2736                                                 VectorSubtract(clipstart, cliptrace.endpos, clipdiff);
2737                                                 VectorNormalize(clipdiff);
2738                                                 // store bentnormal in case the shader has a use for it
2739                                                 splatcolor[ 4] = clipdiff[0] * w;
2740                                                 splatcolor[ 5] = clipdiff[1] * w;
2741                                                 splatcolor[ 6] = clipdiff[2] * w;
2742                                                 splatcolor[ 7] = w;
2743                                                 // accumulate directional contributions (+X, +Y, +Z, -X, -Y, -Z)
2744                                                 splatcolor[ 8] = shotcolor[0] * max(0.0f, clipdiff[0]);
2745                                                 splatcolor[ 9] = shotcolor[0] * max(0.0f, clipdiff[1]);
2746                                                 splatcolor[10] = shotcolor[0] * max(0.0f, clipdiff[2]);
2747                                                 splatcolor[11] = 0.0f;
2748                                                 splatcolor[12] = shotcolor[1] * max(0.0f, clipdiff[0]);
2749                                                 splatcolor[13] = shotcolor[1] * max(0.0f, clipdiff[1]);
2750                                                 splatcolor[14] = shotcolor[1] * max(0.0f, clipdiff[2]);
2751                                                 splatcolor[15] = 0.0f;
2752                                                 splatcolor[16] = shotcolor[2] * max(0.0f, clipdiff[0]);
2753                                                 splatcolor[17] = shotcolor[2] * max(0.0f, clipdiff[1]);
2754                                                 splatcolor[18] = shotcolor[2] * max(0.0f, clipdiff[2]);
2755                                                 splatcolor[19] = 0.0f;
2756                                                 splatcolor[20] = shotcolor[0] * max(0.0f, -clipdiff[0]);
2757                                                 splatcolor[21] = shotcolor[0] * max(0.0f, -clipdiff[1]);
2758                                                 splatcolor[22] = shotcolor[0] * max(0.0f, -clipdiff[2]);
2759                                                 splatcolor[23] = 0.0f;
2760                                                 splatcolor[24] = shotcolor[1] * max(0.0f, -clipdiff[0]);
2761                                                 splatcolor[25] = shotcolor[1] * max(0.0f, -clipdiff[1]);
2762                                                 splatcolor[26] = shotcolor[1] * max(0.0f, -clipdiff[2]);
2763                                                 splatcolor[27] = 0.0f;
2764                                                 splatcolor[28] = shotcolor[2] * max(0.0f, -clipdiff[0]);
2765                                                 splatcolor[29] = shotcolor[2] * max(0.0f, -clipdiff[1]);
2766                                                 splatcolor[30] = shotcolor[2] * max(0.0f, -clipdiff[2]);
2767                                                 splatcolor[31] = 0.0f;
2768                                         }
2769                                         // calculate the number of steps we need to traverse this distance
2770                                         VectorSubtract(cliptrace.endpos, clipstart, stepdelta);
2771                                         numsteps = (int)(VectorLength(stepdelta) * ispacing[0]);
2772                                         numsteps = bound(1, numsteps, 1024);
2773                                         w = 1.0f / numsteps;
2774                                         VectorScale(stepdelta, w, stepdelta);
2775                                         VectorMA(clipstart, 0.5f, stepdelta, steppos);
2776                                         for (step = 0;step < numsteps;step++)
2777                                         {
2778                                                 r_refdef.stats[r_stat_bouncegrid_splats]++;
2779                                                 // figure out which texture pixel this is in
2780                                                 texlerp[1][0] = ((steppos[0] - mins[0]) * ispacing[0]) - 0.5f;
2781                                                 texlerp[1][1] = ((steppos[1] - mins[1]) * ispacing[1]) - 0.5f;
2782                                                 texlerp[1][2] = ((steppos[2] - mins[2]) * ispacing[2]) - 0.5f;
2783                                                 tex[0] = (int)floor(texlerp[1][0]);
2784                                                 tex[1] = (int)floor(texlerp[1][1]);
2785                                                 tex[2] = (int)floor(texlerp[1][2]);
2786                                                 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)
2787                                                 {
2788                                                         // it is within bounds...  do the real work now
2789                                                         // calculate the lerp factors
2790                                                         texlerp[1][0] -= tex[0];
2791                                                         texlerp[1][1] -= tex[1];
2792                                                         texlerp[1][2] -= tex[2];
2793                                                         texlerp[0][0] = 1.0f - texlerp[1][0];
2794                                                         texlerp[0][1] = 1.0f - texlerp[1][1];
2795                                                         texlerp[0][2] = 1.0f - texlerp[1][2];
2796                                                         // calculate individual pixel indexes and weights
2797                                                         pixelindex[0] = (((tex[2]  )*resolution[1]+tex[1]  )*resolution[0]+tex[0]  );pixelweight[0] = (texlerp[0][0]*texlerp[0][1]*texlerp[0][2]);
2798                                                         pixelindex[1] = (((tex[2]  )*resolution[1]+tex[1]  )*resolution[0]+tex[0]+1);pixelweight[1] = (texlerp[1][0]*texlerp[0][1]*texlerp[0][2]);
2799                                                         pixelindex[2] = (((tex[2]  )*resolution[1]+tex[1]+1)*resolution[0]+tex[0]  );pixelweight[2] = (texlerp[0][0]*texlerp[1][1]*texlerp[0][2]);
2800                                                         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]);
2801                                                         pixelindex[4] = (((tex[2]+1)*resolution[1]+tex[1]  )*resolution[0]+tex[0]  );pixelweight[4] = (texlerp[0][0]*texlerp[0][1]*texlerp[1][2]);
2802                                                         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]);
2803                                                         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]);
2804                                                         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]);
2805                                                         // update the 8 pixels...
2806                                                         for (pixelband = 0;pixelband < pixelbands;pixelband++)
2807                                                         {
2808                                                                 for (corner = 0;corner < 8;corner++)
2809                                                                 {
2810                                                                         // calculate address for pixel
2811                                                                         w = pixelweight[corner];
2812                                                                         pixel = pixels + 4 * pixelindex[corner] + pixelband * pixelsperband * 4;
2813                                                                         highpixel = highpixels + 4 * pixelindex[corner] + pixelband * pixelsperband * 4;
2814                                                                         // add to the high precision pixel color
2815                                                                         highpixel[0] += (splatcolor[pixelband*4+0]*w);
2816                                                                         highpixel[1] += (splatcolor[pixelband*4+1]*w);
2817                                                                         highpixel[2] += (splatcolor[pixelband*4+2]*w);
2818                                                                         highpixel[3] += (splatcolor[pixelband*4+3]*w);
2819                                                                         // flag the low precision pixel as needing to be updated
2820                                                                         pixel[3] = 255;
2821                                                                         // advance to next band of coefficients
2822                                                                         //pixel += pixelsperband*4;
2823                                                                         //highpixel += pixelsperband*4;
2824                                                                 }
2825                                                         }
2826                                                 }
2827                                                 VectorAdd(steppos, stepdelta, steppos);
2828                                         }
2829                                 }
2830                                 if (cliptrace.fraction >= 1.0f)
2831                                         break;
2832                                 r_refdef.stats[r_stat_bouncegrid_hits]++;
2833                                 if (bouncecount >= maxbounce)
2834                                         break;
2835                                 // scale down shot color by bounce intensity and texture color (or 50% if no texture reported)
2836                                 // also clamp the resulting color to never add energy, even if the user requests extreme values
2837                                 if (cliptrace.hittexture && cliptrace.hittexture->currentskinframe)
2838                                         VectorCopy(cliptrace.hittexture->currentskinframe->avgcolor, surfcolor);
2839                                 else
2840                                         VectorSet(surfcolor, 0.5f, 0.5f, 0.5f);
2841                                 VectorScale(surfcolor, settings.particlebounceintensity, surfcolor);
2842                                 surfcolor[0] = min(surfcolor[0], 1.0f);
2843                                 surfcolor[1] = min(surfcolor[1], 1.0f);
2844                                 surfcolor[2] = min(surfcolor[2], 1.0f);
2845                                 VectorMultiply(shotcolor, surfcolor, shotcolor);
2846                                 if (VectorLength2(baseshotcolor) == 0.0f)
2847                                         break;
2848                                 r_refdef.stats[r_stat_bouncegrid_bounces]++;
2849                                 if (settings.bounceanglediffuse)
2850                                 {
2851                                         // random direction, primarily along plane normal
2852                                         s = VectorDistance(cliptrace.endpos, clipend);
2853                                         if (settings.stablerandom < 0)
2854                                                 VectorRandom(clipend);
2855                                         else
2856                                                 VectorCheeseRandom(clipend);
2857                                         VectorMA(cliptrace.plane.normal, 0.95f, clipend, clipend);
2858                                         VectorNormalize(clipend);
2859                                         VectorScale(clipend, s, clipend);
2860                                 }
2861                                 else
2862                                 {
2863                                         // reflect the remaining portion of the line across plane normal
2864                                         VectorSubtract(clipend, cliptrace.endpos, clipdiff);
2865                                         VectorReflect(clipdiff, 1.0, cliptrace.plane.normal, clipend);
2866                                 }
2867                                 // calculate the new line start and end
2868                                 VectorCopy(cliptrace.endpos, clipstart);
2869                                 VectorAdd(clipstart, clipend, clipend);
2870                         }
2871                 }
2872         }
2873         // generate pixels array from highpixels array
2874         // skip first and last columns, rows, and layers as these are blank
2875         // the pixel[3] value was written above, so we can use it to detect only pixels that need to be calculated
2876         for (pixelband = 0;pixelband < pixelbands;pixelband++)
2877         {
2878                 for (z = 1;z < resolution[2]-1;z++)
2879                 {
2880                         for (y = 1;y < resolution[1]-1;y++)
2881                         {
2882                                 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)
2883                                 {
2884                                         // only convert pixels that were hit by photons
2885                                         if (pixel[3] == 255)
2886                                         {
2887                                                 // normalize the bentnormal...
2888                                                 if (pixelband == 1)
2889                                                 {
2890                                                         VectorNormalize(highpixel);
2891                                                         c[0] = (int)(highpixel[0]*128.0f+128.0f);
2892                                                         c[1] = (int)(highpixel[1]*128.0f+128.0f);
2893                                                         c[2] = (int)(highpixel[2]*128.0f+128.0f);
2894                                                         c[3] = (int)(highpixel[3]*128.0f+128.0f);
2895                                                 }
2896                                                 else
2897                                                 {
2898                                                         c[0] = (int)(highpixel[0]*256.0f);
2899                                                         c[1] = (int)(highpixel[1]*256.0f);
2900                                                         c[2] = (int)(highpixel[2]*256.0f);
2901                                                         c[3] = (int)(highpixel[3]*256.0f);
2902                                                 }
2903                                                 pixel[2] = (unsigned char)bound(0, c[0], 255);
2904                                                 pixel[1] = (unsigned char)bound(0, c[1], 255);
2905                                                 pixel[0] = (unsigned char)bound(0, c[2], 255);
2906                                                 pixel[3] = (unsigned char)bound(0, c[3], 255);
2907                                         }
2908                                 }
2909                         }
2910                 }
2911         }
2912         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)
2913                 R_UpdateTexture(r_shadow_bouncegridtexture, pixels, 0, 0, 0, resolution[0], resolution[1], resolution[2]*pixelbands);
2914         else
2915         {
2916                 VectorCopy(resolution, r_shadow_bouncegridresolution);
2917                 r_shadow_bouncegriddirectional = settings.directionalshading;
2918                 if (r_shadow_bouncegridtexture)
2919                         R_FreeTexture(r_shadow_bouncegridtexture);
2920                 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);
2921         }
2922         r_shadow_bouncegridtime = realtime;
2923 }
2924
2925 void R_Shadow_RenderMode_VisibleShadowVolumes(void)
2926 {
2927         R_Shadow_RenderMode_Reset();
2928         GL_BlendFunc(GL_ONE, GL_ONE);
2929         GL_DepthRange(0, 1);
2930         GL_DepthTest(r_showshadowvolumes.integer < 2);
2931         GL_Color(0.0, 0.0125 * r_refdef.view.colorscale, 0.1 * r_refdef.view.colorscale, 1);
2932         GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
2933         GL_CullFace(GL_NONE);
2934         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLEVOLUMES;
2935 }
2936
2937 void R_Shadow_RenderMode_VisibleLighting(qboolean stenciltest, qboolean transparent)
2938 {
2939         R_Shadow_RenderMode_Reset();
2940         GL_BlendFunc(GL_ONE, GL_ONE);
2941         GL_DepthRange(0, 1);
2942         GL_DepthTest(r_showlighting.integer < 2);
2943         GL_Color(0.1 * r_refdef.view.colorscale, 0.0125 * r_refdef.view.colorscale, 0, 1);
2944         if (!transparent)
2945                 GL_DepthFunc(GL_EQUAL);
2946         R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2947         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLELIGHTING;
2948 }
2949
2950 void R_Shadow_RenderMode_End(void)
2951 {
2952         R_Shadow_RenderMode_Reset();
2953         R_Shadow_RenderMode_ActiveLight(NULL);
2954         GL_DepthMask(true);
2955         GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
2956         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
2957 }
2958
2959 int bboxedges[12][2] =
2960 {
2961         // top
2962         {0, 1}, // +X
2963         {0, 2}, // +Y
2964         {1, 3}, // Y, +X
2965         {2, 3}, // X, +Y
2966         // bottom
2967         {4, 5}, // +X
2968         {4, 6}, // +Y
2969         {5, 7}, // Y, +X
2970         {6, 7}, // X, +Y
2971         // verticals
2972         {0, 4}, // +Z
2973         {1, 5}, // X, +Z
2974         {2, 6}, // Y, +Z
2975         {3, 7}, // XY, +Z
2976 };
2977
2978 qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
2979 {
2980         if (!r_shadow_scissor.integer || r_shadow_usingdeferredprepass || r_trippy.integer)
2981         {
2982                 r_shadow_lightscissor[0] = r_refdef.view.viewport.x;
2983                 r_shadow_lightscissor[1] = r_refdef.view.viewport.y;
2984                 r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
2985                 r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
2986                 return false;
2987         }
2988         if(R_ScissorForBBox(mins, maxs, r_shadow_lightscissor))
2989                 return true; // invisible
2990         if(r_shadow_lightscissor[0] != r_refdef.view.viewport.x
2991         || r_shadow_lightscissor[1] != r_refdef.view.viewport.y
2992         || r_shadow_lightscissor[2] != r_refdef.view.viewport.width
2993         || r_shadow_lightscissor[3] != r_refdef.view.viewport.height)
2994                 r_refdef.stats[r_stat_lights_scissored]++;
2995         return false;
2996 }
2997
2998 static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int numverts, const float *diffusecolor, const float *ambientcolor)
2999 {
3000         int i;
3001         const float *vertex3f;
3002         const float *normal3f;
3003         float *color4f;
3004         float dist, dot, distintensity, shadeintensity, v[3], n[3];
3005         switch (r_shadow_rendermode)
3006         {
3007         case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
3008         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
3009                 if (VectorLength2(diffusecolor) > 0)
3010                 {
3011                         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)
3012                         {
3013                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3014                                 Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
3015                                 if ((dot = DotProduct(n, v)) < 0)
3016                                 {
3017                                         shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
3018                                         VectorMA(ambientcolor, shadeintensity, diffusecolor, color4f);
3019                                 }
3020                                 else
3021                                         VectorCopy(ambientcolor, color4f);
3022                                 if (r_refdef.fogenabled)
3023                                 {
3024                                         float f;
3025                                         f = RSurf_FogVertex(vertex3f);
3026                                         VectorScale(color4f, f, color4f);
3027                                 }
3028                                 color4f[3] = 1;
3029                         }
3030                 }
3031                 else
3032                 {
3033                         for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3034                         {
3035                                 VectorCopy(ambientcolor, color4f);
3036                                 if (r_refdef.fogenabled)
3037                                 {
3038                                         float f;
3039                                         Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3040                                         f = RSurf_FogVertex(vertex3f);
3041                                         VectorScale(color4f + 4*i, f, color4f);
3042                                 }
3043                                 color4f[3] = 1;
3044                         }
3045                 }
3046                 break;
3047         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3048                 if (VectorLength2(diffusecolor) > 0)
3049                 {
3050                         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)
3051                         {
3052                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3053                                 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3054                                 {
3055                                         Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
3056                                         if ((dot = DotProduct(n, v)) < 0)
3057                                         {
3058                                                 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
3059                                                 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
3060                                                 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
3061                                                 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
3062                                         }
3063                                         else
3064                                         {
3065                                                 color4f[0] = ambientcolor[0] * distintensity;
3066                                                 color4f[1] = ambientcolor[1] * distintensity;
3067                                                 color4f[2] = ambientcolor[2] * distintensity;
3068                                         }
3069                                         if (r_refdef.fogenabled)
3070                                         {
3071                                                 float f;
3072                                                 f = RSurf_FogVertex(vertex3f);
3073                                                 VectorScale(color4f, f, color4f);
3074                                         }
3075                                 }
3076                                 else
3077                                         VectorClear(color4f);
3078                                 color4f[3] = 1;
3079                         }
3080                 }
3081                 else
3082                 {
3083                         for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3084                         {
3085                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3086                                 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3087                                 {
3088                                         color4f[0] = ambientcolor[0] * distintensity;
3089                                         color4f[1] = ambientcolor[1] * distintensity;
3090                                         color4f[2] = ambientcolor[2] * distintensity;
3091                                         if (r_refdef.fogenabled)
3092                                         {
3093                                                 float f;
3094                                                 f = RSurf_FogVertex(vertex3f);
3095                                                 VectorScale(color4f, f, color4f);
3096                                         }
3097                                 }
3098                                 else
3099                                         VectorClear(color4f);
3100                                 color4f[3] = 1;
3101                         }
3102                 }
3103                 break;
3104         case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3105                 if (VectorLength2(diffusecolor) > 0)
3106                 {
3107                         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)
3108                         {
3109                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3110                                 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3111                                 {
3112                                         distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
3113                                         Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
3114                                         if ((dot = DotProduct(n, v)) < 0)
3115                                         {
3116                                                 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
3117                                                 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
3118                                                 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
3119                                                 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
3120                                         }
3121                                         else
3122                                         {
3123                                                 color4f[0] = ambientcolor[0] * distintensity;
3124                                                 color4f[1] = ambientcolor[1] * distintensity;
3125                                                 color4f[2] = ambientcolor[2] * distintensity;
3126                                         }
3127                                         if (r_refdef.fogenabled)
3128                                         {
3129                                                 float f;
3130                                                 f = RSurf_FogVertex(vertex3f);
3131                                                 VectorScale(color4f, f, color4f);
3132                                         }
3133                                 }
3134                                 else
3135                                         VectorClear(color4f);
3136                                 color4f[3] = 1;
3137                         }
3138                 }
3139                 else
3140                 {
3141                         for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3142                         {
3143                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3144                                 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3145                                 {
3146                                         distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
3147                                         color4f[0] = ambientcolor[0] * distintensity;
3148                                         color4f[1] = ambientcolor[1] * distintensity;
3149                                         color4f[2] = ambientcolor[2] * distintensity;
3150                                         if (r_refdef.fogenabled)
3151                                         {
3152                                                 float f;
3153                                                 f = RSurf_FogVertex(vertex3f);
3154                                                 VectorScale(color4f, f, color4f);
3155                                         }
3156                                 }
3157                                 else
3158                                         VectorClear(color4f);
3159                                 color4f[3] = 1;
3160                         }
3161                 }
3162                 break;
3163         default:
3164                 break;
3165         }
3166 }
3167
3168 static void R_Shadow_RenderLighting_VisibleLighting(int texturenumsurfaces, const msurface_t **texturesurfacelist)
3169 {
3170         // used to display how many times a surface is lit for level design purposes
3171         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
3172         R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
3173         RSurf_DrawBatch();
3174 }
3175
3176 static void R_Shadow_RenderLighting_Light_GLSL(int texturenumsurfaces, const msurface_t **texturesurfacelist, const vec3_t lightcolor, float ambientscale, float diffusescale, float specularscale)
3177 {
3178         // ARB2 GLSL shader path (GFFX5200, Radeon 9500)
3179         R_SetupShader_Surface(lightcolor, false, ambientscale, diffusescale, specularscale, RSURFPASS_RTLIGHT, texturenumsurfaces, texturesurfacelist, NULL, false);
3180         RSurf_DrawBatch();
3181 }
3182
3183 static void R_Shadow_RenderLighting_Light_Vertex_Pass(int firstvertex, int numvertices, int numtriangles, const int *element3i, vec3_t diffusecolor2, vec3_t ambientcolor2)
3184 {
3185         int renders;
3186         int i;
3187         int stop;
3188         int newfirstvertex;
3189         int newlastvertex;
3190         int newnumtriangles;
3191         int *newe;
3192         const int *e;
3193         float *c;
3194         int maxtriangles = 1024;
3195         int newelements[1024*3];
3196         R_Shadow_RenderLighting_Light_Vertex_Shading(firstvertex, numvertices, diffusecolor2, ambientcolor2);
3197         for (renders = 0;renders < 4;renders++)
3198         {
3199                 stop = true;
3200                 newfirstvertex = 0;
3201                 newlastvertex = 0;
3202                 newnumtriangles = 0;
3203                 newe = newelements;
3204                 // due to low fillrate on the cards this vertex lighting path is
3205                 // designed for, we manually cull all triangles that do not
3206                 // contain a lit vertex
3207                 // this builds batches of triangles from multiple surfaces and
3208                 // renders them at once
3209                 for (i = 0, e = element3i;i < numtriangles;i++, e += 3)
3210                 {
3211                         if (VectorLength2(rsurface.passcolor4f + e[0] * 4) + VectorLength2(rsurface.passcolor4f + e[1] * 4) + VectorLength2(rsurface.passcolor4f + e[2] * 4) >= 0.01)
3212                         {
3213                                 if (newnumtriangles)
3214                                 {
3215                                         newfirstvertex = min(newfirstvertex, e[0]);
3216                                         newlastvertex  = max(newlastvertex, e[0]);
3217                                 }
3218                                 else
3219                                 {
3220                                         newfirstvertex = e[0];
3221                                         newlastvertex = e[0];
3222                                 }
3223                                 newfirstvertex = min(newfirstvertex, e[1]);
3224                                 newlastvertex  = max(newlastvertex, e[1]);
3225                                 newfirstvertex = min(newfirstvertex, e[2]);
3226                                 newlastvertex  = max(newlastvertex, e[2]);
3227                                 newe[0] = e[0];
3228                                 newe[1] = e[1];
3229                                 newe[2] = e[2];
3230                                 newnumtriangles++;
3231                                 newe += 3;
3232                                 if (newnumtriangles >= maxtriangles)
3233                                 {
3234                                         R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, NULL, NULL, 0);
3235                                         newnumtriangles = 0;
3236                                         newe = newelements;
3237                                         stop = false;
3238                                 }
3239                         }
3240                 }
3241                 if (newnumtriangles >= 1)
3242                 {
3243                         R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, NULL, NULL, 0);
3244                         stop = false;
3245                 }
3246                 // if we couldn't find any lit triangles, exit early
3247                 if (stop)
3248                         break;
3249                 // now reduce the intensity for the next overbright pass
3250                 // we have to clamp to 0 here incase the drivers have improper
3251                 // handling of negative colors
3252                 // (some old drivers even have improper handling of >1 color)
3253                 stop = true;
3254                 for (i = 0, c = rsurface.passcolor4f + 4 * firstvertex;i < numvertices;i++, c += 4)
3255                 {
3256                         if (c[0] > 1 || c[1] > 1 || c[2] > 1)
3257                         {
3258                                 c[0] = max(0, c[0] - 1);
3259                                 c[1] = max(0, c[1] - 1);
3260                                 c[2] = max(0, c[2] - 1);
3261                                 stop = false;
3262                         }
3263                         else
3264                                 VectorClear(c);
3265                 }
3266                 // another check...
3267                 if (stop)
3268                         break;
3269         }
3270 }
3271
3272 static void R_Shadow_RenderLighting_Light_Vertex(int texturenumsurfaces, const msurface_t **texturesurfacelist, const vec3_t lightcolor, float ambientscale, float diffusescale)
3273 {
3274         // OpenGL 1.1 path (anything)
3275         float ambientcolorbase[3], diffusecolorbase[3];
3276         float ambientcolorpants[3], diffusecolorpants[3];
3277         float ambientcolorshirt[3], diffusecolorshirt[3];
3278         const float *surfacecolor = rsurface.texture->dlightcolor;
3279         const float *surfacepants = rsurface.colormap_pantscolor;
3280         const float *surfaceshirt = rsurface.colormap_shirtcolor;
3281         rtexture_t *basetexture = rsurface.texture->basetexture;
3282         rtexture_t *pantstexture = rsurface.texture->pantstexture;
3283         rtexture_t *shirttexture = rsurface.texture->shirttexture;
3284         qboolean dopants = pantstexture && VectorLength2(surfacepants) >= (1.0f / 1048576.0f);
3285         qboolean doshirt = shirttexture && VectorLength2(surfaceshirt) >= (1.0f / 1048576.0f);
3286         ambientscale *= 2 * r_refdef.view.colorscale;
3287         diffusescale *= 2 * r_refdef.view.colorscale;
3288         ambientcolorbase[0] = lightcolor[0] * ambientscale * surfacecolor[0];ambientcolorbase[1] = lightcolor[1] * ambientscale * surfacecolor[1];ambientcolorbase[2] = lightcolor[2] * ambientscale * surfacecolor[2];
3289         diffusecolorbase[0] = lightcolor[0] * diffusescale * surfacecolor[0];diffusecolorbase[1] = lightcolor[1] * diffusescale * surfacecolor[1];diffusecolorbase[2] = lightcolor[2] * diffusescale * surfacecolor[2];
3290         ambientcolorpants[0] = ambientcolorbase[0] * surfacepants[0];ambientcolorpants[1] = ambientcolorbase[1] * surfacepants[1];ambientcolorpants[2] = ambientcolorbase[2] * surfacepants[2];
3291         diffusecolorpants[0] = diffusecolorbase[0] * surfacepants[0];diffusecolorpants[1] = diffusecolorbase[1] * surfacepants[1];diffusecolorpants[2] = diffusecolorbase[2] * surfacepants[2];
3292         ambientcolorshirt[0] = ambientcolorbase[0] * surfaceshirt[0];ambientcolorshirt[1] = ambientcolorbase[1] * surfaceshirt[1];ambientcolorshirt[2] = ambientcolorbase[2] * surfaceshirt[2];
3293         diffusecolorshirt[0] = diffusecolorbase[0] * surfaceshirt[0];diffusecolorshirt[1] = diffusecolorbase[1] * surfaceshirt[1];diffusecolorshirt[2] = diffusecolorbase[2] * surfaceshirt[2];
3294         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | (diffusescale > 0 ? BATCHNEED_ARRAY_NORMAL : 0) | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
3295         rsurface.passcolor4f = (float *)R_FrameData_Alloc((rsurface.batchfirstvertex + rsurface.batchnumvertices) * sizeof(float[4]));
3296         R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3297         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, 0, 0);
3298         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
3299         R_Mesh_TexBind(0, basetexture);
3300         R_Mesh_TexMatrix(0, &rsurface.texture->currenttexmatrix);
3301         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
3302         switch(r_shadow_rendermode)
3303         {
3304         case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
3305                 R_Mesh_TexBind(1, r_shadow_attenuation3dtexture);
3306                 R_Mesh_TexMatrix(1, &rsurface.entitytoattenuationxyz);
3307                 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, 1, 1);
3308                 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3309                 break;
3310         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
3311                 R_Mesh_TexBind(2, r_shadow_attenuation2dtexture);
3312                 R_Mesh_TexMatrix(2, &rsurface.entitytoattenuationz);
3313                 R_Mesh_TexCombine(2, GL_MODULATE, GL_MODULATE, 1, 1);
3314                 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3315                 // fall through
3316         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3317                 R_Mesh_TexBind(1, r_shadow_attenuation2dtexture);
3318                 R_Mesh_TexMatrix(1, &rsurface.entitytoattenuationxyz);
3319                 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, 1, 1);
3320                 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3321                 break;
3322         case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3323                 break;
3324         default:
3325                 break;
3326         }
3327         //R_Mesh_TexBind(0, basetexture);
3328         R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorbase, ambientcolorbase);
3329         if (dopants)
3330         {
3331                 R_Mesh_TexBind(0, pantstexture);
3332                 R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorpants, ambientcolorpants);
3333         }
3334         if (doshirt)
3335         {
3336                 R_Mesh_TexBind(0, shirttexture);
3337                 R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorshirt, ambientcolorshirt);
3338         }
3339 }
3340
3341 extern cvar_t gl_lightmaps;
3342 void R_Shadow_RenderLighting(int texturenumsurfaces, const msurface_t **texturesurfacelist)
3343 {
3344         float ambientscale, diffusescale, specularscale;
3345         qboolean negated;
3346         float lightcolor[3];
3347         VectorCopy(rsurface.rtlight->currentcolor, lightcolor);
3348         ambientscale = rsurface.rtlight->ambientscale + rsurface.texture->rtlightambient;
3349         diffusescale = rsurface.rtlight->diffusescale * max(0, 1.0 - rsurface.texture->rtlightambient);
3350         specularscale = rsurface.rtlight->specularscale * rsurface.texture->specularscale;
3351         if (!r_shadow_usenormalmap.integer)
3352         {
3353                 ambientscale += 1.0f * diffusescale;
3354                 diffusescale = 0;
3355                 specularscale = 0;
3356         }
3357         if ((ambientscale + diffusescale) * VectorLength2(lightcolor) + specularscale * VectorLength2(lightcolor) < (1.0f / 1048576.0f))
3358                 return;
3359         negated = (lightcolor[0] + lightcolor[1] + lightcolor[2] < 0) && vid.support.ext_blend_subtract;
3360         if(negated)
3361         {
3362                 VectorNegate(lightcolor, lightcolor);
3363                 GL_BlendEquationSubtract(true);
3364         }
3365         RSurf_SetupDepthAndCulling();
3366         switch (r_shadow_rendermode)
3367         {
3368         case R_SHADOW_RENDERMODE_VISIBLELIGHTING:
3369                 GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST) && !r_showdisabledepthtest.integer);
3370                 R_Shadow_RenderLighting_VisibleLighting(texturenumsurfaces, texturesurfacelist);
3371                 break;
3372         case R_SHADOW_RENDERMODE_LIGHT_GLSL:
3373                 R_Shadow_RenderLighting_Light_GLSL(texturenumsurfaces, texturesurfacelist, lightcolor, ambientscale, diffusescale, specularscale);
3374                 break;
3375         case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
3376         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
3377         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3378         case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3379                 R_Shadow_RenderLighting_Light_Vertex(texturenumsurfaces, texturesurfacelist, lightcolor, ambientscale, diffusescale);
3380                 break;
3381         default:
3382                 Con_Printf("R_Shadow_RenderLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode);
3383                 break;
3384         }
3385         if(negated)
3386                 GL_BlendEquationSubtract(false);
3387 }
3388
3389 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)
3390 {
3391         matrix4x4_t tempmatrix = *matrix;
3392         Matrix4x4_Scale(&tempmatrix, r_shadow_lightradiusscale.value, 1);
3393
3394         // if this light has been compiled before, free the associated data
3395         R_RTLight_Uncompile(rtlight);
3396
3397         // clear it completely to avoid any lingering data
3398         memset(rtlight, 0, sizeof(*rtlight));
3399
3400         // copy the properties
3401         rtlight->matrix_lighttoworld = tempmatrix;
3402         Matrix4x4_Invert_Simple(&rtlight->matrix_worldtolight, &tempmatrix);
3403         Matrix4x4_OriginFromMatrix(&tempmatrix, rtlight->shadoworigin);
3404         rtlight->radius = Matrix4x4_ScaleFromMatrix(&tempmatrix);
3405         VectorCopy(color, rtlight->color);
3406         rtlight->cubemapname[0] = 0;
3407         if (cubemapname && cubemapname[0])
3408                 strlcpy(rtlight->cubemapname, cubemapname, sizeof(rtlight->cubemapname));
3409         rtlight->shadow = shadow;
3410         rtlight->corona = corona;
3411         rtlight->style = style;
3412         rtlight->isstatic = isstatic;
3413         rtlight->coronasizescale = coronasizescale;
3414         rtlight->ambientscale = ambientscale;
3415         rtlight->diffusescale = diffusescale;
3416         rtlight->specularscale = specularscale;
3417         rtlight->flags = flags;
3418
3419         // compute derived data
3420         //rtlight->cullradius = rtlight->radius;
3421         //rtlight->cullradius2 = rtlight->radius * rtlight->radius;
3422         rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
3423         rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
3424         rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
3425         rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
3426         rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
3427         rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
3428 }
3429
3430 // compiles rtlight geometry
3431 // (undone by R_FreeCompiledRTLight, which R_UpdateLight calls)
3432 void R_RTLight_Compile(rtlight_t *rtlight)
3433 {
3434         int i;
3435         int numsurfaces, numleafs, numleafpvsbytes, numshadowtrispvsbytes, numlighttrispvsbytes;
3436         int lighttris, shadowtris, shadowzpasstris, shadowzfailtris;
3437         entity_render_t *ent = r_refdef.scene.worldentity;
3438         dp_model_t *model = r_refdef.scene.worldmodel;
3439         unsigned char *data;
3440         shadowmesh_t *mesh;
3441
3442         // compile the light
3443         rtlight->compiled = true;
3444         rtlight->shadowmode = rtlight->shadow ? (int)r_shadow_shadowmode : -1;
3445         rtlight->static_numleafs = 0;
3446         rtlight->static_numleafpvsbytes = 0;
3447         rtlight->static_leaflist = NULL;
3448         rtlight->static_leafpvs = NULL;
3449         rtlight->static_numsurfaces = 0;
3450         rtlight->static_surfacelist = NULL;
3451         rtlight->static_shadowmap_receivers = 0x3F;
3452         rtlight->static_shadowmap_casters = 0x3F;
3453         rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
3454         rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
3455         rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
3456         rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
3457         rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
3458         rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
3459
3460         if (model && model->GetLightInfo)
3461         {
3462                 // this variable must be set for the CompileShadowVolume/CompileShadowMap code
3463                 r_shadow_compilingrtlight = rtlight;
3464                 R_FrameData_SetMark();
3465                 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);
3466                 R_FrameData_ReturnToMark();
3467                 numleafpvsbytes = (model->brush.num_leafs + 7) >> 3;
3468                 numshadowtrispvsbytes = ((model->brush.shadowmesh ? model->brush.shadowmesh->numtriangles : model->surfmesh.num_triangles) + 7) >> 3;
3469                 numlighttrispvsbytes = (model->surfmesh.num_triangles + 7) >> 3;
3470                 data = (unsigned char *)Mem_Alloc(r_main_mempool, sizeof(int) * numsurfaces + sizeof(int) * numleafs + numleafpvsbytes + numshadowtrispvsbytes + numlighttrispvsbytes);
3471                 rtlight->static_numsurfaces = numsurfaces;
3472                 rtlight->static_surfacelist = (int *)data;data += sizeof(int) * numsurfaces;
3473                 rtlight->static_numleafs = numleafs;
3474                 rtlight->static_leaflist = (int *)data;data += sizeof(int) * numleafs;
3475                 rtlight->static_numleafpvsbytes = numleafpvsbytes;
3476                 rtlight->static_leafpvs = (unsigned char *)data;data += numleafpvsbytes;
3477                 rtlight->static_numshadowtrispvsbytes = numshadowtrispvsbytes;
3478                 rtlight->static_shadowtrispvs = (unsigned char *)data;data += numshadowtrispvsbytes;
3479                 rtlight->static_numlighttrispvsbytes = numlighttrispvsbytes;
3480                 rtlight->static_lighttrispvs = (unsigned char *)data;data += numlighttrispvsbytes;
3481                 if (rtlight->static_numsurfaces)
3482                         memcpy(rtlight->static_surfacelist, r_shadow_buffer_surfacelist, rtlight->static_numsurfaces * sizeof(*rtlight->static_surfacelist));
3483                 if (rtlight->static_numleafs)
3484                         memcpy(rtlight->static_leaflist, r_shadow_buffer_leaflist, rtlight->static_numleafs * sizeof(*rtlight->static_leaflist));
3485                 if (rtlight->static_numleafpvsbytes)
3486                         memcpy(rtlight->static_leafpvs, r_shadow_buffer_leafpvs, rtlight->static_numleafpvsbytes);
3487                 if (rtlight->static_numshadowtrispvsbytes)
3488                         memcpy(rtlight->static_shadowtrispvs, r_shadow_buffer_shadowtrispvs, rtlight->static_numshadowtrispvsbytes);
3489                 if (rtlight->static_numlighttrispvsbytes)
3490                         memcpy(rtlight->static_lighttrispvs, r_shadow_buffer_lighttrispvs, rtlight->static_numlighttrispvsbytes);
3491                 R_FrameData_SetMark();
3492                 switch (rtlight->shadowmode)
3493                 {
3494                 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
3495                         if (model->CompileShadowMap && rtlight->shadow)
3496                                 model->CompileShadowMap(ent, rtlight->shadoworigin, NULL, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist);
3497                         break;
3498                 default:
3499                         if (model->CompileShadowVolume && rtlight->shadow)
3500                                 model->CompileShadowVolume(ent, rtlight->shadoworigin, NULL, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist);
3501                         break;
3502                 }
3503                 R_FrameData_ReturnToMark();
3504                 // now we're done compiling the rtlight
3505                 r_shadow_compilingrtlight = NULL;
3506         }
3507
3508
3509         // use smallest available cullradius - box radius or light radius
3510         //rtlight->cullradius = RadiusFromBoundsAndOrigin(rtlight->cullmins, rtlight->cullmaxs, rtlight->shadoworigin);
3511         //rtlight->cullradius = min(rtlight->cullradius, rtlight->radius);
3512
3513         shadowzpasstris = 0;
3514         if (rtlight->static_meshchain_shadow_zpass)
3515                 for (mesh = rtlight->static_meshchain_shadow_zpass;mesh;mesh = mesh->next)
3516                         shadowzpasstris += mesh->numtriangles;
3517
3518         shadowzfailtris = 0;
3519         if (rtlight->static_meshchain_shadow_zfail)
3520                 for (mesh = rtlight->static_meshchain_shadow_zfail;mesh;mesh = mesh->next)
3521                         shadowzfailtris += mesh->numtriangles;
3522
3523         lighttris = 0;
3524         if (rtlight->static_numlighttrispvsbytes)
3525                 for (i = 0;i < rtlight->static_numlighttrispvsbytes*8;i++)
3526                         if (CHECKPVSBIT(rtlight->static_lighttrispvs, i))
3527                                 lighttris++;
3528
3529         shadowtris = 0;
3530         if (rtlight->static_numlighttrispvsbytes)
3531                 for (i = 0;i < rtlight->static_numshadowtrispvsbytes*8;i++)
3532                         if (CHECKPVSBIT(rtlight->static_shadowtrispvs, i))
3533                                 shadowtris++;
3534
3535         if (developer_extra.integer)
3536                 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);
3537 }
3538
3539 void R_RTLight_Uncompile(rtlight_t *rtlight)
3540 {
3541         if (rtlight->compiled)
3542         {
3543                 if (rtlight->static_meshchain_shadow_zpass)
3544                         Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_zpass);
3545                 rtlight->static_meshchain_shadow_zpass = NULL;
3546                 if (rtlight->static_meshchain_shadow_zfail)
3547                         Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_zfail);
3548                 rtlight->static_meshchain_shadow_zfail = NULL;
3549                 if (rtlight->static_meshchain_shadow_shadowmap)
3550                         Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_shadowmap);
3551                 rtlight->static_meshchain_shadow_shadowmap = NULL;
3552                 // these allocations are grouped
3553                 if (rtlight->static_surfacelist)
3554                         Mem_Free(rtlight->static_surfacelist);
3555                 rtlight->static_numleafs = 0;
3556                 rtlight->static_numleafpvsbytes = 0;
3557                 rtlight->static_leaflist = NULL;
3558                 rtlight->static_leafpvs = NULL;
3559                 rtlight->static_numsurfaces = 0;
3560                 rtlight->static_surfacelist = NULL;
3561                 rtlight->static_numshadowtrispvsbytes = 0;
3562                 rtlight->static_shadowtrispvs = NULL;
3563                 rtlight->static_numlighttrispvsbytes = 0;
3564                 rtlight->static_lighttrispvs = NULL;
3565                 rtlight->compiled = false;
3566         }
3567 }
3568
3569 void R_Shadow_UncompileWorldLights(void)
3570 {
3571         size_t lightindex;
3572         dlight_t *light;
3573         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
3574         for (lightindex = 0;lightindex < range;lightindex++)
3575         {
3576                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
3577                 if (!light)
3578                         continue;
3579                 R_RTLight_Uncompile(&light->rtlight);
3580         }
3581 }
3582
3583 static void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight)
3584 {
3585         int i, j;
3586         mplane_t plane;
3587         // reset the count of frustum planes
3588         // see rtlight->cached_frustumplanes definition for how much this array
3589         // can hold
3590         rtlight->cached_numfrustumplanes = 0;
3591
3592         if (r_trippy.integer)
3593                 return;
3594
3595         // haven't implemented a culling path for ortho rendering
3596         if (!r_refdef.view.useperspective)
3597         {
3598                 // check if the light is on screen and copy the 4 planes if it is
3599                 for (i = 0;i < 4;i++)
3600                         if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) < -0.03125)
3601                                 break;
3602                 if (i == 4)
3603                         for (i = 0;i < 4;i++)
3604                                 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = r_refdef.view.frustum[i];
3605                 return;
3606         }
3607
3608 #if 1
3609         // generate a deformed frustum that includes the light origin, this is
3610         // used to cull shadow casting surfaces that can not possibly cast a
3611         // shadow onto the visible light-receiving surfaces, which can be a
3612         // performance gain
3613         //
3614         // if the light origin is onscreen the result will be 4 planes exactly
3615         // if the light origin is offscreen on only one axis the result will
3616         // be exactly 5 planes (split-side case)
3617         // if the light origin is offscreen on two axes the result will be
3618         // exactly 4 planes (stretched corner case)
3619         for (i = 0;i < 4;i++)
3620         {
3621                 // quickly reject standard frustum planes that put the light
3622                 // origin outside the frustum
3623                 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) < -0.03125)
3624                         continue;
3625                 // copy the plane
3626                 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = r_refdef.view.frustum[i];
3627         }
3628         // if all the standard frustum planes were accepted, the light is onscreen
3629         // otherwise we need to generate some more planes below...
3630         if (rtlight->cached_numfrustumplanes < 4)
3631         {
3632                 // at least one of the stock frustum planes failed, so we need to
3633                 // create one or two custom planes to enclose the light origin
3634                 for (i = 0;i < 4;i++)
3635                 {
3636                         // create a plane using the view origin and light origin, and a
3637                         // single point from the frustum corner set
3638                         TriangleNormal(r_refdef.view.origin, r_refdef.view.frustumcorner[i], rtlight->shadoworigin, plane.normal);
3639                         VectorNormalize(plane.normal);
3640                         plane.dist = DotProduct(r_refdef.view.origin, plane.normal);
3641                         // see if this plane is backwards and flip it if so
3642                         for (j = 0;j < 4;j++)
3643                                 if (j != i && DotProduct(r_refdef.view.frustumcorner[j], plane.normal) - plane.dist < -0.03125)
3644                                         break;
3645                         if (j < 4)
3646                         {
3647                                 VectorNegate(plane.normal, plane.normal);
3648                                 plane.dist *= -1;
3649                                 // flipped plane, test again to see if it is now valid
3650                                 for (j = 0;j < 4;j++)
3651                                         if (j != i && DotProduct(r_refdef.view.frustumcorner[j], plane.normal) - plane.dist < -0.03125)
3652                                                 break;
3653                                 // if the plane is still not valid, then it is dividing the
3654                                 // frustum and has to be rejected
3655                                 if (j < 4)
3656                                         continue;
3657                         }
3658                         // we have created a valid plane, compute extra info
3659                         PlaneClassify(&plane);
3660                         // copy the plane
3661                         rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3662 #if 1
3663                         // if we've found 5 frustum planes then we have constructed a
3664                         // proper split-side case and do not need to keep searching for
3665                         // planes to enclose the light origin
3666                         if (rtlight->cached_numfrustumplanes == 5)
3667                                 break;
3668 #endif
3669                 }
3670         }
3671 #endif
3672
3673 #if 0
3674         for (i = 0;i < rtlight->cached_numfrustumplanes;i++)
3675         {
3676                 plane = rtlight->cached_frustumplanes[i];
3677                 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));
3678         }
3679 #endif
3680
3681 #if 0
3682         // now add the light-space box planes if the light box is rotated, as any
3683         // caster outside the oriented light box is irrelevant (even if it passed
3684         // the worldspace light box, which is axial)
3685         if (rtlight->matrix_lighttoworld.m[0][0] != 1 || rtlight->matrix_lighttoworld.m[1][1] != 1 || rtlight->matrix_lighttoworld.m[2][2] != 1)
3686         {
3687                 for (i = 0;i < 6;i++)
3688                 {
3689                         vec3_t v;
3690                         VectorClear(v);
3691                         v[i >> 1] = (i & 1) ? -1 : 1;
3692                         Matrix4x4_Transform(&rtlight->matrix_lighttoworld, v, plane.normal);
3693                         VectorSubtract(plane.normal, rtlight->shadoworigin, plane.normal);
3694                         plane.dist = VectorNormalizeLength(plane.normal);
3695                         plane.dist += DotProduct(plane.normal, rtlight->shadoworigin);
3696                         rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3697                 }
3698         }
3699 #endif
3700
3701 #if 0
3702         // add the world-space reduced box planes
3703         for (i = 0;i < 6;i++)
3704         {
3705                 VectorClear(plane.normal);
3706                 plane.normal[i >> 1] = (i & 1) ? -1 : 1;
3707                 plane.dist = (i & 1) ? -rtlight->cached_cullmaxs[i >> 1] : rtlight->cached_cullmins[i >> 1];
3708                 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3709         }
3710 #endif
3711
3712 #if 0
3713         {
3714         int j, oldnum;
3715         vec3_t points[8];
3716         vec_t bestdist;
3717         // reduce all plane distances to tightly fit the rtlight cull box, which
3718         // is in worldspace
3719         VectorSet(points[0], rtlight->cached_cullmins[0], rtlight->cached_cullmins[1], rtlight->cached_cullmins[2]);
3720         VectorSet(points[1], rtlight->cached_cullmaxs[0], rtlight->cached_cullmins[1], rtlight->cached_cullmins[2]);
3721         VectorSet(points[2], rtlight->cached_cullmins[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmins[2]);
3722         VectorSet(points[3], rtlight->cached_cullmaxs[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmins[2]);
3723         VectorSet(points[4], rtlight->cached_cullmins[0], rtlight->cached_cullmins[1], rtlight->cached_cullmaxs[2]);
3724         VectorSet(points[5], rtlight->cached_cullmaxs[0], rtlight->cached_cullmins[1], rtlight->cached_cullmaxs[2]);
3725         VectorSet(points[6], rtlight->cached_cullmins[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmaxs[2]);
3726         VectorSet(points[7], rtlight->cached_cullmaxs[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmaxs[2]);
3727         oldnum = rtlight->cached_numfrustumplanes;
3728         rtlight->cached_numfrustumplanes = 0;
3729         for (j = 0;j < oldnum;j++)
3730         {
3731                 // find the nearest point on the box to this plane
3732                 bestdist = DotProduct(rtlight->cached_frustumplanes[j].normal, points[0]);
3733                 for (i = 1;i < 8;i++)
3734                 {
3735                         dist = DotProduct(rtlight->cached_frustumplanes[j].normal, points[i]);
3736                         if (bestdist > dist)
3737                                 bestdist = dist;
3738                 }
3739                 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);
3740                 // if the nearest point is near or behind the plane, we want this
3741                 // plane, otherwise the plane is useless as it won't cull anything
3742                 if (rtlight->cached_frustumplanes[j].dist < bestdist + 0.03125)
3743                 {
3744                         PlaneClassify(&rtlight->cached_frustumplanes[j]);
3745                         rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = rtlight->cached_frustumplanes[j];
3746                 }
3747         }
3748         }
3749 #endif
3750 }
3751
3752 static void R_Shadow_DrawWorldShadow_ShadowMap(int numsurfaces, int *surfacelist, const unsigned char *trispvs, const unsigned char *surfacesides)
3753 {
3754         shadowmesh_t *mesh;
3755
3756         RSurf_ActiveWorldEntity();
3757
3758         if (rsurface.rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
3759         {
3760                 CHECKGLERROR
3761                 GL_CullFace(GL_NONE);
3762                 mesh = rsurface.rtlight->static_meshchain_shadow_shadowmap;
3763                 for (;mesh;mesh = mesh->next)
3764                 {
3765                         if (!mesh->sidetotals[r_shadow_shadowmapside])
3766                                 continue;
3767                         r_refdef.stats[r_stat_lights_shadowtriangles] += mesh->sidetotals[r_shadow_shadowmapside];
3768                         R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vbo_vertexbuffer, mesh->vbooffset_vertex3f);
3769                         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);
3770                 }
3771                 CHECKGLERROR
3772         }
3773         else if (r_refdef.scene.worldentity->model)
3774                 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);
3775
3776         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3777 }
3778
3779 static void R_Shadow_DrawWorldShadow_ShadowVolume(int numsurfaces, int *surfacelist, const unsigned char *trispvs)
3780 {
3781         qboolean zpass = false;
3782         shadowmesh_t *mesh;
3783         int t, tend;
3784         int surfacelistindex;
3785         msurface_t *surface;
3786
3787         // if triangle neighbors are disabled, shadowvolumes are disabled
3788         if (r_refdef.scene.worldmodel->brush.shadowmesh ? !r_refdef.scene.worldmodel->brush.shadowmesh->neighbor3i : !r_refdef.scene.worldmodel->surfmesh.data_neighbor3i)
3789                 return;
3790
3791         RSurf_ActiveWorldEntity();
3792
3793         if (rsurface.rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
3794         {
3795                 CHECKGLERROR
3796                 if (r_shadow_rendermode != R_SHADOW_RENDERMODE_VISIBLEVOLUMES)
3797                 {
3798                         zpass = R_Shadow_UseZPass(r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs);
3799                         R_Shadow_RenderMode_StencilShadowVolumes(zpass);
3800                 }
3801                 mesh = zpass ? rsurface.rtlight->static_meshchain_shadow_zpass : rsurface.rtlight->static_meshchain_shadow_zfail;
3802                 for (;mesh;mesh = mesh->next)
3803                 {
3804                         r_refdef.stats[r_stat_lights_shadowtriangles] += mesh->numtriangles;
3805                         R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vbo_vertexbuffer, mesh->vbooffset_vertex3f);
3806                         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
3807                         {
3808                                 // increment stencil if frontface is infront of depthbuffer
3809                                 GL_CullFace(r_refdef.view.cullface_back);
3810                                 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_ALWAYS, 128, 255);
3811                                 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);
3812                                 // decrement stencil if backface is infront of depthbuffer
3813                                 GL_CullFace(r_refdef.view.cullface_front);
3814                                 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, 128, 255);
3815                         }
3816                         else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
3817                         {
3818                                 // decrement stencil if backface is behind depthbuffer
3819                                 GL_CullFace(r_refdef.view.cullface_front);
3820                                 R_SetStencil(true, 255, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, 128, 255);
3821                                 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);
3822                                 // increment stencil if frontface is behind depthbuffer
3823                                 GL_CullFace(r_refdef.view.cullface_back);
3824                                 R_SetStencil(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_ALWAYS, 128, 255);
3825                         }
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                 }
3828                 CHECKGLERROR
3829         }
3830         else if (numsurfaces && r_refdef.scene.worldmodel->brush.shadowmesh)
3831         {
3832                 // use the shadow trispvs calculated earlier by GetLightInfo to cull world triangles on this dynamic light
3833                 R_Shadow_PrepareShadowMark(r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles);
3834                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
3835                 {
3836                         surface = r_refdef.scene.worldmodel->data_surfaces + surfacelist[surfacelistindex];
3837                         for (t = surface->num_firstshadowmeshtriangle, tend = t + surface->num_triangles;t < tend;t++)
3838                                 if (CHECKPVSBIT(trispvs, t))
3839                                         shadowmarklist[numshadowmark++] = t;
3840                 }
3841                 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);
3842         }
3843         else if (numsurfaces)
3844         {
3845                 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);
3846         }
3847
3848         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3849 }
3850
3851 static void R_Shadow_DrawEntityShadow(entity_render_t *ent)
3852 {
3853         vec3_t relativeshadoworigin, relativeshadowmins, relativeshadowmaxs;
3854         vec_t relativeshadowradius;
3855         RSurf_ActiveModelEntity(ent, false, false, false);
3856         Matrix4x4_Transform(&ent->inversematrix, rsurface.rtlight->shadoworigin, relativeshadoworigin);
3857         // we need to re-init the shader for each entity because the matrix changed
3858         relativeshadowradius = rsurface.rtlight->radius / ent->scale;
3859         relativeshadowmins[0] = relativeshadoworigin[0] - relativeshadowradius;
3860         relativeshadowmins[1] = relativeshadoworigin[1] - relativeshadowradius;
3861         relativeshadowmins[2] = relativeshadoworigin[2] - relativeshadowradius;
3862         relativeshadowmaxs[0] = relativeshadoworigin[0] + relativeshadowradius;
3863         relativeshadowmaxs[1] = relativeshadoworigin[1] + relativeshadowradius;
3864         relativeshadowmaxs[2] = relativeshadoworigin[2] + relativeshadowradius;
3865         switch (r_shadow_rendermode)
3866         {
3867         case R_SHADOW_RENDERMODE_SHADOWMAP2D:
3868                 ent->model->DrawShadowMap(r_shadow_shadowmapside, ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, NULL, relativeshadowmins, relativeshadowmaxs);
3869                 break;
3870         default:
3871                 ent->model->DrawShadowVolume(ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
3872                 break;
3873         }
3874         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3875 }
3876
3877 void R_Shadow_SetupEntityLight(const entity_render_t *ent)
3878 {
3879         // set up properties for rendering light onto this entity
3880         RSurf_ActiveModelEntity(ent, true, true, false);
3881         Matrix4x4_Concat(&rsurface.entitytolight, &rsurface.rtlight->matrix_worldtolight, &ent->matrix);
3882         Matrix4x4_Concat(&rsurface.entitytoattenuationxyz, &matrix_attenuationxyz, &rsurface.entitytolight);
3883         Matrix4x4_Concat(&rsurface.entitytoattenuationz, &matrix_attenuationz, &rsurface.entitytolight);
3884         Matrix4x4_Transform(&ent->inversematrix, rsurface.rtlight->shadoworigin, rsurface.entitylightorigin);
3885 }
3886
3887 static void R_Shadow_DrawWorldLight(int numsurfaces, int *surfacelist, const unsigned char *lighttrispvs)
3888 {
3889         if (!r_refdef.scene.worldmodel->DrawLight)
3890                 return;
3891
3892         // set up properties for rendering light onto this entity
3893         RSurf_ActiveWorldEntity();
3894         rsurface.entitytolight = rsurface.rtlight->matrix_worldtolight;
3895         Matrix4x4_Concat(&rsurface.entitytoattenuationxyz, &matrix_attenuationxyz, &rsurface.entitytolight);
3896         Matrix4x4_Concat(&rsurface.entitytoattenuationz, &matrix_attenuationz, &rsurface.entitytolight);
3897         VectorCopy(rsurface.rtlight->shadoworigin, rsurface.entitylightorigin);
3898
3899         r_refdef.scene.worldmodel->DrawLight(r_refdef.scene.worldentity, numsurfaces, surfacelist, lighttrispvs);
3900
3901         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3902 }
3903
3904 static void R_Shadow_DrawEntityLight(entity_render_t *ent)
3905 {
3906         dp_model_t *model = ent->model;
3907         if (!model->DrawLight)
3908                 return;
3909
3910         R_Shadow_SetupEntityLight(ent);
3911
3912         model->DrawLight(ent, model->nummodelsurfaces, model->sortedmodelsurfaces, NULL);
3913
3914         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3915 }
3916
3917 static void R_Shadow_PrepareLight(rtlight_t *rtlight)
3918 {
3919         int i;
3920         float f;
3921         int numleafs, numsurfaces;
3922         int *leaflist, *surfacelist;
3923         unsigned char *leafpvs;
3924         unsigned char *shadowtrispvs;
3925         unsigned char *lighttrispvs;
3926         //unsigned char *surfacesides;
3927         int numlightentities;
3928         int numlightentities_noselfshadow;
3929         int numshadowentities;
3930         int numshadowentities_noselfshadow;
3931         static entity_render_t *lightentities[MAX_EDICTS];
3932         static entity_render_t *lightentities_noselfshadow[MAX_EDICTS];
3933         static entity_render_t *shadowentities[MAX_EDICTS];
3934         static entity_render_t *shadowentities_noselfshadow[MAX_EDICTS];
3935         qboolean nolight;
3936         qboolean castshadows;
3937
3938         rtlight->draw = false;
3939         rtlight->cached_numlightentities               = 0;
3940         rtlight->cached_numlightentities_noselfshadow  = 0;
3941         rtlight->cached_numshadowentities              = 0;
3942         rtlight->cached_numshadowentities_noselfshadow = 0;
3943         rtlight->cached_numsurfaces                    = 0;
3944         rtlight->occlusion_buf                         = 0;
3945         rtlight->cached_lightentities                  = NULL;
3946         rtlight->cached_lightentities_noselfshadow     = NULL;
3947         rtlight->cached_shadowentities                 = NULL;
3948         rtlight->cached_shadowentities_noselfshadow    = NULL;
3949         rtlight->cached_shadowtrispvs                  = NULL;
3950         rtlight->cached_lighttrispvs                   = NULL;
3951         rtlight->cached_surfacelist                    = NULL;
3952
3953         // skip lights that don't light because of ambientscale+diffusescale+specularscale being 0 (corona only lights)
3954         // skip lights that are basically invisible (color 0 0 0)
3955         nolight = VectorLength2(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) < (1.0f / 1048576.0f);
3956
3957         // loading is done before visibility checks because loading should happen
3958         // all at once at the start of a level, not when it stalls gameplay.
3959         // (especially important to benchmarks)
3960         // compile light
3961         if (rtlight->isstatic && !nolight && (!rtlight->compiled || (rtlight->shadow && rtlight->shadowmode != (int)r_shadow_shadowmode)) && r_shadow_realtime_world_compile.integer)
3962         {
3963                 if (rtlight->compiled)
3964                         R_RTLight_Uncompile(rtlight);
3965                 R_RTLight_Compile(rtlight);
3966         }
3967
3968         // load cubemap
3969         rtlight->currentcubemap = rtlight->cubemapname[0] ? R_GetCubemap(rtlight->cubemapname) : r_texture_whitecube;
3970
3971         // look up the light style value at this time
3972         f = ((rtlight->style >= 0 && rtlight->style < MAX_LIGHTSTYLES) ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value;
3973         VectorScale(rtlight->color, f, rtlight->currentcolor);
3974         /*
3975         if (rtlight->selected)
3976         {
3977                 f = 2 + sin(realtime * M_PI * 4.0);
3978                 VectorScale(rtlight->currentcolor, f, rtlight->currentcolor);
3979         }
3980         */
3981
3982         // if lightstyle is currently off, don't draw the light
3983         if (VectorLength2(rtlight->currentcolor) < (1.0f / 1048576.0f))
3984                 return;
3985
3986         // skip processing on corona-only lights
3987         if (nolight)
3988                 return;
3989
3990         // if the light box is offscreen, skip it
3991         if (R_CullBox(rtlight->cullmins, rtlight->cullmaxs))
3992                 return;
3993
3994         VectorCopy(rtlight->cullmins, rtlight->cached_cullmins);
3995         VectorCopy(rtlight->cullmaxs, rtlight->cached_cullmaxs);
3996
3997         R_Shadow_ComputeShadowCasterCullingPlanes(rtlight);
3998
3999         // 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
4000         if (r_shadow_bouncegrid.integer == 2 && (rtlight->isstatic || !r_shadow_bouncegrid_static.integer))
4001                 return;
4002
4003         if (rtlight->compiled && r_shadow_realtime_world_compile.integer)
4004         {
4005                 // compiled light, world available and can receive realtime lighting
4006                 // retrieve leaf information
4007                 numleafs = rtlight->static_numleafs;
4008                 leaflist = rtlight->static_leaflist;
4009                 leafpvs = rtlight->static_leafpvs;
4010                 numsurfaces = rtlight->static_numsurfaces;
4011                 surfacelist = rtlight->static_surfacelist;
4012                 //surfacesides = NULL;
4013                 shadowtrispvs = rtlight->static_shadowtrispvs;
4014                 lighttrispvs = rtlight->static_lighttrispvs;
4015         }
4016         else if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->GetLightInfo)
4017         {
4018                 // dynamic light, world available and can receive realtime lighting
4019                 // calculate lit surfaces and leafs
4020                 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);
4021                 R_Shadow_ComputeShadowCasterCullingPlanes(rtlight);
4022                 leaflist = r_shadow_buffer_leaflist;
4023                 leafpvs = r_shadow_buffer_leafpvs;
4024                 surfacelist = r_shadow_buffer_surfacelist;
4025                 //surfacesides = r_shadow_buffer_surfacesides;
4026                 shadowtrispvs = r_shadow_buffer_shadowtrispvs;
4027                 lighttrispvs = r_shadow_buffer_lighttrispvs;
4028                 // if the reduced leaf bounds are offscreen, skip it
4029                 if (R_CullBox(rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4030                         return;
4031         }
4032         else
4033         {
4034                 // no world
4035                 numleafs = 0;
4036                 leaflist = NULL;
4037                 leafpvs = NULL;
4038                 numsurfaces = 0;
4039                 surfacelist = NULL;
4040                 //surfacesides = NULL;
4041                 shadowtrispvs = NULL;
4042                 lighttrispvs = NULL;
4043         }
4044         // check if light is illuminating any visible leafs
4045         if (numleafs)
4046         {
4047                 for (i = 0;i < numleafs;i++)
4048                         if (r_refdef.viewcache.world_leafvisible[leaflist[i]])
4049                                 break;
4050                 if (i == numleafs)
4051                         return;
4052         }
4053
4054         // make a list of lit entities and shadow casting entities
4055         numlightentities = 0;
4056         numlightentities_noselfshadow = 0;
4057         numshadowentities = 0;
4058         numshadowentities_noselfshadow = 0;
4059
4060         // add dynamic entities that are lit by the light
4061         for (i = 0;i < r_refdef.scene.numentities;i++)
4062         {
4063                 dp_model_t *model;
4064                 entity_render_t *ent = r_refdef.scene.entities[i];
4065                 vec3_t org;
4066                 if (!BoxesOverlap(ent->mins, ent->maxs, rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4067                         continue;
4068                 // skip the object entirely if it is not within the valid
4069                 // shadow-casting region (which includes the lit region)
4070                 if (R_CullBoxCustomPlanes(ent->mins, ent->maxs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes))
4071                         continue;
4072                 if (!(model = ent->model))
4073                         continue;
4074                 if (r_refdef.viewcache.entityvisible[i] && model->DrawLight && (ent->flags & RENDER_LIGHT))
4075                 {
4076                         // this entity wants to receive light, is visible, and is
4077                         // inside the light box
4078                         // TODO: check if the surfaces in the model can receive light
4079                         // so now check if it's in a leaf seen by the light
4080                         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))
4081                                 continue;
4082                         if (ent->flags & RENDER_NOSELFSHADOW)
4083                                 lightentities_noselfshadow[numlightentities_noselfshadow++] = ent;
4084                         else
4085                                 lightentities[numlightentities++] = ent;
4086                         // since it is lit, it probably also casts a shadow...
4087                         // about the VectorDistance2 - light emitting entities should not cast their own shadow
4088                         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
4089                         if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1)
4090                         {
4091                                 // note: exterior models without the RENDER_NOSELFSHADOW
4092                                 // flag still create a RENDER_NOSELFSHADOW shadow but
4093                                 // are lit normally, this means that they are
4094                                 // self-shadowing but do not shadow other
4095                                 // RENDER_NOSELFSHADOW entities such as the gun
4096                                 // (very weird, but keeps the player shadow off the gun)
4097                                 if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL))
4098                                         shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent;
4099                                 else
4100                                         shadowentities[numshadowentities++] = ent;
4101                         }
4102                 }
4103                 else if (ent->flags & RENDER_SHADOW)
4104                 {
4105                         // this entity is not receiving light, but may still need to
4106                         // cast a shadow...
4107                         // TODO: check if the surfaces in the model can cast shadow
4108                         // now check if it is in a leaf seen by the light
4109                         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))
4110                                 continue;
4111                         // about the VectorDistance2 - light emitting entities should not cast their own shadow
4112                         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
4113                         if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1)
4114                         {
4115                                 if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL))
4116                                         shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent;
4117                                 else
4118                                         shadowentities[numshadowentities++] = ent;
4119                         }
4120                 }
4121         }
4122
4123         // return if there's nothing at all to light
4124         if (numsurfaces + numlightentities + numlightentities_noselfshadow == 0)
4125                 return;
4126
4127         // count this light in the r_speeds
4128         r_refdef.stats[r_stat_lights]++;
4129
4130         // flag it as worth drawing later
4131         rtlight->draw = true;
4132
4133         // if we have shadows disabled, don't count the shadow entities, this way we don't do the R_AnimCache_GetEntity on each one
4134         castshadows = numsurfaces + numshadowentities + numshadowentities_noselfshadow > 0 && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows);
4135         if (!castshadows)
4136                 numshadowentities = numshadowentities_noselfshadow = 0;
4137
4138         // cache all the animated entities that cast a shadow but are not visible
4139         for (i = 0;i < numshadowentities;i++)
4140                 R_AnimCache_GetEntity(shadowentities[i], false, false);
4141         for (i = 0;i < numshadowentities_noselfshadow;i++)
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_shadowmapdepthtexture != r_fb.usedepthtextures)
4537                 R_Shadow_FreeShadowMaps();
4538
4539         r_shadow_fb_fbo = fbo;
4540         r_shadow_fb_depthtexture = depthtexture;
4541         r_shadow_fb_colortexture = colortexture;
4542
4543         r_shadow_usingshadowmaportho = false;
4544
4545         switch (vid.renderpath)
4546         {
4547         case RENDERPATH_GL20:
4548         case RENDERPATH_D3D9:
4549         case RENDERPATH_D3D10:
4550         case RENDERPATH_D3D11:
4551         case RENDERPATH_SOFT:
4552 #ifndef USE_GLES2
4553                 if (!r_shadow_deferred.integer || r_shadow_shadowmode == R_SHADOW_SHADOWMODE_STENCIL || !vid.support.ext_framebuffer_object || vid.maxdrawbuffers < 2)
4554                 {
4555                         r_shadow_usingdeferredprepass = false;
4556                         if (r_shadow_prepass_width)
4557                                 R_Shadow_FreeDeferred();
4558                         r_shadow_prepass_width = r_shadow_prepass_height = 0;
4559                         break;
4560                 }
4561
4562                 if (r_shadow_prepass_width != vid.width || r_shadow_prepass_height != vid.height)
4563                 {
4564                         R_Shadow_FreeDeferred();
4565
4566                         r_shadow_usingdeferredprepass = true;
4567                         r_shadow_prepass_width = vid.width;
4568                         r_shadow_prepass_height = vid.height;
4569                         r_shadow_prepassgeometrydepthbuffer = R_LoadTextureRenderBuffer(r_shadow_texturepool, "prepassgeometrydepthbuffer", vid.width, vid.height, TEXTYPE_DEPTHBUFFER24);
4570                         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);
4571                         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);
4572                         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);
4573
4574                         // set up the geometry pass fbo (depth + normalmap)
4575                         r_shadow_prepassgeometryfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthbuffer, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL);
4576                         R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL);
4577                         // render depth into a renderbuffer and other important properties into the normalmap texture
4578
4579                         // set up the lighting pass fbo (diffuse + specular)
4580                         r_shadow_prepasslightingdiffusespecularfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4581                         R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4582                         // render diffuse into one texture and specular into another,
4583                         // with depth and normalmap bound as textures,
4584                         // with depth bound as attachment as well
4585
4586                         // set up the lighting pass fbo (diffuse)
4587                         r_shadow_prepasslightingdiffusefbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
4588                         R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
4589                         // render diffuse into one texture,
4590                         // with depth and normalmap bound as textures,
4591                         // with depth bound as attachment as well
4592                 }
4593 #endif
4594                 break;
4595         case RENDERPATH_GL11:
4596         case RENDERPATH_GL13:
4597         case RENDERPATH_GLES1:
4598         case RENDERPATH_GLES2:
4599                 r_shadow_usingdeferredprepass = false;
4600                 break;
4601         }
4602
4603         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);
4604
4605         flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4606         if (r_shadow_debuglight.integer >= 0)
4607         {
4608                 lightindex = r_shadow_debuglight.integer;
4609                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4610                 if (light)
4611                         R_Shadow_PrepareLight(&light->rtlight);
4612         }
4613         else
4614         {
4615                 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4616                 for (lightindex = 0;lightindex < range;lightindex++)
4617                 {
4618                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4619                         if (light && (light->flags & flag))
4620                                 R_Shadow_PrepareLight(&light->rtlight);
4621                 }
4622         }
4623         if (r_refdef.scene.rtdlight)
4624         {
4625                 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4626                         R_Shadow_PrepareLight(r_refdef.scene.lights[lnum]);
4627         }
4628         else if(gl_flashblend.integer)
4629         {
4630                 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4631                 {
4632                         rtlight_t *rtlight = r_refdef.scene.lights[lnum];
4633                         f = ((rtlight->style >= 0 && rtlight->style < MAX_LIGHTSTYLES) ? r_refdef.scene.lightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value;
4634                         VectorScale(rtlight->color, f, rtlight->currentcolor);
4635                 }
4636         }
4637
4638         if (r_editlights.integer)
4639                 R_Shadow_DrawLightSprites();
4640 }
4641
4642 void R_Shadow_DrawLights(void)
4643 {
4644         int flag;
4645         int lnum;
4646         size_t lightindex;
4647         dlight_t *light;
4648         size_t range;
4649
4650         R_Shadow_RenderMode_Begin();
4651
4652         flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4653         if (r_shadow_debuglight.integer >= 0)
4654         {
4655                 lightindex = r_shadow_debuglight.integer;
4656                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4657                 if (light)
4658                         R_Shadow_DrawLight(&light->rtlight);
4659         }
4660         else
4661         {
4662                 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4663                 for (lightindex = 0;lightindex < range;lightindex++)
4664                 {
4665                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4666                         if (light && (light->flags & flag))
4667                                 R_Shadow_DrawLight(&light->rtlight);
4668                 }
4669         }
4670         if (r_refdef.scene.rtdlight)
4671                 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4672                         R_Shadow_DrawLight(r_refdef.scene.lights[lnum]);
4673
4674         R_Shadow_RenderMode_End();
4675 }
4676
4677 #define MAX_MODELSHADOWS 1024
4678 static int r_shadow_nummodelshadows;
4679 static entity_render_t *r_shadow_modelshadows[MAX_MODELSHADOWS];
4680
4681 void R_Shadow_PrepareModelShadows(void)
4682 {
4683         int i;
4684         float scale, size, radius, dot1, dot2;
4685         prvm_vec3_t prvmshadowdir, prvmshadowfocus;
4686         vec3_t shadowdir, shadowforward, shadowright, shadoworigin, shadowfocus, shadowmins, shadowmaxs;
4687         entity_render_t *ent;
4688
4689         r_shadow_nummodelshadows = 0;
4690         if (!r_refdef.scene.numentities)
4691                 return;
4692
4693         switch (r_shadow_shadowmode)
4694         {
4695         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4696                 if (r_shadows.integer >= 2) 
4697                         break;
4698                 // fall through
4699         case R_SHADOW_SHADOWMODE_STENCIL:
4700                 if (!vid.stencil)
4701                         return;
4702                 for (i = 0;i < r_refdef.scene.numentities;i++)
4703                 {
4704                         ent = r_refdef.scene.entities[i];
4705                         if (ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4706                         {
4707                                 if (r_shadow_nummodelshadows >= MAX_MODELSHADOWS)
4708                                         break;
4709                                 r_shadow_modelshadows[r_shadow_nummodelshadows++] = ent;
4710                                 R_AnimCache_GetEntity(ent, false, false);
4711                         }
4712                 }
4713                 return;
4714         default:
4715                 return;
4716         }
4717
4718         size = 2*r_shadow_shadowmapmaxsize;
4719         scale = r_shadow_shadowmapping_precision.value * r_shadows_shadowmapscale.value;
4720         radius = 0.5f * size / scale;
4721
4722         Math_atov(r_shadows_throwdirection.string, prvmshadowdir);
4723         VectorCopy(prvmshadowdir, shadowdir);
4724         VectorNormalize(shadowdir);
4725         dot1 = DotProduct(r_refdef.view.forward, shadowdir);
4726         dot2 = DotProduct(r_refdef.view.up, shadowdir);
4727         if (fabs(dot1) <= fabs(dot2))
4728                 VectorMA(r_refdef.view.forward, -dot1, shadowdir, shadowforward);
4729         else
4730                 VectorMA(r_refdef.view.up, -dot2, shadowdir, shadowforward);
4731         VectorNormalize(shadowforward);
4732         CrossProduct(shadowdir, shadowforward, shadowright);
4733         Math_atov(r_shadows_focus.string, prvmshadowfocus);
4734         VectorCopy(prvmshadowfocus, shadowfocus);
4735         VectorM(shadowfocus[0], r_refdef.view.right, shadoworigin);
4736         VectorMA(shadoworigin, shadowfocus[1], r_refdef.view.up, shadoworigin);
4737         VectorMA(shadoworigin, -shadowfocus[2], r_refdef.view.forward, shadoworigin);
4738         VectorAdd(shadoworigin, r_refdef.view.origin, shadoworigin);
4739         if (shadowfocus[0] || shadowfocus[1] || shadowfocus[2])
4740                 dot1 = 1;
4741         VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin);
4742
4743         shadowmins[0] = shadoworigin[0] - r_shadows_throwdistance.value * fabs(shadowdir[0]) - radius * (fabs(shadowforward[0]) + fabs(shadowright[0]));
4744         shadowmins[1] = shadoworigin[1] - r_shadows_throwdistance.value * fabs(shadowdir[1]) - radius * (fabs(shadowforward[1]) + fabs(shadowright[1]));
4745         shadowmins[2] = shadoworigin[2] - r_shadows_throwdistance.value * fabs(shadowdir[2]) - radius * (fabs(shadowforward[2]) + fabs(shadowright[2]));
4746         shadowmaxs[0] = shadoworigin[0] + r_shadows_throwdistance.value * fabs(shadowdir[0]) + radius * (fabs(shadowforward[0]) + fabs(shadowright[0]));
4747         shadowmaxs[1] = shadoworigin[1] + r_shadows_throwdistance.value * fabs(shadowdir[1]) + radius * (fabs(shadowforward[1]) + fabs(shadowright[1]));
4748         shadowmaxs[2] = shadoworigin[2] + r_shadows_throwdistance.value * fabs(shadowdir[2]) + radius * (fabs(shadowforward[2]) + fabs(shadowright[2]));
4749
4750         for (i = 0;i < r_refdef.scene.numentities;i++)
4751         {
4752                 ent = r_refdef.scene.entities[i];
4753                 if (!BoxesOverlap(ent->mins, ent->maxs, shadowmins, shadowmaxs))
4754                         continue;
4755                 // cast shadows from anything of the map (submodels are optional)
4756                 if (ent->model && ent->model->DrawShadowMap != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4757                 {
4758                         if (r_shadow_nummodelshadows >= MAX_MODELSHADOWS)
4759                                 break;
4760                         r_shadow_modelshadows[r_shadow_nummodelshadows++] = ent;
4761                         R_AnimCache_GetEntity(ent, false, false);
4762                 }
4763         }
4764 }
4765
4766 void R_DrawModelShadowMaps(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture)
4767 {
4768         int i;
4769         float relativethrowdistance, scale, size, radius, nearclip, farclip, bias, dot1, dot2;
4770         entity_render_t *ent;
4771         vec3_t relativelightorigin;
4772         vec3_t relativelightdirection, relativeforward, relativeright;
4773         vec3_t relativeshadowmins, relativeshadowmaxs;
4774         vec3_t shadowdir, shadowforward, shadowright, shadoworigin, shadowfocus;
4775         prvm_vec3_t prvmshadowdir, prvmshadowfocus;
4776         float m[12];
4777         matrix4x4_t shadowmatrix, cameramatrix, mvpmatrix, invmvpmatrix, scalematrix, texmatrix;
4778         r_viewport_t viewport;
4779         GLuint shadowfbo = 0;
4780         float clearcolor[4];
4781
4782         if (!r_shadow_nummodelshadows)
4783                 return;
4784
4785         switch (r_shadow_shadowmode)
4786         {
4787         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4788                 break;
4789         default:
4790                 return;
4791         }
4792
4793         r_shadow_fb_fbo = fbo;
4794         r_shadow_fb_depthtexture = depthtexture;
4795         r_shadow_fb_colortexture = colortexture;
4796
4797         R_ResetViewRendering3D(fbo, depthtexture, colortexture);
4798         R_Shadow_RenderMode_Begin();
4799         R_Shadow_RenderMode_ActiveLight(NULL);
4800
4801         switch (r_shadow_shadowmode)
4802         {
4803         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4804                 if (!r_shadow_shadowmap2ddepthtexture)
4805                         R_Shadow_MakeShadowMap(0, r_shadow_shadowmapmaxsize);
4806                 shadowfbo = r_shadow_fbo2d;
4807                 r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2ddepthtexture);
4808                 r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2ddepthtexture);
4809                 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
4810                 break;
4811         default:
4812                 break;
4813         }
4814
4815         size = 2*r_shadow_shadowmapmaxsize;
4816         scale = (r_shadow_shadowmapping_precision.value * r_shadows_shadowmapscale.value) / size;
4817         radius = 0.5f / scale;
4818         nearclip = -r_shadows_throwdistance.value;
4819         farclip = r_shadows_throwdistance.value;
4820         bias = (r_shadows_shadowmapbias.value < 0) ? r_shadow_shadowmapping_bias.value : r_shadows_shadowmapbias.value * r_shadow_shadowmapping_nearclip.value / (2 * r_shadows_throwdistance.value) * (1024.0f / size);
4821
4822         r_shadow_shadowmap_parameters[0] = size;
4823         r_shadow_shadowmap_parameters[1] = size;
4824         r_shadow_shadowmap_parameters[2] = 1.0;
4825         r_shadow_shadowmap_parameters[3] = bound(0.0f, 1.0f - r_shadows_darken.value, 1.0f);
4826
4827         Math_atov(r_shadows_throwdirection.string, prvmshadowdir);
4828         VectorCopy(prvmshadowdir, shadowdir);
4829         VectorNormalize(shadowdir);
4830         Math_atov(r_shadows_focus.string, prvmshadowfocus);
4831         VectorCopy(prvmshadowfocus, shadowfocus);
4832         VectorM(shadowfocus[0], r_refdef.view.right, shadoworigin);
4833         VectorMA(shadoworigin, shadowfocus[1], r_refdef.view.up, shadoworigin);
4834         VectorMA(shadoworigin, -shadowfocus[2], r_refdef.view.forward, shadoworigin);
4835         VectorAdd(shadoworigin, r_refdef.view.origin, shadoworigin);
4836         dot1 = DotProduct(r_refdef.view.forward, shadowdir);
4837         dot2 = DotProduct(r_refdef.view.up, shadowdir);
4838         if (fabs(dot1) <= fabs(dot2)) 
4839                 VectorMA(r_refdef.view.forward, -dot1, shadowdir, shadowforward);
4840         else
4841                 VectorMA(r_refdef.view.up, -dot2, shadowdir, shadowforward);
4842         VectorNormalize(shadowforward);
4843         VectorM(scale, shadowforward, &m[0]);
4844         if (shadowfocus[0] || shadowfocus[1] || shadowfocus[2])
4845                 dot1 = 1;
4846         m[3] = fabs(dot1) * 0.5f - DotProduct(shadoworigin, &m[0]);
4847         CrossProduct(shadowdir, shadowforward, shadowright);
4848         VectorM(scale, shadowright, &m[4]);
4849         m[7] = 0.5f - DotProduct(shadoworigin, &m[4]);
4850         VectorM(1.0f / (farclip - nearclip), shadowdir, &m[8]);
4851         m[11] = 0.5f - DotProduct(shadoworigin, &m[8]);
4852         Matrix4x4_FromArray12FloatD3D(&shadowmatrix, m);
4853         Matrix4x4_Invert_Full(&cameramatrix, &shadowmatrix);
4854         R_Viewport_InitOrtho(&viewport, &cameramatrix, 0, 0, size, size, 0, 0, 1, 1, 0, -1, NULL); 
4855
4856         VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin);
4857
4858         if (r_shadow_shadowmap2ddepthbuffer)
4859                 R_Mesh_SetRenderTargets(shadowfbo, r_shadow_shadowmap2ddepthbuffer, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL);
4860         else
4861                 R_Mesh_SetRenderTargets(shadowfbo, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL, NULL);
4862         R_SetupShader_DepthOrShadow(true, r_shadow_shadowmap2ddepthbuffer != NULL, false); // FIXME test if we have a skeletal model?
4863         GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
4864         GL_DepthMask(true);
4865         GL_DepthTest(true);
4866         R_SetViewport(&viewport);
4867         GL_Scissor(viewport.x, viewport.y, min(viewport.width + r_shadow_shadowmapborder, 2*r_shadow_shadowmapmaxsize), viewport.height + r_shadow_shadowmapborder);
4868         Vector4Set(clearcolor, 1,1,1,1);
4869         // in D3D9 we have to render to a color texture shadowmap
4870         // in GL we render directly to a depth texture only
4871         if (r_shadow_shadowmap2ddepthbuffer)
4872                 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4873         else
4874                 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4875         // render into a slightly restricted region so that the borders of the
4876         // shadowmap area fade away, rather than streaking across everything
4877         // outside the usable area
4878         GL_Scissor(viewport.x + r_shadow_shadowmapborder, viewport.y + r_shadow_shadowmapborder, viewport.width - 2*r_shadow_shadowmapborder, viewport.height - 2*r_shadow_shadowmapborder);
4879
4880         for (i = 0;i < r_shadow_nummodelshadows;i++)
4881         {
4882                 ent = r_shadow_modelshadows[i];
4883                 relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix);
4884                 Matrix4x4_Transform(&ent->inversematrix, shadoworigin, relativelightorigin);
4885                 Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection);
4886                 Matrix4x4_Transform3x3(&ent->inversematrix, shadowforward, relativeforward);
4887                 Matrix4x4_Transform3x3(&ent->inversematrix, shadowright, relativeright);
4888                 relativeshadowmins[0] = relativelightorigin[0] - r_shadows_throwdistance.value * fabs(relativelightdirection[0]) - radius * (fabs(relativeforward[0]) + fabs(relativeright[0]));
4889                 relativeshadowmins[1] = relativelightorigin[1] - r_shadows_throwdistance.value * fabs(relativelightdirection[1]) - radius * (fabs(relativeforward[1]) + fabs(relativeright[1]));
4890                 relativeshadowmins[2] = relativelightorigin[2] - r_shadows_throwdistance.value * fabs(relativelightdirection[2]) - radius * (fabs(relativeforward[2]) + fabs(relativeright[2]));
4891                 relativeshadowmaxs[0] = relativelightorigin[0] + r_shadows_throwdistance.value * fabs(relativelightdirection[0]) + radius * (fabs(relativeforward[0]) + fabs(relativeright[0]));
4892                 relativeshadowmaxs[1] = relativelightorigin[1] + r_shadows_throwdistance.value * fabs(relativelightdirection[1]) + radius * (fabs(relativeforward[1]) + fabs(relativeright[1]));
4893                 relativeshadowmaxs[2] = relativelightorigin[2] + r_shadows_throwdistance.value * fabs(relativelightdirection[2]) + radius * (fabs(relativeforward[2]) + fabs(relativeright[2]));
4894                 RSurf_ActiveModelEntity(ent, false, false, false);
4895                 ent->model->DrawShadowMap(0, ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, NULL, relativeshadowmins, relativeshadowmaxs);
4896                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
4897         }
4898
4899 #if 0
4900         if (r_test.integer)
4901         {
4902                 unsigned char *rawpixels = Z_Malloc(viewport.width*viewport.height*4);
4903                 CHECKGLERROR
4904                 qglReadPixels(viewport.x, viewport.y, viewport.width, viewport.height, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, rawpixels);
4905                 CHECKGLERROR
4906                 Image_WriteTGABGRA("r_shadows_2.tga", viewport.width, viewport.height, rawpixels);
4907                 Cvar_SetValueQuick(&r_test, 0);
4908                 Z_Free(rawpixels);
4909         }
4910 #endif
4911
4912         R_Shadow_RenderMode_End();
4913
4914         Matrix4x4_Concat(&mvpmatrix, &r_refdef.view.viewport.projectmatrix, &r_refdef.view.viewport.viewmatrix);
4915         Matrix4x4_Invert_Full(&invmvpmatrix, &mvpmatrix);
4916         Matrix4x4_CreateScale3(&scalematrix, size, -size, 1); 
4917         Matrix4x4_AdjustOrigin(&scalematrix, 0, size, -0.5f * bias);
4918         Matrix4x4_Concat(&texmatrix, &scalematrix, &shadowmatrix);
4919         Matrix4x4_Concat(&r_shadow_shadowmapmatrix, &texmatrix, &invmvpmatrix);
4920
4921         switch (vid.renderpath)
4922         {
4923         case RENDERPATH_GL11:
4924         case RENDERPATH_GL13:
4925         case RENDERPATH_GL20:
4926         case RENDERPATH_SOFT:
4927         case RENDERPATH_GLES1:
4928         case RENDERPATH_GLES2:
4929                 break;
4930         case RENDERPATH_D3D9:
4931         case RENDERPATH_D3D10:
4932         case RENDERPATH_D3D11:
4933 #ifdef MATRIX4x4_OPENGLORIENTATION
4934                 r_shadow_shadowmapmatrix.m[0][0]        *= -1.0f;
4935                 r_shadow_shadowmapmatrix.m[0][1]        *= -1.0f;
4936                 r_shadow_shadowmapmatrix.m[0][2]        *= -1.0f;
4937                 r_shadow_shadowmapmatrix.m[0][3]        *= -1.0f;
4938 #else
4939                 r_shadow_shadowmapmatrix.m[0][0]        *= -1.0f;
4940                 r_shadow_shadowmapmatrix.m[1][0]        *= -1.0f;
4941                 r_shadow_shadowmapmatrix.m[2][0]        *= -1.0f;
4942                 r_shadow_shadowmapmatrix.m[3][0]        *= -1.0f;
4943 #endif
4944                 break;
4945         }
4946
4947         r_shadow_usingshadowmaportho = true;
4948         switch (r_shadow_shadowmode)
4949         {
4950         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4951                 r_shadow_usingshadowmap2d = true;
4952                 break;
4953         default:
4954                 break;
4955         }
4956 }
4957
4958 void R_DrawModelShadows(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture)
4959 {
4960         int i;
4961         float relativethrowdistance;
4962         entity_render_t *ent;
4963         vec3_t relativelightorigin;
4964         vec3_t relativelightdirection;
4965         vec3_t relativeshadowmins, relativeshadowmaxs;
4966         vec3_t tmp, shadowdir;
4967         prvm_vec3_t prvmshadowdir;
4968
4969         if (!r_shadow_nummodelshadows || (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL && r_shadows.integer != 1))
4970                 return;
4971
4972         r_shadow_fb_fbo = fbo;
4973         r_shadow_fb_depthtexture = depthtexture;
4974         r_shadow_fb_colortexture = colortexture;
4975
4976         R_ResetViewRendering3D(fbo, depthtexture, colortexture);
4977         //GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
4978         //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
4979         R_Shadow_RenderMode_Begin();
4980         R_Shadow_RenderMode_ActiveLight(NULL);
4981         r_shadow_lightscissor[0] = r_refdef.view.x;
4982         r_shadow_lightscissor[1] = vid.height - r_refdef.view.y - r_refdef.view.height;
4983         r_shadow_lightscissor[2] = r_refdef.view.width;
4984         r_shadow_lightscissor[3] = r_refdef.view.height;
4985         R_Shadow_RenderMode_StencilShadowVolumes(false);
4986
4987         // get shadow dir
4988         if (r_shadows.integer == 2)
4989         {
4990                 Math_atov(r_shadows_throwdirection.string, prvmshadowdir);
4991                 VectorCopy(prvmshadowdir, shadowdir);
4992                 VectorNormalize(shadowdir);
4993         }
4994
4995         R_Shadow_ClearStencil();
4996
4997         for (i = 0;i < r_shadow_nummodelshadows;i++)
4998         {
4999                 ent = r_shadow_modelshadows[i];
5000
5001                 // cast shadows from anything of the map (submodels are optional)
5002                 relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix);
5003                 VectorSet(relativeshadowmins, -relativethrowdistance, -relativethrowdistance, -relativethrowdistance);
5004                 VectorSet(relativeshadowmaxs, relativethrowdistance, relativethrowdistance, relativethrowdistance);
5005                 if (r_shadows.integer == 2) // 2: simpler mode, throw shadows always in same direction
5006                         Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection);
5007                 else
5008                 {
5009                         if(ent->entitynumber != 0)
5010                         {
5011                                 if(ent->entitynumber >= MAX_EDICTS) // csqc entity
5012                                 {
5013                                         // FIXME handle this
5014                                         VectorNegate(ent->modellight_lightdir, relativelightdirection);
5015                                 }
5016                                 else
5017                                 {
5018                                         // networked entity - might be attached in some way (then we should use the parent's light direction, to not tear apart attached entities)
5019                                         int entnum, entnum2, recursion;
5020                                         entnum = entnum2 = ent->entitynumber;
5021                                         for(recursion = 32; recursion > 0; --recursion)
5022                                         {
5023                                                 entnum2 = cl.entities[entnum].state_current.tagentity;
5024                                                 if(entnum2 >= 1 && entnum2 < cl.num_entities && cl.entities_active[entnum2])
5025                                                         entnum = entnum2;
5026                                                 else
5027                                                         break;
5028                                         }
5029                                         if(recursion && recursion != 32) // if we followed a valid non-empty attachment chain
5030                                         {
5031                                                 VectorNegate(cl.entities[entnum].render.modellight_lightdir, relativelightdirection);
5032                                                 // transform into modelspace of OUR entity
5033                                                 Matrix4x4_Transform3x3(&cl.entities[entnum].render.matrix, relativelightdirection, tmp);
5034                                                 Matrix4x4_Transform3x3(&ent->inversematrix, tmp, relativelightdirection);
5035                                         }
5036                                         else
5037                                                 VectorNegate(ent->modellight_lightdir, relativelightdirection);
5038                                 }
5039                         }
5040                         else
5041                                 VectorNegate(ent->modellight_lightdir, relativelightdirection);
5042                 }
5043
5044                 VectorScale(relativelightdirection, -relativethrowdistance, relativelightorigin);
5045                 RSurf_ActiveModelEntity(ent, false, false, false);
5046                 ent->model->DrawShadowVolume(ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
5047                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
5048         }
5049
5050         // not really the right mode, but this will disable any silly stencil features
5051         R_Shadow_RenderMode_End();
5052
5053         // set up ortho view for rendering this pass
5054         //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
5055         //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5056         //GL_ScissorTest(true);
5057         //R_EntityMatrix(&identitymatrix);
5058         //R_Mesh_ResetTextureState();
5059         R_ResetViewRendering2D(fbo, depthtexture, colortexture);
5060
5061         // set up a darkening blend on shadowed areas
5062         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
5063         //GL_DepthRange(0, 1);
5064         //GL_DepthTest(false);
5065         //GL_DepthMask(false);
5066         //GL_PolygonOffset(0, 0);CHECKGLERROR
5067         GL_Color(0, 0, 0, r_shadows_darken.value);
5068         //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5069         //GL_DepthFunc(GL_ALWAYS);
5070         R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_NOTEQUAL, 128, 255);
5071
5072         // apply the blend to the shadowed areas
5073         R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
5074         R_SetupShader_Generic_NoTexture(false, true);
5075         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5076
5077         // restore the viewport
5078         R_SetViewport(&r_refdef.view.viewport);
5079
5080         // restore other state to normal
5081         //R_Shadow_RenderMode_End();
5082 }
5083
5084 static void R_BeginCoronaQuery(rtlight_t *rtlight, float scale, qboolean usequery)
5085 {
5086         float zdist;
5087         vec3_t centerorigin;
5088 #if defined(GL_SAMPLES_PASSED_ARB) && !defined(USE_GLES2)
5089         float vertex3f[12];
5090 #endif
5091         // if it's too close, skip it
5092         if (VectorLength(rtlight->currentcolor) < (1.0f / 256.0f))
5093                 return;
5094         zdist = (DotProduct(rtlight->shadoworigin, r_refdef.view.forward) - DotProduct(r_refdef.view.origin, r_refdef.view.forward));
5095         if (zdist < 32)
5096                 return;
5097         if (usequery && r_numqueries + 2 <= r_maxqueries)
5098         {
5099                 rtlight->corona_queryindex_allpixels = r_queries[r_numqueries++];
5100                 rtlight->corona_queryindex_visiblepixels = r_queries[r_numqueries++];
5101                 // 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
5102                 VectorMA(r_refdef.view.origin, zdist, r_refdef.view.forward, centerorigin);
5103
5104                 switch(vid.renderpath)
5105                 {
5106                 case RENDERPATH_GL11:
5107                 case RENDERPATH_GL13:
5108                 case RENDERPATH_GL20:
5109                 case RENDERPATH_GLES1:
5110                 case RENDERPATH_GLES2:
5111 #if defined(GL_SAMPLES_PASSED_ARB) && !defined(USE_GLES2)
5112                         CHECKGLERROR
5113                         // NOTE: GL_DEPTH_TEST must be enabled or ATI won't count samples, so use GL_DepthFunc instead
5114                         qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_allpixels);
5115                         GL_DepthFunc(GL_ALWAYS);
5116                         R_CalcSprite_Vertex3f(vertex3f, centerorigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5117                         R_Mesh_PrepareVertices_Vertex3f(4, vertex3f, NULL, 0);
5118                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5119                         qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
5120                         GL_DepthFunc(GL_LEQUAL);
5121                         qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_visiblepixels);
5122                         R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5123                         R_Mesh_PrepareVertices_Vertex3f(4, vertex3f, NULL, 0);
5124                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5125                         qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
5126                         CHECKGLERROR
5127 #endif
5128                         break;
5129                 case RENDERPATH_D3D9:
5130                         Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5131                         break;
5132                 case RENDERPATH_D3D10:
5133                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5134                         break;
5135                 case RENDERPATH_D3D11:
5136                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5137                         break;
5138                 case RENDERPATH_SOFT:
5139                         //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5140                         break;
5141                 }
5142         }
5143         rtlight->corona_visibility = bound(0, (zdist - 32) / 32, 1);
5144 }
5145
5146 static float spritetexcoord2f[4*2] = {0, 1, 0, 0, 1, 0, 1, 1};
5147
5148 static void R_DrawCorona(rtlight_t *rtlight, float cscale, float scale)
5149 {
5150         vec3_t color;
5151         unsigned int occlude = 0;
5152         GLint allpixels = 0, visiblepixels = 0;
5153
5154         // now we have to check the query result
5155         if (rtlight->corona_queryindex_visiblepixels)
5156         {
5157                 switch(vid.renderpath)
5158                 {
5159                 case RENDERPATH_GL11:
5160                 case RENDERPATH_GL13:
5161                 case RENDERPATH_GL20:
5162                 case RENDERPATH_GLES1:
5163                 case RENDERPATH_GLES2:
5164 #if defined(GL_SAMPLES_PASSED_ARB) && !defined(USE_GLES2)
5165                         CHECKGLERROR
5166                         // See if we can use the GPU-side method to prevent implicit sync
5167                         if (vid.support.arb_query_buffer_object) {
5168 #define BUFFER_OFFSET(i)    ((void*)NULL + (i))
5169                                 qglGenBuffersARB(1, &rtlight->occlusion_buf);
5170                                 qglBindBufferARB(GL_QUERY_BUFFER_ARB, rtlight->occlusion_buf);
5171                                 qglBufferDataARB(GL_QUERY_BUFFER_ARB, 8, NULL, GL_DYNAMIC_COPY);
5172                                 qglGetQueryObjectivARB(rtlight->corona_queryindex_visiblepixels, GL_QUERY_RESULT_ARB, BUFFER_OFFSET(0));
5173                                 qglGetQueryObjectivARB(rtlight->corona_queryindex_allpixels, GL_QUERY_RESULT_ARB, BUFFER_OFFSET(4));
5174                                 qglBindBufferBase(GL_UNIFORM_BUFFER, 0, rtlight->occlusion_buf);
5175                                 occlude = MATERIALFLAG_OCCLUDE;
5176                         } else {
5177                                 qglGetQueryObjectivARB(rtlight->corona_queryindex_visiblepixels, GL_QUERY_RESULT_ARB, &visiblepixels);
5178                                 qglGetQueryObjectivARB(rtlight->corona_queryindex_allpixels, GL_QUERY_RESULT_ARB, &allpixels); 
5179                                 if (visiblepixels < 1 || allpixels < 1)
5180                                         return;
5181                                 rtlight->corona_visibility *= bound(0, (float)visiblepixels / (float)allpixels, 1);
5182                         }
5183                         cscale *= rtlight->corona_visibility;
5184                         CHECKGLERROR
5185                         break;
5186 #else
5187                         return;
5188 #endif
5189                 case RENDERPATH_D3D9:
5190                         Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5191                         return;
5192                 case RENDERPATH_D3D10:
5193                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5194                         return;
5195                 case RENDERPATH_D3D11:
5196                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5197                         return;
5198                 case RENDERPATH_SOFT:
5199                         //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5200                         return;
5201                 default:
5202                         return;
5203                 }
5204         }
5205         else
5206         {
5207                 // FIXME: these traces should scan all render entities instead of cl.world
5208                 if (CL_TraceLine(r_refdef.view.origin, rtlight->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, collision_extendmovelength.value, true, false, NULL, false, true).fraction < 1)
5209                         return;
5210         }
5211         VectorScale(rtlight->currentcolor, cscale, color);
5212         if (VectorLength(color) > (1.0f / 256.0f))
5213         {
5214                 float vertex3f[12];
5215                 qboolean negated = (color[0] + color[1] + color[2] < 0) && vid.support.ext_blend_subtract;
5216                 if(negated)
5217                 {
5218                         VectorNegate(color, color);
5219                         GL_BlendEquationSubtract(true);
5220                 }
5221                 R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5222                 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);
5223                 R_DrawCustomSurface(r_shadow_lightcorona, &identitymatrix, MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE | MATERIALFLAG_NODEPTHTEST | occlude, 0, 4, 0, 2, false, false);
5224                 if(negated)
5225                         GL_BlendEquationSubtract(false);
5226         }
5227         if (rtlight->occlusion_buf) {
5228                 qglDeleteBuffersARB(1, &rtlight->occlusion_buf);
5229         }
5230 }
5231
5232 void R_Shadow_DrawCoronas(void)
5233 {
5234         int i, flag;
5235         qboolean usequery = false;
5236         size_t lightindex;
5237         dlight_t *light;
5238         rtlight_t *rtlight;
5239         size_t range;
5240         if (r_coronas.value < (1.0f / 256.0f) && !gl_flashblend.integer)
5241                 return;
5242         if (r_fb.water.renderingscene)
5243                 return;
5244         flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
5245         R_EntityMatrix(&identitymatrix);
5246
5247         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5248
5249         // check occlusion of coronas
5250         // use GL_ARB_occlusion_query if available
5251         // otherwise use raytraces
5252         r_numqueries = 0;
5253         switch (vid.renderpath)
5254         {
5255         case RENDERPATH_GL11:
5256         case RENDERPATH_GL13:
5257         case RENDERPATH_GL20:
5258         case RENDERPATH_GLES1:
5259         case RENDERPATH_GLES2:
5260                 usequery = vid.support.arb_occlusion_query && r_coronas_occlusionquery.integer;
5261 #if defined(GL_SAMPLES_PASSED_ARB) && !defined(USE_GLES2)
5262                 if (usequery)
5263                 {
5264                         GL_ColorMask(0,0,0,0);
5265                         if (r_maxqueries < ((unsigned int)range + r_refdef.scene.numlights) * 2)
5266                         if (r_maxqueries < MAX_OCCLUSION_QUERIES)
5267                         {
5268                                 i = r_maxqueries;
5269                                 r_maxqueries = ((unsigned int)range + r_refdef.scene.numlights) * 4;
5270                                 r_maxqueries = min(r_maxqueries, MAX_OCCLUSION_QUERIES);
5271                                 CHECKGLERROR
5272                                 qglGenQueriesARB(r_maxqueries - i, r_queries + i);
5273                                 CHECKGLERROR
5274                         }
5275                         RSurf_ActiveWorldEntity();
5276                         GL_BlendFunc(GL_ONE, GL_ZERO);
5277                         GL_CullFace(GL_NONE);
5278                         GL_DepthMask(false);
5279                         GL_DepthRange(0, 1);
5280                         GL_PolygonOffset(0, 0);
5281                         GL_DepthTest(true);
5282                         R_Mesh_ResetTextureState();
5283                         R_SetupShader_Generic_NoTexture(false, false);
5284                 }
5285 #endif
5286                 break;
5287         case RENDERPATH_D3D9:
5288                 usequery = false;
5289                 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5290                 break;
5291         case RENDERPATH_D3D10:
5292                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5293                 break;
5294         case RENDERPATH_D3D11:
5295                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5296                 break;
5297         case RENDERPATH_SOFT:
5298                 usequery = false;
5299                 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5300                 break;
5301         }
5302         for (lightindex = 0;lightindex < range;lightindex++)
5303         {
5304                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5305                 if (!light)
5306                         continue;
5307                 rtlight = &light->rtlight;
5308                 rtlight->corona_visibility = 0;
5309                 rtlight->corona_queryindex_visiblepixels = 0;
5310                 rtlight->corona_queryindex_allpixels = 0;
5311                 if (!(rtlight->flags & flag))
5312                         continue;
5313                 if (rtlight->corona <= 0)
5314                         continue;
5315                 if (r_shadow_debuglight.integer >= 0 && r_shadow_debuglight.integer != (int)lightindex)
5316                         continue;
5317                 R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
5318         }
5319         for (i = 0;i < r_refdef.scene.numlights;i++)
5320         {
5321                 rtlight = r_refdef.scene.lights[i];
5322                 rtlight->corona_visibility = 0;
5323                 rtlight->corona_queryindex_visiblepixels = 0;
5324                 rtlight->corona_queryindex_allpixels = 0;
5325                 if (!(rtlight->flags & flag))
5326                         continue;
5327                 if (rtlight->corona <= 0)
5328                         continue;
5329                 R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
5330         }
5331         if (usequery)
5332                 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5333
5334         // now draw the coronas using the query data for intensity info
5335         for (lightindex = 0;lightindex < range;lightindex++)
5336         {
5337                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5338                 if (!light)
5339                         continue;
5340                 rtlight = &light->rtlight;
5341                 if (rtlight->corona_visibility <= 0)
5342                         continue;
5343                 R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
5344         }
5345         for (i = 0;i < r_refdef.scene.numlights;i++)
5346         {
5347                 rtlight = r_refdef.scene.lights[i];
5348                 if (rtlight->corona_visibility <= 0)
5349                         continue;
5350                 if (gl_flashblend.integer)
5351                         R_DrawCorona(rtlight, rtlight->corona, rtlight->radius * rtlight->coronasizescale * 2.0f);
5352                 else
5353                         R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
5354         }
5355 }
5356
5357
5358
5359 static dlight_t *R_Shadow_NewWorldLight(void)
5360 {
5361         return (dlight_t *)Mem_ExpandableArray_AllocRecord(&r_shadow_worldlightsarray);
5362 }
5363
5364 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)
5365 {
5366         matrix4x4_t matrix;
5367
5368         // note that style is no longer validated here, -1 is used for unstyled lights and >= MAX_LIGHTSTYLES is accepted for sake of editing rtlights files that might be out of bounds but perfectly formatted
5369
5370         // validate parameters
5371         if (!cubemapname)
5372                 cubemapname = "";
5373
5374         // copy to light properties
5375         VectorCopy(origin, light->origin);
5376         light->angles[0] = angles[0] - 360 * floor(angles[0] / 360);
5377         light->angles[1] = angles[1] - 360 * floor(angles[1] / 360);
5378         light->angles[2] = angles[2] - 360 * floor(angles[2] / 360);
5379         /*
5380         light->color[0] = max(color[0], 0);
5381         light->color[1] = max(color[1], 0);
5382         light->color[2] = max(color[2], 0);
5383         */
5384         light->color[0] = color[0];
5385         light->color[1] = color[1];
5386         light->color[2] = color[2];
5387         light->radius = max(radius, 0);
5388         light->style = style;
5389         light->shadow = shadowenable;
5390         light->corona = corona;
5391         strlcpy(light->cubemapname, cubemapname, sizeof(light->cubemapname));
5392         light->coronasizescale = coronasizescale;
5393         light->ambientscale = ambientscale;
5394         light->diffusescale = diffusescale;
5395         light->specularscale = specularscale;
5396         light->flags = flags;
5397
5398         // update renderable light data
5399         Matrix4x4_CreateFromQuakeEntity(&matrix, light->origin[0], light->origin[1], light->origin[2], light->angles[0], light->angles[1], light->angles[2], light->radius);
5400         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);
5401 }
5402
5403 static void R_Shadow_FreeWorldLight(dlight_t *light)
5404 {
5405         if (r_shadow_selectedlight == light)
5406                 r_shadow_selectedlight = NULL;
5407         R_RTLight_Uncompile(&light->rtlight);
5408         Mem_ExpandableArray_FreeRecord(&r_shadow_worldlightsarray, light);
5409 }
5410
5411 void R_Shadow_ClearWorldLights(void)
5412 {
5413         size_t lightindex;
5414         dlight_t *light;
5415         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5416         for (lightindex = 0;lightindex < range;lightindex++)
5417         {
5418                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5419                 if (light)
5420                         R_Shadow_FreeWorldLight(light);
5421         }
5422         r_shadow_selectedlight = NULL;
5423 }
5424
5425 static void R_Shadow_SelectLight(dlight_t *light)
5426 {
5427         if (r_shadow_selectedlight)
5428                 r_shadow_selectedlight->selected = false;
5429         r_shadow_selectedlight = light;
5430         if (r_shadow_selectedlight)
5431                 r_shadow_selectedlight->selected = true;
5432 }
5433
5434 static void R_Shadow_DrawCursor_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
5435 {
5436         // this is never batched (there can be only one)
5437         float vertex3f[12];
5438         R_CalcSprite_Vertex3f(vertex3f, r_editlights_cursorlocation, r_refdef.view.right, r_refdef.view.up, EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, EDLIGHTSPRSIZE);
5439         RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, 1, 1, 1, 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5440         R_DrawCustomSurface(r_editlights_sprcursor, &identitymatrix, MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5441 }
5442
5443 static void R_Shadow_DrawLightSprite_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
5444 {
5445         float intensity;
5446         float s;
5447         vec3_t spritecolor;
5448         skinframe_t *skinframe;
5449         float vertex3f[12];
5450
5451         // this is never batched (due to the ent parameter changing every time)
5452         // so numsurfaces == 1 and surfacelist[0] == lightnumber
5453         const dlight_t *light = (dlight_t *)ent;
5454         s = EDLIGHTSPRSIZE;
5455
5456         R_CalcSprite_Vertex3f(vertex3f, light->origin, r_refdef.view.right, r_refdef.view.up, s, -s, -s, s);
5457
5458         intensity = 0.5f;
5459         VectorScale(light->color, intensity, spritecolor);
5460         if (VectorLength(spritecolor) < 0.1732f)
5461                 VectorSet(spritecolor, 0.1f, 0.1f, 0.1f);
5462         if (VectorLength(spritecolor) > 1.0f)
5463                 VectorNormalize(spritecolor);
5464
5465         // draw light sprite
5466         if (light->cubemapname[0] && !light->shadow)
5467                 skinframe = r_editlights_sprcubemapnoshadowlight;
5468         else if (light->cubemapname[0])
5469                 skinframe = r_editlights_sprcubemaplight;
5470         else if (!light->shadow)
5471                 skinframe = r_editlights_sprnoshadowlight;
5472         else
5473                 skinframe = r_editlights_sprlight;
5474
5475         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);
5476         R_DrawCustomSurface(skinframe, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5477
5478         // draw selection sprite if light is selected
5479         if (light->selected)
5480         {
5481                 RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, 1, 1, 1, 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5482                 R_DrawCustomSurface(r_editlights_sprselection, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5483                 // VorteX todo: add normalmode/realtime mode light overlay sprites?
5484         }
5485 }
5486
5487 void R_Shadow_DrawLightSprites(void)
5488 {
5489         size_t lightindex;
5490         dlight_t *light;
5491         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5492         for (lightindex = 0;lightindex < range;lightindex++)
5493         {
5494                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5495                 if (light)
5496                         R_MeshQueue_AddTransparent(TRANSPARENTSORT_DISTANCE, light->origin, R_Shadow_DrawLightSprite_TransparentCallback, (entity_render_t *)light, 5, &light->rtlight);
5497         }
5498         if (!r_editlights_lockcursor)
5499                 R_MeshQueue_AddTransparent(TRANSPARENTSORT_DISTANCE, r_editlights_cursorlocation, R_Shadow_DrawCursor_TransparentCallback, NULL, 0, NULL);
5500 }
5501
5502 int R_Shadow_GetRTLightInfo(unsigned int lightindex, float *origin, float *radius, float *color)
5503 {
5504         unsigned int range;
5505         dlight_t *light;
5506         rtlight_t *rtlight;
5507         range = (unsigned int)Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
5508         if (lightindex >= range)
5509                 return -1;
5510         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5511         if (!light)
5512                 return 0;
5513         rtlight = &light->rtlight;
5514         //if (!(rtlight->flags & flag))
5515         //      return 0;
5516         VectorCopy(rtlight->shadoworigin, origin);
5517         *radius = rtlight->radius;
5518         VectorCopy(rtlight->color, color);
5519         return 1;
5520 }
5521
5522 static void R_Shadow_SelectLightInView(void)
5523 {
5524         float bestrating, rating, temp[3];
5525         dlight_t *best;
5526         size_t lightindex;
5527         dlight_t *light;
5528         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5529         best = NULL;
5530         bestrating = 0;
5531
5532         if (r_editlights_lockcursor)
5533                 return;
5534         for (lightindex = 0;lightindex < range;lightindex++)
5535         {
5536                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5537                 if (!light)
5538                         continue;
5539                 VectorSubtract(light->origin, r_refdef.view.origin, temp);
5540                 rating = (DotProduct(temp, r_refdef.view.forward) / sqrt(DotProduct(temp, temp)));
5541                 if (rating >= 0.95)
5542                 {
5543                         rating /= (1 + 0.0625f * sqrt(DotProduct(temp, temp)));
5544                         if (bestrating < rating && CL_TraceLine(light->origin, r_refdef.view.origin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, collision_extendmovelength.value, true, false, NULL, false, true).fraction == 1.0f)
5545                         {
5546                                 bestrating = rating;
5547                                 best = light;
5548                         }
5549                 }
5550         }
5551         R_Shadow_SelectLight(best);
5552 }
5553
5554 void R_Shadow_LoadWorldLights(void)
5555 {
5556         int n, a, style, shadow, flags;
5557         char tempchar, *lightsstring, *s, *t, name[MAX_QPATH], cubemapname[MAX_QPATH];
5558         float origin[3], radius, color[3], angles[3], corona, coronasizescale, ambientscale, diffusescale, specularscale;
5559         if (cl.worldmodel == NULL)
5560         {
5561                 Con_Print("No map loaded.\n");
5562                 return;
5563         }
5564         dpsnprintf(name, sizeof(name), "%s.rtlights", cl.worldnamenoextension);
5565         lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
5566         if (lightsstring)
5567         {
5568                 s = lightsstring;
5569                 n = 0;
5570                 while (*s)
5571                 {
5572                         /*
5573                         t = s;
5574                         shadow = true;
5575                         for (;COM_Parse(t, true) && strcmp(
5576                         if (COM_Parse(t, true))
5577                         {
5578                                 if (com_token[0] == '!')
5579                                 {
5580                                         shadow = false;
5581                                         origin[0] = atof(com_token+1);
5582                                 }
5583                                 else
5584                                         origin[0] = atof(com_token);
5585                                 if (Com_Parse(t
5586                         }
5587                         */
5588                         t = s;
5589                         while (*s && *s != '\n' && *s != '\r')
5590                                 s++;
5591                         if (!*s)
5592                                 break;
5593                         tempchar = *s;
5594                         shadow = true;
5595                         // check for modifier flags
5596                         if (*t == '!')
5597                         {
5598                                 shadow = false;
5599                                 t++;
5600                         }
5601                         *s = 0;
5602 #if _MSC_VER >= 1400
5603 #define sscanf sscanf_s
5604 #endif
5605                         cubemapname[sizeof(cubemapname)-1] = 0;
5606 #if MAX_QPATH != 128
5607 #error update this code if MAX_QPATH changes
5608 #endif
5609                         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
5610 #if _MSC_VER >= 1400
5611 , sizeof(cubemapname)
5612 #endif
5613 , &corona, &angles[0], &angles[1], &angles[2], &coronasizescale, &ambientscale, &diffusescale, &specularscale, &flags);
5614                         *s = tempchar;
5615                         if (a < 18)
5616                                 flags = LIGHTFLAG_REALTIMEMODE;
5617                         if (a < 17)
5618                                 specularscale = 1;
5619                         if (a < 16)
5620                                 diffusescale = 1;
5621                         if (a < 15)
5622                                 ambientscale = 0;
5623                         if (a < 14)
5624                                 coronasizescale = 0.25f;
5625                         if (a < 13)
5626                                 VectorClear(angles);
5627                         if (a < 10)
5628                                 corona = 0;
5629                         if (a < 9 || !strcmp(cubemapname, "\"\""))
5630                                 cubemapname[0] = 0;
5631                         // remove quotes on cubemapname
5632                         if (cubemapname[0] == '"' && cubemapname[strlen(cubemapname) - 1] == '"')
5633                         {
5634                                 size_t namelen;
5635                                 namelen = strlen(cubemapname) - 2;
5636                                 memmove(cubemapname, cubemapname + 1, namelen);
5637                                 cubemapname[namelen] = '\0';
5638                         }
5639                         if (a < 8)
5640                         {
5641                                 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);
5642                                 break;
5643                         }
5644                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, corona, style, shadow, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
5645                         if (*s == '\r')
5646                                 s++;
5647                         if (*s == '\n')
5648                                 s++;
5649                         n++;
5650                 }
5651                 if (*s)
5652                         Con_Printf("invalid rtlights file \"%s\"\n", name);
5653                 Mem_Free(lightsstring);
5654         }
5655 }
5656
5657 void R_Shadow_SaveWorldLights(void)
5658 {
5659         size_t lightindex;
5660         dlight_t *light;
5661         size_t bufchars, bufmaxchars;
5662         char *buf, *oldbuf;
5663         char name[MAX_QPATH];
5664         char line[MAX_INPUTLINE];
5665         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked, assuming the dpsnprintf mess doesn't screw it up...
5666         // I hate lines which are 3 times my screen size :( --blub
5667         if (!range)
5668                 return;
5669         if (cl.worldmodel == NULL)
5670         {
5671                 Con_Print("No map loaded.\n");
5672                 return;
5673         }
5674         dpsnprintf(name, sizeof(name), "%s.rtlights", cl.worldnamenoextension);
5675         bufchars = bufmaxchars = 0;
5676         buf = NULL;
5677         for (lightindex = 0;lightindex < range;lightindex++)
5678         {
5679                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5680                 if (!light)
5681                         continue;
5682                 if (light->coronasizescale != 0.25f || light->ambientscale != 0 || light->diffusescale != 1 || light->specularscale != 1 || light->flags != LIGHTFLAG_REALTIMEMODE)
5683                         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);
5684                 else if (light->cubemapname[0] || light->corona || light->angles[0] || light->angles[1] || light->angles[2])
5685                         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]);
5686                 else
5687                         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);
5688                 if (bufchars + strlen(line) > bufmaxchars)
5689                 {
5690                         bufmaxchars = bufchars + strlen(line) + 2048;
5691                         oldbuf = buf;
5692                         buf = (char *)Mem_Alloc(tempmempool, bufmaxchars);
5693                         if (oldbuf)
5694                         {
5695                                 if (bufchars)
5696                                         memcpy(buf, oldbuf, bufchars);
5697                                 Mem_Free(oldbuf);
5698                         }
5699                 }
5700                 if (strlen(line))
5701                 {
5702                         memcpy(buf + bufchars, line, strlen(line));
5703                         bufchars += strlen(line);
5704                 }
5705         }
5706         if (bufchars)
5707                 FS_WriteFile(name, buf, (fs_offset_t)bufchars);
5708         if (buf)
5709                 Mem_Free(buf);
5710 }
5711
5712 void R_Shadow_LoadLightsFile(void)
5713 {
5714         int n, a, style;
5715         char tempchar, *lightsstring, *s, *t, name[MAX_QPATH];
5716         float origin[3], radius, color[3], subtract, spotdir[3], spotcone, falloff, distbias;
5717         if (cl.worldmodel == NULL)
5718         {
5719                 Con_Print("No map loaded.\n");
5720                 return;
5721         }
5722         dpsnprintf(name, sizeof(name), "%s.lights", cl.worldnamenoextension);
5723         lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
5724         if (lightsstring)
5725         {
5726                 s = lightsstring;
5727                 n = 0;
5728                 while (*s)
5729                 {
5730                         t = s;
5731                         while (*s && *s != '\n' && *s != '\r')
5732                                 s++;
5733                         if (!*s)
5734                                 break;
5735                         tempchar = *s;
5736                         *s = 0;
5737                         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);
5738                         *s = tempchar;
5739                         if (a < 14)
5740                         {
5741                                 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);
5742                                 break;
5743                         }
5744                         radius = sqrt(DotProduct(color, color) / (falloff * falloff * 8192.0f * 8192.0f));
5745                         radius = bound(15, radius, 4096);
5746                         VectorScale(color, (2.0f / (8388608.0f)), color);
5747                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, vec3_origin, color, radius, 0, style, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
5748                         if (*s == '\r')
5749                                 s++;
5750                         if (*s == '\n')
5751                                 s++;
5752                         n++;
5753                 }
5754                 if (*s)
5755                         Con_Printf("invalid lights file \"%s\"\n", name);
5756                 Mem_Free(lightsstring);
5757         }
5758 }
5759
5760 // tyrlite/hmap2 light types in the delay field
5761 typedef enum lighttype_e {LIGHTTYPE_MINUSX, LIGHTTYPE_RECIPX, LIGHTTYPE_RECIPXX, LIGHTTYPE_NONE, LIGHTTYPE_SUN, LIGHTTYPE_MINUSXX} lighttype_t;
5762
5763 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void)
5764 {
5765         int entnum;
5766         int style;
5767         int islight;
5768         int skin;
5769         int pflags;
5770         //int effects;
5771         int type;
5772         int n;
5773         char *entfiledata;
5774         const char *data;
5775         float origin[3], angles[3], radius, color[3], light[4], fadescale, lightscale, originhack[3], overridecolor[3], vec[4];
5776         char key[256], value[MAX_INPUTLINE];
5777         char vabuf[1024];
5778
5779         if (cl.worldmodel == NULL)
5780         {
5781                 Con_Print("No map loaded.\n");
5782                 return;
5783         }
5784         // try to load a .ent file first
5785         dpsnprintf(key, sizeof(key), "%s.ent", cl.worldnamenoextension);
5786         data = entfiledata = (char *)FS_LoadFile(key, tempmempool, true, NULL);
5787         // and if that is not found, fall back to the bsp file entity string
5788         if (!data)
5789                 data = cl.worldmodel->brush.entities;
5790         if (!data)
5791                 return;
5792         for (entnum = 0;COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{';entnum++)
5793         {
5794                 type = LIGHTTYPE_MINUSX;
5795                 origin[0] = origin[1] = origin[2] = 0;
5796                 originhack[0] = originhack[1] = originhack[2] = 0;
5797                 angles[0] = angles[1] = angles[2] = 0;
5798                 color[0] = color[1] = color[2] = 1;
5799                 light[0] = light[1] = light[2] = 1;light[3] = 300;
5800                 overridecolor[0] = overridecolor[1] = overridecolor[2] = 1;
5801                 fadescale = 1;
5802                 lightscale = 1;
5803                 style = 0;
5804                 skin = 0;
5805                 pflags = 0;
5806                 //effects = 0;
5807                 islight = false;
5808                 while (1)
5809                 {
5810                         if (!COM_ParseToken_Simple(&data, false, false, true))
5811                                 break; // error
5812                         if (com_token[0] == '}')
5813                                 break; // end of entity
5814                         if (com_token[0] == '_')
5815                                 strlcpy(key, com_token + 1, sizeof(key));
5816                         else
5817                                 strlcpy(key, com_token, sizeof(key));
5818                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
5819                                 key[strlen(key)-1] = 0;
5820                         if (!COM_ParseToken_Simple(&data, false, false, true))
5821                                 break; // error
5822                         strlcpy(value, com_token, sizeof(value));
5823
5824                         // now that we have the key pair worked out...
5825                         if (!strcmp("light", key))
5826                         {
5827                                 n = sscanf(value, "%f %f %f %f", &vec[0], &vec[1], &vec[2], &vec[3]);
5828                                 if (n == 1)
5829                                 {
5830                                         // quake
5831                                         light[0] = vec[0] * (1.0f / 256.0f);
5832                                         light[1] = vec[0] * (1.0f / 256.0f);
5833                                         light[2] = vec[0] * (1.0f / 256.0f);
5834                                         light[3] = vec[0];
5835                                 }
5836                                 else if (n == 4)
5837                                 {
5838                                         // halflife
5839                                         light[0] = vec[0] * (1.0f / 255.0f);
5840                                         light[1] = vec[1] * (1.0f / 255.0f);
5841                                         light[2] = vec[2] * (1.0f / 255.0f);
5842                                         light[3] = vec[3];
5843                                 }
5844                         }
5845                         else if (!strcmp("delay", key))
5846                                 type = atoi(value);
5847                         else if (!strcmp("origin", key))
5848                                 sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]);
5849                         else if (!strcmp("angle", key))
5850                                 angles[0] = 0, angles[1] = atof(value), angles[2] = 0;
5851                         else if (!strcmp("angles", key))
5852                                 sscanf(value, "%f %f %f", &angles[0], &angles[1], &angles[2]);
5853                         else if (!strcmp("color", key))
5854                                 sscanf(value, "%f %f %f", &color[0], &color[1], &color[2]);
5855                         else if (!strcmp("wait", key))
5856                                 fadescale = atof(value);
5857                         else if (!strcmp("classname", key))
5858                         {
5859                                 if (!strncmp(value, "light", 5))
5860                                 {
5861                                         islight = true;
5862                                         if (!strcmp(value, "light_fluoro"))
5863                                         {
5864                                                 originhack[0] = 0;
5865                                                 originhack[1] = 0;
5866                                                 originhack[2] = 0;
5867                                                 overridecolor[0] = 1;
5868                                                 overridecolor[1] = 1;
5869                                                 overridecolor[2] = 1;
5870                                         }
5871                                         if (!strcmp(value, "light_fluorospark"))
5872                                         {
5873                                                 originhack[0] = 0;
5874                                                 originhack[1] = 0;
5875                                                 originhack[2] = 0;
5876                                                 overridecolor[0] = 1;
5877                                                 overridecolor[1] = 1;
5878                                                 overridecolor[2] = 1;
5879                                         }
5880                                         if (!strcmp(value, "light_globe"))
5881                                         {
5882                                                 originhack[0] = 0;
5883                                                 originhack[1] = 0;
5884                                                 originhack[2] = 0;
5885                                                 overridecolor[0] = 1;
5886                                                 overridecolor[1] = 0.8;
5887                                                 overridecolor[2] = 0.4;
5888                                         }
5889                                         if (!strcmp(value, "light_flame_large_yellow"))
5890                                         {
5891                                                 originhack[0] = 0;
5892                                                 originhack[1] = 0;
5893                                                 originhack[2] = 0;
5894                                                 overridecolor[0] = 1;
5895                                                 overridecolor[1] = 0.5;
5896                                                 overridecolor[2] = 0.1;
5897                                         }
5898                                         if (!strcmp(value, "light_flame_small_yellow"))
5899                                         {
5900                                                 originhack[0] = 0;
5901                                                 originhack[1] = 0;
5902                                                 originhack[2] = 0;
5903                                                 overridecolor[0] = 1;
5904                                                 overridecolor[1] = 0.5;
5905                                                 overridecolor[2] = 0.1;
5906                                         }
5907                                         if (!strcmp(value, "light_torch_small_white"))
5908                                         {
5909                                                 originhack[0] = 0;
5910                                                 originhack[1] = 0;
5911                                                 originhack[2] = 0;
5912                                                 overridecolor[0] = 1;
5913                                                 overridecolor[1] = 0.5;
5914                                                 overridecolor[2] = 0.1;
5915                                         }
5916                                         if (!strcmp(value, "light_torch_small_walltorch"))
5917                                         {
5918                                                 originhack[0] = 0;
5919                                                 originhack[1] = 0;
5920                                                 originhack[2] = 0;
5921                                                 overridecolor[0] = 1;
5922                                                 overridecolor[1] = 0.5;
5923                                                 overridecolor[2] = 0.1;
5924                                         }
5925                                 }
5926                         }
5927                         else if (!strcmp("style", key))
5928                                 style = atoi(value);
5929                         else if (!strcmp("skin", key))
5930                                 skin = (int)atof(value);
5931                         else if (!strcmp("pflags", key))
5932                                 pflags = (int)atof(value);
5933                         //else if (!strcmp("effects", key))
5934                         //      effects = (int)atof(value);
5935                         else if (cl.worldmodel->type == mod_brushq3)
5936                         {
5937                                 if (!strcmp("scale", key))
5938                                         lightscale = atof(value);
5939                                 if (!strcmp("fade", key))
5940                                         fadescale = atof(value);
5941                         }
5942                 }
5943                 if (!islight)
5944                         continue;
5945                 if (lightscale <= 0)
5946                         lightscale = 1;
5947                 if (fadescale <= 0)
5948                         fadescale = 1;
5949                 if (color[0] == color[1] && color[0] == color[2])
5950                 {
5951                         color[0] *= overridecolor[0];
5952                         color[1] *= overridecolor[1];
5953                         color[2] *= overridecolor[2];
5954                 }
5955                 radius = light[3] * r_editlights_quakelightsizescale.value * lightscale / fadescale;
5956                 color[0] = color[0] * light[0];
5957                 color[1] = color[1] * light[1];
5958                 color[2] = color[2] * light[2];
5959                 switch (type)
5960                 {
5961                 case LIGHTTYPE_MINUSX:
5962                         break;
5963                 case LIGHTTYPE_RECIPX:
5964                         radius *= 2;
5965                         VectorScale(color, (1.0f / 16.0f), color);
5966                         break;
5967                 case LIGHTTYPE_RECIPXX:
5968                         radius *= 2;
5969                         VectorScale(color, (1.0f / 16.0f), color);
5970                         break;
5971                 default:
5972                 case LIGHTTYPE_NONE:
5973                         break;
5974                 case LIGHTTYPE_SUN:
5975                         break;
5976                 case LIGHTTYPE_MINUSXX:
5977                         break;
5978                 }
5979                 VectorAdd(origin, originhack, origin);
5980                 if (radius >= 1)
5981                         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);
5982         }
5983         if (entfiledata)
5984                 Mem_Free(entfiledata);
5985 }
5986
5987
5988 static void R_Shadow_SetCursorLocationForView(void)
5989 {
5990         vec_t dist, push;
5991         vec3_t dest, endpos;
5992         trace_t trace;
5993         VectorMA(r_refdef.view.origin, r_editlights_cursordistance.value, r_refdef.view.forward, dest);
5994         trace = CL_TraceLine(r_refdef.view.origin, dest, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, collision_extendmovelength.value, true, false, NULL, false, true);
5995         if (trace.fraction < 1)
5996         {
5997                 dist = trace.fraction * r_editlights_cursordistance.value;
5998                 push = r_editlights_cursorpushback.value;
5999                 if (push > dist)
6000                         push = dist;
6001                 push = -push;
6002                 VectorMA(trace.endpos, push, r_refdef.view.forward, endpos);
6003                 VectorMA(endpos, r_editlights_cursorpushoff.value, trace.plane.normal, endpos);
6004         }
6005         else
6006         {
6007                 VectorClear( endpos );
6008         }
6009         r_editlights_cursorlocation[0] = floor(endpos[0] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
6010         r_editlights_cursorlocation[1] = floor(endpos[1] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
6011         r_editlights_cursorlocation[2] = floor(endpos[2] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
6012 }
6013
6014 void R_Shadow_UpdateWorldLightSelection(void)
6015 {
6016         if (r_editlights.integer)
6017         {
6018                 R_Shadow_SetCursorLocationForView();
6019                 R_Shadow_SelectLightInView();
6020         }
6021         else
6022                 R_Shadow_SelectLight(NULL);
6023 }
6024
6025 static void R_Shadow_EditLights_Clear_f(void)
6026 {
6027         R_Shadow_ClearWorldLights();
6028 }
6029
6030 void R_Shadow_EditLights_Reload_f(void)
6031 {
6032         if (!cl.worldmodel)
6033                 return;
6034         strlcpy(r_shadow_mapname, cl.worldname, sizeof(r_shadow_mapname));
6035         R_Shadow_ClearWorldLights();
6036         R_Shadow_LoadWorldLights();
6037         if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
6038         {
6039                 R_Shadow_LoadLightsFile();
6040                 if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
6041                         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
6042         }
6043 }
6044
6045 static void R_Shadow_EditLights_Save_f(void)
6046 {
6047         if (!cl.worldmodel)
6048                 return;
6049         R_Shadow_SaveWorldLights();
6050 }
6051
6052 static void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void)
6053 {
6054         R_Shadow_ClearWorldLights();
6055         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
6056 }
6057
6058 static void R_Shadow_EditLights_ImportLightsFile_f(void)
6059 {
6060         R_Shadow_ClearWorldLights();
6061         R_Shadow_LoadLightsFile();
6062 }
6063
6064 static void R_Shadow_EditLights_Spawn_f(void)
6065 {
6066         vec3_t color;
6067         if (!r_editlights.integer)
6068         {
6069                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
6070                 return;
6071         }
6072         if (Cmd_Argc() != 1)
6073         {
6074                 Con_Print("r_editlights_spawn does not take parameters\n");
6075                 return;
6076         }
6077         color[0] = color[1] = color[2] = 1;
6078         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), r_editlights_cursorlocation, vec3_origin, color, 200, 0, 0, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
6079 }
6080
6081 static void R_Shadow_EditLights_Edit_f(void)
6082 {
6083         vec3_t origin, angles, color;
6084         vec_t radius, corona, coronasizescale, ambientscale, diffusescale, specularscale;
6085         int style, shadows, flags, normalmode, realtimemode;
6086         char cubemapname[MAX_INPUTLINE];
6087         if (!r_editlights.integer)
6088         {
6089                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
6090                 return;
6091         }
6092         if (!r_shadow_selectedlight)
6093         {
6094                 Con_Print("No selected light.\n");
6095                 return;
6096         }
6097         VectorCopy(r_shadow_selectedlight->origin, origin);
6098         VectorCopy(r_shadow_selectedlight->angles, angles);
6099         VectorCopy(r_shadow_selectedlight->color, color);
6100         radius = r_shadow_selectedlight->radius;
6101         style = r_shadow_selectedlight->style;
6102         if (r_shadow_selectedlight->cubemapname)
6103                 strlcpy(cubemapname, r_shadow_selectedlight->cubemapname, sizeof(cubemapname));
6104         else
6105                 cubemapname[0] = 0;
6106         shadows = r_shadow_selectedlight->shadow;
6107         corona = r_shadow_selectedlight->corona;
6108         coronasizescale = r_shadow_selectedlight->coronasizescale;
6109         ambientscale = r_shadow_selectedlight->ambientscale;
6110         diffusescale = r_shadow_selectedlight->diffusescale;
6111         specularscale = r_shadow_selectedlight->specularscale;
6112         flags = r_shadow_selectedlight->flags;
6113         normalmode = (flags & LIGHTFLAG_NORMALMODE) != 0;
6114         realtimemode = (flags & LIGHTFLAG_REALTIMEMODE) != 0;
6115         if (!strcmp(Cmd_Argv(1), "origin"))
6116         {
6117                 if (Cmd_Argc() != 5)
6118                 {
6119                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6120                         return;
6121                 }
6122                 origin[0] = atof(Cmd_Argv(2));
6123                 origin[1] = atof(Cmd_Argv(3));
6124                 origin[2] = atof(Cmd_Argv(4));
6125         }
6126         else if (!strcmp(Cmd_Argv(1), "originscale"))
6127         {
6128                 if (Cmd_Argc() != 5)
6129                 {
6130                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6131                         return;
6132                 }
6133                 origin[0] *= atof(Cmd_Argv(2));
6134                 origin[1] *= atof(Cmd_Argv(3));
6135                 origin[2] *= atof(Cmd_Argv(4));
6136         }
6137         else if (!strcmp(Cmd_Argv(1), "originx"))
6138         {
6139                 if (Cmd_Argc() != 3)
6140                 {
6141                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6142                         return;
6143                 }
6144                 origin[0] = atof(Cmd_Argv(2));
6145         }
6146         else if (!strcmp(Cmd_Argv(1), "originy"))
6147         {
6148                 if (Cmd_Argc() != 3)
6149                 {
6150                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6151                         return;
6152                 }
6153                 origin[1] = atof(Cmd_Argv(2));
6154         }
6155         else if (!strcmp(Cmd_Argv(1), "originz"))
6156         {
6157                 if (Cmd_Argc() != 3)
6158                 {
6159                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6160                         return;
6161                 }
6162                 origin[2] = atof(Cmd_Argv(2));
6163         }
6164         else if (!strcmp(Cmd_Argv(1), "move"))
6165         {
6166                 if (Cmd_Argc() != 5)
6167                 {
6168                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6169                         return;
6170                 }
6171                 origin[0] += atof(Cmd_Argv(2));
6172                 origin[1] += atof(Cmd_Argv(3));
6173                 origin[2] += atof(Cmd_Argv(4));
6174         }
6175         else if (!strcmp(Cmd_Argv(1), "movex"))
6176         {
6177                 if (Cmd_Argc() != 3)
6178                 {
6179                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6180                         return;
6181                 }
6182                 origin[0] += atof(Cmd_Argv(2));
6183         }
6184         else if (!strcmp(Cmd_Argv(1), "movey"))
6185         {
6186                 if (Cmd_Argc() != 3)
6187                 {
6188                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6189                         return;
6190                 }
6191                 origin[1] += atof(Cmd_Argv(2));
6192         }
6193         else if (!strcmp(Cmd_Argv(1), "movez"))
6194         {
6195                 if (Cmd_Argc() != 3)
6196                 {
6197                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6198                         return;
6199                 }
6200                 origin[2] += atof(Cmd_Argv(2));
6201         }
6202         else if (!strcmp(Cmd_Argv(1), "angles"))
6203         {
6204                 if (Cmd_Argc() != 5)
6205                 {
6206                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6207                         return;
6208                 }
6209                 angles[0] = atof(Cmd_Argv(2));
6210                 angles[1] = atof(Cmd_Argv(3));
6211                 angles[2] = atof(Cmd_Argv(4));
6212         }
6213         else if (!strcmp(Cmd_Argv(1), "anglesx"))
6214         {
6215                 if (Cmd_Argc() != 3)
6216                 {
6217                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6218                         return;
6219                 }
6220                 angles[0] = atof(Cmd_Argv(2));
6221         }
6222         else if (!strcmp(Cmd_Argv(1), "anglesy"))
6223         {
6224                 if (Cmd_Argc() != 3)
6225                 {
6226                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6227                         return;
6228                 }
6229                 angles[1] = atof(Cmd_Argv(2));
6230         }
6231         else if (!strcmp(Cmd_Argv(1), "anglesz"))
6232         {
6233                 if (Cmd_Argc() != 3)
6234                 {
6235                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6236                         return;
6237                 }
6238                 angles[2] = atof(Cmd_Argv(2));
6239         }
6240         else if (!strcmp(Cmd_Argv(1), "color"))
6241         {
6242                 if (Cmd_Argc() != 5)
6243                 {
6244                         Con_Printf("usage: r_editlights_edit %s red green blue\n", Cmd_Argv(1));
6245                         return;
6246                 }
6247                 color[0] = atof(Cmd_Argv(2));
6248                 color[1] = atof(Cmd_Argv(3));
6249                 color[2] = atof(Cmd_Argv(4));
6250         }
6251         else if (!strcmp(Cmd_Argv(1), "radius"))
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), "colorscale"))
6261         {
6262                 if (Cmd_Argc() == 3)
6263                 {
6264                         double scale = atof(Cmd_Argv(2));
6265                         color[0] *= scale;
6266                         color[1] *= scale;
6267                         color[2] *= scale;
6268                 }
6269                 else
6270                 {
6271                         if (Cmd_Argc() != 5)
6272                         {
6273                                 Con_Printf("usage: r_editlights_edit %s red green blue  (OR grey instead of red green blue)\n", Cmd_Argv(1));
6274                                 return;
6275                         }
6276                         color[0] *= atof(Cmd_Argv(2));
6277                         color[1] *= atof(Cmd_Argv(3));
6278                         color[2] *= atof(Cmd_Argv(4));
6279                 }
6280         }
6281         else if (!strcmp(Cmd_Argv(1), "radiusscale") || !strcmp(Cmd_Argv(1), "sizescale"))
6282         {
6283                 if (Cmd_Argc() != 3)
6284                 {
6285                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6286                         return;
6287                 }
6288                 radius *= atof(Cmd_Argv(2));
6289         }
6290         else if (!strcmp(Cmd_Argv(1), "style"))
6291         {
6292                 if (Cmd_Argc() != 3)
6293                 {
6294                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6295                         return;
6296                 }
6297                 style = atoi(Cmd_Argv(2));
6298         }
6299         else if (!strcmp(Cmd_Argv(1), "cubemap"))
6300         {
6301                 if (Cmd_Argc() > 3)
6302                 {
6303                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6304                         return;
6305                 }
6306                 if (Cmd_Argc() == 3)
6307                         strlcpy(cubemapname, Cmd_Argv(2), sizeof(cubemapname));
6308                 else
6309                         cubemapname[0] = 0;
6310         }
6311         else if (!strcmp(Cmd_Argv(1), "shadows"))
6312         {
6313                 if (Cmd_Argc() != 3)
6314                 {
6315                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6316                         return;
6317                 }
6318                 shadows = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6319         }
6320         else if (!strcmp(Cmd_Argv(1), "corona"))
6321         {
6322                 if (Cmd_Argc() != 3)
6323                 {
6324                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6325                         return;
6326                 }
6327                 corona = atof(Cmd_Argv(2));
6328         }
6329         else if (!strcmp(Cmd_Argv(1), "coronasize"))
6330         {
6331                 if (Cmd_Argc() != 3)
6332                 {
6333                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6334                         return;
6335                 }
6336                 coronasizescale = atof(Cmd_Argv(2));
6337         }
6338         else if (!strcmp(Cmd_Argv(1), "ambient"))
6339         {
6340                 if (Cmd_Argc() != 3)
6341                 {
6342                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6343                         return;
6344                 }
6345                 ambientscale = atof(Cmd_Argv(2));
6346         }
6347         else if (!strcmp(Cmd_Argv(1), "diffuse"))
6348         {
6349                 if (Cmd_Argc() != 3)
6350                 {
6351                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6352                         return;
6353                 }
6354                 diffusescale = atof(Cmd_Argv(2));
6355         }
6356         else if (!strcmp(Cmd_Argv(1), "specular"))
6357         {
6358                 if (Cmd_Argc() != 3)
6359                 {
6360                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6361                         return;
6362                 }
6363                 specularscale = atof(Cmd_Argv(2));
6364         }
6365         else if (!strcmp(Cmd_Argv(1), "normalmode"))
6366         {
6367                 if (Cmd_Argc() != 3)
6368                 {
6369                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6370                         return;
6371                 }
6372                 normalmode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6373         }
6374         else if (!strcmp(Cmd_Argv(1), "realtimemode"))
6375         {
6376                 if (Cmd_Argc() != 3)
6377                 {
6378                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6379                         return;
6380                 }
6381                 realtimemode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6382         }
6383         else
6384         {
6385                 Con_Print("usage: r_editlights_edit [property] [value]\n");
6386                 Con_Print("Selected light's properties:\n");
6387                 Con_Printf("Origin       : %f %f %f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);
6388                 Con_Printf("Angles       : %f %f %f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);
6389                 Con_Printf("Color        : %f %f %f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);
6390                 Con_Printf("Radius       : %f\n", r_shadow_selectedlight->radius);
6391                 Con_Printf("Corona       : %f\n", r_shadow_selectedlight->corona);
6392                 Con_Printf("Style        : %i\n", r_shadow_selectedlight->style);
6393                 Con_Printf("Shadows      : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");
6394                 Con_Printf("Cubemap      : %s\n", r_shadow_selectedlight->cubemapname);
6395                 Con_Printf("CoronaSize   : %f\n", r_shadow_selectedlight->coronasizescale);
6396                 Con_Printf("Ambient      : %f\n", r_shadow_selectedlight->ambientscale);
6397                 Con_Printf("Diffuse      : %f\n", r_shadow_selectedlight->diffusescale);
6398                 Con_Printf("Specular     : %f\n", r_shadow_selectedlight->specularscale);
6399                 Con_Printf("NormalMode   : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");
6400                 Con_Printf("RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");
6401                 return;
6402         }
6403         flags = (normalmode ? LIGHTFLAG_NORMALMODE : 0) | (realtimemode ? LIGHTFLAG_REALTIMEMODE : 0);
6404         R_Shadow_UpdateWorldLight(r_shadow_selectedlight, origin, angles, color, radius, corona, style, shadows, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
6405 }
6406
6407 static void R_Shadow_EditLights_EditAll_f(void)
6408 {
6409         size_t lightindex;
6410         dlight_t *light, *oldselected;
6411         size_t range;
6412
6413         if (!r_editlights.integer)
6414         {
6415                 Con_Print("Cannot edit lights when not in editing mode. Set r_editlights to 1.\n");
6416                 return;
6417         }
6418
6419         oldselected = r_shadow_selectedlight;
6420         // EditLights doesn't seem to have a "remove" command or something so:
6421         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
6422         for (lightindex = 0;lightindex < range;lightindex++)
6423         {
6424                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
6425                 if (!light)
6426                         continue;
6427                 R_Shadow_SelectLight(light);
6428                 R_Shadow_EditLights_Edit_f();
6429         }
6430         // return to old selected (to not mess editing once selection is locked)
6431         R_Shadow_SelectLight(oldselected);
6432 }
6433
6434 void R_Shadow_EditLights_DrawSelectedLightProperties(void)
6435 {
6436         int lightnumber, lightcount;
6437         size_t lightindex, range;
6438         dlight_t *light;
6439         char temp[256];
6440         float x, y;
6441
6442         if (!r_editlights.integer)
6443                 return;
6444
6445         // update cvars so QC can query them
6446         if (r_shadow_selectedlight)
6447         {
6448                 dpsnprintf(temp, sizeof(temp), "%f %f %f", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);
6449                 Cvar_SetQuick(&r_editlights_current_origin, temp);
6450                 dpsnprintf(temp, sizeof(temp), "%f %f %f", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);
6451                 Cvar_SetQuick(&r_editlights_current_angles, temp);
6452                 dpsnprintf(temp, sizeof(temp), "%f %f %f", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);
6453                 Cvar_SetQuick(&r_editlights_current_color, temp);
6454                 Cvar_SetValueQuick(&r_editlights_current_radius, r_shadow_selectedlight->radius);
6455                 Cvar_SetValueQuick(&r_editlights_current_corona, r_shadow_selectedlight->corona);
6456                 Cvar_SetValueQuick(&r_editlights_current_coronasize, r_shadow_selectedlight->coronasizescale);
6457                 Cvar_SetValueQuick(&r_editlights_current_style, r_shadow_selectedlight->style);
6458                 Cvar_SetValueQuick(&r_editlights_current_shadows, r_shadow_selectedlight->shadow);
6459                 Cvar_SetQuick(&r_editlights_current_cubemap, r_shadow_selectedlight->cubemapname);
6460                 Cvar_SetValueQuick(&r_editlights_current_ambient, r_shadow_selectedlight->ambientscale);
6461                 Cvar_SetValueQuick(&r_editlights_current_diffuse, r_shadow_selectedlight->diffusescale);
6462                 Cvar_SetValueQuick(&r_editlights_current_specular, r_shadow_selectedlight->specularscale);
6463                 Cvar_SetValueQuick(&r_editlights_current_normalmode, (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? 1 : 0);
6464                 Cvar_SetValueQuick(&r_editlights_current_realtimemode, (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? 1 : 0);
6465         }
6466
6467         // draw properties on screen
6468         if (!r_editlights_drawproperties.integer)
6469                 return;
6470         x = vid_conwidth.value - 240;
6471         y = 5;
6472         DrawQ_Pic(x-5, y-5, NULL, 250, 155, 0, 0, 0, 0.75, 0);
6473         lightnumber = -1;
6474         lightcount = 0;
6475         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
6476         for (lightindex = 0;lightindex < range;lightindex++)
6477         {
6478                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
6479                 if (!light)
6480                         continue;
6481                 if (light == r_shadow_selectedlight)
6482                         lightnumber = (int)lightindex;
6483                 lightcount++;
6484         }
6485         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;
6486         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;
6487         y += 8;
6488         if (r_shadow_selectedlight == NULL)
6489                 return;
6490         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;
6491         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;
6492         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;
6493         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;
6494         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;
6495         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;
6496         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;
6497         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;
6498         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;
6499         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;
6500         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;
6501         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;
6502         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;
6503         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;
6504         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;
6505 }
6506
6507 static void R_Shadow_EditLights_ToggleShadow_f(void)
6508 {
6509         if (!r_editlights.integer)
6510         {
6511                 Con_Print("Cannot spawn 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_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);
6520 }
6521
6522 static void R_Shadow_EditLights_ToggleCorona_f(void)
6523 {
6524         if (!r_editlights.integer)
6525         {
6526                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
6527                 return;
6528         }
6529         if (!r_shadow_selectedlight)
6530         {
6531                 Con_Print("No selected light.\n");
6532                 return;
6533         }
6534         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);
6535 }
6536
6537 static void R_Shadow_EditLights_Remove_f(void)
6538 {
6539         if (!r_editlights.integer)
6540         {
6541                 Con_Print("Cannot remove light when not in editing mode.  Set r_editlights to 1.\n");
6542                 return;
6543         }
6544         if (!r_shadow_selectedlight)
6545         {
6546                 Con_Print("No selected light.\n");
6547                 return;
6548         }
6549         R_Shadow_FreeWorldLight(r_shadow_selectedlight);
6550         r_shadow_selectedlight = NULL;
6551 }
6552
6553 static void R_Shadow_EditLights_Help_f(void)
6554 {
6555         Con_Print(
6556 "Documentation on r_editlights system:\n"
6557 "Settings:\n"
6558 "r_editlights : enable/disable editing mode\n"
6559 "r_editlights_cursordistance : maximum distance of cursor from eye\n"
6560 "r_editlights_cursorpushback : push back cursor this far from surface\n"
6561 "r_editlights_cursorpushoff : push cursor off surface this far\n"
6562 "r_editlights_cursorgrid : snap cursor to grid of this size\n"
6563 "r_editlights_quakelightsizescale : imported quake light entity size scaling\n"
6564 "Commands:\n"
6565 "r_editlights_help : this help\n"
6566 "r_editlights_clear : remove all lights\n"
6567 "r_editlights_reload : reload .rtlights, .lights file, or entities\n"
6568 "r_editlights_lock : lock selection to current light, if already locked - unlock\n"
6569 "r_editlights_save : save to .rtlights file\n"
6570 "r_editlights_spawn : create a light with default settings\n"
6571 "r_editlights_edit command : edit selected light - more documentation below\n"
6572 "r_editlights_remove : remove selected light\n"
6573 "r_editlights_toggleshadow : toggles on/off selected light's shadow property\n"
6574 "r_editlights_importlightentitiesfrommap : reload light entities\n"
6575 "r_editlights_importlightsfile : reload .light file (produced by hlight)\n"
6576 "Edit commands:\n"
6577 "origin x y z : set light location\n"
6578 "originx x: set x component of light location\n"
6579 "originy y: set y component of light location\n"
6580 "originz z: set z component of light location\n"
6581 "move x y z : adjust light location\n"
6582 "movex x: adjust x component of light location\n"
6583 "movey y: adjust y component of light location\n"
6584 "movez z: adjust z component of light location\n"
6585 "angles x y z : set light angles\n"
6586 "anglesx x: set x component of light angles\n"
6587 "anglesy y: set y component of light angles\n"
6588 "anglesz z: set z component of light angles\n"
6589 "color r g b : set color of light (can be brighter than 1 1 1)\n"
6590 "radius radius : set radius (size) of light\n"
6591 "colorscale grey : multiply color of light (1 does nothing)\n"
6592 "colorscale r g b : multiply color of light (1 1 1 does nothing)\n"
6593 "radiusscale scale : multiply radius (size) of light (1 does nothing)\n"
6594 "sizescale scale : multiply radius (size) of light (1 does nothing)\n"
6595 "originscale x y z : multiply origin of light (1 1 1 does nothing)\n"
6596 "style style : set lightstyle of light (flickering patterns, switches, etc)\n"
6597 "cubemap basename : set filter cubemap of light\n"
6598 "shadows 1/0 : turn on/off shadows\n"
6599 "corona n : set corona intensity\n"
6600 "coronasize n : set corona size (0-1)\n"
6601 "ambient n : set ambient intensity (0-1)\n"
6602 "diffuse n : set diffuse intensity (0-1)\n"
6603 "specular n : set specular intensity (0-1)\n"
6604 "normalmode 1/0 : turn on/off rendering of this light in rtworld 0 mode\n"
6605 "realtimemode 1/0 : turn on/off rendering of this light in rtworld 1 mode\n"
6606 "<nothing> : print light properties to console\n"
6607         );
6608 }
6609
6610 static void R_Shadow_EditLights_CopyInfo_f(void)
6611 {
6612         if (!r_editlights.integer)
6613         {
6614                 Con_Print("Cannot copy light info when not in editing mode.  Set r_editlights to 1.\n");
6615                 return;
6616         }
6617         if (!r_shadow_selectedlight)
6618         {
6619                 Con_Print("No selected light.\n");
6620                 return;
6621         }
6622         VectorCopy(r_shadow_selectedlight->angles, r_shadow_bufferlight.angles);
6623         VectorCopy(r_shadow_selectedlight->color, r_shadow_bufferlight.color);
6624         r_shadow_bufferlight.radius = r_shadow_selectedlight->radius;
6625         r_shadow_bufferlight.style = r_shadow_selectedlight->style;
6626         if (r_shadow_selectedlight->cubemapname)
6627                 strlcpy(r_shadow_bufferlight.cubemapname, r_shadow_selectedlight->cubemapname, sizeof(r_shadow_bufferlight.cubemapname));
6628         else
6629                 r_shadow_bufferlight.cubemapname[0] = 0;
6630         r_shadow_bufferlight.shadow = r_shadow_selectedlight->shadow;
6631         r_shadow_bufferlight.corona = r_shadow_selectedlight->corona;
6632         r_shadow_bufferlight.coronasizescale = r_shadow_selectedlight->coronasizescale;
6633         r_shadow_bufferlight.ambientscale = r_shadow_selectedlight->ambientscale;
6634         r_shadow_bufferlight.diffusescale = r_shadow_selectedlight->diffusescale;
6635         r_shadow_bufferlight.specularscale = r_shadow_selectedlight->specularscale;
6636         r_shadow_bufferlight.flags = r_shadow_selectedlight->flags;
6637 }
6638
6639 static void R_Shadow_EditLights_PasteInfo_f(void)
6640 {
6641         if (!r_editlights.integer)
6642         {
6643                 Con_Print("Cannot paste light info when not in editing mode.  Set r_editlights to 1.\n");
6644                 return;
6645         }
6646         if (!r_shadow_selectedlight)
6647         {
6648                 Con_Print("No selected light.\n");
6649                 return;
6650         }
6651         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);
6652 }
6653
6654 static void R_Shadow_EditLights_Lock_f(void)
6655 {
6656         if (!r_editlights.integer)
6657         {
6658                 Con_Print("Cannot lock on light when not in editing mode.  Set r_editlights to 1.\n");
6659                 return;
6660         }
6661         if (r_editlights_lockcursor)
6662         {
6663                 r_editlights_lockcursor = false;
6664                 return;
6665         }
6666         if (!r_shadow_selectedlight)
6667         {
6668                 Con_Print("No selected light to lock on.\n");
6669                 return;
6670         }
6671         r_editlights_lockcursor = true;
6672 }
6673
6674 static void R_Shadow_EditLights_Init(void)
6675 {
6676         Cvar_RegisterVariable(&r_editlights);
6677         Cvar_RegisterVariable(&r_editlights_cursordistance);
6678         Cvar_RegisterVariable(&r_editlights_cursorpushback);
6679         Cvar_RegisterVariable(&r_editlights_cursorpushoff);
6680         Cvar_RegisterVariable(&r_editlights_cursorgrid);
6681         Cvar_RegisterVariable(&r_editlights_quakelightsizescale);
6682         Cvar_RegisterVariable(&r_editlights_drawproperties);
6683         Cvar_RegisterVariable(&r_editlights_current_origin);
6684         Cvar_RegisterVariable(&r_editlights_current_angles);
6685         Cvar_RegisterVariable(&r_editlights_current_color);
6686         Cvar_RegisterVariable(&r_editlights_current_radius);
6687         Cvar_RegisterVariable(&r_editlights_current_corona);
6688         Cvar_RegisterVariable(&r_editlights_current_coronasize);
6689         Cvar_RegisterVariable(&r_editlights_current_style);
6690         Cvar_RegisterVariable(&r_editlights_current_shadows);
6691         Cvar_RegisterVariable(&r_editlights_current_cubemap);
6692         Cvar_RegisterVariable(&r_editlights_current_ambient);
6693         Cvar_RegisterVariable(&r_editlights_current_diffuse);
6694         Cvar_RegisterVariable(&r_editlights_current_specular);
6695         Cvar_RegisterVariable(&r_editlights_current_normalmode);
6696         Cvar_RegisterVariable(&r_editlights_current_realtimemode);
6697         Cmd_AddCommand("r_editlights_help", R_Shadow_EditLights_Help_f, "prints documentation on console commands and variables in rtlight editing system");
6698         Cmd_AddCommand("r_editlights_clear", R_Shadow_EditLights_Clear_f, "removes all world lights (let there be darkness!)");
6699         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)");
6700         Cmd_AddCommand("r_editlights_save", R_Shadow_EditLights_Save_f, "save .rtlights file for current level");
6701         Cmd_AddCommand("r_editlights_spawn", R_Shadow_EditLights_Spawn_f, "creates a light with default properties (let there be light!)");
6702         Cmd_AddCommand("r_editlights_edit", R_Shadow_EditLights_Edit_f, "changes a property on the selected light");
6703         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)");
6704         Cmd_AddCommand("r_editlights_remove", R_Shadow_EditLights_Remove_f, "remove selected light");
6705         Cmd_AddCommand("r_editlights_toggleshadow", R_Shadow_EditLights_ToggleShadow_f, "toggle on/off the shadow option on the selected light");
6706         Cmd_AddCommand("r_editlights_togglecorona", R_Shadow_EditLights_ToggleCorona_f, "toggle on/off the corona option on the selected light");
6707         Cmd_AddCommand("r_editlights_importlightentitiesfrommap", R_Shadow_EditLights_ImportLightEntitiesFromMap_f, "load lights from .ent file or map entities (ignoring .rtlights or .lights file)");
6708         Cmd_AddCommand("r_editlights_importlightsfile", R_Shadow_EditLights_ImportLightsFile_f, "load lights from .lights file (ignoring .rtlights or .ent files and map entities)");
6709         Cmd_AddCommand("r_editlights_copyinfo", R_Shadow_EditLights_CopyInfo_f, "store a copy of all properties (except origin) of the selected light");
6710         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)");
6711         Cmd_AddCommand("r_editlights_lock", R_Shadow_EditLights_Lock_f, "lock selection to current light, if already locked - unlock");
6712 }
6713
6714
6715
6716 /*
6717 =============================================================================
6718
6719 LIGHT SAMPLING
6720
6721 =============================================================================
6722 */
6723
6724 void R_LightPoint(float *color, const vec3_t p, const int flags)
6725 {
6726         int i, numlights, flag;
6727         float f, relativepoint[3], dist, dist2, lightradius2;
6728         vec3_t diffuse, n;
6729         rtlight_t *light;
6730         dlight_t *dlight;
6731
6732         if (r_fullbright.integer)
6733         {
6734                 VectorSet(color, 1, 1, 1);
6735                 return;
6736         }
6737
6738         VectorClear(color);
6739
6740         if (flags & LP_LIGHTMAP)
6741         {
6742                 if (!r_fullbright.integer && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6743                 {
6744                         VectorClear(diffuse);
6745                         r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, color, diffuse, n);
6746                         VectorAdd(color, diffuse, color);
6747                 }
6748                 else
6749                         VectorSet(color, 1, 1, 1);
6750                 color[0] += r_refdef.scene.ambient;
6751                 color[1] += r_refdef.scene.ambient;
6752                 color[2] += r_refdef.scene.ambient;
6753         }
6754
6755         if (flags & LP_RTWORLD)
6756         {
6757                 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
6758                 numlights = (int)Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
6759                 for (i = 0; i < numlights; i++)
6760                 {
6761                         dlight = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, i);
6762                         if (!dlight)
6763                                 continue;
6764                         light = &dlight->rtlight;
6765                         if (!(light->flags & flag))
6766                                 continue;
6767                         // sample
6768                         lightradius2 = light->radius * light->radius;
6769                         VectorSubtract(light->shadoworigin, p, relativepoint);
6770                         dist2 = VectorLength2(relativepoint);
6771                         if (dist2 >= lightradius2)
6772                                 continue;
6773                         dist = sqrt(dist2) / light->radius;
6774                         f = dist < 1 ? (r_shadow_lightintensityscale.value * ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist))) : 0;
6775                         if (f <= 0)
6776                                 continue;
6777                         // todo: add to both ambient and diffuse
6778                         if (!light->shadow || CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, collision_extendmovelength.value, true, false, NULL, false, true).fraction == 1)
6779                                 VectorMA(color, f, light->currentcolor, color);
6780                 }
6781         }
6782         if (flags & LP_DYNLIGHT)
6783         {
6784                 // sample dlights
6785                 for (i = 0;i < r_refdef.scene.numlights;i++)
6786                 {
6787                         light = r_refdef.scene.lights[i];
6788                         // sample
6789                         lightradius2 = light->radius * light->radius;
6790                         VectorSubtract(light->shadoworigin, p, relativepoint);
6791                         dist2 = VectorLength2(relativepoint);
6792                         if (dist2 >= lightradius2)
6793                                 continue;
6794                         dist = sqrt(dist2) / light->radius;
6795                         f = dist < 1 ? (r_shadow_lightintensityscale.value * ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist))) : 0;
6796                         if (f <= 0)
6797                                 continue;
6798                         // todo: add to both ambient and diffuse
6799                         if (!light->shadow || CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, collision_extendmovelength.value, true, false, NULL, false, true).fraction == 1)
6800                                 VectorMA(color, f, light->color, color);
6801                 }
6802         }
6803 }
6804
6805 void R_CompleteLightPoint(vec3_t ambient, vec3_t diffuse, vec3_t lightdir, const vec3_t p, const int flags)
6806 {
6807         int i, numlights, flag;
6808         rtlight_t *light;
6809         dlight_t *dlight;
6810         float relativepoint[3];
6811         float color[3];
6812         float dir[3];
6813         float dist;
6814         float dist2;
6815         float intensity;
6816         float sample[5*3];
6817         float lightradius2;
6818
6819         if (r_fullbright.integer)
6820         {
6821                 VectorSet(ambient, 1, 1, 1);
6822                 VectorClear(diffuse);
6823                 VectorClear(lightdir);
6824                 return;
6825         }
6826
6827         if (flags == LP_LIGHTMAP)
6828         {
6829                 VectorSet(ambient, r_refdef.scene.ambient, r_refdef.scene.ambient, r_refdef.scene.ambient);
6830                 VectorClear(diffuse);
6831                 VectorClear(lightdir);
6832                 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6833                         r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, ambient, diffuse, lightdir);
6834                 else
6835                         VectorSet(ambient, 1, 1, 1);
6836                 return;
6837         }
6838
6839         memset(sample, 0, sizeof(sample));
6840         VectorSet(sample, r_refdef.scene.ambient, r_refdef.scene.ambient, r_refdef.scene.ambient);
6841
6842         if ((flags & LP_LIGHTMAP) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6843         {
6844                 vec3_t tempambient;
6845                 VectorClear(tempambient);
6846                 VectorClear(color);
6847                 VectorClear(relativepoint);
6848                 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, tempambient, color, relativepoint);
6849                 VectorScale(tempambient, r_refdef.lightmapintensity, tempambient);
6850                 VectorScale(color, r_refdef.lightmapintensity, color);
6851                 VectorAdd(sample, tempambient, sample);
6852                 VectorMA(sample    , 0.5f            , color, sample    );
6853                 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6854                 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6855                 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6856                 // calculate a weighted average light direction as well
6857                 intensity = VectorLength(color);
6858                 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6859         }
6860
6861         if (flags & LP_RTWORLD)
6862         {
6863                 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
6864                 numlights = (int)Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
6865                 for (i = 0; i < numlights; i++)
6866                 {
6867                         dlight = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, i);
6868                         if (!dlight)
6869                                 continue;
6870                         light = &dlight->rtlight;
6871                         if (!(light->flags & flag))
6872                                 continue;
6873                         // sample
6874                         lightradius2 = light->radius * light->radius;
6875                         VectorSubtract(light->shadoworigin, p, relativepoint);
6876                         dist2 = VectorLength2(relativepoint);
6877                         if (dist2 >= lightradius2)
6878                                 continue;
6879                         dist = sqrt(dist2) / light->radius;
6880                         intensity = min(1.0f, (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) * r_shadow_lightintensityscale.value;
6881                         if (intensity <= 0.0f)
6882                                 continue;
6883                         if (light->shadow && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, collision_extendmovelength.value, true, false, NULL, false, true).fraction < 1)
6884                                 continue;
6885                         // scale down intensity to add to both ambient and diffuse
6886                         //intensity *= 0.5f;
6887                         VectorNormalize(relativepoint);
6888                         VectorScale(light->currentcolor, intensity, color);
6889                         VectorMA(sample    , 0.5f            , color, sample    );
6890                         VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6891                         VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6892                         VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6893                         // calculate a weighted average light direction as well
6894                         intensity *= VectorLength(color);
6895                         VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6896                 }
6897                 // FIXME: sample bouncegrid too!
6898         }
6899
6900         if (flags & LP_DYNLIGHT)
6901         {
6902                 // sample dlights
6903                 for (i = 0;i < r_refdef.scene.numlights;i++)
6904                 {
6905                         light = r_refdef.scene.lights[i];
6906                         // sample
6907                         lightradius2 = light->radius * light->radius;
6908                         VectorSubtract(light->shadoworigin, p, relativepoint);
6909                         dist2 = VectorLength2(relativepoint);
6910                         if (dist2 >= lightradius2)
6911                                 continue;
6912                         dist = sqrt(dist2) / light->radius;
6913                         intensity = (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist) * r_shadow_lightintensityscale.value;
6914                         if (intensity <= 0.0f)
6915                                 continue;
6916                         if (light->shadow && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, collision_extendmovelength.value, true, false, NULL, false, true).fraction < 1)
6917                                 continue;
6918                         // scale down intensity to add to both ambient and diffuse
6919                         //intensity *= 0.5f;
6920                         VectorNormalize(relativepoint);
6921                         VectorScale(light->currentcolor, intensity, color);
6922                         VectorMA(sample    , 0.5f            , color, sample    );
6923                         VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6924                         VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6925                         VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6926                         // calculate a weighted average light direction as well
6927                         intensity *= VectorLength(color);
6928                         VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6929                 }
6930         }
6931
6932         // calculate the direction we'll use to reduce the sample to a directional light source
6933         VectorCopy(sample + 12, dir);
6934         //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
6935         VectorNormalize(dir);
6936         // extract the diffuse color along the chosen direction and scale it
6937         diffuse[0] = (dir[0]*sample[3] + dir[1]*sample[6] + dir[2]*sample[ 9] + sample[ 0]);
6938         diffuse[1] = (dir[0]*sample[4] + dir[1]*sample[7] + dir[2]*sample[10] + sample[ 1]);
6939         diffuse[2] = (dir[0]*sample[5] + dir[1]*sample[8] + dir[2]*sample[11] + sample[ 2]);
6940         // subtract some of diffuse from ambient
6941         VectorMA(sample, -0.333f, diffuse, ambient);
6942         // store the normalized lightdir
6943         VectorCopy(dir, lightdir);
6944 }