Skip to main content

ifc_lite_processing/types/
mesh.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//! Mesh data types for serialization.
6
7use ifc_lite_geometry::InstanceMeta;
8use serde::{Deserialize, Serialize};
9use std::collections::BTreeMap;
10
11/// A surface texture attached to a mesh (issues #961, #1781). Exactly one of
12/// `rgba` / `url` is set:
13/// - `rgba`: decoded in Rust (`IfcBlobTexture` PNG / `IfcPixelTexture` raw);
14///   the browser only uploads it to a GPU texture — no image logic in TS.
15/// - `url`: an `IfcImageTexture` reference (#1781) the HOST layer resolves —
16///   typically a sibling image file inside the `.ifcZIP` container. Real files
17///   share one multi-megapixel image across dozens of face sets, so the
18///   pipeline ships the reference, never per-mesh pixels.
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct MeshTextureData {
21    /// Express id of the source `IfcSurfaceTexture` — the stable dedup key:
22    /// every mesh sampling the same image carries the same id, so consumers
23    /// create ONE GPU texture per id, not one per mesh. 0 in legacy payloads.
24    #[serde(default)]
25    pub texture_id: u32,
26    /// `width * height * 4` bytes, row-major, top-down, straight alpha.
27    /// `Arc`-shared across meshes; `None` for an external image reference.
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub rgba: Option<std::sync::Arc<Vec<u8>>>,
30    #[serde(default)]
31    pub width: u32,
32    #[serde(default)]
33    pub height: u32,
34    /// `IfcImageTexture.URLReference` verbatim (#1781); `None` for decoded.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub url: Option<String>,
37    /// Sampler wrap from `IfcSurfaceTexture.RepeatS/RepeatT`.
38    pub repeat_s: bool,
39    pub repeat_t: bool,
40}
41
42impl MeshTextureData {
43    /// Build from the geometry crate's per-face-set attachment.
44    pub fn from_attachment(att: &ifc_lite_geometry::TextureAttachment) -> Self {
45        match &att.source {
46            ifc_lite_geometry::TextureSource::Decoded(tex) => Self {
47                texture_id: att.texture_id,
48                rgba: Some(tex.rgba.clone()),
49                width: tex.width,
50                height: tex.height,
51                url: None,
52                repeat_s: tex.repeat_s,
53                repeat_t: tex.repeat_t,
54            },
55            ifc_lite_geometry::TextureSource::Image(img) => Self {
56                texture_id: att.texture_id,
57                rgba: None,
58                width: 0,
59                height: 0,
60                url: Some(img.url.clone()),
61                repeat_s: img.repeat_s,
62                repeat_t: img.repeat_t,
63            },
64        }
65    }
66}
67
68/// Individual mesh data with geometry and metadata.
69#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct MeshData {
71    /// Express ID of the IFC element.
72    pub express_id: u32,
73    /// IFC type name (e.g., "IfcWall").
74    pub ifc_type: String,
75    /// IFC GlobalId (Root attribute #0) when available.
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub global_id: Option<String>,
78    /// IFC Name (Root/Object attribute #2) when available.
79    #[serde(skip_serializing_if = "Option::is_none")]
80    pub name: Option<String>,
81    /// IFC presentation layer assignment name when available.
82    #[serde(skip_serializing_if = "Option::is_none")]
83    pub presentation_layer: Option<String>,
84    /// Vertex positions (x, y, z triplets).
85    pub positions: Vec<f32>,
86    /// Vertex normals (x, y, z triplets).
87    pub normals: Vec<f32>,
88    /// Triangle indices.
89    pub indices: Vec<u32>,
90    /// RGBA color [r, g, b, a] in 0-1 range.
91    pub color: [f32; 4],
92    /// Optional material/style name resolved from per-item IFC styling.
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub material_name: Option<String>,
95    /// Optional source geometry item id for submesh outputs.
96    #[serde(skip_serializing_if = "Option::is_none")]
97    pub geometry_item_id: Option<u32>,
98    /// Optional IFC property set values keyed by IFC property names.
99    /// Primarily attached for IfcSpace/IfcZone so downstream tools can build room attribute UIs.
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub properties: Option<BTreeMap<String, String>>,
102    /// Per-vertex texture coordinates (u, v pairs, 1:1 with `positions`),
103    /// present only for textured meshes (issue #961).
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub uvs: Option<Vec<f32>>,
106    /// Decoded surface texture, present only for textured meshes (#961).
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub texture: Option<MeshTextureData>,
109    /// Provenance of the geometry for the viewer's Model/Types switch (#957):
110    /// 0 = ordinary occurrence, 1 = orphan type-product RepresentationMap (no
111    /// occurrence instantiates it), 2 = instanced type-product map (the type
112    /// library shape; its occurrences already draw the real geometry).
113    /// Serde-default so existing JSON payloads and disk caches stay readable;
114    /// skipped when 0 so ordinary meshes serialize byte-identically.
115    #[serde(default, skip_serializing_if = "geometry_class_is_occurrence")]
116    pub geometry_class: u8,
117    /// Per-mesh local origin (world/RTC frame, f64). `positions` are stored
118    /// RELATIVE to this — the world position of a vertex is `origin + position` —
119    /// so building/georef-scale placement never collapses adjacent vertices to
120    /// bit-identical f32. The renderer applies it as a per-mesh translation
121    /// (camera-relative). `[0, 0, 0]` ⇒ positions are absolute (legacy/local).
122    /// Serde-default + skip-when-zero so existing payloads/caches stay readable
123    /// and local meshes serialize byte-identically.
124    #[serde(default, skip_serializing_if = "origin_is_zero")]
125    pub origin: [f64; 3],
126    /// GPU-instancing metadata (rep-identity + per-occurrence world transform),
127    /// attached only when `IFC_LITE_INSTANCING` is on and the element is a clean
128    /// single-item mapped instance. Purely in-memory for the native streaming
129    /// path — `#[serde(skip)]` because instancing is recomputed fresh each load
130    /// and never round-trips through the JSON/disk cache.
131    #[serde(skip)]
132    pub instance: Option<InstanceMeta>,
133    /// Local (pre-placement, object-space) AABB (issue #1474) — see
134    /// `ifc_lite_geometry::Mesh::local_bounds`. Purely in-memory, like
135    /// `instance` — `#[serde(skip)]`, recomputed fresh each load.
136    #[serde(skip)]
137    pub local_bounds: Option<[f32; 6]>,
138    /// The resolved `IfcLocalPlacement` chain applied to this mesh (issue
139    /// #1474), row-major — see `ifc_lite_geometry::Mesh::local_to_world`.
140    /// Purely in-memory, like `instance` — `#[serde(skip)]`.
141    #[serde(skip)]
142    pub local_to_world: Option<[f64; 16]>,
143}
144
145fn geometry_class_is_occurrence(class: &u8) -> bool {
146    *class == 0
147}
148
149fn origin_is_zero(origin: &[f64; 3]) -> bool {
150    origin[0] == 0.0 && origin[1] == 0.0 && origin[2] == 0.0
151}
152
153impl MeshData {
154    /// Create a new MeshData from geometry components.
155    pub fn new(
156        express_id: u32,
157        ifc_type: String,
158        positions: Vec<f32>,
159        normals: Vec<f32>,
160        indices: Vec<u32>,
161        color: [f32; 4],
162    ) -> Self {
163        Self {
164            express_id,
165            ifc_type,
166            global_id: None,
167            name: None,
168            presentation_layer: None,
169            positions,
170            normals,
171            indices,
172            color,
173            material_name: None,
174            geometry_item_id: None,
175            properties: None,
176            uvs: None,
177            texture: None,
178            geometry_class: 0,
179            origin: [0.0; 3],
180            instance: None,
181            local_bounds: None,
182            local_to_world: None,
183        }
184    }
185
186    /// Attach GPU-instancing metadata (see the `instance` field).
187    pub fn with_instance(mut self, instance: Option<InstanceMeta>) -> Self {
188        self.instance = instance;
189        self
190    }
191
192    /// Set the local (pre-placement, object-space) AABB (see `local_bounds`).
193    pub fn with_local_bounds(mut self, local_bounds: Option<[f32; 6]>) -> Self {
194        self.local_bounds = local_bounds;
195        self
196    }
197
198    /// Set the resolved placement transform (see `local_to_world`).
199    pub fn with_local_to_world(mut self, local_to_world: Option<[f64; 16]>) -> Self {
200        self.local_to_world = local_to_world;
201        self
202    }
203
204    /// Tag the geometry's provenance for the Model/Types view switch (#957).
205    pub fn with_geometry_class(mut self, geometry_class: u8) -> Self {
206        self.geometry_class = geometry_class;
207        self
208    }
209
210    /// Set the per-mesh local origin (positions are relative to it).
211    pub fn with_origin(mut self, origin: [f64; 3]) -> Self {
212        self.origin = origin;
213        self
214    }
215
216    /// Set element-level IFC metadata.
217    pub fn with_element_metadata(
218        mut self,
219        global_id: Option<String>,
220        name: Option<String>,
221        presentation_layer: Option<String>,
222    ) -> Self {
223        self.global_id = global_id;
224        self.name = name;
225        self.presentation_layer = presentation_layer;
226        self
227    }
228
229    /// Set material name and source geometry item id metadata.
230    pub fn with_style_metadata(
231        mut self,
232        material_name: Option<String>,
233        geometry_item_id: Option<u32>,
234    ) -> Self {
235        self.material_name = material_name;
236        self.geometry_item_id = geometry_item_id;
237        self
238    }
239
240    /// Attach optional IFC property set values.
241    pub fn with_properties(mut self, properties: Option<BTreeMap<String, String>>) -> Self {
242        self.properties = properties;
243        self
244    }
245
246    /// Get the number of vertices.
247    pub fn vertex_count(&self) -> usize {
248        self.positions.len() / 3
249    }
250
251    /// Get the number of triangles.
252    pub fn triangle_count(&self) -> usize {
253        self.indices.len() / 3
254    }
255
256    /// Check if the mesh is empty.
257    pub fn is_empty(&self) -> bool {
258        self.positions.is_empty() || self.indices.is_empty()
259    }
260}
261
262/// #1623 Phase 2 "don't-bake": a non-template occurrence of a shared
263/// `IfcRepresentationMap` that skipped the per-occurrence vertex materialize. The
264/// router emits an instance-only placeholder (empty geometry carrying
265/// `InstanceMeta`); [`crate::element::emit_sub_meshes`] turns it into one of these,
266/// and the streaming finalize resolves it against the template MeshData into an
267/// [`InstanceRecord`]. Purely in-memory (recomputed each load), never serialized.
268#[derive(Debug, Clone)]
269pub struct RawInstanceOccurrence {
270    /// This occurrence's IFC element id.
271    pub express_id: u32,
272    /// IFC type name (e.g. "IfcFlowFitting").
273    pub ifc_type: String,
274    /// IFC GlobalId when available.
275    pub global_id: Option<String>,
276    /// IFC Name when available.
277    pub name: Option<String>,
278    /// IFC presentation layer assignment name when available.
279    pub presentation_layer: Option<String>,
280    /// This occurrence's resolved RGBA colour.
281    pub color: [f32; 4],
282    /// Shared-template key = the `IfcRepresentationMap` express id. Matches the
283    /// template MeshData's `instance.rep_identity`.
284    pub rep_identity: u128,
285    /// PRE-RTC composed world transform (row-major) `transform · local · canonical`
286    /// — the same composition `collate_refs` computes for a baked occurrence, but
287    /// captured WITHOUT materializing vertices. The finalize reduces it to the
288    /// post-RTC frame and derives the template-relative `InstanceRecord.transform`.
289    pub world_transform: [f64; 16],
290}
291
292/// #1623 Phase 2: one resolved occurrence of a shared template geometry, emitted in
293/// [`crate::ProcessingResult::instances`] instead of a full materialized mesh when
294/// `StreamingOptions.enable_instancing` is set. The consumer uploads the template
295/// MeshData (`template_express_id`, still in `meshes`) once and draws this occurrence
296/// by applying `transform` to the template's baked world geometry. Purely in-memory,
297/// like [`MeshData::instance`] — recomputed fresh each load, never round-trips a cache.
298#[derive(Debug, Clone)]
299pub struct InstanceRecord {
300    /// This occurrence's IFC element id.
301    pub express_id: u32,
302    /// IFC type name (e.g. "IfcFlowFitting").
303    pub ifc_type: String,
304    /// IFC GlobalId when available.
305    pub global_id: Option<String>,
306    /// IFC Name when available.
307    pub name: Option<String>,
308    /// IFC presentation layer assignment name when available.
309    pub presentation_layer: Option<String>,
310    /// This occurrence's RGBA colour (may differ from the template occurrence's).
311    pub color: [f32; 4],
312    /// `express_id` of the template `MeshData` this occurrence instantiates — the
313    /// consumer's link from record to the geometry it draws (JS-safe u32).
314    pub template_express_id: u32,
315    /// Representation-identity of the shared geometry (`IfcRepresentationMap` id).
316    pub rep_identity: u128,
317    /// Row-major, TEMPLATE-RELATIVE mat4: applied to the template's baked world
318    /// geometry (`template.origin + positions`) it yields this occurrence's world
319    /// geometry (`rel_k = post_rtc(M_k) · post_rtc(M_ref)⁻¹`).
320    pub transform: [f32; 16],
321}