From 4ced1d7bcfbb3bd40c557d4c68cf583ac22f2767 Mon Sep 17 00:00:00 2001 From: Homero Thompson Date: Mon, 26 Oct 2026 07:59:56 +0000 Subject: [PATCH] Viewport: the grid fades with the distance instead of cutting off (#4214) (#4629) * claim: #4214 * Viewport: the grid fades with the distance instead of cutting off (#4214) The ground grid stopped at a fixed distance from the view, so its edge showed as a cut across the picture. It now fades out with the distance from the middle of the view, and it is gone before either of the two lines that used to cut it: its own edge, and the picture's far plane. Each grid line is drawn in pieces, and each piece is as faint as the fade makes it at the distance where it lies. The 'under' batch is drawn by the overlay pipeline with alpha blending, so the colour's alpha reaches the frame. * The headless grid fades with the distance too (#4214) The headless path (solidcraft-cli snapshot, the home-page thumbnail, the MCP screenshot) drew the grid from the engine's palette, where a line had no alpha: the grid still ended in a cut, and at a low camera angle the cut was in the picture. A SceneLine now carries an alpha, the CPU rasterizer blends with it and the GPU capture passes it on, so the engine's grid can fade. The fade itself moves to the engine, next to the grid's other geometry, and both paths use it: the headless grid now reaches as far on the ground as the view is wide (the ground stretches as it is seen at a slant) and dissolves into the distance instead of ending in a line. * Fix the headless/viewport grid fade divergence (#4214) The engine stretched the grid's size with the slant of the plane it is seen at, the viewport stretched it only on the ground, so on a sketch's plane the picture's grid reached further than the window's (153.42 mm against 120.00 mm). Both now share one grid_ext, which the picture and the window draw the same grid from. * The grid fades out before the picture's far plane cuts the ground (#4214) The window's grid faded against a far plane of its own: the scene's radius clipped by the projection's camera (260 mm away at 400 mm of distance), while the picture itself cuts the ground at the far plane of its own projection (223.7 mm at the same distance, because the projection frames the scene's bounds and not its radius). The grid was still a third of its strength where the picture cut the ground, so the cut showed as a straight line across the view. The fade now ends at the far plane the picture's projection uses, and the grid is gone before that plane cuts the ground. The test that watched the fade now measures the ink of each row of the picture, and checks that the grid is already gone in the ten rows above the row where the far plane cuts the ground: the point it compared before lay beyond that plane, where both renders draw nothing at all, so the comparison was always true. --- crates/engine/src/view.rs | 160 +++++++++++++++-- crates/engine/src/view_palette_tests.rs | 69 ++++++++ crates/gpu/src/capture.rs | 6 +- crates/gpu/tests/capture.rs | 34 +++- crates/gpu/tests/depth.rs | 4 +- crates/gpu/tests/thin_lines.rs | 3 +- crates/render/src/raster.rs | 32 +++- crates/render/src/scene.rs | 3 + crates/ui-egui/src/viewport.rs | 221 +++++++++++++++++++++++- 9 files changed, 500 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index 529e2e48f..58eba1f15 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -209,6 +209,116 @@ pub fn grid_step(half_height: f64) -> (f64, f64) { (minor, minor * 5.0) } +/// How the grid fades out with the distance from the middle of the view (#4214). +/// +/// The grid used to stop at a fixed distance, so its edge showed as a cut across the picture. It +/// now fades: at full strength near the middle of the view, and gone before the grid's own edge +/// and before the picture's far plane cuts the ground, so that neither of them shows. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GridFade { + /// The distance from the middle of the view where the grid starts to dim. + pub start: f64, + /// The distance from the middle of the view where the grid is gone. + pub end: f64, +} + +impl GridFade { + /// The fade for a view of the given half height, seen at the given slant (the cosine of the + /// angle between the view and the grid's plane), over a grid of the given half size, that + /// reaches no further than `far_reach` before the picture's far plane cuts the ground. + pub fn new(half_height: f64, slant: f64, ext: f64, far_reach: f64) -> Self { + // The distance from the middle of the view to its edge, measured on the grid's plane: the + // ground stretches as it is seen at a slant, as the grid's own size does (#3087). + let reach = half_height / slant.abs().max(0.25); + // The grid is gone before its own edge, and before the far plane cuts the ground, so that + // neither of them shows as a cut. + let end = (2.2 * reach).min(ext).min(far_reach); + GridFade { start: 0.6 * reach.min(end), end } + } + + /// How much of the grid is left at a distance from the middle of the view. + pub fn alpha(&self, d: f64) -> f32 { + if !d.is_finite() { + return 0.0; + } + if d <= self.start { + return 1.0; + } + if d >= self.end || self.end <= self.start { + return 0.0; + } + ((self.end - d) / (self.end - self.start)) as f32 + } + + /// The pieces the grid's line at the given offset from the middle is drawn in: each with the + /// alpha the fade gives it at the distance where it lies. The line runs along the grid's other + /// axis; it is drawn whole where the grid is at full strength, and in pieces that fade + /// towards its ends. + pub fn pieces(&self, offset: f64) -> Vec<(f64, f64, f32)> { + let mut out = Vec::new(); + let off = offset.abs(); + if !(self.end > 0.0) || off >= self.end { + return out; + } + // Where the grid is still at full strength. + let solid = if off < self.start { (self.start * self.start - off * off).max(0.0).sqrt() } else { 0.0 }; + if solid > 0.0 { + out.push((-solid, solid, 1.0)); + } + // The fading ends, in pieces whose distance from the middle grows evenly, so that the + // grid dims evenly too. + let from = off.max(self.start); + for k in 0..GRID_FADE_STEPS { + let (d0, d1) = + (from + (self.end - from) * k as f64 / GRID_FADE_STEPS as f64, from + (self.end - from) * (k + 1) as f64 / GRID_FADE_STEPS as f64); + let (s0, s1) = ((d0 * d0 - off * off).max(0.0).sqrt(), (d1 * d1 - off * off).max(0.0).sqrt()); + let alpha = self.alpha((d0 + d1) * 0.5); + if alpha > 0.0 { + out.push((s0, s1, alpha)); + out.push((-s1, -s0, alpha)); + } + } + out + } +} + +/// How many pieces a grid line's fading end is drawn in: enough that the grid dims evenly, few +/// enough that the grid stays cheap to draw. +const GRID_FADE_STEPS: u32 = 12; + +/// How far the grid reaches before the picture's far plane cuts the ground: the distance on the +/// grid's plane from the middle of the view to where the far plane ends it (#4214). Looking +/// straight down, the ground's depth does not grow and the far plane never cuts it. +/// +/// `c` is the middle of the view and `n` the grid's normal, both in the world. +pub fn grid_far_reach(cam: &Camera, far: f64, c: Vec3, n: Vec3) -> f64 { + let eye = cam.eye(); + // The direction the camera looks, and where it looks on the grid's plane: the ground's + // forward direction, which the depth grows along. + let view = -cam.back(); + let forward = view - n * view.dot(n); + let len = forward.len(); + if len < 1e-9 { + return f64::INFINITY; + } + let depth = (c - eye).dot(view); + if far <= depth { + return 0.0; + } + (far - depth) / len +} + +/// The grid's half size for a view of the given half height, seen at the given slant (the cosine +/// of the angle between the view and the grid's plane): the grid reaches as far on its plane as +/// the view is wide, which stretches as the plane is seen at a slant (#3087). +/// +/// The picture and the window share it, so that they draw the same grid (#4214). +pub fn grid_ext(half_height: f64, major: f64, slant: f64) -> f64 { + let major = major.max(1e-3); + let ext = (half_height * 3.0 / major).ceil() * major; + (ext / slant.abs().max(0.25) / major).ceil() * major +} + /// Sketch curves as world polylines with their colour. pub fn sketch_lines(sk: &Sketch, plane: &Plane, active: bool, determined: &[bool]) -> Vec<(Vec, Rgb, bool)> { sketch_lines_with_sampler(sk, plane, active, determined, world_curve_parts) @@ -480,34 +590,52 @@ fn build_scene( // Grid on the ground plane (XY with Z up, XZ with Y up), drawn under the model as in the viewport. if guides.grid { let (minor, major) = grid_step(cam.half_height()); - let ext = (cam.half_height() * 3.0 / major).ceil() * major; // Headless pictures keep the grid on the ground, the viewport's default; an open sketch // has its own plane's grid (world coordinates, no camera frame). - let (c, u, v, w): (Vec3, Vec3, Vec3, Box Vec3>) = if let Some(pl) = open_sketch_plane(s) { + let (c, u, v, slant, w): (Vec3, Vec3, Vec3, f64, Box Vec3>) = if let Some(pl) = open_sketch_plane(s) { let (c, u, v) = sketch_grid_frame(&pl, cam.target, major); - (c, u, v, Box::new(|p| p)) + let n = u.cross(v); + (c, u, v, cam.back().dot(n), Box::new(|p| p)) } else { let tf = cam.to_frame(cam.target); let (u, v) = (Vec3::X, Vec3::Y); + let back = cam.to_frame(cam.back()); + let n = u.cross(v); let snap = |a: Vec3| a * ((tf.dot(a) / major).round() * major); - (snap(u) + snap(v), u, v, Box::new(|p| cam.from_frame(p))) + (snap(u) + snap(v), u, v, back.dot(n), Box::new(|p| cam.from_frame(p))) }; - let n = ((ext / minor) as i64).clamp(1, 400); + // The grid reaches as far on the ground as the view is wide (the ground stretches as it + // is seen at a slant) and fades out with the distance, so that it dissolves into the + // distance instead of ending in a cut (#4214). + let ext = grid_ext(cam.half_height(), major, slant); + let far_reach = grid_far_reach(cam, cam.clip(sc.radius).1, w(c), w(u.cross(v))); + let fade = GridFade::new(cam.half_height(), slant, ext, far_reach); + let n = ((fade.end / minor) as i64).clamp(1, 400); for i in -n..=n { let t = i as f64 * minor; let major_line = (t / major).fract().abs() < 1e-9; let col = if major_line { p.grid_major } else { p.grid }; // The viewport's widths (pixels). let width = if major_line { 1.0 } else { 0.7 }; - sc.grid.push(SceneLine { points: vec![w(c + u * t - v * ext), w(c + u * t + v * ext)], color: col, width, on_top: false }); - sc.grid.push(SceneLine { points: vec![w(c - u * ext + v * t), w(c + u * ext + v * t)], color: col, width, on_top: false }); + // Two lines through the point `c + u * t`: one along v, one along u. + for (along, across) in [(v, u), (u, v)] { + for (s0, s1, alpha) in fade.pieces(t) { + sc.grid.push(SceneLine { + points: vec![w(c + across * t + along * s0), w(c + across * t + along * s1)], + color: col, + alpha, + width, + on_top: false, + }); + } + } } } // The origin's axes, each unless hidden one by one (`browser.visibility`), as in the viewport. let axis = cam.half_height() * 0.25; for ((name, d), col) in [("X", Vec3::X), ("Y", Vec3::Y), ("Z", Vec3::Z)].into_iter().zip(p.axes) { if guides.axes && !s.visibility.hidden_origin.iter().any(|h| h == name) { - sc.lines.push(SceneLine { points: vec![Vec3::ZERO, d * axis], color: col, width: 1.6, on_top: false }); + sc.lines.push(SceneLine { points: vec![Vec3::ZERO, d * axis], color: col, alpha: 1.0, width: 1.6, on_top: false }); } } let selected_occurrences: Vec = s @@ -548,19 +676,19 @@ fn build_scene( && s.doc.face_colors(body).iter().all(|(_, l)| l.opacity >= 0.999) { for (a, b) in crate::cosmetic_threads::segments_with_budget(body, &mesh, &st.threads, &mut thread_budget) { - sc.lines.push(SceneLine { points: vec![a, b], color: p.edge, width: 0.85, on_top: false }); + sc.lines.push(SceneLine { points: vec![a, b], color: p.edge, alpha: 1.0, width: 0.85, on_top: false }); } } for (i, e) in mesh.edges.iter().enumerate() { if !mesh.shaded_edge_visible(i) { continue; } - sc.lines.push(SceneLine { points: e.clone(), color: p.edge, width: 1.2, on_top: false }); + sc.lines.push(SceneLine { points: e.clone(), color: p.edge, alpha: 1.0, width: 1.2, on_top: false }); } // The outline of the body where the section cuts it. if let Some((o, n)) = section { for (a, b) in section_segments(&mesh, o, n) { - sc.lines.push(SceneLine { points: vec![a, b], color: p.edge, width: 1.6, on_top: false }); + sc.lines.push(SceneLine { points: vec![a, b], color: p.edge, alpha: 1.0, width: 1.6, on_top: false }); } } } @@ -570,7 +698,7 @@ fn build_scene( continue; } for (pts, col, cons) in sketch_lines_in(&ss.sketch, &ss.plane, active, &ss.report.curve_determined, &mut sampler, p) { - sc.lines.push(SceneLine { points: pts, color: col, width: if cons { 1.0 } else { 1.6 }, on_top: active }); + sc.lines.push(SceneLine { points: pts, color: col, alpha: 1.0, width: if cons { 1.0 } else { 1.6 }, on_top: active }); } } sc @@ -933,7 +1061,13 @@ mod tests { assert!(!section_segments(&s.world_state().bodies[0].mesh(), Vec3::new(0.0, 15.0, 0.0), -Vec3::Y).is_empty()); // A marker inside the body, behind the cut face. let red = Rgb(255, 0, 0); - sc.lines.push(SceneLine { points: vec![Vec3::new(5.0, 25.0, 10.0), Vec3::new(35.0, 25.0, 10.0)], color: red, width: 3.0, on_top: false }); + sc.lines.push(SceneLine { + points: vec![Vec3::new(5.0, 25.0, 10.0), Vec3::new(35.0, 25.0, 10.0)], + color: red, + alpha: 1.0, + width: 3.0, + on_top: false, + }); let img = solidcraft_render::render(&sc, &cam, 300, 220); let px = || img.rgba.chunks(4); let marker = px().filter(|p| p[0] > 200 && p[1] < 60 && p[2] < 60).count(); diff --git a/crates/engine/src/view_palette_tests.rs b/crates/engine/src/view_palette_tests.rs index db1a02787..4b991e325 100644 --- a/crates/engine/src/view_palette_tests.rs +++ b/crates/engine/src/view_palette_tests.rs @@ -6,6 +6,75 @@ use serde_json::json; use solidcraft_geom::Vec2; use solidcraft_sketch::{LinkGeom, LinkKind, LinkSource}; +/// #4214: the grid's fade is at full strength in the middle of the view, and gone before the +/// grid's own edge and before the picture's far plane cuts the ground, so that neither of them +/// shows as a cut. +#[test] +fn the_grid_fades_out_before_its_edge_and_before_the_far_plane() { + let fade = GridFade::new(40.0, 1.0, 120.0, 90.0); + assert!(fade.start < fade.end, "the fade has a width"); + assert!(fade.end <= 90.0, "the grid is gone before the far plane cuts the ground at 90"); + assert!(fade.end <= 120.0, "the grid is gone before its own edge at 120"); + assert_eq!(fade.alpha(0.0), 1.0, "the middle of the grid is at full strength"); + assert_eq!(fade.alpha(fade.start), 1.0, "the grid is at full strength up to {}", fade.start); + assert_eq!(fade.alpha(fade.end), 0.0, "the grid is gone at {}", fade.end); + assert_eq!(fade.alpha(fade.end * 2.0), 0.0, "the grid does not come back"); + assert_eq!(fade.alpha(f64::NAN), 0.0, "a distance that is not a number fades the grid away"); + // The fade falls evenly. + let mid = (fade.start + fade.end) * 0.5; + assert!((fade.alpha(mid) - 0.5).abs() < 0.01, "the fade falls evenly: {} at {mid}", fade.alpha(mid)); +} + +/// #4214: the headless grid fades out with the distance from the middle of the view, as the +/// viewport's does: the lines near the middle are at full strength, the ones further out are +/// dimmer, and the grid is gone before the distance where it used to stop. +#[test] +fn the_headless_grid_fades_out_with_the_distance() { + let s = Session::default(); + let mut cam = home_camera(&s); + // A top view: the ground is the XY plane and the grid is centred on the target. + cam.pitch = std::f64::consts::FRAC_PI_2; + cam.target = Vec3::ZERO; + let scene = scene(&s, &cam); + assert!(!scene.grid.is_empty(), "the grid is drawn"); + // How far each piece of the grid is from the middle of the view, and the alpha it is drawn + // with. + let mut pieces: Vec<(f64, f32)> = scene + .grid + .iter() + .map(|l| { + let mid = l.points[0] + (l.points[1] - l.points[0]) * 0.5; + ((mid.x * mid.x + mid.y * mid.y).sqrt(), l.alpha) + }) + .collect(); + pieces.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)); + // The grid in the middle of the view is at full strength. + let strongest = pieces.iter().filter(|(d, _)| *d < 1.0).map(|(_, a)| *a).fold(0.0f32, f32::max); + assert_eq!(strongest, 1.0, "the middle of the grid is at full strength"); + // The further from the middle, the dimmer: the outer half of the grid is fainter than the + // inner half. + let (near, far) = pieces.split_at(pieces.len() / 2); + let mean = |v: &[(f64, f32)]| v.iter().map(|(_, a)| f64::from(*a)).sum::() / v.len().max(1) as f64; + assert!(mean(near) > mean(far) + 0.1, "the grid fades: {} near the middle, {} far from it", mean(near), mean(far)); + // The grid is gone before the distance where it used to stop, so its edge never shows. + let (_, major) = grid_step(cam.half_height()); + let cut = (cam.half_height() * 3.0 / major).ceil() * major; + let farthest = pieces.last().map(|(d, _)| *d).unwrap_or(0.0); + assert!(farthest < cut, "the grid fades out at {farthest}, short of the cut at {cut}"); +} + +/// #4214: the grid's half size, the one the picture and the window share: the grid reaches as far +/// on its plane as the view is wide, and further as the plane is seen at a slant. +#[test] +fn the_grid_reaches_further_as_its_plane_is_seen_at_a_slant() { + let major = grid_step(40.0).1; + let flat = grid_ext(40.0, major, 1.0); + assert_eq!(flat, (40.0 * 3.0 / major).ceil() * major, "seen face on, the grid reaches as far as the view is wide"); + assert!(grid_ext(40.0, major, 0.5) > flat, "seen at a slant, the grid reaches further on its plane"); + // A plane seen edge-on keeps a usable size. + assert!(grid_ext(40.0, major, 0.0).is_finite()); +} + /// No colour here is one of [`colors`] or an appearance below, and each field has its own. const MARK: Palette = Palette { background: (Rgb(1, 2, 3), Rgb(4, 5, 6)), diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rs index 148e1fce4..25c99daa1 100644 --- a/crates/gpu/src/capture.rs +++ b/crates/gpu/src/capture.rs @@ -430,15 +430,15 @@ pub fn scene_geometry(scene: &Scene) -> GpuScene { } } } - let c4 = |c: Rgb| [c.0, c.1, c.2, 255]; + let c4 = |c: Rgb, a: f32| [c.0, c.1, c.2, (a.clamp(0.0, 1.0) * 255.0).round() as u8]; for l in &scene.grid { for w in l.points.windows(2) { - sc.under_line(w[0].to_f32(), w[1].to_f32(), c4(l.color), l.width as f32); + sc.under_line(w[0].to_f32(), w[1].to_f32(), c4(l.color, l.alpha), l.width as f32); } } for l in &scene.lines { for w in l.points.windows(2) { - sc.line(w[0].to_f32(), w[1].to_f32(), c4(l.color), l.width as f32, l.on_top); + sc.line(w[0].to_f32(), w[1].to_f32(), c4(l.color, l.alpha), l.width as f32, l.on_top); } } sc diff --git a/crates/gpu/tests/capture.rs b/crates/gpu/tests/capture.rs index 2967ed6be..ff78ad9ab 100644 --- a/crates/gpu/tests/capture.rs +++ b/crates/gpu/tests/capture.rs @@ -7,7 +7,7 @@ use serde_json::json; use solidcraft_engine::Session; use solidcraft_engine::geom::Vec3; -use solidcraft_engine::render::{Camera, Rgb, SceneLine}; +use solidcraft_engine::render::{Camera, Rgb, Scene, SceneLine}; use solidcraft_engine::view::{self, Guides, colors}; use solidcraft_gpu::GpuError; use solidcraft_gpu::capture::{self, Capturer}; @@ -162,7 +162,13 @@ fn pictures_show_the_section_and_its_cap() { let mut sc = view::scene(&s, &cam); // A marker inside the body, behind the cut face. let red = Rgb(255, 0, 0); - sc.lines.push(SceneLine { points: vec![Vec3::new(5.0, 25.0, 10.0), Vec3::new(35.0, 25.0, 10.0)], color: red, width: 3.0, on_top: false }); + sc.lines.push(SceneLine { + points: vec![Vec3::new(5.0, 25.0, 10.0), Vec3::new(35.0, 25.0, 10.0)], + color: red, + alpha: 1.0, + width: 3.0, + on_top: false, + }); let img = c.rgba(&sc, &cam, 300, 220).unwrap(); let marker = pixels(&img).filter(|p| p[0] > 200 && p[1] < 60 && p[2] < 60).count(); assert_eq!(marker, 0, "fov {fov}: the inside shows through the cut face"); @@ -226,6 +232,30 @@ fn a_body_behind_the_cut_does_not_colour_the_cap() { } } +/// #4214: a line that is not opaque is blended with what is under it, so the grid's fade reaches +/// the picture. +#[test] +fn pictures_blend_a_line_that_is_not_opaque() { + let Some(c) = capturer() else { return }; + let cam = Camera { distance: 50.0, fov: 0.0, ..Default::default() }; + let darkest = |alpha: f32| { + let mut sc = Scene { radius: 30.0, ..Default::default() }; + sc.lines.push(SceneLine { + points: vec![Vec3::new(-8.0, 2.0, 0.0), Vec3::new(8.0, 2.0, 0.0)], + color: Rgb(0, 0, 0), + alpha, + width: 1.4, + on_top: false, + }); + let img = c.rgba(&sc, &cam, 64, 64).unwrap(); + pixels(&img).map(|p| i32::from(p[0])).min().unwrap_or(255) + }; + let solid = darkest(1.0); + let half = darkest(0.5); + assert!(solid < 40, "the opaque line is black: {solid}"); + assert!(half > 60 && half < 170, "the half-opaque line is between the background and the line: {half} against {solid}"); +} + /// Surface analysis shades headless pictures as it shades the viewport: a box's flat faces in /// the curvature map's flat colour, zebra stripes in black and white, the accessibility analysis /// in reachable and blocked colours. diff --git a/crates/gpu/tests/depth.rs b/crates/gpu/tests/depth.rs index f22848088..a9be41344 100644 --- a/crates/gpu/tests/depth.rs +++ b/crates/gpu/tests/depth.rs @@ -153,7 +153,7 @@ fn front(mesh: Mesh, lines: Vec, radius: f64, fov: f64) -> (Scene, Ca } fn red_line(a: Vec3, b: Vec3, on_top: bool) -> SceneLine { - SceneLine { points: vec![a, b], color: Rgb(255, 0, 0), width: 1.2, on_top } + SceneLine { points: vec![a, b], color: Rgb(255, 0, 0), alpha: 1.0, width: 1.2, on_top } } fn red_pixels(c: &Capturer, scene: &Scene, cam: &Camera) -> usize { @@ -193,7 +193,7 @@ fn a_selected_edge_on_a_grazing_face_draws_whole() { sc.lifted_line(a.to_f32(), b.to_f32(), [255, 0, 0, 255], 6.0, [n.to_f32(), n.to_f32()]); sc }; - let reference = |a: Vec3, b: Vec3| vec![SceneLine { points: vec![a, b], color: Rgb(255, 0, 0), width: 6.0, on_top: true }]; + let reference = |a: Vec3, b: Vec3| vec![SceneLine { points: vec![a, b], color: Rgb(255, 0, 0), alpha: 1.0, width: 6.0, on_top: true }]; for (mode, c) in capturers() { for tilt in [60.0_f64, 80.0, 85.0, 88.0] { let tr = tilt.to_radians(); diff --git a/crates/gpu/tests/thin_lines.rs b/crates/gpu/tests/thin_lines.rs index c8cff8493..e9b6583f2 100644 --- a/crates/gpu/tests/thin_lines.rs +++ b/crates/gpu/tests/thin_lines.rs @@ -35,7 +35,8 @@ fn missing(c: &Capturer, width: f64) -> Vec { (0..N) .filter(|&i| { let z = -4.0 + i as f64 * 0.23; - let line = SceneLine { points: vec![Vec3::new(-8.0, 0.0, z), Vec3::new(8.0, 0.0, z)], color: Rgb(255, 0, 0), width, on_top: true }; + let line = + SceneLine { points: vec![Vec3::new(-8.0, 0.0, z), Vec3::new(8.0, 0.0, z)], color: Rgb(255, 0, 0), alpha: 1.0, width, on_top: true }; let scene = Scene { lines: vec![line], radius: 30.0, ..Default::default() }; let img = c.rgba(&scene, &cam, 200, 200).unwrap(); !img.as_chunks::<4>().0.iter().any(|p| p[0] > 60 && p[0] > p[1].saturating_add(40) && p[0] > p[2].saturating_add(40)) diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 68a3f197e..86ad798a0 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -230,6 +230,8 @@ pub fn render(scene: &Scene, cam: &Camera, w: usize, h: usize) -> Canvas { } for l in scene.grid.iter().chain(&scene.lines) { let col = l.color.f(); + // A line that is not opaque is blended with what is under it (the grid fading out). + let alpha = f64::from(l.alpha).clamp(0.0, 1.0); let half = (l.width * SS as f64 * 0.5).max(0.5); for seg in l.points.windows(2) { let (Some(&p), Some(&q)) = (seg.first(), seg.get(1)) else { continue }; @@ -264,7 +266,7 @@ pub fn render(scene: &Scene, cam: &Camera, w: usize, h: usize) -> Canvas { let visible = l.on_top || c.depth.get(i).zip(slope.get(i)).is_some_and(|(dd, s)| z <= f64::from(*dd) + f64::from(*s) * d + z.abs() * DEPTH_EPS); if visible { - c.put(ix as usize, iy as usize, col, cov); + c.put(ix as usize, iy as usize, col, cov * alpha); } } } @@ -428,6 +430,7 @@ mod tests { lines: vec![SceneLine { points: vec![Vec3::new(-8.0, 2.0, 0.0), Vec3::new(8.0, 2.0, 0.0)], color: Rgb(0, 0, 255), + alpha: 1.0, width: 1.4, on_top: false, }], @@ -499,6 +502,30 @@ mod tests { render(scene, cam, 64, 64).rgba.chunks(4).filter(|p| p[0] > 150 && p[1] < 100 && p[2] < 100).count() } + /// #4214: a line that is not opaque is blended with what is under it: the grid fades out + /// with the distance, and the fade reaches the picture. + #[test] + fn a_line_that_is_not_opaque_is_blended_with_what_is_under_it() { + let line = |alpha: f32| SceneLine { + points: vec![Vec3::new(-8.0, 2.0, 0.0), Vec3::new(8.0, 2.0, 0.0)], + color: Rgb(0, 0, 255), + alpha, + width: 1.4, + on_top: false, + }; + let cam = Camera { distance: 50.0, fov: 0.0, ..Default::default() }; + // The blue of the line over the white background, at full strength and at half. + let blue = |alpha: f32| { + let scene = Scene { lines: vec![line(alpha)], radius: 30.0, ..Default::default() }; + let img = render(&scene, &cam, 64, 64); + img.rgba.chunks(4).map(|p| p[2] as i32).max().unwrap_or(0) + }; + let solid = blue(1.0); + let half = blue(0.5); + assert!(solid > 200, "the opaque line is blue: {solid}"); + assert!(half < solid && half > 100, "the half-opaque line is between the background and the line: {half} against {solid}"); + } + /// An edge 1 mm behind a sheet is hidden in a close view of a large design. The old test /// allowed 2e-4 of the depth range, 2e-4 · (8 · 1200 + 2) = 1.92 mm here (orthographic; far /// more in perspective), so it was drawn on the sheet. Now the allowance is what the sheet's @@ -515,6 +542,7 @@ mod tests { let edge = SceneLine { points: vec![Vec3::new(-10.0, 0.0, 0.0) + back, Vec3::new(10.0, 0.0, 0.0) + back], color: Rgb(255, 0, 0), + alpha: 1.0, width: 1.2, on_top: false, }; @@ -534,7 +562,7 @@ mod tests { fn edges_on_a_steep_face_draw_whole() { let tilt = 70f64.to_radians(); let on = |x: f64, z: f64| Vec3::new(x, z * tilt.tan(), z); - let line = |points: Vec| SceneLine { points, color: Rgb(255, 0, 0), width: 1.2, on_top: false }; + let line = |points: Vec| SceneLine { points, color: Rgb(255, 0, 0), alpha: 1.0, width: 1.2, on_top: false }; for fov in [0.0, 0.6] { for radius in [30.0, 1200.0] { let lines = vec![ diff --git a/crates/render/src/scene.rs b/crates/render/src/scene.rs index 7b1e62f55..79744b516 100644 --- a/crates/render/src/scene.rs +++ b/crates/render/src/scene.rs @@ -58,6 +58,9 @@ pub const MIN_ALPHA: f64 = 0.05; pub struct SceneLine { pub points: Vec, pub color: Rgb, + /// How opaque the line is: 1 is solid, below 1 it is blended with what is under it (the + /// grid fades out with the distance, #4214). + pub alpha: f32, /// Width in output pixels. pub width: f64, /// Draw over everything (sketch geometry being edited). diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 8572525b1..2ce606788 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -9,7 +9,7 @@ use solidcraft_engine::Sel; use solidcraft_engine::geom::{Vec2, Vec3}; use solidcraft_engine::render::{Camera, Mat4, Rgb}; use solidcraft_engine::sketch::CurveKind; -use solidcraft_engine::view::{GridPlane, colors, grid_plane, grid_step, sketch_lines_with_sampler}; +use solidcraft_engine::view::{GridFade, GridPlane, colors, grid_ext, grid_plane, grid_step, sketch_lines_with_sampler}; use std::hash::{Hash, Hasher}; use crate::gpu::{Frame, GpuScene, GpuTarget, SceneSlot, ViewportCallback}; @@ -335,6 +335,13 @@ pub fn projection(app: &SolveApp, rect: Rect) -> Proj { Proj { cam, vp: cam.view_proj_bounds(aspect, &scene_bounds(app)), rect } } +/// The far plane the picture's projection uses: the grid's fade ends before that plane cuts the +/// ground (#4214). The scene's radius is not the radius the picture frames, so the planes of the +/// projection itself are the ones that count. +fn picture_far(app: &SolveApp, cam: &Camera) -> f64 { + cam.clip_bounds(&scene_bounds(app)).1 +} + /// Sketches drawn in the viewport: the active one, and finished ones not yet used by a feature. pub(crate) fn visible_sketches(app: &SolveApp) -> Vec { let st = crate::open_meshing::shown_world(app); @@ -1106,13 +1113,19 @@ fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { let sketch_plane = solidcraft_engine::view::open_sketch_plane(s); if sketch_plane.is_some() || (app.ui.show_grid && !active_view(app).hide_grid) { let (minor, major) = grid_step(app.cam.half_height()); - let mut ext = (app.cam.half_height() * 3.0 / major).ceil() * major; // An open sketch always has its grid on its own plane; otherwise the ground plane: XY with // Z up, XZ with Y up (laid out in the camera's Z-up frame), or the upright origin plane // facing the view when the ground is seen edge-on. - let (c, u, v, w3): (Vec3, Vec3, Vec3, Box [f32; 3]>) = if let Some(pl) = &sketch_plane { + let (c, u, v, slant, ext, far_reach, w3): (Vec3, Vec3, Vec3, f64, f64, f64, Box [f32; 3]>) = if let Some(pl) = &sketch_plane { let (c, u, v) = solidcraft_engine::view::sketch_grid_frame(pl, app.cam.target, major); - (c, u, v, Box::new(|p| p.to_f32())) + // How steeply the sketch's plane is seen: the grid reaches as far on it as the view + // is wide, so the fade with the distance does too (#4214). The sketch's plane is in + // the world, as the camera's direction is. + let n = u.cross(v); + let slant = app.cam.back().dot(n); + let ext = grid_ext(app.cam.half_height(), major, slant); + let far_reach = solidcraft_engine::view::grid_far_reach(&proj.cam, picture_far(app, &proj.cam), c, n); + (c, u, v, slant, ext, far_reach, Box::new(|p| p.to_f32())) } else { let tf = app.cam.to_frame(app.cam.target); // On the ground (XY) unless the Grid follows the view preference is on (#1470); then on @@ -1133,19 +1146,32 @@ fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { let back = app.cam.to_frame(app.cam.back()); let n = u.cross(v); let slant = back.dot(n); - ext = (ext / slant.abs().max(0.25) / major).ceil() * major; + let ext = grid_ext(app.cam.half_height(), major, slant); let centre = grid_centre(tf, back, n, ext); let snap = |a: Vec3| a * ((centre.dot(a) / major).round() * major); - (snap(u) + snap(v), u, v, Box::new(|p| app.cam.from_frame(p).to_f32())) + let c = snap(u) + snap(v); + // The far plane cuts the ground, and the grid's plane is the camera's frame's. + let far_reach = + solidcraft_engine::view::grid_far_reach(&proj.cam, picture_far(app, &proj.cam), app.cam.from_frame(c), app.cam.from_frame(n)); + (c, u, v, slant, ext, far_reach, Box::new(|p| app.cam.from_frame(p).to_f32())) }; - let n = ((ext / minor) as i64).clamp(1, 300); + // The grid fades out with the distance from the middle of the view (#4214): it used to + // stop at a fixed distance, so its edge showed as a cut across the picture. Each line is + // now drawn in pieces, each as faint as the fade makes it there, and the grid is gone + // before its own edge, which is therefore never seen. + let fade = GridFade::new(app.cam.half_height(), slant, ext, far_reach); + let n = ((fade.end / minor) as i64).clamp(1, 300); for i in -n..=n { let t = i as f64 * minor; let maj = (t / major).round() * major == t; let col = if maj { c4(tk.grid_major) } else { c4(tk.grid) }; let wd = if maj { 1.0 } else { 0.7 }; - sc.under_line(w3(c + u * t - v * ext), w3(c + u * t + v * ext), col, wd); - sc.under_line(w3(c - u * ext + v * t), w3(c + u * ext + v * t), col, wd); + // Two lines through the point `c + u * t`: one along v, one along u. + for (along, across) in [(v, u), (u, v)] { + for (s0, s1, alpha) in fade.pieces(t) { + sc.under_line(w3(c + across * t + along * s0), w3(c + across * t + along * s1), grid_colour(col, alpha), wd); + } + } } } for sid in visible_sketches(app) { @@ -4468,6 +4494,11 @@ fn points_2d(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { } } +/// A grid line's colour, as faint as the fade makes it. +fn grid_colour(c: [u8; 4], alpha: f32) -> [u8; 4] { + [c[0], c[1], c[2], (f64::from(c[3]) * f64::from(alpha)).round().clamp(0.0, 255.0) as u8] +} + /// Where the ground grid is centred: where the view's axis (`back`, through the camera's target /// `tf`) meets the plane through the origin with normal `n`, so the middle of the view has grid /// (#3087). At a grazing slant that point runs far off, and the ground in front of the camera @@ -7523,6 +7554,7 @@ mod tests { scene.lines.push(solidcraft_engine::render::SceneLine { points: edge.clone(), color: solidcraft_engine::view::colors::EDGE, + alpha: 1.0, width: 1.2, on_top: false, }); @@ -9178,6 +9210,177 @@ mod grid_plane_tests { assert!(x > lo[0] && x < hi[0] && y > lo[1] && y < hi[1], "the grid spans {lo:?}..{hi:?}, the middle of the view is at {mid:?}"); } + /// #4214: the grid used to stop at a fixed distance from the view, so its edge showed as a + /// cut across the picture. It now fades out with the distance from the middle of the view: + /// the lines near the middle are at full strength, the ones further out are dimmer, and the + /// grid is gone before the distance where it used to stop. + #[test] + fn the_grid_fades_out_with_the_distance_from_the_middle_of_the_view() { + let rect = Rect::from_min_size(Pos2::ZERO, egui::vec2(800.0, 600.0)); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.ui.show_grid = true; + app.ui.perspective = false; + // A top view: the ground is the XY plane, and the grid is centred on the target. + app.cam.pitch = std::f64::consts::FRAC_PI_2; + app.cam.yaw = 0.0; + app.cam.target = Vec3::ZERO; + app.cam.distance = 100.0; + let under = build_sketch_scene(&app, &projection(&app, rect)).under; + // Each line of the grid: two points, a colour and a width. + let segments: Vec<([f32; 3], [f32; 3], u8)> = under + .as_chunks::<32>() + .0 + .iter() + .map(|l| { + let point = |at: usize| [0, 4, 8].map(|i| f32::from_le_bytes(l[at + i..at + i + 4].try_into().unwrap())); + (point(0), point(12), l[27]) + }) + .collect(); + assert!(!segments.is_empty(), "the grid is drawn"); + // How far each piece of the grid is from the middle of the view, and the alpha it is + // drawn with. + let mut pieces: Vec<(f64, u8)> = segments + .iter() + .map(|(a, b, alpha)| { + let mid = [0, 1, 2].map(|i| f64::from((a[i] + b[i]) * 0.5)); + ((mid[0] * mid[0] + mid[1] * mid[1]).sqrt(), *alpha) + }) + .collect(); + pieces.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)); + // The grid in the middle of the view is at full strength. + assert_eq!(pieces.iter().filter(|(d, _)| *d < 1.0).map(|(_, a)| *a).max(), Some(255), "the middle of the grid is at full strength"); + // The further from the middle, the dimmer: the outer half of the grid is fainter than the + // inner half. + let (near, far) = pieces.split_at(pieces.len() / 2); + let mean = |v: &[(f64, u8)]| v.iter().map(|(_, a)| f64::from(*a)).sum::() / v.len().max(1) as f64; + assert!(mean(near) > mean(far) + 10.0, "the grid fades: {} near the middle, {} far from it", mean(near), mean(far)); + // The grid is gone before the distance where it used to stop, so its edge never shows. + let (_, major) = grid_step(app.cam.half_height()); + let cut = (app.cam.half_height() * 3.0 / major).ceil() * major; + let farthest = pieces.last().map(|(d, _)| *d).unwrap_or(0.0); + assert!(farthest < cut, "the grid fades out at {farthest}, short of the cut at {cut}"); + } + + /// #4214: the picture and the window draw the same grid. On a sketch's plane the headless + /// render's grid used to reach further than the viewport's (the picture stretched the grid + /// with the slant, the window did not), so a picture saved from the command line and the + /// window the user sees showed different grids. + #[test] + fn the_picture_and_the_window_draw_the_same_grid_on_a_sketch_plane() { + let rect = Rect::from_min_size(Pos2::ZERO, egui::vec2(800.0, 600.0)); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.run("sketch.create", json!({"plane": "XY"})).unwrap(); + app.ui.perspective = false; + app.cam.fov = 0.0; + app.cam.yaw = 0.0; + app.cam.pitch = 35.0_f64.to_radians(); + app.cam.target = Vec3::ZERO; + app.cam.distance = 100.0; + // The grid's centre, as both draw it: the sketch plane's, round the view's target. + let plane = solidcraft_engine::view::open_sketch_plane(&app.session).unwrap(); + let (_, major) = grid_step(app.cam.half_height()); + let (centre, _, _) = solidcraft_engine::view::sketch_grid_frame(&plane, app.cam.target, major); + // How far the picture's grid reaches from that centre. + let scene = solidcraft_engine::view::scene(&app.session, &app.cam); + let picture = scene.grid.iter().flat_map(|l| l.points.iter()).map(|p| (*p - centre).len()).fold(0.0_f64, f64::max); + // How far the window's grid reaches: the same points, as bytes. + let under = build_sketch_scene(&app, &projection(&app, rect)).under; + let window = under + .as_chunks::<32>() + .0 + .iter() + .flat_map(|l| [&l[0..12], &l[12..24]]) + .map(|b| { + let p = [0, 4, 8].map(|i| f64::from(f32::from_le_bytes(b[i..i + 4].try_into().unwrap()))); + (Vec3::new(p[0], p[1], p[2]) - centre).len() + }) + .fold(0.0_f64, f64::max); + assert!(picture > 0.0, "the picture draws a grid"); + assert!( + (picture - window).abs() <= 1e-3 * picture.max(window), + "the picture's grid reaches {picture} mm from the middle of the view, the window's {window} mm" + ); + } + + /// #4214: the grid fades in the picture as well. The same grid drawn at full strength is + /// much fainter there where the fade has thinned it, and the same in the middle of the view, + /// where the fade leaves the grid alone. Where the picture's far plane cuts the ground, the + /// faded grid is already gone: it fades out instead of ending in a cut. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_grid_fades_out_in_the_picture_instead_of_ending_in_a_cut() { + const SIZE: u32 = 512; + let rect = Rect::from_min_size(Pos2::ZERO, egui::vec2(SIZE as f32, SIZE as f32)); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.ui.show_grid = true; + app.ui.perspective = true; + // A low view of the ground: the far ground is in the picture, where the grid used to end + // in a cut. + app.cam.pitch = 0.25; + app.cam.yaw = 0.0; + app.cam.target = Vec3::ZERO; + app.cam.distance = 100.0; + let proj = projection(&app, rect); + let t = Tokens::get(); + let e = proj.cam.eye().to_f32(); + let eye = [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }]; + let render = |scene: GpuScene| { + crate::gpu::render_offscreen( + scene, + None, + proj.vp.to_f32(), + proj.cam.back().to_f32(), + eye, + SIZE, + None, + [0.0; 8], + crate::gpu::analysis_colors(&t.analysis), + ) + }; + let faded = build_sketch_scene(&app, &proj).merged(); + // The same grid at full strength: every piece of it opaque. + let mut full = faded.clone(); + for piece in full.under.as_chunks_mut::<32>().0 { + piece[27] = 255; + } + let (Some(faded), Some(full)) = (render(faded), render(full)) else { + eprintln!("skipping: no GPU adapter"); + return; + }; + // How far the pixels of each row are from the white the picture was cleared to: the + // grid's lines show. The ink of a row, from the top of the picture. + let row_ink = |img: &[u8]| -> Vec { + (0..SIZE) + .map(|y| { + (0..SIZE) + .map(|x| { + let i = ((y * SIZE + x) * 4) as usize; + img[i..i + 3].iter().map(|c| u64::from(255 - c)).sum::() + }) + .sum::() + }) + .collect() + }; + let (faded_rows, full_rows) = (row_ink(&faded), row_ink(&full)); + // The middle of the view: the grid is drawn there, and the fade leaves it alone. + let middle = SIZE as usize / 2; + assert!(faded_rows[middle] > 0, "the grid is drawn in the middle of the view"); + assert_eq!(faded_rows[middle], full_rows[middle], "the fade leaves the middle of the grid alone"); + // The first row where the grid at full strength shows: the picture's far plane cuts the + // ground there, and the rows above it are the far ground the grid has to fade out in. + let first = full_rows.iter().position(|ink| *ink > 0).expect("the grid is drawn"); + // Where the ground is cut, the faded grid is gone: it fades out instead of ending in a + // cut (#4214). + let band = first.saturating_sub(10)..=first; + let faded_ink: u64 = band.clone().map(|y| faded_rows[y]).sum(); + let full_ink: u64 = band.map(|y| full_rows[y]).sum(); + assert!(full_ink > 0, "the grid shows up to the far plane"); + assert!( + faded_ink * 4 < full_ink, + "the grid still shows at full strength where the far plane cuts the ground: {faded_ink} against {full_ink}" + ); + } + /// An open sketch always has its grid, on its own plane, whatever the Grid switch and the /// follow-the-view preference say; outside a sketch the switch decides. #[test]