Blender V5.3
eevee_ray_trace_screen_lib.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
16
17#include "eevee_bxdf.bsl.hh"
22#include "gpu_shader_codegen_lib.glsl"
25
26/* Inputs expected to be in view-space. */
28{
29 float near_dist = view.near();
30 if ((ray.origin.z + ray.direction.z * ray.max_time) > near_dist) {
31 ray.max_time = abs((near_dist - ray.origin.z) / ray.direction.z);
32 }
33}
34
36 /* Screen space hit position [0..1]. Last component is the ray depth, not the occluder depth. */
38 /* View space hit position. */
40 /* Tracing time in world space. */
41 float time;
42 /* True if there was a valid intersection. False if went out of screen without intersection. */
43 bool valid;
44 /* True if ray was under a surface. */
46};
47
62 RayTraceData rt_data,
63 HiZData hiz_data,
64 sampler2D hiz_tx,
65 float stride_rand,
66 float roughness,
67 const bool allow_self_intersection,
68 Ray ray)
69{
70 /* Clip to near plane for perspective view where there is a singularity at the camera origin. */
71 if (view.winmat[3][3] == 0.0f) {
73 }
74
75 /* NOTE: The 2.0 factor here is because we are applying it in NDC space. */
76 ScreenSpaceRay ssray = ScreenSpaceRay::create(view, ray, 2.0f * rt_data.full_resolution_inv);
77
78 /* Avoid no iteration. */
79 if (!allow_self_intersection && ssray.max_time < 1.1f) {
80 /* Still output the clipped ray. */
81 float3 hit_ssP = ssray.origin.xyz + ssray.direction.xyz * ssray.max_time;
82 float3 hit_P = view.point_screen_to_world(float3(hit_ssP.xy, saturate(hit_ssP.z)));
83 ray.direction = hit_P - ray.origin;
84
85 ScreenTraceHitData no_hit;
86 no_hit.time = 0.0f;
87 no_hit.valid = false;
88 return no_hit;
89 }
90
91 ssray.max_time = max(1.1f, ssray.max_time);
92
93 float prev_delta = 0.0f, prev_time = 0.0f;
94 float depth_sample = view.depth_view_to_screen(ray.origin.z);
95 float delta = depth_sample - ssray.origin.z;
96
97 float lod_fac = saturate(sqrt_fast(roughness) * 2.0f - 0.4f);
98
99 ScreenThicknessEstimator thickness_estimator = ScreenThicknessEstimator::init(depth_sample);
100 float prev_ray_z = ssray.origin.z;
101
102 /* Cross at least one pixel. */
103 float t = 1.001f, time = 1.001f;
104 bool hit = false;
105 constexpr int max_steps = 255;
106 for (int iter = 1; !hit && (time < ssray.max_time) && (iter < max_steps); iter++) {
107 float stride = 1.0f + float(iter) * rt_data.quality;
108 float lod = log2(stride) * lod_fac;
109
110 prev_time = time;
111 prev_delta = delta;
112
113 time = min(t + stride * stride_rand, ssray.max_time);
114 t += stride;
115
116 float3 ss_ray_P = ssray.screen_position_at(time);
117 depth_sample = textureLod(hiz_tx, ss_ray_P.xy * hiz_data.uv_scale, floor(lod)).r;
118
119 float sample_view_Z = view.depth_screen_to_view(depth_sample);
120 float sample_ndc_min_thickness = rt_data.ray_thickness.pixel_depth_thickness_at(sample_view_Z);
121
122 delta = depth_sample - ss_ray_P.z;
123 hit = thickness_estimator.intersect(
124 depth_sample, time, sample_ndc_min_thickness, ss_ray_P.z, prev_ray_z);
125 prev_ray_z = ss_ray_P.z;
126 }
127 /* Reject hit if background. */
128 hit = hit && (depth_sample != 1.0f);
129 /* Refine hit using intersection between the sampled height-field and the ray.
130 * This simplifies nicely to this single line. */
131 time = mix(prev_time, time, saturate(prev_delta / (prev_delta - delta)));
132
133 ScreenTraceHitData result;
134 /* We can only hit a backface if the ray was under the surface.
135 * Fast math optimizations can lead to deltas slightly below zero. */
136 const float backface_epsilon = -1e-7f;
137 result.hit_backface = prev_delta < backface_epsilon;
138 result.ss_hit_P = ssray.origin.xyz + ssray.direction.xyz * time;
139 result.v_hit_P = view.point_screen_to_view(result.ss_hit_P);
140 /* Convert to world space ray time. */
141 result.time = length(result.v_hit_P - ray.origin) / length(ray.direction);
142 /* Update the validity as ss_hit_P can point to a background sample. */
143 result.valid = hit &&
144 (textureLod(hiz_tx, result.ss_hit_P.xy * hiz_data.uv_scale, 0.0f).r != 1.0f);
145
146 return result;
147}
148
150 RayTraceData rt_data,
151 sampler2DArrayDepth planar_depth_tx,
152 PlanarProbeData planar,
153 float stride_rand,
154 Ray ray)
155{
156 /* Clip to near plane for perspective view where there is a singularity at the camera origin. */
157 if (view.winmat[3][3] == 0.0f) {
159 }
160
161 float2 inv_texture_size = 1.0f / float2(textureSize(planar_depth_tx, 0).xy);
162 /* NOTE: The 2.0 factor here is because we are applying it in NDC space. */
163 ScreenSpaceRay ssray = ScreenSpaceRay::create(ray, planar.winmat, 2.0f * inv_texture_size);
164
165 float prev_delta = 0.0f, prev_time = 0.0f;
166 float depth_sample = reverse_z::read(
167 texture(planar_depth_tx, float3(ssray.origin.xy, planar.layer_id)).r);
168 float delta = depth_sample - ssray.origin.z;
169
170 float t = 0.0f, time = 0.0f;
171 bool hit = false;
172 constexpr int max_steps = 32;
173 for (int iter = 1; !hit && (time < ssray.max_time) && (iter < max_steps); iter++) {
174 float stride = 1.0f + float(iter) * rt_data.quality;
175
176 prev_time = time;
177 prev_delta = delta;
178
179 time = min(t + stride * stride_rand, ssray.max_time);
180 t += stride;
181
182 float4 ss_ray = ssray.origin + ssray.direction * time;
183
184 depth_sample = reverse_z::read(texture(planar_depth_tx, float3(ss_ray.xy, planar.layer_id)).r);
185
186 delta = depth_sample - ss_ray.z;
187 /* Check if the ray is below the surface. */
188 hit = (delta < 0.0f);
189 }
190 /* Reject hit if background. */
191 hit = hit && (depth_sample != 1.0f);
192 /* Refine hit using intersection between the sampled height-field and the ray.
193 * This simplifies nicely to this single line. */
194 time = mix(prev_time, time, saturate(prev_delta / (prev_delta - delta)));
195
196 ScreenTraceHitData result;
197 result.ss_hit_P = ssray.origin.xyz + ssray.direction.xyz * time;
198 /* Update the validity as ss_hit_P can point to a not loaded sample. */
199 result.valid =
200 hit &&
201 textureLod(planar_depth_tx, float3(result.ss_hit_P.xy, planar.layer_id), 0.0f).r != 0.0;
202
203 /* NOTE: v_hit_P is in planar reflected view space. */
204 result.v_hit_P = project_point(planar.wininv, view.screen_to_ndc(result.ss_hit_P));
205 /* Convert to world space ray time. */
206 result.time = length(result.v_hit_P - ray.origin) / length(ray.direction);
207 return result;
208}
209
210/* Modify the ray origin before tracing it. We must do this because ray origin is implicitly
211 * reconstructed from gbuffer depth which we cannot modify. */
212Ray raytrace_thickness_ray_amend(Ray ray, ClosureUndetermined cl, float3 V, Thickness thickness)
213{
214 switch (cl.type) {
216 return bxdf_ggx_ray_amend_transmission(cl, V, ray, thickness);
218 return bxdf_translucent_ray_amend(cl, V, ray, thickness);
219 case CLOSURE_NONE_ID:
221 case CLOSURE_BSDF_MICROFACET_GGX_REFLECTION_ID:
224 break;
225 }
226 return ray;
227}
228
229bool clip_ray(float3 &start,
230 float3 &end,
231 const float3 direction,
232 const float max_distance,
233 const float4 frustum_planes[6])
234{
235 float min_t = 0.0f;
236 float max_t = max_distance;
237
238 for (int i = 0; i < 6; i++) {
239 /* Make normals point outwards.
240 * This way xyz * w represents a point in the plane surface. */
241 const float3 plane_normal = -frustum_planes[i].xyz;
242 const float plane_distance = frustum_planes[i].w;
243
244 const float NoR = dot(plane_normal, direction);
245 const float NoS = dot(plane_normal, start);
246
247 if (abs(NoR) < 1e-6f) {
248 /* Parallel ray. */
249 if (NoS > plane_distance) {
250 /* Fully outside the Frustum. */
251 return false;
252 }
253 continue;
254 }
255
256 const float plane_t = (plane_distance - NoS) / NoR;
257
258 if (NoR > 0.0f) {
259 /* Ray going outside. */
260 max_t = min(max_t, plane_t);
261 }
262 else {
263 /* Ray going inside. */
264 min_t = max(min_t, plane_t);
265 }
266 }
267
268 end = start + direction * max_t;
269 start = start + direction * min_t;
270
271 return max_t > min_t;
272}
273
274/*
275 * Similar to `raytrace_screen`, but modified to fit the needs of the Ray-cast node:
276 * - Improves the support for rays parallel or nearly parallel to the incoming direction.
277 * - Supports discarding hits against other objects.
278 * - Traverses every single pixel between start and end, unless the number of steps required is
279 * greater than max_steps, in that case the steps are evenly distributed across the full
280 * distance.
281 * Expects vs_origin and vs_end to be already clipped to the view frustum (see clip_ray above).
282 * Returns the hit distance, or -1 if no hit was found.
283 */
285 const float3 vs_origin,
286 const float3 vs_end,
287 const float3 vs_direction,
288 sampler2D depth_tx,
289 const RayTraceData rt_data,
290 const int max_steps,
291 const float jitter,
292 usampler2D ob_id_tx,
293 const uint object_id,
294 float2 &r_hit_uv)
295{
296 /* Convert ray start and end into NDC for correct interpolation. */
297 float3 start, end;
298 start.xyz = view.point_view_to_screen(vs_origin);
299 end.xyz = view.point_view_to_screen(vs_end);
300
301 const float2 extent = float2(textureSize(ob_id_tx, 0).xy);
302 const float2 texel_to_uv = (float2(1.0f) / extent);
303
304 const float2 total_pixel_delta = abs(start.xy - end.xy) * extent;
305 /* Number of steps required to trace a fully contiguous line. */
306 int steps = int(max(total_pixel_delta.x, total_pixel_delta.y)) + 1;
307 /* Limit to max steps. */
308 steps = min(steps, max_steps);
309
310 /* Per-step delta. */
311 const float3 delta = (end - start) / float(steps);
312
313 const float max_t = max(steps - 1, 1);
314 float previous_step_z = start.z;
315
316 ScreenThicknessEstimator thickness_estimator = ScreenThicknessEstimator::init(start.z);
317
318 /* Skip the first step to avoid self-occlusion. But iterate at least once. */
319 for (int i = 1; i < steps || i == 1; i++) {
320 /* Ensure we don't go past ray end. */
321 const float step_t = min(float(i) + jitter, max_t);
322 const float3 step = start + delta * step_t;
323
324 const float2 texel = step.xy * extent;
325 if (object_id != 0 && object_id != texelFetch(ob_id_tx, int2(texel), 0).r) {
326 thickness_estimator.thickness(1.0f, step_t, 0.0f);
327 previous_step_z = step.z;
328 continue;
329 }
330
331 /* Trick to prevent depth aliasing,
332 * from "Rendering Tiny Glades With Entirely Too Much Ray Marching":
333 * - Fetch depth using both point and linear sampling.
334 * - Use the furthest one for intersection check.
335 * - Use the closest one for thickness check. */
336 const float2 gather_uv = round(texel) * texel_to_uv;
337 const float2 bilinear_coords = fract(texel - 0.5f);
338 const float4 depth4 = reverse_z::read(textureGather(depth_tx, gather_uv));
339 const float hit_depth_point = mix(mix(depth4.w, depth4.z, bilinear_coords.x > 0.5f),
340 mix(depth4.x, depth4.y, bilinear_coords.x > 0.5f),
341 bilinear_coords.y > 0.5f);
342 const float hit_depth_linear = mix(mix(depth4.w, depth4.z, bilinear_coords.x),
343 mix(depth4.x, depth4.y, bilinear_coords.x),
344 bilinear_coords.y);
345 const float hit_min_z = min(hit_depth_point, hit_depth_linear);
346 const float hit_max_z = max(hit_depth_point, hit_depth_linear);
347
348 const float sample_view_Z = view.depth_screen_to_view(hit_depth_point);
349 const float sample_ndc_min_thickness = rt_data.ray_thickness.pixel_depth_thickness_at(
350 sample_view_Z);
351
352 /* Equivalent to #thickness_estimator.intersect() but applies the Tiny Glade fix. */
353 float sample_thickness = thickness_estimator.thickness(
354 hit_depth_point, step_t, sample_ndc_min_thickness);
355 /* We want to test the intersection between the surface estimated AABB and the ray step AABB.
356 * This is equivalent to adding the step delta to the surface thickness and doing an AABB vs
357 * point test. */
358 sample_thickness += abs(step.z - previous_step_z);
359
360 const float sample_min = hit_max_z;
361 const float sample_max = hit_min_z + sample_thickness;
362 const bool hit = step.z >= sample_min && step.z <= sample_max;
363
364 previous_step_z = step.z;
365
366 if (hit) {
367 r_hit_uv = step.xy;
368 /* We have a hit. Compute the distance. */
369 const float3 vs_hit_point = view.point_screen_to_view(float3(step.xy, hit_depth_point));
370 /* Hit point projection along the ray. */
371 return dot(vs_hit_point - vs_origin, vs_direction);
372 }
373 }
374
375 /* No hit was found. Return -1 to signal the failure. */
376 return -1.0f;
377}
378
384 sampler2D radiance_tx,
385 RayTraceData raytrace,
387 float roughness,
388 float2 ss_hit_P)
389{
390 /* We do not need a plausible cone value here.
391 * Just compute some factor to avoid blurring contact points. */
392 float shading_cone_tangent = saturate(roughness * 0.05);
393 float vs_footprint = shading_cone_tangent * hit.time;
394 /* Convert from view space cone to screen space. */
395 float4 hs_hit_P = view.winmat * float4(hit.v_hit_P, 1.0f);
396 float ndc_footprint = (vs_footprint * view.winmat[0][0]) / hs_hit_P.w;
397 float pixel_footprint = ndc_footprint * raytrace.full_resolution.x;
398
399 float3 radiance;
400 /* Fetch radiance at hit-point. */
401 if (pixel_footprint < 1.0f) {
402 radiance = textureLod(radiance_tx, ss_hit_P, 0.0f).rgb;
403 }
404 else {
405 float kernel_radius = saturate(pixel_footprint - 1.0f);
406 float4 ofs = float2(kernel_radius, -kernel_radius).xxyy * raytrace.full_resolution_inv.xyxy;
407 /* 4x4 box filter kernel for rough rays at the hit point.
408 * Reduces variance of noisy reflected objects.
409 * Use squared space to reduce fireflies at the cost of losing energy. */
410 radiance = log2(1.0f + textureLod(radiance_tx, ss_hit_P + ofs.xy, 0.0f).rgb);
411 radiance += log2(1.0f + textureLod(radiance_tx, ss_hit_P + ofs.xw, 0.0f).rgb);
412 radiance += log2(1.0f + textureLod(radiance_tx, ss_hit_P + ofs.zy, 0.0f).rgb);
413 radiance += log2(1.0f + textureLod(radiance_tx, ss_hit_P + ofs.zw, 0.0f).rgb);
414 radiance *= 0.25f;
415 radiance = exp2(radiance) - 1.0f;
416 }
417 return radiance;
418}
419
425 sampler2DArray radiance_tx,
426 RayTraceData raytrace,
428 float roughness,
429 float2 ss_hit_P,
430 int layer)
431{
432 /* We do not need a plausible cone value here.
433 * Just compute some factor to avoid blurring contact points. */
434 float shading_cone_tangent = saturate(roughness * 0.05);
435 float vs_footprint = shading_cone_tangent * hit.time;
436 /* Convert from view space cone to screen space. */
437 float4 hs_hit_P = view.winmat * float4(hit.v_hit_P, 1.0f);
438 float ndc_footprint = (vs_footprint * view.winmat[0][0]) / hs_hit_P.w;
439 float pixel_footprint = ndc_footprint * raytrace.full_resolution.x;
440
441 float3 radiance;
442 /* Fetch radiance at hit-point. */
443 if (pixel_footprint < 1.0f) {
444 radiance = textureLod(radiance_tx, float3(ss_hit_P, layer), 0.0f).rgb;
445 }
446 else {
447 float kernel_radius = saturate(pixel_footprint - 1.0f);
448 float4 ofs = float2(kernel_radius, -kernel_radius).xxyy * raytrace.full_resolution_inv.xyxy;
449 /* 4x4 box filter kernel for rough rays at the hit point.
450 * Reduces variance of noisy reflected objects.
451 * Use squared space to reduce fireflies at the cost of losing energy. */
452 radiance = log2(1.0f + textureLod(radiance_tx, float3(ss_hit_P + ofs.xy, layer), 0.0f).rgb);
453 radiance += log2(1.0f + textureLod(radiance_tx, float3(ss_hit_P + ofs.xw, layer), 0.0f).rgb);
454 radiance += log2(1.0f + textureLod(radiance_tx, float3(ss_hit_P + ofs.zy, layer), 0.0f).rgb);
455 radiance += log2(1.0f + textureLod(radiance_tx, float3(ss_hit_P + ofs.zw, layer), 0.0f).rgb);
456 radiance *= 0.25f;
457 radiance = exp2(radiance) - 1.0f;
458 }
459 return radiance;
460}
btScalar max
Ray bxdf_translucent_ray_amend(ClosureUndetermined cl, float3, Ray ray, Thickness thickness)
Ray bxdf_ggx_ray_amend_transmission(ClosureUndetermined cl, float3 V, Ray ray, Thickness thickness)
ScreenTraceHitData raytrace_screen(ViewMatrices view, RayTraceData rt_data, HiZData hiz_data, sampler2D hiz_tx, float stride_rand, float roughness, const bool allow_self_intersection, Ray ray)
bool clip_ray(float3 &start, float3 &end, const float3 direction, const float max_distance, const float4 frustum_planes[6])
float raytrace_screen_2(ViewMatrices view, const float3 vs_origin, const float3 vs_end, const float3 vs_direction, sampler2D depth_tx, const RayTraceData rt_data, const int max_steps, const float jitter, usampler2D ob_id_tx, const uint object_id, float2 &r_hit_uv)
Ray raytrace_thickness_ray_amend(Ray ray, ClosureUndetermined cl, float3 V, Thickness thickness)
ScreenTraceHitData raytrace_planar(ViewMatrices view, RayTraceData rt_data, sampler2DArrayDepth planar_depth_tx, PlanarProbeData planar, float stride_rand, Ray ray)
float3 raytrace_sample_screen(ViewMatrices view, sampler2D radiance_tx, RayTraceData raytrace, ScreenTraceHitData hit, float roughness, float2 ss_hit_P)
void raytrace_clip_ray_to_near_plane(ViewMatrices view, Ray &ray)
#define layer
#define exp2
#define round
T fract(T) RET
float dot(VecOp< float, D >, VecOp< float, D >) RET
#define log2
#define abs
#define floor
VecBase< float, D > step(VecOp< float, D >, VecOp< float, D >) RET
float length(VecOp< float, D >) RET
SamplerBase< float, 2, false, true, false, true > sampler2DArrayDepth
TEX_TEMPLATE DataVec texture(T, FltCoord, float=0.0f) RET
TEX_TEMPLATE DataVec texelFetch(T, IntCoord, int) RET
TEX_TEMPLATE DataVec textureGather(T, FltCoord, int=0) RET
TEX_TEMPLATE DataVec textureLod(T, FltCoord, float) RET
SamplerBase< float, 2, false, true > sampler2DArray
SamplerBase< float, 2 > sampler2D
TEX_TEMPLATE SizeVec textureSize(T, int) RET
SamplerBase< uint, 2 > usampler2D
float sqrt_fast(float v)
float2 project_point(float3x3 mat, float2 point)
@ CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID
@ CLOSURE_BSDF_DIFFUSE_ID
@ CLOSURE_BSSRDF_BURLEY_ID
@ CLOSURE_NONE_ID
@ CLOSURE_BSDF_THIN_GLASS_TRANSMISSION_ID
@ CLOSURE_BSDF_TRANSLUCENT_ID
VecBase< float, 3 > float3
T read(T depth_buffer_value)
#define mix
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
#define saturate(a)
Definition smaa.cc:319
#define min(a, b)
Definition sort.cc:38
float max_time
packed_float3 direction
packed_float3 origin
static ScreenSpaceRay create(ViewMatrices view, Ray ray, float2 pixel_size)
float3 screen_position_at(float t)
static ScreenThicknessEstimator init(float start_z)
float thickness(float sample_ss_z, float sample_ss_t, float sample_min_thickness)
bool intersect(float sample_ss_z, float sample_ss_t, float sample_min_thickness, float ray_ss_z, float ray_ss_z_prev)
float depth_screen_to_view(float ss_depth) const
float near() const
float3 point_screen_to_world(float3 ssP) const
T screen_to_ndc(T ss_P) const
float depth_view_to_screen(float v_depth) const
float3 point_view_to_screen(float3 vP) const
float3 point_screen_to_view(float3 ssP) const
float x
float y
float z
Definition sky_math.h:136
float y
Definition sky_math.h:225
float z
Definition sky_math.h:225
float x
Definition sky_math.h:225
float w
Definition sky_math.h:225
CCL_NAMESPACE_BEGIN struct Window V