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 quaternion rotation and unit scale.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Identity `Transform3D`.
10    fn default() -> Self {
11        Self {
12            position: Vec3::zero(),
13            rotation: Quat::identity(),
14            scale: Vec3::splat(1.0),
15        }
16    }
17}
18
19/// Quaternion-backed matrix, Euler compatibility, SLERP interpolation, and point transformation helpers for `Transform3D`.
20impl Transform3D {
21    /// Constructs a `Transform3D` from position, Y-axis yaw in radians, and non-uniform scale.
22    ///
23    /// # Arguments
24    ///
25    /// - `Vec3` - World-space translation.
26    /// - `f32` - Horizontal Y-axis yaw rotation in radians.
27    /// - `Vec3` - Non-uniform scale.
28    ///
29    /// # Returns
30    ///
31    /// - `Self` - Constructed quaternion-backed 3D transform.
32    #[must_use]
33    pub fn new(position: Vec3, yaw_rad: f32, scale: Vec3) -> Self {
34        Self {
35            position,
36            rotation: Quat::from_axis_angle(Vec3::new(0.0, 1.0, 0.0), yaw_rad),
37            scale,
38        }
39    }
40
41    /// Constructs a `Transform3D` directly from translation, unit quaternion rotation, and scale.
42    ///
43    /// # Arguments
44    ///
45    /// - `Vec3` - World-space translation.
46    /// - `Quat` - Orientation quaternion.
47    /// - `Vec3` - Non-uniform scale.
48    ///
49    /// # Returns
50    ///
51    /// - `Self` - Constructed 3D transform.
52    #[must_use]
53    pub fn from_trs(position: Vec3, rotation: Quat, scale: Vec3) -> Self {
54        Self {
55            position,
56            rotation: rotation.normalize(),
57            scale,
58        }
59    }
60
61    /// Decomposes an affine 4x4 matrix into a quaternion-backed `Transform3D`.
62    ///
63    /// # Arguments
64    ///
65    /// - `Mat4` - Column-major affine transformation matrix.
66    ///
67    /// # Returns
68    ///
69    /// - `Self` - Decomposed 3D transform.
70    #[must_use]
71    pub fn from_matrix(matrix: Mat4) -> Self {
72        let (position, rotation, scale): (Vec3, Quat, Vec3) = matrix.decompose_trs();
73        Self {
74            position,
75            rotation: rotation.normalize(),
76            scale,
77        }
78    }
79
80    /// Returns a copy of this transform rotated by `rotation`.
81    ///
82    /// # Arguments
83    ///
84    /// - `Self` - Source transform.
85    /// - `Quat` - Orientation quaternion.
86    ///
87    /// # Returns
88    ///
89    /// - `Self` - Updated transform.
90    #[must_use]
91    pub fn with_rotation(mut self, rotation: Quat) -> Self {
92        self.set_rotation(rotation.normalize());
93        self
94    }
95
96    /// Returns a copy of this transform with full yaw, pitch, and roll Euler rotation in radians (`Ry * Rx * Rz`).
97    ///
98    /// # Arguments
99    ///
100    /// - `Self` - Source transform.
101    /// - `f32` - Y-axis yaw in radians.
102    /// - `f32` - X-axis pitch in radians.
103    /// - `f32` - Z-axis roll in radians.
104    ///
105    /// # Returns
106    ///
107    /// - `Self` - Rotated 3D transform.
108    #[must_use]
109    pub fn with_euler(mut self, yaw_rad: f32, pitch_rad: f32, roll_rad: f32) -> Self {
110        self.set_rotation(Quat::from_euler_yxz(yaw_rad, pitch_rad, roll_rad));
111        self
112    }
113
114    /// Extracts `(yaw_rad, pitch_rad, roll_rad)` Euler angles matching `Ry(yaw) * Rx(pitch) * Rz(roll)` from this transform's quaternion.
115    ///
116    /// # Returns
117    ///
118    /// - `(f32, f32, f32)` - Extracted `(yaw_rad, pitch_rad, roll_rad)` in radians.
119    #[must_use]
120    pub fn euler_yxz(&self) -> (f32, f32, f32) {
121        let elems: [f32; 16] = self.get_rotation().to_mat4().get_elements();
122        let rot00: f32 = elems[0];
123        let rot10: f32 = elems[1];
124        let rot20: f32 = elems[2];
125        let rot11: f32 = elems[5];
126        let rot02: f32 = elems[8];
127        let rot12: f32 = elems[9];
128        let rot22: f32 = elems[10];
129        let sin_pitch: f32 = (-rot12).clamp(-1.0, 1.0);
130        let pitch_rad: f32 = sin_pitch.asin();
131        if rot12.abs() < 0.99999 {
132            let yaw_rad: f32 = rot02.atan2(rot22);
133            let roll_rad: f32 = rot10.atan2(rot11);
134            (yaw_rad, pitch_rad, roll_rad)
135        } else {
136            let yaw_rad: f32 = (-rot20).atan2(rot00);
137            (yaw_rad, pitch_rad, 0.0)
138        }
139    }
140
141    /// Returns the horizontal Y-axis yaw angle extracted from this transform's quaternion.
142    ///
143    /// # Returns
144    ///
145    /// - `f32` - Yaw angle in radians.
146    #[must_use]
147    pub fn get_yaw_rad(&self) -> f32 {
148        self.euler_yxz().0
149    }
150
151    /// Returns the vertical X-axis pitch angle extracted from this transform's quaternion.
152    ///
153    /// # Returns
154    ///
155    /// - `f32` - Pitch angle in radians.
156    #[must_use]
157    pub fn get_pitch_rad(&self) -> f32 {
158        self.euler_yxz().1
159    }
160
161    /// Returns the longitudinal Z-axis roll angle extracted from this transform's quaternion.
162    ///
163    /// # Returns
164    ///
165    /// - `f32` - Roll angle in radians.
166    #[must_use]
167    pub fn get_roll_rad(&self) -> f32 {
168        self.euler_yxz().2
169    }
170
171    /// Updates horizontal Y-axis yaw while preserving current pitch and roll angles.
172    ///
173    /// # Arguments
174    ///
175    /// - `&Self` - Mutable transform.
176    /// - `f32` - New Y-axis yaw angle in radians.
177    pub fn set_yaw_rad(&mut self, yaw_rad: f32) {
178        let (_, pitch_rad, roll_rad): (f32, f32, f32) = self.euler_yxz();
179        self.set_rotation(Quat::from_euler_yxz(yaw_rad, pitch_rad, roll_rad));
180    }
181
182    /// Updates vertical X-axis pitch while preserving current yaw and roll angles.
183    ///
184    /// # Arguments
185    ///
186    /// - `&Self` - Mutable transform.
187    /// - `f32` - New X-axis pitch angle in radians.
188    pub fn set_pitch_rad(&mut self, pitch_rad: f32) {
189        let (yaw_rad, _, roll_rad): (f32, f32, f32) = self.euler_yxz();
190        self.set_rotation(Quat::from_euler_yxz(yaw_rad, pitch_rad, roll_rad));
191    }
192
193    /// Updates longitudinal Z-axis roll while preserving current yaw and pitch angles.
194    ///
195    /// # Arguments
196    ///
197    /// - `&Self` - Mutable transform.
198    /// - `f32` - New Z-axis roll angle in radians.
199    pub fn set_roll_rad(&mut self, roll_rad: f32) {
200        let (yaw_rad, pitch_rad, _): (f32, f32, f32) = self.euler_yxz();
201        self.set_rotation(Quat::from_euler_yxz(yaw_rad, pitch_rad, roll_rad));
202    }
203
204    /// Interpolates position, shortest-arc quaternion rotation (SLERP), and scale between `self` and `other`.
205    ///
206    /// # Arguments
207    ///
208    /// - `Self` - Start transform.
209    /// - `Self` - End transform.
210    /// - `f32` - Interpolation factor in `[0.0, 1.0]`.
211    ///
212    /// # Returns
213    ///
214    /// - `Self` - Smoothly interpolated transform.
215    #[must_use]
216    pub fn lerp(self, other: Self, blend_factor: f32) -> Self {
217        let clamped_t: f32 = blend_factor.clamp(0.0, 1.0);
218        Self {
219            position: self.get_position().lerp(other.get_position(), clamped_t),
220            rotation: self.get_rotation().slerp(other.get_rotation(), clamped_t),
221            scale: self.get_scale().lerp(other.get_scale(), clamped_t),
222        }
223    }
224
225    /// Interpolates position, scale, and shortest-arc quaternion rotation (SLERP) between `self` and `other` for render-time snapshot blending.
226    ///
227    /// # Arguments
228    ///
229    /// - `Self` - Previous fixed-step transform.
230    /// - `Self` - Current fixed-step transform.
231    /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
232    ///
233    /// # Returns
234    ///
235    /// - `Self` - Shortest-arc SLERP interpolated transform.
236    #[must_use]
237    pub fn lerp_shortest_angle(self, other: Self, blend_factor: f32) -> Self {
238        self.lerp(other, blend_factor)
239    }
240
241    /// Converts this quaternion-backed TRS transform into a column-major `Mat4`.
242    ///
243    /// # Arguments
244    ///
245    /// - `&Self` - Transform reference.
246    ///
247    /// # Returns
248    ///
249    /// - `Mat4` - Model matrix.
250    #[must_use]
251    pub fn to_mat4(&self) -> Mat4 {
252        Mat4::from_trs_quat(self.get_position(), self.get_rotation(), self.get_scale())
253    }
254
255    /// Computes the exact inverse TRS matrix mapping world space back to local object space.
256    ///
257    /// # Arguments
258    ///
259    /// - `&Self` - Transform reference.
260    ///
261    /// # Returns
262    ///
263    /// - `Mat4` - Inverse model matrix.
264    #[must_use]
265    pub fn to_inv_mat4(&self) -> Mat4 {
266        self.to_mat4().inverse().unwrap_or_else(Mat4::identity)
267    }
268
269    /// Precomputes the exact cofactor-transpose 3x3 normal basis `[col_x, col_y, col_z]` valid under non-uniform and negative scale.
270    ///
271    /// # Arguments
272    ///
273    /// - `&Self` - Transform reference.
274    ///
275    /// # Returns
276    ///
277    /// - `[Vec3; 3]` - Cofactor 3x3 normal basis columns.
278    #[must_use]
279    pub fn normal_mat3(&self) -> [Vec3; 3] {
280        self.to_mat4().normal_matrix_3x3()
281    }
282
283    /// Rotates vector `vec_value` by this transform's unit quaternion orientation.
284    ///
285    /// # Arguments
286    ///
287    /// - `&Self` - Transform reference.
288    /// - `Vec3` - Input vector.
289    ///
290    /// # Returns
291    ///
292    /// - `Vec3` - Rotated vector.
293    #[must_use]
294    fn rotate_vec(&self, vec_value: Vec3) -> Vec3 {
295        self.get_rotation().rotate_vec3(vec_value)
296    }
297
298    /// Transforms a local-space 3D point into world space.
299    ///
300    /// # Arguments
301    ///
302    /// - `&Self` - Transform reference.
303    /// - `Vec3` - Local-space point.
304    ///
305    /// # Returns
306    ///
307    /// - `Vec3` - World-space point.
308    #[must_use]
309    pub fn transform_point(&self, vec_value: Vec3) -> Vec3 {
310        let direction_vec: Vec3 = self.get_scale();
311        let scaled: Vec3 = Vec3::new(
312            vec_value.get_x() * direction_vec.get_x(),
313            vec_value.get_y() * direction_vec.get_y(),
314            vec_value.get_z() * direction_vec.get_z(),
315        );
316        self.rotate_vec(scaled).add(self.get_position())
317    }
318
319    /// Rotates a local-space surface normal into world space.
320    ///
321    /// # Arguments
322    ///
323    /// - `&Self` - Transform reference.
324    /// - `Vec3` - Local normal.
325    ///
326    /// # Returns
327    ///
328    /// - `Vec3` - World-space unit normal.
329    #[must_use]
330    pub fn transform_normal(&self, vec_value: Vec3) -> Vec3 {
331        self.rotate_vec(vec_value).normalize()
332    }
333
334    /// Transforms a local `AxisAlignedBox3D` into an enclosing world-space `AxisAlignedBox3D` using Arvo's 18-multiply method (zero 8-corner loop, zero per-corner trigonometry).
335    ///
336    /// # Arguments
337    ///
338    /// - `&Self` - Transform reference.
339    /// - `AxisAlignedBox3D` - Local bounding box.
340    ///
341    /// # Returns
342    ///
343    /// - `AxisAlignedBox3D` - Enclosing world-space bounding box.
344    #[must_use]
345    pub fn transform_bounds(&self, local: AxisAlignedBox3D) -> AxisAlignedBox3D {
346        self.to_mat4().transform_bounds(local)
347    }
348
349    /// 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.
350    ///
351    /// # Arguments
352    ///
353    /// - `&Self` - Transform reference.
354    /// - `AxisAlignedBox3D` - Local-space bounding box.
355    ///
356    /// # Returns
357    ///
358    /// - `OrientedBox3D` - Oriented bounding box in world space.
359    #[must_use]
360    pub fn to_oriented_box(&self, local: AxisAlignedBox3D) -> OrientedBox3D {
361        let local_center: Vec3 = local.get_min().add(local.get_max()).scale(0.5);
362        let local_half: Vec3 = local.get_max().sub(local.get_min()).scale(0.5);
363        let vec_value: Vec3 = self.get_scale();
364        let center: Vec3 = self.transform_point(local_center);
365        let ax: Vec3 = self.rotate_vec(Vec3::new(1.0, 0.0, 0.0)).normalize();
366        let ay: Vec3 = self.rotate_vec(Vec3::new(0.0, 1.0, 0.0)).normalize();
367        let az: Vec3 = self.rotate_vec(Vec3::new(0.0, 0.0, 1.0)).normalize();
368        let half_extents: Vec3 = Vec3::new(
369            (local_half.get_x() * vec_value.get_x()).abs().max(1e-4),
370            (local_half.get_y() * vec_value.get_y()).abs().max(1e-4),
371            (local_half.get_z() * vec_value.get_z()).abs().max(1e-4),
372        );
373        OrientedBox3D::new(center, [ax, ay, az], half_extents)
374    }
375}
376
377/// Exact oriented bounding box and 13-axis SAT triangle intersection helpers for `OrientedBox3D`.
378impl OrientedBox3D {
379    /// Constructs an axis-aligned `OrientedBox3D` from a world-space `AxisAlignedBox3D`.
380    ///
381    /// # Arguments
382    ///
383    /// - `AxisAlignedBox3D` - World-space axis-aligned bounding box.
384    ///
385    /// # Returns
386    ///
387    /// - `Self` - Equivalent world-space `OrientedBox3D`.
388    #[must_use]
389    pub fn from_bounds(bounds_rect: AxisAlignedBox3D) -> Self {
390        let center: Vec3 = bounds_rect.get_min().add(bounds_rect.get_max()).scale(0.5);
391        let half: Vec3 = bounds_rect.get_max().sub(bounds_rect.get_min()).scale(0.5);
392        Self::new(
393            center,
394            [
395                Vec3::new(1.0, 0.0, 0.0),
396                Vec3::new(0.0, 1.0, 0.0),
397                Vec3::new(0.0, 0.0, 1.0),
398            ],
399            Vec3::new(
400                half.get_x().abs().max(1e-4),
401                half.get_y().abs().max(1e-4),
402                half.get_z().abs().max(1e-4),
403            ),
404        )
405    }
406
407    /// Computes the tightest enclosing world-space `AxisAlignedBox3D` for broadphase culling.
408    ///
409    /// # Arguments
410    ///
411    /// - `&Self` - Oriented bounding box reference.
412    ///
413    /// # Returns
414    ///
415    /// - `AxisAlignedBox3D` - Enclosing world-space axis-aligned bounding box.
416    #[must_use]
417    pub fn to_world_bounds(&self) -> AxisAlignedBox3D {
418        let vec_value: Vec3 = self.get_center();
419        let axes: [Vec3; 3] = self.get_axes();
420        let height_val: Vec3 = self.get_half_extents();
421        let ex: f32 = axes[0].get_x().abs() * height_val.get_x()
422            + axes[1].get_x().abs() * height_val.get_y()
423            + axes[2].get_x().abs() * height_val.get_z();
424        let ey: f32 = axes[0].get_y().abs() * height_val.get_x()
425            + axes[1].get_y().abs() * height_val.get_y()
426            + axes[2].get_y().abs() * height_val.get_z();
427        let ez: f32 = axes[0].get_z().abs() * height_val.get_x()
428            + axes[1].get_z().abs() * height_val.get_y()
429            + axes[2].get_z().abs() * height_val.get_z();
430        let ext: Vec3 = Vec3::new(ex, ey, ez);
431        AxisAlignedBox3D::new(vec_value.sub(ext), vec_value.add(ext))
432    }
433
434    /// Tests exact 13-axis Akenine-Möller SAT intersection between this `OrientedBox3D` and a world-space triangle `(w0, w1, w2)`.
435    ///
436    /// # Arguments
437    ///
438    /// - `&Self` - Oriented bounding box reference.
439    /// - `Vec3` - Triangle vertex 0 in world space.
440    /// - `Vec3` - Triangle vertex 1 in world space.
441    /// - `Vec3` - Triangle vertex 2 in world space.
442    ///
443    /// # Returns
444    ///
445    /// - `Option<(Vec3, f32, Vec3)>` - `(world_outward_normal, penetration_depth, world_contact_point)` when intersecting.
446    #[must_use]
447    pub fn intersect_triangle_world(
448        &self,
449        w0: Vec3,
450        w1: Vec3,
451        w2: Vec3,
452    ) -> Option<(Vec3, f32, Vec3)> {
453        let vec_value: Vec3 = self.get_center();
454        let axes: [Vec3; 3] = self.get_axes();
455        let height_val: Vec3 = self.get_half_extents();
456        let d0: Vec3 = w0.sub(vec_value);
457        let d1: Vec3 = w1.sub(vec_value);
458        let d2: Vec3 = w2.sub(vec_value);
459        let v0: Vec3 = Vec3::new(d0.dot(axes[0]), d0.dot(axes[1]), d0.dot(axes[2]));
460        let v1: Vec3 = Vec3::new(d1.dot(axes[0]), d1.dot(axes[1]), d1.dot(axes[2]));
461        let v2: Vec3 = Vec3::new(d2.dot(axes[0]), d2.dot(axes[1]), d2.dot(axes[2]));
462        let min_x: f32 = v0.get_x().min(v1.get_x()).min(v2.get_x());
463        let max_x: f32 = v0.get_x().max(v1.get_x()).max(v2.get_x());
464        if min_x >= height_val.get_x() || max_x <= -height_val.get_x() {
465            return None;
466        }
467        let min_y: f32 = v0.get_y().min(v1.get_y()).min(v2.get_y());
468        let max_y: f32 = v0.get_y().max(v1.get_y()).max(v2.get_y());
469        if min_y >= height_val.get_y() || max_y <= -height_val.get_y() {
470            return None;
471        }
472        let min_z: f32 = v0.get_z().min(v1.get_z()).min(v2.get_z());
473        let max_z: f32 = v0.get_z().max(v1.get_z()).max(v2.get_z());
474        if min_z >= height_val.get_z() || max_z <= -height_val.get_z() {
475            return None;
476        }
477        let mut best_pen: f32 = f32::INFINITY;
478        let mut best_local_n: Vec3 = Vec3::new(0.0, 1.0, 0.0);
479        let box_axes: [(f32, f32, f32, Vec3); 3] = [
480            (min_x, max_x, height_val.get_x(), Vec3::new(1.0, 0.0, 0.0)),
481            (min_y, max_y, height_val.get_y(), Vec3::new(0.0, 1.0, 0.0)),
482            (min_z, max_z, height_val.get_z(), Vec3::new(0.0, 0.0, 1.0)),
483        ];
484        for (t_min, t_max, half_e, axis) in box_axes {
485            let pen: f32 = (half_e - t_min).min(t_max + half_e);
486            if pen <= 1e-6 {
487                return None;
488            }
489            if pen < best_pen {
490                best_pen = pen;
491                best_local_n = if t_min + t_max > 0.0 {
492                    axis.scale(-1.0)
493                } else {
494                    axis
495                };
496            }
497        }
498        let e0: Vec3 = v1.sub(v0);
499        let e1: Vec3 = v2.sub(v1);
500        let e2: Vec3 = v0.sub(v2);
501        let face_raw: Vec3 = e0.cross(v2.sub(v0));
502        let face_len_sq: f32 = face_raw.length_sq();
503        if face_len_sq > 1e-12 {
504            let face_n: Vec3 = face_raw.scale(1.0 / face_len_sq.sqrt());
505            let dist: f32 = face_n.dot(v0);
506            let red_val: f32 = height_val.get_x() * face_n.get_x().abs()
507                + height_val.get_y() * face_n.get_y().abs()
508                + height_val.get_z() * face_n.get_z().abs();
509            let pen: f32 = red_val - dist.abs();
510            if pen <= 1e-6 {
511                return None;
512            }
513            if pen < best_pen {
514                best_pen = pen;
515                best_local_n = if dist > 0.0 {
516                    face_n.scale(-1.0)
517                } else {
518                    face_n
519                };
520            }
521        }
522        let edges: [Vec3; 3] = [e0, e1, e2];
523        let unit_axes: [Vec3; 3] = [
524            Vec3::new(1.0, 0.0, 0.0),
525            Vec3::new(0.0, 1.0, 0.0),
526            Vec3::new(0.0, 0.0, 1.0),
527        ];
528        for edge in edges {
529            for u_axis in unit_axes {
530                let raw_a: Vec3 = edge.cross(u_axis);
531                let len_sq: f32 = raw_a.length_sq();
532                if len_sq <= 1e-10 {
533                    continue;
534                }
535                let axis: Vec3 = raw_a.scale(1.0 / len_sq.sqrt());
536                let p0: f32 = v0.dot(axis);
537                let p1: f32 = v1.dot(axis);
538                let p2: f32 = v2.dot(axis);
539                let t_min: f32 = p0.min(p1).min(p2);
540                let t_max: f32 = p0.max(p1).max(p2);
541                let radius_val: f32 = height_val.get_x() * axis.get_x().abs()
542                    + height_val.get_y() * axis.get_y().abs()
543                    + height_val.get_z() * axis.get_z().abs();
544                if t_min >= radius_val || t_max <= -radius_val {
545                    return None;
546                }
547                let pen: f32 = (radius_val - t_min).min(t_max + radius_val);
548                if pen <= 1e-6 {
549                    return None;
550                }
551                if pen < best_pen {
552                    best_pen = pen;
553                    best_local_n = if t_min + t_max > 0.0 {
554                        axis.scale(-1.0)
555                    } else {
556                        axis
557                    };
558                }
559            }
560        }
561        let tri_center: Vec3 = v0.add(v1).add(v2).scale(1.0 / 3.0);
562        let local_contact: Vec3 = Vec3::new(
563            tri_center
564                .get_x()
565                .clamp(-height_val.get_x(), height_val.get_x()),
566            tri_center
567                .get_y()
568                .clamp(-height_val.get_y(), height_val.get_y()),
569            tri_center
570                .get_z()
571                .clamp(-height_val.get_z(), height_val.get_z()),
572        );
573        let world_n: Vec3 = axes[0]
574            .scale(best_local_n.get_x())
575            .add(axes[1].scale(best_local_n.get_y()))
576            .add(axes[2].scale(best_local_n.get_z()))
577            .normalize();
578        let world_contact: Vec3 = vec_value
579            .add(axes[0].scale(local_contact.get_x()))
580            .add(axes[1].scale(local_contact.get_y()))
581            .add(axes[2].scale(local_contact.get_z()));
582        Some((world_n, best_pen, world_contact))
583    }
584
585    /// Tests exact 15-axis Separating Axis Theorem intersection between two world-space `OrientedBox3D` volumes for symmetric vehicle-vs-vehicle collision checks.
586    ///
587    /// # Arguments
588    ///
589    /// - `&Self` - First oriented bounding box.
590    /// - `&Self` - Second oriented bounding box.
591    ///
592    /// # Returns
593    ///
594    /// - `bool` - `true` when the two oriented bounding boxes overlap.
595    #[must_use]
596    pub fn intersects_oriented_box(&self, other: &Self) -> bool {
597        let a_axes: [Vec3; 3] = self.get_axes();
598        let b_axes: [Vec3; 3] = other.get_axes();
599        let a_ext: [f32; 3] = [
600            self.get_half_extents().get_x(),
601            self.get_half_extents().get_y(),
602            self.get_half_extents().get_z(),
603        ];
604        let b_ext: [f32; 3] = [
605            other.get_half_extents().get_x(),
606            other.get_half_extents().get_y(),
607            other.get_half_extents().get_z(),
608        ];
609        let mut rot: [[f32; 3]; 3] = [[0.0; 3]; 3];
610        let mut abs_rot: [[f32; 3]; 3] = [[0.0; 3]; 3];
611        for row_idx in 0..3_usize {
612            for col_idx in 0..3_usize {
613                let dot_val: f32 = a_axes[row_idx].dot(b_axes[col_idx]);
614                rot[row_idx][col_idx] = dot_val;
615                abs_rot[row_idx][col_idx] = dot_val.abs() + 1.0e-5;
616            }
617        }
618        let delta_world: Vec3 = other.get_center().sub(self.get_center());
619        let trans: [f32; 3] = [
620            delta_world.dot(a_axes[0]),
621            delta_world.dot(a_axes[1]),
622            delta_world.dot(a_axes[2]),
623        ];
624        for row_idx in 0..3_usize {
625            let ra: f32 = a_ext[row_idx];
626            let rb: f32 = b_ext[0] * abs_rot[row_idx][0]
627                + b_ext[1] * abs_rot[row_idx][1]
628                + b_ext[2] * abs_rot[row_idx][2];
629            if trans[row_idx].abs() > ra + rb {
630                return false;
631            }
632        }
633        for col_idx in 0..3_usize {
634            let ra: f32 = a_ext[0] * abs_rot[0][col_idx]
635                + a_ext[1] * abs_rot[1][col_idx]
636                + a_ext[2] * abs_rot[2][col_idx];
637            let rb: f32 = b_ext[col_idx];
638            let proj: f32 = trans[0] * rot[0][col_idx]
639                + trans[1] * rot[1][col_idx]
640                + trans[2] * rot[2][col_idx];
641            if proj.abs() > ra + rb {
642                return false;
643            }
644        }
645        for row_idx in 0..3_usize {
646            let r1: usize = (row_idx + 1) % 3;
647            let r2: usize = (row_idx + 2) % 3;
648            for col_idx in 0..3_usize {
649                let c1: usize = (col_idx + 1) % 3;
650                let c2: usize = (col_idx + 2) % 3;
651                let ra: f32 = a_ext[r1] * abs_rot[r2][col_idx] + a_ext[r2] * abs_rot[r1][col_idx];
652                let rb: f32 = b_ext[c1] * abs_rot[row_idx][c2] + b_ext[c2] * abs_rot[row_idx][c1];
653                let proj: f32 = trans[r2] * rot[r1][col_idx] - trans[r1] * rot[r2][col_idx];
654                if proj.abs() > ra + rb {
655                    return false;
656                }
657            }
658        }
659        true
660    }
661
662    /// Computes the four horizontal XZ corner coordinates of an oriented box centered at `center`.
663    ///
664    /// # Arguments
665    ///
666    /// - `Vec3` - Box center position.
667    /// - `(f32, f32)` - Normalized horizontal local X axis `(ux, uz)`.
668    /// - `(f32, f32)` - Normalized horizontal local Z axis `(vx, vz)`.
669    /// - `(f32, f32)` - Positive horizontal half-extents `(hx, hz)`.
670    ///
671    /// # Returns
672    ///
673    /// - `[(f32, f32); 4]` - Four world-space XZ corners of the box.
674    #[inline]
675    #[must_use]
676    fn xz_corners(
677        center: Vec3,
678        u_vec: (f32, f32),
679        v_vec: (f32, f32),
680        half_xz: (f32, f32),
681    ) -> [(f32, f32); 4] {
682        let cx: f32 = center.get_x();
683        let cz: f32 = center.get_z();
684        let (hx, hz): (f32, f32) = half_xz;
685        [
686            (
687                cx + u_vec.0 * hx + v_vec.0 * hz,
688                cz + u_vec.1 * hx + v_vec.1 * hz,
689            ),
690            (
691                cx + u_vec.0 * hx - v_vec.0 * hz,
692                cz + u_vec.1 * hx - v_vec.1 * hz,
693            ),
694            (
695                cx - u_vec.0 * hx + v_vec.0 * hz,
696                cz - u_vec.1 * hx + v_vec.1 * hz,
697            ),
698            (
699                cx - u_vec.0 * hx - v_vec.0 * hz,
700                cz - u_vec.1 * hx - v_vec.1 * hz,
701            ),
702        ]
703    }
704
705    /// Computes an exact horizontal XZ Separating Axis Theorem contact manifold between two world-space `OrientedBox3D` vehicle volumes.
706    ///
707    /// # Arguments
708    ///
709    /// - `&Self` - Second oriented bounding box (`B`).
710    ///
711    /// # Returns
712    ///
713    /// - `Option<(Vec3, f32, Vec3)>` - `(unit_normal_b_to_a, penetration_m, world_contact_point)` when overlapping vertically and horizontally.
714    #[must_use]
715    pub fn intersect_oriented_box_xz(&self, other: &Self) -> Option<(Vec3, f32, Vec3)> {
716        let a_bounds: AxisAlignedBox3D = self.to_world_bounds();
717        let b_bounds: AxisAlignedBox3D = other.to_world_bounds();
718        if a_bounds.get_max().get_y() <= b_bounds.get_min().get_y()
719            || b_bounds.get_max().get_y() <= a_bounds.get_min().get_y()
720        {
721            return None;
722        }
723        let norm_xz: fn(Vec3, (f32, f32)) -> (f32, f32) =
724            |axis: Vec3, fallback: (f32, f32)| -> (f32, f32) {
725                let len: f32 = (axis.get_x() * axis.get_x() + axis.get_z() * axis.get_z()).sqrt();
726                if len > 1.0e-5 {
727                    (axis.get_x() / len, axis.get_z() / len)
728                } else {
729                    fallback
730                }
731            };
732        let a_axes: [Vec3; 3] = self.get_axes();
733        let b_axes: [Vec3; 3] = other.get_axes();
734        let ua: (f32, f32) = norm_xz(a_axes[0], (1.0, 0.0));
735        let va: (f32, f32) = norm_xz(a_axes[2], (0.0, 1.0));
736        let ub: (f32, f32) = norm_xz(b_axes[0], (1.0, 0.0));
737        let vb: (f32, f32) = norm_xz(b_axes[2], (0.0, 1.0));
738        let hxa: f32 = self.get_half_extents().get_x();
739        let hza: f32 = self.get_half_extents().get_z();
740        let hxb: f32 = other.get_half_extents().get_x();
741        let hzb: f32 = other.get_half_extents().get_z();
742        let ca: Vec3 = self.get_center();
743        let cb: Vec3 = other.get_center();
744        let dx: f32 = ca.get_x() - cb.get_x();
745        let dz: f32 = ca.get_z() - cb.get_z();
746        let sat_axes: [(f32, f32); 4] = [ua, va, ub, vb];
747        let mut best_pen: f32 = f32::INFINITY;
748        let mut best_nx: f32 = 1.0;
749        let mut best_nz: f32 = 0.0;
750        let mut best_idx: usize = 0;
751        for (axis_idx, &(ax, az)) in sat_axes.iter().enumerate() {
752            let ra: f32 = hxa * (ua.0 * ax + ua.1 * az).abs() + hza * (va.0 * ax + va.1 * az).abs();
753            let rb: f32 = hxb * (ub.0 * ax + ub.1 * az).abs() + hzb * (vb.0 * ax + vb.1 * az).abs();
754            let center_proj: f32 = dx * ax + dz * az;
755            let overlap: f32 = (ra + rb) - center_proj.abs();
756            if overlap <= 1.0e-5 {
757                return None;
758            }
759            if overlap < best_pen {
760                best_pen = overlap;
761                let sign: f32 = if center_proj >= 0.0 { 1.0 } else { -1.0 };
762                best_nx = ax * sign;
763                best_nz = az * sign;
764                best_idx = axis_idx;
765            }
766        }
767        let (inc_corners, dir_x, dir_z): ([(f32, f32); 4], f32, f32) = if best_idx < 2 {
768            (Self::xz_corners(cb, ub, vb, (hxb, hzb)), best_nx, best_nz)
769        } else {
770            (Self::xz_corners(ca, ua, va, (hxa, hza)), -best_nx, -best_nz)
771        };
772        let mut max_proj: f32 = f32::NEG_INFINITY;
773        for &(px, pz) in inc_corners.iter() {
774            let proj: f32 = px * dir_x + pz * dir_z;
775            if proj > max_proj {
776                max_proj = proj;
777            }
778        }
779        let mut sum_x: f32 = 0.0;
780        let mut sum_z: f32 = 0.0;
781        let mut count: f32 = 0.0;
782        for &(px, pz) in inc_corners.iter() {
783            let proj: f32 = px * dir_x + pz * dir_z;
784            if proj >= max_proj - 0.08 {
785                sum_x += px;
786                sum_z += pz;
787                count += 1.0;
788            }
789        }
790        let inv_cnt: f32 = if count > 0.0 { 1.0 / count } else { 1.0 };
791        let contact_y: f32 = (ca.get_y() + cb.get_y()) * 0.5;
792        let contact: Vec3 = Vec3::new(sum_x * inv_cnt, contact_y, sum_z * inv_cnt);
793        Some((Vec3::new(best_nx, 0.0, best_nz), best_pen, contact))
794    }
795}
796
797/// Default full-tank stationary player chassis dynamics state.
798impl Default for PlayerVehiclePhysics3D {
799    /// Initializes a stationary player vehicle with a full nitro boost tank.
800    ///
801    /// # Returns
802    ///
803    /// - `Self` - Stationary `PlayerVehiclePhysics3D` with `boost_charge = 1.0`.
804    fn default() -> Self {
805        Self {
806            vel: Vec3::zero(),
807            yaw_rate: 0.0,
808            body_roll_rad: 0.0,
809            body_pitch_rad: 0.0,
810            boost_active: false,
811            boost_charge: 1.0,
812            drift_active: false,
813            drift_slip_angle: 0.0,
814            drift_duration: 0.0,
815            drift_peak_slip: 0.0,
816            camera_fov_boost: 0.0,
817            camera_shake: 0.0,
818        }
819    }
820}
821
822/// Constructors and navigation route helpers for dynamic rigid-body `NpcVehicle3D` units.
823impl NpcVehicle3D {
824    /// Creates a rigid-body NPC vehicle initially cruising along the 962m boulevard loop with full freedom to be knocked off-road.
825    ///
826    /// # Arguments
827    ///
828    /// - `usize` - Owning scene object index.
829    /// - `f32` - Initial loop centerline arc progress in meters.
830    /// - `f32` - Initial lateral lane offset in meters.
831    /// - `f32` - Signed cruising speed in meters per second.
832    /// - `f32` - Initial facing yaw in radians.
833    ///
834    /// # Returns
835    ///
836    /// - `Self` - Initialized boulevard-cruising rigid-body NPC vehicle.
837    #[must_use]
838    pub(crate) fn new_boulevard(
839        object_index: usize,
840        start_s: f32,
841        lane_u: f32,
842        signed_speed_mps: f32,
843        face_yaw: f32,
844    ) -> Self {
845        let dir: f32 = if signed_speed_mps >= 0.0 { 1.0 } else { -1.0 };
846        let speed: f32 = signed_speed_mps.abs();
847        let fwd: Vec3 = Vec3::new(-face_yaw.sin(), 0.0, -face_yaw.cos());
848        let (target_pos, _): (Vec3, f32) = World3D::loop_pose_at(start_s + dir * 10.0, lane_u);
849        Self {
850            object_index,
851            vel: fwd.scale(speed),
852            yaw_rate: 0.0,
853            mass: VEHICLE_NPC_MASS_KG,
854            cruise_speed: speed,
855            recovery_timer: 0.0,
856            free_roam_mode: false,
857            loop_arc_s: start_s,
858            loop_lane_u: lane_u,
859            loop_dir: dir,
860            nav_target: target_pos,
861            waypoint_idx: 0,
862            route_id: 0,
863        }
864    }
865
866    /// Creates an unrestricted off-road free-roaming rigid-body NPC vehicle navigating open city plazas and courtyards.
867    ///
868    /// # Arguments
869    ///
870    /// - `usize` - Owning scene object index.
871    /// - `u8` - Assigned open-city waypoint route identifier.
872    /// - `usize` - Starting waypoint index along the route.
873    /// - `f32` - Target cruising speed in meters per second.
874    /// - `f32` - Initial facing yaw in radians.
875    ///
876    /// # Returns
877    ///
878    /// - `Self` - Initialized off-road free-roaming rigid-body NPC vehicle.
879    #[must_use]
880    pub(crate) fn new_free_roam(
881        object_index: usize,
882        route_id: u8,
883        waypoint_idx: usize,
884        cruise_speed: f32,
885        face_yaw: f32,
886    ) -> Self {
887        let waypoints: &[(f32, f32)] = Self::route_waypoints(route_id);
888        let safe_idx: usize = waypoint_idx % waypoints.len();
889        let (tx, tz): (f32, f32) = waypoints[safe_idx];
890        let fwd: Vec3 = Vec3::new(-face_yaw.sin(), 0.0, -face_yaw.cos());
891        Self {
892            object_index,
893            vel: fwd.scale(cruise_speed),
894            yaw_rate: 0.0,
895            mass: VEHICLE_NPC_MASS_KG,
896            cruise_speed,
897            recovery_timer: 0.0,
898            free_roam_mode: true,
899            loop_arc_s: 0.0,
900            loop_lane_u: 0.0,
901            loop_dir: 1.0,
902            nav_target: Vec3::new(tx, 0.0, tz),
903            waypoint_idx: safe_idx,
904            route_id,
905        }
906    }
907
908    /// Returns the static open-city off-road waypoint slice for `route_id`.
909    ///
910    /// # Arguments
911    ///
912    /// - `u8` - Open-city route identifier (`0..=2`).
913    ///
914    /// # Returns
915    ///
916    /// - `&'static [(f32, f32)]` - Ordered `(x, z)` waypoints outside the asphalt road.
917    #[must_use]
918    pub(crate) fn route_waypoints(route_id: u8) -> &'static [(f32, f32)] {
919        match route_id {
920            1 => &NPC_OUTER_PLAZA_WAYPOINTS,
921            2 => &NPC_COURTYARD_CROSS_WAYPOINTS,
922            _ => &NPC_INNER_PLAZA_WAYPOINTS,
923        }
924    }
925
926    /// Selects the closest off-road open-city route and waypoint to `pos` so knocked NPCs smoothly resume roaming without ever snapping back to a road lane.
927    ///
928    /// # Arguments
929    ///
930    /// - `Vec3` - Current world-space vehicle position.
931    ///
932    /// # Returns
933    ///
934    /// - `(u8, usize, Vec3)` - `(route_id, waypoint_idx, waypoint_pos)`.
935    #[must_use]
936    pub(crate) fn nearest_open_waypoint(pos: Vec3) -> (u8, usize, Vec3) {
937        let mut best_route: u8 = 0;
938        let mut best_idx: usize = 0;
939        let mut best_pos: Vec3 = Vec3::new(
940            NPC_INNER_PLAZA_WAYPOINTS[0].0,
941            0.0,
942            NPC_INNER_PLAZA_WAYPOINTS[0].1,
943        );
944        let mut best_dist_sq: f32 = f32::INFINITY;
945        for route_id in 0..3_u8 {
946            let pts: &[(f32, f32)] = Self::route_waypoints(route_id);
947            for (idx, &(wx, wz)) in pts.iter().enumerate() {
948                let dx: f32 = wx - pos.get_x();
949                let dz: f32 = wz - pos.get_z();
950                let dist_sq: f32 = dx * dx + dz * dz;
951                if dist_sq > 25.0 && dist_sq < best_dist_sq {
952                    best_dist_sq = dist_sq;
953                    best_route = route_id;
954                    best_idx = idx;
955                    best_pos = Vec3::new(wx, 0.0, wz);
956                }
957            }
958        }
959        (best_route, best_idx, best_pos)
960    }
961}
962
963/// Conversion helpers for `CameraMode3D`.
964impl CameraMode3D {
965    /// Converts a numeric mode index (`0..=5`) into a typed `CameraMode3D`.
966    ///
967    /// # Arguments
968    ///
969    /// - `u8` - Numeric camera mode index.
970    ///
971    /// # Returns
972    ///
973    /// - `Self` - Corresponding `CameraMode3D`.
974    #[must_use]
975    pub const fn from_u8(index: u8) -> Self {
976        match index {
977            1 => Self::Hood,
978            2 => Self::Orbit,
979            3 => Self::Aerial,
980            4 => Self::FreeFly,
981            5 => Self::CinematicDolly,
982            _ => Self::Chase,
983        }
984    }
985
986    /// Converts this `CameraMode3D` into its stable numeric index (`0..=5`).
987    ///
988    /// # Arguments
989    ///
990    /// - `Self` - Camera mode variant.
991    ///
992    /// # Returns
993    ///
994    /// - `u8` - Numeric mode index.
995    #[must_use]
996    pub const fn as_u8(self) -> u8 {
997        match self {
998            Self::Chase => 0,
999            Self::Hood => 1,
1000            Self::Orbit => 2,
1001            Self::Aerial => 3,
1002            Self::FreeFly => 4,
1003            Self::CinematicDolly => 5,
1004        }
1005    }
1006}
1007
1008/// Fluent builder helpers for `SpawnObjectDesc`.
1009impl SpawnObjectDesc {
1010    /// Creates an object spawn descriptor with identity transform, default PBR material, and BVH ray tracing enabled.
1011    ///
1012    /// # Arguments
1013    ///
1014    /// - `&str` - Human-readable object label.
1015    /// - `usize` - Registered mesh identifier.
1016    ///
1017    /// # Returns
1018    ///
1019    /// - `Self` - Ready spawn descriptor.
1020    #[must_use]
1021    pub fn new(name: &str, mesh_id: usize) -> Self {
1022        Self {
1023            name: name.to_string(),
1024            mesh_id,
1025            transform: Transform3D::default(),
1026            material: PbrMaterial::default(),
1027            ray_trace_caster: true,
1028            solid_collider: true,
1029            spin_speed: 0.0,
1030            is_dynamic: false,
1031        }
1032    }
1033
1034    /// Sets the world-space transform for the spawned object.
1035    ///
1036    /// # Arguments
1037    ///
1038    /// - `Self` - Base descriptor.
1039    /// - `Transform3D` - World-space transform.
1040    ///
1041    /// # Returns
1042    ///
1043    /// - `Self` - Updated descriptor.
1044    #[must_use]
1045    pub fn with_transform(mut self, transform: Transform3D) -> Self {
1046        self.set_transform(transform);
1047        self
1048    }
1049
1050    /// Sets the PBR surface material override for the spawned object.
1051    ///
1052    /// # Arguments
1053    ///
1054    /// - `Self` - Base descriptor.
1055    /// - `PbrMaterial` - PBR material.
1056    ///
1057    /// # Returns
1058    ///
1059    /// - `Self` - Updated descriptor.
1060    #[must_use]
1061    pub fn with_material(mut self, material: PbrMaterial) -> Self {
1062        self.set_material(material);
1063        self
1064    }
1065
1066    /// Sets whether this object casts BVH shadows and appears in reflections.
1067    ///
1068    /// # Arguments
1069    ///
1070    /// - `Self` - Base descriptor.
1071    /// - `bool` - Ray-trace caster toggle.
1072    ///
1073    /// # Returns
1074    ///
1075    /// - `Self` - Updated descriptor.
1076    #[must_use]
1077    pub fn with_ray_trace(mut self, ray_trace_caster: bool) -> Self {
1078        self.set_ray_trace_caster(ray_trace_caster);
1079        self
1080    }
1081
1082    /// Sets whether this object participates in solid vehicle and camera collision detection.
1083    ///
1084    /// # Arguments
1085    ///
1086    /// - `Self` - Base descriptor.
1087    /// - `bool` - Solid collider toggle.
1088    ///
1089    /// # Returns
1090    ///
1091    /// - `Self` - Updated descriptor.
1092    #[must_use]
1093    pub fn with_solid_collider(mut self, solid_collider: bool) -> Self {
1094        self.set_solid_collider(solid_collider);
1095        self
1096    }
1097
1098    /// Sets continuous Y-axis spin speed in radians per second.
1099    ///
1100    /// # Arguments
1101    ///
1102    /// - `Self` - Base descriptor.
1103    /// - `f32` - Spin speed in radians/sec.
1104    ///
1105    /// # Returns
1106    ///
1107    /// - `Self` - Updated descriptor.
1108    #[must_use]
1109    pub fn with_spin(mut self, spin_speed: f32) -> Self {
1110        self.set_spin_speed(spin_speed);
1111        if spin_speed.abs() > 0.001 {
1112            self.set_is_dynamic(true);
1113        }
1114        self
1115    }
1116
1117    /// Explicitly marks whether this object belongs in the incrementally refitted dynamic BVH.
1118    ///
1119    /// # Arguments
1120    ///
1121    /// - `Self` - Base descriptor.
1122    /// - `bool` - Dynamic caster flag.
1123    ///
1124    /// # Returns
1125    ///
1126    /// - `Self` - Updated descriptor.
1127    #[must_use]
1128    pub fn with_dynamic(mut self, is_dynamic: bool) -> Self {
1129        self.set_is_dynamic(is_dynamic);
1130        self
1131    }
1132}
1133
1134/// Fluent builder helpers for `ImportModelDesc`.
1135impl ImportModelDesc {
1136    /// Creates an external model import descriptor with identity transform and default PBR fallback material.
1137    ///
1138    /// # Arguments
1139    ///
1140    /// - `ModelFormat` - Interchange format (`Obj` or `GltfJson`).
1141    /// - `&str` - Raw model source text.
1142    ///
1143    /// # Returns
1144    ///
1145    /// - `Self` - Ready import descriptor.
1146    #[must_use]
1147    pub fn new(format: ModelFormat, source: &str) -> Self {
1148        Self {
1149            format,
1150            source: source.to_string(),
1151            transform: Transform3D::default(),
1152            fallback_material: PbrMaterial::default(),
1153            spin_speed: 0.0,
1154        }
1155    }
1156
1157    /// Sets the placement transform for the imported model.
1158    ///
1159    /// # Arguments
1160    ///
1161    /// - `Self` - Base descriptor.
1162    /// - `Transform3D` - Placement transform.
1163    ///
1164    /// # Returns
1165    ///
1166    /// - `Self` - Updated descriptor.
1167    #[must_use]
1168    pub fn with_transform(mut self, transform: Transform3D) -> Self {
1169        self.set_transform(transform);
1170        self
1171    }
1172
1173    /// Sets the fallback PBR material when source omits material metadata.
1174    ///
1175    /// # Arguments
1176    ///
1177    /// - `Self` - Base descriptor.
1178    /// - `PbrMaterial` - Fallback PBR material.
1179    ///
1180    /// # Returns
1181    ///
1182    /// - `Self` - Updated descriptor.
1183    #[must_use]
1184    pub fn with_material(mut self, fallback_material: PbrMaterial) -> Self {
1185        self.set_fallback_material(fallback_material);
1186        self
1187    }
1188
1189    /// Sets continuous Y-axis turntable spin speed in radians per second.
1190    ///
1191    /// # Arguments
1192    ///
1193    /// - `Self` - Base descriptor.
1194    /// - `f32` - Spin speed in radians/sec.
1195    ///
1196    /// # Returns
1197    ///
1198    /// - `Self` - Updated descriptor.
1199    #[must_use]
1200    pub fn with_spin(mut self, spin_speed: f32) -> Self {
1201        self.set_spin_speed(spin_speed);
1202        self
1203    }
1204}
1205
1206/// Dynamic Time-of-Day sun and atmospheric sky lighting for `DirectionalLight3D`.
1207impl DirectionalLight3D {
1208    /// Computes physically inspired sun direction, sun color, and sky colors for `hour` in `[0.0, 24.0]`.
1209    ///
1210    /// # Arguments
1211    ///
1212    /// - `f32` - Hour of day (`6.0` dawn, `12.0` noon, `17.5` golden sunset, `22.0` neon night).
1213    ///
1214    /// # Returns
1215    ///
1216    /// - `Self` - Updated atmospheric directional light.
1217    #[must_use]
1218    pub fn from_time_of_day(hour: f32) -> Self {
1219        let height_val: f32 = hour.rem_euclid(24.0);
1220        let elev_angle: f32 = ((height_val - 6.0) / 12.0 * PI).clamp(-0.35, 3.49);
1221        let sun_y: f32 = elev_angle.sin();
1222        let sun_x: f32 = elev_angle.cos();
1223        let dir: Vec3 = Vec3::new(-sun_x * 0.62, sun_y.max(0.22), -0.78).normalize();
1224        if (7.5..=16.5).contains(&height_val) {
1225            Self {
1226                direction: dir,
1227                color: Vec3::new(2.35, 2.18, 1.96),
1228                sky_zenith: Vec3::new(0.08, 0.24, 0.64),
1229                sky_horizon: Vec3::new(0.46, 0.66, 0.88),
1230                time_of_day: height_val,
1231            }
1232        } else if (5.5..7.5).contains(&height_val) || (16.5..19.5).contains(&height_val) {
1233            Self {
1234                direction: Vec3::new(-0.14, 0.165, -0.976).normalize(),
1235                color: Vec3::new(2.85, 1.42, 0.66),
1236                sky_zenith: Vec3::new(0.028, 0.038, 0.155),
1237                sky_horizon: Vec3::new(0.62, 0.24, 0.22),
1238                time_of_day: height_val,
1239            }
1240        } else {
1241            Self {
1242                direction: Vec3::new(-0.36, 0.56, -0.74).normalize(),
1243                color: Vec3::new(0.52, 0.68, 1.22),
1244                sky_zenith: Vec3::new(0.012, 0.022, 0.068),
1245                sky_horizon: Vec3::new(0.068, 0.115, 0.235),
1246                time_of_day: height_val,
1247            }
1248        }
1249    }
1250}
1251
1252/// Default golden-sunset directional light.
1253impl Default for DirectionalLight3D {
1254    /// Creates a golden-hour sunset sun configuration.
1255    ///
1256    /// # Returns
1257    ///
1258    /// - `Self` - Sunset `DirectionalLight3D`.
1259    fn default() -> Self {
1260        Self::from_time_of_day(17.2)
1261    }
1262}
1263
1264/// Default empty 3D open world.
1265impl Default for World3D {
1266    /// Creates an empty `World3D` with 64m chunk streaming enabled.
1267    ///
1268    /// # Returns
1269    ///
1270    /// - `Self` - Empty `World3D`.
1271    fn default() -> Self {
1272        Self {
1273            mesh_library: Vec::new(),
1274            objects: Vec::new(),
1275            camera: Camera3D::default(),
1276            sun: DirectionalLight3D::default(),
1277            bvh: Bvh3D::default(),
1278            dynamic_bvh: Bvh3D::default(),
1279            mesh_local_bvhs: Vec::new(),
1280            dynamic_instances: Vec::new(),
1281            bvh_dirty: true,
1282            dynamic_bvh_dirty: true,
1283            dynamic_topology_dirty: true,
1284            static_bvh_rebuilds: 0,
1285            dynamic_bvh_refits: 0,
1286            dynamic_bvh_rebuilds: 0,
1287            world_revision: 1,
1288            sim_tick: 0,
1289            dynamic_tris_scratch: Vec::new(),
1290            chunk_size: 64.0,
1291            player_vehicle_index: None,
1292            hero_vehicle_style: HeroVehicleStyle::AventadorV12,
1293            hero_vehicle_meshes: [None, None],
1294            imported_model_count: 0,
1295            camera_mode: 0,
1296            camera_orbit_rad: 0.4,
1297            point_lights: Vec::new(),
1298            spot_lights: Vec::new(),
1299            niagara: NiagaraSystem3D::default(),
1300            atmosphere_preset: 0,
1301            traffic_vehicles: Vec::new(),
1302            player_physics: PlayerVehiclePhysics3D::default(),
1303            world_time_secs: 0.0,
1304            scene_graph: SceneGraph3D::default(),
1305            principled_materials: Vec::new(),
1306            textures: Vec::new(),
1307            skins: Vec::new(),
1308            animation_mixer: AnimationMixer3D::default(),
1309            environment_ibl: None,
1310            area_lights: Vec::new(),
1311            scene_cameras: Vec::new(),
1312            active_scene_camera: None,
1313            node_object_map: Vec::new(),
1314            skin_scratch: SkinPaletteScratch3D::default(),
1315            deformed_meshes: Vec::new(),
1316            use_agx_tonemap: false,
1317            gpu_pass_scratch: World3dGpuPassScratch::default(),
1318            pbr_pass_scratch: World3dPbrPassScratch::default(),
1319        }
1320    }
1321}
1322
1323/// Open-world construction, model importing, BVH rebuild, and live vehicle/camera simulation for `World3D`.
1324impl World3D {
1325    /// Registers a `MeshLodChain` in the instancing library and returns its `mesh_id`.
1326    ///
1327    /// # Arguments
1328    ///
1329    /// - `&Self` - Mutable world.
1330    /// - `MeshLodChain` - Multi-level LOD mesh chain.
1331    ///
1332    /// # Returns
1333    ///
1334    /// - `usize` - Assigned `mesh_id`.
1335    pub fn register_mesh(&mut self, chain: MeshLodChain) -> usize {
1336        let id: usize = self.get_mesh_library().len();
1337        self.get_mut_mesh_library().push(chain);
1338        id
1339    }
1340
1341    /// Spawns an instanced `SceneObject3D` referencing `mesh_id` into its spatial world chunk.
1342    ///
1343    /// # Arguments
1344    ///
1345    /// - `&Self` - Mutable world.
1346    /// - `&str` - Object name.
1347    /// - `usize` - Registered `mesh_id`.
1348    /// - `Transform3D` - World transform.
1349    /// - `PbrMaterial` - Surface PBR material.
1350    /// - `bool` - Whether this object participates in BVH ray tracing.
1351    ///
1352    /// # Returns
1353    ///
1354    /// - `usize` - Index of the spawned `SceneObject3D`.
1355    pub fn spawn_object(
1356        &mut self,
1357        name: &str,
1358        mesh_id: usize,
1359        transform: Transform3D,
1360        material: PbrMaterial,
1361        ray_trace_caster: bool,
1362    ) -> usize {
1363        let local_bounds: AxisAlignedBox3D = self
1364            .get_mesh_library()
1365            .get(mesh_id)
1366            .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
1367            .map(Mesh3D::get_bounds)
1368            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
1369        let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
1370        let cs: f32 = self.get_chunk_size().max(8.0);
1371        let pos: Vec3 = transform.get_position();
1372        let chunk_coord: (i32, i32) = (
1373            (pos.get_x() / cs).floor() as i32,
1374            (pos.get_z() / cs).floor() as i32,
1375        );
1376        let idx: usize = self.get_objects().len();
1377        self.get_mut_objects().push(SceneObject3D {
1378            name: name.to_string(),
1379            mesh_id,
1380            transform,
1381            material,
1382            world_bounds,
1383            chunk_coord,
1384            ray_trace_caster,
1385            solid_collider: ray_trace_caster,
1386            spin_speed: 0.0,
1387            is_dynamic: false,
1388            teleport_epoch: 0,
1389            node_id: None,
1390            principled_material_id: None,
1391            skin_id: None,
1392        });
1393        let Self {
1394            deformed_meshes, ..
1395        } = self;
1396        deformed_meshes.push(None);
1397        if ray_trace_caster {
1398            self.set_bvh_dirty(true);
1399        }
1400        self.bump_world_revision();
1401        idx
1402    }
1403
1404    /// Increments the 3D world revision counter so 3D render caches invalidate independently of UI HUD updates.
1405    ///
1406    /// # Arguments
1407    ///
1408    /// - `&Self` - Mutable world.
1409    pub fn bump_world_revision(&mut self) {
1410        let next: u64 = self.get_world_revision().wrapping_add(1);
1411        self.set_world_revision(next);
1412    }
1413
1414    /// Marks object `obj_idx` as static or dynamic, routing its triangles between the static BVH and incrementally refitted dynamic BVH.
1415    ///
1416    /// # Arguments
1417    ///
1418    /// - `&Self` - Mutable world.
1419    /// - `usize` - Target object index in `objects`.
1420    /// - `bool` - `true` for dynamic BVH routing, `false` for static BVH routing.
1421    ///
1422    /// # Returns
1423    ///
1424    /// - `bool` - `true` when `obj_idx` existed and was updated.
1425    pub fn set_object_dynamic(&mut self, obj_idx: usize, is_dynamic: bool) -> bool {
1426        let Some(obj) = self.get_mut_objects().get_mut(obj_idx) else {
1427            return false;
1428        };
1429        if obj.get_is_dynamic() != is_dynamic {
1430            obj.set_is_dynamic(is_dynamic);
1431            if obj.get_ray_trace_caster() {
1432                self.set_bvh_dirty(true);
1433                self.set_dynamic_bvh_dirty(true);
1434                self.set_dynamic_topology_dirty(true);
1435            }
1436            self.bump_world_revision();
1437        }
1438        true
1439    }
1440
1441    /// Teleports object `obj_idx` to `transform`, incrementing `teleport_epoch` so snapshot interpolation snaps instead of sweeping.
1442    ///
1443    /// # Arguments
1444    ///
1445    /// - `&Self` - Mutable world.
1446    /// - `usize` - Target object index in `objects`.
1447    /// - `Transform3D` - Destination world transform.
1448    ///
1449    /// # Returns
1450    ///
1451    /// - `bool` - `true` when `obj_idx` existed and was teleported.
1452    pub fn teleport_object(&mut self, obj_idx: usize, transform: Transform3D) -> bool {
1453        let Some((mesh_id, ray_caster, is_dynamic)) =
1454            self.get_objects().get(obj_idx).map(|obj: &SceneObject3D| {
1455                (
1456                    obj.get_mesh_id(),
1457                    obj.get_ray_trace_caster(),
1458                    obj.get_is_dynamic(),
1459                )
1460            })
1461        else {
1462            return false;
1463        };
1464        let local_bounds: AxisAlignedBox3D = self
1465            .get_mesh_library()
1466            .get(mesh_id)
1467            .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
1468            .map(Mesh3D::get_bounds)
1469            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
1470        let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
1471        if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
1472            obj.set_transform(transform);
1473            obj.set_world_bounds(world_bounds);
1474            let next_epoch: u32 = obj.get_teleport_epoch().wrapping_add(1);
1475            obj.set_teleport_epoch(next_epoch);
1476        }
1477        if self.vehicle_index() == Some(obj_idx) {
1478            let Self { player_physics, .. } = self;
1479            let saved_charge: f32 = player_physics.get_boost_charge();
1480            *player_physics = PlayerVehiclePhysics3D::default();
1481            player_physics.set_boost_charge(saved_charge);
1482        } else {
1483            let Self {
1484                traffic_vehicles, ..
1485            } = self;
1486            for npc in traffic_vehicles.iter_mut() {
1487                if npc.get_object_index() == obj_idx {
1488                    npc.set_vel(Vec3::zero());
1489                    npc.set_yaw_rate(0.0);
1490                    npc.set_recovery_timer(0.0);
1491                    break;
1492                }
1493            }
1494        }
1495        if ray_caster {
1496            if is_dynamic {
1497                self.set_dynamic_bvh_dirty(true);
1498            } else {
1499                self.set_bvh_dirty(true);
1500            }
1501        }
1502        self.bump_world_revision();
1503        true
1504    }
1505
1506    /// Imports an external `.obj` or `.gltf` model directly into the live 3D world and returns import telemetry.
1507    ///
1508    /// # Arguments
1509    ///
1510    /// - `&Self` - Mutable world.
1511    /// - `ModelFormat` - Source model format.
1512    /// - `&str` - Raw `.obj` or `.gltf` text content.
1513    /// - `Transform3D` - Placement transform in the 3D scene.
1514    /// - `PbrMaterial` - Fallback PBR material.
1515    /// - `f32` - Optional continuous Y-spin speed in radians/sec.
1516    ///
1517    /// # Returns
1518    ///
1519    /// - `Result<ImportedModel3D, String>` - Imported model summary or parse error.
1520    pub fn import_model(
1521        &mut self,
1522        format: ModelFormat,
1523        source: &str,
1524        transform: Transform3D,
1525        fallback_material: PbrMaterial,
1526        spin_speed: f32,
1527    ) -> Result<ImportedModel3D, String> {
1528        let imported: ImportedModel3D = ModelImporter3D::import(format, source, fallback_material)?;
1529        let model_name: String = imported.get_name().clone();
1530        for (item_index, chain) in imported.get_meshes().iter().cloned().enumerate() {
1531            let mat: PbrMaterial = chain
1532                .get_levels()
1533                .first()
1534                .map(Mesh3D::get_material)
1535                .unwrap_or(fallback_material);
1536            let mid: usize = self.register_mesh(chain);
1537            let obj_idx: usize = self.spawn_object(
1538                &format!("{model_name}_{item_index}"),
1539                mid,
1540                transform,
1541                mat,
1542                true,
1543            );
1544            if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
1545                obj.set_spin_speed(spin_speed);
1546            }
1547            if spin_speed.abs() > 0.001 {
1548                let _: bool = self.set_object_dynamic(obj_idx, true);
1549            }
1550        }
1551        let next_cnt: usize = self.get_imported_model_count().saturating_add(1);
1552        self.set_imported_model_count(next_cnt);
1553        Ok(imported)
1554    }
1555
1556    /// Spawns an object from a fluent `SpawnObjectDesc`.
1557    ///
1558    /// # Arguments
1559    ///
1560    /// - `&Self` - Mutable world.
1561    /// - `&SpawnObjectDesc` - Spawn descriptor.
1562    ///
1563    /// # Returns
1564    ///
1565    /// - `usize` - Spawned object index.
1566    pub fn spawn_with(&mut self, desc: &SpawnObjectDesc) -> usize {
1567        let idx: usize = self.spawn_object(
1568            desc.get_name(),
1569            desc.get_mesh_id(),
1570            desc.get_transform(),
1571            desc.get_material(),
1572            desc.get_ray_trace_caster(),
1573        );
1574        if let Some(obj) = self.get_mut_objects().get_mut(idx) {
1575            obj.set_solid_collider(desc.get_solid_collider());
1576            obj.set_spin_speed(desc.get_spin_speed());
1577        }
1578        if desc.get_is_dynamic() || desc.get_spin_speed().abs() > 0.001 {
1579            let _: bool = self.set_object_dynamic(idx, true);
1580        }
1581        idx
1582    }
1583
1584    /// Imports an external `.obj` or `.gltf` model using a fluent `ImportModelDesc`.
1585    ///
1586    /// # Arguments
1587    ///
1588    /// - `&Self` - Mutable world.
1589    /// - `&ImportModelDesc` - Import descriptor.
1590    ///
1591    /// # Returns
1592    ///
1593    /// - `Result<ImportedModel3D, String>` - Imported model telemetry or parse error.
1594    pub fn import_with(&mut self, desc: &ImportModelDesc) -> Result<ImportedModel3D, String> {
1595        self.import_model(
1596            desc.get_format(),
1597            desc.get_source(),
1598            desc.get_transform(),
1599            desc.get_fallback_material(),
1600            desc.get_spin_speed(),
1601        )
1602    }
1603
1604    /// Returns the typed `CameraMode3D` currently active in this world.
1605    ///
1606    /// # Arguments
1607    ///
1608    /// - `&Self` - World reference.
1609    ///
1610    /// # Returns
1611    ///
1612    /// - `CameraMode3D` - Active typed camera controller mode.
1613    #[must_use]
1614    pub fn active_camera_mode(&self) -> CameraMode3D {
1615        CameraMode3D::from_u8(self.get_camera_mode())
1616    }
1617
1618    /// Sets the active 3D camera controller using a typed `CameraMode3D`.
1619    ///
1620    /// # Arguments
1621    ///
1622    /// - `&Self` - Mutable world.
1623    /// - `CameraMode3D` - Desired camera controller mode.
1624    pub fn set_camera_mode_enum(&mut self, mode: CameraMode3D) {
1625        self.set_camera_mode(mode.as_u8());
1626    }
1627
1628    /// Collects world-space triangles for all ray-trace casters matching `dynamic_filter` into `out_tris`.
1629    ///
1630    /// # Arguments
1631    ///
1632    /// - `&[SceneObject3D]` - World object slice.
1633    /// - `&[MeshLodChain]` - Registered mesh library slice.
1634    /// - `bool` - `true` to gather dynamic casters, `false` to gather static casters.
1635    /// - `&mut Vec<BvhTriangle>` - Destination triangle buffer cleared and populated in place.
1636    fn collect_caster_triangles(
1637        objects: &[SceneObject3D],
1638        mesh_library: &[MeshLodChain],
1639        dynamic_filter: bool,
1640        out_tris: &mut Vec<BvhTriangle>,
1641    ) {
1642        out_tris.clear();
1643        for obj in objects.iter() {
1644            if !obj.get_ray_trace_caster() || obj.get_is_dynamic() != dynamic_filter {
1645                continue;
1646            }
1647            let Some(chain) = mesh_library.get(obj.get_mesh_id()) else {
1648                continue;
1649            };
1650            let Some(mesh) = chain.get_levels().first() else {
1651                continue;
1652            };
1653            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1654            let model_m: Mat4 = obj.get_transform().to_mat4();
1655            let mat: PbrMaterial = obj.get_material();
1656            for (tri_idx, tri) in mesh.get_indices().iter().enumerate() {
1657                let (i0, i1, i2): (usize, usize, usize) =
1658                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1659                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1660                    let p0: Vec3 = model_m.mul_point3(verts[i0].get_position());
1661                    let p1: Vec3 = model_m.mul_point3(verts[i1].get_position());
1662                    let p2: Vec3 = model_m.mul_point3(verts[i2].get_position());
1663                    let (tri_mat, mat_slot): (PbrMaterial, u16) =
1664                        mesh.resolve_triangle_material(tri_idx, mat);
1665                    out_tris.push(BvhTriangle::from_points_with_slot(
1666                        p0, p1, p2, tri_mat, mat_slot,
1667                    ));
1668                }
1669            }
1670        }
1671    }
1672
1673    /// Synchronizes the split static and dynamic BVH acceleration structures, refitting moving dynamic casters in O(N) without rebuilding static world geometry.
1674    ///
1675    /// # Arguments
1676    ///
1677    /// - `&Self` - Mutable world.
1678    pub fn ensure_bvh(&mut self) {
1679        if self.get_bvh_dirty() {
1680            let mut static_tris: Vec<BvhTriangle> = Vec::new();
1681            Self::collect_caster_triangles(
1682                self.get_objects().as_slice(),
1683                self.get_mesh_library().as_slice(),
1684                false,
1685                &mut static_tris,
1686            );
1687            self.set_bvh(Bvh3D::build(static_tris));
1688            self.set_bvh_dirty(false);
1689            let next_static: u64 = self.get_static_bvh_rebuilds().saturating_add(1);
1690            self.set_static_bvh_rebuilds(next_static);
1691        }
1692        if self.get_dynamic_bvh_dirty() {
1693            let topology_dirty: bool = self.get_dynamic_topology_dirty();
1694            let Self {
1695                objects,
1696                mesh_library,
1697                dynamic_bvh,
1698                dynamic_tris_scratch,
1699                dynamic_bvh_dirty,
1700                dynamic_topology_dirty,
1701                dynamic_bvh_refits,
1702                dynamic_bvh_rebuilds,
1703                ..
1704            } = self;
1705            Self::collect_caster_triangles(
1706                objects.as_slice(),
1707                mesh_library.as_slice(),
1708                true,
1709                dynamic_tris_scratch,
1710            );
1711            if dynamic_tris_scratch.is_empty() {
1712                dynamic_bvh.rebuild_in_place(&[]);
1713            } else if !topology_dirty
1714                && dynamic_bvh.refit_from_source(dynamic_tris_scratch.as_slice())
1715            {
1716                let check_degraded: bool = ((*dynamic_bvh_refits + 1) & 15) == 0;
1717                if check_degraded && dynamic_bvh.needs_rebuild_after_refit(3.5) {
1718                    dynamic_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
1719                    *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
1720                } else {
1721                    *dynamic_bvh_refits = dynamic_bvh_refits.saturating_add(1);
1722                }
1723            } else {
1724                dynamic_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
1725                *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
1726            }
1727            *dynamic_bvh_dirty = false;
1728            *dynamic_topology_dirty = false;
1729        }
1730        self.sync_dynamic_ray_instances();
1731    }
1732
1733    /// Lazily constructs local-space BVH4/BVH8 trees for dynamic meshes and updates `dynamic_instances` from current object transforms with zero BVH rebuilds.
1734    ///
1735    /// # Arguments
1736    ///
1737    /// - `&Self` - Mutable world reference.
1738    pub fn sync_dynamic_ray_instances(&mut self) {
1739        let Self {
1740            mesh_library,
1741            objects,
1742            mesh_local_bvhs,
1743            dynamic_instances,
1744            ..
1745        } = self;
1746        if mesh_local_bvhs.len() < mesh_library.len() {
1747            mesh_local_bvhs.resize_with(mesh_library.len(), || None);
1748        }
1749        dynamic_instances.clear();
1750        for (obj_idx, obj) in objects.iter().enumerate() {
1751            if !obj.get_ray_trace_caster() || !obj.get_is_dynamic() {
1752                continue;
1753            }
1754            let mesh_id: usize = obj.get_mesh_id();
1755            let Some(chain) = mesh_library.get(mesh_id) else {
1756                continue;
1757            };
1758            let Some(mesh) = chain.get_levels().first() else {
1759                continue;
1760            };
1761            if mesh_local_bvhs[mesh_id].is_none() {
1762                let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1763                let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
1764                let mut local_tris: Vec<BvhTriangle> = Vec::with_capacity(indices.len());
1765                let neutral: PbrMaterial = PbrMaterial::default();
1766                for (tri_idx, tri) in indices.iter().enumerate() {
1767                    let (i0, i1, i2): (usize, usize, usize) =
1768                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1769                    if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1770                        let (tri_mat, mat_slot): (PbrMaterial, u16) =
1771                            mesh.resolve_triangle_material(tri_idx, neutral);
1772                        local_tris.push(BvhTriangle::from_points_with_slot(
1773                            verts[i0].get_position(),
1774                            verts[i1].get_position(),
1775                            verts[i2].get_position(),
1776                            tri_mat,
1777                            mat_slot,
1778                        ));
1779                    }
1780                }
1781                mesh_local_bvhs[mesh_id] = Some(Bvh3D::build(local_tris));
1782            }
1783            let transform_val: Transform3D = obj.get_transform();
1784            dynamic_instances.push(DynamicRayInstance {
1785                obj_idx,
1786                mesh_id,
1787                world_bounds: obj.get_world_bounds(),
1788                inv_model: transform_val.to_inv_mat4(),
1789                normal_basis: transform_val.normal_mat3(),
1790                material: obj.get_material(),
1791            });
1792        }
1793    }
1794
1795    /// Updates only the inverse-model transform, normal basis, and world axis-aligned bounding box of an existing dynamic instance without rebuilding any BVH.
1796    ///
1797    /// # Arguments
1798    ///
1799    /// - `&Self` - Mutable world reference.
1800    /// - `usize` - Scene object index.
1801    /// - `Transform3D` - Interpolated world transform.
1802    /// - `AxisAlignedBox3D` - Interpolated world axis-aligned bounding box.
1803    pub(crate) fn override_dynamic_instance_pose(
1804        &mut self,
1805        obj_idx: usize,
1806        transform: Transform3D,
1807        world_bounds: AxisAlignedBox3D,
1808    ) {
1809        let Self {
1810            dynamic_instances, ..
1811        } = self;
1812        for inst in dynamic_instances.iter_mut() {
1813            if inst.obj_idx == obj_idx {
1814                inst.world_bounds = world_bounds;
1815                inst.inv_model = transform.to_inv_mat4();
1816                inst.normal_basis = transform.normal_mat3();
1817                return;
1818            }
1819        }
1820    }
1821
1822    /// Traces a shadow ray against object-space dynamic instances via inverse interpolated `Mat4` with zero dynamic BVH rebuilds.
1823    ///
1824    /// # Arguments
1825    ///
1826    /// - `&[DynamicRayInstance]` - Active dynamic raytracing instances.
1827    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1828    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1829    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1830    /// - `&mut u32` - Per-thread local occluder triangle hint.
1831    ///
1832    /// # Returns
1833    ///
1834    /// - `bool` - `true` if occluded by any dynamic object at its current or interpolated pose.
1835    #[inline(always)]
1836    #[must_use]
1837    pub(crate) fn trace_any_shadow_dynamic_instances(
1838        instances: &[DynamicRayInstance],
1839        local_bvhs: &[Option<Bvh3D>],
1840        ray: (Vec3, Vec3, Vec3),
1841        bounds: (f32, f32),
1842        dyn_cache: &mut u32,
1843    ) -> bool {
1844        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1845        let (t_min, t_max): (f32, f32) = bounds;
1846        for inst in instances.iter() {
1847            if !inst
1848                .world_bounds
1849                .intersect_ray_near(origin, inv_dir, t_min, t_max)
1850                .is_finite()
1851            {
1852                continue;
1853            }
1854            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1855                continue;
1856            };
1857            let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
1858            let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
1859            let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
1860            if local_bvh
1861                .trace_any_shadow_cached(local_orig, local_dir, local_inv, t_min, t_max, dyn_cache)
1862            {
1863                return true;
1864            }
1865        }
1866        false
1867    }
1868
1869    /// Traces a coherent 4-ray shadow packet against static BVH and object-space inverse-interpolated dynamic instances.
1870    ///
1871    /// # Arguments
1872    ///
1873    /// - `&Bvh3D` - Static world BVH4/BVH8.
1874    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1875    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1876    /// - `&RayPacket4` - Coherent 4-ray shadow packet.
1877    /// - `u8` - 4-bit mask of active rays to trace.
1878    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1879    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder hints.
1880    ///
1881    /// # Returns
1882    ///
1883    /// - `u8` - 4-bit mask of occluded rays.
1884    #[inline(always)]
1885    #[must_use]
1886    pub(crate) fn trace_any_shadow_packet4_with_instances(
1887        static_bvh: &Bvh3D,
1888        instances: &[DynamicRayInstance],
1889        local_bvhs: &[Option<Bvh3D>],
1890        pkt: &RayPacket4,
1891        active_mask: u8,
1892        bounds: (f32, f32),
1893        caches: (&mut u32, &mut u32),
1894    ) -> u8 {
1895        let (t_min, t_max): (f32, f32) = bounds;
1896        let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
1897        let mut occluded: u8 =
1898            static_bvh.trace_any_shadow_packet4(pkt, active_mask, t_min, t_max, static_cache);
1899        let mut rem: u8 = active_mask & !occluded;
1900        if rem == 0 || instances.is_empty() {
1901            return occluded;
1902        }
1903        for inst in instances.iter() {
1904            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1905                continue;
1906            };
1907            let mut hit_box_mask: u8 = 0;
1908            let mut check: u8 = rem;
1909            while check != 0 {
1910                let red_val: usize = check.trailing_zeros() as usize;
1911                check &= check - 1;
1912                let orig_r: Vec3 = Vec3::new(pkt.ox[red_val], pkt.oy[red_val], pkt.oz[red_val]);
1913                let inv_r: Vec3 = Vec3::new(pkt.ix[red_val], pkt.iy[red_val], pkt.iz[red_val]);
1914                if inst
1915                    .world_bounds
1916                    .intersect_ray_near(orig_r, inv_r, t_min, t_max)
1917                    .is_finite()
1918                {
1919                    hit_box_mask |= 1_u8 << red_val;
1920                }
1921            }
1922            if hit_box_mask == 0 {
1923                continue;
1924            }
1925            let mut local_pkt: RayPacket4 = *pkt;
1926            let mut tr_mask: u8 = hit_box_mask;
1927            while tr_mask != 0 {
1928                let radius_val: usize = tr_mask.trailing_zeros() as usize;
1929                tr_mask &= tr_mask - 1;
1930                let lo: Vec3 = inst.inv_model.mul_point3(Vec3::new(
1931                    pkt.ox[radius_val],
1932                    pkt.oy[radius_val],
1933                    pkt.oz[radius_val],
1934                ));
1935                let ld: Vec3 = inst.inv_model.mul_vec3(Vec3::new(
1936                    pkt.dx[radius_val],
1937                    pkt.dy[radius_val],
1938                    pkt.dz[radius_val],
1939                ));
1940                let li: Vec3 = Ray3D::safe_inv_vec(ld);
1941                local_pkt.ox[radius_val] = lo.get_x();
1942                local_pkt.oy[radius_val] = lo.get_y();
1943                local_pkt.oz[radius_val] = lo.get_z();
1944                local_pkt.dx[radius_val] = ld.get_x();
1945                local_pkt.dy[radius_val] = ld.get_y();
1946                local_pkt.dz[radius_val] = ld.get_z();
1947                local_pkt.ix[radius_val] = li.get_x();
1948                local_pkt.iy[radius_val] = li.get_y();
1949                local_pkt.iz[radius_val] = li.get_z();
1950            }
1951            let dyn_occ: u8 = local_bvh.trace_any_shadow_packet4(
1952                &local_pkt,
1953                hit_box_mask,
1954                t_min,
1955                t_max,
1956                dyn_cache,
1957            );
1958            occluded |= dyn_occ;
1959            rem &= !dyn_occ;
1960            if rem == 0 {
1961                break;
1962            }
1963        }
1964        occluded
1965    }
1966
1967    /// Traces a shadow/occlusion ray across static BVH and object-space inverse-interpolated dynamic instances.
1968    ///
1969    /// # Arguments
1970    ///
1971    /// - `&Bvh3D` - Static world BVH.
1972    /// - `&[DynamicRayInstance]` - Active dynamic raytracing instances.
1973    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1974    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1975    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1976    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder hints.
1977    ///
1978    /// # Returns
1979    ///
1980    /// - `bool` - `true` when occluded by static or dynamic geometry.
1981    #[inline(always)]
1982    #[must_use]
1983    pub(crate) fn trace_any_shadow_with_instances(
1984        static_bvh: &Bvh3D,
1985        instances: &[DynamicRayInstance],
1986        local_bvhs: &[Option<Bvh3D>],
1987        ray: (Vec3, Vec3, Vec3),
1988        bounds: (f32, f32),
1989        caches: (&mut u32, &mut u32),
1990    ) -> bool {
1991        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1992        let (t_min, t_max): (f32, f32) = bounds;
1993        let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
1994        if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
1995            return true;
1996        }
1997        if !instances.is_empty() {
1998            return Self::trace_any_shadow_dynamic_instances(
1999                instances, local_bvhs, ray, bounds, dyn_cache,
2000            );
2001        }
2002        false
2003    }
2004
2005    /// Traces a reflection/GI ray across static BVH and object-space inverse-interpolated dynamic instances, returning `(distance, world_normal, material)`.
2006    ///
2007    /// # Arguments
2008    ///
2009    /// - `&Bvh3D` - Static world BVH.
2010    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
2011    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
2012    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
2013    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
2014    ///
2015    /// # Returns
2016    ///
2017    /// - `Option<(f32, Vec3, PbrMaterial)>` - Closest hit distance, world-space unit normal, and PBR material.
2018    #[inline(always)]
2019    #[must_use]
2020    pub(crate) fn trace_closest_with_instances(
2021        static_bvh: &Bvh3D,
2022        instances: &[DynamicRayInstance],
2023        local_bvhs: &[Option<Bvh3D>],
2024        ray: (Vec3, Vec3, Vec3),
2025        bounds: (f32, f32),
2026    ) -> Option<(f32, Vec3, PbrMaterial)> {
2027        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2028        let (t_min, t_max): (f32, f32) = bounds;
2029        let mut best_t: f32 = t_max;
2030        let mut best_hit: Option<(f32, Vec3, PbrMaterial)> = static_bvh
2031            .trace_closest_raw(origin, dir, inv_dir, t_min, t_max)
2032            .map(|(node_style, si): (f32, usize)| {
2033                let tri: &BvhTriangle = &static_bvh.get_triangles()[si];
2034                best_t = node_style;
2035                (node_style, tri.get_normal(), tri.get_material())
2036            });
2037        for inst in instances.iter() {
2038            if !inst
2039                .world_bounds
2040                .intersect_ray_near(origin, inv_dir, t_min, best_t)
2041                .is_finite()
2042            {
2043                continue;
2044            }
2045            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
2046                continue;
2047            };
2048            let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
2049            let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
2050            let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
2051            if let Some((dt, di)) =
2052                local_bvh.trace_closest_raw(local_orig, local_dir, local_inv, t_min, best_t)
2053            {
2054                best_t = dt;
2055                let hit_tri: &BvhTriangle = &local_bvh.get_triangles()[di];
2056                let local_n: Vec3 = hit_tri.get_normal();
2057                let world_n: Vec3 = Mat4::transform_normal_with_basis(local_n, inst.normal_basis);
2058                let hit_mat: PbrMaterial = if hit_tri.get_material_slot() == 0 {
2059                    inst.material
2060                } else {
2061                    hit_tri.get_material()
2062                };
2063                best_hit = Some((dt, world_n, hit_mat));
2064            }
2065        }
2066        best_hit
2067    }
2068
2069    /// Traces a coherent 4-ray closest-hit packet across static BVH and object-space inverse-interpolated dynamic instances.
2070    ///
2071    /// # Arguments
2072    ///
2073    /// - `&Bvh3D` - Static world BVH4/BVH8.
2074    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
2075    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
2076    /// - `&RayPacket4` - Coherent 4-ray reflection or GI packet.
2077    /// - `u8` - 4-bit mask of active rays.
2078    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
2079    ///
2080    /// # Returns
2081    ///
2082    /// - `[Option<(f32, Vec3, PbrMaterial)>; 4]` - Closest hit distance, world normal, and material per lane.
2083    #[inline(always)]
2084    #[must_use]
2085    pub(crate) fn trace_closest_packet4_with_instances(
2086        static_bvh: &Bvh3D,
2087        instances: &[DynamicRayInstance],
2088        local_bvhs: &[Option<Bvh3D>],
2089        pkt: &RayPacket4,
2090        active_mask: u8,
2091        bounds: (f32, f32),
2092    ) -> [Option<(f32, Vec3, PbrMaterial)>; 4] {
2093        let (t_min, t_max): (f32, f32) = bounds;
2094        let mut best_t: [f32; 4] = [t_max; 4];
2095        let mut best_static_idx: [usize; 4] = [usize::MAX; 4];
2096        static_bvh.trace_closest_packet4(
2097            pkt,
2098            active_mask,
2099            t_min,
2100            &mut best_t,
2101            &mut best_static_idx,
2102        );
2103        let static_tris: &[BvhTriangle] = static_bvh.get_triangles().as_slice();
2104        let mut out: [Option<(f32, Vec3, PbrMaterial)>; 4] = [None; 4];
2105        let mut matrix_elems: u8 = active_mask;
2106        while matrix_elems != 0 {
2107            let red_val: usize = matrix_elems.trailing_zeros() as usize;
2108            matrix_elems &= matrix_elems - 1;
2109            let sidx: usize = best_static_idx[red_val];
2110            if sidx != usize::MAX {
2111                let tri: &BvhTriangle = &static_tris[sidx];
2112                out[red_val] = Some((best_t[red_val], tri.get_normal(), tri.get_material()));
2113            }
2114        }
2115        for inst in instances.iter() {
2116            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
2117                continue;
2118            };
2119            let mut hit_box_mask: u8 = 0;
2120            let mut check: u8 = active_mask;
2121            while check != 0 {
2122                let radius_val: usize = check.trailing_zeros() as usize;
2123                check &= check - 1;
2124                if inst
2125                    .world_bounds
2126                    .intersect_ray_near(
2127                        Vec3::new(pkt.ox[radius_val], pkt.oy[radius_val], pkt.oz[radius_val]),
2128                        Vec3::new(pkt.ix[radius_val], pkt.iy[radius_val], pkt.iz[radius_val]),
2129                        t_min,
2130                        best_t[radius_val],
2131                    )
2132                    .is_finite()
2133                {
2134                    hit_box_mask |= 1_u8 << radius_val;
2135                }
2136            }
2137            if hit_box_mask == 0 {
2138                continue;
2139            }
2140            let mut local_pkt: RayPacket4 = *pkt;
2141            let mut tr_mask: u8 = hit_box_mask;
2142            while tr_mask != 0 {
2143                let rect_val: usize = tr_mask.trailing_zeros() as usize;
2144                tr_mask &= tr_mask - 1;
2145                let lo: Vec3 = inst.inv_model.mul_point3(Vec3::new(
2146                    pkt.ox[rect_val],
2147                    pkt.oy[rect_val],
2148                    pkt.oz[rect_val],
2149                ));
2150                let ld: Vec3 = inst.inv_model.mul_vec3(Vec3::new(
2151                    pkt.dx[rect_val],
2152                    pkt.dy[rect_val],
2153                    pkt.dz[rect_val],
2154                ));
2155                let li: Vec3 = Ray3D::safe_inv_vec(ld);
2156                local_pkt.ox[rect_val] = lo.get_x();
2157                local_pkt.oy[rect_val] = lo.get_y();
2158                local_pkt.oz[rect_val] = lo.get_z();
2159                local_pkt.dx[rect_val] = ld.get_x();
2160                local_pkt.dy[rect_val] = ld.get_y();
2161                local_pkt.dz[rect_val] = ld.get_z();
2162                local_pkt.ix[rect_val] = li.get_x();
2163                local_pkt.iy[rect_val] = li.get_y();
2164                local_pkt.iz[rect_val] = li.get_z();
2165            }
2166            let mut dyn_idx: [usize; 4] = [usize::MAX; 4];
2167            local_bvh.trace_closest_packet4(
2168                &local_pkt,
2169                hit_box_mask,
2170                t_min,
2171                &mut best_t,
2172                &mut dyn_idx,
2173            );
2174            let local_tris: &[BvhTriangle] = local_bvh.get_triangles().as_slice();
2175            let mut upd: u8 = hit_box_mask;
2176            while upd != 0 {
2177                let row_val: usize = upd.trailing_zeros() as usize;
2178                upd &= upd - 1;
2179                let di: usize = dyn_idx[row_val];
2180                if di != usize::MAX {
2181                    let hit_tri: &BvhTriangle = &local_tris[di];
2182                    let wn: Vec3 =
2183                        Mat4::transform_normal_with_basis(hit_tri.get_normal(), inst.normal_basis);
2184                    let hit_mat: PbrMaterial = if hit_tri.get_material_slot() == 0 {
2185                        inst.material
2186                    } else {
2187                        hit_tri.get_material()
2188                    };
2189                    out[row_val] = Some((best_t[row_val], wn, hit_mat));
2190                }
2191            }
2192        }
2193        out
2194    }
2195
2196    /// Traces a shadow ray using static BVH plus object-space inverse-interpolated dynamic instances.
2197    ///
2198    /// # Arguments
2199    ///
2200    /// - `&Self` - World reference.
2201    /// - `&Ray3D` - World-space shadow ray.
2202    /// - `f32` - Minimum hit distance.
2203    /// - `f32` - Maximum hit distance.
2204    ///
2205    /// # Returns
2206    ///
2207    /// - `bool` - `true` when occluded by static or dynamic geometry at its current/interpolated pose.
2208    #[must_use]
2209    pub fn trace_any_shadow_object_space(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
2210        let Self {
2211            bvh,
2212            dynamic_instances,
2213            mesh_local_bvhs,
2214            ..
2215        } = self;
2216        let mut scale_factor: u32 = u32::MAX;
2217        let mut dc: u32 = u32::MAX;
2218        Self::trace_any_shadow_with_instances(
2219            bvh,
2220            dynamic_instances.as_slice(),
2221            mesh_local_bvhs.as_slice(),
2222            (
2223                ray.get_origin(),
2224                ray.get_direction(),
2225                ray.get_inv_direction(),
2226            ),
2227            (t_min, t_max),
2228            (&mut scale_factor, &mut dc),
2229        )
2230    }
2231
2232    /// Traces a coherent 4-ray closest-hit packet against both the static BVH4 and object-space inverse-interpolated dynamic instances.
2233    ///
2234    /// # Arguments
2235    ///
2236    /// - `&Self` - World reference.
2237    /// - `&RayPacket4` - Coherent 4-ray query packet.
2238    /// - `u8` - 4-bit mask of active rays (`0..=15`).
2239    /// - `f32` - Minimum hit distance.
2240    /// - `f32` - Maximum hit distance.
2241    ///
2242    /// # Returns
2243    ///
2244    /// - `[Option<RayHit3D>; 4]` - Closest hit surface with world normal and material per active lane.
2245    #[must_use]
2246    pub fn trace_closest_packet4(
2247        &self,
2248        pkt: &RayPacket4,
2249        active_mask: u8,
2250        t_min: f32,
2251        t_max: f32,
2252    ) -> [Option<RayHit3D>; 4] {
2253        let Self {
2254            bvh,
2255            dynamic_instances,
2256            mesh_local_bvhs,
2257            ..
2258        } = self;
2259        let raw: [Option<(f32, Vec3, PbrMaterial)>; 4] = Self::trace_closest_packet4_with_instances(
2260            bvh,
2261            dynamic_instances.as_slice(),
2262            mesh_local_bvhs.as_slice(),
2263            pkt,
2264            active_mask,
2265            (t_min, t_max),
2266        );
2267        let mut out: [Option<RayHit3D>; 4] = [None; 4];
2268        for lane in 0..4 {
2269            if let Some((blend_factor, normal, material)) = raw[lane] {
2270                let point: Vec3 = Vec3::new(
2271                    pkt.ox[lane] + pkt.dx[lane] * blend_factor,
2272                    pkt.oy[lane] + pkt.dy[lane] * blend_factor,
2273                    pkt.oz[lane] + pkt.dz[lane] * blend_factor,
2274                );
2275                out[lane] = Some(RayHit3D {
2276                    distance: blend_factor,
2277                    point,
2278                    normal,
2279                    material,
2280                });
2281            }
2282        }
2283        out
2284    }
2285
2286    /// Traces a closest-hit ray using static BVH plus object-space inverse-interpolated dynamic instances.
2287    ///
2288    /// # Arguments
2289    ///
2290    /// - `&Self` - World reference.
2291    /// - `&Ray3D` - World-space query ray.
2292    /// - `f32` - Minimum hit distance.
2293    /// - `f32` - Maximum hit distance.
2294    ///
2295    /// # Returns
2296    ///
2297    /// - `Option<RayHit3D>` - Closest hit surface with world-space normal and material.
2298    #[must_use]
2299    pub fn trace_closest_object_space(
2300        &self,
2301        ray: &Ray3D,
2302        t_min: f32,
2303        t_max: f32,
2304    ) -> Option<RayHit3D> {
2305        let Self {
2306            bvh,
2307            dynamic_instances,
2308            mesh_local_bvhs,
2309            ..
2310        } = self;
2311        let (blend_factor, normal, material): (f32, Vec3, PbrMaterial) =
2312            Self::trace_closest_with_instances(
2313                bvh,
2314                dynamic_instances.as_slice(),
2315                mesh_local_bvhs.as_slice(),
2316                (
2317                    ray.get_origin(),
2318                    ray.get_direction(),
2319                    ray.get_inv_direction(),
2320                ),
2321                (t_min, t_max),
2322            )?;
2323        Some(RayHit3D {
2324            distance: blend_factor,
2325            point: ray
2326                .get_origin()
2327                .add(ray.get_direction().scale(blend_factor)),
2328            normal,
2329            material,
2330        })
2331    }
2332
2333    /// Returns the combined node count across both static and dynamic BVH acceleration trees.
2334    ///
2335    /// # Arguments
2336    ///
2337    /// - `&Self` - World reference.
2338    ///
2339    /// # Returns
2340    ///
2341    /// - `usize` - Total active BVH nodes.
2342    #[must_use]
2343    pub fn total_bvh_nodes(&self) -> usize {
2344        self.get_bvh()
2345            .get_nodes()
2346            .len()
2347            .saturating_add(self.get_dynamic_bvh().get_nodes().len())
2348    }
2349
2350    /// Traces a shadow/occlusion ray across both static and dynamic BVHs using 1-triangle occluder caches.
2351    ///
2352    /// # Arguments
2353    ///
2354    /// - `(&Bvh3D, &Bvh3D)` - `(static_bvh, dynamic_bvh)` pair.
2355    /// - `(Vec3, Vec3, Vec3)` - `(origin, dir, inv_dir)` ray triple.
2356    /// - `(f32, f32)` - `(t_min, t_max)` distance bounds.
2357    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder triangle hints.
2358    ///
2359    /// # Returns
2360    ///
2361    /// - `bool` - `true` if occluded by either static or dynamic geometry.
2362    #[must_use]
2363    pub fn trace_any_shadow_split(
2364        bvhs: (&Bvh3D, &Bvh3D),
2365        ray: (Vec3, Vec3, Vec3),
2366        bounds: (f32, f32),
2367        caches: (&mut u32, &mut u32),
2368    ) -> bool {
2369        let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
2370        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2371        let (t_min, t_max): (f32, f32) = bounds;
2372        let (static_cache, dynamic_cache): (&mut u32, &mut u32) = caches;
2373        if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
2374            return true;
2375        }
2376        if !dynamic_bvh.is_empty() {
2377            return dynamic_bvh.trace_any_shadow_cached(
2378                origin,
2379                dir,
2380                inv_dir,
2381                t_min,
2382                t_max,
2383                dynamic_cache,
2384            );
2385        }
2386        false
2387    }
2388
2389    /// Traces a reflection/GI ray across both static and dynamic BVHs and returns `(distance, is_dynamic, tri_index)`.
2390    ///
2391    /// # Arguments
2392    ///
2393    /// - `(&Bvh3D, &Bvh3D)` - `(static_bvh, dynamic_bvh)` pair.
2394    /// - `(Vec3, Vec3, Vec3)` - `(origin, dir, inv_dir)` ray triple.
2395    /// - `(f32, f32)` - `(t_min, t_max)` distance bounds.
2396    ///
2397    /// # Returns
2398    ///
2399    /// - `Option<(f32, bool, usize)>` - Closest `(t, hit_in_dynamic_bvh, triangle_index)`.
2400    #[must_use]
2401    pub fn trace_closest_split(
2402        bvhs: (&Bvh3D, &Bvh3D),
2403        ray: (Vec3, Vec3, Vec3),
2404        bounds: (f32, f32),
2405    ) -> Option<(f32, bool, usize)> {
2406        let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
2407        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2408        let (t_min, t_max): (f32, f32) = bounds;
2409        let static_hit: Option<(f32, usize)> =
2410            static_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, t_max);
2411        let dyn_limit: f32 =
2412            static_hit.map_or(t_max, |(blend_factor, _): (f32, usize)| blend_factor);
2413        let dynamic_hit: Option<(f32, usize)> = if !dynamic_bvh.is_empty() {
2414            dynamic_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, dyn_limit)
2415        } else {
2416            None
2417        };
2418        match (static_hit, dynamic_hit) {
2419            (_, Some((dt, di))) => Some((dt, true, di)),
2420            (Some((node_style, si)), None) => Some((node_style, false, si)),
2421            (None, None) => None,
2422        }
2423    }
2424
2425    /// Returns the optional player vehicle index.
2426    ///
2427    /// # Arguments
2428    ///
2429    /// - `&Self` - World reference.
2430    ///
2431    /// # Returns
2432    ///
2433    /// - `Option<usize>` - Vehicle index in `objects`.
2434    #[must_use]
2435    pub fn vehicle_index(&self) -> Option<usize> {
2436        let Self {
2437            player_vehicle_index,
2438            ..
2439        } = self;
2440        *player_vehicle_index
2441    }
2442
2443    /// Evaluates the closed-loop coastal circuit spine distance `d_spine` and signed lateral offset `road_u = d_spine - CITY_LOOP_RADIUS` for any horizontal world coordinate `(world_x, world_z)`.
2444    ///
2445    /// # Arguments
2446    ///
2447    /// - `f32` - World-space X coordinate in meters.
2448    /// - `f32` - World-space Z coordinate in meters.
2449    ///
2450    /// # Returns
2451    ///
2452    /// - `(f32, f32)` - `(d_spine, road_u)` in meters matching the GPU road/puddle/coastal-bay shader contract.
2453    #[must_use]
2454    pub fn loop_lateral_offset(world_x: f32, world_z: f32) -> (f32, f32) {
2455        let spine_z: f32 = world_z.clamp(-CITY_LOOP_STRAIGHT_HALF_Z, CITY_LOOP_STRAIGHT_HALF_Z);
2456        let dx: f32 = world_x - CITY_LOOP_CENTER_X;
2457        let dz: f32 = world_z - spine_z;
2458        let d_spine: f32 = dx.hypot(dz);
2459        (d_spine, d_spine - CITY_LOOP_RADIUS)
2460    }
2461
2462    /// Evaluates the world-space position and clockwise tangent yaw in radians along the 962m closed-loop stadium circuit at continuous arc-length `arc_s` and signed lateral lane offset `lateral_u`.
2463    ///
2464    /// # Arguments
2465    ///
2466    /// - `f32` - Continuous arc-length along the loop centerline in meters (wrapped modulo `CITY_LOOP_TOTAL_LENGTH`).
2467    /// - `f32` - Signed lateral offset from centerline in meters (`+` outward, `-` inward toward Inner Landmark Island).
2468    ///
2469    /// # Returns
2470    ///
2471    /// - `(Vec3, f32)` - `(world_position, clockwise_yaw_rad)` where car forward is `(-sin(yaw), 0, -cos(yaw))`.
2472    #[must_use]
2473    pub fn loop_pose_at(arc_s: f32, lateral_u: f32) -> (Vec3, f32) {
2474        let straight_len: f32 = 2.0 * CITY_LOOP_STRAIGHT_HALF_Z;
2475        let arc_len: f32 = PI * CITY_LOOP_RADIUS;
2476        let s: f32 = arc_s.rem_euclid(CITY_LOOP_TOTAL_LENGTH);
2477        if s < straight_len {
2478            let world_x: f32 = -lateral_u;
2479            let world_z: f32 = CITY_LOOP_STRAIGHT_HALF_Z - s;
2480            (Vec3::new(world_x, 0.0, world_z), 0.0)
2481        } else if s < straight_len + arc_len {
2482            let alpha: f32 = (s - straight_len) / CITY_LOOP_RADIUS;
2483            let radius: f32 = CITY_LOOP_RADIUS + lateral_u;
2484            let (sin_a, cos_a): (f32, f32) = alpha.sin_cos();
2485            let world_x: f32 = CITY_LOOP_CENTER_X - radius * cos_a;
2486            let world_z: f32 = -CITY_LOOP_STRAIGHT_HALF_Z - radius * sin_a;
2487            (Vec3::new(world_x, 0.0, world_z), -alpha)
2488        } else if s < 2.0 * straight_len + arc_len {
2489            let east_s: f32 = s - (straight_len + arc_len);
2490            let world_x: f32 = CITY_LOOP_CENTER_X * 2.0 + lateral_u;
2491            let world_z: f32 = -CITY_LOOP_STRAIGHT_HALF_Z + east_s;
2492            (Vec3::new(world_x, 0.0, world_z), PI)
2493        } else {
2494            let beta: f32 = (s - (2.0 * straight_len + arc_len)) / CITY_LOOP_RADIUS;
2495            let radius: f32 = CITY_LOOP_RADIUS + lateral_u;
2496            let (sin_b, cos_b): (f32, f32) = beta.sin_cos();
2497            let world_x: f32 = CITY_LOOP_CENTER_X + radius * cos_b;
2498            let world_z: f32 = CITY_LOOP_STRAIGHT_HALF_Z + radius * sin_b;
2499            (Vec3::new(world_x, 0.0, world_z), PI - beta)
2500        }
2501    }
2502
2503    /// Returns the curated six-palette architectural facade PBR material library used across the metropolitan skyline.
2504    ///
2505    /// # Returns
2506    ///
2507    /// - `[PbrMaterial; 6]` - Six distinct architectural facade palettes with `SurfaceDetailMode::ArchitecturalFacade`.
2508    #[must_use]
2509    fn curated_skyline_palettes() -> [PbrMaterial; 6] {
2510        [
2511            PbrMaterial::pbr(Color::hex(0x9E8C73), 0.24, 0.36, 0.38)
2512                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2513            PbrMaterial::pbr(Color::hex(0x163C6B), 0.78, 0.12, 0.76)
2514                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2515            PbrMaterial::pbr(Color::hex(0x141D2D), 0.86, 0.10, 0.82)
2516                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2517            PbrMaterial::pbr(Color::hex(0x7B4232), 0.20, 0.42, 0.32)
2518                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2519            PbrMaterial::pbr(Color::hex(0x0E4B47), 0.74, 0.14, 0.72)
2520                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2521            PbrMaterial::pbr(Color::hex(0x64748B), 0.82, 0.18, 0.70)
2522                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2523        ]
2524    }
2525
2526    /// Registers all six distinct sculpted architectural building archetype meshes in `World3D::mesh_library`.
2527    ///
2528    /// # Returns
2529    ///
2530    /// - `[usize; 6]` - Registered mesh indices `[art_deco, chamfered, twisted, cantilever, cylinder, boutique]`.
2531    fn register_building_archetypes(&mut self) -> [usize; 6] {
2532        let base_mat: PbrMaterial = PbrMaterial::default();
2533        let art_deco: usize = self.register_mesh(MeshLodChain::from_mesh(
2534            Mesh3D::building_art_deco_tower(CITY_MESH_ART_DECO, base_mat),
2535        ));
2536        let chamfered: usize = self.register_mesh(MeshLodChain::from_mesh(
2537            Mesh3D::building_chamfered_glass_tower(CITY_MESH_CHAMFERED, base_mat),
2538        ));
2539        let twisted: usize = self.register_mesh(MeshLodChain::from_mesh(
2540            Mesh3D::building_twisted_spire_tower(CITY_MESH_TWISTED, base_mat),
2541        ));
2542        let cantilever: usize = self.register_mesh(MeshLodChain::from_mesh(
2543            Mesh3D::building_cantilever_tech_tower(CITY_MESH_CANTILEVER, base_mat),
2544        ));
2545        let cylinder: usize = self.register_mesh(MeshLodChain::from_mesh(
2546            Mesh3D::building_cylindrical_landmark(CITY_MESH_CYLINDER, base_mat),
2547        ));
2548        let boutique: usize = self.register_mesh(MeshLodChain::from_mesh(
2549            Mesh3D::building_boutique_podium_block(CITY_MESH_BOUTIQUE, base_mat),
2550        ));
2551        [art_deco, chamfered, twisted, cantilever, cylinder, boutique]
2552    }
2553
2554    /// Returns the signature metallic clearcoat paint material for a given `HeroVehicleStyle`.
2555    ///
2556    /// # Arguments
2557    ///
2558    /// - `HeroVehicleStyle` - Target hero supercar bodywork style.
2559    ///
2560    /// # Returns
2561    ///
2562    /// - `PbrMaterial` - Signature body clearcoat PBR material.
2563    #[must_use]
2564    pub fn hero_vehicle_material(style: HeroVehicleStyle) -> PbrMaterial {
2565        match style {
2566            HeroVehicleStyle::AventadorV12 => {
2567                PbrMaterial::pbr(Color::hex(0xFF4500), 0.30, 0.12, 0.42)
2568            }
2569            HeroVehicleStyle::ShelbyCobra => {
2570                PbrMaterial::pbr(Color::hex(0x0A3EC2), 0.30, 0.12, 0.40)
2571            }
2572        }
2573    }
2574
2575    /// Switches the active hero supercar live between `HeroVehicleStyle::AventadorV12` and `HeroVehicleStyle::ShelbyCobra`, seamlessly preserving live position, yaw, headlights, taillights, and solid collision OBB without reallocating or rebuilding static geometry.
2576    ///
2577    /// # Arguments
2578    ///
2579    /// - `&Self` - Mutable world reference.
2580    /// - `HeroVehicleStyle` - Target hero vehicle bodywork archetype.
2581    ///
2582    /// # Returns
2583    ///
2584    /// - `bool` - `true` when the active hero vehicle mesh was updated.
2585    pub fn set_hero_vehicle_style(&mut self, style: HeroVehicleStyle) -> bool {
2586        let Some(car_idx) = self.vehicle_index() else {
2587            self.set_hero_vehicle_style_raw(style);
2588            return false;
2589        };
2590        let slot_idx: usize = match style {
2591            HeroVehicleStyle::AventadorV12 => 0,
2592            HeroVehicleStyle::ShelbyCobra => 1,
2593        };
2594        let cached_entry: Option<(usize, PbrMaterial)> = {
2595            let Self {
2596                hero_vehicle_meshes,
2597                ..
2598            } = self;
2599            hero_vehicle_meshes[slot_idx]
2600        };
2601        let (target_mesh_id, target_mat): (usize, PbrMaterial) = if let Some(pair) = cached_entry {
2602            pair
2603        } else {
2604            let sig_mat: PbrMaterial = Self::hero_vehicle_material(style);
2605            let built_mesh: Mesh3D = match style {
2606                HeroVehicleStyle::AventadorV12 => {
2607                    Mesh3D::aventador_svj(CITY_MESH_AVENTADOR, sig_mat)
2608                }
2609                HeroVehicleStyle::ShelbyCobra => Mesh3D::shelby_cobra(CITY_MESH_SHELBY, sig_mat),
2610            };
2611            let new_mesh_id: usize = self.register_mesh(MeshLodChain::single_level(built_mesh));
2612            let Self {
2613                hero_vehicle_meshes,
2614                ..
2615            } = self;
2616            hero_vehicle_meshes[slot_idx] = Some((new_mesh_id, sig_mat));
2617            (new_mesh_id, sig_mat)
2618        };
2619        let already_active: bool = self.get_hero_vehicle_style() == style
2620            && self
2621                .get_objects()
2622                .get(car_idx)
2623                .is_some_and(|obj: &SceneObject3D| obj.get_mesh_id() == target_mesh_id);
2624        if already_active {
2625            return false;
2626        }
2627        let new_local_bounds: AxisAlignedBox3D = self
2628            .get_mesh_library()
2629            .get(target_mesh_id)
2630            .and_then(|chain: &MeshLodChain| chain.get_levels().first())
2631            .map(Mesh3D::get_bounds)
2632            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.2), Vec3::splat(1.2)));
2633        if let Some(car_obj) = self.get_mut_objects().get_mut(car_idx) {
2634            let live_tr: Transform3D = car_obj.get_transform();
2635            car_obj.set_mesh_id(target_mesh_id);
2636            car_obj.set_material(target_mat);
2637            car_obj.set_world_bounds(live_tr.transform_bounds(new_local_bounds));
2638        }
2639        self.set_hero_vehicle_style_raw(style);
2640        self.set_dynamic_topology_dirty(true);
2641        self.set_dynamic_bvh_dirty(true);
2642        self.sync_dynamic_ray_instances();
2643        self.bump_world_revision();
2644        true
2645    }
2646
2647    /// Updates the stored `hero_vehicle_style` enum tag cleanly via Lombok setter.
2648    ///
2649    /// # Arguments
2650    ///
2651    /// - `&Self` - Mutable world reference.
2652    /// - `HeroVehicleStyle` - New active hero vehicle style.
2653    fn set_hero_vehicle_style_raw(&mut self, style: HeroVehicleStyle) {
2654        let Self {
2655            hero_vehicle_style, ..
2656        } = self;
2657        *hero_vehicle_style = style;
2658    }
2659
2660    /// Constructs a fresh `OpenWorldCityTemplate3D` containing procedural meshes, BVHs, and pre-baked static GPU vertex buffers.
2661    ///
2662    /// # Returns
2663    ///
2664    /// - `OpenWorldCityTemplate3D` - Complete immutable open-world city prototype.
2665    #[must_use]
2666    fn build_open_world_city_template() -> OpenWorldCityTemplate3D {
2667        let world: Self = Self::build_open_world_city_uncached();
2668        let rev: u64 = Self::allocate_gpu_mesh_revision();
2669        let (gpu_mesh_buffer, gpu_mesh_ranges): (Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>) =
2670            world.build_gpu_mesh_buffer(rev);
2671        OpenWorldCityTemplate3D {
2672            world,
2673            gpu_mesh_buffer,
2674            gpu_mesh_ranges,
2675        }
2676    }
2677
2678    /// Invokes `visitor` with a shared reference to the cached Vice Boulevard city template, constructing procedural meshes, BVHs, and static GPU vertex buffers once on first call.
2679    ///
2680    /// # Arguments
2681    ///
2682    /// - `F` - Closure consuming `&OpenWorldCityTemplate3D`.
2683    ///
2684    /// # Returns
2685    ///
2686    /// - `R` - Value returned by `visitor`.
2687    fn with_open_world_city_template<F, R>(visitor: F) -> R
2688    where
2689        F: FnOnce(&OpenWorldCityTemplate3D) -> R,
2690    {
2691        #[cfg(not(target_arch = "wasm32"))]
2692        {
2693            let tpl: &OpenWorldCityTemplate3D =
2694                OPEN_WORLD_CITY_TEMPLATE.get_or_init(Self::build_open_world_city_template);
2695            visitor(tpl)
2696        }
2697        #[cfg(target_arch = "wasm32")]
2698        {
2699            OPEN_WORLD_CITY_TEMPLATE_WASM.with(
2700                |slot: &RefCell<Option<OpenWorldCityTemplate3D>>| -> R {
2701                    if let Ok(mut guard) = slot.try_borrow_mut() {
2702                        if guard.is_none() {
2703                            *guard = Some(Self::build_open_world_city_template());
2704                        }
2705                        if let Some(tpl) = guard.as_ref() {
2706                            return visitor(tpl);
2707                        }
2708                    }
2709                    let fallback: OpenWorldCityTemplate3D = Self::build_open_world_city_template();
2710                    visitor(&fallback)
2711                },
2712            )
2713        }
2714    }
2715
2716    /// Builds a coastal closed-loop 962m metropolitan open-world circuit featuring six sculpted architectural building archetypes, an inner landmark skyline island, an open sunlit eastern ocean waterfront promenade, dynamic rigid-body boulevard and off-road NPC traffic, and selectable Aventador SVJ / Shelby GT500 Cobra hero supercars.
2717    ///
2718    /// # Returns
2719    ///
2720    /// - `Self` - Populated open-world 3D coastal city ready for real-time PBR + Ray Tracing.
2721    #[must_use]
2722    pub fn create_open_world_city() -> Self {
2723        Self::with_open_world_city_template(|tpl: &OpenWorldCityTemplate3D| tpl.world.clone())
2724    }
2725
2726    /// Clones the cached Vice Boulevard open-world city together with its pre-baked static GPU vertex buffer in O(1) `Arc::clone`, avoiding main-thread vertex packing stutters on `/game3d` entry.
2727    ///
2728    /// # Returns
2729    ///
2730    /// - `(Self, Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>)` - Ready-to-render 3D city plus shared static GPU mesh buffer and per-mesh vertex ranges.
2731    #[must_use]
2732    pub fn create_open_world_city_with_gpu_cache()
2733    -> (Self, Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>) {
2734        Self::with_open_world_city_template(|tpl: &OpenWorldCityTemplate3D| {
2735            (
2736                tpl.world.clone(),
2737                Arc::clone(&tpl.gpu_mesh_buffer),
2738                tpl.gpu_mesh_ranges.clone(),
2739            )
2740        })
2741    }
2742
2743    /// Constructs the procedural Vice Boulevard 3D city from scratch with pre-sized buffers for one-time initialization into `OPEN_WORLD_CITY_TEMPLATE`.
2744    ///
2745    /// # Returns
2746    ///
2747    /// - `Self` - Freshly assembled open-world 3D city with static and dynamic BVHs built.
2748    #[must_use]
2749    fn build_open_world_city_uncached() -> Self {
2750        let mut world: Self = Self::default();
2751        world.get_mut_mesh_library().reserve(16);
2752        world.get_mut_objects().reserve(144);
2753        world.get_mut_point_lights().reserve(16);
2754        world.get_mut_spot_lights().reserve(4);
2755        {
2756            let Self {
2757                traffic_vehicles, ..
2758            } = &mut world;
2759            traffic_vehicles.reserve(8);
2760        }
2761        let ground_w: f32 = CITY_GROUND_X_MAX - CITY_GROUND_X_MIN;
2762        let ground_d: f32 = CITY_GROUND_Z_MAX - CITY_GROUND_Z_MIN;
2763        let ground_cx: f32 = (CITY_GROUND_X_MIN + CITY_GROUND_X_MAX) * 0.5;
2764        let ground_cz: f32 = (CITY_GROUND_Z_MIN + CITY_GROUND_Z_MAX) * 0.5;
2765        let asphalt_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0E131C), 0.08, 0.24, 0.62)
2766            .with_surface_detail(SurfaceDetailMode::RoadSurface);
2767        let road_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::ground_plane(
2768            CITY_GROUND_MESH_NAME,
2769            ground_w,
2770            ground_d,
2771            24,
2772            asphalt_mat,
2773        )));
2774        let _: usize = world.spawn_object(
2775            CITY_GROUND_OBJ_NAME,
2776            road_mesh,
2777            Transform3D::new(Vec3::new(ground_cx, 0.0, ground_cz), 0.0, Vec3::splat(1.0)),
2778            asphalt_mat,
2779            false,
2780        );
2781        let ocean_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x063846), 0.05, 0.06, 0.86)
2782            .with_surface_detail(SurfaceDetailMode::OceanWater);
2783        let ocean_mesh: usize =
2784            world.register_mesh(MeshLodChain::from_mesh(Mesh3D::coastal_ocean_ring(
2785                CITY_OCEAN_MESH_NAME,
2786                CITY_OCEAN_SPAN_M,
2787                ground_w * 0.5,
2788                ground_d * 0.5,
2789                24,
2790                ocean_mat,
2791            )));
2792        let _: usize = world.spawn_object(
2793            CITY_OCEAN_MESH_NAME,
2794            ocean_mesh,
2795            Transform3D::new(
2796                Vec3::new(ground_cx, CITY_OCEAN_SURFACE_Y, ground_cz),
2797                0.0,
2798                Vec3::splat(1.0),
2799            ),
2800            ocean_mat,
2801            false,
2802        );
2803        let stud_mat: PbrMaterial = PbrMaterial::neon(Color::hex(0xFBBF24), 0.90);
2804        let stud_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2805            CITY_LANE_STUD_MESH_NAME,
2806            0.10,
2807            0.018,
2808            0.16,
2809            true,
2810            stud_mat,
2811        )));
2812        for iz in -7..=0 {
2813            let _: usize = world.spawn_object(
2814                &format!("stripe_{iz}"),
2815                stud_mesh,
2816                Transform3D::new(
2817                    Vec3::new(0.0, 0.008, (iz as f32) * 14.0),
2818                    0.0,
2819                    Vec3::splat(1.0),
2820                ),
2821                stud_mat,
2822                false,
2823            );
2824        }
2825        let unit_box: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2826            CITY_UNIT_BOX_MESH_NAME,
2827            1.0,
2828            1.0,
2829            1.0,
2830            true,
2831            PbrMaterial::default(),
2832        )));
2833        let neon_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2834            CITY_NEON_SIGN_MESH_NAME,
2835            1.0,
2836            1.0,
2837            1.0,
2838            true,
2839            PbrMaterial::neon(Color::hex(0x38BDF8), 1.8),
2840        )));
2841        let archetypes: [usize; 6] = world.register_building_archetypes();
2842        let palettes: [PbrMaterial; 6] = Self::curated_skyline_palettes();
2843        let neon_colors: [Color; 4] = [
2844            Color::hex(0x38BDF8),
2845            Color::hex(0xF43F5E),
2846            Color::hex(0xA855F7),
2847            Color::hex(0x34D399),
2848        ];
2849        let west_pattern: [(usize, f32, f32, f32); 9] = [
2850            (0, 46.0, 11.2, 12.0),
2851            (5, 20.0, 11.6, 12.4),
2852            (1, 38.0, 11.0, 11.8),
2853            (3, 34.0, 10.6, 11.8),
2854            (4, 48.0, 11.4, 11.4),
2855            (5, 22.0, 11.4, 12.2),
2856            (2, 54.0, 11.2, 11.2),
2857            (1, 40.0, 10.8, 12.0),
2858            (0, 44.0, 11.0, 11.6),
2859        ];
2860        let mut idx_counter: usize = 0;
2861        for side in [-1.0_f32, 1.0_f32] {
2862            for (row_i, row_z_idx) in (-4..=4_i32).enumerate() {
2863                let (base_arch, base_h, width_val, depth_val): (usize, f32, f32, f32) =
2864                    west_pattern[(row_i + if side > 0.0 { 2 } else { 0 }) % west_pattern.len()];
2865                let pos_z: f32 = (row_z_idx as f32) * 28.0 - 4.0;
2866                let pos_x: f32 = side * (22.0 + ((idx_counter % 3) as f32) * 1.1);
2867                let height_val: f32 = if side > 0.0 && base_arch != 5 {
2868                    base_h + 4.0
2869                } else {
2870                    base_h
2871                };
2872                let mat: PbrMaterial = palettes[(idx_counter * 5 + row_i) % palettes.len()];
2873                let _: usize = world.spawn_object(
2874                    &format!("tower_{idx_counter}"),
2875                    archetypes[base_arch],
2876                    Transform3D::new(
2877                        Vec3::new(pos_x, 0.0, pos_z),
2878                        0.0,
2879                        Vec3::new(width_val, height_val, depth_val),
2880                    ),
2881                    mat,
2882                    true,
2883                );
2884                idx_counter += 1;
2885            }
2886        }
2887        let inner_spine_specs: [(f32, f32, f32, f32, f32, usize, usize); 19] = [
2888            (64.0, -158.0, 14.0, 56.0, 14.0, 4, 1),
2889            (64.0, -116.0, 14.5, 68.0, 14.5, 0, 0),
2890            (54.0, -76.0, 13.0, 62.0, 13.0, 2, 2),
2891            (76.0, -76.0, 13.0, 52.0, 13.0, 1, 4),
2892            (64.0, -34.0, 15.0, 74.0, 15.0, 2, 5),
2893            (52.0, 10.0, 13.5, 58.0, 13.5, 3, 3),
2894            (78.0, 12.0, 13.5, 64.0, 13.5, 4, 1),
2895            (64.0, 56.0, 14.5, 70.0, 14.5, 0, 0),
2896            (54.0, 98.0, 13.0, 54.0, 13.0, 1, 2),
2897            (76.0, 100.0, 13.0, 48.0, 13.0, 3, 4),
2898            (64.0, 156.0, 14.0, 58.0, 14.0, 4, 5),
2899            (103.5, -112.0, 11.4, 34.0, 12.4, 5, 0),
2900            (103.5, -78.0, 11.6, 48.0, 11.6, 4, 4),
2901            (103.5, -44.0, 11.4, 24.0, 12.2, 5, 3),
2902            (103.5, -10.0, 11.8, 44.0, 12.0, 1, 1),
2903            (103.5, 24.0, 11.4, 38.0, 12.0, 3, 5),
2904            (103.5, 58.0, 11.6, 22.0, 12.2, 5, 0),
2905            (103.5, 92.0, 11.8, 46.0, 11.8, 0, 2),
2906            (103.5, 124.0, 11.4, 40.0, 11.4, 2, 4),
2907        ];
2908        for (l_idx, &(lx, lz, lw, lh, ld, l_arch, l_pal)) in inner_spine_specs.iter().enumerate() {
2909            let _: usize = world.spawn_object(
2910                &format!("landmark_tower_{l_idx}"),
2911                archetypes[l_arch],
2912                Transform3D::new(Vec3::new(lx, 0.0, lz), 0.0, Vec3::new(lw, lh, ld)),
2913                palettes[l_pal],
2914                true,
2915            );
2916        }
2917        let skyline_specs: [(f32, f32, f32, f32, usize, usize); 6] = [
2918            (-46.0, -96.0, 13.0, 56.0, 0, 2),
2919            (-46.0, -64.0, 12.5, 66.0, 2, 1),
2920            (-46.0, -32.0, 13.0, 52.0, 4, 4),
2921            (-46.0, 4.0, 12.5, 62.0, 1, 5),
2922            (-46.0, 40.0, 12.5, 50.0, 3, 3),
2923            (-46.0, 76.0, 13.0, 58.0, 0, 0),
2924        ];
2925        for (sky_idx, &(sx, sz, sw, sh, s_arch, s_pal)) in skyline_specs.iter().enumerate() {
2926            let _: usize = world.spawn_object(
2927                &format!("{CITY_SKYLINE_MESH_NAME}_{sky_idx}"),
2928                archetypes[s_arch],
2929                Transform3D::new(Vec3::new(sx, 0.0, sz), 0.0, Vec3::new(sw, sh, 13.0)),
2930                palettes[s_pal],
2931                true,
2932            );
2933        }
2934        let mut rim_serial: usize = 0;
2935        let rim_angles_deg: [f32; 7] = [44.0, 64.0, 84.0, 104.0, 124.0, 144.0, 164.0];
2936        for (turn_idx, &turn_sign_z) in [-1.0_f32, 1.0_f32].iter().enumerate() {
2937            let center_z: f32 = turn_sign_z * CITY_LOOP_STRAIGHT_HALF_Z;
2938            for (ang_i, &deg) in rim_angles_deg.iter().enumerate() {
2939                let rad: f32 = deg.to_radians();
2940                let (sin_a, cos_a): (f32, f32) = rad.sin_cos();
2941                let ring_r: f32 = 94.0 + ((ang_i % 2) as f32) * 3.5;
2942                let rx: f32 = CITY_LOOP_CENTER_X + ring_r * cos_a;
2943                let rz: f32 = center_z + turn_sign_z * ring_r * sin_a;
2944                let yaw_rim: f32 = if turn_sign_z < 0.0 {
2945                    rad - FRAC_PI_2
2946                } else {
2947                    FRAC_PI_2 - rad
2948                };
2949                let arch_i: usize = (rim_serial + turn_idx * 2) % archetypes.len();
2950                let height_m: f32 = if arch_i == 5 {
2951                    24.0
2952                } else {
2953                    36.0 + ((rim_serial * 7) % 4) as f32 * 8.0
2954                };
2955                let _: usize = world.spawn_object(
2956                    &format!("rim_tower_{rim_serial}"),
2957                    archetypes[arch_i],
2958                    Transform3D::new(
2959                        Vec3::new(rx, 0.0, rz),
2960                        yaw_rim,
2961                        Vec3::new(11.5, height_m, 11.5),
2962                    ),
2963                    palettes[(rim_serial + 1) % palettes.len()],
2964                    true,
2965                );
2966                rim_serial += 1;
2967            }
2968        }
2969        let seawall_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x475569), 0.14, 0.56, 0.22);
2970        let mut wall_serial: usize = 0;
2971        let _: usize = world.spawn_object(
2972            &format!("{CITY_SEAWALL_MESH_NAME}_{wall_serial}"),
2973            unit_box,
2974            Transform3D::new(
2975                Vec3::new(142.8, 0.0, 0.0),
2976                0.0,
2977                Vec3::new(2.4, 1.15, CITY_LOOP_STRAIGHT_HALF_Z * 2.0 + 4.0),
2978            ),
2979            seawall_mat,
2980            true,
2981        );
2982        wall_serial += 1;
2983        for &turn_sign_z in [-1.0_f32, 1.0_f32].iter() {
2984            let center_z: f32 = turn_sign_z * CITY_LOOP_STRAIGHT_HALF_Z;
2985            let seg_count: usize = 10;
2986            for seg_i in 0..seg_count {
2987                let deg: f32 = 3.0 + (seg_i as f32) * 6.0;
2988                let rad: f32 = deg.to_radians();
2989                let (sin_a, cos_a): (f32, f32) = rad.sin_cos();
2990                let wall_r: f32 = 79.0;
2991                let wx: f32 = CITY_LOOP_CENTER_X + wall_r * cos_a;
2992                let wz: f32 = center_z + turn_sign_z * wall_r * sin_a;
2993                let wall_yaw: f32 = if turn_sign_z < 0.0 { rad } else { -rad };
2994                let _: usize = world.spawn_object(
2995                    &format!("{CITY_SEAWALL_MESH_NAME}_{wall_serial}"),
2996                    unit_box,
2997                    Transform3D::new(Vec3::new(wx, 0.0, wz), wall_yaw, Vec3::new(2.2, 1.15, 10.6)),
2998                    seawall_mat,
2999                    true,
3000                );
3001                wall_serial += 1;
3002            }
3003        }
3004        let palm_mesh: usize = world.register_mesh(MeshLodChain::single_level(Mesh3D::palm_tree(
3005            CITY_PALM_MESH_NAME,
3006        )));
3007        let palm_bark_mat: PbrMaterial = PbrMaterial::dielectric(Color::hex(0x4E392B), 0.88);
3008        let palm_z_positions: [f32; 6] = [-102.0, -74.0, -46.0, -18.0, 10.0, 38.0];
3009        for (palm_row, &palm_z) in palm_z_positions.iter().enumerate() {
3010            for side_idx in 0..2usize {
3011                let side_sign: f32 = if side_idx == 0 { -1.0 } else { 1.0 };
3012                let yaw_palm: f32 = (palm_row as f32) * 0.95
3013                    + (side_idx as f32) * 2.1
3014                    + if side_idx == 0 { 0.35 } else { -0.35 };
3015                let scale_palm: f32 = 0.94 + ((palm_row + side_idx) % 3) as f32 * 0.08;
3016                let _: usize = world.spawn_object(
3017                    &format!("palm_{palm_row}_{side_idx}"),
3018                    palm_mesh,
3019                    Transform3D::new(
3020                        Vec3::new(side_sign * 12.0, 0.0, palm_z),
3021                        yaw_palm,
3022                        Vec3::splat(scale_palm),
3023                    ),
3024                    palm_bark_mat,
3025                    true,
3026                );
3027            }
3028        }
3029        for coast_i in 0..10usize {
3030            let cz: f32 = -124.0 + (coast_i as f32) * 27.5;
3031            let yaw_p: f32 = (coast_i as f32) * 0.72 + 1.2;
3032            let scale_p: f32 = 0.96 + (coast_i % 3) as f32 * 0.07;
3033            let _: usize = world.spawn_object(
3034                &format!("waterfront_palm_{coast_i}"),
3035                palm_mesh,
3036                Transform3D::new(Vec3::new(139.8, 0.0, cz), yaw_p, Vec3::splat(scale_p)),
3037                palm_bark_mat,
3038                true,
3039            );
3040        }
3041        let arch_frame_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0F172A), 0.82, 0.18, 0.60);
3042        for (arch_idx, &arch_z) in [-36.0_f32, -80.0_f32, 48.0_f32].iter().enumerate() {
3043            let arch_neon: PbrMaterial =
3044                PbrMaterial::neon(neon_colors[arch_idx % neon_colors.len()], 2.1);
3045            let _: usize = world.spawn_object(
3046                &format!("arch_beam_{arch_idx}"),
3047                unit_box,
3048                Transform3D::new(
3049                    Vec3::new(0.0, 13.4, arch_z),
3050                    0.0,
3051                    Vec3::new(23.0, 0.58, 0.72),
3052                ),
3053                arch_frame_mat,
3054                true,
3055            );
3056            let _: usize = world.spawn_object(
3057                &format!("arch_glow_{arch_idx}"),
3058                neon_unit,
3059                Transform3D::new(
3060                    Vec3::new(0.0, 13.08, arch_z),
3061                    0.0,
3062                    Vec3::new(21.2, 0.24, 0.34),
3063                ),
3064                arch_neon,
3065                true,
3066            );
3067            for side in [-1.0_f32, 1.0_f32] {
3068                let _: usize = world.spawn_object(
3069                    &format!("arch_pillar_{arch_idx}_{}", if side < 0.0 { 0 } else { 1 }),
3070                    unit_box,
3071                    Transform3D::new(
3072                        Vec3::new(side * 11.2, 0.0, arch_z),
3073                        0.0,
3074                        Vec3::new(0.58, 13.4, 0.68),
3075                    ),
3076                    arch_frame_mat,
3077                    true,
3078                );
3079            }
3080        }
3081        let aventador_mat: PbrMaterial =
3082            Self::hero_vehicle_material(HeroVehicleStyle::AventadorV12);
3083        let shelby_mat: PbrMaterial = Self::hero_vehicle_material(HeroVehicleStyle::ShelbyCobra);
3084        let aventador_mesh: usize = world.register_mesh(MeshLodChain::single_level(
3085            Mesh3D::aventador_svj(CITY_MESH_AVENTADOR, aventador_mat),
3086        ));
3087        let shelby_mesh: usize = world.register_mesh(MeshLodChain::single_level(
3088            Mesh3D::shelby_cobra(CITY_MESH_SHELBY, shelby_mat),
3089        ));
3090        {
3091            let Self {
3092                hero_vehicle_meshes,
3093                ..
3094            } = &mut world;
3095            hero_vehicle_meshes[0] = Some((aventador_mesh, aventador_mat));
3096            hero_vehicle_meshes[1] = Some((shelby_mesh, shelby_mat));
3097        }
3098        let car_idx: usize = world.spawn_object(
3099            CITY_OBJ_PLAYER_CAR,
3100            aventador_mesh,
3101            Transform3D::new(Vec3::new(0.0, 0.0, 0.0), 0.0, Vec3::splat(1.1)),
3102            aventador_mat,
3103            true,
3104        );
3105        let _: bool = world.set_object_dynamic(car_idx, true);
3106        world.set_player_vehicle_index(Some(car_idx));
3107        let _: usize = world.add_point_light(PointLight3D::new(
3108            Vec3::new(0.0, 0.95, 2.9),
3109            Color::hex(0xFF1744),
3110            1.85,
3111            8.5,
3112        ));
3113        let traffic_specs: [(f32, f32, f32, usize, Color); 4] = [
3114            (156.0, 5.6, -11.5, shelby_mesh, Color::hex(0x38BDF8)),
3115            (620.0, 5.6, -11.5, aventador_mesh, Color::hex(0xA855F7)),
3116            (164.0, -5.6, 13.0, aventador_mesh, Color::hex(0x22C55E)),
3117            (645.0, -5.6, 13.0, shelby_mesh, Color::hex(0xF59E0B)),
3118        ];
3119        for (t_idx, &(start_s, lane_u, speed_mps, t_mesh, t_col)) in
3120            traffic_specs.iter().enumerate()
3121        {
3122            let (t_pos, base_yaw): (Vec3, f32) = Self::loop_pose_at(start_s, lane_u);
3123            let face_yaw: f32 = if speed_mps >= 0.0 {
3124                base_yaw
3125            } else {
3126                base_yaw + PI
3127            };
3128            let tmat: PbrMaterial = PbrMaterial::pbr(t_col, 0.84, 0.13, 0.76);
3129            let obj_id: usize = world.spawn_object(
3130                &format!("ai_traffic_{t_idx}"),
3131                t_mesh,
3132                Transform3D::new(t_pos, face_yaw, Vec3::splat(1.04)),
3133                tmat,
3134                true,
3135            );
3136            let _: bool = world.set_object_dynamic(obj_id, true);
3137            let Self {
3138                traffic_vehicles, ..
3139            } = &mut world;
3140            traffic_vehicles.push(NpcVehicle3D::new_boulevard(
3141                obj_id, start_s, lane_u, speed_mps, face_yaw,
3142            ));
3143        }
3144        let offroad_specs: [(Vec3, f32, u8, usize, f32, usize, Color); 4] = [
3145            (
3146                Vec3::new(38.0, 0.0, -40.0),
3147                0.0,
3148                0,
3149                0,
3150                10.5,
3151                aventador_mesh,
3152                Color::hex(0x14B8A6),
3153            ),
3154            (
3155                Vec3::new(91.0, 0.0, 40.0),
3156                PI,
3157                0,
3158                3,
3159                10.0,
3160                shelby_mesh,
3161                Color::hex(0xFB7185),
3162            ),
3163            (
3164                Vec3::new(-72.0, 0.0, -30.0),
3165                PI,
3166                1,
3167                1,
3168                11.0,
3169                aventador_mesh,
3170                Color::hex(0xEAB308),
3171            ),
3172            (
3173                Vec3::new(38.0, 0.0, 78.0),
3174                -FRAC_PI_2,
3175                2,
3176                1,
3177                9.5,
3178                shelby_mesh,
3179                Color::hex(0x6366F1),
3180            ),
3181        ];
3182        for (o_idx, &(o_pos, o_yaw, route_id, wp_idx, o_speed, o_mesh, o_col)) in
3183            offroad_specs.iter().enumerate()
3184        {
3185            let traffic_serial: usize = traffic_specs.len() + o_idx;
3186            let omat: PbrMaterial = PbrMaterial::pbr(o_col, 0.84, 0.13, 0.76);
3187            let obj_id: usize = world.spawn_object(
3188                &format!("ai_traffic_{traffic_serial}"),
3189                o_mesh,
3190                Transform3D::new(o_pos, o_yaw, Vec3::splat(1.04)),
3191                omat,
3192                true,
3193            );
3194            let _: bool = world.set_object_dynamic(obj_id, true);
3195            let Self {
3196                traffic_vehicles, ..
3197            } = &mut world;
3198            traffic_vehicles.push(NpcVehicle3D::new_free_roam(
3199                obj_id, route_id, wp_idx, o_speed, o_yaw,
3200            ));
3201        }
3202        let lamp_palette: [Color; 4] = [
3203            Color::hex(0x38BDF8),
3204            Color::hex(0xF43F5E),
3205            Color::hex(0xA855F7),
3206            Color::hex(0x34D399),
3207        ];
3208        let lamp_z_rows: [f32; 4] = [-62.0, -26.0, 18.0, 66.0];
3209        for lamp_idx in 0..8usize {
3210            let side: f32 = if lamp_idx % 2 == 0 { -1.0 } else { 1.0 };
3211            let z_pos: f32 = lamp_z_rows[lamp_idx / 2];
3212            let lamp_color: Color = lamp_palette[lamp_idx % lamp_palette.len()];
3213            let _: usize = world.spawn_object(
3214                &format!("lamp_pole_{lamp_idx}"),
3215                unit_box,
3216                Transform3D::new(
3217                    Vec3::new(side * 10.65, 0.0, z_pos),
3218                    0.0,
3219                    Vec3::new(0.20, 6.2, 0.20),
3220                ),
3221                arch_frame_mat,
3222                true,
3223            );
3224            let _: usize = world.spawn_object(
3225                &format!("lamp_head_{lamp_idx}"),
3226                neon_unit,
3227                Transform3D::new(
3228                    Vec3::new(side * 10.15, 6.2, z_pos),
3229                    0.0,
3230                    Vec3::new(1.1, 0.18, 0.28),
3231                ),
3232                PbrMaterial::neon(lamp_color, 2.2),
3233                true,
3234            );
3235            let _: usize = world.add_point_light(PointLight3D::new(
3236                Vec3::new(side * 9.8, 6.2, z_pos),
3237                lamp_color,
3238                2.35,
3239                16.5,
3240            ));
3241        }
3242        let _: usize = world.add_spot_light(SpotLight3D::new(
3243            Vec3::new(-0.85, 0.95, -2.2),
3244            Vec3::new(0.0, -0.14, -1.0),
3245            Color::hex(0xFEF3C7),
3246            2.8,
3247            24.0,
3248            (14.0, 26.0),
3249        ));
3250        let _: usize = world.add_spot_light(SpotLight3D::new(
3251            Vec3::new(0.85, 0.95, -2.2),
3252            Vec3::new(0.0, -0.14, -1.0),
3253            Color::hex(0xFEF3C7),
3254            2.8,
3255            24.0,
3256            (14.0, 26.0),
3257        ));
3258        world.set_camera(Camera3D {
3259            position: Vec3::new(0.0, 4.15, 9.2),
3260            yaw: -FRAC_PI_2,
3261            pitch: -0.145,
3262            fov_deg: 60.0,
3263            near: 0.3,
3264            far: 560.0,
3265        });
3266        world.ensure_bvh();
3267        world
3268    }
3269
3270    /// Returns the number of autonomous rigid-body NPC vehicles registered in this world.
3271    ///
3272    /// # Returns
3273    ///
3274    /// - `usize` - Active autonomous NPC vehicle count.
3275    #[must_use]
3276    pub fn traffic_vehicle_count(&self) -> usize {
3277        let Self {
3278            traffic_vehicles, ..
3279        } = self;
3280        traffic_vehicles.len()
3281    }
3282
3283    /// Returns the scene object index for dynamic NPC vehicle `slot`.
3284    ///
3285    /// # Arguments
3286    ///
3287    /// - `usize` - NPC traffic slot index.
3288    ///
3289    /// # Returns
3290    ///
3291    /// - `Option<usize>` - Owning object index in `World3D::objects`, if `slot` is valid.
3292    #[must_use]
3293    pub fn traffic_vehicle_object_index(&self, slot: usize) -> Option<usize> {
3294        let Self {
3295            traffic_vehicles, ..
3296        } = self;
3297        traffic_vehicles
3298            .get(slot)
3299            .map(NpcVehicle3D::get_object_index)
3300    }
3301
3302    /// Returns the live rigid-body horizontal velocity of NPC vehicle `slot` in meters per second.
3303    ///
3304    /// # Arguments
3305    ///
3306    /// - `usize` - NPC traffic slot index.
3307    ///
3308    /// # Returns
3309    ///
3310    /// - `Option<Vec3>` - World-space velocity vector in meters per second.
3311    #[must_use]
3312    pub fn traffic_vehicle_velocity(&self, slot: usize) -> Option<Vec3> {
3313        let Self {
3314            traffic_vehicles, ..
3315        } = self;
3316        traffic_vehicles.get(slot).map(NpcVehicle3D::get_vel)
3317    }
3318
3319    /// Returns the active angular spin rate of NPC vehicle `slot` in radians per second.
3320    ///
3321    /// # Arguments
3322    ///
3323    /// - `usize` - NPC traffic slot index.
3324    ///
3325    /// # Returns
3326    ///
3327    /// - `Option<f32>` - Yaw spin rate in radians per second.
3328    #[must_use]
3329    pub fn traffic_vehicle_yaw_rate(&self, slot: usize) -> Option<f32> {
3330        let Self {
3331            traffic_vehicles, ..
3332        } = self;
3333        traffic_vehicles.get(slot).map(NpcVehicle3D::get_yaw_rate)
3334    }
3335
3336    /// Returns whether NPC vehicle `slot` is operating in unrestricted off-road free-roam mode.
3337    ///
3338    /// # Arguments
3339    ///
3340    /// - `usize` - NPC traffic slot index.
3341    ///
3342    /// # Returns
3343    ///
3344    /// - `Option<bool>` - `true` when freely roaming off-road plazas and city grounds.
3345    #[must_use]
3346    pub fn traffic_vehicle_is_free_roam(&self, slot: usize) -> Option<bool> {
3347        let Self {
3348            traffic_vehicles, ..
3349        } = self;
3350        traffic_vehicles
3351            .get(slot)
3352            .map(NpcVehicle3D::get_free_roam_mode)
3353    }
3354
3355    /// Returns the player vehicle's live world-space horizontal velocity vector in meters per second.
3356    ///
3357    /// # Returns
3358    ///
3359    /// - `Vec3` - Player vehicle velocity `(vx, 0.0, vz)` in meters per second.
3360    #[must_use]
3361    pub fn player_velocity(&self) -> Vec3 {
3362        let Self { player_physics, .. } = self;
3363        player_physics.get_vel()
3364    }
3365
3366    /// Returns the player vehicle's signed longitudinal velocity along its facing direction in meters per second (negative while reversing).
3367    ///
3368    /// # Returns
3369    ///
3370    /// - `f32` - Signed forward velocity in meters per second.
3371    #[must_use]
3372    pub fn player_forward_speed_mps(&self) -> f32 {
3373        let Some(car_idx) = self.vehicle_index() else {
3374            return 0.0;
3375        };
3376        let Some(car_obj) = self.get_objects().get(car_idx) else {
3377            return 0.0;
3378        };
3379        let yaw_rad: f32 = car_obj.get_transform().get_yaw_rad();
3380        let forward_dir: Vec3 = Vec3::new(-yaw_rad.sin(), 0.0, -yaw_rad.cos());
3381        self.player_velocity().dot(forward_dir)
3382    }
3383
3384    /// Resets the player hero vehicle to the coastal boulevard starting grid with full nitro charge and cleared particle trails.
3385    ///
3386    /// # Returns
3387    ///
3388    /// - `bool` - `true` when the player vehicle existed and was reset cleanly.
3389    pub fn reset_player_vehicle(&mut self) -> bool {
3390        let Some(car_idx) = self.vehicle_index() else {
3391            return false;
3392        };
3393        let spawn_transform: Transform3D =
3394            Transform3D::new(Vec3::new(0.0, 0.0, 0.0), 0.0, Vec3::splat(1.1));
3395        if !self.teleport_object(car_idx, spawn_transform) {
3396            return false;
3397        }
3398        {
3399            let Self { player_physics, .. } = self;
3400            player_physics.set_boost_charge(1.0);
3401        }
3402        self.get_mut_niagara().clear();
3403        let mut reset_cam: Camera3D = self.get_camera();
3404        let eye_pos: Vec3 = Vec3::new(0.0, 4.25, 9.8);
3405        let look_target: Vec3 = Vec3::new(0.0, 2.40, -16.0);
3406        let look_dir: Vec3 = look_target.sub(eye_pos).normalize();
3407        reset_cam.set_position(eye_pos);
3408        reset_cam.set_yaw(look_dir.get_z().atan2(look_dir.get_x()));
3409        reset_cam.set_pitch(look_dir.get_y().clamp(-0.92, 0.92).asin());
3410        reset_cam.set_fov_deg(CAMERA_BASE_FOV_DEG);
3411        self.set_camera(reset_cam);
3412        self.bump_world_revision();
3413        true
3414    }
3415
3416    /// Returns the player vehicle's live horizontal speed in meters per second.
3417    ///
3418    /// # Returns
3419    ///
3420    /// - `f32` - Horizontal speed magnitude in meters per second.
3421    #[must_use]
3422    pub fn player_speed_mps(&self) -> f32 {
3423        let v: Vec3 = self.player_velocity();
3424        (v.get_x() * v.get_x() + v.get_z() * v.get_z()).sqrt()
3425    }
3426
3427    /// Returns the player vehicle's live speed in kilometers per hour.
3428    ///
3429    /// # Returns
3430    ///
3431    /// - `f32` - Speed in kilometers per hour.
3432    #[must_use]
3433    pub fn player_speed_kmh(&self) -> f32 {
3434        self.player_speed_mps() * 3.6
3435    }
3436
3437    /// Returns the player vehicle's active yaw angular velocity in radians per second.
3438    ///
3439    /// # Returns
3440    ///
3441    /// - `f32` - Active yaw rate in radians per second.
3442    #[must_use]
3443    pub fn player_yaw_rate(&self) -> f32 {
3444        let Self { player_physics, .. } = self;
3445        player_physics.get_yaw_rate()
3446    }
3447
3448    /// Returns `true` when Shift nitro boost is currently delivering extra thrust.
3449    ///
3450    /// # Returns
3451    ///
3452    /// - `bool` - Whether nitro boost is active.
3453    #[must_use]
3454    pub fn player_boost_active(&self) -> bool {
3455        let Self { player_physics, .. } = self;
3456        player_physics.get_boost_active()
3457    }
3458
3459    /// Returns the player vehicle's normalized remaining nitro boost charge in `[0.0, 1.0]`.
3460    ///
3461    /// # Returns
3462    ///
3463    /// - `f32` - Normalized boost charge in `[0.0, 1.0]`.
3464    #[must_use]
3465    pub fn player_boost_charge(&self) -> f32 {
3466        let Self { player_physics, .. } = self;
3467        player_physics.get_boost_charge()
3468    }
3469
3470    /// Returns `true` when Space handbrake powerslide drift is currently active.
3471    ///
3472    /// # Returns
3473    ///
3474    /// - `bool` - Whether handbrake drift is active.
3475    #[must_use]
3476    pub fn player_drift_active(&self) -> bool {
3477        let Self { player_physics, .. } = self;
3478        player_physics.get_drift_active()
3479    }
3480
3481    /// Returns the player vehicle's signed lateral slip angle in radians.
3482    ///
3483    /// # Returns
3484    ///
3485    /// - `f32` - Signed lateral slip angle `atan2(v_lateral, |v_forward|)` in radians.
3486    #[must_use]
3487    pub fn player_drift_slip_angle_rad(&self) -> f32 {
3488        let Self { player_physics, .. } = self;
3489        player_physics.get_drift_slip_angle()
3490    }
3491
3492    /// Returns the player vehicle's visual lateral chassis body roll angle in radians.
3493    ///
3494    /// # Returns
3495    ///
3496    /// - `f32` - Body roll angle in radians.
3497    #[must_use]
3498    pub fn player_body_roll_rad(&self) -> f32 {
3499        let Self { player_physics, .. } = self;
3500        player_physics.get_body_roll_rad()
3501    }
3502
3503    /// Returns the player vehicle's visual longitudinal chassis pitch angle in radians.
3504    ///
3505    /// # Returns
3506    ///
3507    /// - `f32` - Body pitch angle in radians.
3508    #[must_use]
3509    pub fn player_body_pitch_rad(&self) -> f32 {
3510        let Self { player_physics, .. } = self;
3511        player_physics.get_body_pitch_rad()
3512    }
3513
3514    /// Returns the player chase camera's active dynamic FOV boost offset in degrees.
3515    ///
3516    /// # Returns
3517    ///
3518    /// - `f32` - Dynamic FOV boost offset in degrees.
3519    #[must_use]
3520    pub fn player_camera_fov_boost(&self) -> f32 {
3521        let Self { player_physics, .. } = self;
3522        player_physics.get_camera_fov_boost()
3523    }
3524
3525    /// Returns the player camera's active impact shake intensity in `[0.0, 1.0]`.
3526    ///
3527    /// # Returns
3528    ///
3529    /// - `f32` - Camera impact shake amplitude.
3530    #[must_use]
3531    pub fn player_camera_shake(&self) -> f32 {
3532        let Self { player_physics, .. } = self;
3533        player_physics.get_camera_shake()
3534    }
3535
3536    /// Applies an atmospheric mood preset (`0=Sunset, 1=RainyNight, 2=Noon, 3=Midnight`), updating sun lighting and ambient Niagara rain streaks.
3537    ///
3538    /// # Arguments
3539    ///
3540    /// - `u8` - Atmosphere preset index (`0..=3`).
3541    ///
3542    /// # Returns
3543    ///
3544    /// - `f32` - Corresponding time-of-day hour in `[0.0, 24.0]`.
3545    pub fn apply_atmosphere_preset(&mut self, preset: u8) -> f32 {
3546        let clamped: u8 = preset.min(3);
3547        let hour: f32 = match clamped {
3548            1 => ATMOSPHERE_HOUR_RAINY_NIGHT,
3549            2 => ATMOSPHERE_HOUR_NOON,
3550            3 => ATMOSPHERE_HOUR_MIDNIGHT,
3551            _ => ATMOSPHERE_HOUR_SUNSET,
3552        };
3553        self.set_atmosphere_preset(clamped);
3554        let sun_light: DirectionalLight3D = match clamped {
3555            1 => DirectionalLight3D {
3556                direction: Vec3::new(-0.32, 0.48, -0.82).normalize(),
3557                color: Vec3::new(0.56, 0.78, 1.24),
3558                sky_zenith: Vec3::new(0.015, 0.038, 0.105),
3559                sky_horizon: Vec3::new(0.078, 0.155, 0.275),
3560                time_of_day: hour,
3561            },
3562            3 => DirectionalLight3D {
3563                direction: Vec3::new(-0.42, 0.62, -0.66).normalize(),
3564                color: Vec3::new(0.36, 0.34, 0.88),
3565                sky_zenith: Vec3::new(0.007, 0.005, 0.024),
3566                sky_horizon: Vec3::new(0.135, 0.036, 0.215),
3567                time_of_day: hour,
3568            },
3569            _ => DirectionalLight3D::from_time_of_day(hour),
3570        };
3571        self.set_sun(sun_light);
3572        if clamped == 1 && self.get_niagara().get_active_count() < RAINY_NIGHT_MAX_PARTICLES {
3573            let cam_pos: Vec3 = self.get_camera().get_position();
3574            let mut rain_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
3575            rain_cfg.set_origin(cam_pos.add(Vec3::new(0.0, 4.5, -14.0)));
3576            rain_cfg.set_base_velocity(Vec3::new(-0.4, -17.0, 0.3));
3577            rain_cfg.set_velocity_spread(2.4);
3578            rain_cfg.set_start_color(Color::rgba(175, 222, 255, 165));
3579            rain_cfg.set_end_color(Color::rgba(92, 162, 235, 42));
3580            rain_cfg.set_start_size_m(0.042);
3581            rain_cfg.set_end_size_m(0.016);
3582            rain_cfg.set_min_lifetime(0.55);
3583            rain_cfg.set_max_lifetime(0.95);
3584            rain_cfg.set_emissive_boost(0.85);
3585            self.get_mut_niagara().emit_burst(8, &rain_cfg);
3586        }
3587        self.bump_world_revision();
3588        hour
3589    }
3590
3591    /// Registers a dynamic `PointLight3D` into this world for UE5 Clustered Deferred Lighting and returns its index.
3592    ///
3593    /// # Arguments
3594    ///
3595    /// - `PointLight3D` - World-space point light descriptor.
3596    ///
3597    /// # Returns
3598    ///
3599    /// - `usize` - Assigned point light index.
3600    pub fn add_point_light(&mut self, light: PointLight3D) -> usize {
3601        let light_idx: usize = self.get_point_lights().len();
3602        self.get_mut_point_lights().push(light);
3603        self.bump_world_revision();
3604        light_idx
3605    }
3606
3607    /// Registers a dynamic `SpotLight3D` into this world for UE5 Clustered Deferred Lighting and returns its index.
3608    ///
3609    /// # Arguments
3610    ///
3611    /// - `SpotLight3D` - World-space spotlight descriptor.
3612    ///
3613    /// # Returns
3614    ///
3615    /// - `usize` - Assigned spotlight index.
3616    pub fn add_spot_light(&mut self, light: SpotLight3D) -> usize {
3617        let light_idx: usize = self.get_spot_lights().len();
3618        self.get_mut_spot_lights().push(light);
3619        self.bump_world_revision();
3620        light_idx
3621    }
3622
3623    /// Clears all dynamic local point and spot lights from this world.
3624    pub fn clear_local_lights(&mut self) {
3625        self.get_mut_point_lights().clear();
3626        self.get_mut_spot_lights().clear();
3627        self.bump_world_revision();
3628    }
3629
3630    /// Emits `count` 3D particles into the world's `NiagaraSystem3D` with zero heap allocations.
3631    ///
3632    /// # Arguments
3633    ///
3634    /// - `&NiagaraEmitterConfig3D` - Emitter properties.
3635    /// - `usize` - Number of particles to emit.
3636    ///
3637    /// # Returns
3638    ///
3639    /// - `usize` - Active particle count after emission.
3640    pub fn emit_particles_3d(&mut self, config: &NiagaraEmitterConfig3D, count: usize) -> usize {
3641        self.get_mut_niagara().emit_burst(count, config);
3642        let active: usize = self.get_niagara().get_active_count();
3643        if count > 0 {
3644            self.bump_world_revision();
3645        }
3646        active
3647    }
3648
3649    /// 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.
3650    ///
3651    /// # Arguments
3652    ///
3653    /// - `i32` - City block half-radius (`1..=5`, producing `(2r+1)x(2r+1)` multi-tower blocks).
3654    ///
3655    /// # Returns
3656    ///
3657    /// - `Self` - Populated dense 3D open-world metropolis with built static/dynamic BVHs.
3658    #[must_use]
3659    pub fn create_dense_open_world_city(blocks_radius: i32) -> Self {
3660        let radius: i32 = blocks_radius.clamp(1, 5);
3661        let mut world: Self = Self::create_open_world_city();
3662        let dense_occluder: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
3663            DENSE_TOWER_MESH_NAME,
3664            1.0,
3665            1.0,
3666            1.0,
3667            true,
3668            PbrMaterial::default(),
3669        )));
3670        let archetypes: [usize; 6] = world.register_building_archetypes();
3671        let facades: [PbrMaterial; 6] = Self::curated_skyline_palettes();
3672        let neon_palette: [Color; 4] = [
3673            Color::hex(0x38BDF8),
3674            Color::hex(0xF43F5E),
3675            Color::hex(0xA855F7),
3676            Color::hex(0x34D399),
3677        ];
3678        let mut serial: usize = 0;
3679        for bx in -radius..=radius {
3680            for bz in -radius..=radius {
3681                if bx == 0 && (-3..=3).contains(&bz) {
3682                    continue;
3683                }
3684                let center_x: f32 = (bx as f32) * 26.0;
3685                let center_z: f32 = (bz as f32) * 24.0 - 16.0;
3686                for sub in 0..4usize {
3687                    let off_x: f32 = if (sub & 1) == 0 { -5.5 } else { 5.5 };
3688                    let off_z: f32 = if (sub & 2) == 0 { -5.5 } else { 5.5 };
3689                    let px: f32 = center_x + off_x;
3690                    let pz: f32 = center_z + off_z;
3691                    let (d_spine, _): (f32, f32) = Self::loop_lateral_offset(px, pz);
3692                    if (49.0..=79.0).contains(&d_spine) || px > 134.0 {
3693                        continue;
3694                    }
3695                    let height_m: f32 = 16.0 + (((serial * 11 + sub * 7) % 6) as f32) * 8.0;
3696                    let width_m: f32 = 8.0 + ((serial % 3) as f32) * 1.4;
3697                    let mat: PbrMaterial = facades[serial % facades.len()];
3698                    let mesh_id: usize = if sub % 2 == 0 {
3699                        dense_occluder
3700                    } else {
3701                        archetypes[(serial + sub) % archetypes.len()]
3702                    };
3703                    let _: usize = world.spawn_object(
3704                        &format!("dense_bldg_{serial}"),
3705                        mesh_id,
3706                        Transform3D::new(
3707                            Vec3::new(px, 0.0, pz),
3708                            0.0,
3709                            Vec3::new(width_m, height_m, 9.0),
3710                        ),
3711                        mat,
3712                        true,
3713                    );
3714                    serial += 1;
3715                }
3716                if (bx + bz).abs() <= 2 && world.get_point_lights().len() < 32 {
3717                    let _: usize = world.add_point_light(PointLight3D::new(
3718                        Vec3::new(center_x, 7.0, center_z),
3719                        neon_palette[serial % neon_palette.len()],
3720                        4.5,
3721                        22.0,
3722                    ));
3723                }
3724            }
3725        }
3726        world.ensure_bvh();
3727        world
3728    }
3729
3730    /// Cycles the active 3D camera perspective (`Chase` -> `Hood` -> `Orbit` -> `Aerial`) safely without clipping.
3731    ///
3732    /// # Arguments
3733    ///
3734    /// - `&Self` - Mutable world.
3735    ///
3736    /// # Returns
3737    ///
3738    /// - `u8` - New active camera mode index.
3739    pub fn cycle_camera_mode(&mut self) -> u8 {
3740        let next: u8 = (self.get_camera_mode() + 1) % 4;
3741        self.set_camera_mode(next);
3742        next
3743    }
3744
3745    /// Computes horizontal playable world bounds from non-solid ground meshes when present, preventing hardcoded invisible walls.
3746    ///
3747    /// # Arguments
3748    ///
3749    /// - `&Self` - World reference.
3750    ///
3751    /// # Returns
3752    ///
3753    /// - `Option<(f32, f32, f32, f32)>` - `(min_x, max_x, min_z, max_z)` horizontal ground limits.
3754    #[must_use]
3755    pub fn ground_play_bounds(&self) -> Option<(f32, f32, f32, f32)> {
3756        let mut found: bool = false;
3757        let mut min_x: f32 = f32::INFINITY;
3758        let mut max_x: f32 = f32::NEG_INFINITY;
3759        let mut min_z: f32 = f32::INFINITY;
3760        let mut max_z: f32 = f32::NEG_INFINITY;
3761        for obj in self.get_objects().iter() {
3762            if obj.get_ray_trace_caster()
3763                || obj.get_material().get_surface_detail() == SurfaceDetailMode::OceanWater
3764            {
3765                continue;
3766            }
3767            let blue_val: AxisAlignedBox3D = obj.get_world_bounds();
3768            let span_x: f32 = blue_val.get_max().get_x() - blue_val.get_min().get_x();
3769            let span_z: f32 = blue_val.get_max().get_z() - blue_val.get_min().get_z();
3770            if span_x >= 16.0 && span_z >= 16.0 {
3771                min_x = min_x.min(blue_val.get_min().get_x());
3772                max_x = max_x.max(blue_val.get_max().get_x());
3773                min_z = min_z.min(blue_val.get_min().get_z());
3774                max_z = max_z.max(blue_val.get_max().get_z());
3775                found = true;
3776            }
3777        }
3778        if found {
3779            Some((min_x, max_x, min_z, max_z))
3780        } else {
3781            None
3782        }
3783    }
3784
3785    /// Tests a world-space `OrientedBox3D` against every solid (`solid_collider || ray_trace_caster`) model's real mesh triangles and closed solid interiors (excluding `ignore_idx`), returning the deepest penetration hit.
3786    ///
3787    /// # Arguments
3788    ///
3789    /// - `&Self` - World reference.
3790    /// - `OrientedBox3D` - Candidate oriented bounding box in world space.
3791    /// - `Option<usize>` - Optional scene object index to exclude (self).
3792    ///
3793    /// # Returns
3794    ///
3795    /// - `Option<MeshCollisionHit3D>` - Deepest real-mesh triangle or closed-volume collision contact, or `None` when clear.
3796    #[must_use]
3797    pub fn mesh_oriented_box_collision(
3798        &self,
3799        candidate: OrientedBox3D,
3800        ignore_idx: Option<usize>,
3801    ) -> Option<MeshCollisionHit3D> {
3802        let query_bounds: AxisAlignedBox3D = candidate.to_world_bounds();
3803        let mut deepest: Option<MeshCollisionHit3D> = None;
3804        let objects: &[SceneObject3D] = self.get_objects().as_slice();
3805        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
3806        for (idx, obj) in objects.iter().enumerate() {
3807            if ignore_idx == Some(idx) || !(obj.get_solid_collider() || obj.get_ray_trace_caster())
3808            {
3809                continue;
3810            }
3811            let obj_bounds: AxisAlignedBox3D = obj.get_world_bounds();
3812            if !Self::boxes_overlap(query_bounds, obj_bounds) {
3813                continue;
3814            }
3815            let Some(mesh) = mesh_lib
3816                .get(obj.get_mesh_id())
3817                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
3818            else {
3819                continue;
3820            };
3821            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
3822            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
3823            let obj_tr: Transform3D = obj.get_transform();
3824            let model_mat: Mat4 = obj_tr.to_mat4();
3825            let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
3826            let mut hit_this_obj: bool = false;
3827            if meshlets.is_empty() {
3828                for tri in indices.iter() {
3829                    let (i0, i1, i2): (usize, usize, usize) =
3830                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
3831                    if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
3832                        let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
3833                        let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
3834                        let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
3835                        if let Some((normal, pen, contact)) =
3836                            candidate.intersect_triangle_world(w0, w1, w2)
3837                        {
3838                            hit_this_obj = true;
3839                            let replace: bool = deepest
3840                                .map(|delta_val: MeshCollisionHit3D| {
3841                                    pen > delta_val.get_penetration()
3842                                })
3843                                .unwrap_or(true);
3844                            if replace {
3845                                deepest = Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
3846                            }
3847                        }
3848                    }
3849                }
3850            } else {
3851                for ml in meshlets.iter() {
3852                    let ml_bounds: AxisAlignedBox3D = model_mat.transform_bounds(ml.get_bounds());
3853                    if !Self::boxes_overlap(query_bounds, ml_bounds) {
3854                        continue;
3855                    }
3856                    let start: usize = ml.get_first_tri() as usize;
3857                    let end: usize = start
3858                        .saturating_add(ml.get_tri_count() as usize)
3859                        .min(indices.len());
3860                    for tri in indices[start..end].iter() {
3861                        let (i0, i1, i2): (usize, usize, usize) =
3862                            (tri[0] as usize, tri[1] as usize, tri[2] as usize);
3863                        if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
3864                            let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
3865                            let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
3866                            let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
3867                            if let Some((normal, pen, contact)) =
3868                                candidate.intersect_triangle_world(w0, w1, w2)
3869                            {
3870                                hit_this_obj = true;
3871                                let replace: bool = deepest
3872                                    .map(|distance_val: MeshCollisionHit3D| {
3873                                        pen > distance_val.get_penetration()
3874                                    })
3875                                    .unwrap_or(true);
3876                                if replace {
3877                                    deepest =
3878                                        Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
3879                                }
3880                            }
3881                        }
3882                    }
3883                }
3884            }
3885            if !hit_this_obj
3886                && mesh.get_is_closed()
3887                && Self::point_in_bounds(candidate.get_center(), obj_bounds)
3888                && let Some(inside_hit) =
3889                    Self::point_inside_closed_mesh_mtv(idx, candidate, verts, indices, model_mat)
3890            {
3891                let replace: bool = deepest
3892                    .map(|prev_hit: MeshCollisionHit3D| {
3893                        inside_hit.get_penetration() > prev_hit.get_penetration()
3894                    })
3895                    .unwrap_or(true);
3896                if replace {
3897                    deepest = Some(inside_hit);
3898                }
3899            }
3900        }
3901        deepest
3902    }
3903
3904    /// Tests whether a world-space point lies strictly inside an axis-aligned bounding box.
3905    ///
3906    /// # Arguments
3907    ///
3908    /// - `Vec3` - Query point in world space.
3909    /// - `AxisAlignedBox3D` - World-space axis-aligned bounding box.
3910    ///
3911    /// # Returns
3912    ///
3913    /// - `bool` - `true` when the point lies inside the bounding box on all three axes.
3914    #[inline]
3915    #[must_use]
3916    fn point_in_bounds(point: Vec3, bounds: AxisAlignedBox3D) -> bool {
3917        let bmin: Vec3 = bounds.get_min();
3918        let bmax: Vec3 = bounds.get_max();
3919        point.get_x() >= bmin.get_x()
3920            && point.get_x() <= bmax.get_x()
3921            && point.get_y() >= bmin.get_y()
3922            && point.get_y() <= bmax.get_y()
3923            && point.get_z() >= bmin.get_z()
3924            && point.get_z() <= bmax.get_z()
3925    }
3926
3927    /// Computes the exact closest point on a 3D triangle `(v0, v1, v2)` to query point `point`.
3928    ///
3929    /// # Arguments
3930    ///
3931    /// - `Vec3` - Query point in world space.
3932    /// - `Vec3` - Triangle vertex 0.
3933    /// - `Vec3` - Triangle vertex 1.
3934    /// - `Vec3` - Triangle vertex 2.
3935    ///
3936    /// # Returns
3937    ///
3938    /// - `Vec3` - Closest point lying on or inside the triangle.
3939    #[inline]
3940    #[must_use]
3941    fn closest_point_on_triangle(point: Vec3, v0: Vec3, v1: Vec3, v2: Vec3) -> Vec3 {
3942        let ab: Vec3 = v1.sub(v0);
3943        let ac: Vec3 = v2.sub(v0);
3944        let ap: Vec3 = point.sub(v0);
3945        let d1: f32 = ab.dot(ap);
3946        let d2: f32 = ac.dot(ap);
3947        if d1 <= 0.0 && d2 <= 0.0 {
3948            return v0;
3949        }
3950        let bp: Vec3 = point.sub(v1);
3951        let d3: f32 = ab.dot(bp);
3952        let d4: f32 = ac.dot(bp);
3953        if d3 >= 0.0 && d4 <= d3 {
3954            return v1;
3955        }
3956        let vc: f32 = d1 * d4 - d3 * d2;
3957        if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
3958            let weight_v: f32 = d1 / (d1 - d3).max(1.0e-7);
3959            return v0.add(ab.scale(weight_v));
3960        }
3961        let cp: Vec3 = point.sub(v2);
3962        let d5: f32 = ab.dot(cp);
3963        let d6: f32 = ac.dot(cp);
3964        if d6 >= 0.0 && d5 <= d6 {
3965            return v2;
3966        }
3967        let vb: f32 = d5 * d2 - d1 * d6;
3968        if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
3969            let weight_w: f32 = d2 / (d2 - d6).max(1.0e-7);
3970            return v0.add(ac.scale(weight_w));
3971        }
3972        let va: f32 = d3 * d6 - d5 * d4;
3973        if va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0 {
3974            let denom_bc: f32 = ((d4 - d3) + (d5 - d6)).max(1.0e-7);
3975            let weight_w: f32 = (d4 - d3) / denom_bc;
3976            return v1.add(v2.sub(v1).scale(weight_w));
3977        }
3978        let denom: f32 = (va + vb + vc).max(1.0e-7);
3979        let weight_v: f32 = vb / denom;
3980        let weight_w: f32 = vc / denom;
3981        v0.add(ab.scale(weight_v)).add(ac.scale(weight_w))
3982    }
3983
3984    /// Detects whether an `OrientedBox3D` lies strictly inside a closed solid triangle mesh using odd-even ray parity and returns an outward MTV pushing the box out through the nearest exterior wall.
3985    ///
3986    /// # Arguments
3987    ///
3988    /// - `usize` - Solid scene object index in `World3D::objects`.
3989    /// - `OrientedBox3D` - Candidate oriented bounding box in world space.
3990    /// - `&[Vertex3D]` - Local mesh vertex buffer.
3991    /// - `&[[u32; 3]]` - Local mesh triangle index buffer.
3992    /// - `Mat4` - World model transform matrix of the solid mesh.
3993    ///
3994    /// # Returns
3995    ///
3996    /// - `Option<MeshCollisionHit3D>` - Outward minimum-translation-vector hit when strictly inside the closed solid, or `None` when outside (e.g. open archway tunnels).
3997    #[must_use]
3998    fn point_inside_closed_mesh_mtv(
3999        obj_idx: usize,
4000        candidate: OrientedBox3D,
4001        verts: &[Vertex3D],
4002        indices: &[[u32; 3]],
4003        model_mat: Mat4,
4004    ) -> Option<MeshCollisionHit3D> {
4005        let center: Vec3 = candidate.get_center();
4006        let parity_dir: Vec3 = Vec3::new(1.0, 1.37e-4, 2.71e-4).normalize();
4007        let mut crossings: u32 = 0;
4008        let mut best_horiz_dist_sq: f32 = f32::INFINITY;
4009        let mut best_horiz_cp: Vec3 = center;
4010        let mut best_horiz_n: Vec3 = Vec3::new(1.0, 0.0, 0.0);
4011        let mut best_any_dist_sq: f32 = f32::INFINITY;
4012        let mut best_any_cp: Vec3 = center;
4013        let mut best_any_n: Vec3 = Vec3::new(1.0, 0.0, 0.0);
4014        for tri in indices.iter() {
4015            let (i0, i1, i2): (usize, usize, usize) =
4016                (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4017            if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
4018                continue;
4019            }
4020            let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
4021            let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
4022            let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
4023            if Self::ray_intersect_triangle(center, parity_dir, w0, w1, w2, 1.0e-5, f32::INFINITY)
4024                .is_some()
4025            {
4026                crossings = crossings.wrapping_add(1);
4027            }
4028            let cp: Vec3 = Self::closest_point_on_triangle(center, w0, w1, w2);
4029            let delta: Vec3 = cp.sub(center);
4030            let dist_sq: f32 = delta.length_sq();
4031            let raw_face_n: Vec3 = w1.sub(w0).cross(w2.sub(w0));
4032            let face_n: Vec3 = if raw_face_n.length_sq() > 1.0e-10 {
4033                raw_face_n.normalize()
4034            } else {
4035                Vec3::new(1.0, 0.0, 0.0)
4036            };
4037            if dist_sq < best_any_dist_sq {
4038                best_any_dist_sq = dist_sq;
4039                best_any_cp = cp;
4040                best_any_n = face_n;
4041            }
4042            let horiz_mag_sq: f32 =
4043                face_n.get_x() * face_n.get_x() + face_n.get_z() * face_n.get_z();
4044            if horiz_mag_sq > 0.25 && dist_sq < best_horiz_dist_sq {
4045                best_horiz_dist_sq = dist_sq;
4046                best_horiz_cp = cp;
4047                best_horiz_n = Vec3::new(face_n.get_x(), 0.0, face_n.get_z()).normalize();
4048            }
4049        }
4050        if (crossings & 1) == 0 {
4051            return None;
4052        }
4053        let (target_cp, fallback_n, target_dist_sq): (Vec3, Vec3, f32) =
4054            if best_horiz_dist_sq.is_finite() {
4055                (best_horiz_cp, best_horiz_n, best_horiz_dist_sq)
4056            } else if best_any_dist_sq.is_finite() {
4057                (best_any_cp, best_any_n, best_any_dist_sq)
4058            } else {
4059                return None;
4060            };
4061        let push_raw: Vec3 = target_cp.sub(center);
4062        let push_n: Vec3 = if push_raw.length_sq() > 1.0e-8 {
4063            push_raw.normalize()
4064        } else {
4065            fallback_n
4066        };
4067        let axes: [Vec3; 3] = candidate.get_axes();
4068        let half_extents: Vec3 = candidate.get_half_extents();
4069        let obb_proj: f32 = axes[0].dot(push_n).abs() * half_extents.get_x()
4070            + axes[1].dot(push_n).abs() * half_extents.get_y()
4071            + axes[2].dot(push_n).abs() * half_extents.get_z();
4072        let total_pen: f32 = target_dist_sq.sqrt() + obb_proj;
4073        Some(MeshCollisionHit3D::new(
4074            obj_idx, push_n, total_pen, target_cp,
4075        ))
4076    }
4077
4078    /// Resolves a unit horizontal separation normal against `obj_idx` so wall sliding and MTV push-out stay smooth even when contacting low curbs or seawalls whose top caps overlap vertically.
4079    ///
4080    /// # Arguments
4081    ///
4082    /// - `&Self` - World reference.
4083    /// - `OrientedBox3D` - Candidate oriented bounding box in world space.
4084    /// - `usize` - Colliding solid scene object index.
4085    ///
4086    /// # Returns
4087    ///
4088    /// - `Vec3` - Unit horizontal outward separation normal in the XZ plane, or `Vec3::zero()` if degenerate.
4089    #[must_use]
4090    fn horizontal_collision_normal(&self, candidate: OrientedBox3D, obj_idx: usize) -> Vec3 {
4091        let Some(obj) = self.get_objects().get(obj_idx) else {
4092            return Vec3::zero();
4093        };
4094        if let Some(mesh) = self
4095            .get_mesh_library()
4096            .get(obj.get_mesh_id())
4097            .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
4098        {
4099            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
4100            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
4101            let model_mat: Mat4 = obj.get_transform().to_mat4();
4102            let mut best_pen: f32 = f32::INFINITY;
4103            let mut best_hn: Vec3 = Vec3::zero();
4104            for tri in indices.iter() {
4105                let (i0, i1, i2): (usize, usize, usize) =
4106                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4107                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
4108                    let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
4109                    let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
4110                    let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
4111                    if let Some((normal, pen, _)) = candidate.intersect_triangle_world(w0, w1, w2) {
4112                        let hn: Vec3 = Vec3::new(normal.get_x(), 0.0, normal.get_z());
4113                        if hn.length_sq() > 0.25 && pen < best_pen {
4114                            best_pen = pen;
4115                            best_hn = hn.normalize();
4116                        }
4117                    }
4118                }
4119            }
4120            if best_hn.length_sq() > 1.0e-6 {
4121                return best_hn;
4122            }
4123        }
4124        let bounds: AxisAlignedBox3D = obj.get_world_bounds();
4125        let bcenter: Vec3 = bounds.get_min().add(bounds.get_max()).scale(0.5);
4126        let diff: Vec3 = candidate.get_center().sub(bcenter);
4127        let horiz: Vec3 = Vec3::new(diff.get_x(), 0.0, diff.get_z());
4128        if horiz.length_sq() > 1.0e-6 {
4129            horiz.normalize()
4130        } else {
4131            Vec3::new(1.0, 0.0, 0.0)
4132        }
4133    }
4134
4135    /// Clamps a horizontal world position to playable island ground limits when present.
4136    ///
4137    /// # Arguments
4138    ///
4139    /// - `Vec3` - Candidate world position.
4140    /// - `Option<(f32, f32, f32, f32)>` - Optional playable horizontal `(min_x, max_x, min_z, max_z)` bounds.
4141    /// - `f32` - Vehicle horizontal margin in meters.
4142    ///
4143    /// # Returns
4144    ///
4145    /// - `Vec3` - Ground-clamped world position.
4146    #[inline]
4147    #[must_use]
4148    fn clamp_horizontal_to_ground(
4149        mut pos: Vec3,
4150        ground_limits: Option<(f32, f32, f32, f32)>,
4151        ground_margin: f32,
4152    ) -> Vec3 {
4153        if let Some((gx0, gx1, gz0, gz1)) = ground_limits {
4154            let lo_x: f32 = (gx0 + ground_margin).min(gx1);
4155            let hi_x: f32 = (gx1 - ground_margin).max(lo_x);
4156            let lo_z: f32 = (gz0 + ground_margin).min(gz1);
4157            let hi_z: f32 = (gz1 - ground_margin).max(lo_z);
4158            pos.set_x(pos.get_x().clamp(lo_x, hi_x));
4159            pos.set_z(pos.get_z().clamp(lo_z, hi_z));
4160        }
4161        pos
4162    }
4163
4164    /// Iteratively pushes a penetrating vehicle horizontally out of solid obstacles along the minimum-translation-vector normal until collision-free.
4165    ///
4166    /// # Arguments
4167    ///
4168    /// - `&Self` - World reference.
4169    /// - `&mut Transform3D` - Candidate vehicle transform adjusted in place when penetrating.
4170    /// - `AxisAlignedBox3D` - Vehicle local mesh bounds.
4171    /// - `usize` - Vehicle object index to ignore during self-test.
4172    /// - `Option<(f32, f32, f32, f32)>` - Optional playable ground bounds.
4173    /// - `f32` - Horizontal ground margin in meters.
4174    ///
4175    /// # Returns
4176    ///
4177    /// - `bool` - `true` when the transform was moved to resolve penetration.
4178    fn depenetrate_vehicle_horizontally(
4179        &self,
4180        transform_val: &mut Transform3D,
4181        mesh_bounds: AxisAlignedBox3D,
4182        vehicle_idx: usize,
4183        ground_limits: Option<(f32, f32, f32, f32)>,
4184        ground_margin: f32,
4185    ) -> bool {
4186        let mut adjusted: bool = false;
4187        for _ in 0..COLLISION_MTV_MAX_ITERS {
4188            let Some(hit) = self.collides_with_obstacles(*transform_val, mesh_bounds, vehicle_idx)
4189            else {
4190                break;
4191            };
4192            let raw_hn: Vec3 = Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
4193            let hn: Vec3 = if raw_hn.length_sq() > 1.0e-4 {
4194                raw_hn.normalize()
4195            } else {
4196                self.horizontal_collision_normal(
4197                    transform_val.to_oriented_box(mesh_bounds),
4198                    hit.get_object_index(),
4199                )
4200            };
4201            if hn.length_sq() <= 1.0e-6 {
4202                break;
4203            }
4204            let push_dist: f32 = hit.get_penetration() + COLLISION_MTV_PUSH_EPS;
4205            let cur_pos: Vec3 = transform_val.get_position();
4206            let pushed_pos: Vec3 = Self::clamp_horizontal_to_ground(
4207                Vec3::new(
4208                    cur_pos.get_x() + hn.get_x() * push_dist,
4209                    cur_pos.get_y(),
4210                    cur_pos.get_z() + hn.get_z() * push_dist,
4211                ),
4212                ground_limits,
4213                ground_margin,
4214            );
4215            transform_val.set_position(pushed_pos);
4216            adjusted = true;
4217        }
4218        adjusted
4219    }
4220
4221    /// Casts a world-space ray against every solid (`ray_trace_caster == true`) model's real mesh triangles (excluding `ignore_idx`) up to `max_dist`.
4222    ///
4223    /// # Arguments
4224    ///
4225    /// - `&Self` - World reference.
4226    /// - `Vec3` - Ray origin in world space.
4227    /// - `Vec3` - Unit ray direction in world space.
4228    /// - `f32` - Maximum ray distance.
4229    /// - `Option<usize>` - Optional scene object index to exclude.
4230    ///
4231    /// # Returns
4232    ///
4233    /// - `Option<RayHit3D>` - Closest real-mesh triangle intersection within `(1e-4, max_dist]`.
4234    #[must_use]
4235    pub fn raycast_solid_meshes(
4236        &self,
4237        origin: Vec3,
4238        direction: Vec3,
4239        max_dist: f32,
4240        ignore_idx: Option<usize>,
4241    ) -> Option<RayHit3D> {
4242        let dir: Vec3 = direction.normalize();
4243        let inv_dir: Vec3 = Ray3D::safe_inv_vec(dir);
4244        let t_min: f32 = 1e-4;
4245        let mut best_t: f32 = max_dist;
4246        let mut best_hit: Option<RayHit3D> = None;
4247        let objects: &[SceneObject3D] = self.get_objects().as_slice();
4248        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
4249        let ignore_is_static_caster: bool = ignore_idx
4250            .and_then(|idx: usize| objects.get(idx))
4251            .is_some_and(|obj: &SceneObject3D| obj.get_ray_trace_caster() && !obj.get_is_dynamic());
4252        let use_static_bvh: bool =
4253            !self.get_bvh_dirty() && !self.get_bvh().is_empty() && !ignore_is_static_caster;
4254        if use_static_bvh
4255            && let Some((hit_dist, tri_idx)) = self
4256                .get_bvh()
4257                .trace_closest_raw(origin, dir, inv_dir, t_min, best_t)
4258        {
4259            let bvh_tris: &[BvhTriangle] = self.get_bvh().get_triangles().as_slice();
4260            if let Some(hit_tri) = bvh_tris.get(tri_idx) {
4261                let raw_normal: Vec3 = hit_tri.get_normal();
4262                let oriented_normal: Vec3 = if raw_normal.dot(dir) > 0.0 {
4263                    raw_normal.scale(-1.0)
4264                } else {
4265                    raw_normal
4266                };
4267                best_t = hit_dist;
4268                best_hit = Some(RayHit3D {
4269                    distance: hit_dist,
4270                    point: origin.add(dir.scale(hit_dist)),
4271                    normal: oriented_normal,
4272                    material: hit_tri.get_material(),
4273                });
4274            }
4275        }
4276        for (idx, obj) in objects.iter().enumerate() {
4277            if ignore_idx == Some(idx) || !(obj.get_solid_collider() || obj.get_ray_trace_caster())
4278            {
4279                continue;
4280            }
4281            if use_static_bvh && obj.get_ray_trace_caster() && !obj.get_is_dynamic() {
4282                continue;
4283            }
4284            if !obj
4285                .get_world_bounds()
4286                .intersect_ray_near(origin, inv_dir, t_min, best_t)
4287                .is_finite()
4288            {
4289                continue;
4290            }
4291            let Some(mesh) = mesh_lib
4292                .get(obj.get_mesh_id())
4293                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
4294            else {
4295                continue;
4296            };
4297            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
4298            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
4299            let model_mat: Mat4 = obj.get_transform().to_mat4();
4300            let mat: PbrMaterial = obj.get_material();
4301            for tri in indices.iter() {
4302                let (i0, i1, i2): (usize, usize, usize) =
4303                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4304                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
4305                    let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
4306                    let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
4307                    let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
4308                    if let Some((blend_factor, normal)) =
4309                        Self::ray_intersect_triangle(origin, dir, w0, w1, w2, t_min, best_t)
4310                    {
4311                        best_t = blend_factor;
4312                        best_hit = Some(RayHit3D {
4313                            distance: blend_factor,
4314                            point: origin.add(dir.scale(blend_factor)),
4315                            normal,
4316                            material: mat,
4317                        });
4318                    }
4319                }
4320            }
4321        }
4322        best_hit
4323    }
4324
4325    /// Tests whether two world-space `AxisAlignedBox3D` boxes overlap strictly.
4326    ///
4327    /// # Arguments
4328    ///
4329    /// - `AxisAlignedBox3D` - First bounding box.
4330    /// - `AxisAlignedBox3D` - Second bounding box.
4331    ///
4332    /// # Returns
4333    ///
4334    /// - `bool` - `true` when both axis-aligned bounding boxes overlap on all three axes.
4335    #[inline]
4336    #[must_use]
4337    fn boxes_overlap(alpha_val: AxisAlignedBox3D, blue_val: AxisAlignedBox3D) -> bool {
4338        let ox: bool = alpha_val.get_min().get_x() < blue_val.get_max().get_x()
4339            && alpha_val.get_max().get_x() > blue_val.get_min().get_x();
4340        let oy: bool = alpha_val.get_min().get_y() < blue_val.get_max().get_y()
4341            && alpha_val.get_max().get_y() > blue_val.get_min().get_y();
4342        let oz: bool = alpha_val.get_min().get_z() < blue_val.get_max().get_z()
4343            && alpha_val.get_max().get_z() > blue_val.get_min().get_z();
4344        ox && oy && oz
4345    }
4346
4347    /// Double-sided Möller-Trumbore ray-triangle intersection returning `(t, outward_unit_normal)`.
4348    ///
4349    /// # Arguments
4350    ///
4351    /// - `Vec3` - Ray origin.
4352    /// - `Vec3` - Unit ray direction.
4353    /// - `Vec3` - Triangle vertex 0.
4354    /// - `Vec3` - Triangle vertex 1.
4355    /// - `Vec3` - Triangle vertex 2.
4356    /// - `f32` - Minimum ray parameter `t`.
4357    /// - `f32` - Maximum ray parameter `t`.
4358    ///
4359    /// # Returns
4360    ///
4361    /// - `Option<(f32, Vec3)>` - Hit distance and facing unit normal.
4362    #[inline]
4363    #[must_use]
4364    fn ray_intersect_triangle(
4365        origin: Vec3,
4366        dir: Vec3,
4367        v0: Vec3,
4368        v1: Vec3,
4369        v2: Vec3,
4370        t_min: f32,
4371        t_max: f32,
4372    ) -> Option<(f32, Vec3)> {
4373        let e1: Vec3 = v1.sub(v0);
4374        let e2: Vec3 = v2.sub(v0);
4375        let pvec: Vec3 = dir.cross(e2);
4376        let det: f32 = e1.dot(pvec);
4377        if det.abs() < 1e-7 {
4378            return None;
4379        }
4380        let inv_det: f32 = 1.0 / det;
4381        let tvec: Vec3 = origin.sub(v0);
4382        let tex_u: f32 = tvec.dot(pvec) * inv_det;
4383        if !(0.0..=1.0).contains(&tex_u) {
4384            return None;
4385        }
4386        let qvec: Vec3 = tvec.cross(e1);
4387        let item_val: f32 = dir.dot(qvec) * inv_det;
4388        if item_val < 0.0 || tex_u + item_val > 1.0 {
4389            return None;
4390        }
4391        let blend_factor: f32 = e2.dot(qvec) * inv_det;
4392        if blend_factor <= t_min || blend_factor > t_max {
4393            return None;
4394        }
4395        let raw_n: Vec3 = e1.cross(e2).normalize();
4396        let normal: Vec3 = if raw_n.dot(dir) > 0.0 {
4397            raw_n.scale(-1.0)
4398        } else {
4399            raw_n
4400        };
4401        Some((blend_factor, normal))
4402    }
4403
4404    /// Tests whether a candidate transformed mesh collides with any solid obstacle's real triangles excluding `ignore_idx`.
4405    ///
4406    /// # Arguments
4407    ///
4408    /// - `&Self` - World reference.
4409    /// - `Transform3D` - Candidate object transform.
4410    /// - `AxisAlignedBox3D` - Candidate local mesh bounds.
4411    /// - `usize` - Self object index to skip.
4412    ///
4413    /// # Returns
4414    ///
4415    /// - `Option<MeshCollisionHit3D>` - Deepest real-mesh collision hit, or `None` when clear.
4416    #[must_use]
4417    fn collides_with_obstacles(
4418        &self,
4419        candidate_tr: Transform3D,
4420        local_bounds: AxisAlignedBox3D,
4421        ignore_idx: usize,
4422    ) -> Option<MeshCollisionHit3D> {
4423        let oriented_box: OrientedBox3D = candidate_tr.to_oriented_box(local_bounds);
4424        self.mesh_oriented_box_collision(oriented_box, Some(ignore_idx))
4425    }
4426
4427    /// Tests a world-space `OrientedBox3D` against every static solid (`!is_dynamic && (solid_collider || ray_trace_caster)`) obstacle mesh, returning the deepest penetration contact.
4428    ///
4429    /// # Arguments
4430    ///
4431    /// - `OrientedBox3D` - Candidate oriented bounding box in world space.
4432    /// - `Option<usize>` - Optional scene object index to exclude.
4433    ///
4434    /// # Returns
4435    ///
4436    /// - `Option<MeshCollisionHit3D>` - Deepest static-world collision hit, or `None` when clear.
4437    #[must_use]
4438    fn mesh_oriented_box_static_collision(
4439        &self,
4440        candidate: OrientedBox3D,
4441        ignore_idx: Option<usize>,
4442    ) -> Option<MeshCollisionHit3D> {
4443        let query_bounds: AxisAlignedBox3D = candidate.to_world_bounds();
4444        let mut deepest: Option<MeshCollisionHit3D> = None;
4445        let objects: &[SceneObject3D] = self.get_objects().as_slice();
4446        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
4447        for (idx, obj) in objects.iter().enumerate() {
4448            let is_solid: bool = obj.get_solid_collider() || obj.get_ray_trace_caster();
4449            if ignore_idx == Some(idx) || obj.get_is_dynamic() || !is_solid {
4450                continue;
4451            }
4452            let obj_bounds: AxisAlignedBox3D = obj.get_world_bounds();
4453            if !Self::boxes_overlap(query_bounds, obj_bounds) {
4454                continue;
4455            }
4456            let Some(mesh) = mesh_lib
4457                .get(obj.get_mesh_id())
4458                .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
4459            else {
4460                continue;
4461            };
4462            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
4463            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
4464            let model_mat: Mat4 = obj.get_transform().to_mat4();
4465            let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
4466            let mut hit_this_obj: bool = false;
4467            if meshlets.is_empty() {
4468                for tri in indices.iter() {
4469                    let (i0, i1, i2): (usize, usize, usize) =
4470                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4471                    if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
4472                        let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
4473                        let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
4474                        let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
4475                        if let Some((normal, pen, contact)) =
4476                            candidate.intersect_triangle_world(w0, w1, w2)
4477                        {
4478                            hit_this_obj = true;
4479                            let replace: bool = deepest
4480                                .map(|prev: MeshCollisionHit3D| pen > prev.get_penetration())
4481                                .unwrap_or(true);
4482                            if replace {
4483                                deepest = Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
4484                            }
4485                        }
4486                    }
4487                }
4488            } else {
4489                for ml in meshlets.iter() {
4490                    let ml_bounds: AxisAlignedBox3D = model_mat.transform_bounds(ml.get_bounds());
4491                    if !Self::boxes_overlap(query_bounds, ml_bounds) {
4492                        continue;
4493                    }
4494                    let start: usize = ml.get_first_tri() as usize;
4495                    let end: usize = start
4496                        .saturating_add(ml.get_tri_count() as usize)
4497                        .min(indices.len());
4498                    for tri in indices[start..end].iter() {
4499                        let (i0, i1, i2): (usize, usize, usize) =
4500                            (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4501                        if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
4502                            let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
4503                            let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
4504                            let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
4505                            if let Some((normal, pen, contact)) =
4506                                candidate.intersect_triangle_world(w0, w1, w2)
4507                            {
4508                                hit_this_obj = true;
4509                                let replace: bool = deepest
4510                                    .map(|prev: MeshCollisionHit3D| pen > prev.get_penetration())
4511                                    .unwrap_or(true);
4512                                if replace {
4513                                    deepest =
4514                                        Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
4515                                }
4516                            }
4517                        }
4518                    }
4519                }
4520            }
4521            if !hit_this_obj
4522                && mesh.get_is_closed()
4523                && Self::point_in_bounds(candidate.get_center(), obj_bounds)
4524                && let Some(inside_hit) =
4525                    Self::point_inside_closed_mesh_mtv(idx, candidate, verts, indices, model_mat)
4526            {
4527                let replace: bool = deepest
4528                    .map(|prev: MeshCollisionHit3D| {
4529                        inside_hit.get_penetration() > prev.get_penetration()
4530                    })
4531                    .unwrap_or(true);
4532                if replace {
4533                    deepest = Some(inside_hit);
4534                }
4535            }
4536        }
4537        deepest
4538    }
4539
4540    /// Iteratively pushes a penetrating vehicle horizontally out of static world obstacles along the minimum-translation-vector normal.
4541    ///
4542    /// # Arguments
4543    ///
4544    /// - `&mut Transform3D` - Candidate vehicle transform adjusted in place when penetrating.
4545    /// - `AxisAlignedBox3D` - Vehicle local mesh bounds.
4546    /// - `usize` - Vehicle object index to ignore.
4547    /// - `Option<(f32, f32, f32, f32)>` - Optional playable horizontal ground bounds.
4548    /// - `f32` - Horizontal ground margin in meters.
4549    ///
4550    /// # Returns
4551    ///
4552    /// - `bool` - `true` when the transform was moved to clear static penetration.
4553    fn depenetrate_vehicle_static_horizontally(
4554        &self,
4555        transform_val: &mut Transform3D,
4556        mesh_bounds: AxisAlignedBox3D,
4557        vehicle_idx: usize,
4558        ground_limits: Option<(f32, f32, f32, f32)>,
4559        ground_margin: f32,
4560    ) -> bool {
4561        let mut adjusted: bool = false;
4562        for _ in 0..COLLISION_MTV_MAX_ITERS {
4563            let Some(hit) = self.mesh_oriented_box_static_collision(
4564                transform_val.to_oriented_box(mesh_bounds),
4565                Some(vehicle_idx),
4566            ) else {
4567                break;
4568            };
4569            let raw_hn: Vec3 = Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
4570            let hn: Vec3 = if raw_hn.length_sq() > 1.0e-4 {
4571                raw_hn.normalize()
4572            } else {
4573                self.horizontal_collision_normal(
4574                    transform_val.to_oriented_box(mesh_bounds),
4575                    hit.get_object_index(),
4576                )
4577            };
4578            if hn.length_sq() <= 1.0e-6 {
4579                break;
4580            }
4581            let push_dist: f32 = hit.get_penetration() + COLLISION_MTV_PUSH_EPS;
4582            let cur_pos: Vec3 = transform_val.get_position();
4583            let pushed_pos: Vec3 = Self::clamp_horizontal_to_ground(
4584                Vec3::new(
4585                    cur_pos.get_x() + hn.get_x() * push_dist,
4586                    cur_pos.get_y(),
4587                    cur_pos.get_z() + hn.get_z() * push_dist,
4588                ),
4589                ground_limits,
4590                ground_margin,
4591            );
4592            transform_val.set_position(pushed_pos);
4593            adjusted = true;
4594        }
4595        adjusted
4596    }
4597
4598    /// Wraps an angle in radians into `(-PI, PI]`.
4599    ///
4600    /// # Arguments
4601    ///
4602    /// - `f32` - Unwrapped angle in radians.
4603    ///
4604    /// # Returns
4605    ///
4606    /// - `f32` - Shortest signed equivalent angle in `(-PI, PI]`.
4607    #[inline]
4608    #[must_use]
4609    fn wrap_angle_rad(angle: f32) -> f32 {
4610        let two_pi: f32 = 2.0 * PI;
4611        let wrapped: f32 = (angle + PI).rem_euclid(two_pi) - PI;
4612        if wrapped <= -PI {
4613            wrapped + two_pi
4614        } else {
4615            wrapped
4616        }
4617    }
4618
4619    /// Returns the local mesh bounding box for `mesh_id`, falling back to a unit vehicle box.
4620    ///
4621    /// # Arguments
4622    ///
4623    /// - `usize` - Mesh identifier inside `World3D::mesh_library`.
4624    ///
4625    /// # Returns
4626    ///
4627    /// - `AxisAlignedBox3D` - Local mesh bounds.
4628    #[must_use]
4629    fn local_bounds_for_mesh(&self, mesh_id: usize) -> AxisAlignedBox3D {
4630        self.get_mesh_library()
4631            .get(mesh_id)
4632            .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
4633            .map(Mesh3D::get_bounds)
4634            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)))
4635    }
4636
4637    /// Computes the true physical XZ contact point between a vehicle OBB and a static obstacle face so head-on wall impacts resolve cleanly at bumper center while angled hits and off-center corner clips preserve their exact rotational lever arm.
4638    ///
4639    /// # Arguments
4640    ///
4641    /// - `OrientedBox3D` - Colliding vehicle oriented bounding box.
4642    /// - `Vec3` - Unit outward horizontal wall normal pointing from obstacle into vehicle.
4643    /// - `AxisAlignedBox3D` - World-space bounding box of the colliding static obstacle.
4644    /// - `Vec3` - Fallback triangle contact point.
4645    ///
4646    /// # Returns
4647    ///
4648    /// - `Vec3` - Physical world-space contact point on the colliding bumper or corner.
4649    #[must_use]
4650    fn compute_static_contact_point(
4651        obb: OrientedBox3D,
4652        hn: Vec3,
4653        obstacle_bounds: AxisAlignedBox3D,
4654        fallback_contact: Vec3,
4655    ) -> Vec3 {
4656        let axes: [Vec3; 3] = obb.get_axes();
4657        let half: Vec3 = obb.get_half_extents();
4658        let center: Vec3 = obb.get_center();
4659        let ux: f32 = axes[0].get_x() * half.get_x();
4660        let uz: f32 = axes[0].get_z() * half.get_x();
4661        let vx: f32 = axes[2].get_x() * half.get_z();
4662        let vz: f32 = axes[2].get_z() * half.get_z();
4663        let cx: f32 = center.get_x();
4664        let cz: f32 = center.get_z();
4665        let corners: [(f32, f32); 4] = [
4666            (cx + ux + vx, cz + uz + vz),
4667            (cx + ux - vx, cz + uz - vz),
4668            (cx - ux + vx, cz - uz + vz),
4669            (cx - ux - vx, cz - uz - vz),
4670        ];
4671        let bmin: Vec3 = obstacle_bounds.get_min();
4672        let bmax: Vec3 = obstacle_bounds.get_max();
4673        let pad: f32 = 0.15;
4674        let in_obstacle: fn(f32, f32, Vec3, Vec3, f32) -> bool =
4675            |px: f32, pz: f32, lo: Vec3, hi: Vec3, margin: f32| -> bool {
4676                px >= lo.get_x() - margin
4677                    && px <= hi.get_x() + margin
4678                    && pz >= lo.get_z() - margin
4679                    && pz <= hi.get_z() + margin
4680            };
4681        let mut best_in_proj: f32 = f32::NEG_INFINITY;
4682        let mut any_in: bool = false;
4683        let mut best_all_proj: f32 = f32::NEG_INFINITY;
4684        for &(px, pz) in corners.iter() {
4685            let proj: f32 = -(px * hn.get_x() + pz * hn.get_z());
4686            if proj > best_all_proj {
4687                best_all_proj = proj;
4688            }
4689            if in_obstacle(px, pz, bmin, bmax, pad) {
4690                any_in = true;
4691                if proj > best_in_proj {
4692                    best_in_proj = proj;
4693                }
4694            }
4695        }
4696        let target_proj: f32 = if any_in { best_in_proj } else { best_all_proj };
4697        let mut sum_x: f32 = 0.0;
4698        let mut sum_z: f32 = 0.0;
4699        let mut cnt: f32 = 0.0;
4700        for &(px, pz) in corners.iter() {
4701            if any_in && !in_obstacle(px, pz, bmin, bmax, pad) {
4702                continue;
4703            }
4704            let proj: f32 = -(px * hn.get_x() + pz * hn.get_z());
4705            if proj >= target_proj - 0.16 {
4706                sum_x += px;
4707                sum_z += pz;
4708                cnt += 1.0;
4709            }
4710        }
4711        if cnt > 0.0 {
4712            Vec3::new(sum_x / cnt, fallback_contact.get_y().max(0.45), sum_z / cnt)
4713        } else {
4714            fallback_contact
4715        }
4716    }
4717
4718    /// Applies a physically based rigid-body restitution, Coulomb wall-scrape friction, and off-center corner spin torque impulse against an immovable static wall.
4719    ///
4720    /// # Arguments
4721    ///
4722    /// - `Vec3` - Vehicle center position in world space.
4723    /// - `&mut Vec3` - Mutable vehicle horizontal velocity updated in place.
4724    /// - `&mut f32` - Mutable vehicle yaw angular velocity updated in place.
4725    /// - `(f32, f32)` - `(inv_mass, inv_inertia_yaw)` rigid-body inertial properties.
4726    /// - `Vec3` - Unit horizontal outward wall normal pointing into the vehicle.
4727    /// - `Vec3` - World-space contact point on the colliding wall surface.
4728    ///
4729    /// # Returns
4730    ///
4731    /// - `f32` - Positive normal impact approach speed in meters per second (`0.0` when separating).
4732    fn apply_static_wall_impulse(
4733        car_pos: Vec3,
4734        vel: &mut Vec3,
4735        yaw_rate: &mut f32,
4736        inertia_pair: (f32, f32),
4737        hn: Vec3,
4738        contact_point: Vec3,
4739    ) -> f32 {
4740        let (inv_m, inv_i): (f32, f32) = inertia_pair;
4741        let raw_rx: f32 = contact_point.get_x() - car_pos.get_x();
4742        let raw_rz: f32 = contact_point.get_z() - car_pos.get_z();
4743        let r_len: f32 = (raw_rx * raw_rx + raw_rz * raw_rz).sqrt();
4744        let (rx, rz): (f32, f32) = if r_len > 2.6 {
4745            let scale_r: f32 = 2.6 / r_len;
4746            (raw_rx * scale_r, raw_rz * scale_r)
4747        } else {
4748            (raw_rx, raw_rz)
4749        };
4750        let v_pt_x: f32 = vel.get_x() + (*yaw_rate) * rz;
4751        let v_pt_z: f32 = vel.get_z() - (*yaw_rate) * rx;
4752        let v_n: f32 = v_pt_x * hn.get_x() + v_pt_z * hn.get_z();
4753        if v_n >= 0.0 {
4754            return 0.0;
4755        }
4756        let approach_speed: f32 = -v_n;
4757        let restitution: f32 = if approach_speed > 1.2 {
4758            COLLISION_WALL_RESTITUTION
4759        } else {
4760            0.0
4761        };
4762        let r_cross_n: f32 = rz * hn.get_x() - rx * hn.get_z();
4763        let denom_n: f32 = inv_m + (r_cross_n * r_cross_n) * inv_i;
4764        let j_n: f32 = (-(1.0 + restitution) * v_n / denom_n.max(1.0e-6)).max(0.0);
4765        vel.set_x(vel.get_x() + hn.get_x() * j_n * inv_m);
4766        vel.set_z(vel.get_z() + hn.get_z() * j_n * inv_m);
4767        *yaw_rate = (*yaw_rate + r_cross_n * j_n * inv_i)
4768            .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
4769        let vt_x: f32 = v_pt_x - hn.get_x() * v_n;
4770        let vt_z: f32 = v_pt_z - hn.get_z() * v_n;
4771        let vt_len: f32 = (vt_x * vt_x + vt_z * vt_z).sqrt();
4772        if vt_len > 1.0e-4 && j_n > 0.0 {
4773            let tx: f32 = vt_x / vt_len;
4774            let tz: f32 = vt_z / vt_len;
4775            let r_cross_t: f32 = rz * tx - rx * tz;
4776            let denom_t: f32 = inv_m + (r_cross_t * r_cross_t) * inv_i;
4777            let max_jt: f32 = COLLISION_WALL_FRICTION * j_n;
4778            let j_t: f32 = (-vt_len / denom_t.max(1.0e-6)).clamp(-max_jt, max_jt);
4779            vel.set_x(vel.get_x() + tx * j_t * inv_m);
4780            vel.set_z(vel.get_z() + tz * j_t * inv_m);
4781            *yaw_rate = (*yaw_rate + r_cross_t * j_t * inv_i)
4782                .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
4783        }
4784        approach_speed
4785    }
4786
4787    /// Integrates a rigid-body vehicle over `sub_dt` with substepped continuous static-world collision detection, realistic bounce/scrape/spin impulses, and zero-penetration enforcement.
4788    ///
4789    /// # Arguments
4790    ///
4791    /// - `&mut Transform3D` - Flat horizontal vehicle transform updated in place.
4792    /// - `&mut Vec3` - Mutable horizontal vehicle velocity updated on wall impacts.
4793    /// - `&mut f32` - Mutable yaw spin rate updated on off-center impacts.
4794    /// - `(f32, f32)` - `(inv_mass, inv_inertia_yaw)` inertial properties.
4795    /// - `(usize, AxisAlignedBox3D)` - `(vehicle_obj_idx, local_mesh_bounds)`.
4796    /// - `VehicleCcdStepCtx3D` - Substep duration, optional playable ground bounds, and vehicle margin.
4797    ///
4798    /// # Returns
4799    ///
4800    /// - `(bool, f32, Vec3, Vec3)` - `(moved, peak_impact_mps, impact_contact, impact_normal)`.
4801    fn step_rigid_vehicle_static_ccd(
4802        &self,
4803        tr: &mut Transform3D,
4804        vel: &mut Vec3,
4805        yaw_rate: &mut f32,
4806        inertia_pair: (f32, f32),
4807        vehicle_spec: (usize, AxisAlignedBox3D),
4808        step_ctx: VehicleCcdStepCtx3D,
4809    ) -> (bool, f32, Vec3, Vec3) {
4810        let (vehicle_idx, mesh_bounds): (usize, AxisAlignedBox3D) = vehicle_spec;
4811        let VehicleCcdStepCtx3D {
4812            sub_dt,
4813            ground_limits,
4814            ground_margin,
4815        } = step_ctx;
4816        let mut moved: bool = self.depenetrate_vehicle_static_horizontally(
4817            tr,
4818            mesh_bounds,
4819            vehicle_idx,
4820            ground_limits,
4821            ground_margin,
4822        );
4823        let mut peak_impact: f32 = 0.0;
4824        let mut peak_contact: Vec3 = tr.get_position();
4825        let mut peak_normal: Vec3 = Vec3::new(0.0, 0.0, 1.0);
4826        let speed: f32 = (vel.get_x() * vel.get_x() + vel.get_z() * vel.get_z()).sqrt();
4827        let linear_dist: f32 = speed * sub_dt;
4828        let angular_dist: f32 = yaw_rate.abs() * sub_dt;
4829        if linear_dist <= 1.0e-6 && angular_dist <= 1.0e-6 {
4830            return (moved, peak_impact, peak_contact, peak_normal);
4831        }
4832        let obb_now: OrientedBox3D = tr.to_oriented_box(mesh_bounds);
4833        let min_half: f32 = obb_now
4834            .get_half_extents()
4835            .get_x()
4836            .min(obb_now.get_half_extents().get_z())
4837            .max(0.25);
4838        let max_lin_step: f32 = (min_half * 0.25).min(COLLISION_CCD_MAX_STEP_M);
4839        let lin_steps: usize =
4840            ((linear_dist / max_lin_step).ceil() as usize).clamp(1, COLLISION_CCD_MAX_SUBSTEPS);
4841        let rot_steps: usize = ((angular_dist / COLLISION_ROT_MAX_STEP_RAD).ceil() as usize)
4842            .clamp(1, COLLISION_ROT_MAX_SUBSTEPS);
4843        let substeps: usize = lin_steps.max(rot_steps);
4844        let step_dt: f32 = sub_dt / (substeps as f32);
4845        for _ in 0..substeps {
4846            let d_yaw: f32 = (*yaw_rate) * step_dt;
4847            if d_yaw.abs() > 1.0e-6 {
4848                let mut rotated: Transform3D = *tr;
4849                rotated.set_yaw_rad(tr.get_yaw_rad() + d_yaw);
4850                if let Some(rot_hit) = self.mesh_oriented_box_static_collision(
4851                    rotated.to_oriented_box(mesh_bounds),
4852                    Some(vehicle_idx),
4853                ) {
4854                    if rot_hit.get_penetration() <= COLLISION_ROT_MAX_PUSH_M {
4855                        let mut pushed_rot: Transform3D = rotated;
4856                        let _: bool = self.depenetrate_vehicle_static_horizontally(
4857                            &mut pushed_rot,
4858                            mesh_bounds,
4859                            vehicle_idx,
4860                            ground_limits,
4861                            ground_margin,
4862                        );
4863                        let shift_m: f32 = pushed_rot
4864                            .get_position()
4865                            .sub(rotated.get_position())
4866                            .length();
4867                        if shift_m <= COLLISION_ROT_MAX_PUSH_M
4868                            && self
4869                                .mesh_oriented_box_static_collision(
4870                                    pushed_rot.to_oriented_box(mesh_bounds),
4871                                    Some(vehicle_idx),
4872                                )
4873                                .is_none()
4874                        {
4875                            *tr = pushed_rot;
4876                            moved = true;
4877                        } else {
4878                            *yaw_rate *= -0.2;
4879                        }
4880                    } else {
4881                        *yaw_rate *= -0.2;
4882                    }
4883                } else {
4884                    *tr = rotated;
4885                    moved = true;
4886                }
4887            }
4888            let step_dx: f32 = vel.get_x() * step_dt;
4889            let step_dz: f32 = vel.get_z() * step_dt;
4890            if step_dx * step_dx + step_dz * step_dz <= 1.0e-12 {
4891                continue;
4892            }
4893            let cur_pos: Vec3 = tr.get_position();
4894            let raw_next: Vec3 = Vec3::new(
4895                cur_pos.get_x() + step_dx,
4896                cur_pos.get_y(),
4897                cur_pos.get_z() + step_dz,
4898            );
4899            let next_pos: Vec3 =
4900                Self::clamp_horizontal_to_ground(raw_next, ground_limits, ground_margin);
4901            if (next_pos.get_x() - raw_next.get_x()).abs() > 1.0e-4 {
4902                vel.set_x(-vel.get_x() * COLLISION_WALL_RESTITUTION);
4903            }
4904            if (next_pos.get_z() - raw_next.get_z()).abs() > 1.0e-4 {
4905                vel.set_z(-vel.get_z() * COLLISION_WALL_RESTITUTION);
4906            }
4907            let mut cand: Transform3D = *tr;
4908            cand.set_position(next_pos);
4909            if let Some(hit) = self.mesh_oriented_box_static_collision(
4910                cand.to_oriented_box(mesh_bounds),
4911                Some(vehicle_idx),
4912            ) {
4913                let raw_hn: Vec3 =
4914                    Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
4915                let hn: Vec3 = if raw_hn.length_sq() > 1.0e-4 {
4916                    raw_hn.normalize()
4917                } else {
4918                    self.horizontal_collision_normal(
4919                        cand.to_oriented_box(mesh_bounds),
4920                        hit.get_object_index(),
4921                    )
4922                };
4923                if hn.length_sq() > 1.0e-6 {
4924                    let obs_bounds: AxisAlignedBox3D = self
4925                        .get_objects()
4926                        .get(hit.get_object_index())
4927                        .map(SceneObject3D::get_world_bounds)
4928                        .unwrap_or_else(|| {
4929                            AxisAlignedBox3D::new(
4930                                hit.get_contact_point().sub(Vec3::splat(0.5)),
4931                                hit.get_contact_point().add(Vec3::splat(0.5)),
4932                            )
4933                        });
4934                    let phys_contact: Vec3 = Self::compute_static_contact_point(
4935                        cand.to_oriented_box(mesh_bounds),
4936                        hn,
4937                        obs_bounds,
4938                        hit.get_contact_point(),
4939                    );
4940                    let impact_v: f32 = Self::apply_static_wall_impulse(
4941                        cur_pos,
4942                        vel,
4943                        yaw_rate,
4944                        inertia_pair,
4945                        hn,
4946                        phys_contact,
4947                    );
4948                    if impact_v > peak_impact {
4949                        peak_impact = impact_v;
4950                        peak_contact = phys_contact;
4951                        peak_normal = hn;
4952                    }
4953                    let slide_dx: f32 = vel.get_x() * step_dt;
4954                    let slide_dz: f32 = vel.get_z() * step_dt;
4955                    let push_eps: f32 = COLLISION_MTV_PUSH_EPS;
4956                    let slide_pos: Vec3 = Self::clamp_horizontal_to_ground(
4957                        Vec3::new(
4958                            cur_pos.get_x() + slide_dx + hn.get_x() * push_eps,
4959                            cur_pos.get_y(),
4960                            cur_pos.get_z() + slide_dz + hn.get_z() * push_eps,
4961                        ),
4962                        ground_limits,
4963                        ground_margin,
4964                    );
4965                    let mut slide_tr: Transform3D = *tr;
4966                    slide_tr.set_position(slide_pos);
4967                    if self
4968                        .mesh_oriented_box_static_collision(
4969                            slide_tr.to_oriented_box(mesh_bounds),
4970                            Some(vehicle_idx),
4971                        )
4972                        .is_none()
4973                    {
4974                        *tr = slide_tr;
4975                        moved = true;
4976                        continue;
4977                    }
4978                }
4979                break;
4980            }
4981            *tr = cand;
4982            moved = true;
4983        }
4984        if self.depenetrate_vehicle_static_horizontally(
4985            tr,
4986            mesh_bounds,
4987            vehicle_idx,
4988            ground_limits,
4989            ground_margin,
4990        ) {
4991            moved = true;
4992        }
4993        (moved, peak_impact, peak_contact, peak_normal)
4994    }
4995
4996    /// Emits bright metallic collision sparks via `World3D::niagara` at a rigid-body impact point.
4997    ///
4998    /// # Arguments
4999    ///
5000    /// - `Vec3` - World-space contact point.
5001    /// - `Vec3` - Outward impact normal.
5002    /// - `f32` - Normalized impact intensity in `[0.0, 1.0]`.
5003    fn emit_collision_sparks(&mut self, contact: Vec3, normal: Vec3, intensity: f32) {
5004        if self.get_niagara().get_active_count() >= 56 {
5005            return;
5006        }
5007        let burst: usize = ((3.0 + intensity * 6.0).round() as usize).clamp(2, 9);
5008        let mut cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
5009        cfg.set_origin(Vec3::new(
5010            contact.get_x(),
5011            contact.get_y().max(0.45),
5012            contact.get_z(),
5013        ));
5014        cfg.set_base_velocity(normal.scale(4.5 + intensity * 7.5).add(Vec3::new(
5015            0.0,
5016            2.8 + intensity * 2.5,
5017            0.0,
5018        )));
5019        cfg.set_velocity_spread(3.8 + intensity * 2.5);
5020        cfg.set_start_color(Color::rgba(255, 196, 36, 255));
5021        cfg.set_end_color(Color::rgba(255, 72, 0, 80));
5022        cfg.set_start_size_m(0.12);
5023        cfg.set_end_size_m(0.03);
5024        cfg.set_min_lifetime(0.22);
5025        cfg.set_max_lifetime(0.55);
5026        cfg.set_emissive_boost(1.75);
5027        self.get_mut_niagara().emit_burst(burst, &cfg);
5028    }
5029
5030    /// Emits dual rear-wheel tire smoke puffs via `World3D::niagara` while powersliding.
5031    ///
5032    /// # Arguments
5033    ///
5034    /// - `Vec3` - Player vehicle world position.
5035    /// - `Vec3` - Unit forward heading vector.
5036    /// - `Vec3` - Unit right lateral vector.
5037    /// - `f32` - Absolute slip angle in radians.
5038    fn emit_drift_smoke(
5039        &mut self,
5040        car_origin: Vec3,
5041        car_fwd: Vec3,
5042        car_right: Vec3,
5043        slip_abs: f32,
5044    ) {
5045        if self.get_niagara().get_active_count() >= 48 {
5046            return;
5047        }
5048        let intensity: f32 = ((slip_abs - 0.10) / 0.50).clamp(0.25, 1.0);
5049        let rear_center: Vec3 = car_origin
5050            .sub(car_fwd.scale(1.85))
5051            .add(Vec3::new(0.0, 0.22, 0.0));
5052        for side in [-0.88_f32, 0.88_f32] {
5053            let wheel_pos: Vec3 = rear_center.add(car_right.scale(side));
5054            let mut smoke_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
5055            smoke_cfg.set_origin(wheel_pos);
5056            smoke_cfg.set_base_velocity(car_fwd.scale(-2.4).add(Vec3::new(
5057                0.0,
5058                0.85 + intensity * 0.5,
5059                0.0,
5060            )));
5061            smoke_cfg.set_velocity_spread(1.25);
5062            smoke_cfg.set_start_color(Color::rgba(226, 232, 240, 175));
5063            smoke_cfg.set_end_color(Color::rgba(148, 163, 184, 30));
5064            smoke_cfg.set_start_size_m(0.22 + intensity * 0.12);
5065            smoke_cfg.set_end_size_m(0.52 + intensity * 0.18);
5066            smoke_cfg.set_min_lifetime(0.35);
5067            smoke_cfg.set_max_lifetime(0.75);
5068            smoke_cfg.set_emissive_boost(0.35);
5069            self.get_mut_niagara().emit_burst(1, &smoke_cfg);
5070        }
5071    }
5072
5073    /// Emits luminous dual exhaust nitro boost flames via `World3D::niagara`.
5074    ///
5075    /// # Arguments
5076    ///
5077    /// - `Vec3` - Player vehicle world position.
5078    /// - `Vec3` - Unit forward heading vector.
5079    /// - `Vec3` - Unit right lateral vector.
5080    /// - `Vec3` - Current player vehicle world velocity in meters per second.
5081    fn emit_boost_flame(
5082        &mut self,
5083        car_origin: Vec3,
5084        car_fwd: Vec3,
5085        car_right: Vec3,
5086        car_vel: Vec3,
5087    ) {
5088        if self.get_niagara().get_active_count() >= 64 {
5089            return;
5090        }
5091        let exhaust_center: Vec3 = car_origin
5092            .sub(car_fwd.scale(2.35))
5093            .add(Vec3::new(0.0, 0.44, 0.0));
5094        let base_jet_vel: Vec3 = car_vel
5095            .scale(0.65)
5096            .add(car_fwd.scale(-8.5))
5097            .add(Vec3::new(0.0, 0.35, 0.0));
5098        for side in [-0.46_f32, 0.46_f32] {
5099            let pipe_pos: Vec3 = exhaust_center.add(car_right.scale(side));
5100            let mut flame_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
5101            flame_cfg.set_origin(pipe_pos);
5102            flame_cfg.set_base_velocity(base_jet_vel);
5103            flame_cfg.set_velocity_spread(0.85);
5104            flame_cfg.set_start_color(Color::rgba(0, 178, 255, 245));
5105            flame_cfg.set_end_color(Color::rgba(255, 88, 0, 75));
5106            flame_cfg.set_start_size_m(0.17);
5107            flame_cfg.set_end_size_m(0.05);
5108            flame_cfg.set_min_lifetime(0.10);
5109            flame_cfg.set_max_lifetime(0.22);
5110            flame_cfg.set_emissive_boost(1.65);
5111            self.get_mut_niagara().emit_burst(2, &flame_cfg);
5112        }
5113    }
5114
5115    /// Measures the closest slower or stationary dynamic vehicle directly ahead of `npc_idx` along its forward lane corridor for cautious AI braking.
5116    ///
5117    /// # Arguments
5118    ///
5119    /// - `usize` - Querying NPC scene object index.
5120    /// - `Vec3` - NPC world center position.
5121    /// - `Vec3` - Unit forward direction of the NPC.
5122    /// - `Vec3` - Unit right vector of the NPC.
5123    /// - `f32` - Current forward speed of the NPC in meters per second.
5124    ///
5125    /// # Returns
5126    ///
5127    /// - `Option<f32>` - Forward center-to-center distance in meters to the closest blocking vehicle ahead within `16.0m`.
5128    #[must_use]
5129    fn npc_forward_blocking_gap(
5130        &self,
5131        npc_idx: usize,
5132        pos: Vec3,
5133        fwd: Vec3,
5134        right: Vec3,
5135        npc_fwd_speed: f32,
5136    ) -> Option<f32> {
5137        let mut closest: Option<f32> = None;
5138        let objects: &[SceneObject3D] = self.get_objects().as_slice();
5139        let player_opt: Option<usize> = self.vehicle_index();
5140        let player_vel: Vec3 = self.player_velocity();
5141        let Self {
5142            traffic_vehicles, ..
5143        } = self;
5144        for (other_idx, other_obj) in objects.iter().enumerate() {
5145            let other_solid: bool =
5146                other_obj.get_solid_collider() || other_obj.get_ray_trace_caster();
5147            if other_idx == npc_idx || !other_obj.get_is_dynamic() || !other_solid {
5148                continue;
5149            }
5150            let other_pos: Vec3 = other_obj.get_transform().get_position();
5151            let diff: Vec3 = Vec3::new(
5152                other_pos.get_x() - pos.get_x(),
5153                0.0,
5154                other_pos.get_z() - pos.get_z(),
5155            );
5156            let fwd_d: f32 = diff.dot(fwd);
5157            if fwd_d <= 0.5 || fwd_d >= 16.0 {
5158                continue;
5159            }
5160            let lat_d: f32 = diff.dot(right).abs();
5161            if lat_d > 2.75 {
5162                continue;
5163            }
5164            let other_vel: Vec3 = if player_opt == Some(other_idx) {
5165                player_vel
5166            } else {
5167                traffic_vehicles
5168                    .iter()
5169                    .find(|n: &&NpcVehicle3D| n.get_object_index() == other_idx)
5170                    .map(NpcVehicle3D::get_vel)
5171                    .unwrap_or_else(Vec3::zero)
5172            };
5173            let other_fwd_speed: f32 = other_vel.dot(fwd);
5174            if other_fwd_speed < npc_fwd_speed - 0.5 || other_fwd_speed.abs() < 1.5 {
5175                closest = Some(closest.map(|prev: f32| prev.min(fwd_d)).unwrap_or(fwd_d));
5176            }
5177        }
5178        closest
5179    }
5180
5181    /// Resolves all dynamic vehicle-vs-vehicle rigid-body OBB SAT collisions (Player-vs-NPC and NPC-vs-NPC) with positional separation, momentum transfer, spin torque, off-road knockback, and collision sparks.
5182    ///
5183    /// # Arguments
5184    ///
5185    /// - `Option<(f32, f32, f32, f32)>` - Optional playable horizontal ground bounds.
5186    ///
5187    /// # Returns
5188    ///
5189    /// - `(bool, f32, Vec3, Vec3)` - `(any_moved, player_impact_mps, impact_contact, impact_normal)`.
5190    fn resolve_dynamic_vehicle_collisions(
5191        &mut self,
5192        ground_limits: Option<(f32, f32, f32, f32)>,
5193    ) -> (bool, f32, Vec3, Vec3) {
5194        let player_opt: Option<usize> = self.vehicle_index();
5195        let npc_count: usize = self.traffic_vehicle_count();
5196        let total_bodies: usize = npc_count + usize::from(player_opt.is_some());
5197        if total_bodies < 2 {
5198            return (false, 0.0, Vec3::zero(), Vec3::new(0.0, 0.0, 1.0));
5199        }
5200        let mut any_moved: bool = false;
5201        let mut player_peak_impact: f32 = 0.0;
5202        let mut player_peak_contact: Vec3 = Vec3::zero();
5203        let mut player_peak_normal: Vec3 = Vec3::new(0.0, 0.0, 1.0);
5204        let player_offset: usize = usize::from(player_opt.is_some());
5205        for _ in 0..2_usize {
5206            for idx_a in 0..total_bodies {
5207                for idx_b in (idx_a + 1)..total_bodies {
5208                    let is_a_player: bool = player_opt.is_some() && idx_a == 0;
5209                    let obj_a: usize = if is_a_player {
5210                        match player_opt {
5211                            Some(p_idx) => p_idx,
5212                            None => continue,
5213                        }
5214                    } else {
5215                        match self.traffic_vehicle_object_index(idx_a - player_offset) {
5216                            Some(n_idx) => n_idx,
5217                            None => continue,
5218                        }
5219                    };
5220                    let npc_slot_b: usize = idx_b - player_offset;
5221                    let Some(obj_b) = self.traffic_vehicle_object_index(npc_slot_b) else {
5222                        continue;
5223                    };
5224                    let Some((mut tr_a, mesh_a)) = self
5225                        .get_objects()
5226                        .get(obj_a)
5227                        .map(|o: &SceneObject3D| (o.get_transform(), o.get_mesh_id()))
5228                    else {
5229                        continue;
5230                    };
5231                    let Some((mut tr_b, mesh_b)) = self
5232                        .get_objects()
5233                        .get(obj_b)
5234                        .map(|o: &SceneObject3D| (o.get_transform(), o.get_mesh_id()))
5235                    else {
5236                        continue;
5237                    };
5238                    let bounds_a: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_a);
5239                    let bounds_b: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_b);
5240                    let obb_a: OrientedBox3D = tr_a.to_oriented_box(bounds_a);
5241                    let obb_b: OrientedBox3D = tr_b.to_oriented_box(bounds_b);
5242                    let Some((normal_ba, pen, contact)) = obb_a.intersect_oriented_box_xz(&obb_b)
5243                    else {
5244                        continue;
5245                    };
5246                    let (mut vel_a, mut omega_a, mass_a, inv_i_a): (Vec3, f32, f32, f32) =
5247                        if is_a_player {
5248                            (
5249                                self.player_velocity(),
5250                                self.player_yaw_rate(),
5251                                VEHICLE_PLAYER_MASS_KG,
5252                                1.0 / VEHICLE_PLAYER_INERTIA_YAW,
5253                            )
5254                        } else {
5255                            let Self {
5256                                traffic_vehicles, ..
5257                            } = self;
5258                            let npc_a: NpcVehicle3D = traffic_vehicles[idx_a - player_offset];
5259                            (
5260                                npc_a.get_vel(),
5261                                npc_a.get_yaw_rate(),
5262                                npc_a.get_mass(),
5263                                1.0 / VEHICLE_NPC_INERTIA_YAW,
5264                            )
5265                        };
5266                    let (mut vel_b, mut omega_b, mass_b, inv_i_b): (Vec3, f32, f32, f32) = {
5267                        let Self {
5268                            traffic_vehicles, ..
5269                        } = self;
5270                        let npc_b: NpcVehicle3D = traffic_vehicles[npc_slot_b];
5271                        (
5272                            npc_b.get_vel(),
5273                            npc_b.get_yaw_rate(),
5274                            npc_b.get_mass(),
5275                            1.0 / VEHICLE_NPC_INERTIA_YAW,
5276                        )
5277                    };
5278                    let inv_m_a: f32 = 1.0 / mass_a.max(100.0);
5279                    let inv_m_b: f32 = 1.0 / mass_b.max(100.0);
5280                    let inv_m_sum: f32 = inv_m_a + inv_m_b;
5281                    let total_push: f32 = pen + COLLISION_MTV_PUSH_EPS;
5282                    let share_a: f32 = total_push * (inv_m_a / inv_m_sum);
5283                    let share_b: f32 = total_push * (inv_m_b / inv_m_sum);
5284                    let margin_a: f32 = obb_a
5285                        .get_half_extents()
5286                        .get_x()
5287                        .max(obb_a.get_half_extents().get_z());
5288                    let margin_b: f32 = obb_b
5289                        .get_half_extents()
5290                        .get_x()
5291                        .max(obb_b.get_half_extents().get_z());
5292                    let cand_pos_a: Vec3 = Self::clamp_horizontal_to_ground(
5293                        tr_a.get_position().add(normal_ba.scale(share_a)),
5294                        ground_limits,
5295                        margin_a,
5296                    );
5297                    let cand_pos_b: Vec3 = Self::clamp_horizontal_to_ground(
5298                        tr_b.get_position().sub(normal_ba.scale(share_b)),
5299                        ground_limits,
5300                        margin_b,
5301                    );
5302                    let mut cand_tr_a: Transform3D = tr_a;
5303                    cand_tr_a.set_position(cand_pos_a);
5304                    let mut cand_tr_b: Transform3D = tr_b;
5305                    cand_tr_b.set_position(cand_pos_b);
5306                    let a_static_ok: bool = self
5307                        .mesh_oriented_box_static_collision(
5308                            cand_tr_a.to_oriented_box(bounds_a),
5309                            Some(obj_a),
5310                        )
5311                        .is_none();
5312                    let b_static_ok: bool = self
5313                        .mesh_oriented_box_static_collision(
5314                            cand_tr_b.to_oriented_box(bounds_b),
5315                            Some(obj_b),
5316                        )
5317                        .is_none();
5318                    if a_static_ok && b_static_ok {
5319                        tr_a = cand_tr_a;
5320                        tr_b = cand_tr_b;
5321                    } else if b_static_ok {
5322                        let full_b: Vec3 = Self::clamp_horizontal_to_ground(
5323                            tr_b.get_position().sub(normal_ba.scale(total_push)),
5324                            ground_limits,
5325                            margin_b,
5326                        );
5327                        tr_b.set_position(full_b);
5328                    } else if a_static_ok {
5329                        let full_a: Vec3 = Self::clamp_horizontal_to_ground(
5330                            tr_a.get_position().add(normal_ba.scale(total_push)),
5331                            ground_limits,
5332                            margin_a,
5333                        );
5334                        tr_a.set_position(full_a);
5335                    } else {
5336                        tr_a = cand_tr_a;
5337                        tr_b = cand_tr_b;
5338                        let _: bool = self.depenetrate_vehicle_static_horizontally(
5339                            &mut tr_a,
5340                            bounds_a,
5341                            obj_a,
5342                            ground_limits,
5343                            margin_a,
5344                        );
5345                        let _: bool = self.depenetrate_vehicle_static_horizontally(
5346                            &mut tr_b,
5347                            bounds_b,
5348                            obj_b,
5349                            ground_limits,
5350                            margin_b,
5351                        );
5352                    }
5353                    let pos_a: Vec3 = tr_a.get_position();
5354                    let pos_b: Vec3 = tr_b.get_position();
5355                    let ra_x: f32 = (contact.get_x() - pos_a.get_x()).clamp(-2.6, 2.6);
5356                    let ra_z: f32 = (contact.get_z() - pos_a.get_z()).clamp(-2.6, 2.6);
5357                    let rb_x: f32 = (contact.get_x() - pos_b.get_x()).clamp(-2.6, 2.6);
5358                    let rb_z: f32 = (contact.get_z() - pos_b.get_z()).clamp(-2.6, 2.6);
5359                    let va_pt_x: f32 = vel_a.get_x() + omega_a * ra_z;
5360                    let va_pt_z: f32 = vel_a.get_z() - omega_a * ra_x;
5361                    let vb_pt_x: f32 = vel_b.get_x() + omega_b * rb_z;
5362                    let vb_pt_z: f32 = vel_b.get_z() - omega_b * rb_x;
5363                    let vrel_x: f32 = va_pt_x - vb_pt_x;
5364                    let vrel_z: f32 = va_pt_z - vb_pt_z;
5365                    let vrel_n: f32 = vrel_x * normal_ba.get_x() + vrel_z * normal_ba.get_z();
5366                    let mut impact_dv_a: f32 = 0.0;
5367                    let mut impact_dv_b: f32 = 0.0;
5368                    if vrel_n < 0.0 {
5369                        let ra_cross_n: f32 = ra_z * normal_ba.get_x() - ra_x * normal_ba.get_z();
5370                        let rb_cross_n: f32 = rb_z * normal_ba.get_x() - rb_x * normal_ba.get_z();
5371                        let denom_n: f32 = inv_m_a
5372                            + inv_m_b
5373                            + (ra_cross_n * ra_cross_n) * inv_i_a
5374                            + (rb_cross_n * rb_cross_n) * inv_i_b;
5375                        let restitution: f32 = if -vrel_n > 1.5 {
5376                            COLLISION_CAR_RESTITUTION
5377                        } else {
5378                            0.05
5379                        };
5380                        let j_n: f32 =
5381                            (-(1.0 + restitution) * vrel_n / denom_n.max(1.0e-6)).max(0.0);
5382                        vel_a.set_x(vel_a.get_x() + normal_ba.get_x() * j_n * inv_m_a);
5383                        vel_a.set_z(vel_a.get_z() + normal_ba.get_z() * j_n * inv_m_a);
5384                        omega_a = (omega_a + ra_cross_n * j_n * inv_i_a)
5385                            .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
5386                        vel_b.set_x(vel_b.get_x() - normal_ba.get_x() * j_n * inv_m_b);
5387                        vel_b.set_z(vel_b.get_z() - normal_ba.get_z() * j_n * inv_m_b);
5388                        omega_b = (omega_b - rb_cross_n * j_n * inv_i_b)
5389                            .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
5390                        impact_dv_a = j_n * inv_m_a;
5391                        impact_dv_b = j_n * inv_m_b;
5392                        let vt_x: f32 = vrel_x - normal_ba.get_x() * vrel_n;
5393                        let vt_z: f32 = vrel_z - normal_ba.get_z() * vrel_n;
5394                        let vt_len: f32 = (vt_x * vt_x + vt_z * vt_z).sqrt();
5395                        if vt_len > 1.0e-4 && j_n > 0.0 {
5396                            let tx: f32 = vt_x / vt_len;
5397                            let tz: f32 = vt_z / vt_len;
5398                            let ra_cross_t: f32 = ra_z * tx - ra_x * tz;
5399                            let rb_cross_t: f32 = rb_z * tx - rb_x * tz;
5400                            let denom_t: f32 = inv_m_a
5401                                + inv_m_b
5402                                + (ra_cross_t * ra_cross_t) * inv_i_a
5403                                + (rb_cross_t * rb_cross_t) * inv_i_b;
5404                            let max_jt: f32 = COLLISION_CAR_FRICTION * j_n;
5405                            let j_t: f32 = (-vt_len / denom_t.max(1.0e-6)).clamp(-max_jt, max_jt);
5406                            vel_a.set_x(vel_a.get_x() + tx * j_t * inv_m_a);
5407                            vel_a.set_z(vel_a.get_z() + tz * j_t * inv_m_a);
5408                            omega_a = (omega_a + ra_cross_t * j_t * inv_i_a)
5409                                .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
5410                            vel_b.set_x(vel_b.get_x() - tx * j_t * inv_m_b);
5411                            vel_b.set_z(vel_b.get_z() - tz * j_t * inv_m_b);
5412                            omega_b = (omega_b - rb_cross_t * j_t * inv_i_b)
5413                                .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
5414                        }
5415                        let closing: f32 = -vrel_n;
5416                        if is_a_player && closing > player_peak_impact {
5417                            player_peak_impact = closing;
5418                            player_peak_contact = contact;
5419                            player_peak_normal = normal_ba;
5420                        }
5421                        if closing > 2.5 {
5422                            let spark_int: f32 = ((closing - 2.0) / 24.0).clamp(0.15, 1.0);
5423                            self.emit_collision_sparks(contact, normal_ba, spark_int);
5424                        }
5425                    }
5426                    let wb_a: AxisAlignedBox3D = tr_a.transform_bounds(bounds_a);
5427                    let wb_b: AxisAlignedBox3D = tr_b.transform_bounds(bounds_b);
5428                    if let Some(o_a) = self.get_mut_objects().get_mut(obj_a) {
5429                        o_a.set_transform(tr_a);
5430                        o_a.set_world_bounds(wb_a);
5431                    }
5432                    if let Some(o_b) = self.get_mut_objects().get_mut(obj_b) {
5433                        o_b.set_transform(tr_b);
5434                        o_b.set_world_bounds(wb_b);
5435                    }
5436                    if is_a_player {
5437                        let Self { player_physics, .. } = self;
5438                        player_physics.set_vel(vel_a);
5439                        player_physics.set_yaw_rate(omega_a);
5440                    } else {
5441                        let slot_a: usize = idx_a - player_offset;
5442                        let Self {
5443                            traffic_vehicles, ..
5444                        } = self;
5445                        let npc_a: &mut NpcVehicle3D = &mut traffic_vehicles[slot_a];
5446                        npc_a.set_vel(vel_a);
5447                        npc_a.set_yaw_rate(omega_a);
5448                        if impact_dv_a > 1.5 {
5449                            let rec_s: f32 = (1.4 + impact_dv_a * 0.08).clamp(1.2, 2.8);
5450                            npc_a.set_recovery_timer(npc_a.get_recovery_timer().max(rec_s));
5451                            npc_a.set_free_roam_mode(true);
5452                        }
5453                    }
5454                    {
5455                        let Self {
5456                            traffic_vehicles, ..
5457                        } = self;
5458                        let npc_b: &mut NpcVehicle3D = &mut traffic_vehicles[npc_slot_b];
5459                        npc_b.set_vel(vel_b);
5460                        npc_b.set_yaw_rate(omega_b);
5461                        if impact_dv_b > 1.5 {
5462                            let rec_s: f32 = (1.4 + impact_dv_b * 0.08).clamp(1.2, 2.8);
5463                            npc_b.set_recovery_timer(npc_b.get_recovery_timer().max(rec_s));
5464                            npc_b.set_free_roam_mode(true);
5465                        }
5466                    }
5467                    any_moved = true;
5468                }
5469            }
5470        }
5471        (
5472            any_moved,
5473            player_peak_impact,
5474            player_peak_contact,
5475            player_peak_normal,
5476        )
5477    }
5478
5479    /// Advances drivable vehicle chassis dynamics (`Shift` boost, `Space` drift, Ackermann reverse), dynamic rigid-body NPC traffic, 2-body OBB SAT collisions, raycast chase camera, Niagara particles, and animations.
5480    ///
5481    /// # Arguments
5482    ///
5483    /// - `f32` - Delta time in seconds.
5484    /// - `&InputState` - Real-time polled keyboard/pointer input.
5485    /// - `&ActionMap` - Action bindings for WASD/Arrows, Boost, and Drift controls.
5486    pub fn step_simulation(&mut self, dt: f32, input: &InputState, actions: &ActionMap) {
5487        if dt <= 0.0 || !dt.is_finite() {
5488            return;
5489        }
5490        self.set_world_time_secs(self.get_world_time_secs() + dt);
5491        let sim_tick: u64 = self.get_sim_tick().wrapping_add(1);
5492        self.set_sim_tick(sim_tick);
5493        let kb_steer: f32 = if actions.is_active(GameAction::MoveRight, input) {
5494            1.0
5495        } else {
5496            0.0
5497        } - if actions.is_active(GameAction::MoveLeft, input) {
5498            1.0
5499        } else {
5500            0.0
5501        };
5502        let kb_throttle: f32 = if actions.is_active(GameAction::MoveUp, input) {
5503            1.0
5504        } else {
5505            0.0
5506        } - if actions.is_active(GameAction::MoveDown, input) {
5507            1.0
5508        } else {
5509            0.0
5510        };
5511        let v_stick: Point = input.get_virtual_axis();
5512        let steer: f32 = (kb_steer + v_stick.get_x()).clamp(-1.0, 1.0);
5513        let throttle: f32 = (kb_throttle - v_stick.get_y()).clamp(-1.0, 1.0);
5514        let boost_pressed: bool = actions.is_active(GameAction::Boost, input)
5515            || input.get_modifiers().get_shift()
5516            || input.get_virtual_boost();
5517        let drift_pressed: bool = actions.is_active(GameAction::Drift, input)
5518            || input.is_key_down(KeyCode::Space)
5519            || input.get_virtual_drift();
5520        let mut any_dynamic_moved: bool = false;
5521        let mut any_static_moved: bool = false;
5522        let ground_limits: Option<(f32, f32, f32, f32)> = self.ground_play_bounds();
5523        let car_opt: Option<usize> = self.vehicle_index();
5524        let sim_substeps: usize = ((dt / 0.02).ceil() as usize).clamp(1, 6);
5525        let sub_dt: f32 = dt / (sim_substeps as f32);
5526        let mut player_moved_any: bool = false;
5527        for _ in 0..sim_substeps {
5528            if let Some(car_idx) = car_opt
5529                && let Some((cur_tr, mesh_id, car_is_dynamic)) =
5530                    self.get_objects().get(car_idx).map(|car: &SceneObject3D| {
5531                        (car.get_transform(), car.get_mesh_id(), car.get_is_dynamic())
5532                    })
5533            {
5534                let mesh_bounds: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_id);
5535                let mut phys: PlayerVehiclePhysics3D = {
5536                    let Self { player_physics, .. } = self;
5537                    *player_physics
5538                };
5539                let mut flat_tr: Transform3D = Transform3D::new(
5540                    Vec3::new(
5541                        cur_tr.get_position().get_x(),
5542                        0.0,
5543                        cur_tr.get_position().get_z(),
5544                    ),
5545                    cur_tr.get_yaw_rad(),
5546                    cur_tr.get_scale(),
5547                );
5548                let flat_obb: OrientedBox3D = flat_tr.to_oriented_box(mesh_bounds);
5549                let ground_margin: f32 = flat_obb
5550                    .get_half_extents()
5551                    .get_x()
5552                    .max(flat_obb.get_half_extents().get_z());
5553                let yaw_now: f32 = flat_tr.get_yaw_rad();
5554                let fwd: Vec3 = Vec3::new(-yaw_now.sin(), 0.0, -yaw_now.cos());
5555                let right: Vec3 = Vec3::new(yaw_now.cos(), 0.0, -yaw_now.sin());
5556                let mut vel: Vec3 = phys.get_vel();
5557                let mut v_fwd: f32 = vel.dot(fwd);
5558                let mut v_lat: f32 = vel.dot(right);
5559                let speed_now: f32 = (v_fwd * v_fwd + v_lat * v_lat).sqrt();
5560                let was_boosting: bool = phys.get_boost_active();
5561                let mut boost_charge: f32 = phys.get_boost_charge();
5562                let can_boost: bool = if was_boosting {
5563                    boost_charge > 0.0
5564                } else {
5565                    boost_charge >= VEHICLE_BOOST_MIN_REIGNITE
5566                };
5567                let boost_active: bool = boost_pressed && can_boost && throttle >= -0.05;
5568                let was_drifting: bool = phys.get_drift_active();
5569                let drift_active: bool = drift_pressed
5570                    && speed_now > VEHICLE_DRIFT_MIN_SPEED_MPS
5571                    && v_fwd > VEHICLE_DRIFT_MIN_FWD_MPS;
5572                if boost_active {
5573                    boost_charge = (boost_charge - VEHICLE_BOOST_DRAIN_PER_SEC * sub_dt).max(0.0);
5574                } else {
5575                    let regen_rate: f32 = if drift_active {
5576                        VEHICLE_BOOST_DRIFT_REGEN_PER_SEC
5577                    } else {
5578                        VEHICLE_BOOST_REGEN_PER_SEC
5579                    };
5580                    boost_charge = (boost_charge + regen_rate * sub_dt).min(1.0);
5581                }
5582                let mut drift_duration: f32 = phys.get_drift_duration();
5583                let mut drift_peak_slip: f32 = phys.get_drift_peak_slip();
5584                let mut exit_kick_triggered: bool = false;
5585                if drift_active {
5586                    drift_duration += sub_dt;
5587                } else if was_drifting {
5588                    if drift_duration >= VEHICLE_DRIFT_EXIT_MIN_SECS
5589                        && drift_peak_slip >= VEHICLE_DRIFT_EXIT_MIN_SLIP_RAD
5590                        && v_fwd > 4.0
5591                    {
5592                        let slip_snap: f32 = v_lat.abs() * 0.45;
5593                        v_fwd = (v_fwd + VEHICLE_DRIFT_EXIT_KICK_MPS + slip_snap)
5594                            .min(VEHICLE_BOOST_TOP_SPEED_MPS);
5595                        exit_kick_triggered = true;
5596                    }
5597                    drift_duration = 0.0;
5598                    drift_peak_slip = 0.0;
5599                } else {
5600                    drift_duration = 0.0;
5601                    drift_peak_slip = 0.0;
5602                }
5603                let eff_throttle: f32 = if boost_active && throttle >= 0.0 {
5604                    throttle.max(1.0)
5605                } else {
5606                    throttle
5607                };
5608                let top_fwd: f32 = if boost_active {
5609                    VEHICLE_BOOST_TOP_SPEED_MPS
5610                } else {
5611                    VEHICLE_NORMAL_TOP_SPEED_MPS
5612                };
5613                let long_accel: f32 = if eff_throttle > 0.05 {
5614                    if v_fwd < -0.5 {
5615                        VEHICLE_BRAKE_DECEL_MPS2
5616                    } else {
5617                        let launch: f32 = VEHICLE_NORMAL_ACCEL_MPS2
5618                            + VEHICLE_LAUNCH_BONUS_MPS2
5619                                * (-(v_fwd.abs()) / VEHICLE_LAUNCH_TAPER_MPS).exp();
5620                        let mult: f32 = if boost_active {
5621                            VEHICLE_BOOST_THRUST_MULT
5622                        } else {
5623                            1.0
5624                        };
5625                        let speed_ratio: f32 = (v_fwd / top_fwd).clamp(0.0, 1.0);
5626                        let taper: f32 = (1.0 - speed_ratio * speed_ratio * 0.65).max(0.18);
5627                        eff_throttle * launch * mult * taper
5628                    }
5629                } else if eff_throttle < -0.05 {
5630                    if v_fwd > 0.5 {
5631                        -VEHICLE_BRAKE_DECEL_MPS2
5632                    } else {
5633                        let launch: f32 = VEHICLE_NORMAL_ACCEL_MPS2
5634                            + VEHICLE_LAUNCH_BONUS_MPS2
5635                                * (-(v_fwd.abs()) / VEHICLE_LAUNCH_TAPER_MPS).exp();
5636                        let speed_ratio: f32 =
5637                            ((-v_fwd) / VEHICLE_REVERSE_TOP_SPEED_MPS).clamp(0.0, 1.0);
5638                        let taper: f32 = (1.0 - speed_ratio * speed_ratio * 0.65).max(0.2);
5639                        eff_throttle * launch * taper
5640                    }
5641                } else {
5642                    let handbrake_drag: f32 = if drift_pressed { 4.5 } else { 0.0 };
5643                    let drag: f32 = (VEHICLE_ROLLING_DRAG + handbrake_drag) * v_fwd
5644                        + VEHICLE_AERO_DRAG * v_fwd * v_fwd.abs();
5645                    -drag
5646                };
5647                v_fwd += long_accel * sub_dt;
5648                if eff_throttle.abs() <= 0.05 && v_fwd.abs() < 0.08 && v_lat.abs() < 0.08 {
5649                    v_fwd = 0.0;
5650                    v_lat = 0.0;
5651                } else {
5652                    let max_allowed_fwd: f32 = if boost_active || exit_kick_triggered {
5653                        VEHICLE_BOOST_TOP_SPEED_MPS
5654                    } else if v_fwd > VEHICLE_NORMAL_TOP_SPEED_MPS {
5655                        (v_fwd - 10.0 * sub_dt).max(VEHICLE_NORMAL_TOP_SPEED_MPS)
5656                    } else {
5657                        VEHICLE_NORMAL_TOP_SPEED_MPS
5658                    };
5659                    v_fwd = v_fwd.clamp(-VEHICLE_REVERSE_TOP_SPEED_MPS, max_allowed_fwd);
5660                }
5661                let slip_before: f32 = v_lat.atan2(v_fwd.abs().max(1.0));
5662                let lat_grip: f32 = if drift_active {
5663                    let extra_scrub: f32 = ((slip_before.abs() - 0.66).max(0.0)) * 5.2;
5664                    VEHICLE_DRIFT_LAT_GRIP + extra_scrub
5665                } else {
5666                    VEHICLE_NORMAL_LAT_GRIP
5667                };
5668                v_lat *= (-lat_grip * sub_dt).exp();
5669                let mut yaw_rate: f32 = phys.get_yaw_rate();
5670                let steer_sign: f32 =
5671                    if v_fwd < -0.35 || (v_fwd.abs() <= 0.35 && eff_throttle < -0.05) {
5672                        -1.0
5673                    } else {
5674                        1.0
5675                    };
5676                let active_speed: f32 = (v_fwd * v_fwd + v_lat * v_lat).sqrt();
5677                let base_auth: f32 = (0.90 + 0.10 * (active_speed / 8.0).min(1.0)).min(1.0);
5678                let high_speed_calm: f32 = if drift_active {
5679                    1.0
5680                } else {
5681                    (1.0 - ((active_speed - 28.0).max(0.0) / 60.0)).clamp(0.72, 1.0)
5682                };
5683                let steer_authority: f32 = base_auth * high_speed_calm;
5684                let yaw_gain: f32 = if drift_active {
5685                    VEHICLE_DRIFT_YAW_GAIN
5686                } else {
5687                    VEHICLE_NORMAL_YAW_GAIN
5688                };
5689                let target_yaw_rate: f32 = if steer.abs() > 0.05 {
5690                    -steer * steer_sign * yaw_gain * steer_authority
5691                } else {
5692                    0.0
5693                };
5694                let yaw_resp: f32 = if drift_active { 12.0 } else { 32.0 };
5695                let yaw_blend: f32 = 1.0 - (-yaw_resp * sub_dt).exp();
5696                yaw_rate += (target_yaw_rate - yaw_rate) * yaw_blend;
5697                if drift_active {
5698                    let slip_excess: f32 = (slip_before.abs() - 0.56).max(0.0);
5699                    if slip_excess > 0.0 {
5700                        let align_torque: f32 = -slip_before.signum() * slip_excess * 5.8;
5701                        yaw_rate += align_torque * sub_dt;
5702                    }
5703                    if steer.abs() > 0.05 && slip_before.abs() < 0.28 {
5704                        let kick_dir: f32 = -steer.signum();
5705                        v_lat += -kick_dir * 6.5 * sub_dt;
5706                    }
5707                }
5708                if steer.abs() <= 0.05 && yaw_rate.abs() < 0.01 && active_speed < 0.1 {
5709                    yaw_rate = 0.0;
5710                }
5711                yaw_rate = yaw_rate.clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
5712                vel = fwd.scale(v_fwd).add(right.scale(v_lat));
5713                let (ccd_moved, wall_impact, wall_contact, wall_normal): (bool, f32, Vec3, Vec3) =
5714                    self.step_rigid_vehicle_static_ccd(
5715                        &mut flat_tr,
5716                        &mut vel,
5717                        &mut yaw_rate,
5718                        (
5719                            1.0 / VEHICLE_PLAYER_MASS_KG,
5720                            1.0 / VEHICLE_PLAYER_INERTIA_YAW,
5721                        ),
5722                        (car_idx, mesh_bounds),
5723                        VehicleCcdStepCtx3D {
5724                            sub_dt,
5725                            ground_limits,
5726                            ground_margin,
5727                        },
5728                    );
5729                let final_yaw: f32 = flat_tr.get_yaw_rad();
5730                let final_fwd: Vec3 = Vec3::new(-final_yaw.sin(), 0.0, -final_yaw.cos());
5731                let final_right: Vec3 = Vec3::new(final_yaw.cos(), 0.0, -final_yaw.sin());
5732                let post_vfwd: f32 = vel.dot(final_fwd);
5733                let post_vlat: f32 = vel.dot(final_right);
5734                let post_slip: f32 = if post_vfwd.abs() + post_vlat.abs() > 1.0 {
5735                    post_vlat.atan2(post_vfwd.abs().max(1.0))
5736                } else {
5737                    0.0
5738                };
5739                if drift_active {
5740                    drift_peak_slip = drift_peak_slip.max(post_slip.abs());
5741                }
5742                let mut cam_shake: f32 = phys.get_camera_shake() * (-7.5 * sub_dt).exp();
5743                if cam_shake < 0.004 {
5744                    cam_shake = 0.0;
5745                }
5746                let mut body_pitch: f32 = phys.get_body_pitch_rad();
5747                if wall_impact > 2.8 {
5748                    let imp_norm: f32 = ((wall_impact - 2.0) / 26.0).clamp(0.0, 1.0);
5749                    cam_shake = cam_shake.max(imp_norm * 0.65);
5750                    if wall_normal.dot(final_fwd) < -0.35 {
5751                        body_pitch = (body_pitch - imp_norm * 0.055).clamp(-0.08, 0.06);
5752                    }
5753                    self.emit_collision_sparks(wall_contact, wall_normal, imp_norm);
5754                }
5755                let target_roll: f32 = if post_vlat.abs() > 0.25 {
5756                    (-post_vlat * 0.011).clamp(-0.085, 0.085)
5757                } else {
5758                    0.0
5759                };
5760                let target_pitch: f32 = if boost_active {
5761                    0.036
5762                } else if long_accel > 8.0 {
5763                    0.018
5764                } else if long_accel < -15.0 {
5765                    -0.028
5766                } else {
5767                    0.0
5768                };
5769                let susp_blend: f32 = 1.0 - (-10.0 * sub_dt).exp();
5770                let mut body_roll: f32 = phys.get_body_roll_rad()
5771                    + (target_roll - phys.get_body_roll_rad()) * susp_blend;
5772                body_pitch += (target_pitch - body_pitch) * susp_blend;
5773                if body_roll.abs() < 0.0005 && target_roll == 0.0 {
5774                    body_roll = 0.0;
5775                }
5776                if body_pitch.abs() < 0.0005 && target_pitch == 0.0 {
5777                    body_pitch = 0.0;
5778                }
5779                let target_fov_boost: f32 = if boost_active {
5780                    CAMERA_BOOST_FOV_MAX_DEG
5781                } else if exit_kick_triggered {
5782                    CAMERA_BOOST_FOV_MAX_DEG * 0.6
5783                } else if drift_active && post_slip.abs() > 0.18 {
5784                    3.2
5785                } else {
5786                    0.0
5787                };
5788                let fov_blend: f32 = 1.0 - (-5.5 * sub_dt).exp();
5789                let mut cam_fov_boost: f32 = phys.get_camera_fov_boost()
5790                    + (target_fov_boost - phys.get_camera_fov_boost()) * fov_blend;
5791                if cam_fov_boost < 0.02 && target_fov_boost == 0.0 {
5792                    cam_fov_boost = 0.0;
5793                }
5794                phys.set_vel(vel);
5795                phys.set_yaw_rate(yaw_rate);
5796                phys.set_body_roll_rad(body_roll);
5797                phys.set_body_pitch_rad(body_pitch);
5798                phys.set_boost_active(boost_active);
5799                phys.set_boost_charge(boost_charge);
5800                phys.set_drift_active(drift_active);
5801                phys.set_drift_slip_angle(post_slip);
5802                phys.set_drift_duration(drift_duration);
5803                phys.set_drift_peak_slip(drift_peak_slip);
5804                phys.set_camera_fov_boost(cam_fov_boost);
5805                phys.set_camera_shake(cam_shake);
5806                {
5807                    let Self { player_physics, .. } = self;
5808                    *player_physics = phys;
5809                }
5810                let lift_y: f32 = (body_roll.abs() * 0.55 + body_pitch.abs() * 0.95).min(0.06);
5811                let mut visual_tr: Transform3D = Transform3D {
5812                    position: Vec3::new(
5813                        flat_tr.get_position().get_x(),
5814                        lift_y,
5815                        flat_tr.get_position().get_z(),
5816                    ),
5817                    rotation: Quat::from_euler_yxz(final_yaw, body_pitch, body_roll),
5818                    scale: flat_tr.get_scale(),
5819                };
5820                if (body_roll != 0.0 || body_pitch != 0.0)
5821                    && self
5822                        .mesh_oriented_box_static_collision(
5823                            visual_tr.to_oriented_box(mesh_bounds),
5824                            Some(car_idx),
5825                        )
5826                        .is_some()
5827                {
5828                    visual_tr = flat_tr;
5829                }
5830                let tr_changed: bool = ccd_moved || visual_tr != cur_tr;
5831                if tr_changed {
5832                    let world_b: AxisAlignedBox3D = visual_tr.transform_bounds(mesh_bounds);
5833                    if let Some(car_mut) = self.get_mut_objects().get_mut(car_idx) {
5834                        car_mut.set_transform(visual_tr);
5835                        car_mut.set_world_bounds(world_b);
5836                    }
5837                    player_moved_any = true;
5838                    if car_is_dynamic {
5839                        any_dynamic_moved = true;
5840                    } else {
5841                        any_static_moved = true;
5842                    }
5843                }
5844            }
5845            let traffic_count: usize = self.traffic_vehicle_count();
5846            for slot_idx in 0..traffic_count {
5847                let mut npc: NpcVehicle3D = {
5848                    let Self {
5849                        traffic_vehicles, ..
5850                    } = self;
5851                    traffic_vehicles[slot_idx]
5852                };
5853                let npc_idx: usize = npc.get_object_index();
5854                let Some((cur_tr, mesh_id, is_dynamic)) =
5855                    self.get_objects().get(npc_idx).map(|obj: &SceneObject3D| {
5856                        (obj.get_transform(), obj.get_mesh_id(), obj.get_is_dynamic())
5857                    })
5858                else {
5859                    continue;
5860                };
5861                let local_bounds: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_id);
5862                let mut tr: Transform3D = Transform3D::new(
5863                    Vec3::new(
5864                        cur_tr.get_position().get_x(),
5865                        0.0,
5866                        cur_tr.get_position().get_z(),
5867                    ),
5868                    cur_tr.get_yaw_rad(),
5869                    cur_tr.get_scale(),
5870                );
5871                let obb_npc: OrientedBox3D = tr.to_oriented_box(local_bounds);
5872                let margin: f32 = obb_npc
5873                    .get_half_extents()
5874                    .get_x()
5875                    .max(obb_npc.get_half_extents().get_z());
5876                let pos: Vec3 = tr.get_position();
5877                let yaw: f32 = tr.get_yaw_rad();
5878                let fwd: Vec3 = Vec3::new(-yaw.sin(), 0.0, -yaw.cos());
5879                let right: Vec3 = Vec3::new(yaw.cos(), 0.0, -yaw.sin());
5880                let mut vel: Vec3 = npc.get_vel();
5881                let mut yaw_rate: f32 = npc.get_yaw_rate();
5882                let mut recovery: f32 = npc.get_recovery_timer();
5883                if recovery > 0.0 {
5884                    recovery = (recovery - sub_dt).max(0.0);
5885                    let mut v_fwd: f32 = vel.dot(fwd);
5886                    let mut v_lat: f32 = vel.dot(right);
5887                    v_fwd *= (-1.15 * sub_dt).exp();
5888                    v_lat *= (-2.85 * sub_dt).exp();
5889                    vel = fwd.scale(v_fwd).add(right.scale(v_lat));
5890                    yaw_rate *= (-2.3 * sub_dt).exp();
5891                    if recovery <= 0.0 && yaw_rate.abs() < 0.8 {
5892                        let (route_id, wp_idx, wp_pos): (u8, usize, Vec3) =
5893                            NpcVehicle3D::nearest_open_waypoint(pos);
5894                        npc.set_route_id(route_id);
5895                        npc.set_waypoint_idx(wp_idx);
5896                        npc.set_nav_target(wp_pos);
5897                    }
5898                } else {
5899                    let mut v_fwd: f32 = vel.dot(fwd);
5900                    let mut v_lat: f32 = vel.dot(right);
5901                    let target_pt: Vec3 = if npc.get_free_roam_mode() {
5902                        let cur_tgt: Vec3 = npc.get_nav_target();
5903                        let to_t: Vec3 = Vec3::new(
5904                            cur_tgt.get_x() - pos.get_x(),
5905                            0.0,
5906                            cur_tgt.get_z() - pos.get_z(),
5907                        );
5908                        if to_t.length_sq() < 49.0 {
5909                            let wps: &[(f32, f32)] =
5910                                NpcVehicle3D::route_waypoints(npc.get_route_id());
5911                            let next_wp: usize = (npc.get_waypoint_idx() + 1) % wps.len();
5912                            let next_pt: Vec3 = Vec3::new(wps[next_wp].0, 0.0, wps[next_wp].1);
5913                            npc.set_waypoint_idx(next_wp);
5914                            npc.set_nav_target(next_pt);
5915                            next_pt
5916                        } else {
5917                            cur_tgt
5918                        }
5919                    } else {
5920                        let cur_s: f32 = npc.get_loop_arc_s();
5921                        let lane_u: f32 = npc.get_loop_lane_u();
5922                        let dir: f32 = npc.get_loop_dir();
5923                        let (_, base_yaw_at_s): (Vec3, f32) = Self::loop_pose_at(cur_s, lane_u);
5924                        let tan_yaw: f32 = if dir >= 0.0 {
5925                            base_yaw_at_s
5926                        } else {
5927                            base_yaw_at_s + PI
5928                        };
5929                        let tan_dir: Vec3 = Vec3::new(-tan_yaw.sin(), 0.0, -tan_yaw.cos());
5930                        let prog: f32 = vel.dot(tan_dir).max(0.0) * sub_dt;
5931                        let next_s: f32 = (cur_s + dir * prog).rem_euclid(CITY_LOOP_TOTAL_LENGTH);
5932                        npc.set_loop_arc_s(next_s);
5933                        let look_s: f32 = (next_s + dir * 11.0).rem_euclid(CITY_LOOP_TOTAL_LENGTH);
5934                        let (look_pt, _): (Vec3, f32) = Self::loop_pose_at(look_s, lane_u);
5935                        npc.set_nav_target(look_pt);
5936                        look_pt
5937                    };
5938                    let to_target: Vec3 = Vec3::new(
5939                        target_pt.get_x() - pos.get_x(),
5940                        0.0,
5941                        target_pt.get_z() - pos.get_z(),
5942                    );
5943                    let desired_yaw: f32 = if to_target.length_sq() > 1.0e-4 {
5944                        (-to_target.get_x()).atan2(-to_target.get_z())
5945                    } else {
5946                        yaw
5947                    };
5948                    let mut yaw_err: f32 = Self::wrap_angle_rad(desired_yaw - yaw);
5949                    let mut obstacle_slow: f32 = 1.0;
5950                    if npc.get_free_roam_mode() {
5951                        let probe_dist: f32 = (v_fwd.abs() * 0.55 + 5.5).clamp(5.0, 11.0);
5952                        let probe_tr: Transform3D =
5953                            Transform3D::new(pos.add(fwd.scale(probe_dist)), yaw, tr.get_scale());
5954                        if self
5955                            .mesh_oriented_box_static_collision(
5956                                probe_tr.to_oriented_box(local_bounds),
5957                                Some(npc_idx),
5958                            )
5959                            .is_some()
5960                        {
5961                            let left_yaw: f32 = yaw + 0.55;
5962                            let right_yaw: f32 = yaw - 0.55;
5963                            let left_fwd: Vec3 = Vec3::new(-left_yaw.sin(), 0.0, -left_yaw.cos());
5964                            let right_fwd: Vec3 =
5965                                Vec3::new(-right_yaw.sin(), 0.0, -right_yaw.cos());
5966                            let left_clear: bool = self
5967                                .mesh_oriented_box_static_collision(
5968                                    Transform3D::new(
5969                                        pos.add(left_fwd.scale(probe_dist)),
5970                                        left_yaw,
5971                                        tr.get_scale(),
5972                                    )
5973                                    .to_oriented_box(local_bounds),
5974                                    Some(npc_idx),
5975                                )
5976                                .is_none();
5977                            let right_clear: bool = self
5978                                .mesh_oriented_box_static_collision(
5979                                    Transform3D::new(
5980                                        pos.add(right_fwd.scale(probe_dist)),
5981                                        right_yaw,
5982                                        tr.get_scale(),
5983                                    )
5984                                    .to_oriented_box(local_bounds),
5985                                    Some(npc_idx),
5986                                )
5987                                .is_none();
5988                            if left_clear && !right_clear {
5989                                yaw_err = 0.85;
5990                                obstacle_slow = 0.65;
5991                            } else if right_clear && !left_clear {
5992                                yaw_err = -0.85;
5993                                obstacle_slow = 0.65;
5994                            } else if left_clear {
5995                                yaw_err = if yaw_err >= 0.0 { 0.85 } else { -0.85 };
5996                                obstacle_slow = 0.7;
5997                            } else {
5998                                yaw_err = 1.1;
5999                                obstacle_slow = 0.25;
6000                            }
6001                        }
6002                    }
6003                    let mut target_speed: f32 = npc.get_cruise_speed() * obstacle_slow;
6004                    if let Some(gap_m) =
6005                        self.npc_forward_blocking_gap(npc_idx, pos, fwd, right, v_fwd)
6006                    {
6007                        if gap_m < 9.5 {
6008                            target_speed = 0.0;
6009                        } else if gap_m < 14.5 {
6010                            target_speed *= ((gap_m - 9.5) / 5.0).clamp(0.0, 1.0);
6011                        }
6012                    }
6013                    let speed_diff: f32 = target_speed - v_fwd;
6014                    let accel_rate: f32 = if speed_diff < 0.0 { 36.0 } else { 18.0 };
6015                    v_fwd += speed_diff.clamp(-accel_rate * sub_dt, accel_rate * sub_dt);
6016                    if target_speed <= 0.05 && v_fwd.abs() < 0.15 {
6017                        v_fwd = 0.0;
6018                    }
6019                    v_lat *= (-8.5 * sub_dt).exp();
6020                    let target_omega: f32 = (yaw_err * 3.8).clamp(-2.6, 2.6);
6021                    let omega_blend: f32 = 1.0 - (-12.0 * sub_dt).exp();
6022                    yaw_rate += (target_omega - yaw_rate) * omega_blend;
6023                    if v_fwd.abs() < 0.1 {
6024                        yaw_rate *= (-8.0 * sub_dt).exp();
6025                    }
6026                    vel = fwd.scale(v_fwd).add(right.scale(v_lat));
6027                }
6028                let (npc_moved, npc_wall_imp, npc_wall_cp, npc_wall_n): (bool, f32, Vec3, Vec3) =
6029                    self.step_rigid_vehicle_static_ccd(
6030                        &mut tr,
6031                        &mut vel,
6032                        &mut yaw_rate,
6033                        (
6034                            1.0 / npc.get_mass().max(100.0),
6035                            1.0 / VEHICLE_NPC_INERTIA_YAW,
6036                        ),
6037                        (npc_idx, local_bounds),
6038                        VehicleCcdStepCtx3D {
6039                            sub_dt,
6040                            ground_limits,
6041                            ground_margin: margin,
6042                        },
6043                    );
6044                if npc_wall_imp > 3.5 {
6045                    let spark_int: f32 = ((npc_wall_imp - 2.5) / 22.0).clamp(0.15, 0.9);
6046                    self.emit_collision_sparks(npc_wall_cp, npc_wall_n, spark_int);
6047                    if npc.get_free_roam_mode() && recovery <= 0.0 {
6048                        let wps: &[(f32, f32)] = NpcVehicle3D::route_waypoints(npc.get_route_id());
6049                        let next_wp: usize = (npc.get_waypoint_idx() + 1) % wps.len();
6050                        npc.set_waypoint_idx(next_wp);
6051                        npc.set_nav_target(Vec3::new(wps[next_wp].0, 0.0, wps[next_wp].1));
6052                    }
6053                }
6054                npc.set_vel(vel);
6055                npc.set_yaw_rate(yaw_rate);
6056                npc.set_recovery_timer(recovery);
6057                {
6058                    let Self {
6059                        traffic_vehicles, ..
6060                    } = self;
6061                    traffic_vehicles[slot_idx] = npc;
6062                }
6063                if npc_moved {
6064                    let world_b: AxisAlignedBox3D = tr.transform_bounds(local_bounds);
6065                    if let Some(obj) = self.get_mut_objects().get_mut(npc_idx) {
6066                        obj.set_transform(tr);
6067                        obj.set_world_bounds(world_b);
6068                    }
6069                    if is_dynamic {
6070                        any_dynamic_moved = true;
6071                    } else {
6072                        any_static_moved = true;
6073                    }
6074                }
6075            }
6076            let (dyn_moved, dyn_imp, _dyn_cp, _dyn_n): (bool, f32, Vec3, Vec3) =
6077                self.resolve_dynamic_vehicle_collisions(ground_limits);
6078            if dyn_moved {
6079                any_dynamic_moved = true;
6080                player_moved_any = true;
6081            }
6082            if dyn_imp > 2.5 {
6083                let imp_norm: f32 = ((dyn_imp - 2.0) / 24.0).clamp(0.0, 1.0);
6084                let Self { player_physics, .. } = self;
6085                let next_shake: f32 = player_physics.get_camera_shake().max(imp_norm * 0.70);
6086                player_physics.set_camera_shake(next_shake);
6087            }
6088        }
6089        if let Some(car_idx) = car_opt
6090            && let Some((car_tr, mesh_id)) = self
6091                .get_objects()
6092                .get(car_idx)
6093                .map(|car: &SceneObject3D| (car.get_transform(), car.get_mesh_id()))
6094        {
6095            let car_bounds: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_id);
6096            let mut safe_tr: Transform3D = car_tr;
6097            let car_obb: OrientedBox3D = safe_tr.to_oriented_box(car_bounds);
6098            let car_margin: f32 = car_obb
6099                .get_half_extents()
6100                .get_x()
6101                .max(car_obb.get_half_extents().get_z());
6102            if self.depenetrate_vehicle_horizontally(
6103                &mut safe_tr,
6104                car_bounds,
6105                car_idx,
6106                ground_limits,
6107                car_margin,
6108            ) {
6109                let wb: AxisAlignedBox3D = safe_tr.transform_bounds(car_bounds);
6110                if let Some(car_mut) = self.get_mut_objects().get_mut(car_idx) {
6111                    car_mut.set_transform(safe_tr);
6112                    car_mut.set_world_bounds(wb);
6113                }
6114                player_moved_any = true;
6115                any_dynamic_moved = true;
6116            }
6117            let final_car_tr: Transform3D = self.get_objects()[car_idx].get_transform();
6118            let car_pos: Vec3 = final_car_tr.get_position();
6119            let yaw: f32 = final_car_tr.get_yaw_rad();
6120            let car_fwd: Vec3 = Vec3::new(-yaw.sin(), 0.0, -yaw.cos());
6121            let car_right: Vec3 = Vec3::new(yaw.cos(), 0.0, -yaw.sin());
6122            let phys: PlayerVehiclePhysics3D = {
6123                let Self { player_physics, .. } = self;
6124                *player_physics
6125            };
6126            if player_moved_any || phys.get_boost_active() || phys.get_drift_active() {
6127                let beam_dir: Vec3 = Vec3::new(car_fwd.get_x(), -0.14, car_fwd.get_z()).normalize();
6128                if self.get_spot_lights().len() >= 2 {
6129                    let front_center: Vec3 = car_pos
6130                        .add(car_fwd.scale(2.2))
6131                        .add(Vec3::new(0.0, 0.95, 0.0));
6132                    let left_pos: Vec3 = front_center.sub(car_right.scale(0.85));
6133                    let right_pos: Vec3 = front_center.add(car_right.scale(0.85));
6134                    let spots: &mut Vec<SpotLight3D> = self.get_mut_spot_lights();
6135                    spots[0].set_position(left_pos);
6136                    spots[0].set_direction(beam_dir);
6137                    spots[1].set_position(right_pos);
6138                    spots[1].set_direction(beam_dir);
6139                }
6140                if let Some(tail_light) = self.get_mut_point_lights().first_mut()
6141                    && tail_light.get_color().get_x() > 0.90
6142                    && tail_light.get_color().get_y() < 0.15
6143                {
6144                    let rear_pos: Vec3 = car_pos
6145                        .sub(car_fwd.scale(2.9))
6146                        .add(Vec3::new(0.0, 0.95, 0.0));
6147                    tail_light.set_position(rear_pos);
6148                    if phys.get_boost_active() {
6149                        tail_light.set_color(Vec3::new(1.0, 0.14, 0.06));
6150                        tail_light.set_intensity(4.5);
6151                        tail_light.set_radius(10.5);
6152                    } else if phys.get_drift_active() || throttle < -0.15 {
6153                        tail_light.set_color(Vec3::new(1.0, 0.06, 0.18));
6154                        tail_light.set_intensity(3.85);
6155                        tail_light.set_radius(9.6);
6156                    } else {
6157                        tail_light.set_color(Vec3::new(1.0, 0.09, 0.27));
6158                        tail_light.set_intensity(1.85);
6159                        tail_light.set_radius(8.5);
6160                    }
6161                }
6162                if phys.get_boost_active() && (sim_tick & 1) == 0 {
6163                    self.emit_boost_flame(car_pos, car_fwd, car_right, phys.get_vel());
6164                }
6165                if phys.get_drift_active()
6166                    && phys.get_drift_slip_angle().abs() > 0.12
6167                    && (sim_tick & 1) == 0
6168                {
6169                    self.emit_drift_smoke(
6170                        car_pos,
6171                        car_fwd,
6172                        car_right,
6173                        phys.get_drift_slip_angle().abs(),
6174                    );
6175                } else if throttle.abs() > 0.25
6176                    && !phys.get_boost_active()
6177                    && (sim_tick & 3) == 0
6178                    && self.get_niagara().get_active_count() < 24
6179                {
6180                    let exhaust_pos: Vec3 = car_pos
6181                        .sub(car_fwd.scale(2.3))
6182                        .add(Vec3::new(0.0, 0.42, 0.0));
6183                    let mut spark_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
6184                    spark_cfg.set_origin(exhaust_pos);
6185                    spark_cfg.set_base_velocity(car_fwd.scale(-4.5).add(Vec3::new(0.0, 1.1, 0.0)));
6186                    spark_cfg.set_start_size_m(0.11);
6187                    spark_cfg.set_end_size_m(0.03);
6188                    self.get_mut_niagara().emit_burst(1, &spark_cfg);
6189                }
6190            }
6191            let cam_mode: u8 = self.get_camera_mode();
6192            let fov_boost: f32 = phys.get_camera_fov_boost();
6193            let chase_pullback: f32 = fov_boost * 0.14;
6194            let reverse_speed_mps: f32 = -phys.get_vel().dot(car_fwd);
6195            let reverse_blend: f32 = ((reverse_speed_mps - 0.5) / 8.0).clamp(0.0, 1.0);
6196            let (mut desired_eye, look_target): (Vec3, Vec3) = match cam_mode {
6197                1 => {
6198                    let eye: Vec3 = Vec3::new(
6199                        car_pos.get_x() - yaw.sin() * 1.4,
6200                        2.15,
6201                        car_pos.get_z() - yaw.cos() * 1.4,
6202                    );
6203                    let tgt: Vec3 = Vec3::new(
6204                        car_pos.get_x() - yaw.sin() * 18.0,
6205                        1.8,
6206                        car_pos.get_z() - yaw.cos() * 18.0,
6207                    );
6208                    (eye, tgt)
6209                }
6210                2 => {
6211                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.45;
6212                    self.set_camera_orbit_rad(orbit);
6213                    let eye: Vec3 = Vec3::new(
6214                        car_pos.get_x() + orbit.sin() * 10.5,
6215                        5.2,
6216                        car_pos.get_z() + orbit.cos() * 10.5,
6217                    );
6218                    (eye, Vec3::new(car_pos.get_x(), 1.6, car_pos.get_z()))
6219                }
6220                3 => {
6221                    let eye: Vec3 = Vec3::new(
6222                        car_pos.get_x() + yaw.sin() * 18.0,
6223                        18.5,
6224                        car_pos.get_z() + yaw.cos() * 18.0,
6225                    );
6226                    (eye, Vec3::new(car_pos.get_x(), 1.2, car_pos.get_z()))
6227                }
6228                4 => {
6229                    let cur_cam: Camera3D = self.get_camera();
6230                    let fwd_c: Vec3 = cur_cam.forward();
6231                    let right_c: Vec3 = cur_cam.right();
6232                    let moved: Vec3 = cur_cam
6233                        .get_position()
6234                        .add(fwd_c.scale(throttle * 18.0 * dt))
6235                        .add(right_c.scale(steer * 14.0 * dt));
6236                    let eye: Vec3 = Vec3::new(moved.get_x(), moved.get_y().max(1.5), moved.get_z());
6237                    (eye, eye.add(fwd_c.scale(16.0)))
6238                }
6239                5 => {
6240                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.28;
6241                    self.set_camera_orbit_rad(orbit);
6242                    let eye: Vec3 = Vec3::new(
6243                        car_pos.get_x() + orbit.sin() * 7.8,
6244                        3.6 + (orbit * 1.5).sin() * 1.4,
6245                        car_pos.get_z() + orbit.cos() * 13.5,
6246                    );
6247                    (eye, Vec3::new(car_pos.get_x(), 1.8, car_pos.get_z() - 3.0))
6248                }
6249                _ => {
6250                    let chase_dist: f32 = 9.8 + chase_pullback + reverse_blend * 2.4;
6251                    let eye: Vec3 = Vec3::new(
6252                        car_pos.get_x() + yaw.sin() * chase_dist,
6253                        4.25 + chase_pullback * 0.12 + reverse_blend * 0.55,
6254                        car_pos.get_z() + yaw.cos() * chase_dist,
6255                    );
6256                    let tgt: Vec3 = Vec3::new(
6257                        car_pos.get_x() - yaw.sin() * 16.0,
6258                        2.40 - reverse_blend * 0.65,
6259                        car_pos.get_z() - yaw.cos() * 16.0,
6260                    );
6261                    (eye, tgt)
6262                }
6263            };
6264            let shake_amp: f32 = phys.get_camera_shake();
6265            if shake_amp > 0.005 {
6266                let phase: f32 = self.get_world_time_secs() * 54.0;
6267                let sx: f32 = phase.sin() * shake_amp * 0.34;
6268                let sy: f32 = (phase * 1.37).cos() * shake_amp * 0.22;
6269                desired_eye = desired_eye
6270                    .add(car_right.scale(sx))
6271                    .add(Vec3::new(0.0, sy, 0.0));
6272            }
6273            let boom_anchor: Vec3 =
6274                Vec3::new(car_pos.get_x(), car_pos.get_y() + 1.8, car_pos.get_z());
6275            let boom_vec: Vec3 = desired_eye.sub(boom_anchor);
6276            let boom_len: f32 = boom_vec.length();
6277            if boom_len > 0.25 {
6278                let boom_dir: Vec3 = boom_vec.scale(1.0 / boom_len);
6279                if let Some(hit) =
6280                    self.raycast_solid_meshes(boom_anchor, boom_dir, boom_len, Some(car_idx))
6281                {
6282                    let safe_dist: f32 = (hit.get_distance() - 0.55).max(0.8);
6283                    desired_eye = boom_anchor.add(boom_dir.scale(safe_dist));
6284                }
6285            }
6286            let cam_probe: OrientedBox3D = OrientedBox3D::from_bounds(AxisAlignedBox3D::new(
6287                desired_eye.sub(Vec3::splat(0.45)),
6288                desired_eye.add(Vec3::splat(0.45)),
6289            ));
6290            if let Some(hit) = self.mesh_oriented_box_collision(cam_probe, Some(car_idx)) {
6291                desired_eye = desired_eye.add(hit.get_normal().scale(hit.get_penetration() + 0.1));
6292            }
6293            let prev_cam: Camera3D = self.get_camera();
6294            let mut cam: Camera3D = prev_cam;
6295            let follow_rate: f32 = 7.0 + reverse_blend * 5.0;
6296            let smooth: f32 = (dt * follow_rate).clamp(0.05, 1.0);
6297            cam.set_position(cam.get_position().lerp(desired_eye, smooth));
6298            let look_dir: Vec3 = look_target.sub(cam.get_position()).normalize();
6299            cam.set_yaw(look_dir.get_z().atan2(look_dir.get_x()));
6300            cam.set_pitch(look_dir.get_y().clamp(-0.92, 0.92).asin());
6301            cam.set_fov_deg(CAMERA_BASE_FOV_DEG + fov_boost);
6302            self.set_camera(cam);
6303            if cam != prev_cam {
6304                self.bump_world_revision();
6305            }
6306        }
6307        let Self {
6308            objects,
6309            mesh_library,
6310            ..
6311        } = self;
6312        for obj in objects.iter_mut() {
6313            let spin: f32 = obj.get_spin_speed();
6314            if spin.abs() > 0.001 {
6315                let mut object_transform: Transform3D = obj.get_transform();
6316                object_transform.set_yaw_rad(object_transform.get_yaw_rad() + spin * dt);
6317                obj.set_transform(object_transform);
6318                let local_bounds: AxisAlignedBox3D = mesh_library
6319                    .get(obj.get_mesh_id())
6320                    .and_then(|color_item: &MeshLodChain| color_item.get_levels().first())
6321                    .map(Mesh3D::get_bounds)
6322                    .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
6323                obj.set_world_bounds(object_transform.transform_bounds(local_bounds));
6324                if obj.get_is_dynamic() {
6325                    any_dynamic_moved = true;
6326                } else {
6327                    any_static_moved = true;
6328                }
6329            }
6330        }
6331        if self.get_atmosphere_preset() == 1
6332            && (sim_tick & 1) == 0
6333            && self.get_niagara().get_active_count() < RAINY_NIGHT_MAX_PARTICLES
6334        {
6335            let cam_pos: Vec3 = self.get_camera().get_position();
6336            let mut rain_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
6337            rain_cfg.set_origin(cam_pos.add(Vec3::new(0.0, 5.0, -14.0)));
6338            rain_cfg.set_base_velocity(Vec3::new(-0.5, -15.5, 0.3));
6339            rain_cfg.set_velocity_spread(3.6);
6340            rain_cfg.set_start_color(Color::rgba(150, 218, 255, 210));
6341            rain_cfg.set_end_color(Color::rgba(68, 152, 240, 60));
6342            rain_cfg.set_start_size_m(0.07);
6343            rain_cfg.set_end_size_m(0.03);
6344            rain_cfg.set_min_lifetime(0.6);
6345            rain_cfg.set_max_lifetime(0.95);
6346            rain_cfg.set_emissive_boost(1.4);
6347            self.get_mut_niagara().emit_burst(2, &rain_cfg);
6348        }
6349        if self.get_niagara().get_active_count() > 0 {
6350            let _: usize = self.get_mut_niagara().update(dt, 0.0);
6351        }
6352        if !self.get_animation_mixer().get_layers().is_empty() {
6353            let anim_updates: usize = self.tick_animations(dt);
6354            if anim_updates > 0 {
6355                any_dynamic_moved = true;
6356            }
6357        }
6358        if any_static_moved {
6359            self.set_bvh_dirty(true);
6360        }
6361        if any_dynamic_moved {
6362            self.set_dynamic_bvh_dirty(true);
6363        }
6364        if any_static_moved || any_dynamic_moved {
6365            self.bump_world_revision();
6366        }
6367    }
6368
6369    /// Returns the optional precomputed IBL environment attached to this world.
6370    ///
6371    /// # Returns
6372    ///
6373    /// - `Option<&EnvironmentIbl3D>` - Borrowed IBL environment if configured.
6374    #[must_use]
6375    pub fn environment_ibl(&self) -> Option<&EnvironmentIbl3D> {
6376        let Self {
6377            environment_ibl, ..
6378        } = self;
6379        environment_ibl.as_ref()
6380    }
6381
6382    /// Replaces the world's active IBL environment and increments the world revision.
6383    ///
6384    /// # Arguments
6385    ///
6386    /// - `&Self` - Mutable world.
6387    /// - `Option<EnvironmentIbl3D>` - New IBL environment or `None` to clear.
6388    pub fn set_environment_ibl(&mut self, ibl: Option<EnvironmentIbl3D>) {
6389        let Self {
6390            environment_ibl, ..
6391        } = self;
6392        *environment_ibl = ibl;
6393        self.bump_world_revision();
6394    }
6395
6396    /// Returns the currently active multi-camera index inside `scene_cameras`, if selected.
6397    ///
6398    /// # Returns
6399    ///
6400    /// - `Option<usize>` - Active camera index in `scene_cameras`, or `None` when using `camera`.
6401    #[must_use]
6402    pub fn active_scene_camera_index(&self) -> Option<usize> {
6403        let Self {
6404            active_scene_camera,
6405            ..
6406        } = self;
6407        *active_scene_camera
6408    }
6409
6410    /// Selects an active camera from `scene_cameras` (or `None` to revert to the default `camera`).
6411    ///
6412    /// # Arguments
6413    ///
6414    /// - `&Self` - Mutable world.
6415    /// - `Option<usize>` - Target camera index inside `scene_cameras`.
6416    ///
6417    /// # Returns
6418    ///
6419    /// - `bool` - `true` when the requested camera selection succeeded.
6420    pub fn set_active_scene_camera(&mut self, camera_index: Option<usize>) -> bool {
6421        let cam_count: usize = self.get_scene_cameras().len();
6422        if let Some(target_idx) = camera_index
6423            && target_idx >= cam_count
6424        {
6425            return false;
6426        }
6427        let Self {
6428            active_scene_camera,
6429            ..
6430        } = self;
6431        *active_scene_camera = camera_index;
6432        if let Some(target_idx) = camera_index
6433            && let Some(scene_cam) = self.get_scene_cameras().get(target_idx).cloned()
6434        {
6435            self.set_camera(scene_cam.to_camera3d());
6436        }
6437        self.bump_world_revision();
6438        true
6439    }
6440
6441    /// Returns the active camera's view-projection matrix (respecting Perspective or Orthographic `SceneCamera3D` when selected).
6442    ///
6443    /// # Arguments
6444    ///
6445    /// - `&Self` - World reference.
6446    /// - `f32` - Viewport width-to-height aspect ratio.
6447    ///
6448    /// # Returns
6449    ///
6450    /// - `Mat4` - Active view-projection matrix.
6451    #[must_use]
6452    pub fn active_view_projection(&self, viewport_aspect: f32) -> Mat4 {
6453        if let Some(cam_idx) = self.active_scene_camera_index()
6454            && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
6455        {
6456            return scene_cam.view_projection(viewport_aspect);
6457        }
6458        self.get_camera().view_projection(viewport_aspect)
6459    }
6460
6461    /// Returns the live deformed (morphed and/or skinned) `Mesh3D` for `obj_idx` if active.
6462    ///
6463    /// # Arguments
6464    ///
6465    /// - `&Self` - World reference.
6466    /// - `usize` - Target object index in `objects`.
6467    ///
6468    /// # Returns
6469    ///
6470    /// - `Option<&Mesh3D>` - Borrowed deformed mesh when shape keys or armature skinning are active on `obj_idx`.
6471    #[must_use]
6472    pub fn deformed_mesh_for_object(&self, obj_idx: usize) -> Option<&Mesh3D> {
6473        let Self {
6474            deformed_meshes, ..
6475        } = self;
6476        deformed_meshes.get(obj_idx).and_then(Option::as_ref)
6477    }
6478
6479    /// Returns whether `obj_idx` is effectively visible after evaluating hierarchical node visibility and 64-bit Blender Collections masks.
6480    ///
6481    /// # Arguments
6482    ///
6483    /// - `&Self` - World reference.
6484    /// - `usize` - Target object index in `objects`.
6485    ///
6486    /// # Returns
6487    ///
6488    /// - `bool` - `true` when the object should be rendered.
6489    #[must_use]
6490    pub fn is_object_visible(&self, obj_idx: usize) -> bool {
6491        let Some(obj) = self.get_objects().get(obj_idx) else {
6492            return false;
6493        };
6494        if let Some(node_id) = obj.try_get_node_id() {
6495            return self.get_scene_graph().is_node_effectively_visible(node_id);
6496        }
6497        true
6498    }
6499
6500    /// Updates the deformation algorithm (`LinearBlend` or `DualQuaternion`) for skin `skin_idx` and refreshes deformed meshes immediately.
6501    ///
6502    /// # Arguments
6503    ///
6504    /// - `&Self` - Mutable world.
6505    /// - `usize` - Skin index inside `skins`.
6506    /// - `SkinningMode` - Desired skinning mode.
6507    ///
6508    /// # Returns
6509    ///
6510    /// - `bool` - `true` when `skin_idx` existed.
6511    pub fn set_skinning_mode(&mut self, skin_idx: usize, mode: SkinningMode) -> bool {
6512        let Some(skin) = self.get_mut_skins().get_mut(skin_idx) else {
6513            return false;
6514        };
6515        skin.set_skinning_mode(mode);
6516        let _: usize = self.update_deformed_meshes();
6517        self.bump_world_revision();
6518        true
6519    }
6520
6521    /// Toggles viewport visibility for Blender Collection `collection_name` in `scene_graph`.
6522    ///
6523    /// # Arguments
6524    ///
6525    /// - `&Self` - Mutable world.
6526    /// - `&str` - Collection name.
6527    /// - `bool` - Desired viewport visibility state.
6528    ///
6529    /// # Returns
6530    ///
6531    /// - `bool` - `true` when a matching collection was updated.
6532    pub fn set_collection_visible(&mut self, collection_name: &str, visible: bool) -> bool {
6533        let updated: bool = self
6534            .get_mut_scene_graph()
6535            .get_mut_collections()
6536            .set_collection_visible(collection_name, visible);
6537        if updated {
6538            self.bump_world_revision();
6539        }
6540        updated
6541    }
6542
6543    /// Loads an `ImportedScene3D` (from glTF 2.0 / binary GLB / `.euv3d`) directly into `World3D`, wiring hierarchy, collections, Principled BSDF materials, mipmapped textures, skins, animations, cameras, and lights.
6544    ///
6545    /// # Arguments
6546    ///
6547    /// - `&Self` - Mutable 3D world.
6548    /// - `&ImportedScene3D` - Parsed Blender/glTF 2.0 scene bundle.
6549    ///
6550    /// # Returns
6551    ///
6552    /// - `Vec<usize>` - Indices of all spawned `SceneObject3D` entries inside `World3D::objects`.
6553    pub fn load_imported_scene(&mut self, scene: &ImportedScene3D) -> Vec<usize> {
6554        let texture_base: u32 = self.get_textures().len() as u32;
6555        self.get_mut_textures()
6556            .extend(scene.get_textures().iter().cloned());
6557        let material_base: u32 = self.get_principled_materials().len() as u32;
6558        for raw_mat in scene.get_materials().iter() {
6559            let mut rebased: PrincipledMaterial3D = raw_mat.clone();
6560            Self::rebase_material_textures(&mut rebased, texture_base);
6561            self.get_mut_principled_materials().push(rebased);
6562        }
6563        let mesh_base: usize = self.get_mesh_library().len();
6564        for raw_mesh in scene.get_meshes().iter() {
6565            let mut mesh_copy: Mesh3D = raw_mesh.clone();
6566            if let Some(local_mat_id) = mesh_copy.try_get_material_index() {
6567                mesh_copy.set_material_index(Some(local_mat_id.saturating_add(material_base)));
6568            }
6569            let lod_chain: MeshLodChain = if mesh_copy.get_indices().len() > 24 {
6570                build_qem_lod_chain(&mesh_copy, 3)
6571            } else {
6572                MeshLodChain::from_mesh(mesh_copy)
6573            };
6574            let _: usize = self.register_mesh(lod_chain);
6575        }
6576        let node_base: u32 = self.get_scene_graph().get_nodes().len() as u32;
6577        let skin_base: u32 = self.get_skins().len() as u32;
6578        let mut collection_bit_remap: Vec<u64> = Vec::new();
6579        for coll_entry in scene
6580            .get_scene_graph()
6581            .get_collections()
6582            .get_entries()
6583            .iter()
6584        {
6585            let mask_val: u64 = self
6586                .get_mut_scene_graph()
6587                .get_mut_collections()
6588                .register_collection(coll_entry.get_name());
6589            if !coll_entry.get_visible_viewport() {
6590                let _: bool = self
6591                    .get_mut_scene_graph()
6592                    .get_mut_collections()
6593                    .set_collection_visible(coll_entry.get_name(), false);
6594            }
6595            collection_bit_remap.push(mask_val);
6596        }
6597        let src_graph: &SceneGraph3D = scene.get_scene_graph();
6598        let src_nodes: &[SceneNode3D] = src_graph.get_nodes().as_slice();
6599        for (src_idx, src_node) in src_nodes.iter().enumerate() {
6600            let rebased_parent: Option<u32> = src_node
6601                .try_get_parent()
6602                .map(|parent_idx: u32| parent_idx.saturating_add(node_base));
6603            let node_label: &str = if src_node.get_name().is_empty() {
6604                BLENDER_IMPORTED_NODE_FALLBACK
6605            } else {
6606                src_node.get_name().as_str()
6607            };
6608            let mut dst_node: SceneNode3D = SceneNode3D::from_name(node_label, rebased_parent);
6609            dst_node.set_local_translation(src_node.get_local_translation());
6610            dst_node.set_local_rotation(src_node.get_local_rotation());
6611            dst_node.set_local_scale(src_node.get_local_scale());
6612            dst_node.set_visible(src_node.get_visible());
6613            dst_node.set_extras(src_node.get_extras().clone());
6614            let mut mapped_mask: u64 = 0;
6615            let raw_mask: u64 = src_node.get_collection_mask();
6616            for (bit_pos, &dst_bit) in collection_bit_remap.iter().enumerate() {
6617                if (raw_mask & (1_u64 << (bit_pos as u32))) != 0 {
6618                    mapped_mask |= dst_bit;
6619                }
6620            }
6621            dst_node.set_collection_mask(if mapped_mask == 0 { 1 } else { mapped_mask });
6622            if let Some(src_mesh_id) = src_node.try_get_mesh_id() {
6623                dst_node.set_mesh_id(Some((mesh_base as u32).saturating_add(src_mesh_id)));
6624            }
6625            if let Some(src_skin_id) = src_node.try_get_skin_id() {
6626                dst_node.set_skin_id(Some(skin_base.saturating_add(src_skin_id)));
6627            }
6628            dst_node.set_camera_id(src_node.try_get_camera_id());
6629            dst_node.set_light_id(src_node.try_get_light_id());
6630            let dst_node_id: u32 = self.get_mut_scene_graph().add_node(dst_node);
6631            let src_weights: &[f32] = src_graph.morph_weights_for_node(src_idx as u32);
6632            if !src_weights.is_empty() {
6633                self.get_mut_scene_graph()
6634                    .attach_morph_weights(dst_node_id, src_weights);
6635            }
6636            let Self {
6637                node_object_map, ..
6638            } = self;
6639            node_object_map.push(None);
6640        }
6641        let _: usize = self.get_mut_scene_graph().propagate_world_matrices();
6642        for src_skin in scene.get_skins().iter() {
6643            let mut runtime_skin: Skin3D = Skin3D::from_imported(src_skin);
6644            for joint_node in runtime_skin.get_mut_joints().iter_mut() {
6645                *joint_node = joint_node.saturating_add(node_base);
6646            }
6647            if let Some(root_idx) = runtime_skin.try_get_skeleton_root() {
6648                runtime_skin.set_skeleton_root(Some(root_idx.saturating_add(node_base)));
6649            }
6650            self.get_mut_skins().push(runtime_skin);
6651        }
6652        let mut first_clip_added: Option<usize> = None;
6653        for src_clip in scene.get_animations().iter() {
6654            let mut rebased_clip: ImportedAnimationClip3D = src_clip.clone();
6655            for chan in rebased_clip.get_mut_channels().iter_mut() {
6656                chan.set_target_node(chan.get_target_node().saturating_add(node_base));
6657            }
6658            let clip_idx: usize = self.get_mut_animation_mixer().add_clip(rebased_clip);
6659            if first_clip_added.is_none() {
6660                first_clip_added = Some(clip_idx);
6661            }
6662        }
6663        let graph_snapshot: SceneGraph3D = self.get_scene_graph().clone();
6664        self.get_mut_animation_mixer()
6665            .capture_rest_pose(&graph_snapshot);
6666        if let Some(clip_idx) = first_clip_added
6667            && self.get_animation_mixer().get_layers().is_empty()
6668        {
6669            let _: usize = self
6670                .get_mut_animation_mixer()
6671                .push_layer(NlaLayer3D::new(clip_idx));
6672        }
6673        let mut spawned_objects: Vec<usize> = Vec::new();
6674        let total_nodes: usize = self.get_scene_graph().get_nodes().len();
6675        for node_idx in (node_base as usize)..total_nodes {
6676            let node_copy: SceneNode3D = self.get_scene_graph().get_nodes()[node_idx].clone();
6677            let world_mat: Mat4 = node_copy.get_world_matrix();
6678            let world_tr: Transform3D = Transform3D::from_matrix(world_mat);
6679            if let Some(global_mesh_id) = node_copy.try_get_mesh_id() {
6680                let mesh_usize: usize = global_mesh_id as usize;
6681                let principled_id: Option<u32> = self
6682                    .get_mesh_library()
6683                    .get(mesh_usize)
6684                    .and_then(|chain: &MeshLodChain| chain.get_levels().first())
6685                    .and_then(|mesh_ref: &Mesh3D| mesh_ref.try_get_material_index());
6686                let legacy_mat: PbrMaterial = principled_id
6687                    .and_then(|mat_idx: u32| self.get_principled_materials().get(mat_idx as usize))
6688                    .map_or_else(
6689                        || {
6690                            self.get_mesh_library()
6691                                .get(mesh_usize)
6692                                .and_then(|chain: &MeshLodChain| chain.get_levels().first())
6693                                .map_or_else(PbrMaterial::default, Mesh3D::get_material)
6694                        },
6695                        PrincipledMaterial3D::to_legacy_pbr,
6696                    );
6697                let cast_shadows: bool = node_copy.get_extras().get_cast_shadows();
6698                let obj_idx: usize = self.spawn_object(
6699                    node_copy.get_name(),
6700                    mesh_usize,
6701                    world_tr,
6702                    legacy_mat,
6703                    cast_shadows,
6704                );
6705                let skin_opt: Option<u32> = node_copy.try_get_skin_id();
6706                let is_deformable: bool =
6707                    skin_opt.is_some() || node_copy.get_morph_weight_count() > 0;
6708                if let Some(obj_mut) = self.get_mut_objects().get_mut(obj_idx) {
6709                    obj_mut.set_node_id(Some(node_idx as u32));
6710                    obj_mut.set_principled_material_id(principled_id);
6711                    obj_mut.set_skin_id(skin_opt);
6712                }
6713                if is_deformable {
6714                    let _: bool = self.set_object_dynamic(obj_idx, true);
6715                }
6716                let Self {
6717                    node_object_map, ..
6718                } = self;
6719                if let Some(slot) = node_object_map.get_mut(node_idx) {
6720                    *slot = Some(obj_idx);
6721                }
6722                spawned_objects.push(obj_idx);
6723            }
6724            if let Some(src_cam_id) = node_copy.try_get_camera_id()
6725                && let Some(imp_cam) = scene.get_cameras().get(src_cam_id as usize)
6726            {
6727                self.get_mut_scene_cameras()
6728                    .push(SceneCamera3D::from_imported(
6729                        imp_cam,
6730                        Some(node_idx as u32),
6731                        world_tr.get_position(),
6732                        world_tr.get_rotation(),
6733                    ));
6734            }
6735            if let Some(src_light_id) = node_copy.try_get_light_id()
6736                && let Some(imp_light) = scene.get_lights().get(src_light_id as usize)
6737            {
6738                let emit_dir: Vec3 = world_tr
6739                    .get_rotation()
6740                    .rotate_vec3(Vec3::new(0.0, 0.0, -1.0))
6741                    .normalize();
6742                let light_color: Vec3 = imp_light.get_color();
6743                let light_intensity: f32 = imp_light.get_intensity();
6744                match imp_light.get_kind() {
6745                    GltfLightKind::Directional => {
6746                        let mut sun_val: DirectionalLight3D = self.get_sun();
6747                        sun_val.set_direction(emit_dir.scale(-1.0).normalize());
6748                        sun_val.set_color(light_color.scale(light_intensity.max(0.05)));
6749                        self.set_sun(sun_val);
6750                    }
6751                    GltfLightKind::Point { range } => {
6752                        let resolved_range: f32 = range.unwrap_or(24.0).max(0.5);
6753                        self.get_mut_point_lights().push(PointLight3D::from_linear(
6754                            world_tr.get_position(),
6755                            light_color,
6756                            light_intensity,
6757                            resolved_range,
6758                        ));
6759                    }
6760                    GltfLightKind::Spot {
6761                        range,
6762                        inner_cone_angle,
6763                        outer_cone_angle,
6764                    } => {
6765                        let resolved_range: f32 = range.unwrap_or(32.0).max(0.5);
6766                        self.get_mut_spot_lights().push(SpotLight3D::from_linear(
6767                            world_tr.get_position(),
6768                            emit_dir,
6769                            light_color,
6770                            light_intensity,
6771                            resolved_range,
6772                            (inner_cone_angle, outer_cone_angle),
6773                        ));
6774                    }
6775                    GltfLightKind::Area { width, height } => {
6776                        self.get_mut_area_lights().push(AreaLight3D::new_rect(
6777                            world_tr.get_position(),
6778                            emit_dir,
6779                            light_color,
6780                            light_intensity,
6781                            (width, height),
6782                            28.0,
6783                        ));
6784                    }
6785                }
6786            }
6787        }
6788        let _: usize = self.update_deformed_meshes();
6789        if self.environment_ibl().is_none() {
6790            let sun_ref: DirectionalLight3D = self.get_sun();
6791            let baked_ibl: EnvironmentIbl3D = EnvironmentIbl3D::from_procedural_sky(
6792                &sun_ref,
6793                WORLD_DEFAULT_IBL_OCT_SIZE,
6794                WORLD_DEFAULT_IBL_LUT_SIZE,
6795            );
6796            self.set_environment_ibl(Some(baked_ibl));
6797        }
6798        self.set_use_agx_tonemap(true);
6799        self.set_imported_model_count(self.get_imported_model_count().saturating_add(1));
6800        self.set_bvh_dirty(true);
6801        self.set_dynamic_bvh_dirty(true);
6802        self.set_dynamic_topology_dirty(true);
6803        self.bump_world_revision();
6804        spawned_objects
6805    }
6806
6807    /// Parses binary `.glb` or `.gltf` JSON bytes and loads the resulting Blender scene directly into `World3D`.
6808    ///
6809    /// # Arguments
6810    ///
6811    /// - `&Self` - Mutable 3D world.
6812    /// - `&[u8]` - Raw `.glb` or `.gltf` bytes.
6813    ///
6814    /// # Returns
6815    ///
6816    /// - `Result<Vec<usize>, String>` - Spawned object indices or structured glTF import error.
6817    pub fn load_glb_bytes(&mut self, bytes: &[u8]) -> Result<Vec<usize>, String> {
6818        let imported: ImportedScene3D = parse_gltf_or_glb_bytes(bytes, None)?;
6819        Ok(self.load_imported_scene(&imported))
6820    }
6821
6822    /// Parses pure-Rust Blender 3.x/4.x/5.x `.blend` bytes directly and loads the resulting scene into this `World3D`.
6823    ///
6824    /// # Arguments
6825    ///
6826    /// - `&[u8]` - Raw `.blend` binary buffer (uncompressed, gzip, or Zstd).
6827    ///
6828    /// # Returns
6829    ///
6830    /// - `Result<Vec<usize>, String>` - Spawned object indices or structured `.blend` import error.
6831    pub fn load_blend_bytes(&mut self, bytes: &[u8]) -> Result<Vec<usize>, String> {
6832        let imported: ImportedScene3D = parse_blend_bytes(bytes)?;
6833        Ok(self.load_imported_scene(&imported))
6834    }
6835
6836    /// Decodes a baked `.euv3d` (v1 or v2) binary package and loads its scene hierarchy, meshes, and materials into this `World3D`.
6837    ///
6838    /// # Arguments
6839    ///
6840    /// - `&[u8]` - Raw `.euv3d` binary buffer.
6841    ///
6842    /// # Returns
6843    ///
6844    /// - `Result<Vec<usize>, String>` - Spawned object indices or structured `.euv3d` decode error.
6845    pub fn load_euv3d_bytes(&mut self, bytes: &[u8]) -> Result<Vec<usize>, String> {
6846        let bundle: BakedAssetBundle3D = Euv3dPackage::decode_any_bytes(bytes)?;
6847        Ok(self.load_imported_scene(bundle.get_scene()))
6848    }
6849
6850    /// Tests a single local-space ray against `mesh` using meshlet AABB pruning and exact Möller–Trumbore triangle intersection.
6851    ///
6852    /// # Arguments
6853    ///
6854    /// - `&Mesh3D` - Candidate triangle mesh in local object space.
6855    /// - `Vec3` - Ray origin in mesh local space.
6856    /// - `Vec3` - Ray direction in mesh local space (unnormalized so parametric `t` matches world distance).
6857    /// - `Vec3` - Reciprocal local ray direction for AABB slab pruning.
6858    /// - `f32` - Minimum valid hit distance `t_min`.
6859    /// - `f32` - Current closest hit distance ceiling `best_t`.
6860    ///
6861    /// # Returns
6862    ///
6863    /// - `Option<(f32, Vec3)>` - Nearest `(hit_t, local_unit_normal)` strictly closer than `best_t`, or `None`.
6864    #[must_use]
6865    fn intersect_mesh_triangles_local(
6866        mesh: &Mesh3D,
6867        local_origin: Vec3,
6868        local_dir: Vec3,
6869        local_inv_dir: Vec3,
6870        t_min: f32,
6871        best_t: f32,
6872    ) -> Option<(f32, Vec3)> {
6873        let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
6874        let tris: &[[u32; 3]] = mesh.get_indices().as_slice();
6875        if verts.is_empty() || tris.is_empty() {
6876            return None;
6877        }
6878        let mut closest_t: f32 = best_t;
6879        let mut closest_normal: Vec3 = Vec3::zero();
6880        let mut hit_any: bool = false;
6881        let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
6882        if !meshlets.is_empty() {
6883            for meshlet in meshlets.iter() {
6884                let mbox: AxisAlignedBox3D = meshlet.get_bounds();
6885                let box_t: f32 =
6886                    mbox.intersect_ray_near(local_origin, local_inv_dir, t_min, closest_t);
6887                if box_t >= closest_t {
6888                    continue;
6889                }
6890                let start: usize = meshlet.get_first_tri() as usize;
6891                let end: usize = start
6892                    .saturating_add(meshlet.get_tri_count() as usize)
6893                    .min(tris.len());
6894                for tri in &tris[start..end] {
6895                    let (i0, i1, i2): (usize, usize, usize) =
6896                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
6897                    if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
6898                        continue;
6899                    }
6900                    let v0: Vec3 = verts[i0].get_position();
6901                    let e1: Vec3 = verts[i1].get_position().sub(v0);
6902                    let e2: Vec3 = verts[i2].get_position().sub(v0);
6903                    let h: Vec3 = local_dir.cross(e2);
6904                    let a: f32 = e1.dot(h);
6905                    if a.abs() < 1e-7 {
6906                        continue;
6907                    }
6908                    let inv_a: f32 = 1.0 / a;
6909                    let s: Vec3 = local_origin.sub(v0);
6910                    let u: f32 = inv_a * s.dot(h);
6911                    if !(0.0..=1.0).contains(&u) {
6912                        continue;
6913                    }
6914                    let q: Vec3 = s.cross(e1);
6915                    let v: f32 = inv_a * local_dir.dot(q);
6916                    if v < 0.0 || (u + v) > 1.0 {
6917                        continue;
6918                    }
6919                    let t: f32 = inv_a * e2.dot(q);
6920                    if t >= t_min && t < closest_t {
6921                        closest_t = t;
6922                        closest_normal = e1.cross(e2).normalize();
6923                        hit_any = true;
6924                    }
6925                }
6926            }
6927        } else {
6928            for tri in tris.iter() {
6929                let (i0, i1, i2): (usize, usize, usize) =
6930                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
6931                if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
6932                    continue;
6933                }
6934                let v0: Vec3 = verts[i0].get_position();
6935                let e1: Vec3 = verts[i1].get_position().sub(v0);
6936                let e2: Vec3 = verts[i2].get_position().sub(v0);
6937                let h: Vec3 = local_dir.cross(e2);
6938                let a: f32 = e1.dot(h);
6939                if a.abs() < 1e-7 {
6940                    continue;
6941                }
6942                let inv_a: f32 = 1.0 / a;
6943                let s: Vec3 = local_origin.sub(v0);
6944                let u: f32 = inv_a * s.dot(h);
6945                if !(0.0..=1.0).contains(&u) {
6946                    continue;
6947                }
6948                let q: Vec3 = s.cross(e1);
6949                let v: f32 = inv_a * local_dir.dot(q);
6950                if v < 0.0 || (u + v) > 1.0 {
6951                    continue;
6952                }
6953                let t: f32 = inv_a * e2.dot(q);
6954                if t >= t_min && t < closest_t {
6955                    closest_t = t;
6956                    closest_normal = e1.cross(e2).normalize();
6957                    hit_any = true;
6958                }
6959            }
6960        }
6961        if hit_any {
6962            Some((closest_t, closest_normal))
6963        } else {
6964            None
6965        }
6966    }
6967
6968    /// Casts a picking ray through normalized screen coordinates `(screen_u, screen_v)` in `[0.0, 1.0]` using AABB/meshlet broadphase and exact Möller–Trumbore triangle intersection.
6969    ///
6970    /// # Arguments
6971    ///
6972    /// - `f32` - Normalized horizontal screen coordinate in `[0.0, 1.0]` (left to right).
6973    /// - `f32` - Normalized vertical screen coordinate in `[0.0, 1.0]` (top to bottom).
6974    /// - `f32` - Viewport aspect ratio `width / height`.
6975    ///
6976    /// # Returns
6977    ///
6978    /// - `Option<ScenePickHit3D>` - Nearest visible object triangle hit or `None` when no object is intersected.
6979    #[must_use]
6980    pub fn pick_object_ray(
6981        &self,
6982        screen_u: f32,
6983        screen_v: f32,
6984        aspect: f32,
6985    ) -> Option<ScenePickHit3D> {
6986        let safe_aspect: f32 = if aspect.is_finite() && aspect > 0.05 {
6987            aspect
6988        } else {
6989            1.0
6990        };
6991        let ndc_x: f32 = screen_u.clamp(0.0, 1.0) * 2.0 - 1.0;
6992        let ndc_y: f32 = 1.0 - screen_v.clamp(0.0, 1.0) * 2.0;
6993        let (origin, ray_dir, t_min, mut best_t): (Vec3, Vec3, f32, f32) = if let Some(cam_idx) =
6994            self.active_scene_camera_index()
6995            && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
6996        {
6997            let fwd: Vec3 = scene_cam.forward();
6998            let right: Vec3 = scene_cam.right();
6999            let up: Vec3 = scene_cam.up();
7000            match scene_cam.get_projection() {
7001                GltfCameraProjection::Orthographic {
7002                    xmag,
7003                    ymag,
7004                    znear,
7005                    zfar,
7006                } => {
7007                    let o: Vec3 = scene_cam
7008                        .get_position()
7009                        .add(right.scale(ndc_x * xmag))
7010                        .add(up.scale(ndc_y * ymag));
7011                    (o, fwd, znear.max(0.01), zfar.max(znear + 1.0))
7012                }
7013                GltfCameraProjection::Perspective {
7014                    yfov_rad,
7015                    aspect_ratio,
7016                    znear,
7017                    zfar,
7018                } => {
7019                    let cam_aspect: f32 = aspect_ratio.unwrap_or(safe_aspect).max(0.05);
7020                    let half_tan_y: f32 = (yfov_rad.clamp(0.15, 2.6) * 0.5).tan();
7021                    let dir: Vec3 = fwd
7022                        .add(right.scale(ndc_x * half_tan_y * cam_aspect))
7023                        .add(up.scale(ndc_y * half_tan_y))
7024                        .normalize();
7025                    (
7026                        scene_cam.get_position(),
7027                        dir,
7028                        znear.max(0.01),
7029                        zfar.unwrap_or(480.0).max(znear + 1.0),
7030                    )
7031                }
7032            }
7033        } else {
7034            let cam: Camera3D = self.get_camera();
7035            let half_tan_y: f32 = (cam.get_fov_deg().clamp(12.0, 120.0).to_radians() * 0.5).tan();
7036            let half_tan_x: f32 = half_tan_y * safe_aspect;
7037            let forward: Vec3 = cam.forward();
7038            let right: Vec3 = cam.right();
7039            let up: Vec3 = right.cross(forward).normalize();
7040            let dir: Vec3 = forward
7041                .add(right.scale(ndc_x * half_tan_x))
7042                .add(up.scale(ndc_y * half_tan_y))
7043                .normalize();
7044            let near_v: f32 = cam.get_near().max(0.01);
7045            (
7046                cam.get_position(),
7047                dir,
7048                near_v,
7049                cam.get_far().max(near_v + 1.0),
7050            )
7051        };
7052        let inv_dir: Vec3 = Vec3::new(
7053            if ray_dir.get_x().abs() > 1e-6 {
7054                1.0 / ray_dir.get_x()
7055            } else {
7056                f32::INFINITY
7057            },
7058            if ray_dir.get_y().abs() > 1e-6 {
7059                1.0 / ray_dir.get_y()
7060            } else {
7061                f32::INFINITY
7062            },
7063            if ray_dir.get_z().abs() > 1e-6 {
7064                1.0 / ray_dir.get_z()
7065            } else {
7066                f32::INFINITY
7067            },
7068        );
7069        let Self {
7070            objects,
7071            mesh_library,
7072            deformed_meshes,
7073            ..
7074        } = self;
7075        let mut best_hit: Option<ScenePickHit3D> = None;
7076        for (obj_idx, obj) in objects.iter().enumerate() {
7077            if !self.is_object_visible(obj_idx) {
7078                continue;
7079            }
7080            let bounds: AxisAlignedBox3D = obj.get_world_bounds();
7081            let aabb_t: f32 = bounds.intersect_ray_near(origin, inv_dir, t_min, best_t);
7082            if aabb_t >= best_t {
7083                continue;
7084            }
7085            let mesh_ref: Option<&Mesh3D> = deformed_meshes
7086                .get(obj_idx)
7087                .and_then(|slot: &Option<Mesh3D>| slot.as_ref())
7088                .or_else(|| {
7089                    mesh_library
7090                        .get(obj.get_mesh_id())
7091                        .and_then(|chain: &MeshLodChain| chain.get_levels().first())
7092                });
7093            let Some(mesh) = mesh_ref else {
7094                best_t = aabb_t;
7095                let world_pos: Vec3 = origin.add(ray_dir.scale(aabb_t));
7096                best_hit = Some(ScenePickHit3D::new(
7097                    obj_idx,
7098                    obj.get_mesh_id(),
7099                    aabb_t,
7100                    world_pos,
7101                    ray_dir.scale(-1.0),
7102                ));
7103                continue;
7104            };
7105            if mesh.get_indices().is_empty() {
7106                best_t = aabb_t;
7107                let world_pos: Vec3 = origin.add(ray_dir.scale(aabb_t));
7108                best_hit = Some(ScenePickHit3D::new(
7109                    obj_idx,
7110                    obj.get_mesh_id(),
7111                    aabb_t,
7112                    world_pos,
7113                    ray_dir.scale(-1.0),
7114                ));
7115                continue;
7116            }
7117            let xform: Transform3D = obj.get_transform();
7118            let inv_elems: [f32; 16] = xform.to_inv_mat4().get_elements();
7119            let local_origin: Vec3 = Vec3::new(
7120                inv_elems[0] * origin.get_x()
7121                    + inv_elems[4] * origin.get_y()
7122                    + inv_elems[8] * origin.get_z()
7123                    + inv_elems[12],
7124                inv_elems[1] * origin.get_x()
7125                    + inv_elems[5] * origin.get_y()
7126                    + inv_elems[9] * origin.get_z()
7127                    + inv_elems[13],
7128                inv_elems[2] * origin.get_x()
7129                    + inv_elems[6] * origin.get_y()
7130                    + inv_elems[10] * origin.get_z()
7131                    + inv_elems[14],
7132            );
7133            let local_dir: Vec3 = Vec3::new(
7134                inv_elems[0] * ray_dir.get_x()
7135                    + inv_elems[4] * ray_dir.get_y()
7136                    + inv_elems[8] * ray_dir.get_z(),
7137                inv_elems[1] * ray_dir.get_x()
7138                    + inv_elems[5] * ray_dir.get_y()
7139                    + inv_elems[9] * ray_dir.get_z(),
7140                inv_elems[2] * ray_dir.get_x()
7141                    + inv_elems[6] * ray_dir.get_y()
7142                    + inv_elems[10] * ray_dir.get_z(),
7143            );
7144            let local_inv_dir: Vec3 = Vec3::new(
7145                if local_dir.get_x().abs() > 1e-6 {
7146                    1.0 / local_dir.get_x()
7147                } else {
7148                    f32::INFINITY
7149                },
7150                if local_dir.get_y().abs() > 1e-6 {
7151                    1.0 / local_dir.get_y()
7152                } else {
7153                    f32::INFINITY
7154                },
7155                if local_dir.get_z().abs() > 1e-6 {
7156                    1.0 / local_dir.get_z()
7157                } else {
7158                    f32::INFINITY
7159                },
7160            );
7161            if let Some((hit_t, local_n)) = Self::intersect_mesh_triangles_local(
7162                mesh,
7163                local_origin,
7164                local_dir,
7165                local_inv_dir,
7166                t_min,
7167                best_t,
7168            ) {
7169                best_t = hit_t;
7170                let nmat: [Vec3; 3] = xform.normal_mat3();
7171                let mut world_n: Vec3 = nmat[0]
7172                    .scale(local_n.get_x())
7173                    .add(nmat[1].scale(local_n.get_y()))
7174                    .add(nmat[2].scale(local_n.get_z()))
7175                    .normalize();
7176                if world_n.dot(ray_dir) > 0.0 {
7177                    world_n = world_n.scale(-1.0);
7178                }
7179                let world_pos: Vec3 = origin.add(ray_dir.scale(hit_t));
7180                best_hit = Some(ScenePickHit3D::new(
7181                    obj_idx,
7182                    obj.get_mesh_id(),
7183                    hit_t,
7184                    world_pos,
7185                    world_n,
7186                ));
7187            }
7188        }
7189        best_hit
7190    }
7191
7192    /// Advances active glTF/NLA animations by `dt_secs`, propagates dirty scene-graph transforms, synchronizes object/camera transforms, and evaluates Shape Keys + Armature Skinning with zero steady-state heap allocations.
7193    ///
7194    /// # Arguments
7195    ///
7196    /// - `&Self` - Mutable 3D world.
7197    /// - `f32` - Frame delta time in seconds.
7198    ///
7199    /// # Returns
7200    ///
7201    /// - `usize` - Count of updated scene nodes, morph channels, and deformed meshes.
7202    pub fn tick_animations(&mut self, dt_secs: f32) -> usize {
7203        let anim_updates: usize = {
7204            let Self {
7205                scene_graph,
7206                animation_mixer,
7207                ..
7208            } = self;
7209            animation_mixer.advance_and_apply(dt_secs, scene_graph)
7210        };
7211        let propagated: usize = self.get_mut_scene_graph().propagate_world_matrices();
7212        let synced: usize = self.sync_objects_from_scene_graph();
7213        let deformed: usize = self.update_deformed_meshes();
7214        let total: usize = anim_updates + propagated + synced + deformed;
7215        if total > 0 {
7216            self.set_dynamic_bvh_dirty(true);
7217            self.bump_world_revision();
7218        }
7219        total
7220    }
7221
7222    /// Evaluates Shape Keys (pre-skinning) and Armature Skinning (LBS or DQS) for all deformable objects into reusable `deformed_meshes` buffers with zero steady-state allocations.
7223    ///
7224    /// # Returns
7225    ///
7226    /// - `usize` - Number of objects whose deformed mesh was updated.
7227    pub fn update_deformed_meshes(&mut self) -> usize {
7228        let obj_count: usize = self.get_objects().len();
7229        let Self {
7230            mesh_library,
7231            objects,
7232            scene_graph,
7233            skins,
7234            skin_scratch,
7235            deformed_meshes,
7236            ..
7237        } = self;
7238        if deformed_meshes.len() < obj_count {
7239            deformed_meshes.resize(obj_count, None);
7240        }
7241        let mut updated_count: usize = 0;
7242        for obj_idx in 0..obj_count {
7243            let obj_ref: &SceneObject3D = &objects[obj_idx];
7244            let Some(node_id) = obj_ref.try_get_node_id() else {
7245                continue;
7246            };
7247            let morph_weights: &[f32] = scene_graph.morph_weights_for_node(node_id);
7248            let skin_opt: Option<u32> = obj_ref.try_get_skin_id();
7249            if skin_opt.is_none() && morph_weights.is_empty() {
7250                continue;
7251            }
7252            let Some(base_mesh) = mesh_library
7253                .get(obj_ref.get_mesh_id())
7254                .and_then(|chain: &MeshLodChain| chain.get_levels().first())
7255            else {
7256                continue;
7257            };
7258            let mesh_world: Mat4 = scene_graph.get_nodes().get(node_id as usize).map_or_else(
7259                || obj_ref.get_transform().to_mat4(),
7260                SceneNode3D::get_world_matrix,
7261            );
7262            let did_deform: bool = if let Some(skin_id) = skin_opt
7263                && let Some(skin_ref) = skins.get(skin_id as usize)
7264            {
7265                skin_ref.deform_mesh_into(
7266                    base_mesh,
7267                    morph_weights,
7268                    mesh_world,
7269                    scene_graph,
7270                    skin_scratch,
7271                )
7272            } else {
7273                let morphed: bool = apply_morph_targets_into(
7274                    base_mesh.get_vertices().as_slice(),
7275                    base_mesh.get_morph_targets().as_slice(),
7276                    morph_weights,
7277                    skin_scratch.get_mut_skinned_vertices(),
7278                );
7279                morphed
7280            };
7281            if did_deform {
7282                let deformed_verts: &[Vertex3D] = skin_scratch.get_skinned_vertices().as_slice();
7283                let mut local_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
7284                for vert_item in deformed_verts.iter() {
7285                    local_bounds.expand_point(vert_item.get_position());
7286                }
7287                let target_slot: &mut Option<Mesh3D> = &mut deformed_meshes[obj_idx];
7288                if let Some(existing_mesh) = target_slot.as_mut() {
7289                    let dst_verts: &mut Vec<Vertex3D> = existing_mesh.get_mut_vertices();
7290                    dst_verts.clear();
7291                    dst_verts.extend_from_slice(deformed_verts);
7292                    existing_mesh.set_bounds(local_bounds);
7293                } else {
7294                    let mut cloned_mesh: Mesh3D = base_mesh.clone();
7295                    let dst_verts: &mut Vec<Vertex3D> = cloned_mesh.get_mut_vertices();
7296                    dst_verts.clear();
7297                    dst_verts.extend_from_slice(deformed_verts);
7298                    cloned_mesh.set_bounds(local_bounds);
7299                    *target_slot = Some(cloned_mesh);
7300                }
7301                if let Some(deformed_ref) = target_slot.as_ref() {
7302                    let world_tr: Transform3D = objects[obj_idx].get_transform();
7303                    objects[obj_idx]
7304                        .set_world_bounds(world_tr.transform_bounds(deformed_ref.get_bounds()));
7305                }
7306                updated_count += 1;
7307            }
7308        }
7309        updated_count
7310    }
7311
7312    /// Applies an incremental Blender Live-Link delta in place without resetting camera state or rebuilding unrelated geometry.
7313    ///
7314    /// # Arguments
7315    ///
7316    /// - `&Self` - Mutable 3D world.
7317    /// - `&BlenderLiveDelta3D` - Structured Live-Link delta command.
7318    ///
7319    /// # Returns
7320    ///
7321    /// - `bool` - `true` when at least one scene entity was mutated.
7322    pub fn apply_live_delta(&mut self, delta: &BlenderLiveDelta3D) -> bool {
7323        match delta {
7324            BlenderLiveDelta3D::NodeTransform {
7325                node_name,
7326                translation,
7327                rotation,
7328                scale,
7329                blender_z_up,
7330            } => {
7331                let found_id: Option<u32> = self
7332                    .get_scene_graph()
7333                    .get_nodes()
7334                    .iter()
7335                    .position(|node_ref: &SceneNode3D| node_ref.get_name() == node_name)
7336                    .map(|idx: usize| idx as u32);
7337                let Some(node_id) = found_id else {
7338                    return false;
7339                };
7340                let raw_t: Vec3 = Vec3::from_array(*translation);
7341                let raw_r: Quat = Quat::from_array(*rotation).normalize();
7342                let raw_s: Vec3 = Vec3::from_array(*scale);
7343                let (dst_t, dst_r, dst_s): (Vec3, Quat, Vec3) = if *blender_z_up {
7344                    (
7345                        raw_t.blender_z_up_to_y_up(),
7346                        raw_r.blender_z_up_to_y_up(),
7347                        Vec3::new(raw_s.get_x(), raw_s.get_z(), raw_s.get_y()),
7348                    )
7349                } else {
7350                    (raw_t, raw_r, raw_s)
7351                };
7352                self.get_mut_scene_graph()
7353                    .set_local_trs(node_id, dst_t, dst_r, dst_s);
7354                let _: usize = self.get_mut_scene_graph().propagate_world_matrices();
7355                let _: usize = self.sync_objects_from_scene_graph();
7356                let _: usize = self.update_deformed_meshes();
7357                self.set_dynamic_bvh_dirty(true);
7358                self.bump_world_revision();
7359                true
7360            }
7361            BlenderLiveDelta3D::MaterialParams {
7362                material_name,
7363                base_color_factor,
7364                metallic_factor,
7365                roughness_factor,
7366                clearcoat_factor,
7367                clearcoat_roughness_factor,
7368                sheen_color_factor,
7369                sheen_roughness_factor,
7370                emissive_factor,
7371                emissive_strength,
7372                transmission_factor,
7373                ior,
7374            } => {
7375                let found_idx: Option<usize> = self
7376                    .get_principled_materials()
7377                    .iter()
7378                    .position(|mat_ref: &PrincipledMaterial3D| mat_ref.get_name() == material_name);
7379                let Some(mat_idx) = found_idx else {
7380                    return false;
7381                };
7382                let updated_legacy: PbrMaterial = {
7383                    let mat_mut: &mut PrincipledMaterial3D =
7384                        &mut self.get_mut_principled_materials()[mat_idx];
7385                    if let Some(val) = *base_color_factor {
7386                        mat_mut.set_base_color_factor(val);
7387                    }
7388                    if let Some(val) = *metallic_factor {
7389                        mat_mut.set_metallic_factor(val.clamp(0.0, 1.0));
7390                    }
7391                    if let Some(val) = *roughness_factor {
7392                        mat_mut.set_roughness_factor(val.clamp(0.04, 1.0));
7393                    }
7394                    if let Some(val) = *clearcoat_factor {
7395                        mat_mut.set_clearcoat_factor(val.clamp(0.0, 1.0));
7396                    }
7397                    if let Some(val) = *clearcoat_roughness_factor {
7398                        mat_mut.set_clearcoat_roughness_factor(val.clamp(0.0, 1.0));
7399                    }
7400                    if let Some(val) = *sheen_color_factor {
7401                        mat_mut.set_sheen_color_factor(val);
7402                    }
7403                    if let Some(val) = *sheen_roughness_factor {
7404                        mat_mut.set_sheen_roughness_factor(val.clamp(0.0, 1.0));
7405                    }
7406                    if let Some(val) = *emissive_factor {
7407                        mat_mut.set_emissive_factor(val);
7408                    }
7409                    if let Some(val) = *emissive_strength {
7410                        mat_mut.set_emissive_strength(val.max(0.0));
7411                    }
7412                    if let Some(val) = *transmission_factor {
7413                        mat_mut.set_transmission_factor(val.clamp(0.0, 1.0));
7414                    }
7415                    if let Some(val) = *ior {
7416                        mat_mut.set_ior(val.clamp(1.0, 3.0));
7417                    }
7418                    mat_mut.to_legacy_pbr()
7419                };
7420                let mat_u32: u32 = mat_idx as u32;
7421                for obj_mut in self.get_mut_objects().iter_mut() {
7422                    if obj_mut.try_get_principled_material_id() == Some(mat_u32) {
7423                        obj_mut.set_material(updated_legacy);
7424                    }
7425                }
7426                self.bump_world_revision();
7427                true
7428            }
7429            BlenderLiveDelta3D::MorphWeights { node_name, weights } => {
7430                let found_id: Option<u32> = self
7431                    .get_scene_graph()
7432                    .get_nodes()
7433                    .iter()
7434                    .position(|node_ref: &SceneNode3D| node_ref.get_name() == node_name)
7435                    .map(|idx: usize| idx as u32);
7436                let Some(node_id) = found_id else {
7437                    return false;
7438                };
7439                self.get_mut_scene_graph()
7440                    .update_morph_weights(node_id, weights.as_slice());
7441                let _: usize = self.update_deformed_meshes();
7442                self.set_dynamic_bvh_dirty(true);
7443                self.bump_world_revision();
7444                true
7445            }
7446            BlenderLiveDelta3D::LightUpdate {
7447                light_index,
7448                color,
7449                intensity,
7450                position,
7451                direction,
7452            } => {
7453                let mut changed: bool = false;
7454                if let Some(point_mut) = self.get_mut_point_lights().get_mut(*light_index) {
7455                    if let Some(col_arr) = *color {
7456                        point_mut.set_color(Vec3::from_array(col_arr));
7457                    }
7458                    if let Some(int_val) = *intensity {
7459                        point_mut.set_intensity(int_val.max(0.0));
7460                    }
7461                    if let Some(pos_arr) = *position {
7462                        point_mut.set_position(Vec3::from_array(pos_arr));
7463                    }
7464                    changed = true;
7465                } else if let Some(area_mut) = self.get_mut_area_lights().get_mut(*light_index) {
7466                    if let Some(col_arr) = *color {
7467                        area_mut.set_color(Vec3::from_array(col_arr));
7468                    }
7469                    if let Some(int_val) = *intensity {
7470                        area_mut.set_intensity(int_val.max(0.0));
7471                    }
7472                    if let Some(pos_arr) = *position {
7473                        area_mut.set_position(Vec3::from_array(pos_arr));
7474                    }
7475                    if let Some(dir_arr) = *direction {
7476                        area_mut.set_direction(Vec3::from_array(dir_arr).normalize());
7477                    }
7478                    changed = true;
7479                }
7480                if changed {
7481                    self.bump_world_revision();
7482                }
7483                changed
7484            }
7485            BlenderLiveDelta3D::CameraUpdate {
7486                position,
7487                yaw,
7488                pitch,
7489                fov_deg,
7490            } => {
7491                let mut cam: Camera3D = self.get_camera();
7492                cam.set_position(Vec3::from_array(*position));
7493                cam.set_yaw(*yaw);
7494                cam.set_pitch(pitch.clamp(-1.4, 1.4));
7495                cam.set_fov_deg(fov_deg.clamp(12.0, 120.0));
7496                self.set_camera(cam);
7497                self.bump_world_revision();
7498                true
7499            }
7500            BlenderLiveDelta3D::CollectionVisibility {
7501                collection_name,
7502                visible,
7503            } => self.set_collection_visible(collection_name, *visible),
7504            BlenderLiveDelta3D::EnvironmentUpdate {
7505                rotation_y_rad,
7506                intensity,
7507            } => {
7508                let Self {
7509                    environment_ibl, ..
7510                } = self;
7511                if let Some(ibl_mut) = environment_ibl.as_mut() {
7512                    ibl_mut.set_rotation_y_rad(*rotation_y_rad);
7513                    ibl_mut.set_intensity(intensity.max(0.0));
7514                    self.bump_world_revision();
7515                    true
7516                } else {
7517                    false
7518                }
7519            }
7520        }
7521    }
7522
7523    /// Parses a JSON Live-Link delta payload and applies it in place to this world.
7524    ///
7525    /// # Arguments
7526    ///
7527    /// - `&Self` - Mutable 3D world.
7528    /// - `&str` - JSON Live-Link delta string.
7529    ///
7530    /// # Returns
7531    ///
7532    /// - `Result<bool, String>` - `Ok(applied)` on valid payload, or parse error string.
7533    pub fn apply_live_delta_json(&mut self, json_payload: &str) -> Result<bool, String> {
7534        let root: Value =
7535            from_str::<Value>(json_payload).map_err(|_| ERR_LIVE_DELTA_UNKNOWN_KIND.to_string())?;
7536        let kind_str: &str = root
7537            .get(LIVE_KEY_KIND)
7538            .and_then(Value::as_str)
7539            .ok_or_else(|| ERR_LIVE_DELTA_UNKNOWN_KIND.to_string())?;
7540        let delta: BlenderLiveDelta3D = match kind_str {
7541            LIVE_DELTA_KIND_TRANSFORM => BlenderLiveDelta3D::NodeTransform {
7542                node_name: root
7543                    .get(LIVE_KEY_NODE_NAME)
7544                    .and_then(Value::as_str)
7545                    .unwrap_or_default()
7546                    .to_string(),
7547                translation: Self::json_f32_array3(root.get(LIVE_KEY_TRANSLATION))
7548                    .unwrap_or([0.0, 0.0, 0.0]),
7549                rotation: Self::json_f32_array4(root.get(LIVE_KEY_ROTATION))
7550                    .unwrap_or([0.0, 0.0, 0.0, 1.0]),
7551                scale: Self::json_f32_array3(root.get(LIVE_KEY_SCALE)).unwrap_or([1.0, 1.0, 1.0]),
7552                blender_z_up: root
7553                    .get(LIVE_KEY_BLENDER_Z_UP)
7554                    .and_then(Value::as_bool)
7555                    .unwrap_or(false),
7556            },
7557            LIVE_DELTA_KIND_MATERIAL => BlenderLiveDelta3D::MaterialParams {
7558                material_name: root
7559                    .get(LIVE_KEY_MATERIAL_NAME)
7560                    .and_then(Value::as_str)
7561                    .unwrap_or_default()
7562                    .to_string(),
7563                base_color_factor: Self::json_f32_array4(root.get(LIVE_KEY_BASE_COLOR)),
7564                metallic_factor: root
7565                    .get(LIVE_KEY_METALLIC)
7566                    .and_then(Value::as_f64)
7567                    .map(|val: f64| val as f32),
7568                roughness_factor: root
7569                    .get(LIVE_KEY_ROUGHNESS)
7570                    .and_then(Value::as_f64)
7571                    .map(|val: f64| val as f32),
7572                clearcoat_factor: root
7573                    .get(LIVE_KEY_CLEARCOAT)
7574                    .and_then(Value::as_f64)
7575                    .map(|val: f64| val as f32),
7576                clearcoat_roughness_factor: root
7577                    .get(LIVE_KEY_CLEARCOAT_ROUGHNESS)
7578                    .and_then(Value::as_f64)
7579                    .map(|val: f64| val as f32),
7580                sheen_color_factor: Self::json_f32_array3(root.get(LIVE_KEY_SHEEN_COLOR)),
7581                sheen_roughness_factor: root
7582                    .get(LIVE_KEY_SHEEN_ROUGHNESS)
7583                    .and_then(Value::as_f64)
7584                    .map(|val: f64| val as f32),
7585                emissive_factor: Self::json_f32_array3(root.get(LIVE_KEY_EMISSIVE)),
7586                emissive_strength: root
7587                    .get(LIVE_KEY_EMISSIVE_STRENGTH)
7588                    .and_then(Value::as_f64)
7589                    .map(|val: f64| val as f32),
7590                transmission_factor: root
7591                    .get(LIVE_KEY_TRANSMISSION)
7592                    .and_then(Value::as_f64)
7593                    .map(|val: f64| val as f32),
7594                ior: root
7595                    .get("ior")
7596                    .and_then(Value::as_f64)
7597                    .map(|val: f64| val as f32),
7598            },
7599            LIVE_DELTA_KIND_MORPH => {
7600                let parsed_weights: Vec<f32> = root
7601                    .get(LIVE_KEY_WEIGHTS)
7602                    .and_then(Value::as_array)
7603                    .map(|items: &Vec<Value>| {
7604                        items
7605                            .iter()
7606                            .filter_map(|elem: &Value| elem.as_f64().map(|val: f64| val as f32))
7607                            .collect()
7608                    })
7609                    .unwrap_or_default();
7610                BlenderLiveDelta3D::MorphWeights {
7611                    node_name: root
7612                        .get(LIVE_KEY_NODE_NAME)
7613                        .and_then(Value::as_str)
7614                        .unwrap_or_default()
7615                        .to_string(),
7616                    weights: parsed_weights,
7617                }
7618            }
7619            LIVE_DELTA_KIND_LIGHT => BlenderLiveDelta3D::LightUpdate {
7620                light_index: root
7621                    .get(LIVE_KEY_LIGHT_INDEX)
7622                    .and_then(Value::as_u64)
7623                    .unwrap_or(0) as usize,
7624                color: Self::json_f32_array3(root.get(LIVE_KEY_COLOR)),
7625                intensity: root
7626                    .get(LIVE_KEY_INTENSITY)
7627                    .and_then(Value::as_f64)
7628                    .map(|val: f64| val as f32),
7629                position: Self::json_f32_array3(root.get(LIVE_KEY_POSITION)),
7630                direction: Self::json_f32_array3(root.get(LIVE_KEY_DIRECTION)),
7631            },
7632            LIVE_DELTA_KIND_CAMERA => BlenderLiveDelta3D::CameraUpdate {
7633                position: Self::json_f32_array3(root.get(LIVE_KEY_POSITION))
7634                    .unwrap_or([0.0, 2.0, 6.0]),
7635                yaw: root
7636                    .get("yaw")
7637                    .and_then(Value::as_f64)
7638                    .map_or(0.0, |val: f64| val as f32),
7639                pitch: root
7640                    .get(LIVE_KEY_PITCH)
7641                    .and_then(Value::as_f64)
7642                    .map_or(0.0, |val: f64| val as f32),
7643                fov_deg: root
7644                    .get(LIVE_KEY_FOV_DEG)
7645                    .and_then(Value::as_f64)
7646                    .map_or(60.0, |val: f64| val as f32),
7647            },
7648            LIVE_DELTA_KIND_COLLECTION => BlenderLiveDelta3D::CollectionVisibility {
7649                collection_name: root
7650                    .get(LIVE_KEY_COLLECTION_NAME)
7651                    .and_then(Value::as_str)
7652                    .unwrap_or_default()
7653                    .to_string(),
7654                visible: root
7655                    .get(LIVE_KEY_VISIBLE)
7656                    .and_then(Value::as_bool)
7657                    .unwrap_or(true),
7658            },
7659            LIVE_DELTA_KIND_ENVIRONMENT => BlenderLiveDelta3D::EnvironmentUpdate {
7660                rotation_y_rad: root
7661                    .get(LIVE_KEY_ROTATION_Y_RAD)
7662                    .and_then(Value::as_f64)
7663                    .map_or(0.0, |val: f64| val as f32),
7664                intensity: root
7665                    .get(LIVE_KEY_INTENSITY)
7666                    .and_then(Value::as_f64)
7667                    .map_or(1.0, |val: f64| val as f32),
7668            },
7669            _ => return Err(ERR_LIVE_DELTA_UNKNOWN_KIND.to_string()),
7670        };
7671        Ok(self.apply_live_delta(&delta))
7672    }
7673
7674    /// Synchronizes linked `SceneObject3D` and `SceneCamera3D` transforms from `scene_graph` propagated world matrices.
7675    ///
7676    /// # Returns
7677    ///
7678    /// - `usize` - Number of linked objects or cameras whose transforms were synchronized.
7679    fn sync_objects_from_scene_graph(&mut self) -> usize {
7680        let Self {
7681            mesh_library,
7682            objects,
7683            scene_graph,
7684            scene_cameras,
7685            node_object_map,
7686            deformed_meshes,
7687            ..
7688        } = self;
7689        let nodes: &[SceneNode3D] = scene_graph.get_nodes().as_slice();
7690        let mut synced_count: usize = 0;
7691        for (node_idx, obj_slot) in node_object_map.iter().enumerate() {
7692            let Some(obj_idx) = *obj_slot else {
7693                continue;
7694            };
7695            if node_idx >= nodes.len() || obj_idx >= objects.len() {
7696                continue;
7697            }
7698            let world_tr: Transform3D =
7699                Transform3D::from_matrix(nodes[node_idx].get_world_matrix());
7700            if objects[obj_idx].get_transform() != world_tr {
7701                objects[obj_idx].set_transform(world_tr);
7702                let local_bounds: AxisAlignedBox3D = deformed_meshes
7703                    .get(obj_idx)
7704                    .and_then(Option::as_ref)
7705                    .map(Mesh3D::get_bounds)
7706                    .or_else(|| {
7707                        mesh_library
7708                            .get(objects[obj_idx].get_mesh_id())
7709                            .and_then(|chain: &MeshLodChain| chain.get_levels().first())
7710                            .map(Mesh3D::get_bounds)
7711                    })
7712                    .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
7713                objects[obj_idx].set_world_bounds(world_tr.transform_bounds(local_bounds));
7714                synced_count += 1;
7715            }
7716        }
7717        for cam_mut in scene_cameras.iter_mut() {
7718            if let Some(node_id) = cam_mut.try_get_node_id()
7719                && let Some(node_ref) = nodes.get(node_id as usize)
7720            {
7721                let (pos_val, rot_val, _scale_val): (Vec3, Quat, Vec3) =
7722                    node_ref.get_world_matrix().decompose_trs();
7723                cam_mut.set_position(pos_val);
7724                cam_mut.set_rotation(rot_val);
7725                synced_count += 1;
7726            }
7727        }
7728        synced_count
7729    }
7730
7731    /// Offsets all texture indices inside `material` by `texture_base` when merging an imported scene.
7732    ///
7733    /// # Arguments
7734    ///
7735    /// - `&mut PrincipledMaterial3D` - Mutable material whose texture slots are rebased.
7736    /// - `u32` - Texture pool offset.
7737    fn rebase_material_textures(material: &mut PrincipledMaterial3D, texture_base: u32) {
7738        if texture_base == 0 {
7739            return;
7740        }
7741        let shift_slot: fn(Option<TextureSlot3D>, u32) -> Option<TextureSlot3D> =
7742            |slot_opt: Option<TextureSlot3D>, base_val: u32| -> Option<TextureSlot3D> {
7743                slot_opt.map(|mut slot: TextureSlot3D| {
7744                    slot.set_texture_index(slot.get_texture_index().saturating_add(base_val));
7745                    slot
7746                })
7747            };
7748        material.set_base_color_texture(shift_slot(
7749            material.try_get_base_color_texture(),
7750            texture_base,
7751        ));
7752        material.set_metallic_roughness_texture(shift_slot(
7753            material.try_get_metallic_roughness_texture(),
7754            texture_base,
7755        ));
7756        material.set_normal_texture(shift_slot(material.try_get_normal_texture(), texture_base));
7757        material.set_occlusion_texture(shift_slot(
7758            material.try_get_occlusion_texture(),
7759            texture_base,
7760        ));
7761        material.set_emissive_texture(shift_slot(
7762            material.try_get_emissive_texture(),
7763            texture_base,
7764        ));
7765        material.set_specular_texture(shift_slot(
7766            material.try_get_specular_texture(),
7767            texture_base,
7768        ));
7769        material.set_specular_color_texture(shift_slot(
7770            material.try_get_specular_color_texture(),
7771            texture_base,
7772        ));
7773        material.set_clearcoat_texture(shift_slot(
7774            material.try_get_clearcoat_texture(),
7775            texture_base,
7776        ));
7777        material.set_clearcoat_roughness_texture(shift_slot(
7778            material.try_get_clearcoat_roughness_texture(),
7779            texture_base,
7780        ));
7781        material.set_clearcoat_normal_texture(shift_slot(
7782            material.try_get_clearcoat_normal_texture(),
7783            texture_base,
7784        ));
7785        material.set_transmission_texture(shift_slot(
7786            material.try_get_transmission_texture(),
7787            texture_base,
7788        ));
7789        material.set_sheen_color_texture(shift_slot(
7790            material.try_get_sheen_color_texture(),
7791            texture_base,
7792        ));
7793        material.set_sheen_roughness_texture(shift_slot(
7794            material.try_get_sheen_roughness_texture(),
7795            texture_base,
7796        ));
7797    }
7798
7799    /// Extracts a 3-element `f32` array from an optional JSON array value.
7800    ///
7801    /// # Arguments
7802    ///
7803    /// - `Option<&Value>` - Optional JSON node.
7804    ///
7805    /// # Returns
7806    ///
7807    /// - `Option<[f32; 3]>` - Decoded array when three numeric entries exist.
7808    #[must_use]
7809    fn json_f32_array3(val: Option<&Value>) -> Option<[f32; 3]> {
7810        let arr: &Vec<Value> = val?.as_array()?;
7811        if arr.len() < 3 {
7812            return None;
7813        }
7814        Some([
7815            arr[0].as_f64()? as f32,
7816            arr[1].as_f64()? as f32,
7817            arr[2].as_f64()? as f32,
7818        ])
7819    }
7820
7821    /// Extracts a 4-element `f32` array from an optional JSON array value.
7822    ///
7823    /// # Arguments
7824    ///
7825    /// - `Option<&Value>` - Optional JSON node.
7826    ///
7827    /// # Returns
7828    ///
7829    /// - `Option<[f32; 4]>` - Decoded array when four numeric entries exist.
7830    #[must_use]
7831    fn json_f32_array4(val: Option<&Value>) -> Option<[f32; 4]> {
7832        let arr: &Vec<Value> = val?.as_array()?;
7833        if arr.len() < 4 {
7834            return None;
7835        }
7836        Some([
7837            arr[0].as_f64()? as f32,
7838            arr[1].as_f64()? as f32,
7839            arr[2].as_f64()? as f32,
7840            arr[3].as_f64()? as f32,
7841        ])
7842    }
7843
7844    /// Allocates a globally unique non-zero revision tag for `GpuWorld3dMeshBuffer` VRAM caching across distinct `World3D` instances.
7845    ///
7846    /// # Returns
7847    ///
7848    /// - `u64` - Monotonically increasing non-zero mesh revision tag.
7849    #[must_use]
7850    pub fn allocate_gpu_mesh_revision() -> u64 {
7851        NEXT_GPU_WORLD3D_MESH_REVISION
7852            .fetch_add(1, Ordering::Relaxed)
7853            .max(1)
7854    }
7855
7856    /// Appends a smooth-shaded unit octahedron particle primitive (`8` triangles, `24` vertices) to `vertices`, returning its `(vertex_start, vertex_count)` range.
7857    ///
7858    /// # Arguments
7859    ///
7860    /// - `&mut Vec<GpuWorld3dVertex>` - Destination static GPU vertex buffer.
7861    ///
7862    /// # Returns
7863    ///
7864    /// - `(u32, u32)` - Starting vertex index and vertex count (`24`) for hardware-instanced Niagara particles.
7865    fn append_unit_particle_octahedron(vertices: &mut Vec<GpuWorld3dVertex>) -> (u32, u32) {
7866        let start_idx: u32 = vertices.len() as u32;
7867        let top: [f32; 3] = [0.0, 1.0, 0.0];
7868        let bot: [f32; 3] = [0.0, -1.0, 0.0];
7869        let pos_x: [f32; 3] = [1.0, 0.0, 0.0];
7870        let neg_x: [f32; 3] = [-1.0, 0.0, 0.0];
7871        let pos_z: [f32; 3] = [0.0, 0.0, 1.0];
7872        let neg_z: [f32; 3] = [0.0, 0.0, -1.0];
7873        let faces: [[[f32; 3]; 3]; 8] = [
7874            [top, pos_z, pos_x],
7875            [top, pos_x, neg_z],
7876            [top, neg_z, neg_x],
7877            [top, neg_x, pos_z],
7878            [bot, pos_x, pos_z],
7879            [bot, neg_z, pos_x],
7880            [bot, neg_x, neg_z],
7881            [bot, pos_z, neg_x],
7882        ];
7883        vertices.reserve(24);
7884        for tri in faces.iter() {
7885            for corner in tri.iter() {
7886                vertices.push(GpuWorld3dVertex::new(
7887                    [corner[0], corner[1], corner[2], 1.0],
7888                    [corner[0], corner[1], corner[2], 0.0],
7889                    [1.0, 1.0, 1.0, 0.0],
7890                ));
7891            }
7892        }
7893        let vert_count: u32 = (vertices.len() as u32).saturating_sub(start_idx);
7894        (start_idx, vert_count)
7895    }
7896
7897    /// Flattens every registered `LOD0` prototype mesh in `mesh_library` plus one shared unit Niagara particle primitive into one resident GPU vertex buffer and per-mesh `(vertex_start, vertex_count)` table.
7898    ///
7899    /// # Arguments
7900    ///
7901    /// - `&Self` - World reference.
7902    /// - `u64` - Monotonic revision tag attached to the built buffer for VRAM upload caching.
7903    ///
7904    /// # Returns
7905    ///
7906    /// - `(Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>)` - Shared static GPU vertex buffer and per-mesh range table (with the Niagara particle primitive appended at index `mesh_library.len()`).
7907    #[must_use]
7908    pub fn build_gpu_mesh_buffer(
7909        &self,
7910        revision: u64,
7911    ) -> (Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>) {
7912        let mut vertices: Vec<GpuWorld3dVertex> = Vec::new();
7913        let mut ranges: Vec<(u32, u32)> = Vec::with_capacity(self.get_mesh_library().len() + 1);
7914        for chain in self.get_mesh_library() {
7915            let start_idx: u32 = vertices.len() as u32;
7916            if let Some(mesh) = chain.get_levels().first() {
7917                let mesh_verts: &[Vertex3D] = mesh.get_vertices().as_slice();
7918                let tri_mats: &[u16] = mesh.get_tri_materials().as_slice();
7919                let sub_mats: &[PbrMaterial] = mesh.get_sub_materials().as_slice();
7920                vertices.reserve(mesh.get_indices().len() * 3);
7921                for (tri_idx, &[i0, i1, i2]) in mesh.get_indices().iter().enumerate() {
7922                    let (Some(v0), Some(v1), Some(v2)) = (
7923                        mesh_verts.get(i0 as usize),
7924                        mesh_verts.get(i1 as usize),
7925                        mesh_verts.get(i2 as usize),
7926                    ) else {
7927                        continue;
7928                    };
7929                    let mat_slot: usize = tri_mats.get(tri_idx).copied().unwrap_or(0) as usize;
7930                    let color_submat: [f32; 4] = if mat_slot > 0
7931                        && let Some(sub_mat) = sub_mats.get(mat_slot - 1)
7932                    {
7933                        let base_c: Vec3 = sub_mat.get_base_color();
7934                        let em_c: Vec3 = sub_mat.get_emissive();
7935                        if em_c.length_sq() > 0.01 {
7936                            [
7937                                base_c.get_x() + em_c.get_x() * 1.4,
7938                                base_c.get_y() + em_c.get_y() * 1.4,
7939                                base_c.get_z() + em_c.get_z() * 1.4,
7940                                2.0,
7941                            ]
7942                        } else {
7943                            [base_c.get_x(), base_c.get_y(), base_c.get_z(), 1.0]
7944                        }
7945                    } else {
7946                        [1.0, 1.0, 1.0, 0.0]
7947                    };
7948                    for vert in [v0, v1, v2] {
7949                        let pos: Vec3 = vert.get_position();
7950                        let nrm: Vec3 = vert.get_normal();
7951                        vertices.push(GpuWorld3dVertex::new(
7952                            [pos.get_x(), pos.get_y(), pos.get_z(), 1.0],
7953                            [nrm.get_x(), nrm.get_y(), nrm.get_z(), 0.0],
7954                            color_submat,
7955                        ));
7956                    }
7957                }
7958            }
7959            let vert_count: u32 = (vertices.len() as u32).saturating_sub(start_idx);
7960            ranges.push((start_idx, vert_count));
7961        }
7962        let particle_range: (u32, u32) = Self::append_unit_particle_octahedron(&mut vertices);
7963        ranges.push(particle_range);
7964        (
7965            Arc::new(GpuWorld3dMeshBuffer { revision, vertices }),
7966            ranges,
7967        )
7968    }
7969
7970    /// Populates `out` with a frustum-culled hardware GPU 3D scene pass using `scratch`, performing O(1) indexed dynamic pose lookups and zero `Vec<Vec<_>>` heap allocations.
7971    ///
7972    /// # Arguments
7973    ///
7974    /// - `&Self` - World reference.
7975    /// - `&DoubleBufferedSnapshot<World3DSnapshot>` - Double-buffered dynamic object and camera snapshots.
7976    /// - `f32` - Render interpolation alpha in `[0.0, 1.0]`.
7977    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
7978    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, and fog.
7979    /// - `(&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)])` - Cached static mesh buffer and per-mesh `(vertex_start, vertex_count)` ranges.
7980    /// - `(&mut World3dGpuPassScratch, &mut GpuWorld3dScenePass)` - Persistent flat scratch arena and destination scene pass reused across frames.
7981    fn populate_gpu_scene_pass_with_scratch(
7982        &self,
7983        snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
7984        alpha: f32,
7985        viewport: (u32, u32),
7986        quality: &RenderQualityConfig,
7987        mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
7988        buffers: (&mut World3dGpuPassScratch, &mut GpuWorld3dScenePass),
7989    ) {
7990        let (scratch, out): (&mut World3dGpuPassScratch, &mut GpuWorld3dScenePass) = buffers;
7991        let (target_width, target_height): (u32, u32) = viewport;
7992        let (mesh_buffer, mesh_ranges): (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]) = mesh_cache;
7993        let blend_alpha: f32 = alpha.clamp(0.0, 1.0);
7994        let prev_snap: &World3DSnapshot = snapshots.get_prev_state();
7995        let curr_snap: &World3DSnapshot = snapshots.get_curr_state();
7996        let mut interp_cam: Camera3D = if curr_snap.get_camera_cut() {
7997            curr_snap.get_camera()
7998        } else {
7999            prev_snap
8000                .get_camera()
8001                .lerp(curr_snap.get_camera(), blend_alpha)
8002        };
8003        let aspect: f32 = (target_width.max(1) as f32) / (target_height.max(1) as f32);
8004        if aspect > 3.5 {
8005            let pull_back: f32 = ((aspect - 3.5) * 0.42).min(1.6);
8006            let shifted_pos: Vec3 = interp_cam
8007                .get_position()
8008                .sub(interp_cam.forward().scale(pull_back));
8009            interp_cam.set_position(shifted_pos);
8010        }
8011        let view_proj_mat: Mat4 = if let Some(cam_idx) = self.active_scene_camera_index()
8012            && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
8013        {
8014            scene_cam.view_projection(aspect)
8015        } else {
8016            interp_cam.view_projection(aspect)
8017        };
8018        let frustum: Frustum3D = Frustum3D::from_view_proj(&view_proj_mat);
8019        let cam_pos: Vec3 = interp_cam.get_position();
8020        let draw_dist_sq: f32 = quality.get_draw_distance() * quality.get_draw_distance();
8021        let frustum_on: bool = quality.get_frustum_culling();
8022        let obj_len: usize = self.get_objects().len();
8023        if scratch.dynamic_pose_epochs.len() < obj_len {
8024            scratch.dynamic_pose_epochs.resize(obj_len, 0);
8025            scratch
8026                .dynamic_pose_transforms
8027                .resize(obj_len, Transform3D::default());
8028        }
8029        let next_epoch: u32 = scratch.current_epoch.wrapping_add(1);
8030        let active_epoch: u32 = if next_epoch == 0 {
8031            scratch.dynamic_pose_epochs.fill(0);
8032            1
8033        } else {
8034            next_epoch
8035        };
8036        scratch.current_epoch = active_epoch;
8037        let prev_objs: &[ObjectPose3D] = prev_snap.get_objects().as_slice();
8038        let next_objs: &[ObjectPose3D] = curr_snap.get_objects().as_slice();
8039        for (slot_idx, curr) in next_objs.iter().copied().enumerate() {
8040            let obj_idx: usize = curr.get_object_index();
8041            if obj_idx >= obj_len {
8042                continue;
8043            }
8044            let mut blended_tr: Transform3D = curr.get_transform();
8045            if curr.get_visible()
8046                && let Some(prev) = prev_objs.get(slot_idx).copied()
8047            {
8048                let continuous: bool = prev.get_visible()
8049                    && prev.get_object_index() == obj_idx
8050                    && prev.get_teleport_epoch() == curr.get_teleport_epoch();
8051                if continuous {
8052                    blended_tr = prev
8053                        .get_transform()
8054                        .lerp_shortest_angle(curr.get_transform(), blend_alpha);
8055                }
8056            }
8057            scratch.dynamic_pose_epochs[obj_idx] = active_epoch;
8058            scratch.dynamic_pose_transforms[obj_idx] = blended_tr;
8059        }
8060        let mesh_len: usize = mesh_ranges.len();
8061        if scratch.mesh_counts.len() < mesh_len {
8062            scratch.mesh_counts.resize(mesh_len, 0);
8063            scratch.mesh_cursors.resize(mesh_len, 0);
8064        }
8065        scratch.mesh_counts[..mesh_len].fill(0);
8066        scratch.visible_scratch.clear();
8067        let principled_mats: &[PrincipledMaterial3D] = self.get_principled_materials().as_slice();
8068        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
8069        for (obj_idx, obj) in self.get_objects().iter().enumerate() {
8070            if !self.is_object_visible(obj_idx) {
8071                continue;
8072            }
8073            let mesh_id: usize = obj.get_mesh_id();
8074            let Some(&(_, vert_count)) = mesh_ranges.get(mesh_id) else {
8075                continue;
8076            };
8077            if vert_count == 0 {
8078                continue;
8079            }
8080            let mut tr: Transform3D = obj.get_transform();
8081            let mut world_bounds: AxisAlignedBox3D = obj.get_world_bounds();
8082            if scratch.dynamic_pose_epochs[obj_idx] == active_epoch {
8083                tr = scratch.dynamic_pose_transforms[obj_idx];
8084                if let Some(chain) = mesh_lib.get(mesh_id)
8085                    && let Some(mesh0) = chain.get_levels().first()
8086                {
8087                    world_bounds = tr.transform_bounds(mesh0.get_bounds());
8088                }
8089            }
8090            let dist_sq: f32 = world_bounds.center().sub(cam_pos).length_sq();
8091            let radius: f32 = world_bounds.get_max().sub(world_bounds.get_min()).length() * 0.5;
8092            if dist_sq > draw_dist_sq + radius * radius * 4.0 {
8093                continue;
8094            }
8095            if frustum_on && !frustum.intersects_bounds(&world_bounds) {
8096                continue;
8097            }
8098            let mat: PbrMaterial = obj.get_material();
8099            let (albedo, metallic, roughness, emissive): (Vec3, f32, f32, Vec3) = if let Some(pm_id) =
8100                obj.try_get_principled_material_id()
8101                && let Some(pm) = principled_mats.get(pm_id as usize)
8102            {
8103                let bc: [f32; 4] = pm.get_base_color_factor();
8104                let em: [f32; 3] = pm.get_emissive_factor();
8105                let em_str: f32 = pm.get_emissive_strength();
8106                (
8107                    Vec3::new(bc[0], bc[1], bc[2]),
8108                    pm.get_metallic_factor(),
8109                    pm.get_roughness_factor(),
8110                    Vec3::new(em[0] * em_str, em[1] * em_str, em[2] * em_str),
8111                )
8112            } else {
8113                (
8114                    mat.get_base_color(),
8115                    mat.get_metallic(),
8116                    mat.get_roughness(),
8117                    mat.get_emissive(),
8118                )
8119            };
8120            let mut model_elems: [f32; 16] = tr.to_mat4().get_elements();
8121            model_elems[15] = match mat.get_surface_detail() {
8122                SurfaceDetailMode::None => 0.0,
8123                SurfaceDetailMode::RoadSurface => 1.0,
8124                SurfaceDetailMode::ArchitecturalFacade => 2.0,
8125                SurfaceDetailMode::OceanWater => 3.0,
8126            };
8127            scratch.mesh_counts[mesh_id] = scratch.mesh_counts[mesh_id].saturating_add(1);
8128            scratch.visible_scratch.push((
8129                mesh_id as u32,
8130                GpuWorld3dInstance::new(
8131                    model_elems,
8132                    [
8133                        albedo.get_x(),
8134                        albedo.get_y(),
8135                        albedo.get_z(),
8136                        metallic.clamp(0.0, 1.0),
8137                    ],
8138                    [
8139                        emissive.get_x(),
8140                        emissive.get_y(),
8141                        emissive.get_z(),
8142                        roughness.clamp(0.05, 1.0),
8143                    ],
8144                ),
8145            ));
8146        }
8147        let total_instances: usize = scratch.visible_scratch.len();
8148        out.draw_batches.clear();
8149        let mut cursor: u32 = 0;
8150        for (mesh_id, &(vertex_start, vertex_count)) in mesh_ranges.iter().enumerate() {
8151            let count: u32 = scratch.mesh_counts[mesh_id];
8152            scratch.mesh_cursors[mesh_id] = cursor;
8153            if count == 0 {
8154                continue;
8155            }
8156            out.draw_batches.push(GpuWorld3dMeshRange::new(
8157                vertex_start,
8158                vertex_count,
8159                cursor,
8160                count,
8161            ));
8162            cursor = cursor.saturating_add(count);
8163        }
8164        out.instances
8165            .resize(total_instances, GpuWorld3dInstance::default());
8166        for &(mesh_id_u32, inst) in scratch.visible_scratch.iter() {
8167            let mesh_id: usize = mesh_id_u32 as usize;
8168            let dst_idx: usize = scratch.mesh_cursors[mesh_id] as usize;
8169            scratch.mesh_cursors[mesh_id] = scratch.mesh_cursors[mesh_id].saturating_add(1);
8170            out.instances[dst_idx] = inst;
8171        }
8172        let particle_mesh_idx: usize = mesh_lib.len();
8173        if self.get_niagara().get_active_count() > 0
8174            && let Some(&(particle_vert_start, particle_vert_count)) =
8175                mesh_ranges.get(particle_mesh_idx)
8176            && particle_vert_count > 0
8177        {
8178            let particle_inst_start: u32 = out.instances.len() as u32;
8179            let active_frustum: Option<&Frustum3D> = if frustum_on { Some(&frustum) } else { None };
8180            let particle_inst_count: u32 = self.get_niagara().append_gpu_world3d_instances(
8181                cam_pos,
8182                draw_dist_sq,
8183                active_frustum,
8184                &mut out.instances,
8185            );
8186            if particle_inst_count > 0 {
8187                out.draw_batches.push(GpuWorld3dMeshRange::new(
8188                    particle_vert_start,
8189                    particle_vert_count,
8190                    particle_inst_start,
8191                    particle_inst_count,
8192                ));
8193            }
8194        }
8195        let sun: DirectionalLight3D = self.get_sun();
8196        let sun_dir: Vec3 = sun.get_direction().normalize();
8197        let sun_col: Vec3 = sun.get_color();
8198        let sky_hor: Vec3 = sun.get_sky_horizon();
8199        let sky_zen: Vec3 = sun.get_sky_zenith();
8200        let fog_density: f32 = if quality.get_volumetric_fog() {
8201            0.0028
8202        } else {
8203            0.0008
8204        };
8205        out.target_width = target_width;
8206        out.target_height = target_height;
8207        out.view_proj = view_proj_mat.get_elements();
8208        out.camera_pos = [cam_pos.get_x(), cam_pos.get_y(), cam_pos.get_z(), 1.15];
8209        out.sun_dir_fog = [
8210            sun_dir.get_x(),
8211            sun_dir.get_y(),
8212            sun_dir.get_z(),
8213            fog_density,
8214        ];
8215        out.sun_color_ambient = [sun_col.get_x(), sun_col.get_y(), sun_col.get_z(), 0.34];
8216        let anim_time: f32 =
8217            (sun.get_time_of_day() + self.get_world_time_secs()).rem_euclid(3600.0);
8218        out.sky_horizon_tod = [sky_hor.get_x(), sky_hor.get_y(), sky_hor.get_z(), anim_time];
8219        out.sky_zenith_aspect = [sky_zen.get_x(), sky_zen.get_y(), sky_zen.get_z(), aspect];
8220        out.mesh_buffer = Arc::clone(mesh_buffer);
8221    }
8222
8223    /// Populates a recycled `GpuWorld3dScenePass` in-place using `World3D`'s persistent flat scratch arena with zero per-frame heap allocations.
8224    ///
8225    /// # Arguments
8226    ///
8227    /// - `&Self` - Mutable world reference.
8228    /// - `&DoubleBufferedSnapshot<World3DSnapshot>` - Double-buffered dynamic object and camera snapshots.
8229    /// - `f32` - Render interpolation alpha in `[0.0, 1.0]`.
8230    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
8231    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, and fog.
8232    /// - `(&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)])` - Cached static mesh buffer and per-mesh `(vertex_start, vertex_count)` ranges.
8233    /// - `&mut GpuWorld3dScenePass` - Recycled scene pass destination populated in-place.
8234    pub fn build_gpu_scene_pass_into(
8235        &mut self,
8236        snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
8237        alpha: f32,
8238        viewport: (u32, u32),
8239        quality: &RenderQualityConfig,
8240        mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
8241        out: &mut GpuWorld3dScenePass,
8242    ) {
8243        let mut scratch: World3dGpuPassScratch = {
8244            let Self {
8245                gpu_pass_scratch, ..
8246            } = self;
8247            take(gpu_pass_scratch)
8248        };
8249        self.populate_gpu_scene_pass_with_scratch(
8250            snapshots,
8251            alpha,
8252            viewport,
8253            quality,
8254            mesh_cache,
8255            (&mut scratch, out),
8256        );
8257        let Self {
8258            gpu_pass_scratch, ..
8259        } = self;
8260        *gpu_pass_scratch = scratch;
8261    }
8262
8263    /// Rebuilds the cached quantized 24-byte `GpuPbrMeshBuffer` and per-LOD index ranges only when `mesh_library` geometry changes.
8264    ///
8265    /// # Arguments
8266    ///
8267    /// - `&[MeshLodChain]` - Active scene mesh library.
8268    /// - `&mut World3dPbrPassScratch` - Persistent PBR scratch cache storing the quantized `Arc<GpuPbrMeshBuffer>`.
8269    fn sync_pbr_quantized_mesh_cache(
8270        mesh_library: &[MeshLodChain],
8271        scratch: &mut World3dPbrPassScratch,
8272    ) {
8273        let mut total_verts: usize = 0;
8274        let mut total_indices: usize = 0;
8275        let mut any_skinned: bool = false;
8276        let mut any_morphed: bool = false;
8277        for chain in mesh_library.iter() {
8278            for mesh in chain.get_levels().iter().take(4) {
8279                total_verts = total_verts.saturating_add(mesh.get_vertices().len());
8280                total_indices =
8281                    total_indices.saturating_add(mesh.get_indices().len().saturating_mul(3));
8282                if !mesh.get_skin_influences().is_empty() {
8283                    any_skinned = true;
8284                }
8285                if !mesh.get_morph_targets().is_empty() {
8286                    any_morphed = true;
8287                }
8288            }
8289        }
8290        let signature: (usize, usize, usize) = (mesh_library.len(), total_verts, total_indices);
8291        if scratch.cached_signature == signature && scratch.cached_mesh_buffer.get_revision() > 0 {
8292            return;
8293        }
8294        let next_rev: u64 = NEXT_GPU_PBR_MESH_REVISION
8295            .fetch_add(1, Ordering::Relaxed)
8296            .max(1);
8297        let mut vertices: Vec<QuantizedVertex3D> = Vec::with_capacity(total_verts);
8298        let mut indices: Vec<u32> = Vec::with_capacity(total_indices);
8299        let mut skin_vertices: Vec<QuantizedSkinVertex3D> = if any_skinned {
8300            Vec::with_capacity(total_verts)
8301        } else {
8302            Vec::new()
8303        };
8304        let mut uv1_f16: Vec<[u16; 2]> = Vec::with_capacity(total_verts);
8305        let mut mesh_bounds_min: Vec<[f32; 4]> = Vec::with_capacity(mesh_library.len());
8306        let mut mesh_bounds_extent: Vec<[f32; 4]> = Vec::with_capacity(mesh_library.len());
8307        let mut morph_deltas: Vec<[f32; 4]> = if any_morphed && total_verts > 0 {
8308            vec![[0.0; 4]; total_verts.saturating_mul(4)]
8309        } else {
8310            Vec::new()
8311        };
8312        scratch.cached_lod_ranges.clear();
8313        scratch.cached_lod_ranges.reserve(mesh_library.len());
8314        let mut vert_tags: Vec<u8> = Vec::new();
8315        for chain in mesh_library.iter() {
8316            let levels: &[Mesh3D] = chain.get_levels().as_slice();
8317            let mut lod_ranges: [CachedPbrLodRange; 4] = [CachedPbrLodRange::default(); 4];
8318            let mut base_min: [f32; 4] = [0.0; 4];
8319            let mut base_ext: [f32; 4] = [1.0, 1.0, 1.0, 0.0];
8320            for (lod_idx, mesh) in levels.iter().take(4).enumerate() {
8321                let m_verts: &[Vertex3D] = mesh.get_vertices().as_slice();
8322                let m_tris: &[[u32; 3]] = mesh.get_indices().as_slice();
8323                let mb: AxisAlignedBox3D = mesh.get_bounds();
8324                let bmin: Vec3 = mb.get_min();
8325                let bext_raw: Vec3 = mb.get_max().sub(bmin);
8326                let bext: Vec3 = Vec3::new(
8327                    bext_raw.get_x().max(1e-4),
8328                    bext_raw.get_y().max(1e-4),
8329                    bext_raw.get_z().max(1e-4),
8330                );
8331                let min_arr: [f32; 4] = [bmin.get_x(), bmin.get_y(), bmin.get_z(), 0.0];
8332                let ext_arr: [f32; 4] = [bext.get_x(), bext.get_y(), bext.get_z(), 0.0];
8333                if lod_idx == 0 {
8334                    base_min = min_arr;
8335                    base_ext = ext_arr;
8336                }
8337                vert_tags.clear();
8338                vert_tags.resize(m_verts.len(), 0);
8339                for (cluster_idx, meshlet) in mesh.get_meshlets().iter().enumerate() {
8340                    let tag: u8 = ((cluster_idx % 255) + 1) as u8;
8341                    let t_start: usize = meshlet.get_first_tri() as usize;
8342                    let t_end: usize = t_start
8343                        .saturating_add(meshlet.get_tri_count() as usize)
8344                        .min(m_tris.len());
8345                    for tri in &m_tris[t_start..t_end] {
8346                        for &vi in tri.iter() {
8347                            if let Some(slot) = vert_tags.get_mut(vi as usize) {
8348                                *slot = tag;
8349                            }
8350                        }
8351                    }
8352                }
8353                let base_vertex: u32 = vertices.len() as u32;
8354                let index_start: u32 = indices.len() as u32;
8355                let skins: &[MeshSkinInfluence3D] = mesh.get_skin_influences().as_slice();
8356                for (vi, vert) in m_verts.iter().enumerate() {
8357                    let tag: u8 = vert_tags.get(vi).copied().unwrap_or(0);
8358                    vertices.push(quantize_vertex_3d(vert, bmin, bext, tag));
8359                    let uv1: [f32; 2] = vert.get_uv1();
8360                    uv1_f16.push([encode_f32_to_f16(uv1[0]), encode_f32_to_f16(uv1[1])]);
8361                    if any_skinned {
8362                        let qskin: QuantizedSkinVertex3D = skins
8363                            .get(vi)
8364                            .map_or_else(QuantizedSkinVertex3D::default, quantize_skin_vertex_3d);
8365                        skin_vertices.push(qskin);
8366                    }
8367                }
8368                let has_morphs: bool = !mesh.get_morph_targets().is_empty();
8369                if any_morphed && has_morphs && total_verts > 0 {
8370                    for (t_idx, target) in mesh.get_morph_targets().iter().take(4).enumerate() {
8371                        let dpos: &[[f32; 3]] = target.get_delta_positions().as_slice();
8372                        let target_base: usize = t_idx
8373                            .saturating_mul(total_verts)
8374                            .saturating_add(base_vertex as usize);
8375                        for (vi, delta) in dpos.iter().take(m_verts.len()).enumerate() {
8376                            if let Some(dst) = morph_deltas.get_mut(target_base + vi) {
8377                                *dst = [delta[0], delta[1], delta[2], 0.0];
8378                            }
8379                        }
8380                    }
8381                }
8382                for tri in m_tris.iter() {
8383                    indices.push(base_vertex.saturating_add(tri[0]));
8384                    indices.push(base_vertex.saturating_add(tri[1]));
8385                    indices.push(base_vertex.saturating_add(tri[2]));
8386                }
8387                let index_count: u32 = (indices.len() as u32).saturating_sub(index_start);
8388                lod_ranges[lod_idx] = CachedPbrLodRange {
8389                    index_start,
8390                    index_count,
8391                    bounds_min: min_arr,
8392                    bounds_extent: ext_arr,
8393                    has_morphs,
8394                };
8395            }
8396            let avail: usize = levels.len().min(4);
8397            if avail > 0 && avail < 4 {
8398                let fallback_lod: CachedPbrLodRange = lod_ranges[avail - 1];
8399                for fill_slot in lod_ranges.iter_mut().skip(avail) {
8400                    *fill_slot = fallback_lod;
8401                }
8402            }
8403            mesh_bounds_min.push(base_min);
8404            mesh_bounds_extent.push(base_ext);
8405            scratch.cached_lod_ranges.push(lod_ranges);
8406        }
8407        scratch.cached_signature = signature;
8408        scratch.cached_mesh_buffer = Arc::new(GpuPbrMeshBuffer {
8409            revision: next_rev,
8410            vertices,
8411            indices,
8412            skin_vertices,
8413            morph_deltas,
8414            uv1_f16,
8415            mesh_bounds_min,
8416            mesh_bounds_extent,
8417        });
8418    }
8419
8420    /// Converts a legacy `PbrMaterial` into a std140 `GpuMaterialData3D` and deduplicates against `materials[fallback_base..]` to maximize instancing coalescing.
8421    ///
8422    /// # Arguments
8423    ///
8424    /// - `PbrMaterial` - Legacy per-object PBR material.
8425    /// - `usize` - Starting index of deduplicated fallback materials inside `materials`.
8426    /// - `&mut Vec<GpuMaterialData3D>` - Destination frame material table.
8427    ///
8428    /// # Returns
8429    ///
8430    /// - `u32` - Resolved material table slot index.
8431    fn resolve_fallback_gpu_material(
8432        mat: PbrMaterial,
8433        fallback_base: usize,
8434        materials: &mut Vec<GpuMaterialData3D>,
8435    ) -> u32 {
8436        let albedo: Vec3 = mat.get_base_color();
8437        let emissive: Vec3 = mat.get_emissive();
8438        let candidate: GpuMaterialData3D = GpuMaterialData3D {
8439            base_color_factor: [albedo.get_x(), albedo.get_y(), albedo.get_z(), 1.0],
8440            emissive_alpha_cutoff: [emissive.get_x(), emissive.get_y(), emissive.get_z(), 0.5],
8441            pbr_ior_specular: [
8442                mat.get_metallic().clamp(0.0, 1.0),
8443                mat.get_roughness().clamp(0.04, 1.0),
8444                PRINCIPLED_DEFAULT_IOR,
8445                1.0,
8446            ],
8447            specular_color_clearcoat: [1.0, 1.0, 1.0, 0.0],
8448            clearcoat_normal_occ_trans: [0.1, 1.0, 1.0, 0.0],
8449            volume_attenuation: [1.0, 1.0, 1.0, 0.0],
8450            sheen_color_roughness: [0.0, 0.0, 0.0, 0.5],
8451            tex_indices_a: [GPU_MATERIAL_NO_TEXTURE; 4],
8452            tex_indices_b: [GPU_MATERIAL_NO_TEXTURE; 4],
8453            flags_volume: [
8454                0,
8455                f32::INFINITY.to_bits(),
8456                GPU_MATERIAL_NO_TEXTURE,
8457                GPU_MATERIAL_NO_TEXTURE,
8458            ],
8459        };
8460        if let Some(rel_idx) = materials[fallback_base..]
8461            .iter()
8462            .position(|existing: &GpuMaterialData3D| *existing == candidate)
8463        {
8464            return (fallback_base + rel_idx) as u32;
8465        }
8466        let slot: u32 = materials.len() as u32;
8467        materials.push(candidate);
8468        slot
8469    }
8470
8471    /// Populates a recycled `GpuPbrScenePass` using borrowed `pbr_pass_scratch` and `skin_scratch` arenas with zero steady-state heap allocations.
8472    ///
8473    /// # Arguments
8474    ///
8475    /// - `&Self` - World reference.
8476    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
8477    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, LOD bias, and fog.
8478    /// - `&mut GpuUploadBelt` - Frame-budgeted GPU staging belt enforcing `<= 4 MiB` and `<= 1.5 ms` ceilings.
8479    /// - `&mut World3dPbrPassScratch` - Persistent PBR geometry cache and batcher scratch arena.
8480    /// - `&mut SkinPaletteScratch3D` - Reusable bone matrix evaluation workspace.
8481    /// - `&mut GpuPbrScenePass` - Destination hardware PBR scene pass overwritten in-place.
8482    fn populate_gpu_pbr_scene_pass_with_scratch(
8483        &self,
8484        viewport: (u32, u32),
8485        quality: &RenderQualityConfig,
8486        belt: &mut GpuUploadBelt,
8487        scratch: &mut World3dPbrPassScratch,
8488        skin_scratch: &mut SkinPaletteScratch3D,
8489        out: &mut GpuPbrScenePass,
8490    ) {
8491        belt.begin_frame();
8492        let prev_vp: [f32; 16] = out.get_view_proj();
8493        out.clear_frame_payloads();
8494        let (target_width, target_height): (u32, u32) = viewport;
8495        let aspect: f32 = (target_width.max(1) as f32) / (target_height.max(1) as f32);
8496        let (view_proj_mat, cam_pos, cam_fov_deg, cam_far): (Mat4, Vec3, f32, f32) =
8497            if let Some(cam_idx) = self.active_scene_camera_index()
8498                && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
8499            {
8500                let proj_cam: Camera3D = scene_cam.to_camera3d();
8501                (
8502                    scene_cam.view_projection(aspect),
8503                    scene_cam.get_position(),
8504                    proj_cam.get_fov_deg(),
8505                    proj_cam.get_far(),
8506                )
8507            } else {
8508                let cam: Camera3D = self.get_camera();
8509                (
8510                    cam.view_projection(aspect),
8511                    cam.get_position(),
8512                    cam.get_fov_deg(),
8513                    cam.get_far(),
8514                )
8515            };
8516        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
8517        Self::sync_pbr_quantized_mesh_cache(mesh_lib, scratch);
8518        let src_mats: &[PrincipledMaterial3D] = self.get_principled_materials().as_slice();
8519        let dst_mats: &mut Vec<GpuMaterialData3D> = out.get_mut_materials();
8520        if dst_mats.capacity() < src_mats.len() {
8521            dst_mats.reserve(src_mats.len() - dst_mats.len());
8522        }
8523        for mat_ref in src_mats.iter() {
8524            dst_mats.push(mat_ref.to_gpu_data());
8525        }
8526        let fallback_mat_base: usize = dst_mats.len();
8527        let dst_lights: &mut Vec<GpuPackedLocalLight> = out.get_mut_local_lights();
8528        for pl in self.get_point_lights().iter() {
8529            if dst_lights.len() >= PBR_MAX_LOCAL_LIGHTS {
8530                break;
8531            }
8532            let p: Vec3 = pl.get_position();
8533            let c: Vec3 = pl.get_color();
8534            dst_lights.push(GpuPackedLocalLight::new(
8535                [p.get_x(), p.get_y(), p.get_z(), pl.get_radius().max(0.1)],
8536                [c.get_x(), c.get_y(), c.get_z(), pl.get_intensity().max(0.0)],
8537                [0.0, -1.0, 0.0, 0.0],
8538                [-1.0, -1.0, 0.0, 0.0],
8539            ));
8540        }
8541        for sl in self.get_spot_lights().iter() {
8542            if dst_lights.len() >= PBR_MAX_LOCAL_LIGHTS {
8543                break;
8544            }
8545            let p: Vec3 = sl.get_position();
8546            let c: Vec3 = sl.get_color();
8547            let d: Vec3 = sl.get_direction().normalize();
8548            dst_lights.push(GpuPackedLocalLight::new(
8549                [p.get_x(), p.get_y(), p.get_z(), sl.get_range().max(0.1)],
8550                [c.get_x(), c.get_y(), c.get_z(), sl.get_intensity().max(0.0)],
8551                [d.get_x(), d.get_y(), d.get_z(), 1.0],
8552                [sl.get_inner_cos(), sl.get_outer_cos(), 0.0, 0.0],
8553            ));
8554        }
8555        for al in self.get_area_lights().iter() {
8556            if dst_lights.len() >= PBR_MAX_LOCAL_LIGHTS {
8557                break;
8558            }
8559            let p: Vec3 = al.get_position();
8560            let c: Vec3 = al.get_color();
8561            let d: Vec3 = al.get_direction().normalize();
8562            dst_lights.push(GpuPackedLocalLight::new(
8563                [p.get_x(), p.get_y(), p.get_z(), al.get_range().max(0.1)],
8564                [c.get_x(), c.get_y(), c.get_z(), al.get_intensity().max(0.0)],
8565                [d.get_x(), d.get_y(), d.get_z(), 2.0],
8566                [0.0, -1.0, al.get_width(), al.get_height()],
8567            ));
8568        }
8569        let sun: DirectionalLight3D = self.get_sun();
8570        let sun_dir: Vec3 = sun.get_direction().normalize();
8571        let sun_col: Vec3 = sun.get_color();
8572        let sky_hor: Vec3 = sun.get_sky_horizon();
8573        let sky_zen: Vec3 = sun.get_sky_zenith();
8574        let ibl_sh: [[f32; 4]; 9] = if let Some(env) = self.environment_ibl() {
8575            let raw: [[f32; 3]; 9] = env.get_sh_irradiance();
8576            let mut packed: [[f32; 4]; 9] = [[0.0; 4]; 9];
8577            for (dst, src) in packed.iter_mut().zip(raw.iter()) {
8578                *dst = [src[0], src[1], src[2], 0.0];
8579            }
8580            packed
8581        } else {
8582            let mut packed: [[f32; 4]; 9] = [[0.0; 4]; 9];
8583            let avg_r: f32 = (sky_hor.get_x() + sky_zen.get_x()) * 0.5;
8584            let avg_g: f32 = (sky_hor.get_y() + sky_zen.get_y()) * 0.5;
8585            let avg_b: f32 = (sky_hor.get_z() + sky_zen.get_z()) * 0.5;
8586            packed[0] = [avg_r * 1.35, avg_g * 1.35, avg_b * 1.35, 0.0];
8587            packed[1] = [
8588                (sky_zen.get_x() - sky_hor.get_x()) * 0.35,
8589                (sky_zen.get_y() - sky_hor.get_y()) * 0.35,
8590                (sky_zen.get_z() - sky_hor.get_z()) * 0.35,
8591                0.0,
8592            ];
8593            packed
8594        };
8595        let frustum: Frustum3D = Frustum3D::from_view_proj(&view_proj_mat);
8596        let frustum_planes: [[f32; 4]; 6] = frustum.get_planes();
8597        let half_h: f32 = (cam_fov_deg.clamp(12.0, 120.0).to_radians() * 0.5)
8598            .tan()
8599            .max(0.05);
8600        let focal_px: f32 = (target_height.max(1) as f32) * 0.5 / half_h;
8601        let draw_dist: f32 = quality.get_draw_distance().max(1.0);
8602        let draw_dist_sq: f32 = draw_dist * draw_dist;
8603        let frustum_on: bool = quality.get_frustum_culling();
8604        let chunk_on: bool = quality.get_chunk_streaming();
8605        let lod_bias: f32 = quality.get_lod_bias();
8606        let inv_far: f32 = 1.0 / cam_far.max(draw_dist).max(1.0);
8607        let objects: &[SceneObject3D] = self.get_objects().as_slice();
8608        let scene_graph: &SceneGraph3D = self.get_scene_graph();
8609        let skins: &[Skin3D] = self.get_skins().as_slice();
8610        let total_objs: usize = objects.len();
8611        scratch.batcher.get_mut_entries().clear();
8612        if scratch.batcher.get_entries().capacity() < total_objs {
8613            let need: usize = total_objs - scratch.batcher.get_entries().len();
8614            scratch.batcher.get_mut_entries().reserve(need);
8615        }
8616        let mut meshlets_tested: u32 = 0;
8617        let mut meshlets_culled: u32 = 0;
8618        let mut lod_counts: [u32; 4] = [0; 4];
8619        let mut base_idx: usize = 0;
8620        while base_idx < total_objs {
8621            let chunk: usize = (total_objs - base_idx).min(4);
8622            let mut min_x: [f32; 4] = [0.0; 4];
8623            let mut min_y: [f32; 4] = [0.0; 4];
8624            let mut min_z: [f32; 4] = [0.0; 4];
8625            let mut max_x: [f32; 4] = [0.0; 4];
8626            let mut max_y: [f32; 4] = [0.0; 4];
8627            let mut max_z: [f32; 4] = [0.0; 4];
8628            let mut vis_flags: u8 = 0;
8629            for lane in 0..chunk {
8630                let obj_idx: usize = base_idx + lane;
8631                if !self.is_object_visible(obj_idx) {
8632                    continue;
8633                }
8634                let wb: AxisAlignedBox3D = objects[obj_idx].get_world_bounds();
8635                let dist_sq: f32 = wb.center().sub(cam_pos).length_sq();
8636                if chunk_on && dist_sq > draw_dist_sq {
8637                    continue;
8638                }
8639                let bmin: Vec3 = wb.get_min();
8640                let bmax: Vec3 = wb.get_max();
8641                min_x[lane] = bmin.get_x();
8642                min_y[lane] = bmin.get_y();
8643                min_z[lane] = bmin.get_z();
8644                max_x[lane] = bmax.get_x();
8645                max_y[lane] = bmax.get_y();
8646                max_z[lane] = bmax.get_z();
8647                vis_flags |= 1u8 << lane;
8648            }
8649            let frustum_mask: u8 = if frustum_on && vis_flags != 0 {
8650                let aabb4: SimdAabbBatch4 =
8651                    SimdAabbBatch4::new(min_x, min_y, min_z, max_x, max_y, max_z);
8652                cull_aabb_batch4_simd(&frustum_planes, &aabb4)
8653            } else {
8654                0x0F
8655            };
8656            let active_mask: u8 = vis_flags & frustum_mask;
8657            for lane in 0..chunk {
8658                let obj_idx: usize = base_idx + lane;
8659                let obj: &SceneObject3D = &objects[obj_idx];
8660                let mesh_id: usize = obj.get_mesh_id();
8661                let Some(chain) = mesh_lib.get(mesh_id) else {
8662                    continue;
8663                };
8664                if ((active_mask >> lane) & 1) == 0 {
8665                    if self.is_object_visible(obj_idx)
8666                        && let Some(base_mesh) = chain.get_levels().first()
8667                    {
8668                        let mcount: u32 = base_mesh.get_meshlets().len().max(1) as u32;
8669                        meshlets_tested = meshlets_tested.saturating_add(mcount);
8670                        meshlets_culled = meshlets_culled.saturating_add(mcount);
8671                    }
8672                    continue;
8673                }
8674                let wb: AxisAlignedBox3D = obj.get_world_bounds();
8675                let dist: f32 = wb.center().sub(cam_pos).length();
8676                let (selected_mesh, raw_lod): (&Mesh3D, usize) =
8677                    chain.select_screen_error(dist, wb.radius(), focal_px, lod_bias);
8678                let lod_idx: usize = raw_lod.min(3);
8679                let Some(lod_arr) = scratch.cached_lod_ranges.get(mesh_id) else {
8680                    continue;
8681                };
8682                let lod_range: CachedPbrLodRange = lod_arr[lod_idx];
8683                if lod_range.index_count == 0 {
8684                    continue;
8685                }
8686                let model_mat: Mat4 = obj.get_transform().to_mat4();
8687                let (m_tested, m_culled): (u32, u32) = if !selected_mesh.get_meshlets().is_empty() {
8688                    cull_meshlets_simd(
8689                        selected_mesh.get_meshlets().as_slice(),
8690                        &model_mat,
8691                        &frustum,
8692                        cam_pos,
8693                        selected_mesh.get_is_closed(),
8694                    )
8695                } else {
8696                    (1, 0)
8697                };
8698                meshlets_tested = meshlets_tested.saturating_add(m_tested);
8699                meshlets_culled = meshlets_culled.saturating_add(m_culled);
8700                if selected_mesh.get_is_closed() && m_tested > 0 && m_culled >= m_tested {
8701                    continue;
8702                }
8703                lod_counts[lod_idx] = lod_counts[lod_idx].saturating_add(1);
8704                let mat_slot: u32 = if let Some(pid) = obj.try_get_principled_material_id()
8705                    && (pid as usize) < fallback_mat_base
8706                {
8707                    pid
8708                } else {
8709                    Self::resolve_fallback_gpu_material(
8710                        obj.get_material(),
8711                        fallback_mat_base,
8712                        out.get_mut_materials(),
8713                    )
8714                };
8715                let mat_flags: u32 = out
8716                    .get_materials()
8717                    .get(mat_slot as usize)
8718                    .map_or(0, |m: &GpuMaterialData3D| m.get_flags_volume()[0]);
8719                let is_alpha_blend: bool = (mat_flags & GPU_MATERIAL_FLAG_ALPHA_BLEND) != 0;
8720                let mut inst_flags: u32 = 0;
8721                let mut bone_off: u32 = 0;
8722                let mut pso_variant: u8 = PBR_PSO_VARIANT_OPAQUE;
8723                if let Some(skin_id) = obj.try_get_skin_id()
8724                    && let Some(skin_ref) = skins.get(skin_id as usize)
8725                {
8726                    bone_off = out.get_bone_matrices().len() as u32;
8727                    skin_ref.compute_skin_matrices_into(model_mat, scene_graph, skin_scratch);
8728                    let palette: &[Mat4] = skin_scratch.get_skin_matrices().as_slice();
8729                    let dst_bones: &mut Vec<[f32; 16]> = out.get_mut_bone_matrices();
8730                    if dst_bones.capacity() < dst_bones.len() + palette.len() {
8731                        dst_bones.reserve(palette.len());
8732                    }
8733                    for bm in palette.iter() {
8734                        dst_bones.push(bm.get_elements());
8735                    }
8736                    inst_flags |= PBR_INST_FLAG_SKINNED;
8737                    if skin_ref.get_skinning_mode() == SkinningMode::DualQuaternion {
8738                        inst_flags |= PBR_INST_FLAG_DQS;
8739                    }
8740                    pso_variant = PBR_PSO_VARIANT_SKINNED;
8741                }
8742                let mut morph_off: u32 = 0;
8743                if lod_range.has_morphs
8744                    && let Some(node_id) = obj.try_get_node_id()
8745                {
8746                    let mweights: &[f32] = scene_graph.morph_weights_for_node(node_id);
8747                    if !mweights.is_empty() {
8748                        morph_off = out.get_morph_weights().len() as u32;
8749                        let dst_mw: &mut Vec<f32> = out.get_mut_morph_weights();
8750                        for k in 0..4 {
8751                            dst_mw.push(mweights.get(k).copied().unwrap_or(0.0));
8752                        }
8753                        inst_flags |= PBR_INST_FLAG_MORPHED;
8754                    }
8755                }
8756                let alpha_pass: u8 = if is_alpha_blend {
8757                    pso_variant = PBR_PSO_VARIANT_ALPHA_BLEND;
8758                    inst_flags |= PBR_INST_FLAG_ALPHA_BLEND;
8759                    1
8760                } else {
8761                    0
8762                };
8763                let depth_q16: u16 = ((dist * inv_far).clamp(0.0, 1.0) * 65_535.0).round() as u16;
8764                let sort_key: u64 = pack_pbr_sort_key(
8765                    alpha_pass,
8766                    pso_variant,
8767                    mat_slot,
8768                    mesh_id as u32,
8769                    lod_idx as u8,
8770                    depth_q16,
8771                );
8772                let mut q_origin: [f32; 4] = lod_range.bounds_min;
8773                q_origin[3] = f32::from_bits(obj_idx as u32);
8774                let mut q_extent: [f32; 4] = lod_range.bounds_extent;
8775                q_extent[3] = lod_idx as f32;
8776                let instance: GpuPbrInstance3D = GpuPbrInstance3D::new(
8777                    model_mat.get_elements(),
8778                    q_origin,
8779                    q_extent,
8780                    [mat_slot, bone_off, morph_off, inst_flags],
8781                );
8782                scratch.batcher.get_mut_entries().push(PbrSortEntry3D {
8783                    sort_key,
8784                    index_start: lod_range.index_start,
8785                    index_count: lod_range.index_count,
8786                    base_vertex: 0,
8787                    material_index: mat_slot,
8788                    pso_variant,
8789                    lod_level: lod_idx as u8,
8790                    instance,
8791                });
8792            }
8793            base_idx += 4;
8794        }
8795        let draw_call_count: u32 = {
8796            let GpuPbrScenePass {
8797                instances,
8798                draw_batches,
8799                ..
8800            } = out;
8801            coalesce_pbr_batches_into(&mut scratch.batcher, instances, draw_batches)
8802        };
8803        let textures: &[Texture2D3D] = self.get_textures().as_slice();
8804        if scratch.uploaded_texture_min_mip.len() < textures.len() {
8805            scratch
8806                .uploaded_texture_min_mip
8807                .resize(textures.len(), u8::MAX);
8808        }
8809        for (slot_idx, tex) in textures.iter().enumerate() {
8810            let mips: &[TextureMipLevel3D] = tex.get_mips().as_slice();
8811            if mips.is_empty() {
8812                continue;
8813            }
8814            let current_min: u8 = scratch.uploaded_texture_min_mip[slot_idx];
8815            if current_min == 0 {
8816                continue;
8817            }
8818            let total_mips: u8 = mips.len().min(16) as u8;
8819            let (target_mip, priority): (u8, StreamPriority) = if current_min == u8::MAX {
8820                (total_mips.saturating_sub(1), StreamPriority::Critical)
8821            } else {
8822                let next_mip: u8 = current_min.saturating_sub(1);
8823                let prio: StreamPriority = if next_mip > 0 {
8824                    StreamPriority::VisibleHigh
8825                } else {
8826                    StreamPriority::PrefetchMedium
8827                };
8828                (next_mip, prio)
8829            };
8830            if let Some(mip_data) = mips.get(target_mip as usize) {
8831                let upload: GpuTextureMipUpload = GpuTextureMipUpload {
8832                    texture_slot: slot_idx as u32,
8833                    mip_level: target_mip,
8834                    total_mip_levels: total_mips,
8835                    is_srgb: tex.get_color_space() == TextureColorSpace::Srgb,
8836                    min_lod_clamp: target_mip,
8837                    width: mip_data.get_width(),
8838                    height: mip_data.get_height(),
8839                    rgba8: mip_data.get_pixels().clone(),
8840                };
8841                let _: GpuUploadTicket = belt.enqueue_mip_upload(priority, upload);
8842            }
8843        }
8844        let _: usize = belt.drain_mip_uploads_into(out.get_mut_texture_uploads());
8845        for uploaded in out.get_texture_uploads().iter() {
8846            let slot_idx: usize = uploaded.get_texture_slot() as usize;
8847            if let Some(watermark) = scratch.uploaded_texture_min_mip.get_mut(slot_idx) {
8848                *watermark = (*watermark).min(uploaded.get_mip_level());
8849            }
8850        }
8851        let fog_density: f32 = if quality.get_volumetric_fog() {
8852            0.0028
8853        } else {
8854            0.0008
8855        };
8856        let agx_flag: f32 = if self.get_use_agx_tonemap() { 1.0 } else { 0.0 };
8857        out.set_target_width(target_width);
8858        out.set_target_height(target_height);
8859        out.set_prev_view_proj(prev_vp);
8860        out.set_view_proj(view_proj_mat.get_elements());
8861        out.set_camera_pos_exposure([cam_pos.get_x(), cam_pos.get_y(), cam_pos.get_z(), 1.15]);
8862        out.set_sun_dir_fog([
8863            sun_dir.get_x(),
8864            sun_dir.get_y(),
8865            sun_dir.get_z(),
8866            fog_density,
8867        ]);
8868        out.set_sun_color_ambient([sun_col.get_x(), sun_col.get_y(), sun_col.get_z(), 0.34]);
8869        out.set_sky_horizon_tod([
8870            sky_hor.get_x(),
8871            sky_hor.get_y(),
8872            sky_hor.get_z(),
8873            sun.get_time_of_day(),
8874        ]);
8875        out.set_sky_zenith_agx([sky_zen.get_x(), sky_zen.get_y(), sky_zen.get_z(), agx_flag]);
8876        out.set_ibl_sh(ibl_sh);
8877        out.set_mesh_buffer(Arc::clone(&scratch.cached_mesh_buffer));
8878        let stats: GpuPbrCullStats = GpuPbrCullStats::new(
8879            meshlets_tested,
8880            meshlets_culled,
8881            lod_counts,
8882            draw_call_count,
8883            belt.get_frame_bytes_used(),
8884            belt.get_frame_time_us_used(),
8885        );
8886        out.set_stats(stats);
8887    }
8888
8889    /// Populates a recycled `GpuPbrScenePass` in-place with quantized 24-byte PBR geometry, SIMD frustum and meshlet normal-cone culling, 64-bit instanced sorting, LBS/DQS skinning, morph weights, local lights, SH9 IBL, and budget-capped incremental mip uploads with zero steady-state heap allocations.
8890    ///
8891    /// # Arguments
8892    ///
8893    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
8894    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, LOD bias, and fog.
8895    /// - `&mut GpuUploadBelt` - Frame-budgeted GPU staging belt enforcing `<= 4 MiB` and `<= 1.5 ms` ceilings.
8896    /// - `&mut GpuPbrScenePass` - Recycled PBR scene pass destination populated in-place.
8897    pub fn build_gpu_pbr_scene_pass_into(
8898        &mut self,
8899        viewport: (u32, u32),
8900        quality: &RenderQualityConfig,
8901        belt: &mut GpuUploadBelt,
8902        out: &mut GpuPbrScenePass,
8903    ) {
8904        let (mut pbr_work, mut skin_work): (World3dPbrPassScratch, SkinPaletteScratch3D) = {
8905            let Self {
8906                pbr_pass_scratch,
8907                skin_scratch,
8908                ..
8909            } = self;
8910            (take(pbr_pass_scratch), take(skin_scratch))
8911        };
8912        self.populate_gpu_pbr_scene_pass_with_scratch(
8913            viewport,
8914            quality,
8915            belt,
8916            &mut pbr_work,
8917            &mut skin_work,
8918            out,
8919        );
8920        let Self {
8921            pbr_pass_scratch,
8922            skin_scratch,
8923            ..
8924        } = self;
8925        *pbr_pass_scratch = pbr_work;
8926        *skin_scratch = skin_work;
8927    }
8928
8929    /// Builds a hardware GPU 3D scene pass by frustum-culling visible objects and grouping instanced transforms by `mesh_id` with zero `Vec<Vec<_>>` allocations and O(1) dynamic pose lookup.
8930    ///
8931    /// # Arguments
8932    ///
8933    /// - `&Self` - World reference.
8934    /// - `&DoubleBufferedSnapshot<World3DSnapshot>` - Double-buffered dynamic object and camera snapshots.
8935    /// - `f32` - Render interpolation alpha in `[0.0, 1.0]`.
8936    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
8937    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, and fog.
8938    /// - `(&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)])` - Cached static mesh buffer and per-mesh `(vertex_start, vertex_count)` ranges.
8939    ///
8940    /// # Returns
8941    ///
8942    /// - `GpuWorld3dScenePass` - Hardware instanced 3D scene pass descriptor ready for Metal, GLES3, D3D11, or WebGL2.
8943    #[must_use]
8944    pub fn build_gpu_scene_pass(
8945        &self,
8946        snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
8947        alpha: f32,
8948        viewport: (u32, u32),
8949        quality: &RenderQualityConfig,
8950        mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
8951    ) -> GpuWorld3dScenePass {
8952        let mut out: GpuWorld3dScenePass = GpuWorld3dScenePass::default();
8953        let used_tls: bool = WORLD3D_GPU_PASS_SCRATCH
8954            .try_with(|cell: &RefCell<World3dGpuPassScratch>| -> bool {
8955                if let Ok(mut scratch) = cell.try_borrow_mut() {
8956                    self.populate_gpu_scene_pass_with_scratch(
8957                        snapshots,
8958                        alpha,
8959                        viewport,
8960                        quality,
8961                        mesh_cache,
8962                        (&mut scratch, &mut out),
8963                    );
8964                    true
8965                } else {
8966                    false
8967                }
8968            })
8969            .unwrap_or(false);
8970        if !used_tls {
8971            let mut local_scratch: World3dGpuPassScratch = World3dGpuPassScratch::default();
8972            self.populate_gpu_scene_pass_with_scratch(
8973                snapshots,
8974                alpha,
8975                viewport,
8976                quality,
8977                mesh_cache,
8978                (&mut local_scratch, &mut out),
8979            );
8980        }
8981        out
8982    }
8983}
8984
8985/// Perspective and Orthographic projection matrix builders for `SceneCamera3D`.
8986impl SceneCamera3D {
8987    /// Builds a `SceneCamera3D` from an imported glTF/Blender `ImportedCamera3D` and node world pose.
8988    ///
8989    /// # Arguments
8990    ///
8991    /// - `&ImportedCamera3D` - Imported camera parameters.
8992    /// - `Option<u32>` - Optional owning scene-graph node index.
8993    /// - `Vec3` - World-space camera eye position.
8994    /// - `Quat` - World-space camera orientation quaternion.
8995    ///
8996    /// # Returns
8997    ///
8998    /// - `Self` - Constructed multi-camera entry.
8999    #[must_use]
9000    pub fn from_imported(
9001        imported: &ImportedCamera3D,
9002        node_id: Option<u32>,
9003        position: Vec3,
9004        rotation: Quat,
9005    ) -> Self {
9006        Self {
9007            name: imported.get_name().clone(),
9008            node_id,
9009            position,
9010            rotation: rotation.normalize(),
9011            projection: imported.get_projection(),
9012        }
9013    }
9014
9015    /// Returns the unit world-space forward direction along glTF local `-Z`.
9016    ///
9017    /// # Returns
9018    ///
9019    /// - `Vec3` - Unit forward vector.
9020    #[must_use]
9021    pub fn forward(&self) -> Vec3 {
9022        self.get_rotation()
9023            .rotate_vec3(Vec3::new(0.0, 0.0, -1.0))
9024            .normalize()
9025    }
9026
9027    /// Returns the unit world-space right direction along glTF local `+X`.
9028    ///
9029    /// # Returns
9030    ///
9031    /// - `Vec3` - Unit right vector.
9032    #[must_use]
9033    pub fn right(&self) -> Vec3 {
9034        self.get_rotation()
9035            .rotate_vec3(Vec3::new(1.0, 0.0, 0.0))
9036            .normalize()
9037    }
9038
9039    /// Returns the unit world-space up direction along glTF local `+Y`.
9040    ///
9041    /// # Returns
9042    ///
9043    /// - `Vec3` - Unit up vector.
9044    #[must_use]
9045    pub fn up(&self) -> Vec3 {
9046        self.get_rotation()
9047            .rotate_vec3(Vec3::new(0.0, 1.0, 0.0))
9048            .normalize()
9049    }
9050
9051    /// Returns `true` when this camera uses orthographic projection.
9052    ///
9053    /// # Returns
9054    ///
9055    /// - `bool` - Whether projection is orthographic.
9056    #[must_use]
9057    pub fn is_orthographic(&self) -> bool {
9058        matches!(
9059            self.get_projection(),
9060            GltfCameraProjection::Orthographic { .. }
9061        )
9062    }
9063
9064    /// Computes the combined `projection * view` matrix supporting both Perspective and Orthographic projections.
9065    ///
9066    /// # Arguments
9067    ///
9068    /// - `&Self` - Scene camera reference.
9069    /// - `f32` - Active viewport aspect ratio `width / height`.
9070    ///
9071    /// # Returns
9072    ///
9073    /// - `Mat4` - Combined view-projection matrix.
9074    #[must_use]
9075    pub fn view_projection(&self, viewport_aspect: f32) -> Mat4 {
9076        let pos: Vec3 = self.get_position();
9077        let view: Mat4 = Mat4::look_at(pos, pos.add(self.forward()), self.up());
9078        let proj: Mat4 = match self.get_projection() {
9079            GltfCameraProjection::Perspective {
9080                yfov_rad,
9081                aspect_ratio,
9082                znear,
9083                zfar,
9084            } => Mat4::perspective(
9085                yfov_rad.clamp(0.15, 2.6),
9086                aspect_ratio.unwrap_or(viewport_aspect).max(0.1),
9087                znear.max(0.02),
9088                zfar.unwrap_or(480.0).max(znear + 1.0),
9089            ),
9090            GltfCameraProjection::Orthographic {
9091                xmag,
9092                ymag,
9093                znear,
9094                zfar,
9095            } => Mat4::orthographic_mag(xmag, ymag, znear.max(0.01), zfar.max(znear + 1.0)),
9096        };
9097        proj.mul(view)
9098    }
9099
9100    /// Projects this scene camera to a compatible `Camera3D` for primary viewport synchronization.
9101    ///
9102    /// # Returns
9103    ///
9104    /// - `Camera3D` - Equivalent perspective viewport camera descriptor.
9105    #[must_use]
9106    pub fn to_camera3d(&self) -> Camera3D {
9107        let fwd: Vec3 = self.forward();
9108        let yaw_val: f32 = fwd.get_z().atan2(fwd.get_x());
9109        let pitch_val: f32 = fwd.get_y().clamp(-0.98, 0.98).asin();
9110        let (fov_deg, near_val, far_val): (f32, f32, f32) = match self.get_projection() {
9111            GltfCameraProjection::Perspective {
9112                yfov_rad,
9113                znear,
9114                zfar,
9115                ..
9116            } => (
9117                yfov_rad.to_degrees().clamp(12.0, 120.0),
9118                znear.max(0.05),
9119                zfar.unwrap_or(480.0).max(10.0),
9120            ),
9121            GltfCameraProjection::Orthographic { znear, zfar, .. } => {
9122                (45.0, znear.max(0.05), zfar.max(10.0))
9123            }
9124        };
9125        let mut cam: Camera3D = Camera3D::default();
9126        cam.set_position(self.get_position());
9127        cam.set_yaw(yaw_val);
9128        cam.set_pitch(pitch_val);
9129        cam.set_fov_deg(fov_deg);
9130        cam.set_near(near_val);
9131        cam.set_far(far_val);
9132        cam
9133    }
9134}