1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use crate::{Distance, Triangle};
use mini_math::{Point, Vector3};

/// An infinite plane.
#[derive(Debug)]
pub struct Plane {
    /// The normal that liest perpendicular to the plane.
    pub normal: Vector3,
    /// The distance from the plane to the origin.
    pub d: f32,
}

impl Plane {
    /// Construct a plane given the components of the plan equation.
    pub fn new(normal: Vector3, d: f32) -> Self {
        Self { normal, d }
    }

    /// Constructs a plane from three points that lie on the plane.
    pub fn from_points(p0: Point, p1: Point, p2: Point) -> Self {
        let normal = -(p1 - p0).cross(p2 - p0).normalized();
        let d = Vector3::from(p0).dot(normal);
        Self { normal, d }
    }

    /// Constructs a plane from a point that lies on the plane, and the normal to the plane.
    pub fn from_point_and_normal(p: Point, normal: Vector3) -> Self {
        Self {
            normal,
            d: Vector3::from(p).dot(normal),
        }
    }

    /// Returns the point on the plane that is closest to the given point.
    pub fn point_closest_to(&self, p: Point) -> Point {
        let distance = self.distance(p);
        p - self.normal * distance
    }
}

impl From<&Triangle> for Plane {
    /// Convert a vector into a point
    fn from(t: &Triangle) -> Self {
        Plane::from_points(t.a, t.b, t.c)
    }
}

impl Distance<Point> for Plane {
    /// Returns the signed distance between the plane and a given point.
    fn distance(&self, p: Point) -> f32 {
        self.normal.dot(Vector3::from(p)) - self.d
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_distance() {
        let plane = Plane::from_points(
            Point::new(-1.0, 0.0, -1.0),
            Point::new(1.0, 0.0, -1.0),
            Point::new(0.0, 0.0, 1.0),
        );

        let p = Point::new(3.0, 1.0, 2.0);
        assert_eq!(plane.distance(p), 1.0);

        let p = Point::new(-2.0, -1.0, -3.0);
        assert_eq!(plane.distance(p), -1.0);
    }

    #[test]
    fn test_closest_point() {
        let plane = Plane::from_points(
            Point::new(-1.0, 0.0, -1.0),
            Point::new(1.0, 0.0, -1.0),
            Point::new(0.0, 0.0, 1.0),
        );

        let p = Point::new(2.0, 1.0, 3.0);
        assert_eq!(plane.point_closest_to(p), Point::new(2.0, 0.0, 3.0));

        let p = Point::new(-2.0, -1.0, -3.0);
        assert_eq!(plane.point_closest_to(p), Point::new(-2.0, 0.0, -3.0));
    }
}