SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Section Analysis: dragging the cut stays smooth on large parts (#3616)
kaltenbrunnermarkus266851807921
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex 3ede07560f..7c5e24363b 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -1543,6 +1543,31 @@ fn section_analysis() {assert_eq!(s.undo.len(), undo);}+/// A section index finds the same cut segments, in the same order, as cutting every triangle:+/// tilted and axis normals, cuts through vertices, at the ends and beyond the part.+#[test]+fn section_index_cuts_like_every_triangle() {+ let mut s = Session::default();+ run(&mut s, "solid.cylinder", json!({"radius": 12, "height": 30}));+ run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 8, "operation": "join"}));+ let st = s.model.state();+ let m = st.bodies.first().unwrap().mesh();+ assert!(m.triangles.len() > 64, "enough triangles for several slabs: {}", m.triangles.len());+ for n in [Vec3::Z, -Vec3::Y, Vec3::new(1.0, 2.0, 3.0).normalized().unwrap(), Vec3::new(-0.3, 0.1, 0.9).normalized().unwrap()] {+ let index = view::SectionIndex::new(&m, n);+ let heights: Vec<f64> = m.positions.iter().map(|p| n.dot(*p)).collect();+ let (lo, hi) = heights.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), h| (a.min(*h), b.max(*h)));+ let mut cuts: Vec<f64> = (0..=40).map(|k| lo - 1.0 + (hi - lo + 2.0) * k as f64 / 40.0).collect();+ cuts.extend(heights.iter().step_by(7).copied());+ cuts.extend([lo, hi]);+ for at in cuts {+ let o = n * at;+ let segments = view::section_segments(&m, o, n);+ assert_eq!(index.segments(&m, o), segments, "{n:?} at {at}");+ }+ }+}+/// Press Pull: positive pulls a face out, negative pushes it in (a cut), edges get a fillet.#[test]fn press_pull() {diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rsindex 4ce7ec792e..64863cc01e 100644--- a/crates/engine/src/view.rs+++ b/crates/engine/src/view.rs@@ -544,23 +544,102 @@ fn build_scene(/// Where the plane through `o` with normal `n` cuts a mesh: one segment per crossed triangle,/// nudged a hair to the kept side (so the clip leaves them drawn).pub fn section_segments(m: &solidcraft_geom::Mesh, o: Vec3, n: Vec3) -> Vec<(Vec3, Vec3)> {- let eps = 1e-4 * (1.0 + m.bounds().diagonal());+ let eps = section_nudge(m);let mut out = Vec::new();for t in &m.triangles {- let Some(p) = m.tri(t) else { continue };- let d = p.map(|q| n.dot(q - o));- let mut pts = Vec::with_capacity(2);- for (i, j) in [(0, 1), (1, 2), (2, 0)] {- if (d[i] < 0.0) != (d[j] < 0.0) {- let s = d[i] / (d[i] - d[j]);- pts.push(p[i] + (p[j] - p[i]) * s - n * eps);+ cut_triangle(m, t, o, n, eps, &mut out);+ }+ out+}++/// How far [`section_segments`] nudges the cut to the kept side.+fn section_nudge(m: &solidcraft_geom::Mesh) -> f64 {+ 1e-4 * (1.0 + m.bounds().diagonal())+}++/// The segment where the plane through `o` with normal `n` crosses triangle `t`, if it does.+fn cut_triangle(m: &solidcraft_geom::Mesh, t: &[u32; 3], o: Vec3, n: Vec3, eps: f64, out: &mut Vec<(Vec3, Vec3)>) {+ let Some(p) = m.tri(t) else { return };+ let d = p.map(|q| n.dot(q - o));+ let mut pts = Vec::with_capacity(2);+ for (i, j) in [(0, 1), (1, 2), (2, 0)] {+ if (d[i] < 0.0) != (d[j] < 0.0) {+ let s = d[i] / (d[i] - d[j]);+ pts.push(p[i] + (p[j] - p[i]) * s - n * eps);+ }+ }+ if let [a, b] = pts[..] {+ out.push((a, b));+ }+}++/// A mesh's triangles sorted into slabs along one normal, so cuts with that normal at any+/// height look only at the triangles of one slab: dragging a Section Analysis keeps the normal+/// and moves the cut, and an imported part can have millions of triangles. The same segments+/// as [`section_segments`].+pub struct SectionIndex {+ normal: Vec3,+ /// The lowest height (`normal · p`) of the mesh, and the slab thickness.+ start: f64,+ step: f64,+ /// Per slab, the triangles whose heights reach into it.+ slabs: Vec<Vec<u32>>,+ eps: f64,+}++/// Slabs a [`SectionIndex`] makes, at most.+const SECTION_SLABS: usize = 4096;++impl SectionIndex {+ pub fn new(m: &solidcraft_geom::Mesh, normal: Vec3) -> SectionIndex {+ let heights: Vec<Option<(f64, f64)>> = m+ .triangles+ .iter()+ .map(|t| {+ let d = m.tri(t)?.map(|q| normal.dot(q));+ Some((d[0].min(d[1]).min(d[2]), d[0].max(d[1]).max(d[2])))+ })+ .collect();+ let (lo, hi) = heights.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), (l, h)| (a.min(*l), b.max(*h)));+ let count = if lo.is_finite() && hi.is_finite() { (m.triangles.len() / 64).clamp(1, SECTION_SLABS) } else { 0 };+ let step = if count > 0 && hi > lo { (hi - lo) / count as f64 } else { 1.0 };+ let mut index = SectionIndex { normal, start: lo, step, slabs: vec![Vec::new(); count], eps: section_nudge(m) };+ for (i, h) in heights.iter().enumerate() {+ let (Some((l, h)), Ok(i)) = (h, u32::try_from(i)) else { continue };+ for k in index.slab(*l)..=index.slab(*h) {+ if let Some(slab) = index.slabs.get_mut(k) {+ slab.push(i);+ }}}- if let [a, b] = pts[..] {- out.push((a, b));+ index+ }++ /// The normal this index was made for.+ pub fn normal(&self) -> Vec3 {+ self.normal+ }++ fn slab(&self, height: f64) -> usize {+ let k = ((height - self.start) / self.step).floor();+ if k.is_finite() { (k.max(0.0) as usize).min(self.slabs.len().saturating_sub(1)) } else { 0 }+ }++ /// [`section_segments`] of `m` (the mesh this index was made from) at the plane through+ /// `o` with this index's normal.+ pub fn segments(&self, m: &solidcraft_geom::Mesh, o: Vec3) -> Vec<(Vec3, Vec3)> {+ let mut out = Vec::new();+ let at = self.normal.dot(o);+ if self.slabs.is_empty() || !at.is_finite() || at < self.start {+ return out;+ }+ for i in self.slabs.get(self.slab(at)).into_iter().flatten() {+ if let Some(t) = m.triangles.get(*i as usize) {+ cut_triangle(m, t, o, self.normal, self.eps, &mut out);+ }}+ out}- out}/// Is a sketch drawn? The active one is; others unless hidden. Finished sketches are hiddendiff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 5e874f3de0..911dbea681 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -1391,6 +1391,36 @@ pub(crate) fn take_snap_work() -> (usize, usize) {mod face_snap_tests {use super::*;+ /// A planar face's plane is found once per model state: an open Section Analysis on a face+ /// asks for it several times a frame, and each lookup tessellates the body.+ #[test]+ fn a_planar_face_is_looked_up_once_per_model_state() {+ let mut s = Session::default();+ s.execute("solid.box", &json!({"length":40,"width":30,"height":20})).unwrap();+ let top = |s: &Session| {+ let st = s.world_state();+ let b = st.bodies.first().unwrap();+ let faces = b.body.faces(1e-3).unwrap();+ let f = faces.iter().max_by(|a, b| a.centroid.z.total_cmp(&b.centroid.z)).unwrap();+ (b.name.clone(), f.index)+ };+ let (body, face) = top(&s);+ take_snap_work();+ let first = planar_face(&s, &body, face).expect("the top face is planar");+ for _ in 0..5 {+ assert_eq!(planar_face(&s, &body, face), Some(first));+ }+ assert_eq!(take_snap_work().0, 1, "the same model state looks the face up once");+ assert!((first.0.z - 20.0).abs() < 1e-9 && (first.1 - Vec3::Z).len() < 1e-9, "{first:?}");++ // A changed model is looked at again.+ s.execute("solid.box", &json!({"length":10,"width":10,"height":50,"operation":"join"})).unwrap();+ let (body, face) = top(&s);+ let again = planar_face(&s, &body, face).expect("the new top face is planar");+ assert_eq!(take_snap_work().0, 1);+ assert!((again.0.z - 50.0).abs() < 1e-9, "{again:?}");+ }+#[test]fn a_point_more_than_a_micrometre_off_a_sliver_is_off_the_face() {// A triangle with half-micrometre legs. Points 2 µm below its lower side and 1.6 µm past@@ -1443,13 +1473,42 @@ fn profiles_used(s: &Session, sketch: u64) -> bool {/// The plane of a planar body face: (point on it, unit normal).pub fn planar_face(s: &Session, body: &str, face: usize) -> Option<(Vec3, Vec3)> {+ let st = s.world_state();+ let known = FACE_PLANES.with(|c| {+ let c = c.borrow();+ c.0.as_ref().filter(|k| std::sync::Arc::ptr_eq(k, &st)).and_then(|_| c.1.iter().find(|(b, f, _)| b == body && *f == face).map(|x| x.2))+ });+ if let Some(found) = known {+ return found;+ }#[cfg(test)]SNAP_WORK.with(|w| w.set((w.get().0 + 1, w.get().1)));- let st = s.world_state();- let b = st.body(body)?;- let tol = (b.body.size() * 1e-3).max(1e-3);- let f = b.body.faces(tol).ok()?.into_iter().find(|f| f.index == face)?;- Some((f.centroid, f.plane_normal?))+ let found = st.body(body).and_then(|b| {+ let tol = (b.body.size() * 1e-3).max(1e-3);+ let f = b.body.faces(tol).ok()?.into_iter().find(|f| f.index == face)?;+ Some((f.centroid, f.plane_normal?))+ });+ FACE_PLANES.with(|c| {+ let mut c = c.borrow_mut();+ if !c.0.as_ref().is_some_and(|k| std::sync::Arc::ptr_eq(k, &st)) {+ *c = (Some(st.clone()), Vec::new());+ }+ if c.1.len() >= 8 {+ c.1.remove(0);+ }+ c.1.push((body.to_string(), face, found));+ });+ found+}++thread_local! {+ /// The planar faces looked up last, with the model state they were found in (kept, so the+ /// pointer stays its own). Each lookup tessellates the whole body, about 0.1 s for an+ /// imported part of a few million triangles, and an open Section Analysis on a face asks+ /// for its plane several times a frame.+ #[allow(clippy::type_complexity)]+ static FACE_PLANES: std::cell::RefCell<(Option<std::sync::Arc<solidcraft_engine::doc::ModelState>>, Vec<(String, usize, Option<(Vec3, Vec3)>)>)> =+ const { std::cell::RefCell::new((None, Vec::new())) };}fn polyline_mid(pts: &[Vec3]) -> Vec3 {diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rsindex 61d18726fc..1a8942798c 100644--- a/crates/ui-egui/src/viewport.rs+++ b/crates/ui-egui/src/viewport.rs@@ -62,6 +62,9 @@ pub struct ViewportState {lod_view: u64,/// Each body mesh's box (the mesh held, so its address stays its own), from the last state.mesh_bounds: std::sync::Mutex<std::collections::HashMap<usize, (std::sync::Arc<solidcraft_engine::geom::Mesh>, solidcraft_engine::geom::Aabb3)>>,+ /// Each shown body mesh's section index for the cut's normal (the mesh held, so its address+ /// stays its own): a Section Analysis dragged along its normal cuts through it.+ section_index: std::sync::Mutex<Vec<(std::sync::Arc<solidcraft_engine::geom::Mesh>, std::sync::Arc<solidcraft_engine::view::SectionIndex>)>>,/// Each body mesh's picking index (made the first time a pick reaches the body), kept while/// the mesh is part of the world state.pub(crate) pick_index: crate::pick_index::PickIndexes,@@ -711,10 +714,21 @@ fn build_scene(app: &SolveApp) -> GpuScene {// Section: the outline of each body where the plane cuts it.if let Some((o, n)) = section_plane(app) {let col = c4(tk.text.gamma_multiply(0.9));+ let mut kept = app.viewport.section_index.lock().map(|mut k| std::mem::take(&mut *k)).unwrap_or_default();+ let mut made = Vec::new();for b in st.bodies.iter().filter(|b| app.session.body_visible(&b.name)) {- for (a, c) in solidcraft_engine::view::section_segments(&b.mesh(), o, n) {+ let mesh = b.mesh();+ let index = match kept.iter().position(|(m, i)| std::sync::Arc::ptr_eq(m, &mesh) && i.normal() == n) {+ Some(k) => kept.swap_remove(k).1,+ None => std::sync::Arc::new(solidcraft_engine::view::SectionIndex::new(&mesh, n)),+ };+ for (a, c) in index.segments(&mesh, o) {sc.line(a.to_f32(), c.to_f32(), col, 1.8, false);}+ made.push((mesh, index));+ }+ if let Ok(mut k) = app.viewport.section_index.lock() {+ *k = made;}}// Continuity analysis: each seam `inspect.continuity` measured, drawn over the model in the