From 4762bf6f807146785a88bb0af07647bd2ca24326 Mon Sep 17 00:00:00 2001 From: Verox001 Date: Mon, 13 Jan 2025 21:55:22 +0100 Subject: [PATCH] Finished depth buffer --- src/lib.rs | 123 ++++++++++++++++++++++++++++++++++++++++++++++-- src/model.rs | 44 +++++++++++++++++ src/shader.wgsl | 17 ++++++- src/texture.rs | 42 +++++++++++++++++ 4 files changed, 220 insertions(+), 6 deletions(-) create mode 100644 src/model.rs diff --git a/src/lib.rs b/src/lib.rs index 1566423..8c6782a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,9 +7,69 @@ use winit::{ keyboard::{KeyCode, PhysicalKey}, window::{Window, WindowBuilder}, }; +use cgmath::prelude::*; +use crate::texture::Texture; mod texture; +struct Instance { + position: cgmath::Vector3, + rotation: cgmath::Quaternion, +} + +impl InstanceRaw { + fn desc() -> wgpu::VertexBufferLayout<'static> { + use std::mem; + wgpu::VertexBufferLayout { + array_stride: mem::size_of::() as wgpu::BufferAddress, + // We need to switch from using a step mode of Vertex to Instance + // This means that our shaders will only change to use the next + // instance when the shader starts processing a new instance + step_mode: wgpu::VertexStepMode::Instance, + attributes: &[ + // A mat4 takes up 4 vertex slots as it is technically 4 vec4s. We need to define a slot + // for each vec4. We'll have to reassemble the mat4 in the shader. + wgpu::VertexAttribute { + offset: 0, + // While our vertex shader only uses locations 0, and 1 now, in later tutorials, we'll + // be using 2, 3, and 4, for Vertex. We'll start at slot 5, not conflict with them later + shader_location: 5, + format: wgpu::VertexFormat::Float32x4, + }, + wgpu::VertexAttribute { + offset: mem::size_of::<[f32; 4]>() as wgpu::BufferAddress, + shader_location: 6, + format: wgpu::VertexFormat::Float32x4, + }, + wgpu::VertexAttribute { + offset: mem::size_of::<[f32; 8]>() as wgpu::BufferAddress, + shader_location: 7, + format: wgpu::VertexFormat::Float32x4, + }, + wgpu::VertexAttribute { + offset: mem::size_of::<[f32; 12]>() as wgpu::BufferAddress, + shader_location: 8, + format: wgpu::VertexFormat::Float32x4, + }, + ], + } + } +} + +impl Instance { + fn to_raw(&self) -> InstanceRaw { + InstanceRaw { + model: (cgmath::Matrix4::from_translation(self.position) * cgmath::Matrix4::from(self.rotation)).into(), + } + } +} + +#[repr(C)] +#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] +struct InstanceRaw { + model: [[f32; 4]; 4], +} + #[repr(C)] #[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] struct Vertex { @@ -222,15 +282,20 @@ struct State<'a> { #[allow(dead_code)] diffuse_texture: texture::Texture, diffuse_bind_group: wgpu::BindGroup, - // NEW! camera: Camera, camera_controller: CameraController, camera_uniform: CameraUniform, camera_buffer: wgpu::Buffer, camera_bind_group: wgpu::BindGroup, window: &'a Window, + instances: Vec, + instance_buffer: wgpu::Buffer, + depth_texture: Texture, } +const NUM_INSTANCES_PER_ROW: u32 = 10; +const INSTANCE_DISPLACEMENT: cgmath::Vector3 = cgmath::Vector3::new(NUM_INSTANCES_PER_ROW as f32 * 0.5, 0.0, NUM_INSTANCES_PER_ROW as f32 * 0.5); + impl<'a> State<'a> { async fn new(window: &'a Window) -> State<'a> { let size = window.inner_size(); @@ -288,6 +353,8 @@ impl<'a> State<'a> { desired_maximum_frame_latency: 2, }; + let depth_texture = texture::Texture::create_depth_texture(&device, &config, "depth_texture"); + let diffuse_bytes = include_bytes!("happy-tree.png"); let diffuse_texture = texture::Texture::from_bytes(&device, &queue, diffuse_bytes, "happy-tree.png").unwrap(); @@ -392,7 +459,7 @@ impl<'a> State<'a> { vertex: wgpu::VertexState { module: &shader, entry_point: "vs_main", - buffers: &[Vertex::desc()], + buffers: &[Vertex::desc(), InstanceRaw::desc()], compilation_options: Default::default(), }, fragment: Some(wgpu::FragmentState { @@ -421,7 +488,13 @@ impl<'a> State<'a> { // Requires Features::CONSERVATIVE_RASTERIZATION conservative: false, }, - depth_stencil: None, + depth_stencil: Some(wgpu::DepthStencilState { + format: texture::Texture::DEPTH_FORMAT, + depth_write_enabled: true, + depth_compare: wgpu::CompareFunction::Less, + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), multisample: wgpu::MultisampleState { count: 1, mask: !0, @@ -446,6 +519,33 @@ impl<'a> State<'a> { }); let num_indices = INDICES.len() as u32; + let instances = (0..NUM_INSTANCES_PER_ROW).flat_map(|z| { + (0..NUM_INSTANCES_PER_ROW).map(move |x| { + let position = cgmath::Vector3 { x: x as f32, y: 0.0, z: z as f32 } - INSTANCE_DISPLACEMENT; + + let rotation = if position.is_zero() { + // this is needed so an object at (0, 0, 0) won't get scaled to zero + // as Quaternions can affect scale if they're not created correctly + cgmath::Quaternion::from_axis_angle(cgmath::Vector3::unit_z(), cgmath::Deg(0.0)) + } else { + cgmath::Quaternion::from_axis_angle(position.normalize(), cgmath::Deg(45.0)) + }; + + Instance { + position, rotation, + } + }) + }).collect::>(); + + let instance_data = instances.iter().map(Instance::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 { surface, device, @@ -464,6 +564,9 @@ impl<'a> State<'a> { camera_bind_group, camera_uniform, window, + instances, + instance_buffer, + depth_texture, } } @@ -478,6 +581,8 @@ impl<'a> State<'a> { self.config.height = new_size.height; self.surface.configure(&self.device, &self.config); + self.depth_texture = Texture::create_depth_texture(&self.device, &self.config, "depth_texture"); + self.camera.aspect = self.config.width as f32 / self.config.height as f32; } } @@ -524,7 +629,14 @@ impl<'a> State<'a> { store: wgpu::StoreOp::Store, }, })], - depth_stencil_attachment: None, + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &self.depth_texture.view, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + }), occlusion_query_set: None, timestamp_writes: None, }); @@ -533,8 +645,9 @@ impl<'a> State<'a> { render_pass.set_bind_group(0, &self.diffuse_bind_group, &[]); render_pass.set_bind_group(1, &self.camera_bind_group, &[]); 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.draw_indexed(0..self.num_indices, 0, 0..1); + render_pass.draw_indexed(0..self.num_indices, 0, 0..self.instances.len() as _); } self.queue.submit(iter::once(encoder.finish())); diff --git a/src/model.rs b/src/model.rs new file mode 100644 index 0000000..5361932 --- /dev/null +++ b/src/model.rs @@ -0,0 +1,44 @@ +pub trait Vertex { + fn desc() -> wgpu::VertexBufferLayout<'static>; +} + +#[repr(C)] +#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] +pub struct ModelVertex { + pub position: [f32; 3], + pub tex_coords: [f32; 2], + pub normal: [f32; 3], +} + +impl Vertex for ModelVertex { + fn desc() -> wgpu::VertexBufferLayout<'static> { + todo!(); + } +} + +impl Vertex for ModelVertex { + fn desc() -> wgpu::VertexBufferLayout<'static> { + use std::mem; + wgpu::VertexBufferLayout { + array_stride: mem::size_of::() as wgpu::BufferAddress, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &[ + wgpu::VertexAttribute { + offset: 0, + shader_location: 0, + format: wgpu::VertexFormat::Float32x3, + }, + wgpu::VertexAttribute { + offset: mem::size_of::<[f32; 3]>() as wgpu::BufferAddress, + shader_location: 1, + format: wgpu::VertexFormat::Float32x2, + }, + wgpu::VertexAttribute { + offset: mem::size_of::<[f32; 5]>() as wgpu::BufferAddress, + shader_location: 2, + format: wgpu::VertexFormat::Float32x3, + }, + ], + } + } +} \ No newline at end of file diff --git a/src/shader.wgsl b/src/shader.wgsl index 1a97430..9d8155d 100644 --- a/src/shader.wgsl +++ b/src/shader.wgsl @@ -1,3 +1,11 @@ +struct InstanceInput { + @location(5) model_matrix_0: vec4, + @location(6) model_matrix_1: vec4, + @location(7) model_matrix_2: vec4, + @location(8) model_matrix_3: vec4, +}; + + // Vertex shader struct CameraUniform { view_proj: mat4x4, @@ -18,10 +26,17 @@ struct VertexOutput { @vertex fn vs_main( model: VertexInput, + instance: InstanceInput, ) -> VertexOutput { + let model_matrix = mat4x4( + instance.model_matrix_0, + instance.model_matrix_1, + instance.model_matrix_2, + instance.model_matrix_3, + ); var out: VertexOutput; out.tex_coords = model.tex_coords; - out.clip_position = camera.view_proj * vec4(model.position, 1.0); // 2. + out.clip_position = camera.view_proj * model_matrix * vec4(model.position, 1.0); return out; } diff --git a/src/texture.rs b/src/texture.rs index 0001894..5b80725 100644 --- a/src/texture.rs +++ b/src/texture.rs @@ -77,4 +77,46 @@ impl Texture { Ok(Self { texture, view, sampler }) } +} + +impl Texture { + pub const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float; + + pub fn create_depth_texture(device: &wgpu::Device, config: &wgpu::SurfaceConfiguration, label: &str) -> Self { + let size = wgpu::Extent3d { + width: config.width.max(1), + height: config.height.max(1), + depth_or_array_layers: 1, + }; + let desc = wgpu::TextureDescriptor { + label: Some(label), + size, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: Self::DEPTH_FORMAT, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }; + let texture = device.create_texture(&desc); + + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + let sampler = device.create_sampler( + &wgpu::SamplerDescriptor { + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + address_mode_w: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + mipmap_filter: wgpu::FilterMode::Nearest, + compare: Some(wgpu::CompareFunction::LessEqual), + lod_min_clamp: 0.0, + lod_max_clamp: 100.0, + ..Default::default() + } + ); + + Self { texture, view, sampler } + } } \ No newline at end of file