Displacement in the viewport's key-light shadows

The shadow pass draws the dense copy and displaces it like the 3D view, so a displaced surface
shadows itself instead of being shadowed as if it were still smooth.

- shaders/displace.wgsl: displace_by_height, shared by mesh.wgsl and shadow.wgsl
- the shadow pipeline takes the set bind group (height and sampler) and a displacement vec4
  (on, world units per unit of height with the height strength, vertex spacing)
- while it displaces, the cached shadow map is re-rendered when the set textures change
- test: with flat height, displaced shadows match the plain mesh's
This commit is contained in:
bflatastic committed 2026-11-01 13:35:53 +07:00
1 parent 8b8655a6f3
commit e2637115df
7 files changed
+86 -38

No files matched your search

-1
View File
@@ -191,7 +191,6 @@ from our code against public documentation.
- hardware ray tracing in Rendering mode;
- pen tilt (the windowing layer doesn't report it yet);
- Alembic files in the older HDF5 container, and Alembic animation (the first sample is read);
- displacement in the viewport's key-light shadows (the viewport and the path tracers displace);
- a native-speaker review of the translations;
- the first signed release on every platform.
+43 -26
View File
@@ -427,8 +427,9 @@ struct ViewTargets {
struct ShadowMap {
view: wgpu::TextureView,
size: u32,
/// What the map was rendered for: mesh id, light direction bits, visible sets.
key: Option<(u64, [u32; 3])>,
/// What the map was rendered for: mesh id, light direction bits, displacement (its
/// parameters' bits and, when on, the content revision), visible sets.
key: Option<(u64, [u32; 3], [u32; 4], u64)>,
visible: Vec<bool>,
vp: Mat4,
buf: wgpu::Buffer,
@@ -730,10 +731,10 @@ impl Renderer {
let shader = |label: &str, source: &str| {
device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(source.into()) })
};
let module = shader("tc_mesh", include_str!("shaders/mesh.wgsl"));
let module = shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl")));
let util_module = shader("tc_util", include_str!("shaders/util.wgsl"));
let post_module = shader("tc_post", concat!(include_str!("shaders/util.wgsl"), include_str!("shaders/post.wgsl"), include_str!("shaders/fx.wgsl")));
let shadow_module = shader("tc_shadow", include_str!("shaders/shadow.wgsl"));
let shadow_module = shader("tc_shadow", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/shadow.wgsl")));
let bgl = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| {
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries })
};
@@ -782,7 +783,7 @@ impl Renderer {
let bg_layout = pl("tc_bg", &[Some(&globals_bgl)]);
let blit_layout = pl("tc_blit", &[Some(&blit_bgl)]);
let fx_layout = pl("tc_fx", &[Some(&fx_bgl)]);
let shadow_layout = pl("tc_shadow", &[Some(&shadow_bgl)]);
let shadow_layout = pl("tc_shadow", &[Some(&shadow_bgl), Some(&set_bgl)]);
let vb = [Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Vertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
@@ -888,7 +889,7 @@ impl Renderer {
});
let shadow_buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("tc_shadow"),
size: std::mem::size_of::<[[f32; 4]; 4]>() as u64,
size: std::mem::size_of::<[[f32; 4]; 5]>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
@@ -1420,11 +1421,22 @@ impl Renderer {
}
/// Keep the key-light shadow map current; returns its view-projection. `light` points to
/// the light (world space). Re-renders only when the mesh, light or visible sets changed.
/// the light (world space), `disp` is the shadow pass's displacement (see shadow.wgsl).
/// Re-renders only when the mesh, light, displacement or visible sets changed (and, when it
/// displaces, the set textures).
/// shortcut: casters are fully opaque (the dithered opacity cut-out is ignored) and the map is
/// one shared buffer, so two 3D views with different lights in one frame would share the last
/// light; upgrade to a per-view map if split 3D views get their own lights.
fn update_shadow(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, light: Vec3, visible: &[bool]) -> Option<Mat4> {
#[allow(clippy::too_many_arguments)]
fn update_shadow(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
light: Vec3,
disp: [f32; 4],
visible: &[bool],
) -> Option<Mat4> {
let l = light.try_normalize()?;
let (id, center, radius) = self.mesh.as_ref().map(|m| (m.id, m.center, m.radius))?;
if self.shadow.size != SHADOW_SIZE {
@@ -1435,14 +1447,18 @@ impl Renderer {
v.globals_bg = None;
}
}
let key = (id, l.to_array().map(f32::to_bits));
let displacing = disp[0] > 0.5;
let key = (id, l.to_array().map(f32::to_bits), disp.map(f32::to_bits), if displacing { self.content_rev } else { 0 });
if self.shadow.key == Some(key) && self.shadow.visible == visible {
return Some(self.shadow.vp);
}
// An orthographic light frustum around the mesh's bounding sphere.
let up = if l.y.abs() > 0.99 { Vec3::Z } else { Vec3::Y };
let vp = Mat4::orthographic_rh(-radius, radius, -radius, radius, radius * 0.5, radius * 3.5) * Mat4::look_at_rh(center + l * radius * 2.0, center, up);
queue.write_buffer(&self.shadow.buf, 0, bytemuck::bytes_of(&vp.to_cols_array_2d()));
let mut raw = [[0.0f32; 4]; 5];
raw[..4].copy_from_slice(&vp.to_cols_array_2d());
raw[4] = disp;
queue.write_buffer(&self.shadow.buf, 0, bytemuck::bytes_of(&raw));
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("tc_shadow"),
color_attachments: &[],
@@ -1457,12 +1473,12 @@ impl Renderer {
});
pass.set_pipeline(&self.shadow_pipeline);
pass.set_bind_group(0, &self.shadow.bg, &[]);
// shortcut: casters are the base mesh (not displaced); a displaced shadow pass would
// need the set textures in shadow.wgsl.
if let Some(m) = &self.mesh {
pass.set_vertex_buffer(0, m.geo.vb.slice(..));
pass.set_index_buffer(m.geo.ib.slice(..), wgpu::IndexFormat::Uint32);
for (range, _) in self.drawable(&m.geo.draws, visible, None) {
let geo = m.dense.as_ref().filter(|_| displacing).unwrap_or(&m.geo);
pass.set_vertex_buffer(0, geo.vb.slice(..));
pass.set_index_buffer(geo.ib.slice(..), wgpu::IndexFormat::Uint32);
for (range, set) in self.drawable(&geo.draws, visible, None) {
pass.set_bind_group(1, &set.bind_group, &[]);
pass.draw_indexed(range, 0, 0..1);
}
}
@@ -1517,7 +1533,18 @@ impl Renderer {
let (sin, cos) = s.env_rotation_deg.to_radians().sin_cos();
let [lx, ly, lz, lw] = s.light;
let light = Vec3::new(cos * lx + sin * lz, ly, cos * lz - sin * lx);
let shadow_vp = if !data && s.shadows && lw > 0.0 { self.update_shadow(device, queue, encoder, light, &frame.visible) } else { None };
let displace = s.displacement && frame.kind == ViewKind::Scene;
if displace {
self.ensure_dense(device, queue);
}
let disp = match self.mesh.as_ref().filter(|_| displace) {
// Height-to-normal's slope: strength 1 tilts 45° for a height change of 1 over 1/16 of
// the UV square; the vertex shader samples the mip whose texels match the vertex spacing.
Some(m) => [1.0, m.world_per_uv / 16.0, 1.0 / (m.dense.as_ref().unwrap_or(&m.geo).triangles.max(1) as f32 * 0.5).sqrt(), 0.0],
None => [0.0; 4],
};
let shadow_disp = [disp[0], disp[1] * s.height_strength, disp[2], 0.0];
let shadow_vp = if !data && s.shadows && lw > 0.0 { self.update_shadow(device, queue, encoder, light, shadow_disp, &frame.visible) } else { None };
let radius = self.mesh.as_ref().map_or(1.0, |m| m.radius);
// Background rays come from a perspective camera even in orthographic views (an ortho
// ray grid would show a single flat environment color).
@@ -1529,16 +1556,6 @@ impl Renderer {
let sss = s.sss_blur.filter(|m| scene_fx && m.iter().any(|v| *v > 0.0));
let fx_on = dof.is_some() || sss.is_some();
let refraction = s.refraction && !data && frame.kind == ViewKind::Scene && self.mesh.is_some();
let displace = s.displacement && frame.kind == ViewKind::Scene;
if displace {
self.ensure_dense(device, queue);
}
let disp = match self.mesh.as_ref().filter(|_| displace) {
// Height-to-normal's slope: strength 1 tilts 45° for a height change of 1 over 1/16 of
// the UV square; the vertex shader samples the mip whose texels match the vertex spacing.
Some(m) => [1.0, m.world_per_uv / 16.0, 1.0 / (m.dense.as_ref().unwrap_or(&m.geo).triangles.max(1) as f32 * 0.5).sqrt(), 0.0],
None => [0.0; 4],
};
let cam = &frame.camera;
let half_h = (cam.fov.clamp(5.0, 150.0).to_radians() * 0.5).tan();
let height = frame.size[1].max(1) as f32;
+9
View File
@@ -0,0 +1,9 @@
// Displacement shared by the 3D view (mesh.wgsl) and the key-light shadow pass (shadow.wgsl).
// `p` moved along normal `n` by `scale` times the height at `uv`, read at the mip whose texels
// match the vertex spacing `spacing` (UV units).
fn displace_by_height(p: vec3<f32>, n: vec3<f32>, uv: vec2<f32>, height: texture_2d<f32>, smp: sampler, scale: f32, spacing: f32) -> vec3<f32> {
let dims = vec2<f32>(textureDimensions(height));
let h = textureSampleLevel(height, smp, uv, max(log2(dims.x * spacing), 0.0)).r;
return p + n * inverseSqrt(max(dot(n, n), 1e-12)) * (h * scale);
}
+2 -6
View File
@@ -61,16 +61,12 @@ struct VOut {
@location(3) uv: vec2<f32>,
};
// The vertex moved along its normal by the height channel (displacement), at the mip whose texels
// match the vertex spacing.
// The vertex moved along its normal by the height channel (displacement).
fn displaced(v: VIn) -> vec3<f32> {
if (g.disp.x < 0.5) {
return v.pos;
}
let dims = vec2<f32>(textureDimensions(t_height));
let h = textureSampleLevel(t_height, samp, v.uv, max(log2(dims.x * g.disp.z), 0.0)).r;
let n = v.nrm * inverseSqrt(max(dot(v.nrm, v.nrm), 1e-12));
return v.pos + n * (h * g.mode.z * g.disp.y);
return displace_by_height(v.pos, v.nrm, v.uv, t_height, samp, g.mode.z * g.disp.y, g.disp.z);
}
@vertex
+16 -4
View File
@@ -1,8 +1,20 @@
// Depth-only key-light shadow map pass.
// Depth-only key-light shadow map pass, displaced like the 3D view when it displaces.
@group(0) @binding(0) var<uniform> light_vp: mat4x4<f32>;
struct ShadowPass {
light_vp: mat4x4<f32>,
disp: vec4<f32>, // x displacement on (1), y world units per unit of height, z vertex spacing in UV units, w -
};
@group(0) @binding(0) var<uniform> sp: ShadowPass;
// The set bind group of mesh.wgsl: only its height and sampler.
@group(1) @binding(3) var t_height: texture_2d<f32>;
@group(1) @binding(9) var samp: sampler;
@vertex
fn vs_shadow(@location(0) pos: vec3<f32>) -> @builtin(position) vec4<f32> {
return light_vp * vec4<f32>(pos, 1.0);
fn vs_shadow(@location(0) pos: vec3<f32>, @location(1) nrm: vec3<f32>, @location(3) uv: vec2<f32>) -> @builtin(position) vec4<f32> {
var p = pos;
if (sp.disp.x > 0.5) {
p = displace_by_height(pos, nrm, uv, t_height, samp, sp.disp.y, sp.disp.z);
}
return sp.light_vp * vec4<f32>(p, 1.0);
}
+15
View File
@@ -164,6 +164,21 @@ fn post_effects() {
assert_eq!(all.px.len(), base.px.len());
}
/// The shadow pass draws the displaced (dense) mesh when the view displaces: with flat height it
/// casts the same shadows as the plain mesh.
#[test]
fn displaced_shadows_match_flat_height() {
let Some((mut h, frame)) = setup() else { return };
let lit = shaded(&frame, |s| {
s.light = LIGHT;
s.shadows = true;
});
let plain = render(&mut h, &lit, "shadows_plain");
let displaced = render(&mut h, &shaded(&lit, |s| s.displacement = true), "shadows_displaced");
let off = plain.px.chunks(4).zip(displaced.px.chunks(4)).filter(|(a, b)| a.iter().zip(*b).any(|(x, y)| x.abs_diff(*y) > 8)).count();
assert!(off < 480 * 360 / 100, "{off} pixels differ");
}
#[test]
fn shadows_darken_the_key_light() {
let Some((mut h, frame)) = setup() else { return };
+1 -1
View File
@@ -75,7 +75,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
## The viewport
- Physically based shading (metallic/roughness or specular/glossiness) with clear coat, sheen,
anisotropy, subsurface scattering, transmission, parallax occlusion and **displacement** from the
anisotropy, subsurface scattering, transmission, parallax occlusion and **displacement** (with its own shadows) from the
height channel; image-based lighting from
six procedural studio and outdoor environments or **your own HDR/EXR panoramas**; ACES or linear
tone mapping, key-light shadows, bloom, vignette, sharpen, grain, **depth of field** and