euv-core 0.52.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
use super::*;

/// Numeric tag conversion helpers for `Euv3dSectionKind`.
impl Euv3dSectionKind {
    /// Converts a serialized `u32` section tag into an `Euv3dSectionKind`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Raw little-endian section tag.
    ///
    /// # Returns
    ///
    /// - `Option<Self>` - Decoded section kind if recognized.
    #[must_use]
    pub const fn from_u32(raw: u32) -> Option<Self> {
        match raw {
            1 => Some(Self::SceneMetadataJson),
            2 => Some(Self::Vertices),
            3 => Some(Self::Indices),
            4 => Some(Self::SkinInfluences),
            5 => Some(Self::MorphDeltas),
            6 => Some(Self::Meshlets),
            7 => Some(Self::LodTable),
            8 => Some(Self::Bvh4Nodes),
            9 => Some(Self::BvhTri4Packets),
            10 => Some(Self::BvhTriangles),
            11 => Some(Self::AnimationsBlob),
            12 => Some(Self::TexturesBlob),
            _ => None,
        }
    }

    /// Returns the numeric `u32` wire discriminant of this section kind.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Section kind reference.
    ///
    /// # Returns
    ///
    /// - `u32` - Wire tag value.
    #[must_use]
    pub const fn to_u32(&self) -> u32 {
        *self as u32
    }
}

/// Default production bake configuration enabling 4 QEM LODs, spatial meshlets, BVH4, and mipmaps.
impl Default for Euv3dBakeConfig {
    /// Creates the default `.euv3d` bake configuration (`LOD0..LOD3`, spatial meshlets, BVH4, mipmaps).
    ///
    /// # Returns
    ///
    /// - `Self` - Default `Euv3dBakeConfig`.
    fn default() -> Self {
        Self {
            lod_levels: EUV3D_DEFAULT_LOD_LEVELS,
            build_meshlets: true,
            bake_bvh4: true,
            generate_mipmaps: true,
        }
    }
}

/// Quadric Error Metric matrix operations for Garland-Heckbert edge collapse simplification.
impl QemMatrix {
    /// Builds a fundamental plane error quadric `K = p * p^T` from normalized plane `(a, b, c, d)`.
    ///
    /// # Arguments
    ///
    /// - `f64` - Plane normal X component.
    /// - `f64` - Plane normal Y component.
    /// - `f64` - Plane normal Z component.
    /// - `f64` - Signed plane offset `d`.
    ///
    /// # Returns
    ///
    /// - `Self` - Symmetric 4x4 plane quadric matrix.
    #[must_use]
    pub(crate) fn from_plane(a: f64, b: f64, c: f64, d: f64) -> Self {
        Self {
            coeffs: [
                a * a,
                a * b,
                a * c,
                a * d,
                b * b,
                b * c,
                b * d,
                c * c,
                c * d,
                d * d,
            ],
        }
    }

    /// Returns the element-wise sum of two error quadric matrices.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Left quadric matrix.
    /// - `Self` - Right quadric matrix.
    ///
    /// # Returns
    ///
    /// - `Self` - Combined quadric matrix.
    #[must_use]
    pub(crate) fn add(&self, other: Self) -> Self {
        let Self { coeffs: a } = *self;
        let Self { coeffs: b } = other;
        Self {
            coeffs: [
                a[0] + b[0],
                a[1] + b[1],
                a[2] + b[2],
                a[3] + b[3],
                a[4] + b[4],
                a[5] + b[5],
                a[6] + b[6],
                a[7] + b[7],
                a[8] + b[8],
                a[9] + b[9],
            ],
        }
    }

    /// Scales all quadric matrix entries by `factor`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Source quadric matrix.
    /// - `f64` - Scalar weight multiplier.
    ///
    /// # Returns
    ///
    /// - `Self` - Scaled quadric matrix.
    #[must_use]
    pub(crate) fn scale(&self, factor: f64) -> Self {
        let Self { coeffs: a } = *self;
        Self {
            coeffs: [
                a[0] * factor,
                a[1] * factor,
                a[2] * factor,
                a[3] * factor,
                a[4] * factor,
                a[5] * factor,
                a[6] * factor,
                a[7] * factor,
                a[8] * factor,
                a[9] * factor,
            ],
        }
    }

    /// Evaluates the quadratic error form `[x, y, z, 1] * Q * [x, y, z, 1]^T`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Quadric matrix reference.
    /// - `[f64; 3]` - Candidate 3D vertex position.
    ///
    /// # Returns
    ///
    /// - `f64` - Squared geometric distance error.
    #[must_use]
    pub(crate) fn evaluate(&self, pos: [f64; 3]) -> f64 {
        let Self { coeffs: q } = *self;
        let x: f64 = pos[0];
        let y: f64 = pos[1];
        let z: f64 = pos[2];
        q[0] * x * x
            + 2.0 * q[1] * x * y
            + 2.0 * q[2] * x * z
            + 2.0 * q[3] * x
            + q[4] * y * y
            + 2.0 * q[5] * y * z
            + 2.0 * q[6] * y
            + q[7] * z * z
            + 2.0 * q[8] * z
            + q[9]
    }

    /// Solves the 3x3 symmetric linear system `Q_upper * v = -q_linear` for the optimal contraction point.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Quadric matrix reference.
    ///
    /// # Returns
    ///
    /// - `Option<[f64; 3]>` - Optimal vertex coordinates if the 3x3 upper block is well-conditioned.
    #[must_use]
    pub(crate) fn solve_optimal(&self) -> Option<[f64; 3]> {
        let Self { coeffs: q } = *self;
        let a00: f64 = q[0];
        let a01: f64 = q[1];
        let a02: f64 = q[2];
        let a11: f64 = q[4];
        let a12: f64 = q[5];
        let a22: f64 = q[7];
        let c00: f64 = a11 * a22 - a12 * a12;
        let c01: f64 = -(a01 * a22 - a12 * a02);
        let c02: f64 = a01 * a12 - a11 * a02;
        let det: f64 = a00 * c00 + a01 * c01 + a02 * c02;
        if det.abs() <= EUV3D_QEM_EPSILON {
            return None;
        }
        let c11: f64 = a00 * a22 - a02 * a02;
        let c12: f64 = -(a00 * a12 - a01 * a02);
        let c22: f64 = a00 * a11 - a01 * a01;
        let bx: f64 = -q[3];
        let by: f64 = -q[6];
        let bz: f64 = -q[8];
        let inv_det: f64 = 1.0 / det;
        let rx: f64 = (c00 * bx + c01 * by + c02 * bz) * inv_det;
        let ry: f64 = (c01 * bx + c11 * by + c12 * bz) * inv_det;
        let rz: f64 = (c02 * bx + c12 * by + c22 * bz) * inv_det;
        if rx.is_finite() && ry.is_finite() && rz.is_finite() {
            Some([rx, ry, rz])
        } else {
            None
        }
    }
}

/// Zero-copy header validation and 64-byte-aligned section slice lookup for `Euv3dPackageView`.
impl<'a> Euv3dPackageView<'a> {
    /// Parses and CRC-verifies an `.euv3d` byte buffer with zero payload copies.
    ///
    /// # Arguments
    ///
    /// - `&'a [u8]` - Raw `.euv3d` binary bytes.
    ///
    /// # Returns
    ///
    /// - `Result<Self, String>` - Validated zero-copy view or integrity error.
    pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, String> {
        if bytes.len() < EUV3D_HEADER_BYTES {
            return Err(ERR_EUV3D_TOO_SHORT.to_string());
        }
        if bytes[..8] != EUV3D_MAGIC {
            return Err(ERR_EUV3D_BAD_MAGIC.to_string());
        }
        let version: u32 = read_u32_le(bytes, 8)?;
        if version != EUV3D_FORMAT_VERSION {
            return Err(ERR_EUV3D_BAD_VERSION.to_string());
        }
        let flags: u32 = read_u32_le(bytes, 12)?;
        let section_count: u32 = read_u32_le(bytes, 16)?;
        let table_offset: u64 = read_u64_le(bytes, 24)?;
        let content_crc32: u32 = read_u32_le(bytes, 32)?;
        let header_crc32: u32 = read_u32_le(bytes, 36)?;
        let total_bytes: u64 = read_u64_le(bytes, 40)?;
        let digest_fnv1a: u64 = read_u64_le(bytes, 48)?;
        if (total_bytes as usize) != bytes.len() {
            return Err(ERR_EUV3D_SIZE_MISMATCH.to_string());
        }
        if compute_crc32(&bytes[..36]) != header_crc32 {
            return Err(ERR_EUV3D_CRC_MISMATCH.to_string());
        }
        if compute_crc32(&bytes[EUV3D_HEADER_BYTES..]) != content_crc32 {
            return Err(ERR_EUV3D_CRC_MISMATCH.to_string());
        }
        let table_start: usize = table_offset as usize;
        let table_bytes: usize = (section_count as usize)
            .checked_mul(EUV3D_SECTION_ENTRY_BYTES)
            .ok_or_else(|| ERR_EUV3D_TABLE_OOB.to_string())?;
        let table_end: usize = table_start
            .checked_add(table_bytes)
            .ok_or_else(|| ERR_EUV3D_TABLE_OOB.to_string())?;
        if table_start < EUV3D_HEADER_BYTES || table_end > bytes.len() {
            return Err(ERR_EUV3D_TABLE_OOB.to_string());
        }
        let mut sections: Vec<Euv3dSectionEntry> = Vec::with_capacity(section_count as usize);
        for idx in 0..(section_count as usize) {
            let entry_off: usize = table_start + idx * EUV3D_SECTION_ENTRY_BYTES;
            let raw_kind: u32 = read_u32_le(bytes, entry_off)?;
            let kind: Euv3dSectionKind = Euv3dSectionKind::from_u32(raw_kind)
                .ok_or_else(|| ERR_EUV3D_UNKNOWN_SECTION.to_string())?;
            let sec_flags: u32 = read_u32_le(bytes, entry_off + 4)?;
            let offset: u64 = read_u64_le(bytes, entry_off + 8)?;
            let byte_length: u64 = read_u64_le(bytes, entry_off + 16)?;
            let element_count: u32 = read_u32_le(bytes, entry_off + 24)?;
            if !(offset as usize).is_multiple_of(EUV3D_SECTION_ALIGNMENT) {
                return Err(ERR_EUV3D_UNALIGNED_SECTION.to_string());
            }
            let sec_end: usize = (offset as usize)
                .checked_add(byte_length as usize)
                .ok_or_else(|| ERR_EUV3D_SECTION_OOB.to_string())?;
            if sec_end > bytes.len() {
                return Err(ERR_EUV3D_SECTION_OOB.to_string());
            }
            sections.push(Euv3dSectionEntry {
                kind,
                offset,
                byte_length,
                element_count,
                flags: sec_flags,
            });
        }
        let header: Euv3dHeader = Euv3dHeader {
            version,
            flags,
            section_count,
            table_offset,
            content_crc32,
            total_bytes,
            digest_fnv1a,
        };
        Ok(Self {
            raw_bytes: bytes,
            header,
            sections,
        })
    }

    /// Looks up the directory descriptor for `kind`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Validated `.euv3d` view.
    /// - `Euv3dSectionKind` - Target section identifier.
    ///
    /// # Returns
    ///
    /// - `Option<Euv3dSectionEntry>` - Matching directory entry if present.
    #[must_use]
    pub fn section_entry(&self, kind: Euv3dSectionKind) -> Option<Euv3dSectionEntry> {
        for entry in self.get_sections().iter() {
            if entry.get_kind() == kind {
                return Some(*entry);
            }
        }
        None
    }

    /// Returns a zero-copy 64-byte-aligned byte slice for `kind`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Validated `.euv3d` view.
    /// - `Euv3dSectionKind` - Target section identifier.
    ///
    /// # Returns
    ///
    /// - `Option<&'a [u8]>` - Direct borrowed slice into the backing `.euv3d` buffer.
    #[must_use]
    pub fn section_bytes(&self, kind: Euv3dSectionKind) -> Option<&'a [u8]> {
        let Self { raw_bytes, .. } = self;
        let entry: Euv3dSectionEntry = self.section_entry(kind)?;
        let start: usize = entry.get_offset() as usize;
        let end: usize = start + (entry.get_byte_length() as usize);
        raw_bytes.get(start..end)
    }
}

/// Complete `.euv3d` baking serializer and zero-rebuild binary loader.
impl Euv3dPackage {
    /// Bakes an `ImportedScene3D` into a 64-byte-aligned `.euv3d` binary buffer containing QEM LODs, spatial meshlets, and pre-baked SIMD BVH4 trees.
    ///
    /// # Arguments
    ///
    /// - `&ImportedScene3D` - Source imported Blender/glTF scene.
    /// - `&Euv3dBakeConfig` - LOD, meshlet, BVH4, and mipmap baking configuration.
    ///
    /// # Returns
    ///
    /// - `Result<Vec<u8>, String>` - Self-contained CRC-verified `.euv3d` binary archive.
    pub fn bake_from_scene(
        scene: &ImportedScene3D,
        config: &Euv3dBakeConfig,
    ) -> Result<Vec<u8>, String> {
        let mut vertices_blob: Vec<u8> = Vec::new();
        let mut vertex_total: u32 = 0;
        let mut indices_blob: Vec<u8> = Vec::new();
        let mut tri_total: u32 = 0;
        let mut skins_blob: Vec<u8> = Vec::new();
        let mut skin_total: u32 = 0;
        let mut morph_blob: Vec<u8> = Vec::new();
        let mut morph_vec_total: u32 = 0;
        let mut meshlets_blob: Vec<u8> = Vec::new();
        let mut meshlet_total: u32 = 0;
        let mut bvh4_blob: Vec<u8> = Vec::new();
        let mut bvh4_total: u32 = 0;
        let mut bvh_pkt_blob: Vec<u8> = Vec::new();
        let mut bvh_pkt_total: u32 = 0;
        let mut bvh_tri_blob: Vec<u8> = Vec::new();
        let mut bvh_tri_total: u32 = 0;
        let mut anim_blob: Vec<u8> = Vec::new();
        let mut anim_float_total: u32 = 0;
        let mut tex_blob: Vec<u8> = Vec::new();

        let mut mesh_records: Vec<Euv3dMeshRecord> = Vec::with_capacity(scene.get_meshes().len());
        let mut bvh_records: Vec<Euv3dBvhRecord> = Vec::with_capacity(scene.get_meshes().len());
        let max_lods: usize = config.get_lod_levels().clamp(1, EUV3D_DEFAULT_LOD_LEVELS);

        for mesh in scene.get_meshes().iter() {
            let chain: MeshLodChain = if max_lods > 1 {
                build_qem_lod_chain(mesh, max_lods)
            } else {
                let mut base: Mesh3D = mesh.clone();
                if config.get_build_meshlets() && base.get_tri_materials().is_empty() {
                    let (reordered, clusters): (Vec<[u32; 3]>, Vec<Meshlet3D>) =
                        build_spatial_meshlets(base.get_vertices(), base.get_indices());
                    base.set_indices(reordered);
                    base.set_meshlets(clusters);
                }
                MeshLodChain { levels: vec![base] }
            };
            let mut lod_records: Vec<Euv3dLodRecord> = Vec::with_capacity(chain.get_levels().len());
            for lod_mesh in chain.get_levels().iter() {
                let first_vertex: u32 = vertex_total;
                let vertex_count: u32 = lod_mesh.get_vertices().len() as u32;
                for v in lod_mesh.get_vertices().iter() {
                    push_vertex_bytes(&mut vertices_blob, v);
                }
                vertex_total += vertex_count;

                let first_tri: u32 = tri_total;
                let tri_count: u32 = lod_mesh.get_indices().len() as u32;
                for tri in lod_mesh.get_indices().iter() {
                    indices_blob.extend_from_slice(&tri[0].to_le_bytes());
                    indices_blob.extend_from_slice(&tri[1].to_le_bytes());
                    indices_blob.extend_from_slice(&tri[2].to_le_bytes());
                }
                tri_total += tri_count;

                let first_meshlet: u32 = meshlet_total;
                let meshlet_count: u32 = if config.get_build_meshlets() {
                    for mlet in lod_mesh.get_meshlets().iter() {
                        push_meshlet_bytes(&mut meshlets_blob, mlet);
                    }
                    lod_mesh.get_meshlets().len() as u32
                } else {
                    0
                };
                meshlet_total += meshlet_count;

                lod_records.push(Euv3dLodRecord {
                    first_vertex,
                    vertex_count,
                    first_tri,
                    tri_count,
                    first_meshlet,
                    meshlet_count,
                    bounds_min: lod_mesh.get_bounds().get_min().to_array(),
                    bounds_max: lod_mesh.get_bounds().get_max().to_array(),
                });
            }

            let lod0_ref: &Mesh3D = &chain.get_levels()[0];
            let first_skin: u32 = skin_total;
            let skin_count: u32 = lod0_ref.get_skin_influences().len() as u32;
            for skin in lod0_ref.get_skin_influences().iter() {
                push_skin_bytes(&mut skins_blob, skin);
            }
            skin_total += skin_count;

            let mut morph_records: Vec<Euv3dMorphRecord> =
                Vec::with_capacity(lod0_ref.get_morph_targets().len());
            for target in lod0_ref.get_morph_targets().iter() {
                let first_pos: u32 = morph_vec_total;
                let pos_count: u32 = target.get_delta_positions().len() as u32;
                for d in target.get_delta_positions().iter() {
                    for lane in *d {
                        morph_blob.extend_from_slice(&lane.to_le_bytes());
                    }
                }
                morph_vec_total += pos_count;

                let first_norm: u32 = morph_vec_total;
                let norm_count: u32 = target.get_delta_normals().len() as u32;
                for d in target.get_delta_normals().iter() {
                    for lane in *d {
                        morph_blob.extend_from_slice(&lane.to_le_bytes());
                    }
                }
                morph_vec_total += norm_count;

                let first_tan: u32 = morph_vec_total;
                let tan_count: u32 = target.get_delta_tangents().len() as u32;
                for d in target.get_delta_tangents().iter() {
                    for lane in *d {
                        morph_blob.extend_from_slice(&lane.to_le_bytes());
                    }
                }
                morph_vec_total += tan_count;

                morph_records.push(Euv3dMorphRecord {
                    name: target.get_name().clone(),
                    first_pos,
                    pos_count,
                    first_norm,
                    norm_count,
                    first_tan,
                    tan_count,
                });
            }

            mesh_records.push(Euv3dMeshRecord {
                name: lod0_ref.get_name().clone(),
                material: pbr_to_record(lod0_ref.get_material()),
                sub_materials: lod0_ref
                    .get_sub_materials()
                    .iter()
                    .copied()
                    .map(pbr_to_record)
                    .collect(),
                tri_materials: lod0_ref.get_tri_materials().clone(),
                material_index: lod0_ref.try_get_material_index(),
                is_closed: lod0_ref.get_is_closed(),
                lods: lod_records,
                first_skin,
                skin_count,
                morphs: morph_records,
            });

            if config.get_bake_bvh4() {
                let bvh: Bvh3D = build_local_mesh_bvh(lod0_ref);
                let first_node: u32 = bvh4_total;
                let node_count: u32 = bvh.bvh4_nodes.len() as u32;
                for node in bvh.bvh4_nodes.iter() {
                    push_bvh4_node_bytes(&mut bvh4_blob, node);
                }
                bvh4_total += node_count;

                let first_packet: u32 = bvh_pkt_total;
                let packet_count: u32 = bvh.leaf_packets.len() as u32;
                for pkt in bvh.leaf_packets.iter() {
                    push_bvh_tri4_bytes(&mut bvh_pkt_blob, pkt);
                }
                bvh_pkt_total += packet_count;

                let first_tri: u32 = bvh_tri_total;
                let tri_count: u32 = bvh.get_triangles().len() as u32;
                for tri in bvh.get_triangles().iter() {
                    push_bvh_tri_bytes(&mut bvh_tri_blob, tri);
                }
                bvh_tri_total += tri_count;

                bvh_records.push(Euv3dBvhRecord {
                    first_node,
                    node_count,
                    first_packet,
                    packet_count,
                    first_tri,
                    tri_count,
                    root_min: bvh.root_min,
                    root_max: bvh.root_max,
                    build_sah_cost: bvh.get_build_sah_cost(),
                });
            }
        }

        let collections: Vec<Euv3dCollectionRecord> = scene
            .get_scene_graph()
            .get_collections()
            .get_entries()
            .iter()
            .map(|entry: &CollectionEntry3D| Euv3dCollectionRecord {
                name: entry.get_name().clone(),
                bit_index: entry.get_bit_index(),
                visible_viewport: entry.get_visible_viewport(),
                visible_render: entry.get_visible_render(),
            })
            .collect();

        let all_morph_weights: &[f32] = scene.get_scene_graph().get_morph_weights();
        let nodes: Vec<Euv3dNodeRecord> = scene
            .get_scene_graph()
            .get_nodes()
            .iter()
            .map(|node: &SceneNode3D| {
                let w_start: usize = node.get_morph_weight_offset() as usize;
                let w_end: usize = (w_start + usize::from(node.get_morph_weight_count()))
                    .min(all_morph_weights.len());
                let morph_weights: Vec<f32> = if w_start < w_end {
                    all_morph_weights[w_start..w_end].to_vec()
                } else {
                    Vec::new()
                };
                let extras: &BlenderExtrasTags3D = node.get_extras();
                let collider_shape: u8 = match extras.get_collider() {
                    SceneColliderShape3D::None => 0,
                    SceneColliderShape3D::Box => 1,
                    SceneColliderShape3D::Sphere => 2,
                    SceneColliderShape3D::ConvexHull => 3,
                    SceneColliderShape3D::Mesh => 4,
                };
                Euv3dNodeRecord {
                    name: node.get_name().clone(),
                    parent: node.try_get_parent(),
                    translation: node.get_local_translation().to_array(),
                    rotation: node.get_local_rotation().to_array(),
                    scale: node.get_local_scale().to_array(),
                    mesh_id: node.try_get_mesh_id(),
                    skin_id: node.try_get_skin_id(),
                    camera_id: node.try_get_camera_id(),
                    light_id: node.try_get_light_id(),
                    collection_mask: node.get_collection_mask(),
                    visible: node.get_visible(),
                    morph_weights,
                    collider_shape,
                    buoyancy_density: extras.get_buoyancy_density(),
                    is_trigger: extras.get_is_trigger(),
                    cast_shadows: extras.get_cast_shadows(),
                    custom_json: extras.try_get_custom_json().clone(),
                }
            })
            .collect();

        let materials: Vec<Euv3dMaterialRecord> = scene
            .get_materials()
            .iter()
            .map(material_to_record)
            .collect();

        let mut textures: Vec<Euv3dTextureRecord> = Vec::with_capacity(scene.get_textures().len());
        for tex in scene.get_textures().iter() {
            let color_space: u8 = match tex.get_color_space() {
                TextureColorSpace::Srgb => 0,
                TextureColorSpace::Linear => 1,
                TextureColorSpace::NormalTangent => 2,
            };
            let sampler: TextureSampler3D = tex.get_sampler();
            let encode_filter: fn(TextureFilterMode) -> u8 = |mode: TextureFilterMode| match mode {
                TextureFilterMode::Nearest => 0,
                TextureFilterMode::Linear => 1,
                TextureFilterMode::NearestMipmapNearest => 2,
                TextureFilterMode::LinearMipmapNearest => 3,
                TextureFilterMode::NearestMipmapLinear => 4,
                TextureFilterMode::LinearMipmapLinear => 5,
            };
            let min_filter: u8 = encode_filter(sampler.get_min_filter());
            let mag_filter: u8 = encode_filter(sampler.get_mag_filter());
            let wrap_s: u8 = match sampler.get_wrap_s() {
                TextureWrapMode::Repeat => 0,
                TextureWrapMode::MirroredRepeat => 1,
                TextureWrapMode::ClampToEdge => 2,
            };
            let wrap_t: u8 = match sampler.get_wrap_t() {
                TextureWrapMode::Repeat => 0,
                TextureWrapMode::MirroredRepeat => 1,
                TextureWrapMode::ClampToEdge => 2,
            };
            let mip_limit: usize = if config.get_generate_mipmaps() {
                tex.get_mips().len()
            } else {
                tex.get_mips().len().min(1)
            };
            let mut mips: Vec<Euv3dTexMipRecord> = Vec::with_capacity(mip_limit);
            for mip in tex.get_mips().iter().take(mip_limit) {
                let byte_offset: u64 = tex_blob.len() as u64;
                let pixels: &[u8] = mip.get_pixels();
                tex_blob.extend_from_slice(pixels);
                mips.push(Euv3dTexMipRecord {
                    width: mip.get_width(),
                    height: mip.get_height(),
                    byte_offset,
                    byte_length: pixels.len() as u64,
                });
            }
            textures.push(Euv3dTextureRecord {
                name: tex.get_name().clone(),
                color_space,
                min_filter,
                mag_filter,
                wrap_s,
                wrap_t,
                mips,
            });
        }

        let skins: Vec<Euv3dSkinRecord> = scene
            .get_skins()
            .iter()
            .map(|skin: &ImportedSkin3D| Euv3dSkinRecord {
                name: skin.get_name().clone(),
                joints: skin.get_joints().clone(),
                skeleton_root: skin.try_get_skeleton_root(),
                inverse_bind_matrices: skin
                    .get_inverse_bind_matrices()
                    .iter()
                    .map(|m: &Mat4| m.get_elements())
                    .collect(),
            })
            .collect();

        let mut animations: Vec<Euv3dAnimClipRecord> =
            Vec::with_capacity(scene.get_animations().len());
        for clip in scene.get_animations().iter() {
            let mut samplers: Vec<Euv3dAnimSamplerRecord> =
                Vec::with_capacity(clip.get_samplers().len());
            for samp in clip.get_samplers().iter() {
                let first_time: u32 = anim_float_total;
                let time_count: u32 = samp.get_timestamps().len() as u32;
                for &t in samp.get_timestamps().iter() {
                    anim_blob.extend_from_slice(&t.to_le_bytes());
                }
                anim_float_total += time_count;

                let first_value: u32 = anim_float_total;
                let value_count: u32 = samp.get_values().len() as u32;
                for &val in samp.get_values().iter() {
                    anim_blob.extend_from_slice(&val.to_le_bytes());
                }
                anim_float_total += value_count;

                let interpolation: u8 = match samp.get_interpolation() {
                    GltfInterpolationMode::Step => 0,
                    GltfInterpolationMode::Linear => 1,
                    GltfInterpolationMode::CubicSpline => 2,
                };
                samplers.push(Euv3dAnimSamplerRecord {
                    first_time,
                    time_count,
                    first_value,
                    value_count,
                    value_stride: samp.get_value_stride() as u32,
                    interpolation,
                });
            }
            let channels: Vec<Euv3dAnimChannelRecord> = clip
                .get_channels()
                .iter()
                .map(|ch: &ImportedAnimationChannel3D| {
                    let path: u8 = match ch.get_path() {
                        GltfAnimationPath::Translation => 0,
                        GltfAnimationPath::Rotation => 1,
                        GltfAnimationPath::Scale => 2,
                        GltfAnimationPath::MorphWeights => 3,
                    };
                    Euv3dAnimChannelRecord {
                        target_node: ch.get_target_node(),
                        path,
                        sampler_index: ch.get_sampler_index() as u32,
                    }
                })
                .collect();
            animations.push(Euv3dAnimClipRecord {
                name: clip.get_name().clone(),
                duration_secs: clip.get_duration_secs(),
                samplers,
                channels,
            });
        }

        let cameras: Vec<Euv3dCameraRecord> = scene
            .get_cameras()
            .iter()
            .map(|cam: &ImportedCamera3D| match cam.get_projection() {
                GltfCameraProjection::Perspective {
                    yfov_rad,
                    aspect_ratio,
                    znear,
                    zfar,
                } => Euv3dCameraRecord {
                    name: cam.get_name().clone(),
                    is_perspective: true,
                    param_a: yfov_rad,
                    param_b: aspect_ratio.unwrap_or(-1.0),
                    znear,
                    zfar,
                },
                GltfCameraProjection::Orthographic {
                    xmag,
                    ymag,
                    znear,
                    zfar,
                } => Euv3dCameraRecord {
                    name: cam.get_name().clone(),
                    is_perspective: false,
                    param_a: xmag,
                    param_b: ymag,
                    znear,
                    zfar: Some(zfar),
                },
            })
            .collect();

        let lights: Vec<Euv3dLightRecord> = scene
            .get_lights()
            .iter()
            .map(|light: &ImportedLight3D| match light.get_kind() {
                GltfLightKind::Directional => Euv3dLightRecord {
                    name: light.get_name().clone(),
                    color: light.get_color().to_array(),
                    intensity: light.get_intensity(),
                    kind: 0,
                    range: None,
                    param_a: 0.0,
                    param_b: 0.0,
                },
                GltfLightKind::Point { range } => Euv3dLightRecord {
                    name: light.get_name().clone(),
                    color: light.get_color().to_array(),
                    intensity: light.get_intensity(),
                    kind: 1,
                    range,
                    param_a: 0.0,
                    param_b: 0.0,
                },
                GltfLightKind::Spot {
                    range,
                    inner_cone_angle,
                    outer_cone_angle,
                } => Euv3dLightRecord {
                    name: light.get_name().clone(),
                    color: light.get_color().to_array(),
                    intensity: light.get_intensity(),
                    kind: 2,
                    range,
                    param_a: inner_cone_angle,
                    param_b: outer_cone_angle,
                },
                GltfLightKind::Area { width, height } => Euv3dLightRecord {
                    name: light.get_name().clone(),
                    color: light.get_color().to_array(),
                    intensity: light.get_intensity(),
                    kind: 3,
                    range: None,
                    param_a: width,
                    param_b: height,
                },
            })
            .collect();

        let metadata: Euv3dSceneMetadata = Euv3dSceneMetadata {
            name: scene.get_name().clone(),
            generator: scene.get_generator().clone(),
            collections,
            nodes,
            meshes: mesh_records,
            bvhs: bvh_records,
            materials,
            textures,
            skins,
            animations,
            cameras,
            lights,
        };
        let meta_json: String =
            to_string(&metadata).map_err(|_| ERR_EUV3D_BAD_METADATA.to_string())?;
        let meta_bytes: Vec<u8> = meta_json.into_bytes();

        let mut payload_sections: Vec<(Euv3dSectionKind, u32, Vec<u8>)> = Vec::with_capacity(11);
        payload_sections.push((Euv3dSectionKind::SceneMetadataJson, 1, meta_bytes));
        if !vertices_blob.is_empty() {
            payload_sections.push((Euv3dSectionKind::Vertices, vertex_total, vertices_blob));
        }
        if !indices_blob.is_empty() {
            payload_sections.push((Euv3dSectionKind::Indices, tri_total, indices_blob));
        }
        if !skins_blob.is_empty() {
            payload_sections.push((Euv3dSectionKind::SkinInfluences, skin_total, skins_blob));
        }
        if !morph_blob.is_empty() {
            payload_sections.push((Euv3dSectionKind::MorphDeltas, morph_vec_total, morph_blob));
        }
        if !meshlets_blob.is_empty() {
            payload_sections.push((Euv3dSectionKind::Meshlets, meshlet_total, meshlets_blob));
        }
        if !bvh4_blob.is_empty() {
            payload_sections.push((Euv3dSectionKind::Bvh4Nodes, bvh4_total, bvh4_blob));
        }
        if !bvh_pkt_blob.is_empty() {
            payload_sections.push((
                Euv3dSectionKind::BvhTri4Packets,
                bvh_pkt_total,
                bvh_pkt_blob,
            ));
        }
        if !bvh_tri_blob.is_empty() {
            payload_sections.push((Euv3dSectionKind::BvhTriangles, bvh_tri_total, bvh_tri_blob));
        }
        if !anim_blob.is_empty() {
            payload_sections.push((
                Euv3dSectionKind::AnimationsBlob,
                anim_float_total,
                anim_blob,
            ));
        }
        if !tex_blob.is_empty() {
            payload_sections.push((
                Euv3dSectionKind::TexturesBlob,
                scene.get_textures().len() as u32,
                tex_blob,
            ));
        }

        let section_count: usize = payload_sections.len();
        let table_offset: usize = EUV3D_HEADER_BYTES;
        let mut cursor: usize =
            align_up_64(table_offset + section_count * EUV3D_SECTION_ENTRY_BYTES);
        let mut entries: Vec<Euv3dSectionEntry> = Vec::with_capacity(section_count);
        for &(kind, elem_count, ref data) in &payload_sections {
            let sec_off: usize = align_up_64(cursor);
            entries.push(Euv3dSectionEntry {
                kind,
                offset: sec_off as u64,
                byte_length: data.len() as u64,
                element_count: elem_count,
                flags: 0,
            });
            cursor = align_up_64(sec_off + data.len());
        }
        let total_bytes: usize = cursor;
        let mut out: Vec<u8> = vec![0u8; total_bytes];
        for (idx, entry) in entries.iter().enumerate() {
            let pos: usize = table_offset + idx * EUV3D_SECTION_ENTRY_BYTES;
            out[pos..pos + 4].copy_from_slice(&entry.get_kind().to_u32().to_le_bytes());
            out[pos + 4..pos + 8].copy_from_slice(&entry.get_flags().to_le_bytes());
            out[pos + 8..pos + 16].copy_from_slice(&entry.get_offset().to_le_bytes());
            out[pos + 16..pos + 24].copy_from_slice(&entry.get_byte_length().to_le_bytes());
            out[pos + 24..pos + 28].copy_from_slice(&entry.get_element_count().to_le_bytes());
            let data: &[u8] = &payload_sections[idx].2;
            let dst_start: usize = entry.get_offset() as usize;
            out[dst_start..dst_start + data.len()].copy_from_slice(data);
        }

        let mut flags: u32 = 0;
        if config.get_bake_bvh4() && bvh4_total > 0 {
            flags |= EUV3D_FLAG_HAS_BVH4;
        }
        if config.get_build_meshlets() && meshlet_total > 0 {
            flags |= EUV3D_FLAG_HAS_MESHLETS;
        }
        if max_lods > 1 {
            flags |= EUV3D_FLAG_HAS_LODS;
        }
        let content_crc32: u32 = compute_crc32(&out[EUV3D_HEADER_BYTES..]);
        let digest_fnv1a: u64 = compute_fnv1a_64(&out[EUV3D_HEADER_BYTES..]);
        out[0..8].copy_from_slice(&EUV3D_MAGIC);
        out[8..12].copy_from_slice(&EUV3D_FORMAT_VERSION.to_le_bytes());
        out[12..16].copy_from_slice(&flags.to_le_bytes());
        out[16..20].copy_from_slice(&(section_count as u32).to_le_bytes());
        out[24..32].copy_from_slice(&(table_offset as u64).to_le_bytes());
        out[32..36].copy_from_slice(&content_crc32.to_le_bytes());
        let header_crc32: u32 = compute_crc32(&out[..36]);
        out[36..40].copy_from_slice(&header_crc32.to_le_bytes());
        out[40..48].copy_from_slice(&(total_bytes as u64).to_le_bytes());
        out[48..56].copy_from_slice(&digest_fnv1a.to_le_bytes());
        Ok(out)
    }

    /// Validates and decodes an `.euv3d` archive into a `BakedAssetBundle3D` with zero-rebuild BVH4 restoration.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Raw `.euv3d` binary buffer.
    ///
    /// # Returns
    ///
    /// - `Result<BakedAssetBundle3D, String>` - Restored scene, QEM LOD chains, and ready-to-trace BVH4 trees.
    pub fn decode_bytes(bytes: &[u8]) -> Result<BakedAssetBundle3D, String> {
        let view: Euv3dPackageView<'_> = Euv3dPackageView::from_bytes(bytes)?;
        let meta_slice: &[u8] = view
            .section_bytes(Euv3dSectionKind::SceneMetadataJson)
            .ok_or_else(|| ERR_EUV3D_MISSING_METADATA.to_string())?;
        let meta_str: &str =
            from_utf8(meta_slice).map_err(|_| ERR_EUV3D_BAD_METADATA.to_string())?;
        let meta: Euv3dSceneMetadata =
            from_str(meta_str).map_err(|_| ERR_EUV3D_BAD_METADATA.to_string())?;

        let verts_slice: &[u8] = view
            .section_bytes(Euv3dSectionKind::Vertices)
            .unwrap_or(&[]);
        let idx_slice: &[u8] = view.section_bytes(Euv3dSectionKind::Indices).unwrap_or(&[]);
        let skin_slice: &[u8] = view
            .section_bytes(Euv3dSectionKind::SkinInfluences)
            .unwrap_or(&[]);
        let morph_slice: &[u8] = view
            .section_bytes(Euv3dSectionKind::MorphDeltas)
            .unwrap_or(&[]);
        let mlet_slice: &[u8] = view
            .section_bytes(Euv3dSectionKind::Meshlets)
            .unwrap_or(&[]);
        let bvh4_slice: &[u8] = view
            .section_bytes(Euv3dSectionKind::Bvh4Nodes)
            .unwrap_or(&[]);
        let bvh_pkt_slice: &[u8] = view
            .section_bytes(Euv3dSectionKind::BvhTri4Packets)
            .unwrap_or(&[]);
        let bvh_tri_slice: &[u8] = view
            .section_bytes(Euv3dSectionKind::BvhTriangles)
            .unwrap_or(&[]);
        let anim_slice: &[u8] = view
            .section_bytes(Euv3dSectionKind::AnimationsBlob)
            .unwrap_or(&[]);
        let tex_slice: &[u8] = view
            .section_bytes(Euv3dSectionKind::TexturesBlob)
            .unwrap_or(&[]);

        let mut lod_chains: Vec<MeshLodChain> = Vec::with_capacity(meta.meshes.len());
        let mut lod0_meshes: Vec<Mesh3D> = Vec::with_capacity(meta.meshes.len());
        for mesh_rec in &meta.meshes {
            let mut levels: Vec<Mesh3D> = Vec::with_capacity(mesh_rec.lods.len());
            let base_mat: PbrMaterial = record_to_pbr(&mesh_rec.material);
            let sub_mats: Vec<PbrMaterial> =
                mesh_rec.sub_materials.iter().map(record_to_pbr).collect();
            for (lod_idx, lod_rec) in mesh_rec.lods.iter().enumerate() {
                let mut vertices: Vec<Vertex3D> = Vec::with_capacity(lod_rec.vertex_count as usize);
                for v_i in 0..(lod_rec.vertex_count as usize) {
                    let off: usize =
                        ((lod_rec.first_vertex as usize) + v_i) * EUV3D_VERTEX_STRIDE_BYTES;
                    vertices.push(read_vertex_bytes(verts_slice, off)?);
                }
                let mut indices: Vec<[u32; 3]> = Vec::with_capacity(lod_rec.tri_count as usize);
                for t_i in 0..(lod_rec.tri_count as usize) {
                    let off: usize = ((lod_rec.first_tri as usize) + t_i) * EUV3D_INDEX_TRI_BYTES;
                    let i0: u32 = read_u32_le(idx_slice, off)?;
                    let i1: u32 = read_u32_le(idx_slice, off + 4)?;
                    let i2: u32 = read_u32_le(idx_slice, off + 8)?;
                    indices.push([i0, i1, i2]);
                }
                let mut meshlets: Vec<Meshlet3D> =
                    Vec::with_capacity(lod_rec.meshlet_count as usize);
                for m_i in 0..(lod_rec.meshlet_count as usize) {
                    let off: usize =
                        ((lod_rec.first_meshlet as usize) + m_i) * EUV3D_MESHLET_STRIDE_BYTES;
                    meshlets.push(read_meshlet_bytes(mlet_slice, off)?);
                }
                let bounds: AxisAlignedBox3D = AxisAlignedBox3D::new(
                    Vec3::from_array(lod_rec.bounds_min),
                    Vec3::from_array(lod_rec.bounds_max),
                );
                let mut skin_influences: Vec<MeshSkinInfluence3D> = Vec::new();
                let mut morph_targets: Vec<MorphTarget3D> = Vec::new();
                if lod_idx == 0 {
                    skin_influences.reserve(mesh_rec.skin_count as usize);
                    for s_i in 0..(mesh_rec.skin_count as usize) {
                        let off: usize =
                            ((mesh_rec.first_skin as usize) + s_i) * EUV3D_SKIN_STRIDE_BYTES;
                        skin_influences.push(read_skin_bytes(skin_slice, off)?);
                    }
                    morph_targets.reserve(mesh_rec.morphs.len());
                    for m_rec in &mesh_rec.morphs {
                        let mut delta_positions: Vec<[f32; 3]> =
                            Vec::with_capacity(m_rec.pos_count as usize);
                        for p_i in 0..(m_rec.pos_count as usize) {
                            let off: usize = ((m_rec.first_pos as usize) + p_i) * 12;
                            delta_positions.push([
                                read_f32_le(morph_slice, off)?,
                                read_f32_le(morph_slice, off + 4)?,
                                read_f32_le(morph_slice, off + 8)?,
                            ]);
                        }
                        let mut delta_normals: Vec<[f32; 3]> =
                            Vec::with_capacity(m_rec.norm_count as usize);
                        for n_i in 0..(m_rec.norm_count as usize) {
                            let off: usize = ((m_rec.first_norm as usize) + n_i) * 12;
                            delta_normals.push([
                                read_f32_le(morph_slice, off)?,
                                read_f32_le(morph_slice, off + 4)?,
                                read_f32_le(morph_slice, off + 8)?,
                            ]);
                        }
                        let mut delta_tangents: Vec<[f32; 3]> =
                            Vec::with_capacity(m_rec.tan_count as usize);
                        for t_i in 0..(m_rec.tan_count as usize) {
                            let off: usize = ((m_rec.first_tan as usize) + t_i) * 12;
                            delta_tangents.push([
                                read_f32_le(morph_slice, off)?,
                                read_f32_le(morph_slice, off + 4)?,
                                read_f32_le(morph_slice, off + 8)?,
                            ]);
                        }
                        morph_targets.push(MorphTarget3D {
                            name: m_rec.name.clone(),
                            delta_positions,
                            delta_normals,
                            delta_tangents,
                        });
                    }
                }
                let mesh_level: Mesh3D = Mesh3D {
                    name: mesh_rec.name.clone(),
                    vertices,
                    indices,
                    bounds,
                    material: base_mat,
                    sub_materials: if lod_idx == 0 {
                        sub_mats.clone()
                    } else {
                        Vec::new()
                    },
                    tri_materials: if lod_idx == 0 {
                        mesh_rec.tri_materials.clone()
                    } else {
                        Vec::new()
                    },
                    meshlets,
                    skin_influences,
                    morph_targets,
                    material_index: mesh_rec.material_index,
                    is_closed: mesh_rec.is_closed,
                };
                levels.push(mesh_level);
            }
            if let Some(first_level) = levels.first() {
                lod0_meshes.push(first_level.clone());
            }
            lod_chains.push(MeshLodChain { levels });
        }

        let mut local_bvhs: Vec<Bvh3D> = Vec::with_capacity(meta.bvhs.len());
        for bvh_rec in &meta.bvhs {
            let mut bvh4_nodes: Vec<Bvh4Node> = Vec::with_capacity(bvh_rec.node_count as usize);
            for n_i in 0..(bvh_rec.node_count as usize) {
                let off: usize =
                    ((bvh_rec.first_node as usize) + n_i) * EUV3D_BVH4_NODE_STRIDE_BYTES;
                bvh4_nodes.push(read_bvh4_node_bytes(bvh4_slice, off)?);
            }
            let mut leaf_packets: Vec<BvhTri4> = Vec::with_capacity(bvh_rec.packet_count as usize);
            for p_i in 0..(bvh_rec.packet_count as usize) {
                let off: usize =
                    ((bvh_rec.first_packet as usize) + p_i) * EUV3D_BVH_TRI4_STRIDE_BYTES;
                leaf_packets.push(read_bvh_tri4_bytes(bvh_pkt_slice, off)?);
            }
            let mut triangles: Vec<BvhTriangle> = Vec::with_capacity(bvh_rec.tri_count as usize);
            for t_i in 0..(bvh_rec.tri_count as usize) {
                let off: usize = ((bvh_rec.first_tri as usize) + t_i) * EUV3D_BVH_TRI_STRIDE_BYTES;
                triangles.push(read_bvh_tri_bytes(bvh_tri_slice, off)?);
            }
            for node in &bvh4_nodes {
                let valid: usize = (node.valid_count as usize).min(4);
                for lane in 0..valid {
                    let lc: usize = node.leaf_count[lane] as usize;
                    let ch: usize = node.child[lane] as usize;
                    if lc > 0 {
                        if ch
                            .checked_add(lc)
                            .is_none_or(|end: usize| end > leaf_packets.len())
                        {
                            return Err(ERR_EUV3D_INVALID_BVH4.to_string());
                        }
                    } else if ch >= bvh4_nodes.len() {
                        return Err(ERR_EUV3D_INVALID_BVH4.to_string());
                    }
                }
            }
            for pkt in &leaf_packets {
                for &t_idx in &pkt.tri_indices {
                    if t_idx != u32::MAX && (t_idx as usize) >= triangles.len() {
                        return Err(ERR_EUV3D_INVALID_BVH4.to_string());
                    }
                }
            }
            let geom: Vec<BvhGeomTri> = triangles.iter().map(BvhGeomTri::from_triangle).collect();
            let orig_indices: Vec<u32> = (0..triangles.len()).map(|i: usize| i as u32).collect();
            local_bvhs.push(Bvh3D {
                nodes: Vec::new(),
                triangles,
                geom,
                leaf_packets,
                flat_nodes: Vec::new(),
                bvh4_nodes,
                bvh4_src_children: Vec::new(),
                root_min: bvh_rec.root_min,
                root_max: bvh_rec.root_max,
                #[cfg(target_arch = "x86_64")]
                bvh8_nodes: Vec::new(),
                #[cfg(target_arch = "x86_64")]
                bvh8_src_children: Vec::new(),
                orig_indices,
                node_to_flat: Vec::new(),
                build_sah_cost: bvh_rec.build_sah_cost,
            });
        }

        let mut scene_graph: SceneGraph3D = SceneGraph3D::default();
        if !meta.collections.is_empty() {
            let mut active_mask: u64 = 0;
            let entries: Vec<CollectionEntry3D> = meta
                .collections
                .iter()
                .map(|c: &Euv3dCollectionRecord| {
                    if c.visible_viewport && c.bit_index < 64 {
                        active_mask |= 1u64 << u32::from(c.bit_index);
                    }
                    CollectionEntry3D {
                        name: c.name.clone(),
                        bit_index: c.bit_index,
                        visible_viewport: c.visible_viewport,
                        visible_render: c.visible_render,
                    }
                })
                .collect();
            scene_graph.set_collections(CollectionRegistry3D {
                entries,
                active_mask,
            });
        }
        for n_rec in &meta.nodes {
            let mut node: SceneNode3D = SceneNode3D::from_name(&n_rec.name, n_rec.parent);
            node.set_local_translation(Vec3::from_array(n_rec.translation));
            node.set_local_rotation(Quat::from_array(n_rec.rotation));
            node.set_local_scale(Vec3::from_array(n_rec.scale));
            node.set_mesh_id(n_rec.mesh_id);
            node.set_skin_id(n_rec.skin_id);
            node.set_camera_id(n_rec.camera_id);
            node.set_light_id(n_rec.light_id);
            node.set_collection_mask(n_rec.collection_mask);
            node.set_visible(n_rec.visible);
            let collider: SceneColliderShape3D = match n_rec.collider_shape {
                1 => SceneColliderShape3D::Box,
                2 => SceneColliderShape3D::Sphere,
                3 => SceneColliderShape3D::ConvexHull,
                4 => SceneColliderShape3D::Mesh,
                _ => SceneColliderShape3D::None,
            };
            node.set_extras(BlenderExtrasTags3D {
                collider,
                buoyancy_density: n_rec.buoyancy_density,
                is_trigger: n_rec.is_trigger,
                cast_shadows: n_rec.cast_shadows,
                custom_json: n_rec.custom_json.clone(),
            });
            let node_id: u32 = scene_graph.add_node(node);
            if !n_rec.morph_weights.is_empty() {
                scene_graph.attach_morph_weights(node_id, &n_rec.morph_weights);
            }
        }
        let _: usize = scene_graph.propagate_world_matrices();

        let materials: Vec<PrincipledMaterial3D> =
            meta.materials.iter().map(record_to_material).collect();

        let mut textures: Vec<Texture2D3D> = Vec::with_capacity(meta.textures.len());
        for t_rec in &meta.textures {
            let color_space: TextureColorSpace = match t_rec.color_space {
                1 => TextureColorSpace::Linear,
                2 => TextureColorSpace::NormalTangent,
                _ => TextureColorSpace::Srgb,
            };
            let decode_filter: fn(u8) -> TextureFilterMode = |tag: u8| match tag {
                0 => TextureFilterMode::Nearest,
                2 => TextureFilterMode::NearestMipmapNearest,
                3 => TextureFilterMode::LinearMipmapNearest,
                4 => TextureFilterMode::NearestMipmapLinear,
                5 => TextureFilterMode::LinearMipmapLinear,
                _ => TextureFilterMode::Linear,
            };
            let min_filter: TextureFilterMode = decode_filter(t_rec.min_filter);
            let mag_filter: TextureFilterMode = decode_filter(t_rec.mag_filter);
            let wrap_s: TextureWrapMode = match t_rec.wrap_s {
                1 => TextureWrapMode::MirroredRepeat,
                2 => TextureWrapMode::ClampToEdge,
                _ => TextureWrapMode::Repeat,
            };
            let wrap_t: TextureWrapMode = match t_rec.wrap_t {
                1 => TextureWrapMode::MirroredRepeat,
                2 => TextureWrapMode::ClampToEdge,
                _ => TextureWrapMode::Repeat,
            };
            let mut mips: Vec<TextureMipLevel3D> = Vec::with_capacity(t_rec.mips.len());
            for mip_rec in &t_rec.mips {
                let start: usize = mip_rec.byte_offset as usize;
                let end: usize = start
                    .checked_add(mip_rec.byte_length as usize)
                    .ok_or_else(|| ERR_EUV3D_TRUNCATED_BLOB.to_string())?;
                if end > tex_slice.len() {
                    return Err(ERR_EUV3D_TRUNCATED_BLOB.to_string());
                }
                mips.push(TextureMipLevel3D {
                    width: mip_rec.width,
                    height: mip_rec.height,
                    pixels: tex_slice[start..end].to_vec(),
                });
            }
            let (width, height): (u32, u32) = mips
                .first()
                .map(|m: &TextureMipLevel3D| (m.get_width(), m.get_height()))
                .unwrap_or((0, 0));
            textures.push(Texture2D3D {
                name: t_rec.name.clone(),
                width,
                height,
                color_space,
                sampler: TextureSampler3D::new(mag_filter, min_filter, wrap_s, wrap_t),
                mips,
            });
        }

        let skins: Vec<ImportedSkin3D> = meta
            .skins
            .iter()
            .map(|s: &Euv3dSkinRecord| ImportedSkin3D {
                name: s.name.clone(),
                joints: s.joints.clone(),
                skeleton_root: s.skeleton_root,
                inverse_bind_matrices: s
                    .inverse_bind_matrices
                    .iter()
                    .map(|arr: &[f32; 16]| Mat4::from_cols_array(*arr))
                    .collect(),
            })
            .collect();

        let mut animations: Vec<ImportedAnimationClip3D> =
            Vec::with_capacity(meta.animations.len());
        for c_rec in &meta.animations {
            let mut samplers: Vec<ImportedAnimationSampler3D> =
                Vec::with_capacity(c_rec.samplers.len());
            for s_rec in &c_rec.samplers {
                let mut timestamps: Vec<f32> = Vec::with_capacity(s_rec.time_count as usize);
                for i in 0..(s_rec.time_count as usize) {
                    timestamps.push(read_f32_le(
                        anim_slice,
                        ((s_rec.first_time as usize) + i) * 4,
                    )?);
                }
                let mut values: Vec<f32> = Vec::with_capacity(s_rec.value_count as usize);
                for i in 0..(s_rec.value_count as usize) {
                    values.push(read_f32_le(
                        anim_slice,
                        ((s_rec.first_value as usize) + i) * 4,
                    )?);
                }
                let interpolation: GltfInterpolationMode = match s_rec.interpolation {
                    0 => GltfInterpolationMode::Step,
                    2 => GltfInterpolationMode::CubicSpline,
                    _ => GltfInterpolationMode::Linear,
                };
                samplers.push(ImportedAnimationSampler3D {
                    timestamps,
                    values,
                    value_stride: s_rec.value_stride as usize,
                    interpolation,
                });
            }
            let channels: Vec<ImportedAnimationChannel3D> = c_rec
                .channels
                .iter()
                .map(|ch: &Euv3dAnimChannelRecord| {
                    let path: GltfAnimationPath = match ch.path {
                        1 => GltfAnimationPath::Rotation,
                        2 => GltfAnimationPath::Scale,
                        3 => GltfAnimationPath::MorphWeights,
                        _ => GltfAnimationPath::Translation,
                    };
                    ImportedAnimationChannel3D::new(ch.target_node, path, ch.sampler_index as usize)
                })
                .collect();
            animations.push(ImportedAnimationClip3D {
                name: c_rec.name.clone(),
                duration_secs: c_rec.duration_secs,
                samplers,
                channels,
            });
        }

        let cameras: Vec<ImportedCamera3D> = meta
            .cameras
            .iter()
            .map(|c: &Euv3dCameraRecord| {
                let projection: GltfCameraProjection = if c.is_perspective {
                    GltfCameraProjection::Perspective {
                        yfov_rad: c.param_a,
                        aspect_ratio: if c.param_b > 0.0 {
                            Some(c.param_b)
                        } else {
                            None
                        },
                        znear: c.znear,
                        zfar: c.zfar,
                    }
                } else {
                    GltfCameraProjection::Orthographic {
                        xmag: c.param_a,
                        ymag: c.param_b,
                        znear: c.znear,
                        zfar: c.zfar.unwrap_or(1000.0),
                    }
                };
                ImportedCamera3D {
                    name: c.name.clone(),
                    projection,
                }
            })
            .collect();

        let lights: Vec<ImportedLight3D> = meta
            .lights
            .iter()
            .map(|l: &Euv3dLightRecord| {
                let kind: GltfLightKind = match l.kind {
                    1 => GltfLightKind::Point { range: l.range },
                    2 => GltfLightKind::Spot {
                        range: l.range,
                        inner_cone_angle: l.param_a,
                        outer_cone_angle: l.param_b,
                    },
                    3 => GltfLightKind::Area {
                        width: l.param_a,
                        height: l.param_b,
                    },
                    _ => GltfLightKind::Directional,
                };
                ImportedLight3D {
                    name: l.name.clone(),
                    color: Vec3::from_array(l.color),
                    intensity: l.intensity,
                    kind,
                }
            })
            .collect();

        let scene: ImportedScene3D = ImportedScene3D {
            name: meta.name,
            generator: meta.generator,
            scene_graph,
            meshes: lod0_meshes,
            materials,
            textures,
            skins,
            animations,
            cameras,
            lights,
        };
        let header: Euv3dHeader = view.get_header();
        Ok(BakedAssetBundle3D {
            scene,
            lod_chains,
            local_bvhs,
            section_count: view.get_sections().len(),
            total_bytes: header.get_total_bytes() as usize,
            digest_fnv1a: header.get_digest_fnv1a(),
        })
    }
}