mesh.rs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //! Single mesh
  2. use crate::vertex::*;
  3. use std::ops::Range;
  4. use bytemuck::cast_slice;
  5. use wgpu::{
  6. util::{BufferInitDescriptor, DeviceExt},
  7. *
  8. };
  9. pub const INDEX_FORMAT: IndexFormat = IndexFormat::Uint32;
  10. pub struct Mesh {
  11. vertices: Buffer,
  12. indices: Buffer,
  13. index_count: u32
  14. }
  15. impl Mesh {
  16. /// Create a new mesh from vertices and indices
  17. pub fn new<V: Vertex>(device: &Device, vertex_data: &[V], index_data: &[Index]) -> Self {
  18. let vertices = device.create_buffer_init(&BufferInitDescriptor {
  19. label: Some("Mesh Vertices"),
  20. contents: cast_slice(vertex_data),
  21. usage: BufferUsages::VERTEX
  22. });
  23. let indices = device.create_buffer_init(&BufferInitDescriptor {
  24. label: Some("Mesh Indices"),
  25. contents: cast_slice(index_data),
  26. usage: BufferUsages::INDEX
  27. });
  28. let index_count = index_data.len() as u32;
  29. Self {
  30. vertices,
  31. indices,
  32. index_count
  33. }
  34. }
  35. /// Draw a single instance of this mesh.
  36. /// Drawing indexed or indirectly is prefered.
  37. pub fn draw<'a>(&'a self, pass: &mut RenderPass<'a>) {
  38. pass.set_vertex_buffer(0, self.vertices.slice(..));
  39. pass.set_index_buffer(self.indices.slice(..), INDEX_FORMAT);
  40. pass.draw_indexed(0..self.index_count, 0, 0..1);
  41. }
  42. /// Draw multiple instances of this mesh, the instance buffer must be bound already.
  43. /// Drawing indirectly is prefered.
  44. pub fn draw_instanced<'a>(&'a self, pass: &mut RenderPass<'a>, instances: Range<u32>) {
  45. pass.set_vertex_buffer(0, self.vertices.slice(..));
  46. pass.set_index_buffer(self.indices.slice(..), INDEX_FORMAT);
  47. pass.draw_indexed(0..self.index_count, 0, instances);
  48. }
  49. }