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
663/// Conversion helpers for `CameraMode3D`.
664impl CameraMode3D {
665    /// Converts a numeric mode index (`0..=5`) into a typed `CameraMode3D`.
666    ///
667    /// # Arguments
668    ///
669    /// - `u8` - Numeric camera mode index.
670    ///
671    /// # Returns
672    ///
673    /// - `Self` - Corresponding `CameraMode3D`.
674    #[must_use]
675    pub const fn from_u8(index: u8) -> Self {
676        match index {
677            1 => Self::Hood,
678            2 => Self::Orbit,
679            3 => Self::Aerial,
680            4 => Self::FreeFly,
681            5 => Self::CinematicDolly,
682            _ => Self::Chase,
683        }
684    }
685
686    /// Converts this `CameraMode3D` into its stable numeric index (`0..=5`).
687    ///
688    /// # Arguments
689    ///
690    /// - `Self` - Camera mode variant.
691    ///
692    /// # Returns
693    ///
694    /// - `u8` - Numeric mode index.
695    #[must_use]
696    pub const fn as_u8(self) -> u8 {
697        match self {
698            Self::Chase => 0,
699            Self::Hood => 1,
700            Self::Orbit => 2,
701            Self::Aerial => 3,
702            Self::FreeFly => 4,
703            Self::CinematicDolly => 5,
704        }
705    }
706}
707
708/// Fluent builder helpers for `SpawnObjectDesc`.
709impl SpawnObjectDesc {
710    /// Creates an object spawn descriptor with identity transform, default PBR material, and BVH ray tracing enabled.
711    ///
712    /// # Arguments
713    ///
714    /// - `&str` - Human-readable object label.
715    /// - `usize` - Registered mesh identifier.
716    ///
717    /// # Returns
718    ///
719    /// - `Self` - Ready spawn descriptor.
720    #[must_use]
721    pub fn new(name: &str, mesh_id: usize) -> Self {
722        Self {
723            name: name.to_string(),
724            mesh_id,
725            transform: Transform3D::default(),
726            material: PbrMaterial::default(),
727            ray_trace_caster: true,
728            solid_collider: true,
729            spin_speed: 0.0,
730            is_dynamic: false,
731        }
732    }
733
734    /// Sets the world-space transform for the spawned object.
735    ///
736    /// # Arguments
737    ///
738    /// - `Self` - Base descriptor.
739    /// - `Transform3D` - World-space transform.
740    ///
741    /// # Returns
742    ///
743    /// - `Self` - Updated descriptor.
744    #[must_use]
745    pub fn with_transform(mut self, transform: Transform3D) -> Self {
746        self.set_transform(transform);
747        self
748    }
749
750    /// Sets the PBR surface material override for the spawned object.
751    ///
752    /// # Arguments
753    ///
754    /// - `Self` - Base descriptor.
755    /// - `PbrMaterial` - PBR material.
756    ///
757    /// # Returns
758    ///
759    /// - `Self` - Updated descriptor.
760    #[must_use]
761    pub fn with_material(mut self, material: PbrMaterial) -> Self {
762        self.set_material(material);
763        self
764    }
765
766    /// Sets whether this object casts BVH shadows and appears in reflections.
767    ///
768    /// # Arguments
769    ///
770    /// - `Self` - Base descriptor.
771    /// - `bool` - Ray-trace caster toggle.
772    ///
773    /// # Returns
774    ///
775    /// - `Self` - Updated descriptor.
776    #[must_use]
777    pub fn with_ray_trace(mut self, ray_trace_caster: bool) -> Self {
778        self.set_ray_trace_caster(ray_trace_caster);
779        self
780    }
781
782    /// Sets whether this object participates in solid vehicle and camera collision detection.
783    ///
784    /// # Arguments
785    ///
786    /// - `Self` - Base descriptor.
787    /// - `bool` - Solid collider toggle.
788    ///
789    /// # Returns
790    ///
791    /// - `Self` - Updated descriptor.
792    #[must_use]
793    pub fn with_solid_collider(mut self, solid_collider: bool) -> Self {
794        self.set_solid_collider(solid_collider);
795        self
796    }
797
798    /// Sets continuous Y-axis spin speed in radians per second.
799    ///
800    /// # Arguments
801    ///
802    /// - `Self` - Base descriptor.
803    /// - `f32` - Spin speed in radians/sec.
804    ///
805    /// # Returns
806    ///
807    /// - `Self` - Updated descriptor.
808    #[must_use]
809    pub fn with_spin(mut self, spin_speed: f32) -> Self {
810        self.set_spin_speed(spin_speed);
811        if spin_speed.abs() > 0.001 {
812            self.set_is_dynamic(true);
813        }
814        self
815    }
816
817    /// Explicitly marks whether this object belongs in the incrementally refitted dynamic BVH.
818    ///
819    /// # Arguments
820    ///
821    /// - `Self` - Base descriptor.
822    /// - `bool` - Dynamic caster flag.
823    ///
824    /// # Returns
825    ///
826    /// - `Self` - Updated descriptor.
827    #[must_use]
828    pub fn with_dynamic(mut self, is_dynamic: bool) -> Self {
829        self.set_is_dynamic(is_dynamic);
830        self
831    }
832}
833
834/// Fluent builder helpers for `ImportModelDesc`.
835impl ImportModelDesc {
836    /// Creates an external model import descriptor with identity transform and default PBR fallback material.
837    ///
838    /// # Arguments
839    ///
840    /// - `ModelFormat` - Interchange format (`Obj` or `GltfJson`).
841    /// - `&str` - Raw model source text.
842    ///
843    /// # Returns
844    ///
845    /// - `Self` - Ready import descriptor.
846    #[must_use]
847    pub fn new(format: ModelFormat, source: &str) -> Self {
848        Self {
849            format,
850            source: source.to_string(),
851            transform: Transform3D::default(),
852            fallback_material: PbrMaterial::default(),
853            spin_speed: 0.0,
854        }
855    }
856
857    /// Sets the placement transform for the imported model.
858    ///
859    /// # Arguments
860    ///
861    /// - `Self` - Base descriptor.
862    /// - `Transform3D` - Placement transform.
863    ///
864    /// # Returns
865    ///
866    /// - `Self` - Updated descriptor.
867    #[must_use]
868    pub fn with_transform(mut self, transform: Transform3D) -> Self {
869        self.set_transform(transform);
870        self
871    }
872
873    /// Sets the fallback PBR material when source omits material metadata.
874    ///
875    /// # Arguments
876    ///
877    /// - `Self` - Base descriptor.
878    /// - `PbrMaterial` - Fallback PBR material.
879    ///
880    /// # Returns
881    ///
882    /// - `Self` - Updated descriptor.
883    #[must_use]
884    pub fn with_material(mut self, fallback_material: PbrMaterial) -> Self {
885        self.set_fallback_material(fallback_material);
886        self
887    }
888
889    /// Sets continuous Y-axis turntable spin speed in radians per second.
890    ///
891    /// # Arguments
892    ///
893    /// - `Self` - Base descriptor.
894    /// - `f32` - Spin speed in radians/sec.
895    ///
896    /// # Returns
897    ///
898    /// - `Self` - Updated descriptor.
899    #[must_use]
900    pub fn with_spin(mut self, spin_speed: f32) -> Self {
901        self.set_spin_speed(spin_speed);
902        self
903    }
904}
905
906/// Dynamic Time-of-Day sun and atmospheric sky lighting for `DirectionalLight3D`.
907impl DirectionalLight3D {
908    /// Computes physically inspired sun direction, sun color, and sky colors for `hour` in `[0.0, 24.0]`.
909    ///
910    /// # Arguments
911    ///
912    /// - `f32` - Hour of day (`6.0` dawn, `12.0` noon, `17.5` golden sunset, `22.0` neon night).
913    ///
914    /// # Returns
915    ///
916    /// - `Self` - Updated atmospheric directional light.
917    #[must_use]
918    pub fn from_time_of_day(hour: f32) -> Self {
919        let height_val: f32 = hour.rem_euclid(24.0);
920        let elev_angle: f32 = ((height_val - 6.0) / 12.0 * PI).clamp(-0.35, 3.49);
921        let sun_y: f32 = elev_angle.sin();
922        let sun_x: f32 = elev_angle.cos();
923        let dir: Vec3 = Vec3::new(-sun_x * 0.62, sun_y.max(0.22), -0.78).normalize();
924        if (7.5..=16.5).contains(&height_val) {
925            Self {
926                direction: dir,
927                color: Vec3::new(2.35, 2.18, 1.96),
928                sky_zenith: Vec3::new(0.08, 0.24, 0.64),
929                sky_horizon: Vec3::new(0.46, 0.66, 0.88),
930                time_of_day: height_val,
931            }
932        } else if (5.5..7.5).contains(&height_val) || (16.5..19.5).contains(&height_val) {
933            Self {
934                direction: Vec3::new(-0.14, 0.165, -0.976).normalize(),
935                color: Vec3::new(2.85, 1.42, 0.66),
936                sky_zenith: Vec3::new(0.028, 0.038, 0.155),
937                sky_horizon: Vec3::new(0.62, 0.24, 0.22),
938                time_of_day: height_val,
939            }
940        } else {
941            Self {
942                direction: Vec3::new(-0.36, 0.56, -0.74).normalize(),
943                color: Vec3::new(0.52, 0.68, 1.22),
944                sky_zenith: Vec3::new(0.012, 0.022, 0.068),
945                sky_horizon: Vec3::new(0.068, 0.115, 0.235),
946                time_of_day: height_val,
947            }
948        }
949    }
950}
951
952/// Default golden-sunset directional light.
953impl Default for DirectionalLight3D {
954    /// Creates a golden-hour sunset sun configuration.
955    ///
956    /// # Returns
957    ///
958    /// - `Self` - Sunset `DirectionalLight3D`.
959    fn default() -> Self {
960        Self::from_time_of_day(17.2)
961    }
962}
963
964/// Default empty 3D open world.
965impl Default for World3D {
966    /// Creates an empty `World3D` with 64m chunk streaming enabled.
967    ///
968    /// # Returns
969    ///
970    /// - `Self` - Empty `World3D`.
971    fn default() -> Self {
972        Self {
973            mesh_library: Vec::new(),
974            objects: Vec::new(),
975            camera: Camera3D::default(),
976            sun: DirectionalLight3D::default(),
977            bvh: Bvh3D::default(),
978            dynamic_bvh: Bvh3D::default(),
979            mesh_local_bvhs: Vec::new(),
980            dynamic_instances: Vec::new(),
981            bvh_dirty: true,
982            dynamic_bvh_dirty: true,
983            dynamic_topology_dirty: true,
984            static_bvh_rebuilds: 0,
985            dynamic_bvh_refits: 0,
986            dynamic_bvh_rebuilds: 0,
987            world_revision: 1,
988            dynamic_tris_scratch: Vec::new(),
989            chunk_size: 64.0,
990            player_vehicle_index: None,
991            hero_vehicle_style: HeroVehicleStyle::AventadorV12,
992            hero_vehicle_meshes: [None, None],
993            imported_model_count: 0,
994            camera_mode: 0,
995            camera_orbit_rad: 0.4,
996            point_lights: Vec::new(),
997            spot_lights: Vec::new(),
998            niagara: NiagaraSystem3D::default(),
999            atmosphere_preset: 0,
1000            traffic_vehicles: Vec::new(),
1001            world_time_secs: 0.0,
1002            scene_graph: SceneGraph3D::default(),
1003            principled_materials: Vec::new(),
1004            textures: Vec::new(),
1005            skins: Vec::new(),
1006            animation_mixer: AnimationMixer3D::default(),
1007            environment_ibl: None,
1008            area_lights: Vec::new(),
1009            scene_cameras: Vec::new(),
1010            active_scene_camera: None,
1011            node_object_map: Vec::new(),
1012            skin_scratch: SkinPaletteScratch3D::default(),
1013            deformed_meshes: Vec::new(),
1014            use_agx_tonemap: false,
1015            gpu_pass_scratch: World3dGpuPassScratch::default(),
1016            pbr_pass_scratch: World3dPbrPassScratch::default(),
1017        }
1018    }
1019}
1020
1021/// Open-world construction, model importing, BVH rebuild, and live vehicle/camera simulation for `World3D`.
1022impl World3D {
1023    /// Registers a `MeshLodChain` in the instancing library and returns its `mesh_id`.
1024    ///
1025    /// # Arguments
1026    ///
1027    /// - `&Self` - Mutable world.
1028    /// - `MeshLodChain` - Multi-level LOD mesh chain.
1029    ///
1030    /// # Returns
1031    ///
1032    /// - `usize` - Assigned `mesh_id`.
1033    pub fn register_mesh(&mut self, chain: MeshLodChain) -> usize {
1034        let id: usize = self.get_mesh_library().len();
1035        self.get_mut_mesh_library().push(chain);
1036        id
1037    }
1038
1039    /// Spawns an instanced `SceneObject3D` referencing `mesh_id` into its spatial world chunk.
1040    ///
1041    /// # Arguments
1042    ///
1043    /// - `&Self` - Mutable world.
1044    /// - `&str` - Object name.
1045    /// - `usize` - Registered `mesh_id`.
1046    /// - `Transform3D` - World transform.
1047    /// - `PbrMaterial` - Surface PBR material.
1048    /// - `bool` - Whether this object participates in BVH ray tracing.
1049    ///
1050    /// # Returns
1051    ///
1052    /// - `usize` - Index of the spawned `SceneObject3D`.
1053    pub fn spawn_object(
1054        &mut self,
1055        name: &str,
1056        mesh_id: usize,
1057        transform: Transform3D,
1058        material: PbrMaterial,
1059        ray_trace_caster: bool,
1060    ) -> usize {
1061        let local_bounds: AxisAlignedBox3D = self
1062            .get_mesh_library()
1063            .get(mesh_id)
1064            .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
1065            .map(Mesh3D::get_bounds)
1066            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
1067        let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
1068        let cs: f32 = self.get_chunk_size().max(8.0);
1069        let pos: Vec3 = transform.get_position();
1070        let chunk_coord: (i32, i32) = (
1071            (pos.get_x() / cs).floor() as i32,
1072            (pos.get_z() / cs).floor() as i32,
1073        );
1074        let idx: usize = self.get_objects().len();
1075        self.get_mut_objects().push(SceneObject3D {
1076            name: name.to_string(),
1077            mesh_id,
1078            transform,
1079            material,
1080            world_bounds,
1081            chunk_coord,
1082            ray_trace_caster,
1083            solid_collider: ray_trace_caster,
1084            spin_speed: 0.0,
1085            is_dynamic: false,
1086            teleport_epoch: 0,
1087            node_id: None,
1088            principled_material_id: None,
1089            skin_id: None,
1090        });
1091        let Self {
1092            deformed_meshes, ..
1093        } = self;
1094        deformed_meshes.push(None);
1095        if ray_trace_caster {
1096            self.set_bvh_dirty(true);
1097        }
1098        self.bump_world_revision();
1099        idx
1100    }
1101
1102    /// Increments the 3D world revision counter so 3D render caches invalidate independently of UI HUD updates.
1103    ///
1104    /// # Arguments
1105    ///
1106    /// - `&Self` - Mutable world.
1107    pub fn bump_world_revision(&mut self) {
1108        let next: u64 = self.get_world_revision().wrapping_add(1);
1109        self.set_world_revision(next);
1110    }
1111
1112    /// Marks object `obj_idx` as static or dynamic, routing its triangles between the static BVH and incrementally refitted dynamic BVH.
1113    ///
1114    /// # Arguments
1115    ///
1116    /// - `&Self` - Mutable world.
1117    /// - `usize` - Target object index in `objects`.
1118    /// - `bool` - `true` for dynamic BVH routing, `false` for static BVH routing.
1119    ///
1120    /// # Returns
1121    ///
1122    /// - `bool` - `true` when `obj_idx` existed and was updated.
1123    pub fn set_object_dynamic(&mut self, obj_idx: usize, is_dynamic: bool) -> bool {
1124        let Some(obj) = self.get_mut_objects().get_mut(obj_idx) else {
1125            return false;
1126        };
1127        if obj.get_is_dynamic() != is_dynamic {
1128            obj.set_is_dynamic(is_dynamic);
1129            if obj.get_ray_trace_caster() {
1130                self.set_bvh_dirty(true);
1131                self.set_dynamic_bvh_dirty(true);
1132                self.set_dynamic_topology_dirty(true);
1133            }
1134            self.bump_world_revision();
1135        }
1136        true
1137    }
1138
1139    /// Teleports object `obj_idx` to `transform`, incrementing `teleport_epoch` so snapshot interpolation snaps instead of sweeping.
1140    ///
1141    /// # Arguments
1142    ///
1143    /// - `&Self` - Mutable world.
1144    /// - `usize` - Target object index in `objects`.
1145    /// - `Transform3D` - Destination world transform.
1146    ///
1147    /// # Returns
1148    ///
1149    /// - `bool` - `true` when `obj_idx` existed and was teleported.
1150    pub fn teleport_object(&mut self, obj_idx: usize, transform: Transform3D) -> bool {
1151        let Some((mesh_id, ray_caster, is_dynamic)) =
1152            self.get_objects().get(obj_idx).map(|obj: &SceneObject3D| {
1153                (
1154                    obj.get_mesh_id(),
1155                    obj.get_ray_trace_caster(),
1156                    obj.get_is_dynamic(),
1157                )
1158            })
1159        else {
1160            return false;
1161        };
1162        let local_bounds: AxisAlignedBox3D = self
1163            .get_mesh_library()
1164            .get(mesh_id)
1165            .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
1166            .map(Mesh3D::get_bounds)
1167            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
1168        let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
1169        if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
1170            obj.set_transform(transform);
1171            obj.set_world_bounds(world_bounds);
1172            let next_epoch: u32 = obj.get_teleport_epoch().wrapping_add(1);
1173            obj.set_teleport_epoch(next_epoch);
1174        }
1175        if ray_caster {
1176            if is_dynamic {
1177                self.set_dynamic_bvh_dirty(true);
1178            } else {
1179                self.set_bvh_dirty(true);
1180            }
1181        }
1182        self.bump_world_revision();
1183        true
1184    }
1185
1186    /// Imports an external `.obj` or `.gltf` model directly into the live 3D world and returns import telemetry.
1187    ///
1188    /// # Arguments
1189    ///
1190    /// - `&Self` - Mutable world.
1191    /// - `ModelFormat` - Source model format.
1192    /// - `&str` - Raw `.obj` or `.gltf` text content.
1193    /// - `Transform3D` - Placement transform in the 3D scene.
1194    /// - `PbrMaterial` - Fallback PBR material.
1195    /// - `f32` - Optional continuous Y-spin speed in radians/sec.
1196    ///
1197    /// # Returns
1198    ///
1199    /// - `Result<ImportedModel3D, String>` - Imported model summary or parse error.
1200    pub fn import_model(
1201        &mut self,
1202        format: ModelFormat,
1203        source: &str,
1204        transform: Transform3D,
1205        fallback_material: PbrMaterial,
1206        spin_speed: f32,
1207    ) -> Result<ImportedModel3D, String> {
1208        let imported: ImportedModel3D = ModelImporter3D::import(format, source, fallback_material)?;
1209        let model_name: String = imported.get_name().clone();
1210        for (item_index, chain) in imported.get_meshes().iter().cloned().enumerate() {
1211            let mat: PbrMaterial = chain
1212                .get_levels()
1213                .first()
1214                .map(Mesh3D::get_material)
1215                .unwrap_or(fallback_material);
1216            let mid: usize = self.register_mesh(chain);
1217            let obj_idx: usize = self.spawn_object(
1218                &format!("{model_name}_{item_index}"),
1219                mid,
1220                transform,
1221                mat,
1222                true,
1223            );
1224            if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
1225                obj.set_spin_speed(spin_speed);
1226            }
1227            if spin_speed.abs() > 0.001 {
1228                let _: bool = self.set_object_dynamic(obj_idx, true);
1229            }
1230        }
1231        let next_cnt: usize = self.get_imported_model_count().saturating_add(1);
1232        self.set_imported_model_count(next_cnt);
1233        Ok(imported)
1234    }
1235
1236    /// Spawns an object from a fluent `SpawnObjectDesc`.
1237    ///
1238    /// # Arguments
1239    ///
1240    /// - `&Self` - Mutable world.
1241    /// - `&SpawnObjectDesc` - Spawn descriptor.
1242    ///
1243    /// # Returns
1244    ///
1245    /// - `usize` - Spawned object index.
1246    pub fn spawn_with(&mut self, desc: &SpawnObjectDesc) -> usize {
1247        let idx: usize = self.spawn_object(
1248            desc.get_name(),
1249            desc.get_mesh_id(),
1250            desc.get_transform(),
1251            desc.get_material(),
1252            desc.get_ray_trace_caster(),
1253        );
1254        if let Some(obj) = self.get_mut_objects().get_mut(idx) {
1255            obj.set_solid_collider(desc.get_solid_collider());
1256            obj.set_spin_speed(desc.get_spin_speed());
1257        }
1258        if desc.get_is_dynamic() || desc.get_spin_speed().abs() > 0.001 {
1259            let _: bool = self.set_object_dynamic(idx, true);
1260        }
1261        idx
1262    }
1263
1264    /// Imports an external `.obj` or `.gltf` model using a fluent `ImportModelDesc`.
1265    ///
1266    /// # Arguments
1267    ///
1268    /// - `&Self` - Mutable world.
1269    /// - `&ImportModelDesc` - Import descriptor.
1270    ///
1271    /// # Returns
1272    ///
1273    /// - `Result<ImportedModel3D, String>` - Imported model telemetry or parse error.
1274    pub fn import_with(&mut self, desc: &ImportModelDesc) -> Result<ImportedModel3D, String> {
1275        self.import_model(
1276            desc.get_format(),
1277            desc.get_source(),
1278            desc.get_transform(),
1279            desc.get_fallback_material(),
1280            desc.get_spin_speed(),
1281        )
1282    }
1283
1284    /// Returns the typed `CameraMode3D` currently active in this world.
1285    ///
1286    /// # Arguments
1287    ///
1288    /// - `&Self` - World reference.
1289    ///
1290    /// # Returns
1291    ///
1292    /// - `CameraMode3D` - Active typed camera controller mode.
1293    #[must_use]
1294    pub fn active_camera_mode(&self) -> CameraMode3D {
1295        CameraMode3D::from_u8(self.get_camera_mode())
1296    }
1297
1298    /// Sets the active 3D camera controller using a typed `CameraMode3D`.
1299    ///
1300    /// # Arguments
1301    ///
1302    /// - `&Self` - Mutable world.
1303    /// - `CameraMode3D` - Desired camera controller mode.
1304    pub fn set_camera_mode_enum(&mut self, mode: CameraMode3D) {
1305        self.set_camera_mode(mode.as_u8());
1306    }
1307
1308    /// Collects world-space triangles for all ray-trace casters matching `dynamic_filter` into `out_tris`.
1309    ///
1310    /// # Arguments
1311    ///
1312    /// - `&[SceneObject3D]` - World object slice.
1313    /// - `&[MeshLodChain]` - Registered mesh library slice.
1314    /// - `bool` - `true` to gather dynamic casters, `false` to gather static casters.
1315    /// - `&mut Vec<BvhTriangle>` - Destination triangle buffer cleared and populated in place.
1316    fn collect_caster_triangles(
1317        objects: &[SceneObject3D],
1318        mesh_library: &[MeshLodChain],
1319        dynamic_filter: bool,
1320        out_tris: &mut Vec<BvhTriangle>,
1321    ) {
1322        out_tris.clear();
1323        for obj in objects.iter() {
1324            if !obj.get_ray_trace_caster() || obj.get_is_dynamic() != dynamic_filter {
1325                continue;
1326            }
1327            let Some(chain) = mesh_library.get(obj.get_mesh_id()) else {
1328                continue;
1329            };
1330            let Some(mesh) = chain.get_levels().first() else {
1331                continue;
1332            };
1333            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1334            let model_m: Mat4 = obj.get_transform().to_mat4();
1335            let mat: PbrMaterial = obj.get_material();
1336            for (tri_idx, tri) in mesh.get_indices().iter().enumerate() {
1337                let (i0, i1, i2): (usize, usize, usize) =
1338                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1339                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1340                    let p0: Vec3 = model_m.mul_point3(verts[i0].get_position());
1341                    let p1: Vec3 = model_m.mul_point3(verts[i1].get_position());
1342                    let p2: Vec3 = model_m.mul_point3(verts[i2].get_position());
1343                    let (tri_mat, mat_slot): (PbrMaterial, u16) =
1344                        mesh.resolve_triangle_material(tri_idx, mat);
1345                    out_tris.push(BvhTriangle::from_points_with_slot(
1346                        p0, p1, p2, tri_mat, mat_slot,
1347                    ));
1348                }
1349            }
1350        }
1351    }
1352
1353    /// Synchronizes the split static and dynamic BVH acceleration structures, refitting moving dynamic casters in O(N) without rebuilding static world geometry.
1354    ///
1355    /// # Arguments
1356    ///
1357    /// - `&Self` - Mutable world.
1358    pub fn ensure_bvh(&mut self) {
1359        if self.get_bvh_dirty() {
1360            let mut static_tris: Vec<BvhTriangle> = Vec::new();
1361            Self::collect_caster_triangles(
1362                self.get_objects().as_slice(),
1363                self.get_mesh_library().as_slice(),
1364                false,
1365                &mut static_tris,
1366            );
1367            self.set_bvh(Bvh3D::build(static_tris));
1368            self.set_bvh_dirty(false);
1369            let next_static: u64 = self.get_static_bvh_rebuilds().saturating_add(1);
1370            self.set_static_bvh_rebuilds(next_static);
1371        }
1372        if self.get_dynamic_bvh_dirty() {
1373            let topology_dirty: bool = self.get_dynamic_topology_dirty();
1374            let Self {
1375                objects,
1376                mesh_library,
1377                dynamic_bvh,
1378                dynamic_tris_scratch,
1379                dynamic_bvh_dirty,
1380                dynamic_topology_dirty,
1381                dynamic_bvh_refits,
1382                dynamic_bvh_rebuilds,
1383                ..
1384            } = self;
1385            Self::collect_caster_triangles(
1386                objects.as_slice(),
1387                mesh_library.as_slice(),
1388                true,
1389                dynamic_tris_scratch,
1390            );
1391            if dynamic_tris_scratch.is_empty() {
1392                dynamic_bvh.rebuild_in_place(&[]);
1393            } else if !topology_dirty
1394                && dynamic_bvh.refit_from_source(dynamic_tris_scratch.as_slice())
1395            {
1396                let check_degraded: bool = ((*dynamic_bvh_refits + 1) & 15) == 0;
1397                if check_degraded && dynamic_bvh.needs_rebuild_after_refit(3.5) {
1398                    dynamic_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
1399                    *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
1400                } else {
1401                    *dynamic_bvh_refits = dynamic_bvh_refits.saturating_add(1);
1402                }
1403            } else {
1404                dynamic_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
1405                *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
1406            }
1407            *dynamic_bvh_dirty = false;
1408            *dynamic_topology_dirty = false;
1409        }
1410        self.sync_dynamic_ray_instances();
1411    }
1412
1413    /// Lazily constructs local-space BVH4/BVH8 trees for dynamic meshes and updates `dynamic_instances` from current object transforms with zero BVH rebuilds.
1414    ///
1415    /// # Arguments
1416    ///
1417    /// - `&Self` - Mutable world reference.
1418    pub fn sync_dynamic_ray_instances(&mut self) {
1419        let Self {
1420            mesh_library,
1421            objects,
1422            mesh_local_bvhs,
1423            dynamic_instances,
1424            ..
1425        } = self;
1426        if mesh_local_bvhs.len() < mesh_library.len() {
1427            mesh_local_bvhs.resize_with(mesh_library.len(), || None);
1428        }
1429        dynamic_instances.clear();
1430        for (obj_idx, obj) in objects.iter().enumerate() {
1431            if !obj.get_ray_trace_caster() || !obj.get_is_dynamic() {
1432                continue;
1433            }
1434            let mesh_id: usize = obj.get_mesh_id();
1435            let Some(chain) = mesh_library.get(mesh_id) else {
1436                continue;
1437            };
1438            let Some(mesh) = chain.get_levels().first() else {
1439                continue;
1440            };
1441            if mesh_local_bvhs[mesh_id].is_none() {
1442                let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1443                let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
1444                let mut local_tris: Vec<BvhTriangle> = Vec::with_capacity(indices.len());
1445                let neutral: PbrMaterial = PbrMaterial::default();
1446                for (tri_idx, tri) in indices.iter().enumerate() {
1447                    let (i0, i1, i2): (usize, usize, usize) =
1448                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1449                    if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1450                        let (tri_mat, mat_slot): (PbrMaterial, u16) =
1451                            mesh.resolve_triangle_material(tri_idx, neutral);
1452                        local_tris.push(BvhTriangle::from_points_with_slot(
1453                            verts[i0].get_position(),
1454                            verts[i1].get_position(),
1455                            verts[i2].get_position(),
1456                            tri_mat,
1457                            mat_slot,
1458                        ));
1459                    }
1460                }
1461                mesh_local_bvhs[mesh_id] = Some(Bvh3D::build(local_tris));
1462            }
1463            let transform_val: Transform3D = obj.get_transform();
1464            dynamic_instances.push(DynamicRayInstance {
1465                obj_idx,
1466                mesh_id,
1467                world_bounds: obj.get_world_bounds(),
1468                inv_model: transform_val.to_inv_mat4(),
1469                normal_basis: transform_val.normal_mat3(),
1470                material: obj.get_material(),
1471            });
1472        }
1473    }
1474
1475    /// Updates only the inverse-model transform, normal basis, and world axis-aligned bounding box of an existing dynamic instance without rebuilding any BVH.
1476    ///
1477    /// # Arguments
1478    ///
1479    /// - `&Self` - Mutable world reference.
1480    /// - `usize` - Scene object index.
1481    /// - `Transform3D` - Interpolated world transform.
1482    /// - `AxisAlignedBox3D` - Interpolated world axis-aligned bounding box.
1483    pub(crate) fn override_dynamic_instance_pose(
1484        &mut self,
1485        obj_idx: usize,
1486        transform: Transform3D,
1487        world_bounds: AxisAlignedBox3D,
1488    ) {
1489        let Self {
1490            dynamic_instances, ..
1491        } = self;
1492        for inst in dynamic_instances.iter_mut() {
1493            if inst.obj_idx == obj_idx {
1494                inst.world_bounds = world_bounds;
1495                inst.inv_model = transform.to_inv_mat4();
1496                inst.normal_basis = transform.normal_mat3();
1497                return;
1498            }
1499        }
1500    }
1501
1502    /// Traces a shadow ray against object-space dynamic instances via inverse interpolated `Mat4` with zero dynamic BVH rebuilds.
1503    ///
1504    /// # Arguments
1505    ///
1506    /// - `&[DynamicRayInstance]` - Active dynamic raytracing instances.
1507    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1508    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1509    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1510    /// - `&mut u32` - Per-thread local occluder triangle hint.
1511    ///
1512    /// # Returns
1513    ///
1514    /// - `bool` - `true` if occluded by any dynamic object at its current or interpolated pose.
1515    #[inline(always)]
1516    #[must_use]
1517    pub(crate) fn trace_any_shadow_dynamic_instances(
1518        instances: &[DynamicRayInstance],
1519        local_bvhs: &[Option<Bvh3D>],
1520        ray: (Vec3, Vec3, Vec3),
1521        bounds: (f32, f32),
1522        dyn_cache: &mut u32,
1523    ) -> bool {
1524        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1525        let (t_min, t_max): (f32, f32) = bounds;
1526        for inst in instances.iter() {
1527            if !inst
1528                .world_bounds
1529                .intersect_ray_near(origin, inv_dir, t_min, t_max)
1530                .is_finite()
1531            {
1532                continue;
1533            }
1534            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1535                continue;
1536            };
1537            let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
1538            let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
1539            let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
1540            if local_bvh
1541                .trace_any_shadow_cached(local_orig, local_dir, local_inv, t_min, t_max, dyn_cache)
1542            {
1543                return true;
1544            }
1545        }
1546        false
1547    }
1548
1549    /// Traces a coherent 4-ray shadow packet against static BVH and object-space inverse-interpolated dynamic instances.
1550    ///
1551    /// # Arguments
1552    ///
1553    /// - `&Bvh3D` - Static world BVH4/BVH8.
1554    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1555    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1556    /// - `&RayPacket4` - Coherent 4-ray shadow packet.
1557    /// - `u8` - 4-bit mask of active rays to trace.
1558    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1559    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder hints.
1560    ///
1561    /// # Returns
1562    ///
1563    /// - `u8` - 4-bit mask of occluded rays.
1564    #[inline(always)]
1565    #[must_use]
1566    pub(crate) fn trace_any_shadow_packet4_with_instances(
1567        static_bvh: &Bvh3D,
1568        instances: &[DynamicRayInstance],
1569        local_bvhs: &[Option<Bvh3D>],
1570        pkt: &RayPacket4,
1571        active_mask: u8,
1572        bounds: (f32, f32),
1573        caches: (&mut u32, &mut u32),
1574    ) -> u8 {
1575        let (t_min, t_max): (f32, f32) = bounds;
1576        let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
1577        let mut occluded: u8 =
1578            static_bvh.trace_any_shadow_packet4(pkt, active_mask, t_min, t_max, static_cache);
1579        let mut rem: u8 = active_mask & !occluded;
1580        if rem == 0 || instances.is_empty() {
1581            return occluded;
1582        }
1583        for inst in instances.iter() {
1584            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1585                continue;
1586            };
1587            let mut hit_box_mask: u8 = 0;
1588            let mut check: u8 = rem;
1589            while check != 0 {
1590                let red_val: usize = check.trailing_zeros() as usize;
1591                check &= check - 1;
1592                let orig_r: Vec3 = Vec3::new(pkt.ox[red_val], pkt.oy[red_val], pkt.oz[red_val]);
1593                let inv_r: Vec3 = Vec3::new(pkt.ix[red_val], pkt.iy[red_val], pkt.iz[red_val]);
1594                if inst
1595                    .world_bounds
1596                    .intersect_ray_near(orig_r, inv_r, t_min, t_max)
1597                    .is_finite()
1598                {
1599                    hit_box_mask |= 1_u8 << red_val;
1600                }
1601            }
1602            if hit_box_mask == 0 {
1603                continue;
1604            }
1605            let mut local_pkt: RayPacket4 = *pkt;
1606            let mut tr_mask: u8 = hit_box_mask;
1607            while tr_mask != 0 {
1608                let radius_val: usize = tr_mask.trailing_zeros() as usize;
1609                tr_mask &= tr_mask - 1;
1610                let lo: Vec3 = inst.inv_model.mul_point3(Vec3::new(
1611                    pkt.ox[radius_val],
1612                    pkt.oy[radius_val],
1613                    pkt.oz[radius_val],
1614                ));
1615                let ld: Vec3 = inst.inv_model.mul_vec3(Vec3::new(
1616                    pkt.dx[radius_val],
1617                    pkt.dy[radius_val],
1618                    pkt.dz[radius_val],
1619                ));
1620                let li: Vec3 = Ray3D::safe_inv_vec(ld);
1621                local_pkt.ox[radius_val] = lo.get_x();
1622                local_pkt.oy[radius_val] = lo.get_y();
1623                local_pkt.oz[radius_val] = lo.get_z();
1624                local_pkt.dx[radius_val] = ld.get_x();
1625                local_pkt.dy[radius_val] = ld.get_y();
1626                local_pkt.dz[radius_val] = ld.get_z();
1627                local_pkt.ix[radius_val] = li.get_x();
1628                local_pkt.iy[radius_val] = li.get_y();
1629                local_pkt.iz[radius_val] = li.get_z();
1630            }
1631            let dyn_occ: u8 = local_bvh.trace_any_shadow_packet4(
1632                &local_pkt,
1633                hit_box_mask,
1634                t_min,
1635                t_max,
1636                dyn_cache,
1637            );
1638            occluded |= dyn_occ;
1639            rem &= !dyn_occ;
1640            if rem == 0 {
1641                break;
1642            }
1643        }
1644        occluded
1645    }
1646
1647    /// Traces a shadow/occlusion ray across static BVH and object-space inverse-interpolated dynamic instances.
1648    ///
1649    /// # Arguments
1650    ///
1651    /// - `&Bvh3D` - Static world BVH.
1652    /// - `&[DynamicRayInstance]` - Active dynamic raytracing instances.
1653    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1654    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1655    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1656    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder hints.
1657    ///
1658    /// # Returns
1659    ///
1660    /// - `bool` - `true` when occluded by static or dynamic geometry.
1661    #[inline(always)]
1662    #[must_use]
1663    pub(crate) fn trace_any_shadow_with_instances(
1664        static_bvh: &Bvh3D,
1665        instances: &[DynamicRayInstance],
1666        local_bvhs: &[Option<Bvh3D>],
1667        ray: (Vec3, Vec3, Vec3),
1668        bounds: (f32, f32),
1669        caches: (&mut u32, &mut u32),
1670    ) -> bool {
1671        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1672        let (t_min, t_max): (f32, f32) = bounds;
1673        let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
1674        if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
1675            return true;
1676        }
1677        if !instances.is_empty() {
1678            return Self::trace_any_shadow_dynamic_instances(
1679                instances, local_bvhs, ray, bounds, dyn_cache,
1680            );
1681        }
1682        false
1683    }
1684
1685    /// Traces a reflection/GI ray across static BVH and object-space inverse-interpolated dynamic instances, returning `(distance, world_normal, material)`.
1686    ///
1687    /// # Arguments
1688    ///
1689    /// - `&Bvh3D` - Static world BVH.
1690    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1691    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1692    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1693    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1694    ///
1695    /// # Returns
1696    ///
1697    /// - `Option<(f32, Vec3, PbrMaterial)>` - Closest hit distance, world-space unit normal, and PBR material.
1698    #[inline(always)]
1699    #[must_use]
1700    pub(crate) fn trace_closest_with_instances(
1701        static_bvh: &Bvh3D,
1702        instances: &[DynamicRayInstance],
1703        local_bvhs: &[Option<Bvh3D>],
1704        ray: (Vec3, Vec3, Vec3),
1705        bounds: (f32, f32),
1706    ) -> Option<(f32, Vec3, PbrMaterial)> {
1707        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1708        let (t_min, t_max): (f32, f32) = bounds;
1709        let mut best_t: f32 = t_max;
1710        let mut best_hit: Option<(f32, Vec3, PbrMaterial)> = static_bvh
1711            .trace_closest_raw(origin, dir, inv_dir, t_min, t_max)
1712            .map(|(node_style, si): (f32, usize)| {
1713                let tri: &BvhTriangle = &static_bvh.get_triangles()[si];
1714                best_t = node_style;
1715                (node_style, tri.get_normal(), tri.get_material())
1716            });
1717        for inst in instances.iter() {
1718            if !inst
1719                .world_bounds
1720                .intersect_ray_near(origin, inv_dir, t_min, best_t)
1721                .is_finite()
1722            {
1723                continue;
1724            }
1725            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1726                continue;
1727            };
1728            let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
1729            let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
1730            let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
1731            if let Some((dt, di)) =
1732                local_bvh.trace_closest_raw(local_orig, local_dir, local_inv, t_min, best_t)
1733            {
1734                best_t = dt;
1735                let hit_tri: &BvhTriangle = &local_bvh.get_triangles()[di];
1736                let local_n: Vec3 = hit_tri.get_normal();
1737                let world_n: Vec3 = Mat4::transform_normal_with_basis(local_n, inst.normal_basis);
1738                let hit_mat: PbrMaterial = if hit_tri.get_material_slot() == 0 {
1739                    inst.material
1740                } else {
1741                    hit_tri.get_material()
1742                };
1743                best_hit = Some((dt, world_n, hit_mat));
1744            }
1745        }
1746        best_hit
1747    }
1748
1749    /// Traces a coherent 4-ray closest-hit packet across static BVH and object-space inverse-interpolated dynamic instances.
1750    ///
1751    /// # Arguments
1752    ///
1753    /// - `&Bvh3D` - Static world BVH4/BVH8.
1754    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1755    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1756    /// - `&RayPacket4` - Coherent 4-ray reflection or GI packet.
1757    /// - `u8` - 4-bit mask of active rays.
1758    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1759    ///
1760    /// # Returns
1761    ///
1762    /// - `[Option<(f32, Vec3, PbrMaterial)>; 4]` - Closest hit distance, world normal, and material per lane.
1763    #[inline(always)]
1764    #[must_use]
1765    pub(crate) fn trace_closest_packet4_with_instances(
1766        static_bvh: &Bvh3D,
1767        instances: &[DynamicRayInstance],
1768        local_bvhs: &[Option<Bvh3D>],
1769        pkt: &RayPacket4,
1770        active_mask: u8,
1771        bounds: (f32, f32),
1772    ) -> [Option<(f32, Vec3, PbrMaterial)>; 4] {
1773        let (t_min, t_max): (f32, f32) = bounds;
1774        let mut best_t: [f32; 4] = [t_max; 4];
1775        let mut best_static_idx: [usize; 4] = [usize::MAX; 4];
1776        static_bvh.trace_closest_packet4(
1777            pkt,
1778            active_mask,
1779            t_min,
1780            &mut best_t,
1781            &mut best_static_idx,
1782        );
1783        let static_tris: &[BvhTriangle] = static_bvh.get_triangles().as_slice();
1784        let mut out: [Option<(f32, Vec3, PbrMaterial)>; 4] = [None; 4];
1785        let mut matrix_elems: u8 = active_mask;
1786        while matrix_elems != 0 {
1787            let red_val: usize = matrix_elems.trailing_zeros() as usize;
1788            matrix_elems &= matrix_elems - 1;
1789            let sidx: usize = best_static_idx[red_val];
1790            if sidx != usize::MAX {
1791                let tri: &BvhTriangle = &static_tris[sidx];
1792                out[red_val] = Some((best_t[red_val], tri.get_normal(), tri.get_material()));
1793            }
1794        }
1795        for inst in instances.iter() {
1796            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1797                continue;
1798            };
1799            let mut hit_box_mask: u8 = 0;
1800            let mut check: u8 = active_mask;
1801            while check != 0 {
1802                let radius_val: usize = check.trailing_zeros() as usize;
1803                check &= check - 1;
1804                if inst
1805                    .world_bounds
1806                    .intersect_ray_near(
1807                        Vec3::new(pkt.ox[radius_val], pkt.oy[radius_val], pkt.oz[radius_val]),
1808                        Vec3::new(pkt.ix[radius_val], pkt.iy[radius_val], pkt.iz[radius_val]),
1809                        t_min,
1810                        best_t[radius_val],
1811                    )
1812                    .is_finite()
1813                {
1814                    hit_box_mask |= 1_u8 << radius_val;
1815                }
1816            }
1817            if hit_box_mask == 0 {
1818                continue;
1819            }
1820            let mut local_pkt: RayPacket4 = *pkt;
1821            let mut tr_mask: u8 = hit_box_mask;
1822            while tr_mask != 0 {
1823                let rect_val: usize = tr_mask.trailing_zeros() as usize;
1824                tr_mask &= tr_mask - 1;
1825                let lo: Vec3 = inst.inv_model.mul_point3(Vec3::new(
1826                    pkt.ox[rect_val],
1827                    pkt.oy[rect_val],
1828                    pkt.oz[rect_val],
1829                ));
1830                let ld: Vec3 = inst.inv_model.mul_vec3(Vec3::new(
1831                    pkt.dx[rect_val],
1832                    pkt.dy[rect_val],
1833                    pkt.dz[rect_val],
1834                ));
1835                let li: Vec3 = Ray3D::safe_inv_vec(ld);
1836                local_pkt.ox[rect_val] = lo.get_x();
1837                local_pkt.oy[rect_val] = lo.get_y();
1838                local_pkt.oz[rect_val] = lo.get_z();
1839                local_pkt.dx[rect_val] = ld.get_x();
1840                local_pkt.dy[rect_val] = ld.get_y();
1841                local_pkt.dz[rect_val] = ld.get_z();
1842                local_pkt.ix[rect_val] = li.get_x();
1843                local_pkt.iy[rect_val] = li.get_y();
1844                local_pkt.iz[rect_val] = li.get_z();
1845            }
1846            let mut dyn_idx: [usize; 4] = [usize::MAX; 4];
1847            local_bvh.trace_closest_packet4(
1848                &local_pkt,
1849                hit_box_mask,
1850                t_min,
1851                &mut best_t,
1852                &mut dyn_idx,
1853            );
1854            let local_tris: &[BvhTriangle] = local_bvh.get_triangles().as_slice();
1855            let mut upd: u8 = hit_box_mask;
1856            while upd != 0 {
1857                let row_val: usize = upd.trailing_zeros() as usize;
1858                upd &= upd - 1;
1859                let di: usize = dyn_idx[row_val];
1860                if di != usize::MAX {
1861                    let hit_tri: &BvhTriangle = &local_tris[di];
1862                    let wn: Vec3 =
1863                        Mat4::transform_normal_with_basis(hit_tri.get_normal(), inst.normal_basis);
1864                    let hit_mat: PbrMaterial = if hit_tri.get_material_slot() == 0 {
1865                        inst.material
1866                    } else {
1867                        hit_tri.get_material()
1868                    };
1869                    out[row_val] = Some((best_t[row_val], wn, hit_mat));
1870                }
1871            }
1872        }
1873        out
1874    }
1875
1876    /// Traces a shadow ray using static BVH plus object-space inverse-interpolated dynamic instances.
1877    ///
1878    /// # Arguments
1879    ///
1880    /// - `&Self` - World reference.
1881    /// - `&Ray3D` - World-space shadow ray.
1882    /// - `f32` - Minimum hit distance.
1883    /// - `f32` - Maximum hit distance.
1884    ///
1885    /// # Returns
1886    ///
1887    /// - `bool` - `true` when occluded by static or dynamic geometry at its current/interpolated pose.
1888    #[must_use]
1889    pub fn trace_any_shadow_object_space(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
1890        let Self {
1891            bvh,
1892            dynamic_instances,
1893            mesh_local_bvhs,
1894            ..
1895        } = self;
1896        let mut scale_factor: u32 = u32::MAX;
1897        let mut dc: u32 = u32::MAX;
1898        Self::trace_any_shadow_with_instances(
1899            bvh,
1900            dynamic_instances.as_slice(),
1901            mesh_local_bvhs.as_slice(),
1902            (
1903                ray.get_origin(),
1904                ray.get_direction(),
1905                ray.get_inv_direction(),
1906            ),
1907            (t_min, t_max),
1908            (&mut scale_factor, &mut dc),
1909        )
1910    }
1911
1912    /// Traces a coherent 4-ray closest-hit packet against both the static BVH4 and object-space inverse-interpolated dynamic instances.
1913    ///
1914    /// # Arguments
1915    ///
1916    /// - `&Self` - World reference.
1917    /// - `&RayPacket4` - Coherent 4-ray query packet.
1918    /// - `u8` - 4-bit mask of active rays (`0..=15`).
1919    /// - `f32` - Minimum hit distance.
1920    /// - `f32` - Maximum hit distance.
1921    ///
1922    /// # Returns
1923    ///
1924    /// - `[Option<RayHit3D>; 4]` - Closest hit surface with world normal and material per active lane.
1925    #[must_use]
1926    pub fn trace_closest_packet4(
1927        &self,
1928        pkt: &RayPacket4,
1929        active_mask: u8,
1930        t_min: f32,
1931        t_max: f32,
1932    ) -> [Option<RayHit3D>; 4] {
1933        let Self {
1934            bvh,
1935            dynamic_instances,
1936            mesh_local_bvhs,
1937            ..
1938        } = self;
1939        let raw: [Option<(f32, Vec3, PbrMaterial)>; 4] = Self::trace_closest_packet4_with_instances(
1940            bvh,
1941            dynamic_instances.as_slice(),
1942            mesh_local_bvhs.as_slice(),
1943            pkt,
1944            active_mask,
1945            (t_min, t_max),
1946        );
1947        let mut out: [Option<RayHit3D>; 4] = [None; 4];
1948        for lane in 0..4 {
1949            if let Some((blend_factor, normal, material)) = raw[lane] {
1950                let point: Vec3 = Vec3::new(
1951                    pkt.ox[lane] + pkt.dx[lane] * blend_factor,
1952                    pkt.oy[lane] + pkt.dy[lane] * blend_factor,
1953                    pkt.oz[lane] + pkt.dz[lane] * blend_factor,
1954                );
1955                out[lane] = Some(RayHit3D {
1956                    distance: blend_factor,
1957                    point,
1958                    normal,
1959                    material,
1960                });
1961            }
1962        }
1963        out
1964    }
1965
1966    /// Traces a closest-hit ray using static BVH plus object-space inverse-interpolated dynamic instances.
1967    ///
1968    /// # Arguments
1969    ///
1970    /// - `&Self` - World reference.
1971    /// - `&Ray3D` - World-space query ray.
1972    /// - `f32` - Minimum hit distance.
1973    /// - `f32` - Maximum hit distance.
1974    ///
1975    /// # Returns
1976    ///
1977    /// - `Option<RayHit3D>` - Closest hit surface with world-space normal and material.
1978    #[must_use]
1979    pub fn trace_closest_object_space(
1980        &self,
1981        ray: &Ray3D,
1982        t_min: f32,
1983        t_max: f32,
1984    ) -> Option<RayHit3D> {
1985        let Self {
1986            bvh,
1987            dynamic_instances,
1988            mesh_local_bvhs,
1989            ..
1990        } = self;
1991        let (blend_factor, normal, material): (f32, Vec3, PbrMaterial) =
1992            Self::trace_closest_with_instances(
1993                bvh,
1994                dynamic_instances.as_slice(),
1995                mesh_local_bvhs.as_slice(),
1996                (
1997                    ray.get_origin(),
1998                    ray.get_direction(),
1999                    ray.get_inv_direction(),
2000                ),
2001                (t_min, t_max),
2002            )?;
2003        Some(RayHit3D {
2004            distance: blend_factor,
2005            point: ray
2006                .get_origin()
2007                .add(ray.get_direction().scale(blend_factor)),
2008            normal,
2009            material,
2010        })
2011    }
2012
2013    /// Returns the combined node count across both static and dynamic BVH acceleration trees.
2014    ///
2015    /// # Arguments
2016    ///
2017    /// - `&Self` - World reference.
2018    ///
2019    /// # Returns
2020    ///
2021    /// - `usize` - Total active BVH nodes.
2022    #[must_use]
2023    pub fn total_bvh_nodes(&self) -> usize {
2024        self.get_bvh()
2025            .get_nodes()
2026            .len()
2027            .saturating_add(self.get_dynamic_bvh().get_nodes().len())
2028    }
2029
2030    /// Traces a shadow/occlusion ray across both static and dynamic BVHs using 1-triangle occluder caches.
2031    ///
2032    /// # Arguments
2033    ///
2034    /// - `(&Bvh3D, &Bvh3D)` - `(static_bvh, dynamic_bvh)` pair.
2035    /// - `(Vec3, Vec3, Vec3)` - `(origin, dir, inv_dir)` ray triple.
2036    /// - `(f32, f32)` - `(t_min, t_max)` distance bounds.
2037    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder triangle hints.
2038    ///
2039    /// # Returns
2040    ///
2041    /// - `bool` - `true` if occluded by either static or dynamic geometry.
2042    #[must_use]
2043    pub fn trace_any_shadow_split(
2044        bvhs: (&Bvh3D, &Bvh3D),
2045        ray: (Vec3, Vec3, Vec3),
2046        bounds: (f32, f32),
2047        caches: (&mut u32, &mut u32),
2048    ) -> bool {
2049        let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
2050        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2051        let (t_min, t_max): (f32, f32) = bounds;
2052        let (static_cache, dynamic_cache): (&mut u32, &mut u32) = caches;
2053        if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
2054            return true;
2055        }
2056        if !dynamic_bvh.is_empty() {
2057            return dynamic_bvh.trace_any_shadow_cached(
2058                origin,
2059                dir,
2060                inv_dir,
2061                t_min,
2062                t_max,
2063                dynamic_cache,
2064            );
2065        }
2066        false
2067    }
2068
2069    /// Traces a reflection/GI ray across both static and dynamic BVHs and returns `(distance, is_dynamic, tri_index)`.
2070    ///
2071    /// # Arguments
2072    ///
2073    /// - `(&Bvh3D, &Bvh3D)` - `(static_bvh, dynamic_bvh)` pair.
2074    /// - `(Vec3, Vec3, Vec3)` - `(origin, dir, inv_dir)` ray triple.
2075    /// - `(f32, f32)` - `(t_min, t_max)` distance bounds.
2076    ///
2077    /// # Returns
2078    ///
2079    /// - `Option<(f32, bool, usize)>` - Closest `(t, hit_in_dynamic_bvh, triangle_index)`.
2080    #[must_use]
2081    pub fn trace_closest_split(
2082        bvhs: (&Bvh3D, &Bvh3D),
2083        ray: (Vec3, Vec3, Vec3),
2084        bounds: (f32, f32),
2085    ) -> Option<(f32, bool, usize)> {
2086        let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
2087        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2088        let (t_min, t_max): (f32, f32) = bounds;
2089        let static_hit: Option<(f32, usize)> =
2090            static_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, t_max);
2091        let dyn_limit: f32 =
2092            static_hit.map_or(t_max, |(blend_factor, _): (f32, usize)| blend_factor);
2093        let dynamic_hit: Option<(f32, usize)> = if !dynamic_bvh.is_empty() {
2094            dynamic_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, dyn_limit)
2095        } else {
2096            None
2097        };
2098        match (static_hit, dynamic_hit) {
2099            (_, Some((dt, di))) => Some((dt, true, di)),
2100            (Some((node_style, si)), None) => Some((node_style, false, si)),
2101            (None, None) => None,
2102        }
2103    }
2104
2105    /// Returns the optional player vehicle index.
2106    ///
2107    /// # Arguments
2108    ///
2109    /// - `&Self` - World reference.
2110    ///
2111    /// # Returns
2112    ///
2113    /// - `Option<usize>` - Vehicle index in `objects`.
2114    #[must_use]
2115    pub fn vehicle_index(&self) -> Option<usize> {
2116        let Self {
2117            player_vehicle_index,
2118            ..
2119        } = self;
2120        *player_vehicle_index
2121    }
2122
2123    /// 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)`.
2124    ///
2125    /// # Arguments
2126    ///
2127    /// - `f32` - World-space X coordinate in meters.
2128    /// - `f32` - World-space Z coordinate in meters.
2129    ///
2130    /// # Returns
2131    ///
2132    /// - `(f32, f32)` - `(d_spine, road_u)` in meters matching the GPU road/puddle/coastal-bay shader contract.
2133    #[must_use]
2134    pub fn loop_lateral_offset(world_x: f32, world_z: f32) -> (f32, f32) {
2135        let spine_z: f32 = world_z.clamp(-CITY_LOOP_STRAIGHT_HALF_Z, CITY_LOOP_STRAIGHT_HALF_Z);
2136        let dx: f32 = world_x - CITY_LOOP_CENTER_X;
2137        let dz: f32 = world_z - spine_z;
2138        let d_spine: f32 = dx.hypot(dz);
2139        (d_spine, d_spine - CITY_LOOP_RADIUS)
2140    }
2141
2142    /// 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`.
2143    ///
2144    /// # Arguments
2145    ///
2146    /// - `f32` - Continuous arc-length along the loop centerline in meters (wrapped modulo `CITY_LOOP_TOTAL_LENGTH`).
2147    /// - `f32` - Signed lateral offset from centerline in meters (`+` outward, `-` inward toward Inner Landmark Island).
2148    ///
2149    /// # Returns
2150    ///
2151    /// - `(Vec3, f32)` - `(world_position, clockwise_yaw_rad)` where car forward is `(-sin(yaw), 0, -cos(yaw))`.
2152    #[must_use]
2153    pub fn loop_pose_at(arc_s: f32, lateral_u: f32) -> (Vec3, f32) {
2154        let straight_len: f32 = 2.0 * CITY_LOOP_STRAIGHT_HALF_Z;
2155        let arc_len: f32 = PI * CITY_LOOP_RADIUS;
2156        let s: f32 = arc_s.rem_euclid(CITY_LOOP_TOTAL_LENGTH);
2157        if s < straight_len {
2158            let world_x: f32 = -lateral_u;
2159            let world_z: f32 = CITY_LOOP_STRAIGHT_HALF_Z - s;
2160            (Vec3::new(world_x, 0.0, world_z), 0.0)
2161        } else if s < straight_len + arc_len {
2162            let alpha: f32 = (s - straight_len) / CITY_LOOP_RADIUS;
2163            let radius: f32 = CITY_LOOP_RADIUS + lateral_u;
2164            let (sin_a, cos_a): (f32, f32) = alpha.sin_cos();
2165            let world_x: f32 = CITY_LOOP_CENTER_X - radius * cos_a;
2166            let world_z: f32 = -CITY_LOOP_STRAIGHT_HALF_Z - radius * sin_a;
2167            (Vec3::new(world_x, 0.0, world_z), -alpha)
2168        } else if s < 2.0 * straight_len + arc_len {
2169            let east_s: f32 = s - (straight_len + arc_len);
2170            let world_x: f32 = CITY_LOOP_CENTER_X * 2.0 + lateral_u;
2171            let world_z: f32 = -CITY_LOOP_STRAIGHT_HALF_Z + east_s;
2172            (Vec3::new(world_x, 0.0, world_z), PI)
2173        } else {
2174            let beta: f32 = (s - (2.0 * straight_len + arc_len)) / CITY_LOOP_RADIUS;
2175            let radius: f32 = CITY_LOOP_RADIUS + lateral_u;
2176            let (sin_b, cos_b): (f32, f32) = beta.sin_cos();
2177            let world_x: f32 = CITY_LOOP_CENTER_X + radius * cos_b;
2178            let world_z: f32 = CITY_LOOP_STRAIGHT_HALF_Z + radius * sin_b;
2179            (Vec3::new(world_x, 0.0, world_z), PI - beta)
2180        }
2181    }
2182
2183    /// Returns the curated six-palette architectural facade PBR material library used across the metropolitan skyline.
2184    ///
2185    /// # Returns
2186    ///
2187    /// - `[PbrMaterial; 6]` - Six distinct architectural facade palettes with `SurfaceDetailMode::ArchitecturalFacade`.
2188    #[must_use]
2189    fn curated_skyline_palettes() -> [PbrMaterial; 6] {
2190        [
2191            PbrMaterial::pbr(Color::hex(0x9E8C73), 0.24, 0.36, 0.38)
2192                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2193            PbrMaterial::pbr(Color::hex(0x163C6B), 0.78, 0.12, 0.76)
2194                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2195            PbrMaterial::pbr(Color::hex(0x141D2D), 0.86, 0.10, 0.82)
2196                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2197            PbrMaterial::pbr(Color::hex(0x7B4232), 0.20, 0.42, 0.32)
2198                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2199            PbrMaterial::pbr(Color::hex(0x0E4B47), 0.74, 0.14, 0.72)
2200                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2201            PbrMaterial::pbr(Color::hex(0x64748B), 0.82, 0.18, 0.70)
2202                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2203        ]
2204    }
2205
2206    /// Registers all six distinct sculpted architectural building archetype meshes in `World3D::mesh_library`.
2207    ///
2208    /// # Returns
2209    ///
2210    /// - `[usize; 6]` - Registered mesh indices `[art_deco, chamfered, twisted, cantilever, cylinder, boutique]`.
2211    fn register_building_archetypes(&mut self) -> [usize; 6] {
2212        let base_mat: PbrMaterial = PbrMaterial::default();
2213        let art_deco: usize = self.register_mesh(MeshLodChain::from_mesh(
2214            Mesh3D::building_art_deco_tower(CITY_MESH_ART_DECO, base_mat),
2215        ));
2216        let chamfered: usize = self.register_mesh(MeshLodChain::from_mesh(
2217            Mesh3D::building_chamfered_glass_tower(CITY_MESH_CHAMFERED, base_mat),
2218        ));
2219        let twisted: usize = self.register_mesh(MeshLodChain::from_mesh(
2220            Mesh3D::building_twisted_spire_tower(CITY_MESH_TWISTED, base_mat),
2221        ));
2222        let cantilever: usize = self.register_mesh(MeshLodChain::from_mesh(
2223            Mesh3D::building_cantilever_tech_tower(CITY_MESH_CANTILEVER, base_mat),
2224        ));
2225        let cylinder: usize = self.register_mesh(MeshLodChain::from_mesh(
2226            Mesh3D::building_cylindrical_landmark(CITY_MESH_CYLINDER, base_mat),
2227        ));
2228        let boutique: usize = self.register_mesh(MeshLodChain::from_mesh(
2229            Mesh3D::building_boutique_podium_block(CITY_MESH_BOUTIQUE, base_mat),
2230        ));
2231        [art_deco, chamfered, twisted, cantilever, cylinder, boutique]
2232    }
2233
2234    /// Returns the signature metallic clearcoat paint material for a given `HeroVehicleStyle`.
2235    ///
2236    /// # Arguments
2237    ///
2238    /// - `HeroVehicleStyle` - Target hero supercar bodywork style.
2239    ///
2240    /// # Returns
2241    ///
2242    /// - `PbrMaterial` - Signature body clearcoat PBR material.
2243    #[must_use]
2244    pub fn hero_vehicle_material(style: HeroVehicleStyle) -> PbrMaterial {
2245        match style {
2246            HeroVehicleStyle::AventadorV12 => {
2247                PbrMaterial::pbr(Color::hex(0xFF4500), 0.30, 0.12, 0.42)
2248            }
2249            HeroVehicleStyle::ShelbyCobra => {
2250                PbrMaterial::pbr(Color::hex(0x0A3EC2), 0.30, 0.12, 0.40)
2251            }
2252        }
2253    }
2254
2255    /// 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.
2256    ///
2257    /// # Arguments
2258    ///
2259    /// - `&Self` - Mutable world reference.
2260    /// - `HeroVehicleStyle` - Target hero vehicle bodywork archetype.
2261    ///
2262    /// # Returns
2263    ///
2264    /// - `bool` - `true` when the active hero vehicle mesh was updated.
2265    pub fn set_hero_vehicle_style(&mut self, style: HeroVehicleStyle) -> bool {
2266        let Some(car_idx) = self.vehicle_index() else {
2267            self.set_hero_vehicle_style_raw(style);
2268            return false;
2269        };
2270        let slot_idx: usize = match style {
2271            HeroVehicleStyle::AventadorV12 => 0,
2272            HeroVehicleStyle::ShelbyCobra => 1,
2273        };
2274        let cached_entry: Option<(usize, PbrMaterial)> = {
2275            let Self {
2276                hero_vehicle_meshes,
2277                ..
2278            } = self;
2279            hero_vehicle_meshes[slot_idx]
2280        };
2281        let (target_mesh_id, target_mat): (usize, PbrMaterial) = if let Some(pair) = cached_entry {
2282            pair
2283        } else {
2284            let sig_mat: PbrMaterial = Self::hero_vehicle_material(style);
2285            let built_mesh: Mesh3D = match style {
2286                HeroVehicleStyle::AventadorV12 => {
2287                    Mesh3D::aventador_svj(CITY_MESH_AVENTADOR, sig_mat)
2288                }
2289                HeroVehicleStyle::ShelbyCobra => Mesh3D::shelby_cobra(CITY_MESH_SHELBY, sig_mat),
2290            };
2291            let new_mesh_id: usize = self.register_mesh(MeshLodChain::single_level(built_mesh));
2292            let Self {
2293                hero_vehicle_meshes,
2294                ..
2295            } = self;
2296            hero_vehicle_meshes[slot_idx] = Some((new_mesh_id, sig_mat));
2297            (new_mesh_id, sig_mat)
2298        };
2299        let already_active: bool = self.get_hero_vehicle_style() == style
2300            && self
2301                .get_objects()
2302                .get(car_idx)
2303                .is_some_and(|obj: &SceneObject3D| obj.get_mesh_id() == target_mesh_id);
2304        if already_active {
2305            return false;
2306        }
2307        let new_local_bounds: AxisAlignedBox3D = self
2308            .get_mesh_library()
2309            .get(target_mesh_id)
2310            .and_then(|chain: &MeshLodChain| chain.get_levels().first())
2311            .map(Mesh3D::get_bounds)
2312            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.2), Vec3::splat(1.2)));
2313        if let Some(car_obj) = self.get_mut_objects().get_mut(car_idx) {
2314            let live_tr: Transform3D = car_obj.get_transform();
2315            car_obj.set_mesh_id(target_mesh_id);
2316            car_obj.set_material(target_mat);
2317            car_obj.set_world_bounds(live_tr.transform_bounds(new_local_bounds));
2318        }
2319        self.set_hero_vehicle_style_raw(style);
2320        self.set_dynamic_topology_dirty(true);
2321        self.set_dynamic_bvh_dirty(true);
2322        self.sync_dynamic_ray_instances();
2323        self.bump_world_revision();
2324        true
2325    }
2326
2327    /// Updates the stored `hero_vehicle_style` enum tag cleanly via Lombok setter.
2328    ///
2329    /// # Arguments
2330    ///
2331    /// - `&Self` - Mutable world reference.
2332    /// - `HeroVehicleStyle` - New active hero vehicle style.
2333    fn set_hero_vehicle_style_raw(&mut self, style: HeroVehicleStyle) {
2334        let Self {
2335            hero_vehicle_style, ..
2336        } = self;
2337        *hero_vehicle_style = style;
2338    }
2339
2340    /// 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, continuous zero-teleport AI traffic, and selectable Aventador SVJ / Shelby GT500 Cobra hero supercars.
2341    ///
2342    /// # Returns
2343    ///
2344    /// - `Self` - Populated open-world 3D coastal city ready for real-time PBR + Ray Tracing.
2345    #[must_use]
2346    pub fn create_open_world_city() -> Self {
2347        let mut world: Self = Self::default();
2348        let ground_w: f32 = CITY_GROUND_X_MAX - CITY_GROUND_X_MIN;
2349        let ground_d: f32 = CITY_GROUND_Z_MAX - CITY_GROUND_Z_MIN;
2350        let ground_cx: f32 = (CITY_GROUND_X_MIN + CITY_GROUND_X_MAX) * 0.5;
2351        let ground_cz: f32 = (CITY_GROUND_Z_MIN + CITY_GROUND_Z_MAX) * 0.5;
2352        let asphalt_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0E131C), 0.08, 0.24, 0.62)
2353            .with_surface_detail(SurfaceDetailMode::RoadSurface);
2354        let road_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::ground_plane(
2355            CITY_GROUND_MESH_NAME,
2356            ground_w,
2357            ground_d,
2358            24,
2359            asphalt_mat,
2360        )));
2361        let _: usize = world.spawn_object(
2362            CITY_GROUND_OBJ_NAME,
2363            road_mesh,
2364            Transform3D::new(Vec3::new(ground_cx, 0.0, ground_cz), 0.0, Vec3::splat(1.0)),
2365            asphalt_mat,
2366            false,
2367        );
2368        let ocean_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x063846), 0.05, 0.06, 0.86)
2369            .with_surface_detail(SurfaceDetailMode::OceanWater);
2370        let ocean_mesh: usize =
2371            world.register_mesh(MeshLodChain::from_mesh(Mesh3D::coastal_ocean_ring(
2372                CITY_OCEAN_MESH_NAME,
2373                CITY_OCEAN_SPAN_M,
2374                ground_w * 0.5,
2375                ground_d * 0.5,
2376                24,
2377                ocean_mat,
2378            )));
2379        let _: usize = world.spawn_object(
2380            CITY_OCEAN_MESH_NAME,
2381            ocean_mesh,
2382            Transform3D::new(
2383                Vec3::new(ground_cx, CITY_OCEAN_SURFACE_Y, ground_cz),
2384                0.0,
2385                Vec3::splat(1.0),
2386            ),
2387            ocean_mat,
2388            false,
2389        );
2390        let stud_mat: PbrMaterial = PbrMaterial::neon(Color::hex(0xFBBF24), 0.90);
2391        let stud_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2392            CITY_LANE_STUD_MESH_NAME,
2393            0.10,
2394            0.018,
2395            0.16,
2396            true,
2397            stud_mat,
2398        )));
2399        for iz in -7..=0 {
2400            let _: usize = world.spawn_object(
2401                &format!("stripe_{iz}"),
2402                stud_mesh,
2403                Transform3D::new(
2404                    Vec3::new(0.0, 0.008, (iz as f32) * 14.0),
2405                    0.0,
2406                    Vec3::splat(1.0),
2407                ),
2408                stud_mat,
2409                false,
2410            );
2411        }
2412        let unit_box: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2413            CITY_UNIT_BOX_MESH_NAME,
2414            1.0,
2415            1.0,
2416            1.0,
2417            true,
2418            PbrMaterial::default(),
2419        )));
2420        let neon_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2421            CITY_NEON_SIGN_MESH_NAME,
2422            1.0,
2423            1.0,
2424            1.0,
2425            true,
2426            PbrMaterial::neon(Color::hex(0x38BDF8), 1.8),
2427        )));
2428        let archetypes: [usize; 6] = world.register_building_archetypes();
2429        let palettes: [PbrMaterial; 6] = Self::curated_skyline_palettes();
2430        let neon_colors: [Color; 4] = [
2431            Color::hex(0x38BDF8),
2432            Color::hex(0xF43F5E),
2433            Color::hex(0xA855F7),
2434            Color::hex(0x34D399),
2435        ];
2436        let west_pattern: [(usize, f32, f32, f32); 9] = [
2437            (0, 46.0, 11.2, 12.0),
2438            (5, 20.0, 11.6, 12.4),
2439            (1, 38.0, 11.0, 11.8),
2440            (3, 34.0, 10.6, 11.8),
2441            (4, 48.0, 11.4, 11.4),
2442            (5, 22.0, 11.4, 12.2),
2443            (2, 54.0, 11.2, 11.2),
2444            (1, 40.0, 10.8, 12.0),
2445            (0, 44.0, 11.0, 11.6),
2446        ];
2447        let mut idx_counter: usize = 0;
2448        for side in [-1.0_f32, 1.0_f32] {
2449            for (row_i, row_z_idx) in (-4..=4_i32).enumerate() {
2450                let (base_arch, base_h, width_val, depth_val): (usize, f32, f32, f32) =
2451                    west_pattern[(row_i + if side > 0.0 { 2 } else { 0 }) % west_pattern.len()];
2452                let pos_z: f32 = (row_z_idx as f32) * 28.0 - 4.0;
2453                let pos_x: f32 = side * (22.0 + ((idx_counter % 3) as f32) * 1.1);
2454                let height_val: f32 = if side > 0.0 && base_arch != 5 {
2455                    base_h + 4.0
2456                } else {
2457                    base_h
2458                };
2459                let mat: PbrMaterial = palettes[(idx_counter * 5 + row_i) % palettes.len()];
2460                let _: usize = world.spawn_object(
2461                    &format!("tower_{idx_counter}"),
2462                    archetypes[base_arch],
2463                    Transform3D::new(
2464                        Vec3::new(pos_x, 0.0, pos_z),
2465                        0.0,
2466                        Vec3::new(width_val, height_val, depth_val),
2467                    ),
2468                    mat,
2469                    true,
2470                );
2471                idx_counter += 1;
2472            }
2473        }
2474        let inner_spine_specs: [(f32, f32, f32, f32, f32, usize, usize); 19] = [
2475            (64.0, -158.0, 14.0, 56.0, 14.0, 4, 1),
2476            (64.0, -116.0, 14.5, 68.0, 14.5, 0, 0),
2477            (54.0, -76.0, 13.0, 62.0, 13.0, 2, 2),
2478            (76.0, -76.0, 13.0, 52.0, 13.0, 1, 4),
2479            (64.0, -34.0, 15.0, 74.0, 15.0, 2, 5),
2480            (52.0, 10.0, 13.5, 58.0, 13.5, 3, 3),
2481            (78.0, 12.0, 13.5, 64.0, 13.5, 4, 1),
2482            (64.0, 56.0, 14.5, 70.0, 14.5, 0, 0),
2483            (54.0, 98.0, 13.0, 54.0, 13.0, 1, 2),
2484            (76.0, 100.0, 13.0, 48.0, 13.0, 3, 4),
2485            (64.0, 156.0, 14.0, 58.0, 14.0, 4, 5),
2486            (103.5, -112.0, 11.4, 34.0, 12.4, 5, 0),
2487            (103.5, -78.0, 11.6, 48.0, 11.6, 4, 4),
2488            (103.5, -44.0, 11.4, 24.0, 12.2, 5, 3),
2489            (103.5, -10.0, 11.8, 44.0, 12.0, 1, 1),
2490            (103.5, 24.0, 11.4, 38.0, 12.0, 3, 5),
2491            (103.5, 58.0, 11.6, 22.0, 12.2, 5, 0),
2492            (103.5, 92.0, 11.8, 46.0, 11.8, 0, 2),
2493            (103.5, 124.0, 11.4, 40.0, 11.4, 2, 4),
2494        ];
2495        for (l_idx, &(lx, lz, lw, lh, ld, l_arch, l_pal)) in inner_spine_specs.iter().enumerate() {
2496            let _: usize = world.spawn_object(
2497                &format!("landmark_tower_{l_idx}"),
2498                archetypes[l_arch],
2499                Transform3D::new(Vec3::new(lx, 0.0, lz), 0.0, Vec3::new(lw, lh, ld)),
2500                palettes[l_pal],
2501                true,
2502            );
2503        }
2504        let skyline_specs: [(f32, f32, f32, f32, usize, usize); 6] = [
2505            (-46.0, -96.0, 13.0, 56.0, 0, 2),
2506            (-46.0, -64.0, 12.5, 66.0, 2, 1),
2507            (-46.0, -32.0, 13.0, 52.0, 4, 4),
2508            (-46.0, 4.0, 12.5, 62.0, 1, 5),
2509            (-46.0, 40.0, 12.5, 50.0, 3, 3),
2510            (-46.0, 76.0, 13.0, 58.0, 0, 0),
2511        ];
2512        for (sky_idx, &(sx, sz, sw, sh, s_arch, s_pal)) in skyline_specs.iter().enumerate() {
2513            let _: usize = world.spawn_object(
2514                &format!("{CITY_SKYLINE_MESH_NAME}_{sky_idx}"),
2515                archetypes[s_arch],
2516                Transform3D::new(Vec3::new(sx, 0.0, sz), 0.0, Vec3::new(sw, sh, 13.0)),
2517                palettes[s_pal],
2518                true,
2519            );
2520        }
2521        let mut rim_serial: usize = 0;
2522        let rim_angles_deg: [f32; 7] = [44.0, 64.0, 84.0, 104.0, 124.0, 144.0, 164.0];
2523        for (turn_idx, &turn_sign_z) in [-1.0_f32, 1.0_f32].iter().enumerate() {
2524            let center_z: f32 = turn_sign_z * CITY_LOOP_STRAIGHT_HALF_Z;
2525            for (ang_i, &deg) in rim_angles_deg.iter().enumerate() {
2526                let rad: f32 = deg.to_radians();
2527                let (sin_a, cos_a): (f32, f32) = rad.sin_cos();
2528                let ring_r: f32 = 94.0 + ((ang_i % 2) as f32) * 3.5;
2529                let rx: f32 = CITY_LOOP_CENTER_X + ring_r * cos_a;
2530                let rz: f32 = center_z + turn_sign_z * ring_r * sin_a;
2531                let yaw_rim: f32 = if turn_sign_z < 0.0 {
2532                    rad - FRAC_PI_2
2533                } else {
2534                    FRAC_PI_2 - rad
2535                };
2536                let arch_i: usize = (rim_serial + turn_idx * 2) % archetypes.len();
2537                let height_m: f32 = if arch_i == 5 {
2538                    24.0
2539                } else {
2540                    36.0 + ((rim_serial * 7) % 4) as f32 * 8.0
2541                };
2542                let _: usize = world.spawn_object(
2543                    &format!("rim_tower_{rim_serial}"),
2544                    archetypes[arch_i],
2545                    Transform3D::new(
2546                        Vec3::new(rx, 0.0, rz),
2547                        yaw_rim,
2548                        Vec3::new(11.5, height_m, 11.5),
2549                    ),
2550                    palettes[(rim_serial + 1) % palettes.len()],
2551                    true,
2552                );
2553                rim_serial += 1;
2554            }
2555        }
2556        let seawall_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x475569), 0.14, 0.56, 0.22);
2557        let mut wall_serial: usize = 0;
2558        let _: usize = world.spawn_object(
2559            &format!("{CITY_SEAWALL_MESH_NAME}_{wall_serial}"),
2560            unit_box,
2561            Transform3D::new(
2562                Vec3::new(142.8, 0.0, 0.0),
2563                0.0,
2564                Vec3::new(2.4, 1.15, CITY_LOOP_STRAIGHT_HALF_Z * 2.0 + 4.0),
2565            ),
2566            seawall_mat,
2567            true,
2568        );
2569        wall_serial += 1;
2570        for &turn_sign_z in [-1.0_f32, 1.0_f32].iter() {
2571            let center_z: f32 = turn_sign_z * CITY_LOOP_STRAIGHT_HALF_Z;
2572            let seg_count: usize = 10;
2573            for seg_i in 0..seg_count {
2574                let deg: f32 = 3.0 + (seg_i as f32) * 6.0;
2575                let rad: f32 = deg.to_radians();
2576                let (sin_a, cos_a): (f32, f32) = rad.sin_cos();
2577                let wall_r: f32 = 79.0;
2578                let wx: f32 = CITY_LOOP_CENTER_X + wall_r * cos_a;
2579                let wz: f32 = center_z + turn_sign_z * wall_r * sin_a;
2580                let wall_yaw: f32 = if turn_sign_z < 0.0 { rad } else { -rad };
2581                let _: usize = world.spawn_object(
2582                    &format!("{CITY_SEAWALL_MESH_NAME}_{wall_serial}"),
2583                    unit_box,
2584                    Transform3D::new(Vec3::new(wx, 0.0, wz), wall_yaw, Vec3::new(2.2, 1.15, 10.6)),
2585                    seawall_mat,
2586                    true,
2587                );
2588                wall_serial += 1;
2589            }
2590        }
2591        let palm_mesh: usize = world.register_mesh(MeshLodChain::single_level(Mesh3D::palm_tree(
2592            CITY_PALM_MESH_NAME,
2593        )));
2594        let palm_bark_mat: PbrMaterial = PbrMaterial::dielectric(Color::hex(0x4E392B), 0.88);
2595        let palm_z_positions: [f32; 6] = [-102.0, -74.0, -46.0, -18.0, 10.0, 38.0];
2596        for (palm_row, &palm_z) in palm_z_positions.iter().enumerate() {
2597            for side_idx in 0..2usize {
2598                let side_sign: f32 = if side_idx == 0 { -1.0 } else { 1.0 };
2599                let yaw_palm: f32 = (palm_row as f32) * 0.95
2600                    + (side_idx as f32) * 2.1
2601                    + if side_idx == 0 { 0.35 } else { -0.35 };
2602                let scale_palm: f32 = 0.94 + ((palm_row + side_idx) % 3) as f32 * 0.08;
2603                let _: usize = world.spawn_object(
2604                    &format!("palm_{palm_row}_{side_idx}"),
2605                    palm_mesh,
2606                    Transform3D::new(
2607                        Vec3::new(side_sign * 12.0, 0.0, palm_z),
2608                        yaw_palm,
2609                        Vec3::splat(scale_palm),
2610                    ),
2611                    palm_bark_mat,
2612                    true,
2613                );
2614            }
2615        }
2616        for coast_i in 0..10usize {
2617            let cz: f32 = -124.0 + (coast_i as f32) * 27.5;
2618            let yaw_p: f32 = (coast_i as f32) * 0.72 + 1.2;
2619            let scale_p: f32 = 0.96 + (coast_i % 3) as f32 * 0.07;
2620            let _: usize = world.spawn_object(
2621                &format!("waterfront_palm_{coast_i}"),
2622                palm_mesh,
2623                Transform3D::new(Vec3::new(139.8, 0.0, cz), yaw_p, Vec3::splat(scale_p)),
2624                palm_bark_mat,
2625                true,
2626            );
2627        }
2628        let arch_frame_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0F172A), 0.82, 0.18, 0.60);
2629        for (arch_idx, &arch_z) in [-36.0_f32, -80.0_f32, 48.0_f32].iter().enumerate() {
2630            let arch_neon: PbrMaterial =
2631                PbrMaterial::neon(neon_colors[arch_idx % neon_colors.len()], 2.1);
2632            let _: usize = world.spawn_object(
2633                &format!("arch_beam_{arch_idx}"),
2634                unit_box,
2635                Transform3D::new(
2636                    Vec3::new(0.0, 13.4, arch_z),
2637                    0.0,
2638                    Vec3::new(23.0, 0.58, 0.72),
2639                ),
2640                arch_frame_mat,
2641                true,
2642            );
2643            let _: usize = world.spawn_object(
2644                &format!("arch_glow_{arch_idx}"),
2645                neon_unit,
2646                Transform3D::new(
2647                    Vec3::new(0.0, 13.08, arch_z),
2648                    0.0,
2649                    Vec3::new(21.2, 0.24, 0.34),
2650                ),
2651                arch_neon,
2652                true,
2653            );
2654            for side in [-1.0_f32, 1.0_f32] {
2655                let _: usize = world.spawn_object(
2656                    &format!("arch_pillar_{arch_idx}_{}", if side < 0.0 { 0 } else { 1 }),
2657                    unit_box,
2658                    Transform3D::new(
2659                        Vec3::new(side * 11.2, 0.0, arch_z),
2660                        0.0,
2661                        Vec3::new(0.58, 13.4, 0.68),
2662                    ),
2663                    arch_frame_mat,
2664                    true,
2665                );
2666            }
2667        }
2668        let aventador_mat: PbrMaterial =
2669            Self::hero_vehicle_material(HeroVehicleStyle::AventadorV12);
2670        let shelby_mat: PbrMaterial = Self::hero_vehicle_material(HeroVehicleStyle::ShelbyCobra);
2671        let aventador_mesh: usize = world.register_mesh(MeshLodChain::single_level(
2672            Mesh3D::aventador_svj(CITY_MESH_AVENTADOR, aventador_mat),
2673        ));
2674        let shelby_mesh: usize = world.register_mesh(MeshLodChain::single_level(
2675            Mesh3D::shelby_cobra(CITY_MESH_SHELBY, shelby_mat),
2676        ));
2677        {
2678            let Self {
2679                hero_vehicle_meshes,
2680                ..
2681            } = &mut world;
2682            hero_vehicle_meshes[0] = Some((aventador_mesh, aventador_mat));
2683            hero_vehicle_meshes[1] = Some((shelby_mesh, shelby_mat));
2684        }
2685        let car_idx: usize = world.spawn_object(
2686            CITY_OBJ_PLAYER_CAR,
2687            aventador_mesh,
2688            Transform3D::new(Vec3::new(0.0, 0.0, 0.0), 0.0, Vec3::splat(1.1)),
2689            aventador_mat,
2690            true,
2691        );
2692        let _: bool = world.set_object_dynamic(car_idx, true);
2693        world.set_player_vehicle_index(Some(car_idx));
2694        let _: usize = world.add_point_light(PointLight3D::new(
2695            Vec3::new(0.0, 0.95, 2.9),
2696            Color::hex(0xFF1744),
2697            1.85,
2698            8.5,
2699        ));
2700        let traffic_specs: [(f32, f32, f32, usize, Color); 4] = [
2701            (156.0, 5.6, -11.5, shelby_mesh, Color::hex(0x38BDF8)),
2702            (620.0, 5.6, -11.5, aventador_mesh, Color::hex(0xA855F7)),
2703            (164.0, -5.6, 13.0, aventador_mesh, Color::hex(0x22C55E)),
2704            (645.0, -5.6, 13.0, shelby_mesh, Color::hex(0xF59E0B)),
2705        ];
2706        for (t_idx, &(start_s, lane_u, speed_mps, t_mesh, t_col)) in
2707            traffic_specs.iter().enumerate()
2708        {
2709            let (t_pos, base_yaw): (Vec3, f32) = Self::loop_pose_at(start_s, lane_u);
2710            let face_yaw: f32 = if speed_mps >= 0.0 {
2711                base_yaw
2712            } else {
2713                base_yaw + PI
2714            };
2715            let tmat: PbrMaterial = PbrMaterial::pbr(t_col, 0.84, 0.13, 0.76);
2716            let obj_id: usize = world.spawn_object(
2717                &format!("ai_traffic_{t_idx}"),
2718                t_mesh,
2719                Transform3D::new(t_pos, face_yaw, Vec3::splat(1.04)),
2720                tmat,
2721                true,
2722            );
2723            let _: bool = world.set_object_dynamic(obj_id, true);
2724            let Self {
2725                traffic_vehicles, ..
2726            } = &mut world;
2727            traffic_vehicles.push((obj_id, start_s, lane_u, speed_mps));
2728        }
2729        let lamp_palette: [Color; 4] = [
2730            Color::hex(0x38BDF8),
2731            Color::hex(0xF43F5E),
2732            Color::hex(0xA855F7),
2733            Color::hex(0x34D399),
2734        ];
2735        let lamp_z_rows: [f32; 4] = [-62.0, -26.0, 18.0, 66.0];
2736        for lamp_idx in 0..8usize {
2737            let side: f32 = if lamp_idx % 2 == 0 { -1.0 } else { 1.0 };
2738            let z_pos: f32 = lamp_z_rows[lamp_idx / 2];
2739            let lamp_color: Color = lamp_palette[lamp_idx % lamp_palette.len()];
2740            let _: usize = world.spawn_object(
2741                &format!("lamp_pole_{lamp_idx}"),
2742                unit_box,
2743                Transform3D::new(
2744                    Vec3::new(side * 10.65, 0.0, z_pos),
2745                    0.0,
2746                    Vec3::new(0.20, 6.2, 0.20),
2747                ),
2748                arch_frame_mat,
2749                true,
2750            );
2751            let _: usize = world.spawn_object(
2752                &format!("lamp_head_{lamp_idx}"),
2753                neon_unit,
2754                Transform3D::new(
2755                    Vec3::new(side * 10.15, 6.2, z_pos),
2756                    0.0,
2757                    Vec3::new(1.1, 0.18, 0.28),
2758                ),
2759                PbrMaterial::neon(lamp_color, 2.2),
2760                true,
2761            );
2762            let _: usize = world.add_point_light(PointLight3D::new(
2763                Vec3::new(side * 9.8, 6.2, z_pos),
2764                lamp_color,
2765                2.35,
2766                16.5,
2767            ));
2768        }
2769        let _: usize = world.add_spot_light(SpotLight3D::new(
2770            Vec3::new(-0.85, 0.95, -2.2),
2771            Vec3::new(0.0, -0.14, -1.0),
2772            Color::hex(0xFEF3C7),
2773            2.8,
2774            24.0,
2775            (14.0, 26.0),
2776        ));
2777        let _: usize = world.add_spot_light(SpotLight3D::new(
2778            Vec3::new(0.85, 0.95, -2.2),
2779            Vec3::new(0.0, -0.14, -1.0),
2780            Color::hex(0xFEF3C7),
2781            2.8,
2782            24.0,
2783            (14.0, 26.0),
2784        ));
2785        world.set_camera(Camera3D {
2786            position: Vec3::new(0.0, 4.15, 9.2),
2787            yaw: -FRAC_PI_2,
2788            pitch: -0.145,
2789            fov_deg: 60.0,
2790            near: 0.3,
2791            far: 560.0,
2792        });
2793        world.ensure_bvh();
2794        world
2795    }
2796
2797    /// Returns the number of autonomous cruising traffic vehicles registered in this world.
2798    ///
2799    /// # Returns
2800    ///
2801    /// - `usize` - Active cruising traffic vehicle count.
2802    #[must_use]
2803    pub fn traffic_vehicle_count(&self) -> usize {
2804        let Self {
2805            traffic_vehicles, ..
2806        } = self;
2807        traffic_vehicles.len()
2808    }
2809
2810    /// Applies an atmospheric mood preset (`0=Sunset, 1=RainyNight, 2=Noon, 3=Midnight`), updating sun lighting and ambient Niagara rain streaks.
2811    ///
2812    /// # Arguments
2813    ///
2814    /// - `u8` - Atmosphere preset index (`0..=3`).
2815    ///
2816    /// # Returns
2817    ///
2818    /// - `f32` - Corresponding time-of-day hour in `[0.0, 24.0]`.
2819    pub fn apply_atmosphere_preset(&mut self, preset: u8) -> f32 {
2820        let clamped: u8 = preset.min(3);
2821        let hour: f32 = match clamped {
2822            1 => ATMOSPHERE_HOUR_RAINY_NIGHT,
2823            2 => ATMOSPHERE_HOUR_NOON,
2824            3 => ATMOSPHERE_HOUR_MIDNIGHT,
2825            _ => ATMOSPHERE_HOUR_SUNSET,
2826        };
2827        self.set_atmosphere_preset(clamped);
2828        let sun_light: DirectionalLight3D = match clamped {
2829            1 => DirectionalLight3D {
2830                direction: Vec3::new(-0.32, 0.48, -0.82).normalize(),
2831                color: Vec3::new(0.56, 0.78, 1.24),
2832                sky_zenith: Vec3::new(0.015, 0.038, 0.105),
2833                sky_horizon: Vec3::new(0.078, 0.155, 0.275),
2834                time_of_day: hour,
2835            },
2836            3 => DirectionalLight3D {
2837                direction: Vec3::new(-0.42, 0.62, -0.66).normalize(),
2838                color: Vec3::new(0.36, 0.34, 0.88),
2839                sky_zenith: Vec3::new(0.007, 0.005, 0.024),
2840                sky_horizon: Vec3::new(0.135, 0.036, 0.215),
2841                time_of_day: hour,
2842            },
2843            _ => DirectionalLight3D::from_time_of_day(hour),
2844        };
2845        self.set_sun(sun_light);
2846        if clamped == 1 && self.get_niagara().get_active_count() < RAINY_NIGHT_MAX_PARTICLES {
2847            let cam_pos: Vec3 = self.get_camera().get_position();
2848            let mut rain_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
2849            rain_cfg.set_origin(cam_pos.add(Vec3::new(0.0, 4.5, -14.0)));
2850            rain_cfg.set_base_velocity(Vec3::new(-0.4, -17.0, 0.3));
2851            rain_cfg.set_velocity_spread(2.4);
2852            rain_cfg.set_start_color(Color::rgba(175, 222, 255, 165));
2853            rain_cfg.set_end_color(Color::rgba(92, 162, 235, 42));
2854            rain_cfg.set_start_size_m(0.042);
2855            rain_cfg.set_end_size_m(0.016);
2856            rain_cfg.set_min_lifetime(0.55);
2857            rain_cfg.set_max_lifetime(0.95);
2858            rain_cfg.set_emissive_boost(0.85);
2859            self.get_mut_niagara().emit_burst(8, &rain_cfg);
2860        }
2861        self.bump_world_revision();
2862        hour
2863    }
2864
2865    /// Registers a dynamic `PointLight3D` into this world for UE5 Clustered Deferred Lighting and returns its index.
2866    ///
2867    /// # Arguments
2868    ///
2869    /// - `PointLight3D` - World-space point light descriptor.
2870    ///
2871    /// # Returns
2872    ///
2873    /// - `usize` - Assigned point light index.
2874    pub fn add_point_light(&mut self, light: PointLight3D) -> usize {
2875        let light_idx: usize = self.get_point_lights().len();
2876        self.get_mut_point_lights().push(light);
2877        self.bump_world_revision();
2878        light_idx
2879    }
2880
2881    /// Registers a dynamic `SpotLight3D` into this world for UE5 Clustered Deferred Lighting and returns its index.
2882    ///
2883    /// # Arguments
2884    ///
2885    /// - `SpotLight3D` - World-space spotlight descriptor.
2886    ///
2887    /// # Returns
2888    ///
2889    /// - `usize` - Assigned spotlight index.
2890    pub fn add_spot_light(&mut self, light: SpotLight3D) -> usize {
2891        let light_idx: usize = self.get_spot_lights().len();
2892        self.get_mut_spot_lights().push(light);
2893        self.bump_world_revision();
2894        light_idx
2895    }
2896
2897    /// Clears all dynamic local point and spot lights from this world.
2898    pub fn clear_local_lights(&mut self) {
2899        self.get_mut_point_lights().clear();
2900        self.get_mut_spot_lights().clear();
2901        self.bump_world_revision();
2902    }
2903
2904    /// Emits `count` 3D particles into the world's `NiagaraSystem3D` with zero heap allocations.
2905    ///
2906    /// # Arguments
2907    ///
2908    /// - `&NiagaraEmitterConfig3D` - Emitter properties.
2909    /// - `usize` - Number of particles to emit.
2910    ///
2911    /// # Returns
2912    ///
2913    /// - `usize` - Active particle count after emission.
2914    pub fn emit_particles_3d(&mut self, config: &NiagaraEmitterConfig3D, count: usize) -> usize {
2915        self.get_mut_niagara().emit_burst(count, config);
2916        let active: usize = self.get_niagara().get_active_count();
2917        if count > 0 {
2918            self.bump_world_revision();
2919        }
2920        active
2921    }
2922
2923    /// 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.
2924    ///
2925    /// # Arguments
2926    ///
2927    /// - `i32` - City block half-radius (`1..=5`, producing `(2r+1)x(2r+1)` multi-tower blocks).
2928    ///
2929    /// # Returns
2930    ///
2931    /// - `Self` - Populated dense 3D open-world metropolis with built static/dynamic BVHs.
2932    #[must_use]
2933    pub fn create_dense_open_world_city(blocks_radius: i32) -> Self {
2934        let radius: i32 = blocks_radius.clamp(1, 5);
2935        let mut world: Self = Self::create_open_world_city();
2936        let dense_occluder: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2937            DENSE_TOWER_MESH_NAME,
2938            1.0,
2939            1.0,
2940            1.0,
2941            true,
2942            PbrMaterial::default(),
2943        )));
2944        let archetypes: [usize; 6] = world.register_building_archetypes();
2945        let facades: [PbrMaterial; 6] = Self::curated_skyline_palettes();
2946        let neon_palette: [Color; 4] = [
2947            Color::hex(0x38BDF8),
2948            Color::hex(0xF43F5E),
2949            Color::hex(0xA855F7),
2950            Color::hex(0x34D399),
2951        ];
2952        let mut serial: usize = 0;
2953        for bx in -radius..=radius {
2954            for bz in -radius..=radius {
2955                if bx == 0 && (-3..=3).contains(&bz) {
2956                    continue;
2957                }
2958                let center_x: f32 = (bx as f32) * 26.0;
2959                let center_z: f32 = (bz as f32) * 24.0 - 16.0;
2960                for sub in 0..4usize {
2961                    let off_x: f32 = if (sub & 1) == 0 { -5.5 } else { 5.5 };
2962                    let off_z: f32 = if (sub & 2) == 0 { -5.5 } else { 5.5 };
2963                    let px: f32 = center_x + off_x;
2964                    let pz: f32 = center_z + off_z;
2965                    let (d_spine, _): (f32, f32) = Self::loop_lateral_offset(px, pz);
2966                    if (49.0..=79.0).contains(&d_spine) || px > 134.0 {
2967                        continue;
2968                    }
2969                    let height_m: f32 = 16.0 + (((serial * 11 + sub * 7) % 6) as f32) * 8.0;
2970                    let width_m: f32 = 8.0 + ((serial % 3) as f32) * 1.4;
2971                    let mat: PbrMaterial = facades[serial % facades.len()];
2972                    let mesh_id: usize = if sub % 2 == 0 {
2973                        dense_occluder
2974                    } else {
2975                        archetypes[(serial + sub) % archetypes.len()]
2976                    };
2977                    let _: usize = world.spawn_object(
2978                        &format!("dense_bldg_{serial}"),
2979                        mesh_id,
2980                        Transform3D::new(
2981                            Vec3::new(px, 0.0, pz),
2982                            0.0,
2983                            Vec3::new(width_m, height_m, 9.0),
2984                        ),
2985                        mat,
2986                        true,
2987                    );
2988                    serial += 1;
2989                }
2990                if (bx + bz).abs() <= 2 && world.get_point_lights().len() < 32 {
2991                    let _: usize = world.add_point_light(PointLight3D::new(
2992                        Vec3::new(center_x, 7.0, center_z),
2993                        neon_palette[serial % neon_palette.len()],
2994                        4.5,
2995                        22.0,
2996                    ));
2997                }
2998            }
2999        }
3000        world.ensure_bvh();
3001        world
3002    }
3003
3004    /// Cycles the active 3D camera perspective (`Chase` -> `Hood` -> `Orbit` -> `Aerial`) safely without clipping.
3005    ///
3006    /// # Arguments
3007    ///
3008    /// - `&Self` - Mutable world.
3009    ///
3010    /// # Returns
3011    ///
3012    /// - `u8` - New active camera mode index.
3013    pub fn cycle_camera_mode(&mut self) -> u8 {
3014        let next: u8 = (self.get_camera_mode() + 1) % 4;
3015        self.set_camera_mode(next);
3016        next
3017    }
3018
3019    /// Computes horizontal playable world bounds from non-solid ground meshes when present, preventing hardcoded invisible walls.
3020    ///
3021    /// # Arguments
3022    ///
3023    /// - `&Self` - World reference.
3024    ///
3025    /// # Returns
3026    ///
3027    /// - `Option<(f32, f32, f32, f32)>` - `(min_x, max_x, min_z, max_z)` horizontal ground limits.
3028    #[must_use]
3029    pub fn ground_play_bounds(&self) -> Option<(f32, f32, f32, f32)> {
3030        let mut found: bool = false;
3031        let mut min_x: f32 = f32::INFINITY;
3032        let mut max_x: f32 = f32::NEG_INFINITY;
3033        let mut min_z: f32 = f32::INFINITY;
3034        let mut max_z: f32 = f32::NEG_INFINITY;
3035        for obj in self.get_objects().iter() {
3036            if obj.get_ray_trace_caster()
3037                || obj.get_material().get_surface_detail() == SurfaceDetailMode::OceanWater
3038            {
3039                continue;
3040            }
3041            let blue_val: AxisAlignedBox3D = obj.get_world_bounds();
3042            let span_x: f32 = blue_val.get_max().get_x() - blue_val.get_min().get_x();
3043            let span_z: f32 = blue_val.get_max().get_z() - blue_val.get_min().get_z();
3044            if span_x >= 16.0 && span_z >= 16.0 {
3045                min_x = min_x.min(blue_val.get_min().get_x());
3046                max_x = max_x.max(blue_val.get_max().get_x());
3047                min_z = min_z.min(blue_val.get_min().get_z());
3048                max_z = max_z.max(blue_val.get_max().get_z());
3049                found = true;
3050            }
3051        }
3052        if found {
3053            Some((min_x, max_x, min_z, max_z))
3054        } else {
3055            None
3056        }
3057    }
3058
3059    /// 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.
3060    ///
3061    /// # Arguments
3062    ///
3063    /// - `&Self` - World reference.
3064    /// - `OrientedBox3D` - Candidate oriented bounding box in world space.
3065    /// - `Option<usize>` - Optional scene object index to exclude (self).
3066    ///
3067    /// # Returns
3068    ///
3069    /// - `Option<MeshCollisionHit3D>` - Deepest real-mesh triangle or closed-volume collision contact, or `None` when clear.
3070    #[must_use]
3071    pub fn mesh_oriented_box_collision(
3072        &self,
3073        candidate: OrientedBox3D,
3074        ignore_idx: Option<usize>,
3075    ) -> Option<MeshCollisionHit3D> {
3076        let query_bounds: AxisAlignedBox3D = candidate.to_world_bounds();
3077        let mut deepest: Option<MeshCollisionHit3D> = None;
3078        let objects: &[SceneObject3D] = self.get_objects().as_slice();
3079        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
3080        for (idx, obj) in objects.iter().enumerate() {
3081            if ignore_idx == Some(idx) || !(obj.get_solid_collider() || obj.get_ray_trace_caster())
3082            {
3083                continue;
3084            }
3085            let obj_bounds: AxisAlignedBox3D = obj.get_world_bounds();
3086            if !Self::boxes_overlap(query_bounds, obj_bounds) {
3087                continue;
3088            }
3089            let Some(mesh) = mesh_lib
3090                .get(obj.get_mesh_id())
3091                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
3092            else {
3093                continue;
3094            };
3095            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
3096            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
3097            let obj_tr: Transform3D = obj.get_transform();
3098            let model_mat: Mat4 = obj_tr.to_mat4();
3099            let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
3100            let mut hit_this_obj: bool = false;
3101            if meshlets.is_empty() {
3102                for tri in indices.iter() {
3103                    let (i0, i1, i2): (usize, usize, usize) =
3104                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
3105                    if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
3106                        let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
3107                        let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
3108                        let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
3109                        if let Some((normal, pen, contact)) =
3110                            candidate.intersect_triangle_world(w0, w1, w2)
3111                        {
3112                            hit_this_obj = true;
3113                            let replace: bool = deepest
3114                                .map(|delta_val: MeshCollisionHit3D| {
3115                                    pen > delta_val.get_penetration()
3116                                })
3117                                .unwrap_or(true);
3118                            if replace {
3119                                deepest = Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
3120                            }
3121                        }
3122                    }
3123                }
3124            } else {
3125                for ml in meshlets.iter() {
3126                    let ml_bounds: AxisAlignedBox3D = model_mat.transform_bounds(ml.get_bounds());
3127                    if !Self::boxes_overlap(query_bounds, ml_bounds) {
3128                        continue;
3129                    }
3130                    let start: usize = ml.get_first_tri() as usize;
3131                    let end: usize = start
3132                        .saturating_add(ml.get_tri_count() as usize)
3133                        .min(indices.len());
3134                    for tri in indices[start..end].iter() {
3135                        let (i0, i1, i2): (usize, usize, usize) =
3136                            (tri[0] as usize, tri[1] as usize, tri[2] as usize);
3137                        if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
3138                            let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
3139                            let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
3140                            let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
3141                            if let Some((normal, pen, contact)) =
3142                                candidate.intersect_triangle_world(w0, w1, w2)
3143                            {
3144                                hit_this_obj = true;
3145                                let replace: bool = deepest
3146                                    .map(|distance_val: MeshCollisionHit3D| {
3147                                        pen > distance_val.get_penetration()
3148                                    })
3149                                    .unwrap_or(true);
3150                                if replace {
3151                                    deepest =
3152                                        Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
3153                                }
3154                            }
3155                        }
3156                    }
3157                }
3158            }
3159            if !hit_this_obj
3160                && mesh.get_is_closed()
3161                && Self::point_in_bounds(candidate.get_center(), obj_bounds)
3162                && let Some(inside_hit) =
3163                    Self::point_inside_closed_mesh_mtv(idx, candidate, verts, indices, model_mat)
3164            {
3165                let replace: bool = deepest
3166                    .map(|prev_hit: MeshCollisionHit3D| {
3167                        inside_hit.get_penetration() > prev_hit.get_penetration()
3168                    })
3169                    .unwrap_or(true);
3170                if replace {
3171                    deepest = Some(inside_hit);
3172                }
3173            }
3174        }
3175        deepest
3176    }
3177
3178    /// Tests whether a world-space point lies strictly inside an axis-aligned bounding box.
3179    ///
3180    /// # Arguments
3181    ///
3182    /// - `Vec3` - Query point in world space.
3183    /// - `AxisAlignedBox3D` - World-space axis-aligned bounding box.
3184    ///
3185    /// # Returns
3186    ///
3187    /// - `bool` - `true` when the point lies inside the bounding box on all three axes.
3188    #[inline]
3189    #[must_use]
3190    fn point_in_bounds(point: Vec3, bounds: AxisAlignedBox3D) -> bool {
3191        let bmin: Vec3 = bounds.get_min();
3192        let bmax: Vec3 = bounds.get_max();
3193        point.get_x() >= bmin.get_x()
3194            && point.get_x() <= bmax.get_x()
3195            && point.get_y() >= bmin.get_y()
3196            && point.get_y() <= bmax.get_y()
3197            && point.get_z() >= bmin.get_z()
3198            && point.get_z() <= bmax.get_z()
3199    }
3200
3201    /// Computes the exact closest point on a 3D triangle `(v0, v1, v2)` to query point `point`.
3202    ///
3203    /// # Arguments
3204    ///
3205    /// - `Vec3` - Query point in world space.
3206    /// - `Vec3` - Triangle vertex 0.
3207    /// - `Vec3` - Triangle vertex 1.
3208    /// - `Vec3` - Triangle vertex 2.
3209    ///
3210    /// # Returns
3211    ///
3212    /// - `Vec3` - Closest point lying on or inside the triangle.
3213    #[inline]
3214    #[must_use]
3215    fn closest_point_on_triangle(point: Vec3, v0: Vec3, v1: Vec3, v2: Vec3) -> Vec3 {
3216        let ab: Vec3 = v1.sub(v0);
3217        let ac: Vec3 = v2.sub(v0);
3218        let ap: Vec3 = point.sub(v0);
3219        let d1: f32 = ab.dot(ap);
3220        let d2: f32 = ac.dot(ap);
3221        if d1 <= 0.0 && d2 <= 0.0 {
3222            return v0;
3223        }
3224        let bp: Vec3 = point.sub(v1);
3225        let d3: f32 = ab.dot(bp);
3226        let d4: f32 = ac.dot(bp);
3227        if d3 >= 0.0 && d4 <= d3 {
3228            return v1;
3229        }
3230        let vc: f32 = d1 * d4 - d3 * d2;
3231        if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
3232            let weight_v: f32 = d1 / (d1 - d3).max(1.0e-7);
3233            return v0.add(ab.scale(weight_v));
3234        }
3235        let cp: Vec3 = point.sub(v2);
3236        let d5: f32 = ab.dot(cp);
3237        let d6: f32 = ac.dot(cp);
3238        if d6 >= 0.0 && d5 <= d6 {
3239            return v2;
3240        }
3241        let vb: f32 = d5 * d2 - d1 * d6;
3242        if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
3243            let weight_w: f32 = d2 / (d2 - d6).max(1.0e-7);
3244            return v0.add(ac.scale(weight_w));
3245        }
3246        let va: f32 = d3 * d6 - d5 * d4;
3247        if va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0 {
3248            let denom_bc: f32 = ((d4 - d3) + (d5 - d6)).max(1.0e-7);
3249            let weight_w: f32 = (d4 - d3) / denom_bc;
3250            return v1.add(v2.sub(v1).scale(weight_w));
3251        }
3252        let denom: f32 = (va + vb + vc).max(1.0e-7);
3253        let weight_v: f32 = vb / denom;
3254        let weight_w: f32 = vc / denom;
3255        v0.add(ab.scale(weight_v)).add(ac.scale(weight_w))
3256    }
3257
3258    /// 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.
3259    ///
3260    /// # Arguments
3261    ///
3262    /// - `usize` - Solid scene object index in `World3D::objects`.
3263    /// - `OrientedBox3D` - Candidate oriented bounding box in world space.
3264    /// - `&[Vertex3D]` - Local mesh vertex buffer.
3265    /// - `&[[u32; 3]]` - Local mesh triangle index buffer.
3266    /// - `Mat4` - World model transform matrix of the solid mesh.
3267    ///
3268    /// # Returns
3269    ///
3270    /// - `Option<MeshCollisionHit3D>` - Outward minimum-translation-vector hit when strictly inside the closed solid, or `None` when outside (e.g. open archway tunnels).
3271    #[must_use]
3272    fn point_inside_closed_mesh_mtv(
3273        obj_idx: usize,
3274        candidate: OrientedBox3D,
3275        verts: &[Vertex3D],
3276        indices: &[[u32; 3]],
3277        model_mat: Mat4,
3278    ) -> Option<MeshCollisionHit3D> {
3279        let center: Vec3 = candidate.get_center();
3280        let parity_dir: Vec3 = Vec3::new(1.0, 1.37e-4, 2.71e-4).normalize();
3281        let mut crossings: u32 = 0;
3282        let mut best_horiz_dist_sq: f32 = f32::INFINITY;
3283        let mut best_horiz_cp: Vec3 = center;
3284        let mut best_horiz_n: Vec3 = Vec3::new(1.0, 0.0, 0.0);
3285        let mut best_any_dist_sq: f32 = f32::INFINITY;
3286        let mut best_any_cp: Vec3 = center;
3287        let mut best_any_n: Vec3 = Vec3::new(1.0, 0.0, 0.0);
3288        for tri in indices.iter() {
3289            let (i0, i1, i2): (usize, usize, usize) =
3290                (tri[0] as usize, tri[1] as usize, tri[2] as usize);
3291            if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
3292                continue;
3293            }
3294            let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
3295            let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
3296            let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
3297            if Self::ray_intersect_triangle(center, parity_dir, w0, w1, w2, 1.0e-5, f32::INFINITY)
3298                .is_some()
3299            {
3300                crossings = crossings.wrapping_add(1);
3301            }
3302            let cp: Vec3 = Self::closest_point_on_triangle(center, w0, w1, w2);
3303            let delta: Vec3 = cp.sub(center);
3304            let dist_sq: f32 = delta.length_sq();
3305            let raw_face_n: Vec3 = w1.sub(w0).cross(w2.sub(w0));
3306            let face_n: Vec3 = if raw_face_n.length_sq() > 1.0e-10 {
3307                raw_face_n.normalize()
3308            } else {
3309                Vec3::new(1.0, 0.0, 0.0)
3310            };
3311            if dist_sq < best_any_dist_sq {
3312                best_any_dist_sq = dist_sq;
3313                best_any_cp = cp;
3314                best_any_n = face_n;
3315            }
3316            let horiz_mag_sq: f32 =
3317                face_n.get_x() * face_n.get_x() + face_n.get_z() * face_n.get_z();
3318            if horiz_mag_sq > 0.25 && dist_sq < best_horiz_dist_sq {
3319                best_horiz_dist_sq = dist_sq;
3320                best_horiz_cp = cp;
3321                best_horiz_n = Vec3::new(face_n.get_x(), 0.0, face_n.get_z()).normalize();
3322            }
3323        }
3324        if (crossings & 1) == 0 {
3325            return None;
3326        }
3327        let (target_cp, fallback_n, target_dist_sq): (Vec3, Vec3, f32) =
3328            if best_horiz_dist_sq.is_finite() {
3329                (best_horiz_cp, best_horiz_n, best_horiz_dist_sq)
3330            } else if best_any_dist_sq.is_finite() {
3331                (best_any_cp, best_any_n, best_any_dist_sq)
3332            } else {
3333                return None;
3334            };
3335        let push_raw: Vec3 = target_cp.sub(center);
3336        let push_n: Vec3 = if push_raw.length_sq() > 1.0e-8 {
3337            push_raw.normalize()
3338        } else {
3339            fallback_n
3340        };
3341        let axes: [Vec3; 3] = candidate.get_axes();
3342        let half_extents: Vec3 = candidate.get_half_extents();
3343        let obb_proj: f32 = axes[0].dot(push_n).abs() * half_extents.get_x()
3344            + axes[1].dot(push_n).abs() * half_extents.get_y()
3345            + axes[2].dot(push_n).abs() * half_extents.get_z();
3346        let total_pen: f32 = target_dist_sq.sqrt() + obb_proj;
3347        Some(MeshCollisionHit3D::new(
3348            obj_idx, push_n, total_pen, target_cp,
3349        ))
3350    }
3351
3352    /// 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.
3353    ///
3354    /// # Arguments
3355    ///
3356    /// - `&Self` - World reference.
3357    /// - `OrientedBox3D` - Candidate oriented bounding box in world space.
3358    /// - `usize` - Colliding solid scene object index.
3359    ///
3360    /// # Returns
3361    ///
3362    /// - `Vec3` - Unit horizontal outward separation normal in the XZ plane, or `Vec3::zero()` if degenerate.
3363    #[must_use]
3364    fn horizontal_collision_normal(&self, candidate: OrientedBox3D, obj_idx: usize) -> Vec3 {
3365        let Some(obj) = self.get_objects().get(obj_idx) else {
3366            return Vec3::zero();
3367        };
3368        if let Some(mesh) = self
3369            .get_mesh_library()
3370            .get(obj.get_mesh_id())
3371            .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
3372        {
3373            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
3374            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
3375            let model_mat: Mat4 = obj.get_transform().to_mat4();
3376            let mut best_pen: f32 = f32::INFINITY;
3377            let mut best_hn: Vec3 = Vec3::zero();
3378            for tri in indices.iter() {
3379                let (i0, i1, i2): (usize, usize, usize) =
3380                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
3381                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
3382                    let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
3383                    let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
3384                    let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
3385                    if let Some((normal, pen, _)) = candidate.intersect_triangle_world(w0, w1, w2) {
3386                        let hn: Vec3 = Vec3::new(normal.get_x(), 0.0, normal.get_z());
3387                        if hn.length_sq() > 0.25 && pen < best_pen {
3388                            best_pen = pen;
3389                            best_hn = hn.normalize();
3390                        }
3391                    }
3392                }
3393            }
3394            if best_hn.length_sq() > 1.0e-6 {
3395                return best_hn;
3396            }
3397        }
3398        let bounds: AxisAlignedBox3D = obj.get_world_bounds();
3399        let bcenter: Vec3 = bounds.get_min().add(bounds.get_max()).scale(0.5);
3400        let diff: Vec3 = candidate.get_center().sub(bcenter);
3401        let horiz: Vec3 = Vec3::new(diff.get_x(), 0.0, diff.get_z());
3402        if horiz.length_sq() > 1.0e-6 {
3403            horiz.normalize()
3404        } else {
3405            Vec3::new(1.0, 0.0, 0.0)
3406        }
3407    }
3408
3409    /// Clamps a horizontal world position to playable island ground limits when present.
3410    ///
3411    /// # Arguments
3412    ///
3413    /// - `Vec3` - Candidate world position.
3414    /// - `Option<(f32, f32, f32, f32)>` - Optional playable horizontal `(min_x, max_x, min_z, max_z)` bounds.
3415    /// - `f32` - Vehicle horizontal margin in meters.
3416    ///
3417    /// # Returns
3418    ///
3419    /// - `Vec3` - Ground-clamped world position.
3420    #[inline]
3421    #[must_use]
3422    fn clamp_horizontal_to_ground(
3423        mut pos: Vec3,
3424        ground_limits: Option<(f32, f32, f32, f32)>,
3425        ground_margin: f32,
3426    ) -> Vec3 {
3427        if let Some((gx0, gx1, gz0, gz1)) = ground_limits {
3428            let lo_x: f32 = (gx0 + ground_margin).min(gx1);
3429            let hi_x: f32 = (gx1 - ground_margin).max(lo_x);
3430            let lo_z: f32 = (gz0 + ground_margin).min(gz1);
3431            let hi_z: f32 = (gz1 - ground_margin).max(lo_z);
3432            pos.set_x(pos.get_x().clamp(lo_x, hi_x));
3433            pos.set_z(pos.get_z().clamp(lo_z, hi_z));
3434        }
3435        pos
3436    }
3437
3438    /// Iteratively pushes a penetrating vehicle horizontally out of solid obstacles along the minimum-translation-vector normal until collision-free.
3439    ///
3440    /// # Arguments
3441    ///
3442    /// - `&Self` - World reference.
3443    /// - `&mut Transform3D` - Candidate vehicle transform adjusted in place when penetrating.
3444    /// - `AxisAlignedBox3D` - Vehicle local mesh bounds.
3445    /// - `usize` - Vehicle object index to ignore during self-test.
3446    /// - `Option<(f32, f32, f32, f32)>` - Optional playable ground bounds.
3447    /// - `f32` - Horizontal ground margin in meters.
3448    ///
3449    /// # Returns
3450    ///
3451    /// - `bool` - `true` when the transform was moved to resolve penetration.
3452    fn depenetrate_vehicle_horizontally(
3453        &self,
3454        transform_val: &mut Transform3D,
3455        mesh_bounds: AxisAlignedBox3D,
3456        vehicle_idx: usize,
3457        ground_limits: Option<(f32, f32, f32, f32)>,
3458        ground_margin: f32,
3459    ) -> bool {
3460        let mut adjusted: bool = false;
3461        for _ in 0..COLLISION_MTV_MAX_ITERS {
3462            let Some(hit) = self.collides_with_obstacles(*transform_val, mesh_bounds, vehicle_idx)
3463            else {
3464                break;
3465            };
3466            let raw_hn: Vec3 = Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
3467            let hn: Vec3 = if raw_hn.length_sq() > 1.0e-4 {
3468                raw_hn.normalize()
3469            } else {
3470                self.horizontal_collision_normal(
3471                    transform_val.to_oriented_box(mesh_bounds),
3472                    hit.get_object_index(),
3473                )
3474            };
3475            if hn.length_sq() <= 1.0e-6 {
3476                break;
3477            }
3478            let push_dist: f32 = hit.get_penetration() + COLLISION_MTV_PUSH_EPS;
3479            let cur_pos: Vec3 = transform_val.get_position();
3480            let pushed_pos: Vec3 = Self::clamp_horizontal_to_ground(
3481                Vec3::new(
3482                    cur_pos.get_x() + hn.get_x() * push_dist,
3483                    cur_pos.get_y(),
3484                    cur_pos.get_z() + hn.get_z() * push_dist,
3485                ),
3486                ground_limits,
3487                ground_margin,
3488            );
3489            transform_val.set_position(pushed_pos);
3490            adjusted = true;
3491        }
3492        adjusted
3493    }
3494
3495    /// Casts a world-space ray against every solid (`ray_trace_caster == true`) model's real mesh triangles (excluding `ignore_idx`) up to `max_dist`.
3496    ///
3497    /// # Arguments
3498    ///
3499    /// - `&Self` - World reference.
3500    /// - `Vec3` - Ray origin in world space.
3501    /// - `Vec3` - Unit ray direction in world space.
3502    /// - `f32` - Maximum ray distance.
3503    /// - `Option<usize>` - Optional scene object index to exclude.
3504    ///
3505    /// # Returns
3506    ///
3507    /// - `Option<RayHit3D>` - Closest real-mesh triangle intersection within `(1e-4, max_dist]`.
3508    #[must_use]
3509    pub fn raycast_solid_meshes(
3510        &self,
3511        origin: Vec3,
3512        direction: Vec3,
3513        max_dist: f32,
3514        ignore_idx: Option<usize>,
3515    ) -> Option<RayHit3D> {
3516        let dir: Vec3 = direction.normalize();
3517        let inv_dir: Vec3 = Ray3D::safe_inv_vec(dir);
3518        let t_min: f32 = 1e-4;
3519        let mut best_t: f32 = max_dist;
3520        let mut best_hit: Option<RayHit3D> = None;
3521        let objects: &[SceneObject3D] = self.get_objects().as_slice();
3522        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
3523        let ignore_is_static_caster: bool = ignore_idx
3524            .and_then(|idx: usize| objects.get(idx))
3525            .is_some_and(|obj: &SceneObject3D| obj.get_ray_trace_caster() && !obj.get_is_dynamic());
3526        let use_static_bvh: bool =
3527            !self.get_bvh_dirty() && !self.get_bvh().is_empty() && !ignore_is_static_caster;
3528        if use_static_bvh
3529            && let Some((hit_dist, tri_idx)) = self
3530                .get_bvh()
3531                .trace_closest_raw(origin, dir, inv_dir, t_min, best_t)
3532        {
3533            let bvh_tris: &[BvhTriangle] = self.get_bvh().get_triangles().as_slice();
3534            if let Some(hit_tri) = bvh_tris.get(tri_idx) {
3535                let raw_normal: Vec3 = hit_tri.get_normal();
3536                let oriented_normal: Vec3 = if raw_normal.dot(dir) > 0.0 {
3537                    raw_normal.scale(-1.0)
3538                } else {
3539                    raw_normal
3540                };
3541                best_t = hit_dist;
3542                best_hit = Some(RayHit3D {
3543                    distance: hit_dist,
3544                    point: origin.add(dir.scale(hit_dist)),
3545                    normal: oriented_normal,
3546                    material: hit_tri.get_material(),
3547                });
3548            }
3549        }
3550        for (idx, obj) in objects.iter().enumerate() {
3551            if ignore_idx == Some(idx) || !(obj.get_solid_collider() || obj.get_ray_trace_caster())
3552            {
3553                continue;
3554            }
3555            if use_static_bvh && obj.get_ray_trace_caster() && !obj.get_is_dynamic() {
3556                continue;
3557            }
3558            if !obj
3559                .get_world_bounds()
3560                .intersect_ray_near(origin, inv_dir, t_min, best_t)
3561                .is_finite()
3562            {
3563                continue;
3564            }
3565            let Some(mesh) = mesh_lib
3566                .get(obj.get_mesh_id())
3567                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
3568            else {
3569                continue;
3570            };
3571            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
3572            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
3573            let model_mat: Mat4 = obj.get_transform().to_mat4();
3574            let mat: PbrMaterial = obj.get_material();
3575            for tri in indices.iter() {
3576                let (i0, i1, i2): (usize, usize, usize) =
3577                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
3578                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
3579                    let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
3580                    let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
3581                    let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
3582                    if let Some((blend_factor, normal)) =
3583                        Self::ray_intersect_triangle(origin, dir, w0, w1, w2, t_min, best_t)
3584                    {
3585                        best_t = blend_factor;
3586                        best_hit = Some(RayHit3D {
3587                            distance: blend_factor,
3588                            point: origin.add(dir.scale(blend_factor)),
3589                            normal,
3590                            material: mat,
3591                        });
3592                    }
3593                }
3594            }
3595        }
3596        best_hit
3597    }
3598
3599    /// Tests whether two world-space `AxisAlignedBox3D` boxes overlap strictly.
3600    ///
3601    /// # Arguments
3602    ///
3603    /// - `AxisAlignedBox3D` - First bounding box.
3604    /// - `AxisAlignedBox3D` - Second bounding box.
3605    ///
3606    /// # Returns
3607    ///
3608    /// - `bool` - `true` when both axis-aligned bounding boxes overlap on all three axes.
3609    #[inline]
3610    #[must_use]
3611    fn boxes_overlap(alpha_val: AxisAlignedBox3D, blue_val: AxisAlignedBox3D) -> bool {
3612        let ox: bool = alpha_val.get_min().get_x() < blue_val.get_max().get_x()
3613            && alpha_val.get_max().get_x() > blue_val.get_min().get_x();
3614        let oy: bool = alpha_val.get_min().get_y() < blue_val.get_max().get_y()
3615            && alpha_val.get_max().get_y() > blue_val.get_min().get_y();
3616        let oz: bool = alpha_val.get_min().get_z() < blue_val.get_max().get_z()
3617            && alpha_val.get_max().get_z() > blue_val.get_min().get_z();
3618        ox && oy && oz
3619    }
3620
3621    /// Double-sided Möller-Trumbore ray-triangle intersection returning `(t, outward_unit_normal)`.
3622    ///
3623    /// # Arguments
3624    ///
3625    /// - `Vec3` - Ray origin.
3626    /// - `Vec3` - Unit ray direction.
3627    /// - `Vec3` - Triangle vertex 0.
3628    /// - `Vec3` - Triangle vertex 1.
3629    /// - `Vec3` - Triangle vertex 2.
3630    /// - `f32` - Minimum ray parameter `t`.
3631    /// - `f32` - Maximum ray parameter `t`.
3632    ///
3633    /// # Returns
3634    ///
3635    /// - `Option<(f32, Vec3)>` - Hit distance and facing unit normal.
3636    #[inline]
3637    #[must_use]
3638    fn ray_intersect_triangle(
3639        origin: Vec3,
3640        dir: Vec3,
3641        v0: Vec3,
3642        v1: Vec3,
3643        v2: Vec3,
3644        t_min: f32,
3645        t_max: f32,
3646    ) -> Option<(f32, Vec3)> {
3647        let e1: Vec3 = v1.sub(v0);
3648        let e2: Vec3 = v2.sub(v0);
3649        let pvec: Vec3 = dir.cross(e2);
3650        let det: f32 = e1.dot(pvec);
3651        if det.abs() < 1e-7 {
3652            return None;
3653        }
3654        let inv_det: f32 = 1.0 / det;
3655        let tvec: Vec3 = origin.sub(v0);
3656        let tex_u: f32 = tvec.dot(pvec) * inv_det;
3657        if !(0.0..=1.0).contains(&tex_u) {
3658            return None;
3659        }
3660        let qvec: Vec3 = tvec.cross(e1);
3661        let item_val: f32 = dir.dot(qvec) * inv_det;
3662        if item_val < 0.0 || tex_u + item_val > 1.0 {
3663            return None;
3664        }
3665        let blend_factor: f32 = e2.dot(qvec) * inv_det;
3666        if blend_factor <= t_min || blend_factor > t_max {
3667            return None;
3668        }
3669        let raw_n: Vec3 = e1.cross(e2).normalize();
3670        let normal: Vec3 = if raw_n.dot(dir) > 0.0 {
3671            raw_n.scale(-1.0)
3672        } else {
3673            raw_n
3674        };
3675        Some((blend_factor, normal))
3676    }
3677
3678    /// Tests whether a candidate transformed mesh collides with any solid obstacle's real triangles excluding `ignore_idx`.
3679    ///
3680    /// # Arguments
3681    ///
3682    /// - `&Self` - World reference.
3683    /// - `Transform3D` - Candidate object transform.
3684    /// - `AxisAlignedBox3D` - Candidate local mesh bounds.
3685    /// - `usize` - Self object index to skip.
3686    ///
3687    /// # Returns
3688    ///
3689    /// - `Option<MeshCollisionHit3D>` - Deepest real-mesh collision hit, or `None` when clear.
3690    #[must_use]
3691    fn collides_with_obstacles(
3692        &self,
3693        candidate_tr: Transform3D,
3694        local_bounds: AxisAlignedBox3D,
3695        ignore_idx: usize,
3696    ) -> Option<MeshCollisionHit3D> {
3697        let oriented_box: OrientedBox3D = candidate_tr.to_oriented_box(local_bounds);
3698        self.mesh_oriented_box_collision(oriented_box, Some(ignore_idx))
3699    }
3700
3701    /// Tests whether a candidate traffic-vehicle transform overlaps any static obstacle mesh or symmetrically intersects any other dynamic vehicle's oriented bounding box.
3702    ///
3703    /// # Arguments
3704    ///
3705    /// - `&Self` - World reference.
3706    /// - `Transform3D` - Candidate traffic vehicle transform.
3707    /// - `AxisAlignedBox3D` - Candidate traffic vehicle local mesh bounds.
3708    /// - `usize` - Traffic vehicle object index to exclude.
3709    ///
3710    /// # Returns
3711    ///
3712    /// - `bool` - `true` when the candidate pose collides with a static obstacle or another dynamic vehicle OBB.
3713    #[must_use]
3714    fn traffic_pose_blocked(
3715        &self,
3716        candidate_tr: Transform3D,
3717        local_bounds: AxisAlignedBox3D,
3718        traffic_idx: usize,
3719    ) -> bool {
3720        let cand_obb: OrientedBox3D = candidate_tr.to_oriented_box(local_bounds);
3721        if self
3722            .mesh_oriented_box_collision(cand_obb, Some(traffic_idx))
3723            .is_some()
3724        {
3725            return true;
3726        }
3727        let objects: &[SceneObject3D] = self.get_objects().as_slice();
3728        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
3729        let cand_bounds: AxisAlignedBox3D = cand_obb.to_world_bounds();
3730        for (other_idx, other_obj) in objects.iter().enumerate() {
3731            let is_solid_other: bool =
3732                other_obj.get_solid_collider() || other_obj.get_ray_trace_caster();
3733            if other_idx == traffic_idx || !other_obj.get_is_dynamic() || !is_solid_other {
3734                continue;
3735            }
3736            if !Self::boxes_overlap(cand_bounds, other_obj.get_world_bounds()) {
3737                continue;
3738            }
3739            let other_local: AxisAlignedBox3D = mesh_lib
3740                .get(other_obj.get_mesh_id())
3741                .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
3742                .map(Mesh3D::get_bounds)
3743                .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
3744            let other_obb: OrientedBox3D = other_obj.get_transform().to_oriented_box(other_local);
3745            if cand_obb.intersects_oriented_box(&other_obb) {
3746                return true;
3747            }
3748        }
3749        false
3750    }
3751
3752    /// Advances drivable vehicle/camera controls with continuous real-mesh oriented bounding box-vs-triangle collision, wall sliding, raycast camera boom, and synchronized spinning bounds.
3753    ///
3754    /// # Arguments
3755    ///
3756    /// - `&Self` - Mutable world.
3757    /// - `f32` - Delta time in seconds.
3758    /// - `&InputState` - Real-time polled keyboard/pointer input.
3759    /// - `&ActionMap` - Action bindings for WASD/Arrows movement.
3760    pub fn step_simulation(&mut self, dt: f32, input: &InputState, actions: &ActionMap) {
3761        if dt > 0.0 {
3762            self.set_world_time_secs(self.get_world_time_secs() + dt);
3763        }
3764        let move_vec: Point = actions.movement_vector(input);
3765        let steer: f32 = move_vec.get_x();
3766        let throttle: f32 = -move_vec.get_y();
3767        let mut any_dynamic_moved: bool = false;
3768        let mut any_static_moved: bool = false;
3769        let ground_limits: Option<(f32, f32, f32, f32)> = self.ground_play_bounds();
3770        let car_opt: Option<usize> = self.vehicle_index();
3771        if let Some(car_idx) = car_opt
3772            && let Some((mut transform_val, mesh_id, car_is_dynamic)) =
3773                self.get_objects().get(car_idx).map(|car: &SceneObject3D| {
3774                    (car.get_transform(), car.get_mesh_id(), car.get_is_dynamic())
3775                })
3776        {
3777            let mut car_moved: bool = false;
3778            let mesh_bounds: AxisAlignedBox3D = self
3779                .get_mesh_library()
3780                .get(mesh_id)
3781                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
3782                .map(Mesh3D::get_bounds)
3783                .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-2.0), Vec3::splat(2.0)));
3784            let init_obb: OrientedBox3D = transform_val.to_oriented_box(mesh_bounds);
3785            let ground_margin: f32 = init_obb
3786                .get_half_extents()
3787                .get_x()
3788                .max(init_obb.get_half_extents().get_z());
3789            if self.depenetrate_vehicle_horizontally(
3790                &mut transform_val,
3791                mesh_bounds,
3792                car_idx,
3793                ground_limits,
3794                ground_margin,
3795            ) {
3796                car_moved = true;
3797            }
3798            if steer.abs() > 0.05 {
3799                let steer_direction: f32 = if throttle < -0.05 { -1.0 } else { 1.0 };
3800                let total_yaw: f32 = -steer * steer_direction * 1.85 * dt;
3801                let rot_steps: usize = ((total_yaw.abs() / COLLISION_ROT_MAX_STEP_RAD).ceil()
3802                    as usize)
3803                    .clamp(1, COLLISION_ROT_MAX_SUBSTEPS);
3804                let step_yaw: f32 = total_yaw / (rot_steps as f32);
3805                for _ in 0..rot_steps {
3806                    let mut rotated: Transform3D = transform_val;
3807                    rotated.set_yaw_rad(transform_val.get_yaw_rad() + step_yaw);
3808                    if let Some(rot_hit) =
3809                        self.collides_with_obstacles(rotated, mesh_bounds, car_idx)
3810                    {
3811                        if rot_hit.get_penetration() <= COLLISION_ROT_MAX_PUSH_M {
3812                            let mut pushed_rot: Transform3D = rotated;
3813                            let _: bool = self.depenetrate_vehicle_horizontally(
3814                                &mut pushed_rot,
3815                                mesh_bounds,
3816                                car_idx,
3817                                ground_limits,
3818                                ground_margin,
3819                            );
3820                            let shift_m: f32 = pushed_rot
3821                                .get_position()
3822                                .sub(rotated.get_position())
3823                                .length();
3824                            if shift_m <= COLLISION_ROT_MAX_PUSH_M
3825                                && self
3826                                    .collides_with_obstacles(pushed_rot, mesh_bounds, car_idx)
3827                                    .is_none()
3828                            {
3829                                transform_val = pushed_rot;
3830                                car_moved = true;
3831                                continue;
3832                            }
3833                        }
3834                        break;
3835                    }
3836                    transform_val = rotated;
3837                    car_moved = true;
3838                }
3839            }
3840            if throttle.abs() > 0.05 {
3841                let fwd_x: f32 = -transform_val.get_yaw_rad().sin();
3842                let fwd_z: f32 = -transform_val.get_yaw_rad().cos();
3843                let total_disp: Vec3 = Vec3::new(fwd_x, 0.0, fwd_z).scale(24.0 * throttle * dt);
3844                let oriented_box_now: OrientedBox3D = transform_val.to_oriented_box(mesh_bounds);
3845                let min_half: f32 = oriented_box_now
3846                    .get_half_extents()
3847                    .get_x()
3848                    .min(oriented_box_now.get_half_extents().get_z())
3849                    .max(0.25);
3850                let max_step_len: f32 = (min_half * 0.25).min(COLLISION_CCD_MAX_STEP_M);
3851                let substeps: usize = ((total_disp.length() / max_step_len).ceil() as usize)
3852                    .clamp(1, COLLISION_CCD_MAX_SUBSTEPS);
3853                let step_delta: Vec3 = total_disp.scale(1.0 / (substeps as f32));
3854                for _ in 0..substeps {
3855                    let cur: Vec3 = transform_val.get_position();
3856                    let next_pos: Vec3 = Self::clamp_horizontal_to_ground(
3857                        Vec3::new(
3858                            cur.get_x() + step_delta.get_x(),
3859                            cur.get_y(),
3860                            cur.get_z() + step_delta.get_z(),
3861                        ),
3862                        ground_limits,
3863                        ground_margin,
3864                    );
3865                    let mut cand: Transform3D = transform_val;
3866                    cand.set_position(next_pos);
3867                    if let Some(hit) = self.collides_with_obstacles(cand, mesh_bounds, car_idx) {
3868                        let raw_hn: Vec3 =
3869                            Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
3870                        let hn: Vec3 = if raw_hn.length_sq() > 1.0e-4 {
3871                            raw_hn.normalize()
3872                        } else {
3873                            self.horizontal_collision_normal(
3874                                cand.to_oriented_box(mesh_bounds),
3875                                hit.get_object_index(),
3876                            )
3877                        };
3878                        if hn.length_sq() > 1.0e-6 {
3879                            let into: f32 = step_delta.dot(hn);
3880                            let slide_delta: Vec3 = if into < 0.0 {
3881                                step_delta.sub(hn.scale(into))
3882                            } else {
3883                                Vec3::zero()
3884                            };
3885                            if slide_delta.length_sq() > 1.0e-8 {
3886                                let slide_pos: Vec3 = Self::clamp_horizontal_to_ground(
3887                                    Vec3::new(
3888                                        cur.get_x() + slide_delta.get_x(),
3889                                        cur.get_y(),
3890                                        cur.get_z() + slide_delta.get_z(),
3891                                    ),
3892                                    ground_limits,
3893                                    ground_margin,
3894                                );
3895                                let mut slide_tr: Transform3D = transform_val;
3896                                slide_tr.set_position(slide_pos);
3897                                if self
3898                                    .collides_with_obstacles(slide_tr, mesh_bounds, car_idx)
3899                                    .is_none()
3900                                {
3901                                    transform_val = slide_tr;
3902                                    car_moved = true;
3903                                    continue;
3904                                }
3905                            }
3906                        }
3907                        break;
3908                    } else {
3909                        transform_val = cand;
3910                        car_moved = true;
3911                    }
3912                }
3913            }
3914            if car_moved {
3915                let world_b: AxisAlignedBox3D = transform_val.transform_bounds(mesh_bounds);
3916                if let Some(car_mut) = self.get_mut_objects().get_mut(car_idx) {
3917                    car_mut.set_transform(transform_val);
3918                    car_mut.set_world_bounds(world_b);
3919                }
3920                if car_is_dynamic {
3921                    any_dynamic_moved = true;
3922                } else {
3923                    any_static_moved = true;
3924                }
3925                let car_yaw: f32 = transform_val.get_yaw_rad();
3926                let car_origin: Vec3 = transform_val.get_position();
3927                let car_fwd: Vec3 = Vec3::new(-car_yaw.sin(), 0.0, -car_yaw.cos());
3928                let car_right: Vec3 = Vec3::new(car_yaw.cos(), 0.0, -car_yaw.sin());
3929                let beam_dir: Vec3 = Vec3::new(car_fwd.get_x(), -0.14, car_fwd.get_z()).normalize();
3930                if self.get_spot_lights().len() >= 2 {
3931                    let front_center: Vec3 = car_origin
3932                        .add(car_fwd.scale(2.2))
3933                        .add(Vec3::new(0.0, 0.95, 0.0));
3934                    let left_pos: Vec3 = front_center.sub(car_right.scale(0.85));
3935                    let right_pos: Vec3 = front_center.add(car_right.scale(0.85));
3936                    let spots: &mut Vec<SpotLight3D> = self.get_mut_spot_lights();
3937                    spots[0].set_position(left_pos);
3938                    spots[0].set_direction(beam_dir);
3939                    spots[1].set_position(right_pos);
3940                    spots[1].set_direction(beam_dir);
3941                }
3942                if let Some(tail_light) = self.get_mut_point_lights().first_mut()
3943                    && tail_light.get_color().get_x() > 0.90
3944                    && tail_light.get_color().get_y() < 0.15
3945                {
3946                    let rear_pos: Vec3 = car_origin
3947                        .sub(car_fwd.scale(2.9))
3948                        .add(Vec3::new(0.0, 0.95, 0.0));
3949                    tail_light.set_position(rear_pos);
3950                }
3951                if throttle.abs() > 0.25
3952                    && (self.get_world_revision() & 3) == 0
3953                    && self.get_niagara().get_active_count() < 24
3954                {
3955                    let exhaust_pos: Vec3 = car_origin
3956                        .sub(car_fwd.scale(2.3))
3957                        .add(Vec3::new(0.0, 0.42, 0.0));
3958                    let mut spark_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
3959                    spark_cfg.set_origin(exhaust_pos);
3960                    spark_cfg.set_base_velocity(car_fwd.scale(-4.5).add(Vec3::new(0.0, 1.1, 0.0)));
3961                    spark_cfg.set_start_size_m(0.11);
3962                    spark_cfg.set_end_size_m(0.03);
3963                    self.get_mut_niagara().emit_burst(1, &spark_cfg);
3964                }
3965            }
3966            let car_tr: Transform3D = self.get_objects()[car_idx].get_transform();
3967            let car_pos: Vec3 = car_tr.get_position();
3968            let yaw: f32 = car_tr.get_yaw_rad();
3969            let cam_mode: u8 = self.get_camera_mode();
3970            let (mut desired_eye, look_target): (Vec3, Vec3) = match cam_mode {
3971                1 => {
3972                    let eye: Vec3 = Vec3::new(
3973                        car_pos.get_x() - yaw.sin() * 1.4,
3974                        2.15,
3975                        car_pos.get_z() - yaw.cos() * 1.4,
3976                    );
3977                    let tgt: Vec3 = Vec3::new(
3978                        car_pos.get_x() - yaw.sin() * 18.0,
3979                        1.8,
3980                        car_pos.get_z() - yaw.cos() * 18.0,
3981                    );
3982                    (eye, tgt)
3983                }
3984                2 => {
3985                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.45;
3986                    self.set_camera_orbit_rad(orbit);
3987                    let eye: Vec3 = Vec3::new(
3988                        car_pos.get_x() + orbit.sin() * 10.5,
3989                        5.2,
3990                        car_pos.get_z() + orbit.cos() * 10.5,
3991                    );
3992                    (eye, Vec3::new(car_pos.get_x(), 1.6, car_pos.get_z()))
3993                }
3994                3 => {
3995                    let eye: Vec3 = Vec3::new(
3996                        car_pos.get_x() + yaw.sin() * 18.0,
3997                        18.5,
3998                        car_pos.get_z() + yaw.cos() * 18.0,
3999                    );
4000                    (eye, Vec3::new(car_pos.get_x(), 1.2, car_pos.get_z()))
4001                }
4002                4 => {
4003                    let cur_cam: Camera3D = self.get_camera();
4004                    let fwd: Vec3 = cur_cam.forward();
4005                    let right: Vec3 = cur_cam.right();
4006                    let moved: Vec3 = cur_cam
4007                        .get_position()
4008                        .add(fwd.scale(throttle * 18.0 * dt))
4009                        .add(right.scale(steer * 14.0 * dt));
4010                    let eye: Vec3 = Vec3::new(moved.get_x(), moved.get_y().max(1.5), moved.get_z());
4011                    (eye, eye.add(fwd.scale(16.0)))
4012                }
4013                5 => {
4014                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.28;
4015                    self.set_camera_orbit_rad(orbit);
4016                    let eye: Vec3 = Vec3::new(
4017                        car_pos.get_x() + orbit.sin() * 7.8,
4018                        3.6 + (orbit * 1.5).sin() * 1.4,
4019                        car_pos.get_z() + orbit.cos() * 13.5,
4020                    );
4021                    (eye, Vec3::new(car_pos.get_x(), 1.8, car_pos.get_z() - 3.0))
4022                }
4023                _ => {
4024                    let eye: Vec3 = Vec3::new(
4025                        car_pos.get_x() + yaw.sin() * 9.8,
4026                        4.25,
4027                        car_pos.get_z() + yaw.cos() * 9.8,
4028                    );
4029                    let tgt: Vec3 = Vec3::new(
4030                        car_pos.get_x() - yaw.sin() * 16.0,
4031                        2.40,
4032                        car_pos.get_z() - yaw.cos() * 16.0,
4033                    );
4034                    (eye, tgt)
4035                }
4036            };
4037            let boom_anchor: Vec3 =
4038                Vec3::new(car_pos.get_x(), car_pos.get_y() + 1.8, car_pos.get_z());
4039            let boom_vec: Vec3 = desired_eye.sub(boom_anchor);
4040            let boom_len: f32 = boom_vec.length();
4041            if boom_len > 0.25 {
4042                let boom_dir: Vec3 = boom_vec.scale(1.0 / boom_len);
4043                if let Some(hit) =
4044                    self.raycast_solid_meshes(boom_anchor, boom_dir, boom_len, Some(car_idx))
4045                {
4046                    let safe_dist: f32 = (hit.get_distance() - 0.55).max(0.8);
4047                    desired_eye = boom_anchor.add(boom_dir.scale(safe_dist));
4048                }
4049            }
4050            let cam_probe: OrientedBox3D = OrientedBox3D::from_bounds(AxisAlignedBox3D::new(
4051                desired_eye.sub(Vec3::splat(0.45)),
4052                desired_eye.add(Vec3::splat(0.45)),
4053            ));
4054            if let Some(hit) = self.mesh_oriented_box_collision(cam_probe, Some(car_idx)) {
4055                desired_eye = desired_eye.add(hit.get_normal().scale(hit.get_penetration() + 0.1));
4056            }
4057            let prev_cam: Camera3D = self.get_camera();
4058            let mut cam: Camera3D = prev_cam;
4059            let smooth: f32 = (dt * 7.0).clamp(0.05, 1.0);
4060            cam.set_position(cam.get_position().lerp(desired_eye, smooth));
4061            let look_dir: Vec3 = look_target.sub(cam.get_position()).normalize();
4062            cam.set_yaw(look_dir.get_z().atan2(look_dir.get_x()));
4063            cam.set_pitch(look_dir.get_y().clamp(-0.92, 0.92).asin());
4064            self.set_camera(cam);
4065            if cam != prev_cam {
4066                self.bump_world_revision();
4067            }
4068        }
4069        let traffic_count: usize = self.traffic_vehicle_count();
4070        let bumper_clearance_m: f32 = 0.75;
4071        for slot_idx in 0..traffic_count {
4072            let (traffic_idx, mut cur_s, lane_u, speed_mps): (usize, f32, f32, f32) = {
4073                let Self {
4074                    traffic_vehicles, ..
4075                } = self;
4076                traffic_vehicles[slot_idx]
4077            };
4078            let Some((mut tr, mesh_id, is_dynamic)) =
4079                self.get_objects()
4080                    .get(traffic_idx)
4081                    .map(|obj: &SceneObject3D| {
4082                        (obj.get_transform(), obj.get_mesh_id(), obj.get_is_dynamic())
4083                    })
4084            else {
4085                continue;
4086            };
4087            let local_bounds: AxisAlignedBox3D = self
4088                .get_mesh_library()
4089                .get(mesh_id)
4090                .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
4091                .map(Mesh3D::get_bounds)
4092                .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
4093            let traffic_obb: OrientedBox3D = tr.to_oriented_box(local_bounds);
4094            let traffic_margin: f32 = traffic_obb
4095                .get_half_extents()
4096                .get_x()
4097                .max(traffic_obb.get_half_extents().get_z());
4098            let mut moved_traffic: bool = self.depenetrate_vehicle_horizontally(
4099                &mut tr,
4100                local_bounds,
4101                traffic_idx,
4102                ground_limits,
4103                traffic_margin,
4104            );
4105            let total_ds: f32 = speed_mps * dt;
4106            if total_ds.abs() <= 1e-6 && !moved_traffic {
4107                continue;
4108            }
4109            let dir_sign: f32 = if speed_mps >= 0.0 { 1.0 } else { -1.0 };
4110            if total_ds.abs() > 1e-6 {
4111                let substeps: usize = ((total_ds.abs() / COLLISION_CCD_MAX_STEP_M).ceil() as usize)
4112                    .clamp(1, COLLISION_CCD_MAX_SUBSTEPS);
4113                let step_ds: f32 = total_ds / (substeps as f32);
4114                let scale_vec: Vec3 = tr.get_scale();
4115                for _ in 0..substeps {
4116                    let next_s: f32 = (cur_s + step_ds).rem_euclid(CITY_LOOP_TOTAL_LENGTH);
4117                    let (cand_pos, base_yaw): (Vec3, f32) = Self::loop_pose_at(next_s, lane_u);
4118                    let face_yaw: f32 = if speed_mps >= 0.0 {
4119                        base_yaw
4120                    } else {
4121                        base_yaw + PI
4122                    };
4123                    let cand_tr: Transform3D = Transform3D::new(cand_pos, face_yaw, scale_vec);
4124                    let probe_s: f32 =
4125                        (next_s + dir_sign * bumper_clearance_m).rem_euclid(CITY_LOOP_TOTAL_LENGTH);
4126                    let (probe_pos, probe_base_yaw): (Vec3, f32) =
4127                        Self::loop_pose_at(probe_s, lane_u);
4128                    let probe_yaw: f32 = if speed_mps >= 0.0 {
4129                        probe_base_yaw
4130                    } else {
4131                        probe_base_yaw + PI
4132                    };
4133                    let probe_tr: Transform3D = Transform3D::new(probe_pos, probe_yaw, scale_vec);
4134                    let blocked: bool =
4135                        self.traffic_pose_blocked(cand_tr, local_bounds, traffic_idx)
4136                            || self.traffic_pose_blocked(probe_tr, local_bounds, traffic_idx);
4137                    if blocked {
4138                        break;
4139                    }
4140                    cur_s = next_s;
4141                    tr = cand_tr;
4142                    moved_traffic = true;
4143                }
4144            }
4145            if moved_traffic {
4146                {
4147                    let Self {
4148                        traffic_vehicles, ..
4149                    } = self;
4150                    traffic_vehicles[slot_idx].1 = cur_s;
4151                }
4152                let world_b: AxisAlignedBox3D = tr.transform_bounds(local_bounds);
4153                if let Some(obj) = self.get_mut_objects().get_mut(traffic_idx) {
4154                    obj.set_transform(tr);
4155                    obj.set_world_bounds(world_b);
4156                }
4157                if is_dynamic {
4158                    any_dynamic_moved = true;
4159                } else {
4160                    any_static_moved = true;
4161                }
4162            }
4163        }
4164        let Self {
4165            objects,
4166            mesh_library,
4167            ..
4168        } = self;
4169        for obj in objects.iter_mut() {
4170            let spin: f32 = obj.get_spin_speed();
4171            if spin.abs() > 0.001 {
4172                let mut object_transform: Transform3D = obj.get_transform();
4173                object_transform.set_yaw_rad(object_transform.get_yaw_rad() + spin * dt);
4174                obj.set_transform(object_transform);
4175                let local_bounds: AxisAlignedBox3D = mesh_library
4176                    .get(obj.get_mesh_id())
4177                    .and_then(|color_item: &MeshLodChain| color_item.get_levels().first())
4178                    .map(Mesh3D::get_bounds)
4179                    .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
4180                obj.set_world_bounds(object_transform.transform_bounds(local_bounds));
4181                if obj.get_is_dynamic() {
4182                    any_dynamic_moved = true;
4183                } else {
4184                    any_static_moved = true;
4185                }
4186            }
4187        }
4188        if self.get_atmosphere_preset() == 1
4189            && (self.get_world_revision() & 1) == 0
4190            && self.get_niagara().get_active_count() < RAINY_NIGHT_MAX_PARTICLES
4191        {
4192            let cam_pos: Vec3 = self.get_camera().get_position();
4193            let mut rain_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
4194            rain_cfg.set_origin(cam_pos.add(Vec3::new(0.0, 5.0, -14.0)));
4195            rain_cfg.set_base_velocity(Vec3::new(-0.5, -15.5, 0.3));
4196            rain_cfg.set_velocity_spread(3.6);
4197            rain_cfg.set_start_color(Color::rgba(150, 218, 255, 210));
4198            rain_cfg.set_end_color(Color::rgba(68, 152, 240, 60));
4199            rain_cfg.set_start_size_m(0.07);
4200            rain_cfg.set_end_size_m(0.03);
4201            rain_cfg.set_min_lifetime(0.6);
4202            rain_cfg.set_max_lifetime(0.95);
4203            rain_cfg.set_emissive_boost(1.4);
4204            self.get_mut_niagara().emit_burst(2, &rain_cfg);
4205        }
4206        if self.get_niagara().get_active_count() > 0 {
4207            let _: usize = self.get_mut_niagara().update(dt, 0.0);
4208        }
4209        if !self.get_animation_mixer().get_layers().is_empty() {
4210            let anim_updates: usize = self.tick_animations(dt);
4211            if anim_updates > 0 {
4212                any_dynamic_moved = true;
4213            }
4214        }
4215        if any_static_moved {
4216            self.set_bvh_dirty(true);
4217        }
4218        if any_dynamic_moved {
4219            self.set_dynamic_bvh_dirty(true);
4220        }
4221        if any_static_moved || any_dynamic_moved {
4222            self.bump_world_revision();
4223        }
4224    }
4225
4226    /// Returns the optional precomputed IBL environment attached to this world.
4227    ///
4228    /// # Returns
4229    ///
4230    /// - `Option<&EnvironmentIbl3D>` - Borrowed IBL environment if configured.
4231    #[must_use]
4232    pub fn environment_ibl(&self) -> Option<&EnvironmentIbl3D> {
4233        let Self {
4234            environment_ibl, ..
4235        } = self;
4236        environment_ibl.as_ref()
4237    }
4238
4239    /// Replaces the world's active IBL environment and increments the world revision.
4240    ///
4241    /// # Arguments
4242    ///
4243    /// - `&Self` - Mutable world.
4244    /// - `Option<EnvironmentIbl3D>` - New IBL environment or `None` to clear.
4245    pub fn set_environment_ibl(&mut self, ibl: Option<EnvironmentIbl3D>) {
4246        let Self {
4247            environment_ibl, ..
4248        } = self;
4249        *environment_ibl = ibl;
4250        self.bump_world_revision();
4251    }
4252
4253    /// Returns the currently active multi-camera index inside `scene_cameras`, if selected.
4254    ///
4255    /// # Returns
4256    ///
4257    /// - `Option<usize>` - Active camera index in `scene_cameras`, or `None` when using `camera`.
4258    #[must_use]
4259    pub fn active_scene_camera_index(&self) -> Option<usize> {
4260        let Self {
4261            active_scene_camera,
4262            ..
4263        } = self;
4264        *active_scene_camera
4265    }
4266
4267    /// Selects an active camera from `scene_cameras` (or `None` to revert to the default `camera`).
4268    ///
4269    /// # Arguments
4270    ///
4271    /// - `&Self` - Mutable world.
4272    /// - `Option<usize>` - Target camera index inside `scene_cameras`.
4273    ///
4274    /// # Returns
4275    ///
4276    /// - `bool` - `true` when the requested camera selection succeeded.
4277    pub fn set_active_scene_camera(&mut self, camera_index: Option<usize>) -> bool {
4278        let cam_count: usize = self.get_scene_cameras().len();
4279        if let Some(target_idx) = camera_index
4280            && target_idx >= cam_count
4281        {
4282            return false;
4283        }
4284        let Self {
4285            active_scene_camera,
4286            ..
4287        } = self;
4288        *active_scene_camera = camera_index;
4289        if let Some(target_idx) = camera_index
4290            && let Some(scene_cam) = self.get_scene_cameras().get(target_idx).cloned()
4291        {
4292            self.set_camera(scene_cam.to_camera3d());
4293        }
4294        self.bump_world_revision();
4295        true
4296    }
4297
4298    /// Returns the active camera's view-projection matrix (respecting Perspective or Orthographic `SceneCamera3D` when selected).
4299    ///
4300    /// # Arguments
4301    ///
4302    /// - `&Self` - World reference.
4303    /// - `f32` - Viewport width-to-height aspect ratio.
4304    ///
4305    /// # Returns
4306    ///
4307    /// - `Mat4` - Active view-projection matrix.
4308    #[must_use]
4309    pub fn active_view_projection(&self, viewport_aspect: f32) -> Mat4 {
4310        if let Some(cam_idx) = self.active_scene_camera_index()
4311            && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
4312        {
4313            return scene_cam.view_projection(viewport_aspect);
4314        }
4315        self.get_camera().view_projection(viewport_aspect)
4316    }
4317
4318    /// Returns the live deformed (morphed and/or skinned) `Mesh3D` for `obj_idx` if active.
4319    ///
4320    /// # Arguments
4321    ///
4322    /// - `&Self` - World reference.
4323    /// - `usize` - Target object index in `objects`.
4324    ///
4325    /// # Returns
4326    ///
4327    /// - `Option<&Mesh3D>` - Borrowed deformed mesh when shape keys or armature skinning are active on `obj_idx`.
4328    #[must_use]
4329    pub fn deformed_mesh_for_object(&self, obj_idx: usize) -> Option<&Mesh3D> {
4330        let Self {
4331            deformed_meshes, ..
4332        } = self;
4333        deformed_meshes.get(obj_idx).and_then(Option::as_ref)
4334    }
4335
4336    /// Returns whether `obj_idx` is effectively visible after evaluating hierarchical node visibility and 64-bit Blender Collections masks.
4337    ///
4338    /// # Arguments
4339    ///
4340    /// - `&Self` - World reference.
4341    /// - `usize` - Target object index in `objects`.
4342    ///
4343    /// # Returns
4344    ///
4345    /// - `bool` - `true` when the object should be rendered.
4346    #[must_use]
4347    pub fn is_object_visible(&self, obj_idx: usize) -> bool {
4348        let Some(obj) = self.get_objects().get(obj_idx) else {
4349            return false;
4350        };
4351        if let Some(node_id) = obj.try_get_node_id() {
4352            return self.get_scene_graph().is_node_effectively_visible(node_id);
4353        }
4354        true
4355    }
4356
4357    /// Updates the deformation algorithm (`LinearBlend` or `DualQuaternion`) for skin `skin_idx` and refreshes deformed meshes immediately.
4358    ///
4359    /// # Arguments
4360    ///
4361    /// - `&Self` - Mutable world.
4362    /// - `usize` - Skin index inside `skins`.
4363    /// - `SkinningMode` - Desired skinning mode.
4364    ///
4365    /// # Returns
4366    ///
4367    /// - `bool` - `true` when `skin_idx` existed.
4368    pub fn set_skinning_mode(&mut self, skin_idx: usize, mode: SkinningMode) -> bool {
4369        let Some(skin) = self.get_mut_skins().get_mut(skin_idx) else {
4370            return false;
4371        };
4372        skin.set_skinning_mode(mode);
4373        let _: usize = self.update_deformed_meshes();
4374        self.bump_world_revision();
4375        true
4376    }
4377
4378    /// Toggles viewport visibility for Blender Collection `collection_name` in `scene_graph`.
4379    ///
4380    /// # Arguments
4381    ///
4382    /// - `&Self` - Mutable world.
4383    /// - `&str` - Collection name.
4384    /// - `bool` - Desired viewport visibility state.
4385    ///
4386    /// # Returns
4387    ///
4388    /// - `bool` - `true` when a matching collection was updated.
4389    pub fn set_collection_visible(&mut self, collection_name: &str, visible: bool) -> bool {
4390        let updated: bool = self
4391            .get_mut_scene_graph()
4392            .get_mut_collections()
4393            .set_collection_visible(collection_name, visible);
4394        if updated {
4395            self.bump_world_revision();
4396        }
4397        updated
4398    }
4399
4400    /// 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.
4401    ///
4402    /// # Arguments
4403    ///
4404    /// - `&Self` - Mutable 3D world.
4405    /// - `&ImportedScene3D` - Parsed Blender/glTF 2.0 scene bundle.
4406    ///
4407    /// # Returns
4408    ///
4409    /// - `Vec<usize>` - Indices of all spawned `SceneObject3D` entries inside `World3D::objects`.
4410    pub fn load_imported_scene(&mut self, scene: &ImportedScene3D) -> Vec<usize> {
4411        let texture_base: u32 = self.get_textures().len() as u32;
4412        self.get_mut_textures()
4413            .extend(scene.get_textures().iter().cloned());
4414        let material_base: u32 = self.get_principled_materials().len() as u32;
4415        for raw_mat in scene.get_materials().iter() {
4416            let mut rebased: PrincipledMaterial3D = raw_mat.clone();
4417            Self::rebase_material_textures(&mut rebased, texture_base);
4418            self.get_mut_principled_materials().push(rebased);
4419        }
4420        let mesh_base: usize = self.get_mesh_library().len();
4421        for raw_mesh in scene.get_meshes().iter() {
4422            let mut mesh_copy: Mesh3D = raw_mesh.clone();
4423            if let Some(local_mat_id) = mesh_copy.try_get_material_index() {
4424                mesh_copy.set_material_index(Some(local_mat_id.saturating_add(material_base)));
4425            }
4426            let lod_chain: MeshLodChain = if mesh_copy.get_indices().len() > 24 {
4427                build_qem_lod_chain(&mesh_copy, 3)
4428            } else {
4429                MeshLodChain::from_mesh(mesh_copy)
4430            };
4431            let _: usize = self.register_mesh(lod_chain);
4432        }
4433        let node_base: u32 = self.get_scene_graph().get_nodes().len() as u32;
4434        let skin_base: u32 = self.get_skins().len() as u32;
4435        let mut collection_bit_remap: Vec<u64> = Vec::new();
4436        for coll_entry in scene
4437            .get_scene_graph()
4438            .get_collections()
4439            .get_entries()
4440            .iter()
4441        {
4442            let mask_val: u64 = self
4443                .get_mut_scene_graph()
4444                .get_mut_collections()
4445                .register_collection(coll_entry.get_name());
4446            if !coll_entry.get_visible_viewport() {
4447                let _: bool = self
4448                    .get_mut_scene_graph()
4449                    .get_mut_collections()
4450                    .set_collection_visible(coll_entry.get_name(), false);
4451            }
4452            collection_bit_remap.push(mask_val);
4453        }
4454        let src_graph: &SceneGraph3D = scene.get_scene_graph();
4455        let src_nodes: &[SceneNode3D] = src_graph.get_nodes().as_slice();
4456        for (src_idx, src_node) in src_nodes.iter().enumerate() {
4457            let rebased_parent: Option<u32> = src_node
4458                .try_get_parent()
4459                .map(|parent_idx: u32| parent_idx.saturating_add(node_base));
4460            let node_label: &str = if src_node.get_name().is_empty() {
4461                BLENDER_IMPORTED_NODE_FALLBACK
4462            } else {
4463                src_node.get_name().as_str()
4464            };
4465            let mut dst_node: SceneNode3D = SceneNode3D::from_name(node_label, rebased_parent);
4466            dst_node.set_local_translation(src_node.get_local_translation());
4467            dst_node.set_local_rotation(src_node.get_local_rotation());
4468            dst_node.set_local_scale(src_node.get_local_scale());
4469            dst_node.set_visible(src_node.get_visible());
4470            dst_node.set_extras(src_node.get_extras().clone());
4471            let mut mapped_mask: u64 = 0;
4472            let raw_mask: u64 = src_node.get_collection_mask();
4473            for (bit_pos, &dst_bit) in collection_bit_remap.iter().enumerate() {
4474                if (raw_mask & (1_u64 << (bit_pos as u32))) != 0 {
4475                    mapped_mask |= dst_bit;
4476                }
4477            }
4478            dst_node.set_collection_mask(if mapped_mask == 0 { 1 } else { mapped_mask });
4479            if let Some(src_mesh_id) = src_node.try_get_mesh_id() {
4480                dst_node.set_mesh_id(Some((mesh_base as u32).saturating_add(src_mesh_id)));
4481            }
4482            if let Some(src_skin_id) = src_node.try_get_skin_id() {
4483                dst_node.set_skin_id(Some(skin_base.saturating_add(src_skin_id)));
4484            }
4485            dst_node.set_camera_id(src_node.try_get_camera_id());
4486            dst_node.set_light_id(src_node.try_get_light_id());
4487            let dst_node_id: u32 = self.get_mut_scene_graph().add_node(dst_node);
4488            let src_weights: &[f32] = src_graph.morph_weights_for_node(src_idx as u32);
4489            if !src_weights.is_empty() {
4490                self.get_mut_scene_graph()
4491                    .attach_morph_weights(dst_node_id, src_weights);
4492            }
4493            let Self {
4494                node_object_map, ..
4495            } = self;
4496            node_object_map.push(None);
4497        }
4498        let _: usize = self.get_mut_scene_graph().propagate_world_matrices();
4499        for src_skin in scene.get_skins().iter() {
4500            let mut runtime_skin: Skin3D = Skin3D::from_imported(src_skin);
4501            for joint_node in runtime_skin.get_mut_joints().iter_mut() {
4502                *joint_node = joint_node.saturating_add(node_base);
4503            }
4504            if let Some(root_idx) = runtime_skin.try_get_skeleton_root() {
4505                runtime_skin.set_skeleton_root(Some(root_idx.saturating_add(node_base)));
4506            }
4507            self.get_mut_skins().push(runtime_skin);
4508        }
4509        let mut first_clip_added: Option<usize> = None;
4510        for src_clip in scene.get_animations().iter() {
4511            let mut rebased_clip: ImportedAnimationClip3D = src_clip.clone();
4512            for chan in rebased_clip.get_mut_channels().iter_mut() {
4513                chan.set_target_node(chan.get_target_node().saturating_add(node_base));
4514            }
4515            let clip_idx: usize = self.get_mut_animation_mixer().add_clip(rebased_clip);
4516            if first_clip_added.is_none() {
4517                first_clip_added = Some(clip_idx);
4518            }
4519        }
4520        let graph_snapshot: SceneGraph3D = self.get_scene_graph().clone();
4521        self.get_mut_animation_mixer()
4522            .capture_rest_pose(&graph_snapshot);
4523        if let Some(clip_idx) = first_clip_added
4524            && self.get_animation_mixer().get_layers().is_empty()
4525        {
4526            let _: usize = self
4527                .get_mut_animation_mixer()
4528                .push_layer(NlaLayer3D::new(clip_idx));
4529        }
4530        let mut spawned_objects: Vec<usize> = Vec::new();
4531        let total_nodes: usize = self.get_scene_graph().get_nodes().len();
4532        for node_idx in (node_base as usize)..total_nodes {
4533            let node_copy: SceneNode3D = self.get_scene_graph().get_nodes()[node_idx].clone();
4534            let world_mat: Mat4 = node_copy.get_world_matrix();
4535            let world_tr: Transform3D = Transform3D::from_matrix(world_mat);
4536            if let Some(global_mesh_id) = node_copy.try_get_mesh_id() {
4537                let mesh_usize: usize = global_mesh_id as usize;
4538                let principled_id: Option<u32> = self
4539                    .get_mesh_library()
4540                    .get(mesh_usize)
4541                    .and_then(|chain: &MeshLodChain| chain.get_levels().first())
4542                    .and_then(|mesh_ref: &Mesh3D| mesh_ref.try_get_material_index());
4543                let legacy_mat: PbrMaterial = principled_id
4544                    .and_then(|mat_idx: u32| self.get_principled_materials().get(mat_idx as usize))
4545                    .map_or_else(
4546                        || {
4547                            self.get_mesh_library()
4548                                .get(mesh_usize)
4549                                .and_then(|chain: &MeshLodChain| chain.get_levels().first())
4550                                .map_or_else(PbrMaterial::default, Mesh3D::get_material)
4551                        },
4552                        PrincipledMaterial3D::to_legacy_pbr,
4553                    );
4554                let cast_shadows: bool = node_copy.get_extras().get_cast_shadows();
4555                let obj_idx: usize = self.spawn_object(
4556                    node_copy.get_name(),
4557                    mesh_usize,
4558                    world_tr,
4559                    legacy_mat,
4560                    cast_shadows,
4561                );
4562                let skin_opt: Option<u32> = node_copy.try_get_skin_id();
4563                let is_deformable: bool =
4564                    skin_opt.is_some() || node_copy.get_morph_weight_count() > 0;
4565                if let Some(obj_mut) = self.get_mut_objects().get_mut(obj_idx) {
4566                    obj_mut.set_node_id(Some(node_idx as u32));
4567                    obj_mut.set_principled_material_id(principled_id);
4568                    obj_mut.set_skin_id(skin_opt);
4569                }
4570                if is_deformable {
4571                    let _: bool = self.set_object_dynamic(obj_idx, true);
4572                }
4573                let Self {
4574                    node_object_map, ..
4575                } = self;
4576                if let Some(slot) = node_object_map.get_mut(node_idx) {
4577                    *slot = Some(obj_idx);
4578                }
4579                spawned_objects.push(obj_idx);
4580            }
4581            if let Some(src_cam_id) = node_copy.try_get_camera_id()
4582                && let Some(imp_cam) = scene.get_cameras().get(src_cam_id as usize)
4583            {
4584                self.get_mut_scene_cameras()
4585                    .push(SceneCamera3D::from_imported(
4586                        imp_cam,
4587                        Some(node_idx as u32),
4588                        world_tr.get_position(),
4589                        world_tr.get_rotation(),
4590                    ));
4591            }
4592            if let Some(src_light_id) = node_copy.try_get_light_id()
4593                && let Some(imp_light) = scene.get_lights().get(src_light_id as usize)
4594            {
4595                let emit_dir: Vec3 = world_tr
4596                    .get_rotation()
4597                    .rotate_vec3(Vec3::new(0.0, 0.0, -1.0))
4598                    .normalize();
4599                let light_color: Vec3 = imp_light.get_color();
4600                let light_intensity: f32 = imp_light.get_intensity();
4601                match imp_light.get_kind() {
4602                    GltfLightKind::Directional => {
4603                        let mut sun_val: DirectionalLight3D = self.get_sun();
4604                        sun_val.set_direction(emit_dir.scale(-1.0).normalize());
4605                        sun_val.set_color(light_color.scale(light_intensity.max(0.05)));
4606                        self.set_sun(sun_val);
4607                    }
4608                    GltfLightKind::Point { range } => {
4609                        let resolved_range: f32 = range.unwrap_or(24.0).max(0.5);
4610                        self.get_mut_point_lights().push(PointLight3D::from_linear(
4611                            world_tr.get_position(),
4612                            light_color,
4613                            light_intensity,
4614                            resolved_range,
4615                        ));
4616                    }
4617                    GltfLightKind::Spot {
4618                        range,
4619                        inner_cone_angle,
4620                        outer_cone_angle,
4621                    } => {
4622                        let resolved_range: f32 = range.unwrap_or(32.0).max(0.5);
4623                        self.get_mut_spot_lights().push(SpotLight3D::from_linear(
4624                            world_tr.get_position(),
4625                            emit_dir,
4626                            light_color,
4627                            light_intensity,
4628                            resolved_range,
4629                            (inner_cone_angle, outer_cone_angle),
4630                        ));
4631                    }
4632                    GltfLightKind::Area { width, height } => {
4633                        self.get_mut_area_lights().push(AreaLight3D::new_rect(
4634                            world_tr.get_position(),
4635                            emit_dir,
4636                            light_color,
4637                            light_intensity,
4638                            (width, height),
4639                            28.0,
4640                        ));
4641                    }
4642                }
4643            }
4644        }
4645        let _: usize = self.update_deformed_meshes();
4646        if self.environment_ibl().is_none() {
4647            let sun_ref: DirectionalLight3D = self.get_sun();
4648            let baked_ibl: EnvironmentIbl3D = EnvironmentIbl3D::from_procedural_sky(
4649                &sun_ref,
4650                WORLD_DEFAULT_IBL_OCT_SIZE,
4651                WORLD_DEFAULT_IBL_LUT_SIZE,
4652            );
4653            self.set_environment_ibl(Some(baked_ibl));
4654        }
4655        self.set_use_agx_tonemap(true);
4656        self.set_imported_model_count(self.get_imported_model_count().saturating_add(1));
4657        self.set_bvh_dirty(true);
4658        self.set_dynamic_bvh_dirty(true);
4659        self.set_dynamic_topology_dirty(true);
4660        self.bump_world_revision();
4661        spawned_objects
4662    }
4663
4664    /// Parses binary `.glb` or `.gltf` JSON bytes and loads the resulting Blender scene directly into `World3D`.
4665    ///
4666    /// # Arguments
4667    ///
4668    /// - `&Self` - Mutable 3D world.
4669    /// - `&[u8]` - Raw `.glb` or `.gltf` bytes.
4670    ///
4671    /// # Returns
4672    ///
4673    /// - `Result<Vec<usize>, String>` - Spawned object indices or structured glTF import error.
4674    pub fn load_glb_bytes(&mut self, bytes: &[u8]) -> Result<Vec<usize>, String> {
4675        let imported: ImportedScene3D = parse_gltf_or_glb_bytes(bytes, None)?;
4676        Ok(self.load_imported_scene(&imported))
4677    }
4678
4679    /// Parses pure-Rust Blender 3.x/4.x/5.x `.blend` bytes directly and loads the resulting scene into this `World3D`.
4680    ///
4681    /// # Arguments
4682    ///
4683    /// - `&[u8]` - Raw `.blend` binary buffer (uncompressed, gzip, or Zstd).
4684    ///
4685    /// # Returns
4686    ///
4687    /// - `Result<Vec<usize>, String>` - Spawned object indices or structured `.blend` import error.
4688    pub fn load_blend_bytes(&mut self, bytes: &[u8]) -> Result<Vec<usize>, String> {
4689        let imported: ImportedScene3D = parse_blend_bytes(bytes)?;
4690        Ok(self.load_imported_scene(&imported))
4691    }
4692
4693    /// Decodes a baked `.euv3d` (v1 or v2) binary package and loads its scene hierarchy, meshes, and materials into this `World3D`.
4694    ///
4695    /// # Arguments
4696    ///
4697    /// - `&[u8]` - Raw `.euv3d` binary buffer.
4698    ///
4699    /// # Returns
4700    ///
4701    /// - `Result<Vec<usize>, String>` - Spawned object indices or structured `.euv3d` decode error.
4702    pub fn load_euv3d_bytes(&mut self, bytes: &[u8]) -> Result<Vec<usize>, String> {
4703        let bundle: BakedAssetBundle3D = Euv3dPackage::decode_any_bytes(bytes)?;
4704        Ok(self.load_imported_scene(bundle.get_scene()))
4705    }
4706
4707    /// Tests a single local-space ray against `mesh` using meshlet AABB pruning and exact Möller–Trumbore triangle intersection.
4708    ///
4709    /// # Arguments
4710    ///
4711    /// - `&Mesh3D` - Candidate triangle mesh in local object space.
4712    /// - `Vec3` - Ray origin in mesh local space.
4713    /// - `Vec3` - Ray direction in mesh local space (unnormalized so parametric `t` matches world distance).
4714    /// - `Vec3` - Reciprocal local ray direction for AABB slab pruning.
4715    /// - `f32` - Minimum valid hit distance `t_min`.
4716    /// - `f32` - Current closest hit distance ceiling `best_t`.
4717    ///
4718    /// # Returns
4719    ///
4720    /// - `Option<(f32, Vec3)>` - Nearest `(hit_t, local_unit_normal)` strictly closer than `best_t`, or `None`.
4721    #[must_use]
4722    fn intersect_mesh_triangles_local(
4723        mesh: &Mesh3D,
4724        local_origin: Vec3,
4725        local_dir: Vec3,
4726        local_inv_dir: Vec3,
4727        t_min: f32,
4728        best_t: f32,
4729    ) -> Option<(f32, Vec3)> {
4730        let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
4731        let tris: &[[u32; 3]] = mesh.get_indices().as_slice();
4732        if verts.is_empty() || tris.is_empty() {
4733            return None;
4734        }
4735        let mut closest_t: f32 = best_t;
4736        let mut closest_normal: Vec3 = Vec3::zero();
4737        let mut hit_any: bool = false;
4738        let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
4739        if !meshlets.is_empty() {
4740            for meshlet in meshlets.iter() {
4741                let mbox: AxisAlignedBox3D = meshlet.get_bounds();
4742                let box_t: f32 =
4743                    mbox.intersect_ray_near(local_origin, local_inv_dir, t_min, closest_t);
4744                if box_t >= closest_t {
4745                    continue;
4746                }
4747                let start: usize = meshlet.get_first_tri() as usize;
4748                let end: usize = start
4749                    .saturating_add(meshlet.get_tri_count() as usize)
4750                    .min(tris.len());
4751                for tri in &tris[start..end] {
4752                    let (i0, i1, i2): (usize, usize, usize) =
4753                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4754                    if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
4755                        continue;
4756                    }
4757                    let v0: Vec3 = verts[i0].get_position();
4758                    let e1: Vec3 = verts[i1].get_position().sub(v0);
4759                    let e2: Vec3 = verts[i2].get_position().sub(v0);
4760                    let h: Vec3 = local_dir.cross(e2);
4761                    let a: f32 = e1.dot(h);
4762                    if a.abs() < 1e-7 {
4763                        continue;
4764                    }
4765                    let inv_a: f32 = 1.0 / a;
4766                    let s: Vec3 = local_origin.sub(v0);
4767                    let u: f32 = inv_a * s.dot(h);
4768                    if !(0.0..=1.0).contains(&u) {
4769                        continue;
4770                    }
4771                    let q: Vec3 = s.cross(e1);
4772                    let v: f32 = inv_a * local_dir.dot(q);
4773                    if v < 0.0 || (u + v) > 1.0 {
4774                        continue;
4775                    }
4776                    let t: f32 = inv_a * e2.dot(q);
4777                    if t >= t_min && t < closest_t {
4778                        closest_t = t;
4779                        closest_normal = e1.cross(e2).normalize();
4780                        hit_any = true;
4781                    }
4782                }
4783            }
4784        } else {
4785            for tri in tris.iter() {
4786                let (i0, i1, i2): (usize, usize, usize) =
4787                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4788                if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
4789                    continue;
4790                }
4791                let v0: Vec3 = verts[i0].get_position();
4792                let e1: Vec3 = verts[i1].get_position().sub(v0);
4793                let e2: Vec3 = verts[i2].get_position().sub(v0);
4794                let h: Vec3 = local_dir.cross(e2);
4795                let a: f32 = e1.dot(h);
4796                if a.abs() < 1e-7 {
4797                    continue;
4798                }
4799                let inv_a: f32 = 1.0 / a;
4800                let s: Vec3 = local_origin.sub(v0);
4801                let u: f32 = inv_a * s.dot(h);
4802                if !(0.0..=1.0).contains(&u) {
4803                    continue;
4804                }
4805                let q: Vec3 = s.cross(e1);
4806                let v: f32 = inv_a * local_dir.dot(q);
4807                if v < 0.0 || (u + v) > 1.0 {
4808                    continue;
4809                }
4810                let t: f32 = inv_a * e2.dot(q);
4811                if t >= t_min && t < closest_t {
4812                    closest_t = t;
4813                    closest_normal = e1.cross(e2).normalize();
4814                    hit_any = true;
4815                }
4816            }
4817        }
4818        if hit_any {
4819            Some((closest_t, closest_normal))
4820        } else {
4821            None
4822        }
4823    }
4824
4825    /// 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.
4826    ///
4827    /// # Arguments
4828    ///
4829    /// - `f32` - Normalized horizontal screen coordinate in `[0.0, 1.0]` (left to right).
4830    /// - `f32` - Normalized vertical screen coordinate in `[0.0, 1.0]` (top to bottom).
4831    /// - `f32` - Viewport aspect ratio `width / height`.
4832    ///
4833    /// # Returns
4834    ///
4835    /// - `Option<ScenePickHit3D>` - Nearest visible object triangle hit or `None` when no object is intersected.
4836    #[must_use]
4837    pub fn pick_object_ray(
4838        &self,
4839        screen_u: f32,
4840        screen_v: f32,
4841        aspect: f32,
4842    ) -> Option<ScenePickHit3D> {
4843        let safe_aspect: f32 = if aspect.is_finite() && aspect > 0.05 {
4844            aspect
4845        } else {
4846            1.0
4847        };
4848        let ndc_x: f32 = screen_u.clamp(0.0, 1.0) * 2.0 - 1.0;
4849        let ndc_y: f32 = 1.0 - screen_v.clamp(0.0, 1.0) * 2.0;
4850        let (origin, ray_dir, t_min, mut best_t): (Vec3, Vec3, f32, f32) = if let Some(cam_idx) =
4851            self.active_scene_camera_index()
4852            && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
4853        {
4854            let fwd: Vec3 = scene_cam.forward();
4855            let right: Vec3 = scene_cam.right();
4856            let up: Vec3 = scene_cam.up();
4857            match scene_cam.get_projection() {
4858                GltfCameraProjection::Orthographic {
4859                    xmag,
4860                    ymag,
4861                    znear,
4862                    zfar,
4863                } => {
4864                    let o: Vec3 = scene_cam
4865                        .get_position()
4866                        .add(right.scale(ndc_x * xmag))
4867                        .add(up.scale(ndc_y * ymag));
4868                    (o, fwd, znear.max(0.01), zfar.max(znear + 1.0))
4869                }
4870                GltfCameraProjection::Perspective {
4871                    yfov_rad,
4872                    aspect_ratio,
4873                    znear,
4874                    zfar,
4875                } => {
4876                    let cam_aspect: f32 = aspect_ratio.unwrap_or(safe_aspect).max(0.05);
4877                    let half_tan_y: f32 = (yfov_rad.clamp(0.15, 2.6) * 0.5).tan();
4878                    let dir: Vec3 = fwd
4879                        .add(right.scale(ndc_x * half_tan_y * cam_aspect))
4880                        .add(up.scale(ndc_y * half_tan_y))
4881                        .normalize();
4882                    (
4883                        scene_cam.get_position(),
4884                        dir,
4885                        znear.max(0.01),
4886                        zfar.unwrap_or(480.0).max(znear + 1.0),
4887                    )
4888                }
4889            }
4890        } else {
4891            let cam: Camera3D = self.get_camera();
4892            let half_tan_y: f32 = (cam.get_fov_deg().clamp(12.0, 120.0).to_radians() * 0.5).tan();
4893            let half_tan_x: f32 = half_tan_y * safe_aspect;
4894            let forward: Vec3 = cam.forward();
4895            let right: Vec3 = cam.right();
4896            let up: Vec3 = right.cross(forward).normalize();
4897            let dir: Vec3 = forward
4898                .add(right.scale(ndc_x * half_tan_x))
4899                .add(up.scale(ndc_y * half_tan_y))
4900                .normalize();
4901            let near_v: f32 = cam.get_near().max(0.01);
4902            (
4903                cam.get_position(),
4904                dir,
4905                near_v,
4906                cam.get_far().max(near_v + 1.0),
4907            )
4908        };
4909        let inv_dir: Vec3 = Vec3::new(
4910            if ray_dir.get_x().abs() > 1e-6 {
4911                1.0 / ray_dir.get_x()
4912            } else {
4913                f32::INFINITY
4914            },
4915            if ray_dir.get_y().abs() > 1e-6 {
4916                1.0 / ray_dir.get_y()
4917            } else {
4918                f32::INFINITY
4919            },
4920            if ray_dir.get_z().abs() > 1e-6 {
4921                1.0 / ray_dir.get_z()
4922            } else {
4923                f32::INFINITY
4924            },
4925        );
4926        let Self {
4927            objects,
4928            mesh_library,
4929            deformed_meshes,
4930            ..
4931        } = self;
4932        let mut best_hit: Option<ScenePickHit3D> = None;
4933        for (obj_idx, obj) in objects.iter().enumerate() {
4934            if !self.is_object_visible(obj_idx) {
4935                continue;
4936            }
4937            let bounds: AxisAlignedBox3D = obj.get_world_bounds();
4938            let aabb_t: f32 = bounds.intersect_ray_near(origin, inv_dir, t_min, best_t);
4939            if aabb_t >= best_t {
4940                continue;
4941            }
4942            let mesh_ref: Option<&Mesh3D> = deformed_meshes
4943                .get(obj_idx)
4944                .and_then(|slot: &Option<Mesh3D>| slot.as_ref())
4945                .or_else(|| {
4946                    mesh_library
4947                        .get(obj.get_mesh_id())
4948                        .and_then(|chain: &MeshLodChain| chain.get_levels().first())
4949                });
4950            let Some(mesh) = mesh_ref else {
4951                best_t = aabb_t;
4952                let world_pos: Vec3 = origin.add(ray_dir.scale(aabb_t));
4953                best_hit = Some(ScenePickHit3D::new(
4954                    obj_idx,
4955                    obj.get_mesh_id(),
4956                    aabb_t,
4957                    world_pos,
4958                    ray_dir.scale(-1.0),
4959                ));
4960                continue;
4961            };
4962            if mesh.get_indices().is_empty() {
4963                best_t = aabb_t;
4964                let world_pos: Vec3 = origin.add(ray_dir.scale(aabb_t));
4965                best_hit = Some(ScenePickHit3D::new(
4966                    obj_idx,
4967                    obj.get_mesh_id(),
4968                    aabb_t,
4969                    world_pos,
4970                    ray_dir.scale(-1.0),
4971                ));
4972                continue;
4973            }
4974            let xform: Transform3D = obj.get_transform();
4975            let inv_elems: [f32; 16] = xform.to_inv_mat4().get_elements();
4976            let local_origin: Vec3 = Vec3::new(
4977                inv_elems[0] * origin.get_x()
4978                    + inv_elems[4] * origin.get_y()
4979                    + inv_elems[8] * origin.get_z()
4980                    + inv_elems[12],
4981                inv_elems[1] * origin.get_x()
4982                    + inv_elems[5] * origin.get_y()
4983                    + inv_elems[9] * origin.get_z()
4984                    + inv_elems[13],
4985                inv_elems[2] * origin.get_x()
4986                    + inv_elems[6] * origin.get_y()
4987                    + inv_elems[10] * origin.get_z()
4988                    + inv_elems[14],
4989            );
4990            let local_dir: Vec3 = Vec3::new(
4991                inv_elems[0] * ray_dir.get_x()
4992                    + inv_elems[4] * ray_dir.get_y()
4993                    + inv_elems[8] * ray_dir.get_z(),
4994                inv_elems[1] * ray_dir.get_x()
4995                    + inv_elems[5] * ray_dir.get_y()
4996                    + inv_elems[9] * ray_dir.get_z(),
4997                inv_elems[2] * ray_dir.get_x()
4998                    + inv_elems[6] * ray_dir.get_y()
4999                    + inv_elems[10] * ray_dir.get_z(),
5000            );
5001            let local_inv_dir: Vec3 = Vec3::new(
5002                if local_dir.get_x().abs() > 1e-6 {
5003                    1.0 / local_dir.get_x()
5004                } else {
5005                    f32::INFINITY
5006                },
5007                if local_dir.get_y().abs() > 1e-6 {
5008                    1.0 / local_dir.get_y()
5009                } else {
5010                    f32::INFINITY
5011                },
5012                if local_dir.get_z().abs() > 1e-6 {
5013                    1.0 / local_dir.get_z()
5014                } else {
5015                    f32::INFINITY
5016                },
5017            );
5018            if let Some((hit_t, local_n)) = Self::intersect_mesh_triangles_local(
5019                mesh,
5020                local_origin,
5021                local_dir,
5022                local_inv_dir,
5023                t_min,
5024                best_t,
5025            ) {
5026                best_t = hit_t;
5027                let nmat: [Vec3; 3] = xform.normal_mat3();
5028                let mut world_n: Vec3 = nmat[0]
5029                    .scale(local_n.get_x())
5030                    .add(nmat[1].scale(local_n.get_y()))
5031                    .add(nmat[2].scale(local_n.get_z()))
5032                    .normalize();
5033                if world_n.dot(ray_dir) > 0.0 {
5034                    world_n = world_n.scale(-1.0);
5035                }
5036                let world_pos: Vec3 = origin.add(ray_dir.scale(hit_t));
5037                best_hit = Some(ScenePickHit3D::new(
5038                    obj_idx,
5039                    obj.get_mesh_id(),
5040                    hit_t,
5041                    world_pos,
5042                    world_n,
5043                ));
5044            }
5045        }
5046        best_hit
5047    }
5048
5049    /// 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.
5050    ///
5051    /// # Arguments
5052    ///
5053    /// - `&Self` - Mutable 3D world.
5054    /// - `f32` - Frame delta time in seconds.
5055    ///
5056    /// # Returns
5057    ///
5058    /// - `usize` - Count of updated scene nodes, morph channels, and deformed meshes.
5059    pub fn tick_animations(&mut self, dt_secs: f32) -> usize {
5060        let anim_updates: usize = {
5061            let Self {
5062                scene_graph,
5063                animation_mixer,
5064                ..
5065            } = self;
5066            animation_mixer.advance_and_apply(dt_secs, scene_graph)
5067        };
5068        let propagated: usize = self.get_mut_scene_graph().propagate_world_matrices();
5069        let synced: usize = self.sync_objects_from_scene_graph();
5070        let deformed: usize = self.update_deformed_meshes();
5071        let total: usize = anim_updates + propagated + synced + deformed;
5072        if total > 0 {
5073            self.set_dynamic_bvh_dirty(true);
5074            self.bump_world_revision();
5075        }
5076        total
5077    }
5078
5079    /// 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.
5080    ///
5081    /// # Returns
5082    ///
5083    /// - `usize` - Number of objects whose deformed mesh was updated.
5084    pub fn update_deformed_meshes(&mut self) -> usize {
5085        let obj_count: usize = self.get_objects().len();
5086        let Self {
5087            mesh_library,
5088            objects,
5089            scene_graph,
5090            skins,
5091            skin_scratch,
5092            deformed_meshes,
5093            ..
5094        } = self;
5095        if deformed_meshes.len() < obj_count {
5096            deformed_meshes.resize(obj_count, None);
5097        }
5098        let mut updated_count: usize = 0;
5099        for obj_idx in 0..obj_count {
5100            let obj_ref: &SceneObject3D = &objects[obj_idx];
5101            let Some(node_id) = obj_ref.try_get_node_id() else {
5102                continue;
5103            };
5104            let morph_weights: &[f32] = scene_graph.morph_weights_for_node(node_id);
5105            let skin_opt: Option<u32> = obj_ref.try_get_skin_id();
5106            if skin_opt.is_none() && morph_weights.is_empty() {
5107                continue;
5108            }
5109            let Some(base_mesh) = mesh_library
5110                .get(obj_ref.get_mesh_id())
5111                .and_then(|chain: &MeshLodChain| chain.get_levels().first())
5112            else {
5113                continue;
5114            };
5115            let mesh_world: Mat4 = scene_graph.get_nodes().get(node_id as usize).map_or_else(
5116                || obj_ref.get_transform().to_mat4(),
5117                SceneNode3D::get_world_matrix,
5118            );
5119            let did_deform: bool = if let Some(skin_id) = skin_opt
5120                && let Some(skin_ref) = skins.get(skin_id as usize)
5121            {
5122                skin_ref.deform_mesh_into(
5123                    base_mesh,
5124                    morph_weights,
5125                    mesh_world,
5126                    scene_graph,
5127                    skin_scratch,
5128                )
5129            } else {
5130                let morphed: bool = apply_morph_targets_into(
5131                    base_mesh.get_vertices().as_slice(),
5132                    base_mesh.get_morph_targets().as_slice(),
5133                    morph_weights,
5134                    skin_scratch.get_mut_skinned_vertices(),
5135                );
5136                morphed
5137            };
5138            if did_deform {
5139                let deformed_verts: &[Vertex3D] = skin_scratch.get_skinned_vertices().as_slice();
5140                let mut local_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
5141                for vert_item in deformed_verts.iter() {
5142                    local_bounds.expand_point(vert_item.get_position());
5143                }
5144                let target_slot: &mut Option<Mesh3D> = &mut deformed_meshes[obj_idx];
5145                if let Some(existing_mesh) = target_slot.as_mut() {
5146                    let dst_verts: &mut Vec<Vertex3D> = existing_mesh.get_mut_vertices();
5147                    dst_verts.clear();
5148                    dst_verts.extend_from_slice(deformed_verts);
5149                    existing_mesh.set_bounds(local_bounds);
5150                } else {
5151                    let mut cloned_mesh: Mesh3D = base_mesh.clone();
5152                    let dst_verts: &mut Vec<Vertex3D> = cloned_mesh.get_mut_vertices();
5153                    dst_verts.clear();
5154                    dst_verts.extend_from_slice(deformed_verts);
5155                    cloned_mesh.set_bounds(local_bounds);
5156                    *target_slot = Some(cloned_mesh);
5157                }
5158                if let Some(deformed_ref) = target_slot.as_ref() {
5159                    let world_tr: Transform3D = objects[obj_idx].get_transform();
5160                    objects[obj_idx]
5161                        .set_world_bounds(world_tr.transform_bounds(deformed_ref.get_bounds()));
5162                }
5163                updated_count += 1;
5164            }
5165        }
5166        updated_count
5167    }
5168
5169    /// Applies an incremental Blender Live-Link delta in place without resetting camera state or rebuilding unrelated geometry.
5170    ///
5171    /// # Arguments
5172    ///
5173    /// - `&Self` - Mutable 3D world.
5174    /// - `&BlenderLiveDelta3D` - Structured Live-Link delta command.
5175    ///
5176    /// # Returns
5177    ///
5178    /// - `bool` - `true` when at least one scene entity was mutated.
5179    pub fn apply_live_delta(&mut self, delta: &BlenderLiveDelta3D) -> bool {
5180        match delta {
5181            BlenderLiveDelta3D::NodeTransform {
5182                node_name,
5183                translation,
5184                rotation,
5185                scale,
5186                blender_z_up,
5187            } => {
5188                let found_id: Option<u32> = self
5189                    .get_scene_graph()
5190                    .get_nodes()
5191                    .iter()
5192                    .position(|node_ref: &SceneNode3D| node_ref.get_name() == node_name)
5193                    .map(|idx: usize| idx as u32);
5194                let Some(node_id) = found_id else {
5195                    return false;
5196                };
5197                let raw_t: Vec3 = Vec3::from_array(*translation);
5198                let raw_r: Quat = Quat::from_array(*rotation).normalize();
5199                let raw_s: Vec3 = Vec3::from_array(*scale);
5200                let (dst_t, dst_r, dst_s): (Vec3, Quat, Vec3) = if *blender_z_up {
5201                    (
5202                        raw_t.blender_z_up_to_y_up(),
5203                        raw_r.blender_z_up_to_y_up(),
5204                        Vec3::new(raw_s.get_x(), raw_s.get_z(), raw_s.get_y()),
5205                    )
5206                } else {
5207                    (raw_t, raw_r, raw_s)
5208                };
5209                self.get_mut_scene_graph()
5210                    .set_local_trs(node_id, dst_t, dst_r, dst_s);
5211                let _: usize = self.get_mut_scene_graph().propagate_world_matrices();
5212                let _: usize = self.sync_objects_from_scene_graph();
5213                let _: usize = self.update_deformed_meshes();
5214                self.set_dynamic_bvh_dirty(true);
5215                self.bump_world_revision();
5216                true
5217            }
5218            BlenderLiveDelta3D::MaterialParams {
5219                material_name,
5220                base_color_factor,
5221                metallic_factor,
5222                roughness_factor,
5223                clearcoat_factor,
5224                clearcoat_roughness_factor,
5225                sheen_color_factor,
5226                sheen_roughness_factor,
5227                emissive_factor,
5228                emissive_strength,
5229                transmission_factor,
5230                ior,
5231            } => {
5232                let found_idx: Option<usize> = self
5233                    .get_principled_materials()
5234                    .iter()
5235                    .position(|mat_ref: &PrincipledMaterial3D| mat_ref.get_name() == material_name);
5236                let Some(mat_idx) = found_idx else {
5237                    return false;
5238                };
5239                let updated_legacy: PbrMaterial = {
5240                    let mat_mut: &mut PrincipledMaterial3D =
5241                        &mut self.get_mut_principled_materials()[mat_idx];
5242                    if let Some(val) = *base_color_factor {
5243                        mat_mut.set_base_color_factor(val);
5244                    }
5245                    if let Some(val) = *metallic_factor {
5246                        mat_mut.set_metallic_factor(val.clamp(0.0, 1.0));
5247                    }
5248                    if let Some(val) = *roughness_factor {
5249                        mat_mut.set_roughness_factor(val.clamp(0.04, 1.0));
5250                    }
5251                    if let Some(val) = *clearcoat_factor {
5252                        mat_mut.set_clearcoat_factor(val.clamp(0.0, 1.0));
5253                    }
5254                    if let Some(val) = *clearcoat_roughness_factor {
5255                        mat_mut.set_clearcoat_roughness_factor(val.clamp(0.0, 1.0));
5256                    }
5257                    if let Some(val) = *sheen_color_factor {
5258                        mat_mut.set_sheen_color_factor(val);
5259                    }
5260                    if let Some(val) = *sheen_roughness_factor {
5261                        mat_mut.set_sheen_roughness_factor(val.clamp(0.0, 1.0));
5262                    }
5263                    if let Some(val) = *emissive_factor {
5264                        mat_mut.set_emissive_factor(val);
5265                    }
5266                    if let Some(val) = *emissive_strength {
5267                        mat_mut.set_emissive_strength(val.max(0.0));
5268                    }
5269                    if let Some(val) = *transmission_factor {
5270                        mat_mut.set_transmission_factor(val.clamp(0.0, 1.0));
5271                    }
5272                    if let Some(val) = *ior {
5273                        mat_mut.set_ior(val.clamp(1.0, 3.0));
5274                    }
5275                    mat_mut.to_legacy_pbr()
5276                };
5277                let mat_u32: u32 = mat_idx as u32;
5278                for obj_mut in self.get_mut_objects().iter_mut() {
5279                    if obj_mut.try_get_principled_material_id() == Some(mat_u32) {
5280                        obj_mut.set_material(updated_legacy);
5281                    }
5282                }
5283                self.bump_world_revision();
5284                true
5285            }
5286            BlenderLiveDelta3D::MorphWeights { node_name, weights } => {
5287                let found_id: Option<u32> = self
5288                    .get_scene_graph()
5289                    .get_nodes()
5290                    .iter()
5291                    .position(|node_ref: &SceneNode3D| node_ref.get_name() == node_name)
5292                    .map(|idx: usize| idx as u32);
5293                let Some(node_id) = found_id else {
5294                    return false;
5295                };
5296                self.get_mut_scene_graph()
5297                    .update_morph_weights(node_id, weights.as_slice());
5298                let _: usize = self.update_deformed_meshes();
5299                self.set_dynamic_bvh_dirty(true);
5300                self.bump_world_revision();
5301                true
5302            }
5303            BlenderLiveDelta3D::LightUpdate {
5304                light_index,
5305                color,
5306                intensity,
5307                position,
5308                direction,
5309            } => {
5310                let mut changed: bool = false;
5311                if let Some(point_mut) = self.get_mut_point_lights().get_mut(*light_index) {
5312                    if let Some(col_arr) = *color {
5313                        point_mut.set_color(Vec3::from_array(col_arr));
5314                    }
5315                    if let Some(int_val) = *intensity {
5316                        point_mut.set_intensity(int_val.max(0.0));
5317                    }
5318                    if let Some(pos_arr) = *position {
5319                        point_mut.set_position(Vec3::from_array(pos_arr));
5320                    }
5321                    changed = true;
5322                } else if let Some(area_mut) = self.get_mut_area_lights().get_mut(*light_index) {
5323                    if let Some(col_arr) = *color {
5324                        area_mut.set_color(Vec3::from_array(col_arr));
5325                    }
5326                    if let Some(int_val) = *intensity {
5327                        area_mut.set_intensity(int_val.max(0.0));
5328                    }
5329                    if let Some(pos_arr) = *position {
5330                        area_mut.set_position(Vec3::from_array(pos_arr));
5331                    }
5332                    if let Some(dir_arr) = *direction {
5333                        area_mut.set_direction(Vec3::from_array(dir_arr).normalize());
5334                    }
5335                    changed = true;
5336                }
5337                if changed {
5338                    self.bump_world_revision();
5339                }
5340                changed
5341            }
5342            BlenderLiveDelta3D::CameraUpdate {
5343                position,
5344                yaw,
5345                pitch,
5346                fov_deg,
5347            } => {
5348                let mut cam: Camera3D = self.get_camera();
5349                cam.set_position(Vec3::from_array(*position));
5350                cam.set_yaw(*yaw);
5351                cam.set_pitch(pitch.clamp(-1.4, 1.4));
5352                cam.set_fov_deg(fov_deg.clamp(12.0, 120.0));
5353                self.set_camera(cam);
5354                self.bump_world_revision();
5355                true
5356            }
5357            BlenderLiveDelta3D::CollectionVisibility {
5358                collection_name,
5359                visible,
5360            } => self.set_collection_visible(collection_name, *visible),
5361            BlenderLiveDelta3D::EnvironmentUpdate {
5362                rotation_y_rad,
5363                intensity,
5364            } => {
5365                let Self {
5366                    environment_ibl, ..
5367                } = self;
5368                if let Some(ibl_mut) = environment_ibl.as_mut() {
5369                    ibl_mut.set_rotation_y_rad(*rotation_y_rad);
5370                    ibl_mut.set_intensity(intensity.max(0.0));
5371                    self.bump_world_revision();
5372                    true
5373                } else {
5374                    false
5375                }
5376            }
5377        }
5378    }
5379
5380    /// Parses a JSON Live-Link delta payload and applies it in place to this world.
5381    ///
5382    /// # Arguments
5383    ///
5384    /// - `&Self` - Mutable 3D world.
5385    /// - `&str` - JSON Live-Link delta string.
5386    ///
5387    /// # Returns
5388    ///
5389    /// - `Result<bool, String>` - `Ok(applied)` on valid payload, or parse error string.
5390    pub fn apply_live_delta_json(&mut self, json_payload: &str) -> Result<bool, String> {
5391        let root: Value =
5392            from_str::<Value>(json_payload).map_err(|_| ERR_LIVE_DELTA_UNKNOWN_KIND.to_string())?;
5393        let kind_str: &str = root
5394            .get(LIVE_KEY_KIND)
5395            .and_then(Value::as_str)
5396            .ok_or_else(|| ERR_LIVE_DELTA_UNKNOWN_KIND.to_string())?;
5397        let delta: BlenderLiveDelta3D = match kind_str {
5398            LIVE_DELTA_KIND_TRANSFORM => BlenderLiveDelta3D::NodeTransform {
5399                node_name: root
5400                    .get(LIVE_KEY_NODE_NAME)
5401                    .and_then(Value::as_str)
5402                    .unwrap_or_default()
5403                    .to_string(),
5404                translation: Self::json_f32_array3(root.get(LIVE_KEY_TRANSLATION))
5405                    .unwrap_or([0.0, 0.0, 0.0]),
5406                rotation: Self::json_f32_array4(root.get(LIVE_KEY_ROTATION))
5407                    .unwrap_or([0.0, 0.0, 0.0, 1.0]),
5408                scale: Self::json_f32_array3(root.get(LIVE_KEY_SCALE)).unwrap_or([1.0, 1.0, 1.0]),
5409                blender_z_up: root
5410                    .get(LIVE_KEY_BLENDER_Z_UP)
5411                    .and_then(Value::as_bool)
5412                    .unwrap_or(false),
5413            },
5414            LIVE_DELTA_KIND_MATERIAL => BlenderLiveDelta3D::MaterialParams {
5415                material_name: root
5416                    .get(LIVE_KEY_MATERIAL_NAME)
5417                    .and_then(Value::as_str)
5418                    .unwrap_or_default()
5419                    .to_string(),
5420                base_color_factor: Self::json_f32_array4(root.get(LIVE_KEY_BASE_COLOR)),
5421                metallic_factor: root
5422                    .get(LIVE_KEY_METALLIC)
5423                    .and_then(Value::as_f64)
5424                    .map(|val: f64| val as f32),
5425                roughness_factor: root
5426                    .get(LIVE_KEY_ROUGHNESS)
5427                    .and_then(Value::as_f64)
5428                    .map(|val: f64| val as f32),
5429                clearcoat_factor: root
5430                    .get(LIVE_KEY_CLEARCOAT)
5431                    .and_then(Value::as_f64)
5432                    .map(|val: f64| val as f32),
5433                clearcoat_roughness_factor: root
5434                    .get(LIVE_KEY_CLEARCOAT_ROUGHNESS)
5435                    .and_then(Value::as_f64)
5436                    .map(|val: f64| val as f32),
5437                sheen_color_factor: Self::json_f32_array3(root.get(LIVE_KEY_SHEEN_COLOR)),
5438                sheen_roughness_factor: root
5439                    .get(LIVE_KEY_SHEEN_ROUGHNESS)
5440                    .and_then(Value::as_f64)
5441                    .map(|val: f64| val as f32),
5442                emissive_factor: Self::json_f32_array3(root.get(LIVE_KEY_EMISSIVE)),
5443                emissive_strength: root
5444                    .get(LIVE_KEY_EMISSIVE_STRENGTH)
5445                    .and_then(Value::as_f64)
5446                    .map(|val: f64| val as f32),
5447                transmission_factor: root
5448                    .get(LIVE_KEY_TRANSMISSION)
5449                    .and_then(Value::as_f64)
5450                    .map(|val: f64| val as f32),
5451                ior: root
5452                    .get("ior")
5453                    .and_then(Value::as_f64)
5454                    .map(|val: f64| val as f32),
5455            },
5456            LIVE_DELTA_KIND_MORPH => {
5457                let parsed_weights: Vec<f32> = root
5458                    .get(LIVE_KEY_WEIGHTS)
5459                    .and_then(Value::as_array)
5460                    .map(|items: &Vec<Value>| {
5461                        items
5462                            .iter()
5463                            .filter_map(|elem: &Value| elem.as_f64().map(|val: f64| val as f32))
5464                            .collect()
5465                    })
5466                    .unwrap_or_default();
5467                BlenderLiveDelta3D::MorphWeights {
5468                    node_name: root
5469                        .get(LIVE_KEY_NODE_NAME)
5470                        .and_then(Value::as_str)
5471                        .unwrap_or_default()
5472                        .to_string(),
5473                    weights: parsed_weights,
5474                }
5475            }
5476            LIVE_DELTA_KIND_LIGHT => BlenderLiveDelta3D::LightUpdate {
5477                light_index: root
5478                    .get(LIVE_KEY_LIGHT_INDEX)
5479                    .and_then(Value::as_u64)
5480                    .unwrap_or(0) as usize,
5481                color: Self::json_f32_array3(root.get(LIVE_KEY_COLOR)),
5482                intensity: root
5483                    .get(LIVE_KEY_INTENSITY)
5484                    .and_then(Value::as_f64)
5485                    .map(|val: f64| val as f32),
5486                position: Self::json_f32_array3(root.get(LIVE_KEY_POSITION)),
5487                direction: Self::json_f32_array3(root.get(LIVE_KEY_DIRECTION)),
5488            },
5489            LIVE_DELTA_KIND_CAMERA => BlenderLiveDelta3D::CameraUpdate {
5490                position: Self::json_f32_array3(root.get(LIVE_KEY_POSITION))
5491                    .unwrap_or([0.0, 2.0, 6.0]),
5492                yaw: root
5493                    .get("yaw")
5494                    .and_then(Value::as_f64)
5495                    .map_or(0.0, |val: f64| val as f32),
5496                pitch: root
5497                    .get(LIVE_KEY_PITCH)
5498                    .and_then(Value::as_f64)
5499                    .map_or(0.0, |val: f64| val as f32),
5500                fov_deg: root
5501                    .get(LIVE_KEY_FOV_DEG)
5502                    .and_then(Value::as_f64)
5503                    .map_or(60.0, |val: f64| val as f32),
5504            },
5505            LIVE_DELTA_KIND_COLLECTION => BlenderLiveDelta3D::CollectionVisibility {
5506                collection_name: root
5507                    .get(LIVE_KEY_COLLECTION_NAME)
5508                    .and_then(Value::as_str)
5509                    .unwrap_or_default()
5510                    .to_string(),
5511                visible: root
5512                    .get(LIVE_KEY_VISIBLE)
5513                    .and_then(Value::as_bool)
5514                    .unwrap_or(true),
5515            },
5516            LIVE_DELTA_KIND_ENVIRONMENT => BlenderLiveDelta3D::EnvironmentUpdate {
5517                rotation_y_rad: root
5518                    .get(LIVE_KEY_ROTATION_Y_RAD)
5519                    .and_then(Value::as_f64)
5520                    .map_or(0.0, |val: f64| val as f32),
5521                intensity: root
5522                    .get(LIVE_KEY_INTENSITY)
5523                    .and_then(Value::as_f64)
5524                    .map_or(1.0, |val: f64| val as f32),
5525            },
5526            _ => return Err(ERR_LIVE_DELTA_UNKNOWN_KIND.to_string()),
5527        };
5528        Ok(self.apply_live_delta(&delta))
5529    }
5530
5531    /// Synchronizes linked `SceneObject3D` and `SceneCamera3D` transforms from `scene_graph` propagated world matrices.
5532    ///
5533    /// # Returns
5534    ///
5535    /// - `usize` - Number of linked objects or cameras whose transforms were synchronized.
5536    fn sync_objects_from_scene_graph(&mut self) -> usize {
5537        let Self {
5538            mesh_library,
5539            objects,
5540            scene_graph,
5541            scene_cameras,
5542            node_object_map,
5543            deformed_meshes,
5544            ..
5545        } = self;
5546        let nodes: &[SceneNode3D] = scene_graph.get_nodes().as_slice();
5547        let mut synced_count: usize = 0;
5548        for (node_idx, obj_slot) in node_object_map.iter().enumerate() {
5549            let Some(obj_idx) = *obj_slot else {
5550                continue;
5551            };
5552            if node_idx >= nodes.len() || obj_idx >= objects.len() {
5553                continue;
5554            }
5555            let world_tr: Transform3D =
5556                Transform3D::from_matrix(nodes[node_idx].get_world_matrix());
5557            if objects[obj_idx].get_transform() != world_tr {
5558                objects[obj_idx].set_transform(world_tr);
5559                let local_bounds: AxisAlignedBox3D = deformed_meshes
5560                    .get(obj_idx)
5561                    .and_then(Option::as_ref)
5562                    .map(Mesh3D::get_bounds)
5563                    .or_else(|| {
5564                        mesh_library
5565                            .get(objects[obj_idx].get_mesh_id())
5566                            .and_then(|chain: &MeshLodChain| chain.get_levels().first())
5567                            .map(Mesh3D::get_bounds)
5568                    })
5569                    .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
5570                objects[obj_idx].set_world_bounds(world_tr.transform_bounds(local_bounds));
5571                synced_count += 1;
5572            }
5573        }
5574        for cam_mut in scene_cameras.iter_mut() {
5575            if let Some(node_id) = cam_mut.try_get_node_id()
5576                && let Some(node_ref) = nodes.get(node_id as usize)
5577            {
5578                let (pos_val, rot_val, _scale_val): (Vec3, Quat, Vec3) =
5579                    node_ref.get_world_matrix().decompose_trs();
5580                cam_mut.set_position(pos_val);
5581                cam_mut.set_rotation(rot_val);
5582                synced_count += 1;
5583            }
5584        }
5585        synced_count
5586    }
5587
5588    /// Offsets all texture indices inside `material` by `texture_base` when merging an imported scene.
5589    ///
5590    /// # Arguments
5591    ///
5592    /// - `&mut PrincipledMaterial3D` - Mutable material whose texture slots are rebased.
5593    /// - `u32` - Texture pool offset.
5594    fn rebase_material_textures(material: &mut PrincipledMaterial3D, texture_base: u32) {
5595        if texture_base == 0 {
5596            return;
5597        }
5598        let shift_slot: fn(Option<TextureSlot3D>, u32) -> Option<TextureSlot3D> =
5599            |slot_opt: Option<TextureSlot3D>, base_val: u32| -> Option<TextureSlot3D> {
5600                slot_opt.map(|mut slot: TextureSlot3D| {
5601                    slot.set_texture_index(slot.get_texture_index().saturating_add(base_val));
5602                    slot
5603                })
5604            };
5605        material.set_base_color_texture(shift_slot(
5606            material.try_get_base_color_texture(),
5607            texture_base,
5608        ));
5609        material.set_metallic_roughness_texture(shift_slot(
5610            material.try_get_metallic_roughness_texture(),
5611            texture_base,
5612        ));
5613        material.set_normal_texture(shift_slot(material.try_get_normal_texture(), texture_base));
5614        material.set_occlusion_texture(shift_slot(
5615            material.try_get_occlusion_texture(),
5616            texture_base,
5617        ));
5618        material.set_emissive_texture(shift_slot(
5619            material.try_get_emissive_texture(),
5620            texture_base,
5621        ));
5622        material.set_specular_texture(shift_slot(
5623            material.try_get_specular_texture(),
5624            texture_base,
5625        ));
5626        material.set_specular_color_texture(shift_slot(
5627            material.try_get_specular_color_texture(),
5628            texture_base,
5629        ));
5630        material.set_clearcoat_texture(shift_slot(
5631            material.try_get_clearcoat_texture(),
5632            texture_base,
5633        ));
5634        material.set_clearcoat_roughness_texture(shift_slot(
5635            material.try_get_clearcoat_roughness_texture(),
5636            texture_base,
5637        ));
5638        material.set_clearcoat_normal_texture(shift_slot(
5639            material.try_get_clearcoat_normal_texture(),
5640            texture_base,
5641        ));
5642        material.set_transmission_texture(shift_slot(
5643            material.try_get_transmission_texture(),
5644            texture_base,
5645        ));
5646        material.set_sheen_color_texture(shift_slot(
5647            material.try_get_sheen_color_texture(),
5648            texture_base,
5649        ));
5650        material.set_sheen_roughness_texture(shift_slot(
5651            material.try_get_sheen_roughness_texture(),
5652            texture_base,
5653        ));
5654    }
5655
5656    /// Extracts a 3-element `f32` array from an optional JSON array value.
5657    ///
5658    /// # Arguments
5659    ///
5660    /// - `Option<&Value>` - Optional JSON node.
5661    ///
5662    /// # Returns
5663    ///
5664    /// - `Option<[f32; 3]>` - Decoded array when three numeric entries exist.
5665    #[must_use]
5666    fn json_f32_array3(val: Option<&Value>) -> Option<[f32; 3]> {
5667        let arr: &Vec<Value> = val?.as_array()?;
5668        if arr.len() < 3 {
5669            return None;
5670        }
5671        Some([
5672            arr[0].as_f64()? as f32,
5673            arr[1].as_f64()? as f32,
5674            arr[2].as_f64()? as f32,
5675        ])
5676    }
5677
5678    /// Extracts a 4-element `f32` array from an optional JSON array value.
5679    ///
5680    /// # Arguments
5681    ///
5682    /// - `Option<&Value>` - Optional JSON node.
5683    ///
5684    /// # Returns
5685    ///
5686    /// - `Option<[f32; 4]>` - Decoded array when four numeric entries exist.
5687    #[must_use]
5688    fn json_f32_array4(val: Option<&Value>) -> Option<[f32; 4]> {
5689        let arr: &Vec<Value> = val?.as_array()?;
5690        if arr.len() < 4 {
5691            return None;
5692        }
5693        Some([
5694            arr[0].as_f64()? as f32,
5695            arr[1].as_f64()? as f32,
5696            arr[2].as_f64()? as f32,
5697            arr[3].as_f64()? as f32,
5698        ])
5699    }
5700
5701    /// Allocates a globally unique non-zero revision tag for `GpuWorld3dMeshBuffer` VRAM caching across distinct `World3D` instances.
5702    ///
5703    /// # Returns
5704    ///
5705    /// - `u64` - Monotonically increasing non-zero mesh revision tag.
5706    #[must_use]
5707    pub fn allocate_gpu_mesh_revision() -> u64 {
5708        NEXT_GPU_WORLD3D_MESH_REVISION
5709            .fetch_add(1, Ordering::Relaxed)
5710            .max(1)
5711    }
5712
5713    /// Flattens every registered `LOD0` prototype mesh in `mesh_library` into one resident GPU vertex buffer and per-mesh `(vertex_start, vertex_count)` table.
5714    ///
5715    /// # Arguments
5716    ///
5717    /// - `&Self` - World reference.
5718    /// - `u64` - Monotonic revision tag attached to the built buffer for VRAM upload caching.
5719    ///
5720    /// # Returns
5721    ///
5722    /// - `(Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>)` - Shared static GPU vertex buffer and per-mesh range table.
5723    #[must_use]
5724    pub fn build_gpu_mesh_buffer(
5725        &self,
5726        revision: u64,
5727    ) -> (Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>) {
5728        let mut vertices: Vec<GpuWorld3dVertex> = Vec::new();
5729        let mut ranges: Vec<(u32, u32)> = Vec::with_capacity(self.get_mesh_library().len());
5730        for chain in self.get_mesh_library() {
5731            let start_idx: u32 = vertices.len() as u32;
5732            if let Some(mesh) = chain.get_levels().first() {
5733                let mesh_verts: &[Vertex3D] = mesh.get_vertices().as_slice();
5734                let tri_mats: &[u16] = mesh.get_tri_materials().as_slice();
5735                let sub_mats: &[PbrMaterial] = mesh.get_sub_materials().as_slice();
5736                vertices.reserve(mesh.get_indices().len() * 3);
5737                for (tri_idx, &[i0, i1, i2]) in mesh.get_indices().iter().enumerate() {
5738                    let (Some(v0), Some(v1), Some(v2)) = (
5739                        mesh_verts.get(i0 as usize),
5740                        mesh_verts.get(i1 as usize),
5741                        mesh_verts.get(i2 as usize),
5742                    ) else {
5743                        continue;
5744                    };
5745                    let mat_slot: usize = tri_mats.get(tri_idx).copied().unwrap_or(0) as usize;
5746                    let color_submat: [f32; 4] = if mat_slot > 0
5747                        && let Some(sub_mat) = sub_mats.get(mat_slot - 1)
5748                    {
5749                        let base_c: Vec3 = sub_mat.get_base_color();
5750                        let em_c: Vec3 = sub_mat.get_emissive();
5751                        if em_c.length_sq() > 0.01 {
5752                            [
5753                                base_c.get_x() + em_c.get_x() * 1.4,
5754                                base_c.get_y() + em_c.get_y() * 1.4,
5755                                base_c.get_z() + em_c.get_z() * 1.4,
5756                                2.0,
5757                            ]
5758                        } else {
5759                            [base_c.get_x(), base_c.get_y(), base_c.get_z(), 1.0]
5760                        }
5761                    } else {
5762                        [1.0, 1.0, 1.0, 0.0]
5763                    };
5764                    for vert in [v0, v1, v2] {
5765                        let pos: Vec3 = vert.get_position();
5766                        let nrm: Vec3 = vert.get_normal();
5767                        vertices.push(GpuWorld3dVertex::new(
5768                            [pos.get_x(), pos.get_y(), pos.get_z(), 1.0],
5769                            [nrm.get_x(), nrm.get_y(), nrm.get_z(), 0.0],
5770                            color_submat,
5771                        ));
5772                    }
5773                }
5774            }
5775            let vert_count: u32 = (vertices.len() as u32).saturating_sub(start_idx);
5776            ranges.push((start_idx, vert_count));
5777        }
5778        (
5779            Arc::new(GpuWorld3dMeshBuffer { revision, vertices }),
5780            ranges,
5781        )
5782    }
5783
5784    /// 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.
5785    ///
5786    /// # Arguments
5787    ///
5788    /// - `&Self` - World reference.
5789    /// - `&DoubleBufferedSnapshot<World3DSnapshot>` - Double-buffered dynamic object and camera snapshots.
5790    /// - `f32` - Render interpolation alpha in `[0.0, 1.0]`.
5791    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
5792    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, and fog.
5793    /// - `(&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)])` - Cached static mesh buffer and per-mesh `(vertex_start, vertex_count)` ranges.
5794    /// - `(&mut World3dGpuPassScratch, &mut GpuWorld3dScenePass)` - Persistent flat scratch arena and destination scene pass reused across frames.
5795    fn populate_gpu_scene_pass_with_scratch(
5796        &self,
5797        snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
5798        alpha: f32,
5799        viewport: (u32, u32),
5800        quality: &RenderQualityConfig,
5801        mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
5802        buffers: (&mut World3dGpuPassScratch, &mut GpuWorld3dScenePass),
5803    ) {
5804        let (scratch, out): (&mut World3dGpuPassScratch, &mut GpuWorld3dScenePass) = buffers;
5805        let (target_width, target_height): (u32, u32) = viewport;
5806        let (mesh_buffer, mesh_ranges): (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]) = mesh_cache;
5807        let blend_alpha: f32 = alpha.clamp(0.0, 1.0);
5808        let prev_snap: &World3DSnapshot = snapshots.get_prev_state();
5809        let curr_snap: &World3DSnapshot = snapshots.get_curr_state();
5810        let mut interp_cam: Camera3D = if curr_snap.get_camera_cut() {
5811            curr_snap.get_camera()
5812        } else {
5813            prev_snap
5814                .get_camera()
5815                .lerp(curr_snap.get_camera(), blend_alpha)
5816        };
5817        let aspect: f32 = (target_width.max(1) as f32) / (target_height.max(1) as f32);
5818        if aspect > 3.5 {
5819            let pull_back: f32 = ((aspect - 3.5) * 0.42).min(1.6);
5820            let shifted_pos: Vec3 = interp_cam
5821                .get_position()
5822                .sub(interp_cam.forward().scale(pull_back));
5823            interp_cam.set_position(shifted_pos);
5824        }
5825        let view_proj_mat: Mat4 = if let Some(cam_idx) = self.active_scene_camera_index()
5826            && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
5827        {
5828            scene_cam.view_projection(aspect)
5829        } else {
5830            interp_cam.view_projection(aspect)
5831        };
5832        let frustum: Frustum3D = Frustum3D::from_view_proj(&view_proj_mat);
5833        let cam_pos: Vec3 = interp_cam.get_position();
5834        let draw_dist_sq: f32 = quality.get_draw_distance() * quality.get_draw_distance();
5835        let frustum_on: bool = quality.get_frustum_culling();
5836        let obj_len: usize = self.get_objects().len();
5837        if scratch.dynamic_pose_epochs.len() < obj_len {
5838            scratch.dynamic_pose_epochs.resize(obj_len, 0);
5839            scratch
5840                .dynamic_pose_transforms
5841                .resize(obj_len, Transform3D::default());
5842        }
5843        let next_epoch: u32 = scratch.current_epoch.wrapping_add(1);
5844        let active_epoch: u32 = if next_epoch == 0 {
5845            scratch.dynamic_pose_epochs.fill(0);
5846            1
5847        } else {
5848            next_epoch
5849        };
5850        scratch.current_epoch = active_epoch;
5851        let prev_objs: &[ObjectPose3D] = prev_snap.get_objects().as_slice();
5852        let next_objs: &[ObjectPose3D] = curr_snap.get_objects().as_slice();
5853        for (slot_idx, curr) in next_objs.iter().copied().enumerate() {
5854            let obj_idx: usize = curr.get_object_index();
5855            if obj_idx >= obj_len {
5856                continue;
5857            }
5858            let mut blended_tr: Transform3D = curr.get_transform();
5859            if curr.get_visible()
5860                && let Some(prev) = prev_objs.get(slot_idx).copied()
5861            {
5862                let continuous: bool = prev.get_visible()
5863                    && prev.get_object_index() == obj_idx
5864                    && prev.get_teleport_epoch() == curr.get_teleport_epoch();
5865                if continuous {
5866                    blended_tr = prev
5867                        .get_transform()
5868                        .lerp_shortest_angle(curr.get_transform(), blend_alpha);
5869                }
5870            }
5871            scratch.dynamic_pose_epochs[obj_idx] = active_epoch;
5872            scratch.dynamic_pose_transforms[obj_idx] = blended_tr;
5873        }
5874        let mesh_len: usize = mesh_ranges.len();
5875        if scratch.mesh_counts.len() < mesh_len {
5876            scratch.mesh_counts.resize(mesh_len, 0);
5877            scratch.mesh_cursors.resize(mesh_len, 0);
5878        }
5879        scratch.mesh_counts[..mesh_len].fill(0);
5880        scratch.visible_scratch.clear();
5881        let principled_mats: &[PrincipledMaterial3D] = self.get_principled_materials().as_slice();
5882        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
5883        for (obj_idx, obj) in self.get_objects().iter().enumerate() {
5884            if !self.is_object_visible(obj_idx) {
5885                continue;
5886            }
5887            let mesh_id: usize = obj.get_mesh_id();
5888            let Some(&(_, vert_count)) = mesh_ranges.get(mesh_id) else {
5889                continue;
5890            };
5891            if vert_count == 0 {
5892                continue;
5893            }
5894            let mut tr: Transform3D = obj.get_transform();
5895            let mut world_bounds: AxisAlignedBox3D = obj.get_world_bounds();
5896            if scratch.dynamic_pose_epochs[obj_idx] == active_epoch {
5897                tr = scratch.dynamic_pose_transforms[obj_idx];
5898                if let Some(chain) = mesh_lib.get(mesh_id)
5899                    && let Some(mesh0) = chain.get_levels().first()
5900                {
5901                    world_bounds = tr.transform_bounds(mesh0.get_bounds());
5902                }
5903            }
5904            let dist_sq: f32 = world_bounds.center().sub(cam_pos).length_sq();
5905            let radius: f32 = world_bounds.get_max().sub(world_bounds.get_min()).length() * 0.5;
5906            if dist_sq > draw_dist_sq + radius * radius * 4.0 {
5907                continue;
5908            }
5909            if frustum_on && !frustum.intersects_bounds(&world_bounds) {
5910                continue;
5911            }
5912            let mat: PbrMaterial = obj.get_material();
5913            let (albedo, metallic, roughness, emissive): (Vec3, f32, f32, Vec3) = if let Some(pm_id) =
5914                obj.try_get_principled_material_id()
5915                && let Some(pm) = principled_mats.get(pm_id as usize)
5916            {
5917                let bc: [f32; 4] = pm.get_base_color_factor();
5918                let em: [f32; 3] = pm.get_emissive_factor();
5919                let em_str: f32 = pm.get_emissive_strength();
5920                (
5921                    Vec3::new(bc[0], bc[1], bc[2]),
5922                    pm.get_metallic_factor(),
5923                    pm.get_roughness_factor(),
5924                    Vec3::new(em[0] * em_str, em[1] * em_str, em[2] * em_str),
5925                )
5926            } else {
5927                (
5928                    mat.get_base_color(),
5929                    mat.get_metallic(),
5930                    mat.get_roughness(),
5931                    mat.get_emissive(),
5932                )
5933            };
5934            let mut model_elems: [f32; 16] = tr.to_mat4().get_elements();
5935            model_elems[15] = match mat.get_surface_detail() {
5936                SurfaceDetailMode::None => 0.0,
5937                SurfaceDetailMode::RoadSurface => 1.0,
5938                SurfaceDetailMode::ArchitecturalFacade => 2.0,
5939                SurfaceDetailMode::OceanWater => 3.0,
5940            };
5941            scratch.mesh_counts[mesh_id] = scratch.mesh_counts[mesh_id].saturating_add(1);
5942            scratch.visible_scratch.push((
5943                mesh_id as u32,
5944                GpuWorld3dInstance::new(
5945                    model_elems,
5946                    [
5947                        albedo.get_x(),
5948                        albedo.get_y(),
5949                        albedo.get_z(),
5950                        metallic.clamp(0.0, 1.0),
5951                    ],
5952                    [
5953                        emissive.get_x(),
5954                        emissive.get_y(),
5955                        emissive.get_z(),
5956                        roughness.clamp(0.05, 1.0),
5957                    ],
5958                ),
5959            ));
5960        }
5961        let total_instances: usize = scratch.visible_scratch.len();
5962        out.draw_batches.clear();
5963        let mut cursor: u32 = 0;
5964        for (mesh_id, &(vertex_start, vertex_count)) in mesh_ranges.iter().enumerate() {
5965            let count: u32 = scratch.mesh_counts[mesh_id];
5966            scratch.mesh_cursors[mesh_id] = cursor;
5967            if count == 0 {
5968                continue;
5969            }
5970            out.draw_batches.push(GpuWorld3dMeshRange::new(
5971                vertex_start,
5972                vertex_count,
5973                cursor,
5974                count,
5975            ));
5976            cursor = cursor.saturating_add(count);
5977        }
5978        out.instances
5979            .resize(total_instances, GpuWorld3dInstance::default());
5980        for &(mesh_id_u32, inst) in scratch.visible_scratch.iter() {
5981            let mesh_id: usize = mesh_id_u32 as usize;
5982            let dst_idx: usize = scratch.mesh_cursors[mesh_id] as usize;
5983            scratch.mesh_cursors[mesh_id] = scratch.mesh_cursors[mesh_id].saturating_add(1);
5984            out.instances[dst_idx] = inst;
5985        }
5986        let sun: DirectionalLight3D = self.get_sun();
5987        let sun_dir: Vec3 = sun.get_direction().normalize();
5988        let sun_col: Vec3 = sun.get_color();
5989        let sky_hor: Vec3 = sun.get_sky_horizon();
5990        let sky_zen: Vec3 = sun.get_sky_zenith();
5991        let fog_density: f32 = if quality.get_volumetric_fog() {
5992            0.0028
5993        } else {
5994            0.0008
5995        };
5996        out.target_width = target_width;
5997        out.target_height = target_height;
5998        out.view_proj = view_proj_mat.get_elements();
5999        out.camera_pos = [cam_pos.get_x(), cam_pos.get_y(), cam_pos.get_z(), 1.15];
6000        out.sun_dir_fog = [
6001            sun_dir.get_x(),
6002            sun_dir.get_y(),
6003            sun_dir.get_z(),
6004            fog_density,
6005        ];
6006        out.sun_color_ambient = [sun_col.get_x(), sun_col.get_y(), sun_col.get_z(), 0.34];
6007        let anim_time: f32 =
6008            (sun.get_time_of_day() + self.get_world_time_secs()).rem_euclid(3600.0);
6009        out.sky_horizon_tod = [sky_hor.get_x(), sky_hor.get_y(), sky_hor.get_z(), anim_time];
6010        out.sky_zenith_aspect = [sky_zen.get_x(), sky_zen.get_y(), sky_zen.get_z(), aspect];
6011        out.mesh_buffer = Arc::clone(mesh_buffer);
6012    }
6013
6014    /// Populates a recycled `GpuWorld3dScenePass` in-place using `World3D`'s persistent flat scratch arena with zero per-frame heap allocations.
6015    ///
6016    /// # Arguments
6017    ///
6018    /// - `&Self` - Mutable world reference.
6019    /// - `&DoubleBufferedSnapshot<World3DSnapshot>` - Double-buffered dynamic object and camera snapshots.
6020    /// - `f32` - Render interpolation alpha in `[0.0, 1.0]`.
6021    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
6022    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, and fog.
6023    /// - `(&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)])` - Cached static mesh buffer and per-mesh `(vertex_start, vertex_count)` ranges.
6024    /// - `&mut GpuWorld3dScenePass` - Recycled scene pass destination populated in-place.
6025    pub fn build_gpu_scene_pass_into(
6026        &mut self,
6027        snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
6028        alpha: f32,
6029        viewport: (u32, u32),
6030        quality: &RenderQualityConfig,
6031        mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
6032        out: &mut GpuWorld3dScenePass,
6033    ) {
6034        let mut scratch: World3dGpuPassScratch = {
6035            let Self {
6036                gpu_pass_scratch, ..
6037            } = self;
6038            take(gpu_pass_scratch)
6039        };
6040        self.populate_gpu_scene_pass_with_scratch(
6041            snapshots,
6042            alpha,
6043            viewport,
6044            quality,
6045            mesh_cache,
6046            (&mut scratch, out),
6047        );
6048        let Self {
6049            gpu_pass_scratch, ..
6050        } = self;
6051        *gpu_pass_scratch = scratch;
6052    }
6053
6054    /// Rebuilds the cached quantized 24-byte `GpuPbrMeshBuffer` and per-LOD index ranges only when `mesh_library` geometry changes.
6055    ///
6056    /// # Arguments
6057    ///
6058    /// - `&[MeshLodChain]` - Active scene mesh library.
6059    /// - `&mut World3dPbrPassScratch` - Persistent PBR scratch cache storing the quantized `Arc<GpuPbrMeshBuffer>`.
6060    fn sync_pbr_quantized_mesh_cache(
6061        mesh_library: &[MeshLodChain],
6062        scratch: &mut World3dPbrPassScratch,
6063    ) {
6064        let mut total_verts: usize = 0;
6065        let mut total_indices: usize = 0;
6066        let mut any_skinned: bool = false;
6067        let mut any_morphed: bool = false;
6068        for chain in mesh_library.iter() {
6069            for mesh in chain.get_levels().iter().take(4) {
6070                total_verts = total_verts.saturating_add(mesh.get_vertices().len());
6071                total_indices =
6072                    total_indices.saturating_add(mesh.get_indices().len().saturating_mul(3));
6073                if !mesh.get_skin_influences().is_empty() {
6074                    any_skinned = true;
6075                }
6076                if !mesh.get_morph_targets().is_empty() {
6077                    any_morphed = true;
6078                }
6079            }
6080        }
6081        let signature: (usize, usize, usize) = (mesh_library.len(), total_verts, total_indices);
6082        if scratch.cached_signature == signature && scratch.cached_mesh_buffer.get_revision() > 0 {
6083            return;
6084        }
6085        let next_rev: u64 = NEXT_GPU_PBR_MESH_REVISION
6086            .fetch_add(1, Ordering::Relaxed)
6087            .max(1);
6088        let mut vertices: Vec<QuantizedVertex3D> = Vec::with_capacity(total_verts);
6089        let mut indices: Vec<u32> = Vec::with_capacity(total_indices);
6090        let mut skin_vertices: Vec<QuantizedSkinVertex3D> = if any_skinned {
6091            Vec::with_capacity(total_verts)
6092        } else {
6093            Vec::new()
6094        };
6095        let mut uv1_f16: Vec<[u16; 2]> = Vec::with_capacity(total_verts);
6096        let mut mesh_bounds_min: Vec<[f32; 4]> = Vec::with_capacity(mesh_library.len());
6097        let mut mesh_bounds_extent: Vec<[f32; 4]> = Vec::with_capacity(mesh_library.len());
6098        let mut morph_deltas: Vec<[f32; 4]> = if any_morphed && total_verts > 0 {
6099            vec![[0.0; 4]; total_verts.saturating_mul(4)]
6100        } else {
6101            Vec::new()
6102        };
6103        scratch.cached_lod_ranges.clear();
6104        scratch.cached_lod_ranges.reserve(mesh_library.len());
6105        let mut vert_tags: Vec<u8> = Vec::new();
6106        for chain in mesh_library.iter() {
6107            let levels: &[Mesh3D] = chain.get_levels().as_slice();
6108            let mut lod_ranges: [CachedPbrLodRange; 4] = [CachedPbrLodRange::default(); 4];
6109            let mut base_min: [f32; 4] = [0.0; 4];
6110            let mut base_ext: [f32; 4] = [1.0, 1.0, 1.0, 0.0];
6111            for (lod_idx, mesh) in levels.iter().take(4).enumerate() {
6112                let m_verts: &[Vertex3D] = mesh.get_vertices().as_slice();
6113                let m_tris: &[[u32; 3]] = mesh.get_indices().as_slice();
6114                let mb: AxisAlignedBox3D = mesh.get_bounds();
6115                let bmin: Vec3 = mb.get_min();
6116                let bext_raw: Vec3 = mb.get_max().sub(bmin);
6117                let bext: Vec3 = Vec3::new(
6118                    bext_raw.get_x().max(1e-4),
6119                    bext_raw.get_y().max(1e-4),
6120                    bext_raw.get_z().max(1e-4),
6121                );
6122                let min_arr: [f32; 4] = [bmin.get_x(), bmin.get_y(), bmin.get_z(), 0.0];
6123                let ext_arr: [f32; 4] = [bext.get_x(), bext.get_y(), bext.get_z(), 0.0];
6124                if lod_idx == 0 {
6125                    base_min = min_arr;
6126                    base_ext = ext_arr;
6127                }
6128                vert_tags.clear();
6129                vert_tags.resize(m_verts.len(), 0);
6130                for (cluster_idx, meshlet) in mesh.get_meshlets().iter().enumerate() {
6131                    let tag: u8 = ((cluster_idx % 255) + 1) as u8;
6132                    let t_start: usize = meshlet.get_first_tri() as usize;
6133                    let t_end: usize = t_start
6134                        .saturating_add(meshlet.get_tri_count() as usize)
6135                        .min(m_tris.len());
6136                    for tri in &m_tris[t_start..t_end] {
6137                        for &vi in tri.iter() {
6138                            if let Some(slot) = vert_tags.get_mut(vi as usize) {
6139                                *slot = tag;
6140                            }
6141                        }
6142                    }
6143                }
6144                let base_vertex: u32 = vertices.len() as u32;
6145                let index_start: u32 = indices.len() as u32;
6146                let skins: &[MeshSkinInfluence3D] = mesh.get_skin_influences().as_slice();
6147                for (vi, vert) in m_verts.iter().enumerate() {
6148                    let tag: u8 = vert_tags.get(vi).copied().unwrap_or(0);
6149                    vertices.push(quantize_vertex_3d(vert, bmin, bext, tag));
6150                    let uv1: [f32; 2] = vert.get_uv1();
6151                    uv1_f16.push([encode_f32_to_f16(uv1[0]), encode_f32_to_f16(uv1[1])]);
6152                    if any_skinned {
6153                        let qskin: QuantizedSkinVertex3D = skins
6154                            .get(vi)
6155                            .map_or_else(QuantizedSkinVertex3D::default, quantize_skin_vertex_3d);
6156                        skin_vertices.push(qskin);
6157                    }
6158                }
6159                let has_morphs: bool = !mesh.get_morph_targets().is_empty();
6160                if any_morphed && has_morphs && total_verts > 0 {
6161                    for (t_idx, target) in mesh.get_morph_targets().iter().take(4).enumerate() {
6162                        let dpos: &[[f32; 3]] = target.get_delta_positions().as_slice();
6163                        let target_base: usize = t_idx
6164                            .saturating_mul(total_verts)
6165                            .saturating_add(base_vertex as usize);
6166                        for (vi, delta) in dpos.iter().take(m_verts.len()).enumerate() {
6167                            if let Some(dst) = morph_deltas.get_mut(target_base + vi) {
6168                                *dst = [delta[0], delta[1], delta[2], 0.0];
6169                            }
6170                        }
6171                    }
6172                }
6173                for tri in m_tris.iter() {
6174                    indices.push(base_vertex.saturating_add(tri[0]));
6175                    indices.push(base_vertex.saturating_add(tri[1]));
6176                    indices.push(base_vertex.saturating_add(tri[2]));
6177                }
6178                let index_count: u32 = (indices.len() as u32).saturating_sub(index_start);
6179                lod_ranges[lod_idx] = CachedPbrLodRange {
6180                    index_start,
6181                    index_count,
6182                    bounds_min: min_arr,
6183                    bounds_extent: ext_arr,
6184                    has_morphs,
6185                };
6186            }
6187            let avail: usize = levels.len().min(4);
6188            if avail > 0 && avail < 4 {
6189                let fallback_lod: CachedPbrLodRange = lod_ranges[avail - 1];
6190                for fill_slot in lod_ranges.iter_mut().skip(avail) {
6191                    *fill_slot = fallback_lod;
6192                }
6193            }
6194            mesh_bounds_min.push(base_min);
6195            mesh_bounds_extent.push(base_ext);
6196            scratch.cached_lod_ranges.push(lod_ranges);
6197        }
6198        scratch.cached_signature = signature;
6199        scratch.cached_mesh_buffer = Arc::new(GpuPbrMeshBuffer {
6200            revision: next_rev,
6201            vertices,
6202            indices,
6203            skin_vertices,
6204            morph_deltas,
6205            uv1_f16,
6206            mesh_bounds_min,
6207            mesh_bounds_extent,
6208        });
6209    }
6210
6211    /// Converts a legacy `PbrMaterial` into a std140 `GpuMaterialData3D` and deduplicates against `materials[fallback_base..]` to maximize instancing coalescing.
6212    ///
6213    /// # Arguments
6214    ///
6215    /// - `PbrMaterial` - Legacy per-object PBR material.
6216    /// - `usize` - Starting index of deduplicated fallback materials inside `materials`.
6217    /// - `&mut Vec<GpuMaterialData3D>` - Destination frame material table.
6218    ///
6219    /// # Returns
6220    ///
6221    /// - `u32` - Resolved material table slot index.
6222    fn resolve_fallback_gpu_material(
6223        mat: PbrMaterial,
6224        fallback_base: usize,
6225        materials: &mut Vec<GpuMaterialData3D>,
6226    ) -> u32 {
6227        let albedo: Vec3 = mat.get_base_color();
6228        let emissive: Vec3 = mat.get_emissive();
6229        let candidate: GpuMaterialData3D = GpuMaterialData3D {
6230            base_color_factor: [albedo.get_x(), albedo.get_y(), albedo.get_z(), 1.0],
6231            emissive_alpha_cutoff: [emissive.get_x(), emissive.get_y(), emissive.get_z(), 0.5],
6232            pbr_ior_specular: [
6233                mat.get_metallic().clamp(0.0, 1.0),
6234                mat.get_roughness().clamp(0.04, 1.0),
6235                PRINCIPLED_DEFAULT_IOR,
6236                1.0,
6237            ],
6238            specular_color_clearcoat: [1.0, 1.0, 1.0, 0.0],
6239            clearcoat_normal_occ_trans: [0.1, 1.0, 1.0, 0.0],
6240            volume_attenuation: [1.0, 1.0, 1.0, 0.0],
6241            sheen_color_roughness: [0.0, 0.0, 0.0, 0.5],
6242            tex_indices_a: [GPU_MATERIAL_NO_TEXTURE; 4],
6243            tex_indices_b: [GPU_MATERIAL_NO_TEXTURE; 4],
6244            flags_volume: [
6245                0,
6246                f32::INFINITY.to_bits(),
6247                GPU_MATERIAL_NO_TEXTURE,
6248                GPU_MATERIAL_NO_TEXTURE,
6249            ],
6250        };
6251        if let Some(rel_idx) = materials[fallback_base..]
6252            .iter()
6253            .position(|existing: &GpuMaterialData3D| *existing == candidate)
6254        {
6255            return (fallback_base + rel_idx) as u32;
6256        }
6257        let slot: u32 = materials.len() as u32;
6258        materials.push(candidate);
6259        slot
6260    }
6261
6262    /// Populates a recycled `GpuPbrScenePass` using borrowed `pbr_pass_scratch` and `skin_scratch` arenas with zero steady-state heap allocations.
6263    ///
6264    /// # Arguments
6265    ///
6266    /// - `&Self` - World reference.
6267    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
6268    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, LOD bias, and fog.
6269    /// - `&mut GpuUploadBelt` - Frame-budgeted GPU staging belt enforcing `<= 4 MiB` and `<= 1.5 ms` ceilings.
6270    /// - `&mut World3dPbrPassScratch` - Persistent PBR geometry cache and batcher scratch arena.
6271    /// - `&mut SkinPaletteScratch3D` - Reusable bone matrix evaluation workspace.
6272    /// - `&mut GpuPbrScenePass` - Destination hardware PBR scene pass overwritten in-place.
6273    fn populate_gpu_pbr_scene_pass_with_scratch(
6274        &self,
6275        viewport: (u32, u32),
6276        quality: &RenderQualityConfig,
6277        belt: &mut GpuUploadBelt,
6278        scratch: &mut World3dPbrPassScratch,
6279        skin_scratch: &mut SkinPaletteScratch3D,
6280        out: &mut GpuPbrScenePass,
6281    ) {
6282        belt.begin_frame();
6283        let prev_vp: [f32; 16] = out.get_view_proj();
6284        out.clear_frame_payloads();
6285        let (target_width, target_height): (u32, u32) = viewport;
6286        let aspect: f32 = (target_width.max(1) as f32) / (target_height.max(1) as f32);
6287        let (view_proj_mat, cam_pos, cam_fov_deg, cam_far): (Mat4, Vec3, f32, f32) =
6288            if let Some(cam_idx) = self.active_scene_camera_index()
6289                && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
6290            {
6291                let proj_cam: Camera3D = scene_cam.to_camera3d();
6292                (
6293                    scene_cam.view_projection(aspect),
6294                    scene_cam.get_position(),
6295                    proj_cam.get_fov_deg(),
6296                    proj_cam.get_far(),
6297                )
6298            } else {
6299                let cam: Camera3D = self.get_camera();
6300                (
6301                    cam.view_projection(aspect),
6302                    cam.get_position(),
6303                    cam.get_fov_deg(),
6304                    cam.get_far(),
6305                )
6306            };
6307        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
6308        Self::sync_pbr_quantized_mesh_cache(mesh_lib, scratch);
6309        let src_mats: &[PrincipledMaterial3D] = self.get_principled_materials().as_slice();
6310        let dst_mats: &mut Vec<GpuMaterialData3D> = out.get_mut_materials();
6311        if dst_mats.capacity() < src_mats.len() {
6312            dst_mats.reserve(src_mats.len() - dst_mats.len());
6313        }
6314        for mat_ref in src_mats.iter() {
6315            dst_mats.push(mat_ref.to_gpu_data());
6316        }
6317        let fallback_mat_base: usize = dst_mats.len();
6318        let dst_lights: &mut Vec<GpuPackedLocalLight> = out.get_mut_local_lights();
6319        for pl in self.get_point_lights().iter() {
6320            if dst_lights.len() >= PBR_MAX_LOCAL_LIGHTS {
6321                break;
6322            }
6323            let p: Vec3 = pl.get_position();
6324            let c: Vec3 = pl.get_color();
6325            dst_lights.push(GpuPackedLocalLight::new(
6326                [p.get_x(), p.get_y(), p.get_z(), pl.get_radius().max(0.1)],
6327                [c.get_x(), c.get_y(), c.get_z(), pl.get_intensity().max(0.0)],
6328                [0.0, -1.0, 0.0, 0.0],
6329                [-1.0, -1.0, 0.0, 0.0],
6330            ));
6331        }
6332        for sl in self.get_spot_lights().iter() {
6333            if dst_lights.len() >= PBR_MAX_LOCAL_LIGHTS {
6334                break;
6335            }
6336            let p: Vec3 = sl.get_position();
6337            let c: Vec3 = sl.get_color();
6338            let d: Vec3 = sl.get_direction().normalize();
6339            dst_lights.push(GpuPackedLocalLight::new(
6340                [p.get_x(), p.get_y(), p.get_z(), sl.get_range().max(0.1)],
6341                [c.get_x(), c.get_y(), c.get_z(), sl.get_intensity().max(0.0)],
6342                [d.get_x(), d.get_y(), d.get_z(), 1.0],
6343                [sl.get_inner_cos(), sl.get_outer_cos(), 0.0, 0.0],
6344            ));
6345        }
6346        for al in self.get_area_lights().iter() {
6347            if dst_lights.len() >= PBR_MAX_LOCAL_LIGHTS {
6348                break;
6349            }
6350            let p: Vec3 = al.get_position();
6351            let c: Vec3 = al.get_color();
6352            let d: Vec3 = al.get_direction().normalize();
6353            dst_lights.push(GpuPackedLocalLight::new(
6354                [p.get_x(), p.get_y(), p.get_z(), al.get_range().max(0.1)],
6355                [c.get_x(), c.get_y(), c.get_z(), al.get_intensity().max(0.0)],
6356                [d.get_x(), d.get_y(), d.get_z(), 2.0],
6357                [0.0, -1.0, al.get_width(), al.get_height()],
6358            ));
6359        }
6360        let sun: DirectionalLight3D = self.get_sun();
6361        let sun_dir: Vec3 = sun.get_direction().normalize();
6362        let sun_col: Vec3 = sun.get_color();
6363        let sky_hor: Vec3 = sun.get_sky_horizon();
6364        let sky_zen: Vec3 = sun.get_sky_zenith();
6365        let ibl_sh: [[f32; 4]; 9] = if let Some(env) = self.environment_ibl() {
6366            let raw: [[f32; 3]; 9] = env.get_sh_irradiance();
6367            let mut packed: [[f32; 4]; 9] = [[0.0; 4]; 9];
6368            for (dst, src) in packed.iter_mut().zip(raw.iter()) {
6369                *dst = [src[0], src[1], src[2], 0.0];
6370            }
6371            packed
6372        } else {
6373            let mut packed: [[f32; 4]; 9] = [[0.0; 4]; 9];
6374            let avg_r: f32 = (sky_hor.get_x() + sky_zen.get_x()) * 0.5;
6375            let avg_g: f32 = (sky_hor.get_y() + sky_zen.get_y()) * 0.5;
6376            let avg_b: f32 = (sky_hor.get_z() + sky_zen.get_z()) * 0.5;
6377            packed[0] = [avg_r * 1.35, avg_g * 1.35, avg_b * 1.35, 0.0];
6378            packed[1] = [
6379                (sky_zen.get_x() - sky_hor.get_x()) * 0.35,
6380                (sky_zen.get_y() - sky_hor.get_y()) * 0.35,
6381                (sky_zen.get_z() - sky_hor.get_z()) * 0.35,
6382                0.0,
6383            ];
6384            packed
6385        };
6386        let frustum: Frustum3D = Frustum3D::from_view_proj(&view_proj_mat);
6387        let frustum_planes: [[f32; 4]; 6] = frustum.get_planes();
6388        let half_h: f32 = (cam_fov_deg.clamp(12.0, 120.0).to_radians() * 0.5)
6389            .tan()
6390            .max(0.05);
6391        let focal_px: f32 = (target_height.max(1) as f32) * 0.5 / half_h;
6392        let draw_dist: f32 = quality.get_draw_distance().max(1.0);
6393        let draw_dist_sq: f32 = draw_dist * draw_dist;
6394        let frustum_on: bool = quality.get_frustum_culling();
6395        let chunk_on: bool = quality.get_chunk_streaming();
6396        let lod_bias: f32 = quality.get_lod_bias();
6397        let inv_far: f32 = 1.0 / cam_far.max(draw_dist).max(1.0);
6398        let objects: &[SceneObject3D] = self.get_objects().as_slice();
6399        let scene_graph: &SceneGraph3D = self.get_scene_graph();
6400        let skins: &[Skin3D] = self.get_skins().as_slice();
6401        let total_objs: usize = objects.len();
6402        scratch.batcher.get_mut_entries().clear();
6403        if scratch.batcher.get_entries().capacity() < total_objs {
6404            let need: usize = total_objs - scratch.batcher.get_entries().len();
6405            scratch.batcher.get_mut_entries().reserve(need);
6406        }
6407        let mut meshlets_tested: u32 = 0;
6408        let mut meshlets_culled: u32 = 0;
6409        let mut lod_counts: [u32; 4] = [0; 4];
6410        let mut base_idx: usize = 0;
6411        while base_idx < total_objs {
6412            let chunk: usize = (total_objs - base_idx).min(4);
6413            let mut min_x: [f32; 4] = [0.0; 4];
6414            let mut min_y: [f32; 4] = [0.0; 4];
6415            let mut min_z: [f32; 4] = [0.0; 4];
6416            let mut max_x: [f32; 4] = [0.0; 4];
6417            let mut max_y: [f32; 4] = [0.0; 4];
6418            let mut max_z: [f32; 4] = [0.0; 4];
6419            let mut vis_flags: u8 = 0;
6420            for lane in 0..chunk {
6421                let obj_idx: usize = base_idx + lane;
6422                if !self.is_object_visible(obj_idx) {
6423                    continue;
6424                }
6425                let wb: AxisAlignedBox3D = objects[obj_idx].get_world_bounds();
6426                let dist_sq: f32 = wb.center().sub(cam_pos).length_sq();
6427                if chunk_on && dist_sq > draw_dist_sq {
6428                    continue;
6429                }
6430                let bmin: Vec3 = wb.get_min();
6431                let bmax: Vec3 = wb.get_max();
6432                min_x[lane] = bmin.get_x();
6433                min_y[lane] = bmin.get_y();
6434                min_z[lane] = bmin.get_z();
6435                max_x[lane] = bmax.get_x();
6436                max_y[lane] = bmax.get_y();
6437                max_z[lane] = bmax.get_z();
6438                vis_flags |= 1u8 << lane;
6439            }
6440            let frustum_mask: u8 = if frustum_on && vis_flags != 0 {
6441                let aabb4: SimdAabbBatch4 =
6442                    SimdAabbBatch4::new(min_x, min_y, min_z, max_x, max_y, max_z);
6443                cull_aabb_batch4_simd(&frustum_planes, &aabb4)
6444            } else {
6445                0x0F
6446            };
6447            let active_mask: u8 = vis_flags & frustum_mask;
6448            for lane in 0..chunk {
6449                let obj_idx: usize = base_idx + lane;
6450                let obj: &SceneObject3D = &objects[obj_idx];
6451                let mesh_id: usize = obj.get_mesh_id();
6452                let Some(chain) = mesh_lib.get(mesh_id) else {
6453                    continue;
6454                };
6455                if ((active_mask >> lane) & 1) == 0 {
6456                    if self.is_object_visible(obj_idx)
6457                        && let Some(base_mesh) = chain.get_levels().first()
6458                    {
6459                        let mcount: u32 = base_mesh.get_meshlets().len().max(1) as u32;
6460                        meshlets_tested = meshlets_tested.saturating_add(mcount);
6461                        meshlets_culled = meshlets_culled.saturating_add(mcount);
6462                    }
6463                    continue;
6464                }
6465                let wb: AxisAlignedBox3D = obj.get_world_bounds();
6466                let dist: f32 = wb.center().sub(cam_pos).length();
6467                let (selected_mesh, raw_lod): (&Mesh3D, usize) =
6468                    chain.select_screen_error(dist, wb.radius(), focal_px, lod_bias);
6469                let lod_idx: usize = raw_lod.min(3);
6470                let Some(lod_arr) = scratch.cached_lod_ranges.get(mesh_id) else {
6471                    continue;
6472                };
6473                let lod_range: CachedPbrLodRange = lod_arr[lod_idx];
6474                if lod_range.index_count == 0 {
6475                    continue;
6476                }
6477                let model_mat: Mat4 = obj.get_transform().to_mat4();
6478                let (m_tested, m_culled): (u32, u32) = if !selected_mesh.get_meshlets().is_empty() {
6479                    cull_meshlets_simd(
6480                        selected_mesh.get_meshlets().as_slice(),
6481                        &model_mat,
6482                        &frustum,
6483                        cam_pos,
6484                        selected_mesh.get_is_closed(),
6485                    )
6486                } else {
6487                    (1, 0)
6488                };
6489                meshlets_tested = meshlets_tested.saturating_add(m_tested);
6490                meshlets_culled = meshlets_culled.saturating_add(m_culled);
6491                if selected_mesh.get_is_closed() && m_tested > 0 && m_culled >= m_tested {
6492                    continue;
6493                }
6494                lod_counts[lod_idx] = lod_counts[lod_idx].saturating_add(1);
6495                let mat_slot: u32 = if let Some(pid) = obj.try_get_principled_material_id()
6496                    && (pid as usize) < fallback_mat_base
6497                {
6498                    pid
6499                } else {
6500                    Self::resolve_fallback_gpu_material(
6501                        obj.get_material(),
6502                        fallback_mat_base,
6503                        out.get_mut_materials(),
6504                    )
6505                };
6506                let mat_flags: u32 = out
6507                    .get_materials()
6508                    .get(mat_slot as usize)
6509                    .map_or(0, |m: &GpuMaterialData3D| m.get_flags_volume()[0]);
6510                let is_alpha_blend: bool = (mat_flags & GPU_MATERIAL_FLAG_ALPHA_BLEND) != 0;
6511                let mut inst_flags: u32 = 0;
6512                let mut bone_off: u32 = 0;
6513                let mut pso_variant: u8 = PBR_PSO_VARIANT_OPAQUE;
6514                if let Some(skin_id) = obj.try_get_skin_id()
6515                    && let Some(skin_ref) = skins.get(skin_id as usize)
6516                {
6517                    bone_off = out.get_bone_matrices().len() as u32;
6518                    skin_ref.compute_skin_matrices_into(model_mat, scene_graph, skin_scratch);
6519                    let palette: &[Mat4] = skin_scratch.get_skin_matrices().as_slice();
6520                    let dst_bones: &mut Vec<[f32; 16]> = out.get_mut_bone_matrices();
6521                    if dst_bones.capacity() < dst_bones.len() + palette.len() {
6522                        dst_bones.reserve(palette.len());
6523                    }
6524                    for bm in palette.iter() {
6525                        dst_bones.push(bm.get_elements());
6526                    }
6527                    inst_flags |= PBR_INST_FLAG_SKINNED;
6528                    if skin_ref.get_skinning_mode() == SkinningMode::DualQuaternion {
6529                        inst_flags |= PBR_INST_FLAG_DQS;
6530                    }
6531                    pso_variant = PBR_PSO_VARIANT_SKINNED;
6532                }
6533                let mut morph_off: u32 = 0;
6534                if lod_range.has_morphs
6535                    && let Some(node_id) = obj.try_get_node_id()
6536                {
6537                    let mweights: &[f32] = scene_graph.morph_weights_for_node(node_id);
6538                    if !mweights.is_empty() {
6539                        morph_off = out.get_morph_weights().len() as u32;
6540                        let dst_mw: &mut Vec<f32> = out.get_mut_morph_weights();
6541                        for k in 0..4 {
6542                            dst_mw.push(mweights.get(k).copied().unwrap_or(0.0));
6543                        }
6544                        inst_flags |= PBR_INST_FLAG_MORPHED;
6545                    }
6546                }
6547                let alpha_pass: u8 = if is_alpha_blend {
6548                    pso_variant = PBR_PSO_VARIANT_ALPHA_BLEND;
6549                    inst_flags |= PBR_INST_FLAG_ALPHA_BLEND;
6550                    1
6551                } else {
6552                    0
6553                };
6554                let depth_q16: u16 = ((dist * inv_far).clamp(0.0, 1.0) * 65_535.0).round() as u16;
6555                let sort_key: u64 = pack_pbr_sort_key(
6556                    alpha_pass,
6557                    pso_variant,
6558                    mat_slot,
6559                    mesh_id as u32,
6560                    lod_idx as u8,
6561                    depth_q16,
6562                );
6563                let mut q_origin: [f32; 4] = lod_range.bounds_min;
6564                q_origin[3] = f32::from_bits(obj_idx as u32);
6565                let mut q_extent: [f32; 4] = lod_range.bounds_extent;
6566                q_extent[3] = lod_idx as f32;
6567                let instance: GpuPbrInstance3D = GpuPbrInstance3D::new(
6568                    model_mat.get_elements(),
6569                    q_origin,
6570                    q_extent,
6571                    [mat_slot, bone_off, morph_off, inst_flags],
6572                );
6573                scratch.batcher.get_mut_entries().push(PbrSortEntry3D {
6574                    sort_key,
6575                    index_start: lod_range.index_start,
6576                    index_count: lod_range.index_count,
6577                    base_vertex: 0,
6578                    material_index: mat_slot,
6579                    pso_variant,
6580                    lod_level: lod_idx as u8,
6581                    instance,
6582                });
6583            }
6584            base_idx += 4;
6585        }
6586        let draw_call_count: u32 = {
6587            let GpuPbrScenePass {
6588                instances,
6589                draw_batches,
6590                ..
6591            } = out;
6592            coalesce_pbr_batches_into(&mut scratch.batcher, instances, draw_batches)
6593        };
6594        let textures: &[Texture2D3D] = self.get_textures().as_slice();
6595        if scratch.uploaded_texture_min_mip.len() < textures.len() {
6596            scratch
6597                .uploaded_texture_min_mip
6598                .resize(textures.len(), u8::MAX);
6599        }
6600        for (slot_idx, tex) in textures.iter().enumerate() {
6601            let mips: &[TextureMipLevel3D] = tex.get_mips().as_slice();
6602            if mips.is_empty() {
6603                continue;
6604            }
6605            let current_min: u8 = scratch.uploaded_texture_min_mip[slot_idx];
6606            if current_min == 0 {
6607                continue;
6608            }
6609            let total_mips: u8 = mips.len().min(16) as u8;
6610            let (target_mip, priority): (u8, StreamPriority) = if current_min == u8::MAX {
6611                (total_mips.saturating_sub(1), StreamPriority::Critical)
6612            } else {
6613                let next_mip: u8 = current_min.saturating_sub(1);
6614                let prio: StreamPriority = if next_mip > 0 {
6615                    StreamPriority::VisibleHigh
6616                } else {
6617                    StreamPriority::PrefetchMedium
6618                };
6619                (next_mip, prio)
6620            };
6621            if let Some(mip_data) = mips.get(target_mip as usize) {
6622                let upload: GpuTextureMipUpload = GpuTextureMipUpload {
6623                    texture_slot: slot_idx as u32,
6624                    mip_level: target_mip,
6625                    total_mip_levels: total_mips,
6626                    is_srgb: tex.get_color_space() == TextureColorSpace::Srgb,
6627                    min_lod_clamp: target_mip,
6628                    width: mip_data.get_width(),
6629                    height: mip_data.get_height(),
6630                    rgba8: mip_data.get_pixels().clone(),
6631                };
6632                let _: GpuUploadTicket = belt.enqueue_mip_upload(priority, upload);
6633            }
6634        }
6635        let _: usize = belt.drain_mip_uploads_into(out.get_mut_texture_uploads());
6636        for uploaded in out.get_texture_uploads().iter() {
6637            let slot_idx: usize = uploaded.get_texture_slot() as usize;
6638            if let Some(watermark) = scratch.uploaded_texture_min_mip.get_mut(slot_idx) {
6639                *watermark = (*watermark).min(uploaded.get_mip_level());
6640            }
6641        }
6642        let fog_density: f32 = if quality.get_volumetric_fog() {
6643            0.0028
6644        } else {
6645            0.0008
6646        };
6647        let agx_flag: f32 = if self.get_use_agx_tonemap() { 1.0 } else { 0.0 };
6648        out.set_target_width(target_width);
6649        out.set_target_height(target_height);
6650        out.set_prev_view_proj(prev_vp);
6651        out.set_view_proj(view_proj_mat.get_elements());
6652        out.set_camera_pos_exposure([cam_pos.get_x(), cam_pos.get_y(), cam_pos.get_z(), 1.15]);
6653        out.set_sun_dir_fog([
6654            sun_dir.get_x(),
6655            sun_dir.get_y(),
6656            sun_dir.get_z(),
6657            fog_density,
6658        ]);
6659        out.set_sun_color_ambient([sun_col.get_x(), sun_col.get_y(), sun_col.get_z(), 0.34]);
6660        out.set_sky_horizon_tod([
6661            sky_hor.get_x(),
6662            sky_hor.get_y(),
6663            sky_hor.get_z(),
6664            sun.get_time_of_day(),
6665        ]);
6666        out.set_sky_zenith_agx([sky_zen.get_x(), sky_zen.get_y(), sky_zen.get_z(), agx_flag]);
6667        out.set_ibl_sh(ibl_sh);
6668        out.set_mesh_buffer(Arc::clone(&scratch.cached_mesh_buffer));
6669        let stats: GpuPbrCullStats = GpuPbrCullStats::new(
6670            meshlets_tested,
6671            meshlets_culled,
6672            lod_counts,
6673            draw_call_count,
6674            belt.get_frame_bytes_used(),
6675            belt.get_frame_time_us_used(),
6676        );
6677        out.set_stats(stats);
6678    }
6679
6680    /// 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.
6681    ///
6682    /// # Arguments
6683    ///
6684    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
6685    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, LOD bias, and fog.
6686    /// - `&mut GpuUploadBelt` - Frame-budgeted GPU staging belt enforcing `<= 4 MiB` and `<= 1.5 ms` ceilings.
6687    /// - `&mut GpuPbrScenePass` - Recycled PBR scene pass destination populated in-place.
6688    pub fn build_gpu_pbr_scene_pass_into(
6689        &mut self,
6690        viewport: (u32, u32),
6691        quality: &RenderQualityConfig,
6692        belt: &mut GpuUploadBelt,
6693        out: &mut GpuPbrScenePass,
6694    ) {
6695        let (mut pbr_work, mut skin_work): (World3dPbrPassScratch, SkinPaletteScratch3D) = {
6696            let Self {
6697                pbr_pass_scratch,
6698                skin_scratch,
6699                ..
6700            } = self;
6701            (take(pbr_pass_scratch), take(skin_scratch))
6702        };
6703        self.populate_gpu_pbr_scene_pass_with_scratch(
6704            viewport,
6705            quality,
6706            belt,
6707            &mut pbr_work,
6708            &mut skin_work,
6709            out,
6710        );
6711        let Self {
6712            pbr_pass_scratch,
6713            skin_scratch,
6714            ..
6715        } = self;
6716        *pbr_pass_scratch = pbr_work;
6717        *skin_scratch = skin_work;
6718    }
6719
6720    /// 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.
6721    ///
6722    /// # Arguments
6723    ///
6724    /// - `&Self` - World reference.
6725    /// - `&DoubleBufferedSnapshot<World3DSnapshot>` - Double-buffered dynamic object and camera snapshots.
6726    /// - `f32` - Render interpolation alpha in `[0.0, 1.0]`.
6727    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
6728    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, and fog.
6729    /// - `(&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)])` - Cached static mesh buffer and per-mesh `(vertex_start, vertex_count)` ranges.
6730    ///
6731    /// # Returns
6732    ///
6733    /// - `GpuWorld3dScenePass` - Hardware instanced 3D scene pass descriptor ready for Metal, GLES3, D3D11, or WebGL2.
6734    #[must_use]
6735    pub fn build_gpu_scene_pass(
6736        &self,
6737        snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
6738        alpha: f32,
6739        viewport: (u32, u32),
6740        quality: &RenderQualityConfig,
6741        mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
6742    ) -> GpuWorld3dScenePass {
6743        let mut out: GpuWorld3dScenePass = GpuWorld3dScenePass::default();
6744        let used_tls: bool = WORLD3D_GPU_PASS_SCRATCH
6745            .try_with(|cell: &RefCell<World3dGpuPassScratch>| -> bool {
6746                if let Ok(mut scratch) = cell.try_borrow_mut() {
6747                    self.populate_gpu_scene_pass_with_scratch(
6748                        snapshots,
6749                        alpha,
6750                        viewport,
6751                        quality,
6752                        mesh_cache,
6753                        (&mut scratch, &mut out),
6754                    );
6755                    true
6756                } else {
6757                    false
6758                }
6759            })
6760            .unwrap_or(false);
6761        if !used_tls {
6762            let mut local_scratch: World3dGpuPassScratch = World3dGpuPassScratch::default();
6763            self.populate_gpu_scene_pass_with_scratch(
6764                snapshots,
6765                alpha,
6766                viewport,
6767                quality,
6768                mesh_cache,
6769                (&mut local_scratch, &mut out),
6770            );
6771        }
6772        out
6773    }
6774}
6775
6776/// Perspective and Orthographic projection matrix builders for `SceneCamera3D`.
6777impl SceneCamera3D {
6778    /// Builds a `SceneCamera3D` from an imported glTF/Blender `ImportedCamera3D` and node world pose.
6779    ///
6780    /// # Arguments
6781    ///
6782    /// - `&ImportedCamera3D` - Imported camera parameters.
6783    /// - `Option<u32>` - Optional owning scene-graph node index.
6784    /// - `Vec3` - World-space camera eye position.
6785    /// - `Quat` - World-space camera orientation quaternion.
6786    ///
6787    /// # Returns
6788    ///
6789    /// - `Self` - Constructed multi-camera entry.
6790    #[must_use]
6791    pub fn from_imported(
6792        imported: &ImportedCamera3D,
6793        node_id: Option<u32>,
6794        position: Vec3,
6795        rotation: Quat,
6796    ) -> Self {
6797        Self {
6798            name: imported.get_name().clone(),
6799            node_id,
6800            position,
6801            rotation: rotation.normalize(),
6802            projection: imported.get_projection(),
6803        }
6804    }
6805
6806    /// Returns the unit world-space forward direction along glTF local `-Z`.
6807    ///
6808    /// # Returns
6809    ///
6810    /// - `Vec3` - Unit forward vector.
6811    #[must_use]
6812    pub fn forward(&self) -> Vec3 {
6813        self.get_rotation()
6814            .rotate_vec3(Vec3::new(0.0, 0.0, -1.0))
6815            .normalize()
6816    }
6817
6818    /// Returns the unit world-space right direction along glTF local `+X`.
6819    ///
6820    /// # Returns
6821    ///
6822    /// - `Vec3` - Unit right vector.
6823    #[must_use]
6824    pub fn right(&self) -> Vec3 {
6825        self.get_rotation()
6826            .rotate_vec3(Vec3::new(1.0, 0.0, 0.0))
6827            .normalize()
6828    }
6829
6830    /// Returns the unit world-space up direction along glTF local `+Y`.
6831    ///
6832    /// # Returns
6833    ///
6834    /// - `Vec3` - Unit up vector.
6835    #[must_use]
6836    pub fn up(&self) -> Vec3 {
6837        self.get_rotation()
6838            .rotate_vec3(Vec3::new(0.0, 1.0, 0.0))
6839            .normalize()
6840    }
6841
6842    /// Returns `true` when this camera uses orthographic projection.
6843    ///
6844    /// # Returns
6845    ///
6846    /// - `bool` - Whether projection is orthographic.
6847    #[must_use]
6848    pub fn is_orthographic(&self) -> bool {
6849        matches!(
6850            self.get_projection(),
6851            GltfCameraProjection::Orthographic { .. }
6852        )
6853    }
6854
6855    /// Computes the combined `projection * view` matrix supporting both Perspective and Orthographic projections.
6856    ///
6857    /// # Arguments
6858    ///
6859    /// - `&Self` - Scene camera reference.
6860    /// - `f32` - Active viewport aspect ratio `width / height`.
6861    ///
6862    /// # Returns
6863    ///
6864    /// - `Mat4` - Combined view-projection matrix.
6865    #[must_use]
6866    pub fn view_projection(&self, viewport_aspect: f32) -> Mat4 {
6867        let pos: Vec3 = self.get_position();
6868        let view: Mat4 = Mat4::look_at(pos, pos.add(self.forward()), self.up());
6869        let proj: Mat4 = match self.get_projection() {
6870            GltfCameraProjection::Perspective {
6871                yfov_rad,
6872                aspect_ratio,
6873                znear,
6874                zfar,
6875            } => Mat4::perspective(
6876                yfov_rad.clamp(0.15, 2.6),
6877                aspect_ratio.unwrap_or(viewport_aspect).max(0.1),
6878                znear.max(0.02),
6879                zfar.unwrap_or(480.0).max(znear + 1.0),
6880            ),
6881            GltfCameraProjection::Orthographic {
6882                xmag,
6883                ymag,
6884                znear,
6885                zfar,
6886            } => Mat4::orthographic_mag(xmag, ymag, znear.max(0.01), zfar.max(znear + 1.0)),
6887        };
6888        proj.mul(view)
6889    }
6890
6891    /// Projects this scene camera to a compatible `Camera3D` for primary viewport synchronization.
6892    ///
6893    /// # Returns
6894    ///
6895    /// - `Camera3D` - Equivalent perspective viewport camera descriptor.
6896    #[must_use]
6897    pub fn to_camera3d(&self) -> Camera3D {
6898        let fwd: Vec3 = self.forward();
6899        let yaw_val: f32 = fwd.get_z().atan2(fwd.get_x());
6900        let pitch_val: f32 = fwd.get_y().clamp(-0.98, 0.98).asin();
6901        let (fov_deg, near_val, far_val): (f32, f32, f32) = match self.get_projection() {
6902            GltfCameraProjection::Perspective {
6903                yfov_rad,
6904                znear,
6905                zfar,
6906                ..
6907            } => (
6908                yfov_rad.to_degrees().clamp(12.0, 120.0),
6909                znear.max(0.05),
6910                zfar.unwrap_or(480.0).max(10.0),
6911            ),
6912            GltfCameraProjection::Orthographic { znear, zfar, .. } => {
6913                (45.0, znear.max(0.05), zfar.max(10.0))
6914            }
6915        };
6916        let mut cam: Camera3D = Camera3D::default();
6917        cam.set_position(self.get_position());
6918        cam.set_yaw(yaw_val);
6919        cam.set_pitch(pitch_val);
6920        cam.set_fov_deg(fov_deg);
6921        cam.set_near(near_val);
6922        cam.set_far(far_val);
6923        cam
6924    }
6925}