1use super::*;
2
3impl Default for PbrMaterial {
5 fn default() -> Self {
11 Self {
12 base_color: Vec3::new(0.72, 0.75, 0.80),
13 metallic: 0.1,
14 roughness: 0.55,
15 emissive: Vec3::zero(),
16 reflectivity: 0.12,
17 surface_detail: SurfaceDetailMode::None,
18 }
19 }
20}
21
22impl PbrMaterial {
24 #[must_use]
37 pub fn pbr(color: Color, metallic: f32, roughness: f32, reflectivity: f32) -> Self {
38 Self {
39 base_color: Vec3::from_color(color),
40 metallic: metallic.clamp(0.0, 1.0),
41 roughness: roughness.clamp(0.04, 1.0),
42 emissive: Vec3::zero(),
43 reflectivity: reflectivity.clamp(0.0, 1.0),
44 surface_detail: SurfaceDetailMode::None,
45 }
46 }
47
48 #[must_use]
59 pub fn metallic(color: Color, roughness: f32) -> Self {
60 let r: f32 = roughness.clamp(0.04, 1.0);
61 Self::pbr(color, 0.92, r, (1.0 - r * 0.8).clamp(0.15, 0.96))
62 }
63
64 #[must_use]
75 pub fn dielectric(color: Color, roughness: f32) -> Self {
76 let r: f32 = roughness.clamp(0.04, 1.0);
77 Self::pbr(color, 0.04, r, (0.35 * (1.0 - r)).clamp(0.04, 0.35))
78 }
79
80 #[must_use]
91 pub fn glass(color: Color, roughness: f32) -> Self {
92 let r: f32 = roughness.clamp(0.04, 0.4);
93 Self::pbr(color, 0.12, r, 0.88)
94 }
95
96 #[must_use]
107 pub fn neon(color: Color, intensity: f32) -> Self {
108 let rgb: Vec3 = Vec3::from_color(color);
109 Self {
110 base_color: rgb,
111 metallic: 0.2,
112 roughness: 0.2,
113 emissive: rgb.scale(intensity.max(0.2)),
114 reflectivity: 0.3,
115 surface_detail: SurfaceDetailMode::None,
116 }
117 }
118
119 #[must_use]
130 pub fn with_emissive(mut self, emissive: Vec3) -> Self {
131 self.set_emissive(emissive);
132 self
133 }
134
135 #[must_use]
146 pub fn with_roughness(mut self, roughness: f32) -> Self {
147 self.set_roughness(roughness.clamp(0.04, 1.0));
148 self
149 }
150
151 #[must_use]
162 pub fn with_metallic(mut self, metallic: f32) -> Self {
163 self.set_metallic(metallic.clamp(0.0, 1.0));
164 self
165 }
166
167 #[must_use]
178 pub fn with_reflectivity(mut self, reflectivity: f32) -> Self {
179 self.set_reflectivity(reflectivity.clamp(0.0, 1.0));
180 self
181 }
182
183 #[must_use]
194 pub fn with_surface_detail(mut self, mode: SurfaceDetailMode) -> Self {
195 self.set_surface_detail(mode);
196 self
197 }
198}
199
200impl BoxMeshDesc {
202 #[must_use]
213 pub fn new(name: &str, size: Vec3) -> Self {
214 Self {
215 name: name.to_string(),
216 size,
217 ground_pivot: true,
218 material: PbrMaterial::default(),
219 }
220 }
221
222 #[must_use]
233 pub fn with_ground_pivot(mut self, ground_pivot: bool) -> Self {
234 self.set_ground_pivot(ground_pivot);
235 self
236 }
237
238 #[must_use]
249 pub fn with_material(mut self, material: PbrMaterial) -> Self {
250 self.set_material(material);
251 self
252 }
253}
254
255impl GroundPlaneDesc {
257 #[must_use]
269 pub fn new(name: &str, width: f32, depth: f32) -> Self {
270 Self {
271 name: name.to_string(),
272 width,
273 depth,
274 subdivisions: 8,
275 material: PbrMaterial::default(),
276 }
277 }
278
279 #[must_use]
290 pub fn with_subdivisions(mut self, subdivisions: usize) -> Self {
291 self.set_subdivisions(subdivisions);
292 self
293 }
294
295 #[must_use]
306 pub fn with_material(mut self, material: PbrMaterial) -> Self {
307 self.set_material(material);
308 self
309 }
310}
311
312impl Mesh3D {
314 #[must_use]
325 pub fn build_meshlets_from_parts(
326 vertices: &[Vertex3D],
327 indices: &[[u32; 3]],
328 ) -> Vec<Meshlet3D> {
329 if indices.is_empty() {
330 return Vec::new();
331 }
332 let cluster_count: usize = indices.len().div_ceil(MESHLET_MAX_TRIS);
333 let mut out: Vec<Meshlet3D> = Vec::with_capacity(cluster_count);
334 let mut start: usize = 0;
335 while start < indices.len() {
336 let end: usize = (start + MESHLET_MAX_TRIS).min(indices.len());
337 let mut cluster_box: Aabb3D = Aabb3D::empty();
338 let mut avg_n: Vec3 = Vec3::zero();
339 let mut valid_tris: usize = 0;
340 for tri in &indices[start..end] {
341 let (i0, i1, i2): (usize, usize, usize) =
342 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
343 if i0 < vertices.len() && i1 < vertices.len() && i2 < vertices.len() {
344 let p0: Vec3 = vertices[i0].get_position();
345 let p1: Vec3 = vertices[i1].get_position();
346 let p2: Vec3 = vertices[i2].get_position();
347 cluster_box.expand_point(p0);
348 cluster_box.expand_point(p1);
349 cluster_box.expand_point(p2);
350 let fn_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
351 avg_n = avg_n.add(fn_vec);
352 valid_tris += 1;
353 }
354 }
355 if valid_tris == 0 {
356 cluster_box = Aabb3D::new(Vec3::zero(), Vec3::zero());
357 }
358 let cone_axis: Vec3 = avg_n.normalize();
359 let mut min_dot: f32 = 1.0;
360 for tri in &indices[start..end] {
361 let (i0, i1, i2): (usize, usize, usize) =
362 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
363 if i0 < vertices.len() && i1 < vertices.len() && i2 < vertices.len() {
364 let p0: Vec3 = vertices[i0].get_position();
365 let p1: Vec3 = vertices[i1].get_position();
366 let p2: Vec3 = vertices[i2].get_position();
367 let fn_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
368 min_dot = min_dot.min(fn_vec.dot(cone_axis));
369 }
370 }
371 let radius: f32 = cluster_box.radius().max(0.05);
372 let screen_error: f32 = radius / ((end - start).max(1) as f32).sqrt();
373 out.push(Meshlet3D::new(
374 start as u32,
375 (end - start) as u32,
376 cluster_box,
377 cone_axis,
378 min_dot,
379 screen_error,
380 ));
381 start = end;
382 }
383 out
384 }
385
386 #[must_use]
399 pub fn from_parts(
400 name: String,
401 vertices: Vec<Vertex3D>,
402 indices: Vec<[u32; 3]>,
403 material: PbrMaterial,
404 ) -> Self {
405 let mut bounds: Aabb3D = Aabb3D::empty();
406 for v in vertices.iter() {
407 bounds.expand_point(v.get_position());
408 }
409 if vertices.is_empty() {
410 bounds = Aabb3D::new(Vec3::zero(), Vec3::zero());
411 }
412 let meshlets: Vec<Meshlet3D> = Self::build_meshlets_from_parts(&vertices, &indices);
413 Self {
414 name,
415 vertices,
416 indices,
417 bounds,
418 material,
419 meshlets,
420 is_closed: false,
421 }
422 }
423
424 #[must_use]
439 pub fn box_mesh(
440 name: &str,
441 w: f32,
442 h: f32,
443 d: f32,
444 ground_pivot: bool,
445 material: PbrMaterial,
446 ) -> Self {
447 let hx: f32 = w * 0.5;
448 let hz: f32 = d * 0.5;
449 let y0: f32 = if ground_pivot { 0.0 } else { -h * 0.5 };
450 let y1: f32 = if ground_pivot { h } else { h * 0.5 };
451 let faces: [([Vec3; 4], Vec3); 6] = [
452 (
453 [
454 Vec3::new(-hx, y0, hz),
455 Vec3::new(hx, y0, hz),
456 Vec3::new(hx, y1, hz),
457 Vec3::new(-hx, y1, hz),
458 ],
459 Vec3::new(0.0, 0.0, 1.0),
460 ),
461 (
462 [
463 Vec3::new(hx, y0, -hz),
464 Vec3::new(-hx, y0, -hz),
465 Vec3::new(-hx, y1, -hz),
466 Vec3::new(hx, y1, -hz),
467 ],
468 Vec3::new(0.0, 0.0, -1.0),
469 ),
470 (
471 [
472 Vec3::new(hx, y0, hz),
473 Vec3::new(hx, y0, -hz),
474 Vec3::new(hx, y1, -hz),
475 Vec3::new(hx, y1, hz),
476 ],
477 Vec3::new(1.0, 0.0, 0.0),
478 ),
479 (
480 [
481 Vec3::new(-hx, y0, -hz),
482 Vec3::new(-hx, y0, hz),
483 Vec3::new(-hx, y1, hz),
484 Vec3::new(-hx, y1, -hz),
485 ],
486 Vec3::new(-1.0, 0.0, 0.0),
487 ),
488 (
489 [
490 Vec3::new(-hx, y1, hz),
491 Vec3::new(hx, y1, hz),
492 Vec3::new(hx, y1, -hz),
493 Vec3::new(-hx, y1, -hz),
494 ],
495 Vec3::new(0.0, 1.0, 0.0),
496 ),
497 (
498 [
499 Vec3::new(-hx, y0, -hz),
500 Vec3::new(hx, y0, -hz),
501 Vec3::new(hx, y0, hz),
502 Vec3::new(-hx, y0, hz),
503 ],
504 Vec3::new(0.0, -1.0, 0.0),
505 ),
506 ];
507 let mut vertices: Vec<Vertex3D> = Vec::with_capacity(24);
508 let mut indices: Vec<[u32; 3]> = Vec::with_capacity(12);
509 for (quad, n) in faces.into_iter() {
510 let base: u32 = vertices.len() as u32;
511 for p in quad.into_iter() {
512 vertices.push(Vertex3D::new(p, n));
513 }
514 indices.push([base, base + 1, base + 2]);
515 indices.push([base, base + 2, base + 3]);
516 }
517 let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
518 mesh.set_is_closed(true);
519 mesh
520 }
521
522 #[must_use]
536 pub fn ground_plane(
537 name: &str,
538 w: f32,
539 d: f32,
540 subdivisions: usize,
541 material: PbrMaterial,
542 ) -> Self {
543 let segs: usize = subdivisions.clamp(1, 16);
544 let mut vertices: Vec<Vertex3D> = Vec::with_capacity((segs + 1) * (segs + 1));
545 let mut indices: Vec<[u32; 3]> = Vec::with_capacity(segs * segs * 2);
546 let up: Vec3 = Vec3::new(0.0, 1.0, 0.0);
547 for iz in 0..=segs {
548 let vz: f32 = ((iz as f32) / (segs as f32) - 0.5) * d;
549 for ix in 0..=segs {
550 let vx: f32 = ((ix as f32) / (segs as f32) - 0.5) * w;
551 vertices.push(Vertex3D::new(Vec3::new(vx, 0.0, vz), up));
552 }
553 }
554 let stride: u32 = (segs + 1) as u32;
555 for iz in 0..segs {
556 for ix in 0..segs {
557 let i0: u32 = (iz as u32) * stride + (ix as u32);
558 let i1: u32 = i0 + 1;
559 let i2: u32 = i0 + stride;
560 let i3: u32 = i2 + 1;
561 indices.push([i0, i2, i1]);
562 indices.push([i1, i2, i3]);
563 }
564 }
565 Self::from_parts(name.to_string(), vertices, indices, material)
566 }
567
568 #[must_use]
579 pub fn sports_car(name: &str, material: PbrMaterial) -> Self {
580 let lower: Self = Self::box_mesh(MESH_CAR_LOWER, 2.2, 0.80, 4.6, true, material);
581 let cabin: Self = Self::box_mesh(MESH_CAR_CABIN, 1.82, 0.72, 2.2, true, material);
582 let wheel: Self = Self::box_mesh(MESH_CAR_WHEEL, 0.34, 0.56, 0.62, true, material);
583 let mut vertices: Vec<Vertex3D> = Vec::with_capacity(144);
584 let mut indices: Vec<[u32; 3]> = Vec::with_capacity(72);
585 let lower_offset: u32 = vertices.len() as u32;
586 for v in lower.get_vertices().iter() {
587 let p: Vec3 = v.get_position();
588 vertices.push(Vertex3D::new(
589 Vec3::new(p.get_x(), p.get_y() + 0.24, p.get_z()),
590 v.get_normal(),
591 ));
592 }
593 for tri in lower.get_indices().iter() {
594 indices.push([
595 tri[0] + lower_offset,
596 tri[1] + lower_offset,
597 tri[2] + lower_offset,
598 ]);
599 }
600 let cabin_offset: u32 = vertices.len() as u32;
601 for v in cabin.get_vertices().iter() {
602 let p: Vec3 = v.get_position();
603 vertices.push(Vertex3D::new(
604 Vec3::new(p.get_x(), p.get_y() + 1.04, p.get_z() - 0.15),
605 v.get_normal(),
606 ));
607 }
608 for tri in cabin.get_indices().iter() {
609 indices.push([
610 tri[0] + cabin_offset,
611 tri[1] + cabin_offset,
612 tri[2] + cabin_offset,
613 ]);
614 }
615 let wheel_offsets: [(f32, f32); 4] =
616 [(-1.12, -1.45), (1.12, -1.45), (-1.12, 1.45), (1.12, 1.45)];
617 for (wx, wz) in wheel_offsets.into_iter() {
618 let base: u32 = vertices.len() as u32;
619 for v in wheel.get_vertices().iter() {
620 let p: Vec3 = v.get_position();
621 vertices.push(Vertex3D::new(
622 Vec3::new(p.get_x() + wx, p.get_y() + 0.02, p.get_z() + wz),
623 v.get_normal(),
624 ));
625 }
626 for tri in wheel.get_indices().iter() {
627 indices.push([tri[0] + base, tri[1] + base, tri[2] + base]);
628 }
629 }
630 let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
631 mesh.set_is_closed(true);
632 mesh
633 }
634
635 #[must_use]
645 pub fn from_box_desc(desc: &BoxMeshDesc) -> Self {
646 let size: Vec3 = desc.get_size();
647 Self::box_mesh(
648 desc.get_name(),
649 size.get_x(),
650 size.get_y(),
651 size.get_z(),
652 desc.get_ground_pivot(),
653 desc.get_material(),
654 )
655 }
656
657 #[must_use]
667 pub fn from_ground_desc(desc: &GroundPlaneDesc) -> Self {
668 Self::ground_plane(
669 desc.get_name(),
670 desc.get_width(),
671 desc.get_depth(),
672 desc.get_subdivisions(),
673 desc.get_material(),
674 )
675 }
676
677 #[must_use]
688 pub fn build_lod_proxy(&self, suffix: &str) -> Self {
689 let b: Aabb3D = self.get_bounds();
690 let size: Vec3 = b.get_max().sub(b.get_min());
691 let center: Vec3 = b.center();
692 let mut proxy: Self = Self::box_mesh(
693 &format!("{}_{suffix}", self.get_name()),
694 size.get_x().max(0.2),
695 size.get_y().max(0.2),
696 size.get_z().max(0.2),
697 false,
698 self.get_material(),
699 );
700 for v in proxy.get_mut_vertices().iter_mut() {
701 v.set_position(v.get_position().add(center));
702 }
703 proxy.set_bounds(b);
704 let meshlets: Vec<Meshlet3D> =
705 Self::build_meshlets_from_parts(proxy.get_vertices(), proxy.get_indices());
706 proxy.set_meshlets(meshlets);
707 proxy
708 }
709
710 #[must_use]
721 pub fn build_mid_lod(&self, suffix: &str) -> Self {
722 let verts: &[Vertex3D] = self.get_vertices().as_slice();
723 let tris: &[[u32; 3]] = self.get_indices().as_slice();
724 if tris.len() <= 24 {
725 return self.build_lod_proxy(suffix);
726 }
727 let mut scored: Vec<(f32, [u32; 3])> = Vec::with_capacity(tris.len());
728 for tri in tris.iter().copied() {
729 let (i0, i1, i2): (usize, usize, usize) =
730 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
731 if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
732 let p0: Vec3 = verts[i0].get_position();
733 let p1: Vec3 = verts[i1].get_position();
734 let p2: Vec3 = verts[i2].get_position();
735 let area2: f32 = p1.sub(p0).cross(p2.sub(p0)).length_sq();
736 scored.push((area2, tri));
737 }
738 }
739 scored.sort_unstable_by(|a: &(f32, [u32; 3]), b: &(f32, [u32; 3])| b.0.total_cmp(&a.0));
740 let keep: usize = (scored.len() / 2).max(12);
741 let reduced: Vec<[u32; 3]> = scored
742 .into_iter()
743 .take(keep)
744 .map(|(_, t): (f32, [u32; 3])| t)
745 .collect();
746 Self::from_parts(
747 format!("{}_{suffix}", self.get_name()),
748 self.get_vertices().clone(),
749 reduced,
750 self.get_material(),
751 )
752 }
753}
754
755impl MeshLodChain {
757 #[must_use]
767 pub fn from_mesh(mesh: Mesh3D) -> Self {
768 let tri_count: usize = mesh.get_indices().len();
769 if tri_count > 32 {
770 let lod1: Mesh3D = mesh.build_mid_lod(MESH_LOD1_SUFFIX);
771 let lod2: Mesh3D = mesh.build_lod_proxy(MESH_LOD2_SUFFIX);
772 Self {
773 levels: vec![mesh, lod1, lod2],
774 }
775 } else if tri_count > 16 {
776 let lod1: Mesh3D = mesh.build_lod_proxy(MESH_LOD1_SUFFIX);
777 Self {
778 levels: vec![mesh, lod1],
779 }
780 } else {
781 let clone_lod1: Mesh3D = mesh.clone();
782 Self {
783 levels: vec![mesh, clone_lod1],
784 }
785 }
786 }
787
788 #[must_use]
800 pub fn select(&self, distance: f32, lod_bias: f32) -> (&Mesh3D, usize) {
801 let levels: &[Mesh3D] = self.get_levels().as_slice();
802 let effective_dist: f32 = distance * lod_bias.max(0.25);
803 if levels.len() > 2 && effective_dist > 135.0 {
804 (&levels[2], 2)
805 } else if levels.len() > 1 && effective_dist > 78.0 {
806 (&levels[1], 1)
807 } else {
808 (&levels[0], 0)
809 }
810 }
811
812 #[must_use]
826 pub fn select_screen_error(
827 &self,
828 distance: f32,
829 bounds_radius: f32,
830 focal_px: f32,
831 lod_bias: f32,
832 ) -> (&Mesh3D, usize) {
833 let levels: &[Mesh3D] = self.get_levels().as_slice();
834 let safe_dist: f32 = distance.max(0.5);
835 let projected_px: f32 =
836 (bounds_radius.max(0.2) * focal_px) / (safe_dist * lod_bias.max(0.25));
837 if levels.len() > 2 && projected_px < 22.0 {
838 (&levels[2], 2)
839 } else if levels.len() > 1 && projected_px < 58.0 {
840 (&levels[1], 1)
841 } else {
842 (&levels[0], 0)
843 }
844 }
845}
846
847impl ModelImporter3D {
849 pub fn import(
861 format: ModelFormat,
862 source: &str,
863 fallback_material: PbrMaterial,
864 ) -> Result<ImportedModel3D, String> {
865 match format {
866 ModelFormat::Obj => Self::parse_obj(source, fallback_material),
867 ModelFormat::GltfJson => Self::parse_gltf_json(source, fallback_material),
868 }
869 }
870
871 pub fn parse_obj(source: &str, material: PbrMaterial) -> Result<ImportedModel3D, String> {
882 let mut positions: Vec<Vec3> = Vec::new();
883 let mut normals: Vec<Vec3> = Vec::new();
884 let mut vertices: Vec<Vertex3D> = Vec::new();
885 let mut indices: Vec<[u32; 3]> = Vec::new();
886 let mut model_name: String = MESH_OBJ_DEFAULT_NAME.to_string();
887 for raw_line in source.lines() {
888 let line: &str = raw_line.trim();
889 if line.is_empty() || line.starts_with('#') {
890 continue;
891 }
892 let parts: Vec<&str> = line.split_whitespace().collect();
893 if parts.is_empty() {
894 continue;
895 }
896 match parts[0] {
897 "o" | "g" if parts.len() >= 2 => {
898 model_name = parts[1].to_string();
899 }
900 "v" if parts.len() >= 4 => {
901 let x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
902 let y: f32 = parts[2].parse::<f32>().unwrap_or(0.0);
903 let z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
904 positions.push(Vec3::new(x, y, z));
905 }
906 "vn" if parts.len() >= 4 => {
907 let x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
908 let y: f32 = parts[2].parse::<f32>().unwrap_or(1.0);
909 let z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
910 normals.push(Vec3::new(x, y, z).normalize());
911 }
912 "f" if parts.len() >= 4 => {
913 let mut face_verts: Vec<(Vec3, Option<Vec3>)> =
914 Vec::with_capacity(parts.len() - 1);
915 for token in parts.iter().skip(1) {
916 let comps: Vec<&str> = token.split('/').collect();
917 let v_idx_raw: i32 = comps
918 .first()
919 .and_then(|s: &&str| s.parse::<i32>().ok())
920 .unwrap_or(0);
921 let p_opt: Option<Vec3> = if v_idx_raw > 0 {
922 positions.get((v_idx_raw - 1) as usize).copied()
923 } else if v_idx_raw < 0 {
924 let idx: isize = (positions.len() as isize) + (v_idx_raw as isize);
925 if idx >= 0 {
926 positions.get(idx as usize).copied()
927 } else {
928 None
929 }
930 } else {
931 None
932 };
933 let n_opt: Option<Vec3> = comps
934 .get(2)
935 .and_then(|s: &&str| s.parse::<i32>().ok())
936 .and_then(|n_raw: i32| {
937 if n_raw > 0 {
938 normals.get((n_raw - 1) as usize).copied()
939 } else {
940 None
941 }
942 });
943 if let Some(pos) = p_opt {
944 face_verts.push((pos, n_opt));
945 }
946 }
947 if face_verts.len() >= 3 {
948 for k in 1..(face_verts.len() - 1) {
949 let (p0, n0): (Vec3, Option<Vec3>) = face_verts[0];
950 let (p1, n1): (Vec3, Option<Vec3>) = face_verts[k];
951 let (p2, n2): (Vec3, Option<Vec3>) = face_verts[k + 1];
952 let face_n: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
953 let base: u32 = vertices.len() as u32;
954 vertices.push(Vertex3D::new(p0, n0.unwrap_or(face_n)));
955 vertices.push(Vertex3D::new(p1, n1.unwrap_or(face_n)));
956 vertices.push(Vertex3D::new(p2, n2.unwrap_or(face_n)));
957 indices.push([base, base + 1, base + 2]);
958 }
959 }
960 }
961 _ => {}
962 }
963 }
964 if indices.is_empty() {
965 return Err(ERR_OBJ_EMPTY.to_string());
966 }
967 let total_vertices: usize = vertices.len();
968 let total_triangles: usize = indices.len();
969 let mesh: Mesh3D = Mesh3D::from_parts(model_name.clone(), vertices, indices, material);
970 Ok(ImportedModel3D {
971 name: model_name,
972 format: ModelFormat::Obj,
973 meshes: vec![MeshLodChain::from_mesh(mesh)],
974 total_vertices,
975 total_triangles,
976 })
977 }
978
979 pub fn parse_gltf_json(
990 source: &str,
991 fallback_material: PbrMaterial,
992 ) -> Result<ImportedModel3D, String> {
993 let root: Value = from_str::<Value>(source)
994 .ok()
995 .ok_or_else(|| ERR_GLTF_JSON.to_string())?;
996 let name: String = root
997 .get(GLTF_KEY_ASSET)
998 .and_then(|a: &Value| a.get(GLTF_KEY_GENERATOR))
999 .and_then(Value::as_str)
1000 .unwrap_or(MESH_GLTF_DEFAULT_NAME)
1001 .to_string();
1002 let mut mat: PbrMaterial = fallback_material;
1003 if let Some(pbr) = root
1004 .get(GLTF_KEY_MATERIALS)
1005 .and_then(Value::as_array)
1006 .and_then(|arr: &Vec<Value>| arr.first())
1007 .and_then(|m: &Value| m.get(GLTF_KEY_PBR))
1008 {
1009 if let Some(bc) = pbr.get(GLTF_KEY_BASE_COLOR).and_then(Value::as_array)
1010 && bc.len() >= 3
1011 {
1012 let r: f32 = bc[0].as_f64().unwrap_or(0.8) as f32;
1013 let g: f32 = bc[1].as_f64().unwrap_or(0.8) as f32;
1014 let b: f32 = bc[2].as_f64().unwrap_or(0.8) as f32;
1015 mat.set_base_color(Vec3::new(r, g, b));
1016 }
1017 if let Some(met) = pbr.get(GLTF_KEY_METALLIC).and_then(Value::as_f64) {
1018 mat.set_metallic((met as f32).clamp(0.0, 1.0));
1019 }
1020 if let Some(rough) = pbr.get(GLTF_KEY_ROUGHNESS).and_then(Value::as_f64) {
1021 mat.set_roughness((rough as f32).clamp(0.04, 1.0));
1022 mat.set_reflectivity((1.0 - (rough as f32)).clamp(0.05, 0.95));
1023 }
1024 }
1025 let mut chains: Vec<MeshLodChain> = Vec::new();
1026 let mut total_vertices: usize = 0;
1027 let mut total_triangles: usize = 0;
1028 if let Some(meshes_arr) = root.get(GLTF_KEY_MESHES).and_then(Value::as_array) {
1029 for (m_idx, m_val) in meshes_arr.iter().enumerate() {
1030 let mesh_name: String = m_val
1031 .get(GLTF_KEY_NAME)
1032 .and_then(Value::as_str)
1033 .map(str::to_string)
1034 .unwrap_or_else(|| format!("{name}_mesh_{m_idx}"));
1035 let Some(prims) = m_val.get(GLTF_KEY_PRIMITIVES).and_then(Value::as_array) else {
1036 continue;
1037 };
1038 for prim in prims.iter() {
1039 let extras: &Value = prim.get(GLTF_KEY_EXTRAS).unwrap_or(prim);
1040 let pos_vals: Vec<f32> = extras
1041 .get(GLTF_KEY_POSITIONS)
1042 .and_then(Value::as_array)
1043 .map(|a: &Vec<Value>| {
1044 a.iter()
1045 .filter_map(|v: &Value| v.as_f64().map(|n: f64| n as f32))
1046 .collect()
1047 })
1048 .unwrap_or_default();
1049 let idx_vals: Vec<u32> = extras
1050 .get(GLTF_KEY_INDICES)
1051 .and_then(Value::as_array)
1052 .map(|a: &Vec<Value>| {
1053 a.iter()
1054 .filter_map(|v: &Value| v.as_u64().map(|n: u64| n as u32))
1055 .collect()
1056 })
1057 .unwrap_or_default();
1058 let mut raw_pts: Vec<Vec3> = Vec::new();
1059 for chunk in pos_vals.as_chunks::<3>().0 {
1060 raw_pts.push(Vec3::new(chunk[0], chunk[1], chunk[2]));
1061 }
1062 let mut verts: Vec<Vertex3D> = Vec::new();
1063 let mut tris: Vec<[u32; 3]> = Vec::new();
1064 for tri in idx_vals.as_chunks::<3>().0 {
1065 let (i0, i1, i2): (usize, usize, usize) =
1066 (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1067 if i0 < raw_pts.len() && i1 < raw_pts.len() && i2 < raw_pts.len() {
1068 let p0: Vec3 = raw_pts[i0];
1069 let p1: Vec3 = raw_pts[i1];
1070 let p2: Vec3 = raw_pts[i2];
1071 let n: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
1072 let base: u32 = verts.len() as u32;
1073 verts.push(Vertex3D::new(p0, n));
1074 verts.push(Vertex3D::new(p1, n));
1075 verts.push(Vertex3D::new(p2, n));
1076 tris.push([base, base + 1, base + 2]);
1077 }
1078 }
1079 if !tris.is_empty() {
1080 total_vertices += verts.len();
1081 total_triangles += tris.len();
1082 let mesh: Mesh3D = Mesh3D::from_parts(mesh_name.clone(), verts, tris, mat);
1083 chains.push(MeshLodChain::from_mesh(mesh));
1084 }
1085 }
1086 }
1087 }
1088 if chains.is_empty() {
1089 return Err(ERR_GLTF_EMPTY.to_string());
1090 }
1091 Ok(ImportedModel3D {
1092 name,
1093 format: ModelFormat::GltfJson,
1094 meshes: chains,
1095 total_vertices,
1096 total_triangles,
1097 })
1098 }
1099}