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
125
126
127
128
129
130
131
132
133
134
use crate::*;
#[repr(C)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize, Trans, Schematic)]
pub struct Vec2<T> {
pub x: T,
pub y: T,
}
impl<T: Display> Display for Vec2<T> {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> fmt::Result {
write!(fmt, "({}, {})", self.x, self.y)
}
}
pub const fn vec2<T>(x: T, y: T) -> Vec2<T> {
Vec2 { x, y }
}
impl<T> From<[T; 2]> for Vec2<T> {
fn from(v: [T; 2]) -> Vec2<T> {
let [x, y] = v;
vec2(x, y)
}
}
impl<T> Deref for Vec2<T> {
type Target = [T; 2];
fn deref(&self) -> &[T; 2] {
unsafe { mem::transmute(self) }
}
}
impl<T> DerefMut for Vec2<T> {
fn deref_mut(&mut self) -> &mut [T; 2] {
unsafe { mem::transmute(self) }
}
}
impl<T> Vec2<T> {
pub fn extend(self, z: T) -> Vec3<T> {
vec3(self.x, self.y, z)
}
pub fn map<U, F: Fn(T) -> U>(self, f: F) -> Vec2<U> {
vec2(f(self.x), f(self.y))
}
}
impl<T: Num + Copy> Vec2<T> {
pub fn dot(a: Self, b: Self) -> T {
a.x * b.x + a.y * b.y
}
pub fn skew(a: Self, b: Self) -> T {
a.x * b.y - a.y * b.x
}
}
impl<T: Neg<Output = T>> Vec2<T> {
pub fn rotate_90(self) -> Self {
vec2(-self.y, self.x)
}
}
impl<T: Float> Vec2<T> {
pub fn normalize(self) -> Self {
self / self.len()
}
pub fn len(self) -> T {
T::sqrt(self.x * self.x + self.y * self.y)
}
pub fn rotated(v: Self, angle: T) -> Self {
let (sin, cos) = T::sin_cos(angle);
Self {
x: v.x * cos - v.y * sin,
y: v.x * sin + v.y * cos,
}
}
pub fn clamp(self, max_len: T) -> Self {
let len = self.len();
if len > max_len {
self * max_len / len
} else {
self
}
}
pub fn arg(self) -> T {
T::atan2(self.y, self.x)
}
}