embedded_graphics/geometry/
mod.rs

1//! Geometry module.
2
3mod angle;
4mod real;
5
6pub(crate) use angle::angle_consts;
7pub(crate) use angle::Trigonometry;
8pub use angle::{Angle, AngleUnit};
9pub use embedded_graphics_core::geometry::{
10    AnchorPoint, AnchorX, AnchorY, Dimensions, OriginDimensions, Point, Size,
11};
12pub(crate) use real::Real;
13
14pub(crate) trait PointExt {
15    /// Returns a point that is rotated by 90° relative to the origin.
16    fn rotate_90(self) -> Self;
17
18    /// Calculates the dot product of two points.
19    fn dot_product(self, other: Point) -> i32;
20
21    /// Calculates the determinant of a 2x2 matrix formed by this and another point.
22    ///
23    /// ```text
24    ///          | self.x  self.y  |
25    /// result = |                 |
26    ///          | other.x other.y |
27    /// ```
28    fn determinant(self, other: Point) -> i32;
29
30    /// Returns the squared length.
31    ///
32    /// The returned value is the square of the length of a vector from `(0, 0)`
33    /// to `(self.x, self.y)`.
34    fn length_squared(self) -> i32;
35}
36
37impl PointExt for Point {
38    fn rotate_90(self) -> Self {
39        Self::new(-self.y, self.x)
40    }
41
42    fn dot_product(self, other: Point) -> i32 {
43        self.x * other.x + self.y * other.y
44    }
45
46    fn determinant(self, other: Point) -> i32 {
47        self.x * other.y - self.y * other.x
48    }
49
50    fn length_squared(self) -> i32 {
51        self.x.pow(2) + self.y.pow(2)
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn check_length_squared() {
61        let p = Point::new(3, 4);
62
63        assert_eq!(p.length_squared(), 25);
64    }
65
66    #[test]
67    fn rotate_90() {
68        assert_eq!(Point::new(1, 0).rotate_90(), Point::new(0, 1));
69        assert_eq!(Point::new(0, -2).rotate_90(), Point::new(2, 0));
70        assert_eq!(Point::new(-3, 0).rotate_90(), Point::new(0, -3));
71        assert_eq!(Point::new(0, 4).rotate_90(), Point::new(-4, 0));
72    }
73}