Replaced Degrees and Radians with a single Angle type
[kaka/rust-sdl-test.git] / src / common / geometry.rs
... / ...
CommitLineData
1use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Neg};
2
3////////// POINT ///////////////////////////////////////////////////////////////
4
5#[macro_export]
6macro_rules! point {
7 ( $x:expr, $y:expr ) => {
8 Point { x: $x, y: $y }
9 };
10}
11
12#[derive(Debug, Default, Copy, Clone, PartialEq)]
13pub struct Point<T> {
14 pub x: T,
15 pub y: T,
16}
17
18impl 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
43macro_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
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);
77
78////////// multiply point with scalar //////////////////////////////////////////
79impl<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
90impl<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 ////////////////////////////////////////////
100impl<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
111impl<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
120impl<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
131impl<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
140impl<T> From<Point<T>> for (T, T) {
141 fn from(item: Point<T>) -> Self {
142 (item.x, item.y)
143 }
144}
145
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 }
152 }
153}
154
155////////// ANGLE ///////////////////////////////////////////////////////////////
156
157#[derive(Debug, Default, PartialEq, Clone, Copy)]
158pub struct Angle(pub f64);
159
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 )*
206 }
207}
208
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()
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// TODO override eq, 0==360 osv
227
228// addition and subtraction of angles
229
230impl Add<Angle> for Angle {
231 type Output = Self;
232
233 fn add(self, rhs: Angle) -> Self {
234 Angle(self.0 + rhs.0)
235 }
236}
237
238impl AddAssign<Angle> for Angle {
239 fn add_assign(&mut self, rhs: Angle) {
240 self.0 += rhs.0;
241 }
242}
243
244impl Sub<Angle> for Angle {
245 type Output = Self;
246
247 fn sub(self, rhs: Angle) -> Self {
248 Angle(self.0 - rhs.0)
249 }
250}
251
252impl SubAssign<Angle> for Angle {
253 fn sub_assign(&mut self, rhs: Angle) {
254 self.0 -= rhs.0;
255 }
256}
257
258////////// INTERSECTION ////////////////////////////////////////////////////////
259
260#[derive(Debug)]
261pub enum Intersection {
262 Point(Point<f64>),
263 //Line(Point<f64>, Point<f64>), // TODO: overlapping collinear
264 None,
265}
266
267impl Intersection {
268 pub fn lines(p1: Point<f64>, p2: Point<f64>, p3: Point<f64>, p4: Point<f64>) -> Intersection {
269 let s1 = p2 - p1;
270 let s2 = p4 - p3;
271
272 let denomimator = -s2.x * s1.y + s1.x * s2.y;
273 if denomimator != 0.0 {
274 let s = (-s1.y * (p1.x - p3.x) + s1.x * (p1.y - p3.y)) / denomimator;
275 let t = ( s2.x * (p1.y - p3.y) - s2.y * (p1.x - p3.x)) / denomimator;
276
277 if s >= 0.0 && s <= 1.0 && t >= 0.0 && t <= 1.0 {
278 return Intersection::Point(p1 + (s1 * t))
279 }
280 }
281
282 Intersection::None
283 }
284}
285
286////////// DIMENSION ///////////////////////////////////////////////////////////
287
288#[macro_export]
289macro_rules! dimen {
290 ( $w:expr, $h:expr ) => {
291 Dimension { width: $w, height: $h }
292 };
293}
294
295#[derive(Debug, Default, Copy, Clone, PartialEq)]
296pub struct Dimension<T> {
297 pub width: T,
298 pub height: T,
299}
300
301impl<T: Mul<Output = T> + Copy> Dimension<T> {
302 #[allow(dead_code)]
303 pub fn area(&self) -> T {
304 self.width * self.height
305 }
306}
307
308impl<T> From<(T, T)> for Dimension<T> {
309 fn from(item: (T, T)) -> Self {
310 Dimension {
311 width: item.0,
312 height: item.1,
313 }
314 }
315}
316
317impl<T> From<Dimension<T>> for (T, T) {
318 fn from(item: Dimension<T>) -> Self {
319 (item.width, item.height)
320 }
321}
322
323////////////////////////////////////////////////////////////////////////////////
324
325#[allow(dead_code)]
326pub fn supercover_line_int(p1: Point<isize>, p2: Point<isize>) -> Vec<Point<isize>> {
327 let d = p2 - p1;
328 let n = point!(d.x.abs(), d.y.abs());
329 let step = point!(
330 if d.x > 0 { 1 } else { -1 },
331 if d.y > 0 { 1 } else { -1 }
332 );
333
334 let mut p = p1.clone();
335 let mut points = vec!(point!(p.x as isize, p.y as isize));
336 let mut i = point!(0, 0);
337 while i.x < n.x || i.y < n.y {
338 let decision = (1 + 2 * i.x) * n.y - (1 + 2 * i.y) * n.x;
339 if decision == 0 { // next step is diagonal
340 p.x += step.x;
341 p.y += step.y;
342 i.x += 1;
343 i.y += 1;
344 } else if decision < 0 { // next step is horizontal
345 p.x += step.x;
346 i.x += 1;
347 } else { // next step is vertical
348 p.y += step.y;
349 i.y += 1;
350 }
351 points.push(point!(p.x as isize, p.y as isize));
352 }
353
354 points
355}
356
357/// Calculates all points a line crosses, unlike Bresenham's line algorithm.
358/// There might be room for a lot of improvement here.
359pub fn supercover_line(mut p1: Point<f64>, mut p2: Point<f64>) -> Vec<Point<isize>> {
360 let mut delta = p2 - p1;
361 if (delta.x.abs() > delta.y.abs() && delta.x.is_sign_negative()) || (delta.x.abs() <= delta.y.abs() && delta.y.is_sign_negative()) {
362 std::mem::swap(&mut p1, &mut p2);
363 delta = -delta;
364 }
365
366 let mut last = point!(p1.x as isize, p1.y as isize);
367 let mut coords: Vec<Point<isize>> = vec!();
368 coords.push(last);
369
370 if delta.x.abs() > delta.y.abs() {
371 let k = delta.y / delta.x;
372 let m = p1.y as f64 - p1.x as f64 * k;
373 for x in (p1.x as isize + 1)..=(p2.x as isize) {
374 let y = (k * x as f64 + m).floor();
375 let next = point!(x as isize - 1, y as isize);
376 if next != last {
377 coords.push(next);
378 }
379 let next = point!(x as isize, y as isize);
380 coords.push(next);
381 last = next;
382 }
383 } else {
384 let k = delta.x / delta.y;
385 let m = p1.x as f64 - p1.y as f64 * k;
386 for y in (p1.y as isize + 1)..=(p2.y as isize) {
387 let x = (k * y as f64 + m).floor();
388 let next = point!(x as isize, y as isize - 1);
389 if next != last {
390 coords.push(next);
391 }
392 let next = point!(x as isize, y as isize);
393 coords.push(next);
394 last = next;
395 }
396 }
397
398 let next = point!(p2.x as isize, p2.y as isize);
399 if next != last {
400 coords.push(next);
401 }
402
403 coords
404}
405
406////////// TESTS ///////////////////////////////////////////////////////////////
407
408#[cfg(test)]
409mod tests {
410 use super::*;
411
412 #[test]
413 fn immutable_copy_of_point() {
414 let a = point!(0, 0);
415 let mut b = a; // Copy
416 assert_eq!(a, b); // PartialEq
417 b.x = 1;
418 assert_ne!(a, b); // PartialEq
419 }
420
421 #[test]
422 fn add_points() {
423 let mut a = point!(1, 0);
424 assert_eq!(a + point!(2, 2), point!(3, 2)); // Add
425 a += point!(2, 2); // AddAssign
426 assert_eq!(a, point!(3, 2));
427 assert_eq!(point!(1, 0) + (2, 3), point!(3, 3));
428 }
429
430 #[test]
431 fn sub_points() {
432 let mut a = point!(1, 0);
433 assert_eq!(a - point!(2, 2), point!(-1, -2));
434 a -= point!(2, 2);
435 assert_eq!(a, point!(-1, -2));
436 assert_eq!(point!(1, 0) - (2, 3), point!(-1, -3));
437 }
438
439 #[test]
440 fn mul_points() {
441 let mut a = point!(1, 2);
442 assert_eq!(a * 2, point!(2, 4));
443 assert_eq!(a * point!(2, 3), point!(2, 6));
444 a *= 2;
445 assert_eq!(a, point!(2, 4));
446 a *= point!(3, 1);
447 assert_eq!(a, point!(6, 4));
448 assert_eq!(point!(1, 0) * (2, 3), point!(2, 0));
449 }
450
451 #[test]
452 fn div_points() {
453 let mut a = point!(4, 8);
454 assert_eq!(a / 2, point!(2, 4));
455 assert_eq!(a / point!(2, 4), point!(2, 2));
456 a /= 2;
457 assert_eq!(a, point!(2, 4));
458 a /= point!(2, 4);
459 assert_eq!(a, point!(1, 1));
460 assert_eq!(point!(6, 3) / (2, 3), point!(3, 1));
461 }
462
463 #[test]
464 fn neg_point() {
465 assert_eq!(point!(1, 1), -point!(-1, -1));
466 }
467
468 #[test]
469 fn angles() {
470 assert_eq!(0.radians(), 0.degrees());
471 assert_eq!(180.degrees(), std::f64::consts::PI.radians());
472 assert_eq!(std::f64::consts::PI.radians().to_degrees(), 180.0);
473 assert!((Point::from(90.degrees()) - point!(0.0, 1.0)).length() < 0.001);
474 assert!((Point::from(std::f64::consts::FRAC_PI_2.radians()) - point!(0.0, 1.0)).length() < 0.001);
475 }
476
477 #[test]
478 fn area_for_dimension_of_multipliable_type() {
479 let r: Dimension<_> = (30, 20).into(); // the Into trait uses the From trait
480 assert_eq!(r.area(), 30 * 20);
481 // let a = Dimension::from(("a".to_string(), "b".to_string())).area(); // this doesn't work, because area() is not implemented for String
482 }
483
484 #[test]
485 fn intersection_of_lines() {
486 let p1 = point!(0.0, 0.0);
487 let p2 = point!(2.0, 2.0);
488 let p3 = point!(0.0, 2.0);
489 let p4 = point!(2.0, 0.0);
490 let r = Intersection::lines(p1, p2, p3, p4);
491 if let Intersection::Point(p) = r {
492 assert_eq!(p, point!(1.0, 1.0));
493 } else {
494 panic!();
495 }
496 }
497
498 #[test]
499 fn some_coordinates_on_line() {
500 // horizontally up
501 let coords = supercover_line(point!(0.0, 0.0), point!(3.3, 2.2));
502 assert_eq!(coords.as_slice(), &[point!(0, 0), point!(1, 0), point!(1, 1), point!(2, 1), point!(2, 2), point!(3, 2)]);
503
504 // horizontally down
505 let coords = supercover_line(point!(0.0, 5.0), point!(3.3, 2.2));
506 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)]);
507
508 // vertically right
509 let coords = supercover_line(point!(0.0, 0.0), point!(2.2, 3.3));
510 assert_eq!(coords.as_slice(), &[point!(0, 0), point!(0, 1), point!(1, 1), point!(1, 2), point!(2, 2), point!(2, 3)]);
511
512 // vertically left
513 let coords = supercover_line(point!(5.0, 0.0), point!(3.0, 3.0));
514 assert_eq!(coords.as_slice(), &[point!(5, 0), point!(4, 0), point!(4, 1), point!(3, 1), point!(3, 2), point!(3, 3)]);
515
516 // negative
517 let coords = supercover_line(point!(0.0, 0.0), point!(-3.0, -2.0));
518 assert_eq!(coords.as_slice(), &[point!(-3, -2), point!(-2, -2), point!(-2, -1), point!(-1, -1), point!(-1, 0), point!(0, 0)]);
519
520 //
521 let coords = supercover_line(point!(0.0, 0.0), point!(2.3, 1.1));
522 assert_eq!(coords.as_slice(), &[point!(0, 0), point!(1, 0), point!(2, 0), point!(2, 1)]);
523 }
524}