1use super::*;
2
3impl Euv3dSectionKind {
5 #[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 _ => None,
30 }
31 }
32
33 #[must_use]
43 pub const fn to_u32(&self) -> u32 {
44 *self as u32
45 }
46}
47
48impl Default for Euv3dBakeConfig {
50 fn default() -> Self {
56 Self {
57 lod_levels: EUV3D_DEFAULT_LOD_LEVELS,
58 build_meshlets: true,
59 bake_bvh4: true,
60 generate_mipmaps: true,
61 }
62 }
63}
64
65impl QemMatrix {
67 #[must_use]
80 pub(crate) fn from_plane(a: f64, b: f64, c: f64, d: f64) -> Self {
81 Self {
82 coeffs: [
83 a * a,
84 a * b,
85 a * c,
86 a * d,
87 b * b,
88 b * c,
89 b * d,
90 c * c,
91 c * d,
92 d * d,
93 ],
94 }
95 }
96
97 #[must_use]
108 pub(crate) fn add(&self, other: Self) -> Self {
109 let Self { coeffs: a } = *self;
110 let Self { coeffs: b } = other;
111 Self {
112 coeffs: [
113 a[0] + b[0],
114 a[1] + b[1],
115 a[2] + b[2],
116 a[3] + b[3],
117 a[4] + b[4],
118 a[5] + b[5],
119 a[6] + b[6],
120 a[7] + b[7],
121 a[8] + b[8],
122 a[9] + b[9],
123 ],
124 }
125 }
126
127 #[must_use]
138 pub(crate) fn scale(&self, factor: f64) -> Self {
139 let Self { coeffs: a } = *self;
140 Self {
141 coeffs: [
142 a[0] * factor,
143 a[1] * factor,
144 a[2] * factor,
145 a[3] * factor,
146 a[4] * factor,
147 a[5] * factor,
148 a[6] * factor,
149 a[7] * factor,
150 a[8] * factor,
151 a[9] * factor,
152 ],
153 }
154 }
155
156 #[must_use]
167 pub(crate) fn evaluate(&self, pos: [f64; 3]) -> f64 {
168 let Self { coeffs: q } = *self;
169 let x: f64 = pos[0];
170 let y: f64 = pos[1];
171 let z: f64 = pos[2];
172 q[0] * x * x
173 + 2.0 * q[1] * x * y
174 + 2.0 * q[2] * x * z
175 + 2.0 * q[3] * x
176 + q[4] * y * y
177 + 2.0 * q[5] * y * z
178 + 2.0 * q[6] * y
179 + q[7] * z * z
180 + 2.0 * q[8] * z
181 + q[9]
182 }
183
184 #[must_use]
194 pub(crate) fn solve_optimal(&self) -> Option<[f64; 3]> {
195 let Self { coeffs: q } = *self;
196 let a00: f64 = q[0];
197 let a01: f64 = q[1];
198 let a02: f64 = q[2];
199 let a11: f64 = q[4];
200 let a12: f64 = q[5];
201 let a22: f64 = q[7];
202 let c00: f64 = a11 * a22 - a12 * a12;
203 let c01: f64 = -(a01 * a22 - a12 * a02);
204 let c02: f64 = a01 * a12 - a11 * a02;
205 let det: f64 = a00 * c00 + a01 * c01 + a02 * c02;
206 if det.abs() <= EUV3D_QEM_EPSILON {
207 return None;
208 }
209 let c11: f64 = a00 * a22 - a02 * a02;
210 let c12: f64 = -(a00 * a12 - a01 * a02);
211 let c22: f64 = a00 * a11 - a01 * a01;
212 let bx: f64 = -q[3];
213 let by: f64 = -q[6];
214 let bz: f64 = -q[8];
215 let inv_det: f64 = 1.0 / det;
216 let rx: f64 = (c00 * bx + c01 * by + c02 * bz) * inv_det;
217 let ry: f64 = (c01 * bx + c11 * by + c12 * bz) * inv_det;
218 let rz: f64 = (c02 * bx + c12 * by + c22 * bz) * inv_det;
219 if rx.is_finite() && ry.is_finite() && rz.is_finite() {
220 Some([rx, ry, rz])
221 } else {
222 None
223 }
224 }
225}
226
227impl<'a> Euv3dPackageView<'a> {
229 pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, String> {
239 if bytes.len() < EUV3D_HEADER_BYTES {
240 return Err(ERR_EUV3D_TOO_SHORT.to_string());
241 }
242 if bytes[..8] != EUV3D_MAGIC {
243 return Err(ERR_EUV3D_BAD_MAGIC.to_string());
244 }
245 let version: u32 = read_u32_le(bytes, 8)?;
246 if version != EUV3D_FORMAT_VERSION {
247 return Err(ERR_EUV3D_BAD_VERSION.to_string());
248 }
249 let flags: u32 = read_u32_le(bytes, 12)?;
250 let section_count: u32 = read_u32_le(bytes, 16)?;
251 let table_offset: u64 = read_u64_le(bytes, 24)?;
252 let content_crc32: u32 = read_u32_le(bytes, 32)?;
253 let header_crc32: u32 = read_u32_le(bytes, 36)?;
254 let total_bytes: u64 = read_u64_le(bytes, 40)?;
255 let digest_fnv1a: u64 = read_u64_le(bytes, 48)?;
256 if (total_bytes as usize) != bytes.len() {
257 return Err(ERR_EUV3D_SIZE_MISMATCH.to_string());
258 }
259 if compute_crc32(&bytes[..36]) != header_crc32 {
260 return Err(ERR_EUV3D_CRC_MISMATCH.to_string());
261 }
262 if compute_crc32(&bytes[EUV3D_HEADER_BYTES..]) != content_crc32 {
263 return Err(ERR_EUV3D_CRC_MISMATCH.to_string());
264 }
265 let table_start: usize = table_offset as usize;
266 let table_bytes: usize = (section_count as usize)
267 .checked_mul(EUV3D_SECTION_ENTRY_BYTES)
268 .ok_or_else(|| ERR_EUV3D_TABLE_OOB.to_string())?;
269 let table_end: usize = table_start
270 .checked_add(table_bytes)
271 .ok_or_else(|| ERR_EUV3D_TABLE_OOB.to_string())?;
272 if table_start < EUV3D_HEADER_BYTES || table_end > bytes.len() {
273 return Err(ERR_EUV3D_TABLE_OOB.to_string());
274 }
275 let mut sections: Vec<Euv3dSectionEntry> = Vec::with_capacity(section_count as usize);
276 for idx in 0..(section_count as usize) {
277 let entry_off: usize = table_start + idx * EUV3D_SECTION_ENTRY_BYTES;
278 let raw_kind: u32 = read_u32_le(bytes, entry_off)?;
279 let kind: Euv3dSectionKind = Euv3dSectionKind::from_u32(raw_kind)
280 .ok_or_else(|| ERR_EUV3D_UNKNOWN_SECTION.to_string())?;
281 let sec_flags: u32 = read_u32_le(bytes, entry_off + 4)?;
282 let offset: u64 = read_u64_le(bytes, entry_off + 8)?;
283 let byte_length: u64 = read_u64_le(bytes, entry_off + 16)?;
284 let element_count: u32 = read_u32_le(bytes, entry_off + 24)?;
285 if !(offset as usize).is_multiple_of(EUV3D_SECTION_ALIGNMENT) {
286 return Err(ERR_EUV3D_UNALIGNED_SECTION.to_string());
287 }
288 let sec_end: usize = (offset as usize)
289 .checked_add(byte_length as usize)
290 .ok_or_else(|| ERR_EUV3D_SECTION_OOB.to_string())?;
291 if sec_end > bytes.len() {
292 return Err(ERR_EUV3D_SECTION_OOB.to_string());
293 }
294 sections.push(Euv3dSectionEntry {
295 kind,
296 offset,
297 byte_length,
298 element_count,
299 flags: sec_flags,
300 });
301 }
302 let header: Euv3dHeader = Euv3dHeader {
303 version,
304 flags,
305 section_count,
306 table_offset,
307 content_crc32,
308 total_bytes,
309 digest_fnv1a,
310 };
311 Ok(Self {
312 raw_bytes: bytes,
313 header,
314 sections,
315 })
316 }
317
318 #[must_use]
329 pub fn section_entry(&self, kind: Euv3dSectionKind) -> Option<Euv3dSectionEntry> {
330 for entry in self.get_sections().iter() {
331 if entry.get_kind() == kind {
332 return Some(*entry);
333 }
334 }
335 None
336 }
337
338 #[must_use]
349 pub fn section_bytes(&self, kind: Euv3dSectionKind) -> Option<&'a [u8]> {
350 let Self { raw_bytes, .. } = self;
351 let entry: Euv3dSectionEntry = self.section_entry(kind)?;
352 let start: usize = entry.get_offset() as usize;
353 let end: usize = start + (entry.get_byte_length() as usize);
354 raw_bytes.get(start..end)
355 }
356}
357
358impl Euv3dPackage {
360 pub fn bake_from_scene(
371 scene: &ImportedScene3D,
372 config: &Euv3dBakeConfig,
373 ) -> Result<Vec<u8>, String> {
374 let mut vertices_blob: Vec<u8> = Vec::new();
375 let mut vertex_total: u32 = 0;
376 let mut indices_blob: Vec<u8> = Vec::new();
377 let mut tri_total: u32 = 0;
378 let mut skins_blob: Vec<u8> = Vec::new();
379 let mut skin_total: u32 = 0;
380 let mut morph_blob: Vec<u8> = Vec::new();
381 let mut morph_vec_total: u32 = 0;
382 let mut meshlets_blob: Vec<u8> = Vec::new();
383 let mut meshlet_total: u32 = 0;
384 let mut bvh4_blob: Vec<u8> = Vec::new();
385 let mut bvh4_total: u32 = 0;
386 let mut bvh_pkt_blob: Vec<u8> = Vec::new();
387 let mut bvh_pkt_total: u32 = 0;
388 let mut bvh_tri_blob: Vec<u8> = Vec::new();
389 let mut bvh_tri_total: u32 = 0;
390 let mut anim_blob: Vec<u8> = Vec::new();
391 let mut anim_float_total: u32 = 0;
392 let mut tex_blob: Vec<u8> = Vec::new();
393
394 let mut mesh_records: Vec<Euv3dMeshRecord> = Vec::with_capacity(scene.get_meshes().len());
395 let mut bvh_records: Vec<Euv3dBvhRecord> = Vec::with_capacity(scene.get_meshes().len());
396 let max_lods: usize = config.get_lod_levels().clamp(1, EUV3D_DEFAULT_LOD_LEVELS);
397
398 for mesh in scene.get_meshes().iter() {
399 let chain: MeshLodChain = if max_lods > 1 {
400 build_qem_lod_chain(mesh, max_lods)
401 } else {
402 let mut base: Mesh3D = mesh.clone();
403 if config.get_build_meshlets() && base.get_tri_materials().is_empty() {
404 let (reordered, clusters): (Vec<[u32; 3]>, Vec<Meshlet3D>) =
405 build_spatial_meshlets(base.get_vertices(), base.get_indices());
406 base.set_indices(reordered);
407 base.set_meshlets(clusters);
408 }
409 MeshLodChain { levels: vec![base] }
410 };
411 let mut lod_records: Vec<Euv3dLodRecord> = Vec::with_capacity(chain.get_levels().len());
412 for lod_mesh in chain.get_levels().iter() {
413 let first_vertex: u32 = vertex_total;
414 let vertex_count: u32 = lod_mesh.get_vertices().len() as u32;
415 for v in lod_mesh.get_vertices().iter() {
416 push_vertex_bytes(&mut vertices_blob, v);
417 }
418 vertex_total += vertex_count;
419
420 let first_tri: u32 = tri_total;
421 let tri_count: u32 = lod_mesh.get_indices().len() as u32;
422 for tri in lod_mesh.get_indices().iter() {
423 indices_blob.extend_from_slice(&tri[0].to_le_bytes());
424 indices_blob.extend_from_slice(&tri[1].to_le_bytes());
425 indices_blob.extend_from_slice(&tri[2].to_le_bytes());
426 }
427 tri_total += tri_count;
428
429 let first_meshlet: u32 = meshlet_total;
430 let meshlet_count: u32 = if config.get_build_meshlets() {
431 for mlet in lod_mesh.get_meshlets().iter() {
432 push_meshlet_bytes(&mut meshlets_blob, mlet);
433 }
434 lod_mesh.get_meshlets().len() as u32
435 } else {
436 0
437 };
438 meshlet_total += meshlet_count;
439
440 lod_records.push(Euv3dLodRecord {
441 first_vertex,
442 vertex_count,
443 first_tri,
444 tri_count,
445 first_meshlet,
446 meshlet_count,
447 bounds_min: lod_mesh.get_bounds().get_min().to_array(),
448 bounds_max: lod_mesh.get_bounds().get_max().to_array(),
449 });
450 }
451
452 let lod0_ref: &Mesh3D = &chain.get_levels()[0];
453 let first_skin: u32 = skin_total;
454 let skin_count: u32 = lod0_ref.get_skin_influences().len() as u32;
455 for skin in lod0_ref.get_skin_influences().iter() {
456 push_skin_bytes(&mut skins_blob, skin);
457 }
458 skin_total += skin_count;
459
460 let mut morph_records: Vec<Euv3dMorphRecord> =
461 Vec::with_capacity(lod0_ref.get_morph_targets().len());
462 for target in lod0_ref.get_morph_targets().iter() {
463 let first_pos: u32 = morph_vec_total;
464 let pos_count: u32 = target.get_delta_positions().len() as u32;
465 for d in target.get_delta_positions().iter() {
466 for lane in *d {
467 morph_blob.extend_from_slice(&lane.to_le_bytes());
468 }
469 }
470 morph_vec_total += pos_count;
471
472 let first_norm: u32 = morph_vec_total;
473 let norm_count: u32 = target.get_delta_normals().len() as u32;
474 for d in target.get_delta_normals().iter() {
475 for lane in *d {
476 morph_blob.extend_from_slice(&lane.to_le_bytes());
477 }
478 }
479 morph_vec_total += norm_count;
480
481 let first_tan: u32 = morph_vec_total;
482 let tan_count: u32 = target.get_delta_tangents().len() as u32;
483 for d in target.get_delta_tangents().iter() {
484 for lane in *d {
485 morph_blob.extend_from_slice(&lane.to_le_bytes());
486 }
487 }
488 morph_vec_total += tan_count;
489
490 morph_records.push(Euv3dMorphRecord {
491 name: target.get_name().clone(),
492 first_pos,
493 pos_count,
494 first_norm,
495 norm_count,
496 first_tan,
497 tan_count,
498 });
499 }
500
501 mesh_records.push(Euv3dMeshRecord {
502 name: lod0_ref.get_name().clone(),
503 material: pbr_to_record(lod0_ref.get_material()),
504 sub_materials: lod0_ref
505 .get_sub_materials()
506 .iter()
507 .copied()
508 .map(pbr_to_record)
509 .collect(),
510 tri_materials: lod0_ref.get_tri_materials().clone(),
511 material_index: lod0_ref.try_get_material_index(),
512 is_closed: lod0_ref.get_is_closed(),
513 lods: lod_records,
514 first_skin,
515 skin_count,
516 morphs: morph_records,
517 });
518
519 if config.get_bake_bvh4() {
520 let bvh: Bvh3D = build_local_mesh_bvh(lod0_ref);
521 let first_node: u32 = bvh4_total;
522 let node_count: u32 = bvh.bvh4_nodes.len() as u32;
523 for node in bvh.bvh4_nodes.iter() {
524 push_bvh4_node_bytes(&mut bvh4_blob, node);
525 }
526 bvh4_total += node_count;
527
528 let first_packet: u32 = bvh_pkt_total;
529 let packet_count: u32 = bvh.leaf_packets.len() as u32;
530 for pkt in bvh.leaf_packets.iter() {
531 push_bvh_tri4_bytes(&mut bvh_pkt_blob, pkt);
532 }
533 bvh_pkt_total += packet_count;
534
535 let first_tri: u32 = bvh_tri_total;
536 let tri_count: u32 = bvh.get_triangles().len() as u32;
537 for tri in bvh.get_triangles().iter() {
538 push_bvh_tri_bytes(&mut bvh_tri_blob, tri);
539 }
540 bvh_tri_total += tri_count;
541
542 bvh_records.push(Euv3dBvhRecord {
543 first_node,
544 node_count,
545 first_packet,
546 packet_count,
547 first_tri,
548 tri_count,
549 root_min: bvh.root_min,
550 root_max: bvh.root_max,
551 build_sah_cost: bvh.get_build_sah_cost(),
552 });
553 }
554 }
555
556 let collections: Vec<Euv3dCollectionRecord> = scene
557 .get_scene_graph()
558 .get_collections()
559 .get_entries()
560 .iter()
561 .map(|entry: &CollectionEntry3D| Euv3dCollectionRecord {
562 name: entry.get_name().clone(),
563 bit_index: entry.get_bit_index(),
564 visible_viewport: entry.get_visible_viewport(),
565 visible_render: entry.get_visible_render(),
566 })
567 .collect();
568
569 let all_morph_weights: &[f32] = scene.get_scene_graph().get_morph_weights();
570 let nodes: Vec<Euv3dNodeRecord> = scene
571 .get_scene_graph()
572 .get_nodes()
573 .iter()
574 .map(|node: &SceneNode3D| {
575 let w_start: usize = node.get_morph_weight_offset() as usize;
576 let w_end: usize = (w_start + usize::from(node.get_morph_weight_count()))
577 .min(all_morph_weights.len());
578 let morph_weights: Vec<f32> = if w_start < w_end {
579 all_morph_weights[w_start..w_end].to_vec()
580 } else {
581 Vec::new()
582 };
583 let extras: &BlenderExtrasTags3D = node.get_extras();
584 let collider_shape: u8 = match extras.get_collider() {
585 SceneColliderShape3D::None => 0,
586 SceneColliderShape3D::Box => 1,
587 SceneColliderShape3D::Sphere => 2,
588 SceneColliderShape3D::ConvexHull => 3,
589 SceneColliderShape3D::Mesh => 4,
590 };
591 Euv3dNodeRecord {
592 name: node.get_name().clone(),
593 parent: node.try_get_parent(),
594 translation: node.get_local_translation().to_array(),
595 rotation: node.get_local_rotation().to_array(),
596 scale: node.get_local_scale().to_array(),
597 mesh_id: node.try_get_mesh_id(),
598 skin_id: node.try_get_skin_id(),
599 camera_id: node.try_get_camera_id(),
600 light_id: node.try_get_light_id(),
601 collection_mask: node.get_collection_mask(),
602 visible: node.get_visible(),
603 morph_weights,
604 collider_shape,
605 buoyancy_density: extras.get_buoyancy_density(),
606 is_trigger: extras.get_is_trigger(),
607 cast_shadows: extras.get_cast_shadows(),
608 custom_json: extras.try_get_custom_json().clone(),
609 }
610 })
611 .collect();
612
613 let materials: Vec<Euv3dMaterialRecord> = scene
614 .get_materials()
615 .iter()
616 .map(material_to_record)
617 .collect();
618
619 let mut textures: Vec<Euv3dTextureRecord> = Vec::with_capacity(scene.get_textures().len());
620 for tex in scene.get_textures().iter() {
621 let color_space: u8 = match tex.get_color_space() {
622 TextureColorSpace::Srgb => 0,
623 TextureColorSpace::Linear => 1,
624 TextureColorSpace::NormalTangent => 2,
625 };
626 let sampler: TextureSampler3D = tex.get_sampler();
627 let encode_filter: fn(TextureFilterMode) -> u8 = |mode: TextureFilterMode| match mode {
628 TextureFilterMode::Nearest => 0,
629 TextureFilterMode::Linear => 1,
630 TextureFilterMode::NearestMipmapNearest => 2,
631 TextureFilterMode::LinearMipmapNearest => 3,
632 TextureFilterMode::NearestMipmapLinear => 4,
633 TextureFilterMode::LinearMipmapLinear => 5,
634 };
635 let min_filter: u8 = encode_filter(sampler.get_min_filter());
636 let mag_filter: u8 = encode_filter(sampler.get_mag_filter());
637 let wrap_s: u8 = match sampler.get_wrap_s() {
638 TextureWrapMode::Repeat => 0,
639 TextureWrapMode::MirroredRepeat => 1,
640 TextureWrapMode::ClampToEdge => 2,
641 };
642 let wrap_t: u8 = match sampler.get_wrap_t() {
643 TextureWrapMode::Repeat => 0,
644 TextureWrapMode::MirroredRepeat => 1,
645 TextureWrapMode::ClampToEdge => 2,
646 };
647 let mip_limit: usize = if config.get_generate_mipmaps() {
648 tex.get_mips().len()
649 } else {
650 tex.get_mips().len().min(1)
651 };
652 let mut mips: Vec<Euv3dTexMipRecord> = Vec::with_capacity(mip_limit);
653 for mip in tex.get_mips().iter().take(mip_limit) {
654 let byte_offset: u64 = tex_blob.len() as u64;
655 let pixels: &[u8] = mip.get_pixels();
656 tex_blob.extend_from_slice(pixels);
657 mips.push(Euv3dTexMipRecord {
658 width: mip.get_width(),
659 height: mip.get_height(),
660 byte_offset,
661 byte_length: pixels.len() as u64,
662 });
663 }
664 textures.push(Euv3dTextureRecord {
665 name: tex.get_name().clone(),
666 color_space,
667 min_filter,
668 mag_filter,
669 wrap_s,
670 wrap_t,
671 mips,
672 });
673 }
674
675 let skins: Vec<Euv3dSkinRecord> = scene
676 .get_skins()
677 .iter()
678 .map(|skin: &ImportedSkin3D| Euv3dSkinRecord {
679 name: skin.get_name().clone(),
680 joints: skin.get_joints().clone(),
681 skeleton_root: skin.try_get_skeleton_root(),
682 inverse_bind_matrices: skin
683 .get_inverse_bind_matrices()
684 .iter()
685 .map(|m: &Mat4| m.get_elements())
686 .collect(),
687 })
688 .collect();
689
690 let mut animations: Vec<Euv3dAnimClipRecord> =
691 Vec::with_capacity(scene.get_animations().len());
692 for clip in scene.get_animations().iter() {
693 let mut samplers: Vec<Euv3dAnimSamplerRecord> =
694 Vec::with_capacity(clip.get_samplers().len());
695 for samp in clip.get_samplers().iter() {
696 let first_time: u32 = anim_float_total;
697 let time_count: u32 = samp.get_timestamps().len() as u32;
698 for &t in samp.get_timestamps().iter() {
699 anim_blob.extend_from_slice(&t.to_le_bytes());
700 }
701 anim_float_total += time_count;
702
703 let first_value: u32 = anim_float_total;
704 let value_count: u32 = samp.get_values().len() as u32;
705 for &val in samp.get_values().iter() {
706 anim_blob.extend_from_slice(&val.to_le_bytes());
707 }
708 anim_float_total += value_count;
709
710 let interpolation: u8 = match samp.get_interpolation() {
711 GltfInterpolationMode::Step => 0,
712 GltfInterpolationMode::Linear => 1,
713 GltfInterpolationMode::CubicSpline => 2,
714 };
715 samplers.push(Euv3dAnimSamplerRecord {
716 first_time,
717 time_count,
718 first_value,
719 value_count,
720 value_stride: samp.get_value_stride() as u32,
721 interpolation,
722 });
723 }
724 let channels: Vec<Euv3dAnimChannelRecord> = clip
725 .get_channels()
726 .iter()
727 .map(|ch: &ImportedAnimationChannel3D| {
728 let path: u8 = match ch.get_path() {
729 GltfAnimationPath::Translation => 0,
730 GltfAnimationPath::Rotation => 1,
731 GltfAnimationPath::Scale => 2,
732 GltfAnimationPath::MorphWeights => 3,
733 };
734 Euv3dAnimChannelRecord {
735 target_node: ch.get_target_node(),
736 path,
737 sampler_index: ch.get_sampler_index() as u32,
738 }
739 })
740 .collect();
741 animations.push(Euv3dAnimClipRecord {
742 name: clip.get_name().clone(),
743 duration_secs: clip.get_duration_secs(),
744 samplers,
745 channels,
746 });
747 }
748
749 let cameras: Vec<Euv3dCameraRecord> = scene
750 .get_cameras()
751 .iter()
752 .map(|cam: &ImportedCamera3D| match cam.get_projection() {
753 GltfCameraProjection::Perspective {
754 yfov_rad,
755 aspect_ratio,
756 znear,
757 zfar,
758 } => Euv3dCameraRecord {
759 name: cam.get_name().clone(),
760 is_perspective: true,
761 param_a: yfov_rad,
762 param_b: aspect_ratio.unwrap_or(-1.0),
763 znear,
764 zfar,
765 },
766 GltfCameraProjection::Orthographic {
767 xmag,
768 ymag,
769 znear,
770 zfar,
771 } => Euv3dCameraRecord {
772 name: cam.get_name().clone(),
773 is_perspective: false,
774 param_a: xmag,
775 param_b: ymag,
776 znear,
777 zfar: Some(zfar),
778 },
779 })
780 .collect();
781
782 let lights: Vec<Euv3dLightRecord> = scene
783 .get_lights()
784 .iter()
785 .map(|light: &ImportedLight3D| match light.get_kind() {
786 GltfLightKind::Directional => Euv3dLightRecord {
787 name: light.get_name().clone(),
788 color: light.get_color().to_array(),
789 intensity: light.get_intensity(),
790 kind: 0,
791 range: None,
792 param_a: 0.0,
793 param_b: 0.0,
794 },
795 GltfLightKind::Point { range } => Euv3dLightRecord {
796 name: light.get_name().clone(),
797 color: light.get_color().to_array(),
798 intensity: light.get_intensity(),
799 kind: 1,
800 range,
801 param_a: 0.0,
802 param_b: 0.0,
803 },
804 GltfLightKind::Spot {
805 range,
806 inner_cone_angle,
807 outer_cone_angle,
808 } => Euv3dLightRecord {
809 name: light.get_name().clone(),
810 color: light.get_color().to_array(),
811 intensity: light.get_intensity(),
812 kind: 2,
813 range,
814 param_a: inner_cone_angle,
815 param_b: outer_cone_angle,
816 },
817 GltfLightKind::Area { width, height } => Euv3dLightRecord {
818 name: light.get_name().clone(),
819 color: light.get_color().to_array(),
820 intensity: light.get_intensity(),
821 kind: 3,
822 range: None,
823 param_a: width,
824 param_b: height,
825 },
826 })
827 .collect();
828
829 let metadata: Euv3dSceneMetadata = Euv3dSceneMetadata {
830 name: scene.get_name().clone(),
831 generator: scene.get_generator().clone(),
832 collections,
833 nodes,
834 meshes: mesh_records,
835 bvhs: bvh_records,
836 materials,
837 textures,
838 skins,
839 animations,
840 cameras,
841 lights,
842 };
843 let meta_json: String =
844 to_string(&metadata).map_err(|_| ERR_EUV3D_BAD_METADATA.to_string())?;
845 let meta_bytes: Vec<u8> = meta_json.into_bytes();
846
847 let mut payload_sections: Vec<(Euv3dSectionKind, u32, Vec<u8>)> = Vec::with_capacity(11);
848 payload_sections.push((Euv3dSectionKind::SceneMetadataJson, 1, meta_bytes));
849 if !vertices_blob.is_empty() {
850 payload_sections.push((Euv3dSectionKind::Vertices, vertex_total, vertices_blob));
851 }
852 if !indices_blob.is_empty() {
853 payload_sections.push((Euv3dSectionKind::Indices, tri_total, indices_blob));
854 }
855 if !skins_blob.is_empty() {
856 payload_sections.push((Euv3dSectionKind::SkinInfluences, skin_total, skins_blob));
857 }
858 if !morph_blob.is_empty() {
859 payload_sections.push((Euv3dSectionKind::MorphDeltas, morph_vec_total, morph_blob));
860 }
861 if !meshlets_blob.is_empty() {
862 payload_sections.push((Euv3dSectionKind::Meshlets, meshlet_total, meshlets_blob));
863 }
864 if !bvh4_blob.is_empty() {
865 payload_sections.push((Euv3dSectionKind::Bvh4Nodes, bvh4_total, bvh4_blob));
866 }
867 if !bvh_pkt_blob.is_empty() {
868 payload_sections.push((
869 Euv3dSectionKind::BvhTri4Packets,
870 bvh_pkt_total,
871 bvh_pkt_blob,
872 ));
873 }
874 if !bvh_tri_blob.is_empty() {
875 payload_sections.push((Euv3dSectionKind::BvhTriangles, bvh_tri_total, bvh_tri_blob));
876 }
877 if !anim_blob.is_empty() {
878 payload_sections.push((
879 Euv3dSectionKind::AnimationsBlob,
880 anim_float_total,
881 anim_blob,
882 ));
883 }
884 if !tex_blob.is_empty() {
885 payload_sections.push((
886 Euv3dSectionKind::TexturesBlob,
887 scene.get_textures().len() as u32,
888 tex_blob,
889 ));
890 }
891
892 let section_count: usize = payload_sections.len();
893 let table_offset: usize = EUV3D_HEADER_BYTES;
894 let mut cursor: usize =
895 align_up_64(table_offset + section_count * EUV3D_SECTION_ENTRY_BYTES);
896 let mut entries: Vec<Euv3dSectionEntry> = Vec::with_capacity(section_count);
897 for &(kind, elem_count, ref data) in &payload_sections {
898 let sec_off: usize = align_up_64(cursor);
899 entries.push(Euv3dSectionEntry {
900 kind,
901 offset: sec_off as u64,
902 byte_length: data.len() as u64,
903 element_count: elem_count,
904 flags: 0,
905 });
906 cursor = align_up_64(sec_off + data.len());
907 }
908 let total_bytes: usize = cursor;
909 let mut out: Vec<u8> = vec![0u8; total_bytes];
910 for (idx, entry) in entries.iter().enumerate() {
911 let pos: usize = table_offset + idx * EUV3D_SECTION_ENTRY_BYTES;
912 out[pos..pos + 4].copy_from_slice(&entry.get_kind().to_u32().to_le_bytes());
913 out[pos + 4..pos + 8].copy_from_slice(&entry.get_flags().to_le_bytes());
914 out[pos + 8..pos + 16].copy_from_slice(&entry.get_offset().to_le_bytes());
915 out[pos + 16..pos + 24].copy_from_slice(&entry.get_byte_length().to_le_bytes());
916 out[pos + 24..pos + 28].copy_from_slice(&entry.get_element_count().to_le_bytes());
917 let data: &[u8] = &payload_sections[idx].2;
918 let dst_start: usize = entry.get_offset() as usize;
919 out[dst_start..dst_start + data.len()].copy_from_slice(data);
920 }
921
922 let mut flags: u32 = 0;
923 if config.get_bake_bvh4() && bvh4_total > 0 {
924 flags |= EUV3D_FLAG_HAS_BVH4;
925 }
926 if config.get_build_meshlets() && meshlet_total > 0 {
927 flags |= EUV3D_FLAG_HAS_MESHLETS;
928 }
929 if max_lods > 1 {
930 flags |= EUV3D_FLAG_HAS_LODS;
931 }
932 let content_crc32: u32 = compute_crc32(&out[EUV3D_HEADER_BYTES..]);
933 let digest_fnv1a: u64 = compute_fnv1a_64(&out[EUV3D_HEADER_BYTES..]);
934 out[0..8].copy_from_slice(&EUV3D_MAGIC);
935 out[8..12].copy_from_slice(&EUV3D_FORMAT_VERSION.to_le_bytes());
936 out[12..16].copy_from_slice(&flags.to_le_bytes());
937 out[16..20].copy_from_slice(&(section_count as u32).to_le_bytes());
938 out[24..32].copy_from_slice(&(table_offset as u64).to_le_bytes());
939 out[32..36].copy_from_slice(&content_crc32.to_le_bytes());
940 let header_crc32: u32 = compute_crc32(&out[..36]);
941 out[36..40].copy_from_slice(&header_crc32.to_le_bytes());
942 out[40..48].copy_from_slice(&(total_bytes as u64).to_le_bytes());
943 out[48..56].copy_from_slice(&digest_fnv1a.to_le_bytes());
944 Ok(out)
945 }
946
947 pub fn decode_bytes(bytes: &[u8]) -> Result<BakedAssetBundle3D, String> {
957 let view: Euv3dPackageView<'_> = Euv3dPackageView::from_bytes(bytes)?;
958 let meta_slice: &[u8] = view
959 .section_bytes(Euv3dSectionKind::SceneMetadataJson)
960 .ok_or_else(|| ERR_EUV3D_MISSING_METADATA.to_string())?;
961 let meta_str: &str =
962 from_utf8(meta_slice).map_err(|_| ERR_EUV3D_BAD_METADATA.to_string())?;
963 let meta: Euv3dSceneMetadata =
964 from_str(meta_str).map_err(|_| ERR_EUV3D_BAD_METADATA.to_string())?;
965
966 let verts_slice: &[u8] = view
967 .section_bytes(Euv3dSectionKind::Vertices)
968 .unwrap_or(&[]);
969 let idx_slice: &[u8] = view.section_bytes(Euv3dSectionKind::Indices).unwrap_or(&[]);
970 let skin_slice: &[u8] = view
971 .section_bytes(Euv3dSectionKind::SkinInfluences)
972 .unwrap_or(&[]);
973 let morph_slice: &[u8] = view
974 .section_bytes(Euv3dSectionKind::MorphDeltas)
975 .unwrap_or(&[]);
976 let mlet_slice: &[u8] = view
977 .section_bytes(Euv3dSectionKind::Meshlets)
978 .unwrap_or(&[]);
979 let bvh4_slice: &[u8] = view
980 .section_bytes(Euv3dSectionKind::Bvh4Nodes)
981 .unwrap_or(&[]);
982 let bvh_pkt_slice: &[u8] = view
983 .section_bytes(Euv3dSectionKind::BvhTri4Packets)
984 .unwrap_or(&[]);
985 let bvh_tri_slice: &[u8] = view
986 .section_bytes(Euv3dSectionKind::BvhTriangles)
987 .unwrap_or(&[]);
988 let anim_slice: &[u8] = view
989 .section_bytes(Euv3dSectionKind::AnimationsBlob)
990 .unwrap_or(&[]);
991 let tex_slice: &[u8] = view
992 .section_bytes(Euv3dSectionKind::TexturesBlob)
993 .unwrap_or(&[]);
994
995 let mut lod_chains: Vec<MeshLodChain> = Vec::with_capacity(meta.meshes.len());
996 let mut lod0_meshes: Vec<Mesh3D> = Vec::with_capacity(meta.meshes.len());
997 for mesh_rec in &meta.meshes {
998 let mut levels: Vec<Mesh3D> = Vec::with_capacity(mesh_rec.lods.len());
999 let base_mat: PbrMaterial = record_to_pbr(&mesh_rec.material);
1000 let sub_mats: Vec<PbrMaterial> =
1001 mesh_rec.sub_materials.iter().map(record_to_pbr).collect();
1002 for (lod_idx, lod_rec) in mesh_rec.lods.iter().enumerate() {
1003 let mut vertices: Vec<Vertex3D> = Vec::with_capacity(lod_rec.vertex_count as usize);
1004 for v_i in 0..(lod_rec.vertex_count as usize) {
1005 let off: usize =
1006 ((lod_rec.first_vertex as usize) + v_i) * EUV3D_VERTEX_STRIDE_BYTES;
1007 vertices.push(read_vertex_bytes(verts_slice, off)?);
1008 }
1009 let mut indices: Vec<[u32; 3]> = Vec::with_capacity(lod_rec.tri_count as usize);
1010 for t_i in 0..(lod_rec.tri_count as usize) {
1011 let off: usize = ((lod_rec.first_tri as usize) + t_i) * EUV3D_INDEX_TRI_BYTES;
1012 let i0: u32 = read_u32_le(idx_slice, off)?;
1013 let i1: u32 = read_u32_le(idx_slice, off + 4)?;
1014 let i2: u32 = read_u32_le(idx_slice, off + 8)?;
1015 indices.push([i0, i1, i2]);
1016 }
1017 let mut meshlets: Vec<Meshlet3D> =
1018 Vec::with_capacity(lod_rec.meshlet_count as usize);
1019 for m_i in 0..(lod_rec.meshlet_count as usize) {
1020 let off: usize =
1021 ((lod_rec.first_meshlet as usize) + m_i) * EUV3D_MESHLET_STRIDE_BYTES;
1022 meshlets.push(read_meshlet_bytes(mlet_slice, off)?);
1023 }
1024 let bounds: AxisAlignedBox3D = AxisAlignedBox3D::new(
1025 Vec3::from_array(lod_rec.bounds_min),
1026 Vec3::from_array(lod_rec.bounds_max),
1027 );
1028 let mut skin_influences: Vec<MeshSkinInfluence3D> = Vec::new();
1029 let mut morph_targets: Vec<MorphTarget3D> = Vec::new();
1030 if lod_idx == 0 {
1031 skin_influences.reserve(mesh_rec.skin_count as usize);
1032 for s_i in 0..(mesh_rec.skin_count as usize) {
1033 let off: usize =
1034 ((mesh_rec.first_skin as usize) + s_i) * EUV3D_SKIN_STRIDE_BYTES;
1035 skin_influences.push(read_skin_bytes(skin_slice, off)?);
1036 }
1037 morph_targets.reserve(mesh_rec.morphs.len());
1038 for m_rec in &mesh_rec.morphs {
1039 let mut delta_positions: Vec<[f32; 3]> =
1040 Vec::with_capacity(m_rec.pos_count as usize);
1041 for p_i in 0..(m_rec.pos_count as usize) {
1042 let off: usize = ((m_rec.first_pos as usize) + p_i) * 12;
1043 delta_positions.push([
1044 read_f32_le(morph_slice, off)?,
1045 read_f32_le(morph_slice, off + 4)?,
1046 read_f32_le(morph_slice, off + 8)?,
1047 ]);
1048 }
1049 let mut delta_normals: Vec<[f32; 3]> =
1050 Vec::with_capacity(m_rec.norm_count as usize);
1051 for n_i in 0..(m_rec.norm_count as usize) {
1052 let off: usize = ((m_rec.first_norm as usize) + n_i) * 12;
1053 delta_normals.push([
1054 read_f32_le(morph_slice, off)?,
1055 read_f32_le(morph_slice, off + 4)?,
1056 read_f32_le(morph_slice, off + 8)?,
1057 ]);
1058 }
1059 let mut delta_tangents: Vec<[f32; 3]> =
1060 Vec::with_capacity(m_rec.tan_count as usize);
1061 for t_i in 0..(m_rec.tan_count as usize) {
1062 let off: usize = ((m_rec.first_tan as usize) + t_i) * 12;
1063 delta_tangents.push([
1064 read_f32_le(morph_slice, off)?,
1065 read_f32_le(morph_slice, off + 4)?,
1066 read_f32_le(morph_slice, off + 8)?,
1067 ]);
1068 }
1069 morph_targets.push(MorphTarget3D {
1070 name: m_rec.name.clone(),
1071 delta_positions,
1072 delta_normals,
1073 delta_tangents,
1074 });
1075 }
1076 }
1077 let mesh_level: Mesh3D = Mesh3D {
1078 name: mesh_rec.name.clone(),
1079 vertices,
1080 indices,
1081 bounds,
1082 material: base_mat,
1083 sub_materials: if lod_idx == 0 {
1084 sub_mats.clone()
1085 } else {
1086 Vec::new()
1087 },
1088 tri_materials: if lod_idx == 0 {
1089 mesh_rec.tri_materials.clone()
1090 } else {
1091 Vec::new()
1092 },
1093 meshlets,
1094 skin_influences,
1095 morph_targets,
1096 material_index: mesh_rec.material_index,
1097 is_closed: mesh_rec.is_closed,
1098 };
1099 levels.push(mesh_level);
1100 }
1101 if let Some(first_level) = levels.first() {
1102 lod0_meshes.push(first_level.clone());
1103 }
1104 lod_chains.push(MeshLodChain { levels });
1105 }
1106
1107 let mut local_bvhs: Vec<Bvh3D> = Vec::with_capacity(meta.bvhs.len());
1108 for bvh_rec in &meta.bvhs {
1109 let mut bvh4_nodes: Vec<Bvh4Node> = Vec::with_capacity(bvh_rec.node_count as usize);
1110 for n_i in 0..(bvh_rec.node_count as usize) {
1111 let off: usize =
1112 ((bvh_rec.first_node as usize) + n_i) * EUV3D_BVH4_NODE_STRIDE_BYTES;
1113 bvh4_nodes.push(read_bvh4_node_bytes(bvh4_slice, off)?);
1114 }
1115 let mut leaf_packets: Vec<BvhTri4> = Vec::with_capacity(bvh_rec.packet_count as usize);
1116 for p_i in 0..(bvh_rec.packet_count as usize) {
1117 let off: usize =
1118 ((bvh_rec.first_packet as usize) + p_i) * EUV3D_BVH_TRI4_STRIDE_BYTES;
1119 leaf_packets.push(read_bvh_tri4_bytes(bvh_pkt_slice, off)?);
1120 }
1121 let mut triangles: Vec<BvhTriangle> = Vec::with_capacity(bvh_rec.tri_count as usize);
1122 for t_i in 0..(bvh_rec.tri_count as usize) {
1123 let off: usize = ((bvh_rec.first_tri as usize) + t_i) * EUV3D_BVH_TRI_STRIDE_BYTES;
1124 triangles.push(read_bvh_tri_bytes(bvh_tri_slice, off)?);
1125 }
1126 for node in &bvh4_nodes {
1127 let valid: usize = (node.valid_count as usize).min(4);
1128 for lane in 0..valid {
1129 let lc: usize = node.leaf_count[lane] as usize;
1130 let ch: usize = node.child[lane] as usize;
1131 if lc > 0 {
1132 if ch
1133 .checked_add(lc)
1134 .is_none_or(|end: usize| end > leaf_packets.len())
1135 {
1136 return Err(ERR_EUV3D_INVALID_BVH4.to_string());
1137 }
1138 } else if ch >= bvh4_nodes.len() {
1139 return Err(ERR_EUV3D_INVALID_BVH4.to_string());
1140 }
1141 }
1142 }
1143 for pkt in &leaf_packets {
1144 for &t_idx in &pkt.tri_indices {
1145 if t_idx != u32::MAX && (t_idx as usize) >= triangles.len() {
1146 return Err(ERR_EUV3D_INVALID_BVH4.to_string());
1147 }
1148 }
1149 }
1150 let geom: Vec<BvhGeomTri> = triangles.iter().map(BvhGeomTri::from_triangle).collect();
1151 let orig_indices: Vec<u32> = (0..triangles.len()).map(|i: usize| i as u32).collect();
1152 local_bvhs.push(Bvh3D {
1153 nodes: Vec::new(),
1154 triangles,
1155 geom,
1156 leaf_packets,
1157 flat_nodes: Vec::new(),
1158 bvh4_nodes,
1159 bvh4_src_children: Vec::new(),
1160 root_min: bvh_rec.root_min,
1161 root_max: bvh_rec.root_max,
1162 #[cfg(target_arch = "x86_64")]
1163 bvh8_nodes: Vec::new(),
1164 #[cfg(target_arch = "x86_64")]
1165 bvh8_src_children: Vec::new(),
1166 orig_indices,
1167 node_to_flat: Vec::new(),
1168 build_sah_cost: bvh_rec.build_sah_cost,
1169 });
1170 }
1171
1172 let mut scene_graph: SceneGraph3D = SceneGraph3D::default();
1173 if !meta.collections.is_empty() {
1174 let mut active_mask: u64 = 0;
1175 let entries: Vec<CollectionEntry3D> = meta
1176 .collections
1177 .iter()
1178 .map(|c: &Euv3dCollectionRecord| {
1179 if c.visible_viewport && c.bit_index < 64 {
1180 active_mask |= 1u64 << u32::from(c.bit_index);
1181 }
1182 CollectionEntry3D {
1183 name: c.name.clone(),
1184 bit_index: c.bit_index,
1185 visible_viewport: c.visible_viewport,
1186 visible_render: c.visible_render,
1187 }
1188 })
1189 .collect();
1190 scene_graph.set_collections(CollectionRegistry3D {
1191 entries,
1192 active_mask,
1193 });
1194 }
1195 for n_rec in &meta.nodes {
1196 let mut node: SceneNode3D = SceneNode3D::from_name(&n_rec.name, n_rec.parent);
1197 node.set_local_translation(Vec3::from_array(n_rec.translation));
1198 node.set_local_rotation(Quat::from_array(n_rec.rotation));
1199 node.set_local_scale(Vec3::from_array(n_rec.scale));
1200 node.set_mesh_id(n_rec.mesh_id);
1201 node.set_skin_id(n_rec.skin_id);
1202 node.set_camera_id(n_rec.camera_id);
1203 node.set_light_id(n_rec.light_id);
1204 node.set_collection_mask(n_rec.collection_mask);
1205 node.set_visible(n_rec.visible);
1206 let collider: SceneColliderShape3D = match n_rec.collider_shape {
1207 1 => SceneColliderShape3D::Box,
1208 2 => SceneColliderShape3D::Sphere,
1209 3 => SceneColliderShape3D::ConvexHull,
1210 4 => SceneColliderShape3D::Mesh,
1211 _ => SceneColliderShape3D::None,
1212 };
1213 node.set_extras(BlenderExtrasTags3D {
1214 collider,
1215 buoyancy_density: n_rec.buoyancy_density,
1216 is_trigger: n_rec.is_trigger,
1217 cast_shadows: n_rec.cast_shadows,
1218 custom_json: n_rec.custom_json.clone(),
1219 });
1220 let node_id: u32 = scene_graph.add_node(node);
1221 if !n_rec.morph_weights.is_empty() {
1222 scene_graph.attach_morph_weights(node_id, &n_rec.morph_weights);
1223 }
1224 }
1225 let _: usize = scene_graph.propagate_world_matrices();
1226
1227 let materials: Vec<PrincipledMaterial3D> =
1228 meta.materials.iter().map(record_to_material).collect();
1229
1230 let mut textures: Vec<Texture2D3D> = Vec::with_capacity(meta.textures.len());
1231 for t_rec in &meta.textures {
1232 let color_space: TextureColorSpace = match t_rec.color_space {
1233 1 => TextureColorSpace::Linear,
1234 2 => TextureColorSpace::NormalTangent,
1235 _ => TextureColorSpace::Srgb,
1236 };
1237 let decode_filter: fn(u8) -> TextureFilterMode = |tag: u8| match tag {
1238 0 => TextureFilterMode::Nearest,
1239 2 => TextureFilterMode::NearestMipmapNearest,
1240 3 => TextureFilterMode::LinearMipmapNearest,
1241 4 => TextureFilterMode::NearestMipmapLinear,
1242 5 => TextureFilterMode::LinearMipmapLinear,
1243 _ => TextureFilterMode::Linear,
1244 };
1245 let min_filter: TextureFilterMode = decode_filter(t_rec.min_filter);
1246 let mag_filter: TextureFilterMode = decode_filter(t_rec.mag_filter);
1247 let wrap_s: TextureWrapMode = match t_rec.wrap_s {
1248 1 => TextureWrapMode::MirroredRepeat,
1249 2 => TextureWrapMode::ClampToEdge,
1250 _ => TextureWrapMode::Repeat,
1251 };
1252 let wrap_t: TextureWrapMode = match t_rec.wrap_t {
1253 1 => TextureWrapMode::MirroredRepeat,
1254 2 => TextureWrapMode::ClampToEdge,
1255 _ => TextureWrapMode::Repeat,
1256 };
1257 let mut mips: Vec<TextureMipLevel3D> = Vec::with_capacity(t_rec.mips.len());
1258 for mip_rec in &t_rec.mips {
1259 let start: usize = mip_rec.byte_offset as usize;
1260 let end: usize = start
1261 .checked_add(mip_rec.byte_length as usize)
1262 .ok_or_else(|| ERR_EUV3D_TRUNCATED_BLOB.to_string())?;
1263 if end > tex_slice.len() {
1264 return Err(ERR_EUV3D_TRUNCATED_BLOB.to_string());
1265 }
1266 mips.push(TextureMipLevel3D {
1267 width: mip_rec.width,
1268 height: mip_rec.height,
1269 pixels: tex_slice[start..end].to_vec(),
1270 });
1271 }
1272 let (width, height): (u32, u32) = mips
1273 .first()
1274 .map(|m: &TextureMipLevel3D| (m.get_width(), m.get_height()))
1275 .unwrap_or((0, 0));
1276 textures.push(Texture2D3D {
1277 name: t_rec.name.clone(),
1278 width,
1279 height,
1280 color_space,
1281 sampler: TextureSampler3D::new(mag_filter, min_filter, wrap_s, wrap_t),
1282 mips,
1283 });
1284 }
1285
1286 let skins: Vec<ImportedSkin3D> = meta
1287 .skins
1288 .iter()
1289 .map(|s: &Euv3dSkinRecord| ImportedSkin3D {
1290 name: s.name.clone(),
1291 joints: s.joints.clone(),
1292 skeleton_root: s.skeleton_root,
1293 inverse_bind_matrices: s
1294 .inverse_bind_matrices
1295 .iter()
1296 .map(|arr: &[f32; 16]| Mat4::from_cols_array(*arr))
1297 .collect(),
1298 })
1299 .collect();
1300
1301 let mut animations: Vec<ImportedAnimationClip3D> =
1302 Vec::with_capacity(meta.animations.len());
1303 for c_rec in &meta.animations {
1304 let mut samplers: Vec<ImportedAnimationSampler3D> =
1305 Vec::with_capacity(c_rec.samplers.len());
1306 for s_rec in &c_rec.samplers {
1307 let mut timestamps: Vec<f32> = Vec::with_capacity(s_rec.time_count as usize);
1308 for i in 0..(s_rec.time_count as usize) {
1309 timestamps.push(read_f32_le(
1310 anim_slice,
1311 ((s_rec.first_time as usize) + i) * 4,
1312 )?);
1313 }
1314 let mut values: Vec<f32> = Vec::with_capacity(s_rec.value_count as usize);
1315 for i in 0..(s_rec.value_count as usize) {
1316 values.push(read_f32_le(
1317 anim_slice,
1318 ((s_rec.first_value as usize) + i) * 4,
1319 )?);
1320 }
1321 let interpolation: GltfInterpolationMode = match s_rec.interpolation {
1322 0 => GltfInterpolationMode::Step,
1323 2 => GltfInterpolationMode::CubicSpline,
1324 _ => GltfInterpolationMode::Linear,
1325 };
1326 samplers.push(ImportedAnimationSampler3D {
1327 timestamps,
1328 values,
1329 value_stride: s_rec.value_stride as usize,
1330 interpolation,
1331 });
1332 }
1333 let channels: Vec<ImportedAnimationChannel3D> = c_rec
1334 .channels
1335 .iter()
1336 .map(|ch: &Euv3dAnimChannelRecord| {
1337 let path: GltfAnimationPath = match ch.path {
1338 1 => GltfAnimationPath::Rotation,
1339 2 => GltfAnimationPath::Scale,
1340 3 => GltfAnimationPath::MorphWeights,
1341 _ => GltfAnimationPath::Translation,
1342 };
1343 ImportedAnimationChannel3D::new(ch.target_node, path, ch.sampler_index as usize)
1344 })
1345 .collect();
1346 animations.push(ImportedAnimationClip3D {
1347 name: c_rec.name.clone(),
1348 duration_secs: c_rec.duration_secs,
1349 samplers,
1350 channels,
1351 });
1352 }
1353
1354 let cameras: Vec<ImportedCamera3D> = meta
1355 .cameras
1356 .iter()
1357 .map(|c: &Euv3dCameraRecord| {
1358 let projection: GltfCameraProjection = if c.is_perspective {
1359 GltfCameraProjection::Perspective {
1360 yfov_rad: c.param_a,
1361 aspect_ratio: if c.param_b > 0.0 {
1362 Some(c.param_b)
1363 } else {
1364 None
1365 },
1366 znear: c.znear,
1367 zfar: c.zfar,
1368 }
1369 } else {
1370 GltfCameraProjection::Orthographic {
1371 xmag: c.param_a,
1372 ymag: c.param_b,
1373 znear: c.znear,
1374 zfar: c.zfar.unwrap_or(1000.0),
1375 }
1376 };
1377 ImportedCamera3D {
1378 name: c.name.clone(),
1379 projection,
1380 }
1381 })
1382 .collect();
1383
1384 let lights: Vec<ImportedLight3D> = meta
1385 .lights
1386 .iter()
1387 .map(|l: &Euv3dLightRecord| {
1388 let kind: GltfLightKind = match l.kind {
1389 1 => GltfLightKind::Point { range: l.range },
1390 2 => GltfLightKind::Spot {
1391 range: l.range,
1392 inner_cone_angle: l.param_a,
1393 outer_cone_angle: l.param_b,
1394 },
1395 3 => GltfLightKind::Area {
1396 width: l.param_a,
1397 height: l.param_b,
1398 },
1399 _ => GltfLightKind::Directional,
1400 };
1401 ImportedLight3D {
1402 name: l.name.clone(),
1403 color: Vec3::from_array(l.color),
1404 intensity: l.intensity,
1405 kind,
1406 }
1407 })
1408 .collect();
1409
1410 let scene: ImportedScene3D = ImportedScene3D {
1411 name: meta.name,
1412 generator: meta.generator,
1413 scene_graph,
1414 meshes: lod0_meshes,
1415 materials,
1416 textures,
1417 skins,
1418 animations,
1419 cameras,
1420 lights,
1421 };
1422 let header: Euv3dHeader = view.get_header();
1423 Ok(BakedAssetBundle3D {
1424 scene,
1425 lod_chains,
1426 local_bvhs,
1427 section_count: view.get_sections().len(),
1428 total_bytes: header.get_total_bytes() as usize,
1429 digest_fnv1a: header.get_digest_fnv1a(),
1430 })
1431 }
1432}