Skip to main content

euv_core/game/engine3d/asset/
impl.rs

1use super::*;
2
3/// Numeric tag conversion helpers for `Euv3dSectionKind`.
4impl Euv3dSectionKind {
5    /// Converts a serialized `u32` section tag into an `Euv3dSectionKind`.
6    ///
7    /// # Arguments
8    ///
9    /// - `u32` - Raw little-endian section tag.
10    ///
11    /// # Returns
12    ///
13    /// - `Option<Self>` - Decoded section kind if recognized.
14    #[must_use]
15    pub const fn from_u32(raw: u32) -> Option<Self> {
16        match raw {
17            1 => Some(Self::SceneMetadataJson),
18            2 => Some(Self::Vertices),
19            3 => Some(Self::Indices),
20            4 => Some(Self::SkinInfluences),
21            5 => Some(Self::MorphDeltas),
22            6 => Some(Self::Meshlets),
23            7 => Some(Self::LodTable),
24            8 => Some(Self::Bvh4Nodes),
25            9 => Some(Self::BvhTri4Packets),
26            10 => Some(Self::BvhTriangles),
27            11 => Some(Self::AnimationsBlob),
28            12 => Some(Self::TexturesBlob),
29            13 => Some(Self::QuantizedVertices),
30            14 => Some(Self::QuantizedSkinInfluences),
31            15 => Some(Self::QuantizedMeshlets),
32            16 => Some(Self::TextureMipTails),
33            17 => Some(Self::TextureMipHigh),
34            _ => None,
35        }
36    }
37
38    /// Returns the numeric `u32` wire discriminant of this section kind.
39    ///
40    /// # Arguments
41    ///
42    /// - `&Self` - Section kind reference.
43    ///
44    /// # Returns
45    ///
46    /// - `u32` - Wire tag value.
47    #[must_use]
48    pub const fn to_u32(&self) -> u32 {
49        *self as u32
50    }
51}
52
53/// Default production bake configuration enabling 4 QEM LODs, spatial meshlets, BVH4, and mipmaps.
54impl Default for Euv3dBakeConfig {
55    /// Creates the default `.euv3d` bake configuration (`LOD0..LOD3`, spatial meshlets, BVH4, mipmaps).
56    ///
57    /// # Returns
58    ///
59    /// - `Self` - Default `Euv3dBakeConfig`.
60    fn default() -> Self {
61        Self {
62            lod_levels: EUV3D_DEFAULT_LOD_LEVELS,
63            build_meshlets: true,
64            bake_bvh4: true,
65            generate_mipmaps: true,
66        }
67    }
68}
69
70/// Quadric Error Metric matrix operations for Garland-Heckbert edge collapse simplification.
71impl QemMatrix {
72    /// Builds a fundamental plane error quadric `K = p * p^T` from normalized plane `(a, b, c, d)`.
73    ///
74    /// # Arguments
75    ///
76    /// - `f64` - Plane normal X component.
77    /// - `f64` - Plane normal Y component.
78    /// - `f64` - Plane normal Z component.
79    /// - `f64` - Signed plane offset `d`.
80    ///
81    /// # Returns
82    ///
83    /// - `Self` - Symmetric 4x4 plane quadric matrix.
84    #[must_use]
85    pub(crate) fn from_plane(a: f64, b: f64, c: f64, d: f64) -> Self {
86        Self {
87            coeffs: [
88                a * a,
89                a * b,
90                a * c,
91                a * d,
92                b * b,
93                b * c,
94                b * d,
95                c * c,
96                c * d,
97                d * d,
98            ],
99        }
100    }
101
102    /// Returns the element-wise sum of two error quadric matrices.
103    ///
104    /// # Arguments
105    ///
106    /// - `&Self` - Left quadric matrix.
107    /// - `Self` - Right quadric matrix.
108    ///
109    /// # Returns
110    ///
111    /// - `Self` - Combined quadric matrix.
112    #[must_use]
113    pub(crate) fn add(&self, other: Self) -> Self {
114        let Self { coeffs: a } = *self;
115        let Self { coeffs: b } = other;
116        Self {
117            coeffs: [
118                a[0] + b[0],
119                a[1] + b[1],
120                a[2] + b[2],
121                a[3] + b[3],
122                a[4] + b[4],
123                a[5] + b[5],
124                a[6] + b[6],
125                a[7] + b[7],
126                a[8] + b[8],
127                a[9] + b[9],
128            ],
129        }
130    }
131
132    /// Scales all quadric matrix entries by `factor`.
133    ///
134    /// # Arguments
135    ///
136    /// - `&Self` - Source quadric matrix.
137    /// - `f64` - Scalar weight multiplier.
138    ///
139    /// # Returns
140    ///
141    /// - `Self` - Scaled quadric matrix.
142    #[must_use]
143    pub(crate) fn scale(&self, factor: f64) -> Self {
144        let Self { coeffs: a } = *self;
145        Self {
146            coeffs: [
147                a[0] * factor,
148                a[1] * factor,
149                a[2] * factor,
150                a[3] * factor,
151                a[4] * factor,
152                a[5] * factor,
153                a[6] * factor,
154                a[7] * factor,
155                a[8] * factor,
156                a[9] * factor,
157            ],
158        }
159    }
160
161    /// Evaluates the quadratic error form `[x, y, z, 1] * Q * [x, y, z, 1]^T`.
162    ///
163    /// # Arguments
164    ///
165    /// - `&Self` - Quadric matrix reference.
166    /// - `[f64; 3]` - Candidate 3D vertex position.
167    ///
168    /// # Returns
169    ///
170    /// - `f64` - Squared geometric distance error.
171    #[must_use]
172    pub(crate) fn evaluate(&self, pos: [f64; 3]) -> f64 {
173        let Self { coeffs: q } = *self;
174        let x: f64 = pos[0];
175        let y: f64 = pos[1];
176        let z: f64 = pos[2];
177        q[0] * x * x
178            + 2.0 * q[1] * x * y
179            + 2.0 * q[2] * x * z
180            + 2.0 * q[3] * x
181            + q[4] * y * y
182            + 2.0 * q[5] * y * z
183            + 2.0 * q[6] * y
184            + q[7] * z * z
185            + 2.0 * q[8] * z
186            + q[9]
187    }
188
189    /// Solves the 3x3 symmetric linear system `Q_upper * v = -q_linear` for the optimal contraction point.
190    ///
191    /// # Arguments
192    ///
193    /// - `&Self` - Quadric matrix reference.
194    ///
195    /// # Returns
196    ///
197    /// - `Option<[f64; 3]>` - Optimal vertex coordinates if the 3x3 upper block is well-conditioned.
198    #[must_use]
199    pub(crate) fn solve_optimal(&self) -> Option<[f64; 3]> {
200        let Self { coeffs: q } = *self;
201        let a00: f64 = q[0];
202        let a01: f64 = q[1];
203        let a02: f64 = q[2];
204        let a11: f64 = q[4];
205        let a12: f64 = q[5];
206        let a22: f64 = q[7];
207        let c00: f64 = a11 * a22 - a12 * a12;
208        let c01: f64 = -(a01 * a22 - a12 * a02);
209        let c02: f64 = a01 * a12 - a11 * a02;
210        let det: f64 = a00 * c00 + a01 * c01 + a02 * c02;
211        if det.abs() <= EUV3D_QEM_EPSILON {
212            return None;
213        }
214        let c11: f64 = a00 * a22 - a02 * a02;
215        let c12: f64 = -(a00 * a12 - a01 * a02);
216        let c22: f64 = a00 * a11 - a01 * a01;
217        let bx: f64 = -q[3];
218        let by: f64 = -q[6];
219        let bz: f64 = -q[8];
220        let inv_det: f64 = 1.0 / det;
221        let rx: f64 = (c00 * bx + c01 * by + c02 * bz) * inv_det;
222        let ry: f64 = (c01 * bx + c11 * by + c12 * bz) * inv_det;
223        let rz: f64 = (c02 * bx + c12 * by + c22 * bz) * inv_det;
224        if rx.is_finite() && ry.is_finite() && rz.is_finite() {
225            Some([rx, ry, rz])
226        } else {
227            None
228        }
229    }
230}
231
232/// Zero-copy header validation and 64-byte-aligned section slice lookup for `Euv3dPackageView`.
233impl<'a> Euv3dPackageView<'a> {
234    /// Parses and CRC-verifies an `.euv3d` byte buffer with zero payload copies.
235    ///
236    /// # Arguments
237    ///
238    /// - `&'a [u8]` - Raw `.euv3d` binary bytes.
239    ///
240    /// # Returns
241    ///
242    /// - `Result<Self, String>` - Validated zero-copy view or integrity error.
243    pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, String> {
244        if bytes.len() < EUV3D_HEADER_BYTES {
245            return Err(ERR_EUV3D_TOO_SHORT.to_string());
246        }
247        if bytes[..8] != EUV3D_MAGIC {
248            return Err(ERR_EUV3D_BAD_MAGIC.to_string());
249        }
250        let version: u32 = read_u32_le(bytes, 8)?;
251        if version != EUV3D_FORMAT_VERSION && version != EUV3D_FORMAT_VERSION_V2 {
252            return Err(ERR_EUV3D_BAD_VERSION.to_string());
253        }
254        let flags: u32 = read_u32_le(bytes, 12)?;
255        let section_count: u32 = read_u32_le(bytes, 16)?;
256        let table_offset: u64 = read_u64_le(bytes, 24)?;
257        let content_crc32: u32 = read_u32_le(bytes, 32)?;
258        let header_crc32: u32 = read_u32_le(bytes, 36)?;
259        let total_bytes: u64 = read_u64_le(bytes, 40)?;
260        let digest_fnv1a: u64 = read_u64_le(bytes, 48)?;
261        if (total_bytes as usize) != bytes.len() {
262            return Err(ERR_EUV3D_SIZE_MISMATCH.to_string());
263        }
264        if compute_crc32(&bytes[..36]) != header_crc32 {
265            return Err(ERR_EUV3D_CRC_MISMATCH.to_string());
266        }
267        if compute_crc32(&bytes[EUV3D_HEADER_BYTES..]) != content_crc32 {
268            return Err(ERR_EUV3D_CRC_MISMATCH.to_string());
269        }
270        let table_start: usize = table_offset as usize;
271        let table_bytes: usize = (section_count as usize)
272            .checked_mul(EUV3D_SECTION_ENTRY_BYTES)
273            .ok_or_else(|| ERR_EUV3D_TABLE_OOB.to_string())?;
274        let table_end: usize = table_start
275            .checked_add(table_bytes)
276            .ok_or_else(|| ERR_EUV3D_TABLE_OOB.to_string())?;
277        if table_start < EUV3D_HEADER_BYTES || table_end > bytes.len() {
278            return Err(ERR_EUV3D_TABLE_OOB.to_string());
279        }
280        let mut sections: Vec<Euv3dSectionEntry> = Vec::with_capacity(section_count as usize);
281        for idx in 0..(section_count as usize) {
282            let entry_off: usize = table_start + idx * EUV3D_SECTION_ENTRY_BYTES;
283            let raw_kind: u32 = read_u32_le(bytes, entry_off)?;
284            let kind: Euv3dSectionKind = Euv3dSectionKind::from_u32(raw_kind)
285                .ok_or_else(|| ERR_EUV3D_UNKNOWN_SECTION.to_string())?;
286            let sec_flags: u32 = read_u32_le(bytes, entry_off + 4)?;
287            let offset: u64 = read_u64_le(bytes, entry_off + 8)?;
288            let byte_length: u64 = read_u64_le(bytes, entry_off + 16)?;
289            let element_count: u32 = read_u32_le(bytes, entry_off + 24)?;
290            if !(offset as usize).is_multiple_of(EUV3D_SECTION_ALIGNMENT) {
291                return Err(ERR_EUV3D_UNALIGNED_SECTION.to_string());
292            }
293            let sec_end: usize = (offset as usize)
294                .checked_add(byte_length as usize)
295                .ok_or_else(|| ERR_EUV3D_SECTION_OOB.to_string())?;
296            if sec_end > bytes.len() {
297                return Err(ERR_EUV3D_SECTION_OOB.to_string());
298            }
299            sections.push(Euv3dSectionEntry {
300                kind,
301                offset,
302                byte_length,
303                element_count,
304                flags: sec_flags,
305            });
306        }
307        let header: Euv3dHeader = Euv3dHeader {
308            version,
309            flags,
310            section_count,
311            table_offset,
312            content_crc32,
313            total_bytes,
314            digest_fnv1a,
315        };
316        Ok(Self {
317            raw_bytes: bytes,
318            header,
319            sections,
320        })
321    }
322
323    /// Looks up the directory descriptor for `kind`.
324    ///
325    /// # Arguments
326    ///
327    /// - `&Self` - Validated `.euv3d` view.
328    /// - `Euv3dSectionKind` - Target section identifier.
329    ///
330    /// # Returns
331    ///
332    /// - `Option<Euv3dSectionEntry>` - Matching directory entry if present.
333    #[must_use]
334    pub fn section_entry(&self, kind: Euv3dSectionKind) -> Option<Euv3dSectionEntry> {
335        for entry in self.get_sections().iter() {
336            if entry.get_kind() == kind {
337                return Some(*entry);
338            }
339        }
340        None
341    }
342
343    /// Returns a zero-copy 64-byte-aligned byte slice for `kind`.
344    ///
345    /// # Arguments
346    ///
347    /// - `&Self` - Validated `.euv3d` view.
348    /// - `Euv3dSectionKind` - Target section identifier.
349    ///
350    /// # Returns
351    ///
352    /// - `Option<&'a [u8]>` - Direct borrowed slice into the backing `.euv3d` buffer.
353    #[must_use]
354    pub fn section_bytes(&self, kind: Euv3dSectionKind) -> Option<&'a [u8]> {
355        let Self { raw_bytes, .. } = self;
356        let entry: Euv3dSectionEntry = self.section_entry(kind)?;
357        let start: usize = entry.get_offset() as usize;
358        let end: usize = start + (entry.get_byte_length() as usize);
359        raw_bytes.get(start..end)
360    }
361
362    /// Returns the zero-copy 64-byte-aligned `.euv3d` v2 contiguous mip-tail superblock slice, if present.
363    ///
364    /// # Returns
365    ///
366    /// - `Option<&'a [u8]>` - Direct borrowed slice of `Euv3dSectionKind::TextureMipTails`.
367    #[must_use]
368    pub fn mip_tail_bytes(&self) -> Option<&'a [u8]> {
369        self.section_bytes(Euv3dSectionKind::TextureMipTails)
370    }
371
372    /// Parses the compact binary mip-tail directory at the start of `TextureMipTails` with zero JSON parsing.
373    ///
374    /// # Returns
375    ///
376    /// - `Result<Vec<Euv3dMipTailEntry>, String>` - Parsed mip-tail directory entries aligned with scene texture indices.
377    pub fn parse_mip_tail_directory(&self) -> Result<Vec<Euv3dMipTailEntry>, String> {
378        let Some(blob) = self.mip_tail_bytes() else {
379            return Ok(Vec::new());
380        };
381        if blob.len() < 4 {
382            return Err(ERR_EUV3D_TRUNCATED_BLOB.to_string());
383        }
384        let tex_count: usize = read_u32_le(blob, 0)? as usize;
385        let table_end: usize = 4usize
386            .checked_add(tex_count.saturating_mul(12))
387            .ok_or_else(|| ERR_EUV3D_TRUNCATED_BLOB.to_string())?;
388        if table_end > blob.len() {
389            return Err(ERR_EUV3D_TRUNCATED_BLOB.to_string());
390        }
391        let mut out: Vec<Euv3dMipTailEntry> = Vec::with_capacity(tex_count);
392        for idx in 0..tex_count {
393            let off: usize = 4 + idx * 12;
394            let width: u32 = u32::from(read_u16_le(blob, off)?);
395            let height: u32 = u32::from(read_u16_le(blob, off + 2)?);
396            let cs: TextureColorSpace = match blob[off + 4] {
397                1 => TextureColorSpace::Linear,
398                2 => TextureColorSpace::NormalTangent,
399                _ => TextureColorSpace::Srgb,
400            };
401            let mip_count: u8 = blob[off + 5];
402            let first_byte_offset: usize = read_u32_le(blob, off + 8)? as usize;
403            out.push(Euv3dMipTailEntry::new(
404                width,
405                height,
406                cs,
407                mip_count,
408                first_byte_offset,
409            ));
410        }
411        Ok(out)
412    }
413
414    /// Reads all 64-byte `QuantizedMeshlet3D` descriptors from an `.euv3d` v2 archive.
415    ///
416    /// # Returns
417    ///
418    /// - `Result<Vec<QuantizedMeshlet3D>, String>` - Decoded cache-line meshlets with bounding spheres and normal cones.
419    pub fn read_quantized_meshlets(&self) -> Result<Vec<QuantizedMeshlet3D>, String> {
420        let Some(slice) = self.section_bytes(Euv3dSectionKind::QuantizedMeshlets) else {
421            return Ok(Vec::new());
422        };
423        let count: usize = slice.len() / EUV3D_V2_MESHLET_STRIDE_BYTES;
424        let mut out: Vec<QuantizedMeshlet3D> = Vec::with_capacity(count);
425        for idx in 0..count {
426            out.push(read_quantized_meshlet_bytes(
427                slice,
428                idx * EUV3D_V2_MESHLET_STRIDE_BYTES,
429            )?);
430        }
431        Ok(out)
432    }
433}
434
435/// Complete `.euv3d` baking serializer and zero-rebuild binary loader.
436impl Euv3dPackage {
437    /// Bakes an `ImportedScene3D` into a 64-byte-aligned `.euv3d` binary buffer containing QEM LODs, spatial meshlets, and pre-baked SIMD BVH4 trees.
438    ///
439    /// # Arguments
440    ///
441    /// - `&ImportedScene3D` - Source imported Blender/glTF scene.
442    /// - `&Euv3dBakeConfig` - LOD, meshlet, BVH4, and mipmap baking configuration.
443    ///
444    /// # Returns
445    ///
446    /// - `Result<Vec<u8>, String>` - Self-contained CRC-verified `.euv3d` binary archive.
447    pub fn bake_from_scene(
448        scene: &ImportedScene3D,
449        config: &Euv3dBakeConfig,
450    ) -> Result<Vec<u8>, String> {
451        let mut vertices_blob: Vec<u8> = Vec::new();
452        let mut vertex_total: u32 = 0;
453        let mut indices_blob: Vec<u8> = Vec::new();
454        let mut tri_total: u32 = 0;
455        let mut skins_blob: Vec<u8> = Vec::new();
456        let mut skin_total: u32 = 0;
457        let mut morph_blob: Vec<u8> = Vec::new();
458        let mut morph_vec_total: u32 = 0;
459        let mut meshlets_blob: Vec<u8> = Vec::new();
460        let mut meshlet_total: u32 = 0;
461        let mut bvh4_blob: Vec<u8> = Vec::new();
462        let mut bvh4_total: u32 = 0;
463        let mut bvh_pkt_blob: Vec<u8> = Vec::new();
464        let mut bvh_pkt_total: u32 = 0;
465        let mut bvh_tri_blob: Vec<u8> = Vec::new();
466        let mut bvh_tri_total: u32 = 0;
467        let mut anim_blob: Vec<u8> = Vec::new();
468        let mut anim_float_total: u32 = 0;
469        let mut tex_blob: Vec<u8> = Vec::new();
470
471        let mut mesh_records: Vec<Euv3dMeshRecord> = Vec::with_capacity(scene.get_meshes().len());
472        let mut bvh_records: Vec<Euv3dBvhRecord> = Vec::with_capacity(scene.get_meshes().len());
473        let max_lods: usize = config.get_lod_levels().clamp(1, EUV3D_DEFAULT_LOD_LEVELS);
474
475        for mesh in scene.get_meshes().iter() {
476            let chain: MeshLodChain = if max_lods > 1 {
477                build_qem_lod_chain(mesh, max_lods)
478            } else {
479                let mut base: Mesh3D = mesh.clone();
480                if config.get_build_meshlets() && base.get_tri_materials().is_empty() {
481                    let (reordered, clusters): (Vec<[u32; 3]>, Vec<Meshlet3D>) =
482                        build_spatial_meshlets(base.get_vertices(), base.get_indices());
483                    base.set_indices(reordered);
484                    base.set_meshlets(clusters);
485                }
486                MeshLodChain { levels: vec![base] }
487            };
488            let mut lod_records: Vec<Euv3dLodRecord> = Vec::with_capacity(chain.get_levels().len());
489            for lod_mesh in chain.get_levels().iter() {
490                let first_vertex: u32 = vertex_total;
491                let vertex_count: u32 = lod_mesh.get_vertices().len() as u32;
492                for v in lod_mesh.get_vertices().iter() {
493                    push_vertex_bytes(&mut vertices_blob, v);
494                }
495                vertex_total += vertex_count;
496
497                let first_tri: u32 = tri_total;
498                let tri_count: u32 = lod_mesh.get_indices().len() as u32;
499                for tri in lod_mesh.get_indices().iter() {
500                    indices_blob.extend_from_slice(&tri[0].to_le_bytes());
501                    indices_blob.extend_from_slice(&tri[1].to_le_bytes());
502                    indices_blob.extend_from_slice(&tri[2].to_le_bytes());
503                }
504                tri_total += tri_count;
505
506                let first_meshlet: u32 = meshlet_total;
507                let meshlet_count: u32 = if config.get_build_meshlets() {
508                    for mlet in lod_mesh.get_meshlets().iter() {
509                        push_meshlet_bytes(&mut meshlets_blob, mlet);
510                    }
511                    lod_mesh.get_meshlets().len() as u32
512                } else {
513                    0
514                };
515                meshlet_total += meshlet_count;
516
517                lod_records.push(Euv3dLodRecord {
518                    first_vertex,
519                    vertex_count,
520                    first_tri,
521                    tri_count,
522                    first_meshlet,
523                    meshlet_count,
524                    bounds_min: lod_mesh.get_bounds().get_min().to_array(),
525                    bounds_max: lod_mesh.get_bounds().get_max().to_array(),
526                });
527            }
528
529            let lod0_ref: &Mesh3D = &chain.get_levels()[0];
530            let first_skin: u32 = skin_total;
531            let skin_count: u32 = lod0_ref.get_skin_influences().len() as u32;
532            for skin in lod0_ref.get_skin_influences().iter() {
533                push_skin_bytes(&mut skins_blob, skin);
534            }
535            skin_total += skin_count;
536
537            let mut morph_records: Vec<Euv3dMorphRecord> =
538                Vec::with_capacity(lod0_ref.get_morph_targets().len());
539            for target in lod0_ref.get_morph_targets().iter() {
540                let first_pos: u32 = morph_vec_total;
541                let pos_count: u32 = target.get_delta_positions().len() as u32;
542                for d in target.get_delta_positions().iter() {
543                    for lane in *d {
544                        morph_blob.extend_from_slice(&lane.to_le_bytes());
545                    }
546                }
547                morph_vec_total += pos_count;
548
549                let first_norm: u32 = morph_vec_total;
550                let norm_count: u32 = target.get_delta_normals().len() as u32;
551                for d in target.get_delta_normals().iter() {
552                    for lane in *d {
553                        morph_blob.extend_from_slice(&lane.to_le_bytes());
554                    }
555                }
556                morph_vec_total += norm_count;
557
558                let first_tan: u32 = morph_vec_total;
559                let tan_count: u32 = target.get_delta_tangents().len() as u32;
560                for d in target.get_delta_tangents().iter() {
561                    for lane in *d {
562                        morph_blob.extend_from_slice(&lane.to_le_bytes());
563                    }
564                }
565                morph_vec_total += tan_count;
566
567                morph_records.push(Euv3dMorphRecord {
568                    name: target.get_name().clone(),
569                    first_pos,
570                    pos_count,
571                    first_norm,
572                    norm_count,
573                    first_tan,
574                    tan_count,
575                });
576            }
577
578            mesh_records.push(Euv3dMeshRecord {
579                name: lod0_ref.get_name().clone(),
580                material: pbr_to_record(lod0_ref.get_material()),
581                sub_materials: lod0_ref
582                    .get_sub_materials()
583                    .iter()
584                    .copied()
585                    .map(pbr_to_record)
586                    .collect(),
587                tri_materials: lod0_ref.get_tri_materials().clone(),
588                material_index: lod0_ref.try_get_material_index(),
589                is_closed: lod0_ref.get_is_closed(),
590                lods: lod_records,
591                first_skin,
592                skin_count,
593                morphs: morph_records,
594            });
595
596            if config.get_bake_bvh4() {
597                let bvh: Bvh3D = build_local_mesh_bvh(lod0_ref);
598                let first_node: u32 = bvh4_total;
599                let node_count: u32 = bvh.bvh4_nodes.len() as u32;
600                for node in bvh.bvh4_nodes.iter() {
601                    push_bvh4_node_bytes(&mut bvh4_blob, node);
602                }
603                bvh4_total += node_count;
604
605                let first_packet: u32 = bvh_pkt_total;
606                let packet_count: u32 = bvh.leaf_packets.len() as u32;
607                for pkt in bvh.leaf_packets.iter() {
608                    push_bvh_tri4_bytes(&mut bvh_pkt_blob, pkt);
609                }
610                bvh_pkt_total += packet_count;
611
612                let first_tri: u32 = bvh_tri_total;
613                let tri_count: u32 = bvh.get_triangles().len() as u32;
614                for tri in bvh.get_triangles().iter() {
615                    push_bvh_tri_bytes(&mut bvh_tri_blob, tri);
616                }
617                bvh_tri_total += tri_count;
618
619                bvh_records.push(Euv3dBvhRecord {
620                    first_node,
621                    node_count,
622                    first_packet,
623                    packet_count,
624                    first_tri,
625                    tri_count,
626                    root_min: bvh.root_min,
627                    root_max: bvh.root_max,
628                    build_sah_cost: bvh.get_build_sah_cost(),
629                });
630            }
631        }
632
633        let collections: Vec<Euv3dCollectionRecord> = scene
634            .get_scene_graph()
635            .get_collections()
636            .get_entries()
637            .iter()
638            .map(|entry: &CollectionEntry3D| Euv3dCollectionRecord {
639                name: entry.get_name().clone(),
640                bit_index: entry.get_bit_index(),
641                visible_viewport: entry.get_visible_viewport(),
642                visible_render: entry.get_visible_render(),
643            })
644            .collect();
645
646        let all_morph_weights: &[f32] = scene.get_scene_graph().get_morph_weights();
647        let nodes: Vec<Euv3dNodeRecord> = scene
648            .get_scene_graph()
649            .get_nodes()
650            .iter()
651            .map(|node: &SceneNode3D| {
652                let w_start: usize = node.get_morph_weight_offset() as usize;
653                let w_end: usize = (w_start + usize::from(node.get_morph_weight_count()))
654                    .min(all_morph_weights.len());
655                let morph_weights: Vec<f32> = if w_start < w_end {
656                    all_morph_weights[w_start..w_end].to_vec()
657                } else {
658                    Vec::new()
659                };
660                let extras: &BlenderExtrasTags3D = node.get_extras();
661                let collider_shape: u8 = match extras.get_collider() {
662                    SceneColliderShape3D::None => 0,
663                    SceneColliderShape3D::Box => 1,
664                    SceneColliderShape3D::Sphere => 2,
665                    SceneColliderShape3D::ConvexHull => 3,
666                    SceneColliderShape3D::Mesh => 4,
667                };
668                Euv3dNodeRecord {
669                    name: node.get_name().clone(),
670                    parent: node.try_get_parent(),
671                    translation: node.get_local_translation().to_array(),
672                    rotation: node.get_local_rotation().to_array(),
673                    scale: node.get_local_scale().to_array(),
674                    mesh_id: node.try_get_mesh_id(),
675                    skin_id: node.try_get_skin_id(),
676                    camera_id: node.try_get_camera_id(),
677                    light_id: node.try_get_light_id(),
678                    collection_mask: node.get_collection_mask(),
679                    visible: node.get_visible(),
680                    morph_weights,
681                    collider_shape,
682                    buoyancy_density: extras.get_buoyancy_density(),
683                    is_trigger: extras.get_is_trigger(),
684                    cast_shadows: extras.get_cast_shadows(),
685                    custom_json: extras.try_get_custom_json().clone(),
686                }
687            })
688            .collect();
689
690        let materials: Vec<Euv3dMaterialRecord> = scene
691            .get_materials()
692            .iter()
693            .map(material_to_record)
694            .collect();
695
696        let mut textures: Vec<Euv3dTextureRecord> = Vec::with_capacity(scene.get_textures().len());
697        for tex in scene.get_textures().iter() {
698            let color_space: u8 = match tex.get_color_space() {
699                TextureColorSpace::Srgb => 0,
700                TextureColorSpace::Linear => 1,
701                TextureColorSpace::NormalTangent => 2,
702            };
703            let sampler: TextureSampler3D = tex.get_sampler();
704            let encode_filter: fn(TextureFilterMode) -> u8 = |mode: TextureFilterMode| match mode {
705                TextureFilterMode::Nearest => 0,
706                TextureFilterMode::Linear => 1,
707                TextureFilterMode::NearestMipmapNearest => 2,
708                TextureFilterMode::LinearMipmapNearest => 3,
709                TextureFilterMode::NearestMipmapLinear => 4,
710                TextureFilterMode::LinearMipmapLinear => 5,
711            };
712            let min_filter: u8 = encode_filter(sampler.get_min_filter());
713            let mag_filter: u8 = encode_filter(sampler.get_mag_filter());
714            let wrap_s: u8 = match sampler.get_wrap_s() {
715                TextureWrapMode::Repeat => 0,
716                TextureWrapMode::MirroredRepeat => 1,
717                TextureWrapMode::ClampToEdge => 2,
718            };
719            let wrap_t: u8 = match sampler.get_wrap_t() {
720                TextureWrapMode::Repeat => 0,
721                TextureWrapMode::MirroredRepeat => 1,
722                TextureWrapMode::ClampToEdge => 2,
723            };
724            let mip_limit: usize = if config.get_generate_mipmaps() {
725                tex.get_mips().len()
726            } else {
727                tex.get_mips().len().min(1)
728            };
729            let mut mips: Vec<Euv3dTexMipRecord> = Vec::with_capacity(mip_limit);
730            for mip in tex.get_mips().iter().take(mip_limit) {
731                let byte_offset: u64 = tex_blob.len() as u64;
732                let pixels: &[u8] = mip.get_pixels();
733                tex_blob.extend_from_slice(pixels);
734                mips.push(Euv3dTexMipRecord {
735                    width: mip.get_width(),
736                    height: mip.get_height(),
737                    byte_offset,
738                    byte_length: pixels.len() as u64,
739                    is_mip_tail: false,
740                });
741            }
742            textures.push(Euv3dTextureRecord {
743                name: tex.get_name().clone(),
744                color_space,
745                min_filter,
746                mag_filter,
747                wrap_s,
748                wrap_t,
749                mips,
750            });
751        }
752
753        let skins: Vec<Euv3dSkinRecord> = scene
754            .get_skins()
755            .iter()
756            .map(|skin: &ImportedSkin3D| Euv3dSkinRecord {
757                name: skin.get_name().clone(),
758                joints: skin.get_joints().clone(),
759                skeleton_root: skin.try_get_skeleton_root(),
760                inverse_bind_matrices: skin
761                    .get_inverse_bind_matrices()
762                    .iter()
763                    .map(|m: &Mat4| m.get_elements())
764                    .collect(),
765            })
766            .collect();
767
768        let mut animations: Vec<Euv3dAnimClipRecord> =
769            Vec::with_capacity(scene.get_animations().len());
770        for clip in scene.get_animations().iter() {
771            let mut samplers: Vec<Euv3dAnimSamplerRecord> =
772                Vec::with_capacity(clip.get_samplers().len());
773            for samp in clip.get_samplers().iter() {
774                let first_time: u32 = anim_float_total;
775                let time_count: u32 = samp.get_timestamps().len() as u32;
776                for &t in samp.get_timestamps().iter() {
777                    anim_blob.extend_from_slice(&t.to_le_bytes());
778                }
779                anim_float_total += time_count;
780
781                let first_value: u32 = anim_float_total;
782                let value_count: u32 = samp.get_values().len() as u32;
783                for &val in samp.get_values().iter() {
784                    anim_blob.extend_from_slice(&val.to_le_bytes());
785                }
786                anim_float_total += value_count;
787
788                let interpolation: u8 = match samp.get_interpolation() {
789                    GltfInterpolationMode::Step => 0,
790                    GltfInterpolationMode::Linear => 1,
791                    GltfInterpolationMode::CubicSpline => 2,
792                };
793                samplers.push(Euv3dAnimSamplerRecord {
794                    first_time,
795                    time_count,
796                    first_value,
797                    value_count,
798                    value_stride: samp.get_value_stride() as u32,
799                    interpolation,
800                });
801            }
802            let channels: Vec<Euv3dAnimChannelRecord> = clip
803                .get_channels()
804                .iter()
805                .map(|ch: &ImportedAnimationChannel3D| {
806                    let path: u8 = match ch.get_path() {
807                        GltfAnimationPath::Translation => 0,
808                        GltfAnimationPath::Rotation => 1,
809                        GltfAnimationPath::Scale => 2,
810                        GltfAnimationPath::MorphWeights => 3,
811                    };
812                    Euv3dAnimChannelRecord {
813                        target_node: ch.get_target_node(),
814                        path,
815                        sampler_index: ch.get_sampler_index() as u32,
816                    }
817                })
818                .collect();
819            animations.push(Euv3dAnimClipRecord {
820                name: clip.get_name().clone(),
821                duration_secs: clip.get_duration_secs(),
822                samplers,
823                channels,
824            });
825        }
826
827        let cameras: Vec<Euv3dCameraRecord> = scene
828            .get_cameras()
829            .iter()
830            .map(|cam: &ImportedCamera3D| match cam.get_projection() {
831                GltfCameraProjection::Perspective {
832                    yfov_rad,
833                    aspect_ratio,
834                    znear,
835                    zfar,
836                } => Euv3dCameraRecord {
837                    name: cam.get_name().clone(),
838                    is_perspective: true,
839                    param_a: yfov_rad,
840                    param_b: aspect_ratio.unwrap_or(-1.0),
841                    znear,
842                    zfar,
843                },
844                GltfCameraProjection::Orthographic {
845                    xmag,
846                    ymag,
847                    znear,
848                    zfar,
849                } => Euv3dCameraRecord {
850                    name: cam.get_name().clone(),
851                    is_perspective: false,
852                    param_a: xmag,
853                    param_b: ymag,
854                    znear,
855                    zfar: Some(zfar),
856                },
857            })
858            .collect();
859
860        let lights: Vec<Euv3dLightRecord> = scene
861            .get_lights()
862            .iter()
863            .map(|light: &ImportedLight3D| match light.get_kind() {
864                GltfLightKind::Directional => Euv3dLightRecord {
865                    name: light.get_name().clone(),
866                    color: light.get_color().to_array(),
867                    intensity: light.get_intensity(),
868                    kind: 0,
869                    range: None,
870                    param_a: 0.0,
871                    param_b: 0.0,
872                },
873                GltfLightKind::Point { range } => Euv3dLightRecord {
874                    name: light.get_name().clone(),
875                    color: light.get_color().to_array(),
876                    intensity: light.get_intensity(),
877                    kind: 1,
878                    range,
879                    param_a: 0.0,
880                    param_b: 0.0,
881                },
882                GltfLightKind::Spot {
883                    range,
884                    inner_cone_angle,
885                    outer_cone_angle,
886                } => Euv3dLightRecord {
887                    name: light.get_name().clone(),
888                    color: light.get_color().to_array(),
889                    intensity: light.get_intensity(),
890                    kind: 2,
891                    range,
892                    param_a: inner_cone_angle,
893                    param_b: outer_cone_angle,
894                },
895                GltfLightKind::Area { width, height } => Euv3dLightRecord {
896                    name: light.get_name().clone(),
897                    color: light.get_color().to_array(),
898                    intensity: light.get_intensity(),
899                    kind: 3,
900                    range: None,
901                    param_a: width,
902                    param_b: height,
903                },
904            })
905            .collect();
906
907        let metadata: Euv3dSceneMetadata = Euv3dSceneMetadata {
908            name: scene.get_name().clone(),
909            generator: scene.get_generator().clone(),
910            collections,
911            nodes,
912            meshes: mesh_records,
913            bvhs: bvh_records,
914            materials,
915            textures,
916            skins,
917            animations,
918            cameras,
919            lights,
920        };
921        let meta_json: String =
922            to_string(&metadata).map_err(|_| ERR_EUV3D_BAD_METADATA.to_string())?;
923        let meta_bytes: Vec<u8> = meta_json.into_bytes();
924
925        let mut payload_sections: Vec<(Euv3dSectionKind, u32, Vec<u8>)> = Vec::with_capacity(11);
926        payload_sections.push((Euv3dSectionKind::SceneMetadataJson, 1, meta_bytes));
927        if !vertices_blob.is_empty() {
928            payload_sections.push((Euv3dSectionKind::Vertices, vertex_total, vertices_blob));
929        }
930        if !indices_blob.is_empty() {
931            payload_sections.push((Euv3dSectionKind::Indices, tri_total, indices_blob));
932        }
933        if !skins_blob.is_empty() {
934            payload_sections.push((Euv3dSectionKind::SkinInfluences, skin_total, skins_blob));
935        }
936        if !morph_blob.is_empty() {
937            payload_sections.push((Euv3dSectionKind::MorphDeltas, morph_vec_total, morph_blob));
938        }
939        if !meshlets_blob.is_empty() {
940            payload_sections.push((Euv3dSectionKind::Meshlets, meshlet_total, meshlets_blob));
941        }
942        if !bvh4_blob.is_empty() {
943            payload_sections.push((Euv3dSectionKind::Bvh4Nodes, bvh4_total, bvh4_blob));
944        }
945        if !bvh_pkt_blob.is_empty() {
946            payload_sections.push((
947                Euv3dSectionKind::BvhTri4Packets,
948                bvh_pkt_total,
949                bvh_pkt_blob,
950            ));
951        }
952        if !bvh_tri_blob.is_empty() {
953            payload_sections.push((Euv3dSectionKind::BvhTriangles, bvh_tri_total, bvh_tri_blob));
954        }
955        if !anim_blob.is_empty() {
956            payload_sections.push((
957                Euv3dSectionKind::AnimationsBlob,
958                anim_float_total,
959                anim_blob,
960            ));
961        }
962        if !tex_blob.is_empty() {
963            payload_sections.push((
964                Euv3dSectionKind::TexturesBlob,
965                scene.get_textures().len() as u32,
966                tex_blob,
967            ));
968        }
969
970        let section_count: usize = payload_sections.len();
971        let table_offset: usize = EUV3D_HEADER_BYTES;
972        let mut cursor: usize =
973            align_up_64(table_offset + section_count * EUV3D_SECTION_ENTRY_BYTES);
974        let mut entries: Vec<Euv3dSectionEntry> = Vec::with_capacity(section_count);
975        for &(kind, elem_count, ref data) in &payload_sections {
976            let sec_off: usize = align_up_64(cursor);
977            entries.push(Euv3dSectionEntry {
978                kind,
979                offset: sec_off as u64,
980                byte_length: data.len() as u64,
981                element_count: elem_count,
982                flags: 0,
983            });
984            cursor = align_up_64(sec_off + data.len());
985        }
986        let total_bytes: usize = cursor;
987        let mut out: Vec<u8> = vec![0u8; total_bytes];
988        for (idx, entry) in entries.iter().enumerate() {
989            let pos: usize = table_offset + idx * EUV3D_SECTION_ENTRY_BYTES;
990            out[pos..pos + 4].copy_from_slice(&entry.get_kind().to_u32().to_le_bytes());
991            out[pos + 4..pos + 8].copy_from_slice(&entry.get_flags().to_le_bytes());
992            out[pos + 8..pos + 16].copy_from_slice(&entry.get_offset().to_le_bytes());
993            out[pos + 16..pos + 24].copy_from_slice(&entry.get_byte_length().to_le_bytes());
994            out[pos + 24..pos + 28].copy_from_slice(&entry.get_element_count().to_le_bytes());
995            let data: &[u8] = &payload_sections[idx].2;
996            let dst_start: usize = entry.get_offset() as usize;
997            out[dst_start..dst_start + data.len()].copy_from_slice(data);
998        }
999
1000        let mut flags: u32 = 0;
1001        if config.get_bake_bvh4() && bvh4_total > 0 {
1002            flags |= EUV3D_FLAG_HAS_BVH4;
1003        }
1004        if config.get_build_meshlets() && meshlet_total > 0 {
1005            flags |= EUV3D_FLAG_HAS_MESHLETS;
1006        }
1007        if max_lods > 1 {
1008            flags |= EUV3D_FLAG_HAS_LODS;
1009        }
1010        let content_crc32: u32 = compute_crc32(&out[EUV3D_HEADER_BYTES..]);
1011        let digest_fnv1a: u64 = compute_fnv1a_64(&out[EUV3D_HEADER_BYTES..]);
1012        out[0..8].copy_from_slice(&EUV3D_MAGIC);
1013        out[8..12].copy_from_slice(&EUV3D_FORMAT_VERSION.to_le_bytes());
1014        out[12..16].copy_from_slice(&flags.to_le_bytes());
1015        out[16..20].copy_from_slice(&(section_count as u32).to_le_bytes());
1016        out[24..32].copy_from_slice(&(table_offset as u64).to_le_bytes());
1017        out[32..36].copy_from_slice(&content_crc32.to_le_bytes());
1018        let header_crc32: u32 = compute_crc32(&out[..36]);
1019        out[36..40].copy_from_slice(&header_crc32.to_le_bytes());
1020        out[40..48].copy_from_slice(&(total_bytes as u64).to_le_bytes());
1021        out[48..56].copy_from_slice(&digest_fnv1a.to_le_bytes());
1022        Ok(out)
1023    }
1024
1025    /// Validates and decodes an `.euv3d` archive into a `BakedAssetBundle3D` with zero-rebuild BVH4 restoration.
1026    ///
1027    /// # Arguments
1028    ///
1029    /// - `&[u8]` - Raw `.euv3d` binary buffer.
1030    ///
1031    /// # Returns
1032    ///
1033    /// - `Result<BakedAssetBundle3D, String>` - Restored scene, QEM LOD chains, and ready-to-trace BVH4 trees.
1034    pub fn decode_bytes(bytes: &[u8]) -> Result<BakedAssetBundle3D, String> {
1035        let view: Euv3dPackageView<'_> = Euv3dPackageView::from_bytes(bytes)?;
1036        let meta_slice: &[u8] = view
1037            .section_bytes(Euv3dSectionKind::SceneMetadataJson)
1038            .ok_or_else(|| ERR_EUV3D_MISSING_METADATA.to_string())?;
1039        let meta_str: &str =
1040            from_utf8(meta_slice).map_err(|_| ERR_EUV3D_BAD_METADATA.to_string())?;
1041        let meta: Euv3dSceneMetadata =
1042            from_str(meta_str).map_err(|_| ERR_EUV3D_BAD_METADATA.to_string())?;
1043
1044        let verts_slice: &[u8] = view
1045            .section_bytes(Euv3dSectionKind::Vertices)
1046            .unwrap_or(&[]);
1047        let idx_slice: &[u8] = view.section_bytes(Euv3dSectionKind::Indices).unwrap_or(&[]);
1048        let skin_slice: &[u8] = view
1049            .section_bytes(Euv3dSectionKind::SkinInfluences)
1050            .unwrap_or(&[]);
1051        let morph_slice: &[u8] = view
1052            .section_bytes(Euv3dSectionKind::MorphDeltas)
1053            .unwrap_or(&[]);
1054        let mlet_slice: &[u8] = view
1055            .section_bytes(Euv3dSectionKind::Meshlets)
1056            .unwrap_or(&[]);
1057        let bvh4_slice: &[u8] = view
1058            .section_bytes(Euv3dSectionKind::Bvh4Nodes)
1059            .unwrap_or(&[]);
1060        let bvh_pkt_slice: &[u8] = view
1061            .section_bytes(Euv3dSectionKind::BvhTri4Packets)
1062            .unwrap_or(&[]);
1063        let bvh_tri_slice: &[u8] = view
1064            .section_bytes(Euv3dSectionKind::BvhTriangles)
1065            .unwrap_or(&[]);
1066        let anim_slice: &[u8] = view
1067            .section_bytes(Euv3dSectionKind::AnimationsBlob)
1068            .unwrap_or(&[]);
1069        let tex_slice: &[u8] = view
1070            .section_bytes(Euv3dSectionKind::TexturesBlob)
1071            .unwrap_or(&[]);
1072
1073        let mut lod_chains: Vec<MeshLodChain> = Vec::with_capacity(meta.meshes.len());
1074        let mut lod0_meshes: Vec<Mesh3D> = Vec::with_capacity(meta.meshes.len());
1075        for mesh_rec in &meta.meshes {
1076            let mut levels: Vec<Mesh3D> = Vec::with_capacity(mesh_rec.lods.len());
1077            let base_mat: PbrMaterial = record_to_pbr(&mesh_rec.material);
1078            let sub_mats: Vec<PbrMaterial> =
1079                mesh_rec.sub_materials.iter().map(record_to_pbr).collect();
1080            for (lod_idx, lod_rec) in mesh_rec.lods.iter().enumerate() {
1081                let mut vertices: Vec<Vertex3D> = Vec::with_capacity(lod_rec.vertex_count as usize);
1082                for v_i in 0..(lod_rec.vertex_count as usize) {
1083                    let off: usize =
1084                        ((lod_rec.first_vertex as usize) + v_i) * EUV3D_VERTEX_STRIDE_BYTES;
1085                    vertices.push(read_vertex_bytes(verts_slice, off)?);
1086                }
1087                let mut indices: Vec<[u32; 3]> = Vec::with_capacity(lod_rec.tri_count as usize);
1088                for t_i in 0..(lod_rec.tri_count as usize) {
1089                    let off: usize = ((lod_rec.first_tri as usize) + t_i) * EUV3D_INDEX_TRI_BYTES;
1090                    let i0: u32 = read_u32_le(idx_slice, off)?;
1091                    let i1: u32 = read_u32_le(idx_slice, off + 4)?;
1092                    let i2: u32 = read_u32_le(idx_slice, off + 8)?;
1093                    indices.push([i0, i1, i2]);
1094                }
1095                let mut meshlets: Vec<Meshlet3D> =
1096                    Vec::with_capacity(lod_rec.meshlet_count as usize);
1097                for m_i in 0..(lod_rec.meshlet_count as usize) {
1098                    let off: usize =
1099                        ((lod_rec.first_meshlet as usize) + m_i) * EUV3D_MESHLET_STRIDE_BYTES;
1100                    meshlets.push(read_meshlet_bytes(mlet_slice, off)?);
1101                }
1102                let bounds: AxisAlignedBox3D = AxisAlignedBox3D::new(
1103                    Vec3::from_array(lod_rec.bounds_min),
1104                    Vec3::from_array(lod_rec.bounds_max),
1105                );
1106                let mut skin_influences: Vec<MeshSkinInfluence3D> = Vec::new();
1107                let mut morph_targets: Vec<MorphTarget3D> = Vec::new();
1108                if lod_idx == 0 {
1109                    skin_influences.reserve(mesh_rec.skin_count as usize);
1110                    for s_i in 0..(mesh_rec.skin_count as usize) {
1111                        let off: usize =
1112                            ((mesh_rec.first_skin as usize) + s_i) * EUV3D_SKIN_STRIDE_BYTES;
1113                        skin_influences.push(read_skin_bytes(skin_slice, off)?);
1114                    }
1115                    morph_targets.reserve(mesh_rec.morphs.len());
1116                    for m_rec in &mesh_rec.morphs {
1117                        let mut delta_positions: Vec<[f32; 3]> =
1118                            Vec::with_capacity(m_rec.pos_count as usize);
1119                        for p_i in 0..(m_rec.pos_count as usize) {
1120                            let off: usize = ((m_rec.first_pos as usize) + p_i) * 12;
1121                            delta_positions.push([
1122                                read_f32_le(morph_slice, off)?,
1123                                read_f32_le(morph_slice, off + 4)?,
1124                                read_f32_le(morph_slice, off + 8)?,
1125                            ]);
1126                        }
1127                        let mut delta_normals: Vec<[f32; 3]> =
1128                            Vec::with_capacity(m_rec.norm_count as usize);
1129                        for n_i in 0..(m_rec.norm_count as usize) {
1130                            let off: usize = ((m_rec.first_norm as usize) + n_i) * 12;
1131                            delta_normals.push([
1132                                read_f32_le(morph_slice, off)?,
1133                                read_f32_le(morph_slice, off + 4)?,
1134                                read_f32_le(morph_slice, off + 8)?,
1135                            ]);
1136                        }
1137                        let mut delta_tangents: Vec<[f32; 3]> =
1138                            Vec::with_capacity(m_rec.tan_count as usize);
1139                        for t_i in 0..(m_rec.tan_count as usize) {
1140                            let off: usize = ((m_rec.first_tan as usize) + t_i) * 12;
1141                            delta_tangents.push([
1142                                read_f32_le(morph_slice, off)?,
1143                                read_f32_le(morph_slice, off + 4)?,
1144                                read_f32_le(morph_slice, off + 8)?,
1145                            ]);
1146                        }
1147                        morph_targets.push(MorphTarget3D {
1148                            name: m_rec.name.clone(),
1149                            delta_positions,
1150                            delta_normals,
1151                            delta_tangents,
1152                        });
1153                    }
1154                }
1155                let mesh_level: Mesh3D = Mesh3D {
1156                    name: mesh_rec.name.clone(),
1157                    vertices,
1158                    indices,
1159                    bounds,
1160                    material: base_mat,
1161                    sub_materials: if lod_idx == 0 {
1162                        sub_mats.clone()
1163                    } else {
1164                        Vec::new()
1165                    },
1166                    tri_materials: if lod_idx == 0 {
1167                        mesh_rec.tri_materials.clone()
1168                    } else {
1169                        Vec::new()
1170                    },
1171                    meshlets,
1172                    skin_influences,
1173                    morph_targets,
1174                    material_index: mesh_rec.material_index,
1175                    is_closed: mesh_rec.is_closed,
1176                };
1177                levels.push(mesh_level);
1178            }
1179            if let Some(first_level) = levels.first() {
1180                lod0_meshes.push(first_level.clone());
1181            }
1182            lod_chains.push(MeshLodChain { levels });
1183        }
1184
1185        let mut local_bvhs: Vec<Bvh3D> = Vec::with_capacity(meta.bvhs.len());
1186        for bvh_rec in &meta.bvhs {
1187            let mut bvh4_nodes: Vec<Bvh4Node> = Vec::with_capacity(bvh_rec.node_count as usize);
1188            for n_i in 0..(bvh_rec.node_count as usize) {
1189                let off: usize =
1190                    ((bvh_rec.first_node as usize) + n_i) * EUV3D_BVH4_NODE_STRIDE_BYTES;
1191                bvh4_nodes.push(read_bvh4_node_bytes(bvh4_slice, off)?);
1192            }
1193            let mut leaf_packets: Vec<BvhTri4> = Vec::with_capacity(bvh_rec.packet_count as usize);
1194            for p_i in 0..(bvh_rec.packet_count as usize) {
1195                let off: usize =
1196                    ((bvh_rec.first_packet as usize) + p_i) * EUV3D_BVH_TRI4_STRIDE_BYTES;
1197                leaf_packets.push(read_bvh_tri4_bytes(bvh_pkt_slice, off)?);
1198            }
1199            let mut triangles: Vec<BvhTriangle> = Vec::with_capacity(bvh_rec.tri_count as usize);
1200            for t_i in 0..(bvh_rec.tri_count as usize) {
1201                let off: usize = ((bvh_rec.first_tri as usize) + t_i) * EUV3D_BVH_TRI_STRIDE_BYTES;
1202                triangles.push(read_bvh_tri_bytes(bvh_tri_slice, off)?);
1203            }
1204            for node in &bvh4_nodes {
1205                let valid: usize = (node.valid_count as usize).min(4);
1206                for lane in 0..valid {
1207                    let lc: usize = node.leaf_count[lane] as usize;
1208                    let ch: usize = node.child[lane] as usize;
1209                    if lc > 0 {
1210                        if ch
1211                            .checked_add(lc)
1212                            .is_none_or(|end: usize| end > leaf_packets.len())
1213                        {
1214                            return Err(ERR_EUV3D_INVALID_BVH4.to_string());
1215                        }
1216                    } else if ch >= bvh4_nodes.len() {
1217                        return Err(ERR_EUV3D_INVALID_BVH4.to_string());
1218                    }
1219                }
1220            }
1221            for pkt in &leaf_packets {
1222                for &t_idx in &pkt.tri_indices {
1223                    if t_idx != u32::MAX && (t_idx as usize) >= triangles.len() {
1224                        return Err(ERR_EUV3D_INVALID_BVH4.to_string());
1225                    }
1226                }
1227            }
1228            let geom: Vec<BvhGeomTri> = triangles.iter().map(BvhGeomTri::from_triangle).collect();
1229            let orig_indices: Vec<u32> = (0..triangles.len()).map(|i: usize| i as u32).collect();
1230            local_bvhs.push(Bvh3D {
1231                nodes: Vec::new(),
1232                triangles,
1233                geom,
1234                leaf_packets,
1235                flat_nodes: Vec::new(),
1236                bvh4_nodes,
1237                bvh4_src_children: Vec::new(),
1238                root_min: bvh_rec.root_min,
1239                root_max: bvh_rec.root_max,
1240                #[cfg(target_arch = "x86_64")]
1241                bvh8_nodes: Vec::new(),
1242                #[cfg(target_arch = "x86_64")]
1243                bvh8_src_children: Vec::new(),
1244                orig_indices,
1245                node_to_flat: Vec::new(),
1246                build_sah_cost: bvh_rec.build_sah_cost,
1247            });
1248        }
1249
1250        let mut scene_graph: SceneGraph3D = SceneGraph3D::default();
1251        if !meta.collections.is_empty() {
1252            let mut active_mask: u64 = 0;
1253            let entries: Vec<CollectionEntry3D> = meta
1254                .collections
1255                .iter()
1256                .map(|c: &Euv3dCollectionRecord| {
1257                    if c.visible_viewport && c.bit_index < 64 {
1258                        active_mask |= 1u64 << u32::from(c.bit_index);
1259                    }
1260                    CollectionEntry3D {
1261                        name: c.name.clone(),
1262                        bit_index: c.bit_index,
1263                        visible_viewport: c.visible_viewport,
1264                        visible_render: c.visible_render,
1265                    }
1266                })
1267                .collect();
1268            scene_graph.set_collections(CollectionRegistry3D {
1269                entries,
1270                active_mask,
1271            });
1272        }
1273        for n_rec in &meta.nodes {
1274            let mut node: SceneNode3D = SceneNode3D::from_name(&n_rec.name, n_rec.parent);
1275            node.set_local_translation(Vec3::from_array(n_rec.translation));
1276            node.set_local_rotation(Quat::from_array(n_rec.rotation));
1277            node.set_local_scale(Vec3::from_array(n_rec.scale));
1278            node.set_mesh_id(n_rec.mesh_id);
1279            node.set_skin_id(n_rec.skin_id);
1280            node.set_camera_id(n_rec.camera_id);
1281            node.set_light_id(n_rec.light_id);
1282            node.set_collection_mask(n_rec.collection_mask);
1283            node.set_visible(n_rec.visible);
1284            let collider: SceneColliderShape3D = match n_rec.collider_shape {
1285                1 => SceneColliderShape3D::Box,
1286                2 => SceneColliderShape3D::Sphere,
1287                3 => SceneColliderShape3D::ConvexHull,
1288                4 => SceneColliderShape3D::Mesh,
1289                _ => SceneColliderShape3D::None,
1290            };
1291            node.set_extras(BlenderExtrasTags3D {
1292                collider,
1293                buoyancy_density: n_rec.buoyancy_density,
1294                is_trigger: n_rec.is_trigger,
1295                cast_shadows: n_rec.cast_shadows,
1296                custom_json: n_rec.custom_json.clone(),
1297            });
1298            let node_id: u32 = scene_graph.add_node(node);
1299            if !n_rec.morph_weights.is_empty() {
1300                scene_graph.attach_morph_weights(node_id, &n_rec.morph_weights);
1301            }
1302        }
1303        let _: usize = scene_graph.propagate_world_matrices();
1304
1305        let materials: Vec<PrincipledMaterial3D> =
1306            meta.materials.iter().map(record_to_material).collect();
1307
1308        let mut textures: Vec<Texture2D3D> = Vec::with_capacity(meta.textures.len());
1309        for t_rec in &meta.textures {
1310            let color_space: TextureColorSpace = match t_rec.color_space {
1311                1 => TextureColorSpace::Linear,
1312                2 => TextureColorSpace::NormalTangent,
1313                _ => TextureColorSpace::Srgb,
1314            };
1315            let decode_filter: fn(u8) -> TextureFilterMode = |tag: u8| match tag {
1316                0 => TextureFilterMode::Nearest,
1317                2 => TextureFilterMode::NearestMipmapNearest,
1318                3 => TextureFilterMode::LinearMipmapNearest,
1319                4 => TextureFilterMode::NearestMipmapLinear,
1320                5 => TextureFilterMode::LinearMipmapLinear,
1321                _ => TextureFilterMode::Linear,
1322            };
1323            let min_filter: TextureFilterMode = decode_filter(t_rec.min_filter);
1324            let mag_filter: TextureFilterMode = decode_filter(t_rec.mag_filter);
1325            let wrap_s: TextureWrapMode = match t_rec.wrap_s {
1326                1 => TextureWrapMode::MirroredRepeat,
1327                2 => TextureWrapMode::ClampToEdge,
1328                _ => TextureWrapMode::Repeat,
1329            };
1330            let wrap_t: TextureWrapMode = match t_rec.wrap_t {
1331                1 => TextureWrapMode::MirroredRepeat,
1332                2 => TextureWrapMode::ClampToEdge,
1333                _ => TextureWrapMode::Repeat,
1334            };
1335            let mut mips: Vec<TextureMipLevel3D> = Vec::with_capacity(t_rec.mips.len());
1336            for mip_rec in &t_rec.mips {
1337                let start: usize = mip_rec.byte_offset as usize;
1338                let end: usize = start
1339                    .checked_add(mip_rec.byte_length as usize)
1340                    .ok_or_else(|| ERR_EUV3D_TRUNCATED_BLOB.to_string())?;
1341                if end > tex_slice.len() {
1342                    return Err(ERR_EUV3D_TRUNCATED_BLOB.to_string());
1343                }
1344                mips.push(TextureMipLevel3D {
1345                    width: mip_rec.width,
1346                    height: mip_rec.height,
1347                    pixels: tex_slice[start..end].to_vec(),
1348                });
1349            }
1350            let (width, height): (u32, u32) = mips
1351                .first()
1352                .map(|m: &TextureMipLevel3D| (m.get_width(), m.get_height()))
1353                .unwrap_or((0, 0));
1354            textures.push(Texture2D3D {
1355                name: t_rec.name.clone(),
1356                width,
1357                height,
1358                color_space,
1359                sampler: TextureSampler3D::new(mag_filter, min_filter, wrap_s, wrap_t),
1360                mips,
1361            });
1362        }
1363
1364        let skins: Vec<ImportedSkin3D> = meta
1365            .skins
1366            .iter()
1367            .map(|s: &Euv3dSkinRecord| ImportedSkin3D {
1368                name: s.name.clone(),
1369                joints: s.joints.clone(),
1370                skeleton_root: s.skeleton_root,
1371                inverse_bind_matrices: s
1372                    .inverse_bind_matrices
1373                    .iter()
1374                    .map(|arr: &[f32; 16]| Mat4::from_cols_array(*arr))
1375                    .collect(),
1376            })
1377            .collect();
1378
1379        let mut animations: Vec<ImportedAnimationClip3D> =
1380            Vec::with_capacity(meta.animations.len());
1381        for c_rec in &meta.animations {
1382            let mut samplers: Vec<ImportedAnimationSampler3D> =
1383                Vec::with_capacity(c_rec.samplers.len());
1384            for s_rec in &c_rec.samplers {
1385                let mut timestamps: Vec<f32> = Vec::with_capacity(s_rec.time_count as usize);
1386                for i in 0..(s_rec.time_count as usize) {
1387                    timestamps.push(read_f32_le(
1388                        anim_slice,
1389                        ((s_rec.first_time as usize) + i) * 4,
1390                    )?);
1391                }
1392                let mut values: Vec<f32> = Vec::with_capacity(s_rec.value_count as usize);
1393                for i in 0..(s_rec.value_count as usize) {
1394                    values.push(read_f32_le(
1395                        anim_slice,
1396                        ((s_rec.first_value as usize) + i) * 4,
1397                    )?);
1398                }
1399                let interpolation: GltfInterpolationMode = match s_rec.interpolation {
1400                    0 => GltfInterpolationMode::Step,
1401                    2 => GltfInterpolationMode::CubicSpline,
1402                    _ => GltfInterpolationMode::Linear,
1403                };
1404                samplers.push(ImportedAnimationSampler3D {
1405                    timestamps,
1406                    values,
1407                    value_stride: s_rec.value_stride as usize,
1408                    interpolation,
1409                });
1410            }
1411            let channels: Vec<ImportedAnimationChannel3D> = c_rec
1412                .channels
1413                .iter()
1414                .map(|ch: &Euv3dAnimChannelRecord| {
1415                    let path: GltfAnimationPath = match ch.path {
1416                        1 => GltfAnimationPath::Rotation,
1417                        2 => GltfAnimationPath::Scale,
1418                        3 => GltfAnimationPath::MorphWeights,
1419                        _ => GltfAnimationPath::Translation,
1420                    };
1421                    ImportedAnimationChannel3D::new(ch.target_node, path, ch.sampler_index as usize)
1422                })
1423                .collect();
1424            animations.push(ImportedAnimationClip3D {
1425                name: c_rec.name.clone(),
1426                duration_secs: c_rec.duration_secs,
1427                samplers,
1428                channels,
1429            });
1430        }
1431
1432        let cameras: Vec<ImportedCamera3D> = meta
1433            .cameras
1434            .iter()
1435            .map(|c: &Euv3dCameraRecord| {
1436                let projection: GltfCameraProjection = if c.is_perspective {
1437                    GltfCameraProjection::Perspective {
1438                        yfov_rad: c.param_a,
1439                        aspect_ratio: if c.param_b > 0.0 {
1440                            Some(c.param_b)
1441                        } else {
1442                            None
1443                        },
1444                        znear: c.znear,
1445                        zfar: c.zfar,
1446                    }
1447                } else {
1448                    GltfCameraProjection::Orthographic {
1449                        xmag: c.param_a,
1450                        ymag: c.param_b,
1451                        znear: c.znear,
1452                        zfar: c.zfar.unwrap_or(1000.0),
1453                    }
1454                };
1455                ImportedCamera3D {
1456                    name: c.name.clone(),
1457                    projection,
1458                }
1459            })
1460            .collect();
1461
1462        let lights: Vec<ImportedLight3D> = meta
1463            .lights
1464            .iter()
1465            .map(|l: &Euv3dLightRecord| {
1466                let kind: GltfLightKind = match l.kind {
1467                    1 => GltfLightKind::Point { range: l.range },
1468                    2 => GltfLightKind::Spot {
1469                        range: l.range,
1470                        inner_cone_angle: l.param_a,
1471                        outer_cone_angle: l.param_b,
1472                    },
1473                    3 => GltfLightKind::Area {
1474                        width: l.param_a,
1475                        height: l.param_b,
1476                    },
1477                    _ => GltfLightKind::Directional,
1478                };
1479                ImportedLight3D {
1480                    name: l.name.clone(),
1481                    color: Vec3::from_array(l.color),
1482                    intensity: l.intensity,
1483                    kind,
1484                }
1485            })
1486            .collect();
1487
1488        let scene: ImportedScene3D = ImportedScene3D {
1489            name: meta.name,
1490            generator: meta.generator,
1491            scene_graph,
1492            meshes: lod0_meshes,
1493            materials,
1494            textures,
1495            skins,
1496            animations,
1497            cameras,
1498            lights,
1499        };
1500        let header: Euv3dHeader = view.get_header();
1501        Ok(BakedAssetBundle3D {
1502            scene,
1503            lod_chains,
1504            local_bvhs,
1505            section_count: view.get_sections().len(),
1506            total_bytes: header.get_total_bytes() as usize,
1507            digest_fnv1a: header.get_digest_fnv1a(),
1508        })
1509    }
1510
1511    /// Bakes an `ImportedScene3D` into a quantized `.euv3d` v2 binary package with 24-byte vertices, 16-byte skins, 64-triangle cache-line meshlets, QEM LOD0..LOD3, pre-baked BVH4, and mip-tail-first texture sections.
1512    ///
1513    /// # Arguments
1514    ///
1515    /// - `&ImportedScene3D` - Source imported Blender/glTF scene.
1516    /// - `&Euv3dBakeConfig` - LOD, meshlet, BVH4, and mipmap baking configuration.
1517    ///
1518    /// # Returns
1519    ///
1520    /// - `Result<Vec<u8>, String>` - Self-contained CRC-verified `.euv3d` v2 binary archive.
1521    pub fn bake_v2_from_scene(
1522        scene: &ImportedScene3D,
1523        config: &Euv3dBakeConfig,
1524    ) -> Result<Vec<u8>, String> {
1525        let mut qverts_blob: Vec<u8> = Vec::new();
1526        let mut vertex_total: u32 = 0;
1527        let mut indices_blob: Vec<u8> = Vec::new();
1528        let mut tri_total: u32 = 0;
1529        let mut qskins_blob: Vec<u8> = Vec::new();
1530        let mut skin_total: u32 = 0;
1531        let mut morph_blob: Vec<u8> = Vec::new();
1532        let mut morph_vec_total: u32 = 0;
1533        let mut qmeshlets_blob: Vec<u8> = Vec::new();
1534        let mut meshlet_total: u32 = 0;
1535        let mut bvh4_blob: Vec<u8> = Vec::new();
1536        let mut bvh4_total: u32 = 0;
1537        let mut bvh_pkt_blob: Vec<u8> = Vec::new();
1538        let mut bvh_pkt_total: u32 = 0;
1539        let mut bvh_tri_blob: Vec<u8> = Vec::new();
1540        let mut bvh_tri_total: u32 = 0;
1541        let mut anim_blob: Vec<u8> = Vec::new();
1542        let mut anim_float_total: u32 = 0;
1543        let mut mesh_records: Vec<Euv3dMeshRecord> = Vec::with_capacity(scene.get_meshes().len());
1544        let mut bvh_records: Vec<Euv3dBvhRecord> = Vec::with_capacity(scene.get_meshes().len());
1545        let max_lods: usize = config.get_lod_levels().clamp(1, EUV3D_DEFAULT_LOD_LEVELS);
1546        for mesh in scene.get_meshes().iter() {
1547            let chain: MeshLodChain = if max_lods > 1 {
1548                build_qem_lod_chain(mesh, max_lods)
1549            } else {
1550                MeshLodChain {
1551                    levels: vec![mesh.clone()],
1552                }
1553            };
1554            let mut lod_records: Vec<Euv3dLodRecord> = Vec::with_capacity(chain.get_levels().len());
1555            for lod_mesh in chain.get_levels().iter() {
1556                let bounds_min: Vec3 = lod_mesh.get_bounds().get_min();
1557                let bounds_max: Vec3 = lod_mesh.get_bounds().get_max();
1558                let first_vertex: u32 = vertex_total;
1559                let vertex_count: u32 = lod_mesh.get_vertices().len() as u32;
1560                for v in lod_mesh.get_vertices().iter() {
1561                    let qv: QuantizedVertex3D = quantize_euv3d_vertex(v, bounds_min, bounds_max);
1562                    push_quantized_vertex_bytes(&mut qverts_blob, &qv);
1563                }
1564                vertex_total += vertex_count;
1565                let (reordered_tris, q_meshlets): (Vec<[u32; 3]>, Vec<QuantizedMeshlet3D>) =
1566                    if config.get_build_meshlets() && lod_mesh.get_tri_materials().is_empty() {
1567                        let (reord, _, qm): (
1568                            Vec<[u32; 3]>,
1569                            Vec<Meshlet3D>,
1570                            Vec<QuantizedMeshlet3D>,
1571                        ) = build_quantized_meshlets_v2(
1572                            lod_mesh.get_vertices(),
1573                            lod_mesh.get_indices(),
1574                        );
1575                        (reord, qm)
1576                    } else if config.get_build_meshlets() {
1577                        let (_, _, qm): (Vec<[u32; 3]>, Vec<Meshlet3D>, Vec<QuantizedMeshlet3D>) =
1578                            build_quantized_meshlets_v2(
1579                                lod_mesh.get_vertices(),
1580                                lod_mesh.get_indices(),
1581                            );
1582                        (lod_mesh.get_indices().clone(), qm)
1583                    } else {
1584                        (lod_mesh.get_indices().clone(), Vec::new())
1585                    };
1586                let first_tri: u32 = tri_total;
1587                let tri_count: u32 = reordered_tris.len() as u32;
1588                for tri in reordered_tris.iter() {
1589                    indices_blob.extend_from_slice(&tri[0].to_le_bytes());
1590                    indices_blob.extend_from_slice(&tri[1].to_le_bytes());
1591                    indices_blob.extend_from_slice(&tri[2].to_le_bytes());
1592                }
1593                tri_total += tri_count;
1594                let first_meshlet: u32 = meshlet_total;
1595                let meshlet_count: u32 = q_meshlets.len() as u32;
1596                for qm in q_meshlets.iter() {
1597                    push_quantized_meshlet_bytes(&mut qmeshlets_blob, qm);
1598                }
1599                meshlet_total += meshlet_count;
1600                lod_records.push(Euv3dLodRecord {
1601                    first_vertex,
1602                    vertex_count,
1603                    first_tri,
1604                    tri_count,
1605                    first_meshlet,
1606                    meshlet_count,
1607                    bounds_min: bounds_min.to_array(),
1608                    bounds_max: bounds_max.to_array(),
1609                });
1610            }
1611            let lod0_ref: &Mesh3D = &chain.get_levels()[0];
1612            let first_skin: u32 = skin_total;
1613            let skin_count: u32 = lod0_ref.get_skin_influences().len() as u32;
1614            for skin in lod0_ref.get_skin_influences().iter() {
1615                let qs: QuantizedSkinVertex3D = quantize_euv3d_skin_vertex(skin);
1616                push_quantized_skin_bytes(&mut qskins_blob, &qs);
1617            }
1618            skin_total += skin_count;
1619            let mut morph_records: Vec<Euv3dMorphRecord> =
1620                Vec::with_capacity(lod0_ref.get_morph_targets().len());
1621            for target in lod0_ref.get_morph_targets().iter() {
1622                let first_pos: u32 = morph_vec_total;
1623                let pos_count: u32 = target.get_delta_positions().len() as u32;
1624                for d in target.get_delta_positions().iter() {
1625                    for lane in *d {
1626                        morph_blob.extend_from_slice(&lane.to_le_bytes());
1627                    }
1628                }
1629                morph_vec_total += pos_count;
1630                let first_norm: u32 = morph_vec_total;
1631                let norm_count: u32 = target.get_delta_normals().len() as u32;
1632                for d in target.get_delta_normals().iter() {
1633                    for lane in *d {
1634                        morph_blob.extend_from_slice(&lane.to_le_bytes());
1635                    }
1636                }
1637                morph_vec_total += norm_count;
1638                let first_tan: u32 = morph_vec_total;
1639                let tan_count: u32 = target.get_delta_tangents().len() as u32;
1640                for d in target.get_delta_tangents().iter() {
1641                    for lane in *d {
1642                        morph_blob.extend_from_slice(&lane.to_le_bytes());
1643                    }
1644                }
1645                morph_vec_total += tan_count;
1646                morph_records.push(Euv3dMorphRecord {
1647                    name: target.get_name().clone(),
1648                    first_pos,
1649                    pos_count,
1650                    first_norm,
1651                    norm_count,
1652                    first_tan,
1653                    tan_count,
1654                });
1655            }
1656            mesh_records.push(Euv3dMeshRecord {
1657                name: lod0_ref.get_name().clone(),
1658                material: pbr_to_record(lod0_ref.get_material()),
1659                sub_materials: lod0_ref
1660                    .get_sub_materials()
1661                    .iter()
1662                    .copied()
1663                    .map(pbr_to_record)
1664                    .collect(),
1665                tri_materials: lod0_ref.get_tri_materials().clone(),
1666                material_index: lod0_ref.try_get_material_index(),
1667                is_closed: lod0_ref.get_is_closed(),
1668                lods: lod_records,
1669                first_skin,
1670                skin_count,
1671                morphs: morph_records,
1672            });
1673            if config.get_bake_bvh4() {
1674                let bvh: Bvh3D = build_local_mesh_bvh(lod0_ref);
1675                let first_node: u32 = bvh4_total;
1676                let node_count: u32 = bvh.bvh4_nodes.len() as u32;
1677                for node in bvh.bvh4_nodes.iter() {
1678                    push_bvh4_node_bytes(&mut bvh4_blob, node);
1679                }
1680                bvh4_total += node_count;
1681                let first_packet: u32 = bvh_pkt_total;
1682                let packet_count: u32 = bvh.leaf_packets.len() as u32;
1683                for pkt in bvh.leaf_packets.iter() {
1684                    push_bvh_tri4_bytes(&mut bvh_pkt_blob, pkt);
1685                }
1686                bvh_pkt_total += packet_count;
1687                let first_tri: u32 = bvh_tri_total;
1688                let tri_count: u32 = bvh.get_triangles().len() as u32;
1689                for tri in bvh.get_triangles().iter() {
1690                    push_bvh_tri_bytes(&mut bvh_tri_blob, tri);
1691                }
1692                bvh_tri_total += tri_count;
1693                bvh_records.push(Euv3dBvhRecord {
1694                    first_node,
1695                    node_count,
1696                    first_packet,
1697                    packet_count,
1698                    first_tri,
1699                    tri_count,
1700                    root_min: bvh.root_min,
1701                    root_max: bvh.root_max,
1702                    build_sah_cost: bvh.get_build_sah_cost(),
1703                });
1704            }
1705        }
1706        let collections: Vec<Euv3dCollectionRecord> = scene
1707            .get_scene_graph()
1708            .get_collections()
1709            .get_entries()
1710            .iter()
1711            .map(|entry: &CollectionEntry3D| Euv3dCollectionRecord {
1712                name: entry.get_name().clone(),
1713                bit_index: entry.get_bit_index(),
1714                visible_viewport: entry.get_visible_viewport(),
1715                visible_render: entry.get_visible_render(),
1716            })
1717            .collect();
1718        let all_morph_weights: &[f32] = scene.get_scene_graph().get_morph_weights();
1719        let nodes: Vec<Euv3dNodeRecord> = scene
1720            .get_scene_graph()
1721            .get_nodes()
1722            .iter()
1723            .map(|node: &SceneNode3D| {
1724                let w_start: usize = node.get_morph_weight_offset() as usize;
1725                let w_end: usize = (w_start + usize::from(node.get_morph_weight_count()))
1726                    .min(all_morph_weights.len());
1727                let morph_weights: Vec<f32> = if w_start < w_end {
1728                    all_morph_weights[w_start..w_end].to_vec()
1729                } else {
1730                    Vec::new()
1731                };
1732                let extras: &BlenderExtrasTags3D = node.get_extras();
1733                let collider_shape: u8 = match extras.get_collider() {
1734                    SceneColliderShape3D::None => 0,
1735                    SceneColliderShape3D::Box => 1,
1736                    SceneColliderShape3D::Sphere => 2,
1737                    SceneColliderShape3D::ConvexHull => 3,
1738                    SceneColliderShape3D::Mesh => 4,
1739                };
1740                Euv3dNodeRecord {
1741                    name: node.get_name().clone(),
1742                    parent: node.try_get_parent(),
1743                    translation: node.get_local_translation().to_array(),
1744                    rotation: node.get_local_rotation().to_array(),
1745                    scale: node.get_local_scale().to_array(),
1746                    mesh_id: node.try_get_mesh_id(),
1747                    skin_id: node.try_get_skin_id(),
1748                    camera_id: node.try_get_camera_id(),
1749                    light_id: node.try_get_light_id(),
1750                    collection_mask: node.get_collection_mask(),
1751                    visible: node.get_visible(),
1752                    morph_weights,
1753                    collider_shape,
1754                    buoyancy_density: extras.get_buoyancy_density(),
1755                    is_trigger: extras.get_is_trigger(),
1756                    cast_shadows: extras.get_cast_shadows(),
1757                    custom_json: extras.try_get_custom_json().clone(),
1758                }
1759            })
1760            .collect();
1761        let materials: Vec<Euv3dMaterialRecord> = scene
1762            .get_materials()
1763            .iter()
1764            .map(material_to_record)
1765            .collect();
1766        let tex_count: usize = scene.get_textures().len();
1767        let mut mip_tail_blob: Vec<u8> = Vec::new();
1768        let mut mip_high_blob: Vec<u8> = Vec::new();
1769        if tex_count > 0 {
1770            mip_tail_blob.resize(4 + tex_count * 12, 0u8);
1771            mip_tail_blob[0..4].copy_from_slice(&(tex_count as u32).to_le_bytes());
1772        }
1773        let mut textures: Vec<Euv3dTextureRecord> = Vec::with_capacity(tex_count);
1774        for (tex_idx, tex) in scene.get_textures().iter().enumerate() {
1775            let color_space: u8 = match tex.get_color_space() {
1776                TextureColorSpace::Srgb => 0,
1777                TextureColorSpace::Linear => 1,
1778                TextureColorSpace::NormalTangent => 2,
1779            };
1780            let sampler: TextureSampler3D = tex.get_sampler();
1781            let encode_filter: fn(TextureFilterMode) -> u8 = |mode: TextureFilterMode| match mode {
1782                TextureFilterMode::Nearest => 0,
1783                TextureFilterMode::Linear => 1,
1784                TextureFilterMode::NearestMipmapNearest => 2,
1785                TextureFilterMode::LinearMipmapNearest => 3,
1786                TextureFilterMode::NearestMipmapLinear => 4,
1787                TextureFilterMode::LinearMipmapLinear => 5,
1788            };
1789            let min_filter: u8 = encode_filter(sampler.get_min_filter());
1790            let mag_filter: u8 = encode_filter(sampler.get_mag_filter());
1791            let wrap_s: u8 = match sampler.get_wrap_s() {
1792                TextureWrapMode::Repeat => 0,
1793                TextureWrapMode::MirroredRepeat => 1,
1794                TextureWrapMode::ClampToEdge => 2,
1795            };
1796            let wrap_t: u8 = match sampler.get_wrap_t() {
1797                TextureWrapMode::Repeat => 0,
1798                TextureWrapMode::MirroredRepeat => 1,
1799                TextureWrapMode::ClampToEdge => 2,
1800            };
1801            let mip_limit: usize = if config.get_generate_mipmaps() {
1802                tex.get_mips().len()
1803            } else {
1804                tex.get_mips().len().min(1)
1805            };
1806            let mut mips: Vec<Euv3dTexMipRecord> = Vec::with_capacity(mip_limit);
1807            let mut tail_first_offset: u32 = mip_tail_blob.len() as u32;
1808            let mut tail_top_w: u16 = 0;
1809            let mut tail_top_h: u16 = 0;
1810            let mut tail_mip_count: u8 = 0;
1811            for (mip_idx, mip) in tex.get_mips().iter().take(mip_limit).enumerate() {
1812                let w: u32 = mip.get_width();
1813                let h: u32 = mip.get_height();
1814                let pixels: &[u8] = mip.get_pixels();
1815                let is_tail: bool = (w <= EUV3D_V2_MIP_TAIL_MAX_DIM
1816                    && h <= EUV3D_V2_MIP_TAIL_MAX_DIM)
1817                    || (mip_idx + 1 == mip_limit && tail_mip_count == 0);
1818                if is_tail {
1819                    if tail_mip_count == 0 {
1820                        tail_first_offset = mip_tail_blob.len() as u32;
1821                        tail_top_w = w.min(u32::from(u16::MAX)) as u16;
1822                        tail_top_h = h.min(u32::from(u16::MAX)) as u16;
1823                    }
1824                    let byte_offset: u64 = mip_tail_blob.len() as u64;
1825                    mip_tail_blob.extend_from_slice(pixels);
1826                    tail_mip_count = tail_mip_count.saturating_add(1);
1827                    mips.push(Euv3dTexMipRecord {
1828                        width: w,
1829                        height: h,
1830                        byte_offset,
1831                        byte_length: pixels.len() as u64,
1832                        is_mip_tail: true,
1833                    });
1834                } else {
1835                    let byte_offset: u64 = mip_high_blob.len() as u64;
1836                    mip_high_blob.extend_from_slice(pixels);
1837                    mips.push(Euv3dTexMipRecord {
1838                        width: w,
1839                        height: h,
1840                        byte_offset,
1841                        byte_length: pixels.len() as u64,
1842                        is_mip_tail: false,
1843                    });
1844                }
1845            }
1846            let dir_off: usize = 4 + tex_idx * 12;
1847            mip_tail_blob[dir_off..(dir_off + 2)].copy_from_slice(&tail_top_w.to_le_bytes());
1848            mip_tail_blob[(dir_off + 2)..(dir_off + 4)].copy_from_slice(&tail_top_h.to_le_bytes());
1849            mip_tail_blob[dir_off + 4] = color_space;
1850            mip_tail_blob[dir_off + 5] = tail_mip_count;
1851            mip_tail_blob[(dir_off + 8)..(dir_off + 12)]
1852                .copy_from_slice(&tail_first_offset.to_le_bytes());
1853            textures.push(Euv3dTextureRecord {
1854                name: tex.get_name().clone(),
1855                color_space,
1856                min_filter,
1857                mag_filter,
1858                wrap_s,
1859                wrap_t,
1860                mips,
1861            });
1862        }
1863        let skins: Vec<Euv3dSkinRecord> = scene
1864            .get_skins()
1865            .iter()
1866            .map(|skin: &ImportedSkin3D| Euv3dSkinRecord {
1867                name: skin.get_name().clone(),
1868                joints: skin.get_joints().clone(),
1869                skeleton_root: skin.try_get_skeleton_root(),
1870                inverse_bind_matrices: skin
1871                    .get_inverse_bind_matrices()
1872                    .iter()
1873                    .map(|m: &Mat4| m.get_elements())
1874                    .collect(),
1875            })
1876            .collect();
1877        let mut animations: Vec<Euv3dAnimClipRecord> =
1878            Vec::with_capacity(scene.get_animations().len());
1879        for clip in scene.get_animations().iter() {
1880            let mut samplers: Vec<Euv3dAnimSamplerRecord> =
1881                Vec::with_capacity(clip.get_samplers().len());
1882            for samp in clip.get_samplers().iter() {
1883                let first_time: u32 = anim_float_total;
1884                let time_count: u32 = samp.get_timestamps().len() as u32;
1885                for &t in samp.get_timestamps().iter() {
1886                    anim_blob.extend_from_slice(&t.to_le_bytes());
1887                }
1888                anim_float_total += time_count;
1889                let first_value: u32 = anim_float_total;
1890                let value_count: u32 = samp.get_values().len() as u32;
1891                for &val in samp.get_values().iter() {
1892                    anim_blob.extend_from_slice(&val.to_le_bytes());
1893                }
1894                anim_float_total += value_count;
1895                let interpolation: u8 = match samp.get_interpolation() {
1896                    GltfInterpolationMode::Step => 0,
1897                    GltfInterpolationMode::Linear => 1,
1898                    GltfInterpolationMode::CubicSpline => 2,
1899                };
1900                samplers.push(Euv3dAnimSamplerRecord {
1901                    first_time,
1902                    time_count,
1903                    first_value,
1904                    value_count,
1905                    value_stride: samp.get_value_stride() as u32,
1906                    interpolation,
1907                });
1908            }
1909            let channels: Vec<Euv3dAnimChannelRecord> = clip
1910                .get_channels()
1911                .iter()
1912                .map(|ch: &ImportedAnimationChannel3D| {
1913                    let path: u8 = match ch.get_path() {
1914                        GltfAnimationPath::Translation => 0,
1915                        GltfAnimationPath::Rotation => 1,
1916                        GltfAnimationPath::Scale => 2,
1917                        GltfAnimationPath::MorphWeights => 3,
1918                    };
1919                    Euv3dAnimChannelRecord {
1920                        target_node: ch.get_target_node(),
1921                        path,
1922                        sampler_index: ch.get_sampler_index() as u32,
1923                    }
1924                })
1925                .collect();
1926            animations.push(Euv3dAnimClipRecord {
1927                name: clip.get_name().clone(),
1928                duration_secs: clip.get_duration_secs(),
1929                samplers,
1930                channels,
1931            });
1932        }
1933        let cameras: Vec<Euv3dCameraRecord> = scene
1934            .get_cameras()
1935            .iter()
1936            .map(|cam: &ImportedCamera3D| match cam.get_projection() {
1937                GltfCameraProjection::Perspective {
1938                    yfov_rad,
1939                    aspect_ratio,
1940                    znear,
1941                    zfar,
1942                } => Euv3dCameraRecord {
1943                    name: cam.get_name().clone(),
1944                    is_perspective: true,
1945                    param_a: yfov_rad,
1946                    param_b: aspect_ratio.unwrap_or(-1.0),
1947                    znear,
1948                    zfar,
1949                },
1950                GltfCameraProjection::Orthographic {
1951                    xmag,
1952                    ymag,
1953                    znear,
1954                    zfar,
1955                } => Euv3dCameraRecord {
1956                    name: cam.get_name().clone(),
1957                    is_perspective: false,
1958                    param_a: xmag,
1959                    param_b: ymag,
1960                    znear,
1961                    zfar: Some(zfar),
1962                },
1963            })
1964            .collect();
1965        let lights: Vec<Euv3dLightRecord> = scene
1966            .get_lights()
1967            .iter()
1968            .map(|light: &ImportedLight3D| match light.get_kind() {
1969                GltfLightKind::Directional => Euv3dLightRecord {
1970                    name: light.get_name().clone(),
1971                    color: light.get_color().to_array(),
1972                    intensity: light.get_intensity(),
1973                    kind: 0,
1974                    range: None,
1975                    param_a: 0.0,
1976                    param_b: 0.0,
1977                },
1978                GltfLightKind::Point { range } => Euv3dLightRecord {
1979                    name: light.get_name().clone(),
1980                    color: light.get_color().to_array(),
1981                    intensity: light.get_intensity(),
1982                    kind: 1,
1983                    range,
1984                    param_a: 0.0,
1985                    param_b: 0.0,
1986                },
1987                GltfLightKind::Spot {
1988                    range,
1989                    inner_cone_angle,
1990                    outer_cone_angle,
1991                } => Euv3dLightRecord {
1992                    name: light.get_name().clone(),
1993                    color: light.get_color().to_array(),
1994                    intensity: light.get_intensity(),
1995                    kind: 2,
1996                    range,
1997                    param_a: inner_cone_angle,
1998                    param_b: outer_cone_angle,
1999                },
2000                GltfLightKind::Area { width, height } => Euv3dLightRecord {
2001                    name: light.get_name().clone(),
2002                    color: light.get_color().to_array(),
2003                    intensity: light.get_intensity(),
2004                    kind: 3,
2005                    range: None,
2006                    param_a: width,
2007                    param_b: height,
2008                },
2009            })
2010            .collect();
2011        let metadata: Euv3dSceneMetadata = Euv3dSceneMetadata {
2012            name: scene.get_name().clone(),
2013            generator: scene.get_generator().clone(),
2014            collections,
2015            nodes,
2016            meshes: mesh_records,
2017            bvhs: bvh_records,
2018            materials,
2019            textures,
2020            skins,
2021            animations,
2022            cameras,
2023            lights,
2024        };
2025        let meta_json: String =
2026            to_string(&metadata).map_err(|_| ERR_EUV3D_BAD_METADATA.to_string())?;
2027        let meta_bytes: Vec<u8> = meta_json.into_bytes();
2028        let mut payload_sections: Vec<(Euv3dSectionKind, u32, Vec<u8>)> = Vec::with_capacity(12);
2029        payload_sections.push((Euv3dSectionKind::SceneMetadataJson, 1, meta_bytes));
2030        if !mip_tail_blob.is_empty() {
2031            payload_sections.push((
2032                Euv3dSectionKind::TextureMipTails,
2033                tex_count as u32,
2034                mip_tail_blob,
2035            ));
2036        }
2037        if !qverts_blob.is_empty() {
2038            payload_sections.push((
2039                Euv3dSectionKind::QuantizedVertices,
2040                vertex_total,
2041                qverts_blob,
2042            ));
2043        }
2044        if !indices_blob.is_empty() {
2045            payload_sections.push((Euv3dSectionKind::Indices, tri_total, indices_blob));
2046        }
2047        if !qskins_blob.is_empty() {
2048            payload_sections.push((
2049                Euv3dSectionKind::QuantizedSkinInfluences,
2050                skin_total,
2051                qskins_blob,
2052            ));
2053        }
2054        if !morph_blob.is_empty() {
2055            payload_sections.push((Euv3dSectionKind::MorphDeltas, morph_vec_total, morph_blob));
2056        }
2057        if !qmeshlets_blob.is_empty() {
2058            payload_sections.push((
2059                Euv3dSectionKind::QuantizedMeshlets,
2060                meshlet_total,
2061                qmeshlets_blob,
2062            ));
2063        }
2064        if !bvh4_blob.is_empty() {
2065            payload_sections.push((Euv3dSectionKind::Bvh4Nodes, bvh4_total, bvh4_blob));
2066        }
2067        if !bvh_pkt_blob.is_empty() {
2068            payload_sections.push((
2069                Euv3dSectionKind::BvhTri4Packets,
2070                bvh_pkt_total,
2071                bvh_pkt_blob,
2072            ));
2073        }
2074        if !bvh_tri_blob.is_empty() {
2075            payload_sections.push((Euv3dSectionKind::BvhTriangles, bvh_tri_total, bvh_tri_blob));
2076        }
2077        if !anim_blob.is_empty() {
2078            payload_sections.push((
2079                Euv3dSectionKind::AnimationsBlob,
2080                anim_float_total,
2081                anim_blob,
2082            ));
2083        }
2084        if !mip_high_blob.is_empty() {
2085            payload_sections.push((
2086                Euv3dSectionKind::TextureMipHigh,
2087                tex_count as u32,
2088                mip_high_blob,
2089            ));
2090        }
2091        let section_count: usize = payload_sections.len();
2092        let table_offset: usize = EUV3D_HEADER_BYTES;
2093        let mut cursor: usize =
2094            align_up_64(table_offset + section_count * EUV3D_SECTION_ENTRY_BYTES);
2095        let mut entries: Vec<Euv3dSectionEntry> = Vec::with_capacity(section_count);
2096        for &(kind, elem_count, ref data) in &payload_sections {
2097            let sec_off: usize = align_up_64(cursor);
2098            entries.push(Euv3dSectionEntry {
2099                kind,
2100                offset: sec_off as u64,
2101                byte_length: data.len() as u64,
2102                element_count: elem_count,
2103                flags: 0,
2104            });
2105            cursor = align_up_64(sec_off + data.len());
2106        }
2107        let total_bytes: usize = cursor;
2108        let mut out: Vec<u8> = vec![0u8; total_bytes];
2109        for (idx, entry) in entries.iter().enumerate() {
2110            let pos: usize = table_offset + idx * EUV3D_SECTION_ENTRY_BYTES;
2111            out[pos..(pos + 4)].copy_from_slice(&entry.get_kind().to_u32().to_le_bytes());
2112            out[(pos + 4)..(pos + 8)].copy_from_slice(&entry.get_flags().to_le_bytes());
2113            out[(pos + 8)..(pos + 16)].copy_from_slice(&entry.get_offset().to_le_bytes());
2114            out[(pos + 16)..(pos + 24)].copy_from_slice(&entry.get_byte_length().to_le_bytes());
2115            out[(pos + 24)..(pos + 28)].copy_from_slice(&entry.get_element_count().to_le_bytes());
2116            let data: &[u8] = &payload_sections[idx].2;
2117            let dst_start: usize = entry.get_offset() as usize;
2118            out[dst_start..(dst_start + data.len())].copy_from_slice(data);
2119        }
2120        let mut flags: u32 = EUV3D_FLAG_QUANTIZED_V2 | EUV3D_FLAG_MIP_TAIL_FIRST;
2121        if config.get_bake_bvh4() && bvh4_total > 0 {
2122            flags |= EUV3D_FLAG_HAS_BVH4;
2123        }
2124        if config.get_build_meshlets() && meshlet_total > 0 {
2125            flags |= EUV3D_FLAG_HAS_MESHLETS;
2126        }
2127        if max_lods > 1 {
2128            flags |= EUV3D_FLAG_HAS_LODS;
2129        }
2130        let content_crc32: u32 = compute_crc32(&out[EUV3D_HEADER_BYTES..]);
2131        let digest_fnv1a: u64 = compute_fnv1a_64(&out[EUV3D_HEADER_BYTES..]);
2132        out[0..8].copy_from_slice(&EUV3D_MAGIC);
2133        out[8..12].copy_from_slice(&EUV3D_FORMAT_VERSION_V2.to_le_bytes());
2134        out[12..16].copy_from_slice(&flags.to_le_bytes());
2135        out[16..20].copy_from_slice(&(section_count as u32).to_le_bytes());
2136        out[24..32].copy_from_slice(&(table_offset as u64).to_le_bytes());
2137        out[32..36].copy_from_slice(&content_crc32.to_le_bytes());
2138        let header_crc32: u32 = compute_crc32(&out[..36]);
2139        out[36..40].copy_from_slice(&header_crc32.to_le_bytes());
2140        out[40..48].copy_from_slice(&(total_bytes as u64).to_le_bytes());
2141        out[48..56].copy_from_slice(&digest_fnv1a.to_le_bytes());
2142        Ok(out)
2143    }
2144
2145    /// Decodes a quantized `.euv3d` v2 binary buffer into a `BakedAssetBundle3D`.
2146    ///
2147    /// # Arguments
2148    ///
2149    /// - `&[u8]` - Raw `.euv3d` v2 binary buffer.
2150    ///
2151    /// # Returns
2152    ///
2153    /// - `Result<BakedAssetBundle3D, String>` - Restored scene, QEM LOD chains, and ready-to-trace BVH4 trees.
2154    pub fn decode_v2_bytes(bytes: &[u8]) -> Result<BakedAssetBundle3D, String> {
2155        let view: Euv3dPackageView<'_> = Euv3dPackageView::from_bytes(bytes)?;
2156        if view.get_header().get_version() == EUV3D_FORMAT_VERSION {
2157            return Self::decode_bytes(bytes);
2158        }
2159        let meta_slice: &[u8] = view
2160            .section_bytes(Euv3dSectionKind::SceneMetadataJson)
2161            .ok_or_else(|| ERR_EUV3D_MISSING_METADATA.to_string())?;
2162        let meta_str: &str =
2163            from_utf8(meta_slice).map_err(|_| ERR_EUV3D_BAD_METADATA.to_string())?;
2164        let meta: Euv3dSceneMetadata =
2165            from_str(meta_str).map_err(|_| ERR_EUV3D_BAD_METADATA.to_string())?;
2166        let qverts_slice: &[u8] = view
2167            .section_bytes(Euv3dSectionKind::QuantizedVertices)
2168            .unwrap_or(&[]);
2169        let idx_slice: &[u8] = view.section_bytes(Euv3dSectionKind::Indices).unwrap_or(&[]);
2170        let qskin_slice: &[u8] = view
2171            .section_bytes(Euv3dSectionKind::QuantizedSkinInfluences)
2172            .unwrap_or(&[]);
2173        let morph_slice: &[u8] = view
2174            .section_bytes(Euv3dSectionKind::MorphDeltas)
2175            .unwrap_or(&[]);
2176        let qmlet_slice: &[u8] = view
2177            .section_bytes(Euv3dSectionKind::QuantizedMeshlets)
2178            .unwrap_or(&[]);
2179        let bvh4_slice: &[u8] = view
2180            .section_bytes(Euv3dSectionKind::Bvh4Nodes)
2181            .unwrap_or(&[]);
2182        let bvh_pkt_slice: &[u8] = view
2183            .section_bytes(Euv3dSectionKind::BvhTri4Packets)
2184            .unwrap_or(&[]);
2185        let bvh_tri_slice: &[u8] = view
2186            .section_bytes(Euv3dSectionKind::BvhTriangles)
2187            .unwrap_or(&[]);
2188        let anim_slice: &[u8] = view
2189            .section_bytes(Euv3dSectionKind::AnimationsBlob)
2190            .unwrap_or(&[]);
2191        let mip_tail_slice: &[u8] = view
2192            .section_bytes(Euv3dSectionKind::TextureMipTails)
2193            .unwrap_or(&[]);
2194        let mip_high_slice: &[u8] = view
2195            .section_bytes(Euv3dSectionKind::TextureMipHigh)
2196            .unwrap_or(&[]);
2197        let mut lod_chains: Vec<MeshLodChain> = Vec::with_capacity(meta.meshes.len());
2198        let mut lod0_meshes: Vec<Mesh3D> = Vec::with_capacity(meta.meshes.len());
2199        for mesh_rec in &meta.meshes {
2200            let mut levels: Vec<Mesh3D> = Vec::with_capacity(mesh_rec.lods.len());
2201            let base_mat: PbrMaterial = record_to_pbr(&mesh_rec.material);
2202            let sub_mats: Vec<PbrMaterial> =
2203                mesh_rec.sub_materials.iter().map(record_to_pbr).collect();
2204            for (lod_idx, lod_rec) in mesh_rec.lods.iter().enumerate() {
2205                let bounds_min: Vec3 = Vec3::from_array(lod_rec.bounds_min);
2206                let bounds_max: Vec3 = Vec3::from_array(lod_rec.bounds_max);
2207                let mut vertices: Vec<Vertex3D> = Vec::with_capacity(lod_rec.vertex_count as usize);
2208                for v_i in 0..(lod_rec.vertex_count as usize) {
2209                    let off: usize =
2210                        ((lod_rec.first_vertex as usize) + v_i) * EUV3D_V2_VERTEX_STRIDE_BYTES;
2211                    let qv: QuantizedVertex3D = read_quantized_vertex_bytes(qverts_slice, off)?;
2212                    vertices.push(dequantize_euv3d_vertex(&qv, bounds_min, bounds_max));
2213                }
2214                let mut indices: Vec<[u32; 3]> = Vec::with_capacity(lod_rec.tri_count as usize);
2215                for t_i in 0..(lod_rec.tri_count as usize) {
2216                    let off: usize = ((lod_rec.first_tri as usize) + t_i) * EUV3D_INDEX_TRI_BYTES;
2217                    let i0: u32 = read_u32_le(idx_slice, off)?;
2218                    let i1: u32 = read_u32_le(idx_slice, off + 4)?;
2219                    let i2: u32 = read_u32_le(idx_slice, off + 8)?;
2220                    indices.push([i0, i1, i2]);
2221                }
2222                let mut meshlets: Vec<Meshlet3D> =
2223                    Vec::with_capacity(lod_rec.meshlet_count as usize);
2224                for m_i in 0..(lod_rec.meshlet_count as usize) {
2225                    let off: usize =
2226                        ((lod_rec.first_meshlet as usize) + m_i) * EUV3D_V2_MESHLET_STRIDE_BYTES;
2227                    let qm: QuantizedMeshlet3D = read_quantized_meshlet_bytes(qmlet_slice, off)?;
2228                    let ax: [i8; 3] = qm.get_cone_axis_s8();
2229                    let cone_axis: Vec3 = Vec3::new(
2230                        f32::from(ax[0]) / 127.0,
2231                        f32::from(ax[1]) / 127.0,
2232                        f32::from(ax[2]) / 127.0,
2233                    )
2234                    .normalize();
2235                    let cutoff_sin: f32 =
2236                        (f32::from(qm.get_cone_cutoff_s8()) / 127.0).clamp(-1.0, 1.0);
2237                    let cone_cutoff: f32 = if cutoff_sin >= 0.995 {
2238                        0.0
2239                    } else {
2240                        (1.0 - cutoff_sin * cutoff_sin).max(0.0).sqrt()
2241                    };
2242                    meshlets.push(Meshlet3D::new(
2243                        qm.get_first_tri(),
2244                        qm.get_tri_count(),
2245                        AxisAlignedBox3D::new(
2246                            Vec3::from_array(qm.get_bounds_min()),
2247                            Vec3::from_array(qm.get_bounds_max()),
2248                        ),
2249                        cone_axis,
2250                        cone_cutoff,
2251                        qm.get_sphere_radius() * 0.01,
2252                    ));
2253                }
2254                let bounds: AxisAlignedBox3D = AxisAlignedBox3D::new(bounds_min, bounds_max);
2255                let mut skin_influences: Vec<MeshSkinInfluence3D> = Vec::new();
2256                let mut morph_targets: Vec<MorphTarget3D> = Vec::new();
2257                if lod_idx == 0 {
2258                    skin_influences.reserve(mesh_rec.skin_count as usize);
2259                    for s_i in 0..(mesh_rec.skin_count as usize) {
2260                        let off: usize =
2261                            ((mesh_rec.first_skin as usize) + s_i) * EUV3D_V2_SKIN_STRIDE_BYTES;
2262                        let qs: QuantizedSkinVertex3D =
2263                            read_quantized_skin_bytes(qskin_slice, off)?;
2264                        skin_influences.push(dequantize_euv3d_skin_vertex(&qs));
2265                    }
2266                    morph_targets.reserve(mesh_rec.morphs.len());
2267                    for m_rec in &mesh_rec.morphs {
2268                        let mut delta_positions: Vec<[f32; 3]> =
2269                            Vec::with_capacity(m_rec.pos_count as usize);
2270                        for p_i in 0..(m_rec.pos_count as usize) {
2271                            let off: usize = ((m_rec.first_pos as usize) + p_i) * 12;
2272                            delta_positions.push([
2273                                read_f32_le(morph_slice, off)?,
2274                                read_f32_le(morph_slice, off + 4)?,
2275                                read_f32_le(morph_slice, off + 8)?,
2276                            ]);
2277                        }
2278                        let mut delta_normals: Vec<[f32; 3]> =
2279                            Vec::with_capacity(m_rec.norm_count as usize);
2280                        for n_i in 0..(m_rec.norm_count as usize) {
2281                            let off: usize = ((m_rec.first_norm as usize) + n_i) * 12;
2282                            delta_normals.push([
2283                                read_f32_le(morph_slice, off)?,
2284                                read_f32_le(morph_slice, off + 4)?,
2285                                read_f32_le(morph_slice, off + 8)?,
2286                            ]);
2287                        }
2288                        let mut delta_tangents: Vec<[f32; 3]> =
2289                            Vec::with_capacity(m_rec.tan_count as usize);
2290                        for t_i in 0..(m_rec.tan_count as usize) {
2291                            let off: usize = ((m_rec.first_tan as usize) + t_i) * 12;
2292                            delta_tangents.push([
2293                                read_f32_le(morph_slice, off)?,
2294                                read_f32_le(morph_slice, off + 4)?,
2295                                read_f32_le(morph_slice, off + 8)?,
2296                            ]);
2297                        }
2298                        morph_targets.push(MorphTarget3D {
2299                            name: m_rec.name.clone(),
2300                            delta_positions,
2301                            delta_normals,
2302                            delta_tangents,
2303                        });
2304                    }
2305                }
2306                levels.push(Mesh3D {
2307                    name: mesh_rec.name.clone(),
2308                    vertices,
2309                    indices,
2310                    bounds,
2311                    material: base_mat,
2312                    sub_materials: if lod_idx == 0 {
2313                        sub_mats.clone()
2314                    } else {
2315                        Vec::new()
2316                    },
2317                    tri_materials: if lod_idx == 0 {
2318                        mesh_rec.tri_materials.clone()
2319                    } else {
2320                        Vec::new()
2321                    },
2322                    meshlets,
2323                    skin_influences,
2324                    morph_targets,
2325                    material_index: mesh_rec.material_index,
2326                    is_closed: mesh_rec.is_closed,
2327                });
2328            }
2329            if let Some(first_level) = levels.first() {
2330                lod0_meshes.push(first_level.clone());
2331            }
2332            lod_chains.push(MeshLodChain { levels });
2333        }
2334        let mut local_bvhs: Vec<Bvh3D> = Vec::with_capacity(meta.bvhs.len());
2335        for bvh_rec in &meta.bvhs {
2336            let mut bvh4_nodes: Vec<Bvh4Node> = Vec::with_capacity(bvh_rec.node_count as usize);
2337            for n_i in 0..(bvh_rec.node_count as usize) {
2338                let off: usize =
2339                    ((bvh_rec.first_node as usize) + n_i) * EUV3D_BVH4_NODE_STRIDE_BYTES;
2340                bvh4_nodes.push(read_bvh4_node_bytes(bvh4_slice, off)?);
2341            }
2342            let mut leaf_packets: Vec<BvhTri4> = Vec::with_capacity(bvh_rec.packet_count as usize);
2343            for p_i in 0..(bvh_rec.packet_count as usize) {
2344                let off: usize =
2345                    ((bvh_rec.first_packet as usize) + p_i) * EUV3D_BVH_TRI4_STRIDE_BYTES;
2346                leaf_packets.push(read_bvh_tri4_bytes(bvh_pkt_slice, off)?);
2347            }
2348            let mut triangles: Vec<BvhTriangle> = Vec::with_capacity(bvh_rec.tri_count as usize);
2349            for t_i in 0..(bvh_rec.tri_count as usize) {
2350                let off: usize = ((bvh_rec.first_tri as usize) + t_i) * EUV3D_BVH_TRI_STRIDE_BYTES;
2351                triangles.push(read_bvh_tri_bytes(bvh_tri_slice, off)?);
2352            }
2353            for node in &bvh4_nodes {
2354                let valid: usize = (node.valid_count as usize).min(4);
2355                for lane in 0..valid {
2356                    let lc: usize = node.leaf_count[lane] as usize;
2357                    let ch: usize = node.child[lane] as usize;
2358                    if lc > 0 {
2359                        if ch
2360                            .checked_add(lc)
2361                            .is_none_or(|end: usize| end > leaf_packets.len())
2362                        {
2363                            return Err(ERR_EUV3D_INVALID_BVH4.to_string());
2364                        }
2365                    } else if ch >= bvh4_nodes.len() {
2366                        return Err(ERR_EUV3D_INVALID_BVH4.to_string());
2367                    }
2368                }
2369            }
2370            for pkt in &leaf_packets {
2371                for &t_idx in &pkt.tri_indices {
2372                    if t_idx != u32::MAX && (t_idx as usize) >= triangles.len() {
2373                        return Err(ERR_EUV3D_INVALID_BVH4.to_string());
2374                    }
2375                }
2376            }
2377            let geom: Vec<BvhGeomTri> = triangles.iter().map(BvhGeomTri::from_triangle).collect();
2378            let orig_indices: Vec<u32> = (0..triangles.len()).map(|i: usize| i as u32).collect();
2379            local_bvhs.push(Bvh3D {
2380                nodes: Vec::new(),
2381                triangles,
2382                geom,
2383                leaf_packets,
2384                flat_nodes: Vec::new(),
2385                bvh4_nodes,
2386                bvh4_src_children: Vec::new(),
2387                root_min: bvh_rec.root_min,
2388                root_max: bvh_rec.root_max,
2389                #[cfg(target_arch = "x86_64")]
2390                bvh8_nodes: Vec::new(),
2391                #[cfg(target_arch = "x86_64")]
2392                bvh8_src_children: Vec::new(),
2393                orig_indices,
2394                node_to_flat: Vec::new(),
2395                build_sah_cost: bvh_rec.build_sah_cost,
2396            });
2397        }
2398        let mut scene_graph: SceneGraph3D = SceneGraph3D::default();
2399        if !meta.collections.is_empty() {
2400            let mut active_mask: u64 = 0;
2401            let entries: Vec<CollectionEntry3D> = meta
2402                .collections
2403                .iter()
2404                .map(|c: &Euv3dCollectionRecord| {
2405                    if c.visible_viewport && c.bit_index < 64 {
2406                        active_mask |= 1u64 << u32::from(c.bit_index);
2407                    }
2408                    CollectionEntry3D {
2409                        name: c.name.clone(),
2410                        bit_index: c.bit_index,
2411                        visible_viewport: c.visible_viewport,
2412                        visible_render: c.visible_render,
2413                    }
2414                })
2415                .collect();
2416            scene_graph.set_collections(CollectionRegistry3D {
2417                entries,
2418                active_mask,
2419            });
2420        }
2421        for n_rec in &meta.nodes {
2422            let mut node: SceneNode3D = SceneNode3D::from_name(&n_rec.name, n_rec.parent);
2423            node.set_local_translation(Vec3::from_array(n_rec.translation));
2424            node.set_local_rotation(Quat::from_array(n_rec.rotation));
2425            node.set_local_scale(Vec3::from_array(n_rec.scale));
2426            node.set_mesh_id(n_rec.mesh_id);
2427            node.set_skin_id(n_rec.skin_id);
2428            node.set_camera_id(n_rec.camera_id);
2429            node.set_light_id(n_rec.light_id);
2430            node.set_collection_mask(n_rec.collection_mask);
2431            node.set_visible(n_rec.visible);
2432            let collider: SceneColliderShape3D = match n_rec.collider_shape {
2433                1 => SceneColliderShape3D::Box,
2434                2 => SceneColliderShape3D::Sphere,
2435                3 => SceneColliderShape3D::ConvexHull,
2436                4 => SceneColliderShape3D::Mesh,
2437                _ => SceneColliderShape3D::None,
2438            };
2439            node.set_extras(BlenderExtrasTags3D {
2440                collider,
2441                buoyancy_density: n_rec.buoyancy_density,
2442                is_trigger: n_rec.is_trigger,
2443                cast_shadows: n_rec.cast_shadows,
2444                custom_json: n_rec.custom_json.clone(),
2445            });
2446            let node_id: u32 = scene_graph.add_node(node);
2447            if !n_rec.morph_weights.is_empty() {
2448                scene_graph.attach_morph_weights(node_id, &n_rec.morph_weights);
2449            }
2450        }
2451        let _: usize = scene_graph.propagate_world_matrices();
2452        let materials: Vec<PrincipledMaterial3D> =
2453            meta.materials.iter().map(record_to_material).collect();
2454        let mut textures: Vec<Texture2D3D> = Vec::with_capacity(meta.textures.len());
2455        for t_rec in &meta.textures {
2456            let color_space: TextureColorSpace = match t_rec.color_space {
2457                1 => TextureColorSpace::Linear,
2458                2 => TextureColorSpace::NormalTangent,
2459                _ => TextureColorSpace::Srgb,
2460            };
2461            let decode_filter: fn(u8) -> TextureFilterMode = |tag: u8| match tag {
2462                0 => TextureFilterMode::Nearest,
2463                2 => TextureFilterMode::NearestMipmapNearest,
2464                3 => TextureFilterMode::LinearMipmapNearest,
2465                4 => TextureFilterMode::NearestMipmapLinear,
2466                5 => TextureFilterMode::LinearMipmapLinear,
2467                _ => TextureFilterMode::Linear,
2468            };
2469            let min_filter: TextureFilterMode = decode_filter(t_rec.min_filter);
2470            let mag_filter: TextureFilterMode = decode_filter(t_rec.mag_filter);
2471            let wrap_s: TextureWrapMode = match t_rec.wrap_s {
2472                1 => TextureWrapMode::MirroredRepeat,
2473                2 => TextureWrapMode::ClampToEdge,
2474                _ => TextureWrapMode::Repeat,
2475            };
2476            let wrap_t: TextureWrapMode = match t_rec.wrap_t {
2477                1 => TextureWrapMode::MirroredRepeat,
2478                2 => TextureWrapMode::ClampToEdge,
2479                _ => TextureWrapMode::Repeat,
2480            };
2481            let mut mips: Vec<TextureMipLevel3D> = Vec::with_capacity(t_rec.mips.len());
2482            for mip_rec in &t_rec.mips {
2483                let backing: &[u8] = if mip_rec.is_mip_tail {
2484                    mip_tail_slice
2485                } else {
2486                    mip_high_slice
2487                };
2488                let start: usize = mip_rec.byte_offset as usize;
2489                let end: usize = start
2490                    .checked_add(mip_rec.byte_length as usize)
2491                    .ok_or_else(|| ERR_EUV3D_TRUNCATED_BLOB.to_string())?;
2492                if end > backing.len() {
2493                    return Err(ERR_EUV3D_TRUNCATED_BLOB.to_string());
2494                }
2495                mips.push(TextureMipLevel3D {
2496                    width: mip_rec.width,
2497                    height: mip_rec.height,
2498                    pixels: backing[start..end].to_vec(),
2499                });
2500            }
2501            let (width, height): (u32, u32) = mips
2502                .first()
2503                .map(|m: &TextureMipLevel3D| (m.get_width(), m.get_height()))
2504                .unwrap_or((0, 0));
2505            textures.push(Texture2D3D {
2506                name: t_rec.name.clone(),
2507                width,
2508                height,
2509                color_space,
2510                sampler: TextureSampler3D::new(mag_filter, min_filter, wrap_s, wrap_t),
2511                mips,
2512            });
2513        }
2514        let skins: Vec<ImportedSkin3D> = meta
2515            .skins
2516            .iter()
2517            .map(|s: &Euv3dSkinRecord| ImportedSkin3D {
2518                name: s.name.clone(),
2519                joints: s.joints.clone(),
2520                skeleton_root: s.skeleton_root,
2521                inverse_bind_matrices: s
2522                    .inverse_bind_matrices
2523                    .iter()
2524                    .map(|arr: &[f32; 16]| Mat4::from_cols_array(*arr))
2525                    .collect(),
2526            })
2527            .collect();
2528        let mut animations: Vec<ImportedAnimationClip3D> =
2529            Vec::with_capacity(meta.animations.len());
2530        for c_rec in &meta.animations {
2531            let mut samplers: Vec<ImportedAnimationSampler3D> =
2532                Vec::with_capacity(c_rec.samplers.len());
2533            for s_rec in &c_rec.samplers {
2534                let mut timestamps: Vec<f32> = Vec::with_capacity(s_rec.time_count as usize);
2535                for i in 0..(s_rec.time_count as usize) {
2536                    timestamps.push(read_f32_le(
2537                        anim_slice,
2538                        ((s_rec.first_time as usize) + i) * 4,
2539                    )?);
2540                }
2541                let mut values: Vec<f32> = Vec::with_capacity(s_rec.value_count as usize);
2542                for i in 0..(s_rec.value_count as usize) {
2543                    values.push(read_f32_le(
2544                        anim_slice,
2545                        ((s_rec.first_value as usize) + i) * 4,
2546                    )?);
2547                }
2548                let interpolation: GltfInterpolationMode = match s_rec.interpolation {
2549                    0 => GltfInterpolationMode::Step,
2550                    2 => GltfInterpolationMode::CubicSpline,
2551                    _ => GltfInterpolationMode::Linear,
2552                };
2553                samplers.push(ImportedAnimationSampler3D {
2554                    timestamps,
2555                    values,
2556                    value_stride: s_rec.value_stride as usize,
2557                    interpolation,
2558                });
2559            }
2560            let channels: Vec<ImportedAnimationChannel3D> = c_rec
2561                .channels
2562                .iter()
2563                .map(|ch: &Euv3dAnimChannelRecord| {
2564                    let path: GltfAnimationPath = match ch.path {
2565                        1 => GltfAnimationPath::Rotation,
2566                        2 => GltfAnimationPath::Scale,
2567                        3 => GltfAnimationPath::MorphWeights,
2568                        _ => GltfAnimationPath::Translation,
2569                    };
2570                    ImportedAnimationChannel3D::new(ch.target_node, path, ch.sampler_index as usize)
2571                })
2572                .collect();
2573            animations.push(ImportedAnimationClip3D {
2574                name: c_rec.name.clone(),
2575                duration_secs: c_rec.duration_secs,
2576                samplers,
2577                channels,
2578            });
2579        }
2580        let cameras: Vec<ImportedCamera3D> = meta
2581            .cameras
2582            .iter()
2583            .map(|c: &Euv3dCameraRecord| {
2584                let projection: GltfCameraProjection = if c.is_perspective {
2585                    GltfCameraProjection::Perspective {
2586                        yfov_rad: c.param_a,
2587                        aspect_ratio: if c.param_b > 0.0 {
2588                            Some(c.param_b)
2589                        } else {
2590                            None
2591                        },
2592                        znear: c.znear,
2593                        zfar: c.zfar,
2594                    }
2595                } else {
2596                    GltfCameraProjection::Orthographic {
2597                        xmag: c.param_a,
2598                        ymag: c.param_b,
2599                        znear: c.znear,
2600                        zfar: c.zfar.unwrap_or(1000.0),
2601                    }
2602                };
2603                ImportedCamera3D {
2604                    name: c.name.clone(),
2605                    projection,
2606                }
2607            })
2608            .collect();
2609        let lights: Vec<ImportedLight3D> = meta
2610            .lights
2611            .iter()
2612            .map(|l: &Euv3dLightRecord| {
2613                let kind: GltfLightKind = match l.kind {
2614                    1 => GltfLightKind::Point { range: l.range },
2615                    2 => GltfLightKind::Spot {
2616                        range: l.range,
2617                        inner_cone_angle: l.param_a,
2618                        outer_cone_angle: l.param_b,
2619                    },
2620                    3 => GltfLightKind::Area {
2621                        width: l.param_a,
2622                        height: l.param_b,
2623                    },
2624                    _ => GltfLightKind::Directional,
2625                };
2626                ImportedLight3D {
2627                    name: l.name.clone(),
2628                    color: Vec3::from_array(l.color),
2629                    intensity: l.intensity,
2630                    kind,
2631                }
2632            })
2633            .collect();
2634        let scene: ImportedScene3D = ImportedScene3D {
2635            name: meta.name,
2636            generator: meta.generator,
2637            scene_graph,
2638            meshes: lod0_meshes,
2639            materials,
2640            textures,
2641            skins,
2642            animations,
2643            cameras,
2644            lights,
2645        };
2646        let header: Euv3dHeader = view.get_header();
2647        Ok(BakedAssetBundle3D {
2648            scene,
2649            lod_chains,
2650            local_bvhs,
2651            section_count: view.get_sections().len(),
2652            total_bytes: header.get_total_bytes() as usize,
2653            digest_fnv1a: header.get_digest_fnv1a(),
2654        })
2655    }
2656
2657    /// Decodes either an `.euv3d` v1 or `.euv3d` v2 binary buffer by automatically dispatching on the header format version.
2658    ///
2659    /// # Arguments
2660    ///
2661    /// - `&[u8]` - Raw `.euv3d` v1 or v2 binary buffer.
2662    ///
2663    /// # Returns
2664    ///
2665    /// - `Result<BakedAssetBundle3D, String>` - Restored scene, QEM LOD chains, and ready-to-trace BVH4 trees.
2666    pub fn decode_any_bytes(bytes: &[u8]) -> Result<BakedAssetBundle3D, String> {
2667        if bytes.len() >= 12 {
2668            let version: u32 = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
2669            if version == EUV3D_FORMAT_VERSION_V2 {
2670                return Self::decode_v2_bytes(bytes);
2671            }
2672        }
2673        Self::decode_bytes(bytes)
2674    }
2675}