makepad_vector/geometry/
point.rs

1use crate::geometry::{F64Ext, Transform, Transformation, Vector};
2use std::ops::{Add, AddAssign, Sub, SubAssign};
3
4/// A point in 2-dimensional Euclidian space.
5///
6/// A point represents a position, whereas a vector represents a displacement. That is, the result
7/// of subtracting two points is a vector. Moreover, the result of adding/subtracting a vector
8/// to/from a point is another point. However, adding two points is not defined. Similarly, whereas
9/// a point can be scaled, rotated, and translated, a vector can only be scaled and rotated.
10#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)]
11pub struct Point {
12    pub x: f64,
13    pub y: f64,
14}
15
16impl Point {
17    /// Creates a new point with the given coordinates.
18    pub fn new(x: f64, y: f64) -> Point {
19        Point { x, y }
20    }
21
22    /// Returns the point at the origin.
23    pub fn origin() -> Point {
24        Point::new(0.0, 0.0)
25    }
26
27    /// Converts `self` to a vector.
28    ///
29    /// This is equivalent to subtracting `self` from the origin.
30    pub fn to_vector(self) -> Vector {
31        Vector::new(self.x, self.y)
32    }
33
34    /// Linearly interpolate between `self` and `other` with parameter `t`.
35    pub fn lerp(self, other: Point, t: f64) -> Point {
36        Point::new(self.x.ext_lerp(other.x, t), self.y.ext_lerp(other.y, t))
37    }
38}
39
40impl AddAssign<Vector> for Point {
41    fn add_assign(&mut self, vector: Vector) {
42        *self = *self + vector;
43    }
44}
45
46impl SubAssign<Vector> for Point {
47    fn sub_assign(&mut self, vector: Vector) {
48        *self = *self - vector;
49    }
50}
51
52impl Add<Vector> for Point {
53    type Output = Point;
54
55    fn add(self, v: Vector) -> Point {
56        Point::new(self.x + v.x, self.y + v.y)
57    }
58}
59
60impl Sub for Point {
61    type Output = Vector;
62
63    fn sub(self, other: Point) -> Vector {
64        Vector::new(self.x - other.x, self.y - other.y)
65    }
66}
67
68impl Sub<Vector> for Point {
69    type Output = Point;
70
71    fn sub(self, v: Vector) -> Point {
72        Point::new(self.x - v.x, self.y - v.y)
73    }
74}
75
76impl Transform for Point {
77    fn transform<T>(self, t: &T) -> Point
78    where
79        T: Transformation,
80    {
81        t.transform_point(self)
82    }
83
84    fn transform_mut<T>(&mut self, t: &T)
85    where
86        T: Transformation,
87    {
88        *self = self.transform(t);
89    }
90}