From 791abbd9b10e85f37da68af3f2d7000f504efe15 Mon Sep 17 00:00:00 2001 From: Ryan <45923095+Ryan-Red@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:11:42 +0000 Subject: [PATCH] Sketch: hold horizontal/vertical and line up with other points at once while drawing (#7828) (#8474) * claim: #7828 Co-Authored-By: Claude Opus 5.5 * Sketch: hold horizontal/vertical and line up with other points at once while drawing (#7828) While drawing, the pointer lines up horizontally with the nearest sketch point level with it and vertically with the nearest one plumb with it, at the same time, as a dragged point already does; holding H/V with the previous point still lines up across with another point. Dotted guides run from the points lined up with (H, V or H+V), and the click adds a Horizontal or Vertical constraint with each, in the shape's undo step, unless the sketch already has it. A click takes the tool out of the app while it runs, so refine_snap treated every tool as the Line tool then: a rectangle's click could take a line-extension inference its hover never showed. The tool's points and kind are kept from the last hover, as the previous point was. Preferences > Sketch > "Line up with other sketch points while drawing" (sketch_align_points) turns it off for the old behaviour. Co-Authored-By: Claude Opus 5.5 * Sketch: lining up with other points is off unless turned on Review on #8474: sketch_align_points defaults to off, so nothing changes for anyone who doesn't turn it on. With it off, a click also treats the tool as before (the Line tool's inferences), instead of keeping the tool's kind from the hover. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../locales/pending/sketch-align-points.json | 34 +++++ crates/ui-egui/src/prefs.rs | 5 + crates/ui-egui/src/prefs/sketch.rs | 2 + .../ui-egui/src/sketch_guidance_ui_tests.rs | 109 +++++++++++++ crates/ui-egui/src/sketch_tools.rs | 144 ++++++++++++++++-- crates/ui-egui/src/tools.rs | 12 ++ docs/book/src/guide/sketching.md | 11 ++ 7 files changed, 303 insertions(+), 14 deletions(-) create mode 100644 assets/locales/pending/sketch-align-points.json diff --git a/assets/locales/pending/sketch-align-points.json b/assets/locales/pending/sketch-align-points.json new file mode 100644 index 000000000..6e697b75b --- /dev/null +++ b/assets/locales/pending/sketch-align-points.json @@ -0,0 +1,34 @@ +{ + "en": { + "prefs.sketch_align_points": "Line up with other sketch points while drawing", + "prefs.sketch_align_points_note": "While drawing, a point lines up horizontally with one sketch point and vertically with another at the same time, with a dotted guide, and the click keeps both alignments. Off: only with the previous point, one axis at a time." + }, + "ar": { + "prefs.sketch_align_points": "المحاذاة مع نقاط الرسم الأخرى أثناء الرسم", + "prefs.sketch_align_points_note": "أثناء الرسم، تتحاذى النقطة أفقيًا مع نقطة رسم وعموديًا مع نقطة أخرى في الوقت نفسه، مع خط إرشادي منقط، وتحتفظ النقرة بالمحاذاتين. عند الإيقاف: مع النقطة السابقة فقط، محور واحد في كل مرة." + }, + "de": { + "prefs.sketch_align_points": "Beim Zeichnen an anderen Skizzenpunkten ausrichten", + "prefs.sketch_align_points_note": "Beim Zeichnen richtet sich ein Punkt zugleich waagerecht an einem Skizzenpunkt und senkrecht an einem anderen aus, mit einer gepunkteten Hilfslinie; der Klick behält beide Ausrichtungen. Aus: nur am vorherigen Punkt, jeweils eine Achse." + }, + "he": { + "prefs.sketch_align_points": "יישור לנקודות סקיצה אחרות בזמן השרטוט", + "prefs.sketch_align_points_note": "בזמן השרטוט, נקודה מתיישרת אופקית עם נקודת סקיצה אחת ואנכית עם אחרת בו-זמנית, עם קו עזר מנוקד, והלחיצה שומרת את שני היישורים. כבוי: רק עם הנקודה הקודמת, ציר אחד בכל פעם." + }, + "ja": { + "prefs.sketch_align_points": "描画中にほかのスケッチ点に揃える", + "prefs.sketch_align_points_note": "描画中、点が一つのスケッチ点と水平に、別の点と垂直に同時に揃い、点線のガイドが表示されます。クリックすると両方の整列が保持されます。オフ: 直前の点にのみ、一度に一方向だけ揃えます。" + }, + "ko": { + "prefs.sketch_align_points": "그리는 동안 다른 스케치 점에 맞추기", + "prefs.sketch_align_points_note": "그리는 동안 점이 한 스케치 점과 수평으로, 다른 점과 수직으로 동시에 맞춰지고 점선 안내선이 표시됩니다. 클릭하면 두 정렬이 모두 유지됩니다. 끄기: 이전 점에만, 한 번에 한 축씩 맞춥니다." + }, + "vi": { + "prefs.sketch_align_points": "Căn theo các điểm phác thảo khác khi vẽ", + "prefs.sketch_align_points_note": "Khi vẽ, một điểm được căn ngang theo một điểm phác thảo và căn dọc theo điểm khác cùng lúc, kèm đường dẫn chấm; cú nhấp giữ cả hai ràng buộc căn. Tắt: chỉ căn theo điểm trước, mỗi lần một trục." + }, + "zh": { + "prefs.sketch_align_points": "绘制时与其他草图点对齐", + "prefs.sketch_align_points_note": "绘制时,点可同时与一个草图点水平对齐、与另一个草图点竖直对齐,并显示虚线参考线;单击后保留两个对齐约束。关闭:仅与上一点对齐,每次一个方向。" + } +} diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 4d3c1eb09..681e49cd5 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -1229,6 +1229,10 @@ preference_settings! { suppress_sketch_snap: ModifierCombo = ModifierCombo::CTRL_ALT, PAGE_SKETCH; /// Temporary horizontal/vertical guides from hovered centres and edge midpoints. sketch_tracking_guides: bool = true, PAGE_SKETCH; + /// Drawing lines a point up with the sketch's points on both axes at once, keeping the + /// horizontal or vertical snap to the previous point, and the click adds the alignments + /// (#7828). Off by default: only with the previous point, one axis at a time, as before. + sketch_align_points: bool = false, PAGE_SKETCH; /// Open Project's options before picking; off restores its previous direct-pick workflow. project_options_dialog: bool = true, PAGE_SKETCH; /// Whether Alt/Option also frees gizmo / canvas manipulator arrows (Primary always does). @@ -4806,6 +4810,7 @@ mod tests { ("suppress_sketch_snap", json!(ModifierCombo::NONE), PAGE_SKETCH), ("sketch_state_icons", json!(false), PAGE_SKETCH), ("sketch_tracking_guides", json!(false), PAGE_SKETCH), + ("sketch_align_points", json!(true), PAGE_SKETCH), ("msaa", json!(8), PAGE_GRAPHICS), ("single_surface_analysis", json!(false), PAGE_GRAPHICS), ]; diff --git a/crates/ui-egui/src/prefs/sketch.rs b/crates/ui-egui/src/prefs/sketch.rs index b72466c2c..6455f8835 100644 --- a/crates/ui-egui/src/prefs/sketch.rs +++ b/crates/ui-egui/src/prefs/sketch.rs @@ -7,6 +7,8 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::settings_section(ui, "sketch", app.tr("prefs.sketching"), |ui| { ui_kit::checkbox(ui, app.tr("prefs.sketch_tracking_guides"), &mut app.preferences.sketch_tracking_guides) .on_hover_text(app.tr("prefs.sketch_tracking_guides_note")); + ui_kit::checkbox(ui, app.tr("prefs.sketch_align_points"), &mut app.preferences.sketch_align_points) + .on_hover_text(app.tr("prefs.sketch_align_points_note")); let mut auto = app.session.auto_project; if ui_kit::checkbox(ui, crate::i18n::tr_label("Project face edges into new sketches"), &mut auto).changed() { let _ = app.run("sketch.auto_project", json!({"value": auto})); diff --git a/crates/ui-egui/src/sketch_guidance_ui_tests.rs b/crates/ui-egui/src/sketch_guidance_ui_tests.rs index 8a659ec81..63185e10a 100644 --- a/crates/ui-egui/src/sketch_guidance_ui_tests.rs +++ b/crates/ui-egui/src/sketch_guidance_ui_tests.rs @@ -355,3 +355,112 @@ fn tracking_does_not_leak_outside_the_viewport_or_into_another_sketch() { h.frames(3); assert!(h.app.viewport.tracking.guide.is_none()); } + +/// Lining up while drawing (#7828), turned on (it is off by default): a fixture whose points sit +/// off the grid, so that only lining up can place a point exactly on them, seen from the top at +/// about 1 mm of snap tolerance. +fn lining_up_fixture(points: &[(&str, Value)]) -> Harness { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.look_at_anim = false; + assert!(!h.app.preferences.sketch_align_points, "off unless turned on"); + h.app.preferences.sketch_align_points = true; + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + for (command, params) in points { + h.app.run(command, params.clone()).unwrap(); + } + h.call("ui.view", json!({"view":"top"})); + h.call("ui.camera", json!({"target":[25,0,0],"distance":180})); + h.frames(3); + h +} + +/// The active sketch's point at `at`, and the points level (`Horizontal`) or plumb (`Vertical`) +/// constraints tie it to. +fn point_and_alignments(h: &Harness, at: [f64; 2]) -> Option<(String, Vec<(&'static str, String)>)> { + use solidcraft_engine::sketch::ConstraintKind::{HorizontalPoints, VerticalPoints}; + let st = h.app.session.world_state(); + let sk = &st.sketch(h.app.session.active_sketch?)?.sketch; + let at = solidcraft_engine::geom::Vec2::new(at[0], at[1]); + let i = sk.points.iter().position(|p| p.pos.dist(at) < 1e-9)?; + let id = |k: usize| sk.points.get(k).map(|p| p.id.clone()).unwrap_or_default(); + let tied = sk + .constraints + .iter() + .filter_map(|c| match c.kind { + HorizontalPoints { p, q } if p == i || q == i => Some(("Horizontal", id(if p == i { q } else { p }))), + VerticalPoints { p, q } if p == i || q == i => Some(("Vertical", id(if p == i { q } else { p }))), + _ => None, + }) + .collect(); + Some((id(i), tied)) +} + +#[test] +fn line_up_takes_the_nearest_point_on_each_axis_on_its_own() { + use crate::sketch_tools::{Lined, line_up}; + use solidcraft_engine::geom::Vec2; + let points = [(Some("a".to_string()), Vec2::new(0.0, 10.4)), (Some("b".to_string()), Vec2::new(50.3, -30.0)), (None, Vec2::new(5.0, 10.2))]; + let (level, plumb) = line_up(&points, Vec2::new(50.0, 10.0), 0.5); + assert_eq!(level, Some(Lined { id: None, at: Vec2::new(5.0, 10.2), horizontal: true }), "the nearer of the two level points"); + assert_eq!(plumb, Some(Lined { id: Some("b".into()), at: Vec2::new(50.3, -30.0), horizontal: false })); + // Right on a point is a point snap's business, not lining up; far from all, nothing. + assert_eq!(line_up(&points, Vec2::new(50.3, -30.1), 0.5), (None, None)); + assert_eq!(line_up(&points, Vec2::new(25.0, -10.0), 0.5), (None, None)); +} + +/// #8089, a duplicate of #7828: a rectangle drawn beside another takes its height from one +/// rectangle and its width from a point below, both at once, and keeps both alignments, in the +/// rectangle's one undo step. With the preference off, only one axis lines up, as before. +#[test] +fn a_rectangle_corner_lines_up_with_two_points_at_once_and_keeps_both() { + for aligning in [true, false] { + let mut h = lining_up_fixture(&[ + ("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[20.37,10.43]})), + ("sketch.point", json!({"point":[50.37,-30.21]})), + ]); + h.app.preferences.sketch_align_points = aligning; + let undo = h.app.session.undo.len(); + let below = point_and_alignments(&h, [50.37, -30.21]).unwrap().0; + step(&mut h, json!({"start":"sketch.rectangle.two_point"})); + step(&mut h, json!({"click":{"sketch":[30,0.3]}})); + step(&mut h, json!({"move":{"sketch":[50.2,10.6]}})); + if aligning { + step(&mut h, json!({"expect":{"count":{"name":"sketch_align_guides","value":2}}})); + } + step(&mut h, json!({"click":{"sketch":[50.2,10.6]}})); + let corner = point_and_alignments(&h, [50.37, 10.43]); + if !aligning { + assert!(corner.is_none(), "off: the corner follows the grid, not the other points"); + continue; + } + let (_, tied) = corner.expect("the corner lands level with the rectangle's top and plumb with the point"); + assert!(tied.iter().any(|(kind, to)| *kind == "Vertical" && *to == below), "{tied:?}"); + assert!(tied.iter().any(|(kind, _)| *kind == "Horizontal"), "{tied:?}"); + let (_, start) = point_and_alignments(&h, [30.0, 0.0]).expect("the first corner lines up with the bottom"); + assert!(start.iter().any(|(kind, _)| *kind == "Horizontal"), "{start:?}"); + assert_eq!(h.app.session.undo.len(), undo + 1, "the alignments are in the rectangle's undo step"); + } +} + +/// #7828: a line kept horizontal from its start also lines up under a point above, and the +/// click keeps both: the line's Horizontal and the end's alignment with that point. +#[test] +fn a_horizontal_line_ends_plumb_with_a_point_above_and_keeps_both() { + let mut h = lining_up_fixture(&[("sketch.point", json!({"point":[20.37,30.13]}))]); + let above = point_and_alignments(&h, [20.37, 30.13]).unwrap().0; + step(&mut h, json!({"start":"sketch.line"})); + step(&mut h, json!({"click":{"sketch":[0,0]}})); + step(&mut h, json!({"move":{"sketch":[20.2,0.15]}})); + step(&mut h, json!({"expect":{"count":{"name":"sketch_align_guides","value":1}}})); + step(&mut h, json!({"click":{"sketch":[20.2,0.15]}})); + step(&mut h, json!({"key":"Escape"})); + let (_, tied) = point_and_alignments(&h, [20.37, 0.0]).expect("the end is level with the start and plumb with the point"); + assert_eq!(tied, [("Vertical", above)]); + let st = h.app.session.world_state(); + let sk = &st.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; + assert!( + sk.constraints.iter().any(|c| matches!(c.kind, solidcraft_engine::sketch::ConstraintKind::Horizontal { .. })), + "the line stays horizontal" + ); +} diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index 0a8fa3a9f..d64c84aaf 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -85,7 +85,11 @@ thread_local! { static PICKED: RefCell> = const { RefCell::new(None) }; /// The inference the cursor snapped to last (label, sketch point), for the hint. static SNAP: RefCell> = const { RefCell::new(None) }; - static PREV: Cell> = const { Cell::new(None) }; + /// The points that snap lined the cursor up with, and where it went (#7828). + static LINED: RefCell)>> = const { RefCell::new(None) }; + /// The drawing tool's points so far and whether it is the Line tool, from the last hover: a + /// click takes the tool out of the app while it runs, and must place what the hover showed. + static TOOL: RefCell<(Vec, bool)> = const { RefCell::new((Vec::new(), true)) }; /// Curvature comb teeth (foot, tip) shown while the comb tool is active. static COMBS: RefCell>> = const { RefCell::new(Vec::new()) }; /// The image file a Canvas or Decal tool places. @@ -381,6 +385,82 @@ fn combs(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { }); } +/// A point the cursor lined up with while drawing (#7828): its sketch point id (none for a point +/// of the shape being drawn, not in the sketch yet), where it is, and the axis the cursor +/// shares with it: level (`horizontal`, the same y) or plumb (the same x). +#[derive(Clone, Debug, PartialEq)] +pub struct Lined { + pub id: Option, + pub at: Vec2, + pub horizontal: bool, +} + +/// The points the cursor can line up with: the sketch's visible points on screen (line ends, +/// centres, standalone points, the origin) and the shape's own points so far. +fn align_targets( + proj: &Proj, + sk: &solidcraft_engine::sketch::Sketch, + plane: &solidcraft_engine::geom::Plane, + own: &[Vec2], +) -> Vec<(Option, Vec2)> { + let visible = solidcraft_engine::view::SketchPointVisibility::new(sk); + let on_screen = |p: Vec2| proj.to_screen(plane.to_world(p)).is_some_and(|q| proj.rect.contains(q)); + let mut out: Vec<(Option, Vec2)> = + sk.points.iter().filter(|p| visible.takes(p) && on_screen(p.pos)).map(|p| (Some(p.id.clone()), p.pos)).collect(); + out.extend(own.iter().map(|p| (None, *p))); + out +} + +/// The nearest point level with `lp` (within `tol` across, more than `tol` along) and the +/// nearest plumb with it, each on its own axis, as a dragged point lines up (`drag_snap::find`). +pub(crate) fn line_up(points: &[(Option, Vec2)], lp: Vec2, tol: f64) -> (Option, Option) { + let (mut level, mut plumb): (Option<(f64, Lined)>, Option<(f64, Lined)>) = (None, None); + for (id, p) in points { + let (dx, dy) = ((lp.x - p.x).abs(), (lp.y - p.y).abs()); + if dy < tol && dx > tol && level.as_ref().is_none_or(|l| dy < l.0) { + level = Some((dy, Lined { id: id.clone(), at: *p, horizontal: true })); + } + if dx < tol && dy > tol && plumb.as_ref().is_none_or(|l| dx < l.0) { + plumb = Some((dx, Lined { id: id.clone(), at: *p, horizontal: false })); + } + } + (level.map(|l| l.1), plumb.map(|l| l.1)) +} + +/// What the last snap lined a point placed at `at` up with (#7828). +pub(crate) fn lined_at(at: Vec2) -> Vec { + LINED.with(|l| l.borrow().as_ref().filter(|(p, _)| p.dist(at) < 1e-9).map(|(_, lined)| lined.clone()).unwrap_or_default()) +} + +/// The active sketch's point ids, to tell the points a command makes from those it had. +pub(crate) fn point_ids(app: &SolveApp) -> Vec { + let st = app.session.world_state(); + app.session.active_sketch.and_then(|id| st.sketch(id)).map(|ss| ss.sketch.points.iter().map(|p| p.id.clone()).collect()).unwrap_or_default() +} + +/// Once a shape is made (#7828): each new point that was placed lined up with a sketch point +/// (`placed`, the shape's points) stays level or plumb with it. Only what the sketch doesn't +/// already have is added, in the shape's undo step. +pub(crate) fn constrain_lined(app: &mut SolveApp, tool: &mut Tool, placed: &[Vec2], before: &[String]) { + let lined = std::mem::take(&mut tool.lined); + let new: Vec<(String, Vec2)> = { + let st = app.session.world_state(); + let Some(ss) = app.session.active_sketch.and_then(|id| st.sketch(id)) else { return }; + ss.sketch.points.iter().filter(|p| !before.contains(&p.id)).map(|p| (p.id.clone(), p.pos)).collect() + }; + let history = std::mem::take(&mut app.session.undo); + for (at, targets) in lined.iter().filter(|(at, _)| placed.iter().any(|p| p.dist(*at) < 1e-9)) { + let Some((point, _)) = new.iter().find(|(_, p)| p.dist(*at) < 1e-6) else { continue }; + for target in targets { + let Some(id) = &target.id else { continue }; + let mode = if target.horizontal { "horizontal" } else { "vertical" }; + let params = json!({"points": [point, id], "mode": mode, "if_redundant": "refuse"}); + let _ = app.session.execute("sketch.constraint.horizontal_vertical", ¶ms); + } + } + app.session.undo = history; +} + /// Snap a cursor point on the sketch plane to what is inferred while drawing: a crossing of /// two curves, a line's midpoint, or alignment (horizontal/vertical) with the previous point /// of the tool. None: nothing near, use the grid. @@ -392,6 +472,7 @@ pub fn refine_snap( lp: Vec2, ) -> Option<(Vec2, Option)> { crate::inference::clear(); + LINED.with(|l| *l.borrow_mut() = None); // Millimetres per pixel here. let (a, b) = (proj.to_screen(plane.to_world(lp))?, proj.to_screen(plane.to_world(lp + Vec2::X))?); let px = 1.0 / (a.distance(b) as f64).max(1e-9); @@ -430,19 +511,21 @@ pub fn refine_snap( } } } - // The tool's previous point (a click takes the tool out of the app while it runs, so the - // last hover's is kept). - let prev = match app.tool.as_ref() { + // The tool's points and kind (a click takes the tool out of the app while it runs, so the + // last hover's are kept: a rectangle's click takes no Line tool inference its hover didn't). + let (own, line_tool) = match app.tool.as_ref() { Some(t) => { - let p = t.pts.last().map(|p| p.0); - PREV.with(|c| c.set(p)); - p + let own: (Vec, bool) = (t.pts.iter().map(|p| p.0).collect(), t.cmd == "sketch.line"); + TOOL.with(|c| *c.borrow_mut() = own.clone()); + own } - None => PREV.with(Cell::get), + None => TOOL.with(|c| c.borrow().clone()), }; + // With `sketch_align_points` off, a click takes the Line tool's inferences, as before. + let line_tool = if app.preferences.sketch_align_points { line_tool } else { app.tool.as_ref().is_none_or(|t| t.cmd == "sketch.line") }; + let prev = own.last().copied(); // Line tool: the tangent point of a circle or arc, then a line through its centre // (before plain "on the curve", which would leave a chord free to miss the centre). - let line_tool = app.tool.as_ref().is_none_or(|t| t.cmd == "sketch.line"); if !mid_only && best.is_none() && line_tool @@ -472,18 +555,26 @@ pub fn refine_snap( } } } + // The free coordinate still follows the grid. + let step = solidcraft_engine::view::grid_step(app.cam.half_height()).0 / 10.0; + let g = |v: f64| (v / step).round() * step; + // Points to line up with as well (#7828): with `sketch_align_points` off, none, so only the + // previous point, one axis at a time, as before. + let targets = if app.preferences.sketch_align_points { align_targets(proj, sk, plane, &own) } else { Vec::new() }; + let mut lined = Vec::new(); if !mid_only && best.is_none() && let Some(prev) = prev { let (dx, dy) = ((lp.x - prev.x).abs(), (lp.y - prev.y).abs()); - // The free coordinate still follows the grid. - let step = solidcraft_engine::view::grid_step(app.cam.half_height()).0 / 10.0; - let g = |v: f64| (v / step).round() * step; + // Level with (or plumb with) the previous point, and lined up across with another. + let (level, plumb) = line_up(&targets, lp, tol); if dy < tol && dx > tol { - best = Some((dy, "H", Vec2::new(g(lp.x), prev.y))); + best = Some((dy, if plumb.is_some() { "H+V" } else { "H" }, Vec2::new(plumb.as_ref().map_or(g(lp.x), |p| p.at.x), prev.y))); + lined.extend(plumb); } else if dx < tol && dy > tol { - best = Some((dx, "V", Vec2::new(prev.x, g(lp.y)))); + best = Some((dx, if level.is_some() { "H+V" } else { "V" }, Vec2::new(prev.x, level.as_ref().map_or(g(lp.y), |l| l.at.y)))); + lined.extend(level); } } // Line tool: parallel or perpendicular to a line, or on a line's extension. @@ -495,7 +586,25 @@ pub fn refine_snap( { best = Some((i.dist, i.label(), i.at)); } + // Lined up with other points, on one axis or on both at once (#7828). + if !mid_only && best.is_none() { + let (level, plumb) = line_up(&targets, lp, tol); + let at = Vec2::new(plumb.as_ref().map_or(g(lp.x), |p| p.at.x), level.as_ref().map_or(g(lp.y), |l| l.at.y)); + let off = |l: &Lined| if l.horizontal { (lp.y - l.at.y).abs() } else { (lp.x - l.at.x).abs() }; + let label = match (&level, &plumb) { + (Some(_), Some(_)) => Some("H+V"), + (Some(_), None) => Some("H"), + (None, Some(_)) => Some("V"), + (None, None) => None, + }; + if let Some(label) = label { + best = Some((level.iter().chain(&plumb).map(off).fold(f64::INFINITY, f64::min), label, at)); + lined.extend(level); + lined.extend(plumb); + } + } SNAP.with(|s| *s.borrow_mut() = best.map(|(_, l, p)| (l, p))); + LINED.with(|l| *l.borrow_mut() = best.filter(|_| !lined.is_empty()).map(|(_, _, at)| (at, lined))); // A midpoint snap is a point argument the commands understand ("mid:"). // "x:a+b:x,y" is a crossing of two curves; "on::x,y" is a point on one curve. best.map(|(_, l, p)| { @@ -643,6 +752,7 @@ pub fn tool_for(id: &str) -> Option { dims_stage: usize::MAX, dims_focus: false, arc_turn: 0.0, + lined: Vec::new(), }) } @@ -1584,6 +1694,12 @@ fn snap_hint(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { let Some(ss) = active_sketch(app).and_then(|s| st.sketch(s)) else { return }; let Some(sp) = proj.to_screen(ss.plane.to_world(p)) else { return }; let tk = crate::theme::Tokens::get(); + // A dotted guide from each point the snap lined the cursor up with (#7828). + let guides = LINED.with(|l| l.borrow().as_ref().filter(|(at, _)| at.dist(p) < 1e-9).map(|(_, lined)| lined.clone()).unwrap_or_default()); + for from in guides.iter().filter_map(|l| proj.to_screen(ss.plane.to_world(l.at))) { + painter.add(egui::Shape::dashed_line(&[from, sp], Stroke::new(1.0, tk.rubber_band), 5.0, 4.0)); + } + crate::scenario::publish_count("sketch_align_guides", guides.len() as f64); let r = egui::Rect::from_min_size(sp + egui::vec2(12.0, -24.0), egui::vec2(24.0, 14.0)); painter.rect_filled(r, tk.radius_sm.saturating_sub(1), tk.accent_soft); painter.text(r.center(), egui::Align2::CENTER_CENTER, label, egui::FontId::proportional(crate::theme::Tokens::get().font_micro), tk.text); diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 2780e35a8..4eca51a7b 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -94,6 +94,9 @@ pub struct Tool { /// How far (radians, signed) the cursor has gone round a centre-point arc's centre since its /// start was placed: its sign is the way the arc runs (#6645). pub arc_turn: f64, + /// Where each point was placed and the sketch points the snap lined it up with (#7828): + /// constrained to them once the shape is made. + pub lined: Vec<(Vec2, Vec)>, } impl Tool { @@ -145,6 +148,7 @@ impl Tool { dims_stage: usize::MAX, dims_focus: false, arc_turn: 0.0, + lined: Vec::new(), }) } } @@ -496,7 +500,9 @@ pub fn place(app: &mut SolveApp, p: (Vec2, Option)) { app.tool = Some(tool); return; } + tool.lined.push((p.0, crate::sketch_tools::lined_at(p.0))); tool.pts.push(p); + let before = crate::sketch_tools::point_ids(app); if tool.cmd == "sketch.line" { if tool.pts.len() >= 2 { let (a, b) = (tool.pts[tool.pts.len() - 2].clone(), tool.pts[tool.pts.len() - 1].clone()); @@ -508,11 +514,13 @@ pub fn place(app: &mut SolveApp, p: (Vec2, Option)) { if let Some(id) = curves.first() { if angled { crate::inference::clear(); + tool.lined.clear(); } else { // Endpoint inference is part of this drawing. Preserve its original // undo history even when the history is already at the engine's cap. let history = dimensioned.then(|| std::mem::take(&mut app.session.undo)); crate::inference::commit(app, id, b.0); + crate::sketch_tools::constrain_lined(app, &mut tool, &[a.0, b.0], &before); if let Some(history) = history { app.session.undo = history; } @@ -525,17 +533,21 @@ pub fn place(app: &mut SolveApp, p: (Vec2, Option)) { crate::sketch_dims::reset(&mut tool); } else { tool.pts.pop(); + tool.lined.pop(); } } } else if n > 0 && tool.pts.len() >= n { match run_shape(app, &tool) { Ok(_) => { + let placed: Vec = tool.pts.iter().map(|p| p.0).collect(); + crate::sketch_tools::constrain_lined(app, &mut tool, &placed, &before); tool.pts.clear(); crate::sketch_dims::reset(&mut tool); } Err(error) => { app.set_status(error, true); tool.pts.pop(); + tool.lined.pop(); } } } diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md index a0d0474b9..9501d5616 100644 --- a/docs/book/src/guide/sketching.md +++ b/docs/book/src/guide/sketching.md @@ -199,6 +199,17 @@ to prefer a line midpoint instead; hold Ctrl/Cmd or Alt/Option (the default supp to stop snapping for that gesture. Scripts pass `"x:+:x,y"` as a point argument, the same way `"mid:"` and `"on::x,y"` work. +With Preferences › Sketch › **Line up with other sketch points while drawing** turned on (it's +off by default), the pointer also **lines up** while drawing with the sketch's points on screen: +line ends, centres, standalone points and the origin, and the shape's own earlier points. It +lines up on both axes at once, level with one point and plumb with another, so a rectangle drawn +beside another can take its height from one and its width from a point below. A line kept +horizontal or vertical from its start can still end under or beside another point. A dotted guide +runs from each point it lines up with, and the snap hint shows **H**, **V** or **H+V**. The click +keeps the alignment: the new point gets a Horizontal or Vertical constraint with each sketch +point it lined up with, in the shape's undo step, unless the sketch already sets it. With the +preference off, drawing lines up only with the previous point, one axis at a time. + Enable **3D Sketch** in the Sketch Palette to draw lines, fit splines and points off the plane. While placing these points, you can snap to points on other visible sketches. For a bridge line, start Line and click an endpoint on each source sketch; each endpoint uses its source