1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use wgpu::util::DeviceExt;
use crate::primitives::vertices::Vertex;
/// A simple struct that contains the information of mesh in a way that can be used by WGPU.
#[derive(Debug)]
pub struct Mesh {
pub(crate) vertex_buf: wgpu::Buffer,
pub(crate) index_buf: wgpu::Buffer,
pub(crate) num_indices: u32,
pub(crate) num_vertices: u32
}
impl Mesh {
/// Create a new mesh from a WGPU device with vertices and indices arrays.
///
/// Arguments:
/// * device: &wgpu::Device - The WGPU device to be used to create the buffers for this mesh.
/// * vertices: &[Vertex] - The array of vertices for this mesh.
/// * indices: &[u16] - The indices of this mesh.
pub fn from_raw(device: &wgpu::Device, vertices: &[Vertex], indices: &[u16]) -> Self {
Self {
vertex_buf: device.create_buffer_init(
&wgpu::util::BufferInitDescriptor {
label: Some("Vertex Buffer"),
contents: bytemuck::cast_slice(vertices),
usage: wgpu::BufferUsages::VERTEX
}
),
index_buf: device.create_buffer_init(
&wgpu::util::BufferInitDescriptor {
label: Some("Index Buffer"),
contents: bytemuck::cast_slice(indices),
usage: wgpu::BufferUsages::INDEX
}
),
num_indices: indices.len() as u32,
num_vertices: vertices.len() as u32
}
}
/// Draws a mesh to this render pass.
///
/// Arguments:
/// * self: &self - The mesh to be rendered
/// * pass: &mut wgpu::RenderPass - The render pass to render too.
/// * instance_buf: &wgpu::Buffer - The instances buffer to draw the mesh with.
/// * instance_count: u32 - The number of instances in the above buffer.
pub fn draw<'rpass>(
&'rpass self,
pass: &mut wgpu::RenderPass<'rpass>,
instance_buffer: &'rpass wgpu::Buffer,
instance_count: u32
) {
pass.set_vertex_buffer(0, self.vertex_buf.slice(..));
pass.set_vertex_buffer(1, instance_buffer.slice(..));
pass.set_index_buffer(self.index_buf.slice(..), wgpu::IndexFormat::Uint16);
pass.draw_indexed(0..self.num_indices, 0, 0..instance_count);
}
/// Draws a mesh to this render pass only using its vertices buffer.
///
/// Arguments:
/// * self: &self - The mesh to be rendered
/// * pass: &mut wgpu::RenderPass - The render pass to render too.
/// * instance_buf: &wgpu::Buffer - The instances buffer to draw the mesh with.
/// * instance_count: u32 - The number of instances in the above buffer.
pub fn draw_list<'rpass>(
&'rpass self,
pass: &mut wgpu::RenderPass<'rpass>,
instance_buffer: &'rpass wgpu::Buffer,
instance_count: u32
) {
pass.set_vertex_buffer(0, self.vertex_buf.slice(..));
pass.set_vertex_buffer(1, instance_buffer.slice(..));
pass.set_index_buffer(self.index_buf.slice(..), wgpu::IndexFormat::Uint16);
pass.draw(0 .. self.num_vertices, 0..instance_count);
}
}