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 diff: f32 = b - a;
125        let raw: f32 = diff - (diff / TAU).floor() * TAU;
126        let delta: f32 = if raw > PI { raw - TAU } else { raw };
127        a + delta * k
128    }
129
130    /// Converts this TRS transform into a column-major `Mat4`.
131    ///
132    /// # Arguments
133    ///
134    /// - `&Self` - Transform reference.
135    ///
136    /// # Returns
137    ///
138    /// - `Mat4` - Model matrix.
139    #[must_use]
140    pub fn to_mat4(&self) -> Mat4 {
141        Mat4::from_trs_euler(
142            self.get_position(),
143            self.get_yaw_rad(),
144            self.get_pitch_rad(),
145            self.get_roll_rad(),
146            self.get_scale(),
147        )
148    }
149
150    /// Computes the exact analytical inverse TRS matrix (`S^-1 * R^T * T^-1`) for object-space raytracing.
151    ///
152    /// # Arguments
153    ///
154    /// - `&Self` - Transform reference.
155    ///
156    /// # Returns
157    ///
158    /// - `Mat4` - Inverse model matrix mapping world space back to local object space.
159    #[must_use]
160    pub fn to_inv_mat4(&self) -> Mat4 {
161        Mat4::inverse_trs_euler(
162            self.get_position(),
163            self.get_yaw_rad(),
164            self.get_pitch_rad(),
165            self.get_roll_rad(),
166            self.get_scale(),
167        )
168    }
169
170    /// Precomputes the inverse-transpose 3x3 normal basis `[col_x, col_y, col_z]` once per object.
171    ///
172    /// # Arguments
173    ///
174    /// - `&Self` - Transform reference.
175    ///
176    /// # Returns
177    ///
178    /// - `[Vec3; 3]` - Inverse-transpose 3x3 normal basis columns.
179    #[must_use]
180    pub fn normal_mat3(&self) -> [Vec3; 3] {
181        Mat4::normal_basis_from_euler_scale(
182            self.get_yaw_rad(),
183            self.get_pitch_rad(),
184            self.get_roll_rad(),
185            self.get_scale(),
186        )
187    }
188
189    /// Rotates vector `v` by this transform's `(yaw, pitch, roll)` Euler orientation.
190    ///
191    /// # Arguments
192    ///
193    /// - `&Self` - Transform reference.
194    /// - `Vec3` - Input vector.
195    ///
196    /// # Returns
197    ///
198    /// - `Vec3` - Rotated vector.
199    #[must_use]
200    fn rotate_vec(&self, v: Vec3) -> Vec3 {
201        let pitch: f32 = self.get_pitch_rad();
202        let roll: f32 = self.get_roll_rad();
203        let yaw: f32 = self.get_yaw_rad();
204        let (cy, sy): (f32, f32) = (yaw.cos(), yaw.sin());
205        if pitch.abs() < 1e-6 && roll.abs() < 1e-6 {
206            return Vec3::new(
207                v.get_x() * cy + v.get_z() * sy,
208                v.get_y(),
209                -v.get_x() * sy + v.get_z() * cy,
210            );
211        }
212        let (cr, sr): (f32, f32) = (roll.cos(), roll.sin());
213        let x1: f32 = v.get_x() * cr - v.get_y() * sr;
214        let y1: f32 = v.get_x() * sr + v.get_y() * cr;
215        let z1: f32 = v.get_z();
216        let (cp, sp): (f32, f32) = (pitch.cos(), pitch.sin());
217        let x2: f32 = x1;
218        let y2: f32 = y1 * cp - z1 * sp;
219        let z2: f32 = y1 * sp + z1 * cp;
220        Vec3::new(x2 * cy + z2 * sy, y2, -x2 * sy + z2 * cy)
221    }
222
223    /// Transforms a local-space 3D point into world space.
224    ///
225    /// # Arguments
226    ///
227    /// - `&Self` - Transform reference.
228    /// - `Vec3` - Local-space point.
229    ///
230    /// # Returns
231    ///
232    /// - `Vec3` - World-space point.
233    #[must_use]
234    pub fn transform_point(&self, p: Vec3) -> Vec3 {
235        let sc: Vec3 = self.get_scale();
236        let scaled: Vec3 = Vec3::new(
237            p.get_x() * sc.get_x(),
238            p.get_y() * sc.get_y(),
239            p.get_z() * sc.get_z(),
240        );
241        self.rotate_vec(scaled).add(self.get_position())
242    }
243
244    /// Rotates a local-space surface normal into world space.
245    ///
246    /// # Arguments
247    ///
248    /// - `&Self` - Transform reference.
249    /// - `Vec3` - Local normal.
250    ///
251    /// # Returns
252    ///
253    /// - `Vec3` - World-space unit normal.
254    #[must_use]
255    pub fn transform_normal(&self, n: Vec3) -> Vec3 {
256        self.rotate_vec(n).normalize()
257    }
258
259    /// Transforms a local `Aabb3D` into an enclosing world-space `Aabb3D` using Arvo's 18-multiply method (zero 8-corner loop, zero per-corner trigonometry).
260    ///
261    /// # Arguments
262    ///
263    /// - `&Self` - Transform reference.
264    /// - `Aabb3D` - Local bounding box.
265    ///
266    /// # Returns
267    ///
268    /// - `Aabb3D` - Enclosing world-space bounding box.
269    #[must_use]
270    pub fn transform_aabb(&self, local: Aabb3D) -> Aabb3D {
271        self.to_mat4().transform_aabb(local)
272    }
273}
274
275/// Conversion helpers for `CameraMode3D`.
276impl CameraMode3D {
277    /// Converts a numeric mode index (`0..=5`) into a typed `CameraMode3D`.
278    ///
279    /// # Arguments
280    ///
281    /// - `u8` - Numeric camera mode index.
282    ///
283    /// # Returns
284    ///
285    /// - `Self` - Corresponding `CameraMode3D`.
286    #[must_use]
287    pub const fn from_u8(index: u8) -> Self {
288        match index {
289            1 => Self::Hood,
290            2 => Self::Orbit,
291            3 => Self::Aerial,
292            4 => Self::FreeFly,
293            5 => Self::CinematicDolly,
294            _ => Self::Chase,
295        }
296    }
297
298    /// Converts this `CameraMode3D` into its stable numeric index (`0..=5`).
299    ///
300    /// # Arguments
301    ///
302    /// - `Self` - Camera mode variant.
303    ///
304    /// # Returns
305    ///
306    /// - `u8` - Numeric mode index.
307    #[must_use]
308    pub const fn as_u8(self) -> u8 {
309        match self {
310            Self::Chase => 0,
311            Self::Hood => 1,
312            Self::Orbit => 2,
313            Self::Aerial => 3,
314            Self::FreeFly => 4,
315            Self::CinematicDolly => 5,
316        }
317    }
318}
319
320/// Fluent builder helpers for `SpawnObjectDesc`.
321impl SpawnObjectDesc {
322    /// Creates an object spawn descriptor with identity transform, default PBR material, and BVH ray tracing enabled.
323    ///
324    /// # Arguments
325    ///
326    /// - `&str` - Human-readable object label.
327    /// - `usize` - Registered mesh identifier.
328    ///
329    /// # Returns
330    ///
331    /// - `Self` - Ready spawn descriptor.
332    #[must_use]
333    pub fn new(name: &str, mesh_id: usize) -> Self {
334        Self {
335            name: name.to_string(),
336            mesh_id,
337            transform: Transform3D::default(),
338            material: PbrMaterial::default(),
339            ray_trace_caster: true,
340            spin_speed: 0.0,
341            is_dynamic: false,
342        }
343    }
344
345    /// Sets the world-space transform for the spawned object.
346    ///
347    /// # Arguments
348    ///
349    /// - `Self` - Base descriptor.
350    /// - `Transform3D` - World-space transform.
351    ///
352    /// # Returns
353    ///
354    /// - `Self` - Updated descriptor.
355    #[must_use]
356    pub fn with_transform(mut self, transform: Transform3D) -> Self {
357        self.set_transform(transform);
358        self
359    }
360
361    /// Sets the PBR surface material override for the spawned object.
362    ///
363    /// # Arguments
364    ///
365    /// - `Self` - Base descriptor.
366    /// - `PbrMaterial` - PBR material.
367    ///
368    /// # Returns
369    ///
370    /// - `Self` - Updated descriptor.
371    #[must_use]
372    pub fn with_material(mut self, material: PbrMaterial) -> Self {
373        self.set_material(material);
374        self
375    }
376
377    /// Sets whether this object casts BVH shadows and appears in reflections.
378    ///
379    /// # Arguments
380    ///
381    /// - `Self` - Base descriptor.
382    /// - `bool` - Ray-trace caster toggle.
383    ///
384    /// # Returns
385    ///
386    /// - `Self` - Updated descriptor.
387    #[must_use]
388    pub fn with_ray_trace(mut self, ray_trace_caster: bool) -> Self {
389        self.set_ray_trace_caster(ray_trace_caster);
390        self
391    }
392
393    /// Sets continuous Y-axis spin speed in radians per second.
394    ///
395    /// # Arguments
396    ///
397    /// - `Self` - Base descriptor.
398    /// - `f32` - Spin speed in radians/sec.
399    ///
400    /// # Returns
401    ///
402    /// - `Self` - Updated descriptor.
403    #[must_use]
404    pub fn with_spin(mut self, spin_speed: f32) -> Self {
405        self.set_spin_speed(spin_speed);
406        if spin_speed.abs() > 0.001 {
407            self.set_is_dynamic(true);
408        }
409        self
410    }
411
412    /// Explicitly marks whether this object belongs in the incrementally refitted dynamic BVH.
413    ///
414    /// # Arguments
415    ///
416    /// - `Self` - Base descriptor.
417    /// - `bool` - Dynamic caster flag.
418    ///
419    /// # Returns
420    ///
421    /// - `Self` - Updated descriptor.
422    #[must_use]
423    pub fn with_dynamic(mut self, is_dynamic: bool) -> Self {
424        self.set_is_dynamic(is_dynamic);
425        self
426    }
427}
428
429/// Fluent builder helpers for `ImportModelDesc`.
430impl ImportModelDesc {
431    /// Creates an external model import descriptor with identity transform and default PBR fallback material.
432    ///
433    /// # Arguments
434    ///
435    /// - `ModelFormat` - Interchange format (`Obj` or `GltfJson`).
436    /// - `&str` - Raw model source text.
437    ///
438    /// # Returns
439    ///
440    /// - `Self` - Ready import descriptor.
441    #[must_use]
442    pub fn new(format: ModelFormat, source: &str) -> Self {
443        Self {
444            format,
445            source: source.to_string(),
446            transform: Transform3D::default(),
447            fallback_material: PbrMaterial::default(),
448            spin_speed: 0.0,
449        }
450    }
451
452    /// Sets the placement transform for the imported model.
453    ///
454    /// # Arguments
455    ///
456    /// - `Self` - Base descriptor.
457    /// - `Transform3D` - Placement transform.
458    ///
459    /// # Returns
460    ///
461    /// - `Self` - Updated descriptor.
462    #[must_use]
463    pub fn with_transform(mut self, transform: Transform3D) -> Self {
464        self.set_transform(transform);
465        self
466    }
467
468    /// Sets the fallback PBR material when source omits material metadata.
469    ///
470    /// # Arguments
471    ///
472    /// - `Self` - Base descriptor.
473    /// - `PbrMaterial` - Fallback PBR material.
474    ///
475    /// # Returns
476    ///
477    /// - `Self` - Updated descriptor.
478    #[must_use]
479    pub fn with_material(mut self, fallback_material: PbrMaterial) -> Self {
480        self.set_fallback_material(fallback_material);
481        self
482    }
483
484    /// Sets continuous Y-axis turntable spin speed in radians per second.
485    ///
486    /// # Arguments
487    ///
488    /// - `Self` - Base descriptor.
489    /// - `f32` - Spin speed in radians/sec.
490    ///
491    /// # Returns
492    ///
493    /// - `Self` - Updated descriptor.
494    #[must_use]
495    pub fn with_spin(mut self, spin_speed: f32) -> Self {
496        self.set_spin_speed(spin_speed);
497        self
498    }
499}
500
501/// Dynamic Time-of-Day sun and atmospheric sky lighting for `DirectionalLight3D`.
502impl DirectionalLight3D {
503    /// Computes physically inspired sun direction, sun color, and sky colors for `hour` in `[0.0, 24.0]`.
504    ///
505    /// # Arguments
506    ///
507    /// - `f32` - Hour of day (`6.0` dawn, `12.0` noon, `17.5` golden sunset, `22.0` neon night).
508    ///
509    /// # Returns
510    ///
511    /// - `Self` - Updated atmospheric directional light.
512    #[must_use]
513    pub fn from_time_of_day(hour: f32) -> Self {
514        let h: f32 = hour.rem_euclid(24.0);
515        let elev_angle: f32 = ((h - 6.0) / 12.0 * PI).clamp(-0.35, 3.49);
516        let sun_y: f32 = elev_angle.sin();
517        let sun_x: f32 = elev_angle.cos();
518        let dir: Vec3 = Vec3::new(sun_x * 0.85, sun_y.max(0.18), 0.52).normalize();
519        if (7.5..=16.5).contains(&h) {
520            Self {
521                direction: dir,
522                color: Vec3::new(2.2, 2.08, 1.92),
523                sky_zenith: Vec3::new(0.14, 0.34, 0.72),
524                sky_horizon: Vec3::new(0.62, 0.78, 0.94),
525                time_of_day: h,
526            }
527        } else if (5.5..7.5).contains(&h) || (16.5..19.5).contains(&h) {
528            Self {
529                direction: dir,
530                color: Vec3::new(2.4, 1.35, 0.72),
531                sky_zenith: Vec3::new(0.15, 0.14, 0.38),
532                sky_horizon: Vec3::new(0.92, 0.45, 0.28),
533                time_of_day: h,
534            }
535        } else {
536            Self {
537                direction: Vec3::new(-0.4, 0.65, 0.55).normalize(),
538                color: Vec3::new(0.55, 0.68, 1.15),
539                sky_zenith: Vec3::new(0.02, 0.03, 0.09),
540                sky_horizon: Vec3::new(0.08, 0.11, 0.24),
541                time_of_day: h,
542            }
543        }
544    }
545}
546
547/// Default golden-sunset directional light.
548impl Default for DirectionalLight3D {
549    /// Creates a golden-hour sunset sun configuration.
550    ///
551    /// # Returns
552    ///
553    /// - `Self` - Sunset `DirectionalLight3D`.
554    fn default() -> Self {
555        Self::from_time_of_day(17.2)
556    }
557}
558
559/// Default empty 3D open world.
560impl Default for World3D {
561    /// Creates an empty `World3D` with 64m chunk streaming enabled.
562    ///
563    /// # Returns
564    ///
565    /// - `Self` - Empty `World3D`.
566    fn default() -> Self {
567        Self {
568            mesh_library: Vec::new(),
569            objects: Vec::new(),
570            camera: Camera3D::default(),
571            sun: DirectionalLight3D::default(),
572            bvh: Bvh3D::default(),
573            dynamic_bvh: Bvh3D::default(),
574            mesh_local_bvhs: Vec::new(),
575            dynamic_instances: Vec::new(),
576            bvh_dirty: true,
577            dynamic_bvh_dirty: true,
578            dynamic_topology_dirty: true,
579            static_bvh_rebuilds: 0,
580            dynamic_bvh_refits: 0,
581            dynamic_bvh_rebuilds: 0,
582            world_revision: 1,
583            dynamic_tris_scratch: Vec::new(),
584            chunk_size: 64.0,
585            player_vehicle_index: None,
586            imported_model_count: 0,
587            camera_mode: 0,
588            camera_orbit_rad: 0.4,
589        }
590    }
591}
592
593/// Open-world construction, model importing, BVH rebuild, and live vehicle/camera simulation for `World3D`.
594impl World3D {
595    /// Registers a `MeshLodChain` in the instancing library and returns its `mesh_id`.
596    ///
597    /// # Arguments
598    ///
599    /// - `&Self` - Mutable world.
600    /// - `MeshLodChain` - Multi-level LOD mesh chain.
601    ///
602    /// # Returns
603    ///
604    /// - `usize` - Assigned `mesh_id`.
605    pub fn register_mesh(&mut self, chain: MeshLodChain) -> usize {
606        let id: usize = self.get_mesh_library().len();
607        self.get_mut_mesh_library().push(chain);
608        id
609    }
610
611    /// Spawns an instanced `SceneObject3D` referencing `mesh_id` into its spatial world chunk.
612    ///
613    /// # Arguments
614    ///
615    /// - `&Self` - Mutable world.
616    /// - `&str` - Object name.
617    /// - `usize` - Registered `mesh_id`.
618    /// - `Transform3D` - World transform.
619    /// - `PbrMaterial` - Surface PBR material.
620    /// - `bool` - Whether this object participates in BVH ray tracing.
621    ///
622    /// # Returns
623    ///
624    /// - `usize` - Index of the spawned `SceneObject3D`.
625    pub fn spawn_object(
626        &mut self,
627        name: &str,
628        mesh_id: usize,
629        transform: Transform3D,
630        material: PbrMaterial,
631        ray_trace_caster: bool,
632    ) -> usize {
633        let local_bounds: Aabb3D = self
634            .get_mesh_library()
635            .get(mesh_id)
636            .and_then(|c: &MeshLodChain| c.get_levels().first())
637            .map(Mesh3D::get_bounds)
638            .unwrap_or_else(|| Aabb3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
639        let world_bounds: Aabb3D = transform.transform_aabb(local_bounds);
640        let cs: f32 = self.get_chunk_size().max(8.0);
641        let pos: Vec3 = transform.get_position();
642        let chunk_coord: (i32, i32) = (
643            (pos.get_x() / cs).floor() as i32,
644            (pos.get_z() / cs).floor() as i32,
645        );
646        let idx: usize = self.get_objects().len();
647        self.get_mut_objects().push(SceneObject3D {
648            name: name.to_string(),
649            mesh_id,
650            transform,
651            material,
652            world_bounds,
653            chunk_coord,
654            ray_trace_caster,
655            spin_speed: 0.0,
656            is_dynamic: false,
657            teleport_epoch: 0,
658        });
659        if ray_trace_caster {
660            self.set_bvh_dirty(true);
661        }
662        self.bump_world_revision();
663        idx
664    }
665
666    /// Increments the 3D world revision counter so 3D render caches invalidate independently of UI HUD updates.
667    ///
668    /// # Arguments
669    ///
670    /// - `&Self` - Mutable world.
671    pub fn bump_world_revision(&mut self) {
672        let next: u64 = self.get_world_revision().wrapping_add(1);
673        self.set_world_revision(next);
674    }
675
676    /// Marks object `obj_idx` as static or dynamic, routing its triangles between the static BVH and incrementally refitted dynamic BVH.
677    ///
678    /// # Arguments
679    ///
680    /// - `&Self` - Mutable world.
681    /// - `usize` - Target object index in `objects`.
682    /// - `bool` - `true` for dynamic BVH routing, `false` for static BVH routing.
683    ///
684    /// # Returns
685    ///
686    /// - `bool` - `true` when `obj_idx` existed and was updated.
687    pub fn set_object_dynamic(&mut self, obj_idx: usize, is_dynamic: bool) -> bool {
688        let Some(obj) = self.get_mut_objects().get_mut(obj_idx) else {
689            return false;
690        };
691        if obj.get_is_dynamic() != is_dynamic {
692            obj.set_is_dynamic(is_dynamic);
693            if obj.get_ray_trace_caster() {
694                self.set_bvh_dirty(true);
695                self.set_dynamic_bvh_dirty(true);
696                self.set_dynamic_topology_dirty(true);
697            }
698            self.bump_world_revision();
699        }
700        true
701    }
702
703    /// Teleports object `obj_idx` to `transform`, incrementing `teleport_epoch` so snapshot interpolation snaps instead of sweeping.
704    ///
705    /// # Arguments
706    ///
707    /// - `&Self` - Mutable world.
708    /// - `usize` - Target object index in `objects`.
709    /// - `Transform3D` - Destination world transform.
710    ///
711    /// # Returns
712    ///
713    /// - `bool` - `true` when `obj_idx` existed and was teleported.
714    pub fn teleport_object(&mut self, obj_idx: usize, transform: Transform3D) -> bool {
715        let Some((mesh_id, ray_caster, is_dynamic)) =
716            self.get_objects().get(obj_idx).map(|obj: &SceneObject3D| {
717                (
718                    obj.get_mesh_id(),
719                    obj.get_ray_trace_caster(),
720                    obj.get_is_dynamic(),
721                )
722            })
723        else {
724            return false;
725        };
726        let local_bounds: Aabb3D = self
727            .get_mesh_library()
728            .get(mesh_id)
729            .and_then(|c: &MeshLodChain| c.get_levels().first())
730            .map(Mesh3D::get_bounds)
731            .unwrap_or_else(|| Aabb3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
732        let world_bounds: Aabb3D = transform.transform_aabb(local_bounds);
733        if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
734            obj.set_transform(transform);
735            obj.set_world_bounds(world_bounds);
736            let next_epoch: u32 = obj.get_teleport_epoch().wrapping_add(1);
737            obj.set_teleport_epoch(next_epoch);
738        }
739        if ray_caster {
740            if is_dynamic {
741                self.set_dynamic_bvh_dirty(true);
742            } else {
743                self.set_bvh_dirty(true);
744            }
745        }
746        self.bump_world_revision();
747        true
748    }
749
750    /// Imports an external `.obj` or `.gltf` model directly into the live 3D world and returns import telemetry.
751    ///
752    /// # Arguments
753    ///
754    /// - `&Self` - Mutable world.
755    /// - `ModelFormat` - Source model format.
756    /// - `&str` - Raw `.obj` or `.gltf` text content.
757    /// - `Transform3D` - Placement transform in the 3D scene.
758    /// - `PbrMaterial` - Fallback PBR material.
759    /// - `f32` - Optional continuous Y-spin speed in radians/sec.
760    ///
761    /// # Returns
762    ///
763    /// - `Result<ImportedModel3D, String>` - Imported model summary or parse error.
764    pub fn import_model(
765        &mut self,
766        format: ModelFormat,
767        source: &str,
768        transform: Transform3D,
769        fallback_material: PbrMaterial,
770        spin_speed: f32,
771    ) -> Result<ImportedModel3D, String> {
772        let imported: ImportedModel3D = ModelImporter3D::import(format, source, fallback_material)?;
773        let model_name: String = imported.get_name().clone();
774        for (i, chain) in imported.get_meshes().iter().cloned().enumerate() {
775            let mat: PbrMaterial = chain
776                .get_levels()
777                .first()
778                .map(Mesh3D::get_material)
779                .unwrap_or(fallback_material);
780            let mid: usize = self.register_mesh(chain);
781            let obj_idx: usize =
782                self.spawn_object(&format!("{model_name}_{i}"), mid, transform, mat, true);
783            if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
784                obj.set_spin_speed(spin_speed);
785            }
786            if spin_speed.abs() > 0.001 {
787                let _: bool = self.set_object_dynamic(obj_idx, true);
788            }
789        }
790        let next_cnt: usize = self.get_imported_model_count().saturating_add(1);
791        self.set_imported_model_count(next_cnt);
792        Ok(imported)
793    }
794
795    /// Spawns an object from a fluent `SpawnObjectDesc`.
796    ///
797    /// # Arguments
798    ///
799    /// - `&Self` - Mutable world.
800    /// - `&SpawnObjectDesc` - Spawn descriptor.
801    ///
802    /// # Returns
803    ///
804    /// - `usize` - Spawned object index.
805    pub fn spawn_with(&mut self, desc: &SpawnObjectDesc) -> usize {
806        let idx: usize = self.spawn_object(
807            desc.get_name(),
808            desc.get_mesh_id(),
809            desc.get_transform(),
810            desc.get_material(),
811            desc.get_ray_trace_caster(),
812        );
813        if let Some(obj) = self.get_mut_objects().get_mut(idx) {
814            obj.set_spin_speed(desc.get_spin_speed());
815        }
816        if desc.get_is_dynamic() || desc.get_spin_speed().abs() > 0.001 {
817            let _: bool = self.set_object_dynamic(idx, true);
818        }
819        idx
820    }
821
822    /// Imports an external `.obj` or `.gltf` model using a fluent `ImportModelDesc`.
823    ///
824    /// # Arguments
825    ///
826    /// - `&Self` - Mutable world.
827    /// - `&ImportModelDesc` - Import descriptor.
828    ///
829    /// # Returns
830    ///
831    /// - `Result<ImportedModel3D, String>` - Imported model telemetry or parse error.
832    pub fn import_with(&mut self, desc: &ImportModelDesc) -> Result<ImportedModel3D, String> {
833        self.import_model(
834            desc.get_format(),
835            desc.get_source(),
836            desc.get_transform(),
837            desc.get_fallback_material(),
838            desc.get_spin_speed(),
839        )
840    }
841
842    /// Returns the typed `CameraMode3D` currently active in this world.
843    ///
844    /// # Arguments
845    ///
846    /// - `&Self` - World reference.
847    ///
848    /// # Returns
849    ///
850    /// - `CameraMode3D` - Active typed camera controller mode.
851    #[must_use]
852    pub fn active_camera_mode(&self) -> CameraMode3D {
853        CameraMode3D::from_u8(self.get_camera_mode())
854    }
855
856    /// Sets the active 3D camera controller using a typed `CameraMode3D`.
857    ///
858    /// # Arguments
859    ///
860    /// - `&Self` - Mutable world.
861    /// - `CameraMode3D` - Desired camera controller mode.
862    pub fn set_camera_mode_enum(&mut self, mode: CameraMode3D) {
863        self.set_camera_mode(mode.as_u8());
864    }
865
866    /// Collects world-space triangles for all ray-trace casters matching `dynamic_filter` into `out_tris`.
867    ///
868    /// # Arguments
869    ///
870    /// - `&[SceneObject3D]` - World object slice.
871    /// - `&[MeshLodChain]` - Registered mesh library slice.
872    /// - `bool` - `true` to gather dynamic casters, `false` to gather static casters.
873    /// - `&mut Vec<BvhTriangle>` - Destination triangle buffer cleared and populated in place.
874    fn collect_caster_triangles(
875        objects: &[SceneObject3D],
876        mesh_library: &[MeshLodChain],
877        dynamic_filter: bool,
878        out_tris: &mut Vec<BvhTriangle>,
879    ) {
880        out_tris.clear();
881        for obj in objects.iter() {
882            if !obj.get_ray_trace_caster() || obj.get_is_dynamic() != dynamic_filter {
883                continue;
884            }
885            let Some(chain) = mesh_library.get(obj.get_mesh_id()) else {
886                continue;
887            };
888            let Some(mesh) = chain.get_levels().first() else {
889                continue;
890            };
891            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
892            let model_m: Mat4 = obj.get_transform().to_mat4();
893            let mat: PbrMaterial = obj.get_material();
894            for tri in mesh.get_indices().iter() {
895                let (i0, i1, i2): (usize, usize, usize) =
896                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
897                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
898                    let p0: Vec3 = model_m.mul_point3(verts[i0].get_position());
899                    let p1: Vec3 = model_m.mul_point3(verts[i1].get_position());
900                    let p2: Vec3 = model_m.mul_point3(verts[i2].get_position());
901                    out_tris.push(BvhTriangle::from_points(p0, p1, p2, mat));
902                }
903            }
904        }
905    }
906
907    /// Synchronizes the split static and dynamic BVH acceleration structures, refitting moving dynamic casters in O(N) without rebuilding static world geometry.
908    ///
909    /// # Arguments
910    ///
911    /// - `&Self` - Mutable world.
912    pub fn ensure_bvh(&mut self) {
913        if self.get_bvh_dirty() {
914            let mut static_tris: Vec<BvhTriangle> = Vec::new();
915            Self::collect_caster_triangles(
916                self.get_objects().as_slice(),
917                self.get_mesh_library().as_slice(),
918                false,
919                &mut static_tris,
920            );
921            self.set_bvh(Bvh3D::build(static_tris));
922            self.set_bvh_dirty(false);
923            let next_static: u64 = self.get_static_bvh_rebuilds().saturating_add(1);
924            self.set_static_bvh_rebuilds(next_static);
925        }
926        if self.get_dynamic_bvh_dirty() {
927            let topology_dirty: bool = self.get_dynamic_topology_dirty();
928            let Self {
929                objects,
930                mesh_library,
931                dynamic_bvh,
932                dynamic_tris_scratch,
933                dynamic_bvh_dirty,
934                dynamic_topology_dirty,
935                dynamic_bvh_refits,
936                dynamic_bvh_rebuilds,
937                ..
938            } = self;
939            Self::collect_caster_triangles(
940                objects.as_slice(),
941                mesh_library.as_slice(),
942                true,
943                dynamic_tris_scratch,
944            );
945            if dynamic_tris_scratch.is_empty() {
946                dynamic_bvh.rebuild_in_place(&[]);
947            } else if !topology_dirty
948                && dynamic_bvh.refit_from_source(dynamic_tris_scratch.as_slice())
949            {
950                if dynamic_bvh.needs_rebuild_after_refit(1.65) {
951                    dynamic_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
952                    *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
953                } else {
954                    *dynamic_bvh_refits = dynamic_bvh_refits.saturating_add(1);
955                }
956            } else {
957                dynamic_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
958                *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
959            }
960            *dynamic_bvh_dirty = false;
961            *dynamic_topology_dirty = false;
962        }
963        self.sync_dynamic_ray_instances();
964    }
965
966    /// Lazily constructs local-space BVH4/BVH8 trees for dynamic meshes and updates `dynamic_instances` from current object transforms with zero BVH rebuilds.
967    ///
968    /// # Arguments
969    ///
970    /// - `&Self` - Mutable world reference.
971    pub fn sync_dynamic_ray_instances(&mut self) {
972        let Self {
973            mesh_library,
974            objects,
975            mesh_local_bvhs,
976            dynamic_instances,
977            ..
978        } = self;
979        if mesh_local_bvhs.len() < mesh_library.len() {
980            mesh_local_bvhs.resize_with(mesh_library.len(), || None);
981        }
982        dynamic_instances.clear();
983        for (obj_idx, obj) in objects.iter().enumerate() {
984            if !obj.get_ray_trace_caster() || !obj.get_is_dynamic() {
985                continue;
986            }
987            let mesh_id: usize = obj.get_mesh_id();
988            let Some(chain) = mesh_library.get(mesh_id) else {
989                continue;
990            };
991            let Some(mesh) = chain.get_levels().first() else {
992                continue;
993            };
994            if mesh_local_bvhs[mesh_id].is_none() {
995                let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
996                let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
997                let mut local_tris: Vec<BvhTriangle> = Vec::with_capacity(indices.len());
998                let neutral: PbrMaterial = PbrMaterial::default();
999                for tri in indices.iter() {
1000                    let (i0, i1, i2): (usize, usize, usize) =
1001                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1002                    if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1003                        local_tris.push(BvhTriangle::from_points(
1004                            verts[i0].get_position(),
1005                            verts[i1].get_position(),
1006                            verts[i2].get_position(),
1007                            neutral,
1008                        ));
1009                    }
1010                }
1011                mesh_local_bvhs[mesh_id] = Some(Bvh3D::build(local_tris));
1012            }
1013            let tr: Transform3D = obj.get_transform();
1014            dynamic_instances.push(DynamicRayInstance {
1015                obj_idx,
1016                mesh_id,
1017                world_bounds: obj.get_world_bounds(),
1018                inv_model: tr.to_inv_mat4(),
1019                normal_basis: tr.normal_mat3(),
1020                material: obj.get_material(),
1021            });
1022        }
1023    }
1024
1025    /// Updates only the inverse-model transform, normal basis, and world AABB of an existing dynamic instance without rebuilding any BVH.
1026    ///
1027    /// # Arguments
1028    ///
1029    /// - `&Self` - Mutable world reference.
1030    /// - `usize` - Scene object index.
1031    /// - `Transform3D` - Interpolated world transform.
1032    /// - `Aabb3D` - Interpolated world AABB.
1033    pub(crate) fn override_dynamic_instance_pose(
1034        &mut self,
1035        obj_idx: usize,
1036        transform: Transform3D,
1037        world_bounds: Aabb3D,
1038    ) {
1039        let Self {
1040            dynamic_instances, ..
1041        } = self;
1042        for inst in dynamic_instances.iter_mut() {
1043            if inst.obj_idx == obj_idx {
1044                inst.world_bounds = world_bounds;
1045                inst.inv_model = transform.to_inv_mat4();
1046                inst.normal_basis = transform.normal_mat3();
1047                return;
1048            }
1049        }
1050    }
1051
1052    /// Traces a shadow ray against object-space dynamic instances via inverse interpolated `Mat4` with zero dynamic BVH rebuilds.
1053    ///
1054    /// # Arguments
1055    ///
1056    /// - `&[DynamicRayInstance]` - Active dynamic raytracing instances.
1057    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1058    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1059    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1060    /// - `&mut u32` - Per-thread local occluder triangle hint.
1061    ///
1062    /// # Returns
1063    ///
1064    /// - `bool` - `true` if occluded by any dynamic object at its current or interpolated pose.
1065    #[inline(always)]
1066    #[must_use]
1067    pub(crate) fn trace_any_shadow_dynamic_instances(
1068        instances: &[DynamicRayInstance],
1069        local_bvhs: &[Option<Bvh3D>],
1070        ray: (Vec3, Vec3, Vec3),
1071        bounds: (f32, f32),
1072        dyn_cache: &mut u32,
1073    ) -> bool {
1074        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1075        let (t_min, t_max): (f32, f32) = bounds;
1076        for inst in instances.iter() {
1077            if !inst
1078                .world_bounds
1079                .intersect_ray_near(origin, inv_dir, t_min, t_max)
1080                .is_finite()
1081            {
1082                continue;
1083            }
1084            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1085                continue;
1086            };
1087            let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
1088            let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
1089            let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
1090            if local_bvh
1091                .trace_any_shadow_cached(local_orig, local_dir, local_inv, t_min, t_max, dyn_cache)
1092            {
1093                return true;
1094            }
1095        }
1096        false
1097    }
1098
1099    /// Traces a coherent 4-ray shadow packet against static BVH and object-space inverse-interpolated dynamic instances.
1100    ///
1101    /// # Arguments
1102    ///
1103    /// - `&Bvh3D` - Static world BVH4/BVH8.
1104    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1105    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1106    /// - `&RayPacket4` - Coherent 4-ray shadow packet.
1107    /// - `u8` - 4-bit mask of active rays to trace.
1108    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1109    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder hints.
1110    ///
1111    /// # Returns
1112    ///
1113    /// - `u8` - 4-bit mask of occluded rays.
1114    #[inline(always)]
1115    #[must_use]
1116    pub(crate) fn trace_any_shadow_packet4_with_instances(
1117        static_bvh: &Bvh3D,
1118        instances: &[DynamicRayInstance],
1119        local_bvhs: &[Option<Bvh3D>],
1120        pkt: &RayPacket4,
1121        active_mask: u8,
1122        bounds: (f32, f32),
1123        caches: (&mut u32, &mut u32),
1124    ) -> u8 {
1125        let (t_min, t_max): (f32, f32) = bounds;
1126        let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
1127        let mut occluded: u8 =
1128            static_bvh.trace_any_shadow_packet4(pkt, active_mask, t_min, t_max, static_cache);
1129        let mut rem: u8 = active_mask & !occluded;
1130        if rem == 0 || instances.is_empty() {
1131            return occluded;
1132        }
1133        for inst in instances.iter() {
1134            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1135                continue;
1136            };
1137            let mut hit_box_mask: u8 = 0;
1138            let mut check: u8 = rem;
1139            while check != 0 {
1140                let r: usize = check.trailing_zeros() as usize;
1141                check &= check - 1;
1142                let orig_r: Vec3 = Vec3::new(pkt.ox[r], pkt.oy[r], pkt.oz[r]);
1143                let inv_r: Vec3 = Vec3::new(pkt.ix[r], pkt.iy[r], pkt.iz[r]);
1144                if inst
1145                    .world_bounds
1146                    .intersect_ray_near(orig_r, inv_r, t_min, t_max)
1147                    .is_finite()
1148                {
1149                    hit_box_mask |= 1_u8 << r;
1150                }
1151            }
1152            if hit_box_mask == 0 {
1153                continue;
1154            }
1155            let mut local_pkt: RayPacket4 = *pkt;
1156            let mut tr_mask: u8 = hit_box_mask;
1157            while tr_mask != 0 {
1158                let r: usize = tr_mask.trailing_zeros() as usize;
1159                tr_mask &= tr_mask - 1;
1160                let lo: Vec3 = inst
1161                    .inv_model
1162                    .mul_point3(Vec3::new(pkt.ox[r], pkt.oy[r], pkt.oz[r]));
1163                let ld: Vec3 = inst
1164                    .inv_model
1165                    .mul_vec3(Vec3::new(pkt.dx[r], pkt.dy[r], pkt.dz[r]));
1166                let li: Vec3 = Ray3D::safe_inv_vec(ld);
1167                local_pkt.ox[r] = lo.get_x();
1168                local_pkt.oy[r] = lo.get_y();
1169                local_pkt.oz[r] = lo.get_z();
1170                local_pkt.dx[r] = ld.get_x();
1171                local_pkt.dy[r] = ld.get_y();
1172                local_pkt.dz[r] = ld.get_z();
1173                local_pkt.ix[r] = li.get_x();
1174                local_pkt.iy[r] = li.get_y();
1175                local_pkt.iz[r] = li.get_z();
1176            }
1177            let dyn_occ: u8 = local_bvh.trace_any_shadow_packet4(
1178                &local_pkt,
1179                hit_box_mask,
1180                t_min,
1181                t_max,
1182                dyn_cache,
1183            );
1184            occluded |= dyn_occ;
1185            rem &= !dyn_occ;
1186            if rem == 0 {
1187                break;
1188            }
1189        }
1190        occluded
1191    }
1192
1193    /// Traces a shadow/occlusion ray across static BVH and object-space inverse-interpolated dynamic instances.
1194    ///
1195    /// # Arguments
1196    ///
1197    /// - `&Bvh3D` - Static world BVH.
1198    /// - `&[DynamicRayInstance]` - Active dynamic raytracing instances.
1199    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1200    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1201    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1202    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder hints.
1203    ///
1204    /// # Returns
1205    ///
1206    /// - `bool` - `true` when occluded by static or dynamic geometry.
1207    #[inline(always)]
1208    #[must_use]
1209    pub(crate) fn trace_any_shadow_with_instances(
1210        static_bvh: &Bvh3D,
1211        instances: &[DynamicRayInstance],
1212        local_bvhs: &[Option<Bvh3D>],
1213        ray: (Vec3, Vec3, Vec3),
1214        bounds: (f32, f32),
1215        caches: (&mut u32, &mut u32),
1216    ) -> bool {
1217        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1218        let (t_min, t_max): (f32, f32) = bounds;
1219        let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
1220        if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
1221            return true;
1222        }
1223        if !instances.is_empty() {
1224            return Self::trace_any_shadow_dynamic_instances(
1225                instances, local_bvhs, ray, bounds, dyn_cache,
1226            );
1227        }
1228        false
1229    }
1230
1231    /// Traces a reflection/GI ray across static BVH and object-space inverse-interpolated dynamic instances, returning `(distance, world_normal, material)`.
1232    ///
1233    /// # Arguments
1234    ///
1235    /// - `&Bvh3D` - Static world BVH.
1236    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1237    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1238    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1239    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1240    ///
1241    /// # Returns
1242    ///
1243    /// - `Option<(f32, Vec3, PbrMaterial)>` - Closest hit distance, world-space unit normal, and PBR material.
1244    #[inline(always)]
1245    #[must_use]
1246    pub(crate) fn trace_closest_with_instances(
1247        static_bvh: &Bvh3D,
1248        instances: &[DynamicRayInstance],
1249        local_bvhs: &[Option<Bvh3D>],
1250        ray: (Vec3, Vec3, Vec3),
1251        bounds: (f32, f32),
1252    ) -> Option<(f32, Vec3, PbrMaterial)> {
1253        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1254        let (t_min, t_max): (f32, f32) = bounds;
1255        let mut best_t: f32 = t_max;
1256        let mut best_hit: Option<(f32, Vec3, PbrMaterial)> = static_bvh
1257            .trace_closest_raw(origin, dir, inv_dir, t_min, t_max)
1258            .map(|(st, si): (f32, usize)| {
1259                let tri: &BvhTriangle = &static_bvh.get_triangles()[si];
1260                best_t = st;
1261                (st, tri.get_normal(), tri.get_material())
1262            });
1263        for inst in instances.iter() {
1264            if !inst
1265                .world_bounds
1266                .intersect_ray_near(origin, inv_dir, t_min, best_t)
1267                .is_finite()
1268            {
1269                continue;
1270            }
1271            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1272                continue;
1273            };
1274            let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
1275            let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
1276            let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
1277            if let Some((dt, di)) =
1278                local_bvh.trace_closest_raw(local_orig, local_dir, local_inv, t_min, best_t)
1279            {
1280                best_t = dt;
1281                let local_n: Vec3 = local_bvh.get_triangles()[di].get_normal();
1282                let world_n: Vec3 = Mat4::transform_normal_with_basis(local_n, inst.normal_basis);
1283                best_hit = Some((dt, world_n, inst.material));
1284            }
1285        }
1286        best_hit
1287    }
1288
1289    /// Traces a coherent 4-ray closest-hit packet across static BVH and object-space inverse-interpolated dynamic instances.
1290    ///
1291    /// # Arguments
1292    ///
1293    /// - `&Bvh3D` - Static world BVH4/BVH8.
1294    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1295    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1296    /// - `&RayPacket4` - Coherent 4-ray reflection or GI packet.
1297    /// - `u8` - 4-bit mask of active rays.
1298    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1299    ///
1300    /// # Returns
1301    ///
1302    /// - `[Option<(f32, Vec3, PbrMaterial)>; 4]` - Closest hit distance, world normal, and material per lane.
1303    #[inline(always)]
1304    #[must_use]
1305    pub(crate) fn trace_closest_packet4_with_instances(
1306        static_bvh: &Bvh3D,
1307        instances: &[DynamicRayInstance],
1308        local_bvhs: &[Option<Bvh3D>],
1309        pkt: &RayPacket4,
1310        active_mask: u8,
1311        bounds: (f32, f32),
1312    ) -> [Option<(f32, Vec3, PbrMaterial)>; 4] {
1313        let (t_min, t_max): (f32, f32) = bounds;
1314        let mut best_t: [f32; 4] = [t_max; 4];
1315        let mut best_static_idx: [usize; 4] = [usize::MAX; 4];
1316        static_bvh.trace_closest_packet4(
1317            pkt,
1318            active_mask,
1319            t_min,
1320            &mut best_t,
1321            &mut best_static_idx,
1322        );
1323        let static_tris: &[BvhTriangle] = static_bvh.get_triangles().as_slice();
1324        let mut out: [Option<(f32, Vec3, PbrMaterial)>; 4] = [None; 4];
1325        let mut m: u8 = active_mask;
1326        while m != 0 {
1327            let r: usize = m.trailing_zeros() as usize;
1328            m &= m - 1;
1329            let sidx: usize = best_static_idx[r];
1330            if sidx != usize::MAX {
1331                let tri: &BvhTriangle = &static_tris[sidx];
1332                out[r] = Some((best_t[r], tri.get_normal(), tri.get_material()));
1333            }
1334        }
1335        for inst in instances.iter() {
1336            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1337                continue;
1338            };
1339            let mut hit_box_mask: u8 = 0;
1340            let mut check: u8 = active_mask;
1341            while check != 0 {
1342                let r: usize = check.trailing_zeros() as usize;
1343                check &= check - 1;
1344                if inst
1345                    .world_bounds
1346                    .intersect_ray_near(
1347                        Vec3::new(pkt.ox[r], pkt.oy[r], pkt.oz[r]),
1348                        Vec3::new(pkt.ix[r], pkt.iy[r], pkt.iz[r]),
1349                        t_min,
1350                        best_t[r],
1351                    )
1352                    .is_finite()
1353                {
1354                    hit_box_mask |= 1_u8 << r;
1355                }
1356            }
1357            if hit_box_mask == 0 {
1358                continue;
1359            }
1360            let mut local_pkt: RayPacket4 = *pkt;
1361            let mut tr_mask: u8 = hit_box_mask;
1362            while tr_mask != 0 {
1363                let r: usize = tr_mask.trailing_zeros() as usize;
1364                tr_mask &= tr_mask - 1;
1365                let lo: Vec3 = inst
1366                    .inv_model
1367                    .mul_point3(Vec3::new(pkt.ox[r], pkt.oy[r], pkt.oz[r]));
1368                let ld: Vec3 = inst
1369                    .inv_model
1370                    .mul_vec3(Vec3::new(pkt.dx[r], pkt.dy[r], pkt.dz[r]));
1371                let li: Vec3 = Ray3D::safe_inv_vec(ld);
1372                local_pkt.ox[r] = lo.get_x();
1373                local_pkt.oy[r] = lo.get_y();
1374                local_pkt.oz[r] = lo.get_z();
1375                local_pkt.dx[r] = ld.get_x();
1376                local_pkt.dy[r] = ld.get_y();
1377                local_pkt.dz[r] = ld.get_z();
1378                local_pkt.ix[r] = li.get_x();
1379                local_pkt.iy[r] = li.get_y();
1380                local_pkt.iz[r] = li.get_z();
1381            }
1382            let mut dyn_idx: [usize; 4] = [usize::MAX; 4];
1383            local_bvh.trace_closest_packet4(
1384                &local_pkt,
1385                hit_box_mask,
1386                t_min,
1387                &mut best_t,
1388                &mut dyn_idx,
1389            );
1390            let local_tris: &[BvhTriangle] = local_bvh.get_triangles().as_slice();
1391            let mut upd: u8 = hit_box_mask;
1392            while upd != 0 {
1393                let r: usize = upd.trailing_zeros() as usize;
1394                upd &= upd - 1;
1395                let di: usize = dyn_idx[r];
1396                if di != usize::MAX {
1397                    let wn: Vec3 = Mat4::transform_normal_with_basis(
1398                        local_tris[di].get_normal(),
1399                        inst.normal_basis,
1400                    );
1401                    out[r] = Some((best_t[r], wn, inst.material));
1402                }
1403            }
1404        }
1405        out
1406    }
1407
1408    /// Traces a shadow ray using static BVH plus object-space inverse-interpolated dynamic instances.
1409    ///
1410    /// # Arguments
1411    ///
1412    /// - `&Self` - World reference.
1413    /// - `&Ray3D` - World-space shadow ray.
1414    /// - `f32` - Minimum hit distance.
1415    /// - `f32` - Maximum hit distance.
1416    ///
1417    /// # Returns
1418    ///
1419    /// - `bool` - `true` when occluded by static or dynamic geometry at its current/interpolated pose.
1420    #[must_use]
1421    pub fn trace_any_shadow_object_space(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
1422        let Self {
1423            bvh,
1424            dynamic_instances,
1425            mesh_local_bvhs,
1426            ..
1427        } = self;
1428        let mut sc: u32 = u32::MAX;
1429        let mut dc: u32 = u32::MAX;
1430        Self::trace_any_shadow_with_instances(
1431            bvh,
1432            dynamic_instances.as_slice(),
1433            mesh_local_bvhs.as_slice(),
1434            (
1435                ray.get_origin(),
1436                ray.get_direction(),
1437                ray.get_inv_direction(),
1438            ),
1439            (t_min, t_max),
1440            (&mut sc, &mut dc),
1441        )
1442    }
1443
1444    /// Traces a coherent 4-ray closest-hit packet against both the static BVH4 and object-space inverse-interpolated dynamic instances.
1445    ///
1446    /// # Arguments
1447    ///
1448    /// - `&Self` - World reference.
1449    /// - `&RayPacket4` - Coherent 4-ray query packet.
1450    /// - `u8` - 4-bit mask of active rays (`0..=15`).
1451    /// - `f32` - Minimum hit distance.
1452    /// - `f32` - Maximum hit distance.
1453    ///
1454    /// # Returns
1455    ///
1456    /// - `[Option<RayHit3D>; 4]` - Closest hit surface with world normal and material per active lane.
1457    #[must_use]
1458    pub fn trace_closest_packet4(
1459        &self,
1460        pkt: &RayPacket4,
1461        active_mask: u8,
1462        t_min: f32,
1463        t_max: f32,
1464    ) -> [Option<RayHit3D>; 4] {
1465        let Self {
1466            bvh,
1467            dynamic_instances,
1468            mesh_local_bvhs,
1469            ..
1470        } = self;
1471        let raw: [Option<(f32, Vec3, PbrMaterial)>; 4] = Self::trace_closest_packet4_with_instances(
1472            bvh,
1473            dynamic_instances.as_slice(),
1474            mesh_local_bvhs.as_slice(),
1475            pkt,
1476            active_mask,
1477            (t_min, t_max),
1478        );
1479        let mut out: [Option<RayHit3D>; 4] = [None; 4];
1480        for lane in 0..4 {
1481            if let Some((t, normal, material)) = raw[lane] {
1482                let point: Vec3 = Vec3::new(
1483                    pkt.ox[lane] + pkt.dx[lane] * t,
1484                    pkt.oy[lane] + pkt.dy[lane] * t,
1485                    pkt.oz[lane] + pkt.dz[lane] * t,
1486                );
1487                out[lane] = Some(RayHit3D {
1488                    distance: t,
1489                    point,
1490                    normal,
1491                    material,
1492                });
1493            }
1494        }
1495        out
1496    }
1497
1498    /// Traces a closest-hit ray using static BVH plus object-space inverse-interpolated dynamic instances.
1499    ///
1500    /// # Arguments
1501    ///
1502    /// - `&Self` - World reference.
1503    /// - `&Ray3D` - World-space query ray.
1504    /// - `f32` - Minimum hit distance.
1505    /// - `f32` - Maximum hit distance.
1506    ///
1507    /// # Returns
1508    ///
1509    /// - `Option<RayHit3D>` - Closest hit surface with world-space normal and material.
1510    #[must_use]
1511    pub fn trace_closest_object_space(
1512        &self,
1513        ray: &Ray3D,
1514        t_min: f32,
1515        t_max: f32,
1516    ) -> Option<RayHit3D> {
1517        let Self {
1518            bvh,
1519            dynamic_instances,
1520            mesh_local_bvhs,
1521            ..
1522        } = self;
1523        let (t, normal, material): (f32, Vec3, PbrMaterial) = Self::trace_closest_with_instances(
1524            bvh,
1525            dynamic_instances.as_slice(),
1526            mesh_local_bvhs.as_slice(),
1527            (
1528                ray.get_origin(),
1529                ray.get_direction(),
1530                ray.get_inv_direction(),
1531            ),
1532            (t_min, t_max),
1533        )?;
1534        Some(RayHit3D {
1535            distance: t,
1536            point: ray.get_origin().add(ray.get_direction().scale(t)),
1537            normal,
1538            material,
1539        })
1540    }
1541
1542    /// Returns the combined node count across both static and dynamic BVH acceleration trees.
1543    ///
1544    /// # Arguments
1545    ///
1546    /// - `&Self` - World reference.
1547    ///
1548    /// # Returns
1549    ///
1550    /// - `usize` - Total active BVH nodes.
1551    #[must_use]
1552    pub fn total_bvh_nodes(&self) -> usize {
1553        self.get_bvh()
1554            .get_nodes()
1555            .len()
1556            .saturating_add(self.get_dynamic_bvh().get_nodes().len())
1557    }
1558
1559    /// Traces a shadow/occlusion ray across both static and dynamic BVHs using 1-triangle occluder caches.
1560    ///
1561    /// # Arguments
1562    ///
1563    /// - `(&Bvh3D, &Bvh3D)` - `(static_bvh, dynamic_bvh)` pair.
1564    /// - `(Vec3, Vec3, Vec3)` - `(origin, dir, inv_dir)` ray triple.
1565    /// - `(f32, f32)` - `(t_min, t_max)` distance bounds.
1566    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder triangle hints.
1567    ///
1568    /// # Returns
1569    ///
1570    /// - `bool` - `true` if occluded by either static or dynamic geometry.
1571    #[must_use]
1572    pub fn trace_any_shadow_split(
1573        bvhs: (&Bvh3D, &Bvh3D),
1574        ray: (Vec3, Vec3, Vec3),
1575        bounds: (f32, f32),
1576        caches: (&mut u32, &mut u32),
1577    ) -> bool {
1578        let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
1579        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1580        let (t_min, t_max): (f32, f32) = bounds;
1581        let (static_cache, dynamic_cache): (&mut u32, &mut u32) = caches;
1582        if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
1583            return true;
1584        }
1585        if !dynamic_bvh.is_empty() {
1586            return dynamic_bvh.trace_any_shadow_cached(
1587                origin,
1588                dir,
1589                inv_dir,
1590                t_min,
1591                t_max,
1592                dynamic_cache,
1593            );
1594        }
1595        false
1596    }
1597
1598    /// Traces a reflection/GI ray across both static and dynamic BVHs and returns `(distance, is_dynamic, tri_index)`.
1599    ///
1600    /// # Arguments
1601    ///
1602    /// - `(&Bvh3D, &Bvh3D)` - `(static_bvh, dynamic_bvh)` pair.
1603    /// - `(Vec3, Vec3, Vec3)` - `(origin, dir, inv_dir)` ray triple.
1604    /// - `(f32, f32)` - `(t_min, t_max)` distance bounds.
1605    ///
1606    /// # Returns
1607    ///
1608    /// - `Option<(f32, bool, usize)>` - Closest `(t, hit_in_dynamic_bvh, triangle_index)`.
1609    #[must_use]
1610    pub fn trace_closest_split(
1611        bvhs: (&Bvh3D, &Bvh3D),
1612        ray: (Vec3, Vec3, Vec3),
1613        bounds: (f32, f32),
1614    ) -> Option<(f32, bool, usize)> {
1615        let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
1616        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1617        let (t_min, t_max): (f32, f32) = bounds;
1618        let static_hit: Option<(f32, usize)> =
1619            static_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, t_max);
1620        let dyn_limit: f32 = static_hit.map_or(t_max, |(t, _): (f32, usize)| t);
1621        let dynamic_hit: Option<(f32, usize)> = if !dynamic_bvh.is_empty() {
1622            dynamic_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, dyn_limit)
1623        } else {
1624            None
1625        };
1626        match (static_hit, dynamic_hit) {
1627            (_, Some((dt, di))) => Some((dt, true, di)),
1628            (Some((st, si)), None) => Some((st, false, si)),
1629            (None, None) => None,
1630        }
1631    }
1632
1633    /// Returns the optional player vehicle index.
1634    ///
1635    /// # Arguments
1636    ///
1637    /// - `&Self` - World reference.
1638    ///
1639    /// # Returns
1640    ///
1641    /// - `Option<usize>` - Vehicle index in `objects`.
1642    #[must_use]
1643    pub fn vehicle_index(&self) -> Option<usize> {
1644        let Self {
1645            player_vehicle_index,
1646            ..
1647        } = self;
1648        *player_vehicle_index
1649    }
1650
1651    /// Builds a GTA-inspired open-world neon downtown city with reflective wet asphalt, glass towers, and a drivable sports car.
1652    ///
1653    /// # Returns
1654    ///
1655    /// - `Self` - Populated open-world 3D city ready for real-time PBR + Ray Tracing.
1656    #[must_use]
1657    pub fn create_open_world_city() -> Self {
1658        let mut world: Self = Self::default();
1659        let asphalt_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x18202C), 0.25, 0.14, 0.58)
1660            .with_surface_detail(SurfaceDetailMode::RoadSurface);
1661        let road_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::ground_plane(
1662            "wet_asphalt_boulevard",
1663            220.0,
1664            220.0,
1665            24,
1666            asphalt_mat,
1667        )));
1668        let _: usize = world.spawn_object(
1669            "city_ground",
1670            road_mesh,
1671            Transform3D::default(),
1672            asphalt_mat,
1673            false,
1674        );
1675        let stripe_mat: PbrMaterial = PbrMaterial::neon(Color::hex(0xFACC15), 1.2);
1676        let stripe_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
1677            "lane_stripe",
1678            0.35,
1679            0.05,
1680            5.0,
1681            true,
1682            stripe_mat,
1683        )));
1684        for iz in -7..=7 {
1685            let _: usize = world.spawn_object(
1686                &format!("stripe_{iz}"),
1687                stripe_mesh,
1688                Transform3D::new(
1689                    Vec3::new(0.0, 0.02, (iz as f32) * 14.0),
1690                    0.0,
1691                    Vec3::splat(1.0),
1692                ),
1693                stripe_mat,
1694                false,
1695            );
1696        }
1697        let tower_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
1698            "city_skyscraper",
1699            1.0,
1700            1.0,
1701            1.0,
1702            true,
1703            PbrMaterial::default(),
1704        )));
1705        let neon_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
1706            "neon_sign",
1707            1.0,
1708            1.0,
1709            1.0,
1710            true,
1711            PbrMaterial::neon(Color::hex(0x38BDF8), 1.8),
1712        )));
1713        let tower_palettes: [PbrMaterial; 4] = [
1714            PbrMaterial::pbr(Color::hex(0x1E293B), 0.72, 0.16, 0.65)
1715                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
1716            PbrMaterial::pbr(Color::hex(0x334155), 0.55, 0.24, 0.45)
1717                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
1718            PbrMaterial::pbr(Color::hex(0x0F172A), 0.85, 0.10, 0.78)
1719                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
1720            PbrMaterial::pbr(Color::hex(0x475569), 0.40, 0.35, 0.35)
1721                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
1722        ];
1723        let neon_colors: [Color; 4] = [
1724            Color::hex(0x38BDF8),
1725            Color::hex(0xF43F5E),
1726            Color::hex(0xA855F7),
1727            Color::hex(0x34D399),
1728        ];
1729        let mut idx_counter: usize = 0;
1730        for side in [-1.0_f32, 1.0_f32] {
1731            for row in -4..=4 {
1732                let z: f32 = (row as f32) * 20.0 - 12.0;
1733                let x: f32 = side * (16.5 + ((idx_counter % 3) as f32) * 3.0);
1734                let h: f32 = 16.0 + ((idx_counter * 7) % 5) as f32 * 8.5;
1735                let w: f32 = 9.0 + ((idx_counter % 2) as f32) * 3.0;
1736                let mat: PbrMaterial = tower_palettes[idx_counter % tower_palettes.len()];
1737                let _: usize = world.spawn_object(
1738                    &format!("tower_{idx_counter}"),
1739                    tower_unit,
1740                    Transform3D::new(Vec3::new(x, 0.0, z), 0.0, Vec3::new(w, h, 11.0)),
1741                    mat,
1742                    true,
1743                );
1744                let neon_mat: PbrMaterial =
1745                    PbrMaterial::neon(neon_colors[idx_counter % neon_colors.len()], 1.9);
1746                let _: usize = world.spawn_object(
1747                    &format!("crown_{idx_counter}"),
1748                    neon_unit,
1749                    Transform3D::new(
1750                        Vec3::new(x - side * (w * 0.5 + 0.28), h * 0.72, z),
1751                        0.0,
1752                        Vec3::new(0.36, 1.4, 8.2),
1753                    ),
1754                    neon_mat,
1755                    false,
1756                );
1757                idx_counter += 1;
1758            }
1759        }
1760        let car_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0xF43F5E), 0.88, 0.12, 0.72);
1761        let car_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::sports_car(
1762            "hero_gt", car_mat,
1763        )));
1764        let car_idx: usize = world.spawn_object(
1765            "player_gt_car",
1766            car_mesh,
1767            Transform3D::new(Vec3::new(0.0, 0.0, 6.0), 0.0, Vec3::splat(1.1)),
1768            car_mat,
1769            true,
1770        );
1771        let _: bool = world.set_object_dynamic(car_idx, true);
1772        world.set_player_vehicle_index(Some(car_idx));
1773        world.set_camera(Camera3D {
1774            position: Vec3::new(0.0, 6.2, 18.5),
1775            yaw: -FRAC_PI_2,
1776            pitch: -0.18,
1777            fov_deg: 62.0,
1778            near: 0.3,
1779            far: 420.0,
1780        });
1781        world.ensure_bvh();
1782        world
1783    }
1784
1785    /// Cycles the active 3D camera perspective (`Chase` -> `Hood` -> `Orbit` -> `Aerial`) safely without clipping.
1786    ///
1787    /// # Arguments
1788    ///
1789    /// - `&Self` - Mutable world.
1790    ///
1791    /// # Returns
1792    ///
1793    /// - `u8` - New active camera mode index.
1794    pub fn cycle_camera_mode(&mut self) -> u8 {
1795        let next: u8 = (self.get_camera_mode() + 1) % 4;
1796        self.set_camera_mode(next);
1797        next
1798    }
1799
1800    /// Tests whether a candidate horizontal AABB intersects any solid obstacle object excluding `ignore_idx`.
1801    ///
1802    /// # Arguments
1803    ///
1804    /// - `&Self` - World reference.
1805    /// - `Aabb3D` - Candidate moving object bounds.
1806    /// - `usize` - Self object index to skip.
1807    ///
1808    /// # Returns
1809    ///
1810    /// - `bool` - `true` when blocked by a solid building or imported model.
1811    #[must_use]
1812    fn collides_with_obstacles(&self, candidate: Aabb3D, ignore_idx: usize) -> bool {
1813        for (idx, obj) in self.get_objects().iter().enumerate() {
1814            if idx == ignore_idx || !obj.get_ray_trace_caster() {
1815                continue;
1816            }
1817            let b: Aabb3D = obj.get_world_bounds();
1818            let overlap_x: bool = candidate.get_min().get_x() < b.get_max().get_x()
1819                && candidate.get_max().get_x() > b.get_min().get_x();
1820            let overlap_y: bool = candidate.get_min().get_y() < b.get_max().get_y()
1821                && candidate.get_max().get_y() > b.get_min().get_y();
1822            let overlap_z: bool = candidate.get_min().get_z() < b.get_max().get_z()
1823                && candidate.get_max().get_z() > b.get_min().get_z();
1824            if overlap_x && overlap_y && overlap_z {
1825                return true;
1826            }
1827        }
1828        false
1829    }
1830
1831    /// Advances drivable vehicle/camera controls, AABB collision resolution, and spinning models by `dt` seconds.
1832    ///
1833    /// # Arguments
1834    ///
1835    /// - `&Self` - Mutable world.
1836    /// - `f32` - Delta time in seconds.
1837    /// - `&InputState` - Real-time polled keyboard/pointer input.
1838    /// - `&ActionMap` - Action bindings for WASD/Arrows movement.
1839    pub fn step_simulation(&mut self, dt: f32, input: &InputState, actions: &ActionMap) {
1840        let move_vec: Point = actions.movement_vector(input);
1841        let steer: f32 = move_vec.get_x();
1842        let throttle: f32 = -move_vec.get_y();
1843        let mut any_dynamic_moved: bool = false;
1844        let mut any_static_moved: bool = false;
1845        let car_opt: Option<usize> = self.vehicle_index();
1846        if let Some(car_idx) = car_opt
1847            && let Some((mut tr, mesh_id, car_is_dynamic)) =
1848                self.get_objects().get(car_idx).map(|car: &SceneObject3D| {
1849                    (car.get_transform(), car.get_mesh_id(), car.get_is_dynamic())
1850                })
1851        {
1852            let mut car_moved: bool = false;
1853            let mesh_bounds: Aabb3D = self
1854                .get_mesh_library()
1855                .get(mesh_id)
1856                .and_then(|c: &MeshLodChain| c.get_levels().first())
1857                .map(Mesh3D::get_bounds)
1858                .unwrap_or_else(|| Aabb3D::new(Vec3::splat(-2.0), Vec3::splat(2.0)));
1859            if steer.abs() > 0.05 {
1860                let mut rotated: Transform3D = tr;
1861                rotated.set_yaw_rad(tr.get_yaw_rad() - steer * 1.85 * dt);
1862                if !self.collides_with_obstacles(rotated.transform_aabb(mesh_bounds), car_idx) {
1863                    tr = rotated;
1864                    car_moved = true;
1865                }
1866            }
1867            if throttle.abs() > 0.05 {
1868                let fwd_x: f32 = -tr.get_yaw_rad().sin();
1869                let fwd_z: f32 = -tr.get_yaw_rad().cos();
1870                let speed: f32 = 24.0 * throttle * dt;
1871                let cur: Vec3 = tr.get_position();
1872                let cand_x: f32 = (cur.get_x() + fwd_x * speed).clamp(-9.2, 9.2);
1873                let cand_z: f32 = (cur.get_z() + fwd_z * speed).clamp(-85.0, 85.0);
1874                let mut try_x: Transform3D = tr;
1875                try_x.set_position(Vec3::new(cand_x, 0.0, cur.get_z()));
1876                if !self.collides_with_obstacles(try_x.transform_aabb(mesh_bounds), car_idx) {
1877                    tr.set_position(Vec3::new(cand_x, 0.0, tr.get_position().get_z()));
1878                    car_moved = true;
1879                }
1880                let mut try_z: Transform3D = tr;
1881                try_z.set_position(Vec3::new(tr.get_position().get_x(), 0.0, cand_z));
1882                if !self.collides_with_obstacles(try_z.transform_aabb(mesh_bounds), car_idx) {
1883                    tr.set_position(Vec3::new(tr.get_position().get_x(), 0.0, cand_z));
1884                    car_moved = true;
1885                }
1886            }
1887            if car_moved {
1888                let world_b: Aabb3D = tr.transform_aabb(mesh_bounds);
1889                if let Some(car_mut) = self.get_mut_objects().get_mut(car_idx) {
1890                    car_mut.set_transform(tr);
1891                    car_mut.set_world_bounds(world_b);
1892                }
1893                if car_is_dynamic {
1894                    any_dynamic_moved = true;
1895                } else {
1896                    any_static_moved = true;
1897                }
1898            }
1899            let car_tr: Transform3D = self.get_objects()[car_idx].get_transform();
1900            let car_pos: Vec3 = car_tr.get_position();
1901            let yaw: f32 = car_tr.get_yaw_rad();
1902            let cam_mode: u8 = self.get_camera_mode();
1903            let (mut desired_eye, look_target): (Vec3, Vec3) = match cam_mode {
1904                1 => {
1905                    let eye: Vec3 = Vec3::new(
1906                        car_pos.get_x() - yaw.sin() * 1.4,
1907                        2.15,
1908                        car_pos.get_z() - yaw.cos() * 1.4,
1909                    );
1910                    let tgt: Vec3 = Vec3::new(
1911                        car_pos.get_x() - yaw.sin() * 18.0,
1912                        1.8,
1913                        car_pos.get_z() - yaw.cos() * 18.0,
1914                    );
1915                    (eye, tgt)
1916                }
1917                2 => {
1918                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.45;
1919                    self.set_camera_orbit_rad(orbit);
1920                    let eye: Vec3 = Vec3::new(
1921                        car_pos.get_x() + orbit.sin() * 10.5,
1922                        5.2,
1923                        car_pos.get_z() + orbit.cos() * 10.5,
1924                    );
1925                    (eye, Vec3::new(car_pos.get_x(), 1.6, car_pos.get_z()))
1926                }
1927                3 => {
1928                    let eye: Vec3 = Vec3::new(
1929                        car_pos.get_x() + yaw.sin() * 18.0,
1930                        18.5,
1931                        car_pos.get_z() + yaw.cos() * 18.0,
1932                    );
1933                    (eye, Vec3::new(car_pos.get_x(), 1.2, car_pos.get_z()))
1934                }
1935                4 => {
1936                    let cur_cam: Camera3D = self.get_camera();
1937                    let fwd: Vec3 = cur_cam.forward();
1938                    let right: Vec3 = cur_cam.right();
1939                    let moved: Vec3 = cur_cam
1940                        .get_position()
1941                        .add(fwd.scale(throttle * 18.0 * dt))
1942                        .add(right.scale(steer * 14.0 * dt));
1943                    let eye: Vec3 = Vec3::new(moved.get_x(), moved.get_y().max(1.5), moved.get_z());
1944                    (eye, eye.add(fwd.scale(16.0)))
1945                }
1946                5 => {
1947                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.28;
1948                    self.set_camera_orbit_rad(orbit);
1949                    let eye: Vec3 = Vec3::new(
1950                        car_pos.get_x() + orbit.sin() * 7.8,
1951                        3.6 + (orbit * 1.5).sin() * 1.4,
1952                        car_pos.get_z() + orbit.cos() * 13.5,
1953                    );
1954                    (eye, Vec3::new(car_pos.get_x(), 1.8, car_pos.get_z() - 3.0))
1955                }
1956                _ => {
1957                    let eye: Vec3 = Vec3::new(
1958                        car_pos.get_x() + yaw.sin() * 12.5,
1959                        6.0,
1960                        car_pos.get_z() + yaw.cos() * 12.5,
1961                    );
1962                    let tgt: Vec3 =
1963                        Vec3::new(car_pos.get_x(), 2.2, car_pos.get_z() - yaw.cos() * 4.0);
1964                    (eye, tgt)
1965                }
1966            };
1967            desired_eye.set_x(desired_eye.get_x().clamp(-9.5, 9.5));
1968            let cam_probe: Aabb3D = Aabb3D::new(
1969                desired_eye.sub(Vec3::splat(0.6)),
1970                desired_eye.add(Vec3::splat(0.6)),
1971            );
1972            if self.collides_with_obstacles(cam_probe, car_idx) {
1973                desired_eye = Vec3::new(
1974                    car_pos.get_x(),
1975                    desired_eye.get_y().max(8.5),
1976                    car_pos.get_z() + 8.0,
1977                );
1978            }
1979            let prev_cam: Camera3D = self.get_camera();
1980            let mut cam: Camera3D = prev_cam;
1981            let smooth: f32 = (dt * 7.0).clamp(0.05, 1.0);
1982            cam.set_position(cam.get_position().lerp(desired_eye, smooth));
1983            let look_dir: Vec3 = look_target.sub(cam.get_position()).normalize();
1984            cam.set_yaw(look_dir.get_z().atan2(look_dir.get_x()));
1985            cam.set_pitch(look_dir.get_y().clamp(-0.92, 0.92).asin());
1986            self.set_camera(cam);
1987            if cam != prev_cam {
1988                self.bump_world_revision();
1989            }
1990        }
1991        for obj in self.get_mut_objects().iter_mut() {
1992            let spin: f32 = obj.get_spin_speed();
1993            if spin.abs() > 0.001 {
1994                let mut tr: Transform3D = obj.get_transform();
1995                tr.set_yaw_rad(tr.get_yaw_rad() + spin * dt);
1996                obj.set_transform(tr);
1997                if obj.get_is_dynamic() {
1998                    any_dynamic_moved = true;
1999                } else {
2000                    any_static_moved = true;
2001                }
2002            }
2003        }
2004        if any_static_moved {
2005            self.set_bvh_dirty(true);
2006        }
2007        if any_dynamic_moved {
2008            self.set_dynamic_bvh_dirty(true);
2009        }
2010        if any_static_moved || any_dynamic_moved {
2011            self.bump_world_revision();
2012        }
2013    }
2014}