1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
use {
    crate::{
        layout::Plain,
        topology::{Topology, TriangleList},
        vertex::Vertex,
    },
    std::{borrow::Cow, slice},
    wgpu::{Buffer, Device, Queue},
};

/// A data struct for a mesh creation.
#[derive(Clone)]
pub struct Data<'a, V, T = TriangleList>
where
    T: Topology,
{
    verts: &'a [V],
    indxs: Option<Cow<'a, [T::Face]>>,
}

impl<'a, V, T> Data<'a, V, T>
where
    T: Topology,
{
    /// Creates a new [`MeshData`](crate::MeshData) from given vertices.
    pub fn from_verts(verts: &'a [V]) -> Self {
        Self { verts, indxs: None }
    }
}

impl<'a, V> Data<'a, V> {
    /// Creates a new [`MeshData`](crate::MeshData) from given vertices and indices.
    ///
    /// Returns `Some` if a data length fits in `u16` and all indices point to the data,
    /// otherwise returns `None`.
    pub fn new(verts: &'a [V], indxs: &'a [[u16; 3]]) -> Option<Self> {
        let len: u16 = verts.len().try_into().ok()?;
        indxs.iter().flatten().all(|&i| i < len).then_some(Self {
            verts,
            indxs: Some(indxs.into()),
        })
    }

    /// Creates a new [`MeshData`](crate::MeshData) from given quadrangles.
    ///
    /// Returns `Some` if a data length fits in `u16` and is multiple by 4,
    /// otherwise returns `None`.
    pub fn from_quads(verts: &'a [V]) -> Option<Self> {
        let len: u16 = verts.len().try_into().ok()?;
        (len % 4 == 0).then_some({
            Self {
                verts,
                indxs: Some(
                    (0..len)
                        .step_by(4)
                        .flat_map(|i| [[i, i + 1, i + 2], [i + 2, i + 1, i + 3]])
                        .collect(),
                ),
            }
        })
    }
}

pub(crate) struct Mesh {
    vertex_buffer: Buffer,
    ty: Type,
}

impl Mesh {
    pub fn new<V, T>(data: &Data<V, T>, device: &Device) -> Self
    where
        V: Vertex,
        T: Topology,
    {
        use wgpu::{
            util::{BufferInitDescriptor, DeviceExt},
            BufferUsages,
        };

        Self {
            vertex_buffer: device.create_buffer_init(&BufferInitDescriptor {
                label: Some("vertex buffer"),
                contents: data.verts.as_bytes(),
                usage: BufferUsages::VERTEX,
            }),
            ty: match &data.indxs {
                Some(indxs) => Type::indexed(
                    unsafe { slice::from_raw_parts(indxs.as_ptr().cast(), indxs.len() * 3) },
                    device,
                ),
                None => Type::sequential(data.verts),
            },
        }
    }

    pub fn update_data<V, T>(&mut self, data: &Data<V, T>, device: &Device, queue: &Queue)
    where
        V: Vertex,
        T: Topology,
    {
        queue.write_buffer(&self.vertex_buffer, 0, data.verts.as_bytes());

        match &mut self.ty {
            Type::Indexed {
                index_buffer,
                n_indices,
            } => match &data.indxs {
                Some(indxs) => {
                    queue.write_buffer(index_buffer, 0, indxs.as_ref().as_bytes());
                    *n_indices = (indxs.len() * 3).try_into().expect("too many indexes");
                }
                None => self.ty = Type::sequential(data.verts),
            },
            Type::Sequential { .. } => match &data.indxs {
                Some(indxs) => {
                    self.ty = Type::indexed(
                        unsafe { slice::from_raw_parts(indxs.as_ptr().cast(), indxs.len() * 3) },
                        device,
                    );
                }
                None => self.ty = Type::sequential(data.verts),
            },
        }
    }

    pub fn vertex_buffer(&self) -> &Buffer {
        &self.vertex_buffer
    }

    pub fn mesh_type(&self) -> &Type {
        &self.ty
    }
}

pub(crate) enum Type {
    Indexed {
        index_buffer: Buffer,
        n_indices: u32,
    },
    Sequential {
        n_vertices: u32,
    },
}

impl Type {
    fn indexed(indxs: &[u16], device: &Device) -> Self {
        use wgpu::{
            util::{BufferInitDescriptor, DeviceExt},
            BufferUsages,
        };

        Self::Indexed {
            index_buffer: device.create_buffer_init(&BufferInitDescriptor {
                label: Some("index buffer"),
                contents: indxs.as_ref().as_bytes(),
                usage: BufferUsages::INDEX,
            }),
            n_indices: indxs.len().try_into().expect("too many indexes"),
        }
    }

    fn sequential<V>(verts: &[V]) -> Self {
        Self::Sequential {
            n_vertices: verts.len().try_into().expect("too many vertices"),
        }
    }
}