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