SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
fix: a face-centre joint origin stays put when a hole in its face moves or goes (#6370)
NOWN-DEVb8d9db74400c
diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rsindex 425d7b504e..08b2923d34 100644--- a/crates/doc/src/joints.rs+++ b/crates/doc/src/joints.rs@@ -767,26 +767,33 @@ fn named_pick(doc: &Document, st: &ModelState, pick: Vec3, face: Option<&str>) -}}-/// The centre and outward normal of the planar face nearest `pick` (component coordinates; a-/// body moved in from another component placed by its offset, as a named face is).+/// The centre (the middle of its outline, `face::outline_centre`) and outward normal of the+/// planar face nearest `pick` (component coordinates; a body moved in from another component+/// placed by its offset, as a named face is).fn nearest_plane(doc: &Document, st: &ModelState, o: &JointOrigin, pick: Vec3) -> Result<(Vec3, Vec3)> {let comp = component_of(doc, o.occurrence)?;- let mut best: Option<(f64, Vec3, Vec3)> = None;+ let mut best: Option<(f64, &crate::ModelBody, solidcraft_kernel::FaceInfo, Vec3)> = None;for b in component_bodies(doc, st, comp) {let offset = doc.model_body_offset(b);for f in b.joint_faces()?.iter() {- let Some(n) = f.plane_normal else { continue };+ let Some(own) = f.plane_normal else { continue };let (c, n) = match offset {- Some(m) => (apply_point(m, f.centroid), apply_vector(m, n)),- None => (f.centroid, n),+ Some(m) => (apply_point(m, f.centroid), apply_vector(m, own)),+ None => (f.centroid, own),};let d = (pick - c).dot(n).abs() + 1e-3 * (pick - c).len();- if best.as_ref().is_none_or(|(bd, _, _)| d < *bd) {- best = Some((d, c, n));+ if best.as_ref().is_none_or(|(bd, ..)| d < *bd) {+ best = Some((d, b, f.clone(), own));}}}- best.map(|(_, c, n)| (c, n)).ok_or_else(|| DocError::Invalid("joint origin: no planar face there".into()))+ let (_, b, f, n) = best.ok_or_else(|| DocError::Invalid("joint origin: no planar face there".into()))?;+ // The face's middle: its outline's on a face with holes.+ let c = face::outline_centre(&b.mesh(), f.index, f.centroid, n).unwrap_or(f.centroid);+ Ok(match doc.model_body_offset(b) {+ Some(m) => (apply_point(m, c), apply_vector(m, n)),+ None => (c, n),+ })}/// Resolve a joint origin to a frame in its component's coordinates.diff --git a/crates/doc/src/joints_face.rs b/crates/doc/src/joints_face.rsindex a61e5b86a2..6fbb663361 100644--- a/crates/doc/src/joints_face.rs+++ b/crates/doc/src/joints_face.rs@@ -4,9 +4,9 @@//! A round origin's end is kept by the name of the face across the rim at that end, so it is the//! same end after the design changes; an x reference keeps the origin's turn about its axis.-use std::collections::BTreeMap;+use std::collections::{BTreeMap, BTreeSet};-use solidcraft_geom::Vec3;+use solidcraft_geom::{Loop2, Mesh, Plane, Ring, Vec2, Vec3};use solidcraft_kernel::CylinderFace;use super::{Snap, XRef, component_bodies};@@ -62,13 +62,65 @@ impl NamedFace<'_> {self.own_cylinder().map(|c| placed(&self.offset, c))}- /// The face's centre and outward normal (the component's coordinates), when it is planar.+ /// The face's centre (the middle of its outline, `outline_centre`) and outward normal (the+ /// component's coordinates), when it is planar.pub fn plane(&self) -> Result<Option<(Vec3, Vec3)>> {let faces = self.body.joint_faces()?;- Ok(faces.get(self.face).and_then(|f| f.plane_normal.map(|n| (apply_point(&self.offset, f.centroid), apply_vector(&self.offset, n)))))+ Ok(faces.get(self.face).and_then(|f| {+ let n = f.plane_normal?;+ let c = outline_centre(&self.body.mesh(), self.face, f.centroid, n).unwrap_or(f.centroid);+ Some((apply_point(&self.offset, c), apply_vector(&self.offset, n)))+ }))}}+/// The middle of the area the outer boundary of planar face `face` encloses (the body's own+/// coordinates; `centroid` and `n` are the face's), for a face with holes: a hole cut into the+/// face, moved or suppressed changes the face's centroid but not its outline, so a joint at the+/// face's centre stays where it is. `None` for a face without holes (its centroid is that middle+/// already) and for one whose mesh gives no clean outline (the caller keeps the centroid).+pub(super) fn outline_centre(mesh: &Mesh, face: usize, centroid: Vec3, n: Vec3) -> Option<Vec3> {+ let plane = Plane::from_normal(centroid, n)?;+ let tris: Vec<[Vec3; 3]> =+ mesh.triangles.iter().zip(&mesh.tri_face).filter(|(_, f)| **f as usize == face).filter_map(|(t, _)| mesh.tri(t)).collect();+ // The face's triangles need not share vertex indices: their corners are matched by place.+ let size = tris.iter().flatten().fold(0.0_f64, |m, p| m.max(p.x.abs()).max(p.y.abs()).max(p.z.abs()));+ let q = (size * 1e-9).max(1e-12);+ let key = |p: Vec3| ((p.x / q).round() as i64, (p.y / q).round() as i64, (p.z / q).round() as i64);+ let sides: BTreeMap<_, Vec3> = tris.iter().flat_map(|[a, b, c]| [(a, b), (b, c), (c, a)]).map(|(a, b)| ((key(*a), key(*b)), *b)).collect();+ // The outline: the sides no other triangle of the face runs back along, by the corner each+ // starts at (a corner starting two is where loops touch: no clean outline).+ let mut next = BTreeMap::new();+ for ((a, b), p) in &sides {+ if a != b && !sides.contains_key(&(*b, *a)) && next.insert(*a, (*b, *p)).is_some() {+ return None;+ }+ }+ // Chained into loops (the face's plane coordinates); one that doesn't close is no outline.+ let (mut loops, mut seen): (Vec<Ring<Vec2>>, BTreeSet<_>) = (Vec::new(), BTreeSet::new());+ for start in next.keys() {+ let (mut at, mut ring) = (*start, Vec::new());+ while seen.insert(at) {+ let (to, p) = next.get(&at)?;+ ring.push(plane.to_local(*p));+ at = *to;+ }+ if ring.is_empty() {+ continue;+ }+ if at != *start {+ return None;+ }+ loops.push(Ring::new(ring));+ }+ if loops.len() < 2 {+ return None;+ }+ // The outer boundary encloses the most area.+ let outer = loops.iter().max_by(|a, b| a.signed_area().abs().total_cmp(&b.signed_area().abs()))?;+ (outer.signed_area().abs() > q * q).then(|| plane.to_world(Loop2::polygon(outer).centroid()))+}+/// A cylinder of a body's own coordinates placed by the body's (rigid) offset.pub(super) fn placed(m: &Mat, c: CylinderFace) -> CylinderFace {CylinderFace { axis_point: apply_point(m, c.axis_point), axis: apply_vector(m, *c.axis).unit().unwrap_or(c.axis), ..c }diff --git a/crates/engine/src/cmd/joints_face_tests.rs b/crates/engine/src/cmd/joints_face_tests.rsindex 7aa1840e1b..07027a6d21 100644--- a/crates/engine/src/cmd/joints_face_tests.rs+++ b/crates/engine/src/cmd/joints_face_tests.rs@@ -363,3 +363,38 @@ fn a_round_origin_keeps_its_end_when_the_face_it_opens_onto_gets_other_neighbourlet (z, dz) = top(&s).unwrap_or_default();assert!((z - 4.0).abs() < 1e-9 && (dz - 1.0).abs() < 1e-9, "{z} {dz}");}++#[test]+fn a_face_centre_stays_put_when_a_hole_in_its_face_moves_or_goes() {+ // A 200 x 100 plate with a 20 mm hole at `HX` in its top face, and an origin at the top+ // face's centre, by the face's name and by a point alone. Moving the hole or suppressing it+ // changes the face's area, not its outline: the origin stays at the outline's middle.+ let mut s = Session::default();+ run(&mut s, "parameters.change", json!({"name": "HX", "expression": "60 mm"}));+ run(&mut s, "component.create", json!({"name": "Plate"}));+ run(&mut s, "solid.box", json!({"length": 200, "width": 100, "height": 2, "corner": [0, 0, 0]}));+ run(&mut s, "solid.hole", json!({"position": ["HX", 50, 2], "diameter": 20, "name": "H"}));+ let pick = Vec3::new(150.0, 80.0, 2.0);+ let top = face_name(&mut s, "Plate", pick);+ run(&mut s, "joint.origin", json!({"name": "Top", "face": top}));+ let by_point = |s: &Session| {+ let o = solidcraft_doc::joints::JointOrigin { occurrence: occ(s, "Plate"), snap: Snap::FaceCenter { pick, face: None, x: None } };+ let m = solidcraft_doc::joints::resolve_origin(&s.doc, &s.model.state(), &o).ok()?;+ Some((Vec3::new(m[3][0], m[3][1], m[3][2]), Vec3::new(m[2][0], m[2][1], m[2][2])))+ };+ let mut seen = vec![(origin_frame(&s, "Top"), by_point(&s))];+ for (cmd, p) in [+ ("parameters.change", json!({"name": "HX", "expression": "80 mm"})),+ ("timeline.suppress", json!({"feature": "H", "suppressed": true})),+ ("parameters.change", json!({"name": "HX", "expression": "40 mm"})),+ ("timeline.suppress", json!({"feature": "H", "suppressed": false})),+ ] {+ run(&mut s, cmd, p);+ seen.push((origin_frame(&s, "Top"), by_point(&s)));+ }+ for (i, f) in seen.iter().enumerate() {+ for (o, z) in [f.0, f.1].map(|f| f.unwrap_or((Vec3::ZERO, Vec3::ZERO))) {+ assert!(near(o, Vec3::new(100.0, 50.0, 2.0)) && near(z, Vec3::Z), "step {i}: {f:?}");+ }+ }+}