From 94e6d1f5859205897fe6c8fa29d7ebff5e9af4fa Mon Sep 17 00:00:00 2001 From: Dominik Kaiser Date: Fri, 27 Nov 2026 19:59:41 +0100 Subject: The index buffer --- games/00_triangle/src/main.rs | 42 ++++++++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 16 deletions(-) (limited to 'games/00_triangle') diff --git a/games/00_triangle/src/main.rs b/games/00_triangle/src/main.rs index da4d548..952b29d 100644 --- a/games/00_triangle/src/main.rs +++ b/games/00_triangle/src/main.rs @@ -39,19 +39,20 @@ impl Vertex { } } +#[rustfmt::skip] const VERTICES: &[Vertex] = &[ - Vertex { - position: [0.0, 0.5, 0.0], - color: [1.0, 0.0, 0.0], - }, - Vertex { - position: [-0.5, -0.5, 0.0], - color: [0.0, 1.0, 0.0], - }, - Vertex { - position: [0.5, -0.5, 0.0], - color: [0.0, 0.0, 1.0], - }, + Vertex { position: [-0.0868241, 0.49240386, 0.0], color: [0.5, 0.0, 0.5] }, // A + Vertex { position: [-0.49513406, 0.06958647, 0.0], color: [0.5, 0.0, 0.5] }, // B + Vertex { position: [-0.21918549, -0.44939706, 0.0], color: [0.5, 0.0, 0.5] }, // C + Vertex { position: [0.35966998, -0.3473291, 0.0], color: [0.5, 0.0, 0.5] }, // D + Vertex { position: [0.44147372, 0.2347359, 0.0], color: [0.5, 0.0, 0.5] }, // E +]; + +#[rustfmt::skip] +const INDICES: &[u16] = &[ + 0, 1, 4, + 1, 2, 4, + 2, 3, 4, ]; pub struct State { @@ -63,7 +64,8 @@ pub struct State { window: Arc, render_pipeline: wgpu::RenderPipeline, vertex_buffer: wgpu::Buffer, - num_vertices: u32, + index_buffer: wgpu::Buffer, + num_indices: u32, } impl State { @@ -172,7 +174,13 @@ impl State { usage: wgpu::BufferUsages::VERTEX, }); - let num_vertices = VERTICES.len() as u32; + let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("Index Buffer"), + contents: bytemuck::cast_slice(INDICES), + usage: wgpu::BufferUsages::INDEX, + }); + + let num_indices = INDICES.len() as u32; Ok(Self { surface, @@ -183,7 +191,8 @@ impl State { render_pipeline, window, vertex_buffer, - num_vertices, + index_buffer, + num_indices, }) } @@ -263,7 +272,8 @@ impl State { render_pass.set_pipeline(&self.render_pipeline); render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..)); - render_pass.draw(0..self.num_vertices, 0..1); + render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16); + render_pass.draw_indexed(0..self.num_indices, 0, 0..1); } self.queue.submit(std::iter::once(encoder.finish())); -- cgit v1.2.3