SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
2-tangent circle: start from the touching circle, not the click (#3141) (#3210)
phanoobf81549193685
diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rsindex dc54235933..b97d7dd4a4 100644--- a/crates/engine/src/cmd/sketch_create.rs+++ b/crates/engine/src/cmd/sketch_create.rs@@ -3,7 +3,7 @@use serde_json::{Value, json};use solidcraft_geom::Vec2;-use solidcraft_sketch::{ConstraintKind, CurveKind, LinkKind, LinkSource, Sketch, TextAlign, TextExprs, TextStyle};+use solidcraft_sketch::{ConstraintKind, CurveKind, LinkKind, LinkSource, Shape, Sketch, TextAlign, TextExprs, TextStyle};/// The style parameters of `sketch.text` and `sketch.edit_text`.macro_rules! text_style_doc {@@ -822,6 +822,39 @@ fn guess_radius(sk: &Sketch, curves: &[usize], at: Vec2) -> f64 {if r.is_finite() && r > 1e-6 { r } else { 1.0 }}+/// Where the centre of a circle of radius `d` touching `sh` can lie: the line moved `d` to either+/// side, or the circle grown and shrunk by `d` (arcs as their full circle).+fn centre_paths(sh: &Shape, d: f64) -> Vec<Shape> {+ match *sh {+ Shape::Line { a, b } => {+ (b - a).normalized().map(|u| [d, -d].map(|s| Shape::Line { a: a + u.perp() * s, b: b + u.perp() * s }).to_vec()).unwrap_or_default()+ }+ Shape::Round { c, r, .. } => [r + d, (r - d).abs()]+ .into_iter()+ .filter(|x| *x > 1e-12)+ .map(|r| Shape::Round { c, r, start: 0.0, sweep: std::f64::consts::TAU })+ .collect(),+ }+}++/// The centre nearest `near` of a circle of radius `r` touching curves `a` and `b` (#3141): the+/// solver starts from the answer instead of from the click, which lies on a curve, where the+/// tangency has no side yet and the solve fails or moves the curves.+fn tangent_centre(sk: &Sketch, a: usize, b: usize, r: f64, near: Vec2) -> Option<Vec2> {+ let (sa, sb) = (sk.shape(a)?, sk.shape(b)?);+ let mut best: Option<Vec2> = None;+ for x in centre_paths(&sa, r) {+ for y in centre_paths(&sb, r) {+ for q in solidcraft_sketch::intersections_within(&x, &y, 1e-9 * (1.0 + r)) {+ if q.x.is_finite() && q.y.is_finite() && best.is_none_or(|b| q.dist(near) < b.dist(near)) {+ best = Some(q);+ }+ }+ }+ }+ best+}+fn tangent_curves(sk: &Sketch, p: &Value, cmd: &str, n: usize) -> Result<Vec<usize>> {let ids = string_list(p, "curves");if ids.len() != n {@@ -842,10 +875,14 @@ fn tangent_circle(s: &mut Session, p: &Value, cmd: &str, n: usize, radius: Optioif !(r0 > 1e-9 && r0 < 1e8) {return Err(bad(cmd, "radius must be positive"));}- // Start where the circle already nearly touches: move the centre so the guessed circle- // sits between the curves.+ // Start where the circle already touches when that can be worked out (two curves and a+ // radius), so that only the new circle moves.+ let start = match cs.as_slice() {+ [a, b] if radius.is_some() => tangent_centre(sk, *a, *b, r0, near).unwrap_or(near),+ _ => near,+ };let first_new = sk.points.len();- let c = sk.add_circle(near, r0, None, None)?;+ let c = sk.add_circle(start, r0, None, None)?;let mut cons = Vec::new();for k in &cs {cons.push(add_c(sk, ConstraintKind::Tangent { a: *k, b: c })?);diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rsindex a65fbf2583..63de01fec0 100644--- a/crates/engine/src/cmd/sketch_modify_tests.rs+++ b/crates/engine/src/cmd/sketch_modify_tests.rs@@ -438,6 +438,51 @@ fn new_creation_tools() {assert!(a.iter().any(|x| close(*x, pi * 5.0 * 2.0 + pi)), "{a:?}");}+/// #3141: a 2-tangent circle asked for near a point on one of its curves (where a click on that+/// curve puts it) is solved from the touching circle nearest that point: it lands in the corner,+/// the rectangle stays as drawn, and fixed sides no longer make it fail.+#[test]+fn two_tangent_circle_from_a_click_on_a_curve_leaves_the_curves_as_drawn() {+ let side = |s: &Session, sides: &[String], on: fn(Vec2) -> bool| -> String {+ let sk = sketch(s);+ sides+ .iter()+ .find(|c| {+ let i = sk.curve_index(c).unwrap();+ matches!(sk.shape(i), Some(solidcraft_sketch::Shape::Line { a, b }) if on(a) && on(b))+ })+ .unwrap()+ .clone()+ };+ let points = |s: &Session| sketch(s).points.iter().map(|p| p.pos).collect::<Vec<_>>();+ for fixed in [false, true] {+ let mut s = new_sketch();+ let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-800, 0], "p1": [-300, 500]}));+ let sides = ids(&r["curves"]);+ if fixed {+ run(&mut s, "sketch.constraint.fix", json!({"entities": sides}));+ }+ let before = points(&s);+ let bottom = side(&s, &sides, |p| p.y.abs() < 1e-9);+ let left = side(&s, &sides, |p| (p.x + 800.0).abs() < 1e-9);+ // Midway between a click on the bottom side and one on the left side.+ let r = run(&mut s, "sketch.circle.two_tangent", json!({"curves": [bottom, left], "radius": 50, "near": [-675, 125]}));+ let c = ids(&r["curves"])[0].clone();+ let sk = sketch(&s);+ let ci = sk.curve_index(&c).unwrap();+ assert!(sk.center(ci).unwrap().dist(Vec2::new(-750.0, 50.0)) < 1e-6, "fixed {fixed}: {:?}", sk.center(ci));+ assert!(close(sk.radius(ci).unwrap(), 50.0));+ let after = points(&s);+ assert!(before.iter().zip(&after).all(|(a, b)| a.dist(*b) < 1e-9), "fixed {fixed}: the rectangle did not move: {after:?}");+ // Asked for right on the left side: still a touching circle next to it.+ let r = run(&mut s, "sketch.circle.two_tangent", json!({"curves": [bottom, left], "radius": 20, "near": [-800, 30]}));+ let c = ids(&r["curves"])[0].clone();+ let sk = sketch(&s);+ let o = sk.center(sk.curve_index(&c).unwrap()).unwrap();+ assert!(close(o.y, 20.0) && close((o.x + 800.0).abs(), 20.0), "fixed {fixed}: {o:?}");+ }+}+#[test]fn ellipse_splines_conic() {let pi = std::f64::consts::PI;diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rsindex aada4300c7..08c7748378 100644--- a/crates/sketch/src/lib.rs+++ b/crates/sketch/src/lib.rs@@ -63,7 +63,7 @@ pub use profiles::{CurvePick, Profile, distinct_curves, find_drawn_profiles, find_profiles, merge_regions, profile_at_point, profile_by_curves,without_text_counters,};-pub use shape::{Shape, intersections};+pub use shape::{Shape, intersections, intersections_within};pub use solver::solve_after_edit_with_analysis;pub use solver::{Analysis, CONSISTENT, DrivingValues, Hold, SolveReport, SolveStatus, constraint_residual, determined_by, measure_dimension, move_line_towards,diff --git a/crates/ui-egui/src/sketch_corner_ui_tests.rs b/crates/ui-egui/src/sketch_corner_ui_tests.rsindex 5a2b629fbb..d0b602123e 100644--- a/crates/ui-egui/src/sketch_corner_ui_tests.rs+++ b/crates/ui-egui/src/sketch_corner_ui_tests.rs@@ -649,3 +649,33 @@ fn trim_hover_shows_the_piece_a_click_takes_away() {h.step(&json!({"move":{"world":[15,0,0]}})).unwrap();assert!(trim_hover_piece(&h.app, sid, &line).is_none(), "only Trim shows a piece");}++/// #3141: the 2-tangent circle tool, clicked on two sides of a rectangle drawn away from the+/// origin, puts its circle in the corner between the clicks without moving the rectangle, and+/// fixed sides no longer make it fail.+#[test]+fn two_tangent_circle_clicked_on_two_sides_fits_the_corner_and_moves_nothing() {+ for fixed in [false, true] {+ let mut h = crate::scenario::Harness::new();+ h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();+ let r = h.app.run("sketch.rectangle.two_point", json!({"p0":[-800,0],"p1":[-300,500]})).unwrap();+ if fixed {+ h.app.run("sketch.constraint.fix", json!({"entities": r["curves"]})).unwrap();+ }+ h.step(&json!({"call":"ui.view","params":{"view":"fit"}})).unwrap();+ h.settle();+ let sid = h.app.session.active_sketch.unwrap();+ let points =+ |h: &crate::scenario::Harness| h.app.session.model.state().sketch(sid).unwrap().sketch.points.iter().map(|p| p.pos).collect::<Vec<_>>();+ let before = points(&h);+ h.step(&json!({"start":"sketch.circle.two_tangent"})).unwrap();+ h.step(&json!({"click":{"world":[-550,0,0]}})).unwrap();+ h.step(&json!({"click":{"world":[-800,250,0]}})).unwrap();+ let sk = h.app.session.model.state().sketch(sid).unwrap().sketch.clone();+ let circle = sk.curves.iter().position(|c| matches!(c.kind, CurveKind::Circle { .. }));+ let circle = circle.unwrap_or_else(|| panic!("fixed {fixed}: no circle: {:?}", h.app.status));+ assert!(sk.center(circle).unwrap().dist(Vec2::new(-750.0, 50.0)) < 1e-6, "fixed {fixed}: {:?}", sk.center(circle));+ let after = points(&h);+ assert!(before.iter().zip(&after).all(|(a, b)| a.dist(*b) < 1e-9), "fixed {fixed}: the rectangle moved: {after:?}");+ }+}diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rsindex b8a758a358..a8e90d8467 100644--- a/crates/ui-egui/src/sketch_tools.rs+++ b/crates/ui-egui/src/sketch_tools.rs@@ -595,7 +595,7 @@ pub fn hint(id: &str) -> Option<String> {"sketch.edit_text" => "Edit Text: click a letter interior or outline","sketch.blend_curve" => "Blend curve: click the ends of two curves","sketch.constraint.curvature" => "Curvature: click two curves that share an end",- "sketch.circle.two_tangent" => "2-tangent circle: click two curves (the circle goes near the second click)",+ "sketch.circle.two_tangent" => "2-tangent circle: click two curves (the circle goes between the two clicks)","sketch.circle.three_tangent" => "3-tangent circle: click three curves","sketch.constrainer" => "Constrain: click one or two entities; right-click to apply","sketch.constraint.polygon" => "Polygon: click the lines of a closed chain; right-click to apply",@@ -1007,7 +1007,9 @@ fn run_entities(app: &mut SolveApp, t: &Tool) {"sketch.constraint.curvature" => json!({"a": k[0], "b": k[1]}),"sketch.circle.two_tangent" => {let r = round_nice(curve_len(app, &k[0]).min(curve_len(app, &k[1])) * 0.1);- let near = t.pts.last().map(|p| xy(p.0)).unwrap_or(json!([0, 0]));+ // Between the two clicks: each lies on its curve, so the circle in the corner they+ // span is the one nearest their midpoint (#3141).+ let near = xy(t.pts.iter().fold(Vec2::ZERO, |a, p| a + p.0) / t.pts.len().max(1) as f64);json!({"curves": k, "radius": r, "near": near})}"sketch.circle.three_tangent" => {