Skip to main content

euv_core/game/engine3d/world/
impl.rs

1use super::*;
2
3/// Default identity `Transform3D`.
4impl Default for Transform3D {
5    /// Returns identity transform at origin with unit scale.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Identity `Transform3D`.
10    fn default() -> Self {
11        Self {
12            position: Vec3::zero(),
13            yaw_rad: 0.0,
14            pitch_rad: 0.0,
15            roll_rad: 0.0,
16            scale: Vec3::splat(1.0),
17        }
18    }
19}
20
21/// Matrix and point transformation helpers for `Transform3D`.
22impl Transform3D {
23    /// Constructs a `Transform3D` from position, Y-axis yaw, and non-uniform scale.
24    ///
25    /// # Arguments
26    ///
27    /// - `Vec3` - World-space translation.
28    /// - `f32` - Horizontal Y-axis yaw rotation in radians.
29    /// - `Vec3` - Non-uniform scale.
30    ///
31    /// # Returns
32    ///
33    /// - `Self` - Constructed 3D transform.
34    #[must_use]
35    pub const fn new(position: Vec3, yaw_rad: f32, scale: Vec3) -> Self {
36        Self {
37            position,
38            yaw_rad,
39            pitch_rad: 0.0,
40            roll_rad: 0.0,
41            scale,
42        }
43    }
44
45    /// Returns a copy of this transform with full yaw, pitch, and roll Euler rotation in radians.
46    ///
47    /// # Arguments
48    ///
49    /// - `Self` - Source transform.
50    /// - `f32` - Y-axis yaw in radians.
51    /// - `f32` - X-axis pitch in radians.
52    /// - `f32` - Z-axis roll in radians.
53    ///
54    /// # Returns
55    ///
56    /// - `Self` - Rotated 3D transform.
57    #[must_use]
58    pub fn with_euler(mut self, yaw_rad: f32, pitch_rad: f32, roll_rad: f32) -> Self {
59        self.set_yaw_rad(yaw_rad);
60        self.set_pitch_rad(pitch_rad);
61        self.set_roll_rad(roll_rad);
62        self
63    }
64
65    /// Linearly interpolates position, Euler angles, and scale between `self` and `other`.
66    ///
67    /// # Arguments
68    ///
69    /// - `Self` - Start transform.
70    /// - `Self` - End transform.
71    /// - `f32` - Interpolation factor in `[0.0, 1.0]`.
72    ///
73    /// # Returns
74    ///
75    /// - `Self` - Interpolated transform.
76    #[must_use]
77    pub fn lerp(self, other: Self, t: f32) -> Self {
78        let k: f32 = t.clamp(0.0, 1.0);
79        Self {
80            position: self.get_position().lerp(other.get_position(), k),
81            yaw_rad: self.get_yaw_rad() + (other.get_yaw_rad() - self.get_yaw_rad()) * k,
82            pitch_rad: self.get_pitch_rad() + (other.get_pitch_rad() - self.get_pitch_rad()) * k,
83            roll_rad: self.get_roll_rad() + (other.get_roll_rad() - self.get_roll_rad()) * k,
84            scale: self.get_scale().lerp(other.get_scale(), k),
85        }
86    }
87
88    /// Converts this TRS transform into a column-major `Mat4`.
89    ///
90    /// # Arguments
91    ///
92    /// - `&Self` - Transform reference.
93    ///
94    /// # Returns
95    ///
96    /// - `Mat4` - Model matrix.
97    #[must_use]
98    pub fn to_mat4(&self) -> Mat4 {
99        Mat4::from_trs_euler(
100            self.get_position(),
101            self.get_yaw_rad(),
102            self.get_pitch_rad(),
103            self.get_roll_rad(),
104            self.get_scale(),
105        )
106    }
107
108    /// Rotates vector `v` by this transform's `(yaw, pitch, roll)` Euler orientation.
109    ///
110    /// # Arguments
111    ///
112    /// - `&Self` - Transform reference.
113    /// - `Vec3` - Input vector.
114    ///
115    /// # Returns
116    ///
117    /// - `Vec3` - Rotated vector.
118    #[must_use]
119    fn rotate_vec(&self, v: Vec3) -> Vec3 {
120        let pitch: f32 = self.get_pitch_rad();
121        let roll: f32 = self.get_roll_rad();
122        let yaw: f32 = self.get_yaw_rad();
123        let (cy, sy): (f32, f32) = (yaw.cos(), yaw.sin());
124        if pitch.abs() < 1e-6 && roll.abs() < 1e-6 {
125            return Vec3::new(
126                v.get_x() * cy + v.get_z() * sy,
127                v.get_y(),
128                -v.get_x() * sy + v.get_z() * cy,
129            );
130        }
131        let (cr, sr): (f32, f32) = (roll.cos(), roll.sin());
132        let x1: f32 = v.get_x() * cr - v.get_y() * sr;
133        let y1: f32 = v.get_x() * sr + v.get_y() * cr;
134        let z1: f32 = v.get_z();
135        let (cp, sp): (f32, f32) = (pitch.cos(), pitch.sin());
136        let x2: f32 = x1;
137        let y2: f32 = y1 * cp - z1 * sp;
138        let z2: f32 = y1 * sp + z1 * cp;
139        Vec3::new(x2 * cy + z2 * sy, y2, -x2 * sy + z2 * cy)
140    }
141
142    /// Transforms a local-space 3D point into world space.
143    ///
144    /// # Arguments
145    ///
146    /// - `&Self` - Transform reference.
147    /// - `Vec3` - Local-space point.
148    ///
149    /// # Returns
150    ///
151    /// - `Vec3` - World-space point.
152    #[must_use]
153    pub fn transform_point(&self, p: Vec3) -> Vec3 {
154        let sc: Vec3 = self.get_scale();
155        let scaled: Vec3 = Vec3::new(
156            p.get_x() * sc.get_x(),
157            p.get_y() * sc.get_y(),
158            p.get_z() * sc.get_z(),
159        );
160        self.rotate_vec(scaled).add(self.get_position())
161    }
162
163    /// Rotates a local-space surface normal into world space.
164    ///
165    /// # Arguments
166    ///
167    /// - `&Self` - Transform reference.
168    /// - `Vec3` - Local normal.
169    ///
170    /// # Returns
171    ///
172    /// - `Vec3` - World-space unit normal.
173    #[must_use]
174    pub fn transform_normal(&self, n: Vec3) -> Vec3 {
175        self.rotate_vec(n).normalize()
176    }
177
178    /// Transforms a local `Aabb3D` into an enclosing world-space `Aabb3D`.
179    ///
180    /// # Arguments
181    ///
182    /// - `&Self` - Transform reference.
183    /// - `Aabb3D` - Local bounding box.
184    ///
185    /// # Returns
186    ///
187    /// - `Aabb3D` - Enclosing world-space bounding box.
188    #[must_use]
189    pub fn transform_aabb(&self, local: Aabb3D) -> Aabb3D {
190        let mn: Vec3 = local.get_min();
191        let mx: Vec3 = local.get_max();
192        let corners: [Vec3; 8] = [
193            Vec3::new(mn.get_x(), mn.get_y(), mn.get_z()),
194            Vec3::new(mx.get_x(), mn.get_y(), mn.get_z()),
195            Vec3::new(mn.get_x(), mx.get_y(), mn.get_z()),
196            Vec3::new(mx.get_x(), mx.get_y(), mn.get_z()),
197            Vec3::new(mn.get_x(), mn.get_y(), mx.get_z()),
198            Vec3::new(mx.get_x(), mn.get_y(), mx.get_z()),
199            Vec3::new(mn.get_x(), mx.get_y(), mx.get_z()),
200            Vec3::new(mx.get_x(), mx.get_y(), mx.get_z()),
201        ];
202        let mut out: Aabb3D = Aabb3D::empty();
203        for c in corners.into_iter() {
204            out.expand_point(self.transform_point(c));
205        }
206        out
207    }
208}
209
210/// Conversion helpers for `CameraMode3D`.
211impl CameraMode3D {
212    /// Converts a numeric mode index (`0..=5`) into a typed `CameraMode3D`.
213    ///
214    /// # Arguments
215    ///
216    /// - `u8` - Numeric camera mode index.
217    ///
218    /// # Returns
219    ///
220    /// - `Self` - Corresponding `CameraMode3D`.
221    #[must_use]
222    pub const fn from_u8(index: u8) -> Self {
223        match index {
224            1 => Self::Hood,
225            2 => Self::Orbit,
226            3 => Self::Aerial,
227            4 => Self::FreeFly,
228            5 => Self::CinematicDolly,
229            _ => Self::Chase,
230        }
231    }
232
233    /// Converts this `CameraMode3D` into its stable numeric index (`0..=5`).
234    ///
235    /// # Arguments
236    ///
237    /// - `Self` - Camera mode variant.
238    ///
239    /// # Returns
240    ///
241    /// - `u8` - Numeric mode index.
242    #[must_use]
243    pub const fn as_u8(self) -> u8 {
244        match self {
245            Self::Chase => 0,
246            Self::Hood => 1,
247            Self::Orbit => 2,
248            Self::Aerial => 3,
249            Self::FreeFly => 4,
250            Self::CinematicDolly => 5,
251        }
252    }
253}
254
255/// Fluent builder helpers for `SpawnObjectDesc`.
256impl SpawnObjectDesc {
257    /// Creates an object spawn descriptor with identity transform, default PBR material, and BVH ray tracing enabled.
258    ///
259    /// # Arguments
260    ///
261    /// - `&str` - Human-readable object label.
262    /// - `usize` - Registered mesh identifier.
263    ///
264    /// # Returns
265    ///
266    /// - `Self` - Ready spawn descriptor.
267    #[must_use]
268    pub fn new(name: &str, mesh_id: usize) -> Self {
269        Self {
270            name: name.to_string(),
271            mesh_id,
272            transform: Transform3D::default(),
273            material: PbrMaterial::default(),
274            ray_trace_caster: true,
275            spin_speed: 0.0,
276        }
277    }
278
279    /// Sets the world-space transform for the spawned object.
280    ///
281    /// # Arguments
282    ///
283    /// - `Self` - Base descriptor.
284    /// - `Transform3D` - World-space transform.
285    ///
286    /// # Returns
287    ///
288    /// - `Self` - Updated descriptor.
289    #[must_use]
290    pub fn with_transform(mut self, transform: Transform3D) -> Self {
291        self.set_transform(transform);
292        self
293    }
294
295    /// Sets the PBR surface material override for the spawned object.
296    ///
297    /// # Arguments
298    ///
299    /// - `Self` - Base descriptor.
300    /// - `PbrMaterial` - PBR material.
301    ///
302    /// # Returns
303    ///
304    /// - `Self` - Updated descriptor.
305    #[must_use]
306    pub fn with_material(mut self, material: PbrMaterial) -> Self {
307        self.set_material(material);
308        self
309    }
310
311    /// Sets whether this object casts BVH shadows and appears in reflections.
312    ///
313    /// # Arguments
314    ///
315    /// - `Self` - Base descriptor.
316    /// - `bool` - Ray-trace caster toggle.
317    ///
318    /// # Returns
319    ///
320    /// - `Self` - Updated descriptor.
321    #[must_use]
322    pub fn with_ray_trace(mut self, ray_trace_caster: bool) -> Self {
323        self.set_ray_trace_caster(ray_trace_caster);
324        self
325    }
326
327    /// Sets continuous Y-axis spin speed in radians per second.
328    ///
329    /// # Arguments
330    ///
331    /// - `Self` - Base descriptor.
332    /// - `f32` - Spin speed in radians/sec.
333    ///
334    /// # Returns
335    ///
336    /// - `Self` - Updated descriptor.
337    #[must_use]
338    pub fn with_spin(mut self, spin_speed: f32) -> Self {
339        self.set_spin_speed(spin_speed);
340        self
341    }
342}
343
344/// Fluent builder helpers for `ImportModelDesc`.
345impl ImportModelDesc {
346    /// Creates an external model import descriptor with identity transform and default PBR fallback material.
347    ///
348    /// # Arguments
349    ///
350    /// - `ModelFormat` - Interchange format (`Obj` or `GltfJson`).
351    /// - `&str` - Raw model source text.
352    ///
353    /// # Returns
354    ///
355    /// - `Self` - Ready import descriptor.
356    #[must_use]
357    pub fn new(format: ModelFormat, source: &str) -> Self {
358        Self {
359            format,
360            source: source.to_string(),
361            transform: Transform3D::default(),
362            fallback_material: PbrMaterial::default(),
363            spin_speed: 0.0,
364        }
365    }
366
367    /// Sets the placement transform for the imported model.
368    ///
369    /// # Arguments
370    ///
371    /// - `Self` - Base descriptor.
372    /// - `Transform3D` - Placement transform.
373    ///
374    /// # Returns
375    ///
376    /// - `Self` - Updated descriptor.
377    #[must_use]
378    pub fn with_transform(mut self, transform: Transform3D) -> Self {
379        self.set_transform(transform);
380        self
381    }
382
383    /// Sets the fallback PBR material when source omits material metadata.
384    ///
385    /// # Arguments
386    ///
387    /// - `Self` - Base descriptor.
388    /// - `PbrMaterial` - Fallback PBR material.
389    ///
390    /// # Returns
391    ///
392    /// - `Self` - Updated descriptor.
393    #[must_use]
394    pub fn with_material(mut self, fallback_material: PbrMaterial) -> Self {
395        self.set_fallback_material(fallback_material);
396        self
397    }
398
399    /// Sets continuous Y-axis turntable spin speed in radians per second.
400    ///
401    /// # Arguments
402    ///
403    /// - `Self` - Base descriptor.
404    /// - `f32` - Spin speed in radians/sec.
405    ///
406    /// # Returns
407    ///
408    /// - `Self` - Updated descriptor.
409    #[must_use]
410    pub fn with_spin(mut self, spin_speed: f32) -> Self {
411        self.set_spin_speed(spin_speed);
412        self
413    }
414}
415
416/// Dynamic Time-of-Day sun and atmospheric sky lighting for `DirectionalLight3D`.
417impl DirectionalLight3D {
418    /// Computes physically inspired sun direction, sun color, and sky colors for `hour` in `[0.0, 24.0]`.
419    ///
420    /// # Arguments
421    ///
422    /// - `f32` - Hour of day (`6.0` dawn, `12.0` noon, `17.5` golden sunset, `22.0` neon night).
423    ///
424    /// # Returns
425    ///
426    /// - `Self` - Updated atmospheric directional light.
427    #[must_use]
428    pub fn from_time_of_day(hour: f32) -> Self {
429        let h: f32 = hour.rem_euclid(24.0);
430        let elev_angle: f32 = ((h - 6.0) / 12.0 * PI).clamp(-0.35, 3.49);
431        let sun_y: f32 = elev_angle.sin();
432        let sun_x: f32 = elev_angle.cos();
433        let dir: Vec3 = Vec3::new(sun_x * 0.85, sun_y.max(0.18), 0.52).normalize();
434        if (7.5..=16.5).contains(&h) {
435            Self {
436                direction: dir,
437                color: Vec3::new(2.2, 2.08, 1.92),
438                sky_zenith: Vec3::new(0.14, 0.34, 0.72),
439                sky_horizon: Vec3::new(0.62, 0.78, 0.94),
440                time_of_day: h,
441            }
442        } else if (5.5..7.5).contains(&h) || (16.5..19.5).contains(&h) {
443            Self {
444                direction: dir,
445                color: Vec3::new(2.4, 1.35, 0.72),
446                sky_zenith: Vec3::new(0.15, 0.14, 0.38),
447                sky_horizon: Vec3::new(0.92, 0.45, 0.28),
448                time_of_day: h,
449            }
450        } else {
451            Self {
452                direction: Vec3::new(-0.4, 0.65, 0.55).normalize(),
453                color: Vec3::new(0.55, 0.68, 1.15),
454                sky_zenith: Vec3::new(0.02, 0.03, 0.09),
455                sky_horizon: Vec3::new(0.08, 0.11, 0.24),
456                time_of_day: h,
457            }
458        }
459    }
460}
461
462/// Default golden-sunset directional light.
463impl Default for DirectionalLight3D {
464    /// Creates a golden-hour sunset sun configuration.
465    ///
466    /// # Returns
467    ///
468    /// - `Self` - Sunset `DirectionalLight3D`.
469    fn default() -> Self {
470        Self::from_time_of_day(17.2)
471    }
472}
473
474/// Default empty 3D open world.
475impl Default for World3D {
476    /// Creates an empty `World3D` with 64m chunk streaming enabled.
477    ///
478    /// # Returns
479    ///
480    /// - `Self` - Empty `World3D`.
481    fn default() -> Self {
482        Self {
483            mesh_library: Vec::new(),
484            objects: Vec::new(),
485            camera: Camera3D::default(),
486            sun: DirectionalLight3D::default(),
487            bvh: Bvh3D::default(),
488            bvh_dirty: true,
489            chunk_size: 64.0,
490            player_vehicle_index: None,
491            imported_model_count: 0,
492            camera_mode: 0,
493            camera_orbit_rad: 0.4,
494        }
495    }
496}
497
498/// Open-world construction, model importing, BVH rebuild, and live vehicle/camera simulation for `World3D`.
499impl World3D {
500    /// Registers a `MeshLodChain` in the instancing library and returns its `mesh_id`.
501    ///
502    /// # Arguments
503    ///
504    /// - `&Self` - Mutable world.
505    /// - `MeshLodChain` - Multi-level LOD mesh chain.
506    ///
507    /// # Returns
508    ///
509    /// - `usize` - Assigned `mesh_id`.
510    pub fn register_mesh(&mut self, chain: MeshLodChain) -> usize {
511        let id: usize = self.get_mesh_library().len();
512        self.get_mut_mesh_library().push(chain);
513        id
514    }
515
516    /// Spawns an instanced `SceneObject3D` referencing `mesh_id` into its spatial world chunk.
517    ///
518    /// # Arguments
519    ///
520    /// - `&Self` - Mutable world.
521    /// - `&str` - Object name.
522    /// - `usize` - Registered `mesh_id`.
523    /// - `Transform3D` - World transform.
524    /// - `PbrMaterial` - Surface PBR material.
525    /// - `bool` - Whether this object participates in BVH ray tracing.
526    ///
527    /// # Returns
528    ///
529    /// - `usize` - Index of the spawned `SceneObject3D`.
530    pub fn spawn_object(
531        &mut self,
532        name: &str,
533        mesh_id: usize,
534        transform: Transform3D,
535        material: PbrMaterial,
536        ray_trace_caster: bool,
537    ) -> usize {
538        let local_bounds: Aabb3D = self
539            .get_mesh_library()
540            .get(mesh_id)
541            .and_then(|c: &MeshLodChain| c.get_levels().first())
542            .map(Mesh3D::get_bounds)
543            .unwrap_or_else(|| Aabb3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
544        let world_bounds: Aabb3D = transform.transform_aabb(local_bounds);
545        let cs: f32 = self.get_chunk_size().max(8.0);
546        let pos: Vec3 = transform.get_position();
547        let chunk_coord: (i32, i32) = (
548            (pos.get_x() / cs).floor() as i32,
549            (pos.get_z() / cs).floor() as i32,
550        );
551        let idx: usize = self.get_objects().len();
552        self.get_mut_objects().push(SceneObject3D {
553            name: name.to_string(),
554            mesh_id,
555            transform,
556            material,
557            world_bounds,
558            chunk_coord,
559            ray_trace_caster,
560            spin_speed: 0.0,
561        });
562        self.set_bvh_dirty(true);
563        idx
564    }
565
566    /// Imports an external `.obj` or `.gltf` model directly into the live 3D world and returns import telemetry.
567    ///
568    /// # Arguments
569    ///
570    /// - `&Self` - Mutable world.
571    /// - `ModelFormat` - Source model format.
572    /// - `&str` - Raw `.obj` or `.gltf` text content.
573    /// - `Transform3D` - Placement transform in the 3D scene.
574    /// - `PbrMaterial` - Fallback PBR material.
575    /// - `f32` - Optional continuous Y-spin speed in radians/sec.
576    ///
577    /// # Returns
578    ///
579    /// - `Result<ImportedModel3D, String>` - Imported model summary or parse error.
580    pub fn import_model(
581        &mut self,
582        format: ModelFormat,
583        source: &str,
584        transform: Transform3D,
585        fallback_material: PbrMaterial,
586        spin_speed: f32,
587    ) -> Result<ImportedModel3D, String> {
588        let imported: ImportedModel3D = ModelImporter3D::import(format, source, fallback_material)?;
589        let model_name: String = imported.get_name().clone();
590        for (i, chain) in imported.get_meshes().iter().cloned().enumerate() {
591            let mat: PbrMaterial = chain
592                .get_levels()
593                .first()
594                .map(Mesh3D::get_material)
595                .unwrap_or(fallback_material);
596            let mid: usize = self.register_mesh(chain);
597            let obj_idx: usize =
598                self.spawn_object(&format!("{model_name}_{i}"), mid, transform, mat, true);
599            if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
600                obj.set_spin_speed(spin_speed);
601            }
602        }
603        let next_cnt: usize = self.get_imported_model_count().saturating_add(1);
604        self.set_imported_model_count(next_cnt);
605        Ok(imported)
606    }
607
608    /// Spawns an object from a fluent `SpawnObjectDesc`.
609    ///
610    /// # Arguments
611    ///
612    /// - `&Self` - Mutable world.
613    /// - `&SpawnObjectDesc` - Spawn descriptor.
614    ///
615    /// # Returns
616    ///
617    /// - `usize` - Spawned object index.
618    pub fn spawn_with(&mut self, desc: &SpawnObjectDesc) -> usize {
619        let idx: usize = self.spawn_object(
620            desc.get_name(),
621            desc.get_mesh_id(),
622            desc.get_transform(),
623            desc.get_material(),
624            desc.get_ray_trace_caster(),
625        );
626        if let Some(obj) = self.get_mut_objects().get_mut(idx) {
627            obj.set_spin_speed(desc.get_spin_speed());
628        }
629        idx
630    }
631
632    /// Imports an external `.obj` or `.gltf` model using a fluent `ImportModelDesc`.
633    ///
634    /// # Arguments
635    ///
636    /// - `&Self` - Mutable world.
637    /// - `&ImportModelDesc` - Import descriptor.
638    ///
639    /// # Returns
640    ///
641    /// - `Result<ImportedModel3D, String>` - Imported model telemetry or parse error.
642    pub fn import_with(&mut self, desc: &ImportModelDesc) -> Result<ImportedModel3D, String> {
643        self.import_model(
644            desc.get_format(),
645            desc.get_source(),
646            desc.get_transform(),
647            desc.get_fallback_material(),
648            desc.get_spin_speed(),
649        )
650    }
651
652    /// Returns the typed `CameraMode3D` currently active in this world.
653    ///
654    /// # Arguments
655    ///
656    /// - `&Self` - World reference.
657    ///
658    /// # Returns
659    ///
660    /// - `CameraMode3D` - Active typed camera controller mode.
661    #[must_use]
662    pub fn active_camera_mode(&self) -> CameraMode3D {
663        CameraMode3D::from_u8(self.get_camera_mode())
664    }
665
666    /// Sets the active 3D camera controller using a typed `CameraMode3D`.
667    ///
668    /// # Arguments
669    ///
670    /// - `&Self` - Mutable world.
671    /// - `CameraMode3D` - Desired camera controller mode.
672    pub fn set_camera_mode_enum(&mut self, mode: CameraMode3D) {
673        self.set_camera_mode(mode.as_u8());
674    }
675
676    /// Rebuilds the world-space BVH acceleration structure when geometry or transforms are dirty.
677    ///
678    /// # Arguments
679    ///
680    /// - `&Self` - Mutable world.
681    pub fn ensure_bvh(&mut self) {
682        if !self.get_bvh_dirty() {
683            return;
684        }
685        let mut tris: Vec<BvhTriangle> = Vec::new();
686        for obj in self.get_objects().iter() {
687            if !obj.get_ray_trace_caster() {
688                continue;
689            }
690            let Some(chain) = self.get_mesh_library().get(obj.get_mesh_id()) else {
691                continue;
692            };
693            let Some(mesh) = chain.get_levels().first() else {
694                continue;
695            };
696            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
697            let tr: Transform3D = obj.get_transform();
698            let mat: PbrMaterial = obj.get_material();
699            for tri in mesh.get_indices().iter() {
700                let (i0, i1, i2): (usize, usize, usize) =
701                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
702                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
703                    let p0: Vec3 = tr.transform_point(verts[i0].get_position());
704                    let p1: Vec3 = tr.transform_point(verts[i1].get_position());
705                    let p2: Vec3 = tr.transform_point(verts[i2].get_position());
706                    tris.push(BvhTriangle::from_points(p0, p1, p2, mat));
707                }
708            }
709        }
710        self.set_bvh(Bvh3D::build(tris));
711        self.set_bvh_dirty(false);
712    }
713
714    /// Returns the optional player vehicle index.
715    ///
716    /// # Arguments
717    ///
718    /// - `&Self` - World reference.
719    ///
720    /// # Returns
721    ///
722    /// - `Option<usize>` - Vehicle index in `objects`.
723    #[must_use]
724    pub fn vehicle_index(&self) -> Option<usize> {
725        let Self {
726            player_vehicle_index,
727            ..
728        } = self;
729        *player_vehicle_index
730    }
731
732    /// Builds a GTA-inspired open-world neon downtown city with reflective wet asphalt, glass towers, and a drivable sports car.
733    ///
734    /// # Returns
735    ///
736    /// - `Self` - Populated open-world 3D city ready for real-time PBR + Ray Tracing.
737    #[must_use]
738    pub fn create_open_world_city() -> Self {
739        let mut world: Self = Self::default();
740        let asphalt_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x18202C), 0.25, 0.14, 0.58)
741            .with_surface_detail(SurfaceDetailMode::RoadSurface);
742        let road_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::ground_plane(
743            "wet_asphalt_boulevard",
744            220.0,
745            220.0,
746            24,
747            asphalt_mat,
748        )));
749        let _: usize = world.spawn_object(
750            "city_ground",
751            road_mesh,
752            Transform3D::default(),
753            asphalt_mat,
754            false,
755        );
756        let stripe_mat: PbrMaterial = PbrMaterial::neon(Color::hex(0xFACC15), 1.2);
757        let stripe_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
758            "lane_stripe",
759            0.35,
760            0.05,
761            5.0,
762            true,
763            stripe_mat,
764        )));
765        for iz in -7..=7 {
766            let _: usize = world.spawn_object(
767                &format!("stripe_{iz}"),
768                stripe_mesh,
769                Transform3D::new(
770                    Vec3::new(0.0, 0.02, (iz as f32) * 14.0),
771                    0.0,
772                    Vec3::splat(1.0),
773                ),
774                stripe_mat,
775                false,
776            );
777        }
778        let tower_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
779            "city_skyscraper",
780            1.0,
781            1.0,
782            1.0,
783            true,
784            PbrMaterial::default(),
785        )));
786        let neon_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
787            "neon_sign",
788            1.0,
789            1.0,
790            1.0,
791            true,
792            PbrMaterial::neon(Color::hex(0x38BDF8), 1.8),
793        )));
794        let tower_palettes: [PbrMaterial; 4] = [
795            PbrMaterial::pbr(Color::hex(0x1E293B), 0.72, 0.16, 0.65)
796                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
797            PbrMaterial::pbr(Color::hex(0x334155), 0.55, 0.24, 0.45)
798                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
799            PbrMaterial::pbr(Color::hex(0x0F172A), 0.85, 0.10, 0.78)
800                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
801            PbrMaterial::pbr(Color::hex(0x475569), 0.40, 0.35, 0.35)
802                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
803        ];
804        let neon_colors: [Color; 4] = [
805            Color::hex(0x38BDF8),
806            Color::hex(0xF43F5E),
807            Color::hex(0xA855F7),
808            Color::hex(0x34D399),
809        ];
810        let mut idx_counter: usize = 0;
811        for side in [-1.0_f32, 1.0_f32] {
812            for row in -4..=4 {
813                let z: f32 = (row as f32) * 20.0 - 12.0;
814                let x: f32 = side * (16.5 + ((idx_counter % 3) as f32) * 3.0);
815                let h: f32 = 16.0 + ((idx_counter * 7) % 5) as f32 * 8.5;
816                let w: f32 = 9.0 + ((idx_counter % 2) as f32) * 3.0;
817                let mat: PbrMaterial = tower_palettes[idx_counter % tower_palettes.len()];
818                let _: usize = world.spawn_object(
819                    &format!("tower_{idx_counter}"),
820                    tower_unit,
821                    Transform3D::new(Vec3::new(x, 0.0, z), 0.0, Vec3::new(w, h, 11.0)),
822                    mat,
823                    true,
824                );
825                let neon_mat: PbrMaterial =
826                    PbrMaterial::neon(neon_colors[idx_counter % neon_colors.len()], 1.9);
827                let _: usize = world.spawn_object(
828                    &format!("crown_{idx_counter}"),
829                    neon_unit,
830                    Transform3D::new(
831                        Vec3::new(x - side * (w * 0.5 + 0.28), h * 0.72, z),
832                        0.0,
833                        Vec3::new(0.36, 1.4, 8.2),
834                    ),
835                    neon_mat,
836                    false,
837                );
838                idx_counter += 1;
839            }
840        }
841        let car_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0xF43F5E), 0.88, 0.12, 0.72);
842        let car_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::sports_car(
843            "hero_gt", car_mat,
844        )));
845        let car_idx: usize = world.spawn_object(
846            "player_gt_car",
847            car_mesh,
848            Transform3D::new(Vec3::new(0.0, 0.0, 6.0), 0.0, Vec3::splat(1.1)),
849            car_mat,
850            true,
851        );
852        world.set_player_vehicle_index(Some(car_idx));
853        world.set_camera(Camera3D {
854            position: Vec3::new(0.0, 6.2, 18.5),
855            yaw: -FRAC_PI_2,
856            pitch: -0.18,
857            fov_deg: 62.0,
858            near: 0.3,
859            far: 420.0,
860        });
861        world.ensure_bvh();
862        world
863    }
864
865    /// Cycles the active 3D camera perspective (`Chase` -> `Hood` -> `Orbit` -> `Aerial`) safely without clipping.
866    ///
867    /// # Arguments
868    ///
869    /// - `&Self` - Mutable world.
870    ///
871    /// # Returns
872    ///
873    /// - `u8` - New active camera mode index.
874    pub fn cycle_camera_mode(&mut self) -> u8 {
875        let next: u8 = (self.get_camera_mode() + 1) % 4;
876        self.set_camera_mode(next);
877        next
878    }
879
880    /// Tests whether a candidate horizontal AABB intersects any solid obstacle object excluding `ignore_idx`.
881    ///
882    /// # Arguments
883    ///
884    /// - `&Self` - World reference.
885    /// - `Aabb3D` - Candidate moving object bounds.
886    /// - `usize` - Self object index to skip.
887    ///
888    /// # Returns
889    ///
890    /// - `bool` - `true` when blocked by a solid building or imported model.
891    #[must_use]
892    fn collides_with_obstacles(&self, candidate: Aabb3D, ignore_idx: usize) -> bool {
893        for (idx, obj) in self.get_objects().iter().enumerate() {
894            if idx == ignore_idx || !obj.get_ray_trace_caster() {
895                continue;
896            }
897            let b: Aabb3D = obj.get_world_bounds();
898            let overlap_x: bool = candidate.get_min().get_x() < b.get_max().get_x()
899                && candidate.get_max().get_x() > b.get_min().get_x();
900            let overlap_y: bool = candidate.get_min().get_y() < b.get_max().get_y()
901                && candidate.get_max().get_y() > b.get_min().get_y();
902            let overlap_z: bool = candidate.get_min().get_z() < b.get_max().get_z()
903                && candidate.get_max().get_z() > b.get_min().get_z();
904            if overlap_x && overlap_y && overlap_z {
905                return true;
906            }
907        }
908        false
909    }
910
911    /// Advances drivable vehicle/camera controls, AABB collision resolution, and spinning models by `dt` seconds.
912    ///
913    /// # Arguments
914    ///
915    /// - `&Self` - Mutable world.
916    /// - `f32` - Delta time in seconds.
917    /// - `&InputState` - Real-time polled keyboard/pointer input.
918    /// - `&ActionMap` - Action bindings for WASD/Arrows movement.
919    pub fn step_simulation(&mut self, dt: f32, input: &InputState, actions: &ActionMap) {
920        let move_vec: Point = actions.movement_vector(input);
921        let steer: f32 = move_vec.get_x();
922        let throttle: f32 = -move_vec.get_y();
923        let mut any_moved: bool = false;
924        let car_opt: Option<usize> = self.vehicle_index();
925        if let Some(car_idx) = car_opt
926            && let Some((mut tr, mesh_id)) = self
927                .get_objects()
928                .get(car_idx)
929                .map(|car: &SceneObject3D| (car.get_transform(), car.get_mesh_id()))
930        {
931            let mesh_bounds: Aabb3D = self
932                .get_mesh_library()
933                .get(mesh_id)
934                .and_then(|c: &MeshLodChain| c.get_levels().first())
935                .map(Mesh3D::get_bounds)
936                .unwrap_or_else(|| Aabb3D::new(Vec3::splat(-2.0), Vec3::splat(2.0)));
937            if steer.abs() > 0.05 {
938                let mut rotated: Transform3D = tr;
939                rotated.set_yaw_rad(tr.get_yaw_rad() - steer * 1.85 * dt);
940                if !self.collides_with_obstacles(rotated.transform_aabb(mesh_bounds), car_idx) {
941                    tr = rotated;
942                    any_moved = true;
943                }
944            }
945            if throttle.abs() > 0.05 {
946                let fwd_x: f32 = -tr.get_yaw_rad().sin();
947                let fwd_z: f32 = -tr.get_yaw_rad().cos();
948                let speed: f32 = 24.0 * throttle * dt;
949                let cur: Vec3 = tr.get_position();
950                let cand_x: f32 = (cur.get_x() + fwd_x * speed).clamp(-9.2, 9.2);
951                let cand_z: f32 = (cur.get_z() + fwd_z * speed).clamp(-85.0, 85.0);
952                let mut try_x: Transform3D = tr;
953                try_x.set_position(Vec3::new(cand_x, 0.0, cur.get_z()));
954                if !self.collides_with_obstacles(try_x.transform_aabb(mesh_bounds), car_idx) {
955                    tr.set_position(Vec3::new(cand_x, 0.0, tr.get_position().get_z()));
956                    any_moved = true;
957                }
958                let mut try_z: Transform3D = tr;
959                try_z.set_position(Vec3::new(tr.get_position().get_x(), 0.0, cand_z));
960                if !self.collides_with_obstacles(try_z.transform_aabb(mesh_bounds), car_idx) {
961                    tr.set_position(Vec3::new(tr.get_position().get_x(), 0.0, cand_z));
962                    any_moved = true;
963                }
964            }
965            if any_moved {
966                let world_b: Aabb3D = tr.transform_aabb(mesh_bounds);
967                if let Some(car_mut) = self.get_mut_objects().get_mut(car_idx) {
968                    car_mut.set_transform(tr);
969                    car_mut.set_world_bounds(world_b);
970                }
971            }
972            let car_tr: Transform3D = self.get_objects()[car_idx].get_transform();
973            let car_pos: Vec3 = car_tr.get_position();
974            let yaw: f32 = car_tr.get_yaw_rad();
975            let cam_mode: u8 = self.get_camera_mode();
976            let (mut desired_eye, look_target): (Vec3, Vec3) = match cam_mode {
977                1 => {
978                    let eye: Vec3 = Vec3::new(
979                        car_pos.get_x() - yaw.sin() * 1.4,
980                        2.15,
981                        car_pos.get_z() - yaw.cos() * 1.4,
982                    );
983                    let tgt: Vec3 = Vec3::new(
984                        car_pos.get_x() - yaw.sin() * 18.0,
985                        1.8,
986                        car_pos.get_z() - yaw.cos() * 18.0,
987                    );
988                    (eye, tgt)
989                }
990                2 => {
991                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.45;
992                    self.set_camera_orbit_rad(orbit);
993                    let eye: Vec3 = Vec3::new(
994                        car_pos.get_x() + orbit.sin() * 10.5,
995                        5.2,
996                        car_pos.get_z() + orbit.cos() * 10.5,
997                    );
998                    (eye, Vec3::new(car_pos.get_x(), 1.6, car_pos.get_z()))
999                }
1000                3 => {
1001                    let eye: Vec3 = Vec3::new(
1002                        car_pos.get_x() + yaw.sin() * 18.0,
1003                        18.5,
1004                        car_pos.get_z() + yaw.cos() * 18.0,
1005                    );
1006                    (eye, Vec3::new(car_pos.get_x(), 1.2, car_pos.get_z()))
1007                }
1008                4 => {
1009                    let cur_cam: Camera3D = self.get_camera();
1010                    let fwd: Vec3 = cur_cam.forward();
1011                    let right: Vec3 = cur_cam.right();
1012                    let moved: Vec3 = cur_cam
1013                        .get_position()
1014                        .add(fwd.scale(throttle * 18.0 * dt))
1015                        .add(right.scale(steer * 14.0 * dt));
1016                    let eye: Vec3 = Vec3::new(moved.get_x(), moved.get_y().max(1.5), moved.get_z());
1017                    (eye, eye.add(fwd.scale(16.0)))
1018                }
1019                5 => {
1020                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.28;
1021                    self.set_camera_orbit_rad(orbit);
1022                    let eye: Vec3 = Vec3::new(
1023                        car_pos.get_x() + orbit.sin() * 7.8,
1024                        3.6 + (orbit * 1.5).sin() * 1.4,
1025                        car_pos.get_z() + orbit.cos() * 13.5,
1026                    );
1027                    (eye, Vec3::new(car_pos.get_x(), 1.8, car_pos.get_z() - 3.0))
1028                }
1029                _ => {
1030                    let eye: Vec3 = Vec3::new(
1031                        car_pos.get_x() + yaw.sin() * 12.5,
1032                        6.0,
1033                        car_pos.get_z() + yaw.cos() * 12.5,
1034                    );
1035                    let tgt: Vec3 =
1036                        Vec3::new(car_pos.get_x(), 2.2, car_pos.get_z() - yaw.cos() * 4.0);
1037                    (eye, tgt)
1038                }
1039            };
1040            desired_eye.set_x(desired_eye.get_x().clamp(-9.5, 9.5));
1041            let cam_probe: Aabb3D = Aabb3D::new(
1042                desired_eye.sub(Vec3::splat(0.6)),
1043                desired_eye.add(Vec3::splat(0.6)),
1044            );
1045            if self.collides_with_obstacles(cam_probe, car_idx) {
1046                desired_eye = Vec3::new(
1047                    car_pos.get_x(),
1048                    desired_eye.get_y().max(8.5),
1049                    car_pos.get_z() + 8.0,
1050                );
1051            }
1052            let mut cam: Camera3D = self.get_camera();
1053            let smooth: f32 = (dt * 7.0).clamp(0.05, 1.0);
1054            cam.set_position(cam.get_position().lerp(desired_eye, smooth));
1055            let look_dir: Vec3 = look_target.sub(cam.get_position()).normalize();
1056            cam.set_yaw(look_dir.get_z().atan2(look_dir.get_x()));
1057            cam.set_pitch(look_dir.get_y().clamp(-0.92, 0.92).asin());
1058            self.set_camera(cam);
1059        }
1060        for obj in self.get_mut_objects().iter_mut() {
1061            let spin: f32 = obj.get_spin_speed();
1062            if spin.abs() > 0.001 {
1063                let mut tr: Transform3D = obj.get_transform();
1064                tr.set_yaw_rad(tr.get_yaw_rad() + spin * dt);
1065                obj.set_transform(tr);
1066                any_moved = true;
1067            }
1068        }
1069        if any_moved {
1070            self.set_bvh_dirty(true);
1071        }
1072    }
1073}