use std::borrow::Cow;
use mln_gfx::gfx_types::AttributeDataType;
use crate::draw::vertex_attribute::{SharedAttribute, VertexAttributeArray};
use crate::draw::vertices::VertexBuffer;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VertexAttribute {
pub name: &'static str,
pub format: AttributeDataType,
pub offset: u32,
}
pub trait Vertex: bytemuck::Pod {
const ATTRIBUTES: &'static [VertexAttribute];
}
#[macro_export]
macro_rules! vertex_attributes {
($vertex:ty { $($field:ident => $name:literal: $format:ident),+ $(,)? }) => {
impl $crate::draw::Vertex for $vertex {
const ATTRIBUTES: &'static [$crate::draw::VertexAttribute] = &[$(
$crate::draw::VertexAttribute {
name: $name,
format: $crate::__private::mln_gfx::gfx_types::AttributeDataType::$format,
offset: ::core::mem::offset_of!($vertex, $field) as u32,
},
)+];
}
};
}
#[derive(Clone, Debug)]
pub struct VertexBinding {
pub buffer: VertexBuffer,
pub stride: u32,
pub first_vertex: u32,
pub attributes: Cow<'static, [VertexAttribute]>,
}
impl VertexBinding {
#[must_use]
pub fn new(buffer: &VertexBuffer, stride: u32, attributes: impl Into<Cow<'static, [VertexAttribute]>>) -> Self {
VertexBinding { buffer: buffer.clone(), stride, first_vertex: 0, attributes: attributes.into() }
}
#[must_use]
pub fn of<V: Vertex>(buffer: &VertexBuffer) -> Self {
VertexBinding::new(buffer, size_of::<V>() as u32, V::ATTRIBUTES)
}
#[must_use]
pub fn starting_at(self, first_vertex: u32) -> Self {
VertexBinding { first_vertex, ..self }
}
#[must_use]
pub fn with_buffer(self, buffer: &VertexBuffer) -> Self {
VertexBinding { buffer: buffer.clone(), ..self }
}
#[must_use]
pub fn attribute(&self, name: &str) -> Option<&VertexAttribute> {
self.attributes.iter().find(|attribute| attribute.name == name)
}
pub(crate) fn bind(&self, attrs: &mut VertexAttributeArray) {
for (name, shared) in self.shared() {
attrs.set_shared(name, shared);
}
}
fn shared(&self) -> impl Iterator<Item = (&'static str, SharedAttribute)> + '_ {
self.attributes.iter().map(|attribute| {
let shared = SharedAttribute::new(self.buffer.clone(), attribute.format, attribute.offset, self.stride)
.starting_at(self.first_vertex);
(attribute.name, shared)
})
}
}
pub(crate) fn replace_attributes<'b>(
attrs: &mut VertexAttributeArray,
bindings: impl IntoIterator<Item = &'b VertexBinding>,
) {
attrs.replace(bindings.into_iter().flat_map(VertexBinding::shared));
}
pub(crate) fn attributes_of(bindings: &[VertexBinding]) -> VertexAttributeArray {
let mut attrs = VertexAttributeArray::new();
for binding in bindings {
binding.bind(&mut attrs);
}
attrs
}