Moved geometry to root level
[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 }
296187ca
TW
41}
42
0d75b79e 43macro_rules! impl_point_op {
6cd86b94 44 ($op:tt, $trait:ident($fn:ident), $trait_assign:ident($fn_assign:ident), $rhs:ident = $Rhs:ty => $x:expr, $y:expr) => {
e570927a 45 impl<T: $trait<Output = T>> $trait<$Rhs> for Point<T> {
6cd86b94
TW
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 }
2836f506 54 }
2836f506 55
e570927a 56 impl<T: $trait<Output = T> + Copy> $trait_assign<$Rhs> for Point<T> {
6cd86b94
TW
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 }
2836f506
TW
63 }
64 }
65}
66
0d75b79e
TW
67impl_point_op!(+, Add(add), AddAssign(add_assign), rhs = Point<T> => rhs.x, rhs.y);
68impl_point_op!(-, Sub(sub), SubAssign(sub_assign), rhs = Point<T> => rhs.x, rhs.y);
69impl_point_op!(*, Mul(mul), MulAssign(mul_assign), rhs = Point<T> => rhs.x, rhs.y);
70impl_point_op!(/, Div(div), DivAssign(div_assign), rhs = Point<T> => rhs.x, rhs.y);
71impl_point_op!(+, Add(add), AddAssign(add_assign), rhs = (T, T) => rhs.0, rhs.1);
72impl_point_op!(-, Sub(sub), SubAssign(sub_assign), rhs = (T, T) => rhs.0, rhs.1);
73impl_point_op!(*, Mul(mul), MulAssign(mul_assign), rhs = (T, T) => rhs.0, rhs.1);
74impl_point_op!(/, Div(div), DivAssign(div_assign), rhs = (T, T) => rhs.0, rhs.1);
75impl_point_op!(*, Mul(mul), MulAssign(mul_assign), rhs = Dimension<T> => rhs.width, rhs.height);
76impl_point_op!(/, Div(div), DivAssign(div_assign), rhs = Dimension<T> => rhs.width, rhs.height);
2836f506
TW
77
78////////// multiply point with scalar //////////////////////////////////////////
e570927a 79impl<T: Mul<Output = T> + Copy> Mul<T> for Point<T> {
2836f506
TW
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
e570927a 90impl<T: Mul<Output = T> + Copy> MulAssign<T> for Point<T> {
2836f506
TW
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
2836f506 99////////// divide point with scalar ////////////////////////////////////////////
e570927a 100impl<T: Div<Output = T> + Copy> Div<T> for Point<T> {
2836f506
TW
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
e570927a 111impl<T: Div<Output = T> + Copy> DivAssign<T> for Point<T> {
2836f506
TW
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
e570927a 120impl<T: Neg<Output = T>> Neg for Point<T> {
2836f506
TW
121 type Output = Self;
122
123 fn neg(self) -> Self {
124 Self {
125 x: -self.x,
126 y: -self.y,
127 }
296187ca
TW
128 }
129}
130
e570927a 131impl<T> From<(T, T)> for Point<T> {
b0566120 132 fn from(item: (T, T)) -> Self {
e570927a 133 Point {
b0566120
TW
134 x: item.0,
135 y: item.1,
136 }
137 }
138}
139
e570927a
TW
140impl<T> From<Point<T>> for (T, T) {
141 fn from(item: Point<T>) -> Self {
bf7b5671
TW
142 (item.x, item.y)
143 }
144}
145
40742678
TW
146impl From<Angle> for Point<f64> {
147 fn from(item: Angle) -> Self {
148 Point {
149 x: item.0.cos(),
150 y: item.0.sin(),
151 }
e58a1769
TW
152 }
153}
154
40742678 155////////// ANGLE ///////////////////////////////////////////////////////////////
e58a1769 156
a9eacb2b 157#[derive(Debug, Default, Clone, Copy)]
40742678 158pub struct Angle(pub f64);
e58a1769 159
40742678
TW
160pub trait ToAngle {
161 fn radians(self) -> Angle;
162 fn degrees(self) -> Angle;
163}
164
165macro_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 )*
e58a1769
TW
206 }
207}
208
40742678
TW
209impl_angle!(f32, f64, i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
210
211impl 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()
e58a1769 218 }
8065e264
TW
219
220 /// Returns the reflection of the incident when mirrored along this angle.
40742678
TW
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
a9eacb2b
TW
226impl 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}
40742678
TW
231
232// addition and subtraction of angles
233
234impl 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
242impl AddAssign<Angle> for Angle {
243 fn add_assign(&mut self, rhs: Angle) {
244 self.0 += rhs.0;
245 }
246}
247
248impl 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
256impl SubAssign<Angle> for Angle {
257 fn sub_assign(&mut self, rhs: Angle) {
258 self.0 -= rhs.0;
8065e264 259 }
e58a1769
TW
260}
261
60058b91
TW
262////////// INTERSECTION ////////////////////////////////////////////////////////
263
264#[derive(Debug)]
265pub enum Intersection {
266 Point(Point<f64>),
267 //Line(Point<f64>, Point<f64>), // TODO: overlapping collinear
268 None,
269}
270
271impl 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
0c56b1f7 281 if (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&t) {
60058b91
TW
282 return Intersection::Point(p1 + (s1 * t))
283 }
284 }
285
286 Intersection::None
287 }
288}
289
290////////// DIMENSION ///////////////////////////////////////////////////////////
291
0b5024d1 292#[macro_export]
1f42d724
TW
293macro_rules! dimen {
294 ( $w:expr, $h:expr ) => {
295 Dimension { width: $w, height: $h }
0b5024d1
TW
296 };
297}
298
8012f86b 299#[derive(Debug, Default, Copy, Clone, PartialEq)]
1f42d724 300pub struct Dimension<T> {
6edafdc0
TW
301 pub width: T,
302 pub height: T,
303}
304
1f42d724 305impl<T: Mul<Output = T> + Copy> Dimension<T> {
6edafdc0
TW
306 #[allow(dead_code)]
307 pub fn area(&self) -> T {
6ba7aef1 308 self.width * self.height
6edafdc0
TW
309 }
310}
311
1f42d724 312impl<T> From<(T, T)> for Dimension<T> {
6edafdc0 313 fn from(item: (T, T)) -> Self {
1f42d724 314 Dimension {
6ba7aef1
TW
315 width: item.0,
316 height: item.1,
317 }
6edafdc0
TW
318 }
319}
320
8012f86b
TW
321impl<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)]
330pub 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!(
334 if d.x > 0 { 1 } else { -1 },
335 if d.y > 0 { 1 } else { -1 }
336 );
337
0c56b1f7 338 let mut p = p1;
8012f86b
TW
339 let mut points = vec!(point!(p.x as isize, p.y as isize));
340 let mut i = point!(0, 0);
341 while i.x < n.x || i.y < n.y {
342 let decision = (1 + 2 * i.x) * n.y - (1 + 2 * i.y) * n.x;
343 if decision == 0 { // next step is diagonal
344 p.x += step.x;
345 p.y += step.y;
346 i.x += 1;
347 i.y += 1;
348 } else if decision < 0 { // next step is horizontal
349 p.x += step.x;
350 i.x += 1;
351 } else { // next step is vertical
352 p.y += step.y;
353 i.y += 1;
354 }
355 points.push(point!(p.x as isize, p.y as isize));
356 }
357
358 points
359}
360
361/// Calculates all points a line crosses, unlike Bresenham's line algorithm.
362/// There might be room for a lot of improvement here.
363pub fn supercover_line(mut p1: Point<f64>, mut p2: Point<f64>) -> Vec<Point<isize>> {
364 let mut delta = p2 - p1;
365 if (delta.x.abs() > delta.y.abs() && delta.x.is_sign_negative()) || (delta.x.abs() <= delta.y.abs() && delta.y.is_sign_negative()) {
366 std::mem::swap(&mut p1, &mut p2);
367 delta = -delta;
368 }
369
370 let mut last = point!(p1.x as isize, p1.y as isize);
371 let mut coords: Vec<Point<isize>> = vec!();
372 coords.push(last);
373
374 if delta.x.abs() > delta.y.abs() {
375 let k = delta.y / delta.x;
376 let m = p1.y as f64 - p1.x as f64 * k;
377 for x in (p1.x as isize + 1)..=(p2.x as isize) {
378 let y = (k * x as f64 + m).floor();
379 let next = point!(x as isize - 1, y as isize);
380 if next != last {
381 coords.push(next);
382 }
383 let next = point!(x as isize, y as isize);
384 coords.push(next);
385 last = next;
386 }
387 } else {
388 let k = delta.x / delta.y;
389 let m = p1.x as f64 - p1.y as f64 * k;
390 for y in (p1.y as isize + 1)..=(p2.y as isize) {
391 let x = (k * y as f64 + m).floor();
392 let next = point!(x as isize, y as isize - 1);
393 if next != last {
394 coords.push(next);
395 }
396 let next = point!(x as isize, y as isize);
397 coords.push(next);
398 last = next;
399 }
400 }
401
402 let next = point!(p2.x as isize, p2.y as isize);
403 if next != last {
404 coords.push(next);
405 }
406
407 coords
408}
409
60058b91 410////////// TESTS ///////////////////////////////////////////////////////////////
249d43ea 411
296187ca
TW
412#[cfg(test)]
413mod tests {
414 use super::*;
415
416 #[test]
417 fn immutable_copy_of_point() {
418 let a = point!(0, 0);
419 let mut b = a; // Copy
420 assert_eq!(a, b); // PartialEq
421 b.x = 1;
422 assert_ne!(a, b); // PartialEq
423 }
424
425 #[test]
426 fn add_points() {
427 let mut a = point!(1, 0);
428 assert_eq!(a + point!(2, 2), point!(3, 2)); // Add
429 a += point!(2, 2); // AddAssign
430 assert_eq!(a, point!(3, 2));
2836f506
TW
431 assert_eq!(point!(1, 0) + (2, 3), point!(3, 3));
432 }
433
434 #[test]
435 fn sub_points() {
436 let mut a = point!(1, 0);
437 assert_eq!(a - point!(2, 2), point!(-1, -2));
438 a -= point!(2, 2);
439 assert_eq!(a, point!(-1, -2));
6cd86b94 440 assert_eq!(point!(1, 0) - (2, 3), point!(-1, -3));
2836f506
TW
441 }
442
443 #[test]
444 fn mul_points() {
445 let mut a = point!(1, 2);
446 assert_eq!(a * 2, point!(2, 4));
447 assert_eq!(a * point!(2, 3), point!(2, 6));
448 a *= 2;
449 assert_eq!(a, point!(2, 4));
450 a *= point!(3, 1);
451 assert_eq!(a, point!(6, 4));
6cd86b94 452 assert_eq!(point!(1, 0) * (2, 3), point!(2, 0));
2836f506
TW
453 }
454
455 #[test]
456 fn div_points() {
457 let mut a = point!(4, 8);
458 assert_eq!(a / 2, point!(2, 4));
459 assert_eq!(a / point!(2, 4), point!(2, 2));
460 a /= 2;
461 assert_eq!(a, point!(2, 4));
462 a /= point!(2, 4);
463 assert_eq!(a, point!(1, 1));
6cd86b94 464 assert_eq!(point!(6, 3) / (2, 3), point!(3, 1));
2836f506
TW
465 }
466
467 #[test]
468 fn neg_point() {
469 assert_eq!(point!(1, 1), -point!(-1, -1));
296187ca 470 }
6edafdc0
TW
471
472 #[test]
e58a1769 473 fn angles() {
40742678 474 assert_eq!(0.radians(), 0.degrees());
a9eacb2b 475 assert_eq!(0.degrees(), 360.degrees());
40742678
TW
476 assert_eq!(180.degrees(), std::f64::consts::PI.radians());
477 assert_eq!(std::f64::consts::PI.radians().to_degrees(), 180.0);
478 assert!((Point::from(90.degrees()) - point!(0.0, 1.0)).length() < 0.001);
479 assert!((Point::from(std::f64::consts::FRAC_PI_2.radians()) - point!(0.0, 1.0)).length() < 0.001);
e58a1769
TW
480 }
481
482 #[test]
1f42d724
TW
483 fn area_for_dimension_of_multipliable_type() {
484 let r: Dimension<_> = (30, 20).into(); // the Into trait uses the From trait
6ba7aef1 485 assert_eq!(r.area(), 30 * 20);
1f42d724 486 // let a = Dimension::from(("a".to_string(), "b".to_string())).area(); // this doesn't work, because area() is not implemented for String
6edafdc0 487 }
60058b91
TW
488
489 #[test]
490 fn intersection_of_lines() {
491 let p1 = point!(0.0, 0.0);
492 let p2 = point!(2.0, 2.0);
493 let p3 = point!(0.0, 2.0);
494 let p4 = point!(2.0, 0.0);
495 let r = Intersection::lines(p1, p2, p3, p4);
496 if let Intersection::Point(p) = r {
497 assert_eq!(p, point!(1.0, 1.0));
498 } else {
499 panic!();
500 }
501 }
8012f86b
TW
502
503 #[test]
504 fn some_coordinates_on_line() {
505 // horizontally up
506 let coords = supercover_line(point!(0.0, 0.0), point!(3.3, 2.2));
507 assert_eq!(coords.as_slice(), &[point!(0, 0), point!(1, 0), point!(1, 1), point!(2, 1), point!(2, 2), point!(3, 2)]);
508
509 // horizontally down
510 let coords = supercover_line(point!(0.0, 5.0), point!(3.3, 2.2));
511 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)]);
512
513 // vertically right
514 let coords = supercover_line(point!(0.0, 0.0), point!(2.2, 3.3));
515 assert_eq!(coords.as_slice(), &[point!(0, 0), point!(0, 1), point!(1, 1), point!(1, 2), point!(2, 2), point!(2, 3)]);
516
517 // vertically left
518 let coords = supercover_line(point!(5.0, 0.0), point!(3.0, 3.0));
519 assert_eq!(coords.as_slice(), &[point!(5, 0), point!(4, 0), point!(4, 1), point!(3, 1), point!(3, 2), point!(3, 3)]);
520
521 // negative
522 let coords = supercover_line(point!(0.0, 0.0), point!(-3.0, -2.0));
523 assert_eq!(coords.as_slice(), &[point!(-3, -2), point!(-2, -2), point!(-2, -1), point!(-1, -1), point!(-1, 0), point!(0, 0)]);
524
525 //
526 let coords = supercover_line(point!(0.0, 0.0), point!(2.3, 1.1));
527 assert_eq!(coords.as_slice(), &[point!(0, 0), point!(1, 0), point!(2, 0), point!(2, 1)]);
528 }
296187ca 529}