SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Add base-height and new-body options to Snap Fit (#1994) (#6911)
Dahak Buildsab709e6c4613
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rsindex 66ef524c5f..4d17108021 100644--- a/crates/doc/src/document.rs+++ b/crates/doc/src/document.rs@@ -1273,6 +1273,14 @@ pub enum FeatureKind {/// The catch's height along the arm.#[walk(length = "Catch length")]catch_length: Expr,+ /// The base extends this far below the face (none: the arm starts at the face).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[walk(length = "Base height")]+ base_height: Option<Expr>,+ /// Make the snap fit its own body instead of joining the target, so it can be+ /// patterned or moved on its own.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ new_body: bool,#[serde(default, skip_serializing_if = "Option::is_none")]body: Option<BodyName>,},diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rsindex 873048982b..12b84ca81a 100644--- a/crates/doc/src/eval_more.rs+++ b/crates/doc/src/eval_more.rs@@ -2005,19 +2005,22 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &Fapply_traced(doc, st, f, tool, Operation::Join, std::slice::from_ref(&target))}}- FeatureKind::SnapFit { position, direction, hook, length, thickness, width, catch_depth, catch_length, body } => {+ FeatureKind::SnapFit { position, direction, hook, length, thickness, width, catch_depth, catch_length, base_height, new_body, body } => {let target = body_under(st, body, position.0)?;let size = |what: &str, e: &str| plastic_size("snap fit", what, len(e)?);let (l, t, w) = (size("length", length)?, size("thickness", thickness)?, size("width", width)?);let (cd, cl) = (size("catch_depth", catch_depth)?, size("catch_length", catch_length)?);+ let bh = base_height.as_deref().map(|e| size("base_height", e)).transpose()?.unwrap_or(0.0);if !(cl < l) {return Err(DocError::Invalid("the snap fit's catch must be shorter than its arm".into()));}let (x, y, z) = local_frame(direction.0, Some(hook.0))?;let delta = (l * 0.05).clamp(1e-3, 0.5);// Side profile (x = toward the catch, y = up the arm), extruded across the width.- let pts =- [Vec2::new(-t, -delta), Vec2::new(0.0, -delta), Vec2::new(0.0, l - cl), Vec2::new(cd, l - cl), Vec2::new(0.0, l), Vec2::new(-t, l)];+ // The base reaches `base_height` below the face; a joined arm bites `delta` into+ // the wall, a separate body sits flush on it.+ let y0 = if *new_body { -bh } else { -delta - bh };+ let pts = [Vec2::new(-t, y0), Vec2::new(0.0, y0), Vec2::new(0.0, l - cl), Vec2::new(cd, l - cl), Vec2::new(0.0, l), Vec2::new(-t, l)];let o = position.0 - y * (w / 2.0);let pl = Plane::new(o, x, z).ok_or_else(|| DocError::Invalid("snap fit frame".into()))?;let mut lp = Loop2::polygon(&pts);@@ -2028,7 +2031,8 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &Flet (lo, hi) = if sgn > 0.0 { (0.0, w) } else { (-w, 0.0) };let tool = kernel::extrude(&pl, &[Region2 { outer: lp, holes: Vec::new() }], lo, hi)?;let tool = tool.into_iter().map(|b| crate::lineage::part_tool(b, "arm")).collect();- apply_traced(doc, st, f, tool, Operation::Join, std::slice::from_ref(&target))+ let op = if *new_body { Operation::NewBody } else { Operation::Join };+ apply_traced(doc, st, f, tool, op, std::slice::from_ref(&target))}FeatureKind::Rest { position, direction, along, width, length, height, draft, thickness, body } => {let target = body_under(st, body, position.0)?;diff --git a/crates/engine/src/cmd/plastic.rs b/crates/engine/src/cmd/plastic.rsindex 5a4e138b4c..38de1be77c 100644--- a/crates/engine/src/cmd/plastic.rs+++ b/crates/engine/src/cmd/plastic.rs@@ -22,7 +22,8 @@ pub static COMMANDS: &[CommandSpec] = &["face: [x,y,z] on the rim face of a shelled body; width, height; type?: lip|groove; gap? (groove clearance); side?: inside|outside (which rim edge); body?",),CommandSpec::new("plastic.snap_fit", "Snap Fit", snap_fit).at("PLASTIC", "CREATE").icon("snap_fit").params(- "position: [x,y,z] on a face; direction? (default: out of the face); hook: [x,y,z] (the catch's direction); length, thickness, width, catch_depth, catch_length; body?",+ "position: [x,y,z] on a face; direction? (default: out of the face); hook: [x,y,z] (the catch's direction); length, thickness, width, catch_depth, catch_length; \+ base_height? (extends the base below the face); new_body?: bool (make a separate body instead of joining); body?",),CommandSpec::new("plastic.rest", "Rest", rest).at("PLASTIC", "CREATE").icon("rest").params("position: [x,y,z] on a face (the rest's centre); direction? (default: out of the face); width (round: the diameter); length? (a rectangle, along `along`); along?: [x,y,z]; \@@ -262,6 +263,8 @@ fn snap_fit(s: &mut Session, p: &Value) -> Result<Value> {width: required(s, p, "width", Kind::Length, cmd)?,catch_depth: required(s, p, "catch_depth", Kind::Length, cmd)?,catch_length: required(s, p, "catch_length", Kind::Length, cmd)?,+ base_height: checked(s, p, "base_height", Kind::Length, cmd)?,+ new_body: bool_(p, "new_body").unwrap_or(false),body: str_(p, "body").map(BodyName::from),};add_feature(s, p, kind)@@ -425,6 +428,43 @@ mod tests {assert!(s.execute("plastic.snap_fit", &json!({"position": [5, 5, 4], "direction": [0, 0, 1], "hook": [0, 0, 1], "length": 15, "thickness": 1.5, "width": 6, "catch_depth": 1, "catch_length": 3})).is_err());}+ #[test]+ fn snap_fit_base_height_and_new_body() {+ let snap =+ json!({"position": [20, 20, 4], "hook": [1, 0, 0], "length": 15, "thickness": 1.5, "width": 6, "catch_depth": 1, "catch_length": 3});+ let arm = 1.5 * 15.0 * 6.0 + 0.5 * 1.0 * 3.0 * 6.0;+ let snap_volume = |s: &mut Session| {+ let m = run(s, "inspect.measure", json!({}));+ m["bodies"].as_array().unwrap().iter().map(|b| b["volume_mm3"].as_f64().unwrap()).min_by(f64::total_cmp).unwrap_or(f64::NAN)+ };+ // New body: the snap fit stands on its own, its volume exact, so it can be arrayed or moved.+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 4}));+ let mut p = snap.clone();+ p["new_body"] = json!(true);+ run(&mut s, "plastic.snap_fit", p);+ assert_eq!(run(&mut s, "inspect.measure", json!({}))["body_count"], 2);+ assert!(rel(snap_volume(&mut s), arm) < 1e-6);+ // Base height adds a t·w·base_height base below the face.+ let mut t = Session::default();+ run(&mut t, "solid.box", json!({"length": 40, "width": 40, "height": 4}));+ let mut p = snap.clone();+ p["new_body"] = json!(true);+ p["base_height"] = json!(4);+ run(&mut t, "plastic.snap_fit", p);+ assert!(rel(snap_volume(&mut t), arm + 1.5 * 6.0 * 4.0) < 1e-6);+ // Joined with a base height it still builds: the base bites into the wall, so the+ // total grows only by the arm above the face, and there is still one body.+ let mut u = Session::default();+ run(&mut u, "solid.box", json!({"length": 40, "width": 40, "height": 4}));+ let v0 = volume(&mut u);+ let mut p = snap.clone();+ p["base_height"] = json!(2);+ run(&mut u, "plastic.snap_fit", p);+ assert!(rel(volume(&mut u) - v0, arm) < 1e-6);+ assert_eq!(run(&mut u, "inspect.measure", json!({}))["body_count"], 1);+ }+#[test]fn plastic_sizes_below_the_minimum_are_refused_by_name() {let mut s = Session::default();diff --git a/crates/ui-egui/src/dialogs_plastic.rs b/crates/ui-egui/src/dialogs_plastic.rsindex e044b5a838..df268d874a 100644--- a/crates/ui-egui/src/dialogs_plastic.rs+++ b/crates/ui-egui/src/dialogs_plastic.rs@@ -55,6 +55,8 @@ crate::dialog_descriptor::dialog_descriptors! {width: String,catch_depth: String,catch_length: String,+ base_height: String,+ new_body: bool,},/// The rule manager: the rule shown (index into the rules, past the end for a new one).Rules {@@ -103,6 +105,8 @@ fn snap_fit(app: &SolveApp) -> Pl {width: crate::dialogs::length_default(&app.session, "5"),catch_depth: crate::dialogs::length_default(&app.session, "1"),catch_length: crate::dialogs::length_default(&app.session, "2"),+ base_height: String::new(),+ new_body: false,}}@@ -185,7 +189,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Pl, inputs: &[SelInpuenter |= opt_field(ui, "Clearance", gap, crate::length_input::unit(&app.session.doc), "from the rule");}}- Pl::SnapFit { hook, length, thickness, width, catch_depth, catch_length } => {+ Pl::SnapFit { hook, length, thickness, width, catch_depth, catch_length, base_height, new_body } => {let dirs = face_normal(app, inputs).map(hook_dirs).unwrap_or_default();if !dirs.is_empty() {let names: Vec<&str> = dirs.iter().map(|(n, _)| n.as_str()).collect();@@ -196,6 +200,12 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Pl, inputs: &[SelInpuenter |= expr_row(ui, "Width", width);enter |= expr_row(ui, "Catch Depth", catch_depth);enter |= expr_row(ui, "Catch Length", catch_length);+ enter |= opt_field(ui, "Base Height", base_height, crate::length_input::unit(&app.session.doc), "at the face");+ form_row(ui, "Body", |ui| {+ let mut op = usize::from(*new_body);+ combo(ui, "pl_snap_body", &["Join", "New Body"], &mut op);+ *new_body = op == 1;+ });}Pl::Rest { round, width, length, height, draft, thickness } => {form_row(ui, "Shape", |ui| {@@ -296,7 +306,7 @@ pub fn commands(app: &SolveApp, k: &Pl, inputs: &[SelInput], extra: &Map<String,}("plastic.lip", p)}- Pl::SnapFit { hook, length, thickness, width, catch_depth, catch_length } => {+ Pl::SnapFit { hook, length, thickness, width, catch_depth, catch_length, base_height, new_body } => {let mut p = placed("a point on a face")?;let n = extra.get("direction")@@ -309,6 +319,10 @@ pub fn commands(app: &SolveApp, k: &Pl, inputs: &[SelInput], extra: &Map<String,{p[key] = json!(v);}+ put(&mut p, &[("base_height", base_height)]);+ if *new_body {+ p["new_body"] = json!(true);+ }("plastic.snap_fit", p)}Pl::Rest { round, length, draft, thickness, .. } => {@@ -365,7 +379,7 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec<SelI}(Pl::simple_restore(kind)?, "plastic.lip", face.0)}- FeatureKind::SnapFit { position, direction, hook, length, thickness, width, catch_depth, catch_length, body } => {+ FeatureKind::SnapFit { position, direction, hook, length, thickness, width, catch_depth, catch_length, base_height, new_body, body } => {extra.insert("direction".into(), pt(direction.0));if let Some(b) = body {extra.insert("body".into(), json!(b));@@ -381,6 +395,8 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec<SelIwidth: shown_expr(width, ValueKind::Length),catch_depth: shown_expr(catch_depth, ValueKind::Length),catch_length: shown_expr(catch_length, ValueKind::Length),+ base_height: base_height.as_deref().map(|v| shown_expr(v, ValueKind::Length)).unwrap_or_default(),+ new_body: *new_body,};(f, "plastic.snap_fit", position.0)}diff --git a/crates/ui-egui/src/dialogs_plastic_tests.rs b/crates/ui-egui/src/dialogs_plastic_tests.rsindex 5cde4207bf..e23eff0e7a 100644--- a/crates/ui-egui/src/dialogs_plastic_tests.rs+++ b/crates/ui-egui/src/dialogs_plastic_tests.rs@@ -139,6 +139,29 @@ fn bare_numbers_show_their_units() {assert_eq!(count(&app), n);}+/// #1994: the Snap Fit dialog sends Base Height and New Body when set, nothing when not,+/// and Edit Feature refills them.+#[test]+fn snap_fit_base_height_and_new_body_dialog() {+ let mut app = app_with(&[("solid.box", json!({"length": 40, "width": 40, "height": 4}))]);+ app.session.selection = face_sel(&app.session, Vec3::new(20.0, 20.0, 4.0)).into_iter().collect();+ app.start("plastic.snap_fit");+ let mut d = app.dialog.clone().unwrap();+ let p = &apply_commands(&app, &d).unwrap()[0].1;+ assert!(p.get("base_height").is_none() && p.get("new_body").is_none(), "defaults send nothing: {p}");+ if let Kind::Plastic(Pl::SnapFit { base_height, new_body, .. }) = &mut d.kind {+ *base_height = "2 mm".into();+ *new_body = true;+ }+ let c = apply_commands(&app, &d).unwrap();+ assert_eq!(c[0].1["base_height"], "2 mm");+ assert_eq!(c[0].1["new_body"], true);+ run_all(&mut app, c);+ let f = app.session.doc.features.last().unwrap().clone();+ let e = edit_dialog(&app, f.id, None).unwrap();+ assert!(matches!(&e.kind, Kind::Plastic(Pl::SnapFit { base_height, new_body, .. }) if base_height == "2 mm" && *new_body));+}+/// `shown_expr` adds the unit only to a bare number of a length or an angle.#[test]fn shown_expr_adds_units_to_bare_numbers() {diff --git a/crates/ui-egui/src/length_input.rs b/crates/ui-egui/src/length_input.rsindex 0b671068be..6b9c9175c9 100644--- a/crates/ui-egui/src/length_input.rs+++ b/crates/ui-egui/src/length_input.rs@@ -130,7 +130,9 @@ pub(crate) fn fields<'a>(doc: &Document, kind: &'a mut crate::dialogs::Kind) ->vec![diameter, height, hole_diameter, hole_depth, fillet, rib_thickness, rib_length, rib_offset]}Pl::Lip { width, height, gap, .. } => vec![width, height, gap],- Pl::SnapFit { length, thickness, width, catch_depth, catch_length, .. } => vec![length, thickness, width, catch_depth, catch_length],+ Pl::SnapFit { length, thickness, width, catch_depth, catch_length, base_height, .. } => {+ vec![length, thickness, width, catch_depth, catch_length, base_height]+ }Pl::Rest { width, length, height, thickness, .. } => vec![width, length, height, thickness],Pl::Rules { values, .. } => {let kinds = solidcraft_engine::doc::plastic::PlasticRule::library()diff --git a/crates/ui-egui/src/primitive_units_tests.rs b/crates/ui-egui/src/primitive_units_tests.rsindex 692c2bde9c..1589b85f86 100644--- a/crates/ui-egui/src/primitive_units_tests.rs+++ b/crates/ui-egui/src/primitive_units_tests.rs@@ -304,7 +304,7 @@ fn operation_length_defaults_follow_every_design_unit() {("sheet.fold", &[""]),("plastic.boss", &["6", "10", "3", "", "", "1", "3", "1"]),("plastic.lip", &["1.5", "2", ""]),- ("plastic.snap_fit", &["10", "1.5", "5", "1", "2"]),+ ("plastic.snap_fit", &["10", "1.5", "5", "1", "2", ""]),("plastic.rest", &["10", "15", "2", ""]),("joint.create", &["0", "0", "0"]),("joint.gear", &["10", "20"]),