Skip to content

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

Pattern counts: say when a parameter has a length unit, and refuse fractional counts (#5066) (#5337)

raykholo0e01dc9badb0
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index fab3da747d..d38922a724 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -6252,7 +6252,7 @@ pub fn pattern_matrices(doc: &Document, st: &ModelState, p: &crate::PatternKind)
fn pattern_transforms(doc: &Document, vals: &BTreeMap<String, Value>, st: &ModelState, component: u64, p: &crate::PatternKind) -> Result<Vec<Mat>> {
let count = |e: &str| -> Result<usize> {
- let n = val(vals, e, Kind::Unitless)?.round();
+ let n = expr::eval_count(e, vals)?;
if !(1.0..=MAX_INSTANCES as f64).contains(&n) {
return Err(DocError::Invalid(format!("pattern count must be 1…{MAX_INSTANCES}")));
}
diff --git a/crates/doc/src/expr.rs b/crates/doc/src/expr.rs
index 203238361b..9c8ca556d4 100644
--- a/crates/doc/src/expr.rs
+++ b/crates/doc/src/expr.rs
@@ -982,6 +982,24 @@ fn call(f: &str, args: &[Value], d: Defaults) -> Result<Value, DocError> {
})
}
+/// Evaluate a count: a unit-less whole number. A length or angle says how to fix it, and a
+/// fraction is refused rather than rounded to a different number of copies.
+pub fn eval_count(s: &str, vals: &BTreeMap<String, Value>) -> Result<f64, DocError> {
+ let e = s.trim();
+ let value = eval_with(e, &|n| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))))?;
+ if let Some(kind @ (Kind::Length | Kind::Angle)) = value.kind() {
+ let subject = if vals.contains_key(e) { format!("`{e}`") } else { "this expression".into() };
+ let remedy = if vals.contains_key(e) { "set its Unit to none to use it as a count" } else { "use a unit-less expression as a count" };
+ return Err(DocError::Expr(format!("{subject} is {} ({}); {remedy}", value.describe(), kind.default_unit())));
+ }
+ let n = value.to_kind(Kind::Unitless)?;
+ // Allow float noise such as `10 / 3 * 3`, never a real fraction.
+ if !n.is_finite() || (n - n.round()).abs() > 1e-9 {
+ return Err(DocError::Expr(format!("a count must be a whole number; `{e}` is {n}")));
+ }
+ Ok(n.round())
+}
+
/// Evaluate an expression; `lookup` resolves parameter names. Bare numbers are mm / degrees.
pub fn eval_with(s: &str, lookup: &dyn Fn(&str) -> Result<Value, DocError>) -> Result<Value, DocError> {
eval_with_defaults(s, lookup, Defaults::default())
diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs
index 3eefa45a13..db3d5732a0 100644
--- a/crates/engine/src/cmd/features.rs
+++ b/crates/engine/src/cmd/features.rs
@@ -641,6 +641,12 @@ pub(super) fn check_expr(s: &Session, e: &str, kind: Kind, cmd: &str, what: &str
s.doc.eval(e, kind).map(|_| ()).map_err(|err| bad(cmd, format!("{what}: {err}")))
}
+/// A pattern count: a whole, unit-less number (see `expr::eval_count`).
+pub(super) fn check_count(s: &Session, e: &str, cmd: &str, what: &str) -> Result<()> {
+ let (vals, _) = s.doc.param_values();
+ solidcraft_doc::expr::eval_count(e, &vals).map(|_| ()).map_err(|err| bad(cmd, format!("{what}: {err}")))
+}
+
/// Add a feature, evaluate, and report its result (an evaluation error fails the command).
pub(super) fn add_feature(s: &mut Session, p: &Value, kind: FeatureKind) -> Result<Value> {
add_feature_in(s, p, kind, true)
@@ -2001,12 +2007,12 @@ fn pattern_rect(s: &mut Session, p: &Value) -> Result<Value> {
let dir1 = p.get("dir1").and_then(vec3).ok_or_else(|| bad(cmd, "`dir1` must be [x, y, z]"))?;
let count1 = req_expr(cmd, p, "count1")?;
let spacing1 = req_expr(cmd, p, "spacing1")?;
- check_expr(s, &count1, Kind::Unitless, cmd, "count1")?;
+ check_count(s, &count1, cmd, "count1")?;
check_expr(s, &spacing1, Kind::Length, cmd, "spacing1")?;
let dir2 = p.get("dir2").and_then(vec3);
let (count2, spacing2) = (expr(p, "count2"), expr(p, "spacing2"));
if let Some(c) = &count2 {
- check_expr(s, c, Kind::Unitless, cmd, "count2")?;
+ check_count(s, c, cmd, "count2")?;
}
if let Some(c) = &spacing2 {
check_expr(s, c, Kind::Length, cmd, "spacing2")?;
@@ -2031,7 +2037,7 @@ fn pattern_circ(s: &mut Session, p: &Value) -> Result<Value> {
let (features, bodies) = pattern_sources(s, p, cmd)?;
let (origin, axis, axis_ref, axis_feature) = axis_line(s, p, cmd)?;
let count = req_expr(cmd, p, "count")?;
- check_expr(s, &count, Kind::Unitless, cmd, "count")?;
+ check_count(s, &count, cmd, "count")?;
let angle = expr(p, "angle").unwrap_or_else(|| "360 deg".into());
check_expr(s, &angle, Kind::Angle, cmd, "angle")?;
let pattern = solidcraft_doc::PatternKind::Circular {
@@ -2056,7 +2062,7 @@ fn pattern_path(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "`path` must list 1…1000 curve ids"));
}
let count = req_expr(cmd, p, "count")?;
- check_expr(s, &count, Kind::Unitless, cmd, "count")?;
+ check_count(s, &count, cmd, "count")?;
let (spacing, extent) = match (expr(p, "spacing"), expr(p, "distance")) {
(Some(x), _) => (x, false),
(None, Some(x)) => (x, true),
diff --git a/crates/engine/src/cmd/patterns_tests.rs b/crates/engine/src/cmd/patterns_tests.rs
index 2fe7a32c52..54183a669c 100644
--- a/crates/engine/src/cmd/patterns_tests.rs
+++ b/crates/engine/src/cmd/patterns_tests.rs
@@ -970,3 +970,82 @@ fn pattern_of_features_picked_in_any_order_copies_them_in_timeline_order() {
assert!(rel(volume(&mut s), expected) < 1e-9, "{picked:?}");
}
}
+
+#[test]
+fn pattern_count_units_explain_how_to_use_a_parameter() -> Result<(), Box<dyn std::error::Error>> {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "body_name": "Seed"}));
+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Path"}));
+ run(&mut s, "sketch.line", json!({"points": [[0, 0], [100, 0]], "ids": ["line"]}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "parameters.add", json!({"name": "columns", "expression": "3", "unit": "mm"}));
+ run(&mut s, "parameters.add", json!({"name": "turns", "expression": "3", "unit": "deg"}));
+ for (command, field, params) in [
+ ("solid.pattern.rectangular", "count1", json!({"bodies": ["Seed"], "dir1": [1, 0, 0], "spacing1": 10})),
+ (
+ "solid.pattern.rectangular",
+ "count2",
+ json!({"bodies": ["Seed"], "dir1": [1, 0, 0], "spacing1": 10, "count1": 2, "dir2": [0, 1, 0], "spacing2": 10}),
+ ),
+ ("solid.pattern.circular", "count", json!({"bodies": ["Seed"], "axis": "Z"})),
+ ("solid.pattern.path", "count", json!({"bodies": ["Seed"], "path_sketch": "Path", "path": ["line"], "spacing": 10})),
+ ] {
+ for (expression, message) in [
+ ("columns", "`columns` is a length (mm); set its Unit to none to use it as a count"),
+ ("columns * 2", "this expression is a length (mm)"),
+ ("turns", "`turns` is an angle (deg); set its Unit to none to use it as a count"),
+ ] {
+ let mut params = params.clone();
+ params[field] = json!(expression);
+ let before = s.doc.to_json();
+ let error = s.execute(command, &params).err().ok_or("dimensioned count was accepted")?.to_string();
+ assert!(error.contains(message), "{command} {field}: {error}");
+ assert_eq!(s.doc.to_json(), before);
+ }
+ }
+ Ok(())
+}
+
+#[test]
+fn pattern_count_fractions_are_refused() -> Result<(), Box<dyn std::error::Error>> {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "body_name": "Seed"}));
+ run(&mut s, "parameters.add", json!({"name": "n", "expression": "2.5", "unit": ""}));
+ for expression in [json!(2.5), json!("n"), json!("n * 2 - 2.5")] {
+ let params = json!({"bodies": ["Seed"], "dir1": [1, 0, 0], "count1": expression, "spacing1": 10});
+ let error = s.execute("solid.pattern.rectangular", &params).err().ok_or("fractional count was accepted")?.to_string();
+ assert!(error.contains("a count must be a whole number;"), "{error}");
+ assert!(error.contains("is 2.5"), "{error}");
+ if expression == json!("n") {
+ assert!(error.contains("`n` is 2.5"), "{error}");
+ }
+ }
+ Ok(())
+}
+
+#[test]
+fn pattern_count_integer_parameters_survive_save_and_reject_fractional_edits() -> Result<(), Box<dyn std::error::Error>> {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "body_name": "Seed"}));
+ run(&mut s, "parameters.add", json!({"name": "n", "expression": "3", "unit": ""}));
+ run(&mut s, "solid.pattern.rectangular", json!({"bodies": ["Seed"], "dir1": [1, 0, 0], "count1": "n", "spacing1": 10, "name": "Copies"}));
+ assert_eq!(s.model.state().bodies.len(), 3);
+ let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json())?);
+ assert!(reopened.model.results.iter().all(|r| r.error.is_none()));
+ assert_eq!(reopened.model.state().bodies.len(), 3);
+ let error = reopened
+ .execute("timeline.edit", &json!({"feature": "Copies", "set": {"pattern": {"count1": "n / 2"}}}))
+ .err()
+ .ok_or("fractional edit was accepted")?
+ .to_string();
+ assert!(error.contains("a count must be a whole number;"), "{error}");
+ let mut saved = solidcraft_doc::Document::from_json(&s.doc.to_json())?;
+ for feature in &mut saved.features {
+ if let solidcraft_doc::FeatureKind::Pattern { pattern: solidcraft_doc::PatternKind::Rectangular { count1, .. }, .. } = &mut feature.kind {
+ *count1 = "n / 2".into();
+ }
+ }
+ let invalid = Session::new(solidcraft_doc::Document::from_json(&saved.to_json())?);
+ assert!(invalid.model.results.iter().any(|r| r.error.as_ref().is_some_and(|e| e.contains("a count must be a whole number;"))));
+ Ok(())
+}