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};
#[derive(Debug)]
pub struct Plane {
pub normal: Vector3,
pub d: f32,
}
impl Plane {
pub fn new(normal: Vector3, d: f32) -> Self {
Self { normal, d }
}
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 }
}
pub fn from_point_and_normal(p: Point, normal: Vector3) -> Self {
Self {
normal,
d: Vector3::from(p).dot(normal),
}
}
pub fn point_closest_to(&self, p: Point) -> Point {
let distance = self.distance(p);
p - self.normal * distance
}
}
impl From<&Triangle> for Plane {
fn from(t: &Triangle) -> Self {
Plane::from_points(t.a, t.b, t.c)
}
}
impl Distance<Point> for Plane {
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));
}
}