Skip to main content

brep_render/engine_state/
components.rs

1use crate::json_support::vec3_or;
2use super::*;
3
4// Components are derived from authored ACOMP features and namespaced display
5// solids. Kernel records stay on the runner; namespace parsing uses the kernel's
6// shared parser so both sides agree on component ownership.
7
8/// One assembly component instance as the APP sees it: the owning ACOMP feature
9/// id, the parts-library part name, the authored rigid pose (`inputParams.
10/// transform` — `{translate, rotateEulerDeg}`, intrinsic-XYZ degrees), the
11/// grounded flag, and the member solid names currently in the display scene.
12#[derive(Debug, Clone, PartialEq)]
13pub struct ComponentInfo {
14    /// The owning ACOMP feature id (`ACOMP<digits>`) — also the namespace prefix.
15    pub id: String,
16    /// The parts-library entry this instance places (`inputParams.partName`).
17    pub part_name: String,
18    /// `inputParams.transform.translate` (numbers-or-zero: an expression-valued
19    /// slot reads 0 here, matching the transform gizmo's numeric read).
20    pub translate: [f64; 3],
21    /// `inputParams.transform.rotateEulerDeg` (degrees, intrinsic XYZ).
22    pub rotate_deg: [f64; 3],
23    /// Grounded: an explicit `isFixed` wins; ABSENT mirrors the kernel's
24    /// auto-ground rule (grounded iff no ACOMP precedes it in the history).
25    pub fixed: bool,
26    /// Member solid names in display-scene order (`{id}:{part solid name}`).
27    /// Empty when the instance is rolled back / failed to build.
28    pub members: Vec<String>,
29}
30
31/// The ACOMP dispatch predicate, mirroring the kernel's `is_acomp_type` (the
32/// two literals `execute_feature` matches on).
33pub(crate) fn is_acomp_feature_type(feature_type: &str) -> bool {
34    matches!(feature_type, "ACOMP" | "ASSEMBLY COMPONENT")
35}
36
37
38impl EngineState {
39    /// The OWNING component feature id of a scene solid — the OUTERMOST
40    /// `ACOMP<digits>:` namespace segment of its name, verified against the
41    /// history (the segment must be an ACOMP feature of THIS document; a nested
42    /// chain's inner segments belong to the sub-assembly's own document).
43    /// `None` for ordinary modeling solids (no prefix) and for sketch-child
44    /// names (`S1:G20` — `S1` is not an ACOMP segment).
45    pub fn component_of_solid(&self, solid_name: &str) -> Option<String> {
46        let (chain, _local) = brep_kernel::split_component_namespace(solid_name);
47        let head = *chain.first()?;
48        // A Pattern Component instance is a component its pattern emits.
49        if brep_kernel::pattern_component_instance(head).is_some() {
50            return self.assembly_components().iter().any(|c| c.id == head).then(|| head.to_string());
51        }
52        let index = self.history.index_of(head)?;
53        self.history
54            .feature_type(index)
55            .filter(|ty| is_acomp_feature_type(ty))
56            .map(|_| head.to_string())
57    }
58
59    /// Every component a Pattern Component `pattern_id` controls: the seeds it
60    /// follows and every instance it placed, in a stable order (instances in
61    /// the record order, each seed before the first instance that follows it).
62    /// A seed that is itself an instance of an earlier pattern is included as
63    /// itself; a seed that is an earlier PATTERN brings in that pattern's whole
64    /// group, so a nested pattern names the whole tree. Empty when no instance
65    /// of `pattern_id` exists.
66    pub fn pattern_group(&self, pattern_id: &str) -> Vec<String> {
67        let mut group: Vec<String> = Vec::new();
68        for record in self.assembly_components() {
69            let Some((pattern, seed, _)) = brep_kernel::pattern_component_instance(&record.id) else { continue };
70            if pattern != pattern_id {
71                continue;
72            }
73            // A seed that is an earlier pattern's instance carries that
74            // pattern's own seed chain: walk it so the tree is whole.
75            let mut chain = vec![seed.clone()];
76            let mut cursor = seed;
77            while let Some((_, inner, _)) = brep_kernel::pattern_component_instance(&cursor) {
78                chain.push(inner.clone());
79                cursor = inner;
80            }
81            for id in chain.into_iter().rev().chain(std::iter::once(record.id.clone())) {
82                if !group.contains(&id) {
83                    group.push(id);
84                }
85            }
86        }
87        group
88    }
89
90    /// The Pattern Components a component belongs to: the pattern that placed
91    /// it (an instance), and every pattern that follows it as a seed.
92    pub fn patterns_of_component(&self, component_id: &str) -> Vec<String> {
93        let mut patterns: Vec<String> = Vec::new();
94        for record in self.assembly_components() {
95            let Some((pattern, seed, _)) = brep_kernel::pattern_component_instance(&record.id) else { continue };
96            if (record.id == component_id || seed == component_id) && !patterns.contains(&pattern) {
97                patterns.push(pattern);
98            }
99        }
100        patterns
101    }
102
103    /// The owning top-level occurrence of every selected vertex (vertices
104    /// carry no names, so the app's selection read cannot resolve them), or
105    /// `None` when any selected vertex is not component geometry.
106    pub fn selected_vertex_components(&self) -> Option<Vec<String>> {
107        self.emphasis
108            .selected_vertices
109            .iter()
110            .map(|vertex| self.component_of_solid(&vertex.solid))
111            .collect()
112    }
113
114    /// Every ACOMP feature id in history order (the structure tree's row order).
115    pub fn component_ids(&self) -> Vec<String> {
116        (0..self.history.len())
117            .filter(|&i| {
118                self.history
119                    .feature_type(i)
120                    .is_some_and(|ty| is_acomp_feature_type(&ty))
121            })
122            .filter_map(|i| self.history.feature_id(i))
123            .collect()
124    }
125
126    /// The derived [`ComponentInfo`] for an ACOMP feature id (`None` when the id
127    /// is missing or not an ACOMP feature).
128    pub fn component_info(&self, feature_id: &str) -> Option<ComponentInfo> {
129        let index = self.history.index_of(feature_id)?;
130        self.history
131            .feature_type(index)
132            .filter(|ty| is_acomp_feature_type(ty))?;
133        let params = self.history.feature_params(index).unwrap_or_default();
134        let transform = params.get("transform");
135        let translate = vec3_or(transform.and_then(|t| t.get("translate")), [0.0; 3]);
136        let rotate_deg = vec3_or(transform.and_then(|t| t.get("rotateEulerDeg")), [0.0; 3]);
137        // Grounded: explicit boolean wins; ABSENT (or null) mirrors the kernel's
138        // auto-ground — the FIRST component of the document is grounded.
139        let fixed = match params.get("isFixed") {
140            Some(serde_json::Value::Bool(flag)) => *flag,
141            _ => self
142                .component_ids()
143                .first()
144                .is_some_and(|first| first == feature_id),
145        };
146        let members = self.member_solid_names(feature_id);
147        Some(ComponentInfo {
148            id: feature_id.to_string(),
149            part_name: params
150                .get("partName")
151                .and_then(|v| v.as_str())
152                .unwrap_or_default()
153                .to_string(),
154            translate,
155            rotate_deg,
156            fixed,
157            members,
158        })
159    }
160
161    /// The world bbox CENTER of a component's member solids — the Move gizmo's
162    /// attach point. `None` when the component has no resident
163    /// members (rolled back / failed build).
164    pub fn component_bbox_center(&self, feature_id: &str) -> Option<[f64; 3]> {
165        let mut bbox = crate::camera::Aabb::empty();
166        for solid in self.scene.solids() {
167            if owned_by(&solid.name, feature_id) {
168                bbox.union(&solid.bbox);
169            }
170        }
171        (!bbox.is_empty()).then(|| bbox.center())
172    }
173
174    /// The member solids of a placed component or of a Pattern Component
175    /// instance (which has no feature of its own).
176    pub fn component_members(&self, id: &str) -> Vec<String> {
177        match self.component_info(id) {
178            Some(info) => info.members,
179            None => self.member_solid_names(id),
180        }
181    }
182
183    /// Every Pattern Component instance the last run placed, in run order.
184    pub fn pattern_instance_ids(&self) -> Vec<String> {
185        self.assembly_components()
186            .iter()
187            .filter(|c| brep_kernel::pattern_component_instance(&c.id).is_some())
188            .map(|c| c.id.clone())
189            .collect()
190    }
191
192    /// The member solid names of ACOMP `feature_id`, in display-scene order.
193    /// The caller has already resolved `feature_id` to an ACOMP feature of
194    /// THIS document, so ownership is the outermost namespace segment alone —
195    /// no per-solid history lookup. Routing every solid through
196    /// [`Self::component_of_solid`] (a linear `index_of` scan each) made this
197    /// O(solids × features); the BOM paid it once per row per frame.
198    pub(super) fn member_solid_names(&self, feature_id: &str) -> Vec<String> {
199        self.scene
200            .solids()
201            .iter()
202            .filter(|solid| owned_by(&solid.name, feature_id))
203            .map(|solid| solid.name.clone())
204            .collect()
205    }
206}
207
208/// Whether `solid_name`'s OUTERMOST `ACOMP<digits>:` segment is `feature_id`.
209/// A nested chain's inner segments belong to the sub-assembly's own document,
210/// exactly as [`EngineState::component_of_solid`] reads them.
211pub(super) fn owned_by(solid_name: &str, feature_id: &str) -> bool {
212    let (chain, _local) = brep_kernel::split_component_namespace(solid_name);
213    chain.first().copied() == Some(feature_id)
214}
215
216