jagua_rs/geometry/primitives/
point.rs1use std::hash::{Hash, Hasher};
2
3use crate::geometry::Transformation;
4use crate::geometry::geo_traits::{CollidesWith, DistanceTo, Transformable, TransformableFrom};
5
6#[derive(Debug, Clone, PartialEq, Copy)]
8pub struct Point(pub f32, pub f32);
9
10impl Transformable for Point {
11 fn transform(&mut self, t: &Transformation) -> &mut Self {
12 let Point(x, y) = self;
13 (*x, *y) = TRANSFORM_FORMULA(*x, *y, t);
14 self
15 }
16}
17
18impl TransformableFrom for Point {
19 fn transform_from(&mut self, reference: &Self, t: &Transformation) -> &mut Self {
20 let Point(x, y) = self;
21 (*x, *y) = TRANSFORM_FORMULA(reference.0, reference.1, t);
22 self
23 }
24}
25
26const TRANSFORM_FORMULA: fn(f32, f32, &Transformation) -> (f32, f32) = |x, y, t| -> (f32, f32) {
27 let m = t.matrix();
28 let t_x = m[0][0].into_inner() * x + m[0][1].into_inner() * y + m[0][2].into_inner() * 1.0;
29 let t_y = m[1][0].into_inner() * x + m[1][1].into_inner() * y + m[1][2].into_inner() * 1.0;
30 (t_x, t_y)
31};
32
33impl Point {
34 #[must_use]
35 pub fn x(&self) -> f32 {
36 self.0
37 }
38
39 #[must_use]
40 pub fn y(&self) -> f32 {
41 self.1
42 }
43}
44
45impl DistanceTo<Point> for Point {
46 #[inline(always)]
47 fn distance_to(&self, other: &Point) -> f32 {
48 ((self.0 - other.0).powi(2) + (self.1 - other.1).powi(2)).sqrt()
49 }
50
51 #[inline(always)]
52 fn sq_distance_to(&self, other: &Point) -> f32 {
53 (self.0 - other.0).powi(2) + (self.1 - other.1).powi(2)
54 }
55}
56
57impl Eq for Point {}
58
59impl Hash for Point {
60 fn hash<H: Hasher>(&self, state: &mut H) {
61 let x = self.0.to_bits();
62 let y = self.1.to_bits();
63 x.hash(state);
64 y.hash(state);
65 }
66}
67
68impl From<Point> for (f32, f32) {
69 fn from(p: Point) -> Self {
70 (p.0, p.1)
71 }
72}
73
74impl From<(f32, f32)> for Point {
75 fn from((x, y): (f32, f32)) -> Self {
76 Point(x, y)
77 }
78}
79
80impl<T> CollidesWith<T> for Point
81where
82 T: CollidesWith<Point>,
83{
84 fn collides_with(&self, other: &T) -> bool {
85 other.collides_with(self)
86 }
87}