Skip to content

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

Typed contracts for the cylinder, sphere, torus, cone, pipe, bounding solid and scale (#2829) (#7145)

Matthew Knutsonae530bff4413
diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs
index 58668a8a3e..e260ef51d6 100644
--- a/crates/engine/src/cmd/features.rs
+++ b/crates/engine/src/cmd/features.rs
@@ -11,12 +11,21 @@ use solidcraft_geom::Vec3;
use super::{CommandSpec, not_in_sketch};
use crate::params::{bad, bool_, expr, expr_problem, req_expr, str_, string_list, vec2, vec3};
-use crate::schema::features::{BoxParams, ExtrudeParams, FeatureResult};
+use crate::schema::features::{
+ BoundingSolidParams, BoxParams, ConeParams, CylinderParams, ExtrudeParams, FeatureResult, PipeParams, ScaleParams, SphereParams, TorusParams,
+};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
const BOX_CONTRACT: TypedContract<BoxParams> = TypedContract::new();
const EXTRUDE_CONTRACT: TypedContract<ExtrudeParams> = TypedContract::new();
+const CYLINDER_CONTRACT: TypedContract<CylinderParams> = TypedContract::new();
+const SPHERE_CONTRACT: TypedContract<SphereParams> = TypedContract::new();
+const TORUS_CONTRACT: TypedContract<TorusParams> = TypedContract::new();
+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();
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("solid.extrude", "Extrude", crate::checked!("solid.extrude", extrude))
@@ -41,10 +50,30 @@ pub static COMMANDS: &[CommandSpec] = &[
.contract(&BOX_CONTRACT)
.output(output_schema_for::<FeatureResult>)
.params("length, width, height: expr; corner?: [x,y,z] | center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"),
- CommandSpec::new("solid.cylinder", "Cylinder", prim_cylinder).at("SOLID", "CREATE").icon("cylinder").params("radius | diameter, height: expr; base?: [x,y,z] (centre of the bottom: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); operation?, targets?: [body], name?, body_name?"),
- CommandSpec::new("solid.sphere", "Sphere", prim_sphere).at("SOLID", "CREATE").icon("sphere").params("radius | diameter: expr; center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"),
- CommandSpec::new("solid.torus", "Torus", prim_torus).at("SOLID", "CREATE").icon("torus").params("major, minor: expr (radii); center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"),
- CommandSpec::new("solid.cone", "Cone", prim_cone).at("SOLID", "CREATE").icon("cone").params("radius | diameter, height: expr (the base circle, and the top's distance along the axis; a negative height goes the other way); top_radius? | top_diameter?: expr (the top circle; default 0: a full cone ending in an apex); base?: [x,y,z] (centre of the base circle: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); operation?, targets?: [body], name?, body_name?"),
+ CommandSpec::new("solid.cylinder", "Cylinder", crate::checked!("solid.cylinder", prim_cylinder))
+ .at("SOLID", "CREATE")
+ .icon("cylinder")
+ .contract(&CYLINDER_CONTRACT)
+ .output(output_schema_for::<FeatureResult>)
+ .params("radius | diameter, height: expr; base?: [x,y,z] (centre of the bottom: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); operation?, targets?: [body], name?, body_name?"),
+ CommandSpec::new("solid.sphere", "Sphere", crate::checked!("solid.sphere", prim_sphere))
+ .at("SOLID", "CREATE")
+ .icon("sphere")
+ .contract(&SPHERE_CONTRACT)
+ .output(output_schema_for::<FeatureResult>)
+ .params("radius | diameter: expr; center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"),
+ CommandSpec::new("solid.torus", "Torus", crate::checked!("solid.torus", prim_torus))
+ .at("SOLID", "CREATE")
+ .icon("torus")
+ .contract(&TORUS_CONTRACT)
+ .output(output_schema_for::<FeatureResult>)
+ .params("major, minor: expr (radii); center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"),
+ CommandSpec::new("solid.cone", "Cone", crate::checked!("solid.cone", prim_cone))
+ .at("SOLID", "CREATE")
+ .icon("cone")
+ .contract(&CONE_CONTRACT)
+ .output(output_schema_for::<FeatureResult>)
+ .params("radius | diameter, height: expr (the base circle, and the top's distance along the axis; a negative height goes the other way); top_radius? | top_diameter?: expr (the top circle; default 0: a full cone ending in an apex); base?: [x,y,z] (centre of the base circle: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); operation?, targets?: [body], name?, body_name?"),
CommandSpec::new("solid.fillet", "Fillet", fillet)
.at("SOLID", "MODIFY")
.icon("fillet")
@@ -70,17 +99,23 @@ pub static COMMANDS: &[CommandSpec] = &[
.icon("hole")
.key("H")
.params("position: [x,y,z] on a face (numbers, or length expressions the hole follows) | sketch + points: [sketch point ids] (one hole each, perpendicular to the sketch, into the material on whichever side of the sketch plane it is) | sketch alone (every sketch point: standalone points and circle centres); flip?: bool (sketch points: drill to the other side); single?: bool (with one sketch point: a Single hole that follows the point, drilled into the face there); direction?: [x,y,z] (default: into the face, against its outward normal; one that leaves the face is mirrored into it; ignored with sketch points unless single); diameter | thread (a tapped hole: metric major minus pitch or tabulated UNC/UNF, G or Rp cut-tap drill) | clearance: \"M6\" with fit?: close|normal|loose (ISO 273); depth? (default through all) | to?: [x,y,z] (To Object: drill to that face or point); references?: [{edge: [x,y,z] on a straight edge of the face, distance: expr}] (at most two; the centre goes that far from each edge's line, in the face's plane, and follows the edges; with a numeric position only); type?: simple|drilled|counterbore|countersink; tip_angle?; cb_diameter?, cb_depth?; cs_diameter?, cs_angle?; thread?: \"M6\" or \"1/4-20 UNC\" (cosmetic); handedness?: right|left (default right, needs thread for left); thread_depth?: positive length independent of drill depth (default: full useful cylindrical wall; must fit that wall); targets?: [body] (the bodies to drill; holes at the points of a sketch on a body's face default to that body, found along the holes' direction on it alone; explicit targets or participants override, [\"*\"] every body)"),
- CommandSpec::new("solid.pipe", "Pipe", pipe)
+ CommandSpec::new("solid.pipe", "Pipe", crate::checked!("solid.pipe", pipe))
.at("SOLID", "CREATE")
.icon("pipe")
+ .contract(&PIPE_CONTRACT)
+ .output(output_schema_for::<FeatureResult>)
.params("path_sketch: sketch; path: [curve ids in order]; diameter: expr; wall?: expr (hollow); operation?, targets?, name?, body_name?"),
- CommandSpec::new("solid.bounding_solid", "Bounding Solid", bounding_solid)
+ CommandSpec::new("solid.bounding_solid", "Bounding Solid", crate::checked!("solid.bounding_solid", bounding_solid))
.at("SOLID", "CREATE")
.icon("bounding_solid")
+ .contract(&BOUNDING_SOLID_CONTRACT)
+ .output(output_schema_for::<FeatureResult>)
.params("bodies?: [names] (default: all); margin?: expr; name?, body_name?"),
- CommandSpec::new("solid.scale", "Scale", scale)
+ CommandSpec::new("solid.scale", "Scale", crate::checked!("solid.scale", scale))
.at("SOLID", "MODIFY")
.icon("scale")
+ .contract(&SCALE_CONTRACT)
+ .output(output_schema_for::<FeatureResult>)
.params("bodies: [names]; factor: expr | factors: [x, y, z] exprs; origin?: [x,y,z]"),
CommandSpec::new("face.delete", "Delete Face", delete_face)
.at("SOLID", "MODIFY")
@@ -1296,13 +1331,21 @@ pub(super) fn point_param(s: &Session, p: &Value, key: &str, cmd: &str) -> Resul
pub(super) fn axis_dir_param(p: &Value, cmd: &str) -> Result<Vec3> {
match p.get("axis") {
None => Ok(Vec3::Z),
- Some(Value::String(a)) => match a.trim().to_ascii_uppercase().as_str() {
+ Some(v) => axis_dir_form(v).map_err(|why| bad(cmd, why)),
+ }
+}
+
+/// What [`axis_dir_param`] reads a given `axis` as, without the design: X, Y or Z (trimmed, any
+/// case), else a non-zero `[x, y, z]`, normalized.
+pub(crate) fn axis_dir_form(v: &Value) -> std::result::Result<Vec3, &'static str> {
+ match v {
+ Value::String(a) => match a.trim().to_ascii_uppercase().as_str() {
"X" => Ok(Vec3::X),
"Y" => Ok(Vec3::Y),
"Z" => Ok(Vec3::Z),
- _ => Err(bad(cmd, "`axis` must be X, Y, Z or [x, y, z]")),
+ _ => Err("`axis` must be X, Y, Z or [x, y, z]"),
},
- Some(v) => vec3(v).and_then(|a| a.normalized()).ok_or_else(|| bad(cmd, "`axis` must be X, Y, Z or a non-zero [x, y, z]")),
+ v => vec3(v).and_then(|a| a.normalized()).ok_or("`axis` must be X, Y, Z or a non-zero [x, y, z]"),
}
}
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index cf4e472072..29ed3a3924 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -37,7 +37,7 @@ mod features;
mod features_more;
pub(crate) use face::{FaceRefForm, face_ref_form};
pub(crate) use features::profiles as feature_profiles;
-pub(crate) use features::{EdgeRefForm, edge_ref_form, sketch_key};
+pub(crate) use features::{EdgeRefForm, axis_dir_form, edge_ref_form, sketch_key};
pub use features::{auto_operation, extrude_reach};
pub use sketch_import::drawing_import_command;
pub use sketch_modify::{extend_arc_preview, extend_preview, trim_piece};
diff --git a/crates/engine/src/schema/features.rs b/crates/engine/src/schema/features.rs
index 81286aa334..78a04f321e 100644
--- a/crates/engine/src/schema/features.rs
+++ b/crates/engine/src/schema/features.rs
@@ -9,8 +9,9 @@ use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use super::types::{
- AngleExpr, ConventionParam, DirectionParam, ExtentKeyword, ExtrudeOperation, FacesParam, FromPoint, IdOrName, LengthExpr, OperationParam, Point3,
- PointExpr3, ProfilesParam, StringList, ThinSideParam, ToPoint, present,
+ AngleExpr, AxisDir, ConventionParam, DirectionParam, ExtentKeyword, ExtrudeOperation, FacesParam, FeatureCommon, FromPoint, IdOrName, LengthExpr,
+ NumberExpr, OperationParam, Point3, PointExpr3, ProfilesParam, ScaleFactors, SketchRef, StringList, ThinSideParam, ToPoint, feature_common,
+ present,
};
/// Add a box primitive.
@@ -35,10 +36,12 @@ pub struct BoxParams {
/// How the box combines with existing bodies. Default: new.
#[serde(default)]
pub operation: Option<OperationParam>,
- /// The bodies a join, cut or intersect works on. Default: the bodies the box meets.
+ /// The bodies a join, cut or intersect works on. Default: every body in the active
+ /// component (an intersect removes those the box doesn't meet). Ignored when
+ /// `participants` lists bodies.
#[serde(default)]
pub targets: Option<StringList>,
- /// The bodies taking part (the same as `targets` for a primitive).
+ /// The bodies a join, cut or intersect works on, in place of `targets`.
#[serde(default)]
pub participants: Option<StringList>,
/// The feature's name in the timeline.
@@ -166,6 +169,198 @@ pub struct ExtrudeParams {
pub thickness2: Option<LengthExpr>,
}
+/// Add a cylinder primitive.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct CylinderParams {
+ /// The radius. Give it or `diameter`; when both are given, `radius` is used.
+ #[serde(default)]
+ pub radius: Option<LengthExpr>,
+ /// The diameter, instead of `radius`.
+ #[serde(default)]
+ pub diameter: Option<LengthExpr>,
+ /// The height, along `axis`.
+ pub height: LengthExpr,
+ /// The centre of the bottom face. Default: the origin.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointExpr3")]
+ pub base: Option<PointExpr3>,
+ /// The direction from the bottom to the top. Default: Z.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "AxisDir")]
+ pub axis: Option<AxisDir>,
+ /// How the cylinder combines with existing bodies. Default: new.
+ #[serde(default)]
+ pub operation: Option<OperationParam>,
+ /// The bodies a join, cut or intersect works on. Default: every body in the active
+ /// component (an intersect removes those the cylinder doesn't meet).
+ /// Ignored when `participants` lists bodies.
+ #[serde(default)]
+ pub targets: Option<StringList>,
+ #[serde(flatten, deserialize_with = "feature_common")]
+ pub common: FeatureCommon,
+}
+
+/// Add a sphere primitive.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct SphereParams {
+ /// The radius. Give it or `diameter`; when both are given, `radius` is used.
+ #[serde(default)]
+ pub radius: Option<LengthExpr>,
+ /// The diameter, instead of `radius`.
+ #[serde(default)]
+ pub diameter: Option<LengthExpr>,
+ /// The centre. Default: the origin.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointExpr3")]
+ pub center: Option<PointExpr3>,
+ /// How the sphere combines with existing bodies. Default: new.
+ #[serde(default)]
+ pub operation: Option<OperationParam>,
+ /// The bodies a join, cut or intersect works on. Default: every body in the active
+ /// component (an intersect removes those the sphere doesn't meet).
+ /// Ignored when `participants` lists bodies.
+ #[serde(default)]
+ pub targets: Option<StringList>,
+ #[serde(flatten, deserialize_with = "feature_common")]
+ pub common: FeatureCommon,
+}
+
+/// Add a torus primitive, around the Z axis.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct TorusParams {
+ /// The major radius: from the centre to the middle of the ring.
+ pub major: LengthExpr,
+ /// The minor radius: of the ring's cross-section, above 0 and less than `major`.
+ pub minor: LengthExpr,
+ /// The centre. Default: the origin.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointExpr3")]
+ pub center: Option<PointExpr3>,
+ /// How the torus combines with existing bodies. Default: new.
+ #[serde(default)]
+ pub operation: Option<OperationParam>,
+ /// The bodies a join, cut or intersect works on. Default: every body in the active
+ /// component (an intersect removes those the torus doesn't meet).
+ /// Ignored when `participants` lists bodies.
+ #[serde(default)]
+ pub targets: Option<StringList>,
+ #[serde(flatten, deserialize_with = "feature_common")]
+ pub common: FeatureCommon,
+}
+
+/// Add a cone or truncated cone: the base circle and, `height` along `axis`, the top circle (a
+/// point when its radius is 1e-6 mm or less). Its radii, height and base are within 1e7 mm.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct ConeParams {
+ /// The base circle's radius, above 1e-6 mm. Give it or `diameter`; when both are given,
+ /// `radius` is used.
+ #[serde(default)]
+ pub radius: Option<LengthExpr>,
+ /// The base circle's diameter, instead of `radius`.
+ #[serde(default)]
+ pub diameter: Option<LengthExpr>,
+ /// The top circle's radius, 0 or more; up to 1e-6 mm makes a full cone ending in a point.
+ /// When both are given, `top_radius` is used. Default: 0.
+ #[serde(default)]
+ pub top_radius: Option<LengthExpr>,
+ /// The top circle's diameter, instead of `top_radius`.
+ #[serde(default)]
+ pub top_diameter: Option<LengthExpr>,
+ /// The top's distance from the base along `axis`, more than 1e-6 mm either way; a negative
+ /// height goes the other way.
+ pub height: LengthExpr,
+ /// The centre of the base circle. Default: the origin.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointExpr3")]
+ pub base: Option<PointExpr3>,
+ /// The direction `height` is measured along: from the base towards the top when `height` is
+ /// positive. Default: Z.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "AxisDir")]
+ pub axis: Option<AxisDir>,
+ /// How the cone combines with existing bodies. Default: new.
+ #[serde(default)]
+ pub operation: Option<OperationParam>,
+ /// The bodies a join, cut or intersect works on. Default: every body in the active
+ /// component (an intersect removes those the cone doesn't meet).
+ /// Ignored when `participants` lists bodies.
+ #[serde(default)]
+ pub targets: Option<StringList>,
+ #[serde(flatten, deserialize_with = "feature_common")]
+ pub common: FeatureCommon,
+}
+
+/// Add a solid tube along a path of sketch curves.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct PipeParams {
+ /// The sketch holding the path, by id or name.
+ pub path_sketch: SketchRef,
+ /// The path's curve ids, in order along the path.
+ pub path: StringList,
+ /// The tube's outside diameter.
+ pub diameter: LengthExpr,
+ /// The wall thickness, for a hollow tube: above 0 and less than half `diameter`. Default:
+ /// solid.
+ #[serde(default)]
+ pub wall: Option<LengthExpr>,
+ /// How the pipe combines with existing bodies. Default: new.
+ #[serde(default)]
+ pub operation: Option<OperationParam>,
+ /// The bodies a join, cut or intersect works on; given, they win over `participants`.
+ /// Default: `participants`, else every body in the active component (an intersect removes
+ /// those the pipe doesn't meet), or for a cut or intersect where it has none, every body.
+ #[serde(default)]
+ pub targets: Option<StringList>,
+ #[serde(flatten, deserialize_with = "feature_common")]
+ pub common: FeatureCommon,
+}
+
+/// Add a box around bodies, larger by a margin on every side.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct BoundingSolidParams {
+ /// The bodies to enclose (`participants` doesn't change which). Default: all of them.
+ #[serde(default)]
+ pub bodies: Option<StringList>,
+ /// How much larger than the bodies on every side. Default: 0.
+ #[serde(default)]
+ pub margin: Option<LengthExpr>,
+ #[serde(flatten, deserialize_with = "feature_common")]
+ pub common: FeatureCommon,
+}
+
+/// Scale bodies about a point.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct ScaleParams {
+ /// The bodies to scale.
+ pub bodies: StringList,
+ /// The same factor in every direction, above 1e-9 and below 1e6. Give it or `factors`.
+ #[serde(default)]
+ pub factor: Option<NumberExpr>,
+ /// Different factors along X, Y and Z, each above 1e-9 and below 1e6. When given, these set
+ /// the scale; a `factor` given too has no effect but must still evaluate.
+ #[serde(default)]
+ pub factors: Option<ScaleFactors>,
+ /// The point that stays where it is, in mm. Default: the origin.
+ #[serde(default)]
+ pub origin: Option<Point3>,
+ // Not `FeatureCommon`: a scale makes no body, so `body_name` and `body_names` would do nothing.
+ // `participants` stays because `timeline.redefine` passes a feature's own back.
+ /// The feature's name in the timeline.
+ #[serde(default)]
+ pub name: Option<String>,
+ /// The bodies taking part, which every feature records; each an existing body or `*`. A
+ /// scale changes only `bodies`, whatever this lists.
+ #[serde(default)]
+ pub participants: Option<StringList>,
+}
+
/// What a feature command returns.
#[derive(Debug, Serialize, JsonSchema)]
pub struct FeatureResult {
diff --git a/crates/engine/src/schema/features_tests.rs b/crates/engine/src/schema/features_tests.rs
index 4ed208cded..e3e1679bbe 100644
--- a/crates/engine/src/schema/features_tests.rs
+++ b/crates/engine/src/schema/features_tests.rs
@@ -1,6 +1,8 @@
use serde_json::{Value, json};
-use super::{BoxParams, ExtrudeParams, FeatureResult};
+use super::{
+ BoundingSolidParams, BoxParams, ConeParams, CylinderParams, ExtrudeParams, FeatureResult, PipeParams, ScaleParams, SphereParams, TorusParams,
+};
use crate::Session;
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms, sketch_rectangle};
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
@@ -45,6 +47,42 @@ fn schemas_and_the_key_check_agree() {
"to_offset",
],
);
+ assert_keys(
+ input_schema_for::<CylinderParams>(),
+ &["axis", "base", "body_name", "body_names", "diameter", "height", "name", "operation", "participants", "radius", "targets"],
+ );
+ assert_keys(
+ input_schema_for::<SphereParams>(),
+ &["body_name", "body_names", "center", "diameter", "name", "operation", "participants", "radius", "targets"],
+ );
+ assert_keys(
+ input_schema_for::<TorusParams>(),
+ &["body_name", "body_names", "center", "major", "minor", "name", "operation", "participants", "targets"],
+ );
+ assert_keys(
+ input_schema_for::<ConeParams>(),
+ &[
+ "axis",
+ "base",
+ "body_name",
+ "body_names",
+ "diameter",
+ "height",
+ "name",
+ "operation",
+ "participants",
+ "radius",
+ "targets",
+ "top_diameter",
+ "top_radius",
+ ],
+ );
+ assert_keys(
+ input_schema_for::<PipeParams>(),
+ &["body_name", "body_names", "diameter", "name", "operation", "participants", "path", "path_sketch", "targets", "wall"],
+ );
+ assert_keys(input_schema_for::<BoundingSolidParams>(), &["bodies", "body_name", "body_names", "margin", "name", "participants"]);
+ assert_keys(input_schema_for::<ScaleParams>(), &["bodies", "factor", "factors", "name", "origin", "participants"]);
}
#[test]
@@ -72,6 +110,31 @@ fn strict_keeps_todays_errors() {
("solid.extrude", json!({"distance": 5, "convention": "per_side"})),
("solid.extrude", json!({"distance": " "})),
("solid.extrude", json!({"distance": 5, "operation": "x".repeat(1000)})),
+ ("solid.cylinder", json!({"radius": 5, "height": 5, "axis": "W"})),
+ ("solid.cylinder", json!({"radius": 5, "height": 5, "axis": " w "})),
+ ("solid.cylinder", json!({"radius": 5, "height": 5, "axis": [0, 0, 0]})),
+ ("solid.cylinder", json!({"radius": 5, "height": 5, "axis": null})),
+ ("solid.cylinder", json!({"radius": 5, "height": 5, "base": [1, 2]})),
+ ("solid.cylinder", json!({"radius": 5, "height": 5, "operation": "bogus"})),
+ ("solid.cylinder", json!({"radius": 5, "height": true})),
+ ("solid.sphere", json!({"radius": 5, "center": "x"})),
+ ("solid.sphere", json!({"radius": 5, "center": null})),
+ ("solid.sphere", json!({"radius": 5, "operation": "bogus"})),
+ ("solid.torus", json!({"major": 5, "minor": 1, "center": {"x": 1, "y": 2}})),
+ ("solid.torus", json!({"major": true, "minor": 1})),
+ ("solid.torus", json!({"major": 5, "minor": 1, "operation": "bogus"})),
+ ("solid.cone", json!({"radius": 5, "height": 5, "axis": "W"})),
+ ("solid.cone", json!({"radius": 5, "height": 5, "axis": null})),
+ ("solid.cone", json!({"radius": 5, "height": 5, "base": [1, 2]})),
+ ("solid.cone", json!({"radius": 5, "height": true})),
+ ("solid.cone", json!({"radius": 5, "height": 5, "operation": "bogus"})),
+ // A `null` top radius alone is the handler's to refuse, with its message.
+ ("solid.cone", json!({"radius": 5, "height": 5, "top_radius": null})),
+ ("solid.pipe", json!({"path_sketch": true, "path": ["l1"], "diameter": 2})),
+ ("solid.pipe", json!({"path_sketch": null, "path": ["l1"], "diameter": 2})),
+ ("solid.scale", json!({"bodies": ["Body1"], "factors": [1, 2]})),
+ ("solid.scale", json!({"bodies": ["Body1"], "factors": [1, 2, 3, 4]})),
+ ("solid.scale", json!({"bodies": ["Body1"]})),
]);
}
@@ -126,3 +189,92 @@ fn replies_match_the_output_schema() {
bad.as_object_mut().map(|o| o.remove("name"));
assert!(!conforms(schema, schema, &bad), "{bad}");
}
+
+/// The feature commands converted after box and extrude answer with `FeatureResult` too, and
+/// their contracts take every form these calls use: in Warn, a contract that refused one would
+/// still run the command, so the replies are checked for warnings too.
+#[test]
+fn converted_primitives_and_body_commands_reply_with_feature_result() {
+ let schema = output_schema_for::<FeatureResult>();
+ let schema = schema.as_value();
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"));
+ let mut replies = vec![
+ run(
+ "solid.cylinder",
+ json!({"radius": 2, "diameter": 9, "height": 5, "base": [20, "0 mm", 0], "axis": " x ", "name": "Cyl", "body_name": "Cyl"}),
+ ),
+ run("solid.cylinder", json!({"diameter": 2, "height": 3, "base": [0, -20, 0], "axis": [0, 1, 0], "operation": "new body"})),
+ run(
+ "solid.cylinder",
+ json!({"radius": 1, "height": 3, "base": {"x": 0, "y": -30, "z": 0}, "axis": {"x": 0, "y": 0, "z": 1}, "body_names": ["Peg"]}),
+ ),
+ run("solid.sphere", json!({"diameter": 4, "center": {"x": 0, "y": 20, "z": 0}})),
+ run("solid.sphere", json!({"radius": 1, "center": [22, 0, 2], "operation": "union", "targets": ["Peg"], "participants": []})),
+ run("solid.sphere", json!({"radius": 1, "center": [23, 0, -2], "operation": "join", "targets": ["Peg"], "participants": ["Cyl"]})),
+ run("solid.torus", json!({"major": 5, "minor": 1, "center": [0, 0, "20 mm"], "participants": ["Peg"]})),
+ run("solid.bounding_solid", json!({"bodies": ["Cyl"], "margin": 1})),
+ run("solid.bounding_solid", json!({})),
+ run("solid.bounding_solid", json!({"bodies": "Peg", "body_name": "PegBox"})),
+ run("solid.scale", json!({"bodies": ["Cyl"], "factors": [1, 2, "1.5"], "origin": [20, 0, 0]})),
+ run("solid.scale", json!({"bodies": "Cyl", "factors": [1, 1, 2], "factor": 3})),
+ run(
+ "solid.scale",
+ json!({"bodies": "Peg", "factor": "3 / 2", "origin": {"x": 0, "y": -30, "z": 0}, "name": "Grow", "participants": ["Cyl"]}),
+ ),
+ ];
+ let sketch = run("sketch.create", json!({"plane": "XZ", "name": "Path"}));
+ let line = run("sketch.line", json!({"points": [[40, 0], [40, 30]]}));
+ let across = run("sketch.line", json!({"points": [[22, -8], [22, 8]]}));
+ run("sketch.finish", json!({}));
+ let id = sketch["sketch"].clone();
+ assert!(id.is_u64(), "{sketch}");
+ replies.push(run("solid.pipe", json!({"path_sketch": "Path", "path": line["curves"].clone(), "diameter": 4, "wall": 1, "body_name": "Tube"})));
+ replies.push(run(
+ "solid.pipe",
+ json!({"path_sketch": id, "path": across["curves"][0].clone(), "diameter": 1, "operation": "join", "targets": ["Cyl"]}),
+ ));
+ replies.push(run("solid.cone", json!({"radius": 3, "height": 6, "base": [60, 0, 0]})));
+ replies.push(run(
+ "solid.cone",
+ json!({"diameter": 6, "top_diameter": 2, "height": "-4 mm", "base": {"x": 70, "y": 0, "z": 0}, "axis": " x ", "name": "Frustum", "body_name": "Frustum"}),
+ ));
+ replies.push(run(
+ "solid.cone",
+ json!({"radius": 2, "diameter": 9, "top_radius": 1, "top_diameter": 7, "height": 5, "base": [80, "0 mm", 0], "axis": [0, 1, 0]}),
+ ));
+ replies.push(run(
+ "solid.cone",
+ json!({"radius": 2, "top_radius": null, "top_diameter": 2, "height": 3, "base": [90, 0, 0], "axis": {"x": 0, "y": 0, "z": 1}, "operation": "new body", "body_names": ["Can"]}),
+ ));
+ // The cone meets only `Frustum` but joins its target, `Can`, as the sphere above does.
+ let cone_union =
+ run("solid.cone", json!({"radius": 1, "height": 2, "base": [69, 0, 0], "operation": "union", "targets": ["Can"], "participants": []}));
+ assert_eq!(cone_union["changed_bodies"], json!(["Can"]), "{cone_union}");
+ replies.push(cone_union);
+ // Warn reports what the contract refuses and runs the command anyway.
+ let typo = run("solid.scale", json!({"bodies": "Cyl", "factor": 2, "colour": "red"}));
+ assert_eq!(typo["param_warnings"], json!(["unknown key `colour`"]));
+ // A scale makes no body, so its contract doesn't take the new body's name.
+ let no_body = run("solid.scale", json!({"bodies": "Cyl", "factor": 1, "body_name": "Big"}));
+ let warning = no_body["param_warnings"][0].as_str().unwrap_or_default();
+ assert!(warning.starts_with("unknown key `body_name`"), "{no_body}");
+ for r in replies.iter().chain([&typo, &no_body]) {
+ assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
+ }
+ for r in &replies {
+ assert!(r.get("param_warnings").is_none(), "{r}");
+ }
+ // A primitive's `targets` count when `participants` lists no bodies (the sphere meets only
+ // `Cyl` but joins `Peg`) and not when it does; a scale's `participants` don't change which
+ // bodies it scales.
+ let changed = [4, 5, 12].map(|i| replies[i]["changed_bodies"].clone());
+ assert_eq!(changed, [json!(["Peg"]), json!(["Cyl"]), json!(["Peg"])]);
+ // With `factors` given, `factor` has no effect but must still evaluate.
+ assert!(s.execute("solid.scale", &json!({"bodies": "Cyl", "factors": [1, 1, 2], "factor": "no_such_parameter"})).is_err());
+ // Without `targets`, a primitive works on every body in the component: an intersect removes
+ // the bodies it doesn't meet.
+ let r = s.execute("solid.sphere", &json!({"radius": 1, "center": [22, 0, 0], "operation": "intersect"})).unwrap_or_else(|e| panic!("{e}"));
+ let (changed, removed) = (r["changed_bodies"].as_array().cloned(), r["removed_bodies"].as_array().cloned());
+ assert!(changed.is_some_and(|c| c.contains(&json!("Bounding"))) && removed.is_some_and(|r| r.contains(&json!("Peg"))), "{r}");
+}
diff --git a/crates/engine/src/schema/tests.rs b/crates/engine/src/schema/tests.rs
index 66bfd7ff0d..3d5a3f00fa 100644
--- a/crates/engine/src/schema/tests.rs
+++ b/crates/engine/src/schema/tests.rs
@@ -27,6 +27,7 @@ fn expressions_accept_what_params_expr_accepts() {
for v in [json!(5), json!(-2.5), json!("w / 2"), json!(" 30 mm "), json!(999_999_999.0)] {
let want = crate::params::expr(&json!({ "v": v.clone() }), "v");
assert_eq!(parse::<LengthExpr>(v.clone()).map(|e| e.0), want, "{v}");
+ assert_eq!(parse::<NumberExpr>(v.clone()).map(|e| e.0), want, "{v}");
assert!(want.is_some(), "{v}");
}
let long = "x".repeat(4097);
@@ -37,6 +38,43 @@ fn expressions_accept_what_params_expr_accepts() {
assert!(crate::params::expr(&json!({ "v": v.clone() }), "v").is_none(), "{v}");
assert!(parse::<LengthExpr>(v.clone()).is_none(), "{v}");
assert!(parse::<AngleExpr>(v.clone()).is_none(), "{v}");
+ assert!(parse::<NumberExpr>(v.clone()).is_none(), "{v}");
+ }
+}
+
+/// `AxisDir` accepts what `features::axis_dir_param` reads (X, Y or Z trimmed of what Rust's
+/// `trim` removes, in any case, or a non-zero vector), and its schema agrees: its string pattern
+/// allows exactly that whitespace (`conforms` doesn't read patterns), and a schema can't refuse
+/// the zero vector. `ScaleFactors` takes exactly three numbers or expressions.
+#[test]
+fn axes_and_scale_factors_match_their_readers() {
+ let root = schemars::schema_for!(AxisDir);
+ let root = root.as_value();
+ for v in [json!("X"), json!(" y "), json!("z"), json!("\u{85}Z\u{3000}"), json!([0, 0, 1]), json!([1, 2, 3]), json!({"x": 0, "y": 1, "z": 0})] {
+ assert!(crate::cmd::axis_dir_form(&v).is_ok(), "{v}");
+ assert!(parse::<AxisDir>(v.clone()).is_some(), "{v}");
+ assert!(conforms(root, root, &v), "{v}");
+ }
+ for v in [json!("W"), json!("XY"), json!(""), json!("x\u{feff}"), json!([1, 2]), json!(null), json!(true), json!([0, 0, 0])] {
+ assert!(crate::cmd::axis_dir_form(&v).is_err(), "{v}");
+ assert!(parse::<AxisDir>(v.clone()).is_none(), "{v}");
+ if !v.is_string() {
+ assert_eq!(conforms(root, root, &v), v == json!([0, 0, 0]), "{v}");
+ }
+ }
+ // The same class as the expression schema's, whose text `the_blank_pattern_matches_trim` pins.
+ let ws = super::types::not_blank_pattern().trim_start_matches("[^").trim_end_matches(']').to_string();
+ let pattern = root.pointer("/anyOf/0/pattern").and_then(Value::as_str);
+ assert_eq!(pattern, Some(format!("^[{ws}]*[XYZxyz][{ws}]*$").as_str()));
+ let root = schemars::schema_for!(ScaleFactors);
+ let root = root.as_value();
+ for v in [json!([1, 2, 3]), json!([1, "k / 2", 2.5])] {
+ assert!(parse::<ScaleFactors>(v.clone()).is_some(), "{v}");
+ assert!(conforms(root, root, &v), "{v}");
+ }
+ for v in [json!([1, 2]), json!([1, 2, 3, 4]), json!([1, true, 2]), json!([1, "", 2]), json!("2"), json!({})] {
+ assert!(parse::<ScaleFactors>(v.clone()).is_none(), "{v}");
+ assert!(!conforms(root, root, &v), "{v}");
}
}
@@ -518,10 +556,19 @@ pub(super) fn assert_keys(schema: Schema, fields: &[&str]) {
assert_eq!(v.get("$schema").and_then(Value::as_str), Some("https://json-schema.org/draft/2020-12/schema"));
}
-/// A call that already fails gets the same error in strict as with the check off, apart from
-/// the missing-key, missing-instead-of-wrong-type, non-object, profile-index, 10,000-item and
-/// over-4-KB messages the report lists, and a list of picks where one finds nothing in the
-/// design and a later one is malformed (the handler fails on the first, strict on the second).
+/// A call with one problem that already fails gets the same error in strict as with the check
+/// off, apart from messages that differ on purpose. Chiefly: a missing key; a value the handler
+/// reads as missing where its message for a missing key says something else (a wrong type, a
+/// list none of whose items is text, blank text, a number 1e9 or more in size or text over 4 KB
+/// for an optional expression, an `extent` other than through_all); a non-object, a profile
+/// index, a list over 10,000 items, a message quoting nearly 4 KB of the caller's text or more
+/// (strict caps it); and a scale `factors` item that is blank, 1e9 or more in size, over 4 KB,
+/// or not a number or an expression (see `ScaleFactors`). A call with more than one problem can
+/// get another one named: strict and the handler look at the keys in different orders
+/// (strict's comes from `TypedContract::check` and serde), and the handler may stop first at
+/// one the contract can't see (against the design: a pick that finds nothing, a missing sketch,
+/// an expression that doesn't evaluate; one of two keys, such as `radius` or `diameter`; an
+/// empty list).
/// Each module's `strict_keeps_todays_errors` calls this with its commands' cases; each runs
/// after `sketch_rectangle`.
pub(super) fn assert_strict_keeps_todays_errors(cases: &[(&str, Value)]) {
diff --git a/crates/engine/src/schema/types.rs b/crates/engine/src/schema/types.rs
index 1aa122ac00..ed6e6b9862 100644
--- a/crates/engine/src/schema/types.rs
+++ b/crates/engine/src/schema/types.rs
@@ -41,11 +41,15 @@ pub(crate) const WHITESPACE: [(char, char); 10] = [
('\u{3000}', '\u{3000}'),
];
+/// [`WHITESPACE`] as the inside of a regex character class.
+fn whitespace_class() -> String {
+ let u = |c: char| format!("\\u{:04x}", c as u32);
+ WHITESPACE.iter().map(|&(a, b)| if a == b { u(a) } else { format!("{}-{}", u(a), u(b)) }).collect()
+}
+
/// A pattern for text that isn't blank once trimmed: a character outside [`WHITESPACE`].
pub(crate) fn not_blank_pattern() -> String {
- let u = |c: char| format!("\\u{:04x}", c as u32);
- let class: String = WHITESPACE.iter().map(|&(a, b)| if a == b { u(a) } else { format!("{}-{}", u(a), u(b)) }).collect();
- format!("[^{class}]")
+ format!("[^{}]", whitespace_class())
}
/// `v` as the only key of an object, for the helpers that read `p.get(key)`.
@@ -96,6 +100,52 @@ expr_type!(
"AngleExpr",
"An angle: a number of degrees, or an expression such as \"30 deg\" or \"a / 2\"."
);
+expr_type!(
+ /// A plain number, or an expression such as `"k / 2"`: a ratio or a factor, with no unit.
+ NumberExpr,
+ "NumberExpr",
+ "A number with no unit, or an expression such as \"k / 2\"."
+);
+
+/// Scale's `factors`: three factors, along X, Y and Z, each a [`NumberExpr`]. The handler takes
+/// any three values, reading an item that isn't text as its JSON text (`true`, `null`), and
+/// reports one that doesn't evaluate as a bad expression. Strict refuses, with this type's
+/// message, a blank item, a number of 1e9 or more in size, text over 4 KB, or one that isn't a
+/// number or an expression.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ScaleFactors(pub [NumberExpr; 3]);
+
+impl<'de> Deserialize<'de> for ScaleFactors {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Array(a) if a.len() == 3 => {
+ let factors = a.into_iter().map(|v| params::expr(&wrap(v), "v").map(NumberExpr)).collect::<Option<Vec<_>>>();
+ factors
+ .and_then(|f| <[NumberExpr; 3]>::try_from(f).ok())
+ .map(ScaleFactors)
+ .ok_or_else(|| D::Error::custom("must be three numbers or expressions"))
+ }
+ Value::Array(_) => Err(D::Error::custom(whole("`factors` must have three values"))),
+ _ => Err(D::Error::custom("must be three numbers or expressions")),
+ }
+ }
+}
+
+impl JsonSchema for ScaleFactors {
+ fn schema_name() -> Cow<'static, str> {
+ "ScaleFactors".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let f = generator.subschema_for::<NumberExpr>();
+ json_schema!({
+ "description": "Factors along X, Y and Z: three numbers or expressions.",
+ "type": "array",
+ "items": f,
+ "minItems": 3,
+ "maxItems": 3
+ })
+ }
+}
/// A point in mm: `[x, y, z]` or `{x, y, z}` of finite numbers (read by `params::vec3`).
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -194,6 +244,30 @@ impl JsonSchema for FacesParam {
}
}
+/// A direction given as an axis, as `features::axis_dir_param` reads it: X, Y or Z (trimmed, any
+/// case) or a non-zero `[x, y, z]` (or `{x, y, z}`), with its messages.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct AxisDir(pub Vec3);
+
+impl<'de> Deserialize<'de> for AxisDir {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ crate::cmd::axis_dir_form(&Value::deserialize(d)?).map(AxisDir).map_err(|why| D::Error::custom(whole(why)))
+ }
+}
+
+impl JsonSchema for AxisDir {
+ fn schema_name() -> Cow<'static, str> {
+ "AxisDir".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<Point3>();
+ json_schema!({
+ "description": "An axis: X, Y or Z (any case), or a direction [x, y, z] that isn't zero.",
+ "anyOf": [{"type": "string", "pattern": format!("^[{ws}]*[XYZxyz][{ws}]*$", ws = whitespace_class())}, point]
+ })
+ }
+}
+
/// A sketch point in mm: `[x, y]` or `{x, y}` of finite numbers (read by `params::vec2`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Point2(pub Vec2);
@@ -769,7 +843,8 @@ pub struct FeatureCommon {
/// Names for the new bodies, in order.
#[serde(default)]
pub body_names: Option<StringList>,
- /// The bodies taking part; overrides the default scope.
+ /// The bodies taking part, each an existing body or `*`; what that changes depends on the
+ /// feature.
#[serde(default)]
pub participants: Option<StringList>,
}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index a909e6d486..9f504448f6 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -371,11 +371,9 @@ sketch.trim
sketch.trim.path
solid.align
solid.boundary_fill
-solid.bounding_solid
solid.chamfer
solid.coil
solid.combine
-solid.cylinder
solid.draft
solid.emboss
solid.fillet
@@ -387,20 +385,16 @@ solid.offset_face
solid.pattern.circular
solid.pattern.path
solid.pattern.rectangular
-solid.pipe
solid.press_pull
solid.remove
solid.replace_face
solid.revolve
solid.rib
-solid.scale
solid.shell
-solid.sphere
solid.split_body
solid.split_face
solid.sweep
solid.thread
-solid.torus
solid.web
surface.blend
surface.boundary
diff --git a/docs/book/src/dev/schemas.md b/docs/book/src/dev/schemas.md
index f22c6d1492..3d3106f278 100644
--- a/docs/book/src/dev/schemas.md
+++ b/docs/book/src/dev/schemas.md
@@ -47,9 +47,13 @@ handler and everything it passes `p` to:
feature is evaluated (`crates/doc/src/eval.rs`). `participants` takes its description from
`FeatureCommon`, shared by every feature, so say what it does for this one elsewhere: where it
and another key override each other (a primitive's `targets` gives way to it; an extrude's
- `targets` overrides it), in that key's description; where it has no effect, in the summary.
- For the primitives (box, cylinder, sphere, torus) `add_feature` also reads `targets`; a new
- primitive must join the `primitive` match in `add_feature_in`, and its contract declares
+ `targets` overrides it), in that key's description; where it has no effect, in the summary or
+ in the description of the key it might seem to change (bounding solid's `bodies`). A feature
+ that makes no body (scale) declares `name` and `participants` itself instead, as `body_name`
+ and `body_names` would do nothing. It keeps `participants` because `timeline.redefine` passes
+ a feature's own back, though for a scale it changes nothing either; its own description says
+ so. For the primitives (box, cylinder, sphere, torus, cone) `add_feature` also reads `targets`;
+ a new primitive must join the `primitive` match in `add_feature_in`, and its contract declares
`targets`. The commands that combine bodies read `operation` (and usually `targets`) in their
own handlers;
- keys read around the command: `frames::to_local` reads `body` (and `face_body`) for commands
@@ -123,7 +127,8 @@ pub struct WedgeParams {
someone who has only the schema. Check what each value does where the feature is evaluated
(`crates/doc/src/eval.rs` and the kernel), not only how the handler reads it: a limit the
evaluation enforces (a torus's `minor` must be less than its `major`) or a key it ignores
- belongs in the description.
+ belongs in the description. A scale's `factor`, for one, has no effect when `factors` is
+ given, though it must still evaluate.
- **Required or optional** follows the handler: a key it can't do without is a plain field;
any other is `#[serde(default)] Option<T>`.
- **`null`:** the common readers (`str_`, `num`, `bool_`, `expr`, `string_list`) read `null` as
@@ -208,7 +213,9 @@ In the module's tests file:
and a list of names) in Warn, and check those replies have no `param_warnings`: Warn runs a
call the contract refuses anyway, so a matching reply doesn't show the contract accepts the
call. A reply that isn't an object never carries `param_warnings`; run those calls in Strict,
- where a refused call is an error.
+ where a refused call is an error. In the same file,
+ `converted_primitives_and_body_commands_reply_with_feature_result` shows the Warn and
+ no-`param_warnings` checks across several commands.
`schema_defaults_are_valid` checks the `default` of each top-level parameter on its own; a
nested type's defaults are yours to check.
@@ -238,6 +245,7 @@ calling that reader.
| Type | For | Matches |
| --- | --- | --- |
| `LengthExpr`, `AngleExpr` | a number or an expression (`"w / 2"`, `"30 deg"`) | `params::expr` |
+| `NumberExpr` | a number or an expression with no unit (a ratio, a factor) | `params::expr` |
| `Point3`, `Point2` | `[x, y, z]` / `[x, y]` or `{x, y, z}` of numbers, in mm | `params::vec3`, `params::vec2` |
| `PointExpr3` | a placement point whose coordinates may be expressions | `features::point_param` |
| `IdOrName` | a feature by id or name (extrude's `sketch`) | `features::feature_sketch` |
@@ -248,6 +256,8 @@ calling that reader.
| `FaceRefs` | the `faces` list of shell, draft, offset face, split face and `face.delete` (not `solid.replace_face`, whose messages differ) | `features::face_points` |
| `EdgeRef`, `EdgeRefs` | an edge by a point on it or `{body, index}`; fillet's and chamfer's `edges` | `features::edge_points` |
| `ProfilesParam` | which sketch profiles | `features::profiles` |
+| `ScaleFactors` | scale's `factors`: three `NumberExpr`s (strict words a bad item differently; see its doc) | `features::scale` |
+| `AxisDir` | X, Y or Z, or a non-zero `[x, y, z]` / `{x, y, z}` (cylinder's, cone's and coil's `axis`) | `features::axis_dir_form` |
| `FeatureCommon` | `name`, `body_name`, `body_names`, `participants`, flattened | `features::add_feature` |
### When no shared type fits
@@ -266,7 +276,11 @@ Add one to `types.rs`, next to the reader it mirrors:
point [x, y, z] of numbers" becomes ``"`corner` must be a point [x, y, z] of numbers"``. (Any
other message comes out as ``"`corner`: …"``.)
- Its `JsonSchema` describes the same values, with a description. Where JSON Schema can't say
- something the reader checks (ignoring case, a byte length), say it in the description.
+ something the reader checks (ignoring case, a byte length), say it in the description. A
+ pattern that allows surrounding whitespace must allow exactly what Rust's `trim` removes:
+ build it from `WHITESPACE`, as `not_blank_pattern` and `AxisDir` do, rather than writing a
+ regex's whitespace class by hand (it differs, and the escapes are easy to get wrong).
+ `conforms` doesn't read patterns, so pin the pattern's text in a test.
- Test both: values the reader accepts and refuses are accepted and refused by the type, and
they match the schema (the `conforms` helper in `schema/tests.rs`; see
`face_and_edge_refs_match_the_pick_readers`).
@@ -275,8 +289,9 @@ Add one to `types.rs`, next to the reader it mirrors:
## Checklist
-1. The contract's keys are exactly the handler's reads, including `add_feature`'s, the frame
- mapping's and `live`.
+1. The contract's keys are exactly the handler's reads, including `add_feature`'s (less
+ `body_name` and `body_names` for a feature that makes no body), the frame mapping's and
+ `live`.
2. The struct and every field have descriptions, with defaults and when a key is ignored.
3. Shared types wherever they fit; a new type calls the handler's reader and gives its message.
4. `FeatureResult` for a command that returns `add_feature`'s reply unchanged, else a reply type