SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Schemas: the rectangle and polygon sketch commands describe their parameters and replies (#13197)
0rdnungsamt1ec5eda9557c
diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rsindex 0103b491f5..144eb0901f 100644--- a/crates/engine/src/cmd/sketch.rs+++ b/crates/engine/src/cmd/sketch.rs@@ -21,7 +21,8 @@ use crate::schema::sketch_session::{};use crate::schema::sketch_shapes::{ArcCenterPointParams, ArcThreePointParams, CircleCenterParams, CircleThreePointParams, CircleTwoPointParams, Created, DrawResult, LineParams,- PointParams, PointResult,+ PointParams, PointResult, PolygonCircumscribedParams, PolygonEdgeParams, PolygonInscribedParams, PolygonResult, RectCenterParams, RectCorners,+ RectResult, RectRoundedParams, RectSides, RectThreePointParams, RectTwoPointParams, RoundedRectResult,};use crate::schema::{TypedContract, output_schema_for};use crate::{EngineError, Result, Session, SketchEntry, Snapshot};@@ -80,6 +81,13 @@ const CIRCLE_TWO_POINT_CONTRACT: TypedContract<CircleTwoPointParams> = TypedContconst CIRCLE_THREE_POINT_CONTRACT: TypedContract<CircleThreePointParams> = TypedContract::new();const ARC_THREE_POINT_CONTRACT: TypedContract<ArcThreePointParams> = TypedContract::new();const ARC_CENTER_POINT_CONTRACT: TypedContract<ArcCenterPointParams> = TypedContract::new();+const RECT_TWO_POINT_CONTRACT: TypedContract<RectTwoPointParams> = TypedContract::new();+const RECT_THREE_POINT_CONTRACT: TypedContract<RectThreePointParams> = TypedContract::new();+const RECT_ROUNDED_CONTRACT: TypedContract<RectRoundedParams> = TypedContract::new();+const RECT_CENTER_CONTRACT: TypedContract<RectCenterParams> = TypedContract::new();+const POLYGON_INSCRIBED_CONTRACT: TypedContract<PolygonInscribedParams> = TypedContract::new();+const POLYGON_CIRCUMSCRIBED_CONTRACT: TypedContract<PolygonCircumscribedParams> = TypedContract::new();+const POLYGON_EDGE_CONTRACT: TypedContract<PolygonEdgeParams> = TypedContract::new();pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("sketch.create", "Create Sketch", crate::checked!("sketch.create", create_sketch))@@ -113,26 +121,34 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("sketch.draw.dimensioned", "Draw Dimensioned Sketch Geometry", draw_dimensioned).icon("dimension").enabled(in_sketch).params(concat!("command: sketch creation command, params: object, dimensions: object of role to numeric or expression value, or `name = expression` (also `#name = expression`), which defines the user parameter `name` as sketch.dimension does (the reply's `defined` lists the names) (optional with as_drawn or locate), as_drawn?: bool (also dimension every other role of the shape at its size as drawn; a radius or diameter given takes the place of the other, as an edge polygon's side length does its radius, a circle otherwise takes its diameter, and a size the sketch already determines, such as the angle of a line inferred horizontal, is left out), locate?: bool (then place the shape from the sketch origin until nothing of it is left free: horizontal and vertical distances from the origin to its points, centres first, each kept only where it removes freedom, so a shape anchored to the origin or to placed geometry gets none; a point on an axis goes onto that axis instead of a 0 distance; the reply's located lists them); creates geometry and all driving dimensions atomically in one undo step", created_doc!())),- CommandSpec::new("sketch.rectangle.two_point", "2-Point Rectangle", rect_two_point)+ CommandSpec::new("sketch.rectangle.two_point", "2-Point Rectangle", crate::checked!("sketch.rectangle.two_point", rect_two_point)).at("SKETCH", "CREATE").icon("rect").key("R").enabled(in_sketch)+ .contract(&RECT_TWO_POINT_CONTRACT)+ .output(output_schema_for::<RectResult>).params(concat!("p0, p1: opposite corners [x,y] (a coordinate may be an expression over the design's parameters: the corner follows them); construction?. Returns sides {bottom, right, top, left} (line ids) and corners {bottom_left, bottom_right, top_right, top_left} (point ids)", connect_doc!(), created_doc!())),- CommandSpec::new("sketch.rectangle.three_point", "3-Point Rectangle", rect_three_point)+ CommandSpec::new("sketch.rectangle.three_point", "3-Point Rectangle", crate::checked!("sketch.rectangle.three_point", rect_three_point)).at("SKETCH", "CREATE").icon("rect3").enabled(in_sketch)+ .contract(&RECT_THREE_POINT_CONTRACT)+ .output(output_schema_for::<DrawResult>).params(concat!("p0, p1: first edge; p2: point on the opposite edge; construction?: bool", connect_doc!(), created_doc!())),- CommandSpec::new("sketch.rectangle.rounded", "Rounded Rectangle", rect_rounded)+ CommandSpec::new("sketch.rectangle.rounded", "Rounded Rectangle", crate::checked!("sketch.rectangle.rounded", rect_rounded)).at("SKETCH", "CREATE").icon("rect_rounded").enabled(in_sketch)+ .contract(&RECT_ROUNDED_CONTRACT)+ .output(output_schema_for::<RoundedRectResult>).params(concat!("p0, p1: opposite corners [x,y] (a coordinate may be an expression over the design's parameters: the corner follows them, as in `sketch.rectangle.two_point`); radius: expr (the corner radius, less than half the shorter side); construction?. A 2-point rectangle whose four corners are filleted alike: one radius dimension (`param`), the other arcs equal to it. Returns sides {bottom, right, top, left} (line ids) and arcs (the corner arcs: bottom-left, bottom-right, top-right, top-left)", connect_doc!(), created_doc!())),- CommandSpec::new("sketch.rectangle.center", "Center Rectangle", rect_center)+ CommandSpec::new("sketch.rectangle.center", "Center Rectangle", crate::checked!("sketch.rectangle.center", rect_center)).at("SKETCH", "CREATE").icon("rect_center").enabled(in_sketch)+ .contract(&RECT_CENTER_CONTRACT)+ .output(output_schema_for::<RectResult>).params(concat!("center, corner: [x,y] (a coordinate may be an expression over the design's parameters: the point follows them); construction?: bool. Returns sides {bottom, right, top, left} (line ids) and corners {bottom_left, bottom_right, top_right, top_left} (point ids)", connect_doc!(), created_doc!())),CommandSpec::new("sketch.circle.center", "Center Diameter Circle", crate::checked!("sketch.circle.center", circle_center)).at("SKETCH", "CREATE")@@ -168,20 +184,26 @@ pub static COMMANDS: &[CommandSpec] = &[.contract(&ARC_CENTER_POINT_CONTRACT).output(output_schema_for::<DrawResult>).params(concat!("center, start, end (counter-clockwise from start; clockwise?: bool for clockwise) | center, start, sweep: signed degrees; construction?: bool", connect_doc!(), created_doc!())),- CommandSpec::new("sketch.polygon.inscribed", "Inscribed Polygon", polygon_inscribed)+ CommandSpec::new("sketch.polygon.inscribed", "Inscribed Polygon", crate::checked!("sketch.polygon.inscribed", polygon_inscribed)).at("SKETCH", "CREATE").icon("polygon").enabled(in_sketch)+ .contract(&POLYGON_INSCRIBED_CONTRACT)+ .output(output_schema_for::<PolygonResult>).params(concat!("center, radius (to vertices), sides, angle?: deg", connect_doc!(), created_doc!())),- CommandSpec::new("sketch.polygon.circumscribed", "Circumscribed Polygon", polygon_circumscribed)+ CommandSpec::new("sketch.polygon.circumscribed", "Circumscribed Polygon", crate::checked!("sketch.polygon.circumscribed", polygon_circumscribed)).at("SKETCH", "CREATE").icon("polygon_circumscribed").enabled(in_sketch)+ .contract(&POLYGON_CIRCUMSCRIBED_CONTRACT)+ .output(output_schema_for::<PolygonResult>).params(concat!("center, radius (to edge midpoints), sides, angle?: deg", connect_doc!(), created_doc!())),- CommandSpec::new("sketch.polygon.edge", "Edge Polygon", polygon_edge)+ CommandSpec::new("sketch.polygon.edge", "Edge Polygon", crate::checked!("sketch.polygon.edge", polygon_edge)).at("SKETCH", "CREATE").icon("polygon_edge").enabled(in_sketch)+ .contract(&POLYGON_EDGE_CONTRACT)+ .output(output_schema_for::<PolygonResult>).params(concat!("p0, p1: one edge, sides", connect_doc!(), created_doc!())),CommandSpec::new("sketch.slot.center_to_center", "Center to Center Slot", slot_c2c).at("SKETCH", "CREATE")@@ -1531,22 +1553,19 @@ fn drop_implied_axes(sk: &mut Sketch, cons: &mut Vec<String>) {/// Which side and corner of an axis-aligned rectangle is which, from its lines and corner/// points as `polygon_lines` made them (counter-clockwise from the bottom-left corner), so a/// caller can dimension it without inspecting the sketch first.-fn rect_names(sk: &Sketch, l: &[usize], pts: &[usize]) -> Value {+fn rect_names(sk: &Sketch, l: &[usize], pts: &[usize]) -> (RectSides, RectCorners) {let curve = |i: usize| l.get(i).and_then(|c| sk.curves.get(*c)).map(|c| c.id.clone());let point = |i: usize| pts.get(i).and_then(|q| sk.points.get(*q)).map(|q| q.id.clone());- json!({- "sides": {"bottom": curve(0), "right": curve(1), "top": curve(2), "left": curve(3)},- "corners": {"bottom_left": point(0), "bottom_right": point(1), "top_right": point(2), "top_left": point(3)},- })+ (+ RectSides { bottom: curve(0), right: curve(1), top: curve(2), left: curve(3) },+ RectCorners { bottom_left: point(0), bottom_right: point(1), top_right: point(2), top_left: point(3) },+ )}-/// `result` plus the rectangle's named sides and corners.-fn rect_result(sk_out: (Vec<String>, Vec<String>), names: Value, info: Value) -> Value {- let mut out = result(sk_out, info);- if let (Some(o), Value::Object(n)) = (out.as_object_mut(), names) {- o.extend(n);- }- out+/// The reply of a rectangle with named sides and corners, built from [`RectResult`].+fn rect_result(sk_out: (Vec<String>, Vec<String>), (sides, corners): (RectSides, RectCorners), info: Value) -> Result<Value> {+ let reply = RectResult { curves: sk_out.0, constraints: sk_out.1, sketch: info, sides, corners, created: None, param_warnings: Vec::new() };+ serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string()))}/// A rectangle corner: `[x, y]` of numbers, or with a coordinate typed as an expression (as a@@ -1591,7 +1610,7 @@ fn rect_two_point(s: &mut Session, p: &Value) -> Result<Value> {drop_implied_axes(sk, &mut cons);Ok(((ids_of(sk, &l), cons), rect_names(sk, &l, &pts)))})?;- Ok(rect_result(out, names, info))+ rect_result(out, names, info)}/// A 2-point rectangle with its corners filleted, as one undo step: the rectangle and the@@ -1615,7 +1634,7 @@ fn rect_rounded(s: &mut Session, p: &Value) -> Result<Value> {o.remove("radius");}let mut scratch = s.scratch();- let mut out = scratch.execute("sketch.rectangle.two_point", &rect)?;+ let out = scratch.execute("sketch.rectangle.two_point", &rect)?;// The fillet rounds each corner by the two sides meeting there, not by the corner point: a// corner that lands on another curve's end is shared with it, and rounding the point would// weld the two together, leaving the corner on three curves (#7878).@@ -1641,23 +1660,23 @@ fn rect_rounded(s: &mut Session, p: &Value) -> Result<Value> {// Session::execute records the wrapper's before snapshot. Nested history must not leak.scratch.undo.clear();s.accept_computed(scratch);- let arcs = rounded.get("curves").cloned().unwrap_or_else(|| json!([]));- if let Some(o) = out.as_object_mut() {- // The sharp corners are gone (the lines end at the arcs now).- o.remove("corners");- if let (Some(Value::Array(curves)), Value::Array(extra)) = (o.get_mut("curves"), &arcs) {- curves.extend(extra.iter().cloned());- }- if let (Some(Value::Array(cons)), Some(Value::Array(extra))) = (o.get_mut("constraints"), rounded.get("constraints")) {- cons.extend(extra.iter().cloned());- }- o.insert("arcs".into(), arcs);- o.insert("param".into(), rounded.get("param").cloned().unwrap_or(Value::Null));- if let Some(info) = rounded.get("sketch") {- o.insert("sketch".into(), info.clone());- }- }- Ok(out)+ let ids = |v: &Value, k: &str| -> Vec<String> {+ v.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default()+ };+ let side = |k: &str| out["sides"].get(k).and_then(Value::as_str).map(str::to_string);+ let arcs = ids(&rounded, "curves");+ // The sharp corners are gone (the lines end at the arcs now): the reply names no corners.+ let reply = RoundedRectResult {+ curves: ids(&out, "curves").into_iter().chain(arcs.iter().cloned()).collect(),+ constraints: ids(&out, "constraints").into_iter().chain(ids(&rounded, "constraints")).collect(),+ sketch: rounded.get("sketch").or_else(|| out.get("sketch")).cloned().unwrap_or(Value::Null),+ sides: RectSides { bottom: side("bottom"), right: side("right"), top: side("top"), left: side("left") },+ arcs,+ param: rounded.get("param").and_then(Value::as_str).unwrap_or_default().to_string(),+ created: None,+ param_warnings: Vec::new(),+ };+ serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string()))}fn rect_center(s: &mut Session, p: &Value) -> Result<Value> {@@ -1699,7 +1718,7 @@ fn rect_center(s: &mut Session, p: &Value) -> Result<Value> {drop_implied_axes(sk, &mut cons);Ok(((ids_of(sk, &l), cons), rect_names(sk, &l, &pts)))})?;- Ok(rect_result(out, names, info))+ rect_result(out, names, info)}fn rect_three_point(s: &mut Session, p: &Value) -> Result<Value> {@@ -1722,7 +1741,7 @@ fn rect_three_point(s: &mut Session, p: &Value) -> Result<Value> {mark_construction(sk, &l, p);Ok((ids_of(sk, &l), cons))})?;- Ok(result(out, info))+ draw_reply(out, info)}pub(super) fn radius_arg(p: &Value, cmd: &str) -> Result<f64> {@@ -1980,9 +1999,8 @@ fn polygon(s: &mut Session, p: &Value, cmd: &str, center: Vec2, r_vertex: f64, s}Ok((ids_of(sk, &l), cons))})?;- let mut value = result(out, info);- value["support_circle"] = json!(support_circle);- Ok(value)+ let reply = PolygonResult { curves: out.0, constraints: out.1, sketch: info, support_circle, created: None, param_warnings: Vec::new() };+ serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string()))}fn sides(p: &Value, cmd: &str) -> Result<usize> {diff --git a/crates/engine/src/profile_refs_tests.rs b/crates/engine/src/profile_refs_tests.rsindex 8cbff001b5..980426f1db 100644--- a/crates/engine/src/profile_refs_tests.rs+++ b/crates/engine/src/profile_refs_tests.rs@@ -83,7 +83,7 @@ fn a_port_picked_by_index_stays_a_cut_after_a_width_change() {fn a_lost_profile_is_an_error_not_another_pick() {let mut s = Session::default();run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));- run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10], "ids": ["a", "b", "c", "d"]}));+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]}));run(&mut s, "sketch.circle.center", json!({"center": [30, 5], "radius": 3, "id": "ring"}));run(&mut s, "sketch.finish", json!({}));let ring = s.model.state().sketches[0].profiles.iter().position(|p| p.outer_curves == ["ring"]).unwrap();diff --git a/crates/engine/src/schema/sketch_shapes.rs b/crates/engine/src/schema/sketch_shapes.rsindex 5efe215ed4..f04a24057b 100644--- a/crates/engine/src/schema/sketch_shapes.rs+++ b/crates/engine/src/schema/sketch_shapes.rs@@ -1,5 +1,5 @@//! Contracts and result types for the drawing commands in `cmd/sketch.rs`: a line, a point, the-//! circles and the arcs (#12953).+//! circles and the arcs (#12953), the rectangles and the polygons (#13196).use std::borrow::Cow;@@ -585,6 +585,333 @@ pub struct PointResult {pub param_warnings: Vec<String>,}+/// A rectangle corner as `sketch::corner_arg` reads it: `[x, y]` or `{x, y}` of numbers, or+/// `[x, y]` with a coordinate typed as an expression over the design's parameters. Not a point's+/// id or a snap. Kept as given, for the handler, which evaluates the expressions.+#[derive(Clone, Debug, PartialEq)]+pub struct CornerPoint(pub Value);++impl<'de> Deserialize<'de> for CornerPoint {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let v = Value::deserialize(d)?;+ if params::vec2(&v).is_some() {+ return Ok(CornerPoint(v));+ }+ // `corner_arg` reads a pair with a coordinate typed as text as `sketch::expr_point` does,+ // which is `point_arg_form`'s expression branch; anything else as `params::req_vec2`.+ let typed = v.as_array().is_some_and(|a| a.len() == 2 && a.iter().any(Value::is_string));+ if typed {+ return crate::cmd::point_arg_form(&v, false).map(|()| CornerPoint(v)).map_err(|why| D::Error::custom(whole(why)));+ }+ Err(D::Error::custom("must be a point [x, y]"))+ }+}++impl JsonSchema for CornerPoint {+ fn schema_name() -> Cow<'static, str> {+ "CornerPoint".into()+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ let point = generator.subschema_for::<Point2>();+ let coordinate = generator.subschema_for::<LengthExpr>();+ json_schema!({+ "description": "A corner: [x, y] or {x, y} in mm, or [x, y] where a coordinate is an expression over the design's parameters, such as [\"w / 2\", 5]: the corner then follows the parameters. Not a point's id or a snap.",+ "anyOf": [+ point,+ {"type": "array", "items": coordinate, "minItems": 2, "maxItems": 2}+ ]+ })+ }+}++/// A number as `params::num` reads it (a polygon's `radius`, `diameter`, `sides` and `angle`): a+/// finite number, never an expression.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct PlainNumber(pub f64);++impl<'de> Deserialize<'de> for PlainNumber {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ Value::deserialize(d)?.as_f64().and_then(params::finite).map(PlainNumber).ok_or_else(|| D::Error::custom("must be a number"))+ }+}++impl JsonSchema for PlainNumber {+ fn schema_name() -> Cow<'static, str> {+ "PlainNumber".into()+ }+ fn inline_schema() -> bool {+ true+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"type": "number"})+ }+}++/// Draw an axis-aligned rectangle from two opposite corners.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct RectTwoPointParams {+ /// The sketch to draw in: its feature id or name. Default: the one being edited.+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+ /// One corner. A coordinate typed as an expression holds the corner where the parameters put it.+ pub p0: CornerPoint,+ /// The opposite corner. It must differ from `p0` in both x and y.+ pub p1: CornerPoint,+ /// Draw construction geometry, which is not part of a profile. Default: false.+ #[serde(default)]+ pub construction: Option<bool>,+ /// Make a new point that lands exactly on an existing point (the origin too) coincident with+ /// it. Default: true.+ #[serde(default)]+ pub connect: Option<bool>,+}++/// Draw a rectangle from one edge and a point on the opposite edge, at any angle.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct RectThreePointParams {+ /// The sketch to draw in: its feature id or name. Default: the one being edited.+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+ /// One end of the first edge, as [x, y] or {x, y} in mm. An expression, a point's id or a+ /// snap is not taken.+ pub p0: PlainPoint,+ /// The other end of the first edge. Not the same point as `p0`.+ pub p1: PlainPoint,+ /// A point on the opposite edge: its distance from the first edge is the rectangle's width.+ /// Not on the first edge's line.+ pub p2: PlainPoint,+ /// Draw construction geometry, which is not part of a profile. Default: false.+ #[serde(default)]+ pub construction: Option<bool>,+ /// Make a new point that lands exactly on an existing point (the origin too) coincident with+ /// it. Default: true.+ #[serde(default)]+ pub connect: Option<bool>,+}++/// Draw an axis-aligned rectangle from its centre and one corner, with construction diagonals+/// that hold the centre.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct RectCenterParams {+ /// The sketch to draw in: its feature id or name. Default: the one being edited.+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+ /// The centre. A coordinate typed as an expression holds the centre where the parameters put it.+ pub center: CornerPoint,+ /// One corner, in any quadrant round the centre. It must differ from `center` in both x and y.+ pub corner: CornerPoint,+ /// Draw construction geometry, which is not part of a profile. Default: false.+ #[serde(default)]+ pub construction: Option<bool>,+ /// Make a new point that lands exactly on an existing point (the origin too) coincident with+ /// it. Default: true.+ #[serde(default)]+ pub connect: Option<bool>,+}++/// Draw an axis-aligned rectangle from two opposite corners, its four corners rounded alike, as+/// one undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct RectRoundedParams {+ /// The sketch to draw in: its feature id or name. Default: the one being edited.+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+ /// One corner of the rectangle before rounding, as `sketch.rectangle.two_point` takes it.+ pub p0: CornerPoint,+ /// The opposite corner. It must differ from `p0` in both x and y.+ pub p1: CornerPoint,+ /// The corner radius, in mm: a number or an expression over the design's parameters. Positive+ /// and less than half the shorter side. One radius dimension holds it; the other arcs are+ /// equal to it.+ pub radius: LengthExpr,+ /// Draw construction geometry, which is not part of a profile. Default: false.+ #[serde(default)]+ pub construction: Option<bool>,+ /// Make a new point that lands exactly on an existing point (the origin too) coincident with+ /// it. Default: true.+ #[serde(default)]+ pub connect: Option<bool>,+}++/// Draw a regular polygon whose corners lie on a circle round its centre.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct PolygonInscribedParams {+ /// The sketch to draw in: its feature id or name. Default: the one being edited.+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+ /// The centre, as [x, y] or {x, y} in mm. An expression, a point's id or a snap is not taken.+ pub center: PlainPoint,+ /// The distance from the centre to each corner, in mm. Positive. Wins over `diameter`. Give+ /// one of the two.+ #[serde(default)]+ pub radius: Option<PlainNumber>,+ /// Twice the distance from the centre to each corner, in mm. Used when `radius` is not.+ #[serde(default)]+ pub diameter: Option<PlainNumber>,+ /// The number of sides: a whole number from 3 to 200. Default: 6.+ #[serde(default)]+ pub sides: Option<PlainNumber>,+ /// The direction of the first corner from the centre, in degrees counter-clockwise from the+ /// sketch's x axis. Default: 90 (straight up).+ #[serde(default)]+ pub angle: Option<PlainNumber>,+ /// Make a new point that lands exactly on an existing point (the origin too) coincident with+ /// it. Default: true.+ #[serde(default)]+ pub connect: Option<bool>,+}++/// Draw a regular polygon whose sides touch a circle round its centre.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct PolygonCircumscribedParams {+ /// The sketch to draw in: its feature id or name. Default: the one being edited.+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+ /// The centre, as [x, y] or {x, y} in mm. An expression, a point's id or a snap is not taken.+ pub center: PlainPoint,+ /// The distance from the centre to the middle of each side, in mm. Positive. Wins over+ /// `diameter`. Give one of the two.+ #[serde(default)]+ pub radius: Option<PlainNumber>,+ /// Twice the distance from the centre to the middle of each side (the width across flats), in+ /// mm. Used when `radius` is not.+ #[serde(default)]+ pub diameter: Option<PlainNumber>,+ /// The number of sides: a whole number from 3 to 200. Default: 6.+ #[serde(default)]+ pub sides: Option<PlainNumber>,+ /// The direction of the middle of the first side from the centre, in degrees counter-clockwise+ /// from the sketch's x axis. Default: 90 (straight up).+ #[serde(default)]+ pub angle: Option<PlainNumber>,+ /// Make a new point that lands exactly on an existing point (the origin too) coincident with+ /// it. Default: true.+ #[serde(default)]+ pub connect: Option<bool>,+}++/// Draw a regular polygon from one of its sides: the polygon lies to the left of the side from+/// `p0` to `p1`.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct PolygonEdgeParams {+ /// The sketch to draw in: its feature id or name. Default: the one being edited.+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+ /// One end of the side, as [x, y] or {x, y} in mm. An expression, a point's id or a snap is+ /// not taken.+ pub p0: PlainPoint,+ /// The other end of the side. Not the same point as `p0`.+ pub p1: PlainPoint,+ /// The number of sides: a whole number from 3 to 200. Default: 6.+ #[serde(default)]+ pub sides: Option<PlainNumber>,+ /// Make a new point that lands exactly on an existing point (the origin too) coincident with+ /// it. Default: true.+ #[serde(default)]+ pub connect: Option<bool>,+}++/// An axis-aligned rectangle's sides by place, as line ids.+#[derive(Debug, Default, Serialize, JsonSchema)]+pub struct RectSides {+ /// The bottom side (least y).+ pub bottom: Option<String>,+ /// The right side (greatest x).+ pub right: Option<String>,+ /// The top side (greatest y).+ pub top: Option<String>,+ /// The left side (least x).+ pub left: Option<String>,+}++/// An axis-aligned rectangle's corners by place, as point ids.+#[derive(Debug, Default, Serialize, JsonSchema)]+pub struct RectCorners {+ /// The corner with the least x and y.+ pub bottom_left: Option<String>,+ /// The corner with the greatest x and least y.+ pub bottom_right: Option<String>,+ /// The corner with the greatest x and y.+ pub top_right: Option<String>,+ /// The corner with the least x and greatest y.+ pub top_left: Option<String>,+}++/// What `sketch.rectangle.two_point` and `sketch.rectangle.center` return.+#[derive(Debug, Serialize, JsonSchema)]+pub struct RectResult {+ /// The ids of the four sides, counter-clockwise from the bottom side.+ pub curves: Vec<String>,+ /// The ids of the constraints added: horizontal and vertical sides, a coincident for a corner+ /// that landed on an existing point, the centre rectangle's midpoint.+ pub constraints: Vec<String>,+ /// The sketch's solve: `{solved, dof}`.+ pub sketch: Value,+ /// The sides by place, so a caller can dimension them without inspecting the sketch.+ pub sides: RectSides,+ /// The corners by place.+ pub corners: RectCorners,+ /// Everything the call added to the sketch: `{points, curves, constraints, dimensions}`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub created: Option<Created>,+ /// 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 `sketch.rectangle.rounded` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct RoundedRectResult {+ /// The ids of the four sides, then the four corner arcs.+ pub curves: Vec<String>,+ /// The ids of the constraints added: the rectangle's, then the fillet's (tangencies and the+ /// arcs equal to the first).+ pub constraints: Vec<String>,+ /// The sketch's solve after the rounding: `{solved, dof}`.+ pub sketch: Value,+ /// The sides by place. They end at the arcs now; there are no sharp corners to name.+ pub sides: RectSides,+ /// The corner arcs: bottom-left, bottom-right, top-right, top-left.+ pub arcs: Vec<String>,+ /// The parameter that holds the corner radius.+ pub param: String,+ /// Everything the call added to the sketch: `{points, curves, constraints, dimensions}`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub created: Option<Created>,+ /// 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 the polygon commands return.+#[derive(Debug, Serialize, JsonSchema)]+pub struct PolygonResult {+ /// The ids of the sides, in order round the polygon.+ pub curves: Vec<String>,+ /// The ids of the constraints added: equal sides, the corners on their construction circle+ /// (and, round a circumscribed polygon, its tangent side), a coincident for a corner that+ /// landed on an existing point.+ pub constraints: Vec<String>,+ /// The sketch's solve: `{solved, dof}`.+ pub sketch: Value,+ /// The id of the construction circle that holds the polygon to its centre: through the+ /// corners of an inscribed or edge polygon, touching the sides of a circumscribed one.+ pub support_circle: String,+ /// Everything the call added to the sketch: `{points, curves, constraints, dimensions}`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub created: Option<Created>,+ /// 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>,+}+#[cfg(test)]#[path = "sketch_shapes_tests.rs"]mod tests;diff --git a/crates/engine/src/schema/sketch_shapes_tests.rs b/crates/engine/src/schema/sketch_shapes_tests.rsindex df95399ec1..7aa7941997 100644--- a/crates/engine/src/schema/sketch_shapes_tests.rs+++ b/crates/engine/src/schema/sketch_shapes_tests.rs@@ -2,7 +2,8 @@ use serde_json::{Value, json};use super::{ArcCenterPointParams, ArcThreePointParams, CircleCenterParams, CircleThreePointParams, CircleTwoPointParams, DrawResult, LineParams, PointParams,- PointResult,+ PointResult, PolygonCircumscribedParams, PolygonEdgeParams, PolygonInscribedParams, PolygonResult, RectCenterParams, RectResult,+ RectRoundedParams, RectThreePointParams, RectTwoPointParams, RoundedRectResult,};use crate::Session;use crate::schema::tests::{assert_keys, conforms};@@ -32,6 +33,14 @@ fn schemas_and_the_key_check_agree() {input_schema_for::<ArcCenterPointParams>(),&["center", "clockwise", "connect", "construction", "end", "id", "sketch", "start", "sweep"],);+ assert_keys(input_schema_for::<RectTwoPointParams>(), &["connect", "construction", "p0", "p1", "sketch"]);+ assert_keys(input_schema_for::<RectThreePointParams>(), &["connect", "construction", "p0", "p1", "p2", "sketch"]);+ assert_keys(input_schema_for::<RectCenterParams>(), &["center", "connect", "construction", "corner", "sketch"]);+ assert_keys(input_schema_for::<RectRoundedParams>(), &["connect", "construction", "p0", "p1", "radius", "sketch"]);+ // The polygons draw no construction geometry: their handlers never read `construction`.+ assert_keys(input_schema_for::<PolygonInscribedParams>(), &["angle", "center", "connect", "diameter", "radius", "sides", "sketch"]);+ assert_keys(input_schema_for::<PolygonCircumscribedParams>(), &["angle", "center", "connect", "diameter", "radius", "sides", "sketch"]);+ assert_keys(input_schema_for::<PolygonEdgeParams>(), &["connect", "p0", "p1", "sides", "sketch"]);}/// Calls the handler refuses fail in strict with the same message. (The shared helper finishes@@ -81,6 +90,30 @@ fn strict_keeps_todays_errors() {("sketch.arc.center_point", json!({"center": [0, 0], "start": [5, 0], "end": true})),("sketch.arc.center_point", json!({"center": [0, 0], "start": [5, 0], "end": null})),("sketch.arc.center_point", json!({"center": [0, 0], "start": [5, 0]})),+ ("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [0, 5]})),+ ("sketch.rectangle.two_point", json!({"p0": "l1.end", "p1": [5, 5]})),+ ("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [5, true]})),+ ("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": ["", 5]})),+ ("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": ["5", true]})),+ ("sketch.rectangle.center", json!({"center": [0, 0], "corner": [0, 5]})),+ ("sketch.rectangle.center", json!({"center": {"ref": "l1.end"}, "corner": [5, 5]})),+ ("sketch.rectangle.rounded", json!({"p0": [0, 0], "p1": [10, 10], "radius": 6})),+ ("sketch.rectangle.rounded", json!({"p0": [0, 0], "p1": [10, 10], "radius": 0})),+ ("sketch.rectangle.rounded", json!({"p0": [0, 0], "p1": [10, 10], "radius": true})),+ ("sketch.rectangle.rounded", json!({"p0": [0, 0], "p1": [1], "radius": 1})),+ ("sketch.rectangle.three_point", json!({"p0": [0, 0], "p1": [0, 0], "p2": [1, 1]})),+ ("sketch.rectangle.three_point", json!({"p0": [0, 0], "p1": [5, 0], "p2": [9, 0]})),+ ("sketch.rectangle.three_point", json!({"p0": "l1.end", "p1": [5, 0], "p2": [5, 5]})),+ ("sketch.polygon.inscribed", json!({"center": [0, 0]})),+ ("sketch.polygon.inscribed", json!({"center": [0, 0], "radius": 0})),+ ("sketch.polygon.inscribed", json!({"center": [0, 0], "radius": "5"})),+ ("sketch.polygon.inscribed", json!({"center": [0, 0], "radius": 5, "sides": 2})),+ ("sketch.polygon.inscribed", json!({"center": "l1.end", "radius": 5})),+ ("sketch.polygon.circumscribed", json!({"center": [0, 0], "diameter": "x"})),+ ("sketch.polygon.circumscribed", json!({"center": [0, 0], "radius": 5, "sides": 201})),+ ("sketch.polygon.edge", json!({"p0": [0, 0], "p1": [0, 0]})),+ ("sketch.polygon.edge", json!({"p0": [0, 0], "p1": [5, 0], "sides": 2.5})),+ ("sketch.polygon.edge", json!({"p0": [0, 0], "p1": ["5", 0]})),];for (id, p) in &cases {let error = |level| session(level).execute(id, p).err().map(|e| e.to_string());@@ -215,3 +248,85 @@ fn wrong_typed_keys_are_reported() {fn input_schema_has(id: &str, key: &str) -> bool {crate::cmd::find_command(id).and_then(|c| c.contract).is_some_and(|c| c.allowed_keys().contains(key))}++/// The rectangles and polygons (#13196): every form each takes is accepted (run in warn, no+/// warnings), and each reply matches its own output schema.+#[test]+fn rectangles_and_polygons_reply_with_their_types() {+ let schemas = [+ ("rect", output_schema_for::<RectResult>()),+ ("draw", output_schema_for::<DrawResult>()),+ ("rounded", output_schema_for::<RoundedRectResult>()),+ ("polygon", output_schema_for::<PolygonResult>()),+ ];+ let calls = [+ ("rect", "sketch.rectangle.two_point", json!({"p0": [100, 0], "p1": [110, 10]})),+ ("rect", "sketch.rectangle.two_point", json!({"p0": {"x": 100, "y": 20}, "p1": ["110 mm", 30], "construction": true, "connect": false})),+ ("rect", "sketch.rectangle.two_point", json!({"p0": [100, 40], "p1": [110, 50], "sketch": null})),+ ("draw", "sketch.rectangle.three_point", json!({"p0": [120, 0], "p1": [130, 0], "p2": [125, 5]})),+ ("draw", "sketch.rectangle.three_point", json!({"p0": {"x": 120, "y": 20}, "p1": [130, 25], "p2": [120, 30], "construction": true})),+ ("rect", "sketch.rectangle.center", json!({"center": [150, 5], "corner": [155, 10]})),+ ("rect", "sketch.rectangle.center", json!({"center": ["150 mm", 25], "corner": [145, 20], "connect": false})),+ ("rounded", "sketch.rectangle.rounded", json!({"p0": [170, 0], "p1": [190, 10], "radius": 2})),+ ("rounded", "sketch.rectangle.rounded", json!({"p0": [170, 20], "p1": [190, 30], "radius": "1 mm", "construction": true})),+ ("polygon", "sketch.polygon.inscribed", json!({"center": [210, 5], "radius": 4})),+ ("polygon", "sketch.polygon.inscribed", json!({"center": {"x": 210, "y": 25}, "diameter": 8, "sides": 5, "angle": 0})),+ ("polygon", "sketch.polygon.circumscribed", json!({"center": [230, 5], "radius": 4, "sides": 8})),+ ("polygon", "sketch.polygon.circumscribed", json!({"center": [230, 25], "diameter": 8, "angle": 45, "connect": false})),+ ("polygon", "sketch.polygon.edge", json!({"p0": [250, 0], "p1": [255, 0]})),+ ("polygon", "sketch.polygon.edge", json!({"p0": [250, 20], "p1": [255, 20], "sides": 4})),+ ];+ let mut s = session(ParamCheck::Warn);+ for (kind, id, p) in &calls {+ let schema = schemas.iter().find(|(k, _)| k == kind).map(|(_, s)| s.as_value()).unwrap();+ let r = run(&mut s, id, p.clone());+ assert!(conforms(schema, schema, &r), "{id} {p}: {r} doesn't match {schema}");+ assert!(r.get("param_warnings").is_none(), "{id} {p}: {r}");+ assert!(r["created"]["curves"].is_array(), "{r}");+ }+ // The replies' keys, as the handlers wrote them before the types: a rounded rectangle names+ // its arcs and radius parameter, and no corners.+ let keys = |r: &Value| r.as_object().map(|o| o.keys().cloned().collect::<Vec<_>>()).unwrap_or_default();+ let mut off = session(ParamCheck::Off);+ let r = run(&mut off, "sketch.rectangle.two_point", json!({"p0": [100, 0], "p1": [110, 10]}));+ assert_eq!(keys(&r), ["constraints", "corners", "created", "curves", "sides", "sketch"]);+ assert!(r["sides"]["bottom"].is_string() && r["corners"]["top_left"].is_string(), "{r}");+ let r = run(&mut off, "sketch.rectangle.rounded", json!({"p0": [170, 0], "p1": [190, 10], "radius": 2}));+ assert_eq!(keys(&r), ["arcs", "constraints", "created", "curves", "param", "sides", "sketch"]);+ assert_eq!((r["curves"].as_array().map(Vec::len), r["arcs"].as_array().map(Vec::len)), (Some(8), Some(4)), "{r}");+ assert!(r["param"].as_str().is_some_and(|name| !name.is_empty()), "{r}");+ let r = run(&mut off, "sketch.polygon.inscribed", json!({"center": [210, 5], "radius": 4}));+ assert_eq!(keys(&r), ["constraints", "created", "curves", "sketch", "support_circle"]);+ assert_eq!(r["curves"].as_array().map(Vec::len), Some(6), "six sides by default: {r}");+ // The same calls give the same JSON with the check off and in strict.+ let (mut off, mut strict) = (session(ParamCheck::Off), session(ParamCheck::Strict));+ for (_, id, p) in &calls {+ assert_eq!(run(&mut off, id, p.clone()), run(&mut strict, id, p.clone()), "{id} {p}");+ }+}++/// What the rectangles and polygons ignore or read as left out today is reported: a number typed+/// as text, a key a polygon never reads.+#[test]+fn rectangles_and_polygons_report_wrong_typed_keys() {+ let message = |id: &str, p: Value| issues(id, &p).first().map(|i| i.message.clone());+ let polygon = json!({"center": [0, 0], "radius": 5});+ for key in ["sides", "angle"] {+ let mut bad = polygon.clone();+ bad[key] = json!("6");+ assert_eq!(message("sketch.polygon.inscribed", bad), Some(format!("`{key}` must be a number")));+ }+ let mut bad = polygon.clone();+ bad["construction"] = json!(true);+ assert_eq!(issues("sketch.polygon.inscribed", &bad).len(), 1, "a polygon draws no construction geometry");+ assert_eq!(+ message("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [5, 5], "construction": "yes"})).as_deref(),+ Some("`construction` must be true or false")+ );+ assert_eq!(+ message("sketch.rectangle.center", json!({"center": [0, 0], "corner": [5, 5], "sketch": true})).as_deref(),+ Some("`sketch` must be an id or a name")+ );+ assert_eq!(message("sketch.rectangle.rounded", json!({"p0": ["w / 2", 0], "p1": [5, 5], "radius": "r"})), None);+ assert_eq!(message("sketch.polygon.edge", json!({"p0": [0, 0], "p1": [5, 0], "sides": 4})), None);+}diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex 84dab1e3d6..5b0995e3e0 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -42,13 +42,6 @@ sheet.flat_patternsheet.path_flangesketch.dimensionsketch.draw.dimensioned-sketch.polygon.circumscribed-sketch.polygon.edge-sketch.polygon.inscribed-sketch.rectangle.center-sketch.rectangle.rounded-sketch.rectangle.three_point-sketch.rectangle.two_pointsketch.slot.center_to_centersketch.slot.overallsolid.align