SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Snap points: a flat face offers its corners, edge middles and every hole's centre (#11476) (#11477)
alfonsotamescccf8c1ece3c
diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rsindex b553d13e0d..e10e88e727 100644--- a/crates/engine/src/snap.rs+++ b/crates/engine/src/snap.rs@@ -1,15 +1,23 @@//! Snap points (#5881): the points a hovered edge or face offers as picks, so a point input//! (Move's From and To, Measure, …) can take a hole's centre or an edge's middle where no vertex//! sits. A round edge offers its centre (an arc also its ends and middle), a straight or other-//! edge its ends and middle, a flat face its centre, a cylinder or cone the centres of its ends,-//! a sphere or torus its centre, a vertex itself. The shapes are Measure's: exact from the+//! edge its ends and middle, a cylinder or cone the centres of its ends, a sphere or torus its+//! centre, a vertex itself. A flat face offers its centre and its whole outline at once (#11476):+//! every corner, the middle of every straight edge and the centre of every round edge, holes+//! included, read from the exact faces and edges. The other shapes are Measure's: exact from the//! kernel where it knows the curve or surface, fitted to the mesh otherwise. World coordinates,//! as the viewport shows the model.+//!+//! [`snap_points_from`] also says where each point came from ([`SnapSource`]): the face, its+//! outward normal and the edge, so a tool can keep the point by name and turn a frame to the face.use serde::Serialize;use solidcore_record::Vec3;+use solidcore_record::brep::{Brep, Curve, Loop};use solidcraft_geom::UnitVec3;+use solidcraft_geom::brep::eval::CurveEval;use solidcraft_geom::prelude::*;+use solidcraft_kernel::{Body, EdgeCircle};use crate::cmd::Shape;use crate::{Sel, Session};@@ -39,26 +47,88 @@ pub struct SnapPoint {pub body: String,}-/// Points closer than this (relative to the item's size) are one snap point.+/// Where a snap point came from, in world coordinates: what a tool needs to keep the point by+/// name as the part changes (`joint.create`'s `{"edge", "corner", "on"}`) and to turn a frame to+/// the face it lies on. Empty for a vertex and for sketch geometry.+#[derive(Clone, Debug, Default, PartialEq, Serialize)]+pub struct SnapSource {+ /// A point on the face that offered the point: where the face was picked.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub face: Option<Vec3>,+ /// Which way the point's face looks, as a unit vector: a flat face's outward normal (out of+ /// the material), or for a cylinder's or cone's end centre the axis pointing out of that end+ /// of the face. That is an axis direction, not always out of the material: at a blind hole's+ /// bottom it points into the material below.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub normal: Option<Vec3>,+ /// A point inside the edge the point belongs to: the edge a corner starts, the straight edge a+ /// middle halves, the round edge a centre is the centre of, or the picked edge itself.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub edge: Option<Vec3>,+}++/// Two round edges' radii closer than this (relative to the radii) are one circle.const SAME: f64 = 1e-6;+/// Points of one kind closer than this (relative to how far from the origin they are) are one+/// place: well above the rounding of coordinates there and of a circle fitted to an imported+/// edge, so a point found twice is one, and far below any feature, so distinct points stay apart+/// far from the origin too (0.06 µm at 60 m, where `SAME` would be 0.06 mm).+const SAME_PLACE: f64 = 1e-9;++/// The most edges of one face whose points a flat face offers: a face with more (an imported+/// lattice) offers those of its first edges.+const MAX_OUTLINE_EDGES: usize = 4096;++/// A point found on an item, its kind and where it came from.+pub(crate) type Found = (Vec3, SnapKind, SnapSource);+/// The snap points `sel` offers: none for things with no points to offer (a body, a plane).pub fn snap_points(s: &Session, sel: &Sel) -> Vec<SnapPoint> {+ snap_points_from(s, sel).into_iter().map(|(p, _)| p).collect()+}++/// [`snap_points`], each with where it came from.+pub fn snap_points_from(s: &Session, sel: &Sel) -> Vec<(SnapPoint, SnapSource)> {let body = match sel {Sel::Edge { body, .. } | Sel::Face { body, .. } | Sel::Vertex { body, .. } => body.clone(),_ => String::new(),};+ let tagged =+ |points: Vec<(Vec3, SnapKind)>, from: SnapSource| -> Vec<Found> { points.into_iter().map(|(at, kind)| (at, kind, from.clone())).collect() };let found = match sel {- Sel::Vertex { point, .. } => vec![(*point, SnapKind::Vertex)],- Sel::Edge { .. } | Sel::SketchCurve { .. } | Sel::ExternalSketchCurve { .. } => edge_points(s, sel),+ Sel::Vertex { point, .. } => vec![(*point, SnapKind::Vertex, SnapSource::default())],+ Sel::Edge { point, .. } => tagged(edge_points(s, sel), SnapSource { edge: Some(*point), ..SnapSource::default() }),+ Sel::SketchCurve { .. } | Sel::ExternalSketchCurve { .. } => tagged(edge_points(s, sel), SnapSource::default()),Sel::Face { .. } => face_points(s, sel),_ => Vec::new(),};- let mut out: Vec<SnapPoint> = Vec::new();- for (at, kind) in found {- let tol = SAME * (1.0 + at.len());- if at.is_finite() && !out.iter().any(|p| p.at.dist(at) <= tol) {- out.push(SnapPoint { at, kind, body: body.clone() });+ merged(found, &body)+}++/// The points found on an item as snap points, a point found twice kept once.+pub(crate) fn merged(found: Vec<Found>, body: &str) -> Vec<(SnapPoint, SnapSource)> {+ // A round edge's centre with the radius its rim has (the rim point is on the circle).+ let radius = |at: Vec3, from: &SnapSource| from.edge.map(|rim| rim.dist(at));+ let mut out: Vec<(SnapPoint, SnapSource)> = Vec::new();+ for (at, kind, from) in found {+ let tol = SAME_PLACE * (1.0 + at.len());+ // Only points of one kind are one point: a hole centred on its face is both the face's+ // centre and the hole's, and only the hole's keeps its rim. Centres are one point only+ // on one circle: a washer's two rims keep a centre each, while the pieces the kernel+ // split one circle into are one.+ let r = radius(at, &from);+ let one_circle = |other: Option<f64>| match (other, r) {+ // By the radii's own size, not the place's: far from the origin two close rims+ // would otherwise count as one.+ (Some(a), Some(b)) => (a - b).abs() <= SAME * (1.0 + a.max(b)),+ (None, None) => true,+ _ => false,+ };+ let same =+ |(p, f): &(SnapPoint, SnapSource)| p.kind == kind && p.at.dist(at) <= tol && (kind != SnapKind::Centre || one_circle(radius(p.at, f)));+ if at.is_finite() && !out.iter().any(same) {+ out.push((SnapPoint { at, kind, body: body.to_string() }, from));}}out@@ -155,28 +225,101 @@ fn along(pts: &[Vec3], f: f64) -> Option<Vec3> {pts.last().copied()}-/// A face's points: a flat face its area's centre; a cylinder or cone the centres of its two-/// ends on the axis; a sphere or torus its centre.-fn face_points(s: &Session, sel: &Sel) -> Vec<(Vec3, SnapKind)> {- let Sel::Face { body, index, .. } = sel else { return Vec::new() };+/// A face's points: a flat face its area's centre and its outline ([`outline_points`]); a+/// cylinder or cone the centres of its two ends on the axis; a sphere or torus its centre.+fn face_points(s: &Session, sel: &Sel) -> Vec<Found> {+ let Sel::Face { body, index, point } = sel else { return Vec::new() };let Ok(st) = s.world_state() else { return Vec::new() };let Some(b) = st.body(body) else { return Vec::new() };let Some((shape, _, tris)) = crate::cmd::shape_of(s, sel) else { return Vec::new() };let verts: Vec<Vec3> = tris.iter().flat_map(|t| t.iter().copied()).collect();+ let on = SnapSource { face: Some(*point), ..SnapSource::default() };+ let tagged = |points: Vec<(Vec3, SnapKind)>| -> Vec<Found> { points.into_iter().map(|(at, kind)| (at, kind, on.clone())).collect() };match solidcraft_kernel::face_surface(&b.body, *index) {Some(solidcraft_kernel::FaceSurface::Sphere { center, .. } | solidcraft_kernel::FaceSurface::Torus { center, .. }) => {- return vec![(center, SnapKind::Centre)];+ return tagged(vec![(center, SnapKind::Centre)]);}- Some(solidcraft_kernel::FaceSurface::Cone { apex, axis, .. }) => return axis_ends(apex, axis, &verts),+ Some(solidcraft_kernel::FaceSurface::Cone { apex, axis, .. }) => return ends_out(axis_ends(apex, axis, &verts), axis, &on),_ => {}}match shape {- Shape::Round { center, axis, .. } => axis_ends(center, axis, &verts),- Shape::Plane { .. } => area_centre(&tris).map(|p| vec![(p, SnapKind::FaceCentre)]).unwrap_or_default(),+ Shape::Round { center, axis, .. } => ends_out(axis_ends(center, axis, &verts), axis, &on),+ Shape::Plane { .. } => {+ let flat = SnapSource { normal: b.body.planar_face(*index).and_then(|p| p.normal().normalized()), ..on.clone() };+ let mut v: Vec<Found> = area_centre(&tris).map(|p| vec![(p, SnapKind::FaceCentre, flat.clone())]).unwrap_or_default();+ v.extend(outline_points(&b.body, *index).into_iter().map(|(at, kind, edge)| (at, kind, SnapSource { edge: Some(edge), ..flat.clone() })));+ v+ }_ => Vec::new(),}}+/// A flat face's outline from the exact record: every corner (where one edge ends and another+/// begins, but not where a round edge runs on into the next piece of its circle, nor on a closed+/// circle's seam), the middle of every straight edge and the centre of every round edge, holes+/// included. Each comes with a point inside the edge it belongs to, which finds that edge again.+fn outline_points(body: &Body, face: usize) -> Vec<(Vec3, SnapKind, Vec3)> {+ let record = body.record();+ let Some(f) = record.faces.get(face) else { return Vec::new() };+ let tol = (body.size() * 1e-7).max(1e-9) * 100.0;+ let mut out = Vec::new();+ let mut left = MAX_OUTLINE_EDGES;+ for l in &f.loops {+ let Loop::Edges { edges } = l else { continue };+ let edges = &edges[..edges.len().min(left)];+ left -= edges.len();+ let circles: Vec<Option<EdgeCircle>> = edges.iter().map(|oe| solidcraft_kernel::edge_circle(body, oe.edge as usize)).collect();+ for (i, oe) in edges.iter().enumerate() {+ let Some(e) = record.edges.get(oe.edge as usize) else { continue };+ let Some(c) = CurveEval::new(e.parameters()).ok() else { continue };+ let [t0, t1] = e.interval;+ let Some(inside) = c.point((t0 + t1) * 0.5) else { continue };+ match (circles.get(i).and_then(Option::as_ref), &e.curve) {+ (Some(circle), _) => out.push((circle.center, SnapKind::Centre, inside)),+ (None, Curve::Line { .. }) => {+ if let (Some(a), Some(b)) = (c.point(t0), c.point(t1)) {+ out.push((a.lerp(b, 0.5), SnapKind::Middle, inside));+ }+ }+ _ => {}+ }+ // The corner this edge starts from in the loop.+ if e.vertices[0] == e.vertices[1] {+ continue;+ }+ let previous = i.checked_sub(1).unwrap_or(edges.len().saturating_sub(1));+ let runs_on = match (circles.get(previous).and_then(Option::as_ref), circles.get(i).and_then(Option::as_ref)) {+ (Some(a), Some(b)) if previous != i => same_circle(a, b, tol),+ _ => false,+ };+ let start = if oe.forward { e.vertices[0] } else { e.vertices[1] };+ if let (false, Some(p)) = (runs_on, vertex(record, start)) {+ out.push((p, SnapKind::End, inside));+ }+ }+ if left == 0 {+ break;+ }+ }+ out+}++/// Whether two round edges lie on one circle: one circle the kernel split into pieces.+fn same_circle(a: &EdgeCircle, b: &EdgeCircle, tol: f64) -> bool {+ a.center.dist(b.center) <= tol && (a.radius - b.radius).abs() <= tol && a.axis.dot(b.axis).abs() >= 1.0 - 1e-9+}++/// Vertex `i`'s point.+fn vertex(record: &Brep, i: u32) -> Option<Vec3> {+ record.vertices.get(i as usize).map(|v| Vec3::from(v.point)).filter(|p| p.is_finite())+}++/// A round face's two end centres (lower along `axis` first), each with the axis pointing out of+/// its end as the normal: the normal of the face a hole opens onto, or of a pin's end.+fn ends_out(ends: Vec<(Vec3, SnapKind)>, axis: UnitVec3, on: &SnapSource) -> Vec<Found> {+ ends.into_iter().zip([-axis.vec(), axis.vec()]).map(|((at, kind), out)| (at, kind, SnapSource { normal: Some(out), ..on.clone() })).collect()+}+/// The points of the axis through `origin` along `axis` level with the face's two ends.fn axis_ends(origin: Vec3, axis: UnitVec3, verts: &[Vec3]) -> Vec<(Vec3, SnapKind)> {let along = || verts.iter().map(|p| (*p - origin).dot(axis));diff --git a/crates/engine/src/snap_tests.rs b/crates/engine/src/snap_tests.rsindex 249e8f5d4a..90fa1b10ac 100644--- a/crates/engine/src/snap_tests.rs+++ b/crates/engine/src/snap_tests.rs@@ -7,7 +7,7 @@ use std::f64::consts::{FRAC_1_SQRT_2, PI};use serde_json::{Value, json};use solidcore_record::Vec3;-use crate::snap::{SnapKind, SnapPoint, snap_points};+use crate::snap::{SnapKind, SnapPoint, SnapSource, snap_points, snap_points_from};use crate::{Sel, Session};fn run(s: &mut Session, id: &str, p: Value) {@@ -86,7 +86,7 @@ fn a_straight_edge_offers_its_ends_and_middle() {}#[test]-fn a_flat_face_offers_the_centre_of_its_area() {+fn a_flat_face_offers_its_centre_corners_edge_middles_and_hole_centres() {let s = plate();let top = face(&s, |p| (p.z - 10.0).abs() < 1e-9);// The plate's area less the two holes, each holding its area at its centre.@@ -95,7 +95,111 @@ fn a_flat_face_offers_the_centre_of_its_area() {let got = snap_points(&s, &top);// The holes' circles are tessellated, so their areas are a little off.assert!(same(&of(&got, SnapKind::FaceCentre), &[Vec3::new(x, 20.0, 10.0)], 0.02), "want x = {x}: {got:?}");- assert_eq!(got.len(), 1, "{got:?}");+ let at = |x: f64, y: f64| Vec3::new(x, y, 10.0);+ let corners = [at(0.0, 0.0), at(60.0, 0.0), at(60.0, 40.0), at(0.0, 40.0)];+ assert!(same(&of(&got, SnapKind::End), &corners, 1e-9), "the four corners, none on a hole's seam: {got:?}");+ let middles = [at(30.0, 0.0), at(60.0, 20.0), at(30.0, 40.0), at(0.0, 20.0)];+ assert!(same(&of(&got, SnapKind::Middle), &middles, 1e-9), "{got:?}");+ assert!(same(&of(&got, SnapKind::Centre), &[at(15.0, 20.0), at(45.0, 20.0)], 1e-9), "both holes' centres: {got:?}");+ assert_eq!(got.len(), 11, "{got:?}");+}++#[test]+fn a_flat_faces_points_say_which_face_and_edge_they_came_from() {+ let s = plate();+ let top = face(&s, |p| (p.z - 10.0).abs() < 1e-9);+ let Sel::Face { point: pick, .. } = top else { panic!("the top is a face pick") };+ let got = snap_points_from(&s, &top);+ assert!(got.iter().all(|(_, from)| from.face == Some(pick)), "{got:?}");+ assert!(got.iter().all(|(_, from)| from.normal.is_some_and(|n| n.dist(Vec3::Z) < 1e-12)), "out of the material: {got:?}");+ let source = |want: Vec3| got.iter().find(|(p, _)| p.at.dist(want) < 1e-9).map(|(_, from)| from.edge);+ // The face's centre belongs to no edge; a middle to its own edge; a corner to an edge that+ // starts there; a hole's centre to its rim.+ assert_eq!(got.iter().find(|(p, _)| p.kind == SnapKind::FaceCentre).map(|(_, from)| from.edge), Some(None));+ assert_eq!(source(Vec3::new(30.0, 0.0, 10.0)), Some(Some(Vec3::new(30.0, 0.0, 10.0))));+ let corner = source(Vec3::ZERO + Vec3::new(0.0, 0.0, 10.0)).flatten().unwrap();+ assert!([Vec3::new(30.0, 0.0, 10.0), Vec3::new(0.0, 20.0, 10.0)].iter().any(|m| m.dist(corner) < 1e-9), "{corner:?}");+ let rim = source(Vec3::new(45.0, 20.0, 10.0)).flatten().unwrap();+ assert!((rim.dist(Vec3::new(45.0, 20.0, 10.0)) - 4.0).abs() < 1e-9 && (rim.z - 10.0).abs() < 1e-9, "{rim:?}");++ let bottom = face(&s, |p| p.z.abs() < 1e-9);+ let got = snap_points_from(&s, &bottom);+ assert!(got.iter().all(|(_, from)| from.normal.is_some_and(|n| n.dist(-Vec3::Z) < 1e-12)), "{got:?}");++ let front = edge(&s, |p| p.y.abs() < 1e-9 && (p.z - 10.0).abs() < 1e-9);+ let Sel::Edge { point, .. } = front else { panic!("the front is an edge pick") };+ let got = snap_points_from(&s, &front);+ assert!(got.iter().all(|(_, from)| *from == SnapSource { edge: Some(point), ..SnapSource::default() }), "{got:?}");+}++#[test]+fn a_face_with_a_hundred_holes_offers_every_centre() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 110, "width": 110, "height": 5}));+ run(&mut s, "solid.cylinder", json!({"radius": 2, "height": 7, "base": [10, 10, -1], "operation": "cut", "name": "Hole"}));+ run(+ &mut s,+ "solid.pattern.rectangular",+ json!({"features": ["Hole"], "dir1": [1, 0, 0], "count1": 10, "spacing1": 10, "dir2": [0, 1, 0], "count2": 10, "spacing2": 10}),+ );+ let top = face(&s, |p| (p.z - 5.0).abs() < 1e-9);+ let got = snap_points(&s, &top);+ let want: Vec<Vec3> = (0..100).map(|k| Vec3::new(10.0 + 10.0 * f64::from(k % 10), 10.0 + 10.0 * f64::from(k / 10), 5.0)).collect();+ assert!(same(&of(&got, SnapKind::Centre), &want, 1e-9), "{} centres: {got:?}", of(&got, SnapKind::Centre).len());+ assert_eq!(of(&got, SnapKind::End).len(), 4, "the plate's corners only: {got:?}");+}++#[test]+fn a_rounded_outline_offers_its_tangent_corners_and_its_rounds_centres() {+ // A 40 × 40 tube end: 4 mm rounds outside, a sharp 34 × 34 opening inside.+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 20}));+ run(&mut s, "solid.fillet", json!({"edges": [[0, 0, 10], [40, 0, 10], [40, 40, 10], [0, 40, 10]], "radius": 4}));+ run(&mut s, "solid.box", json!({"corner": [3, 3, -1], "length": 34, "width": 34, "height": 22, "operation": "cut"}));+ let top = face(&s, |p| (p.z - 20.0).abs() < 1e-9);+ let got = snap_points(&s, &top);+ let at = |x: f64, y: f64| Vec3::new(x, y, 20.0);+ let rounds = [at(4.0, 4.0), at(36.0, 4.0), at(36.0, 36.0), at(4.0, 36.0)];+ assert!(same(&of(&got, SnapKind::Centre), &rounds, 1e-9), "{got:?}");+ let mut ends: Vec<Vec3> = [(4.0, 0.0), (36.0, 0.0), (40.0, 4.0), (40.0, 36.0), (36.0, 40.0), (4.0, 40.0), (0.0, 36.0), (0.0, 4.0)]+ .into_iter()+ .map(|(x, y)| at(x, y))+ .collect();+ ends.extend([at(3.0, 3.0), at(37.0, 3.0), at(37.0, 37.0), at(3.0, 37.0)]);+ assert!(same(&of(&got, SnapKind::End), &ends, 1e-9), "where each round meets a side, and the opening's corners: {got:?}");+ let middles = [at(20.0, 0.0), at(40.0, 20.0), at(20.0, 40.0), at(0.0, 20.0), at(20.0, 3.0), at(37.0, 20.0), at(20.0, 37.0), at(3.0, 20.0)];+ assert!(same(&of(&got, SnapKind::Middle), &middles, 1e-9), "{got:?}");+}++#[test]+fn a_moved_parts_face_offers_its_points_where_the_part_stands() {+ let mut s = plate();+ run(&mut s, "component.create", json!({"name": "Plate", "parent": "root", "activate": false}));+ run(&mut s, "component.move_bodies", json!({"bodies": ["Body1"], "component": "Plate"}));+ run(&mut s, "occurrence.ground", json!({"occurrence": "Plate:1", "grounded": false}));+ run(&mut s, "occurrence.move", json!({"occurrence": "Plate:1", "translate": [100, 0, 30]}));+ let st = s.world_state().unwrap();+ let b = st.bodies.first().unwrap();+ let m = b.mesh();+ // The face on top, now at z = 40: the plate moved 100 along x and 30 up.+ let on_top = |f: &u32| {+ m.triangles+ .iter()+ .zip(&m.tri_face)+ .filter(|(_, tf)| *tf == f)+ .filter_map(|(t, _)| m.tri(t))+ .all(|t| t.iter().all(|p| (p.z - 40.0).abs() < 1e-9))+ };+ let f = m.tri_face.iter().copied().find(on_top).unwrap();+ let pick = m.triangles.iter().zip(&m.tri_face).find(|(_, tf)| **tf == f).and_then(|(t, _)| m.tri(t)).unwrap()[0];+ let top = sel(json!({"type": "face", "body": b.name, "index": f, "point": pick}));+ let got = snap_points_from(&s, &top);+ let placed = |x: f64, y: f64| Vec3::new(x + 100.0, y, 40.0);+ let corners = [placed(0.0, 0.0), placed(60.0, 0.0), placed(60.0, 40.0), placed(0.0, 40.0)];+ let points: Vec<_> = got.iter().map(|(p, _)| p.clone()).collect();+ assert!(same(&of(&points, SnapKind::End), &corners, 1e-9), "{got:?}");+ assert!(same(&of(&points, SnapKind::Centre), &[placed(15.0, 20.0), placed(45.0, 20.0)], 1e-9), "{got:?}");+ assert!(got.iter().all(|(_, from)| from.normal.is_some_and(|n| n.dist(Vec3::Z) < 1e-12)), "{got:?}");}#[test]@@ -138,3 +242,80 @@ fn things_without_points_offer_none() {assert!(snap_points(&s, &sel(v.clone())).is_empty(), "{v}");}}++#[test]+fn a_round_faces_end_centres_point_out_of_their_ends() {+ let s = plate();+ let wall = face(&s, |p| ((p - Vec3::new(15.0, 20.0, p.z)).len() - 3.0).abs() < 1e-3);+ let got = snap_points_from(&s, &wall);+ let normal_at = |z: f64| got.iter().find(|(p, _)| p.at.dist(Vec3::new(15.0, 20.0, z)) < 1e-6).and_then(|(_, from)| from.normal);+ assert!(normal_at(0.0).is_some_and(|n| n.dist(-Vec3::Z) < 1e-9), "the bottom end, out of the plate's bottom: {got:?}");+ assert!(normal_at(10.0).is_some_and(|n| n.dist(Vec3::Z) < 1e-9), "the top end, out of its top: {got:?}");+}++#[test]+fn a_hole_centred_on_its_face_is_both_the_faces_centre_and_the_holes() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 60, "width": 40, "height": 10}));+ run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 12, "base": [30, 20, -1], "operation": "cut"}));+ let top = face(&s, |p| (p.z - 10.0).abs() < 1e-9);+ let got = snap_points_from(&s, &top);+ let at = Vec3::new(30.0, 20.0, 10.0);+ let here: Vec<_> = got.iter().filter(|(p, _)| p.at.dist(at) < 0.02).collect();+ assert_eq!(here.iter().map(|(p, _)| p.kind).collect::<Vec<_>>(), [SnapKind::FaceCentre, SnapKind::Centre], "{got:?}");+ // Only the hole's centre keeps its rim: a point on the circle of radius 4 about it.+ assert!(here[0].1.edge.is_none(), "{:?}", here[0]);+ let rim = here[1].1.edge.unwrap();+ assert!((rim.dist(at) - 4.0).abs() < 1e-9 && (rim.z - 10.0).abs() < 1e-9, "{rim:?}");+}++#[test]+fn a_washers_two_rims_keep_a_centre_each() {+ // A Ø20 × 5 disc with a Ø8 hole through its middle: its top is a washer.+ let mut s = Session::default();+ run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 5, "base": [0, 0, 0]}));+ run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 7, "base": [0, 0, -1], "operation": "cut"}));+ let top = face(&s, |p| (p.z - 5.0).abs() < 1e-9);+ let got = snap_points_from(&s, &top);+ let at = Vec3::new(0.0, 0.0, 5.0);+ let mut radii: Vec<f64> = got+ .iter()+ .filter(|(p, _)| p.kind == SnapKind::Centre && p.at.dist(at) < 1e-9)+ .filter_map(|(p, from)| from.edge.map(|e| e.dist(p.at)))+ .collect();+ radii.sort_by(f64::total_cmp);+ assert!(radii.len() == 2 && (radii[0] - 4.0).abs() < 1e-9 && (radii[1] - 10.0).abs() < 1e-9, "one centre per rim: {got:?}");+}++#[test]+fn a_washer_far_from_the_origin_keeps_both_its_rims() {+ // Rims of 4 and 4.05 around (60000, 0, 5): 60 m out, the place's own tolerance is wider than+ // the 0.05 between them, so the rims are told apart by their radii.+ let mut s = Session::default();+ run(&mut s, "solid.cylinder", json!({"radius": 4.05, "height": 5, "base": [60000, 0, 0]}));+ run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 7, "base": [60000, 0, -1], "operation": "cut"}));+ let top = face(&s, |p| (p.z - 5.0).abs() < 1e-9);+ let got = snap_points_from(&s, &top);+ let at = Vec3::new(60000.0, 0.0, 5.0);+ let mut radii: Vec<f64> = got+ .iter()+ .filter(|(p, _)| p.kind == SnapKind::Centre && p.at.dist(at) < 1e-6)+ .filter_map(|(p, from)| from.edge.map(|e| e.dist(p.at)))+ .collect();+ radii.sort_by(f64::total_cmp);+ assert!(radii.len() == 2 && (radii[0] - 4.0).abs() < 1e-6 && (radii[1] - 4.05).abs() < 1e-6, "one centre per rim: {radii:?} in {got:?}");+}++#[test]+fn nearby_holes_far_from_the_origin_keep_a_centre_each() {+ // Two Ø0.02 holes whose centres are 0.05 apart, 60 m out: a tolerance that grew with the+ // distance from the origin like the radii's would make them one.+ let rim = |c: Vec3| crate::snap::SnapSource { edge: Some(c + Vec3::new(0.01, 0.0, 0.0)), ..crate::snap::SnapSource::default() };+ let (a, b) = (Vec3::new(60000.0, 0.0, 5.0), Vec3::new(60000.05, 0.0, 5.0));+ let found = vec![(a, SnapKind::Centre, rim(a)), (b, SnapKind::Centre, rim(b))];+ let got = crate::snap::merged(found, "Body1");+ assert_eq!(got.iter().map(|(p, _)| p.at).collect::<Vec<_>>(), [a, b], "{got:?}");+ // A point found twice, rounded a little differently, is still one.+ let twice = vec![(a, SnapKind::End, rim(a)), (a + Vec3::new(1e-9, 0.0, 0.0), SnapKind::End, rim(a))];+ assert_eq!(crate::snap::merged(twice, "Body1").len(), 1);+}