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