From 6c0cfbefce201cda3b8996f4c7294d90040408ff Mon Sep 17 00:00:00 2001 From: Verox001 Date: Mon, 5 May 2025 21:59:27 +0200 Subject: [PATCH] Added depth buffer to sort drawing indices --- solar_engine/src/state.rs | 40 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/solar_engine/src/state.rs b/solar_engine/src/state.rs index d88b702..6d25f1d 100644 --- a/solar_engine/src/state.rs +++ b/solar_engine/src/state.rs @@ -31,6 +31,7 @@ pub struct State<'a> { global_buffer: wgpu::Buffer, camera: Camera, + depth_texture: wgpu::TextureView, } impl<'a> State<'a> { @@ -92,6 +93,8 @@ impl<'a> State<'a> { contents: bytemuck::cast_slice(&instance_data), usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, }); + + let depth_texture = Self::create_depth_texture(&device, config.width, config.height, sample_count.get()); Self { surface, @@ -108,9 +111,28 @@ impl<'a> State<'a> { instances, instance_buffer, camera, + depth_texture, } } + fn create_depth_texture(device: &Device, width: u32, height: u32, sample_count: u32) -> wgpu::TextureView { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("Depth Texture"), + size: wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Depth32Float, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + texture.create_view(&Default::default()) + } + fn create_geometries(device: &Device) -> HashMap { let mut geometries = HashMap::new(); @@ -229,7 +251,13 @@ impl<'a> State<'a> { // Requires Features::CONSERVATIVE_RASTERIZATION conservative: false, }, - depth_stencil: None, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: true, + depth_compare: wgpu::CompareFunction::Less, + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), multisample: wgpu::MultisampleState { count: sample_count, mask: !0, @@ -301,6 +329,7 @@ impl<'a> State<'a> { view_proj: view_proj.into(), }; self.queue.write_buffer(&self.global_buffer, 0, bytemuck::cast_slice(&[new_globals])); + self.depth_texture = Self::create_depth_texture(&self.device, self.config.width, self.config.height, self.sample_count.get()); println!("Resized to {:?} from state!", new_size); } @@ -350,7 +379,14 @@ impl<'a> State<'a> { store: wgpu::StoreOp::Store, } })], - depth_stencil_attachment: None, + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &self.depth_texture, + 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, });