Skip to content

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

Sketch: a tangent to an ellipse or a conic touches it and never crosses it (#11535) (#11562)

semmelrinde5a630606a4ec
diff --git a/crates/sketch/src/solver.rs b/crates/sketch/src/solver.rs
index 51f4939345..724c270989 100644
--- a/crates/sketch/src/solver.rs
+++ b/crates/sketch/src/solver.rs
@@ -481,6 +481,48 @@ fn place_pierced_points(sk: &mut Sketch) {
}
/// Distance from `p` to the infinite line through `a`, `b` (signed by side).
+/// What a tangent to a free-form curve has to bring to zero, from the signed gaps of the curve's
+/// samples to the other curve (`closed`: the samples run round): the extremum of the gap nearest
+/// zero, refined between the samples by the parabola through its neighbours. Curves that cross
+/// have a zero gap too, but no extremum there, so a crossing is not taken for a touch (#11535).
+/// An open curve's ends count as extrema too: a touch at its end, or a monotone gap (an open
+/// curve running away from the other), takes the gap nearest zero.
+fn touch_gap(gaps: &[f64], closed: bool) -> f64 {
+ let n = gaps.len();
+ let at = |i: usize, back: bool| -> Option<f64> {
+ let j = match (back, closed) {
+ (true, true) => (i + n - 1) % n,
+ (false, true) => (i + 1) % n,
+ (true, false) => i.checked_sub(1)?,
+ (false, false) => i + 1,
+ };
+ gaps.get(j).copied()
+ };
+ let mut best: Option<f64> = None;
+ for (i, &g) in gaps.iter().enumerate() {
+ let (Some(p), Some(q)) = (at(i, true), at(i, false)) else { continue };
+ if !((g >= p && g >= q) || (g <= p && g <= q)) {
+ continue;
+ }
+ let bend = p - 2.0 * g + q;
+ let v = if bend.abs() > 1e-15 { g - (q - p) * (q - p) / (8.0 * bend) } else { g };
+ let v = if v.is_finite() { v } else { g };
+ if best.is_none_or(|b| v.abs() < b.abs()) {
+ best = Some(v);
+ }
+ }
+ // An open curve's ends are extrema of its gap too (a touch at its end, or a gap that is
+ // monotone and has no other extremum).
+ if !closed && let (Some(&first), Some(&last)) = (gaps.first(), gaps.last()) {
+ for end in [first, last] {
+ if best.is_none_or(|b| end.abs() < b.abs()) {
+ best = Some(end);
+ }
+ }
+ }
+ best.unwrap_or(0.0)
+}
+
fn line_dist(p: Vec2, a: Vec2, b: Vec2) -> f64 {
let d = b - a;
let l = d.len().max(1e-12);
@@ -557,21 +599,26 @@ fn residuals(s: &State, k: &ConstraintKind, out: &mut Vec<f64>) {
Tangent { a, b } => {
let (la, lb) = (s.is_line(a), s.is_line(b));
if s.is_freeform(a) || s.is_freeform(b) {
- // Without a shared end point: the curves touch (closest approach zero).
+ // Without a shared end point: the curves touch (an extremum of the gap is zero).
let (f, o) = if s.is_freeform(a) { (a, b) } else { (b, a) };
- let poly = s.poly(f);
- // Signed gap at the closest approach (smooth through zero, unlike its size).
- let closest = |v: &mut dyn Iterator<Item = f64>| v.fold(f64::INFINITY, |m: f64, x| if x.abs() < m.abs() { x } else { m });
- let d = if s.is_line(o) {
+ let mut poly = s.poly(f);
+ // A closed curve's polyline ends where it starts: its samples run round.
+ let closed = poly.len() > 2 && poly.first().zip(poly.last()).is_some_and(|(p, q)| p.dist(*q) < 1e-9);
+ if closed {
+ poly.pop();
+ }
+ // Signed gaps (smooth through zero, unlike their sizes).
+ let gaps: Vec<f64> = if s.is_line(o) {
let (p0, p1) = s.line(o);
- closest(&mut poly.iter().map(|q| line_dist(*q, p0, p1)))
+ poly.iter().map(|q| line_dist(*q, p0, p1)).collect()
} else if s.is_freeform(o) {
let other = s.poly(o);
- closest(&mut poly.iter().map(|q| crate::curves::polyline_signed_dist(&other, *q)))
+ poly.iter().map(|q| crate::curves::polyline_signed_dist(&other, *q)).collect()
} else {
let (cc, r) = s.round(o);
- closest(&mut poly.iter().map(|q| q.dist(cc) - r))
+ poly.iter().map(|q| q.dist(cc) - r).collect()
};
+ let d = touch_gap(&gaps, closed);
out.push(if d.is_finite() { d } else { 0.0 });
} else if la || lb {
let (l, c) = if la { (a, b) } else { (b, a) };
@@ -3430,3 +3477,23 @@ mod typed_dimension_tests {
assert!(solve(&mut sk).ok());
}
}
+
+#[cfg(test)]
+mod touch_gap_tests {
+ use super::touch_gap;
+
+ /// #11535: an open curve that touches the other at its end (the gap y = 9t^2 - 8t^3 starts at
+ /// zero with zero slope, and has its interior maximum 1.63 further on) has residual zero.
+ #[test]
+ fn an_open_curve_touching_at_its_end_has_no_residual() {
+ let gaps: Vec<f64> = (0..=100).map(|i| f64::from(i) / 100.0).map(|t| 9.0 * t * t - 8.0 * t * t * t).collect();
+ assert!(touch_gap(&gaps, false).abs() < 1e-12);
+ }
+
+ /// A crossing's zero, with a bigger extremum beside it, is not a touch.
+ #[test]
+ fn a_crossing_is_not_a_touch() {
+ let gaps: Vec<f64> = (0..=100).map(|i| (f64::from(i) / 100.0 - 0.5) * 4.0 + 0.2 * (f64::from(i) / 8.0).sin()).collect();
+ assert!(touch_gap(&gaps, false).abs() > 0.5);
+ }
+}
diff --git a/crates/sketch/src/tests.rs b/crates/sketch/src/tests.rs
index 28b072170e..28611967d6 100644
--- a/crates/sketch/src/tests.rs
+++ b/crates/sketch/src/tests.rs
@@ -279,6 +279,94 @@ fn circles_tangent_equal_concentric() {
assert!(sk.center(c3).unwrap().dist(sk.center(c2).unwrap()) < 1e-7);
}
+/// The least and greatest of `gap` over many points along a free-form curve, read from its own
+/// definition (not the solver's polyline).
+fn freeform_gap_range(sk: &Sketch, c: usize, gap: impl Fn(Vec2) -> f64) -> (f64, f64) {
+ let p = |i: usize| sk.points[i].pos;
+ let n = 20_000;
+ let at: Box<dyn Fn(f64) -> Vec2> = match sk.curves[c].kind {
+ CurveKind::Ellipse { c, m, r } => Box::new(move |t| crate::curves::ellipse_point(p(c), p(m), r, t * 2.0 * PI)),
+ CurveKind::Conic { a, b, apex, rho } => Box::new(move |t| crate::curves::conic_point(p(a), p(apex), p(b), rho, t)),
+ _ => panic!("not an ellipse or a conic"),
+ };
+ (0..=n).map(|i| gap(at(i as f64 / n as f64))).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), g| (lo.min(g), hi.max(g)))
+}
+
+/// Touching means the gap reaches zero on one side only: `(least, greatest)` crossing zero is a
+/// crossing.
+fn assert_touches(what: &str, (lo, hi): (f64, f64)) {
+ let near = if lo.abs() < hi.abs() { lo } else { hi };
+ assert!(near.abs() < 1e-3 && (lo > -1e-3 || hi < 1e-3), "{what}: the gap runs from {lo} to {hi}");
+}
+
+/// A tangent to an ellipse or a conic keeps the curves touching, also once the geometry moves:
+/// a crossing has a zero gap as well, and was taken for a touch (#11535).
+#[test]
+fn a_tangent_to_an_ellipse_or_a_conic_touches_and_never_crosses() {
+ use ConstraintKind::*;
+ let side = |a: Vec2, b: Vec2| move |q: Vec2| (b - a).cross(q - a) / a.dist(b);
+ // A line on an ellipse (a 30, b 15), then the line's end dragged to (38, 6).
+ let mut sk = Sketch::new();
+ let (ec, em) = (sk.add_point(v(0.0, 0.0), None).unwrap(), sk.add_point(v(30.0, 0.0), None).unwrap());
+ let e = sk.add_curve(CurveKind::Ellipse { c: ec, m: em, r: 15.0 }, None).unwrap();
+ let l = sk.add_line(v(-20.0, 25.0), v(40.0, 20.0), None, None, None).unwrap();
+ sk.add_constraint(Tangent { a: l, b: e }, None).unwrap();
+ assert!(solve(&mut sk).ok());
+ let (a, b) = line_pts(&sk, l);
+ assert_touches("the line", freeform_gap_range(&sk, e, side(a, b)));
+ let CurveKind::Line { b: end, .. } = sk.curves[l].kind else { panic!("a line") };
+ sk.points[end].pos = v(38.0, 6.0);
+ let hold = Hold { points: vec![ec, em, end], radii: vec![e] };
+ assert!(solve_holding(&mut sk, &hold).ok());
+ let (a, b) = line_pts(&sk, l);
+ assert_touches("the line dragged", freeform_gap_range(&sk, e, side(a, b)));
+
+ // A circle of radius 10 on the same ellipse, then the major axis's end dragged from 30 to 36.
+ let mut sk = Sketch::new();
+ let (ec, em) = (sk.add_point(v(0.0, 0.0), None).unwrap(), sk.add_point(v(30.0, 0.0), None).unwrap());
+ let e = sk.add_curve(CurveKind::Ellipse { c: ec, m: em, r: 15.0 }, None).unwrap();
+ let c = sk.add_circle(v(45.0, 12.0), 10.0, None, None).unwrap();
+ sk.add_constraint(Radius { c, value: 10.0 }, None).unwrap();
+ sk.add_constraint(Tangent { a: e, b: c }, None).unwrap();
+ assert!(solve(&mut sk).ok());
+ let round = |sk: &Sketch| {
+ let (cc, r) = (sk.center(c).unwrap(), sk.radius(c).unwrap());
+ move |q: Vec2| q.dist(cc) - r
+ };
+ assert_touches("the circle", freeform_gap_range(&sk, e, round(&sk)));
+ sk.points[em].pos = v(36.0, 0.0);
+ assert!(solve_holding(&mut sk, &Hold { points: vec![ec, em], radii: vec![e] }).ok());
+ assert_touches("the circle on the longer ellipse", freeform_gap_range(&sk, e, round(&sk)));
+
+ // A line on a conic arch, then the line's end dragged down to (45, 2).
+ let mut sk = Sketch::new();
+ let [ca, cb, apex] = [v(0.0, 0.0), v(40.0, 0.0), v(20.0, 20.0)].map(|p| sk.add_point(p, None).unwrap());
+ let k = sk.add_curve(CurveKind::Conic { a: ca, b: cb, apex, rho: 0.5 }, None).unwrap();
+ let l = sk.add_line(v(-10.0, 15.0), v(50.0, 12.0), None, None, None).unwrap();
+ sk.add_constraint(Tangent { a: l, b: k }, None).unwrap();
+ assert!(solve(&mut sk).ok());
+ let (a, b) = line_pts(&sk, l);
+ assert_touches("the line on the conic", freeform_gap_range(&sk, k, side(a, b)));
+ let CurveKind::Line { b: end, .. } = sk.curves[l].kind else { panic!("a line") };
+ sk.points[end].pos = v(45.0, 2.0);
+ assert!(solve_holding(&mut sk, &Hold { points: vec![ca, cb, apex, end], radii: vec![] }).ok());
+ let (a, b) = line_pts(&sk, l);
+ assert_touches("the line on the conic dragged", freeform_gap_range(&sk, k, side(a, b)));
+
+ // A line that crosses the arch from end to end (x = 20 through the apex's span): the gap is
+ // monotone and ~0 at the crossing, which is not a touch.
+ let mut sk = Sketch::new();
+ let [ca, cb, apex] = [v(0.0, 0.0), v(40.0, 0.0), v(20.0, 20.0)].map(|p| sk.add_point(p, None).unwrap());
+ let k = sk.add_curve(CurveKind::Conic { a: ca, b: cb, apex, rho: 0.5 }, None).unwrap();
+ let l = sk.add_line(v(20.0, -10.0), v(20.0, 40.0), None, None, None).unwrap();
+ sk.add_constraint(Tangent { a: l, b: k }, None).unwrap();
+ // The solver may report it cannot do it, but it must never call the crossing a touch.
+ if solve(&mut sk).ok() {
+ let (a, b) = line_pts(&sk, l);
+ assert_touches("the line across the conic", freeform_gap_range(&sk, k, side(a, b)));
+ }
+}
+
#[test]
fn line_tangent_to_circle_and_angles() {
let mut sk = Sketch::new();