Skip to main content

ifc_lite_processing/
element.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//! Canonical per-element mesh production — THE single decision tree that turns
6//! one IFC product (or type-product RepresentationMap) into renderable meshes.
7//!
8//! Both pipelines run this exact code:
9//! - the native orchestrator (`processor.rs`) calls [`produce_element_meshes`]
10//!   from its rayon loop with a fresh seeded decoder + router per element;
11//! - the browser batch path (`wasm-bindings` `processGeometryBatch`) calls it
12//!   per job with a warm per-batch decoder + router.
13//!
14//! History: the two pipelines used to carry diverging inline copies of this
15//! tree, and fixes had to land twice (#858, #913, #957, #961, #1071). Any
16//! change to mesh-production behaviour belongs HERE, exactly once. The only
17//! sanctioned behavioural fork is [`TypeGeometryMode`] — a product
18//! requirement, not drift: an export must never duplicate type geometry,
19//! while the interactive viewer renders it tagged for its Model/Types switch.
20//!
21//! The converged decision tree (union of the strongest behaviours of both
22//! former copies):
23//!
24//! ```text
25//! representation gate (IfcAlignment exempt)
26//! ├─ TypeProduct job (#957): render each planned RepresentationMap
27//! │    (textures #961, geometry_class tag, styled-item colour)
28//! └─ Product job:
29//!    ├─ has openings → submesh-aware void cut (per-part colours survive)
30//!    ├─ else        → submesh path for ALL types (per-item colours,
31//!    │                per-item error skipping, #858 palette split per item)
32//!    └─ fallback chain when the submesh path produced nothing:
33//!         void-aware single mesh → plain element → element-level #858 split
34//!         → single coloured mesh
35//! ```
36
37use crate::style::{FullIndexedColourMap, GeometryStyleInfo};
38use crate::types::mesh::{MeshData, MeshTextureData, RawInstanceOccurrence};
39use ifc_lite_core::{DecodedEntity, EntityDecoder, IfcType};
40use ifc_lite_geometry::{
41    calculate_normals, compose_instance_world_row_major, orient_mesh_outward_verdict, BoolFailure,
42    GeometryHasher, GeometryRouter, ResolvedTextureMap, SubMeshCollection,
43};
44use rustc_hash::{FxHashMap, FxHashSet};
45use std::collections::BTreeMap;
46
47/// The f32-collapse degenerate backstop, its per-element tally, and the reason
48/// that tally now gates the closure verdict. A CHILD module: it exists only to
49/// serve this file's produce/emit cycle.
50#[path = "element_degenerate.rs"]
51mod degenerate;
52mod element_color;
53use element_color::{find_indexed_colour_for_element, infer_opening_subpart_material_name};
54// Re-exported because these two have callers outside this module:
55// `find_geometry_item_color` from processor/color_layer.rs, and
56// `resolve_color_for_representation_map` from processor/jobs.rs.
57pub(crate) use element_color::{find_geometry_item_color, resolve_color_for_representation_map};
58
59/// Element-level metadata stamped on every produced [`MeshData`]. The native
60/// pipeline resolves these during its metadata phase; the browser passes
61/// `None` (its viewer gets metadata from the parser worker instead).
62#[derive(Debug, Clone, Default)]
63pub struct ElementMeshMetadata {
64    pub global_id: Option<String>,
65    pub name: Option<String>,
66    pub presentation_layer: Option<String>,
67    pub space_zone_properties: Option<BTreeMap<String, String>>,
68}
69
70/// What the job renders.
71#[derive(Debug, Clone)]
72pub enum ElementJobKind {
73    /// Ordinary product occurrence — walk its IfcProductDefinitionShape.
74    Product,
75    /// #957 type geometry: render these RepresentationMaps directly (baking
76    /// their MappingOrigin), each pre-tagged with its geometry_class
77    /// (1 = orphan, 2 = instanced). Produce the list with
78    /// [`plan_type_geometry`] — callers must not hand-roll the filter.
79    TypeProduct { rep_maps: Vec<(u32, u8)> },
80}
81
82/// One unit of mesh production.
83pub struct ElementMeshJob<'a> {
84    pub id: u32,
85    pub ifc_type: IfcType,
86    /// The decoded product (or type-product) entity. Callers decode it —
87    /// they own skip-set checks and decode-failure policy.
88    pub entity: &'a DecodedEntity,
89    pub kind: ElementJobKind,
90    /// Caller-resolved element fallback colour (direct style > material
91    /// chain > type default). `None` ⇒ `default_color_for_type`.
92    pub element_color: Option<[f32; 4]>,
93    pub metadata: Option<&'a ElementMeshMetadata>,
94}
95
96/// Read-only shared state for one production run. Every field is a borrow of
97/// `Sync` data, so `&MeshProductionContext` can be captured by a rayon
98/// closure (native) or used serially (wasm).
99pub struct MeshProductionContext<'a> {
100    /// Host element id → opening ids (post void-propagation / opening filter).
101    pub void_index: &'a FxHashMap<u32, Vec<u32>>,
102    /// Geometry item id → resolved style (styled-item index).
103    pub geometry_style_index: &'a FxHashMap<u32, GeometryStyleInfo>,
104    /// Geometry item id → full per-triangle palette (#858).
105    pub indexed_colour_full: &'a FxHashMap<u32, FullIndexedColourMap>,
106    /// Element id → material colour list (#407/#913 transparent/opaque
107    /// alternation). Empty map when the caller has no material chain data.
108    pub element_material_colors: &'a FxHashMap<u32, Vec<[f32; 4]>>,
109    /// Surface textures + UV maps keyed by face-set id (#961).
110    pub texture_index: &'a FxHashMap<u32, ResolvedTextureMap>,
111    /// Site-local rotation (native `site_local` coordinate space only).
112    /// `None` for the browser — its Z-up→Y-up swap happens at the FFI
113    /// boundary, after this function.
114    pub site_local_rotation: Option<&'a Vec<f64>>,
115}
116
117/// RTC-invariant per-element fingerprint configuration (#971/#924).
118#[derive(Debug, Clone, Copy)]
119pub struct GeometryHashConfig {
120    /// Quantization grid in metres.
121    pub tolerance: f64,
122    /// World-reconstruction offset added back to local positions (the batch
123    /// RTC when a shift was applied, else zeros) so the file's RTC choice
124    /// never registers as a geometry change.
125    pub world_rtc: [f64; 3],
126}
127
128#[derive(Debug, Clone, Copy, Default)]
129pub struct MeshProductionOptions {
130    /// `Some` ⇒ compute one fingerprint per element (browser diff feature).
131    /// Type-product jobs are never hashed (diffing type-library shapes is a
132    /// separate feature decision).
133    pub geometry_hash: Option<GeometryHashConfig>,
134}
135
136/// The #957 suppress-vs-tag decision — an explicit product-requirement fork,
137/// not drift. See [`plan_type_geometry`].
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub enum TypeGeometryMode {
140    /// Native/export: instanced types are suppressed entirely (an export must
141    /// never duplicate geometry); orphan maps emit with geometry_class 1.
142    SuppressInstanced,
143    /// Viewer: instanced types emit too, tagged geometry_class 2, so the
144    /// Model/Types view switch can filter at render time.
145    EmitTagged,
146}
147
148/// The single home of the #957 orphan/instanced RepresentationMap decision.
149///
150/// A map referenced by an `IfcMappedItem` always draws through its occurrence
151/// — emitting it again would double-render at the MappingOrigin (the
152/// AC20/ArchiCAD duplicate-boxes regression), so referenced maps are filtered
153/// in every mode. What remains is classified by whether the type has an
154/// occurrence (`IfcRelDefinesByType`): orphans are class 1 (part of the
155/// model — nothing else renders them), instanced types are class 2 (the
156/// type-library shape) and only emitted in [`TypeGeometryMode::EmitTagged`].
157pub fn plan_type_geometry(
158    rep_map_ids: &[u32],
159    referenced_representation_maps: &FxHashSet<u32>,
160    type_is_instantiated: bool,
161    mode: TypeGeometryMode,
162) -> Vec<(u32, u8)> {
163    if mode == TypeGeometryMode::SuppressInstanced && type_is_instantiated {
164        return Vec::new();
165    }
166    let class: u8 = if type_is_instantiated { 2 } else { 1 };
167    rep_map_ids
168        .iter()
169        .filter(|rm| !referenced_representation_maps.contains(rm))
170        .map(|rm| (*rm, class))
171        .collect()
172}
173
174/// Everything one element produced.
175pub struct ProducedElementMeshes {
176    pub meshes: Vec<MeshData>,
177    /// #1623 Phase 2 don't-bake output: this element's occurrences of a repeated
178    /// `IfcRepresentationMap` that skipped the per-occurrence materialize. Empty
179    /// unless the router was armed with an instancing plan
180    /// (`GeometryRouter::enable_output_instancing`); the streaming finalize resolves
181    /// each into a [`crate::InstanceRecord`] against the shared template MeshData.
182    pub instance_occurrences: Vec<RawInstanceOccurrence>,
183    /// Per-ELEMENT fingerprint, accumulated across all of the element's
184    /// meshes in the native IFC frame (pre-split, pre-site-rotation).
185    /// `None` when hashing is off, nothing was produced, or the job is a
186    /// TypeProduct.
187    pub geometry_hash: Option<u64>,
188    /// The same pass's world-space AABB, `[minx, miny, minz, maxx, maxy, maxz]`
189    /// in unquantized `f64` world coordinates (the file's RTC folded back in),
190    /// over every triangle corner the hasher saw. `Some` exactly when
191    /// [`Self::geometry_hash`] is `Some`, so the two stay index-parallel at the
192    /// FFI boundary.
193    ///
194    /// Why the diff engine needs it: the hash conflates moved / reshaped /
195    /// re-tessellated into one "different" bit. The box separates them — same
196    /// extent at a new centre is a MOVE, a different extent is a reshape, an
197    /// identical box with a different hash is retriangulation.
198    pub geometry_aabb: Option<[f64; 6]>,
199    /// The element's enclosed volume in m³ from the SAME pass — `Some` ONLY
200    /// when the produced geometry was provably a single closed orientable
201    /// solid, `None` otherwise (#1891). `None` is the common case for
202    /// material-layered walls, open `SurfaceModel` geometry, and any element
203    /// assembled from more than one representation item.
204    ///
205    /// Read `ifc_lite_geometry::GeometryHasher::volume` before widening any
206    /// clause of that gate: the alternative is not a slightly-off volume, it is
207    /// a confidently wrong one with nothing about it that looks wrong.
208    pub geometry_volume: Option<f64>,
209    /// The folded per-segment topology verdict behind [`Self::geometry_volume`]
210    /// — which clause held and which refused. `Some` exactly when
211    /// [`Self::geometry_hash`] is. A model checker wants it: "open shell" and
212    /// "multi-item assembly" are different findings with different fixes.
213    pub geometry_closure: Option<ifc_lite_geometry::GeometryClosure>,
214    /// CSG diagnostics recorded while producing THIS element, attributed by
215    /// product id. The router is fully drained on return, so a warm router
216    /// reused across a batch never leaks one element's failures into the
217    /// next. Failures from a superseded strategy (a fallback re-attempting
218    /// the same cuts) are discarded — only the path that produced the
219    /// returned meshes contributes.
220    pub csg_failures: FxHashMap<u32, Vec<BoolFailure>>,
221    /// Triangles dropped by the f32-collapse degenerate-triangle backstop
222    /// (see the `degenerate` child module) across ALL of this element's meshes.
223    /// Zero when the backstop is disabled or nothing was degenerate.
224    /// Request-local (scoped per `produce_element_meshes` call) so concurrent
225    /// passes never cross-contaminate. Non-zero also RETRACTS
226    /// [`Self::geometry_closure`] and [`Self::geometry_volume`] — the drop
227    /// happens after the verdict was taken and can open a certified shell.
228    pub degenerate_triangles_dropped: u64,
229}
230
231/// THE canonical per-element mesh producer.
232///
233/// Decoder and router are caller-supplied so each pipeline keeps its reuse
234/// policy: the native rayon loop builds a fresh seeded decoder + router per
235/// element; the browser batch path reuses one warm pair per batch. The
236/// decoder MUST have its unit-scale caches seeded
237/// (`EntityDecoder::seed_unit_scales`) — otherwise arc tessellation re-pays
238/// an O(file) IFCPROJECT scan per fresh decoder.
239pub fn produce_element_meshes(
240    job: &ElementMeshJob<'_>,
241    ctx: &MeshProductionContext<'_>,
242    opts: &MeshProductionOptions,
243    decoder: &mut EntityDecoder,
244    router: &GeometryRouter,
245) -> ProducedElementMeshes {
246    // Open a per-element CSG escalation scope (#1109). Every boolean this element
247    // issues (one per opening, plus clip cuts) accumulates into ONE deterministic
248    // budget, so a boolean-heavy element (a slab cut by 24+ openings, a Tekla
249    // member with stacked half-space clips) degrades as a UNIT — its remaining
250    // cuts bail to the #635 AABB fallback — instead of grinding the geometry
251    // stream past the 95% watchdog. The per-boolean cap alone could not see this
252    // distributed cost. Unbounded under the server/offline-export profile.
253    // Both scopes restore the enclosing element's counters on drop: a rayon
254    // work-steal can run another element to completion inside this one.
255    let _budget_scope = ifc_lite_geometry::kernel::budget::enter_element();
256
257    // Open this element's degenerate-backstop scope; see the `degenerate` child
258    // module.
259    let _degenerate_scope = degenerate::begin_element();
260
261    let mut hasher = match (&job.kind, opts.geometry_hash) {
262        (ElementJobKind::Product, Some(cfg)) => {
263            Some(GeometryHasher::new(cfg.tolerance, cfg.world_rtc))
264        }
265        _ => None,
266    };
267
268    let (meshes, instance_occurrences) = produce_inner(job, ctx, decoder, router, &mut hasher);
269
270    // Drain the router's per-element CSG diagnostics on EVERY return path so
271    // a warm (batch-reused) router starts the next element clean.
272    let csg_failures = router.take_csg_failures();
273
274    // A hash with NO box is reachable and deliberately KEPT (a NaN axis hashes
275    // but never accumulates); `push_geometry_hash` reserves NaN slots so the FFI
276    // arrays still cannot misalign. Box-without-hash is impossible. VOLUME may
277    // likewise be `None` within an emitted entry (landing as NaN) — the normal
278    // answer for most elements. See `world_aabb` / `GeometryHasher::volume`.
279    let degenerate_triangles_dropped = degenerate::dropped_this_element();
280
281    // The verdict was taken where the orienter runs; `build_mesh_data` then ran
282    // the degenerate backstop over the same triangles, and a dropped triangle
283    // opens every neighbour along its three edges. Retract before reading, so
284    // what ships describes the mesh actually returned (see
285    // `retract_closure_if_mesh_edited`).
286    let (geometry_hash, geometry_aabb, geometry_volume, geometry_closure) = match hasher {
287        Some(mut h) if !h.is_empty() => {
288            h.retract_closure_if_mesh_edited(degenerate_triangles_dropped);
289            (Some(h.finish()), h.world_aabb(), h.volume(), Some(h.closure()))
290        }
291        _ => (None, None, None, None),
292    };
293
294    ProducedElementMeshes {
295        meshes,
296        instance_occurrences,
297        geometry_hash,
298        geometry_aabb,
299        geometry_volume,
300        geometry_closure,
301        csg_failures,
302        degenerate_triangles_dropped,
303    }
304}
305
306fn produce_inner(
307    job: &ElementMeshJob<'_>,
308    ctx: &MeshProductionContext<'_>,
309    decoder: &mut EntityDecoder,
310    router: &GeometryRouter,
311    hasher: &mut Option<GeometryHasher>,
312) -> (Vec<MeshData>, Vec<RawInstanceOccurrence>) {
313    // Representation gate, with the IfcAlignment exception: alignments carry
314    // their geometry on IfcAlignment*Segment children, so a null
315    // Representation attribute does not mean "nothing to render".
316    let has_representation = job.entity.get(6).is_some_and(|a| !a.is_null());
317    if !has_representation && job.ifc_type != IfcType::IfcAlignment {
318        return (Vec::new(), Vec::new());
319    }
320
321    let element_color = job
322        .element_color
323        .unwrap_or_else(|| crate::style::default_color_for_type(job.ifc_type).to_array());
324
325    if let ElementJobKind::TypeProduct { rep_maps } = &job.kind {
326        // Type-product geometry (orphan/instanced RepresentationMaps) never rides the
327        // don't-bake path — it is view-mode-gated by geometry_class, not instanced.
328        return (
329            produce_type_geometry(job, rep_maps, element_color, ctx, decoder, router),
330            Vec::new(),
331        );
332    }
333
334    let has_openings = ctx
335        .void_index
336        .get(&job.id)
337        .is_some_and(|openings| openings.iter().any(|&id| router.opening_requires_subtraction(id, decoder)));
338
339    // Material-layer wall: tag its per-layer slices GEOM_CLASS_LAYER_SLICE so the
340    // 2D/section cut can split the cut into per-layer fills (one sub-mesh = one
341    // layer = one colour). Since #1311 the slices are OPEN bands whose union is
342    // the wall's watertight outer skin (no coincident interface caps), and the
343    // renderer draws them DOUBLE-SIDED like all other IFC geometry — IFC winding
344    // is not reliably outward, so the previous backface-culling of these slices
345    // dropped inward-wound faces and made the wall read hollow. The tag no longer
346    // drives any culling; it is purely the per-layer-fill marker.
347    let layer_class = if router.is_material_layer_sliceable(job.id) {
348        GEOM_CLASS_LAYER_SLICE
349    } else {
350        0
351    };
352
353    if has_openings {
354        // Voided elements: submesh-aware cut FIRST, so per-part colours
355        // survive the void subtraction (a voided window keeps frame/glass
356        // split; a voided multi-layer wall keeps its layer colours).
357        if let Ok(sub_meshes) =
358            router.process_element_with_submeshes_and_voids(job.entity, decoder, ctx.void_index)
359        {
360            if !sub_meshes.is_empty() {
361                let (out, occ) =
362                    emit_sub_meshes(job, sub_meshes, element_color, ctx, decoder, hasher, layer_class);
363                if !out.is_empty() || !occ.is_empty() {
364                    return (out, occ);
365                }
366            }
367        }
368    } else {
369        // Submesh path for ALL types: per-geometry-item colours (window glass
370        // transparency, multi-material doors) and per-item error skipping —
371        // one unsupported representation item no longer blanks the whole
372        // element (`process_element` aborts with `?`). #858 palette split
373        // happens per item inside `emit_sub_meshes`.
374        let submeshes = router.process_element_with_submeshes_textured(job.entity, decoder, ctx.texture_index);
375        // Annotation validation failures are terminal, not another meshing strategy.
376        // Retrying the fallback chain would count one refused fill three times.
377        if job.ifc_type == IfcType::IfcAnnotation && submeshes.is_err() { return (Vec::new(), Vec::new()); }
378        if let Ok(sub_meshes) = submeshes {
379            if !sub_meshes.is_empty() {
380                let (out, occ) =
381                    emit_sub_meshes(job, sub_meshes, element_color, ctx, decoder, hasher, layer_class);
382                // #1623 Phase 2: a pure don't-bake occurrence produces NO flat mesh
383                // (only instance placeholders); treat that as success so the fallback
384                // chain below does not re-materialize the element flat.
385                if !out.is_empty() || !occ.is_empty() {
386                    return (out, occ);
387                }
388            }
389        }
390    }
391
392    // Fallback chain. A superseding strategy is about to re-process this
393    // element's representation and re-attempt the same (deterministic)
394    // cuts/booleans; discard the abandoned attempt's diagnostics so
395    // re-failures aren't double-counted. (The voids→plain-element
396    // mini-fallback below intentionally keeps its records: a failed/emptying
397    // cut that leaves the host uncut IS the diagnostic.)
398    let _ = router.take_csg_failures();
399
400    let mut mesh_candidate = router
401        .process_element_with_voids(job.entity, decoder, ctx.void_index)
402        .ok();
403    let needs_fallback = match mesh_candidate.as_ref() {
404        // An empty void-cut result normally means the cut FAILED and emptied
405        // the host, so we re-render it un-cut. But when a containing void
406        // genuinely CONSUMED the host (`host_consumed_by_void`), the empty
407        // result is correct — keep it, or the un-cut host re-appears as a
408        // spurious solid.
409        Some(mesh) => mesh.is_empty() && !router.host_consumed_by_void(job.id),
410        None => true,
411    };
412    if needs_fallback {
413        mesh_candidate = router.process_element(job.entity, decoder).ok();
414    }
415
416    let Some(mut mesh) = mesh_candidate else {
417        return (Vec::new(), Vec::new());
418    };
419    if mesh.is_empty() {
420        return (Vec::new(), Vec::new());
421    }
422
423    // Make the assembled body consistently outward-wound. A faceted brep (IFC
424    // face loops are not reliably outward) or a merged multi-item body (extrusion
425    // unioned with a boolean cut) can carry MIXED winding that corrupts signed
426    // volume and the smooth normals computed below. No-op for already-consistent
427    // bodies (every extrusion), so their index buffer + normals are untouched; a
428    // flip invalidates any baked normals, so recompute them.
429    //
430    // The verdict rides along to the hasher below: this pass is the only place
431    // that knows whether the assembled body is a closed orientable solid, and
432    // without that a per-element volume cannot be emitted honestly (#1891).
433    let verdict = orient_mesh_outward_verdict(&mut mesh);
434    if verdict.flipped {
435        calculate_normals(&mut mesh);
436    }
437
438    // Multi-colour IfcIndexedColourMap → one mesh per palette group (#858),
439    // resolved by walking the element's representation for the colour-mapped
440    // face set. Only applies while the produced triangle count still matches
441    // the face set's CoordIndex (no CSG/void retopology) — the splitter
442    // guards this; otherwise the single dominant-coloured mesh below wins.
443    if !ctx.indexed_colour_full.is_empty() {
444        if let Some(full) =
445            find_indexed_colour_for_element(job.entity, ctx.indexed_colour_full, decoder)
446        {
447            let geometry_id = full.geometry_id;
448            if let Some(groups) = crate::style::split_mesh_by_indexed_colour(&mesh, full) {
449                if let Some(h) = hasher.as_mut() {
450                    // The palette split below only partitions triangles; the
451                    // verdict from the un-split body is the one that describes
452                    // this hashed buffer.
453                    h.add_oriented_mesh(&mesh.positions, &mesh.indices, mesh.origin, verdict);
454                }
455                let mut out: Vec<MeshData> = Vec::with_capacity(groups.len());
456                for (color, mut part) in groups {
457                    if part.normals.len() != part.positions.len() {
458                        calculate_normals(&mut part);
459                    }
460                    out.push(build_mesh_data(
461                        job,
462                        part,
463                        color.to_array(),
464                        None,
465                        Some(geometry_id),
466                        false,
467                        0,
468                        ctx,
469                        None,
470                    ));
471                }
472                if !out.is_empty() {
473                    return (out, Vec::new());
474                }
475            }
476        }
477    }
478
479    if mesh.normals.len() != mesh.positions.len() {
480        calculate_normals(&mut mesh);
481    }
482    if let Some(h) = hasher.as_mut() {
483        h.add_oriented_mesh(&mesh.positions, &mesh.indices, mesh.origin, verdict);
484    }
485    (
486        vec![build_mesh_data(job, mesh, element_color, None, None, false, 0, ctx, None)],
487        Vec::new(),
488    )
489}
490
491/// Emit a sub-mesh collection: per-item colour resolution through the
492/// canonical `resolve_submesh_color` precedence (#913 §4.2), material-name
493/// inference for window/door parts, and the #858 per-item palette split.
494fn emit_sub_meshes(
495    job: &ElementMeshJob<'_>,
496    sub_meshes: SubMeshCollection,
497    element_color: [f32; 4],
498    ctx: &MeshProductionContext<'_>,
499    decoder: &mut EntityDecoder,
500    hasher: &mut Option<GeometryHasher>,
501    // geometry_class stamped on every emitted sub-mesh. 0 for normal occurrence
502    // geometry; GEOM_CLASS_LAYER_SLICE (3) when these are the per-layer slices of
503    // a material-layer wall — a section-only detail the 3D renderer skips (the
504    // wall renders as one solid) but the 2D/section cut consumes.
505    slice_class: u8,
506) -> (Vec<MeshData>, Vec<RawInstanceOccurrence>) {
507    // Read ONCE, before the loop consumes the collection: what the ids MEAN is
508    // a property of the collection, not of any individual sub-mesh (#3199).
509    let ids_are_materials = sub_meshes.ids_are_materials;
510    let mut out: Vec<MeshData> = Vec::with_capacity(sub_meshes.len());
511    let mut occurrences: Vec<RawInstanceOccurrence> = Vec::new();
512    // Material colours for this element, used when a sub-mesh has no direct
513    // style — alternated so frame (opaque) and glazing (transparent) split
514    // across the window's parts (#913 §2.3).
515    let material_colors = ctx.element_material_colors.get(&job.id);
516    let mut mat_color_idx = 0usize;
517
518    for sub in sub_meshes.sub_meshes {
519        let mut sub_mesh = sub.mesh;
520        if sub_mesh.is_empty() {
521            // #1623 Phase 2 don't-bake: an EMPTY sub-mesh carrying instanceable
522            // InstanceMeta is a non-template occurrence of a shared template. Convert
523            // it to a RawInstanceOccurrence (resolving its colour EXACTLY as a
524            // materialized sub-mesh would, keyed on the same nested-solid geometry_id)
525            // instead of dropping it. `transform` was folded into `im.transform` by
526            // `apply_submesh_placement`; we compose the full pre-RTC world transform
527            // here and let the streaming finalize derive the template-relative mat4.
528            if let Some(im) = sub_mesh.instance_meta.as_ref().filter(|im| im.instanceable) {
529                let style = ctx.geometry_style_index.get(&sub.geometry_id);
530                let direct_color = style.map(|s| s.color).or_else(|| {
531                    find_geometry_item_color(sub.geometry_id, ctx.geometry_style_index, decoder)
532                });
533                let color = crate::style::resolve_submesh_color(
534                    direct_color,
535                    material_colors.map(|v| v.as_slice()),
536                    &mut mat_color_idx,
537                    element_color,
538                );
539                occurrences.push(RawInstanceOccurrence {
540                    express_id: job.id,
541                    ifc_type: job.ifc_type.name().to_string(),
542                    global_id: job.metadata.and_then(|m| m.global_id.clone()),
543                    name: job.metadata.and_then(|m| m.name.clone()),
544                    presentation_layer: job.metadata.and_then(|m| m.presentation_layer.clone()),
545                    color,
546                    rep_identity: im.rep_identity,
547                    world_transform: compose_instance_world_row_major(im),
548                    // #2985: the id `build_mesh_data` would have stamped had this
549                    // sub-mesh materialized. ONE home for the #3199 discriminator and the
550                    // 0-filter — two spellings drift invisibly ("no item id" reads as "no item").
551                    geometry_item_id: MeshData::style_geometry_item_id(Some(sub.geometry_id), ids_are_materials),
552                });
553            }
554            continue;
555        }
556        // Consistently outward-wind each sub-body (see the single-mesh path); a
557        // flip invalidates baked normals, so recompute on flip or when absent.
558        // The verdict is per SUB-BODY, which is also the hasher's segment
559        // granularity, so closedness is attributed to exactly what it describes.
560        let verdict = orient_mesh_outward_verdict(&mut sub_mesh);
561        if verdict.flipped || sub_mesh.normals.len() != sub_mesh.positions.len() {
562            calculate_normals(&mut sub_mesh);
563        }
564
565        let style = ctx.geometry_style_index.get(&sub.geometry_id);
566        // Direct style wins; else chase IfcMappedItem so mapped sub-geometry
567        // inherits its underlying style (#913 §2.7).
568        let direct_color = style.map(|s| s.color).or_else(|| {
569            find_geometry_item_color(sub.geometry_id, ctx.geometry_style_index, decoder)
570        });
571        let color = crate::style::resolve_submesh_color(
572            direct_color,
573            material_colors.map(|v| v.as_slice()),
574            &mut mat_color_idx,
575            element_color,
576        );
577        let material_name = style
578            .and_then(|s| s.material_name.as_ref())
579            .map(ToString::to_string)
580            .or_else(|| infer_opening_subpart_material_name(&job.ifc_type, color, sub.geometry_id));
581
582        if let Some(h) = hasher.as_mut() {
583            h.add_oriented_mesh(&sub_mesh.positions, &sub_mesh.indices, sub_mesh.origin, verdict);
584        }
585
586        // Textured face set (#1781): thread the per-vertex UVs through the
587        // weld (kept 1:1 with positions, seams stay split) and attach the
588        // texture, mirroring the type-geometry path (#961). The length guard
589        // drops the texture instead of sampling garbage if any upstream step
590        // rebuilt vertices without maintaining the UV channel.
591        if let (Some(uvs), Some(texture)) = (sub.uvs, sub.texture.as_ref()) {
592            if uvs.len() / 2 == sub_mesh.positions.len() / 3 {
593                let mut mesh_data = build_mesh_data(
594                    job,
595                    sub_mesh,
596                    color,
597                    material_name,
598                    Some(sub.geometry_id),
599                    ids_are_materials,
600                    slice_class,
601                    ctx,
602                    Some(uvs),
603                );
604                mesh_data.texture = Some(MeshTextureData::from_attachment(texture));
605                out.push(mesh_data);
606                continue;
607            }
608        }
609
610        // #858: a face set with a per-triangle colour map splits into one
611        // mesh per palette group (guards inside the splitter: triangle count
612        // must still match, ≥2 distinct colours). Palette colours supersede
613        // the resolved style colour for the split parts.
614        if let Some(full) = ctx.indexed_colour_full.get(&sub.geometry_id) {
615            if let Some(groups) = crate::style::split_mesh_by_indexed_colour(&sub_mesh, full) {
616                for (rgba, mut part) in groups {
617                    if part.normals.len() != part.positions.len() {
618                        calculate_normals(&mut part);
619                    }
620                    out.push(build_mesh_data(
621                        job,
622                        part,
623                        rgba.to_array(),
624                        None,
625                        Some(sub.geometry_id),
626                        ids_are_materials,
627                        slice_class,
628                        ctx,
629                        None,
630                    ));
631                }
632                continue;
633            }
634        }
635
636        out.push(build_mesh_data(
637            job,
638            sub_mesh,
639            color,
640            material_name,
641            Some(sub.geometry_id),
642            ids_are_materials,
643            slice_class,
644            ctx,
645            None,
646        ));
647    }
648    (out, occurrences)
649}
650
651/// geometry_class for the per-layer slices of a material-layer wall. The wall's
652/// slices have verified outward winding, so the 3D renderer draws THIS class
653/// BACKFACE-CULLED — the build-up shows on the faces/edges but the interior
654/// coincident caps never rasterise, so the thin stacked solids don't z-fight
655/// into a hollow shell. The 2D/section cut consumes the same class (never
656/// culled) for its per-layer fills.
657pub const GEOM_CLASS_LAYER_SLICE: u8 = 3;
658
659/// Render a type-product's planned RepresentationMaps (#957), texture-aware
660/// (#961), each mesh tagged with its planned geometry_class.
661fn produce_type_geometry(
662    job: &ElementMeshJob<'_>,
663    rep_maps: &[(u32, u8)],
664    element_color: [f32; 4],
665    ctx: &MeshProductionContext<'_>,
666    decoder: &mut EntityDecoder,
667    router: &GeometryRouter,
668) -> Vec<MeshData> {
669    let mut out: Vec<MeshData> = Vec::new();
670    for &(rep_map_id, geometry_class) in rep_maps {
671        let Ok(rep_map) = decoder.decode_by_id(rep_map_id) else {
672            continue;
673        };
674        // One part per output mesh: each textured face set carries its own
675        // UVs + decoded image; untextured items merge into one part (#961).
676        let Ok(parts) =
677            router.process_representation_map_with_texture(&rep_map, decoder, ctx.texture_index)
678        else {
679            continue;
680        };
681        if parts.is_empty() {
682            continue;
683        }
684
685        let color =
686            resolve_color_for_representation_map(rep_map_id, ctx.geometry_style_index, decoder)
687                .unwrap_or(element_color);
688
689        for (mut mesh, uvs, texture) in parts {
690            if mesh.is_empty() {
691                continue;
692            }
693            if mesh.normals.len() != mesh.positions.len() {
694                calculate_normals(&mut mesh);
695            }
696            // Thread the per-vertex UVs through `build_mesh_data` so the source
697            // weld remaps them WITH the deduped positions (and keeps texture
698            // seams split). Only textured parts carry UVs; untextured parts pass
699            // `None` and get the full position+normal weld.
700            let part_uvs = if texture.is_some() { Some(uvs) } else { None };
701            let mut mesh_data =
702                build_mesh_data(job, mesh, color, None, None, false, geometry_class, ctx, part_uvs);
703            if let Some(tex) = texture {
704                // UVs were already welded onto `mesh_data`; attach only the
705                // texture (decoded image or #1781 external reference) here.
706                mesh_data.texture = Some(MeshTextureData::from_attachment(&tex));
707            }
708            out.push(mesh_data);
709        }
710    }
711    out
712}
713
714#[path = "element_mesh_build.rs"]
715mod element_mesh_build;
716use element_mesh_build::build_mesh_data;
717
718#[cfg(test)]
719#[path = "element_tests.rs"]
720mod tests;