Skip to main content

rscad_core/objects/two_dimensional/
square.rs

1use crate::prelude_::*;
2
3#[derive(Clone, Copy, Debug, Default)]
4#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
5#[cfg_attr(feature = "reflect", derive(bevy_reflect::Reflect))]
6pub struct Square {
7    pub x: f64,
8    pub y: f64,
9}
10
11impl Square {
12    pub fn new<T1: Number, T2: Number>(x: T1, y: T2) -> Self {
13        Square {
14            x: x.to_f64(),
15            y: y.to_f64(),
16        }
17    }
18
19    pub fn with_x<T: Number>(self, x: T) -> Self {
20        Square {
21            x: x.to_f64(),
22            ..self
23        }
24    }
25    pub fn with_y<T: Number>(self, y: T) -> Self {
26        Square {
27            y: y.to_f64(),
28            ..self
29        }
30    }
31
32    pub fn points(&self) -> [DVec2; 4] {
33        [
34            DVec2::new(0.0, 0.0),
35            DVec2::new(self.x, 0.0),
36            DVec2::new(self.x, self.y),
37            DVec2::new(0.0, self.y),
38        ]
39    }
40}
41
42pub trait SquareExt {
43    fn length(&self) -> f64;
44    fn width(&self) -> f64;
45    fn area(&self) -> f64;
46    fn perimeter(&self) -> f64;
47    fn diagonal(&self) -> f64;
48}
49
50impl SquareExt for Square {
51    fn length(&self) -> f64 {
52        self.x
53    }
54    fn width(&self) -> f64 {
55        self.y
56    }
57    fn area(&self) -> f64 {
58        self.x * self.y
59    }
60    fn perimeter(&self) -> f64 {
61        2.0 * (self.x + self.y)
62    }
63    fn diagonal(&self) -> f64 {
64        (self.x.powi(2) + self.y.powi(2)).sqrt()
65    }
66}
67
68impl Object for Square {}