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 #[inline(always)]
44 #[must_use]
45 pub fn scale(self, s: f32) -> Self {
46 Self {
47 x: self.get_x() * s,
48 y: self.get_y() * s,
49 z: self.get_z() * s,
50 }
51 }
52
53 /// Computes the dot product `self · rhs`.
54 ///
55 /// # Arguments
56 ///
57 /// - `Self` - Left vector.
58 /// - `Self` - Right vector.
59 ///
60 /// # Returns
61 ///
62 /// - `f32` - Scalar dot product.
63 #[inline(always)]
64 #[must_use]
65 pub fn dot(self, rhs: Self) -> f32 {
66 self.get_x().mul_add(
67 rhs.get_x(),
68 self.get_y()
69 .mul_add(rhs.get_y(), self.get_z() * rhs.get_z()),
70 )
71 }
72
73 /// Computes the 3D cross product `self × rhs`.
74 ///
75 /// # Arguments
76 ///
77 /// - `Self` - Left vector.
78 /// - `Self` - Right vector.
79 ///
80 /// # Returns
81 ///
82 /// - `Self` - Orthogonal cross product vector.
83 #[inline(always)]
84 #[must_use]
85 pub fn cross(self, rhs: Self) -> Self {
86 Self {
87 x: self.get_y() * rhs.get_z() - self.get_z() * rhs.get_y(),
88 y: self.get_z() * rhs.get_x() - self.get_x() * rhs.get_z(),
89 z: self.get_x() * rhs.get_y() - self.get_y() * rhs.get_x(),
90 }
91 }
92
93 /// Computes squared Euclidean length.
94 ///
95 /// # Arguments
96 ///
97 /// - `Self` - Source vector.
98 ///
99 /// # Returns
100 ///
101 /// - `f32` - Squared magnitude.
102 #[inline(always)]
103 #[must_use]
104 pub fn length_sq(self) -> f32 {
105 self.dot(self)
106 }
107
108 /// Computes Euclidean length.
109 ///
110 /// # Arguments
111 ///
112 /// - `Self` - Source vector.
113 ///
114 /// # Returns
115 ///
116 /// - `f32` - Magnitude.
117 #[inline(always)]
118 #[must_use]
119 pub fn length(self) -> f32 {
120 self.length_sq().sqrt()
121 }
122
123 /// Returns a unit-length vector pointing along `self`, or `(0, 1, 0)` if degenerate.
124 ///
125 /// # Arguments
126 ///
127 /// - `Self` - Source vector.
128 ///
129 /// # Returns
130 ///
131 /// - `Self` - Normalized unit vector.
132 #[inline(always)]
133 #[must_use]
134 pub fn normalize(self) -> Self {
135 let len: f32 = self.length();
136 if len > 1e-6 {
137 self.scale(1.0 / len)
138 } else {
139 Self::new(0.0, 1.0, 0.0)
140 }
141 }
142
143 /// Linearly interpolates between `self` and `other` by `t`.
144 ///
145 /// # Arguments
146 ///
147 /// - `Self` - Start vector.
148 /// - `Self` - End vector.
149 /// - `f32` - Interpolation factor.
150 ///
151 /// # Returns
152 ///
153 /// - `Self` - Interpolated vector.
154 #[inline(always)]
155 #[must_use]
156 pub fn lerp(self, other: Self, t: f32) -> Self {
157 Self {
158 x: (other.get_x() - self.get_x()).mul_add(t, self.get_x()),
159 y: (other.get_y() - self.get_y()).mul_add(t, self.get_y()),
160 z: (other.get_z() - self.get_z()).mul_add(t, self.get_z()),
161 }
162 }
163
164 /// Reflects incident vector `self` across unit surface normal `normal`.
165 ///
166 /// # Arguments
167 ///
168 /// - `Self` - Incident vector.
169 /// - `Self` - Unit surface normal.
170 ///
171 /// # Returns
172 ///
173 /// - `Self` - Reflected direction vector.
174 #[inline(always)]
175 #[must_use]
176 pub fn reflect(self, normal: Self) -> Self {
177 self.sub(normal.scale(2.0 * self.dot(normal)))
178 }
179
180 /// Returns component-wise minimum of `self` and `rhs`.
181 ///
182 /// # Arguments
183 ///
184 /// - `Self` - Left vector.
185 /// - `Self` - Right vector.
186 ///
187 /// # Returns
188 ///
189 /// - `Self` - Component-wise minimum.
190 #[must_use]
191 pub fn min(self, rhs: Self) -> Self {
192 Self {
193 x: self.get_x().min(rhs.get_x()),
194 y: self.get_y().min(rhs.get_y()),
195 z: self.get_z().min(rhs.get_z()),
196 }
197 }
198
199 /// Returns component-wise maximum of `self` and `rhs`.
200 ///
201 /// # Arguments
202 ///
203 /// - `Self` - Left vector.
204 /// - `Self` - Right vector.
205 ///
206 /// # Returns
207 ///
208 /// - `Self` - Component-wise maximum.
209 #[must_use]
210 pub fn max(self, rhs: Self) -> Self {
211 Self {
212 x: self.get_x().max(rhs.get_x()),
213 y: self.get_y().max(rhs.get_y()),
214 z: self.get_z().max(rhs.get_z()),
215 }
216 }
217
218 /// Converts an sRGB `Color` into linear RGB `Vec3` radiance in `[0.0, 1.0]`.
219 ///
220 /// # Arguments
221 ///
222 /// - `Color` - Source RGBA color.
223 ///
224 /// # Returns
225 ///
226 /// - `Self` - Normalized linear RGB vector.
227 #[must_use]
228 pub fn from_color(c: Color) -> Self {
229 Self {
230 x: (c.get_r() as f32) / 255.0,
231 y: (c.get_g() as f32) / 255.0,
232 z: (c.get_b() as f32) / 255.0,
233 }
234 }
235
236 /// Maps a single HDR channel through the ACES filmic tone curve into sRGB byte space.
237 ///
238 /// # Arguments
239 ///
240 /// - `f32` - Linear HDR scalar.
241 ///
242 /// # Returns
243 ///
244 /// - `u8` - Gamma-encoded sRGB byte.
245 #[inline(always)]
246 #[must_use]
247 fn aces_channel(v: f32) -> u8 {
248 let x: f32 = v.max(0.0);
249 let num: f32 = x * x.mul_add(2.51, 0.03);
250 let den: f32 = x.mul_add(x.mul_add(2.43, 0.59), 0.14);
251 let mapped: f32 = num / den;
252 let idx: usize = mapped.clamp(0.0, 1.0).mul_add(1024.0, 0.5) as usize;
253 LINEAR_TO_SRGB_LUT[idx.min(1024)]
254 }
255
256 /// Applies ACES filmic tone mapping and converts linear radiance to RGBA8 `[r, g, b, 255]`.
257 ///
258 /// # Arguments
259 ///
260 /// - `Self` - Linear HDR RGB radiance.
261 ///
262 /// # Returns
263 ///
264 /// - `[u8; 4]` - Tone-mapped RGBA8 pixel bytes.
265 #[inline(always)]
266 #[must_use]
267 pub fn to_aces_rgba8(self) -> [u8; 4] {
268 [
269 Self::aces_channel(self.get_x()),
270 Self::aces_channel(self.get_y()),
271 Self::aces_channel(self.get_z()),
272 255,
273 ]
274 }
275
276 /// Maps four HDR scalar values through the ACES filmic tone curve into 10-bit LUT indices `[0..=1024]`.
277 ///
278 /// # Arguments
279 ///
280 /// - `[f32; 4]` - Four linear HDR channel scalars.
281 ///
282 /// # Returns
283 ///
284 /// - `[u32; 4]` - Clamped LUT indices into `LINEAR_TO_SRGB_LUT`.
285 #[inline(always)]
286 #[must_use]
287 fn aces_indices_4x(vals: [f32; 4]) -> [u32; 4] {
288 #[cfg(target_arch = "aarch64")]
289 {
290 let mut out: [u32; 4] = [0; 4];
291 // SAFETY: `vals` and `out` are valid 16-byte stack arrays; NEON is mandatory on `aarch64`.
292 unsafe {
293 let zero: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(0.0);
294 let one: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(1.0);
295 let x: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
296 core::arch::aarch64::vld1q_f32(vals.as_ptr()),
297 zero,
298 );
299 let num: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
300 x,
301 core::arch::aarch64::vfmaq_f32(
302 core::arch::aarch64::vdupq_n_f32(0.03),
303 x,
304 core::arch::aarch64::vdupq_n_f32(2.51),
305 ),
306 );
307 let den_inner: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
308 core::arch::aarch64::vdupq_n_f32(0.59),
309 x,
310 core::arch::aarch64::vdupq_n_f32(2.43),
311 );
312 let den: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
313 core::arch::aarch64::vdupq_n_f32(0.14),
314 x,
315 den_inner,
316 );
317 let den_est: core::arch::aarch64::float32x4_t =
318 core::arch::aarch64::vrecpeq_f32(den);
319 let inv_den: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
320 den_est,
321 core::arch::aarch64::vrecpsq_f32(den, den_est),
322 );
323 let mapped: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
324 core::arch::aarch64::vmaxq_f32(
325 core::arch::aarch64::vmulq_f32(num, inv_den),
326 zero,
327 ),
328 one,
329 );
330 let scaled: core::arch::aarch64::float32x4_t = core::arch::aarch64::vaddq_f32(
331 core::arch::aarch64::vmulq_f32(
332 mapped,
333 core::arch::aarch64::vdupq_n_f32(1024.0),
334 ),
335 core::arch::aarch64::vdupq_n_f32(0.5),
336 );
337 let idx_u32: core::arch::aarch64::uint32x4_t =
338 core::arch::aarch64::vcvtq_u32_f32(scaled);
339 core::arch::aarch64::vst1q_u32(out.as_mut_ptr(), idx_u32);
340 }
341 [
342 out[0].min(1024),
343 out[1].min(1024),
344 out[2].min(1024),
345 out[3].min(1024),
346 ]
347 }
348 #[cfg(target_arch = "x86_64")]
349 {
350 let mut out: [i32; 4] = [0; 4];
351 // SAFETY: `vals` and `out` are valid 16-byte stack arrays; SSE2 is mandatory on `x86_64`.
352 unsafe {
353 let zero: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(0.0);
354 let one: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(1.0);
355 let x: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
356 core::arch::x86_64::_mm_loadu_ps(vals.as_ptr()),
357 zero,
358 );
359 let num: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
360 x,
361 core::arch::x86_64::_mm_add_ps(
362 core::arch::x86_64::_mm_mul_ps(x, core::arch::x86_64::_mm_set1_ps(2.51)),
363 core::arch::x86_64::_mm_set1_ps(0.03),
364 ),
365 );
366 let den: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
367 core::arch::x86_64::_mm_mul_ps(
368 x,
369 core::arch::x86_64::_mm_add_ps(
370 core::arch::x86_64::_mm_mul_ps(
371 x,
372 core::arch::x86_64::_mm_set1_ps(2.43),
373 ),
374 core::arch::x86_64::_mm_set1_ps(0.59),
375 ),
376 ),
377 core::arch::x86_64::_mm_set1_ps(0.14),
378 );
379 let mapped: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
380 core::arch::x86_64::_mm_max_ps(core::arch::x86_64::_mm_div_ps(num, den), zero),
381 one,
382 );
383 let scaled: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
384 core::arch::x86_64::_mm_mul_ps(mapped, core::arch::x86_64::_mm_set1_ps(1024.0)),
385 core::arch::x86_64::_mm_set1_ps(0.5),
386 );
387 core::arch::x86_64::_mm_storeu_si128(
388 out.as_mut_ptr().cast::<core::arch::x86_64::__m128i>(),
389 core::arch::x86_64::_mm_cvttps_epi32(scaled),
390 );
391 }
392 [
393 (out[0].clamp(0, 1024)) as u32,
394 (out[1].clamp(0, 1024)) as u32,
395 (out[2].clamp(0, 1024)) as u32,
396 (out[3].clamp(0, 1024)) as u32,
397 ]
398 }
399 #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))]
400 {
401 let mut out: [u32; 4] = [0; 4];
402 for i in 0..4 {
403 let x: f32 = vals[i].max(0.0);
404 let num: f32 = x * x.mul_add(2.51, 0.03);
405 let den: f32 = x.mul_add(x.mul_add(2.43, 0.59), 0.14);
406 let idx: u32 = ((num / den).clamp(0.0, 1.0).mul_add(1024.0, 0.5)) as u32;
407 out[i] = idx.min(1024);
408 }
409 out
410 }
411 }
412
413 /// Vectorized 4-pixel ACES filmic tone mapper returning RGBA8 pixels and Rec.601 luma bytes.
414 ///
415 /// # Arguments
416 ///
417 /// - `[f32; 4]` - Four linear HDR red channel values.
418 /// - `[f32; 4]` - Four linear HDR green channel values.
419 /// - `[f32; 4]` - Four linear HDR blue channel values.
420 ///
421 /// # Returns
422 ///
423 /// - `([[u8; 4]; 4], [u8; 4])` - Tone-mapped RGBA8 pixels and corresponding Rec.601 luma values.
424 #[inline(always)]
425 #[must_use]
426 pub fn aces_rgba8_luma_4x(r: [f32; 4], g: [f32; 4], b: [f32; 4]) -> ([[u8; 4]; 4], [u8; 4]) {
427 let ir: [u32; 4] = Self::aces_indices_4x(r);
428 let ig: [u32; 4] = Self::aces_indices_4x(g);
429 let ib: [u32; 4] = Self::aces_indices_4x(b);
430 let mut rgba: [[u8; 4]; 4] = [[0, 0, 0, 255]; 4];
431 let mut luma: [u8; 4] = [0; 4];
432 for i in 0..4 {
433 let rv: u8 = LINEAR_TO_SRGB_LUT[ir[i] as usize];
434 let gv: u8 = LINEAR_TO_SRGB_LUT[ig[i] as usize];
435 let bv: u8 = LINEAR_TO_SRGB_LUT[ib[i] as usize];
436 rgba[i] = [rv, gv, bv, 255];
437 luma[i] = (((rv as u32) * 77 + (gv as u32) * 150 + (bv as u32) * 29) >> 8) as u8;
438 }
439 (rgba, luma)
440 }
441}
442
443/// Component-wise vector addition for `Vec3`.
444impl Add for Vec3 {
445 type Output = Self;
446
447 /// Adds two vectors component-wise.
448 ///
449 /// # Arguments
450 ///
451 /// - `Self` - Left vector.
452 /// - `Self` - Right vector.
453 ///
454 /// # Returns
455 ///
456 /// - `Self` - Component-wise sum.
457 #[inline(always)]
458 fn add(self, rhs: Self) -> Self {
459 Self {
460 x: self.get_x() + rhs.get_x(),
461 y: self.get_y() + rhs.get_y(),
462 z: self.get_z() + rhs.get_z(),
463 }
464 }
465}
466
467/// Component-wise vector subtraction for `Vec3`.
468impl Sub for Vec3 {
469 type Output = Self;
470
471 /// Subtracts `rhs` from `self`.
472 ///
473 /// # Arguments
474 ///
475 /// - `Self` - Left vector.
476 /// - `Self` - Right vector.
477 ///
478 /// # Returns
479 ///
480 /// - `Self` - Component-wise difference.
481 #[inline(always)]
482 fn sub(self, rhs: Self) -> Self {
483 Self {
484 x: self.get_x() - rhs.get_x(),
485 y: self.get_y() - rhs.get_y(),
486 z: self.get_z() - rhs.get_z(),
487 }
488 }
489}
490
491/// Component-wise Hadamard vector multiplication for `Vec3`.
492impl Mul for Vec3 {
493 type Output = Self;
494
495 /// Multiplies two vectors component-wise.
496 ///
497 /// # Arguments
498 ///
499 /// - `Self` - Left vector.
500 /// - `Self` - Right vector.
501 ///
502 /// # Returns
503 ///
504 /// - `Self` - Component-wise product.
505 #[inline(always)]
506 fn mul(self, rhs: Self) -> Self {
507 Self {
508 x: self.get_x() * rhs.get_x(),
509 y: self.get_y() * rhs.get_y(),
510 z: self.get_z() * rhs.get_z(),
511 }
512 }
513}
514
515/// Matrix multiplication `self * rhs` for `Mat4`.
516impl Mul for Mat4 {
517 type Output = Self;
518
519 /// Multiplies `self * rhs`.
520 ///
521 /// # Arguments
522 ///
523 /// - `Self` - Left matrix.
524 /// - `Self` - Right matrix.
525 ///
526 /// # Returns
527 ///
528 /// - `Self` - Product matrix.
529 fn mul(self, rhs: Self) -> Self {
530 let a: [f32; 16] = self.get_m();
531 let b: [f32; 16] = rhs.get_m();
532 let mut out: [f32; 16] = [0.0; 16];
533 for col in 0..4 {
534 for row in 0..4 {
535 out[col * 4 + row] = a[row] * b[col * 4]
536 + a[4 + row] * b[col * 4 + 1]
537 + a[8 + row] * b[col * 4 + 2]
538 + a[12 + row] * b[col * 4 + 3];
539 }
540 }
541 Self { m: out }
542 }
543}
544
545/// Matrix constructors, projection, and point projection for `Mat4`.
546impl Mat4 {
547 /// Identity 4x4 matrix.
548 ///
549 /// # Returns
550 ///
551 /// - `Self` - Identity matrix.
552 #[must_use]
553 pub const fn identity() -> Self {
554 Self {
555 m: [
556 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,
557 ],
558 }
559 }
560
561 /// Builds a right-handed perspective projection matrix.
562 ///
563 /// # Arguments
564 ///
565 /// - `f32` - Vertical FOV in radians.
566 /// - `f32` - Viewport aspect ratio `width / height`.
567 /// - `f32` - Near plane distance.
568 /// - `f32` - Far plane distance.
569 ///
570 /// # Returns
571 ///
572 /// - `Self` - Perspective projection matrix.
573 #[must_use]
574 pub fn perspective(fov_rad: f32, aspect: f32, near: f32, far: f32) -> Self {
575 let f: f32 = 1.0 / (fov_rad * 0.5).tan().max(1e-4);
576 let nf: f32 = 1.0 / (near - far);
577 Self {
578 m: [
579 f / aspect.max(0.01),
580 0.0,
581 0.0,
582 0.0,
583 0.0,
584 f,
585 0.0,
586 0.0,
587 0.0,
588 0.0,
589 (far + near) * nf,
590 -1.0,
591 0.0,
592 0.0,
593 2.0 * far * near * nf,
594 0.0,
595 ],
596 }
597 }
598
599 /// Builds a right-handed look-at view matrix.
600 ///
601 /// # Arguments
602 ///
603 /// - `Vec3` - Camera eye position.
604 /// - `Vec3` - Target look-at position.
605 /// - `Vec3` - World up direction.
606 ///
607 /// # Returns
608 ///
609 /// - `Self` - View transformation matrix.
610 #[must_use]
611 pub fn look_at(eye: Vec3, target: Vec3, up: Vec3) -> Self {
612 let f: Vec3 = target.sub(eye).normalize();
613 let s: Vec3 = f.cross(up).normalize();
614 let u: Vec3 = s.cross(f);
615 Self {
616 m: [
617 s.get_x(),
618 u.get_x(),
619 -f.get_x(),
620 0.0,
621 s.get_y(),
622 u.get_y(),
623 -f.get_y(),
624 0.0,
625 s.get_z(),
626 u.get_z(),
627 -f.get_z(),
628 0.0,
629 -s.dot(eye),
630 -u.dot(eye),
631 f.dot(eye),
632 1.0,
633 ],
634 }
635 }
636
637 /// Builds a TRS model matrix (`translate * rotate_y * scale`).
638 ///
639 /// # Arguments
640 ///
641 /// - `Vec3` - World translation.
642 /// - `f32` - Y-axis yaw rotation in radians.
643 /// - `Vec3` - Non-uniform scale.
644 ///
645 /// # Returns
646 ///
647 /// - `Self` - Composed model transform matrix.
648 #[must_use]
649 pub fn from_trs(position: Vec3, yaw_rad: f32, scale: Vec3) -> Self {
650 let c: f32 = yaw_rad.cos();
651 let s: f32 = yaw_rad.sin();
652 Self {
653 m: [
654 c * scale.get_x(),
655 0.0,
656 -s * scale.get_x(),
657 0.0,
658 0.0,
659 scale.get_y(),
660 0.0,
661 0.0,
662 s * scale.get_z(),
663 0.0,
664 c * scale.get_z(),
665 0.0,
666 position.get_x(),
667 position.get_y(),
668 position.get_z(),
669 1.0,
670 ],
671 }
672 }
673
674 /// Builds a full 3D Euler TRS model matrix (`translate * rotate_y(yaw) * rotate_x(pitch) * rotate_z(roll) * scale`).
675 ///
676 /// # Arguments
677 ///
678 /// - `Vec3` - World translation.
679 /// - `f32` - Y-axis yaw rotation in radians.
680 /// - `f32` - X-axis pitch rotation in radians.
681 /// - `f32` - Z-axis roll rotation in radians.
682 /// - `Vec3` - Non-uniform scale.
683 ///
684 /// # Returns
685 ///
686 /// - `Self` - Composed 3D model transform matrix.
687 #[must_use]
688 pub fn from_trs_euler(
689 position: Vec3,
690 yaw_rad: f32,
691 pitch_rad: f32,
692 roll_rad: f32,
693 scale: Vec3,
694 ) -> Self {
695 if pitch_rad.abs() < 1e-6 && roll_rad.abs() < 1e-6 {
696 return Self::from_trs(position, yaw_rad, scale);
697 }
698 let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
699 let (cp, sp): (f32, f32) = (pitch_rad.cos(), pitch_rad.sin());
700 let (cr, sr): (f32, f32) = (roll_rad.cos(), roll_rad.sin());
701 let r00: f32 = cy * cr + sy * sp * sr;
702 let r10: f32 = cp * sr;
703 let r20: f32 = -sy * cr + cy * sp * sr;
704 let r01: f32 = -cy * sr + sy * sp * cr;
705 let r11: f32 = cp * cr;
706 let r21: f32 = sy * sr + cy * sp * cr;
707 let r02: f32 = sy * cp;
708 let r12: f32 = -sp;
709 let r22: f32 = cy * cp;
710 let sx: f32 = scale.get_x();
711 let sy_sc: f32 = scale.get_y();
712 let sz: f32 = scale.get_z();
713 Self {
714 m: [
715 r00 * sx,
716 r10 * sx,
717 r20 * sx,
718 0.0,
719 r01 * sy_sc,
720 r11 * sy_sc,
721 r21 * sy_sc,
722 0.0,
723 r02 * sz,
724 r12 * sz,
725 r22 * sz,
726 0.0,
727 position.get_x(),
728 position.get_y(),
729 position.get_z(),
730 1.0,
731 ],
732 }
733 }
734
735 /// Transforms a 3D point returning homogeneous clip coordinates `(x, y, z, w)`.
736 ///
737 /// # Arguments
738 ///
739 /// - `&Self` - Transformation matrix.
740 /// - `Vec3` - Input 3D position.
741 ///
742 /// # Returns
743 ///
744 /// - `[f32; 4]` - Homogeneous clip-space coordinates.
745 #[inline(always)]
746 #[must_use]
747 pub fn mul_point4(&self, p: Vec3) -> [f32; 4] {
748 let m: [f32; 16] = self.get_m();
749 let px: f32 = p.get_x();
750 let py: f32 = p.get_y();
751 let pz: f32 = p.get_z();
752 [
753 px.mul_add(m[0], py.mul_add(m[4], pz.mul_add(m[8], m[12]))),
754 px.mul_add(m[1], py.mul_add(m[5], pz.mul_add(m[9], m[13]))),
755 px.mul_add(m[2], py.mul_add(m[6], pz.mul_add(m[10], m[14]))),
756 px.mul_add(m[3], py.mul_add(m[7], pz.mul_add(m[11], m[15]))),
757 ]
758 }
759
760 /// Transforms a 3D point by the upper 3x4 affine portion of `self`.
761 ///
762 /// # Arguments
763 ///
764 /// - `&Self` - Affine transformation matrix.
765 /// - `Vec3` - Input 3D position.
766 ///
767 /// # Returns
768 ///
769 /// - `Vec3` - Transformed 3D position.
770 #[inline(always)]
771 #[must_use]
772 pub fn mul_point3(&self, p: Vec3) -> Vec3 {
773 let m: [f32; 16] = self.get_m();
774 let px: f32 = p.get_x();
775 let py: f32 = p.get_y();
776 let pz: f32 = p.get_z();
777 Vec3::new(
778 px.mul_add(m[0], py.mul_add(m[4], pz.mul_add(m[8], m[12]))),
779 px.mul_add(m[1], py.mul_add(m[5], pz.mul_add(m[9], m[13]))),
780 px.mul_add(m[2], py.mul_add(m[6], pz.mul_add(m[10], m[14]))),
781 )
782 }
783
784 /// Transforms a 3D direction vector by the upper-left 3x3 linear portion of `self` (no translation).
785 ///
786 /// # Arguments
787 ///
788 /// - `&Self` - Transformation matrix.
789 /// - `Vec3` - Input 3D vector.
790 ///
791 /// # Returns
792 ///
793 /// - `Vec3` - Linearly transformed 3D vector.
794 #[inline(always)]
795 #[must_use]
796 pub fn mul_vec3(&self, v: Vec3) -> Vec3 {
797 let m: [f32; 16] = self.get_m();
798 let vx: f32 = v.get_x();
799 let vy: f32 = v.get_y();
800 let vz: f32 = v.get_z();
801 Vec3::new(
802 vx.mul_add(m[0], vy.mul_add(m[4], vz * m[8])),
803 vx.mul_add(m[1], vy.mul_add(m[5], vz * m[9])),
804 vx.mul_add(m[2], vy.mul_add(m[6], vz * m[10])),
805 )
806 }
807
808 /// Transforms a local `Aabb3D` into an enclosing world-space `Aabb3D` via Arvo's 18-multiply method (zero corner loop, zero trigonometry).
809 ///
810 /// # Arguments
811 ///
812 /// - `&Self` - Affine model transformation matrix.
813 /// - `Aabb3D` - Local-space bounding box.
814 ///
815 /// # Returns
816 ///
817 /// - `Aabb3D` - Tight world-space enclosing AABB.
818 #[inline(always)]
819 #[must_use]
820 pub fn transform_aabb(&self, local: Aabb3D) -> Aabb3D {
821 let m: [f32; 16] = self.get_m();
822 let lmin: Vec3 = local.get_min();
823 let lmax: Vec3 = local.get_max();
824 let lx0: f32 = lmin.get_x();
825 let ly0: f32 = lmin.get_y();
826 let lz0: f32 = lmin.get_z();
827 let lx1: f32 = lmax.get_x();
828 let ly1: f32 = lmax.get_y();
829 let lz1: f32 = lmax.get_z();
830 let ax0: f32 = m[0] * lx0;
831 let ax1: f32 = m[0] * lx1;
832 let ay0: f32 = m[4] * ly0;
833 let ay1: f32 = m[4] * ly1;
834 let az0: f32 = m[8] * lz0;
835 let az1: f32 = m[8] * lz1;
836 let out_min_x: f32 = m[12] + ax0.min(ax1) + ay0.min(ay1) + az0.min(az1);
837 let out_max_x: f32 = m[12] + ax0.max(ax1) + ay0.max(ay1) + az0.max(az1);
838 let bx0: f32 = m[1] * lx0;
839 let bx1: f32 = m[1] * lx1;
840 let by0: f32 = m[5] * ly0;
841 let by1: f32 = m[5] * ly1;
842 let bz0: f32 = m[9] * lz0;
843 let bz1: f32 = m[9] * lz1;
844 let out_min_y: f32 = m[13] + bx0.min(bx1) + by0.min(by1) + bz0.min(bz1);
845 let out_max_y: f32 = m[13] + bx0.max(bx1) + by0.max(by1) + bz0.max(bz1);
846 let cx0: f32 = m[2] * lx0;
847 let cx1: f32 = m[2] * lx1;
848 let cy0: f32 = m[6] * ly0;
849 let cy1: f32 = m[6] * ly1;
850 let cz0: f32 = m[10] * lz0;
851 let cz1: f32 = m[10] * lz1;
852 let out_min_z: f32 = m[14] + cx0.min(cx1) + cy0.min(cy1) + cz0.min(cz1);
853 let out_max_z: f32 = m[14] + cx0.max(cx1) + cy0.max(cy1) + cz0.max(cz1);
854 Aabb3D::new(
855 Vec3::new(out_min_x, out_min_y, out_min_z),
856 Vec3::new(out_max_x, out_max_y, out_max_z),
857 )
858 }
859
860 /// Computes the exact analytical inverse of a TRS Euler matrix (`S^-1 * R^T * T^-1`) for object-space raytracing.
861 ///
862 /// # Arguments
863 ///
864 /// - `Vec3` - World translation.
865 /// - `f32` - Y-axis yaw rotation in radians.
866 /// - `f32` - X-axis pitch rotation in radians.
867 /// - `f32` - Z-axis roll rotation in radians.
868 /// - `Vec3` - Non-uniform scale.
869 ///
870 /// # Returns
871 ///
872 /// - `Self` - Exact inverse model matrix mapping world space back to local object space.
873 #[must_use]
874 pub fn inverse_trs_euler(
875 position: Vec3,
876 yaw_rad: f32,
877 pitch_rad: f32,
878 roll_rad: f32,
879 scale: Vec3,
880 ) -> Self {
881 let isx: f32 = if scale.get_x().abs() > 1e-6 {
882 1.0 / scale.get_x()
883 } else {
884 1.0
885 };
886 let isy: f32 = if scale.get_y().abs() > 1e-6 {
887 1.0 / scale.get_y()
888 } else {
889 1.0
890 };
891 let isz: f32 = if scale.get_z().abs() > 1e-6 {
892 1.0 / scale.get_z()
893 } else {
894 1.0
895 };
896 let (r00, r10, r20, r01, r11, r21, r02, r12, r22): (
897 f32,
898 f32,
899 f32,
900 f32,
901 f32,
902 f32,
903 f32,
904 f32,
905 f32,
906 ) = if pitch_rad.abs() < 1e-6 && roll_rad.abs() < 1e-6 {
907 let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
908 (cy, 0.0, -sy, 0.0, 1.0, 0.0, sy, 0.0, cy)
909 } else {
910 let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
911 let (cp, sp): (f32, f32) = (pitch_rad.cos(), pitch_rad.sin());
912 let (cr, sr): (f32, f32) = (roll_rad.cos(), roll_rad.sin());
913 (
914 cy * cr + sy * sp * sr,
915 cp * sr,
916 -sy * cr + cy * sp * sr,
917 -cy * sr + sy * sp * cr,
918 cp * cr,
919 sy * sr + cy * sp * cr,
920 sy * cp,
921 -sp,
922 cy * cp,
923 )
924 };
925 let m00: f32 = r00 * isx;
926 let m01: f32 = r10 * isx;
927 let m02: f32 = r20 * isx;
928 let m10: f32 = r01 * isy;
929 let m11: f32 = r11 * isy;
930 let m12: f32 = r21 * isy;
931 let m20: f32 = r02 * isz;
932 let m21: f32 = r12 * isz;
933 let m22: f32 = r22 * isz;
934 let px: f32 = position.get_x();
935 let py: f32 = position.get_y();
936 let pz: f32 = position.get_z();
937 let tx: f32 = -(m00 * px + m01 * py + m02 * pz);
938 let ty: f32 = -(m10 * px + m11 * py + m12 * pz);
939 let tz: f32 = -(m20 * px + m21 * py + m22 * pz);
940 Self {
941 m: [
942 m00, m10, m20, 0.0, m01, m11, m21, 0.0, m02, m12, m22, 0.0, tx, ty, tz, 1.0,
943 ],
944 }
945 }
946
947 /// Computes the inverse-transpose 3x3 normal transformation basis `[col_x, col_y, col_z]` (`R * S^-1`) once per object.
948 ///
949 /// # Arguments
950 ///
951 /// - `f32` - Y-axis yaw rotation in radians.
952 /// - `f32` - X-axis pitch rotation in radians.
953 /// - `f32` - Z-axis roll rotation in radians.
954 /// - `Vec3` - Non-uniform scale.
955 ///
956 /// # Returns
957 ///
958 /// - `[Vec3; 3]` - Three column vectors transforming local normals into world space.
959 #[must_use]
960 pub fn normal_basis_from_euler_scale(
961 yaw_rad: f32,
962 pitch_rad: f32,
963 roll_rad: f32,
964 scale: Vec3,
965 ) -> [Vec3; 3] {
966 let isx: f32 = if scale.get_x().abs() > 1e-6 {
967 1.0 / scale.get_x()
968 } else {
969 1.0
970 };
971 let isy: f32 = if scale.get_y().abs() > 1e-6 {
972 1.0 / scale.get_y()
973 } else {
974 1.0
975 };
976 let isz: f32 = if scale.get_z().abs() > 1e-6 {
977 1.0 / scale.get_z()
978 } else {
979 1.0
980 };
981 if pitch_rad.abs() < 1e-6 && roll_rad.abs() < 1e-6 {
982 let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
983 return [
984 Vec3::new(cy * isx, 0.0, -sy * isx),
985 Vec3::new(0.0, isy, 0.0),
986 Vec3::new(sy * isz, 0.0, cy * isz),
987 ];
988 }
989 let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
990 let (cp, sp): (f32, f32) = (pitch_rad.cos(), pitch_rad.sin());
991 let (cr, sr): (f32, f32) = (roll_rad.cos(), roll_rad.sin());
992 [
993 Vec3::new(
994 (cy * cr + sy * sp * sr) * isx,
995 (cp * sr) * isx,
996 (-sy * cr + cy * sp * sr) * isx,
997 ),
998 Vec3::new(
999 (-cy * sr + sy * sp * cr) * isy,
1000 (cp * cr) * isy,
1001 (sy * sr + cy * sp * cr) * isy,
1002 ),
1003 Vec3::new((sy * cp) * isz, (-sp) * isz, (cy * cp) * isz),
1004 ]
1005 }
1006
1007 /// Transforms a local surface normal using a precomputed 3x3 `normal_basis` without trigonometry.
1008 ///
1009 /// # Arguments
1010 ///
1011 /// - `Vec3` - Local-space normal vector.
1012 /// - `[Vec3; 3]` - Precomputed inverse-transpose 3x3 normal basis `[col_x, col_y, col_z]`.
1013 ///
1014 /// # Returns
1015 ///
1016 /// - `Vec3` - Normalized world-space surface normal.
1017 #[inline(always)]
1018 #[must_use]
1019 pub fn transform_normal_with_basis(n: Vec3, basis: [Vec3; 3]) -> Vec3 {
1020 let nx: f32 = n.get_x();
1021 let ny: f32 = n.get_y();
1022 let nz: f32 = n.get_z();
1023 Vec3::new(
1024 nx.mul_add(
1025 basis[0].get_x(),
1026 ny.mul_add(basis[1].get_x(), nz * basis[2].get_x()),
1027 ),
1028 nx.mul_add(
1029 basis[0].get_y(),
1030 ny.mul_add(basis[1].get_y(), nz * basis[2].get_y()),
1031 ),
1032 nx.mul_add(
1033 basis[0].get_z(),
1034 ny.mul_add(basis[1].get_z(), nz * basis[2].get_z()),
1035 ),
1036 )
1037 .normalize()
1038 }
1039}
1040
1041/// Bounding-box union, centroid, surface area, and ray-slab intersection for `Aabb3D`.
1042impl Aabb3D {
1043 /// Creates an inverted empty AABB ready to accumulate points via `expand_point`.
1044 ///
1045 /// # Returns
1046 ///
1047 /// - `Self` - Empty AABB.
1048 #[must_use]
1049 pub const fn empty() -> Self {
1050 Self {
1051 min: Vec3::splat(f32::INFINITY),
1052 max: Vec3::splat(f32::NEG_INFINITY),
1053 }
1054 }
1055
1056 /// Expands this bounding box to include `point`.
1057 ///
1058 /// # Arguments
1059 ///
1060 /// - `&Self` - Mutable AABB.
1061 /// - `Vec3` - Point to enclose.
1062 pub fn expand_point(&mut self, point: Vec3) {
1063 let mn: Vec3 = self.get_min().min(point);
1064 let mx: Vec3 = self.get_max().max(point);
1065 self.set_min(mn);
1066 self.set_max(mx);
1067 }
1068
1069 /// Expands this bounding box to include `other`.
1070 ///
1071 /// # Arguments
1072 ///
1073 /// - `&Self` - Mutable AABB.
1074 /// - `Self` - Other bounding box.
1075 pub fn expand_box(&mut self, other: Self) {
1076 let mn: Vec3 = self.get_min().min(other.get_min());
1077 let mx: Vec3 = self.get_max().max(other.get_max());
1078 self.set_min(mn);
1079 self.set_max(mx);
1080 }
1081
1082 /// Returns the geometric center of the AABB.
1083 ///
1084 /// # Arguments
1085 ///
1086 /// - `&Self` - AABB reference.
1087 ///
1088 /// # Returns
1089 ///
1090 /// - `Vec3` - Box centroid.
1091 #[must_use]
1092 pub fn center(&self) -> Vec3 {
1093 self.get_min().add(self.get_max()).scale(0.5)
1094 }
1095
1096 /// Computes bounding-sphere radius enclosing this box.
1097 ///
1098 /// # Arguments
1099 ///
1100 /// - `&Self` - AABB reference.
1101 ///
1102 /// # Returns
1103 ///
1104 /// - `f32` - Enclosing radius.
1105 #[must_use]
1106 pub fn radius(&self) -> f32 {
1107 self.get_max().sub(self.get_min()).length() * 0.5
1108 }
1109
1110 /// Computes half surface area (`dx*dy + dy*dz + dz*dx`) for Surface Area Heuristic (SAH) BVH splits.
1111 ///
1112 /// # Arguments
1113 ///
1114 /// - `&Self` - AABB reference.
1115 ///
1116 /// # Returns
1117 ///
1118 /// - `f32` - Non-negative half surface area.
1119 #[must_use]
1120 pub fn surface_area(&self) -> f32 {
1121 let d: Vec3 = self.get_max().sub(self.get_min());
1122 let dx: f32 = d.get_x().max(0.0);
1123 let dy: f32 = d.get_y().max(0.0);
1124 let dz: f32 = d.get_z().max(0.0);
1125 dx * dy + dy * dz + dz * dx
1126 }
1127
1128 /// Branchless slab Ray-AABB intersection returning entry distance `tmin` or `f32::INFINITY` on miss.
1129 ///
1130 /// # Arguments
1131 ///
1132 /// - `&Self` - AABB reference.
1133 /// - `Vec3` - Ray origin.
1134 /// - `Vec3` - Precomputed safe reciprocal ray direction.
1135 /// - `f32` - Minimum valid distance.
1136 /// - `f32` - Maximum valid distance.
1137 ///
1138 /// # Returns
1139 ///
1140 /// - `f32` - Near intersection distance if hit, or `f32::INFINITY` if missed.
1141 #[must_use]
1142 pub fn intersect_ray_near(&self, origin: Vec3, inv_dir: Vec3, t_min: f32, t_max: f32) -> f32 {
1143 let mn: Vec3 = self.get_min();
1144 let mx: Vec3 = self.get_max();
1145 let tx1: f32 = (mn.get_x() - origin.get_x()) * inv_dir.get_x();
1146 let tx2: f32 = (mx.get_x() - origin.get_x()) * inv_dir.get_x();
1147 let mut tmin: f32 = t_min.max(tx1.min(tx2));
1148 let mut tmax: f32 = t_max.min(tx1.max(tx2));
1149 let ty1: f32 = (mn.get_y() - origin.get_y()) * inv_dir.get_y();
1150 let ty2: f32 = (mx.get_y() - origin.get_y()) * inv_dir.get_y();
1151 tmin = tmin.max(ty1.min(ty2));
1152 tmax = tmax.min(ty1.max(ty2));
1153 let tz1: f32 = (mn.get_z() - origin.get_z()) * inv_dir.get_z();
1154 let tz2: f32 = (mx.get_z() - origin.get_z()) * inv_dir.get_z();
1155 tmin = tmin.max(tz1.min(tz2));
1156 tmax = tmax.min(tz1.max(tz2));
1157 if tmax >= tmin && tmax >= 0.0 {
1158 tmin
1159 } else {
1160 f32::INFINITY
1161 }
1162 }
1163
1164 /// Branchless slab Ray-AABB intersection returning `true` when `ray` hits within `[t_min, t_max]`.
1165 ///
1166 /// # Arguments
1167 ///
1168 /// - `&Self` - AABB reference.
1169 /// - `&Ray3D` - Ray with precomputed inverse direction.
1170 /// - `f32` - Minimum valid distance.
1171 /// - `f32` - Maximum valid distance.
1172 ///
1173 /// # Returns
1174 ///
1175 /// - `bool` - Whether the ray intersects this box.
1176 #[must_use]
1177 pub fn intersects_ray(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
1178 self.intersect_ray_near(ray.get_origin(), ray.get_inv_direction(), t_min, t_max)
1179 .is_finite()
1180 }
1181}
1182
1183/// Ray construction with safe reciprocal components for `Ray3D`.
1184impl Ray3D {
1185 /// Safe reciprocal scalar preventing division by zero in slab ray-box tests.
1186 ///
1187 /// # Arguments
1188 ///
1189 /// - `f32` - Component scalar.
1190 ///
1191 /// # Returns
1192 ///
1193 /// - `f32` - Clamped reciprocal value.
1194 #[must_use]
1195 fn safe_inv(v: f32) -> f32 {
1196 if v.abs() < 1e-7 {
1197 if v < 0.0 { -1e7 } else { 1e7 }
1198 } else {
1199 1.0 / v
1200 }
1201 }
1202
1203 /// Computes safe reciprocal vector for an already-normalized ray direction.
1204 ///
1205 /// # Arguments
1206 ///
1207 /// - `Vec3` - Unit ray direction.
1208 ///
1209 /// # Returns
1210 ///
1211 /// - `Vec3` - Reciprocal direction safe for slab ray-AABB intersection.
1212 #[must_use]
1213 pub fn safe_inv_vec(dir: Vec3) -> Vec3 {
1214 Vec3::new(
1215 Self::safe_inv(dir.get_x()),
1216 Self::safe_inv(dir.get_y()),
1217 Self::safe_inv(dir.get_z()),
1218 )
1219 }
1220
1221 /// Constructs a normalized `Ray3D` with safe reciprocal direction components.
1222 ///
1223 /// # Arguments
1224 ///
1225 /// - `Vec3` - Ray origin.
1226 /// - `Vec3` - Ray direction (normalized internally).
1227 ///
1228 /// # Returns
1229 ///
1230 /// - `Self` - Ready BVH ray.
1231 #[must_use]
1232 pub fn new(origin: Vec3, direction: Vec3) -> Self {
1233 let dir: Vec3 = direction.normalize();
1234 Self {
1235 origin,
1236 direction: dir,
1237 inv_direction: Vec3::new(
1238 Self::safe_inv(dir.get_x()),
1239 Self::safe_inv(dir.get_y()),
1240 Self::safe_inv(dir.get_z()),
1241 ),
1242 }
1243 }
1244}
1245
1246/// Gribb-Hartmann 6-plane frustum extraction and AABB visibility testing for `Frustum3D`.
1247impl Frustum3D {
1248 /// Normalizes a 4-component plane equation `(a, b, c, d)`.
1249 ///
1250 /// # Arguments
1251 ///
1252 /// - `[f32; 4]` - Raw plane coefficients.
1253 ///
1254 /// # Returns
1255 ///
1256 /// - `[f32; 4]` - Unit-normal plane coefficients.
1257 #[must_use]
1258 fn normalize_plane(p: [f32; 4]) -> [f32; 4] {
1259 let len: f32 = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt().max(1e-6);
1260 [p[0] / len, p[1] / len, p[2] / len, p[3] / len]
1261 }
1262
1263 /// Extracts the 6 normalized view-frustum planes from a column-major view-projection matrix.
1264 ///
1265 /// # Arguments
1266 ///
1267 /// - `&Mat4` - Combined `projection * view` matrix.
1268 ///
1269 /// # Returns
1270 ///
1271 /// - `Self` - Normalized 6-plane frustum.
1272 #[must_use]
1273 pub fn from_view_proj(vp: &Mat4) -> Self {
1274 let m: [f32; 16] = vp.get_m();
1275 let r0: [f32; 4] = [m[0], m[4], m[8], m[12]];
1276 let r1: [f32; 4] = [m[1], m[5], m[9], m[13]];
1277 let r2: [f32; 4] = [m[2], m[6], m[10], m[14]];
1278 let r3: [f32; 4] = [m[3], m[7], m[11], m[15]];
1279 Self {
1280 planes: [
1281 Self::normalize_plane([r3[0] + r0[0], r3[1] + r0[1], r3[2] + r0[2], r3[3] + r0[3]]),
1282 Self::normalize_plane([r3[0] - r0[0], r3[1] - r0[1], r3[2] - r0[2], r3[3] - r0[3]]),
1283 Self::normalize_plane([r3[0] + r1[0], r3[1] + r1[1], r3[2] + r1[2], r3[3] + r1[3]]),
1284 Self::normalize_plane([r3[0] - r1[0], r3[1] - r1[1], r3[2] - r1[2], r3[3] - r1[3]]),
1285 Self::normalize_plane([r3[0] + r2[0], r3[1] + r2[1], r3[2] + r2[2], r3[3] + r2[3]]),
1286 Self::normalize_plane([r3[0] - r2[0], r3[1] - r2[1], r3[2] - r2[2], r3[3] - r2[3]]),
1287 ],
1288 }
1289 }
1290
1291 /// Returns `true` when `aabb` is at least partially inside the view frustum.
1292 ///
1293 /// # Arguments
1294 ///
1295 /// - `&Self` - Frustum reference.
1296 /// - `&Aabb3D` - World-space AABB to test.
1297 ///
1298 /// # Returns
1299 ///
1300 /// - `bool` - `true` if potentially visible, `false` if completely culled.
1301 #[must_use]
1302 pub fn intersects_aabb(&self, aabb: &Aabb3D) -> bool {
1303 let mn: Vec3 = aabb.get_min();
1304 let mx: Vec3 = aabb.get_max();
1305 for p in self.get_planes().iter() {
1306 let px: f32 = if p[0] >= 0.0 { mx.get_x() } else { mn.get_x() };
1307 let py: f32 = if p[1] >= 0.0 { mx.get_y() } else { mn.get_y() };
1308 let pz: f32 = if p[2] >= 0.0 { mx.get_z() } else { mn.get_z() };
1309 if p[0] * px + p[1] * py + p[2] * pz + p[3] < 0.0 {
1310 return false;
1311 }
1312 }
1313 true
1314 }
1315}
1316
1317/// Default 3D camera framing an open-world street boulevard.
1318impl Default for Camera3D {
1319 /// Creates a default street-level perspective camera.
1320 ///
1321 /// # Returns
1322 ///
1323 /// - `Self` - Default `Camera3D`.
1324 fn default() -> Self {
1325 Self {
1326 position: Vec3::new(0.0, 9.5, 28.0),
1327 yaw: -FRAC_PI_2,
1328 pitch: -0.22,
1329 fov_deg: 60.0,
1330 near: 0.3,
1331 far: 450.0,
1332 }
1333 }
1334}
1335
1336/// Orientation, movement, and view-projection helpers for `Camera3D`.
1337impl Camera3D {
1338 /// Returns the unit forward look vector derived from `(yaw, pitch)`.
1339 ///
1340 /// # Arguments
1341 ///
1342 /// - `&Self` - Camera reference.
1343 ///
1344 /// # Returns
1345 ///
1346 /// - `Vec3` - Forward unit vector.
1347 #[must_use]
1348 pub fn forward(&self) -> Vec3 {
1349 let yaw: f32 = self.get_yaw();
1350 let pitch: f32 = self.get_pitch();
1351 let cp: f32 = pitch.cos();
1352 Vec3::new(yaw.cos() * cp, pitch.sin(), yaw.sin() * cp).normalize()
1353 }
1354
1355 /// Returns the unit right vector orthogonal to `forward()` and world up.
1356 ///
1357 /// # Arguments
1358 ///
1359 /// - `&Self` - Camera reference.
1360 ///
1361 /// # Returns
1362 ///
1363 /// - `Vec3` - Right unit vector.
1364 #[must_use]
1365 pub fn right(&self) -> Vec3 {
1366 self.forward().cross(Vec3::new(0.0, 1.0, 0.0)).normalize()
1367 }
1368
1369 /// Converts a physical camera focal length and full-frame sensor height in millimeters to vertical FOV degrees.
1370 ///
1371 /// # Arguments
1372 ///
1373 /// - `f32` - Lens focal length in millimeters (e.g., `24.0`, `35.0`, `50.0`, `85.0`).
1374 /// - `f32` - Camera sensor height in millimeters (`24.0` for 35mm full-frame).
1375 ///
1376 /// # Returns
1377 ///
1378 /// - `f32` - Vertical field of view in degrees clamped to `[12.0, 120.0]`.
1379 #[must_use]
1380 pub fn focal_length_to_fov_deg(focal_length_mm: f32, sensor_height_mm: f32) -> f32 {
1381 let f_mm: f32 = focal_length_mm.max(8.0);
1382 let s_mm: f32 = sensor_height_mm.max(4.0);
1383 (2.0 * (s_mm / (2.0 * f_mm)).atan().to_degrees()).clamp(12.0, 120.0)
1384 }
1385
1386 /// Constructs a physically based 35mm full-frame `Camera3D` using lens focal length in millimeters.
1387 ///
1388 /// # Arguments
1389 ///
1390 /// - `Vec3` - World-space eye position.
1391 /// - `f32` - Horizontal yaw angle in radians.
1392 /// - `f32` - Vertical pitch angle in radians.
1393 /// - `f32` - Lens focal length in millimeters.
1394 ///
1395 /// # Returns
1396 ///
1397 /// - `Self` - Physically configured perspective camera.
1398 #[must_use]
1399 pub fn from_lens(position: Vec3, yaw: f32, pitch: f32, focal_length_mm: f32) -> Self {
1400 Self {
1401 position,
1402 yaw,
1403 pitch: pitch.clamp(-1.4, 1.4),
1404 fov_deg: Self::focal_length_to_fov_deg(focal_length_mm, 24.0),
1405 near: 0.25,
1406 far: 480.0,
1407 }
1408 }
1409
1410 /// Computes physical exposure value `EV100` from lens aperture (f-stop), shutter speed (seconds), and ISO.
1411 ///
1412 /// # Arguments
1413 ///
1414 /// - `f32` - Aperture f-number (e.g., `2.8`, `4.0`, `8.0`).
1415 /// - `f32` - Shutter exposure time in seconds (e.g., `1.0 / 125.0`).
1416 /// - `f32` - Sensor ISO sensitivity (e.g., `100.0`).
1417 ///
1418 /// # Returns
1419 ///
1420 /// - `f32` - Physical exposure value `EV100`.
1421 #[must_use]
1422 pub fn ev100(aperture_fstop: f32, shutter_seconds: f32, iso: f32) -> f32 {
1423 let n: f32 = aperture_fstop.max(0.7);
1424 let t: f32 = shutter_seconds.max(1e-5);
1425 let s: f32 = iso.max(25.0);
1426 ((n * n) / t * (100.0 / s)).log2()
1427 }
1428
1429 /// Converts an `EV100` exposure value into a linear HDR scene exposure multiplier.
1430 ///
1431 /// # Arguments
1432 ///
1433 /// - `f32` - Physical exposure value `EV100`.
1434 ///
1435 /// # Returns
1436 ///
1437 /// - `f32` - Linear exposure multiplier clamped to `[0.05, 8.0]`.
1438 #[must_use]
1439 pub fn exposure_scale_from_ev100(ev100: f32) -> f32 {
1440 let max_lum: f32 = 1.2 * 2.0_f32.powf(ev100);
1441 (1.0 / max_lum.max(1e-4)).clamp(0.05, 8.0)
1442 }
1443
1444 /// Orients this camera's yaw and pitch to aim directly at `target`.
1445 ///
1446 /// # Arguments
1447 ///
1448 /// - `&Self` - Mutable camera reference.
1449 /// - `Vec3` - World-space look target.
1450 pub fn look_at(&mut self, target: Vec3) {
1451 let dir: Vec3 = target.sub(self.get_position()).normalize();
1452 self.set_yaw(dir.get_z().atan2(dir.get_x()));
1453 self.set_pitch(dir.get_y().clamp(-0.98, 0.98).asin());
1454 }
1455
1456 /// Linearly interpolates camera position, shortest-arc yaw, pitch, and lens parameters between `self` and `other`.
1457 ///
1458 /// # Arguments
1459 ///
1460 /// - `Self` - Previous fixed-step 3D camera state.
1461 /// - `Self` - Current fixed-step 3D camera state.
1462 /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
1463 ///
1464 /// # Returns
1465 ///
1466 /// - `Self` - Interpolated 3D camera.
1467 #[must_use]
1468 pub fn lerp(self, other: Self, alpha: f32) -> Self {
1469 let k: f32 = alpha.clamp(0.0, 1.0);
1470 let diff: f32 = other.get_yaw() - self.get_yaw();
1471 let raw_yaw_delta: f32 = diff - (diff / TAU).floor() * TAU;
1472 let shortest_yaw: f32 = if raw_yaw_delta > PI {
1473 raw_yaw_delta - TAU
1474 } else {
1475 raw_yaw_delta
1476 };
1477 Self {
1478 position: self.get_position().lerp(other.get_position(), k),
1479 yaw: self.get_yaw() + shortest_yaw * k,
1480 pitch: (self.get_pitch() + (other.get_pitch() - self.get_pitch()) * k).clamp(-1.4, 1.4),
1481 fov_deg: self.get_fov_deg() + (other.get_fov_deg() - self.get_fov_deg()) * k,
1482 near: self.get_near() + (other.get_near() - self.get_near()) * k,
1483 far: self.get_far() + (other.get_far() - self.get_far()) * k,
1484 }
1485 }
1486
1487 /// Computes the combined `projection * view` matrix for viewport `aspect`.
1488 ///
1489 /// # Arguments
1490 ///
1491 /// - `&Self` - Camera reference.
1492 /// - `f32` - Viewport aspect ratio `width / height`.
1493 ///
1494 /// # Returns
1495 ///
1496 /// - `Mat4` - View-projection matrix.
1497 #[must_use]
1498 pub fn view_projection(&self, aspect: f32) -> Mat4 {
1499 let pos: Vec3 = self.get_position();
1500 let view: Mat4 = Mat4::look_at(pos, pos.add(self.forward()), Vec3::new(0.0, 1.0, 0.0));
1501 let proj: Mat4 = Mat4::perspective(
1502 self.get_fov_deg().to_radians(),
1503 aspect.max(0.1),
1504 self.get_near().max(0.05),
1505 self.get_far().max(10.0),
1506 );
1507 proj.mul(view)
1508 }
1509}