ifc-lite-wasm 4.2.0

WebAssembly bindings for IFC-Lite
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use ifc_lite_geometry::Mesh;
use wasm_bindgen::prelude::*;

/// Individual mesh data with express ID and color (matches MeshData interface)
#[wasm_bindgen]
pub struct MeshDataJs {
    express_id: u32,
    ifc_type: String, // IFC type name (e.g., "IfcWall", "IfcSpace")
    positions: Vec<f32>,
    normals: Vec<f32>,
    indices: Vec<u32>,
    /// Apparent rendering colour: IfcSurfaceStyleRendering.DiffuseColour
    /// when authored, otherwise the SurfaceColour.
    color: [f32; 4], // RGBA
    /// SurfaceColour, populated only when the file authored a distinct
    /// DiffuseColour (so the two would differ). Consumed by the GLB
    /// exporter's "Shading" colour-source option; renderers ignore it.
    shading_color: Option<[f32; 4]>,
    /// Per-vertex texture coordinates (u, v pairs, 1:1 with positions),
    /// present only for textured meshes (#961). Empty otherwise.
    uvs: Vec<f32>,
    /// Decoded RGBA8 texture (`width*height*4`), present only for textured
    /// meshes (#961). Empty otherwise. The browser uploads this verbatim to a
    /// GPU texture — no image decoding happens in JS.
    texture_rgba: Vec<u8>,
    texture_width: u32,
    texture_height: u32,
    texture_repeat_s: bool,
    texture_repeat_t: bool,
    /// Stable texture dedup key: the `IfcSurfaceTexture` express id (#1781).
    /// Every mesh sampling the same image carries the same id, so the consumer
    /// creates ONE GPU texture per id. 0 when the mesh is untextured.
    texture_id: u32,
    /// `IfcImageTexture.URLReference` (#1781): an external image reference the
    /// host resolves (typically a sibling file inside the `.ifcZIP`). `None`
    /// for untextured meshes and for Rust-decoded blob/pixel textures.
    texture_url: Option<String>,
    /// Geometry provenance for the viewer's Model/Types view switch:
    /// 0 = occurrence (a placed IfcProduct), 1 = orphan type geometry (an
    /// IfcTypeProduct RepresentationMap with NO occurrence — buildingSMART
    /// annex-E showcase files; part of "the model" since nothing else renders
    /// it), 2 = instanced type geometry (an IfcTypeProduct that IS instantiated
    /// via IfcRelDefinesByType — the type-library shape, hidden in Model mode to
    /// avoid double-rendering, shown in Types mode). See #957 follow-up.
    geometry_class: u8,
    /// Per-element local-frame origin (f64), in the SAME (WebGL Y-up) frame as
    /// `positions`: world position of vertex i = `origin + positions[3i..]`.
    /// Default `[0,0,0]` means positions are absolute (legacy). Carries the
    /// per-element AABB-centre relativization so building-scale coordinates stay
    /// f32-precise (no fan collapse). See `Mesh::origin`/transform_mesh_world_framed.
    origin: [f64; 3],
    /// Local (pre-placement, object-space) AABB, WebGL Y-up (issue #1474):
    /// `[minX,minY,minZ,maxX,maxY,maxZ]`. `None` when not captured (e.g. a
    /// synthetic/from-meshes mesh). See `Mesh::local_bounds`.
    local_bounds: Option<[f32; 6]>,
    /// The resolved placement (`local_to_world`), row-major, WebGL Y-up (issue
    /// #1474). `None` when not captured. See `Mesh::local_to_world`.
    local_to_world: Option<[f64; 16]>,
}

#[wasm_bindgen]
impl MeshDataJs {
    /// Get express ID
    #[wasm_bindgen(getter, js_name = expressId)]
    pub fn express_id(&self) -> u32 {
        self.express_id
    }

    /// Get IFC type name (e.g., "IfcWall", "IfcSpace")
    #[wasm_bindgen(getter, js_name = ifcType)]
    pub fn ifc_type(&self) -> String {
        self.ifc_type.clone()
    }

    /// Get positions as Float32Array (copy to JS)
    #[wasm_bindgen(getter)]
    pub fn positions(&self) -> js_sys::Float32Array {
        js_sys::Float32Array::from(&self.positions[..])
    }

    /// Get normals as Float32Array (copy to JS)
    #[wasm_bindgen(getter)]
    pub fn normals(&self) -> js_sys::Float32Array {
        js_sys::Float32Array::from(&self.normals[..])
    }

    /// Get indices as Uint32Array (copy to JS)
    #[wasm_bindgen(getter)]
    pub fn indices(&self) -> js_sys::Uint32Array {
        js_sys::Uint32Array::from(&self.indices[..])
    }

    /// Get color as [r, g, b, a] array
    #[wasm_bindgen(getter)]
    pub fn color(&self) -> Vec<f32> {
        self.color.to_vec()
    }

    /// Optional SurfaceColour for the "Shading" GLB-export choice — only
    /// present when the file authored a distinct DiffuseColour. JS sees
    /// `undefined` when absent (most files).
    #[wasm_bindgen(getter, js_name = shadingColor)]
    pub fn shading_color(&self) -> Option<Vec<f32>> {
        self.shading_color.map(|c| c.to_vec())
    }

    /// Get vertex count
    #[wasm_bindgen(getter, js_name = vertexCount)]
    pub fn vertex_count(&self) -> usize {
        self.positions.len() / 3
    }

    /// Get triangle count
    #[wasm_bindgen(getter, js_name = triangleCount)]
    pub fn triangle_count(&self) -> usize {
        self.indices.len() / 3
    }

    /// True when this mesh carries a surface texture (#961).
    #[wasm_bindgen(getter, js_name = hasTexture)]
    pub fn has_texture(&self) -> bool {
        !self.texture_rgba.is_empty()
    }

    /// Per-vertex texture coordinates as Float32Array (u, v pairs). Empty when
    /// the mesh is untextured.
    #[wasm_bindgen(getter)]
    pub fn uvs(&self) -> js_sys::Float32Array {
        js_sys::Float32Array::from(&self.uvs[..])
    }

    /// Decoded RGBA8 texture bytes (`width*height*4`). Empty when untextured.
    #[wasm_bindgen(getter, js_name = textureRgba)]
    pub fn texture_rgba(&self) -> js_sys::Uint8Array {
        js_sys::Uint8Array::from(&self.texture_rgba[..])
    }

    #[wasm_bindgen(getter, js_name = textureWidth)]
    pub fn texture_width(&self) -> u32 {
        self.texture_width
    }

    #[wasm_bindgen(getter, js_name = textureHeight)]
    pub fn texture_height(&self) -> u32 {
        self.texture_height
    }

    /// Sampler wrap for the S axis (`IfcSurfaceTexture.RepeatS`): true = repeat.
    #[wasm_bindgen(getter, js_name = textureRepeatS)]
    pub fn texture_repeat_s(&self) -> bool {
        self.texture_repeat_s
    }

    /// Sampler wrap for the T axis (`IfcSurfaceTexture.RepeatT`): true = repeat.
    #[wasm_bindgen(getter, js_name = textureRepeatT)]
    pub fn texture_repeat_t(&self) -> bool {
        self.texture_repeat_t
    }

    /// Stable texture dedup key (`IfcSurfaceTexture` express id, #1781).
    /// 0 when the mesh is untextured.
    #[wasm_bindgen(getter, js_name = textureId)]
    pub fn texture_id(&self) -> u32 {
        self.texture_id
    }

    /// External image reference (`IfcImageTexture.URLReference`, #1781) for the
    /// host to resolve — e.g. a sibling image inside the `.ifcZIP`. `undefined`
    /// for untextured meshes and Rust-decoded blob/pixel textures.
    #[wasm_bindgen(getter, js_name = textureUrl)]
    pub fn texture_url(&self) -> Option<String> {
        self.texture_url.clone()
    }

    /// Geometry provenance for the viewer's Model/Types switch (#957 follow-up):
    /// 0 = occurrence, 1 = orphan type geometry (no occurrence), 2 = instanced
    /// type geometry (hidden in Model mode, shown in Types mode).
    #[wasm_bindgen(getter, js_name = geometryClass)]
    pub fn geometry_class(&self) -> u8 {
        self.geometry_class
    }

    /// Per-element local-frame origin (Float64Array[3], WebGL Y-up, metres):
    /// world position of vertex i = `origin + positions[3i..3i+3]`. Returns
    /// [0,0,0] when positions are absolute (legacy / local frame off).
    #[wasm_bindgen(getter)]
    pub fn origin(&self) -> js_sys::Float64Array {
        js_sys::Float64Array::from(&self.origin[..])
    }

    /// Local (pre-placement, object-space) AABB (issue #1474), WebGL Y-up,
    /// `[minX,minY,minZ,maxX,maxY,maxZ]`. `undefined` when not captured
    /// (wasm-bindgen maps `Option::None` to `undefined`, not `null`).
    #[wasm_bindgen(getter, js_name = localBounds)]
    pub fn local_bounds(&self) -> Option<Vec<f32>> {
        self.local_bounds.map(|b| b.to_vec())
    }

    /// The resolved `IfcLocalPlacement` chain for this mesh (issue #1474),
    /// row-major 4×4, WebGL Y-up. `undefined` when not captured (see
    /// `local_bounds` above).
    #[wasm_bindgen(getter, js_name = localToWorld)]
    pub fn local_to_world(&self) -> Option<Vec<f64>> {
        self.local_to_world.map(|m| m.to_vec())
    }
}

/// Swap an axis-aligned box's corners from IFC Z-up to WebGL Y-up
/// (`(x,y,z) -> (x,z,-y)`). A per-component swap of `min`/`max` independently
/// is WRONG: negating the Y axis flips which corner is the min/max along the
/// new Z, so the new Z range is `[-maxY, -minY]`, not `[-minY, -maxY]`.
fn swap_zup_to_yup_aabb(b: [f32; 6]) -> [f32; 6] {
    let [min_x, min_y, min_z, max_x, max_y, max_z] = b;
    [min_x, min_z, -max_y, max_x, max_z, -min_y]
}

/// Conjugate a row-major 4×4 matrix by the fixed IFC Z-up → WebGL Y-up swap
/// `S`: `(x,y,z,w) -> (x,z,-y,w)`, so a placement/rotation matrix expressed in
/// the IFC frame becomes valid in the Y-up frame the renderer uses:
/// `M' = S · M · Sᵀ` (S is orthogonal, so `S⁻¹ = Sᵀ`).
fn swap_zup_to_yup_mat4(m: &[f64; 16]) -> [f64; 16] {
    #[rustfmt::skip]
    const S: [f64; 16] = [
        1.0, 0.0, 0.0, 0.0,
        0.0, 0.0, 1.0, 0.0,
        0.0, -1.0, 0.0, 0.0,
        0.0, 0.0, 0.0, 1.0,
    ];
    #[rustfmt::skip]
    const ST: [f64; 16] = [
        1.0, 0.0, 0.0, 0.0,
        0.0, 0.0, -1.0, 0.0,
        0.0, 1.0, 0.0, 0.0,
        0.0, 0.0, 0.0, 1.0,
    ];
    fn matmul(a: &[f64; 16], b: &[f64; 16]) -> [f64; 16] {
        let mut out = [0.0; 16];
        for r in 0..4 {
            for c in 0..4 {
                let mut sum = 0.0;
                for k in 0..4 {
                    sum += a[r * 4 + k] * b[k * 4 + c];
                }
                out[r * 4 + c] = sum;
            }
        }
        out
    }
    matmul(&matmul(&S, m), &ST)
}

impl MeshDataJs {
    /// Create new mesh data with IFC Z-up to WebGL Y-up conversion.
    ///
    /// Performs coordinate conversion and winding order reversal in Rust
    /// to avoid expensive per-vertex JS iteration (63.5M vertices for large files).
    /// IFC Z-up → WebGL Y-up: swap Y/Z, negate new Z for right-handedness.
    /// Winding order reversed to compensate for the handedness flip.
    pub fn new(express_id: u32, ifc_type: String, mut mesh: Mesh, color: [f32; 4]) -> Self {
        // Convert positions: IFC Z-up → WebGL Y-up
        for chunk in mesh.positions.chunks_exact_mut(3) {
            let y = chunk[1];
            let z = chunk[2];
            chunk[1] = z; // New Y = old Z (vertical)
            chunk[2] = -y; // New Z = -old Y (depth, negated for right-hand rule)
        }

        // Convert normals the same way
        for chunk in mesh.normals.chunks_exact_mut(3) {
            let y = chunk[1];
            let z = chunk[2];
            chunk[1] = z;
            chunk[2] = -y;
        }

        // Reverse winding order to compensate for handedness flip
        let remainder = mesh.indices.len() % 3;
        let end = mesh.indices.len() - remainder;
        for i in (0..end).step_by(3) {
            mesh.indices.swap(i + 1, i + 2);
        }

        // The per-element origin is a world-frame point and MUST undergo the
        // identical IFC Z-up → WebGL Y-up swap as the positions above, or
        // `world = origin + position` would mix axes (element renders mirrored
        // / displaced). Default [0,0,0] swaps to [0,0,0] (no-op for legacy).
        let origin = [mesh.origin[0], mesh.origin[2], -mesh.origin[1]];

        // Local (pre-placement) AABB (issue #1474): same swap as positions, but
        // an AABB corner can't be swapped component-wise — negating an axis
        // flips which corner is min/max along it. See `swap_zup_to_yup_aabb`.
        let local_bounds = mesh.local_bounds.map(swap_zup_to_yup_aabb);
        // The placement transform (issue #1474) is conjugated by the same
        // swap, since it's expressed in the IFC frame the positions were in
        // before this conversion: M' = S · M · Sᵀ. See `swap_zup_to_yup_mat4`.
        let local_to_world = mesh.local_to_world.map(|m| swap_zup_to_yup_mat4(&m));

        Self {
            express_id,
            ifc_type,
            positions: mesh.positions,
            normals: mesh.normals,
            indices: mesh.indices,
            color,
            shading_color: None,
            uvs: Vec::new(),
            texture_rgba: Vec::new(),
            texture_width: 0,
            texture_height: 0,
            texture_repeat_s: true,
            texture_repeat_t: true,
            texture_id: 0,
            texture_url: None,
            geometry_class: 0,
            origin,
            local_bounds,
            local_to_world,
        }
    }

    /// Tag this mesh's geometry provenance for the Model/Types view switch
    /// (0 = occurrence, 1 = orphan type, 2 = instanced type). Call after `new`.
    pub fn set_geometry_class(&mut self, class: u8) {
        self.geometry_class = class;
    }

    /// Attach an optional SurfaceColour for the GLB exporter's "Shading"
    /// colour source. Callers that have a `geometry_shading_styles` entry
    /// for the mesh's source geometry id should invoke this after `new`.
    pub fn set_shading_color(&mut self, shading: Option<[f32; 4]>) {
        self.shading_color = shading;
    }

    /// Attach per-vertex UVs + a decoded RGBA8 texture (#961). UVs are 1:1 with
    /// `positions` and need no coordinate flip (they are 2D); the winding
    /// reversal in `new` swaps indices, not vertices, so per-vertex UVs stay
    /// aligned. Call after `new`.
    pub fn set_texture(
        &mut self,
        uvs: Vec<f32>,
        rgba: Vec<u8>,
        width: u32,
        height: u32,
        repeat_s: bool,
        repeat_t: bool,
        texture_id: u32,
    ) {
        self.uvs = uvs;
        self.texture_rgba = rgba;
        self.texture_width = width;
        self.texture_height = height;
        self.texture_repeat_s = repeat_s;
        self.texture_repeat_t = repeat_t;
        self.texture_id = texture_id;
    }

    /// Attach per-vertex UVs + an EXTERNAL image reference (#1781): the host
    /// resolves `url` (e.g. against the `.ifcZIP` siblings), decodes it once
    /// per `texture_id`, and shares the GPU texture. Call after `new`.
    pub fn set_texture_ref(
        &mut self,
        uvs: Vec<f32>,
        url: String,
        repeat_s: bool,
        repeat_t: bool,
        texture_id: u32,
    ) {
        self.uvs = uvs;
        self.texture_url = Some(url);
        self.texture_repeat_s = repeat_s;
        self.texture_repeat_t = repeat_t;
        self.texture_id = texture_id;
    }

    /// Build from the canonical per-element producer's [`MeshData`]
    /// (`ifc_lite_processing::element`): wraps [`MeshDataJs::new`] (IFC Z-up →
    /// WebGL Y-up + winding reversal), copies the `geometry_class` tag and the
    /// optional texture/UVs. Element metadata the browser doesn't carry
    /// (global_id / name / presentation layer / material name / properties) is
    /// dropped — the viewer gets it from the parser worker instead.
    pub fn from_mesh_data(m: ifc_lite_processing::MeshData) -> Self {
        let mesh = Mesh {
            positions: m.positions,
            normals: m.normals,
            indices: m.indices,
            // Positions are final here (the canonical producer already applied
            // placement/RTC); the flag only guards upstream double-subtraction.
            rtc_applied: true,
            // Per-element local-frame origin from the producer (IFC frame); the
            // Z-up→Y-up swap is applied in `new`. [0,0,0] when local frame off.
            origin: m.origin,
            // Instancing side-channel is not used on this wasm zero-copy path.
            instance_meta: None,
            // Local bounds/placement (issue #1474), still in the IFC frame —
            // `new` applies the same Z-up→Y-up swap it applies to positions/origin.
            local_bounds: m.local_bounds,
            local_to_world: m.local_to_world,
        };
        let mut js = Self::new(m.express_id, m.ifc_type, mesh, m.color);
        js.set_geometry_class(m.geometry_class);
        if let (Some(uvs), Some(tex)) = (m.uvs, m.texture) {
            if let Some(rgba) = tex.rgba {
                // Rust-decoded blob/pixel texture (#961): the Arc is shared
                // across meshes in Rust; this boundary copy is per-mesh but
                // blob/pixel images are small by construction.
                js.set_texture(
                    uvs,
                    rgba.as_ref().clone(),
                    tex.width,
                    tex.height,
                    tex.repeat_s,
                    tex.repeat_t,
                    tex.texture_id,
                );
            } else if let Some(url) = tex.url {
                // External image reference (#1781): ship the URL + repeat
                // flags only; the host decodes once per texture_id.
                js.set_texture_ref(uvs, url, tex.repeat_s, tex.repeat_t, tex.texture_id);
            }
        }
        js
    }
}

/// Collection of mesh data for returning multiple meshes
#[wasm_bindgen]
pub struct MeshCollection {
    meshes: Vec<MeshDataJs>,
    /// RTC (Relative-to-Center) offset applied to all positions
    /// This is subtracted from world coordinates to improve Float32 precision
    rtc_offset_x: f64,
    rtc_offset_y: f64,
    rtc_offset_z: f64,
    /// Building rotation angle in radians (from IfcSite's top-level placement)
    /// This is the rotation of the building's principal axes relative to world X/Y/Z
    building_rotation: Option<f64>,
    /// Per-entity geometry fingerprints for revision diffing, populated only
    /// when `IfcAPI::set_compute_geometry_hashes` is enabled. Parallel arrays:
    /// `geometry_hash_ids[i]` is the entity express id, `geometry_hash_values[i]`
    /// its fingerprint (see `ifc_lite_geometry::geom_hash`). Empty otherwise.
    geometry_hash_ids: Vec<u32>,
    geometry_hash_values: Vec<u64>,
    /// Typed CSG / opening diagnostics for the batch that produced this collection
    /// (the public `GeometryDiagnostics` contract). The worker merges these across
    /// batches and the loader across workers, surfacing one per-load `diagnostics`
    /// object on the streaming `complete` event. Both the flat and partitioned
    /// batch paths set it; `None` when no diagnostics were recorded.
    diagnostics: Option<ifc_lite_geometry::GeometryDiagnostics>,
}

#[wasm_bindgen]
impl MeshCollection {
    /// Get number of meshes
    #[wasm_bindgen(getter)]
    pub fn length(&self) -> usize {
        self.meshes.len()
    }

    /// Get mesh at index (clones — non-destructive). Prefer `takeMesh` on the
    /// hot streaming path; this stays for callers that read meshes more than once.
    #[wasm_bindgen]
    pub fn get(&self, index: usize) -> Option<MeshDataJs> {
        self.meshes.get(index).map(|m| MeshDataJs {
            express_id: m.express_id,
            ifc_type: m.ifc_type.clone(),
            positions: m.positions.clone(),
            normals: m.normals.clone(),
            indices: m.indices.clone(),
            color: m.color,
            shading_color: m.shading_color,
            uvs: m.uvs.clone(),
            texture_rgba: m.texture_rgba.clone(),
            texture_width: m.texture_width,
            texture_height: m.texture_height,
            texture_repeat_s: m.texture_repeat_s,
            texture_repeat_t: m.texture_repeat_t,
            texture_id: m.texture_id,
            texture_url: m.texture_url.clone(),
            geometry_class: m.geometry_class,
            origin: m.origin,
            local_bounds: m.local_bounds,
            local_to_world: m.local_to_world,
        })
    }

    /// #1097 perf: MOVE the mesh at `index` out of the collection (the Vec
    /// buffers are `std::mem::take`-n, leaving an empty stub). The streaming
    /// worker reads each mesh exactly once, so moving avoids the full vertex-
    /// data clone `get` pays — one fewer copy of positions/normals/indices/uvs/
    /// texture per mesh (the JS getters still do the single Rust→JS copy). Calling
    /// it twice for the same index yields the second call an empty mesh.
    #[wasm_bindgen(js_name = takeMesh)]
    pub fn take_mesh(&mut self, index: usize) -> Option<MeshDataJs> {
        self.meshes.get_mut(index).map(|m| MeshDataJs {
            express_id: m.express_id,
            ifc_type: std::mem::take(&mut m.ifc_type),
            positions: std::mem::take(&mut m.positions),
            normals: std::mem::take(&mut m.normals),
            indices: std::mem::take(&mut m.indices),
            color: m.color,
            shading_color: m.shading_color,
            uvs: std::mem::take(&mut m.uvs),
            texture_rgba: std::mem::take(&mut m.texture_rgba),
            texture_width: m.texture_width,
            texture_height: m.texture_height,
            texture_repeat_s: m.texture_repeat_s,
            texture_repeat_t: m.texture_repeat_t,
            texture_id: m.texture_id,
            texture_url: m.texture_url.take(),
            geometry_class: m.geometry_class,
            origin: m.origin,
            local_bounds: m.local_bounds,
            local_to_world: m.local_to_world,
        })
    }

    /// Get total vertex count across all meshes
    #[wasm_bindgen(getter, js_name = totalVertices)]
    pub fn total_vertices(&self) -> usize {
        self.meshes.iter().map(|m| m.positions.len() / 3).sum()
    }

    /// Get total triangle count across all meshes
    #[wasm_bindgen(getter, js_name = totalTriangles)]
    pub fn total_triangles(&self) -> usize {
        self.meshes.iter().map(|m| m.indices.len() / 3).sum()
    }

    /// Get RTC offset X (for converting local coords back to world coords)
    /// Add this to local X coordinates to get world X coordinates
    #[wasm_bindgen(getter, js_name = rtcOffsetX)]
    pub fn rtc_offset_x(&self) -> f64 {
        self.rtc_offset_x
    }

    /// Get RTC offset Y
    #[wasm_bindgen(getter, js_name = rtcOffsetY)]
    pub fn rtc_offset_y(&self) -> f64 {
        self.rtc_offset_y
    }

    /// Get RTC offset Z
    #[wasm_bindgen(getter, js_name = rtcOffsetZ)]
    pub fn rtc_offset_z(&self) -> f64 {
        self.rtc_offset_z
    }

    /// Check if RTC offset is significant (>10km)
    #[wasm_bindgen(js_name = hasRtcOffset)]
    pub fn has_rtc_offset(&self) -> bool {
        const THRESHOLD: f64 = 10000.0;
        self.rtc_offset_x.abs() > THRESHOLD
            || self.rtc_offset_y.abs() > THRESHOLD
            || self.rtc_offset_z.abs() > THRESHOLD
    }

    /// Get building rotation angle in radians (from IfcSite placement)
    /// Returns None if no rotation was detected
    #[wasm_bindgen(getter, js_name = buildingRotation)]
    pub fn building_rotation(&self) -> Option<f64> {
        self.building_rotation
    }

    /// Express ids for the per-entity geometry fingerprints, parallel to
    /// [`Self::geometry_hash_values`]. Empty unless geometry hashing was
    /// enabled via `IfcAPI.setComputeGeometryHashes`.
    #[wasm_bindgen(getter, js_name = geometryHashIds)]
    pub fn geometry_hash_ids(&self) -> js_sys::Uint32Array {
        js_sys::Uint32Array::from(&self.geometry_hash_ids[..])
    }

    /// Per-entity geometry fingerprints as a `BigUint64Array`, parallel to
    /// [`Self::geometry_hash_ids`]. `u64` is exposed (not hex strings) so JS
    /// can compare with `===` and key maps without allocation. Empty unless
    /// geometry hashing was enabled.
    #[wasm_bindgen(getter, js_name = geometryHashValues)]
    pub fn geometry_hash_values(&self) -> js_sys::BigUint64Array {
        js_sys::BigUint64Array::from(&self.geometry_hash_values[..])
    }

    /// Number of per-entity geometry fingerprints recorded.
    #[wasm_bindgen(getter, js_name = geometryHashCount)]
    pub fn geometry_hash_count(&self) -> usize {
        self.geometry_hash_ids.len()
    }

    /// The batch's typed CSG / opening diagnostics as a JS object (the
    /// `GeometryDiagnostics` contract), or `undefined` if none were recorded. The
    /// worker merges these across batches. One serialized value keeps the rich
    /// nested shape as a single FFI crossing instead of dozens of getters.
    #[wasm_bindgen(getter, js_name = diagnostics)]
    pub fn diagnostics(&self) -> JsValue {
        match self.diagnostics.as_ref() {
            Some(d) => serde_wasm_bindgen::to_value(d).unwrap_or(JsValue::UNDEFINED),
            None => JsValue::UNDEFINED,
        }
    }
}

impl MeshCollection {
    /// Create new empty collection
    pub fn new() -> Self {
        Self {
            meshes: Vec::new(),
            rtc_offset_x: 0.0,
            rtc_offset_y: 0.0,
            rtc_offset_z: 0.0,
            building_rotation: None,
            geometry_hash_ids: Vec::new(),
            geometry_hash_values: Vec::new(),
            diagnostics: None,
        }
    }

    /// Create new collection with capacity hint
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            meshes: Vec::with_capacity(capacity),
            rtc_offset_x: 0.0,
            rtc_offset_y: 0.0,
            rtc_offset_z: 0.0,
            building_rotation: None,
            geometry_hash_ids: Vec::new(),
            geometry_hash_values: Vec::new(),
            diagnostics: None,
        }
    }

    /// Add a mesh to the collection
    #[inline]
    pub fn add(&mut self, mesh: MeshDataJs) {
        self.meshes.push(mesh);
    }

    /// Record a per-entity geometry fingerprint (for revision diffing).
    #[inline]
    pub fn push_geometry_hash(&mut self, express_id: u32, hash: u64) {
        self.geometry_hash_ids.push(express_id);
        self.geometry_hash_values.push(hash);
    }

    /// Attach the batch's typed CSG / opening diagnostics (the public
    /// `GeometryDiagnostics` contract).
    #[inline]
    pub fn set_diagnostics(&mut self, diagnostics: ifc_lite_geometry::GeometryDiagnostics) {
        // Skip all-zero diagnostics so the `diagnostics` getter stays `undefined`
        // when no opening / CSG activity happened — lets a consumer gate on
        // presence (`if event.diagnostics`) as well as on counts.
        if !diagnostics.is_empty() {
            self.diagnostics = Some(diagnostics);
        }
    }

    /// Create from vec of meshes
    pub fn from_vec(meshes: Vec<MeshDataJs>) -> Self {
        Self {
            meshes,
            rtc_offset_x: 0.0,
            rtc_offset_y: 0.0,
            rtc_offset_z: 0.0,
            building_rotation: None,
            geometry_hash_ids: Vec::new(),
            geometry_hash_values: Vec::new(),
            diagnostics: None,
        }
    }

    /// Get number of meshes (internal)
    pub fn len(&self) -> usize {
        self.meshes.len()
    }

    /// Check if collection is empty
    pub fn is_empty(&self) -> bool {
        self.meshes.is_empty()
    }

    /// Set the RTC offset (called during parsing when large coordinates are detected)
    pub fn set_rtc_offset(&mut self, x: f64, y: f64, z: f64) {
        self.rtc_offset_x = x;
        self.rtc_offset_y = y;
        self.rtc_offset_z = z;
    }

    /// Set the building rotation angle in radians
    pub fn set_building_rotation(&mut self, rotation: Option<f64>) {
        self.building_rotation = rotation;
    }

    /// Apply RTC offset to all meshes (shift coordinates)
    /// This is used when meshes are collected first and then shifted
    pub fn apply_rtc_offset(&mut self, x: f64, y: f64, z: f64) {
        self.rtc_offset_x = x;
        self.rtc_offset_y = y;
        self.rtc_offset_z = z;
        for mesh in &mut self.meshes {
            for chunk in mesh.positions.chunks_exact_mut(3) {
                chunk[0] = (chunk[0] as f64 - x) as f32;
                chunk[1] = (chunk[1] as f64 - y) as f32;
                chunk[2] = (chunk[2] as f64 - z) as f32;
            }
        }
    }
}

impl Clone for MeshCollection {
    fn clone(&self) -> Self {
        Self {
            meshes: self
                .meshes
                .iter()
                .map(|m| MeshDataJs {
                    express_id: m.express_id,
                    ifc_type: m.ifc_type.clone(),
                    positions: m.positions.clone(),
                    normals: m.normals.clone(),
                    indices: m.indices.clone(),
                    color: m.color,
                    shading_color: m.shading_color,
                    uvs: m.uvs.clone(),
                    texture_rgba: m.texture_rgba.clone(),
                    texture_width: m.texture_width,
                    texture_height: m.texture_height,
                    texture_repeat_s: m.texture_repeat_s,
                    texture_repeat_t: m.texture_repeat_t,
                    texture_id: m.texture_id,
                    texture_url: m.texture_url.clone(),
                    geometry_class: m.geometry_class,
                    origin: m.origin,
                    local_bounds: m.local_bounds,
                    local_to_world: m.local_to_world,
                })
                .collect(),
            rtc_offset_x: self.rtc_offset_x,
            rtc_offset_y: self.rtc_offset_y,
            rtc_offset_z: self.rtc_offset_z,
            building_rotation: self.building_rotation,
            geometry_hash_ids: self.geometry_hash_ids.clone(),
            geometry_hash_values: self.geometry_hash_values.clone(),
            diagnostics: self.diagnostics.clone(),
        }
    }
}

impl Default for MeshCollection {
    fn default() -> Self {
        Self::new()
    }
}