SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agents and scripts: Flat Pattern, Export Bend Table and Path Flange describe their exact parameters and replies (#6581) (#12545)
MarkusRe8706d623fb7b
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rsindex 6481036a2d..85693b1e0e 100644--- a/crates/engine/src/cmd/mod.rs+++ b/crates/engine/src/cmd/mod.rs@@ -106,8 +106,8 @@ mod render_ui;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,- sheet_rule_name, then_list,+ FlangeType, ThenStep, bend_table_format, flange_edge, flange_edge_list, flange_position, flange_type, fold_points, fold_position,+ perforation_pattern, sheet_points, sheet_rule_name, then_list,};mod silhouette;mod sketch;diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rsindex 5cdce0e7a7..a42d4831ac 100644--- a/crates/engine/src/cmd/sheet.rs+++ b/crates/engine/src/cmd/sheet.rs@@ -16,8 +16,10 @@ use super::features::{add_feature, check_expr, feature_sketch, profiles, sketch_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, ListedRule, ManageRulesParams, ManageRulesResult, PerforateParams, RuleFeatureError,- RuleReply, RulesParams, RulesResult, UnfoldParams,+ BendDirection, BendTableFormat, BendTableParams, BendTableResult, ConvertParams, FlangeParams, FlatBend, FlatBore, FlatCircle, FlatPatternParams,+ FlatPatternResult, FlatPerforation, FlatPerforationPattern, FlatPocket, FlatSegment, FlatShape, FoldParams, HemParams, ListedRule,+ ManageRulesParams, ManageRulesResult, PathFlangeParams, PerforateParams, PocketSide, RuleFeatureError, RuleReply, RulesParams, RulesResult,+ UnfoldParams,};use crate::schema::{TypedContract, output_schema_for};use crate::{EngineError, Result, Session};@@ -32,6 +34,10 @@ const CONVERT_CONTRACT: TypedContract<ConvertParams> = TypedContract::new();const RULES_CONTRACT: TypedContract<RulesParams> = TypedContract::new();const MANAGE_RULES_CONTRACT: TypedContract<ManageRulesParams> = TypedContract::new();+const PATH_FLANGE_CONTRACT: TypedContract<PathFlangeParams> = TypedContract::new();+const FLAT_PATTERN_CONTRACT: TypedContract<FlatPatternParams> = TypedContract::new();+const BEND_TABLE_CONTRACT: TypedContract<BendTableParams> = TypedContract::new();+pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("sheet.flange", "Flange", crate::checked!("sheet.flange", flange)).at("SHEET METAL", "CREATE")@@ -53,7 +59,12 @@ pub static COMMANDS: &[CommandSpec] = &[Thickness, K-factor and bend radius come from the rule (sheet.manage_rules); passing them here is refused, \and so is the corner relief on a base or contour flange",),- CommandSpec::new("sheet.path_flange", "Path Flange", path_flange).at("SHEET METAL", "CREATE").icon("path_flange").params(+ CommandSpec::new("sheet.path_flange", "Path Flange", crate::checked!("sheet.path_flange", path_flange))+ .at("SHEET METAL", "CREATE")+ .icon("path_flange")+ .contract(&PATH_FLANGE_CONTRACT)+ .output(output_schema_for::<FeatureResult>)+ .params("edge: [x,y,z] on a top or bottom edge of the sheet; sketch + curves: an open chain of sketch lines drawn on a plane across \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",@@ -121,10 +132,12 @@ pub static COMMANDS: &[CommandSpec] = &[),CommandSpec::new("sheet.rules", "List Sheet Metal Rules", crate::checked!("sheet.rules", list_rules)).contract(&RULES_CONTRACT).output(output_schema_for::<RulesResult>).icon("sheet_rules").noundo().doc_only().params("→ rules with their expressions and values, and the active one"),- CommandSpec::new("sheet.flat_pattern", "Create Flat Pattern", flat_pattern)+ CommandSpec::new("sheet.flat_pattern", "Create Flat Pattern", crate::checked!("sheet.flat_pattern", flat_pattern)).at("SHEET METAL", "CREATE").icon("flat").noundo()+ .contract(&FLAT_PATTERN_CONTRACT)+ .output(output_schema_for::<FlatPatternResult>).params("body? → flat size, outline loops and cut-outs (flat coordinates, as point lists), cutout_shapes (the same cut-outs exactly, in the same order: {circle: {center, radius}} for a round hole, else {segments: [{line: [a, b]} | {arc: {center, radius, start_deg, sweep_deg}} | {polyline: [...]}]}), pockets (with their own cutout_shapes), bend lines and the bend table",),@@ -141,8 +154,10 @@ pub static COMMANDS: &[CommandSpec] = &[→ DXF (AutoCAD 2000, mm): layers OUTLINE (the outer contour), CUT (what is cut out inside it), TEXT or ETCH (letters), BEND_UP and BEND_DOWN (dashed centre lines), BEND_NOTES, \POCKET_<BOTTOM|TOP|INTERNAL>_Z<from>_TO_<to>_MM (one per side and depth) and PERFORATION; inner contours come before the outline",),- CommandSpec::new("sheet.export_bend_table", "Export Bend Table", export_bend_table).icon("bendtable")+ CommandSpec::new("sheet.export_bend_table", "Export Bend Table", crate::checked!("sheet.export_bend_table", export_bend_table)).icon("bendtable").noundo()+ .contract(&BEND_TABLE_CONTRACT)+ .output(output_schema_for::<BendTableResult>).params("body?, format?: csv|json (default csv), path? → bend table in mm and degrees, including rule and flat centre-line coordinates; angle_deg is the bend angle and included_angle_deg the angle left between the bend's sides (180° less it); a bend that cut-outs split has a row for each piece"),];@@ -734,24 +749,24 @@ fn loop_circle(lp: &solidcore_record::Loop2) -> Option<(Vec2, f64)> {/// A loop's exact shape for the flat pattern JSON: a circle, or its lines and arcs (other/// curves as point lists at the flat pattern's 0.001 mm tolerance).-fn loop_shape(lp: &solidcore_record::Loop2) -> Value {+fn loop_shape(lp: &solidcore_record::Loop2) -> FlatShape {use solidcore_record::Seg2;- let pt = |v: Vec2| json!([v.x, v.y]);+ let pt = |v: Vec2| [v.x, v.y];if let Some((center, radius)) = loop_circle(lp) {- return json!({"circle": {"center": pt(center), "radius": radius}});+ return FlatShape::Circle { circle: FlatCircle { center: pt(center), radius } };}- let segments: Vec<Value> = lp+ let segments: Vec<FlatSegment> = lp.segs.iter().map(|seg| match *seg {- Seg2::Line { a, b } => json!({"line": [pt(a), pt(b)]}),+ Seg2::Line { a, b } => FlatSegment::Line([pt(a), pt(b)]),Seg2::Arc { center, radius, start, sweep } => {- json!({"arc": {"center": pt(center), "radius": radius, "start_deg": start.to_degrees(), "sweep_deg": sweep.to_degrees()}})+ FlatSegment::Arc { center: pt(center), radius, start_deg: start.to_degrees(), sweep_deg: sweep.to_degrees() }}- ref other => json!({"polyline": other.polyline(1e-3).into_iter().map(pt).collect::<Vec<_>>()}),+ ref other => FlatSegment::Polyline(other.polyline(1e-3).into_iter().map(pt).collect()),}).collect();- json!({"segments": segments})+ FlatShape::Segments { segments }}fn flat_json(sh: &SheetBody) -> Result<Value> {@@ -759,63 +774,98 @@ fn flat_json(sh: &SheetBody) -> Result<Value> {let loops: Vec<Ring<Vec2>> = regions.iter().map(|r| r.outer.polyline(1e-3)).collect();let size = loops.iter().fold(Aabb2::EMPTY, |b, l| b.union(&l.bounds())).size();let (w, h) = (size.x, size.y);- let pt = |v: &Vec2| json!([v.x, v.y]);- let outline: Vec<Value> = loops.iter().map(|l| Value::Array(l.iter().map(pt).collect())).collect();- let holes: Vec<Value> = regions.iter().flat_map(|r| &r.holes).map(|h| Value::Array(h.polyline(1e-3).iter().map(pt).collect())).collect();- let hole_shapes: Vec<Value> = regions.iter().flat_map(|r| &r.holes).map(loop_shape).collect();- let bends: Vec<Value> = sh+ let pt = |v: &Vec2| [v.x, v.y];+ let outline: Vec<Vec<[f64; 2]>> = loops.iter().map(|l| l.iter().map(pt).collect()).collect();+ let holes: Vec<Vec<[f64; 2]>> = regions.iter().flat_map(|r| &r.holes).map(|h| h.polyline(1e-3).iter().map(pt).collect()).collect();+ let hole_shapes: Vec<FlatShape> = regions.iter().flat_map(|r| &r.holes).map(loop_shape).collect();+ let bends: Vec<FlatBend> = sh.bends().iter()- .map(|b| {- json!({"bend": b.index, "angle_deg": b.angle_deg, "included_angle_deg": b.included_angle_deg(), "radius": b.radius, "direction": if b.up { "up" } else { "down" },- "allowance": b.allowance, "length": b.length, "start": pt(&b.start), "end": pt(&b.end)})+ .map(|b| FlatBend {+ bend: b.index,+ angle_deg: b.angle_deg,+ included_angle_deg: b.included_angle_deg(),+ radius: b.radius,+ direction: if b.up { BendDirection::Up } else { BendDirection::Down },+ allowance: b.allowance,+ length: b.length,+ start: pt(&b.start),+ end: pt(&b.end),}).collect();- let pockets: Vec<Value> = sh+ let pockets: Vec<FlatPocket> = sh.machining()?.iter().map(|p| {let side = if p.z0 == 0.0 {- "bottom"+ PocketSide::Bottom} else if p.z1 == sh.t {- "top"+ PocketSide::Top} else {- "internal"+ PocketSide::Internal};- json!({"outline": p.region.outer.polyline(1e-3).iter().map(pt).collect::<Vec<_>>(),- "cutouts": p.region.holes.iter().map(|h| h.polyline(1e-3).iter().map(pt).collect::<Vec<_>>()).collect::<Vec<_>>(),- "cutout_shapes": p.region.holes.iter().map(loop_shape).collect::<Vec<_>>(),- "side": side, "depth_mm": p.z1-p.z0, "z0_mm": p.z0, "z1_mm": p.z1})+ FlatPocket {+ outline: p.region.outer.polyline(1e-3).iter().map(pt).collect(),+ cutouts: p.region.holes.iter().map(|h| h.polyline(1e-3).iter().map(pt).collect()).collect(),+ cutout_shapes: p.region.holes.iter().map(loop_shape).collect(),+ side,+ depth_mm: p.z1 - p.z0,+ z0_mm: p.z0,+ z1_mm: p.z1,+ }}).collect();// Holes drilled along a panel into its rim: drilled after cutting, not in the outline.- let bores: Vec<Value> = sh+ let bores: Vec<FlatBore> = sh.bores.iter()- .map(|b| json!({"start": [b.base.x, b.base.y, b.base.z], "axis": [b.axis.x, b.axis.y, b.axis.z], "diameter": b.radius * 2.0, "length": b.height.abs()}))+ .map(|b| FlatBore {+ start: [b.base.x, b.base.y, b.base.z],+ axis: [b.axis.x, b.axis.y, b.axis.z],+ diameter: b.radius * 2.0,+ length: b.height.abs(),+ }).collect();let mut perforations = Vec::new();for p in &sh.perforations {let n = sh.perforation_holes(p)?.len();- perforations.push(json!({"feature": p.feature, "diameter": p.diameter, "pitch": p.pitch, "margin": p.margin,- "pattern": if p.square { "square" } else { "staggered" }, "count": n,- "open_area_mm2": n as f64 * std::f64::consts::PI * (p.diameter / 2.0).powi(2)}));+ perforations.push(FlatPerforation {+ feature: p.feature,+ diameter: p.diameter,+ pitch: p.pitch,+ margin: p.margin,+ pattern: if p.square { FlatPerforationPattern::Square } else { FlatPerforationPattern::Staggered },+ count: n,+ open_area_mm2: n as f64 * std::f64::consts::PI * (p.diameter / 2.0).powi(2),+ });}- let bend_zones: Vec<Value> = sh+ let bend_zones: Vec<[f64; 4]> = sh.bend_zones().iter().map(|z| {let pts = z.outer.polyline(1e-3);let f = |g: fn(&Vec2) -> f64, m: fn(f64, f64) -> f64, s: f64| pts.iter().map(g).fold(s, m);- json!([f(|p| p.x, f64::min, f64::MAX), f(|p| p.x, f64::max, f64::MIN), f(|p| p.y, f64::min, f64::MAX), f(|p| p.y, f64::max, f64::MIN)])+ [f(|p| p.x, f64::min, f64::MAX), f(|p| p.x, f64::max, f64::MIN), f(|p| p.y, f64::min, f64::MAX), f(|p| p.y, f64::max, f64::MIN)]}).collect();- let mut out = json!({"body": sh.body, "rule": sh.rule, "thickness": sh.t, "k_factor": sh.k, "flat_size_mm": [w, h, sh.t], "outline": outline, "cutouts": holes, "cutout_shapes": hole_shapes, "pockets": pockets, "bends": bends, "unfolded": sh.flat,- "perforations": perforations, "bend_zones": bend_zones});- if !bores.is_empty() {- out["bores"] = Value::Array(bores);- }- Ok(out)+ let out = FlatPatternResult {+ body: sh.body.clone(),+ rule: sh.rule.clone(),+ thickness: sh.t,+ k_factor: sh.k,+ flat_size_mm: [w, h, sh.t],+ outline,+ cutouts: holes,+ cutout_shapes: hole_shapes,+ pockets,+ bends,+ unfolded: sh.flat,+ perforations,+ bend_zones,+ bores,+ param_warnings: Vec::new(),+ };+ serde_json::to_value(out).map_err(|e| EngineError::Other(e.to_string()))}fn flat_pattern(s: &mut Session, p: &Value) -> Result<Value> {@@ -1137,16 +1187,22 @@ fn export_dxf(s: &mut Session, p: &Value) -> Result<Value> {Ok(json!({"dxf": text, "bends": sh.bends().len()}))}+/// A bend table's `format`: csv or json, in any case.+pub(crate) fn bend_table_format(t: &str) -> Option<BendTableFormat> {+ match t.to_ascii_lowercase().as_str() {+ "csv" => Some(BendTableFormat::Csv),+ "json" => Some(BendTableFormat::Json),+ _ => None,+ }+}+fn export_bend_table(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "sheet.export_bend_table";- let format = str_(p, "format").unwrap_or("csv").to_ascii_lowercase();- if !matches!(format.as_str(), "csv" | "json") {- return Err(bad(cmd, "`format` must be csv or json"));- }+ let format = str_(p, "format").map_or(Some(BendTableFormat::Csv), bend_table_format).ok_or_else(|| bad(cmd, "`format` must be csv or json"))?;let sh = sheet_of(s, p, cmd)?;sh.flat_matches_body()?;let table = flat_json(&sh)?;- let text = if format == "json" {+ let text = if format == BendTableFormat::Json {serde_json::to_string_pretty(&table).map_err(|e| EngineError::Other(e.to_string()))?} else {// Always quote text fields: body/rule names may include commas, quotes or newlines.@@ -1176,11 +1232,14 @@ fn export_bend_table(s: &mut Session, p: &Value) -> Result<Value> {}csv};- if let Some(path) = str_(p, "path").filter(|x| !x.trim().is_empty()) {+ let bends = sh.bends().len();+ let reply = if let Some(path) = str_(p, "path").filter(|x| !x.trim().is_empty()) {solidcraft_io::vfs::write(path, text.as_bytes()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;- return Ok(json!({"path": path, "format": format, "bends": sh.bends().len()}));- }- Ok(json!({"format": format, "text": text, "bends": sh.bends().len()}))+ BendTableResult::Written { path: path.to_string(), format, bends, param_warnings: Vec::new() }+ } else {+ BendTableResult::Text { format, text, bends, param_warnings: Vec::new() }+ };+ serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string()))}#[cfg(test)]diff --git a/crates/engine/src/schema/sheet.rs b/crates/engine/src/schema/sheet.rsindex 652ceccf7c..e7cd6c8984 100644--- a/crates/engine/src/schema/sheet.rs+++ b/crates/engine/src/schema/sheet.rs@@ -1,5 +1,6 @@-//! Contracts for sheet metal feature and rule commands in `cmd/sheet.rs`. Feature commands-//! return [`FeatureResult`](super::features::FeatureResult); rule commands have their own replies.+//! Contracts for sheet metal feature, rule, flat pattern and bend table commands in+//! `cmd/sheet.rs`. Feature commands return [`FeatureResult`](super::features::FeatureResult); the+//! others have their own replies.//!//! 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@@ -752,6 +753,301 @@ pub enum ManageRulesResult {},}+/// A point in mm on a sheet edge, `[x, y, z]` or `{x, y, z}`, with a path flange's message for+/// `edge`.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct SheetEdgePoint(pub Vec3);++impl<'de> Deserialize<'de> for SheetEdgePoint {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ crate::params::vec3(&Value::deserialize(d)?).map(SheetEdgePoint).ok_or_else(|| D::Error::custom("must be a point [x, y, z] on a sheet edge"))+ }+}++impl JsonSchema for SheetEdgePoint {+ fn schema_name() -> Cow<'static, str> {+ "SheetEdgePoint".into()+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ Point3::json_schema(generator)+ }+}++/// Add a path flange: flanges along an open chain of sketch lines drawn on a plane across a+/// sheet edge, from the edge out. Each line is one flange as long as the line (to the outer face+/// from the virtual sharp) and each corner one bend, turning the way the lines turn. One+/// feature, one body. `participants` changes nothing.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct PathFlangeParams {+ /// A point on a top or bottom edge of the sheet, where the path starts.+ pub edge: SheetEdgePoint,+ /// The sketch holding the path, by id or name.+ pub sketch: SketchRef,+ /// The path's lines: 1 to 64 lines of `sketch`, by id, in one open chain, in any order. Arcs+ /// are refused.+ pub curves: StringList,+ /// The inner bend radius. Default: the sheet's rule's.+ #[serde(default)]+ pub radius: Option<LengthExpr>,+ /// The sheet metal body. Default: the sheet with an edge nearest `edge`.+ #[serde(default)]+ pub body: Option<String>,+ #[serde(flatten, deserialize_with = "feature_common")]+ pub common: FeatureCommon,+}++/// Read a sheet's flat pattern: its size, outline, cut-outs, pockets, bends and perforations, in+/// flat coordinates (mm, on the base panel's bottom face). Refused while a feature that is not+/// sheet metal (a fillet, a join) has changed the body.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct FlatPatternParams {+ /// The sheet metal body. Default: the last sheet.+ #[serde(default)]+ pub body: Option<String>,+}++/// Export a sheet's bend table: a row per bend, in mm and degrees, with the rule and the bend's+/// centre line in flat coordinates. A bend that cut-outs split has a row for each piece.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct BendTableParams {+ /// The sheet metal body. Default: the last sheet.+ #[serde(default)]+ pub body: Option<String>,+ /// csv (a header and a row per bend, quoted body and rule names, CRLF line ends) or json (the+ /// flat pattern that `sheet.flat_pattern` returns, as text). Default: csv.+ #[serde(default)]+ pub format: Option<BendTableFormatParam>,+ /// The file to write. Default (or blank): no file; the reply holds the table's text.+ #[serde(default)]+ pub path: Option<String>,+}++/// The form of a bend table.+#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, JsonSchema)]+#[serde(rename_all = "lowercase")]+pub enum BendTableFormat {+ Csv,+ Json,+}++/// A bend table's `format`, in any case (read by `sheet::bend_table_format`).+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct BendTableFormatParam(pub BendTableFormat);++impl<'de> Deserialize<'de> for BendTableFormatParam {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let v = Value::deserialize(d)?;+ v.as_str().and_then(crate::cmd::bend_table_format).map(BendTableFormatParam).ok_or_else(|| D::Error::custom("must be csv or json"))+ }+}++impl JsonSchema for BendTableFormatParam {+ fn schema_name() -> Cow<'static, str> {+ "BendTableFormat".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"description": "csv or json, in any case.", "type": "string", "pattern": "^([Cc][Ss][Vv]|[Jj][Ss][Oo][Nn])$"})+ }+}++/// A point `[x, y]` in flat coordinates, in mm.+pub type FlatPoint = [f64; 2];++/// One curve of a cut-out's exact shape.+#[derive(Debug, serde::Serialize, JsonSchema)]+#[serde(rename_all = "lowercase")]+pub enum FlatSegment {+ /// A straight line from its first point to its second.+ Line([FlatPoint; 2]),+ /// A circular arc.+ Arc {+ center: FlatPoint,+ radius: f64,+ /// Where the arc starts, in degrees counterclockwise from +X.+ start_deg: f64,+ /// How far it turns, in degrees: positive counterclockwise.+ sweep_deg: f64,+ },+ /// Any other curve (an ellipse, a spline), as points within 0.001 mm of it.+ Polyline(Vec<FlatPoint>),+}++/// A circle's centre and radius, in mm.+#[derive(Debug, serde::Serialize, JsonSchema)]+pub struct FlatCircle {+ pub center: FlatPoint,+ pub radius: f64,+}++/// A cut-out's exact shape: a whole circle, or its curves in order.+#[derive(Debug, serde::Serialize, JsonSchema)]+#[serde(untagged)]+pub enum FlatShape {+ Circle { circle: FlatCircle },+ Segments { segments: Vec<FlatSegment> },+}++/// Which side of the sheet a pocket is machined from.+#[derive(Debug, serde::Serialize, JsonSchema)]+#[serde(rename_all = "lowercase")]+pub enum PocketSide {+ /// From the flat's bottom face.+ Bottom,+ /// From its top face.+ Top,+ /// Inside the sheet, open to neither face.+ Internal,+}++/// A pocket: material machined to a depth, not through the sheet.+#[derive(Debug, serde::Serialize, JsonSchema)]+pub struct FlatPocket {+ /// Its outer contour, as points within 0.001 mm.+ pub outline: Vec<FlatPoint>,+ /// Islands inside it that keep their material, as points within 0.001 mm.+ pub cutouts: Vec<Vec<FlatPoint>>,+ /// The same islands exactly, in the same order.+ pub cutout_shapes: Vec<FlatShape>,+ pub side: PocketSide,+ /// `z1_mm` less `z0_mm`.+ pub depth_mm: f64,+ /// The pocket's bottom and top, measured from the flat's bottom face, in mm.+ pub z0_mm: f64,+ pub z1_mm: f64,+}++/// Which way a bend folds: up toward the flat's top face (+z), down toward its bottom.+#[derive(Debug, serde::Serialize, JsonSchema)]+#[serde(rename_all = "lowercase")]+pub enum BendDirection {+ Up,+ Down,+}++/// A bend of the flat pattern.+#[derive(Debug, serde::Serialize, JsonSchema)]+pub struct FlatBend {+ /// The bend's number, from 1. The stretches that cut-outs leave of one bend each have a row,+ /// with the same number.+ pub bend: usize,+ /// The bend angle, in degrees.+ pub angle_deg: f64,+ /// The angle left between the bend's sides, in degrees: 180 less `angle_deg`.+ pub included_angle_deg: f64,+ /// The inner bend radius, in mm.+ pub radius: f64,+ pub direction: BendDirection,+ /// The bend allowance (the bend zone's width in the flat), in mm.+ pub allowance: f64,+ /// The length of this stretch of the bend's centre line, in mm.+ pub length: f64,+ /// The bend's centre line, from `start` to `end`.+ pub start: FlatPoint,+ pub end: FlatPoint,+}++/// How a perforation field lays out its holes.+#[derive(Debug, serde::Serialize, JsonSchema)]+#[serde(rename_all = "lowercase")]+pub enum FlatPerforationPattern {+ /// Rows offset for a 60° pattern.+ Staggered,+ Square,+}++/// A perforation field: round holes in the flat pattern, not cut into the solid.+#[derive(Debug, serde::Serialize, JsonSchema)]+pub struct FlatPerforation {+ /// The `sheet.perforate` feature's id.+ pub feature: u64,+ /// The holes' diameter, the distance between their centres and how far they stay clear of+ /// edges, cut-outs and bends, in mm.+ pub diameter: f64,+ pub pitch: f64,+ pub margin: f64,+ pub pattern: FlatPerforationPattern,+ /// How many holes the field has.+ pub count: usize,+ /// The holes' area together, in mm².+ pub open_area_mm2: f64,+}++/// A hole drilled along a panel into its rim, drilled after cutting and not in the outline.+#[derive(Debug, serde::Serialize, JsonSchema)]+pub struct FlatBore {+ /// Where it starts, in flat coordinates with z up from the bottom face, in mm.+ pub start: [f64; 3],+ /// Its direction, a unit vector.+ pub axis: [f64; 3],+ /// Its diameter and length, in mm.+ pub diameter: f64,+ pub length: f64,+}++/// What `sheet.flat_pattern` returns: the sheet's flat pattern in flat coordinates (mm, on the+/// base panel's bottom face). The `json` form of `sheet.export_bend_table` is this as text.+#[derive(Debug, serde::Serialize, JsonSchema)]+pub struct FlatPatternResult {+ /// The sheet metal body.+ pub body: String,+ /// Its sheet metal rule, by name.+ pub rule: String,+ /// The sheet's thickness, in mm.+ pub thickness: f64,+ /// The K-factor its bends unfold with.+ pub k_factor: f64,+ /// The flat pattern's width and height (its bounding box) and its thickness, in mm.+ pub flat_size_mm: [f64; 3],+ /// The outer contours, one per piece, as points within 0.001 mm.+ pub outline: Vec<Vec<FlatPoint>>,+ /// The cut-outs through the sheet, as points within 0.001 mm.+ pub cutouts: Vec<Vec<FlatPoint>>,+ /// The same cut-outs exactly, in the same order.+ pub cutout_shapes: Vec<FlatShape>,+ pub pockets: Vec<FlatPocket>,+ pub bends: Vec<FlatBend>,+ /// Whether the sheet is unfolded now.+ pub unfolded: bool,+ pub perforations: Vec<FlatPerforation>,+ /// Each bend zone's bounding box, `[min x, max x, min y, max y]` in mm.+ pub bend_zones: Vec<[f64; 4]>,+ /// Left out when there are none.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub bores: Vec<FlatBore>,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++/// What `sheet.export_bend_table` returns: the file it wrote, or the table's text.+#[derive(Debug, serde::Serialize, JsonSchema)]+#[serde(untagged)]+pub enum BendTableResult {+ /// The table went to `path`.+ Written {+ path: String,+ format: BendTableFormat,+ /// How many rows the table has: one per bend, or per stretch of a bend that cut-outs split.+ bends: usize,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ param_warnings: Vec<String>,+ },+ /// No `path`: the table's text.+ Text {+ format: BendTableFormat,+ text: String,+ /// How many rows the table has: one per bend, or per stretch of a bend that cut-outs split.+ bends: usize,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ param_warnings: Vec<String>,+ },+}+#[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.rsindex 6a63080f28..08128db254 100644--- a/crates/engine/src/schema/sheet_tests.rs+++ b/crates/engine/src/schema/sheet_tests.rs@@ -2,8 +2,9 @@ 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,+ BendTableFormatParam, BendTableParams, BendTableResult, ConvertParams, FixedPoint, FlangeEdges, FlangeParams, FlangePosition, FlangeTypeParam,+ FlatPatternParams, FlatPatternResult, FoldParams, FoldPoints, FoldPosition, HeightFromParam, HemParams, PathFlangeParams, PerforateParams,+ PerforationPattern, ReliefShapeParam, SheetEdgePoint, SheetPoints, ThenSteps, UnfoldParams,};use crate::Session;use crate::schema::features::FeatureResult;@@ -69,6 +70,9 @@ fn schemas_and_the_key_check_agree() {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"]));+ assert_keys(input_schema_for::<PathFlangeParams>(), &keys(&["body", "curves", "edge", "radius", "sketch"]));+ assert_keys(input_schema_for::<FlatPatternParams>(), &["body"]);+ assert_keys(input_schema_for::<BendTableParams>(), &["body", "format", "path"]);}fn parse<T: DeserializeOwned>(v: Value) -> Option<T> {@@ -157,6 +161,7 @@ fn the_value_types_match_the_readers() {}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}");+ assert_eq!(takes::<SheetEdgePoint>(&v), ok, "{v}");}for (v, ok) in [(json!("staggered"), true),@@ -185,6 +190,17 @@ fn the_value_types_match_the_readers() {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());+ // A bend table's format: what the handler reads, in any case but without blanks.+ let formats = ["csv", "CSV", "Json", "jSoN"];+ words(&formats, &[json!(" csv"), json!("xml"), json!(""), json!(5), json!(null)], &|v| parse::<BendTableFormatParam>(v).is_some());+ for f in formats {+ assert!(crate::cmd::bend_table_format(f).is_some(), "{f}");+ }+ for f in [" csv", "csv ", "xml", "", "csv"] {+ assert!(crate::cmd::bend_table_format(f).is_none(), "{f}");+ }+ let format = input_schema_for::<BendTableFormatParam>();+ assert_eq!(format.as_value()["pattern"], "^([Cc][Ss][Vv]|[Jj][Ss][Oo][Nn])$");}#[test]@@ -218,6 +234,14 @@ fn strict_keeps_todays_errors() {("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]})),+ ("sheet.path_flange", json!({"edge": [1, 2], "sketch": "Path", "curves": ["p1"]})),+ ("sheet.path_flange", json!({"edge": null, "sketch": "Path", "curves": ["p1"]})),+ ("sheet.path_flange", json!({"edge": [1, 0, 20], "sketch": true, "curves": ["p1"]})),+ ("sheet.flat_pattern", json!({})),+ ("sheet.flat_pattern", json!({"body": "Nothing"})),+ ("sheet.export_bend_table", json!({"format": "xml"})),+ ("sheet.export_bend_table", json!({"format": " csv", "body": "Nothing"})),+ ("sheet.export_bend_table", json!({"format": "JSON", "body": "Nothing"})),]);// Calls that get past the handler's first checks only on a sheet.for (id, p) in [@@ -227,6 +251,10 @@ fn strict_keeps_todays_errors() {("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})),+ ("sheet.path_flange", json!({"edge": [50, 0, 2.5], "sketch": "Base", "curves": []})),+ ("sheet.path_flange", json!({"edge": [50, 0, 2.5], "sketch": "Base", "curves": vec!["l1"; 65]})),+ ("sheet.path_flange", json!({"edge": [50, 0, 2.5], "sketch": "Base", "curves": ["l1"], "radius": "2 deg"})),+ ("sheet.export_bend_table", json!({"format": "yaml"})),] {let error = |level: ParamCheck| {let mut s = sheet();@@ -491,3 +519,171 @@ fn rule_warnings_match_the_output_schema_and_strict_does_not_mutate() {assert!(conforms(schema.as_value(), schema.as_value(), &reply));}}++/// Runs `id` in `s` and returns its reply, which carries no warnings.+fn quiet(s: &mut Session, id: &str, p: Value) -> 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+}++/// The wall bracket of the path flange tests in `cmd/sheet_tests.rs`, in Warn: a 150 × 100 base+/// of a 2 mm rule with a 40 mm wall up its edge at x = 0, and the lines `p1` and `p2` of sketch+/// `Path` drawn across the wall's end edge (y = 0) at half its height.+fn path_bracket() -> Session {+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ for (id, p) in [+ (+ "sheet.manage_rules",+ json!({"name": "Demo", "thickness": "2 mm", "bend_radius": "2 mm", "gap": "0.5 mm", "k_factor": "0.4", "active": true}),+ ),+ ("sketch.create", json!({"plane": "XY", "name": "Base"})),+ ("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [150, 100]})),+ ("sketch.finish", json!({})),+ ("sheet.flange", json!({"sketch": "Base"})),+ ("sheet.flange", json!({"edges": [[0, 50, 2]], "height": 40})),+ ("sketch.create", json!({"plane": {"origin": [0, 0, 20], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "name": "Path"})),+ ("sketch.line", json!({"points": [[0, 0], [20, -20], [100, -20]], "ids": ["p1", "p2"]})),+ ("sketch.finish", json!({})),+ ] {+ quiet(&mut s, id, p);+ }+ s+}++#[test]+fn path_flange_replies_match_the_output_schema() {+ let schema = output_schema_for::<FeatureResult>();+ let schema = schema.as_value();+ // Each form, in Warn, without warnings. The path's two lines make two bends besides the+ // wall's; one line makes one.+ for (p, bends) in [+ (json!({"edge": [1, 0, 20], "sketch": "Path", "curves": ["p1", "p2"]}), 3),+ (json!({"edge": {"x": 1, "y": 0, "z": 20}, "sketch": "Path", "curves": "p1", "radius": "1 mm", "body": "?", "name": "Flap"}), 2),+ (json!({"edge": [1, 0, 20], "sketch": "Path", "curves": ["p2", "p1"], "radius": null, "body": null}), 3),+ ] {+ let mut s = path_bracket();+ let body = s.model.state().sheets.first().map(|sh| sh.body.clone()).unwrap_or_default();+ let mut p = p;+ if p["body"] == "?" {+ p["body"] = json!(body);+ }+ let r = quiet(&mut s, "sheet.path_flange", p.clone());+ assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");+ let flat = quiet(&mut s, "sheet.flat_pattern", json!({}));+ assert_eq!(flat["bends"].as_array().map(Vec::len), Some(bends), "{p}: {flat}");+ }+ // A misspelt key: the call runs, and the reply carrying its warning still matches.+ let mut s = path_bracket();+ let r = s+ .execute("sheet.path_flange", &json!({"edge": [1, 0, 20], "sketch": "Path", "curves": ["p1"], "radiuss": 1}))+ .unwrap_or_else(|e| panic!("{e}"));+ assert!(r.get("param_warnings").is_some(), "{r}");+ assert!(conforms(schema, schema, &r), "{r}");+}++/// The 100 × 60 sheet with a flange up its edge at y = 0, a 6 mm hole at (30, 30), a 1 mm deep+/// pocket from below, a perforation field and a 1.5 mm bore into its rim at x = 100; in Warn.+fn worked_sheet() -> Session {+ let mut s = sheet();+ for (id, p) in [+ ("sheet.flange", json!({"edges": [[50, 0, 2.5]], "height": 20})),+ ("solid.hole", json!({"position": [30, 30, 2.5], "direction": [0, 0, -1], "diameter": 6})),+ ("sketch.create", json!({"plane": "XY", "name": "Pocket"})),+ ("sketch.rectangle.two_point", json!({"p0": [60, 20], "p1": [70, 30]})),+ ("sketch.finish", json!({})),+ ("solid.extrude", json!({"sketch": "Pocket", "distance": 1, "operation": "cut"})),+ ("sheet.perforate", json!({"diameter": 2, "pitch": 6})),+ ("solid.hole", json!({"position": [100, 45, 1.25], "direction": [-1, 0, 0], "diameter": 1.5})),+ ] {+ if let Err(e) = s.execute(id, &p) {+ panic!("{id}: {e}");+ }+ }+ s.param_check = ParamCheck::Warn;+ s+}++#[test]+fn flat_pattern_replies_match_the_output_schema() {+ let schema = output_schema_for::<FlatPatternResult>();+ let schema = schema.as_value();+ let mut s = worked_sheet();+ let body = s.model.state().sheets.first().map(|sh| sh.body.clone()).unwrap_or_default();+ let f = quiet(&mut s, "sheet.flat_pattern", json!({}));+ assert!(conforms(schema, schema, &f), "{f} doesn't match {schema}");+ // Every part of the reply is there, from the features above.+ assert_eq!(f["body"], json!(body));+ assert_eq!(f["rule"], STEEL);+ assert_eq!(f["unfolded"], false);+ assert_eq!(f["bends"].as_array().map(Vec::len), Some(1), "{f}");+ assert_eq!((&f["bends"][0]["angle_deg"], &f["bends"][0]["included_angle_deg"]), (&json!(90.0), &json!(90.0)), "{f}");+ let circles: Vec<&Value> = f["cutout_shapes"].as_array().into_iter().flatten().filter_map(|c| c.get("circle")).collect();+ assert_eq!(circles.len(), 1, "{f}");+ assert!((circles[0]["radius"].as_f64().unwrap_or_default() - 3.0).abs() < 1e-9, "{f}");+ assert_eq!(f["pockets"].as_array().map(Vec::len), Some(1), "{f}");+ assert_eq!((&f["pockets"][0]["side"], &f["pockets"][0]["depth_mm"]), (&json!("bottom"), &json!(1.0)), "{f}");+ assert!(f["pockets"][0]["cutout_shapes"].is_array(), "{f}");+ let perforation = &f["perforations"][0];+ let count = perforation["count"].as_f64().unwrap_or_default();+ assert!(count > 0.0, "{f}");+ assert_eq!(perforation["pattern"], "staggered");+ assert!((perforation["open_area_mm2"].as_f64().unwrap_or_default() - count * std::f64::consts::PI).abs() < 1e-6, "{f}");+ assert_eq!(f["bores"].as_array().map(Vec::len), Some(1), "{f}");+ assert!((f["bores"][0]["diameter"].as_f64().unwrap_or_default() - 1.5).abs() < 1e-9, "{f}");+ assert_eq!(f["bend_zones"].as_array().map(Vec::len), Some(1), "{f}");+ // The same sheet by name, and with a null body.+ assert_eq!(quiet(&mut s, "sheet.flat_pattern", json!({"body": body})), f);+ assert_eq!(quiet(&mut s, "sheet.flat_pattern", json!({"body": null})), f);+ // Unfolded, and a plain sheet without bores, which the reply leaves out.+ quiet(&mut s, "sheet.unfold", json!({}));+ let unfolded = quiet(&mut s, "sheet.flat_pattern", json!({}));+ assert_eq!(unfolded["unfolded"], true);+ assert!(conforms(schema, schema, &unfolded), "{unfolded}");+ let mut plain = sheet();+ plain.param_check = ParamCheck::Warn;+ let r = quiet(&mut plain, "sheet.flat_pattern", json!({}));+ assert!(r.get("bores").is_none(), "{r}");+ assert!(conforms(schema, schema, &r), "{r}");+ // A misspelt key: the call runs, and the reply carrying its warning still matches.+ let r = plain.execute("sheet.flat_pattern", &json!({"bodyy": body})).unwrap_or_else(|e| panic!("{e}"));+ assert!(r.get("param_warnings").is_some(), "{r}");+ assert!(conforms(schema, schema, &r), "{r}");+}++#[test]+fn bend_table_replies_match_the_output_schema() {+ let schema = output_schema_for::<BendTableResult>();+ let schema = schema.as_value();+ let mut s = worked_sheet();+ let body = s.model.state().sheets.first().map(|sh| sh.body.clone()).unwrap_or_default();+ let flat = quiet(&mut s, "sheet.flat_pattern", json!({}));+ let rows = flat["bends"].as_array().map_or(0, Vec::len);+ let table = |s: &mut Session, p: Value| {+ let r = quiet(s, "sheet.export_bend_table", p);+ assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");+ assert_eq!(r["bends"], json!(rows), "{r}");+ r+ };+ // csv: a header and a row per bend.+ let csv = table(&mut s, json!({}));+ assert_eq!(csv["format"], "csv");+ let text = csv["text"].as_str().unwrap_or_default().to_string();+ assert_eq!(text.matches("\r\n").count(), rows + 1, "{text}");+ assert_eq!(table(&mut s, json!({"format": "CSV", "path": " ", "body": null})), csv);+ // json: the flat pattern as text.+ let json = table(&mut s, json!({"format": "Json", "body": body}));+ assert_eq!(json["format"], "json");+ assert_eq!(serde_json::from_str::<Value>(json["text"].as_str().unwrap_or_default()).ok(), Some(flat));+ // To a file: the reply names it, and the file holds the text.+ let path = solidcraft_io::vfs::temp_dir().join(format!("solidcraft-bend-table-{}.csv", std::process::id()));+ let path = path.to_string_lossy().to_string();+ let written = table(&mut s, json!({"format": null, "path": path}));+ assert_eq!((written.get("text"), &written["path"], &written["format"]), (None, &json!(path), &json!("csv")), "{written}");+ assert_eq!(std::fs::read_to_string(&path).ok(), Some(text));+ let _ = std::fs::remove_file(&path);+ // A misspelt key: the call runs, and the reply carrying its warning still matches.+ let r = s.execute("sheet.export_bend_table", &json!({"formatt": "json"})).unwrap_or_else(|e| panic!("{e}"));+ assert!(r.get("param_warnings").is_some(), "{r}");+ assert!(conforms(schema, schema, &r), "{r}");+}diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex 68ef83d206..9cb1816185 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -34,10 +34,7 @@ render.result.regraderender.scenerender.startrender.status-sheet.export_bend_tablesheet.export_dxf-sheet.flat_pattern-sheet.path_flangesketch.dimensionsketch.draw.dimensionedsketch.slot.center_to_center