Typed schemas for the curvature comb, minimum radius, isocurve and centre of mass commands (#10949) (#10950)

* claim: #10949

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Curvature comb, minimum radius, isocurve, centre of mass: schemas (#10949)

The four analysis commands get typed contracts and reply types in
schema/sketch_inspect.rs and leave unconverted.txt. Each point list has
its own type with its handler's messages and reads only as many points
as the handler does; `count`, `density` and `scale` read numbers as
params::num does. The replies are built from the types, with the same
JSON as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
austin62jake
2026-11-02 18:40:25 +00:00
committed by GitHub
parent 38cc3507db
commit b73eb6c243
5 changed files with 398 additions and 33 deletions
+1
View File
@@ -76,6 +76,7 @@ pub mod sketch_constraints;
pub mod sketch_create;
pub mod sketch_ends;
pub mod sketch_equation;
pub mod sketch_inspect;
pub mod surface_analysis;
pub mod surface_boundary;
pub mod ui_prefs;
+257
View File
@@ -0,0 +1,257 @@
//! Contracts and result types for the commands in `cmd/sketch_inspect.rs`: curvature combs,
//! minimum radius and isocurves on sketch curves, model edges and faces, and the centre of mass
//! of bodies (#10949).
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;
use solidcraft_geom::Vec3;
use super::check::whole;
use super::types::{Point3, SketchRef, StringList, present};
use crate::params;
/// Points that pick edges or faces, read as the handler reads them: a list whose first `$limit`
/// items are each a point `params::vec3` reads (the handler looks at no more), with its message
/// for anything else and, where it refuses one, for an empty list.
macro_rules! point_list {
($(#[$doc:meta])* $name:ident, limit: $limit:literal, bad: $bad:literal, empty: $empty:expr) => {
$(#[$doc])*
#[derive(Clone, Debug, PartialEq)]
pub struct $name(pub Vec<Vec3>);
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let v = Value::deserialize(d)?;
let points = v.as_array().ok_or_else(|| D::Error::custom(whole($bad)))?;
let empty: Option<&str> = $empty;
if let (true, Some(message)) = (points.is_empty(), empty) {
return Err(D::Error::custom(whole(message)));
}
points.iter().take($limit).map(params::vec3).collect::<Option<Vec<_>>>().map($name).ok_or_else(|| D::Error::custom(whole($bad)))
}
}
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 {
let point = generator.subschema_for::<Point3>();
let empty: Option<&str> = $empty;
json_schema!({"type": "array", "items": point, "minItems": u32::from(empty.is_some())})
}
}
};
}
point_list!(
/// Points on model edges, each picking the nearest edge of any body (the first 1000 are used).
EdgePoints,
limit: 1000,
bad: "`edges` must be points [x,y,z]",
empty: None
);
point_list!(
/// Points on faces, for combs along each face's isoparametric curves (the first 100 are used).
CombFaces,
limit: 100,
bad: "`faces` must list points [x,y,z]",
empty: Some("`faces` must list points [x,y,z]")
);
point_list!(
/// Points on faces, each picking the nearest face of any body (the first 1000 are used).
RadiusFaces,
limit: 1000,
bad: "`faces` must be points [x,y,z]",
empty: None
);
point_list!(
/// Points on faces, each picking the nearest face of any body (the first 100 are used).
IsoFaces,
limit: 100,
bad: "`faces` must list points [x,y,z]",
empty: Some("`faces` is empty")
);
/// A number, as `params::num` reads one (finite, under 1e9 in size), with the curvature comb's
/// message for anything else; `null` is none.
fn number<'de, D: Deserializer<'de>>(d: D) -> Result<Option<f64>, D::Error> {
match Value::deserialize(d)? {
Value::Null => Ok(None),
v => v.as_f64().and_then(params::finite).map(Some).ok_or_else(|| D::Error::custom("must be a number")),
}
}
fn number_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({"type": ["number", "null"], "exclusiveMinimum": -1e9, "exclusiveMaximum": 1e9})
}
/// Curvature combs: teeth along each curve, edge or face isocurve, each as long as the curvature
/// there times `scale`, standing out on the convex side. Give `curves`, `edges` or `faces`, or
/// more than one.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct CurvatureCombParams {
/// Sketch curve ids (the first 1000 are used).
#[serde(default)]
pub curves: Option<StringList>,
/// The sketch the curves are in (default: the one being edited). Read only with `curves`.
#[serde(default)]
pub sketch: Option<SketchRef>,
#[serde(default)]
pub edges: Option<EdgePoints>,
#[serde(default, deserialize_with = "present")]
#[schemars(with = "CombFaces")]
pub faces: Option<CombFaces>,
/// With `faces`: how many isoparametric curves each way (default 4; 1 to 50).
#[serde(default, deserialize_with = "number")]
#[schemars(schema_with = "number_schema")]
pub count: Option<f64>,
/// Teeth per curve (default 40; 2 to 2000).
#[serde(default, deserialize_with = "number")]
#[schemars(schema_with = "number_schema")]
pub density: Option<f64>,
/// Tooth length per unit of curvature (mm²). Default, or when not above 0: the longest tooth
/// is a fifth of the size of everything combed.
#[serde(default, deserialize_with = "number")]
#[schemars(schema_with = "number_schema")]
pub scale: Option<f64>,
}
/// The smallest radius of curvature of each sketch curve, edge or face, and where it is. With
/// none of `curves`, `edges` and `faces`: every face of every body.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct MinimumRadiusParams {
/// Sketch curve ids (the first 1000 are used).
#[serde(default)]
pub curves: Option<StringList>,
/// The sketch the curves are in (default: the one being edited). Read only with `curves`.
#[serde(default)]
pub sketch: Option<SketchRef>,
#[serde(default)]
pub edges: Option<EdgePoints>,
#[serde(default)]
pub faces: Option<RadiusFaces>,
}
/// The isoparametric curves of faces.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct IsocurveParams {
pub faces: IsoFaces,
/// How many curves each way (default 8; 1 to 100).
#[serde(default, deserialize_with = "number")]
#[schemars(schema_with = "number_schema")]
pub count: Option<f64>,
}
/// The centre of mass of bodies, at uniform density, each and all together, where the bodies
/// are placed in the assembly.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct CenterOfMassParams {
/// The bodies, by name (default: all). A body whose volume can't be measured is left out.
#[serde(default)]
pub bodies: Option<StringList>,
}
/// What `inspect.curvature_comb` returns.
#[derive(Debug, Serialize, JsonSchema)]
pub struct CurvatureCombs {
/// One comb per curve, edge and face isocurve.
pub combs: Vec<Comb>,
/// The tooth length per unit of curvature used for every comb (mm²).
pub scale: f64,
/// 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>,
}
/// One curvature comb.
#[derive(Debug, Serialize, JsonSchema)]
pub struct Comb {
/// What it combs: a sketch curve's id, `edge@x,y,z` or `face@x,y,z#k` (the point given, and
/// the face's isocurve).
pub curve: String,
/// Each tooth, from the curve out to its tip.
pub teeth: Vec<[[f64; 3]; 2]>,
/// The teeth's tips, in order.
pub envelope: Vec<[f64; 3]>,
/// The largest curvature along it (1/mm).
pub max_curvature: f64,
/// Its smallest radius of curvature (mm); `null` when it is straight.
pub min_radius: Option<f64>,
}
/// What `inspect.minimum_radius` returns.
#[derive(Debug, Serialize, JsonSchema)]
pub struct MinimumRadii {
/// Each curve, edge or face looked at.
pub items: Vec<RadiusItem>,
/// The smallest of them all (mm); `null` when everything is straight or flat.
pub min_radius: Option<f64>,
/// Where that is; `null` with it.
pub at: Option<[f64; 3]>,
/// 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>,
}
/// One curve, edge or face's smallest radius of curvature.
#[derive(Debug, Serialize, JsonSchema)]
pub struct RadiusItem {
/// A sketch curve's id, `edge@x,y,z`, `face@x,y,z` (the point given) or `<body>:face<n>`.
pub item: String,
/// Its smallest radius of curvature (mm); `null` when it is straight or flat.
pub min_radius: Option<f64>,
/// Where that is; only with a radius.
#[serde(skip_serializing_if = "Option::is_none")]
pub at: Option<[f64; 3]>,
}
/// What `inspect.isocurve` returns.
#[derive(Debug, Serialize, JsonSchema)]
pub struct Isocurves {
/// Each isoparametric curve as points along it, `count` each way per face.
pub curves: Vec<Vec<[f64; 3]>>,
/// 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 `inspect.center_of_mass` returns.
#[derive(Debug, Serialize, JsonSchema)]
pub struct CentersOfMass {
/// The centre of mass of the bodies together.
pub center: [f64; 3],
/// Their volume together (mm³).
pub volume: f64,
/// Each body measured.
pub bodies: Vec<BodyCenter>,
/// 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>,
}
/// One body's centre of mass.
#[derive(Debug, Serialize, JsonSchema)]
pub struct BodyCenter {
/// Its name, in the assembly.
pub body: String,
/// Its centre of mass.
pub center: [f64; 3],
/// Its volume (mm³).
pub volume: f64,
}
#[cfg(test)]
#[path = "sketch_inspect_tests.rs"]
mod tests;
@@ -0,0 +1,96 @@
use serde_json::{Value, json};
use super::{CenterOfMassParams, CentersOfMass, CurvatureCombParams, CurvatureCombs, IsocurveParams, Isocurves, MinimumRadii, MinimumRadiusParams};
use crate::Session;
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
#[test]
fn schemas_and_the_key_check_agree() {
assert_keys(input_schema_for::<CurvatureCombParams>(), &["count", "curves", "density", "edges", "faces", "scale", "sketch"]);
assert_keys(input_schema_for::<MinimumRadiusParams>(), &["curves", "edges", "faces", "sketch"]);
assert_keys(input_schema_for::<IsocurveParams>(), &["count", "faces"]);
assert_keys(input_schema_for::<CenterOfMassParams>(), &["bodies"]);
}
/// Each point list keeps its own command's messages: a bad point, an empty list, `null`.
#[test]
fn strict_keeps_todays_errors() {
assert_strict_keeps_todays_errors(&[
("inspect.curvature_comb", json!({})),
("inspect.curvature_comb", json!({"faces": []})),
("inspect.curvature_comb", json!({"faces": null})),
("inspect.curvature_comb", json!({"faces": "x"})),
("inspect.curvature_comb", json!({"faces": [[1, 2]]})),
("inspect.curvature_comb", json!({"faces": [[0, 0, 0]], "count": "x"})),
("inspect.curvature_comb", json!({"faces": [[0, 0, 0]], "count": 1e9})),
("inspect.curvature_comb", json!({"edges": [[1, 2]]})),
("inspect.curvature_comb", json!({"edges": [[0, 0, 1e9]]})),
("inspect.minimum_radius", json!({"edges": ["x"]})),
("inspect.minimum_radius", json!({"faces": [[1, 2]]})),
("inspect.minimum_radius", json!({"faces": [[0, 0, 500]]})),
("inspect.isocurve", json!({"faces": []})),
("inspect.isocurve", json!({"faces": null})),
("inspect.isocurve", json!({"faces": 5})),
("inspect.isocurve", json!({"faces": [[1, 2]]})),
("inspect.isocurve", json!({"faces": [{"x": 0, "y": 0, "z": 500}]})),
("inspect.center_of_mass", json!({})),
("inspect.center_of_mass", json!({"bodies": ["nope"]})),
]);
}
/// #10949: the four analysis commands reply as their output schemas say, in Warn without
/// warnings for good calls and with them for a misspelt key, on sketch curves, a cylinder's
/// edge and face, and every face. A `density` that isn't a number, which the handler reads as
/// none, gets a warning, and strict refuses it.
#[test]
fn analysis_commands_reply_with_their_schemas() {
let (combs, radii, isocurves, centers) = (
output_schema_for::<CurvatureCombs>(),
output_schema_for::<MinimumRadii>(),
output_schema_for::<Isocurves>(),
output_schema_for::<CentersOfMass>(),
);
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
let run = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
let matches = |schema: &schemars::Schema, 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}");
};
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Curves"}));
let circle = run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 5}))["curves"][0].clone();
let line = run(&mut s, "sketch.line", json!({"points": [[0, 20], [10, 20]]}))["curves"][0].clone();
let r = run(&mut s, "inspect.curvature_comb", json!({"curves": [circle, line], "density": 20}));
matches(&combs, &r, false);
assert!(r["combs"][1]["min_radius"].is_null(), "a line is straight: {r}");
let r = run(&mut s, "inspect.minimum_radius", json!({"curves": circle, "sketch": "Curves"}));
matches(&radii, &r, false);
assert!(r["items"][0]["at"].is_array() && r["at"].is_array(), "{r}");
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.cylinder", json!({"base": [50, 0, 0], "radius": 8, "height": 10, "body_name": "Can"}));
matches(&combs, &run(&mut s, "inspect.curvature_comb", json!({"edges": [[58, 0, 10]]})), false);
let r = run(&mut s, "inspect.curvature_comb", json!({"faces": [{"x": 58, "y": 0, "z": 5}], "count": 3, "scale": 0.5}));
matches(&combs, &r, false);
assert_eq!(r["scale"], 0.5, "{r}");
matches(&radii, &run(&mut s, "inspect.minimum_radius", json!({"faces": [[58, 0, 5]], "edges": [[58, 0, 10]]})), false);
// Every face: the flat ends have no radius, and so no `at`.
let r = run(&mut s, "inspect.minimum_radius", json!({}));
matches(&radii, &r, false);
assert!(r["items"].as_array().into_iter().flatten().any(|i| i["min_radius"].is_null() && i.get("at").is_none()), "{r}");
matches(&isocurves, &run(&mut s, "inspect.isocurve", json!({"faces": [[58, 0, 5]], "count": 4})), false);
matches(&centers, &run(&mut s, "inspect.center_of_mass", json!({})), false);
let r = run(&mut s, "inspect.center_of_mass", json!({"bodies": "Can"}));
matches(&centers, &r, false);
assert_eq!(r["bodies"][0]["body"], "Can", "{r}");
matches(&combs, &run(&mut s, "inspect.curvature_comb", json!({"edges": [[58, 0, 10]], "dencity": 20})), true);
matches(&combs, &run(&mut s, "inspect.curvature_comb", json!({"edges": [[58, 0, 10]], "density": "20"})), true);
matches(&radii, &run(&mut s, "inspect.minimum_radius", json!({"face": [[58, 0, 5]]})), true);
matches(&isocurves, &run(&mut s, "inspect.isocurve", json!({"faces": [[58, 0, 5]], "cnt": 2})), true);
matches(&centers, &run(&mut s, "inspect.center_of_mass", json!({"body": "Can"})), true);
s.param_check = ParamCheck::Strict;
let error = s.execute("inspect.curvature_comb", &json!({"edges": [[58, 0, 10]], "density": "20"})).err().map(|e| e.to_string());
assert!(error.as_deref().is_some_and(|e| e.contains("`density` must be a number")), "{error:?}");
}
-4
View File
@@ -90,14 +90,10 @@ frame.member
frame.profile.insert
frame.profile.list
frame.profile.properties
inspect.center_of_mass
inspect.clearance
inspect.compare
inspect.curvature_comb
inspect.interference
inspect.isocurve
inspect.measure
inspect.minimum_radius
inspect.parameter_sweep
inspect.silhouette
joint.as_built