Skip to main content

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}`.
195pub fn namespaced(component_id: &str, name: &str) -> String {
196    format!("{component_id}:{name}")
197}
198
199/// Prefix every NAMED face/edge of a member solid with the component id (the
200/// solid's own scene name is prefixed by the caller — solids carry their name in
201/// [`AddedSolid`], not on the BREP). Unnamed entities stay unnamed (they are not
202/// scene-resolvable either way).
203fn namespace_solid_names(solid: &mut BrepSolid, component_id: &str) {
204    for shell in &mut solid.shells {
205        for face in &mut shell.faces {
206            if let Some(name) = &face.name {
207                face.name = Some(namespaced(component_id, name));
208            }
209        }
210    }
211    for edge in &mut solid.edges {
212        if let Some(name) = &edge.name {
213            edge.name = Some(namespaced(component_id, name));
214        }
215    }
216}
217
218/// Register a member body a weld prepared in context (an assembly-level
219/// result replacing the member under its own name). Its names follow the
220/// component's convention as if the part had been cut in its own document and
221/// then placed: every face and edge name is read without the member's
222/// namespace path (`ACOMP2:` for `ACOMP2:Part`), the faces made unique, the
223/// topology edges re-derived from them, and the path put back on all of them.
224/// So the member's untouched faces and edges keep the names references hold,
225/// and the faces the cut leaves (named for the weld) live under the component,
226/// where the reference fence still sees them as component geometry.
227pub(crate) fn register_context_member(mut body: BrepSolid, member: &str) -> AddedSolid {
228    let path = member.rfind(':').map(|end| &member[..=end]).unwrap_or("");
229    let strip = |name: &mut Option<String>| {
230        if let Some(local) = name.as_deref().and_then(|name| name.strip_prefix(path)) {
231            *name = Some(local.to_string());
232        }
233    };
234    for face in body.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
235        strip(&mut face.name);
236    }
237    for edge in &mut body.edges {
238        strip(&mut edge.name);
239    }
240    crate::feature_pipeline::features::common::ensure_unique_face_names(&mut body);
241    crate::feature_pipeline::features::common::stamp_derived_edge_names(&mut body);
242    if let Some(prefix) = path.strip_suffix(':') {
243        namespace_solid_names(&mut body, prefix);
244    }
245    let face_names = collect_face_names(&body);
246    let edge_names = collect_edge_names(&body);
247    let handle = crate::register_solid_value(body);
248    AddedSolid { handle, name: member.to_string(), face_names, edge_names, ..AddedSolid::default() }
249}
250
251/// A component id must be a plain feature id: non-empty, no `:` (the namespace
252/// delimiter) and no `|` (the topology-vs-authored name discriminator).
253fn validate_component_id(id: &str) -> Result<(), String> {
254    if id.is_empty() {
255        return Err("component id must not be empty".into());
256    }
257    if id.contains(':') || id.contains('|') {
258        return Err(format!("component id '{id}' must not contain ':' or '|'"));
259    }
260    Ok(())
261}
262
263// ===========================================================================
264// Rigid-transform helpers (row-major 4x4, the AffineTransform layout)
265// ===========================================================================
266
267/// Require a RIGID map (orthonormal rotation rows, determinant +1). Components
268/// move as rigid bodies — a scaling/shearing/reflecting instance pose is a
269/// modeling error, rejected loudly (no fallback).
270fn require_rigid(transform: &AffineTransform) -> Result<(), String> {
271    if transform.is_rigid(crate::RIGID_TOL) { return Ok(()); }
272    if (transform.determinant3() - 1.0).abs() > crate::RIGID_TOL {
273        return Err("component transform must be rigid (no reflection/scale)".into());
274    }
275    Err("component transform must be rigid (rotation + translation)".into())
276}
277
278/// Row-major product `a · b` (apply `b` first, then `a`).
279pub(crate) fn compose(a: &AffineTransform, b: &AffineTransform) -> Result<AffineTransform, String> {
280    a.compose(b)
281}
282
283// ===========================================================================
284// Create / re-pose
285// ===========================================================================
286
287/// Build a component from a set of PART-LOCAL solids: rigid-pose each member
288/// with `transform`, namespace its entity names with `id`, and register it as a
289/// scene-resident solid. Returns the component record plus one [`AddedSolid`]
290/// per member — the owning ACOMP feature pushes both into its `FeatureResult`
291/// (`added` + `components`), and the record's handles are then owned by that
292/// feature's history-cache entry like any other feature output.
293///
294/// `members` are `(solid name, part-local BREP)` pairs exactly as the sub-part's
295/// history produced them (deterministic names final; see the module doc — the
296/// prefix wraps them, nothing is re-derived). Two-phase: every member is posed
297/// BEFORE anything registers, so a failure never leaks a half-built component.
298// Contract surface for the Wave-2 ACOMP feature; exercised by this module's tests.
299#[allow(dead_code)]
300pub fn create_component(
301    id: &str,
302    part_name: &str,
303    fixed: bool,
304    source: serde_json::Value,
305    transform: AffineTransform,
306    members: Vec<(String, BrepSolid)>,
307) -> Result<(ComponentRecord, Vec<AddedSolid>), String> {
308    validate_component_id(id)?;
309    require_rigid(&transform)?;
310
311    // Phase 1 (fallible): pose + namespace every member.
312    let mut posed: Vec<(String, BrepSolid)> = Vec::with_capacity(members.len());
313    for (member_name, solid) in &members {
314        let mut body = transform_brep(solid, transform, false)
315            .map_err(|error| format!("component '{id}': member '{member_name}': {error}"))?;
316        namespace_solid_names(&mut body, id);
317        posed.push((namespaced(id, member_name), body));
318    }
319
320    // Phase 2 (infallible): register.
321    let mut added = Vec::with_capacity(posed.len());
322    let mut solids = Vec::with_capacity(posed.len());
323    for (name, body) in posed {
324        let face_names = collect_face_names(&body);
325        let edge_names = collect_edge_names(&body);
326        let handle = crate::register_solid_value(body);
327        solids.push(name.clone());
328        added.push(AddedSolid {
329            handle,
330            name,
331            face_names,
332            edge_names,
333            ..AddedSolid::default()
334        });
335    }
336
337    Ok((
338        ComponentRecord {
339            id: id.to_string(),
340            part_name: part_name.to_string(),
341            transform,
342            fixed,
343            source,
344            solids,
345            ports: Vec::new(),
346            nested_constraints: Vec::new(),
347            nested_poses: BTreeMap::new(),
348            pattern: None,
349            flexible: None,
350        },
351        added,
352    ))
353}
354
355/// Pose a part-local port record by a rigid transform: the base point maps as
356/// a point, the direction by the rotation part alone.
357pub fn pose_port(record: &PortRecord, transform: &AffineTransform) -> PortRecord {
358    let point = transform.point(record.point);
359    let tip = transform.point(record.point.add(record.direction));
360    let direction = tip.sub(point).normalized().unwrap_or(record.direction);
361    PortRecord {
362        point,
363        direction,
364        ..record.clone()
365    }
366}
367
368/// Attach a part's connection points to a placed component: each point's
369/// ADDRESS is wrapped `{component}:{address}` and its record is posed by the
370/// component transform. The record's `port_name` / `point_name` / `purpose`
371/// stay PART-LOCAL — the occurrence chain lives in the address, so pin `VCC` of
372/// port `J1` reads the same however deep it is placed. The record lists the
373/// addresses so [`update_component_transform`] moves them with the members; the
374/// posed records are returned for the feature to publish.
375pub fn attach_component_ports(
376    record: &mut ComponentRecord,
377    ports: &BTreeMap<String, PortRecord>,
378) -> Vec<(String, PortRecord)> {
379    let mut posed = Vec::with_capacity(ports.len());
380    for (local_id, port) in ports {
381        let id = namespaced(&record.id, local_id);
382        let port = pose_port(port, &record.transform);
383        record.ports.push(id.clone());
384        posed.push((id, port));
385    }
386    posed
387}
388
389/// Re-pose a component to a NEW absolute rigid transform: applies the delta
390/// `new · old⁻¹` to every member solid IN PLACE (same handles — a rigid map
391/// keeps every topology id and name, so the scene's face/edge refs stay valid)
392/// and updates the record.
393///
394/// This is the INTERACTIVE lane (move-gizmo drag, solver preview). The
395/// AUTHORITATIVE pose lives on the owning ACOMP feature's `inputParams`
396/// transform: a commit must write it back there (the solver pose write-back),
397/// which dirties the feature's fingerprint so the next history run re-executes
398/// it from the snapshot at the committed pose. Without the write-back, a clean
399/// cache replay would serve the mutated geometry against a stale descriptor.
400///
401/// Two-phase: every member transform is computed before anything commits, so a
402/// failure never leaves the component half-posed.
403// Contract surface for the Wave-2/3 move + solver lanes; exercised by tests.
404#[allow(dead_code)]
405pub fn update_component_transform(
406    scene: &mut SceneMap,
407    id: &str,
408    new_transform: AffineTransform,
409) -> Result<(), String> {
410    require_rigid(&new_transform)?;
411    let record = scene
412        .resolve_component(id)
413        .ok_or_else(|| format!("unknown component '{id}'"))?;
414    let delta = compose(&new_transform, &record.transform.rigid_inverse()?)?;
415    let port_ids = record.ports.clone();
416
417    // Phase 1 (fallible): resolve + re-pose every member. A member a weld
418    // prepared in context has two bodies, the component's own and the
419    // prepared one under its name: both move (the weld re-cuts from the
420    // component's when it rebuilds, and a scene the weld never rebuilds,
421    // such as the assembly session's own solve, still shows it in place).
422    let mut posed: Vec<(u32, BrepSolid)> = Vec::with_capacity(record.solids.len());
423    let mut prepared_by: Vec<String> = Vec::new();
424    for name in &record.solids {
425        let handle = scene
426            .solids
427            .get(name)
428            .copied()
429            .ok_or_else(|| format!("component '{id}': member '{name}' is not scene-resident"))?;
430        let mut handles = vec![handle];
431        if let Some(member) = scene.context_member(name) {
432            if member.prior != handle {
433                handles.push(member.prior);
434            }
435            prepared_by.push(member.weld.clone());
436        }
437        for handle in handles {
438            if posed.iter().any(|(seen, _)| *seen == handle) {
439                continue;
440            }
441            let body = crate::with_registered_solid_str(handle, |solid| {
442                transform_brep(solid, delta, false)
443            })
444            .map_err(|error| format!("component '{id}': member '{name}': {error}"))?;
445            posed.push((handle, body));
446        }
447    }
448
449    // Phase 2: commit under the existing handles, then update the record.
450    for (handle, body) in posed {
451        crate::replace_registered_solid(handle, body)?;
452    }
453    // The preparing weld's cache entry owns a body that just moved in place.
454    for weld in prepared_by {
455        super::mark_component_cache_posed(&weld);
456    }
457    if let Some(record) = scene.components.get_mut(id) {
458        record.transform = new_transform;
459        // A flexible instance's occurrences are among its members: they moved
460        // with it, so their frames follow.
461        let prefix = format!("{id}:");
462        for occurrence in scene.occurrences.values_mut().filter(|o| o.id.starts_with(&prefix)) {
463            occurrence.transform = compose(&delta, &occurrence.transform)?;
464        }
465        super::mark_component_cache_posed(id);
466    } else if scene.occurrences.contains_key(id) {
467        // A flexible occurrence placed inside a flexible occurrence moved
468        // with it too.
469        let prefix = format!("{id}:");
470        for occurrence in scene.occurrences.values_mut() {
471            if occurrence.id == id {
472                occurrence.transform = new_transform;
473            } else if occurrence.id.starts_with(&prefix) {
474                occurrence.transform = compose(&delta, &occurrence.transform)?;
475            }
476        }
477        // The placing feature's cache entry owns the occurrence's solids.
478        let owner = id.split(':').next().unwrap_or(id).to_string();
479        super::mark_component_cache_posed(&owner);
480    }
481
482    // The component's ports (and their published entities) follow the members,
483    // so a solve that moves a part moves the harness network it carries.
484    for port_id in port_ids {
485        let Some(port) = scene.ports.get(&port_id) else {
486            continue;
487        };
488        let posed = pose_port(port, &delta);
489        crate::feature_pipeline::ports::place_scene_port(scene, &port_id, posed)?;
490    }
491    Ok(())
492}
493
494/// The feature fence: fail with a clear message when any of
495/// `names` resolves to component-owned geometry. Modeling features that consume
496/// solids/faces/edges call this over their reference names before operating —
497/// cross-part feature linking is out of scope and must be rejected cleanly,
498/// never silently applied.
499pub fn reject_component_references<'a>(
500    scene: &SceneMap,
501    names: impl IntoIterator<Item = &'a str>,
502) -> Result<(), String> {
503    for name in names {
504        if let Some(record) = scene.owning_component(name) {
505            return Err(format!(
506                "'{name}' belongs to assembly component '{}' — modeling features cannot consume component geometry",
507                record.id
508            ));
509        }
510    }
511    Ok(())
512}
513
514/// The fence at the DISPATCH altitude — the one place every feature passes
515/// through (`execute_feature`), so no per-feature checks are scattered. A
516/// reference here is what the pipeline already defines it to be (the
517/// `scan_consumed` cache-dependency walk): any descriptor string that
518/// exact-matches a scene name. Any such string owned by a component fails the
519/// feature before it executes.
520///
521/// Exempt (the two ALLOWED in-context uses, attach + project): SKETCH (plane
522/// attach + edge projection), DATUM/PLANE (a datum derived from component
523/// geometry), ACOMP itself (the component's own feature, wired by the
524/// parts-library lane), and the two wire-harness construction features —
525/// WAYPOINT (its `directionRef` is a face on a placed component: the harness
526/// workbench's whole point) and SPLINE (its anchors attach to connection
527/// points). Assembly constraints are not history features, so they never
528/// reach this fence. The exemption is type-level, which is safe because none
529/// of the exempt types carries a `boolean` param or operand-solid references
530/// — re-examine if such a param is ever added to one of them.
531pub fn enforce_reference_fence(
532    feature_type: &str,
533    descriptor: &FeatureDescriptor,
534    scene: &SceneMap,
535) -> Result<(), String> {
536    // Componentless scenes skip the walk entirely — the byte-identical
537    // guarantee for every existing modeling document.
538    if scene.components.is_empty() {
539        return Ok(());
540    }
541    // Verbatim dispatch alias strings (the dispatch matches exact spellings;
542    // "ASSEMBLY COMPONENT" is ACOMP's long dispatch alias in assembly_component.rs).
543    if matches!(
544        feature_type,
545        "S" | "SKETCH"
546            | "S3D"
547            | "SKETCH3D"
548            | "3D SKETCH"
549            | "D"
550            | "DATUM"
551            | "DATIUM"
552            | "P"
553            | "PLANE"
554            | "ACOMP"
555            | "ASSEMBLY COMPONENT"
556            | "APAT"
557            | "PATTERN COMPONENT"
558            | "WP"
559            | "WAYPOINT"
560            | "SP"
561            | "SPLINE"
562    ) || super::features::weld::is_weld_type(feature_type)
563    {
564        return Ok(());
565    }
566    if let Some(name) = first_component_owned(&descriptor.input_params, scene)
567        .or_else(|| first_component_owned(&descriptor.persistent_data, scene))
568    {
569        return reject_component_references(scene, [name]);
570    }
571    Ok(())
572}
573
574/// The first string anywhere in `value` (recursively, both param sources — the
575/// `scan_consumed` walk shape) that names component-owned geometry.
576fn first_component_owned<'a>(
577    value: &'a serde_json::Value,
578    scene: &SceneMap,
579) -> Option<&'a str> {
580    match value {
581        serde_json::Value::String(text) => {
582            let trimmed = text.trim();
583            (!trimmed.is_empty() && scene.is_component_owned(trimmed)).then_some(trimmed)
584        }
585        serde_json::Value::Array(items) => {
586            items.iter().find_map(|item| first_component_owned(item, scene))
587        }
588        serde_json::Value::Object(map) => {
589            map.values().find_map(|item| first_component_owned(item, scene))
590        }
591        _ => None,
592    }
593}
594
595// ===========================================================================
596// SceneMap component surface
597// ===========================================================================
598
599impl SceneMap {
600    /// Resolve a component record by its owning feature id (exact match).
601    /// Contract surface for the Wave-2 constraint/selection lanes.
602    #[allow(dead_code)]
603    pub fn resolve_component(&self, id: &str) -> Option<&ComponentRecord> {
604        self.components.get(id).or_else(|| self.occurrences.get(id))
605    }
606
607    /// The component owning an entity name, if any: the BARE component id itself
608    /// (a COMPONENT-type selection), or the name's OUTERMOST namespace prefix
609    /// (`ACOMP3:ACOMP1:X` is owned by `ACOMP3` at this scene level; `ACOMP1` is
610    /// the nested assembly's internal structure). Membership is decided against
611    /// the registered component set, never syntactically — authored names like
612    /// `S1:PROFILE` have a first segment that is a sketch id, not a component id.
613    pub fn owning_component(&self, name: &str) -> Option<&ComponentRecord> {
614        if let Some(record) = self.resolve_component(name) {
615            return Some(record);
616        }
617        // A flexible instance's occurrence owns its own geometry (the deepest
618        // registered prefix wins over the instance).
619        if let Some(record) = self
620            .occurrences
621            .values()
622            .filter(|record| name.starts_with(&format!("{}:", record.id)))
623            .max_by_key(|record| record.id.len())
624        {
625            return Some(record);
626        }
627        let (prefix, _) = name.split_once(':')?;
628        self.components.get(prefix)
629    }
630
631    /// The feature-fence predicate: does this entity name belong to a component?
632    /// Cheap (one map probe + one prefix probe); the dispatch fence
633    /// (`enforce_reference_fence`) uses it to REJECT component geometry as
634    /// modeling-feature input.
635    pub fn is_component_owned(&self, name: &str) -> bool {
636        self.owning_component(name).is_some()
637    }
638
639    /// Iterate the scene's components in deterministic (id) order — the
640    /// structure-tree / BOM projection surface.
641    #[allow(dead_code)]
642    pub fn iter_components(&self) -> impl Iterator<Item = &ComponentRecord> {
643        self.components.values()
644    }
645
646    /// A component's member solids as `(scene name, resident handle)`, in the
647    /// record's member order. A member missing from the solid map (never the
648    /// case for an intact scene) is skipped.
649    #[allow(dead_code)]
650    pub fn component_solids(&self, id: &str) -> Vec<(String, u32)> {
651        let Some(record) = self.resolve_component(id) else {
652            return Vec::new();
653        };
654        record
655            .solids
656            .iter()
657            .filter_map(|name| self.solids.get(name).map(|&handle| (name.clone(), handle)))
658            .collect()
659    }
660
661    /// The member solids of an occurrence path: a component's (or a flexible
662    /// occurrence's) own record, else every solid named under the path, which
663    /// is how a placement inside a rigid sub-assembly is reached
664    /// (`ACOMP1:ACOMP2` → `ACOMP1:ACOMP2:Pin`), in name order.
665    pub fn occurrence_solids(&self, path: &str) -> Vec<(String, u32)> {
666        if self.resolve_component(path).is_some() {
667            return self.component_solids(path);
668        }
669        let prefix = format!("{path}:");
670        let mut solids: Vec<(String, u32)> = self
671            .solids
672            .iter()
673            .filter(|(name, _)| name.starts_with(&prefix))
674            .map(|(name, &handle)| (name.clone(), handle))
675            .collect();
676        solids.sort();
677        solids
678    }
679
680    /// A component's grounded flag (`None` for an unknown id).
681    #[allow(dead_code)]
682    pub fn component_fixed(&self, id: &str) -> Option<bool> {
683        self.resolve_component(id).map(|record| record.fixed)
684    }
685
686    /// Set a component's grounded flag. Scene-view state only — the
687    /// authoritative flag is the owning feature's `isFixed` (the Fixed
688    /// constraint / tree action writes THERE; this keeps the live scene in
689    /// sync between runs). Returns false for an unknown id.
690    #[allow(dead_code)]
691    pub fn set_component_fixed(&mut self, id: &str, fixed: bool) -> bool {
692        match self.components.get_mut(id).or(self.occurrences.get_mut(id)) {
693            Some(record) => {
694                record.fixed = fixed;
695                true
696            }
697            None => false,
698        }
699    }
700}
701