Added instancing

This commit is contained in:
Verox001 2025-05-04 12:03:18 +02:00
parent e88a5d171a
commit 60bd8c67d6
3 changed files with 85 additions and 24 deletions

View File

@ -12,3 +12,4 @@ env_logger = "0.11.8"
bytemuck = "1.23.0" bytemuck = "1.23.0"
wgpu = "25.0" wgpu = "25.0"
pollster = "0.4.0" pollster = "0.4.0"
cgmath = "0.18.0"

View File

@ -1,6 +1,7 @@
use std::cmp::max; use std::cmp::max;
use std::sync::Arc; use std::sync::Arc;
use cgmath::num_traits::ToPrimitive;
use cgmath::Rotation3;
use pollster::FutureExt; use pollster::FutureExt;
use wgpu::util::DeviceExt; use wgpu::util::DeviceExt;
use wgpu::{Adapter, Device, Instance, PresentMode, Queue, Surface, SurfaceCapabilities}; use wgpu::{Adapter, Device, Instance, PresentMode, Queue, Surface, SurfaceCapabilities};
@ -17,6 +18,39 @@ pub async fn run() {
let _ = event_loop.run_app(&mut window_state); let _ = event_loop.run_app(&mut window_state);
} }
struct RenderInstance {
position: cgmath::Vector3<f32>,
rotation: cgmath::Quaternion<f32>,
}
impl RenderInstance {
fn to_raw(&self) -> InstanceRaw {
let model = cgmath::Matrix4::from_translation(self.position) * cgmath::Matrix4::from(self.rotation);
InstanceRaw { model: model.into() }
}
}
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct InstanceRaw {
model: [[f32; 4]; 4],
}
impl InstanceRaw {
fn desc() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout {
array_stride: size_of::<InstanceRaw>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &[
wgpu::VertexAttribute { offset: 0, shader_location: 5, format: wgpu::VertexFormat::Float32x4 },
wgpu::VertexAttribute { offset: size_of::<[f32; 4]>() as wgpu::BufferAddress, shader_location: 6, format: wgpu::VertexFormat::Float32x4 },
wgpu::VertexAttribute { offset: size_of::<[f32; 8]>() as wgpu::BufferAddress, shader_location: 7, format: wgpu::VertexFormat::Float32x4 },
wgpu::VertexAttribute { offset: size_of::<[f32; 12]>() as wgpu::BufferAddress, shader_location: 8, format: wgpu::VertexFormat::Float32x4 },
],
}
}
}
#[repr(C)] #[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] #[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct Vertex { struct Vertex {
@ -115,6 +149,9 @@ struct State<'a> {
vertex_buffer: wgpu::Buffer, vertex_buffer: wgpu::Buffer,
index_buffer: wgpu::Buffer, index_buffer: wgpu::Buffer,
instances: Vec<RenderInstance>,
instance_buffer: wgpu::Buffer,
num_vertices: u32, num_vertices: u32,
num_indices: u32, num_indices: u32,
} }
@ -138,6 +175,23 @@ impl<'a> State<'a> {
let num_vertices = VERTICES.len() as u32; let num_vertices = VERTICES.len() as u32;
let num_indices = INDICES.len() as u32; let num_indices = INDICES.len() as u32;
let instances = vec![
RenderInstance {
position: cgmath::Vector3::new(0.0, 0.0, 0.0),
rotation: cgmath::Quaternion::from_angle_z(cgmath::Deg(0.0)),
},
RenderInstance {
position: cgmath::Vector3::new(1.0, 1.0, 0.0),
rotation: cgmath::Quaternion::from_angle_z(cgmath::Deg(45.0)),
},
];
let instance_data: Vec<InstanceRaw> = instances.iter().map(RenderInstance::to_raw).collect();
let instance_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Instance Buffer"),
contents: bytemuck::cast_slice(&instance_data),
usage: wgpu::BufferUsages::VERTEX,
});
Self { Self {
surface, surface,
device, device,
@ -150,6 +204,9 @@ impl<'a> State<'a> {
vertex_buffer, vertex_buffer,
index_buffer, index_buffer,
instances,
instance_buffer,
num_vertices, num_vertices,
num_indices, num_indices,
} }
@ -202,7 +259,7 @@ impl<'a> State<'a> {
vertex: wgpu::VertexState { vertex: wgpu::VertexState {
module: &shader, module: &shader,
entry_point: Some("vs_main"), entry_point: Some("vs_main"),
buffers: &[Vertex::desc()], buffers: &[Vertex::desc(), InstanceRaw::desc()],
compilation_options: Default::default(), compilation_options: Default::default(),
}, },
fragment: Some(wgpu::FragmentState { fragment: Some(wgpu::FragmentState {
@ -326,8 +383,9 @@ impl<'a> State<'a> {
render_pass.set_pipeline(&self.render_pipeline); render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..)); render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
render_pass.set_vertex_buffer(1, self.instance_buffer.slice(..));
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16); render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
render_pass.draw_indexed(0..self.num_indices, 0, 0..1); render_pass.draw_indexed(0..self.num_indices, 0, 0..self.instances.len() as u32);
} }
self.queue.submit(std::iter::once(encoder.finish())); self.queue.submit(std::iter::once(encoder.finish()));

View File

@ -3,31 +3,33 @@ struct VertexInput {
@location(1) color: vec3<f32>, @location(1) color: vec3<f32>,
}; };
struct VertexOutput { struct InstanceInput {
@builtin(position) clip_position: vec4<f32>, @location(5) model_row0: vec4<f32>,
@location(6) model_row1: vec4<f32>,
@location(7) model_row2: vec4<f32>,
@location(8) model_row3: vec4<f32>,
};
struct VSOutput {
@builtin(position) position: vec4<f32>,
@location(0) color: vec3<f32>, @location(0) color: vec3<f32>,
}; };
@vertex @vertex
fn vs_main( fn vs_main(vertex: VertexInput, instance: InstanceInput) -> VSOutput {
model: VertexInput, var out: VSOutput;
) -> VertexOutput { let model = mat4x4<f32>(
var out: VertexOutput; instance.model_row0,
out.color = model.color; instance.model_row1,
out.clip_position = vec4<f32>(model.position, 1.0); instance.model_row2,
instance.model_row3
);
out.position = model * vec4<f32>(vertex.position, 1.0);
out.color = vertex.color;
return out; return out;
} }
fn srgb_to_linear(c: f32) -> f32 {
return pow((c + 0.055) / 1.055, 2.4);
}
@fragment @fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> { fn fs_main(input: VSOutput) -> @location(0) vec4<f32> {
let linear_color = vec3<f32>( return vec4<f32>(input.color, 1.0);
srgb_to_linear(in.color.r),
srgb_to_linear(in.color.g),
srgb_to_linear(in.color.b),
);
return vec4<f32>(linear_color, 1.0);
} }