Skip to main content

mln_engine/draw/
vertex_attribute.rs

1//! The vertex attributes of a draw, by the names of the program's
2//! attributes they bind to: each reads either values of its own, which the
3//! draw owns and uploads to a buffer of its own, or vertices of the context's
4//! store that other draws share.
5
6use std::sync::atomic::{AtomicU64, Ordering};
7
8use mln_gfx::gfx_types::AttributeDataType;
9use mln_gfx::gpu::{BufferUsage, Gpu, GpuError};
10use mln_gfx::shaders::bindings::MAX_ATTRIBUTES;
11
12use crate::draw::buffer::Buffer;
13use crate::draw::context::Context;
14use crate::draw::upload::{AttributeBinding, AttributeDescriptor};
15use crate::draw::vertices::{VertexBuffer, Vertices};
16
17/// Where an attribute reads vertices of the context's store: at `offset`
18/// in each of `stride` bytes, from the vertex `vertex_offset` on, as
19/// `data_type`.
20#[derive(Clone)]
21pub(crate) struct SharedAttribute {
22    pub(crate) vertices: VertexBuffer,
23    pub(crate) data_type: AttributeDataType,
24    pub(crate) offset: u32,
25    pub(crate) vertex_offset: u32,
26    pub(crate) stride: u32,
27}
28
29impl SharedAttribute {
30    /// The attribute that reads `vertices` at `offset` in each of `stride`
31    /// bytes, from the first vertex on, as `data_type`.
32    #[must_use]
33    pub(crate) fn new(vertices: VertexBuffer, data_type: AttributeDataType, offset: u32, stride: u32) -> Self {
34        SharedAttribute { vertices, data_type, offset, vertex_offset: 0, stride }
35    }
36
37    /// The attribute, reading from the vertex `vertex_offset` on.
38    #[must_use]
39    pub(crate) fn starting_at(self, vertex_offset: u32) -> Self {
40        SharedAttribute { vertex_offset, ..self }
41    }
42}
43
44/// Where an attribute's own values are: in their bytes until the first
45/// upload moves them into a buffer, which the draw owns.
46pub(crate) enum OwnValues {
47    Bytes(Vec<u8>),
48    Buffer(Buffer),
49}
50
51/// What a vertex attribute reads.
52pub(crate) enum AttributeSource {
53    /// Values of its own, of `data_type`, `count` of them.
54    Own { data_type: AttributeDataType, count: usize, values: OwnValues },
55    /// Vertices of the context's store.
56    Shared(SharedAttribute),
57}
58
59impl AttributeSource {
60    /// The number of values the attribute reads.
61    pub(crate) fn count(&self) -> usize {
62        match self {
63            AttributeSource::Own { count, .. } => *count,
64            AttributeSource::Shared(shared) => shared.vertices.count(),
65        }
66    }
67
68    /// Whether the next upload writes what the attribute reads: its own
69    /// values before their first upload, or shared vertices that are new
70    /// or updated since theirs.
71    pub(crate) fn needs_upload(&self, context: &Context) -> bool {
72        match self {
73            AttributeSource::Own { values, .. } => matches!(values, OwnValues::Bytes(_)),
74            AttributeSource::Shared(shared) => context.vertices(&shared.vertices).is_some_and(Vertices::needs_upload),
75        }
76    }
77
78    /// The attribute's binding, of the buffer it reads, which this uploads
79    /// to `gpu` where [`needs_upload`](Self::needs_upload) says; `None`
80    /// where there are no values.
81    pub(crate) fn binding(
82        &mut self,
83        gpu: &mut dyn Gpu,
84        context: &mut Context,
85    ) -> Result<Option<AttributeBinding>, GpuError> {
86        match self {
87            AttributeSource::Own { data_type, values, .. } => {
88                let buffer = match values {
89                    OwnValues::Buffer(buffer) => buffer.id(),
90                    OwnValues::Bytes(bytes) => {
91                        let buffer = context.device().buffer(gpu, BufferUsage::Vertex, bytes)?;
92                        let id = buffer.id();
93                        *values = OwnValues::Buffer(buffer);
94                        id
95                    }
96                };
97                Ok(Some(AttributeBinding {
98                    attribute: AttributeDescriptor { data_type: *data_type, offset: 0 },
99                    vertex_stride: data_type.stride() as u32,
100                    buffer,
101                    vertex_offset: 0,
102                    held: None,
103                }))
104            }
105            AttributeSource::Shared(shared) => {
106                let Some(buffer) = context.upload_vertices(gpu, &shared.vertices)? else {
107                    return Ok(None);
108                };
109                debug_assert!(
110                    context
111                        .vertices(&shared.vertices)
112                        .is_none_or(|vertices| (shared.stride as usize) * (shared.vertex_offset as usize)
113                            < vertices.vertex_size() * vertices.count())
114                );
115                Ok(Some(AttributeBinding {
116                    attribute: AttributeDescriptor { data_type: shared.data_type, offset: shared.offset },
117                    vertex_stride: shared.stride,
118                    buffer,
119                    vertex_offset: shared.vertex_offset,
120                    held: Some(shared.vertices.held()),
121                }))
122            }
123        }
124    }
125}
126
127/// The paint properties a draw reads from their uniforms instead, by name.
128#[derive(Clone, Copy, Debug, Default)]
129pub struct Uniforms {
130    names: [&'static str; MAX_ATTRIBUTES],
131    len: usize,
132}
133
134impl Uniforms {
135    pub(crate) fn insert(&mut self, name: &'static str) {
136        if self.contains(name) {
137            return;
138        }
139        debug_assert!(self.len < self.names.len(), "more uniforms than attributes");
140        if let Some(slot) = self.names.get_mut(self.len) {
141            *slot = name;
142            self.len += 1;
143        }
144    }
145
146    #[must_use]
147    pub(crate) fn contains(&self, name: &str) -> bool {
148        self.names[..self.len].contains(&name)
149    }
150}
151
152impl FromIterator<&'static str> for Uniforms {
153    fn from_iter<I: IntoIterator<Item = &'static str>>(names: I) -> Uniforms {
154        let mut uniforms = Uniforms::default();
155        for name in names {
156            uniforms.insert(name);
157        }
158        uniforms
159    }
160}
161
162/// Vertex attributes by the names of the program's attributes they bind to,
163/// each in a slot of the array, which `slot_of` finds.
164#[derive(Default)]
165pub(crate) struct VertexAttributeArray {
166    attrs: [Option<Box<(&'static str, AttributeSource)>>; MAX_ATTRIBUTES],
167    /// Which names its slots hold ([`layout`](Self::layout)).
168    layout: u64,
169}
170
171/// A layout of no other array: 0 is every empty array's.
172fn new_layout() -> u64 {
173    static NEXT: AtomicU64 = AtomicU64::new(1);
174    NEXT.fetch_add(1, Ordering::Relaxed)
175}
176
177impl VertexAttributeArray {
178    /// An array without attributes.
179    #[must_use]
180    pub(crate) fn new() -> Self {
181        Self::default()
182    }
183
184    /// The fewest values any of the attributes reads, `usize::MAX` without
185    /// attributes.
186    #[must_use]
187    pub(crate) fn min_count(&self) -> usize {
188        self.iter().map(|(_, attr)| attr.count()).min().unwrap_or(usize::MAX)
189    }
190
191    /// The slot of the attribute `name`.
192    #[must_use]
193    pub(crate) fn slot_of(&self, name: &str) -> Option<usize> {
194        self.attrs.iter().position(|attr| attr.as_ref().is_some_and(|attr| attr.0 == name))
195    }
196
197    /// The attribute in `slot`.
198    #[must_use]
199    pub(crate) fn at(&self, slot: usize) -> Option<&AttributeSource> {
200        self.attrs.get(slot)?.as_ref().map(|attr| &attr.1)
201    }
202
203    /// The attribute in `slot`, to change.
204    pub(crate) fn at_mut(&mut self, slot: usize) -> Option<&mut AttributeSource> {
205        self.attrs.get_mut(slot)?.as_mut().map(|attr| &mut attr.1)
206    }
207
208    /// Which names the slots hold: arrays of one layout hold the same names
209    /// in the same slots. An array keeps its layout while it only gives
210    /// attributes of its names other values, and takes one of no other
211    /// array's when it gives a slot a name.
212    #[must_use]
213    pub(crate) fn layout(&self) -> u64 {
214        self.layout
215    }
216
217    /// Makes the attribute `name` read `bytes`, its own values of
218    /// `data_type`.
219    pub(crate) fn set_own(&mut self, name: &'static str, data_type: AttributeDataType, bytes: Vec<u8>) {
220        let count = bytes.len().checked_div(data_type.stride()).unwrap_or(0);
221        self.set(name, AttributeSource::Own { data_type, count, values: OwnValues::Bytes(bytes) });
222    }
223
224    /// Makes the attribute `name` read vertices of the context's store as
225    /// `shared` says.
226    pub(crate) fn set_shared(&mut self, name: &'static str, shared: SharedAttribute) {
227        let _slot = self.set(name, AttributeSource::Shared(shared));
228    }
229
230    /// Makes `attribute` the one of `name`, in its slot or the first empty
231    /// one, and returns the slot.
232    fn set(&mut self, name: &'static str, attribute: AttributeSource) -> Option<usize> {
233        if let Some(slot) = self.slot_of(name) {
234            if let Some(Some(held)) = self.attrs.get_mut(slot) {
235                held.1 = attribute;
236            }
237            return Some(slot);
238        }
239        let slot = self.attrs.iter().position(Option::is_none);
240        debug_assert!(slot.is_some(), "more attributes than a shader has");
241        let slot = slot?;
242        self.attrs[slot] = Some(Box::new((name, attribute)));
243        self.layout = new_layout();
244        Some(slot)
245    }
246
247    /// Makes `attributes` the array's, in place of what it had: those of
248    /// the names it has stay in their slots, and the others go.
249    pub(crate) fn replace(&mut self, attributes: impl IntoIterator<Item = (&'static str, SharedAttribute)>) {
250        let mut kept = [false; MAX_ATTRIBUTES];
251        for (name, shared) in attributes {
252            if let Some(slot) = self.set(name, AttributeSource::Shared(shared)) {
253                kept[slot] = true;
254            }
255        }
256        for (slot, kept) in self.attrs.iter_mut().zip(kept) {
257            if !kept && slot.take().is_some() {
258                self.layout = new_layout();
259            }
260        }
261    }
262
263    /// Whether an attribute has values of its own, in a buffer the draw
264    /// owns.
265    pub(crate) fn has_own(&self) -> bool {
266        self.iter().any(|(_, attr)| matches!(attr, AttributeSource::Own { .. }))
267    }
268
269    /// The attributes, with their names.
270    pub(crate) fn iter(&self) -> impl Iterator<Item = (&'static str, &AttributeSource)> {
271        self.attrs.iter().filter_map(|attr| attr.as_ref().map(|attr| (attr.0, &attr.1)))
272    }
273}