SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Joint origins: resolve by the named face, keep a hole's end and the turn (#2186) (#2187)
NOWN-DEV8313c3468add
diff --git a/crates/doc/src/format/pending/joint-origin-faces.rs b/crates/doc/src/format/pending/joint-origin-faces.rsnew file mode 100644index 0000000000..ab4b305629--- /dev/null+++ b/crates/doc/src/format/pending/joint-origin-faces.rs@@ -0,0 +1,8 @@+//! A face-centre or circle-centre joint origin can carry `x`: what turns its frame about z (a+//! direction, `[x, y, z]`, or `{face, pick?}`: a face by its persistent name), and a+//! circle-centre one `end`: the name of the face across the rim at the end it takes, so a part+//! stays on the same side of a hole when the design changes. A named face is now resolved by its+//! own plane or cylinder rather than the face nearest the pick. Older designs need no+//! transformation: an origin without `end` takes the end nearer its pick, and one without `x`+//! any direction square to z, as before; 0.14.x asks for an update instead of dropping a saved+//! end or turn.diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rsindex c8fae80a38..b126301e2f 100644--- a/crates/doc/src/joints.rs+++ b/crates/doc/src/joints.rs@@ -36,18 +36,31 @@ pub enum Snap {x: Option<Vec3>,},/// The centre of the planar face nearest `pick`, z along its outward normal. `face` is the- /// face's persistent name (found first).+ /// face's persistent name: when it names a planar face, that face's own plane and centre are+ /// taken (the pick only tells the pieces of a split face apart).FaceCenter {pick: Vec3,#[serde(default, skip_serializing_if = "Option::is_none")]face: Option<String>,+ /// What turns the frame about z (default: any direction square to z).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ x: Option<XRef>,},- /// The centre of the circular end nearest `pick` of the cylindrical face there, z along its- /// axis (pointing out of the face's end).+ /// The centre of a circular end of the cylindrical face at `pick`, z along its axis+ /// (pointing out of the face's end). `face` is the face's persistent name: when it names a+ /// cylindrical face, that face's own axis, radius and extent are taken. `end` is the name of+ /// the face across the rim at the chosen end (the plate's face a hole opens onto), so the+ /// end stays the same when the design changes; without it (or when neither end has that+ /// face any more), the end nearer `pick` along the axis.CircleCenter {pick: Vec3,#[serde(default, skip_serializing_if = "Option::is_none")]face: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ end: Option<String>,+ /// What turns the frame about z (default: any direction square to z).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ x: Option<XRef>,},/// A point, z along `z` (default +Z).Point {@@ -57,6 +70,76 @@ pub enum Snap {},}+/// What sets a joint origin's x axis (its turn about z): a direction, or a face found by its+/// persistent name, so a round origin keeps its turn when the design changes.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(untagged)]+pub enum XRef {+ /// A direction (component coordinates); its part square to z is taken.+ Dir(Vec3),+ /// A face: a plane's outward normal, a cylinder's way from the origin to its axis (another+ /// hole), any other face's way from the origin to the point of it nearest `pick` (component+ /// coordinates; it also tells the pieces of a split face apart, default the origin).+ Face {+ face: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pick: Option<Vec3>,+ },+}++impl Snap {+ /// The persistent face names the snap refers to (its face, its end's, its x reference's).+ pub fn face_names(&self) -> Vec<&String> {+ let mut out = Vec::new();+ if let Snap::FaceCenter { face, x, .. } | Snap::CircleCenter { face, x, .. } = self {+ out.extend(face.iter());+ if let Some(XRef::Face { face, .. }) = x {+ out.push(face);+ }+ }+ if let Snap::CircleCenter { end: Some(end), .. } = self {+ out.push(end);+ }+ out+ }++ /// [`Snap::face_names`], to rewrite them (a copied component's faces have new names).+ pub fn face_names_mut(&mut self) -> Vec<&mut String> {+ let mut out = Vec::new();+ match self {+ Snap::FaceCenter { face, x, .. } => {+ out.extend(face.iter_mut());+ if let Some(XRef::Face { face, .. }) = x {+ out.push(face);+ }+ }+ Snap::CircleCenter { face, end, x, .. } => {+ out.extend(face.iter_mut());+ out.extend(end.iter_mut());+ if let Some(XRef::Face { face, .. }) = x {+ out.push(face);+ }+ }+ _ => {}+ }+ out+ }++ /// Whether every point and direction in the snap is finite.+ pub fn is_finite(&self) -> bool {+ let x_ok = |x: &Option<XRef>| match x {+ Some(XRef::Dir(d)) => d.is_finite(),+ Some(XRef::Face { pick, .. }) => pick.is_none_or(|p| p.is_finite()),+ None => true,+ };+ match self {+ Snap::Frame { origin, z, x } => origin.is_finite() && z.is_finite() && x.is_none_or(|x| x.is_finite()),+ Snap::FaceCenter { pick, x, .. } | Snap::CircleCenter { pick, x, .. } => pick.is_finite() && x_ok(x),+ Snap::Point { point, z } => point.is_finite() && z.is_none_or(|z| z.is_finite()),+ }+ }+}+/// A joint origin: a snap on an occurrence's component (occurrence 0 = the root design).#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]pub struct JointOrigin {@@ -257,7 +340,7 @@ fn size_of(doc: &Document, st: &ModelState, s: &Size) -> Result<f64> {let v = match s {Size::Length(v) => *v,Size::Expr(e) => doc.eval(e, crate::expr::Kind::Length)?,- Size::Circle(o) => circle_at(doc, st, o)?.1.radius,+ Size::Circle(o) => circle_at(doc, st, o)?.radius,};if v.is_finite() && v > 1e-9 && v <= MAX_SIZE {Ok(v)@@ -385,58 +468,84 @@ fn component_of(doc: &Document, occ: u64) -> Result<u64> {doc.occurrences.iter().find(|o| o.id == occ).map(|o| o.component).ok_or_else(|| DocError::Unknown(format!("occurrence {occ}")))}-/// Resolve a joint origin to a frame in its component's coordinates./// A snap's pick point moved onto its named face (an error when the face is gone: a joint must/// not quietly attach elsewhere).-fn named_pick(st: &ModelState, pick: Vec3, face: Option<&str>) -> Result<Vec3> {+fn named_pick(doc: &Document, st: &ModelState, pick: Vec3, face: Option<&str>) -> Result<Vec3> {match face {- Some(n) => crate::naming::point_on_face(st, n, pick)- .map(|(q, _)| q)- .ok_or_else(|| DocError::Invalid(format!("joint origin: the face `{n}` no longer exists (edit the joint to pick again)"))),+ Some(n) => face::named_face(doc, st, pick, n).map(|f| f.point),None => Ok(pick),}}+/// 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).+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;+ for b in component_bodies(doc, st, comp) {+ let offset = doc.model_body_offset(b);+ let tol = (b.body.size() * 2e-3).max(1e-3);+ for f in b.body.faces(tol)? {+ let Some(n) = 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),+ };+ 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));+ }+ }+ }+ best.map(|(_, c, n)| (c, n)).ok_or_else(|| DocError::Invalid("joint origin: no planar face there".into()))+}++/// Resolve a joint origin to a frame in its component's coordinates.pub fn resolve_origin(doc: &Document, st: &ModelState, o: &JointOrigin) -> Result<Mat> {let bad = || DocError::Invalid("joint origin: degenerate frame".into());match &o.snap {Snap::Frame { origin, z, x } => frame(*origin, *z, *x).ok_or_else(bad),Snap::Point { point, z } => frame(*point, z.unwrap_or(Vec3::Z), None).ok_or_else(bad),- Snap::FaceCenter { pick, face } => {- let pick = &named_pick(st, *pick, face.as_deref())?;- let comp = component_of(doc, o.occurrence)?;- let mut best: Option<(f64, Vec3, Vec3)> = None;- for b in component_bodies(doc, st, comp) {- let tol = (b.body.size() * 2e-3).max(1e-3);- for f in b.body.faces(tol)? {- let Some(n) = f.plane_normal else { continue };- let d = (*pick - f.centroid).dot(n).abs() + 1e-3 * (*pick - f.centroid).len();- if best.as_ref().is_none_or(|(bd, _, _)| d < *bd) {- best = Some((d, f.centroid, n));- }- }- }- let (_, c, n) = best.ok_or_else(|| DocError::Invalid("joint origin: no planar face there".into()))?;- frame(c, n, None).ok_or_else(bad)+ Snap::FaceCenter { pick, face, x } => {+ // A named planar face gives its own centre and normal; another face (or none) the+ // planar face nearest the point.+ let named = match face.as_deref() {+ Some(n) => Some(face::named_face(doc, st, *pick, n)?),+ None => None,+ };+ let (c, n) = match named.as_ref().map(face::NamedFace::plane).transpose()?.flatten() {+ Some(cn) => cn,+ None => nearest_plane(doc, st, o, named.as_ref().map_or(*pick, |f| f.point))?,+ };+ frame(c, n, face::x_axis(doc, st, x.as_ref(), c)?).ok_or_else(bad)}- Snap::CircleCenter { .. } => {- let (pick, cyl) = circle_at(doc, st, o)?;- let s = (pick - cyl.axis_point).dot(cyl.axis);- let (at, dir) = if (s - cyl.start).abs() <= (cyl.end - s).abs() { (cyl.start, -1.0) } else { (cyl.end, 1.0) };- frame(cyl.axis_point + cyl.axis * at, cyl.axis * dir, None).ok_or_else(bad)+ Snap::CircleCenter { x, .. } => {+ let r = round_of(doc, st, o)?;+ frame(r.centre, r.z, face::x_axis(doc, st, x.as_ref(), r.centre)?).ok_or_else(bad)}}}-/// The pick of a circle-centre snap (on its named face) and the cylindrical face there-/// (component coordinates). Any other snap is refused.-fn circle_at(doc: &Document, st: &ModelState, o: &JointOrigin) -> Result<(Vec3, solidcraft_kernel::CylinderFace)> {- let Snap::CircleCenter { pick, face } = &o.snap else { return Err(DocError::Invalid("pick a round face".into())) };- let pick = named_pick(st, *pick, face.as_deref())?;+/// A circle-centre snap's cylinder and the end it takes (component coordinates): through its+/// named face when it names a cylinder, else the cylindrical face at its pick and the end nearer+/// it, as older builds found them. Any other snap is refused.+fn round_of(doc: &Document, st: &ModelState, o: &JointOrigin) -> Result<face::Round> {+ let Snap::CircleCenter { pick, face, end, .. } = &o.snap else { return Err(DocError::Invalid("pick a round face".into())) };+ if let Some(n) = face.as_deref()+ && let Some(r) = face::named_round(doc, st, *pick, n, end.as_deref())?+ {+ return Ok(r);+ }+ let pick = named_pick(doc, st, *pick, face.as_deref())?;let comp = component_of(doc, o.occurrence)?;+ // A body moved in from another component: looked at in its own coordinates, its cylinder+ // placed by its offset (as a named face is).let cyl = component_bodies(doc, st, comp).into_iter()- .filter_map(|b| solidcraft_kernel::cylinder_face_at(&b.body, pick))+ .filter_map(|b| match doc.model_body_offset(b) {+ Some(m) => solidcraft_kernel::cylinder_face_at(&b.body, apply_point(&mat_inverse(m)?, pick)).map(|c| face::placed(m, c)),+ None => solidcraft_kernel::cylinder_face_at(&b.body, pick),+ }).min_by(|a, b| {let off = |c: &solidcraft_kernel::CylinderFace| {let v = pick - c.axis_point;@@ -445,7 +554,14 @@ fn circle_at(doc: &Document, st: &ModelState, o: &JointOrigin) -> Result<(Vec3,off(a).total_cmp(&off(b))}).ok_or_else(|| DocError::Invalid("joint origin: no cylindrical face there".into()))?;- Ok((pick, cyl))+ let s = (pick - cyl.axis_point).dot(cyl.axis);+ let (at, dir) = if (s - cyl.start).abs() <= (cyl.end - s).abs() { (cyl.start, -1.0) } else { (cyl.end, 1.0) };+ Ok(face::Round { cylinder: cyl, centre: cyl.axis_point + cyl.axis * at, z: cyl.axis * dir })+}++/// The cylindrical face of a circle-centre snap (component coordinates).+fn circle_at(doc: &Document, st: &ModelState, o: &JointOrigin) -> Result<solidcraft_kernel::CylinderFace> {+ round_of(doc, st, o).map(|r| r.cylinder)}/// World transform of an occurrence (through its parents).@@ -1434,6 +1550,10 @@ pub mod cam;#[path = "joints_reach.rs"]mod reach;++#[path = "joints_face.rs"]+mod face;+pub use face::{end_faces, face_name_at, named_face_spot, pin_end, round_end_at};pub use reach::{REACH_TOL, Reach, Reached, reach};/// The frame matrix for an explicit origin / z / x (public for commands).diff --git a/crates/doc/src/joints_face.rs b/crates/doc/src/joints_face.rsnew file mode 100644index 0000000000..9f14332887--- /dev/null+++ b/crates/doc/src/joints_face.rs@@ -0,0 +1,316 @@+//! Joint origins on named faces: a face found by its persistent name gives its own plane or+//! cylinder (axis, radius, extent) directly, instead of searching again for the face nearest a+//! point (on a thin plate the face nearest a point on a hole's wall is often the plate's face).+//! 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 solidcraft_geom::Vec3;+use solidcraft_kernel::CylinderFace;++use super::{Snap, XRef, component_bodies};+use crate::{DocError, Document, IDENTITY, Mat, ModelBody, ModelState, Result, apply_point, apply_vector, mat_inverse};++/// Rim points sampled to find the face across a cylinder's rim.+const RIM_SAMPLES: usize = 16;++/// A face found by its persistent name: its body, its index there, the point of it nearest the+/// pick (the component's coordinates) and the body's offset (a body moved in from another+/// component keeps its geometry where it was made; the offset places it).+pub(super) struct NamedFace<'a> {+ pub body: &'a ModelBody,+ pub face: usize,+ pub point: Vec3,+ pub offset: Mat,+}++fn gone(name: &str) -> DocError {+ DocError::Invalid(format!("joint origin: the face `{name}` no longer exists (edit the joint to pick again)"))+}++/// The face called `name` nearest `pick` (an error when it is gone: a joint must not quietly+/// attach elsewhere).+pub(super) fn named_face<'a>(doc: &Document, st: &'a ModelState, pick: Vec3, name: &str) -> Result<NamedFace<'a>> {+ let hit = crate::name_lookup::locate_face(st, name, pick).ok_or_else(|| gone(name))?;+ let body = st.bodies.get(hit.body).ok_or_else(|| gone(name))?;+ let Some(offset) = doc.model_body_offset(body).copied() else {+ return Ok(NamedFace { body, face: hit.face, point: hit.point, offset: IDENTITY });+ };+ let inv = mat_inverse(&offset).ok_or_else(|| gone(name))?;+ let (face, at, _) = crate::naming::face_on_body(body, name, apply_point(&inv, pick)).ok_or_else(|| gone(name))?;+ Ok(NamedFace { body, face, point: apply_point(&offset, at), offset })+}++impl NamedFace<'_> {+ /// A point of the component's coordinates in the body's own.+ fn local(&self, p: Vec3) -> Vec3 {+ if self.offset == IDENTITY {+ return p;+ }+ mat_inverse(&self.offset).map_or(p, |inv| apply_point(&inv, p))+ }++ /// The face as a cylinder, in the body's own coordinates (`None`: not a cylinder).+ fn own_cylinder(&self) -> Option<CylinderFace> {+ solidcraft_kernel::cylinder_face(&self.body.body, &self.body.mesh(), self.face)+ }++ /// The face as a cylinder, in the component's coordinates.+ pub fn cylinder(&self) -> Option<CylinderFace> {+ self.own_cylinder().map(|c| placed(&self.offset, c))+ }++ /// The face's centre and outward normal (the component's coordinates), when it is planar.+ pub fn plane(&self) -> Result<Option<(Vec3, Vec3)>> {+ let tol = (self.body.body.size() * 2e-3).max(1e-3);+ let faces = self.body.body.faces(tol)?;+ Ok(faces.get(self.face).and_then(|f| f.plane_normal.map(|n| (apply_point(&self.offset, f.centroid), apply_vector(&self.offset, n)))))+ }+}++/// 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), ..c }+}++/// The face across the rim at the `at` end (along the axis) of cylinder `c`, face `face` of `b`+/// (the body's own coordinates): of the body's other faces, the one nearest the rim's points.+fn rim_neighbour(b: &ModelBody, face: usize, c: &CylinderFace, at: f64) -> Option<usize> {+ let mesh = b.mesh();+ let slack = (c.end - c.start).abs() * 1e-3 + 1e-9;+ let mut rim: Vec<Vec3> = Vec::new();+ for (t, f) in mesh.triangles.iter().zip(&mesh.tri_face) {+ if *f as usize != face {+ continue;+ }+ for k in t {+ if let Some(q) = mesh.positions.get(*k as usize)+ && ((*q - c.axis_point).dot(c.axis) - at).abs() <= slack+ && !rim.iter().any(|r| r.dist(*q) <= slack)+ {+ rim.push(*q);+ }+ }+ }+ // Evenly through the rim's points, at most RIM_SAMPLES of them.+ let step = rim.len().div_ceil(RIM_SAMPLES).max(1);+ let rim: Vec<Vec3> = rim.into_iter().step_by(step).collect();+ if rim.is_empty() {+ return None;+ }+ let mut near: BTreeMap<usize, Vec<f64>> = BTreeMap::new();+ for (t, f) in mesh.triangles.iter().zip(&mesh.tri_face) {+ let f = *f as usize;+ if f == face {+ continue;+ }+ let Some([p, q, r]) = mesh.tri(t) else { continue };+ let slot = near.entry(f).or_insert_with(|| vec![f64::INFINITY; rim.len()]);+ for (d, x) in slot.iter_mut().zip(&rim) {+ *d = d.min(crate::naming::closest(*x, p, q, r).dist(*x));+ }+ }+ // The face that meets the whole rim (the other half of a cylinder split in two meets only+ // the rim's points at its seams).+ near.into_iter().map(|(f, d)| (d.iter().sum::<f64>(), f)).min_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, f)| f)+}++/// The ends of a cylinder: (place along the axis, which way out of the face).+fn ends(c: &CylinderFace) -> [(f64, f64); 2] {+ [(c.start, -1.0), (c.end, 1.0)]+}++/// The end of `c` nearer `pick` along the axis. On a tie, the end older builds took: the start+/// of the axis as the kernel turns it (toward +x, else +y, else +z), whichever way the face's+/// own surface runs.+fn nearer_end(c: &CylinderFace, pick: Vec3) -> (f64, f64) {+ let s = (pick - c.axis_point).dot(c.axis);+ let [start, end] = ends(c);+ let (to_start, to_end) = ((s - c.start).abs(), (c.end - s).abs());+ let reversed = c.axis.x + c.axis.y * 1e-3 + c.axis.z * 1e-6 < 0.0;+ if to_start < to_end || (to_start == to_end && !reversed) { start } else { end }+}++/// The end a named round face takes without an `end` (a design saved before origins named+/// it): the one nearer the pick (moved onto the face) along the axis, decided as those builds+/// decided it, by the kernel's reading of the cylinder at the pick, so a pick midway along the+/// wall takes the same end as it did then. `own` is the face's cylinder (the body's own+/// coordinates).+fn end_by_pick(nf: &NamedFace, own: &CylinderFace) -> (f64, f64) {+ let pick = nf.local(nf.point);+ let [start, end] = ends(own);+ match solidcraft_kernel::cylinder_face_at(&nf.body.body, pick).filter(|k| k.axis.dot(own.axis).abs() > 0.5) {+ Some(k) => {+ let s = (pick - k.axis_point).dot(k.axis);+ let out = if (s - k.start).abs() <= (k.end - s).abs() { -k.axis } else { k.axis };+ if out.dot(own.axis) < 0.0 { start } else { end }+ }+ None => nearer_end(own, pick),+ }+}++/// A round joint origin worked out: its cylinder, and the centre and outward axis of the end+/// it takes (the component's coordinates).+pub(super) struct Round {+ pub cylinder: CylinderFace,+ pub centre: Vec3,+ pub z: Vec3,+}++impl Round {+ fn at(c: CylinderFace, (at, dir): (f64, f64)) -> Round {+ Round { cylinder: c, centre: c.axis_point + c.axis * at, z: c.axis * dir }+ }+}++/// A circle-centre snap's cylinder found through its named face (`None`: the snap names no+/// face, or the face is not a cylinder any more; the caller looks by point, as older builds+/// did). The end is the one whose rim meets the face called `end`, else the one nearer `pick`.+pub(super) fn named_round(doc: &Document, st: &ModelState, pick: Vec3, face: &str, end: Option<&str>) -> Result<Option<Round>> {+ let nf = named_face(doc, st, pick, face)?;+ let Some(own) = nf.own_cylinder() else { return Ok(None) };+ let chosen = end+ .and_then(|name| {+ let hits: Vec<(f64, f64)> = ends(&own)+ .into_iter()+ .filter(|(at, _)| rim_neighbour(nf.body, nf.face, &own, *at).is_some_and(|f| crate::name_lookup::face_has_name(nf.body, f, name)))+ .collect();+ match hits[..] {+ [one] => Some(one),+ _ => None,+ }+ })+ .unwrap_or_else(|| end_by_pick(&nf, &own));+ Ok(Some(Round::at(placed(&nf.offset, own), chosen)))+}++/// The x axis an x reference gives a frame at `o` with axis `z` (`None`: no reference).+pub(super) fn x_axis(doc: &Document, st: &ModelState, x: Option<&XRef>, o: Vec3) -> Result<Option<Vec3>> {+ Ok(match x {+ None => None,+ Some(XRef::Dir(d)) => Some(*d),+ Some(XRef::Face { face, pick }) => {+ let nf = named_face(doc, st, pick.unwrap_or(o), face)?;+ if let Some((_, n)) = nf.plane()? {+ Some(n)+ } else if let Some(c) = nf.cylinder() {+ let v = c.axis_point - o;+ Some(v - c.axis * v.dot(c.axis))+ } else {+ Some(nf.point - o)+ }+ }+ })+}++/// The persistent name of the face of a component's bodies at `pick` (the component's+/// coordinates), measured to each face's triangles and, among the faces as near as the mesh+/// lets them be told apart, to the face's own surface (a point on a thin plate's hole wall lies+/// as near the facets of the plate's face round the rim). `round` prefers a cylinder on a tie+/// (a pick on a hole's rim names its wall). `None`: no named face there.+pub fn face_name_at(doc: &Document, st: &ModelState, component: u64, pick: Vec3, round: bool) -> Option<String> {+ let mut best: Option<(f64, &ModelBody, usize)> = None;+ for b in component_bodies(doc, st, component) {+ if b.body.is_mesh() {+ continue;+ }+ let offset = doc.model_body_offset(b).copied().unwrap_or(IDENTITY);+ let p = apply_point(&mat_inverse(&offset)?, pick);+ let mesh = b.mesh();+ let tol = (b.body.size() * 1e-3).max(1e-3).max(b.display_tol());+ let mut near: BTreeMap<usize, f64> = BTreeMap::new();+ for (t, f) in mesh.triangles.iter().zip(&mesh.tri_face) {+ let Some([x, y, z]) = mesh.tri(t) else { continue };+ let d = crate::naming::closest(p, x, y, z).dist(p);+ near.entry(*f as usize).and_modify(|n| *n = n.min(d)).or_insert(d);+ }+ let nearest = near.values().copied().fold(f64::INFINITY, f64::min);+ if nearest > tol * 5.0 {+ continue;+ }+ for (f, d) in near.into_iter().filter(|(_, d)| *d <= nearest + tol) {+ let (off, cylinder) = match solidcraft_kernel::face_surface(&b.body, f) {+ Some(solidcraft_kernel::FaceSurface::Plane { normal, point }) => (d.min((p - point).dot(normal).abs()), false),+ Some(solidcraft_kernel::FaceSurface::Cylinder { .. }) => {+ (solidcraft_kernel::cylinder_face(&b.body, &mesh, f).map_or(d, |c| d.min(c.off(p))), true)+ }+ _ => (d, false),+ };+ let score = if round && cylinder { off - tol } else { off };+ if best.as_ref().is_none_or(|(s, ..)| score < *s) {+ best = Some((score, b, f));+ }+ }+ }+ let (_, b, f) = best?;+ crate::naming::face_names(b).get(f).filter(|n| !n.is_empty()).cloned()+}++/// A circle-centre snap for the round end of a component's cylindrical face centred at+/// `centre` (the component's coordinates; a circle given by its centre, where no face lies),+/// with the face's name and its end's: `None` when no named cylinder ends there.+pub fn round_end_at(doc: &Document, st: &ModelState, component: u64, centre: Vec3) -> Option<Snap> {+ let mut best: Option<(f64, &ModelBody, usize, CylinderFace, f64)> = None;+ for b in component_bodies(doc, st, component) {+ if b.body.is_mesh() {+ continue;+ }+ let offset = doc.model_body_offset(b).copied().unwrap_or(IDENTITY);+ let p = apply_point(&mat_inverse(&offset)?, centre);+ let mesh = b.mesh();+ let tol = (b.body.size() * 1e-3).max(1e-3);+ for f in 0..b.body.face_count() {+ let Some(c) = solidcraft_kernel::cylinder_face(&b.body, &mesh, f) else { continue };+ let v = p - c.axis_point;+ let along = v.dot(c.axis);+ for (at, _) in ends(&c) {+ let off = (v - c.axis * along).len() + (along - at).abs();+ if off <= tol && best.as_ref().is_none_or(|(o, ..)| off < *o) {+ best = Some((off, b, f, c, at));+ }+ }+ }+ }+ let (_, b, f, c, at) = best?;+ let names = crate::naming::face_names(b);+ let face = names.get(f).filter(|n| !n.is_empty()).cloned()?;+ let end = rim_neighbour(b, f, &c, at).and_then(|n| names.get(n)).filter(|n| !n.is_empty()).cloned();+ Some(Snap::CircleCenter { pick: centre, face: Some(face), end, x: None })+}++/// Name the end a named circle-centre snap takes now (the face across the rim there), so it+/// keeps that end when the design changes. Other snaps, and one whose end is named already, are+/// left as they are.+pub fn pin_end(doc: &Document, st: &ModelState, snap: &mut Snap) {+ let Snap::CircleCenter { pick, face: Some(face), end: end @ None, .. } = snap else { return };+ let Ok(nf) = named_face(doc, st, *pick, face) else { return };+ let Some(own) = nf.own_cylinder() else { return };+ let (at, _) = end_by_pick(&nf, &own);+ *end = rim_neighbour(nf.body, nf.face, &own, at).and_then(|n| crate::naming::face_names(nf.body).get(n).cloned()).filter(|n| !n.is_empty());+}++/// The names of the faces across the rims at the two ends of a named circle-centre snap's+/// cylinder (what its `end` can be); empty when the snap names no cylinder.+pub fn end_faces(doc: &Document, st: &ModelState, snap: &Snap) -> Vec<String> {+ let Snap::CircleCenter { pick, face: Some(face), .. } = snap else { return Vec::new() };+ let Ok(nf) = named_face(doc, st, *pick, face) else { return Vec::new() };+ let Some(own) = nf.own_cylinder() else { return Vec::new() };+ let names = crate::naming::face_names(nf.body);+ ends(&own)+ .iter()+ .filter_map(|(at, _)| rim_neighbour(nf.body, nf.face, &own, *at).and_then(|n| names.get(n).cloned()))+ .filter(|n| !n.is_empty())+ .collect()+}++/// The face `model.faces` calls `name` (on the body called `body`, or any body): the component+/// it belongs to and a point on it in that component's coordinates, for a joint origin given by+/// a face's name. `Err` says why there is no one such face.+pub fn named_face_spot(doc: &Document, st: &ModelState, body: Option<&str>, name: &str) -> std::result::Result<(u64, Vec3), String> {+ let hit = crate::name_lookup::locate_one(st, body, name)?;+ let b = st.bodies.get(hit.body).ok_or_else(|| format!("no face is named `{name}`"))?;+ let spot = crate::naming::face_spot(b, hit.face).ok_or_else(|| format!("face `{name}` has no surface to pick"))?;+ let offset = doc.model_body_offset(b).copied().unwrap_or(IDENTITY);+ Ok((doc.model_body_component(b), apply_point(&offset, spot.point)))+}diff --git a/crates/engine/src/cmd/component_clone_assembly.rs b/crates/engine/src/cmd/component_clone_assembly.rsindex 7cf3a027c1..df381acd00 100644--- a/crates/engine/src/cmd/component_clone_assembly.rs+++ b/crates/engine/src/cmd/component_clone_assembly.rs@@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet};use solidcraft_doc::Document;use solidcraft_doc::joints::cam::CamProfile;-use solidcraft_doc::joints::{Assembly, Coupling, JointOrigin, Size, Snap};+use solidcraft_doc::joints::{Assembly, Coupling, JointOrigin, Size};use crate::{EngineError, Result};@@ -26,12 +26,7 @@ fn add_references(count: &mut usize, more: usize) -> Result<()> {}fn finite_origin(origin: &JointOrigin) -> Result<()> {- let finite = match &origin.snap {- Snap::Frame { origin, z, x } => origin.is_finite() && z.is_finite() && x.is_none_or(|x| x.is_finite()),- Snap::FaceCenter { pick, .. } | Snap::CircleCenter { pick, .. } => pick.is_finite(),- Snap::Point { point, z } => point.is_finite() && z.is_none_or(|z| z.is_finite()),- };- if !finite {+ if !origin.snap.is_finite() {return Err(invalid("joint origin contains non-finite geometry"));}Ok(())@@ -61,7 +56,7 @@ fn budget(assembly: &Assembly) -> Result<()> {for origin in &assembly.origins {finite_origin(&origin.origin)?;text(&origin.name)?;- if let Snap::FaceCenter { face: Some(face), .. } | Snap::CircleCenter { face: Some(face), .. } = &origin.origin.snap {+ for face in origin.origin.snap.face_names() {text(face)?;}}@@ -77,7 +72,7 @@ fn budget(assembly: &Assembly) -> Result<()> {}for origin in [&joint.a, &joint.b] {finite_origin(origin)?;- if let Snap::FaceCenter { face: Some(face), .. } | Snap::CircleCenter { face: Some(face), .. } = &origin.snap {+ for face in origin.snap.face_names() {text(face)?;}}@@ -234,9 +229,8 @@ fn origin() -> Option<JointOrigin> {let mut out = origin.clone();out.occurrence = *occurrences.get(&origin.occurrence)?;- match &mut out.snap {- Snap::FaceCenter { face: Some(face), .. } | Snap::CircleCenter { face: Some(face), .. } => *face = face_name(face, features, bodies)?,- _ => {}+ for face in out.snap.face_names_mut() {+ *face = face_name(face, features, bodies)?;}Some(out)}diff --git a/crates/engine/src/cmd/component_clone_assembly_tests.rs b/crates/engine/src/cmd/component_clone_assembly_tests.rsindex 63f110363f..23defb3897 100644--- a/crates/engine/src/cmd/component_clone_assembly_tests.rs+++ b/crates/engine/src/cmd/component_clone_assembly_tests.rs@@ -1,6 +1,6 @@#![allow(clippy::unwrap_used, clippy::panic)]use super::*;-use solidcraft_doc::joints::{Coupling, Joint, JointKind, MotionLink, NamedOrigin, Size};+use solidcraft_doc::joints::{Coupling, Joint, JointKind, MotionLink, NamedOrigin, Size, Snap, XRef};use solidcraft_doc::motion::{ContactSet, ExplodedView, MotionStudy, StudyKey};use solidcraft_doc::{IDENTITY, Occurrence};use solidcraft_geom::Vec3;@@ -35,11 +35,18 @@ fn documents() -> (Document, Document) {source.assembly.origins = vec![NamedOrigin {name: "Typed origin".into(),- origin: JointOrigin { occurrence: 1, snap: Snap::FaceCenter { pick: Vec3::new(1.0, 2.0, 3.0), face: Some("F1:[email protected]".into()) } },+ origin: JointOrigin {+ occurrence: 1,+ snap: Snap::FaceCenter {+ pick: Vec3::new(1.0, 2.0, 3.0),+ face: Some("F1:[email protected]".into()),+ x: Some(XRef::Face { face: "F10:side".into(), pick: None }),+ },+ },},NamedOrigin {name: "Foreign geometry".into(),- origin: JointOrigin { occurrence: 1, snap: Snap::CircleCenter { pick: Vec3::ZERO, face: Some("F99:end".into()) } },+ origin: JointOrigin { occurrence: 1, snap: Snap::CircleCenter { pick: Vec3::ZERO, face: Some("F99:end".into()), end: None, x: None } },},NamedOrigin { name: "Outside".into(), origin: at(9) },];@@ -79,7 +86,9 @@ fn internal_relationships_receive_independent_ids_and_remapped_typed_references(assert_eq!(a.joints[4].limits, source.assembly.joints[0].limits);assert_eq!(a.joints[4].name, "Joint1 (copy)");assert_eq!(a.origins.len(), 4);- assert!(matches!(&a.origins[3].origin.snap, Snap::FaceCenter { face: Some(face), .. } if face == "F11:[email protected]"));+ // Its x reference's face is the copy's too.+ assert!(matches!(&a.origins[3].origin.snap, Snap::FaceCenter { face: Some(face), x: Some(XRef::Face { face: x, .. }), .. }+ if face == "F11:[email protected]" && x == "F110:side"));assert_eq!((a.links[2].a, a.links[2].b, a.links[2].ratio), (5, 6, -2.0));assert_eq!(a.contact_sets[2].id, 7);assert_eq!(a.contact_sets[2].occurrences, vec![101, 102]);@@ -103,7 +112,12 @@ fn internal_relationships_receive_independent_ids_and_remapped_typed_references(#[test]fn copied_gears_take_their_picked_faces_along() {let (mut source, _) = documents();- let circle = |face: &str| Size::Circle(JointOrigin { occurrence: 1, snap: Snap::CircleCenter { pick: Vec3::X, face: Some(face.into()) } });+ let circle = |face: &str| {+ Size::Circle(JointOrigin {+ occurrence: 1,+ snap: Snap::CircleCenter { pick: Vec3::X, face: Some(face.into()), end: Some("F1:top".into()), x: None },+ })+ };let gear = |ra| Coupling::Gear { ra, rb: Size::Length(5.0), internal: false, reverse: false };source.assembly.links = vec![MotionLink { a: 1, ia: 0, b: 2, ib: 0, ratio: -2.0, offset: 0.0, coupling: Some(gear(circle("F1:side"))), lift: Vec::new() },@@ -116,7 +130,10 @@ fn copied_gears_take_their_picked_faces_along() {.unwrap();let copied = destination.assembly.links.get(2).and_then(|l| l.coupling.clone());let Some(Coupling::Gear { ra: Size::Circle(o), .. }) = copied else { panic!("{:?}", destination.assembly.links) };- assert!(o.occurrence == 101 && matches!(&o.snap, Snap::CircleCenter { face: Some(f), .. } if f == "F11:side"), "{o:?}");+ assert!(+ o.occurrence == 101 && matches!(&o.snap, Snap::CircleCenter { face: Some(f), end: Some(e), .. } if f == "F11:side" && e == "F11:top"),+ "{o:?}"+ );assert_eq!(destination.assembly.links.len(), 3, "the gear on foreign geometry stays behind");assert!(report.iter().any(|m| m.contains("motion link")), "{report:?}");}diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rsindex d0a8f78487..a6e3a56073 100644--- a/crates/engine/src/cmd/joints.rs+++ b/crates/engine/src/cmd/joints.rs@@ -8,7 +8,7 @@ use std::collections::{BTreeMap, BTreeSet};use serde_json::{Value, json};use solidcraft_doc::expr::Kind;use solidcraft_doc::joints::cam::{self, Cam, CamProfile, Follower};-use solidcraft_doc::joints::{self, Coupling, Joint, JointKind, JointOrigin, MotionLink, NamedOrigin, Size, Snap};+use solidcraft_doc::joints::{self, Coupling, Joint, JointKind, JointOrigin, MotionLink, NamedOrigin, Size, Snap, XRef};use solidcraft_geom::{Aabb3, Vec3};use super::CommandSpec;@@ -17,10 +17,10 @@ use crate::{EngineError, Result, Session};pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("joint.origin", "Joint Origin", joint_origin).at("SOLID", "CREATE").icon("joint_origin").params(- "name?, occurrence?: id|name (default: from the pick), face: [x,y,z] (centre of a planar face) | circle: [x,y,z] (centre of a round end) | point: [x,y,z], z?: [x,y,z]",+ "name?, occurrence?: id|name (default: from the pick, or the named face's component), face: [x,y,z] | \"<name>\" (centre of a planar face) | circle: [x,y,z] | \"<name>\" (centre of a round end: a point on its wall or rim, the end's centre, or the round face's name as model.faces lists it) | point: [x,y,z], z?: [x,y,z]; body?: the named face's body; end?: \"<name>\" (a circle's end: the face across its rim there; default the end nearer the pick); x?: [x,y,z] (a direction, world) | \"<face name>\" | {face: [x,y,z]} (the frame's x: a direction, a plane's normal, or the way to another hole's axis; keeps a round origin's turn). Faces are kept by name: the origin follows its face, and a circle its end, when the design changes",),CommandSpec::new("joint.create", "Joint", joint).at("SOLID", "ASSEMBLE").icon("joint").key("J").params(- "type: rigid|revolute|slider|cylindrical|pin_slot|planar|ball; a, b: joint origins ({occurrence, face|circle|point: [x,y,z] in world} | origin name); \+ "type: rigid|revolute|slider|cylindrical|pin_slot|planar|ball; a, b: joint origins ({occurrence, face|circle|point: [x,y,z] in world, or face|circle: \"<face name>\"; end?, x? as joint.origin} | origin name); \values?: [angles in deg or expressions, distances]; limits?: [[min, max] | null…]; flip?: bool (default false: the origins are mated, \b's z against a's as two faces meet; true: b's z along a's, so two origins given at one point with the same z stay as they are); \offset?; angle?; name?; quiet?: bool (leave out dof and fixed)",@@ -275,11 +275,15 @@ fn origin_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result<JointOrigin.map(|o| o.origin.clone()).ok_or_else(|| bad(cmd, format!("no joint origin `{name}`")));}+ // A face given by its name, as `model.faces` lists it.+ if let Some((what, name)) = ["face", "circle"].iter().find_map(|k| v.get(*k).and_then(Value::as_str).map(|n| (*k, n))) {+ return origin_by_name(s, v, what, name, cmd);+ }let pick = ["face", "circle", "point"].iter().find_map(|k| v.get(*k).and_then(vec3).map(|p| (*k, p)));let (what, world) = match (pick, v.get("frame")) {(Some(x), _) => x,(None, Some(f)) => ("frame", f.get("origin").and_then(vec3).ok_or_else(|| bad(cmd, "`frame` needs origin and z"))?),- _ => return Err(bad(cmd, "a joint origin needs face, circle, point or frame [x, y, z]")),+ _ => return Err(bad(cmd, "a joint origin needs face, circle, point or frame [x, y, z], or a face's name")),};let occurrence = match v.get("occurrence") {Some(o) => occurrence_id(s, Some(o), cmd)?,@@ -290,17 +294,15 @@ fn origin_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result<JointOriginlet inv = solidcraft_doc::mat_inverse(&t).ok_or_else(|| bad(cmd, "occurrence transform"))?;let local = |p: Vec3| solidcraft_doc::apply_point(&inv, p);let local_dir = |d: Vec3| solidcraft_doc::apply_vector(&inv, d);+ let component = component_of(s, occurrence);+ let st = s.model.state();let snap = match what {"face" | "circle" => {let pick = local(world);- // A circle's name is its cylindrical wall's (a rim pick also touches the end face).- let named_at = if what == "circle" {- s.model.state().bodies.iter().filter_map(|b| cylinder_wall_point(&b.body, pick)).next().unwrap_or(pick)- } else {- pick- };- let face = solidcraft_doc::naming::face_names_at(&s.model.state(), &[named_at]).into_iter().next().filter(|n| !n.is_empty());- if what == "face" { Snap::FaceCenter { pick, face } } else { Snap::CircleCenter { pick, face } }+ // The face's name, which it is found by from then on (a circle's is its wall's).+ let face = joints::face_name_at(&s.doc, &st, component, pick, what == "circle");+ let x = x_param(s, v, component, &inv, cmd)?;+ if what == "face" { Snap::FaceCenter { pick, face, x } } else { Snap::CircleCenter { pick, face, end: None, x } }}"point" => Snap::Point { point: local(world), z: v.get("z").and_then(vec3).map(local_dir) },_ => {@@ -310,13 +312,97 @@ fn origin_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result<JointOrigin}};let o = JointOrigin { occurrence, snap };- match joints::resolve_origin(&s.doc, &s.model.state(), &o) {- Ok(_) => Ok(o),- // A circle given by its centre, where no face lies (#393).- Err(e) => match (what == "circle").then(|| circle_centre(s, occurrence, local(world))).flatten() {- Some(snap) => Ok(JointOrigin { occurrence, snap }),- None => Err(bad(cmd, e.to_string())),+ match settle(s, o, v, cmd) {+ Ok(o) => Ok(o),+ // A circle given by its centre, where no face lies (#393): that end of the cylinder, by+ // its face's name and its end's (a face without a name: the point and axis there).+ Err(e) if what == "circle" => {+ let snap = match joints::round_end_at(&s.doc, &st, component, local(world)) {+ Some(Snap::CircleCenter { pick, face, end, .. }) => Snap::CircleCenter { pick, face, end, x: x_param(s, v, component, &inv, cmd)? },+ _ => circle_centre(s, occurrence, local(world)).ok_or(e)?,+ };+ settle(s, JointOrigin { occurrence, snap }, v, cmd)+ }+ Err(e) => Err(e),+ }+}++/// The component an occurrence places (0 for the root, or an unknown occurrence).+fn component_of(s: &Session, occurrence: u64) -> u64 {+ if occurrence == 0 { 0 } else { s.doc.occurrences.iter().find(|o| o.id == occurrence).map_or(0, |o| o.component) }+}++/// A joint origin on a face given by its name (`face: "<name>"`: its centre; `circle: "<name>"`:+/// a round end of it), on `body?`, of `occurrence?` (default: the first occurrence of the+/// face's component).+fn origin_by_name(s: &Session, v: &Value, what: &str, name: &str, cmd: &str) -> Result<JointOrigin> {+ if name.is_empty() || name.len() > 512 {+ return Err(bad(cmd, "a face name is 1…512 characters"));+ }+ let st = s.model.state();+ let (component, pick) = joints::named_face_spot(&s.doc, &st, str_(v, "body"), name).map_err(|why| bad(cmd, why))?;+ let occurrence = match v.get("occurrence") {+ Some(o) => occurrence_id(s, Some(o), cmd)?,+ None if component == 0 => 0,+ None => {+ s.doc.occurrence_of(component).map(|o| o.id).ok_or_else(|| bad(cmd, format!("face `{name}` is on a component with no occurrence")))?+ }+ };+ if component_of(s, occurrence) != component {+ return Err(bad(cmd, format!("face `{name}` is not on that occurrence's component")));+ }+ let t = if occurrence == 0 { solidcraft_doc::IDENTITY } else { joints::occurrence_world(&s.doc, occurrence) };+ let inv = solidcraft_doc::mat_inverse(&t).ok_or_else(|| bad(cmd, "occurrence transform"))?;+ let x = x_param(s, v, component, &inv, cmd)?;+ let face = Some(name.to_string());+ let snap = if what == "face" { Snap::FaceCenter { pick, face, x } } else { Snap::CircleCenter { pick, face, end: None, x } };+ settle(s, JointOrigin { occurrence, snap }, v, cmd)+}++/// A new joint origin checked: `end?` (a circle's end, by the name of the face across its rim+/// there) set, and the end it takes named so it keeps it; refused when it doesn't resolve.+fn settle(s: &Session, mut o: JointOrigin, v: &Value, cmd: &str) -> Result<JointOrigin> {+ let st = s.model.state();+ if let Some(want) = v.get("end") {+ let want =+ want.as_str().filter(|n| !n.is_empty() && n.len() <= 512).ok_or_else(|| bad(cmd, "`end` is the name of a face a round end lies on"))?;+ let Snap::CircleCenter { end, .. } = &mut o.snap else { return Err(bad(cmd, "`end` is for a round origin (`circle`)")) };+ *end = Some(want.to_string());+ let names = joints::end_faces(&s.doc, &st, &o.snap);+ if !names.iter().any(|n| n == want) {+ return Err(bad(cmd, format!("the round face doesn't end on face `{want}` (its ends lie on: {})", names.join(", "))));+ }+ }+ joints::resolve_origin(&s.doc, &st, &o).map_err(|e| bad(cmd, e.to_string()))?;+ joints::pin_end(&s.doc, &st, &mut o.snap);+ Ok(o)+}++/// A joint origin's x reference (its turn about z): `x: [x, y, z]` (a direction, world), `x:+/// "<face name>"`, or `x: {face: [x, y, z]}` (the face of the origin's component there, world).+fn x_param(s: &Session, v: &Value, component: u64, inv: &solidcraft_doc::Mat, cmd: &str) -> Result<Option<XRef>> {+ let st = s.model.state();+ let named = |name: &str| -> Result<Option<XRef>> {+ joints::named_face_spot(&s.doc, &st, None, name).map_err(|why| bad(cmd, format!("`x`: {why}")))?;+ Ok(Some(XRef::Face { face: name.to_string(), pick: None }))+ };+ let wrong = || bad(cmd, "`x` is a direction [x, y, z], a face's name, or {face: [x, y, z]}");+ match v.get("x") {+ None | Some(Value::Null) => Ok(None),+ Some(Value::String(name)) if !name.is_empty() && name.len() <= 512 => named(name),+ Some(o @ Value::Object(_)) => match o.get("face") {+ Some(Value::String(name)) if !name.is_empty() && name.len() <= 512 => named(name),+ Some(p) => {+ let pick = vec3(p).map(|p| solidcraft_doc::apply_point(inv, p)).ok_or_else(wrong)?;+ let face = joints::face_name_at(&s.doc, &st, component, pick, false).ok_or_else(|| bad(cmd, "`x`: no named face there"))?;+ Ok(Some(XRef::Face { face, pick: Some(pick) }))+ }+ None => Err(wrong()),},+ Some(d) => {+ let d = vec3(d).filter(|d| d.is_finite() && d.len() > 1e-9).ok_or_else(wrong)?;+ Ok(Some(XRef::Dir(solidcraft_doc::apply_vector(inv, d))))+ }}}@@ -1230,18 +1316,12 @@ pub(crate) fn overlapping_pairs(boxes: &[Aabb3], limit: usize) -> (Vec<(usize, u(pairs, skipped)}+#[cfg(test)]+#[path = "joints_face_tests.rs"]+mod face_tests;#[cfg(test)]#[path = "joints_reach_tests.rs"]mod reach_tests;#[cfg(test)]#[path = "joints_tests.rs"]mod tests;--/// A point in the middle of the cylindrical face at `pick` (on its wall, halfway along).-fn cylinder_wall_point(b: &solidcraft_doc::kernel::Body, pick: Vec3) -> Option<Vec3> {- let c = solidcraft_doc::kernel::cylinder_face_at(b, pick)?;- let v = pick - c.axis_point;- let along = v.dot(c.axis);- let radial = (v - c.axis * along).normalized()?;- Some(c.axis_point + c.axis * ((c.start + c.end) / 2.0) + radial * c.radius)-}diff --git a/crates/engine/src/cmd/joints_face_tests.rs b/crates/engine/src/cmd/joints_face_tests.rsnew file mode 100644index 0000000000..a97e2694ba--- /dev/null+++ b/crates/engine/src/cmd/joints_face_tests.rs@@ -0,0 +1,267 @@+//! Joint origins found by their face's name: a part jointed to a hole stays on it, on the same+//! side and turned the same way, as the design's parameters change.++use serde_json::{Value, json};+use solidcraft_doc::joints::{Snap, XRef};+use solidcraft_geom::Vec3;++use super::tests::{occ, place, run};+use crate::Session;++fn near(a: Vec3, b: Vec3) -> bool {+ a.dist(b) < 1e-6+}++/// Widths swept: small steps (a hole's wall in a 1 mm plate is a few long facets, and a pick+/// stored at the old width lies beside the moved hole) and large ones.+const WIDTHS: [f64; 9] = [302.0, 304.0, 310.0, 330.0, 400.0, 450.0, 510.0, 301.0, 300.0];++/// A tray: a 1 mm plate `W` wide (a parameter, 300 mm to start) and 100 deep, with a 6 mm hole+/// 20 mm in from its right edge (an expression); grounded. A bracket: a 20 x 20 x 2 foot with a+/// 6 mm hole in its middle and a 15 mm upright along its +X edge, so a turn shows.+fn tray() -> Session {+ let mut s = Session::default();+ run(&mut s, "parameters.change", json!({"name": "W", "expression": "300 mm"}));+ run(&mut s, "component.create", json!({"name": "Tray"}));+ run(&mut s, "solid.box", json!({"length": "W", "width": 100, "height": 1, "corner": [0, 0, 0]}));+ run(&mut s, "solid.hole", json!({"position": ["W - 20 mm", 50, 1], "diameter": 6}));+ let tray = occ(&s, "Tray");+ run(&mut s, "occurrence.ground", json!({"occurrence": tray, "grounded": true}));+ run(&mut s, "component.activate", json!({"component": "root"}));+ run(&mut s, "component.create", json!({"name": "Bracket"}));+ run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 2, "corner": [100, 200, 0]}));+ run(&mut s, "solid.box", json!({"length": 2, "width": 20, "height": 15, "corner": [118, 200, 0], "operation": "join"}));+ run(&mut s, "solid.hole", json!({"position": [110, 210, 2], "diameter": 6}));+ s+}++fn width(s: &mut Session, w: f64) {+ run(s, "parameters.change", json!({"name": "W", "expression": format!("{w} mm")}));+ let r = run(s, "joint.solve", json!({}));+ assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "W = {w}: {r}");+}++/// The bracket sits on the tray's top, its hole on the tray's hole and its upright toward +X.+fn on_the_hole(s: &Session, w: f64) {+ let hole = place(s, "Bracket", Vec3::new(110.0, 210.0, 0.0));+ assert!(near(hole, Vec3::new(w - 20.0, 50.0, 1.0)), "W = {w}: the bracket's hole is at {hole:?}");+ let upright = place(s, "Bracket", Vec3::new(119.0, 210.0, 15.0));+ assert!(near(upright, Vec3::new(w - 11.0, 50.0, 16.0)), "W = {w}: the upright's top is at {upright:?}");+}++fn origin(s: &Session, joint: &str, a: bool) -> Snap {+ let j = s.doc.assembly.joints.iter().find(|j| j.name == joint).map(|j| if a { &j.a } else { &j.b });+ j.map(|o| o.snap.clone()).unwrap_or(Snap::Point { point: Vec3::ZERO, z: None })+}++#[test]+fn a_bracket_on_a_hole_in_thin_plate_stays_on_it_as_the_plate_widens() {+ let mut s = tray();+ // Picks inside the 1 mm wall of the tray's hole (nearer its top) and the 2 mm wall of the+ // bracket's (nearer its bottom); both x along +X.+ let r = run(+ &mut s,+ "joint.create",+ json!({"type": "rigid", "name": "Mount",+ "a": {"occurrence": "Tray", "circle": [283, 50, 0.8], "x": [1, 0, 0]},+ "b": {"occurrence": "Bracket", "circle": [113, 210, 0.4], "x": [1, 0, 0]}}),+ );+ assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}");+ on_the_hole(&s, 300.0);+ // Both origins are kept by their wall's name and their end's (the tray's top face, the+ // bracket's bottom one).+ for a in [true, false] {+ let snap = origin(&s, "Mount", a);+ assert!(matches!(&snap, Snap::CircleCenter { face: Some(_), end: Some(_), x: Some(XRef::Dir(_)), .. }), "{snap:?}");+ }+ for w in WIDTHS {+ width(&mut s, w);+ on_the_hole(&s, w);+ }+ // Saved and opened again, it still follows.+ let dir = std::env::temp_dir().join(format!("solidcraft-joint-faces-{}", std::process::id()));+ let _ = std::fs::create_dir_all(&dir);+ let path = dir.join("tray.json").to_string_lossy().to_string();+ run(&mut s, "file.save", json!({"path": path}));+ run(&mut s, "file.new", json!({}));+ run(&mut s, "doc.open", json!({"path": path}));+ for w in [330.0, 510.0] {+ width(&mut s, w);+ on_the_hole(&s, w);+ }+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn a_circle_given_by_its_centre_follows_its_hole() {+ let mut s = tray();+ // The centres of the tray hole's top rim and the bracket hole's bottom rim.+ let r = run(+ &mut s,+ "joint.create",+ json!({"type": "rigid", "name": "Mount",+ "a": {"occurrence": "Tray", "circle": [280, 50, 1], "x": [1, 0, 0]},+ "b": {"occurrence": "Bracket", "circle": [110, 210, 0], "x": [1, 0, 0]}}),+ );+ assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}");+ let snap = origin(&s, "Mount", true);+ assert!(matches!(&snap, Snap::CircleCenter { face: Some(_), end: Some(_), .. }), "a centre names its face and end: {snap:?}");+ on_the_hole(&s, 300.0);+ for w in WIDTHS {+ width(&mut s, w);+ on_the_hole(&s, w);+ }+}++/// The name `model.faces` gives the face of `component`'s body holding `p` (component coordinates).+fn face_name(s: &mut Session, component: &str, p: Vec3) -> String {+ let st = s.model.state();+ let c = s.doc.find_component(component).unwrap_or(0);+ solidcraft_doc::joints::face_name_at(&s.doc, &st, c, p, false).unwrap_or_default()+}++#[test]+fn origins_take_faces_by_name_and_an_end_and_turn_by_name() {+ let mut s = tray();+ let wall = face_name(&mut s, "Tray", Vec3::new(283.0, 50.0, 0.5));+ let top = face_name(&mut s, "Tray", Vec3::new(150.0, 50.0, 1.0));+ let bottom = face_name(&mut s, "Tray", Vec3::new(150.0, 50.0, 0.0));+ let right = face_name(&mut s, "Tray", Vec3::new(300.0, 50.0, 0.5));+ let foot = face_name(&mut s, "Bracket", Vec3::new(113.0, 210.0, 1.0));+ let under = face_name(&mut s, "Bracket", Vec3::new(105.0, 205.0, 0.0));+ assert!(![&wall, &top, &bottom, &right, &foot, &under].iter().any(|n| n.is_empty()));+ // A round end by the wall's name and the face it opens onto; x along the tray's right end+ // face's normal (+X).+ run(&mut s, "joint.origin", json!({"name": "Hole", "circle": wall, "end": top, "x": right}));+ let r = run(&mut s, "joint.create", json!({"type": "rigid", "name": "Mount", "a": "Hole", "b": {"circle": foot, "end": under, "x": [1, 0, 0]}}));+ assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}");+ on_the_hole(&s, 300.0);+ for w in [304.0, 400.0, 510.0] {+ width(&mut s, w);+ on_the_hole(&s, w);+ }+ // The other end: the bracket hangs under the plate (its foot's underside on the plate's).+ run(&mut s, "joint.origin", json!({"name": "Under", "circle": wall, "end": bottom, "x": right}));+ run(&mut s, "joint.delete", json!({"joint": "Mount"}));+ run(&mut s, "joint.create", json!({"type": "rigid", "name": "Hung", "a": "Under", "b": {"circle": foot, "end": under, "x": [1, 0, 0]}}));+ let hole = place(&s, "Bracket", Vec3::new(110.0, 210.0, 0.0));+ assert!(near(hole, Vec3::new(490.0, 50.0, 0.0)), "{hole:?}");+ assert!(place(&s, "Bracket", Vec3::new(119.0, 210.0, 15.0)).z < -10.0);+ // An end the hole doesn't have, a missing face and a bad x are refused.+ for bad in [+ json!({"circle": wall, "end": right}),+ json!({"circle": "F999:nothing"}),+ json!({"circle": wall, "x": "F999:nothing"}),+ json!({"circle": wall, "x": [0, 0, 0]}),+ json!({"face": [10, 10, 1], "end": top}),+ ] {+ assert!(s.execute("joint.origin", &bad).is_err(), "{bad}");+ }+}++#[test]+fn a_face_centre_by_name_follows_its_face() {+ let mut s = tray();+ let right = face_name(&mut s, "Tray", Vec3::new(300.0, 50.0, 0.5));+ run(&mut s, "joint.origin", json!({"name": "End", "face": right, "x": [0, 1, 0]}));+ let frame = |s: &Session| {+ let o = s.doc.assembly.origins.iter().find(|o| o.name == "End").map(|o| o.origin.clone());+ o.and_then(|o| solidcraft_doc::joints::resolve_origin(&s.doc, &s.model.state(), &o).ok())+ };+ for w in [300.0, 330.0, 510.0] {+ width(&mut s, w);+ let m = frame(&s).unwrap_or(solidcraft_doc::IDENTITY);+ let (o, x, z) = (Vec3::new(m[3][0], m[3][1], m[3][2]), Vec3::new(m[0][0], m[0][1], m[0][2]), Vec3::new(m[2][0], m[2][1], m[2][2]));+ assert!(near(o, Vec3::new(w, 50.0, 0.5)) && near(z, Vec3::X) && near(x, Vec3::Y), "W = {w}: {o:?} {x:?} {z:?}");+ }+}++#[test]+fn an_origin_without_an_end_or_turn_opens_as_before() {+ // A design saved before origins named their end and turn: the snap reads without them.+ let snap: Snap = serde_json::from_value(json!({"type": "circle_center", "pick": [1, 2, 3], "face": "F1:side"}))+ .unwrap_or(Snap::Point { point: Vec3::ZERO, z: None });+ assert_eq!(snap, Snap::CircleCenter { pick: Vec3::new(1.0, 2.0, 3.0), face: Some("F1:side".into()), end: None, x: None });+ let back: Value = serde_json::to_value(&snap).unwrap_or_default();+ assert_eq!(back, json!({"type": "circle_center", "pick": [1.0, 2.0, 3.0], "face": "F1:side"}));+ let turned = Snap::FaceCenter { pick: Vec3::ZERO, face: None, x: Some(XRef::Face { face: "F2:+x".into(), pick: None }) };+ let v = serde_json::to_value(&turned).unwrap_or_default();+ assert_eq!(v["x"], json!({"face": "F2:+x"}));+ assert_eq!(serde_json::from_value::<Snap>(v).ok(), Some(turned));+}++/// The frame a named joint origin resolves to: its origin and z.+fn origin_frame(s: &Session, name: &str) -> Option<(Vec3, Vec3)> {+ let o = s.doc.assembly.origins.iter().find(|o| o.name == name)?;+ let m = solidcraft_doc::joints::resolve_origin(&s.doc, &s.model.state(), &o.origin).ok()?;+ Some((Vec3::new(m[3][0], m[3][1], m[3][2]), Vec3::new(m[2][0], m[2][1], m[2][2])))+}++#[test]+fn a_round_origin_saved_without_an_end_takes_the_end_it_took_before() {+ // A plate `T` thick (5 mm) with a 6 mm hole through it, and two round origins as builds+ // before `end` saved them (no `end`, no `x`): picks on the hole's wall 4 mm and 1 mm up.+ let mut s = Session::default();+ run(&mut s, "parameters.change", json!({"name": "T", "expression": "5 mm"}));+ run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": "T", "corner": [0, 0, 0]}));+ run(&mut s, "solid.hole", json!({"position": [20, 20, "T"], "diameter": 6}));+ let wall = solidcraft_doc::joints::face_name_at(&s.doc, &s.model.state(), 0, Vec3::new(23.0, 20.0, 2.5), true).unwrap_or_default();+ assert!(!wall.is_empty());+ for (name, z) in [("High", 4.0), ("Low", 1.0)] {+ let saved = json!({"name": name, "origin": {"occurrence": 0, "snap": {"face": wall, "pick": [23.0, 20.0, z], "type": "circle_center"}}});+ let o: solidcraft_doc::joints::NamedOrigin = serde_json::from_value(saved).unwrap_or_else(|e| panic!("{e}"));+ s.doc_mut().assembly.origins.push(o);+ }+ let dir = std::env::temp_dir().join(format!("solidcraft-joint-end-tie-{}", std::process::id()));+ let _ = std::fs::create_dir_all(&dir);+ let path = dir.join("plate.json").to_string_lossy().to_string();+ run(&mut s, "file.save", json!({"path": path}));+ run(&mut s, "file.new", json!({}));+ run(&mut s, "doc.open", json!({"path": path}));+ let _ = std::fs::remove_dir_all(&dir);+ let (top, bottom) = (|t: f64| (Vec3::new(20.0, 20.0, t), Vec3::Z), (Vec3::new(20.0, 20.0, 0.0), -Vec3::Z));+ // Where the pick is nearer one end, that end; midway along the wall (the plate 8 mm thick+ // for the pick 4 mm up, 2 mm for the one 1 mm up), the bottom end, as those builds took.+ for (t, high, low) in [(5.0, Some(top(5.0)), bottom), (8.0, Some(bottom), bottom), (2.0, None, bottom), (5.0, Some(top(5.0)), bottom)] {+ run(&mut s, "parameters.change", json!({"name": "T", "expression": format!("{t} mm")}));+ for (name, want) in [("High", high), ("Low", Some(low))] {+ let Some((o, z)) = want else { continue };+ let got = origin_frame(&s, name);+ assert!(got.is_some_and(|(go, gz)| near(go, o) && near(gz, z)), "T = {t}, {name}: {got:?}, expected {o:?} {z:?}");+ }+ }+}++#[test]+fn origins_on_a_body_placed_by_an_offset_agree_named_or_not() {+ // A plate made at the origin, then placed by an offset (turned a quarter about x, moved):+ // a body moved in from another component keeps its geometry where it was made.+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 5, "corner": [0, 0, 0], "body_name": "Plate"}));+ run(&mut s, "solid.hole", json!({"position": [20, 20, 5], "diameter": 6}));+ let offset = solidcraft_doc::rigid(Vec3::new(7.0, 0.0, 3.0), Vec3::ZERO, Vec3::X, std::f64::consts::FRAC_PI_2);+ s.doc_mut().body_offsets.insert("Plate".into(), offset);+ s.refresh();+ let at = |p: Vec3| solidcraft_doc::apply_point(&offset, p);+ let up = solidcraft_doc::apply_vector(&offset, Vec3::Z);+ let st = s.model.state();+ let (top_pick, wall_pick) = (at(Vec3::new(10.0, 10.0, 5.0)), at(Vec3::new(23.0, 20.0, 4.0)));+ let top = solidcraft_doc::joints::face_name_at(&s.doc, &st, 0, top_pick, false);+ let wall = solidcraft_doc::joints::face_name_at(&s.doc, &st, 0, wall_pick, true);+ assert!(top.is_some() && wall.is_some(), "{top:?} {wall:?}");+ let resolve = |snap: Snap| {+ let o = solidcraft_doc::joints::JointOrigin { occurrence: 0, snap };+ let m = solidcraft_doc::joints::resolve_origin(&s.doc, &st, &o).unwrap_or_else(|e| panic!("{e}"));+ (Vec3::new(m[3][0], m[3][1], m[3][2]), Vec3::new(m[2][0], m[2][1], m[2][2]))+ };+ // The top face's centre: by its name, and by the point alone.+ let named = resolve(Snap::FaceCenter { pick: top_pick, face: top, x: None });+ let unnamed = resolve(Snap::FaceCenter { pick: top_pick, face: None, x: None });+ assert!(near(named.0, unnamed.0) && near(named.1, unnamed.1), "{named:?} {unnamed:?}");+ assert!(near(named.1, up) && (named.0 - at(Vec3::new(0.0, 0.0, 5.0))).dot(up).abs() < 1e-6, "{named:?}");+ // The hole's top end (the pick nearer it): by the wall's name, and by the point alone.+ let named = resolve(Snap::CircleCenter { pick: wall_pick, face: wall, end: None, x: None });+ let unnamed = resolve(Snap::CircleCenter { pick: wall_pick, face: None, end: None, x: None });+ assert!(near(named.0, unnamed.0) && near(named.1, unnamed.1), "{named:?} {unnamed:?}");+ assert!(near(named.0, at(Vec3::new(20.0, 20.0, 5.0))) && near(named.1, up), "{named:?}");+}diff --git a/crates/engine/src/cmd/joints_tests.rs b/crates/engine/src/cmd/joints_tests.rsindex 4c5e4a6cb5..adf3df2fc6 100644--- a/crates/engine/src/cmd/joints_tests.rs+++ b/crates/engine/src/cmd/joints_tests.rs@@ -55,17 +55,17 @@ fn circle_given_by_its_centre_takes_that_round_end() {for z in [6.0, 16.0] {assert!(near(place(&s, "Knob", Vec3::new(0.0, 0.0, z)), Vec3::new(0.0, 0.0, z)), "{:?}", place(&s, "Knob", Vec3::new(0.0, 0.0, z)));}- // The top end's centre: its axis points up, out of the knob.+ // The top end's centre: its axis points up, out of the knob. It is kept by the knob's wall+ // and the face its end opens onto, so it follows them.run(&mut s, "joint.origin", json!({"occurrence": "Knob", "circle": [0, 0, 16], "name": "Top"}));- let top = s.doc.assembly.origins.iter().find(|o| o.name == "Top").map(|o| o.origin.snap.clone());- assert!(- matches!(top, Some(solidcraft_doc::joints::Snap::Point { point, z: Some(z) }) if near(point, Vec3::new(0.0, 0.0, 16.0)) && near(z, Vec3::Z)),- "{top:?}"- );- // Off the axis is still refused, and so is a coupling size (it follows a face).+ let top = s.doc.assembly.origins.iter().find(|o| o.name == "Top").map(|o| o.origin.clone()).unwrap();+ assert!(matches!(&top.snap, solidcraft_doc::joints::Snap::CircleCenter { face: Some(_), end: Some(_), .. }), "{top:?}");+ let m = solidcraft_doc::joints::resolve_origin(&s.doc, &s.model.state(), &top).unwrap();+ assert!(near(Vec3::new(m[3][0], m[3][1], m[3][2]), Vec3::new(0.0, 0.0, 16.0)) && near(Vec3::new(m[2][0], m[2][1], m[2][2]), Vec3::Z), "{m:?}");+ // Off the axis is still refused; a coupling size given by a centre is that round face's+ // radius (it follows the face).assert!(s.execute("joint.origin", &json!({"occurrence": "Knob", "circle": [3, 0, 6]})).is_err());- let e = s.execute("joint.screw", &json!({"joint": "J", "pitch": {"occurrence": "Knob", "circle": [0, 0, 6]}})).unwrap_err();- assert!(e.to_string().contains("not its centre"), "{e}");+ run(&mut s, "joint.screw", json!({"joint": "J", "pitch": {"occurrence": "Knob", "circle": [0, 0, 6]}}));}#[test]diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rsindex cd85def334..c75130a8db 100644--- a/crates/kernel/src/lib.rs+++ b/crates/kernel/src/lib.rs@@ -204,7 +204,7 @@ pub use surfaces::{sweep_sheet_points, sweep_sheet_points_with, sweep_sheet_with, thicken, trim, unstitch,};pub use sweep_path::{RailFit, SweepControl, SweepOrientation, sweep_path, sweep_path_with};-pub use topo::{CylinderFace, cylinder_end_at, cylinder_face_at};+pub use topo::{CylinderFace, cylinder_end_at, cylinder_face, cylinder_face_at};pub use topo::{TopoCounts, merged_topology, seam_flags};pub use tspline::tspline_sheet;diff --git a/crates/kernel/src/topo.rs b/crates/kernel/src/topo.rsindex 60be2b42aa..93654c25ba 100644--- a/crates/kernel/src/topo.rs+++ b/crates/kernel/src/topo.rs@@ -645,25 +645,61 @@ pub struct CylinderFace {pub fn cylinder_face_at(b: &Body, p: Vec3) -> Option<CylinderFace> {let size = b.size();- let mesh = b.tessellate((size * 1e-3).max(1e-3)).ok()?;- // The face of the triangle nearest the point.- let mut best: Option<(f64, u32)> = None;+ let tol = (size * 1e-3).max(1e-3);+ let mesh = b.tessellate(tol).ok()?;+ // Each face's distance from the point (its nearest triangle).+ let mut near: HashMap<u32, f64> = HashMap::new();for (t, f) in mesh.triangles.iter().zip(&mesh.tri_face) {let Some([a, bb, c]) = mesh.tri(t) else { continue };- let d = ((a + bb + c) / 3.0).dist(p).min(a.dist(p)).min(bb.dist(p)).min(c.dist(p));- if best.is_none_or(|(bd, _)| d < bd) {- best = Some((d, *f));- }+ let d = crate::boolean_guard::point_triangle_dist(p, a, bb, c);+ near.entry(*f).and_modify(|x| *x = x.min(d)).or_insert(d);}- let (d, face) = best?;- if d > size * 0.05 {+ let nearest = near.values().copied().fold(f64::INFINITY, f64::min);+ if nearest > size * 0.05 {return None;}- let nf = b.face_count();- let tol = (size * 1e-4).max(1e-6);- let surfs = classify_faces(b, &mesh, nf, tol);- let Surf::Cylinder { axis, p: ap, r } = *surfs.get(face as usize)? else { return None };- Some(cylinder_extent(&mesh, face, axis, ap, r))+ let surfs = classify_faces(b, &mesh, b.face_count(), (size * 1e-4).max(1e-6));+ // The facets of a curved face lie off it by up to the mesh's tolerance, so the triangle+ // nearest a point on a hole's wall can be one of the face round its rim (they share the+ // rim's points; in a thin plate the wall is a few long facets). Of the faces within that+ // tolerance of the nearest, the point lies on the one whose own surface it is nearest (a+ // cylinder: within its extent).+ let mut faces: Vec<(u32, f64)> = near.into_iter().filter(|(_, d)| *d <= nearest + tol).collect();+ faces.sort_by_key(|(f, _)| *f);+ let mut best: Option<(f64, Option<CylinderFace>)> = None;+ for (face, d) in faces {+ let (off, cyl) = match surfs.get(face as usize) {+ Some(Surf::Plane { n, d: k }) => (d.min((n.dot(p) - k).abs()), None),+ Some(Surf::Cylinder { axis, p: ap, r }) => {+ let c = cylinder_extent(&mesh, face, *axis, *ap, *r);+ (d.min(c.off(p)), Some(c))+ }+ _ => (d, None),+ };+ if best.as_ref().is_none_or(|(bo, _)| off < *bo) {+ best = Some((off, cyl));+ }+ }+ best?.1+}++/// Face `face` of a body as a cylinder: the axis and radius of its own surface, and its extent+/// along the axis and side read from `mesh` (the body's tessellation, whose faces are the+/// body's). `None` when the face is not part of a cylinder, or has no triangles.+pub fn cylinder_face(b: &Body, mesh: &Mesh, face: usize) -> Option<CylinderFace> {+ let crate::FaceSurface::Cylinder { origin, axis, radius } = crate::face_surface(b, face)? else { return None };+ let axis = axis.normalized()?;+ let c = cylinder_extent(mesh, u32::try_from(face).ok()?, axis, origin, radius);+ (c.start.is_finite() && c.end.is_finite()).then_some(c)+}++impl CylinderFace {+ /// How far `p` is from the face: off its cylinder, and past its ends along the axis.+ pub fn off(&self, p: Vec3) -> f64 {+ let v = p - self.axis_point;+ let along = v.dot(self.axis);+ ((v - self.axis * along).len() - self.radius).abs() + (self.start - along).max(along - self.end).max(0.0)+ }}/// The cylindrical face one of whose end circles is centred at `p` (a circle given by its