SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Combine: input and output schemas (part of #2829) (#12918)
austin62jake96a6629ed1c3
diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rsindex 9ecae7a246..a93b3aa325 100644--- a/crates/engine/src/cmd/features.rs+++ b/crates/engine/src/cmd/features.rs@@ -13,8 +13,9 @@ use solidcraft_geom::prelude::*;use super::{CommandSpec, not_in_sketch};use crate::params::{UNKNOWN_COMMAND, bad, bool_, expr, expr_problem, req_expr, str_, string_list, string_list_or_default, vec2, vec3};use crate::schema::features::{- AppliedRadius, BoundingSolidParams, BoxParams, ConeParams, CylinderParams, ExtrudeParams, FeatureNotice, FeatureResult, FilletParams,- FilletResult, NoticeAction, OffsetPlaneParams, PipeParams, PlaneAtAngleParams, ScaleParams, SphereParams, TorusParams,+ AppliedRadius, BoundingSolidParams, BoxParams, CombineParams, CombineResult, ConeParams, CylinderParams, ExtrudeParams, FeatureNotice,+ FeatureResult, FilletParams, FilletResult, NoticeAction, OffsetPlaneParams, PipeParams, PlaneAtAngleParams, ScaleParams, SphereParams,+ TorusParams,};use crate::schema::{TypedContract, output_schema_for};use crate::{EngineError, Result, Session};@@ -28,6 +29,7 @@ const CONE_CONTRACT: TypedContract<ConeParams> = TypedContract::new();const PIPE_CONTRACT: TypedContract<PipeParams> = TypedContract::new();const BOUNDING_SOLID_CONTRACT: TypedContract<BoundingSolidParams> = TypedContract::new();const SCALE_CONTRACT: TypedContract<ScaleParams> = TypedContract::new();+const COMBINE_CONTRACT: TypedContract<CombineParams> = TypedContract::new();const OFFSET_PLANE_CONTRACT: TypedContract<OffsetPlaneParams> = TypedContract::new();const PLANE_AT_ANGLE_CONTRACT: TypedContract<PlaneAtAngleParams> = TypedContract::new();const FILLET_CONTRACT: TypedContract<FilletParams> = TypedContract::new();@@ -87,7 +89,12 @@ pub static COMMANDS: &[CommandSpec] = &[.output(output_schema_for::<FilletResult>).params("edges: [[x,y,z] point on edge | {body, index}] ; radius: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is rounded with it; false: exactly the picked edges); body?; type?: constant|curvature (alias g2: curvature-continuous quintic between planar faces along straight edges, one planar end face at each end (including sloped ends); radius sets the equivalent circular setback, not constant curvature; exact fit only)|chord (radius is the width across)|variable (radius at the end nearest start, radius2 at the other; one end may be 0, where the round closes to the corner)|spline (the radius along the edge is a clamped B-spline from the end nearest start: radius is its first control radius, radii the rest, knots its knot vector from 0 to 1; one end may be 0); radius2?; start?: [x,y,z]; radii?: [expr, …]; knots?: [number, …]; mid?: [[position 0…1 from start, radius expr], …] (variable radii between the ends); smooth?: bool (smooth instead of straight between the radii); corner?: rolling|g2 (rolling, the default: the corners where three blended edges meet are pieces of the rolling ball's sphere, tangent to each blend; a curvature round's corners are always g2 patches, between its own sections; g2: each corner where three or more rounded edges meet, and every edge there is rounded, is set back (1.5 × the radius along each edge unless `setbacks` names it) and filled with a patch meeting the rounds and the faces round it to the second order (curvature-continuous seams, clear of the points where a round's section ends on a face), constant-radius exact fillets only, refused where it cannot be built); setbacks?: [{vertex: [x,y,z], distance: expr}, …] (corner setbacks: the corner at the vertex nearest `vertex`, where every edge meeting it is rounded, starts its patch `distance` along each of those edges from the vertex, past where the rounds would meet (past the radius at a square corner), so the rounds blend through a larger patch; one distance for all of a corner's edges; constant-radius exact fillets only; with `corner: g2`, the G2 patch's corners); turn?: mitre|swept (where two rounds turn round a sharp, straight, convex side edge square to both on a plane, such as the rounds along a boss's base at its upright edges: mitre, the default, runs them on to meet in a mitre; swept ends them at the side edge and fills the corner with their section revolved about it, a torus; swept takes type: constant, corner: rolling, no setbacks and fit: exact or reduce, and is refused with the reason where the rounds are unequal or the side edge is concave, curved or tangent); fit?: exact|reduce|taper (exact, the default: a radius too large for the geometry around the edges is refused, naming the largest that fits; reduce: where it doesn't fit it is reduced to the largest that does, one radius for edges sharing a face; the smallest used is returned as `radius_applied`, each edge's as `radii_applied: [{edge: [x,y,z], radius}]`, and noted in the feature's warning; taper: along each straight edge between planar faces where it doesn't fit, the radius follows the room there as a smooth spline, down to 0 where a face closes to a point, noted in the feature's warning)"),CommandSpec::new("solid.chamfer", "Chamfer", chamfer).at("SOLID", "MODIFY").icon("chamfer").params("edges: [[x,y,z] | {body, index}] ; distance: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is cut with it; false: exactly the picked edges); distance2?: expr (along the second face) | angle?: expr (from the first face); flip?: bool (which face is first: by default the one facing up most); body?"),- CommandSpec::new("solid.combine", "Combine", combine).at("SOLID", "MODIFY").icon("combine").params("target: body; tools: [body]; operation?: join|cut|intersect; touching?: separate|one_body (what a join makes of pieces that share no face: separate, the default, makes each piece that touches another only along an edge or at a point a body of its own and keeps pieces that touch nothing in one body; one_body keeps every piece in one body); keep_tools?: bool; new_component?: bool (the result goes into a new component; component_name?)"),+ CommandSpec::new("solid.combine", "Combine", crate::checked!("solid.combine", combine))+ .at("SOLID", "MODIFY")+ .icon("combine")+ .contract(&COMBINE_CONTRACT)+ .output(output_schema_for::<CombineResult>)+ .params("target: body; tools: [body]; operation?: join|cut|intersect; touching?: separate|one_body (what a join makes of pieces that share no face: separate, the default, makes each piece that touches another only along an edge or at a point a body of its own and keeps pieces that touch nothing in one body; one_body keeps every piece in one body); keep_tools?: bool; new_component?: bool (the result goes into a new component; component_name?)"),CommandSpec::new("solid.pattern.rectangular", "Rectangular Pattern", pattern_rect).at("SOLID", "CREATE").icon("pattern_rect")diff --git a/crates/engine/src/schema/features.rs b/crates/engine/src/schema/features.rsindex 305c6191ed..ec2ebdcbe7 100644--- a/crates/engine/src/schema/features.rs+++ b/crates/engine/src/schema/features.rs@@ -5,16 +5,20 @@//! fields whose descriptions say so; the contracts don't check the combinations, and the//! handlers ignore those keys otherwise.-use schemars::JsonSchema;-use serde::{Deserialize, Serialize};+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};+use serde::de::Error as _;+use serde::{Deserialize, Deserializer, Serialize};use serde_json::Value;+use super::check::whole;+use super::config::NameList;use super::types::{- AngleExpr, AxisDir, AxisLine, ConventionParam, DirectionParam, EdgeRefs, ExtentKeyword, ExtrudeOperation, FacesParam, FeatureCommon,- FilletCornerParam, FilletFitParam, FilletTurnParam, FilletTypeParam, FromPoint, GeoRefParam, IdOrName, LengthExpr, NumberExpr, OperationParam,- PlaneCommon, PlaneOrFace, Point3, PointExpr3, ProfilesParam, ScaleFactors, SketchRef, StringList, ThinSideParam, ToPoint, TouchingParam,- feature_common, present,+ AngleExpr, AxisDir, AxisLine, CombineOperation, ConventionParam, DirectionParam, EdgeRefs, ExtentKeyword, ExtrudeOperation, FacesParam,+ FeatureCommon, FilletCornerParam, FilletFitParam, FilletTurnParam, FilletTypeParam, FromPoint, GeoRefParam, IdOrName, LengthExpr, NumberExpr,+ OperationParam, PlaneCommon, PlaneOrFace, Point3, PointExpr3, ProfilesParam, ScaleFactors, SketchRef, StringList, ThinSideParam, ToPoint,+ TouchingParam, feature_common, present,};+use crate::params::MAX_STRING_LIST;/// Add a box primitive.#[derive(Debug, Deserialize, JsonSchema)]@@ -398,6 +402,80 @@ pub struct ScaleParams {pub participants: Option<StringList>,}+/// Combine bodies: join the tool bodies to the target, cut them from it, or keep only the space+/// the target shares with them. Whether each body exists stays the handler's to check.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct CombineParams {+ /// The body the tools combine with, by name.+ #[serde(deserialize_with = "target_body")]+ #[schemars(with = "String")]+ pub target: String,+ #[serde(deserialize_with = "tool_bodies")]+ #[schemars(schema_with = "tool_bodies_schema")]+ pub tools: NameList,+ /// What the tools do to the target. Default: join.+ #[serde(default)]+ pub operation: Option<CombineOperation>,+ /// What a join makes of pieces that share no face. Default: separate.+ #[serde(default)]+ pub touching: Option<TouchingParam>,+ /// Keep the tool bodies as they are. Default: false (the combine uses them up).+ #[serde(default)]+ pub keep_tools: Option<bool>,+ /// Move the result into a new component, made for it. Default: false.+ #[serde(default)]+ pub new_component: Option<bool>,+ /// With `new_component`: the new component's name. Default: the target's name and+ /// " Combined".+ #[serde(default)]+ pub component_name: Option<String>,+ #[serde(flatten, deserialize_with = "feature_common")]+ pub common: FeatureCommon,+}++/// `target`: a body name, with the handler's message for anything else, `null` included.+fn target_body<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {+ match Value::deserialize(d)? {+ Value::String(name) => Ok(name),+ _ => Err(D::Error::custom(whole("`target` must be a body name"))),+ }+}++/// The handler's message for no tools.+const NO_TOOLS: &str = "`tools` must list bodies";++/// `tools`: a name or a list of names, as `params::string_list` reads it and with its messages,+/// and at least one. An empty list, and `null` (which the reader reads as none), get the+/// handler's message for no tools.+fn tool_bodies<'de, D: Deserializer<'de>>(d: D) -> Result<NameList, D::Error> {+ match Value::deserialize(d)? {+ Value::Null => Err(D::Error::custom(whole(NO_TOOLS))),+ v => match NameList::deserialize(v).map_err(D::Error::custom)? {+ NameList(names) if names.is_empty() => Err(D::Error::custom(whole(NO_TOOLS))),+ names => Ok(names),+ },+ }+}++fn tool_bodies_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "The bodies combined with the target, by name: a name, or a list of one or more names (at most 10000).",+ "anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": MAX_STRING_LIST}]+ })+}++/// What `solid.combine` returns: a feature command's reply, with the new component's id when+/// `new_component` moved the result into one.+#[derive(Debug, Serialize, JsonSchema)]+pub struct CombineResult {+ #[serde(flatten)]+ pub feature: FeatureResult,+ /// With `new_component`: the id of the component the result went into.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub component: Option<u64>,+}+/// Add a construction plane parallel to `base`: `offset` away along its normal, or through a/// point.#[derive(Debug, Deserialize, JsonSchema)]diff --git a/crates/engine/src/schema/features_tests.rs b/crates/engine/src/schema/features_tests.rsindex 9ca9a18cd4..3f09b0d59c 100644--- a/crates/engine/src/schema/features_tests.rs+++ b/crates/engine/src/schema/features_tests.rs@@ -1,8 +1,10 @@+use std::collections::BTreeSet;+use serde_json::{Value, json};use super::{- BoundingSolidParams, BoxParams, ConeParams, CylinderParams, ExtrudeParams, FeatureResult, FilletParams, FilletResult, OffsetPlaneParams,- PipeParams, PlaneAtAngleParams, ScaleParams, SphereParams, TorusParams,+ BoundingSolidParams, BoxParams, CombineParams, CombineResult, ConeParams, CylinderParams, ExtrudeParams, FeatureResult, FilletParams,+ FilletResult, OffsetPlaneParams, PipeParams, PlaneAtAngleParams, ScaleParams, SphereParams, TorusParams,};use crate::Session;use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms, sketch_rectangle};@@ -113,6 +115,26 @@ fn schemas_and_the_key_check_agree() {);}+#[test]+fn combine_schema_and_the_key_check_agree() {+ assert_keys(+ input_schema_for::<CombineParams>(),+ &[+ "body_name",+ "body_names",+ "component_name",+ "keep_tools",+ "name",+ "new_component",+ "operation",+ "participants",+ "target",+ "tools",+ "touching",+ ],+ );+}+#[test]fn strict_keeps_todays_errors() {assert_strict_keeps_todays_errors(&[@@ -188,9 +210,90 @@ fn strict_keeps_todays_errors() {("solid.fillet", json!({"edges": [[0, 0, 0]], "radius": 1, "corner": "round"})),("solid.fillet", json!({"edges": [], "radius": 1})),("solid.fillet", json!({"edges": 5, "radius": 1})),+ // #12917: Combine's keys of the wrong shape; bodies the design lacks stay the handler's+ // to refuse.+ ("solid.combine", json!({"target": 5, "tools": ["B"]})),+ ("solid.combine", json!({"target": null, "tools": ["B"]})),+ ("solid.combine", json!({"target": "A", "tools": []})),+ ("solid.combine", json!({"target": "A", "tools": null})),+ ("solid.combine", json!({"target": "A", "tools": 5})),+ ("solid.combine", json!({"target": "A", "tools": ["B", 1]})),+ ("solid.combine", json!({"target": "A", "tools": vec!["B"; 10_001]})),+ ("solid.combine", json!({"target": "A", "tools": ["B"], "operation": "new"})),+ ("solid.combine", json!({"target": "A", "tools": ["B"], "operation": "bogus"})),+ ("solid.combine", json!({"target": "A", "tools": ["B"]})),]);}+/// #12917: Combine's contract takes what its input schema allows: each call's check finds no+/// issue exactly when the call matches the schema. Left out: an operation spelt in capitals,+/// which the check takes as the handler does and the schema's enum doesn't.+#[test]+fn combine_check_takes_what_the_schema_allows() {+ let schema = input_schema_for::<CombineParams>();+ let schema = schema.as_value();+ for (p, takes) in [+ (json!({"target": "A", "tools": ["B"]}), true),+ (json!({"target": "A", "tools": "B", "operation": "cut", "keep_tools": true}), true),+ (+ json!({"target": "A", "tools": ["B", "C"], "operation": "intersection", "touching": "one_body", "new_component": true, "component_name": "Merged", "name": "C1", "body_name": "X"}),+ true,+ ),+ (json!({"target": "A", "tools": ["B"], "operation": null, "touching": null, "keep_tools": null, "component_name": null}), true),+ (json!({"target": 5, "tools": ["B"]}), false),+ (json!({"target": null, "tools": ["B"]}), false),+ (json!({"target": "A"}), false),+ (json!({"target": "A", "tools": []}), false),+ (json!({"target": "A", "tools": null}), false),+ (json!({"target": "A", "tools": [1]}), false),+ (json!({"target": "A", "tools": ["B"], "operation": "new"}), false),+ (json!({"target": "A", "tools": ["B"], "operation": 5}), false),+ (json!({"target": "A", "tools": ["B"], "touching": "glued"}), false),+ (json!({"target": "A", "tools": ["B"], "keep_tools": "yes"}), false),+ (json!({"target": "A", "tools": ["B"], "targets": ["A"]}), false),+ ] {+ let issues = crate::schema::issues("solid.combine", &p);+ assert_eq!(issues.is_empty(), takes, "{p}: {issues:?}");+ assert_eq!(conforms(schema, schema, &p), takes, "{p}");+ }+}++/// #12917: Combine replies with `CombineResult`, with the keys it gave before, in each of its+/// forms: a join, a cut keeping its tool, an intersect, a join into one body, and a join into a+/// new component (which adds the component's id). In Warn, without warnings, so its contract+/// takes each call.+#[test]+fn combine_replies_with_combine_result() {+ let schema = output_schema_for::<CombineResult>();+ let schema = schema.as_value();+ let before = BTreeSet::from(["feature", "name", "bodies", "created_bodies", "changed_bodies", "removed_bodies", "warning", "ms"]);+ for p in [+ json!({"target": "A", "tools": ["B"]}),+ json!({"target": "A", "tools": "B", "operation": "cut", "keep_tools": true}),+ json!({"target": "A", "tools": ["B"], "operation": "intersect", "name": "Common"}),+ json!({"target": "A", "tools": ["B"], "operation": "union", "touching": "one_body"}),+ json!({"target": "A", "tools": ["B"], "new_component": true, "component_name": "Merged"}),+ ] {+ // Two 10 mm cubes, `B` overlapping `A` by 5 mm along each axis; made again for each call.+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ for (corner, body) in [([0, 0, 0], "A"), ([5, 5, 5], "B")] {+ let box_ = json!({"length": 10, "width": 10, "height": 10, "corner": corner, "body_name": body});+ s.execute("solid.box", &box_).unwrap_or_else(|e| panic!("{e}"));+ }+ let r = s.execute("solid.combine", &p).unwrap_or_else(|e| panic!("{p}: {e}"));+ assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");+ assert!(r.get("param_warnings").is_none(), "{p}: {r}");+ let keys: BTreeSet<&str> = r.as_object().into_iter().flatten().map(|(k, _)| k.as_str()).collect();+ let mut expected = before.clone();+ if p.get("new_component").is_some() {+ assert!(r["component"].is_u64(), "{p}: {r}");+ expected.insert("component");+ }+ assert_eq!(keys, expected, "{p}: {r}");+ assert!(r["changed_bodies"].as_array().is_some_and(|changed| changed.contains(&json!("A"))), "{p}: {r}");+ }+}+#[test]fn feature_result_serializes_like_the_old_reply() {for (warning, ms) in [(None, None), (Some("a Boolean needed a retry".to_string()), Some(12.5)), (None, Some(0.0)), (None, Some(1.0 / 3.0))] {diff --git a/crates/engine/src/schema/types.rs b/crates/engine/src/schema/types.rsindex 9bff4188ca..4c9ebceef3 100644--- a/crates/engine/src/schema/types.rs+++ b/crates/engine/src/schema/types.rs@@ -625,6 +625,41 @@ impl JsonSchema for ExtrudeOperation {}}+/// What Combine's tools do to its target, as `features::combine` reads `operation`: a spelling+/// of join, cut or intersect that `Operation::parse` accepts. A spelling of new, or any other+/// word, gets the handler's message.+#[derive(Clone, Debug, PartialEq)]+pub struct CombineOperation(pub Operation);++/// The handler's message for an operation Combine doesn't take.+const COMBINE_OPERATION_MESSAGE: &str = "operation must be join, cut or intersect";++/// Combine's operation for `s`: `Operation::parse`'s, but not new.+fn combine_operation(s: &str) -> Option<Operation> {+ Operation::parse(s).filter(|o| *o != Operation::NewBody)+}++impl<'de> Deserialize<'de> for CombineOperation {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let ok = |s: &str| combine_operation(s).is_some();+ let s = string_matching(d, ok, "join, cut or intersect", |_| whole(COMBINE_OPERATION_MESSAGE))?;+ combine_operation(&s).map(CombineOperation).ok_or_else(|| D::Error::custom(whole(COMBINE_OPERATION_MESSAGE)))+ }+}++impl JsonSchema for CombineOperation {+ fn schema_name() -> Cow<'static, str> {+ "CombineOperation".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ let values: Vec<&str> = OPERATIONS.iter().copied().filter(|s| combine_operation(s).is_some()).collect();+ enum_schema(+ &values,+ "What the tools do to the target: join (the default), cut or intersect. The others are aliases. Matching ignores case, spaces, '_' and '-'.",+ )+ }+}+const DIRECTIONS: &[&str] = &["positive", "negative", "symmetric", "one_side", "reverse", "flip"];/// Extrude's direction, as `extent_param` reads it (lowercased, not trimmed).diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex 95944e26da..c2fa952fec 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -185,7 +185,6 @@ sketch.toggle_drivensolid.alignsolid.chamfersolid.coil-solid.combinesolid.draftsolid.embosssolid.hole