Typed schemas for List Edges, List Faces and List Threads (#10942) (#10943)

* claim: #10942

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

* List Edges, List Faces and List Threads: input and output schemas (#10942)

model.edges and model.faces take a typed `body`; model.threads takes no
parameters. Their replies are built from ModelEdges, ModelFaces and
ModelThreads in schema/inspect.rs, with the same JSON as before, and the
three commands leave unconverted.txt.

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:41:09 +00:00
committed by GitHub
parent b73eb6c243
commit 7015c296ea
4 changed files with 279 additions and 26 deletions
+57 -19
View File
@@ -10,8 +10,15 @@ use solidcraft_sketch::CurveKind;
use super::CommandSpec;
use crate::params::{bad, bool_, str_, string_list};
use crate::schema::inspect::{
BodyListParams, FaceCylinder, ModelEdge, ModelEdges, ModelFace, ModelFaces, ModelThread, ModelThreads, ModelThreadsParams,
};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
const BODY_LIST_CONTRACT: TypedContract<BodyListParams> = TypedContract::new();
const THREADS_CONTRACT: TypedContract<ModelThreadsParams> = TypedContract::new();
#[path = "appearance_chain.rs"]
mod appearance_chain;
@@ -35,14 +42,28 @@ pub static COMMANDS: &[CommandSpec] = &[
never on a selection or a view; from one counter for the whole run, so it never repeats). Read-only",
),
CommandSpec::new("sketch.inspect", "Inspect Sketch", sketch_inspect).at("SKETCH", "INSPECT").icon("inspect").noundo().params("sketch?: id|name (default active)"),
CommandSpec::new("model.edges", "List Edges", model_edges).icon("inspect").noundo().params("body: name"),
CommandSpec::new("model.faces", "List Faces", model_faces).icon("inspect").noundo().params(
CommandSpec::new("model.edges", "List Edges", crate::checked!("model.edges", model_edges))
.icon("inspect")
.noundo()
.contract(&BODY_LIST_CONTRACT)
.output(output_schema_for::<ModelEdges>)
.params("body: name"),
CommandSpec::new("model.faces", "List Faces", crate::checked!("model.faces", model_faces))
.icon("inspect")
.noundo()
.contract(&BODY_LIST_CONTRACT)
.output(output_schema_for::<ModelFaces>)
.params(
"body: name → per face: index, name (what face.delete, sheet.convert `face`, solid.shell … take in place of a point), exact, area, centroid (not always on the face), \
plane_normal, point (a point on the face that picks it), cylinder? ({origin, axis, radius} of a cylindrical face), \
sheet_face? (a folded sheet's face: `sheet:<body>:<panel>:<side>`, panel base or a flange's tag F<feature>.<k>, side top | bottom | rim.<edge> | bend.inner | bend.outer; \
taken wherever a face name is, and it holds while sizes change and flanges come and go)",
),
CommandSpec::new("model.threads", "List Threads", model_threads).icon("inspect").noundo(),
CommandSpec::new("model.threads", "List Threads", crate::checked!("model.threads", model_threads))
.icon("inspect")
.noundo()
.contract(&THREADS_CONTRACT)
.output(output_schema_for::<ModelThreads>),
CommandSpec::new("material.assign", "Physical Material", physical_material)
.at("SOLID", "MODIFY")
.icon("material")
@@ -395,13 +416,24 @@ fn model_edges(s: &mut Session, p: &Value) -> Result<Value> {
let b = body_of(&st, p, "model.edges")?;
let tol = (b.body.size() * 2e-3).max(1e-3);
let names = solidcraft_doc::naming::edge_names(b);
let edges: Vec<Value> = b
let edges = b
.body
.edges(tol)?
.iter()
.map(|e| json!({"index": e.index, "name": names.get(e.index), "mid": e.mid, "length": e.length, "start": e.points.first(), "end": e.points.last()}))
.map(|e| ModelEdge {
index: e.index,
name: names.get(e.index).cloned(),
mid: e.mid.into(),
length: e.length,
start: e.points.first().map(|&p| p.into()),
end: e.points.last().map(|&p| p.into()),
})
.collect();
Ok(json!({"body": b.name, "edges": edges}))
reply("model.edges", ModelEdges { body: b.name.clone(), edges, param_warnings: Vec::new() })
}
fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
}
fn model_faces(s: &mut Session, p: &Value) -> Result<Value> {
@@ -414,26 +446,32 @@ fn model_faces(s: &mut Session, p: &Value) -> Result<Value> {
// the body's own coordinates.
let model = s.model.state();
let sheet_names = model.body(&b.name).map(|own| solidcraft_doc::sheet::body_sheet_face_names(&model, own)).unwrap_or_default();
let faces: Vec<Value> = b
let faces = b
.body
.faces(tol)?
.iter()
.map(|f| {
let spot = spots.get(f.index).copied().flatten();
let mut v = json!({"index": f.index, "name": names.get(f.index), "exact": solidcraft_doc::naming::face_name_exact(b, f.index),
"area": f.area, "centroid": f.centroid, "plane_normal": f.plane_normal, "point": spot.map(|x| x.point)});
if let (Some(Some(name)), Some(o)) = (sheet_names.get(f.index), v.as_object_mut()) {
o.insert("sheet_face".into(), json!(name));
let cylinder = match spot.and_then(|x| x.surface) {
Some(solidcraft_kernel::FaceSurface::Cylinder { origin, axis, radius }) => {
Some(FaceCylinder { origin: origin.into(), axis: solidcraft_geom::Vec3::from(axis).into(), radius })
}
_ => None,
};
ModelFace {
index: f.index,
name: names.get(f.index).cloned(),
exact: solidcraft_doc::naming::face_name_exact(b, f.index),
area: f.area,
centroid: f.centroid.into(),
plane_normal: f.plane_normal.map(Into::into),
point: spot.map(|x| x.point.into()),
cylinder,
sheet_face: sheet_names.get(f.index).and_then(|n| n.as_ref().map(|n| n.to_string())),
}
if let (Some(solidcraft_kernel::FaceSurface::Cylinder { origin, axis, radius }), Some(o)) =
(spot.and_then(|x| x.surface), v.as_object_mut())
{
o.insert("cylinder".into(), json!({"origin": origin, "axis": axis, "radius": radius}));
}
v
})
.collect();
Ok(json!({"body": b.name, "faces": faces}))
reply("model.faces", ModelFaces { body: b.name.clone(), faces, param_warnings: Vec::new() })
}
const DESCRIBE_CONTRACT: crate::schema::TypedContract<crate::schema::inspect::DescribeParams> = crate::schema::TypedContract::new();
@@ -459,7 +497,7 @@ fn commands(s: &mut Session, _p: &Value) -> Result<Value> {
fn model_threads(s: &mut Session, _p: &Value) -> Result<Value> {
let st = s.world_state();
Ok(json!({ "threads": st.threads }))
reply("model.threads", ModelThreads { threads: st.threads.iter().map(ModelThread::from).collect(), param_warnings: Vec::new() })
}
fn physical_material(s: &mut Session, p: &Value) -> Result<Value> {
+165
View File
@@ -37,6 +37,171 @@ pub struct DescribeResult {
pub param_warnings: Vec<String>,
}
/// List a body's edges or faces, with what picks each one.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct BodyListParams {
/// The body, by name.
pub body: String,
}
/// List the design's cosmetic threads.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ModelThreadsParams {}
/// What `model.edges` returns.
#[derive(Debug, Serialize, JsonSchema)]
pub struct ModelEdges {
/// The body's name.
pub body: String,
/// Its edges, in the kernel's order.
pub edges: Vec<ModelEdge>,
/// 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 edge of a body.
#[derive(Debug, Serialize, JsonSchema)]
pub struct ModelEdge {
/// Its index, which changes when the body is rebuilt differently.
pub index: usize,
/// Its name, `<face A>|<face B>` from the faces it joins (numbered when repeated); `null`
/// when it has none.
pub name: Option<String>,
/// The point halfway along it, which picks it.
pub mid: [f64; 3],
/// Its length (mm).
pub length: f64,
/// Where it starts; `null` for an edge with no points.
pub start: Option<[f64; 3]>,
/// Where it ends; `null` for an edge with no points.
pub end: Option<[f64; 3]>,
}
/// What `model.faces` returns.
#[derive(Debug, Serialize, JsonSchema)]
pub struct ModelFaces {
/// The body's name.
pub body: String,
/// Its faces, in the kernel's order.
pub faces: Vec<ModelFace>,
/// 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 face of a body.
#[derive(Debug, Serialize, JsonSchema)]
pub struct ModelFace {
/// Its index, which changes when the body is rebuilt differently.
pub index: usize,
/// Its name: what `face.delete`, `sheet.convert`'s `face`, `solid.shell` and others take in
/// place of a point. `null` when it has none.
pub name: Option<String>,
/// Whether the name follows the face's exact history; `false` when it was worked out from
/// the geometry, which an edit earlier in the timeline can fool.
pub exact: bool,
/// Its area (mm²).
pub area: f64,
/// Its centroid, which isn't always on the face.
pub centroid: [f64; 3],
/// Its outward unit normal if it is planar, else `null`.
pub plane_normal: Option<[f64; 3]>,
/// A point on the face that picks it; `null` when none was found.
pub point: Option<[f64; 3]>,
/// For a cylindrical face: its axis and radius.
#[serde(skip_serializing_if = "Option::is_none")]
pub cylinder: Option<FaceCylinder>,
/// For a folded sheet's face: `sheet:<body>:<panel>:<side>`, where the panel is `base` or a
/// flange's tag `F<feature>.<k>` and the side is `top`, `bottom`, `rim.<edge>`, `bend.inner`
/// or `bend.outer`. It is taken wherever a face name is, and holds while sizes change and
/// flanges come and go.
#[serde(skip_serializing_if = "Option::is_none")]
pub sheet_face: Option<String>,
}
/// A cylindrical face's axis and radius.
#[derive(Debug, Serialize, JsonSchema)]
pub struct FaceCylinder {
/// A point on the axis.
pub origin: [f64; 3],
/// The axis direction, a unit vector.
pub axis: [f64; 3],
/// The radius (mm).
pub radius: f64,
}
/// What `model.threads` returns.
#[derive(Debug, Serialize, JsonSchema)]
pub struct ModelThreads {
/// The cosmetic threads, in timeline order.
pub threads: Vec<ModelThread>,
/// 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>,
}
/// A cosmetic thread: on which cylinder, its size, and the threaded part of the axis.
#[derive(Debug, Serialize, JsonSchema)]
pub struct ModelThread {
/// The id of the thread feature.
pub feature: u64,
/// The body it is on.
pub body: String,
/// Its size, such as `M6x1`.
pub designation: String,
/// Its major diameter (mm).
pub major_diameter: f64,
/// The radius of the cylindrical face it is on (mm).
pub radius: f64,
/// Its pitch (mm).
pub pitch: f64,
/// Whether it is cut into a hole rather than on a shaft.
pub internal: bool,
/// Which way it turns.
pub handedness: ThreadHand,
/// A point on the axis, which `start` and `end` are measured from.
pub axis_point: [f64; 3],
/// The axis direction, a unit vector.
pub axis: [f64; 3],
/// Where the threaded part starts along the axis from `axis_point` (mm).
pub start: f64,
/// Where it ends (mm).
pub end: f64,
}
/// Which way a thread turns.
#[derive(Clone, Copy, Debug, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ThreadHand {
Right,
Left,
}
impl From<&solidcraft_doc::ThreadInfo> for ModelThread {
fn from(t: &solidcraft_doc::ThreadInfo) -> Self {
ModelThread {
feature: t.feature,
body: t.body.clone(),
designation: t.designation.clone(),
major_diameter: t.major_diameter,
radius: t.radius,
pitch: t.pitch,
internal: t.internal,
handedness: match t.handedness {
solidcraft_doc::ThreadHandedness::Right => ThreadHand::Right,
solidcraft_doc::ThreadHandedness::Left => ThreadHand::Left,
},
axis_point: t.axis_point.into(),
axis: solidcraft_geom::Vec3::from(t.axis).into(),
start: t.start,
end: t.end,
}
}
}
#[cfg(test)]
#[path = "inspect_tests.rs"]
mod tests;
+57 -4
View File
@@ -1,13 +1,15 @@
use serde_json::json;
use serde_json::{Value, json};
use super::DescribeParams;
use super::{BodyListParams, DescribeParams, ModelEdges, ModelFaces, ModelThreads, ModelThreadsParams};
use crate::Session;
use crate::schema::input_schema_for;
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors};
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::<DescribeParams>(), &["command"]);
assert_keys(input_schema_for::<BodyListParams>(), &["body"]);
assert_keys(input_schema_for::<ModelThreadsParams>(), &[]);
}
#[test]
@@ -16,9 +18,60 @@ fn strict_keeps_todays_errors() {
("engine.describe", json!({"command": 5})),
("engine.describe", json!({"command": null})),
("engine.describe", json!({"command": "solid.extrud"})),
("model.edges", json!({})),
("model.edges", json!({"body": "Nope"})),
("model.faces", json!({})),
("model.faces", json!({"body": "Nope"})),
]);
}
/// #10942: a body's edges and faces and the design's threads reply as their output schemas say,
/// in Warn without warnings for good calls and with them for a misspelt key. A cylindrical face
/// carries `cylinder` and a folded sheet's face `sheet_face`; strict refuses a `body` that isn't
/// text, which the handlers read as no body.
#[test]
fn model_lists_reply_with_their_schemas() {
let (edges, faces, threads) = (output_schema_for::<ModelEdges>(), output_schema_for::<ModelFaces>(), output_schema_for::<ModelThreads>());
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, "solid.cylinder", json!({"radius": 4, "height": 20, "body_name": "Shaft"}));
run(&mut s, "solid.thread", json!({"face": [4, 0, 10], "designation": "M8"}));
run(&mut s, "sheet.manage_rules", json!({"name": "R1", "thickness": "1 mm", "bend_radius": "1 mm", "active": true}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Base"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [20, 0], "p1": [60, 30]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "sheet.flange", json!({"sketch": "Base"}));
let sheet = s.model.state().bodies.iter().map(|b| b.name.clone()).find(|n| n != "Shaft").unwrap_or_default();
let r = run(&mut s, "model.edges", json!({"body": "Shaft"}));
matches(&edges, &r, false);
assert!(r["edges"].as_array().is_some_and(|e| !e.is_empty()), "{r}");
let r = run(&mut s, "model.faces", json!({"body": "Shaft"}));
matches(&faces, &r, false);
assert!(r["faces"].as_array().into_iter().flatten().any(|f| f["cylinder"]["radius"].as_f64().is_some_and(|r| (r - 4.0).abs() < 1e-9)), "{r}");
let r = run(&mut s, "model.faces", json!({"body": sheet}));
matches(&faces, &r, false);
assert!(r["faces"].as_array().into_iter().flatten().any(|f| f["sheet_face"].as_str().is_some_and(|n| n.starts_with("sheet:"))), "{r}");
let r = run(&mut s, "model.threads", json!({}));
matches(&threads, &r, false);
assert_eq!((r["threads"][0]["designation"].as_str(), r["threads"][0]["handedness"].as_str()), (Some("M8"), Some("right")), "{r}");
matches(&edges, &run(&mut s, "model.edges", json!({"body": "Shaft", "bdy": 1})), true);
matches(&faces, &run(&mut s, "model.faces", json!({"body": "Shaft", "bdy": 1})), true);
matches(&threads, &run(&mut s, "model.threads", json!({"body": "Shaft"})), true);
let mut strict = Session { param_check: ParamCheck::Strict, ..Session::default() };
strict.execute("solid.cylinder", &json!({"radius": 4, "height": 20, "body_name": "Shaft"})).unwrap_or_else(|e| panic!("{e}"));
for id in ["model.edges", "model.faces"] {
let error = strict.execute(id, &json!({"body": 5})).err().map(|e| e.to_string()).unwrap_or_default();
assert!(error.contains("`body` must be text"), "{id}: {error}");
}
}
#[test]
fn describe_returns_both_schemas() {
let mut s = Session::default();
-3
View File
@@ -125,9 +125,6 @@ material.list
material.properties.directional
material.properties.validate
mesh.convert
model.edges
model.faces
model.threads
motion.delete
motion.export
motion.export_animation