ifc_lite_processing/
retained_geometry.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Explicit admission of canonical processing output into a geometry document.
3//!
4//! This adapter never parses IFC, selects a kernel or re-runs geometry. It
5//! retains the entire processing result and copies positions, normals and
6//! indices into object-local mesh definitions of an
7//! [`ifc_lite_geometry::document::GeometryDocument`]. Its memory cost is
8//! opt-in; ordinary loads never construct it.
9//!
10//! Every admitted mesh is a display approximation of the processed element,
11//! never authored geometry: no source, analytic or solidity claim is made.
12//! Retained authored sources and worker requests live separately, in
13//! [`crate::retained_requests`].
14
15use crate::ProcessingResult;
16use ifc_lite_geometry::document::{
17    DefinitionHandle, DocumentError, GeometryDocument, OccurrenceHandle,
18};
19use ifc_lite_geometry::Mesh;
20use std::collections::BTreeMap;
21
22/// An admitted display mesh, linked to its untouched processing record.
23///
24/// Definitions use local coordinates. Occurrence transforms place them into
25/// [`ProcessingResult::frame`], not directly into IFC absolute world space.
26#[derive(Debug, Clone, Copy)]
27pub struct RetainedMeshRecord {
28    pub mesh_index: usize,
29    pub definition: DefinitionHandle,
30    pub occurrence: OccurrenceHandle,
31}
32
33/// One existing instance applied to one template mesh. A multi-mesh template
34/// contributes multiple records, sharing its existing mesh definitions.
35#[derive(Debug, Clone, Copy)]
36pub struct RetainedInstanceRecord {
37    pub instance_index: usize,
38    pub mesh_index: usize,
39    pub occurrence: OccurrenceHandle,
40}
41
42/// The processing record whose admission was refused.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum RetainedGeometryLocation {
45    /// Index into `ProcessingResult::meshes`.
46    Mesh(usize),
47    /// Index into `ProcessingResult::instances`.
48    Instance(usize),
49}
50
51/// Why admission was refused.
52#[derive(Debug, PartialEq, Eq)]
53#[non_exhaustive]
54pub enum RetainedGeometryErrorCause {
55    /// The document contract refused a mesh buffer or an occurrence transform.
56    Document(DocumentError),
57    /// An instance names a template element with no processed mesh.
58    MissingTemplate { template_express_id: u32 },
59}
60
61impl std::fmt::Display for RetainedGeometryErrorCause {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        match self {
64            Self::Document(error) => std::fmt::Display::fmt(error, f),
65            Self::MissingTemplate {
66                template_express_id,
67            } => write!(f, "instance template {template_express_id} has no mesh"),
68        }
69    }
70}
71
72impl std::error::Error for RetainedGeometryErrorCause {
73    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
74        match self {
75            Self::Document(error) => Some(error),
76            Self::MissingTemplate { .. } => None,
77        }
78    }
79}
80
81/// Failed admission identifies the first refused processing record and returns
82/// ownership of the untouched result; no partial document escapes.
83pub struct RetainedGeometryError {
84    pub location: RetainedGeometryLocation,
85    pub source: RetainedGeometryErrorCause,
86    processed: Box<ProcessingResult>,
87}
88
89impl RetainedGeometryError {
90    /// Recover the canonical result when execution admission is refused.
91    pub fn into_processing_result(self) -> ProcessingResult {
92        *self.processed
93    }
94}
95
96impl std::fmt::Debug for RetainedGeometryError {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        f.debug_struct("RetainedGeometryError")
99            .field("location", &self.location)
100            .field("source", &self.source)
101            .finish()
102    }
103}
104
105impl std::fmt::Display for RetainedGeometryError {
106    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107        write!(
108            f,
109            "{:?} failed retained admission: {}",
110            self.location, self.source
111        )
112    }
113}
114
115impl std::error::Error for RetainedGeometryError {
116    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
117        Some(&self.source)
118    }
119}
120
121/// A geometry document of display meshes plus the complete canonical
122/// processing result it was admitted from.
123///
124/// Owns both. Texture, appearance, source attribution, instance records and
125/// [`crate::MeshFrame`] remain authoritative in `processed()`; the document
126/// holds display approximations only, never authored geometry, and makes no
127/// claim that their source geometry is mathematically exact.
128pub struct RetainedGeometry {
129    processed: ProcessingResult,
130    document: GeometryDocument,
131    records: Vec<RetainedMeshRecord>,
132    instances: Vec<RetainedInstanceRecord>,
133}
134
135impl RetainedGeometry {
136    /// Admit an already-produced result. Runs no second load or geometry pipeline.
137    ///
138    /// Copies positions, normals and indices for execution. The original result
139    /// remains recoverable without reconstructed or dropped presentation fields.
140    /// If processing was cancelled or filtered, this retains that same partial or
141    /// filtered result: admission must not be interpreted as load completion.
142    pub fn try_from_processing(processed: ProcessingResult) -> Result<Self, RetainedGeometryError> {
143        match admit(&processed) {
144            Ok((document, records, instances)) => Ok(Self {
145                processed,
146                document,
147                records,
148                instances,
149            }),
150            Err((location, source)) => Err(RetainedGeometryError {
151                location,
152                source,
153                processed: Box::new(processed),
154            }),
155        }
156    }
157
158    /// Canonical geometry, presentation, placement, instances and diagnostics.
159    pub fn processed(&self) -> &ProcessingResult {
160        &self.processed
161    }
162
163    /// Immutable document view; nothing can replace an admitted display mesh.
164    pub fn document(&self) -> &GeometryDocument {
165        &self.document
166    }
167
168    /// One definition plus its own placed occurrence per processed mesh, in
169    /// `ProcessingResult::meshes` order.
170    pub fn records(&self) -> &[RetainedMeshRecord] {
171        &self.records
172    }
173
174    /// Additional placed occurrences for every canonical instance/template mesh
175    /// pair. Appearance and source metadata remain in `processed().instances`.
176    pub fn instances(&self) -> &[RetainedInstanceRecord] {
177        &self.instances
178    }
179
180    /// Return every original record and metadata field without a lossy conversion.
181    pub fn into_processing_result(self) -> ProcessingResult {
182        self.processed
183    }
184}
185
186type Admission = (
187    GeometryDocument,
188    Vec<RetainedMeshRecord>,
189    Vec<RetainedInstanceRecord>,
190);
191type AdmissionError = (RetainedGeometryLocation, RetainedGeometryErrorCause);
192
193fn admit(processed: &ProcessingResult) -> Result<Admission, AdmissionError> {
194    let mut document = GeometryDocument::new();
195    let mut records = Vec::with_capacity(processed.meshes.len());
196    let mut templates: BTreeMap<u32, Vec<usize>> = BTreeMap::new();
197    for (mesh_index, source) in processed.meshes.iter().enumerate() {
198        let mut mesh = Mesh::new();
199        mesh.positions = source.positions.clone();
200        mesh.normals = source.normals.clone();
201        mesh.indices = source.indices.clone();
202        let definition = document
203            .add_mesh_definition(source.geometry_item_id.unwrap_or(source.express_id), mesh)
204            .map_err(|source| {
205                (
206                    RetainedGeometryLocation::Mesh(mesh_index),
207                    RetainedGeometryErrorCause::Document(source),
208                )
209            })?;
210        let [x, y, z] = source.origin;
211        let occurrence = document
212            .add_occurrence(
213                definition,
214                source.express_id,
215                [
216                    1.0, 0.0, 0.0, x, 0.0, 1.0, 0.0, y, 0.0, 0.0, 1.0, z, 0.0, 0.0, 0.0, 1.0,
217                ],
218            )
219            .map_err(|source| {
220                (
221                    RetainedGeometryLocation::Mesh(mesh_index),
222                    RetainedGeometryErrorCause::Document(source),
223                )
224            })?;
225        records.push(RetainedMeshRecord {
226            mesh_index,
227            definition,
228            occurrence,
229        });
230        templates
231            .entry(source.express_id)
232            .or_default()
233            .push(mesh_index);
234    }
235    let instances = admit_instances(processed, &records, &templates, &mut document)?;
236    Ok((document, records, instances))
237}
238
239fn admit_instances(
240    processed: &ProcessingResult,
241    records: &[RetainedMeshRecord],
242    templates: &BTreeMap<u32, Vec<usize>>,
243    document: &mut GeometryDocument,
244) -> Result<Vec<RetainedInstanceRecord>, AdmissionError> {
245    let mut instances = Vec::with_capacity(processed.instances.len());
246    for (instance_index, source) in processed.instances.iter().enumerate() {
247        let location = RetainedGeometryLocation::Instance(instance_index);
248        let mesh_indices = templates.get(&source.template_express_id).ok_or((
249            location,
250            RetainedGeometryErrorCause::MissingTemplate {
251                template_express_id: source.template_express_id,
252            },
253        ))?;
254        for &mesh_index in mesh_indices {
255            let mut transform = source.transform.map(f64::from);
256            let origin = processed.meshes[mesh_index].origin;
257            // Row-major A * T(origin): instance transforms address the baked
258            // template frame (origin + local positions). Preserve that frame
259            // in f64 rather than dropping its origin or narrowing it again.
260            for row in 0..4 {
261                transform[row * 4 + 3] += transform[row * 4] * origin[0]
262                    + transform[row * 4 + 1] * origin[1]
263                    + transform[row * 4 + 2] * origin[2];
264            }
265            let occurrence = document
266                .add_occurrence(records[mesh_index].definition, source.express_id, transform)
267                .map_err(|error| (location, RetainedGeometryErrorCause::Document(error)))?;
268            instances.push(RetainedInstanceRecord {
269                instance_index,
270                mesh_index,
271                occurrence,
272            });
273        }
274    }
275    Ok(instances)
276}