Skip to content

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

Typed schemas for Line, Point, Circle and Arc (#12953) (#12955)

Loohi4425b87d2b84
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index 2c54e5d443..af84b788d0 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -110,7 +110,7 @@ mod sketch;
pub(crate) use sketch::author_path_for_rebind;
pub(crate) use sketch::collapse_reason;
pub(crate) use sketch::created as sketch_created;
-pub(crate) use sketch::{PLANE_REF_FORMS, custom_plane_form};
+pub(crate) use sketch::{PLANE_REF_FORMS, custom_plane_form, point_arg_form};
mod canvas_sketch;
mod sketch_3d;
mod sketch_canvas;
diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs
index 8aff0e12f9..ba4360daf8 100644
--- a/crates/engine/src/cmd/sketch.rs
+++ b/crates/engine/src/cmd/sketch.rs
@@ -13,6 +13,10 @@ use crate::schema::sketch::{
EditResult, EqualMade, EqualParams, EqualResult, ExitParams, FinishResult, FixOutcome, FixParams, FixResult, HorizontalVerticalParams,
MidpointParams, ParallelParams, PerpendicularParams, SymmetryParams, SymmetryResult, TangentParams,
};
+use crate::schema::sketch_shapes::{
+ ArcCenterPointParams, ArcThreePointParams, CircleCenterParams, CircleThreePointParams, CircleTwoPointParams, Created, DrawResult, LineParams,
+ PointParams, PointResult,
+};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session, SketchEntry, Snapshot};
@@ -53,6 +57,13 @@ const MIDPOINT_CONTRACT: TypedContract<MidpointParams> = TypedContract::new();
const CONCENTRIC_CONTRACT: TypedContract<ConcentricParams> = TypedContract::new();
const COLLINEAR_CONTRACT: TypedContract<CollinearParams> = TypedContract::new();
const SYMMETRY_CONTRACT: TypedContract<SymmetryParams> = TypedContract::new();
+const LINE_CONTRACT: TypedContract<LineParams> = TypedContract::new();
+const POINT_CONTRACT: TypedContract<PointParams> = TypedContract::new();
+const CIRCLE_CENTER_CONTRACT: TypedContract<CircleCenterParams> = TypedContract::new();
+const CIRCLE_TWO_POINT_CONTRACT: TypedContract<CircleTwoPointParams> = TypedContract::new();
+const 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();
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("sketch.create", "Create Sketch", create_sketch)
@@ -73,11 +84,13 @@ pub static COMMANDS: &[CommandSpec] = &[
.enabled(in_sketch)
.contract(&EXIT_CONTRACT).output(output_schema_for::<CancelResult>)
.params("Leaves the sketch without keeping what changed since it was created or opened for editing: the design goes back to how it was then (a new sketch is removed), as one step that Undo brings back. Refused when the undo history no longer leads back to that point (use Undo instead). restore_marker?: bool (default true); false transfers the temporary marker to another editor"),
- CommandSpec::new("sketch.line", "Line", draw_line)
+ CommandSpec::new("sketch.line", "Line", crate::checked!("sketch.line", draw_line))
.at("SKETCH", "CREATE")
.icon("line")
.key("L")
.enabled(in_sketch)
+ .contract(&LINE_CONTRACT)
+ .output(output_schema_for::<DrawResult>)
.params(concat!("points: [[x,y] | \"l1.end\" | {at, ref}…] (x and y each a number or an expression over the design's parameters, \"W / 2\": such a point is fixed where it comes to and follows the parameters; likewise wherever a point argument also takes a point id), closed?: bool, construction?: bool, ids?: [..], infer?: bool (add horizontal/vertical)", connect_doc!(), created_doc!())),
CommandSpec::new("sketch.draw.dimensioned", "Draw Dimensioned Sketch Geometry", draw_dimensioned).icon("dimension")
.enabled(in_sketch)
@@ -103,31 +116,39 @@ pub static COMMANDS: &[CommandSpec] = &[
.icon("rect_center")
.enabled(in_sketch)
.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", circle_center)
+ CommandSpec::new("sketch.circle.center", "Center Diameter Circle", crate::checked!("sketch.circle.center", circle_center))
.at("SKETCH", "CREATE")
.icon("circle")
.key("C")
.enabled(in_sketch)
+ .contract(&CIRCLE_CENTER_CONTRACT)
+ .output(output_schema_for::<DrawResult>)
.params(concat!(
"center: [x,y] or point ref (a coordinate may be an expression over the design's parameters: the centre follows them), radius | diameter: number or expression (an expression naming a parameter is a dimension driven by it; with `through` a point ref, that and the point both fix the radius); through?: point ref (a point the circle passes through, kept on it: where the tool's second click snapped); construction?: bool",
connect_doc!(),
created_doc!()
)),
- CommandSpec::new("sketch.circle.two_point", "2-Point Circle", circle_two)
+ CommandSpec::new("sketch.circle.two_point", "2-Point Circle", crate::checked!("sketch.circle.two_point", circle_two))
.at("SKETCH", "CREATE")
.icon("circle2")
.enabled(in_sketch)
+ .contract(&CIRCLE_TWO_POINT_CONTRACT)
+ .output(output_schema_for::<DrawResult>)
.params(concat!("p0, p1: diameter ends; construction?: bool", connect_doc!(), created_doc!())),
- CommandSpec::new("sketch.circle.three_point", "3-Point Circle", circle_three)
+ CommandSpec::new("sketch.circle.three_point", "3-Point Circle", crate::checked!("sketch.circle.three_point", circle_three))
.at("SKETCH", "CREATE")
.icon("circle3")
.enabled(in_sketch)
+ .contract(&CIRCLE_THREE_POINT_CONTRACT)
+ .output(output_schema_for::<DrawResult>)
.params(concat!("p0, p1, p2: [x,y] or point ref (a referenced point stays on the circle); construction?: bool", connect_doc!(), created_doc!())),
- CommandSpec::new("sketch.arc.three_point", "3-Point Arc", arc_three).at("SKETCH", "CREATE").icon("arc3").enabled(in_sketch).params(concat!("start, end, through: [x,y] or point ref (a referenced through point stays on the arc); construction?: bool", connect_doc!(), created_doc!())),
- CommandSpec::new("sketch.arc.center_point", "Center Point Arc", arc_center)
+ CommandSpec::new("sketch.arc.three_point", "3-Point Arc", crate::checked!("sketch.arc.three_point", arc_three)).at("SKETCH", "CREATE").icon("arc3").enabled(in_sketch).contract(&ARC_THREE_POINT_CONTRACT).output(output_schema_for::<DrawResult>).params(concat!("start, end, through: [x,y] or point ref (a referenced through point stays on the arc); construction?: bool", connect_doc!(), created_doc!())),
+ CommandSpec::new("sketch.arc.center_point", "Center Point Arc", crate::checked!("sketch.arc.center_point", arc_center))
.at("SKETCH", "CREATE")
.icon("arc_center")
.enabled(in_sketch)
+ .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)
.at("SKETCH", "CREATE")
@@ -154,7 +175,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.icon("slot_overall")
.enabled(in_sketch)
.params(concat!("p0, p1: overall ends, width", connect_doc!(), created_doc!())),
- CommandSpec::new("sketch.point", "Point", draw_point).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).params(concat!("point: [x,y] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them) or a snap: \"mid:<line>\" (held at the line's midpoint), \"on:<curve>:x,y\" (on the curve near x,y), {vertex: [x,y,z]} or {on_edge: [x,y,z]} of the model; id?", connect_doc!(), created_doc!())),
+ CommandSpec::new("sketch.point", "Point", crate::checked!("sketch.point", draw_point)).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).contract(&POINT_CONTRACT).output(output_schema_for::<PointResult>).params(concat!("point: [x,y] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them) or a snap: \"mid:<line>\" (held at the line's midpoint), \"on:<curve>:x,y\" (on the curve near x,y), {vertex: [x,y,z]} or {on_edge: [x,y,z]} of the model; id?", connect_doc!(), created_doc!())),
CommandSpec::new("sketch.dimension", "Sketch Dimension", dimension).at("SKETCH", "CREATE").icon("dimension").key("D").enabled(in_sketch).params(
"entities: [refs] (a line midpoint is \"mid:line_id\"; a model edge or vertex, {edge: [x,y,z], body?} or {vertex: [x,y,z], body?}, is projected into the sketch first and measured there: a point against the projected edge measures the distance to it), type?: auto|distance|horizontal|distance_x|vertical|distance_y|length|radius|diameter|major|minor|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override), or `name = expression` (e.g. \"width = 40\"; also `#name = expression`), which adds the user parameter `name` with that expression and dimensions with `name` (refused when the name is taken or reserved; the reply's `defined` names it); text_at?: [x, y]. Two points or a line off the axes: with auto, text_at across from them (between the perpendiculars through them, or a tenth of their distance past) is the distance between them; pulled further past an end, up or down from it horizontal, sideways vertical. Two midpoints: placing text above or below their bounding box measures horizontally, beside it vertically, anywhere else (inside it or past its corners) the distance between them. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A point and a circle or arc: the distance from the point to its edge (or how far within it a point inside lies). Two circles or arcs: the gap between their edges (or how far they overlap when they cross, or the narrowest gap between them when one lies inside the other), or the centre-to-centre distance when they are the two caps of a slot. An ellipse: a half-axis, the distance from the centre to an axis end (major or minor; with auto, text_at pulled across the major axis gives the major half-axis, pulled out past an end of it the minor one, the minor without text_at; previous_axis?: major|minor, the half-axis an earlier placement chose, kept while text_at is near the boundary between them; the reply's axis names the one chosen; with auto, when a driving dimension already holds one half-axis (or its whole axis), the other one, wherever text_at is; without its major axis line the major half-axis goes to the ellipse's own major end, without its minor axis line the minor half-axis is the minor radius); any other type, radius among them, the minor radius; an ellipse's axis line with auto: its length, the whole axis, wherever text_at is; half_axes?: bool (default true; false: with auto, the minor radius wherever text_at is, as before half-axes, which the Dimension tool sends with Draw ellipses with their axes off). An arc and one of its end points: the arc's length (type arc_length does it from the arc alone). A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends the Sketch preference, on by default): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled",
),
@@ -613,7 +634,7 @@ pub(super) fn parg(sk: &mut Sketch, doc: &solidcraft_doc::Document, v: &Value, c
if let Some(at) = v.get("at").and_then(vec2) {
return Ok(PArg::At(at));
}
- Err(bad(cmd, "a point must be [x, y], a point id like \"l1.end\", or {at, ref}"))
+ Err(bad(cmd, POINT_ARG_MUST))
}
pub(super) fn req_parg(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value, k: &str, cmd: &str) -> Result<PArg> {
@@ -622,6 +643,39 @@ pub(super) fn req_parg(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Valu
const POINT_MUST: &str = "a point's coordinates must be numbers or expressions over the design's parameters";
+/// What a point argument must be, when it is none of the forms [`parg`] reads.
+const POINT_ARG_MUST: &str = "a point must be [x, y], a point id like \"l1.end\", or {at, ref}";
+
+/// Whether `v` is a point argument [`parg`] reads, looking only at the JSON: what the design
+/// decides (an unknown point id, an expression naming no parameter) stays the handler's. `snaps`:
+/// the command also reads the forms `sketch_project::snap_points` rewrites first (`{vertex}`,
+/// `{on_edge}`). The error is the handler's message.
+pub(crate) fn point_arg_form(v: &Value, snaps: bool) -> std::result::Result<(), &'static str> {
+ if snaps && (v.get("vertex").and_then(vec3).is_some() || v.get("on_edge").and_then(vec3).is_some()) {
+ return Ok(());
+ }
+ if vec2(v).is_some() {
+ return Ok(());
+ }
+ if let Some([x, y]) = v.as_array().map(Vec::as_slice)
+ && (x.is_string() || y.is_string())
+ {
+ // The coordinates `expr_point` reads: a finite number, or text that isn't blank.
+ let coordinate = |c: &Value| match c {
+ Value::Number(n) => n.as_f64().and_then(crate::params::finite).is_some(),
+ Value::String(e) => !e.trim().is_empty() && e.len() <= 4096,
+ _ => false,
+ };
+ return if coordinate(x) && coordinate(y) { Ok(()) } else { Err(POINT_MUST) };
+ }
+ let named = match v {
+ Value::String(_) => true,
+ Value::Object(o) => o.get("ref").is_some_and(Value::is_string),
+ _ => false,
+ };
+ if named || v.get("at").and_then(vec2).is_some() { Ok(()) } else { Err(POINT_ARG_MUST) }
+}
+
/// A point given as `[x, y]` with a coordinate typed as text: where it is now and, when a
/// coordinate names a parameter, the expressions that place it (none: a plain point).
pub(super) fn expr_point(doc: &solidcraft_doc::Document, v: &Value, cmd: &str) -> Result<Option<(Vec2, Option<PointExprs>)>> {
@@ -708,14 +762,16 @@ pub(crate) fn created(before: Option<&Sketch>, after: &Sketch) -> Value {
let curves: Vec<&str> = after.curves.iter().map(|x| x.id.as_str()).filter(new).collect();
let (dims, cons): (Vec<_>, Vec<_>) = after.constraints.iter().filter(|c| new(&c.id.as_str())).partition(|c| c.kind.is_dimension());
let ids = |v: Vec<&solidcraft_sketch::Constraint>| v.into_iter().map(|c| c.id.clone()).collect::<Vec<_>>();
- let mut out = json!({"points": points, "curves": curves, "constraints": ids(cons), "dimensions": ids(dims)});
- let wires: Vec<&str> = after.wires.iter().map(|x| x.id.as_str()).filter(new).collect();
- if !wires.is_empty()
- && let Some(o) = out.as_object_mut()
- {
- o.insert("wires".into(), json!(wires));
- }
- out
+ let wires: Vec<String> = after.wires.iter().map(|x| x.id.as_str()).filter(new).map(str::to_string).collect();
+ let owned = |v: Vec<&str>| v.into_iter().map(str::to_string).collect::<Vec<_>>();
+ let out = Created { points: owned(points), curves: owned(curves), constraints: ids(cons), dimensions: ids(dims), wires };
+ serde_json::to_value(out).unwrap_or_default()
+}
+
+/// The reply of a line, circle or arc: what `result` gives, built from [`DrawResult`].
+fn draw_reply(out: (Vec<String>, Vec<String>), info: Value) -> Result<Value> {
+ let reply = DrawResult { curves: out.0, constraints: out.1, sketch: info, created: None, param_warnings: Vec::new() };
+ serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string()))
}
pub(super) fn result(sk_out: (Vec<String>, Vec<String>), info: Value) -> Value {
@@ -1254,7 +1310,7 @@ fn draw_line(s: &mut Session, p: &Value) -> Result<Value> {
mark_construction(sk, &curves, p);
Ok((ids_of(sk, &curves), cons))
})?;
- Ok(result((curves, cons), info))
+ draw_reply((curves, cons), info)
}
/// A relation the new line `c` has with the curve it starts from (drawn exactly so): tangent
@@ -1657,7 +1713,7 @@ fn circle_center(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok((ids_of(sk, &[ci]), cons))
})?;
- Ok(result(out, info))
+ draw_reply(out, info)
}
fn circle_two(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1672,7 +1728,7 @@ fn circle_two(s: &mut Session, p: &Value) -> Result<Value> {
mark_construction(sk, &[ci], p);
Ok((ids_of(sk, &[ci]), Vec::new()))
})?;
- Ok(result(out, info))
+ draw_reply(out, info)
}
/// Circle through three points.
@@ -1707,7 +1763,7 @@ fn circle_three(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok((ids_of(sk, &[ci]), cons))
})?;
- Ok(result(out, info))
+ draw_reply(out, info)
}
fn arc_three(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1734,7 +1790,7 @@ fn arc_three(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok((ids_of(sk, &[ci]), cons))
})?;
- Ok(result(out, info))
+ draw_reply(out, info)
}
fn arc_center(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1801,7 +1857,7 @@ fn arc_center(s: &mut Session, p: &Value) -> Result<Value> {
mark_construction(sk, &[ci], p);
Ok((ids_of(sk, &[ci]), Vec::new()))
})?;
- Ok(result(out, info))
+ draw_reply(out, info)
}
fn polygon(s: &mut Session, p: &Value, cmd: &str, center: Vec2, r_vertex: f64, start: f64, n: usize, inscribed: bool) -> Result<Value> {
@@ -1967,7 +2023,7 @@ fn draw_point(s: &mut Session, p: &Value) -> Result<Value> {
));
};
let ((), info) = edit(s, p, cmd, false, |_, _| Ok(()))?;
- return Ok(json!({"point": pid, "constraints": [], "sketch": info}));
+ return point_reply(pid, Vec::new(), info);
}
let ((pid, cons), info) = edit(s, p, cmd, false, |sk, doc| {
let i = match expr_point(doc, p.get("point").unwrap_or(&Value::Null), cmd)? {
@@ -1978,7 +2034,13 @@ fn draw_point(s: &mut Session, p: &Value) -> Result<Value> {
let cons = connect_points(sk, i, p)?;
Ok((sk.points.get(i).map(|q| q.id.clone()).unwrap_or_default(), cons))
})?;
- Ok(json!({"point": pid, "constraints": cons, "sketch": info}))
+ point_reply(pid, cons, info)
+}
+
+/// The reply of `sketch.point`, built from [`PointResult`].
+fn point_reply(point: String, constraints: Vec<String>, sketch: Value) -> Result<Value> {
+ let reply = PointResult { point, constraints, sketch, created: None, param_warnings: Vec::new() };
+ serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string()))
}
// ---------------------------------------------------------------------------------------------
diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs
index 95cf36cc4d..5d756b460b 100644
--- a/crates/engine/src/cmd/sketch_create.rs
+++ b/crates/engine/src/cmd/sketch_create.rs
@@ -1534,7 +1534,7 @@ mod blend_tests {
assert_eq!(ids(&r["created"]["curves"]), vec![sp.clone()], "{r}");
assert_eq!(ids(&r["created"]["points"]).len(), 8, "{r}");
assert!(ids(&r["created"]["constraints"]).is_empty() && ids(&r["created"]["dimensions"]).is_empty(), "{r}");
- run(&mut s, "sketch.line", json!({"points": [[20, 10], [2, 0]], "id": "chord"}));
+ run(&mut s, "sketch.line", json!({"points": [[20, 10], [2, 0]], "ids": "chord"}));
// Drop the two references: what is left is the blend and its chord, one closed region.
run(&mut s, "sketch.delete", json!({"entities": [a, b]}));
let id = s.active_sketch.unwrap();
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index a88a695989..b10567fe00 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -110,6 +110,7 @@ pub mod sketch_ends;
pub mod sketch_equation;
pub mod sketch_inspect;
pub mod sketch_modify;
+pub mod sketch_shapes;
pub mod surface_analysis;
pub mod surface_boundary;
pub mod surface_match;
diff --git a/crates/engine/src/schema/sketch_shapes.rs b/crates/engine/src/schema/sketch_shapes.rs
new file mode 100644
index 0000000000..5efe215ed4
--- /dev/null
+++ b/crates/engine/src/schema/sketch_shapes.rs
@@ -0,0 +1,590 @@
+//! Contracts and result types for the drawing commands in `cmd/sketch.rs`: a line, a point, the
+//! circles and the arcs (#12953).
+
+use std::borrow::Cow;
+
+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
+use serde::de::Error as _;
+use serde::{Deserialize, Deserializer, Serialize};
+use serde_json::{Value, json};
+use solidcore_record::Vec2;
+
+use super::check::whole;
+use super::sketch_ends::SketchTarget;
+use super::types::{LengthExpr, Point2, Point3, present};
+use crate::params;
+
+/// What the coordinates of a point typed as text must be.
+const POINT_MUST: &str = "a point's coordinates must be numbers or expressions over the design's parameters";
+/// The most points a line takes.
+const MAX_LINE_POINTS: usize = 10_000;
+
+/// The forms of a point argument: [`SketchPoint`] and [`SnapPoint`] differ in the snaps.
+fn point_arg_schema(generator: &mut SchemaGenerator, snaps: bool) -> Schema {
+ let point = generator.subschema_for::<Point2>();
+ let coordinate = generator.subschema_for::<LengthExpr>();
+ let mut forms = vec![
+ json!(point),
+ json!({
+ "description": "[x, y] where a coordinate may be an expression over the design's parameters, such as [\"w / 2\", 5]: a point that follows the parameters.",
+ "type": "array", "items": coordinate, "minItems": 2, "maxItems": 2
+ }),
+ json!({"description": "An existing point's id such as \"l1.end\" or \"p3\", or a snap such as \"mid:l1\".", "type": "string"}),
+ json!({"description": "An existing point by id.", "type": "object", "properties": {"ref": {"type": "string"}}, "required": ["ref"]}),
+ json!({"description": "A point by place.", "type": "object", "properties": {"at": point}, "required": ["at"]}),
+ ];
+ let description = if snaps {
+ let model = generator.subschema_for::<Point3>();
+ forms.push(json!({"description": "A model vertex [x, y, z] in mm, projected into the sketch.", "type": "object", "properties": {"vertex": model}, "required": ["vertex"]}));
+ forms.push(json!({"description": "A point on a model edge [x, y, z] in mm, projected into the sketch.", "type": "object", "properties": {"on_edge": model}, "required": ["on_edge"]}));
+ "A sketch point: [x, y] in mm (a coordinate may be an expression), an existing point's id (\"l1.end\"), {ref} or {at}, a snap as text (\"mid:<line>\", \"on:<curve>:x,y\", \"x:<a>+<b>:x,y\", \"vertex:x,y,z\"), or a model {vertex} or {on_edge}."
+ } else {
+ "A sketch point: [x, y] in mm (a coordinate may be an expression over the design's parameters), an existing point's id such as \"l1.end\", or {ref} or {at}."
+ };
+ json_schema!({"description": description, "anyOf": forms})
+}
+
+/// A point argument as `sketch::parg` reads it: a place `[x, y]` (a coordinate may be an
+/// expression), an existing point's id, `{ref}` or `{at}`. Kept as given, for the handler, which
+/// has the design to find a point and evaluate an expression.
+#[derive(Clone, Debug, PartialEq)]
+pub struct SketchPoint(pub Value);
+
+impl<'de> Deserialize<'de> for SketchPoint {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ crate::cmd::point_arg_form(&v, false).map(|()| SketchPoint(v)).map_err(|why| D::Error::custom(whole(why)))
+ }
+}
+
+impl JsonSchema for SketchPoint {
+ fn schema_name() -> Cow<'static, str> {
+ "SketchPoint".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ point_arg_schema(generator, false)
+ }
+}
+
+/// A point argument of a command that snaps its points (`sketch_project::snap_points`): a
+/// [`SketchPoint`], or a model `{vertex}` or `{on_edge}`. Snaps given as text are text.
+#[derive(Clone, Debug, PartialEq)]
+pub struct SnapPoint(pub Value);
+
+impl<'de> Deserialize<'de> for SnapPoint {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ crate::cmd::point_arg_form(&v, true).map(|()| SnapPoint(v)).map_err(|why| D::Error::custom(whole(why)))
+ }
+}
+
+impl JsonSchema for SnapPoint {
+ fn schema_name() -> Cow<'static, str> {
+ "SnapPoint".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ point_arg_schema(generator, true)
+ }
+}
+
+/// A point as `params::req_vec2` reads it: `[x, y]` or `{x, y}` of numbers, with no expression, id
+/// or snap (the 2-point circle's `p0` and `p1`).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct PlainPoint(pub Vec2);
+
+impl<'de> Deserialize<'de> for PlainPoint {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ params::vec2(&Value::deserialize(d)?).map(PlainPoint).ok_or_else(|| D::Error::custom("must be a point [x, y]"))
+ }
+}
+
+impl JsonSchema for PlainPoint {
+ fn schema_name() -> Cow<'static, str> {
+ "PlainPoint".into()
+ }
+ fn inline_schema() -> bool {
+ true
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ generator.subschema_for::<Point2>()
+ }
+}
+
+/// The points of a line: a list of [`SnapPoint`]s, 2 to 10 000.
+#[derive(Clone, Debug, PartialEq)]
+pub struct LinePoints(pub Vec<Value>);
+
+impl<'de> Deserialize<'de> for LinePoints {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let Value::Array(list) = Value::deserialize(d)? else {
+ return Err(D::Error::custom(whole("`points` must be a list")));
+ };
+ if list.len() < 2 || list.len() > MAX_LINE_POINTS {
+ return Err(D::Error::custom(whole("a line needs 2 or more points")));
+ }
+ for v in &list {
+ crate::cmd::point_arg_form(v, true).map_err(|why| D::Error::custom(whole(why)))?;
+ }
+ Ok(LinePoints(list))
+ }
+}
+
+impl JsonSchema for LinePoints {
+ fn schema_name() -> Cow<'static, str> {
+ "LinePoints".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<SnapPoint>();
+ json_schema!({
+ "description": "The points the line runs through, in order: 2 to 10 000. Each is a SnapPoint.",
+ "type": "array", "items": point, "minItems": 2, "maxItems": MAX_LINE_POINTS
+ })
+ }
+}
+
+/// Whether `v` is a snap that `sketch.point` takes as one, and if so whether it is well formed
+/// (what the design makes of it, such as a line that is not there, stays the handler's).
+fn snap_form(v: &Value) -> Option<bool> {
+ let text = v.as_str();
+ let snapped =
+ text.is_some_and(|t| ["mid:", "on:", "vertex:"].iter().any(|k| t.starts_with(k))) || v.get("vertex").is_some() || v.get("on_edge").is_some();
+ if !snapped {
+ return None;
+ }
+ let numbers = |t: &str| -> Vec<f64> { t.split(',').filter_map(|x| x.trim().parse().ok()).collect() };
+ let finite3 = |n: &[f64]| matches!(n, [x, y, z] if x.is_finite() && y.is_finite() && z.is_finite());
+ let vertex =
+ v.get("vertex").and_then(params::vec3).is_some() || text.and_then(|t| t.strip_prefix("vertex:")).is_some_and(|t| finite3(&numbers(t)));
+ let edge = v.get("on_edge").and_then(params::vec3).is_some();
+ let mid = text.is_some_and(|t| t.starts_with("mid:"));
+ let on = text
+ .and_then(|t| t.strip_prefix("on:"))
+ .and_then(|t| t.rsplit_once(':'))
+ .is_some_and(|(_, xy)| matches!(numbers(xy)[..], [x, y] if x.is_finite() && y.is_finite()));
+ Some(vertex || edge || mid || on)
+}
+
+/// `sketch.point`'s `point`: `[x, y]` (numbers, or text expressions over the design's parameters),
+/// `{x, y}`, or a snap that makes the point. An existing point's id is not taken.
+#[derive(Clone, Debug, PartialEq)]
+pub struct PointOrSnap(pub Value);
+
+impl<'de> Deserialize<'de> for PointOrSnap {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ match snap_form(&v) {
+ Some(true) => return Ok(PointOrSnap(v)),
+ Some(false) => {
+ return Err(D::Error::custom(whole(format!(
+ "`point` {v} is not a snap it takes: \"mid:<line>\", \"on:<curve>:x,y\", \"vertex:x,y,z\", {{vertex: [x,y,z]}} or {{on_edge: [x,y,z]}}"
+ ))));
+ }
+ None => {}
+ }
+ if let Some([x, y]) = v.as_array().map(Vec::as_slice)
+ && (x.is_string() || y.is_string())
+ {
+ // The coordinates `sketch::expr_point` reads: a finite number, or text that isn't blank.
+ let coordinate = |c: &Value| match c {
+ Value::Number(n) => n.as_f64().and_then(params::finite).is_some(),
+ Value::String(e) => !e.trim().is_empty() && e.len() <= 4096,
+ _ => false,
+ };
+ return if coordinate(x) && coordinate(y) { Ok(PointOrSnap(v)) } else { Err(D::Error::custom(whole(POINT_MUST))) };
+ }
+ if params::vec2(&v).is_some() { Ok(PointOrSnap(v)) } else { Err(D::Error::custom("must be a point [x, y]")) }
+ }
+}
+
+impl JsonSchema for PointOrSnap {
+ fn schema_name() -> Cow<'static, str> {
+ "PointOrSnap".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<Point2>();
+ let coordinate = generator.subschema_for::<LengthExpr>();
+ let model = generator.subschema_for::<Point3>();
+ json_schema!({
+ "description": "A point to make: [x, y] in mm (a coordinate may be an expression over the design's parameters: the point then follows them), or a snap that makes it and holds it: \"mid:<line>\" (the line's midpoint), \"on:<curve>:x,y\" (on the curve, near x,y), \"vertex:x,y,z\" or {vertex: [x,y,z]} (a model vertex, projected) or {on_edge: [x,y,z]} (a point on a model edge, projected). An existing point's id is not taken.",
+ "anyOf": [
+ point,
+ {"type": "array", "items": coordinate, "minItems": 2, "maxItems": 2},
+ {"type": "string", "pattern": "^(mid:|on:|vertex:)"},
+ {"type": "object", "properties": {"vertex": model}, "required": ["vertex"]},
+ {"type": "object", "properties": {"on_edge": model}, "required": ["on_edge"]}
+ ]
+ })
+ }
+}
+
+/// An id a drawing command gives its curve or point, as `named_id` reads it: text that can be
+/// written into a face name whole.
+#[derive(Clone, Debug, PartialEq)]
+pub struct DrawId(pub String);
+
+/// `id`, or an entry of `ids`, as `named_id` refuses it (the entry's position is not named).
+fn id_problem(id: &str) -> Option<String> {
+ (!solidcraft_doc::persistent_name::text_fits_name(id))
+ .then(|| format!("the id `{id}` cannot be written into a name whole; give an id without `|`, `,`, `~`, `#` or `]`"))
+}
+
+impl<'de> Deserialize<'de> for DrawId {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let Value::String(id) = Value::deserialize(d)? else {
+ return Err(D::Error::custom("must be text"));
+ };
+ match id_problem(&id) {
+ Some(why) => Err(D::Error::custom(whole(why))),
+ None => Ok(DrawId(id)),
+ }
+ }
+}
+
+impl JsonSchema for DrawId {
+ fn schema_name() -> Cow<'static, str> {
+ "DrawId".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "An id for the new geometry, such as \"base\". It may not hold `|`, `,`, `~`, `#` or `]`, which a face name made from it would read as its own.",
+ "type": "string"
+ })
+ }
+}
+
+/// A line's `ids`, as `params::string_list` and `named_id` read them: a list of ids (one id is a
+/// list of one), at most 10 000.
+#[derive(Clone, Debug, PartialEq)]
+pub struct DrawIds(pub Vec<String>);
+
+impl<'de> Deserialize<'de> for DrawIds {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ let ids = match params::string_list("", &json!({"ids": v}), "ids") {
+ Ok(ids) => ids,
+ Err(crate::EngineError::BadParams { msg, .. }) => return Err(D::Error::custom(whole(msg))),
+ Err(e) => return Err(D::Error::custom(whole(e))),
+ };
+ if let Some(why) = ids.iter().find_map(|id| id_problem(id)) {
+ return Err(D::Error::custom(whole(why)));
+ }
+ Ok(DrawIds(ids))
+ }
+}
+
+impl JsonSchema for DrawIds {
+ fn schema_name() -> Cow<'static, str> {
+ "DrawIds".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "Ids for the lines, in order: the first for the first segment and so on. One id is a list of one. Segments past the end of the list get an id of the sketch's own. An id may not hold `|`, `,`, `~`, `#` or `]`.",
+ "anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}, "maxItems": 10000}]
+ })
+ }
+}
+
+/// A circle's `radius` or `diameter`, as `radius_arg` and `circle_size` read it: a number, or text
+/// that is an expression over the design's parameters (a dimension driven by them). Whether it is
+/// positive, and whether an expression evaluates, is the handler's to check.
+fn size_form(v: &Value, key: &str) -> Result<(), String> {
+ match v {
+ Value::Number(n) if n.as_f64().and_then(params::finite).is_some() => Ok(()),
+ Value::String(_) if params::expr(&json!({ "v": v }), "v").is_some() => Ok(()),
+ Value::String(_) => Err(format!("`{key}` {}", params::expr_problem(Some(v)))),
+ _ => Err(format!("`{key}` must be a number")),
+ }
+}
+
+macro_rules! circle_size {
+ ($name:ident, $key:literal, $doc:literal) => {
+ #[doc = $doc]
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct $name(pub Value);
+
+ impl<'de> Deserialize<'de> for $name {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ size_form(&v, $key).map(|()| $name(v)).map_err(|why| D::Error::custom(whole(why)))
+ }
+ }
+
+ impl JsonSchema for $name {
+ fn schema_name() -> Cow<'static, str> {
+ stringify!($name).into()
+ }
+ fn inline_schema() -> bool {
+ true
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ generator.subschema_for::<LengthExpr>()
+ }
+ }
+ };
+}
+
+circle_size!(CircleRadius, "radius", "A circle's `radius`: a number or an expression.");
+circle_size!(CircleDiameter, "diameter", "A circle's `diameter`: a number or an expression.");
+
+/// An arc's `sweep`, as `params::num` reads it: a number below 1e9 in size. That it is between
+/// -360 and 360 and not 0 is the handler's to check.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Sweep(pub f64);
+
+impl<'de> Deserialize<'de> for Sweep {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ Value::deserialize(d)?.as_f64().and_then(params::finite).map(Sweep).ok_or_else(|| D::Error::custom("must be a number of degrees"))
+ }
+}
+
+impl JsonSchema for Sweep {
+ fn schema_name() -> Cow<'static, str> {
+ "Sweep".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "The angle the arc turns through, in degrees: positive counter-clockwise from `start`, negative clockwise. Not 0, and less than 360 in size.",
+ "type": "number", "exclusiveMinimum": -360, "exclusiveMaximum": 360
+ })
+ }
+}
+
+/// Draw a line through two or more points, or a closed polyline.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct LineParams {
+ /// The sketch to draw in: its feature id or name. Default: the one being edited.
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+ /// The points to run through, in order: one segment between each two. A point that is an
+ /// existing point's id (or `{ref}`) shares that point, so the line starts or ends there.
+ pub points: LinePoints,
+ /// Close the line with a segment from the last point back to the first. Default: false.
+ #[serde(default)]
+ pub closed: Option<bool>,
+ /// Draw construction geometry, which is not part of a profile. Default: false.
+ #[serde(default)]
+ pub construction: Option<bool>,
+ /// Ids for the segments, in order. Default: ids of the sketch's own.
+ #[serde(default)]
+ pub ids: Option<DrawIds>,
+ /// Add a horizontal or vertical constraint to a segment that is drawn exactly so, and a
+ /// tangent to the arc or a perpendicular to the line that it starts from. Default: false.
+ #[serde(default)]
+ pub infer: 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>,
+}
+
+/// Add a point to the sketch, or a point made by a snap that holds it.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct PointParams {
+ /// The sketch to draw in: its feature id or name. Default: the one being edited.
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+ /// Where the point goes, or the snap that makes it.
+ pub point: PointOrSnap,
+ /// An id for the point. Default: one of the sketch's own. Ignored when `point` is a snap.
+ #[serde(default)]
+ pub id: Option<DrawId>,
+ /// Make the new point coincident with an existing point it lands exactly on (the origin
+ /// too). Default: true. Ignored when `point` is a snap.
+ #[serde(default)]
+ pub connect: Option<bool>,
+}
+
+/// Draw a circle from its centre and its radius or diameter.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct CircleCenterParams {
+ /// The sketch to draw in: its feature id or name. Default: the one being edited.
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+ /// The centre. A point's id or `{ref}` makes that point the centre, so the circle follows it.
+ pub center: SnapPoint,
+ /// The radius, in mm: a number, or an expression over the design's parameters, which makes
+ /// the radius a dimension driven by them. Wins over `diameter`. Give one of the two.
+ #[serde(default)]
+ pub radius: Option<CircleRadius>,
+ /// The diameter, in mm, as `radius` is given. Used when `radius` is not.
+ #[serde(default)]
+ pub diameter: Option<CircleDiameter>,
+ /// A point the circle passes through, kept on it. With a placed centre and an existing
+ /// point, that point and `radius` both fix the radius.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SnapPoint")]
+ pub through: Option<SnapPoint>,
+ /// An id for the circle. Default: one of the sketch's own.
+ #[serde(default)]
+ pub id: Option<DrawId>,
+ /// 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 circle from the two ends of a diameter.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct CircleTwoPointParams {
+ /// 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 diameter, 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 diameter. Not the same point as `p0`.
+ pub p1: 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 a circle through three points.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct CircleThreePointParams {
+ /// The sketch to draw in: its feature id or name. Default: the one being edited.
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+ /// A point on the circle. One that is an existing point's id stays on the circle.
+ pub p0: SnapPoint,
+ /// A second point on the circle.
+ pub p1: SnapPoint,
+ /// A third point on the circle. The three may not be in a line.
+ pub p2: SnapPoint,
+ /// 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 arc from its two ends and a point on it.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct ArcThreePointParams {
+ /// 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 arc.
+ pub start: SnapPoint,
+ /// The other end of the arc.
+ pub end: SnapPoint,
+ /// A point the arc passes through, between the ends. One that is an existing point's id
+ /// stays on the arc. The three may not be in a line.
+ pub through: SnapPoint,
+ /// An id for the arc. Default: one of the sketch's own.
+ #[serde(default)]
+ pub id: Option<DrawId>,
+ /// 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 arc round a centre, from a start point to an end point or through a sweep.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct ArcCenterPointParams {
+ /// The sketch to draw in: its feature id or name. Default: the one being edited.
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+ /// The centre of the arc.
+ pub center: SnapPoint,
+ /// Where the arc starts. Its distance from `center` is the radius.
+ pub start: SnapPoint,
+ /// A point in the direction of the arc's end from `center`: the arc ends on the ray through
+ /// it, at the radius. Give `end` or `sweep`; `sweep` wins.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SnapPoint")]
+ pub end: Option<SnapPoint>,
+ /// With `end`: go clockwise from `start` to `end`. Default: false, counter-clockwise.
+ #[serde(default)]
+ pub clockwise: Option<bool>,
+ /// The angle to turn through from `start`, in degrees, instead of `end`.
+ #[serde(default)]
+ pub sweep: Option<Sweep>,
+ /// An id for the arc. Default: one of the sketch's own.
+ #[serde(default)]
+ pub id: Option<DrawId>,
+ /// 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>,
+}
+
+/// What a command added to its sketch: the ids that the sketch has now and did not before.
+#[derive(Debug, Default, Serialize, JsonSchema)]
+pub struct Created {
+ /// Point ids.
+ pub points: Vec<String>,
+ /// Curve ids.
+ pub curves: Vec<String>,
+ /// Constraint ids, dimensions not among them.
+ pub constraints: Vec<String>,
+ /// Dimension ids.
+ pub dimensions: Vec<String>,
+ /// The ids of 3D curves, when the command made any.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub wires: Vec<String>,
+}
+
+/// What a drawing command returns for a line, a circle or an arc.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct DrawResult {
+ /// The ids of the curves drawn, in order.
+ pub curves: Vec<String>,
+ /// The ids of the constraints added besides the curves' own: a coincident for a point that
+ /// landed on an existing one, a point on the curve for a point that was given by id, a radius
+ /// for a size given as an expression, what `infer` added.
+ pub constraints: Vec<String>,
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// Everything the call added to the sketch: `{points, curves, constraints, dimensions}`, and
+ /// `wires` when there are any.
+ #[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.point` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct PointResult {
+ /// The id of the point made.
+ pub point: String,
+ /// The ids of the constraints added: a coincident with the existing point it landed on.
+ pub constraints: Vec<String>,
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// 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.rs
new file mode 100644
index 0000000000..df95399ec1
--- /dev/null
+++ b/crates/engine/src/schema/sketch_shapes_tests.rs
@@ -0,0 +1,217 @@
+use serde_json::{Value, json};
+
+use super::{
+ ArcCenterPointParams, ArcThreePointParams, CircleCenterParams, CircleThreePointParams, CircleTwoPointParams, DrawResult, LineParams, PointParams,
+ PointResult,
+};
+use crate::Session;
+use crate::schema::tests::{assert_keys, conforms};
+use crate::schema::{ParamCheck, input_schema_for, issues, output_schema_for};
+
+/// A session in a new sketch that holds one line, `l1`, from [0, 0] to [10, 0].
+fn session(level: ParamCheck) -> Session {
+ let mut s = Session { param_check: level, ..Session::default() };
+ run(&mut s, "sketch.create", json!({"plane": "XY"}));
+ run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0]], "ids": ["l1"]}));
+ s
+}
+
+fn run(s: &mut Session, id: &str, p: Value) -> Value {
+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
+}
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<LineParams>(), &["closed", "connect", "construction", "ids", "infer", "points", "sketch"]);
+ assert_keys(input_schema_for::<PointParams>(), &["connect", "id", "point", "sketch"]);
+ assert_keys(input_schema_for::<CircleCenterParams>(), &["center", "connect", "construction", "diameter", "id", "radius", "sketch", "through"]);
+ assert_keys(input_schema_for::<CircleTwoPointParams>(), &["connect", "construction", "p0", "p1", "sketch"]);
+ assert_keys(input_schema_for::<CircleThreePointParams>(), &["connect", "construction", "p0", "p1", "p2", "sketch"]);
+ assert_keys(input_schema_for::<ArcThreePointParams>(), &["connect", "construction", "end", "id", "sketch", "start", "through"]);
+ assert_keys(
+ input_schema_for::<ArcCenterPointParams>(),
+ &["center", "clockwise", "connect", "construction", "end", "id", "sketch", "start", "sweep"],
+ );
+}
+
+/// Calls the handler refuses fail in strict with the same message. (The shared helper finishes
+/// its sketch first; these need one being edited.)
+#[test]
+fn strict_keeps_todays_errors() {
+ let cases = [
+ ("sketch.line", json!({"points": 5})),
+ ("sketch.line", json!({"points": [[0, 0]]})),
+ ("sketch.line", json!({"points": [[0, 0], "zz"]})),
+ ("sketch.line", json!({"points": [[0, 0], [1]]})),
+ ("sketch.line", json!({"points": [[0, 0], [true, "a"]]})),
+ ("sketch.line", json!({"points": [[0, 0], ["", 1]]})),
+ ("sketch.line", json!({"points": [[0, 0], [5, 5]], "ids": 5})),
+ ("sketch.line", json!({"points": [[0, 0], [5, 5]], "ids": [1]})),
+ ("sketch.line", json!({"points": [[0, 0], [5, 5]], "ids": ["a|b"]})),
+ ("sketch.line", json!({"points": [[0, 0], [5, 5]], "ids": "a,b"})),
+ ("sketch.line", json!({"points": [[0, 0], {"vertex": "x"}]})),
+ ("sketch.point", json!({"point": "l1.end"})),
+ ("sketch.point", json!({"point": [1]})),
+ ("sketch.point", json!({"point": ["", 2]})),
+ ("sketch.point", json!({"point": [1, true]})),
+ ("sketch.point", json!({"point": "mid:nope"})),
+ ("sketch.point", json!({"point": {"vertex": "x"}})),
+ ("sketch.point", json!({"point": "on:l1:x"})),
+ ("sketch.point", json!({"point": "vertex:1,2"})),
+ ("sketch.point", json!({"point": [1, 2], "id": "a|b"})),
+ ("sketch.circle.center", json!({"center": [0, 0]})),
+ ("sketch.circle.center", json!({"center": [0, 0], "radius": true})),
+ ("sketch.circle.center", json!({"center": [0, 0], "radius": " "})),
+ ("sketch.circle.center", json!({"center": [0, 0], "radius": 1e12})),
+ ("sketch.circle.center", json!({"center": [0, 0], "radius": 0})),
+ ("sketch.circle.center", json!({"center": [0, 0], "diameter": [1]})),
+ ("sketch.circle.center", json!({"center": 5, "radius": 1})),
+ ("sketch.circle.center", json!({"center": [0, 0], "radius": 1, "through": null})),
+ ("sketch.circle.center", json!({"center": [0, 0], "radius": 1, "id": "a]"})),
+ ("sketch.circle.two_point", json!({"p0": "l1.end", "p1": [1, 1]})),
+ ("sketch.circle.two_point", json!({"p0": [0, 0], "p1": ["1", 1]})),
+ ("sketch.circle.two_point", json!({"p0": [0, 0], "p1": [0, 0]})),
+ ("sketch.circle.three_point", json!({"p0": [0, 0], "p1": [1, 0], "p2": [2, 0]})),
+ ("sketch.circle.three_point", json!({"p0": [0, 0], "p1": 5, "p2": [2, 3]})),
+ ("sketch.arc.three_point", json!({"start": [0, 0], "end": [10, 0], "through": [5, 0]})),
+ ("sketch.arc.three_point", json!({"start": [0, 0], "end": [10, 0], "through": "zz"})),
+ ("sketch.arc.three_point", json!({"start": [0, 0], "end": [10, 0], "through": [5, 5], "id": "a|b"})),
+ ("sketch.arc.center_point", json!({"center": [0, 0], "start": [5, 0], "sweep": 0})),
+ ("sketch.arc.center_point", json!({"center": [0, 0], "start": [5, 0], "sweep": 400})),
+ ("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]})),
+ ];
+ for (id, p) in &cases {
+ let error = |level| session(level).execute(id, p).err().map(|e| e.to_string());
+ let off = error(ParamCheck::Off);
+ assert!(off.is_some(), "{id} {p} should fail today");
+ assert_eq!(error(ParamCheck::Strict), off, "{id} {p}");
+ }
+}
+
+/// Every form each command takes is accepted by the contract: run in warn, the reply has no
+/// warnings and matches the output schema.
+#[test]
+fn replies_match_the_output_schema_and_forms_are_accepted() {
+ let draw = output_schema_for::<DrawResult>();
+ let draw = draw.as_value();
+ let point = output_schema_for::<PointResult>();
+ let point = point.as_value();
+ let calls = [
+ ("sketch.line", json!({"points": [[0, 5], [10, 5]]})),
+ ("sketch.line", json!({"points": ["l1.end", [20, 0]], "infer": true})),
+ ("sketch.line", json!({"points": [{"ref": "l1.start"}, {"at": [1, 2]}], "construction": true})),
+ ("sketch.line", json!({"points": [[30, 0], ["5 mm", 3], {"x": 40, "y": 9}], "closed": true, "ids": "solo", "connect": false})),
+ ("sketch.line", json!({"points": [[50, 0], [60, 0]], "ids": ["a", "b"], "sketch": null})),
+ ("sketch.circle.center", json!({"center": [50, 50], "radius": 2})),
+ ("sketch.circle.center", json!({"center": [50, 60], "diameter": 4, "id": "ring", "construction": true})),
+ ("sketch.circle.center", json!({"center": [50, 70], "radius": "3 mm", "connect": false})),
+ ("sketch.circle.center", json!({"center": ["1 mm", 80], "diameter": "6 mm", "through": "l1.end"})),
+ ("sketch.circle.two_point", json!({"p0": [70, 0], "p1": [80, 0]})),
+ ("sketch.circle.two_point", json!({"p0": {"x": 70, "y": 10}, "p1": {"x": 80, "y": 10}, "construction": false})),
+ ("sketch.circle.three_point", json!({"p0": [90, 0], "p1": [100, 10], "p2": [110, 0]})),
+ ("sketch.circle.three_point", json!({"p0": "l1.start", "p1": {"at": [0, -10]}, "p2": [-10, 0]})),
+ ("sketch.arc.three_point", json!({"start": [0, 20], "end": [10, 20], "through": [5, 25], "id": "arc_one"})),
+ ("sketch.arc.three_point", json!({"start": [0, 30], "end": [10, 30], "through": [5, 35], "construction": true})),
+ ("sketch.arc.center_point", json!({"center": [0, 40], "start": [5, 40], "end": [0, 45]})),
+ ("sketch.arc.center_point", json!({"center": [0, 50], "start": [5, 50], "end": [0, 55], "clockwise": true, "id": "arc_two"})),
+ ("sketch.arc.center_point", json!({"center": [0, 60], "start": [5, 60], "sweep": 90})),
+ ("sketch.arc.center_point", json!({"center": [0, 70], "start": [5, 70], "sweep": -45, "end": [0, 75]})),
+ ];
+ let point_calls = [
+ json!({"point": [30, 30]}),
+ json!({"point": {"x": 31, "y": 31}, "id": "pt"}),
+ json!({"point": ["10 mm", 40], "connect": false}),
+ json!({"point": "mid:l1"}),
+ json!({"point": "on:l1:5,0"}),
+ ];
+ let mut s = session(ParamCheck::Warn);
+ for (id, p) in &calls {
+ let r = run(&mut s, id, p.clone());
+ assert!(conforms(draw, draw, &r), "{id} {p}: {r} doesn't match {draw}");
+ assert!(r.get("param_warnings").is_none(), "{id} {p}: {r}");
+ assert!(r["created"]["curves"].is_array(), "{r}");
+ }
+ for p in &point_calls {
+ let r = run(&mut s, "sketch.point", p.clone());
+ assert!(conforms(point, point, &r), "{p}: {r} doesn't match {point}");
+ assert!(r.get("param_warnings").is_none(), "{p}: {r}");
+ }
+ // A misspelt key still runs in warn and is named.
+ let r = run(&mut s, "sketch.line", json!({"points": [[0, 90], [10, 90]], "constructon": true}));
+ assert!(conforms(draw, draw, &r), "{r} doesn't match {draw}");
+ assert!(r["param_warnings"].as_array().is_some_and(|w| w.len() == 1), "{r}");
+ let r = run(&mut s, "sketch.point", json!({"point": [3, 95], "constructon": true}));
+ assert!(conforms(point, point, &r), "{r} doesn't match {point}");
+ assert!(r["param_warnings"].as_array().is_some_and(|w| w.len() == 1), "{r}");
+}
+
+/// The same calls give the same JSON with the check off and in strict.
+#[test]
+fn the_check_does_not_change_the_reply() {
+ let calls = [
+ ("sketch.line", json!({"points": [[0, 5], [10, 5], [10, 15]], "closed": true, "ids": ["a", "b", "c"]})),
+ ("sketch.point", json!({"point": [3, 3]})),
+ ("sketch.point", json!({"point": "mid:l1"})),
+ ("sketch.circle.center", json!({"center": [50, 50], "radius": 2, "id": "c1"})),
+ ("sketch.circle.two_point", json!({"p0": [70, 0], "p1": [80, 0]})),
+ ("sketch.circle.three_point", json!({"p0": [90, 0], "p1": [100, 10], "p2": [110, 0]})),
+ ("sketch.arc.three_point", json!({"start": [0, 20], "end": [10, 20], "through": [5, 25]})),
+ ("sketch.arc.center_point", json!({"center": [0, 40], "start": [5, 40], "sweep": 90})),
+ ];
+ let (mut off, mut strict) = (session(ParamCheck::Off), session(ParamCheck::Strict));
+ for (id, p) in &calls {
+ let (a, b) = (run(&mut off, id, p.clone()), run(&mut strict, id, p.clone()));
+ assert_eq!(a, b, "{id} {p}");
+ assert!(a["created"]["points"].is_array() && a["sketch"]["dof"].is_number(), "{a}");
+ }
+ // Key order and spelling of a reply, as the handlers wrote it before the types.
+ let r = run(&mut off, "sketch.point", json!({"point": [4, 4]}));
+ assert_eq!(
+ r.as_object().map(|o| o.keys().cloned().collect::<Vec<_>>()),
+ Some(vec!["constraints".into(), "created".into(), "point".into(), "sketch".into()])
+ );
+}
+
+/// Values of the wrong type that a handler ignores or reads as left out are refused by the
+/// contract: that is what warn reports and strict refuses.
+#[test]
+fn wrong_typed_keys_are_reported() {
+ let base = [
+ ("sketch.line", json!({"points": [[0, 0], [5, 5]]})),
+ ("sketch.point", json!({"point": [1, 1]})),
+ ("sketch.circle.center", json!({"center": [0, 0], "radius": 1})),
+ ("sketch.circle.two_point", json!({"p0": [0, 0], "p1": [5, 5]})),
+ ("sketch.circle.three_point", json!({"p0": [0, 0], "p1": [5, 5], "p2": [10, 0]})),
+ ("sketch.arc.three_point", json!({"start": [0, 0], "end": [10, 0], "through": [5, 5]})),
+ ("sketch.arc.center_point", json!({"center": [0, 0], "start": [5, 0], "sweep": 90})),
+ ];
+ for (id, p) in &base {
+ assert!(issues(id, p).is_empty(), "{id} {p}");
+ for key in ["connect", "construction", "closed", "infer", "clockwise"] {
+ let mut bad = p.clone();
+ bad[key] = json!("yes");
+ if input_schema_has(id, key) {
+ assert_eq!(issues(id, &bad).len(), 1, "{id} {key}: {:?}", issues(id, &bad));
+ }
+ }
+ let mut bad = p.clone();
+ bad["sketch"] = json!(true);
+ assert_eq!(issues(id, &bad)[0].message, "`sketch` must be an id or a name");
+ }
+ let message = |id: &str, p: Value| issues(id, &p).first().map(|i| i.message.clone());
+ assert_eq!(message("sketch.point", json!({"point": [1, 1], "id": 5})).as_deref(), Some("`id` must be text"));
+ assert_eq!(
+ message("sketch.arc.center_point", json!({"center": [0, 0], "start": [5, 0], "sweep": "90"})).as_deref(),
+ Some("`sweep` must be a number of degrees")
+ );
+ assert_eq!(message("sketch.circle.center", json!({"center": [0, 0], "radius": 1, "through": {"vertex": [1, 2, 3]}})), None);
+ assert_eq!(message("sketch.point", json!({"point": {"on_edge": [1, 2, 3]}})), None);
+ assert_eq!(message("sketch.point", json!({"point": "vertex:1,2,3"})), None);
+ assert_eq!(message("sketch.line", json!({"points": [{"vertex": [1, 2, 3]}, {"on_edge": [1, 2, 3]}]})), None);
+}
+
+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))
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index f7a166d217..51c6188e8d 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -95,9 +95,7 @@ sheet.export_bend_table
sheet.export_dxf
sheet.flat_pattern
sheet.path_flange
-sketch.arc.center_point
sketch.arc.tangent
-sketch.arc.three_point
sketch.auto_constrain
sketch.auto_constrain_from_datum
sketch.auto_project
@@ -105,10 +103,7 @@ sketch.blend_curve
sketch.break_link
sketch.centerline
sketch.chain
-sketch.circle.center
-sketch.circle.three_point
sketch.circle.three_tangent
-sketch.circle.two_point
sketch.circle.two_tangent
sketch.conic
sketch.constrainer
@@ -136,13 +131,11 @@ sketch.inspect
sketch.intersect
sketch.intersection_curve
sketch.isoparametric_curve
-sketch.line
sketch.line.midpoint
sketch.line3d
sketch.move3d
sketch.move_point
sketch.options
-sketch.point
sketch.point3d
sketch.polygon.circumscribed
sketch.polygon.edge