Make constrained sketch edges follow the cursor (#3360) (#3362)

* claim: #3360

* Fix constrained sketch edge following and final drag coordinates
This commit is contained in:
takuto-NA
2026-10-20 12:43:59 +00:00
committed by GitHub
parent 7c6845da95
commit d8eb65d26e
11 changed files with 491 additions and 67 deletions
+6 -7
View File
@@ -179,7 +179,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.params("entities: [curve, point or constraint ids]"),
CommandSpec::new("sketch.move_point", "Drag Sketch Point", move_point).icon("sketch_move").enabled(in_sketch).params("point: ref, to: [x,y]"),
CommandSpec::new("sketch.drag", "Drag Sketch Geometry", drag).icon("sketch_move").enabled(in_sketch).live(drag_live).params(
"entity: point or curve, from: [x,y] where it was grabbed, to: [x,y], live?: bool: a point moves toward `to` within the design constraints; when exact cursor placement is impossible, bounded feasible steps minimize cursor distance while keeping design constraints mandatory. A line (spline, conic) slides by to - from; a circle or arc grabbed on its edge takes the radius to `to`. `with?`: [point or curve ids]: the rest of a selection dragged by `entity`, which all slides by to - from as one (circles keep their radii). Long moves use continuation to retain the solution branch, and a step that would sweep an arc through its start is rejected. Returns `reached`: progress along the requested move (0..1; feasible point motion projects its actual displacement onto that move), and `at`: where the grabbed spot went (`from` moved as the dragged points did), the `from` of the next move. `live: true` solves the sketch and leaves later features stale until `sketch.drag_end` or a command that reads the model; `dof` is then the one from before the drag",
"entity: point or curve, from: [x,y] where it was grabbed, to: [x,y], live?: bool: points and the material point grabbed on a line move toward `to` within the design constraints. When exact placement is impossible, bounded feasible steps minimize cursor distance. Splines slide by to - from; a circle or arc grabbed on its edge takes the radius to `to`. `with?`: [point or curve ids] moves the rest of a selection with the entity as one translation (circles keep their radii). Long moves retain the solution branch; arcs cannot sweep through their starts. Returns `reached`: progress projected onto the requested move (0..1), `at`: the grabbed position for the next frame, and `retry`: budget-limited progress can continue in another frame. `live: true` shares a work budget across held-solve decomposition and cursor correction; ordinary recovery and the final model evaluation retain their existing limits, not a wall-clock deadline. Later features stay stale until `sketch.drag_end`; `dof` stays from before the drag",
),
CommandSpec::new("sketch.drag_end", "End Sketch Drag", drag_end).icon("sketch_move").enabled(in_sketch).doc_only().params(
"constraint?: {command: a sketch.constraint.* id, params}: ends a drag made of `sketch.drag` `live: true` frames: adds the constraint it let go on (not kept if it over-constrains the sketch), then evaluates the whole model once; returns the constraint's result and the sketch's solved state and degrees of freedom",
@@ -2453,7 +2453,7 @@ fn drag_frame(s: &mut Session, p: &Value, live: bool) -> Result<(Value, Option<c
if let Some(link) = super::sketch_create::text_link(sk, r).map(str::to_owned) {
let moving = sk.link_points(&link).into_iter().filter_map(|i| sk.point(i).map(|p| (i, p))).collect();
super::sketch_create::move_text(sk, &link, to - from, 0.0, Vec2::ZERO, false)?;
return Ok((drag::Dragged { reached: 1.0, moving }, Left::Unsolved));
return Ok((drag::Dragged { reached: 1.0, moving, ..Default::default() }, Left::Unsolved));
}
// The held solves work on the dimensions' current values (a solved step applies them).
doc.apply_dimension_values(&doc.param_values().0, sk)?;
@@ -2462,13 +2462,12 @@ fn drag_frame(s: &mut Session, p: &Value, live: bool) -> Result<(Value, Option<c
// its degrees of freedom.
Ok((d, if live && last.is_some() { left } else { left.solve_again() }))
})?;
// Where the grabbed spot went: `from` moved as the dragged points did on average (with the
// whole step when it followed; otherwise as the sketch's own solve left them).
// Lines retain the grabbed material point through rotation. Other entities report the
// average displacement of their moving points, as before.
let sk = s.doc.sketch(id)?;
let moves: Vec<Vec2> = d.moving.iter().filter_map(|&(q, was)| Some(sk.point(q)? - was)).collect();
let at = from + moves.iter().fold(Vec2::ZERO, |a, m| a + *m) * (1.0 / moves.len().max(1) as f64);
let at = d.at(sk, from);
let rep = rep.or_else(|| last.map(|last| SolveReport { status: solidcraft_sketch::SolveStatus::Solved, failing: Vec::new(), ..last }));
let out = json!({"sketch": rep.as_ref().map(report_json), "reached": d.reached, "at": [at.x, at.y]});
let out = json!({"sketch": rep.as_ref().map(report_json), "reached": d.reached, "at": [at.x, at.y], "retry": d.retry});
Ok((out, rep.filter(|_| live).map(|report| crate::LiveEdit { sketch: id, report })))
}
+82 -22
View File
@@ -104,21 +104,21 @@ impl Path {
}
}
/// Drag: the grabbed entity follows the cursor where possible (a point moves toward it; a line or spline
/// slides by the cursor's move; a circle or arc grabbed on its edge changes radius about its
/// Drag: the grabbed entity follows the cursor where possible (a point or a material point on a
/// line moves toward it; a spline slides by the cursor's move; a circle or arc changes radius about its
/// centre; a conic grabbed on its curve reads its fullness, `rho`, off the cursor) and the rest
/// of the sketch moves as little as it can, staying on the
/// solution it started on. Fixed geometry stays. A step that cannot be solved with the entity
/// held (the path crosses where the geometry cannot reach) is approached by halving the way to
/// it, and the next steps are tried from the last solved state, the last of them being the whole
/// remaining move. A point whose exact pin fails instead minimizes cursor distance in the
/// design's remaining freedom, retaining only corrected, feasible poses. For other entities,
/// remaining move. A point or line whose exact pin fails instead minimizes cursor distance in
/// the design's remaining freedom, retaining only corrected, feasible poses. For other entities,
/// when none past it solves, the first failed step stays placed but unsolved:
/// the edit's ordinary, non-strict solve that follows (seeded on the last solved state, see
/// [`Left::MovedFrom`]) then pulls it back (fully constrained geometry) or leaves the sketch
/// unsolved for the user to see. A step that would sweep an arc through its own start is undone
/// and the drag ends there. Returns how far it got and what it leaves for the edit's solve
/// ([`Left::Solved`]: the held solve of the last step it kept left the sketch solved).
/// ([`Left::Solved`]: the retained pose satisfies the design constraints, even without progress).
///
/// `with`: the rest of a selection dragged by one of its entities; all of it slides by the
/// cursor's move as one (see [`plan_group`]).
@@ -127,11 +127,13 @@ impl Path {
/// one frame's work budget ([`Budget::frame`]); otherwise each has a solve's own.
pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to: Vec2, live: bool) -> (Dragged, Left) {
let Some((path, hold, n, short)) = prepare(sk, e, with, from, to) else {
return (Dragged { reached: 0.0, moving: Vec::new() }, Left::Unsolved);
return (Dragged::default(), Left::Unsolved);
};
#[cfg(test)]
let (n, short) = (n.min(step_cap::get()), short.min(step_cap::get()));
let moving: Vec<_> = path.points().filter_map(|q| Some((q, sk.point(q)?))).collect();
let line_grab = if with.is_empty() { LineGrab::new(sk, e, from) } else { None };
let start = line_grab.and_then(|g| g.point(sk)).or_else(|| if let Ent::Point(q) = e { sk.point(q) } else { None });
let mut frame = live.then(frame_budget);
// Only success matters to these solves: the degrees of freedom of a sketch with the entity
// held are not the sketch's. Each is seeded on the last solved state (`last`), so what the
@@ -167,6 +169,7 @@ pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to:
// short steps.
let (mut base, mut dt, mut k, mut t) = (0.0, 1.0 / n as f64, 0, 0.0);
let mut shortened = false;
let mut wrapped = false;
'walk: while t < 1.0 {
if solves.cut && !shortened {
shortened = true;
@@ -189,11 +192,18 @@ pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to:
continue;
}
Step::Wrapped => {
wrapped = true;
failed = None;
break 'walk;
}
Step::Failed => {}
}
// Translating both ends can be impossible although a link can rotate. Do not spend
// the frame walking more impossible pins: optimize the point actually grabbed.
if line_grab.is_some() {
failed = Some(t);
break 'walk;
}
if failed.is_none() {
// Halve the way to the failed step, so the state the next steps start from (and are
// seeded on) is as close to it as the geometry follows. The shortest move is tried
@@ -209,7 +219,10 @@ pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to:
good = mid;
last.take(sk);
}
Step::Wrapped => break 'walk,
Step::Wrapped => {
wrapped = true;
break 'walk;
}
Step::Failed => miss = mid,
}
}
@@ -219,19 +232,26 @@ pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to:
// First retain held continuation across unreachable stretches of an otherwise reachable
// path (for example an arm dragged through the hole around its shoulder). If it cannot
// arrive, optimize the full cursor target without relaxing the design constraints.
if failed.is_some()
&& let Ent::Point(q) = e
if !wrapped
&& with.is_empty()
&& (matches!(e, Ent::Point(_)) || line_grab.is_some())
&& (failed.is_some() || line_grab.and_then(|g| g.point(sk)).is_some_and(|at| at.dist(to) > 1e-7))
{
let (points, radii) = sk.coupled(&hold.points, &hold.radii);
let size = smallest_size(sk, &hold, Some(Group { points: &points, radii: &radii }));
let max_step = (size * SHORT_STEP_FRACTION).min(path.length()).max(MIN_STEP);
#[cfg(test)]
let spent = frame.as_ref().map_or(0, Budget::spent);
let followed = solidcraft_sketch::move_point_towards(sk, q, to, max_step, frame.as_mut(), |before, after| {
let valid = |before: &Sketch, after: &Sketch| {
let mut geometry = Geometry::default();
geometry.take(before);
!geometry.sweep_wrapped(after)
});
};
let followed = match (e, line_grab) {
(Ent::Point(q), _) => solidcraft_sketch::move_point_towards(sk, q, to, max_step, frame.as_mut(), valid),
(_, Some(g)) => solidcraft_sketch::move_line_towards(sk, g.curve, g.local, to, max_step, frame.as_mut(), valid),
_ => false,
};
#[cfg(test)]
if let Some(budget) = &frame {
solves.work += budget.spent() - spent;
@@ -240,15 +260,13 @@ pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to:
if followed {
#[cfg(test)]
last_drag::set(solves);
let reached = moving
.iter()
.find(|(p, _)| *p == q)
.and_then(|(_, start)| {
let d = to - *start;
sk.point(q).map(|at| if at.dist(to) < 1e-6 || d.dot(d) == 0.0 { 1.0 } else { ((at - *start).dot(d) / d.dot(d)).clamp(0.0, 1.0) })
})
.unwrap_or(0.0);
return (Dragged { reached, moving }, Left::Solved);
let at = line_grab.and_then(|g| g.point(sk)).or_else(|| if let Ent::Point(q) = e { sk.point(q) } else { None });
let reached = start.zip(at).map_or(0.0, |(start, at)| {
let d = to - start;
if at.dist(to) < 1e-6 || d.dot(d) == 0.0 { 1.0 } else { ((at - start).dot(d) / d.dot(d)).clamp(0.0, 1.0) }
});
let retry = frame.as_ref().is_some_and(Budget::exhausted) && start.zip(at).is_some_and(|(a, b)| a.dist(b) > 1e-9);
return (Dragged { reached, moving, line_grab, retry }, Left::Solved);
}
}
#[cfg(test)]
@@ -262,7 +280,7 @@ pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, with: &[Ent], from: Vec2, to:
None if good > 0.0 => Left::Solved,
None => Left::Unsolved,
};
(Dragged { reached: good, moving }, left)
(Dragged { reached: good, moving, line_grab, retry: false }, left)
}
/// The held solves of one drag: how many, their shared work (including cursor correction),
@@ -333,12 +351,54 @@ enum Step {
}
/// How far a drag got.
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, Default, PartialEq)]
pub(super) struct Dragged {
/// The part of the way from where it was grabbed to the cursor the geometry followed (0..1).
pub reached: f64,
/// The points the drag moves (not the fixed ones it holds), where they were before it.
pub moving: Vec<(usize, Vec2)>,
pub line_grab: Option<LineGrab>,
/// Cursor work stopped at its budget after making progress; another frame can continue.
pub retry: bool,
}
impl Dragged {
pub(super) fn at(&self, sk: &Sketch, from: Vec2) -> Vec2 {
if let Some(at) = self.line_grab.and_then(|g| g.point(sk)) {
return at;
}
let moves: Vec<_> = self.moving.iter().filter_map(|&(q, was)| Some(sk.point(q)? - was)).collect();
from + moves.iter().fold(Vec2::ZERO, |a, m| a + *m) * (1.0 / moves.len().max(1) as f64)
}
}
/// The grabbed position in a line's frame, retained through rotation and constraint correction.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct LineGrab {
curve: usize,
a: usize,
b: usize,
local: Vec2,
}
impl LineGrab {
fn new(sk: &Sketch, e: Ent, from: Vec2) -> Option<Self> {
let Ent::Curve(curve) = e else { return None };
let CurveKind::Line { a, b } = sk.curves.get(curve)?.kind else { return None };
let pa = sk.point(a)?;
let d = sk.point(b)? - pa;
let len2 = d.dot(d);
if !(len2 > 1e-18) {
return None;
}
Some(Self { curve, a, b, local: Vec2::new((from - pa).dot(d) / len2, d.cross(from - pa) / len2) })
}
fn point(self, sk: &Sketch) -> Option<Vec2> {
let a = sk.point(self.a)?;
let d = sk.point(self.b)? - a;
Some(a + d * self.local.x + Vec2::new(-d.y, d.x) * self.local.y)
}
}
/// The geometry a step changes (point positions; curves, for radii and the arc ends a solve
+19 -21
View File
@@ -136,28 +136,27 @@ fn a_scripted_drag_still_evaluates_the_whole_model() {
#[test]
fn a_drag_reports_how_far_the_geometry_followed() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.line", json!({"points": [[10, 10], [40, 10]]}));
run(&mut s, "sketch.line", json!({"points": [[10, 30], [40, 30]]}));
run(&mut s, "sketch.constraint.fix", json!({"entities": ["l1.start"]}));
run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": 30}));
for live in [false, true] {
// A line of fixed length with a fixed end cannot slide: the sketch's own solve only
// turns it a little toward the cursor, and the grab follows its free end.
let before = pt(&s, "l1.end");
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.line", json!({"points": [[10, 10], [40, 10]]}));
run(&mut s, "sketch.line", json!({"points": [[10, 30], [40, 30]]}));
run(&mut s, "sketch.constraint.fix", json!({"entities": ["l1.start"]}));
run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": 30}));
// The grabbed midpoint follows a 15 mm circle around the fixed start.
let r = run(&mut s, "sketch.drag", json!({"entity": "l1", "from": [25, 10], "to": [25, 20], "live": live}));
assert_eq!(r["reached"], json!(0.0), "{r}");
let moved = pt(&s, "l1.end") - before;
let at = crate::params::vec2(&r["at"]).expect("`at`");
assert!(at.dist(solidcraft_geom::Vec2::new(25.0, 10.0) + moved) < 1e-9 && at.y < 20.0, "{r}");
let to = 40 + 10 * usize::from(live);
let r = run(&mut s, "sketch.drag", json!({"entity": "l2", "from": [25, to - 10], "to": [25, to]}));
assert_eq!((&r["reached"], &r["at"]), (&json!(1.0), &json!([25.0, to as f64])), "{r}");
let base = solidcraft_geom::Vec2::new(10.0, 10.0);
let expected = base + solidcraft_geom::Vec2::new(15.0, 10.0).normalized().unwrap() * 15.0;
assert!(at.dist(expected) < 1e-4, "{r}");
assert!(at.dist((pt(&s, "l1.start") + pt(&s, "l1.end")) * 0.5) < 1e-6);
assert!((r["reached"].as_f64().unwrap() - (at.y - 10.0) / 10.0).abs() < 1e-6);
assert!((pt(&s, "l1.end").dist(base) - 30.0).abs() < 1e-6);
let r = run(&mut s, "sketch.drag", json!({"entity": "l2", "from": [25, 30], "to": [25, 40]}));
assert_eq!((&r["reached"], &r["at"]), (&json!(1.0), &json!([25.0, 40.0])), "{r}");
let r = run(&mut s, "sketch.drag", json!({"entity": "l1.start", "from": [10, 10], "to": [0, 0], "live": true}));
assert_eq!(r["reached"], json!(0.0));
}
// A point that cannot move at all.
let r = run(&mut s, "sketch.drag", json!({"entity": "l1.start", "from": [10, 10], "to": [0, 0], "live": true}));
assert_eq!(r["reached"], json!(0.0));
}
#[test]
@@ -192,14 +191,13 @@ fn ui_frames(s: &mut Session, entity: &str, grab: [f64; 2], moves: &[[f64; 2]])
#[test]
fn the_grab_follows_the_points_that_move() {
// A line with a fixed end, dragged by its middle: only the free end moves, and it keeps the
// cursor's offset frame after frame.
// With one end fixed, the free end moves twice as far as its grabbed midpoint.
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.line", json!({"points": [[10, 10], [30, 10]]}));
run(&mut s, "sketch.constraint.fix", json!({"entities": ["l1.start"]}));
ui_frames(&mut s, "l1", [20.0, 10.0], &[[0.0, 1.0]; 6]);
assert!(pt(&s, "l1.end").dist(solidcraft_geom::Vec2::new(30.0, 16.0)) < 1e-9, "{:?}", pt(&s, "l1.end"));
assert!(pt(&s, "l1.end").dist(solidcraft_geom::Vec2::new(30.0, 22.0)) < 1e-6, "{:?}", pt(&s, "l1.end"));
assert!(pt(&s, "l1.start").dist(solidcraft_geom::Vec2::new(10.0, 10.0)) < 1e-12);
}
+57
View File
@@ -1543,3 +1543,60 @@ fn cursor_fallback_respects_an_exhausted_live_frame_budget() {
run(&mut s, "sketch.drag", json!({"entity": "crank.end", "from": [at.x, at.y], "to": [target.x, target.y], "live": false}));
assert!(pt(&s, "crank.end").dist(nearest) < 1e-4, "scripted motion retains the full cursor objective");
}
fn four_bar_drag_sketch() -> Session {
let mut s = new_sketch();
let x = -10.0 + (1600.0 - 400.0 + 52.0 * 52.0) / 104.0;
let y = -(1600.0_f64 - (x + 10.0) * (x + 10.0)).sqrt();
run(&mut s, "sketch.line", json!({"points":[[0,0],[-10,0],[x,y],[42,0]],"ids":["crank","coupler","rocker"],"infer":false}));
run(&mut s, "sketch.line", json!({"points":["crank.start","rocker.end"],"ids":["ground"],"infer":false}));
for (line, len) in [("crank", 10), ("coupler", 40), ("rocker", 20), ("ground", 42)] {
run(&mut s, "sketch.dimension", json!({"entities":[line],"value":len}));
}
run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line":"ground"}));
s
}
#[test]
fn releasing_a_budget_limited_four_bar_drag_finishes_with_a_bounded_budget() {
for (entity, fraction) in [("crank.end", 1.0), ("crank", 0.7)] {
let mut s = four_bar_drag_sketch();
let target = v(-10.0, 16.0) * fraction;
let nearest = target * (10.0 * fraction / target.len());
super::drag::last_drag::with_frame_work(0, || {
run(&mut s, "sketch.drag", json!({"entity":entity,"from":[-10.0*fraction,0],"to":[target.x,target.y],"live":true}));
let at = pt(&s, "crank.end") * fraction;
assert!(at.dist(nearest) > 0.5);
});
// The release is a new frame, with the same normal frame budget, not an unbounded
// final solve. The pointer has not moved since the budget-limited frame.
let at = pt(&s, "crank.end") * fraction;
run(&mut s, "sketch.drag", json!({"entity":entity,"from":[at.x,at.y],"to":[target.x,target.y],"live":true}));
assert!((pt(&s, "crank.end") * fraction).dist(nearest) < 1e-4);
run(&mut s, "sketch.drag_end", json!({}));
assert!((pt(&s, "crank.end") * fraction).dist(nearest) < 1e-4);
}
}
#[test]
fn budget_limited_cursor_progress_requests_a_frame_with_the_same_target() {
let mut exercised = false;
for budget in [2048, 4096, 8192, 16384, 32768] {
let mut s = four_bar_drag_sketch();
let target = v(-7.0, 11.2);
let nearest = target * (7.0 / target.len());
let r = super::drag::last_drag::with_frame_work(budget, || {
run(&mut s, "sketch.drag", json!({"entity":"crank","from":[-7,0],"to":[target.x,target.y],"live":true}))
});
if r["retry"] != true {
continue;
}
exercised = true;
let at = pt(&s, "crank.end") * 0.7;
assert!(at.dist(target) < v(-7.0, 0.0).dist(target));
let r = run(&mut s, "sketch.drag", json!({"entity":"crank","from":[at.x,at.y],"to":[target.x,target.y],"live":true}));
assert!((pt(&s, "crank.end") * 0.7).dist(nearest) < 1e-4);
assert_eq!(r["retry"], false);
}
assert!(exercised, "exercise continuation after budget-limited progress");
}
+157
View File
@@ -105,3 +105,160 @@ fn four_bar_other_joint_follows_the_rocker_arc_and_its_limits() {
assert!(four_bar::point(&s, "coupler.end").unwrap().dist(nearest) < 1e-4);
}
}
fn grab(s: &solidcraft_engine::Session, line: &str, fraction: f64) -> Vec2 {
let a = four_bar::point(s, &format!("{line}.start")).unwrap();
let b = four_bar::point(s, &format!("{line}.end")).unwrap();
a + (b - a) * fraction
}
#[test]
fn a_free_line_grabbed_slightly_off_its_edge_still_translates_rigidly() {
for from in [Vec2::new(15.0, 12.0), Vec2::new(32.0, 11.0)] {
let mut s = solidcraft_engine::Session::default();
s.execute("sketch.create", &json!({"plane":"XZ"})).unwrap();
s.execute("sketch.line", &json!({"points":[[10,10],[30,10]],"ids":["free"],"infer":false})).unwrap();
let to = from + Vec2::new(3.0, 5.0);
let r = s.execute("sketch.drag", &json!({"entity":"free","from":[from.x,from.y],"to":[to.x,to.y],"live":true})).unwrap();
assert!(four_bar::point(&s, "free.start").unwrap().dist(Vec2::new(13.0, 15.0)) < 1e-6);
assert!(four_bar::point(&s, "free.end").unwrap().dist(Vec2::new(33.0, 15.0)) < 1e-6);
let at = Vec2::new(r["at"][0].as_f64().unwrap(), r["at"][1].as_f64().unwrap());
assert!(at.dist(to) < 1e-6);
}
}
#[test]
fn an_offset_edge_grab_rotates_with_the_link_and_does_not_drift() {
for local in [Vec2::new(0.7, 0.1), Vec2::new(0.7, -0.1)] {
let mut s = four_bar::session().unwrap();
let target = Vec2::new(-7.0, 11.2);
let closest = target * (10.0 * local.len() / target.len());
let attached = |s: &solidcraft_engine::Session| {
let a = four_bar::point(s, "crank.start").unwrap();
let d = four_bar::point(s, "crank.end").unwrap() - a;
a + d * local.x + Vec2::new(-d.y, d.x) * local.y
};
let mut from = attached(&s);
for _ in 0..8 {
let r = s.execute("sketch.drag", &json!({"entity":"crank","from":[from.x,from.y],"to":[target.x,target.y],"live":true})).unwrap();
from = Vec2::new(r["at"][0].as_f64().unwrap(), r["at"][1].as_f64().unwrap());
assert!(from.dist(attached(&s)) < 1e-6);
assert!(attached(&s).dist(closest) < 1e-4);
assert!(four_bar::length_error(&s).unwrap() < 1e-6);
assert_eq!(four_bar::branch(&s).unwrap(), -1.0);
}
}
}
#[test]
fn crank_edge_large_drag_reaches_the_nearest_material_point() {
for fraction in [0.2, 0.5, 0.8] {
let mut s = four_bar::session().unwrap();
let side = four_bar::branch(&s).unwrap();
let from = grab(&s, "crank", fraction);
let target = Vec2::new(-10.0, 16.0) * fraction;
let nearest = target * (10.0 * fraction / target.len());
let result = s.execute("sketch.drag", &json!({"entity":"crank", "from":[from.x,from.y], "to":[target.x,target.y], "live":true})).unwrap();
let actual = grab(&s, "crank", fraction);
assert!(four_bar::length_error(&s).unwrap() < 1e-6);
assert_eq!(four_bar::branch(&s).unwrap(), side);
assert!(actual.dist(nearest) < 1e-4, "fraction {fraction}: {actual:?}, expected {nearest:?}");
let at = Vec2::new(result["at"][0].as_f64().unwrap(), result["at"][1].as_f64().unwrap());
assert!(at.dist(actual) < 1e-6, "reported grab {at:?}, actual {actual:?}");
s.execute("sketch.drag_end", &json!({})).unwrap();
assert!(grab(&s, "crank", fraction).dist(nearest) < 1e-4);
}
}
#[test]
fn rocker_edge_keeps_its_material_point_and_motion_limits() {
let base = Vec2::new(42.0, 0.0);
let lo = -(-1264.0_f64 / 1680.0).acos();
let hi = -(0.2_f64).acos();
for fraction in [0.2, 0.5, 0.8] {
for angle in [-2.6_f64, -2.1, -1.5, -1.1] {
let mut s = four_bar::session().unwrap();
let from = grab(&s, "rocker", fraction);
let target = base + Vec2::new(angle.cos(), angle.sin()) * (60.0 * (1.0 - fraction));
let closest = base + Vec2::new(angle.clamp(lo, hi).cos(), angle.clamp(lo, hi).sin()) * (20.0 * (1.0 - fraction));
s.execute("sketch.drag", &json!({"entity":"rocker","from":[from.x,from.y],"to":[target.x,target.y],"live":true})).unwrap();
assert!(
grab(&s, "rocker", fraction).dist(closest) < 1e-4,
"fraction {fraction}, angle {angle}, actual {:?}, expected {closest:?}",
grab(&s, "rocker", fraction)
);
assert!(four_bar::length_error(&s).unwrap() < 1e-6);
assert_eq!(four_bar::branch(&s).unwrap(), -1.0);
}
}
}
#[test]
fn an_off_centre_edge_grab_agrees_for_one_move_split_moves_and_holding_still() {
for fraction in [0.2, 0.5, 0.8] {
for frames in [1, 16] {
let mut s = four_bar::session().unwrap();
let start = grab(&s, "crank", fraction);
let target = Vec2::new(-10.0, 16.0) * fraction;
let mut from = start;
for i in 1..=frames + 8 {
let to = start + (target - start) * (i.min(frames) as f64 / frames as f64);
let result = s.execute("sketch.drag", &json!({"entity":"crank","from":[from.x,from.y],"to":[to.x,to.y],"live":true})).unwrap();
from = Vec2::new(result["at"][0].as_f64().unwrap(), result["at"][1].as_f64().unwrap());
assert!(from.dist(grab(&s, "crank", fraction)) < 1e-6);
assert!(four_bar::length_error(&s).unwrap() < 1e-6);
}
let closest = target * (10.0 * fraction / target.len());
assert!(grab(&s, "crank", fraction).dist(closest) < 1e-4);
}
}
}
fn coupler_point(angle: f64, along: f64) -> Vec2 {
let a = Vec2::new(angle.cos(), angle.sin()) * 10.0;
let d = Vec2::new(42.0, 0.0) - a;
let len = d.len();
let u = d * (1.0 / len);
let x = (40.0 * 40.0 - 20.0 * 20.0 + len * len) / (2.0 * len);
let c = a + u * x + Vec2::new(u.y, -u.x) * (1600.0 - x * x).sqrt();
a + (c - a) * along
}
fn closest_coupler_point(target: Vec2, along: f64) -> Vec2 {
// Independent one-dimensional oracle: sample the full crank revolution, then refine
// the best interval. Both circle intersections keep the reported linkage's branch.
let step = std::f64::consts::TAU / 4096.0;
let best = (0..4096)
.min_by(|a, b| coupler_point(*a as f64 * step, along).dist(target).total_cmp(&coupler_point(*b as f64 * step, along).dist(target)))
.unwrap();
let (mut lo, mut hi) = ((best as f64 - 1.0) * step, (best as f64 + 1.0) * step);
for _ in 0..80 {
let a = (2.0 * lo + hi) / 3.0;
let b = (lo + 2.0 * hi) / 3.0;
if coupler_point(a, along).dist(target) < coupler_point(b, along).dist(target) {
hi = b;
} else {
lo = a;
}
}
coupler_point((lo + hi) * 0.5, along)
}
#[test]
fn the_coupler_edge_follows_with_both_ends_free_to_rotate() {
for along in [0.2, 0.5, 0.8] {
for angle in [1.8, 2.3, 3.8] {
let mut s = four_bar::session().unwrap();
let from = grab(&s, "coupler", along);
let target = coupler_point(angle, along) + Vec2::new(-3.0, 4.0);
let closest = closest_coupler_point(target, along);
let result = s.execute("sketch.drag", &json!({"entity":"coupler","from":[from.x,from.y],"to":[target.x,target.y],"live":true})).unwrap();
let actual = grab(&s, "coupler", along);
assert!(actual.dist(closest) < 1e-4, "along {along}, angle {angle}, actual {actual:?}, closest {closest:?}");
let at = Vec2::new(result["at"][0].as_f64().unwrap(), result["at"][1].as_f64().unwrap());
assert!(at.dist(actual) < 1e-6);
assert!(four_bar::length_error(&s).unwrap() < 1e-6);
assert_eq!(four_bar::branch(&s).unwrap(), -1.0);
}
}
}
+68 -11
View File
@@ -28,6 +28,44 @@ pub fn move_point_towards(
point: usize,
target: Vec2,
max_step: f64,
budget: Option<&mut Budget>,
valid: impl Fn(&Sketch, &Sketch) -> bool,
) -> bool {
move_cursor_towards(sk, &[(point, Vec2::X)], target, max_step, budget, valid)
}
/// Move a grabbed position attached to a line toward the cursor. `grab.x` is its fraction
/// along the line (0 at its start, 1 at its end); `grab.y` is the signed perpendicular offset,
/// also divided by the line's length. The offset rotates and scales with the line.
/// The line may rotate: its endpoints are not independently pinned to a translation.
/// Feasibility, work limits and the return value have the same meaning as [`move_point_towards`].
pub fn move_line_towards(
sk: &mut Sketch,
line: usize,
grab: Vec2,
target: Vec2,
max_step: f64,
budget: Option<&mut Budget>,
valid: impl Fn(&Sketch, &Sketch) -> bool,
) -> bool {
if !grab.is_finite() {
return false;
}
let Some(CurveKind::Line { a, b }) = sk.curves.get(line).map(|c| &c.kind) else { return false };
let (Some(pa), Some(pb)) = (sk.point(*a), sk.point(*b)) else { return false };
let d = pb - pa;
if !(d.dot(d) > 1e-18 && crate::model::in_range(pa + weighted(d, grab))) {
return false;
}
move_cursor_towards(sk, &[(*a, Vec2::new(1.0 - grab.x, -grab.y)), (*b, grab)], target, max_step, budget, valid)
}
// Both callers' endpoint weights sum to (1, 0): translating the anchors translates the grab.
fn move_cursor_towards(
sk: &mut Sketch,
points: &[(usize, Vec2)],
target: Vec2,
max_step: f64,
mut budget: Option<&mut Budget>,
valid: impl Fn(&Sketch, &Sketch) -> bool,
) -> bool {
@@ -40,10 +78,15 @@ pub fn move_point_towards(
}
let problem = sk.clone();
let lay = layout(&problem, &Hold::default());
let Some(px) = lay.pvar.get(point).copied().flatten() else { return false };
let active: Vec<_> =
points.iter().filter(|(_, w)| w.x != 0.0 || w.y != 0.0).filter_map(|(p, w)| Some((lay.pvar.get(*p).copied().flatten()?, *w))).collect();
let Some(&(px, _)) = active.first() else { return false };
let (blocks, _) = build_blocks(&problem, &lay, &points_on_curves(&problem));
let mut parent: Vec<usize> = (0..lay.n).collect();
union(&mut parent, px, px + 1);
for &(v, _) in &active {
union(&mut parent, px, v);
union(&mut parent, px, v + 1);
}
for (_, vars) in &blocks {
if let Some(&first) = vars.first() {
for &v in vars.iter().skip(1) {
@@ -70,7 +113,13 @@ pub fn move_point_towards(
}
let mut col = vec![usize::MAX; lay.n];
columns(&mut col, &vars, &vars);
let (Some(ix), Some(iy)) = (vars.iter().position(|v| *v == px), vars.iter().position(|v| *v == px + 1)) else { return false };
let axes: Vec<_> = active.iter().filter_map(|(v, w)| Some((vars.binary_search(v).ok()?, *w))).collect();
let position = |x: &[f64]| {
let state = State { sk: &problem, lay: &lay, x };
// Relative coordinates avoid cancellation when a small line is far from the origin.
let base = points.first().map_or(Vec2::ZERO, |(p, _)| state.p(*p));
points.iter().fold(base, |at, (p, w)| at + weighted(state.p(*p) - base, *w))
};
let mut best = problem.clone();
let mut spent = 0;
// Held feasibility solves accept up to ACCEPT. A tiny, nearly feasible hard pin can
@@ -91,7 +140,7 @@ pub fn move_point_towards(
}
let mut gain = 1.0_f64;
for _ in 0..MAX_STEPS {
let at = State { sk: &problem, lay: &lay, x: &x }.p(point);
let at = position(&x);
let error = target - at;
if error.len() < 1e-7 || spent >= TOTAL_CORRECTION_ITERS {
break;
@@ -110,7 +159,7 @@ pub fn move_point_towards(
if z.is_empty() {
break;
}
let mut direction = target_step(&z, ix, iy, error);
let mut direction = target_step(&z, &axes, error);
let norm = length(&direction);
// Adapt to curvature of the reachable locus. Inside a circle the Gauss-Newton
// cursor step can be arbitrarily small although useful freedom remains.
@@ -122,7 +171,7 @@ pub fn move_point_towards(
// A cursor across a circular locus has (nearly) zero first derivative at the
// farthest point. If line search stalls, probe both tangent directions. Testing
// only an exactly zero gradient would strand reversed drags after rounding.
let influence = |v: &&Vec<f64>| v.get(ix).copied().unwrap_or(0.0).hypot(v.get(iy).copied().unwrap_or(0.0));
let influence = |v: &&Vec<f64>| cursor_direction(v, &axes).len();
let mut probes: Vec<_> = z.iter().collect();
probes.sort_by(|a, b| influence(b).total_cmp(&influence(a)));
for v in probes.into_iter().take(2) {
@@ -165,7 +214,7 @@ pub fn move_point_towards(
}
continue;
}
let next = State { sk: &problem, lay: &lay, x: &trial }.p(point);
let next = position(&trial);
let cost = (target - next).dot(target - next);
if !cost.is_finite() || cost >= old_cost - 1e-14 * old_cost.max(1.0) {
continue;
@@ -248,13 +297,21 @@ fn null_space(mut j: Mat) -> Vec<Vec<f64>> {
z
}
fn target_step(z: &[Vec<f64>], ix: usize, iy: usize, error: Vec2) -> Vec<f64> {
/// The second weight component multiplies a 90-degree rotation of the endpoint.
fn weighted(v: Vec2, w: Vec2) -> Vec2 {
if w.y == 0.0 { v * w.x } else { Vec2::new(v.x * w.x - v.y * w.y, v.y * w.x + v.x * w.y) }
}
fn cursor_direction(v: &[f64], axes: &[(usize, Vec2)]) -> Vec2 {
axes.iter().fold(Vec2::ZERO, |at, (i, w)| at + weighted(Vec2::new(v.get(*i).copied().unwrap_or(0.0), v.get(*i + 1).copied().unwrap_or(0.0)), *w))
}
fn target_step(z: &[Vec<f64>], axes: &[(usize, Vec2)], error: Vec2) -> Vec<f64> {
let mut a = 0.0;
let mut b = 0.0;
let mut c = 0.0;
for q in z {
let x = q.get(ix).copied().unwrap_or(0.0);
let y = q.get(iy).copied().unwrap_or(0.0);
let Vec2 { x, y } = cursor_direction(q, axes);
a += x * x;
b += x * y;
c += y * y;
@@ -269,7 +326,7 @@ fn target_step(z: &[Vec<f64>], ix: usize, iy: usize, error: Vec2) -> Vec<f64> {
}
let mut step = vec![0.0; z.first().map_or(0, Vec::len)];
for q in z {
let d = q.get(ix).copied().unwrap_or(0.0) * u.x + q.get(iy).copied().unwrap_or(0.0) * u.y;
let d = cursor_direction(q, axes).dot(u);
for (x, v) in step.iter_mut().zip(q) {
*x += d * v;
}
+2 -2
View File
@@ -63,8 +63,8 @@ pub use profiles::{
};
pub use shape::{Shape, intersections};
pub use solver::{
Analysis, CONSISTENT, DrivingValues, Hold, SolveReport, SolveStatus, constraint_residual, determined_by, measure_dimension, move_point_towards,
solve, solve_after_edit, solve_after_value_edit, solve_holding, solve_with,
Analysis, CONSISTENT, DrivingValues, Hold, 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,
};
pub use text::{MAX_TEXT_CHARS, TextAlign, TextStyle, text_geometry, text_geometry_in, text_geometry_styled};
pub use thin::{MAX_THIN_SEGMENTS, thin_wall_regions};
+2 -2
View File
@@ -23,7 +23,7 @@ use crate::union_find::{find, union};
#[path = "cursor.rs"]
mod cursor;
pub use cursor::move_point_towards;
pub use cursor::{move_line_towards, move_point_towards};
#[path = "redundancy.rs"]
mod redundancy;
@@ -2036,7 +2036,7 @@ fn solve_inner(
// start (the seeded one is where the pinned solve failed), or to its own start when
// the seed did not move it.
let reseeded = unseeded.as_ref().filter(|plain| vars.iter().any(|v| plain.get(*v).is_some_and(Option::is_some)));
if !solved && !(pinned_failed && reseeded.is_some()) {
if !(solved || pinned_failed && reseeded.is_some()) {
let (its, r) = lm(sk, &lay, &sub, vars, &mut x, &col);
iterations += its;
residual = r;
+26 -1
View File
@@ -1,6 +1,6 @@
//! Analytic cursor oracle plus feasibility checks on every accepted continuation step.
use solidcraft_geom::Vec2;
use solidcraft_sketch::{ConstraintKind, Sketch, move_point_towards, solve};
use solidcraft_sketch::{ConstraintKind, Sketch, move_line_towards, move_point_towards, solve};
fn linkage() -> (Sketch, usize, usize) {
let mut sk = Sketch::new();
@@ -16,6 +16,31 @@ fn linkage() -> (Sketch, usize, usize) {
(sk, a, c)
}
#[test]
fn a_material_point_on_a_link_follows_without_relaxing_its_length() {
for along in [0.2, 0.5, 0.8] {
for target in [Vec2::new(-10.0, 16.0), Vec2::new(20.0, 0.0), Vec2::new(1000.0, -1000.0)] {
let (mut sk, a, c) = linkage();
let line = sk.add_line_pts(0, a, None).unwrap();
let target = target * along;
assert!(move_line_towards(&mut sk, line, Vec2::new(along, 0.0), target, 1.25, None, |before, after| {
assert!((after.points[a].pos.len() - 10.0).abs() < 1e-9);
assert!((after.points[a].pos.dist(after.points[c].pos) - 40.0).abs() < 1e-9);
assert!((after.points[c].pos.dist(Vec2::new(42.0, 0.0)) - 20.0).abs() < 1e-9);
assert!((after.points[a].pos * along).dist(target) < (before.points[a].pos * along).dist(target));
(Vec2::new(42.0, 0.0) - after.points[a].pos).cross(after.points[c].pos - after.points[a].pos) < 0.0
}));
let closest = target * (10.0 * along / target.len());
assert!((sk.points[a].pos * along).dist(closest) < 1e-4);
let before = sk.clone();
for invalid in [Vec2::new(f64::NAN, 0.0), Vec2::new(0.5, f64::INFINITY), Vec2::new(1e300, 1e300)] {
assert!(!move_line_towards(&mut sk, line, invalid, target, 1.25, None, |_, _| true));
assert_eq!(sk, before);
}
}
}
}
#[test]
fn circle_oracle_all_directions_and_large_targets() {
for radius in [1.0, 12.8, 28.3, 100.0, 1000.0] {
@@ -97,6 +97,72 @@ fn steps(a: egui::Pos2, b: egui::Pos2, n: usize) -> Vec<egui::Pos2> {
(1..=n).map(|k| a + (b - a) * (k as f32 / n as f32)).collect()
}
fn four_bar() -> Harness {
let mut h = Harness::new();
h.app.home.open = false;
run(&mut h, "sketch.create", json!({"plane":"XZ"}));
let x = -10.0 + (1600.0 - 400.0 + 52.0 * 52.0) / 104.0;
let y = -(1600.0_f64 - (x + 10.0) * (x + 10.0)).sqrt();
run(&mut h, "sketch.line", json!({"points":[[0,0],[-10,0],[x,y],[42,0]],"ids":["crank","coupler","rocker"],"infer":false}));
run(&mut h, "sketch.line", json!({"points":["crank.start","rocker.end"],"ids":["ground"],"infer":false}));
for (line, length) in [("crank", 10), ("coupler", 40), ("rocker", 20), ("ground", 42)] {
run(&mut h, "sketch.dimension", json!({"entities":[line],"value":length}));
}
run(&mut h, "sketch.constraint.horizontal_vertical", json!({"line":"ground"}));
run(&mut h, "sketch.options", json!({"snap":false,"show_dimensions":false,"show_constraints":false}));
h.settle();
h
}
#[test]
fn a_four_bar_edge_follows_a_stationary_pointer_and_keeps_the_grab() {
let mut h = four_bar();
let a = screen(&mut h, -7.0, 0.0);
let b = screen(&mut h, -7.0, 11.2);
let undo = h.app.session.undo.len();
press_and_move(&mut h, &[a, b]);
assert_eq!(h.app.viewport.point_drag.as_ref().map(|(id, _, _)| id.as_str()), Some("crank"), "grabbed the edge, not an endpoint");
h.frames(8);
let nearest = Vec2::new(-10.0, 16.0).normalized().unwrap() * 10.0;
assert!(point(&h, "crank.end").dist(nearest) < 0.05, "{:?}", point(&h, "crank.end"));
release(&mut h, b);
assert!(point(&h, "crank.end").dist(nearest) < 0.05);
assert_eq!(h.app.session.undo.len(), undo + 1);
run(&mut h, "edit.undo", json!({}));
assert!(point(&h, "crank.end").dist(Vec2::new(-10.0, 0.0)) < 1e-7);
}
#[test]
fn a_four_bar_release_uses_the_final_pointer_position() {
let mut h = four_bar();
let a = screen(&mut h, -10.0, 0.0);
let b = screen(&mut h, -10.0, 3.0);
let end = screen(&mut h, -10.0, 16.0);
press_and_move(&mut h, &[a, b]);
h.frames(8);
assert_eq!(h.app.viewport.point_drag.as_ref().map(|(id, _, _)| id.as_str()), Some("crank.end"));
release(&mut h, end);
let nearest = Vec2::new(-10.0, 16.0).normalized().unwrap() * 10.0;
assert!(point(&h, "crank.end").dist(nearest) < 0.05, "release left {:?}", point(&h, "crank.end"));
assert!(!h.app.session.model.is_stale());
}
#[test]
fn a_four_bar_edge_grab_keeps_its_pick_offset_when_rotating() {
let mut h = four_bar();
let a = screen(&mut h, -7.0, 0.25);
let b = screen(&mut h, -7.0, 11.2);
press_and_move(&mut h, &[a, b]);
assert_eq!(h.app.viewport.point_drag.as_ref().map(|(id, _, _)| id.as_str()), Some("crank"));
h.frames(8);
release(&mut h, b);
let local = Vec2::new(0.7, -0.025);
let target = Vec2::new(-7.0, 11.2);
let closest = target * (10.0 * local.len() / target.len());
let end = (closest * local.x - Vec2::new(-closest.y, closest.x) * local.y) * (1.0 / local.dot(local));
assert!(point(&h, "crank.end").dist(end) < 0.05, "{:?}, expected {end:?}", point(&h, "crank.end"));
}
#[test]
fn a_viewport_drag_solves_the_sketch_live_and_rebuilds_the_model_on_release() {
let mut h = Harness::new();
+6 -1
View File
@@ -2746,7 +2746,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
}
}
if let Some((id, depth, grab)) = app.viewport.point_drag.clone()
&& resp.dragged_by(egui::PointerButton::Primary)
&& (resp.dragged_by(egui::PointerButton::Primary) || resp.drag_stopped())
&& let Some(mut q) = hover.and_then(|p| on_plane(app, p))
{
let from = grab.unwrap_or(q);
@@ -2783,6 +2783,11 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
let at = match app.session.execute("sketch.drag", &params) {
Ok(r) => {
app.session.undo.truncate(depth + 1);
// Budget-limited progress continues even when the mouse stops. A stalled
// search asks for no more frames; release gets one bounded final attempt.
if r.get("retry").and_then(serde_json::Value::as_bool) == Some(true) && !resp.drag_stopped() {
ui.ctx().request_repaint();
}
r.get("at").and_then(solidcraft_engine::params::vec2).unwrap_or(q)
}
Err(_) => from,