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 namespace = self.component_namespace();
47 let (chain, _local) = namespace.split(solid_name);
48 let head = *chain.first()?;
49 // A Pattern Component instance is a component its pattern emits.
50 if brep_kernel::pattern_component_instance(head).is_some() {
51 return self.assembly_components().iter().any(|c| c.id == head).then(|| head.to_string());
52 }
53 let index = self.history.index_of(head)?;
54 self.history
55 .feature_type(index)
56 .filter(|ty| is_acomp_feature_type(ty))
57 .map(|_| head.to_string())
58 }
59
60 /// Every component a Pattern Component `pattern_id` controls: the seeds it
61 /// follows and every instance it placed, in a stable order (instances in
62 /// the record order, each seed before the first instance that follows it).
63 /// A seed that is itself an instance of an earlier pattern is included as
64 /// itself; a seed that is an earlier PATTERN brings in that pattern's whole
65 /// group, so a nested pattern names the whole tree. Empty when no instance
66 /// of `pattern_id` exists.
67 pub fn pattern_group(&self, pattern_id: &str) -> Vec<String> {
68 let mut group: Vec<String> = Vec::new();
69 for record in self.assembly_components() {
70 let Some((pattern, seed, _)) = brep_kernel::pattern_component_instance(&record.id) else { continue };
71 if pattern != pattern_id {
72 continue;
73 }
74 // A seed that is an earlier pattern's instance carries that
75 // pattern's own seed chain: walk it so the tree is whole.
76 let mut chain = vec![seed.clone()];
77 let mut cursor = seed;
78 while let Some((_, inner, _)) = brep_kernel::pattern_component_instance(&cursor) {
79 chain.push(inner.clone());
80 cursor = inner;
81 }
82 for id in chain.into_iter().rev().chain(std::iter::once(record.id.clone())) {
83 if !group.contains(&id) {
84 group.push(id);
85 }
86 }
87 }
88 group
89 }
90
91 /// The Pattern Components a component belongs to: the pattern that placed
92 /// it (an instance), and every pattern that follows it as a seed.
93 pub fn patterns_of_component(&self, component_id: &str) -> Vec<String> {
94 let mut patterns: Vec<String> = Vec::new();
95 for record in self.assembly_components() {
96 let Some((pattern, seed, _)) = brep_kernel::pattern_component_instance(&record.id) else { continue };
97 if (record.id == component_id || seed == component_id) && !patterns.contains(&pattern) {
98 patterns.push(pattern);
99 }
100 }
101 patterns
102 }
103
104 /// The owning top-level occurrence of every selected vertex (vertices
105 /// carry no names, so the app's selection read cannot resolve them), or
106 /// `None` when any selected vertex is not component geometry.
107 pub fn selected_vertex_components(&self) -> Option<Vec<String>> {
108 self.emphasis
109 .selected_vertices
110 .iter()
111 .map(|vertex| self.component_of_solid(&vertex.solid))
112 .collect()
113 }
114
115 /// Every ACOMP feature id in history order (the structure tree's row order).
116 pub fn component_ids(&self) -> Vec<String> {
117 (0..self.history.len())
118 .filter(|&i| {
119 self.history
120 .feature_type(i)
121 .is_some_and(|ty| is_acomp_feature_type(&ty))
122 })
123 .filter_map(|i| self.history.feature_id(i))
124 .collect()
125 }
126
127 /// The derived [`ComponentInfo`] for an ACOMP feature id (`None` when the id
128 /// is missing or not an ACOMP feature).
129 pub fn component_info(&self, feature_id: &str) -> Option<ComponentInfo> {
130 let index = self.history.index_of(feature_id)?;
131 self.history
132 .feature_type(index)
133 .filter(|ty| is_acomp_feature_type(ty))?;
134 let params = self.history.feature_params(index).unwrap_or_default();
135 let transform = params.get("transform");
136 let translate = vec3_or(transform.and_then(|t| t.get("translate")), [0.0; 3]);
137 let rotate_deg = vec3_or(transform.and_then(|t| t.get("rotateEulerDeg")), [0.0; 3]);
138 // Grounded: explicit boolean wins; ABSENT (or null) mirrors the kernel's
139 // auto-ground — the FIRST component of the document is grounded.
140 let fixed = match params.get("isFixed") {
141 Some(serde_json::Value::Bool(flag)) => *flag,
142 _ => self
143 .component_ids()
144 .first()
145 .is_some_and(|first| first == feature_id),
146 };
147 let members = self.member_solid_names(feature_id);
148 Some(ComponentInfo {
149 id: feature_id.to_string(),
150 part_name: params
151 .get("partName")
152 .and_then(|v| v.as_str())
153 .unwrap_or_default()
154 .to_string(),
155 translate,
156 rotate_deg,
157 fixed,
158 members,
159 })
160 }
161
162 /// The world bbox CENTER of a component's member solids — the Move gizmo's
163 /// attach point. `None` when the component has no resident
164 /// members (rolled back / failed build).
165 pub fn component_bbox_center(&self, feature_id: &str) -> Option<[f64; 3]> {
166 let mut bbox = crate::camera::Aabb::empty();
167 for solid in self.scene.solids() {
168 if owned_by(&solid.name, feature_id) {
169 bbox.union(&solid.bbox);
170 }
171 }
172 (!bbox.is_empty()).then(|| bbox.center())
173 }
174
175 /// The member solids of a placed component or of a Pattern Component
176 /// instance (which has no feature of its own).
177 pub fn component_members(&self, id: &str) -> Vec<String> {
178 match self.component_info(id) {
179 Some(info) => info.members,
180 None => self.member_solid_names(id),
181 }
182 }
183
184 /// Every Pattern Component instance the last run placed, in run order.
185 pub fn pattern_instance_ids(&self) -> Vec<String> {
186 self.assembly_components()
187 .iter()
188 .filter(|c| brep_kernel::pattern_component_instance(&c.id).is_some())
189 .map(|c| c.id.clone())
190 .collect()
191 }
192
193 /// The member solid names of ACOMP `feature_id`, in display-scene order.
194 /// The caller has already resolved `feature_id` to an ACOMP feature of
195 /// THIS document, so ownership is the outermost namespace segment alone —
196 /// no per-solid history lookup. Routing every solid through
197 /// [`Self::component_of_solid`] (a linear `index_of` scan each) made this
198 /// O(solids × features); the BOM paid it once per row per frame.
199 pub(super) fn member_solid_names(&self, feature_id: &str) -> Vec<String> {
200 self.scene
201 .solids()
202 .iter()
203 .filter(|solid| owned_by(&solid.name, feature_id))
204 .map(|solid| solid.name.clone())
205 .collect()
206 }
207}
208
209/// Whether `solid_name`'s OUTERMOST `ACOMP<digits>:` segment is `feature_id`.
210/// A nested chain's inner segments belong to the sub-assembly's own document,
211/// exactly as [`EngineState::component_of_solid`] reads them.
212pub(super) fn owned_by(solid_name: &str, feature_id: &str) -> bool {
213 // `feature_id` is a component of this document, so the name's first
214 // segment is it exactly when the name opens with `{feature_id}:`.
215 solid_name.split_once(':').is_some_and(|(head, _)| head == feature_id)
216}
217
218