1use crate::position::Position;
2use std::ops::{Add, AddAssign, Mul, Sub, SubAssign};
3
4#[derive(Debug, PartialEq)]
6pub struct Vector {
7 x: f64,
8 y: f64,
9}
10
11impl Vector {
12 pub fn new(x: f64, y: f64) -> Vector {
14 let mut v = Vector { x, y };
15 v.normalise();
16 v
17 }
18
19 pub fn x(&self) -> f64 {
21 self.x
22 }
23
24 pub fn y(&self) -> f64 {
26 self.y
27 }
28
29 pub fn dot(&self, other: &Vector) -> f64 {
31 self.x * other.x + self.y * other.y
32 }
33
34 pub fn negate(&mut self) {
36 self.x = -self.x;
37 self.y = -self.y;
38 }
39
40 pub fn magnitude(&self) -> f64 {
42 (self.x.powi(2) + self.y.powi(2)).sqrt()
43 }
44
45 pub fn normalise(&mut self) {
47 let magnitude = self.magnitude();
48 self.x /= magnitude;
49 self.y /= magnitude;
50 }
51}
52
53impl Add for Vector {
54 type Output = Self;
55
56 fn add(self, other: Self) -> Self {
57 Self {
58 x: self.x + other.x,
59 y: self.y + other.y,
60 }
61 }
62}
63
64impl<'a, 'b> Add<&'b Vector> for &'a Vector {
65 type Output = Vector;
66
67 fn add(self, other: &'b Vector) -> Vector {
68 Vector {
69 x: self.x + other.x,
70 y: self.y + other.y,
71 }
72 }
73}
74
75impl<'a, 'b> Add<&'b Position> for &'a Vector {
76 type Output = Position;
77
78 fn add(self, other: &'b Position) -> Position {
79 Position::new(
80 (self.x + f64::from(other.x())) as u16,
81 (self.y + f64::from(other.y())) as u16,
82 )
83 }
84}
85
86impl AddAssign<Vector> for Vector {
87 fn add_assign(&mut self, other: Self) {
88 *self = Self {
89 x: self.x + other.x,
90 y: self.y + other.y,
91 }
92 }
93}
94
95impl<'a> AddAssign<&'a Vector> for Vector {
96 fn add_assign(&mut self, other: &Self) {
97 *self = Self {
98 x: self.x + other.x,
99 y: self.y + other.y,
100 }
101 }
102}
103
104impl Sub for Vector {
105 type Output = Self;
106
107 fn sub(self, other: Self) -> Self {
108 Self {
109 x: self.x - other.x,
110 y: self.y - other.y,
111 }
112 }
113}
114
115impl SubAssign for Vector {
116 fn sub_assign(&mut self, other: Self) {
117 *self = Self {
118 x: self.x - other.x,
119 y: self.y - other.y,
120 }
121 }
122}
123
124impl Mul<f64> for Vector {
125 type Output = Vector;
126
127 fn mul(self, scalar: f64) -> Vector {
128 Vector {
129 x: self.x * scalar,
130 y: self.y * scalar,
131 }
132 }
133}
134
135impl Mul<Vector> for f64 {
136 type Output = Vector;
137
138 fn mul(self, vector: Vector) -> Vector {
139 Vector {
140 x: self * vector.x,
141 y: self * vector.y,
142 }
143 }
144}