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, blend_factor: f32) -> Self {
78        let entry_index: f32 = blend_factor.clamp(0.0, 1.0);
79        Self {
80            position: self.get_position().lerp(other.get_position(), entry_index),
81            yaw_rad: self.get_yaw_rad() + (other.get_yaw_rad() - self.get_yaw_rad()) * entry_index,
82            pitch_rad: self.get_pitch_rad()
83                + (other.get_pitch_rad() - self.get_pitch_rad()) * entry_index,
84            roll_rad: self.get_roll_rad()
85                + (other.get_roll_rad() - self.get_roll_rad()) * entry_index,
86            scale: self.get_scale().lerp(other.get_scale(), entry_index),
87        }
88    }
89
90    /// Interpolates position, scale, and shortest-arc Euler angles between `self` and `other` for render-time snapshot blending.
91    ///
92    /// # Arguments
93    ///
94    /// - `Self` - Previous fixed-step transform.
95    /// - `Self` - Current fixed-step transform.
96    /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
97    ///
98    /// # Returns
99    ///
100    /// - `Self` - Shortest-arc interpolated transform.
101    #[must_use]
102    pub fn lerp_shortest_angle(self, other: Self, blend_factor: f32) -> Self {
103        let entry_index: f32 = blend_factor.clamp(0.0, 1.0);
104        Self {
105            position: self.get_position().lerp(other.get_position(), entry_index),
106            yaw_rad: Self::lerp_angle_rad(self.get_yaw_rad(), other.get_yaw_rad(), entry_index),
107            pitch_rad: Self::lerp_angle_rad(
108                self.get_pitch_rad(),
109                other.get_pitch_rad(),
110                entry_index,
111            ),
112            roll_rad: Self::lerp_angle_rad(self.get_roll_rad(), other.get_roll_rad(), entry_index),
113            scale: self.get_scale().lerp(other.get_scale(), entry_index),
114        }
115    }
116
117    /// Interpolates two angles along the shortest signed angular arc in radians.
118    ///
119    /// # Arguments
120    ///
121    /// - `f32` - Starting angle in radians.
122    /// - `f32` - Target angle in radians.
123    /// - `f32` - Clamped interpolation weight in `[0.0, 1.0]`.
124    ///
125    /// # Returns
126    ///
127    /// - `f32` - Interpolated angle in radians.
128    #[must_use]
129    fn lerp_angle_rad(alpha_val: f32, blue_val: f32, entry_index: f32) -> f32 {
130        let diff: f32 = blue_val - alpha_val;
131        let raw: f32 = diff - (diff / TAU).floor() * TAU;
132        let delta: f32 = if raw > PI { raw - TAU } else { raw };
133        alpha_val + delta * entry_index
134    }
135
136    /// Converts this TRS transform into a column-major `Mat4`.
137    ///
138    /// # Arguments
139    ///
140    /// - `&Self` - Transform reference.
141    ///
142    /// # Returns
143    ///
144    /// - `Mat4` - Model matrix.
145    #[must_use]
146    pub fn to_mat4(&self) -> Mat4 {
147        Mat4::from_trs_euler(
148            self.get_position(),
149            self.get_yaw_rad(),
150            self.get_pitch_rad(),
151            self.get_roll_rad(),
152            self.get_scale(),
153        )
154    }
155
156    /// Computes the exact analytical inverse TRS matrix (`S^-1 * R^T * T^-1`) for object-space raytracing.
157    ///
158    /// # Arguments
159    ///
160    /// - `&Self` - Transform reference.
161    ///
162    /// # Returns
163    ///
164    /// - `Mat4` - Inverse model matrix mapping world space back to local object space.
165    #[must_use]
166    pub fn to_inv_mat4(&self) -> Mat4 {
167        Mat4::inverse_trs_euler(
168            self.get_position(),
169            self.get_yaw_rad(),
170            self.get_pitch_rad(),
171            self.get_roll_rad(),
172            self.get_scale(),
173        )
174    }
175
176    /// Precomputes the inverse-transpose 3x3 normal basis `[col_x, col_y, col_z]` once per object.
177    ///
178    /// # Arguments
179    ///
180    /// - `&Self` - Transform reference.
181    ///
182    /// # Returns
183    ///
184    /// - `[Vec3; 3]` - Inverse-transpose 3x3 normal basis columns.
185    #[must_use]
186    pub fn normal_mat3(&self) -> [Vec3; 3] {
187        Mat4::normal_basis_from_euler_scale(
188            self.get_yaw_rad(),
189            self.get_pitch_rad(),
190            self.get_roll_rad(),
191            self.get_scale(),
192        )
193    }
194
195    /// Rotates vector `v` by this transform's `(yaw, pitch, roll)` Euler orientation.
196    ///
197    /// # Arguments
198    ///
199    /// - `&Self` - Transform reference.
200    /// - `Vec3` - Input vector.
201    ///
202    /// # Returns
203    ///
204    /// - `Vec3` - Rotated vector.
205    #[must_use]
206    fn rotate_vec(&self, vec_value: Vec3) -> Vec3 {
207        let pitch: f32 = self.get_pitch_rad();
208        let roll: f32 = self.get_roll_rad();
209        let yaw: f32 = self.get_yaw_rad();
210        let (cy, sy): (f32, f32) = (yaw.cos(), yaw.sin());
211        if pitch.abs() < 1e-6 && roll.abs() < 1e-6 {
212            return Vec3::new(
213                vec_value.get_x() * cy + vec_value.get_z() * sy,
214                vec_value.get_y(),
215                -vec_value.get_x() * sy + vec_value.get_z() * cy,
216            );
217        }
218        let (cr, sr): (f32, f32) = (roll.cos(), roll.sin());
219        let x1: f32 = vec_value.get_x() * cr - vec_value.get_y() * sr;
220        let y1: f32 = vec_value.get_x() * sr + vec_value.get_y() * cr;
221        let z1: f32 = vec_value.get_z();
222        let (cp, sp): (f32, f32) = (pitch.cos(), pitch.sin());
223        let x2: f32 = x1;
224        let y2: f32 = y1 * cp - z1 * sp;
225        let z2: f32 = y1 * sp + z1 * cp;
226        Vec3::new(x2 * cy + z2 * sy, y2, -x2 * sy + z2 * cy)
227    }
228
229    /// Transforms a local-space 3D point into world space.
230    ///
231    /// # Arguments
232    ///
233    /// - `&Self` - Transform reference.
234    /// - `Vec3` - Local-space point.
235    ///
236    /// # Returns
237    ///
238    /// - `Vec3` - World-space point.
239    #[must_use]
240    pub fn transform_point(&self, vec_value: Vec3) -> Vec3 {
241        let direction_vec: Vec3 = self.get_scale();
242        let scaled: Vec3 = Vec3::new(
243            vec_value.get_x() * direction_vec.get_x(),
244            vec_value.get_y() * direction_vec.get_y(),
245            vec_value.get_z() * direction_vec.get_z(),
246        );
247        self.rotate_vec(scaled).add(self.get_position())
248    }
249
250    /// Rotates a local-space surface normal into world space.
251    ///
252    /// # Arguments
253    ///
254    /// - `&Self` - Transform reference.
255    /// - `Vec3` - Local normal.
256    ///
257    /// # Returns
258    ///
259    /// - `Vec3` - World-space unit normal.
260    #[must_use]
261    pub fn transform_normal(&self, vec_value: Vec3) -> Vec3 {
262        self.rotate_vec(vec_value).normalize()
263    }
264
265    /// Transforms a local `AxisAlignedBox3D` into an enclosing world-space `AxisAlignedBox3D` using Arvo's 18-multiply method (zero 8-corner loop, zero per-corner trigonometry).
266    ///
267    /// # Arguments
268    ///
269    /// - `&Self` - Transform reference.
270    /// - `AxisAlignedBox3D` - Local bounding box.
271    ///
272    /// # Returns
273    ///
274    /// - `AxisAlignedBox3D` - Enclosing world-space bounding box.
275    #[must_use]
276    pub fn transform_bounds(&self, local: AxisAlignedBox3D) -> AxisAlignedBox3D {
277        self.to_mat4().transform_bounds(local)
278    }
279
280    /// Converts a local-space `AxisAlignedBox3D` into a tight world-space oriented bounding box (`OrientedBox3D`) preserving rotation and non-uniform scale without axis-aligned bounding box corner inflation.
281    ///
282    /// # Arguments
283    ///
284    /// - `&Self` - Transform reference.
285    /// - `AxisAlignedBox3D` - Local-space bounding box.
286    ///
287    /// # Returns
288    ///
289    /// - `OrientedBox3D` - Oriented bounding box in world space.
290    #[must_use]
291    pub fn to_oriented_box(&self, local: AxisAlignedBox3D) -> OrientedBox3D {
292        let local_center: Vec3 = local.get_min().add(local.get_max()).scale(0.5);
293        let local_half: Vec3 = local.get_max().sub(local.get_min()).scale(0.5);
294        let vec_value: Vec3 = self.get_scale();
295        let center: Vec3 = self.transform_point(local_center);
296        let ax: Vec3 = self.rotate_vec(Vec3::new(1.0, 0.0, 0.0)).normalize();
297        let ay: Vec3 = self.rotate_vec(Vec3::new(0.0, 1.0, 0.0)).normalize();
298        let az: Vec3 = self.rotate_vec(Vec3::new(0.0, 0.0, 1.0)).normalize();
299        let half_extents: Vec3 = Vec3::new(
300            (local_half.get_x() * vec_value.get_x()).abs().max(1e-4),
301            (local_half.get_y() * vec_value.get_y()).abs().max(1e-4),
302            (local_half.get_z() * vec_value.get_z()).abs().max(1e-4),
303        );
304        OrientedBox3D::new(center, [ax, ay, az], half_extents)
305    }
306}
307
308/// Exact oriented bounding box and 13-axis SAT triangle intersection helpers for `OrientedBox3D`.
309impl OrientedBox3D {
310    /// Constructs an axis-aligned `OrientedBox3D` from a world-space `AxisAlignedBox3D`.
311    ///
312    /// # Arguments
313    ///
314    /// - `AxisAlignedBox3D` - World-space axis-aligned bounding box.
315    ///
316    /// # Returns
317    ///
318    /// - `Self` - Equivalent world-space `OrientedBox3D`.
319    #[must_use]
320    pub fn from_bounds(bounds_rect: AxisAlignedBox3D) -> Self {
321        let center: Vec3 = bounds_rect.get_min().add(bounds_rect.get_max()).scale(0.5);
322        let half: Vec3 = bounds_rect.get_max().sub(bounds_rect.get_min()).scale(0.5);
323        Self::new(
324            center,
325            [
326                Vec3::new(1.0, 0.0, 0.0),
327                Vec3::new(0.0, 1.0, 0.0),
328                Vec3::new(0.0, 0.0, 1.0),
329            ],
330            Vec3::new(
331                half.get_x().abs().max(1e-4),
332                half.get_y().abs().max(1e-4),
333                half.get_z().abs().max(1e-4),
334            ),
335        )
336    }
337
338    /// Computes the tightest enclosing world-space `AxisAlignedBox3D` for broadphase culling.
339    ///
340    /// # Arguments
341    ///
342    /// - `&Self` - Oriented bounding box reference.
343    ///
344    /// # Returns
345    ///
346    /// - `AxisAlignedBox3D` - Enclosing world-space axis-aligned bounding box.
347    #[must_use]
348    pub fn to_world_bounds(&self) -> AxisAlignedBox3D {
349        let vec_value: Vec3 = self.get_center();
350        let axes: [Vec3; 3] = self.get_axes();
351        let height_val: Vec3 = self.get_half_extents();
352        let ex: f32 = axes[0].get_x().abs() * height_val.get_x()
353            + axes[1].get_x().abs() * height_val.get_y()
354            + axes[2].get_x().abs() * height_val.get_z();
355        let ey: f32 = axes[0].get_y().abs() * height_val.get_x()
356            + axes[1].get_y().abs() * height_val.get_y()
357            + axes[2].get_y().abs() * height_val.get_z();
358        let ez: f32 = axes[0].get_z().abs() * height_val.get_x()
359            + axes[1].get_z().abs() * height_val.get_y()
360            + axes[2].get_z().abs() * height_val.get_z();
361        let ext: Vec3 = Vec3::new(ex, ey, ez);
362        AxisAlignedBox3D::new(vec_value.sub(ext), vec_value.add(ext))
363    }
364
365    /// Tests exact 13-axis Akenine-Möller SAT intersection between this `OrientedBox3D` and a world-space triangle `(w0, w1, w2)`.
366    ///
367    /// # Arguments
368    ///
369    /// - `&Self` - Oriented bounding box reference.
370    /// - `Vec3` - Triangle vertex 0 in world space.
371    /// - `Vec3` - Triangle vertex 1 in world space.
372    /// - `Vec3` - Triangle vertex 2 in world space.
373    ///
374    /// # Returns
375    ///
376    /// - `Option<(Vec3, f32, Vec3)>` - `(world_outward_normal, penetration_depth, world_contact_point)` when intersecting.
377    #[must_use]
378    pub fn intersect_triangle_world(
379        &self,
380        w0: Vec3,
381        w1: Vec3,
382        w2: Vec3,
383    ) -> Option<(Vec3, f32, Vec3)> {
384        let vec_value: Vec3 = self.get_center();
385        let axes: [Vec3; 3] = self.get_axes();
386        let height_val: Vec3 = self.get_half_extents();
387        let d0: Vec3 = w0.sub(vec_value);
388        let d1: Vec3 = w1.sub(vec_value);
389        let d2: Vec3 = w2.sub(vec_value);
390        let v0: Vec3 = Vec3::new(d0.dot(axes[0]), d0.dot(axes[1]), d0.dot(axes[2]));
391        let v1: Vec3 = Vec3::new(d1.dot(axes[0]), d1.dot(axes[1]), d1.dot(axes[2]));
392        let v2: Vec3 = Vec3::new(d2.dot(axes[0]), d2.dot(axes[1]), d2.dot(axes[2]));
393        let min_x: f32 = v0.get_x().min(v1.get_x()).min(v2.get_x());
394        let max_x: f32 = v0.get_x().max(v1.get_x()).max(v2.get_x());
395        if min_x >= height_val.get_x() || max_x <= -height_val.get_x() {
396            return None;
397        }
398        let min_y: f32 = v0.get_y().min(v1.get_y()).min(v2.get_y());
399        let max_y: f32 = v0.get_y().max(v1.get_y()).max(v2.get_y());
400        if min_y >= height_val.get_y() || max_y <= -height_val.get_y() {
401            return None;
402        }
403        let min_z: f32 = v0.get_z().min(v1.get_z()).min(v2.get_z());
404        let max_z: f32 = v0.get_z().max(v1.get_z()).max(v2.get_z());
405        if min_z >= height_val.get_z() || max_z <= -height_val.get_z() {
406            return None;
407        }
408        let mut best_pen: f32 = f32::INFINITY;
409        let mut best_local_n: Vec3 = Vec3::new(0.0, 1.0, 0.0);
410        let box_axes: [(f32, f32, f32, Vec3); 3] = [
411            (min_x, max_x, height_val.get_x(), Vec3::new(1.0, 0.0, 0.0)),
412            (min_y, max_y, height_val.get_y(), Vec3::new(0.0, 1.0, 0.0)),
413            (min_z, max_z, height_val.get_z(), Vec3::new(0.0, 0.0, 1.0)),
414        ];
415        for (t_min, t_max, half_e, axis) in box_axes {
416            let pen: f32 = (half_e - t_min).min(t_max + half_e);
417            if pen <= 1e-6 {
418                return None;
419            }
420            if pen < best_pen {
421                best_pen = pen;
422                best_local_n = if t_min + t_max > 0.0 {
423                    axis.scale(-1.0)
424                } else {
425                    axis
426                };
427            }
428        }
429        let e0: Vec3 = v1.sub(v0);
430        let e1: Vec3 = v2.sub(v1);
431        let e2: Vec3 = v0.sub(v2);
432        let face_raw: Vec3 = e0.cross(v2.sub(v0));
433        let face_len_sq: f32 = face_raw.length_sq();
434        if face_len_sq > 1e-12 {
435            let face_n: Vec3 = face_raw.scale(1.0 / face_len_sq.sqrt());
436            let dist: f32 = face_n.dot(v0);
437            let red_val: f32 = height_val.get_x() * face_n.get_x().abs()
438                + height_val.get_y() * face_n.get_y().abs()
439                + height_val.get_z() * face_n.get_z().abs();
440            let pen: f32 = red_val - dist.abs();
441            if pen <= 1e-6 {
442                return None;
443            }
444            if pen < best_pen {
445                best_pen = pen;
446                best_local_n = if dist > 0.0 {
447                    face_n.scale(-1.0)
448                } else {
449                    face_n
450                };
451            }
452        }
453        let edges: [Vec3; 3] = [e0, e1, e2];
454        let unit_axes: [Vec3; 3] = [
455            Vec3::new(1.0, 0.0, 0.0),
456            Vec3::new(0.0, 1.0, 0.0),
457            Vec3::new(0.0, 0.0, 1.0),
458        ];
459        for edge in edges {
460            for u_axis in unit_axes {
461                let raw_a: Vec3 = edge.cross(u_axis);
462                let len_sq: f32 = raw_a.length_sq();
463                if len_sq <= 1e-10 {
464                    continue;
465                }
466                let axis: Vec3 = raw_a.scale(1.0 / len_sq.sqrt());
467                let p0: f32 = v0.dot(axis);
468                let p1: f32 = v1.dot(axis);
469                let p2: f32 = v2.dot(axis);
470                let t_min: f32 = p0.min(p1).min(p2);
471                let t_max: f32 = p0.max(p1).max(p2);
472                let radius_val: f32 = height_val.get_x() * axis.get_x().abs()
473                    + height_val.get_y() * axis.get_y().abs()
474                    + height_val.get_z() * axis.get_z().abs();
475                if t_min >= radius_val || t_max <= -radius_val {
476                    return None;
477                }
478                let pen: f32 = (radius_val - t_min).min(t_max + radius_val);
479                if pen <= 1e-6 {
480                    return None;
481                }
482                if pen < best_pen {
483                    best_pen = pen;
484                    best_local_n = if t_min + t_max > 0.0 {
485                        axis.scale(-1.0)
486                    } else {
487                        axis
488                    };
489                }
490            }
491        }
492        let tri_center: Vec3 = v0.add(v1).add(v2).scale(1.0 / 3.0);
493        let local_contact: Vec3 = Vec3::new(
494            tri_center
495                .get_x()
496                .clamp(-height_val.get_x(), height_val.get_x()),
497            tri_center
498                .get_y()
499                .clamp(-height_val.get_y(), height_val.get_y()),
500            tri_center
501                .get_z()
502                .clamp(-height_val.get_z(), height_val.get_z()),
503        );
504        let world_n: Vec3 = axes[0]
505            .scale(best_local_n.get_x())
506            .add(axes[1].scale(best_local_n.get_y()))
507            .add(axes[2].scale(best_local_n.get_z()))
508            .normalize();
509        let world_contact: Vec3 = vec_value
510            .add(axes[0].scale(local_contact.get_x()))
511            .add(axes[1].scale(local_contact.get_y()))
512            .add(axes[2].scale(local_contact.get_z()));
513        Some((world_n, best_pen, world_contact))
514    }
515}
516
517/// Conversion helpers for `CameraMode3D`.
518impl CameraMode3D {
519    /// Converts a numeric mode index (`0..=5`) into a typed `CameraMode3D`.
520    ///
521    /// # Arguments
522    ///
523    /// - `u8` - Numeric camera mode index.
524    ///
525    /// # Returns
526    ///
527    /// - `Self` - Corresponding `CameraMode3D`.
528    #[must_use]
529    pub const fn from_u8(index: u8) -> Self {
530        match index {
531            1 => Self::Hood,
532            2 => Self::Orbit,
533            3 => Self::Aerial,
534            4 => Self::FreeFly,
535            5 => Self::CinematicDolly,
536            _ => Self::Chase,
537        }
538    }
539
540    /// Converts this `CameraMode3D` into its stable numeric index (`0..=5`).
541    ///
542    /// # Arguments
543    ///
544    /// - `Self` - Camera mode variant.
545    ///
546    /// # Returns
547    ///
548    /// - `u8` - Numeric mode index.
549    #[must_use]
550    pub const fn as_u8(self) -> u8 {
551        match self {
552            Self::Chase => 0,
553            Self::Hood => 1,
554            Self::Orbit => 2,
555            Self::Aerial => 3,
556            Self::FreeFly => 4,
557            Self::CinematicDolly => 5,
558        }
559    }
560}
561
562/// Fluent builder helpers for `SpawnObjectDesc`.
563impl SpawnObjectDesc {
564    /// Creates an object spawn descriptor with identity transform, default PBR material, and BVH ray tracing enabled.
565    ///
566    /// # Arguments
567    ///
568    /// - `&str` - Human-readable object label.
569    /// - `usize` - Registered mesh identifier.
570    ///
571    /// # Returns
572    ///
573    /// - `Self` - Ready spawn descriptor.
574    #[must_use]
575    pub fn new(name: &str, mesh_id: usize) -> Self {
576        Self {
577            name: name.to_string(),
578            mesh_id,
579            transform: Transform3D::default(),
580            material: PbrMaterial::default(),
581            ray_trace_caster: true,
582            spin_speed: 0.0,
583            is_dynamic: false,
584        }
585    }
586
587    /// Sets the world-space transform for the spawned object.
588    ///
589    /// # Arguments
590    ///
591    /// - `Self` - Base descriptor.
592    /// - `Transform3D` - World-space transform.
593    ///
594    /// # Returns
595    ///
596    /// - `Self` - Updated descriptor.
597    #[must_use]
598    pub fn with_transform(mut self, transform: Transform3D) -> Self {
599        self.set_transform(transform);
600        self
601    }
602
603    /// Sets the PBR surface material override for the spawned object.
604    ///
605    /// # Arguments
606    ///
607    /// - `Self` - Base descriptor.
608    /// - `PbrMaterial` - PBR material.
609    ///
610    /// # Returns
611    ///
612    /// - `Self` - Updated descriptor.
613    #[must_use]
614    pub fn with_material(mut self, material: PbrMaterial) -> Self {
615        self.set_material(material);
616        self
617    }
618
619    /// Sets whether this object casts BVH shadows and appears in reflections.
620    ///
621    /// # Arguments
622    ///
623    /// - `Self` - Base descriptor.
624    /// - `bool` - Ray-trace caster toggle.
625    ///
626    /// # Returns
627    ///
628    /// - `Self` - Updated descriptor.
629    #[must_use]
630    pub fn with_ray_trace(mut self, ray_trace_caster: bool) -> Self {
631        self.set_ray_trace_caster(ray_trace_caster);
632        self
633    }
634
635    /// Sets continuous Y-axis spin speed in radians per second.
636    ///
637    /// # Arguments
638    ///
639    /// - `Self` - Base descriptor.
640    /// - `f32` - Spin speed in radians/sec.
641    ///
642    /// # Returns
643    ///
644    /// - `Self` - Updated descriptor.
645    #[must_use]
646    pub fn with_spin(mut self, spin_speed: f32) -> Self {
647        self.set_spin_speed(spin_speed);
648        if spin_speed.abs() > 0.001 {
649            self.set_is_dynamic(true);
650        }
651        self
652    }
653
654    /// Explicitly marks whether this object belongs in the incrementally refitted dynamic BVH.
655    ///
656    /// # Arguments
657    ///
658    /// - `Self` - Base descriptor.
659    /// - `bool` - Dynamic caster flag.
660    ///
661    /// # Returns
662    ///
663    /// - `Self` - Updated descriptor.
664    #[must_use]
665    pub fn with_dynamic(mut self, is_dynamic: bool) -> Self {
666        self.set_is_dynamic(is_dynamic);
667        self
668    }
669}
670
671/// Fluent builder helpers for `ImportModelDesc`.
672impl ImportModelDesc {
673    /// Creates an external model import descriptor with identity transform and default PBR fallback material.
674    ///
675    /// # Arguments
676    ///
677    /// - `ModelFormat` - Interchange format (`Obj` or `GltfJson`).
678    /// - `&str` - Raw model source text.
679    ///
680    /// # Returns
681    ///
682    /// - `Self` - Ready import descriptor.
683    #[must_use]
684    pub fn new(format: ModelFormat, source: &str) -> Self {
685        Self {
686            format,
687            source: source.to_string(),
688            transform: Transform3D::default(),
689            fallback_material: PbrMaterial::default(),
690            spin_speed: 0.0,
691        }
692    }
693
694    /// Sets the placement transform for the imported model.
695    ///
696    /// # Arguments
697    ///
698    /// - `Self` - Base descriptor.
699    /// - `Transform3D` - Placement transform.
700    ///
701    /// # Returns
702    ///
703    /// - `Self` - Updated descriptor.
704    #[must_use]
705    pub fn with_transform(mut self, transform: Transform3D) -> Self {
706        self.set_transform(transform);
707        self
708    }
709
710    /// Sets the fallback PBR material when source omits material metadata.
711    ///
712    /// # Arguments
713    ///
714    /// - `Self` - Base descriptor.
715    /// - `PbrMaterial` - Fallback PBR material.
716    ///
717    /// # Returns
718    ///
719    /// - `Self` - Updated descriptor.
720    #[must_use]
721    pub fn with_material(mut self, fallback_material: PbrMaterial) -> Self {
722        self.set_fallback_material(fallback_material);
723        self
724    }
725
726    /// Sets continuous Y-axis turntable spin speed in radians per second.
727    ///
728    /// # Arguments
729    ///
730    /// - `Self` - Base descriptor.
731    /// - `f32` - Spin speed in radians/sec.
732    ///
733    /// # Returns
734    ///
735    /// - `Self` - Updated descriptor.
736    #[must_use]
737    pub fn with_spin(mut self, spin_speed: f32) -> Self {
738        self.set_spin_speed(spin_speed);
739        self
740    }
741}
742
743/// Dynamic Time-of-Day sun and atmospheric sky lighting for `DirectionalLight3D`.
744impl DirectionalLight3D {
745    /// Computes physically inspired sun direction, sun color, and sky colors for `hour` in `[0.0, 24.0]`.
746    ///
747    /// # Arguments
748    ///
749    /// - `f32` - Hour of day (`6.0` dawn, `12.0` noon, `17.5` golden sunset, `22.0` neon night).
750    ///
751    /// # Returns
752    ///
753    /// - `Self` - Updated atmospheric directional light.
754    #[must_use]
755    pub fn from_time_of_day(hour: f32) -> Self {
756        let height_val: f32 = hour.rem_euclid(24.0);
757        let elev_angle: f32 = ((height_val - 6.0) / 12.0 * PI).clamp(-0.35, 3.49);
758        let sun_y: f32 = elev_angle.sin();
759        let sun_x: f32 = elev_angle.cos();
760        let dir: Vec3 = Vec3::new(-sun_x * 0.62, sun_y.max(0.22), -0.78).normalize();
761        if (7.5..=16.5).contains(&height_val) {
762            Self {
763                direction: dir,
764                color: Vec3::new(2.35, 2.18, 1.96),
765                sky_zenith: Vec3::new(0.08, 0.24, 0.64),
766                sky_horizon: Vec3::new(0.46, 0.66, 0.88),
767                time_of_day: height_val,
768            }
769        } else if (5.5..7.5).contains(&height_val) || (16.5..19.5).contains(&height_val) {
770            Self {
771                direction: Vec3::new(-0.14, 0.165, -0.976).normalize(),
772                color: Vec3::new(2.85, 1.42, 0.66),
773                sky_zenith: Vec3::new(0.028, 0.038, 0.155),
774                sky_horizon: Vec3::new(0.62, 0.24, 0.22),
775                time_of_day: height_val,
776            }
777        } else {
778            Self {
779                direction: Vec3::new(-0.36, 0.56, -0.74).normalize(),
780                color: Vec3::new(0.52, 0.68, 1.22),
781                sky_zenith: Vec3::new(0.012, 0.022, 0.068),
782                sky_horizon: Vec3::new(0.068, 0.115, 0.235),
783                time_of_day: height_val,
784            }
785        }
786    }
787}
788
789/// Default golden-sunset directional light.
790impl Default for DirectionalLight3D {
791    /// Creates a golden-hour sunset sun configuration.
792    ///
793    /// # Returns
794    ///
795    /// - `Self` - Sunset `DirectionalLight3D`.
796    fn default() -> Self {
797        Self::from_time_of_day(17.2)
798    }
799}
800
801/// Default empty 3D open world.
802impl Default for World3D {
803    /// Creates an empty `World3D` with 64m chunk streaming enabled.
804    ///
805    /// # Returns
806    ///
807    /// - `Self` - Empty `World3D`.
808    fn default() -> Self {
809        Self {
810            mesh_library: Vec::new(),
811            objects: Vec::new(),
812            camera: Camera3D::default(),
813            sun: DirectionalLight3D::default(),
814            bvh: Bvh3D::default(),
815            dynamic_bvh: Bvh3D::default(),
816            mesh_local_bvhs: Vec::new(),
817            dynamic_instances: Vec::new(),
818            bvh_dirty: true,
819            dynamic_bvh_dirty: true,
820            dynamic_topology_dirty: true,
821            static_bvh_rebuilds: 0,
822            dynamic_bvh_refits: 0,
823            dynamic_bvh_rebuilds: 0,
824            world_revision: 1,
825            dynamic_tris_scratch: Vec::new(),
826            chunk_size: 64.0,
827            player_vehicle_index: None,
828            imported_model_count: 0,
829            camera_mode: 0,
830            camera_orbit_rad: 0.4,
831            point_lights: Vec::new(),
832            spot_lights: Vec::new(),
833            niagara: NiagaraSystem3D::default(),
834            atmosphere_preset: 0,
835            traffic_vehicles: Vec::new(),
836            world_time_secs: 0.0,
837        }
838    }
839}
840
841/// Open-world construction, model importing, BVH rebuild, and live vehicle/camera simulation for `World3D`.
842impl World3D {
843    /// Registers a `MeshLodChain` in the instancing library and returns its `mesh_id`.
844    ///
845    /// # Arguments
846    ///
847    /// - `&Self` - Mutable world.
848    /// - `MeshLodChain` - Multi-level LOD mesh chain.
849    ///
850    /// # Returns
851    ///
852    /// - `usize` - Assigned `mesh_id`.
853    pub fn register_mesh(&mut self, chain: MeshLodChain) -> usize {
854        let id: usize = self.get_mesh_library().len();
855        self.get_mut_mesh_library().push(chain);
856        id
857    }
858
859    /// Spawns an instanced `SceneObject3D` referencing `mesh_id` into its spatial world chunk.
860    ///
861    /// # Arguments
862    ///
863    /// - `&Self` - Mutable world.
864    /// - `&str` - Object name.
865    /// - `usize` - Registered `mesh_id`.
866    /// - `Transform3D` - World transform.
867    /// - `PbrMaterial` - Surface PBR material.
868    /// - `bool` - Whether this object participates in BVH ray tracing.
869    ///
870    /// # Returns
871    ///
872    /// - `usize` - Index of the spawned `SceneObject3D`.
873    pub fn spawn_object(
874        &mut self,
875        name: &str,
876        mesh_id: usize,
877        transform: Transform3D,
878        material: PbrMaterial,
879        ray_trace_caster: bool,
880    ) -> usize {
881        let local_bounds: AxisAlignedBox3D = self
882            .get_mesh_library()
883            .get(mesh_id)
884            .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
885            .map(Mesh3D::get_bounds)
886            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
887        let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
888        let cs: f32 = self.get_chunk_size().max(8.0);
889        let pos: Vec3 = transform.get_position();
890        let chunk_coord: (i32, i32) = (
891            (pos.get_x() / cs).floor() as i32,
892            (pos.get_z() / cs).floor() as i32,
893        );
894        let idx: usize = self.get_objects().len();
895        self.get_mut_objects().push(SceneObject3D {
896            name: name.to_string(),
897            mesh_id,
898            transform,
899            material,
900            world_bounds,
901            chunk_coord,
902            ray_trace_caster,
903            spin_speed: 0.0,
904            is_dynamic: false,
905            teleport_epoch: 0,
906        });
907        if ray_trace_caster {
908            self.set_bvh_dirty(true);
909        }
910        self.bump_world_revision();
911        idx
912    }
913
914    /// Increments the 3D world revision counter so 3D render caches invalidate independently of UI HUD updates.
915    ///
916    /// # Arguments
917    ///
918    /// - `&Self` - Mutable world.
919    pub fn bump_world_revision(&mut self) {
920        let next: u64 = self.get_world_revision().wrapping_add(1);
921        self.set_world_revision(next);
922    }
923
924    /// Marks object `obj_idx` as static or dynamic, routing its triangles between the static BVH and incrementally refitted dynamic BVH.
925    ///
926    /// # Arguments
927    ///
928    /// - `&Self` - Mutable world.
929    /// - `usize` - Target object index in `objects`.
930    /// - `bool` - `true` for dynamic BVH routing, `false` for static BVH routing.
931    ///
932    /// # Returns
933    ///
934    /// - `bool` - `true` when `obj_idx` existed and was updated.
935    pub fn set_object_dynamic(&mut self, obj_idx: usize, is_dynamic: bool) -> bool {
936        let Some(obj) = self.get_mut_objects().get_mut(obj_idx) else {
937            return false;
938        };
939        if obj.get_is_dynamic() != is_dynamic {
940            obj.set_is_dynamic(is_dynamic);
941            if obj.get_ray_trace_caster() {
942                self.set_bvh_dirty(true);
943                self.set_dynamic_bvh_dirty(true);
944                self.set_dynamic_topology_dirty(true);
945            }
946            self.bump_world_revision();
947        }
948        true
949    }
950
951    /// Teleports object `obj_idx` to `transform`, incrementing `teleport_epoch` so snapshot interpolation snaps instead of sweeping.
952    ///
953    /// # Arguments
954    ///
955    /// - `&Self` - Mutable world.
956    /// - `usize` - Target object index in `objects`.
957    /// - `Transform3D` - Destination world transform.
958    ///
959    /// # Returns
960    ///
961    /// - `bool` - `true` when `obj_idx` existed and was teleported.
962    pub fn teleport_object(&mut self, obj_idx: usize, transform: Transform3D) -> bool {
963        let Some((mesh_id, ray_caster, is_dynamic)) =
964            self.get_objects().get(obj_idx).map(|obj: &SceneObject3D| {
965                (
966                    obj.get_mesh_id(),
967                    obj.get_ray_trace_caster(),
968                    obj.get_is_dynamic(),
969                )
970            })
971        else {
972            return false;
973        };
974        let local_bounds: AxisAlignedBox3D = self
975            .get_mesh_library()
976            .get(mesh_id)
977            .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
978            .map(Mesh3D::get_bounds)
979            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
980        let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
981        if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
982            obj.set_transform(transform);
983            obj.set_world_bounds(world_bounds);
984            let next_epoch: u32 = obj.get_teleport_epoch().wrapping_add(1);
985            obj.set_teleport_epoch(next_epoch);
986        }
987        if ray_caster {
988            if is_dynamic {
989                self.set_dynamic_bvh_dirty(true);
990            } else {
991                self.set_bvh_dirty(true);
992            }
993        }
994        self.bump_world_revision();
995        true
996    }
997
998    /// Imports an external `.obj` or `.gltf` model directly into the live 3D world and returns import telemetry.
999    ///
1000    /// # Arguments
1001    ///
1002    /// - `&Self` - Mutable world.
1003    /// - `ModelFormat` - Source model format.
1004    /// - `&str` - Raw `.obj` or `.gltf` text content.
1005    /// - `Transform3D` - Placement transform in the 3D scene.
1006    /// - `PbrMaterial` - Fallback PBR material.
1007    /// - `f32` - Optional continuous Y-spin speed in radians/sec.
1008    ///
1009    /// # Returns
1010    ///
1011    /// - `Result<ImportedModel3D, String>` - Imported model summary or parse error.
1012    pub fn import_model(
1013        &mut self,
1014        format: ModelFormat,
1015        source: &str,
1016        transform: Transform3D,
1017        fallback_material: PbrMaterial,
1018        spin_speed: f32,
1019    ) -> Result<ImportedModel3D, String> {
1020        let imported: ImportedModel3D = ModelImporter3D::import(format, source, fallback_material)?;
1021        let model_name: String = imported.get_name().clone();
1022        for (item_index, chain) in imported.get_meshes().iter().cloned().enumerate() {
1023            let mat: PbrMaterial = chain
1024                .get_levels()
1025                .first()
1026                .map(Mesh3D::get_material)
1027                .unwrap_or(fallback_material);
1028            let mid: usize = self.register_mesh(chain);
1029            let obj_idx: usize = self.spawn_object(
1030                &format!("{model_name}_{item_index}"),
1031                mid,
1032                transform,
1033                mat,
1034                true,
1035            );
1036            if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
1037                obj.set_spin_speed(spin_speed);
1038            }
1039            if spin_speed.abs() > 0.001 {
1040                let _: bool = self.set_object_dynamic(obj_idx, true);
1041            }
1042        }
1043        let next_cnt: usize = self.get_imported_model_count().saturating_add(1);
1044        self.set_imported_model_count(next_cnt);
1045        Ok(imported)
1046    }
1047
1048    /// Spawns an object from a fluent `SpawnObjectDesc`.
1049    ///
1050    /// # Arguments
1051    ///
1052    /// - `&Self` - Mutable world.
1053    /// - `&SpawnObjectDesc` - Spawn descriptor.
1054    ///
1055    /// # Returns
1056    ///
1057    /// - `usize` - Spawned object index.
1058    pub fn spawn_with(&mut self, desc: &SpawnObjectDesc) -> usize {
1059        let idx: usize = self.spawn_object(
1060            desc.get_name(),
1061            desc.get_mesh_id(),
1062            desc.get_transform(),
1063            desc.get_material(),
1064            desc.get_ray_trace_caster(),
1065        );
1066        if let Some(obj) = self.get_mut_objects().get_mut(idx) {
1067            obj.set_spin_speed(desc.get_spin_speed());
1068        }
1069        if desc.get_is_dynamic() || desc.get_spin_speed().abs() > 0.001 {
1070            let _: bool = self.set_object_dynamic(idx, true);
1071        }
1072        idx
1073    }
1074
1075    /// Imports an external `.obj` or `.gltf` model using a fluent `ImportModelDesc`.
1076    ///
1077    /// # Arguments
1078    ///
1079    /// - `&Self` - Mutable world.
1080    /// - `&ImportModelDesc` - Import descriptor.
1081    ///
1082    /// # Returns
1083    ///
1084    /// - `Result<ImportedModel3D, String>` - Imported model telemetry or parse error.
1085    pub fn import_with(&mut self, desc: &ImportModelDesc) -> Result<ImportedModel3D, String> {
1086        self.import_model(
1087            desc.get_format(),
1088            desc.get_source(),
1089            desc.get_transform(),
1090            desc.get_fallback_material(),
1091            desc.get_spin_speed(),
1092        )
1093    }
1094
1095    /// Returns the typed `CameraMode3D` currently active in this world.
1096    ///
1097    /// # Arguments
1098    ///
1099    /// - `&Self` - World reference.
1100    ///
1101    /// # Returns
1102    ///
1103    /// - `CameraMode3D` - Active typed camera controller mode.
1104    #[must_use]
1105    pub fn active_camera_mode(&self) -> CameraMode3D {
1106        CameraMode3D::from_u8(self.get_camera_mode())
1107    }
1108
1109    /// Sets the active 3D camera controller using a typed `CameraMode3D`.
1110    ///
1111    /// # Arguments
1112    ///
1113    /// - `&Self` - Mutable world.
1114    /// - `CameraMode3D` - Desired camera controller mode.
1115    pub fn set_camera_mode_enum(&mut self, mode: CameraMode3D) {
1116        self.set_camera_mode(mode.as_u8());
1117    }
1118
1119    /// Collects world-space triangles for all ray-trace casters matching `dynamic_filter` into `out_tris`.
1120    ///
1121    /// # Arguments
1122    ///
1123    /// - `&[SceneObject3D]` - World object slice.
1124    /// - `&[MeshLodChain]` - Registered mesh library slice.
1125    /// - `bool` - `true` to gather dynamic casters, `false` to gather static casters.
1126    /// - `&mut Vec<BvhTriangle>` - Destination triangle buffer cleared and populated in place.
1127    fn collect_caster_triangles(
1128        objects: &[SceneObject3D],
1129        mesh_library: &[MeshLodChain],
1130        dynamic_filter: bool,
1131        out_tris: &mut Vec<BvhTriangle>,
1132    ) {
1133        out_tris.clear();
1134        for obj in objects.iter() {
1135            if !obj.get_ray_trace_caster() || obj.get_is_dynamic() != dynamic_filter {
1136                continue;
1137            }
1138            let Some(chain) = mesh_library.get(obj.get_mesh_id()) else {
1139                continue;
1140            };
1141            let Some(mesh) = chain.get_levels().first() else {
1142                continue;
1143            };
1144            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1145            let model_m: Mat4 = obj.get_transform().to_mat4();
1146            let mat: PbrMaterial = obj.get_material();
1147            for (tri_idx, tri) in mesh.get_indices().iter().enumerate() {
1148                let (i0, i1, i2): (usize, usize, usize) =
1149                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1150                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1151                    let p0: Vec3 = model_m.mul_point3(verts[i0].get_position());
1152                    let p1: Vec3 = model_m.mul_point3(verts[i1].get_position());
1153                    let p2: Vec3 = model_m.mul_point3(verts[i2].get_position());
1154                    let (tri_mat, mat_slot): (PbrMaterial, u16) =
1155                        mesh.resolve_triangle_material(tri_idx, mat);
1156                    out_tris.push(BvhTriangle::from_points_with_slot(
1157                        p0, p1, p2, tri_mat, mat_slot,
1158                    ));
1159                }
1160            }
1161        }
1162    }
1163
1164    /// Synchronizes the split static and dynamic BVH acceleration structures, refitting moving dynamic casters in O(N) without rebuilding static world geometry.
1165    ///
1166    /// # Arguments
1167    ///
1168    /// - `&Self` - Mutable world.
1169    pub fn ensure_bvh(&mut self) {
1170        if self.get_bvh_dirty() {
1171            let mut static_tris: Vec<BvhTriangle> = Vec::new();
1172            Self::collect_caster_triangles(
1173                self.get_objects().as_slice(),
1174                self.get_mesh_library().as_slice(),
1175                false,
1176                &mut static_tris,
1177            );
1178            self.set_bvh(Bvh3D::build(static_tris));
1179            self.set_bvh_dirty(false);
1180            let next_static: u64 = self.get_static_bvh_rebuilds().saturating_add(1);
1181            self.set_static_bvh_rebuilds(next_static);
1182        }
1183        if self.get_dynamic_bvh_dirty() {
1184            let topology_dirty: bool = self.get_dynamic_topology_dirty();
1185            let Self {
1186                objects,
1187                mesh_library,
1188                dynamic_bvh,
1189                dynamic_tris_scratch,
1190                dynamic_bvh_dirty,
1191                dynamic_topology_dirty,
1192                dynamic_bvh_refits,
1193                dynamic_bvh_rebuilds,
1194                ..
1195            } = self;
1196            Self::collect_caster_triangles(
1197                objects.as_slice(),
1198                mesh_library.as_slice(),
1199                true,
1200                dynamic_tris_scratch,
1201            );
1202            if dynamic_tris_scratch.is_empty() {
1203                dynamic_bvh.rebuild_in_place(&[]);
1204            } else if !topology_dirty
1205                && dynamic_bvh.refit_from_source(dynamic_tris_scratch.as_slice())
1206            {
1207                let check_degraded: bool = ((*dynamic_bvh_refits + 1) & 15) == 0;
1208                if check_degraded && dynamic_bvh.needs_rebuild_after_refit(3.5) {
1209                    dynamic_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
1210                    *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
1211                } else {
1212                    *dynamic_bvh_refits = dynamic_bvh_refits.saturating_add(1);
1213                }
1214            } else {
1215                dynamic_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
1216                *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
1217            }
1218            *dynamic_bvh_dirty = false;
1219            *dynamic_topology_dirty = false;
1220        }
1221        self.sync_dynamic_ray_instances();
1222    }
1223
1224    /// Lazily constructs local-space BVH4/BVH8 trees for dynamic meshes and updates `dynamic_instances` from current object transforms with zero BVH rebuilds.
1225    ///
1226    /// # Arguments
1227    ///
1228    /// - `&Self` - Mutable world reference.
1229    pub fn sync_dynamic_ray_instances(&mut self) {
1230        let Self {
1231            mesh_library,
1232            objects,
1233            mesh_local_bvhs,
1234            dynamic_instances,
1235            ..
1236        } = self;
1237        if mesh_local_bvhs.len() < mesh_library.len() {
1238            mesh_local_bvhs.resize_with(mesh_library.len(), || None);
1239        }
1240        dynamic_instances.clear();
1241        for (obj_idx, obj) in objects.iter().enumerate() {
1242            if !obj.get_ray_trace_caster() || !obj.get_is_dynamic() {
1243                continue;
1244            }
1245            let mesh_id: usize = obj.get_mesh_id();
1246            let Some(chain) = mesh_library.get(mesh_id) else {
1247                continue;
1248            };
1249            let Some(mesh) = chain.get_levels().first() else {
1250                continue;
1251            };
1252            if mesh_local_bvhs[mesh_id].is_none() {
1253                let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1254                let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
1255                let mut local_tris: Vec<BvhTriangle> = Vec::with_capacity(indices.len());
1256                let neutral: PbrMaterial = PbrMaterial::default();
1257                for (tri_idx, tri) in indices.iter().enumerate() {
1258                    let (i0, i1, i2): (usize, usize, usize) =
1259                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1260                    if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1261                        let (tri_mat, mat_slot): (PbrMaterial, u16) =
1262                            mesh.resolve_triangle_material(tri_idx, neutral);
1263                        local_tris.push(BvhTriangle::from_points_with_slot(
1264                            verts[i0].get_position(),
1265                            verts[i1].get_position(),
1266                            verts[i2].get_position(),
1267                            tri_mat,
1268                            mat_slot,
1269                        ));
1270                    }
1271                }
1272                mesh_local_bvhs[mesh_id] = Some(Bvh3D::build(local_tris));
1273            }
1274            let transform_val: Transform3D = obj.get_transform();
1275            dynamic_instances.push(DynamicRayInstance {
1276                obj_idx,
1277                mesh_id,
1278                world_bounds: obj.get_world_bounds(),
1279                inv_model: transform_val.to_inv_mat4(),
1280                normal_basis: transform_val.normal_mat3(),
1281                material: obj.get_material(),
1282            });
1283        }
1284    }
1285
1286    /// Updates only the inverse-model transform, normal basis, and world axis-aligned bounding box of an existing dynamic instance without rebuilding any BVH.
1287    ///
1288    /// # Arguments
1289    ///
1290    /// - `&Self` - Mutable world reference.
1291    /// - `usize` - Scene object index.
1292    /// - `Transform3D` - Interpolated world transform.
1293    /// - `AxisAlignedBox3D` - Interpolated world axis-aligned bounding box.
1294    pub(crate) fn override_dynamic_instance_pose(
1295        &mut self,
1296        obj_idx: usize,
1297        transform: Transform3D,
1298        world_bounds: AxisAlignedBox3D,
1299    ) {
1300        let Self {
1301            dynamic_instances, ..
1302        } = self;
1303        for inst in dynamic_instances.iter_mut() {
1304            if inst.obj_idx == obj_idx {
1305                inst.world_bounds = world_bounds;
1306                inst.inv_model = transform.to_inv_mat4();
1307                inst.normal_basis = transform.normal_mat3();
1308                return;
1309            }
1310        }
1311    }
1312
1313    /// Traces a shadow ray against object-space dynamic instances via inverse interpolated `Mat4` with zero dynamic BVH rebuilds.
1314    ///
1315    /// # Arguments
1316    ///
1317    /// - `&[DynamicRayInstance]` - Active dynamic raytracing instances.
1318    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1319    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1320    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1321    /// - `&mut u32` - Per-thread local occluder triangle hint.
1322    ///
1323    /// # Returns
1324    ///
1325    /// - `bool` - `true` if occluded by any dynamic object at its current or interpolated pose.
1326    #[inline(always)]
1327    #[must_use]
1328    pub(crate) fn trace_any_shadow_dynamic_instances(
1329        instances: &[DynamicRayInstance],
1330        local_bvhs: &[Option<Bvh3D>],
1331        ray: (Vec3, Vec3, Vec3),
1332        bounds: (f32, f32),
1333        dyn_cache: &mut u32,
1334    ) -> bool {
1335        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1336        let (t_min, t_max): (f32, f32) = bounds;
1337        for inst in instances.iter() {
1338            if !inst
1339                .world_bounds
1340                .intersect_ray_near(origin, inv_dir, t_min, t_max)
1341                .is_finite()
1342            {
1343                continue;
1344            }
1345            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1346                continue;
1347            };
1348            let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
1349            let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
1350            let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
1351            if local_bvh
1352                .trace_any_shadow_cached(local_orig, local_dir, local_inv, t_min, t_max, dyn_cache)
1353            {
1354                return true;
1355            }
1356        }
1357        false
1358    }
1359
1360    /// Traces a coherent 4-ray shadow packet against static BVH and object-space inverse-interpolated dynamic instances.
1361    ///
1362    /// # Arguments
1363    ///
1364    /// - `&Bvh3D` - Static world BVH4/BVH8.
1365    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1366    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1367    /// - `&RayPacket4` - Coherent 4-ray shadow packet.
1368    /// - `u8` - 4-bit mask of active rays to trace.
1369    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1370    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder hints.
1371    ///
1372    /// # Returns
1373    ///
1374    /// - `u8` - 4-bit mask of occluded rays.
1375    #[inline(always)]
1376    #[must_use]
1377    pub(crate) fn trace_any_shadow_packet4_with_instances(
1378        static_bvh: &Bvh3D,
1379        instances: &[DynamicRayInstance],
1380        local_bvhs: &[Option<Bvh3D>],
1381        pkt: &RayPacket4,
1382        active_mask: u8,
1383        bounds: (f32, f32),
1384        caches: (&mut u32, &mut u32),
1385    ) -> u8 {
1386        let (t_min, t_max): (f32, f32) = bounds;
1387        let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
1388        let mut occluded: u8 =
1389            static_bvh.trace_any_shadow_packet4(pkt, active_mask, t_min, t_max, static_cache);
1390        let mut rem: u8 = active_mask & !occluded;
1391        if rem == 0 || instances.is_empty() {
1392            return occluded;
1393        }
1394        for inst in instances.iter() {
1395            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1396                continue;
1397            };
1398            let mut hit_box_mask: u8 = 0;
1399            let mut check: u8 = rem;
1400            while check != 0 {
1401                let red_val: usize = check.trailing_zeros() as usize;
1402                check &= check - 1;
1403                let orig_r: Vec3 = Vec3::new(pkt.ox[red_val], pkt.oy[red_val], pkt.oz[red_val]);
1404                let inv_r: Vec3 = Vec3::new(pkt.ix[red_val], pkt.iy[red_val], pkt.iz[red_val]);
1405                if inst
1406                    .world_bounds
1407                    .intersect_ray_near(orig_r, inv_r, t_min, t_max)
1408                    .is_finite()
1409                {
1410                    hit_box_mask |= 1_u8 << red_val;
1411                }
1412            }
1413            if hit_box_mask == 0 {
1414                continue;
1415            }
1416            let mut local_pkt: RayPacket4 = *pkt;
1417            let mut tr_mask: u8 = hit_box_mask;
1418            while tr_mask != 0 {
1419                let radius_val: usize = tr_mask.trailing_zeros() as usize;
1420                tr_mask &= tr_mask - 1;
1421                let lo: Vec3 = inst.inv_model.mul_point3(Vec3::new(
1422                    pkt.ox[radius_val],
1423                    pkt.oy[radius_val],
1424                    pkt.oz[radius_val],
1425                ));
1426                let ld: Vec3 = inst.inv_model.mul_vec3(Vec3::new(
1427                    pkt.dx[radius_val],
1428                    pkt.dy[radius_val],
1429                    pkt.dz[radius_val],
1430                ));
1431                let li: Vec3 = Ray3D::safe_inv_vec(ld);
1432                local_pkt.ox[radius_val] = lo.get_x();
1433                local_pkt.oy[radius_val] = lo.get_y();
1434                local_pkt.oz[radius_val] = lo.get_z();
1435                local_pkt.dx[radius_val] = ld.get_x();
1436                local_pkt.dy[radius_val] = ld.get_y();
1437                local_pkt.dz[radius_val] = ld.get_z();
1438                local_pkt.ix[radius_val] = li.get_x();
1439                local_pkt.iy[radius_val] = li.get_y();
1440                local_pkt.iz[radius_val] = li.get_z();
1441            }
1442            let dyn_occ: u8 = local_bvh.trace_any_shadow_packet4(
1443                &local_pkt,
1444                hit_box_mask,
1445                t_min,
1446                t_max,
1447                dyn_cache,
1448            );
1449            occluded |= dyn_occ;
1450            rem &= !dyn_occ;
1451            if rem == 0 {
1452                break;
1453            }
1454        }
1455        occluded
1456    }
1457
1458    /// Traces a shadow/occlusion ray across static BVH and object-space inverse-interpolated dynamic instances.
1459    ///
1460    /// # Arguments
1461    ///
1462    /// - `&Bvh3D` - Static world BVH.
1463    /// - `&[DynamicRayInstance]` - Active dynamic raytracing instances.
1464    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1465    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1466    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1467    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder hints.
1468    ///
1469    /// # Returns
1470    ///
1471    /// - `bool` - `true` when occluded by static or dynamic geometry.
1472    #[inline(always)]
1473    #[must_use]
1474    pub(crate) fn trace_any_shadow_with_instances(
1475        static_bvh: &Bvh3D,
1476        instances: &[DynamicRayInstance],
1477        local_bvhs: &[Option<Bvh3D>],
1478        ray: (Vec3, Vec3, Vec3),
1479        bounds: (f32, f32),
1480        caches: (&mut u32, &mut u32),
1481    ) -> bool {
1482        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1483        let (t_min, t_max): (f32, f32) = bounds;
1484        let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
1485        if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
1486            return true;
1487        }
1488        if !instances.is_empty() {
1489            return Self::trace_any_shadow_dynamic_instances(
1490                instances, local_bvhs, ray, bounds, dyn_cache,
1491            );
1492        }
1493        false
1494    }
1495
1496    /// Traces a reflection/GI ray across static BVH and object-space inverse-interpolated dynamic instances, returning `(distance, world_normal, material)`.
1497    ///
1498    /// # Arguments
1499    ///
1500    /// - `&Bvh3D` - Static world BVH.
1501    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1502    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1503    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1504    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1505    ///
1506    /// # Returns
1507    ///
1508    /// - `Option<(f32, Vec3, PbrMaterial)>` - Closest hit distance, world-space unit normal, and PBR material.
1509    #[inline(always)]
1510    #[must_use]
1511    pub(crate) fn trace_closest_with_instances(
1512        static_bvh: &Bvh3D,
1513        instances: &[DynamicRayInstance],
1514        local_bvhs: &[Option<Bvh3D>],
1515        ray: (Vec3, Vec3, Vec3),
1516        bounds: (f32, f32),
1517    ) -> Option<(f32, Vec3, PbrMaterial)> {
1518        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1519        let (t_min, t_max): (f32, f32) = bounds;
1520        let mut best_t: f32 = t_max;
1521        let mut best_hit: Option<(f32, Vec3, PbrMaterial)> = static_bvh
1522            .trace_closest_raw(origin, dir, inv_dir, t_min, t_max)
1523            .map(|(node_style, si): (f32, usize)| {
1524                let tri: &BvhTriangle = &static_bvh.get_triangles()[si];
1525                best_t = node_style;
1526                (node_style, tri.get_normal(), tri.get_material())
1527            });
1528        for inst in instances.iter() {
1529            if !inst
1530                .world_bounds
1531                .intersect_ray_near(origin, inv_dir, t_min, best_t)
1532                .is_finite()
1533            {
1534                continue;
1535            }
1536            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1537                continue;
1538            };
1539            let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
1540            let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
1541            let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
1542            if let Some((dt, di)) =
1543                local_bvh.trace_closest_raw(local_orig, local_dir, local_inv, t_min, best_t)
1544            {
1545                best_t = dt;
1546                let hit_tri: &BvhTriangle = &local_bvh.get_triangles()[di];
1547                let local_n: Vec3 = hit_tri.get_normal();
1548                let world_n: Vec3 = Mat4::transform_normal_with_basis(local_n, inst.normal_basis);
1549                let hit_mat: PbrMaterial = if hit_tri.get_material_slot() == 0 {
1550                    inst.material
1551                } else {
1552                    hit_tri.get_material()
1553                };
1554                best_hit = Some((dt, world_n, hit_mat));
1555            }
1556        }
1557        best_hit
1558    }
1559
1560    /// Traces a coherent 4-ray closest-hit packet across static BVH and object-space inverse-interpolated dynamic instances.
1561    ///
1562    /// # Arguments
1563    ///
1564    /// - `&Bvh3D` - Static world BVH4/BVH8.
1565    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1566    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1567    /// - `&RayPacket4` - Coherent 4-ray reflection or GI packet.
1568    /// - `u8` - 4-bit mask of active rays.
1569    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1570    ///
1571    /// # Returns
1572    ///
1573    /// - `[Option<(f32, Vec3, PbrMaterial)>; 4]` - Closest hit distance, world normal, and material per lane.
1574    #[inline(always)]
1575    #[must_use]
1576    pub(crate) fn trace_closest_packet4_with_instances(
1577        static_bvh: &Bvh3D,
1578        instances: &[DynamicRayInstance],
1579        local_bvhs: &[Option<Bvh3D>],
1580        pkt: &RayPacket4,
1581        active_mask: u8,
1582        bounds: (f32, f32),
1583    ) -> [Option<(f32, Vec3, PbrMaterial)>; 4] {
1584        let (t_min, t_max): (f32, f32) = bounds;
1585        let mut best_t: [f32; 4] = [t_max; 4];
1586        let mut best_static_idx: [usize; 4] = [usize::MAX; 4];
1587        static_bvh.trace_closest_packet4(
1588            pkt,
1589            active_mask,
1590            t_min,
1591            &mut best_t,
1592            &mut best_static_idx,
1593        );
1594        let static_tris: &[BvhTriangle] = static_bvh.get_triangles().as_slice();
1595        let mut out: [Option<(f32, Vec3, PbrMaterial)>; 4] = [None; 4];
1596        let mut matrix_elems: u8 = active_mask;
1597        while matrix_elems != 0 {
1598            let red_val: usize = matrix_elems.trailing_zeros() as usize;
1599            matrix_elems &= matrix_elems - 1;
1600            let sidx: usize = best_static_idx[red_val];
1601            if sidx != usize::MAX {
1602                let tri: &BvhTriangle = &static_tris[sidx];
1603                out[red_val] = Some((best_t[red_val], tri.get_normal(), tri.get_material()));
1604            }
1605        }
1606        for inst in instances.iter() {
1607            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1608                continue;
1609            };
1610            let mut hit_box_mask: u8 = 0;
1611            let mut check: u8 = active_mask;
1612            while check != 0 {
1613                let radius_val: usize = check.trailing_zeros() as usize;
1614                check &= check - 1;
1615                if inst
1616                    .world_bounds
1617                    .intersect_ray_near(
1618                        Vec3::new(pkt.ox[radius_val], pkt.oy[radius_val], pkt.oz[radius_val]),
1619                        Vec3::new(pkt.ix[radius_val], pkt.iy[radius_val], pkt.iz[radius_val]),
1620                        t_min,
1621                        best_t[radius_val],
1622                    )
1623                    .is_finite()
1624                {
1625                    hit_box_mask |= 1_u8 << radius_val;
1626                }
1627            }
1628            if hit_box_mask == 0 {
1629                continue;
1630            }
1631            let mut local_pkt: RayPacket4 = *pkt;
1632            let mut tr_mask: u8 = hit_box_mask;
1633            while tr_mask != 0 {
1634                let rect_val: usize = tr_mask.trailing_zeros() as usize;
1635                tr_mask &= tr_mask - 1;
1636                let lo: Vec3 = inst.inv_model.mul_point3(Vec3::new(
1637                    pkt.ox[rect_val],
1638                    pkt.oy[rect_val],
1639                    pkt.oz[rect_val],
1640                ));
1641                let ld: Vec3 = inst.inv_model.mul_vec3(Vec3::new(
1642                    pkt.dx[rect_val],
1643                    pkt.dy[rect_val],
1644                    pkt.dz[rect_val],
1645                ));
1646                let li: Vec3 = Ray3D::safe_inv_vec(ld);
1647                local_pkt.ox[rect_val] = lo.get_x();
1648                local_pkt.oy[rect_val] = lo.get_y();
1649                local_pkt.oz[rect_val] = lo.get_z();
1650                local_pkt.dx[rect_val] = ld.get_x();
1651                local_pkt.dy[rect_val] = ld.get_y();
1652                local_pkt.dz[rect_val] = ld.get_z();
1653                local_pkt.ix[rect_val] = li.get_x();
1654                local_pkt.iy[rect_val] = li.get_y();
1655                local_pkt.iz[rect_val] = li.get_z();
1656            }
1657            let mut dyn_idx: [usize; 4] = [usize::MAX; 4];
1658            local_bvh.trace_closest_packet4(
1659                &local_pkt,
1660                hit_box_mask,
1661                t_min,
1662                &mut best_t,
1663                &mut dyn_idx,
1664            );
1665            let local_tris: &[BvhTriangle] = local_bvh.get_triangles().as_slice();
1666            let mut upd: u8 = hit_box_mask;
1667            while upd != 0 {
1668                let row_val: usize = upd.trailing_zeros() as usize;
1669                upd &= upd - 1;
1670                let di: usize = dyn_idx[row_val];
1671                if di != usize::MAX {
1672                    let hit_tri: &BvhTriangle = &local_tris[di];
1673                    let wn: Vec3 =
1674                        Mat4::transform_normal_with_basis(hit_tri.get_normal(), inst.normal_basis);
1675                    let hit_mat: PbrMaterial = if hit_tri.get_material_slot() == 0 {
1676                        inst.material
1677                    } else {
1678                        hit_tri.get_material()
1679                    };
1680                    out[row_val] = Some((best_t[row_val], wn, hit_mat));
1681                }
1682            }
1683        }
1684        out
1685    }
1686
1687    /// Traces a shadow ray using static BVH plus object-space inverse-interpolated dynamic instances.
1688    ///
1689    /// # Arguments
1690    ///
1691    /// - `&Self` - World reference.
1692    /// - `&Ray3D` - World-space shadow ray.
1693    /// - `f32` - Minimum hit distance.
1694    /// - `f32` - Maximum hit distance.
1695    ///
1696    /// # Returns
1697    ///
1698    /// - `bool` - `true` when occluded by static or dynamic geometry at its current/interpolated pose.
1699    #[must_use]
1700    pub fn trace_any_shadow_object_space(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
1701        let Self {
1702            bvh,
1703            dynamic_instances,
1704            mesh_local_bvhs,
1705            ..
1706        } = self;
1707        let mut scale_factor: u32 = u32::MAX;
1708        let mut dc: u32 = u32::MAX;
1709        Self::trace_any_shadow_with_instances(
1710            bvh,
1711            dynamic_instances.as_slice(),
1712            mesh_local_bvhs.as_slice(),
1713            (
1714                ray.get_origin(),
1715                ray.get_direction(),
1716                ray.get_inv_direction(),
1717            ),
1718            (t_min, t_max),
1719            (&mut scale_factor, &mut dc),
1720        )
1721    }
1722
1723    /// Traces a coherent 4-ray closest-hit packet against both the static BVH4 and object-space inverse-interpolated dynamic instances.
1724    ///
1725    /// # Arguments
1726    ///
1727    /// - `&Self` - World reference.
1728    /// - `&RayPacket4` - Coherent 4-ray query packet.
1729    /// - `u8` - 4-bit mask of active rays (`0..=15`).
1730    /// - `f32` - Minimum hit distance.
1731    /// - `f32` - Maximum hit distance.
1732    ///
1733    /// # Returns
1734    ///
1735    /// - `[Option<RayHit3D>; 4]` - Closest hit surface with world normal and material per active lane.
1736    #[must_use]
1737    pub fn trace_closest_packet4(
1738        &self,
1739        pkt: &RayPacket4,
1740        active_mask: u8,
1741        t_min: f32,
1742        t_max: f32,
1743    ) -> [Option<RayHit3D>; 4] {
1744        let Self {
1745            bvh,
1746            dynamic_instances,
1747            mesh_local_bvhs,
1748            ..
1749        } = self;
1750        let raw: [Option<(f32, Vec3, PbrMaterial)>; 4] = Self::trace_closest_packet4_with_instances(
1751            bvh,
1752            dynamic_instances.as_slice(),
1753            mesh_local_bvhs.as_slice(),
1754            pkt,
1755            active_mask,
1756            (t_min, t_max),
1757        );
1758        let mut out: [Option<RayHit3D>; 4] = [None; 4];
1759        for lane in 0..4 {
1760            if let Some((blend_factor, normal, material)) = raw[lane] {
1761                let point: Vec3 = Vec3::new(
1762                    pkt.ox[lane] + pkt.dx[lane] * blend_factor,
1763                    pkt.oy[lane] + pkt.dy[lane] * blend_factor,
1764                    pkt.oz[lane] + pkt.dz[lane] * blend_factor,
1765                );
1766                out[lane] = Some(RayHit3D {
1767                    distance: blend_factor,
1768                    point,
1769                    normal,
1770                    material,
1771                });
1772            }
1773        }
1774        out
1775    }
1776
1777    /// Traces a closest-hit ray using static BVH plus object-space inverse-interpolated dynamic instances.
1778    ///
1779    /// # Arguments
1780    ///
1781    /// - `&Self` - World reference.
1782    /// - `&Ray3D` - World-space query ray.
1783    /// - `f32` - Minimum hit distance.
1784    /// - `f32` - Maximum hit distance.
1785    ///
1786    /// # Returns
1787    ///
1788    /// - `Option<RayHit3D>` - Closest hit surface with world-space normal and material.
1789    #[must_use]
1790    pub fn trace_closest_object_space(
1791        &self,
1792        ray: &Ray3D,
1793        t_min: f32,
1794        t_max: f32,
1795    ) -> Option<RayHit3D> {
1796        let Self {
1797            bvh,
1798            dynamic_instances,
1799            mesh_local_bvhs,
1800            ..
1801        } = self;
1802        let (blend_factor, normal, material): (f32, Vec3, PbrMaterial) =
1803            Self::trace_closest_with_instances(
1804                bvh,
1805                dynamic_instances.as_slice(),
1806                mesh_local_bvhs.as_slice(),
1807                (
1808                    ray.get_origin(),
1809                    ray.get_direction(),
1810                    ray.get_inv_direction(),
1811                ),
1812                (t_min, t_max),
1813            )?;
1814        Some(RayHit3D {
1815            distance: blend_factor,
1816            point: ray
1817                .get_origin()
1818                .add(ray.get_direction().scale(blend_factor)),
1819            normal,
1820            material,
1821        })
1822    }
1823
1824    /// Returns the combined node count across both static and dynamic BVH acceleration trees.
1825    ///
1826    /// # Arguments
1827    ///
1828    /// - `&Self` - World reference.
1829    ///
1830    /// # Returns
1831    ///
1832    /// - `usize` - Total active BVH nodes.
1833    #[must_use]
1834    pub fn total_bvh_nodes(&self) -> usize {
1835        self.get_bvh()
1836            .get_nodes()
1837            .len()
1838            .saturating_add(self.get_dynamic_bvh().get_nodes().len())
1839    }
1840
1841    /// Traces a shadow/occlusion ray across both static and dynamic BVHs using 1-triangle occluder caches.
1842    ///
1843    /// # Arguments
1844    ///
1845    /// - `(&Bvh3D, &Bvh3D)` - `(static_bvh, dynamic_bvh)` pair.
1846    /// - `(Vec3, Vec3, Vec3)` - `(origin, dir, inv_dir)` ray triple.
1847    /// - `(f32, f32)` - `(t_min, t_max)` distance bounds.
1848    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder triangle hints.
1849    ///
1850    /// # Returns
1851    ///
1852    /// - `bool` - `true` if occluded by either static or dynamic geometry.
1853    #[must_use]
1854    pub fn trace_any_shadow_split(
1855        bvhs: (&Bvh3D, &Bvh3D),
1856        ray: (Vec3, Vec3, Vec3),
1857        bounds: (f32, f32),
1858        caches: (&mut u32, &mut u32),
1859    ) -> bool {
1860        let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
1861        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1862        let (t_min, t_max): (f32, f32) = bounds;
1863        let (static_cache, dynamic_cache): (&mut u32, &mut u32) = caches;
1864        if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
1865            return true;
1866        }
1867        if !dynamic_bvh.is_empty() {
1868            return dynamic_bvh.trace_any_shadow_cached(
1869                origin,
1870                dir,
1871                inv_dir,
1872                t_min,
1873                t_max,
1874                dynamic_cache,
1875            );
1876        }
1877        false
1878    }
1879
1880    /// Traces a reflection/GI ray across both static and dynamic BVHs and returns `(distance, is_dynamic, tri_index)`.
1881    ///
1882    /// # Arguments
1883    ///
1884    /// - `(&Bvh3D, &Bvh3D)` - `(static_bvh, dynamic_bvh)` pair.
1885    /// - `(Vec3, Vec3, Vec3)` - `(origin, dir, inv_dir)` ray triple.
1886    /// - `(f32, f32)` - `(t_min, t_max)` distance bounds.
1887    ///
1888    /// # Returns
1889    ///
1890    /// - `Option<(f32, bool, usize)>` - Closest `(t, hit_in_dynamic_bvh, triangle_index)`.
1891    #[must_use]
1892    pub fn trace_closest_split(
1893        bvhs: (&Bvh3D, &Bvh3D),
1894        ray: (Vec3, Vec3, Vec3),
1895        bounds: (f32, f32),
1896    ) -> Option<(f32, bool, usize)> {
1897        let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
1898        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1899        let (t_min, t_max): (f32, f32) = bounds;
1900        let static_hit: Option<(f32, usize)> =
1901            static_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, t_max);
1902        let dyn_limit: f32 =
1903            static_hit.map_or(t_max, |(blend_factor, _): (f32, usize)| blend_factor);
1904        let dynamic_hit: Option<(f32, usize)> = if !dynamic_bvh.is_empty() {
1905            dynamic_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, dyn_limit)
1906        } else {
1907            None
1908        };
1909        match (static_hit, dynamic_hit) {
1910            (_, Some((dt, di))) => Some((dt, true, di)),
1911            (Some((node_style, si)), None) => Some((node_style, false, si)),
1912            (None, None) => None,
1913        }
1914    }
1915
1916    /// Returns the optional player vehicle index.
1917    ///
1918    /// # Arguments
1919    ///
1920    /// - `&Self` - World reference.
1921    ///
1922    /// # Returns
1923    ///
1924    /// - `Option<usize>` - Vehicle index in `objects`.
1925    #[must_use]
1926    pub fn vehicle_index(&self) -> Option<usize> {
1927        let Self {
1928            player_vehicle_index,
1929            ..
1930        } = self;
1931        *player_vehicle_index
1932    }
1933
1934    /// Builds a GTA-inspired open-world neon downtown city with reflective wet asphalt, glass towers, and a drivable sports car.
1935    ///
1936    /// # Returns
1937    ///
1938    /// - `Self` - Populated open-world 3D city ready for real-time PBR + Ray Tracing.
1939    #[must_use]
1940    pub fn create_open_world_city() -> Self {
1941        let mut world: Self = Self::default();
1942        let island_w: f32 = CITY_ISLAND_HALF_X * 2.0;
1943        let island_d: f32 = CITY_ISLAND_Z_MAX - CITY_ISLAND_Z_MIN;
1944        let island_z_center: f32 = (CITY_ISLAND_Z_MIN + CITY_ISLAND_Z_MAX) * 0.5;
1945        let asphalt_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0E131C), 0.08, 0.24, 0.62)
1946            .with_surface_detail(SurfaceDetailMode::RoadSurface);
1947        let road_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::ground_plane(
1948            "wet_asphalt_boulevard",
1949            island_w,
1950            island_d,
1951            24,
1952            asphalt_mat,
1953        )));
1954        let _: usize = world.spawn_object(
1955            "city_ground",
1956            road_mesh,
1957            Transform3D::new(Vec3::new(0.0, 0.0, island_z_center), 0.0, Vec3::splat(1.0)),
1958            asphalt_mat,
1959            false,
1960        );
1961        let ocean_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x063846), 0.05, 0.06, 0.86)
1962            .with_surface_detail(SurfaceDetailMode::OceanWater);
1963        let ocean_mesh: usize =
1964            world.register_mesh(MeshLodChain::from_mesh(Mesh3D::coastal_ocean_ring(
1965                CITY_OCEAN_MESH_NAME,
1966                CITY_OCEAN_SPAN_M,
1967                CITY_ISLAND_HALF_X,
1968                island_d * 0.5,
1969                24,
1970                ocean_mat,
1971            )));
1972        let _: usize = world.spawn_object(
1973            CITY_OCEAN_MESH_NAME,
1974            ocean_mesh,
1975            Transform3D::new(
1976                Vec3::new(0.0, CITY_OCEAN_SURFACE_Y, island_z_center),
1977                0.0,
1978                Vec3::splat(1.0),
1979            ),
1980            ocean_mat,
1981            false,
1982        );
1983        let stud_mat: PbrMaterial = PbrMaterial::neon(Color::hex(0xFBBF24), 0.90);
1984        let stud_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
1985            "lane_stripe",
1986            0.10,
1987            0.018,
1988            0.16,
1989            true,
1990            stud_mat,
1991        )));
1992        for iz in -7..=0 {
1993            let _: usize = world.spawn_object(
1994                &format!("stripe_{iz}"),
1995                stud_mesh,
1996                Transform3D::new(
1997                    Vec3::new(0.0, 0.008, (iz as f32) * 12.0),
1998                    0.0,
1999                    Vec3::splat(1.0),
2000                ),
2001                stud_mat,
2002                false,
2003            );
2004        }
2005        let tower_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2006            "city_skyscraper",
2007            1.0,
2008            1.0,
2009            1.0,
2010            true,
2011            PbrMaterial::default(),
2012        )));
2013        let neon_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2014            "neon_sign",
2015            1.0,
2016            1.0,
2017            1.0,
2018            true,
2019            PbrMaterial::neon(Color::hex(0x38BDF8), 1.8),
2020        )));
2021        let tower_palettes: [PbrMaterial; 4] = [
2022            PbrMaterial::pbr(Color::hex(0x1E293B), 0.72, 0.16, 0.65)
2023                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2024            PbrMaterial::pbr(Color::hex(0x334155), 0.55, 0.24, 0.45)
2025                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2026            PbrMaterial::pbr(Color::hex(0x0F172A), 0.85, 0.10, 0.78)
2027                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2028            PbrMaterial::pbr(Color::hex(0x475569), 0.40, 0.35, 0.35)
2029                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2030        ];
2031        let neon_colors: [Color; 4] = [
2032            Color::hex(0x38BDF8),
2033            Color::hex(0xF43F5E),
2034            Color::hex(0xA855F7),
2035            Color::hex(0x34D399),
2036        ];
2037        let mut idx_counter: usize = 0;
2038        for side in [-1.0_f32, 1.0_f32] {
2039            for row in -4..=4 {
2040                let pos_z: f32 = (row as f32) * 20.0 - 12.0;
2041                let pos_x: f32 = side * (16.5 + ((idx_counter % 3) as f32) * 3.0);
2042                let height_val: f32 = 16.0 + ((idx_counter * 7) % 5) as f32 * 8.5;
2043                let width_val: f32 = 9.0 + ((idx_counter % 2) as f32) * 3.0;
2044                let mat: PbrMaterial = tower_palettes[idx_counter % tower_palettes.len()];
2045                let _: usize = world.spawn_object(
2046                    &format!("tower_{idx_counter}"),
2047                    tower_unit,
2048                    Transform3D::new(
2049                        Vec3::new(pos_x, 0.0, pos_z),
2050                        0.0,
2051                        Vec3::new(width_val, height_val, 11.0),
2052                    ),
2053                    mat,
2054                    true,
2055                );
2056                let neon_mat: PbrMaterial =
2057                    PbrMaterial::neon(neon_colors[idx_counter % neon_colors.len()], 1.9);
2058                let _: usize = world.spawn_object(
2059                    &format!("crown_{idx_counter}"),
2060                    neon_unit,
2061                    Transform3D::new(
2062                        Vec3::new(
2063                            pos_x - side * (width_val * 0.5 + 0.28),
2064                            height_val * 0.72,
2065                            pos_z,
2066                        ),
2067                        0.0,
2068                        Vec3::new(0.36, 1.4, 8.2),
2069                    ),
2070                    neon_mat,
2071                    true,
2072                );
2073                if idx_counter.is_multiple_of(2) {
2074                    let awning_mat: PbrMaterial =
2075                        PbrMaterial::pbr(Color::hex(0x111827), 0.72, 0.22, 0.45);
2076                    let _: usize = world.spawn_object(
2077                        &format!("awning_{idx_counter}"),
2078                        tower_unit,
2079                        Transform3D::new(
2080                            Vec3::new(pos_x - side * (width_val * 0.5 + 0.65), 3.45, pos_z),
2081                            0.0,
2082                            Vec3::new(1.35, 0.28, 9.6),
2083                        ),
2084                        awning_mat,
2085                        false,
2086                    );
2087                    let sign_mat: PbrMaterial =
2088                        PbrMaterial::neon(neon_colors[(idx_counter + 1) % neon_colors.len()], 2.4);
2089                    let _: usize = world.spawn_object(
2090                        &format!("blade_sign_{idx_counter}"),
2091                        neon_unit,
2092                        Transform3D::new(
2093                            Vec3::new(pos_x - side * (width_val * 0.5 + 0.72), 7.2, pos_z + 2.4),
2094                            0.0,
2095                            Vec3::new(0.24, 5.2, 1.35),
2096                        ),
2097                        sign_mat,
2098                        false,
2099                    );
2100                }
2101                if height_val >= 28.0 {
2102                    let spire_mat: PbrMaterial =
2103                        PbrMaterial::pbr(Color::hex(0x1E293B), 0.85, 0.14, 0.75);
2104                    let _: usize = world.spawn_object(
2105                        &format!("penthouse_{idx_counter}"),
2106                        tower_unit,
2107                        Transform3D::new(
2108                            Vec3::new(pos_x, height_val, pos_z),
2109                            0.0,
2110                            Vec3::new(width_val * 0.52, 4.2, 5.8),
2111                        ),
2112                        spire_mat,
2113                        false,
2114                    );
2115                    let _: usize = world.spawn_object(
2116                        &format!("spire_{idx_counter}"),
2117                        neon_unit,
2118                        Transform3D::new(
2119                            Vec3::new(pos_x, height_val + 4.2, pos_z),
2120                            0.0,
2121                            Vec3::new(0.45, 7.5, 0.45),
2122                        ),
2123                        neon_mat,
2124                        false,
2125                    );
2126                }
2127                idx_counter += 1;
2128            }
2129        }
2130        let palm_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::palm_tree(
2131            CITY_PALM_MESH_NAME,
2132        )));
2133        let palm_bark_mat: PbrMaterial = PbrMaterial::dielectric(Color::hex(0x4E392B), 0.88);
2134        let palm_z_positions: [f32; 6] = [1.0, -15.0, -31.0, -47.0, -63.0, -79.0];
2135        for (palm_row, &palm_z) in palm_z_positions.iter().enumerate() {
2136            for side_idx in 0..2usize {
2137                let side_sign: f32 = if side_idx == 0 { -1.0 } else { 1.0 };
2138                let yaw_palm: f32 = (palm_row as f32) * 0.95
2139                    + (side_idx as f32) * 2.1
2140                    + if side_idx == 0 { 0.35 } else { -0.35 };
2141                let scale_palm: f32 = 0.94 + ((palm_row + side_idx) % 3) as f32 * 0.08;
2142                let _: usize = world.spawn_object(
2143                    &format!("palm_{palm_row}_{side_idx}"),
2144                    palm_mesh,
2145                    Transform3D::new(
2146                        Vec3::new(side_sign * 11.45, 0.0, palm_z + (side_idx as f32) * 4.5),
2147                        yaw_palm,
2148                        Vec3::splat(scale_palm),
2149                    ),
2150                    palm_bark_mat,
2151                    false,
2152                );
2153            }
2154        }
2155        let skyline_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0B1120), 0.65, 0.22, 0.48)
2156            .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade);
2157        let skyline_specs: [(f32, f32, f32, f32); 6] = [
2158            (-38.0, -95.0, 13.0, 52.0),
2159            (-24.0, -96.0, 12.0, 62.0),
2160            (24.0, -96.0, 12.0, 60.0),
2161            (38.0, -95.0, 13.0, 54.0),
2162            (-38.0, -46.0, 13.0, 48.0),
2163            (38.0, -46.0, 13.0, 50.0),
2164        ];
2165        for (sky_idx, &(sx, sz, sw, sh)) in skyline_specs.iter().enumerate() {
2166            let _: usize = world.spawn_object(
2167                &format!("{CITY_SKYLINE_MESH_NAME}_{sky_idx}"),
2168                tower_unit,
2169                Transform3D::new(Vec3::new(sx, 0.0, sz), 0.0, Vec3::new(sw, sh, 12.0)),
2170                skyline_mat,
2171                false,
2172            );
2173        }
2174        let seawall_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x334155), 0.14, 0.62, 0.18);
2175        let seawall_specs: [(f32, f32, f32, f32); 4] = [
2176            (0.0, CITY_ISLAND_Z_MIN + 0.75, island_w, 1.5),
2177            (0.0, CITY_ISLAND_Z_MAX - 0.75, island_w, 1.5),
2178            (-CITY_ISLAND_HALF_X + 0.75, island_z_center, 1.5, island_d),
2179            (CITY_ISLAND_HALF_X - 0.75, island_z_center, 1.5, island_d),
2180        ];
2181        for (wall_idx, &(wx, wz, ww, wd)) in seawall_specs.iter().enumerate() {
2182            let _: usize = world.spawn_object(
2183                &format!("{CITY_SEAWALL_MESH_NAME}_{wall_idx}"),
2184                tower_unit,
2185                Transform3D::new(Vec3::new(wx, -1.25, wz), 0.0, Vec3::new(ww, 1.51, wd)),
2186                seawall_mat,
2187                true,
2188            );
2189        }
2190        let arch_frame_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0F172A), 0.82, 0.18, 0.60);
2191        for (arch_idx, &arch_z) in [-22.0_f32, -58.0_f32, -92.0_f32].iter().enumerate() {
2192            let arch_neon: PbrMaterial =
2193                PbrMaterial::neon(neon_colors[arch_idx % neon_colors.len()], 2.1);
2194            let _: usize = world.spawn_object(
2195                &format!("arch_beam_{arch_idx}"),
2196                tower_unit,
2197                Transform3D::new(
2198                    Vec3::new(0.0, 13.4, arch_z),
2199                    0.0,
2200                    Vec3::new(22.4, 0.58, 0.72),
2201                ),
2202                arch_frame_mat,
2203                false,
2204            );
2205            let _: usize = world.spawn_object(
2206                &format!("arch_glow_{arch_idx}"),
2207                neon_unit,
2208                Transform3D::new(
2209                    Vec3::new(0.0, 13.08, arch_z),
2210                    0.0,
2211                    Vec3::new(20.6, 0.24, 0.34),
2212                ),
2213                arch_neon,
2214                false,
2215            );
2216            for side in [-1.0_f32, 1.0_f32] {
2217                let _: usize = world.spawn_object(
2218                    &format!("arch_pillar_{arch_idx}_{}", if side < 0.0 { 0 } else { 1 }),
2219                    tower_unit,
2220                    Transform3D::new(
2221                        Vec3::new(side * 10.9, 0.0, arch_z),
2222                        0.0,
2223                        Vec3::new(0.58, 13.6, 0.68),
2224                    ),
2225                    arch_frame_mat,
2226                    false,
2227                );
2228            }
2229        }
2230        let car_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0xDC143C), 0.86, 0.11, 0.76);
2231        let car_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::sports_car(
2232            "hero_gt", car_mat,
2233        )));
2234        let car_idx: usize = world.spawn_object(
2235            "player_gt_car",
2236            car_mesh,
2237            Transform3D::new(Vec3::new(0.0, 0.0, 6.0), 0.0, Vec3::splat(1.1)),
2238            car_mat,
2239            true,
2240        );
2241        let _: bool = world.set_object_dynamic(car_idx, true);
2242        world.set_player_vehicle_index(Some(car_idx));
2243        let _: usize = world.add_point_light(PointLight3D::new(
2244            Vec3::new(0.0, 0.95, 9.2),
2245            Color::hex(0xFF1744),
2246            1.85,
2247            8.5,
2248        ));
2249        let traffic_specs: [(f32, f32, f32, f32, Color); 4] = [
2250            (-5.6, -16.0, PI, 11.5, Color::hex(0x38BDF8)),
2251            (-5.6, -56.0, PI, 10.0, Color::hex(0xA855F7)),
2252            (5.6, -24.0, 0.0, -13.0, Color::hex(0x34D399)),
2253            (5.6, -68.0, 0.0, -11.0, Color::hex(0xF59E0B)),
2254        ];
2255        for (t_idx, &(tx, tz, tyaw, tvel, tcol)) in traffic_specs.iter().enumerate() {
2256            let tmat: PbrMaterial = PbrMaterial::pbr(tcol, 0.86, 0.14, 0.74);
2257            let obj_id: usize = world.spawn_object(
2258                &format!("ai_traffic_{t_idx}"),
2259                car_mesh,
2260                Transform3D::new(Vec3::new(tx, 0.0, tz), tyaw, Vec3::splat(1.04)),
2261                tmat,
2262                true,
2263            );
2264            let _: bool = world.set_object_dynamic(obj_id, true);
2265            let Self {
2266                traffic_vehicles, ..
2267            } = &mut world;
2268            traffic_vehicles.push((obj_id, tvel, -94.0, 68.0));
2269        }
2270        let lamp_palette: [Color; 4] = [
2271            Color::hex(0x38BDF8),
2272            Color::hex(0xF43F5E),
2273            Color::hex(0xA855F7),
2274            Color::hex(0x34D399),
2275        ];
2276        for lamp_idx in 0..8usize {
2277            let side: f32 = if lamp_idx % 2 == 0 { -1.0 } else { 1.0 };
2278            let z_pos: f32 = -42.0 + ((lamp_idx / 2) as f32) * 24.0;
2279            let lamp_color: Color = lamp_palette[lamp_idx % lamp_palette.len()];
2280            let _: usize = world.spawn_object(
2281                &format!("lamp_pole_{lamp_idx}"),
2282                tower_unit,
2283                Transform3D::new(
2284                    Vec3::new(side * 10.35, 0.0, z_pos),
2285                    0.0,
2286                    Vec3::new(0.20, 6.2, 0.20),
2287                ),
2288                arch_frame_mat,
2289                false,
2290            );
2291            let _: usize = world.spawn_object(
2292                &format!("lamp_head_{lamp_idx}"),
2293                neon_unit,
2294                Transform3D::new(
2295                    Vec3::new(side * 9.85, 6.1, z_pos),
2296                    0.0,
2297                    Vec3::new(1.1, 0.18, 0.28),
2298                ),
2299                PbrMaterial::neon(lamp_color, 2.2),
2300                false,
2301            );
2302            let _: usize = world.add_point_light(PointLight3D::new(
2303                Vec3::new(side * 9.5, 6.2, z_pos),
2304                lamp_color,
2305                2.35,
2306                16.5,
2307            ));
2308        }
2309        let _: usize = world.add_spot_light(SpotLight3D::new(
2310            Vec3::new(-0.85, 0.95, 3.8),
2311            Vec3::new(0.0, -0.14, -1.0),
2312            Color::hex(0xFEF3C7),
2313            2.8,
2314            24.0,
2315            (14.0, 26.0),
2316        ));
2317        let _: usize = world.add_spot_light(SpotLight3D::new(
2318            Vec3::new(0.85, 0.95, 3.8),
2319            Vec3::new(0.0, -0.14, -1.0),
2320            Color::hex(0xFEF3C7),
2321            2.8,
2322            24.0,
2323            (14.0, 26.0),
2324        ));
2325        world.set_camera(Camera3D {
2326            position: Vec3::new(0.0, 4.25, 15.8),
2327            yaw: -FRAC_PI_2,
2328            pitch: -0.068,
2329            fov_deg: 60.0,
2330            near: 0.3,
2331            far: 480.0,
2332        });
2333        world.ensure_bvh();
2334        world
2335    }
2336
2337    /// Returns the number of autonomous cruising traffic vehicles registered in this world.
2338    ///
2339    /// # Returns
2340    ///
2341    /// - `usize` - Active cruising traffic vehicle count.
2342    #[must_use]
2343    pub fn traffic_vehicle_count(&self) -> usize {
2344        let Self {
2345            traffic_vehicles, ..
2346        } = self;
2347        traffic_vehicles.len()
2348    }
2349
2350    /// Applies an atmospheric mood preset (`0=Sunset, 1=RainyNight, 2=Noon, 3=Midnight`), updating sun lighting and ambient Niagara rain streaks.
2351    ///
2352    /// # Arguments
2353    ///
2354    /// - `u8` - Atmosphere preset index (`0..=3`).
2355    ///
2356    /// # Returns
2357    ///
2358    /// - `f32` - Corresponding time-of-day hour in `[0.0, 24.0]`.
2359    pub fn apply_atmosphere_preset(&mut self, preset: u8) -> f32 {
2360        let clamped: u8 = preset.min(3);
2361        let hour: f32 = match clamped {
2362            1 => ATMOSPHERE_HOUR_RAINY_NIGHT,
2363            2 => ATMOSPHERE_HOUR_NOON,
2364            3 => ATMOSPHERE_HOUR_MIDNIGHT,
2365            _ => ATMOSPHERE_HOUR_SUNSET,
2366        };
2367        self.set_atmosphere_preset(clamped);
2368        let sun_light: DirectionalLight3D = match clamped {
2369            1 => DirectionalLight3D {
2370                direction: Vec3::new(-0.32, 0.48, -0.82).normalize(),
2371                color: Vec3::new(0.56, 0.78, 1.24),
2372                sky_zenith: Vec3::new(0.015, 0.038, 0.105),
2373                sky_horizon: Vec3::new(0.078, 0.155, 0.275),
2374                time_of_day: hour,
2375            },
2376            3 => DirectionalLight3D {
2377                direction: Vec3::new(-0.42, 0.62, -0.66).normalize(),
2378                color: Vec3::new(0.36, 0.34, 0.88),
2379                sky_zenith: Vec3::new(0.007, 0.005, 0.024),
2380                sky_horizon: Vec3::new(0.135, 0.036, 0.215),
2381                time_of_day: hour,
2382            },
2383            _ => DirectionalLight3D::from_time_of_day(hour),
2384        };
2385        self.set_sun(sun_light);
2386        if clamped == 1 && self.get_niagara().get_active_count() < RAINY_NIGHT_MAX_PARTICLES {
2387            let cam_pos: Vec3 = self.get_camera().get_position();
2388            let mut rain_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
2389            rain_cfg.set_origin(cam_pos.add(Vec3::new(0.0, 4.5, -14.0)));
2390            rain_cfg.set_base_velocity(Vec3::new(-0.4, -17.0, 0.3));
2391            rain_cfg.set_velocity_spread(2.4);
2392            rain_cfg.set_start_color(Color::rgba(175, 222, 255, 165));
2393            rain_cfg.set_end_color(Color::rgba(92, 162, 235, 42));
2394            rain_cfg.set_start_size_m(0.042);
2395            rain_cfg.set_end_size_m(0.016);
2396            rain_cfg.set_min_lifetime(0.55);
2397            rain_cfg.set_max_lifetime(0.95);
2398            rain_cfg.set_emissive_boost(0.85);
2399            self.get_mut_niagara().emit_burst(8, &rain_cfg);
2400        }
2401        self.bump_world_revision();
2402        hour
2403    }
2404
2405    /// Registers a dynamic `PointLight3D` into this world for UE5 Clustered Deferred Lighting and returns its index.
2406    ///
2407    /// # Arguments
2408    ///
2409    /// - `PointLight3D` - World-space point light descriptor.
2410    ///
2411    /// # Returns
2412    ///
2413    /// - `usize` - Assigned point light index.
2414    pub fn add_point_light(&mut self, light: PointLight3D) -> usize {
2415        let light_idx: usize = self.get_point_lights().len();
2416        self.get_mut_point_lights().push(light);
2417        self.bump_world_revision();
2418        light_idx
2419    }
2420
2421    /// Registers a dynamic `SpotLight3D` into this world for UE5 Clustered Deferred Lighting and returns its index.
2422    ///
2423    /// # Arguments
2424    ///
2425    /// - `SpotLight3D` - World-space spotlight descriptor.
2426    ///
2427    /// # Returns
2428    ///
2429    /// - `usize` - Assigned spotlight index.
2430    pub fn add_spot_light(&mut self, light: SpotLight3D) -> usize {
2431        let light_idx: usize = self.get_spot_lights().len();
2432        self.get_mut_spot_lights().push(light);
2433        self.bump_world_revision();
2434        light_idx
2435    }
2436
2437    /// Clears all dynamic local point and spot lights from this world.
2438    pub fn clear_local_lights(&mut self) {
2439        self.get_mut_point_lights().clear();
2440        self.get_mut_spot_lights().clear();
2441        self.bump_world_revision();
2442    }
2443
2444    /// Emits `count` 3D particles into the world's `NiagaraSystem3D` with zero heap allocations.
2445    ///
2446    /// # Arguments
2447    ///
2448    /// - `&NiagaraEmitterConfig3D` - Emitter properties.
2449    /// - `usize` - Number of particles to emit.
2450    ///
2451    /// # Returns
2452    ///
2453    /// - `usize` - Active particle count after emission.
2454    pub fn emit_particles_3d(&mut self, config: &NiagaraEmitterConfig3D, count: usize) -> usize {
2455        self.get_mut_niagara().emit_burst(count, config);
2456        let active: usize = self.get_niagara().get_active_count();
2457        if count > 0 {
2458            self.bump_world_revision();
2459        }
2460        active
2461    }
2462
2463    /// Builds a dense UE5-scale multi-block cyberpunk metropolis with hundreds of occluding towers, local neon lights, and dynamic vehicles for scalability and occlusion benchmarking.
2464    ///
2465    /// # Arguments
2466    ///
2467    /// - `i32` - City block half-radius (`1..=5`, producing `(2r+1)x(2r+1)` multi-tower blocks).
2468    ///
2469    /// # Returns
2470    ///
2471    /// - `Self` - Populated dense 3D open-world metropolis with built static/dynamic BVHs.
2472    #[must_use]
2473    pub fn create_dense_open_world_city(blocks_radius: i32) -> Self {
2474        let radius: i32 = blocks_radius.clamp(1, 5);
2475        let mut world: Self = Self::create_open_world_city();
2476        let tower_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2477            DENSE_TOWER_MESH_NAME,
2478            1.0,
2479            1.0,
2480            1.0,
2481            true,
2482            PbrMaterial::default(),
2483        )));
2484        let facades: [PbrMaterial; 4] = [
2485            PbrMaterial::pbr(Color::hex(0x1E293B), 0.72, 0.16, 0.65)
2486                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2487            PbrMaterial::pbr(Color::hex(0x334155), 0.55, 0.24, 0.45)
2488                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2489            PbrMaterial::pbr(Color::hex(0x0F172A), 0.85, 0.10, 0.78)
2490                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2491            PbrMaterial::pbr(Color::hex(0x475569), 0.40, 0.35, 0.35)
2492                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2493        ];
2494        let neon_palette: [Color; 4] = [
2495            Color::hex(0x38BDF8),
2496            Color::hex(0xF43F5E),
2497            Color::hex(0xA855F7),
2498            Color::hex(0x34D399),
2499        ];
2500        let mut serial: usize = 0;
2501        for bx in -radius..=radius {
2502            for bz in -radius..=radius {
2503                if bx == 0 && (-3..=3).contains(&bz) {
2504                    continue;
2505                }
2506                let center_x: f32 = (bx as f32) * 26.0;
2507                let center_z: f32 = (bz as f32) * 24.0 - 16.0;
2508                for sub in 0..4usize {
2509                    let off_x: f32 = if (sub & 1) == 0 { -5.5 } else { 5.5 };
2510                    let off_z: f32 = if (sub & 2) == 0 { -5.5 } else { 5.5 };
2511                    let height_m: f32 = 14.0 + (((serial * 11 + sub * 7) % 6) as f32) * 7.5;
2512                    let width_m: f32 = 7.5 + ((serial % 3) as f32) * 1.4;
2513                    let mat: PbrMaterial = facades[serial % facades.len()];
2514                    let _: usize = world.spawn_object(
2515                        &format!("dense_bldg_{serial}"),
2516                        tower_mesh,
2517                        Transform3D::new(
2518                            Vec3::new(center_x + off_x, 0.0, center_z + off_z),
2519                            0.0,
2520                            Vec3::new(width_m, height_m, 8.5),
2521                        ),
2522                        mat,
2523                        true,
2524                    );
2525                    serial += 1;
2526                }
2527                if (bx + bz).abs() <= 2 && world.get_point_lights().len() < 32 {
2528                    let _: usize = world.add_point_light(PointLight3D::new(
2529                        Vec3::new(center_x, 7.0, center_z),
2530                        neon_palette[serial % neon_palette.len()],
2531                        4.5,
2532                        22.0,
2533                    ));
2534                }
2535            }
2536        }
2537        world.ensure_bvh();
2538        world
2539    }
2540
2541    /// Cycles the active 3D camera perspective (`Chase` -> `Hood` -> `Orbit` -> `Aerial`) safely without clipping.
2542    ///
2543    /// # Arguments
2544    ///
2545    /// - `&Self` - Mutable world.
2546    ///
2547    /// # Returns
2548    ///
2549    /// - `u8` - New active camera mode index.
2550    pub fn cycle_camera_mode(&mut self) -> u8 {
2551        let next: u8 = (self.get_camera_mode() + 1) % 4;
2552        self.set_camera_mode(next);
2553        next
2554    }
2555
2556    /// Computes horizontal playable world bounds from non-solid ground meshes when present, preventing hardcoded invisible walls.
2557    ///
2558    /// # Arguments
2559    ///
2560    /// - `&Self` - World reference.
2561    ///
2562    /// # Returns
2563    ///
2564    /// - `Option<(f32, f32, f32, f32)>` - `(min_x, max_x, min_z, max_z)` horizontal ground limits.
2565    #[must_use]
2566    pub fn ground_play_bounds(&self) -> Option<(f32, f32, f32, f32)> {
2567        let mut found: bool = false;
2568        let mut min_x: f32 = f32::INFINITY;
2569        let mut max_x: f32 = f32::NEG_INFINITY;
2570        let mut min_z: f32 = f32::INFINITY;
2571        let mut max_z: f32 = f32::NEG_INFINITY;
2572        for obj in self.get_objects().iter() {
2573            if obj.get_ray_trace_caster()
2574                || obj.get_material().get_surface_detail() == SurfaceDetailMode::OceanWater
2575            {
2576                continue;
2577            }
2578            let blue_val: AxisAlignedBox3D = obj.get_world_bounds();
2579            let span_x: f32 = blue_val.get_max().get_x() - blue_val.get_min().get_x();
2580            let span_z: f32 = blue_val.get_max().get_z() - blue_val.get_min().get_z();
2581            if span_x >= 16.0 && span_z >= 16.0 {
2582                min_x = min_x.min(blue_val.get_min().get_x());
2583                max_x = max_x.max(blue_val.get_max().get_x());
2584                min_z = min_z.min(blue_val.get_min().get_z());
2585                max_z = max_z.max(blue_val.get_max().get_z());
2586                found = true;
2587            }
2588        }
2589        if found {
2590            Some((min_x, max_x, min_z, max_z))
2591        } else {
2592            None
2593        }
2594    }
2595
2596    /// Tests a world-space `OrientedBox3D` against every solid (`ray_trace_caster == true`) model's real mesh triangles (excluding `ignore_idx`), returning the deepest penetration hit.
2597    ///
2598    /// # Arguments
2599    ///
2600    /// - `&Self` - World reference.
2601    /// - `OrientedBox3D` - Candidate oriented bounding box in world space.
2602    /// - `Option<usize>` - Optional scene object index to exclude (self).
2603    ///
2604    /// # Returns
2605    ///
2606    /// - `Option<MeshCollisionHit3D>` - Deepest real-mesh triangle collision contact, or `None` when clear.
2607    #[must_use]
2608    pub fn mesh_oriented_box_collision(
2609        &self,
2610        candidate: OrientedBox3D,
2611        ignore_idx: Option<usize>,
2612    ) -> Option<MeshCollisionHit3D> {
2613        let query_bounds: AxisAlignedBox3D = candidate.to_world_bounds();
2614        let mut deepest: Option<MeshCollisionHit3D> = None;
2615        let objects: &[SceneObject3D] = self.get_objects().as_slice();
2616        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
2617        for (idx, obj) in objects.iter().enumerate() {
2618            if ignore_idx == Some(idx) || !obj.get_ray_trace_caster() {
2619                continue;
2620            }
2621            if !Self::boxes_overlap(query_bounds, obj.get_world_bounds()) {
2622                continue;
2623            }
2624            let Some(mesh) = mesh_lib
2625                .get(obj.get_mesh_id())
2626                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
2627            else {
2628                continue;
2629            };
2630            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
2631            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
2632            let obj_tr: Transform3D = obj.get_transform();
2633            let model_mat: Mat4 = obj_tr.to_mat4();
2634            let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
2635            if meshlets.is_empty() {
2636                for tri in indices.iter() {
2637                    let (i0, i1, i2): (usize, usize, usize) =
2638                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
2639                    if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
2640                        let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
2641                        let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
2642                        let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
2643                        if let Some((normal, pen, contact)) =
2644                            candidate.intersect_triangle_world(w0, w1, w2)
2645                        {
2646                            let replace: bool = deepest
2647                                .map(|delta_val: MeshCollisionHit3D| {
2648                                    pen > delta_val.get_penetration()
2649                                })
2650                                .unwrap_or(true);
2651                            if replace {
2652                                deepest = Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
2653                            }
2654                        }
2655                    }
2656                }
2657            } else {
2658                for ml in meshlets.iter() {
2659                    let ml_bounds: AxisAlignedBox3D = model_mat.transform_bounds(ml.get_bounds());
2660                    if !Self::boxes_overlap(query_bounds, ml_bounds) {
2661                        continue;
2662                    }
2663                    let start: usize = ml.get_first_tri() as usize;
2664                    let end: usize = start
2665                        .saturating_add(ml.get_tri_count() as usize)
2666                        .min(indices.len());
2667                    for tri in indices[start..end].iter() {
2668                        let (i0, i1, i2): (usize, usize, usize) =
2669                            (tri[0] as usize, tri[1] as usize, tri[2] as usize);
2670                        if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
2671                            let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
2672                            let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
2673                            let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
2674                            if let Some((normal, pen, contact)) =
2675                                candidate.intersect_triangle_world(w0, w1, w2)
2676                            {
2677                                let replace: bool = deepest
2678                                    .map(|distance_val: MeshCollisionHit3D| {
2679                                        pen > distance_val.get_penetration()
2680                                    })
2681                                    .unwrap_or(true);
2682                                if replace {
2683                                    deepest =
2684                                        Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
2685                                }
2686                            }
2687                        }
2688                    }
2689                }
2690            }
2691        }
2692        deepest
2693    }
2694
2695    /// Casts a world-space ray against every solid (`ray_trace_caster == true`) model's real mesh triangles (excluding `ignore_idx`) up to `max_dist`.
2696    ///
2697    /// # Arguments
2698    ///
2699    /// - `&Self` - World reference.
2700    /// - `Vec3` - Ray origin in world space.
2701    /// - `Vec3` - Unit ray direction in world space.
2702    /// - `f32` - Maximum ray distance.
2703    /// - `Option<usize>` - Optional scene object index to exclude.
2704    ///
2705    /// # Returns
2706    ///
2707    /// - `Option<RayHit3D>` - Closest real-mesh triangle intersection within `(1e-4, max_dist]`.
2708    #[must_use]
2709    pub fn raycast_solid_meshes(
2710        &self,
2711        origin: Vec3,
2712        direction: Vec3,
2713        max_dist: f32,
2714        ignore_idx: Option<usize>,
2715    ) -> Option<RayHit3D> {
2716        let dir: Vec3 = direction.normalize();
2717        let inv_dir: Vec3 = Ray3D::safe_inv_vec(dir);
2718        let t_min: f32 = 1e-4;
2719        let mut best_t: f32 = max_dist;
2720        let mut best_hit: Option<RayHit3D> = None;
2721        let objects: &[SceneObject3D] = self.get_objects().as_slice();
2722        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
2723        let ignore_is_static_caster: bool = ignore_idx
2724            .and_then(|idx: usize| objects.get(idx))
2725            .is_some_and(|obj: &SceneObject3D| obj.get_ray_trace_caster() && !obj.get_is_dynamic());
2726        let use_static_bvh: bool =
2727            !self.get_bvh_dirty() && !self.get_bvh().is_empty() && !ignore_is_static_caster;
2728        if use_static_bvh
2729            && let Some((hit_dist, tri_idx)) = self
2730                .get_bvh()
2731                .trace_closest_raw(origin, dir, inv_dir, t_min, best_t)
2732        {
2733            let bvh_tris: &[BvhTriangle] = self.get_bvh().get_triangles().as_slice();
2734            if let Some(hit_tri) = bvh_tris.get(tri_idx) {
2735                let raw_normal: Vec3 = hit_tri.get_normal();
2736                let oriented_normal: Vec3 = if raw_normal.dot(dir) > 0.0 {
2737                    raw_normal.scale(-1.0)
2738                } else {
2739                    raw_normal
2740                };
2741                best_t = hit_dist;
2742                best_hit = Some(RayHit3D {
2743                    distance: hit_dist,
2744                    point: origin.add(dir.scale(hit_dist)),
2745                    normal: oriented_normal,
2746                    material: hit_tri.get_material(),
2747                });
2748            }
2749        }
2750        for (idx, obj) in objects.iter().enumerate() {
2751            if ignore_idx == Some(idx) || !obj.get_ray_trace_caster() {
2752                continue;
2753            }
2754            if use_static_bvh && !obj.get_is_dynamic() {
2755                continue;
2756            }
2757            if !obj
2758                .get_world_bounds()
2759                .intersect_ray_near(origin, inv_dir, t_min, best_t)
2760                .is_finite()
2761            {
2762                continue;
2763            }
2764            let Some(mesh) = mesh_lib
2765                .get(obj.get_mesh_id())
2766                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
2767            else {
2768                continue;
2769            };
2770            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
2771            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
2772            let model_mat: Mat4 = obj.get_transform().to_mat4();
2773            let mat: PbrMaterial = obj.get_material();
2774            for tri in indices.iter() {
2775                let (i0, i1, i2): (usize, usize, usize) =
2776                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
2777                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
2778                    let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
2779                    let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
2780                    let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
2781                    if let Some((blend_factor, normal)) =
2782                        Self::ray_intersect_triangle(origin, dir, w0, w1, w2, t_min, best_t)
2783                    {
2784                        best_t = blend_factor;
2785                        best_hit = Some(RayHit3D {
2786                            distance: blend_factor,
2787                            point: origin.add(dir.scale(blend_factor)),
2788                            normal,
2789                            material: mat,
2790                        });
2791                    }
2792                }
2793            }
2794        }
2795        best_hit
2796    }
2797
2798    /// Tests whether two world-space `AxisAlignedBox3D` boxes overlap strictly.
2799    ///
2800    /// # Arguments
2801    ///
2802    /// - `AxisAlignedBox3D` - First bounding box.
2803    /// - `AxisAlignedBox3D` - Second bounding box.
2804    ///
2805    /// # Returns
2806    ///
2807    /// - `bool` - `true` when both axis-aligned bounding boxes overlap on all three axes.
2808    #[inline]
2809    #[must_use]
2810    fn boxes_overlap(alpha_val: AxisAlignedBox3D, blue_val: AxisAlignedBox3D) -> bool {
2811        let ox: bool = alpha_val.get_min().get_x() < blue_val.get_max().get_x()
2812            && alpha_val.get_max().get_x() > blue_val.get_min().get_x();
2813        let oy: bool = alpha_val.get_min().get_y() < blue_val.get_max().get_y()
2814            && alpha_val.get_max().get_y() > blue_val.get_min().get_y();
2815        let oz: bool = alpha_val.get_min().get_z() < blue_val.get_max().get_z()
2816            && alpha_val.get_max().get_z() > blue_val.get_min().get_z();
2817        ox && oy && oz
2818    }
2819
2820    /// Double-sided Möller-Trumbore ray-triangle intersection returning `(t, outward_unit_normal)`.
2821    ///
2822    /// # Arguments
2823    ///
2824    /// - `Vec3` - Ray origin.
2825    /// - `Vec3` - Unit ray direction.
2826    /// - `Vec3` - Triangle vertex 0.
2827    /// - `Vec3` - Triangle vertex 1.
2828    /// - `Vec3` - Triangle vertex 2.
2829    /// - `f32` - Minimum ray parameter `t`.
2830    /// - `f32` - Maximum ray parameter `t`.
2831    ///
2832    /// # Returns
2833    ///
2834    /// - `Option<(f32, Vec3)>` - Hit distance and facing unit normal.
2835    #[inline]
2836    #[must_use]
2837    fn ray_intersect_triangle(
2838        origin: Vec3,
2839        dir: Vec3,
2840        v0: Vec3,
2841        v1: Vec3,
2842        v2: Vec3,
2843        t_min: f32,
2844        t_max: f32,
2845    ) -> Option<(f32, Vec3)> {
2846        let e1: Vec3 = v1.sub(v0);
2847        let e2: Vec3 = v2.sub(v0);
2848        let pvec: Vec3 = dir.cross(e2);
2849        let det: f32 = e1.dot(pvec);
2850        if det.abs() < 1e-7 {
2851            return None;
2852        }
2853        let inv_det: f32 = 1.0 / det;
2854        let tvec: Vec3 = origin.sub(v0);
2855        let tex_u: f32 = tvec.dot(pvec) * inv_det;
2856        if !(0.0..=1.0).contains(&tex_u) {
2857            return None;
2858        }
2859        let qvec: Vec3 = tvec.cross(e1);
2860        let item_val: f32 = dir.dot(qvec) * inv_det;
2861        if item_val < 0.0 || tex_u + item_val > 1.0 {
2862            return None;
2863        }
2864        let blend_factor: f32 = e2.dot(qvec) * inv_det;
2865        if blend_factor <= t_min || blend_factor > t_max {
2866            return None;
2867        }
2868        let raw_n: Vec3 = e1.cross(e2).normalize();
2869        let normal: Vec3 = if raw_n.dot(dir) > 0.0 {
2870            raw_n.scale(-1.0)
2871        } else {
2872            raw_n
2873        };
2874        Some((blend_factor, normal))
2875    }
2876
2877    /// Tests whether a candidate transformed mesh collides with any solid obstacle's real triangles excluding `ignore_idx`.
2878    ///
2879    /// # Arguments
2880    ///
2881    /// - `&Self` - World reference.
2882    /// - `Transform3D` - Candidate object transform.
2883    /// - `AxisAlignedBox3D` - Candidate local mesh bounds.
2884    /// - `usize` - Self object index to skip.
2885    ///
2886    /// # Returns
2887    ///
2888    /// - `Option<MeshCollisionHit3D>` - Deepest real-mesh collision hit, or `None` when clear.
2889    #[must_use]
2890    fn collides_with_obstacles(
2891        &self,
2892        candidate_tr: Transform3D,
2893        local_bounds: AxisAlignedBox3D,
2894        ignore_idx: usize,
2895    ) -> Option<MeshCollisionHit3D> {
2896        let oriented_box: OrientedBox3D = candidate_tr.to_oriented_box(local_bounds);
2897        self.mesh_oriented_box_collision(oriented_box, Some(ignore_idx))
2898    }
2899
2900    /// Advances drivable vehicle/camera controls with continuous real-mesh oriented bounding box-vs-triangle collision, wall sliding, raycast camera boom, and synchronized spinning bounds.
2901    ///
2902    /// # Arguments
2903    ///
2904    /// - `&Self` - Mutable world.
2905    /// - `f32` - Delta time in seconds.
2906    /// - `&InputState` - Real-time polled keyboard/pointer input.
2907    /// - `&ActionMap` - Action bindings for WASD/Arrows movement.
2908    pub fn step_simulation(&mut self, dt: f32, input: &InputState, actions: &ActionMap) {
2909        if dt > 0.0 {
2910            self.set_world_time_secs(self.get_world_time_secs() + dt);
2911        }
2912        let move_vec: Point = actions.movement_vector(input);
2913        let steer: f32 = move_vec.get_x();
2914        let throttle: f32 = -move_vec.get_y();
2915        let mut any_dynamic_moved: bool = false;
2916        let mut any_static_moved: bool = false;
2917        let ground_limits: Option<(f32, f32, f32, f32)> = self.ground_play_bounds();
2918        let car_opt: Option<usize> = self.vehicle_index();
2919        if let Some(car_idx) = car_opt
2920            && let Some((mut transform_val, mesh_id, car_is_dynamic)) =
2921                self.get_objects().get(car_idx).map(|car: &SceneObject3D| {
2922                    (car.get_transform(), car.get_mesh_id(), car.get_is_dynamic())
2923                })
2924        {
2925            let mut car_moved: bool = false;
2926            let mesh_bounds: AxisAlignedBox3D = self
2927                .get_mesh_library()
2928                .get(mesh_id)
2929                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
2930                .map(Mesh3D::get_bounds)
2931                .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-2.0), Vec3::splat(2.0)));
2932            if steer.abs() > 0.05 {
2933                let total_yaw: f32 = -steer * 1.85 * dt;
2934                let rot_steps: usize = ((total_yaw.abs() / 0.12).ceil() as usize).clamp(1, 12);
2935                let step_yaw: f32 = total_yaw / (rot_steps as f32);
2936                for _ in 0..rot_steps {
2937                    let mut rotated: Transform3D = transform_val;
2938                    rotated.set_yaw_rad(transform_val.get_yaw_rad() + step_yaw);
2939                    if self
2940                        .collides_with_obstacles(rotated, mesh_bounds, car_idx)
2941                        .is_none()
2942                    {
2943                        transform_val = rotated;
2944                        car_moved = true;
2945                    } else {
2946                        break;
2947                    }
2948                }
2949            }
2950            if throttle.abs() > 0.05 {
2951                let fwd_x: f32 = -transform_val.get_yaw_rad().sin();
2952                let fwd_z: f32 = -transform_val.get_yaw_rad().cos();
2953                let total_disp: Vec3 = Vec3::new(fwd_x, 0.0, fwd_z).scale(24.0 * throttle * dt);
2954                let oriented_box_now: OrientedBox3D = transform_val.to_oriented_box(mesh_bounds);
2955                let min_half: f32 = oriented_box_now
2956                    .get_half_extents()
2957                    .get_x()
2958                    .min(oriented_box_now.get_half_extents().get_z())
2959                    .max(0.25);
2960                let max_step_len: f32 = (min_half * 0.35).min(0.20);
2961                let substeps: usize =
2962                    ((total_disp.length() / max_step_len).ceil() as usize).clamp(1, 32);
2963                let step_delta: Vec3 = total_disp.scale(1.0 / (substeps as f32));
2964                let ground_margin: f32 = oriented_box_now
2965                    .get_half_extents()
2966                    .get_x()
2967                    .max(oriented_box_now.get_half_extents().get_z());
2968                for _ in 0..substeps {
2969                    let cur: Vec3 = transform_val.get_position();
2970                    let mut next_pos: Vec3 = Vec3::new(
2971                        cur.get_x() + step_delta.get_x(),
2972                        cur.get_y(),
2973                        cur.get_z() + step_delta.get_z(),
2974                    );
2975                    if let Some((gx0, gx1, gz0, gz1)) = ground_limits {
2976                        let lo_x: f32 = (gx0 + ground_margin).min(gx1);
2977                        let hi_x: f32 = (gx1 - ground_margin).max(lo_x);
2978                        let lo_z: f32 = (gz0 + ground_margin).min(gz1);
2979                        let hi_z: f32 = (gz1 - ground_margin).max(lo_z);
2980                        next_pos.set_x(next_pos.get_x().clamp(lo_x, hi_x));
2981                        next_pos.set_z(next_pos.get_z().clamp(lo_z, hi_z));
2982                    }
2983                    let mut cand: Transform3D = transform_val;
2984                    cand.set_position(next_pos);
2985                    if let Some(hit) = self.collides_with_obstacles(cand, mesh_bounds, car_idx) {
2986                        let mut hn: Vec3 =
2987                            Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
2988                        if hn.length_sq() > 1e-6 {
2989                            hn = hn.normalize();
2990                            let into: f32 = step_delta.dot(hn);
2991                            let slide_delta: Vec3 = if into < 0.0 {
2992                                step_delta.sub(hn.scale(into))
2993                            } else {
2994                                Vec3::zero()
2995                            };
2996                            if slide_delta.length_sq() > 1e-8 {
2997                                let mut slide_pos: Vec3 = Vec3::new(
2998                                    cur.get_x() + slide_delta.get_x(),
2999                                    cur.get_y(),
3000                                    cur.get_z() + slide_delta.get_z(),
3001                                );
3002                                if let Some((gx0, gx1, gz0, gz1)) = ground_limits {
3003                                    let lo_x: f32 = (gx0 + ground_margin).min(gx1);
3004                                    let hi_x: f32 = (gx1 - ground_margin).max(lo_x);
3005                                    let lo_z: f32 = (gz0 + ground_margin).min(gz1);
3006                                    let hi_z: f32 = (gz1 - ground_margin).max(lo_z);
3007                                    slide_pos.set_x(slide_pos.get_x().clamp(lo_x, hi_x));
3008                                    slide_pos.set_z(slide_pos.get_z().clamp(lo_z, hi_z));
3009                                }
3010                                let mut slide_tr: Transform3D = transform_val;
3011                                slide_tr.set_position(slide_pos);
3012                                if self
3013                                    .collides_with_obstacles(slide_tr, mesh_bounds, car_idx)
3014                                    .is_none()
3015                                {
3016                                    transform_val = slide_tr;
3017                                    car_moved = true;
3018                                    continue;
3019                                }
3020                            }
3021                        }
3022                        break;
3023                    } else {
3024                        transform_val = cand;
3025                        car_moved = true;
3026                    }
3027                }
3028            }
3029            if car_moved {
3030                let world_b: AxisAlignedBox3D = transform_val.transform_bounds(mesh_bounds);
3031                if let Some(car_mut) = self.get_mut_objects().get_mut(car_idx) {
3032                    car_mut.set_transform(transform_val);
3033                    car_mut.set_world_bounds(world_b);
3034                }
3035                if car_is_dynamic {
3036                    any_dynamic_moved = true;
3037                } else {
3038                    any_static_moved = true;
3039                }
3040                let car_yaw: f32 = transform_val.get_yaw_rad();
3041                let car_origin: Vec3 = transform_val.get_position();
3042                let car_fwd: Vec3 = Vec3::new(-car_yaw.sin(), 0.0, -car_yaw.cos());
3043                let car_right: Vec3 = Vec3::new(car_yaw.cos(), 0.0, -car_yaw.sin());
3044                let beam_dir: Vec3 = Vec3::new(car_fwd.get_x(), -0.14, car_fwd.get_z()).normalize();
3045                if self.get_spot_lights().len() >= 2 {
3046                    let front_center: Vec3 = car_origin
3047                        .add(car_fwd.scale(2.2))
3048                        .add(Vec3::new(0.0, 0.95, 0.0));
3049                    let left_pos: Vec3 = front_center.sub(car_right.scale(0.85));
3050                    let right_pos: Vec3 = front_center.add(car_right.scale(0.85));
3051                    let spots: &mut Vec<SpotLight3D> = self.get_mut_spot_lights();
3052                    spots[0].set_position(left_pos);
3053                    spots[0].set_direction(beam_dir);
3054                    spots[1].set_position(right_pos);
3055                    spots[1].set_direction(beam_dir);
3056                }
3057                if let Some(tail_light) = self.get_mut_point_lights().first_mut()
3058                    && tail_light.get_color().get_x() > 0.90
3059                    && tail_light.get_color().get_y() < 0.15
3060                {
3061                    let rear_pos: Vec3 = car_origin
3062                        .sub(car_fwd.scale(2.9))
3063                        .add(Vec3::new(0.0, 0.95, 0.0));
3064                    tail_light.set_position(rear_pos);
3065                }
3066                if throttle.abs() > 0.25
3067                    && (self.get_world_revision() & 3) == 0
3068                    && self.get_niagara().get_active_count() < 24
3069                {
3070                    let exhaust_pos: Vec3 = car_origin
3071                        .sub(car_fwd.scale(2.3))
3072                        .add(Vec3::new(0.0, 0.42, 0.0));
3073                    let mut spark_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
3074                    spark_cfg.set_origin(exhaust_pos);
3075                    spark_cfg.set_base_velocity(car_fwd.scale(-4.5).add(Vec3::new(0.0, 1.1, 0.0)));
3076                    spark_cfg.set_start_size_m(0.11);
3077                    spark_cfg.set_end_size_m(0.03);
3078                    self.get_mut_niagara().emit_burst(1, &spark_cfg);
3079                }
3080            }
3081            let car_tr: Transform3D = self.get_objects()[car_idx].get_transform();
3082            let car_pos: Vec3 = car_tr.get_position();
3083            let yaw: f32 = car_tr.get_yaw_rad();
3084            let cam_mode: u8 = self.get_camera_mode();
3085            let (mut desired_eye, look_target): (Vec3, Vec3) = match cam_mode {
3086                1 => {
3087                    let eye: Vec3 = Vec3::new(
3088                        car_pos.get_x() - yaw.sin() * 1.4,
3089                        2.15,
3090                        car_pos.get_z() - yaw.cos() * 1.4,
3091                    );
3092                    let tgt: Vec3 = Vec3::new(
3093                        car_pos.get_x() - yaw.sin() * 18.0,
3094                        1.8,
3095                        car_pos.get_z() - yaw.cos() * 18.0,
3096                    );
3097                    (eye, tgt)
3098                }
3099                2 => {
3100                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.45;
3101                    self.set_camera_orbit_rad(orbit);
3102                    let eye: Vec3 = Vec3::new(
3103                        car_pos.get_x() + orbit.sin() * 10.5,
3104                        5.2,
3105                        car_pos.get_z() + orbit.cos() * 10.5,
3106                    );
3107                    (eye, Vec3::new(car_pos.get_x(), 1.6, car_pos.get_z()))
3108                }
3109                3 => {
3110                    let eye: Vec3 = Vec3::new(
3111                        car_pos.get_x() + yaw.sin() * 18.0,
3112                        18.5,
3113                        car_pos.get_z() + yaw.cos() * 18.0,
3114                    );
3115                    (eye, Vec3::new(car_pos.get_x(), 1.2, car_pos.get_z()))
3116                }
3117                4 => {
3118                    let cur_cam: Camera3D = self.get_camera();
3119                    let fwd: Vec3 = cur_cam.forward();
3120                    let right: Vec3 = cur_cam.right();
3121                    let moved: Vec3 = cur_cam
3122                        .get_position()
3123                        .add(fwd.scale(throttle * 18.0 * dt))
3124                        .add(right.scale(steer * 14.0 * dt));
3125                    let eye: Vec3 = Vec3::new(moved.get_x(), moved.get_y().max(1.5), moved.get_z());
3126                    (eye, eye.add(fwd.scale(16.0)))
3127                }
3128                5 => {
3129                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.28;
3130                    self.set_camera_orbit_rad(orbit);
3131                    let eye: Vec3 = Vec3::new(
3132                        car_pos.get_x() + orbit.sin() * 7.8,
3133                        3.6 + (orbit * 1.5).sin() * 1.4,
3134                        car_pos.get_z() + orbit.cos() * 13.5,
3135                    );
3136                    (eye, Vec3::new(car_pos.get_x(), 1.8, car_pos.get_z() - 3.0))
3137                }
3138                _ => {
3139                    let eye: Vec3 = Vec3::new(
3140                        car_pos.get_x() + yaw.sin() * 9.8,
3141                        4.25,
3142                        car_pos.get_z() + yaw.cos() * 9.8,
3143                    );
3144                    let tgt: Vec3 = Vec3::new(
3145                        car_pos.get_x() - yaw.sin() * 16.0,
3146                        2.40,
3147                        car_pos.get_z() - yaw.cos() * 16.0,
3148                    );
3149                    (eye, tgt)
3150                }
3151            };
3152            let boom_anchor: Vec3 =
3153                Vec3::new(car_pos.get_x(), car_pos.get_y() + 1.8, car_pos.get_z());
3154            let boom_vec: Vec3 = desired_eye.sub(boom_anchor);
3155            let boom_len: f32 = boom_vec.length();
3156            if boom_len > 0.25 {
3157                let boom_dir: Vec3 = boom_vec.scale(1.0 / boom_len);
3158                if let Some(hit) =
3159                    self.raycast_solid_meshes(boom_anchor, boom_dir, boom_len, Some(car_idx))
3160                {
3161                    let safe_dist: f32 = (hit.get_distance() - 0.55).max(0.8);
3162                    desired_eye = boom_anchor.add(boom_dir.scale(safe_dist));
3163                }
3164            }
3165            let cam_probe: OrientedBox3D = OrientedBox3D::from_bounds(AxisAlignedBox3D::new(
3166                desired_eye.sub(Vec3::splat(0.45)),
3167                desired_eye.add(Vec3::splat(0.45)),
3168            ));
3169            if let Some(hit) = self.mesh_oriented_box_collision(cam_probe, Some(car_idx)) {
3170                desired_eye = desired_eye.add(hit.get_normal().scale(hit.get_penetration() + 0.1));
3171            }
3172            let prev_cam: Camera3D = self.get_camera();
3173            let mut cam: Camera3D = prev_cam;
3174            let smooth: f32 = (dt * 7.0).clamp(0.05, 1.0);
3175            cam.set_position(cam.get_position().lerp(desired_eye, smooth));
3176            let look_dir: Vec3 = look_target.sub(cam.get_position()).normalize();
3177            cam.set_yaw(look_dir.get_z().atan2(look_dir.get_x()));
3178            cam.set_pitch(look_dir.get_y().clamp(-0.92, 0.92).asin());
3179            self.set_camera(cam);
3180            if cam != prev_cam {
3181                self.bump_world_revision();
3182            }
3183        }
3184        let traffic_count: usize = self.traffic_vehicle_count();
3185        let bumper_clearance_m: f32 = 0.75;
3186        for slot_idx in 0..traffic_count {
3187            let (traffic_idx, vel_z, z_min, z_max): (usize, f32, f32, f32) = {
3188                let Self {
3189                    traffic_vehicles, ..
3190                } = self;
3191                traffic_vehicles[slot_idx]
3192            };
3193            let Some((mut tr, mesh_id, is_dynamic)) =
3194                self.get_objects()
3195                    .get(traffic_idx)
3196                    .map(|obj: &SceneObject3D| {
3197                        (obj.get_transform(), obj.get_mesh_id(), obj.get_is_dynamic())
3198                    })
3199            else {
3200                continue;
3201            };
3202            let local_bounds: AxisAlignedBox3D = self
3203                .get_mesh_library()
3204                .get(mesh_id)
3205                .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
3206                .map(Mesh3D::get_bounds)
3207                .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
3208            let total_dz: f32 = vel_z * dt;
3209            if total_dz.abs() <= 1e-6 {
3210                continue;
3211            }
3212            let dir_z: f32 = if vel_z >= 0.0 { 1.0 } else { -1.0 };
3213            let start_z: f32 = tr.get_position().get_z();
3214            let target_z: f32 = start_z + total_dz;
3215            let mut moved_traffic: bool = false;
3216            let mut wrapped: bool = false;
3217            if target_z < z_min || target_z > z_max {
3218                let wrap_z: f32 = if target_z < z_min { z_max } else { z_min };
3219                let mut wrap_tr: Transform3D = tr;
3220                let mut wrap_pos: Vec3 = wrap_tr.get_position();
3221                wrap_pos.set_z(wrap_z);
3222                wrap_tr.set_position(wrap_pos);
3223                let mut probe_tr: Transform3D = wrap_tr;
3224                let mut probe_pos: Vec3 = wrap_pos;
3225                probe_pos.set_z(wrap_z + dir_z * bumper_clearance_m);
3226                probe_tr.set_position(probe_pos);
3227                if self
3228                    .collides_with_obstacles(wrap_tr, local_bounds, traffic_idx)
3229                    .is_none()
3230                    && self
3231                        .collides_with_obstacles(probe_tr, local_bounds, traffic_idx)
3232                        .is_none()
3233                {
3234                    tr = wrap_tr;
3235                    moved_traffic = true;
3236                    wrapped = true;
3237                }
3238            } else {
3239                let substeps: usize = ((total_dz.abs() / 0.20).ceil() as usize).clamp(1, 32);
3240                let step_dz: f32 = total_dz / (substeps as f32);
3241                for _ in 0..substeps {
3242                    let cur_pos: Vec3 = tr.get_position();
3243                    let next_z: f32 = cur_pos.get_z() + step_dz;
3244                    let mut cand_tr: Transform3D = tr;
3245                    let mut cand_pos: Vec3 = cur_pos;
3246                    cand_pos.set_z(next_z);
3247                    cand_tr.set_position(cand_pos);
3248                    let mut probe_tr: Transform3D = cand_tr;
3249                    let mut probe_pos: Vec3 = cand_pos;
3250                    probe_pos.set_z(next_z + dir_z * bumper_clearance_m);
3251                    probe_tr.set_position(probe_pos);
3252                    let blocked: bool = self
3253                        .collides_with_obstacles(cand_tr, local_bounds, traffic_idx)
3254                        .is_some()
3255                        || self
3256                            .collides_with_obstacles(probe_tr, local_bounds, traffic_idx)
3257                            .is_some();
3258                    if blocked {
3259                        break;
3260                    }
3261                    tr = cand_tr;
3262                    moved_traffic = true;
3263                }
3264            }
3265            if moved_traffic {
3266                let world_b: AxisAlignedBox3D = tr.transform_bounds(local_bounds);
3267                if let Some(obj) = self.get_mut_objects().get_mut(traffic_idx) {
3268                    obj.set_transform(tr);
3269                    if wrapped {
3270                        obj.set_teleport_epoch(obj.get_teleport_epoch().wrapping_add(1));
3271                    }
3272                    obj.set_world_bounds(world_b);
3273                }
3274                if is_dynamic {
3275                    any_dynamic_moved = true;
3276                } else {
3277                    any_static_moved = true;
3278                }
3279            }
3280        }
3281        let Self {
3282            objects,
3283            mesh_library,
3284            ..
3285        } = self;
3286        for obj in objects.iter_mut() {
3287            let spin: f32 = obj.get_spin_speed();
3288            if spin.abs() > 0.001 {
3289                let mut object_transform: Transform3D = obj.get_transform();
3290                object_transform.set_yaw_rad(object_transform.get_yaw_rad() + spin * dt);
3291                obj.set_transform(object_transform);
3292                let local_bounds: AxisAlignedBox3D = mesh_library
3293                    .get(obj.get_mesh_id())
3294                    .and_then(|color_item: &MeshLodChain| color_item.get_levels().first())
3295                    .map(Mesh3D::get_bounds)
3296                    .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
3297                obj.set_world_bounds(object_transform.transform_bounds(local_bounds));
3298                if obj.get_is_dynamic() {
3299                    any_dynamic_moved = true;
3300                } else {
3301                    any_static_moved = true;
3302                }
3303            }
3304        }
3305        if self.get_atmosphere_preset() == 1
3306            && (self.get_world_revision() & 1) == 0
3307            && self.get_niagara().get_active_count() < RAINY_NIGHT_MAX_PARTICLES
3308        {
3309            let cam_pos: Vec3 = self.get_camera().get_position();
3310            let mut rain_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
3311            rain_cfg.set_origin(cam_pos.add(Vec3::new(0.0, 5.0, -14.0)));
3312            rain_cfg.set_base_velocity(Vec3::new(-0.5, -15.5, 0.3));
3313            rain_cfg.set_velocity_spread(3.6);
3314            rain_cfg.set_start_color(Color::rgba(150, 218, 255, 210));
3315            rain_cfg.set_end_color(Color::rgba(68, 152, 240, 60));
3316            rain_cfg.set_start_size_m(0.07);
3317            rain_cfg.set_end_size_m(0.03);
3318            rain_cfg.set_min_lifetime(0.6);
3319            rain_cfg.set_max_lifetime(0.95);
3320            rain_cfg.set_emissive_boost(1.4);
3321            self.get_mut_niagara().emit_burst(2, &rain_cfg);
3322        }
3323        if self.get_niagara().get_active_count() > 0 {
3324            let _: usize = self.get_mut_niagara().update(dt, 0.0);
3325        }
3326        if any_static_moved {
3327            self.set_bvh_dirty(true);
3328        }
3329        if any_dynamic_moved {
3330            self.set_dynamic_bvh_dirty(true);
3331        }
3332        if any_static_moved || any_dynamic_moved {
3333            self.bump_world_revision();
3334        }
3335    }
3336}