mln_engine/draw/
vertex.rs1use std::borrow::Cow;
7
8use mln_gfx::gfx_types::AttributeDataType;
9
10use crate::draw::vertex_attribute::{SharedAttribute, VertexAttributeArray};
11use crate::draw::vertices::VertexBuffer;
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub struct VertexAttribute {
17 pub name: &'static str,
18 pub format: AttributeDataType,
19 pub offset: u32,
20}
21
22pub trait Vertex: bytemuck::Pod {
25 const ATTRIBUTES: &'static [VertexAttribute];
26}
27
28#[macro_export]
41macro_rules! vertex_attributes {
42 ($vertex:ty { $($field:ident => $name:literal: $format:ident),+ $(,)? }) => {
43 impl $crate::draw::Vertex for $vertex {
44 const ATTRIBUTES: &'static [$crate::draw::VertexAttribute] = &[$(
45 $crate::draw::VertexAttribute {
46 name: $name,
47 format: $crate::__private::mln_gfx::gfx_types::AttributeDataType::$format,
48 offset: ::core::mem::offset_of!($vertex, $field) as u32,
49 },
50 )+];
51 }
52 };
53}
54
55#[derive(Clone, Debug)]
59pub struct VertexBinding {
60 pub buffer: VertexBuffer,
61 pub stride: u32,
62 pub first_vertex: u32,
63 pub attributes: Cow<'static, [VertexAttribute]>,
64}
65
66impl VertexBinding {
67 #[must_use]
69 pub fn new(buffer: &VertexBuffer, stride: u32, attributes: impl Into<Cow<'static, [VertexAttribute]>>) -> Self {
70 VertexBinding { buffer: buffer.clone(), stride, first_vertex: 0, attributes: attributes.into() }
71 }
72
73 #[must_use]
75 pub fn of<V: Vertex>(buffer: &VertexBuffer) -> Self {
76 VertexBinding::new(buffer, size_of::<V>() as u32, V::ATTRIBUTES)
77 }
78
79 #[must_use]
81 pub fn starting_at(self, first_vertex: u32) -> Self {
82 VertexBinding { first_vertex, ..self }
83 }
84
85 #[must_use]
87 pub fn with_buffer(self, buffer: &VertexBuffer) -> Self {
88 VertexBinding { buffer: buffer.clone(), ..self }
89 }
90
91 #[must_use]
93 pub fn attribute(&self, name: &str) -> Option<&VertexAttribute> {
94 self.attributes.iter().find(|attribute| attribute.name == name)
95 }
96
97 pub(crate) fn bind(&self, attrs: &mut VertexAttributeArray) {
99 for (name, shared) in self.shared() {
100 attrs.set_shared(name, shared);
101 }
102 }
103
104 fn shared(&self) -> impl Iterator<Item = (&'static str, SharedAttribute)> + '_ {
106 self.attributes.iter().map(|attribute| {
107 let shared = SharedAttribute::new(self.buffer.clone(), attribute.format, attribute.offset, self.stride)
108 .starting_at(self.first_vertex);
109 (attribute.name, shared)
110 })
111 }
112}
113
114pub(crate) fn replace_attributes<'b>(
117 attrs: &mut VertexAttributeArray,
118 bindings: impl IntoIterator<Item = &'b VertexBinding>,
119) {
120 attrs.replace(bindings.into_iter().flat_map(VertexBinding::shared));
121}
122
123pub(crate) fn attributes_of(bindings: &[VertexBinding]) -> VertexAttributeArray {
125 let mut attrs = VertexAttributeArray::new();
126 for binding in bindings {
127 binding.bind(&mut attrs);
128 }
129 attrs
130}