Skip to content

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

Agents and scripts: Match Surface describes its exact parameters and reply (#10981) (#10982)

austin62jakee199f9aeff95
diff --git a/crates/engine/src/cmd/surface_match.rs b/crates/engine/src/cmd/surface_match.rs
index a16e8edf45..bb5e6f303c 100644
--- a/crates/engine/src/cmd/surface_match.rs
+++ b/crates/engine/src/cmd/surface_match.rs
@@ -10,12 +10,19 @@ use solidcraft_kernel::{Construction, Continuity};
use super::CommandSpec;
use super::features::add_feature;
use crate::params::{bad, str_, vec3};
+use crate::schema::features::FeatureResult;
+use crate::schema::surface_match::MatchSurfaceParams;
+use crate::schema::{TypedContract, output_schema_for};
use crate::{Result, Session};
+const CONTRACT: TypedContract<MatchSurfaceParams> = TypedContract::new();
+
pub static COMMANDS: &[CommandSpec] = &[
- CommandSpec::new("surface.match", "Match Surface", match_surface)
+ CommandSpec::new("surface.match", "Match Surface", crate::checked!("surface.match", match_surface))
.at("SURFACE", "MODIFY")
.icon("continuity")
+ .contract(&CONTRACT)
+ .output(output_schema_for::<FeatureResult>)
.params(
"body: surface name (the body whose face is rebuilt); faces?: [[x,y,z]] (points on that face, default: the body's first); target: body name (the body the seam must meet); edges: [[x,y,z]] (points on one edge chain of the target: the rebuilt boundary takes its place); order?: g1|g2|g3 (default g2: position and tangent plane, the curvature too, or how that curvature changes along the seam). The far boundary stays where it was and the body keeps its name",
),
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index a13d3c77c8..a0b17878e2 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -86,6 +86,7 @@ pub mod sketch_equation;
pub mod sketch_inspect;
pub mod surface_analysis;
pub mod surface_boundary;
+pub mod surface_match;
pub mod ui_prefs;
pub mod view_navigation;
diff --git a/crates/engine/src/schema/surface_match.rs b/crates/engine/src/schema/surface_match.rs
new file mode 100644
index 0000000000..c4dfdcbfcb
--- /dev/null
+++ b/crates/engine/src/schema/surface_match.rs
@@ -0,0 +1,165 @@
+//! Contract for `surface.match` in `cmd/surface_match.rs` (#10981). It returns `add_feature`'s
+//! reply, a [`super::features::FeatureResult`].
+
+use std::borrow::Cow;
+
+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
+use serde::de::Error as _;
+use serde::{Deserialize, Deserializer};
+use serde_json::Value;
+use solidcore_record::Vec3;
+use solidcraft_kernel::{Construction, Continuity};
+
+use super::check::whole;
+use super::types::{Point3, StringList, present};
+use crate::params;
+
+/// Rebuild one face of a surface body so that its boundary nearest a picked edge chain of another
+/// body lies on that chain and repeats that body's shape there up to `order`, while the opposite
+/// boundary keeps its place. The body keeps its name: a match changes it rather than making one.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct MatchSurfaceParams {
+ /// The surface body whose face is rebuilt, by name.
+ #[serde(deserialize_with = "body")]
+ pub body: String,
+ #[serde(default)]
+ pub faces: Option<MatchFaces>,
+ /// The body the seam must meet, by name.
+ #[serde(deserialize_with = "target")]
+ pub target: String,
+ pub edges: MatchEdges,
+ /// How closely the seam follows the target: `g1` (tangent), `g2` (curvature, the default) or
+ /// `g3`, in any case.
+ #[serde(default, deserialize_with = "present")]
+ #[schemars(with = "MatchOrder")]
+ pub order: Option<MatchOrder>,
+ // Not `FeatureCommon`: a match makes no body, so `body_name` and `body_names` would do
+ // nothing. `participants` stays because `timeline.redefine` passes a feature's own back.
+ /// The feature's name in the timeline.
+ #[serde(default)]
+ pub name: Option<String>,
+ /// The bodies taking part, which every feature records; each an existing body or `*`. A match
+ /// changes only `body`, whatever this lists.
+ #[serde(default)]
+ pub participants: Option<StringList>,
+}
+
+/// A body name, with the handler's message for anything that isn't text.
+fn body<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(s) => Ok(s),
+ _ => Err(D::Error::custom(whole("`body` is required"))),
+ }
+}
+
+/// The target's name, with the handler's message for anything that isn't text.
+fn target<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(s) => Ok(s),
+ _ => Err(D::Error::custom(whole("`target` is required"))),
+ }
+}
+
+/// Points `params::vec3` reads, or none if any isn't one.
+fn points(v: &[Value]) -> Option<Vec<Vec3>> {
+ v.iter().map(params::vec3).collect()
+}
+
+/// Points on the face to rebuild, at most 64 (default: the body's first face).
+#[derive(Clone, Debug, PartialEq)]
+pub struct MatchFaces(pub Vec<Vec3>);
+
+impl<'de> Deserialize<'de> for MatchFaces {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let faces =
+ Value::deserialize(d)?.as_array().and_then(|a| points(a)).ok_or_else(|| D::Error::custom("must be a list of points [x, y, z]"))?;
+ if faces.len() > 64 {
+ return Err(D::Error::custom(whole("too many points on the face to rebuild")));
+ }
+ Ok(MatchFaces(faces))
+ }
+}
+
+impl JsonSchema for MatchFaces {
+ fn schema_name() -> Cow<'static, str> {
+ "MatchFaces".into()
+ }
+ fn inline_schema() -> bool {
+ true
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<Point3>();
+ json_schema!({
+ "description": "Points on the face to rebuild, at most 64 (default: the body's first face).",
+ "type": "array",
+ "items": point,
+ "maxItems": 64
+ })
+ }
+}
+
+/// Points on one edge chain of the target: the rebuilt boundary takes its place. 1 to 10 000,
+/// with the handler's message for anything else.
+#[derive(Clone, Debug, PartialEq)]
+pub struct MatchEdges(pub Vec<Vec3>);
+
+impl<'de> Deserialize<'de> for MatchEdges {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ Value::deserialize(d)?
+ .as_array()
+ .and_then(|a| points(a))
+ .filter(|edges| !edges.is_empty() && edges.len() <= 10_000)
+ .map(MatchEdges)
+ .ok_or_else(|| D::Error::custom(whole("`edges` must list 1 to 10000 points on the target's edge chain")))
+ }
+}
+
+impl JsonSchema for MatchEdges {
+ fn schema_name() -> Cow<'static, str> {
+ "MatchEdges".into()
+ }
+ fn inline_schema() -> bool {
+ true
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<Point3>();
+ json_schema!({
+ "description": "Points on one edge chain of the target: the rebuilt boundary takes its place.",
+ "type": "array",
+ "items": point,
+ "minItems": 1,
+ "maxItems": 10000
+ })
+ }
+}
+
+/// A match's continuity, as `params::continuity` reads it for a match (g1 to g3), with its messages.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct MatchOrder(pub Continuity);
+
+impl<'de> Deserialize<'de> for MatchOrder {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ params::continuity("surface.match", Some(&v), "`order`", Construction::Match).map(MatchOrder).map_err(|e| match e {
+ crate::EngineError::BadParams { msg, .. } => D::Error::custom(whole(msg)),
+ other => D::Error::custom(whole(other.to_string())),
+ })
+ }
+}
+
+impl JsonSchema for MatchOrder {
+ fn schema_name() -> Cow<'static, str> {
+ "MatchOrder".into()
+ }
+ fn inline_schema() -> bool {
+ true
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"type": "string", "pattern": "^[gG][123]$"})
+ }
+}
+
+#[cfg(test)]
+#[path = "surface_match_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/surface_match_tests.rs b/crates/engine/src/schema/surface_match_tests.rs
new file mode 100644
index 0000000000..47bedff2ec
--- /dev/null
+++ b/crates/engine/src/schema/surface_match_tests.rs
@@ -0,0 +1,121 @@
+use serde_json::{Value, json};
+use solidcore_record::Vec3;
+
+use super::MatchSurfaceParams;
+use crate::Session;
+use crate::schema::features::FeatureResult;
+use crate::schema::tests::{assert_keys, conforms};
+use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
+
+fn run(s: &mut Session, id: &str, p: Value) -> Value {
+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
+}
+
+/// Two points on the cylinder's straight vertical wall seam, as the command's own tests pick it.
+fn picks(s: &Session) -> Vec<Vec3> {
+ let boss = s.world_state().ok().and_then(|st| st.body("Boss").map(|b| b.body.clone())).unwrap_or_else(|| panic!("no Boss"));
+ let e = boss
+ .edges(boss.size() * 1e-2)
+ .unwrap_or_default()
+ .into_iter()
+ .find(|e| e.length > 25.0 && (e.mid.x.hypot(e.mid.y) - 10.0).abs() < 0.05 && e.mid.z > 5.0 && e.mid.z < 25.0)
+ .unwrap_or_else(|| panic!("the cylinder has a straight vertical wall seam"));
+ let (a, b) = (e.points.first().copied().unwrap_or(e.mid), e.points.last().copied().unwrap_or(e.mid));
+ vec![a + (b - a) * 0.25, a + (b - a) * 0.75]
+}
+
+/// A cylinder `Boss` of radius 10, 30 high, and a cylindrical surface `Skirt` of radius 11 from
+/// the cylinder's wall seam round 60 degrees, as in the command's own tests: a point on the skirt.
+fn boss_and_skirt(s: &mut Session) -> [f64; 3] {
+ run(s, "sketch.create", json!({"plane": "XY", "name": "Round"}));
+ run(s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10}));
+ run(s, "sketch.finish", json!({}));
+ run(s, "solid.extrude", json!({"sketch": "Round", "distance": 30, "body_name": "Boss"}));
+ let seam = picks(s)[0];
+ let a = seam.y.atan2(seam.x);
+ let at = |t: f64| json!([11.0 * t.cos(), 11.0 * t.sin()]);
+ run(s, "sketch.create", json!({"plane": "XY", "name": "Skirt sketch"}));
+ let arc = run(s, "sketch.arc.three_point", json!({"start": at(a), "end": at(a + 60f64.to_radians()), "through": at(a + 30f64.to_radians())}))
+ ["created"]["curves"][0]
+ .clone();
+ run(s, "sketch.finish", json!({}));
+ run(s, "surface.extrude", json!({"sketch": "Skirt sketch", "curves": [arc], "distance": 30, "body_name": "Skirt"}));
+ let mid = a + 30f64.to_radians();
+ [11.0 * mid.cos(), 11.0 * mid.sin(), 15.0]
+}
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<MatchSurfaceParams>(), &["body", "edges", "faces", "name", "order", "participants", "target"]);
+}
+
+/// A call that fails today gets the same message in strict. The handler looks both bodies up
+/// before it reads the picks, so each call runs on a design with two (a missing `edges` is left
+/// out: strict says it is required, the handler what it must list).
+#[test]
+fn strict_keeps_todays_errors() {
+ let many = vec![[0, 0, 0]; 10_001];
+ let faces = vec![[0, 0, 0]; 65];
+ let e = json!([[0, 0, 0]]);
+ for p in [
+ json!({"target": "T", "edges": e}),
+ json!({"body": 5, "target": "T", "edges": e}),
+ json!({"body": "Nope", "target": "T", "edges": e}),
+ json!({"body": "B", "edges": e}),
+ json!({"body": "B", "target": [], "edges": e}),
+ json!({"body": "B", "target": "Nope", "edges": e}),
+ json!({"body": "B", "target": "T", "faces": faces, "edges": e}),
+ json!({"body": "B", "target": "T", "edges": []}),
+ json!({"body": "B", "target": "T", "edges": null}),
+ json!({"body": "B", "target": "T", "edges": 5}),
+ json!({"body": "B", "target": "T", "edges": [[1, 2]]}),
+ json!({"body": "B", "target": "T", "edges": many}),
+ json!({"body": "B", "target": "T", "edges": e, "order": "g5"}),
+ json!({"body": "B", "target": "T", "edges": e, "order": "g0"}),
+ json!({"body": "B", "target": "T", "edges": e, "order": null}),
+ json!({"body": "B", "target": "T", "edges": e, "order": 2}),
+ json!({"body": "B", "target": "T", "edges": e}),
+ ] {
+ let error = |level: ParamCheck| {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 4, "body_name": "B"}));
+ run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 4, "corner": [10, 0, 0], "body_name": "T"}));
+ s.param_check = level;
+ s.execute("surface.match", &p).err().map(|e| e.to_string())
+ };
+ let off = error(ParamCheck::Off);
+ assert!(off.is_some(), "{p} should fail today");
+ assert_eq!(error(ParamCheck::Strict), off, "{p}");
+ }
+}
+
+/// #10981: a match replies with `FeatureResult`, in Warn without warnings for good calls (the
+/// body's first face, and a picked face with every other key) and with them for a misspelt key;
+/// strict refuses a face point the handler would drop.
+#[test]
+fn a_match_replies_with_the_feature_result() {
+ let schema = output_schema_for::<FeatureResult>();
+ let matches = |r: &Value, warned: bool| {
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
+ assert_eq!(r.get("param_warnings").is_some(), warned, "{r}");
+ };
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let on_skirt = boss_and_skirt(&mut s);
+ let chain = picks(&s);
+ let r = run(&mut s, "surface.match", json!({"body": "Skirt", "target": "Boss", "edges": chain, "order": "G2"}));
+ matches(&r, false);
+ assert_eq!(r["changed_bodies"], json!(["Skirt"]), "{r}");
+ let r = run(
+ &mut s,
+ "surface.match",
+ json!({"body": "Skirt", "faces": [on_skirt], "target": "Boss", "edges": chain, "order": "g1", "name": "Seam", "participants": ["*"]}),
+ );
+ matches(&r, false);
+ assert_eq!(r["name"], "Seam", "{r}");
+ matches(&run(&mut s, "surface.match", json!({"body": "Skirt", "target": "Boss", "edges": chain, "ordr": "g3"})), true);
+ s.param_check = ParamCheck::Strict;
+ let error = s.execute("surface.match", &json!({"body": "Skirt", "faces": [on_skirt, [1, 2]], "target": "Boss", "edges": chain}));
+ let error = error.err().map(|e| e.to_string());
+ assert!(error.as_deref().is_some_and(|e| e.contains("`faces` must be a list of points")), "{error:?}");
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index ea1c6f24c9..018ef6d57c 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -329,7 +329,6 @@ surface.extend
surface.extrude
surface.fair
surface.loft
-surface.match
surface.offset
surface.patch
surface.reverse_normal