ifc_lite_processing/
retained_requests.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Opt-in retained authored-source requests for a model.
3//!
4//! Re-reads the model's authored `IfcExtrudedAreaSolid` or `IfcSweptDiskSolid`
5//! sources with original records captured, admits each supported source into
6//! its own [`GeometryDocument`] and keeps the placed occurrences that can host
7//! it. Ordinary loads never call this; its walk and memory cost are opt-in.
8//!
9//! Strictly source-only: a request describes the raw authored solid. Openings,
10//! enclosing booleans, styles and other representation items are never
11//! applied, so a published retained display is not final product geometry.
12//! Every source or occurrence outside the supported family is listed in
13//! [`RetainedSources::refused`] with its reason, never dropped
14//! silently or replaced by a tessellated mesh.
15
16use crate::{
17    extract_extrusion_definitions, extract_swept_disk_definitions, AnalyticSourceKey,
18    ExtrusionInstance, SweptDiskDefinition,
19};
20use ifc_lite_geometry::analytic::{with_source_capture, AnalyticStatus, AnalyticSweptDisk};
21use ifc_lite_geometry::document::{
22    DefinitionHandle, GeometryDocument, OccurrenceHandle, RegionQualification, RetainedCompletion,
23    RetainedDefinitionHandle, RetainedDisplayContract, RetainedExtrusion, RetainedRefusal,
24    RetainedRequest, RetainedSweptDisk,
25};
26use nalgebra::Matrix4;
27use std::collections::{BTreeMap, HashSet};
28
29/// Orthonormality and unit-determinant budget for a composed world placement.
30/// Unit: dimensionless. Mapping operators with scale are refused, not absorbed.
31const WORLD_RIGID_EPS: f64 = 1e-9;
32
33/// Why a source or one of its occurrences is outside the retained family.
34#[derive(Debug, PartialEq, Eq)]
35#[non_exhaustive]
36pub enum RetainedSourceRefusal {
37    /// The geometry document refused the authored source itself.
38    Source(RetainedRefusal),
39    /// The solid is an operand of an enclosing boolean; publishing the raw
40    /// operand as the product's shape would be false.
41    EnclosingBooleanUnevaluated,
42    /// The analytic walk could not resolve this occurrence or its placement.
43    OccurrenceUnsupported(String),
44    /// The composed world placement is not a proper rigid motion.
45    UnqualifiedOccurrenceTransform,
46}
47
48/// A refused source (`product_id` is `None`) or a refused occurrence of it.
49#[derive(Debug)]
50pub struct RefusedSource {
51    pub key: AnalyticSourceKey,
52    pub product_id: Option<u32>,
53    pub refusal: RetainedSourceRefusal,
54}
55
56/// One admitted placement of a retained source.
57#[derive(Debug, Clone)]
58pub struct RetainedOccurrence {
59    pub product_id: u32,
60    /// Family-local ordinal from [`ExtrusionInstance::ordinal`].
61    pub ordinal: usize,
62    /// Row-major evaluation metres -> absolute IFC Z-up world metres. This is
63    /// not [`crate::ProcessingResult::frame`].
64    pub world_from_evaluation: [f64; 16],
65}
66
67/// A display mesh published from one completion, placed at every occurrence.
68#[derive(Debug)]
69pub struct PublishedRetainedDisplay {
70    pub definition: DefinitionHandle,
71    /// `(product_id, occurrence)` in [`RetainedSource::occurrences`] order.
72    pub occurrences: Vec<(u32, OccurrenceHandle)>,
73}
74
75/// One supported authored source, its own document and its admitted placements.
76#[derive(Debug)]
77pub struct RetainedSource {
78    key: AnalyticSourceKey,
79    document: GeometryDocument,
80    definition: RetainedDefinitionHandle,
81    occurrences: Vec<RetainedOccurrence>,
82}
83
84impl RetainedSource {
85    pub fn key(&self) -> &AnalyticSourceKey {
86        &self.key
87    }
88    /// Retained source, encoded request and any published display meshes.
89    pub fn document(&self) -> &GeometryDocument {
90        &self.document
91    }
92    pub fn definition(&self) -> RetainedDefinitionHandle {
93        self.definition
94    }
95    pub fn occurrences(&self) -> &[RetainedOccurrence] {
96        &self.occurrences
97    }
98
99    /// The runtime capability needed to evaluate this source.
100    pub fn qualification(&self) -> Result<RegionQualification, RetainedRefusal> {
101        Ok(self
102            .document
103            .retained_payload(self.definition)?
104            .qualification)
105    }
106
107    /// Request for the worker incarnation the caller selected (never 0).
108    pub fn prepare(&self, worker_incarnation: u64) -> Result<RetainedRequest, RetainedRefusal> {
109        self.document
110            .prepare_retained(self.definition, worker_incarnation)
111    }
112
113    /// Publishes a completion as one display definition placed at every
114    /// admitted occurrence. Atomic: a refusal changes nothing and the caller
115    /// keeps the completion. Publication makes other outstanding requests of
116    /// this source stale.
117    pub fn publish_display(
118        &mut self,
119        completion: &RetainedCompletion,
120        live_worker_incarnation: u64,
121        contract: RetainedDisplayContract,
122    ) -> Result<PublishedRetainedDisplay, RetainedRefusal> {
123        let placements: Vec<_> = self
124            .occurrences
125            .iter()
126            .map(|occurrence| (occurrence.product_id, occurrence.world_from_evaluation))
127            .collect();
128        let (definition, handles) = self.document.publish_retained_display(
129            completion,
130            live_worker_incarnation,
131            contract,
132            &placements,
133        )?;
134        let occurrences = placements
135            .iter()
136            .zip(handles)
137            .map(|(&(product_id, _), handle)| (product_id, handle))
138            .collect();
139        Ok(PublishedRetainedDisplay {
140            definition,
141            occurrences,
142        })
143    }
144}
145
146/// Every retained request source of one model, admitted or refused.
147#[derive(Debug)]
148pub struct RetainedSources {
149    pub model_sha256: String,
150    /// Raw IFC file length unit -> metres.
151    pub length_unit_scale: f64,
152    pub admitted: Vec<RetainedSource>,
153    pub refused: Vec<RefusedSource>,
154    /// Representation walk diagnostics; affected products have no sources.
155    pub diagnostics: Vec<String>,
156}
157
158impl RetainedSources {
159    /// Walk the model's authored extrusions, optionally only for the given
160    /// product STEP IDs (`Some(empty)` returns nothing). No geometry is
161    /// evaluated and nothing is tessellated.
162    pub fn extrusions(content: &[u8], ids: Option<&HashSet<u32>>) -> Self {
163        let definitions = with_source_capture(|| extract_extrusion_definitions(content, ids));
164        let mut sources = Self::new(
165            definitions.model_sha256,
166            definitions.length_unit_scale,
167            definitions.diagnostics,
168        );
169        let mut placements = by_source(definitions.instances.into_values().flatten());
170        for definition in definitions.sources {
171            let recipe = RetainedExtrusion {
172                source: definition.source,
173                length_unit_scale: sources.length_unit_scale,
174            };
175            let placements = placements.remove(&definition.key).unwrap_or_default();
176            let status = recipe.source.status.clone();
177            sources.admit(definition.key, &status, placements, |document| {
178                document.add_retained_extrusion(recipe)
179            });
180        }
181        sources
182    }
183
184    /// Walk the model's authored swept disks, as [`Self::extrusions`] does.
185    /// Only solid disks along one rational B-spline, line or partial arc are
186    /// admitted (wire format 2); every other directrix is refused by name.
187    pub fn swept_disks(content: &[u8], ids: Option<&HashSet<u32>>) -> Self {
188        let definitions = with_source_capture(|| extract_swept_disk_definitions(content, ids));
189        let mut sources = Self::new(
190            definitions.model_sha256,
191            definitions.length_unit_scale,
192            definitions.diagnostics,
193        );
194        let mut placements = by_source(definitions.instances.into_values().flatten());
195        for definition in definitions.sources {
196            let recipe = swept_disk_recipe(&definition, sources.length_unit_scale);
197            let placements = placements.remove(&definition.key).unwrap_or_default();
198            sources.admit(definition.key, &definition.status, placements, |document| {
199                document.add_retained_swept_disk(recipe)
200            });
201        }
202        sources
203    }
204
205    fn new(model_sha256: String, length_unit_scale: f64, diagnostics: Vec<String>) -> Self {
206        Self {
207            model_sha256,
208            length_unit_scale,
209            admitted: Vec::new(),
210            refused: Vec::new(),
211            diagnostics,
212        }
213    }
214
215    /// `source_status` is the source's line/arc interpretation status, which
216    /// every occurrence inherits; only occurrence-specific failures refuse one.
217    fn admit(
218        &mut self,
219        key: AnalyticSourceKey,
220        source_status: &AnalyticStatus,
221        placements: Vec<ExtrusionInstance>,
222        retain: impl FnOnce(&mut GeometryDocument) -> Result<RetainedDefinitionHandle, RetainedRefusal>,
223    ) {
224        let mut document = GeometryDocument::new();
225        let admitted = retain(&mut document).and_then(|definition| {
226            let frame = document
227                .retained_payload(definition)?
228                .source_from_evaluation;
229            Ok((definition, frame))
230        });
231        let (definition, source_from_evaluation) = match admitted {
232            Ok(admitted) => admitted,
233            Err(refusal) => {
234                self.refused.push(RefusedSource {
235                    key,
236                    product_id: None,
237                    refusal: RetainedSourceRefusal::Source(refusal),
238                });
239                return;
240            }
241        };
242        let mut occurrences = Vec::with_capacity(placements.len());
243        for placement in placements {
244            match occurrence(&placement, source_status, &source_from_evaluation) {
245                Ok(world_from_evaluation) => occurrences.push(RetainedOccurrence {
246                    product_id: placement.product_id,
247                    ordinal: placement.ordinal,
248                    world_from_evaluation,
249                }),
250                Err(refusal) => self.refused.push(RefusedSource {
251                    key: key.clone(),
252                    product_id: Some(placement.product_id),
253                    refusal,
254                }),
255            }
256        }
257        // A source with no placeable occurrence has nothing to publish; its
258        // occurrence refusals above already explain why.
259        if !occurrences.is_empty() {
260            self.admitted.push(RetainedSource {
261                key,
262                document,
263                definition,
264                occurrences,
265            });
266        }
267    }
268}
269
270/// Extrusion and swept-disk occurrences share one instance type.
271fn by_source(
272    instances: impl Iterator<Item = ExtrusionInstance>,
273) -> BTreeMap<AnalyticSourceKey, Vec<ExtrusionInstance>> {
274    let mut placements = BTreeMap::<AnalyticSourceKey, Vec<ExtrusionInstance>>::new();
275    for instance in instances {
276        placements
277            .entry(instance.source.clone())
278            .or_default()
279            .push(instance);
280    }
281    placements
282}
283
284/// The definition carries every captured field of the extracted disk.
285fn swept_disk_recipe(
286    definition: &SweptDiskDefinition,
287    length_unit_scale: f64,
288) -> RetainedSweptDisk {
289    RetainedSweptDisk {
290        solid_id: definition.key.solid_id,
291        source: AnalyticSweptDisk {
292            directrix_id: definition.directrix_id,
293            start_param: definition.start_param,
294            end_param: definition.end_param,
295            source: definition.source.clone(),
296            owned_directrix: definition.owned_directrix.clone(),
297            radius: definition.radius,
298            inner_radius: definition.inner_radius,
299            segments: definition.directrix.clone(),
300            status: definition.status.clone(),
301        },
302        length_unit_scale,
303    }
304}
305
306fn occurrence(
307    instance: &ExtrusionInstance,
308    source_status: &AnalyticStatus,
309    source_from_evaluation: &[f64; 16],
310) -> Result<[f64; 16], RetainedSourceRefusal> {
311    // A rational disk directrix has no line/arc interpretation; the request
312    // encodes its owned coefficients instead, so that inherited status is no
313    // reason to refuse the placement.
314    if let AnalyticStatus::Unsupported(reason) = &instance.status {
315        if instance.status != *source_status {
316            return Err(RetainedSourceRefusal::OccurrenceUnsupported(reason.clone()));
317        }
318    }
319    if instance.source_modified {
320        return Err(RetainedSourceRefusal::EnclosingBooleanUnevaluated);
321    }
322    let world_from_source = instance.world_from_source.ok_or_else(|| {
323        RetainedSourceRefusal::OccurrenceUnsupported("occurrence placement unavailable".into())
324    })?;
325    let world = Matrix4::from_column_slice(&world_from_source)
326        * Matrix4::from_column_slice(source_from_evaluation);
327    let orthonormal = (0..3).all(|i| {
328        (0..3).all(|j| {
329            let dot = (0..3).map(|k| world[(k, i)] * world[(k, j)]).sum::<f64>();
330            (dot - if i == j { 1.0 } else { 0.0 }).abs() < WORLD_RIGID_EPS
331        })
332    });
333    if world.iter().any(|value| !value.is_finite())
334        || !orthonormal
335        || (world.fixed_view::<3, 3>(0, 0).determinant() - 1.0).abs() > WORLD_RIGID_EPS
336        || world.fixed_view::<1, 4>(3, 0) != nalgebra::RowVector4::new(0.0, 0.0, 0.0, 1.0)
337    {
338        return Err(RetainedSourceRefusal::UnqualifiedOccurrenceTransform);
339    }
340    Ok(std::array::from_fn(|i| world[(i / 4, i % 4)]))
341}