brep_kernel/feature_pipeline/component.rs
1//! The scene COMPONENT concept.
2//!
3//! A component is a rigid group of solids inserted by an ACOMP feature (one per
4//! placed instance). Its record carries the owning feature id, the library part
5//! name, the rigid instance pose, the fixed (grounded) flag, and an opaque source
6//! metadata slot; its member solids are ordinary scene-resident solids whose
7//! entity names are NAMESPACED with the owning feature id.
8//!
9//! # Namespacing — the prefix wraps, nothing else moves
10//!
11//! Every entity name of a member solid (the solid name, every `face.name`, every
12//! `edge.name` — the only named entities in this kernel; vertices carry no names)
13//! is prefixed with `{component_id}:` AT THE COMPONENT BOUNDARY, i.e. when the
14//! sub-part's solids enter the assembly scene:
15//!
16//! ```text
17//! Extrude1_top -> ACOMP2:Extrude1_top
18//! Extrude1|Extrude1_top[0]-> ACOMP2:Extrude1|Extrude1_top[0]
19//! ```
20//!
21//! INSIDE the namespace the deterministic-naming rules apply UNCHANGED: the
22//! names arrive final from the sub-part's own `register_added` passes
23//! (`ensure_unique_face_names` + `stamp_derived_edge_names`) and are NEVER
24//! re-derived here. Re-running the derived-edge pass after prefixing would
25//! rewrite `ACOMP2:A|B[0]` from the prefixed face names (different sort, embedded
26//! prefixes) — do not "fix" this by routing members through `register_added`.
27//! Two instances of the same part therefore never collide (distinct feature ids),
28//! and a nested assembly's already-namespaced members chain naturally:
29//! `ACOMP1:Extrude1_top` wrapped by `ACOMP3` becomes `ACOMP3:ACOMP1:Extrude1_top`.
30//!
31//! # The feature fence
32//!
33//! Solids from ordinary modeling features never belong to a component and behave
34//! exactly as before. Component geometry is valid input for constraints and
35//! sketch attach/project ONLY; modeling features must cheaply REJECT it —
36//! [`SceneMap::is_component_owned`] / [`reject_component_references`] are that
37//! predicate (Wave 2 wires the checks into feature resolution).
38
39use std::collections::BTreeMap;
40
41use crate::feature_pipeline::features::common::{collect_edge_names, collect_face_names};
42use crate::feature_pipeline::{AddedSolid, FeatureDescriptor, PortRecord, SceneMap};
43use crate::{transform_brep, AffineTransform, BrepSolid};
44
45// ===========================================================================
46// The component record
47// ===========================================================================
48
49/// One scene component: an ACOMP instance's identity, pose, and member solids.
50/// Rides the [`crate::feature_pipeline::FeatureResult`] `components` side-channel
51/// into `SceneMap::apply`, exactly like profiles/frames — the scene's component
52/// set is rebuilt from feature results every history run (a projected view,
53/// never an owning data structure).
54#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
55pub struct ComponentRecord {
56 /// The owning ACOMP feature id — also the namespace prefix segment.
57 pub id: String,
58 /// The display / parts-library part name (`M4-bolt` in `M4-bolt (ACOMP3)`).
59 pub part_name: String,
60 /// The rigid instance pose (part-local snapshot space -> assembly space),
61 /// already baked into the member geometry. Kept so a pose UPDATE can apply
62 /// the delta `new · old⁻¹` and so the solver can read the current pose.
63 pub transform: AffineTransform,
64 /// Grounded flag (the feature's `isFixed`; the solver never moves it).
65 pub fixed: bool,
66 /// Opaque source metadata slot (`sourceKey` / `sourceSignature` / …) for the
67 /// parts-library + update-components lanes; the scene never interprets it.
68 pub source: serde_json::Value,
69 /// Member solid scene names, already namespaced (`{id}:{part solid name}`).
70 pub solids: Vec<String>,
71 /// The part's harness PORT ids, namespaced (`{id}:{part port id}`) — the
72 /// wire-harness entities a placed part carries. Their records live in
73 /// [`SceneMap::ports`]; the re-pose lane moves them with the members.
74 pub ports: Vec<String>,
75 /// A sub-assembly's own constraint statuses (and those of every level
76 /// below it), namespaced with this component's id — solved inside the
77 /// sub-assembly's run, reported by the parent's (see `NestedConstraint`).
78 pub nested_constraints: Vec<NestedConstraint>,
79 /// A sub-assembly's SOLVED occurrence poses: occurrence path below this
80 /// component (`ACOMP2`, `ACOMP2:ACOMP1`, …) → its pose in this component's
81 /// part-local frame. Its own solve can move an occurrence away from the
82 /// transform its document authors, so anything that needs where a nested
83 /// occurrence actually sits composes `transform` with this, never the
84 /// authored transform. Empty for a part (and for a sub-assembly built from
85 /// a snapshot before its first solve this session).
86 pub nested_poses: BTreeMap<String, AffineTransform>,
87 /// An instance of a Pattern Component (`APAT`): which seed it follows and
88 /// how. `None` for every ACOMP-placed component.
89 pub pattern: Option<PatternFollow>,
90 /// Set on a FLEXIBLE sub-assembly instance (`inputParams.flexible`): what
91 /// the parent's solve needs to move its occurrences individually. `None`
92 /// = rigid, the default.
93 pub flexible: Option<FlexibleSpec>,
94}
95
96/// How a pattern instance follows its seed: its pose is `delta · seed pose`
97/// (`T · delta · T⁻¹ · seed pose` with `T` the driver's pose, in HOLES mode).
98#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
99pub struct PatternFollow {
100 /// The `APAT` feature that emitted it.
101 pub pattern_id: String,
102 /// The seed component it follows.
103 pub seed: String,
104 /// The instance's offset from the seed, in assembly space.
105 pub delta: AffineTransform,
106 /// Its place in the pattern (the seed is 1), or its hole's key.
107 pub key: i64,
108 /// HOLES mode: the component whose hole it follows. `delta` is then in
109 /// that component's frame and applies through its solved pose.
110 pub driver: Option<String>,
111}
112
113/// A flexible sub-assembly instance, as the parent's constraint run reads it
114/// (`assembly::flexible`): the child document's own constraints (raw, its
115/// namespace), which of its occurrences stay with the instance's frame, where
116/// the child authors each occurrence, and the per-instance solved poses the
117/// placing feature persists. All poses are part-local (the instance frame).
118/// `nested` holds the same for each occurrence the child itself places
119/// flexible (keyed by its id in the child), at any depth; only the top spec
120/// carries seeds and `fixed`, keyed by the full occurrence path
121/// (`ACOMP1:ACOMP2`). `fixed` is this instance's own Fix/Float of an
122/// occurrence (`inputParams.flexibleFixed`): it wins over the child's
123/// grounding, and a fixed occurrence is a grounded body where it stands.
124#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
125pub struct FlexibleSpec {
126 pub constraints: Vec<serde_json::Value>,
127 pub grounded: std::collections::BTreeSet<String>,
128 pub authored: BTreeMap<String, AffineTransform>,
129 pub seeds: BTreeMap<String, AffineTransform>,
130 pub fixed: BTreeMap<String, bool>,
131 pub nested: BTreeMap<String, FlexibleSpec>,
132}
133
134/// One constraint of a NESTED sub-assembly as its parent reports it.
135///
136/// A sub-assembly is rigid: its own constraints solve inside its own run (the
137/// isolated document run that makes its snapshot), and the parent's mates then
138/// place it as one body. The parent never re-solves these, but it must still
139/// say how they ended, so the row rides the component record. `id` carries the
140/// namespace of every level it passed (`ACOMP1:ACOMP2:CONC1`).
141#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
142pub struct NestedConstraint {
143 pub id: String,
144 #[serde(rename = "type")]
145 pub constraint_type: String,
146 pub enabled: bool,
147 pub status: String,
148 pub message: String,
149 pub satisfied: bool,
150}
151
152impl NestedConstraint {
153 /// The row for one constraint the run just settled.
154 pub fn from_entry(entry: &crate::feature_pipeline::assembly::ConstraintEntry) -> Self {
155 Self {
156 id: entry.id().to_string(),
157 constraint_type: entry.constraint_type.clone(),
158 enabled: entry.enabled,
159 status: entry.status().to_string(),
160 message: entry
161 .persistent("message")
162 .and_then(|value| value.as_str())
163 .unwrap_or("")
164 .to_string(),
165 satisfied: entry
166 .persistent("satisfied")
167 .and_then(|value| value.as_bool())
168 .unwrap_or(false),
169 }
170 }
171
172 /// The same row one level up, under the placing component's id.
173 pub fn namespaced(&self, component_id: &str) -> Self {
174 Self {
175 id: namespaced(component_id, &self.id),
176 ..self.clone()
177 }
178 }
179
180 /// Whether the parent should be told: enabled and not satisfied.
181 pub fn is_failure(&self) -> bool {
182 self.enabled && !self.satisfied
183 }
184}
185
186/// The scene's component set, keyed by owning feature id. `BTreeMap` so
187/// iteration (structure tree, BOM) is deterministic.
188pub type ComponentMap = BTreeMap<String, ComponentRecord>;
189
190// ===========================================================================
191// Namespacing
192// ===========================================================================
193
194/// Wrap one entity name with a component prefix: `{component_id}:{name}`.
195/// The component namespace of a history document (owner 2026-11-27): its
196/// own components (`ACOMP` features), each with the namespace of its part's
197/// document below it, found in the document's own `partsLibrary` or else in
198/// the installed library. Nesting deeper than 16 levels (a cycle) is cut off.
199pub fn component_namespace(document: &serde_json::Value) -> crate::ComponentNamespace {
200 namespace_level(document, document.get("partsLibrary"), 0)
201}
202
203/// [`component_namespace`] for a document whose parts library is held apart
204/// from it (the app's history keeps the block in its own field).
205pub fn component_namespace_with_library(document: &serde_json::Value, library: &serde_json::Value) -> crate::ComponentNamespace {
206 namespace_level(document, Some(library), 0)
207}
208
209/// [`component_namespace`] for a run's parsed request: its components, each
210/// part's document found in the request's library or else the installed one.
211pub(crate) fn component_namespace_of(
212 features: &[FeatureDescriptor],
213 library: &crate::feature_pipeline::parts_library::PartsLibraryMap,
214) -> crate::ComponentNamespace {
215 let mut namespace = crate::ComponentNamespace::new();
216 for feature in features.iter().filter(|f| crate::feature_pipeline::parts_library::is_acomp_type(&f.feature_type)) {
217 let text = |key: &str| feature.input_params.get(key).and_then(serde_json::Value::as_str).map(str::trim).filter(|t| !t.is_empty());
218 let Some(id) = text("id") else { continue };
219 let inner = text("partName")
220 .and_then(|part| {
221 library.get(part).map(|e| e.document.clone())
222 .or_else(|| crate::feature_pipeline::parts_library::active_entry(part).map(|e| e.document))
223 })
224 .map(|part| namespace_level(&part, part.get("partsLibrary"), 1))
225 .unwrap_or_default();
226 namespace.insert(id, inner);
227 }
228 namespace
229}
230
231fn namespace_level(document: &serde_json::Value, library: Option<&serde_json::Value>, depth: usize) -> crate::ComponentNamespace {
232 let mut namespace = crate::ComponentNamespace::new();
233 if depth > 16 {
234 return namespace;
235 }
236 let Some(features) = document.get("features").and_then(serde_json::Value::as_array) else {
237 return namespace;
238 };
239 for feature in features {
240 let is_component = feature
241 .get("type")
242 .and_then(serde_json::Value::as_str)
243 .is_some_and(crate::feature_pipeline::parts_library::is_acomp_type);
244 let params = feature.get("inputParams");
245 let text = |key: &str| {
246 params.and_then(|p| p.get(key)).and_then(serde_json::Value::as_str).map(str::trim).filter(|t| !t.is_empty())
247 };
248 let (true, Some(id)) = (is_component, text("id")) else { continue };
249 let inner = text("partName")
250 .and_then(|part| {
251 library
252 .and_then(|library| library.get(part))
253 .and_then(|entry| entry.get("document"))
254 .cloned()
255 .or_else(|| crate::feature_pipeline::parts_library::active_entry(part).map(|e| e.document))
256 })
257 .map(|part| namespace_level(&part, part.get("partsLibrary"), depth + 1))
258 .unwrap_or_default();
259 namespace.insert(id, inner);
260 }
261 namespace
262}
263
264pub fn namespaced(component_id: &str, name: &str) -> String {
265 format!("{component_id}:{name}")
266}
267
268/// Prefix every NAMED face/edge of a member solid with the component id (the
269/// solid's own scene name is prefixed by the caller — solids carry their name in
270/// [`AddedSolid`], not on the BREP). Unnamed entities stay unnamed (they are not
271/// scene-resolvable either way).
272fn namespace_solid_names(solid: &mut BrepSolid, component_id: &str) {
273 for shell in &mut solid.shells {
274 for face in &mut shell.faces {
275 if let Some(name) = &face.name {
276 face.name = Some(namespaced(component_id, name));
277 }
278 }
279 }
280 for edge in &mut solid.edges {
281 if let Some(name) = &edge.name {
282 edge.name = Some(namespaced(component_id, name));
283 }
284 }
285}
286
287/// Register a member body a weld prepared in context (an assembly-level
288/// result replacing the member under its own name). Its names follow the
289/// component's convention as if the part had been cut in its own document and
290/// then placed: every face and edge name is read without the member's
291/// namespace path (`ACOMP2:` for `ACOMP2:Part`), the faces made unique, the
292/// topology edges re-derived from them, and the path put back on all of them.
293/// So the member's untouched faces and edges keep the names references hold,
294/// and the faces the cut leaves (named for the weld) live under the component,
295/// where the reference fence still sees them as component geometry.
296pub(crate) fn register_context_member(mut body: BrepSolid, member: &str) -> AddedSolid {
297 let path = member.rfind(':').map(|end| &member[..=end]).unwrap_or("");
298 let strip = |name: &mut Option<String>| {
299 if let Some(local) = name.as_deref().and_then(|name| name.strip_prefix(path)) {
300 *name = Some(local.to_string());
301 }
302 };
303 for face in body.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
304 strip(&mut face.name);
305 }
306 for edge in &mut body.edges {
307 strip(&mut edge.name);
308 }
309 crate::feature_pipeline::features::common::ensure_unique_face_names(&mut body);
310 crate::feature_pipeline::features::common::stamp_derived_edge_names(&mut body);
311 if let Some(prefix) = path.strip_suffix(':') {
312 namespace_solid_names(&mut body, prefix);
313 }
314 let face_names = collect_face_names(&body);
315 let edge_names = collect_edge_names(&body);
316 let handle = crate::register_solid_value(body);
317 AddedSolid { handle, name: member.to_string(), face_names, edge_names, ..AddedSolid::default() }
318}
319
320/// A component id must be a plain feature id: non-empty, no `:` (the namespace
321/// delimiter) and no `|` (the topology-vs-authored name discriminator).
322fn validate_component_id(id: &str) -> Result<(), String> {
323 if id.is_empty() {
324 return Err("component id must not be empty".into());
325 }
326 if id.contains(':') || id.contains('|') {
327 return Err(format!("component id '{id}' must not contain ':' or '|'"));
328 }
329 Ok(())
330}
331
332// ===========================================================================
333// Rigid-transform helpers (row-major 4x4, the AffineTransform layout)
334// ===========================================================================
335
336/// Require a RIGID map (orthonormal rotation rows, determinant +1). Components
337/// move as rigid bodies — a scaling/shearing/reflecting instance pose is a
338/// modeling error, rejected loudly (no fallback).
339fn require_rigid(transform: &AffineTransform) -> Result<(), String> {
340 if transform.is_rigid(crate::RIGID_TOL) { return Ok(()); }
341 if (transform.determinant3() - 1.0).abs() > crate::RIGID_TOL {
342 return Err("component transform must be rigid (no reflection/scale)".into());
343 }
344 Err("component transform must be rigid (rotation + translation)".into())
345}
346
347/// Row-major product `a · b` (apply `b` first, then `a`).
348pub(crate) fn compose(a: &AffineTransform, b: &AffineTransform) -> Result<AffineTransform, String> {
349 a.compose(b)
350}
351
352// ===========================================================================
353// Create / re-pose
354// ===========================================================================
355
356/// Build a component from a set of PART-LOCAL solids: rigid-pose each member
357/// with `transform`, namespace its entity names with `id`, and register it as a
358/// scene-resident solid. Returns the component record plus one [`AddedSolid`]
359/// per member — the owning ACOMP feature pushes both into its `FeatureResult`
360/// (`added` + `components`), and the record's handles are then owned by that
361/// feature's history-cache entry like any other feature output.
362///
363/// `members` are `(solid name, part-local BREP)` pairs exactly as the sub-part's
364/// history produced them (deterministic names final; see the module doc — the
365/// prefix wraps them, nothing is re-derived). Two-phase: every member is posed
366/// BEFORE anything registers, so a failure never leaks a half-built component.
367// Contract surface for the Wave-2 ACOMP feature; exercised by this module's tests.
368#[allow(dead_code)]
369pub fn create_component(
370 id: &str,
371 part_name: &str,
372 fixed: bool,
373 source: serde_json::Value,
374 transform: AffineTransform,
375 members: Vec<(String, BrepSolid)>,
376) -> Result<(ComponentRecord, Vec<AddedSolid>), String> {
377 validate_component_id(id)?;
378 require_rigid(&transform)?;
379
380 // Phase 1 (fallible): pose + namespace every member.
381 let mut posed: Vec<(String, BrepSolid)> = Vec::with_capacity(members.len());
382 for (member_name, solid) in &members {
383 let mut body = transform_brep(solid, transform, false)
384 .map_err(|error| format!("component '{id}': member '{member_name}': {error}"))?;
385 namespace_solid_names(&mut body, id);
386 posed.push((namespaced(id, member_name), body));
387 }
388
389 // Phase 2 (infallible): register.
390 let mut added = Vec::with_capacity(posed.len());
391 let mut solids = Vec::with_capacity(posed.len());
392 for (name, body) in posed {
393 let face_names = collect_face_names(&body);
394 let edge_names = collect_edge_names(&body);
395 let handle = crate::register_solid_value(body);
396 solids.push(name.clone());
397 added.push(AddedSolid {
398 handle,
399 name,
400 face_names,
401 edge_names,
402 ..AddedSolid::default()
403 });
404 }
405
406 Ok((
407 ComponentRecord {
408 id: id.to_string(),
409 part_name: part_name.to_string(),
410 transform,
411 fixed,
412 source,
413 solids,
414 ports: Vec::new(),
415 nested_constraints: Vec::new(),
416 nested_poses: BTreeMap::new(),
417 pattern: None,
418 flexible: None,
419 },
420 added,
421 ))
422}
423
424/// Pose a part-local port record by a rigid transform: the base point maps as
425/// a point, the direction by the rotation part alone.
426pub fn pose_port(record: &PortRecord, transform: &AffineTransform) -> PortRecord {
427 let point = transform.point(record.point);
428 let tip = transform.point(record.point.add(record.direction));
429 let direction = tip.sub(point).normalized().unwrap_or(record.direction);
430 PortRecord {
431 point,
432 direction,
433 ..record.clone()
434 }
435}
436
437/// Attach a part's connection points to a placed component: each point's
438/// ADDRESS is wrapped `{component}:{address}` and its record is posed by the
439/// component transform. The record's `port_name` / `point_name` / `purpose`
440/// stay PART-LOCAL — the occurrence chain lives in the address, so pin `VCC` of
441/// port `J1` reads the same however deep it is placed. The record lists the
442/// addresses so [`update_component_transform`] moves them with the members; the
443/// posed records are returned for the feature to publish.
444pub fn attach_component_ports(
445 record: &mut ComponentRecord,
446 ports: &BTreeMap<String, PortRecord>,
447) -> Vec<(String, PortRecord)> {
448 let mut posed = Vec::with_capacity(ports.len());
449 for (local_id, port) in ports {
450 let id = namespaced(&record.id, local_id);
451 let port = pose_port(port, &record.transform);
452 record.ports.push(id.clone());
453 posed.push((id, port));
454 }
455 posed
456}
457
458/// Re-pose a component to a NEW absolute rigid transform: applies the delta
459/// `new · old⁻¹` to every member solid IN PLACE (same handles — a rigid map
460/// keeps every topology id and name, so the scene's face/edge refs stay valid)
461/// and updates the record.
462///
463/// This is the INTERACTIVE lane (move-gizmo drag, solver preview). The
464/// AUTHORITATIVE pose lives on the owning ACOMP feature's `inputParams`
465/// transform: a commit must write it back there (the solver pose write-back),
466/// which dirties the feature's fingerprint so the next history run re-executes
467/// it from the snapshot at the committed pose. Without the write-back, a clean
468/// cache replay would serve the mutated geometry against a stale descriptor.
469///
470/// Two-phase: every member transform is computed before anything commits, so a
471/// failure never leaves the component half-posed.
472// Contract surface for the Wave-2/3 move + solver lanes; exercised by tests.
473#[allow(dead_code)]
474pub fn update_component_transform(
475 scene: &mut SceneMap,
476 id: &str,
477 new_transform: AffineTransform,
478) -> Result<(), String> {
479 require_rigid(&new_transform)?;
480 let record = scene
481 .resolve_component(id)
482 .ok_or_else(|| format!("unknown component '{id}'"))?;
483 let delta = compose(&new_transform, &record.transform.rigid_inverse()?)?;
484 let port_ids = record.ports.clone();
485
486 // Phase 1 (fallible): resolve + re-pose every member. A member a weld
487 // prepared in context has two bodies, the component's own and the
488 // prepared one under its name: both move (the weld re-cuts from the
489 // component's when it rebuilds, and a scene the weld never rebuilds,
490 // such as the assembly session's own solve, still shows it in place).
491 let mut posed: Vec<(u32, BrepSolid)> = Vec::with_capacity(record.solids.len());
492 let mut prepared_by: Vec<String> = Vec::new();
493 for name in &record.solids {
494 let handle = scene
495 .solids
496 .get(name)
497 .copied()
498 .ok_or_else(|| format!("component '{id}': member '{name}' is not scene-resident"))?;
499 let mut handles = vec![handle];
500 if let Some(member) = scene.context_member(name) {
501 if member.prior != handle {
502 handles.push(member.prior);
503 }
504 prepared_by.push(member.weld.clone());
505 }
506 for handle in handles {
507 if posed.iter().any(|(seen, _)| *seen == handle) {
508 continue;
509 }
510 let body = crate::with_registered_solid_str(handle, |solid| {
511 transform_brep(solid, delta, false)
512 })
513 .map_err(|error| format!("component '{id}': member '{name}': {error}"))?;
514 posed.push((handle, body));
515 }
516 }
517
518 // Phase 2: commit under the existing handles, then update the record.
519 for (handle, body) in posed {
520 crate::replace_registered_solid(handle, body)?;
521 }
522 // The preparing weld's cache entry owns a body that just moved in place.
523 for weld in prepared_by {
524 super::mark_component_cache_posed(&weld);
525 }
526 if let Some(record) = scene.components.get_mut(id) {
527 record.transform = new_transform;
528 // A flexible instance's occurrences are among its members: they moved
529 // with it, so their frames follow.
530 let prefix = format!("{id}:");
531 for occurrence in scene.occurrences.values_mut().filter(|o| o.id.starts_with(&prefix)) {
532 occurrence.transform = compose(&delta, &occurrence.transform)?;
533 }
534 super::mark_component_cache_posed(id);
535 } else if scene.occurrences.contains_key(id) {
536 // A flexible occurrence placed inside a flexible occurrence moved
537 // with it too.
538 let prefix = format!("{id}:");
539 for occurrence in scene.occurrences.values_mut() {
540 if occurrence.id == id {
541 occurrence.transform = new_transform;
542 } else if occurrence.id.starts_with(&prefix) {
543 occurrence.transform = compose(&delta, &occurrence.transform)?;
544 }
545 }
546 // The placing feature's cache entry owns the occurrence's solids.
547 let owner = id.split(':').next().unwrap_or(id).to_string();
548 super::mark_component_cache_posed(&owner);
549 }
550
551 // The component's ports (and their published entities) follow the members,
552 // so a solve that moves a part moves the harness network it carries.
553 for port_id in port_ids {
554 let Some(port) = scene.ports.get(&port_id) else {
555 continue;
556 };
557 let posed = pose_port(port, &delta);
558 crate::feature_pipeline::ports::place_scene_port(scene, &port_id, posed)?;
559 }
560 Ok(())
561}
562
563/// The feature fence: fail with a clear message when any of
564/// `names` resolves to component-owned geometry. Modeling features that consume
565/// solids/faces/edges call this over their reference names before operating —
566/// cross-part feature linking is out of scope and must be rejected cleanly,
567/// never silently applied.
568pub fn reject_component_references<'a>(
569 scene: &SceneMap,
570 names: impl IntoIterator<Item = &'a str>,
571) -> Result<(), String> {
572 for name in names {
573 if let Some(record) = scene.owning_component(name) {
574 return Err(format!(
575 "'{name}' belongs to assembly component '{}' — modeling features cannot consume component geometry",
576 record.id
577 ));
578 }
579 }
580 Ok(())
581}
582
583/// The fence at the DISPATCH altitude — the one place every feature passes
584/// through (`execute_feature`), so no per-feature checks are scattered. A
585/// reference here is what the pipeline already defines it to be (the
586/// `scan_consumed` cache-dependency walk): any descriptor string that
587/// exact-matches a scene name. Any such string owned by a component fails the
588/// feature before it executes.
589///
590/// Exempt (the two ALLOWED in-context uses, attach + project): SKETCH (plane
591/// attach + edge projection), DATUM/PLANE (a datum derived from component
592/// geometry), ACOMP itself (the component's own feature, wired by the
593/// parts-library lane), and the two wire-harness construction features —
594/// WAYPOINT (its `directionRef` is a face on a placed component: the harness
595/// workbench's whole point) and SPLINE (its anchors attach to connection
596/// points). Assembly constraints are not history features, so they never
597/// reach this fence. The exemption is type-level, which is safe because none
598/// of the exempt types carries a `boolean` param or operand-solid references
599/// — re-examine if such a param is ever added to one of them.
600pub fn enforce_reference_fence(
601 feature_type: &str,
602 descriptor: &FeatureDescriptor,
603 scene: &SceneMap,
604) -> Result<(), String> {
605 // Componentless scenes skip the walk entirely — the byte-identical
606 // guarantee for every existing modeling document.
607 if scene.components.is_empty() {
608 return Ok(());
609 }
610 // Verbatim dispatch alias strings (the dispatch matches exact spellings;
611 // "ASSEMBLY COMPONENT" is ACOMP's long dispatch alias in assembly_component.rs).
612 if matches!(
613 feature_type,
614 "S" | "SKETCH"
615 | "S3D"
616 | "SKETCH3D"
617 | "3D SKETCH"
618 | "D"
619 | "DATUM"
620 | "DATIUM"
621 | "P"
622 | "PLANE"
623 | "ACOMP"
624 | "ASSEMBLY COMPONENT"
625 | "APAT"
626 | "PATTERN COMPONENT"
627 | "WP"
628 | "WAYPOINT"
629 | "SP"
630 | "SPLINE"
631 ) || super::features::weld::is_weld_type(feature_type)
632 {
633 return Ok(());
634 }
635 if let Some(name) = first_component_owned(&descriptor.input_params, scene)
636 .or_else(|| first_component_owned(&descriptor.persistent_data, scene))
637 {
638 return reject_component_references(scene, [name]);
639 }
640 Ok(())
641}
642
643/// The first string anywhere in `value` (recursively, both param sources — the
644/// `scan_consumed` walk shape) that names component-owned geometry.
645fn first_component_owned<'a>(
646 value: &'a serde_json::Value,
647 scene: &SceneMap,
648) -> Option<&'a str> {
649 match value {
650 serde_json::Value::String(text) => {
651 let trimmed = text.trim();
652 (!trimmed.is_empty() && scene.is_component_owned(trimmed)).then_some(trimmed)
653 }
654 serde_json::Value::Array(items) => {
655 items.iter().find_map(|item| first_component_owned(item, scene))
656 }
657 serde_json::Value::Object(map) => {
658 map.values().find_map(|item| first_component_owned(item, scene))
659 }
660 _ => None,
661 }
662}
663
664// ===========================================================================
665// SceneMap component surface
666// ===========================================================================
667
668impl SceneMap {
669 /// Resolve a component record by its owning feature id (exact match).
670 /// Contract surface for the Wave-2 constraint/selection lanes.
671 #[allow(dead_code)]
672 pub fn resolve_component(&self, id: &str) -> Option<&ComponentRecord> {
673 super::early_cutoff::note_read(id);
674 self.components.get(id).or_else(|| self.occurrences.get(id))
675 }
676
677 /// The component owning an entity name, if any: the BARE component id itself
678 /// (a COMPONENT-type selection), or the name's OUTERMOST namespace prefix
679 /// (`ACOMP3:ACOMP1:X` is owned by `ACOMP3` at this scene level; `ACOMP1` is
680 /// the nested assembly's internal structure). Membership is decided against
681 /// the registered component set, never syntactically — authored names like
682 /// `S1:PROFILE` have a first segment that is a sketch id, not a component id.
683 pub fn owning_component(&self, name: &str) -> Option<&ComponentRecord> {
684 if let Some(record) = self.resolve_component(name) {
685 return Some(record);
686 }
687 // A flexible instance's occurrence owns its own geometry (the deepest
688 // registered prefix wins over the instance).
689 if let Some(record) = self
690 .occurrences
691 .values()
692 .filter(|record| name.starts_with(&format!("{}:", record.id)))
693 .max_by_key(|record| record.id.len())
694 {
695 return Some(record);
696 }
697 let (prefix, _) = name.split_once(':')?;
698 self.components.get(prefix)
699 }
700
701 /// The feature-fence predicate: does this entity name belong to a component?
702 /// Cheap (one map probe + one prefix probe); the dispatch fence
703 /// (`enforce_reference_fence`) uses it to REJECT component geometry as
704 /// modeling-feature input.
705 pub fn is_component_owned(&self, name: &str) -> bool {
706 self.owning_component(name).is_some()
707 }
708
709 /// Iterate the scene's components in deterministic (id) order — the
710 /// structure-tree / BOM projection surface.
711 #[allow(dead_code)]
712 pub fn iter_components(&self) -> impl Iterator<Item = &ComponentRecord> {
713 self.components.values()
714 }
715
716 /// A component's member solids as `(scene name, resident handle)`, in the
717 /// record's member order. A member missing from the solid map (never the
718 /// case for an intact scene) is skipped.
719 #[allow(dead_code)]
720 pub fn component_solids(&self, id: &str) -> Vec<(String, u32)> {
721 let Some(record) = self.resolve_component(id) else {
722 return Vec::new();
723 };
724 record
725 .solids
726 .iter()
727 .filter_map(|name| self.solids.get(name).map(|&handle| (name.clone(), handle)))
728 .collect()
729 }
730
731 /// The member solids of an occurrence path: a component's (or a flexible
732 /// occurrence's) own record, else every solid named under the path, which
733 /// is how a placement inside a rigid sub-assembly is reached
734 /// (`ACOMP1:ACOMP2` → `ACOMP1:ACOMP2:Pin`), in name order.
735 pub fn occurrence_solids(&self, path: &str) -> Vec<(String, u32)> {
736 if self.resolve_component(path).is_some() {
737 return self.component_solids(path);
738 }
739 let prefix = format!("{path}:");
740 let mut solids: Vec<(String, u32)> = self
741 .solids
742 .iter()
743 .filter(|(name, _)| name.starts_with(&prefix))
744 .map(|(name, &handle)| (name.clone(), handle))
745 .collect();
746 solids.sort();
747 solids
748 }
749
750 /// A component's grounded flag (`None` for an unknown id).
751 #[allow(dead_code)]
752 pub fn component_fixed(&self, id: &str) -> Option<bool> {
753 self.resolve_component(id).map(|record| record.fixed)
754 }
755
756 /// Set a component's grounded flag. Scene-view state only — the
757 /// authoritative flag is the owning feature's `isFixed` (the Fixed
758 /// constraint / tree action writes THERE; this keeps the live scene in
759 /// sync between runs). Returns false for an unknown id.
760 #[allow(dead_code)]
761 pub fn set_component_fixed(&mut self, id: &str, fixed: bool) -> bool {
762 match self.components.get_mut(id).or(self.occurrences.get_mut(id)) {
763 Some(record) => {
764 record.fixed = fixed;
765 true
766 }
767 None => false,
768 }
769 }
770}
771