Files
makeCAD/crates/engine/src/cmd/joints_inspect.rs
T
JIJINBEI cdde7d62b2 Persistent names read by one parser; four misreadings fixed (#5814) (#5966)
* doc: persistent names read as their structure; joint.inspect splits an edge with a blend face first

`persistent_name::{FaceName, EdgeName}` parse a face or edge name once (blends, inner walls,
copies, pieces, numbered pieces, `~k`) and write it back as the same text, bounded against
hostile input. A suffix after a blend's edge naming a later feature belongs to the blend face.

joint.inspect split an edge at its first `|`, so an edge whose first face is a blend
(`F4:blend:F3:+x|F3:+z#[…]|F5:-y`) came back as a cut-off blend name and a string that is no
face. It now uses `EdgeName::parse`.

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

* doc: persistent names as typed values: features, roles, suffixes, a lexer and errors that say where

`FaceName` is a base (made by a feature in a role, a blend and the edge it rounds, an inner
wall, a body's face by index, other text) and its suffixes (copy, piece, numbered piece).
Roles are typed where the vocabulary is known (top, side:<curve>, +x, face:<k>, …) and kept as
written otherwise. The text form is lexed into tokens and read by the grammar in the module's
doc; a name that doesn't read says where and what was expected.

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

* names: read what made a face, its kind and its feature ids through persistent_name

The places that took a name apart by hand to find the feature that made a face, whether it is
a blend, a copy, a numbered piece or a wall, or to remap feature ids on copy, now ask the typed
name (`made_by`, `split_feature`, `is_blend`, `is_copy`, `is_numbered_piece`, `is_wall`,
`features`, `map`). A name that doesn't read falls back to the old text check.

- An offset of a face that only names a blend inside it (`F2:top#[F5:blend:…]`) is no longer
  taken for a fillet's.
- Copying a component remaps feature ids inside a piece's `#[…]` too.
- A shell's inner wall split by a later cut keeps the qualifier on the wall.
- joint.inspect finds the sketch curve of a copied side (`side:l1@F7.2`).

Finding a face by name (strip_piece, parent_piece) is unchanged: it reads a trailing
qualifier as the whole name's and moves once the text form says where it belongs.

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

* engine: regression tests for press-pull on a wall that only names a fillet and joint.inspect on a copied side

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

* names: an edge holds one face or more; made_by reads only the leading token

An open boundary's edge has one face and an edge several faces meet at has more, so an edge name
is a list of faces (a blend's own edge still takes two at most, as before). `made_by` reads just
the leading `F<n>:`, which every name a feature made starts with, so asking it of every face
each frame stays cheap. Names are read up to 1 MiB: a face engraved with text has piece names
past 4 KiB.

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

* persistent_name: split into lexer, parser, write, text and tests

No code changed; callers' paths stay the same (`pub use text::*`).

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 01:48:26 +00:00

212 lines
8.1 KiB
Rust

//! Inspect Joint (`joint.inspect`): what each joint is defined by and attached to — its two
//! origins (the occurrence, the snap as saved, and the feature, face, edge or sketch curve each
//! persistent name refers to), whether each origin is found today and why not, its kind, offset,
//! angle, flip, limits, values, expressions and the motion links it takes part in. Reads only.
use serde_json::{Value, json};
use solidcraft_doc::joints::{self, Joint, JointOrigin, Snap, XRef};
use solidcraft_doc::naming::legacy_name;
use solidcraft_doc::persistent_name::{Base, EdgeName, FaceName, Role};
use solidcraft_doc::{Document, MAX_PLACEMENT_DEPTH, ModelState};
use super::{component_of, joint_id, link_json, named_values, occurrence_name};
use crate::{Result, Session};
pub(super) fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "joint.inspect";
let ids: Vec<u64> = match p.get("joint") {
None | Some(Value::Null) => s.doc.assembly.joints.iter().map(|j| j.id).collect(),
v => vec![joint_id(s, v, cmd)?],
};
let st = s.model.state();
let sol = joints::solve(&s.doc, &st);
let vals = joints::joint_values(&s.doc.assembly);
let out: Vec<Value> = ids
.iter()
.filter_map(|id| s.doc.assembly.joints.iter().find(|j| j.id == *id))
.map(|j| {
let q = vals.get(&j.id).map(Vec::as_slice).unwrap_or(&j.values);
joint_json(s, &st, &sol, j, q)
})
.collect();
Ok(json!({ "joints": out }))
}
fn joint_json(s: &Session, st: &ModelState, sol: &joints::Solution, j: &Joint, q: &[f64]) -> Value {
let links: Vec<Value> = s
.doc
.assembly
.links
.iter()
.enumerate()
.filter(|(_, l)| l.a == j.id || l.b == j.id)
.map(|(i, l)| {
let mut v = link_json(s, st, l);
v["index"] = json!(i);
v["role"] = json!(if l.b == j.id { "driven" } else { "driver" });
v
})
.collect();
let why = |list: &[(u64, String, String)]| list.iter().filter(|(id, ..)| *id == j.id).map(|(.., why)| why.clone()).collect::<Vec<_>>();
let mut v = json!({
"id": j.id,
"name": j.name,
"type": j.kind,
"suppressed": j.suppressed,
"visible": s.joint_visible(j.id),
"flip": j.flip,
"offset": j.offset,
"angle": j.angle.to_degrees(),
"values": named_values(j, q),
"dofs": j.kind.dofs(),
"a": side_json(s, st, &j.a),
"b": side_json(s, st, &j.b),
"links": links,
"errors": why(&sol.errors),
"conflicts": why(&sol.conflicts),
});
if !j.exprs.is_empty() {
v["expressions"] = json!(j.exprs);
}
v
}
/// One of a joint's origins: what it sits on, what it refers to, and where it is now.
fn side_json(s: &Session, st: &ModelState, o: &JointOrigin) -> Value {
let component = component_of(s, o.occurrence);
let component_name = if component == 0 {
"root".to_string()
} else {
s.doc.components.iter().find(|c| c.id == component).map(|c| c.name.clone()).unwrap_or_default()
};
let occurrence_name = if o.occurrence == 0 { "root".to_string() } else { occurrence_name(s, o.occurrence) };
let mut v = json!({
"occurrence": o.occurrence,
"occurrence_name": occurrence_name,
"component": component,
"component_name": component_name,
"path": occurrence_path(&s.doc, o.occurrence),
"snap": o.snap,
"references": references(&s.doc, &o.snap),
});
match s.doc.origin_world(st, o) {
Ok(m) => {
v["resolves"] = json!(true);
v["frame"] = json!({"origin": [m[3][0], m[3][1], m[3][2]], "z": [m[2][0], m[2][1], m[2][2]], "x": [m[0][0], m[0][1], m[0][2]]});
}
Err(e) => {
v["resolves"] = json!(false);
v["error"] = json!(e.to_string());
}
}
v
}
/// The occurrence names from the top of the assembly down to `occurrence` (`/` between); a
/// nested component's parent is taken at its first placement. Empty for the root.
fn occurrence_path(doc: &Document, occurrence: u64) -> String {
let mut names = Vec::new();
let mut id = occurrence;
for _ in 0..=MAX_PLACEMENT_DEPTH {
let Some(o) = doc.occurrences.iter().find(|o| o.id == id) else { break };
names.push(o.name.as_str());
let Some(parent) = (o.parent != 0).then(|| doc.occurrence_of(o.parent)).flatten() else { break };
id = parent.id;
}
names.reverse();
names.join("/")
}
/// Every persistent name the snap holds, with what it refers to.
fn references(doc: &Document, snap: &Snap) -> Vec<Value> {
let mut out = Vec::new();
let mut face = |role: &str, name: &Option<String>| {
if let Some(n) = name {
out.push(with_role(role, face_ref(doc, n)));
}
};
match snap {
Snap::FaceCenter { face: f, x, .. } => {
face("face", f);
if let Some(XRef::Face { face: n, .. }) = x {
face("x", &Some(n.clone()));
}
}
Snap::CircleCenter { face: f, end, x, .. } => {
face("face", f);
face("end", end);
if let Some(XRef::Face { face: n, .. }) = x {
face("x", &Some(n.clone()));
}
}
Snap::Edge { edge, face: f, corner, .. } => {
if let Some(e) = edge {
out.push(with_role("edge", edge_ref(doc, e)));
}
if let Some(n) = f {
out.push(with_role("face", face_ref(doc, n)));
}
if let Some(e) = corner {
out.push(with_role("corner", edge_ref(doc, e)));
}
}
Snap::Frame { .. } | Snap::Point { .. } => {}
}
out
}
fn with_role(role: &str, mut v: Value) -> Value {
v["role"] = json!(role);
v
}
/// What a face's persistent name refers to: `F<feature>:<role>` names the feature that made the
/// face, and a side `side:<curve>` (or a later profile's `side:s<k>.<curve>`) the sketch curve
/// it was swept from. Names of another form are given as they are.
fn face_ref(doc: &Document, name: &str) -> Value {
let mut v = json!({ "name": name });
let bare = match legacy_name(name) {
Some(n) => {
v["unverified"] = json!(true);
n
}
None => name,
};
let Ok(face) = FaceName::parse(bare) else { return v };
let Some(fid) = face.made_by().map(|id| id.0) else { return v };
let stem = face.stem().to_string();
v["role_in_feature"] = json!(stem.strip_prefix(&format!("F{fid}:")).unwrap_or(&stem));
let Some(f) = doc.feature(fid) else {
v["feature"] = json!({"id": fid, "error": format!("feature {fid} is gone")});
return v;
};
v["feature"] = json!({"id": f.id, "name": f.name, "type": f.kind.type_name()});
// A side swept from a sketch curve (a later profile's too, `side:s<k>.<curve>`).
if let Base::Made { role: Role::Side { curve, .. }, .. } = &face.base {
let found = f.kind.input_sketches().into_iter().find_map(|id| {
let sk = doc.sketch(id).ok()?;
let c = sk.curves.iter().find(|c| c.id == *curve)?;
let curve_type = serde_json::to_value(&c.kind).ok().and_then(|k| k.get("type").cloned()).unwrap_or(Value::Null);
let name = doc.feature(id).map(|f| f.name.clone()).unwrap_or_default();
Some(json!({"id": id, "name": name, "curve": curve, "curve_type": curve_type}))
});
v["sketch"] = found.unwrap_or_else(|| json!({"curve": curve, "error": format!("no sketch of {} has a curve `{curve}`", f.name)}));
}
v
}
/// An edge's persistent name (`<face A>|<face B>`, `~k` for one of several between them) with
/// what each of its faces refers to.
fn edge_ref(doc: &Document, name: &str) -> Value {
let bare = legacy_name(name).unwrap_or(name);
let faces: Vec<Value> = match EdgeName::parse(bare) {
Ok(e) => e.faces.iter().map(|f| face_ref(doc, &f.to_string())).collect(),
Err(_) => Vec::new(),
};
let mut v = json!({"name": name, "faces": faces});
if legacy_name(name).is_some() {
v["unverified"] = json!(true);
}
v
}