ifc_lite_processing/data_model/
mod.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//! Data model extraction service - extracts properties, relationships, and spatial hierarchy.
6
7mod classifications;
8mod documents;
9mod jobs;
10mod materials;
11mod material_units;
12mod material_usages;
13mod metadata;
14pub mod property;
15pub mod quantity;
16pub mod render;
17pub mod rows;
18pub mod spatial_walk;
19pub mod type_assignments;
20mod inherit;
21mod properties;
22mod property_value;
23mod quantities;
24mod relationships;
25mod rooted;
26mod scan;
27mod slots;
28mod spatial;
29mod types;
30
31pub use rooted::DataModelEntities;
32pub use spatial::extract_elevation_if_storey;
33pub use types::*;
34
35use classifications::extract_classifications;
36use documents::extract_documents;
37use ifc_lite_core::{build_entity_index, DecodedEntity, EntityDecoder, EntityIndex};
38use jobs::JobBuckets;
39use materials::extract_materials;
40use material_units::MaterialUnitContext;
41use metadata::extract_entity_metadata;
42use properties::extract_properties;
43use quantities::extract_quantities;
44use relationships::extract_relationships;
45use scan::scan_entity_jobs;
46use spatial::build_spatial_hierarchy;
47use std::sync::Arc;
48
49/// Which rows and which optional tables an extraction builds.
50///
51/// [`Self::default`] is the behaviour every caller had before #9582: every
52/// STEP instance, properties and quantities both on.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct DataModelOptions {
55    /// Which STEP instances the entities table carries. Applied BEFORE the
56    /// metadata is built (see [`extract_data_model_with`]).
57    pub entities: DataModelEntities,
58    /// Build the property-set table. Property extraction reads every
59    /// `IfcPropertySet` in the file and owns a `String` per value; a consumer
60    /// that serves properties from somewhere else pays that for nothing.
61    pub properties: bool,
62    /// Build the quantity-set table, on the same terms as `properties`.
63    pub quantities: bool,
64}
65
66impl Default for DataModelOptions {
67    fn default() -> Self {
68        Self { entities: DataModelEntities::All, properties: true, quantities: true }
69    }
70}
71
72impl DataModelOptions {
73    /// The default tables, narrowed to `entities`. What the parse routes ask
74    /// for: they serve the whole data model, and only the entities table is
75    /// selectable over the wire.
76    pub fn for_entities(entities: DataModelEntities) -> Self {
77        Self { entities, ..Self::default() }
78    }
79}
80
81/// Extract complete data model from IFC content.
82pub fn extract_data_model<T>(content: &T) -> DataModel
83where
84    T: AsRef<[u8]> + ?Sized,
85{
86    extract_data_model_with(content, DataModelOptions::default()).model
87}
88
89/// Extract the data model, building entity metadata only for the rows
90/// `options.entities` asks for. Returns it with the number of STEP instances
91/// the scan saw ([`DataModelExtraction`]).
92///
93/// [`DataModelEntities::Rooted`] narrows the table to exactly what
94/// [`DataModelEntities::apply`] leaves, but it does so BEFORE the metadata is
95/// built rather than after. Over `various/O-S1-BWK-BIM architectural` that is
96/// 211,716 rows built instead of 4,411,807 -- six owned `String`s each. The
97/// result fits either way; the peak is what a caller with a memory ceiling
98/// cannot afford (#9582).
99///
100/// The output matches `extract_data_model` followed by `apply` table for
101/// table, which `rooted_tests.rs` asserts directly on real models. That holds
102/// only while every other table is built first; see [`rooted::metadata_jobs`]
103/// for the ordering condition and the proof that the spatial hierarchy -- the
104/// one table the pre-filter cannot consult -- needs no special handling.
105///
106/// `DataModelEntities::All` is the default path and is untouched by this: it
107/// borrows the full job list rather than copying it, and its metadata pass
108/// still runs in the same `rayon::join` beside the other extractors.
109pub fn extract_data_model_with<T>(content: &T, options: DataModelOptions) -> DataModelExtraction
110where
111    T: AsRef<[u8]> + ?Sized,
112{
113    let content = content.as_ref();
114    let extract_start = std::time::Instant::now();
115    tracing::info!(
116        content_size = content.len(),
117        "Starting data model extraction"
118    );
119
120    // Build entity index (shared across all extractors)
121    let entity_index = Arc::new(build_entity_index(content));
122
123    let all_entities = scan_entity_jobs(content);
124    let total_entities = all_entities.len();
125
126    // Which jobs need metadata is known up front for `All` and only after the
127    // other tables exist for every narrowing variant. So `All` keeps the join
128    // it has always had -- metadata beside properties, quantities and
129    // relationships -- and only a narrowed extraction defers the pass.
130    let prefilter = options.entities != DataModelEntities::All;
131
132    // Parallel extraction using rayon::join. Every extractor borrows the
133    // content: `rayon::join` scopes the borrow, so the copy of the whole
134    // upload this used to make (up to `MAX_FILE_SIZE_MB`, on top of the parse
135    // running beside it) bought nothing (#7676, SERVER-11).
136    let buckets = JobBuckets::new(&all_entities);
137    let (entities, ((property_sets, quantity_sets), relationships)) = rayon::join(
138        || {
139            if prefilter {
140                None
141            } else {
142                Some(extract_entity_metadata(&all_entities, content, &entity_index))
143            }
144        },
145        || {
146            rayon::join(
147                || {
148                    rayon::join(
149                        || {
150                            if options.properties {
151                                extract_properties(&buckets.property_sets, content, &entity_index)
152                            } else {
153                                Vec::new()
154                            }
155                        },
156                        || {
157                            if options.quantities {
158                                extract_quantities(&buckets.quantity_sets, content, &entity_index)
159                            } else {
160                                Vec::new()
161                            }
162                        },
163                    )
164                },
165                || extract_relationships(&all_entities, content, &entity_index),
166            )
167        },
168    );
169
170    // Runs BEFORE the pre-filter, not after: a `materials` row points at an
171    // `IfcMaterial` by `definition_id` / `material_id`, rows that carry no
172    // GlobalId and that nothing else references. See `rooted::metadata_jobs`.
173    let Associations {
174        length_unit_scale,
175        classifications,
176        materials,
177        documents,
178        refused,
179    } = extract_associations(content, &entity_index, &buckets, &relationships);
180
181    let entities = entities.unwrap_or_else(|| {
182        let jobs = rooted::metadata_jobs(
183            options.entities,
184            &all_entities,
185            rooted::TableRefs {
186                property_sets: &property_sets,
187                quantity_sets: &quantity_sets,
188                relationships: &relationships,
189                classifications: &classifications,
190                materials: &materials,
191                documents: &documents,
192            },
193        );
194        extract_entity_metadata(&jobs, content, &entity_index)
195    });
196
197    // Build spatial hierarchy (depends on relationships and entities)
198    let spatial_hierarchy = build_spatial_hierarchy(
199        &relationships,
200        &entities,
201        content,
202        &entity_index,
203        length_unit_scale,
204    );
205
206    let extract_time = extract_start.elapsed();
207    tracing::info!(
208        entities = entities.len(),
209        total_entities = total_entities,
210        property_sets = property_sets.len(),
211        quantity_sets = quantity_sets.len(),
212        relationships = relationships.len(),
213        classifications = classifications.len(),
214        materials = materials.len(),
215        documents = documents.len(),
216        spatial_nodes = spatial_hierarchy.nodes.len(),
217        extract_time_ms = extract_time.as_millis(),
218        "Data model extraction complete"
219    );
220
221    let mut model = DataModel {
222        entities,
223        property_sets,
224        quantity_sets,
225        relationships,
226        classifications,
227        materials,
228        documents,
229        spatial_hierarchy,
230        refused,
231    };
232
233    // `metadata_jobs` over-keeps unknown types (see its docs); the exact rule
234    // needs the extracted row, so it runs here -- on the narrowed table rather
235    // than on every instance in the file. A no-op for `All`.
236    options.entities.apply(&mut model);
237    DataModelExtraction { model, total_entities }
238}
239
240/// The `IfcRelAssociates*` tables, with the length-unit scale they resolve
241/// against.
242struct Associations {
243    length_unit_scale: f64,
244    classifications: Vec<ClassificationAssociation>,
245    materials: Vec<MaterialAssociation>,
246    documents: Vec<DocumentAssociation>,
247    refused: Option<String>,
248}
249
250/// Classifications, materials and documents, which follow the same
251/// `IfcRelAssociates*` pattern as the relationship pass but resolve the
252/// referenced object (classification reference, material layer set, document)
253/// into a flat, element-keyed shape (issue #900 parity).
254fn extract_associations(
255    content: &[u8],
256    entity_index: &Arc<EntityIndex>,
257    buckets: &JobBuckets,
258    relationships: &[Relationship],
259) -> Associations {
260    // Extract length unit scale (e.g., 0.001 for millimeters) from the model's
261    // project, found by the one locator. Data path: main's value, never a
262    // refusal (#7678); the decoder is lossless.
263    let mut unit_decoder = EntityDecoder::with_arc_index(content, entity_index.clone());
264    let project_ids = ifc_lite_core::find_project_ids(content);
265    let length_unit_scale = unit_decoder.length_unit_scale();
266    tracing::debug!(
267        length_unit_scale = length_unit_scale,
268        "Extracted length unit scale"
269    );
270    // Materials need the length-unit scale to report layer thickness in metres.
271    let material_units = MaterialUnitContext::new(
272        &project_ids, relationships, &mut unit_decoder, length_unit_scale,
273    );
274
275    let ((classifications, materials), documents) = rayon::join(
276        || {
277            rayon::join(
278                || extract_classifications(&buckets.rel_classifications, content, entity_index),
279                || {
280                    extract_materials(
281                        &buckets.rel_materials,
282                        content,
283                        entity_index,
284                        &material_units,
285                    )
286                },
287            )
288        },
289        || extract_documents(&buckets.rel_documents, content, entity_index),
290    );
291
292    // A table over its budget is not served truncated: the refusal travels
293    // with the model to the one serializer every route uses (#7675).
294    let (materials, refused) = match materials {
295        Ok(rows) => (rows, None),
296        Err(reason) => (Vec::new(), Some(reason)),
297    };
298
299    Associations {
300        length_unit_scale,
301        classifications,
302        materials,
303        documents,
304        refused,
305    }
306}
307
308/// Collect the `RelatedObjects` (attribute 4) entity ids of an `IfcRelAssociates*`.
309pub(super) fn related_object_ids(rel: &DecodedEntity) -> Vec<u32> {
310    rel.get_list(4)
311        .map(|list| list.iter().filter_map(|v| v.as_entity_ref()).collect())
312        .unwrap_or_default()
313}
314
315
316#[cfg(test)]
317#[path = "tests.rs"]
318mod tests;