ifc_lite_processing/
discovery.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Shared record discovery; native metadata and geometry-job decoration remain consumers.
6use crate::element::{plan_type_geometry, TypeGeometryMode};
7use crate::{prepass::PrepassSpans, scan::ScanClass};
8use ifc_lite_core::{
9    parser::{parse_ref, StepRecord},
10    IfcType, StepListItems,
11};
12use rustc_hash::{FxHashMap, FxHashSet};
13
14#[path = "discovery_type_admission.rs"]
15mod type_admission;
16
17/// One file's type-geometry decisions. The mode is explicit because exports
18/// suppress instantiated types while the viewer tags them for its Types view.
19pub type PlannedTypeProduct = (u32, usize, usize, IfcType, Vec<(u32, u8)>);
20pub struct TypeGeometryPlan {
21    pub mode: TypeGeometryMode,
22    pub referenced_representation_maps: FxHashSet<u32>,
23    pub instantiated_type_ids: FxHashSet<u32>,
24    pub mapped_item_plan: FxHashMap<u32, (u32, u32)>,
25    pub products: Vec<PlannedTypeProduct>,
26}
27
28impl TypeGeometryPlan {
29    pub fn from_file(content: &[u8], decoder: &mut ifc_lite_core::EntityDecoder, mode: TypeGeometryMode) -> Self {
30        Self::from_file_missing(content, decoder, true, true, mode)
31    }
32
33    pub fn from_file_missing(
34        content: &[u8],
35        decoder: &mut ifc_lite_core::EntityDecoder,
36        need_referenced: bool,
37        need_instantiated: bool,
38        mode: TypeGeometryMode,
39    ) -> Self {
40        let mut mapped = Vec::new();
41        let mut defines = Vec::new();
42        let mut scanner = ifc_lite_core::EntityScanner::new(content);
43        while let Some((id, name, start, end)) = scanner.next_entity() {
44            if need_referenced && ifc_lite_core::keyword_eq(name, "IFCMAPPEDITEM") {
45                mapped.push((id, start, end));
46            } else if need_instantiated && ifc_lite_core::keyword_eq(name, "IFCRELDEFINESBYTYPE") {
47                defines.push((id, start, end));
48            }
49        }
50        Self::from_spans(content, &mapped, &defines, &[], decoder, mode)
51    }
52
53    pub fn from_sets(
54        referenced_representation_maps: FxHashSet<u32>,
55        instantiated_type_ids: FxHashSet<u32>,
56        mode: TypeGeometryMode,
57    ) -> Self {
58        Self {
59            mode,
60            referenced_representation_maps,
61            instantiated_type_ids,
62            mapped_item_plan: FxHashMap::default(),
63            products: Vec::new(),
64        }
65    }
66
67    pub fn maps_for(&self, id: u32, maps: &[u32]) -> Vec<(u32, u8)> {
68        plan_type_geometry(
69            maps,
70            &self.referenced_representation_maps,
71            self.instantiated_type_ids.contains(&id),
72            self.mode,
73        )
74    }
75
76    pub fn from_scan(types: TypeScan, mapped_item_plan: FxHashMap<u32, (u32, u32)>, mode: TypeGeometryMode) -> Self {
77        let TypeScan {
78            products,
79            referenced_representation_maps,
80            instantiated_type_ids,
81        } = types;
82        let products = products
83            .into_iter()
84            .map(|(id, start, end, ty, maps)| {
85                let maps = plan_type_geometry(
86                    &maps,
87                    &referenced_representation_maps,
88                    instantiated_type_ids.contains(&id),
89                    mode,
90                );
91                (id, start, end, ty, maps)
92            })
93            .collect();
94        Self {
95            mode,
96            referenced_representation_maps,
97            instantiated_type_ids,
98            mapped_item_plan,
99            products,
100        }
101    }
102
103    /// Browser spans are decoded with the full decoder. A type record rejected
104    /// there is intentionally omitted, even if the scan-time parser accepts it
105    /// ([`Self::decode_products_reporting`] reports it; native drops the same
106    /// records via [`Self::retain_decodable_products`]).
107    pub fn from_spans(
108        content: &[u8],
109        mapped: &[(u32, usize, usize)],
110        defines: &[(u32, usize, usize)],
111        candidates: &[(u32, usize, usize, IfcType)],
112        decoder: &mut ifc_lite_core::EntityDecoder,
113        mode: TypeGeometryMode,
114    ) -> Self {
115        let mut referenced_representation_maps = FxHashSet::default();
116        let mut instantiated_type_ids = FxHashSet::default();
117        let mut mapped_item_plan: FxHashMap<u32, (u32, u32)> = FxHashMap::default();
118        for &(id, start, end) in mapped {
119            if let Ok(entity) = decoder.decode_at_with_id(id, start, end) {
120                if let Some(source) = entity.get_ref(ifc_lite_core::slot::IfcMappedItem::MAPPING_SOURCE.index()) {
121                    referenced_representation_maps.insert(source);
122                    mapped_item_plan
123                        .entry(source)
124                        .and_modify(|(count, min)| {
125                            *count += 1;
126                            *min = (*min).min(id);
127                        })
128                        .or_insert((1, id));
129                }
130            }
131        }
132        for &(id, start, end) in defines {
133            if let Ok(entity) = decoder.decode_at_with_id(id, start, end) {
134                if let Some(ty) = entity.get_ref(ifc_lite_core::slot::IfcRelDefinesByType::RELATING_TYPE.index()) {
135                    instantiated_type_ids.insert(ty);
136                }
137            }
138        }
139        let mut plan = Self {
140            mode,
141            referenced_representation_maps,
142            instantiated_type_ids,
143            mapped_item_plan,
144            products: Vec::new(),
145        };
146        plan.decode_products(content, candidates, decoder);
147        plan
148    }
149
150    /// Plan the candidates the full decoder accepts. Use
151    /// [`Self::decode_products_reporting`] to also learn what was omitted (F2).
152    pub fn decode_products(
153        &mut self,
154        content: &[u8],
155        candidates: &[(u32, usize, usize, IfcType)],
156        decoder: &mut ifc_lite_core::EntityDecoder,
157    ) {
158        self.decode_products_reporting(content, candidates, decoder);
159    }
160
161    pub fn jobs(&self) -> Vec<(u32, usize, usize, IfcType)> {
162        self.products
163            .iter()
164            .filter(|(_, _, _, _, maps)| !maps.is_empty())
165            .map(|(id, start, end, ty, _)| (*id, *start, *end, ty.clone()))
166            .collect()
167    }
168
169    pub fn browser_instance_sources(&self) -> Vec<u32> {
170        let mut ids: Vec<_> = self
171            .mapped_item_plan
172            .iter()
173            .filter(|(_, (count, _))| *count >= 2)
174            .map(|(&id, _)| id)
175            .collect();
176        ids.sort_unstable();
177        ids
178    }
179
180    /// The model-wide `IfcMappedItem` count of each source
181    /// [`Self::browser_instance_sources`] lists, in the same (ascending id)
182    /// order, so the browser's global instance plan applies its gate once per
183    /// model instead of once per batch.
184    pub fn browser_instance_counts(&self) -> Vec<u32> {
185        self.browser_instance_sources()
186            .iter()
187            .map(|id| self.mapped_item_plan.get(id).map_or(0, |(count, _)| *count))
188            .collect()
189    }
190}
191
192/// #957: type-product geometry (IfcXxxType + its RepresentationMaps) and the
193/// set of RepresentationMaps already instantiated by an IfcMappedItem. After
194/// the scan, RepresentationMaps NOT in the referenced set are rendered as
195/// orphan type geometry (buildingSMART annex-E showcase files).
196#[derive(Default)]
197pub struct TypeScan {
198    pub products: Vec<(u32, usize, usize, IfcType, Vec<u32>)>,
199    pub referenced_representation_maps: FxHashSet<u32>,
200    // #957 follow-up: type ids that an IfcRelDefinesByType instantiates (the type
201    // has at least one occurrence). Such a type's geometry is already drawn through
202    // its occurrences — directly or via an IfcMappedItem — so it must NOT also be
203    // rendered as orphan type-only geometry. Real-world exporters (e.g. ArchiCAD
204    // AC20) attach a RepresentationMap to nearly every door/window/furniture type
205    // while the occurrence carries its own body, leaving the type map referenced by
206    // no IfcMappedItem; without this gate every such type double-renders at its
207    // MappingOrigin (duplicate boxes at the wrong position).
208    pub instantiated_type_ids: FxHashSet<u32>,
209}
210/// The references in attribute `index`: every `#n` item of a list, or the one
211/// reference the attribute is. An item that is not exactly `#digits` (`#+5`,
212/// `#12abc`, an id past `u32::MAX`) is skipped, not guessed.
213pub(crate) fn ref_items(record: Option<&StepRecord<'_>>, index: usize) -> Vec<u32> {
214    let Some(token) = record.and_then(|record| record.attr(index)) else {
215        return Vec::new();
216    };
217    match StepListItems::of_list(token) {
218        Some(items) => items.filter_map(parse_ref).collect(),
219        None => parse_ref(token).into_iter().collect(),
220    }
221}
222
223/// Attribute `index` of a scanned record when it is exactly one reference.
224#[inline(never)]
225pub(crate) fn record_ref_at(bytes: &[u8], index: usize) -> Option<u32> {
226    StepRecord::parse(bytes)?.ref_at(index)
227}
228
229/// The references in attribute `index` of a scanned record ([`ref_items`]).
230#[inline(never)]
231pub fn record_refs_at(bytes: &[u8], index: usize) -> Vec<u32> {
232    ref_items(StepRecord::parse(bytes).as_ref(), index)
233}
234
235/// Scan-time state shared by native and future browser adapters.
236#[derive(Default)]
237#[non_exhaustive]
238pub struct Discovery {
239    pub prepass_spans: PrepassSpans,
240    pub project_id: Option<u32>,
241    pub site_entity_pos: Option<(usize, usize)>,
242    pub building_entity_pos: Option<(usize, usize)>,
243    pub mapped_item_plan: FxHashMap<u32, (u32, u32)>,
244    pub types: TypeScan,
245    instancing: bool,
246}
247
248impl Discovery {
249    pub fn new(instancing: bool) -> Self {
250        Self {
251            instancing,
252            ..Self::default()
253        }
254    }
255
256    /// Observe one record in file order. Returns the type of a geometry job;
257    /// callers retain the raw keyword when decorating metadata (#1910).
258    #[inline(always)]
259    pub fn observe(
260        &mut self,
261        content: &[u8],
262        class: ScanClass,
263        id: u32,
264        type_name: &str,
265        start: usize,
266        end: usize,
267    ) -> Option<IfcType> {
268        self.observe_inner::<false>(content, class, id, type_name, start, end)
269    }
270
271    /// Observe a browser record without collecting native type/mapping state.
272    #[inline(always)]
273    pub fn observe_browser(
274        &mut self,
275        content: &[u8],
276        class: ScanClass,
277        id: u32,
278        type_name: &str,
279        start: usize,
280        end: usize,
281    ) -> Option<IfcType> {
282        self.observe_inner::<true>(content, class, id, type_name, start, end)
283    }
284
285    #[inline(always)]
286    fn observe_inner<const BROWSER: bool>(
287        &mut self,
288        content: &[u8],
289        class: ScanClass,
290        id: u32,
291        type_name: &str,
292        start: usize,
293        end: usize,
294    ) -> Option<IfcType> {
295        if matches!(
296            class,
297            ScanClass::IndexedColourMap
298                | ScanClass::StyledItem
299                | ScanClass::MaterialDefinitionRepresentation
300                | ScanClass::RelAssociatesMaterial
301        ) {
302            self.prepass_spans.stash_class(class, id, start, end);
303            return None;
304        }
305        match class {
306            ScanClass::RelVoidsElement | ScanClass::RelFillsElement
307            | ScanClass::RelAggregates | ScanClass::RelDefinesByType => {
308                self.prepass_spans.stash_class(class, id, start, end);
309            }
310            ScanClass::Project => {
311                self.project_id.get_or_insert(id);
312            }
313            ScanClass::Site => {
314                self.site_entity_pos.get_or_insert((start, end));
315            }
316            ScanClass::Building => {
317                self.building_entity_pos.get_or_insert((start, end));
318            }
319            _ => {}
320        }
321        if ifc_lite_core::is_geometry_job(type_name, &content[start..end]) {
322            Some(ifc_lite_core::ifc_type_from_keyword(type_name))
323        } else {
324            if !BROWSER {
325                self.note_type_geometry(content, class, id, type_name, start, end);
326            }
327            None
328        }
329    }
330
331    // #957: collect type-product geometry (IfcXxxType carrying its own
332    // RepresentationMaps) and every IfcMappedItem's MappingSource, so after
333    // the scan we can render the RepresentationMaps that NO occurrence
334    // instantiates (orphan library/showcase geometry). The cheap suffix
335    // pre-filter keeps the is_subtype_of check off the hot path for the
336    // ~all-non-type majority of entities.
337    #[inline(always)]
338    fn note_type_geometry(
339        &mut self,
340        content: &[u8],
341        class: ScanClass,
342        id: u32,
343        type_name: &str,
344        start: usize,
345        end: usize,
346    ) {
347        if class == ScanClass::MappedItem {
348            if let Some(source_id) = record_ref_at(&content[start..end], 0) {
349                self.types.referenced_representation_maps.insert(source_id);
350                // #1623 Phase 2: tally occurrences per source + track the min-id
351                // (deterministic template) occurrence. `id` is this IfcMappedItem's
352                // express id (the router's `item.id` at mesh time).
353                if self.instancing {
354                    self.mapped_item_plan
355                        .entry(source_id)
356                        .and_modify(|(count, template)| {
357                            *count += 1;
358                            if id < *template {
359                                *template = id;
360                            }
361                        })
362                        .or_insert((1, id));
363                }
364            }
365        } else if class == ScanClass::RelDefinesByType {
366            // IfcRelDefinesByType.RelatingType is the last attribute (index 5);
367            // record it so its type-only geometry is suppressed (it has occurrences).
368            // (Its span also feeds the shared resolver's type-material fallback:
369            // stashed with the other relationship spans above.)
370            if let Some(type_id) = record_ref_at(&content[start..end], 5) {
371                self.types.instantiated_type_ids.insert(type_id);
372            }
373        } else if let Some(type_ty) = ifc_lite_core::type_product_ifc_type(type_name) {
374            // IfcTypeProduct.RepresentationMaps is attribute index 6.
375            let rep_map_ids = record_refs_at(&content[start..end], 6);
376            if !rep_map_ids.is_empty() {
377                self.types.products.push((id, start, end, type_ty, rep_map_ids));
378            }
379        }
380    }
381}