diff --git a/assets/locales/pending/placement-handles.json b/assets/locales/pending/placement-handles.json new file mode 100644 index 000000000..aa1c57450 --- /dev/null +++ b/assets/locales/pending/placement-handles.json @@ -0,0 +1,42 @@ +{ + "en": { + "Drag to move the boss across the model. It snaps to sketch points on the face.": "Drag to move the boss across the model. It snaps to sketch points on the face.", + "Drag to move the rest across the model. It snaps to sketch points on the face.": "Drag to move the rest across the model. It snaps to sketch points on the face.", + "Drag to move the snap fit across the model. It snaps to sketch points on the face.": "Drag to move the snap fit across the model. It snaps to sketch points on the face.", + "Drag to point the catch in another direction.": "Drag to point the catch in another direction.", + "Drag to turn the rest in 5° steps. Hold Alt or Ctrl to turn it freely.": "Drag to turn the rest in 5° steps. Hold Alt or Ctrl to turn it freely.", + "prefs.placement": "Placement", + "ui.placement_handles": "Placement handles", + "ui.placement_handles_tip": "Handles on the preview of a Rest, Boss or Snap Fit: drag the marker to move it across the model, turn it by its ring" + }, + "ja": { + "Drag to move the boss across the model. It snaps to sketch points on the face.": "ドラッグしてボスをモデル上で移動します。面上のスケッチ点にスナップします。", + "Drag to move the rest across the model. It snaps to sketch points on the face.": "ドラッグしてレストをモデル上で移動します。面上のスケッチ点にスナップします。", + "Drag to move the snap fit across the model. It snaps to sketch points on the face.": "ドラッグしてスナップ フィットをモデル上で移動します。面上のスケッチ点にスナップします。", + "Drag to point the catch in another direction.": "ドラッグしてキャッチの向きを変えます。", + "Drag to turn the rest in 5° steps. Hold Alt or Ctrl to turn it freely.": "ドラッグしてレストを 5° 刻みで回転します。Alt または Ctrl を押したままにすると自由に回転します。", + "prefs.placement": "配置", + "ui.placement_handles": "配置ハンドル", + "ui.placement_handles_tip": "レスト、ボス、スナップ フィットのプレビューに表示されるハンドル: マーカーをドラッグしてモデル上を移動し、リングで回転します" + }, + "pl": { + "Drag to move the boss across the model. It snaps to sketch points on the face.": "Przeciągnij, aby przesunąć występ po modelu. Przyciąga się do punktów szkicu na ścianie.", + "Drag to move the rest across the model. It snaps to sketch points on the face.": "Przeciągnij, aby przesunąć podparcie po modelu. Przyciąga się do punktów szkicu na ścianie.", + "Drag to move the snap fit across the model. It snaps to sketch points on the face.": "Przeciągnij, aby przesunąć zatrzask po modelu. Przyciąga się do punktów szkicu na ścianie.", + "Drag to point the catch in another direction.": "Przeciągnij, aby skierować zaczep w inną stronę.", + "Drag to turn the rest in 5° steps. Hold Alt or Ctrl to turn it freely.": "Przeciągnij, aby obrócić podparcie co 5°. Przytrzymaj Alt lub Ctrl, aby obracać swobodnie.", + "prefs.placement": "Umieszczanie", + "ui.placement_handles": "Uchwyty umieszczania", + "ui.placement_handles_tip": "Uchwyty na podglądzie podparcia, występu lub zatrzasku: przeciągnij znacznik, aby przesunąć element po modelu, obróć go pierścieniem" + }, + "zh": { + "Drag to move the boss across the model. It snaps to sketch points on the face.": "拖动以在模型上移动凸台。它会吸附到面上的草图点。", + "Drag to move the rest across the model. It snaps to sketch points on the face.": "拖动以在模型上移动垫块。它会吸附到面上的草图点。", + "Drag to move the snap fit across the model. It snaps to sketch points on the face.": "拖动以在模型上移动卡扣。它会吸附到面上的草图点。", + "Drag to point the catch in another direction.": "拖动以将卡钩指向另一个方向。", + "Drag to turn the rest in 5° steps. Hold Alt or Ctrl to turn it freely.": "拖动以 5° 为步长旋转垫块。按住 Alt 或 Ctrl 可自由旋转。", + "prefs.placement": "放置", + "ui.placement_handles": "放置手柄", + "ui.placement_handles_tip": "垫块、凸台或卡扣预览上的手柄:拖动标记在模型上移动,用转环旋转" + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ad08c8ed7..007b38216 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -285,6 +285,7 @@ pub(crate) fn owns_pointer(app: &SolveApp, proj: &Proj, p: Pos2) -> bool { || (app.dialog.is_none() && app.tool.is_none() && crate::browser::occurrence_triad_model(app).is_some_and(|t| crate::gizmo::contains_pointer(proj, &t, p))) + || crate::place_gizmo::contains_pointer(app, p) } /// Draw the manipulator and the value box (called by the viewport after the model is drawn). @@ -359,6 +360,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj { draw(app, ui, painter, proj, &mut d, base, bs, dir); } + crate::place_gizmo::show(app, ui, painter, proj, &mut d); app.dialog = Some(d); // A Single hole's handles, over the depth arrow's stem: a press on a hole moves it. crate::hole_place::show(app, ui, painter, proj); @@ -534,14 +536,28 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, if let (Kind::Extrude { direction: crate::dialogs::TWO_SIDES | crate::dialogs::TWO_SIDES_REVERSED, distance2, .. }, Some(n)) = (&mut d.kind, dir) && let Some(l2) = crate::length_input::eval(&app.session.doc, distance2, ValueKind::Length).ok().filter(|v| v.is_finite()) { - drag_arrow(&app.session.doc, ui, painter, proj, base, bs, -(n * sign), l2, true, egui::Id::new("sc_manipulator2"), half_height, distance2); + drag_arrow( + &app.session.doc, + ui, + painter, + proj, + base, + bs, + -(n * sign), + l2, + true, + egui::Id::new("sc_manipulator2"), + half_height, + 0.0, + distance2, + ); } // A chamfer of two distances: Distance 2 gets its own arrow along the other face. let faces = chamfer_face_dirs(app, d, base); if let (Kind::Fillet { distance2, .. }, Some((_, t2))) = (&mut d.kind, faces) && let Some(l2) = crate::length_input::eval(&app.session.doc, distance2, ValueKind::Length).ok().filter(|v| v.is_finite()) { - drag_arrow(&app.session.doc, ui, painter, proj, base, bs, t2, l2, false, egui::Id::new("sc_manipulator2"), half_height, distance2); + drag_arrow(&app.session.doc, ui, painter, proj, base, bs, t2, l2, false, egui::Id::new("sc_manipulator2"), half_height, 0.0, distance2); } // A rectangular pattern's second direction gets its own arrow for Spacing 2 (#2462), as the // first direction's arrow sets Spacing. @@ -553,7 +569,7 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, if let Some(spacing2) = spacing2 && let Some(l2) = crate::length_input::eval(&app.session.doc, spacing2, ValueKind::Length).ok().filter(|v| v.is_finite()) { - drag_arrow(&app.session.doc, ui, painter, proj, base, bs, n2, l2, false, egui::Id::new("sc_manipulator2"), half_height, spacing2); + drag_arrow(&app.session.doc, ui, painter, proj, base, bs, n2, l2, false, egui::Id::new("sc_manipulator2"), half_height, 0.0, spacing2); } } // An offset plane shows where it will be: at the distance, or through the picked point. @@ -611,7 +627,7 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, crate::length_input::eval(&app.session.doc, depth, ValueKind::Length).ok().filter(|v| v.is_finite()).unwrap_or(0.0) }; let before = depth.clone(); - drag_arrow(&app.session.doc, ui, painter, proj, base, bs, -n, l, false, egui::Id::new("sc_manipulator_depth"), half_height, depth); + drag_arrow(&app.session.doc, ui, painter, proj, base, bs, -n, l, false, egui::Id::new("sc_manipulator_depth"), half_height, 0.0, depth); // Dragging the depth turns "through all" into a distance. if *depth != before { opts.all = false; @@ -648,6 +664,7 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, false, egui::Id::new("sc_manipulator_offset2"), half_height, + 0.0, distance2, ) { // Its own area and field, so it does not share Distance's focus or text. @@ -662,6 +679,8 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, ); } } + // A placement marker at the base: the arrow stands above it and the base dot is the marker's. + let clear = crate::place_gizmo::arrow_clearance(app, d); let Some((label, kind, value)) = d.primary() else { return }; let len = all_span.or_else(|| { if to_span.is_some() && value.trim().is_empty() { @@ -672,6 +691,8 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, }); let before = value.clone(); let mut box_at = bs + vec2(16.0, -30.0); + // Where the box hangs from: the arrow's tip, or the base when there is no arrow. + let mut anchor = bs; if let (Some(n), Some(l)) = (dir, len.filter(|_| kind == ValueKind::Length)) { let n = n * sign; let baseline = to_span.map(f64::abs).unwrap_or(0.0); @@ -692,6 +713,7 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, signed, egui::Id::new("sc_manipulator"), half_height, + clear, dragged, ) { if (to_span.is_some() || symmetric_scale != 1.0) @@ -703,11 +725,16 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, if symmetric && let Some(bt) = proj.to_screen(base - n * half) { arrow(painter, bs, bt, t.manipulator); } - painter.circle(bs, 3.5, t.manipulator, Stroke::new(1.0, Color32::WHITE)); + if clear == 0.0 { + painter.circle(bs, 3.5, t.manipulator, Stroke::new(1.0, Color32::WHITE)); + } box_at = ts + vec2(14.0, -12.0); + anchor = ts; } } let note = crate::drag_extrude::step_note(app); + // Also without an arrow (the value does not evaluate yet): the box still keeps off the handles. + let box_at = crate::place_gizmo::yield_box(ui, anchor, box_at); value_box_noted(ui, label, value, box_at, focus || *value != before, note.as_deref()); if *value != before && let Kind::Extrude { all, .. } = &mut d.kind @@ -813,7 +840,9 @@ fn to_segment(p: Pos2, a: Pos2, b: Pos2) -> f32 { /// A draggable arrow from `base` along `n` showing `l` (at least a short stub); dragging writes /// the snapped length into `value`. The tip and the stem take the drag (#1740): pressed on the /// stem, the arrow keeps its length until the pointer moves, and then moves with it as far as the -/// pointer does. Returns the tip's screen position. +/// pointer does. Returns the tip's screen position. `clear_px` keeps that many screen points at +/// the base free: the arrow starts past them and its shortest length grows by them, so it stands +/// above a placement marker drawn at the base instead of through it. #[allow(clippy::too_many_arguments)] fn drag_arrow( doc: &solidcraft_engine::doc::Document, @@ -827,19 +856,29 @@ fn drag_arrow( signed: bool, id: egui::Id, half_height: f64, + clear_px: f32, value: &mut String, ) -> Option { let t = Tokens::get(); - let min = 40.0 * 2.0 * half_height / f64::from(proj.rect.height().max(1.0)); + let min = f64::from(40.0 + clear_px) * 2.0 * half_height / f64::from(proj.rect.height().max(1.0)); let tip = |length: f64| { let shown = if length.abs() < min { min * if length < 0.0 { -1.0 } else { 1.0 } } else { length }; proj.to_screen(base + n * shown) }; let mut ts = tip(l)?; + // Where the drawn arrow starts: the base, or past the cleared marker. + let start = |ts: Pos2| if clear_px > 0.0 && (ts - bs).length() > clear_px { bs + (ts - bs).normalized() * clear_px } else { bs }; let at_tip = egui::Rect::from_center_size(ts, vec2(20.0, 20.0)); - // Over the stem, the arrow answers where the pointer is. - let on_stem = ui.input(|i| i.pointer.hover_pos()).filter(|p| !at_tip.contains(*p) && to_segment(*p, bs, ts) <= ARROW_STEM_REACH); - let area = on_stem.map_or(at_tip, |p| egui::Rect::from_center_size(p, vec2(2.0 * ARROW_STEM_REACH, 2.0 * ARROW_STEM_REACH))); + // Over the stem, the arrow answers where the pointer is. A placement handle the arrow crosses + // (the turn ring's grip) keeps the pointer: the arrow then answers nowhere. + let hover = ui.input(|i| i.pointer.hover_pos()); + let on_handle = hover.is_some_and(crate::place_gizmo::drawn_at); + let on_stem = hover.filter(|p| !on_handle && !at_tip.contains(*p) && to_segment(*p, start(ts), ts) <= ARROW_STEM_REACH); + let area = if on_handle { + egui::Rect::NOTHING + } else { + on_stem.map_or(at_tip, |p| egui::Rect::from_center_size(p, vec2(2.0 * ARROW_STEM_REACH, 2.0 * ARROW_STEM_REACH))) + }; let r = ui.interact(area, id, egui::Sense::drag()); // How far along the arrow the press was short of its end: the drag keeps that gap. let grab = id.with("stem grab"); @@ -873,7 +912,7 @@ fn drag_arrow( crate::scenario::publish_handle(if id == egui::Id::new("sc_manipulator") { "arrow" } else { "arrow2" }, ts); let hot = r.hovered() || r.dragged(); let col = if hot { t.accent } else { t.manipulator }; - arrow(painter, bs, ts, col); + arrow(painter, start(ts), ts, col); if hot { painter.circle_stroke(ts, 8.0, Stroke::new(1.5, col)); ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); @@ -1534,7 +1573,7 @@ fn rotation_handle( /// An edge-on ring has two equally valid depths; retain the branch nearest the current handle. #[allow(clippy::too_many_arguments)] -fn projected_rotation_angle( +pub(crate) fn projected_rotation_angle( proj: &Proj, pointer: Pos2, centre: Vec3, diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 7c6382593..4171f0bba 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2508,9 +2508,11 @@ pub enum Shown { Max, } -fn vec3_of(v: &Value) -> Option { +/// A finite `[x, y, z]` of plain numbers. +pub(crate) fn vec3_of(v: &Value) -> Option { let a = v.as_array()?; - Some(Vec3::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?)) + let p = Vec3::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?); + p.is_finite().then_some(p) } /// The distance shown for a measured pair: which one, its value and its two ends. The chosen diff --git a/crates/ui-egui/src/dialogs_plastic.rs b/crates/ui-egui/src/dialogs_plastic.rs index df268d874..d6662a11c 100644 --- a/crates/ui-egui/src/dialogs_plastic.rs +++ b/crates/ui-egui/src/dialogs_plastic.rs @@ -122,6 +122,15 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { "plastic.assign_rule" => (Pl::Assign { rule: 1 }, vec![SelInput::new("Bodies", BODIES, true)]), _ => Pl::simple_start(id)?, }; + let mut inputs = inputs; + // A tool with placement handles snaps its place to sketch points on the face as a Single + // hole's does, so the marker can be dragged onto one; a bare sketch point is refused by OK as + // before. + if crate::place_gizmo::snaps_to_points(app, id) + && let Some(position) = inputs.first_mut() + { + position.accept |= crate::selection::POINTS; + } Some((crate::length_input::defaults(&app.session.doc, Kind::Plastic(pl)), inputs)) } @@ -424,6 +433,48 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec Option<(Vec3, Vec3)> { + let Sel::Face { body, index, point } = d.inputs.first()?.items.first()? else { return None }; + let n = crate::dialogs::planar_face(&app.session, body, *index) + .map(|(_, n)| n) + .or_else(|| d.extra.get("direction").and_then(crate::dialogs::vec3_of)) + .and_then(|n| n.normalized())?; + Some((*point, n)) +} + +/// The placement handles' move for a feature placed through its first input: re-place it where a +/// click at `pos` would (snapped to a sketch point as a click is when the input takes points), with +/// the stored `direction` and in-face `along` carried onto the new face. False when nothing there +/// can take it. +pub(crate) fn handle_move(app: &SolveApp, d: &mut crate::dialogs::Dialog, proj: &crate::viewport::Proj, pos: egui::Pos2) -> bool { + use crate::place_gizmo::{angle_of, dir_at}; + let s = &app.session; + let turned = handle_frame(app, d).and_then(|(_, n)| d.extra.get("along").and_then(crate::dialogs::vec3_of).map(|a| angle_of(a, n))); + let hits = crate::viewport::pick(app, proj, pos); + let snap = d.face_snap(s, &hits); + let Some(to) = hits.iter().find_map(|h| d.candidate_on(s, h, snap.as_ref()).filter(|c| matches!(c, Sel::Face { .. }))) else { + return false; + }; + if let Sel::Face { body, index, .. } = &to + && let Some((_, nn)) = crate::dialogs::planar_face(s, body, *index) + { + if d.extra.contains_key("direction") { + d.extra.insert("direction".into(), pt(nn)); + } + if let Some(a) = turned { + d.extra.insert("along".into(), pt(dir_at(nn, a))); + } + } + if let Some(inp) = d.inputs.first_mut() { + inp.items = vec![to]; + } + d.error = None; + true +} + #[cfg(test)] #[path = "dialogs_plastic_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/gizmo.rs b/crates/ui-egui/src/gizmo.rs index c809e2e15..144756316 100644 --- a/crates/ui-egui/src/gizmo.rs +++ b/crates/ui-egui/src/gizmo.rs @@ -141,7 +141,7 @@ fn in_quad(p: Pos2, q: &Ring) -> bool { } /// Where the view ray through `pos` meets the plane through `o` with normal `n`. -fn on_plane(proj: &Proj, pos: Pos2, o: Vec3, n: Vec3) -> Option { +pub(crate) fn on_plane(proj: &Proj, pos: Pos2, o: Vec3, n: Vec3) -> Option { let (ro, rd) = proj.ray(pos); let den = rd.dot(n); if den.abs() < 1e-9 { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 140defbca..3a5392ad9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -108,6 +108,7 @@ mod measurement_ui_tests; mod menu_tests; pub(crate) mod mesh_lod; pub mod messages; +pub(crate) mod motion; pub mod occurrence_drag; #[cfg(test)] mod pattern_arrow_tests; @@ -181,6 +182,7 @@ pub mod open_elsewhere; pub(crate) mod open_meshing; pub mod params_dialog; pub(crate) mod pick_index; +pub(crate) mod place_gizmo; pub(crate) mod plugins; pub mod prefs; pub mod prefs_notice; diff --git a/crates/ui-egui/src/motion.rs b/crates/ui-egui/src/motion.rs new file mode 100644 index 000000000..0480e8e46 --- /dev/null +++ b/crates/ui-egui/src/motion.rs @@ -0,0 +1,86 @@ +//! Motions shared by the viewport's handles: a state factor that eases in and out each way on its +//! own terms, a handle stepping back while another works, a colour that comes and goes, the +//! offset a press keeps for its drag, and an offset that slides instead of jumping. egui's own +//! `animate_bool_with_time` is one time both ways and linear; these are what the placement +//! handles needed on top of it (#4384), kept apart so the next manipulator reuses them. + +use egui::{Color32, Context, Id, Pos2, Response, Ui, Vec2}; + +/// A 0 to 1 factor that eases towards 1 while `on` and back to 0 when not, each way with its own +/// time and easing: a hover that opens slowly and leaves fast, for one. +#[derive(Clone, Copy)] +pub struct Transition { + /// Seconds to reach 1, and to fall back to 0. + pub on_s: f32, + pub off_s: f32, + /// The easing each way (`egui::emath::easing`). + pub ease_on: fn(f32) -> f32, + pub ease_off: fn(f32) -> f32, +} + +impl Transition { + /// The same time both ways, linear. + pub const fn symmetric(s: f32) -> Self { + Self { on_s: s, off_s: s, ease_on: egui::emath::easing::linear, ease_off: egui::emath::easing::linear } + } + + /// The factor this frame. Repaints only while it moves. + pub fn run(&self, ctx: &Context, id: Id, on: bool) -> Factor { + let (time, ease) = if on { (self.on_s, self.ease_on) } else { (self.off_s, self.ease_off) }; + Factor { t: ctx.animate_bool_with_time_and_easing(id, on, time, ease), rising: on } + } +} + +/// A [`Transition`]'s value: where it is and which way it goes, so a look can morph on the way +/// up and fade on the way down. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Factor { + pub t: f32, + pub rising: bool, +} + +impl Factor { + /// On the way down and not yet gone. + pub fn fading(self) -> bool { + !self.rising && self.t > 0.0 + } +} + +/// How much of itself a thing keeps while it steps back: 1 normally, `keep` while `back`, +/// eased over `s` seconds. +pub fn step_back(ctx: &Context, id: Id, back: bool, keep: f32, s: f32) -> f32 { + 1.0 - (1.0 - keep) * ctx.animate_bool_with_time(id, back, s) +} + +/// `colour` eased in over `s` seconds from `from`, and eased out again from the last colour given +/// once there is none: the colour it fades out of is the one it was on. +pub fn tint(ctx: &Context, id: Id, colour: Option, from: Color32, s: f32) -> Option { + if let Some(c) = colour { + ctx.data_mut(|d| d.insert_temp(id.with("colour"), c)); + } + let t = ctx.animate_bool_with_time(id, colour.is_some(), s); + ctx.data(|d| d.get_temp::(id.with("colour"))).filter(|_| t > 0.01).map(|c| from.lerp_to_gamma(c, t)) +} + +/// The gap a press keeps for its drag: `at_press` measures it from the pointer when the drag +/// starts (none when it cannot), and every dragged frame gets it back, so what is dragged follows +/// the pointer from where it was grabbed instead of jumping onto it at the first move. +pub fn grab(ui: &Ui, id: Id, r: &Response, at_press: impl FnOnce(Pos2) -> Option) -> Option { + if r.drag_started() + && let Some(p) = r.interact_pointer_pos() + { + match at_press(p) { + Some(g) => { + ui.data_mut(|d| d.insert_temp(id, g)); + } + None => ui.data_mut(|d| d.remove::(id)), + } + } + if r.dragged() { ui.data(|d| d.get_temp::(id)) } else { None } +} + +/// An offset that slides to `target` over `s` seconds instead of jumping there; the first call +/// lands at once. +pub fn slide(ctx: &Context, id: Id, target: Vec2, s: f32) -> Vec2 { + Vec2::new(ctx.animate_value_with_time(id.with("x"), target.x, s), ctx.animate_value_with_time(id.with("y"), target.y, s)) +} diff --git a/crates/ui-egui/src/place_gizmo.rs b/crates/ui-egui/src/place_gizmo.rs new file mode 100644 index 000000000..d7ad44e73 --- /dev/null +++ b/crates/ui-egui/src/place_gizmo.rs @@ -0,0 +1,412 @@ +//! Handles that place a feature on a face and turn it in the face. +//! +//! A dashed crosshair at the feature's place drags it across the model, near-white so the blue +//! preview it sits on does not hide it, cased in a darker edge so it also carries on a light body. +//! Under the pointer its lines grow, it shows the move cursor and a tooltip. While it drags, the +//! feature's footprint is outlined where the marker is: the solid preview is recomputed off the +//! window thread and trails the pointer by its boolean, the outline does not. A feature that can +//! turn in its face also gets a ring lying on the face about the same centre, a fixed size on +//! screen like the move triad's arrows; dragging its grip turns the feature about the face normal. +//! Nothing runs until OK: the handles edit the open dialog, which the live preview follows, so a +//! new feature and an Edit Feature behave alike. +//! +//! The mechanics live here; each tool that uses them is one file under `place_gizmo/` that gives a +//! [`Spec`]: where the place is, how a pointer re-places it, the footprint, and the turn if any. +//! [`spec`] picks the file by the dialog kind. The handles are published as `:position` and +//! `:rotate` for `ui.handles`. +//! +//! The handles are behind the `placement_handles` preference (Preferences > Design > Placement), off by +//! default: off, a feature is placed by its click only, as before, and its Position input takes faces +//! only. + +mod boss; +mod look; +mod rest; +mod snap_fit; + +use egui::{Pos2, vec2}; +use look::{ + CrossStyle, DIM, DIM_S, MARKER_ACTIVE, MARKER_HOT, RING_ACTIVE, RING_OPEN, RING_PX, RingStyle, angle_label, compass, crosshair, footprint, ring, +}; +use solidcraft_engine::doc::expr::Kind as ValueKind; +use solidcraft_engine::geom::Vec3; + +use crate::SolveApp; +use crate::dialogs::Dialog; +pub(crate) use crate::dialogs::vec3_of; +use crate::motion; +pub(crate) use crate::selection::point_value as pt; +use crate::theme::Tokens; +use crate::viewport::Proj; + +/// One tool's use of the handles. +pub(crate) struct Spec { + /// Handle names (`:position`, `:rotate`) and widget ids. + pub name: &'static str, + /// Is this dialog one of the tool's? + pub serves: fn(&Dialog) -> bool, + /// The tool's commands whose face place also snaps to sketch points on the face while the + /// handles are on (the place input then takes points, as a Single hole's does). + pub snap_commands: &'static [&'static str], + /// The move marker's tooltip. + pub move_tip: &'static str, + /// The place and the direction the feature grows out of its face. + pub frame: fn(&SolveApp, &Dialog) -> Option<(Vec3, Vec3)>, + /// Re-place the feature where a click at the pointer would put it; false when nothing there + /// can take it. + pub move_to: fn(&SolveApp, &mut Dialog, &Proj, Pos2) -> bool, + /// The footprint outlined while dragging, in world points (empty: no outline). + pub footprint: fn(&SolveApp, &Dialog, Vec3, Vec3) -> Vec, + pub turn: Option, +} + +/// A ring whose grip turns the feature about its face normal. +pub(crate) struct Turn { + pub tip: &'static str, + /// How far the feature reaches from its place along its turn (world); `None` hides the ring + /// (a round Rest has nothing to turn). The ring's size does not follow it. + pub reach: fn(&SolveApp, &Dialog) -> Option, + /// The current turn about `n`, from [`axes`]'s x towards its y. + pub angle: fn(&SolveApp, &Dialog, Vec3) -> f64, + /// Turn to the pointer's angle (`free` when Alt or Ctrl is held); returns the angle taken. + pub set: fn(&SolveApp, &mut Dialog, Vec3, f64, bool) -> f64, +} + +/// Every tool with handles, one file each under `place_gizmo/`, one per line in name order so +/// tools added on separate branches merge without touching each other's line. +#[rustfmt::skip] +static TOOLS: &[&Spec] = &[ + &boss::SPEC, + &rest::SPEC, + &snap_fit::SPEC, +]; + +thread_local! { + /// Where the handles were drawn last frame (screen), for [`contains_pointer`]: navigation and + /// Select Other's press-and-hold run before the handles are drawn. + static DRAWN: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + /// The ring's screen centre last frame, for [`yield_box`]. + static RING_ABOUT: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Is `p` on a placement handle of the open dialog (as drawn last frame)? +pub(crate) fn contains_pointer(app: &SolveApp, p: Pos2) -> bool { + app.dialog.as_ref().is_some_and(|d| spec(app, d).is_some()) && drawn_at(p) +} + +/// Is `p` within reach of a handle drawn last frame? For the dialog's own manipulators, which run +/// before the handles and would otherwise take a press meant for a handle their stem crosses. +pub(crate) fn drawn_at(p: Pos2) -> bool { + DRAWN.with(|h| h.borrow().iter().any(|c| c.distance(p) <= REACH)) +} + +/// The tool whose dialog this is, if it has handles. +fn spec(app: &SolveApp, d: &Dialog) -> Option<&'static Spec> { + if !app.preferences.placement_handles { + return None; + } + TOOLS.iter().copied().find(|s| (s.serves)(d)) +} + +/// How much of the screen around the base the dialog's drag arrow leaves to the move marker +/// (pixels): the marker's full reach and a gap, so the arrow stands above it. Zero without handles. +pub(crate) fn arrow_clearance(app: &SolveApp, d: &Dialog) -> f32 { + if spec(app, d).is_some() { look::MARKER_CLEAR } else { 0.0 } +} + +/// Does this command's face place also snap to sketch points on the face, so its marker can be +/// dragged onto one? +pub(crate) fn snaps_to_points(app: &SolveApp, id: &str) -> bool { + app.preferences.placement_handles && TOOLS.iter().any(|s| s.snap_commands.contains(&id)) +} + +/// Reach of a handle around its centre (pixels): wide, so a finger finds it. +const REACH: f32 = 18.0; +/// Points on a round footprint's outline. +const FOOTPRINT_SEGS: usize = 48; + +/// A length expression's value (mm), zero when it does not evaluate. +pub(crate) fn len(app: &SolveApp, e: &str) -> f64 { + app.session.doc.eval(e, ValueKind::Length).ok().filter(|v| v.is_finite()).unwrap_or(0.0).abs() +} + +/// In-plane axes about `n`: x is the engine's default in-face direction (its `any_perp`), y +/// completes them, so angle 0 is an untouched feature. +pub(crate) fn axes(n: Vec3) -> (Vec3, Vec3) { + let x = n.any_perp(); + (x, n.cross(x)) +} + +/// The direction in the face at `angle` about `n` from [`axes`]'s x. +pub(crate) fn dir_at(n: Vec3, angle: f64) -> Vec3 { + let (x, y) = axes(n); + x * angle.cos() + y * angle.sin() +} + +/// The angle of `v` about `n` from [`axes`]'s x. +pub(crate) fn angle_of(v: Vec3, n: Vec3) -> f64 { + let (x, y) = axes(n); + v.dot(y).atan2(v.dot(x)) +} + +/// `deg` rounded to `step` degrees unless `free`. +pub(crate) fn stepped(deg: f64, step: f64, free: bool) -> f64 { + if free { deg } else { (deg / step).round() * step } +} + +/// The face's four compass points: the in-face directions along the world axes, as the Snap Fit +/// combo names them (`+X`, `−Y`, …), each with its angle about `n` from [`axes`]'s x. +pub(crate) fn cardinals(n: Vec3) -> Vec<(String, f64)> { + crate::dialogs_plastic::hook_dirs(n).into_iter().map(|(name, d)| (name, angle_of(d, n))).collect() +} + +/// Within this many degrees of a compass point the turn is pulled onto it; turning freely (Alt or +/// Ctrl held) keeps only a hair of it, so an axis can still be hit exactly. +const PULL_DEG: f64 = 8.0; +const PULL_FREE_DEG: f64 = 0.5; + +/// `deg` pulled onto a compass point of the face when within [`PULL_DEG`] of one, otherwise +/// rounded to `step`; `free` leaves it alone but for the hair. +pub(crate) fn pulled(deg: f64, n: Vec3, step: f64, free: bool) -> f64 { + let off = |a: f64| ((a - deg + 180.0).rem_euclid(360.0) - 180.0).abs(); + let pull = if free { PULL_FREE_DEG } else { PULL_DEG }; + match cardinals(n).into_iter().map(|(_, a)| a.to_degrees()).min_by(|a, b| off(*a).total_cmp(&off(*b))) { + Some(a) if off(a) <= pull => a, + _ => stepped(deg, step, free), + } +} + +/// The colour of the world axis a compass point's name ends in (the one set of axis colours). +fn axis_colour(name: &str, t: &Tokens) -> egui::Color32 { + match name.chars().last() { + Some('X') => t.axis_x, + Some('Y') => t.axis_y, + _ => t.axis_z, + } +} + +/// The compass point `angle` sits on, if any. +fn at_cardinal(n: Vec3, angle: f64) -> Option { + cardinals(n) + .into_iter() + .find(|(_, a)| ((a - angle + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI).abs() < 1e-6) + .map(|(name, _)| name) +} + +/// A circle of radius `r` about `base` across `n`. +pub(crate) fn circle(base: Vec3, n: Vec3, r: f64) -> Vec { + let (x, y) = axes(n); + (0..FOOTPRINT_SEGS) + .map(|i| { + let a = std::f64::consts::TAU * i as f64 / FOOTPRINT_SEGS as f64; + base + (x * a.cos() + y * a.sin()) * r + }) + .collect() +} + +/// A rectangle about `base` across `n`: `hl` either way along `a`, `hw` either way across it. +pub(crate) fn rect(base: Vec3, n: Vec3, a: Vec3, hl: f64, hw: f64) -> Vec { + let b = n.cross(a); + [(1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)].into_iter().map(|(sa, sb)| base + a * (sa * hl) + b * (sb * hw)).collect() +} + +/// Where the pointer's ray meets the plane through `base` across `n`, none near edge-on, where a +/// plane intersection magnifies subpixel pointer error. +fn on_plane(proj: &Proj, pos: Pos2, base: Vec3, n: Vec3) -> Option { + if proj.ray(pos).1.dot(n).abs() < 0.05 { + return None; + } + crate::gizmo::on_plane(proj, pos, base, n).filter(|p| p.is_finite()) +} + +/// Draw the handles and take their drags (after the dialog's own arrow, so the marker wins +/// the pointer near the base). +pub(crate) fn show(app: &mut SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, d: &mut Dialog) { + DRAWN.with(|h| h.borrow_mut().clear()); + RING_ABOUT.with(|c| c.set(None)); + let Some(sp) = spec(app, d) else { return }; + let Some((base, _)) = (sp.frame)(app, d) else { return }; + let Some(bs) = proj.to_screen(base) else { return }; + let t = Tokens::get(); + let area = |c: Pos2| egui::Rect::from_center_size(c, vec2(2.0 * REACH, 2.0 * REACH)); + let id = |what: &str| egui::Id::new(("sc_place", sp.name, what)); + + // The crosshair that moves the feature. The press lands where the finger is, not always the + // centre: the drag keeps that gap. + let r = ui.interact(area(bs), id("position"), egui::Sense::drag()); + let off = motion::grab(ui, id("grab"), &r, |p| Some(p - bs)); + if r.dragged() { + crate::tool_modifiers::set_manipulator_dragging(true); + if let Some(p) = r.interact_pointer_pos() { + (sp.move_to)(app, d, proj, p - off.unwrap_or_default()); + } + } + // Read the frame again: a drag moved it this frame. + let Some((base, n)) = (sp.frame)(app, d) else { return }; + let Some(bs) = proj.to_screen(base) else { return }; + crate::scenario::publish_handle(&format!("{}:position", sp.name), bs); + DRAWN.with(|h| h.borrow_mut().push(bs)); + let (hovered, dragging) = (r.hovered(), r.dragged()); + // The tip while pointing, not while dragging: the hand is busy and the footprint says it all. + if hovered && !dragging { + r.clone().on_hover_text(crate::i18n::tr_label(sp.move_tip)); + } + // The handle not in use steps back while the other one works (the ring's drag is last frame's). + let turning = ui.data(|m| m.get_temp::(id("turning"))).unwrap_or(false); + let ctx = ui.ctx().clone(); + let style = CrossStyle { + hot: MARKER_HOT.run(&ctx, id("hot"), hovered || dragging).t, + active: MARKER_ACTIVE.run(&ctx, id("active"), dragging).t, + alpha: motion::step_back(&ctx, id("marker_dim"), turning, DIM, DIM_S), + }; + if dragging { + let pts: Option> = (sp.footprint)(app, d, base, n).into_iter().map(|p| proj.to_screen(p)).collect(); + if let Some(pts) = pts.filter(|p| p.len() >= 3) { + footprint(painter, &pts, &t); + } + } + crosshair(painter, bs, &style, &t); + let moving = dragging; + if hovered || dragging { + ui.ctx().set_cursor_icon(if dragging { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Move }); + } + + // The ring that turns it: on the face about the same centre, a fixed size on screen. + let Some(turn) = &sp.turn else { return }; + if (turn.reach)(app, d).is_none() { + return; + } + let mut angle = (turn.angle)(app, d, n); + let (x, y) = axes(n); + // The world radius that makes the ring RING_PX across its least foreshortened face direction + // (the larger singular value of the projected x, y pair), so it keeps its size as the view + // turns and does not change while the feature turns. + let Some(radius) = ring_radius(proj, base, x, y) else { return }; + // A point of the ring's plane by its angle and its offsets from the circle in screen points + // (outwards along the radius, along the tangent), so the grip and the compass lie on the + // face like the ring and foreshorten with it. + let per_px = radius / f64::from(RING_PX); + let on = |a: f64, r_px: f32, t_px: f32| { + let (rd, td) = (x * a.cos() + y * a.sin(), y * a.cos() - x * a.sin()); + proj.to_screen(base + rd * (radius + f64::from(r_px) * per_px) + td * (f64::from(t_px) * per_px)) + }; + let at = |a: f64| on(a, 0.0, 0.0); + let Some(mut gs) = at(angle) else { return }; + let r = ui.interact(area(gs), id("rotate"), egui::Sense::drag()); + let pointer_angle = |p: Pos2| match on_plane(proj, p, base, n) { + Some(q) => Some((q - base).dot(y).atan2((q - base).dot(x))), + None => crate::canvas::projected_rotation_angle(proj, p, base, x, y, radius, angle, (-std::f64::consts::PI, std::f64::consts::PI)), + }; + // As for the marker, the press lands somewhere on the grip, not on its exact angle: the drag + // keeps that angular gap. + let grab = motion::grab(ui, id("rotate_grab"), &r, |p| pointer_angle(p).filter(|a| a.is_finite()).map(|a| a - angle)); + if r.dragged() + && let Some(p) = r.interact_pointer_pos() + { + crate::tool_modifiers::set_manipulator_dragging(true); + if let Some(raw) = pointer_angle(p).filter(|a| a.is_finite()).map(|a| a - grab.unwrap_or(0.0)) { + angle = (turn.set)(app, d, n, raw, crate::tool_modifiers::manipulator_free()); + d.error = None; + if let Some(g) = at(angle) { + gs = g; + } + } + } + crate::scenario::publish_handle(&format!("{}:rotate", sp.name), gs); + DRAWN.with(|h| h.borrow_mut().push(gs)); + let (hovered, dragging) = (r.hovered(), r.dragged()); + ui.data_mut(|m| m.insert_temp(id("turning"), dragging)); + RING_ABOUT.with(|c| c.set(Some(bs))); + let open = RING_OPEN.run(&ctx, id("ring_hot"), hovered || dragging); + let on_point = at_cardinal(n, angle); + // Aligned with a world axis, the grip takes that axis's colour. + let axis = on_point.as_deref().map(|name| axis_colour(name, &t)); + let style = RingStyle { + hot: open.t, + active: RING_ACTIVE.run(&ctx, id("ring_active"), dragging).t, + fading: open.fading(), + alpha: motion::step_back(&ctx, id("ring_dim"), moving, DIM, DIM_S), + tint: motion::tint(&ctx, id("ring_tint"), axis, look::core(true), DIM_S), + }; + ring(painter, &on, angle, &style); + // The compass stays put while the feature turns, so you can see how far you have gone. + if style.active > 0.01 { + // The tick of the point the grip sits on is left out: the grip, in that axis's colour, is + // the tick then, and a tick drawn under it would show its casing through. + let near = |a: f64| ((a - angle + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI).abs() < 1e-6; + let dirs: Vec<(f64, egui::Color32)> = + cardinals(n).into_iter().filter(|(_, a)| !near(*a)).map(|(name, a)| (a, axis_colour(&name, &t))).collect(); + compass(painter, &on, &dirs, style.active); + } + if hovered && !dragging { + r.clone().on_hover_text(crate::i18n::tr_label(turn.tip)); + } + if hovered || dragging { + ui.ctx().set_cursor_icon(if dragging { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab }); + } + if dragging { + // The readout wraps to a half turn either way; the grab offset can carry the raw angle past it. + let mut shown = (angle + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI; + if shown <= -std::f64::consts::PI + 1e-9 { + shown = std::f64::consts::PI; + } + angle_label(painter, gs, bs, shown, on_point.as_deref().map(|name| (name, axis_colour(name, &t))), &t); + } +} + +/// The world radius of a circle about `base` across the face spanned by `x` and `y` that is +/// [`RING_PX`] on screen along the face direction the view foreshortens least. +fn ring_radius(proj: &Proj, base: Vec3, x: Vec3, y: Vec3) -> Option { + let o = proj.to_screen(base)?; + let (a, b) = (proj.to_screen(base + x)? - o, proj.to_screen(base + y)? - o); + let (p, q, r) = (f64::from(a.length_sq()), f64::from(b.length_sq()), f64::from(a.dot(b))); + let px_per_mm = ((p + q + ((p - q).powi(2) + 4.0 * r * r).sqrt()) / 2.0).sqrt(); + (px_per_mm > 1e-6).then(|| f64::from(RING_PX) / px_per_mm) +} + +/// Where the floating value box goes so it does not cover a placement handle: `at` as the caller +/// wants it, or, with a handle's centre drawn under it last frame, the same box to the left of +/// `anchor` (the arrow's tip) or above it, whichever is clear first. Seen straight down the arrow +/// collapses onto the place and the box sits just right of it, where the ring's grip often is. +pub(crate) fn yield_box(ui: &egui::Ui, anchor: Pos2, at: Pos2) -> Pos2 { + let Some(size) = ui.ctx().memory(|m| m.area_rect(egui::Id::new("sc_canvas_area"))).map(|r| r.size()) else { return at }; + let target = match RING_ABOUT.with(|c| c.get()) { + // With a ring, the box keeps out of the whole circle the ring, its grip, the compass and + // the readout sweep, whatever the turn: one place per view, nothing moves when a turn + // starts, and the grip can never come under the box. + Some(centre) => clear_of_circle(at, size, centre, RING_PX + RING_ROOM), + None => { + let covers = |p: Pos2| DRAWN.with(|h| h.borrow().iter().any(|c| egui::Rect::from_min_size(p, size).expand(4.0).contains(*c))); + if covers(at) { + let left = Pos2::new(anchor.x - (at.x - anchor.x) - size.x, at.y); + let above = Pos2::new(at.x, anchor.y - 14.0 - size.y); + [left, above].into_iter().find(|p| !covers(*p)).unwrap_or(at) + } else { + at + } + } + }; + // The step aside slides, as an offset from where the box would be, so the box still follows + // the arrow's tip at once when the view moves. + at + motion::slide(ui.ctx(), egui::Id::new("sc_place_box"), target - at, DIM_S) +} + +/// What the ring needs around it beyond its radius (pixels): the grip, the compass and the +/// readout beside the grip. +const RING_ROOM: f32 = 44.0; + +/// `at`, or the nearest place above, below, left or right of the circle where a box of `size` +/// no longer meets it. +fn clear_of_circle(at: Pos2, size: egui::Vec2, centre: Pos2, r: f32) -> Pos2 { + let rect = egui::Rect::from_min_size(at, size); + if rect.clamp(centre).distance(centre) >= r { + return at; + } + let candidates = [ + Pos2::new(at.x, centre.y - r - size.y), + Pos2::new(at.x, centre.y + r), + Pos2::new(centre.x + r, at.y), + Pos2::new(centre.x - r - size.x, at.y), + ]; + candidates.into_iter().min_by(|a, b| a.distance(at).total_cmp(&b.distance(at))).unwrap_or(at) +} diff --git a/crates/ui-egui/src/place_gizmo/boss.rs b/crates/ui-egui/src/place_gizmo/boss.rs new file mode 100644 index 000000000..078d1a99b --- /dev/null +++ b/crates/ui-egui/src/place_gizmo/boss.rs @@ -0,0 +1,30 @@ +//! Boss: the marker moves the boss across the model and snaps to sketch points, so a screw boss +//! lands on the centre of a circle drawn for it. A boss is round: no ring. + +use solidcraft_engine::geom::Vec3; + +use super::{Spec, circle, len}; +use crate::SolveApp; +use crate::dialogs::{Dialog, Kind}; +use crate::dialogs_plastic::Pl; + +pub(super) static SPEC: Spec = Spec { + name: "boss", + serves: |d| matches!(d.kind, Kind::Plastic(Pl::Boss { .. })), + snap_commands: &["plastic.boss"], + move_tip: "Drag to move the boss across the model. It snaps to sketch points on the face.", + frame: crate::dialogs_plastic::handle_frame, + move_to: crate::dialogs_plastic::handle_move, + footprint, + turn: None, +}; + +/// The boss's outer circle. +fn footprint(app: &SolveApp, d: &Dialog, base: Vec3, n: Vec3) -> Vec { + let Kind::Plastic(Pl::Boss { diameter, .. }) = &d.kind else { return Vec::new() }; + circle(base, n, len(app, diameter) * 0.5) +} + +#[cfg(test)] +#[path = "boss_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/place_gizmo/boss_tests.rs b/crates/ui-egui/src/place_gizmo/boss_tests.rs new file mode 100644 index 000000000..c93cb016d --- /dev/null +++ b/crates/ui-egui/src/place_gizmo/boss_tests.rs @@ -0,0 +1,75 @@ +//! The Boss handle: the marker drags a new boss onto a sketch point, +//! and moves an existing one from Edit Feature. + +use serde_json::json; +use solidcraft_engine::Sel; +use solidcraft_engine::doc::FeatureKind; +use solidcraft_engine::geom::Vec3; + +use crate::scenario::Harness; + +/// An 80 × 50 × 10 plate seen from the top,. +fn plate() -> Harness { + let mut h = Harness::new(); + h.app.set_origin_shown(false); + h.app.preferences.placement_handles = true; + h.app.run("solid.box", json!({"length": 80, "width": 50, "height": 10})).unwrap(); + h.step(&json!({"call": "ui.view", "params": {"view": "top"}})).unwrap(); + h.settle(); + h +} + +fn position(h: &Harness) -> Vec3 { + let d = h.app.dialog.as_ref().expect("a dialog is open"); + match d.inputs.first().and_then(|i| i.items.first()) { + Some(Sel::Face { point, .. }) => *point, + other => panic!("the Position input holds a face place, not {other:?}"), + } +} + +fn boss_position(h: &Harness) -> Vec3 { + let f = h.app.session.doc.features.iter().find(|f| matches!(f.kind, FeatureKind::Boss { .. })).expect("a Boss was made"); + let FeatureKind::Boss { position, .. } = &f.kind else { panic!("a Boss: {:?}", f.kind) }; + position.0 +} + +#[test] +fn marker_drags_a_new_boss_onto_a_sketch_point() { + let mut h = plate(); + h.app.run("sketch.create", json!({"plane": {"face": [40, 25, 10]}})).unwrap(); + h.app.run("sketch.circle.center", json!({"center": [60, 35], "radius": 1.5})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.settle(); + h.step(&json!({"start": "plastic.boss"})).unwrap(); + h.step(&json!({"click": {"world": [15, 12, 10]}})).unwrap(); + h.settle(); + assert!(position(&h).dist(Vec3::new(15.0, 12.0, 10.0)) < 0.5, "placed where clicked: {:?}", position(&h)); + assert!(h.at(&json!({"handle": "boss:position"})).is_ok(), "the marker is published"); + assert!(h.at(&json!({"handle": "boss:rotate"})).is_err(), "a round boss has no grip"); + + h.step(&json!({"drag": [{"handle": "boss:position"}, {"world": [60, 35, 10]}], "steps": 12})).unwrap(); + h.settle(); + assert!(position(&h).dist(Vec3::new(60.0, 35.0, 10.0)) < 1e-6, "snapped to the circle's centre: {:?}", position(&h)); + + h.step(&json!({"click": {"handle": "dialog:OK"}})).unwrap(); + h.settle(); + assert!(h.app.dialog.is_none(), "OK closed the dialog"); + assert!(boss_position(&h).dist(Vec3::new(60.0, 35.0, 10.0)) < 1e-6, "the Boss took the dragged place: {:?}", boss_position(&h)); +} + +#[test] +fn marker_moves_a_boss_from_edit_feature() { + let mut h = plate(); + let made = h.app.run("plastic.boss", json!({"position": [20, 20, 10], "diameter": 6, "height": 8})).unwrap(); + let name = made["name"].as_str().unwrap().to_string(); + h.settle(); + h.step(&json!({"call": "ui.editFeature", "params": {"feature": name}})).unwrap(); + h.settle(); + h.step(&json!({"drag": [{"handle": "boss:position"}, {"world": [55, 30, 10]}], "steps": 12})).unwrap(); + h.settle(); + h.step(&json!({"click": {"handle": "dialog:OK"}})).unwrap(); + h.settle(); + assert!(h.app.dialog.is_none(), "OK closed the dialog"); + assert!(boss_position(&h).dist(Vec3::new(55.0, 30.0, 10.0)) < 0.5, "the Boss moved: {:?}", boss_position(&h)); + h.step(&json!({"expect": {"errors": 0, "bodies": 1}})).unwrap(); +} diff --git a/crates/ui-egui/src/place_gizmo/look.rs b/crates/ui-egui/src/place_gizmo/look.rs new file mode 100644 index 000000000..6e836683e --- /dev/null +++ b/crates/ui-egui/src/place_gizmo/look.rs @@ -0,0 +1,345 @@ +//! The handles' appearance and nothing else: colours, line widths, sizes, easing and the shapes +//! they are drawn as. A restyle touches only this file; `place_gizmo.rs` decides where handles +//! are and what a drag does. +//! +//! The rules the handles are drawn by (worked out in a browser prototype first, see the notes on +//! #4384): white with a dark casing marks what can be grabbed, and only handles are drawn so; a +//! dotted line is a proposal (what a drag would do), a solid line a drag under way; at rest a handle +//! shows only enough to be noticed and pointing at it shows the whole action; the shape of a tip +//! names the motion (an arrowhead for a straight move). The sizes below are the prototype's, in +//! screen points. + +use egui::{Color32, Pos2, Stroke, Vec2, vec2}; + +use crate::motion::Transition; +use crate::theme::Tokens; + +/// The handles' core: the icon highlight (white in every theme), so the blue preview they sit on +/// does not hide them. They carry no meaning, only contrast, so it is the same hot or not. +pub(super) fn core(_hot: bool) -> Color32 { + Tokens::get().icons.highlight +} + +/// The casing drawn under every line and around every dot: the marker halo (dark, translucent, +/// per theme), so the white core also carries on a light body. +fn casing() -> Color32 { + Tokens::get().icons.marker_halo +} + +/// How much wider than its core a casing is (both sides together). +const CASE: f32 = 0.8; + +/// The feature's footprint on the face while the marker drags it: a filled shape in the preview's +/// own blue with a thin darker edge, so white stays reserved for the handles. It shows where the +/// feature is going before the recomputed preview gets there. +pub(super) fn footprint(painter: &egui::Painter, pts: &[Pos2], t: &Tokens) { + for shape in crate::viewport::projected_polygon(pts, t.preview_add.gamma_multiply(0.38), Stroke::new(1.2, t.manipulator)) { + painter.add(shape); + } +} + +/// The move marker's look for a frame, interpolated between its three states so hover and drag +/// grow in and out rather than snap. `hot` eases 0 (resting) to 1 (pointer over or dragging); +/// `active` eases 0 to 1 while dragging. +pub(super) struct CrossStyle { + pub(super) hot: f32, + pub(super) active: f32, + /// 1 normally, [`DIM`] while the other handle is in use. + pub(super) alpha: f32, +} + +/// How much of itself the handle not in use keeps while the other one is dragged. +pub(super) const DIM: f32 = 0.25; +/// How long a handle takes to step back and to come forward again, and how long the grip's axis +/// colour takes to come and go (seconds). +pub(super) const DIM_S: f32 = 0.16; + +/// The marker answering the pointer arriving or leaving, and switching into and out of a drag. +pub(super) const MARKER_HOT: Transition = Transition::symmetric(0.22); +pub(super) const MARKER_ACTIVE: Transition = Transition::symmetric(0.36); +/// The marker's line width (a dash's and the shaft's). +const LINE: f32 = 2.0; +/// The dot's radius. +const DOT_R: f32 = 3.9; +/// Where an arm starts, from the centre. +const ARM_FROM: f32 = 6.0; +/// A dotted arm's dash and gap. At rest an arm is two dashes; the outer one is the shape that +/// becomes the arrowhead. +const DASH: f32 = 5.5; +const GAP: f32 = 2.3; +/// The arrowhead: a filled triangle this long, this wide either side of the arm, its base where +/// the outer dash began. +const HEAD_LEN: f32 = 8.7; +const HEAD_HALF: f32 = 3.55; +/// Where the outer dash, and so the head, begins. +const HEAD_BASE: f32 = ARM_FROM + DASH + GAP; +/// What the marker needs around its centre when fully grown, plus a gap, so another manipulator +/// (the dialog's drag arrow) can keep clear of it. +pub(super) const MARKER_CLEAR: f32 = HEAD_BASE + HEAD_LEN + 6.0; + +/// The move marker: a dot with four arms to the screen cardinals. At rest each arm is two dashes, +/// a place that can be grabbed and nothing more. Pointed at, the outer dash becomes an arrowhead, +/// its far end narrowing to a point and its near end widening while it grows a little: the +/// feature moves straight in any direction along the face. While it drags, the inner dash runs +/// on into the head as a solid shaft. The dotted-to-solid switch is the one step that cannot +/// tween, so it flips halfway into the drag. +pub(super) fn crosshair(painter: &egui::Painter, c: Pos2, s: &CrossStyle, _t: &Tokens) { + let solid = s.active > 0.5; + let (core, case) = (core(s.hot > 0.5).gamma_multiply(s.alpha), casing().gamma_multiply(s.alpha)); + // The outer dash on its way to being the head. + let len = DASH + (HEAD_LEN - DASH) * s.hot; + let near = LINE / 2.0 + (HEAD_HALF - LINE / 2.0) * s.hot; + let far = LINE / 2.0 * (1.0 - s.hot); + let mut lines: Vec> = Vec::new(); + let mut heads: Vec> = Vec::new(); + for d in [vec2(1.0, 0.0), vec2(-1.0, 0.0), vec2(0.0, 1.0), vec2(0.0, -1.0)] { + // The inner dash, or the shaft up to the head's base. + lines.push(vec![c + d * ARM_FROM, c + d * if solid { HEAD_BASE } else { ARM_FROM + DASH }]); + let n: Vec2 = vec2(-d.y, d.x); + let (base, tip) = (c + d * HEAD_BASE, c + d * (HEAD_BASE + len)); + let mut h = vec![base + n * near, tip + n * far, tip - n * far, base - n * near]; + if far < 0.05 { + h.remove(2); + } + heads.push(h); + } + // Casings first, then every core over them, so a core never sits under a neighbour's casing; + // a head's casing is the same shape grown by the casing's reach, as a line's is. + for pts in &lines { + painter.add(egui::Shape::line(pts.clone(), Stroke::new(LINE + CASE, case))); + } + for h in &heads { + painter.add(egui::Shape::convex_polygon(grown(h, CASE / 2.0), case, Stroke::NONE)); + } + for pts in &lines { + painter.add(egui::Shape::line(pts.clone(), Stroke::new(LINE, core))); + } + for h in &heads { + painter.add(egui::Shape::convex_polygon(h.clone(), core, Stroke::NONE)); + } + painter.circle_filled(c, DOT_R + CASE / 2.0, case); + painter.circle_filled(c, DOT_R, core); +} + +/// A convex polygon with every edge moved outwards by `d` (mitred corners). +fn grown(pts: &[Pos2], d: f32) -> Vec { + let n = pts.len(); + if n < 3 { + return pts.to_vec(); + } + let centre = pts.iter().fold(Vec2::ZERO, |a, p| a + p.to_vec2()) / n as f32; + // Outward unit normal of the edge from pts[i] to pts[i + 1]. + let normal = |i: usize| { + let (a, b) = (pts[i], pts[(i + 1) % n]); + let e = (b - a).normalized(); + let m = vec2(-e.y, e.x); + let mid = (a.to_vec2() + b.to_vec2()) / 2.0; + if m.dot(mid - centre) < 0.0 { -m } else { m } + }; + (0..n) + .map(|i| { + let (n1, n2) = (normal((i + n - 1) % n), normal(i)); + let b = (n1 + n2).normalized(); + let cos = b.dot(n1).max(0.2); + pts[i] + b * (d / cos) + }) + .collect() +} + +/// The turn ring's look for a frame. `hot` eases 0 (resting) to 1 (pointer over the grip or +/// turning), `active` 0 to 1 while turning. While `fading`, the pointer has left: the open ring +/// no longer folds back but fades out over the resting one (`hot` is then its opacity). +pub(super) struct RingStyle { + pub(super) hot: f32, + pub(super) active: f32, + pub(super) fading: bool, + /// 1 normally, [`DIM`] while the marker is dragged. + pub(super) alpha: f32, + /// The grip filled in this colour instead of white: the axis the feature is aligned with. + pub(super) tint: Option, +} + +/// The ring's size on screen (radius, pixels): fixed, like the move triad's arrows, whatever the +/// zoom or the feature. It is a control of something on the screen, not a measure of the model. +pub(super) const RING_PX: f32 = 65.0; +/// The ring opening from its grip round the circle: eased in, slow off the grip and closing fast +/// at the far side; once the pointer has left, a quick fade, not the sweep played backwards. +pub(super) const RING_OPEN: Transition = + Transition { on_s: 0.3, off_s: 0.15, ease_on: egui::emath::easing::quadratic_in, ease_off: egui::emath::easing::linear }; +/// The solid arc and the compass coming up when a turn starts, and going. +pub(super) const RING_ACTIVE: Transition = Transition::symmetric(0.2); +/// Half of the arc shown at rest and of the solid arc while turning, either side of the grip (degrees). +const ARC_HALF_DEG: f64 = 50.0; +/// The ring's line width, its dash and gap along the arc. +const RING_LINE: f32 = 1.6; +const RING_DASH: f32 = 4.5; +const RING_GAP: f32 = 4.5; +/// The grip: a half-diamond pointing in at the centre, this long and this wide either side; at +/// rest an open chevron this far outside the ring, sliding in onto it as the ring opens. +const GRIP_LEN: f32 = 12.0; +const GRIP_HALF: f32 = 6.0; +const GRIP_OUT: f32 = 8.0; +/// The chevron's leg thickness across the base, and how far from the tip its hole's apex sits at +/// rest (the thickness along the legs' bisector). +const GRIP_LEG: f32 = 1.8; +const GRIP_APEX_IN: f32 = 3.8; +/// Angular step of the arc's polyline (degrees). +const ARC_STEP_DEG: f64 = 1.5; + +/// The turn ring: a circle lying on the face about the move marker's centre, drawn in +/// perspective. At rest a short dotted arc with the grip, enough to say that something here +/// turns; pointed at, the dotted circle opens from the grip both ways round and the grip slides +/// in onto it and fills; while turning, a solid arc around the grip is laid over the circle. `on` +/// gives the screen point of the ring's plane at an angle about the face normal and offsets from +/// the circle (outwards, along the tangent) in screen points (none when behind the eye), so the +/// grip lies on the face like the ring; `grip` is the feature's turn, where the grip sits. +pub(super) fn ring(painter: &egui::Painter, on: &dyn Fn(f64, f32, f32) -> Option, grip: f64, s: &RingStyle) { + if s.fading { + // The resting ring underneath, the open one fading out over it. + arc(painter, on, grip, ARC_HALF_DEG, false, 0.0, (1.0 - s.hot) * s.alpha, s.tint); + arc(painter, on, grip, 180.0, false, 1.0, s.hot * s.alpha, s.tint); + } else { + let open = ARC_HALF_DEG + (180.0 - ARC_HALF_DEG) * f64::from(s.hot); + arc(painter, on, grip, open, false, s.hot, s.alpha, s.tint); + } + if s.active > 0.01 { + arc_only(painter, on, grip, ARC_HALF_DEG, true, s.active * s.alpha); + } +} + +/// One layer of the ring: the arc `half` degrees either side of the grip, dotted or solid, and the +/// grip `slid` of the way from its resting chevron outside the ring to the filled half-diamond on it. +#[allow(clippy::too_many_arguments)] +fn arc( + painter: &egui::Painter, + on: &dyn Fn(f64, f32, f32) -> Option, + grip: f64, + half: f64, + solid: bool, + slid: f32, + alpha: f32, + tint: Option, +) { + arc_only(painter, on, grip, half, solid, alpha); + let (core, case) = (tint.unwrap_or_else(|| core(slid > 0.5)).gamma_multiply(alpha), casing().gamma_multiply(alpha)); + // The grip is a thick white chevron: a triangle with a triangular hole, cased along its outer + // and its inner edge. As it slides in onto the ring the hole flattens, its apex sinking to the + // base, until the inner edge is the base line of a full half-diamond and fades away. + let out = GRIP_OUT * (1.0 - slid); + let apex_in = GRIP_APEX_IN + (GRIP_LEN - GRIP_APEX_IN) * slid; + let (Some(tip), Some(c1), Some(c2), Some(i1), Some(i2), Some(apex)) = ( + on(grip, out, 0.0), + on(grip, out + GRIP_LEN, GRIP_HALF), + on(grip, out + GRIP_LEN, -GRIP_HALF), + on(grip, out + GRIP_LEN, GRIP_HALF - GRIP_LEG), + on(grip, out + GRIP_LEN, -(GRIP_HALF - GRIP_LEG)), + on(grip, out + apex_in, 0.0), + ) else { + return; + }; + // Casing first, the white over it, so the casing shows by half its width outside every edge, + // as a line's does: the outer edge and the legs' ends always; the inner edge gives way to the + // base line as the hole closes. + let closing = ((slid - 0.85) / 0.15).clamp(0.0, 1.0); + let lines: Vec<(Vec, f32)> = + vec![(vec![c1, tip, c2], 1.0), (vec![c1, i1], 1.0), (vec![c2, i2], 1.0), (vec![i1, apex, i2], 1.0 - closing), (vec![i1, i2], closing)]; + for (l, a) in &lines { + if *a > 0.01 { + painter.add(egui::Shape::line(l.clone(), Stroke::new(CASE, case.gamma_multiply(*a)))); + } + } + // The two legs, convex quads that meet at the tip; as the apex sinks they fill the triangle. + for leg in [vec![c1, tip, apex, i1], vec![c2, tip, apex, i2]] { + painter.add(egui::Shape::convex_polygon(leg, core, Stroke::NONE)); + } +} + +/// The arc alone, `half` degrees either side of the grip, dotted or solid. +fn arc_only(painter: &egui::Painter, on: &dyn Fn(f64, f32, f32) -> Option, grip: f64, half: f64, solid: bool, alpha: f32) { + let steps = (2.0 * half / ARC_STEP_DEG).ceil().max(2.0) as usize; + let pts: Vec = + (0..=steps).filter_map(|i| on(grip - half.to_radians() + 2.0 * half.to_radians() * i as f64 / steps as f64, 0.0, 0.0)).collect(); + let (core, case) = (core(true).gamma_multiply(alpha), casing().gamma_multiply(alpha)); + let pieces: Vec> = if solid { vec![pts] } else { dashed(&pts, RING_DASH, RING_GAP) }; + for piece in &pieces { + painter.add(egui::Shape::line(piece.clone(), Stroke::new(RING_LINE + CASE, case))); + } + for piece in &pieces { + painter.add(egui::Shape::line(piece.clone(), Stroke::new(RING_LINE, core))); + } +} + +/// `pts` cut into dashes of `dash` screen length with `gap` between them, measured along the line. +fn dashed(pts: &[Pos2], dash: f32, gap: f32) -> Vec> { + let mut out: Vec> = Vec::new(); + let mut cur: Vec = Vec::new(); + // Where we are in the dash cycle: on for `dash`, off for `gap`. + let (mut phase, mut on) = (0.0f32, true); + for w in pts.windows(2) { + let (a, b) = (w[0], w[1]); + let len = (b - a).length(); + let mut t0 = 0.0f32; + while t0 < len { + let span = (if on { dash } else { gap }) - phase; + let t1 = (t0 + span).min(len); + if on { + if cur.is_empty() { + cur.push(a + (b - a) * (t0 / len)); + } + cur.push(a + (b - a) * (t1 / len)); + } + if t1 < len || (t1 - t0) >= span { + // the piece ended inside this segment (or exactly at its end): switch + if on && !cur.is_empty() { + out.push(std::mem::take(&mut cur)); + } + on = !on; + phase = 0.0; + } else { + phase += t1 - t0; + } + t0 = t1; + } + } + if !cur.is_empty() { + out.push(cur); + } + out +} + +/// The compass: a short tick just outside the ring at each of the face's compass points, in the +/// ring's plane and the unturned frame, so it stays put while the ring turns, each in the colour +/// of the world axis it points along (the move triad's). Faded in by `alpha`. +pub(super) fn compass(painter: &egui::Painter, on: &dyn Fn(f64, f32, f32) -> Option, dirs: &[(f64, Color32)], alpha: f32) { + let case = casing().gamma_multiply(alpha); + for &(a, col) in dirs { + let (Some(p), Some(q)) = (on(a, TICK_FROM, 0.0), on(a, TICK_FROM + TICK_LEN, 0.0)) else { continue }; + painter.line_segment([p, q], Stroke::new(RING_LINE + CASE, case)); + painter.line_segment([p, q], Stroke::new(RING_LINE, col.gamma_multiply(alpha))); + } +} + +/// A compass tick starts this far outside the ring and is this long. +const TICK_FROM: f32 = 4.0; +const TICK_LEN: f32 = 7.0; + +/// The turn ring's readout while turning, beside the grip at `at`, away from the ring's `centre`: +/// the angle, and the compass point it was pulled onto ("90° · +X"). +pub(super) fn angle_label(painter: &egui::Painter, at: Pos2, centre: Pos2, angle: f64, on: Option<(&str, Color32)>, t: &Tokens) { + // The point's name in its axis colour, so the eye finds the axis before it reads the letter. + let font = egui::FontId::proportional(t.font_body); + let mut job = egui::text::LayoutJob::default(); + job.append(&format!("{:.0}°", angle.to_degrees()), 0.0, egui::TextFormat::simple(font.clone(), t.text)); + if let Some((name, col)) = on { + job.append(" · ", 0.0, egui::TextFormat::simple(font.clone(), t.text)); + job.append(name, 0.0, egui::TextFormat::simple(font, col)); + } + let out = (at - centre).normalized(); + let out = if out.is_finite() { out } else { vec2(1.0, 0.0) }; + let anchor = at + out * (GRIP_LEN + GRIP_OUT + 6.0); + let align = if out.x >= 0.0 { egui::Align2::LEFT_CENTER } else { egui::Align2::RIGHT_CENTER }; + let galley = painter.layout_job(job); + let rect = align.anchor_size(anchor, galley.size()).expand2(vec2(5.0, 2.0)); + painter.rect(rect, 4.0, t.panel.gamma_multiply(0.92), Stroke::new(1.0, t.manipulator), egui::StrokeKind::Inside); + painter.galley(rect.shrink2(vec2(5.0, 2.0)).min, galley, t.text); +} diff --git a/crates/ui-egui/src/place_gizmo/rest.rs b/crates/ui-egui/src/place_gizmo/rest.rs new file mode 100644 index 000000000..5a811f1d2 --- /dev/null +++ b/crates/ui-egui/src/place_gizmo/rest.rs @@ -0,0 +1,55 @@ +//! Rest: the marker moves the pad, the ring turns a rectangular one in 5° steps, pulled onto the +//! face's compass points when near one (Alt or Ctrl held: free), kept as the command's `along`. + +use solidcraft_engine::geom::Vec3; + +use super::{Spec, Turn, angle_of, circle, dir_at, len, pt, pulled, rect, vec3_of}; +use crate::SolveApp; +use crate::dialogs::{Dialog, Kind}; +use crate::dialogs_plastic::Pl; + +pub(super) static SPEC: Spec = Spec { + name: "rest", + serves: |d| matches!(d.kind, Kind::Plastic(Pl::Rest { .. })), + snap_commands: &["plastic.rest"], + move_tip: "Drag to move the rest across the model. It snaps to sketch points on the face.", + frame: crate::dialogs_plastic::handle_frame, + move_to: crate::dialogs_plastic::handle_move, + footprint, + turn: Some(Turn { tip: "Drag to turn the rest in 5° steps. Hold Alt or Ctrl to turn it freely.", reach, angle, set }), +}; + +/// Rotation step without a modifier (degrees). +const STEP_DEG: f64 = 5.0; + +/// The pad's footprint: a circle of the diameter, or the rectangle of the length along `along` +/// and the width across it. +fn footprint(app: &SolveApp, d: &Dialog, base: Vec3, n: Vec3) -> Vec { + let Kind::Plastic(Pl::Rest { round, width, length, .. }) = &d.kind else { return Vec::new() }; + if *round { + circle(base, n, len(app, width) * 0.5) + } else { + rect(base, n, dir_at(n, angle(app, d, n)), len(app, length) * 0.5, len(app, width) * 0.5) + } +} + +/// Half the length of a rectangular pad; a round one has no ring. +fn reach(app: &SolveApp, d: &Dialog) -> Option { + let Kind::Plastic(Pl::Rest { round: false, length, .. }) = &d.kind else { return None }; + Some(len(app, length) * 0.5) +} + +/// The stored `along` as an angle about `n` from the engine's default direction. +fn angle(_: &SolveApp, d: &Dialog, n: Vec3) -> f64 { + d.extra.get("along").and_then(vec3_of).map(|a| angle_of(a, n)).unwrap_or(0.0) +} + +fn set(_: &SolveApp, d: &mut Dialog, n: Vec3, raw: f64, free: bool) -> f64 { + let a = pulled(raw.to_degrees(), n, STEP_DEG, free).to_radians(); + d.extra.insert("along".into(), pt(dir_at(n, a))); + a +} + +#[cfg(test)] +#[path = "rest_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/place_gizmo/rest_tests.rs b/crates/ui-egui/src/place_gizmo/rest_tests.rs new file mode 100644 index 000000000..0e036f652 --- /dev/null +++ b/crates/ui-egui/src/place_gizmo/rest_tests.rs @@ -0,0 +1,178 @@ +//! The Rest handles: the marker drags the pad across the model and snaps to +//! a sketch point as a click would; the grip turns a rectangular pad, also from Edit Feature. + +use serde_json::json; +use solidcraft_engine::Sel; +use solidcraft_engine::doc::FeatureKind; +use solidcraft_engine::geom::Vec3; + +use crate::scenario::Harness; + +/// An 80 × 50 × 10 plate seen from the top, with the handles on. +fn plate() -> Harness { + let mut h = Harness::new(); + h.app.set_origin_shown(false); + h.app.preferences.placement_handles = true; + h.app.run("solid.box", json!({"length": 80, "width": 50, "height": 10})).unwrap(); + h.step(&json!({"call": "ui.view", "params": {"view": "top"}})).unwrap(); + h.settle(); + h +} + +fn position(h: &Harness) -> Vec3 { + let d = h.app.dialog.as_ref().expect("a dialog is open"); + match d.inputs.first().and_then(|i| i.items.first()) { + Some(Sel::Face { point, .. }) => *point, + other => panic!("the Position input holds a face place, not {other:?}"), + } +} + +fn drag_handle(h: &mut Harness, name: &str, to: serde_json::Value) { + h.step(&json!({"drag": [{"handle": name}, to], "steps": 12})).unwrap(); + h.settle(); +} + +#[test] +fn ball_drags_the_rest_across_the_face_and_snaps_to_a_sketch_point() { + let mut h = plate(); + // A circle on the top face: its centre is a sketch point the pad can snap to. + h.app.run("sketch.create", json!({"plane": {"face": [40, 25, 10]}})).unwrap(); + h.app.run("sketch.circle.center", json!({"center": [60, 40], "radius": 4})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.settle(); + h.step(&json!({"start": "plastic.rest"})).unwrap(); + h.step(&json!({"click": {"world": [15, 12, 10]}})).unwrap(); + h.settle(); + assert!(position(&h).dist(Vec3::new(15.0, 12.0, 10.0)) < 0.5, "placed where clicked: {:?}", position(&h)); + assert!(h.at(&json!({"handle": "rest:position"})).is_ok(), "the ball is published"); + + drag_handle(&mut h, "rest:position", json!({"world": [40, 20, 10]})); + assert!(position(&h).dist(Vec3::new(40.0, 20.0, 10.0)) < 0.5, "dragged across the face: {:?}", position(&h)); + + drag_handle(&mut h, "rest:position", json!({"world": [60, 40, 10]})); + let p = position(&h); + assert!(p.dist(Vec3::new(60.0, 40.0, 10.0)) < 1e-6, "snapped to the circle's centre: {p:?}"); + assert!(h.app.dialog.as_ref().is_some_and(|d| d.error.is_none())); + + h.step(&json!({"click": {"handle": "dialog:OK"}})).unwrap(); + h.settle(); + assert!(h.app.dialog.is_none(), "OK closed the dialog"); + let rest = h.app.session.doc.features.iter().find(|f| matches!(f.kind, FeatureKind::Rest { .. })).expect("a Rest was made"); + let FeatureKind::Rest { position, .. } = &rest.kind else { panic!("a Rest: {:?}", rest.kind) }; + assert!(position.0.dist(Vec3::new(60.0, 40.0, 10.0)) < 1e-6, "the Rest took the dragged place: {:?}", position.0); +} + +#[test] +fn grip_turns_a_rectangular_rest_from_edit_feature() { + let mut h = plate(); + let made = h.app.run("plastic.rest", json!({"position": [40, 25, 10], "width": 6, "length": 16, "height": 2})).unwrap(); + let name = made["name"].as_str().unwrap().to_string(); + h.settle(); + h.step(&json!({"call": "ui.editFeature", "params": {"feature": name}})).unwrap(); + h.settle(); + let ball = h.at(&json!({"handle": "rest:position"})).unwrap(); + let grip = h.at(&json!({"handle": "rest:rotate"})).unwrap(); + assert!((grip[0] - ball[0]).hypot(grip[1] - ball[1]) > 20.0, "the grip stands off the ball: {grip:?} {ball:?}"); + // A quarter turn of the grip about the ball on screen (the top view looks straight down). + let (dx, dy) = (grip[0] - ball[0], grip[1] - ball[1]); + let to = [ball[0] - dy, ball[1] + dx]; + h.step(&json!({"drag": [grip, to], "steps": 16})).unwrap(); + h.settle(); + let along = h.app.dialog.as_ref().and_then(|d| d.extra.get("along")).cloned().expect("the dialog keeps `along`"); + let a: Vec = along.as_array().unwrap().iter().filter_map(|v| v.as_f64()).collect(); + // Untouched, a pad on a Z face runs along Y; a quarter turn puts it along X. + assert!(a[0].abs() > 0.99 && a[1].abs() < 0.02, "turned a quarter: {a:?}"); + + h.step(&json!({"click": {"handle": "dialog:OK"}})).unwrap(); + h.settle(); + assert!(h.app.dialog.is_none(), "OK closed the dialog"); + let rest = h.app.session.doc.find_feature(&name).expect("the Rest is still there"); + let FeatureKind::Rest { along: Some(along), length: Some(_), .. } = &rest.kind else { + panic!("a rectangular Rest with `along`: {:?}", rest.kind) + }; + assert!(along.0.x.abs() > 0.99, "the feature keeps the turn: {:?}", along.0); + h.step(&json!({"expect": {"errors": 0, "bodies": 1}})).unwrap(); +} + +/// Seen from the home view, the Height arrow's stem starts at the pad's centre, where the ball +/// sits. A press there belongs to the ball: the pad moves, the height stays. +#[test] +fn ball_wins_the_press_over_the_height_arrow_at_the_base() { + let mut h = Harness::new(); + h.app.set_origin_shown(false); + h.app.preferences.placement_handles = true; + h.app.run("solid.box", json!({"length": 80, "width": 50, "height": 10})).unwrap(); + h.settle(); + h.step(&json!({"start": "plastic.rest"})).unwrap(); + h.step(&json!({"click": {"world": [20, 15, 10]}})).unwrap(); + h.settle(); + let height_before = match &h.app.dialog.as_ref().expect("a dialog").kind { + crate::dialogs::Kind::Plastic(crate::dialogs_plastic::Pl::Rest { height, .. }) => height.clone(), + other => panic!("a Rest dialog, not {other:?}"), + }; + // Up and to the right on screen, the way the arrow points in the home view. + drag_handle(&mut h, "rest:position", json!({"world": [45, 35, 10]})); + assert!(position(&h).dist(Vec3::new(45.0, 35.0, 10.0)) < 0.5, "the pad moved: {:?}", position(&h)); + let height_after = match &h.app.dialog.as_ref().expect("a dialog").kind { + crate::dialogs::Kind::Plastic(crate::dialogs_plastic::Pl::Rest { height, .. }) => height.clone(), + other => panic!("a Rest dialog, not {other:?}"), + }; + assert_eq!(height_after, height_before, "the Height arrow did not take the press"); +} + +/// Grabbing the marker off its centre must not jump the pad: the drag keeps the offset from the +/// press, so the pad moves by the drag vector, not by the vector plus the off-centre grab. +#[test] +fn a_press_off_centre_does_not_jump_the_pad() { + let mut h = plate(); + h.step(&json!({"start": "plastic.rest"})).unwrap(); + h.step(&json!({"click": {"world": [40, 25, 10]}})).unwrap(); + h.settle(); + let start = h.at(&json!({"handle": "rest:position"})).unwrap(); + // Press 14 px off centre (inside the marker's reach), then drag by a known screen vector. + let off = 14.0; + let (dx, dy) = (60.0, 30.0); + let from = json!([start[0] + off, start[1]]); + let to = json!([start[0] + off + dx, start[1] + dy]); + h.step(&json!({"drag": [from, to], "steps": 10})).unwrap(); + h.settle(); + let end = h.at(&json!({"handle": "rest:position"})).unwrap(); + // The pad followed the drag vector. Without the grab offset it would land `off` further along. + assert!((end[0] - (start[0] + dx)).abs() < 6.0, "x jumped: start {start:?} end {end:?}"); + assert!((end[1] - (start[1] + dy)).abs() < 6.0, "y jumped: start {start:?} end {end:?}"); +} + +/// A still press on the marker is someone thinking about where to drag: it never opens Select +/// Other's list, even where the list has things to offer (a sketch point on a face). +#[test] +fn holding_the_marker_still_never_opens_select_other() { + let mut h = plate(); + h.app.run("sketch.create", json!({"plane": {"face": [40, 25, 10]}})).unwrap(); + h.app.run("sketch.circle.center", json!({"center": [40, 25], "radius": 4})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.settle(); + h.step(&json!({"start": "plastic.rest"})).unwrap(); + h.step(&json!({"click": {"world": [40, 25, 10]}})).unwrap(); + h.settle(); + h.step(&json!({"hold": {"handle": "rest:position"}})).unwrap(); + assert!(!crate::select_other::is_open(&h.app), "a held press on the marker opened Select Other"); + // Away from the marker the same hold still opens it. + h.step(&json!({"hold": {"world": [40, 29, 10]}})).unwrap(); + assert!(crate::select_other::is_open(&h.app), "a held press on the circle opens Select Other"); +} + +/// With the preference off (the default) nothing changes: the Position input takes faces only, no +/// handle is drawn, and the pad stays where it was clicked. +#[test] +fn with_the_preference_off_a_rest_is_placed_by_its_click_alone() { + let mut h = plate(); + h.app.preferences.placement_handles = false; + h.step(&json!({"start": "plastic.rest"})).unwrap(); + h.step(&json!({"click": {"world": [15, 12, 10]}})).unwrap(); + h.settle(); + let accept = h.app.dialog.as_ref().expect("a dialog").inputs.first().expect("a Position input").accept; + assert_eq!(accept & crate::selection::POINTS, 0, "the Position input takes faces only"); + assert!(h.at(&json!({"handle": "rest:position"})).is_err(), "no marker is published"); + assert!(h.at(&json!({"handle": "rest:rotate"})).is_err(), "no grip is published"); + assert!(position(&h).dist(Vec3::new(15.0, 12.0, 10.0)) < 0.5, "placed where clicked: {:?}", position(&h)); +} diff --git a/crates/ui-egui/src/place_gizmo/snap_fit.rs b/crates/ui-egui/src/place_gizmo/snap_fit.rs new file mode 100644 index 000000000..9e3419ba0 --- /dev/null +++ b/crates/ui-egui/src/place_gizmo/snap_fit.rs @@ -0,0 +1,62 @@ +//! Snap Fit: the marker moves the arm and snaps to sketch points (#3423 asks to put it where a +//! sketch says); the ring's grip points the catch, in the four directions the Catch Direction +//! combo offers for the face, so the ring and the combo always agree. + +use solidcraft_engine::geom::Vec3; + +use super::{Spec, Turn, angle_of, len, rect}; +use crate::SolveApp; +use crate::dialogs::{Dialog, Kind}; +use crate::dialogs_plastic::{Pl, hook_dirs}; + +pub(super) static SPEC: Spec = Spec { + name: "snap_fit", + serves: |d| matches!(d.kind, Kind::Plastic(Pl::SnapFit { .. })), + snap_commands: &["plastic.snap_fit"], + move_tip: "Drag to move the snap fit across the model. It snaps to sketch points on the face.", + frame: crate::dialogs_plastic::handle_frame, + move_to: crate::dialogs_plastic::handle_move, + footprint, + turn: Some(Turn { tip: "Drag to point the catch in another direction.", reach, angle, set }), +}; + +/// The catch's direction across the face, as the combo shows it. +fn catch(d: &Dialog, n: Vec3) -> Option { + let Kind::Plastic(Pl::SnapFit { hook, .. }) = &d.kind else { return None }; + hook_dirs(n).get(*hook).map(|h| h.1) +} + +/// The arm's foot: its thickness behind the place, towards the catch's opposite side, and its +/// width centred across (the evaluator's side profile). +fn footprint(app: &SolveApp, d: &Dialog, base: Vec3, n: Vec3) -> Vec { + let (Kind::Plastic(Pl::SnapFit { thickness, width, .. }), Some(c)) = (&d.kind, catch(d, n)) else { return Vec::new() }; + let t = len(app, thickness); + rect(base - c * (t * 0.5), n, c, t * 0.5, len(app, width) * 0.5) +} + +/// The catch reaches its depth past the place. +fn reach(app: &SolveApp, d: &Dialog) -> Option { + let Kind::Plastic(Pl::SnapFit { catch_depth, .. }) = &d.kind else { return None }; + Some(len(app, catch_depth)) +} + +fn angle(_: &SolveApp, d: &Dialog, n: Vec3) -> f64 { + catch(d, n).map(|c| angle_of(c, n)).unwrap_or(0.0) +} + +/// The catch direction nearest the pointer; free turning is not offered, the command keeps only +/// the combo's four directions. +fn set(_: &SolveApp, d: &mut Dialog, n: Vec3, raw: f64, _free: bool) -> f64 { + let dirs = hook_dirs(n); + let off = |a: f64| (a - raw + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI; + let best = dirs.iter().map(|h| angle_of(h.1, n)).enumerate().min_by(|a, b| off(a.1).abs().total_cmp(&off(b.1).abs())); + let Some((i, a)) = best else { return raw }; + if let Kind::Plastic(Pl::SnapFit { hook, .. }) = &mut d.kind { + *hook = i; + } + a +} + +#[cfg(test)] +#[path = "snap_fit_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/place_gizmo/snap_fit_tests.rs b/crates/ui-egui/src/place_gizmo/snap_fit_tests.rs new file mode 100644 index 000000000..4dc7de873 --- /dev/null +++ b/crates/ui-egui/src/place_gizmo/snap_fit_tests.rs @@ -0,0 +1,75 @@ +//! The Snap Fit handles: the marker drags the arm onto a sketch +//! point (#3423), the grip points the catch and the Catch Direction combo follows. + +use serde_json::json; +use solidcraft_engine::Sel; +use solidcraft_engine::doc::FeatureKind; +use solidcraft_engine::geom::Vec3; + +use crate::dialogs::Kind; +use crate::dialogs_plastic::{Pl, hook_dirs}; +use crate::scenario::Harness; + +/// An 80 × 50 × 10 plate seen from the top,. +fn plate() -> Harness { + let mut h = Harness::new(); + h.app.set_origin_shown(false); + h.app.preferences.placement_handles = true; + h.app.run("solid.box", json!({"length": 80, "width": 50, "height": 10})).unwrap(); + h.step(&json!({"call": "ui.view", "params": {"view": "top"}})).unwrap(); + h.settle(); + h +} + +fn position(h: &Harness) -> Vec3 { + let d = h.app.dialog.as_ref().expect("a dialog is open"); + match d.inputs.first().and_then(|i| i.items.first()) { + Some(Sel::Face { point, .. }) => *point, + other => panic!("the Position input holds a face place, not {other:?}"), + } +} + +fn hook(h: &Harness) -> usize { + match &h.app.dialog.as_ref().expect("a dialog is open").kind { + Kind::Plastic(Pl::SnapFit { hook, .. }) => *hook, + other => panic!("a Snap Fit dialog, not {other:?}"), + } +} + +#[test] +fn marker_drags_the_snap_fit_onto_a_sketch_point_and_the_grip_points_the_catch() { + let mut h = plate(); + h.app.run("sketch.create", json!({"plane": {"face": [40, 25, 10]}})).unwrap(); + h.app.run("sketch.point", json!({"point": [50, 30]})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.settle(); + h.step(&json!({"start": "plastic.snap_fit"})).unwrap(); + h.step(&json!({"click": {"world": [15, 12, 10]}})).unwrap(); + h.settle(); + h.step(&json!({"drag": [{"handle": "snap_fit:position"}, {"world": [50, 30, 10]}], "steps": 12})).unwrap(); + h.settle(); + assert!(position(&h).dist(Vec3::new(50.0, 30.0, 10.0)) < 1e-6, "snapped to the sketch point: {:?}", position(&h)); + + // Turn the grip a quarter about the marker on screen: the catch takes the next direction. + let before = hook(&h); + let ball = h.at(&json!({"handle": "snap_fit:position"})).unwrap(); + let grip = h.at(&json!({"handle": "snap_fit:rotate"})).unwrap(); + let (dx, dy) = (grip[0] - ball[0], grip[1] - ball[1]); + assert!(dx.hypot(dy) > 20.0, "the grip stands off the marker: {grip:?} {ball:?}"); + h.step(&json!({"drag": [grip, [ball[0] - dy, ball[1] + dx]], "steps": 16})).unwrap(); + h.settle(); + let after = hook(&h); + assert_ne!(after, before, "the catch turned"); + let n = Vec3::new(0.0, 0.0, 1.0); + let (b, a) = (hook_dirs(n)[before].1, hook_dirs(n)[after].1); + assert!(a.dot(b).abs() < 1e-9, "a quarter turn: {b:?} -> {a:?}"); + + h.step(&json!({"click": {"handle": "dialog:OK"}})).unwrap(); + h.settle(); + assert!(h.app.dialog.is_none(), "OK closed the dialog"); + let f = h.app.session.doc.features.iter().find(|f| matches!(f.kind, FeatureKind::SnapFit { .. })).expect("a Snap Fit was made"); + let FeatureKind::SnapFit { position, hook, .. } = &f.kind else { panic!("a Snap Fit: {:?}", f.kind) }; + assert!(position.0.dist(Vec3::new(50.0, 30.0, 10.0)) < 1e-6, "the place: {:?}", position.0); + assert!(hook.0.dist(a) < 1e-9, "the catch direction: {:?}", hook.0); + h.step(&json!({"expect": {"errors": 0, "bodies": 1}})).unwrap(); +} diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 4152e76d8..0bb647dd5 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -612,6 +612,10 @@ preference_settings! { hole_moves: bool = false, PAGE_DESIGN => check("Move holes by clicking or dragging"); /// The browser's Origin folder starts hidden in designs that don't keep its eye themselves. hide_origin: bool = false, PAGE_DESIGN => check_tr("ui.hide_origin_by_default"); + /// Handles on the preview of a feature placed on a face (Rest, Boss, Snap Fit): a marker that + /// drags it across the model and a ring that turns it. Off by default: the feature is then placed + /// by its click only, as before, and its Position input takes faces only. + placement_handles: bool = false, PAGE_DESIGN => check("Placement handles", "Handles on the preview of a Rest, Boss or Snap Fit: drag the marker to move it across the model, turn it by its ring"); /// What a middle-button double-click in the view does: `home`, `fit` or `off`. middle_double_click: String = "home".into(), PAGE_NAVIGATION; /// Colour vision mode (#778): `off`, `protan`, `deutan` or `tritan`. diff --git a/crates/ui-egui/src/prefs/design.rs b/crates/ui-egui/src/prefs/design.rs index 40c890752..59a275822 100644 --- a/crates/ui-egui/src/prefs/design.rs +++ b/crates/ui-egui/src/prefs/design.rs @@ -75,4 +75,7 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::Text::Hint("hole_moves"), ); }); + ui_kit::settings_section(ui, "placement", app.tr("prefs.placement"), |ui| { + setting::placement_handles(app, ui); + }); } diff --git a/crates/ui-egui/src/select_other.rs b/crates/ui-egui/src/select_other.rs index 382434970..60271ad7c 100644 --- a/crates/ui-egui/src/select_other.rs +++ b/crates/ui-egui/src/select_other.rs @@ -427,7 +427,9 @@ pub fn track_hold( && !is_open(app) && app.dialog.as_ref().is_none_or(|d| d.wants_picks()) && app.viewport.point_drag.is_none(); - if pressed && inside && free && !navigating { + // A press on a canvas handle (a manipulator) drags it, and a still hold there is someone + // thinking about where to drag, not asking for the overlapping-pick list. + if pressed && inside && free && !navigating && !hover.is_some_and(|p| crate::canvas::owns_pointer(app, proj, p)) { let held = Held::from_modifiers(ctx.input(|i| i.modifiers)); app.viewport.select_other.hold = hover.map(|p| (p, now, held)); } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d57758ea1..6138e758b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -303,7 +303,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox. | `ui.home` | `open?`: bool; `sample?`: index | the start page: show or hide it, open a built-in sample (once built); returns `open` and the recent designs | | `ui.shortcut` | `command`, `key?`, `replace?` | a command's key, or rebinds it (`""` clears; a key another command uses is refused unless `replace`) | | `ui.help` | `item?`: `about`, `shortcuts` (read only), `report` (opens a report draft for review), `crashes` (the Crash Reports window) | the version, commit, build date and diagnostic text | -| `ui.prefs` | any of `default_units`, `nav` (`fusion`, `solidworks`, `inventor`, `alias`, `blender`, `tinkercad`, `openscad`, `touchpad`), `zoom_reverse`, `pan_reverse_x` (default false: horizontal scrolling pans the other way), `zoom_to_cursor`, `smooth_wheel_zoom` (default true), `trackpad_pan` (default true: two-finger scroll pans, except Touchpad always zooms; pinch zooms), `orbit_around` (`view_centre` (default: what Pan moves and Fit frames), `origin` (the world origin stays still on screen), `cursor` (the model point under the pointer when the drag began); the older `orbit_cursor` boolean still sets `cursor` when true), `look_at_anim`, `look_at_speed`, `middle_double_click` (`home` (default), `fit`, `off`), `msaa`, `show_frame_rate` (default false: frames per second in the view's bottom-right corner, counting the frames the view draws anyway; it reads 0 FPS once the view is idle), `window_system` (Linux: `auto` (default: XWayland whenever there is an X display, native Wayland on niri), `wayland`, `x11`; saved in `graphics.json`, applies at the next start; `SOLIDCRAFT_WAYLAND` overrides it), `graphics_adapter` (exact card name, or empty for Automatic; applies after restart; `WGPU_ADAPTER_NAME` takes precedence), `frame_rate_details` (default false: with the frame rate, a frame-time graph of the frames drawn with the triangles over it, a frame-time histogram and what the GPU drew; clicking the readout switches it), `length_decimals`, `angle_decimals`, `step_values` (default false: Up/Down and the wheel step a plain number in a focused value field), `theme` (`dark`, `light`, `system` or a theme file's id: a built-in one such as `gruvbox-dark`, or an imported one; the reply's `theme_ids` lists them), `viewport_theme` (`theme` (default: the theme's own), `light`, `dark`: the 3D view in the Light or Dark theme's colours whatever the window uses, #4146), `theme_import` (a `solidcraft-theme/1` file's JSON or text: adds the theme and turns it on; the reply's `theme_imported` is its id), `theme_remove` (an imported theme's id), `theme_export: true` (the reply's `theme_file` is the theme on now as a complete file; see [colour themes](book/src/guide/ui-tour.md#colour-themes)), `language` (`en`, `ja`, `de`, `fr`, `ko`, `ms`, `ru`, `uk`, `zh`; see [localization](localization.md)), `ui_scale`, `ui_font` (an installed font family or a font file for the interface; empty for the built-in font), `up_axis` (`z`, `y`), `offer_stand_up`, `extrude_auto_to_object` (default false: in the Extrude dialog, with a profile picked, a face, vertex or parallel plane picked off its plane switches the extent to To Object; it applies to Extrude dialogs opened afterwards), `hole_snaps` (default false: a Single hole snaps to its face's middle and round edges' centres), `hole_moves` (default false: a placed Single hole has a drag handle (`hole:`), and a pick on a face that has a hole moves it there), `color_vision` (`off` (default), `protan`, `deutan`, `tritan`: colour vision modes, #778), `view_confirm_corner` (default false: while a dialog or a sketch is open, a check and a cross at the view's top right, handles `view:confirm:ok` and `view:confirm:cancel`, do what the dialog's OK and Cancel do, or Finish Sketch and Cancel Sketch; the axis view or cube moves down below them, #6709), `check_updates` (default true; [updates](book/src/guide/updates.md)); `open` (a page: General, Interface, Design, Navigation, Keyboard Shortcuts, Sketch, Graphics, AI, Plugins; Shortcuts, Assistant and Sketch & selection are aliases, and the former Selection page opens Sketch) opens the Preferences dialog there; `button`: `ok`, `cancel`, `apply`, `defaults`; `stand_up: true` stands up a just-opened Y-up file, `stand_up: false` leaves it as it is ("Leave it": the offer closes and `offer_stand_up` stays on); the offer's buttons are the handles `stand_up:stand`, `stand_up:leave` and `stand_up:never` | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `dark`, `viewport_dark` (whether the 3D view is dark) and `stand_up_offer` | +| `ui.prefs` | any of `default_units`, `nav` (`fusion`, `solidworks`, `inventor`, `alias`, `blender`, `tinkercad`, `openscad`, `touchpad`), `zoom_reverse`, `pan_reverse_x` (default false: horizontal scrolling pans the other way), `zoom_to_cursor`, `smooth_wheel_zoom` (default true), `trackpad_pan` (default true: two-finger scroll pans, except Touchpad always zooms; pinch zooms), `orbit_around` (`view_centre` (default: what Pan moves and Fit frames), `origin` (the world origin stays still on screen), `cursor` (the model point under the pointer when the drag began); the older `orbit_cursor` boolean still sets `cursor` when true), `look_at_anim`, `look_at_speed`, `middle_double_click` (`home` (default), `fit`, `off`), `msaa`, `show_frame_rate` (default false: frames per second in the view's bottom-right corner, counting the frames the view draws anyway; it reads 0 FPS once the view is idle), `window_system` (Linux: `auto` (default: XWayland whenever there is an X display, native Wayland on niri), `wayland`, `x11`; saved in `graphics.json`, applies at the next start; `SOLIDCRAFT_WAYLAND` overrides it), `graphics_adapter` (exact card name, or empty for Automatic; applies after restart; `WGPU_ADAPTER_NAME` takes precedence), `frame_rate_details` (default false: with the frame rate, a frame-time graph of the frames drawn with the triangles over it, a frame-time histogram and what the GPU drew; clicking the readout switches it), `length_decimals`, `angle_decimals`, `step_values` (default false: Up/Down and the wheel step a plain number in a focused value field), `theme` (`dark`, `light`, `system` or a theme file's id: a built-in one such as `gruvbox-dark`, or an imported one; the reply's `theme_ids` lists them), `viewport_theme` (`theme` (default: the theme's own), `light`, `dark`: the 3D view in the Light or Dark theme's colours whatever the window uses, #4146), `theme_import` (a `solidcraft-theme/1` file's JSON or text: adds the theme and turns it on; the reply's `theme_imported` is its id), `theme_remove` (an imported theme's id), `theme_export: true` (the reply's `theme_file` is the theme on now as a complete file; see [colour themes](book/src/guide/ui-tour.md#colour-themes)), `language` (`en`, `ja`, `de`, `fr`, `ko`, `ms`, `ru`, `uk`, `zh`; see [localization](localization.md)), `ui_scale`, `ui_font` (an installed font family or a font file for the interface; empty for the built-in font), `up_axis` (`z`, `y`), `offer_stand_up`, `extrude_auto_to_object` (default false: in the Extrude dialog, with a profile picked, a face, vertex or parallel plane picked off its plane switches the extent to To Object; it applies to Extrude dialogs opened afterwards), `hole_snaps` (default false: a Single hole snaps to its face's middle and round edges' centres), `hole_moves` (default false: a placed Single hole has a drag handle (`hole:`), and a pick on a face that has a hole moves it there), `placement_handles` (default false: handles on the preview of a Rest, Boss or Snap Fit that move it across the model and turn it), `color_vision` (`off` (default), `protan`, `deutan`, `tritan`: colour vision modes, #778), `view_confirm_corner` (default false: while a dialog or a sketch is open, a check and a cross at the view's top right, handles `view:confirm:ok` and `view:confirm:cancel`, do what the dialog's OK and Cancel do, or Finish Sketch and Cancel Sketch; the axis view or cube moves down below them, #6709), `check_updates` (default true; [updates](book/src/guide/updates.md)); `open` (a page: General, Interface, Design, Navigation, Keyboard Shortcuts, Sketch, Graphics, AI, Plugins; Shortcuts, Assistant and Sketch & selection are aliases, and the former Selection page opens Sketch) opens the Preferences dialog there; `button`: `ok`, `cancel`, `apply`, `defaults`; `stand_up: true` stands up a just-opened Y-up file, `stand_up: false` leaves it as it is ("Leave it": the offer closes and `offer_stand_up` stays on); the offer's buttons are the handles `stand_up:stand`, `stand_up:leave` and `stand_up:never` | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `dark`, `viewport_dark` (whether the 3D view is dark) and `stand_up_offer` | | `ui.capture` | `action?`: `capture`, `revert`, `cancel` | answers the Capture Position question (asked when a command starts or the design is saved while components were moved without capturing); without `action`, what waits | | `ui.window` | `action`: minimize, maximize, restore, toggle, close | what the title bar's caption buttons do (on Windows and Linux the application bar is the title bar); close asks about unsaved designs first | | `ui.agent_cursor` | `show` (bool), `speed`: a number from 1 to 5 (times the normal speed) or `"instant"` (no animation: the command runs at once and the pointer jumps to where it acted), `follow_camera` (bool); all optional | the settings. While the cursor is shown, `engine.execute` first glides to the command's toolbar button and to each pick, then runs and replies; later requests wait their turn. The pointer shows the command's localized name, including commands inside a closed toolbar group; an animated batch names each command it visits. It also follows the pointer input sent with `ui.move`, `ui.click`, `ui.drag` and `ui.scroll`, as each event reaches the app, and a press leaves a ripple. `"animate": false` on a call skips it |