diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 825254243..bbcd1b527 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -3684,7 +3684,9 @@ impl Document { /// `moved_from`: the stored sketch, when `sk` is that sketch with its links refreshed. A /// link's points are where their source is now; the sides and turns the solve keeps are /// those of the stored state ([`Sketch::positions_in`]), not the ones read beside a line - /// that has moved past a point. + /// that has moved past a point. Where the links moved so far that the solve fails or turns + /// part of the sketch over, they are walked there in steps + /// ([`solidcraft_sketch::solve_after_link_move`]). pub fn solve_sketch( &self, vals: &std::collections::BTreeMap, @@ -3713,7 +3715,31 @@ impl Document { // Offsets always require another solve after refresh. Only that last report is // published; the first report only decides which state the second solve starts from. let first_analysis = if offsets { solidcraft_sketch::Analysis::StatusOnly } else { analysis }; + // A linked or fixed point is not where the stored sketch has it. + let given_moved = moved_from + .is_some_and(|from| sk.points.iter().zip(&from.points).any(|(p, q)| (p.fixed || p.link.is_some()) && p.id == q.id && p.pos != q.pos)); let mut report = solidcraft_sketch::solve_after_edit_with_analysis(sk, stored, was(sk).as_deref(), first_analysis); + // Links that moved far (a large change of a size upstream): when the jump fails, or + // lands on the mirror image of a side or turn the stored sketch has, walked there in + // steps; a turn the walk cannot avoid either is reported as one. + if let Some(from) = moved_from.filter(|_| given_moved) { + let flips = if report.ok() { solidcraft_sketch::flips_from_stored(sk, from) } else { Vec::new() }; + if !report.keeps_orientation() || !flips.is_empty() { + match solidcraft_sketch::solve_after_link_move(sk, from, stored, first_analysis) { + Some(walked) => report = walked, + None => { + for id in flips { + if !report.failing.contains(&id) { + report.failing.push(id.clone()); + } + if !report.folded.contains(&id) { + report.folded.push(id); + } + } + } + } + } + } if offsets { // Source dimensions may have moved curves during the solve. sk.refresh_offsets()?; diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index bd842456c..4582ea6f2 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1767,10 +1767,16 @@ impl Model { } /// The sketches the last evaluation solved for driving values other than the ones `doc` - /// stores them with (a value edit since they were stored). + /// stores them with (a value edit since they were stored), or with their linked points + /// elsewhere (a value edit upstream moved what they project: stored, the next evaluation + /// starts where this one ended instead of walking the links there again). pub fn edited_sketches<'a>(&'a self, doc: &'a Document) -> impl Iterator + 'a { self.results.iter().filter(|r| !r.skipped && r.error.is_none()).filter_map(|r| r.state.sketch(r.id)).filter(|s| { - s.report.keeps_orientation() && doc.sketch(s.feature).is_ok_and(|stored| stored.driving_values() != s.sketch.driving_values()) + s.report.keeps_orientation() + && doc.sketch(s.feature).is_ok_and(|stored| { + stored.driving_values() != s.sketch.driving_values() + || s.sketch.points.iter().zip(&stored.points).any(|(p, q)| p.link.is_some() && p.id == q.id && p.pos != q.pos) + }) }) } diff --git a/crates/engine/src/cmd/sketch_project_side_tests.rs b/crates/engine/src/cmd/sketch_project_side_tests.rs index 4e847b07f..9b43f1a21 100644 --- a/crates/engine/src/cmd/sketch_project_side_tests.rs +++ b/crates/engine/src/cmd/sketch_project_side_tests.rs @@ -178,3 +178,69 @@ fn a_dimension_added_after_the_source_moved_takes_the_side_its_point_is_on() { set_height(&mut s, 6.0); assert_p(&s, 14.0, "8 from the line, height 6"); } + +/// A rectangle of construction lines placed on three points projected from another sketch +/// (its near side on the line's ends, its far side 4 from the middle) and a centred text on +/// the far side. Moved about 280 away (more than one jump can take: the solve walks there from the +/// stored sketch), the rectangle follows and keeps its side ("the sketch constraints conflict" +/// before), and comes back. +#[test] +fn a_label_on_a_path_follows_its_source_far() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "x", "expression": "100 mm"})); + run(&mut s, "parameters.add", json!({"name": "y", "expression": "120 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "A"})); + run(&mut s, "sketch.line", json!({"points": [[100, 120], [100, 100]], "ids": ["rail"]})); + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "rail", "mode": "vertical"})); + run(&mut s, "sketch.dimension", json!({"entities": ["origin", "rail.start"], "type": "horizontal", "value": "x"})); + run(&mut s, "sketch.dimension", json!({"entities": ["origin", "rail.start"], "type": "vertical", "value": "y"})); + run(&mut s, "sketch.dimension", json!({"entities": ["rail"], "value": "20 mm"})); + run(&mut s, "sketch.point", json!({"point": [100, 110], "id": "mid"})); + run(&mut s, "sketch.constraint.midpoint", json!({"point": "mid", "line": "rail"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let refs = ["rail.start", "rail.end", "mid"].map(|p| json!({"sketch": "A", "point": p})); + let r = run(&mut s, "sketch.project", json!({"refs": refs})); + let brought: Vec = (0..3).map(|i| r["links"][i]["points"][0].as_str().unwrap().to_string()).collect(); + let near = 100.0 - 4.0; + for (id, a, b) in [ + ("l1", [100.0, 120.0], [100.0, 100.0]), + ("l2", [near, 120.0], [near, 100.0]), + ("l3", [100.0, 120.0], [near, 120.0]), + ("l4", [100.0, 100.0], [near, 100.0]), + ] { + run(&mut s, "sketch.line", json!({"points": [a, b], "ids": [id], "construction": true, "connect": false})); + } + for (a, b) in [ + ("l1.start", brought[0].as_str()), + ("l1.end", &brought[1]), + ("l3.start", "l1.start"), + ("l3.end", "l2.start"), + ("l4.start", "l1.end"), + ("l4.end", "l2.end"), + ] { + run(&mut s, "sketch.constraint.coincident", json!({"a": a, "b": b})); + } + run(&mut s, "sketch.constraint.parallel", json!({"a": "l2", "b": "l1"})); + run(&mut s, "sketch.dimension", json!({"entities": [brought[2], "l2"], "type": "distance", "value": "4 mm"})); + run(&mut s, "sketch.constraint.perpendicular", json!({"a": "l3", "b": "l1"})); + run(&mut s, "sketch.constraint.perpendicular", json!({"a": "l4", "b": "l1"})); + run(&mut s, "sketch.text", json!({"text": "TAG-1", "at": [0, 0], "height": 3, "align": "center", "path": "l2"})); + run(&mut s, "sketch.finish", json!({})); + let far_side = |s: &Session| { + let st = s.model.state(); + let sk = &st.sketch(s.doc.find_feature("S").unwrap().id).unwrap().sketch; + sk.point(sk.resolve_point("l2.start").unwrap()).unwrap() + }; + #[track_caller] + fn quiet(s: &Session, when: &str) { + let feature = s.model.result(s.doc.find_feature("S").unwrap().id).unwrap(); + assert_eq!((&feature.error, &feature.warning), (&None, &None), "{when}"); + } + quiet(&s, "drawn"); + for (x, y) in [(300.0, 320.0), (100.0, 120.0)] { + run(&mut s, "parameters.change", json!({"changes": {"x": format!("{x} mm"), "y": format!("{y} mm")}})); + quiet(&s, &format!("moved to ({x}, {y})")); + assert!(far_side(&s).dist(Vec2::new(x - 4.0, y)) < 1e-6, "({x}, {y}): {:?}", far_side(&s)); + } +} diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rs index c009dbf57..d95a7f102 100644 --- a/crates/sketch/src/lib.rs +++ b/crates/sketch/src/lib.rs @@ -66,8 +66,9 @@ pub use profiles::{ pub use shape::{Shape, intersections, intersections_within}; pub use solver::solve_after_edit_with_analysis; pub use solver::{ - Analysis, CONSISTENT, DrivingValues, Hold, MAX_COMPONENT_VARS, SolveReport, SolveStatus, constraint_residual, determined_by, measure_dimension, - move_line_towards, move_point_towards, solve, solve_after_edit, solve_after_value_edit, solve_holding, solve_with, + Analysis, CONSISTENT, DrivingValues, Hold, MAX_COMPONENT_VARS, SolveReport, SolveStatus, constraint_residual, determined_by, flips_from_stored, + measure_dimension, move_line_towards, move_point_towards, solve, solve_after_edit, solve_after_link_move, solve_after_value_edit, solve_holding, + solve_with, }; pub use text::{MAX_TEXT_CHARS, TextAlign, TextMetrics, TextStyle, text_geometry, text_geometry_in, text_geometry_styled}; pub use thin::{MAX_THIN_SEGMENTS, thin_wall_regions}; diff --git a/crates/sketch/src/link_side_tests.rs b/crates/sketch/src/link_side_tests.rs index e5b077389..bbb15a108 100644 --- a/crates/sketch/src/link_side_tests.rs +++ b/crates/sketch/src/link_side_tests.rs @@ -3,7 +3,7 @@ //! not beside a line that has already moved past them. use super::*; -use crate::{ConstraintKind, solve, solve_after_edit}; +use crate::{Analysis, ConstraintKind, flips_from_stored, solve, solve_after_edit, solve_after_link_move}; fn source() -> LinkSource { LinkSource::SketchCurve { sketch: 1, curve: "rail".into() } @@ -120,3 +120,55 @@ fn stored_positions_are_matched_by_point_id() { assert_eq!(was[i], sk.points[i].pos); } } + +/// A 40 mm horizontal line tangent to a linked circle (r 3) above it, its left end 20 mm left +/// of the centre; the stored sketch with the circle where it was (`y`). +fn tangent_on_circle(y: f64) -> (Sketch, String, usize) { + let circle = |y: f64| vec![LinkGeom::Circle(Vec2::new(0.0, y), 3.0)]; + let mut sk = Sketch::new(); + let link = sk.add_link(LinkKind::Project, LinkSource::SketchCurve { sketch: 1, curve: "bend".into() }, &circle(y)).unwrap(); + let c = sk.link_curves(&link)[0]; + let centre = sk.link_points(&link)[0]; + let l = sk.add_line(Vec2::new(-20.0, y + 3.0), Vec2::new(20.0, y + 3.0), None, None, None).unwrap(); + let (a, _) = sk.curves[l].kind.ends().unwrap(); + sk.add_constraint(ConstraintKind::Horizontal { l }, None).unwrap(); + sk.add_constraint(ConstraintKind::Tangent { a: l, b: c }, None).unwrap(); + sk.add_constraint(ConstraintKind::DistanceX { p: a, q: centre, value: 20.0 }, None).unwrap(); + sk.add_constraint(ConstraintKind::Length { l, value: 40.0 }, None).unwrap(); + assert!(solve(&mut sk).ok()); + (sk, link, l) +} + +#[test] +fn a_line_tangent_to_a_linked_circle_keeps_its_side_when_the_circle_moves_far() { + let (stored, link, l) = tangent_on_circle(0.0); + let height = |sk: &Sketch| match sk.curves[l].kind { + CurveKind::Line { a, .. } => sk.points[a].pos.y, + _ => f64::NAN, + }; + assert!((height(&stored) - 3.0).abs() < 1e-9); + let circle = |y: f64| vec![LinkGeom::Circle(Vec2::new(0.0, y), 3.0)]; + // Moved 100 mm up, the circle passes the line. Its other tangent (y 97, a diameter below) + // solves every constraint too: only the side it left tells it from the right one. + let mut mirrored = stored.clone(); + mirrored.update_link(&link, &circle(100.0)).unwrap(); + for p in &mut mirrored.points { + if p.link.is_none() && p.id != "origin" { + p.pos.y += 94.0; + } + } + assert!((height(&mirrored) - 97.0).abs() < 1e-9); + assert!(solve(&mut mirrored).ok() && (height(&mirrored) - 97.0).abs() < 1e-9); + assert!(!flips_from_stored(&mirrored, &stored).is_empty()); + // Walked there, the line stays above the circle, in either direction and far. + for y in [100.0, -100.0, 2000.0] { + let mut sk = stored.clone(); + sk.update_link(&link, &circle(y)).unwrap(); + let report = solve_after_link_move(&mut sk, &stored, &stored.driving_values(), Analysis::Full); + assert!(report.is_some_and(|r| r.keeps_orientation()), "{y}"); + assert!((height(&sk) - (y + 3.0)).abs() < 1e-9 && flips_from_stored(&sk, &stored).is_empty(), "{y}: {}", height(&sk)); + } + // Nothing moved: nothing to walk. + let mut sk = stored.clone(); + assert!(solve_after_link_move(&mut sk, &stored, &stored.driving_values(), Analysis::Full).is_none()); +} diff --git a/crates/sketch/src/solver.rs b/crates/sketch/src/solver.rs index 51954460c..18e374e21 100644 --- a/crates/sketch/src/solver.rs +++ b/crates/sketch/src/solver.rs @@ -1470,6 +1470,165 @@ pub fn solve_after_edit_with_analysis(sk: &mut Sketch, old: &DrivingValues, stor solve_from(sk, &Hold::default(), stored, analysis, Some(&old_values), &mut Budget::full()) } +/// The orientations of `stored` that `solved` (the same sketch, its links moved and solved +/// again) turned over, by constraint id: the sides of unsigned offsets and the turns of +/// distance triangles, each read where `stored` has its points and where `solved` has them. +/// A solve after its links moved checks none of these when no value changed, so a jump can +/// land on the mirror image of a part of the sketch and still report it solved. Empty when the +/// two sketches are not the same entities (a link was rebuilt). +pub fn flips_from_stored(solved: &Sketch, stored: &Sketch) -> Vec { + let aligned = solved.points.len() == stored.points.len() + && solved.curves.len() == stored.curves.len() + && solved.constraints.len() == stored.constraints.len() + && solved.points.iter().zip(&stored.points).all(|(p, q)| p.id == q.id) + && solved.constraints.iter().zip(&stored.constraints).all(|(c, d)| c.id == d.id); + if !aligned { + return Vec::new(); + } + let hold = Hold::default(); + let (lay_before, lay_now) = (layout(stored, &hold), layout(solved, &hold)); + let (x_before, x_now) = (initial_x(stored, &lay_before), initial_x(solved, &lay_now)); + let before = State { sk: stored, lay: &lay_before, x: &x_before }; + let now = State { sk: solved, lay: &lay_now, x: &x_now }; + let (blocks, _) = build_blocks(stored, &lay_before, &points_on_curves(stored)); + let mut out: Vec = Vec::new(); + for (o, cs) in orients(&before, &blocks) { + if reference_orientation(&before, o).zip(orientation(&now, o)).is_some_and(|(b, n)| b != n) { + for ci in cs { + if let Some(c) = stored.constraints.get(ci) + && !out.contains(&c.id) + { + out.push(c.id.clone()); + } + } + } + } + out +} + +/// The finest steps a link move is split into: a walk that needs smaller ones gives up. +const LINK_STEPS: usize = 4096; +/// The walk's first step (in [`LINK_STEPS`]), small enough to stay on the stored solution's +/// branch; the secant of it predicts the next. +const LINK_FIRST_STEP: usize = 4; +/// Most solves one [`solve_after_link_move`] may spend. +const LINK_STEP_SOLVES: usize = 400; + +/// [`solve_after_edit`] for a sketch whose linked (or fixed) points moved far from where +/// `stored` has them, when that solve fails or turns the sketch over (also as +/// [`flips_from_stored`] tells): one jump can take a +/// sketch of many constraints to a solution it cannot reach (the iteration fails) or to +/// another one (a dimension's side flips), although the sketch solves where the links are now +/// when it is drawn there. The changed values are solved first with the links where they were +/// stored; then the moved points are walked from there to where they are now, in steps that +/// halve where a step fails or turns a constraint over and grow again where they solve, each +/// solved from the last two solutions carried on along their secant. `sk` is the stored sketch with its links refreshed and +/// its new values applied (what [`solve_after_edit`] takes), `old` the values `stored` is +/// solved for. `None` (and `sk` left as it was) when nothing moved, the point lists differ (a +/// link was rebuilt), or the walk does not reach the end. +pub fn solve_after_link_move(sk: &mut Sketch, stored: &Sketch, old: &DrivingValues, analysis: Analysis) -> Option { + let aligned = sk.points.len() == stored.points.len() && sk.points.iter().zip(&stored.points).all(|(p, q)| p.id == q.id); + if !aligned || sk.curves.len() != stored.curves.len() { + return None; + } + let to: Vec = sk.points.iter().map(|p| p.pos).collect(); + let from: Vec = stored.points.iter().map(|p| p.pos).collect(); + let moving: Vec = + sk.points.iter().enumerate().filter(|(i, p)| (p.fixed || p.link.is_some()) && from.get(*i) != to.get(*i)).map(|(i, _)| i).collect(); + // Linked circles keep their radius as a constant: it is walked with the points. + let radius = |c: &crate::model::Curve| match c.kind { + CurveKind::Circle { r, .. } | CurveKind::Ellipse { r, .. } if c.link.is_some() => Some(r), + _ => None, + }; + let radii: Vec<(usize, f64, f64)> = sk + .curves + .iter() + .zip(&stored.curves) + .enumerate() + .filter_map(|(i, (c, s))| Some((i, radius(s)?, radius(c)?))) + .filter(|(_, a, b)| a != b) + .collect(); + if moving.is_empty() && radii.is_empty() { + return None; + } + let target = sk.clone(); + // The walk's sketch at `t` of the way: the moved points there, every other point where the + // last solved step left it. + let at = |t: f64, solved: &[Vec2]| -> Sketch { + let mut step = target.clone(); + for (p, s) in step.points.iter_mut().zip(solved) { + p.pos = *s; + } + for &i in &moving { + if let (Some(p), Some(a), Some(b)) = (step.points.get_mut(i), from.get(i), to.get(i)) { + p.pos = *a + (*b - *a) * t; + } + } + for &(i, a, b) in &radii { + if let Some(crate::model::Curve { kind: CurveKind::Circle { r, .. } | CurveKind::Ellipse { r, .. }, .. }) = step.curves.get_mut(i) { + *r = a + (b - a) * t; + } + } + step + }; + // The new values where the links were stored (a value edit, continued as `solve_after_edit` does). + let mut first = at(0.0, &from); + if !solve_after_edit_with_analysis(&mut first, old, None, Analysis::StatusOnly).keeps_orientation() { + return None; + } + let mut solved: Vec = first.points.iter().map(|p| p.pos).collect(); + let values = target.driving_values(); + // Predictor and corrector: each step starts from the last two solutions carried on along + // their secant (a tangent to a moving circle moves with it instead of hopping to the + // circle's other side) and is solved from there. A tiny first step gives the secant; a + // step grows while it solves, and stays below one that failed (a failed solve costs the + // iteration's whole budget) until a run of solved steps lets it grow again. + let mut prev: Option<(usize, Vec)> = None; + let (mut t, mut h, mut cap, mut run, mut spent) = (0usize, LINK_FIRST_STEP, LINK_STEPS, 0usize, 0usize); + while t < LINK_STEPS { + if spent >= LINK_STEP_SOLVES { + return None; + } + spent += 1; + let next = (t + h).min(LINK_STEPS); + let start: Vec = match &prev { + Some((tp, pp)) if *tp < t => { + let k = (next - t) as f64 / (t - tp) as f64; + solved.iter().zip(pp).map(|(s, p)| *s + (*s - *p) * k).collect() + } + _ => solved.clone(), + }; + let mut step = at(next as f64 / LINK_STEPS as f64, &start); + let last = at(t as f64 / LINK_STEPS as f64, &solved); + let before = step.positions_in(&last); + if solve_after_edit_with_analysis(&mut step, &values, before.as_deref(), Analysis::StatusOnly).keeps_orientation() + && flips_from_stored(&step, &last).is_empty() + { + prev = Some((t, std::mem::replace(&mut solved, step.points.iter().map(|p| p.pos).collect()))); + t = next; + run += 1; + if run >= 3 { + (cap, run) = ((2 * cap).min(LINK_STEPS), 0); + } + h = (2 * h).min(cap).max(1); + } else if h > 1 { + (cap, run) = ((h / 2).max(1), 0); + h /= 2; + } else { + return None; + } + } + let mut done = target; + for (p, s) in done.points.iter_mut().zip(&solved) { + p.pos = *s; + } + let report = solve_with(&mut done, &Hold::default(), Some(&solved), analysis, None); + (report.keeps_orientation() && flips_from_stored(&done, stored).is_empty()).then(|| { + *sk = done; + report + }) +} + impl Sketch { /// Each dimension's driving value by constraint id, as [`solve_after_value_edit`] takes /// them. @@ -1843,6 +2002,16 @@ fn orients(s: &State, sub: &[(Block, Vec)]) -> Vec<(Orient, Vec)> out.push((Orient::OfLine(*centre, l, value + s.round(c).1), vec![*ci])); } } + // A line tangent to a circle away from both their ends: the circle stays on its side + // (the other tangent of that direction is a diameter away). + ConstraintKind::Tangent { a, b } => { + let (l, c) = if s.is_line(a) { (a, b) } else { (b, a) }; + if s.is_line(l) + && let Some(CurveKind::Circle { c: centre, .. } | CurveKind::Arc { c: centre, .. }) = s.sk.curves.get(c).map(|x| &x.kind) + { + out.push((Orient::OfLine(*centre, l, s.round(c).1), vec![*ci])); + } + } _ => {} } }