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
use crate::Distance;
use mini_math::{Point, Vector3};
#[derive(Debug)]
pub struct Ray {
pub origin: Point,
pub direction: Vector3,
}
impl Ray {
pub fn new(origin: Point, direction: Vector3) -> Self {
Self { origin, direction }
}
}
impl Distance<Point> for Ray {
fn distance(&self, p: Point) -> f32 {
let diff = p - self.origin;
let dot = self.direction.dot(diff);
if dot < 0.0 {
return diff.magnitude();
}
let cross = self.direction.cross(diff);
cross.magnitude()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_distance() {
let ray = Ray::new(Point::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 1.0));
let p = Point::new(0.0, 0.0, -5.0);
assert_eq!(ray.distance(p), 5.0);
let p = Point::new(0.0, 5.0, 25.0);
assert_eq!(ray.distance(p), 5.0);
}
}