Skip to content

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

Box dialog: place the box by its corner or centre (#5638) (#6248)

HiroKenEz8962ae10e77f
diff --git a/assets/locales/pending/box-dialog-placement.json b/assets/locales/pending/box-dialog-placement.json
new file mode 100644
index 0000000000..4f5220ae6d
--- /dev/null
+++ b/assets/locales/pending/box-dialog-placement.json
@@ -0,0 +1,9 @@
+{
+ "en": { "Base Center": "Base Center" },
+ "en-GB": { "Base Center": "Base Centre" },
+ "ar": { "Base Center": "مركز القاعدة" },
+ "he": { "Base Center": "מרכז הבסיס" },
+ "ja": { "Base Center": "底面の中心" },
+ "vi": { "Base Center": "Tâm đáy" },
+ "zh": { "Base Center": "底面中心" }
+}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index be47574348..0cf0bdc37e 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -933,7 +933,7 @@ impl Dialog {
operation: 0,
at: None,
},
- vec![],
+ crate::primitive_placement::inputs("solid.box"),
),
"solid.cylinder" => Dialog::new(
Kind::Primitive {
@@ -1567,6 +1567,10 @@ impl Dialog {
self.error = None;
self.sync_thread(s);
self.sync_material(s);
+ if let Kind::Primitive { cmd, at, .. } = &mut self.kind {
+ let picked = self.inputs.get(self.active).and_then(|i| i.items.first());
+ crate::primitive_placement::picked(s, cmd, at, &mut self.extra, picked);
+ }
}
/// Box selection result: replace (or add to) the active input.
@@ -3435,7 +3439,7 @@ pub(crate) fn length_default(s: &Session, number: &str) -> String {
/// A feature's length as its edit field shows it. A bare number is kept in millimetres: where the
/// design reads bare numbers in another unit, the field says "mm" (as the configuration table
/// does), so OK keeps the size. Anything else shows as stored.
-fn stored_length(s: &Session, e: &str) -> String {
+pub(crate) fn stored_length(s: &Session, e: &str) -> String {
if s.doc.with_design_unit(e, ValueKind::Length) == e { e.to_string() } else { format!("{} mm", e.trim()) }
}
@@ -4498,6 +4502,8 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, S
p.insert("center".into(), pt(point));
}
}
+ } else {
+ crate::primitive_placement::params(s, cmd, &d.extra, &mut p);
}
p.insert("operation".into(), json!(OPS.get(*operation).copied().unwrap_or("new")));
(cmd, Value::Object(p))
diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs
index 513cda6009..708b7c345a 100644
--- a/crates/ui-egui/src/dialogs_dense.rs
+++ b/crates/ui-egui/src/dialogs_dense.rs
@@ -804,6 +804,9 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo
if *cmd == "solid.coil" {
enter |= coil_rows(ui, &mut d.extra);
}
+ if at.is_none() {
+ enter |= crate::primitive_placement::rows(ui, &app.session, cmd, &mut d.extra);
+ }
if let Some((p, _)) = *at {
form_row(ui, "Position", |ui| {
ui.horizontal(|ui| {
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index e774ea0dec..02c794effc 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -197,6 +197,7 @@ pub mod prefs_notice;
#[cfg(test)]
mod preselect_tests;
pub mod preview;
+mod primitive_placement;
#[cfg(test)]
mod primitive_units_tests;
pub mod recovery_ui;
diff --git a/crates/ui-egui/src/primitive_placement.rs b/crates/ui-egui/src/primitive_placement.rs
new file mode 100644
index 0000000000..053d399a84
--- /dev/null
+++ b/crates/ui-egui/src/primitive_placement.rs
@@ -0,0 +1,133 @@
+//! Where a Box or Cylinder goes, typed in its dialog (#5638). The Box is placed by its corner
+//! or its centre, the Cylinder by the centre of its base, as X, Y and Z fields that take
+//! expressions and units like the size fields. A point picked in the view (a vertex, a point on
+//! an edge or face, the origin) fills the Box's fields.
+//!
+//! The placement lives in the dialog's extra parameters under the command's own key (`corner`,
+//! `center` or `base`). It is written there only once a field or the choice changes, so a new
+//! dialog left alone sends no placement (the box stays at the origin, as before), and an edited
+//! feature's stored point goes back unchanged.
+
+use serde_json::{Map, Value, json};
+use solidcraft_engine::Session;
+use solidcraft_engine::doc::expr::Kind as ValueKind;
+use solidcraft_engine::geom::Vec3;
+
+use crate::i18n::tr;
+use crate::selection::{EDGES, FACES, ORIGIN, SelInput, VERTICES};
+use crate::ui_kit::{self, choice_row, expr_row};
+use solidcraft_engine::Sel;
+
+/// The placement keys a primitive's dialog offers, the choice's first option first.
+fn keys(cmd: &str) -> &'static [&'static str] {
+ match cmd {
+ "solid.box" => &["corner", "center"],
+ "solid.cylinder" => &["base"],
+ _ => &[],
+ }
+}
+
+/// The Box's choice of the point its fields place.
+const BOX_PLACEMENTS: [&str; 2] = ["Corner", "Center"];
+
+/// The selection inputs of a primitive's dialog: the Box takes a point for its corner or centre.
+pub(crate) fn inputs(cmd: &str) -> Vec<SelInput> {
+ match cmd {
+ "solid.box" => vec![SelInput::new("Point", VERTICES | EDGES | FACES | ORIGIN, false)],
+ _ => Vec::new(),
+ }
+}
+
+/// The text a placement coordinate shows: typed text as it is, a stored number (millimetres) as
+/// the edit fields show stored lengths.
+fn shown(s: &Session, v: Option<&Value>) -> String {
+ match v {
+ Some(Value::String(t)) => t.clone(),
+ // "10", not the JSON number's "10.0".
+ Some(Value::Number(n)) => crate::dialogs::stored_length(s, &n.as_f64().map_or_else(|| n.to_string(), |v| v.to_string())),
+ _ => crate::dialogs::length_default(s, "0"),
+ }
+}
+
+/// The current placement: which key, and its three coordinates as the fields show them.
+fn current(s: &Session, cmd: &str, extra: &Map<String, Value>) -> Option<(usize, [String; 3])> {
+ let keys = keys(cmd);
+ let first = keys.first()?;
+ let index = keys.iter().position(|k| extra.contains_key(*k)).unwrap_or(0);
+ let point = extra.get(keys.get(index).copied().unwrap_or(first)).and_then(Value::as_array);
+ let coord = |i: usize| shown(s, point.and_then(|p| p.get(i)));
+ Some((index, [coord(0), coord(1), coord(2)]))
+}
+
+/// Store a placement under `key`, replacing the other choice.
+fn store(cmd: &str, extra: &mut Map<String, Value>, index: usize, coords: &[String; 3]) {
+ let keys = keys(cmd);
+ let Some(key) = keys.get(index) else { return };
+ for k in keys {
+ extra.remove(*k);
+ }
+ extra.insert((*key).into(), json!(coords));
+}
+
+/// The placement rows (shown while no pre-selected face or vertex places the primitive). True
+/// when Enter was pressed in a field.
+pub(crate) fn rows(ui: &mut egui::Ui, s: &Session, cmd: &str, extra: &mut Map<String, Value>) -> bool {
+ let Some((index, mut coords)) = current(s, cmd, extra) else { return false };
+ let mut choice = index;
+ if keys(cmd).len() > 1 {
+ choice_row(ui, "Placement", "pr_place", &mut choice, &BOX_PLACEMENTS);
+ } else {
+ ui_kit::row(ui, "Placement", |ui| {
+ ui_kit::text(ui, tr("Base Center"), ui_kit::Text::Cell);
+ });
+ }
+ let before = coords.clone();
+ let mut enter = false;
+ for (label, value) in ["X", "Y", "Z"].into_iter().zip(coords.iter_mut()) {
+ enter |= expr_row(ui, label, value);
+ }
+ if choice != index || coords != before {
+ store(cmd, extra, choice, &coords);
+ }
+ enter
+}
+
+/// A coordinate of a picked point as a field shows it, in millimetres.
+fn mm(v: f64) -> String {
+ let v = (v * 1e6).round() / 1e6;
+ // No "-0 mm".
+ let v = if v == 0.0 { 0.0 } else { v };
+ format!("{v} mm")
+}
+
+/// A point picked into the Box's input: it goes into the X, Y and Z of the current placement
+/// (the corner or the centre), replacing a pre-selected face or vertex.
+pub(crate) fn picked(s: &Session, cmd: &str, at: &mut Option<(Vec3, Option<Vec3>)>, extra: &mut Map<String, Value>, sel: Option<&Sel>) {
+ let point = match sel {
+ Some(Sel::Vertex { point, .. } | Sel::Face { point, .. } | Sel::Edge { point, .. }) => *point,
+ _ => return,
+ };
+ if !point.is_finite() || inputs(cmd).is_empty() {
+ return;
+ }
+ let Some((index, _)) = current(s, cmd, extra) else { return };
+ store(cmd, extra, index, &[mm(point.x), mm(point.y), mm(point.z)]);
+ *at = None;
+}
+
+/// 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<String, Value>, p: &mut Map<String, Value>) {
+ for key in keys(cmd) {
+ let Some(Value::Array(point)) = extra.get(*key) else { continue };
+ let coords: Vec<Value> = point
+ .iter()
+ .map(|c| match c {
+ Value::String(t) if t.trim().is_empty() => json!(0),
+ Value::String(t) => json!(s.doc.with_design_unit(t, ValueKind::Length)),
+ other => other.clone(),
+ })
+ .collect();
+ p.insert((*key).into(), Value::Array(coords));
+ }
+}
diff --git a/crates/ui-egui/src/primitive_units_tests.rs b/crates/ui-egui/src/primitive_units_tests.rs
index 5f94a74630..7c2fcbf63d 100644
--- a/crates/ui-egui/src/primitive_units_tests.rs
+++ b/crates/ui-egui/src/primitive_units_tests.rs
@@ -1,6 +1,7 @@
//! #630: the Box, Cylinder, Sphere, Torus and Coil dialogs show the unit of their sizes, as the
//! other dialogs do ("10 mm"), in the design's units. OK makes what the bare numbers made before,
-//! and a bare number typed into a field still means the design's units.
+//! and a bare number typed into a field still means the design's units. #5638: the Box dialog
+//! places the box by its corner or centre and the Cylinder dialog by its base, typed or picked.
use serde_json::{Value, json};
use solidcraft_engine::Session;
@@ -438,3 +439,175 @@ fn cone_dialog_makes_a_cone_and_edits_it_into_a_frustum() {
let (_, params) = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap().remove(0);
assert_eq!(params["operation"], json!("cut"));
}
+
+/// The bounding boxes of the design's bodies, in order: (min, max) in mm.
+fn bounds(s: &mut Session) -> Vec<([f64; 3], [f64; 3])> {
+ let r = s.execute("inspect.measure", &json!({})).unwrap();
+ let corner = |v: &Value| -> [f64; 3] { std::array::from_fn(|i| v[i].as_f64().unwrap()) };
+ r["bodies"].as_array().unwrap().iter().map(|b| (corner(&b["bbox"]["min"]), corner(&b["bbox"]["max"]))).collect()
+}
+
+/// Within a micron.
+fn assert_near(got: [f64; 3], want: [f64; 3]) {
+ assert_within(got, want, 1e-6);
+}
+
+fn assert_within(got: [f64; 3], want: [f64; 3], tol: f64) {
+ assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < tol), "{got:?}, want {want:?}");
+}
+
+/// The open dialog's command parameters.
+fn sent(h: &Harness) -> Value {
+ apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap().remove(0).1
+}
+
+/// Choose a dropdown option, as a person does.
+fn choose(h: &mut Harness, row: &str, option: &str) {
+ h.step(&json!({"click": {"handle": format!("dialog:{row}")}})).unwrap();
+ h.frames(2);
+ h.step(&json!({"click": {"handle": format!("dialog:{row}:{option}")}})).unwrap();
+ h.frames(2);
+}
+
+#[test]
+fn the_box_dialog_places_the_box_by_its_corner_or_its_centre() {
+ let mut h = design("mm");
+ h.app.start("solid.box");
+ h.frames(3);
+ let origin: Vec<(&str, String)> = ["X", "Y", "Z"].iter().map(|k| (*k, "0 mm".to_string())).collect();
+ assert_shown(&h, &origin);
+ // Left alone it sends no placement: the box at the origin, as before.
+ let p = sent(&h);
+ assert!(p.get("corner").is_none() && p.get("center").is_none(), "{p}");
+ // The corner, typed: a bare number, a unit, an expression.
+ type_into(&mut h, "X", "10");
+ type_into(&mut h, "Y", "-5 mm");
+ type_into(&mut h, "Z", "2 * 5 mm");
+ h.frames(2);
+ assert_eq!(sent(&h)["corner"], json!(["10", "-5 mm", "2 * 5 mm"]));
+ ok(&mut h);
+ let made = bounds(&mut h.app.session);
+ assert_near(made[0].0, [10.0, -5.0, 10.0]);
+ assert_near(made[0].1, [30.0, 15.0, 30.0]);
+ // The centre instead.
+ h.app.start("solid.box");
+ h.frames(3);
+ choose(&mut h, "Placement", "Center");
+ type_into(&mut h, "X", "50");
+ h.frames(2);
+ let p = sent(&h);
+ assert_eq!(p["center"], json!(["50", "0 mm", "0 mm"]), "{p}");
+ assert!(p.get("corner").is_none(), "{p}");
+ ok(&mut h);
+ let made = bounds(&mut h.app.session);
+ assert_near(made[1].0, [40.0, -10.0, -10.0]);
+ assert_near(made[1].1, [60.0, 10.0, 10.0]);
+}
+
+#[test]
+fn a_bare_placement_number_is_in_the_designs_units_and_negative_sizes_go_the_other_way() {
+ let mut h = design("in");
+ h.app.start("solid.box");
+ h.frames(3);
+ type_into(&mut h, "X", "1");
+ type_into(&mut h, "length", "-1");
+ h.frames(2);
+ let p = sent(&h);
+ assert_eq!((&p["corner"][0], &p["length"]), (&json!("1 in"), &json!("-1 in")), "{p}");
+ ok(&mut h);
+ // From the corner at x = 1 in back to x = 0.
+ let made = bounds(&mut h.app.session);
+ assert_near(made[0].0, [0.0, 0.0, 0.0]);
+ assert_near(made[0].1, [25.4, 508.0, 508.0]);
+}
+
+#[test]
+fn editing_a_box_or_cylinder_shows_its_placement_and_keeps_it() {
+ use solidcraft_engine::doc::FeatureKind;
+ let mut h = design("mm");
+ h.app.run("parameters.add", json!({"name": "w", "expression": "15 mm"})).unwrap();
+ h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": ["w", 0, 5]})).unwrap();
+ h.app.run("solid.cylinder", json!({"radius": 5, "height": 10, "base": [60, 0, 0], "operation": "new"})).unwrap();
+ h.frames(2);
+ let ids: Vec<u64> = h.app.session.doc.features.iter().map(|f| f.id).collect();
+ let stored = |h: &Harness, id: u64| match h.app.session.doc.feature(id).map(|f| &f.kind) {
+ Some(FeatureKind::Box { corner, .. }) => corner.iter().map(ToString::to_string).collect::<Vec<_>>(),
+ Some(FeatureKind::Cylinder { base, .. }) => base.iter().map(ToString::to_string).collect(),
+ other => panic!("not a box or cylinder: {other:?}"),
+ };
+ let (box_id, cylinder_id) = (ids[0], ids[1]);
+ let box_corner = stored(&h, box_id);
+ h.app.edit_feature(box_id);
+ h.frames(3);
+ assert_shown(&h, &[("X", "w".into()), ("Y", "0".into()), ("Z", "5".into())]);
+ ok(&mut h);
+ assert_eq!(stored(&h, box_id), box_corner, "OK without a change keeps the corner");
+ // A changed coordinate moves it.
+ h.app.edit_feature(box_id);
+ h.frames(3);
+ type_into(&mut h, "Z", "8");
+ h.frames(2);
+ ok(&mut h);
+ assert_eq!(stored(&h, box_id), ["w", "0", "8"]);
+ assert_near(bounds(&mut h.app.session)[0].0, [15.0, 0.0, 8.0]);
+ // The cylinder's base.
+ let base = stored(&h, cylinder_id);
+ h.app.edit_feature(cylinder_id);
+ h.frames(3);
+ assert_shown(&h, &[("X", "60".into()), ("Y", "0".into()), ("Z", "0".into())]);
+ ok(&mut h);
+ assert_eq!(stored(&h, cylinder_id), base);
+}
+
+#[test]
+fn the_cylinder_dialog_takes_its_base_point() {
+ let mut h = design("mm");
+ h.app.start("solid.cylinder");
+ h.frames(3);
+ assert!(sent(&h).get("base").is_none(), "left alone, at the origin as before");
+ type_into(&mut h, "X", "30");
+ type_into(&mut h, "Z", "-4");
+ h.frames(2);
+ assert_eq!(sent(&h)["base"], json!(["30", "0 mm", "-4"]));
+ ok(&mut h);
+ let made = bounds(&mut h.app.session);
+ assert_within(made[0].0, [20.0, -10.0, -4.0], 1e-2);
+ assert_within(made[0].1, [40.0, 10.0, 16.0], 1e-2);
+}
+
+#[test]
+fn a_point_picked_in_the_box_dialog_becomes_its_corner_or_centre() {
+ use solidcraft_engine::Sel;
+ use solidcraft_engine::geom::Vec3;
+ let mut h = design("mm");
+ h.app.run("solid.box", json!({"length": 40, "width": 30, "height": 20, "body_name": "Base"})).unwrap();
+ h.frames(2);
+ // A face picked before the command: the box stands on it, as before (no typed placement).
+ h.app.session.selection = vec![Sel::Face { body: "Base".into(), index: 0, point: Vec3::new(20.0, 15.0, 20.0) }];
+ h.app.start("solid.box");
+ h.frames(3);
+ let pick = |h: &mut Harness, sel: Sel| {
+ let mut d = h.app.dialog.take().unwrap();
+ let hit = crate::viewport::Hit::Vertex { body: "Base".into(), point: Vec3::ZERO };
+ assert!(d.active_input().is_some_and(|i| i.accepts(&hit, None, |_, _| true).is_some()), "the Box dialog takes a vertex");
+ d.pick(&h.app.session, sel);
+ h.app.dialog = Some(d);
+ h.frames(2);
+ };
+ let placed = |h: &Harness| matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(Kind::Primitive { at: Some(_), .. }));
+ assert!(placed(&h), "the pre-selected face places it");
+ // A vertex picked in the dialog: the corner there, in the fields, instead of the face.
+ pick(&mut h, Sel::Vertex { body: "Base".into(), point: Vec3::new(40.0, 30.0, 20.0) });
+ assert!(!placed(&h));
+ assert_shown(&h, &[("X", "40 mm".into()), ("Y", "30 mm".into()), ("Z", "20 mm".into())]);
+ assert_eq!(sent(&h)["corner"], json!(["40 mm", "30 mm", "20 mm"]));
+ // With Center chosen, the pick is the centre.
+ choose(&mut h, "Placement", "Center");
+ pick(&mut h, Sel::Vertex { body: "Base".into(), point: Vec3::new(0.0, 0.0, 0.0) });
+ let p = sent(&h);
+ assert_eq!(p["center"], json!(["0 mm", "0 mm", "0 mm"]), "{p}");
+ assert!(p.get("corner").is_none(), "{p}");
+ ok(&mut h);
+ let made = bounds(&mut h.app.session);
+ assert_near(made[1].0, [-10.0, -10.0, -10.0]);
+}