three_d/renderer/geometry/
circle.rs

1use crate::renderer::*;
2
3///
4/// A circle 2D geometry which can be rendered using a camera created by [Camera::new_2d].
5///
6pub struct Circle {
7    mesh: Mesh,
8    radius: f32,
9    center: PhysicalPoint,
10}
11
12impl Circle {
13    ///
14    /// Constructs a new circle geometry.
15    ///
16    pub fn new(context: &Context, center: impl Into<PhysicalPoint>, radius: f32) -> Self {
17        let mesh = CpuMesh::circle(64);
18        let mut circle = Self {
19            mesh: Mesh::new(context, &mesh),
20            center: center.into(),
21            radius,
22        };
23        circle.update();
24        circle
25    }
26
27    /// Set the radius of the circle.
28    pub fn set_radius(&mut self, radius: f32) {
29        self.radius = radius;
30        self.update();
31    }
32
33    /// Get the radius of the circle.
34    pub fn radius(&self) -> f32 {
35        self.radius
36    }
37
38    /// Set the center of the circle.
39    pub fn set_center(&mut self, center: impl Into<PhysicalPoint>) {
40        self.center = center.into();
41        self.update();
42    }
43
44    /// Get the center of the circle.
45    pub fn center(&self) -> PhysicalPoint {
46        self.center
47    }
48
49    fn update(&mut self) {
50        self.mesh.set_transformation_2d(
51            Mat3::from_translation(self.center.into()) * Mat3::from_scale(self.radius),
52        );
53    }
54}
55
56impl<'a> IntoIterator for &'a Circle {
57    type Item = &'a dyn Geometry;
58    type IntoIter = std::iter::Once<&'a dyn Geometry>;
59
60    fn into_iter(self) -> Self::IntoIter {
61        std::iter::once(self)
62    }
63}
64
65use std::ops::Deref;
66impl Deref for Circle {
67    type Target = Mesh;
68    fn deref(&self) -> &Self::Target {
69        &self.mesh
70    }
71}
72
73impl std::ops::DerefMut for Circle {
74    fn deref_mut(&mut self) -> &mut Self::Target {
75        &mut self.mesh
76    }
77}
78
79impl Geometry for Circle {
80    impl_geometry_body!(deref);
81
82    fn animate(&mut self, time: f32) {
83        self.mesh.animate(time)
84    }
85}