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