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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
use crate::{Point, Vector};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
#[repr(C)]
pub struct Line<const D: usize> {
pub origin: Point<D>,
pub direction: Vector<D>,
}
impl<const D: usize> Line<D> {
pub fn from_points(points: [impl Into<Point<D>>; 2]) -> Self {
let [a, b] = points.map(Into::into);
Self {
origin: a,
direction: b - a,
}
}
#[must_use]
pub fn reverse(mut self) -> Self {
self.direction = -self.direction;
self
}
pub fn point_to_line_coords(&self, point: impl Into<Point<D>>) -> Point<1> {
Point {
coords: self.vector_to_line_coords(point.into() - self.origin),
}
}
pub fn vector_to_line_coords(
&self,
vector: impl Into<Vector<D>>,
) -> Vector<1> {
let t = vector.into().scalar_projection_onto(&self.direction)
/ self.direction.magnitude();
Vector::from([t])
}
pub fn point_from_line_coords(
&self,
point: impl Into<Point<1>>,
) -> Point<D> {
self.origin + self.vector_from_line_coords(point.into().coords)
}
pub fn vector_from_line_coords(
&self,
vector: impl Into<Vector<1>>,
) -> Vector<D> {
self.direction * vector.into().t
}
}
impl<const D: usize> approx::AbsDiffEq for Line<D> {
type Epsilon = <f64 as approx::AbsDiffEq>::Epsilon;
fn default_epsilon() -> Self::Epsilon {
f64::default_epsilon()
}
fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
self.origin.abs_diff_eq(&other.origin, epsilon)
&& self.direction.abs_diff_eq(&other.direction, epsilon)
}
}
#[cfg(test)]
mod tests {
use approx::assert_abs_diff_eq;
use crate::{Point, Vector};
use super::Line;
#[test]
fn convert_point_to_line_coords() {
let line = Line {
origin: Point::from([1., 2., 3.]),
direction: Vector::from([2., 3., 5.]),
};
verify(line, -1.);
verify(line, 0.);
verify(line, 1.);
verify(line, 2.);
fn verify(line: Line<3>, t: f64) {
let point = line.point_from_line_coords([t]);
let t_result = line.point_to_line_coords(point);
assert_abs_diff_eq!(Point::from([t]), t_result, epsilon = 1e-8);
}
}
}