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;
205 qboolean r_shadow_shadowmapdepthtexture;
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", "0", "brightness of corona flare effects around certain lights, 0 disables corona effects"};
348 cvar_t r_coronas_occlusionsizescale = {CVAR_SAVE, "r_coronas_occlusionsizescale", "0.1", "size of light source for corona occlusion checksum the proportion of hidden pixels controls corona intensity"};
349 cvar_t r_coronas_occlusionquery = {CVAR_SAVE, "r_coronas_occlusionquery", "0", "use GL_ARB_occlusion_query extension if supported (fades coronas according to visibility) - bad performance (synchronous rendering) - worse on multi-gpu!"};
350 cvar_t gl_flashblend = {CVAR_SAVE, "gl_flashblend", "0", "render bright coronas for dynamic lights instead of actual lighting, fast but ugly"};
351 cvar_t gl_ext_separatestencil = {0, "gl_ext_separatestencil", "1", "make use of OpenGL 2.0 glStencilOpSeparate or GL_ATI_separate_stencil extension"};
352 cvar_t gl_ext_stenciltwoside = {0, "gl_ext_stenciltwoside", "1", "make use of GL_EXT_stenciltwoside extension (NVIDIA only)"};
353 cvar_t r_editlights = {0, "r_editlights", "0", "enables .rtlights file editing mode"};
354 cvar_t r_editlights_cursordistance = {0, "r_editlights_cursordistance", "1024", "maximum distance of cursor from eye"};
355 cvar_t r_editlights_cursorpushback = {0, "r_editlights_cursorpushback", "0", "how far to pull the cursor back toward the eye"};
356 cvar_t r_editlights_cursorpushoff = {0, "r_editlights_cursorpushoff", "4", "how far to push the cursor off the impacted surface"};
357 cvar_t r_editlights_cursorgrid = {0, "r_editlights_cursorgrid", "4", "snaps cursor to this grid size"};
358 cvar_t r_editlights_quakelightsizescale = {CVAR_SAVE, "r_editlights_quakelightsizescale", "1", "changes size of light entities loaded from a map"};
359 cvar_t r_editlights_drawproperties = {0, "r_editlights_drawproperties", "1", "draw properties of currently selected light"};
360 cvar_t r_editlights_current_origin = {0, "r_editlights_current_origin", "0 0 0", "origin of selected light"};
361 cvar_t r_editlights_current_angles = {0, "r_editlights_current_angles", "0 0 0", "angles of selected light"};
362 cvar_t r_editlights_current_color = {0, "r_editlights_current_color", "1 1 1", "color of selected light"};
363 cvar_t r_editlights_current_radius = {0, "r_editlights_current_radius", "0", "radius of selected light"};
364 cvar_t r_editlights_current_corona = {0, "r_editlights_current_corona", "0", "corona intensity of selected light"};
365 cvar_t r_editlights_current_coronasize = {0, "r_editlights_current_coronasize", "0", "corona size of selected light"};
366 cvar_t r_editlights_current_style = {0, "r_editlights_current_style", "0", "style of selected light"};
367 cvar_t r_editlights_current_shadows = {0, "r_editlights_current_shadows", "0", "shadows flag of selected light"};
368 cvar_t r_editlights_current_cubemap = {0, "r_editlights_current_cubemap", "0", "cubemap of selected light"};
369 cvar_t r_editlights_current_ambient = {0, "r_editlights_current_ambient", "0", "ambient intensity of selected light"};
370 cvar_t r_editlights_current_diffuse = {0, "r_editlights_current_diffuse", "1", "diffuse intensity of selected light"};
371 cvar_t r_editlights_current_specular = {0, "r_editlights_current_specular", "1", "specular intensity of selected light"};
372 cvar_t r_editlights_current_normalmode = {0, "r_editlights_current_normalmode", "0", "normalmode flag of selected light"};
373 cvar_t r_editlights_current_realtimemode = {0, "r_editlights_current_realtimemode", "0", "realtimemode flag of selected light"};
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_shadowmapdepthtexture = r_fb.usedepthtextures;
456 r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL;
457 if ((r_shadow_shadowmapping.integer || r_shadow_deferred.integer) && vid.support.ext_framebuffer_object)
459 switch(vid.renderpath)
461 case RENDERPATH_GL20:
462 if(r_shadow_shadowmapfilterquality < 0)
464 if (!r_fb.usedepthtextures)
465 r_shadow_shadowmappcf = 1;
466 else if((strstr(gl_vendor, "NVIDIA") || strstr(gl_renderer, "Radeon HD")) && vid.support.arb_shadow && r_shadow_shadowmapshadowsampler)
468 r_shadow_shadowmapsampler = true;
469 r_shadow_shadowmappcf = 1;
471 else if(vid.support.amd_texture_texture4 || vid.support.arb_texture_gather)
472 r_shadow_shadowmappcf = 1;
473 else if((strstr(gl_vendor, "ATI") || strstr(gl_vendor, "Advanced Micro Devices")) && !strstr(gl_renderer, "Mesa") && !strstr(gl_version, "Mesa"))
474 r_shadow_shadowmappcf = 1;
476 r_shadow_shadowmapsampler = vid.support.arb_shadow && r_shadow_shadowmapshadowsampler;
480 switch (r_shadow_shadowmapfilterquality)
483 r_shadow_shadowmapsampler = vid.support.arb_shadow && r_shadow_shadowmapshadowsampler;
486 r_shadow_shadowmapsampler = vid.support.arb_shadow && r_shadow_shadowmapshadowsampler;
487 r_shadow_shadowmappcf = 1;
490 r_shadow_shadowmappcf = 1;
493 r_shadow_shadowmappcf = 2;
497 if (!r_fb.usedepthtextures)
498 r_shadow_shadowmapsampler = false;
499 r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D;
501 case RENDERPATH_D3D9:
502 case RENDERPATH_D3D10:
503 case RENDERPATH_D3D11:
504 case RENDERPATH_SOFT:
505 r_shadow_shadowmapsampler = false;
506 r_shadow_shadowmappcf = 1;
507 r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D;
509 case RENDERPATH_GL11:
510 case RENDERPATH_GL13:
511 case RENDERPATH_GLES1:
512 case RENDERPATH_GLES2:
517 if(R_CompileShader_CheckStaticParms())
521 qboolean R_Shadow_ShadowMappingEnabled(void)
523 switch (r_shadow_shadowmode)
525 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
532 static void R_Shadow_FreeShadowMaps(void)
534 R_Shadow_SetShadowMode();
536 R_Mesh_DestroyFramebufferObject(r_shadow_fbo2d);
540 if (r_shadow_shadowmap2ddepthtexture)
541 R_FreeTexture(r_shadow_shadowmap2ddepthtexture);
542 r_shadow_shadowmap2ddepthtexture = NULL;
544 if (r_shadow_shadowmap2ddepthbuffer)
545 R_FreeTexture(r_shadow_shadowmap2ddepthbuffer);
546 r_shadow_shadowmap2ddepthbuffer = NULL;
548 if (r_shadow_shadowmapvsdcttexture)
549 R_FreeTexture(r_shadow_shadowmapvsdcttexture);
550 r_shadow_shadowmapvsdcttexture = NULL;
553 static void r_shadow_start(void)
555 // allocate vertex processing arrays
556 r_shadow_bouncegridpixels = NULL;
557 r_shadow_bouncegridhighpixels = NULL;
558 r_shadow_bouncegridnumpixels = 0;
559 r_shadow_bouncegridtexture = NULL;
560 r_shadow_bouncegriddirectional = false;
561 r_shadow_attenuationgradienttexture = NULL;
562 r_shadow_attenuation2dtexture = NULL;
563 r_shadow_attenuation3dtexture = NULL;
564 r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL;
565 r_shadow_shadowmap2ddepthtexture = NULL;
566 r_shadow_shadowmap2ddepthbuffer = NULL;
567 r_shadow_shadowmapvsdcttexture = NULL;
568 r_shadow_shadowmapmaxsize = 0;
569 r_shadow_shadowmapsize = 0;
570 r_shadow_shadowmaplod = 0;
571 r_shadow_shadowmapfilterquality = -1;
572 r_shadow_shadowmapdepthbits = 0;
573 r_shadow_shadowmapvsdct = false;
574 r_shadow_shadowmapsampler = false;
575 r_shadow_shadowmappcf = 0;
578 R_Shadow_FreeShadowMaps();
580 r_shadow_texturepool = NULL;
581 r_shadow_filters_texturepool = NULL;
582 R_Shadow_ValidateCvars();
583 R_Shadow_MakeTextures();
584 maxshadowtriangles = 0;
585 shadowelements = NULL;
586 maxshadowvertices = 0;
587 shadowvertex3f = NULL;
595 shadowmarklist = NULL;
600 shadowsideslist = NULL;
601 r_shadow_buffer_numleafpvsbytes = 0;
602 r_shadow_buffer_visitingleafpvs = NULL;
603 r_shadow_buffer_leafpvs = NULL;
604 r_shadow_buffer_leaflist = NULL;
605 r_shadow_buffer_numsurfacepvsbytes = 0;
606 r_shadow_buffer_surfacepvs = NULL;
607 r_shadow_buffer_surfacelist = NULL;
608 r_shadow_buffer_surfacesides = NULL;
609 r_shadow_buffer_numshadowtrispvsbytes = 0;
610 r_shadow_buffer_shadowtrispvs = NULL;
611 r_shadow_buffer_numlighttrispvsbytes = 0;
612 r_shadow_buffer_lighttrispvs = NULL;
614 r_shadow_usingdeferredprepass = false;
615 r_shadow_prepass_width = r_shadow_prepass_height = 0;
618 static void R_Shadow_FreeDeferred(void);
619 static void r_shadow_shutdown(void)
622 R_Shadow_UncompileWorldLights();
624 R_Shadow_FreeShadowMaps();
626 r_shadow_usingdeferredprepass = false;
627 if (r_shadow_prepass_width)
628 R_Shadow_FreeDeferred();
629 r_shadow_prepass_width = r_shadow_prepass_height = 0;
632 r_shadow_bouncegridtexture = NULL;
633 r_shadow_bouncegridpixels = NULL;
634 r_shadow_bouncegridhighpixels = NULL;
635 r_shadow_bouncegridnumpixels = 0;
636 r_shadow_bouncegriddirectional = false;
637 r_shadow_attenuationgradienttexture = NULL;
638 r_shadow_attenuation2dtexture = NULL;
639 r_shadow_attenuation3dtexture = NULL;
640 R_FreeTexturePool(&r_shadow_texturepool);
641 R_FreeTexturePool(&r_shadow_filters_texturepool);
642 maxshadowtriangles = 0;
644 Mem_Free(shadowelements);
645 shadowelements = NULL;
647 Mem_Free(shadowvertex3f);
648 shadowvertex3f = NULL;
651 Mem_Free(vertexupdate);
654 Mem_Free(vertexremap);
660 Mem_Free(shadowmark);
663 Mem_Free(shadowmarklist);
664 shadowmarklist = NULL;
669 Mem_Free(shadowsides);
672 Mem_Free(shadowsideslist);
673 shadowsideslist = NULL;
674 r_shadow_buffer_numleafpvsbytes = 0;
675 if (r_shadow_buffer_visitingleafpvs)
676 Mem_Free(r_shadow_buffer_visitingleafpvs);
677 r_shadow_buffer_visitingleafpvs = NULL;
678 if (r_shadow_buffer_leafpvs)
679 Mem_Free(r_shadow_buffer_leafpvs);
680 r_shadow_buffer_leafpvs = NULL;
681 if (r_shadow_buffer_leaflist)
682 Mem_Free(r_shadow_buffer_leaflist);
683 r_shadow_buffer_leaflist = NULL;
684 r_shadow_buffer_numsurfacepvsbytes = 0;
685 if (r_shadow_buffer_surfacepvs)
686 Mem_Free(r_shadow_buffer_surfacepvs);
687 r_shadow_buffer_surfacepvs = NULL;
688 if (r_shadow_buffer_surfacelist)
689 Mem_Free(r_shadow_buffer_surfacelist);
690 r_shadow_buffer_surfacelist = NULL;
691 if (r_shadow_buffer_surfacesides)
692 Mem_Free(r_shadow_buffer_surfacesides);
693 r_shadow_buffer_surfacesides = NULL;
694 r_shadow_buffer_numshadowtrispvsbytes = 0;
695 if (r_shadow_buffer_shadowtrispvs)
696 Mem_Free(r_shadow_buffer_shadowtrispvs);
697 r_shadow_buffer_numlighttrispvsbytes = 0;
698 if (r_shadow_buffer_lighttrispvs)
699 Mem_Free(r_shadow_buffer_lighttrispvs);
702 static void r_shadow_newmap(void)
704 if (r_shadow_bouncegridtexture) R_FreeTexture(r_shadow_bouncegridtexture);r_shadow_bouncegridtexture = NULL;
705 if (r_shadow_lightcorona) R_SkinFrame_MarkUsed(r_shadow_lightcorona);
706 if (r_editlights_sprcursor) R_SkinFrame_MarkUsed(r_editlights_sprcursor);
707 if (r_editlights_sprlight) R_SkinFrame_MarkUsed(r_editlights_sprlight);
708 if (r_editlights_sprnoshadowlight) R_SkinFrame_MarkUsed(r_editlights_sprnoshadowlight);
709 if (r_editlights_sprcubemaplight) R_SkinFrame_MarkUsed(r_editlights_sprcubemaplight);
710 if (r_editlights_sprcubemapnoshadowlight) R_SkinFrame_MarkUsed(r_editlights_sprcubemapnoshadowlight);
711 if (r_editlights_sprselection) R_SkinFrame_MarkUsed(r_editlights_sprselection);
712 if (strncmp(cl.worldname, r_shadow_mapname, sizeof(r_shadow_mapname)))
713 R_Shadow_EditLights_Reload_f();
716 void R_Shadow_Init(void)
718 Cvar_RegisterVariable(&r_shadow_bumpscale_basetexture);
719 Cvar_RegisterVariable(&r_shadow_bumpscale_bumpmap);
720 Cvar_RegisterVariable(&r_shadow_usebihculling);
721 Cvar_RegisterVariable(&r_shadow_usenormalmap);
722 Cvar_RegisterVariable(&r_shadow_debuglight);
723 Cvar_RegisterVariable(&r_shadow_deferred);
724 Cvar_RegisterVariable(&r_shadow_gloss);
725 Cvar_RegisterVariable(&r_shadow_gloss2intensity);
726 Cvar_RegisterVariable(&r_shadow_glossintensity);
727 Cvar_RegisterVariable(&r_shadow_glossexponent);
728 Cvar_RegisterVariable(&r_shadow_gloss2exponent);
729 Cvar_RegisterVariable(&r_shadow_glossexact);
730 Cvar_RegisterVariable(&r_shadow_lightattenuationdividebias);
731 Cvar_RegisterVariable(&r_shadow_lightattenuationlinearscale);
732 Cvar_RegisterVariable(&r_shadow_lightintensityscale);
733 Cvar_RegisterVariable(&r_shadow_lightradiusscale);
734 Cvar_RegisterVariable(&r_shadow_projectdistance);
735 Cvar_RegisterVariable(&r_shadow_frontsidecasting);
736 Cvar_RegisterVariable(&r_shadow_realtime_dlight);
737 Cvar_RegisterVariable(&r_shadow_realtime_dlight_shadows);
738 Cvar_RegisterVariable(&r_shadow_realtime_dlight_svbspculling);
739 Cvar_RegisterVariable(&r_shadow_realtime_dlight_portalculling);
740 Cvar_RegisterVariable(&r_shadow_realtime_world);
741 Cvar_RegisterVariable(&r_shadow_realtime_world_lightmaps);
742 Cvar_RegisterVariable(&r_shadow_realtime_world_shadows);
743 Cvar_RegisterVariable(&r_shadow_realtime_world_compile);
744 Cvar_RegisterVariable(&r_shadow_realtime_world_compileshadow);
745 Cvar_RegisterVariable(&r_shadow_realtime_world_compilesvbsp);
746 Cvar_RegisterVariable(&r_shadow_realtime_world_compileportalculling);
747 Cvar_RegisterVariable(&r_shadow_scissor);
748 Cvar_RegisterVariable(&r_shadow_shadowmapping);
749 Cvar_RegisterVariable(&r_shadow_shadowmapping_vsdct);
750 Cvar_RegisterVariable(&r_shadow_shadowmapping_filterquality);
751 Cvar_RegisterVariable(&r_shadow_shadowmapping_useshadowsampler);
752 Cvar_RegisterVariable(&r_shadow_shadowmapping_depthbits);
753 Cvar_RegisterVariable(&r_shadow_shadowmapping_precision);
754 Cvar_RegisterVariable(&r_shadow_shadowmapping_maxsize);
755 Cvar_RegisterVariable(&r_shadow_shadowmapping_minsize);
756 // Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_bias);
757 // Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_scale);
758 Cvar_RegisterVariable(&r_shadow_shadowmapping_bordersize);
759 Cvar_RegisterVariable(&r_shadow_shadowmapping_nearclip);
760 Cvar_RegisterVariable(&r_shadow_shadowmapping_bias);
761 Cvar_RegisterVariable(&r_shadow_shadowmapping_polygonfactor);
762 Cvar_RegisterVariable(&r_shadow_shadowmapping_polygonoffset);
763 Cvar_RegisterVariable(&r_shadow_sortsurfaces);
764 Cvar_RegisterVariable(&r_shadow_polygonfactor);
765 Cvar_RegisterVariable(&r_shadow_polygonoffset);
766 Cvar_RegisterVariable(&r_shadow_texture3d);
767 Cvar_RegisterVariable(&r_shadow_bouncegrid);
768 Cvar_RegisterVariable(&r_shadow_bouncegrid_bounceanglediffuse);
769 Cvar_RegisterVariable(&r_shadow_bouncegrid_directionalshading);
770 Cvar_RegisterVariable(&r_shadow_bouncegrid_dlightparticlemultiplier);
771 Cvar_RegisterVariable(&r_shadow_bouncegrid_hitmodels);
772 Cvar_RegisterVariable(&r_shadow_bouncegrid_includedirectlighting);
773 Cvar_RegisterVariable(&r_shadow_bouncegrid_intensity);
774 Cvar_RegisterVariable(&r_shadow_bouncegrid_lightradiusscale);
775 Cvar_RegisterVariable(&r_shadow_bouncegrid_maxbounce);
776 Cvar_RegisterVariable(&r_shadow_bouncegrid_particlebounceintensity);
777 Cvar_RegisterVariable(&r_shadow_bouncegrid_particleintensity);
778 Cvar_RegisterVariable(&r_shadow_bouncegrid_photons);
779 Cvar_RegisterVariable(&r_shadow_bouncegrid_spacing);
780 Cvar_RegisterVariable(&r_shadow_bouncegrid_stablerandom);
781 Cvar_RegisterVariable(&r_shadow_bouncegrid_static);
782 Cvar_RegisterVariable(&r_shadow_bouncegrid_static_directionalshading);
783 Cvar_RegisterVariable(&r_shadow_bouncegrid_static_lightradiusscale);
784 Cvar_RegisterVariable(&r_shadow_bouncegrid_static_maxbounce);
785 Cvar_RegisterVariable(&r_shadow_bouncegrid_static_photons);
786 Cvar_RegisterVariable(&r_shadow_bouncegrid_updateinterval);
787 Cvar_RegisterVariable(&r_shadow_bouncegrid_x);
788 Cvar_RegisterVariable(&r_shadow_bouncegrid_y);
789 Cvar_RegisterVariable(&r_shadow_bouncegrid_z);
790 Cvar_RegisterVariable(&r_coronas);
791 Cvar_RegisterVariable(&r_coronas_occlusionsizescale);
792 Cvar_RegisterVariable(&r_coronas_occlusionquery);
793 Cvar_RegisterVariable(&gl_flashblend);
794 Cvar_RegisterVariable(&gl_ext_separatestencil);
795 Cvar_RegisterVariable(&gl_ext_stenciltwoside);
796 R_Shadow_EditLights_Init();
797 Mem_ExpandableArray_NewArray(&r_shadow_worldlightsarray, r_main_mempool, sizeof(dlight_t), 128);
798 maxshadowtriangles = 0;
799 shadowelements = NULL;
800 maxshadowvertices = 0;
801 shadowvertex3f = NULL;
809 shadowmarklist = NULL;
814 shadowsideslist = NULL;
815 r_shadow_buffer_numleafpvsbytes = 0;
816 r_shadow_buffer_visitingleafpvs = NULL;
817 r_shadow_buffer_leafpvs = NULL;
818 r_shadow_buffer_leaflist = NULL;
819 r_shadow_buffer_numsurfacepvsbytes = 0;
820 r_shadow_buffer_surfacepvs = NULL;
821 r_shadow_buffer_surfacelist = NULL;
822 r_shadow_buffer_surfacesides = NULL;
823 r_shadow_buffer_shadowtrispvs = NULL;
824 r_shadow_buffer_lighttrispvs = NULL;
825 R_RegisterModule("R_Shadow", r_shadow_start, r_shadow_shutdown, r_shadow_newmap, NULL, NULL);
828 matrix4x4_t matrix_attenuationxyz =
831 {0.5, 0.0, 0.0, 0.5},
832 {0.0, 0.5, 0.0, 0.5},
833 {0.0, 0.0, 0.5, 0.5},
838 matrix4x4_t matrix_attenuationz =
841 {0.0, 0.0, 0.5, 0.5},
842 {0.0, 0.0, 0.0, 0.5},
843 {0.0, 0.0, 0.0, 0.5},
848 static void R_Shadow_ResizeShadowArrays(int numvertices, int numtriangles, int vertscale, int triscale)
850 numvertices = ((numvertices + 255) & ~255) * vertscale;
851 numtriangles = ((numtriangles + 255) & ~255) * triscale;
852 // make sure shadowelements is big enough for this volume
853 if (maxshadowtriangles < numtriangles)
855 maxshadowtriangles = numtriangles;
857 Mem_Free(shadowelements);
858 shadowelements = (int *)Mem_Alloc(r_main_mempool, maxshadowtriangles * sizeof(int[3]));
860 // make sure shadowvertex3f is big enough for this volume
861 if (maxshadowvertices < numvertices)
863 maxshadowvertices = numvertices;
865 Mem_Free(shadowvertex3f);
866 shadowvertex3f = (float *)Mem_Alloc(r_main_mempool, maxshadowvertices * sizeof(float[3]));
870 static void R_Shadow_EnlargeLeafSurfaceTrisBuffer(int numleafs, int numsurfaces, int numshadowtriangles, int numlighttriangles)
872 int numleafpvsbytes = (((numleafs + 7) >> 3) + 255) & ~255;
873 int numsurfacepvsbytes = (((numsurfaces + 7) >> 3) + 255) & ~255;
874 int numshadowtrispvsbytes = (((numshadowtriangles + 7) >> 3) + 255) & ~255;
875 int numlighttrispvsbytes = (((numlighttriangles + 7) >> 3) + 255) & ~255;
876 if (r_shadow_buffer_numleafpvsbytes < numleafpvsbytes)
878 if (r_shadow_buffer_visitingleafpvs)
879 Mem_Free(r_shadow_buffer_visitingleafpvs);
880 if (r_shadow_buffer_leafpvs)
881 Mem_Free(r_shadow_buffer_leafpvs);
882 if (r_shadow_buffer_leaflist)
883 Mem_Free(r_shadow_buffer_leaflist);
884 r_shadow_buffer_numleafpvsbytes = numleafpvsbytes;
885 r_shadow_buffer_visitingleafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
886 r_shadow_buffer_leafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
887 r_shadow_buffer_leaflist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes * 8 * sizeof(*r_shadow_buffer_leaflist));
889 if (r_shadow_buffer_numsurfacepvsbytes < numsurfacepvsbytes)
891 if (r_shadow_buffer_surfacepvs)
892 Mem_Free(r_shadow_buffer_surfacepvs);
893 if (r_shadow_buffer_surfacelist)
894 Mem_Free(r_shadow_buffer_surfacelist);
895 if (r_shadow_buffer_surfacesides)
896 Mem_Free(r_shadow_buffer_surfacesides);
897 r_shadow_buffer_numsurfacepvsbytes = numsurfacepvsbytes;
898 r_shadow_buffer_surfacepvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes);
899 r_shadow_buffer_surfacelist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
900 r_shadow_buffer_surfacesides = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
902 if (r_shadow_buffer_numshadowtrispvsbytes < numshadowtrispvsbytes)
904 if (r_shadow_buffer_shadowtrispvs)
905 Mem_Free(r_shadow_buffer_shadowtrispvs);
906 r_shadow_buffer_numshadowtrispvsbytes = numshadowtrispvsbytes;
907 r_shadow_buffer_shadowtrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numshadowtrispvsbytes);
909 if (r_shadow_buffer_numlighttrispvsbytes < numlighttrispvsbytes)
911 if (r_shadow_buffer_lighttrispvs)
912 Mem_Free(r_shadow_buffer_lighttrispvs);
913 r_shadow_buffer_numlighttrispvsbytes = numlighttrispvsbytes;
914 r_shadow_buffer_lighttrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numlighttrispvsbytes);
918 void R_Shadow_PrepareShadowMark(int numtris)
920 // make sure shadowmark is big enough for this volume
921 if (maxshadowmark < numtris)
923 maxshadowmark = numtris;
925 Mem_Free(shadowmark);
927 Mem_Free(shadowmarklist);
928 shadowmark = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmark));
929 shadowmarklist = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmarklist));
933 // if shadowmarkcount wrapped we clear the array and adjust accordingly
934 if (shadowmarkcount == 0)
937 memset(shadowmark, 0, maxshadowmark * sizeof(*shadowmark));
942 void R_Shadow_PrepareShadowSides(int numtris)
944 if (maxshadowsides < numtris)
946 maxshadowsides = numtris;
948 Mem_Free(shadowsides);
950 Mem_Free(shadowsideslist);
951 shadowsides = (unsigned char *)Mem_Alloc(r_main_mempool, maxshadowsides * sizeof(*shadowsides));
952 shadowsideslist = (int *)Mem_Alloc(r_main_mempool, maxshadowsides * sizeof(*shadowsideslist));
957 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)
960 int outtriangles = 0, outvertices = 0;
963 float ratio, direction[3], projectvector[3];
965 if (projectdirection)
966 VectorScale(projectdirection, projectdistance, projectvector);
968 VectorClear(projectvector);
970 // create the vertices
971 if (projectdirection)
973 for (i = 0;i < numshadowmarktris;i++)
975 element = inelement3i + shadowmarktris[i] * 3;
976 for (j = 0;j < 3;j++)
978 if (vertexupdate[element[j]] != vertexupdatenum)
980 vertexupdate[element[j]] = vertexupdatenum;
981 vertexremap[element[j]] = outvertices;
982 vertex = invertex3f + element[j] * 3;
983 // project one copy of the vertex according to projectvector
984 VectorCopy(vertex, outvertex3f);
985 VectorAdd(vertex, projectvector, (outvertex3f + 3));
994 for (i = 0;i < numshadowmarktris;i++)
996 element = inelement3i + shadowmarktris[i] * 3;
997 for (j = 0;j < 3;j++)
999 if (vertexupdate[element[j]] != vertexupdatenum)
1001 vertexupdate[element[j]] = vertexupdatenum;
1002 vertexremap[element[j]] = outvertices;
1003 vertex = invertex3f + element[j] * 3;
1004 // project one copy of the vertex to the sphere radius of the light
1005 // (FIXME: would projecting it to the light box be better?)
1006 VectorSubtract(vertex, projectorigin, direction);
1007 ratio = projectdistance / VectorLength(direction);
1008 VectorCopy(vertex, outvertex3f);
1009 VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
1017 if (r_shadow_frontsidecasting.integer)
1019 for (i = 0;i < numshadowmarktris;i++)
1021 int remappedelement[3];
1023 const int *neighbortriangle;
1025 markindex = shadowmarktris[i] * 3;
1026 element = inelement3i + markindex;
1027 neighbortriangle = inneighbor3i + markindex;
1028 // output the front and back triangles
1029 outelement3i[0] = vertexremap[element[0]];
1030 outelement3i[1] = vertexremap[element[1]];
1031 outelement3i[2] = vertexremap[element[2]];
1032 outelement3i[3] = vertexremap[element[2]] + 1;
1033 outelement3i[4] = vertexremap[element[1]] + 1;
1034 outelement3i[5] = vertexremap[element[0]] + 1;
1038 // output the sides (facing outward from this triangle)
1039 if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
1041 remappedelement[0] = vertexremap[element[0]];
1042 remappedelement[1] = vertexremap[element[1]];
1043 outelement3i[0] = remappedelement[1];
1044 outelement3i[1] = remappedelement[0];
1045 outelement3i[2] = remappedelement[0] + 1;
1046 outelement3i[3] = remappedelement[1];
1047 outelement3i[4] = remappedelement[0] + 1;
1048 outelement3i[5] = remappedelement[1] + 1;
1053 if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
1055 remappedelement[1] = vertexremap[element[1]];
1056 remappedelement[2] = vertexremap[element[2]];
1057 outelement3i[0] = remappedelement[2];
1058 outelement3i[1] = remappedelement[1];
1059 outelement3i[2] = remappedelement[1] + 1;
1060 outelement3i[3] = remappedelement[2];
1061 outelement3i[4] = remappedelement[1] + 1;
1062 outelement3i[5] = remappedelement[2] + 1;
1067 if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
1069 remappedelement[0] = vertexremap[element[0]];
1070 remappedelement[2] = vertexremap[element[2]];
1071 outelement3i[0] = remappedelement[0];
1072 outelement3i[1] = remappedelement[2];
1073 outelement3i[2] = remappedelement[2] + 1;
1074 outelement3i[3] = remappedelement[0];
1075 outelement3i[4] = remappedelement[2] + 1;
1076 outelement3i[5] = remappedelement[0] + 1;
1085 for (i = 0;i < numshadowmarktris;i++)
1087 int remappedelement[3];
1089 const int *neighbortriangle;
1091 markindex = shadowmarktris[i] * 3;
1092 element = inelement3i + markindex;
1093 neighbortriangle = inneighbor3i + markindex;
1094 // output the front and back triangles
1095 outelement3i[0] = vertexremap[element[2]];
1096 outelement3i[1] = vertexremap[element[1]];
1097 outelement3i[2] = vertexremap[element[0]];
1098 outelement3i[3] = vertexremap[element[0]] + 1;
1099 outelement3i[4] = vertexremap[element[1]] + 1;
1100 outelement3i[5] = vertexremap[element[2]] + 1;
1104 // output the sides (facing outward from this triangle)
1105 if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
1107 remappedelement[0] = vertexremap[element[0]];
1108 remappedelement[1] = vertexremap[element[1]];
1109 outelement3i[0] = remappedelement[0];
1110 outelement3i[1] = remappedelement[1];
1111 outelement3i[2] = remappedelement[1] + 1;
1112 outelement3i[3] = remappedelement[0];
1113 outelement3i[4] = remappedelement[1] + 1;
1114 outelement3i[5] = remappedelement[0] + 1;
1119 if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
1121 remappedelement[1] = vertexremap[element[1]];
1122 remappedelement[2] = vertexremap[element[2]];
1123 outelement3i[0] = remappedelement[1];
1124 outelement3i[1] = remappedelement[2];
1125 outelement3i[2] = remappedelement[2] + 1;
1126 outelement3i[3] = remappedelement[1];
1127 outelement3i[4] = remappedelement[2] + 1;
1128 outelement3i[5] = remappedelement[1] + 1;
1133 if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
1135 remappedelement[0] = vertexremap[element[0]];
1136 remappedelement[2] = vertexremap[element[2]];
1137 outelement3i[0] = remappedelement[2];
1138 outelement3i[1] = remappedelement[0];
1139 outelement3i[2] = remappedelement[0] + 1;
1140 outelement3i[3] = remappedelement[2];
1141 outelement3i[4] = remappedelement[0] + 1;
1142 outelement3i[5] = remappedelement[2] + 1;
1150 *outnumvertices = outvertices;
1151 return outtriangles;
1154 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)
1157 int outtriangles = 0, outvertices = 0;
1159 const float *vertex;
1160 float ratio, direction[3], projectvector[3];
1163 if (projectdirection)
1164 VectorScale(projectdirection, projectdistance, projectvector);
1166 VectorClear(projectvector);
1168 for (i = 0;i < numshadowmarktris;i++)
1170 int remappedelement[3];
1172 const int *neighbortriangle;
1174 markindex = shadowmarktris[i] * 3;
1175 neighbortriangle = inneighbor3i + markindex;
1176 side[0] = shadowmark[neighbortriangle[0]] == shadowmarkcount;
1177 side[1] = shadowmark[neighbortriangle[1]] == shadowmarkcount;
1178 side[2] = shadowmark[neighbortriangle[2]] == shadowmarkcount;
1179 if (side[0] + side[1] + side[2] == 0)
1183 element = inelement3i + markindex;
1185 // create the vertices
1186 for (j = 0;j < 3;j++)
1188 if (side[j] + side[j+1] == 0)
1191 if (vertexupdate[k] != vertexupdatenum)
1193 vertexupdate[k] = vertexupdatenum;
1194 vertexremap[k] = outvertices;
1195 vertex = invertex3f + k * 3;
1196 VectorCopy(vertex, outvertex3f);
1197 if (projectdirection)
1199 // project one copy of the vertex according to projectvector
1200 VectorAdd(vertex, projectvector, (outvertex3f + 3));
1204 // project one copy of the vertex to the sphere radius of the light
1205 // (FIXME: would projecting it to the light box be better?)
1206 VectorSubtract(vertex, projectorigin, direction);
1207 ratio = projectdistance / VectorLength(direction);
1208 VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
1215 // output the sides (facing outward from this triangle)
1218 remappedelement[0] = vertexremap[element[0]];
1219 remappedelement[1] = vertexremap[element[1]];
1220 outelement3i[0] = remappedelement[1];
1221 outelement3i[1] = remappedelement[0];
1222 outelement3i[2] = remappedelement[0] + 1;
1223 outelement3i[3] = remappedelement[1];
1224 outelement3i[4] = remappedelement[0] + 1;
1225 outelement3i[5] = remappedelement[1] + 1;
1232 remappedelement[1] = vertexremap[element[1]];
1233 remappedelement[2] = vertexremap[element[2]];
1234 outelement3i[0] = remappedelement[2];
1235 outelement3i[1] = remappedelement[1];
1236 outelement3i[2] = remappedelement[1] + 1;
1237 outelement3i[3] = remappedelement[2];
1238 outelement3i[4] = remappedelement[1] + 1;
1239 outelement3i[5] = remappedelement[2] + 1;
1246 remappedelement[0] = vertexremap[element[0]];
1247 remappedelement[2] = vertexremap[element[2]];
1248 outelement3i[0] = remappedelement[0];
1249 outelement3i[1] = remappedelement[2];
1250 outelement3i[2] = remappedelement[2] + 1;
1251 outelement3i[3] = remappedelement[0];
1252 outelement3i[4] = remappedelement[2] + 1;
1253 outelement3i[5] = remappedelement[0] + 1;
1260 *outnumvertices = outvertices;
1261 return outtriangles;
1264 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)
1270 if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1272 tend = firsttriangle + numtris;
1273 if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1275 // surface box entirely inside light box, no box cull
1276 if (projectdirection)
1278 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1280 TriangleNormal(invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3, normal);
1281 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1282 shadowmarklist[numshadowmark++] = t;
1287 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1288 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3))
1289 shadowmarklist[numshadowmark++] = t;
1294 // surface box not entirely inside light box, cull each triangle
1295 if (projectdirection)
1297 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1299 v[0] = invertex3f + e[0] * 3;
1300 v[1] = invertex3f + e[1] * 3;
1301 v[2] = invertex3f + e[2] * 3;
1302 TriangleNormal(v[0], v[1], v[2], normal);
1303 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1304 && TriangleBBoxOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1305 shadowmarklist[numshadowmark++] = t;
1310 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1312 v[0] = invertex3f + e[0] * 3;
1313 v[1] = invertex3f + e[1] * 3;
1314 v[2] = invertex3f + e[2] * 3;
1315 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1316 && TriangleBBoxOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1317 shadowmarklist[numshadowmark++] = t;
1323 static qboolean R_Shadow_UseZPass(vec3_t mins, vec3_t maxs)
1328 if (r_shadow_compilingrtlight || !r_shadow_frontsidecasting.integer || !r_shadow_usezpassifpossible.integer)
1330 // check if the shadow volume intersects the near plane
1332 // a ray between the eye and light origin may intersect the caster,
1333 // indicating that the shadow may touch the eye location, however we must
1334 // test the near plane (a polygon), not merely the eye location, so it is
1335 // easiest to enlarge the caster bounding shape slightly for this.
1341 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)
1343 int i, tris, outverts;
1344 if (projectdistance < 0.1)
1346 Con_Printf("R_Shadow_Volume: projectdistance %f\n", projectdistance);
1349 if (!numverts || !nummarktris)
1351 // make sure shadowelements is big enough for this volume
1352 if (maxshadowtriangles < nummarktris*8 || maxshadowvertices < numverts*2)
1353 R_Shadow_ResizeShadowArrays(numverts, nummarktris, 2, 8);
1355 if (maxvertexupdate < numverts)
1357 maxvertexupdate = numverts;
1359 Mem_Free(vertexupdate);
1361 Mem_Free(vertexremap);
1362 vertexupdate = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1363 vertexremap = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1364 vertexupdatenum = 0;
1367 if (vertexupdatenum == 0)
1369 vertexupdatenum = 1;
1370 memset(vertexupdate, 0, maxvertexupdate * sizeof(int));
1371 memset(vertexremap, 0, maxvertexupdate * sizeof(int));
1374 for (i = 0;i < nummarktris;i++)
1375 shadowmark[marktris[i]] = shadowmarkcount;
1377 if (r_shadow_compilingrtlight)
1379 // if we're compiling an rtlight, capture the mesh
1380 //tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1381 //Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zpass, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1382 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1383 Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zfail, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1385 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_VISIBLEVOLUMES)
1387 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1388 R_Mesh_PrepareVertices_Vertex3f(outverts, shadowvertex3f, NULL);
1389 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1393 // decide which type of shadow to generate and set stencil mode
1394 R_Shadow_RenderMode_StencilShadowVolumes(R_Shadow_UseZPass(trismins, trismaxs));
1395 // generate the sides or a solid volume, depending on type
1396 if (r_shadow_rendermode >= R_SHADOW_RENDERMODE_ZPASS_STENCIL && r_shadow_rendermode <= R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE)
1397 tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1399 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1400 r_refdef.stats.lights_dynamicshadowtriangles += tris;
1401 r_refdef.stats.lights_shadowtriangles += tris;
1402 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
1404 // increment stencil if frontface is infront of depthbuffer
1405 GL_CullFace(r_refdef.view.cullface_front);
1406 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, 128, 255);
1407 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1408 // decrement stencil if backface is infront of depthbuffer
1409 GL_CullFace(r_refdef.view.cullface_back);
1410 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_ALWAYS, 128, 255);
1412 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
1414 // decrement stencil if backface is behind depthbuffer
1415 GL_CullFace(r_refdef.view.cullface_front);
1416 R_SetStencil(true, 255, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, 128, 255);
1417 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1418 // increment stencil if frontface is behind depthbuffer
1419 GL_CullFace(r_refdef.view.cullface_back);
1420 R_SetStencil(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_ALWAYS, 128, 255);
1422 R_Mesh_PrepareVertices_Vertex3f(outverts, shadowvertex3f, NULL);
1423 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1427 int R_Shadow_CalcTriangleSideMask(const vec3_t p1, const vec3_t p2, const vec3_t p3, float bias)
1429 // p1, p2, p3 are in the cubemap's local coordinate system
1430 // bias = border/(size - border)
1433 float dp1 = p1[0] + p1[1], dn1 = p1[0] - p1[1], ap1 = fabs(dp1), an1 = fabs(dn1),
1434 dp2 = p2[0] + p2[1], dn2 = p2[0] - p2[1], ap2 = fabs(dp2), an2 = fabs(dn2),
1435 dp3 = p3[0] + p3[1], dn3 = p3[0] - p3[1], ap3 = fabs(dp3), an3 = fabs(dn3);
1436 if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1438 | (dp1 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1439 | (dp2 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1440 | (dp3 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1441 if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1443 | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1444 | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1445 | (dn3 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1447 dp1 = p1[1] + p1[2], dn1 = p1[1] - p1[2], ap1 = fabs(dp1), an1 = fabs(dn1),
1448 dp2 = p2[1] + p2[2], dn2 = p2[1] - p2[2], ap2 = fabs(dp2), an2 = fabs(dn2),
1449 dp3 = p3[1] + p3[2], dn3 = p3[1] - p3[2], ap3 = fabs(dp3), an3 = fabs(dn3);
1450 if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1452 | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))
1453 | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))
1454 | (dp3 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1455 if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1457 | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1458 | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1459 | (dn3 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1461 dp1 = p1[2] + p1[0], dn1 = p1[2] - p1[0], ap1 = fabs(dp1), an1 = fabs(dn1),
1462 dp2 = p2[2] + p2[0], dn2 = p2[2] - p2[0], ap2 = fabs(dp2), an2 = fabs(dn2),
1463 dp3 = p3[2] + p3[0], dn3 = p3[2] - p3[0], ap3 = fabs(dp3), an3 = fabs(dn3);
1464 if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1466 | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1467 | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1468 | (dp3 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1469 if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1471 | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1472 | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1473 | (dn3 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1478 static int R_Shadow_CalcBBoxSideMask(const vec3_t mins, const vec3_t maxs, const matrix4x4_t *worldtolight, const matrix4x4_t *radiustolight, float bias)
1480 vec3_t center, radius, lightcenter, lightradius, pmin, pmax;
1481 float dp1, dn1, ap1, an1, dp2, dn2, ap2, an2;
1484 VectorSubtract(maxs, mins, radius);
1485 VectorScale(radius, 0.5f, radius);
1486 VectorAdd(mins, radius, center);
1487 Matrix4x4_Transform(worldtolight, center, lightcenter);
1488 Matrix4x4_Transform3x3(radiustolight, radius, lightradius);
1489 VectorSubtract(lightcenter, lightradius, pmin);
1490 VectorAdd(lightcenter, lightradius, pmax);
1492 dp1 = pmax[0] + pmax[1], dn1 = pmax[0] - pmin[1], ap1 = fabs(dp1), an1 = fabs(dn1),
1493 dp2 = pmin[0] + pmin[1], dn2 = pmin[0] - pmax[1], ap2 = fabs(dp2), an2 = fabs(dn2);
1494 if(ap1 > bias*an1 && ap2 > bias*an2)
1496 | (dp1 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1497 | (dp2 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1498 if(an1 > bias*ap1 && an2 > bias*ap2)
1500 | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1501 | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1503 dp1 = pmax[1] + pmax[2], dn1 = pmax[1] - pmin[2], ap1 = fabs(dp1), an1 = fabs(dn1),
1504 dp2 = pmin[1] + pmin[2], dn2 = pmin[1] - pmax[2], ap2 = fabs(dp2), an2 = fabs(dn2);
1505 if(ap1 > bias*an1 && ap2 > bias*an2)
1507 | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))
1508 | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1509 if(an1 > bias*ap1 && an2 > bias*ap2)
1511 | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1512 | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1514 dp1 = pmax[2] + pmax[0], dn1 = pmax[2] - pmin[0], ap1 = fabs(dp1), an1 = fabs(dn1),
1515 dp2 = pmin[2] + pmin[0], dn2 = pmin[2] - pmax[0], ap2 = fabs(dp2), an2 = fabs(dn2);
1516 if(ap1 > bias*an1 && ap2 > bias*an2)
1518 | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1519 | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1520 if(an1 > bias*ap1 && an2 > bias*ap2)
1522 | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1523 | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1528 #define R_Shadow_CalcEntitySideMask(ent, worldtolight, radiustolight, bias) R_Shadow_CalcBBoxSideMask((ent)->mins, (ent)->maxs, worldtolight, radiustolight, bias)
1530 int R_Shadow_CalcSphereSideMask(const vec3_t p, float radius, float bias)
1532 // p is in the cubemap's local coordinate system
1533 // bias = border/(size - border)
1534 float dxyp = p[0] + p[1], dxyn = p[0] - p[1], axyp = fabs(dxyp), axyn = fabs(dxyn);
1535 float dyzp = p[1] + p[2], dyzn = p[1] - p[2], ayzp = fabs(dyzp), ayzn = fabs(dyzn);
1536 float dzxp = p[2] + p[0], dzxn = p[2] - p[0], azxp = fabs(dzxp), azxn = fabs(dzxn);
1538 if(axyp > bias*axyn + radius) mask &= dxyp < 0 ? ~((1<<0)|(1<<2)) : ~((2<<0)|(2<<2));
1539 if(axyn > bias*axyp + radius) mask &= dxyn < 0 ? ~((1<<0)|(2<<2)) : ~((2<<0)|(1<<2));
1540 if(ayzp > bias*ayzn + radius) mask &= dyzp < 0 ? ~((1<<2)|(1<<4)) : ~((2<<2)|(2<<4));
1541 if(ayzn > bias*ayzp + radius) mask &= dyzn < 0 ? ~((1<<2)|(2<<4)) : ~((2<<2)|(1<<4));
1542 if(azxp > bias*azxn + radius) mask &= dzxp < 0 ? ~((1<<4)|(1<<0)) : ~((2<<4)|(2<<0));
1543 if(azxn > bias*azxp + radius) mask &= dzxn < 0 ? ~((1<<4)|(2<<0)) : ~((2<<4)|(1<<0));
1547 static int R_Shadow_CullFrustumSides(rtlight_t *rtlight, float size, float border)
1551 int sides = 0x3F, masks[6] = { 3<<4, 3<<4, 3<<0, 3<<0, 3<<2, 3<<2 };
1552 float scale = (size - 2*border)/size, len;
1553 float bias = border / (float)(size - border), dp, dn, ap, an;
1554 // check if cone enclosing side would cross frustum plane
1555 scale = 2 / (scale*scale + 2);
1556 Matrix4x4_OriginFromMatrix(&rtlight->matrix_lighttoworld, o);
1557 for (i = 0;i < 5;i++)
1559 if (PlaneDiff(o, &r_refdef.view.frustum[i]) > -0.03125)
1561 Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[i].normal, n);
1562 len = scale*VectorLength2(n);
1563 if(n[0]*n[0] > len) sides &= n[0] < 0 ? ~(1<<0) : ~(2 << 0);
1564 if(n[1]*n[1] > len) sides &= n[1] < 0 ? ~(1<<2) : ~(2 << 2);
1565 if(n[2]*n[2] > len) sides &= n[2] < 0 ? ~(1<<4) : ~(2 << 4);
1567 if (PlaneDiff(o, &r_refdef.view.frustum[4]) >= r_refdef.farclip - r_refdef.nearclip + 0.03125)
1569 Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[4].normal, n);
1570 len = scale*VectorLength2(n);
1571 if(n[0]*n[0] > len) sides &= n[0] >= 0 ? ~(1<<0) : ~(2 << 0);
1572 if(n[1]*n[1] > len) sides &= n[1] >= 0 ? ~(1<<2) : ~(2 << 2);
1573 if(n[2]*n[2] > len) sides &= n[2] >= 0 ? ~(1<<4) : ~(2 << 4);
1575 // this next test usually clips off more sides than the former, but occasionally clips fewer/different ones, so do both and combine results
1576 // check if frustum corners/origin cross plane sides
1578 // infinite version, assumes frustum corners merely give direction and extend to infinite distance
1579 Matrix4x4_Transform(&rtlight->matrix_worldtolight, r_refdef.view.origin, p);
1580 dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn);
1581 masks[0] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1582 masks[1] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1583 dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn);
1584 masks[2] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1585 masks[3] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1586 dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn);
1587 masks[4] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1588 masks[5] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1589 for (i = 0;i < 4;i++)
1591 Matrix4x4_Transform(&rtlight->matrix_worldtolight, r_refdef.view.frustumcorner[i], n);
1592 VectorSubtract(n, p, n);
1593 dp = n[0] + n[1], dn = n[0] - n[1], ap = fabs(dp), an = fabs(dn);
1594 if(ap > 0) masks[0] |= dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2);
1595 if(an > 0) masks[1] |= dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2);
1596 dp = n[1] + n[2], dn = n[1] - n[2], ap = fabs(dp), an = fabs(dn);
1597 if(ap > 0) masks[2] |= dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4);
1598 if(an > 0) masks[3] |= dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4);
1599 dp = n[2] + n[0], dn = n[2] - n[0], ap = fabs(dp), an = fabs(dn);
1600 if(ap > 0) masks[4] |= dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0);
1601 if(an > 0) masks[5] |= dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0);
1604 // finite version, assumes corners are a finite distance from origin dependent on far plane
1605 for (i = 0;i < 5;i++)
1607 Matrix4x4_Transform(&rtlight->matrix_worldtolight, !i ? r_refdef.view.origin : r_refdef.view.frustumcorner[i-1], p);
1608 dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn);
1609 masks[0] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1610 masks[1] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1611 dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn);
1612 masks[2] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1613 masks[3] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1614 dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn);
1615 masks[4] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1616 masks[5] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1619 return sides & masks[0] & masks[1] & masks[2] & masks[3] & masks[4] & masks[5];
1622 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)
1630 int mask, surfacemask = 0;
1631 if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1633 bias = r_shadow_shadowmapborder / (float)(r_shadow_shadowmapmaxsize - r_shadow_shadowmapborder);
1634 tend = firsttriangle + numtris;
1635 if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1637 // surface box entirely inside light box, no box cull
1638 if (projectdirection)
1640 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1642 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1643 TriangleNormal(v[0], v[1], v[2], normal);
1644 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1646 Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1647 mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1648 surfacemask |= mask;
1651 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;
1652 shadowsides[numshadowsides] = mask;
1653 shadowsideslist[numshadowsides++] = t;
1660 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1662 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1663 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2]))
1665 Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1666 mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1667 surfacemask |= mask;
1670 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;
1671 shadowsides[numshadowsides] = mask;
1672 shadowsideslist[numshadowsides++] = t;
1680 // surface box not entirely inside light box, cull each triangle
1681 if (projectdirection)
1683 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1685 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1686 TriangleNormal(v[0], v[1], v[2], normal);
1687 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1688 && TriangleBBoxOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1690 Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1691 mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1692 surfacemask |= mask;
1695 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;
1696 shadowsides[numshadowsides] = mask;
1697 shadowsideslist[numshadowsides++] = t;
1704 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1706 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1707 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1708 && TriangleBBoxOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1710 Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1711 mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1712 surfacemask |= mask;
1715 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;
1716 shadowsides[numshadowsides] = mask;
1717 shadowsideslist[numshadowsides++] = t;
1726 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)
1728 int i, j, outtriangles = 0;
1729 int *outelement3i[6];
1730 if (!numverts || !numsidetris || !r_shadow_compilingrtlight)
1732 outtriangles = sidetotals[0] + sidetotals[1] + sidetotals[2] + sidetotals[3] + sidetotals[4] + sidetotals[5];
1733 // make sure shadowelements is big enough for this mesh
1734 if (maxshadowtriangles < outtriangles)
1735 R_Shadow_ResizeShadowArrays(0, outtriangles, 0, 1);
1737 // compute the offset and size of the separate index lists for each cubemap side
1739 for (i = 0;i < 6;i++)
1741 outelement3i[i] = shadowelements + outtriangles * 3;
1742 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap->sideoffsets[i] = outtriangles;
1743 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap->sidetotals[i] = sidetotals[i];
1744 outtriangles += sidetotals[i];
1747 // gather up the (sparse) triangles into separate index lists for each cubemap side
1748 for (i = 0;i < numsidetris;i++)
1750 const int *element = elements + sidetris[i] * 3;
1751 for (j = 0;j < 6;j++)
1753 if (sides[i] & (1 << j))
1755 outelement3i[j][0] = element[0];
1756 outelement3i[j][1] = element[1];
1757 outelement3i[j][2] = element[2];
1758 outelement3i[j] += 3;
1763 Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap, NULL, NULL, NULL, vertex3f, NULL, NULL, NULL, NULL, outtriangles, shadowelements);
1766 static void R_Shadow_MakeTextures_MakeCorona(void)
1770 unsigned char pixels[32][32][4];
1771 for (y = 0;y < 32;y++)
1773 dy = (y - 15.5f) * (1.0f / 16.0f);
1774 for (x = 0;x < 32;x++)
1776 dx = (x - 15.5f) * (1.0f / 16.0f);
1777 a = (int)(((1.0f / (dx * dx + dy * dy + 0.2f)) - (1.0f / (1.0f + 0.2))) * 32.0f / (1.0f / (1.0f + 0.2)));
1778 a = bound(0, a, 255);
1779 pixels[y][x][0] = a;
1780 pixels[y][x][1] = a;
1781 pixels[y][x][2] = a;
1782 pixels[y][x][3] = 255;
1785 r_shadow_lightcorona = R_SkinFrame_LoadInternalBGRA("lightcorona", TEXF_FORCELINEAR, &pixels[0][0][0], 32, 32, false);
1788 static unsigned int R_Shadow_MakeTextures_SamplePoint(float x, float y, float z)
1790 float dist = sqrt(x*x+y*y+z*z);
1791 float intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1792 // note this code could suffer byte order issues except that it is multiplying by an integer that reads the same both ways
1793 return (unsigned char)bound(0, intensity * 256.0f, 255) * 0x01010101;
1796 static void R_Shadow_MakeTextures(void)
1799 float intensity, dist;
1801 R_Shadow_FreeShadowMaps();
1802 R_FreeTexturePool(&r_shadow_texturepool);
1803 r_shadow_texturepool = R_AllocTexturePool();
1804 r_shadow_attenlinearscale = r_shadow_lightattenuationlinearscale.value;
1805 r_shadow_attendividebias = r_shadow_lightattenuationdividebias.value;
1806 data = (unsigned int *)Mem_Alloc(tempmempool, max(max(ATTEN3DSIZE*ATTEN3DSIZE*ATTEN3DSIZE, ATTEN2DSIZE*ATTEN2DSIZE), ATTEN1DSIZE) * 4);
1807 // the table includes one additional value to avoid the need to clamp indexing due to minor math errors
1808 for (x = 0;x <= ATTENTABLESIZE;x++)
1810 dist = (x + 0.5f) * (1.0f / ATTENTABLESIZE) * (1.0f / 0.9375);
1811 intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1812 r_shadow_attentable[x] = bound(0, intensity, 1);
1814 // 1D gradient texture
1815 for (x = 0;x < ATTEN1DSIZE;x++)
1816 data[x] = R_Shadow_MakeTextures_SamplePoint((x + 0.5f) * (1.0f / ATTEN1DSIZE) * (1.0f / 0.9375), 0, 0);
1817 r_shadow_attenuationgradienttexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation1d", ATTEN1DSIZE, 1, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1818 // 2D circle texture
1819 for (y = 0;y < ATTEN2DSIZE;y++)
1820 for (x = 0;x < ATTEN2DSIZE;x++)
1821 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);
1822 r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1823 // 3D sphere texture
1824 if (r_shadow_texture3d.integer && vid.support.ext_texture_3d)
1826 for (z = 0;z < ATTEN3DSIZE;z++)
1827 for (y = 0;y < ATTEN3DSIZE;y++)
1828 for (x = 0;x < ATTEN3DSIZE;x++)
1829 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));
1830 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);
1833 r_shadow_attenuation3dtexture = NULL;
1836 R_Shadow_MakeTextures_MakeCorona();
1838 // Editor light sprites
1839 r_editlights_sprcursor = R_SkinFrame_LoadInternal8bit("gfx/editlights/cursor", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1856 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1857 r_editlights_sprlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/light", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1874 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1875 r_editlights_sprnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/noshadow", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1892 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1893 r_editlights_sprcubemaplight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemaplight", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1910 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1911 r_editlights_sprcubemapnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemapnoshadowlight", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1928 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1929 r_editlights_sprselection = R_SkinFrame_LoadInternal8bit("gfx/editlights/selection", TEXF_ALPHA | TEXF_CLAMP, (unsigned char *)
1946 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1949 void R_Shadow_ValidateCvars(void)
1951 if (r_shadow_texture3d.integer && !vid.support.ext_texture_3d)
1952 Cvar_SetValueQuick(&r_shadow_texture3d, 0);
1953 if (gl_ext_separatestencil.integer && !vid.support.ati_separate_stencil)
1954 Cvar_SetValueQuick(&gl_ext_separatestencil, 0);
1955 if (gl_ext_stenciltwoside.integer && !vid.support.ext_stencil_two_side)
1956 Cvar_SetValueQuick(&gl_ext_stenciltwoside, 0);
1959 void R_Shadow_RenderMode_Begin(void)
1965 R_Shadow_ValidateCvars();
1967 if (!r_shadow_attenuation2dtexture
1968 || (!r_shadow_attenuation3dtexture && r_shadow_texture3d.integer)
1969 || r_shadow_lightattenuationdividebias.value != r_shadow_attendividebias
1970 || r_shadow_lightattenuationlinearscale.value != r_shadow_attenlinearscale)
1971 R_Shadow_MakeTextures();
1974 R_Mesh_ResetTextureState();
1975 GL_BlendFunc(GL_ONE, GL_ZERO);
1976 GL_DepthRange(0, 1);
1977 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
1979 GL_DepthMask(false);
1980 GL_Color(0, 0, 0, 1);
1981 GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
1983 r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
1985 if (gl_ext_separatestencil.integer && vid.support.ati_separate_stencil)
1987 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL;
1988 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL;
1990 else if (gl_ext_stenciltwoside.integer && vid.support.ext_stencil_two_side)
1992 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE;
1993 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE;
1997 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCIL;
1998 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCIL;
2001 switch(vid.renderpath)
2003 case RENDERPATH_GL20:
2004 case RENDERPATH_D3D9:
2005 case RENDERPATH_D3D10:
2006 case RENDERPATH_D3D11:
2007 case RENDERPATH_SOFT:
2008 case RENDERPATH_GLES2:
2009 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_GLSL;
2011 case RENDERPATH_GL11:
2012 case RENDERPATH_GL13:
2013 case RENDERPATH_GLES1:
2014 if (r_textureunits.integer >= 2 && vid.texunits >= 2 && r_shadow_texture3d.integer && r_shadow_attenuation3dtexture)
2015 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN;
2016 else if (r_textureunits.integer >= 3 && vid.texunits >= 3)
2017 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN;
2018 else if (r_textureunits.integer >= 2 && vid.texunits >= 2)
2019 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN;
2021 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX;
2027 qglGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);CHECKGLERROR
2028 qglGetIntegerv(GL_READ_BUFFER, &readbuffer);CHECKGLERROR
2029 r_shadow_drawbuffer = drawbuffer;
2030 r_shadow_readbuffer = readbuffer;
2032 r_shadow_cullface_front = r_refdef.view.cullface_front;
2033 r_shadow_cullface_back = r_refdef.view.cullface_back;
2036 void R_Shadow_RenderMode_ActiveLight(const rtlight_t *rtlight)
2038 rsurface.rtlight = rtlight;
2041 void R_Shadow_RenderMode_Reset(void)
2043 R_Mesh_ResetTextureState();
2044 R_Mesh_SetRenderTargets(r_shadow_fb_fbo, r_shadow_fb_depthtexture, r_shadow_fb_colortexture, NULL, NULL, NULL);
2045 R_SetViewport(&r_refdef.view.viewport);
2046 GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
2047 GL_DepthRange(0, 1);
2049 GL_DepthMask(false);
2050 GL_DepthFunc(GL_LEQUAL);
2051 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
2052 r_refdef.view.cullface_front = r_shadow_cullface_front;
2053 r_refdef.view.cullface_back = r_shadow_cullface_back;
2054 GL_CullFace(r_refdef.view.cullface_back);
2055 GL_Color(1, 1, 1, 1);
2056 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
2057 GL_BlendFunc(GL_ONE, GL_ZERO);
2058 R_SetupShader_Generic_NoTexture(false, false);
2059 r_shadow_usingshadowmap2d = false;
2060 r_shadow_usingshadowmaportho = false;
2061 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
2064 void R_Shadow_ClearStencil(void)
2066 GL_Clear(GL_STENCIL_BUFFER_BIT, NULL, 1.0f, 128);
2067 r_refdef.stats.lights_clears++;
2070 void R_Shadow_RenderMode_StencilShadowVolumes(qboolean zpass)
2072 r_shadow_rendermode_t mode = zpass ? r_shadow_shadowingrendermode_zpass : r_shadow_shadowingrendermode_zfail;
2073 if (r_shadow_rendermode == mode)
2075 R_Shadow_RenderMode_Reset();
2076 GL_DepthFunc(GL_LESS);
2077 GL_ColorMask(0, 0, 0, 0);
2078 GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
2079 GL_CullFace(GL_NONE);
2080 R_SetupShader_DepthOrShadow(false, false);
2081 r_shadow_rendermode = mode;
2086 case R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE:
2087 case R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL:
2088 R_SetStencilSeparate(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, GL_ALWAYS, 128, 255);
2090 case R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE:
2091 case R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL:
2092 R_SetStencilSeparate(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, GL_ALWAYS, 128, 255);
2097 static void R_Shadow_MakeVSDCT(void)
2099 // maps to a 2x3 texture rectangle with normalized coordinates
2104 // stores abs(dir.xy), offset.xy/2.5
2105 unsigned char data[4*6] =
2107 255, 0, 0x33, 0x33, // +X: <1, 0>, <0.5, 0.5>
2108 255, 0, 0x99, 0x33, // -X: <1, 0>, <1.5, 0.5>
2109 0, 255, 0x33, 0x99, // +Y: <0, 1>, <0.5, 1.5>
2110 0, 255, 0x99, 0x99, // -Y: <0, 1>, <1.5, 1.5>
2111 0, 0, 0x33, 0xFF, // +Z: <0, 0>, <0.5, 2.5>
2112 0, 0, 0x99, 0xFF, // -Z: <0, 0>, <1.5, 2.5>
2114 r_shadow_shadowmapvsdcttexture = R_LoadTextureCubeMap(r_shadow_texturepool, "shadowmapvsdct", 1, data, TEXTYPE_RGBA, TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, -1, NULL);
2117 static void R_Shadow_MakeShadowMap(int side, int size)
2119 switch (r_shadow_shadowmode)
2121 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
2122 if (r_shadow_shadowmap2ddepthtexture) return;
2123 if (r_fb.usedepthtextures)
2125 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);
2126 r_shadow_shadowmap2ddepthbuffer = NULL;
2127 r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL, NULL);
2131 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);
2132 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);
2133 r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2ddepthbuffer, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL);
2141 static void R_Shadow_RenderMode_ShadowMap(int side, int clear, int size)
2143 float nearclip, farclip, bias;
2144 r_viewport_t viewport;
2147 float clearcolor[4];
2148 nearclip = r_shadow_shadowmapping_nearclip.value / rsurface.rtlight->radius;
2150 bias = r_shadow_shadowmapping_bias.value * nearclip * (1024.0f / size);// * rsurface.rtlight->radius;
2151 r_shadow_shadowmap_parameters[1] = -nearclip * farclip / (farclip - nearclip) - 0.5f * bias;
2152 r_shadow_shadowmap_parameters[3] = 0.5f + 0.5f * (farclip + nearclip) / (farclip - nearclip);
2153 r_shadow_shadowmapside = side;
2154 r_shadow_shadowmapsize = size;
2156 r_shadow_shadowmap_parameters[0] = 0.5f * (size - r_shadow_shadowmapborder);
2157 r_shadow_shadowmap_parameters[2] = r_shadow_shadowmapvsdct ? 2.5f*size : size;
2158 R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapborder, nearclip, farclip, NULL);
2159 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAP2D) goto init_done;
2161 // complex unrolled cube approach (more flexible)
2162 if (r_shadow_shadowmapvsdct && !r_shadow_shadowmapvsdcttexture)
2163 R_Shadow_MakeVSDCT();
2164 if (!r_shadow_shadowmap2ddepthtexture)
2165 R_Shadow_MakeShadowMap(side, r_shadow_shadowmapmaxsize);
2166 fbo2d = r_shadow_fbo2d;
2167 r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2ddepthtexture);
2168 r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2ddepthtexture);
2169 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
2171 R_Mesh_ResetTextureState();
2172 R_Shadow_RenderMode_Reset();
2173 if (r_shadow_shadowmap2ddepthbuffer)
2174 R_Mesh_SetRenderTargets(fbo2d, r_shadow_shadowmap2ddepthbuffer, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL);
2176 R_Mesh_SetRenderTargets(fbo2d, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL, NULL);
2177 R_SetupShader_DepthOrShadow(true, r_shadow_shadowmap2ddepthbuffer != NULL);
2178 GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
2183 R_SetViewport(&viewport);
2184 flipped = (side & 1) ^ (side >> 2);
2185 r_refdef.view.cullface_front = flipped ? r_shadow_cullface_back : r_shadow_cullface_front;
2186 r_refdef.view.cullface_back = flipped ? r_shadow_cullface_front : r_shadow_cullface_back;
2187 if (r_shadow_shadowmap2ddepthbuffer)
2189 // completely different meaning than in depthtexture approach
2190 r_shadow_shadowmap_parameters[1] = 0;
2191 r_shadow_shadowmap_parameters[3] = -bias;
2193 Vector4Set(clearcolor, 1,1,1,1);
2194 if (r_shadow_shadowmap2ddepthbuffer)
2195 GL_ColorMask(1,1,1,1);
2197 GL_ColorMask(0,0,0,0);
2198 switch(vid.renderpath)
2200 case RENDERPATH_GL11:
2201 case RENDERPATH_GL13:
2202 case RENDERPATH_GL20:
2203 case RENDERPATH_SOFT:
2204 case RENDERPATH_GLES1:
2205 case RENDERPATH_GLES2:
2206 GL_CullFace(r_refdef.view.cullface_back);
2207 // OpenGL lets us scissor larger than the viewport, so go ahead and clear all views at once
2208 if ((clear & ((2 << side) - 1)) == (1 << side)) // only clear if the side is the first in the mask
2210 // get tightest scissor rectangle that encloses all viewports in the clear mask
2211 int x1 = clear & 0x15 ? 0 : size;
2212 int x2 = clear & 0x2A ? 2 * size : size;
2213 int y1 = clear & 0x03 ? 0 : (clear & 0xC ? size : 2 * size);
2214 int y2 = clear & 0x30 ? 3 * size : (clear & 0xC ? 2 * size : size);
2215 GL_Scissor(x1, y1, x2 - x1, y2 - y1);
2218 if (r_shadow_shadowmap2ddepthbuffer)
2219 GL_Clear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
2221 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
2224 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
2226 case RENDERPATH_D3D9:
2227 case RENDERPATH_D3D10:
2228 case RENDERPATH_D3D11:
2229 // we invert the cull mode because we flip the projection matrix
2230 // NOTE: this actually does nothing because the DrawShadowMap code sets it to doublesided...
2231 GL_CullFace(r_refdef.view.cullface_front);
2232 // D3D considers it an error to use a scissor larger than the viewport... clear just this view
2233 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
2236 if (r_shadow_shadowmap2ddepthbuffer)
2237 GL_Clear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
2239 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
2245 void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qboolean shadowmapping)
2247 R_Mesh_ResetTextureState();
2250 r_shadow_lightscissor[0] = r_refdef.view.viewport.x;
2251 r_shadow_lightscissor[1] = r_refdef.view.viewport.y;
2252 r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
2253 r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
2255 R_Shadow_RenderMode_Reset();
2256 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2258 GL_DepthFunc(GL_EQUAL);
2259 // do global setup needed for the chosen lighting mode
2260 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
2261 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0);
2262 r_shadow_usingshadowmap2d = shadowmapping;
2263 r_shadow_rendermode = r_shadow_lightingrendermode;
2264 // only draw light where this geometry was already rendered AND the
2265 // stencil is 128 (values other than this mean shadow)
2267 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2269 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
2272 static const unsigned short bboxelements[36] =
2282 static const float bboxpoints[8][3] =
2294 void R_Shadow_RenderMode_DrawDeferredLight(qboolean stenciltest, qboolean shadowmapping)
2297 float vertex3f[8*3];
2298 const matrix4x4_t *matrix = &rsurface.rtlight->matrix_lighttoworld;
2299 // do global setup needed for the chosen lighting mode
2300 R_Shadow_RenderMode_Reset();
2301 r_shadow_rendermode = r_shadow_lightingrendermode;
2302 R_EntityMatrix(&identitymatrix);
2303 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2304 // only draw light where this geometry was already rendered AND the
2305 // stencil is 128 (values other than this mean shadow)
2306 R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2307 if (rsurface.rtlight->specularscale > 0 && r_shadow_gloss.integer > 0)
2308 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
2310 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
2312 r_shadow_usingshadowmap2d = shadowmapping;
2314 // render the lighting
2315 R_SetupShader_DeferredLight(rsurface.rtlight);
2316 for (i = 0;i < 8;i++)
2317 Matrix4x4_Transform(matrix, bboxpoints[i], vertex3f + i*3);
2318 GL_ColorMask(1,1,1,1);
2319 GL_DepthMask(false);
2320 GL_DepthRange(0, 1);
2321 GL_PolygonOffset(0, 0);
2323 GL_DepthFunc(GL_GREATER);
2324 GL_CullFace(r_refdef.view.cullface_back);
2325 R_Mesh_PrepareVertices_Vertex3f(8, vertex3f, NULL);
2326 R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
2329 void R_Shadow_UpdateBounceGridTexture(void)
2331 #define MAXBOUNCEGRIDPARTICLESPERLIGHT 1048576
2333 int flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
2335 int hitsupercontentsmask;
2344 //trace_t cliptrace2;
2345 //trace_t cliptrace3;
2346 unsigned char *pixel;
2347 unsigned char *pixels;
2350 unsigned int lightindex;
2352 unsigned int range1;
2353 unsigned int range2;
2354 unsigned int seed = (unsigned int)(realtime * 1000.0f);
2356 vec3_t baseshotcolor;
2369 vec3_t cullmins, cullmaxs;
2372 vec_t lightintensity;
2373 vec_t photonscaling;
2374 vec_t photonresidual;
2376 float texlerp[2][3];
2377 float splatcolor[32];
2378 float pixelweight[8];
2390 r_shadow_bouncegrid_settings_t settings;
2391 qboolean enable = r_shadow_bouncegrid.integer != 0 && r_refdef.scene.worldmodel;
2392 qboolean allowdirectionalshading = false;
2393 switch(vid.renderpath)
2395 case RENDERPATH_GL20:
2396 allowdirectionalshading = true;
2397 if (!vid.support.ext_texture_3d)
2400 case RENDERPATH_GLES2:
2401 // for performance reasons, do not use directional shading on GLES devices
2402 if (!vid.support.ext_texture_3d)
2405 // these renderpaths do not currently have the code to display the bouncegrid, so disable it on them...
2406 case RENDERPATH_GL11:
2407 case RENDERPATH_GL13:
2408 case RENDERPATH_GLES1:
2409 case RENDERPATH_SOFT:
2410 case RENDERPATH_D3D9:
2411 case RENDERPATH_D3D10:
2412 case RENDERPATH_D3D11:
2416 r_shadow_bouncegridintensity = r_shadow_bouncegrid_intensity.value;
2418 // see if there are really any lights to render...
2419 if (enable && r_shadow_bouncegrid_static.integer)
2422 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
2423 for (lightindex = 0;lightindex < range;lightindex++)
2425 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2426 if (!light || !(light->flags & flag))
2428 rtlight = &light->rtlight;
2429 // when static, we skip styled lights because they tend to change...
2430 if (rtlight->style > 0)
2432 VectorScale(rtlight->color, (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale), lightcolor);
2433 if (!VectorLength2(lightcolor))
2442 if (r_shadow_bouncegridtexture)
2444 R_FreeTexture(r_shadow_bouncegridtexture);
2445 r_shadow_bouncegridtexture = NULL;
2447 if (r_shadow_bouncegridpixels)
2448 Mem_Free(r_shadow_bouncegridpixels);
2449 r_shadow_bouncegridpixels = NULL;
2450 if (r_shadow_bouncegridhighpixels)
2451 Mem_Free(r_shadow_bouncegridhighpixels);
2452 r_shadow_bouncegridhighpixels = NULL;
2453 r_shadow_bouncegridnumpixels = 0;
2454 r_shadow_bouncegriddirectional = false;
2458 // build up a complete collection of the desired settings, so that memcmp can be used to compare parameters
2459 memset(&settings, 0, sizeof(settings));
2460 settings.staticmode = r_shadow_bouncegrid_static.integer != 0;
2461 settings.bounceanglediffuse = r_shadow_bouncegrid_bounceanglediffuse.integer != 0;
2462 settings.directionalshading = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_directionalshading.integer != 0 : r_shadow_bouncegrid_directionalshading.integer != 0) && allowdirectionalshading;
2463 settings.dlightparticlemultiplier = r_shadow_bouncegrid_dlightparticlemultiplier.value;
2464 settings.hitmodels = r_shadow_bouncegrid_hitmodels.integer != 0;
2465 settings.includedirectlighting = r_shadow_bouncegrid_includedirectlighting.integer != 0 || r_shadow_bouncegrid.integer == 2;
2466 settings.lightradiusscale = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_lightradiusscale.value : r_shadow_bouncegrid_lightradiusscale.value);
2467 settings.maxbounce = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_maxbounce.integer : r_shadow_bouncegrid_maxbounce.integer);
2468 settings.particlebounceintensity = r_shadow_bouncegrid_particlebounceintensity.value;
2469 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);
2470 settings.photons = r_shadow_bouncegrid_static.integer ? r_shadow_bouncegrid_static_photons.integer : r_shadow_bouncegrid_photons.integer;
2471 settings.spacing[0] = r_shadow_bouncegrid_spacing.value;
2472 settings.spacing[1] = r_shadow_bouncegrid_spacing.value;
2473 settings.spacing[2] = r_shadow_bouncegrid_spacing.value;
2474 settings.stablerandom = r_shadow_bouncegrid_stablerandom.integer;
2476 // bound the values for sanity
2477 settings.photons = bound(1, settings.photons, 1048576);
2478 settings.lightradiusscale = bound(0.0001f, settings.lightradiusscale, 1024.0f);
2479 settings.maxbounce = bound(0, settings.maxbounce, 16);
2480 settings.spacing[0] = bound(1, settings.spacing[0], 512);
2481 settings.spacing[1] = bound(1, settings.spacing[1], 512);
2482 settings.spacing[2] = bound(1, settings.spacing[2], 512);
2484 // get the spacing values
2485 spacing[0] = settings.spacing[0];
2486 spacing[1] = settings.spacing[1];
2487 spacing[2] = settings.spacing[2];
2488 ispacing[0] = 1.0f / spacing[0];
2489 ispacing[1] = 1.0f / spacing[1];
2490 ispacing[2] = 1.0f / spacing[2];
2492 // calculate texture size enclosing entire world bounds at the spacing
2493 VectorMA(r_refdef.scene.worldmodel->normalmins, -2.0f, spacing, mins);
2494 VectorMA(r_refdef.scene.worldmodel->normalmaxs, 2.0f, spacing, maxs);
2495 VectorSubtract(maxs, mins, size);
2496 // now we can calculate the resolution we want
2497 c[0] = (int)floor(size[0] / spacing[0] + 0.5f);
2498 c[1] = (int)floor(size[1] / spacing[1] + 0.5f);
2499 c[2] = (int)floor(size[2] / spacing[2] + 0.5f);
2500 // figure out the exact texture size (honoring power of 2 if required)
2501 c[0] = bound(4, c[0], (int)vid.maxtexturesize_3d);
2502 c[1] = bound(4, c[1], (int)vid.maxtexturesize_3d);
2503 c[2] = bound(4, c[2], (int)vid.maxtexturesize_3d);
2504 if (vid.support.arb_texture_non_power_of_two)
2506 resolution[0] = c[0];
2507 resolution[1] = c[1];
2508 resolution[2] = c[2];
2512 for (resolution[0] = 4;resolution[0] < c[0];resolution[0]*=2) ;
2513 for (resolution[1] = 4;resolution[1] < c[1];resolution[1]*=2) ;
2514 for (resolution[2] = 4;resolution[2] < c[2];resolution[2]*=2) ;
2516 size[0] = spacing[0] * resolution[0];
2517 size[1] = spacing[1] * resolution[1];
2518 size[2] = spacing[2] * resolution[2];
2520 // if dynamic we may or may not want to use the world bounds
2521 // if the dynamic size is smaller than the world bounds, use it instead
2522 if (!settings.staticmode && (r_shadow_bouncegrid_x.integer * r_shadow_bouncegrid_y.integer * r_shadow_bouncegrid_z.integer < resolution[0] * resolution[1] * resolution[2]))
2524 // we know the resolution we want
2525 c[0] = r_shadow_bouncegrid_x.integer;
2526 c[1] = r_shadow_bouncegrid_y.integer;
2527 c[2] = r_shadow_bouncegrid_z.integer;
2528 // now we can calculate the texture size (power of 2 if required)
2529 c[0] = bound(4, c[0], (int)vid.maxtexturesize_3d);
2530 c[1] = bound(4, c[1], (int)vid.maxtexturesize_3d);
2531 c[2] = bound(4, c[2], (int)vid.maxtexturesize_3d);
2532 if (vid.support.arb_texture_non_power_of_two)
2534 resolution[0] = c[0];
2535 resolution[1] = c[1];
2536 resolution[2] = c[2];
2540 for (resolution[0] = 4;resolution[0] < c[0];resolution[0]*=2) ;
2541 for (resolution[1] = 4;resolution[1] < c[1];resolution[1]*=2) ;
2542 for (resolution[2] = 4;resolution[2] < c[2];resolution[2]*=2) ;
2544 size[0] = spacing[0] * resolution[0];
2545 size[1] = spacing[1] * resolution[1];
2546 size[2] = spacing[2] * resolution[2];
2547 // center the rendering on the view
2548 mins[0] = floor(r_refdef.view.origin[0] * ispacing[0] + 0.5f) * spacing[0] - 0.5f * size[0];
2549 mins[1] = floor(r_refdef.view.origin[1] * ispacing[1] + 0.5f) * spacing[1] - 0.5f * size[1];
2550 mins[2] = floor(r_refdef.view.origin[2] * ispacing[2] + 0.5f) * spacing[2] - 0.5f * size[2];
2553 // recalculate the maxs in case the resolution was not satisfactory
2554 VectorAdd(mins, size, maxs);
2556 // if all the settings seem identical to the previous update, return
2557 if (r_shadow_bouncegridtexture && (settings.staticmode || realtime < r_shadow_bouncegridtime + r_shadow_bouncegrid_updateinterval.value) && !memcmp(&r_shadow_bouncegridsettings, &settings, sizeof(settings)))
2560 // store the new settings
2561 r_shadow_bouncegridsettings = settings;
2563 pixelbands = settings.directionalshading ? 8 : 1;
2564 pixelsperband = resolution[0]*resolution[1]*resolution[2];
2565 numpixels = pixelsperband*pixelbands;
2567 // we're going to update the bouncegrid, update the matrix...
2568 memset(m, 0, sizeof(m));
2569 m[0] = 1.0f / size[0];
2570 m[3] = -mins[0] * m[0];
2571 m[5] = 1.0f / size[1];
2572 m[7] = -mins[1] * m[5];
2573 m[10] = 1.0f / size[2];
2574 m[11] = -mins[2] * m[10];
2576 Matrix4x4_FromArrayFloatD3D(&r_shadow_bouncegridmatrix, m);
2577 // reallocate pixels for this update if needed...
2578 if (r_shadow_bouncegridnumpixels != numpixels || !r_shadow_bouncegridpixels || !r_shadow_bouncegridhighpixels)
2580 if (r_shadow_bouncegridtexture)
2582 R_FreeTexture(r_shadow_bouncegridtexture);
2583 r_shadow_bouncegridtexture = NULL;
2585 r_shadow_bouncegridpixels = (unsigned char *)Mem_Realloc(r_main_mempool, r_shadow_bouncegridpixels, numpixels * sizeof(unsigned char[4]));
2586 r_shadow_bouncegridhighpixels = (float *)Mem_Realloc(r_main_mempool, r_shadow_bouncegridhighpixels, numpixels * sizeof(float[4]));
2588 r_shadow_bouncegridnumpixels = numpixels;
2589 pixels = r_shadow_bouncegridpixels;
2590 highpixels = r_shadow_bouncegridhighpixels;
2591 x = pixelsperband*4;
2592 for (pixelband = 0;pixelband < pixelbands;pixelband++)
2595 memset(pixels + pixelband * x, 128, x);
2597 memset(pixels + pixelband * x, 0, x);
2599 memset(highpixels, 0, numpixels * sizeof(float[4]));
2600 // figure out what we want to interact with
2601 if (settings.hitmodels)
2602 hitsupercontentsmask = SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY;// | SUPERCONTENTS_LIQUIDSMASK;
2604 hitsupercontentsmask = SUPERCONTENTS_SOLID;// | SUPERCONTENTS_LIQUIDSMASK;
2605 maxbounce = settings.maxbounce;
2606 // clear variables that produce warnings otherwise
2607 memset(splatcolor, 0, sizeof(splatcolor));
2608 // iterate world rtlights
2609 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
2610 range1 = settings.staticmode ? 0 : r_refdef.scene.numlights;
2611 range2 = range + range1;
2613 for (lightindex = 0;lightindex < range2;lightindex++)
2615 if (lightindex < range)
2617 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2620 rtlight = &light->rtlight;
2621 VectorClear(rtlight->photoncolor);
2622 rtlight->photons = 0;
2623 if (!(light->flags & flag))
2625 if (settings.staticmode)
2627 // when static, we skip styled lights because they tend to change...
2628 if (rtlight->style > 0 && r_shadow_bouncegrid.integer != 2)
2634 rtlight = r_refdef.scene.lights[lightindex - range];
2635 VectorClear(rtlight->photoncolor);
2636 rtlight->photons = 0;
2638 // draw only visible lights (major speedup)
2639 radius = rtlight->radius * settings.lightradiusscale;
2640 cullmins[0] = rtlight->shadoworigin[0] - radius;
2641 cullmins[1] = rtlight->shadoworigin[1] - radius;
2642 cullmins[2] = rtlight->shadoworigin[2] - radius;
2643 cullmaxs[0] = rtlight->shadoworigin[0] + radius;
2644 cullmaxs[1] = rtlight->shadoworigin[1] + radius;
2645 cullmaxs[2] = rtlight->shadoworigin[2] + radius;
2646 if (R_CullBox(cullmins, cullmaxs))
2648 if (r_refdef.scene.worldmodel
2649 && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs
2650 && !r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs(r_refdef.scene.worldmodel, r_refdef.viewcache.world_leafvisible, cullmins, cullmaxs))
2652 w = r_shadow_lightintensityscale.value * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale);
2653 if (w * VectorLength2(rtlight->color) == 0.0f)
2655 w *= (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1);
2656 VectorScale(rtlight->color, w, rtlight->photoncolor);
2657 //if (!VectorLength2(rtlight->photoncolor))
2659 // shoot particles from this light
2660 // use a calculation for the number of particles that will not
2661 // vary with lightstyle, otherwise we get randomized particle
2662 // distribution, the seeded random is only consistent for a
2663 // consistent number of particles on this light...
2664 s = rtlight->radius;
2665 lightintensity = VectorLength(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale);
2666 if (lightindex >= range)
2667 lightintensity *= settings.dlightparticlemultiplier;
2668 rtlight->photons = max(0.0f, lightintensity * s * s);
2669 photoncount += rtlight->photons;
2671 photonscaling = (float)settings.photons / max(1, photoncount);
2672 photonresidual = 0.0f;
2673 for (lightindex = 0;lightindex < range2;lightindex++)
2675 if (lightindex < range)
2677 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2680 rtlight = &light->rtlight;
2683 rtlight = r_refdef.scene.lights[lightindex - range];
2684 // skip a light with no photons
2685 if (rtlight->photons == 0.0f)
2687 // skip a light with no photon color)
2688 if (VectorLength2(rtlight->photoncolor) == 0.0f)
2690 photonresidual += rtlight->photons * photonscaling;
2691 shootparticles = (int)bound(0, photonresidual, MAXBOUNCEGRIDPARTICLESPERLIGHT);
2692 if (!shootparticles)
2694 photonresidual -= shootparticles;
2695 radius = rtlight->radius * settings.lightradiusscale;
2696 s = settings.particleintensity / shootparticles;
2697 VectorScale(rtlight->photoncolor, s, baseshotcolor);
2698 r_refdef.stats.bouncegrid_lights++;
2699 r_refdef.stats.bouncegrid_particles += shootparticles;
2700 for (shotparticles = 0;shotparticles < shootparticles;shotparticles++)
2702 if (settings.stablerandom > 0)
2703 seed = lightindex * 11937 + shotparticles;
2704 VectorCopy(baseshotcolor, shotcolor);
2705 VectorCopy(rtlight->shadoworigin, clipstart);
2706 if (settings.stablerandom < 0)
2707 VectorRandom(clipend);
2709 VectorCheeseRandom(clipend);
2710 VectorMA(clipstart, radius, clipend, clipend);
2711 for (bouncecount = 0;;bouncecount++)
2713 r_refdef.stats.bouncegrid_traces++;
2714 //r_refdef.scene.worldmodel->TraceLineAgainstSurfaces(r_refdef.scene.worldmodel, NULL, NULL, &cliptrace, clipstart, clipend, hitsupercontentsmask);
2715 //r_refdef.scene.worldmodel->TraceLine(r_refdef.scene.worldmodel, NULL, NULL, &cliptrace2, clipstart, clipend, hitsupercontentsmask);
2716 if (settings.staticmode)
2718 // static mode fires a LOT of rays but none of them are identical, so they are not cached
2719 cliptrace = CL_TraceLine(clipstart, clipend, settings.staticmode ? MOVE_WORLDONLY : (settings.hitmodels ? MOVE_HITMODEL : MOVE_NOMONSTERS), NULL, hitsupercontentsmask, true, false, NULL, true, true);
2723 // dynamic mode fires many rays and most will match the cache from the previous frame
2724 cliptrace = CL_Cache_TraceLineSurfaces(clipstart, clipend, settings.staticmode ? MOVE_WORLDONLY : (settings.hitmodels ? MOVE_HITMODEL : MOVE_NOMONSTERS), hitsupercontentsmask);
2726 if (bouncecount > 0 || settings.includedirectlighting)
2728 // calculate second order spherical harmonics values (average, slopeX, slopeY, slopeZ)
2729 // accumulate average shotcolor
2730 w = VectorLength(shotcolor);
2731 splatcolor[ 0] = shotcolor[0];
2732 splatcolor[ 1] = shotcolor[1];
2733 splatcolor[ 2] = shotcolor[2];
2734 splatcolor[ 3] = 0.0f;
2737 VectorSubtract(clipstart, cliptrace.endpos, clipdiff);
2738 VectorNormalize(clipdiff);
2739 // store bentnormal in case the shader has a use for it
2740 splatcolor[ 4] = clipdiff[0] * w;
2741 splatcolor[ 5] = clipdiff[1] * w;
2742 splatcolor[ 6] = clipdiff[2] * w;
2744 // accumulate directional contributions (+X, +Y, +Z, -X, -Y, -Z)
2745 splatcolor[ 8] = shotcolor[0] * max(0.0f, clipdiff[0]);
2746 splatcolor[ 9] = shotcolor[0] * max(0.0f, clipdiff[1]);
2747 splatcolor[10] = shotcolor[0] * max(0.0f, clipdiff[2]);
2748 splatcolor[11] = 0.0f;
2749 splatcolor[12] = shotcolor[1] * max(0.0f, clipdiff[0]);
2750 splatcolor[13] = shotcolor[1] * max(0.0f, clipdiff[1]);
2751 splatcolor[14] = shotcolor[1] * max(0.0f, clipdiff[2]);
2752 splatcolor[15] = 0.0f;
2753 splatcolor[16] = shotcolor[2] * max(0.0f, clipdiff[0]);
2754 splatcolor[17] = shotcolor[2] * max(0.0f, clipdiff[1]);
2755 splatcolor[18] = shotcolor[2] * max(0.0f, clipdiff[2]);
2756 splatcolor[19] = 0.0f;
2757 splatcolor[20] = shotcolor[0] * max(0.0f, -clipdiff[0]);
2758 splatcolor[21] = shotcolor[0] * max(0.0f, -clipdiff[1]);
2759 splatcolor[22] = shotcolor[0] * max(0.0f, -clipdiff[2]);
2760 splatcolor[23] = 0.0f;
2761 splatcolor[24] = shotcolor[1] * max(0.0f, -clipdiff[0]);
2762 splatcolor[25] = shotcolor[1] * max(0.0f, -clipdiff[1]);
2763 splatcolor[26] = shotcolor[1] * max(0.0f, -clipdiff[2]);
2764 splatcolor[27] = 0.0f;
2765 splatcolor[28] = shotcolor[2] * max(0.0f, -clipdiff[0]);
2766 splatcolor[29] = shotcolor[2] * max(0.0f, -clipdiff[1]);
2767 splatcolor[30] = shotcolor[2] * max(0.0f, -clipdiff[2]);
2768 splatcolor[31] = 0.0f;
2770 // calculate the number of steps we need to traverse this distance
2771 VectorSubtract(cliptrace.endpos, clipstart, stepdelta);
2772 numsteps = (int)(VectorLength(stepdelta) * ispacing[0]);
2773 numsteps = bound(1, numsteps, 1024);
2774 w = 1.0f / numsteps;
2775 VectorScale(stepdelta, w, stepdelta);
2776 VectorMA(clipstart, 0.5f, stepdelta, steppos);
2777 for (step = 0;step < numsteps;step++)
2779 r_refdef.stats.bouncegrid_splats++;
2780 // figure out which texture pixel this is in
2781 texlerp[1][0] = ((steppos[0] - mins[0]) * ispacing[0]) - 0.5f;
2782 texlerp[1][1] = ((steppos[1] - mins[1]) * ispacing[1]) - 0.5f;
2783 texlerp[1][2] = ((steppos[2] - mins[2]) * ispacing[2]) - 0.5f;
2784 tex[0] = (int)floor(texlerp[1][0]);
2785 tex[1] = (int)floor(texlerp[1][1]);
2786 tex[2] = (int)floor(texlerp[1][2]);
2787 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)
2789 // it is within bounds... do the real work now
2790 // calculate the lerp factors
2791 texlerp[1][0] -= tex[0];
2792 texlerp[1][1] -= tex[1];
2793 texlerp[1][2] -= tex[2];
2794 texlerp[0][0] = 1.0f - texlerp[1][0];
2795 texlerp[0][1] = 1.0f - texlerp[1][1];
2796 texlerp[0][2] = 1.0f - texlerp[1][2];
2797 // calculate individual pixel indexes and weights
2798 pixelindex[0] = (((tex[2] )*resolution[1]+tex[1] )*resolution[0]+tex[0] );pixelweight[0] = (texlerp[0][0]*texlerp[0][1]*texlerp[0][2]);
2799 pixelindex[1] = (((tex[2] )*resolution[1]+tex[1] )*resolution[0]+tex[0]+1);pixelweight[1] = (texlerp[1][0]*texlerp[0][1]*texlerp[0][2]);
2800 pixelindex[2] = (((tex[2] )*resolution[1]+tex[1]+1)*resolution[0]+tex[0] );pixelweight[2] = (texlerp[0][0]*texlerp[1][1]*texlerp[0][2]);
2801 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]);
2802 pixelindex[4] = (((tex[2]+1)*resolution[1]+tex[1] )*resolution[0]+tex[0] );pixelweight[4] = (texlerp[0][0]*texlerp[0][1]*texlerp[1][2]);
2803 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]);
2804 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]);
2805 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]);
2806 // update the 8 pixels...
2807 for (pixelband = 0;pixelband < pixelbands;pixelband++)
2809 for (corner = 0;corner < 8;corner++)
2811 // calculate address for pixel
2812 w = pixelweight[corner];
2813 pixel = pixels + 4 * pixelindex[corner] + pixelband * pixelsperband * 4;
2814 highpixel = highpixels + 4 * pixelindex[corner] + pixelband * pixelsperband * 4;
2815 // add to the high precision pixel color
2816 highpixel[0] += (splatcolor[pixelband*4+0]*w);
2817 highpixel[1] += (splatcolor[pixelband*4+1]*w);
2818 highpixel[2] += (splatcolor[pixelband*4+2]*w);
2819 highpixel[3] += (splatcolor[pixelband*4+3]*w);
2820 // flag the low precision pixel as needing to be updated
2822 // advance to next band of coefficients
2823 //pixel += pixelsperband*4;
2824 //highpixel += pixelsperband*4;
2828 VectorAdd(steppos, stepdelta, steppos);
2831 if (cliptrace.fraction >= 1.0f)
2833 r_refdef.stats.bouncegrid_hits++;
2834 if (bouncecount >= maxbounce)
2836 // scale down shot color by bounce intensity and texture color (or 50% if no texture reported)
2837 // also clamp the resulting color to never add energy, even if the user requests extreme values
2838 if (cliptrace.hittexture && cliptrace.hittexture->currentskinframe)
2839 VectorCopy(cliptrace.hittexture->currentskinframe->avgcolor, surfcolor);
2841 VectorSet(surfcolor, 0.5f, 0.5f, 0.5f);
2842 VectorScale(surfcolor, settings.particlebounceintensity, surfcolor);
2843 surfcolor[0] = min(surfcolor[0], 1.0f);
2844 surfcolor[1] = min(surfcolor[1], 1.0f);
2845 surfcolor[2] = min(surfcolor[2], 1.0f);
2846 VectorMultiply(shotcolor, surfcolor, shotcolor);
2847 if (VectorLength2(baseshotcolor) == 0.0f)
2849 r_refdef.stats.bouncegrid_bounces++;
2850 if (settings.bounceanglediffuse)
2852 // random direction, primarily along plane normal
2853 s = VectorDistance(cliptrace.endpos, clipend);
2854 if (settings.stablerandom < 0)
2855 VectorRandom(clipend);
2857 VectorCheeseRandom(clipend);
2858 VectorMA(cliptrace.plane.normal, 0.95f, clipend, clipend);
2859 VectorNormalize(clipend);
2860 VectorScale(clipend, s, clipend);
2864 // reflect the remaining portion of the line across plane normal
2865 VectorSubtract(clipend, cliptrace.endpos, clipdiff);
2866 VectorReflect(clipdiff, 1.0, cliptrace.plane.normal, clipend);
2868 // calculate the new line start and end
2869 VectorCopy(cliptrace.endpos, clipstart);
2870 VectorAdd(clipstart, clipend, clipend);
2874 // generate pixels array from highpixels array
2875 // skip first and last columns, rows, and layers as these are blank
2876 // the pixel[3] value was written above, so we can use it to detect only pixels that need to be calculated
2877 for (pixelband = 0;pixelband < pixelbands;pixelband++)
2879 for (z = 1;z < resolution[2]-1;z++)
2881 for (y = 1;y < resolution[1]-1;y++)
2883 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)
2885 // only convert pixels that were hit by photons
2886 if (pixel[3] == 255)
2888 // normalize the bentnormal...
2891 VectorNormalize(highpixel);
2892 c[0] = (int)(highpixel[0]*128.0f+128.0f);
2893 c[1] = (int)(highpixel[1]*128.0f+128.0f);
2894 c[2] = (int)(highpixel[2]*128.0f+128.0f);
2895 c[3] = (int)(highpixel[3]*128.0f+128.0f);
2899 c[0] = (int)(highpixel[0]*256.0f);
2900 c[1] = (int)(highpixel[1]*256.0f);
2901 c[2] = (int)(highpixel[2]*256.0f);
2902 c[3] = (int)(highpixel[3]*256.0f);
2904 pixel[2] = (unsigned char)bound(0, c[0], 255);
2905 pixel[1] = (unsigned char)bound(0, c[1], 255);
2906 pixel[0] = (unsigned char)bound(0, c[2], 255);
2907 pixel[3] = (unsigned char)bound(0, c[3], 255);
2913 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)
2914 R_UpdateTexture(r_shadow_bouncegridtexture, pixels, 0, 0, 0, resolution[0], resolution[1], resolution[2]*pixelbands);
2917 VectorCopy(resolution, r_shadow_bouncegridresolution);
2918 r_shadow_bouncegriddirectional = settings.directionalshading;
2919 if (r_shadow_bouncegridtexture)
2920 R_FreeTexture(r_shadow_bouncegridtexture);
2921 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);
2923 r_shadow_bouncegridtime = realtime;
2926 void R_Shadow_RenderMode_VisibleShadowVolumes(void)
2928 R_Shadow_RenderMode_Reset();
2929 GL_BlendFunc(GL_ONE, GL_ONE);
2930 GL_DepthRange(0, 1);
2931 GL_DepthTest(r_showshadowvolumes.integer < 2);
2932 GL_Color(0.0, 0.0125 * r_refdef.view.colorscale, 0.1 * r_refdef.view.colorscale, 1);
2933 GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
2934 GL_CullFace(GL_NONE);
2935 r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLEVOLUMES;
2938 void R_Shadow_RenderMode_VisibleLighting(qboolean stenciltest, qboolean transparent)
2940 R_Shadow_RenderMode_Reset();
2941 GL_BlendFunc(GL_ONE, GL_ONE);
2942 GL_DepthRange(0, 1);
2943 GL_DepthTest(r_showlighting.integer < 2);
2944 GL_Color(0.1 * r_refdef.view.colorscale, 0.0125 * r_refdef.view.colorscale, 0, 1);
2946 GL_DepthFunc(GL_EQUAL);
2947 R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2948 r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLELIGHTING;
2951 void R_Shadow_RenderMode_End(void)
2953 R_Shadow_RenderMode_Reset();
2954 R_Shadow_RenderMode_ActiveLight(NULL);
2956 GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
2957 r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
2960 int bboxedges[12][2] =
2979 qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
2981 if (!r_shadow_scissor.integer || r_shadow_usingdeferredprepass || r_trippy.integer)
2983 r_shadow_lightscissor[0] = r_refdef.view.viewport.x;
2984 r_shadow_lightscissor[1] = r_refdef.view.viewport.y;
2985 r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
2986 r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
2989 if(R_ScissorForBBox(mins, maxs, r_shadow_lightscissor))
2990 return true; // invisible
2991 if(r_shadow_lightscissor[0] != r_refdef.view.viewport.x
2992 || r_shadow_lightscissor[1] != r_refdef.view.viewport.y
2993 || r_shadow_lightscissor[2] != r_refdef.view.viewport.width
2994 || r_shadow_lightscissor[3] != r_refdef.view.viewport.height)
2995 r_refdef.stats.lights_scissored++;
2999 static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int numverts, const float *diffusecolor, const float *ambientcolor)
3002 const float *vertex3f;
3003 const float *normal3f;
3005 float dist, dot, distintensity, shadeintensity, v[3], n[3];
3006 switch (r_shadow_rendermode)
3008 case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
3009 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
3010 if (VectorLength2(diffusecolor) > 0)
3012 for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, normal3f = rsurface.batchnormal3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, normal3f += 3, color4f += 4)
3014 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3015 Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
3016 if ((dot = DotProduct(n, v)) < 0)
3018 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
3019 VectorMA(ambientcolor, shadeintensity, diffusecolor, color4f);
3022 VectorCopy(ambientcolor, color4f);
3023 if (r_refdef.fogenabled)
3026 f = RSurf_FogVertex(vertex3f);
3027 VectorScale(color4f, f, color4f);
3034 for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3036 VectorCopy(ambientcolor, color4f);
3037 if (r_refdef.fogenabled)
3040 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3041 f = RSurf_FogVertex(vertex3f);
3042 VectorScale(color4f + 4*i, f, color4f);
3048 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3049 if (VectorLength2(diffusecolor) > 0)
3051 for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, normal3f = rsurface.batchnormal3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, normal3f += 3, color4f += 4)
3053 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3054 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3056 Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
3057 if ((dot = DotProduct(n, v)) < 0)
3059 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
3060 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
3061 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
3062 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
3066 color4f[0] = ambientcolor[0] * distintensity;
3067 color4f[1] = ambientcolor[1] * distintensity;
3068 color4f[2] = ambientcolor[2] * distintensity;
3070 if (r_refdef.fogenabled)
3073 f = RSurf_FogVertex(vertex3f);
3074 VectorScale(color4f, f, color4f);
3078 VectorClear(color4f);
3084 for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3086 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3087 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3089 color4f[0] = ambientcolor[0] * distintensity;
3090 color4f[1] = ambientcolor[1] * distintensity;
3091 color4f[2] = ambientcolor[2] * distintensity;
3092 if (r_refdef.fogenabled)
3095 f = RSurf_FogVertex(vertex3f);
3096 VectorScale(color4f, f, color4f);
3100 VectorClear(color4f);
3105 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3106 if (VectorLength2(diffusecolor) > 0)
3108 for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, normal3f = rsurface.batchnormal3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, normal3f += 3, color4f += 4)
3110 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3111 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3113 distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
3114 Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
3115 if ((dot = DotProduct(n, v)) < 0)
3117 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
3118 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
3119 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
3120 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
3124 color4f[0] = ambientcolor[0] * distintensity;
3125 color4f[1] = ambientcolor[1] * distintensity;
3126 color4f[2] = ambientcolor[2] * distintensity;
3128 if (r_refdef.fogenabled)
3131 f = RSurf_FogVertex(vertex3f);
3132 VectorScale(color4f, f, color4f);
3136 VectorClear(color4f);
3142 for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3144 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3145 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3147 distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
3148 color4f[0] = ambientcolor[0] * distintensity;
3149 color4f[1] = ambientcolor[1] * distintensity;
3150 color4f[2] = ambientcolor[2] * distintensity;
3151 if (r_refdef.fogenabled)
3154 f = RSurf_FogVertex(vertex3f);
3155 VectorScale(color4f, f, color4f);
3159 VectorClear(color4f);
3169 static void R_Shadow_RenderLighting_VisibleLighting(int texturenumsurfaces, const msurface_t **texturesurfacelist)
3171 // used to display how many times a surface is lit for level design purposes
3172 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
3173 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
3177 static void R_Shadow_RenderLighting_Light_GLSL(int texturenumsurfaces, const msurface_t **texturesurfacelist, const vec3_t lightcolor, float ambientscale, float diffusescale, float specularscale)
3179 // ARB2 GLSL shader path (GFFX5200, Radeon 9500)
3180 R_SetupShader_Surface(lightcolor, false, ambientscale, diffusescale, specularscale, RSURFPASS_RTLIGHT, texturenumsurfaces, texturesurfacelist, NULL, false);
3184 static void R_Shadow_RenderLighting_Light_Vertex_Pass(int firstvertex, int numvertices, int numtriangles, const int *element3i, vec3_t diffusecolor2, vec3_t ambientcolor2)
3191 int newnumtriangles;
3195 int maxtriangles = 1024;
3196 int newelements[1024*3];
3197 R_Shadow_RenderLighting_Light_Vertex_Shading(firstvertex, numvertices, diffusecolor2, ambientcolor2);
3198 for (renders = 0;renders < 4;renders++)
3203 newnumtriangles = 0;
3205 // due to low fillrate on the cards this vertex lighting path is
3206 // designed for, we manually cull all triangles that do not
3207 // contain a lit vertex
3208 // this builds batches of triangles from multiple surfaces and
3209 // renders them at once
3210 for (i = 0, e = element3i;i < numtriangles;i++, e += 3)
3212 if (VectorLength2(rsurface.passcolor4f + e[0] * 4) + VectorLength2(rsurface.passcolor4f + e[1] * 4) + VectorLength2(rsurface.passcolor4f + e[2] * 4) >= 0.01)
3214 if (newnumtriangles)
3216 newfirstvertex = min(newfirstvertex, e[0]);
3217 newlastvertex = max(newlastvertex, e[0]);
3221 newfirstvertex = e[0];
3222 newlastvertex = e[0];
3224 newfirstvertex = min(newfirstvertex, e[1]);
3225 newlastvertex = max(newlastvertex, e[1]);
3226 newfirstvertex = min(newfirstvertex, e[2]);
3227 newlastvertex = max(newlastvertex, e[2]);
3233 if (newnumtriangles >= maxtriangles)
3235 R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, NULL, NULL, 0);
3236 newnumtriangles = 0;
3242 if (newnumtriangles >= 1)
3244 R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, NULL, NULL, 0);
3247 // if we couldn't find any lit triangles, exit early
3250 // now reduce the intensity for the next overbright pass
3251 // we have to clamp to 0 here incase the drivers have improper
3252 // handling of negative colors
3253 // (some old drivers even have improper handling of >1 color)
3255 for (i = 0, c = rsurface.passcolor4f + 4 * firstvertex;i < numvertices;i++, c += 4)
3257 if (c[0] > 1 || c[1] > 1 || c[2] > 1)
3259 c[0] = max(0, c[0] - 1);
3260 c[1] = max(0, c[1] - 1);
3261 c[2] = max(0, c[2] - 1);
3273 static void R_Shadow_RenderLighting_Light_Vertex(int texturenumsurfaces, const msurface_t **texturesurfacelist, const vec3_t lightcolor, float ambientscale, float diffusescale)
3275 // OpenGL 1.1 path (anything)
3276 float ambientcolorbase[3], diffusecolorbase[3];
3277 float ambientcolorpants[3], diffusecolorpants[3];
3278 float ambientcolorshirt[3], diffusecolorshirt[3];
3279 const float *surfacecolor = rsurface.texture->dlightcolor;
3280 const float *surfacepants = rsurface.colormap_pantscolor;
3281 const float *surfaceshirt = rsurface.colormap_shirtcolor;
3282 rtexture_t *basetexture = rsurface.texture->basetexture;
3283 rtexture_t *pantstexture = rsurface.texture->pantstexture;
3284 rtexture_t *shirttexture = rsurface.texture->shirttexture;
3285 qboolean dopants = pantstexture && VectorLength2(surfacepants) >= (1.0f / 1048576.0f);
3286 qboolean doshirt = shirttexture && VectorLength2(surfaceshirt) >= (1.0f / 1048576.0f);
3287 ambientscale *= 2 * r_refdef.view.colorscale;
3288 diffusescale *= 2 * r_refdef.view.colorscale;
3289 ambientcolorbase[0] = lightcolor[0] * ambientscale * surfacecolor[0];ambientcolorbase[1] = lightcolor[1] * ambientscale * surfacecolor[1];ambientcolorbase[2] = lightcolor[2] * ambientscale * surfacecolor[2];
3290 diffusecolorbase[0] = lightcolor[0] * diffusescale * surfacecolor[0];diffusecolorbase[1] = lightcolor[1] * diffusescale * surfacecolor[1];diffusecolorbase[2] = lightcolor[2] * diffusescale * surfacecolor[2];
3291 ambientcolorpants[0] = ambientcolorbase[0] * surfacepants[0];ambientcolorpants[1] = ambientcolorbase[1] * surfacepants[1];ambientcolorpants[2] = ambientcolorbase[2] * surfacepants[2];
3292 diffusecolorpants[0] = diffusecolorbase[0] * surfacepants[0];diffusecolorpants[1] = diffusecolorbase[1] * surfacepants[1];diffusecolorpants[2] = diffusecolorbase[2] * surfacepants[2];
3293 ambientcolorshirt[0] = ambientcolorbase[0] * surfaceshirt[0];ambientcolorshirt[1] = ambientcolorbase[1] * surfaceshirt[1];ambientcolorshirt[2] = ambientcolorbase[2] * surfaceshirt[2];
3294 diffusecolorshirt[0] = diffusecolorbase[0] * surfaceshirt[0];diffusecolorshirt[1] = diffusecolorbase[1] * surfaceshirt[1];diffusecolorshirt[2] = diffusecolorbase[2] * surfaceshirt[2];
3295 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | (diffusescale > 0 ? BATCHNEED_ARRAY_NORMAL : 0) | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
3296 rsurface.passcolor4f = (float *)R_FrameData_Alloc((rsurface.batchfirstvertex + rsurface.batchnumvertices) * sizeof(float[4]));
3297 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3298 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, 0, 0);
3299 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
3300 R_Mesh_TexBind(0, basetexture);
3301 R_Mesh_TexMatrix(0, &rsurface.texture->currenttexmatrix);
3302 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
3303 switch(r_shadow_rendermode)
3305 case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
3306 R_Mesh_TexBind(1, r_shadow_attenuation3dtexture);
3307 R_Mesh_TexMatrix(1, &rsurface.entitytoattenuationxyz);
3308 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, 1, 1);
3309 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3311 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
3312 R_Mesh_TexBind(2, r_shadow_attenuation2dtexture);
3313 R_Mesh_TexMatrix(2, &rsurface.entitytoattenuationz);
3314 R_Mesh_TexCombine(2, GL_MODULATE, GL_MODULATE, 1, 1);
3315 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3317 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3318 R_Mesh_TexBind(1, r_shadow_attenuation2dtexture);
3319 R_Mesh_TexMatrix(1, &rsurface.entitytoattenuationxyz);
3320 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, 1, 1);
3321 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3323 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3328 //R_Mesh_TexBind(0, basetexture);
3329 R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorbase, ambientcolorbase);
3332 R_Mesh_TexBind(0, pantstexture);
3333 R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorpants, ambientcolorpants);
3337 R_Mesh_TexBind(0, shirttexture);
3338 R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorshirt, ambientcolorshirt);
3342 extern cvar_t gl_lightmaps;
3343 void R_Shadow_RenderLighting(int texturenumsurfaces, const msurface_t **texturesurfacelist)
3345 float ambientscale, diffusescale, specularscale;
3347 float lightcolor[3];
3348 VectorCopy(rsurface.rtlight->currentcolor, lightcolor);
3349 ambientscale = rsurface.rtlight->ambientscale + rsurface.texture->rtlightambient;
3350 diffusescale = rsurface.rtlight->diffusescale * max(0, 1.0 - rsurface.texture->rtlightambient);
3351 specularscale = rsurface.rtlight->specularscale * rsurface.texture->specularscale;
3352 if (!r_shadow_usenormalmap.integer)
3354 ambientscale += 1.0f * diffusescale;
3358 if ((ambientscale + diffusescale) * VectorLength2(lightcolor) + specularscale * VectorLength2(lightcolor) < (1.0f / 1048576.0f))
3360 negated = (lightcolor[0] + lightcolor[1] + lightcolor[2] < 0) && vid.support.ext_blend_subtract;
3363 VectorNegate(lightcolor, lightcolor);
3364 GL_BlendEquationSubtract(true);
3366 RSurf_SetupDepthAndCulling();
3367 switch (r_shadow_rendermode)
3369 case R_SHADOW_RENDERMODE_VISIBLELIGHTING:
3370 GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST) && !r_showdisabledepthtest.integer);
3371 R_Shadow_RenderLighting_VisibleLighting(texturenumsurfaces, texturesurfacelist);
3373 case R_SHADOW_RENDERMODE_LIGHT_GLSL:
3374 R_Shadow_RenderLighting_Light_GLSL(texturenumsurfaces, texturesurfacelist, lightcolor, ambientscale, diffusescale, specularscale);
3376 case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
3377 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
3378 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3379 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3380 R_Shadow_RenderLighting_Light_Vertex(texturenumsurfaces, texturesurfacelist, lightcolor, ambientscale, diffusescale);
3383 Con_Printf("R_Shadow_RenderLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode);
3387 GL_BlendEquationSubtract(false);
3390 void R_RTLight_Update(rtlight_t *rtlight, int isstatic, matrix4x4_t *matrix, vec3_t color, int style, const char *cubemapname, int shadow, vec_t corona, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags)
3392 matrix4x4_t tempmatrix = *matrix;
3393 Matrix4x4_Scale(&tempmatrix, r_shadow_lightradiusscale.value, 1);
3395 // if this light has been compiled before, free the associated data
3396 R_RTLight_Uncompile(rtlight);
3398 // clear it completely to avoid any lingering data
3399 memset(rtlight, 0, sizeof(*rtlight));
3401 // copy the properties
3402 rtlight->matrix_lighttoworld = tempmatrix;
3403 Matrix4x4_Invert_Simple(&rtlight->matrix_worldtolight, &tempmatrix);
3404 Matrix4x4_OriginFromMatrix(&tempmatrix, rtlight->shadoworigin);
3405 rtlight->radius = Matrix4x4_ScaleFromMatrix(&tempmatrix);
3406 VectorCopy(color, rtlight->color);
3407 rtlight->cubemapname[0] = 0;
3408 if (cubemapname && cubemapname[0])
3409 strlcpy(rtlight->cubemapname, cubemapname, sizeof(rtlight->cubemapname));
3410 rtlight->shadow = shadow;
3411 rtlight->corona = corona;
3412 rtlight->style = style;
3413 rtlight->isstatic = isstatic;
3414 rtlight->coronasizescale = coronasizescale;
3415 rtlight->ambientscale = ambientscale;
3416 rtlight->diffusescale = diffusescale;
3417 rtlight->specularscale = specularscale;
3418 rtlight->flags = flags;
3420 // compute derived data
3421 //rtlight->cullradius = rtlight->radius;
3422 //rtlight->cullradius2 = rtlight->radius * rtlight->radius;
3423 rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
3424 rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
3425 rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
3426 rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
3427 rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
3428 rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
3431 // compiles rtlight geometry
3432 // (undone by R_FreeCompiledRTLight, which R_UpdateLight calls)
3433 void R_RTLight_Compile(rtlight_t *rtlight)
3436 int numsurfaces, numleafs, numleafpvsbytes, numshadowtrispvsbytes, numlighttrispvsbytes;
3437 int lighttris, shadowtris, shadowzpasstris, shadowzfailtris;
3438 entity_render_t *ent = r_refdef.scene.worldentity;
3439 dp_model_t *model = r_refdef.scene.worldmodel;
3440 unsigned char *data;
3443 // compile the light
3444 rtlight->compiled = true;
3445 rtlight->shadowmode = rtlight->shadow ? (int)r_shadow_shadowmode : -1;
3446 rtlight->static_numleafs = 0;
3447 rtlight->static_numleafpvsbytes = 0;
3448 rtlight->static_leaflist = NULL;
3449 rtlight->static_leafpvs = NULL;
3450 rtlight->static_numsurfaces = 0;
3451 rtlight->static_surfacelist = NULL;
3452 rtlight->static_shadowmap_receivers = 0x3F;
3453 rtlight->static_shadowmap_casters = 0x3F;
3454 rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
3455 rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
3456 rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
3457 rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
3458 rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
3459 rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
3461 if (model && model->GetLightInfo)
3463 // this variable must be set for the CompileShadowVolume/CompileShadowMap code
3464 r_shadow_compilingrtlight = rtlight;
3465 R_FrameData_SetMark();
3466 model->GetLightInfo(ent, rtlight->shadoworigin, rtlight->radius, rtlight->cullmins, rtlight->cullmaxs, r_shadow_buffer_leaflist, r_shadow_buffer_leafpvs, &numleafs, r_shadow_buffer_surfacelist, r_shadow_buffer_surfacepvs, &numsurfaces, r_shadow_buffer_shadowtrispvs, r_shadow_buffer_lighttrispvs, r_shadow_buffer_visitingleafpvs, 0, NULL);
3467 R_FrameData_ReturnToMark();
3468 numleafpvsbytes = (model->brush.num_leafs + 7) >> 3;
3469 numshadowtrispvsbytes = ((model->brush.shadowmesh ? model->brush.shadowmesh->numtriangles : model->surfmesh.num_triangles) + 7) >> 3;
3470 numlighttrispvsbytes = (model->surfmesh.num_triangles + 7) >> 3;
3471 data = (unsigned char *)Mem_Alloc(r_main_mempool, sizeof(int) * numsurfaces + sizeof(int) * numleafs + numleafpvsbytes + numshadowtrispvsbytes + numlighttrispvsbytes);
3472 rtlight->static_numsurfaces = numsurfaces;
3473 rtlight->static_surfacelist = (int *)data;data += sizeof(int) * numsurfaces;
3474 rtlight->static_numleafs = numleafs;
3475 rtlight->static_leaflist = (int *)data;data += sizeof(int) * numleafs;
3476 rtlight->static_numleafpvsbytes = numleafpvsbytes;
3477 rtlight->static_leafpvs = (unsigned char *)data;data += numleafpvsbytes;
3478 rtlight->static_numshadowtrispvsbytes = numshadowtrispvsbytes;
3479 rtlight->static_shadowtrispvs = (unsigned char *)data;data += numshadowtrispvsbytes;
3480 rtlight->static_numlighttrispvsbytes = numlighttrispvsbytes;
3481 rtlight->static_lighttrispvs = (unsigned char *)data;data += numlighttrispvsbytes;
3482 if (rtlight->static_numsurfaces)
3483 memcpy(rtlight->static_surfacelist, r_shadow_buffer_surfacelist, rtlight->static_numsurfaces * sizeof(*rtlight->static_surfacelist));
3484 if (rtlight->static_numleafs)
3485 memcpy(rtlight->static_leaflist, r_shadow_buffer_leaflist, rtlight->static_numleafs * sizeof(*rtlight->static_leaflist));
3486 if (rtlight->static_numleafpvsbytes)
3487 memcpy(rtlight->static_leafpvs, r_shadow_buffer_leafpvs, rtlight->static_numleafpvsbytes);
3488 if (rtlight->static_numshadowtrispvsbytes)
3489 memcpy(rtlight->static_shadowtrispvs, r_shadow_buffer_shadowtrispvs, rtlight->static_numshadowtrispvsbytes);
3490 if (rtlight->static_numlighttrispvsbytes)
3491 memcpy(rtlight->static_lighttrispvs, r_shadow_buffer_lighttrispvs, rtlight->static_numlighttrispvsbytes);
3492 R_FrameData_SetMark();
3493 switch (rtlight->shadowmode)
3495 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
3496 if (model->CompileShadowMap && rtlight->shadow)
3497 model->CompileShadowMap(ent, rtlight->shadoworigin, NULL, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist);
3500 if (model->CompileShadowVolume && rtlight->shadow)
3501 model->CompileShadowVolume(ent, rtlight->shadoworigin, NULL, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist);
3504 R_FrameData_ReturnToMark();
3505 // now we're done compiling the rtlight
3506 r_shadow_compilingrtlight = NULL;
3510 // use smallest available cullradius - box radius or light radius
3511 //rtlight->cullradius = RadiusFromBoundsAndOrigin(rtlight->cullmins, rtlight->cullmaxs, rtlight->shadoworigin);
3512 //rtlight->cullradius = min(rtlight->cullradius, rtlight->radius);
3514 shadowzpasstris = 0;
3515 if (rtlight->static_meshchain_shadow_zpass)
3516 for (mesh = rtlight->static_meshchain_shadow_zpass;mesh;mesh = mesh->next)
3517 shadowzpasstris += mesh->numtriangles;
3519 shadowzfailtris = 0;
3520 if (rtlight->static_meshchain_shadow_zfail)
3521 for (mesh = rtlight->static_meshchain_shadow_zfail;mesh;mesh = mesh->next)
3522 shadowzfailtris += mesh->numtriangles;
3525 if (rtlight->static_numlighttrispvsbytes)
3526 for (i = 0;i < rtlight->static_numlighttrispvsbytes*8;i++)
3527 if (CHECKPVSBIT(rtlight->static_lighttrispvs, i))
3531 if (rtlight->static_numlighttrispvsbytes)
3532 for (i = 0;i < rtlight->static_numshadowtrispvsbytes*8;i++)
3533 if (CHECKPVSBIT(rtlight->static_shadowtrispvs, i))
3536 if (developer_extra.integer)
3537 Con_DPrintf("static light built: %f %f %f : %f %f %f box, %i light triangles, %i shadow triangles, %i zpass/%i zfail compiled shadow volume triangles\n", rtlight->cullmins[0], rtlight->cullmins[1], rtlight->cullmins[2], rtlight->cullmaxs[0], rtlight->cullmaxs[1], rtlight->cullmaxs[2], lighttris, shadowtris, shadowzpasstris, shadowzfailtris);
3540 void R_RTLight_Uncompile(rtlight_t *rtlight)
3542 if (rtlight->compiled)
3544 if (rtlight->static_meshchain_shadow_zpass)
3545 Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_zpass);
3546 rtlight->static_meshchain_shadow_zpass = NULL;
3547 if (rtlight->static_meshchain_shadow_zfail)
3548 Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_zfail);
3549 rtlight->static_meshchain_shadow_zfail = NULL;
3550 if (rtlight->static_meshchain_shadow_shadowmap)
3551 Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_shadowmap);
3552 rtlight->static_meshchain_shadow_shadowmap = NULL;
3553 // these allocations are grouped
3554 if (rtlight->static_surfacelist)
3555 Mem_Free(rtlight->static_surfacelist);
3556 rtlight->static_numleafs = 0;
3557 rtlight->static_numleafpvsbytes = 0;
3558 rtlight->static_leaflist = NULL;
3559 rtlight->static_leafpvs = NULL;
3560 rtlight->static_numsurfaces = 0;
3561 rtlight->static_surfacelist = NULL;
3562 rtlight->static_numshadowtrispvsbytes = 0;
3563 rtlight->static_shadowtrispvs = NULL;
3564 rtlight->static_numlighttrispvsbytes = 0;
3565 rtlight->static_lighttrispvs = NULL;
3566 rtlight->compiled = false;
3570 void R_Shadow_UncompileWorldLights(void)
3574 size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
3575 for (lightindex = 0;lightindex < range;lightindex++)
3577 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
3580 R_RTLight_Uncompile(&light->rtlight);
3584 static void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight)
3588 // reset the count of frustum planes
3589 // see rtlight->cached_frustumplanes definition for how much this array
3591 rtlight->cached_numfrustumplanes = 0;
3593 if (r_trippy.integer)
3596 // haven't implemented a culling path for ortho rendering
3597 if (!r_refdef.view.useperspective)
3599 // check if the light is on screen and copy the 4 planes if it is
3600 for (i = 0;i < 4;i++)
3601 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) < -0.03125)
3604 for (i = 0;i < 4;i++)
3605 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = r_refdef.view.frustum[i];
3610 // generate a deformed frustum that includes the light origin, this is
3611 // used to cull shadow casting surfaces that can not possibly cast a
3612 // shadow onto the visible light-receiving surfaces, which can be a
3615 // if the light origin is onscreen the result will be 4 planes exactly
3616 // if the light origin is offscreen on only one axis the result will
3617 // be exactly 5 planes (split-side case)
3618 // if the light origin is offscreen on two axes the result will be
3619 // exactly 4 planes (stretched corner case)
3620 for (i = 0;i < 4;i++)
3622 // quickly reject standard frustum planes that put the light
3623 // origin outside the frustum
3624 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) < -0.03125)
3627 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = r_refdef.view.frustum[i];
3629 // if all the standard frustum planes were accepted, the light is onscreen
3630 // otherwise we need to generate some more planes below...
3631 if (rtlight->cached_numfrustumplanes < 4)
3633 // at least one of the stock frustum planes failed, so we need to
3634 // create one or two custom planes to enclose the light origin
3635 for (i = 0;i < 4;i++)
3637 // create a plane using the view origin and light origin, and a
3638 // single point from the frustum corner set
3639 TriangleNormal(r_refdef.view.origin, r_refdef.view.frustumcorner[i], rtlight->shadoworigin, plane.normal);
3640 VectorNormalize(plane.normal);
3641 plane.dist = DotProduct(r_refdef.view.origin, plane.normal);
3642 // see if this plane is backwards and flip it if so
3643 for (j = 0;j < 4;j++)
3644 if (j != i && DotProduct(r_refdef.view.frustumcorner[j], plane.normal) - plane.dist < -0.03125)
3648 VectorNegate(plane.normal, plane.normal);
3650 // flipped plane, test again to see if it is now valid
3651 for (j = 0;j < 4;j++)
3652 if (j != i && DotProduct(r_refdef.view.frustumcorner[j], plane.normal) - plane.dist < -0.03125)
3654 // if the plane is still not valid, then it is dividing the
3655 // frustum and has to be rejected
3659 // we have created a valid plane, compute extra info
3660 PlaneClassify(&plane);
3662 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3664 // if we've found 5 frustum planes then we have constructed a
3665 // proper split-side case and do not need to keep searching for
3666 // planes to enclose the light origin
3667 if (rtlight->cached_numfrustumplanes == 5)
3675 for (i = 0;i < rtlight->cached_numfrustumplanes;i++)
3677 plane = rtlight->cached_frustumplanes[i];
3678 Con_Printf("light %p plane #%i %f %f %f : %f (%f %f %f %f %f)\n", rtlight, i, plane.normal[0], plane.normal[1], plane.normal[2], plane.dist, PlaneDiff(r_refdef.view.frustumcorner[0], &plane), PlaneDiff(r_refdef.view.frustumcorner[1], &plane), PlaneDiff(r_refdef.view.frustumcorner[2], &plane), PlaneDiff(r_refdef.view.frustumcorner[3], &plane), PlaneDiff(rtlight->shadoworigin, &plane));
3683 // now add the light-space box planes if the light box is rotated, as any
3684 // caster outside the oriented light box is irrelevant (even if it passed
3685 // the worldspace light box, which is axial)
3686 if (rtlight->matrix_lighttoworld.m[0][0] != 1 || rtlight->matrix_lighttoworld.m[1][1] != 1 || rtlight->matrix_lighttoworld.m[2][2] != 1)
3688 for (i = 0;i < 6;i++)
3692 v[i >> 1] = (i & 1) ? -1 : 1;
3693 Matrix4x4_Transform(&rtlight->matrix_lighttoworld, v, plane.normal);
3694 VectorSubtract(plane.normal, rtlight->shadoworigin, plane.normal);
3695 plane.dist = VectorNormalizeLength(plane.normal);
3696 plane.dist += DotProduct(plane.normal, rtlight->shadoworigin);
3697 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3703 // add the world-space reduced box planes
3704 for (i = 0;i < 6;i++)
3706 VectorClear(plane.normal);
3707 plane.normal[i >> 1] = (i & 1) ? -1 : 1;
3708 plane.dist = (i & 1) ? -rtlight->cached_cullmaxs[i >> 1] : rtlight->cached_cullmins[i >> 1];
3709 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3718 // reduce all plane distances to tightly fit the rtlight cull box, which
3720 VectorSet(points[0], rtlight->cached_cullmins[0], rtlight->cached_cullmins[1], rtlight->cached_cullmins[2]);
3721 VectorSet(points[1], rtlight->cached_cullmaxs[0], rtlight->cached_cullmins[1], rtlight->cached_cullmins[2]);
3722 VectorSet(points[2], rtlight->cached_cullmins[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmins[2]);
3723 VectorSet(points[3], rtlight->cached_cullmaxs[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmins[2]);
3724 VectorSet(points[4], rtlight->cached_cullmins[0], rtlight->cached_cullmins[1], rtlight->cached_cullmaxs[2]);
3725 VectorSet(points[5], rtlight->cached_cullmaxs[0], rtlight->cached_cullmins[1], rtlight->cached_cullmaxs[2]);
3726 VectorSet(points[6], rtlight->cached_cullmins[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmaxs[2]);
3727 VectorSet(points[7], rtlight->cached_cullmaxs[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmaxs[2]);
3728 oldnum = rtlight->cached_numfrustumplanes;
3729 rtlight->cached_numfrustumplanes = 0;
3730 for (j = 0;j < oldnum;j++)
3732 // find the nearest point on the box to this plane
3733 bestdist = DotProduct(rtlight->cached_frustumplanes[j].normal, points[0]);
3734 for (i = 1;i < 8;i++)
3736 dist = DotProduct(rtlight->cached_frustumplanes[j].normal, points[i]);
3737 if (bestdist > dist)
3740 Con_Printf("light %p %splane #%i %f %f %f : %f < %f\n", rtlight, rtlight->cached_frustumplanes[j].dist < bestdist + 0.03125 ? "^2" : "^1", j, rtlight->cached_frustumplanes[j].normal[0], rtlight->cached_frustumplanes[j].normal[1], rtlight->cached_frustumplanes[j].normal[2], rtlight->cached_frustumplanes[j].dist, bestdist);
3741 // if the nearest point is near or behind the plane, we want this
3742 // plane, otherwise the plane is useless as it won't cull anything
3743 if (rtlight->cached_frustumplanes[j].dist < bestdist + 0.03125)
3745 PlaneClassify(&rtlight->cached_frustumplanes[j]);
3746 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = rtlight->cached_frustumplanes[j];
3753 static void R_Shadow_DrawWorldShadow_ShadowMap(int numsurfaces, int *surfacelist, const unsigned char *trispvs, const unsigned char *surfacesides)
3757 RSurf_ActiveWorldEntity();
3759 if (rsurface.rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
3762 GL_CullFace(GL_NONE);
3763 mesh = rsurface.rtlight->static_meshchain_shadow_shadowmap;
3764 for (;mesh;mesh = mesh->next)
3766 if (!mesh->sidetotals[r_shadow_shadowmapside])
3768 r_refdef.stats.lights_shadowtriangles += mesh->sidetotals[r_shadow_shadowmapside];
3769 if (mesh->vertex3fbuffer)
3770 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vertex3fbuffer);
3772 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vbo_vertexbuffer);
3773 R_Mesh_Draw(0, mesh->numverts, mesh->sideoffsets[r_shadow_shadowmapside], mesh->sidetotals[r_shadow_shadowmapside], mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset);
3777 else if (r_refdef.scene.worldentity->model)
3778 r_refdef.scene.worldmodel->DrawShadowMap(r_shadow_shadowmapside, r_refdef.scene.worldentity, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius, numsurfaces, surfacelist, surfacesides, rsurface.rtlight->cached_cullmins, rsurface.rtlight->cached_cullmaxs);
3780 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3783 static void R_Shadow_DrawWorldShadow_ShadowVolume(int numsurfaces, int *surfacelist, const unsigned char *trispvs)
3785 qboolean zpass = false;
3788 int surfacelistindex;
3789 msurface_t *surface;
3791 // if triangle neighbors are disabled, shadowvolumes are disabled
3792 if (r_refdef.scene.worldmodel->brush.shadowmesh ? !r_refdef.scene.worldmodel->brush.shadowmesh->neighbor3i : !r_refdef.scene.worldmodel->surfmesh.data_neighbor3i)
3795 RSurf_ActiveWorldEntity();
3797 if (rsurface.rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
3800 if (r_shadow_rendermode != R_SHADOW_RENDERMODE_VISIBLEVOLUMES)
3802 zpass = R_Shadow_UseZPass(r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs);
3803 R_Shadow_RenderMode_StencilShadowVolumes(zpass);
3805 mesh = zpass ? rsurface.rtlight->static_meshchain_shadow_zpass : rsurface.rtlight->static_meshchain_shadow_zfail;
3806 for (;mesh;mesh = mesh->next)
3808 r_refdef.stats.lights_shadowtriangles += mesh->numtriangles;
3809 if (mesh->vertex3fbuffer)
3810 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vertex3fbuffer);
3812 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vbo_vertexbuffer);
3813 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
3815 // increment stencil if frontface is infront of depthbuffer
3816 GL_CullFace(r_refdef.view.cullface_back);
3817 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_ALWAYS, 128, 255);
3818 R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset);
3819 // decrement stencil if backface is infront of depthbuffer
3820 GL_CullFace(r_refdef.view.cullface_front);
3821 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, 128, 255);
3823 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
3825 // decrement stencil if backface is behind depthbuffer
3826 GL_CullFace(r_refdef.view.cullface_front);
3827 R_SetStencil(true, 255, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, 128, 255);
3828 R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset);
3829 // increment stencil if frontface is behind depthbuffer
3830 GL_CullFace(r_refdef.view.cullface_back);
3831 R_SetStencil(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_ALWAYS, 128, 255);
3833 R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset);
3837 else if (numsurfaces && r_refdef.scene.worldmodel->brush.shadowmesh)
3839 // use the shadow trispvs calculated earlier by GetLightInfo to cull world triangles on this dynamic light
3840 R_Shadow_PrepareShadowMark(r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles);
3841 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
3843 surface = r_refdef.scene.worldmodel->data_surfaces + surfacelist[surfacelistindex];
3844 for (t = surface->num_firstshadowmeshtriangle, tend = t + surface->num_triangles;t < tend;t++)
3845 if (CHECKPVSBIT(trispvs, t))
3846 shadowmarklist[numshadowmark++] = t;
3848 R_Shadow_VolumeFromList(r_refdef.scene.worldmodel->brush.shadowmesh->numverts, r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles, r_refdef.scene.worldmodel->brush.shadowmesh->vertex3f, r_refdef.scene.worldmodel->brush.shadowmesh->element3i, r_refdef.scene.worldmodel->brush.shadowmesh->neighbor3i, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius + r_refdef.scene.worldmodel->radius*2 + r_shadow_projectdistance.value, numshadowmark, shadowmarklist, r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs);
3850 else if (numsurfaces)
3852 r_refdef.scene.worldmodel->DrawShadowVolume(r_refdef.scene.worldentity, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius, numsurfaces, surfacelist, rsurface.rtlight->cached_cullmins, rsurface.rtlight->cached_cullmaxs);
3855 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3858 static void R_Shadow_DrawEntityShadow(entity_render_t *ent)
3860 vec3_t relativeshadoworigin, relativeshadowmins, relativeshadowmaxs;
3861 vec_t relativeshadowradius;
3862 RSurf_ActiveModelEntity(ent, false, false, false);
3863 Matrix4x4_Transform(&ent->inversematrix, rsurface.rtlight->shadoworigin, relativeshadoworigin);
3864 // we need to re-init the shader for each entity because the matrix changed
3865 relativeshadowradius = rsurface.rtlight->radius / ent->scale;
3866 relativeshadowmins[0] = relativeshadoworigin[0] - relativeshadowradius;
3867 relativeshadowmins[1] = relativeshadoworigin[1] - relativeshadowradius;
3868 relativeshadowmins[2] = relativeshadoworigin[2] - relativeshadowradius;
3869 relativeshadowmaxs[0] = relativeshadoworigin[0] + relativeshadowradius;
3870 relativeshadowmaxs[1] = relativeshadoworigin[1] + relativeshadowradius;
3871 relativeshadowmaxs[2] = relativeshadoworigin[2] + relativeshadowradius;
3872 switch (r_shadow_rendermode)
3874 case R_SHADOW_RENDERMODE_SHADOWMAP2D:
3875 ent->model->DrawShadowMap(r_shadow_shadowmapside, ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, NULL, relativeshadowmins, relativeshadowmaxs);
3878 ent->model->DrawShadowVolume(ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
3881 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3884 void R_Shadow_SetupEntityLight(const entity_render_t *ent)
3886 // set up properties for rendering light onto this entity
3887 RSurf_ActiveModelEntity(ent, true, true, false);
3888 Matrix4x4_Concat(&rsurface.entitytolight, &rsurface.rtlight->matrix_worldtolight, &ent->matrix);
3889 Matrix4x4_Concat(&rsurface.entitytoattenuationxyz, &matrix_attenuationxyz, &rsurface.entitytolight);
3890 Matrix4x4_Concat(&rsurface.entitytoattenuationz, &matrix_attenuationz, &rsurface.entitytolight);
3891 Matrix4x4_Transform(&ent->inversematrix, rsurface.rtlight->shadoworigin, rsurface.entitylightorigin);
3894 static void R_Shadow_DrawWorldLight(int numsurfaces, int *surfacelist, const unsigned char *lighttrispvs)
3896 if (!r_refdef.scene.worldmodel->DrawLight)
3899 // set up properties for rendering light onto this entity
3900 RSurf_ActiveWorldEntity();
3901 rsurface.entitytolight = rsurface.rtlight->matrix_worldtolight;
3902 Matrix4x4_Concat(&rsurface.entitytoattenuationxyz, &matrix_attenuationxyz, &rsurface.entitytolight);
3903 Matrix4x4_Concat(&rsurface.entitytoattenuationz, &matrix_attenuationz, &rsurface.entitytolight);
3904 VectorCopy(rsurface.rtlight->shadoworigin, rsurface.entitylightorigin);
3906 r_refdef.scene.worldmodel->DrawLight(r_refdef.scene.worldentity, numsurfaces, surfacelist, lighttrispvs);
3908 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3911 static void R_Shadow_DrawEntityLight(entity_render_t *ent)
3913 dp_model_t *model = ent->model;
3914 if (!model->DrawLight)
3917 R_Shadow_SetupEntityLight(ent);
3919 model->DrawLight(ent, model->nummodelsurfaces, model->sortedmodelsurfaces, NULL);
3921 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3924 static void R_Shadow_PrepareLight(rtlight_t *rtlight)
3928 int numleafs, numsurfaces;
3929 int *leaflist, *surfacelist;
3930 unsigned char *leafpvs;
3931 unsigned char *shadowtrispvs;
3932 unsigned char *lighttrispvs;
3933 //unsigned char *surfacesides;
3934 int numlightentities;
3935 int numlightentities_noselfshadow;
3936 int numshadowentities;
3937 int numshadowentities_noselfshadow;
3938 static entity_render_t *lightentities[MAX_EDICTS];
3939 static entity_render_t *lightentities_noselfshadow[MAX_EDICTS];
3940 static entity_render_t *shadowentities[MAX_EDICTS];
3941 static entity_render_t *shadowentities_noselfshadow[MAX_EDICTS];
3944 rtlight->draw = false;
3945 rtlight->cached_numlightentities = 0;
3946 rtlight->cached_numlightentities_noselfshadow = 0;
3947 rtlight->cached_numshadowentities = 0;
3948 rtlight->cached_numshadowentities_noselfshadow = 0;
3949 rtlight->cached_numsurfaces = 0;
3950 rtlight->cached_lightentities = NULL;
3951 rtlight->cached_lightentities_noselfshadow = NULL;
3952 rtlight->cached_shadowentities = NULL;
3953 rtlight->cached_shadowentities_noselfshadow = NULL;
3954 rtlight->cached_shadowtrispvs = NULL;
3955 rtlight->cached_lighttrispvs = NULL;
3956 rtlight->cached_surfacelist = NULL;
3958 // skip lights that don't light because of ambientscale+diffusescale+specularscale being 0 (corona only lights)
3959 // skip lights that are basically invisible (color 0 0 0)
3960 nolight = VectorLength2(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) < (1.0f / 1048576.0f);
3962 // loading is done before visibility checks because loading should happen
3963 // all at once at the start of a level, not when it stalls gameplay.
3964 // (especially important to benchmarks)
3966 if (rtlight->isstatic && !nolight && (!rtlight->compiled || (rtlight->shadow && rtlight->shadowmode != (int)r_shadow_shadowmode)) && r_shadow_realtime_world_compile.integer)
3968 if (rtlight->compiled)
3969 R_RTLight_Uncompile(rtlight);
3970 R_RTLight_Compile(rtlight);
3974 rtlight->currentcubemap = rtlight->cubemapname[0] ? R_GetCubemap(rtlight->cubemapname) : r_texture_whitecube;
3976 // look up the light style value at this time
3977 f = (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value;
3978 VectorScale(rtlight->color, f, rtlight->currentcolor);
3980 if (rtlight->selected)
3982 f = 2 + sin(realtime * M_PI * 4.0);
3983 VectorScale(rtlight->currentcolor, f, rtlight->currentcolor);
3987 // if lightstyle is currently off, don't draw the light
3988 if (VectorLength2(rtlight->currentcolor) < (1.0f / 1048576.0f))
3991 // skip processing on corona-only lights
3995 // if the light box is offscreen, skip it
3996 if (R_CullBox(rtlight->cullmins, rtlight->cullmaxs))
3999 VectorCopy(rtlight->cullmins, rtlight->cached_cullmins);
4000 VectorCopy(rtlight->cullmaxs, rtlight->cached_cullmaxs);
4002 R_Shadow_ComputeShadowCasterCullingPlanes(rtlight);
4004 // don't allow lights to be drawn if using r_shadow_bouncegrid 2, except if we're using static bouncegrid where dynamic lights still need to draw
4005 if (r_shadow_bouncegrid.integer == 2 && (rtlight->isstatic || !r_shadow_bouncegrid_static.integer))
4008 if (rtlight->compiled && r_shadow_realtime_world_compile.integer)
4010 // compiled light, world available and can receive realtime lighting
4011 // retrieve leaf information
4012 numleafs = rtlight->static_numleafs;
4013 leaflist = rtlight->static_leaflist;
4014 leafpvs = rtlight->static_leafpvs;
4015 numsurfaces = rtlight->static_numsurfaces;
4016 surfacelist = rtlight->static_surfacelist;
4017 //surfacesides = NULL;
4018 shadowtrispvs = rtlight->static_shadowtrispvs;
4019 lighttrispvs = rtlight->static_lighttrispvs;
4021 else if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->GetLightInfo)
4023 // dynamic light, world available and can receive realtime lighting
4024 // calculate lit surfaces and leafs
4025 r_refdef.scene.worldmodel->GetLightInfo(r_refdef.scene.worldentity, rtlight->shadoworigin, rtlight->radius, rtlight->cached_cullmins, rtlight->cached_cullmaxs, r_shadow_buffer_leaflist, r_shadow_buffer_leafpvs, &numleafs, r_shadow_buffer_surfacelist, r_shadow_buffer_surfacepvs, &numsurfaces, r_shadow_buffer_shadowtrispvs, r_shadow_buffer_lighttrispvs, r_shadow_buffer_visitingleafpvs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes);
4026 R_Shadow_ComputeShadowCasterCullingPlanes(rtlight);
4027 leaflist = r_shadow_buffer_leaflist;
4028 leafpvs = r_shadow_buffer_leafpvs;
4029 surfacelist = r_shadow_buffer_surfacelist;
4030 //surfacesides = r_shadow_buffer_surfacesides;
4031 shadowtrispvs = r_shadow_buffer_shadowtrispvs;
4032 lighttrispvs = r_shadow_buffer_lighttrispvs;
4033 // if the reduced leaf bounds are offscreen, skip it
4034 if (R_CullBox(rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4045 //surfacesides = NULL;
4046 shadowtrispvs = NULL;
4047 lighttrispvs = NULL;
4049 // check if light is illuminating any visible leafs
4052 for (i = 0;i < numleafs;i++)
4053 if (r_refdef.viewcache.world_leafvisible[leaflist[i]])
4059 // make a list of lit entities and shadow casting entities
4060 numlightentities = 0;
4061 numlightentities_noselfshadow = 0;
4062 numshadowentities = 0;
4063 numshadowentities_noselfshadow = 0;
4065 // add dynamic entities that are lit by the light
4066 for (i = 0;i < r_refdef.scene.numentities;i++)
4069 entity_render_t *ent = r_refdef.scene.entities[i];
4071 if (!BoxesOverlap(ent->mins, ent->maxs, rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4073 // skip the object entirely if it is not within the valid
4074 // shadow-casting region (which includes the lit region)
4075 if (R_CullBoxCustomPlanes(ent->mins, ent->maxs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes))
4077 if (!(model = ent->model))
4079 if (r_refdef.viewcache.entityvisible[i] && model->DrawLight && (ent->flags & RENDER_LIGHT))
4081 // this entity wants to receive light, is visible, and is
4082 // inside the light box
4083 // TODO: check if the surfaces in the model can receive light
4084 // so now check if it's in a leaf seen by the light
4085 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS && !r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS(r_refdef.scene.worldmodel, leafpvs, ent->mins, ent->maxs))
4087 if (ent->flags & RENDER_NOSELFSHADOW)
4088 lightentities_noselfshadow[numlightentities_noselfshadow++] = ent;
4090 lightentities[numlightentities++] = ent;
4091 // since it is lit, it probably also casts a shadow...
4092 // about the VectorDistance2 - light emitting entities should not cast their own shadow
4093 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
4094 if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1)
4096 // note: exterior models without the RENDER_NOSELFSHADOW
4097 // flag still create a RENDER_NOSELFSHADOW shadow but
4098 // are lit normally, this means that they are
4099 // self-shadowing but do not shadow other
4100 // RENDER_NOSELFSHADOW entities such as the gun
4101 // (very weird, but keeps the player shadow off the gun)
4102 if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL))
4103 shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent;
4105 shadowentities[numshadowentities++] = ent;
4108 else if (ent->flags & RENDER_SHADOW)
4110 // this entity is not receiving light, but may still need to
4112 // TODO: check if the surfaces in the model can cast shadow
4113 // now check if it is in a leaf seen by the light
4114 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS && !r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS(r_refdef.scene.worldmodel, leafpvs, ent->mins, ent->maxs))
4116 // about the VectorDistance2 - light emitting entities should not cast their own shadow
4117 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
4118 if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1)
4120 if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL))
4121 shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent;
4123 shadowentities[numshadowentities++] = ent;
4128 // return if there's nothing at all to light
4129 if (numsurfaces + numlightentities + numlightentities_noselfshadow == 0)
4132 // count this light in the r_speeds
4133 r_refdef.stats.lights++;
4135 // flag it as worth drawing later
4136 rtlight->draw = true;
4138 // cache all the animated entities that cast a shadow but are not visible
4139 for (i = 0;i < numshadowentities;i++)
4140 if (!shadowentities[i]->animcache_vertex3f)
4141 R_AnimCache_GetEntity(shadowentities[i], false, false);
4142 for (i = 0;i < numshadowentities_noselfshadow;i++)
4143 if (!shadowentities_noselfshadow[i]->animcache_vertex3f)
4144 R_AnimCache_GetEntity(shadowentities_noselfshadow[i], false, false);
4146 // allocate some temporary memory for rendering this light later in the frame
4147 // reusable buffers need to be copied, static data can be used as-is
4148 rtlight->cached_numlightentities = numlightentities;
4149 rtlight->cached_numlightentities_noselfshadow = numlightentities_noselfshadow;
4150 rtlight->cached_numshadowentities = numshadowentities;
4151 rtlight->cached_numshadowentities_noselfshadow = numshadowentities_noselfshadow;
4152 rtlight->cached_numsurfaces = numsurfaces;
4153 rtlight->cached_lightentities = (entity_render_t**)R_FrameData_Store(numlightentities*sizeof(entity_render_t*), (void*)lightentities);
4154 rtlight->cached_lightentities_noselfshadow = (entity_render_t**)R_FrameData_Store(numlightentities_noselfshadow*sizeof(entity_render_t*), (void*)lightentities_noselfshadow);
4155 rtlight->cached_shadowentities = (entity_render_t**)R_FrameData_Store(numshadowentities*sizeof(entity_render_t*), (void*)shadowentities);
4156 rtlight->cached_shadowentities_noselfshadow = (entity_render_t**)R_FrameData_Store(numshadowentities_noselfshadow*sizeof(entity_render_t *), (void*)shadowentities_noselfshadow);
4157 if (shadowtrispvs == r_shadow_buffer_shadowtrispvs)
4159 int numshadowtrispvsbytes = (((r_refdef.scene.worldmodel->brush.shadowmesh ? r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles : r_refdef.scene.worldmodel->surfmesh.num_triangles) + 7) >> 3);
4160 int numlighttrispvsbytes = ((r_refdef.scene.worldmodel->surfmesh.num_triangles + 7) >> 3);
4161 rtlight->cached_shadowtrispvs = (unsigned char *)R_FrameData_Store(numshadowtrispvsbytes, shadowtrispvs);
4162 rtlight->cached_lighttrispvs = (unsigned char *)R_FrameData_Store(numlighttrispvsbytes, lighttrispvs);
4163 rtlight->cached_surfacelist = (int*)R_FrameData_Store(numsurfaces*sizeof(int), (void*)surfacelist);
4167 // compiled light data
4168 rtlight->cached_shadowtrispvs = shadowtrispvs;
4169 rtlight->cached_lighttrispvs = lighttrispvs;
4170 rtlight->cached_surfacelist = surfacelist;
4174 static void R_Shadow_DrawLight(rtlight_t *rtlight)
4178 unsigned char *shadowtrispvs, *lighttrispvs, *surfacesides;
4179 int numlightentities;
4180 int numlightentities_noselfshadow;
4181 int numshadowentities;
4182 int numshadowentities_noselfshadow;
4183 entity_render_t **lightentities;
4184 entity_render_t **lightentities_noselfshadow;
4185 entity_render_t **shadowentities;
4186 entity_render_t **shadowentities_noselfshadow;
4188 static unsigned char entitysides[MAX_EDICTS];
4189 static unsigned char entitysides_noselfshadow[MAX_EDICTS];
4190 vec3_t nearestpoint;
4192 qboolean castshadows;
4195 // check if we cached this light this frame (meaning it is worth drawing)
4199 numlightentities = rtlight->cached_numlightentities;
4200 numlightentities_noselfshadow = rtlight->cached_numlightentities_noselfshadow;
4201 numshadowentities = rtlight->cached_numshadowentities;
4202 numshadowentities_noselfshadow = rtlight->cached_numshadowentities_noselfshadow;
4203 numsurfaces = rtlight->cached_numsurfaces;
4204 lightentities = rtlight->cached_lightentities;
4205 lightentities_noselfshadow = rtlight->cached_lightentities_noselfshadow;
4206 shadowentities = rtlight->cached_shadowentities;
4207 shadowentities_noselfshadow = rtlight->cached_shadowentities_noselfshadow;
4208 shadowtrispvs = rtlight->cached_shadowtrispvs;
4209 lighttrispvs = rtlight->cached_lighttrispvs;
4210 surfacelist = rtlight->cached_surfacelist;
4212 // set up a scissor rectangle for this light
4213 if (R_Shadow_ScissorForBBox(rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4216 // don't let sound skip if going slow
4217 if (r_refdef.scene.extraupdate)
4220 // make this the active rtlight for rendering purposes
4221 R_Shadow_RenderMode_ActiveLight(rtlight);
4223 if (r_showshadowvolumes.integer && r_refdef.view.showdebug && numsurfaces + numshadowentities + numshadowentities_noselfshadow && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows))
4225 // optionally draw visible shape of the shadow volumes
4226 // for performance analysis by level designers
4227 R_Shadow_RenderMode_VisibleShadowVolumes();
4229 R_Shadow_DrawWorldShadow_ShadowVolume(numsurfaces, surfacelist, shadowtrispvs);
4230 for (i = 0;i < numshadowentities;i++)
4231 R_Shadow_DrawEntityShadow(shadowentities[i]);
4232 for (i = 0;i < numshadowentities_noselfshadow;i++)
4233 R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4234 R_Shadow_RenderMode_VisibleLighting(false, false);
4237 if (r_showlighting.integer && r_refdef.view.showdebug && numsurfaces + numlightentities + numlightentities_noselfshadow)
4239 // optionally draw the illuminated areas
4240 // for performance analysis by level designers
4241 R_Shadow_RenderMode_VisibleLighting(false, false);
4243 R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4244 for (i = 0;i < numlightentities;i++)
4245 R_Shadow_DrawEntityLight(lightentities[i]);
4246 for (i = 0;i < numlightentities_noselfshadow;i++)
4247 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4250 castshadows = numsurfaces + numshadowentities + numshadowentities_noselfshadow > 0 && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows);
4252 nearestpoint[0] = bound(rtlight->cullmins[0], r_refdef.view.origin[0], rtlight->cullmaxs[0]);
4253 nearestpoint[1] = bound(rtlight->cullmins[1], r_refdef.view.origin[1], rtlight->cullmaxs[1]);
4254 nearestpoint[2] = bound(rtlight->cullmins[2], r_refdef.view.origin[2], rtlight->cullmaxs[2]);
4255 distance = VectorDistance(nearestpoint, r_refdef.view.origin);
4257 lodlinear = (rtlight->radius * r_shadow_shadowmapping_precision.value) / sqrt(max(1.0f, distance/rtlight->radius));
4258 //lodlinear = (int)(r_shadow_shadowmapping_lod_bias.value + r_shadow_shadowmapping_lod_scale.value * rtlight->radius / max(1.0f, distance));
4259 lodlinear = bound(r_shadow_shadowmapping_minsize.integer, lodlinear, r_shadow_shadowmapmaxsize);
4261 if (castshadows && r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D)
4267 int receivermask = 0;
4268 matrix4x4_t radiustolight = rtlight->matrix_worldtolight;
4269 Matrix4x4_Abs(&radiustolight);
4271 r_shadow_shadowmaplod = 0;
4272 for (i = 1;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
4273 if ((r_shadow_shadowmapmaxsize >> i) > lodlinear)
4274 r_shadow_shadowmaplod = i;
4276 size = bound(r_shadow_shadowmapborder, lodlinear, r_shadow_shadowmapmaxsize);
4278 borderbias = r_shadow_shadowmapborder / (float)(size - r_shadow_shadowmapborder);
4280 surfacesides = NULL;
4283 if (rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
4285 castermask = rtlight->static_shadowmap_casters;
4286 receivermask = rtlight->static_shadowmap_receivers;
4290 surfacesides = r_shadow_buffer_surfacesides;
4291 for(i = 0;i < numsurfaces;i++)
4293 msurface_t *surface = r_refdef.scene.worldmodel->data_surfaces + surfacelist[i];
4294 surfacesides[i] = R_Shadow_CalcBBoxSideMask(surface->mins, surface->maxs, &rtlight->matrix_worldtolight, &radiustolight, borderbias);
4295 castermask |= surfacesides[i];
4296 receivermask |= surfacesides[i];
4300 if (receivermask < 0x3F)
4302 for (i = 0;i < numlightentities;i++)
4303 receivermask |= R_Shadow_CalcEntitySideMask(lightentities[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias);
4304 if (receivermask < 0x3F)
4305 for(i = 0; i < numlightentities_noselfshadow;i++)
4306 receivermask |= R_Shadow_CalcEntitySideMask(lightentities_noselfshadow[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias);
4309 receivermask &= R_Shadow_CullFrustumSides(rtlight, size, r_shadow_shadowmapborder);
4313 for (i = 0;i < numshadowentities;i++)
4314 castermask |= (entitysides[i] = R_Shadow_CalcEntitySideMask(shadowentities[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias));
4315 for (i = 0;i < numshadowentities_noselfshadow;i++)
4316 castermask |= (entitysides_noselfshadow[i] = R_Shadow_CalcEntitySideMask(shadowentities_noselfshadow[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias));
4319 //Con_Printf("distance %f lodlinear %i (lod %i) size %i\n", distance, lodlinear, r_shadow_shadowmaplod, size);
4321 // render shadow casters into 6 sided depth texture
4322 for (side = 0;side < 6;side++) if (receivermask & (1 << side))
4324 R_Shadow_RenderMode_ShadowMap(side, receivermask, size);
4325 if (! (castermask & (1 << side))) continue;
4327 R_Shadow_DrawWorldShadow_ShadowMap(numsurfaces, surfacelist, shadowtrispvs, surfacesides);
4328 for (i = 0;i < numshadowentities;i++) if (entitysides[i] & (1 << side))
4329 R_Shadow_DrawEntityShadow(shadowentities[i]);
4332 if (numlightentities_noselfshadow)
4334 // render lighting using the depth texture as shadowmap
4335 // draw lighting in the unmasked areas
4336 R_Shadow_RenderMode_Lighting(false, false, true);
4337 for (i = 0;i < numlightentities_noselfshadow;i++)
4338 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4341 // render shadow casters into 6 sided depth texture
4342 if (numshadowentities_noselfshadow)
4344 for (side = 0;side < 6;side++) if ((receivermask & castermask) & (1 << side))
4346 R_Shadow_RenderMode_ShadowMap(side, 0, size);
4347 for (i = 0;i < numshadowentities_noselfshadow;i++) if (entitysides_noselfshadow[i] & (1 << side))
4348 R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4352 // render lighting using the depth texture as shadowmap
4353 // draw lighting in the unmasked areas
4354 R_Shadow_RenderMode_Lighting(false, false, true);
4355 // draw lighting in the unmasked areas
4357 R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4358 for (i = 0;i < numlightentities;i++)
4359 R_Shadow_DrawEntityLight(lightentities[i]);
4361 else if (castshadows && vid.stencil)
4363 // draw stencil shadow volumes to mask off pixels that are in shadow
4364 // so that they won't receive lighting
4365 GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
4366 R_Shadow_ClearStencil();
4369 R_Shadow_DrawWorldShadow_ShadowVolume(numsurfaces, surfacelist, shadowtrispvs);
4370 for (i = 0;i < numshadowentities;i++)
4371 R_Shadow_DrawEntityShadow(shadowentities[i]);
4373 // draw lighting in the unmasked areas
4374 R_Shadow_RenderMode_Lighting(true, false, false);
4375 for (i = 0;i < numlightentities_noselfshadow;i++)
4376 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4378 for (i = 0;i < numshadowentities_noselfshadow;i++)
4379 R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4381 // draw lighting in the unmasked areas
4382 R_Shadow_RenderMode_Lighting(true, false, false);
4384 R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4385 for (i = 0;i < numlightentities;i++)
4386 R_Shadow_DrawEntityLight(lightentities[i]);
4390 // draw lighting in the unmasked areas
4391 R_Shadow_RenderMode_Lighting(false, false, false);
4393 R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4394 for (i = 0;i < numlightentities;i++)
4395 R_Shadow_DrawEntityLight(lightentities[i]);
4396 for (i = 0;i < numlightentities_noselfshadow;i++)
4397 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4400 if (r_shadow_usingdeferredprepass)
4402 // when rendering deferred lighting, we simply rasterize the box
4403 if (castshadows && r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D)
4404 R_Shadow_RenderMode_DrawDeferredLight(false, true);
4405 else if (castshadows && vid.stencil)
4406 R_Shadow_RenderMode_DrawDeferredLight(true, false);
4408 R_Shadow_RenderMode_DrawDeferredLight(false, false);
4412 static void R_Shadow_FreeDeferred(void)
4414 R_Mesh_DestroyFramebufferObject(r_shadow_prepassgeometryfbo);
4415 r_shadow_prepassgeometryfbo = 0;
4417 R_Mesh_DestroyFramebufferObject(r_shadow_prepasslightingdiffusespecularfbo);
4418 r_shadow_prepasslightingdiffusespecularfbo = 0;
4420 R_Mesh_DestroyFramebufferObject(r_shadow_prepasslightingdiffusefbo);
4421 r_shadow_prepasslightingdiffusefbo = 0;
4423 if (r_shadow_prepassgeometrydepthbuffer)
4424 R_FreeTexture(r_shadow_prepassgeometrydepthbuffer);
4425 r_shadow_prepassgeometrydepthbuffer = NULL;
4427 if (r_shadow_prepassgeometrynormalmaptexture)
4428 R_FreeTexture(r_shadow_prepassgeometrynormalmaptexture);
4429 r_shadow_prepassgeometrynormalmaptexture = NULL;
4431 if (r_shadow_prepasslightingdiffusetexture)
4432 R_FreeTexture(r_shadow_prepasslightingdiffusetexture);
4433 r_shadow_prepasslightingdiffusetexture = NULL;
4435 if (r_shadow_prepasslightingspeculartexture)
4436 R_FreeTexture(r_shadow_prepasslightingspeculartexture);
4437 r_shadow_prepasslightingspeculartexture = NULL;
4440 void R_Shadow_DrawPrepass(void)
4448 entity_render_t *ent;
4449 float clearcolor[4];
4451 R_Mesh_ResetTextureState();
4453 GL_ColorMask(1,1,1,1);
4454 GL_BlendFunc(GL_ONE, GL_ZERO);
4457 R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL);
4458 Vector4Set(clearcolor, 0.5f,0.5f,0.5f,1.0f);
4459 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4460 if (r_timereport_active)
4461 R_TimeReport("prepasscleargeom");
4463 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawPrepass)
4464 r_refdef.scene.worldmodel->DrawPrepass(r_refdef.scene.worldentity);
4465 if (r_timereport_active)
4466 R_TimeReport("prepassworld");
4468 for (i = 0;i < r_refdef.scene.numentities;i++)
4470 if (!r_refdef.viewcache.entityvisible[i])
4472 ent = r_refdef.scene.entities[i];
4473 if (ent->model && ent->model->DrawPrepass != NULL)
4474 ent->model->DrawPrepass(ent);
4477 if (r_timereport_active)
4478 R_TimeReport("prepassmodels");
4480 GL_DepthMask(false);
4481 GL_ColorMask(1,1,1,1);
4484 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4485 Vector4Set(clearcolor, 0, 0, 0, 0);
4486 GL_Clear(GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
4487 if (r_timereport_active)
4488 R_TimeReport("prepassclearlit");
4490 R_Shadow_RenderMode_Begin();
4492 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4493 if (r_shadow_debuglight.integer >= 0)
4495 lightindex = r_shadow_debuglight.integer;
4496 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4497 if (light && (light->flags & flag) && light->rtlight.draw)
4498 R_Shadow_DrawLight(&light->rtlight);
4502 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4503 for (lightindex = 0;lightindex < range;lightindex++)
4505 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4506 if (light && (light->flags & flag) && light->rtlight.draw)
4507 R_Shadow_DrawLight(&light->rtlight);
4510 if (r_refdef.scene.rtdlight)
4511 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4512 if (r_refdef.scene.lights[lnum]->draw)
4513 R_Shadow_DrawLight(r_refdef.scene.lights[lnum]);
4515 R_Shadow_RenderMode_End();
4517 if (r_timereport_active)
4518 R_TimeReport("prepasslights");
4521 void R_Shadow_DrawLightSprites(void);
4522 void R_Shadow_PrepareLights(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture)
4531 if (r_shadow_shadowmapmaxsize != bound(1, r_shadow_shadowmapping_maxsize.integer, (int)vid.maxtexturesize_2d / 4) ||
4532 (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL) != (r_shadow_shadowmapping.integer || r_shadow_deferred.integer) ||
4533 r_shadow_shadowmapvsdct != (r_shadow_shadowmapping_vsdct.integer != 0 && vid.renderpath == RENDERPATH_GL20) ||
4534 r_shadow_shadowmapfilterquality != r_shadow_shadowmapping_filterquality.integer ||
4535 r_shadow_shadowmapshadowsampler != (vid.support.arb_shadow && r_shadow_shadowmapping_useshadowsampler.integer) ||
4536 r_shadow_shadowmapdepthbits != r_shadow_shadowmapping_depthbits.integer ||
4537 r_shadow_shadowmapborder != bound(0, r_shadow_shadowmapping_bordersize.integer, 16) ||
4538 r_shadow_shadowmapdepthtexture != r_fb.usedepthtextures)
4539 R_Shadow_FreeShadowMaps();
4541 r_shadow_fb_fbo = fbo;
4542 r_shadow_fb_depthtexture = depthtexture;
4543 r_shadow_fb_colortexture = colortexture;
4545 r_shadow_usingshadowmaportho = false;
4547 switch (vid.renderpath)
4549 case RENDERPATH_GL20:
4550 case RENDERPATH_D3D9:
4551 case RENDERPATH_D3D10:
4552 case RENDERPATH_D3D11:
4553 case RENDERPATH_SOFT:
4555 if (!r_shadow_deferred.integer || r_shadow_shadowmode == R_SHADOW_SHADOWMODE_STENCIL || !vid.support.ext_framebuffer_object || vid.maxdrawbuffers < 2)
4557 r_shadow_usingdeferredprepass = false;
4558 if (r_shadow_prepass_width)
4559 R_Shadow_FreeDeferred();
4560 r_shadow_prepass_width = r_shadow_prepass_height = 0;
4564 if (r_shadow_prepass_width != vid.width || r_shadow_prepass_height != vid.height)
4566 R_Shadow_FreeDeferred();
4568 r_shadow_usingdeferredprepass = true;
4569 r_shadow_prepass_width = vid.width;
4570 r_shadow_prepass_height = vid.height;
4571 r_shadow_prepassgeometrydepthbuffer = R_LoadTextureRenderBuffer(r_shadow_texturepool, "prepassgeometrydepthbuffer", vid.width, vid.height, TEXTYPE_DEPTHBUFFER24);
4572 r_shadow_prepassgeometrynormalmaptexture = R_LoadTexture2D(r_shadow_texturepool, "prepassgeometrynormalmap", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER32F, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4573 r_shadow_prepasslightingdiffusetexture = R_LoadTexture2D(r_shadow_texturepool, "prepasslightingdiffuse", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER16F, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4574 r_shadow_prepasslightingspeculartexture = R_LoadTexture2D(r_shadow_texturepool, "prepasslightingspecular", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER16F, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4576 // set up the geometry pass fbo (depth + normalmap)
4577 r_shadow_prepassgeometryfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthbuffer, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL);
4578 R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL);
4579 // render depth into a renderbuffer and other important properties into the normalmap texture
4581 // set up the lighting pass fbo (diffuse + specular)
4582 r_shadow_prepasslightingdiffusespecularfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4583 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4584 // render diffuse into one texture and specular into another,
4585 // with depth and normalmap bound as textures,
4586 // with depth bound as attachment as well
4588 // set up the lighting pass fbo (diffuse)
4589 r_shadow_prepasslightingdiffusefbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
4590 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
4591 // render diffuse into one texture,
4592 // with depth and normalmap bound as textures,
4593 // with depth bound as attachment as well
4597 case RENDERPATH_GL11:
4598 case RENDERPATH_GL13:
4599 case RENDERPATH_GLES1:
4600 case RENDERPATH_GLES2:
4601 r_shadow_usingdeferredprepass = false;
4605 R_Shadow_EnlargeLeafSurfaceTrisBuffer(r_refdef.scene.worldmodel->brush.num_leafs, r_refdef.scene.worldmodel->num_surfaces, r_refdef.scene.worldmodel->brush.shadowmesh ? r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles : r_refdef.scene.worldmodel->surfmesh.num_triangles, r_refdef.scene.worldmodel->surfmesh.num_triangles);
4607 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4608 if (r_shadow_debuglight.integer >= 0)
4610 lightindex = r_shadow_debuglight.integer;
4611 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4613 R_Shadow_PrepareLight(&light->rtlight);
4617 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4618 for (lightindex = 0;lightindex < range;lightindex++)
4620 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4621 if (light && (light->flags & flag))
4622 R_Shadow_PrepareLight(&light->rtlight);
4625 if (r_refdef.scene.rtdlight)
4627 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4628 R_Shadow_PrepareLight(r_refdef.scene.lights[lnum]);
4630 else if(gl_flashblend.integer)
4632 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4634 rtlight_t *rtlight = r_refdef.scene.lights[lnum];
4635 f = (rtlight->style >= 0 ? r_refdef.scene.lightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value;
4636 VectorScale(rtlight->color, f, rtlight->currentcolor);
4640 if (r_editlights.integer)
4641 R_Shadow_DrawLightSprites();
4644 void R_Shadow_DrawLights(void)
4652 R_Shadow_RenderMode_Begin();
4654 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4655 if (r_shadow_debuglight.integer >= 0)
4657 lightindex = r_shadow_debuglight.integer;
4658 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4660 R_Shadow_DrawLight(&light->rtlight);
4664 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4665 for (lightindex = 0;lightindex < range;lightindex++)
4667 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4668 if (light && (light->flags & flag))
4669 R_Shadow_DrawLight(&light->rtlight);
4672 if (r_refdef.scene.rtdlight)
4673 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4674 R_Shadow_DrawLight(r_refdef.scene.lights[lnum]);
4676 R_Shadow_RenderMode_End();
4679 void R_Shadow_PrepareModelShadows(void)
4682 float scale, size, radius, dot1, dot2;
4683 prvm_vec3_t prvmshadowdir, prvmshadowfocus;
4684 vec3_t shadowdir, shadowforward, shadowright, shadoworigin, shadowfocus, shadowmins, shadowmaxs;
4685 entity_render_t *ent;
4687 if (!r_refdef.scene.numentities)
4690 switch (r_shadow_shadowmode)
4692 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4693 if (r_shadows.integer >= 2)
4696 case R_SHADOW_SHADOWMODE_STENCIL:
4697 for (i = 0;i < r_refdef.scene.numentities;i++)
4699 ent = r_refdef.scene.entities[i];
4700 if (!ent->animcache_vertex3f && ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4701 R_AnimCache_GetEntity(ent, false, false);
4708 size = 2*r_shadow_shadowmapmaxsize;
4709 scale = r_shadow_shadowmapping_precision.value * r_shadows_shadowmapscale.value;
4710 radius = 0.5f * size / scale;
4712 Math_atov(r_shadows_throwdirection.string, prvmshadowdir);
4713 VectorCopy(prvmshadowdir, shadowdir);
4714 VectorNormalize(shadowdir);
4715 dot1 = DotProduct(r_refdef.view.forward, shadowdir);
4716 dot2 = DotProduct(r_refdef.view.up, shadowdir);
4717 if (fabs(dot1) <= fabs(dot2))
4718 VectorMA(r_refdef.view.forward, -dot1, shadowdir, shadowforward);
4720 VectorMA(r_refdef.view.up, -dot2, shadowdir, shadowforward);
4721 VectorNormalize(shadowforward);
4722 CrossProduct(shadowdir, shadowforward, shadowright);
4723 Math_atov(r_shadows_focus.string, prvmshadowfocus);
4724 VectorCopy(prvmshadowfocus, shadowfocus);
4725 VectorM(shadowfocus[0], r_refdef.view.right, shadoworigin);
4726 VectorMA(shadoworigin, shadowfocus[1], r_refdef.view.up, shadoworigin);
4727 VectorMA(shadoworigin, -shadowfocus[2], r_refdef.view.forward, shadoworigin);
4728 VectorAdd(shadoworigin, r_refdef.view.origin, shadoworigin);
4729 if (shadowfocus[0] || shadowfocus[1] || shadowfocus[2])
4731 VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin);
4733 shadowmins[0] = shadoworigin[0] - r_shadows_throwdistance.value * fabs(shadowdir[0]) - radius * (fabs(shadowforward[0]) + fabs(shadowright[0]));
4734 shadowmins[1] = shadoworigin[1] - r_shadows_throwdistance.value * fabs(shadowdir[1]) - radius * (fabs(shadowforward[1]) + fabs(shadowright[1]));
4735 shadowmins[2] = shadoworigin[2] - r_shadows_throwdistance.value * fabs(shadowdir[2]) - radius * (fabs(shadowforward[2]) + fabs(shadowright[2]));
4736 shadowmaxs[0] = shadoworigin[0] + r_shadows_throwdistance.value * fabs(shadowdir[0]) + radius * (fabs(shadowforward[0]) + fabs(shadowright[0]));
4737 shadowmaxs[1] = shadoworigin[1] + r_shadows_throwdistance.value * fabs(shadowdir[1]) + radius * (fabs(shadowforward[1]) + fabs(shadowright[1]));
4738 shadowmaxs[2] = shadoworigin[2] + r_shadows_throwdistance.value * fabs(shadowdir[2]) + radius * (fabs(shadowforward[2]) + fabs(shadowright[2]));
4740 for (i = 0;i < r_refdef.scene.numentities;i++)
4742 ent = r_refdef.scene.entities[i];
4743 if (!BoxesOverlap(ent->mins, ent->maxs, shadowmins, shadowmaxs))
4745 // cast shadows from anything of the map (submodels are optional)
4746 if (!ent->animcache_vertex3f && ent->model && ent->model->DrawShadowMap != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4747 R_AnimCache_GetEntity(ent, false, false);
4751 void R_DrawModelShadowMaps(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture)
4754 float relativethrowdistance, scale, size, radius, nearclip, farclip, bias, dot1, dot2;
4755 entity_render_t *ent;
4756 vec3_t relativelightorigin;
4757 vec3_t relativelightdirection, relativeforward, relativeright;
4758 vec3_t relativeshadowmins, relativeshadowmaxs;
4759 vec3_t shadowdir, shadowforward, shadowright, shadoworigin, shadowfocus;
4760 prvm_vec3_t prvmshadowdir, prvmshadowfocus;
4762 matrix4x4_t shadowmatrix, cameramatrix, mvpmatrix, invmvpmatrix, scalematrix, texmatrix;
4763 r_viewport_t viewport;
4764 GLuint shadowfbo = 0;
4765 float clearcolor[4];
4767 if (!r_refdef.scene.numentities)
4770 switch (r_shadow_shadowmode)
4772 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4778 r_shadow_fb_fbo = fbo;
4779 r_shadow_fb_depthtexture = depthtexture;
4780 r_shadow_fb_colortexture = colortexture;
4782 R_ResetViewRendering3D(fbo, depthtexture, colortexture);
4783 R_Shadow_RenderMode_Begin();
4784 R_Shadow_RenderMode_ActiveLight(NULL);
4786 switch (r_shadow_shadowmode)
4788 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4789 if (!r_shadow_shadowmap2ddepthtexture)
4790 R_Shadow_MakeShadowMap(0, r_shadow_shadowmapmaxsize);
4791 shadowfbo = r_shadow_fbo2d;
4792 r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2ddepthtexture);
4793 r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2ddepthtexture);
4794 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
4800 size = 2*r_shadow_shadowmapmaxsize;
4801 scale = (r_shadow_shadowmapping_precision.value * r_shadows_shadowmapscale.value) / size;
4802 radius = 0.5f / scale;
4803 nearclip = -r_shadows_throwdistance.value;
4804 farclip = r_shadows_throwdistance.value;
4805 bias = (r_shadows_shadowmapbias.value < 0) ? r_shadow_shadowmapping_bias.value : r_shadows_shadowmapbias.value * r_shadow_shadowmapping_nearclip.value / (2 * r_shadows_throwdistance.value) * (1024.0f / size);
4807 r_shadow_shadowmap_parameters[0] = size;
4808 r_shadow_shadowmap_parameters[1] = size;
4809 r_shadow_shadowmap_parameters[2] = 1.0;
4810 r_shadow_shadowmap_parameters[3] = bound(0.0f, 1.0f - r_shadows_darken.value, 1.0f);
4812 Math_atov(r_shadows_throwdirection.string, prvmshadowdir);
4813 VectorCopy(prvmshadowdir, shadowdir);
4814 VectorNormalize(shadowdir);
4815 Math_atov(r_shadows_focus.string, prvmshadowfocus);
4816 VectorCopy(prvmshadowfocus, shadowfocus);
4817 VectorM(shadowfocus[0], r_refdef.view.right, shadoworigin);
4818 VectorMA(shadoworigin, shadowfocus[1], r_refdef.view.up, shadoworigin);
4819 VectorMA(shadoworigin, -shadowfocus[2], r_refdef.view.forward, shadoworigin);
4820 VectorAdd(shadoworigin, r_refdef.view.origin, shadoworigin);
4821 dot1 = DotProduct(r_refdef.view.forward, shadowdir);
4822 dot2 = DotProduct(r_refdef.view.up, shadowdir);
4823 if (fabs(dot1) <= fabs(dot2))
4824 VectorMA(r_refdef.view.forward, -dot1, shadowdir, shadowforward);
4826 VectorMA(r_refdef.view.up, -dot2, shadowdir, shadowforward);
4827 VectorNormalize(shadowforward);
4828 VectorM(scale, shadowforward, &m[0]);
4829 if (shadowfocus[0] || shadowfocus[1] || shadowfocus[2])
4831 m[3] = fabs(dot1) * 0.5f - DotProduct(shadoworigin, &m[0]);
4832 CrossProduct(shadowdir, shadowforward, shadowright);
4833 VectorM(scale, shadowright, &m[4]);
4834 m[7] = 0.5f - DotProduct(shadoworigin, &m[4]);
4835 VectorM(1.0f / (farclip - nearclip), shadowdir, &m[8]);
4836 m[11] = 0.5f - DotProduct(shadoworigin, &m[8]);
4837 Matrix4x4_FromArray12FloatD3D(&shadowmatrix, m);
4838 Matrix4x4_Invert_Full(&cameramatrix, &shadowmatrix);
4839 R_Viewport_InitOrtho(&viewport, &cameramatrix, 0, 0, size, size, 0, 0, 1, 1, 0, -1, NULL);
4841 VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin);
4843 if (r_shadow_shadowmap2ddepthbuffer)
4844 R_Mesh_SetRenderTargets(shadowfbo, r_shadow_shadowmap2ddepthbuffer, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL);
4846 R_Mesh_SetRenderTargets(shadowfbo, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL, NULL);
4847 R_SetupShader_DepthOrShadow(true, r_shadow_shadowmap2ddepthbuffer != NULL);
4848 GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
4851 R_SetViewport(&viewport);
4852 GL_Scissor(viewport.x, viewport.y, min(viewport.width + r_shadow_shadowmapborder, 2*r_shadow_shadowmapmaxsize), viewport.height + r_shadow_shadowmapborder);
4853 Vector4Set(clearcolor, 1,1,1,1);
4854 // in D3D9 we have to render to a color texture shadowmap
4855 // in GL we render directly to a depth texture only
4856 if (r_shadow_shadowmap2ddepthbuffer)
4857 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4859 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4860 // render into a slightly restricted region so that the borders of the
4861 // shadowmap area fade away, rather than streaking across everything
4862 // outside the usable area
4863 GL_Scissor(viewport.x + r_shadow_shadowmapborder, viewport.y + r_shadow_shadowmapborder, viewport.width - 2*r_shadow_shadowmapborder, viewport.height - 2*r_shadow_shadowmapborder);
4867 R_Mesh_SetRenderTargets(r_shadow_fb_fbo, r_shadow_fb_depthtexture, r_shadow_fb_colortexture, NULL, NULL, NULL);
4868 R_SetupShader_ShowDepth(true);
4869 GL_ColorMask(1,1,1,1);
4870 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4873 for (i = 0;i < r_refdef.scene.numentities;i++)
4875 ent = r_refdef.scene.entities[i];
4877 // cast shadows from anything of the map (submodels are optional)
4878 if (ent->model && ent->model->DrawShadowMap != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4880 relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix);
4881 Matrix4x4_Transform(&ent->inversematrix, shadoworigin, relativelightorigin);
4882 Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection);
4883 Matrix4x4_Transform3x3(&ent->inversematrix, shadowforward, relativeforward);
4884 Matrix4x4_Transform3x3(&ent->inversematrix, shadowright, relativeright);
4885 relativeshadowmins[0] = relativelightorigin[0] - r_shadows_throwdistance.value * fabs(relativelightdirection[0]) - radius * (fabs(relativeforward[0]) + fabs(relativeright[0]));
4886 relativeshadowmins[1] = relativelightorigin[1] - r_shadows_throwdistance.value * fabs(relativelightdirection[1]) - radius * (fabs(relativeforward[1]) + fabs(relativeright[1]));
4887 relativeshadowmins[2] = relativelightorigin[2] - r_shadows_throwdistance.value * fabs(relativelightdirection[2]) - radius * (fabs(relativeforward[2]) + fabs(relativeright[2]));
4888 relativeshadowmaxs[0] = relativelightorigin[0] + r_shadows_throwdistance.value * fabs(relativelightdirection[0]) + radius * (fabs(relativeforward[0]) + fabs(relativeright[0]));
4889 relativeshadowmaxs[1] = relativelightorigin[1] + r_shadows_throwdistance.value * fabs(relativelightdirection[1]) + radius * (fabs(relativeforward[1]) + fabs(relativeright[1]));
4890 relativeshadowmaxs[2] = relativelightorigin[2] + r_shadows_throwdistance.value * fabs(relativelightdirection[2]) + radius * (fabs(relativeforward[2]) + fabs(relativeright[2]));
4891 RSurf_ActiveModelEntity(ent, false, false, false);
4892 ent->model->DrawShadowMap(0, ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, NULL, relativeshadowmins, relativeshadowmaxs);
4893 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
4900 unsigned char *rawpixels = Z_Malloc(viewport.width*viewport.height*4);
4902 qglReadPixels(viewport.x, viewport.y, viewport.width, viewport.height, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, rawpixels);
4904 Image_WriteTGABGRA("r_shadows_2.tga", viewport.width, viewport.height, rawpixels);
4905 Cvar_SetValueQuick(&r_test, 0);
4910 R_Shadow_RenderMode_End();
4912 Matrix4x4_Concat(&mvpmatrix, &r_refdef.view.viewport.projectmatrix, &r_refdef.view.viewport.viewmatrix);
4913 Matrix4x4_Invert_Full(&invmvpmatrix, &mvpmatrix);
4914 Matrix4x4_CreateScale3(&scalematrix, size, -size, 1);
4915 Matrix4x4_AdjustOrigin(&scalematrix, 0, size, -0.5f * bias);
4916 Matrix4x4_Concat(&texmatrix, &scalematrix, &shadowmatrix);
4917 Matrix4x4_Concat(&r_shadow_shadowmapmatrix, &texmatrix, &invmvpmatrix);
4919 switch (vid.renderpath)
4921 case RENDERPATH_GL11:
4922 case RENDERPATH_GL13:
4923 case RENDERPATH_GL20:
4924 case RENDERPATH_SOFT:
4925 case RENDERPATH_GLES1:
4926 case RENDERPATH_GLES2:
4928 case RENDERPATH_D3D9:
4929 case RENDERPATH_D3D10:
4930 case RENDERPATH_D3D11:
4931 #ifdef OPENGL_ORIENTATION
4932 r_shadow_shadowmapmatrix.m[0][0] *= -1.0f;
4933 r_shadow_shadowmapmatrix.m[0][1] *= -1.0f;
4934 r_shadow_shadowmapmatrix.m[0][2] *= -1.0f;
4935 r_shadow_shadowmapmatrix.m[0][3] *= -1.0f;
4937 r_shadow_shadowmapmatrix.m[0][0] *= -1.0f;
4938 r_shadow_shadowmapmatrix.m[1][0] *= -1.0f;
4939 r_shadow_shadowmapmatrix.m[2][0] *= -1.0f;
4940 r_shadow_shadowmapmatrix.m[3][0] *= -1.0f;
4945 r_shadow_usingshadowmaportho = true;
4946 switch (r_shadow_shadowmode)
4948 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4949 r_shadow_usingshadowmap2d = true;
4956 void R_DrawModelShadows(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture)
4959 float relativethrowdistance;
4960 entity_render_t *ent;
4961 vec3_t relativelightorigin;
4962 vec3_t relativelightdirection;
4963 vec3_t relativeshadowmins, relativeshadowmaxs;
4964 vec3_t tmp, shadowdir;
4965 prvm_vec3_t prvmshadowdir;
4967 if (!r_refdef.scene.numentities || !vid.stencil || (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL && r_shadows.integer != 1))
4970 r_shadow_fb_fbo = fbo;
4971 r_shadow_fb_depthtexture = depthtexture;
4972 r_shadow_fb_colortexture = colortexture;
4974 R_ResetViewRendering3D(fbo, depthtexture, colortexture);
4975 //GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
4976 //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
4977 R_Shadow_RenderMode_Begin();
4978 R_Shadow_RenderMode_ActiveLight(NULL);
4979 r_shadow_lightscissor[0] = r_refdef.view.x;
4980 r_shadow_lightscissor[1] = vid.height - r_refdef.view.y - r_refdef.view.height;
4981 r_shadow_lightscissor[2] = r_refdef.view.width;
4982 r_shadow_lightscissor[3] = r_refdef.view.height;
4983 R_Shadow_RenderMode_StencilShadowVolumes(false);
4986 if (r_shadows.integer == 2)
4988 Math_atov(r_shadows_throwdirection.string, prvmshadowdir);
4989 VectorCopy(prvmshadowdir, shadowdir);
4990 VectorNormalize(shadowdir);
4993 R_Shadow_ClearStencil();
4995 for (i = 0;i < r_refdef.scene.numentities;i++)
4997 ent = r_refdef.scene.entities[i];
4999 // cast shadows from anything of the map (submodels are optional)
5000 if (ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
5002 relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix);
5003 VectorSet(relativeshadowmins, -relativethrowdistance, -relativethrowdistance, -relativethrowdistance);
5004 VectorSet(relativeshadowmaxs, relativethrowdistance, relativethrowdistance, relativethrowdistance);
5005 if (r_shadows.integer == 2) // 2: simpler mode, throw shadows always in same direction
5006 Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection);
5009 if(ent->entitynumber != 0)
5011 if(ent->entitynumber >= MAX_EDICTS) // csqc entity
5013 // FIXME handle this
5014 VectorNegate(ent->modellight_lightdir, relativelightdirection);
5018 // networked entity - might be attached in some way (then we should use the parent's light direction, to not tear apart attached entities)
5019 int entnum, entnum2, recursion;
5020 entnum = entnum2 = ent->entitynumber;
5021 for(recursion = 32; recursion > 0; --recursion)
5023 entnum2 = cl.entities[entnum].state_current.tagentity;
5024 if(entnum2 >= 1 && entnum2 < cl.num_entities && cl.entities_active[entnum2])
5029 if(recursion && recursion != 32) // if we followed a valid non-empty attachment chain
5031 VectorNegate(cl.entities[entnum].render.modellight_lightdir, relativelightdirection);
5032 // transform into modelspace of OUR entity
5033 Matrix4x4_Transform3x3(&cl.entities[entnum].render.matrix, relativelightdirection, tmp);
5034 Matrix4x4_Transform3x3(&ent->inversematrix, tmp, relativelightdirection);
5037 VectorNegate(ent->modellight_lightdir, relativelightdirection);
5041 VectorNegate(ent->modellight_lightdir, relativelightdirection);
5044 VectorScale(relativelightdirection, -relativethrowdistance, relativelightorigin);
5045 RSurf_ActiveModelEntity(ent, false, false, false);
5046 ent->model->DrawShadowVolume(ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
5047 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
5051 // not really the right mode, but this will disable any silly stencil features
5052 R_Shadow_RenderMode_End();
5054 // set up ortho view for rendering this pass
5055 //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
5056 //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5057 //GL_ScissorTest(true);
5058 //R_EntityMatrix(&identitymatrix);
5059 //R_Mesh_ResetTextureState();
5060 R_ResetViewRendering2D(fbo, depthtexture, colortexture);
5062 // set up a darkening blend on shadowed areas
5063 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
5064 //GL_DepthRange(0, 1);
5065 //GL_DepthTest(false);
5066 //GL_DepthMask(false);
5067 //GL_PolygonOffset(0, 0);CHECKGLERROR
5068 GL_Color(0, 0, 0, r_shadows_darken.value);
5069 //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5070 //GL_DepthFunc(GL_ALWAYS);
5071 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_NOTEQUAL, 128, 255);
5073 // apply the blend to the shadowed areas
5074 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
5075 R_SetupShader_Generic_NoTexture(false, true);
5076 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5078 // restore the viewport
5079 R_SetViewport(&r_refdef.view.viewport);
5081 // restore other state to normal
5082 //R_Shadow_RenderMode_End();
5085 static void R_BeginCoronaQuery(rtlight_t *rtlight, float scale, qboolean usequery)
5088 vec3_t centerorigin;
5090 // if it's too close, skip it
5091 if (VectorLength(rtlight->currentcolor) < (1.0f / 256.0f))
5093 zdist = (DotProduct(rtlight->shadoworigin, r_refdef.view.forward) - DotProduct(r_refdef.view.origin, r_refdef.view.forward));
5096 if (usequery && r_numqueries + 2 <= r_maxqueries)
5098 rtlight->corona_queryindex_allpixels = r_queries[r_numqueries++];
5099 rtlight->corona_queryindex_visiblepixels = r_queries[r_numqueries++];
5100 // we count potential samples in the middle of the screen, we count actual samples at the light location, this allows counting potential samples of off-screen lights
5101 VectorMA(r_refdef.view.origin, zdist, r_refdef.view.forward, centerorigin);
5103 switch(vid.renderpath)
5105 case RENDERPATH_GL11:
5106 case RENDERPATH_GL13:
5107 case RENDERPATH_GL20:
5108 case RENDERPATH_GLES1:
5109 case RENDERPATH_GLES2:
5110 #ifdef GL_SAMPLES_PASSED_ARB
5112 // NOTE: GL_DEPTH_TEST must be enabled or ATI won't count samples, so use GL_DepthFunc instead
5113 qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_allpixels);
5114 GL_DepthFunc(GL_ALWAYS);
5115 R_CalcSprite_Vertex3f(vertex3f, centerorigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5116 R_Mesh_PrepareVertices_Vertex3f(4, vertex3f, NULL);
5117 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5118 qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
5119 GL_DepthFunc(GL_LEQUAL);
5120 qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_visiblepixels);
5121 R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5122 R_Mesh_PrepareVertices_Vertex3f(4, vertex3f, NULL);
5123 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5124 qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
5128 case RENDERPATH_D3D9:
5129 Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5131 case RENDERPATH_D3D10:
5132 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5134 case RENDERPATH_D3D11:
5135 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5137 case RENDERPATH_SOFT:
5138 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5142 rtlight->corona_visibility = bound(0, (zdist - 32) / 32, 1);
5145 static float spritetexcoord2f[4*2] = {0, 1, 0, 0, 1, 0, 1, 1};
5147 static void R_DrawCorona(rtlight_t *rtlight, float cscale, float scale)
5150 GLint allpixels = 0, visiblepixels = 0;
5151 // now we have to check the query result
5152 if (rtlight->corona_queryindex_visiblepixels)
5154 switch(vid.renderpath)
5156 case RENDERPATH_GL11:
5157 case RENDERPATH_GL13:
5158 case RENDERPATH_GL20:
5159 case RENDERPATH_GLES1:
5160 case RENDERPATH_GLES2:
5161 #ifdef GL_SAMPLES_PASSED_ARB
5163 qglGetQueryObjectivARB(rtlight->corona_queryindex_visiblepixels, GL_QUERY_RESULT_ARB, &visiblepixels);
5164 qglGetQueryObjectivARB(rtlight->corona_queryindex_allpixels, GL_QUERY_RESULT_ARB, &allpixels);
5168 case RENDERPATH_D3D9:
5169 Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5171 case RENDERPATH_D3D10:
5172 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5174 case RENDERPATH_D3D11:
5175 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5177 case RENDERPATH_SOFT:
5178 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5181 //Con_Printf("%i of %i pixels\n", (int)visiblepixels, (int)allpixels);
5182 if (visiblepixels < 1 || allpixels < 1)
5184 rtlight->corona_visibility *= bound(0, (float)visiblepixels / (float)allpixels, 1);
5185 cscale *= rtlight->corona_visibility;
5189 // FIXME: these traces should scan all render entities instead of cl.world
5190 if (CL_TraceLine(r_refdef.view.origin, rtlight->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
5193 VectorScale(rtlight->currentcolor, cscale, color);
5194 if (VectorLength(color) > (1.0f / 256.0f))
5197 qboolean negated = (color[0] + color[1] + color[2] < 0) && vid.support.ext_blend_subtract;
5200 VectorNegate(color, color);
5201 GL_BlendEquationSubtract(true);
5203 R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5204 RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, RENDER_NODEPTHTEST, 0, color[0], color[1], color[2], 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5205 R_DrawCustomSurface(r_shadow_lightcorona, &identitymatrix, MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5207 GL_BlendEquationSubtract(false);
5211 void R_Shadow_DrawCoronas(void)
5214 qboolean usequery = false;
5219 if (r_coronas.value < (1.0f / 256.0f) && !gl_flashblend.integer)
5221 if (r_fb.water.renderingscene)
5223 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
5224 R_EntityMatrix(&identitymatrix);
5226 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5228 // check occlusion of coronas
5229 // use GL_ARB_occlusion_query if available
5230 // otherwise use raytraces
5232 switch (vid.renderpath)
5234 case RENDERPATH_GL11:
5235 case RENDERPATH_GL13:
5236 case RENDERPATH_GL20:
5237 case RENDERPATH_GLES1:
5238 case RENDERPATH_GLES2:
5239 usequery = vid.support.arb_occlusion_query && r_coronas_occlusionquery.integer;
5240 #ifdef GL_SAMPLES_PASSED_ARB
5243 GL_ColorMask(0,0,0,0);
5244 if (r_maxqueries < (range + r_refdef.scene.numlights) * 2)
5245 if (r_maxqueries < MAX_OCCLUSION_QUERIES)
5248 r_maxqueries = (range + r_refdef.scene.numlights) * 4;
5249 r_maxqueries = min(r_maxqueries, MAX_OCCLUSION_QUERIES);
5251 qglGenQueriesARB(r_maxqueries - i, r_queries + i);
5254 RSurf_ActiveWorldEntity();
5255 GL_BlendFunc(GL_ONE, GL_ZERO);
5256 GL_CullFace(GL_NONE);
5257 GL_DepthMask(false);
5258 GL_DepthRange(0, 1);
5259 GL_PolygonOffset(0, 0);
5261 R_Mesh_ResetTextureState();
5262 R_SetupShader_Generic_NoTexture(false, false);
5266 case RENDERPATH_D3D9:
5268 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5270 case RENDERPATH_D3D10:
5271 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5273 case RENDERPATH_D3D11:
5274 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5276 case RENDERPATH_SOFT:
5278 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5281 for (lightindex = 0;lightindex < range;lightindex++)
5283 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5286 rtlight = &light->rtlight;
5287 rtlight->corona_visibility = 0;
5288 rtlight->corona_queryindex_visiblepixels = 0;
5289 rtlight->corona_queryindex_allpixels = 0;
5290 if (!(rtlight->flags & flag))
5292 if (rtlight->corona <= 0)
5294 if (r_shadow_debuglight.integer >= 0 && r_shadow_debuglight.integer != (int)lightindex)
5296 R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
5298 for (i = 0;i < r_refdef.scene.numlights;i++)
5300 rtlight = r_refdef.scene.lights[i];
5301 rtlight->corona_visibility = 0;
5302 rtlight->corona_queryindex_visiblepixels = 0;
5303 rtlight->corona_queryindex_allpixels = 0;
5304 if (!(rtlight->flags & flag))
5306 if (rtlight->corona <= 0)
5308 R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
5311 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5313 // now draw the coronas using the query data for intensity info
5314 for (lightindex = 0;lightindex < range;lightindex++)
5316 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5319 rtlight = &light->rtlight;
5320 if (rtlight->corona_visibility <= 0)
5322 R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
5324 for (i = 0;i < r_refdef.scene.numlights;i++)
5326 rtlight = r_refdef.scene.lights[i];
5327 if (rtlight->corona_visibility <= 0)
5329 if (gl_flashblend.integer)
5330 R_DrawCorona(rtlight, rtlight->corona, rtlight->radius * rtlight->coronasizescale * 2.0f);
5332 R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
5338 static dlight_t *R_Shadow_NewWorldLight(void)
5340 return (dlight_t *)Mem_ExpandableArray_AllocRecord(&r_shadow_worldlightsarray);
5343 static void R_Shadow_UpdateWorldLight(dlight_t *light, vec3_t origin, vec3_t angles, vec3_t color, vec_t radius, vec_t corona, int style, int shadowenable, const char *cubemapname, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags)
5346 // validate parameters
5347 if (style < 0 || style >= MAX_LIGHTSTYLES)
5349 Con_Printf("R_Shadow_NewWorldLight: invalid light style number %i, must be >= 0 and < %i\n", light->style, MAX_LIGHTSTYLES);
5355 // copy to light properties
5356 VectorCopy(origin, light->origin);
5357 light->angles[0] = angles[0] - 360 * floor(angles[0] / 360);
5358 light->angles[1] = angles[1] - 360 * floor(angles[1] / 360);
5359 light->angles[2] = angles[2] - 360 * floor(angles[2] / 360);
5361 light->color[0] = max(color[0], 0);
5362 light->color[1] = max(color[1], 0);
5363 light->color[2] = max(color[2], 0);
5365 light->color[0] = color[0];
5366 light->color[1] = color[1];
5367 light->color[2] = color[2];
5368 light->radius = max(radius, 0);
5369 light->style = style;
5370 light->shadow = shadowenable;
5371 light->corona = corona;
5372 strlcpy(light->cubemapname, cubemapname, sizeof(light->cubemapname));
5373 light->coronasizescale = coronasizescale;
5374 light->ambientscale = ambientscale;
5375 light->diffusescale = diffusescale;
5376 light->specularscale = specularscale;
5377 light->flags = flags;
5379 // update renderable light data
5380 Matrix4x4_CreateFromQuakeEntity(&matrix, light->origin[0], light->origin[1], light->origin[2], light->angles[0], light->angles[1], light->angles[2], light->radius);
5381 R_RTLight_Update(&light->rtlight, true, &matrix, light->color, light->style, light->cubemapname[0] ? light->cubemapname : NULL, light->shadow, light->corona, light->coronasizescale, light->ambientscale, light->diffusescale, light->specularscale, light->flags);
5384 static void R_Shadow_FreeWorldLight(dlight_t *light)
5386 if (r_shadow_selectedlight == light)
5387 r_shadow_selectedlight = NULL;
5388 R_RTLight_Uncompile(&light->rtlight);
5389 Mem_ExpandableArray_FreeRecord(&r_shadow_worldlightsarray, light);
5392 void R_Shadow_ClearWorldLights(void)
5396 size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5397 for (lightindex = 0;lightindex < range;lightindex++)
5399 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5401 R_Shadow_FreeWorldLight(light);
5403 r_shadow_selectedlight = NULL;
5406 static void R_Shadow_SelectLight(dlight_t *light)
5408 if (r_shadow_selectedlight)
5409 r_shadow_selectedlight->selected = false;
5410 r_shadow_selectedlight = light;
5411 if (r_shadow_selectedlight)
5412 r_shadow_selectedlight->selected = true;
5415 static void R_Shadow_DrawCursor_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
5417 // this is never batched (there can be only one)
5419 R_CalcSprite_Vertex3f(vertex3f, r_editlights_cursorlocation, r_refdef.view.right, r_refdef.view.up, EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, EDLIGHTSPRSIZE);
5420 RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, 1, 1, 1, 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5421 R_DrawCustomSurface(r_editlights_sprcursor, &identitymatrix, MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5424 static void R_Shadow_DrawLightSprite_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
5429 skinframe_t *skinframe;
5432 // this is never batched (due to the ent parameter changing every time)
5433 // so numsurfaces == 1 and surfacelist[0] == lightnumber
5434 const dlight_t *light = (dlight_t *)ent;
5437 R_CalcSprite_Vertex3f(vertex3f, light->origin, r_refdef.view.right, r_refdef.view.up, s, -s, -s, s);
5440 VectorScale(light->color, intensity, spritecolor);
5441 if (VectorLength(spritecolor) < 0.1732f)
5442 VectorSet(spritecolor, 0.1f, 0.1f, 0.1f);
5443 if (VectorLength(spritecolor) > 1.0f)
5444 VectorNormalize(spritecolor);
5446 // draw light sprite
5447 if (light->cubemapname[0] && !light->shadow)
5448 skinframe = r_editlights_sprcubemapnoshadowlight;
5449 else if (light->cubemapname[0])
5450 skinframe = r_editlights_sprcubemaplight;
5451 else if (!light->shadow)
5452 skinframe = r_editlights_sprnoshadowlight;
5454 skinframe = r_editlights_sprlight;
5456 RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, spritecolor[0], spritecolor[1], spritecolor[2], 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5457 R_DrawCustomSurface(skinframe, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5459 // draw selection sprite if light is selected
5460 if (light->selected)
5462 RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, 1, 1, 1, 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5463 R_DrawCustomSurface(r_editlights_sprselection, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5464 // VorteX todo: add normalmode/realtime mode light overlay sprites?
5468 void R_Shadow_DrawLightSprites(void)
5472 size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5473 for (lightindex = 0;lightindex < range;lightindex++)
5475 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5477 R_MeshQueue_AddTransparent(TRANSPARENTSORT_DISTANCE, light->origin, R_Shadow_DrawLightSprite_TransparentCallback, (entity_render_t *)light, 5, &light->rtlight);
5479 if (!r_editlights_lockcursor)
5480 R_MeshQueue_AddTransparent(TRANSPARENTSORT_DISTANCE, r_editlights_cursorlocation, R_Shadow_DrawCursor_TransparentCallback, NULL, 0, NULL);
5483 int R_Shadow_GetRTLightInfo(unsigned int lightindex, float *origin, float *radius, float *color)
5488 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
5489 if (lightindex >= range)
5491 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5494 rtlight = &light->rtlight;
5495 //if (!(rtlight->flags & flag))
5497 VectorCopy(rtlight->shadoworigin, origin);
5498 *radius = rtlight->radius;
5499 VectorCopy(rtlight->color, color);
5503 static void R_Shadow_SelectLightInView(void)
5505 float bestrating, rating, temp[3];
5509 size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5513 if (r_editlights_lockcursor)
5515 for (lightindex = 0;lightindex < range;lightindex++)
5517 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5520 VectorSubtract(light->origin, r_refdef.view.origin, temp);
5521 rating = (DotProduct(temp, r_refdef.view.forward) / sqrt(DotProduct(temp, temp)));
5524 rating /= (1 + 0.0625f * sqrt(DotProduct(temp, temp)));
5525 if (bestrating < rating && CL_TraceLine(light->origin, r_refdef.view.origin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1.0f)
5527 bestrating = rating;
5532 R_Shadow_SelectLight(best);
5535 void R_Shadow_LoadWorldLights(void)
5537 int n, a, style, shadow, flags;
5538 char tempchar, *lightsstring, *s, *t, name[MAX_QPATH], cubemapname[MAX_QPATH];
5539 float origin[3], radius, color[3], angles[3], corona, coronasizescale, ambientscale, diffusescale, specularscale;
5540 if (cl.worldmodel == NULL)
5542 Con_Print("No map loaded.\n");
5545 dpsnprintf(name, sizeof(name), "%s.rtlights", cl.worldnamenoextension);
5546 lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
5556 for (;COM_Parse(t, true) && strcmp(
5557 if (COM_Parse(t, true))
5559 if (com_token[0] == '!')
5562 origin[0] = atof(com_token+1);
5565 origin[0] = atof(com_token);
5570 while (*s && *s != '\n' && *s != '\r')
5576 // check for modifier flags
5583 #if _MSC_VER >= 1400
5584 #define sscanf sscanf_s
5586 cubemapname[sizeof(cubemapname)-1] = 0;
5587 #if MAX_QPATH != 128
5588 #error update this code if MAX_QPATH changes
5590 a = sscanf(t, "%f %f %f %f %f %f %f %d %127s %f %f %f %f %f %f %f %f %i", &origin[0], &origin[1], &origin[2], &radius, &color[0], &color[1], &color[2], &style, cubemapname
5591 #if _MSC_VER >= 1400
5592 , sizeof(cubemapname)
5594 , &corona, &angles[0], &angles[1], &angles[2], &coronasizescale, &ambientscale, &diffusescale, &specularscale, &flags);
5597 flags = LIGHTFLAG_REALTIMEMODE;
5605 coronasizescale = 0.25f;
5607 VectorClear(angles);
5610 if (a < 9 || !strcmp(cubemapname, "\"\""))
5612 // remove quotes on cubemapname
5613 if (cubemapname[0] == '"' && cubemapname[strlen(cubemapname) - 1] == '"')
5616 namelen = strlen(cubemapname) - 2;
5617 memmove(cubemapname, cubemapname + 1, namelen);
5618 cubemapname[namelen] = '\0';
5622 Con_Printf("found %d parameters on line %i, should be 8 or more parameters (origin[0] origin[1] origin[2] radius color[0] color[1] color[2] style \"cubemapname\" corona angles[0] angles[1] angles[2] coronasizescale ambientscale diffusescale specularscale flags)\n", a, n + 1);
5625 R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, corona, style, shadow, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
5633 Con_Printf("invalid rtlights file \"%s\"\n", name);
5634 Mem_Free(lightsstring);
5638 void R_Shadow_SaveWorldLights(void)
5642 size_t bufchars, bufmaxchars;
5644 char name[MAX_QPATH];
5645 char line[MAX_INPUTLINE];
5646 size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked, assuming the dpsnprintf mess doesn't screw it up...
5647 // I hate lines which are 3 times my screen size :( --blub
5650 if (cl.worldmodel == NULL)
5652 Con_Print("No map loaded.\n");
5655 dpsnprintf(name, sizeof(name), "%s.rtlights", cl.worldnamenoextension);
5656 bufchars = bufmaxchars = 0;
5658 for (lightindex = 0;lightindex < range;lightindex++)
5660 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5663 if (light->coronasizescale != 0.25f || light->ambientscale != 0 || light->diffusescale != 1 || light->specularscale != 1 || light->flags != LIGHTFLAG_REALTIMEMODE)
5664 dpsnprintf(line, sizeof(line), "%s%f %f %f %f %f %f %f %d \"%s\" %f %f %f %f %f %f %f %f %i\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style, light->cubemapname, light->corona, light->angles[0], light->angles[1], light->angles[2], light->coronasizescale, light->ambientscale, light->diffusescale, light->specularscale, light->flags);
5665 else if (light->cubemapname[0] || light->corona || light->angles[0] || light->angles[1] || light->angles[2])
5666 dpsnprintf(line, sizeof(line), "%s%f %f %f %f %f %f %f %d \"%s\" %f %f %f %f\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style, light->cubemapname, light->corona, light->angles[0], light->angles[1], light->angles[2]);
5668 dpsnprintf(line, sizeof(line), "%s%f %f %f %f %f %f %f %d\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style);
5669 if (bufchars + strlen(line) > bufmaxchars)
5671 bufmaxchars = bufchars + strlen(line) + 2048;
5673 buf = (char *)Mem_Alloc(tempmempool, bufmaxchars);
5677 memcpy(buf, oldbuf, bufchars);
5683 memcpy(buf + bufchars, line, strlen(line));
5684 bufchars += strlen(line);
5688 FS_WriteFile(name, buf, (fs_offset_t)bufchars);
5693 void R_Shadow_LoadLightsFile(void)
5696 char tempchar, *lightsstring, *s, *t, name[MAX_QPATH];
5697 float origin[3], radius, color[3], subtract, spotdir[3], spotcone, falloff, distbias;
5698 if (cl.worldmodel == NULL)
5700 Con_Print("No map loaded.\n");
5703 dpsnprintf(name, sizeof(name), "%s.lights", cl.worldnamenoextension);
5704 lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
5712 while (*s && *s != '\n' && *s != '\r')
5718 a = sscanf(t, "%f %f %f %f %f %f %f %f %f %f %f %f %f %d", &origin[0], &origin[1], &origin[2], &falloff, &color[0], &color[1], &color[2], &subtract, &spotdir[0], &spotdir[1], &spotdir[2], &spotcone, &distbias, &style);
5722 Con_Printf("invalid lights file, found %d parameters on line %i, should be 14 parameters (origin[0] origin[1] origin[2] falloff light[0] light[1] light[2] subtract spotdir[0] spotdir[1] spotdir[2] spotcone distancebias style)\n", a, n + 1);
5725 radius = sqrt(DotProduct(color, color) / (falloff * falloff * 8192.0f * 8192.0f));
5726 radius = bound(15, radius, 4096);
5727 VectorScale(color, (2.0f / (8388608.0f)), color);
5728 R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, vec3_origin, color, radius, 0, style, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
5736 Con_Printf("invalid lights file \"%s\"\n", name);
5737 Mem_Free(lightsstring);
5741 // tyrlite/hmap2 light types in the delay field
5742 typedef enum lighttype_e {LIGHTTYPE_MINUSX, LIGHTTYPE_RECIPX, LIGHTTYPE_RECIPXX, LIGHTTYPE_NONE, LIGHTTYPE_SUN, LIGHTTYPE_MINUSXX} lighttype_t;
5744 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void)
5756 float origin[3], angles[3], radius, color[3], light[4], fadescale, lightscale, originhack[3], overridecolor[3], vec[4];
5757 char key[256], value[MAX_INPUTLINE];
5760 if (cl.worldmodel == NULL)
5762 Con_Print("No map loaded.\n");
5765 // try to load a .ent file first
5766 dpsnprintf(key, sizeof(key), "%s.ent", cl.worldnamenoextension);
5767 data = entfiledata = (char *)FS_LoadFile(key, tempmempool, true, NULL);
5768 // and if that is not found, fall back to the bsp file entity string
5770 data = cl.worldmodel->brush.entities;
5773 for (entnum = 0;COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{';entnum++)
5775 type = LIGHTTYPE_MINUSX;
5776 origin[0] = origin[1] = origin[2] = 0;
5777 originhack[0] = originhack[1] = originhack[2] = 0;
5778 angles[0] = angles[1] = angles[2] = 0;
5779 color[0] = color[1] = color[2] = 1;
5780 light[0] = light[1] = light[2] = 1;light[3] = 300;
5781 overridecolor[0] = overridecolor[1] = overridecolor[2] = 1;
5791 if (!COM_ParseToken_Simple(&data, false, false, true))
5793 if (com_token[0] == '}')
5794 break; // end of entity
5795 if (com_token[0] == '_')
5796 strlcpy(key, com_token + 1, sizeof(key));
5798 strlcpy(key, com_token, sizeof(key));
5799 while (key[strlen(key)-1] == ' ') // remove trailing spaces
5800 key[strlen(key)-1] = 0;
5801 if (!COM_ParseToken_Simple(&data, false, false, true))
5803 strlcpy(value, com_token, sizeof(value));
5805 // now that we have the key pair worked out...
5806 if (!strcmp("light", key))
5808 n = sscanf(value, "%f %f %f %f", &vec[0], &vec[1], &vec[2], &vec[3]);
5812 light[0] = vec[0] * (1.0f / 256.0f);
5813 light[1] = vec[0] * (1.0f / 256.0f);
5814 light[2] = vec[0] * (1.0f / 256.0f);
5820 light[0] = vec[0] * (1.0f / 255.0f);
5821 light[1] = vec[1] * (1.0f / 255.0f);
5822 light[2] = vec[2] * (1.0f / 255.0f);
5826 else if (!strcmp("delay", key))
5828 else if (!strcmp("origin", key))
5829 sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]);
5830 else if (!strcmp("angle", key))
5831 angles[0] = 0, angles[1] = atof(value), angles[2] = 0;
5832 else if (!strcmp("angles", key))
5833 sscanf(value, "%f %f %f", &angles[0], &angles[1], &angles[2]);
5834 else if (!strcmp("color", key))
5835 sscanf(value, "%f %f %f", &color[0], &color[1], &color[2]);
5836 else if (!strcmp("wait", key))
5837 fadescale = atof(value);
5838 else if (!strcmp("classname", key))
5840 if (!strncmp(value, "light", 5))
5843 if (!strcmp(value, "light_fluoro"))
5848 overridecolor[0] = 1;
5849 overridecolor[1] = 1;
5850 overridecolor[2] = 1;
5852 if (!strcmp(value, "light_fluorospark"))
5857 overridecolor[0] = 1;
5858 overridecolor[1] = 1;
5859 overridecolor[2] = 1;
5861 if (!strcmp(value, "light_globe"))
5866 overridecolor[0] = 1;
5867 overridecolor[1] = 0.8;
5868 overridecolor[2] = 0.4;
5870 if (!strcmp(value, "light_flame_large_yellow"))
5875 overridecolor[0] = 1;
5876 overridecolor[1] = 0.5;
5877 overridecolor[2] = 0.1;
5879 if (!strcmp(value, "light_flame_small_yellow"))
5884 overridecolor[0] = 1;
5885 overridecolor[1] = 0.5;
5886 overridecolor[2] = 0.1;
5888 if (!strcmp(value, "light_torch_small_white"))
5893 overridecolor[0] = 1;
5894 overridecolor[1] = 0.5;
5895 overridecolor[2] = 0.1;
5897 if (!strcmp(value, "light_torch_small_walltorch"))
5902 overridecolor[0] = 1;
5903 overridecolor[1] = 0.5;
5904 overridecolor[2] = 0.1;
5908 else if (!strcmp("style", key))
5909 style = atoi(value);
5910 else if (!strcmp("skin", key))
5911 skin = (int)atof(value);
5912 else if (!strcmp("pflags", key))
5913 pflags = (int)atof(value);
5914 //else if (!strcmp("effects", key))
5915 // effects = (int)atof(value);
5916 else if (cl.worldmodel->type == mod_brushq3)
5918 if (!strcmp("scale", key))
5919 lightscale = atof(value);
5920 if (!strcmp("fade", key))
5921 fadescale = atof(value);
5926 if (lightscale <= 0)
5930 if (color[0] == color[1] && color[0] == color[2])
5932 color[0] *= overridecolor[0];
5933 color[1] *= overridecolor[1];
5934 color[2] *= overridecolor[2];
5936 radius = light[3] * r_editlights_quakelightsizescale.value * lightscale / fadescale;
5937 color[0] = color[0] * light[0];
5938 color[1] = color[1] * light[1];
5939 color[2] = color[2] * light[2];
5942 case LIGHTTYPE_MINUSX:
5944 case LIGHTTYPE_RECIPX:
5946 VectorScale(color, (1.0f / 16.0f), color);
5948 case LIGHTTYPE_RECIPXX:
5950 VectorScale(color, (1.0f / 16.0f), color);
5953 case LIGHTTYPE_NONE:
5957 case LIGHTTYPE_MINUSXX:
5960 VectorAdd(origin, originhack, origin);
5962 R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, (pflags & PFLAGS_CORONA) != 0, style, (pflags & PFLAGS_NOSHADOW) == 0, skin >= 16 ? va(vabuf, sizeof(vabuf), "cubemaps/%i", skin) : NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
5965 Mem_Free(entfiledata);
5969 static void R_Shadow_SetCursorLocationForView(void)
5972 vec3_t dest, endpos;
5974 VectorMA(r_refdef.view.origin, r_editlights_cursordistance.value, r_refdef.view.forward, dest);
5975 trace = CL_TraceLine(r_refdef.view.origin, dest, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true);
5976 if (trace.fraction < 1)
5978 dist = trace.fraction * r_editlights_cursordistance.value;
5979 push = r_editlights_cursorpushback.value;
5983 VectorMA(trace.endpos, push, r_refdef.view.forward, endpos);
5984 VectorMA(endpos, r_editlights_cursorpushoff.value, trace.plane.normal, endpos);
5988 VectorClear( endpos );
5990 r_editlights_cursorlocation[0] = floor(endpos[0] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
5991 r_editlights_cursorlocation[1] = floor(endpos[1] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
5992 r_editlights_cursorlocation[2] = floor(endpos[2] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
5995 void R_Shadow_UpdateWorldLightSelection(void)
5997 if (r_editlights.integer)
5999 R_Shadow_SetCursorLocationForView();
6000 R_Shadow_SelectLightInView();
6003 R_Shadow_SelectLight(NULL);
6006 static void R_Shadow_EditLights_Clear_f(void)
6008 R_Shadow_ClearWorldLights();
6011 void R_Shadow_EditLights_Reload_f(void)
6015 strlcpy(r_shadow_mapname, cl.worldname, sizeof(r_shadow_mapname));
6016 R_Shadow_ClearWorldLights();
6017 R_Shadow_LoadWorldLights();
6018 if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
6020 R_Shadow_LoadLightsFile();
6021 if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
6022 R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
6026 static void R_Shadow_EditLights_Save_f(void)
6030 R_Shadow_SaveWorldLights();
6033 static void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void)
6035 R_Shadow_ClearWorldLights();
6036 R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
6039 static void R_Shadow_EditLights_ImportLightsFile_f(void)
6041 R_Shadow_ClearWorldLights();
6042 R_Shadow_LoadLightsFile();
6045 static void R_Shadow_EditLights_Spawn_f(void)
6048 if (!r_editlights.integer)
6050 Con_Print("Cannot spawn light when not in editing mode. Set r_editlights to 1.\n");
6053 if (Cmd_Argc() != 1)
6055 Con_Print("r_editlights_spawn does not take parameters\n");
6058 color[0] = color[1] = color[2] = 1;
6059 R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), r_editlights_cursorlocation, vec3_origin, color, 200, 0, 0, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
6062 static void R_Shadow_EditLights_Edit_f(void)
6064 vec3_t origin, angles, color;
6065 vec_t radius, corona, coronasizescale, ambientscale, diffusescale, specularscale;
6066 int style, shadows, flags, normalmode, realtimemode;
6067 char cubemapname[MAX_INPUTLINE];
6068 if (!r_editlights.integer)
6070 Con_Print("Cannot spawn light when not in editing mode. Set r_editlights to 1.\n");
6073 if (!r_shadow_selectedlight)
6075 Con_Print("No selected light.\n");
6078 VectorCopy(r_shadow_selectedlight->origin, origin);
6079 VectorCopy(r_shadow_selectedlight->angles, angles);
6080 VectorCopy(r_shadow_selectedlight->color, color);
6081 radius = r_shadow_selectedlight->radius;
6082 style = r_shadow_selectedlight->style;
6083 if (r_shadow_selectedlight->cubemapname)
6084 strlcpy(cubemapname, r_shadow_selectedlight->cubemapname, sizeof(cubemapname));
6087 shadows = r_shadow_selectedlight->shadow;
6088 corona = r_shadow_selectedlight->corona;
6089 coronasizescale = r_shadow_selectedlight->coronasizescale;
6090 ambientscale = r_shadow_selectedlight->ambientscale;
6091 diffusescale = r_shadow_selectedlight->diffusescale;
6092 specularscale = r_shadow_selectedlight->specularscale;
6093 flags = r_shadow_selectedlight->flags;
6094 normalmode = (flags & LIGHTFLAG_NORMALMODE) != 0;
6095 realtimemode = (flags & LIGHTFLAG_REALTIMEMODE) != 0;
6096 if (!strcmp(Cmd_Argv(1), "origin"))
6098 if (Cmd_Argc() != 5)
6100 Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6103 origin[0] = atof(Cmd_Argv(2));
6104 origin[1] = atof(Cmd_Argv(3));
6105 origin[2] = atof(Cmd_Argv(4));
6107 else if (!strcmp(Cmd_Argv(1), "originscale"))
6109 if (Cmd_Argc() != 5)
6111 Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6114 origin[0] *= atof(Cmd_Argv(2));
6115 origin[1] *= atof(Cmd_Argv(3));
6116 origin[2] *= atof(Cmd_Argv(4));
6118 else if (!strcmp(Cmd_Argv(1), "originx"))
6120 if (Cmd_Argc() != 3)
6122 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6125 origin[0] = atof(Cmd_Argv(2));
6127 else if (!strcmp(Cmd_Argv(1), "originy"))
6129 if (Cmd_Argc() != 3)
6131 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6134 origin[1] = atof(Cmd_Argv(2));
6136 else if (!strcmp(Cmd_Argv(1), "originz"))
6138 if (Cmd_Argc() != 3)
6140 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6143 origin[2] = atof(Cmd_Argv(2));
6145 else if (!strcmp(Cmd_Argv(1), "move"))
6147 if (Cmd_Argc() != 5)
6149 Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6152 origin[0] += atof(Cmd_Argv(2));
6153 origin[1] += atof(Cmd_Argv(3));
6154 origin[2] += atof(Cmd_Argv(4));
6156 else if (!strcmp(Cmd_Argv(1), "movex"))
6158 if (Cmd_Argc() != 3)
6160 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6163 origin[0] += atof(Cmd_Argv(2));
6165 else if (!strcmp(Cmd_Argv(1), "movey"))
6167 if (Cmd_Argc() != 3)
6169 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6172 origin[1] += atof(Cmd_Argv(2));
6174 else if (!strcmp(Cmd_Argv(1), "movez"))
6176 if (Cmd_Argc() != 3)
6178 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6181 origin[2] += atof(Cmd_Argv(2));
6183 else if (!strcmp(Cmd_Argv(1), "angles"))
6185 if (Cmd_Argc() != 5)
6187 Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6190 angles[0] = atof(Cmd_Argv(2));
6191 angles[1] = atof(Cmd_Argv(3));
6192 angles[2] = atof(Cmd_Argv(4));
6194 else if (!strcmp(Cmd_Argv(1), "anglesx"))
6196 if (Cmd_Argc() != 3)
6198 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6201 angles[0] = atof(Cmd_Argv(2));
6203 else if (!strcmp(Cmd_Argv(1), "anglesy"))
6205 if (Cmd_Argc() != 3)
6207 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6210 angles[1] = atof(Cmd_Argv(2));
6212 else if (!strcmp(Cmd_Argv(1), "anglesz"))
6214 if (Cmd_Argc() != 3)
6216 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6219 angles[2] = atof(Cmd_Argv(2));
6221 else if (!strcmp(Cmd_Argv(1), "color"))
6223 if (Cmd_Argc() != 5)
6225 Con_Printf("usage: r_editlights_edit %s red green blue\n", Cmd_Argv(1));
6228 color[0] = atof(Cmd_Argv(2));
6229 color[1] = atof(Cmd_Argv(3));
6230 color[2] = atof(Cmd_Argv(4));
6232 else if (!strcmp(Cmd_Argv(1), "radius"))
6234 if (Cmd_Argc() != 3)
6236 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6239 radius = atof(Cmd_Argv(2));
6241 else if (!strcmp(Cmd_Argv(1), "colorscale"))
6243 if (Cmd_Argc() == 3)
6245 double scale = atof(Cmd_Argv(2));
6252 if (Cmd_Argc() != 5)
6254 Con_Printf("usage: r_editlights_edit %s red green blue (OR grey instead of red green blue)\n", Cmd_Argv(1));
6257 color[0] *= atof(Cmd_Argv(2));
6258 color[1] *= atof(Cmd_Argv(3));
6259 color[2] *= atof(Cmd_Argv(4));
6262 else if (!strcmp(Cmd_Argv(1), "radiusscale") || !strcmp(Cmd_Argv(1), "sizescale"))
6264 if (Cmd_Argc() != 3)
6266 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6269 radius *= atof(Cmd_Argv(2));
6271 else if (!strcmp(Cmd_Argv(1), "style"))
6273 if (Cmd_Argc() != 3)
6275 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6278 style = atoi(Cmd_Argv(2));
6280 else if (!strcmp(Cmd_Argv(1), "cubemap"))
6284 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6287 if (Cmd_Argc() == 3)
6288 strlcpy(cubemapname, Cmd_Argv(2), sizeof(cubemapname));
6292 else if (!strcmp(Cmd_Argv(1), "shadows"))
6294 if (Cmd_Argc() != 3)
6296 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6299 shadows = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6301 else if (!strcmp(Cmd_Argv(1), "corona"))
6303 if (Cmd_Argc() != 3)
6305 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6308 corona = atof(Cmd_Argv(2));
6310 else if (!strcmp(Cmd_Argv(1), "coronasize"))
6312 if (Cmd_Argc() != 3)
6314 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6317 coronasizescale = atof(Cmd_Argv(2));
6319 else if (!strcmp(Cmd_Argv(1), "ambient"))
6321 if (Cmd_Argc() != 3)
6323 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6326 ambientscale = atof(Cmd_Argv(2));
6328 else if (!strcmp(Cmd_Argv(1), "diffuse"))
6330 if (Cmd_Argc() != 3)
6332 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6335 diffusescale = atof(Cmd_Argv(2));
6337 else if (!strcmp(Cmd_Argv(1), "specular"))
6339 if (Cmd_Argc() != 3)
6341 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6344 specularscale = atof(Cmd_Argv(2));
6346 else if (!strcmp(Cmd_Argv(1), "normalmode"))
6348 if (Cmd_Argc() != 3)
6350 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6353 normalmode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6355 else if (!strcmp(Cmd_Argv(1), "realtimemode"))
6357 if (Cmd_Argc() != 3)
6359 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6362 realtimemode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6366 Con_Print("usage: r_editlights_edit [property] [value]\n");
6367 Con_Print("Selected light's properties:\n");
6368 Con_Printf("Origin : %f %f %f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);
6369 Con_Printf("Angles : %f %f %f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);
6370 Con_Printf("Color : %f %f %f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);
6371 Con_Printf("Radius : %f\n", r_shadow_selectedlight->radius);
6372 Con_Printf("Corona : %f\n", r_shadow_selectedlight->corona);
6373 Con_Printf("Style : %i\n", r_shadow_selectedlight->style);
6374 Con_Printf("Shadows : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");
6375 Con_Printf("Cubemap : %s\n", r_shadow_selectedlight->cubemapname);
6376 Con_Printf("CoronaSize : %f\n", r_shadow_selectedlight->coronasizescale);
6377 Con_Printf("Ambient : %f\n", r_shadow_selectedlight->ambientscale);
6378 Con_Printf("Diffuse : %f\n", r_shadow_selectedlight->diffusescale);
6379 Con_Printf("Specular : %f\n", r_shadow_selectedlight->specularscale);
6380 Con_Printf("NormalMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");
6381 Con_Printf("RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");
6384 flags = (normalmode ? LIGHTFLAG_NORMALMODE : 0) | (realtimemode ? LIGHTFLAG_REALTIMEMODE : 0);
6385 R_Shadow_UpdateWorldLight(r_shadow_selectedlight, origin, angles, color, radius, corona, style, shadows, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
6388 static void R_Shadow_EditLights_EditAll_f(void)
6391 dlight_t *light, *oldselected;
6394 if (!r_editlights.integer)
6396 Con_Print("Cannot edit lights when not in editing mode. Set r_editlights to 1.\n");
6400 oldselected = r_shadow_selectedlight;
6401 // EditLights doesn't seem to have a "remove" command or something so:
6402 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
6403 for (lightindex = 0;lightindex < range;lightindex++)
6405 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
6408 R_Shadow_SelectLight(light);
6409 R_Shadow_EditLights_Edit_f();
6411 // return to old selected (to not mess editing once selection is locked)
6412 R_Shadow_SelectLight(oldselected);
6415 void R_Shadow_EditLights_DrawSelectedLightProperties(void)
6417 int lightnumber, lightcount;
6418 size_t lightindex, range;
6423 if (!r_editlights.integer)
6426 // update cvars so QC can query them
6427 if (r_shadow_selectedlight)
6429 dpsnprintf(temp, sizeof(temp), "%f %f %f", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);
6430 Cvar_SetQuick(&r_editlights_current_origin, temp);
6431 dpsnprintf(temp, sizeof(temp), "%f %f %f", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);
6432 Cvar_SetQuick(&r_editlights_current_angles, temp);
6433 dpsnprintf(temp, sizeof(temp), "%f %f %f", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);
6434 Cvar_SetQuick(&r_editlights_current_color, temp);
6435 Cvar_SetValueQuick(&r_editlights_current_radius, r_shadow_selectedlight->radius);
6436 Cvar_SetValueQuick(&r_editlights_current_corona, r_shadow_selectedlight->corona);
6437 Cvar_SetValueQuick(&r_editlights_current_coronasize, r_shadow_selectedlight->coronasizescale);
6438 Cvar_SetValueQuick(&r_editlights_current_style, r_shadow_selectedlight->style);
6439 Cvar_SetValueQuick(&r_editlights_current_shadows, r_shadow_selectedlight->shadow);
6440 Cvar_SetQuick(&r_editlights_current_cubemap, r_shadow_selectedlight->cubemapname);
6441 Cvar_SetValueQuick(&r_editlights_current_ambient, r_shadow_selectedlight->ambientscale);
6442 Cvar_SetValueQuick(&r_editlights_current_diffuse, r_shadow_selectedlight->diffusescale);
6443 Cvar_SetValueQuick(&r_editlights_current_specular, r_shadow_selectedlight->specularscale);
6444 Cvar_SetValueQuick(&r_editlights_current_normalmode, (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? 1 : 0);
6445 Cvar_SetValueQuick(&r_editlights_current_realtimemode, (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? 1 : 0);
6448 // draw properties on screen
6449 if (!r_editlights_drawproperties.integer)
6451 x = vid_conwidth.value - 240;
6453 DrawQ_Pic(x-5, y-5, NULL, 250, 155, 0, 0, 0, 0.75, 0);
6456 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
6457 for (lightindex = 0;lightindex < range;lightindex++)
6459 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
6462 if (light == r_shadow_selectedlight)
6463 lightnumber = lightindex;
6466 dpsnprintf(temp, sizeof(temp), "Cursor origin: %.0f %.0f %.0f", r_editlights_cursorlocation[0], r_editlights_cursorlocation[1], r_editlights_cursorlocation[2]); DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, false, FONT_DEFAULT);y += 8;
6467 dpsnprintf(temp, sizeof(temp), "Total lights : %i active (%i total)", lightcount, (int)Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray)); DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, false, FONT_DEFAULT);y += 8;
6469 if (r_shadow_selectedlight == NULL)
6471 dpsnprintf(temp, sizeof(temp), "Light #%i properties:", lightnumber);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6472 dpsnprintf(temp, sizeof(temp), "Origin : %.0f %.0f %.0f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6473 dpsnprintf(temp, sizeof(temp), "Angles : %.0f %.0f %.0f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6474 dpsnprintf(temp, sizeof(temp), "Color : %.2f %.2f %.2f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6475 dpsnprintf(temp, sizeof(temp), "Radius : %.0f\n", r_shadow_selectedlight->radius);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6476 dpsnprintf(temp, sizeof(temp), "Corona : %.0f\n", r_shadow_selectedlight->corona);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6477 dpsnprintf(temp, sizeof(temp), "Style : %i\n", r_shadow_selectedlight->style);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6478 dpsnprintf(temp, sizeof(temp), "Shadows : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6479 dpsnprintf(temp, sizeof(temp), "Cubemap : %s\n", r_shadow_selectedlight->cubemapname);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6480 dpsnprintf(temp, sizeof(temp), "CoronaSize : %.2f\n", r_shadow_selectedlight->coronasizescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6481 dpsnprintf(temp, sizeof(temp), "Ambient : %.2f\n", r_shadow_selectedlight->ambientscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6482 dpsnprintf(temp, sizeof(temp), "Diffuse : %.2f\n", r_shadow_selectedlight->diffusescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6483 dpsnprintf(temp, sizeof(temp), "Specular : %.2f\n", r_shadow_selectedlight->specularscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6484 dpsnprintf(temp, sizeof(temp), "NormalMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6485 dpsnprintf(temp, sizeof(temp), "RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6488 static void R_Shadow_EditLights_ToggleShadow_f(void)
6490 if (!r_editlights.integer)
6492 Con_Print("Cannot spawn light when not in editing mode. Set r_editlights to 1.\n");
6495 if (!r_shadow_selectedlight)
6497 Con_Print("No selected light.\n");
6500 R_Shadow_UpdateWorldLight(r_shadow_selectedlight, r_shadow_selectedlight->origin, r_shadow_selectedlight->angles, r_shadow_selectedlight->color, r_shadow_selectedlight->radius, r_shadow_selectedlight->corona, r_shadow_selectedlight->style, !r_shadow_selectedlight->shadow, r_shadow_selectedlight->cubemapname, r_shadow_selectedlight->coronasizescale, r_shadow_selectedlight->ambientscale, r_shadow_selectedlight->diffusescale, r_shadow_selectedlight->specularscale, r_shadow_selectedlight->flags);
6503 static void R_Shadow_EditLights_ToggleCorona_f(void)
6505 if (!r_editlights.integer)
6507 Con_Print("Cannot spawn light when not in editing mode. Set r_editlights to 1.\n");
6510 if (!r_shadow_selectedlight)
6512 Con_Print("No selected light.\n");
6515 R_Shadow_UpdateWorldLight(r_shadow_selectedlight, r_shadow_selectedlight->origin, r_shadow_selectedlight->angles, r_shadow_selectedlight->color, r_shadow_selectedlight->radius, !r_shadow_selectedlight->corona, r_shadow_selectedlight->style, r_shadow_selectedlight->shadow, r_shadow_selectedlight->cubemapname, r_shadow_selectedlight->coronasizescale, r_shadow_selectedlight->ambientscale, r_shadow_selectedlight->diffusescale, r_shadow_selectedlight->specularscale, r_shadow_selectedlight->flags);
6518 static void R_Shadow_EditLights_Remove_f(void)
6520 if (!r_editlights.integer)
6522 Con_Print("Cannot remove light when not in editing mode. Set r_editlights to 1.\n");
6525 if (!r_shadow_selectedlight)
6527 Con_Print("No selected light.\n");
6530 R_Shadow_FreeWorldLight(r_shadow_selectedlight);
6531 r_shadow_selectedlight = NULL;
6534 static void R_Shadow_EditLights_Help_f(void)
6537 "Documentation on r_editlights system:\n"
6539 "r_editlights : enable/disable editing mode\n"
6540 "r_editlights_cursordistance : maximum distance of cursor from eye\n"
6541 "r_editlights_cursorpushback : push back cursor this far from surface\n"
6542 "r_editlights_cursorpushoff : push cursor off surface this far\n"
6543 "r_editlights_cursorgrid : snap cursor to grid of this size\n"
6544 "r_editlights_quakelightsizescale : imported quake light entity size scaling\n"
6546 "r_editlights_help : this help\n"
6547 "r_editlights_clear : remove all lights\n"
6548 "r_editlights_reload : reload .rtlights, .lights file, or entities\n"
6549 "r_editlights_lock : lock selection to current light, if already locked - unlock\n"
6550 "r_editlights_save : save to .rtlights file\n"
6551 "r_editlights_spawn : create a light with default settings\n"
6552 "r_editlights_edit command : edit selected light - more documentation below\n"
6553 "r_editlights_remove : remove selected light\n"
6554 "r_editlights_toggleshadow : toggles on/off selected light's shadow property\n"
6555 "r_editlights_importlightentitiesfrommap : reload light entities\n"
6556 "r_editlights_importlightsfile : reload .light file (produced by hlight)\n"
6558 "origin x y z : set light location\n"
6559 "originx x: set x component of light location\n"
6560 "originy y: set y component of light location\n"
6561 "originz z: set z component of light location\n"
6562 "move x y z : adjust light location\n"
6563 "movex x: adjust x component of light location\n"
6564 "movey y: adjust y component of light location\n"
6565 "movez z: adjust z component of light location\n"
6566 "angles x y z : set light angles\n"
6567 "anglesx x: set x component of light angles\n"
6568 "anglesy y: set y component of light angles\n"
6569 "anglesz z: set z component of light angles\n"
6570 "color r g b : set color of light (can be brighter than 1 1 1)\n"
6571 "radius radius : set radius (size) of light\n"
6572 "colorscale grey : multiply color of light (1 does nothing)\n"
6573 "colorscale r g b : multiply color of light (1 1 1 does nothing)\n"
6574 "radiusscale scale : multiply radius (size) of light (1 does nothing)\n"
6575 "sizescale scale : multiply radius (size) of light (1 does nothing)\n"
6576 "originscale x y z : multiply origin of light (1 1 1 does nothing)\n"
6577 "style style : set lightstyle of light (flickering patterns, switches, etc)\n"
6578 "cubemap basename : set filter cubemap of light\n"
6579 "shadows 1/0 : turn on/off shadows\n"
6580 "corona n : set corona intensity\n"
6581 "coronasize n : set corona size (0-1)\n"
6582 "ambient n : set ambient intensity (0-1)\n"
6583 "diffuse n : set diffuse intensity (0-1)\n"
6584 "specular n : set specular intensity (0-1)\n"
6585 "normalmode 1/0 : turn on/off rendering of this light in rtworld 0 mode\n"
6586 "realtimemode 1/0 : turn on/off rendering of this light in rtworld 1 mode\n"
6587 "<nothing> : print light properties to console\n"
6591 static void R_Shadow_EditLights_CopyInfo_f(void)
6593 if (!r_editlights.integer)
6595 Con_Print("Cannot copy light info when not in editing mode. Set r_editlights to 1.\n");
6598 if (!r_shadow_selectedlight)
6600 Con_Print("No selected light.\n");
6603 VectorCopy(r_shadow_selectedlight->angles, r_shadow_bufferlight.angles);
6604 VectorCopy(r_shadow_selectedlight->color, r_shadow_bufferlight.color);
6605 r_shadow_bufferlight.radius = r_shadow_selectedlight->radius;
6606 r_shadow_bufferlight.style = r_shadow_selectedlight->style;
6607 if (r_shadow_selectedlight->cubemapname)
6608 strlcpy(r_shadow_bufferlight.cubemapname, r_shadow_selectedlight->cubemapname, sizeof(r_shadow_bufferlight.cubemapname));
6610 r_shadow_bufferlight.cubemapname[0] = 0;
6611 r_shadow_bufferlight.shadow = r_shadow_selectedlight->shadow;
6612 r_shadow_bufferlight.corona = r_shadow_selectedlight->corona;
6613 r_shadow_bufferlight.coronasizescale = r_shadow_selectedlight->coronasizescale;
6614 r_shadow_bufferlight.ambientscale = r_shadow_selectedlight->ambientscale;
6615 r_shadow_bufferlight.diffusescale = r_shadow_selectedlight->diffusescale;
6616 r_shadow_bufferlight.specularscale = r_shadow_selectedlight->specularscale;
6617 r_shadow_bufferlight.flags = r_shadow_selectedlight->flags;
6620 static void R_Shadow_EditLights_PasteInfo_f(void)
6622 if (!r_editlights.integer)
6624 Con_Print("Cannot paste light info when not in editing mode. Set r_editlights to 1.\n");
6627 if (!r_shadow_selectedlight)
6629 Con_Print("No selected light.\n");
6632 R_Shadow_UpdateWorldLight(r_shadow_selectedlight, r_shadow_selectedlight->origin, r_shadow_bufferlight.angles, r_shadow_bufferlight.color, r_shadow_bufferlight.radius, r_shadow_bufferlight.corona, r_shadow_bufferlight.style, r_shadow_bufferlight.shadow, r_shadow_bufferlight.cubemapname, r_shadow_bufferlight.coronasizescale, r_shadow_bufferlight.ambientscale, r_shadow_bufferlight.diffusescale, r_shadow_bufferlight.specularscale, r_shadow_bufferlight.flags);
6635 static void R_Shadow_EditLights_Lock_f(void)
6637 if (!r_editlights.integer)
6639 Con_Print("Cannot lock on light when not in editing mode. Set r_editlights to 1.\n");
6642 if (r_editlights_lockcursor)
6644 r_editlights_lockcursor = false;
6647 if (!r_shadow_selectedlight)
6649 Con_Print("No selected light to lock on.\n");
6652 r_editlights_lockcursor = true;
6655 static void R_Shadow_EditLights_Init(void)
6657 Cvar_RegisterVariable(&r_editlights);
6658 Cvar_RegisterVariable(&r_editlights_cursordistance);
6659 Cvar_RegisterVariable(&r_editlights_cursorpushback);
6660 Cvar_RegisterVariable(&r_editlights_cursorpushoff);
6661 Cvar_RegisterVariable(&r_editlights_cursorgrid);
6662 Cvar_RegisterVariable(&r_editlights_quakelightsizescale);
6663 Cvar_RegisterVariable(&r_editlights_drawproperties);
6664 Cvar_RegisterVariable(&r_editlights_current_origin);
6665 Cvar_RegisterVariable(&r_editlights_current_angles);
6666 Cvar_RegisterVariable(&r_editlights_current_color);
6667 Cvar_RegisterVariable(&r_editlights_current_radius);
6668 Cvar_RegisterVariable(&r_editlights_current_corona);
6669 Cvar_RegisterVariable(&r_editlights_current_coronasize);
6670 Cvar_RegisterVariable(&r_editlights_current_style);
6671 Cvar_RegisterVariable(&r_editlights_current_shadows);
6672 Cvar_RegisterVariable(&r_editlights_current_cubemap);
6673 Cvar_RegisterVariable(&r_editlights_current_ambient);
6674 Cvar_RegisterVariable(&r_editlights_current_diffuse);
6675 Cvar_RegisterVariable(&r_editlights_current_specular);
6676 Cvar_RegisterVariable(&r_editlights_current_normalmode);
6677 Cvar_RegisterVariable(&r_editlights_current_realtimemode);
6678 Cmd_AddCommand("r_editlights_help", R_Shadow_EditLights_Help_f, "prints documentation on console commands and variables in rtlight editing system");
6679 Cmd_AddCommand("r_editlights_clear", R_Shadow_EditLights_Clear_f, "removes all world lights (let there be darkness!)");
6680 Cmd_AddCommand("r_editlights_reload", R_Shadow_EditLights_Reload_f, "reloads rtlights file (or imports from .lights file or .ent file or the map itself)");
6681 Cmd_AddCommand("r_editlights_save", R_Shadow_EditLights_Save_f, "save .rtlights file for current level");
6682 Cmd_AddCommand("r_editlights_spawn", R_Shadow_EditLights_Spawn_f, "creates a light with default properties (let there be light!)");
6683 Cmd_AddCommand("r_editlights_edit", R_Shadow_EditLights_Edit_f, "changes a property on the selected light");
6684 Cmd_AddCommand("r_editlights_editall", R_Shadow_EditLights_EditAll_f, "changes a property on ALL lights at once (tip: use radiusscale and colorscale to alter these properties)");
6685 Cmd_AddCommand("r_editlights_remove", R_Shadow_EditLights_Remove_f, "remove selected light");
6686 Cmd_AddCommand("r_editlights_toggleshadow", R_Shadow_EditLights_ToggleShadow_f, "toggle on/off the shadow option on the selected light");
6687 Cmd_AddCommand("r_editlights_togglecorona", R_Shadow_EditLights_ToggleCorona_f, "toggle on/off the corona option on the selected light");
6688 Cmd_AddCommand("r_editlights_importlightentitiesfrommap", R_Shadow_EditLights_ImportLightEntitiesFromMap_f, "load lights from .ent file or map entities (ignoring .rtlights or .lights file)");
6689 Cmd_AddCommand("r_editlights_importlightsfile", R_Shadow_EditLights_ImportLightsFile_f, "load lights from .lights file (ignoring .rtlights or .ent files and map entities)");
6690 Cmd_AddCommand("r_editlights_copyinfo", R_Shadow_EditLights_CopyInfo_f, "store a copy of all properties (except origin) of the selected light");
6691 Cmd_AddCommand("r_editlights_pasteinfo", R_Shadow_EditLights_PasteInfo_f, "apply the stored properties onto the selected light (making it exactly identical except for origin)");
6692 Cmd_AddCommand("r_editlights_lock", R_Shadow_EditLights_Lock_f, "lock selection to current light, if already locked - unlock");
6698 =============================================================================
6702 =============================================================================
6705 void R_LightPoint(float *color, const vec3_t p, const int flags)
6707 int i, numlights, flag;
6708 float f, relativepoint[3], dist, dist2, lightradius2;
6713 if (r_fullbright.integer)
6715 VectorSet(color, 1, 1, 1);
6721 if (flags & LP_LIGHTMAP)
6723 if (!r_fullbright.integer && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6725 VectorClear(diffuse);
6726 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, color, diffuse, n);
6727 VectorAdd(color, diffuse, color);
6730 VectorSet(color, 1, 1, 1);
6731 color[0] += r_refdef.scene.ambient;
6732 color[1] += r_refdef.scene.ambient;
6733 color[2] += r_refdef.scene.ambient;
6736 if (flags & LP_RTWORLD)
6738 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
6739 numlights = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
6740 for (i = 0; i < numlights; i++)
6742 dlight = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, i);
6745 light = &dlight->rtlight;
6746 if (!(light->flags & flag))
6749 lightradius2 = light->radius * light->radius;
6750 VectorSubtract(light->shadoworigin, p, relativepoint);
6751 dist2 = VectorLength2(relativepoint);
6752 if (dist2 >= lightradius2)
6754 dist = sqrt(dist2) / light->radius;
6755 f = dist < 1 ? (r_shadow_lightintensityscale.value * ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist))) : 0;
6758 // todo: add to both ambient and diffuse
6759 if (!light->shadow || CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1)
6760 VectorMA(color, f, light->currentcolor, color);
6763 if (flags & LP_DYNLIGHT)
6766 for (i = 0;i < r_refdef.scene.numlights;i++)
6768 light = r_refdef.scene.lights[i];
6770 lightradius2 = light->radius * light->radius;
6771 VectorSubtract(light->shadoworigin, p, relativepoint);
6772 dist2 = VectorLength2(relativepoint);
6773 if (dist2 >= lightradius2)
6775 dist = sqrt(dist2) / light->radius;
6776 f = dist < 1 ? (r_shadow_lightintensityscale.value * ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist))) : 0;
6779 // todo: add to both ambient and diffuse
6780 if (!light->shadow || CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1)
6781 VectorMA(color, f, light->color, color);
6786 void R_CompleteLightPoint(vec3_t ambient, vec3_t diffuse, vec3_t lightdir, const vec3_t p, const int flags)
6788 int i, numlights, flag;
6791 float relativepoint[3];
6800 if (r_fullbright.integer)
6802 VectorSet(ambient, 1, 1, 1);
6803 VectorClear(diffuse);
6804 VectorClear(lightdir);
6808 if (flags == LP_LIGHTMAP)
6810 VectorSet(ambient, r_refdef.scene.ambient, r_refdef.scene.ambient, r_refdef.scene.ambient);
6811 VectorClear(diffuse);
6812 VectorClear(lightdir);
6813 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6814 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, ambient, diffuse, lightdir);
6816 VectorSet(ambient, 1, 1, 1);
6820 memset(sample, 0, sizeof(sample));
6821 VectorSet(sample, r_refdef.scene.ambient, r_refdef.scene.ambient, r_refdef.scene.ambient);
6823 if ((flags & LP_LIGHTMAP) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6826 VectorClear(tempambient);
6828 VectorClear(relativepoint);
6829 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, tempambient, color, relativepoint);
6830 VectorScale(tempambient, r_refdef.lightmapintensity, tempambient);
6831 VectorScale(color, r_refdef.lightmapintensity, color);
6832 VectorAdd(sample, tempambient, sample);
6833 VectorMA(sample , 0.5f , color, sample );
6834 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6835 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6836 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6837 // calculate a weighted average light direction as well
6838 intensity = VectorLength(color);
6839 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6842 if (flags & LP_RTWORLD)
6844 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
6845 numlights = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
6846 for (i = 0; i < numlights; i++)
6848 dlight = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, i);
6851 light = &dlight->rtlight;
6852 if (!(light->flags & flag))
6855 lightradius2 = light->radius * light->radius;
6856 VectorSubtract(light->shadoworigin, p, relativepoint);
6857 dist2 = VectorLength2(relativepoint);
6858 if (dist2 >= lightradius2)
6860 dist = sqrt(dist2) / light->radius;
6861 intensity = min(1.0f, (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) * r_shadow_lightintensityscale.value;
6862 if (intensity <= 0.0f)
6864 if (light->shadow && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
6866 // scale down intensity to add to both ambient and diffuse
6867 //intensity *= 0.5f;
6868 VectorNormalize(relativepoint);
6869 VectorScale(light->currentcolor, intensity, color);
6870 VectorMA(sample , 0.5f , color, sample );
6871 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6872 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6873 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6874 // calculate a weighted average light direction as well
6875 intensity *= VectorLength(color);
6876 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6878 // FIXME: sample bouncegrid too!
6881 if (flags & LP_DYNLIGHT)
6884 for (i = 0;i < r_refdef.scene.numlights;i++)
6886 light = r_refdef.scene.lights[i];
6888 lightradius2 = light->radius * light->radius;
6889 VectorSubtract(light->shadoworigin, p, relativepoint);
6890 dist2 = VectorLength2(relativepoint);
6891 if (dist2 >= lightradius2)
6893 dist = sqrt(dist2) / light->radius;
6894 intensity = (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist) * r_shadow_lightintensityscale.value;
6895 if (intensity <= 0.0f)
6897 if (light->shadow && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
6899 // scale down intensity to add to both ambient and diffuse
6900 //intensity *= 0.5f;
6901 VectorNormalize(relativepoint);
6902 VectorScale(light->currentcolor, intensity, color);
6903 VectorMA(sample , 0.5f , color, sample );
6904 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6905 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6906 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6907 // calculate a weighted average light direction as well
6908 intensity *= VectorLength(color);
6909 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6913 // calculate the direction we'll use to reduce the sample to a directional light source
6914 VectorCopy(sample + 12, dir);
6915 //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
6916 VectorNormalize(dir);
6917 // extract the diffuse color along the chosen direction and scale it
6918 diffuse[0] = (dir[0]*sample[3] + dir[1]*sample[6] + dir[2]*sample[ 9] + sample[ 0]);
6919 diffuse[1] = (dir[0]*sample[4] + dir[1]*sample[7] + dir[2]*sample[10] + sample[ 1]);
6920 diffuse[2] = (dir[0]*sample[5] + dir[1]*sample[8] + dir[2]*sample[11] + sample[ 2]);
6921 // subtract some of diffuse from ambient
6922 VectorMA(sample, -0.333f, diffuse, ambient);
6923 // store the normalized lightdir
6924 VectorCopy(dir, lightdir);