appcore_render/
frustum.rs1use crate::{BoundingSphere, RenderError};
12#[derive(Debug, Clone, Copy)]
14pub struct Frustum {
15 planes: [[f32; 4]; 6],
16}
17impl Frustum {
18 pub fn from_matrix(matrix: [f32; 16]) -> Result<Self, RenderError> {
20 if !matrix.iter().all(|v| v.is_finite()) {
21 return Err(RenderError::InvalidLimits);
22 }
23 let row = |r: usize| std::array::from_fn::<_, 4, _>(|c| f64::from(matrix[c * 4 + r]));
24 let rows = [row(0), row(1), row(2), row(3)];
25 let combine =
26 |axis: usize, sign: f64| std::array::from_fn(|i| rows[3][i] + sign * rows[axis][i]);
27 let raw = [
28 combine(0, 1.0),
29 combine(0, -1.0),
30 combine(1, 1.0),
31 combine(1, -1.0),
32 rows[2],
33 combine(2, -1.0),
34 ];
35 let mut planes = [[0.0; 4]; 6];
36 for (index, plane) in raw.into_iter().enumerate() {
37 let length = plane[..3].iter().map(|v| v * v).sum::<f64>().sqrt();
38 if !length.is_finite() || length == 0.0 {
39 return Err(RenderError::InvalidLimits);
40 }
41 for (i, value) in plane.into_iter().enumerate() {
42 planes[index][i] = (value / length) as f32;
43 }
44 if !planes[index].iter().all(|v| v.is_finite()) {
45 return Err(RenderError::InvalidLimits);
46 }
47 }
48 Ok(Self { planes })
49 }
50 pub fn planes(&self) -> &[[f32; 4]; 6] {
52 &self.planes
53 }
54 pub fn intersects(&self, sphere: BoundingSphere) -> Result<bool, RenderError> {
56 validate_sphere(sphere)?;
57 Ok(self.planes.iter().all(|plane| {
58 let distance = (0..3)
59 .map(|i| f64::from(plane[i]) * f64::from(sphere.center[i]))
60 .sum::<f64>()
61 + f64::from(plane[3]);
62 let magnitude = (0..3)
63 .map(|i| (f64::from(plane[i]) * f64::from(sphere.center[i])).abs())
64 .sum::<f64>()
65 + f64::from(plane[3]).abs()
66 + f64::from(sphere.radius)
67 + 1.0;
68 distance >= -f64::from(sphere.radius) - magnitude * 0.00001
69 }))
70 }
71}
72pub(crate) fn validate_sphere(sphere: BoundingSphere) -> Result<(), RenderError> {
73 if !sphere
74 .center
75 .iter()
76 .all(|v| v.is_finite() && v.abs() <= 1e12)
77 || !sphere.radius.is_finite()
78 || !(0.0..=1e12).contains(&sphere.radius)
79 {
80 return Err(RenderError::InvalidLimits);
81 }
82 Ok(())
83}