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.85, sun_y.max(0.18), 0.52).normalize();
761        if (7.5..=16.5).contains(&height_val) {
762            Self {
763                direction: dir,
764                color: Vec3::new(2.2, 2.08, 1.92),
765                sky_zenith: Vec3::new(0.14, 0.34, 0.72),
766                sky_horizon: Vec3::new(0.62, 0.78, 0.94),
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: dir,
772                color: Vec3::new(2.4, 1.35, 0.72),
773                sky_zenith: Vec3::new(0.15, 0.14, 0.38),
774                sky_horizon: Vec3::new(0.92, 0.45, 0.28),
775                time_of_day: height_val,
776            }
777        } else {
778            Self {
779                direction: Vec3::new(-0.4, 0.65, 0.55).normalize(),
780                color: Vec3::new(0.55, 0.68, 1.15),
781                sky_zenith: Vec3::new(0.02, 0.03, 0.09),
782                sky_horizon: Vec3::new(0.08, 0.11, 0.24),
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        }
837    }
838}
839
840/// Open-world construction, model importing, BVH rebuild, and live vehicle/camera simulation for `World3D`.
841impl World3D {
842    /// Registers a `MeshLodChain` in the instancing library and returns its `mesh_id`.
843    ///
844    /// # Arguments
845    ///
846    /// - `&Self` - Mutable world.
847    /// - `MeshLodChain` - Multi-level LOD mesh chain.
848    ///
849    /// # Returns
850    ///
851    /// - `usize` - Assigned `mesh_id`.
852    pub fn register_mesh(&mut self, chain: MeshLodChain) -> usize {
853        let id: usize = self.get_mesh_library().len();
854        self.get_mut_mesh_library().push(chain);
855        id
856    }
857
858    /// Spawns an instanced `SceneObject3D` referencing `mesh_id` into its spatial world chunk.
859    ///
860    /// # Arguments
861    ///
862    /// - `&Self` - Mutable world.
863    /// - `&str` - Object name.
864    /// - `usize` - Registered `mesh_id`.
865    /// - `Transform3D` - World transform.
866    /// - `PbrMaterial` - Surface PBR material.
867    /// - `bool` - Whether this object participates in BVH ray tracing.
868    ///
869    /// # Returns
870    ///
871    /// - `usize` - Index of the spawned `SceneObject3D`.
872    pub fn spawn_object(
873        &mut self,
874        name: &str,
875        mesh_id: usize,
876        transform: Transform3D,
877        material: PbrMaterial,
878        ray_trace_caster: bool,
879    ) -> usize {
880        let local_bounds: AxisAlignedBox3D = self
881            .get_mesh_library()
882            .get(mesh_id)
883            .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
884            .map(Mesh3D::get_bounds)
885            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
886        let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
887        let cs: f32 = self.get_chunk_size().max(8.0);
888        let pos: Vec3 = transform.get_position();
889        let chunk_coord: (i32, i32) = (
890            (pos.get_x() / cs).floor() as i32,
891            (pos.get_z() / cs).floor() as i32,
892        );
893        let idx: usize = self.get_objects().len();
894        self.get_mut_objects().push(SceneObject3D {
895            name: name.to_string(),
896            mesh_id,
897            transform,
898            material,
899            world_bounds,
900            chunk_coord,
901            ray_trace_caster,
902            spin_speed: 0.0,
903            is_dynamic: false,
904            teleport_epoch: 0,
905        });
906        if ray_trace_caster {
907            self.set_bvh_dirty(true);
908        }
909        self.bump_world_revision();
910        idx
911    }
912
913    /// Increments the 3D world revision counter so 3D render caches invalidate independently of UI HUD updates.
914    ///
915    /// # Arguments
916    ///
917    /// - `&Self` - Mutable world.
918    pub fn bump_world_revision(&mut self) {
919        let next: u64 = self.get_world_revision().wrapping_add(1);
920        self.set_world_revision(next);
921    }
922
923    /// Marks object `obj_idx` as static or dynamic, routing its triangles between the static BVH and incrementally refitted dynamic BVH.
924    ///
925    /// # Arguments
926    ///
927    /// - `&Self` - Mutable world.
928    /// - `usize` - Target object index in `objects`.
929    /// - `bool` - `true` for dynamic BVH routing, `false` for static BVH routing.
930    ///
931    /// # Returns
932    ///
933    /// - `bool` - `true` when `obj_idx` existed and was updated.
934    pub fn set_object_dynamic(&mut self, obj_idx: usize, is_dynamic: bool) -> bool {
935        let Some(obj) = self.get_mut_objects().get_mut(obj_idx) else {
936            return false;
937        };
938        if obj.get_is_dynamic() != is_dynamic {
939            obj.set_is_dynamic(is_dynamic);
940            if obj.get_ray_trace_caster() {
941                self.set_bvh_dirty(true);
942                self.set_dynamic_bvh_dirty(true);
943                self.set_dynamic_topology_dirty(true);
944            }
945            self.bump_world_revision();
946        }
947        true
948    }
949
950    /// Teleports object `obj_idx` to `transform`, incrementing `teleport_epoch` so snapshot interpolation snaps instead of sweeping.
951    ///
952    /// # Arguments
953    ///
954    /// - `&Self` - Mutable world.
955    /// - `usize` - Target object index in `objects`.
956    /// - `Transform3D` - Destination world transform.
957    ///
958    /// # Returns
959    ///
960    /// - `bool` - `true` when `obj_idx` existed and was teleported.
961    pub fn teleport_object(&mut self, obj_idx: usize, transform: Transform3D) -> bool {
962        let Some((mesh_id, ray_caster, is_dynamic)) =
963            self.get_objects().get(obj_idx).map(|obj: &SceneObject3D| {
964                (
965                    obj.get_mesh_id(),
966                    obj.get_ray_trace_caster(),
967                    obj.get_is_dynamic(),
968                )
969            })
970        else {
971            return false;
972        };
973        let local_bounds: AxisAlignedBox3D = self
974            .get_mesh_library()
975            .get(mesh_id)
976            .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
977            .map(Mesh3D::get_bounds)
978            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
979        let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
980        if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
981            obj.set_transform(transform);
982            obj.set_world_bounds(world_bounds);
983            let next_epoch: u32 = obj.get_teleport_epoch().wrapping_add(1);
984            obj.set_teleport_epoch(next_epoch);
985        }
986        if ray_caster {
987            if is_dynamic {
988                self.set_dynamic_bvh_dirty(true);
989            } else {
990                self.set_bvh_dirty(true);
991            }
992        }
993        self.bump_world_revision();
994        true
995    }
996
997    /// Imports an external `.obj` or `.gltf` model directly into the live 3D world and returns import telemetry.
998    ///
999    /// # Arguments
1000    ///
1001    /// - `&Self` - Mutable world.
1002    /// - `ModelFormat` - Source model format.
1003    /// - `&str` - Raw `.obj` or `.gltf` text content.
1004    /// - `Transform3D` - Placement transform in the 3D scene.
1005    /// - `PbrMaterial` - Fallback PBR material.
1006    /// - `f32` - Optional continuous Y-spin speed in radians/sec.
1007    ///
1008    /// # Returns
1009    ///
1010    /// - `Result<ImportedModel3D, String>` - Imported model summary or parse error.
1011    pub fn import_model(
1012        &mut self,
1013        format: ModelFormat,
1014        source: &str,
1015        transform: Transform3D,
1016        fallback_material: PbrMaterial,
1017        spin_speed: f32,
1018    ) -> Result<ImportedModel3D, String> {
1019        let imported: ImportedModel3D = ModelImporter3D::import(format, source, fallback_material)?;
1020        let model_name: String = imported.get_name().clone();
1021        for (item_index, chain) in imported.get_meshes().iter().cloned().enumerate() {
1022            let mat: PbrMaterial = chain
1023                .get_levels()
1024                .first()
1025                .map(Mesh3D::get_material)
1026                .unwrap_or(fallback_material);
1027            let mid: usize = self.register_mesh(chain);
1028            let obj_idx: usize = self.spawn_object(
1029                &format!("{model_name}_{item_index}"),
1030                mid,
1031                transform,
1032                mat,
1033                true,
1034            );
1035            if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
1036                obj.set_spin_speed(spin_speed);
1037            }
1038            if spin_speed.abs() > 0.001 {
1039                let _: bool = self.set_object_dynamic(obj_idx, true);
1040            }
1041        }
1042        let next_cnt: usize = self.get_imported_model_count().saturating_add(1);
1043        self.set_imported_model_count(next_cnt);
1044        Ok(imported)
1045    }
1046
1047    /// Spawns an object from a fluent `SpawnObjectDesc`.
1048    ///
1049    /// # Arguments
1050    ///
1051    /// - `&Self` - Mutable world.
1052    /// - `&SpawnObjectDesc` - Spawn descriptor.
1053    ///
1054    /// # Returns
1055    ///
1056    /// - `usize` - Spawned object index.
1057    pub fn spawn_with(&mut self, desc: &SpawnObjectDesc) -> usize {
1058        let idx: usize = self.spawn_object(
1059            desc.get_name(),
1060            desc.get_mesh_id(),
1061            desc.get_transform(),
1062            desc.get_material(),
1063            desc.get_ray_trace_caster(),
1064        );
1065        if let Some(obj) = self.get_mut_objects().get_mut(idx) {
1066            obj.set_spin_speed(desc.get_spin_speed());
1067        }
1068        if desc.get_is_dynamic() || desc.get_spin_speed().abs() > 0.001 {
1069            let _: bool = self.set_object_dynamic(idx, true);
1070        }
1071        idx
1072    }
1073
1074    /// Imports an external `.obj` or `.gltf` model using a fluent `ImportModelDesc`.
1075    ///
1076    /// # Arguments
1077    ///
1078    /// - `&Self` - Mutable world.
1079    /// - `&ImportModelDesc` - Import descriptor.
1080    ///
1081    /// # Returns
1082    ///
1083    /// - `Result<ImportedModel3D, String>` - Imported model telemetry or parse error.
1084    pub fn import_with(&mut self, desc: &ImportModelDesc) -> Result<ImportedModel3D, String> {
1085        self.import_model(
1086            desc.get_format(),
1087            desc.get_source(),
1088            desc.get_transform(),
1089            desc.get_fallback_material(),
1090            desc.get_spin_speed(),
1091        )
1092    }
1093
1094    /// Returns the typed `CameraMode3D` currently active in this world.
1095    ///
1096    /// # Arguments
1097    ///
1098    /// - `&Self` - World reference.
1099    ///
1100    /// # Returns
1101    ///
1102    /// - `CameraMode3D` - Active typed camera controller mode.
1103    #[must_use]
1104    pub fn active_camera_mode(&self) -> CameraMode3D {
1105        CameraMode3D::from_u8(self.get_camera_mode())
1106    }
1107
1108    /// Sets the active 3D camera controller using a typed `CameraMode3D`.
1109    ///
1110    /// # Arguments
1111    ///
1112    /// - `&Self` - Mutable world.
1113    /// - `CameraMode3D` - Desired camera controller mode.
1114    pub fn set_camera_mode_enum(&mut self, mode: CameraMode3D) {
1115        self.set_camera_mode(mode.as_u8());
1116    }
1117
1118    /// Collects world-space triangles for all ray-trace casters matching `dynamic_filter` into `out_tris`.
1119    ///
1120    /// # Arguments
1121    ///
1122    /// - `&[SceneObject3D]` - World object slice.
1123    /// - `&[MeshLodChain]` - Registered mesh library slice.
1124    /// - `bool` - `true` to gather dynamic casters, `false` to gather static casters.
1125    /// - `&mut Vec<BvhTriangle>` - Destination triangle buffer cleared and populated in place.
1126    fn collect_caster_triangles(
1127        objects: &[SceneObject3D],
1128        mesh_library: &[MeshLodChain],
1129        dynamic_filter: bool,
1130        out_tris: &mut Vec<BvhTriangle>,
1131    ) {
1132        out_tris.clear();
1133        for obj in objects.iter() {
1134            if !obj.get_ray_trace_caster() || obj.get_is_dynamic() != dynamic_filter {
1135                continue;
1136            }
1137            let Some(chain) = mesh_library.get(obj.get_mesh_id()) else {
1138                continue;
1139            };
1140            let Some(mesh) = chain.get_levels().first() else {
1141                continue;
1142            };
1143            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1144            let model_m: Mat4 = obj.get_transform().to_mat4();
1145            let mat: PbrMaterial = obj.get_material();
1146            for tri in mesh.get_indices().iter() {
1147                let (i0, i1, i2): (usize, usize, usize) =
1148                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1149                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1150                    let p0: Vec3 = model_m.mul_point3(verts[i0].get_position());
1151                    let p1: Vec3 = model_m.mul_point3(verts[i1].get_position());
1152                    let p2: Vec3 = model_m.mul_point3(verts[i2].get_position());
1153                    out_tris.push(BvhTriangle::from_points(p0, p1, p2, mat));
1154                }
1155            }
1156        }
1157    }
1158
1159    /// Synchronizes the split static and dynamic BVH acceleration structures, refitting moving dynamic casters in O(N) without rebuilding static world geometry.
1160    ///
1161    /// # Arguments
1162    ///
1163    /// - `&Self` - Mutable world.
1164    pub fn ensure_bvh(&mut self) {
1165        if self.get_bvh_dirty() {
1166            let mut static_tris: Vec<BvhTriangle> = Vec::new();
1167            Self::collect_caster_triangles(
1168                self.get_objects().as_slice(),
1169                self.get_mesh_library().as_slice(),
1170                false,
1171                &mut static_tris,
1172            );
1173            self.set_bvh(Bvh3D::build(static_tris));
1174            self.set_bvh_dirty(false);
1175            let next_static: u64 = self.get_static_bvh_rebuilds().saturating_add(1);
1176            self.set_static_bvh_rebuilds(next_static);
1177        }
1178        if self.get_dynamic_bvh_dirty() {
1179            let topology_dirty: bool = self.get_dynamic_topology_dirty();
1180            let Self {
1181                objects,
1182                mesh_library,
1183                dynamic_bvh,
1184                dynamic_tris_scratch,
1185                dynamic_bvh_dirty,
1186                dynamic_topology_dirty,
1187                dynamic_bvh_refits,
1188                dynamic_bvh_rebuilds,
1189                ..
1190            } = self;
1191            Self::collect_caster_triangles(
1192                objects.as_slice(),
1193                mesh_library.as_slice(),
1194                true,
1195                dynamic_tris_scratch,
1196            );
1197            if dynamic_tris_scratch.is_empty() {
1198                dynamic_bvh.rebuild_in_place(&[]);
1199            } else if !topology_dirty
1200                && dynamic_bvh.refit_from_source(dynamic_tris_scratch.as_slice())
1201            {
1202                if dynamic_bvh.needs_rebuild_after_refit(1.65) {
1203                    dynamic_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
1204                    *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
1205                } else {
1206                    *dynamic_bvh_refits = dynamic_bvh_refits.saturating_add(1);
1207                }
1208            } else {
1209                dynamic_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
1210                *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
1211            }
1212            *dynamic_bvh_dirty = false;
1213            *dynamic_topology_dirty = false;
1214        }
1215        self.sync_dynamic_ray_instances();
1216    }
1217
1218    /// Lazily constructs local-space BVH4/BVH8 trees for dynamic meshes and updates `dynamic_instances` from current object transforms with zero BVH rebuilds.
1219    ///
1220    /// # Arguments
1221    ///
1222    /// - `&Self` - Mutable world reference.
1223    pub fn sync_dynamic_ray_instances(&mut self) {
1224        let Self {
1225            mesh_library,
1226            objects,
1227            mesh_local_bvhs,
1228            dynamic_instances,
1229            ..
1230        } = self;
1231        if mesh_local_bvhs.len() < mesh_library.len() {
1232            mesh_local_bvhs.resize_with(mesh_library.len(), || None);
1233        }
1234        dynamic_instances.clear();
1235        for (obj_idx, obj) in objects.iter().enumerate() {
1236            if !obj.get_ray_trace_caster() || !obj.get_is_dynamic() {
1237                continue;
1238            }
1239            let mesh_id: usize = obj.get_mesh_id();
1240            let Some(chain) = mesh_library.get(mesh_id) else {
1241                continue;
1242            };
1243            let Some(mesh) = chain.get_levels().first() else {
1244                continue;
1245            };
1246            if mesh_local_bvhs[mesh_id].is_none() {
1247                let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1248                let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
1249                let mut local_tris: Vec<BvhTriangle> = Vec::with_capacity(indices.len());
1250                let neutral: PbrMaterial = PbrMaterial::default();
1251                for tri in indices.iter() {
1252                    let (i0, i1, i2): (usize, usize, usize) =
1253                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1254                    if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1255                        local_tris.push(BvhTriangle::from_points(
1256                            verts[i0].get_position(),
1257                            verts[i1].get_position(),
1258                            verts[i2].get_position(),
1259                            neutral,
1260                        ));
1261                    }
1262                }
1263                mesh_local_bvhs[mesh_id] = Some(Bvh3D::build(local_tris));
1264            }
1265            let transform_val: Transform3D = obj.get_transform();
1266            dynamic_instances.push(DynamicRayInstance {
1267                obj_idx,
1268                mesh_id,
1269                world_bounds: obj.get_world_bounds(),
1270                inv_model: transform_val.to_inv_mat4(),
1271                normal_basis: transform_val.normal_mat3(),
1272                material: obj.get_material(),
1273            });
1274        }
1275    }
1276
1277    /// Updates only the inverse-model transform, normal basis, and world axis-aligned bounding box of an existing dynamic instance without rebuilding any BVH.
1278    ///
1279    /// # Arguments
1280    ///
1281    /// - `&Self` - Mutable world reference.
1282    /// - `usize` - Scene object index.
1283    /// - `Transform3D` - Interpolated world transform.
1284    /// - `AxisAlignedBox3D` - Interpolated world axis-aligned bounding box.
1285    pub(crate) fn override_dynamic_instance_pose(
1286        &mut self,
1287        obj_idx: usize,
1288        transform: Transform3D,
1289        world_bounds: AxisAlignedBox3D,
1290    ) {
1291        let Self {
1292            dynamic_instances, ..
1293        } = self;
1294        for inst in dynamic_instances.iter_mut() {
1295            if inst.obj_idx == obj_idx {
1296                inst.world_bounds = world_bounds;
1297                inst.inv_model = transform.to_inv_mat4();
1298                inst.normal_basis = transform.normal_mat3();
1299                return;
1300            }
1301        }
1302    }
1303
1304    /// Traces a shadow ray against object-space dynamic instances via inverse interpolated `Mat4` with zero dynamic BVH rebuilds.
1305    ///
1306    /// # Arguments
1307    ///
1308    /// - `&[DynamicRayInstance]` - Active dynamic raytracing instances.
1309    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1310    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1311    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1312    /// - `&mut u32` - Per-thread local occluder triangle hint.
1313    ///
1314    /// # Returns
1315    ///
1316    /// - `bool` - `true` if occluded by any dynamic object at its current or interpolated pose.
1317    #[inline(always)]
1318    #[must_use]
1319    pub(crate) fn trace_any_shadow_dynamic_instances(
1320        instances: &[DynamicRayInstance],
1321        local_bvhs: &[Option<Bvh3D>],
1322        ray: (Vec3, Vec3, Vec3),
1323        bounds: (f32, f32),
1324        dyn_cache: &mut u32,
1325    ) -> bool {
1326        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1327        let (t_min, t_max): (f32, f32) = bounds;
1328        for inst in instances.iter() {
1329            if !inst
1330                .world_bounds
1331                .intersect_ray_near(origin, inv_dir, t_min, t_max)
1332                .is_finite()
1333            {
1334                continue;
1335            }
1336            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1337                continue;
1338            };
1339            let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
1340            let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
1341            let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
1342            if local_bvh
1343                .trace_any_shadow_cached(local_orig, local_dir, local_inv, t_min, t_max, dyn_cache)
1344            {
1345                return true;
1346            }
1347        }
1348        false
1349    }
1350
1351    /// Traces a coherent 4-ray shadow packet against static BVH and object-space inverse-interpolated dynamic instances.
1352    ///
1353    /// # Arguments
1354    ///
1355    /// - `&Bvh3D` - Static world BVH4/BVH8.
1356    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1357    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1358    /// - `&RayPacket4` - Coherent 4-ray shadow packet.
1359    /// - `u8` - 4-bit mask of active rays to trace.
1360    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1361    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder hints.
1362    ///
1363    /// # Returns
1364    ///
1365    /// - `u8` - 4-bit mask of occluded rays.
1366    #[inline(always)]
1367    #[must_use]
1368    pub(crate) fn trace_any_shadow_packet4_with_instances(
1369        static_bvh: &Bvh3D,
1370        instances: &[DynamicRayInstance],
1371        local_bvhs: &[Option<Bvh3D>],
1372        pkt: &RayPacket4,
1373        active_mask: u8,
1374        bounds: (f32, f32),
1375        caches: (&mut u32, &mut u32),
1376    ) -> u8 {
1377        let (t_min, t_max): (f32, f32) = bounds;
1378        let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
1379        let mut occluded: u8 =
1380            static_bvh.trace_any_shadow_packet4(pkt, active_mask, t_min, t_max, static_cache);
1381        let mut rem: u8 = active_mask & !occluded;
1382        if rem == 0 || instances.is_empty() {
1383            return occluded;
1384        }
1385        for inst in instances.iter() {
1386            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1387                continue;
1388            };
1389            let mut hit_box_mask: u8 = 0;
1390            let mut check: u8 = rem;
1391            while check != 0 {
1392                let red_val: usize = check.trailing_zeros() as usize;
1393                check &= check - 1;
1394                let orig_r: Vec3 = Vec3::new(pkt.ox[red_val], pkt.oy[red_val], pkt.oz[red_val]);
1395                let inv_r: Vec3 = Vec3::new(pkt.ix[red_val], pkt.iy[red_val], pkt.iz[red_val]);
1396                if inst
1397                    .world_bounds
1398                    .intersect_ray_near(orig_r, inv_r, t_min, t_max)
1399                    .is_finite()
1400                {
1401                    hit_box_mask |= 1_u8 << red_val;
1402                }
1403            }
1404            if hit_box_mask == 0 {
1405                continue;
1406            }
1407            let mut local_pkt: RayPacket4 = *pkt;
1408            let mut tr_mask: u8 = hit_box_mask;
1409            while tr_mask != 0 {
1410                let radius_val: usize = tr_mask.trailing_zeros() as usize;
1411                tr_mask &= tr_mask - 1;
1412                let lo: Vec3 = inst.inv_model.mul_point3(Vec3::new(
1413                    pkt.ox[radius_val],
1414                    pkt.oy[radius_val],
1415                    pkt.oz[radius_val],
1416                ));
1417                let ld: Vec3 = inst.inv_model.mul_vec3(Vec3::new(
1418                    pkt.dx[radius_val],
1419                    pkt.dy[radius_val],
1420                    pkt.dz[radius_val],
1421                ));
1422                let li: Vec3 = Ray3D::safe_inv_vec(ld);
1423                local_pkt.ox[radius_val] = lo.get_x();
1424                local_pkt.oy[radius_val] = lo.get_y();
1425                local_pkt.oz[radius_val] = lo.get_z();
1426                local_pkt.dx[radius_val] = ld.get_x();
1427                local_pkt.dy[radius_val] = ld.get_y();
1428                local_pkt.dz[radius_val] = ld.get_z();
1429                local_pkt.ix[radius_val] = li.get_x();
1430                local_pkt.iy[radius_val] = li.get_y();
1431                local_pkt.iz[radius_val] = li.get_z();
1432            }
1433            let dyn_occ: u8 = local_bvh.trace_any_shadow_packet4(
1434                &local_pkt,
1435                hit_box_mask,
1436                t_min,
1437                t_max,
1438                dyn_cache,
1439            );
1440            occluded |= dyn_occ;
1441            rem &= !dyn_occ;
1442            if rem == 0 {
1443                break;
1444            }
1445        }
1446        occluded
1447    }
1448
1449    /// Traces a shadow/occlusion ray across static BVH and object-space inverse-interpolated dynamic instances.
1450    ///
1451    /// # Arguments
1452    ///
1453    /// - `&Bvh3D` - Static world BVH.
1454    /// - `&[DynamicRayInstance]` - Active dynamic raytracing instances.
1455    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1456    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1457    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1458    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder hints.
1459    ///
1460    /// # Returns
1461    ///
1462    /// - `bool` - `true` when occluded by static or dynamic geometry.
1463    #[inline(always)]
1464    #[must_use]
1465    pub(crate) fn trace_any_shadow_with_instances(
1466        static_bvh: &Bvh3D,
1467        instances: &[DynamicRayInstance],
1468        local_bvhs: &[Option<Bvh3D>],
1469        ray: (Vec3, Vec3, Vec3),
1470        bounds: (f32, f32),
1471        caches: (&mut u32, &mut u32),
1472    ) -> bool {
1473        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1474        let (t_min, t_max): (f32, f32) = bounds;
1475        let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
1476        if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
1477            return true;
1478        }
1479        if !instances.is_empty() {
1480            return Self::trace_any_shadow_dynamic_instances(
1481                instances, local_bvhs, ray, bounds, dyn_cache,
1482            );
1483        }
1484        false
1485    }
1486
1487    /// Traces a reflection/GI ray across static BVH and object-space inverse-interpolated dynamic instances, returning `(distance, world_normal, material)`.
1488    ///
1489    /// # Arguments
1490    ///
1491    /// - `&Bvh3D` - Static world BVH.
1492    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1493    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1494    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1495    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1496    ///
1497    /// # Returns
1498    ///
1499    /// - `Option<(f32, Vec3, PbrMaterial)>` - Closest hit distance, world-space unit normal, and PBR material.
1500    #[inline(always)]
1501    #[must_use]
1502    pub(crate) fn trace_closest_with_instances(
1503        static_bvh: &Bvh3D,
1504        instances: &[DynamicRayInstance],
1505        local_bvhs: &[Option<Bvh3D>],
1506        ray: (Vec3, Vec3, Vec3),
1507        bounds: (f32, f32),
1508    ) -> Option<(f32, Vec3, PbrMaterial)> {
1509        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1510        let (t_min, t_max): (f32, f32) = bounds;
1511        let mut best_t: f32 = t_max;
1512        let mut best_hit: Option<(f32, Vec3, PbrMaterial)> = static_bvh
1513            .trace_closest_raw(origin, dir, inv_dir, t_min, t_max)
1514            .map(|(node_style, si): (f32, usize)| {
1515                let tri: &BvhTriangle = &static_bvh.get_triangles()[si];
1516                best_t = node_style;
1517                (node_style, tri.get_normal(), tri.get_material())
1518            });
1519        for inst in instances.iter() {
1520            if !inst
1521                .world_bounds
1522                .intersect_ray_near(origin, inv_dir, t_min, best_t)
1523                .is_finite()
1524            {
1525                continue;
1526            }
1527            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1528                continue;
1529            };
1530            let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
1531            let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
1532            let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
1533            if let Some((dt, di)) =
1534                local_bvh.trace_closest_raw(local_orig, local_dir, local_inv, t_min, best_t)
1535            {
1536                best_t = dt;
1537                let local_n: Vec3 = local_bvh.get_triangles()[di].get_normal();
1538                let world_n: Vec3 = Mat4::transform_normal_with_basis(local_n, inst.normal_basis);
1539                best_hit = Some((dt, world_n, inst.material));
1540            }
1541        }
1542        best_hit
1543    }
1544
1545    /// Traces a coherent 4-ray closest-hit packet across static BVH and object-space inverse-interpolated dynamic instances.
1546    ///
1547    /// # Arguments
1548    ///
1549    /// - `&Bvh3D` - Static world BVH4/BVH8.
1550    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1551    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1552    /// - `&RayPacket4` - Coherent 4-ray reflection or GI packet.
1553    /// - `u8` - 4-bit mask of active rays.
1554    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1555    ///
1556    /// # Returns
1557    ///
1558    /// - `[Option<(f32, Vec3, PbrMaterial)>; 4]` - Closest hit distance, world normal, and material per lane.
1559    #[inline(always)]
1560    #[must_use]
1561    pub(crate) fn trace_closest_packet4_with_instances(
1562        static_bvh: &Bvh3D,
1563        instances: &[DynamicRayInstance],
1564        local_bvhs: &[Option<Bvh3D>],
1565        pkt: &RayPacket4,
1566        active_mask: u8,
1567        bounds: (f32, f32),
1568    ) -> [Option<(f32, Vec3, PbrMaterial)>; 4] {
1569        let (t_min, t_max): (f32, f32) = bounds;
1570        let mut best_t: [f32; 4] = [t_max; 4];
1571        let mut best_static_idx: [usize; 4] = [usize::MAX; 4];
1572        static_bvh.trace_closest_packet4(
1573            pkt,
1574            active_mask,
1575            t_min,
1576            &mut best_t,
1577            &mut best_static_idx,
1578        );
1579        let static_tris: &[BvhTriangle] = static_bvh.get_triangles().as_slice();
1580        let mut out: [Option<(f32, Vec3, PbrMaterial)>; 4] = [None; 4];
1581        let mut matrix_elems: u8 = active_mask;
1582        while matrix_elems != 0 {
1583            let red_val: usize = matrix_elems.trailing_zeros() as usize;
1584            matrix_elems &= matrix_elems - 1;
1585            let sidx: usize = best_static_idx[red_val];
1586            if sidx != usize::MAX {
1587                let tri: &BvhTriangle = &static_tris[sidx];
1588                out[red_val] = Some((best_t[red_val], tri.get_normal(), tri.get_material()));
1589            }
1590        }
1591        for inst in instances.iter() {
1592            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1593                continue;
1594            };
1595            let mut hit_box_mask: u8 = 0;
1596            let mut check: u8 = active_mask;
1597            while check != 0 {
1598                let radius_val: usize = check.trailing_zeros() as usize;
1599                check &= check - 1;
1600                if inst
1601                    .world_bounds
1602                    .intersect_ray_near(
1603                        Vec3::new(pkt.ox[radius_val], pkt.oy[radius_val], pkt.oz[radius_val]),
1604                        Vec3::new(pkt.ix[radius_val], pkt.iy[radius_val], pkt.iz[radius_val]),
1605                        t_min,
1606                        best_t[radius_val],
1607                    )
1608                    .is_finite()
1609                {
1610                    hit_box_mask |= 1_u8 << radius_val;
1611                }
1612            }
1613            if hit_box_mask == 0 {
1614                continue;
1615            }
1616            let mut local_pkt: RayPacket4 = *pkt;
1617            let mut tr_mask: u8 = hit_box_mask;
1618            while tr_mask != 0 {
1619                let rect_val: usize = tr_mask.trailing_zeros() as usize;
1620                tr_mask &= tr_mask - 1;
1621                let lo: Vec3 = inst.inv_model.mul_point3(Vec3::new(
1622                    pkt.ox[rect_val],
1623                    pkt.oy[rect_val],
1624                    pkt.oz[rect_val],
1625                ));
1626                let ld: Vec3 = inst.inv_model.mul_vec3(Vec3::new(
1627                    pkt.dx[rect_val],
1628                    pkt.dy[rect_val],
1629                    pkt.dz[rect_val],
1630                ));
1631                let li: Vec3 = Ray3D::safe_inv_vec(ld);
1632                local_pkt.ox[rect_val] = lo.get_x();
1633                local_pkt.oy[rect_val] = lo.get_y();
1634                local_pkt.oz[rect_val] = lo.get_z();
1635                local_pkt.dx[rect_val] = ld.get_x();
1636                local_pkt.dy[rect_val] = ld.get_y();
1637                local_pkt.dz[rect_val] = ld.get_z();
1638                local_pkt.ix[rect_val] = li.get_x();
1639                local_pkt.iy[rect_val] = li.get_y();
1640                local_pkt.iz[rect_val] = li.get_z();
1641            }
1642            let mut dyn_idx: [usize; 4] = [usize::MAX; 4];
1643            local_bvh.trace_closest_packet4(
1644                &local_pkt,
1645                hit_box_mask,
1646                t_min,
1647                &mut best_t,
1648                &mut dyn_idx,
1649            );
1650            let local_tris: &[BvhTriangle] = local_bvh.get_triangles().as_slice();
1651            let mut upd: u8 = hit_box_mask;
1652            while upd != 0 {
1653                let row_val: usize = upd.trailing_zeros() as usize;
1654                upd &= upd - 1;
1655                let di: usize = dyn_idx[row_val];
1656                if di != usize::MAX {
1657                    let wn: Vec3 = Mat4::transform_normal_with_basis(
1658                        local_tris[di].get_normal(),
1659                        inst.normal_basis,
1660                    );
1661                    out[row_val] = Some((best_t[row_val], wn, inst.material));
1662                }
1663            }
1664        }
1665        out
1666    }
1667
1668    /// Traces a shadow ray using static BVH plus object-space inverse-interpolated dynamic instances.
1669    ///
1670    /// # Arguments
1671    ///
1672    /// - `&Self` - World reference.
1673    /// - `&Ray3D` - World-space shadow ray.
1674    /// - `f32` - Minimum hit distance.
1675    /// - `f32` - Maximum hit distance.
1676    ///
1677    /// # Returns
1678    ///
1679    /// - `bool` - `true` when occluded by static or dynamic geometry at its current/interpolated pose.
1680    #[must_use]
1681    pub fn trace_any_shadow_object_space(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
1682        let Self {
1683            bvh,
1684            dynamic_instances,
1685            mesh_local_bvhs,
1686            ..
1687        } = self;
1688        let mut scale_factor: u32 = u32::MAX;
1689        let mut dc: u32 = u32::MAX;
1690        Self::trace_any_shadow_with_instances(
1691            bvh,
1692            dynamic_instances.as_slice(),
1693            mesh_local_bvhs.as_slice(),
1694            (
1695                ray.get_origin(),
1696                ray.get_direction(),
1697                ray.get_inv_direction(),
1698            ),
1699            (t_min, t_max),
1700            (&mut scale_factor, &mut dc),
1701        )
1702    }
1703
1704    /// Traces a coherent 4-ray closest-hit packet against both the static BVH4 and object-space inverse-interpolated dynamic instances.
1705    ///
1706    /// # Arguments
1707    ///
1708    /// - `&Self` - World reference.
1709    /// - `&RayPacket4` - Coherent 4-ray query packet.
1710    /// - `u8` - 4-bit mask of active rays (`0..=15`).
1711    /// - `f32` - Minimum hit distance.
1712    /// - `f32` - Maximum hit distance.
1713    ///
1714    /// # Returns
1715    ///
1716    /// - `[Option<RayHit3D>; 4]` - Closest hit surface with world normal and material per active lane.
1717    #[must_use]
1718    pub fn trace_closest_packet4(
1719        &self,
1720        pkt: &RayPacket4,
1721        active_mask: u8,
1722        t_min: f32,
1723        t_max: f32,
1724    ) -> [Option<RayHit3D>; 4] {
1725        let Self {
1726            bvh,
1727            dynamic_instances,
1728            mesh_local_bvhs,
1729            ..
1730        } = self;
1731        let raw: [Option<(f32, Vec3, PbrMaterial)>; 4] = Self::trace_closest_packet4_with_instances(
1732            bvh,
1733            dynamic_instances.as_slice(),
1734            mesh_local_bvhs.as_slice(),
1735            pkt,
1736            active_mask,
1737            (t_min, t_max),
1738        );
1739        let mut out: [Option<RayHit3D>; 4] = [None; 4];
1740        for lane in 0..4 {
1741            if let Some((blend_factor, normal, material)) = raw[lane] {
1742                let point: Vec3 = Vec3::new(
1743                    pkt.ox[lane] + pkt.dx[lane] * blend_factor,
1744                    pkt.oy[lane] + pkt.dy[lane] * blend_factor,
1745                    pkt.oz[lane] + pkt.dz[lane] * blend_factor,
1746                );
1747                out[lane] = Some(RayHit3D {
1748                    distance: blend_factor,
1749                    point,
1750                    normal,
1751                    material,
1752                });
1753            }
1754        }
1755        out
1756    }
1757
1758    /// Traces a closest-hit ray using static BVH plus object-space inverse-interpolated dynamic instances.
1759    ///
1760    /// # Arguments
1761    ///
1762    /// - `&Self` - World reference.
1763    /// - `&Ray3D` - World-space query ray.
1764    /// - `f32` - Minimum hit distance.
1765    /// - `f32` - Maximum hit distance.
1766    ///
1767    /// # Returns
1768    ///
1769    /// - `Option<RayHit3D>` - Closest hit surface with world-space normal and material.
1770    #[must_use]
1771    pub fn trace_closest_object_space(
1772        &self,
1773        ray: &Ray3D,
1774        t_min: f32,
1775        t_max: f32,
1776    ) -> Option<RayHit3D> {
1777        let Self {
1778            bvh,
1779            dynamic_instances,
1780            mesh_local_bvhs,
1781            ..
1782        } = self;
1783        let (blend_factor, normal, material): (f32, Vec3, PbrMaterial) =
1784            Self::trace_closest_with_instances(
1785                bvh,
1786                dynamic_instances.as_slice(),
1787                mesh_local_bvhs.as_slice(),
1788                (
1789                    ray.get_origin(),
1790                    ray.get_direction(),
1791                    ray.get_inv_direction(),
1792                ),
1793                (t_min, t_max),
1794            )?;
1795        Some(RayHit3D {
1796            distance: blend_factor,
1797            point: ray
1798                .get_origin()
1799                .add(ray.get_direction().scale(blend_factor)),
1800            normal,
1801            material,
1802        })
1803    }
1804
1805    /// Returns the combined node count across both static and dynamic BVH acceleration trees.
1806    ///
1807    /// # Arguments
1808    ///
1809    /// - `&Self` - World reference.
1810    ///
1811    /// # Returns
1812    ///
1813    /// - `usize` - Total active BVH nodes.
1814    #[must_use]
1815    pub fn total_bvh_nodes(&self) -> usize {
1816        self.get_bvh()
1817            .get_nodes()
1818            .len()
1819            .saturating_add(self.get_dynamic_bvh().get_nodes().len())
1820    }
1821
1822    /// Traces a shadow/occlusion ray across both static and dynamic BVHs using 1-triangle occluder caches.
1823    ///
1824    /// # Arguments
1825    ///
1826    /// - `(&Bvh3D, &Bvh3D)` - `(static_bvh, dynamic_bvh)` pair.
1827    /// - `(Vec3, Vec3, Vec3)` - `(origin, dir, inv_dir)` ray triple.
1828    /// - `(f32, f32)` - `(t_min, t_max)` distance bounds.
1829    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder triangle hints.
1830    ///
1831    /// # Returns
1832    ///
1833    /// - `bool` - `true` if occluded by either static or dynamic geometry.
1834    #[must_use]
1835    pub fn trace_any_shadow_split(
1836        bvhs: (&Bvh3D, &Bvh3D),
1837        ray: (Vec3, Vec3, Vec3),
1838        bounds: (f32, f32),
1839        caches: (&mut u32, &mut u32),
1840    ) -> bool {
1841        let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
1842        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1843        let (t_min, t_max): (f32, f32) = bounds;
1844        let (static_cache, dynamic_cache): (&mut u32, &mut u32) = caches;
1845        if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
1846            return true;
1847        }
1848        if !dynamic_bvh.is_empty() {
1849            return dynamic_bvh.trace_any_shadow_cached(
1850                origin,
1851                dir,
1852                inv_dir,
1853                t_min,
1854                t_max,
1855                dynamic_cache,
1856            );
1857        }
1858        false
1859    }
1860
1861    /// Traces a reflection/GI ray across both static and dynamic BVHs and returns `(distance, is_dynamic, tri_index)`.
1862    ///
1863    /// # Arguments
1864    ///
1865    /// - `(&Bvh3D, &Bvh3D)` - `(static_bvh, dynamic_bvh)` pair.
1866    /// - `(Vec3, Vec3, Vec3)` - `(origin, dir, inv_dir)` ray triple.
1867    /// - `(f32, f32)` - `(t_min, t_max)` distance bounds.
1868    ///
1869    /// # Returns
1870    ///
1871    /// - `Option<(f32, bool, usize)>` - Closest `(t, hit_in_dynamic_bvh, triangle_index)`.
1872    #[must_use]
1873    pub fn trace_closest_split(
1874        bvhs: (&Bvh3D, &Bvh3D),
1875        ray: (Vec3, Vec3, Vec3),
1876        bounds: (f32, f32),
1877    ) -> Option<(f32, bool, usize)> {
1878        let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
1879        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1880        let (t_min, t_max): (f32, f32) = bounds;
1881        let static_hit: Option<(f32, usize)> =
1882            static_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, t_max);
1883        let dyn_limit: f32 =
1884            static_hit.map_or(t_max, |(blend_factor, _): (f32, usize)| blend_factor);
1885        let dynamic_hit: Option<(f32, usize)> = if !dynamic_bvh.is_empty() {
1886            dynamic_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, dyn_limit)
1887        } else {
1888            None
1889        };
1890        match (static_hit, dynamic_hit) {
1891            (_, Some((dt, di))) => Some((dt, true, di)),
1892            (Some((node_style, si)), None) => Some((node_style, false, si)),
1893            (None, None) => None,
1894        }
1895    }
1896
1897    /// Returns the optional player vehicle index.
1898    ///
1899    /// # Arguments
1900    ///
1901    /// - `&Self` - World reference.
1902    ///
1903    /// # Returns
1904    ///
1905    /// - `Option<usize>` - Vehicle index in `objects`.
1906    #[must_use]
1907    pub fn vehicle_index(&self) -> Option<usize> {
1908        let Self {
1909            player_vehicle_index,
1910            ..
1911        } = self;
1912        *player_vehicle_index
1913    }
1914
1915    /// Builds a GTA-inspired open-world neon downtown city with reflective wet asphalt, glass towers, and a drivable sports car.
1916    ///
1917    /// # Returns
1918    ///
1919    /// - `Self` - Populated open-world 3D city ready for real-time PBR + Ray Tracing.
1920    #[must_use]
1921    pub fn create_open_world_city() -> Self {
1922        let mut world: Self = Self::default();
1923        let asphalt_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x18202C), 0.25, 0.14, 0.58)
1924            .with_surface_detail(SurfaceDetailMode::RoadSurface);
1925        let road_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::ground_plane(
1926            "wet_asphalt_boulevard",
1927            220.0,
1928            220.0,
1929            24,
1930            asphalt_mat,
1931        )));
1932        let _: usize = world.spawn_object(
1933            "city_ground",
1934            road_mesh,
1935            Transform3D::default(),
1936            asphalt_mat,
1937            false,
1938        );
1939        let stripe_mat: PbrMaterial = PbrMaterial::neon(Color::hex(0xFACC15), 1.2);
1940        let stripe_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
1941            "lane_stripe",
1942            0.35,
1943            0.05,
1944            5.0,
1945            true,
1946            stripe_mat,
1947        )));
1948        for iz in -7..=7 {
1949            let _: usize = world.spawn_object(
1950                &format!("stripe_{iz}"),
1951                stripe_mesh,
1952                Transform3D::new(
1953                    Vec3::new(0.0, 0.02, (iz as f32) * 14.0),
1954                    0.0,
1955                    Vec3::splat(1.0),
1956                ),
1957                stripe_mat,
1958                false,
1959            );
1960        }
1961        let tower_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
1962            "city_skyscraper",
1963            1.0,
1964            1.0,
1965            1.0,
1966            true,
1967            PbrMaterial::default(),
1968        )));
1969        let neon_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
1970            "neon_sign",
1971            1.0,
1972            1.0,
1973            1.0,
1974            true,
1975            PbrMaterial::neon(Color::hex(0x38BDF8), 1.8),
1976        )));
1977        let tower_palettes: [PbrMaterial; 4] = [
1978            PbrMaterial::pbr(Color::hex(0x1E293B), 0.72, 0.16, 0.65)
1979                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
1980            PbrMaterial::pbr(Color::hex(0x334155), 0.55, 0.24, 0.45)
1981                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
1982            PbrMaterial::pbr(Color::hex(0x0F172A), 0.85, 0.10, 0.78)
1983                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
1984            PbrMaterial::pbr(Color::hex(0x475569), 0.40, 0.35, 0.35)
1985                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
1986        ];
1987        let neon_colors: [Color; 4] = [
1988            Color::hex(0x38BDF8),
1989            Color::hex(0xF43F5E),
1990            Color::hex(0xA855F7),
1991            Color::hex(0x34D399),
1992        ];
1993        let mut idx_counter: usize = 0;
1994        for side in [-1.0_f32, 1.0_f32] {
1995            for row in -4..=4 {
1996                let pos_z: f32 = (row as f32) * 20.0 - 12.0;
1997                let pos_x: f32 = side * (16.5 + ((idx_counter % 3) as f32) * 3.0);
1998                let height_val: f32 = 16.0 + ((idx_counter * 7) % 5) as f32 * 8.5;
1999                let width_val: f32 = 9.0 + ((idx_counter % 2) as f32) * 3.0;
2000                let mat: PbrMaterial = tower_palettes[idx_counter % tower_palettes.len()];
2001                let _: usize = world.spawn_object(
2002                    &format!("tower_{idx_counter}"),
2003                    tower_unit,
2004                    Transform3D::new(
2005                        Vec3::new(pos_x, 0.0, pos_z),
2006                        0.0,
2007                        Vec3::new(width_val, height_val, 11.0),
2008                    ),
2009                    mat,
2010                    true,
2011                );
2012                let neon_mat: PbrMaterial =
2013                    PbrMaterial::neon(neon_colors[idx_counter % neon_colors.len()], 1.9);
2014                let _: usize = world.spawn_object(
2015                    &format!("crown_{idx_counter}"),
2016                    neon_unit,
2017                    Transform3D::new(
2018                        Vec3::new(
2019                            pos_x - side * (width_val * 0.5 + 0.28),
2020                            height_val * 0.72,
2021                            pos_z,
2022                        ),
2023                        0.0,
2024                        Vec3::new(0.36, 1.4, 8.2),
2025                    ),
2026                    neon_mat,
2027                    true,
2028                );
2029                if height_val >= 28.0 {
2030                    let spire_mat: PbrMaterial =
2031                        PbrMaterial::pbr(Color::hex(0x1E293B), 0.85, 0.14, 0.75);
2032                    let _: usize = world.spawn_object(
2033                        &format!("penthouse_{idx_counter}"),
2034                        tower_unit,
2035                        Transform3D::new(
2036                            Vec3::new(pos_x, height_val, pos_z),
2037                            0.0,
2038                            Vec3::new(width_val * 0.52, 4.2, 5.8),
2039                        ),
2040                        spire_mat,
2041                        false,
2042                    );
2043                    let _: usize = world.spawn_object(
2044                        &format!("spire_{idx_counter}"),
2045                        neon_unit,
2046                        Transform3D::new(
2047                            Vec3::new(pos_x, height_val + 4.2, pos_z),
2048                            0.0,
2049                            Vec3::new(0.45, 7.5, 0.45),
2050                        ),
2051                        neon_mat,
2052                        false,
2053                    );
2054                }
2055                idx_counter += 1;
2056            }
2057        }
2058        let arch_frame_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0F172A), 0.82, 0.18, 0.60);
2059        for (arch_idx, &arch_z) in [-22.0_f32, -58.0_f32, -92.0_f32].iter().enumerate() {
2060            let arch_neon: PbrMaterial =
2061                PbrMaterial::neon(neon_colors[arch_idx % neon_colors.len()], 2.1);
2062            let _: usize = world.spawn_object(
2063                &format!("arch_beam_{arch_idx}"),
2064                tower_unit,
2065                Transform3D::new(
2066                    Vec3::new(0.0, 11.4, arch_z),
2067                    0.0,
2068                    Vec3::new(22.4, 0.65, 0.75),
2069                ),
2070                arch_frame_mat,
2071                false,
2072            );
2073            let _: usize = world.spawn_object(
2074                &format!("arch_glow_{arch_idx}"),
2075                neon_unit,
2076                Transform3D::new(
2077                    Vec3::new(0.0, 11.05, arch_z),
2078                    0.0,
2079                    Vec3::new(20.6, 0.28, 0.36),
2080                ),
2081                arch_neon,
2082                false,
2083            );
2084            for side in [-1.0_f32, 1.0_f32] {
2085                let _: usize = world.spawn_object(
2086                    &format!("arch_pillar_{arch_idx}_{}", if side < 0.0 { 0 } else { 1 }),
2087                    tower_unit,
2088                    Transform3D::new(
2089                        Vec3::new(side * 10.9, 0.0, arch_z),
2090                        0.0,
2091                        Vec3::new(0.58, 11.6, 0.68),
2092                    ),
2093                    arch_frame_mat,
2094                    false,
2095                );
2096            }
2097        }
2098        let car_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0xF43F5E), 0.88, 0.12, 0.72);
2099        let car_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::sports_car(
2100            "hero_gt", car_mat,
2101        )));
2102        let car_idx: usize = world.spawn_object(
2103            "player_gt_car",
2104            car_mesh,
2105            Transform3D::new(Vec3::new(0.0, 0.0, 6.0), 0.0, Vec3::splat(1.1)),
2106            car_mat,
2107            true,
2108        );
2109        let _: bool = world.set_object_dynamic(car_idx, true);
2110        world.set_player_vehicle_index(Some(car_idx));
2111        let traffic_specs: [(f32, f32, f32, f32, Color); 4] = [
2112            (-5.6, -16.0, PI, 11.5, Color::hex(0x38BDF8)),
2113            (-5.6, -56.0, PI, 10.0, Color::hex(0xA855F7)),
2114            (5.6, -24.0, 0.0, -13.0, Color::hex(0x34D399)),
2115            (5.6, -68.0, 0.0, -11.0, Color::hex(0xF59E0B)),
2116        ];
2117        for (t_idx, &(tx, tz, tyaw, tvel, tcol)) in traffic_specs.iter().enumerate() {
2118            let tmat: PbrMaterial = PbrMaterial::pbr(tcol, 0.86, 0.14, 0.74);
2119            let obj_id: usize = world.spawn_object(
2120                &format!("ai_traffic_{t_idx}"),
2121                car_mesh,
2122                Transform3D::new(Vec3::new(tx, 0.0, tz), tyaw, Vec3::splat(1.04)),
2123                tmat,
2124                true,
2125            );
2126            let _: bool = world.set_object_dynamic(obj_id, true);
2127            let Self {
2128                traffic_vehicles, ..
2129            } = &mut world;
2130            traffic_vehicles.push((obj_id, tvel, -94.0, 68.0));
2131        }
2132        let lamp_palette: [Color; 4] = [
2133            Color::hex(0x38BDF8),
2134            Color::hex(0xF43F5E),
2135            Color::hex(0xA855F7),
2136            Color::hex(0x34D399),
2137        ];
2138        for lamp_idx in 0..8usize {
2139            let side: f32 = if lamp_idx % 2 == 0 { -1.0 } else { 1.0 };
2140            let z_pos: f32 = -42.0 + ((lamp_idx / 2) as f32) * 24.0;
2141            let lamp_color: Color = lamp_palette[lamp_idx % lamp_palette.len()];
2142            let _: usize = world.spawn_object(
2143                &format!("lamp_pole_{lamp_idx}"),
2144                tower_unit,
2145                Transform3D::new(
2146                    Vec3::new(side * 10.35, 0.0, z_pos),
2147                    0.0,
2148                    Vec3::new(0.20, 6.2, 0.20),
2149                ),
2150                arch_frame_mat,
2151                false,
2152            );
2153            let _: usize = world.spawn_object(
2154                &format!("lamp_head_{lamp_idx}"),
2155                neon_unit,
2156                Transform3D::new(
2157                    Vec3::new(side * 9.85, 6.1, z_pos),
2158                    0.0,
2159                    Vec3::new(1.1, 0.18, 0.28),
2160                ),
2161                PbrMaterial::neon(lamp_color, 2.2),
2162                false,
2163            );
2164            let _: usize = world.add_point_light(PointLight3D::new(
2165                Vec3::new(side * 9.5, 6.2, z_pos),
2166                lamp_color,
2167                1.6,
2168                14.0,
2169            ));
2170        }
2171        let _: usize = world.add_spot_light(SpotLight3D::new(
2172            Vec3::new(-0.85, 0.95, 3.8),
2173            Vec3::new(0.0, -0.14, -1.0),
2174            Color::hex(0xFEF3C7),
2175            2.8,
2176            24.0,
2177            (14.0, 26.0),
2178        ));
2179        let _: usize = world.add_spot_light(SpotLight3D::new(
2180            Vec3::new(0.85, 0.95, 3.8),
2181            Vec3::new(0.0, -0.14, -1.0),
2182            Color::hex(0xFEF3C7),
2183            2.8,
2184            24.0,
2185            (14.0, 26.0),
2186        ));
2187        world.set_camera(Camera3D {
2188            position: Vec3::new(0.0, 6.2, 18.5),
2189            yaw: -FRAC_PI_2,
2190            pitch: -0.18,
2191            fov_deg: 62.0,
2192            near: 0.3,
2193            far: 420.0,
2194        });
2195        world.ensure_bvh();
2196        world
2197    }
2198
2199    /// Returns the number of autonomous cruising traffic vehicles registered in this world.
2200    ///
2201    /// # Returns
2202    ///
2203    /// - `usize` - Active cruising traffic vehicle count.
2204    #[must_use]
2205    pub fn traffic_vehicle_count(&self) -> usize {
2206        let Self {
2207            traffic_vehicles, ..
2208        } = self;
2209        traffic_vehicles.len()
2210    }
2211
2212    /// Applies an atmospheric mood preset (`0=Sunset, 1=RainyNight, 2=Noon, 3=Midnight`), updating sun lighting and ambient Niagara rain streaks.
2213    ///
2214    /// # Arguments
2215    ///
2216    /// - `u8` - Atmosphere preset index (`0..=3`).
2217    ///
2218    /// # Returns
2219    ///
2220    /// - `f32` - Corresponding time-of-day hour in `[0.0, 24.0]`.
2221    pub fn apply_atmosphere_preset(&mut self, preset: u8) -> f32 {
2222        let clamped: u8 = preset.min(3);
2223        let hour: f32 = match clamped {
2224            1 => ATMOSPHERE_HOUR_RAINY_NIGHT,
2225            2 => ATMOSPHERE_HOUR_NOON,
2226            3 => ATMOSPHERE_HOUR_MIDNIGHT,
2227            _ => ATMOSPHERE_HOUR_SUNSET,
2228        };
2229        self.set_atmosphere_preset(clamped);
2230        let sun_light: DirectionalLight3D = match clamped {
2231            1 => DirectionalLight3D {
2232                direction: Vec3::new(-0.32, 0.56, 0.62).normalize(),
2233                color: Vec3::new(0.58, 0.78, 1.20),
2234                sky_zenith: Vec3::new(0.018, 0.045, 0.115),
2235                sky_horizon: Vec3::new(0.085, 0.165, 0.285),
2236                time_of_day: hour,
2237            },
2238            3 => DirectionalLight3D {
2239                direction: Vec3::new(-0.48, 0.72, 0.44).normalize(),
2240                color: Vec3::new(0.38, 0.34, 0.86),
2241                sky_zenith: Vec3::new(0.008, 0.004, 0.025),
2242                sky_horizon: Vec3::new(0.145, 0.038, 0.225),
2243                time_of_day: hour,
2244            },
2245            _ => DirectionalLight3D::from_time_of_day(hour),
2246        };
2247        self.set_sun(sun_light);
2248        if clamped == 1 && self.get_niagara().get_active_count() < RAINY_NIGHT_MAX_PARTICLES {
2249            let cam_pos: Vec3 = self.get_camera().get_position();
2250            let mut rain_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
2251            rain_cfg.set_origin(cam_pos.add(Vec3::new(0.0, 4.5, -14.0)));
2252            rain_cfg.set_base_velocity(Vec3::new(-0.4, -17.0, 0.3));
2253            rain_cfg.set_velocity_spread(2.4);
2254            rain_cfg.set_start_color(Color::rgba(175, 222, 255, 165));
2255            rain_cfg.set_end_color(Color::rgba(92, 162, 235, 42));
2256            rain_cfg.set_start_size_m(0.042);
2257            rain_cfg.set_end_size_m(0.016);
2258            rain_cfg.set_min_lifetime(0.55);
2259            rain_cfg.set_max_lifetime(0.95);
2260            rain_cfg.set_emissive_boost(0.85);
2261            self.get_mut_niagara().emit_burst(8, &rain_cfg);
2262        }
2263        self.bump_world_revision();
2264        hour
2265    }
2266
2267    /// Registers a dynamic `PointLight3D` into this world for UE5 Clustered Deferred Lighting and returns its index.
2268    ///
2269    /// # Arguments
2270    ///
2271    /// - `PointLight3D` - World-space point light descriptor.
2272    ///
2273    /// # Returns
2274    ///
2275    /// - `usize` - Assigned point light index.
2276    pub fn add_point_light(&mut self, light: PointLight3D) -> usize {
2277        let light_idx: usize = self.get_point_lights().len();
2278        self.get_mut_point_lights().push(light);
2279        self.bump_world_revision();
2280        light_idx
2281    }
2282
2283    /// Registers a dynamic `SpotLight3D` into this world for UE5 Clustered Deferred Lighting and returns its index.
2284    ///
2285    /// # Arguments
2286    ///
2287    /// - `SpotLight3D` - World-space spotlight descriptor.
2288    ///
2289    /// # Returns
2290    ///
2291    /// - `usize` - Assigned spotlight index.
2292    pub fn add_spot_light(&mut self, light: SpotLight3D) -> usize {
2293        let light_idx: usize = self.get_spot_lights().len();
2294        self.get_mut_spot_lights().push(light);
2295        self.bump_world_revision();
2296        light_idx
2297    }
2298
2299    /// Clears all dynamic local point and spot lights from this world.
2300    pub fn clear_local_lights(&mut self) {
2301        self.get_mut_point_lights().clear();
2302        self.get_mut_spot_lights().clear();
2303        self.bump_world_revision();
2304    }
2305
2306    /// Emits `count` 3D particles into the world's `NiagaraSystem3D` with zero heap allocations.
2307    ///
2308    /// # Arguments
2309    ///
2310    /// - `&NiagaraEmitterConfig3D` - Emitter properties.
2311    /// - `usize` - Number of particles to emit.
2312    ///
2313    /// # Returns
2314    ///
2315    /// - `usize` - Active particle count after emission.
2316    pub fn emit_particles_3d(&mut self, config: &NiagaraEmitterConfig3D, count: usize) -> usize {
2317        self.get_mut_niagara().emit_burst(count, config);
2318        let active: usize = self.get_niagara().get_active_count();
2319        if count > 0 {
2320            self.bump_world_revision();
2321        }
2322        active
2323    }
2324
2325    /// 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.
2326    ///
2327    /// # Arguments
2328    ///
2329    /// - `i32` - City block half-radius (`1..=5`, producing `(2r+1)x(2r+1)` multi-tower blocks).
2330    ///
2331    /// # Returns
2332    ///
2333    /// - `Self` - Populated dense 3D open-world metropolis with built static/dynamic BVHs.
2334    #[must_use]
2335    pub fn create_dense_open_world_city(blocks_radius: i32) -> Self {
2336        let radius: i32 = blocks_radius.clamp(1, 5);
2337        let mut world: Self = Self::create_open_world_city();
2338        let tower_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2339            DENSE_TOWER_MESH_NAME,
2340            1.0,
2341            1.0,
2342            1.0,
2343            true,
2344            PbrMaterial::default(),
2345        )));
2346        let facades: [PbrMaterial; 4] = [
2347            PbrMaterial::pbr(Color::hex(0x1E293B), 0.72, 0.16, 0.65)
2348                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2349            PbrMaterial::pbr(Color::hex(0x334155), 0.55, 0.24, 0.45)
2350                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2351            PbrMaterial::pbr(Color::hex(0x0F172A), 0.85, 0.10, 0.78)
2352                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2353            PbrMaterial::pbr(Color::hex(0x475569), 0.40, 0.35, 0.35)
2354                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2355        ];
2356        let neon_palette: [Color; 4] = [
2357            Color::hex(0x38BDF8),
2358            Color::hex(0xF43F5E),
2359            Color::hex(0xA855F7),
2360            Color::hex(0x34D399),
2361        ];
2362        let mut serial: usize = 0;
2363        for bx in -radius..=radius {
2364            for bz in -radius..=radius {
2365                if bx == 0 && (-3..=3).contains(&bz) {
2366                    continue;
2367                }
2368                let center_x: f32 = (bx as f32) * 26.0;
2369                let center_z: f32 = (bz as f32) * 24.0 - 16.0;
2370                for sub in 0..4usize {
2371                    let off_x: f32 = if (sub & 1) == 0 { -5.5 } else { 5.5 };
2372                    let off_z: f32 = if (sub & 2) == 0 { -5.5 } else { 5.5 };
2373                    let height_m: f32 = 14.0 + (((serial * 11 + sub * 7) % 6) as f32) * 7.5;
2374                    let width_m: f32 = 7.5 + ((serial % 3) as f32) * 1.4;
2375                    let mat: PbrMaterial = facades[serial % facades.len()];
2376                    let _: usize = world.spawn_object(
2377                        &format!("dense_bldg_{serial}"),
2378                        tower_mesh,
2379                        Transform3D::new(
2380                            Vec3::new(center_x + off_x, 0.0, center_z + off_z),
2381                            0.0,
2382                            Vec3::new(width_m, height_m, 8.5),
2383                        ),
2384                        mat,
2385                        true,
2386                    );
2387                    serial += 1;
2388                }
2389                if (bx + bz).abs() <= 2 && world.get_point_lights().len() < 32 {
2390                    let _: usize = world.add_point_light(PointLight3D::new(
2391                        Vec3::new(center_x, 7.0, center_z),
2392                        neon_palette[serial % neon_palette.len()],
2393                        4.5,
2394                        22.0,
2395                    ));
2396                }
2397            }
2398        }
2399        world.ensure_bvh();
2400        world
2401    }
2402
2403    /// Cycles the active 3D camera perspective (`Chase` -> `Hood` -> `Orbit` -> `Aerial`) safely without clipping.
2404    ///
2405    /// # Arguments
2406    ///
2407    /// - `&Self` - Mutable world.
2408    ///
2409    /// # Returns
2410    ///
2411    /// - `u8` - New active camera mode index.
2412    pub fn cycle_camera_mode(&mut self) -> u8 {
2413        let next: u8 = (self.get_camera_mode() + 1) % 4;
2414        self.set_camera_mode(next);
2415        next
2416    }
2417
2418    /// Computes horizontal playable world bounds from non-solid ground meshes when present, preventing hardcoded invisible walls.
2419    ///
2420    /// # Arguments
2421    ///
2422    /// - `&Self` - World reference.
2423    ///
2424    /// # Returns
2425    ///
2426    /// - `Option<(f32, f32, f32, f32)>` - `(min_x, max_x, min_z, max_z)` horizontal ground limits.
2427    #[must_use]
2428    pub fn ground_play_bounds(&self) -> Option<(f32, f32, f32, f32)> {
2429        let mut found: bool = false;
2430        let mut min_x: f32 = f32::INFINITY;
2431        let mut max_x: f32 = f32::NEG_INFINITY;
2432        let mut min_z: f32 = f32::INFINITY;
2433        let mut max_z: f32 = f32::NEG_INFINITY;
2434        for obj in self.get_objects().iter() {
2435            if obj.get_ray_trace_caster() {
2436                continue;
2437            }
2438            let blue_val: AxisAlignedBox3D = obj.get_world_bounds();
2439            let span_x: f32 = blue_val.get_max().get_x() - blue_val.get_min().get_x();
2440            let span_z: f32 = blue_val.get_max().get_z() - blue_val.get_min().get_z();
2441            if span_x >= 16.0 && span_z >= 16.0 {
2442                min_x = min_x.min(blue_val.get_min().get_x());
2443                max_x = max_x.max(blue_val.get_max().get_x());
2444                min_z = min_z.min(blue_val.get_min().get_z());
2445                max_z = max_z.max(blue_val.get_max().get_z());
2446                found = true;
2447            }
2448        }
2449        if found {
2450            Some((min_x, max_x, min_z, max_z))
2451        } else {
2452            None
2453        }
2454    }
2455
2456    /// 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.
2457    ///
2458    /// # Arguments
2459    ///
2460    /// - `&Self` - World reference.
2461    /// - `OrientedBox3D` - Candidate oriented bounding box in world space.
2462    /// - `Option<usize>` - Optional scene object index to exclude (self).
2463    ///
2464    /// # Returns
2465    ///
2466    /// - `Option<MeshCollisionHit3D>` - Deepest real-mesh triangle collision contact, or `None` when clear.
2467    #[must_use]
2468    pub fn mesh_oriented_box_collision(
2469        &self,
2470        candidate: OrientedBox3D,
2471        ignore_idx: Option<usize>,
2472    ) -> Option<MeshCollisionHit3D> {
2473        let query_bounds: AxisAlignedBox3D = candidate.to_world_bounds();
2474        let mut deepest: Option<MeshCollisionHit3D> = None;
2475        let objects: &[SceneObject3D] = self.get_objects().as_slice();
2476        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
2477        for (idx, obj) in objects.iter().enumerate() {
2478            if ignore_idx == Some(idx) || !obj.get_ray_trace_caster() {
2479                continue;
2480            }
2481            if !Self::boxes_overlap(query_bounds, obj.get_world_bounds()) {
2482                continue;
2483            }
2484            let Some(mesh) = mesh_lib
2485                .get(obj.get_mesh_id())
2486                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
2487            else {
2488                continue;
2489            };
2490            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
2491            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
2492            let obj_tr: Transform3D = obj.get_transform();
2493            let model_mat: Mat4 = obj_tr.to_mat4();
2494            let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
2495            if meshlets.is_empty() {
2496                for tri in indices.iter() {
2497                    let (i0, i1, i2): (usize, usize, usize) =
2498                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
2499                    if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
2500                        let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
2501                        let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
2502                        let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
2503                        if let Some((normal, pen, contact)) =
2504                            candidate.intersect_triangle_world(w0, w1, w2)
2505                        {
2506                            let replace: bool = deepest
2507                                .map(|delta_val: MeshCollisionHit3D| {
2508                                    pen > delta_val.get_penetration()
2509                                })
2510                                .unwrap_or(true);
2511                            if replace {
2512                                deepest = Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
2513                            }
2514                        }
2515                    }
2516                }
2517            } else {
2518                for ml in meshlets.iter() {
2519                    let ml_bounds: AxisAlignedBox3D = model_mat.transform_bounds(ml.get_bounds());
2520                    if !Self::boxes_overlap(query_bounds, ml_bounds) {
2521                        continue;
2522                    }
2523                    let start: usize = ml.get_first_tri() as usize;
2524                    let end: usize = start
2525                        .saturating_add(ml.get_tri_count() as usize)
2526                        .min(indices.len());
2527                    for tri in indices[start..end].iter() {
2528                        let (i0, i1, i2): (usize, usize, usize) =
2529                            (tri[0] as usize, tri[1] as usize, tri[2] as usize);
2530                        if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
2531                            let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
2532                            let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
2533                            let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
2534                            if let Some((normal, pen, contact)) =
2535                                candidate.intersect_triangle_world(w0, w1, w2)
2536                            {
2537                                let replace: bool = deepest
2538                                    .map(|distance_val: MeshCollisionHit3D| {
2539                                        pen > distance_val.get_penetration()
2540                                    })
2541                                    .unwrap_or(true);
2542                                if replace {
2543                                    deepest =
2544                                        Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
2545                                }
2546                            }
2547                        }
2548                    }
2549                }
2550            }
2551        }
2552        deepest
2553    }
2554
2555    /// Casts a world-space ray against every solid (`ray_trace_caster == true`) model's real mesh triangles (excluding `ignore_idx`) up to `max_dist`.
2556    ///
2557    /// # Arguments
2558    ///
2559    /// - `&Self` - World reference.
2560    /// - `Vec3` - Ray origin in world space.
2561    /// - `Vec3` - Unit ray direction in world space.
2562    /// - `f32` - Maximum ray distance.
2563    /// - `Option<usize>` - Optional scene object index to exclude.
2564    ///
2565    /// # Returns
2566    ///
2567    /// - `Option<RayHit3D>` - Closest real-mesh triangle intersection within `(1e-4, max_dist]`.
2568    #[must_use]
2569    pub fn raycast_solid_meshes(
2570        &self,
2571        origin: Vec3,
2572        direction: Vec3,
2573        max_dist: f32,
2574        ignore_idx: Option<usize>,
2575    ) -> Option<RayHit3D> {
2576        let dir: Vec3 = direction.normalize();
2577        let inv_dir: Vec3 = Ray3D::safe_inv_vec(dir);
2578        let t_min: f32 = 1e-4;
2579        let mut best_t: f32 = max_dist;
2580        let mut best_hit: Option<RayHit3D> = None;
2581        let objects: &[SceneObject3D] = self.get_objects().as_slice();
2582        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
2583        let ignore_is_static_caster: bool = ignore_idx
2584            .and_then(|idx: usize| objects.get(idx))
2585            .is_some_and(|obj: &SceneObject3D| obj.get_ray_trace_caster() && !obj.get_is_dynamic());
2586        let use_static_bvh: bool =
2587            !self.get_bvh_dirty() && !self.get_bvh().is_empty() && !ignore_is_static_caster;
2588        if use_static_bvh
2589            && let Some((hit_dist, tri_idx)) = self
2590                .get_bvh()
2591                .trace_closest_raw(origin, dir, inv_dir, t_min, best_t)
2592        {
2593            let bvh_tris: &[BvhTriangle] = self.get_bvh().get_triangles().as_slice();
2594            if let Some(hit_tri) = bvh_tris.get(tri_idx) {
2595                let raw_normal: Vec3 = hit_tri.get_normal();
2596                let oriented_normal: Vec3 = if raw_normal.dot(dir) > 0.0 {
2597                    raw_normal.scale(-1.0)
2598                } else {
2599                    raw_normal
2600                };
2601                best_t = hit_dist;
2602                best_hit = Some(RayHit3D {
2603                    distance: hit_dist,
2604                    point: origin.add(dir.scale(hit_dist)),
2605                    normal: oriented_normal,
2606                    material: hit_tri.get_material(),
2607                });
2608            }
2609        }
2610        for (idx, obj) in objects.iter().enumerate() {
2611            if ignore_idx == Some(idx) || !obj.get_ray_trace_caster() {
2612                continue;
2613            }
2614            if use_static_bvh && !obj.get_is_dynamic() {
2615                continue;
2616            }
2617            if !obj
2618                .get_world_bounds()
2619                .intersect_ray_near(origin, inv_dir, t_min, best_t)
2620                .is_finite()
2621            {
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 model_mat: Mat4 = obj.get_transform().to_mat4();
2633            let mat: PbrMaterial = obj.get_material();
2634            for tri in indices.iter() {
2635                let (i0, i1, i2): (usize, usize, usize) =
2636                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
2637                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
2638                    let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
2639                    let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
2640                    let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
2641                    if let Some((blend_factor, normal)) =
2642                        Self::ray_intersect_triangle(origin, dir, w0, w1, w2, t_min, best_t)
2643                    {
2644                        best_t = blend_factor;
2645                        best_hit = Some(RayHit3D {
2646                            distance: blend_factor,
2647                            point: origin.add(dir.scale(blend_factor)),
2648                            normal,
2649                            material: mat,
2650                        });
2651                    }
2652                }
2653            }
2654        }
2655        best_hit
2656    }
2657
2658    /// Tests whether two world-space `AxisAlignedBox3D` boxes overlap strictly.
2659    ///
2660    /// # Arguments
2661    ///
2662    /// - `AxisAlignedBox3D` - First bounding box.
2663    /// - `AxisAlignedBox3D` - Second bounding box.
2664    ///
2665    /// # Returns
2666    ///
2667    /// - `bool` - `true` when both axis-aligned bounding boxes overlap on all three axes.
2668    #[inline]
2669    #[must_use]
2670    fn boxes_overlap(alpha_val: AxisAlignedBox3D, blue_val: AxisAlignedBox3D) -> bool {
2671        let ox: bool = alpha_val.get_min().get_x() < blue_val.get_max().get_x()
2672            && alpha_val.get_max().get_x() > blue_val.get_min().get_x();
2673        let oy: bool = alpha_val.get_min().get_y() < blue_val.get_max().get_y()
2674            && alpha_val.get_max().get_y() > blue_val.get_min().get_y();
2675        let oz: bool = alpha_val.get_min().get_z() < blue_val.get_max().get_z()
2676            && alpha_val.get_max().get_z() > blue_val.get_min().get_z();
2677        ox && oy && oz
2678    }
2679
2680    /// Double-sided Möller-Trumbore ray-triangle intersection returning `(t, outward_unit_normal)`.
2681    ///
2682    /// # Arguments
2683    ///
2684    /// - `Vec3` - Ray origin.
2685    /// - `Vec3` - Unit ray direction.
2686    /// - `Vec3` - Triangle vertex 0.
2687    /// - `Vec3` - Triangle vertex 1.
2688    /// - `Vec3` - Triangle vertex 2.
2689    /// - `f32` - Minimum ray parameter `t`.
2690    /// - `f32` - Maximum ray parameter `t`.
2691    ///
2692    /// # Returns
2693    ///
2694    /// - `Option<(f32, Vec3)>` - Hit distance and facing unit normal.
2695    #[inline]
2696    #[must_use]
2697    fn ray_intersect_triangle(
2698        origin: Vec3,
2699        dir: Vec3,
2700        v0: Vec3,
2701        v1: Vec3,
2702        v2: Vec3,
2703        t_min: f32,
2704        t_max: f32,
2705    ) -> Option<(f32, Vec3)> {
2706        let e1: Vec3 = v1.sub(v0);
2707        let e2: Vec3 = v2.sub(v0);
2708        let pvec: Vec3 = dir.cross(e2);
2709        let det: f32 = e1.dot(pvec);
2710        if det.abs() < 1e-7 {
2711            return None;
2712        }
2713        let inv_det: f32 = 1.0 / det;
2714        let tvec: Vec3 = origin.sub(v0);
2715        let tex_u: f32 = tvec.dot(pvec) * inv_det;
2716        if !(0.0..=1.0).contains(&tex_u) {
2717            return None;
2718        }
2719        let qvec: Vec3 = tvec.cross(e1);
2720        let item_val: f32 = dir.dot(qvec) * inv_det;
2721        if item_val < 0.0 || tex_u + item_val > 1.0 {
2722            return None;
2723        }
2724        let blend_factor: f32 = e2.dot(qvec) * inv_det;
2725        if blend_factor <= t_min || blend_factor > t_max {
2726            return None;
2727        }
2728        let raw_n: Vec3 = e1.cross(e2).normalize();
2729        let normal: Vec3 = if raw_n.dot(dir) > 0.0 {
2730            raw_n.scale(-1.0)
2731        } else {
2732            raw_n
2733        };
2734        Some((blend_factor, normal))
2735    }
2736
2737    /// Tests whether a candidate transformed mesh collides with any solid obstacle's real triangles excluding `ignore_idx`.
2738    ///
2739    /// # Arguments
2740    ///
2741    /// - `&Self` - World reference.
2742    /// - `Transform3D` - Candidate object transform.
2743    /// - `AxisAlignedBox3D` - Candidate local mesh bounds.
2744    /// - `usize` - Self object index to skip.
2745    ///
2746    /// # Returns
2747    ///
2748    /// - `Option<MeshCollisionHit3D>` - Deepest real-mesh collision hit, or `None` when clear.
2749    #[must_use]
2750    fn collides_with_obstacles(
2751        &self,
2752        candidate_tr: Transform3D,
2753        local_bounds: AxisAlignedBox3D,
2754        ignore_idx: usize,
2755    ) -> Option<MeshCollisionHit3D> {
2756        let oriented_box: OrientedBox3D = candidate_tr.to_oriented_box(local_bounds);
2757        self.mesh_oriented_box_collision(oriented_box, Some(ignore_idx))
2758    }
2759
2760    /// Advances drivable vehicle/camera controls with continuous real-mesh oriented bounding box-vs-triangle collision, wall sliding, raycast camera boom, and synchronized spinning bounds.
2761    ///
2762    /// # Arguments
2763    ///
2764    /// - `&Self` - Mutable world.
2765    /// - `f32` - Delta time in seconds.
2766    /// - `&InputState` - Real-time polled keyboard/pointer input.
2767    /// - `&ActionMap` - Action bindings for WASD/Arrows movement.
2768    pub fn step_simulation(&mut self, dt: f32, input: &InputState, actions: &ActionMap) {
2769        let move_vec: Point = actions.movement_vector(input);
2770        let steer: f32 = move_vec.get_x();
2771        let throttle: f32 = -move_vec.get_y();
2772        let mut any_dynamic_moved: bool = false;
2773        let mut any_static_moved: bool = false;
2774        let ground_limits: Option<(f32, f32, f32, f32)> = self.ground_play_bounds();
2775        let car_opt: Option<usize> = self.vehicle_index();
2776        if let Some(car_idx) = car_opt
2777            && let Some((mut transform_val, mesh_id, car_is_dynamic)) =
2778                self.get_objects().get(car_idx).map(|car: &SceneObject3D| {
2779                    (car.get_transform(), car.get_mesh_id(), car.get_is_dynamic())
2780                })
2781        {
2782            let mut car_moved: bool = false;
2783            let mesh_bounds: AxisAlignedBox3D = self
2784                .get_mesh_library()
2785                .get(mesh_id)
2786                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
2787                .map(Mesh3D::get_bounds)
2788                .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-2.0), Vec3::splat(2.0)));
2789            if steer.abs() > 0.05 {
2790                let total_yaw: f32 = -steer * 1.85 * dt;
2791                let rot_steps: usize = ((total_yaw.abs() / 0.12).ceil() as usize).clamp(1, 12);
2792                let step_yaw: f32 = total_yaw / (rot_steps as f32);
2793                for _ in 0..rot_steps {
2794                    let mut rotated: Transform3D = transform_val;
2795                    rotated.set_yaw_rad(transform_val.get_yaw_rad() + step_yaw);
2796                    if self
2797                        .collides_with_obstacles(rotated, mesh_bounds, car_idx)
2798                        .is_none()
2799                    {
2800                        transform_val = rotated;
2801                        car_moved = true;
2802                    } else {
2803                        break;
2804                    }
2805                }
2806            }
2807            if throttle.abs() > 0.05 {
2808                let fwd_x: f32 = -transform_val.get_yaw_rad().sin();
2809                let fwd_z: f32 = -transform_val.get_yaw_rad().cos();
2810                let total_disp: Vec3 = Vec3::new(fwd_x, 0.0, fwd_z).scale(24.0 * throttle * dt);
2811                let oriented_box_now: OrientedBox3D = transform_val.to_oriented_box(mesh_bounds);
2812                let min_half: f32 = oriented_box_now
2813                    .get_half_extents()
2814                    .get_x()
2815                    .min(oriented_box_now.get_half_extents().get_z())
2816                    .max(0.25);
2817                let max_step_len: f32 = (min_half * 0.35).min(0.20);
2818                let substeps: usize =
2819                    ((total_disp.length() / max_step_len).ceil() as usize).clamp(1, 32);
2820                let step_delta: Vec3 = total_disp.scale(1.0 / (substeps as f32));
2821                let ground_margin: f32 = oriented_box_now
2822                    .get_half_extents()
2823                    .get_x()
2824                    .max(oriented_box_now.get_half_extents().get_z());
2825                for _ in 0..substeps {
2826                    let cur: Vec3 = transform_val.get_position();
2827                    let mut next_pos: Vec3 = Vec3::new(
2828                        cur.get_x() + step_delta.get_x(),
2829                        cur.get_y(),
2830                        cur.get_z() + step_delta.get_z(),
2831                    );
2832                    if let Some((gx0, gx1, gz0, gz1)) = ground_limits {
2833                        let lo_x: f32 = (gx0 + ground_margin).min(gx1);
2834                        let hi_x: f32 = (gx1 - ground_margin).max(lo_x);
2835                        let lo_z: f32 = (gz0 + ground_margin).min(gz1);
2836                        let hi_z: f32 = (gz1 - ground_margin).max(lo_z);
2837                        next_pos.set_x(next_pos.get_x().clamp(lo_x, hi_x));
2838                        next_pos.set_z(next_pos.get_z().clamp(lo_z, hi_z));
2839                    }
2840                    let mut cand: Transform3D = transform_val;
2841                    cand.set_position(next_pos);
2842                    if let Some(hit) = self.collides_with_obstacles(cand, mesh_bounds, car_idx) {
2843                        let mut hn: Vec3 =
2844                            Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
2845                        if hn.length_sq() > 1e-6 {
2846                            hn = hn.normalize();
2847                            let into: f32 = step_delta.dot(hn);
2848                            let slide_delta: Vec3 = if into < 0.0 {
2849                                step_delta.sub(hn.scale(into))
2850                            } else {
2851                                Vec3::zero()
2852                            };
2853                            if slide_delta.length_sq() > 1e-8 {
2854                                let mut slide_pos: Vec3 = Vec3::new(
2855                                    cur.get_x() + slide_delta.get_x(),
2856                                    cur.get_y(),
2857                                    cur.get_z() + slide_delta.get_z(),
2858                                );
2859                                if let Some((gx0, gx1, gz0, gz1)) = ground_limits {
2860                                    let lo_x: f32 = (gx0 + ground_margin).min(gx1);
2861                                    let hi_x: f32 = (gx1 - ground_margin).max(lo_x);
2862                                    let lo_z: f32 = (gz0 + ground_margin).min(gz1);
2863                                    let hi_z: f32 = (gz1 - ground_margin).max(lo_z);
2864                                    slide_pos.set_x(slide_pos.get_x().clamp(lo_x, hi_x));
2865                                    slide_pos.set_z(slide_pos.get_z().clamp(lo_z, hi_z));
2866                                }
2867                                let mut slide_tr: Transform3D = transform_val;
2868                                slide_tr.set_position(slide_pos);
2869                                if self
2870                                    .collides_with_obstacles(slide_tr, mesh_bounds, car_idx)
2871                                    .is_none()
2872                                {
2873                                    transform_val = slide_tr;
2874                                    car_moved = true;
2875                                    continue;
2876                                }
2877                            }
2878                        }
2879                        break;
2880                    } else {
2881                        transform_val = cand;
2882                        car_moved = true;
2883                    }
2884                }
2885            }
2886            if car_moved {
2887                let world_b: AxisAlignedBox3D = transform_val.transform_bounds(mesh_bounds);
2888                if let Some(car_mut) = self.get_mut_objects().get_mut(car_idx) {
2889                    car_mut.set_transform(transform_val);
2890                    car_mut.set_world_bounds(world_b);
2891                }
2892                if car_is_dynamic {
2893                    any_dynamic_moved = true;
2894                } else {
2895                    any_static_moved = true;
2896                }
2897                let car_yaw: f32 = transform_val.get_yaw_rad();
2898                let car_origin: Vec3 = transform_val.get_position();
2899                let car_fwd: Vec3 = Vec3::new(-car_yaw.sin(), 0.0, -car_yaw.cos());
2900                let car_right: Vec3 = Vec3::new(car_yaw.cos(), 0.0, -car_yaw.sin());
2901                let beam_dir: Vec3 = Vec3::new(car_fwd.get_x(), -0.14, car_fwd.get_z()).normalize();
2902                if self.get_spot_lights().len() >= 2 {
2903                    let front_center: Vec3 = car_origin
2904                        .add(car_fwd.scale(2.2))
2905                        .add(Vec3::new(0.0, 0.95, 0.0));
2906                    let left_pos: Vec3 = front_center.sub(car_right.scale(0.85));
2907                    let right_pos: Vec3 = front_center.add(car_right.scale(0.85));
2908                    let spots: &mut Vec<SpotLight3D> = self.get_mut_spot_lights();
2909                    spots[0].set_position(left_pos);
2910                    spots[0].set_direction(beam_dir);
2911                    spots[1].set_position(right_pos);
2912                    spots[1].set_direction(beam_dir);
2913                }
2914                if throttle.abs() > 0.25
2915                    && (self.get_world_revision() & 3) == 0
2916                    && self.get_niagara().get_active_count() < 24
2917                {
2918                    let exhaust_pos: Vec3 = car_origin
2919                        .sub(car_fwd.scale(2.3))
2920                        .add(Vec3::new(0.0, 0.42, 0.0));
2921                    let mut spark_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
2922                    spark_cfg.set_origin(exhaust_pos);
2923                    spark_cfg.set_base_velocity(car_fwd.scale(-4.5).add(Vec3::new(0.0, 1.1, 0.0)));
2924                    spark_cfg.set_start_size_m(0.11);
2925                    spark_cfg.set_end_size_m(0.03);
2926                    self.get_mut_niagara().emit_burst(1, &spark_cfg);
2927                }
2928            }
2929            let car_tr: Transform3D = self.get_objects()[car_idx].get_transform();
2930            let car_pos: Vec3 = car_tr.get_position();
2931            let yaw: f32 = car_tr.get_yaw_rad();
2932            let cam_mode: u8 = self.get_camera_mode();
2933            let (mut desired_eye, look_target): (Vec3, Vec3) = match cam_mode {
2934                1 => {
2935                    let eye: Vec3 = Vec3::new(
2936                        car_pos.get_x() - yaw.sin() * 1.4,
2937                        2.15,
2938                        car_pos.get_z() - yaw.cos() * 1.4,
2939                    );
2940                    let tgt: Vec3 = Vec3::new(
2941                        car_pos.get_x() - yaw.sin() * 18.0,
2942                        1.8,
2943                        car_pos.get_z() - yaw.cos() * 18.0,
2944                    );
2945                    (eye, tgt)
2946                }
2947                2 => {
2948                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.45;
2949                    self.set_camera_orbit_rad(orbit);
2950                    let eye: Vec3 = Vec3::new(
2951                        car_pos.get_x() + orbit.sin() * 10.5,
2952                        5.2,
2953                        car_pos.get_z() + orbit.cos() * 10.5,
2954                    );
2955                    (eye, Vec3::new(car_pos.get_x(), 1.6, car_pos.get_z()))
2956                }
2957                3 => {
2958                    let eye: Vec3 = Vec3::new(
2959                        car_pos.get_x() + yaw.sin() * 18.0,
2960                        18.5,
2961                        car_pos.get_z() + yaw.cos() * 18.0,
2962                    );
2963                    (eye, Vec3::new(car_pos.get_x(), 1.2, car_pos.get_z()))
2964                }
2965                4 => {
2966                    let cur_cam: Camera3D = self.get_camera();
2967                    let fwd: Vec3 = cur_cam.forward();
2968                    let right: Vec3 = cur_cam.right();
2969                    let moved: Vec3 = cur_cam
2970                        .get_position()
2971                        .add(fwd.scale(throttle * 18.0 * dt))
2972                        .add(right.scale(steer * 14.0 * dt));
2973                    let eye: Vec3 = Vec3::new(moved.get_x(), moved.get_y().max(1.5), moved.get_z());
2974                    (eye, eye.add(fwd.scale(16.0)))
2975                }
2976                5 => {
2977                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.28;
2978                    self.set_camera_orbit_rad(orbit);
2979                    let eye: Vec3 = Vec3::new(
2980                        car_pos.get_x() + orbit.sin() * 7.8,
2981                        3.6 + (orbit * 1.5).sin() * 1.4,
2982                        car_pos.get_z() + orbit.cos() * 13.5,
2983                    );
2984                    (eye, Vec3::new(car_pos.get_x(), 1.8, car_pos.get_z() - 3.0))
2985                }
2986                _ => {
2987                    let eye: Vec3 = Vec3::new(
2988                        car_pos.get_x() + yaw.sin() * 12.5,
2989                        6.0,
2990                        car_pos.get_z() + yaw.cos() * 12.5,
2991                    );
2992                    let tgt: Vec3 =
2993                        Vec3::new(car_pos.get_x(), 2.2, car_pos.get_z() - yaw.cos() * 4.0);
2994                    (eye, tgt)
2995                }
2996            };
2997            let boom_anchor: Vec3 =
2998                Vec3::new(car_pos.get_x(), car_pos.get_y() + 1.8, car_pos.get_z());
2999            let boom_vec: Vec3 = desired_eye.sub(boom_anchor);
3000            let boom_len: f32 = boom_vec.length();
3001            if boom_len > 0.25 {
3002                let boom_dir: Vec3 = boom_vec.scale(1.0 / boom_len);
3003                if let Some(hit) =
3004                    self.raycast_solid_meshes(boom_anchor, boom_dir, boom_len, Some(car_idx))
3005                {
3006                    let safe_dist: f32 = (hit.get_distance() - 0.55).max(0.8);
3007                    desired_eye = boom_anchor.add(boom_dir.scale(safe_dist));
3008                }
3009            }
3010            let cam_probe: OrientedBox3D = OrientedBox3D::from_bounds(AxisAlignedBox3D::new(
3011                desired_eye.sub(Vec3::splat(0.45)),
3012                desired_eye.add(Vec3::splat(0.45)),
3013            ));
3014            if let Some(hit) = self.mesh_oriented_box_collision(cam_probe, Some(car_idx)) {
3015                desired_eye = desired_eye.add(hit.get_normal().scale(hit.get_penetration() + 0.1));
3016            }
3017            let prev_cam: Camera3D = self.get_camera();
3018            let mut cam: Camera3D = prev_cam;
3019            let smooth: f32 = (dt * 7.0).clamp(0.05, 1.0);
3020            cam.set_position(cam.get_position().lerp(desired_eye, smooth));
3021            let look_dir: Vec3 = look_target.sub(cam.get_position()).normalize();
3022            cam.set_yaw(look_dir.get_z().atan2(look_dir.get_x()));
3023            cam.set_pitch(look_dir.get_y().clamp(-0.92, 0.92).asin());
3024            self.set_camera(cam);
3025            if cam != prev_cam {
3026                self.bump_world_revision();
3027            }
3028        }
3029        let Self {
3030            objects,
3031            mesh_library,
3032            traffic_vehicles,
3033            ..
3034        } = self;
3035        for &(traffic_idx, vel_z, z_min, z_max) in traffic_vehicles.iter() {
3036            if let Some(obj) = objects.get_mut(traffic_idx) {
3037                let mut tr: Transform3D = obj.get_transform();
3038                let mut pos: Vec3 = tr.get_position();
3039                let mut next_z: f32 = pos.get_z() + vel_z * dt;
3040                let mut wrapped: bool = false;
3041                if next_z < z_min {
3042                    next_z = z_max;
3043                    wrapped = true;
3044                } else if next_z > z_max {
3045                    next_z = z_min;
3046                    wrapped = true;
3047                }
3048                pos.set_z(next_z);
3049                tr.set_position(pos);
3050                obj.set_transform(tr);
3051                if wrapped {
3052                    obj.set_teleport_epoch(obj.get_teleport_epoch().wrapping_add(1));
3053                }
3054                let local_bounds: AxisAlignedBox3D = mesh_library
3055                    .get(obj.get_mesh_id())
3056                    .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
3057                    .map(Mesh3D::get_bounds)
3058                    .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
3059                obj.set_world_bounds(tr.transform_bounds(local_bounds));
3060                if obj.get_is_dynamic() {
3061                    any_dynamic_moved = true;
3062                } else {
3063                    any_static_moved = true;
3064                }
3065            }
3066        }
3067        for obj in objects.iter_mut() {
3068            let spin: f32 = obj.get_spin_speed();
3069            if spin.abs() > 0.001 {
3070                let mut object_transform: Transform3D = obj.get_transform();
3071                object_transform.set_yaw_rad(object_transform.get_yaw_rad() + spin * dt);
3072                obj.set_transform(object_transform);
3073                let local_bounds: AxisAlignedBox3D = mesh_library
3074                    .get(obj.get_mesh_id())
3075                    .and_then(|color_item: &MeshLodChain| color_item.get_levels().first())
3076                    .map(Mesh3D::get_bounds)
3077                    .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
3078                obj.set_world_bounds(object_transform.transform_bounds(local_bounds));
3079                if obj.get_is_dynamic() {
3080                    any_dynamic_moved = true;
3081                } else {
3082                    any_static_moved = true;
3083                }
3084            }
3085        }
3086        if self.get_atmosphere_preset() == 1
3087            && (self.get_world_revision() & 1) == 0
3088            && self.get_niagara().get_active_count() < RAINY_NIGHT_MAX_PARTICLES
3089        {
3090            let cam_pos: Vec3 = self.get_camera().get_position();
3091            let mut rain_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
3092            rain_cfg.set_origin(cam_pos.add(Vec3::new(0.0, 5.0, -14.0)));
3093            rain_cfg.set_base_velocity(Vec3::new(-0.5, -15.5, 0.3));
3094            rain_cfg.set_velocity_spread(3.6);
3095            rain_cfg.set_start_color(Color::rgba(150, 218, 255, 210));
3096            rain_cfg.set_end_color(Color::rgba(68, 152, 240, 60));
3097            rain_cfg.set_start_size_m(0.07);
3098            rain_cfg.set_end_size_m(0.03);
3099            rain_cfg.set_min_lifetime(0.6);
3100            rain_cfg.set_max_lifetime(0.95);
3101            rain_cfg.set_emissive_boost(1.4);
3102            self.get_mut_niagara().emit_burst(2, &rain_cfg);
3103        }
3104        if self.get_niagara().get_active_count() > 0 {
3105            let _: usize = self.get_mut_niagara().update(dt, 0.0);
3106        }
3107        if any_static_moved {
3108            self.set_bvh_dirty(true);
3109        }
3110        if any_dynamic_moved {
3111            self.set_dynamic_bvh_dirty(true);
3112        }
3113        if any_static_moved || any_dynamic_moved {
3114            self.bump_world_revision();
3115        }
3116    }
3117}