shape_core/elements/ellipses/
circle.rs

1use super::*;
2
3impl<T> Default for Circle<T>
4    where
5        T: Zero + One,
6{
7    fn default() -> Self {
8        Self { center: Point::default(), radius: T::one() }
9    }
10}
11
12impl<T> Circle<T>
13    where
14        T: Real + Clone,
15{
16    /// Create circle with the center and radius.
17    pub fn new(center: Point<T>, radius: T) -> Self {
18        Self { center, radius }
19    }
20    /// Change circle center
21    pub fn with_center(center: Point<T>) -> Self {
22        Self { center, radius: T::zero() }
23    }
24    /// Change circle radius
25    pub fn with_radius(center: Point<T>, radius: T) -> Self {
26        Self { center, radius }
27    }
28    /// Create circle from center point and unknown radius
29    pub fn from_1_points(p1: &Point<T>) -> Self {
30        Self {
31            center: Point { x: p1.x.clone(), y: p1.y.clone() },
32            radius: T::zero(),
33        }
34    }
35    /// Create circle from two points on the diameter.
36    pub fn from_2_points(p1: &Point<T>, p2: &Point<T>) -> Self {
37        let two = T::one() + T::one();
38        let center = Point::new((p1.x + p2.x).div(two), (p1.y + p2.y).div(two));
39        Self { center, radius: p1.euclidean_distance(&p2).div(two) }
40    }
41
42    /// Create circle that intersects the 3 points.
43    pub fn from_3_points(p1: &Point<T>, p2: &Point<T>, p3: &Point<T>) -> Self {
44        let two = T::one() + T::one();
45
46        let p12 = Point::new(p2.x - p1.x.clone(), p2.y - p1.y.clone());
47        let p13 = Point::new(p3.x - p1.x.clone(), p3.y - p1.y.clone());
48
49        let c12 = p12.x * p12.x + p12.y * p12.y;
50        let c13 = p13.x * p13.x + p13.y * p13.y;
51        let c123 = p12.x * p13.y - p12.y * p13.x;
52
53        let cx = (p13.y * c12 - p12.y * c13) / c123.mul(two);
54        let cy = (p12.x * c13 - p13.x * c12) / c123.mul(two);
55
56        let center = Point::new(cx + p1.x, cy + p1.y);
57        Self { center, radius: center.euclidean_distance(&p1) }
58    }
59}
60
61impl<T> Circle<T>
62    where
63        T: Real,
64{
65    /// Checks if the circle contains the given points.
66    pub fn contains(&self, point: &Point<T>) -> bool {
67        self.center.euclidean_squared(point) <= self.radius * self.radius
68    }
69}
70
71impl<T> Circle<T>
72    where
73        T: Real + FloatConst,
74{
75    /// Returns the area of the circle.
76    pub fn area(&self) -> T {
77        self.radius.clone() * self.radius.clone() * pi()
78    }
79    /// Returns the circumference of the circle.
80    pub fn perimeter(&self) -> T {
81        self.radius.clone() * two_pi()
82    }
83    /// Checks if the circle intersects the given circle.
84    pub fn intersects(&self, other: &Self) -> bool {
85        self.center.euclidean_distance(&other.center) <= self.radius + other.radius
86    }
87}