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
use crate::*;
#[repr(C)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize, Trans, Schematic)]
pub struct Vec3<T> {
pub x: T,
pub y: T,
pub z: T,
}
impl<T: Display> Display for Vec3<T> {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> fmt::Result {
write!(fmt, "({}, {}, {})", self.x, self.y, self.z)
}
}
pub const fn vec3<T>(x: T, y: T, z: T) -> Vec3<T> {
Vec3 { x, y, z }
}
impl<T> From<[T; 3]> for Vec3<T> {
fn from(v: [T; 3]) -> Vec3<T> {
let [x, y, z] = v;
vec3(x, y, z)
}
}
impl<T> Deref for Vec3<T> {
type Target = [T; 3];
fn deref(&self) -> &[T; 3] {
unsafe { mem::transmute(self) }
}
}
impl<T> DerefMut for Vec3<T> {
fn deref_mut(&mut self) -> &mut [T; 3] {
unsafe { mem::transmute(self) }
}
}
impl<T> Vec3<T> {
pub fn extend(self, w: T) -> Vec4<T> {
vec4(self.x, self.y, self.z, w)
}
pub fn map<U, F: Fn(T) -> U>(self, f: F) -> Vec3<U> {
vec3(f(self.x), f(self.y), f(self.z))
}
}
impl<T: Copy + Num> Vec3<T> {
pub fn dot(a: Self, b: Self) -> T {
a.x * b.x + a.y * b.y + a.z * b.z
}
pub fn cross(a: Self, b: Self) -> Self {
Self {
x: a.y * b.z - a.z * b.y,
y: a.z * b.x - a.x * b.z,
z: a.x * b.y - a.y * b.x,
}
}
}
impl<T: Float> Vec3<T> {
pub fn normalize(self) -> Self {
self / self.len()
}
pub fn len(self) -> T {
T::sqrt(self.x * self.x + self.y * self.y + self.z * self.z)
}
pub fn clamp(self, max_len: T) -> Self {
let len = self.len();
if len > max_len {
self * max_len / len
} else {
self
}
}
}