1use crate::algebra::Vector3;
2use crate::visitor::{Visit, VisitResult, Visitor};
3
4#[derive(Copy, Clone, Debug, PartialEq)]
5pub struct Plane {
6 pub normal: Vector3<f32>,
7 pub d: f32,
8}
9
10impl Default for Plane {
11 #[inline]
12 fn default() -> Self {
13 Plane {
14 normal: Vector3::new(0.0, 1.0, 0.0),
15 d: 0.0,
16 }
17 }
18}
19
20impl Plane {
21 #[inline]
24 pub fn from_normal_and_point(normal: &Vector3<f32>, point: &Vector3<f32>) -> Option<Self> {
25 normal
26 .try_normalize(f32::EPSILON)
27 .map(|normalized_normal| Self {
28 normal: normalized_normal,
29 d: -point.dot(&normalized_normal),
30 })
31 }
32
33 #[inline]
36 pub fn from_abcd(a: f32, b: f32, c: f32, d: f32) -> Option<Self> {
37 let normal = Vector3::new(a, b, c);
38 let len = normal.norm();
39 if len == 0.0 {
40 None
41 } else {
42 let coeff = 1.0 / len;
43 Some(Self {
44 normal: normal.scale(coeff),
45 d: d * coeff,
46 })
47 }
48 }
49
50 #[inline]
51 pub fn dot(&self, point: &Vector3<f32>) -> f32 {
52 self.normal.dot(point) + self.d
53 }
54
55 #[inline]
56 pub fn distance(&self, point: &Vector3<f32>) -> f32 {
57 self.dot(point).abs()
58 }
59
60 pub fn intersection_point(&self, b: &Plane, c: &Plane) -> Vector3<f32> {
62 let f = -1.0 / self.normal.dot(&b.normal.cross(&c.normal));
63
64 let v1 = b.normal.cross(&c.normal).scale(self.d);
65 let v2 = c.normal.cross(&self.normal).scale(b.d);
66 let v3 = self.normal.cross(&b.normal).scale(c.d);
67
68 (v1 + v2 + v3).scale(f)
69 }
70}
71
72impl Visit for Plane {
73 fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
74 visitor.enter_region(name)?;
75
76 self.normal.visit("Normal", visitor)?;
77 self.d.visit("D", visitor)?;
78
79 visitor.leave_region()
80 }
81}
82
83#[test]
84fn plane_sanity_tests() {
85 let plane =
87 Plane::from_normal_and_point(&Vector3::new(0.0, 10.0, 0.0), &Vector3::new(0.0, 3.0, 0.0));
88 assert!(plane.is_some());
89 let plane = plane.unwrap();
90 assert_eq!(plane.normal.x, 0.0);
91 assert_eq!(plane.normal.y, 1.0);
92 assert_eq!(plane.normal.z, 0.0);
93 assert_eq!(plane.d, -3.0);
94
95 let plane =
97 Plane::from_normal_and_point(&Vector3::new(0.0, 0.0, 0.0), &Vector3::new(0.0, 0.0, 0.0));
98 assert!(plane.is_none());
99
100 let plane = Plane::from_abcd(0.0, 0.0, 0.0, 0.0);
101 assert!(plane.is_none())
102}