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)
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.
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).
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).
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).
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
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.
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.
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.
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
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).
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.
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
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
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.
137 #include "quakedef.h"
138 #include "r_shadow.h"
139 #include "cl_collision.h"
142 #include "dpsoftrast.h"
146 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
149 static void R_Shadow_EditLights_Init(void);
151 typedef enum r_shadow_rendermode_e
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
169 r_shadow_rendermode_t;
171 typedef enum r_shadow_shadowmode_e
173 R_SHADOW_SHADOWMODE_STENCIL,
174 R_SHADOW_SHADOWMODE_SHADOWMAP2D
176 r_shadow_shadowmode_t;
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];
188 int r_shadow_drawbuffer;
189 int r_shadow_readbuffer;
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;
206 int maxshadowtriangles;
209 int maxshadowvertices;
210 float *shadowvertex3f;
220 unsigned char *shadowsides;
221 int *shadowsideslist;
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;
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;
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;
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
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;
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;
269 // lights are reloaded when this changes
270 char r_shadow_mapname[MAX_QPATH];
272 // used only for light filters (cubemaps)
273 rtexturepool_t *r_shadow_filters_texturepool;
275 cvar_t r_shadow_bumpscale_basetexture = {0, "r_shadow_bumpscale_basetexture", "0", "generate fake bumpmaps from diffuse textures at this bumpyness, try 4 to match tenebrae, higher values increase depth, requires r_restart to take effect"};
276 cvar_t r_shadow_bumpscale_bumpmap = {0, "r_shadow_bumpscale_bumpmap", "4", "what magnitude to interpret _bump.tga textures as, higher values increase depth, requires r_restart to take effect"};
277 cvar_t r_shadow_debuglight = {0, "r_shadow_debuglight", "-1", "renders only one light, for level design purposes or debugging"};
278 cvar_t r_shadow_deferred = {CVAR_SAVE, "r_shadow_deferred", "0", "uses image-based lighting instead of geometry-based lighting, the method used renders a depth image and a normalmap image, renders lights into separate diffuse and specular images, and then combines this into the normal rendering, requires r_shadow_shadowmapping"};
279 cvar_t r_shadow_usebihculling = {0, "r_shadow_usebihculling", "1", "use BIH (Bounding Interval Hierarchy) for culling lit surfaces instead of BSP (Binary Space Partitioning)"};
280 cvar_t r_shadow_usenormalmap = {CVAR_SAVE, "r_shadow_usenormalmap", "1", "enables use of directional shading on lights"};
281 cvar_t r_shadow_gloss = {CVAR_SAVE, "r_shadow_gloss", "1", "0 disables gloss (specularity) rendering, 1 uses gloss if textures are found, 2 forces a flat metallic specular effect on everything without textures (similar to tenebrae)"};
282 cvar_t r_shadow_gloss2intensity = {0, "r_shadow_gloss2intensity", "0.125", "how bright the forced flat gloss should look if r_shadow_gloss is 2"};
283 cvar_t r_shadow_glossintensity = {0, "r_shadow_glossintensity", "1", "how bright textured glossmaps should look if r_shadow_gloss is 1 or 2"};
284 cvar_t r_shadow_glossexponent = {0, "r_shadow_glossexponent", "32", "how 'sharp' the gloss should appear (specular power)"};
285 cvar_t r_shadow_gloss2exponent = {0, "r_shadow_gloss2exponent", "32", "same as r_shadow_glossexponent but for forced gloss (gloss 2) surfaces"};
286 cvar_t r_shadow_glossexact = {0, "r_shadow_glossexact", "0", "use exact reflection math for gloss (slightly slower, but should look a tad better)"};
287 cvar_t r_shadow_lightattenuationdividebias = {0, "r_shadow_lightattenuationdividebias", "1", "changes attenuation texture generation"};
288 cvar_t r_shadow_lightattenuationlinearscale = {0, "r_shadow_lightattenuationlinearscale", "2", "changes attenuation texture generation"};
289 cvar_t r_shadow_lightintensityscale = {0, "r_shadow_lightintensityscale", "1", "renders all world lights brighter or darker"};
290 cvar_t r_shadow_lightradiusscale = {0, "r_shadow_lightradiusscale", "1", "renders all world lights larger or smaller"};
291 cvar_t r_shadow_projectdistance = {0, "r_shadow_projectdistance", "0", "how far to cast shadows"};
292 cvar_t r_shadow_frontsidecasting = {0, "r_shadow_frontsidecasting", "1", "whether to cast shadows from illuminated triangles (front side of model) or unlit triangles (back side of model)"};
293 cvar_t r_shadow_realtime_dlight = {CVAR_SAVE, "r_shadow_realtime_dlight", "1", "enables rendering of dynamic lights such as explosions and rocket light"};
294 cvar_t r_shadow_realtime_dlight_shadows = {CVAR_SAVE, "r_shadow_realtime_dlight_shadows", "1", "enables rendering of shadows from dynamic lights"};
295 cvar_t r_shadow_realtime_dlight_svbspculling = {0, "r_shadow_realtime_dlight_svbspculling", "0", "enables svbsp optimization on dynamic lights (very slow!)"};
296 cvar_t r_shadow_realtime_dlight_portalculling = {0, "r_shadow_realtime_dlight_portalculling", "0", "enables portal optimization on dynamic lights (slow!)"};
297 cvar_t r_shadow_realtime_world = {CVAR_SAVE, "r_shadow_realtime_world", "0", "enables rendering of full world lighting (whether loaded from the map, or a .rtlights file, or a .ent file, or a .lights file produced by hlight)"};
298 cvar_t r_shadow_realtime_world_lightmaps = {CVAR_SAVE, "r_shadow_realtime_world_lightmaps", "0", "brightness to render lightmaps when using full world lighting, try 0.5 for a tenebrae-like appearance"};
299 cvar_t r_shadow_realtime_world_shadows = {CVAR_SAVE, "r_shadow_realtime_world_shadows", "1", "enables rendering of shadows from world lights"};
300 cvar_t r_shadow_realtime_world_compile = {0, "r_shadow_realtime_world_compile", "1", "enables compilation of world lights for higher performance rendering"};
301 cvar_t r_shadow_realtime_world_compileshadow = {0, "r_shadow_realtime_world_compileshadow", "1", "enables compilation of shadows from world lights for higher performance rendering"};
302 cvar_t r_shadow_realtime_world_compilesvbsp = {0, "r_shadow_realtime_world_compilesvbsp", "1", "enables svbsp optimization during compilation (slower than compileportalculling but more exact)"};
303 cvar_t r_shadow_realtime_world_compileportalculling = {0, "r_shadow_realtime_world_compileportalculling", "1", "enables portal-based culling optimization during compilation (overrides compilesvbsp)"};
304 cvar_t r_shadow_scissor = {0, "r_shadow_scissor", "1", "use scissor optimization of light rendering (restricts rendering to the portion of the screen affected by the light)"};
305 cvar_t r_shadow_shadowmapping = {CVAR_SAVE, "r_shadow_shadowmapping", "1", "enables use of shadowmapping (depth texture sampling) instead of stencil shadow volumes, requires gl_fbo 1"};
306 cvar_t r_shadow_shadowmapping_filterquality = {CVAR_SAVE, "r_shadow_shadowmapping_filterquality", "-1", "shadowmap filter modes: -1 = auto-select, 0 = no filtering, 1 = bilinear, 2 = bilinear 2x2 blur (fast), 3 = 3x3 blur (moderate), 4 = 4x4 blur (slow)"};
307 cvar_t r_shadow_shadowmapping_useshadowsampler = {CVAR_SAVE, "r_shadow_shadowmapping_useshadowsampler", "1", "whether to use sampler2DShadow if available"};
308 cvar_t r_shadow_shadowmapping_depthbits = {CVAR_SAVE, "r_shadow_shadowmapping_depthbits", "24", "requested minimum shadowmap texture depth bits"};
309 cvar_t r_shadow_shadowmapping_vsdct = {CVAR_SAVE, "r_shadow_shadowmapping_vsdct", "1", "enables use of virtual shadow depth cube texture"};
310 cvar_t r_shadow_shadowmapping_minsize = {CVAR_SAVE, "r_shadow_shadowmapping_minsize", "32", "shadowmap size limit"};
311 cvar_t r_shadow_shadowmapping_maxsize = {CVAR_SAVE, "r_shadow_shadowmapping_maxsize", "512", "shadowmap size limit"};
312 cvar_t r_shadow_shadowmapping_precision = {CVAR_SAVE, "r_shadow_shadowmapping_precision", "1", "makes shadowmaps have a maximum resolution of this number of pixels per light source radius unit such that, for example, at precision 0.5 a light with radius 200 will have a maximum resolution of 100 pixels"};
313 //cvar_t r_shadow_shadowmapping_lod_bias = {CVAR_SAVE, "r_shadow_shadowmapping_lod_bias", "16", "shadowmap size bias"};
314 //cvar_t r_shadow_shadowmapping_lod_scale = {CVAR_SAVE, "r_shadow_shadowmapping_lod_scale", "128", "shadowmap size scaling parameter"};
315 cvar_t r_shadow_shadowmapping_bordersize = {CVAR_SAVE, "r_shadow_shadowmapping_bordersize", "4", "shadowmap size bias for filtering"};
316 cvar_t r_shadow_shadowmapping_nearclip = {CVAR_SAVE, "r_shadow_shadowmapping_nearclip", "1", "shadowmap nearclip in world units"};
317 cvar_t r_shadow_shadowmapping_bias = {CVAR_SAVE, "r_shadow_shadowmapping_bias", "0.03", "shadowmap bias parameter (this is multiplied by nearclip * 1024 / lodsize)"};
318 cvar_t r_shadow_shadowmapping_polygonfactor = {CVAR_SAVE, "r_shadow_shadowmapping_polygonfactor", "2", "slope-dependent shadowmapping bias"};
319 cvar_t r_shadow_shadowmapping_polygonoffset = {CVAR_SAVE, "r_shadow_shadowmapping_polygonoffset", "0", "constant shadowmapping bias"};
320 cvar_t r_shadow_sortsurfaces = {0, "r_shadow_sortsurfaces", "1", "improve performance by sorting illuminated surfaces by texture"};
321 cvar_t r_shadow_polygonfactor = {0, "r_shadow_polygonfactor", "0", "how much to enlarge shadow volume polygons when rendering (should be 0!)"};
322 cvar_t r_shadow_polygonoffset = {0, "r_shadow_polygonoffset", "1", "how much to push shadow volumes into the distance when rendering, to reduce chances of zfighting artifacts (should not be less than 0)"};
323 cvar_t r_shadow_texture3d = {0, "r_shadow_texture3d", "1", "use 3D voxel textures for spherical attenuation rather than cylindrical (does not affect OpenGL 2.0 render path)"};
324 cvar_t r_shadow_bouncegrid = {CVAR_SAVE, "r_shadow_bouncegrid", "0", "perform particle tracing for indirect lighting (Global Illumination / radiosity) using a 3D texture covering the scene, only active on levels with realtime lights active (r_shadow_realtime_world is usually required for these)"};
325 cvar_t r_shadow_bouncegrid_bounceanglediffuse = {CVAR_SAVE, "r_shadow_bouncegrid_bounceanglediffuse", "0", "use random bounce direction rather than true reflection, makes some corner areas dark"};
326 cvar_t r_shadow_bouncegrid_directionalshading = {CVAR_SAVE, "r_shadow_bouncegrid_directionalshading", "0", "use diffuse shading rather than ambient, 3D texture becomes 8x as many pixels to hold the additional data"};
327 cvar_t r_shadow_bouncegrid_dlightparticlemultiplier = {CVAR_SAVE, "r_shadow_bouncegrid_dlightparticlemultiplier", "0", "if set to a high value like 16 this can make dlights look great, but 0 is recommended for performance reasons"};
328 cvar_t r_shadow_bouncegrid_hitmodels = {CVAR_SAVE, "r_shadow_bouncegrid_hitmodels", "0", "enables hitting character model geometry (SLOW)"};
329 cvar_t r_shadow_bouncegrid_includedirectlighting = {CVAR_SAVE, "r_shadow_bouncegrid_includedirectlighting", "0", "allows direct lighting to be recorded, not just indirect (gives an effect somewhat like r_shadow_realtime_world_lightmaps)"};
330 cvar_t r_shadow_bouncegrid_intensity = {CVAR_SAVE, "r_shadow_bouncegrid_intensity", "4", "overall brightness of bouncegrid texture"};
331 cvar_t r_shadow_bouncegrid_lightradiusscale = {CVAR_SAVE, "r_shadow_bouncegrid_lightradiusscale", "4", "particles stop at this fraction of light radius (can be more than 1)"};
332 cvar_t r_shadow_bouncegrid_maxbounce = {CVAR_SAVE, "r_shadow_bouncegrid_maxbounce", "2", "maximum number of bounces for a particle (minimum is 0)"};
333 cvar_t r_shadow_bouncegrid_particlebounceintensity = {CVAR_SAVE, "r_shadow_bouncegrid_particlebounceintensity", "1", "amount of energy carried over after each bounce, this is a multiplier of texture color and the result is clamped to 1 or less, to prevent adding energy on each bounce"};
334 cvar_t r_shadow_bouncegrid_particleintensity = {CVAR_SAVE, "r_shadow_bouncegrid_particleintensity", "1", "brightness of particles contributing to bouncegrid texture"};
335 cvar_t r_shadow_bouncegrid_photons = {CVAR_SAVE, "r_shadow_bouncegrid_photons", "2000", "total photons to shoot per update, divided proportionately between lights"};
336 cvar_t r_shadow_bouncegrid_spacing = {CVAR_SAVE, "r_shadow_bouncegrid_spacing", "64", "unit size of bouncegrid pixel"};
337 cvar_t r_shadow_bouncegrid_stablerandom = {CVAR_SAVE, "r_shadow_bouncegrid_stablerandom", "1", "make particle distribution consistent from frame to frame"};
338 cvar_t r_shadow_bouncegrid_static = {CVAR_SAVE, "r_shadow_bouncegrid_static", "1", "use static radiosity solution (high quality) rather than dynamic (splotchy)"};
339 cvar_t r_shadow_bouncegrid_static_directionalshading = {CVAR_SAVE, "r_shadow_bouncegrid_static_directionalshading", "1", "whether to use directionalshading when in static mode"};
340 cvar_t r_shadow_bouncegrid_static_lightradiusscale = {CVAR_SAVE, "r_shadow_bouncegrid_static_lightradiusscale", "10", "particles stop at this fraction of light radius (can be more than 1) when in static mode"};
341 cvar_t r_shadow_bouncegrid_static_maxbounce = {CVAR_SAVE, "r_shadow_bouncegrid_static_maxbounce", "5", "maximum number of bounces for a particle (minimum is 0) in static mode"};
342 cvar_t r_shadow_bouncegrid_static_photons = {CVAR_SAVE, "r_shadow_bouncegrid_static_photons", "25000", "photons value to use when in static mode"};
343 cvar_t r_shadow_bouncegrid_updateinterval = {CVAR_SAVE, "r_shadow_bouncegrid_updateinterval", "0", "update bouncegrid texture once per this many seconds, useful values are 0, 0.05, or 1000000"};
344 cvar_t r_shadow_bouncegrid_x = {CVAR_SAVE, "r_shadow_bouncegrid_x", "64", "maximum texture size of bouncegrid on X axis"};
345 cvar_t r_shadow_bouncegrid_y = {CVAR_SAVE, "r_shadow_bouncegrid_y", "64", "maximum texture size of bouncegrid on Y axis"};
346 cvar_t r_shadow_bouncegrid_z = {CVAR_SAVE, "r_shadow_bouncegrid_z", "32", "maximum texture size of bouncegrid on Z axis"};
347 cvar_t r_coronas = {CVAR_SAVE, "r_coronas", "1", "brightness of corona flare effects around certain lights, 0 disables corona effects"};
348 cvar_t r_coronas_occlusionsizescale = {CVAR_SAVE, "r_coronas_occlusionsizescale", "0.1", "size of light source for corona occlusion checksum the proportion of hidden pixels controls corona intensity"};
349 cvar_t r_coronas_occlusionquery = {CVAR_SAVE, "r_coronas_occlusionquery", "1", "use GL_ARB_occlusion_query extension if supported (fades coronas according to visibility)"};
350 cvar_t gl_flashblend = {CVAR_SAVE, "gl_flashblend", "0", "render bright coronas for dynamic lights instead of actual lighting, fast but ugly"};
351 cvar_t gl_ext_separatestencil = {0, "gl_ext_separatestencil", "1", "make use of OpenGL 2.0 glStencilOpSeparate or GL_ATI_separate_stencil extension"};
352 cvar_t gl_ext_stenciltwoside = {0, "gl_ext_stenciltwoside", "1", "make use of GL_EXT_stenciltwoside extension (NVIDIA only)"};
353 cvar_t r_editlights = {0, "r_editlights", "0", "enables .rtlights file editing mode"};
354 cvar_t r_editlights_cursordistance = {0, "r_editlights_cursordistance", "1024", "maximum distance of cursor from eye"};
355 cvar_t r_editlights_cursorpushback = {0, "r_editlights_cursorpushback", "0", "how far to pull the cursor back toward the eye"};
356 cvar_t r_editlights_cursorpushoff = {0, "r_editlights_cursorpushoff", "4", "how far to push the cursor off the impacted surface"};
357 cvar_t r_editlights_cursorgrid = {0, "r_editlights_cursorgrid", "4", "snaps cursor to this grid size"};
358 cvar_t r_editlights_quakelightsizescale = {CVAR_SAVE, "r_editlights_quakelightsizescale", "1", "changes size of light entities loaded from a map"};
359 cvar_t r_editlights_drawproperties = {0, "r_editlights_drawproperties", "1", "draw properties of currently selected light"};
360 cvar_t r_editlights_current_origin = {0, "r_editlights_current_origin", "0 0 0", "origin of selected light"};
361 cvar_t r_editlights_current_angles = {0, "r_editlights_current_angles", "0 0 0", "angles of selected light"};
362 cvar_t r_editlights_current_color = {0, "r_editlights_current_color", "1 1 1", "color of selected light"};
363 cvar_t r_editlights_current_radius = {0, "r_editlights_current_radius", "0", "radius of selected light"};
364 cvar_t r_editlights_current_corona = {0, "r_editlights_current_corona", "0", "corona intensity of selected light"};
365 cvar_t r_editlights_current_coronasize = {0, "r_editlights_current_coronasize", "0", "corona size of selected light"};
366 cvar_t r_editlights_current_style = {0, "r_editlights_current_style", "0", "style of selected light"};
367 cvar_t r_editlights_current_shadows = {0, "r_editlights_current_shadows", "0", "shadows flag of selected light"};
368 cvar_t r_editlights_current_cubemap = {0, "r_editlights_current_cubemap", "0", "cubemap of selected light"};
369 cvar_t r_editlights_current_ambient = {0, "r_editlights_current_ambient", "0", "ambient intensity of selected light"};
370 cvar_t r_editlights_current_diffuse = {0, "r_editlights_current_diffuse", "1", "diffuse intensity of selected light"};
371 cvar_t r_editlights_current_specular = {0, "r_editlights_current_specular", "1", "specular intensity of selected light"};
372 cvar_t r_editlights_current_normalmode = {0, "r_editlights_current_normalmode", "0", "normalmode flag of selected light"};
373 cvar_t r_editlights_current_realtimemode = {0, "r_editlights_current_realtimemode", "0", "realtimemode flag of selected light"};
376 typedef struct r_shadow_bouncegrid_settings_s
379 qboolean bounceanglediffuse;
380 qboolean directionalshading;
381 qboolean includedirectlighting;
382 float dlightparticlemultiplier;
384 float lightradiusscale;
386 float particlebounceintensity;
387 float particleintensity;
392 r_shadow_bouncegrid_settings_t;
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;
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
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];
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;
423 extern int con_vislines;
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);
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;
443 static void R_Shadow_SetShadowMode(void)
445 r_shadow_shadowmapmaxsize = bound(1, r_shadow_shadowmapping_maxsize.integer, (int)vid.maxtexturesize_2d / 4);
446 r_shadow_shadowmapvsdct = r_shadow_shadowmapping_vsdct.integer != 0 && vid.renderpath == RENDERPATH_GL20;
447 r_shadow_shadowmapfilterquality = r_shadow_shadowmapping_filterquality.integer;
448 r_shadow_shadowmapshadowsampler = r_shadow_shadowmapping_useshadowsampler.integer != 0;
449 r_shadow_shadowmapdepthbits = r_shadow_shadowmapping_depthbits.integer;
450 r_shadow_shadowmapborder = bound(0, r_shadow_shadowmapping_bordersize.integer, 16);
451 r_shadow_shadowmaplod = -1;
452 r_shadow_shadowmapsize = 0;
453 r_shadow_shadowmapsampler = false;
454 r_shadow_shadowmappcf = 0;
455 r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL;
456 if ((r_shadow_shadowmapping.integer || r_shadow_deferred.integer) && vid.support.ext_framebuffer_object)
458 switch(vid.renderpath)
460 case RENDERPATH_GL20:
461 if(r_shadow_shadowmapfilterquality < 0)
463 if (!r_fb.usedepthtextures)
464 r_shadow_shadowmappcf = 1;
465 else if(vid.support.amd_texture_texture4 || vid.support.arb_texture_gather)
466 r_shadow_shadowmappcf = 1;
467 else if(strstr(gl_vendor, "NVIDIA") || strstr(gl_renderer, "Radeon HD"))
469 r_shadow_shadowmapsampler = vid.support.arb_shadow && r_shadow_shadowmapshadowsampler;
470 r_shadow_shadowmappcf = 1;
472 else if((strstr(gl_vendor, "ATI") || strstr(gl_vendor, "Advanced Micro Devices")) && !strstr(gl_renderer, "Mesa") && !strstr(gl_version, "Mesa"))
473 r_shadow_shadowmappcf = 1;
475 r_shadow_shadowmapsampler = vid.support.arb_shadow && r_shadow_shadowmapshadowsampler;
479 switch (r_shadow_shadowmapfilterquality)
482 r_shadow_shadowmapsampler = vid.support.arb_shadow && r_shadow_shadowmapshadowsampler;
485 r_shadow_shadowmapsampler = vid.support.arb_shadow && r_shadow_shadowmapshadowsampler;
486 r_shadow_shadowmappcf = 1;
489 r_shadow_shadowmappcf = 1;
492 r_shadow_shadowmappcf = 2;
496 if (!r_fb.usedepthtextures)
497 r_shadow_shadowmapsampler = false;
498 r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D;
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;
508 case RENDERPATH_GL11:
509 case RENDERPATH_GL13:
510 case RENDERPATH_GLES1:
511 case RENDERPATH_GLES2:
516 if(R_CompileShader_CheckStaticParms())
520 qboolean R_Shadow_ShadowMappingEnabled(void)
522 switch (r_shadow_shadowmode)
524 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
531 static void R_Shadow_FreeShadowMaps(void)
533 R_Shadow_SetShadowMode();
535 R_Mesh_DestroyFramebufferObject(r_shadow_fbo2d);
539 if (r_shadow_shadowmap2ddepthtexture)
540 R_FreeTexture(r_shadow_shadowmap2ddepthtexture);
541 r_shadow_shadowmap2ddepthtexture = NULL;
543 if (r_shadow_shadowmap2ddepthbuffer)
544 R_FreeTexture(r_shadow_shadowmap2ddepthbuffer);
545 r_shadow_shadowmap2ddepthbuffer = NULL;
547 if (r_shadow_shadowmapvsdcttexture)
548 R_FreeTexture(r_shadow_shadowmapvsdcttexture);
549 r_shadow_shadowmapvsdcttexture = NULL;
552 static void r_shadow_start(void)
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;
577 R_Shadow_FreeShadowMaps();
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;
594 shadowmarklist = 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;
613 r_shadow_usingdeferredprepass = false;
614 r_shadow_prepass_width = r_shadow_prepass_height = 0;
617 static void R_Shadow_FreeDeferred(void);
618 static void r_shadow_shutdown(void)
621 R_Shadow_UncompileWorldLights();
623 R_Shadow_FreeShadowMaps();
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;
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;
643 Mem_Free(shadowelements);
644 shadowelements = NULL;
646 Mem_Free(shadowvertex3f);
647 shadowvertex3f = NULL;
650 Mem_Free(vertexupdate);
653 Mem_Free(vertexremap);
659 Mem_Free(shadowmark);
662 Mem_Free(shadowmarklist);
663 shadowmarklist = NULL;
668 Mem_Free(shadowsides);
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);
701 static void r_shadow_newmap(void)
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();
715 void R_Shadow_Init(void)
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;
808 shadowmarklist = 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);
827 matrix4x4_t matrix_attenuationxyz =
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},
837 matrix4x4_t matrix_attenuationz =
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},
847 static void R_Shadow_ResizeShadowArrays(int numvertices, int numtriangles, int vertscale, int triscale)
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)
854 maxshadowtriangles = numtriangles;
856 Mem_Free(shadowelements);
857 shadowelements = (int *)Mem_Alloc(r_main_mempool, maxshadowtriangles * sizeof(int[3]));
859 // make sure shadowvertex3f is big enough for this volume
860 if (maxshadowvertices < numvertices)
862 maxshadowvertices = numvertices;
864 Mem_Free(shadowvertex3f);
865 shadowvertex3f = (float *)Mem_Alloc(r_main_mempool, maxshadowvertices * sizeof(float[3]));
869 static void R_Shadow_EnlargeLeafSurfaceTrisBuffer(int numleafs, int numsurfaces, int numshadowtriangles, int numlighttriangles)
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)
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));
888 if (r_shadow_buffer_numsurfacepvsbytes < numsurfacepvsbytes)
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));
901 if (r_shadow_buffer_numshadowtrispvsbytes < numshadowtrispvsbytes)
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);
908 if (r_shadow_buffer_numlighttrispvsbytes < numlighttrispvsbytes)
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);
917 void R_Shadow_PrepareShadowMark(int numtris)
919 // make sure shadowmark is big enough for this volume
920 if (maxshadowmark < numtris)
922 maxshadowmark = numtris;
924 Mem_Free(shadowmark);
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));
932 // if shadowmarkcount wrapped we clear the array and adjust accordingly
933 if (shadowmarkcount == 0)
936 memset(shadowmark, 0, maxshadowmark * sizeof(*shadowmark));
941 void R_Shadow_PrepareShadowSides(int numtris)
943 if (maxshadowsides < numtris)
945 maxshadowsides = numtris;
947 Mem_Free(shadowsides);
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));
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)
959 int outtriangles = 0, outvertices = 0;
962 float ratio, direction[3], projectvector[3];
964 if (projectdirection)
965 VectorScale(projectdirection, projectdistance, projectvector);
967 VectorClear(projectvector);
969 // create the vertices
970 if (projectdirection)
972 for (i = 0;i < numshadowmarktris;i++)
974 element = inelement3i + shadowmarktris[i] * 3;
975 for (j = 0;j < 3;j++)
977 if (vertexupdate[element[j]] != vertexupdatenum)
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));
993 for (i = 0;i < numshadowmarktris;i++)
995 element = inelement3i + shadowmarktris[i] * 3;
996 for (j = 0;j < 3;j++)
998 if (vertexupdate[element[j]] != vertexupdatenum)
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));
1016 if (r_shadow_frontsidecasting.integer)
1018 for (i = 0;i < numshadowmarktris;i++)
1020 int remappedelement[3];
1022 const int *neighbortriangle;
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;
1037 // output the sides (facing outward from this triangle)
1038 if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
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;
1052 if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
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;
1066 if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
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;
1084 for (i = 0;i < numshadowmarktris;i++)
1086 int remappedelement[3];
1088 const int *neighbortriangle;
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;
1103 // output the sides (facing outward from this triangle)
1104 if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
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;
1118 if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
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;
1132 if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
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;
1149 *outnumvertices = outvertices;
1150 return outtriangles;
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)
1156 int outtriangles = 0, outvertices = 0;
1158 const float *vertex;
1159 float ratio, direction[3], projectvector[3];
1162 if (projectdirection)
1163 VectorScale(projectdirection, projectdistance, projectvector);
1165 VectorClear(projectvector);
1167 for (i = 0;i < numshadowmarktris;i++)
1169 int remappedelement[3];
1171 const int *neighbortriangle;
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)
1182 element = inelement3i + markindex;
1184 // create the vertices
1185 for (j = 0;j < 3;j++)
1187 if (side[j] + side[j+1] == 0)
1190 if (vertexupdate[k] != vertexupdatenum)
1192 vertexupdate[k] = vertexupdatenum;
1193 vertexremap[k] = outvertices;
1194 vertex = invertex3f + k * 3;
1195 VectorCopy(vertex, outvertex3f);
1196 if (projectdirection)
1198 // project one copy of the vertex according to projectvector
1199 VectorAdd(vertex, projectvector, (outvertex3f + 3));
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));
1214 // output the sides (facing outward from this triangle)
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;
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;
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;
1259 *outnumvertices = outvertices;
1260 return outtriangles;
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)
1269 if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1271 tend = firsttriangle + numtris;
1272 if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1274 // surface box entirely inside light box, no box cull
1275 if (projectdirection)
1277 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
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;
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;
1293 // surface box not entirely inside light box, cull each triangle
1294 if (projectdirection)
1296 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1298 v[0] = invertex3f + e[0] * 3;
1299 v[1] = invertex3f + e[1] * 3;
1300 v[2] = invertex3f + e[2] * 3;
1301 TriangleNormal(v[0], v[1], v[2], normal);
1302 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1303 && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1304 shadowmarklist[numshadowmark++] = t;
1309 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1311 v[0] = invertex3f + e[0] * 3;
1312 v[1] = invertex3f + e[1] * 3;
1313 v[2] = invertex3f + e[2] * 3;
1314 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1315 && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1316 shadowmarklist[numshadowmark++] = t;
1322 static qboolean R_Shadow_UseZPass(vec3_t mins, vec3_t maxs)
1327 if (r_shadow_compilingrtlight || !r_shadow_frontsidecasting.integer || !r_shadow_usezpassifpossible.integer)
1329 // check if the shadow volume intersects the near plane
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.
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)
1342 int i, tris, outverts;
1343 if (projectdistance < 0.1)
1345 Con_Printf("R_Shadow_Volume: projectdistance %f\n", projectdistance);
1348 if (!numverts || !nummarktris)
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);
1354 if (maxvertexupdate < numverts)
1356 maxvertexupdate = numverts;
1358 Mem_Free(vertexupdate);
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;
1366 if (vertexupdatenum == 0)
1368 vertexupdatenum = 1;
1369 memset(vertexupdate, 0, maxvertexupdate * sizeof(int));
1370 memset(vertexremap, 0, maxvertexupdate * sizeof(int));
1373 for (i = 0;i < nummarktris;i++)
1374 shadowmark[marktris[i]] = shadowmarkcount;
1376 if (r_shadow_compilingrtlight)
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);
1384 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_VISIBLEVOLUMES)
1386 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1387 R_Mesh_PrepareVertices_Vertex3f(outverts, shadowvertex3f, NULL);
1388 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
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);
1398 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1399 r_refdef.stats.lights_dynamicshadowtriangles += tris;
1400 r_refdef.stats.lights_shadowtriangles += tris;
1401 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
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);
1411 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
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);
1421 R_Mesh_PrepareVertices_Vertex3f(outverts, shadowvertex3f, NULL);
1422 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1426 int R_Shadow_CalcTriangleSideMask(const vec3_t p1, const vec3_t p2, const vec3_t p3, float bias)
1428 // p1, p2, p3 are in the cubemap's local coordinate system
1429 // bias = border/(size - border)
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)
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)
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));
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)
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)
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));
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)
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)
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));
1477 static int R_Shadow_CalcBBoxSideMask(const vec3_t mins, const vec3_t maxs, const matrix4x4_t *worldtolight, const matrix4x4_t *radiustolight, float bias)
1479 vec3_t center, radius, lightcenter, lightradius, pmin, pmax;
1480 float dp1, dn1, ap1, an1, dp2, dn2, ap2, an2;
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);
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)
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)
1499 | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1500 | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
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)
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)
1510 | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1511 | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
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)
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)
1521 | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1522 | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1527 #define R_Shadow_CalcEntitySideMask(ent, worldtolight, radiustolight, bias) R_Shadow_CalcBBoxSideMask((ent)->mins, (ent)->maxs, worldtolight, radiustolight, bias)
1529 int R_Shadow_CalcSphereSideMask(const vec3_t p, float radius, float bias)
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);
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));
1546 static int R_Shadow_CullFrustumSides(rtlight_t *rtlight, float size, float border)
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++)
1558 if (PlaneDiff(o, &r_refdef.view.frustum[i]) > -0.03125)
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);
1566 if (PlaneDiff(o, &r_refdef.view.frustum[4]) >= r_refdef.farclip - r_refdef.nearclip + 0.03125)
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);
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
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++)
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);
1603 // finite version, assumes corners are a finite distance from origin dependent on far plane
1604 for (i = 0;i < 5;i++)
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));
1618 return sides & masks[0] & masks[1] & masks[2] & masks[3] & masks[4] & masks[5];
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)
1629 int mask, surfacemask = 0;
1630 if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1632 bias = r_shadow_shadowmapborder / (float)(r_shadow_shadowmapmaxsize - r_shadow_shadowmapborder);
1633 tend = firsttriangle + numtris;
1634 if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1636 // surface box entirely inside light box, no box cull
1637 if (projectdirection)
1639 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
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))
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;
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;
1659 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
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]))
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;
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;
1679 // surface box not entirely inside light box, cull each triangle
1680 if (projectdirection)
1682 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
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 && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
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;
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;
1703 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
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 && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
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;
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;
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)
1727 int i, j, outtriangles = 0;
1728 int *outelement3i[6];
1729 if (!numverts || !numsidetris || !r_shadow_compilingrtlight)
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);
1736 // compute the offset and size of the separate index lists for each cubemap side
1738 for (i = 0;i < 6;i++)
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];
1746 // gather up the (sparse) triangles into separate index lists for each cubemap side
1747 for (i = 0;i < numsidetris;i++)
1749 const int *element = elements + sidetris[i] * 3;
1750 for (j = 0;j < 6;j++)
1752 if (sides[i] & (1 << j))
1754 outelement3i[j][0] = element[0];
1755 outelement3i[j][1] = element[1];
1756 outelement3i[j][2] = element[2];
1757 outelement3i[j] += 3;
1762 Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap, NULL, NULL, NULL, vertex3f, NULL, NULL, NULL, NULL, outtriangles, shadowelements);
1765 static void R_Shadow_MakeTextures_MakeCorona(void)
1769 unsigned char pixels[32][32][4];
1770 for (y = 0;y < 32;y++)
1772 dy = (y - 15.5f) * (1.0f / 16.0f);
1773 for (x = 0;x < 32;x++)
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;
1784 r_shadow_lightcorona = R_SkinFrame_LoadInternalBGRA("lightcorona", TEXF_FORCELINEAR, &pixels[0][0][0], 32, 32, false);
1787 static unsigned int R_Shadow_MakeTextures_SamplePoint(float x, float y, float z)
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;
1795 static void R_Shadow_MakeTextures(void)
1798 float intensity, dist;
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++)
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);
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)
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);
1832 r_shadow_attenuation3dtexture = NULL;
1835 R_Shadow_MakeTextures_MakeCorona();
1837 // Editor light sprites
1838 r_editlights_sprcursor = R_SkinFrame_LoadInternal8bit("gfx/editlights/cursor", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
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 *)
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 *)
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 *)
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 *)
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 *)
1945 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1948 void R_Shadow_ValidateCvars(void)
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);
1958 void R_Shadow_RenderMode_Begin(void)
1964 R_Shadow_ValidateCvars();
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();
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);
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);
1982 r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
1984 if (gl_ext_separatestencil.integer && vid.support.ati_separate_stencil)
1986 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL;
1987 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL;
1989 else if (gl_ext_stenciltwoside.integer && vid.support.ext_stencil_two_side)
1991 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE;
1992 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE;
1996 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCIL;
1997 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCIL;
2000 switch(vid.renderpath)
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;
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;
2020 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX;
2026 qglGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);CHECKGLERROR
2027 qglGetIntegerv(GL_READ_BUFFER, &readbuffer);CHECKGLERROR
2028 r_shadow_drawbuffer = drawbuffer;
2029 r_shadow_readbuffer = readbuffer;
2031 r_shadow_cullface_front = r_refdef.view.cullface_front;
2032 r_shadow_cullface_back = r_refdef.view.cullface_back;
2035 void R_Shadow_RenderMode_ActiveLight(const rtlight_t *rtlight)
2037 rsurface.rtlight = rtlight;
2040 void R_Shadow_RenderMode_Reset(void)
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);
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);
2063 void R_Shadow_ClearStencil(void)
2065 GL_Clear(GL_STENCIL_BUFFER_BIT, NULL, 1.0f, 128);
2066 r_refdef.stats.lights_clears++;
2069 void R_Shadow_RenderMode_StencilShadowVolumes(qboolean zpass)
2071 r_shadow_rendermode_t mode = zpass ? r_shadow_shadowingrendermode_zpass : r_shadow_shadowingrendermode_zfail;
2072 if (r_shadow_rendermode == mode)
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);
2080 r_shadow_rendermode = mode;
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);
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);
2096 static void R_Shadow_MakeVSDCT(void)
2098 // maps to a 2x3 texture rectangle with normalized coordinates
2103 // stores abs(dir.xy), offset.xy/2.5
2104 unsigned char data[4*6] =
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>
2113 r_shadow_shadowmapvsdcttexture = R_LoadTextureCubeMap(r_shadow_texturepool, "shadowmapvsdct", 1, data, TEXTYPE_RGBA, TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, -1, NULL);
2116 static void R_Shadow_MakeShadowMap(int side, int size)
2118 switch (r_shadow_shadowmode)
2120 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
2121 if (r_shadow_shadowmap2ddepthtexture) return;
2122 if (r_fb.usedepthtextures)
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);
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);
2140 static void R_Shadow_RenderMode_ShadowMap(int side, int clear, int size)
2142 float nearclip, farclip, bias;
2143 r_viewport_t viewport;
2146 float clearcolor[4];
2147 nearclip = r_shadow_shadowmapping_nearclip.value / rsurface.rtlight->radius;
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;
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;
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;
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);
2175 R_Mesh_SetRenderTargets(fbo2d, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL, NULL);
2176 R_SetupShader_DepthOrShadow(true, r_shadow_shadowmap2ddepthbuffer != NULL);
2177 GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
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)
2188 // completely different meaning than in depthtexture approach
2189 r_shadow_shadowmap_parameters[1] = 0;
2190 r_shadow_shadowmap_parameters[3] = -bias;
2192 Vector4Set(clearcolor, 1,1,1,1);
2193 if (r_shadow_shadowmap2ddepthbuffer)
2194 GL_ColorMask(1,1,1,1);
2196 GL_ColorMask(0,0,0,0);
2197 switch(vid.renderpath)
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
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);
2217 if (r_shadow_shadowmap2ddepthbuffer)
2218 GL_Clear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
2220 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
2223 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
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);
2235 if (r_shadow_shadowmap2ddepthbuffer)
2236 GL_Clear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
2238 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
2244 void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qboolean shadowmapping)
2246 R_Mesh_ResetTextureState();
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;
2254 R_Shadow_RenderMode_Reset();
2255 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
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)
2266 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2268 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
2271 static const unsigned short bboxelements[36] =
2281 static const float bboxpoints[8][3] =
2293 void R_Shadow_RenderMode_DrawDeferredLight(qboolean stenciltest, qboolean shadowmapping)
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);
2309 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
2311 r_shadow_usingshadowmap2d = shadowmapping;
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);
2322 GL_DepthFunc(GL_GREATER);
2323 GL_CullFace(r_refdef.view.cullface_back);
2324 R_Mesh_PrepareVertices_Vertex3f(8, vertex3f, NULL);
2325 R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
2328 void R_Shadow_UpdateBounceGridTexture(void)
2330 #define MAXBOUNCEGRIDPARTICLESPERLIGHT 1048576
2332 int flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
2334 int hitsupercontentsmask;
2343 //trace_t cliptrace2;
2344 //trace_t cliptrace3;
2345 unsigned char *pixel;
2346 unsigned char *pixels;
2349 unsigned int lightindex;
2351 unsigned int range1;
2352 unsigned int range2;
2353 unsigned int seed = (unsigned int)(realtime * 1000.0f);
2355 vec3_t baseshotcolor;
2368 vec3_t cullmins, cullmaxs;
2371 vec_t lightintensity;
2372 vec_t photonscaling;
2373 vec_t photonresidual;
2375 float texlerp[2][3];
2376 float splatcolor[32];
2377 float pixelweight[8];
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)
2394 case RENDERPATH_GL20:
2395 allowdirectionalshading = true;
2396 if (!vid.support.ext_texture_3d)
2399 case RENDERPATH_GLES2:
2400 // for performance reasons, do not use directional shading on GLES devices
2401 if (!vid.support.ext_texture_3d)
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:
2415 r_shadow_bouncegridintensity = r_shadow_bouncegrid_intensity.value;
2417 // see if there are really any lights to render...
2418 if (enable && r_shadow_bouncegrid_static.integer)
2421 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
2422 for (lightindex = 0;lightindex < range;lightindex++)
2424 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2425 if (!light || !(light->flags & flag))
2427 rtlight = &light->rtlight;
2428 // when static, we skip styled lights because they tend to change...
2429 if (rtlight->style > 0)
2431 VectorScale(rtlight->color, (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale), lightcolor);
2432 if (!VectorLength2(lightcolor))
2441 if (r_shadow_bouncegridtexture)
2443 R_FreeTexture(r_shadow_bouncegridtexture);
2444 r_shadow_bouncegridtexture = NULL;
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;
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;
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);
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];
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)
2505 resolution[0] = c[0];
2506 resolution[1] = c[1];
2507 resolution[2] = c[2];
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) ;
2515 size[0] = spacing[0] * resolution[0];
2516 size[1] = spacing[1] * resolution[1];
2517 size[2] = spacing[2] * resolution[2];
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]))
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)
2533 resolution[0] = c[0];
2534 resolution[1] = c[1];
2535 resolution[2] = c[2];
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) ;
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];
2552 // recalculate the maxs in case the resolution was not satisfactory
2553 VectorAdd(mins, size, maxs);
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)))
2559 // store the new settings
2560 r_shadow_bouncegridsettings = settings;
2562 pixelbands = settings.directionalshading ? 8 : 1;
2563 pixelsperband = resolution[0]*resolution[1]*resolution[2];
2564 numpixels = pixelsperband*pixelbands;
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];
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)
2579 if (r_shadow_bouncegridtexture)
2581 R_FreeTexture(r_shadow_bouncegridtexture);
2582 r_shadow_bouncegridtexture = NULL;
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]));
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++)
2594 memset(pixels + pixelband * x, 128, x);
2596 memset(pixels + pixelband * x, 0, x);
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;
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 = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
2609 range1 = settings.staticmode ? 0 : r_refdef.scene.numlights;
2610 range2 = range + range1;
2612 for (lightindex = 0;lightindex < range2;lightindex++)
2614 if (lightindex < range)
2616 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2619 rtlight = &light->rtlight;
2620 VectorClear(rtlight->photoncolor);
2621 rtlight->photons = 0;
2622 if (!(light->flags & flag))
2624 if (settings.staticmode)
2626 // when static, we skip styled lights because they tend to change...
2627 if (rtlight->style > 0 && r_shadow_bouncegrid.integer != 2)
2633 rtlight = r_refdef.scene.lights[lightindex - range];
2634 VectorClear(rtlight->photoncolor);
2635 rtlight->photons = 0;
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))
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))
2651 w = r_shadow_lightintensityscale.value * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale);
2652 if (w * VectorLength2(rtlight->color) == 0.0f)
2654 w *= (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1);
2655 VectorScale(rtlight->color, w, rtlight->photoncolor);
2656 //if (!VectorLength2(rtlight->photoncolor))
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;
2670 photonscaling = (float)settings.photons / max(1, photoncount);
2671 photonresidual = 0.0f;
2672 for (lightindex = 0;lightindex < range2;lightindex++)
2674 if (lightindex < range)
2676 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2679 rtlight = &light->rtlight;
2682 rtlight = r_refdef.scene.lights[lightindex - range];
2683 // skip a light with no photons
2684 if (rtlight->photons == 0.0f)
2686 // skip a light with no photon color)
2687 if (VectorLength2(rtlight->photoncolor) == 0.0f)
2689 photonresidual += rtlight->photons * photonscaling;
2690 shootparticles = (int)bound(0, photonresidual, MAXBOUNCEGRIDPARTICLESPERLIGHT);
2691 if (!shootparticles)
2693 photonresidual -= shootparticles;
2694 radius = rtlight->radius * settings.lightradiusscale;
2695 s = settings.particleintensity / shootparticles;
2696 VectorScale(rtlight->photoncolor, s, baseshotcolor);
2697 r_refdef.stats.bouncegrid_lights++;
2698 r_refdef.stats.bouncegrid_particles += shootparticles;
2699 for (shotparticles = 0;shotparticles < shootparticles;shotparticles++)
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);
2708 VectorCheeseRandom(clipend);
2709 VectorMA(clipstart, radius, clipend, clipend);
2710 for (bouncecount = 0;;bouncecount++)
2712 r_refdef.stats.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)
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, true, false, NULL, true, true);
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);
2725 if (bouncecount > 0 || settings.includedirectlighting)
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;
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;
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;
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++)
2778 r_refdef.stats.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)
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++)
2808 for (corner = 0;corner < 8;corner++)
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
2821 // advance to next band of coefficients
2822 //pixel += pixelsperband*4;
2823 //highpixel += pixelsperband*4;
2827 VectorAdd(steppos, stepdelta, steppos);
2830 if (cliptrace.fraction >= 1.0f)
2832 r_refdef.stats.bouncegrid_hits++;
2833 if (bouncecount >= maxbounce)
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);
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)
2848 r_refdef.stats.bouncegrid_bounces++;
2849 if (settings.bounceanglediffuse)
2851 // random direction, primarily along plane normal
2852 s = VectorDistance(cliptrace.endpos, clipend);
2853 if (settings.stablerandom < 0)
2854 VectorRandom(clipend);
2856 VectorCheeseRandom(clipend);
2857 VectorMA(cliptrace.plane.normal, 0.95f, clipend, clipend);
2858 VectorNormalize(clipend);
2859 VectorScale(clipend, s, clipend);
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);
2867 // calculate the new line start and end
2868 VectorCopy(cliptrace.endpos, clipstart);
2869 VectorAdd(clipstart, clipend, clipend);
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++)
2878 for (z = 1;z < resolution[2]-1;z++)
2880 for (y = 1;y < resolution[1]-1;y++)
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)
2884 // only convert pixels that were hit by photons
2885 if (pixel[3] == 255)
2887 // normalize the bentnormal...
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);
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);
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);
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);
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);
2922 r_shadow_bouncegridtime = realtime;
2925 void R_Shadow_RenderMode_VisibleShadowVolumes(void)
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;
2937 void R_Shadow_RenderMode_VisibleLighting(qboolean stenciltest, qboolean transparent)
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);
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;
2950 void R_Shadow_RenderMode_End(void)
2952 R_Shadow_RenderMode_Reset();
2953 R_Shadow_RenderMode_ActiveLight(NULL);
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;
2959 int bboxedges[12][2] =
2978 qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
2980 if (!r_shadow_scissor.integer || r_shadow_usingdeferredprepass || r_trippy.integer)
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;
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.lights_scissored++;
2998 static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int numverts, const float *diffusecolor, const float *ambientcolor)
3001 const float *vertex3f;
3002 const float *normal3f;
3004 float dist, dot, distintensity, shadeintensity, v[3], n[3];
3005 switch (r_shadow_rendermode)