Linked components: joints keep their face after Update Links (#3330) (#4874)

* claim: #3330

* Linked components: joints keep their face after Update Links (#3330)

A linked design comes in as STEP text, which keeps no face names, so the
faces of its bodies were named by their place in the file (`face:<k>`).
An edit of the part that adds a face earlier in the file (a second hole
of the same size) gave that place to another face, and a joint on the
linked part moved there silently.

When a link is made or updated, each imported face is matched to the
part face it was written from (the same geometry), and the Import
feature keeps that face's name in the part (`Feature::link_faces`, a new
pending format change). The linked face is named
`F<import>🔗<digest of that name>`, pieces keeping their qualifiers,
so references follow the part's own history through Update Links as they
do inside the part, and a face the part no longer has is reported.
Linked faces still answer to `face:<k>`, so older references keep
resolving; Update Links warns about joints that use them and reports
joints that no longer solve.

* Linked faces: a solid's twin keeps its own names; renamed faces count as an update

Two solids of a part alike in one place each take the names of the solid
the file names them after. Update Links reports a link whose part named
its faces differently since as updated (a joint may follow that name to
another face), not as unchanged; only a link getting its first names
stays unchanged.

* Linked faces: Extract to File carries the design's face names too

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

---------

Co-authored-by: MateuszSychXpl <151755914+MateuszSychXpl@users.noreply.github.com>
Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Mateusz Sych
2026-10-24 08:33:36 +00:00
committed by GitHub
parent 8b65d41b31
commit 9a737bd63c
10 changed files with 338 additions and 21 deletions
+2 -1
View File
@@ -566,7 +566,7 @@ pub(super) fn extract(s: &mut Session, p: &Value) -> Result<Value> {
// This design: the component's history becomes an Import feature of the new design's bodies
let shown = file.display().to_string();
let (_, sf) = session_bodies(&part, &shown)?;
let (_, sf, faces) = session_bodies(&part, &shown)?;
// The link has a body per piece: a body in pieces keeps its name on the first
let mut solids: Vec<String> = Vec::new();
for b in part.world_state().bodies.iter().filter(|b| !b.body.is_mesh()) {
@@ -589,6 +589,7 @@ pub(super) fn extract(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(f) = d.feature_mut(id) {
f.component = comp;
f.body_names = if solids.len() == sf.body_names.len() { solids } else { sf.body_names };
f.link_faces = faces;
}
let path = stored(s.path.as_deref(), &file);
s.doc_mut().links.insert(comp, DesignLink { path: path.clone(), feature: id });
+194 -15
View File
@@ -4,7 +4,9 @@
//! join a new component through an Import feature (exact B-rep, kept in this design so it opens
//! without the part file). The link remembers the file, relative to this design's folder once it
//! is saved; Update Links reads the file again and replaces the Import feature's bodies, and
//! Break Link keeps the bodies and forgets the file.
//! Break Link keeps the bodies and forgets the file. The bodies' faces are named after the names
//! the design gives them (`Feature::link_faces`), so a joint on a linked face stays on that face
//! when the design changes, as it would inside the design, and reports it when the face is gone.
use std::path::{Component as PathPart, Path, PathBuf};
@@ -30,7 +32,8 @@ pub static COMMANDS: &[CommandSpec] = &[
reuse?: bool (default false): insert a free occurrence, reusing an existing link to the same file when available",
),
CommandSpec::new("component.update_links", "Update Links", update_links).icon("update").params(
"component?: id or name (default: every linked component) — reads the linked designs again and replaces their bodies where they changed",
"component?: id or name (default: every linked component) — reads the linked designs again and replaces their bodies where they changed; \
→ updated, unchanged, warnings (also joints whose faces are gone or that no longer solve)",
),
CommandSpec::new("component.relink", "Relink Source", relink).icon("update").params(
"component: id or name of a linked component; path: a saved .solidcraft design — replaces the source and linked bodies for all its occurrences, preserving identities and placements; returns path, previous_path, warnings, joint_errors and joint_conflicts",
@@ -120,8 +123,12 @@ pub(super) fn rebased(doc: &Document, from: Option<&str>, to: &str) -> std::coll
doc.links.iter().map(|(c, l)| (*c, DesignLink { path: stored(Some(to), &resolve(from, &l.path)), feature: l.feature })).collect()
}
/// The bodies of a linked design: its name, the Import feature that holds them and the names
/// the design gives their faces (`Feature::link_faces`).
type Linked = (String, solidcraft_io::StepFeature, Vec<Vec<String>>);
/// The solid bodies of the design at `file`, evaluated, as an Import feature.
fn linked_bodies(file: &Path, own: Option<&str>) -> Result<(String, solidcraft_io::StepFeature)> {
fn linked_bodies(file: &Path, own: Option<&str>) -> Result<Linked> {
let shown = file.display().to_string();
if own.is_some_and(|o| absolute(Path::new(o)) == absolute(file)) {
return Err(EngineError::Other(format!("{shown}: a design can't be linked into itself")));
@@ -132,7 +139,7 @@ fn linked_bodies(file: &Path, own: Option<&str>) -> Result<(String, solidcraft_i
}
/// The solid bodies of `part`, the design saved as `shown`, as an Import feature.
fn session_bodies(part: &Session, shown: &str) -> Result<(String, solidcraft_io::StepFeature)> {
fn session_bodies(part: &Session, shown: &str) -> Result<Linked> {
let name = part.doc.name.clone();
if let Some(e) = part.model.results.iter().find_map(|r| r.error.clone()) {
return Err(EngineError::Other(format!("{shown}: the design has a feature that fails ({e}); fix it before linking it")));
@@ -148,7 +155,10 @@ fn session_bodies(part: &Session, shown: &str) -> Result<(String, solidcraft_io:
if world.bodies.len() > solids.len() {
feature.warnings.push(format!("{} mesh bodies of {shown} are not linked", world.bodies.len() - solids.len()));
}
Ok((name, feature))
// The STEP text keeps no face names: carry the design's own, so references into the linked
// bodies follow them as they do inside the design (#3330).
let faces = solidcraft_doc::naming::carried_face_names(&world, &feature.import.bodies);
Ok((name, feature, faces))
}
fn component_key(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<u64> {
@@ -178,7 +188,7 @@ fn insert_design(s: &mut Session, p: &Value) -> Result<Value> {
return super::component::copy_occurrence(s, &json!({"component": component, "parent": parent, "translate": translate}));
}
}
let (design_name, sf) = linked_bodies(&file, s.path.as_deref())?;
let (design_name, sf, faces) = linked_bodies(&file, s.path.as_deref())?;
let name = str_(p, "name").filter(|n| !n.trim().is_empty()).map(str::to_string).unwrap_or(design_name);
let mut create = json!({"name": name, "activate": false});
// Clipboard insertion uses reuse even for the first paste, which must stay movable.
@@ -195,6 +205,7 @@ fn insert_design(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(f) = s.doc_mut().feature_mut(id) {
f.component = comp;
f.body_names = sf.body_names;
f.link_faces = faces;
}
if let Some(o) = s.doc_mut().occurrences.iter_mut().find(|o| Some(o.id) == occ) {
o.transform[3] = [translate.x, translate.y, translate.z, 1.0];
@@ -237,28 +248,63 @@ fn update_links(s: &mut Session, p: &Value) -> Result<Value> {
};
let old = old.clone();
let file = resolve(s.path.as_deref(), &link.path);
let (_, sf) = linked_bodies(&file, s.path.as_deref()).map_err(|e| bad(cmd, format!("{cname}: {e}")))?;
let (_, sf, faces) = linked_bodies(&file, s.path.as_deref()).map_err(|e| bad(cmd, format!("{cname}: {e}")))?;
warnings.extend(sf.warnings.iter().cloned());
if matches!(&sf.kind, FeatureKind::Import { step, .. } if *step == old) {
let same = matches!(&sf.kind, FeatureKind::Import { step, .. } if *step == old);
let kept = s.doc.feature(link.feature).map(|f| &f.link_faces);
if same && kept == Some(&faces) {
unchanged.push(cname);
continue;
}
if let Some(f) = s.doc_mut().feature_mut(link.feature) {
// Bodies keep their names where the design still has as many.
if f.body_names.len() != sf.body_names.len() {
f.body_names = sf.body_names;
// The same bodies, their faces named for the first time (a link made before names were
// kept): nothing a reference finds changes. Names the design gave other faces since do.
let changed = !same || kept.is_some_and(|k| !k.is_empty());
if !same {
for name in numbered_references(s, comp, link.feature) {
warnings.push(format!(
"{name} refers to faces of {cname} by their place in the linked file, which this update can change: check it, and pick its faces again so it follows them by name"
));
}
f.kind = sf.kind;
}
updated.push(cname);
if let Some(f) = s.doc_mut().feature_mut(link.feature) {
if !same {
// Bodies keep their names where the design still has as many.
if f.body_names.len() != sf.body_names.len() {
f.body_names = sf.body_names;
}
f.kind = sf.kind;
}
// A link made before the design's face names were kept gets them here.
f.link_faces = faces;
}
if changed { updated.push(cname) } else { unchanged.push(cname) }
}
s.refresh();
if let Some(e) = s.doc.links.values().find_map(|l| s.model.result(l.feature).and_then(|r| r.error.clone())) {
return Err(EngineError::Other(e));
}
// A reference whose face the design no longer has says so here, not only in the joint list.
if !updated.is_empty() {
let sol = solidcraft_doc::joints::solve(&s.doc, &s.model.state());
warnings.extend(sol.errors.iter().chain(&sol.conflicts).map(|(_, name, why)| format!("joint {name}: {why}")));
}
Ok(json!({"updated": updated, "unchanged": unchanged, "warnings": warnings}))
}
/// The joints and joint origins on occurrences of `comp` that name its linked faces by their
/// place in the file (`F<feature>:face:<k>`, made before the design's own names were kept), which
/// an update can give to another face.
fn numbered_references(s: &Session, comp: u64, feature: u64) -> Vec<String> {
let numbered = format!("F{feature}:face:");
let on = |o: &solidcraft_doc::joints::JointOrigin| {
s.doc.occurrences.iter().any(|x| x.id == o.occurrence && x.component == comp)
&& o.snap.face_names().iter().any(|n| n.trim_start_matches(solidcraft_doc::naming::LEGACY_MARK).starts_with(&numbered))
};
let joints = s.doc.assembly.joints.iter().filter(|j| on(&j.a) || on(&j.b)).map(|j| format!("joint {}", j.name));
let origins = s.doc.assembly.origins.iter().filter(|o| on(&o.origin)).map(|o| format!("joint origin {}", o.name));
joints.chain(origins).collect()
}
fn relink(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "component.relink";
let comp = component_key(s, p, "component", cmd)?;
@@ -280,7 +326,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
}
// Read/evaluate the candidate before changing anything. Session::execute owns the single
// undo step and restores both the document and evaluated state on any later failure.
let (_, sf) = linked_bodies(&file, s.path.as_deref()).map_err(|e| bad(cmd, e.to_string()))?;
let (_, sf, faces) = linked_bodies(&file, s.path.as_deref()).map_err(|e| bad(cmd, e.to_string()))?;
let geometry_changed = match (s.doc.feature(link.feature).map(|f| &f.kind), &sf.kind) {
(Some(FeatureKind::Import { step: old, .. }), FeatureKind::Import { step, .. }) => old != step,
_ => true,
@@ -301,6 +347,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
f.body_names = sf.body_names;
}
f.kind = sf.kind;
f.link_faces = faces;
}
s.doc_mut().links.insert(comp, DesignLink { path: path.clone(), feature: link.feature });
s.refresh();
@@ -431,4 +478,136 @@ mod tests {
assert!(s.execute("component.insert_design", &json!({"path": "x.solidcraft", "translate": [1, "a", 2]})).is_err());
assert!(s.doc.components.is_empty() && s.doc.links.is_empty() && s.doc.features.is_empty());
}
/// #3330's part: a plate 60 × 40 × 5 with a Ø 6 hole at x = `hx` (10 mm), saved at `path`. The
/// session stays open to edit the part as a user would.
fn plate(path: &Path) -> Session {
let mut part = Session::default();
run(&mut part, "parameters.add", json!({"name": "hx", "expression": "10 mm"}));
run(&mut part, "solid.box", json!({"length": 60, "width": 40, "height": 5, "corner": [-30, -20, 0], "body_name": "Plate"}));
run(&mut part, "solid.cylinder", json!({"diameter": 6, "height": 7, "base": ["hx", 0, -1], "operation": "cut", "name": "Hole"}));
run(&mut part, "file.save", json!({"path": path}));
part
}
/// Another Ø 6 hole through the plate at `x`.
fn hole(part: &mut Session, x: f64, name: &str) {
run(part, "solid.cylinder", json!({"diameter": 6, "height": 7, "base": [x, 0, -1], "operation": "cut", "name": name}));
}
/// #3330's assembly: the plate linked in and grounded, and a pin rigidly jointed to the top edge
/// of its hole. `older`: the link keeps no face names, as one made before them.
fn pinned(path: &Path, older: bool) -> Session {
let mut s = Session::default();
let feature = run(&mut s, "component.insert_design", json!({"path": path, "name": "Plate"}))["feature"].as_u64().unwrap();
if older {
s.doc_mut().feature_mut(feature).unwrap().link_faces.clear();
s.refresh();
}
run(&mut s, "occurrence.ground", json!({"occurrence": "Plate:1", "grounded": true}));
run(&mut s, "solid.cylinder", json!({"diameter": 6, "height": 20, "base": [0, 50, 0], "operation": "new", "body_name": "PinBody"}));
run(&mut s, "component.create", json!({"name": "Pin", "parent": "root", "activate": false}));
run(&mut s, "component.move_bodies", json!({"bodies": ["PinBody"], "component": "Pin"}));
let joint = json!({"type": "rigid", "name": "PinInHole", "flip": true,
"a": {"occurrence": "Plate:1", "circle": [13, 0, 5]}, "b": {"occurrence": "Pin:1", "circle": [3, 50, 0]}});
run(&mut s, "joint.create", joint);
s
}
/// Asserts the pin's joint sits on the plate's top at x (world) and solves without errors.
fn assert_joint_at(s: &mut Session, x: f64, case: &str) {
let list = run(s, "joint.list", json!({}));
assert_eq!(list["errors"], json!([]), "{case}: {list}");
let o = &list["joints"][0]["frame_a"]["origin"];
let at = [0, 1, 2].map(|i| o[i].as_f64().unwrap_or(f64::NAN));
assert!((at[0] - x).abs() < 1e-6 && at[1].abs() < 1e-6 && (at[2] - 5.0).abs() < 1e-6, "{case}: the joint is at {at:?}, not x = {x}");
}
/// #3330: a joint on a linked part's hole stays on that hole when Update Links brings in an
/// edit of the part, as it does inside one design, also when the edit adds a hole of the same
/// size that takes the first one's place in the file.
#[test]
fn joints_on_a_linked_part_follow_its_faces_through_update_links() {
let dir = std::env::temp_dir().join(format!("solidcraft-link-names-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("plate.solidcraft");
let hx = |part: &mut Session, x: &str| {
run(part, "parameters.change", json!({"name": "hx", "expression": x}));
};
let edits: [(&str, &dyn Fn(&mut Session), f64); 3] = [
("the hole moved to x = 20", &|p: &mut Session| hx(p, "20 mm"), 20.0),
(
"a hole at x = -10 added before it in the timeline, and the hole moved to x = 20",
&|p: &mut Session| {
run(p, "timeline.rollback", json!({"position": 1}));
hole(p, -10.0, "Hole0");
run(p, "timeline.rollback", json!({}));
hx(p, "20 mm");
},
20.0,
),
(
"the hole moved to x = 5, and a hole added at x = 15",
&|p: &mut Session| {
hx(p, "5 mm");
hole(p, 15.0, "Hole2");
},
5.0,
),
];
for (case, edit, x) in edits {
let mut part = plate(&path);
let mut s = pinned(&path, false);
assert_joint_at(&mut s, 10.0, case);
edit(&mut part);
run(&mut part, "file.save", json!({}));
let update = run(&mut s, "component.update_links", json!({}));
assert_eq!(update["updated"], json!(["Plate"]), "{case}: {update}");
assert_eq!(update["warnings"], json!([]), "{case}: {update}");
assert_joint_at(&mut s, x, case);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// #3330: when the part no longer has the face a joint is on, Update Links and the joint list
/// say so instead of moving the joint to another hole of the same size.
#[test]
fn a_joint_whose_linked_face_is_gone_is_reported_not_moved() {
let dir = std::env::temp_dir().join(format!("solidcraft-link-gone-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("plate.solidcraft");
let mut part = plate(&path);
let mut s = pinned(&path, false);
hole(&mut part, -10.0, "Hole0");
run(&mut part, "timeline.delete", json!({"feature": "Hole"}));
run(&mut part, "file.save", json!({}));
let update = run(&mut s, "component.update_links", json!({}));
let warnings = update["warnings"].to_string();
assert!(warnings.contains("joint PinInHole") && warnings.contains("no longer exists"), "{update}");
let list = run(&mut s, "joint.list", json!({}));
assert_eq!(list["errors"][0]["name"], "PinInHole", "{list}");
assert!(list["joints"][0]["frame_a"].is_null(), "{list}");
let _ = std::fs::remove_dir_all(&dir);
}
/// A joint made on a link that kept no face names (an older design) names the faces by their
/// place in the file: Update Links says it can't vouch for it, and keeps the names from then on.
#[test]
fn update_links_warns_about_joints_on_faces_named_by_their_place() {
let dir = std::env::temp_dir().join(format!("solidcraft-link-numbered-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("plate.solidcraft");
let mut part = plate(&path);
let mut s = pinned(&path, true);
let feature = s.doc.links.values().next().unwrap().feature;
assert!(s.doc.feature(feature).unwrap().link_faces.is_empty());
// An unchanged part keeps the bodies; the names come in quietly.
assert_eq!(run(&mut s, "component.update_links", json!({}))["unchanged"], json!(["Plate"]));
assert!(!s.doc.feature(feature).unwrap().link_faces.is_empty());
run(&mut part, "parameters.change", json!({"name": "hx", "expression": "20 mm"}));
run(&mut part, "file.save", json!({}));
let update = run(&mut s, "component.update_links", json!({}));
assert!(update["warnings"].to_string().contains("joint PinInHole refers to faces of Plate by their place"), "{update}");
let _ = std::fs::remove_dir_all(&dir);
}
}