Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Sketch: show temporary centre and midpoint alignment guides (#7903)

cronosb72165fd3061
diff --git a/assets/locales/pending/sketch-tracking-guides.json b/assets/locales/pending/sketch-tracking-guides.json
new file mode 100644
index 0000000000..d8bc19ddc5
--- /dev/null
+++ b/assets/locales/pending/sketch-tracking-guides.json
@@ -0,0 +1,38 @@
+{
+ "en": {
+ "prefs.sketch_tracking_guides": "Center and midpoint alignment guides",
+ "prefs.sketch_tracking_guides_note": "Hover over a circle center or straight-edge midpoint, then move horizontally or vertically to show a temporary dotted guide."
+ },
+ "ja": {
+ "prefs.sketch_tracking_guides": "中心・中点の整列ガイド",
+ "prefs.sketch_tracking_guides_note": "円の中心や直線辺の中点にカーソルを合わせ、水平・垂直に移動すると一時的な点線ガイドを表示します。"
+ },
+ "zh": {
+ "prefs.sketch_tracking_guides": "圆心和中点对齐辅助线",
+ "prefs.sketch_tracking_guides_note": "将光标悬停在圆心或直线边的中点,然后水平或垂直移动以显示临时虚线辅助线。"
+ },
+ "de": {
+ "prefs.sketch_tracking_guides": "Ausrichtungshilfen für Mittelpunkte",
+ "prefs.sketch_tracking_guides_note": "Den Mauszeiger über einen Kreismittelpunkt oder eine Kantenmitte bewegen und dann waagerecht oder senkrecht bewegen, um eine temporäre gepunktete Hilfslinie anzuzeigen."
+ },
+ "ko": {
+ "prefs.sketch_tracking_guides": "중심 및 중점 정렬 안내선",
+ "prefs.sketch_tracking_guides_note": "원 중심이나 직선 모서리의 중점에 마우스를 올린 다음 수평 또는 수직으로 이동하면 임시 점선 안내선이 표시됩니다."
+ },
+ "en-GB": {
+ "prefs.sketch_tracking_guides": "Centre and midpoint alignment guides",
+ "prefs.sketch_tracking_guides_note": "Hover over a circle centre or straight-edge midpoint, then move horizontally or vertically to show a temporary dotted guide."
+ },
+ "ar": {
+ "prefs.sketch_tracking_guides": "أدلة محاذاة المراكز ونقاط المنتصف",
+ "prefs.sketch_tracking_guides_note": "مرّر المؤشر فوق مركز دائرة أو نقطة منتصف حافة مستقيمة، ثم حرّكه أفقيًا أو عموديًا لإظهار دليل منقّط مؤقت."
+ },
+ "he": {
+ "prefs.sketch_tracking_guides": "קווי עזר ליישור מרכזים ונקודות אמצע",
+ "prefs.sketch_tracking_guides_note": "יש לרחף עם הסמן מעל מרכז מעגל או נקודת אמצע של צלע ישרה, ואז להזיז אותו אופקית או אנכית כדי להציג קו עזר מקווקו זמני."
+ },
+ "vi": {
+ "prefs.sketch_tracking_guides": "Đường căn chỉnh tâm và trung điểm",
+ "prefs.sketch_tracking_guides_note": "Di con trỏ lên tâm đường tròn hoặc trung điểm của cạnh thẳng, rồi di chuyển theo phương ngang hoặc dọc để hiển thị đường căn chỉnh nét đứt tạm thời."
+ }
+}
diff --git a/attribution/pending/sketch-tracking-guides.md b/attribution/pending/sketch-tracking-guides.md
new file mode 100644
index 0000000000..8b15634f2a
--- /dev/null
+++ b/attribution/pending/sketch-tracking-guides.md
@@ -0,0 +1 @@
+| `assets/locales/pending/sketch-tracking-guides.json` | SolidCraft contributors | Original alignment-guide preference labels and help text | MIT OR Apache-2.0 |
diff --git a/crates/ui-egui/src/inference.rs b/crates/ui-egui/src/inference.rs
index 6dc2d299f5..0dfc9b3380 100644
--- a/crates/ui-egui/src/inference.rs
+++ b/crates/ui-egui/src/inference.rs
@@ -250,6 +250,100 @@ pub fn show(app: &SolveApp, painter: &egui::Painter, proj: &Proj) {
}
}
+/// A hovered centre or straight-edge midpoint. Transient, per viewport, never a constraint.
+#[derive(Default)]
+pub(crate) struct Tracking {
+ sketch: Option<u64>,
+ document: std::sync::Weak<solidcraft_engine::doc::Document>,
+ anchor: Option<String>,
+ pub(crate) guide: Option<(Vec2, Vec2)>,
+}
+
+impl Tracking {
+ fn reference(sk: &Sketch, index: usize) -> Option<Vec2> {
+ if !solidcraft_engine::view::sketch_curve_visible(sk, index) {
+ return None;
+ }
+ match sk.curves.get(index)?.kind {
+ CurveKind::Line { a, b } => Some((sk.point(a)? + sk.point(b)?) * 0.5),
+ CurveKind::Circle { .. } | CurveKind::Arc { .. } => sk.center(index),
+ _ => None,
+ }
+ }
+
+ fn update(&mut self, sk: &Sketch, plane: &solidcraft_engine::geom::Plane, proj: &Proj, cursor: egui::Pos2) {
+ self.guide = None;
+ let to = |p: Vec2| proj.to_screen(plane.to_world(p));
+ // Screen-space tolerances stay the same at any zoom; only visible references wake.
+ let mut nearest = 8.0;
+ for (index, curve) in sk.curves.iter().enumerate() {
+ let Some(p) = Self::reference(sk, index).and_then(to).filter(|p| proj.rect.contains(*p)) else { continue };
+ let distance = cursor.distance(p);
+ if distance < nearest {
+ nearest = distance;
+ self.anchor = Some(curve.id.clone());
+ }
+ }
+ let Some((anchor, origin)) = self.anchor.as_deref().and_then(|id| {
+ let anchor = Self::reference(sk, sk.curve_index(id)?)?;
+ Some((anchor, to(anchor)?))
+ }) else {
+ self.anchor = None;
+ return;
+ };
+ if !proj.rect.contains(origin) {
+ return;
+ }
+ let (ray, direction) = proj.ray(cursor);
+ let Some(world) = plane.intersect_ray(ray, direction) else { return };
+ let at = plane.to_local(world);
+ if !at.x.is_finite() || !at.y.is_finite() {
+ return;
+ }
+ // Finite guides connect the reference to the cursor's projection onto its axis.
+ // No model-space length cap: the viewport clips them, as it does other sketch guides.
+ let mut distance = 6.0;
+ for end in [Vec2::new(at.x, anchor.y), Vec2::new(anchor.x, at.y)] {
+ let Some(screen) = to(end) else { continue };
+ let off_axis = cursor.distance(screen);
+ if origin.distance(screen) > 8.0 && off_axis < distance {
+ distance = off_axis;
+ self.guide = Some((anchor, end));
+ }
+ }
+ }
+}
+
+/// Visual H/V tracking works before a tool's first click and while simply editing a sketch.
+/// Existing snaps, picks and constraints retain their behaviour.
+pub(crate) fn track_and_show(app: &mut SolveApp, painter: &egui::Painter, proj: &Proj, cursor: Option<egui::Pos2>) {
+ crate::scenario::publish_count("sketch_tracking_guides", 0.0);
+ let document = std::sync::Arc::downgrade(&app.session.doc);
+ let active = app.session.active_sketch;
+ let tracking = &mut app.viewport.tracking;
+ if tracking.sketch != active || !tracking.document.ptr_eq(&document) {
+ *tracking = Tracking { sketch: active, document, ..Default::default() };
+ }
+ let state = app.session.world_state();
+ let Some((ss, cursor)) = active
+ .and_then(|id| state.sketch(id))
+ .zip(cursor)
+ .filter(|_| app.preferences.sketch_tracking_guides && !crate::drag_snap::suppressed() && app.viewport.point_drag.is_none())
+ else {
+ *tracking = Tracking::default();
+ return;
+ };
+ tracking.update(&ss.sketch, &ss.plane, proj, cursor);
+ crate::scenario::publish_count("sketch_tracking_guides", usize::from(tracking.guide.is_some()) as f64);
+ if let Some((a, b)) = tracking.guide
+ && let (Some(a), Some(b)) = (proj.to_screen(ss.plane.to_world(a)), proj.to_screen(ss.plane.to_world(b)))
+ {
+ let tk = Tokens::get();
+ painter.add(Shape::dashed_line(&[a, b], Stroke::new(1.0, tk.rubber_band), 5.0, 4.0));
+ painter.circle_stroke(a, 4.0, Stroke::new(1.0, tk.rubber_band));
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -261,6 +355,44 @@ mod tests {
s
}
+ #[test]
+ fn tracking_has_pixel_tolerance_and_only_spans_reference_to_cursor() {
+ use solidcraft_engine::geom::Plane;
+ let mut app = SolveApp::new(Default::default(), Default::default());
+ app.cam.yaw = 0.0;
+ app.cam.pitch = std::f64::consts::FRAC_PI_2;
+ let mut sk = Sketch::new();
+ sk.add_circle(Vec2::new(-10.0, 3.0), 5.0, None, Some("c")).unwrap();
+ sk.add_line(Vec2::new(10.0, -20.0), Vec2::new(30.0, -20.0), None, None, Some("l")).unwrap();
+ for zoom in [60.0, 180.0] {
+ app.cam.distance = zoom;
+ let proj = crate::viewport::projection(&app, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)));
+ let to = |p: Vec2| proj.to_screen(Plane::XY.to_world(p)).unwrap();
+ let mut tracking = Tracking::default();
+ let centre = Vec2::new(-10.0, 3.0);
+ tracking.update(&sk, &Plane::XY, &proj, to(centre));
+ assert!(tracking.guide.is_none(), "no zero-length guide at the centre");
+ for end in [Vec2::new(35.0, 3.0), Vec2::new(-35.0, 3.0), Vec2::new(-10.0, 38.0), Vec2::new(-10.0, -38.0)] {
+ tracking.update(&sk, &Plane::XY, &proj, to(end));
+ let (a, b) = tracking.guide.expect("all four directions");
+ assert!(a.dist(centre) < 1e-4 && b.dist(end) < 1e-4);
+ }
+ let end = Vec2::new(35.0, 3.0);
+ tracking.update(&sk, &Plane::XY, &proj, to(end) + egui::vec2(0.0, 5.0));
+ assert!(tracking.guide.is_some(), "5 screen points from the axis");
+ tracking.update(&sk, &Plane::XY, &proj, to(end) + egui::vec2(0.0, 7.0));
+ assert!(tracking.guide.is_none(), "7 screen points from the axis");
+ let mid = Vec2::new(20.0, -20.0);
+ tracking.update(&sk, &Plane::XY, &proj, to(mid));
+ tracking.update(&sk, &Plane::XY, &proj, to(Vec2::new(20.0, 20.0)));
+ assert!(tracking.guide.unwrap().0.dist(mid) < 1e-8, "new MID replaces centre");
+ sk.curves.iter_mut().find(|c| c.id == "l").unwrap().id = "renamed".into();
+ tracking.update(&sk, &Plane::XY, &proj, to(Vec2::new(20.0, 20.0)));
+ assert!(tracking.guide.is_none(), "removed references cannot leave a stale guide");
+ sk.curves.iter_mut().find(|c| c.id == "renamed").unwrap().id = "l".into();
+ }
+ }
+
#[test]
fn parallel_and_perpendicular_from_the_previous_point() {
let s = sk();
diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs
index 156ac82811..fe79ce6f58 100644
--- a/crates/ui-egui/src/prefs.rs
+++ b/crates/ui-egui/src/prefs.rs
@@ -1033,6 +1033,8 @@ preference_settings! {
/// Modifier that suppresses sketch auto-snap while drawing or dragging a sketch point.
/// Default: Alt/Option. Set to Ctrl/Cmd for the alternate mapping.
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;
/// Whether Alt/Option also frees gizmo / canvas manipulator arrows (Primary always does).
manipulator_free_alt: bool = true, PAGE_SKETCH;
/// A sketch tool's shortcut pressed again before the first point steps to the tool's next
@@ -4374,6 +4376,7 @@ mod tests {
("look_at_anim", json!(false), PAGE_NAVIGATION),
("selection_shift_add_only", json!(true), PAGE_SKETCH),
("suppress_sketch_snap", json!(ModifierCombo::NONE), PAGE_SKETCH),
+ ("sketch_tracking_guides", json!(false), PAGE_SKETCH),
("msaa", json!(8), PAGE_GRAPHICS),
];
let defaults = serde_json::to_value(Prefs::default()).unwrap();
diff --git a/crates/ui-egui/src/prefs/sketch.rs b/crates/ui-egui/src/prefs/sketch.rs
index f7a676c9ce..d839755b31 100644
--- a/crates/ui-egui/src/prefs/sketch.rs
+++ b/crates/ui-egui/src/prefs/sketch.rs
@@ -5,6 +5,8 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
let t = Tokens::get();
ui_kit::settings_heading(ui, app.tr("prefs.sketch_selection_heading"), app.tr("prefs.sketch_selection_note"));
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"));
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 1dd92524c0..8f9426f151 100644
--- a/crates/ui-egui/src/sketch_guidance_ui_tests.rs
+++ b/crates/ui-egui/src/sketch_guidance_ui_tests.rs
@@ -263,3 +263,94 @@ fn sketch_modify_keeps_custom_point_ids_that_contain_colons() {
}
assert_eq!(h.app.session.world_state().sketch(1).unwrap().sketch.curves.len(), 8);
}
+
+fn tracking_fixture() -> Harness {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.preferences.look_at_anim = false;
+ for (command, params) in [
+ ("sketch.create", json!({"plane":"XY"})),
+ ("sketch.rectangle.two_point", json!({"p0":[-30,-20],"p1":[30,20]})),
+ ("sketch.circle.center", json!({"center":[-10,3],"radius":7})),
+ ] {
+ h.app.run(command, params).unwrap();
+ }
+ h.call("ui.view", json!({"view":"top"}));
+ h.call("ui.camera", json!({"target":[-30,0,0],"distance":180}));
+ h.frames(3);
+ h
+}
+
+#[test]
+fn centre_and_midpoint_tracking_is_visual_in_idle_and_drawing_modes() {
+ use solidcraft_engine::geom::Vec2;
+ let mut h = tracking_fixture();
+ let before = h.app.session.doc.to_json();
+ let undo = h.app.session.undo.len();
+ for tool in [None, Some("sketch.line"), Some("sketch.circle.center")] {
+ if let Some(tool) = tool {
+ h.app.start(tool);
+ }
+ for (anchor, end) in [([-10.0, 3.0], [20.0, 3.0]), ([0.0, 20.0], [0.0, -10.0]), ([30.0, 0.0], [-10.0, 0.0])] {
+ step(&mut h, json!({"move":{"sketch":anchor}}));
+ step(&mut h, json!({"move":{"sketch":end}}));
+ let (a, b) = h.app.viewport.tracking.guide.expect("centre/MID guide");
+ assert!(a.dist(Vec2::new(anchor[0], anchor[1])) < 1e-4);
+ assert!(b.dist(Vec2::new(end[0], end[1])) < 1e-4);
+ step(&mut h, json!({"move":{"sketch":[15,12]}}));
+ assert!(h.app.viewport.tracking.guide.is_none(), "off-axis hides the guide");
+ }
+ step(&mut h, json!({"key":"Escape"}));
+ }
+ assert_eq!(h.app.session.doc.to_json(), before, "guides add no geometry or constraints");
+ assert_eq!(h.app.session.undo.len(), undo);
+}
+
+#[test]
+fn tracking_clears_on_escape_sketch_exit_and_preference_and_respects_suppression() {
+ let mut h = tracking_fixture();
+ for action in ["suppression", "preference", "escape", "exit"] {
+ step(&mut h, json!({"move":{"sketch":[-10,3]}}));
+ step(&mut h, json!({"move":{"sketch":[20,3]}}));
+ assert!(h.app.viewport.tracking.guide.is_some());
+ match action {
+ "suppression" => step(&mut h, json!({"move":{"sketch":[20,3]},"alt":true})),
+ "preference" => {
+ h.call("ui.prefs", json!({"sketch_tracking_guides":false}));
+ h.frames(2);
+ }
+ "escape" => step(&mut h, json!({"key":"Escape"})),
+ _ => {
+ h.app.run("sketch.finish", json!({})).unwrap();
+ h.frames(2);
+ }
+ }
+ assert!(h.app.viewport.tracking.guide.is_none(), "{action}");
+ if action == "exit" {
+ break;
+ }
+ if action == "preference" {
+ h.call("ui.prefs", json!({"sketch_tracking_guides":true}));
+ }
+ step(&mut h, json!({"move":{"sketch":[15,12]}}));
+ }
+}
+
+#[test]
+fn tracking_does_not_leak_outside_the_viewport_or_into_another_sketch() {
+ let mut h = tracking_fixture();
+ step(&mut h, json!({"move":{"sketch":[-10,3]}}));
+ step(&mut h, json!({"move":{"sketch":[20,3]}}));
+ assert!(h.app.viewport.tracking.guide.is_some());
+ h.call("ui.move", json!({"x":0,"y":0}));
+ assert!(h.app.viewport.tracking.guide.is_none());
+ step(&mut h, json!({"move":{"sketch":[20,3]}}));
+ assert!(h.app.viewport.tracking.guide.is_none(), "leaving requires acquiring a reference again");
+ step(&mut h, json!({"move":{"sketch":[-10,3]}}));
+ step(&mut h, json!({"move":{"sketch":[20,3]}}));
+ assert!(h.app.viewport.tracking.guide.is_some());
+ h.app.run("sketch.finish", json!({})).unwrap();
+ h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();
+ h.frames(3);
+ assert!(h.app.viewport.tracking.guide.is_none());
+}
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 4db5c308af..527801e4cc 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -155,6 +155,8 @@ pub struct ViewportState {
/// (sketch, point id): it is drawn, and it takes the pointer from further away
/// ([`WOKEN_CENTRE_PX`]), until another curve or point is hovered.
pub woken_centre: Option<(u64, String)>,
+ /// The centre or midpoint most recently hovered for visual H/V tracking.
+ pub(crate) tracking: crate::inference::Tracking,
pub mouse: Option<Pos2>,
/// Box selection being dragged.
pub boxsel: Option<BoxSel>,
@@ -4525,6 +4527,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
crate::dim_view::show(app, ui, &painter, &proj);
crate::sketch_text_handles::show(app, ui, &painter, &proj, hover);
crate::sketch3d::show(app, &painter, &proj);
+ let tracking_cursor = hover.filter(|_| inside && !navigating && !app.esc_handled && !ui.input(|i| i.key_pressed(egui::Key::Escape)));
+ crate::inference::track_and_show(app, &painter, &proj, tracking_cursor);
crate::inference::show(app, &painter, &proj);
crate::drag_snap::show(app, &painter, &proj);
crate::insert_handles::show(app, ui, &proj);
diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md
index 2d58929bc4..b763b0f70b 100644
--- a/docs/book/src/guide/sketching.md
+++ b/docs/book/src/guide/sketching.md
@@ -29,6 +29,14 @@ without changing sketch geometry, dimensions, or undo history.
On short windows or enlarged displays, the Sketch Palette's options scroll while its
constraint status and **Finish Sketch** button remain visible.
+Hover over a circle or arc centre, or the midpoint of a straight sketch edge, then move
+horizontally or vertically to see a dotted alignment guide. The guide connects that reference
+to the cursor's projection on the sketch axis, within the viewport; it disappears when you
+move away from the axis. This works while editing and before a drawing tool's first click.
+It adds no geometry or constraints. Esc, leaving the viewport, or ending the sketch clears
+the reference. Preferences › Sketch › **Center and midpoint alignment guides** turns it off;
+the configured snap-suppression modifier also hides it.
+
## Geometry
**Point** is available directly on the default Sketch **CREATE** toolbar. Click it, then
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index ce37b326fe..d68fbdaf4d 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -383,6 +383,14 @@ Other `ui.prefs` parameters:
Entering Render requires finishing the current modelling operation; returning restores
the Design camera. See [the integrated Render workspace](render-workspace.md).
+### Sketch alignment guides
+
+`ui.prefs {sketch_tracking_guides: true}` enables temporary horizontal and vertical dotted
+alignment guides from hovered circle/arc centres and straight-edge midpoints (default true).
+The guide spans the reference and cursor projection, including positions inside a circle.
+It is visual only: coordinates, snapping and constraints are unchanged. Set the preference
+to `false` to hide the guides.
+
### Continuous camera motion
Continuous camera motion is also available through `engine.execute` with command