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    /// Interpolates position, scale, and shortest-arc Euler angles between `self` and `other` for render-time snapshot blending.
89    ///
90    /// # Arguments
91    ///
92    /// - `Self` - Previous fixed-step transform.
93    /// - `Self` - Current fixed-step transform.
94    /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
95    ///
96    /// # Returns
97    ///
98    /// - `Self` - Shortest-arc interpolated transform.
99    #[must_use]
100    pub fn lerp_shortest_angle(self, other: Self, t: f32) -> Self {
101        let k: f32 = t.clamp(0.0, 1.0);
102        Self {
103            position: self.get_position().lerp(other.get_position(), k),
104            yaw_rad: Self::lerp_angle_rad(self.get_yaw_rad(), other.get_yaw_rad(), k),
105            pitch_rad: Self::lerp_angle_rad(self.get_pitch_rad(), other.get_pitch_rad(), k),
106            roll_rad: Self::lerp_angle_rad(self.get_roll_rad(), other.get_roll_rad(), k),
107            scale: self.get_scale().lerp(other.get_scale(), k),
108        }
109    }
110
111    /// Interpolates two angles along the shortest signed angular arc in radians.
112    ///
113    /// # Arguments
114    ///
115    /// - `f32` - Starting angle in radians.
116    /// - `f32` - Target angle in radians.
117    /// - `f32` - Clamped interpolation weight in `[0.0, 1.0]`.
118    ///
119    /// # Returns
120    ///
121    /// - `f32` - Interpolated angle in radians.
122    #[must_use]
123    fn lerp_angle_rad(a: f32, b: f32, k: f32) -> f32 {
124        let raw: f32 = (b - a).rem_euclid(TAU);
125        let delta: f32 = if raw > PI { raw - TAU } else { raw };
126        a + delta * k
127    }
128
129    /// Converts this TRS transform into a column-major `Mat4`.
130    ///
131    /// # Arguments
132    ///
133    /// - `&Self` - Transform reference.
134    ///
135    /// # Returns
136    ///
137    /// - `Mat4` - Model matrix.
138    #[must_use]
139    pub fn to_mat4(&self) -> Mat4 {
140        Mat4::from_trs_euler(
141            self.get_position(),
142            self.get_yaw_rad(),
143            self.get_pitch_rad(),
144            self.get_roll_rad(),
145            self.get_scale(),
146        )
147    }
148
149    /// Rotates vector `v` by this transform's `(yaw, pitch, roll)` Euler orientation.
150    ///
151    /// # Arguments
152    ///
153    /// - `&Self` - Transform reference.
154    /// - `Vec3` - Input vector.
155    ///
156    /// # Returns
157    ///
158    /// - `Vec3` - Rotated vector.
159    #[must_use]
160    fn rotate_vec(&self, v: Vec3) -> Vec3 {
161        let pitch: f32 = self.get_pitch_rad();
162        let roll: f32 = self.get_roll_rad();
163        let yaw: f32 = self.get_yaw_rad();
164        let (cy, sy): (f32, f32) = (yaw.cos(), yaw.sin());
165        if pitch.abs() < 1e-6 && roll.abs() < 1e-6 {
166            return Vec3::new(
167                v.get_x() * cy + v.get_z() * sy,
168                v.get_y(),
169                -v.get_x() * sy + v.get_z() * cy,
170            );
171        }
172        let (cr, sr): (f32, f32) = (roll.cos(), roll.sin());
173        let x1: f32 = v.get_x() * cr - v.get_y() * sr;
174        let y1: f32 = v.get_x() * sr + v.get_y() * cr;
175        let z1: f32 = v.get_z();
176        let (cp, sp): (f32, f32) = (pitch.cos(), pitch.sin());
177        let x2: f32 = x1;
178        let y2: f32 = y1 * cp - z1 * sp;
179        let z2: f32 = y1 * sp + z1 * cp;
180        Vec3::new(x2 * cy + z2 * sy, y2, -x2 * sy + z2 * cy)
181    }
182
183    /// Transforms a local-space 3D point into world space.
184    ///
185    /// # Arguments
186    ///
187    /// - `&Self` - Transform reference.
188    /// - `Vec3` - Local-space point.
189    ///
190    /// # Returns
191    ///
192    /// - `Vec3` - World-space point.
193    #[must_use]
194    pub fn transform_point(&self, p: Vec3) -> Vec3 {
195        let sc: Vec3 = self.get_scale();
196        let scaled: Vec3 = Vec3::new(
197            p.get_x() * sc.get_x(),
198            p.get_y() * sc.get_y(),
199            p.get_z() * sc.get_z(),
200        );
201        self.rotate_vec(scaled).add(self.get_position())
202    }
203
204    /// Rotates a local-space surface normal into world space.
205    ///
206    /// # Arguments
207    ///
208    /// - `&Self` - Transform reference.
209    /// - `Vec3` - Local normal.
210    ///
211    /// # Returns
212    ///
213    /// - `Vec3` - World-space unit normal.
214    #[must_use]
215    pub fn transform_normal(&self, n: Vec3) -> Vec3 {
216        self.rotate_vec(n).normalize()
217    }
218
219    /// Transforms a local `Aabb3D` into an enclosing world-space `Aabb3D`.
220    ///
221    /// # Arguments
222    ///
223    /// - `&Self` - Transform reference.
224    /// - `Aabb3D` - Local bounding box.
225    ///
226    /// # Returns
227    ///
228    /// - `Aabb3D` - Enclosing world-space bounding box.
229    #[must_use]
230    pub fn transform_aabb(&self, local: Aabb3D) -> Aabb3D {
231        let mn: Vec3 = local.get_min();
232        let mx: Vec3 = local.get_max();
233        let corners: [Vec3; 8] = [
234            Vec3::new(mn.get_x(), mn.get_y(), mn.get_z()),
235            Vec3::new(mx.get_x(), mn.get_y(), mn.get_z()),
236            Vec3::new(mn.get_x(), mx.get_y(), mn.get_z()),
237            Vec3::new(mx.get_x(), mx.get_y(), mn.get_z()),
238            Vec3::new(mn.get_x(), mn.get_y(), mx.get_z()),
239            Vec3::new(mx.get_x(), mn.get_y(), mx.get_z()),
240            Vec3::new(mn.get_x(), mx.get_y(), mx.get_z()),
241            Vec3::new(mx.get_x(), mx.get_y(), mx.get_z()),
242        ];
243        let mut out: Aabb3D = Aabb3D::empty();
244        for c in corners.into_iter() {
245            out.expand_point(self.transform_point(c));
246        }
247        out
248    }
249}
250
251/// Conversion helpers for `CameraMode3D`.
252impl CameraMode3D {
253    /// Converts a numeric mode index (`0..=5`) into a typed `CameraMode3D`.
254    ///
255    /// # Arguments
256    ///
257    /// - `u8` - Numeric camera mode index.
258    ///
259    /// # Returns
260    ///
261    /// - `Self` - Corresponding `CameraMode3D`.
262    #[must_use]
263    pub const fn from_u8(index: u8) -> Self {
264        match index {
265            1 => Self::Hood,
266            2 => Self::Orbit,
267            3 => Self::Aerial,
268            4 => Self::FreeFly,
269            5 => Self::CinematicDolly,
270            _ => Self::Chase,
271        }
272    }
273
274    /// Converts this `CameraMode3D` into its stable numeric index (`0..=5`).
275    ///
276    /// # Arguments
277    ///
278    /// - `Self` - Camera mode variant.
279    ///
280    /// # Returns
281    ///
282    /// - `u8` - Numeric mode index.
283    #[must_use]
284    pub const fn as_u8(self) -> u8 {
285        match self {
286            Self::Chase => 0,
287            Self::Hood => 1,
288            Self::Orbit => 2,
289            Self::Aerial => 3,
290            Self::FreeFly => 4,
291            Self::CinematicDolly => 5,
292        }
293    }
294}
295
296/// Fluent builder helpers for `SpawnObjectDesc`.
297impl SpawnObjectDesc {
298    /// Creates an object spawn descriptor with identity transform, default PBR material, and BVH ray tracing enabled.
299    ///
300    /// # Arguments
301    ///
302    /// - `&str` - Human-readable object label.
303    /// - `usize` - Registered mesh identifier.
304    ///
305    /// # Returns
306    ///
307    /// - `Self` - Ready spawn descriptor.
308    #[must_use]
309    pub fn new(name: &str, mesh_id: usize) -> Self {
310        Self {
311            name: name.to_string(),
312            mesh_id,
313            transform: Transform3D::default(),
314            material: PbrMaterial::default(),
315            ray_trace_caster: true,
316            spin_speed: 0.0,
317            is_dynamic: false,
318        }
319    }
320
321    /// Sets the world-space transform for the spawned object.
322    ///
323    /// # Arguments
324    ///
325    /// - `Self` - Base descriptor.
326    /// - `Transform3D` - World-space transform.
327    ///
328    /// # Returns
329    ///
330    /// - `Self` - Updated descriptor.
331    #[must_use]
332    pub fn with_transform(mut self, transform: Transform3D) -> Self {
333        self.set_transform(transform);
334        self
335    }
336
337    /// Sets the PBR surface material override for the spawned object.
338    ///
339    /// # Arguments
340    ///
341    /// - `Self` - Base descriptor.
342    /// - `PbrMaterial` - PBR material.
343    ///
344    /// # Returns
345    ///
346    /// - `Self` - Updated descriptor.
347    #[must_use]
348    pub fn with_material(mut self, material: PbrMaterial) -> Self {
349        self.set_material(material);
350        self
351    }
352
353    /// Sets whether this object casts BVH shadows and appears in reflections.
354    ///
355    /// # Arguments
356    ///
357    /// - `Self` - Base descriptor.
358    /// - `bool` - Ray-trace caster toggle.
359    ///
360    /// # Returns
361    ///
362    /// - `Self` - Updated descriptor.
363    #[must_use]
364    pub fn with_ray_trace(mut self, ray_trace_caster: bool) -> Self {
365        self.set_ray_trace_caster(ray_trace_caster);
366        self
367    }
368
369    /// Sets continuous Y-axis spin speed in radians per second.
370    ///
371    /// # Arguments
372    ///
373    /// - `Self` - Base descriptor.
374    /// - `f32` - Spin speed in radians/sec.
375    ///
376    /// # Returns
377    ///
378    /// - `Self` - Updated descriptor.
379    #[must_use]
380    pub fn with_spin(mut self, spin_speed: f32) -> Self {
381        self.set_spin_speed(spin_speed);
382        if spin_speed.abs() > 0.001 {
383            self.set_is_dynamic(true);
384        }
385        self
386    }
387
388    /// Explicitly marks whether this object belongs in the incrementally refitted dynamic BVH.
389    ///
390    /// # Arguments
391    ///
392    /// - `Self` - Base descriptor.
393    /// - `bool` - Dynamic caster flag.
394    ///
395    /// # Returns
396    ///
397    /// - `Self` - Updated descriptor.
398    #[must_use]
399    pub fn with_dynamic(mut self, is_dynamic: bool) -> Self {
400        self.set_is_dynamic(is_dynamic);
401        self
402    }
403}
404
405/// Fluent builder helpers for `ImportModelDesc`.
406impl ImportModelDesc {
407    /// Creates an external model import descriptor with identity transform and default PBR fallback material.
408    ///
409    /// # Arguments
410    ///
411    /// - `ModelFormat` - Interchange format (`Obj` or `GltfJson`).
412    /// - `&str` - Raw model source text.
413    ///
414    /// # Returns
415    ///
416    /// - `Self` - Ready import descriptor.
417    #[must_use]
418    pub fn new(format: ModelFormat, source: &str) -> Self {
419        Self {
420            format,
421            source: source.to_string(),
422            transform: Transform3D::default(),
423            fallback_material: PbrMaterial::default(),
424            spin_speed: 0.0,
425        }
426    }
427
428    /// Sets the placement transform for the imported model.
429    ///
430    /// # Arguments
431    ///
432    /// - `Self` - Base descriptor.
433    /// - `Transform3D` - Placement transform.
434    ///
435    /// # Returns
436    ///
437    /// - `Self` - Updated descriptor.
438    #[must_use]
439    pub fn with_transform(mut self, transform: Transform3D) -> Self {
440        self.set_transform(transform);
441        self
442    }
443
444    /// Sets the fallback PBR material when source omits material metadata.
445    ///
446    /// # Arguments
447    ///
448    /// - `Self` - Base descriptor.
449    /// - `PbrMaterial` - Fallback PBR material.
450    ///
451    /// # Returns
452    ///
453    /// - `Self` - Updated descriptor.
454    #[must_use]
455    pub fn with_material(mut self, fallback_material: PbrMaterial) -> Self {
456        self.set_fallback_material(fallback_material);
457        self
458    }
459
460    /// Sets continuous Y-axis turntable spin speed in radians per second.
461    ///
462    /// # Arguments
463    ///
464    /// - `Self` - Base descriptor.
465    /// - `f32` - Spin speed in radians/sec.
466    ///
467    /// # Returns
468    ///
469    /// - `Self` - Updated descriptor.
470    #[must_use]
471    pub fn with_spin(mut self, spin_speed: f32) -> Self {
472        self.set_spin_speed(spin_speed);
473        self
474    }
475}
476
477/// Dynamic Time-of-Day sun and atmospheric sky lighting for `DirectionalLight3D`.
478impl DirectionalLight3D {
479    /// Computes physically inspired sun direction, sun color, and sky colors for `hour` in `[0.0, 24.0]`.
480    ///
481    /// # Arguments
482    ///
483    /// - `f32` - Hour of day (`6.0` dawn, `12.0` noon, `17.5` golden sunset, `22.0` neon night).
484    ///
485    /// # Returns
486    ///
487    /// - `Self` - Updated atmospheric directional light.
488    #[must_use]
489    pub fn from_time_of_day(hour: f32) -> Self {
490        let h: f32 = hour.rem_euclid(24.0);
491        let elev_angle: f32 = ((h - 6.0) / 12.0 * PI).clamp(-0.35, 3.49);
492        let sun_y: f32 = elev_angle.sin();
493        let sun_x: f32 = elev_angle.cos();
494        let dir: Vec3 = Vec3::new(sun_x * 0.85, sun_y.max(0.18), 0.52).normalize();
495        if (7.5..=16.5).contains(&h) {
496            Self {
497                direction: dir,
498                color: Vec3::new(2.2, 2.08, 1.92),
499                sky_zenith: Vec3::new(0.14, 0.34, 0.72),
500                sky_horizon: Vec3::new(0.62, 0.78, 0.94),
501                time_of_day: h,
502            }
503        } else if (5.5..7.5).contains(&h) || (16.5..19.5).contains(&h) {
504            Self {
505                direction: dir,
506                color: Vec3::new(2.4, 1.35, 0.72),
507                sky_zenith: Vec3::new(0.15, 0.14, 0.38),
508                sky_horizon: Vec3::new(0.92, 0.45, 0.28),
509                time_of_day: h,
510            }
511        } else {
512            Self {
513                direction: Vec3::new(-0.4, 0.65, 0.55).normalize(),
514                color: Vec3::new(0.55, 0.68, 1.15),
515                sky_zenith: Vec3::new(0.02, 0.03, 0.09),
516                sky_horizon: Vec3::new(0.08, 0.11, 0.24),
517                time_of_day: h,
518            }
519        }
520    }
521}
522
523/// Default golden-sunset directional light.
524impl Default for DirectionalLight3D {
525    /// Creates a golden-hour sunset sun configuration.
526    ///
527    /// # Returns
528    ///
529    /// - `Self` - Sunset `DirectionalLight3D`.
530    fn default() -> Self {
531        Self::from_time_of_day(17.2)
532    }
533}
534
535/// Default empty 3D open world.
536impl Default for World3D {
537    /// Creates an empty `World3D` with 64m chunk streaming enabled.
538    ///
539    /// # Returns
540    ///
541    /// - `Self` - Empty `World3D`.
542    fn default() -> Self {
543        Self {
544            mesh_library: Vec::new(),
545            objects: Vec::new(),
546            camera: Camera3D::default(),
547            sun: DirectionalLight3D::default(),
548            bvh: Bvh3D::default(),
549            dynamic_bvh: Bvh3D::default(),
550            bvh_dirty: true,
551            dynamic_bvh_dirty: true,
552            dynamic_topology_dirty: true,
553            static_bvh_rebuilds: 0,
554            dynamic_bvh_refits: 0,
555            dynamic_bvh_rebuilds: 0,
556            world_revision: 1,
557            dynamic_tris_scratch: Vec::new(),
558            chunk_size: 64.0,
559            player_vehicle_index: None,
560            imported_model_count: 0,
561            camera_mode: 0,
562            camera_orbit_rad: 0.4,
563        }
564    }
565}
566
567/// Open-world construction, model importing, BVH rebuild, and live vehicle/camera simulation for `World3D`.
568impl World3D {
569    /// Registers a `MeshLodChain` in the instancing library and returns its `mesh_id`.
570    ///
571    /// # Arguments
572    ///
573    /// - `&Self` - Mutable world.
574    /// - `MeshLodChain` - Multi-level LOD mesh chain.
575    ///
576    /// # Returns
577    ///
578    /// - `usize` - Assigned `mesh_id`.
579    pub fn register_mesh(&mut self, chain: MeshLodChain) -> usize {
580        let id: usize = self.get_mesh_library().len();
581        self.get_mut_mesh_library().push(chain);
582        id
583    }
584
585    /// Spawns an instanced `SceneObject3D` referencing `mesh_id` into its spatial world chunk.
586    ///
587    /// # Arguments
588    ///
589    /// - `&Self` - Mutable world.
590    /// - `&str` - Object name.
591    /// - `usize` - Registered `mesh_id`.
592    /// - `Transform3D` - World transform.
593    /// - `PbrMaterial` - Surface PBR material.
594    /// - `bool` - Whether this object participates in BVH ray tracing.
595    ///
596    /// # Returns
597    ///
598    /// - `usize` - Index of the spawned `SceneObject3D`.
599    pub fn spawn_object(
600        &mut self,
601        name: &str,
602        mesh_id: usize,
603        transform: Transform3D,
604        material: PbrMaterial,
605        ray_trace_caster: bool,
606    ) -> usize {
607        let local_bounds: Aabb3D = self
608            .get_mesh_library()
609            .get(mesh_id)
610            .and_then(|c: &MeshLodChain| c.get_levels().first())
611            .map(Mesh3D::get_bounds)
612            .unwrap_or_else(|| Aabb3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
613        let world_bounds: Aabb3D = transform.transform_aabb(local_bounds);
614        let cs: f32 = self.get_chunk_size().max(8.0);
615        let pos: Vec3 = transform.get_position();
616        let chunk_coord: (i32, i32) = (
617            (pos.get_x() / cs).floor() as i32,
618            (pos.get_z() / cs).floor() as i32,
619        );
620        let idx: usize = self.get_objects().len();
621        self.get_mut_objects().push(SceneObject3D {
622            name: name.to_string(),
623            mesh_id,
624            transform,
625            material,
626            world_bounds,
627            chunk_coord,
628            ray_trace_caster,
629            spin_speed: 0.0,
630            is_dynamic: false,
631            teleport_epoch: 0,
632        });
633        if ray_trace_caster {
634            self.set_bvh_dirty(true);
635        }
636        self.bump_world_revision();
637        idx
638    }
639
640    /// Increments the 3D world revision counter so 3D render caches invalidate independently of UI HUD updates.
641    ///
642    /// # Arguments
643    ///
644    /// - `&Self` - Mutable world.
645    pub fn bump_world_revision(&mut self) {
646        let next: u64 = self.get_world_revision().wrapping_add(1);
647        self.set_world_revision(next);
648    }
649
650    /// Marks object `obj_idx` as static or dynamic, routing its triangles between the static BVH and incrementally refitted dynamic BVH.
651    ///
652    /// # Arguments
653    ///
654    /// - `&Self` - Mutable world.
655    /// - `usize` - Target object index in `objects`.
656    /// - `bool` - `true` for dynamic BVH routing, `false` for static BVH routing.
657    ///
658    /// # Returns
659    ///
660    /// - `bool` - `true` when `obj_idx` existed and was updated.
661    pub fn set_object_dynamic(&mut self, obj_idx: usize, is_dynamic: bool) -> bool {
662        let Some(obj) = self.get_mut_objects().get_mut(obj_idx) else {
663            return false;
664        };
665        if obj.get_is_dynamic() != is_dynamic {
666            obj.set_is_dynamic(is_dynamic);
667            if obj.get_ray_trace_caster() {
668                self.set_bvh_dirty(true);
669                self.set_dynamic_bvh_dirty(true);
670                self.set_dynamic_topology_dirty(true);
671            }
672            self.bump_world_revision();
673        }
674        true
675    }
676
677    /// Teleports object `obj_idx` to `transform`, incrementing `teleport_epoch` so snapshot interpolation snaps instead of sweeping.
678    ///
679    /// # Arguments
680    ///
681    /// - `&Self` - Mutable world.
682    /// - `usize` - Target object index in `objects`.
683    /// - `Transform3D` - Destination world transform.
684    ///
685    /// # Returns
686    ///
687    /// - `bool` - `true` when `obj_idx` existed and was teleported.
688    pub fn teleport_object(&mut self, obj_idx: usize, transform: Transform3D) -> bool {
689        let Some((mesh_id, ray_caster, is_dynamic)) =
690            self.get_objects().get(obj_idx).map(|obj: &SceneObject3D| {
691                (
692                    obj.get_mesh_id(),
693                    obj.get_ray_trace_caster(),
694                    obj.get_is_dynamic(),
695                )
696            })
697        else {
698            return false;
699        };
700        let local_bounds: Aabb3D = self
701            .get_mesh_library()
702            .get(mesh_id)
703            .and_then(|c: &MeshLodChain| c.get_levels().first())
704            .map(Mesh3D::get_bounds)
705            .unwrap_or_else(|| Aabb3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
706        let world_bounds: Aabb3D = transform.transform_aabb(local_bounds);
707        if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
708            obj.set_transform(transform);
709            obj.set_world_bounds(world_bounds);
710            let next_epoch: u32 = obj.get_teleport_epoch().wrapping_add(1);
711            obj.set_teleport_epoch(next_epoch);
712        }
713        if ray_caster {
714            if is_dynamic {
715                self.set_dynamic_bvh_dirty(true);
716            } else {
717                self.set_bvh_dirty(true);
718            }
719        }
720        self.bump_world_revision();
721        true
722    }
723
724    /// Imports an external `.obj` or `.gltf` model directly into the live 3D world and returns import telemetry.
725    ///
726    /// # Arguments
727    ///
728    /// - `&Self` - Mutable world.
729    /// - `ModelFormat` - Source model format.
730    /// - `&str` - Raw `.obj` or `.gltf` text content.
731    /// - `Transform3D` - Placement transform in the 3D scene.
732    /// - `PbrMaterial` - Fallback PBR material.
733    /// - `f32` - Optional continuous Y-spin speed in radians/sec.
734    ///
735    /// # Returns
736    ///
737    /// - `Result<ImportedModel3D, String>` - Imported model summary or parse error.
738    pub fn import_model(
739        &mut self,
740        format: ModelFormat,
741        source: &str,
742        transform: Transform3D,
743        fallback_material: PbrMaterial,
744        spin_speed: f32,
745    ) -> Result<ImportedModel3D, String> {
746        let imported: ImportedModel3D = ModelImporter3D::import(format, source, fallback_material)?;
747        let model_name: String = imported.get_name().clone();
748        for (i, chain) in imported.get_meshes().iter().cloned().enumerate() {
749            let mat: PbrMaterial = chain
750                .get_levels()
751                .first()
752                .map(Mesh3D::get_material)
753                .unwrap_or(fallback_material);
754            let mid: usize = self.register_mesh(chain);
755            let obj_idx: usize =
756                self.spawn_object(&format!("{model_name}_{i}"), mid, transform, mat, true);
757            if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
758                obj.set_spin_speed(spin_speed);
759            }
760            if spin_speed.abs() > 0.001 {
761                let _: bool = self.set_object_dynamic(obj_idx, true);
762            }
763        }
764        let next_cnt: usize = self.get_imported_model_count().saturating_add(1);
765        self.set_imported_model_count(next_cnt);
766        Ok(imported)
767    }
768
769    /// Spawns an object from a fluent `SpawnObjectDesc`.
770    ///
771    /// # Arguments
772    ///
773    /// - `&Self` - Mutable world.
774    /// - `&SpawnObjectDesc` - Spawn descriptor.
775    ///
776    /// # Returns
777    ///
778    /// - `usize` - Spawned object index.
779    pub fn spawn_with(&mut self, desc: &SpawnObjectDesc) -> usize {
780        let idx: usize = self.spawn_object(
781            desc.get_name(),
782            desc.get_mesh_id(),
783            desc.get_transform(),
784            desc.get_material(),
785            desc.get_ray_trace_caster(),
786        );
787        if let Some(obj) = self.get_mut_objects().get_mut(idx) {
788            obj.set_spin_speed(desc.get_spin_speed());
789        }
790        if desc.get_is_dynamic() || desc.get_spin_speed().abs() > 0.001 {
791            let _: bool = self.set_object_dynamic(idx, true);
792        }
793        idx
794    }
795
796    /// Imports an external `.obj` or `.gltf` model using a fluent `ImportModelDesc`.
797    ///
798    /// # Arguments
799    ///
800    /// - `&Self` - Mutable world.
801    /// - `&ImportModelDesc` - Import descriptor.
802    ///
803    /// # Returns
804    ///
805    /// - `Result<ImportedModel3D, String>` - Imported model telemetry or parse error.
806    pub fn import_with(&mut self, desc: &ImportModelDesc) -> Result<ImportedModel3D, String> {
807        self.import_model(
808            desc.get_format(),
809            desc.get_source(),
810            desc.get_transform(),
811            desc.get_fallback_material(),
812            desc.get_spin_speed(),
813        )
814    }
815
816    /// Returns the typed `CameraMode3D` currently active in this world.
817    ///
818    /// # Arguments
819    ///
820    /// - `&Self` - World reference.
821    ///
822    /// # Returns
823    ///
824    /// - `CameraMode3D` - Active typed camera controller mode.
825    #[must_use]
826    pub fn active_camera_mode(&self) -> CameraMode3D {
827        CameraMode3D::from_u8(self.get_camera_mode())
828    }
829
830    /// Sets the active 3D camera controller using a typed `CameraMode3D`.
831    ///
832    /// # Arguments
833    ///
834    /// - `&Self` - Mutable world.
835    /// - `CameraMode3D` - Desired camera controller mode.
836    pub fn set_camera_mode_enum(&mut self, mode: CameraMode3D) {
837        self.set_camera_mode(mode.as_u8());
838    }
839
840    /// Collects world-space triangles for all ray-trace casters matching `dynamic_filter` into `out_tris`.
841    ///
842    /// # Arguments
843    ///
844    /// - `&[SceneObject3D]` - World object slice.
845    /// - `&[MeshLodChain]` - Registered mesh library slice.
846    /// - `bool` - `true` to gather dynamic casters, `false` to gather static casters.
847    /// - `&mut Vec<BvhTriangle>` - Destination triangle buffer cleared and populated in place.
848    fn collect_caster_triangles(
849        objects: &[SceneObject3D],
850        mesh_library: &[MeshLodChain],
851        dynamic_filter: bool,
852        out_tris: &mut Vec<BvhTriangle>,
853    ) {
854        out_tris.clear();
855        for obj in objects.iter() {
856            if !obj.get_ray_trace_caster() || obj.get_is_dynamic() != dynamic_filter {
857                continue;
858            }
859            let Some(chain) = mesh_library.get(obj.get_mesh_id()) else {
860                continue;
861            };
862            let Some(mesh) = chain.get_levels().first() else {
863                continue;
864            };
865            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
866            let tr: Transform3D = obj.get_transform();
867            let mat: PbrMaterial = obj.get_material();
868            for tri in mesh.get_indices().iter() {
869                let (i0, i1, i2): (usize, usize, usize) =
870                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
871                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
872                    let p0: Vec3 = tr.transform_point(verts[i0].get_position());
873                    let p1: Vec3 = tr.transform_point(verts[i1].get_position());
874                    let p2: Vec3 = tr.transform_point(verts[i2].get_position());
875                    out_tris.push(BvhTriangle::from_points(p0, p1, p2, mat));
876                }
877            }
878        }
879    }
880
881    /// Synchronizes the split static and dynamic BVH acceleration structures, refitting moving dynamic casters in O(N) without rebuilding static world geometry.
882    ///
883    /// # Arguments
884    ///
885    /// - `&Self` - Mutable world.
886    pub fn ensure_bvh(&mut self) {
887        if self.get_bvh_dirty() {
888            let mut static_tris: Vec<BvhTriangle> = Vec::new();
889            Self::collect_caster_triangles(
890                self.get_objects().as_slice(),
891                self.get_mesh_library().as_slice(),
892                false,
893                &mut static_tris,
894            );
895            self.set_bvh(Bvh3D::build(static_tris));
896            self.set_bvh_dirty(false);
897            let next_static: u64 = self.get_static_bvh_rebuilds().saturating_add(1);
898            self.set_static_bvh_rebuilds(next_static);
899        }
900        if self.get_dynamic_bvh_dirty() {
901            let topology_dirty: bool = self.get_dynamic_topology_dirty();
902            let Self {
903                objects,
904                mesh_library,
905                dynamic_bvh,
906                dynamic_tris_scratch,
907                dynamic_bvh_dirty,
908                dynamic_topology_dirty,
909                dynamic_bvh_refits,
910                dynamic_bvh_rebuilds,
911                ..
912            } = self;
913            Self::collect_caster_triangles(
914                objects.as_slice(),
915                mesh_library.as_slice(),
916                true,
917                dynamic_tris_scratch,
918            );
919            if dynamic_tris_scratch.is_empty() {
920                *dynamic_bvh = Bvh3D::default();
921            } else if !topology_dirty
922                && dynamic_bvh.refit_from_source(dynamic_tris_scratch.as_slice())
923            {
924                if dynamic_bvh.needs_rebuild_after_refit(1.65) {
925                    *dynamic_bvh = Bvh3D::build(dynamic_tris_scratch.clone());
926                    *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
927                } else {
928                    *dynamic_bvh_refits = dynamic_bvh_refits.saturating_add(1);
929                }
930            } else {
931                *dynamic_bvh = Bvh3D::build(dynamic_tris_scratch.clone());
932                *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
933            }
934            *dynamic_bvh_dirty = false;
935            *dynamic_topology_dirty = false;
936        }
937    }
938
939    /// Returns the combined node count across both static and dynamic BVH acceleration trees.
940    ///
941    /// # Arguments
942    ///
943    /// - `&Self` - World reference.
944    ///
945    /// # Returns
946    ///
947    /// - `usize` - Total active BVH nodes.
948    #[must_use]
949    pub fn total_bvh_nodes(&self) -> usize {
950        self.get_bvh()
951            .get_nodes()
952            .len()
953            .saturating_add(self.get_dynamic_bvh().get_nodes().len())
954    }
955
956    /// Traces a shadow/occlusion ray across both static and dynamic BVHs using 1-triangle occluder caches.
957    ///
958    /// # Arguments
959    ///
960    /// - `(&Bvh3D, &Bvh3D)` - `(static_bvh, dynamic_bvh)` pair.
961    /// - `(Vec3, Vec3, Vec3)` - `(origin, dir, inv_dir)` ray triple.
962    /// - `(f32, f32)` - `(t_min, t_max)` distance bounds.
963    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder triangle hints.
964    ///
965    /// # Returns
966    ///
967    /// - `bool` - `true` if occluded by either static or dynamic geometry.
968    #[must_use]
969    pub fn trace_any_shadow_split(
970        bvhs: (&Bvh3D, &Bvh3D),
971        ray: (Vec3, Vec3, Vec3),
972        bounds: (f32, f32),
973        caches: (&mut u32, &mut u32),
974    ) -> bool {
975        let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
976        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
977        let (t_min, t_max): (f32, f32) = bounds;
978        let (static_cache, dynamic_cache): (&mut u32, &mut u32) = caches;
979        if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
980            return true;
981        }
982        if !dynamic_bvh.is_empty() {
983            return dynamic_bvh.trace_any_shadow_cached(
984                origin,
985                dir,
986                inv_dir,
987                t_min,
988                t_max,
989                dynamic_cache,
990            );
991        }
992        false
993    }
994
995    /// Traces a reflection/GI ray across both static and dynamic BVHs and returns `(distance, is_dynamic, tri_index)`.
996    ///
997    /// # Arguments
998    ///
999    /// - `(&Bvh3D, &Bvh3D)` - `(static_bvh, dynamic_bvh)` pair.
1000    /// - `(Vec3, Vec3, Vec3)` - `(origin, dir, inv_dir)` ray triple.
1001    /// - `(f32, f32)` - `(t_min, t_max)` distance bounds.
1002    ///
1003    /// # Returns
1004    ///
1005    /// - `Option<(f32, bool, usize)>` - Closest `(t, hit_in_dynamic_bvh, triangle_index)`.
1006    #[must_use]
1007    pub fn trace_closest_split(
1008        bvhs: (&Bvh3D, &Bvh3D),
1009        ray: (Vec3, Vec3, Vec3),
1010        bounds: (f32, f32),
1011    ) -> Option<(f32, bool, usize)> {
1012        let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
1013        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1014        let (t_min, t_max): (f32, f32) = bounds;
1015        let static_hit: Option<(f32, usize)> =
1016            static_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, t_max);
1017        let dyn_limit: f32 = static_hit.map_or(t_max, |(t, _): (f32, usize)| t);
1018        let dynamic_hit: Option<(f32, usize)> = if !dynamic_bvh.is_empty() {
1019            dynamic_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, dyn_limit)
1020        } else {
1021            None
1022        };
1023        match (static_hit, dynamic_hit) {
1024            (_, Some((dt, di))) => Some((dt, true, di)),
1025            (Some((st, si)), None) => Some((st, false, si)),
1026            (None, None) => None,
1027        }
1028    }
1029
1030    /// Returns the optional player vehicle index.
1031    ///
1032    /// # Arguments
1033    ///
1034    /// - `&Self` - World reference.
1035    ///
1036    /// # Returns
1037    ///
1038    /// - `Option<usize>` - Vehicle index in `objects`.
1039    #[must_use]
1040    pub fn vehicle_index(&self) -> Option<usize> {
1041        let Self {
1042            player_vehicle_index,
1043            ..
1044        } = self;
1045        *player_vehicle_index
1046    }
1047
1048    /// Builds a GTA-inspired open-world neon downtown city with reflective wet asphalt, glass towers, and a drivable sports car.
1049    ///
1050    /// # Returns
1051    ///
1052    /// - `Self` - Populated open-world 3D city ready for real-time PBR + Ray Tracing.
1053    #[must_use]
1054    pub fn create_open_world_city() -> Self {
1055        let mut world: Self = Self::default();
1056        let asphalt_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x18202C), 0.25, 0.14, 0.58)
1057            .with_surface_detail(SurfaceDetailMode::RoadSurface);
1058        let road_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::ground_plane(
1059            "wet_asphalt_boulevard",
1060            220.0,
1061            220.0,
1062            24,
1063            asphalt_mat,
1064        )));
1065        let _: usize = world.spawn_object(
1066            "city_ground",
1067            road_mesh,
1068            Transform3D::default(),
1069            asphalt_mat,
1070            false,
1071        );
1072        let stripe_mat: PbrMaterial = PbrMaterial::neon(Color::hex(0xFACC15), 1.2);
1073        let stripe_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
1074            "lane_stripe",
1075            0.35,
1076            0.05,
1077            5.0,
1078            true,
1079            stripe_mat,
1080        )));
1081        for iz in -7..=7 {
1082            let _: usize = world.spawn_object(
1083                &format!("stripe_{iz}"),
1084                stripe_mesh,
1085                Transform3D::new(
1086                    Vec3::new(0.0, 0.02, (iz as f32) * 14.0),
1087                    0.0,
1088                    Vec3::splat(1.0),
1089                ),
1090                stripe_mat,
1091                false,
1092            );
1093        }
1094        let tower_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
1095            "city_skyscraper",
1096            1.0,
1097            1.0,
1098            1.0,
1099            true,
1100            PbrMaterial::default(),
1101        )));
1102        let neon_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
1103            "neon_sign",
1104            1.0,
1105            1.0,
1106            1.0,
1107            true,
1108            PbrMaterial::neon(Color::hex(0x38BDF8), 1.8),
1109        )));
1110        let tower_palettes: [PbrMaterial; 4] = [
1111            PbrMaterial::pbr(Color::hex(0x1E293B), 0.72, 0.16, 0.65)
1112                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
1113            PbrMaterial::pbr(Color::hex(0x334155), 0.55, 0.24, 0.45)
1114                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
1115            PbrMaterial::pbr(Color::hex(0x0F172A), 0.85, 0.10, 0.78)
1116                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
1117            PbrMaterial::pbr(Color::hex(0x475569), 0.40, 0.35, 0.35)
1118                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
1119        ];
1120        let neon_colors: [Color; 4] = [
1121            Color::hex(0x38BDF8),
1122            Color::hex(0xF43F5E),
1123            Color::hex(0xA855F7),
1124            Color::hex(0x34D399),
1125        ];
1126        let mut idx_counter: usize = 0;
1127        for side in [-1.0_f32, 1.0_f32] {
1128            for row in -4..=4 {
1129                let z: f32 = (row as f32) * 20.0 - 12.0;
1130                let x: f32 = side * (16.5 + ((idx_counter % 3) as f32) * 3.0);
1131                let h: f32 = 16.0 + ((idx_counter * 7) % 5) as f32 * 8.5;
1132                let w: f32 = 9.0 + ((idx_counter % 2) as f32) * 3.0;
1133                let mat: PbrMaterial = tower_palettes[idx_counter % tower_palettes.len()];
1134                let _: usize = world.spawn_object(
1135                    &format!("tower_{idx_counter}"),
1136                    tower_unit,
1137                    Transform3D::new(Vec3::new(x, 0.0, z), 0.0, Vec3::new(w, h, 11.0)),
1138                    mat,
1139                    true,
1140                );
1141                let neon_mat: PbrMaterial =
1142                    PbrMaterial::neon(neon_colors[idx_counter % neon_colors.len()], 1.9);
1143                let _: usize = world.spawn_object(
1144                    &format!("crown_{idx_counter}"),
1145                    neon_unit,
1146                    Transform3D::new(
1147                        Vec3::new(x - side * (w * 0.5 + 0.28), h * 0.72, z),
1148                        0.0,
1149                        Vec3::new(0.36, 1.4, 8.2),
1150                    ),
1151                    neon_mat,
1152                    false,
1153                );
1154                idx_counter += 1;
1155            }
1156        }
1157        let car_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0xF43F5E), 0.88, 0.12, 0.72);
1158        let car_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::sports_car(
1159            "hero_gt", car_mat,
1160        )));
1161        let car_idx: usize = world.spawn_object(
1162            "player_gt_car",
1163            car_mesh,
1164            Transform3D::new(Vec3::new(0.0, 0.0, 6.0), 0.0, Vec3::splat(1.1)),
1165            car_mat,
1166            true,
1167        );
1168        let _: bool = world.set_object_dynamic(car_idx, true);
1169        world.set_player_vehicle_index(Some(car_idx));
1170        world.set_camera(Camera3D {
1171            position: Vec3::new(0.0, 6.2, 18.5),
1172            yaw: -FRAC_PI_2,
1173            pitch: -0.18,
1174            fov_deg: 62.0,
1175            near: 0.3,
1176            far: 420.0,
1177        });
1178        world.ensure_bvh();
1179        world
1180    }
1181
1182    /// Cycles the active 3D camera perspective (`Chase` -> `Hood` -> `Orbit` -> `Aerial`) safely without clipping.
1183    ///
1184    /// # Arguments
1185    ///
1186    /// - `&Self` - Mutable world.
1187    ///
1188    /// # Returns
1189    ///
1190    /// - `u8` - New active camera mode index.
1191    pub fn cycle_camera_mode(&mut self) -> u8 {
1192        let next: u8 = (self.get_camera_mode() + 1) % 4;
1193        self.set_camera_mode(next);
1194        next
1195    }
1196
1197    /// Tests whether a candidate horizontal AABB intersects any solid obstacle object excluding `ignore_idx`.
1198    ///
1199    /// # Arguments
1200    ///
1201    /// - `&Self` - World reference.
1202    /// - `Aabb3D` - Candidate moving object bounds.
1203    /// - `usize` - Self object index to skip.
1204    ///
1205    /// # Returns
1206    ///
1207    /// - `bool` - `true` when blocked by a solid building or imported model.
1208    #[must_use]
1209    fn collides_with_obstacles(&self, candidate: Aabb3D, ignore_idx: usize) -> bool {
1210        for (idx, obj) in self.get_objects().iter().enumerate() {
1211            if idx == ignore_idx || !obj.get_ray_trace_caster() {
1212                continue;
1213            }
1214            let b: Aabb3D = obj.get_world_bounds();
1215            let overlap_x: bool = candidate.get_min().get_x() < b.get_max().get_x()
1216                && candidate.get_max().get_x() > b.get_min().get_x();
1217            let overlap_y: bool = candidate.get_min().get_y() < b.get_max().get_y()
1218                && candidate.get_max().get_y() > b.get_min().get_y();
1219            let overlap_z: bool = candidate.get_min().get_z() < b.get_max().get_z()
1220                && candidate.get_max().get_z() > b.get_min().get_z();
1221            if overlap_x && overlap_y && overlap_z {
1222                return true;
1223            }
1224        }
1225        false
1226    }
1227
1228    /// Advances drivable vehicle/camera controls, AABB collision resolution, and spinning models by `dt` seconds.
1229    ///
1230    /// # Arguments
1231    ///
1232    /// - `&Self` - Mutable world.
1233    /// - `f32` - Delta time in seconds.
1234    /// - `&InputState` - Real-time polled keyboard/pointer input.
1235    /// - `&ActionMap` - Action bindings for WASD/Arrows movement.
1236    pub fn step_simulation(&mut self, dt: f32, input: &InputState, actions: &ActionMap) {
1237        let move_vec: Point = actions.movement_vector(input);
1238        let steer: f32 = move_vec.get_x();
1239        let throttle: f32 = -move_vec.get_y();
1240        let mut any_dynamic_moved: bool = false;
1241        let mut any_static_moved: bool = false;
1242        let car_opt: Option<usize> = self.vehicle_index();
1243        if let Some(car_idx) = car_opt
1244            && let Some((mut tr, mesh_id, car_is_dynamic)) =
1245                self.get_objects().get(car_idx).map(|car: &SceneObject3D| {
1246                    (car.get_transform(), car.get_mesh_id(), car.get_is_dynamic())
1247                })
1248        {
1249            let mut car_moved: bool = false;
1250            let mesh_bounds: Aabb3D = self
1251                .get_mesh_library()
1252                .get(mesh_id)
1253                .and_then(|c: &MeshLodChain| c.get_levels().first())
1254                .map(Mesh3D::get_bounds)
1255                .unwrap_or_else(|| Aabb3D::new(Vec3::splat(-2.0), Vec3::splat(2.0)));
1256            if steer.abs() > 0.05 {
1257                let mut rotated: Transform3D = tr;
1258                rotated.set_yaw_rad(tr.get_yaw_rad() - steer * 1.85 * dt);
1259                if !self.collides_with_obstacles(rotated.transform_aabb(mesh_bounds), car_idx) {
1260                    tr = rotated;
1261                    car_moved = true;
1262                }
1263            }
1264            if throttle.abs() > 0.05 {
1265                let fwd_x: f32 = -tr.get_yaw_rad().sin();
1266                let fwd_z: f32 = -tr.get_yaw_rad().cos();
1267                let speed: f32 = 24.0 * throttle * dt;
1268                let cur: Vec3 = tr.get_position();
1269                let cand_x: f32 = (cur.get_x() + fwd_x * speed).clamp(-9.2, 9.2);
1270                let cand_z: f32 = (cur.get_z() + fwd_z * speed).clamp(-85.0, 85.0);
1271                let mut try_x: Transform3D = tr;
1272                try_x.set_position(Vec3::new(cand_x, 0.0, cur.get_z()));
1273                if !self.collides_with_obstacles(try_x.transform_aabb(mesh_bounds), car_idx) {
1274                    tr.set_position(Vec3::new(cand_x, 0.0, tr.get_position().get_z()));
1275                    car_moved = true;
1276                }
1277                let mut try_z: Transform3D = tr;
1278                try_z.set_position(Vec3::new(tr.get_position().get_x(), 0.0, cand_z));
1279                if !self.collides_with_obstacles(try_z.transform_aabb(mesh_bounds), car_idx) {
1280                    tr.set_position(Vec3::new(tr.get_position().get_x(), 0.0, cand_z));
1281                    car_moved = true;
1282                }
1283            }
1284            if car_moved {
1285                let world_b: Aabb3D = tr.transform_aabb(mesh_bounds);
1286                if let Some(car_mut) = self.get_mut_objects().get_mut(car_idx) {
1287                    car_mut.set_transform(tr);
1288                    car_mut.set_world_bounds(world_b);
1289                }
1290                if car_is_dynamic {
1291                    any_dynamic_moved = true;
1292                } else {
1293                    any_static_moved = true;
1294                }
1295            }
1296            let car_tr: Transform3D = self.get_objects()[car_idx].get_transform();
1297            let car_pos: Vec3 = car_tr.get_position();
1298            let yaw: f32 = car_tr.get_yaw_rad();
1299            let cam_mode: u8 = self.get_camera_mode();
1300            let (mut desired_eye, look_target): (Vec3, Vec3) = match cam_mode {
1301                1 => {
1302                    let eye: Vec3 = Vec3::new(
1303                        car_pos.get_x() - yaw.sin() * 1.4,
1304                        2.15,
1305                        car_pos.get_z() - yaw.cos() * 1.4,
1306                    );
1307                    let tgt: Vec3 = Vec3::new(
1308                        car_pos.get_x() - yaw.sin() * 18.0,
1309                        1.8,
1310                        car_pos.get_z() - yaw.cos() * 18.0,
1311                    );
1312                    (eye, tgt)
1313                }
1314                2 => {
1315                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.45;
1316                    self.set_camera_orbit_rad(orbit);
1317                    let eye: Vec3 = Vec3::new(
1318                        car_pos.get_x() + orbit.sin() * 10.5,
1319                        5.2,
1320                        car_pos.get_z() + orbit.cos() * 10.5,
1321                    );
1322                    (eye, Vec3::new(car_pos.get_x(), 1.6, car_pos.get_z()))
1323                }
1324                3 => {
1325                    let eye: Vec3 = Vec3::new(
1326                        car_pos.get_x() + yaw.sin() * 18.0,
1327                        18.5,
1328                        car_pos.get_z() + yaw.cos() * 18.0,
1329                    );
1330                    (eye, Vec3::new(car_pos.get_x(), 1.2, car_pos.get_z()))
1331                }
1332                4 => {
1333                    let cur_cam: Camera3D = self.get_camera();
1334                    let fwd: Vec3 = cur_cam.forward();
1335                    let right: Vec3 = cur_cam.right();
1336                    let moved: Vec3 = cur_cam
1337                        .get_position()
1338                        .add(fwd.scale(throttle * 18.0 * dt))
1339                        .add(right.scale(steer * 14.0 * dt));
1340                    let eye: Vec3 = Vec3::new(moved.get_x(), moved.get_y().max(1.5), moved.get_z());
1341                    (eye, eye.add(fwd.scale(16.0)))
1342                }
1343                5 => {
1344                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.28;
1345                    self.set_camera_orbit_rad(orbit);
1346                    let eye: Vec3 = Vec3::new(
1347                        car_pos.get_x() + orbit.sin() * 7.8,
1348                        3.6 + (orbit * 1.5).sin() * 1.4,
1349                        car_pos.get_z() + orbit.cos() * 13.5,
1350                    );
1351                    (eye, Vec3::new(car_pos.get_x(), 1.8, car_pos.get_z() - 3.0))
1352                }
1353                _ => {
1354                    let eye: Vec3 = Vec3::new(
1355                        car_pos.get_x() + yaw.sin() * 12.5,
1356                        6.0,
1357                        car_pos.get_z() + yaw.cos() * 12.5,
1358                    );
1359                    let tgt: Vec3 =
1360                        Vec3::new(car_pos.get_x(), 2.2, car_pos.get_z() - yaw.cos() * 4.0);
1361                    (eye, tgt)
1362                }
1363            };
1364            desired_eye.set_x(desired_eye.get_x().clamp(-9.5, 9.5));
1365            let cam_probe: Aabb3D = Aabb3D::new(
1366                desired_eye.sub(Vec3::splat(0.6)),
1367                desired_eye.add(Vec3::splat(0.6)),
1368            );
1369            if self.collides_with_obstacles(cam_probe, car_idx) {
1370                desired_eye = Vec3::new(
1371                    car_pos.get_x(),
1372                    desired_eye.get_y().max(8.5),
1373                    car_pos.get_z() + 8.0,
1374                );
1375            }
1376            let prev_cam: Camera3D = self.get_camera();
1377            let mut cam: Camera3D = prev_cam;
1378            let smooth: f32 = (dt * 7.0).clamp(0.05, 1.0);
1379            cam.set_position(cam.get_position().lerp(desired_eye, smooth));
1380            let look_dir: Vec3 = look_target.sub(cam.get_position()).normalize();
1381            cam.set_yaw(look_dir.get_z().atan2(look_dir.get_x()));
1382            cam.set_pitch(look_dir.get_y().clamp(-0.92, 0.92).asin());
1383            self.set_camera(cam);
1384            if cam != prev_cam {
1385                self.bump_world_revision();
1386            }
1387        }
1388        for obj in self.get_mut_objects().iter_mut() {
1389            let spin: f32 = obj.get_spin_speed();
1390            if spin.abs() > 0.001 {
1391                let mut tr: Transform3D = obj.get_transform();
1392                tr.set_yaw_rad(tr.get_yaw_rad() + spin * dt);
1393                obj.set_transform(tr);
1394                if obj.get_is_dynamic() {
1395                    any_dynamic_moved = true;
1396                } else {
1397                    any_static_moved = true;
1398                }
1399            }
1400        }
1401        if any_static_moved {
1402            self.set_bvh_dirty(true);
1403        }
1404        if any_dynamic_moved {
1405            self.set_dynamic_bvh_dirty(true);
1406        }
1407        if any_static_moved || any_dynamic_moved {
1408            self.bump_world_revision();
1409        }
1410    }
1411}