Calculations from the world's 2D to the wall's 1D
[kaka/rust-sdl-test.git] / src / geometry.rs
CommitLineData
2836f506 1use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Neg};
296187ca 2
60058b91
TW
3////////// POINT ///////////////////////////////////////////////////////////////
4
787dbfb4 5#[macro_export]
296187ca 6macro_rules! point {
6ba7aef1 7 ( $x:expr, $y:expr ) => {
e570927a 8 Point { x: $x, y: $y }
6ba7aef1 9 };
296187ca
TW
10}
11
b0566120 12#[derive(Debug, Default, Copy, Clone, PartialEq)]
e570927a 13pub struct Point<T> {
296187ca
TW
14 pub x: T,
15 pub y: T,
16}
17
e570927a 18impl Point<f64> {
eca25591 19 pub fn length(&self) -> f64 {
296187ca
TW
20 ((self.x * self.x) + (self.y * self.y)).sqrt()
21 }
bf7b5671 22
93fc5734 23 pub fn normalized(&self) -> Self {
eca25591
TW
24 let l = self.length();
25 Self {
26 x: self.x / l,
27 y: self.y / l,
28 }
29 }
30
40742678
TW
31 pub fn to_angle(&self) -> Angle {
32 self.y.atan2(self.x).radians()
eca25591
TW
33 }
34
e570927a
TW
35 pub fn to_i32(self) -> Point<i32> {
36 Point {
bf7b5671
TW
37 x: self.x as i32,
38 y: self.y as i32,
39 }
40 }
b1075e66
TW
41
42 pub fn cross_product(&self, p: Self) -> f64 {
43 return self.x * p.y - self.y * p.x;
44 }
15cda333
TW
45
46 /// Returns the perpendicular projection of this vector on a line with the specified angle.
47 pub fn project_onto(&self, angle: Angle) -> Point<f64> {
48 let dot_product = self.length() * (self.to_angle() - angle).to_radians().cos();
49 Point::from(angle) * dot_product
50 }
296187ca
TW
51}
52
0d75b79e 53macro_rules! impl_point_op {
6cd86b94 54 ($op:tt, $trait:ident($fn:ident), $trait_assign:ident($fn_assign:ident), $rhs:ident = $Rhs:ty => $x:expr, $y:expr) => {
e570927a 55 impl<T: $trait<Output = T>> $trait<$Rhs> for Point<T> {
6cd86b94
TW
56 type Output = Self;
57
58 fn $fn(self, $rhs: $Rhs) -> Self {
59 Self {
60 x: self.x $op $x,
61 y: self.y $op $y,
62 }
63 }
2836f506 64 }
2836f506 65
e570927a 66 impl<T: $trait<Output = T> + Copy> $trait_assign<$Rhs> for Point<T> {
6cd86b94
TW
67 fn $fn_assign(&mut self, $rhs: $Rhs) {
68 *self = Self {
69 x: self.x $op $x,
70 y: self.y $op $y,
71 }
72 }
2836f506
TW
73 }
74 }
75}
76
0d75b79e
TW
77impl_point_op!(+, Add(add), AddAssign(add_assign), rhs = Point<T> => rhs.x, rhs.y);
78impl_point_op!(-, Sub(sub), SubAssign(sub_assign), rhs = Point<T> => rhs.x, rhs.y);
79impl_point_op!(*, Mul(mul), MulAssign(mul_assign), rhs = Point<T> => rhs.x, rhs.y);
80impl_point_op!(/, Div(div), DivAssign(div_assign), rhs = Point<T> => rhs.x, rhs.y);
81impl_point_op!(+, Add(add), AddAssign(add_assign), rhs = (T, T) => rhs.0, rhs.1);
82impl_point_op!(-, Sub(sub), SubAssign(sub_assign), rhs = (T, T) => rhs.0, rhs.1);
83impl_point_op!(*, Mul(mul), MulAssign(mul_assign), rhs = (T, T) => rhs.0, rhs.1);
84impl_point_op!(/, Div(div), DivAssign(div_assign), rhs = (T, T) => rhs.0, rhs.1);
85impl_point_op!(*, Mul(mul), MulAssign(mul_assign), rhs = Dimension<T> => rhs.width, rhs.height);
86impl_point_op!(/, Div(div), DivAssign(div_assign), rhs = Dimension<T> => rhs.width, rhs.height);
2836f506
TW
87
88////////// multiply point with scalar //////////////////////////////////////////
e570927a 89impl<T: Mul<Output = T> + Copy> Mul<T> for Point<T> {
2836f506
TW
90 type Output = Self;
91
92 fn mul(self, rhs: T) -> Self {
93 Self {
94 x: self.x * rhs,
95 y: self.y * rhs,
96 }
97 }
98}
99
e570927a 100impl<T: Mul<Output = T> + Copy> MulAssign<T> for Point<T> {
2836f506
TW
101 fn mul_assign(&mut self, rhs: T) {
102 *self = Self {
103 x: self.x * rhs,
104 y: self.y * rhs,
105 }
106 }
107}
108
2836f506 109////////// divide point with scalar ////////////////////////////////////////////
e570927a 110impl<T: Div<Output = T> + Copy> Div<T> for Point<T> {
2836f506
TW
111 type Output = Self;
112
113 fn div(self, rhs: T) -> Self {
114 Self {
115 x: self.x / rhs,
116 y: self.y / rhs,
117 }
118 }
119}
120
e570927a 121impl<T: Div<Output = T> + Copy> DivAssign<T> for Point<T> {
2836f506
TW
122 fn div_assign(&mut self, rhs: T) {
123 *self = Self {
124 x: self.x / rhs,
125 y: self.y / rhs,
126 }
127 }
128}
129
e570927a 130impl<T: Neg<Output = T>> Neg for Point<T> {
2836f506
TW
131 type Output = Self;
132
133 fn neg(self) -> Self {
134 Self {
135 x: -self.x,
136 y: -self.y,
137 }
296187ca
TW
138 }
139}
140
e570927a 141impl<T> From<(T, T)> for Point<T> {
b0566120 142 fn from(item: (T, T)) -> Self {
e570927a 143 Point {
b0566120
TW
144 x: item.0,
145 y: item.1,
146 }
147 }
148}
149
e570927a
TW
150impl<T> From<Point<T>> for (T, T) {
151 fn from(item: Point<T>) -> Self {
bf7b5671
TW
152 (item.x, item.y)
153 }
154}
155
40742678
TW
156impl From<Angle> for Point<f64> {
157 fn from(item: Angle) -> Self {
158 Point {
159 x: item.0.cos(),
160 y: item.0.sin(),
161 }
e58a1769
TW
162 }
163}
164
40742678 165////////// ANGLE ///////////////////////////////////////////////////////////////
e58a1769 166
a9eacb2b 167#[derive(Debug, Default, Clone, Copy)]
40742678 168pub struct Angle(pub f64);
e58a1769 169
40742678
TW
170pub trait ToAngle {
171 fn radians(self) -> Angle;
172 fn degrees(self) -> Angle;
173}
174
175macro_rules! impl_angle {
176 ($($type:ty),*) => {
177 $(
178 impl ToAngle for $type {
179 fn radians(self) -> Angle {
180 Angle(self as f64)
181 }
182
183 fn degrees(self) -> Angle {
184 Angle((self as f64).to_radians())
185 }
186 }
187
188 impl Mul<$type> for Angle {
189 type Output = Self;
190
191 fn mul(self, rhs: $type) -> Self {
192 Angle(self.0 * (rhs as f64))
193 }
194 }
195
196 impl MulAssign<$type> for Angle {
197 fn mul_assign(&mut self, rhs: $type) {
198 self.0 *= rhs as f64;
199 }
200 }
201
202 impl Div<$type> for Angle {
203 type Output = Self;
204
205 fn div(self, rhs: $type) -> Self {
206 Angle(self.0 / (rhs as f64))
207 }
208 }
209
210 impl DivAssign<$type> for Angle {
211 fn div_assign(&mut self, rhs: $type) {
212 self.0 /= rhs as f64;
213 }
214 }
215 )*
e58a1769
TW
216 }
217}
218
40742678
TW
219impl_angle!(f32, f64, i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
220
221impl Angle {
222 pub fn to_radians(self) -> f64 {
223 self.0
224 }
225
226 pub fn to_degrees(self) -> f64 {
227 self.0.to_degrees()
e58a1769 228 }
8065e264
TW
229
230 /// Returns the reflection of the incident when mirrored along this angle.
40742678
TW
231 pub fn mirror(&self, incidence: Angle) -> Angle {
232 Angle((std::f64::consts::PI + self.0 * 2.0 - incidence.0) % std::f64::consts::TAU)
233 }
15cda333
TW
234
235 pub fn reverse(&self) -> Angle {
236 Angle((self.0 + std::f64::consts::PI) % std::f64::consts::TAU)
237 }
40742678
TW
238}
239
a9eacb2b
TW
240impl PartialEq for Angle {
241 fn eq(&self, rhs: &Angle) -> bool {
242 self.0 % std::f64::consts::TAU == rhs.0 % std::f64::consts::TAU
243 }
244}
40742678
TW
245
246// addition and subtraction of angles
247
248impl Add<Angle> for Angle {
249 type Output = Self;
250
251 fn add(self, rhs: Angle) -> Self {
252 Angle(self.0 + rhs.0)
253 }
254}
255
256impl AddAssign<Angle> for Angle {
257 fn add_assign(&mut self, rhs: Angle) {
258 self.0 += rhs.0;
259 }
260}
261
262impl Sub<Angle> for Angle {
263 type Output = Self;
264
265 fn sub(self, rhs: Angle) -> Self {
266 Angle(self.0 - rhs.0)
267 }
268}
269
270impl SubAssign<Angle> for Angle {
271 fn sub_assign(&mut self, rhs: Angle) {
272 self.0 -= rhs.0;
8065e264 273 }
e58a1769
TW
274}
275
60058b91
TW
276////////// INTERSECTION ////////////////////////////////////////////////////////
277
278#[derive(Debug)]
279pub enum Intersection {
280 Point(Point<f64>),
281 //Line(Point<f64>, Point<f64>), // TODO: overlapping collinear
282 None,
283}
284
285impl Intersection {
286 pub fn lines(p1: Point<f64>, p2: Point<f64>, p3: Point<f64>, p4: Point<f64>) -> Intersection {
287 let s1 = p2 - p1;
288 let s2 = p4 - p3;
289
290 let denomimator = -s2.x * s1.y + s1.x * s2.y;
291 if denomimator != 0.0 {
292 let s = (-s1.y * (p1.x - p3.x) + s1.x * (p1.y - p3.y)) / denomimator;
293 let t = ( s2.x * (p1.y - p3.y) - s2.y * (p1.x - p3.x)) / denomimator;
294
0c56b1f7 295 if (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&t) {
60058b91
TW
296 return Intersection::Point(p1 + (s1 * t))
297 }
298 }
299
300 Intersection::None
301 }
302}
303
304////////// DIMENSION ///////////////////////////////////////////////////////////
305
0b5024d1 306#[macro_export]
1f42d724
TW
307macro_rules! dimen {
308 ( $w:expr, $h:expr ) => {
309 Dimension { width: $w, height: $h }
0b5024d1
TW
310 };
311}
312
8012f86b 313#[derive(Debug, Default, Copy, Clone, PartialEq)]
1f42d724 314pub struct Dimension<T> {
6edafdc0
TW
315 pub width: T,
316 pub height: T,
317}
318
1f42d724 319impl<T: Mul<Output = T> + Copy> Dimension<T> {
6edafdc0
TW
320 #[allow(dead_code)]
321 pub fn area(&self) -> T {
6ba7aef1 322 self.width * self.height
6edafdc0
TW
323 }
324}
325
1f42d724 326impl<T> From<(T, T)> for Dimension<T> {
6edafdc0 327 fn from(item: (T, T)) -> Self {
1f42d724 328 Dimension {
6ba7aef1
TW
329 width: item.0,
330 height: item.1,
331 }
6edafdc0
TW
332 }
333}
334
8012f86b
TW
335impl<T> From<Dimension<T>> for (T, T) {
336 fn from(item: Dimension<T>) -> Self {
337 (item.width, item.height)
338 }
339}
340
341////////////////////////////////////////////////////////////////////////////////
342
343#[allow(dead_code)]
344pub fn supercover_line_int(p1: Point<isize>, p2: Point<isize>) -> Vec<Point<isize>> {
345 let d = p2 - p1;
346 let n = point!(d.x.abs(), d.y.abs());
bb3eb700 347 let step = point!(d.x.signum(), d.y.signum());
8012f86b 348
0c56b1f7 349 let mut p = p1;
8012f86b
TW
350 let mut points = vec!(point!(p.x as isize, p.y as isize));
351 let mut i = point!(0, 0);
352 while i.x < n.x || i.y < n.y {
353 let decision = (1 + 2 * i.x) * n.y - (1 + 2 * i.y) * n.x;
354 if decision == 0 { // next step is diagonal
355 p.x += step.x;
356 p.y += step.y;
357 i.x += 1;
358 i.y += 1;
359 } else if decision < 0 { // next step is horizontal
360 p.x += step.x;
361 i.x += 1;
362 } else { // next step is vertical
363 p.y += step.y;
364 i.y += 1;
365 }
366 points.push(point!(p.x as isize, p.y as isize));
367 }
368
369 points
370}
371
372/// Calculates all points a line crosses, unlike Bresenham's line algorithm.
373/// There might be room for a lot of improvement here.
374pub fn supercover_line(mut p1: Point<f64>, mut p2: Point<f64>) -> Vec<Point<isize>> {
375 let mut delta = p2 - p1;
376 if (delta.x.abs() > delta.y.abs() && delta.x.is_sign_negative()) || (delta.x.abs() <= delta.y.abs() && delta.y.is_sign_negative()) {
377 std::mem::swap(&mut p1, &mut p2);
378 delta = -delta;
379 }
380
381 let mut last = point!(p1.x as isize, p1.y as isize);
382 let mut coords: Vec<Point<isize>> = vec!();
383 coords.push(last);
384
385 if delta.x.abs() > delta.y.abs() {
386 let k = delta.y / delta.x;
387 let m = p1.y as f64 - p1.x as f64 * k;
388 for x in (p1.x as isize + 1)..=(p2.x as isize) {
389 let y = (k * x as f64 + m).floor();
390 let next = point!(x as isize - 1, y as isize);
391 if next != last {
392 coords.push(next);
393 }
394 let next = point!(x as isize, y as isize);
395 coords.push(next);
396 last = next;
397 }
398 } else {
399 let k = delta.x / delta.y;
400 let m = p1.x as f64 - p1.y as f64 * k;
401 for y in (p1.y as isize + 1)..=(p2.y as isize) {
402 let x = (k * y as f64 + m).floor();
403 let next = point!(x as isize, y as isize - 1);
404 if next != last {
405 coords.push(next);
406 }
407 let next = point!(x as isize, y as isize);
408 coords.push(next);
409 last = next;
410 }
411 }
412
413 let next = point!(p2.x as isize, p2.y as isize);
414 if next != last {
415 coords.push(next);
416 }
417
418 coords
419}
420
60058b91 421////////// TESTS ///////////////////////////////////////////////////////////////
249d43ea 422
296187ca
TW
423#[cfg(test)]
424mod tests {
425 use super::*;
426
427 #[test]
428 fn immutable_copy_of_point() {
429 let a = point!(0, 0);
430 let mut b = a; // Copy
431 assert_eq!(a, b); // PartialEq
432 b.x = 1;
433 assert_ne!(a, b); // PartialEq
434 }
435
436 #[test]
437 fn add_points() {
438 let mut a = point!(1, 0);
439 assert_eq!(a + point!(2, 2), point!(3, 2)); // Add
440 a += point!(2, 2); // AddAssign
441 assert_eq!(a, point!(3, 2));
2836f506
TW
442 assert_eq!(point!(1, 0) + (2, 3), point!(3, 3));
443 }
444
445 #[test]
446 fn sub_points() {
447 let mut a = point!(1, 0);
448 assert_eq!(a - point!(2, 2), point!(-1, -2));
449 a -= point!(2, 2);
450 assert_eq!(a, point!(-1, -2));
6cd86b94 451 assert_eq!(point!(1, 0) - (2, 3), point!(-1, -3));
2836f506
TW
452 }
453
454 #[test]
455 fn mul_points() {
456 let mut a = point!(1, 2);
457 assert_eq!(a * 2, point!(2, 4));
458 assert_eq!(a * point!(2, 3), point!(2, 6));
459 a *= 2;
460 assert_eq!(a, point!(2, 4));
461 a *= point!(3, 1);
462 assert_eq!(a, point!(6, 4));
6cd86b94 463 assert_eq!(point!(1, 0) * (2, 3), point!(2, 0));
2836f506
TW
464 }
465
466 #[test]
467 fn div_points() {
468 let mut a = point!(4, 8);
469 assert_eq!(a / 2, point!(2, 4));
470 assert_eq!(a / point!(2, 4), point!(2, 2));
471 a /= 2;
472 assert_eq!(a, point!(2, 4));
473 a /= point!(2, 4);
474 assert_eq!(a, point!(1, 1));
6cd86b94 475 assert_eq!(point!(6, 3) / (2, 3), point!(3, 1));
2836f506
TW
476 }
477
478 #[test]
479 fn neg_point() {
480 assert_eq!(point!(1, 1), -point!(-1, -1));
296187ca 481 }
6edafdc0
TW
482
483 #[test]
e58a1769 484 fn angles() {
40742678 485 assert_eq!(0.radians(), 0.degrees());
a9eacb2b 486 assert_eq!(0.degrees(), 360.degrees());
40742678
TW
487 assert_eq!(180.degrees(), std::f64::consts::PI.radians());
488 assert_eq!(std::f64::consts::PI.radians().to_degrees(), 180.0);
489 assert!((Point::from(90.degrees()) - point!(0.0, 1.0)).length() < 0.001);
490 assert!((Point::from(std::f64::consts::FRAC_PI_2.radians()) - point!(0.0, 1.0)).length() < 0.001);
e58a1769
TW
491 }
492
493 #[test]
1f42d724
TW
494 fn area_for_dimension_of_multipliable_type() {
495 let r: Dimension<_> = (30, 20).into(); // the Into trait uses the From trait
6ba7aef1 496 assert_eq!(r.area(), 30 * 20);
1f42d724 497 // let a = Dimension::from(("a".to_string(), "b".to_string())).area(); // this doesn't work, because area() is not implemented for String
6edafdc0 498 }
60058b91
TW
499
500 #[test]
501 fn intersection_of_lines() {
502 let p1 = point!(0.0, 0.0);
503 let p2 = point!(2.0, 2.0);
504 let p3 = point!(0.0, 2.0);
505 let p4 = point!(2.0, 0.0);
506 let r = Intersection::lines(p1, p2, p3, p4);
507 if let Intersection::Point(p) = r {
508 assert_eq!(p, point!(1.0, 1.0));
509 } else {
510 panic!();
511 }
512 }
8012f86b
TW
513
514 #[test]
515 fn some_coordinates_on_line() {
516 // horizontally up
517 let coords = supercover_line(point!(0.0, 0.0), point!(3.3, 2.2));
518 assert_eq!(coords.as_slice(), &[point!(0, 0), point!(1, 0), point!(1, 1), point!(2, 1), point!(2, 2), point!(3, 2)]);
519
520 // horizontally down
521 let coords = supercover_line(point!(0.0, 5.0), point!(3.3, 2.2));
522 assert_eq!(coords.as_slice(), &[point!(0, 5), point!(0, 4), point!(1, 4), point!(1, 3), point!(2, 3), point!(2, 2), point!(3, 2)]);
523
524 // vertically right
525 let coords = supercover_line(point!(0.0, 0.0), point!(2.2, 3.3));
526 assert_eq!(coords.as_slice(), &[point!(0, 0), point!(0, 1), point!(1, 1), point!(1, 2), point!(2, 2), point!(2, 3)]);
527
528 // vertically left
529 let coords = supercover_line(point!(5.0, 0.0), point!(3.0, 3.0));
530 assert_eq!(coords.as_slice(), &[point!(5, 0), point!(4, 0), point!(4, 1), point!(3, 1), point!(3, 2), point!(3, 3)]);
531
532 // negative
533 let coords = supercover_line(point!(0.0, 0.0), point!(-3.0, -2.0));
534 assert_eq!(coords.as_slice(), &[point!(-3, -2), point!(-2, -2), point!(-2, -1), point!(-1, -1), point!(-1, 0), point!(0, 0)]);
535
536 //
537 let coords = supercover_line(point!(0.0, 0.0), point!(2.3, 1.1));
538 assert_eq!(coords.as_slice(), &[point!(0, 0), point!(1, 0), point!(2, 0), point!(2, 1)]);
539 }
296187ca 540}