Skip to main content

euv_core/game/engine3d/mesh/
impl.rs

1use super::*;
2
3/// Default neutral matte PBR material.
4impl Default for PbrMaterial {
5    /// Returns a mid-gray dielectric PBR material.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default `PbrMaterial`.
10    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
22/// Material presets and fluent builders for metallic conductors, dielectrics, architectural glass, and neon signage.
23impl PbrMaterial {
24    /// Creates a PBR material from an sRGB `Color`, `metallic`, `roughness`, and `reflectivity`.
25    ///
26    /// # Arguments
27    ///
28    /// - `Color` - Base albedo color.
29    /// - `f32` - Metallic scalar `[0.0, 1.0]`.
30    /// - `f32` - Roughness scalar `[0.04, 1.0]`.
31    /// - `f32` - Ray-traced reflectivity weight `[0.0, 1.0]`.
32    ///
33    /// # Returns
34    ///
35    /// - `Self` - Configured PBR material.
36    #[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    /// Creates a metallic conductor PBR material (chrome, painted car body, brushed steel).
49    ///
50    /// # Arguments
51    ///
52    /// - `Color` - Base metallic reflectance color.
53    /// - `f32` - Surface roughness in `[0.04, 1.0]`.
54    ///
55    /// # Returns
56    ///
57    /// - `Self` - Conductor PBR material.
58    #[must_use]
59    pub fn metallic(color: Color, roughness: f32) -> Self {
60        let red_val: f32 = roughness.clamp(0.04, 1.0);
61        Self::pbr(
62            color,
63            0.92,
64            red_val,
65            (1.0 - red_val * 0.8).clamp(0.15, 0.96),
66        )
67    }
68
69    /// Creates a non-metallic dielectric PBR material (asphalt, concrete, matte plastic, cloth).
70    ///
71    /// # Arguments
72    ///
73    /// - `Color` - Base diffuse albedo color.
74    /// - `f32` - Surface roughness in `[0.04, 1.0]`.
75    ///
76    /// # Returns
77    ///
78    /// - `Self` - Dielectric PBR material.
79    #[must_use]
80    pub fn dielectric(color: Color, roughness: f32) -> Self {
81        let red_val: f32 = roughness.clamp(0.04, 1.0);
82        Self::pbr(
83            color,
84            0.04,
85            red_val,
86            (0.35 * (1.0 - red_val)).clamp(0.04, 0.35),
87        )
88    }
89
90    /// Creates a highly reflective architectural glass PBR material.
91    ///
92    /// # Arguments
93    ///
94    /// - `Color` - Subtle glass tint color.
95    /// - `f32` - Surface roughness in `[0.04, 0.4]`.
96    ///
97    /// # Returns
98    ///
99    /// - `Self` - Reflective glass PBR material.
100    #[must_use]
101    pub fn glass(color: Color, roughness: f32) -> Self {
102        let red_val: f32 = roughness.clamp(0.04, 0.4);
103        Self::pbr(color, 0.12, red_val, 0.88)
104    }
105
106    /// Creates an emissive neon PBR material for city signage, vehicle tail-lights, and beacons.
107    ///
108    /// # Arguments
109    ///
110    /// - `Color` - Base and emissive neon color.
111    /// - `f32` - Emissive intensity multiplier.
112    ///
113    /// # Returns
114    ///
115    /// - `Self` - Emissive PBR material.
116    #[must_use]
117    pub fn neon(color: Color, intensity: f32) -> Self {
118        let rgb: Vec3 = Vec3::from_color(color);
119        Self {
120            base_color: rgb,
121            metallic: 0.2,
122            roughness: 0.2,
123            emissive: rgb.scale(intensity.max(0.2)),
124            reflectivity: 0.3,
125            surface_detail: SurfaceDetailMode::None,
126        }
127    }
128
129    /// Returns a copy of this material with custom linear HDR emissive radiance.
130    ///
131    /// # Arguments
132    ///
133    /// - `Self` - Base material.
134    /// - `Vec3` - Emissive HDR RGB radiance.
135    ///
136    /// # Returns
137    ///
138    /// - `Self` - Updated material.
139    #[must_use]
140    pub fn with_emissive(mut self, emissive: Vec3) -> Self {
141        self.set_emissive(emissive);
142        self
143    }
144
145    /// Returns a copy of this material with adjusted surface roughness.
146    ///
147    /// # Arguments
148    ///
149    /// - `Self` - Base material.
150    /// - `f32` - Surface roughness clamped to `[0.04, 1.0]`.
151    ///
152    /// # Returns
153    ///
154    /// - `Self` - Updated material.
155    #[must_use]
156    pub fn with_roughness(mut self, roughness: f32) -> Self {
157        self.set_roughness(roughness.clamp(0.04, 1.0));
158        self
159    }
160
161    /// Returns a copy of this material with adjusted metallic factor.
162    ///
163    /// # Arguments
164    ///
165    /// - `Self` - Base material.
166    /// - `f32` - Metallic factor clamped to `[0.0, 1.0]`.
167    ///
168    /// # Returns
169    ///
170    /// - `Self` - Updated material.
171    #[must_use]
172    pub fn with_metallic(mut self, metallic: f32) -> Self {
173        self.set_metallic(metallic.clamp(0.0, 1.0));
174        self
175    }
176
177    /// Returns a copy of this material with adjusted ray-traced reflectivity.
178    ///
179    /// # Arguments
180    ///
181    /// - `Self` - Base material.
182    /// - `f32` - Reflectivity weight clamped to `[0.0, 1.0]`.
183    ///
184    /// # Returns
185    ///
186    /// - `Self` - Updated material.
187    #[must_use]
188    pub fn with_reflectivity(mut self, reflectivity: f32) -> Self {
189        self.set_reflectivity(reflectivity.clamp(0.0, 1.0));
190        self
191    }
192
193    /// Returns a copy of this material with the requested procedural surface detail overlay.
194    ///
195    /// # Arguments
196    ///
197    /// - `Self` - Base material.
198    /// - `SurfaceDetailMode` - Procedural surface detail mode.
199    ///
200    /// # Returns
201    ///
202    /// - `Self` - Updated material.
203    #[must_use]
204    pub fn with_surface_detail(mut self, mode: SurfaceDetailMode) -> Self {
205        self.set_surface_detail(mode);
206        self
207    }
208}
209
210/// Fluent constructors for `BoxMeshDesc`.
211impl BoxMeshDesc {
212    /// Creates a box mesh descriptor with default ground pivot and neutral PBR material.
213    ///
214    /// # Arguments
215    ///
216    /// - `&str` - Asset name.
217    /// - `Vec3` - Box extents `(width, height, depth)`.
218    ///
219    /// # Returns
220    ///
221    /// - `Self` - Ready descriptor.
222    #[must_use]
223    pub fn new(name: &str, size: Vec3) -> Self {
224        Self {
225            name: name.to_string(),
226            size,
227            ground_pivot: true,
228            material: PbrMaterial::default(),
229        }
230    }
231
232    /// Sets whether the box rests on `y = 0` or is centered at the origin.
233    ///
234    /// # Arguments
235    ///
236    /// - `Self` - Base descriptor.
237    /// - `bool` - Ground pivot toggle.
238    ///
239    /// # Returns
240    ///
241    /// - `Self` - Updated descriptor.
242    #[must_use]
243    pub fn with_ground_pivot(mut self, ground_pivot: bool) -> Self {
244        self.set_ground_pivot(ground_pivot);
245        self
246    }
247
248    /// Assigns the PBR material for the generated box mesh.
249    ///
250    /// # Arguments
251    ///
252    /// - `Self` - Base descriptor.
253    /// - `PbrMaterial` - Surface material.
254    ///
255    /// # Returns
256    ///
257    /// - `Self` - Updated descriptor.
258    #[must_use]
259    pub fn with_material(mut self, material: PbrMaterial) -> Self {
260        self.set_material(material);
261        self
262    }
263}
264
265/// Fluent constructors for `GroundPlaneDesc`.
266impl GroundPlaneDesc {
267    /// Creates a ground plane descriptor with default subdivisions and neutral PBR material.
268    ///
269    /// # Arguments
270    ///
271    /// - `&str` - Asset name.
272    /// - `f32` - Width along X.
273    /// - `f32` - Depth along Z.
274    ///
275    /// # Returns
276    ///
277    /// - `Self` - Ready descriptor.
278    #[must_use]
279    pub fn new(name: &str, width: f32, depth: f32) -> Self {
280        Self {
281            name: name.to_string(),
282            width,
283            depth,
284            subdivisions: 8,
285            material: PbrMaterial::default(),
286        }
287    }
288
289    /// Sets the grid subdivision count along each axis.
290    ///
291    /// # Arguments
292    ///
293    /// - `Self` - Base descriptor.
294    /// - `usize` - Subdivision count.
295    ///
296    /// # Returns
297    ///
298    /// - `Self` - Updated descriptor.
299    #[must_use]
300    pub fn with_subdivisions(mut self, subdivisions: usize) -> Self {
301        self.set_subdivisions(subdivisions);
302        self
303    }
304
305    /// Assigns the PBR material for the generated ground plane.
306    ///
307    /// # Arguments
308    ///
309    /// - `Self` - Base descriptor.
310    /// - `PbrMaterial` - Surface material.
311    ///
312    /// # Returns
313    ///
314    /// - `Self` - Updated descriptor.
315    #[must_use]
316    pub fn with_material(mut self, material: PbrMaterial) -> Self {
317        self.set_material(material);
318        self
319    }
320}
321
322/// Mesh construction, Nanite-style meshlet clustering, decimation, and procedural asset generators for `Mesh3D`.
323impl Mesh3D {
324    /// Partitions indexed triangles into Nanite-style `Meshlet3D` clusters with tight axis-aligned bounding boxes and normal cones.
325    ///
326    /// # Arguments
327    ///
328    /// - `&[Vertex3D]` - Source vertex buffer.
329    /// - `&[[u32; 3]]` - Source triangle indices.
330    ///
331    /// # Returns
332    ///
333    /// - `Vec<Meshlet3D>` - Contiguous cluster descriptors covering all triangles.
334    #[must_use]
335    pub fn build_meshlets_from_parts(
336        vertices: &[Vertex3D],
337        indices: &[[u32; 3]],
338    ) -> Vec<Meshlet3D> {
339        if indices.is_empty() {
340            return Vec::new();
341        }
342        let cluster_count: usize = indices.len().div_ceil(MESHLET_MAX_TRIS);
343        let mut out: Vec<Meshlet3D> = Vec::with_capacity(cluster_count);
344        let mut start: usize = 0;
345        while start < indices.len() {
346            let end: usize = (start + MESHLET_MAX_TRIS).min(indices.len());
347            let mut cluster_box: AxisAlignedBox3D = AxisAlignedBox3D::empty();
348            let mut avg_n: Vec3 = Vec3::zero();
349            let mut valid_tris: usize = 0;
350            for tri in &indices[start..end] {
351                let (i0, i1, i2): (usize, usize, usize) =
352                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
353                if i0 < vertices.len() && i1 < vertices.len() && i2 < vertices.len() {
354                    let p0: Vec3 = vertices[i0].get_position();
355                    let p1: Vec3 = vertices[i1].get_position();
356                    let p2: Vec3 = vertices[i2].get_position();
357                    cluster_box.expand_point(p0);
358                    cluster_box.expand_point(p1);
359                    cluster_box.expand_point(p2);
360                    let fn_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
361                    avg_n = avg_n.add(fn_vec);
362                    valid_tris += 1;
363                }
364            }
365            if valid_tris == 0 {
366                cluster_box = AxisAlignedBox3D::new(Vec3::zero(), Vec3::zero());
367            }
368            let cone_axis: Vec3 = avg_n.normalize();
369            let mut min_dot: f32 = 1.0;
370            for tri in &indices[start..end] {
371                let (i0, i1, i2): (usize, usize, usize) =
372                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
373                if i0 < vertices.len() && i1 < vertices.len() && i2 < vertices.len() {
374                    let p0: Vec3 = vertices[i0].get_position();
375                    let p1: Vec3 = vertices[i1].get_position();
376                    let p2: Vec3 = vertices[i2].get_position();
377                    let fn_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
378                    min_dot = min_dot.min(fn_vec.dot(cone_axis));
379                }
380            }
381            let radius: f32 = cluster_box.radius().max(0.05);
382            let screen_error: f32 = radius / ((end - start).max(1) as f32).sqrt();
383            out.push(Meshlet3D::new(
384                start as u32,
385                (end - start) as u32,
386                cluster_box,
387                cone_axis,
388                min_dot,
389                screen_error,
390            ));
391            start = end;
392        }
393        out
394    }
395
396    /// Constructs a `Mesh3D`, computes its local `AxisAlignedBox3D`, and partitions Nanite-style `Meshlet3D` clusters.
397    ///
398    /// # Arguments
399    ///
400    /// - `String` - Asset name.
401    /// - `Vec<Vertex3D>` - Vertex list.
402    /// - `Vec<[u32; 3]>` - Triangle indices.
403    /// - `PbrMaterial` - Default material.
404    ///
405    /// # Returns
406    ///
407    /// - `Self` - Ready indexed mesh with meshlets.
408    #[must_use]
409    pub fn from_parts(
410        name: String,
411        vertices: Vec<Vertex3D>,
412        indices: Vec<[u32; 3]>,
413        material: PbrMaterial,
414    ) -> Self {
415        let mut bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
416        for item_val in vertices.iter() {
417            bounds.expand_point(item_val.get_position());
418        }
419        if vertices.is_empty() {
420            bounds = AxisAlignedBox3D::new(Vec3::zero(), Vec3::zero());
421        }
422        let meshlets: Vec<Meshlet3D> = Self::build_meshlets_from_parts(&vertices, &indices);
423        Self {
424            name,
425            vertices,
426            indices,
427            bounds,
428            material,
429            meshlets,
430            is_closed: false,
431        }
432    }
433
434    /// Generates an axis-aligned box mesh of dimensions `(w, h, d)` resting on `y = 0` or centered.
435    ///
436    /// # Arguments
437    ///
438    /// - `&str` - Mesh name.
439    /// - `f32` - Width along X.
440    /// - `f32` - Height along Y.
441    /// - `f32` - Depth along Z.
442    /// - `bool` - When `true`, base rests on `y = 0`; otherwise centered at origin.
443    /// - `PbrMaterial` - Surface PBR material.
444    ///
445    /// # Returns
446    ///
447    /// - `Self` - Indexed 12-triangle box mesh with crisp flat face normals.
448    #[must_use]
449    pub fn box_mesh(
450        name: &str,
451        width_val: f32,
452        height_val: f32,
453        delta_val: f32,
454        ground_pivot: bool,
455        material: PbrMaterial,
456    ) -> Self {
457        let hx: f32 = width_val * 0.5;
458        let hz: f32 = delta_val * 0.5;
459        let y0: f32 = if ground_pivot { 0.0 } else { -height_val * 0.5 };
460        let y1: f32 = if ground_pivot {
461            height_val
462        } else {
463            height_val * 0.5
464        };
465        let faces: [([Vec3; 4], Vec3); 6] = [
466            (
467                [
468                    Vec3::new(-hx, y0, hz),
469                    Vec3::new(hx, y0, hz),
470                    Vec3::new(hx, y1, hz),
471                    Vec3::new(-hx, y1, hz),
472                ],
473                Vec3::new(0.0, 0.0, 1.0),
474            ),
475            (
476                [
477                    Vec3::new(hx, y0, -hz),
478                    Vec3::new(-hx, y0, -hz),
479                    Vec3::new(-hx, y1, -hz),
480                    Vec3::new(hx, y1, -hz),
481                ],
482                Vec3::new(0.0, 0.0, -1.0),
483            ),
484            (
485                [
486                    Vec3::new(hx, y0, hz),
487                    Vec3::new(hx, y0, -hz),
488                    Vec3::new(hx, y1, -hz),
489                    Vec3::new(hx, y1, hz),
490                ],
491                Vec3::new(1.0, 0.0, 0.0),
492            ),
493            (
494                [
495                    Vec3::new(-hx, y0, -hz),
496                    Vec3::new(-hx, y0, hz),
497                    Vec3::new(-hx, y1, hz),
498                    Vec3::new(-hx, y1, -hz),
499                ],
500                Vec3::new(-1.0, 0.0, 0.0),
501            ),
502            (
503                [
504                    Vec3::new(-hx, y1, hz),
505                    Vec3::new(hx, y1, hz),
506                    Vec3::new(hx, y1, -hz),
507                    Vec3::new(-hx, y1, -hz),
508                ],
509                Vec3::new(0.0, 1.0, 0.0),
510            ),
511            (
512                [
513                    Vec3::new(-hx, y0, -hz),
514                    Vec3::new(hx, y0, -hz),
515                    Vec3::new(hx, y0, hz),
516                    Vec3::new(-hx, y0, hz),
517                ],
518                Vec3::new(0.0, -1.0, 0.0),
519            ),
520        ];
521        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(24);
522        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(12);
523        for (quad, item_count) in faces.into_iter() {
524            let base: u32 = vertices.len() as u32;
525            for point_val in quad.into_iter() {
526                vertices.push(Vertex3D::new(point_val, item_count));
527            }
528            indices.push([base, base + 1, base + 2]);
529            indices.push([base, base + 2, base + 3]);
530        }
531        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
532        mesh.set_is_closed(true);
533        mesh
534    }
535
536    /// Generates a horizontal ground/road quad plane at `y = 0` subdivided for crisp specular/shadow falloff.
537    ///
538    /// # Arguments
539    ///
540    /// - `&str` - Mesh name.
541    /// - `f32` - Width along X.
542    /// - `f32` - Depth along Z.
543    /// - `usize` - Grid subdivisions per axis.
544    /// - `PbrMaterial` - Surface PBR material.
545    ///
546    /// # Returns
547    ///
548    /// - `Self` - Subdivided ground plane mesh.
549    #[must_use]
550    pub fn ground_plane(
551        name: &str,
552        width_val: f32,
553        delta_val: f32,
554        subdivisions: usize,
555        material: PbrMaterial,
556    ) -> Self {
557        let segs: usize = subdivisions.clamp(1, 16);
558        let mut vertices: Vec<Vertex3D> = Vec::with_capacity((segs + 1) * (segs + 1));
559        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(segs * segs * 2);
560        let up: Vec3 = Vec3::new(0.0, 1.0, 0.0);
561        for iz in 0..=segs {
562            let vz: f32 = ((iz as f32) / (segs as f32) - 0.5) * delta_val;
563            for ix in 0..=segs {
564                let vx: f32 = ((ix as f32) / (segs as f32) - 0.5) * width_val;
565                vertices.push(Vertex3D::new(Vec3::new(vx, 0.0, vz), up));
566            }
567        }
568        let stride: u32 = (segs + 1) as u32;
569        for iz in 0..segs {
570            for ix in 0..segs {
571                let i0: u32 = (iz as u32) * stride + (ix as u32);
572                let i1: u32 = i0 + 1;
573                let i2: u32 = i0 + stride;
574                let i3: u32 = i2 + 1;
575                indices.push([i0, i2, i1]);
576                indices.push([i1, i2, i3]);
577            }
578        }
579        Self::from_parts(name.to_string(), vertices, indices, material)
580    }
581
582    /// Generates a low-poly sculpted sports car chassis resting on `y = 0`.
583    ///
584    /// # Arguments
585    ///
586    /// - `&str` - Asset name.
587    /// - `PbrMaterial` - Car body paint PBR material.
588    ///
589    /// # Returns
590    ///
591    /// - `Self` - Composite vehicle mesh.
592    #[must_use]
593    pub fn sports_car(name: &str, material: PbrMaterial) -> Self {
594        let lower: Self = Self::box_mesh(MESH_CAR_LOWER, 2.2, 0.80, 4.6, true, material);
595        let cabin: Self = Self::box_mesh(MESH_CAR_CABIN, 1.82, 0.72, 2.2, true, material);
596        let wheel: Self = Self::box_mesh(MESH_CAR_WHEEL, 0.34, 0.56, 0.62, true, material);
597        let wing: Self = Self::box_mesh(MESH_CAR_WING, 2.04, 0.11, 0.42, true, material);
598        let strut: Self = Self::box_mesh(MESH_CAR_STRUT, 0.10, 0.30, 0.18, true, material);
599        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(216);
600        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(108);
601        let lower_offset: u32 = vertices.len() as u32;
602        for item_val in lower.get_vertices().iter() {
603            let vec_value: Vec3 = item_val.get_position();
604            let mut px: f32 = vec_value.get_x();
605            let mut py: f32 = vec_value.get_y();
606            let pz: f32 = vec_value.get_z();
607            let mut norm: Vec3 = item_val.get_normal();
608            if py > 0.4 {
609                if pz < 0.0 {
610                    px *= 0.86;
611                    py *= 0.66;
612                    norm = norm.add(Vec3::new(0.0, 0.35, -0.45)).normalize();
613                } else {
614                    px *= 0.98;
615                    py *= 1.04;
616                    norm = norm.add(Vec3::new(0.0, 0.20, 0.15)).normalize();
617                }
618            }
619            vertices.push(Vertex3D::new(Vec3::new(px, py + 0.24, pz), norm));
620        }
621        for tri in lower.get_indices().iter() {
622            indices.push([
623                tri[0] + lower_offset,
624                tri[1] + lower_offset,
625                tri[2] + lower_offset,
626            ]);
627        }
628        let cabin_offset: u32 = vertices.len() as u32;
629        for tex_v in cabin.get_vertices().iter() {
630            let direction_vec: Vec3 = tex_v.get_position();
631            let mut px: f32 = direction_vec.get_x();
632            let py: f32 = direction_vec.get_y();
633            let mut pz: f32 = direction_vec.get_z();
634            let mut norm: Vec3 = tex_v.get_normal();
635            if py > 0.35 {
636                px *= 0.76;
637                if pz < 0.0 {
638                    pz += 0.46;
639                    norm = norm.add(Vec3::new(0.0, 0.55, -0.50)).normalize();
640                } else {
641                    pz -= 0.18;
642                    norm = norm.add(Vec3::new(0.0, 0.45, 0.35)).normalize();
643                }
644            } else if pz > 0.0 {
645                pz += 0.26;
646            }
647            vertices.push(Vertex3D::new(Vec3::new(px, py + 0.98, pz + 0.06), norm));
648        }
649        for tri in cabin.get_indices().iter() {
650            indices.push([
651                tri[0] + cabin_offset,
652                tri[1] + cabin_offset,
653                tri[2] + cabin_offset,
654            ]);
655        }
656        let wing_offset: u32 = vertices.len() as u32;
657        for wing_v in wing.get_vertices().iter() {
658            let wp: Vec3 = wing_v.get_position();
659            vertices.push(Vertex3D::new(
660                Vec3::new(wp.get_x(), wp.get_y() + 1.24, wp.get_z() + 1.98),
661                wing_v.get_normal(),
662            ));
663        }
664        for tri in wing.get_indices().iter() {
665            indices.push([
666                tri[0] + wing_offset,
667                tri[1] + wing_offset,
668                tri[2] + wing_offset,
669            ]);
670        }
671        for strut_x in [-0.66_f32, 0.66_f32] {
672            let strut_off: u32 = vertices.len() as u32;
673            for sv in strut.get_vertices().iter() {
674                let sp: Vec3 = sv.get_position();
675                vertices.push(Vertex3D::new(
676                    Vec3::new(sp.get_x() + strut_x, sp.get_y() + 0.98, sp.get_z() + 1.94),
677                    sv.get_normal(),
678                ));
679            }
680            for tri in strut.get_indices().iter() {
681                indices.push([tri[0] + strut_off, tri[1] + strut_off, tri[2] + strut_off]);
682            }
683        }
684        let wheel_offsets: [(f32, f32); 4] =
685            [(-1.12, -1.45), (1.12, -1.45), (-1.12, 1.45), (1.12, 1.45)];
686        for (wx, wz) in wheel_offsets.into_iter() {
687            let base: u32 = vertices.len() as u32;
688            for bary_v in wheel.get_vertices().iter() {
689                let position_vec: Vec3 = bary_v.get_position();
690                vertices.push(Vertex3D::new(
691                    Vec3::new(
692                        position_vec.get_x() + wx,
693                        position_vec.get_y() + 0.02,
694                        position_vec.get_z() + wz,
695                    ),
696                    bary_v.get_normal(),
697                ));
698            }
699            for tri in wheel.get_indices().iter() {
700                indices.push([tri[0] + base, tri[1] + base, tri[2] + base]);
701            }
702        }
703        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
704        mesh.set_is_closed(true);
705        mesh
706    }
707
708    /// Builds a box mesh from a fluent `BoxMeshDesc`.
709    ///
710    /// # Arguments
711    ///
712    /// - `&BoxMeshDesc` - Box mesh descriptor.
713    ///
714    /// # Returns
715    ///
716    /// - `Self` - Indexed 12-triangle box mesh.
717    #[must_use]
718    pub fn from_box_desc(desc: &BoxMeshDesc) -> Self {
719        let size: Vec3 = desc.get_size();
720        Self::box_mesh(
721            desc.get_name(),
722            size.get_x(),
723            size.get_y(),
724            size.get_z(),
725            desc.get_ground_pivot(),
726            desc.get_material(),
727        )
728    }
729
730    /// Builds a subdivided ground plane from a fluent `GroundPlaneDesc`.
731    ///
732    /// # Arguments
733    ///
734    /// - `&GroundPlaneDesc` - Ground plane descriptor.
735    ///
736    /// # Returns
737    ///
738    /// - `Self` - Subdivided ground plane mesh.
739    #[must_use]
740    pub fn from_ground_desc(desc: &GroundPlaneDesc) -> Self {
741        Self::ground_plane(
742            desc.get_name(),
743            desc.get_width(),
744            desc.get_depth(),
745            desc.get_subdivisions(),
746            desc.get_material(),
747        )
748    }
749
750    /// Builds a simplified proxy mesh enclosing this mesh's axis-aligned bounding box for distant LOD tiers.
751    ///
752    /// # Arguments
753    ///
754    /// - `&Self` - Source mesh reference.
755    /// - `&str` - LOD suffix label.
756    ///
757    /// # Returns
758    ///
759    /// - `Self` - Lightweight 12-triangle LOD proxy mesh.
760    #[must_use]
761    pub fn build_lod_proxy(&self, suffix: &str) -> Self {
762        let blue_val: AxisAlignedBox3D = self.get_bounds();
763        let size: Vec3 = blue_val.get_max().sub(blue_val.get_min());
764        let center: Vec3 = blue_val.center();
765        let mut proxy: Self = Self::box_mesh(
766            &format!("{}_{suffix}", self.get_name()),
767            size.get_x().max(0.2),
768            size.get_y().max(0.2),
769            size.get_z().max(0.2),
770            false,
771            self.get_material(),
772        );
773        for item_val in proxy.get_mut_vertices().iter_mut() {
774            item_val.set_position(item_val.get_position().add(center));
775        }
776        proxy.set_bounds(blue_val);
777        let meshlets: Vec<Meshlet3D> =
778            Self::build_meshlets_from_parts(proxy.get_vertices(), proxy.get_indices());
779        proxy.set_meshlets(meshlets);
780        proxy
781    }
782
783    /// Produces a mid-detail decimated mesh by retaining dominant triangles while preserving bounding silhouette.
784    ///
785    /// # Arguments
786    ///
787    /// - `&Self` - Source mesh reference.
788    /// - `&str` - LOD suffix label.
789    ///
790    /// # Returns
791    ///
792    /// - `Self` - Decimated intermediate LOD mesh.
793    #[must_use]
794    pub fn build_mid_lod(&self, suffix: &str) -> Self {
795        let verts: &[Vertex3D] = self.get_vertices().as_slice();
796        let tris: &[[u32; 3]] = self.get_indices().as_slice();
797        if tris.len() <= 24 {
798            return self.build_lod_proxy(suffix);
799        }
800        let mut scored: Vec<(f32, [u32; 3])> = Vec::with_capacity(tris.len());
801        for tri in tris.iter().copied() {
802            let (i0, i1, i2): (usize, usize, usize) =
803                (tri[0] as usize, tri[1] as usize, tri[2] as usize);
804            if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
805                let p0: Vec3 = verts[i0].get_position();
806                let p1: Vec3 = verts[i1].get_position();
807                let p2: Vec3 = verts[i2].get_position();
808                let area2: f32 = p1.sub(p0).cross(p2.sub(p0)).length_sq();
809                scored.push((area2, tri));
810            }
811        }
812        scored.sort_unstable_by(|alpha_val: &(f32, [u32; 3]), blue_val: &(f32, [u32; 3])| {
813            blue_val.0.total_cmp(&alpha_val.0)
814        });
815        let keep: usize = (scored.len() / 2).max(12);
816        let reduced: Vec<[u32; 3]> = scored
817            .into_iter()
818            .take(keep)
819            .map(|(_, blend_factor): (f32, [u32; 3])| blend_factor)
820            .collect();
821        Self::from_parts(
822            format!("{}_{suffix}", self.get_name()),
823            self.get_vertices().clone(),
824            reduced,
825            self.get_material(),
826        )
827    }
828}
829
830/// Multi-level continuous LOD chain creation and screen-error selection for `MeshLodChain`.
831impl MeshLodChain {
832    /// Builds a continuous 3-tier Nanite-style LOD chain (`LOD0` full -> `LOD1` mid -> `LOD2` proxy) automatically.
833    ///
834    /// # Arguments
835    ///
836    /// - `Mesh3D` - Full-resolution `LOD0` mesh.
837    ///
838    /// # Returns
839    ///
840    /// - `Self` - Ready LOD chain.
841    #[must_use]
842    pub fn from_mesh(mesh: Mesh3D) -> Self {
843        let tri_count: usize = mesh.get_indices().len();
844        if tri_count > 32 {
845            let lod1: Mesh3D = mesh.build_mid_lod(MESH_LOD1_SUFFIX);
846            let lod2: Mesh3D = mesh.build_lod_proxy(MESH_LOD2_SUFFIX);
847            Self {
848                levels: vec![mesh, lod1, lod2],
849            }
850        } else if tri_count > 16 {
851            let lod1: Mesh3D = mesh.build_lod_proxy(MESH_LOD1_SUFFIX);
852            Self {
853                levels: vec![mesh, lod1],
854            }
855        } else {
856            let clone_lod1: Mesh3D = mesh.clone();
857            Self {
858                levels: vec![mesh, clone_lod1],
859            }
860        }
861    }
862
863    /// Selects the appropriate `Mesh3D` detail level for `distance` and `lod_bias`.
864    ///
865    /// # Arguments
866    ///
867    /// - `&Self` - LOD chain reference.
868    /// - `f32` - Camera-to-object distance in meters.
869    /// - `f32` - Quality LOD bias multiplier.
870    ///
871    /// # Returns
872    ///
873    /// - `(&Mesh3D, usize)` - Selected mesh reference and its LOD tier index.
874    #[must_use]
875    pub fn select(&self, distance: f32, lod_bias: f32) -> (&Mesh3D, usize) {
876        let levels: &[Mesh3D] = self.get_levels().as_slice();
877        let effective_dist: f32 = distance * lod_bias.max(0.25);
878        if levels.len() > 2 && effective_dist > 135.0 {
879            (&levels[2], 2)
880        } else if levels.len() > 1 && effective_dist > 78.0 {
881            (&levels[1], 1)
882        } else {
883            (&levels[0], 0)
884        }
885    }
886
887    /// Nanite-style continuous LOD selection driven by projected screen-space pixel coverage.
888    ///
889    /// # Arguments
890    ///
891    /// - `&Self` - LOD chain reference.
892    /// - `f32` - Camera-to-object distance in meters.
893    /// - `f32` - World-space bounding sphere radius in meters.
894    /// - `f32` - Projected viewport focal length in pixels (`height / (2 * tan(fov/2))`).
895    /// - `f32` - Quality LOD bias multiplier (`< 1.0` higher detail, `> 1.0` aggressive simplification).
896    ///
897    /// # Returns
898    ///
899    /// - `(&Mesh3D, usize)` - Selected mesh reference and its LOD tier index.
900    #[must_use]
901    pub fn select_screen_error(
902        &self,
903        distance: f32,
904        bounds_radius: f32,
905        focal_px: f32,
906        lod_bias: f32,
907    ) -> (&Mesh3D, usize) {
908        let levels: &[Mesh3D] = self.get_levels().as_slice();
909        let safe_dist: f32 = distance.max(0.5);
910        let projected_px: f32 =
911            (bounds_radius.max(0.2) * focal_px) / (safe_dist * lod_bias.max(0.25));
912        if levels.len() > 2 && projected_px < 22.0 {
913            (&levels[2], 2)
914        } else if levels.len() > 1 && projected_px < 58.0 {
915            (&levels[1], 1)
916        } else {
917            (&levels[0], 0)
918        }
919    }
920}
921
922/// Native Wavefront `.obj` and glTF 2.0 `.gltf` JSON parsers for `ModelImporter3D`.
923impl ModelImporter3D {
924    /// Imports a 3D model from text source in the specified `ModelFormat` and generates LOD chains.
925    ///
926    /// # Arguments
927    ///
928    /// - `ModelFormat` - Interchange format (`Obj` or `GltfJson`).
929    /// - `&str` - Raw `.obj` or `.gltf` text content.
930    /// - `PbrMaterial` - Fallback PBR material when source omits material definitions.
931    ///
932    /// # Returns
933    ///
934    /// - `Result<ImportedModel3D, String>` - Imported model bundle or parse error diagnostic.
935    pub fn import(
936        format: ModelFormat,
937        source: &str,
938        fallback_material: PbrMaterial,
939    ) -> Result<ImportedModel3D, String> {
940        match format {
941            ModelFormat::Obj => Self::parse_obj(source, fallback_material),
942            ModelFormat::GltfJson => Self::parse_gltf_json(source, fallback_material),
943        }
944    }
945
946    /// Parses a Wavefront `.obj` mesh (`o`, `v`, `vn`, `f` with n-gon fan triangulation and auto-normals).
947    ///
948    /// # Arguments
949    ///
950    /// - `&str` - Raw `.obj` ASCII text.
951    /// - `PbrMaterial` - Material assigned to the parsed mesh.
952    ///
953    /// # Returns
954    ///
955    /// - `Result<ImportedModel3D, String>` - Parsed model or error string.
956    pub fn parse_obj(source: &str, material: PbrMaterial) -> Result<ImportedModel3D, String> {
957        let mut positions: Vec<Vec3> = Vec::new();
958        let mut normals: Vec<Vec3> = Vec::new();
959        let mut vertices: Vec<Vertex3D> = Vec::new();
960        let mut indices: Vec<[u32; 3]> = Vec::new();
961        let mut model_name: String = MESH_OBJ_DEFAULT_NAME.to_string();
962        for raw_line in source.lines() {
963            let line: &str = raw_line.trim();
964            if line.is_empty() || line.starts_with('#') {
965                continue;
966            }
967            let parts: Vec<&str> = line.split_whitespace().collect();
968            if parts.is_empty() {
969                continue;
970            }
971            match parts[0] {
972                "o" | "g" if parts.len() >= 2 => {
973                    model_name = parts[1].to_string();
974                }
975                "v" if parts.len() >= 4 => {
976                    let pos_x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
977                    let pos_y: f32 = parts[2].parse::<f32>().unwrap_or(0.0);
978                    let pos_z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
979                    positions.push(Vec3::new(pos_x, pos_y, pos_z));
980                }
981                "vn" if parts.len() >= 4 => {
982                    let coord_x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
983                    let coord_y: f32 = parts[2].parse::<f32>().unwrap_or(1.0);
984                    let coord_z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
985                    normals.push(Vec3::new(coord_x, coord_y, coord_z).normalize());
986                }
987                "f" if parts.len() >= 4 => {
988                    let mut face_verts: Vec<(Vec3, Option<Vec3>)> =
989                        Vec::with_capacity(parts.len() - 1);
990                    for token in parts.iter().skip(1) {
991                        let comps: Vec<&str> = token.split('/').collect();
992                        let v_idx_raw: i32 = comps
993                            .first()
994                            .and_then(|source_val: &&str| source_val.parse::<i32>().ok())
995                            .unwrap_or(0);
996                        let p_opt: Option<Vec3> = if v_idx_raw > 0 {
997                            positions.get((v_idx_raw - 1) as usize).copied()
998                        } else if v_idx_raw < 0 {
999                            let idx: isize = (positions.len() as isize) + (v_idx_raw as isize);
1000                            if idx >= 0 {
1001                                positions.get(idx as usize).copied()
1002                            } else {
1003                                None
1004                            }
1005                        } else {
1006                            None
1007                        };
1008                        let n_opt: Option<Vec3> = comps
1009                            .get(2)
1010                            .and_then(|scale_val: &&str| scale_val.parse::<i32>().ok())
1011                            .and_then(|n_raw: i32| {
1012                                if n_raw > 0 {
1013                                    normals.get((n_raw - 1) as usize).copied()
1014                                } else {
1015                                    None
1016                                }
1017                            });
1018                        if let Some(pos) = p_opt {
1019                            face_verts.push((pos, n_opt));
1020                        }
1021                    }
1022                    if face_verts.len() >= 3 {
1023                        for entry_index in 1..(face_verts.len() - 1) {
1024                            let (p0, n0): (Vec3, Option<Vec3>) = face_verts[0];
1025                            let (p1, n1): (Vec3, Option<Vec3>) = face_verts[entry_index];
1026                            let (p2, n2): (Vec3, Option<Vec3>) = face_verts[entry_index + 1];
1027                            let face_n: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
1028                            let base: u32 = vertices.len() as u32;
1029                            vertices.push(Vertex3D::new(p0, n0.unwrap_or(face_n)));
1030                            vertices.push(Vertex3D::new(p1, n1.unwrap_or(face_n)));
1031                            vertices.push(Vertex3D::new(p2, n2.unwrap_or(face_n)));
1032                            indices.push([base, base + 1, base + 2]);
1033                        }
1034                    }
1035                }
1036                _ => {}
1037            }
1038        }
1039        if indices.is_empty() {
1040            return Err(ERR_OBJ_EMPTY.to_string());
1041        }
1042        let total_vertices: usize = vertices.len();
1043        let total_triangles: usize = indices.len();
1044        let mesh: Mesh3D = Mesh3D::from_parts(model_name.clone(), vertices, indices, material);
1045        Ok(ImportedModel3D {
1046            name: model_name,
1047            format: ModelFormat::Obj,
1048            meshes: vec![MeshLodChain::from_mesh(mesh)],
1049            total_vertices,
1050            total_triangles,
1051        })
1052    }
1053
1054    /// Parses a glTF 2.0 JSON asset supporting inline PBR materials and embedded mesh positions/indices.
1055    ///
1056    /// # Arguments
1057    ///
1058    /// - `&str` - Raw `.gltf` JSON string.
1059    /// - `PbrMaterial` - Fallback PBR material when JSON omits `pbrMetallicRoughness`.
1060    ///
1061    /// # Returns
1062    ///
1063    /// - `Result<ImportedModel3D, String>` - Parsed model bundle or validation error.
1064    pub fn parse_gltf_json(
1065        source: &str,
1066        fallback_material: PbrMaterial,
1067    ) -> Result<ImportedModel3D, String> {
1068        let root: Value = from_str::<Value>(source)
1069            .ok()
1070            .ok_or_else(|| ERR_GLTF_JSON.to_string())?;
1071        let name: String = root
1072            .get(GLTF_KEY_ASSET)
1073            .and_then(|alpha_val: &Value| alpha_val.get(GLTF_KEY_GENERATOR))
1074            .and_then(Value::as_str)
1075            .unwrap_or(MESH_GLTF_DEFAULT_NAME)
1076            .to_string();
1077        let mut mat: PbrMaterial = fallback_material;
1078        if let Some(pbr) = root
1079            .get(GLTF_KEY_MATERIALS)
1080            .and_then(Value::as_array)
1081            .and_then(|arr: &Vec<Value>| arr.first())
1082            .and_then(|matrix_elems: &Value| matrix_elems.get(GLTF_KEY_PBR))
1083        {
1084            if let Some(bc) = pbr.get(GLTF_KEY_BASE_COLOR).and_then(Value::as_array)
1085                && bc.len() >= 3
1086            {
1087                let red_val: f32 = bc[0].as_f64().unwrap_or(0.8) as f32;
1088                let green_val: f32 = bc[1].as_f64().unwrap_or(0.8) as f32;
1089                let blue_val: f32 = bc[2].as_f64().unwrap_or(0.8) as f32;
1090                mat.set_base_color(Vec3::new(red_val, green_val, blue_val));
1091            }
1092            if let Some(met) = pbr.get(GLTF_KEY_METALLIC).and_then(Value::as_f64) {
1093                mat.set_metallic((met as f32).clamp(0.0, 1.0));
1094            }
1095            if let Some(rough) = pbr.get(GLTF_KEY_ROUGHNESS).and_then(Value::as_f64) {
1096                mat.set_roughness((rough as f32).clamp(0.04, 1.0));
1097                mat.set_reflectivity((1.0 - (rough as f32)).clamp(0.05, 0.95));
1098            }
1099        }
1100        let mut chains: Vec<MeshLodChain> = Vec::new();
1101        let mut total_vertices: usize = 0;
1102        let mut total_triangles: usize = 0;
1103        if let Some(meshes_arr) = root.get(GLTF_KEY_MESHES).and_then(Value::as_array) {
1104            for (m_idx, m_val) in meshes_arr.iter().enumerate() {
1105                let mesh_name: String = m_val
1106                    .get(GLTF_KEY_NAME)
1107                    .and_then(Value::as_str)
1108                    .map(str::to_string)
1109                    .unwrap_or_else(|| format!("{name}_mesh_{m_idx}"));
1110                let Some(prims) = m_val.get(GLTF_KEY_PRIMITIVES).and_then(Value::as_array) else {
1111                    continue;
1112                };
1113                for prim in prims.iter() {
1114                    let extras: &Value = prim.get(GLTF_KEY_EXTRAS).unwrap_or(prim);
1115                    let pos_vals: Vec<f32> = extras
1116                        .get(GLTF_KEY_POSITIONS)
1117                        .and_then(Value::as_array)
1118                        .map(|first_val: &Vec<Value>| {
1119                            first_val
1120                                .iter()
1121                                .filter_map(|item_val: &Value| {
1122                                    item_val.as_f64().map(|item_count: f64| item_count as f32)
1123                                })
1124                                .collect()
1125                        })
1126                        .unwrap_or_default();
1127                    let idx_vals: Vec<u32> = extras
1128                        .get(GLTF_KEY_INDICES)
1129                        .and_then(Value::as_array)
1130                        .map(|area_val: &Vec<Value>| {
1131                            area_val
1132                                .iter()
1133                                .filter_map(|tex_v: &Value| {
1134                                    tex_v.as_u64().map(|node_entry: u64| node_entry as u32)
1135                                })
1136                                .collect()
1137                        })
1138                        .unwrap_or_default();
1139                    let mut raw_pts: Vec<Vec3> = Vec::new();
1140                    for chunk in pos_vals.as_chunks::<3>().0 {
1141                        raw_pts.push(Vec3::new(chunk[0], chunk[1], chunk[2]));
1142                    }
1143                    let mut verts: Vec<Vertex3D> = Vec::new();
1144                    let mut tris: Vec<[u32; 3]> = Vec::new();
1145                    for tri in idx_vals.as_chunks::<3>().0 {
1146                        let (i0, i1, i2): (usize, usize, usize) =
1147                            (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1148                        if i0 < raw_pts.len() && i1 < raw_pts.len() && i2 < raw_pts.len() {
1149                            let p0: Vec3 = raw_pts[i0];
1150                            let p1: Vec3 = raw_pts[i1];
1151                            let p2: Vec3 = raw_pts[i2];
1152                            let vec_value: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
1153                            let base: u32 = verts.len() as u32;
1154                            verts.push(Vertex3D::new(p0, vec_value));
1155                            verts.push(Vertex3D::new(p1, vec_value));
1156                            verts.push(Vertex3D::new(p2, vec_value));
1157                            tris.push([base, base + 1, base + 2]);
1158                        }
1159                    }
1160                    if !tris.is_empty() {
1161                        total_vertices += verts.len();
1162                        total_triangles += tris.len();
1163                        let mesh: Mesh3D = Mesh3D::from_parts(mesh_name.clone(), verts, tris, mat);
1164                        chains.push(MeshLodChain::from_mesh(mesh));
1165                    }
1166                }
1167            }
1168        }
1169        if chains.is_empty() {
1170            return Err(ERR_GLTF_EMPTY.to_string());
1171        }
1172        Ok(ImportedModel3D {
1173            name,
1174            format: ModelFormat::GltfJson,
1175            meshes: chains,
1176            total_vertices,
1177            total_triangles,
1178        })
1179    }
1180}