VectorCraft: An open-source, vector art tool written by scratch in pure Rust
Perspective Selection: Snap to Grid keeps a Shift-constrained move on its axis or diagonal
dotCooCoo9f644523030a
diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rsindex 3da43957c..e22469279 100644--- a/crates/engine/src/cmd/distortcmds.rs+++ b/crates/engine/src/cmd/distortcmds.rs@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {"Move in Perspective",[],None,- "{ids?|id?, from: [x,y], to: [x,y], plane?, copy?: bool (move copies, as Alt-dragging does), perpendicular?: bool (move along the plane's normal instead, as pressing 5 while dragging does), snap?: bool (default: View › Perspective Grid › Snap to Grid)} slide objects within their plane (unattached objects attach to `plane`/the active plane first); snapping lands the nearer edge of the objects' joint bounds on a gridline within a quarter cell; Transform Again repeats it",+ "{ids?|id?, from: [x,y], to: [x,y], plane?, copy?: bool (move copies, as Alt-dragging does), perpendicular?: bool (move along the plane's normal instead, as pressing 5 while dragging does), snap?: bool (default: View › Perspective Grid › Snap to Grid), constrain?: [dx,dy] (nonzero plane-space direction; keeps snap correction on that line for in-plane moves)} slide objects within their plane (unattached objects attach to `plane`/the active plane first); snapping pulls the nearer edge of the objects' joint bounds toward a gridline within a quarter cell, along `constrain` when supplied; Transform Again repeats it",has_doc,persp_move),diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rsindex 848177027..023fa95c2 100644--- a/crates/engine/src/cmd/distortcmds/perspective.rs+++ b/crates/engine/src/cmd/distortcmds/perspective.rs@@ -284,12 +284,28 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {}let fallback = plane_param(&grid_of(&s.doc()?.doc), p, C).ok();let (perp, copy) = (switch_or(p, "perpendicular", false, C)?, switch_or(p, "copy", false, C)?);+ let constrain = match p.get("constrain").filter(|v| !v.is_null()) {+ Some(v) => {+ let direction = v.as_array().filter(|v| v.len() == 2).and_then(|v| Some((v.first()?.as_f64()?, v.get(1)?.as_f64()?)));+ let (x, y) = direction.ok_or_else(|| bad(C, "constrain must be two finite numbers, not both zero"))?;+ if !x.is_finite() || !y.is_finite() || (x == 0.0 && y == 0.0) {+ return Err(bad(C, "constrain must be two finite numbers, not both zero"));+ }+ let scale = x.abs().max(y.abs());+ let (x, y) = (x / scale, y / scale);+ let length = x.hypot(y);+ Some(vectorcraft_geom::Vec2::new(x / length, y / length))+ }+ None => None,+ };// `snap_fix` uses Snap to Grid's setting for a `snap` that is not true or false.check_switches(p, &["snap"], C)?;// Snap to Grid: a correction for the objects on the first one's plane and depth.let fix = if perp { None } else { crate::cmd::perspgrid::snap_fix(&s.doc()?.doc, &ids, p, (from, to)) };let snapped = move |pl: Plane, depth: f64, dv: vectorcraft_geom::Vec2| {- dv + fix.filter(|f| f.0 == pl && f.1 == depth).map_or(vectorcraft_geom::Vec2::ZERO, |f| f.2)+ dv + fix+ .filter(|f| f.0 == pl && f.1 == depth)+ .map_or(vectorcraft_geom::Vec2::ZERO, |f| constrain.map_or(f.2, |unit| unit * (f.2.x * unit.x + f.2.y * unit.y)))};// In-plane: the plane-space offset under the pointer; perpendicular: the depth it reaches.let step = |g: &PerspectiveGrid, pl: Plane, depth: f64| -> Result<(Homography, f64)> {diff --git a/crates/engine/src/tests/persp_select.rs b/crates/engine/src/tests/persp_select.rsindex a6f912b73..b3e8341f5 100644--- a/crates/engine/src/tests/persp_select.rs+++ b/crates/engine/src/tests/persp_select.rs@@ -129,6 +129,89 @@ fn shift_drag_moves_on_a_plane_axis() {assert_eq!(plane_pts(&s, id, Plane::Right, 0.0), before);}+/// An attached rectangle with a horizontal edge close enough to a gridline to be pulled by snapping.+fn near_gridline_session() -> (Session, NodeId) {+ let (mut s, id) = persp_session();+ let g = grid(&s);+ let b = bounds_of(&plane_pts(&s, id, Plane::Right, 0.0));+ let dy = (b.y0 / g.cell).round() * g.cell + g.cell * 0.1 - b.y0;+ let h = g.homography(Plane::Right).unwrap();+ let from = h.apply(b.center()).unwrap();+ let to = h.apply(b.center() + Vec2::new(0.0, dy)).unwrap();+ s.execute("perspective.move", &json!({"ids": [id.0], "from": [from.x, from.y], "to": [to.x, to.y], "snap": false})).unwrap();+ s.execute("perspective.grid.snap", &json!({"on": true})).unwrap();+ (s, id)+}++fn shift_move_near_gridline(diagonal: bool, copy: bool) {+ let (mut s, id) = near_gridline_session();+ s.select_tool("perspectiveSelection", ViewInfo::default()).unwrap();+ let before = plane_pts(&s, id, Plane::Right, 0.0);+ let h = grid(&s).homography(Plane::Right).unwrap();+ let start = bounds_of(&before).center();+ let raw = if diagonal { Vec2::new(40.0, 50.0) } else { Vec2::new(80.0, 20.0) };+ let from = h.apply(start).unwrap();+ let to = h.apply(start + raw).unwrap();+ drag(&mut s, &[from, to, to], Mods { shift: true, alt: copy, ..Default::default() });+ let target = if copy { *s.doc().unwrap().selection.objects.first().unwrap() } else { id };+ assert!(!copy || target != id);+ let after = plane_pts(&s, target, Plane::Right, 0.0);+ for (a, b) in before.iter().zip(after) {+ let d = b - *a;+ if diagonal {+ assert!((d.x - d.y).abs() < 1e-6, "diagonal move left its line: {d:?}");+ } else {+ assert!(d.y.abs() < 1e-6, "axis move left its line: {d:?}");+ }+ }+ if copy {+ assert_eq!(plane_pts(&s, id, Plane::Right, 0.0), before);+ }+}++#[test]+fn shift_axis_move_stays_on_axis_with_grid_snap() {+ shift_move_near_gridline(false, false);+}++#[test]+fn shift_axis_copy_stays_on_axis_with_grid_snap() {+ shift_move_near_gridline(false, true);+}++#[test]+fn shift_diagonal_move_stays_on_diagonal_with_grid_snap() {+ shift_move_near_gridline(true, false);+}++#[test]+fn shift_diagonal_copy_stays_on_diagonal_with_grid_snap() {+ shift_move_near_gridline(true, true);+}++#[test]+fn constrained_move_command_stays_on_axis_with_grid_snap() {+ let (mut s, id) = near_gridline_session();+ let before = plane_pts(&s, id, Plane::Right, 0.0);+ let h = grid(&s).homography(Plane::Right).unwrap();+ let start = bounds_of(&before).center();+ let from = h.apply(start).unwrap();+ let to = h.apply(start + Vec2::new(80.0, 0.0)).unwrap();+ s.execute("perspective.move", &json!({"ids": [id.0], "from": [from.x, from.y], "to": [to.x, to.y], "constrain": [1.0, 0.0]})).unwrap();+ for (a, b) in before.iter().zip(plane_pts(&s, id, Plane::Right, 0.0)) {+ assert!((b.y - a.y).abs() < 1e-6, "constrained command left axis: {a:?} to {b:?}");+ }+}++#[test]+fn constrained_move_rejects_invalid_direction() {+ let (mut s, id) = near_gridline_session();+ for direction in [json!([0.0, 0.0]), json!([1.0]), json!([1.0, "bad"]), json!([null, 1.0])] {+ let error = s.execute("perspective.move", &json!({"ids": [id.0], "from": [1.0, 1.0], "to": [2.0, 2.0], "constrain": direction})).unwrap_err();+ assert!(error.to_string().contains("constrain must be two finite numbers, not both zero"), "{error}");+ }+}+#[test]fn shift_drag_keeps_its_displacement_after_a_plane_key() {let (mut s, id) = persp_session();diff --git a/crates/tools/src/distort/perspective.rs b/crates/tools/src/distort/perspective.rsindex 2542e6a1a..9052ecca4 100644--- a/crates/tools/src/distort/perspective.rs+++ b/crates/tools/src/distort/perspective.rs@@ -1250,6 +1250,9 @@ mod tests {let endpoint = Point::new(v["to"][0].as_f64().unwrap(), v["to"][1].as_f64().unwrap());let delta = hi.apply(endpoint).unwrap() - start;assert!((delta - expected).hypot() < 1e-6, "{plane:?}: {delta:?} != {expected:?}");+ let direction = expected / expected.hypot();+ let sent = Vec2::new(v["constrain"][0].as_f64().unwrap(), v["constrain"][1].as_f64().unwrap());+ assert!((sent - direction).hypot() < 1e-12, "{plane:?}: {sent:?} != {direction:?}");}}}@@ -1276,16 +1279,19 @@ mod tests {t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(Mods { shift: true, alt: true, ..Default::default() }));let Some(Action::Preview(_, snapped)) = shifted.last() else { panic!("{shifted:?}") };assert_eq!(snapped["copy"], json!(true));+ assert_eq!(snapped["constrain"], json!([1.0, 0.0]));assert_ne!(snapped["to"], raw["to"]);let perpendicular = t.key(&c, ToolKey::Digit(5), Mods { shift: true, alt: true, ..Default::default() });let Some(Action::Preview(_, depth)) = perpendicular.last() else { panic!("{perpendicular:?}") };assert_eq!(depth["to"], raw["to"]);+ assert!(depth.get("constrain").is_none());let in_plane = t.key(&c, ToolKey::Digit(5), Mods { shift: true, alt: true, ..Default::default() });let Some(Action::Preview(_, snapped_again)) = in_plane.last() else { panic!("{in_plane:?}") };assert_eq!(snapped_again["to"], snapped["to"]);let released = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y));let Some(Action::Preview(_, raw_again)) = released.last() else { panic!("{released:?}") };assert_eq!(raw_again["to"], raw["to"]);+ assert!(raw_again.get("constrain").is_none());}#[test]diff --git a/crates/tools/src/distort/perspective/tools.rs b/crates/tools/src/distort/perspective/tools.rsindex 9e9454b30..d748cb51b 100644--- a/crates/tools/src/distort/perspective/tools.rs+++ b/crates/tools/src/distort/perspective/tools.rs@@ -167,7 +167,7 @@ impl PerspectiveSelectionTool {let SelDrag::Move { ids, from, last, perp, copy, shift, .. } = &self.drag else { return None };let g = PerspectiveGrid::current(cx.doc);let at = ids.first().and_then(|id| g.attachment_of(cx.doc, *id)).or((g.plane != Plane::None).then_some((g.plane, g.offset(g.plane))));- let to = if *shift && !*perp {+ let constrained = if *shift && !*perp {at.and_then(|(plane, depth)| {let h = g.homography_at(plane, depth)?;let hi = h.inverse()?;@@ -176,13 +176,16 @@ impl PerspectiveSelectionTool {let angle = (delta.y.atan2(delta.x) / std::f64::consts::FRAC_PI_4).round() * std::f64::consts::FRAC_PI_4;let direction = Vec2::new(angle.cos(), angle.sin());let distance = delta.x * direction.x + delta.y * direction.y;- h.apply(start + direction * distance).filter(|p| p.x.is_finite() && p.y.is_finite())+ h.apply(start + direction * distance).filter(|p| p.x.is_finite() && p.y.is_finite()).map(|to| (to, direction))})- .unwrap_or(*last)} else {- *last+ None};+ let to = if let Some((to, _)) = constrained { to } else { *last };let mut v = json!({"ids": crate::json_ids(ids), "from": [from.x, from.y], "to": [to.x, to.y], "copy": copy, "perpendicular": perp});+ if let Some((_, direction)) = constrained {+ v["constrain"] = json!([direction.x, direction.y]);+ }if g.plane != Plane::None {v["plane"] = json!(g.plane.id());}diff --git a/docs/mcp.md b/docs/mcp.mdindex add4788c4..164320533 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -5477,7 +5477,9 @@ distance along the plane's normal), so copies, duplicates and pastes stay attach`perspectiveSelection` tool, a drag moves the selection within its plane (`perspective.move`; Alt copies), thebounding-box handles scale it in plane space (`perspective.transform`; Shift keeps proportions, Alt scales about thecentre), and `press_key` `5` during a drag switches the move to perpendicular to the plane (press again to switch-back). `press_key` Escape during a move, a resize or a plane widget drag cancels it and puts the objects and the+back). Holding Shift during an in-plane move constrains the displacement to a plane axis or 45° diagonal; `perspective.move`+passes that plane-space direction as `constrain: [dx, dy]`, so Snap to Grid adjusts the move only along that line.+`press_key` Escape during a move, a resize or a plane widget drag cancels it and puts the objects and thegrid back. The arrow keys nudge a selection in perspective by the keyboard increment (`perspective.nudge`; Shift ×10, Altcopies). Object › Transform › Transform Again repeats the last perspective move or scale in plane space.