Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Sketch Intersect: a cut through small rounds stays one closed profile (#12722)

MarkusRec1bd94e93738
diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs
index f5e733ceb0..ad9ec10f14 100644
--- a/crates/doc/src/project.rs
+++ b/crates/doc/src/project.rs
@@ -1612,8 +1612,7 @@ pub(crate) fn section(plane: &Plane, m: &Mesh, face: Option<u32>) -> Vec<LinkGeo
let size = m.bounds().diagonal().max(1e-9);
let (segs, exact) = section_segments(plane, m, face);
let segs: Vec<(Vec2, Vec2)> = segs.into_iter().map(|(a, b, _)| (a, b)).collect();
- let loose = size * 2e-3;
- let refine = |v: Vec<LinkGeom>| -> Vec<LinkGeom> { v.into_iter().map(|g| refine_round(g, &exact, loose)).collect() };
+ let refine = |v: Vec<LinkGeom>| -> Vec<LinkGeom> { refine_rounds(v, &exact, size) };
let lossy = refine(fit_segments(&segs, size, false));
// Lines and arcs that follow the section closely (the corners of a rounded profile stay
// where they are) are kept when they take no more curves than the loose fit.
@@ -1785,6 +1784,91 @@ fn section_segments(plane: &Plane, m: &Mesh, face: Option<u32>) -> (Vec<(Vec2, V
(segs, exact.into_inner())
}
+/// Re-fit each circle and arc of a fitted section through the exact section points near it.
+/// The outline stays closed: a line meeting an arc's end moves with it. Where two arcs meet,
+/// their refits stand only while their ends stay within the distance a profile joins ends
+/// across; else both keep their fits, since moving an arc's end would take it off its circle.
+fn refine_rounds(mut v: Vec<LinkGeom>, exact: &[Vec2], size: f64) -> Vec<LinkGeom> {
+ // Ends this close meet: the fit joins crossings this close into one point.
+ let meet = size * 1e-7;
+ let ends = |h: &LinkGeom| match *h {
+ LinkGeom::Arc { a, b, .. } => Some([a, b]),
+ _ => None,
+ };
+ let fitted = v.clone();
+ // Each arc's refit, and whether it stands.
+ let refits: Vec<Option<LinkGeom>> =
+ fitted.iter().map(|g| matches!(g, LinkGeom::Arc { .. }).then(|| refine_round(g.clone(), exact, size * 2e-3))).collect();
+ let mut stands: Vec<bool> = refits.iter().map(Option::is_some).collect();
+ // Where two arcs met as fitted: (arc, its end, other arc, its end).
+ let mut joints = Vec::new();
+ for (i, gi) in fitted.iter().enumerate() {
+ for (j, gj) in fitted.iter().enumerate().skip(i + 1) {
+ let (Some(ei), Some(ej)) = (ends(gi), ends(gj)) else { continue };
+ for (ki, pi) in ei.iter().enumerate() {
+ for (kj, pj) in ej.iter().enumerate() {
+ if pi.dist(*pj) <= meet {
+ joints.push((i, ki, j, kj));
+ }
+ }
+ }
+ }
+ }
+ // Take back both refits at a joint they would tear, until no joint tears.
+ let end_now = |stands: &[bool], i: usize, k: usize| {
+ let g = if stands.get(i).copied().unwrap_or(false) { refits.get(i).and_then(Option::as_ref) } else { fitted.get(i) };
+ g.and_then(ends).and_then(|e| e.get(k).copied())
+ };
+ let mut changed = true;
+ while changed {
+ changed = false;
+ for &(i, ki, j, kj) in &joints {
+ let (Some(p), Some(q)) = (end_now(&stands, i, ki), end_now(&stands, j, kj)) else { continue };
+ if p.dist(q) > solidcraft_sketch::ENDPOINT_JOIN_TOL {
+ for k in [i, j] {
+ if let Some(s) = stands.get_mut(k).filter(|s| **s) {
+ *s = false;
+ changed = true;
+ }
+ }
+ }
+ }
+ }
+ for (i, g) in fitted.iter().enumerate() {
+ match g {
+ LinkGeom::Arc { a: a0, b: b0, .. } => {
+ let (true, Some(refined @ LinkGeom::Arc { a: a1, b: b1, .. })) =
+ (stands.get(i).copied().unwrap_or(false), refits.get(i).and_then(Option::as_ref))
+ else {
+ continue;
+ };
+ for h in v.iter_mut() {
+ if let LinkGeom::Line(s, t) = h {
+ for end in [s, t] {
+ if end.dist(*a0) <= meet {
+ *end = *a1;
+ } else if end.dist(*b0) <= meet {
+ *end = *b1;
+ }
+ }
+ }
+ }
+ if let Some(slot) = v.get_mut(i) {
+ *slot = refined.clone();
+ }
+ }
+ LinkGeom::Circle(..) => {
+ if let Some(slot) = v.get_mut(i) {
+ *slot = refine_round(g.clone(), exact, size * 2e-3);
+ }
+ }
+ // Lines have moved with the arcs they meet; nothing else is refitted.
+ _ => {}
+ }
+ }
+ v
+}
+
/// Re-fit a circle or arc through the exact section points near it, when there are enough.
fn refine_round(g: LinkGeom, exact: &[Vec2], tol: f64) -> LinkGeom {
let (c, r) = match g {
diff --git a/crates/doc/src/project_order.rs b/crates/doc/src/project_order.rs
index 29792b4fe6..ad048adf34 100644
--- a/crates/doc/src/project_order.rs
+++ b/crates/doc/src/project_order.rs
@@ -368,6 +368,133 @@ mod tests {
}
}
+ #[test]
+ fn a_round_refitted_to_the_exact_section_still_meets_its_neighbours() {
+ use solidcore_record::Vec2;
+ use solidcraft_sketch::LinkGeom;
+ let v = Vec2::new;
+ // A 10 x 10 square with an R2 round at its top right corner, fitted from mesh crossings:
+ // the arc misses the round's circle (centre (8, 8)) by 5e-4 but meets the sides exactly.
+ // The exact crossings lie on the circle, and the refit puts the arc on it. The outline has
+ // to stay closed: a profile joins ends only within 1e-4, so a wider gap leaves none (the
+ // R2 rounds of a section at y = 20 through grooved walls, tangency-labs/solidcore#2908).
+ let c = v(7.9995, 7.9995);
+ let (p, q) = (v(10., c.y), v(c.x, 10.));
+ let exact: Vec<Vec2> =
+ (0..=8).map(|k| f64::from(k) * std::f64::consts::FRAC_PI_8 / 2.).map(|t| v(8. + 2. * t.cos(), 8. + 2. * t.sin())).collect();
+ let square = |top: Vec<LinkGeom>| {
+ let mut out = vec![LinkGeom::Line(v(0., 0.), v(10., 0.)), LinkGeom::Line(v(10., 0.), p), LinkGeom::Arc { c, a: p, b: q }];
+ out.extend(top);
+ out.push(LinkGeom::Line(v(0., 10.), v(0., 0.)));
+ out
+ };
+ // The top side a line, or an arc of radius 10 (a shallow round on it) and then a line.
+ let bulge = v(c.x, 20.);
+ let from = bulge + v(-(10f64.to_radians().sin()), -(10f64.to_radians().cos())) * 10.;
+ let cases =
+ [square(vec![LinkGeom::Line(q, v(0., 10.))]), square(vec![LinkGeom::Arc { c: bulge, a: from, b: q }, LinkGeom::Line(from, v(0., 10.))])];
+ // Ends as the sketch takes them: an arc ends on the circle through its start.
+ let ends = |g: &LinkGeom| match *g {
+ LinkGeom::Line(s, t) => vec![s, t],
+ LinkGeom::Arc { c, a, b } => vec![a, c + (b - c).normalized().unwrap_or(Vec2::X) * c.dist(a)],
+ _ => Vec::new(),
+ };
+ for (n, fitted) in cases.into_iter().enumerate() {
+ // The size of the section: the square's diagonal.
+ let out = super::super::refine_rounds(fitted, &exact, 200f64.sqrt());
+ for (i, g) in out.iter().enumerate() {
+ for e in ends(g) {
+ let gap =
+ out.iter().enumerate().filter(|(j, _)| *j != i).flat_map(|(_, h)| ends(h)).map(|x| x.dist(e)).fold(f64::INFINITY, f64::min);
+ assert!(gap < 1e-9, "case {n}: gap {gap} at {e:?}: {out:?}");
+ }
+ }
+ // Where the round meets only lines, the arc lies on the round's circle.
+ if n == 0 {
+ let Some(LinkGeom::Arc { c, a, b }) = out.get(2) else { panic!("{out:?}") };
+ assert!(c.dist(v(8., 8.)) < 1e-9 && (c.dist(*a) - 2.).abs() < 1e-9 && (c.dist(*b) - 2.).abs() < 1e-9, "{out:?}");
+ }
+ }
+ }
+
+ #[test]
+ fn a_round_beside_another_arc_is_refitted_when_their_joint_stays_put() {
+ use solidcore_record::Vec2;
+ use solidcraft_sketch::LinkGeom;
+ let v = Vec2::new;
+ // The R2 round of a 10 x 10 square misses its circle (centre (8, 8)) by `s`, and an arc of
+ // radius 10 runs on from its end. The refit moves that joint by `s`. While that is within
+ // the 1e-4 a profile joins ends across, the round is refitted as before the fix for
+ // tangency-labs/solidcore#2908, and the profile still closes.
+ let exact: Vec<Vec2> =
+ (0..=8).map(|k| f64::from(k) * std::f64::consts::FRAC_PI_8 / 2.).map(|t| v(8. + 2. * t.cos(), 8. + 2. * t.sin())).collect();
+ for s in [1e-8, 1e-6, 1e-5, 5e-5, 9e-5] {
+ let c = v(8., 8. + s);
+ let (p, q) = (v(10., c.y), v(8., 10. + s));
+ let bulge = v(8., 20. + s);
+ let from = bulge + v(-(10f64.to_radians().sin()), -(10f64.to_radians().cos())) * 10.;
+ let fitted = vec![
+ LinkGeom::Line(v(0., 0.), v(10., 0.)),
+ LinkGeom::Line(v(10., 0.), p),
+ LinkGeom::Arc { c, a: p, b: q },
+ LinkGeom::Arc { c: bulge, a: from, b: q },
+ LinkGeom::Line(from, v(0., 10.)),
+ LinkGeom::Line(v(0., 10.), v(0., 0.)),
+ ];
+ let out = super::super::refine_rounds(fitted, &exact, 200f64.sqrt());
+ let (Some(LinkGeom::Arc { c, b, .. }), Some(LinkGeom::Arc { b: joint, .. })) = (out.get(2), out.get(3)) else { panic!("{out:?}") };
+ assert!(c.dist(v(8., 8.)) < 1e-12, "shift {s}: the round is refitted: {out:?}");
+ assert!(b.dist(*joint) < 1e-4, "shift {s}: {out:?}");
+ }
+ }
+
+ #[test]
+ fn two_arcs_refitted_the_same_way_keep_their_joint() {
+ use solidcore_record::Vec2;
+ use solidcraft_sketch::LinkGeom;
+ let v = Vec2::new;
+ // The R2 round of a 10 x 10 square and the arc of radius 10 running on from it both miss
+ // their circles (centres (8, 8) and (8, 20)) by `s` in the same direction. Both refits move
+ // their joint from (8, 10 + s) to (8, 10), so the two refitted arcs still meet, as they do
+ // before the fix for tangency-labs/solidcore#2908, even where `s` is past a profile's 1e-4.
+ let round = (0..=8).map(|k| f64::from(k) * std::f64::consts::FRAC_PI_8 / 2.).map(|t| v(8. + 2. * t.cos(), 8. + 2. * t.sin()));
+ let side = [261., 263., 265., 267., 269.].map(|d: f64| v(8. + 10. * d.to_radians().cos(), 20. + 10. * d.to_radians().sin()));
+ let exact: Vec<Vec2> = round.chain(side).collect();
+ for s in [1e-5, 2e-4, 5e-4] {
+ let c = v(8., 8. + s);
+ let (p, q) = (v(10., c.y), v(8., 10. + s));
+ let bulge = v(8., 20. + s);
+ let from = bulge + v(-(10f64.to_radians().sin()), -(10f64.to_radians().cos())) * 10.;
+ let fitted = vec![
+ LinkGeom::Line(v(0., 0.), v(10., 0.)),
+ LinkGeom::Line(v(10., 0.), p),
+ LinkGeom::Arc { c, a: p, b: q },
+ LinkGeom::Arc { c: bulge, a: from, b: q },
+ LinkGeom::Line(from, v(0., 10.)),
+ LinkGeom::Line(v(0., 10.), v(0., 0.)),
+ ];
+ let out = super::super::refine_rounds(fitted, &exact, 200f64.sqrt());
+ let (Some(LinkGeom::Arc { c: c1, b: b1, .. }), Some(LinkGeom::Arc { c: c2, b: b2, .. })) = (out.get(2), out.get(3)) else {
+ panic!("{out:?}")
+ };
+ assert!(c1.dist(v(8., 8.)) < 1e-9 && c2.dist(v(8., 20.)) < 1e-9, "shift {s}: both arcs are refitted: {out:?}");
+ assert!(b1.dist(*b2) < 1e-4, "shift {s}: {out:?}");
+ // The lines on the arcs' other ends move with them: the whole outline stays closed.
+ let ends = |g: &LinkGeom| match *g {
+ LinkGeom::Line(s, t) => vec![s, t],
+ LinkGeom::Arc { c, a, b } => vec![a, c + (b - c).normalized().unwrap_or(Vec2::X) * c.dist(a)],
+ _ => Vec::new(),
+ };
+ for (i, g) in out.iter().enumerate() {
+ for e in ends(g) {
+ let gap =
+ out.iter().enumerate().filter(|(j, _)| *j != i).flat_map(|(_, h)| ends(h)).map(|x| x.dist(e)).fold(f64::INFINITY, f64::min);
+ assert!(gap < 1e-9, "shift {s}: gap {gap} at {e:?}: {out:?}");
+ }
+ }
+ }
+ }
+
#[test]
fn boundaries_touching_at_a_vertex_project() {
// Two squares of one face family meet only at the corner (1, 1): four boundary edges meet
diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rs
index 21923cddd8..7ebb7aa0ef 100644
--- a/crates/sketch/src/lib.rs
+++ b/crates/sketch/src/lib.rs
@@ -68,8 +68,8 @@ pub use offset_topology::{OffsetCreated, OffsetRole, OffsetRoleFlags, OffsetRole
pub use pattern::{PatternAlignment, PatternInstance, SketchPattern, SketchPatternKind};
pub use periodic::periodic_beziers;
pub use profiles::{
- CurvePick, MAX_PROFILE_EDGES, Profile, ProfileSearch, distinct_curves, find_drawn_profiles, find_profiles, find_profiles_checked, merge_regions,
- profile_at_point, profile_by_curves, without_text_counters,
+ CurvePick, ENDPOINT_JOIN_TOL, MAX_PROFILE_EDGES, Profile, ProfileSearch, distinct_curves, find_drawn_profiles, find_profiles,
+ find_profiles_checked, merge_regions, profile_at_point, profile_by_curves, without_text_counters,
};
pub use shape::{Shape, intersections, intersections_within, nearest_crossing, nearest_curve_intersection};
pub use solver::solve_after_edit_with_analysis;
diff --git a/crates/sketch/src/profiles.rs b/crates/sketch/src/profiles.rs
index dc77d44c66..8fd49f73c3 100644
--- a/crates/sketch/src/profiles.rs
+++ b/crates/sketch/src/profiles.rs
@@ -20,7 +20,10 @@ use crate::shape::{Shape, intersections_within};
use crate::union_find::{find, union};
const MERGE_TOL: f64 = 1e-6;
-const ENDPOINT_JOIN_TOL: f64 = MERGE_TOL * 100.0;
+/// How far apart (mm) curve ends may be and still join into one corner of a profile. Two ends
+/// within it join only when each is the other's unique nearest end, so a third end as near
+/// leaves the gap open.
+pub const ENDPOINT_JOIN_TOL: f64 = MERGE_TOL * 100.0;
const MAX_EDGES: usize = 50_000;
/// A closed region usable by features, with the ids of the curves bounding it.