Skip to main content

mln_engine/draw/
vertices.rs

1//! The vertices that draws bind from the context's store: a bucket's, which
2//! a tile's draws share, and those a layer makes for its draws. Draws hold
3//! them as [`SharedVertices`]; only the holder of a [`TypedVertices`], who
4//! made them as dynamic vertices of a type, can replace them with new
5//! vertices of it. Only the store makes either, of the entries it adds, so a
6//! handle's count and vertex type are its entry's.
7
8use std::marker::PhantomData;
9use std::rc::Rc;
10
11use mln_gfx::gpu::{BufferId, BufferUsage, Gpu, GpuError};
12#[cfg(target_family = "wasm")]
13use mln_wire::host_bytes::HostBytes;
14
15use crate::draw::buffer::Buffer;
16use crate::draw::owned::Held;
17use crate::draw::release::ReleaseQueue;
18use crate::draw::resources::Device;
19use crate::draw::store::{Shared, Store, VerticesKey};
20
21/// Where the vertices' bytes are: in the vector of the alignment of their
22/// type, which a vector of vertices moves into without a copy, or of
23/// dynamic vertices in bytes.
24enum VertexData {
25    Bytes(Vec<u8>),
26    Halves(Vec<u16>),
27    Words(Vec<u32>),
28    Doubles(Vec<u64>),
29    /// Dynamic vertices' bytes, which the next upload writes.
30    Dynamic(Vec<u8>),
31    /// Dynamic vertices' bytes that the last upload wrote, whose storage the
32    /// next update fills.
33    Written(Vec<u8>),
34    /// The bytes in the JS array they arrived in, which the upload writes
35    /// from there.
36    #[cfg(target_family = "wasm")]
37    Host(HostBytes),
38    /// Freed once in a buffer.
39    Freed,
40}
41
42/// Vertices of the context's store: their bytes until an upload writes them
43/// to a buffer, which frees them, and that buffer. Dynamic vertices take
44/// updates, each new bytes of as many vertices, which the next upload
45/// writes over the buffer's; their uploads keep their bytes' storage for
46/// the next update to fill.
47pub struct Vertices {
48    /// The bytes the next upload writes; once it wrote them, `Freed`, or
49    /// `Written` for dynamic vertices.
50    data: VertexData,
51    count: usize,
52    vertex_size: usize,
53    buffer: Option<Buffer>,
54}
55
56impl VertexData {
57    /// The data of `vertices`, moved.
58    fn of<V: bytemuck::Pod>(vertices: Vec<V>) -> VertexData {
59        use bytemuck::allocation::try_cast_vec;
60        let moved = match align_of::<V>() {
61            1 => try_cast_vec(vertices).map(VertexData::Bytes),
62            2 => try_cast_vec(vertices).map(VertexData::Halves),
63            4 => try_cast_vec(vertices).map(VertexData::Words),
64            8 => try_cast_vec(vertices).map(VertexData::Doubles),
65            _ => Err((bytemuck::PodCastError::AlignmentMismatch, vertices)),
66        };
67        moved.unwrap_or_else(|(_, vertices)| VertexData::Bytes(bytemuck::cast_slice(&vertices).to_vec()))
68    }
69
70    /// The bytes, while they are in wasm memory, to change.
71    fn bytes_mut(&mut self) -> Option<&mut [u8]> {
72        match self {
73            VertexData::Bytes(bytes) => Some(bytes),
74            VertexData::Halves(data) => Some(bytemuck::cast_slice_mut(data)),
75            VertexData::Words(data) => Some(bytemuck::cast_slice_mut(data)),
76            VertexData::Doubles(data) => Some(bytemuck::cast_slice_mut(data)),
77            VertexData::Dynamic(bytes) => Some(bytes),
78            #[cfg(target_family = "wasm")]
79            VertexData::Host(_) => None,
80            VertexData::Written(_) | VertexData::Freed => None,
81        }
82    }
83
84    /// The bytes, while they are in wasm memory.
85    fn bytes(&self) -> Option<&[u8]> {
86        match self {
87            VertexData::Bytes(bytes) => Some(bytes),
88            VertexData::Halves(data) => Some(bytemuck::cast_slice(data)),
89            VertexData::Words(data) => Some(bytemuck::cast_slice(data)),
90            VertexData::Doubles(data) => Some(bytemuck::cast_slice(data)),
91            VertexData::Dynamic(bytes) => Some(bytes),
92            #[cfg(target_family = "wasm")]
93            VertexData::Host(_) => None,
94            VertexData::Written(_) | VertexData::Freed => None,
95        }
96    }
97}
98
99impl Vertices {
100    /// `vertices`, moved.
101    fn new<V: bytemuck::Pod>(vertices: Vec<V>) -> Vertices {
102        let count = vertices.len();
103        let data = VertexData::of(vertices);
104        Vertices { data, count, vertex_size: size_of::<V>(), buffer: None }
105    }
106
107    /// Dynamic vertices of a copy of `vertices`.
108    fn dynamic<V: bytemuck::Pod>(vertices: &[V]) -> Vertices {
109        let data = VertexData::Dynamic(bytemuck::cast_slice(vertices).to_vec());
110        Vertices { data, count: vertices.len(), vertex_size: size_of::<V>(), buffer: None }
111    }
112
113    /// The vertices of `vertex_size` bytes each in a JS array.
114    #[cfg(target_family = "wasm")]
115    fn from_host(bytes: HostBytes, vertex_size: usize) -> Vertices {
116        debug_assert!(bytes.len().is_multiple_of(vertex_size.max(1)));
117        let count = bytes.len() / vertex_size.max(1);
118        Vertices { data: VertexData::Host(bytes), count, vertex_size, buffer: None }
119    }
120
121    /// The number of vertices, which stays once the upload freed them.
122    #[must_use]
123    pub(crate) fn count(&self) -> usize {
124        self.count
125    }
126
127    /// The bytes a vertex takes.
128    #[must_use]
129    pub fn vertex_size(&self) -> usize {
130        self.vertex_size
131    }
132
133    /// The bytes the vertices take.
134    fn size(&self) -> usize {
135        self.count() * self.vertex_size()
136    }
137
138    /// Whether the next upload writes the vertices: they are new, or
139    /// updated since the last upload, which wrote their bytes. A draw bound
140    /// before then binds them again, and its other attributes with them.
141    #[must_use]
142    pub fn needs_upload(&self) -> bool {
143        !matches!(self.data, VertexData::Written(_) | VertexData::Freed)
144    }
145
146    /// The bytes of the vertices while they are in wasm memory.
147    #[must_use]
148    pub fn bytes(&self) -> &[u8] {
149        self.data.bytes().unwrap_or_default()
150    }
151
152    /// Replaces the bytes of dynamic vertices with `bytes`, of as many
153    /// vertices, which the next upload writes. Returns false, leaving the
154    /// vertices be, for another number of bytes.
155    fn update(&mut self, bytes: &[u8]) -> bool {
156        if bytes.len() != self.size() {
157            return false;
158        }
159        if let VertexData::Written(storage) = &mut self.data {
160            self.data = VertexData::Dynamic(std::mem::take(storage));
161        }
162        match self.data.bytes_mut() {
163            Some(data) => data.copy_from_slice(bytes),
164            None => self.data = VertexData::Bytes(bytes.to_vec()),
165        }
166        true
167    }
168
169    /// Frees the bytes, which the upload wrote, or keeps those of dynamic
170    /// vertices for the next update.
171    fn written(&mut self) {
172        self.data = match std::mem::replace(&mut self.data, VertexData::Freed) {
173            VertexData::Dynamic(bytes) | VertexData::Written(bytes) => VertexData::Written(bytes),
174            _ => VertexData::Freed,
175        };
176    }
177
178    /// The buffer of the vertices of `gpu` through `device`: made of them
179    /// by the first upload, and written over by the upload after an update,
180    /// each of which frees their bytes, or keeps dynamic vertices' for the
181    /// next update; `None` where there are none.
182    fn upload(&mut self, gpu: &mut dyn Gpu, device: &mut Device) -> Result<Option<BufferId>, GpuError> {
183        if let Some(buffer) = &self.buffer {
184            let id = buffer.id();
185            if let Some(bytes) = self.data.bytes() {
186                device.write(gpu, buffer, bytes)?;
187                self.written();
188            }
189            return Ok(Some(id));
190        }
191        let size = self.size();
192        if size == 0 {
193            self.written();
194            return Ok(None);
195        }
196        let buffer = match &self.data {
197            #[cfg(target_family = "wasm")]
198            VertexData::Host(bytes) => device.buffer_from_host(gpu, BufferUsage::Vertex, bytes)?,
199            data => {
200                let Some(bytes) = data.bytes() else {
201                    debug_assert!(false, "vertices without data or a buffer");
202                    return Err(GpuError::Invalid("vertices without data or a buffer".to_owned()));
203                };
204                device.buffer(gpu, BufferUsage::Vertex, &bytes[..size])?
205            }
206        };
207        let id = buffer.id();
208        self.buffer = Some(buffer);
209        self.written();
210        Ok(Some(id))
211    }
212}
213
214/// The context's store of the vertices that draws bind, which their
215/// handles keep while they last.
216#[derive(Default)]
217pub(crate) struct VertexStore(Store<VerticesKey, Vertices>);
218
219impl VertexStore {
220    /// Keeps `vertices` while a clone of the returned handle lasts, whose
221    /// key goes to `queue` once the last clone drops.
222    pub(crate) fn add<V: bytemuck::Pod>(&mut self, vertices: Vec<V>, queue: &Rc<ReleaseQueue>) -> SharedVertices {
223        self.insert(Vertices::new(vertices), queue)
224    }
225
226    /// Keeps a copy of `vertices` as dynamic vertices, which the holder of
227    /// the returned handle updates ([`update`](Self::update)), as
228    /// [`add`](Self::add) does.
229    pub(crate) fn add_dynamic<V: bytemuck::Pod>(
230        &mut self,
231        vertices: &[V],
232        queue: &Rc<ReleaseQueue>,
233    ) -> TypedVertices<V> {
234        TypedVertices { shared: self.insert(Vertices::dynamic(vertices), queue), vertex_type: PhantomData }
235    }
236
237    /// Keeps the vertices of the type `V` in the JS array `bytes`, as
238    /// [`add`](Self::add) does.
239    #[cfg(target_family = "wasm")]
240    pub(crate) fn add_host<V: bytemuck::Pod>(&mut self, bytes: HostBytes, queue: &Rc<ReleaseQueue>) -> SharedVertices {
241        self.insert(Vertices::from_host(bytes, size_of::<V>()), queue)
242    }
243
244    fn insert(&mut self, vertices: Vertices, queue: &Rc<ReleaseQueue>) -> SharedVertices {
245        let count = vertices.count();
246        SharedVertices { handle: self.0.add(vertices, queue), count }
247    }
248
249    /// The vertices of `shared`.
250    pub(crate) fn get(&self, shared: &SharedVertices) -> Option<&Vertices> {
251        self.0.get(&shared.handle)
252    }
253
254    /// Whether the store has the vertices `key`.
255    #[cfg(test)]
256    pub(crate) fn contains(&self, key: VerticesKey) -> bool {
257        self.0.contains(key)
258    }
259
260    /// Replaces the vertices of `typed` with a copy of `data`, as many, as
261    /// [`Vertices::update`] does.
262    pub(crate) fn update<V: bytemuck::Pod>(&mut self, typed: &TypedVertices<V>, data: &[V]) -> bool {
263        let Some(entry) = self.0.get_mut(&typed.shared.handle) else {
264            return false;
265        };
266        debug_assert_eq!(entry.vertex_size(), size_of::<V>());
267        entry.update(bytemuck::cast_slice(data))
268    }
269
270    /// The buffer of the vertices of `shared`, as [`Vertices::upload`]
271    /// makes it.
272    pub(crate) fn upload(
273        &mut self,
274        gpu: &mut dyn Gpu,
275        device: &mut Device,
276        shared: &SharedVertices,
277    ) -> Result<Option<BufferId>, GpuError> {
278        self.0.get_mut(&shared.handle).ok_or(GpuError::UnknownId("vertices"))?.upload(gpu, device)
279    }
280
281    /// Takes out the vertices `key`, whose last handle dropped.
282    pub(crate) fn remove(&mut self, key: VerticesKey) -> Option<Vertices> {
283        self.0.remove(key)
284    }
285
286    /// Drops every entry.
287    pub(crate) fn clear(&mut self) {
288        self.0.clear();
289    }
290}
291
292/// Vertices of the context's store that draws bind, with their count. They
293/// are equal where they are the same entry.
294#[derive(Clone, PartialEq, Eq)]
295pub struct SharedVertices {
296    handle: Shared<VerticesKey>,
297    count: usize,
298}
299
300impl SharedVertices {
301    /// What geometry made of the vertices holds.
302    pub(crate) fn held(&self) -> Held {
303        Held::Vertices(self.handle.clone())
304    }
305
306    /// The entry's key in the store.
307    #[cfg(test)]
308    #[must_use]
309    pub(crate) fn key(&self) -> VerticesKey {
310        self.handle.key()
311    }
312
313    /// The number of vertices.
314    #[must_use]
315    pub fn count(&self) -> usize {
316        self.count
317    }
318}
319
320/// Dynamic vertices of the context's store made of vertices of the type
321/// `V`, which their holder can replace with others of `V`
322/// ([`Context::update_vertices`]).
323///
324/// [`Context::update_vertices`]: crate::draw::context::Context::update_vertices
325pub struct TypedVertices<V> {
326    shared: SharedVertices,
327    vertex_type: PhantomData<fn() -> V>,
328}
329
330impl<V> TypedVertices<V> {
331    /// The vertices, as draws bind them.
332    #[must_use]
333    pub fn shared(&self) -> &SharedVertices {
334        &self.shared
335    }
336}
337
338impl<V> Clone for TypedVertices<V> {
339    fn clone(&self) -> Self {
340        TypedVertices { shared: self.shared.clone(), vertex_type: PhantomData }
341    }
342}