solstice_2d/d3/shapes/
plane_geometry.rs

1use crate::d3::Vertex3D;
2
3#[derive(Debug, Copy, Clone, PartialEq)]
4pub struct Plane {
5    pub width: f32,
6    pub height: f32,
7    pub width_segments: u32,
8    pub height_segments: u32,
9}
10
11impl Plane {
12    pub fn new(width: f32, height: f32, width_segments: u32, height_segments: u32) -> Self {
13        Self {
14            width,
15            height,
16            width_segments,
17            height_segments,
18        }
19    }
20
21    fn vertices(&self) -> Vec<Vertex3D> {
22        let Self {
23            width,
24            height,
25            width_segments,
26            height_segments,
27        } = *self;
28
29        let segment_width = width / width_segments as f32;
30        let segment_height = height / height_segments as f32;
31
32        let width_half = width / 2.;
33        let height_half = height / 2.;
34
35        let grid_x1 = self.width_segments + 1;
36        let grid_y1 = self.height_segments + 1;
37
38        (0..grid_y1)
39            .flat_map(move |iy| {
40                let iy = iy as f32;
41                let y = iy * segment_height - height_half;
42                (0..grid_x1).map(move |ix| {
43                    let ix = ix as f32;
44                    let x = ix * segment_width - width_half;
45
46                    let position = [x, y, 0.];
47                    let normal = [0., 0., 1.];
48
49                    Vertex3D {
50                        position,
51                        normal,
52                        uv: [
53                            ix / self.width_segments as f32,
54                            iy / self.height_segments as f32,
55                        ],
56                        color: [1., 1., 1., 1.],
57                    }
58                })
59            })
60            .collect()
61    }
62
63    fn indices(&self) -> Vec<u32> {
64        let grid_x1 = self.width_segments + 1;
65        (0..self.height_segments)
66            .flat_map(|iy| {
67                (0..self.width_segments).flat_map(move |ix| {
68                    let a = ix + grid_x1 * iy;
69                    let b = ix + grid_x1 * (iy + 1);
70                    let c = (ix + 1) + grid_x1 * (iy + 1);
71                    let d = (ix + 1) + grid_x1 * iy;
72
73                    IntoIterator::into_iter([a, b, d, b, c, d])
74                })
75            })
76            .collect()
77    }
78}
79
80impl Default for Plane {
81    fn default() -> Self {
82        Self {
83            width: 1.,
84            height: 1.,
85            width_segments: 1,
86            height_segments: 1,
87        }
88    }
89}
90
91impl From<&Plane> for crate::Geometry<'_, Vertex3D> {
92    fn from(b: &Plane) -> Self {
93        Self::new(b.vertices(), Some(b.indices()))
94    }
95}
96
97impl From<Plane> for crate::Geometry<'_, Vertex3D> {
98    fn from(b: Plane) -> Self {
99        Self::new(b.vertices(), Some(b.indices()))
100    }
101}