Body names: inspect.interference refuses an unknown body; appearance.chain and appearance.list take a placed copy's name (#9740) (#9856)

* claim: #9740

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FAWPuFoh9qxn2uS2j53QZ

* Body names: inspect.interference refuses an unknown body; appearance reads take a placed copy's name (#9740)

inspect.interference dropped a name that is no body, so a misspelled or
wrongly cased name left that body unchecked and two overlapping cubes
answered count 0. It now refuses the name, as inspect.clearance does,
naming the closest body when one is near enough to be a typo or another
case (cmd::no_body, on the existing edit_distance).

appearance.chain, appearance.list and appearance.replace's scope take a
placed copy's name (KB (K:2)) and a placement's (K:2) for the body and
component they show, as appearance.assign already does, through two
Session helpers: own_body_name (on body_frames) and component_or_placement,
which appearance.assign now uses too. A name that is neither is still
refused. select.set already refuses an unknown body on main (#9737).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FAWPuFoh9qxn2uS2j53QZ

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
austin62jakeandClaude Opus 5.5 authored and GitHub committed 2026-10-31 05:07:04 +00:00
1 parent 9d8ab72da7
commit affe37bcc3
8 files changed
+122 -21

No files matched your search

+21 -9
View File
@@ -21,16 +21,20 @@ fn component(s: &Session, cmd: &str, value: &Value) -> Result<u64> {
Value::Number(_) => value.as_u64().ok_or_else(|| bad(cmd, "component must be a name or unsigned id"))?.to_string(),
_ => return Err(bad(cmd, "component must be a name or unsigned id")),
};
s.doc.find_component(&key).filter(|id| *id != 0).ok_or_else(|| bad(cmd, "unknown or root component"))
// A placement's name (`K:2`) means its component, as appearance.assign takes it (#9740).
s.component_or_placement(&key).ok_or_else(|| bad(cmd, "unknown or root component"))
}
pub(super) fn chain(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "appearance.chain";
let target = p.get("target").and_then(Value::as_object).ok_or_else(|| bad(cmd, "give one target object"))?;
let target = match (target.get("body"), target.get("face"), target.get("component")) {
(Some(body), None, None) if target.len() == 1 => AppearanceTarget::Body(name(cmd, body)?),
// A placed copy's name (`KB (K:2)`) means the body it shows, as appearance.assign takes it
// (#9740); a name that is neither is left for the chain to refuse.
let body = target.get("body").map(|b| name(cmd, b).map(|n| s.own_body_name(n).unwrap_or_else(|| n.to_string()))).transpose()?;
let target = match (body.as_deref(), target.get("face"), target.get("component")) {
(Some(body), None, None) if target.len() == 1 => AppearanceTarget::Body(body),
(Some(body), Some(face), None) if target.len() == 2 => AppearanceTarget::Face {
body: name(cmd, body)?,
body,
face: face.as_u64().and_then(|f| usize::try_from(f).ok()).ok_or_else(|| bad(cmd, "face must be a zero-based unsigned index"))?,
},
(None, None, Some(id)) if target.len() == 1 => AppearanceTarget::Component(component(s, cmd, id)?),
@@ -80,12 +84,18 @@ fn scope(s: &Session, cmd: &str, value: &Value) -> Result<AppearanceScope> {
if object.contains_key("bodies") {
let state = s.model.state();
let bodies: BTreeSet<_> = state.bodies.iter().map(|b| b.name.as_str()).collect();
// A placed copy's name means the body it shows (#9740). Built once, and only when a
// name is not the model's own.
let mut placed: Option<BTreeMap<String, String>> = None;
for body in list("bodies")? {
let body = name(cmd, body)?;
if !bodies.contains(body) {
return Err(bad(cmd, "unknown body in scope"));
}
scope.bodies.insert(body.into());
let own = if bodies.contains(body) {
body.to_string()
} else {
let placed = placed.get_or_insert_with(|| s.body_frames().iter().map(|(world, own, _)| (world.clone(), own.clone())).collect());
placed.get(body).cloned().ok_or_else(|| bad(cmd, "unknown body in scope"))?
};
scope.bodies.insert(own);
}
}
if object.contains_key("components") {
@@ -93,11 +103,13 @@ fn scope(s: &Session, cmd: &str, value: &Value) -> Result<AppearanceScope> {
// 10000-component design once per target.
let ids: BTreeSet<_> = s.doc.components.iter().map(|c| c.id).collect();
let names: BTreeMap<_, _> = s.doc.components.iter().rev().map(|c| (c.name.as_str(), c.id)).collect();
// A placement's name (`K:2`) means its component (#9740).
let placements: BTreeMap<_, _> = s.doc.occurrences.iter().rev().map(|o| (o.name.as_str(), o.component)).collect();
for target in list("components")? {
let id = match target {
Value::String(_) => {
let key = name(cmd, target)?;
key.parse::<u64>().ok().filter(|id| ids.contains(id)).or_else(|| names.get(key).copied())
key.parse::<u64>().ok().filter(|id| ids.contains(id)).or_else(|| names.get(key).copied()).or_else(|| placements.get(key).copied())
}
Value::Number(_) => target.as_u64().filter(|id| ids.contains(id)),
_ => None,
+9 -11
View File
@@ -59,17 +59,17 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("appearance.favorite", "Favorite Look", appearance_gestures::favorite).icon("star").noundo().doc_only()
.params("look: appearance.assign look; favorite: bool → validated look and preference request; UI library preference only, no document change or dialogs."),
CommandSpec::new("appearance.chain", "Appearance Chain", appearance_chain::chain).icon("inspect").noundo().params(
"target: {body: name} | {body: name, face: zero-based model.faces index} | {component: name or id}. Returns steps [{step: face|body|component|material, look: {name,color,opacity,pbr?} or null}] in precedence order and active (step or null). Component material is the common default look of its directly owned bodies, null if mixed/empty. Imported paint is a display fallback outside the four steps. Read-only; no dialogs",
"target: {body: name} | {body: name, face: zero-based model.faces index} | {component: name or id}; a placed copy's name (`KB (K:2)`, `K:2`) means the body or component it shows. Returns steps [{step: face|body|component|material, look: {name,color,opacity,pbr?} or null}] in precedence order and active (step or null). Component material is the common default look of its directly owned bodies, null if mixed/empty. Imported paint is a display fallback outside the four steps. Read-only; no dialogs",
),
CommandSpec::new("appearance.replace", "Replace Appearance", appearance_chain::replace).icon("appearance").params(
"from: library name | saved look {name,color,opacity,pbr?} (copy appearance.list in_design); to: library name | assignment look {appearance? | color, name?, opacity?, pbr?} (appearance.assign rules; no clear). Matches the full look including name and PBR. scope?: {bodies?: [names], components?: [names or ids]}, at most 10000 targets; body scope includes face overrides, component scope selects only the component override. Omitted scope means all overrides, including hidden/suppressed ones; physical defaults are unchanged. Duplicate targets count once. Returns count of rewritten overrides; zero adds no history. One undo step, atomic; no dialogs. Designs above 100000 overrides refuse",
"from: library name | saved look {name,color,opacity,pbr?} (copy appearance.list in_design); to: library name | assignment look {appearance? | color, name?, opacity?, pbr?} (appearance.assign rules; no clear). Matches the full look including name and PBR. scope?: {bodies?: [names], components?: [names or ids]} (a placed copy's name means the body or component it shows), at most 10000 targets; body scope includes face overrides, component scope selects only the component override. Omitted scope means all overrides, including hidden/suppressed ones; physical defaults are unchanged. Duplicate targets count once. Returns count of rewritten overrides; zero adds no history. One undo step, atomic; no dialogs. Designs above 100000 overrides refuse",
),
CommandSpec::new("appearance.library", "Appearance Library", appearance_library).icon("library")
.noundo()
.params("→ 20 legacy scalar appearances, six opaque PBR finishes and 40 starter recipes with IDs, categories, provenance, requirements and availability; six starter glass recipes are unavailable"),
CommandSpec::new("appearance.list", "List Appearances", appearance_list).icon("list")
.noundo()
.params("body?: name → assigned appearances; with body, its resolved look and its faces' (face index, look)"),
.params("body?: name (or a placed copy's, `KB (K:2)`: the body it shows) → assigned appearances; with body, its resolved look and its faces' (face index, look)"),
CommandSpec::new("material.list", "List Materials", material_list).icon("list")
.noundo()
.doc_only()
@@ -519,12 +519,7 @@ pub(super) fn appearance(s: &mut Session, p: &Value) -> Result<Value> {
}
let mut comps: Vec<u64> = Vec::new();
for c in string_list(cmd, p, "components")? {
let id = s
.doc
.find_component(&c)
.or_else(|| s.doc.occurrences.iter().find(|o| o.name == c).map(|o| o.component))
.filter(|id| *id != 0)
.ok_or_else(|| bad(cmd, format!("no component `{c}`")))?;
let id = s.component_or_placement(&c).ok_or_else(|| bad(cmd, format!("no component `{c}`")))?;
comps.push(id);
}
if bodies.is_empty() && faces.is_empty() && comps.is_empty() {
@@ -791,9 +786,12 @@ fn appearance_list(s: &mut Session, p: &Value) -> Result<Value> {
});
if let Some(name) = str_(p, "body") {
let st = s.model.state();
let b = st.body(name).ok_or_else(|| bad("appearance.list", format!("no body `{name}`")))?;
// A placed copy's name (`KB (K:2)`) means the body it shows, as appearance.assign takes
// it (#9740): the reply names that body.
let own = s.own_body_name(name);
let b = own.as_deref().and_then(|n| st.body(n)).ok_or_else(|| bad("appearance.list", format!("no body `{name}`")))?;
out["body"] = json!({
"name": name,
"name": b.name,
"appearance": s.doc.model_body_look(b).map(|l| look_json(&l)),
"color": s.doc.body_color(b),
"faces": s.doc.face_colors(b).iter().map(|(i, l)| json!({"face": i, "appearance": look_json(l)})).collect::<Vec<_>>(),
+5
View File
@@ -75,6 +75,11 @@ pub(super) fn interference(s: &mut Session, p: &Value) -> Result<Value> {
let budget = std::time::Duration::from_secs_f64(budget_s);
let want = string_list(cmd, p, "bodies")?;
let st = s.world_state();
// A name that is no body is refused, as inspect.clearance refuses it. Dropped, a misspelled
// body was never checked and the answer read as no interference (#9740).
if let Some(n) = want.iter().find(|n| st.body(n).is_none()) {
return Err(bad(cmd, super::no_body(n, st.bodies.iter().map(|b| b.name.as_str()))));
}
let (meshes_left, bodies): (Vec<&solidcraft_doc::ModelBody>, Vec<&solidcraft_doc::ModelBody>) =
st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).partition(|b| b.body.is_mesh());
@@ -156,3 +156,24 @@ fn mesh_bodies_are_listed_as_unchecked_not_dropped() {
assert_eq!(i["checked"], 1, "{i}");
assert_eq!(i["unchecked"][0]["a"].as_str(), Some(meshes[0].as_str()), "{i}");
}
/// A name that is no body is refused, as inspect.clearance refuses it. Dropped, a misspelled or
/// wrongly cased body was never checked and two overlapping cubes read as no interference (#9740).
#[test]
fn a_body_name_that_is_no_body_is_refused() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "A"}));
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [9, 0, 0], "operation": "new_body", "body_name": "B"}));
let i = run(&mut s, "inspect.interference", json!({"bodies": ["A", "B"]}));
assert_eq!((&i["count"], &i["checked"]), (&json!(1), &json!(2)), "{i}");
for (names, says) in
[(json!(["A", "Typo"]), "no body `Typo`"), (json!(["A", "b"]), "no body `b`; did you mean `B`?"), (json!(["Typo"]), "no body `Typo`")]
{
let e = s.execute("inspect.interference", &json!({"bodies": names})).map(|r| r.to_string()).unwrap_or_else(|e| e.to_string());
assert!(e.contains(says), "{names}: {e}");
}
assert!(
!s.execute("inspect.interference", &json!({"bodies": ["Typo"]})).unwrap_err().to_string().contains("did you mean"),
"nothing is near `Typo`"
);
}
+1 -1
View File
@@ -105,7 +105,7 @@ pub static COMMANDS: &[CommandSpec] = &[
),
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(
"bodies?: [names] (default: all, in world placement); 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 (a pin a hair off the axis of a hole of its size also has near_coaxial: {offset_mm, length_mm}, its volume the crescent the walls share); 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",
"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 (a pin a hair off the axis of a hole of its size also has near_coaxial: {offset_mm, length_mm}, its volume the crescent the walls share); 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",
),
];
+14
View File
@@ -386,6 +386,20 @@ pub(crate) fn did_you_mean(id: &str) -> String {
}
}
/// "no body `name`", and the closest of `bodies` when it is near enough to be a typo or another
/// case of the same name (`b` for `B`): `no body `Bdy`; did you mean `Body`?` (#9740).
pub(crate) fn no_body<'a>(name: &str, bodies: impl IntoIterator<Item = &'a str>) -> String {
let want = name.to_lowercase();
let near = (want.chars().count() / 3).max(1);
let closest = (want.len() <= 256)
.then(|| bodies.into_iter().map(|b| (edit_distance(&want, &b.to_lowercase()), b)).filter(|(d, _)| *d <= near).min_by_key(|(d, _)| *d))
.flatten();
match closest {
Some((_, b)) => format!("no body `{name}`; did you mean `{b}`?"),
None => format!("no body `{name}`"),
}
}
/// Levenshtein distance: the single-character edits that turn `a` into `b`.
pub(crate) fn edit_distance(a: &str, b: &str) -> usize {
let b: Vec<char> = b.chars().collect();
@@ -945,3 +945,38 @@ fn appearance_gestures_favorite_is_a_validated_transient_request() {
assert!(Arc::ptr_eq(&before, &s.doc));
assert_eq!((s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty()), state);
}
/// A placed copy's name (`KB (K:2)`, the name inspect.measure lists) and a placement's (`K:2`)
/// mean the body and component they show in appearance.chain, appearance.list and
/// appearance.replace's scope, as appearance.assign already takes them (#9740).
#[test]
fn appearance_reads_and_scopes_take_a_placed_copys_name() {
let mut s = Session::default();
s.execute("component.create", &json!({"name":"K"})).unwrap();
s.execute("solid.box", &json!({"body_name":"KB","length":10,"width":10,"height":10})).unwrap();
s.execute("occurrence.copy", &json!({"component":"K","translate":[30,0,0]})).unwrap();
let world: Vec<String> = s.world_state().bodies.iter().map(|b| b.name.clone()).collect();
assert!(world.iter().any(|n| n == "KB (K:2)"), "{world:?}");
s.execute("appearance.assign", &json!({"bodies":["KB"],"appearance":"ABS - Red"})).unwrap();
s.execute("appearance.assign", &json!({"components":["K"],"appearance":"ABS - Blue"})).unwrap();
assert_eq!(chain_read(&mut s, json!({"body":"KB (K:2)"})), chain_read(&mut s, json!({"body":"KB"})));
assert_eq!(chain_read(&mut s, json!({"body":"KB (K:2)","face":0})), chain_read(&mut s, json!({"body":"KB","face":0})));
assert_eq!(chain_read(&mut s, json!({"component":"K:2"})), chain_read(&mut s, json!({"component":"K"})));
let listed = |s: &mut Session, body: &str| s.execute("appearance.list", &json!({"body":body})).unwrap()["body"].clone();
let placed = listed(&mut s, "KB (K:2)");
assert_eq!(placed["name"], "KB", "the reply names the body the copy shows: {placed}");
assert_eq!(placed, listed(&mut s, "KB"));
let scope = json!({"bodies":["KB (K:2)"],"components":["K:2"]});
let r = s.execute("appearance.replace", &json!({"from":"ABS - Red","to":"ABS - Blue","scope":scope})).unwrap();
assert_eq!(r["count"], 1, "{r}");
assert_eq!(s.doc.appearances.bodies["KB"], s.doc.appearances.components[&s.doc.find_component("K").unwrap()]);
// A name that is neither the model's nor a placed copy's is still refused.
assert!(s.execute("appearance.chain", &json!({"target":{"body":"KB (K:9)"}})).is_err());
assert!(s.execute("appearance.chain", &json!({"target":{"component":"K:9"}})).is_err());
assert!(s.execute("appearance.list", &json!({"body":"KB (K:9)"})).is_err());
assert!(s.execute("appearance.replace", &json!({"from":"ABS - Blue","to":"ABS - Red","scope":{"bodies":["KB (K:9)"]}})).is_err());
assert!(s.execute("appearance.replace", &json!({"from":"ABS - Blue","to":"ABS - Red","scope":{"components":["K:9"]}})).is_err());
}
+16
View File
@@ -960,6 +960,22 @@ impl Session {
}
}
/// The model body a name means: one of the model's own bodies as it is named, else the body
/// a placed copy shows (`KB (K:2)`, the name `inspect.measure` lists), as `appearance.assign`
/// takes it (#9740). `None` when neither names it.
pub(crate) fn own_body_name(&self, name: &str) -> Option<String> {
if self.model.state().body(name).is_some() {
return Some(name.to_string());
}
self.body_frames().iter().find(|(world, ..)| world == name).map(|(_, own, _)| own.clone())
}
/// A component by its id or name, or by the name of one of its placements (`K:2`); never the
/// root.
pub(crate) fn component_or_placement(&self, key: &str) -> Option<u64> {
self.doc.find_component(key).or_else(|| self.doc.occurrences.iter().find(|o| o.name == key).map(|o| o.component)).filter(|id| *id != 0)
}
pub fn refresh(&mut self) {
if self.model.evaluate_shared(&self.doc) {
#[cfg(test)]