diff --git a/assets/locales/pending/primitive-handles.json b/assets/locales/pending/primitive-handles.json new file mode 100644 index 00000000000..e3215a06334 --- /dev/null +++ b/assets/locales/pending/primitive-handles.json @@ -0,0 +1,29 @@ +{ + "en": { + "Drag to place it on another face.": "Drag to place it on another face." + }, + "ar": { + "Drag to place it on another face.": "اسحب لوضعه على وجه آخر." + }, + "de": { + "Drag to place it on another face.": "Ziehen, um es auf eine andere Fläche zu setzen." + }, + "he": { + "Drag to place it on another face.": "יש לגרור כדי להציב אותו על פאה אחרת." + }, + "ja": { + "Drag to place it on another face.": "ドラッグして別の面に配置します。" + }, + "ko": { + "Drag to place it on another face.": "드래그하여 다른 면에 배치합니다." + }, + "pl": { + "Drag to place it on another face.": "Przeciągnij, aby umieścić go na innej ścianie." + }, + "vi": { + "Drag to place it on another face.": "Kéo để đặt nó lên một bề mặt khác." + }, + "zh": { + "Drag to place it on another face.": "拖动以将其放置到另一个面上。" + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index d0a594d2b46..20a00d18124 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -423,10 +423,11 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj return; } // A cylinder's values are typed in its window; its distances from its reference edges - // (#6380) are shown and typed on the canvas, as a hole's. + // (#6380) are shown and typed on the canvas, as a hole's, then its placement handles drawn. if matches!(d.kind, Kind::Primitive { cmd: "solid.cylinder", .. }) { crate::hole_refs::canvas(app, ui, painter, proj, &mut d); app.dialog = Some(d); + crate::place_gizmo::show(app, ui, painter, proj); return; } if let Some((base, dir)) = anchor(app, &d) diff --git a/crates/ui-egui/src/dialogs_plastic.rs b/crates/ui-egui/src/dialogs_plastic.rs index 01f724e6d15..a05dc360e4a 100644 --- a/crates/ui-egui/src/dialogs_plastic.rs +++ b/crates/ui-egui/src/dialogs_plastic.rs @@ -434,44 +434,6 @@ 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 with `hits` (the pick under the pointer) 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, hits: &[crate::viewport::Hit]) -> 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 Some(to) = crate::place_gizmo::face_pick(d, s, hits) 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/hole_refs.rs b/crates/ui-egui/src/hole_refs.rs index 30677cd6ec2..17d3dd7bda1 100644 --- a/crates/ui-egui/src/hole_refs.rs +++ b/crates/ui-egui/src/hole_refs.rs @@ -205,6 +205,28 @@ fn framed(s: &Session, d: &Dialog, at: Vec3, edges: [Option; 2]) -> Option }) } +/// Let go of the reference edges the place cannot be measured from any more (after a move to +/// another body, say), as the command would refuse them; the others are kept and measured again. +pub(crate) fn keep_reachable(s: &Session, d: &mut Dialog) { + let Some(at) = place(d) else { return }; + let Some(dir) = direction(s, d, at) else { return }; + let world = crate::open_meshing::session_world(s); + for (k, edge) in edges(d).into_iter().enumerate() { + let Some(p) = edge else { continue }; + if reference_frame(&world, at, dir, &[(p, None)], true).is_ok() { + continue; + } + if let Some(inp) = REFERENCES.get(k).and_then(|label| d.inputs.iter_mut().find(|i| i.label == *label)) { + inp.items.clear(); + } + if let Some(refs) = refs_mut(d) { + refs.distance[k].clear(); + refs.exact[k] = None; + refs.shown[k] = None; + } + } +} + /// The face input's item the reference edges place: the first face pick (see [`place`]). The /// edges place that one hole only; OK refuses them with more than one. fn place_item(d: &Dialog) -> Option { @@ -214,16 +236,17 @@ fn place_item(d: &Dialog) -> Option { /// What the picked reference edges leave the hole at item `i` of the face input free to do: with /// one edge, along it at its distance; with two, anywhere again, a move then setting both /// distances (as it did before any edge was picked); with none, anywhere. Only the hole the edges -/// place (see [`place_item`]) is held; another hole in the same dialog moves anywhere. Read from +/// place (see [`place_item`]) is held; another hole in the same dialog moves anywhere. A +/// Cylinder's reference edges hold it the same way. Read from /// the frame last found for these edges (`sync` keeps it current), or found again when the design /// changed since; an edge picked but not framed yet, or a frame that failed, leaves the hole free. pub(crate) fn freedom(s: &Session, d: &Dialog, i: usize) -> Freedom { - let Kind::Hole { opts, .. } = &d.kind else { return Freedom::Plane }; + let Some(refs) = refs(d).filter(|_| takes(d)) else { return Freedom::Plane }; if place_item(d) != Some(i) { return Freedom::Plane; } let edges = edges(d); - let Some(f) = opts.refs.frame.as_ref().filter(|f| f.edges == edges) else { return Freedom::Plane }; + let Some(f) = refs.frame.as_ref().filter(|f| f.edges == edges) else { return Freedom::Plane }; let fresh = if f.revision == s.revision { None } else { Some(place(d).and_then(|at| framed(s, d, at, edges))) }; match fresh.as_ref().unwrap_or(&f.frame).as_ref().map(|(fr, _)| fr.lines.as_slice()) { Some([a]) => Freedom::Line(a.along), @@ -242,8 +265,8 @@ pub(crate) enum Stuck { } /// Move the hole at item `i` of the face input toward `near` as far as its one reference edge -/// lets it: onto the line at the typed distance from it, nearest `near`. The typed distance -/// stays as it is, an expression included, so a drag never rewrites it. +/// lets it: onto the line at the typed distance from it, nearest `near` (a Cylinder's base with +/// it). The typed distance stays as it is, an expression included, so a drag never rewrites it. pub(crate) fn drag_to(s: &Session, d: &mut Dialog, i: usize, near: Vec3) -> Result<(), Stuck> { if place_item(d) != Some(i) { return Err(Stuck::Not); @@ -252,19 +275,19 @@ pub(crate) fn drag_to(s: &Session, d: &mut Dialog, i: usize, near: Vec3) -> Resu if picked.len() != 1 { return Err(Stuck::Not); } - let Kind::Hole { opts, .. } = &d.kind else { return Err(Stuck::Not) }; - let values: Option> = picked.iter().map(|k| model_text(&opts.refs, *k).and_then(|e| s.doc.eval(e, ValueKind::Length).ok())).collect(); + let Some(refs) = refs(d).filter(|_| takes(d)) else { return Err(Stuck::Not) }; + let values: Option> = picked.iter().map(|k| model_text(refs, *k).and_then(|e| s.doc.eval(e, ValueKind::Length).ok())).collect(); let Some(to) = values.and_then(|v| f.place(near, &v).ok()) else { return Err(Stuck::Not) }; if !on_reference_face(&crate::open_meshing::session_world(s), &f, to) { return Err(Stuck::OffFace); } - let Some(Sel::Face { point, .. }) = d.inputs.first_mut().and_then(|inp| inp.items.get_mut(i)) else { return Err(Stuck::Not) }; - *point = to; + if !matches!(d.inputs.first().and_then(|inp| inp.items.get(i)), Some(Sel::Face { .. })) { + return Err(Stuck::Not); + } + set_place(d, to); // In step already: the place moved by its distances, so there is nothing to measure again. let edges = edges(d); - if let Kind::Hole { opts, .. } = &mut d.kind - && let Some(sn) = opts.refs.seen.as_mut() - { + if let Some(sn) = refs_mut(d).and_then(|r| r.seen.as_mut()) { sn.place = to; sn.edges = edges; } diff --git a/crates/ui-egui/src/place_gizmo.rs b/crates/ui-egui/src/place_gizmo.rs index 2739861b190..f6bb633d473 100644 --- a/crates/ui-egui/src/place_gizmo.rs +++ b/crates/ui-egui/src/place_gizmo.rs @@ -15,17 +15,20 @@ //! [`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 +//! The handles are behind the `placement_handles` preference (Preferences > Tools > Placement handles), off by //! default: off, a feature is placed by its click only, as before, and its Position input takes faces //! only. A Single hole's markers (#6818) stay behind Create Hole › Move holes by clicking or dragging //! instead, as the hole's own handle was; each tool's [`Spec::serves`] says what turns it on. //! //! A tool has one place (a Rest) or one per item of its first input (a Single hole, a marker on each -//! hole placed): [`Spec::places`] lists them, and a drag or a click names the place by its key. +//! hole placed): [`Spec::place`] says where they come from, and a drag or a click names the place by +//! its key. Most tools keep their place as the face item of one input ([`PlaceSource::Input`]): the +//! marker reads it from there and moves it by replacing the item, as a click on the input does. mod boss; mod hole; mod look; +mod primitive; mod rest; mod snap_fit; @@ -67,12 +70,8 @@ pub(crate) struct Spec { /// (a Single hole's; `turn` is then ignored). Off: one place, `:position`, and the ring /// if any. pub many: bool, - /// The places the handles stand at. - pub places: fn(&SolveApp, &Dialog) -> Vec, - /// Re-place the feature at `key` where a click with these hits (the pick under the pointer, - /// taken while the dialog is open, so it snaps as a click does) would put it; false when - /// nothing there can take it. - pub move_to: fn(&SolveApp, &mut Dialog, &[Hit], usize) -> bool, + /// Where the places the handles stand at come from, and how a drag moves one. + pub place: PlaceSource, /// What a click (a press without a drag) on the marker at `key` does: a Single hole is taken /// out. `None`: a click on the marker does nothing. pub click: Option, @@ -85,6 +84,81 @@ pub(crate) struct Spec { pub turn: Option, } +/// Where a tool keeps its place, so where the marker reads it and how a drag moves it. +pub(crate) enum PlaceSource { + /// The face item of the dialog's input `n` (a Rest's, Boss's or Snap Fit's Position input): + /// the picked point, growing along the face's normal, else the stored `direction` when the + /// face is gone. A drag replaces the item where a click on that input would put it, snapped + /// as the click is, carrying `direction` and the in-face `along` onto the new face. + Input(usize), + /// The tool's own: `places` lists them; `move_to` re-places the one at `key` where a click + /// with these hits (the pick under the pointer, taken while the dialog is open, so it snaps + /// as a click does) would put it, false when nothing there can take it. + Own { places: fn(&SolveApp, &Dialog) -> Vec, move_to: fn(&SolveApp, &mut Dialog, &[Hit], usize) -> bool }, +} + +impl Spec { + /// The places the handles stand at. + fn places(&self, app: &SolveApp, d: &Dialog) -> Vec { + match self.place { + PlaceSource::Input(i) => one(input_frame(app, d, i)), + PlaceSource::Own { places, .. } => places(app, d), + } + } + + /// Re-place the feature at `key` where a click with these hits would put it. + fn move_to(&self, app: &SolveApp, d: &mut Dialog, hits: &[Hit], key: usize) -> bool { + match self.place { + PlaceSource::Input(i) => input_move(app, d, hits, i), + PlaceSource::Own { move_to, .. } => move_to(app, d, hits, key), + } + } + + /// The input whose rules the marker's pick follows: the place's, else the first (a Single + /// hole's places are the items of its first input). + fn place_input(&self) -> usize { + match self.place { + PlaceSource::Input(i) => i, + PlaceSource::Own { .. } => 0, + } + } +} + +/// The place of a tool kept in its input `i`: the face item's point and the direction the +/// feature grows, the face's normal, else the stored `direction`. +fn input_frame(app: &SolveApp, d: &Dialog, i: usize) -> Option<(Vec3, Vec3)> { + let Sel::Face { body, index, point } = d.inputs.get(i)?.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(vec3_of)) + .and_then(|n| n.normalized())?; + Some((*point, n)) +} + +/// The move of a tool kept in its input `i`: the item replaced where a click with `hits` would +/// put it (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. +fn input_move(app: &SolveApp, d: &mut Dialog, hits: &[Hit], i: usize) -> bool { + let s = &app.session; + let turned = input_frame(app, d, i).and_then(|(_, n)| d.extra.get("along").and_then(vec3_of).map(|a| angle_of(a, n))); + let Some(to) = face_pick(d, s, hits) 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.get_mut(i) { + inp.items = vec![to]; + } + d.error = None; + true +} + /// The ways a place can go on its face. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum Freedom { @@ -114,12 +188,18 @@ pub(crate) fn one(frame: Option<(Vec3, Vec3)>) -> Vec { frame.map(|(base, n)| Place { key: 0, base, n }).into_iter().collect() } -/// Are the shared handles on (Preferences > Design > Placement handles)? The gate of every +/// Are the shared handles on (Preferences > Tools > Placement handles)? The gate of every /// tool but the hole, whose markers keep the hole's own setting. pub(crate) fn on(app: &SolveApp) -> bool { app.preferences.placement_handles } +/// A pick the shared handles take as a move: a Cylinder held by one reference edge moves along it +/// (see `primitive::pick_held`). Only with the handles on; off, the pick is the dialog's, as before. +pub(crate) fn pick_held(app: &SolveApp, d: &mut Dialog, sel: &Sel) -> bool { + on(app) && primitive::pick_held(app, d, sel) +} + /// The face place a click with `hits` would add to the dialog's first input: snapped to a sketch /// point as a click is when the input takes points; none when nothing there is a face. pub(crate) fn face_pick(d: &Dialog, s: &Session, hits: &[Hit]) -> Option { @@ -145,6 +225,7 @@ pub(crate) struct Turn { static TOOLS: &[&Spec] = &[ &boss::SPEC, &hole::SPEC, + &primitive::SPEC, &rest::SPEC, &snap_fit::SPEC, ]; @@ -346,7 +427,7 @@ pub(crate) fn show(app: &mut SolveApp, ui: &mut egui::Ui, painter: &egui::Painte DRAWN.with(|h| h.borrow_mut().clear()); RING_ABOUT.with(|c| c.set(None)); let Some(sp) = app.dialog.as_ref().and_then(|d| spec(app, d)) else { return }; - let places = |app: &SolveApp| app.dialog.as_ref().map(|d| (sp.places)(app, d)).unwrap_or_default(); + let places = |app: &SolveApp| app.dialog.as_ref().map(|d| sp.places(app, d)).unwrap_or_default(); 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::unique(("sc_place", sp.name, what)); @@ -377,10 +458,11 @@ pub(crate) fn show(app: &mut SolveApp, ui: &mut egui::Ui, painter: &egui::Painte if r.dragged() { crate::tool_modifiers::set_manipulator_dragging(true); if let Some(p) = r.interact_pointer_pos() { - let was = app.dialog.as_mut().map(|d| std::mem::replace(&mut d.active, 0)); + // The pick follows the place input's rules, whichever input is active. + let was = app.dialog.as_mut().map(|d| std::mem::replace(&mut d.active, sp.place_input())); let hits = crate::viewport::pick(app, proj, p - off.unwrap_or_default()); with_dialog(app, |app, d| { - (sp.move_to)(app, d, &hits, pl.key); + sp.move_to(app, d, &hits, pl.key); }); if let (Some(d), Some(was)) = (app.dialog.as_mut(), was) { d.active = was; diff --git a/crates/ui-egui/src/place_gizmo/boss.rs b/crates/ui-egui/src/place_gizmo/boss.rs index ce8e276b0c6..974abdecc78 100644 --- a/crates/ui-egui/src/place_gizmo/boss.rs +++ b/crates/ui-egui/src/place_gizmo/boss.rs @@ -3,7 +3,7 @@ use solidcore_record::Vec3; -use super::{Spec, circle, len}; +use super::{PlaceSource, Spec, circle, len}; use crate::SolveApp; use crate::dialogs::{Dialog, Kind}; use crate::dialogs_plastic::Pl; @@ -14,8 +14,7 @@ pub(super) static SPEC: Spec = Spec { snap_commands: &["plastic.boss"], move_tip: "Drag to move the boss across the model. It snaps to sketch points on the face.", many: false, - places: |app, d| super::one(crate::dialogs_plastic::handle_frame(app, d)), - move_to: |app, d, hits, _| crate::dialogs_plastic::handle_move(app, d, hits), + place: PlaceSource::Input(0), click: None, footprint, freedom: super::anywhere, diff --git a/crates/ui-egui/src/place_gizmo/hole.rs b/crates/ui-egui/src/place_gizmo/hole.rs index 5556055a9c2..36280eb8796 100644 --- a/crates/ui-egui/src/place_gizmo/hole.rs +++ b/crates/ui-egui/src/place_gizmo/hole.rs @@ -16,7 +16,7 @@ use solidcore_record::Vec3; use solidcraft_engine::Sel; use solidcraft_engine::geom::prelude::*; -use super::{Freedom, Place, Spec, circle, face_pick, len, vec3_of}; +use super::{Freedom, Place, PlaceSource, Spec, circle, face_pick, len, vec3_of}; use crate::SolveApp; use crate::dialogs::{Dialog, Kind}; use crate::viewport::Hit; @@ -27,8 +27,7 @@ pub(super) static SPEC: Spec = Spec { snap_commands: &[], move_tip: "Drag to move the hole; click to remove it", many: true, - places, - move_to, + place: PlaceSource::Own { places, move_to }, click: Some(|app, d, key| { if crate::hole_place::several(app, d) { crate::hole_place::several_change_item(&app.session, d, key, None); diff --git a/crates/ui-egui/src/place_gizmo/primitive.rs b/crates/ui-egui/src/place_gizmo/primitive.rs new file mode 100644 index 00000000000..5ce690a7c34 --- /dev/null +++ b/crates/ui-egui/src/place_gizmo/primitive.rs @@ -0,0 +1,310 @@ +//! Box, Cylinder, Cone, Sphere, Torus and Coil: the marker places the primitive on the face under +//! the pointer, standing on it as a pre-selected face places it, while the dialog is open, from +//! Edit Feature too. The primitives do not turn in their face: no ring. +//! +//! Where the place is kept differs by primitive, and the marker moves it there: +//! - a Cylinder stands where its Face input is picked (and its reference edges measure from +//! there, #6380), so a drag replaces that item, as a click on the input does; one reference +//! edge holds it on a line at the typed distance, as it holds a hole; +//! - a Box placed by its typed corner or centre (#5638) has the drop written into those fields, +//! so it stands on the face, centred across it; +//! - any other, and a Box a pre-selected face placed, takes the drop as its picked place. +//! +//! The marker sits at the dialog's picked place when there is one, else at the stored or typed +//! position (the centre, the base, or the middle of the box's side on its face), else where the +//! command puts a primitive with none (the origin). A typed Box's side on its face is found from +//! the model: the side that lies on a planar face looking at it, its bottom first. +//! +//! A Cylinder, Cone or Coil needs a planar face for its axis: a curved one does not take the drop. +//! A Torus is made flat, so its outline is drawn flat whatever face it is over. +//! +//! A Coil with a sketch profile has no marker: its place is the profile's, and the base and axis +//! the dialog would send from a picked place move the axis but not the section. + +use std::cell::RefCell; +use std::sync::Arc; + +use serde_json::Value; +use solidcore_record::Vec3; +use solidcraft_engine::doc::expr::Kind as ValueKind; +use solidcraft_engine::geom::prelude::*; + +use solidcraft_engine::Sel; + +use super::{PlaceSource, Spec, circle, face_pick, rect, vec3_of}; +use crate::SolveApp; +use crate::dialogs::{Dialog, Kind}; +use crate::viewport::Hit; + +pub(super) static SPEC: Spec = Spec { + name: "primitive", + serves: |app, d| super::on(app) && matches!(d.kind, Kind::Primitive { .. }) && !coil_with_profile(d), + snap_commands: &[], + move_tip: "Drag to place it on another face.", + many: false, + place: PlaceSource::Own { places: |app, d| super::one(frame(app, d)), move_to }, + click: None, + footprint, + freedom: |app, d, key| crate::hole_refs::freedom(&app.session, d, key), + turn: None, +}; + +/// A planar face's plane: a point on it, its outward normal and the face's bounds (lowest and +/// highest corner of the box round it). +type FacePlane = (Vec3, Vec3, [Vec3; 2]); + +thread_local! { + /// The planes of the planar faces of the model state last asked about, found once per state. + static PLANES: RefCell<(Option>, Arc>)> = RefCell::new((None, Arc::new(Vec::new()))); +} + +/// The planes of the model's planar faces. +fn planes(app: &SolveApp) -> Arc> { + let st = crate::open_meshing::session_world(&app.session); + if let Some(known) = PLANES.with(|c| c.borrow().0.as_ref().filter(|k| Arc::ptr_eq(k, &st)).map(|_| c.borrow().1.clone())) { + return known; + } + let found: Vec = st + .bodies + .iter() + .flat_map(|b| { + let m = b.mesh(); + let mut bounds: std::collections::HashMap = std::collections::HashMap::new(); + for (t, f) in m.triangles.iter().zip(&m.tri_face) { + for q in m.tri(t).into_iter().flatten() { + let e = bounds.entry(*f as usize).or_insert([q, q]); + *e = [e[0].min(q), e[1].max(q)]; + } + } + b.body + .faces((b.body.size() * 1e-3).max(1e-3)) + .unwrap_or_default() + .into_iter() + .filter_map(|f| Some((f.centroid, f.plane_normal?, *bounds.get(&f.index)?))) + .collect::>() + }) + .collect(); + let found = Arc::new(found); + PLANES.with(|c| *c.borrow_mut() = (Some(st), found.clone())); + found +} + +/// Is this a Coil whose section comes from a sketch (its Profile input holds something)? +fn coil_with_profile(d: &Dialog) -> bool { + matches!(&d.kind, Kind::Primitive { cmd: "solid.coil", .. }) && d.inputs.iter().any(|i| !i.items.is_empty()) +} + +/// A size field's value (mm), zero when it is missing or does not evaluate, read as OK reads it +/// (`length_input::eval`): a bare number, a decimal comma or a unitless expression is in the +/// design's unit. +fn size(app: &SolveApp, d: &Dialog, key: &str) -> f64 { + let Kind::Primitive { fields, .. } = &d.kind else { return 0.0 }; + fields + .iter() + .find(|f| f.0 == key) + .and_then(|f| crate::length_input::eval(&app.session.doc, &f.1, ValueKind::Length).ok()) + .filter(|v| v.is_finite()) + .map(f64::abs) + .unwrap_or(0.0) +} + +/// The radius, from whichever of `radius` (Edit Feature) or `diameter` (a new one) the dialog holds. +fn radius(app: &SolveApp, d: &Dialog) -> f64 { + let Kind::Primitive { fields, .. } = &d.kind else { return 0.0 }; + if fields.iter().any(|f| f.0 == "radius") { size(app, d, "radius") } else { size(app, d, "diameter") * 0.5 } +} + +/// The box's length, width and height (mm). +fn box_size(app: &SolveApp, d: &Dialog) -> Vec3 { + Vec3::new(size(app, d, "length"), size(app, d, "width"), size(app, d, "height")) +} + +/// A stored or typed point of expressions (numbers, or strings in the design's terms); an empty +/// field is 0, as OK sends it. +fn expr_point(app: &SolveApp, v: &Value) -> Option { + let c = |i: usize| -> Option { + let x = v.as_array()?.get(i)?; + if x.as_str().is_some_and(|t| t.trim().is_empty()) { + return Some(0.0); + } + x.as_f64() + .or_else(|| app.session.doc.eval(&app.session.doc.with_design_unit(x.as_str()?, ValueKind::Length), ValueKind::Length).ok()) + .filter(|v| v.is_finite()) + }; + Some(Vec3::new(c(0)?, c(1)?, c(2)?)) +} + +/// Is `n` along a world axis (either way)? +fn square_to(n: Vec3, axis: Vec3) -> bool { + n.dot(axis).abs() > 1.0 - 1e-9 +} + +/// The faces a Box can stand on, by their normal, in the order they are looked for. +const STANDS_ON: [Vec3; 6] = [Vec3::Z, Vec3::X, Vec3::new(-1.0, 0.0, 0.0), Vec3::Y, Vec3::new(0.0, -1.0, 0.0), Vec3::new(0.0, 0.0, -1.0)]; + +/// How far a box side may be from the face plane and still stand on it (mm): a drop is written to +/// the micrometre. +const ON_PLANE: f64 = 1e-3; + +/// Where a typed Box stands: the middle of its side that lies on a planar face of the model +/// looking at it (its bottom first), else the middle of its bottom. +fn box_frame(app: &SolveApp, d: &Dialog) -> Option<(Vec3, Vec3)> { + let half = box_size(app, d) * 0.5; + let centre = match d.extra.get("center") { + Some(v) => expr_point(app, v)?, + None => d.extra.get("corner").and_then(|v| expr_point(app, v)).unwrap_or(Vec3::ZERO) + half, + }; + let side = |n: Vec3| centre - Vec3::new(n.x * half.x, n.y * half.y, n.z * half.z); + // The side's rectangle overlaps the face across its plane: a far face in the same plane is + // not one the box stands on. + let overlaps = |n: Vec3, [lo, hi]: [Vec3; 2]| { + let (c, across) = (side(n), half - Vec3::new(n.x.abs() * half.x, n.y.abs() * half.y, n.z.abs() * half.z)); + let (a, b) = (c - across, c + across); + [(a.x, b.x, lo.x, hi.x, n.x), (a.y, b.y, lo.y, hi.y, n.y), (a.z, b.z, lo.z, hi.z, n.z)] + .into_iter() + .all(|(a, b, lo, hi, along)| along.abs() > 0.5 || (b.min(hi) - a.max(lo)) > ON_PLANE) + }; + let planes = planes(app); + let n = STANDS_ON + .into_iter() + .find(|n| planes.iter().any(|(q, m, bounds)| m.dot(*n) > 1.0 - 1e-9 && (side(*n) - *q).dot(*m).abs() < ON_PLANE && overlaps(*n, *bounds))) + .unwrap_or(Vec3::Z); + Some((side(n), n)) +} + +fn frame(app: &SolveApp, d: &Dialog) -> Option<(Vec3, Vec3)> { + let Kind::Primitive { cmd, at, .. } = &d.kind else { return None }; + let axis = || d.extra.get("axis").and_then(vec3_of).and_then(|a| a.normalized()).unwrap_or(Vec3::Z); + match (*cmd, at) { + (_, Some((p, Some(n)))) => return Some((*p, *n)), + // A box at a vertex or on a curved face is centred on the point: the marker at its bottom. + ("solid.box", Some((p, None))) => return Some((*p - Vec3::Z * (box_size(app, d).z * 0.5), Vec3::Z)), + // No face to stand on: the axis it is made along, the stored one or the command's. + ("solid.cylinder" | "solid.coil" | "solid.cone", Some((p, None))) => return Some((*p, axis())), + (_, Some((p, None))) => return Some((*p, Vec3::Z)), + (_, None) => {} + } + match *cmd { + "solid.box" => box_frame(app, d), + "solid.cylinder" | "solid.coil" | "solid.cone" => Some((d.extra.get("base").and_then(|v| expr_point(app, v)).unwrap_or(Vec3::ZERO), axis())), + _ => Some((d.extra.get("center").and_then(|v| expr_point(app, v)).unwrap_or(Vec3::ZERO), Vec3::Z)), + } +} + +/// Stand the primitive on the face under the pointer, as a pre-selected face places it: through +/// the Cylinder's Face input (its place follows in the same frame), into a typed Box's corner or +/// centre, else as the picked place; the point pick, which no longer says where it is, is +/// dropped. A Cylinder, Cone or Coil does not take a curved face: it has no one axis there. +fn move_to(app: &SolveApp, d: &mut Dialog, hits: &[Hit], _: usize) -> bool { + let s = &app.session; + let planar = |sel: &Sel| match sel { + Sel::Face { body, index, point } => crate::dialogs::planar_face(s, body, *index).map(|(_, n)| (*point, n)), + _ => None, + }; + if crate::hole_refs::takes(d) { + let Some(to) = face_pick(d, s, hits) else { return false }; + let Some((p, n)) = planar(&to) else { return false }; + // One reference edge holds it on a line at the typed distance, as it holds a hole; where + // the line leaves the face it stays. On another body the edge is let go (below). + let same_body = |a: &Sel, b: Option<&Sel>| matches!((a, b), (Sel::Face { body: x, .. }, Some(Sel::Face { body: y, .. })) if x == y); + if same_body(&to, d.inputs.first().and_then(|inp| inp.items.first())) + && let super::Freedom::Line(_) = crate::hole_refs::freedom(s, d, 0) + { + return crate::hole_refs::drag_to(s, d, 0, p).is_ok(); + } + if let Some(inp) = d.inputs.first_mut() { + inp.items = vec![to]; + } + if let Kind::Primitive { at, .. } = &mut d.kind { + *at = Some((p, Some(n))); + } + // Reference edges the new place cannot be measured from (another body's) are let go. + crate::hole_refs::keep_reachable(s, d); + d.error = None; + return true; + } + let Some((p, n)) = hits.iter().find_map(|h| match h { + Hit::Face { body, index, point } => Some((*point, planar(&Sel::Face { body: body.clone(), index: *index, point: *point }).map(|(_, n)| n))), + _ => None, + }) else { + return false; + }; + let sz = box_size(app, d); + let texts = ["length", "width", "height"].map(|k| match &d.kind { + Kind::Primitive { fields, .. } => fields.iter().find(|f| f.0 == k).map(|f| f.1.clone()).unwrap_or_default(), + _ => String::new(), + }); + let Kind::Primitive { cmd, at, .. } = &mut d.kind else { return false }; + match *cmd { + "solid.cone" | "solid.coil" if n.is_none() => return false, + "solid.box" => { + if at.is_none() { + // Typed fields stand the box square to the world: on a curved face, the way out of + // it at the point; a tilted face or a curved one whose way out there is off the + // axes, which has no outline for it, does not take it. + let n = n.or_else(|| solidcraft_engine::doc::hole_direction_at(&crate::open_meshing::session_world(s), p, &[]).map(|d| -d)); + if n.is_some_and(|n| !STANDS_ON.iter().any(|axis| square_to(n, *axis))) { + return false; + } + crate::primitive_placement::dropped(s, &mut d.extra, p, n.unwrap_or(Vec3::Z), sz, [&texts[0], &texts[1], &texts[2]]); + } else { + *at = Some((p, n)); + } + } + _ => *at = Some((p, n)), + } + // The point pick no longer says where it is. + if let Some(inp) = d.inputs.first_mut() { + inp.items.clear(); + } + d.error = None; + true +} + +/// A pick on the Cylinder's face while one reference edge holds it, with its Face input active: +/// it moves along the edge at the typed distance, as a drag of the marker does and as a hole held +/// so moves on a pick; where the line leaves the face it stays. False when the pick is not that +/// (another face, a vertex, two edges or none, or a pick on the cylinder itself, within its +/// radius of its place), for the dialog to take it as usual. +pub(super) fn pick_held(app: &SolveApp, d: &mut Dialog, sel: &Sel) -> bool { + let s = &app.session; + if !matches!(d.kind, Kind::Primitive { cmd: "solid.cylinder", .. }) || d.active != 0 { + return false; + } + let Sel::Face { body, index, point } = sel else { return false }; + let Some(Sel::Face { body: b, index: i, point: was }) = d.inputs.first().and_then(|inp| inp.items.first()) else { return false }; + if b != body || i != index || was.dist(*point) <= radius(app, d) { + return false; + } + if !matches!(crate::hole_refs::freedom(s, d, 0), super::Freedom::Line(_)) { + return false; + } + !matches!(crate::hole_refs::drag_to(s, d, 0, *point), Err(crate::hole_refs::Stuck::Not)) +} + +/// The primitive's outline on the face: the box's side that stands on it (a face square to an +/// axis), the cylinder's, cone's or coil's base circle, the sphere's widest circle across the +/// face, the torus's outer circle lying flat, as it is made. +fn footprint(app: &SolveApp, d: &Dialog, base: Vec3, n: Vec3) -> Vec { + let Kind::Primitive { cmd, .. } = &d.kind else { return Vec::new() }; + match *cmd { + "solid.box" => { + let sz = box_size(app, d) * 0.5; + if square_to(n, Vec3::Z) { + rect(base, n, Vec3::X, sz.x, sz.y) + } else if square_to(n, Vec3::X) { + rect(base, n, Vec3::Y, sz.y, sz.z) + } else if square_to(n, Vec3::Y) { + rect(base, n, Vec3::X, sz.x, sz.z) + } else { + Vec::new() + } + } + "solid.torus" => circle(base, Vec3::Z, size(app, d, "major") + size(app, d, "minor")), + _ => circle(base, n, radius(app, d)), + } +} + +#[cfg(test)] +#[path = "primitive_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/place_gizmo/primitive_tests.rs b/crates/ui-egui/src/place_gizmo/primitive_tests.rs new file mode 100644 index 00000000000..1126f10043b --- /dev/null +++ b/crates/ui-egui/src/place_gizmo/primitive_tests.rs @@ -0,0 +1,621 @@ +//! The primitives' handle: the marker places a new primitive on a face while its dialog is open, +//! moves one from Edit Feature, and an edit opened again finds it where it was moved. + +use serde_json::json; +use solidcore_record::Vec3; +use solidcraft_engine::Sel; +use solidcraft_engine::doc::FeatureKind; +use solidcraft_engine::geom::prelude::*; + +use super::{footprint, frame, move_to}; +use crate::dialogs::Kind; +use crate::scenario::Harness; +use crate::viewport::Hit; + +/// 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 start(h: &mut Harness, cmd: &str) { + h.step(&json!({"start": cmd})).unwrap(); + h.settle(); +} + +fn drag(h: &mut Harness, to: [f64; 3]) { + assert!(h.at(&json!({"handle": "primitive:position"})).is_ok(), "the marker is published"); + assert!(h.at(&json!({"handle": "primitive:rotate"})).is_err(), "a primitive has no ring"); + h.step(&json!({"drag": [{"handle": "primitive:position"}, {"world": to}], "steps": 12})).unwrap(); + h.settle(); +} + +fn ok(h: &mut Harness) { + h.step(&json!({"click": {"handle": "dialog:OK"}})).unwrap(); + h.settle(); + assert!(h.app.dialog.is_none(), "OK closed the dialog: {:?}", h.app.dialog.as_ref().map(|d| &d.error)); +} + +fn drag_ok(h: &mut Harness, to: [f64; 3]) { + drag(h, to); + ok(h); +} + +fn value(h: &Harness, e: &str) -> f64 { + h.app.session.doc.eval(e, solidcraft_engine::doc::expr::Kind::Length).unwrap() +} + +fn point(h: &Harness, p: &solidcraft_engine::doc::PointExpr) -> Vec3 { + Vec3::new(value(h, &p[0]), value(h, &p[1]), value(h, &p[2])) +} + +/// The open dialog's typed placement under `key` (the corner or centre fields), in mm. +fn typed(h: &Harness, key: &str) -> Vec3 { + let v = h.app.dialog.as_ref().and_then(|d| d.extra.get(key)).and_then(|v| v.as_array()).expect("typed fields"); + let c = |i: usize| value(h, v[i].as_str().expect("a typed field")); + Vec3::new(c(0), c(1), c(2)) +} + +/// The last feature: the primitive just made. +fn last(h: &Harness) -> (String, FeatureKind) { + let f = h.app.session.doc.features.last().expect("a feature"); + (f.name.clone(), f.kind.clone()) +} + +/// Edit Feature on `name` again: the marker stands on screen where `world` is. +fn reopened_at(h: &mut Harness, name: &str, world: [f64; 3]) { + h.step(&json!({"call": "ui.editFeature", "params": {"feature": name}})).unwrap(); + h.settle(); + let at = h.at(&json!({"handle": "primitive:position"})).expect("the marker is published again"); + let expect = h.at(&json!({"world": world})).unwrap(); + assert!((at[0] - expect[0]).hypot(at[1] - expect[1]) < 2.0, "the edit opens with the marker where it was moved: {at:?} {expect:?}"); +} + +#[test] +fn marker_stands_a_new_box_on_the_face_through_its_corner_fields() { + let mut h = plate(); + start(&mut h, "solid.box"); + drag(&mut h, [40.0, 25.0, 10.0]); + let d = h.app.dialog.as_ref().expect("the dialog is open"); + assert!(matches!(d.kind, Kind::Primitive { at: None, .. }), "the typed placement stays: the fields show it"); + assert!(typed(&h, "corner").dist(Vec3::new(30.0, 15.0, 10.0)) < 1e-3, "the corner fields took the drop: {:?}", d.extra.get("corner")); + ok(&mut h); + let (name, kind) = last(&h); + let FeatureKind::Box { corner, .. } = &kind else { panic!("a Box: {kind:?}") }; + // 20 × 20 × 20 by default, centred over the drop and standing on the top. + assert!(point(&h, corner).dist(Vec3::new(30.0, 15.0, 10.0)) < 1e-3, "the corner: {:?}", point(&h, corner)); + reopened_at(&mut h, &name, [40.0, 25.0, 10.0]); +} + +/// Sizes that are expressions stay expressions in the dropped corner, as a pre-selected face's +/// box keeps them (`box_corner`), so the box stays centred on the drop when a parameter they +/// name changes. +#[test] +fn a_dropped_box_keeps_its_size_expressions_so_it_stays_centred_when_they_change() { + let mut h = plate(); + h.app.run("parameters.add", json!({"name": "side", "expression": "20 mm"})).unwrap(); + start(&mut h, "solid.box"); + if let Some(Kind::Primitive { fields, .. }) = h.app.dialog.as_mut().map(|d| &mut d.kind) + && let Some(f) = fields.iter_mut().find(|f| f.0 == "length") + { + f.1 = "side".into(); + } + assert!(drop_on(&mut h, [40.0, 25.0, 10.0])); + assert!(typed(&h, "corner").dist(Vec3::new(30.0, 15.0, 10.0)) < 1e-3, "{:?}", typed(&h, "corner")); + ok(&mut h); + h.app.run("parameters.change", json!({"name": "side", "expression": "40 mm"})).unwrap(); + h.settle(); + let (_, kind) = last(&h); + let FeatureKind::Box { corner, .. } = &kind else { panic!("a Box: {kind:?}") }; + assert!((point(&h, corner).x - 20.0).abs() < 1e-3, "still centred on x = 40: {corner:?}"); +} + +#[test] +fn marker_moves_a_box_placed_by_its_centre_through_its_centre_fields() { + let mut h = plate(); + let made = h.app.run("solid.box", json!({"length": 10, "width": 6, "height": 8, "center": [20, 15, 14], "operation": "join"})).unwrap(); + let name = made["name"].as_str().unwrap().to_string(); + h.settle(); + h.step(&json!({"call": "ui.editFeature", "params": {"feature": name}})).unwrap(); + h.settle(); + // Edit Feature reads the stored corner back; choosing Center keeps the box where it is. + let at = h.at(&json!({"handle": "primitive:position"})).unwrap(); + let expect = h.at(&json!({"world": [20, 15, 10]})).unwrap(); + assert!((at[0] - expect[0]).hypot(at[1] - expect[1]) < 2.0, "the marker stands under the centre, on the bottom: {at:?} {expect:?}"); + { + let d = h.app.dialog.as_mut().expect("a dialog"); + d.extra.remove("corner"); + d.extra.insert("center".into(), json!(["20 mm", "15 mm", "14 mm"])); + } + drag(&mut h, [60.0, 35.0, 10.0]); + let d = h.app.dialog.as_ref().expect("the dialog is open"); + assert!(typed(&h, "center").dist(Vec3::new(60.0, 35.0, 14.0)) < 1e-3, "the centre fields took the drop: {:?}", d.extra.get("center")); + ok(&mut h); + let f = h.app.session.doc.find_feature(&name).expect("the Box is still there"); + let FeatureKind::Box { corner, .. } = &f.kind else { panic!("a Box: {:?}", f.kind) }; + assert!(point(&h, corner).dist(Vec3::new(55.0, 32.0, 10.0)) < 1e-3, "moved: {:?}", point(&h, corner)); + reopened_at(&mut h, &name, [60.0, 35.0, 10.0]); +} + +#[test] +fn a_dropped_box_stands_out_from_a_side_face_and_under_the_underside() { + let s = solidcraft_engine::Session::default(); + let mut extra = serde_json::Map::new(); + let size = Vec3::new(20.0, 10.0, 6.0); + let written = crate::primitive_placement::dropped(&s, &mut extra, Vec3::new(80.0, 25.0, 5.0), Vec3::X, size, [""; 3]); + assert_eq!(written, Some(json!(["80 mm", "20 mm", "2 mm"])), "out from the +X side, centred across it"); + assert_eq!(extra.get("corner"), written.as_ref()); + extra.remove("corner"); + extra.insert("center".into(), json!(["0", "0", "0"])); + let written = crate::primitive_placement::dropped(&s, &mut extra, Vec3::new(40.0, 25.0, 0.0), -Vec3::Z, size, [""; 3]); + assert_eq!(written, Some(json!(["40 mm", "25 mm", "-3 mm"])), "below the underside: the centre half the height down"); + assert!(!extra.contains_key("corner"), "the choice of Center stays"); +} + +/// In a metre design a drop writes the Box's fields in metres, as a picked point does, and what +/// they say is the dropped place to the micrometre: no millimetre lost to the field's unit. +#[test] +fn a_dropped_box_in_a_metre_design_is_written_in_metres_at_the_dropped_place() { + let mut s = solidcraft_engine::Session::default(); + s.execute("document.units", &json!({"units": "m"})).unwrap(); + let mut extra = serde_json::Map::new(); + let written = crate::primitive_placement::dropped(&s, &mut extra, Vec3::new(80.0123, 25.4567, 5.0), Vec3::Z, Vec3::new(20.0, 10.0, 6.0), [""; 3]); + assert_eq!(written, Some(json!(["0.070012 m", "0.020457 m", "0.005 m"])), "centred across the top face, in metres"); + let Some(serde_json::Value::Array(corner)) = extra.get("corner") else { panic!("the corner: {extra:?}") }; + let at: Vec = corner.iter().map(|c| s.doc.eval(c.as_str().unwrap(), solidcraft_engine::doc::expr::Kind::Length).unwrap()).collect(); + for (got, want) in at.iter().zip([70.012, 20.457, 5.0]) { + assert!((got - want).abs() < 1e-6, "{at:?}"); + } +} + +/// A bare size ("2") is in the design's unit for the marker, as OK reads it: in an inch design a +/// 2 in long box dropped at x = 40 mm starts 1 in before it, and its outline is 2 in long. +#[test] +fn a_bare_size_is_read_in_the_design_unit_by_the_marker() { + let mut h = plate(); + h.app.run("document.units", json!({"units": "in"})).unwrap(); + h.settle(); + start(&mut h, "solid.box"); + if let Some(Kind::Primitive { fields, .. }) = h.app.dialog.as_mut().map(|d| &mut d.kind) + && let Some(f) = fields.iter_mut().find(|f| f.0 == "length") + { + f.1 = "2".into(); + } + let size = h.app.dialog.as_ref().map(|d| super::box_size(&h.app, d)).unwrap(); + assert!((size.x - 50.8).abs() < 1e-6, "2 in: {size:?}"); + assert!(drop_on(&mut h, [40.0, 25.0, 10.0])); + assert!((typed(&h, "corner").x - (40.0 - 25.4)).abs() < 1e-3, "{:?}", typed(&h, "corner")); + // A decimal comma and a unitless expression are in the design's unit too, as OK reads them. + for (text, inches) in [("2,5", 2.5), ("2 * 1", 2.0)] { + if let Some(Kind::Primitive { fields, .. }) = h.app.dialog.as_mut().map(|d| &mut d.kind) + && let Some(f) = fields.iter_mut().find(|f| f.0 == "length") + { + f.1 = text.into(); + } + let size = h.app.dialog.as_ref().map(|d| super::box_size(&h.app, d)).unwrap(); + assert!((size.x - inches * 25.4).abs() < 1e-6, "{text}: {size:?}"); + } +} + +/// An empty placement field is 0, as OK sends it: while one is cleared to be retyped the marker +/// stays where the other two put it, for the Centre and the Corner alike. +#[test] +fn an_empty_placement_field_counts_as_zero_for_the_marker() { + let mut h = plate(); + start(&mut h, "solid.box"); + let size = h.app.dialog.as_ref().map(|d| super::box_size(&h.app, d)).unwrap(); + h.app.dialog.as_mut().unwrap().extra.insert("center".into(), json!(["", "100", "200"])); + let (base, _) = place(&h); + assert!(base.dist(Vec3::new(0.0, 100.0, 200.0 - size.z / 2.0)) < 1e-6, "centre with x empty: {base:?}"); + let d = h.app.dialog.as_mut().unwrap(); + d.extra.remove("center"); + d.extra.insert("corner".into(), json!(["300", "", "400"])); + let (base, _) = place(&h); + assert!(base.dist(Vec3::new(300.0 + size.x / 2.0, size.y / 2.0, 400.0)) < 1e-6, "corner with y empty: {base:?}"); +} + +/// A size typed as a bare expression ("2 * 1") is in the design's unit, as OK reads it: in an +/// inch design the corner a drop writes is 1 in back from the point, not 1 mm. +#[test] +fn a_dropped_box_reads_a_bare_size_expression_in_the_design_unit() { + let mut s = solidcraft_engine::Session::default(); + s.execute("document.units", &json!({"units": "in"})).unwrap(); + let mut extra = serde_json::Map::new(); + crate::primitive_placement::dropped(&s, &mut extra, Vec3::new(50.8, 50.8, 0.0), Vec3::Z, Vec3::new(50.8, 50.8, 25.4), ["2 * 1", "2 * 1", "1"]); + let Some(serde_json::Value::Array(corner)) = extra.get("corner") else { panic!("the corner: {extra:?}") }; + let x = s.doc.eval(corner[0].as_str().unwrap(), solidcraft_engine::doc::expr::Kind::Length).unwrap(); + assert!((x - 25.4).abs() < 1e-6, "1 in back from 2 in: {x} mm from {corner:?}"); +} + +#[test] +fn marker_stands_a_new_cylinder_on_the_face_through_its_face_input() { + let mut h = plate(); + start(&mut h, "solid.cylinder"); + // Nothing was pre-selected: the marker starts where the command would put it, the origin. + drag(&mut h, [40.0, 25.0, 10.0]); + let d = h.app.dialog.as_ref().expect("the dialog is still open"); + match d.inputs[0].items.as_slice() { + [Sel::Face { point, .. }] => assert!(point.dist(Vec3::new(40.0, 25.0, 10.0)) < 0.5, "the Face input: {point:?}"), + other => panic!("one face place in the Face input, not {other:?}"), + } + let Kind::Primitive { at, .. } = &d.kind else { panic!("a primitive") }; + assert!(at.is_some_and(|(p, n)| p.dist(Vec3::new(40.0, 25.0, 10.0)) < 0.5 && n == Some(Vec3::Z)), "it stands where the input is: {at:?}"); + ok(&mut h); + let (name, kind) = last(&h); + let FeatureKind::Cylinder { base, axis, .. } = &kind else { panic!("a Cylinder: {kind:?}") }; + assert!(point(&h, base).dist(Vec3::new(40.0, 25.0, 10.0)) < 0.5, "stands where it was dropped: {:?}", point(&h, base)); + assert!(axis.0.dist(Vec3::Z) < 1e-9, "along the face normal: {:?}", axis.0); + reopened_at(&mut h, &name, [40.0, 25.0, 10.0]); +} + +#[test] +fn dragging_a_cylinder_with_a_reference_edge_keeps_its_typed_distance() { + let mut h = plate(); + start(&mut h, "solid.cylinder"); + h.step(&json!({"click": {"world": [30, 25, 10]}})).unwrap(); + h.settle(); + h.step(&json!({"click": {"world": [0, 20, 10]}})).unwrap(); + h.settle(); + let distance = |h: &Harness| match &h.app.dialog.as_ref().expect("a dialog").kind { + Kind::Primitive { refs, .. } => value(h, &refs.distance[0]), + other => panic!("a primitive: {other:?}"), + }; + assert!((distance(&h) - 30.0).abs() < 0.5, "measured from the left edge: {}", distance(&h)); + // The left edge holds it at x = 30, as it holds a hole: the drag moves it along the edge only. + drag(&mut h, [50.0, 30.0, 10.0]); + assert!((distance(&h) - 30.0).abs() < 0.5, "the typed distance stays: {}", distance(&h)); + ok(&mut h); + let (_, kind) = last(&h); + let FeatureKind::Cylinder { base, references, .. } = &kind else { panic!("a Cylinder: {kind:?}") }; + assert_eq!(references.len(), 1); + let b = point(&h, base); + assert!((b.x - 30.0).abs() < 0.5 && (b.y - 30.0).abs() < 0.5, "along the edge to y = 30: {b:?}"); +} + +#[test] +fn a_cylinder_held_by_one_edge_keeps_its_typed_distance_when_its_face_is_picked_again() { + let mut h = plate(); + start(&mut h, "solid.cylinder"); + h.step(&json!({"click": {"world": [30, 25, 10]}})).unwrap(); + h.settle(); + h.step(&json!({"click": {"world": [0, 20, 10]}})).unwrap(); + h.settle(); + let distance = |h: &Harness| match &h.app.dialog.as_ref().expect("a dialog").kind { + Kind::Primitive { refs, .. } => value(h, &refs.distance[0]), + other => panic!("a primitive: {other:?}"), + }; + assert!((distance(&h) - 30.0).abs() < 0.5, "measured from the left edge: {}", distance(&h)); + // A pick elsewhere on the face, as a drag of the marker does, moves it along the edge only. + h.step(&json!({"click": {"handle": "dialog:Face"}})).unwrap(); + h.step(&json!({"click": {"world": [50, 35, 10]}})).unwrap(); + h.settle(); + assert!((distance(&h) - 30.0).abs() < 0.5, "the typed distance stays: {}", distance(&h)); + let at = match &h.app.dialog.as_ref().expect("a dialog").kind { + Kind::Primitive { at: Some((p, _)), .. } => *p, + other => panic!("a placed cylinder: {other:?}"), + }; + assert!((at.x - 30.0).abs() < 0.5 && (at.y - 35.0).abs() < 0.5, "along the edge to y = 35: {at:?}"); + // A pick on another face of the plate is the dialog's, as with the handles off: it moves there. + let top = match h.app.dialog.as_ref().and_then(|d| d.inputs[0].items.first()) { + Some(Sel::Face { index, .. }) => *index, + other => panic!("a face pick: {other:?}"), + }; + h.step(&json!({"click": {"handle": "dialog:Face"}})).unwrap(); + assert!(drop_on_pick(&mut h, [80.0, 25.0, 5.0]), "the side face is picked"); + match h.app.dialog.as_ref().and_then(|d| d.inputs[0].items.first()) { + Some(Sel::Face { index, point, .. }) => assert!(*index != top && (point.x - 80.0).abs() < 1e-6, "on the side face: {index} {point:?}"), + other => panic!("a face pick: {other:?}"), + } +} + +/// The open dialog takes a viewport pick of the face at `p`, the shared handles first, as a click does. +fn drop_on_pick(h: &mut Harness, p: [f64; 3]) -> bool { + let Some(sel) = crate::dialogs::face_sel(&h.app.session, Vec3::new(p[0], p[1], p[2])) else { return false }; + let mut d = h.app.dialog.take().expect("a dialog"); + if !crate::place_gizmo::pick_held(&h.app, &mut d, &sel) { + d.pick(&h.app.session, sel); + } + h.app.dialog = Some(d); + h.settle(); + true +} + +#[test] +fn marker_stands_a_new_cone_on_the_face() { + let mut h = plate(); + start(&mut h, "solid.cone"); + drag_ok(&mut h, [40.0, 25.0, 10.0]); + let (name, kind) = last(&h); + let FeatureKind::Cone { base, axis, .. } = &kind else { panic!("a Cone: {kind:?}") }; + assert!(point(&h, base).dist(Vec3::new(40.0, 25.0, 10.0)) < 0.5, "{:?}", point(&h, base)); + assert!(axis.0.dist(Vec3::Z) < 1e-9, "{:?}", axis.0); + reopened_at(&mut h, &name, [40.0, 25.0, 10.0]); +} + +#[test] +fn marker_moves_a_sphere_from_edit_feature() { + let mut h = plate(); + let made = h.app.run("solid.sphere", json!({"radius": 4, "center": [15, 15, 10], "operation": "join"})).unwrap(); + let name = made["name"].as_str().unwrap().to_string(); + h.settle(); + reopened_at(&mut h, &name, [15.0, 15.0, 10.0]); + drag_ok(&mut h, [60.0, 35.0, 10.0]); + let f = h.app.session.doc.find_feature(&name).expect("the Sphere is still there"); + let FeatureKind::Sphere { center, .. } = &f.kind else { panic!("a Sphere: {:?}", f.kind) }; + assert!(point(&h, center).dist(Vec3::new(60.0, 35.0, 10.0)) < 0.5, "moved: {:?}", point(&h, center)); + h.step(&json!({"expect": {"errors": 0, "bodies": 1}})).unwrap(); + reopened_at(&mut h, &name, [60.0, 35.0, 10.0]); +} + +#[test] +fn marker_stands_a_new_torus_on_the_face() { + let mut h = plate(); + start(&mut h, "solid.torus"); + // Off the plate's middle: there the torus (25 mm out) touches both long sides, and a drop a + // micrometre off it is a near-tangent join the kernel refuses. + drag_ok(&mut h, [40.0, 20.0, 10.0]); + let (name, kind) = last(&h); + let FeatureKind::Torus { center, .. } = &kind else { panic!("a Torus: {kind:?}") }; + assert!(point(&h, center).dist(Vec3::new(40.0, 20.0, 10.0)) < 0.5, "{:?}", point(&h, center)); + reopened_at(&mut h, &name, [40.0, 20.0, 10.0]); +} + +#[test] +fn marker_stands_a_new_coil_on_the_face() { + let mut h = plate(); + start(&mut h, "solid.coil"); + drag_ok(&mut h, [40.0, 25.0, 10.0]); + let (name, kind) = last(&h); + let FeatureKind::Coil { base, axis, .. } = &kind else { panic!("a Coil: {kind:?}") }; + assert!(point(&h, base).dist(Vec3::new(40.0, 25.0, 10.0)) < 0.5, "{:?}", point(&h, base)); + assert!(axis.0.dist(Vec3::Z) < 1e-9, "{:?}", axis.0); + reopened_at(&mut h, &name, [40.0, 25.0, 10.0]); +} + +#[test] +fn a_coil_with_a_sketch_profile_has_no_marker() { + let mut h = plate(); + // A circle on the plate's top: a profile the Coil can sweep. + let sketch = h.app.run("sketch.create", json!({"plane": {"face": [40, 25, 10]}})).unwrap()["sketch"].as_u64().unwrap(); + h.app.run("sketch.circle.center", json!({"center": [60, 25], "radius": 3})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.settle(); + start(&mut h, "solid.coil"); + assert!(h.at(&json!({"handle": "primitive:position"})).is_ok(), "a coil of its own section has the marker"); + h.app.dialog.as_mut().expect("a dialog").inputs[0].items = vec![Sel::Profile { sketch, index: 0 }]; + h.frames(2); + assert!(h.at(&json!({"handle": "primitive:position"})).is_err(), "with a profile picked, no marker"); + let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["sketch"], json!(sketch), "the coil is made from the profile: {:?}", commands[0].1); +} + +/// With the preference off (the default) no primitive's dialog shows the marker. +#[test] +fn with_the_preference_off_no_primitive_has_a_marker() { + let mut h = plate(); + h.app.preferences.placement_handles = false; + for cmd in ["solid.box", "solid.cone", "solid.coil", "solid.cylinder", "solid.sphere", "solid.torus"] { + start(&mut h, cmd); + assert!(h.app.dialog.is_some(), "{cmd}: a dialog"); + assert!(h.at(&json!({"handle": "primitive:position"})).is_err(), "{cmd}: no marker is published"); + h.app.dialog = None; + } +} + +/// The open dialog's marker place and the direction the solid grows from it. +fn place(h: &Harness) -> (Vec3, Vec3) { + frame(&h.app, h.app.dialog.as_ref().expect("a dialog")).expect("a place") +} + +/// The open dialog's footprint at its marker. +fn outline(h: &Harness) -> Vec { + let (base, n) = place(h); + footprint(&h.app, h.app.dialog.as_ref().expect("a dialog"), base, n) +} + +/// The marker dropped on the face at `p`, as one frame of a drag does; whether it took it. The +/// frame after is not run, so the place read next is the one the drop itself left. +fn drop_on(h: &mut Harness, p: [f64; 3]) -> bool { + let Some(Sel::Face { body, index, point }) = crate::dialogs::face_sel(&h.app.session, Vec3::new(p[0], p[1], p[2])) else { + panic!("a face at {p:?}") + }; + let mut d = h.app.dialog.take().expect("a dialog"); + let took = move_to(&h.app, &mut d, &[Hit::Face { body, index, point }], 0); + h.app.dialog = Some(d); + took +} + +#[test] +fn a_box_dropped_on_a_side_face_stands_on_it_and_reopens_there() { + let mut h = plate(); + start(&mut h, "solid.box"); + assert!(drop_on(&mut h, [80.0, 25.0, 5.0]), "the side face takes the box"); + let (base, n) = place(&h); + assert!(base.dist(Vec3::new(80.0, 25.0, 5.0)) < 1e-3 && n.dist(Vec3::X) < 1e-9, "on the side face: {base:?} {n:?}"); + assert!(outline(&h).iter().all(|p| (p.x - 80.0).abs() < 1e-6), "the outline lies on the side face: {:?}", outline(&h)); + ok(&mut h); + let (name, _) = last(&h); + h.step(&json!({"call": "ui.editFeature", "params": {"feature": name}})).unwrap(); + h.settle(); + let (base, n) = place(&h); + assert!(base.dist(Vec3::new(80.0, 25.0, 5.0)) < 1e-3 && n.dist(Vec3::X) < 1e-9, "reopened on the side face: {base:?} {n:?}"); +} + +#[test] +fn a_side_drop_does_not_follow_another_box_with_the_same_fields() { + let mut h = plate(); + start(&mut h, "solid.box"); + assert!(drop_on(&mut h, [80.0, 25.0, 5.0])); + let typed = h.app.dialog.as_ref().unwrap().extra.get("corner").cloned().expect("the corner fields"); + // Another design with no plate: the same fields stand the box on nothing, so its marker is + // under it. + let mut other = Harness::new(); + other.app.preferences.placement_handles = true; + start(&mut other, "solid.box"); + other.app.dialog.as_mut().unwrap().extra.insert("corner".into(), typed); + let (base, n) = place(&other); + assert!(n.dist(Vec3::Z) < 1e-9 && base.dist(Vec3::new(90.0, 25.0, -5.0)) < 1e-3, "the middle of its bottom: {base:?} {n:?}"); +} + +#[test] +fn a_typed_box_beside_a_far_face_in_the_same_plane_does_not_stand_on_it() { + let mut h = plate(); + start(&mut h, "solid.box"); + // The box's left side is in the plane of the plate's right side (x = 80), 150 mm away from it. + let fields = json!(["80", "200", "0"]); + h.app.dialog.as_mut().unwrap().extra.insert("corner".into(), fields); + let size = h.app.dialog.as_ref().map(|d| super::box_size(&h.app, d)).unwrap(); + let (base, n) = place(&h); + let bottom = Vec3::new(80.0 + size.x / 2.0, 200.0 + size.y / 2.0, 0.0); + assert!(n.dist(Vec3::Z) < 1e-9 && base.dist(bottom) < 1e-6, "the middle of its bottom, not the far face's side: {base:?} {n:?}"); +} + +#[test] +fn a_typed_box_dropped_on_a_round_wall_stands_out_from_it() { + let mut h = plate(); + h.app.run("solid.cylinder", json!({"radius": 10, "height": 20, "base": [40, 25, 10], "operation": "new"})).unwrap(); + h.settle(); + start(&mut h, "solid.box"); + let size = h.app.dialog.as_ref().map(|d| super::box_size(&h.app, d)).unwrap(); + assert!(drop_on(&mut h, [50.0, 25.0, 20.0]), "the wall takes the box"); + let corner = typed(&h, "corner"); + assert!( + (corner.x - 50.0).abs() < 1e-3 && (corner.z - (20.0 - size.z / 2.0)).abs() < 1e-3, + "out from the wall along +X, centred on the point: {corner:?}" + ); + // Off the world axes the wall's way out is tilted: a typed box, square to the world, does not + // take it (as a tilted face does not), rather than stand buried on +Z at the point. + let before = typed(&h, "corner"); + let a = std::f64::consts::FRAC_PI_4; + assert!(!drop_on(&mut h, [40.0 + 10.0 * a.cos(), 25.0 + 10.0 * a.sin(), 20.0]), "45 degrees round the wall does not take it"); + assert!(typed(&h, "corner").dist(before) < 1e-9, "the box stays where it was: {:?}", typed(&h, "corner")); +} + +#[test] +fn a_typed_box_is_not_dropped_on_a_tilted_face() { + let mut h = plate(); + h.app.run("solid.chamfer", json!({"edges": [[80, 25, 10]], "distance": 5})).unwrap(); + h.settle(); + start(&mut h, "solid.box"); + let before = h.app.dialog.as_ref().unwrap().extra.clone(); + assert!(!drop_on(&mut h, [77.5, 25.0, 7.5]), "a tilted face has no outline to stand the box on"); + assert_eq!(h.app.dialog.as_ref().unwrap().extra, before, "the fields are left alone"); +} + +#[test] +fn a_cylinder_dropped_on_another_body_lets_go_of_the_edges_it_cannot_reach() { + let mut h = plate(); + h.app.run("solid.box", json!({"length": 40, "width": 50, "height": 10, "corner": [120, 0, 0], "operation": "new"})).unwrap(); + h.settle(); + start(&mut h, "solid.cylinder"); + h.step(&json!({"click": {"world": [30, 25, 10]}})).unwrap(); + h.settle(); + h.step(&json!({"click": {"world": [0, 20, 10]}})).unwrap(); + h.settle(); + drag_ok(&mut h, [140.0, 25.0, 10.0]); + let (_, kind) = last(&h); + let FeatureKind::Cylinder { base, references, .. } = &kind else { panic!("a Cylinder: {kind:?}") }; + assert!(references.is_empty(), "the plate's edge is let go: {references:?}"); + assert!(point(&h, base).dist(Vec3::new(140.0, 25.0, 10.0)) < 0.5, "{:?}", point(&h, base)); +} + +#[test] +fn a_box_on_a_vertex_has_its_marker_and_outline_at_its_bottom() { + let mut h = plate(); + h.app.session.selection = vec![Sel::Vertex { body: "Body1".into(), point: Vec3::new(80.0, 50.0, 10.0) }]; + start(&mut h, "solid.box"); + // The box is centred on the vertex (20 high), so its bottom is 10 below it. + let (base, n) = place(&h); + assert!(base.dist(Vec3::new(80.0, 50.0, 0.0)) < 1e-6 && n.dist(Vec3::Z) < 1e-9, "{base:?} {n:?}"); + assert!(outline(&h).iter().all(|p| p.z.abs() < 1e-6), "the outline is the box's bottom: {:?}", outline(&h)); +} + +#[test] +fn a_box_sphere_or_torus_moved_by_its_marker_drops_its_point_pick() { + for cmd in ["solid.box", "solid.sphere", "solid.torus"] { + let mut h = plate(); + start(&mut h, cmd); + { + let s = &h.app.session; + let d = h.app.dialog.as_mut().unwrap(); + d.pick(s, Sel::Vertex { body: "Body1".into(), point: Vec3::new(0.0, 0.0, 10.0) }); + } + assert!(!h.app.dialog.as_ref().unwrap().inputs[0].items.is_empty(), "{cmd}: the point is picked"); + assert!(drop_on(&mut h, [40.0, 25.0, 10.0])); + let d = h.app.dialog.as_ref().unwrap(); + assert!(d.inputs[0].items.is_empty(), "{cmd}: the pick no longer says where it is: {:?}", d.inputs[0].items); + assert!(crate::canvas::anchor(&h.app, d).is_none(), "{cmd}: nothing on the canvas stays at the old point"); + } +} + +#[test] +fn a_torus_dropped_on_a_side_face_is_outlined_flat_as_it_is_made() { + let mut h = plate(); + start(&mut h, "solid.torus"); + assert!(drop_on(&mut h, [80.0, 25.0, 5.0])); + let o = outline(&h); + assert!(!o.is_empty() && o.iter().all(|p| (p.z - 5.0).abs() < 1e-6), "flat about its centre: {o:?}"); + let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert!(commands[0].1.get("axis").is_none(), "the torus has no axis to tilt: {:?}", commands[0].1); +} + +#[test] +fn a_cylinder_follows_its_marker_in_the_same_frame() { + let mut h = plate(); + start(&mut h, "solid.cylinder"); + assert!(drop_on(&mut h, [40.0, 25.0, 10.0])); + let (base, n) = place(&h); + assert!(base.dist(Vec3::new(40.0, 25.0, 10.0)) < 0.5 && n.dist(Vec3::Z) < 1e-9, "no frame behind the pointer: {base:?}"); +} + +#[test] +fn a_cone_coil_or_cylinder_is_not_dropped_on_a_curved_face() { + let mut h = plate(); + h.app.run("solid.cylinder", json!({"radius": 10, "height": 20, "base": [40, 25, 10], "operation": "new"})).unwrap(); + h.settle(); + for cmd in ["solid.cone", "solid.coil", "solid.cylinder"] { + start(&mut h, cmd); + let before = place(&h); + assert!(!drop_on(&mut h, [50.0, 25.0, 20.0]), "{cmd}: a curved face has no one axis to stand on"); + assert_eq!(place(&h), before, "{cmd}: it stays where it was"); + h.app.dialog = None; + } +} + +#[test] +fn a_tilted_cone_placed_at_a_point_keeps_its_axis_for_the_marker() { + let mut h = plate(); + let made = h + .app + .run("solid.cone", json!({"radius": 5, "top_radius": 0, "height": 10, "base": [20, 20, 30], "axis": [1, 0, 0], "operation": "new"})) + .unwrap(); + let name = made["name"].as_str().unwrap().to_string(); + h.settle(); + h.step(&json!({"call": "ui.editFeature", "params": {"feature": name}})).unwrap(); + h.settle(); + if let Some(Kind::Primitive { at, .. }) = h.app.dialog.as_mut().map(|d| &mut d.kind) { + *at = Some((Vec3::new(20.0, 20.0, 30.0), None)); + } + let (_, n) = place(&h); + assert!(n.dist(Vec3::X) < 1e-9, "the axis the cone is made along: {n:?}"); + assert!(outline(&h).iter().all(|p| (p.x - 20.0).abs() < 1e-6), "the base circle across that axis"); +} + +#[test] +fn a_cylinder_with_a_reference_edge_reopens_with_its_marker_and_outline_on_its_face() { + let mut h = plate(); + let made = h + .app + .run("solid.cylinder", json!({"radius": 4, "height": 8, "base": [30, 25, 10], "axis": [0, 0, 1], "references": [{"edge": [0, 20, 10], "distance": "30 mm"}], "operation": "join"})) + .unwrap(); + let name = made["name"].as_str().unwrap().to_string(); + h.settle(); + reopened_at(&mut h, &name, [30.0, 25.0, 10.0]); + let o = outline(&h); + assert!(!o.is_empty() && o.iter().all(|p| (p.z - 10.0).abs() < 1e-6 && (p.dist(Vec3::new(30.0, 25.0, 10.0)) - 4.0).abs() < 1e-6), "{o:?}"); +} diff --git a/crates/ui-egui/src/place_gizmo/rest.rs b/crates/ui-egui/src/place_gizmo/rest.rs index 33f4e61de40..fd662f9cf9b 100644 --- a/crates/ui-egui/src/place_gizmo/rest.rs +++ b/crates/ui-egui/src/place_gizmo/rest.rs @@ -3,7 +3,7 @@ use solidcore_record::Vec3; -use super::{Spec, Turn, angle_of, circle, dir_at, len, pt, pulled, rect, vec3_of}; +use super::{PlaceSource, 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; @@ -14,8 +14,7 @@ pub(super) static SPEC: Spec = Spec { snap_commands: &["plastic.rest"], move_tip: "Drag to move the rest across the model. It snaps to sketch points on the face.", many: false, - places: |app, d| super::one(crate::dialogs_plastic::handle_frame(app, d)), - move_to: |app, d, hits, _| crate::dialogs_plastic::handle_move(app, d, hits), + place: PlaceSource::Input(0), click: None, footprint, freedom: super::anywhere, diff --git a/crates/ui-egui/src/place_gizmo/snap_fit.rs b/crates/ui-egui/src/place_gizmo/snap_fit.rs index 0aecaa793b1..1ce4fcef8a8 100644 --- a/crates/ui-egui/src/place_gizmo/snap_fit.rs +++ b/crates/ui-egui/src/place_gizmo/snap_fit.rs @@ -4,7 +4,7 @@ use solidcore_record::Vec3; -use super::{Spec, Turn, angle_of, len, rect}; +use super::{PlaceSource, Spec, Turn, angle_of, len, rect}; use crate::SolveApp; use crate::dialogs::{Dialog, Kind}; use crate::dialogs_plastic::{Pl, hook_dirs}; @@ -15,8 +15,7 @@ pub(super) static SPEC: Spec = Spec { snap_commands: &["plastic.snap_fit"], move_tip: "Drag to move the snap fit across the model. It snaps to sketch points on the face.", many: false, - places: |app, d| super::one(crate::dialogs_plastic::handle_frame(app, d)), - move_to: |app, d, hits, _| crate::dialogs_plastic::handle_move(app, d, hits), + place: PlaceSource::Input(0), click: None, footprint, freedom: super::anywhere, diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index e697d045cc3..f49b5f825d2 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -1397,9 +1397,11 @@ preference_settings! { hole_group: bool = false, PAGE_TOOLS => check_id("prefs.design_tools.hole_group"); /// 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. + /// Handles on the preview of a feature placed on a face (Rest, Boss, Snap Fit, and the Box, + /// Cylinder, Cone, Sphere, Torus and Coil): a marker that drags it across the model and, where + /// it can turn in the face, a ring that turns it. Off by default: a Rest, Boss or Snap Fit is + /// then placed by its click only, as before, and its Position input takes faces only; a + /// primitive by its fields, its inputs or the selection it opened with. placement_handles: bool = false, PAGE_TOOLS => check_tr("ui.placement_handles"); /// The files a design names (linked designs, font files) may be on any network location, for /// organisations that keep their designs on file servers. Off (the default): only on the diff --git a/crates/ui-egui/src/primitive_placement.rs b/crates/ui-egui/src/primitive_placement.rs index dbbb9b20705..d7c5645f5fb 100644 --- a/crates/ui-egui/src/primitive_placement.rs +++ b/crates/ui-egui/src/primitive_placement.rs @@ -14,7 +14,7 @@ use serde_json::{Map, Value, json}; use solidcore_record::Vec3; use solidcraft_engine::Session; use solidcraft_engine::doc::expr::Kind as ValueKind; -use solidcraft_engine::geom::PlaneGeom as _; +use solidcraft_engine::geom::prelude::*; use crate::selection::{EDGES, EXTERNAL_POINTS, FACES, ORIGIN, POINTS, SelInput, VERTICES}; use crate::ui_kit::{self, choice_row, expr_row}; @@ -101,9 +101,10 @@ pub(crate) fn rows(ui: &mut egui::Ui, s: &Session, cmd: &str, extra: &mut Map String { let v = (v * 1e6).round() / 1e6; // No "-0 mm". @@ -138,6 +139,51 @@ pub(crate) fn picked(s: &Session, cmd: &str, at: &mut Option<(Vec3, Option *at = None; } +/// A Box dropped by its placement marker at `p` on a face with normal `n`: the current placement +/// (the corner or the centre) written so the box stands on the face, centred on `p` across it +/// (only centred on `p` on a face square to no axis), as a pre-selected face places it. `size` is +/// the box's length, width and height (mm), `texts` the same as typed: a size that is an +/// expression stays one in the place (as `dialogs::box_corner` keeps it), so the box keeps +/// standing there when the size changes. Returns the point written, in the design's length unit +/// as the fields show it. +pub(crate) fn dropped(s: &Session, extra: &mut Map, p: Vec3, n: Vec3, size: Vec3, texts: [&str; 3]) -> Option { + if !p.is_finite() { + return None; + } + let index = keys("solid.box").iter().position(|k| extra.contains_key(*k)).unwrap_or(0); + // How much of the size lies behind `p` along each axis: for the corner none (or all) along + // the face's normal and half across it; the centre is half a size further on. + let behind = |axis: Vec3| { + let corner = match n.dot(axis) { + d if d > 1.0 - 1e-9 => 0.0, + d if d < -1.0 + 1e-9 => 1.0, + _ => 0.5, + }; + if index == 0 { corner } else { corner - 0.5 } + }; + // A drop is only as exact as the pointer: to the micrometre, so the fields read 45 mm, not + // 44.999991 mm. + let um = |v: f64| coord(s, (v * 1e3).round() / 1e3); + let at = |c: f64, size: f64, text: &str, axis: Vec3| { + let f = behind(axis); + // A size typed as `l = 20` is placed by its value: `l` exists only once the box does. + let text = solidcraft_engine::doc::expr::definition(text).map_or(text, |(_, rhs)| rhs).trim(); + if f == 0.0 || text.is_empty() || solidcraft_engine::doc::expr::is_literal(text) { + return um(c - f * size); + } + // A bare number in it has the design's unit, as OK reads the size. + let text = crate::length_input::expression(&s.doc, text, ValueKind::Length); + match f { + 1.0 => format!("{} - ({text})", um(c)), + 0.5 => format!("{} - ({text}) / 2", um(c)), + _ => format!("{} + ({text}) / 2", um(c)), + } + }; + let coords = [at(p.x, size.x, texts[0], Vec3::X), at(p.y, size.y, texts[1], Vec3::Y), at(p.z, size.z, texts[2], Vec3::Z)]; + store("solid.box", extra, index, &coords); + Some(json!(coords)) +} + /// The typed placement into the command's parameters: a bare number typed into a field is in the /// design's units (as in the size fields), an empty field is 0, and a stored number is kept. pub(crate) fn params(s: &Session, cmd: &str, extra: &Map, p: &mut Map) { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 51aed3b81f8..e637afd9dd7 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -3671,7 +3671,8 @@ pub(crate) fn dialog_pick(app: &mut SolveApp, hit: &Hit, sel: Sel) { let Some(mut d) = app.dialog.take() else { return }; // With several holes on a face (Preferences), a Single hole's pick adds a hole or takes one // out; with holes moving by clicking, a Single hole picked again on its face moves there. - let picked = if crate::hole_place::pick_several(app, &mut d, &sel) { + // With Placement handles on, a Cylinder held by one reference edge moves along it on a pick. + let picked = if crate::place_gizmo::pick_held(app, &mut d, &sel) || crate::hole_place::pick_several(app, &mut d, &sel) { crate::hole_place::PickMove::Moved } else if app.preferences.hole_moves { crate::hole_place::pick_moves(&mut d, &app.session, &sel) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 492dc1069ee..a5176a9bcdb 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -822,7 +822,7 @@ no box selection. | `ui.dialogInput` | `index` | what clicking an input's Select chip does: picks go to that input | | `ui.at` | `world: [x,y,z]` \| `sketch: [x,y]` \| `plane: "XY"` \| `axis: "Z"` \| `dimension: "d1"` (its value text) \| `handle: "arrow"` (a manipulator handle, see `scenario::publish_handle`) | the screen point (a scenario step's target; see `crates/ui-egui/src/scenario.rs`) | | `ui.pick` | `pixels?: [[x,y]…]`, `rays?: [{origin, dir}…]`, `frame?: "window"\|"model"`, `width?`, `height?`, `edges?` (default true), `edge_px?` (default 6), `all?`, `include_ghosted?` | read-only geometry under each pixel or ray (#6304): one entry per input, `null` where nothing is hit — body, face index, exact world `point` and outward `normal`, `depth`, `occurrence`/`component` for placed parts, `edge`/`vertex` within `edge_px` of a pixel, `section_cap: true` on a cut face. `window` pixels are physical pixels of a window screenshot; `model` pixels are pixels of a `ui.render` of `width`×`height` (default 960×600), so it works headless. As `view.pick` through `engine.execute`/`engine.batch`. See `crates/ui-egui/src/view_pick.rs` | -| `ui.handles` | `prefix?` | the handles drawn last frame, `[{name, x, y}]`: toolbar buttons and drop-down items `toolbar:` (the button alone: `button:`; a drop-down row: `dropdown:`, highlighted `dropdown_hot:`, its pin `dropdown_pin:`; Customize Toolbar's check boxes `customize:`), ribbon tabs `tab:` (MODEL, SURFACE, ASSEMBLE, INSERT, INSPECT, MANAGE, VIEW, SHEET METAL, WELDMENTS; contextual SKETCH; workspace RENDER), the toolbar menu button `ribbon:add_tab`, the hint when every tab is hidden `ribbon:tabs_hidden`, Preferences tab check boxes `prefs:toolbar_tab:`, panel labels `panel::` (also `ribbon:section::
`), document overflow list `tab:overflow`, workspace column `ribbon:workspace`, command-search launcher `ribbon:search`, browser rows `row: