Blender V5.3
eevee_shadow_tracing.bsl.hh
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#pragma once
6
10
11#include "draw_math_geom.bsl.hh"
12#include "draw_view.bsl.hh"
15#include "eevee_shadow.bsl.hh"
17#include "eevee_uniform.bsl.hh"
23
24namespace eevee {
25
26/* ---------------------------------------------------------------------- */
29
30static constexpr float SHADOW_TRACING_INVALID_HISTORY = FLT_MAX;
31
33 /* Occluder ray coordinate at previous valid depth sample. */
35 /* Time slope between previous valid sample (N-1) and the one before that (N-2). */
37 /* Multiplier and bias to the ray step quickly compute ray time. */
40 /* State of the trace. */
41 float ray_time;
42 bool hit;
43};
44
45ShadowMapTracingState shadow_map_trace_init(int sample_count, float step_offset)
46{
50 /* We trace the ray in reverse. From 1.0 (light) to 0.0f (shading point). */
51 state.ray_step_mul = -1.0f / float(sample_count);
52 state.ray_step_bias = 1.0f + step_offset * state.ray_step_mul;
53 state.hit = false;
54 return state;
55}
56
66
75 bool is_last_sample)
76{
77 bool is_behind_occluder = samp.occluder.y > 1e-6f;
78
79 if (samp.skip_sample) {
80 /* Skip empty tiles since they do not contain actual depth information.
81 * Not doing so would change the z gradient history. */
82 }
83 else if (state.occluder_history.x == SHADOW_TRACING_INVALID_HISTORY) {
84 /* First sample, regular depth compare since we do not have history values. */
85 state.hit = is_behind_occluder || (is_last_sample && (samp.occluder.x > state.ray_time));
86 state.occluder_history = samp.occluder;
87 }
88 else if (is_behind_occluder && (state.occluder_slope != SHADOW_TRACING_INVALID_HISTORY)) {
89 /* Extrapolate last known valid occluder and check if it crossed the ray.
90 * Note that we only want to check if the extrapolated occluder is above the ray at a certain
91 * time value, we don't actually care about the correct value. So we replace the complex
92 * problem of trying to get the extrapolation in shadow map space into the extrapolation at
93 * ray_time in ray space. This is equivalent as both functions have the same roots. */
94 float delta_time = state.ray_time - state.occluder_history.x;
95 float extrapolated_occluder_y = abs(state.occluder_history.y) +
96 state.occluder_slope * delta_time;
97 /* NOTE: We use the absolute of the function to account for all occluders configurations.
98 * The test just checks if it doesn't extrapolate in the other Y region. */
99 state.hit = extrapolated_occluder_y < 0.0f;
100 }
101 else {
102 /* Compute current occluder slope and record history for when the ray goes behind a surface. */
103 float2 delta = samp.occluder - state.occluder_history;
104 /* Clamping the slope to a minimum avoid light leaking. */
105 /* TODO(@fclem): Expose as parameter? */
106 const float min_slope = tan(M_PI * 0.25f);
107 state.occluder_slope = max(min_slope, abs(delta.y / delta.x));
108 state.occluder_history = samp.occluder;
109 /* Intersection test. Intersect if above the ray time. */
110 state.hit = is_behind_occluder || (is_last_sample && (samp.occluder.x > state.ray_time));
111 }
112}
113
120template<typename ShadowRayType>
122 ShadowRayType ray,
123 int sample_count,
124 float step_offset)
125{
126 ShadowMapTracingState state = shadow_map_trace_init(sample_count, step_offset);
127 for (int i = 0; (i <= sample_count) && (i <= SHADOW_MAX_STEP) && (state.hit == false); i++) {
128 /* Saturate to always cover the shading point position when i == sample_count. */
129 state.ray_time = square(saturate(float(i) * state.ray_step_mul + state.ray_step_bias));
130
132
133 shadow_map_trace_hit_check(state, samp, i == sample_count);
134 }
135 return state.hit;
136}
137
139
140/* ---------------------------------------------------------------------- */
143
145 /* Ray in light rotated space. But not translated. */
148 /* Convert form local light position to ray oriented position where X axis is the ray. */
150 LightData light;
151};
152
153/* `lP` is supposed to be in light rotated space. But not translated. */
155 LightData light, float2 random_2d, float3 lP, float texel_radius, float soft_shadow_scale)
156{
157 float clip_near = orderedIntBitsToFloat(light.clip_near);
158 /* Assumed to be non-null. */
159 float dist_to_near_plane = -lP.z - clip_near;
160 /* Trace in a radius that is covered by low resolution page inflation. */
161 float max_tracing_distance = texel_radius * float(SHADOW_PAGE_RES << SHADOW_TILEMAP_LOD);
162 float max_tracing_angle_cos = cos_from_tan(max_tracing_distance / dist_to_near_plane);
163 /* Taking max of cosines to get the minimum of the angles. */
164 float shadow_angle_cos = max(light.sun.shadow_angle_cos, max_tracing_angle_cos);
165
166 /* Light shape is 1 unit away from the shading point. */
167 float3 direction = sample_uniform_cone(random_2d, shadow_angle_cos);
168
169 float3 shadow_space_light_direction = transform_direction_transposed(
170 light.object_to_world, float3(light.sun.direction));
171 direction = spherical_interpolate(shadow_space_light_direction, direction, soft_shadow_scale);
172
173 /* It only make sense to trace where there can be occluder. Clamp by distance to near plane. */
174 direction *= max(texel_radius, dist_to_near_plane / direction.z);
175
177 ray.origin = lP;
178 ray.direction = direction;
179 ray.light = light;
180 /* TODO(fclem): We can simplify this using the ray direction construction. */
182 cross(cross(float3(0.0f, 0.0f, -1.0f), ray.direction), ray.direction));
183 return ray;
184}
185
189{
190 /* Ray position is ray local position with origin at light origin. */
191 float3 ray_pos = ray.origin + ray.direction * state.ray_time;
192
194
195 float depth = srd.read_depth(coord);
196 /* Distance from near plane. */
197 float clip_near = orderedIntBitsToFloat(ray.light.clip_near);
198 float3 occluder_pos = float3(ray_pos.xy, -depth - clip_near);
199 /* Transform to ray local space. */
200 float3 ray_local_occluder = occluder_pos - ray.origin;
201
203 samp.occluder.x = dot(ray_local_occluder, ray.direction) / length_squared(ray.direction);
204 samp.occluder.y = dot(ray_local_occluder, ray.local_ray_up);
205 samp.skip_sample = (depth == -1.0f);
206 return samp;
207}
208
211 int,
212 float);
213
215
216/* ---------------------------------------------------------------------- */
219
221 /* Light space shadow ray origin and direction. */
224 /* Convert form local light position to ray oriented position where X axis is the ray. */
226 /* Tile-map to sample. */
228 LightData light;
229};
230
231/* Return ray in UV clip space [0..1]. */
233 float2 random_2d,
234 float3 lP,
235 float soft_shadow_scale)
236{
237 if (light.type == LIGHT_RECT) {
238 random_2d = random_2d * 2.0f - 1.0f;
239 }
240 else {
241 random_2d = sample_disk(random_2d);
242 }
243 random_2d *= soft_shadow_scale;
244
245 float clip_near = intBitsToFloat(light.clip_near);
246 float shape_radius = light.spot.local.shadow_radius;
247 /* Clamp to a minimum value to avoid `local_ray_up` being degenerate. Could be revisited as the
248 * issue might reappear at different zoom level. */
249 shape_radius = max(0.00002f, shape_radius);
250
251 float3 point_on_light_shape;
252 if (is_area_light(light.type)) {
253 random_2d *= light.area.size * light.area.shadow_scale;
254
255 point_on_light_shape = float3(random_2d, 0.0f);
256 }
257 else {
258 float dist;
259 float3 lL = normalize_and_get_length(lP, dist);
260 /* Disk rotated towards light vector. */
261 float3 right, up;
262 make_orthonormal_basis(lL, right, up);
263
264 if (is_sphere_light(light.type)) {
265 shape_radius = light_sphere_disk_radius(shape_radius, dist);
266 }
267 random_2d *= shape_radius;
268
269 point_on_light_shape = right * random_2d.x + up * random_2d.y;
270 }
271
272 /* Avoid numerical issue when random point is exactly on the light center. */
273 if (length_squared(point_on_light_shape) < 1e-8f) {
274 point_on_light_shape = float3(1e-6f);
275 }
276
277 float3 direction = point_on_light_shape - lP;
278
279 float3 shadow_position = light.local.local.shadow_position;
280 /* Clip the ray to not cross the near plane.
281 * Avoid traces that starts on tiles that have not been queried, creating noise. */
282 float clip_distance = max(0.0f, length(lP - shadow_position) - clip_near);
283 /* Still clamp to a minimal size to avoid issue with zero length vectors. */
284 direction *= saturate(1e-6f + clip_distance * inversesqrt(length_squared(direction)));
285
286 /* Compute the ray again. */
288 /* Transform to shadow local space. */
289 ray.origin = lP - shadow_position;
290 ray.direction = direction + shadow_position * soft_shadow_scale;
291 ray.light_tilemap_index = light.tilemap_index;
293 ray.light = light;
294 return ray;
295}
296
300{
301 float3 receiver_pos = ray.origin + ray.direction * state.ray_time;
302 int face_id = shadow_punctual_face_index_get(receiver_pos);
303 float3 face_pos = shadow_punctual_local_position_to_face_local(face_id, receiver_pos);
304 ShadowCoordinates coord = shadow_punctual_coordinates(ray.light, face_pos, face_id);
305
306 float radial_occluder_depth = srd.read_depth(coord);
307 float3 occluder_pos = receiver_pos * (radial_occluder_depth / length(receiver_pos));
308
309 /* Transform to ray local space. */
310 float3 ray_local_occluder = occluder_pos - ray.origin;
311
313 samp.occluder.x = dot(ray_local_occluder, ray.direction) / length_squared(ray.direction);
314 samp.occluder.y = dot(ray_local_occluder, ray.local_ray_up);
315 samp.skip_sample = (radial_occluder_depth == -1.0f);
316 return samp;
317}
318
321 int,
322 float);
323
325
326/* ---------------------------------------------------------------------- */
329
330/* Compute the world space offset of the shading position required for
331 * stochastic percentage closer filtering of shadow-maps. */
333{
334 /* Angle between Light and normal. */
335 float cos_theta = abs(dot(L, Ng));
337 /* Slope of the receiver plane with respect to light direction. Equal to `tan(theta)`.
338 * Stop at 45 degrees angle to avoid large bias and peter panning artifacts. */
339 float cone_height = saturate(sin_theta * safe_rcp(cos_theta));
340 /* We choose a random disk distribution because it is rotationally invariant.
341 * This saves us the trouble of getting the correct orientation for punctual. */
342 float distance_to_center = sqrt(random.x);
343 float2 disk_sample = sample_circle(random.y) * distance_to_center;
344 /* Set the samples on a cone up to 45 degree. */
345 float3 cone_sample = float3(disk_sample, distance_to_center * cone_height);
346 /* Setup the cone around the light vector. */
347 float3 pcf_offset = from_up_axis(L) * cone_sample;
348 /* Offset the cone in normal direction to avoid self shadowing
349 * when angle is greater than 45 degrees. */
350 pcf_offset += Ng * saturate(sin_theta - cos_theta);
351 return pcf_offset;
352}
353
360 const draw::View &views,
361 LightData light,
362 const bool is_directional,
363 float3 P)
364{
365 /* For direction, footprint of the sampled clipmap (or cascade) at the given position.
366 * For punctual, footprint of the tilemap at given position scaled by the LOD level.
367 * Each of these a smooth upper bound estimation (will transition smoothly to the next level). */
368 float scale = 1.0f;
369 if (is_directional) {
370 float3 lP = transform_direction_transposed(light.object_to_world, P);
371 lP -= light.position();
372 LightSunData sun = light.sun;
373 if (light.type == LIGHT_SUN) {
374 /* Simplification of `coverage_get(shadow_directional_level_fractional)`.
375 * Do not apply the narrowing since we want the size of the tilemap (not its application
376 * radius). */
377 scale = length(lP) * 2.0f;
378 scale = max(scale * exp2(light.lod_bias), exp2(light.lod_min));
379 scale = clamp(scale, exp2(float(sun.clipmap_lod_min)), exp2(float(sun.clipmap_lod_max)));
380 }
381 else {
382 /* Uniform distribution everywhere. No distance scaling.
383 * shadow_directional_level_fractional returns the cascade level, but all levels have the
384 * same density as the level 0. So the effective density only depends on the `lod_bias`. */
385 scale = exp2(float(sun.clipmap_lod_min));
386 }
387 }
388 else {
389 const ViewMatrices view = views.get(0);
390
392 lP -= light.local.local.shadow_position;
393 /* Simplification of `exp2(shadow_punctual_level_fractional)`. */
395 lP,
396 view.is_perspective(),
397 view.z_distance(P),
398 uni.uniform_buf.shadow.film_pixel_radius);
399 /* This gives the size of pixels at Z = 1. */
400 scale = 1.0f / scale;
401 scale = min(scale, float(1 << SHADOW_TILEMAP_LOD));
402 /* Now scale by distance to the light. */
403 scale *= reduce_max(abs(lP));
404 }
405 /* Pixel bounding radius inside a tilemap of unit scale.
406 * Take only half of it because we want the radius and not the diameter. */
407 constexpr float texel_radius = M_SQRT2 / SHADOW_MAP_MAX_RES;
408 return texel_radius * scale;
409}
410
418float shadow_normal_offset(float3 Ng, float3 L, float texel_radius)
419{
420 /* Attenuate depending on light angle. */
421 float cos_theta = abs(dot(Ng, L));
422 float slope_offset = sin_from_cos(cos_theta);
423
424 /* Ng might have been quantized. Compensate the error by scaling the offset. */
425 const float max_angular_quantization_error = 0.534f; /* Radians. */
426 const float max_error_cos_inv = 1.0f / cos(max_angular_quantization_error);
427 /* The scaling is only to fix the self shadowing we need another bias for shadowing of adjacent
428 * polygons. */
429 const float max_error_adjacent_polygon = 0.195f; /* Eye-balled. */
430 float biased_offset = slope_offset * max_error_cos_inv + max_error_adjacent_polygon;
431
432 return biased_offset * texel_radius;
433}
434
436 float3 L,
437 float shadow_terminator_normal_offset,
438 float shadow_terminator_geometry_offset)
439{
440 const float offset_cutoff = shadow_terminator_geometry_offset;
441
442 if (shadow_terminator_geometry_offset == 0.0) {
443 return 0.0;
444 }
445
446 float cos_theta = dot(N, L);
447 const float offset_amount = saturate(1.0f - cos_theta / offset_cutoff);
448 return offset_amount * shadow_terminator_normal_offset;
449}
450
456 LightData light,
457 const bool is_directional,
458 const bool is_transmission,
459 bool is_translucent_with_thickness,
460 float2 frag_co,
461 Thickness thickness, /* Only used if is_transmission is true. */
462 float3 P,
463 float3 Ng,
464 float3 N,
465 float terminator_normal_offset,
466 float terminator_geometry_offset,
467 float soft_shadow_scale,
468 int ray_count,
469 int ray_step_count)
470{
471 /* Case of surfel light eval. */
472 float3 random_shadow_3d = float3(0.5f);
473 float2 random_pcf_2d = float2(0.0f);
474
476 random_shadow_3d = srd.util_tx.fetch(frag_co, UTIL_BLUE_NOISE_LAYER).rgb;
477 random_pcf_2d = random_shadow_3d.xy;
478
480 random_shadow_3d = fract(random_shadow_3d + srd.sampling.rng_3D_get(SAMPLING_SHADOW_U));
481 random_pcf_2d = fract(random_pcf_2d + srd.sampling.rng_2D_get(SAMPLING_SHADOW_X));
482 }
483 }
484
485 float distance_to_shadow;
486 /* Direction towards the shadow center (punctual) or direction (direction).
487 * Not the same as the light vector if the shadow is jittered. */
488 float3 L;
489 if (is_directional) {
490 L = light.z_axis();
491 }
492 else {
493 L = light.position() + light.local.local.shadow_position - P;
494 L = normalize_and_get_length(L, distance_to_shadow);
495 }
496
497 bool is_facing_light = (dot(Ng, L) > 0.0f);
498 /* Still bias the transmission surfaces towards the light if they are facing away. */
499 float3 N_bias = (is_transmission && !is_facing_light) ? reflect(Ng, L) : Ng;
500
501 /* Shadow map texel radius at the receiver position. */
502 float texel_radius = shadow_texel_radius_at_position(
503 srd.uniforms, srd.views, light, is_directional, P);
504
505 if (is_transmission && !is_facing_light) {
506 /* Ideally, we should bias using the chosen ray direction. In practice, this conflict with our
507 * shadow tile usage tagging system as the sampling position becomes heavily shifted from the
508 * tagging position. This is the same thing happening with missing tiles with large radii. */
509 P += abs(is_directional ? thickness.value() :
510 min(thickness.value(), distance_to_shadow - 0.01f)) *
511 L;
512 }
513 /* Avoid self intersection with respect to numerical precision. */
514 P = offset_ray(P, N_bias);
515 /* Stochastic Percentage Closer Filtering. */
516 P += (light.filter_radius * texel_radius) * shadow_pcf_offset(L, Ng, random_pcf_2d);
517 /* Add normal bias to avoid aliasing artifacts. */
518 P += N_bias * shadow_normal_offset(Ng, L, texel_radius);
519
520 /* Bias more to avoid terminator artifacts. */
521 P += N * shadow_terminator_offset(N, L, terminator_normal_offset, terminator_geometry_offset);
522
523 float3 lP = is_directional ? light_world_to_local_direction(light, P) :
526 /* Invert horizon clipping. */
527 lNg = (is_transmission) ? -lNg : lNg;
528 /* Don't do a any horizon clipping in this case as the closure is lit from both sides. */
529 lNg = (is_transmission && is_translucent_with_thickness) ? float3(0.0f) : lNg;
530
531 float surface_hit = 0.0f;
532 for (int ray_index = 0; ray_index < ray_count && ray_index < SHADOW_MAX_RAY; ray_index++) {
533 float2 random_ray_2d = fract(random::hammersley_2d(ray_index, ray_count) +
534 random_shadow_3d.xy);
535
536 bool has_hit;
537 if (is_directional) {
539 light, random_ray_2d, lP, texel_radius, soft_shadow_scale);
540 has_hit = shadow_map_trace(srd, clip_ray, ray_step_count, random_shadow_3d.z);
541 }
542 else {
544 light, random_ray_2d, lP, soft_shadow_scale);
545 has_hit = shadow_map_trace(srd, clip_ray, ray_step_count, random_shadow_3d.z);
546 }
547
548 surface_hit += float(has_hit);
549 }
550 /* Average samples. */
551 return saturate(1.0f - surface_hit / float(ray_count));
552}
553
555
556} // namespace eevee
#define M_SQRT2
#define M_PI
ccl_device_inline float cos_theta(const float3 w)
ccl_device_inline float sin_theta(const float3 w)
btScalar max
void make_orthonormal_basis(float3 N, float3 &T, float3 &B)
#define UTIL_BLUE_NOISE_LAYER
float light_sphere_disk_radius(float sphere_radius, float distance_to_sphere)
float3 light_world_to_local_point(LightData light, float3 point)
float3 light_world_to_local_direction(LightData light, float3 L)
bool clip_ray(float3 &start, float3 &end, const float3 direction, const float max_distance, const float4 frustum_planes[6])
float2 sample_disk(float2 rand)
float3 sample_uniform_cone(float2 rand, float cos_angle)
float2 sample_circle(float rand)
ShadowCoordinates shadow_punctual_coordinates(LightData light, float3 lP, int face_id)
int shadow_punctual_face_index_get(float3 lL)
float shadow_punctual_pixel_ratio(LightData light, float3 lP, bool is_perspective, float distance_to_camera, float film_pixel_radius)
ShadowCoordinates shadow_directional_coordinates(LightData light, float3 lP)
float3 shadow_punctual_local_position_to_face_local(int face_id, float3 lL)
#define FLT_MAX
#define static_branch
#define clip_distance
#define tan
#define exp2
T fract(T) RET
VecBase< float, D > intBitsToFloat(VecOp< int, D >) RET
VecBase< T, D > reflect(VecOp< T, D >, VecOp< T, D >) RET
#define cos
float dot(VecOp< float, D >, VecOp< float, D >) RET
constexpr T inversesqrt(T) RET
#define abs
#define sqrt
VecBase< float, 3 > cross(VecOp< float, 3 >, VecOp< float, 3 >) RET
constexpr T clamp(T, U, U) RET
float length(VecOp< float, D >) RET
float square(float v)
float cos_from_tan(float t)
float sin_from_cos(float c)
float3x3 scale(float3x3 mat, float2 scale)
float3x3 from_up_axis(float3 up)
float3 spherical_interpolate(float3 a, float3 b, float t)
float safe_rcp(float a)
VecT normalize_and_get_length(VecT vector, float &out_length)
float length_squared(VecT a)
float reduce_max(float2 a)
VecT safe_normalize(VecT vector)
float3 offset_ray(float3 P, float3 Ng)
float orderedIntBitsToFloat(int int_value)
const int state
@ LIGHT_SUN
#define N
#define L
ShadowMapTracingState shadow_map_trace_init(int sample_count, float step_offset)
static constexpr float SHADOW_TRACING_INVALID_HISTORY
void shadow_map_trace_hit_check(ShadowMapTracingState &state, ShadowTracingSample samp, bool is_last_sample)
ShadowRayPunctual shadow_ray_generate_punctual(LightData light, float2 random_2d, float3 lP, float soft_shadow_scale)
ShadowTracingSample shadow_map_trace_sample(ShadowRenderData &srd, ShadowMapTracingState state, ShadowRayDirectional &ray)
float3 shadow_pcf_offset(float3 L, float3 Ng, float2 random)
float shadow_normal_offset(float3 Ng, float3 L, float texel_radius)
ShadowRayDirectional shadow_ray_generate_directional(LightData light, float2 random_2d, float3 lP, float texel_radius, float soft_shadow_scale)
float shadow_eval(ShadowRenderData &srd, LightData light, const bool is_directional, const bool is_transmission, bool is_translucent_with_thickness, float2 frag_co, Thickness thickness, float3 P, float3 Ng, float3 N, float terminator_normal_offset, float terminator_geometry_offset, float soft_shadow_scale, int ray_count, int ray_step_count)
float shadow_terminator_offset(float3 N, float3 L, float shadow_terminator_normal_offset, float shadow_terminator_geometry_offset)
bool shadow_map_trace(ShadowRenderData &srd, ShadowRayType ray, int sample_count, float step_offset)
float shadow_texel_radius_at_position(const Uniform &uni, const draw::View &views, LightData light, const bool is_directional, float3 P)
float2 hammersley_2d(T i, T sample_count)
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
#define saturate(a)
Definition smaa.cc:319
#define min(a, b)
Definition sort.cc:38
float4 fetch(float2 texel, float layer) const
bool is_perspective() const
float z_distance(float3 P) const
ViewMatrices get(uint view_id) const
float3 rng_3D_get(const eSamplingDimension dim) const
float2 rng_2D_get(const eSamplingDimension dim) const
float read_depth(ShadowCoordinates coord) const
ShadowRenderConstants constants
const UniformData & uniform_buf
float x
float y
float z
Definition sky_math.h:136
ccl_device_inline T transform_direction_transposed(const ccl_private Transform *t, const T a)
Definition transform.h:176