Skip to content

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

Sheet metal feature commands: typed parameter contracts (#6581) (#6582)

NOWN-DEVeb29c4b2d8b4
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index b1b06effdf..894ddc7691 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -79,6 +79,10 @@ mod render_ui;
#[cfg(test)]
mod script_tests;
mod sheet;
+pub(crate) use sheet::{
+ FlangeType, ThenStep, flange_edge, flange_edge_list, flange_position, flange_type, fold_points, fold_position, perforation_pattern, sheet_points,
+ then_list,
+};
mod silhouette;
mod sketch;
pub(crate) use sketch::author_path_for_rebind;
diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rs
index f22de39a54..dcb9862579 100644
--- a/crates/engine/src/cmd/sheet.rs
+++ b/crates/engine/src/cmd/sheet.rs
@@ -12,10 +12,25 @@ use solidcraft_geom::{Aabb2, Ring, Vec2, Vec3};
use super::CommandSpec;
use super::features::{add_feature, check_expr, feature_sketch, profiles, sketch_id};
use crate::params::{bad, bool_, expr, expr_problem, req_expr, str_, string_list, vec3};
+use crate::schema::features::FeatureResult;
+use crate::schema::sheet::{ConvertParams, FlangeParams, FoldParams, HemParams, PerforateParams, UnfoldParams};
+use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
+const FLANGE_CONTRACT: TypedContract<FlangeParams> = TypedContract::new();
+const PERFORATE_CONTRACT: TypedContract<PerforateParams> = TypedContract::new();
+const HEM_CONTRACT: TypedContract<HemParams> = TypedContract::new();
+const FOLD_CONTRACT: TypedContract<FoldParams> = TypedContract::new();
+const UNFOLD_CONTRACT: TypedContract<UnfoldParams> = TypedContract::new();
+const CONVERT_CONTRACT: TypedContract<ConvertParams> = TypedContract::new();
+
pub static COMMANDS: &[CommandSpec] = &[
- CommandSpec::new("sheet.flange", "Flange", flange).at("SHEET METAL", "CREATE").icon("flange").params(
+ CommandSpec::new("sheet.flange", "Flange", crate::checked!("sheet.flange", flange))
+ .at("SHEET METAL", "CREATE")
+ .icon("flange")
+ .contract(&FLANGE_CONTRACT)
+ .output(output_schema_for::<FeatureResult>)
+ .params(
"base: sketch + profiles? (rule?, flip?) | contour: sketch + curves (open chain of lines) + distance (rule?, flip?, reverse?) | \
edge: edges: [[x,y,z] on top/bottom edges, or {point: [x,y,z], angle?, height?} for an edge with its own angle and height] + \
height (along the flange, to its far edge), angle? (default 90 deg), radius? (default: rule), \
@@ -35,23 +50,47 @@ pub static COMMANDS: &[CommandSpec] = &[
that edge, from the edge out (each line one flange as long as the line, to the outer face from the virtual sharp; each \
corner one bend, turning the way the lines turn); radius? (default: rule); body?. One feature, one body",
),
- CommandSpec::new("sheet.perforate", "Perforate", perforate).at("SHEET METAL", "CREATE").icon("perforate").params(
+ CommandSpec::new("sheet.perforate", "Perforate", crate::checked!("sheet.perforate", perforate))
+ .at("SHEET METAL", "CREATE")
+ .icon("perforate")
+ .contract(&PERFORATE_CONTRACT)
+ .output(output_schema_for::<FeatureResult>)
+ .params(
"diameter, pitch: expr; margin?: expr (clear of edges, cut-outs and bends; default: the diameter); pattern?: staggered (60°, default) | square; body? - a perforation field over the whole flat sheet: holes in the flat pattern (perforations), the DXF (layer PERFORATION) and the measured volume, not cut into the B-rep (#732)",
),
- CommandSpec::new("sheet.hem", "Hem", hem)
+ CommandSpec::new("sheet.hem", "Hem", crate::checked!("sheet.hem", hem))
.at("SHEET METAL", "CREATE")
.icon("hem")
+ .contract(&HEM_CONTRACT)
+ .output(output_schema_for::<FeatureResult>)
.params("edges: [[x,y,z] on sheet edges]; length (to the outer face); gap? (inner radius, default: rule); flip?; body?"),
- CommandSpec::new("sheet.fold", "Fold", fold).at("SHEET METAL", "CREATE").icon("fold").params(
+ CommandSpec::new("sheet.fold", "Fold", crate::checked!("sheet.fold", fold))
+ .at("SHEET METAL", "CREATE")
+ .icon("fold")
+ .contract(&FOLD_CONTRACT)
+ .output(output_schema_for::<FeatureResult>)
+ .params(
"line: sketch + curve (a sketch line on the sheet's base face; followed when the sketch changes) or points: [[x,y,z], [x,y,z]]; \
angle? (default 90 deg); radius? (default: rule); position?: centerline|start|end|mould (where the line sits in the bend, default centerline); \
fixed?: [x,y,z] on the side that stays (default: the larger side); flip? (fold the other way); body?",
),
- CommandSpec::new("sheet.unfold", "Unfold", unfold).at("SHEET METAL", "MODIFY").icon("unfold").params("body? (default: the last sheet body) — all bends"),
- CommandSpec::new("sheet.refold", "Refold", refold).at("SHEET METAL", "MODIFY").icon("refold").params("body? (default: the last unfolded sheet)"),
- CommandSpec::new("sheet.convert", "Convert to Sheet Metal", convert)
+ CommandSpec::new("sheet.unfold", "Unfold", crate::checked!("sheet.unfold", unfold))
+ .at("SHEET METAL", "MODIFY")
+ .icon("unfold")
+ .contract(&UNFOLD_CONTRACT)
+ .output(output_schema_for::<FeatureResult>)
+ .params("body? (default: the last sheet body) — all bends"),
+ CommandSpec::new("sheet.refold", "Refold", crate::checked!("sheet.refold", refold))
+ .at("SHEET METAL", "MODIFY")
+ .icon("refold")
+ .contract(&UNFOLD_CONTRACT)
+ .output(output_schema_for::<FeatureResult>)
+ .params("body? (default: the last unfolded sheet)"),
+ CommandSpec::new("sheet.convert", "Convert to Sheet Metal", crate::checked!("sheet.convert", convert))
.at("SHEET METAL", "CREATE")
.icon("convert_sheet")
+ .contract(&CONVERT_CONTRACT)
+ .output(output_schema_for::<FeatureResult>)
.params(
"body; face: [x,y,z] on its large flat face (a plate of even thickness; recesses in one face up to half the thickness deep, \
such as an engraved label, become pockets of the sheet), or that face's name from model.faces; rule?; \
@@ -98,13 +137,17 @@ pub static COMMANDS: &[CommandSpec] = &[
];
fn points(p: &Value, k: &str, cmd: &str) -> Result<Vec<Vec3>> {
- let a = p.get(k).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("`{k}` must list points [x, y, z] on sheet edges")))?;
+ sheet_points(p.get(k)).map_err(|why| bad(cmd, format!("`{k}` {why}")))
+}
+
+/// What [`points`] reads a list of sheet-edge picks as, without the design: 1…1000 points
+/// `[x, y, z]`, `{x, y, z}` or `{point}`. The error follows the key's name.
+pub(crate) fn sheet_points(v: Option<&Value>) -> std::result::Result<Vec<Vec3>, &'static str> {
+ let a = v.and_then(Value::as_array).ok_or("must list points [x, y, z] on sheet edges")?;
if a.is_empty() || a.len() > 1000 {
- return Err(bad(cmd, format!("`{k}` must list 1…1000 points")));
+ return Err("must list 1…1000 points");
}
- a.iter()
- .map(|v| vec3(v).or_else(|| v.get("point").and_then(vec3)).ok_or_else(|| bad(cmd, format!("`{k}` must contain [x, y, z] points"))))
- .collect()
+ a.iter().map(|v| vec3(v).or_else(|| v.get("point").and_then(vec3)).ok_or("must contain [x, y, z] points")).collect()
}
/// The `edges` of an edge flange: points `[x, y, z]` on sheet edges, or `{point, angle?, height?}`
@@ -114,31 +157,41 @@ const MAX_THEN: usize = 16;
/// One further bend of an edge flange: its angle, its height and, if it has its own, which way
/// it turns (`flip`; the flange's own otherwise).
-type ThenStep = (solidcraft_doc::Expr, solidcraft_doc::Expr, Option<bool>);
+pub(crate) type ThenStep = (solidcraft_doc::Expr, solidcraft_doc::Expr, Option<bool>);
/// The further bends of an edge flange (`then`): each an angle and a height, made one after
/// the other, every one on the far edge of the flange before it.
fn then_steps(s: &Session, p: &Value, cmd: &str) -> Result<Vec<ThenStep>> {
- let Some(v) = p.get("then").filter(|v| !v.is_null()) else { return Ok(Vec::new()) };
+ let steps = then_list(p.get("then")).map_err(|why| bad(cmd, why))?;
+ for (i, (angle, height, _)) in steps.iter().enumerate() {
+ check_expr(s, height, Kind::Length, cmd, &format!("then[{i}].height"))?;
+ check_expr(s, angle, Kind::Angle, cmd, &format!("then[{i}].angle"))?;
+ }
+ Ok(steps)
+}
+
+/// What [`then_steps`] reads `then` as, without the design: up to [`MAX_THEN`] bends
+/// `{angle?, height, flip?}` (the angle 90° when it is left out, null or not an expression).
+/// Whether the expressions suit the design is checked by the handler.
+pub(crate) fn then_list(v: Option<&Value>) -> std::result::Result<Vec<ThenStep>, String> {
+ let Some(v) = v.filter(|v| !v.is_null()) else { return Ok(Vec::new()) };
let list = "`then` must list further bends {angle?, height, flip?}: each on the far edge of the flange before it";
- let a = v.as_array().ok_or_else(|| bad(cmd, list))?;
+ let a = v.as_array().ok_or(list)?;
if a.len() > MAX_THEN {
- return Err(bad(cmd, format!("`then` may list at most {MAX_THEN} bends")));
+ return Err(format!("`then` may list at most {MAX_THEN} bends"));
}
let mut out = Vec::with_capacity(a.len());
for (i, step) in a.iter().enumerate() {
- let o = step.as_object().ok_or_else(|| bad(cmd, format!("then[{i}]: {list}")))?;
+ let o = step.as_object().ok_or_else(|| format!("then[{i}]: {list}"))?;
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "angle" | "height" | "flip")) {
- return Err(bad(cmd, format!("then[{i}]: unknown key `{k}` (a bend takes angle, height and flip)")));
+ return Err(format!("then[{i}]: unknown key `{k}` (a bend takes angle, height and flip)"));
}
let flip = match o.get("flip").filter(|v| !v.is_null()) {
- Some(v) => Some(v.as_bool().ok_or_else(|| bad(cmd, format!("then[{i}]: `flip` must be true or false")))?),
+ Some(v) => Some(v.as_bool().ok_or_else(|| format!("then[{i}]: `flip` must be true or false"))?),
None => None,
};
- let height = req_expr(cmd, step, "height").map_err(|_| bad(cmd, format!("then[{i}]: `height` is required")))?;
- check_expr(s, &height, Kind::Length, cmd, &format!("then[{i}].height"))?;
+ let height = expr(step, "height").ok_or_else(|| format!("then[{i}]: `height` is required"))?;
let angle = expr(step, "angle").unwrap_or_else(|| "90 deg".into());
- check_expr(s, &angle, Kind::Angle, cmd, &format!("then[{i}].angle"))?;
out.push((angle, height, flip));
}
Ok(out)
@@ -162,36 +215,53 @@ fn far_edge_picks(s: &Session, id: u64, cmd: &str) -> Result<Vec<FlangeEdge>> {
}
fn flange_edges(s: &Session, p: &Value, cmd: &str) -> Result<Vec<FlangeEdge>> {
- const KEYS: [&str; 3] = ["point", "angle", "height"];
- let list = "`edges` must list points [x, y, z] on sheet edges, or {point, angle?, height?}";
- let a = p.get("edges").and_then(Value::as_array).ok_or_else(|| bad(cmd, list))?;
- if a.is_empty() || a.len() > 1000 {
- return Err(bad(cmd, "`edges` must list 1…1000 points"));
- }
+ let a = flange_edge_list(p.get("edges")).map_err(|why| bad(cmd, why))?;
let mut edges = Vec::with_capacity(a.len());
for (i, v) in a.iter().enumerate() {
- // A bare point, as before: [x, y, z] or {x, y, z}.
- let Some(o) = v.as_object().filter(|o| KEYS.iter().any(|k| o.contains_key(*k))) else {
- edges.push(FlangeEdge::at(vec3(v).ok_or_else(|| bad(cmd, format!("edges[{i}]: {list}")))?));
- continue;
- };
- if let Some(k) = o.keys().find(|k| !KEYS.contains(&k.as_str())) {
- return Err(bad(cmd, format!("edges[{i}]: unknown key `{k}` (an edge takes point, angle and height)")));
- }
- let point = o.get("point").and_then(vec3).ok_or_else(|| bad(cmd, format!("edges[{i}]: `point` must be [x, y, z]")))?;
- let own = |k: &str, kind: Kind| -> Result<Option<solidcraft_doc::Expr>> {
- if o.get(k).is_none_or(Value::is_null) {
- return Ok(None);
+ let edge = flange_edge(i, v).map_err(|why| bad(cmd, why))?;
+ for (k, e, kind) in [("angle", &edge.angle, Kind::Angle), ("height", &edge.height, Kind::Length)] {
+ if let Some(e) = e {
+ check_expr(s, e, kind, cmd, &format!("edges[{i}].{k}"))?;
}
- let e = expr(v, k).ok_or_else(|| bad(cmd, format!("edges[{i}]: `{k}` {}", expr_problem(v.get(k)))))?;
- check_expr(s, &e, kind, cmd, &format!("edges[{i}].{k}"))?;
- Ok(Some(e))
- };
- edges.push(FlangeEdge { point: Position(point), angle: own("angle", Kind::Angle)?, height: own("height", Kind::Length)? });
+ }
+ edges.push(edge);
}
Ok(edges)
}
+/// The message for `edges` that are not a list of points or edges.
+const FLANGE_EDGE_LIST: &str = "`edges` must list points [x, y, z] on sheet edges, or {point, angle?, height?}";
+
+/// An edge flange's `edges` as a list of 1…1000 items, without the design.
+pub(crate) fn flange_edge_list(v: Option<&Value>) -> std::result::Result<&Vec<Value>, &'static str> {
+ let a = v.and_then(Value::as_array).ok_or(FLANGE_EDGE_LIST)?;
+ if a.is_empty() || a.len() > 1000 {
+ return Err("`edges` must list 1…1000 points");
+ }
+ Ok(a)
+}
+
+/// Item `i` of an edge flange's `edges`, without the design: whether its expressions suit the
+/// design is checked by the handler.
+pub(crate) fn flange_edge(i: usize, v: &Value) -> std::result::Result<FlangeEdge, String> {
+ const KEYS: [&str; 3] = ["point", "angle", "height"];
+ // A bare point, as before: [x, y, z] or {x, y, z}.
+ let Some(o) = v.as_object().filter(|o| KEYS.iter().any(|k| o.contains_key(*k))) else {
+ return vec3(v).map(FlangeEdge::at).ok_or_else(|| format!("edges[{i}]: {FLANGE_EDGE_LIST}"));
+ };
+ if let Some(k) = o.keys().find(|k| !KEYS.contains(&k.as_str())) {
+ return Err(format!("edges[{i}]: unknown key `{k}` (an edge takes point, angle and height)"));
+ }
+ let point = o.get("point").and_then(vec3).ok_or_else(|| format!("edges[{i}]: `point` must be [x, y, z]"))?;
+ let own = |k: &str| -> std::result::Result<Option<solidcraft_doc::Expr>, String> {
+ if o.get(k).is_none_or(Value::is_null) {
+ return Ok(None);
+ }
+ expr(v, k).map(Some).ok_or_else(|| format!("edges[{i}]: `{k}` {}", expr_problem(v.get(k))))
+ };
+ Ok(FlangeEdge { point: Position(point), angle: own("angle")?, height: own("height")? })
+}
+
fn rule_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<String>> {
match str_(p, "rule") {
Some(r) if s.doc.sheet.rules.iter().any(|x| x.name == r) || r == SheetRule::steel().name => Ok(Some(r.to_string())),
@@ -230,8 +300,8 @@ fn flange(s: &mut Session, p: &Value) -> Result<Value> {
if ty != "edge" && p.get("then").is_some_and(|v| !v.is_null()) {
return Err(bad(cmd, "`then` (further bends) is only for edge flanges"));
}
- match ty.as_str() {
- "base" => {
+ match flange_type(&ty).map_err(|why| bad(cmd, why))? {
+ FlangeType::Base => {
let sketch = feature_sketch(s, p, cmd)?;
let rule = rule_param(s, p, cmd)?;
add_feature(
@@ -240,7 +310,7 @@ fn flange(s: &mut Session, p: &Value) -> Result<Value> {
FeatureKind::SheetBase { sketch: SketchId(sketch), profiles: profiles(p, cmd)?, rule, flip: bool_(p, "flip").unwrap_or(false) },
)
}
- "contour" => {
+ FlangeType::Contour => {
let sketch = sketch_id(s, p.get("sketch"), cmd, "sketch")?;
let curves = string_list(cmd, p, "curves")?;
if curves.is_empty() || curves.len() > 1000 {
@@ -262,7 +332,7 @@ fn flange(s: &mut Session, p: &Value) -> Result<Value> {
},
)
}
- "edge" => {
+ FlangeType::Edge => {
let edges = flange_edges(s, p, cmd)?;
let then = then_steps(s, p, cmd)?;
let height = req_expr(cmd, p, "height")?;
@@ -273,14 +343,8 @@ fn flange(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(r) = &radius {
check_expr(s, r, Kind::Length, cmd, "radius")?;
}
- let mut position = str_(p, "position").unwrap_or("inside").to_ascii_lowercase();
- if !matches!(position.as_str(), "inside" | "outside" | "bend_outside" | "middle" | "material_outside" | "tangent") {
- return Err(bad(cmd, "`position` must be inside, outside, middle, material_outside or tangent"));
- }
- // The bend starting at the edge is `outside`, whichever name asked for it.
- if position == "bend_outside" {
- position = "outside".into();
- }
+ let position = flange_position(str_(p, "position").unwrap_or("inside"))
+ .ok_or_else(|| bad(cmd, "`position` must be inside, outside, middle, material_outside or tangent"))?;
// Where the heights are measured from; the outer sharp (the default) is saved as nothing.
let height_from = match p.get("height_from").filter(|v| !v.is_null()) {
Some(v) => v.as_str().and_then(sheet::HeightFrom::parse).ok_or_else(|| bad(cmd, "`height_from` must be outer, inner or tangent"))?,
@@ -345,7 +409,55 @@ fn flange(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(made)
}
- other => Err(bad(cmd, format!("unknown flange type `{other}` (base, edge or contour)"))),
+ }
+}
+
+/// The three kinds of flange.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum FlangeType {
+ Base,
+ Edge,
+ Contour,
+}
+
+/// A flange's `type`, in any case.
+pub(crate) fn flange_type(t: &str) -> std::result::Result<FlangeType, String> {
+ match t.to_ascii_lowercase().as_str() {
+ "base" => Ok(FlangeType::Base),
+ "edge" => Ok(FlangeType::Edge),
+ "contour" => Ok(FlangeType::Contour),
+ other => Err(format!("unknown flange type `{other}` (base, edge or contour)")),
+ }
+}
+
+/// An edge flange's `position` (in any case), lower-cased; the bend starting at the edge is
+/// `outside`, whichever name asked for it (`bend_outside` is the same).
+pub(crate) fn flange_position(t: &str) -> Option<String> {
+ match t.to_ascii_lowercase().as_str() {
+ "bend_outside" => Some("outside".into()),
+ t @ ("inside" | "outside" | "middle" | "material_outside" | "tangent") => Some(t.into()),
+ _ => None,
+ }
+}
+
+/// A fold's `position` (in any case), lower-cased.
+pub(crate) fn fold_position(t: &str) -> Option<String> {
+ Some(t.to_ascii_lowercase()).filter(|t| matches!(t.as_str(), "centerline" | "start" | "end" | "mould" | "mold"))
+}
+
+/// A fold's `points`: the fold line's two ends. The error follows the key's name.
+pub(crate) fn fold_points(v: &Value) -> std::result::Result<(Vec3, Vec3), &'static str> {
+ let pts = v.as_array().filter(|a| a.len() == 2).ok_or("must be two points [x, y, z]")?;
+ let a = pts.first().and_then(vec3).ok_or("must be two finite points [x, y, z]")?;
+ let b = pts.get(1).and_then(vec3).ok_or("must be two finite points [x, y, z]")?;
+ Ok((a, b))
+}
+
+/// A perforation's `pattern`.
+pub(crate) fn perforation_pattern(t: &str) -> std::result::Result<&str, &'static str> {
+ match t {
+ "staggered" | "square" => Ok(t),
+ _ => Err("`pattern` is \"staggered\" (60°, default) or \"square\""),
}
}
@@ -359,10 +471,7 @@ fn perforate(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(m) = &margin {
check_expr(s, m, Kind::Length, cmd, "margin")?;
}
- let pattern = str_(p, "pattern").map(str::to_string);
- if pattern.as_deref().is_some_and(|t| t != "staggered" && t != "square") {
- return Err(bad(cmd, "`pattern` is \"staggered\" (60°, default) or \"square\""));
- }
+ let pattern = str_(p, "pattern").map(|t| perforation_pattern(t).map(str::to_string).map_err(|why| bad(cmd, why))).transpose()?;
add_feature(s, p, FeatureKind::SheetPerforate { diameter, pitch, margin, pattern, body: str_(p, "body").map(BodyName::from) })
}
@@ -392,9 +501,7 @@ fn fold(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sheet.fold";
let (sketch, curve, a, b) = match p.get("points") {
Some(v) => {
- let pts = v.as_array().filter(|a| a.len() == 2).ok_or_else(|| bad(cmd, "`points` must be two points [x, y, z]"))?;
- let a = pts.first().and_then(vec3).ok_or_else(|| bad(cmd, "`points` must be two finite points [x, y, z]"))?;
- let b = pts.get(1).and_then(vec3).ok_or_else(|| bad(cmd, "`points` must be two finite points [x, y, z]"))?;
+ let (a, b) = fold_points(v).map_err(|why| bad(cmd, format!("`points` {why}")))?;
(None, None, a, b)
}
None => {
@@ -419,10 +526,8 @@ fn fold(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(r) = &radius {
check_expr(s, r, Kind::Length, cmd, "radius")?;
}
- let position = str_(p, "position").unwrap_or("centerline").to_ascii_lowercase();
- if !matches!(position.as_str(), "centerline" | "start" | "end" | "mould" | "mold") {
- return Err(bad(cmd, "`position` must be centerline, start, end or mould"));
- }
+ let position =
+ fold_position(str_(p, "position").unwrap_or("centerline")).ok_or_else(|| bad(cmd, "`position` must be centerline, start, end or mould"))?;
let fixed = match p.get("fixed") {
Some(v) => Some(vec3(v).ok_or_else(|| bad(cmd, "`fixed` must be a point [x, y, z]"))?),
None => None,
diff --git a/crates/engine/src/cmd/sheet_tests.rs b/crates/engine/src/cmd/sheet_tests.rs
index b7c2ce3f76..adc6e3f109 100644
--- a/crates/engine/src/cmd/sheet_tests.rs
+++ b/crates/engine/src/cmd/sheet_tests.rs
@@ -2921,7 +2921,7 @@ fn fold_accepts_a_fixed_point_on_the_top_face() {
[440, 229.25], [440, 239.36], [30, 239.36], [30, 229.25], [1.7, 229.25]], "closed": true}),
);
run(&mut s, "sketch.finish", json!({}));
- run(&mut s, "sheet.flange", json!({"base": {"sketch": "Blank"}, "rule": "SGCC 0.8"}));
+ run(&mut s, "sheet.flange", json!({"sketch": "Blank", "rule": "SGCC 0.8"}));
let flat = volume(&mut s);
run(&mut s, "sheet.fold", json!({"points": [[30, 230.255, 508.2], [440, 230.255, 508.2]], "fixed": [420, 120, fixed_z], "flip": true}));
assert!(rel(volume(&mut s), flat) < 1e-3, "fixed z {fixed_z}: a fold keeps the material");
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index 36c94c1843..5811189d55 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -58,6 +58,7 @@ pub mod component;
pub mod edit;
pub mod features;
pub mod inspect;
+pub mod sheet;
pub mod sketch_constraints;
pub mod sketch_create;
pub mod view_navigation;
diff --git a/crates/engine/src/schema/sheet.rs b/crates/engine/src/schema/sheet.rs
new file mode 100644
index 0000000000..8e3cbf5731
--- /dev/null
+++ b/crates/engine/src/schema/sheet.rs
@@ -0,0 +1,550 @@
+//! Contracts for the sheet metal feature commands in `cmd/sheet.rs`. They all return
+//! [`FeatureResult`](super::features::FeatureResult).
+//!
+//! A sheet metal rule sets the sheet's thickness, K-factor, bend radius and reliefs: the
+//! commands refuse those keys with a pointer to `sheet.manage_rules`, so they are no keys of
+//! these contracts (strict refuses them as unknown keys). The same goes for the nested `base`
+//! object an old base flange call may carry, which the handler reads only to refuse rule keys
+//! in it.
+//!
+//! The value types below are used by these commands only. Like the shared ones in
+//! [`types`](super::types), each calls the handler's own reader (split out of `cmd/sheet.rs`)
+//! and gives its message.
+
+use std::borrow::Cow;
+
+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
+use serde::de::Error as _;
+use serde::{Deserialize, Deserializer};
+use serde_json::Value;
+use solidcraft_doc::FlangeEdge;
+use solidcraft_geom::Vec3;
+
+use super::check::whole;
+use super::types::{AngleExpr, FaceRef, FeatureCommon, IdOrName, LengthExpr, Point3, ProfilesParam, SketchRef, StringList, feature_common, present};
+
+/// Points on sheet edges, as the `edges` of a hem and the `bends` of a conversion: 1 to 1000
+/// points `[x, y, z]`, `{x, y, z}` or `{point}` (read by `sheet::sheet_points`).
+#[derive(Clone, Debug, PartialEq)]
+pub struct SheetPoints(pub Vec<Vec3>);
+
+impl<'de> Deserialize<'de> for SheetPoints {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ crate::cmd::sheet_points(Some(&Value::deserialize(d)?)).map(SheetPoints).map_err(D::Error::custom)
+ }
+}
+
+impl JsonSchema for SheetPoints {
+ fn schema_name() -> Cow<'static, str> {
+ "SheetPoints".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<Point3>();
+ json_schema!({
+ "description": "Points in mm on sheet edges, 1 to 1000: each [x, y, z], {\"x\", \"y\", \"z\"} or {\"point\": [x, y, z]}.",
+ "type": "array",
+ "items": {"anyOf": [point, {"type": "object", "properties": {"point": point}, "required": ["point"]}]},
+ "minItems": 1,
+ "maxItems": 1000
+ })
+ }
+}
+
+/// The `edges` of an edge flange: 1 to 1000 points on sheet edges, each `[x, y, z]` (or
+/// `{x, y, z}`) or `{point, angle?, height?}` for an edge with its own angle and height (read by
+/// `sheet::flange_edge`). Whether the expressions suit the design is checked by the handler.
+#[derive(Clone, Debug, PartialEq)]
+pub struct FlangeEdges(pub Vec<FlangeEdge>);
+
+impl<'de> Deserialize<'de> for FlangeEdges {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ let items = crate::cmd::flange_edge_list(Some(&v)).map_err(|why| D::Error::custom(whole(why)))?;
+ items
+ .iter()
+ .enumerate()
+ .map(|(i, item)| crate::cmd::flange_edge(i, item).map_err(|why| D::Error::custom(whole(why))))
+ .collect::<Result<_, _>>()
+ .map(FlangeEdges)
+ }
+}
+
+impl JsonSchema for FlangeEdges {
+ fn schema_name() -> Cow<'static, str> {
+ "FlangeEdges".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<Point3>();
+ let angle = generator.subschema_for::<AngleExpr>();
+ let height = generator.subschema_for::<LengthExpr>();
+ json_schema!({
+ "description": "Points in mm on the sheet's top or bottom edges, 1 to 1000: each [x, y, z] or {\"x\", \"y\", \"z\"}, or {\"point\": [x, y, z], \"angle\"?, \"height\"?} for an edge with its own angle and height (null: the feature's).",
+ "type": "array",
+ "items": {
+ "anyOf": [
+ // An object with any of the edge's keys is an edge, never a bare point.
+ {"anyOf": [point], "not": {"type": "object", "anyOf": [{"required": ["point"]}, {"required": ["angle"]}, {"required": ["height"]}]}},
+ {
+ "type": "object",
+ "properties": {"point": point, "angle": {"anyOf": [angle, {"type": "null"}]}, "height": {"anyOf": [height, {"type": "null"}]}},
+ "required": ["point"],
+ "additionalProperties": false
+ }
+ ]
+ },
+ "minItems": 1,
+ "maxItems": 1000
+ })
+ }
+}
+
+/// A fold line's two ends, `[[x, y, z], [x, y, z]]` (read by `sheet::fold_points`).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct FoldPoints(pub Vec3, pub Vec3);
+
+impl<'de> Deserialize<'de> for FoldPoints {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ crate::cmd::fold_points(&Value::deserialize(d)?).map(|(a, b)| FoldPoints(a, b)).map_err(D::Error::custom)
+ }
+}
+
+impl JsonSchema for FoldPoints {
+ fn schema_name() -> Cow<'static, str> {
+ "FoldPoints".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<Point3>();
+ json_schema!({"description": "The fold line's two ends, in mm.", "type": "array", "items": point, "minItems": 2, "maxItems": 2})
+ }
+}
+
+/// A point in mm, `[x, y, z]` or `{x, y, z}`, with a fold's message for `fixed` (`Point3` says
+/// "of numbers" after it).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct FixedPoint(pub Vec3);
+
+impl<'de> Deserialize<'de> for FixedPoint {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ crate::params::vec3(&Value::deserialize(d)?).map(FixedPoint).ok_or_else(|| D::Error::custom("must be a point [x, y, z]"))
+ }
+}
+
+impl JsonSchema for FixedPoint {
+ fn schema_name() -> Cow<'static, str> {
+ "FixedPoint".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ Point3::json_schema(generator)
+ }
+}
+
+/// A flange's `type`, in any case (read by `sheet::flange_type`).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct FlangeTypeParam(pub(crate) crate::cmd::FlangeType);
+
+impl<'de> Deserialize<'de> for FlangeTypeParam {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ let t = v.as_str().ok_or_else(|| D::Error::custom("must be base, edge or contour"))?;
+ crate::cmd::flange_type(t).map(FlangeTypeParam).map_err(|why| D::Error::custom(whole(why)))
+ }
+}
+
+impl JsonSchema for FlangeTypeParam {
+ fn schema_name() -> Cow<'static, str> {
+ "FlangeType".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "base, edge or contour, in any case.",
+ "type": "string",
+ "pattern": "^([Bb][Aa][Ss][Ee]|[Ee][Dd][Gg][Ee]|[Cc][Oo][Nn][Tt][Oo][Uu][Rr])$"
+ })
+ }
+}
+
+/// A word from a short list, in any case, read by a handler's reader that returns `None` for
+/// any other text; `$message` is the handler's.
+macro_rules! word {
+ ($(#[$doc:meta])* $name:ident, $reader:path, $message:literal, $description:literal, [$($word:literal),+]) => {
+ $(#[$doc])*
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct $name(pub String);
+
+ impl<'de> Deserialize<'de> for $name {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ Value::deserialize(d)?.as_str().and_then($reader).map($name).ok_or_else(|| D::Error::custom($message))
+ }
+ }
+
+ impl JsonSchema for $name {
+ fn schema_name() -> Cow<'static, str> {
+ stringify!($name).into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ let any_case = |w: &str| w.chars().map(|c| format!("[{}{}]", c.to_ascii_uppercase(), c)).collect::<String>();
+ let words: Vec<String> = [$($word),+].iter().map(|w| any_case(w)).collect();
+ json_schema!({"description": $description, "type": "string", "pattern": format!("^({})$", words.join("|"))})
+ }
+ }
+ };
+}
+
+word!(
+ /// An edge flange's `position` (read by `sheet::flange_position`).
+ FlangePosition,
+ crate::cmd::flange_position,
+ "must be inside, outside, middle, material_outside or tangent",
+ "inside, outside (bend_outside is the same), middle, material_outside or tangent, in any case.",
+ ["inside", "outside", "bend_outside", "middle", "material_outside", "tangent"]
+);
+word!(
+ /// A fold's `position` (read by `sheet::fold_position`).
+ FoldPosition,
+ crate::cmd::fold_position,
+ "must be centerline, start, end or mould",
+ "centerline, start, end or mould (or mold), in any case.",
+ ["centerline", "start", "end", "mould", "mold"]
+);
+
+/// A corner relief's shape: notch, round, rectangular or tear, in any case and with blanks
+/// around it (read by `ReliefShape::parse`).
+#[derive(Clone, Debug, PartialEq)]
+pub struct ReliefShapeParam(pub solidcraft_doc::sheet::ReliefShape);
+
+impl<'de> Deserialize<'de> for ReliefShapeParam {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ Value::deserialize(d)?
+ .as_str()
+ .and_then(solidcraft_doc::sheet::ReliefShape::parse)
+ .map(ReliefShapeParam)
+ .ok_or_else(|| D::Error::custom("must be notch, round, rectangular or tear"))
+ }
+}
+
+impl JsonSchema for ReliefShapeParam {
+ fn schema_name() -> Cow<'static, str> {
+ "ReliefShape".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "notch, round, rectangular or tear, in any case (blanks around it are ignored).",
+ "type": "string",
+ "pattern": format!("^{blank}({words}){blank}$", blank = blanks(), words = "[Nn][Oo][Tt][Cc][Hh]|[Rr][Oo][Uu][Nn][Dd]|[Rr][Ee][Cc][Tt][Aa][Nn][Gg][Uu][Ll][Aa][Rr]|[Tt][Ee][Aa][Rr]")
+ })
+ }
+}
+
+/// Where an edge flange's height is measured from: outer, inner or tangent, in any case and with
+/// blanks around it (read by `HeightFrom::parse`).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct HeightFromParam(pub solidcraft_doc::sheet::HeightFrom);
+
+impl<'de> Deserialize<'de> for HeightFromParam {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ Value::deserialize(d)?
+ .as_str()
+ .and_then(solidcraft_doc::sheet::HeightFrom::parse)
+ .map(HeightFromParam)
+ .ok_or_else(|| D::Error::custom("must be outer, inner or tangent"))
+ }
+}
+
+impl JsonSchema for HeightFromParam {
+ fn schema_name() -> Cow<'static, str> {
+ "HeightFrom".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "outer, inner or tangent, in any case (blanks around it are ignored).",
+ "type": "string",
+ "pattern": format!("^{blank}({words}){blank}$", blank = blanks(), words = "[Oo][Uu][Tt][Ee][Rr]|[Ii][Nn][Nn][Ee][Rr]|[Tt][Aa][Nn][Gg][Ee][Nn][Tt]")
+ })
+ }
+}
+
+/// An edge flange's further bends (`then`): up to 16, each `{angle?, height, flip?}`, made on the
+/// far edge of the flange before it (read by `sheet::then_list`). Whether the expressions suit
+/// the design is checked by the handler. The handler reads an `angle` that is no expression as
+/// left out (90°); this type refuses it.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ThenSteps(pub Vec<crate::cmd::ThenStep>);
+
+impl<'de> Deserialize<'de> for ThenSteps {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ let steps = crate::cmd::then_list(Some(&v)).map_err(|why| D::Error::custom(whole(why)))?;
+ let bends = v.as_array().map(Vec::as_slice).unwrap_or_default();
+ let wrong = bends
+ .iter()
+ .enumerate()
+ .find_map(|(i, b)| b.get("angle").filter(|a| !a.is_null() && crate::params::expr(b, "angle").is_none()).map(|a| (i, a)));
+ match wrong {
+ Some((i, a)) => Err(D::Error::custom(whole(format!("then[{i}]: `angle` {}", crate::params::expr_problem(Some(a)))))),
+ None => Ok(ThenSteps(steps)),
+ }
+ }
+}
+
+impl JsonSchema for ThenSteps {
+ fn schema_name() -> Cow<'static, str> {
+ "ThenSteps".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let angle = generator.subschema_for::<AngleExpr>();
+ let height = generator.subschema_for::<LengthExpr>();
+ json_schema!({
+ "description": "Further bends, at most 16, each a flange on the far edge of the one before: its height, its angle (default 90 deg) and flip (true turns that bend the other way; default: the flange's).",
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {"angle": {"anyOf": [angle, {"type": "null"}]}, "height": height, "flip": {"type": ["boolean", "null"]}},
+ "required": ["height"],
+ "additionalProperties": false
+ },
+ "maxItems": 16
+ })
+ }
+}
+
+/// Any run of the characters Rust's `trim` removes, as a regex.
+fn blanks() -> String {
+ let u = |c: char| format!("\\u{:04x}", c as u32);
+ let class: String = super::types::WHITESPACE.iter().map(|&(a, b)| if a == b { u(a) } else { format!("{}-{}", u(a), u(b)) }).collect();
+ format!("[{class}]*")
+}
+
+/// A perforation's `pattern` (read by `sheet::perforation_pattern`).
+#[derive(Clone, Debug, PartialEq)]
+pub struct PerforationPattern(pub String);
+
+impl<'de> Deserialize<'de> for PerforationPattern {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ let t = v.as_str().unwrap_or_default();
+ crate::cmd::perforation_pattern(t).map(|t| PerforationPattern(t.to_string())).map_err(|why| D::Error::custom(whole(why)))
+ }
+}
+
+impl JsonSchema for PerforationPattern {
+ fn schema_name() -> Cow<'static, str> {
+ "PerforationPattern".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "staggered (rows offset for a 60° pattern) or square, lower case.", "enum": ["staggered", "square"]})
+ }
+}
+
+/// Add a sheet metal flange: a base flange from sketch profiles, a contour flange along an open
+/// chain of sketch lines, or edge flanges on a sheet's edges. Thickness, K-factor, bend radius
+/// and reliefs come from the sheet metal rule (`sheet.manage_rules`), so those keys are refused;
+/// an edge flange may set its own `radius` and corner relief. `participants` changes nothing.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct FlangeParams {
+ /// Which flange: base, edge or contour, in any case. Default: edge when `edges` is given,
+ /// else contour when `curves` is given, else base.
+ #[serde(default)]
+ pub r#type: Option<FlangeTypeParam>,
+ /// Base and contour: the sketch, by id or name. A base flange's default is the active sketch,
+ /// else the last one; a contour flange needs it.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "IdOrName")]
+ pub sketch: Option<IdOrName>,
+ /// Base: which of the sketch's profiles become the sheet. Default: all of them.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ProfilesParam")]
+ pub profiles: Option<ProfilesParam>,
+ /// Base and contour: the sheet metal rule, by name. Default: the active rule. Ignored by an
+ /// edge flange, which takes its sheet's.
+ #[serde(default)]
+ pub rule: Option<String>,
+ /// Base: the thickness goes to the other side of the sketch plane. Contour: the material goes
+ /// to the other side of the chain. Edge: the flanges bend the other way. Default: false.
+ #[serde(default)]
+ pub flip: Option<bool>,
+ /// Contour: the open chain's lines (curve ids; arcs aren't supported yet), 1 to 1000.
+ #[serde(default)]
+ pub curves: Option<StringList>,
+ /// Contour: how far the flange runs from the sketch plane, positive.
+ #[serde(default)]
+ pub distance: Option<LengthExpr>,
+ /// Contour: the flange runs from the sketch plane the other way. Default: false.
+ #[serde(default)]
+ pub reverse: Option<bool>,
+ /// Edge: the edges that get a flange.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "FlangeEdges")]
+ pub edges: Option<FlangeEdges>,
+ /// Edge: each flange's height, along the flange to its far edge, from where `height_from` says
+ /// (an edge's own `height` replaces it). Required for an edge flange.
+ #[serde(default)]
+ pub height: Option<LengthExpr>,
+ /// Edge: where the height is measured from: the outer virtual sharp (outer), the inner virtual
+ /// sharp (inner), or past 90° the line square to the flange touching the bend's outside
+ /// (tangent; up to 90° the outer sharp). Default: outer.
+ #[serde(default)]
+ pub height_from: Option<HeightFromParam>,
+ /// Edge: the bend angle, more than 0 and at most 180° (an edge's own `angle` replaces it).
+ /// Default: 90 deg.
+ #[serde(default)]
+ pub angle: Option<AngleExpr>,
+ /// Edge: the inner bend radius. Default: the sheet's rule's.
+ #[serde(default)]
+ pub radius: Option<LengthExpr>,
+ /// Edge: where the bend starts: inside (the outer virtual sharp on the edge), outside or
+ /// bend_outside (the bend starting at the edge), middle (half-way), material_outside (the
+ /// inner virtual sharp on the edge) or tangent (the bend's outer face tangent to the edge's
+ /// face; below 90° the bend's end on that face). Default: inside.
+ #[serde(default)]
+ pub position: Option<FlangePosition>,
+ /// Edge: the sheet metal body. Default: the sheet with an edge nearest the first point.
+ #[serde(default)]
+ pub body: Option<String>,
+ /// Edge: the shape of the relief cut where these flanges meet at a corner, in place of the
+ /// rule's. Refused on a base or contour flange.
+ #[serde(default)]
+ pub corner_relief_shape: Option<ReliefShapeParam>,
+ /// Edge: the size across of a round or rectangular corner relief, in place of the rule's.
+ /// Refused on a base or contour flange.
+ #[serde(default)]
+ pub corner_relief: Option<LengthExpr>,
+ /// Edge: further bends, each a flange on the far edge of the one before (at most 16). Refused
+ /// on a base or contour flange.
+ #[serde(default)]
+ pub then: Option<ThenSteps>,
+ #[serde(flatten, deserialize_with = "feature_common")]
+ pub common: FeatureCommon,
+}
+
+/// Add a field of round perforations over a whole flat sheet: holes in the flat pattern, the DXF
+/// (layer PERFORATION) and the measured volume, not cut into the solid. `participants` changes
+/// nothing.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct PerforateParams {
+ /// The holes' diameter, more than 0.
+ pub diameter: LengthExpr,
+ /// The distance between hole centres, more than the diameter.
+ pub pitch: LengthExpr,
+ /// How far the holes stay clear of the sheet's edges, cut-outs and bends, at least 0.
+ /// Default: the diameter.
+ #[serde(default)]
+ pub margin: Option<LengthExpr>,
+ /// How the holes are laid out. Default: staggered.
+ #[serde(default)]
+ pub pattern: Option<PerforationPattern>,
+ /// The sheet metal body. Default: the newest sheet.
+ #[serde(default)]
+ pub body: Option<String>,
+ #[serde(flatten, deserialize_with = "feature_common")]
+ pub common: FeatureCommon,
+}
+
+/// Add hems: the sheet folded back on itself along edges. `participants` changes nothing.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct HemParams {
+ /// The edges to hem.
+ pub edges: SheetPoints,
+ /// The hem's length, to its outer face.
+ pub length: LengthExpr,
+ /// The gap inside the hem (its inner radius). Default: the sheet's rule's hem gap.
+ #[serde(default)]
+ pub gap: Option<LengthExpr>,
+ /// Hem to the other side. Default: false.
+ #[serde(default)]
+ pub flip: Option<bool>,
+ /// The sheet metal body. Default: the sheet with an edge nearest the first point.
+ #[serde(default)]
+ pub body: Option<String>,
+ #[serde(flatten, deserialize_with = "feature_common")]
+ pub common: FeatureCommon,
+}
+
+/// Fold a sheet along a line on its top or bottom face: a sketch line (followed when the sketch
+/// changes) or two points. The bend zone comes out of the sheet, so the flat pattern keeps its
+/// size. `participants` changes nothing.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct FoldParams {
+ /// The fold line's two ends, instead of `sketch` and `curve`.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "FoldPoints")]
+ pub points: Option<FoldPoints>,
+ /// The sketch holding the fold line, by id or name. Required unless `points` is given;
+ /// ignored then.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SketchRef")]
+ pub sketch: Option<SketchRef>,
+ /// The fold line: a line of `sketch`, by id. Required unless `points` is given; ignored then.
+ #[serde(default)]
+ pub curve: Option<String>,
+ /// The bend angle. Default: 90 deg.
+ #[serde(default)]
+ pub angle: Option<AngleExpr>,
+ /// The inner bend radius. Default: the sheet's rule's.
+ #[serde(default)]
+ pub radius: Option<LengthExpr>,
+ /// Where the line sits in the bend zone: its centre (centerline), its start or end, from the
+ /// side that stays, or the mould line (mould: where the outer faces meet). Default:
+ /// centerline.
+ #[serde(default)]
+ pub position: Option<FoldPosition>,
+ /// A point on the side that stays, on the sheet. Default: the larger side (on a flange, the
+ /// side toward its own bend).
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "FixedPoint")]
+ pub fixed: Option<FixedPoint>,
+ /// Fold the other way. Default: false.
+ #[serde(default)]
+ pub flip: Option<bool>,
+ /// The sheet metal body. Default: the sheet with an edge nearest the line's middle.
+ #[serde(default)]
+ pub body: Option<String>,
+ #[serde(flatten, deserialize_with = "feature_common")]
+ pub common: FeatureCommon,
+}
+
+/// Unfold every bend of a sheet (`sheet.unfold`), or fold an unfolded sheet back
+/// (`sheet.refold`). `participants` changes nothing.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct UnfoldParams {
+ /// The sheet metal body. Default: the last folded sheet (unfold) or the last unfolded one
+ /// (refold).
+ #[serde(default)]
+ pub body: Option<String>,
+ #[serde(flatten, deserialize_with = "feature_common")]
+ pub common: FeatureCommon,
+}
+
+/// Turn a body into sheet metal. Without `bends`, a plate of even thickness: its large flat face
+/// becomes the sheet, holes become cut-outs and recesses in one face up to half the thickness
+/// deep (an engraved label) become pockets. With `bends`, a solid or shelled body: `face` stays
+/// put and the flat faces reached from it across those edges become the sheet; a shell keeps its
+/// thickness, a solid takes the rule's inward, and edges between two of those faces that are no
+/// bends are cut open with the rule's gap. `participants` changes nothing.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct ConvertParams {
+ /// The body to convert.
+ pub body: String,
+ /// Its large flat face (a plate), or the face that stays put (with `bends`).
+ pub face: FaceRef,
+ /// The sharp edges that become bends of the rule's radius at their virtual sharp. A point in
+ /// the middle of a chamfer between two faces, or on a bend modelled with its radius (a
+ /// cylinder tangent to two flat faces, either skin), makes it one bend. Default: none (a
+ /// plate).
+ #[serde(default)]
+ pub bends: Option<SheetPoints>,
+ /// The sheet metal rule, by name. Default: the active rule. A plate keeps its own thickness.
+ #[serde(default)]
+ pub rule: Option<String>,
+ #[serde(flatten, deserialize_with = "feature_common")]
+ pub common: FeatureCommon,
+}
+
+#[cfg(test)]
+#[path = "sheet_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/sheet_tests.rs b/crates/engine/src/schema/sheet_tests.rs
new file mode 100644
index 0000000000..069904a051
--- /dev/null
+++ b/crates/engine/src/schema/sheet_tests.rs
@@ -0,0 +1,357 @@
+use serde::de::DeserializeOwned;
+use serde_json::{Value, json};
+
+use super::{
+ ConvertParams, FixedPoint, FlangeEdges, FlangeParams, FlangePosition, FlangeTypeParam, FoldParams, FoldPoints, FoldPosition, HeightFromParam,
+ HemParams, PerforateParams, PerforationPattern, ReliefShapeParam, SheetPoints, ThenSteps, UnfoldParams,
+};
+use crate::Session;
+use crate::schema::features::FeatureResult;
+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
+use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
+
+/// The built-in rule's name, which a design without rules uses.
+const STEEL: &str = "Steel (mm)";
+
+/// A command's own keys and `FeatureCommon`'s, sorted.
+fn keys(own: &[&'static str]) -> Vec<&'static str> {
+ let mut k = own.to_vec();
+ k.extend(["body_name", "body_names", "name", "participants"]);
+ k.sort_unstable();
+ k
+}
+
+/// A 100 × 60 sheet of the default rule (2.5 thick) from sketch `Base`, and a 100 × 60 × 2.5
+/// box `Plate` beside it.
+fn sheet() -> Session {
+ let mut s = Session::default();
+ for (id, p) in [
+ ("sketch.create", json!({"plane": "XY", "name": "Base"})),
+ ("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [100, 60]})),
+ ("sketch.finish", json!({})),
+ ("sheet.flange", json!({"sketch": "Base"})),
+ ("solid.box", json!({"length": 100, "width": 60, "height": 2.5, "corner": [0, 100, 0], "body_name": "Plate"})),
+ ] {
+ if let Err(e) = s.execute(id, &p) {
+ panic!("{id}: {e}");
+ }
+ }
+ s
+}
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(
+ input_schema_for::<FlangeParams>(),
+ &keys(&[
+ "angle",
+ "body",
+ "corner_relief",
+ "corner_relief_shape",
+ "curves",
+ "distance",
+ "edges",
+ "flip",
+ "height",
+ "height_from",
+ "position",
+ "profiles",
+ "radius",
+ "reverse",
+ "rule",
+ "sketch",
+ "then",
+ "type",
+ ]),
+ );
+ assert_keys(input_schema_for::<PerforateParams>(), &keys(&["body", "diameter", "margin", "pattern", "pitch"]));
+ assert_keys(input_schema_for::<HemParams>(), &keys(&["body", "edges", "flip", "gap", "length"]));
+ assert_keys(input_schema_for::<FoldParams>(), &keys(&["angle", "body", "curve", "fixed", "flip", "points", "position", "radius", "sketch"]));
+ assert_keys(input_schema_for::<UnfoldParams>(), &keys(&["body"]));
+ assert_keys(input_schema_for::<ConvertParams>(), &keys(&["bends", "body", "face", "rule"]));
+}
+
+fn parse<T: DeserializeOwned>(v: Value) -> Option<T> {
+ serde_json::from_value(v).ok()
+}
+
+/// Whether `T` accepts `v` and its schema agrees.
+fn takes<T: DeserializeOwned + schemars::JsonSchema>(v: &Value) -> bool {
+ let schema = input_schema_for::<T>();
+ let schema = schema.as_value();
+ let accepted = parse::<T>(v.clone()).is_some();
+ assert_eq!(conforms(schema, schema, v), accepted, "{v}: the schema and the reader disagree");
+ accepted
+}
+
+/// The value types accept what the handlers' readers accept, and their schemas agree (apart
+/// from the word types' patterns, which the test validator doesn't read: those are checked on
+/// the readers alone).
+#[test]
+fn the_value_types_match_the_readers() {
+ let many = |n: usize| Value::Array(vec![json!([1, 2, 3]); n]);
+ for (v, ok) in [
+ (json!([[1, 2, 3]]), true),
+ (json!([{"x": 1, "y": 2, "z": 3}, {"point": [1, 2, 3]}, {"point": {"x": 1, "y": 2, "z": 3}, "body": "B"}]), true),
+ (many(1000), true),
+ (many(1001), false),
+ (json!([]), false),
+ (json!([[1, 2]]), false),
+ (json!([{"point": [1, 2]}]), false),
+ (json!([[1e10, 0, 0]]), false),
+ (json!(5), false),
+ (json!(null), false),
+ ] {
+ assert_eq!(takes::<SheetPoints>(&v), ok, "{v}");
+ assert_eq!(parse::<SheetPoints>(v.clone()).map(|p| p.0), crate::cmd::sheet_points(Some(&v)).ok(), "{v}");
+ }
+ for (v, ok) in [
+ (json!([[1, 2, 3], {"x": 1, "y": 2, "z": 3}]), true),
+ (json!([{"point": [1, 2, 3]}, {"point": [1, 2, 3], "angle": "30 deg", "height": 5}, {"point": [1, 2, 3], "angle": null}]), true),
+ (many(1000), true),
+ (many(1001), false),
+ (json!([{"x": 1, "y": 2, "z": 3, "point": [1, 2, 3]}]), false),
+ (json!([{"x": 1, "y": 2, "z": 3, "angle": 30}]), false),
+ (json!([{"angle": 30}]), false),
+ (json!([{"point": [1, 2, 3], "depth": 1}]), false),
+ (json!([{"point": [1, 2, 3], "angle": true}]), false),
+ (json!([{"point": [1, 2]}]), false),
+ (json!([[1, 2]]), false),
+ (json!([]), false),
+ (json!(null), false),
+ ] {
+ assert_eq!(takes::<FlangeEdges>(&v), ok, "{v}");
+ }
+ let bends = |n: usize| Value::Array(vec![json!({"height": 10}); n]);
+ for (v, ok) in [
+ (json!([{"height": 10}]), true),
+ (json!([{"height": 10, "angle": "45 deg", "flip": true}, {"height": "5 mm", "angle": null, "flip": null}]), true),
+ (json!([]), true),
+ (bends(16), true),
+ (bends(17), false),
+ (json!([{"angle": 30}]), false),
+ (json!([{"height": 10, "depth": 1}]), false),
+ (json!([{"height": 10, "flip": "yes"}]), false),
+ (json!([5]), false),
+ (json!(5), false),
+ ] {
+ assert_eq!(takes::<ThenSteps>(&v), ok, "{v}");
+ assert_eq!(parse::<ThenSteps>(v.clone()).map(|t| t.0), crate::cmd::then_list(Some(&v)).ok(), "{v}");
+ }
+ // The handler reads a bend's `angle` that is no expression as left out (90°); the type
+ // refuses it, which is what warn and strict report.
+ for angle in [json!(true), json!([45])] {
+ let v = json!([{"height": 10, "angle": angle}]);
+ assert!(!takes::<ThenSteps>(&v), "{v}");
+ assert_eq!(crate::cmd::then_list(Some(&v)), crate::cmd::then_list(Some(&json!([{"height": 10}]))), "{v}");
+ }
+ for (v, ok) in [
+ (json!([[0, 0, 0], [1, 1, 1]]), true),
+ (json!([{"x": 0, "y": 0, "z": 0}, [1, 1, 1]]), true),
+ (json!([[0, 0, 0]]), false),
+ (json!([[0, 0, 0], [1, 1]]), false),
+ (json!([[0, 0, 0], [1, 1, 1], [2, 2, 2]]), false),
+ (json!(null), false),
+ ] {
+ assert_eq!(takes::<FoldPoints>(&v), ok, "{v}");
+ }
+ for (v, ok) in [(json!([1, 2, 3]), true), (json!({"x": 1, "y": 2, "z": 3}), true), (json!([1, 2]), false), (json!(null), false)] {
+ assert_eq!(takes::<FixedPoint>(&v), ok, "{v}");
+ }
+ for (v, ok) in [
+ (json!("staggered"), true),
+ (json!("square"), true),
+ (json!("Square"), false),
+ (json!("hex"), false),
+ (json!(5), false),
+ (json!(null), false),
+ ] {
+ assert_eq!(takes::<PerforationPattern>(&v), ok, "{v}");
+ }
+ let words = |accepted: &[&str], refused: &[Value], read: &dyn Fn(Value) -> bool| {
+ for w in accepted {
+ assert!(read(json!(w)), "{w}");
+ }
+ for v in refused {
+ assert!(!read(v.clone()), "{v}");
+ }
+ };
+ words(&["base", "Edge", "CONTOUR"], &[json!("sideways"), json!(""), json!(5)], &|v| parse::<FlangeTypeParam>(v).is_some());
+ words(
+ &["inside", "Outside", "MIDDLE", "bend_outside", "Material_Outside", "TANGENT"],
+ &[json!("mid"), json!(" inside"), json!("material outside"), json!(""), json!(3)],
+ &|v| parse::<FlangePosition>(v).is_some(),
+ );
+ words(&["outer", " Inner ", "TANGENT"], &[json!("sharp"), json!(""), json!(5)], &|v| parse::<HeightFromParam>(v).is_some());
+ words(&["centerline", "Start", "END", "mould", "Mold"], &[json!("center"), json!("side"), json!(null)], &|v| parse::<FoldPosition>(v).is_some());
+ words(&["notch", " Round ", "rectangular", "TEAR"], &[json!("oval"), json!(""), json!(5)], &|v| parse::<ReliefShapeParam>(v).is_some());
+}
+
+#[test]
+fn strict_keeps_todays_errors() {
+ assert_strict_keeps_todays_errors(&[
+ ("sheet.flange", json!({"type": "sideways"})),
+ ("sheet.flange", json!({"type": "EDGEWAYS", "edges": [[0, 0, 0]], "height": 10})),
+ ("sheet.flange", json!({"edges": [], "height": 10})),
+ ("sheet.flange", json!({"edges": 5, "height": 10})),
+ ("sheet.flange", json!({"edges": [[0, 0]], "height": 10})),
+ ("sheet.flange", json!({"edges": [[0, 0, 0], {"point": [0, 0, 0], "depth": 3}], "height": 10})),
+ ("sheet.flange", json!({"edges": [{"point": [0, 0]}], "height": 10})),
+ ("sheet.flange", json!({"edges": [{"point": [0, 0, 0], "angle": true}], "height": 10})),
+ ("sheet.flange", json!({"edges": [{"point": [0, 0, 0], "height": " "}], "height": 10})),
+ ("sheet.flange", json!({"edges": [[0, 0, 0]], "height": 10, "position": "nowhere"})),
+ ("sheet.flange", json!({"edges": [[0, 0, 0]], "height": 10, "height_from": "sharp"})),
+ ("sheet.flange", json!({"edges": [[0, 0, 0]], "height": 10, "then": 5})),
+ ("sheet.flange", json!({"edges": [[0, 0, 0]], "height": 10, "then": [{"angle": 30}]})),
+ ("sheet.flange", json!({"edges": [[0, 0, 0]], "height": 10, "then": [{"height": 5, "turn": 1}]})),
+ ("sheet.perforate", json!({"diameter": 2, "pitch": 5, "pattern": "hex"})),
+ ("sheet.perforate", json!({"diameter": 2, "pitch": 5, "pattern": "Square"})),
+ ("sheet.hem", json!({"edges": [], "length": 5})),
+ ("sheet.hem", json!({"edges": 5, "length": 5})),
+ ("sheet.hem", json!({"edges": null, "length": 5})),
+ ("sheet.hem", json!({"edges": [[1, 2]], "length": 5})),
+ ("sheet.fold", json!({"points": [[0, 0, 0]]})),
+ ("sheet.fold", json!({"points": [[0, 0, 0], [1, 2]]})),
+ ("sheet.fold", json!({"points": null})),
+ ("sheet.fold", json!({"points": [[0, 0, 0], [10, 0, 0]], "position": "side"})),
+ ("sheet.fold", json!({"points": [[0, 0, 0], [10, 0, 0]], "fixed": [1, 2]})),
+ ("sheet.fold", json!({"points": [[0, 0, 0], [10, 0, 0]], "fixed": null})),
+ ("sheet.fold", json!({"sketch": true, "curve": "l1"})),
+ ("sheet.convert", json!({"body": "Nothing", "face": [0, 0, 0]})),
+ ]);
+ // Calls that get past the handler's first checks only on a sheet.
+ for (id, p) in [
+ ("sheet.flange", json!({"edges": [[50, 0, 2.5]], "height": 20, "corner_relief_shape": "oval"})),
+ ("sheet.flange", json!({"edges": [[50, 0, 2.5]], "height": 20, "corner_relief_shape": 5})),
+ ("sheet.convert", json!({"body": "Plate", "face": [50, 130, 2.5], "bends": []})),
+ ("sheet.convert", json!({"body": "Plate", "face": [50, 130, 2.5], "bends": [[1, 2]]})),
+ ("sheet.convert", json!({"body": "Plate", "face": ""})),
+ ("sheet.convert", json!({"body": "Plate", "face": true})),
+ ] {
+ let error = |level: ParamCheck| {
+ let mut s = sheet();
+ s.param_check = level;
+ s.execute(id, &p).err().map(|e| e.to_string())
+ };
+ let off = error(ParamCheck::Off);
+ assert!(off.is_some(), "{p} should fail today");
+ assert_eq!(error(ParamCheck::Strict), off, "{p}");
+ }
+}
+
+/// A rule's value given to a flange or a bent conversion is refused either way: by the handler,
+/// which points to `sheet.manage_rules`, and in strict as a key the command doesn't take.
+#[test]
+fn rule_values_are_refused_with_the_check_off_and_in_strict() {
+ for (id, p, key) in [
+ ("sheet.flange", json!({"sketch": "Base", "thickness": 2}), "thickness"),
+ ("sheet.flange", json!({"edges": [[50, 0, 2.5]], "height": 20, "k_factor": 0.4}), "k_factor"),
+ ("sheet.convert", json!({"body": "Plate", "face": [50, 130, 2.5], "bends": [[50, 100, 1.25]], "bend_radius": 2}), "bend_radius"),
+ ] {
+ let error = |level: ParamCheck| {
+ let mut s = sheet();
+ s.param_check = level;
+ s.execute(id, &p).err().map(|e| e.to_string()).unwrap_or_default()
+ };
+ let off = error(ParamCheck::Off);
+ assert!(off.contains(&format!("`{key}` is not a {id} parameter: the sheet metal rule sets it")), "{p}: {off}");
+ assert!(error(ParamCheck::Strict).contains(&format!("unknown key `{key}`")), "{p}");
+ }
+}
+
+/// A further bend's `angle` that is no expression: with the check off the flange bends it 90°,
+/// as before; warn reports it and strict refuses it.
+#[test]
+fn a_bend_angle_that_is_no_expression_is_reported() {
+ let p = json!({"edges": [[0, 30, 2.5]], "height": 12, "then": [{"height": 8, "angle": true}]});
+ let want = "then[0]: `angle` must be a number or an expression";
+ let run = |level: ParamCheck| {
+ let mut s = sheet();
+ s.param_check = level;
+ s.execute("sheet.flange", &p)
+ };
+ let off = run(ParamCheck::Off).unwrap_or_else(|e| panic!("{e}"));
+ assert_eq!(off.get("param_warnings"), None, "{off}");
+ let warn = run(ParamCheck::Warn).unwrap_or_else(|e| panic!("{e}"));
+ assert_eq!(warn["param_warnings"], json!([want]), "{warn}");
+ let strict = run(ParamCheck::Strict).err().map(|e| e.to_string()).unwrap_or_default();
+ assert!(strict.ends_with(want), "{strict}");
+}
+
+#[test]
+fn replies_match_the_output_schema() {
+ let schema = output_schema_for::<FeatureResult>();
+ let schema = schema.as_value();
+ let check = |r: Value| assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");
+ let warn = || {
+ let mut s = sheet();
+ s.param_check = ParamCheck::Warn;
+ s
+ };
+ let ok = |s: &mut Session, id: &str, p: Value| {
+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ assert_eq!(r.get("param_warnings"), None, "{id} {p}: {r}");
+ r
+ };
+ // Each form each command takes, in Warn, without warnings.
+ let mut s = warn();
+ for (id, p) in [
+ ("sheet.flange", json!({"edges": [[50, 0, 2.5]], "height": 20})),
+ ("sheet.hem", json!({"edges": [[50, 0, 20]], "length": 8, "gap": 1, "flip": false})),
+ (
+ "sheet.flange",
+ json!({"type": "Edge", "edges": [{"point": [100, 30, 2.5], "angle": "60 deg", "height": null}], "height": 15, "angle": 90,
+ "radius": 2, "position": "OUTSIDE", "flip": true, "corner_relief_shape": " round ", "corner_relief": 3, "name": "Side"}),
+ ),
+ ("sheet.perforate", json!({"diameter": 2, "pitch": 5, "margin": 3, "pattern": "square"})),
+ (
+ "sheet.flange",
+ json!({"edges": [[0, 30, 2.5]], "height": 12, "position": "material_outside", "height_from": "inner",
+ "then": [{"height": 8}, {"height": 6, "angle": "45 deg", "flip": true}], "name": "Chain"}),
+ ),
+ ("sheet.unfold", json!({})),
+ ("sheet.refold", json!({"name": "Back"})),
+ ("sheet.flange", json!({"type": "BASE", "sketch": "Base", "profiles": "all", "rule": STEEL, "flip": true, "body_names": ["Second"]})),
+ ("sheet.unfold", json!({"body": "Second"})),
+ ("sheet.refold", json!({"body": "Second"})),
+ ("sheet.convert", json!({"body": "Plate", "face": [50, 130, 2.5], "bends": null, "rule": STEEL, "body_name": "Plated"})),
+ ] {
+ check(ok(&mut s, id, p));
+ }
+ let mut s = warn();
+ for (id, p) in [
+ ("sheet.fold", json!({"points": [[60, 0, 2.5], [60, 60, 2.5]], "angle": "45 deg", "radius": 1, "position": "Mould", "fixed": [10, 30, 2.5]})),
+ ("sheet.perforate", json!({"diameter": 2, "pitch": 6})),
+ ] {
+ check(ok(&mut s, id, p));
+ }
+ let mut s = warn();
+ for (id, p) in [
+ ("sketch.create", json!({"plane": "XY", "offset": 2.5, "name": "FoldLine"})),
+ ("sketch.line", json!({"points": [[40, 0], [40, 60]], "ids": ["fl"]})),
+ ("sketch.finish", json!({})),
+ ] {
+ ok(&mut s, id, p);
+ }
+ let body = s.model.state().sheets.first().map(|sh| sh.body.clone()).unwrap_or_default();
+ check(ok(&mut s, "sheet.fold", json!({"sketch": "FoldLine", "curve": "fl", "position": "start", "flip": true, "body": body})));
+ let mut s = warn();
+ for (id, p) in [
+ ("sketch.create", json!({"plane": {"origin": [0, 0, 0], "x_dir": [1, 0, 0], "y_dir": [0, 0, -1]}, "name": "Contour"})),
+ ("sketch.line", json!({"points": [[0, 0], [40, 0], [40, -30], [70, -30]], "ids": ["l1", "l2", "l3"]})),
+ ("sketch.finish", json!({})),
+ ] {
+ ok(&mut s, id, p);
+ }
+ check(ok(
+ &mut s,
+ "sheet.flange",
+ json!({"sketch": "Contour", "curves": ["l1", "l2", "l3"], "distance": 50, "reverse": true, "flip": true, "rule": STEEL}),
+ ));
+ check(ok(&mut s, "sheet.flange", json!({"type": "contour", "sketch": "Contour", "curves": "l1", "distance": "20 mm", "body_name": "Strip"})));
+ // A misspelt key: the call runs, and the reply carrying its warning still matches.
+ let mut s = warn();
+ let r = s.execute("sheet.unfold", &json!({"bodies": "x"})).unwrap_or_else(|e| panic!("{e}"));
+ assert!(r.get("param_warnings").is_some(), "{r}");
+ check(r);
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index 9f504448f6..20c8f7fdfb 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -249,19 +249,12 @@ render.status
select.clear
select.set
selection.delete
-sheet.convert
sheet.export_bend_table
sheet.export_dxf
-sheet.flange
sheet.flat_pattern
-sheet.fold
-sheet.hem
sheet.manage_rules
sheet.path_flange
-sheet.perforate
-sheet.refold
sheet.rules
-sheet.unfold
sketch.arc.center_point
sketch.arc.tangent
sketch.arc.three_point