Skip to main content

euv_core/game/engine3d/math/
impl.rs

1use super::*;
2
3/// Vector arithmetic, normalization, dot/cross products, and reflection helpers for `Vec3`.
4impl Vec3 {
5    /// Zero vector `(0, 0, 0)`.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Zero vector.
10    #[must_use]
11    pub const fn zero() -> Self {
12        Self {
13            x: 0.0,
14            y: 0.0,
15            z: 0.0,
16        }
17    }
18
19    /// Uniform vector `(v, v, v)`.
20    ///
21    /// # Arguments
22    ///
23    /// - `f32` - Scalar value replicated across all axes.
24    ///
25    /// # Returns
26    ///
27    /// - `Self` - Splat vector.
28    #[must_use]
29    pub const fn splat(v: f32) -> Self {
30        Self { x: v, y: v, z: v }
31    }
32
33    /// Scales `self` by scalar `s`.
34    ///
35    /// # Arguments
36    ///
37    /// - `Self` - Source vector.
38    /// - `f32` - Scalar multiplier.
39    ///
40    /// # Returns
41    ///
42    /// - `Self` - Scaled vector.
43    #[must_use]
44    pub fn scale(self, s: f32) -> Self {
45        Self {
46            x: self.get_x() * s,
47            y: self.get_y() * s,
48            z: self.get_z() * s,
49        }
50    }
51
52    /// Computes the dot product `self · rhs`.
53    ///
54    /// # Arguments
55    ///
56    /// - `Self` - Left vector.
57    /// - `Self` - Right vector.
58    ///
59    /// # Returns
60    ///
61    /// - `f32` - Scalar dot product.
62    #[must_use]
63    pub fn dot(self, rhs: Self) -> f32 {
64        self.get_x() * rhs.get_x() + self.get_y() * rhs.get_y() + self.get_z() * rhs.get_z()
65    }
66
67    /// Computes the 3D cross product `self × rhs`.
68    ///
69    /// # Arguments
70    ///
71    /// - `Self` - Left vector.
72    /// - `Self` - Right vector.
73    ///
74    /// # Returns
75    ///
76    /// - `Self` - Orthogonal cross product vector.
77    #[must_use]
78    pub fn cross(self, rhs: Self) -> Self {
79        Self {
80            x: self.get_y() * rhs.get_z() - self.get_z() * rhs.get_y(),
81            y: self.get_z() * rhs.get_x() - self.get_x() * rhs.get_z(),
82            z: self.get_x() * rhs.get_y() - self.get_y() * rhs.get_x(),
83        }
84    }
85
86    /// Computes squared Euclidean length.
87    ///
88    /// # Arguments
89    ///
90    /// - `Self` - Source vector.
91    ///
92    /// # Returns
93    ///
94    /// - `f32` - Squared magnitude.
95    #[must_use]
96    pub fn length_sq(self) -> f32 {
97        self.dot(self)
98    }
99
100    /// Computes Euclidean length.
101    ///
102    /// # Arguments
103    ///
104    /// - `Self` - Source vector.
105    ///
106    /// # Returns
107    ///
108    /// - `f32` - Magnitude.
109    #[must_use]
110    pub fn length(self) -> f32 {
111        self.length_sq().sqrt()
112    }
113
114    /// Returns a unit-length vector pointing along `self`, or `(0, 1, 0)` if degenerate.
115    ///
116    /// # Arguments
117    ///
118    /// - `Self` - Source vector.
119    ///
120    /// # Returns
121    ///
122    /// - `Self` - Normalized unit vector.
123    #[must_use]
124    pub fn normalize(self) -> Self {
125        let len: f32 = self.length();
126        if len > 1e-6 {
127            self.scale(1.0 / len)
128        } else {
129            Self::new(0.0, 1.0, 0.0)
130        }
131    }
132
133    /// Linearly interpolates between `self` and `other` by `t`.
134    ///
135    /// # Arguments
136    ///
137    /// - `Self` - Start vector.
138    /// - `Self` - End vector.
139    /// - `f32` - Interpolation factor.
140    ///
141    /// # Returns
142    ///
143    /// - `Self` - Interpolated vector.
144    #[must_use]
145    pub fn lerp(self, other: Self, t: f32) -> Self {
146        Self {
147            x: self.get_x() + (other.get_x() - self.get_x()) * t,
148            y: self.get_y() + (other.get_y() - self.get_y()) * t,
149            z: self.get_z() + (other.get_z() - self.get_z()) * t,
150        }
151    }
152
153    /// Reflects incident vector `self` across unit surface normal `normal`.
154    ///
155    /// # Arguments
156    ///
157    /// - `Self` - Incident vector.
158    /// - `Self` - Unit surface normal.
159    ///
160    /// # Returns
161    ///
162    /// - `Self` - Reflected direction vector.
163    #[must_use]
164    pub fn reflect(self, normal: Self) -> Self {
165        self.sub(normal.scale(2.0 * self.dot(normal)))
166    }
167
168    /// Returns component-wise minimum of `self` and `rhs`.
169    ///
170    /// # Arguments
171    ///
172    /// - `Self` - Left vector.
173    /// - `Self` - Right vector.
174    ///
175    /// # Returns
176    ///
177    /// - `Self` - Component-wise minimum.
178    #[must_use]
179    pub fn min(self, rhs: Self) -> Self {
180        Self {
181            x: self.get_x().min(rhs.get_x()),
182            y: self.get_y().min(rhs.get_y()),
183            z: self.get_z().min(rhs.get_z()),
184        }
185    }
186
187    /// Returns component-wise maximum of `self` and `rhs`.
188    ///
189    /// # Arguments
190    ///
191    /// - `Self` - Left vector.
192    /// - `Self` - Right vector.
193    ///
194    /// # Returns
195    ///
196    /// - `Self` - Component-wise maximum.
197    #[must_use]
198    pub fn max(self, rhs: Self) -> Self {
199        Self {
200            x: self.get_x().max(rhs.get_x()),
201            y: self.get_y().max(rhs.get_y()),
202            z: self.get_z().max(rhs.get_z()),
203        }
204    }
205
206    /// Converts an sRGB `Color` into linear RGB `Vec3` radiance in `[0.0, 1.0]`.
207    ///
208    /// # Arguments
209    ///
210    /// - `Color` - Source RGBA color.
211    ///
212    /// # Returns
213    ///
214    /// - `Self` - Normalized linear RGB vector.
215    #[must_use]
216    pub fn from_color(c: Color) -> Self {
217        Self {
218            x: (c.get_r() as f32) / 255.0,
219            y: (c.get_g() as f32) / 255.0,
220            z: (c.get_b() as f32) / 255.0,
221        }
222    }
223
224    /// Maps a single HDR channel through the ACES filmic tone curve into sRGB byte space.
225    ///
226    /// # Arguments
227    ///
228    /// - `f32` - Linear HDR scalar.
229    ///
230    /// # Returns
231    ///
232    /// - `u8` - Gamma-encoded sRGB byte.
233    #[must_use]
234    fn aces_channel(v: f32) -> u8 {
235        let x: f32 = v.max(0.0);
236        let mapped: f32 = (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14);
237        let idx: usize = ((mapped.clamp(0.0, 1.0) * 1024.0) + 0.5) as usize;
238        LINEAR_TO_SRGB_LUT[idx.min(1024)]
239    }
240
241    /// Applies ACES filmic tone mapping and converts linear radiance to RGBA8 `[r, g, b, 255]`.
242    ///
243    /// # Arguments
244    ///
245    /// - `Self` - Linear HDR RGB radiance.
246    ///
247    /// # Returns
248    ///
249    /// - `[u8; 4]` - Tone-mapped RGBA8 pixel bytes.
250    #[must_use]
251    pub fn to_aces_rgba8(self) -> [u8; 4] {
252        [
253            Self::aces_channel(self.get_x()),
254            Self::aces_channel(self.get_y()),
255            Self::aces_channel(self.get_z()),
256            255,
257        ]
258    }
259}
260
261/// Component-wise vector addition for `Vec3`.
262impl Add for Vec3 {
263    type Output = Self;
264
265    /// Adds two vectors component-wise.
266    ///
267    /// # Arguments
268    ///
269    /// - `Self` - Left vector.
270    /// - `Self` - Right vector.
271    ///
272    /// # Returns
273    ///
274    /// - `Self` - Component-wise sum.
275    fn add(self, rhs: Self) -> Self {
276        Self {
277            x: self.get_x() + rhs.get_x(),
278            y: self.get_y() + rhs.get_y(),
279            z: self.get_z() + rhs.get_z(),
280        }
281    }
282}
283
284/// Component-wise vector subtraction for `Vec3`.
285impl Sub for Vec3 {
286    type Output = Self;
287
288    /// Subtracts `rhs` from `self`.
289    ///
290    /// # Arguments
291    ///
292    /// - `Self` - Left vector.
293    /// - `Self` - Right vector.
294    ///
295    /// # Returns
296    ///
297    /// - `Self` - Component-wise difference.
298    fn sub(self, rhs: Self) -> Self {
299        Self {
300            x: self.get_x() - rhs.get_x(),
301            y: self.get_y() - rhs.get_y(),
302            z: self.get_z() - rhs.get_z(),
303        }
304    }
305}
306
307/// Component-wise Hadamard vector multiplication for `Vec3`.
308impl Mul for Vec3 {
309    type Output = Self;
310
311    /// Multiplies two vectors component-wise.
312    ///
313    /// # Arguments
314    ///
315    /// - `Self` - Left vector.
316    /// - `Self` - Right vector.
317    ///
318    /// # Returns
319    ///
320    /// - `Self` - Component-wise product.
321    fn mul(self, rhs: Self) -> Self {
322        Self {
323            x: self.get_x() * rhs.get_x(),
324            y: self.get_y() * rhs.get_y(),
325            z: self.get_z() * rhs.get_z(),
326        }
327    }
328}
329
330/// Matrix multiplication `self * rhs` for `Mat4`.
331impl Mul for Mat4 {
332    type Output = Self;
333
334    /// Multiplies `self * rhs`.
335    ///
336    /// # Arguments
337    ///
338    /// - `Self` - Left matrix.
339    /// - `Self` - Right matrix.
340    ///
341    /// # Returns
342    ///
343    /// - `Self` - Product matrix.
344    fn mul(self, rhs: Self) -> Self {
345        let a: [f32; 16] = self.get_m();
346        let b: [f32; 16] = rhs.get_m();
347        let mut out: [f32; 16] = [0.0; 16];
348        for col in 0..4 {
349            for row in 0..4 {
350                out[col * 4 + row] = a[row] * b[col * 4]
351                    + a[4 + row] * b[col * 4 + 1]
352                    + a[8 + row] * b[col * 4 + 2]
353                    + a[12 + row] * b[col * 4 + 3];
354            }
355        }
356        Self { m: out }
357    }
358}
359
360/// Matrix constructors, projection, and point projection for `Mat4`.
361impl Mat4 {
362    /// Identity 4x4 matrix.
363    ///
364    /// # Returns
365    ///
366    /// - `Self` - Identity matrix.
367    #[must_use]
368    pub const fn identity() -> Self {
369        Self {
370            m: [
371                1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
372            ],
373        }
374    }
375
376    /// Builds a right-handed perspective projection matrix.
377    ///
378    /// # Arguments
379    ///
380    /// - `f32` - Vertical FOV in radians.
381    /// - `f32` - Viewport aspect ratio `width / height`.
382    /// - `f32` - Near plane distance.
383    /// - `f32` - Far plane distance.
384    ///
385    /// # Returns
386    ///
387    /// - `Self` - Perspective projection matrix.
388    #[must_use]
389    pub fn perspective(fov_rad: f32, aspect: f32, near: f32, far: f32) -> Self {
390        let f: f32 = 1.0 / (fov_rad * 0.5).tan().max(1e-4);
391        let nf: f32 = 1.0 / (near - far);
392        Self {
393            m: [
394                f / aspect.max(0.01),
395                0.0,
396                0.0,
397                0.0,
398                0.0,
399                f,
400                0.0,
401                0.0,
402                0.0,
403                0.0,
404                (far + near) * nf,
405                -1.0,
406                0.0,
407                0.0,
408                2.0 * far * near * nf,
409                0.0,
410            ],
411        }
412    }
413
414    /// Builds a right-handed look-at view matrix.
415    ///
416    /// # Arguments
417    ///
418    /// - `Vec3` - Camera eye position.
419    /// - `Vec3` - Target look-at position.
420    /// - `Vec3` - World up direction.
421    ///
422    /// # Returns
423    ///
424    /// - `Self` - View transformation matrix.
425    #[must_use]
426    pub fn look_at(eye: Vec3, target: Vec3, up: Vec3) -> Self {
427        let f: Vec3 = target.sub(eye).normalize();
428        let s: Vec3 = f.cross(up).normalize();
429        let u: Vec3 = s.cross(f);
430        Self {
431            m: [
432                s.get_x(),
433                u.get_x(),
434                -f.get_x(),
435                0.0,
436                s.get_y(),
437                u.get_y(),
438                -f.get_y(),
439                0.0,
440                s.get_z(),
441                u.get_z(),
442                -f.get_z(),
443                0.0,
444                -s.dot(eye),
445                -u.dot(eye),
446                f.dot(eye),
447                1.0,
448            ],
449        }
450    }
451
452    /// Builds a TRS model matrix (`translate * rotate_y * scale`).
453    ///
454    /// # Arguments
455    ///
456    /// - `Vec3` - World translation.
457    /// - `f32` - Y-axis yaw rotation in radians.
458    /// - `Vec3` - Non-uniform scale.
459    ///
460    /// # Returns
461    ///
462    /// - `Self` - Composed model transform matrix.
463    #[must_use]
464    pub fn from_trs(position: Vec3, yaw_rad: f32, scale: Vec3) -> Self {
465        let c: f32 = yaw_rad.cos();
466        let s: f32 = yaw_rad.sin();
467        Self {
468            m: [
469                c * scale.get_x(),
470                0.0,
471                -s * scale.get_x(),
472                0.0,
473                0.0,
474                scale.get_y(),
475                0.0,
476                0.0,
477                s * scale.get_z(),
478                0.0,
479                c * scale.get_z(),
480                0.0,
481                position.get_x(),
482                position.get_y(),
483                position.get_z(),
484                1.0,
485            ],
486        }
487    }
488
489    /// Builds a full 3D Euler TRS model matrix (`translate * rotate_y(yaw) * rotate_x(pitch) * rotate_z(roll) * scale`).
490    ///
491    /// # Arguments
492    ///
493    /// - `Vec3` - World translation.
494    /// - `f32` - Y-axis yaw rotation in radians.
495    /// - `f32` - X-axis pitch rotation in radians.
496    /// - `f32` - Z-axis roll rotation in radians.
497    /// - `Vec3` - Non-uniform scale.
498    ///
499    /// # Returns
500    ///
501    /// - `Self` - Composed 3D model transform matrix.
502    #[must_use]
503    pub fn from_trs_euler(
504        position: Vec3,
505        yaw_rad: f32,
506        pitch_rad: f32,
507        roll_rad: f32,
508        scale: Vec3,
509    ) -> Self {
510        if pitch_rad.abs() < 1e-6 && roll_rad.abs() < 1e-6 {
511            return Self::from_trs(position, yaw_rad, scale);
512        }
513        let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
514        let (cp, sp): (f32, f32) = (pitch_rad.cos(), pitch_rad.sin());
515        let (cr, sr): (f32, f32) = (roll_rad.cos(), roll_rad.sin());
516        let r00: f32 = cy * cr + sy * sp * sr;
517        let r10: f32 = cp * sr;
518        let r20: f32 = -sy * cr + cy * sp * sr;
519        let r01: f32 = -cy * sr + sy * sp * cr;
520        let r11: f32 = cp * cr;
521        let r21: f32 = sy * sr + cy * sp * cr;
522        let r02: f32 = sy * cp;
523        let r12: f32 = -sp;
524        let r22: f32 = cy * cp;
525        let sx: f32 = scale.get_x();
526        let sy_sc: f32 = scale.get_y();
527        let sz: f32 = scale.get_z();
528        Self {
529            m: [
530                r00 * sx,
531                r10 * sx,
532                r20 * sx,
533                0.0,
534                r01 * sy_sc,
535                r11 * sy_sc,
536                r21 * sy_sc,
537                0.0,
538                r02 * sz,
539                r12 * sz,
540                r22 * sz,
541                0.0,
542                position.get_x(),
543                position.get_y(),
544                position.get_z(),
545                1.0,
546            ],
547        }
548    }
549
550    /// Transforms a 3D point returning homogeneous clip coordinates `(x, y, z, w)`.
551    ///
552    /// # Arguments
553    ///
554    /// - `&Self` - Transformation matrix.
555    /// - `Vec3` - Input 3D position.
556    ///
557    /// # Returns
558    ///
559    /// - `[f32; 4]` - Homogeneous clip-space coordinates.
560    #[must_use]
561    pub fn mul_point4(&self, p: Vec3) -> [f32; 4] {
562        let m: [f32; 16] = self.get_m();
563        [
564            m[0] * p.get_x() + m[4] * p.get_y() + m[8] * p.get_z() + m[12],
565            m[1] * p.get_x() + m[5] * p.get_y() + m[9] * p.get_z() + m[13],
566            m[2] * p.get_x() + m[6] * p.get_y() + m[10] * p.get_z() + m[14],
567            m[3] * p.get_x() + m[7] * p.get_y() + m[11] * p.get_z() + m[15],
568        ]
569    }
570}
571
572/// Bounding-box union, centroid, surface area, and ray-slab intersection for `Aabb3D`.
573impl Aabb3D {
574    /// Creates an inverted empty AABB ready to accumulate points via `expand_point`.
575    ///
576    /// # Returns
577    ///
578    /// - `Self` - Empty AABB.
579    #[must_use]
580    pub const fn empty() -> Self {
581        Self {
582            min: Vec3::splat(f32::INFINITY),
583            max: Vec3::splat(f32::NEG_INFINITY),
584        }
585    }
586
587    /// Expands this bounding box to include `point`.
588    ///
589    /// # Arguments
590    ///
591    /// - `&Self` - Mutable AABB.
592    /// - `Vec3` - Point to enclose.
593    pub fn expand_point(&mut self, point: Vec3) {
594        let mn: Vec3 = self.get_min().min(point);
595        let mx: Vec3 = self.get_max().max(point);
596        self.set_min(mn);
597        self.set_max(mx);
598    }
599
600    /// Expands this bounding box to include `other`.
601    ///
602    /// # Arguments
603    ///
604    /// - `&Self` - Mutable AABB.
605    /// - `Self` - Other bounding box.
606    pub fn expand_box(&mut self, other: Self) {
607        let mn: Vec3 = self.get_min().min(other.get_min());
608        let mx: Vec3 = self.get_max().max(other.get_max());
609        self.set_min(mn);
610        self.set_max(mx);
611    }
612
613    /// Returns the geometric center of the AABB.
614    ///
615    /// # Arguments
616    ///
617    /// - `&Self` - AABB reference.
618    ///
619    /// # Returns
620    ///
621    /// - `Vec3` - Box centroid.
622    #[must_use]
623    pub fn center(&self) -> Vec3 {
624        self.get_min().add(self.get_max()).scale(0.5)
625    }
626
627    /// Computes bounding-sphere radius enclosing this box.
628    ///
629    /// # Arguments
630    ///
631    /// - `&Self` - AABB reference.
632    ///
633    /// # Returns
634    ///
635    /// - `f32` - Enclosing radius.
636    #[must_use]
637    pub fn radius(&self) -> f32 {
638        self.get_max().sub(self.get_min()).length() * 0.5
639    }
640
641    /// Computes half surface area (`dx*dy + dy*dz + dz*dx`) for Surface Area Heuristic (SAH) BVH splits.
642    ///
643    /// # Arguments
644    ///
645    /// - `&Self` - AABB reference.
646    ///
647    /// # Returns
648    ///
649    /// - `f32` - Non-negative half surface area.
650    #[must_use]
651    pub fn surface_area(&self) -> f32 {
652        let d: Vec3 = self.get_max().sub(self.get_min());
653        let dx: f32 = d.get_x().max(0.0);
654        let dy: f32 = d.get_y().max(0.0);
655        let dz: f32 = d.get_z().max(0.0);
656        dx * dy + dy * dz + dz * dx
657    }
658
659    /// Branchless slab Ray-AABB intersection returning entry distance `tmin` or `f32::INFINITY` on miss.
660    ///
661    /// # Arguments
662    ///
663    /// - `&Self` - AABB reference.
664    /// - `Vec3` - Ray origin.
665    /// - `Vec3` - Precomputed safe reciprocal ray direction.
666    /// - `f32` - Minimum valid distance.
667    /// - `f32` - Maximum valid distance.
668    ///
669    /// # Returns
670    ///
671    /// - `f32` - Near intersection distance if hit, or `f32::INFINITY` if missed.
672    #[must_use]
673    pub fn intersect_ray_near(&self, origin: Vec3, inv_dir: Vec3, t_min: f32, t_max: f32) -> f32 {
674        let mn: Vec3 = self.get_min();
675        let mx: Vec3 = self.get_max();
676        let tx1: f32 = (mn.get_x() - origin.get_x()) * inv_dir.get_x();
677        let tx2: f32 = (mx.get_x() - origin.get_x()) * inv_dir.get_x();
678        let mut tmin: f32 = t_min.max(tx1.min(tx2));
679        let mut tmax: f32 = t_max.min(tx1.max(tx2));
680        let ty1: f32 = (mn.get_y() - origin.get_y()) * inv_dir.get_y();
681        let ty2: f32 = (mx.get_y() - origin.get_y()) * inv_dir.get_y();
682        tmin = tmin.max(ty1.min(ty2));
683        tmax = tmax.min(ty1.max(ty2));
684        let tz1: f32 = (mn.get_z() - origin.get_z()) * inv_dir.get_z();
685        let tz2: f32 = (mx.get_z() - origin.get_z()) * inv_dir.get_z();
686        tmin = tmin.max(tz1.min(tz2));
687        tmax = tmax.min(tz1.max(tz2));
688        if tmax >= tmin && tmax >= 0.0 {
689            tmin
690        } else {
691            f32::INFINITY
692        }
693    }
694
695    /// Branchless slab Ray-AABB intersection returning `true` when `ray` hits within `[t_min, t_max]`.
696    ///
697    /// # Arguments
698    ///
699    /// - `&Self` - AABB reference.
700    /// - `&Ray3D` - Ray with precomputed inverse direction.
701    /// - `f32` - Minimum valid distance.
702    /// - `f32` - Maximum valid distance.
703    ///
704    /// # Returns
705    ///
706    /// - `bool` - Whether the ray intersects this box.
707    #[must_use]
708    pub fn intersects_ray(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
709        self.intersect_ray_near(ray.get_origin(), ray.get_inv_direction(), t_min, t_max)
710            .is_finite()
711    }
712}
713
714/// Ray construction with safe reciprocal components for `Ray3D`.
715impl Ray3D {
716    /// Safe reciprocal scalar preventing division by zero in slab ray-box tests.
717    ///
718    /// # Arguments
719    ///
720    /// - `f32` - Component scalar.
721    ///
722    /// # Returns
723    ///
724    /// - `f32` - Clamped reciprocal value.
725    #[must_use]
726    fn safe_inv(v: f32) -> f32 {
727        if v.abs() < 1e-7 {
728            if v < 0.0 { -1e7 } else { 1e7 }
729        } else {
730            1.0 / v
731        }
732    }
733
734    /// Computes safe reciprocal vector for an already-normalized ray direction.
735    ///
736    /// # Arguments
737    ///
738    /// - `Vec3` - Unit ray direction.
739    ///
740    /// # Returns
741    ///
742    /// - `Vec3` - Reciprocal direction safe for slab ray-AABB intersection.
743    #[must_use]
744    pub fn safe_inv_vec(dir: Vec3) -> Vec3 {
745        Vec3::new(
746            Self::safe_inv(dir.get_x()),
747            Self::safe_inv(dir.get_y()),
748            Self::safe_inv(dir.get_z()),
749        )
750    }
751
752    /// Constructs a normalized `Ray3D` with safe reciprocal direction components.
753    ///
754    /// # Arguments
755    ///
756    /// - `Vec3` - Ray origin.
757    /// - `Vec3` - Ray direction (normalized internally).
758    ///
759    /// # Returns
760    ///
761    /// - `Self` - Ready BVH ray.
762    #[must_use]
763    pub fn new(origin: Vec3, direction: Vec3) -> Self {
764        let dir: Vec3 = direction.normalize();
765        Self {
766            origin,
767            direction: dir,
768            inv_direction: Vec3::new(
769                Self::safe_inv(dir.get_x()),
770                Self::safe_inv(dir.get_y()),
771                Self::safe_inv(dir.get_z()),
772            ),
773        }
774    }
775}
776
777/// Gribb-Hartmann 6-plane frustum extraction and AABB visibility testing for `Frustum3D`.
778impl Frustum3D {
779    /// Normalizes a 4-component plane equation `(a, b, c, d)`.
780    ///
781    /// # Arguments
782    ///
783    /// - `[f32; 4]` - Raw plane coefficients.
784    ///
785    /// # Returns
786    ///
787    /// - `[f32; 4]` - Unit-normal plane coefficients.
788    #[must_use]
789    fn normalize_plane(p: [f32; 4]) -> [f32; 4] {
790        let len: f32 = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt().max(1e-6);
791        [p[0] / len, p[1] / len, p[2] / len, p[3] / len]
792    }
793
794    /// Extracts the 6 normalized view-frustum planes from a column-major view-projection matrix.
795    ///
796    /// # Arguments
797    ///
798    /// - `&Mat4` - Combined `projection * view` matrix.
799    ///
800    /// # Returns
801    ///
802    /// - `Self` - Normalized 6-plane frustum.
803    #[must_use]
804    pub fn from_view_proj(vp: &Mat4) -> Self {
805        let m: [f32; 16] = vp.get_m();
806        let r0: [f32; 4] = [m[0], m[4], m[8], m[12]];
807        let r1: [f32; 4] = [m[1], m[5], m[9], m[13]];
808        let r2: [f32; 4] = [m[2], m[6], m[10], m[14]];
809        let r3: [f32; 4] = [m[3], m[7], m[11], m[15]];
810        Self {
811            planes: [
812                Self::normalize_plane([r3[0] + r0[0], r3[1] + r0[1], r3[2] + r0[2], r3[3] + r0[3]]),
813                Self::normalize_plane([r3[0] - r0[0], r3[1] - r0[1], r3[2] - r0[2], r3[3] - r0[3]]),
814                Self::normalize_plane([r3[0] + r1[0], r3[1] + r1[1], r3[2] + r1[2], r3[3] + r1[3]]),
815                Self::normalize_plane([r3[0] - r1[0], r3[1] - r1[1], r3[2] - r1[2], r3[3] - r1[3]]),
816                Self::normalize_plane([r3[0] + r2[0], r3[1] + r2[1], r3[2] + r2[2], r3[3] + r2[3]]),
817                Self::normalize_plane([r3[0] - r2[0], r3[1] - r2[1], r3[2] - r2[2], r3[3] - r2[3]]),
818            ],
819        }
820    }
821
822    /// Returns `true` when `aabb` is at least partially inside the view frustum.
823    ///
824    /// # Arguments
825    ///
826    /// - `&Self` - Frustum reference.
827    /// - `&Aabb3D` - World-space AABB to test.
828    ///
829    /// # Returns
830    ///
831    /// - `bool` - `true` if potentially visible, `false` if completely culled.
832    #[must_use]
833    pub fn intersects_aabb(&self, aabb: &Aabb3D) -> bool {
834        let mn: Vec3 = aabb.get_min();
835        let mx: Vec3 = aabb.get_max();
836        for p in self.get_planes().iter() {
837            let px: f32 = if p[0] >= 0.0 { mx.get_x() } else { mn.get_x() };
838            let py: f32 = if p[1] >= 0.0 { mx.get_y() } else { mn.get_y() };
839            let pz: f32 = if p[2] >= 0.0 { mx.get_z() } else { mn.get_z() };
840            if p[0] * px + p[1] * py + p[2] * pz + p[3] < 0.0 {
841                return false;
842            }
843        }
844        true
845    }
846}
847
848/// Default 3D camera framing an open-world street boulevard.
849impl Default for Camera3D {
850    /// Creates a default street-level perspective camera.
851    ///
852    /// # Returns
853    ///
854    /// - `Self` - Default `Camera3D`.
855    fn default() -> Self {
856        Self {
857            position: Vec3::new(0.0, 9.5, 28.0),
858            yaw: -FRAC_PI_2,
859            pitch: -0.22,
860            fov_deg: 60.0,
861            near: 0.3,
862            far: 450.0,
863        }
864    }
865}
866
867/// Orientation, movement, and view-projection helpers for `Camera3D`.
868impl Camera3D {
869    /// Returns the unit forward look vector derived from `(yaw, pitch)`.
870    ///
871    /// # Arguments
872    ///
873    /// - `&Self` - Camera reference.
874    ///
875    /// # Returns
876    ///
877    /// - `Vec3` - Forward unit vector.
878    #[must_use]
879    pub fn forward(&self) -> Vec3 {
880        let yaw: f32 = self.get_yaw();
881        let pitch: f32 = self.get_pitch();
882        let cp: f32 = pitch.cos();
883        Vec3::new(yaw.cos() * cp, pitch.sin(), yaw.sin() * cp).normalize()
884    }
885
886    /// Returns the unit right vector orthogonal to `forward()` and world up.
887    ///
888    /// # Arguments
889    ///
890    /// - `&Self` - Camera reference.
891    ///
892    /// # Returns
893    ///
894    /// - `Vec3` - Right unit vector.
895    #[must_use]
896    pub fn right(&self) -> Vec3 {
897        self.forward().cross(Vec3::new(0.0, 1.0, 0.0)).normalize()
898    }
899
900    /// Converts a physical camera focal length and full-frame sensor height in millimeters to vertical FOV degrees.
901    ///
902    /// # Arguments
903    ///
904    /// - `f32` - Lens focal length in millimeters (e.g., `24.0`, `35.0`, `50.0`, `85.0`).
905    /// - `f32` - Camera sensor height in millimeters (`24.0` for 35mm full-frame).
906    ///
907    /// # Returns
908    ///
909    /// - `f32` - Vertical field of view in degrees clamped to `[12.0, 120.0]`.
910    #[must_use]
911    pub fn focal_length_to_fov_deg(focal_length_mm: f32, sensor_height_mm: f32) -> f32 {
912        let f_mm: f32 = focal_length_mm.max(8.0);
913        let s_mm: f32 = sensor_height_mm.max(4.0);
914        (2.0 * (s_mm / (2.0 * f_mm)).atan().to_degrees()).clamp(12.0, 120.0)
915    }
916
917    /// Constructs a physically based 35mm full-frame `Camera3D` using lens focal length in millimeters.
918    ///
919    /// # Arguments
920    ///
921    /// - `Vec3` - World-space eye position.
922    /// - `f32` - Horizontal yaw angle in radians.
923    /// - `f32` - Vertical pitch angle in radians.
924    /// - `f32` - Lens focal length in millimeters.
925    ///
926    /// # Returns
927    ///
928    /// - `Self` - Physically configured perspective camera.
929    #[must_use]
930    pub fn from_lens(position: Vec3, yaw: f32, pitch: f32, focal_length_mm: f32) -> Self {
931        Self {
932            position,
933            yaw,
934            pitch: pitch.clamp(-1.4, 1.4),
935            fov_deg: Self::focal_length_to_fov_deg(focal_length_mm, 24.0),
936            near: 0.25,
937            far: 480.0,
938        }
939    }
940
941    /// Computes physical exposure value `EV100` from lens aperture (f-stop), shutter speed (seconds), and ISO.
942    ///
943    /// # Arguments
944    ///
945    /// - `f32` - Aperture f-number (e.g., `2.8`, `4.0`, `8.0`).
946    /// - `f32` - Shutter exposure time in seconds (e.g., `1.0 / 125.0`).
947    /// - `f32` - Sensor ISO sensitivity (e.g., `100.0`).
948    ///
949    /// # Returns
950    ///
951    /// - `f32` - Physical exposure value `EV100`.
952    #[must_use]
953    pub fn ev100(aperture_fstop: f32, shutter_seconds: f32, iso: f32) -> f32 {
954        let n: f32 = aperture_fstop.max(0.7);
955        let t: f32 = shutter_seconds.max(1e-5);
956        let s: f32 = iso.max(25.0);
957        ((n * n) / t * (100.0 / s)).log2()
958    }
959
960    /// Converts an `EV100` exposure value into a linear HDR scene exposure multiplier.
961    ///
962    /// # Arguments
963    ///
964    /// - `f32` - Physical exposure value `EV100`.
965    ///
966    /// # Returns
967    ///
968    /// - `f32` - Linear exposure multiplier clamped to `[0.05, 8.0]`.
969    #[must_use]
970    pub fn exposure_scale_from_ev100(ev100: f32) -> f32 {
971        let max_lum: f32 = 1.2 * 2.0_f32.powf(ev100);
972        (1.0 / max_lum.max(1e-4)).clamp(0.05, 8.0)
973    }
974
975    /// Orients this camera's yaw and pitch to aim directly at `target`.
976    ///
977    /// # Arguments
978    ///
979    /// - `&Self` - Mutable camera reference.
980    /// - `Vec3` - World-space look target.
981    pub fn look_at(&mut self, target: Vec3) {
982        let dir: Vec3 = target.sub(self.get_position()).normalize();
983        self.set_yaw(dir.get_z().atan2(dir.get_x()));
984        self.set_pitch(dir.get_y().clamp(-0.98, 0.98).asin());
985    }
986
987    /// Computes the combined `projection * view` matrix for viewport `aspect`.
988    ///
989    /// # Arguments
990    ///
991    /// - `&Self` - Camera reference.
992    /// - `f32` - Viewport aspect ratio `width / height`.
993    ///
994    /// # Returns
995    ///
996    /// - `Mat4` - View-projection matrix.
997    #[must_use]
998    pub fn view_projection(&self, aspect: f32) -> Mat4 {
999        let pos: Vec3 = self.get_position();
1000        let view: Mat4 = Mat4::look_at(pos, pos.add(self.forward()), Vec3::new(0.0, 1.0, 0.0));
1001        let proj: Mat4 = Mat4::perspective(
1002            self.get_fov_deg().to_radians(),
1003            aspect.max(0.1),
1004            self.get_near().max(0.05),
1005            self.get_far().max(10.0),
1006        );
1007        proj.mul(view)
1008    }
1009}