ifc_lite_processing/data_model/rows/
mod.rs

1// SPDX-License-Identifier: MPL-2.0
2//! (Moved from `rust/export/src/model.rs`, C6-8, #7783; `ifc_lite_export::model`
3//! re-exports it at the same paths.)
4//!
5//! Shared **export data model** — one parse pass that yields the entities,
6//! property sets and quantity sets the tabular / semantic exporters (CSV, JSON,
7//! JSON-LD, Parquet) all consume.
8//!
9//! Built directly on `ifc_lite_core`'s `EntityDecoder` / `AttributeValue` model
10//! (the Rust source of truth), so property + quantity extraction lives in Rust
11//! rather than the TS `columnar-parser`. Covers `IfcProduct` occurrences and their
12//! directly-attached `IfcRelDefinesByProperties` property/quantity sets.
13
14use std::collections::HashMap;
15use std::sync::Arc;
16
17use ifc_lite_core::{
18    keyword_eq, slot, AttributeValue, DecodedEntity, EntityDecoder, EntityIndex, EntityScanner, IfcType,
19    EXPORTER_STRATUM_ALIASES,
20};
21use crate::element::{plan_type_geometry, TypeGeometryMode};
22use crate::prepass::{resolve_unit_scales, UnitScales};
23use ifc_lite_geometry::GeometryRouter;
24use rustc_hash::FxHashSet;
25
26
27mod options;
28pub use options::{ModelOptions, Placement};
29
30pub use ifc_lite_core::fmt_num::fmt_num;
31use super::inherit::{inherit_from_type, TypeSetCache};
32use super::type_assignments::TypeAssignments;
33use super::render::flat::{new_property_decoder, opt_string, ref_list, render_attributes, resolve_pset_defs_with_kinds};
34use super::property::PropertyKind;
35
36mod classified;
37pub use classified::{
38    stream_export_model_with_inherited, stream_export_model_with_options, stream_export_model_with_property_kinds,
39};
40mod support;
41mod types;
42use support::TypeProductCandidate;
43pub use support::attribute_schema;
44pub use types::{EntityRow, ExportModel, Inherited, PropValue, PropertySet, QuantitySet, QuantityValue, ValueKind};
45
46/// Build the export model from raw IFC/STEP bytes.
47///
48/// Collects every row into an [`ExportModel`]. This is fine for normal models,
49/// but for very large ones (tens of millions of entities) the retained
50/// `Vec<EntityRow>` is itself multiple GB — prefer [`stream_export_model`], which
51/// yields rows one at a time and never holds them all. `build_export_model` is a
52/// thin `collect` over `stream_export_model`, so the two share one code path.
53pub fn build_export_model(content: &[u8]) -> ExportModel {
54    let mut entities = Vec::new();
55    let units = stream_export_model(content, |row| entities.push(row));
56    ExportModel { entities, units }
57}
58
59/// [`build_export_model`] with options. Same memory caveat: this collects.
60pub fn build_export_model_with_options(content: &[u8], opts: &ModelOptions) -> ExportModel {
61    let entity_index = Arc::new(crate::build_entity_index_parallel(content));
62    let mut entities = Vec::new();
63    let units =
64        stream_export_model_with_options(content, &entity_index, opts, |row, _| entities.push(row));
65    ExportModel { entities, units }
66}
67
68/// Stream one [`EntityRow`] per `IfcProduct` occurrence, in file order, invoking
69/// `f` for each row and then dropping it.
70///
71/// Unlike [`build_export_model`], this never retains all rows and never caches the
72/// non-product entities (cartesian points, directions, index lists, …) that make
73/// up the bulk of a STEP file. Peak working set is bounded by the entity index
74/// plus the property side-map (both O(products)), so a model with tens of millions
75/// of entities extracts in a few GB instead of exhausting memory. Output is the
76/// caller's responsibility to stream onwards (e.g. to S3/Parquet) and drop.
77pub fn stream_export_model(content: &[u8], f: impl FnMut(EntityRow)) -> UnitScales {
78    // Parallel on native (byte-identical to `build_entity_index`), serial on wasm.
79    let entity_index = Arc::new(crate::build_entity_index_parallel(content));
80    stream_export_model_with_index(content, &entity_index, f)
81}
82
83/// Like [`stream_export_model`] but reuses a pre-built entity index. A caller also
84/// running the geometry pass ([`crate::try_export_glb_with_stats_with_index`]) over the
85/// same bytes builds the index once with [`build_entity_index`] and shares it across
86/// both, skipping the duplicate scan. `entity_index` MUST be built from the same
87/// `content`; output is identical to `stream_export_model`.
88/// Returns the model's [`UnitScales`], so a caller consuming attribute values can
89/// interpret them without a second pass over the file: the scales are resolved
90/// from the decoder this function already builds.
91pub fn stream_export_model_with_index(
92    content: &[u8],
93    entity_index: &Arc<EntityIndex>,
94    mut f: impl FnMut(EntityRow),
95) -> UnitScales {
96    stream_export_model_with_options(content, entity_index, &ModelOptions::default(), |row, _| {
97        f(row)
98    })
99}
100
101fn stream_rows(
102    content: &[u8],
103    entity_index: &Arc<EntityIndex>,
104    opts: &ModelOptions,
105    capture_kinds: bool,
106    mut f: impl FnMut(EntityRow, Inherited, Option<&DecodedEntity>, &[Vec<PropertyKind>]),
107) -> UnitScales {
108    // Attribute positions are schema-specific. Unlike STEP re-export, where
109    // IFC4 is an established fallback for a missing declaration, attribute
110    // export must fail closed rather than assign IFC4 names to unknown slots.
111    let source_schema = attribute_schema(content);
112    // Property resolution memoizes the shared `IfcPropertySet`/leaf entities for
113    // speed. Cap that cache so it can't grow without bound across millions of
114    // products; clearing only forces a re-decode of a shared set, never affects
115    // correctness.
116    const PSET_CACHE_CAP: usize = 1 << 18; // 262_144 entries
117
118    let mut decoder = EntityDecoder::with_arc_index(content, entity_index.clone());
119    let mut props = new_property_decoder(content.len());
120    // Pass 1 — one scan that collects, uncached (each entity visited once here):
121    //   • object → attached property/quantity definitions (IfcRelDefinesByProperties),
122    //   • the #957/#1518 type-product orphan-geometry bookkeeping, mirroring the
123    //     geometry pass exactly so both agree on which IfcTypeProducts are meshed.
124    // IfcRelDefinesByProperties: [GlobalId, OwnerHistory, Name, Description,
125    //                             RelatedObjects(4, list), RelatingPropertyDefinition(5, ref or set)]
126    let mut defs_by_object: HashMap<u32, Vec<u32>> = HashMap::new();
127    // The file's single IFCPROJECT, for the unit resolution below. First wins:
128    // the schema allows exactly one, and a malformed file with two would
129    // otherwise make which units apply depend on scan order.
130    let mut project_id: Option<u32> = None;
131    // #957 "Route B": an IfcTypeProduct that carries its own RepresentationMaps
132    // renders directly under the type's expressId when NO occurrence draws it. The
133    // geometry pass (processor::process_geometry) decides this with three sets —
134    // reproduce them here so a type-product row is emitted for exactly the meshed
135    // set (#1518), reusing the CANONICAL `plan_type_geometry` gate for the decision.
136    let mut referenced_representation_maps: FxHashSet<u32> = FxHashSet::default();
137    let mut instantiated_type_ids: FxHashSet<u32> = FxHashSet::default();
138    let mut type_product_candidates: Vec<TypeProductCandidate> = Vec::new();
139    // Occurrence → its `IfcTypeObject`, from `IfcRelDefinesByType.RelatedObjects`.
140    // Populated only when `opts.inherit_type_properties` asks for it.
141    let mut type_by_object = TypeAssignments::new();
142    // Type id → its resolved sets, so one IfcWallType typing 5000 walls is
143    // decoded once. Bounded by the file's distinct types, which is orders of
144    // magnitude below its occurrences.
145    let mut type_pset_cache = TypeSetCache::new();
146    {
147        let mut scanner = EntityScanner::new(content);
148        while let Some((id, type_name, start, end)) = scanner.next_entity() {
149            if keyword_eq(type_name, "IFCRELDEFINESBYPROPERTIES") {
150                let rel = match decoder.decode_at_uncached(start, end) {
151                    Ok(e) => e,
152                    Err(_) => continue,
153                };
154                // A single definition or an IfcPropertySetDefinitionSet, bare
155                // or typed (#7681): `get_refs` reads every spelling.
156                let Some(def_ids) = rel.ref_list_at(slot::IfcRelDefinesByProperties::RELATING_PROPERTY_DEFINITION) else { continue };
157                if let Some(objs) = rel.attr(slot::IfcRelDefinesByProperties::RELATED_OBJECTS).and_then(|a| a.as_list()) {
158                    for o in objs {
159                        if let Some(oid) = o.as_entity_ref() {
160                            defs_by_object.entry(oid).or_default().extend_from_slice(&def_ids);
161                        }
162                    }
163                }
164            } else if keyword_eq(type_name, "IFCMAPPEDITEM") {
165                // IfcMappedItem.MappingSource (attr 0) → the RepresentationMap an
166                // occurrence instances; such maps draw through the occurrence, so
167                // they are NOT orphan type geometry.
168                if let Ok(mi) = decoder.decode_at_uncached(start, end) {
169                    if let Some(src) = mi.ref_at(slot::IfcMappedItem::MAPPING_SOURCE) {
170                        referenced_representation_maps.insert(src);
171                    }
172                }
173            } else if keyword_eq(type_name, "IFCRELDEFINESBYTYPE") {
174                // IfcRelDefinesByType.RelatingType (attr 5) → a type WITH occurrences;
175                // its geometry is drawn by those occurrences, never as orphan type
176                // geometry (the AC20/ArchiCAD duplicate-boxes guard).
177                //
178                // RelatedObjects (attr 4) is read only when property inheritance
179                // is on: it is the occurrence → type edge that makes a type's
180                // HasPropertySets reachable from the occurrence, and building the
181                // map costs an allocation per typed occurrence that the geometry
182                // bookkeeping above has no use for.
183                if let Ok(rel) = decoder.decode_at_uncached(start, end) {
184                    if let Some(tid) = rel.ref_at(slot::IfcRelDefinesByType::RELATING_TYPE) {
185                        instantiated_type_ids.insert(tid);
186                        if opts.inherit_type_properties {
187                            if let Some(objs) = rel.attr(slot::IfcRelDefinesByType::RELATED_OBJECTS).and_then(|a| a.as_list()) {
188                                for o in objs {
189                                    if let Some(oid) = o.as_entity_ref() {
190                                        // FIRST relationship wins, conflicts recorded (D42).
191                                        type_by_object.record(oid, tid);
192                                    }
193                                }
194                            }
195                        }
196                    }
197                }
198            } else if keyword_eq(type_name, "IFCPROJECT") {
199                project_id = project_id.or(Some(id));
200            } else {
201                // An IfcTypeProduct subtype carrying RepresentationMaps (attr 6).
202                // `type_product_ifc_type` keeps its own cheap suffix pre-filter, so
203                // the non-type majority still pays only that.
204                //
205                // Asked once, in the branch body rather than in its condition: a
206                // condition cannot bind, so testing `.is_some()` there forced a
207                // second identical call to get the value. Shares `type_product_ifc_type` with the
208                // processor's type-geometry gate, so this pass cannot admit a
209                // different set than the one that gets meshed (#1518, #3187).
210                let Some(type_ty) = ifc_lite_core::type_product_ifc_type(type_name) else {
211                    continue;
212                };
213                let t = match decoder.decode_at_uncached(start, end) {
214                    Ok(e) => e,
215                    Err(_) => continue,
216                };
217                let rep_map_ids = crate::discovery::record_refs_at(
218                    &content[start..end],
219                    slot::IfcTypeProduct::REPRESENTATION_MAPS.index(),
220                );
221                if rep_map_ids.is_empty() {
222                    continue;
223                }
224                type_product_candidates.push(TypeProductCandidate {
225                    express_id: id,
226                    ifc_type: type_ty,
227                    type_name: type_name.to_string(),
228                    global_id: opt_string(t.attr(slot::IfcTypeProduct::GLOBAL_ID)),
229                    name: opt_string(t.attr(slot::IfcTypeProduct::NAME)),
230                    description: opt_string(t.attr(slot::IfcTypeProduct::DESCRIPTION)),
231                    rep_map_ids,
232                    pset_def_ids: ref_list(t.attr(slot::IfcTypeProduct::HAS_PROPERTY_SETS)),
233                });
234            }
235        }
236    }
237
238    // Units, resolved from the `IFCPROJECT` pass 1 just walked past. The
239    // resolver falls back to a SIMD substring search for that entity when it is
240    // not told which one it is; handing it the id makes this an O(1) decode
241    // against the index this function already holds, and pass 1 visits every
242    // entity anyway, so recording it costs nothing.
243    //
244    // Resolved here rather than left to the caller because a consumer of the
245    // rows needs it to interpret them — attribute values are in the file's own
246    // units, unlike the geometry exporters' output — and returning it means
247    // they cannot forget to ask.
248    let units = resolve_unit_scales(content, project_id, &mut decoder);
249
250    // Not drained: meshes nothing. Pinned by rust/geometry/tests/issue_3821_auxiliary_routers_mesh_nothing.rs.
251    // Built with the file's scale, NOT `GeometryRouter::new()`: `new` defaults
252    // `unit_scale` to 1.0 and `scale_transform` only scales when it was given
253    // the real one, so the difference is silently-millimetre translations.
254    // Constructed only when asked — it registers its processor table.
255    let router = opts
256        .placements
257        .then(|| GeometryRouter::with_scale(units.length_unit_scale));
258
259    // Pass 2 — emit a row per IfcProduct occurrence, resolving its property/quantity sets.
260    let mut scanner = EntityScanner::new(content);
261    while let Some((id, type_name, start, end)) = scanner.next_entity() {
262        // Filter on the STEP keyword before decoding, skipping non-product geometry primitives. The three exporter-only stratum
263        // spellings are explicit product compatibility aliases: they keep their
264        // owned exact keyword rather than being relabelled as a nearby EXPRESS
265        // entity, while still receiving the row their geometry needs.
266        let ty = ifc_lite_core::ifc_type_from_keyword(type_name);
267        if !ty.is_subtype_of(IfcType::IfcProduct)
268            && !EXPORTER_STRATUM_ALIASES
269                .iter()
270                .any(|alias| keyword_eq(type_name, alias))
271        {
272            continue;
273        }
274        let entity = match decoder.decode_at_uncached(start, end) {
275            Ok(e) => e,
276            Err(_) => continue,
277        };
278        // PascalCase canonical name (IfcWall), not the STEP keyword (IFCWALL).
279        // An owned unknown compatibility alias intentionally retains its exact
280        // upper-case STEP spelling, matching the geometry label.
281        let ifc_type = ty.name().to_string();
282        let global_id = opt_string(entity.attr(slot::IfcProduct::GLOBAL_ID));
283        let name = opt_string(entity.attr(slot::IfcProduct::NAME));
284        let description = opt_string(entity.attr(slot::IfcProduct::DESCRIPTION));
285        let object_type = opt_string(entity.attr(slot::IfcProduct::OBJECT_TYPE));
286        let has_geometry = entity.attr(slot::IfcProduct::REPRESENTATION).is_some_and(|a| !a.is_null());
287
288        // `None` is decided from attribute 5, not from the resolver's `Result`:
289        // the resolver answers `Ok(identity)` for an absent placement as well as
290        // for a broken one, so asking it would report every unplaced product as
291        // sitting at the origin.
292        let placement = router.as_ref().and_then(|r| {
293            entity.attr(slot::IfcProduct::OBJECT_PLACEMENT).filter(|a| !matches!(a, AttributeValue::Null | AttributeValue::Derived))?;
294            r.resolve_scaled_placement(&entity, &mut decoder)
295                .ok()
296                .map(|matrix| Placement { matrix })
297        });
298
299        // One pass over the object's definitions: `(#20,#20)`, or two
300        // relationships naming one set, must not export that set twice.
301        let mut def_ids = defs_by_object.get(&id).cloned().unwrap_or_default();
302        if def_ids.len() > 1 {
303            let mut seen = FxHashSet::default();
304            def_ids.retain(|d| seen.insert(*d));
305        }
306        let mut kinds = Vec::new();
307        let (mut property_sets, mut quantity_sets) = resolve_pset_defs_with_kinds(
308            &mut props, &mut decoder, &def_ids, capture_kinds.then_some(&mut kinds),
309        );
310
311        let mut inherited = Inherited::default();
312        if opts.inherit_type_properties {
313            if let Some(type_id) = type_by_object.type_of(id) {
314                (property_sets, quantity_sets, inherited) = inherit_from_type(
315                    &mut type_pset_cache,
316                    type_id,
317                    &mut props,
318                    &mut decoder,
319                    &defs_by_object,
320                    property_sets,
321                    quantity_sets,
322                );
323            }
324        }
325
326        f(
327            EntityRow {
328                express_id: id,
329                ifc_type,
330                global_id,
331                name,
332                description,
333                object_type,
334                has_geometry,
335                placement,
336                property_sets,
337                quantity_sets,
338                attributes: if opts.attributes {
339                    render_attributes(&entity, type_name, source_schema.as_deref())
340                } else {
341                    Vec::new()
342                },
343            },
344            inherited, Some(&entity), &kinds,
345        );
346
347        // Bound decoded-entity retention without invalidating placement memoization.
348        if decoder.cache_size() > PSET_CACHE_CAP {
349            decoder.clear_entity_cache();
350        }
351    }
352
353    // Pass 3 — emit a row for each IfcTypeProduct whose ORPHAN RepresentationMaps
354    // the geometry pass meshes (#957 class 1) under the type's own expressId. Ties
355    // the exact same canonical gate (`plan_type_geometry`, SuppressInstanced — the
356    // export/native profile) the processor uses, so the geometry and attribute
357    // passes agree on the meshed set: no more type-product GLB nodes without an
358    // EntityRow (#1518). Emitted after all product rows, matching the geometry
359    // pass appending its type-geometry jobs after the product jobs. On a normal
360    // model (no orphan type geometry) `type_product_candidates` is empty, so this
361    // is a no-op and output is byte-identical to before.
362    for cand in &type_product_candidates {
363        let meshed = !plan_type_geometry(
364            &cand.rep_map_ids,
365            &referenced_representation_maps,
366            instantiated_type_ids.contains(&cand.express_id),
367            TypeGeometryMode::SuppressInstanced,
368        )
369        .is_empty();
370        if !meshed {
371            continue;
372        }
373
374        // The type's own HasPropertySets. Sets attached to it by
375        // IfcRelDefinesByProperties are read only for inheritance.
376        let mut kinds = Vec::new();
377        let (property_sets, quantity_sets) = resolve_pset_defs_with_kinds(
378            &mut props, &mut decoder, &cand.pset_def_ids, capture_kinds.then_some(&mut kinds),
379        );
380
381        f(
382            EntityRow {
383                express_id: cand.express_id,
384                // PascalCase canonical name (IfcBoilerType) — equals the node's
385                // `ifcType` extra the geometry pass emits.
386                ifc_type: cand.ifc_type.name().to_string(),
387                global_id: cand.global_id.clone(),
388                name: cand.name.clone(),
389                description: cand.description.clone(),
390                // IfcTypeObject attr 4 is ApplicableOccurrence, not ObjectType.
391                object_type: None,
392                has_geometry: true,
393                placement: None,
394                property_sets,
395                quantity_sets,
396                // Pass 3 has no type handle, so honouring the attributes option
397                // costs one decode per rare orphan-geometry type.
398                attributes: if opts.attributes {
399                    decoder
400                        .decode_by_id(cand.express_id)
401                        .ok()
402                        .map(|t| render_attributes(&t, &cand.type_name, source_schema.as_deref()))
403                        .unwrap_or_default()
404                } else {
405                    Vec::new()
406                },
407            },
408            Inherited::default(), None, &kinds,
409        );
410        if decoder.cache_size() > PSET_CACHE_CAP {
411            decoder.clear_entity_cache();
412        }
413    }
414
415    units
416}