Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Viewport: ambient occlusion no longer shows ghost copies of the model (#4167) (#4251)

CamWight4577dffb3680
diff --git a/assets/shaders/viewport.wgsl b/assets/shaders/viewport.wgsl
index 922fc6b853..7980b295f6 100644
--- a/assets/shaders/viewport.wgsl
+++ b/assets/shaders/viewport.wgsl
@@ -296,9 +296,10 @@ fn opaque_depth(i: TOut, front: bool) -> AoDepth {
return AoDepth(depth, bitcast<u32>(depth));
}
-// Deterministic cosine-weighted hemisphere samples. Projecting the sample and a point one
-// radius toward the eye supplies a depth range in both orthographic and perspective views;
-// distant foreground geometry cannot cast a dark halo onto a background surface.
+// Cosine-weighted hemisphere samples, the pattern turned by a different angle at each pixel.
+// Projecting the sample and a point one radius toward the eye supplies a depth range in both
+// orthographic and perspective views; distant foreground geometry cannot cast a dark halo onto
+// a background surface.
fn occlusion(i: TOut) -> f32 {
let radius = u.ao.x;
if (radius <= 0.0 || length(i.n) < 0.5) { return 1.0; }
@@ -311,6 +312,14 @@ fn occlusion(i: TOut) -> f32 {
// The map is a 1 × 1 stand-in until a frame draws into it (the product preview draws no
// prepass): sampling it tells nothing, so leave the surface unoccluded.
if (size.x < 2 || size.y < 2) { return 1.0; }
+ // The same offsets at every pixel made each sample darken its own shifted copy of a nearby
+ // part's outline: faint ghosts of the part where the radius is large on screen (#4167),
+ // stepped bands along contacts where it is small (#3407). Turned by interleaved gradient
+ // noise (Jimenez 2014), neighbouring pixels sample different points and the copies break up
+ // into an even grain.
+ let turn = fract(52.9829189 * fract(dot(i.pos.xy, vec2<f32>(0.06711056, 0.00583715))));
+ let t = tangent * cos(turn * 6.28318531) + bitangent * sin(turn * 6.28318531);
+ let b = cross(n, t);
// One comparison for both depth directions: depths read as 0 near / 1 far (mirrored when
// the buffer runs reversed). The map is cleared to its far plane either way, so a texel
// with nothing in it reads as 1 and the `d < 1.0` test below skips it.
@@ -319,7 +328,7 @@ fn occlusion(i: TOut) -> f32 {
for (var j = 0u; j < 32u; j = j + 1u) {
let f = (f32(j) + 0.5) / 32.0;
let angle = f32(j) * 2.39996323;
- let direction = tangent * (cos(angle) * sqrt(f)) + bitangent * (sin(angle) * sqrt(f)) + n * sqrt(1.0 - f);
+ let direction = t * (cos(angle) * sqrt(f)) + b * (sin(angle) * sqrt(f)) + n * sqrt(1.0 - f);
let reach = radius * (0.2 + 0.8 * fract(f32(j) * 0.61803399 + 0.5));
let sample = i.wp + n * (radius * 0.025) + direction * reach;
let q = u.vp * vec4<f32>(sample, 1.0);
diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs
index f95817f8ea..05597f1f90 100644
--- a/crates/ui-egui/src/gpu.rs
+++ b/crates/ui-egui/src/gpu.rs
@@ -219,7 +219,7 @@ pub(crate) fn render_offscreen(
back,
eye,
size,
- Offscreen { tess, product: false, srgb: false, analysis, analysis_colors: colors, ssaa: 1.0 },
+ Offscreen { tess, product: false, srgb: false, analysis, analysis_colors: colors, ssaa: 1.0, ao_radius: 0.0 },
)
}
@@ -239,7 +239,7 @@ pub(crate) fn render_product_offscreen(
back,
eye,
size,
- Offscreen { tess: None, product: true, srgb, analysis: [0.0; 8], analysis_colors: [0.0; 36], ssaa: 1.0 },
+ Offscreen { tess: None, product: true, srgb, analysis: [0.0; 8], analysis_colors: [0.0; 36], ssaa: 1.0, ao_radius: 0.0 },
)
}
@@ -251,6 +251,7 @@ struct Offscreen<'a> {
analysis: [f32; 8],
analysis_colors: [f32; 36],
ssaa: f32,
+ ao_radius: f32,
}
/// [`render_offscreen`] of a scene supersampled `ssaa` times (1: off).
@@ -270,7 +271,28 @@ pub(crate) fn render_offscreen_ssaa(
back,
eye,
size,
- Offscreen { tess: None, product: false, srgb: false, analysis: [0.0; 8], analysis_colors: [0.0; 36], ssaa },
+ Offscreen { tess: None, product: false, srgb: false, analysis: [0.0; 8], analysis_colors: [0.0; 36], ssaa, ao_radius: 0.0 },
+ )
+}
+
+/// [`render_offscreen`] of a scene with ambient occlusion of `ao_radius` (world units; 0: off).
+#[cfg(all(test, not(target_arch = "wasm32")))]
+pub(crate) fn render_offscreen_ao(
+ scene: GpuScene,
+ view_proj: [[f32; 4]; 4],
+ back: [f32; 3],
+ eye: [f32; 4],
+ size: u32,
+ ao_radius: f32,
+) -> Option<Vec<u8>> {
+ offscreen(
+ scene,
+ None,
+ view_proj,
+ back,
+ eye,
+ size,
+ Offscreen { tess: None, product: false, srgb: false, analysis: [0.0; 8], analysis_colors: [0.0; 36], ssaa: 1.0, ao_radius },
)
}
@@ -284,7 +306,7 @@ fn offscreen(
size: u32,
options: Offscreen<'_>,
) -> Option<Vec<u8>> {
- let Offscreen { tess, product, srgb, analysis, analysis_colors, ssaa } = options;
+ let Offscreen { tess, product, srgb, analysis, analysis_colors, ssaa, ao_radius } = options;
let (adapter, device, queue) = offscreen_device()?;
eprintln!("offscreen adapter: {:?}", adapter.get_info().backend);
let format = if srgb { wgpu::TextureFormat::Rgba8UnormSrgb } else { wgpu::TextureFormat::Rgba8Unorm };
@@ -316,7 +338,7 @@ fn offscreen(
access: None,
outline: false,
eye,
- ao_radius: 0.0,
+ ao_radius,
ssaa,
hover_tint: [0.0; 3],
selection_tint: [0.0; 3],
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 1972aaff08..1c016ea52b 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -5241,6 +5241,68 @@ mod tests {
assert!(w < 5120 && w as f32 >= 2560.0 * 1.25 && u64::from(w) * u64::from(h) * 32 <= 384 << 20, "{w} x {h}");
}
+ /// Ambient occlusion beside a block on a plate (#4167, #3407), seen from above with a radius
+ /// large on screen (a big design seen close up): the plate darkens toward the block and is
+ /// clear beyond the radius, with no copies of the block's outline in the darkening. The same
+ /// sample offsets at every pixel gave each sample its own shifted copy, so beside the block's
+ /// straight side every row was the same staircase. Skipped without a GPU adapter.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn ambient_occlusion_draws_no_copies_of_a_part() {
+ let mut s = solidcraft_engine::Session::default();
+ s.execute("solid.box", &json!({"length": 300, "width": 300, "height": 4, "corner": [-150, -150, -4], "body_name": "plate"})).unwrap();
+ s.execute("solid.box", &json!({"length": 30, "width": 160, "height": 16, "corner": [0, -80, 0], "operation": "new", "body_name": "block"}))
+ .unwrap();
+ let mut app = SolveApp::new(s, crate::Services::default());
+ let (yaw, pitch) = solidcraft_engine::render::StandardView::Top.angles();
+ app.cam = Camera { target: Vec3::new(-30.0, 0.0, 0.0), yaw, pitch, roll: 0.0, distance: 200.0, fov: 0.0, ..Default::default() };
+ app.ui.perspective = false;
+ app.ui.show_grid = false;
+ app.set_origin_shown(false);
+ app.ui.ground_shadow = false;
+ app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false });
+ const SIZE: u32 = 512;
+ const RADIUS: f32 = 45.0;
+ let rect = Rect::from_min_size(Pos2::ZERO, vec2(SIZE as f32, SIZE as f32));
+ let proj = projection(&app, rect);
+ let e = proj.cam.eye().to_f32();
+ let eye = [e[0], e[1], e[2], 0.0];
+ let render =
+ |radius: f32| crate::gpu::render_offscreen_ao(build_scene(&app).merged(), proj.vp.to_f32(), proj.cam.back().to_f32(), eye, SIZE, radius);
+ let (Some(off), Some(on)) = (render(0.0), render(RADIUS)) else {
+ eprintln!("skipping: no GPU adapter");
+ return;
+ };
+ let (w, r) = (f64::from(SIZE), scene_radius(&app));
+ let at = |p: Vec3| proj.cam.to_screen(p, w, w, r).unwrap();
+ // The block's left side on screen, the radius in pixels, and rows beside the middle of
+ // the side, far enough from its ends that every sample's copy spans them all.
+ let edge = at(Vec3::new(0.0, 0.0, 16.0)).0;
+ let reach = (at(Vec3::new(f64::from(RADIUS), 0.0, 0.0)).0 - at(Vec3::ZERO).0).abs();
+ let (a, b) = (at(Vec3::new(-10.0, 10.0, 0.0)).1.round() as usize, at(Vec3::new(-10.0, -10.0, 0.0)).1.round() as usize);
+ let (y0, y1) = (a.min(b), a.max(b));
+ assert!(reach > 100.0 && y1 > y0 + 20, "{reach} px, rows {y0}..{y1}");
+ let lum = |img: &[u8], x: usize, y: usize| img[(y * SIZE as usize + x) * 4..][..3].iter().map(|&c| f64::from(c)).sum::<f64>();
+ // The plate's visibility in each column: its brightness with AO over its brightness
+ // without, averaged over the rows.
+ let column = |x: usize| (y0..y1).map(|y| lum(&on, x, y) / lum(&off, x, y).max(1.0)).sum::<f64>() / (y1 - y0) as f64;
+ // From 30 px beyond the radius up to 4 px from the block (its outline).
+ let from = (edge - reach - 30.0) as usize;
+ let profile: Vec<f64> = (from..=(edge - 4.0) as usize).map(column).collect();
+ let (clear, shaded) = (&profile[..20], &profile[30..]);
+ let step = shaded.windows(2).map(|p| (p[1] - p[0]).abs()).fold(0.0, f64::max);
+ eprintln!(
+ "plate {} without AO; edge {edge:.1} px, radius {reach:.1} px, rows {y0}..{y1}; clear {:.4}..{:.4}; next to the block {:.4}; largest step {step:.4}",
+ lum(&off, from, y0) / 3.0,
+ clear.iter().copied().fold(f64::INFINITY, f64::min),
+ clear.iter().copied().fold(0.0, f64::max),
+ profile[profile.len() - 1],
+ );
+ assert!(profile[profile.len() - 1] < 0.98, "the plate darkens beside the block: {:.4}", profile[profile.len() - 1]);
+ assert!(clear.iter().all(|v| (v - 1.0).abs() < 0.004), "the plate is clear beyond the radius: {clear:?}");
+ assert!(step < 0.005, "no copies of the block's outline: a step of {step:.4} between neighbouring columns");
+ }
+
/// A hovered face lights solidly over a body drawn from its display plan on the GPU: the
/// highlight uses the plan's triangles, not the reference mesh's other triangulation of the
/// same face, which fought the model at equal depth and shimmered in wedges. Every face of a
diff --git a/docs/ambient-occlusion.md b/docs/ambient-occlusion.md
index ab2a1c0dee..8e8d53ded4 100644
--- a/docs/ambient-occlusion.md
+++ b/docs/ambient-occlusion.md
@@ -30,8 +30,11 @@ The control channel and connected MCP clients can use the same command as the UI
`ui.prefs {"ambient_occlusion": true}` also sets the preference. The command changes
only display preferences, without adding a modelling undo step or moving the camera.
-The GPU viewport uses 32 deterministic hemisphere samples per shaded pixel against
-an opaque depth prepass (at most 2048 pixels on its longest side). The radius follows
+The GPU viewport uses 32 hemisphere samples per shaded pixel against an opaque depth
+prepass (at most 2048 pixels on its longest side), the sample pattern turned by a
+different angle at each pixel. One pattern for every pixel drew faint shifted copies of
+nearby parts (#4167) and stepped bands along contacts (#3407); turned, they become an
+even fine grain, which 2× supersampling smooths further. The radius follows
model size, and depth-range rejection avoids shadows from distant foreground objects.
It supports orthographic and perspective cameras and respects section clipping.
Wireframe, transparent bodies, overlays and surface-analysis colours are unaffected.