SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Viewport: a selected edge's highlight no longer shows as a wedge on a grazing face (#3544)
rbousigues8813b4f6e98c1e
diff --git a/assets/shaders/viewport.wgsl b/assets/shaders/viewport.wgslindex 62c372164b..922fc6b853 100644--- a/assets/shaders/viewport.wgsl+++ b/assets/shaders/viewport.wgsl@@ -482,8 +482,62 @@ struct LOut {@location(1) wp: vec3<f32>,};+/// A normal from its 12-bit octahedral form (`octahedral6` in view.rs); 0 is unknown (zero).+fn octahedral(q: u32) -> vec3<f32> {+ let qx = q & 63u;+ let qy = (q >> 6u) & 63u;+ if (qx == 0u || qy == 0u) { return vec3<f32>(0.0); }+ var x = f32(qx - 1u) / 31.0 - 1.0;+ var y = f32(qy - 1u) / 31.0 - 1.0;+ let z = 1.0 - abs(x) - abs(y);+ if (z < 0.0) {+ let ox = x;+ let oy = y;+ x = (1.0 - abs(oy)) * select(-1.0, 1.0, ox >= 0.0);+ y = (1.0 - abs(ox)) * select(-1.0, 1.0, oy >= 0.0);+ }+ return normalize(vec3<f32>(x, y, z));+}++/// How steeply the faces beside an edge are seen at `p`: the depth a face gains per pixel across+/// the edge, in pixels (tan of the angle between its normal and the view), the larger of the two;+/// 1 when neither is known. Capped, so a face seen exactly edge on does not lift the band far.+fn grazing(p: vec3<f32>, na: vec3<f32>, nb: vec3<f32>) -> f32 {+ var toward = normalize(u.back.xyz);+ if (u.eye.w > 0.5) { toward = normalize(u.eye.xyz - p); }+ var g = 1.0;+ for (var i = 0; i < 2; i++) {+ let n = select(nb, na, i == 0);+ if (dot(n, n) < 0.25) { continue; }+ let d = abs(dot(n, toward));+ g = max(g, sqrt(max(1.0 - d * d, 0.0)) / max(d, 0.02));+ }+ return min(g, 50.0);+}++/// Clip z of the world point `p` (clip position `c`) moved `px` pixels toward the eye: the front+/// of a thin cylinder around an edge, so the band drawn along it is not buried by a face next to+/// the edge seen at a grazing angle. Measured on the screen, it is the same at every zoom.+fn lifted_z(p: vec3<f32>, c: vec4<f32>, px: f32, half: vec2<f32>) -> f32 {+ let b = normalize(u.back.xyz);+ var a = vec3<f32>(0.0, 0.0, 1.0);+ if (abs(b.z) > 0.9) { a = vec3<f32>(1.0, 0.0, 0.0); }+ let side = normalize(cross(b, a));+ let cs = u.vp * vec4<f32>(p + side, 1.0);+ if (cs.w <= 1e-6) { return c.z; }+ // Pixels per millimetre across the view at the point's depth.+ let ppm = length((cs.xy / cs.w - c.xy / c.w) * half);+ if (ppm < 1e-9) { return c.z; }+ var toward = b;+ if (u.eye.w > 0.5) { toward = normalize(u.eye.xyz - p); }+ let q = u.vp * vec4<f32>(p + toward * (px / ppm), 1.0);+ if (q.w <= 1e-6) { return c.z; }+ // The same depth at the original w, so the band stays where it was on the screen.+ return q.z / q.w * c.w;+}+@vertex-fn vs_line(@builtin(vertex_index) vi: u32, @location(0) a: vec3<f32>, @location(1) b: vec3<f32>, @location(2) c: vec4<f32>, @location(3) w: f32) -> LOut {+fn vs_line(@builtin(vertex_index) vi: u32, @location(0) a: vec3<f32>, @location(1) b: vec3<f32>, @location(2) c: vec4<f32>, @location(3) wbits: u32) -> LOut {var pa = a;var pb = b;var ca = u.vp * vec4<f32>(a, 1.0);@@ -518,11 +572,22 @@ fn vs_line(@builtin(vertex_index) vi: u32, @location(0) a: vec3<f32>, @location(// A line thinner than a pixel is drawn a pixel wide, faded by the width it lacks: a narrower// quad covers no pixel centre when it falls between two rows, so without multisampling thin// lines (the grid's) came and went as the view zoomed (#2823).- let wd = max(w, 1.0);+ // The top bit marks a lifted highlight (`GpuScene::lifted_line`, `lifted_width`); a plain+ // line's slot is its width as an f32.+ let lifted = (wbits & 0x80000000u) != 0u;+ var wa = bitcast<f32>(wbits);+ if (lifted) { wa = f32((wbits >> 24u) & 127u) / 8.0; }+ let wd = max(wa, 1.0);let off = nrm * s * wd * 0.5 + dir * (t * 2.0 - 1.0) * wd * 0.5;+ var z = base.z;+ if (lifted && base.w > 1e-6) {+ let p = select(pa, pb, t > 0.5);+ let g = grazing(p, octahedral(wbits & 4095u), octahedral((wbits >> 12u) & 4095u));+ z = lifted_z(p, base, wd * 0.5 * g + 1.0, half);+ }var o: LOut;- o.pos = vec4<f32>(base.xy + off / half * base.w, base.z, base.w);- o.c = vec4<f32>(c.rgb, c.a * (w / wd));+ o.pos = vec4<f32>(base.xy + off / half * base.w, z, base.w);+ o.c = vec4<f32>(c.rgb, c.a * (wa / wd));o.wp = select(pa, pb, t > 0.5);return o;}diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rsindex 940dfe7351..148e1fce47 100644--- a/crates/gpu/src/capture.rs+++ b/crates/gpu/src/capture.rs@@ -170,6 +170,12 @@ impl Capturer {/// `scene` seen by `cam`, `width` × `height` pixels: straight RGBA, rows top to bottom.pub fn rgba(&self, scene: &Scene, cam: &Camera, width: u32, height: u32) -> Result<Vec<u8>> {+ self.rgba_highlighted(scene, None, cam, width, height)+ }++ /// [`Capturer::rgba`] with `highlight` drawn as the viewport draws its highlight scene+ /// (selection and hover feedback), over the model scene.+ pub fn rgba_highlighted(&self, scene: &Scene, highlight: Option<GpuScene>, cam: &Camera, width: u32, height: u32) -> Result<Vec<u8>> {if !(1..=self.max_side).contains(&width) || !(1..=self.max_side).contains(&height) {return Err(GpuError::Render(format!("a picture is 1 to {} pixels a side, not {width} × {height}", self.max_side)));}@@ -187,7 +193,11 @@ impl Capturer {}_ => None,};- let frame = frame(scene, cam, [width, height], state.key, access);+ let mut frame = frame(scene, cam, [width, height], state.key, access);+ if let Some(h) = highlight {+ frame.hl_key = state.key;+ frame.hl_slot = Arc::new(Mutex::new(Some(h)));+ }let (device, queue) = (&self.device, &self.queue);let scopes = error_scopes(device);let size = wgpu::Extent3d { width, height, depth_or_array_layers: 1 };diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rsindex 5126930aa9..42a1059a77 100644--- a/crates/gpu/src/view.rs+++ b/crates/gpu/src/view.rs@@ -27,6 +27,34 @@ pub const LINE_SIZE: usize = 32;/// Placement of an [`InstancedMesh`]: the rows of its rigid move (3 × 4 f32; a point's x, y and z/// are each row's dot product with (p, 1)), then its colour (4 × u8).pub const INSTANCE_SIZE: usize = 52;++/// The width slot of a lifted line ([`GpuScene::lifted_line`]): the top bit set (a plain line's+/// width is a positive `f32`, whose top bit is clear), the width in eighths of a pixel (7 bits,+/// up to 15.9 px), and the two faces' normals in octahedral form (6 bits a component). The+/// shader reads the slot as `u32` so the bits arrive as they are.+pub fn lifted_width(width: f32, normals: [[f32; 3]; 2]) -> u32 {+ let w = if width.is_finite() { (width * 8.0).round().clamp(1.0, 127.0) as u32 } else { 8 };+ let [a, b] = normals.map(octahedral6);+ 0x8000_0000 | (w << 24) | (b << 12) | a+}++/// A unit normal in octahedral form, 6 bits a component (12 bits); a zero or non-finite+/// normal is 0, which reads back as "unknown".+fn octahedral6(n: [f32; 3]) -> u32 {+ let l1 = n[0].abs() + n[1].abs() + n[2].abs();+ if !(l1.is_finite() && l1 > 1e-6) {+ return 0;+ }+ let (mut x, mut y) = (n[0] / l1, n[1] / l1);+ if n[2] < 0.0 {+ let (ox, oy) = (x, y);+ x = (1.0 - oy.abs()) * ox.signum();+ y = (1.0 - ox.abs()) * oy.signum();+ }+ // 1..=63 (0 kept for "unknown"): -1 → 1, 1 → 63.+ let q = |v: f32| ((v.clamp(-1.0, 1.0) + 1.0) * 31.0).round() as u32 + 1;+ (q(y).min(63) << 6) | q(x).min(63)+}/// The shader's `U`: the view-projection matrix, 10 `vec4`s (the tenth carries the ambient/// occlusion radius), the 8 analysis colours, their flags, the depth direction and the two/// whole-body highlight colours (`uniform_bytes`).@@ -489,6 +517,18 @@ impl GpuScene {self.guide_lines.extend_from_slice(&c);self.guide_lines.extend_from_slice(&width.to_le_bytes());}+ /// A thick highlight along an edge (a selected or hovered edge with its halo), lit like a+ /// thin cylinder around it: its depth is pulled toward the eye by its half width times how+ /// steeply the faces beside it are seen (`normals`: theirs along the segment; zero when+ /// unknown), so a face seen at a grazing angle no longer buries part of the band (it showed as+ /// a thin wedge instead of a line). See [`lifted_width`] for how this travels.+ pub fn lifted_line(&mut self, a: [f32; 3], b: [f32; 3], c: [u8; 4], width: f32, normals: [[f32; 3]; 2]) {+ for v in a.iter().chain(&b) {+ self.lines.extend_from_slice(&v.to_le_bytes());+ }+ self.lines.extend_from_slice(&c);+ self.lines.extend_from_slice(&lifted_width(width, normals).to_le_bytes());+ }pub fn line(&mut self, a: [f32; 3], b: [f32; 3], c: [u8; 4], width: f32, on_top: bool) {let out = if on_top { &mut self.overlay } else { &mut self.lines };for v in a.iter().chain(&b) {@@ -1462,7 +1502,7 @@ fn color_layout() -> wgpu::VertexBufferLayout<'static> {}fn line_layout() -> wgpu::VertexBufferLayout<'static> {- const A: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Unorm8x4, 3 => Float32];+ const A: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Unorm8x4, 3 => Uint32];wgpu::VertexBufferLayout { array_stride: LINE_SIZE as u64, step_mode: wgpu::VertexStepMode::Instance, attributes: &A }}diff --git a/crates/gpu/tests/depth.rs b/crates/gpu/tests/depth.rsindex 6bb6bfc1bf..f22848088c 100644--- a/crates/gpu/tests/depth.rs+++ b/crates/gpu/tests/depth.rs@@ -182,6 +182,47 @@ fn an_edge_on_a_face_draws_whole_at_any_angle() {}}+/// A selected edge's highlight (a 3 px core in a 6 px halo, drawn by `GpuScene::lifted_line`+/// in the highlight scene) lying on a face seen almost edge on draws its whole width: the face+/// no longer buries part of the band, which showed as a thin wedge instead of a line. The same+/// band 5 mm behind a face seen square, beside faces seen square, stays hidden.+#[test]+fn a_selected_edge_on_a_grazing_face_draws_whole() {+ let highlight = |a: Vec3, b: Vec3, n: Vec3| {+ let mut sc = solidcraft_gpu::view::GpuScene::default();+ 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 }];+ for (mode, c) in capturers() {+ for tilt in [60.0_f64, 80.0, 85.0, 88.0] {+ let tr = tilt.to_radians();+ let t = tr.tan();+ let n = Vec3::new(0.0, -tr.cos(), tr.sin());+ let (a, b) = (Vec3::new(-12.0, 5.0 * t, 5.0), Vec3::new(12.0, 5.0 * t, 5.0));+ for radius in [30.0, 17_000.0] {+ for fov in [0.0, 0.6] {+ let (plain, cam) = front(sheet(tr), Vec::new(), radius, fov);+ let (top, _) = front(sheet(tr), reference(a, b), radius, fov);+ let shown = pixels(&c.rgba_highlighted(&plain, Some(highlight(a, b, n)), &cam, 200, 200).unwrap()).filter(|p| red(*p)).count();+ let all = red_pixels(c, &top, &cam);+ assert!(all > 100, "{mode}: the band itself ({all} px)");+ assert!(shown * 10 >= all * 9, "{mode} depth, tilt {tilt}°, radius {radius}, fov {fov}: {shown} of {all} px drawn");+ }+ }+ }+ for radius in [30.0, 17_000.0] {+ for fov in [0.0, 0.6] {+ let (a, b) = (Vec3::new(-12.0, 5.0, 5.0), Vec3::new(12.0, 5.0, 5.0));+ let (plain, cam) = front(sheet(0.0), Vec::new(), radius, fov);+ let img = c.rgba_highlighted(&plain, Some(highlight(a, b, Vec3::new(0.0, -1.0, 0.0))), &cam, 200, 200).unwrap();+ let n = pixels(&img).filter(|p| red(*p)).count();+ assert_eq!(n, 0, "{mode} depth, radius {radius}, fov {fov}: the band behind shows in {n} px");+ }+ }+ }+}+/// An edge 0.5 mm behind a face seen square is hidden, however large the design: lines were pulled/// toward the eye by a share of the depth range, about 27 mm in a design 34 m across.#[test]diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rsindex 50b22b114e..76d1f42599 100644--- a/crates/ui-egui/src/viewport.rs+++ b/crates/ui-egui/src/viewport.rs@@ -2283,10 +2283,11 @@ fn mesh_tris(sc: &mut GpuScene, m: &solidcraft_engine::geom::Mesh, col: [u8; 4],/// A highlighted edge: a halo and a core, and where the model hides it, the core dimmed (so a/// pick on the far side still shows).-fn edge_lines(sc: &mut GpuScene, e: &[Vec3], core: Color32, halo: Color32, w: f32) {+fn edge_lines(sc: &mut GpuScene, e: &[Vec3], core: Color32, halo: Color32, w: f32, normals: &[[[f32; 3]; 2]]) {for (col, width) in [(halo, w + 3.0), (core, w)] {- for p in e.windows(2) {- sc.line(p[0].to_f32(), p[1].to_f32(), c4(col), width, false);+ for (i, p) in e.windows(2).enumerate() {+ let n = normals.get(i).copied().unwrap_or_default();+ sc.lifted_line(p[0].to_f32(), p[1].to_f32(), c4(col), width, n);}}for p in e.windows(2) {@@ -2294,6 +2295,34 @@ fn edge_lines(sc: &mut GpuScene, e: &[Vec3], core: Color32, halo: Color32, w: f3}}+/// The normals of the faces beside an edge, for each of its segments (the two most different+/// ones found at the segment's ends; zero where none is found), so its highlight can be lifted+/// over a face seen at a grazing angle (`GpuScene::lifted_line`). One pass over the mesh's+/// vertices: the tessellation shares the edge's points with the faces on either side.+fn edge_normals(m: &solidcraft_engine::geom::Mesh, e: &[Vec3]) -> Vec<[[f32; 3]; 2]> {+ let tol = m.bounds().diagonal().max(1.0) * 1e-7;+ let key = |p: Vec3| ((p.x / tol).round() as i64, (p.y / tol).round() as i64, (p.z / tol).round() as i64);+ let mut at: std::collections::HashMap<(i64, i64, i64), Vec<Vec3>> = e.iter().map(|p| (key(*p), Vec::new())).collect();+ for (p, n) in m.positions.iter().zip(&m.normals) {+ if let Some(list) = at.get_mut(&key(*p))+ && list.len() < 8+ {+ list.push(*n);+ }+ }+ e.windows(2)+ .map(|w| {+ let mut found: Vec<Vec3> = Vec::new();+ for p in w {+ found.extend(at.get(&key(*p)).into_iter().flatten().copied());+ }+ let Some(first) = found.first().copied() else { return [[0.0; 3]; 2] };+ let other = found.iter().copied().min_by(|a, b| a.dot(first).total_cmp(&b.dot(first))).unwrap_or(first);+ [first.to_f32(), other.to_f32()]+ })+ .collect()+}+/// The outline of a highlighted face where the model hides it (dimmed).fn hidden_face_outline(sc: &mut GpuScene, m: &solidcraft_engine::geom::Mesh, face: usize, col: Color32) {for (ei, e) in m.edges.iter().enumerate() {@@ -2676,9 +2705,11 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene {Sel::Edge { body, index, point } => {if let Some(b) = st.body(body)&& app.session.body_visible(body)- && let Some(e) = edge_of(&drawn_mesh(app, b), *index, *point){- edge_lines(&mut feedback, e, t.sel_edge, t.sel_edge_rim, 3.0);+ let m = drawn_mesh(app, b);+ if let Some(e) = edge_of(&m, *index, *point) {+ edge_lines(&mut feedback, e, t.sel_edge, t.sel_edge_rim, 3.0, &edge_normals(&m, e));+ }}}Sel::Profile { sketch, index } => profile_fill(&mut feedback, app, *sketch, *index, t.sel_profile, t.sel_profile_edge),@@ -2779,7 +2810,7 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene {}for (ei, e) in m.edges.iter().enumerate() {if m.edge_pickable(ei) && (whole || m.edge_faces.get(ei).is_some_and(|fs| fs.iter().any(|f| faces.contains(&(*f as usize))))) {- edge_lines(&mut feedback, e, t.hover_edge, t.hover_edge_halo, 1.5);+ edge_lines(&mut feedback, e, t.hover_edge, t.hover_edge_halo, 1.5, &[]);}}}@@ -2819,7 +2850,7 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene {if let Some(p) = m.edges.get(e)&& m.edge_pickable(e){- edge_lines(&mut feedback, p, t.hover_edge, t.hover_edge_halo, 1.5);+ edge_lines(&mut feedback, p, t.hover_edge, t.hover_edge_halo, 1.5, &[]);}}}@@ -2831,7 +2862,7 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene {for i in m.circular_rim(*index) {let selected = sel.iter().any(|x| matches!(x, Sel::Edge { body: b, index: j, .. } if b == body && *j == i));if !selected && let Some(e) = if i == *index { edge_of(&m, i, *mid) } else { m.edges.get(i) } {- edge_lines(&mut feedback, e, t.hover_edge, t.hover_edge_halo, 2.0);+ edge_lines(&mut feedback, e, t.hover_edge, t.hover_edge_halo, 2.0, &edge_normals(&m, e));}}}