Skip to content

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

Agents and scripts: Interference describes its exact parameters and reply (#12875)

austin62jake3dc258c20310
diff --git a/crates/engine/src/cmd/interference.rs b/crates/engine/src/cmd/interference.rs
index 69dec681c5..b99c15093f 100644
--- a/crates/engine/src/cmd/interference.rs
+++ b/crates/engine/src/cmd/interference.rs
@@ -13,7 +13,7 @@
use std::collections::HashSet;
use std::sync::Arc;
-use serde_json::{Value, json};
+use serde_json::Value;
use solidcore_record::Vec3;
use solidcraft_geom::mesh_distance::TriangleSet;
use solidcraft_geom::{Aabb3, Mesh};
@@ -21,6 +21,8 @@ use solidcraft_kernel::Body;
use solidcraft_kernel::profile::KernelTimes;
use crate::params::{bad, num, string_list};
+use crate::schema::clearance::{Overlap, OverlapBounds, Unchecked};
+use crate::schema::interference::{InterferenceResult, PairTime};
use crate::{Result, Session};
/// Most pairs with overlapping bounding boxes one call intersects.
@@ -49,7 +51,7 @@ struct Job {
/// What an exact check of one pair came to.
enum Outcome {
- Hit(Value),
+ Hit(Overlap),
Clear,
Unchecked(String),
}
@@ -159,26 +161,30 @@ pub(super) fn interference(s: &mut Session, p: &Value) -> Result<Value> {
let waited_ms = waited.elapsed().as_secs_f64() * 1000.0;
// Mesh bodies are not intersected: say so, rather than let `count: 0` read as "no overlap".
- let mut unchecked: Vec<Value> = meshes_left.iter().map(|b| json!({"a": b.name, "b": null, "reason": MESH_NOT_CHECKED})).collect();
+ let mut unchecked: Vec<Unchecked> =
+ meshes_left.iter().map(|b| Unchecked { a: b.name.clone(), b: None, reason: MESH_NOT_CHECKED.to_string() }).collect();
let (mut hits, mut timed) = (Vec::new(), Vec::new());
let (mut not_checked, mut boolean_ms, mut tessellate_ms) = (0usize, 0.0, 0.0);
for ((a, b), d) in done {
let Some(d) = d else {
not_checked += 1;
- unchecked.push(json!({"a": a, "b": b, "reason": format!("not checked: the time budget of {budget_s} s ran out (budget_s)")}));
+ unchecked.push(Unchecked { a, b: Some(b), reason: format!("not checked: the time budget of {budget_s} s ran out (budget_s)") });
continue;
};
boolean_ms += d.kernel.boolean_ms;
tessellate_ms += d.kernel.tessellate_ms;
- timed.push((
- d.ms,
- json!({"a": a, "b": b, "ms": round_ms(d.ms), "boolean_ms": round_ms(d.kernel.boolean_ms),
- "tessellate_ms": round_ms(d.kernel.tessellate_ms)}),
- ));
+ let time = PairTime {
+ a: a.clone(),
+ b: b.clone(),
+ ms: round_ms(d.ms),
+ boolean_ms: round_ms(d.kernel.boolean_ms),
+ tessellate_ms: round_ms(d.kernel.tessellate_ms),
+ };
+ timed.push((d.ms, time));
match d.outcome {
- Outcome::Hit(v) => hits.push(v),
+ Outcome::Hit(overlap) => hits.push(overlap),
Outcome::Clear => {}
- Outcome::Unchecked(reason) => unchecked.push(json!({"a": a, "b": b, "reason": reason})),
+ Outcome::Unchecked(reason) => unchecked.push(Unchecked { a, b: Some(b), reason }),
}
}
// A timing profile of the command (`--profile`) counts the kernel time the workers spent,
@@ -189,15 +195,28 @@ pub(super) fn interference(s: &mut Session, p: &Value) -> Result<Value> {
solidcraft_kernel::profile::credit(KernelTimes { boolean_ms: boolean_ms * share, tessellate_ms: tessellate_ms * share });
}
timed.sort_by(|x, y| y.0.total_cmp(&x.0));
- let slowest: Vec<Value> = timed.into_iter().take(SLOWEST).map(|t| t.1).collect();
- Ok(json!({
- "interferences": hits, "count": hits.len(), "checked": bodies.len(), "unchecked": unchecked,
- "truncated": skipped > 0, "skipped_pairs": skipped,
- "pairs_candidate": pairs.len(), "pairs_cleared": cleared, "pairs_intersected": intersected,
- "pairs_not_checked": not_checked, "budget_s": budget_s, "budget_exceeded": not_checked > 0,
- "threads": threads, "boolean_ms": round_ms(boolean_ms), "tessellate_ms": round_ms(tessellate_ms),
- "slowest": slowest, "ms": round_ms(started.elapsed().as_secs_f64() * 1000.0),
- }))
+ let slowest: Vec<PairTime> = timed.into_iter().take(SLOWEST).map(|t| t.1).collect();
+ let reply = InterferenceResult {
+ count: hits.len(),
+ interferences: hits,
+ checked: bodies.len(),
+ unchecked,
+ truncated: skipped > 0,
+ skipped_pairs: skipped,
+ pairs_candidate: pairs.len(),
+ pairs_cleared: cleared,
+ pairs_intersected: intersected,
+ pairs_not_checked: not_checked,
+ budget_s,
+ budget_exceeded: not_checked > 0,
+ threads,
+ boolean_ms: round_ms(boolean_ms),
+ tessellate_ms: round_ms(tessellate_ms),
+ slowest,
+ ms: round_ms(started.elapsed().as_secs_f64() * 1000.0),
+ param_warnings: Vec::new(),
+ };
+ serde_json::to_value(reply).map_err(|e| crate::EngineError::Other(e.to_string()))
}
fn round_ms(ms: f64) -> f64 {
@@ -284,9 +303,14 @@ fn check_pair(a: &Body, b: &Body, (na, nb): &(String, String)) -> Outcome {
Err(e) => return Outcome::Unchecked(e.to_string()),
};
if m.volume > threshold {
- let hit = json!({"a": na, "b": nb, "volume_mm3": m.volume, "area_mm2": m.area, "center": m.centroid,
- "bbox": {"min": m.bbox.min, "max": m.bbox.max}});
- return Outcome::Hit(hit);
+ return Outcome::Hit(Overlap {
+ a: na.clone(),
+ b: nb.clone(),
+ volume_mm3: m.volume,
+ area_mm2: m.area,
+ bbox: OverlapBounds { min: m.bbox.min.into(), max: m.bbox.max.into() },
+ center: m.centroid.into(),
+ });
}
Outcome::Clear
}
diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs
index 875b03a03c..2d7c30a62f 100644
--- a/crates/engine/src/cmd/joints.rs
+++ b/crates/engine/src/cmd/joints.rs
@@ -109,7 +109,13 @@ pub static COMMANDS: &[CommandSpec] = &[
links: [{index, role: driver|driven, …as joint.list}], errors, conflicts}] (reads only: nothing changes)",
),
CommandSpec::new("joint.solve", "Solve Joints", solve_cmd).icon("compute").params("re-place the occurrences from the joints → conflicts, errors, dof"),
- CommandSpec::new("inspect.interference", "Interference", super::interference::interference).at("SOLID", "INSPECT").icon("interference").noundo().params(
+ CommandSpec::new("inspect.interference", "Interference", crate::checked!("inspect.interference", super::interference::interference))
+ .contract(&crate::schema::TypedContract::<crate::schema::interference::InterferenceParams>::new())
+ .output(crate::schema::output_schema_for::<crate::schema::interference::InterferenceResult>)
+ .at("SOLID", "INSPECT")
+ .icon("interference")
+ .noundo()
+ .params(
"bodies?: [names] (default: all, in world placement; a name that is no body is refused); budget_s?: seconds (default 240, at most 86400: pairs not finished by then are listed in unchecked as \"not checked: the time budget … ran out\" and the call returns) → interferences: pairs that overlap with the overlap volume, area, bounding box and centre; unchecked: [{a, b, reason}], the pairs that could not be checked, with the reason, and each mesh body (STL, 3MF or OBJ import: not intersected) as {a: name, b: null, reason: \"mesh body: not checked\"}, so count: 0 is not read as no overlap (checked counts the solid bodies). Bodies are pruned by bounding box first, then by their display meshes (pairs whose meshes stay apart by more than their chord tolerances, neither inside the other, are clear without a boolean), so any number of bodies is fine; the pairs left are intersected exactly, in parallel on desktop, the slowest first; at most 20000 pairs whose boxes overlap are intersected per call (truncated: true and skipped_pairs: n say when more were left out). Also: pairs_candidate (boxes overlap), pairs_cleared (by the meshes), pairs_intersected, pairs_not_checked, budget_exceeded, threads (worker threads; 0: on the calling thread), boolean_ms and tessellate_ms (kernel time summed over the pairs), slowest: [{a, b, ms, boolean_ms, tessellate_ms}] and ms",
),
];
diff --git a/crates/engine/src/schema/interference.rs b/crates/engine/src/schema/interference.rs
new file mode 100644
index 0000000000..c7aaac7259
--- /dev/null
+++ b/crates/engine/src/schema/interference.rs
@@ -0,0 +1,118 @@
+//! Contract and reply type for Interference (`inspect.interference`, #12874), whose handler is
+//! `interference` in `cmd/interference.rs`: the pairs of solid bodies that share volume, and how
+//! much, in world placement. It changes nothing.
+//!
+//! Its hits and its `unchecked` entries have the shapes of Inspect Clearance's `Overlap` and
+//! `Unchecked` (`schema/clearance.rs`), which it reuses. The handler reads its parameters from
+//! the raw JSON, so each key here reads as its handler reads it and fails with its message.
+//! Whether each body exists stays the handler's to check.
+
+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
+use serde::de::Error as _;
+use serde::{Deserialize, Deserializer, Serialize};
+use serde_json::Value;
+
+use super::clearance::{Overlap, Unchecked};
+use super::config::NameList;
+
+/// The longest `budget_s` a call takes: a day (`MAX_BUDGET_S` in `cmd/interference.rs`).
+const MAX_BUDGET_S: f64 = 86_400.0;
+
+/// Find the pairs of solid bodies that share volume, in world placement, and how much. Pairs are
+/// ruled out by their boxes, then by their meshes; the pairs left are intersected exactly,
+/// slowest first, within `budget_s`. Mesh bodies aren't intersected: each is listed in
+/// `unchecked`.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct InterferenceParams {
+ /// The bodies to check, by name. Default (or `null`): every body. A name that is no body is
+ /// refused.
+ #[serde(default)]
+ pub bodies: Option<NameList>,
+ /// The seconds the exact checks may take, above 0, at most 86400 (a day). Pairs not finished
+ /// by then are listed in `unchecked`, and the call returns. Default (or `null`): 240.
+ #[serde(default, deserialize_with = "budget_s")]
+ #[schemars(schema_with = "budget_s_schema")]
+ pub budget_s: Option<f64>,
+}
+
+/// `budget_s`: seconds above 0, at most a day, or `null`, as the handler reads it (with
+/// `params::num`, which takes the number finite and smaller than 1e9 in size), with its message
+/// (the check names the key).
+fn budget_s<'de, D: Deserializer<'de>>(d: D) -> Result<Option<f64>, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Null => Ok(None),
+ v => v
+ .as_f64()
+ .filter(|s| s.is_finite() && *s > 0.0 && *s <= MAX_BUDGET_S)
+ .map(Some)
+ .ok_or_else(|| D::Error::custom(format!("must be a number of seconds above 0, at most {MAX_BUDGET_S}"))),
+ }
+}
+
+fn budget_s_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "The seconds the exact checks may take, above 0, at most 86400 (a day). Pairs not finished by then are listed \
+ in `unchecked`, and the call returns. Default (or `null`): 240.",
+ "type": ["number", "null"],
+ "exclusiveMinimum": 0,
+ "maximum": MAX_BUDGET_S,
+ })
+}
+
+/// The time one pair's exact check took, in ms.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct PairTime {
+ pub a: String,
+ pub b: String,
+ pub ms: f64,
+ /// The kernel's boolean time within it.
+ pub boolean_ms: f64,
+ /// The kernel's tessellation time within it.
+ pub tessellate_ms: f64,
+}
+
+/// What `inspect.interference` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct InterferenceResult {
+ /// The pairs that share volume, with the volume, its surface area, its box and its centre.
+ pub interferences: Vec<Overlap>,
+ /// How many: 0 isn't "no overlap" while `unchecked` lists pairs.
+ pub count: usize,
+ /// How many solid bodies were checked.
+ pub checked: usize,
+ /// The pairs that couldn't be checked, with the reason (a boolean that failed, or the time
+ /// budget ran out), and each mesh body (`b` is then `null`).
+ pub unchecked: Vec<Unchecked>,
+ /// Whether more than 20000 pairs had overlapping boxes, so `skipped_pairs` were left out.
+ pub truncated: bool,
+ pub skipped_pairs: usize,
+ /// The pairs whose boxes overlap.
+ pub pairs_candidate: usize,
+ /// Of those, the pairs cleared by their meshes, without a boolean.
+ pub pairs_cleared: usize,
+ /// The pairs intersected exactly.
+ pub pairs_intersected: usize,
+ /// The pairs not finished within the time budget.
+ pub pairs_not_checked: usize,
+ /// The time budget, in seconds.
+ pub budget_s: f64,
+ /// Whether it ran out.
+ pub budget_exceeded: bool,
+ /// The worker threads the exact checks ran on; 0: on the calling thread.
+ pub threads: usize,
+ /// The kernel's boolean and tessellation time, summed over the pairs, in ms.
+ pub boolean_ms: f64,
+ pub tessellate_ms: f64,
+ /// The slowest pairs, at most 8, slowest first.
+ pub slowest: Vec<PairTime>,
+ /// The time the whole call took, in ms.
+ pub ms: 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>,
+}
+
+#[cfg(test)]
+#[path = "interference_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/interference_tests.rs b/crates/engine/src/schema/interference_tests.rs
new file mode 100644
index 0000000000..7a105b9a95
--- /dev/null
+++ b/crates/engine/src/schema/interference_tests.rs
@@ -0,0 +1,114 @@
+use std::collections::BTreeSet;
+
+use serde_json::{Value, json};
+
+use super::{InterferenceParams, InterferenceResult};
+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::<InterferenceParams>(), &["bodies", "budget_s"]);
+}
+
+/// #12874: calls that fail today get the same message in strict: `string_list`'s for `bodies`
+/// of the wrong shape (`NameList` gives them), the handler's for `budget_s` out of range, and
+/// its own for a body the design lacks.
+#[test]
+fn strict_keeps_todays_errors() {
+ let too_many = vec![json!("A"); 10_001];
+ assert_strict_keeps_todays_errors(&[
+ ("inspect.interference", json!({"bodies": 5})),
+ ("inspect.interference", json!({"bodies": {"name": "A"}})),
+ ("inspect.interference", json!({"bodies": ["A", 1]})),
+ ("inspect.interference", json!({"bodies": too_many})),
+ ("inspect.interference", json!({"bodies": ["Nope"]})),
+ ("inspect.interference", json!({"budget_s": 0})),
+ ("inspect.interference", json!({"budget_s": -1})),
+ ("inspect.interference", json!({"budget_s": 86401})),
+ ("inspect.interference", json!({"budget_s": "60"})),
+ ("inspect.interference", json!({"budget_s": true})),
+ ]);
+}
+
+/// #12874: the contract takes what the input schema allows: each call's check finds no issue
+/// exactly when it matches the schema.
+#[test]
+fn the_check_takes_what_the_schema_allows() {
+ let schema = input_schema_for::<InterferenceParams>();
+ let schema = schema.as_value();
+ for (p, takes) in [
+ (json!({}), true),
+ (json!({"bodies": "C1"}), true),
+ (json!({"bodies": ["C1", "C2"]}), true),
+ (json!({"bodies": []}), true),
+ (json!({"bodies": null, "budget_s": null}), true),
+ (json!({"budget_s": 0.5}), true),
+ (json!({"budget_s": 86400}), true),
+ (json!({"bodies": 5}), false),
+ (json!({"bodies": ["C1", 1]}), false),
+ (json!({"budget_s": 0}), false),
+ (json!({"budget_s": 86401}), false),
+ (json!({"budget_s": "60"}), false),
+ ] {
+ let issues = crate::schema::issues("inspect.interference", &p);
+ assert_eq!(issues.is_empty(), takes, "{p}: {issues:?}");
+ assert_eq!(conforms(schema, schema, &p), takes, "{p}");
+ }
+}
+
+/// The keys of an object.
+fn keys(v: &Value) -> BTreeSet<&str> {
+ v.as_object().into_iter().flatten().map(|(k, _)| k.as_str()).collect()
+}
+
+/// #12874: Interference replies as its output schema says, in Warn without warnings, with the
+/// keys it gave before: on two cylinders that overlap and one apart, checked together and in
+/// pairs, with a time budget given.
+#[test]
+fn interference_replies_with_its_schema() {
+ let mut s = Session::default();
+ for p in [
+ json!({"radius": 5, "height": 10, "base": [0, 0, 0], "body_name": "C1"}),
+ json!({"radius": 5, "height": 10, "base": [7, 0, 0], "operation": "new", "body_name": "C2"}),
+ json!({"radius": 5, "height": 10, "base": [40, 0, 0], "operation": "new", "body_name": "Far"}),
+ ] {
+ s.execute("solid.cylinder", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
+ }
+ s.param_check = ParamCheck::Warn;
+ let schema = output_schema_for::<InterferenceResult>();
+ let schema = schema.as_value();
+ let reply_keys = BTreeSet::from([
+ "interferences",
+ "count",
+ "checked",
+ "unchecked",
+ "truncated",
+ "skipped_pairs",
+ "pairs_candidate",
+ "pairs_cleared",
+ "pairs_intersected",
+ "pairs_not_checked",
+ "budget_s",
+ "budget_exceeded",
+ "threads",
+ "boolean_ms",
+ "tessellate_ms",
+ "slowest",
+ "ms",
+ ]);
+ for p in [json!({}), json!({"bodies": "C1"}), json!({"bodies": ["C1", "C2"], "budget_s": 60}), json!({"bodies": ["C1", "Far"]})] {
+ let r = s.execute("inspect.interference", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
+ assert!(conforms(schema, schema, &r), "{p}: {r} doesn't match {schema}");
+ assert!(r.get("param_warnings").is_none(), "{p}: {r}");
+ assert_eq!(keys(&r), reply_keys, "{p}: {r}");
+ }
+ let r = s.execute("inspect.interference", &json!({"bodies": ["C1", "C2"]})).unwrap_or_default();
+ let hit = &r["interferences"][0];
+ assert_eq!((&r["count"], &hit["a"], &hit["b"]), (&json!(1), &json!("C1"), &json!("C2")), "{r}");
+ assert_eq!(keys(hit), BTreeSet::from(["a", "b", "volume_mm3", "area_mm2", "bbox", "center"]), "{r}");
+ assert!(hit["volume_mm3"].as_f64().is_some_and(|v| v > 0.0) && keys(&hit["bbox"]) == BTreeSet::from(["min", "max"]), "{r}");
+ let slowest = &r["slowest"][0];
+ assert_eq!(keys(slowest), BTreeSet::from(["a", "b", "ms", "boolean_ms", "tessellate_ms"]), "{r}");
+}
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index e7de65f40d..d0ece2c299 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -71,6 +71,7 @@ pub mod features;
pub mod features_more;
pub mod file;
pub mod inspect;
+pub mod interference;
pub mod joints;
pub mod libraries;
pub mod mass_properties;
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index e6b655b324..20d596f341 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -39,7 +39,6 @@ frame.member
frame.profile.insert
frame.profile.list
frame.profile.properties
-inspect.interference
inspect.measure
joint.as_built
joint.cam