A GameCube/Wii emulator and debugger written in Rust.
depth efb copy resolve
Layleb46e57912074
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rsindex ed49794..3435eaa 100644--- a/crates/backend-wgpu/src/action.rs+++ b/crates/backend-wgpu/src/action.rs@@ -116,11 +116,7 @@ impl GxRenderer {// after a prior EFB copy. Return the stale GPU// copy to its pool and let the RAM-decoded entry win.if let Some((old_tex, old_view)) = self.efb_copy_cache.remove(&tid) {- let old_size = old_tex.size();- self.efb_copy_pool- .entry((old_size.width, old_size.height))- .or_default()- .push((old_tex, old_view));+ self.return_to_pool(old_tex, old_view);}self.texture_cache.insert(*id, (tex, view));@@ -300,8 +296,10 @@ impl GxRenderer {*alpha_supported,);- // Blit the resolved EFB region into a GPU texture keyed by `dest_addr`.- if !*depth_copy {+ // Blit or resolve the EFB region into a GPU texture keyed by `dest_addr`.+ if *depth_copy {+ self.cache_efb_copy_depth(device, queue, *dest_addr, *src_x, *src_y, *src_w, *src_h, *mipmap);+ } else {self.cache_efb_copy_color(device, queue, *dest_addr, *src_x, *src_y, *src_w, *src_h, *mipmap);}diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rsindex 57bbf91..56f117a 100644--- a/crates/backend-wgpu/src/lib.rs+++ b/crates/backend-wgpu/src/lib.rs@@ -114,6 +114,12 @@ pub struct GxRenderer {pub(crate) efb_copy_pool: FxHashMap<(u32, u32), Vec<(wgpu::Texture, wgpu::TextureView)>>,// Blits a sub-rect of `efb_view` into an `Rgba8Unorm` target, reusing xfb_copy's shader and layout.pub(crate) efb_copy_pipeline: wgpu::RenderPipeline,+ // Retired depth copy textures grouped by size, kept separate so the (w, h) key isn't shared with color.+ pub(crate) efb_depth_pool: FxHashMap<(u32, u32), Vec<(wgpu::Texture, wgpu::TextureView)>>,+ // Resolves a sub-rect of the 4x MSAA `efb_depth_view` into an R32Float target.+ pub(crate) efb_depth_resolve_pipeline: wgpu::RenderPipeline,+ pub(crate) efb_depth_resolve_bg_layout: wgpu::BindGroupLayout,+ pub(crate) efb_depth_resolve_uniform_buffer: wgpu::Buffer,pub(crate) fallback_view: wgpu::TextureView,pub(crate) scratch_vertices: Vec<GpuVertex>,pub(crate) scratch_draws: Vec<(u32, u32)>,@@ -179,6 +185,10 @@ impl GxRenderer {label: Some("xfb_copy_shader"),source: wgpu::ShaderSource::Wgsl(include_str!("shaders/xfb_copy.wgsl").into()),});+ let efb_depth_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("efb_depth_shader"),+ source: wgpu::ShaderSource::Wgsl(include_str!("shaders/efb_depth.wgsl").into()),+ });// Bindings: 0=FrameUniforms, 1=DrawUniforms, 2-9=textures 0-7, 10-17=samplers 0-7let mut layout_entries = vec![@@ -344,7 +354,7 @@ impl GxRenderer {sample_count: EFB_SAMPLE_COUNT,dimension: wgpu::TextureDimension::D2,format: wgpu::TextureFormat::Depth24Plus,- usage: wgpu::TextureUsages::RENDER_ATTACHMENT,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,view_formats: &[],});let efb_depth_view = efb_depth_texture.create_view(&Default::default());@@ -490,6 +500,75 @@ impl GxRenderer {mapped_at_creation: false,});+ let efb_depth_resolve_bg_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("efb_depth_resolve_bgl"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture {+ multisampled: true,+ view_dimension: wgpu::TextureViewDimension::D2,+ sample_type: wgpu::TextureSampleType::Depth,+ },+ count: None,+ },+ ],+ });+ let efb_depth_resolve_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some("efb_depth_resolve_layout"),+ bind_group_layouts: &[&efb_depth_resolve_bg_layout],+ immediate_size: 0,+ });+ let efb_depth_resolve_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("efb_depth_resolve_pipeline"),+ layout: Some(&efb_depth_resolve_pipeline_layout),+ vertex: wgpu::VertexState {+ module: &efb_depth_shader,+ entry_point: Some("vs_main"),+ buffers: &[],+ compilation_options: Default::default(),+ },+ fragment: Some(wgpu::FragmentState {+ module: &efb_depth_shader,+ entry_point: Some("fs_main"),+ targets: &[Some(wgpu::ColorTargetState {+ format: wgpu::TextureFormat::R16Float,+ blend: None,+ write_mask: wgpu::ColorWrites::RED,+ })],+ compilation_options: Default::default(),+ }),+ primitive: wgpu::PrimitiveState {+ topology: wgpu::PrimitiveTopology::TriangleList,+ ..Default::default()+ },+ depth_stencil: None,+ multisample: wgpu::MultisampleState {+ count: 1,+ mask: !0,+ alpha_to_coverage_enabled: false,+ },+ multiview_mask: None,+ cache: None,+ });+ let efb_depth_resolve_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("efb_depth_resolve_uniforms"),+ size: std::mem::size_of::<render::XfbCopyUniforms>() as u64,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+let efb_clear = clear::EfbClear::new(device,surface_format,@@ -527,6 +606,10 @@ impl GxRenderer {efb_copy_cache: FxHashMap::default(),efb_copy_pool: FxHashMap::default(),efb_copy_pipeline,+ efb_depth_pool: FxHashMap::default(),+ efb_depth_resolve_pipeline,+ efb_depth_resolve_bg_layout,+ efb_depth_resolve_uniform_buffer,fallback_view,scratch_vertices: Vec::new(),scratch_draws: Vec::new(),diff --git a/crates/backend-wgpu/src/render.rs b/crates/backend-wgpu/src/render.rsindex 033d19a..b5d1718 100644--- a/crates/backend-wgpu/src/render.rs+++ b/crates/backend-wgpu/src/render.rs@@ -279,19 +279,11 @@ impl GxRenderer {let dst_w = (width / divisor).max(1);let dst_h = (height / divisor).max(1);- // Evict any prior cached copy at this address, returning the- // texture to the pool bucket for its own size so it can be- // reused by a future copy at the same dimensions.+ // Send any prior cached entry back to the right pool so it can be reused.if let Some((old_tex, old_view)) = self.efb_copy_cache.remove(&dest_addr) {- let old_size = old_tex.size();- self.efb_copy_pool- .entry((old_size.width, old_size.height))- .or_default()- .push((old_tex, old_view));+ self.return_to_pool(old_tex, old_view);}- // Drop bind groups that referenced `dest_addr`. They captured- // the old view and would still point at a pooled, stale texture- // on next use. This is the same invalidation `LoadTexture` does.+ // Drop stale bind groups that captured the old view.self.bind_group_cache.retain(|key, _| !key.tex_keys.contains(&Some(dest_addr)));@@ -382,6 +374,131 @@ impl GxRenderer {self.efb_copy_cache.insert(dest_addr, (tex, view));}+ /// Sends an evicted efb_copy_cache entry back to the correct size-keyed pool based on its format.+ pub(crate) fn return_to_pool(&mut self, tex: wgpu::Texture, view: wgpu::TextureView) {+ let size = tex.size();+ let key = (size.width, size.height);+ match tex.format() {+ wgpu::TextureFormat::R16Float => self.efb_depth_pool.entry(key).or_default().push((tex, view)),+ _ => self.efb_copy_pool.entry(key).or_default().push((tex, view)),+ }+ }++ /// Resolves the 4x MSAA `efb_depth_view` into a single-sample R32Float texture keyed by `dest_addr`.+ pub(crate) fn cache_efb_copy_depth(+ &mut self,+ device: &wgpu::Device,+ queue: &wgpu::Queue,+ dest_addr: Address,+ src_x: u32,+ src_y: u32,+ src_w: u32,+ src_h: u32,+ half: bool,+ ) {+ let width = src_w.min(crate::EFB_WIDTH.saturating_sub(src_x));+ let height = src_h.min(crate::EFB_HEIGHT.saturating_sub(src_y));+ if width == 0 || height == 0 {+ tracing::warn!(+ src_x,+ src_y,+ src_w,+ src_h,+ "efb_depth_cache: zero-area region after clamping, skipping"+ );+ return;+ }+ let divisor = if half { 2 } else { 1 };+ let dst_w = (width / divisor).max(1);+ let dst_h = (height / divisor).max(1);++ if let Some((old_tex, old_view)) = self.efb_copy_cache.remove(&dest_addr) {+ self.return_to_pool(old_tex, old_view);+ }+ self.bind_group_cache+ .retain(|key, _| !key.tex_keys.contains(&Some(dest_addr)));++ let (tex, view) = self+ .efb_depth_pool+ .get_mut(&(dst_w, dst_h))+ .and_then(Vec::pop)+ .unwrap_or_else(|| {+ let label = format!("efb_depth addr={dest_addr:#010x} size={dst_w}x{dst_h}");+ let tex = device.create_texture(&wgpu::TextureDescriptor {+ label: Some(&label),+ size: wgpu::Extent3d {+ width: dst_w,+ height: dst_h,+ depth_or_array_layers: 1,+ },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: wgpu::TextureFormat::R16Float,+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,+ view_formats: &[],+ });+ let view = tex.create_view(&Default::default());+ (tex, view)+ });++ let uniforms = XfbCopyUniforms {+ src_rect: [src_x as f32, src_y as f32, width as f32, height as f32],+ dst_size: [dst_w as f32, dst_h as f32],+ gamma: 1.0,+ filter_mode: 0,+ };+ queue.write_buffer(&self.efb_depth_resolve_uniform_buffer, 0, bytemuck::bytes_of(&uniforms));++ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("efb_depth_resolve_bg"),+ layout: &self.efb_depth_resolve_bg_layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: self.efb_depth_resolve_uniform_buffer.as_entire_binding(),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: wgpu::BindingResource::TextureView(&self.efb_depth_view),+ },+ ],+ });++ let group_label = format!(+ "CopyEfbDepthToTexture addr={dest_addr:#010x} src=({src_x},{src_y} {width}x{height}) dst={dst_w}x{dst_h}"+ );+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {+ label: Some("efb_depth_resolve_encoder"),+ });+ encoder.push_debug_group(&group_label);+ {+ let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some("efb_depth_resolve"),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: &view,+ resolve_target: None,+ ops: wgpu::Operations {+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),+ store: wgpu::StoreOp::Store,+ },+ depth_slice: None,+ })],+ depth_stencil_attachment: None,+ occlusion_query_set: None,+ timestamp_writes: None,+ multiview_mask: None,+ });+ rpass.set_pipeline(&self.efb_depth_resolve_pipeline);+ rpass.set_bind_group(0, &bind_group, &[]);+ rpass.draw(0..3, 0..1);+ }+ encoder.pop_debug_group();+ queue.submit([encoder.finish()]);++ self.efb_copy_cache.insert(dest_addr, (tex, view));+ }+pub(crate) fn execute_present_xfb(&mut self,device: &wgpu::Device,diff --git a/crates/backend-wgpu/src/shaders/efb_depth.wgsl b/crates/backend-wgpu/src/shaders/efb_depth.wgslnew file mode 100644index 0000000..942447e--- /dev/null+++ b/crates/backend-wgpu/src/shaders/efb_depth.wgsl@@ -0,0 +1,32 @@+struct Uniforms {+ src_rect: vec4<f32>,+ dst_size: vec2<f32>,+ gamma: f32,+ filter_mode: u32,+};++@group(0) @binding(0)+var<uniform> u: Uniforms;++@group(0) @binding(1)+var efb_depth: texture_depth_multisampled_2d;++struct VsOut {+ @builtin(position) position: vec4<f32>,+};++@vertex+fn vs_main(@builtin(vertex_index) vi: u32) -> VsOut {+ let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));+ var out: VsOut;+ out.position = vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);+ return out;+}++@fragment+fn fs_main(@builtin(position) position: vec4<f32>) -> @location(0) f32 {+ let dst_size = max(u.dst_size, vec2<f32>(1.0, 1.0));+ let src_pixel = u.src_rect.xy + (position.xy / dst_size) * u.src_rect.zw;+ let coord = vec2<i32>(src_pixel);+ return textureLoad(efb_depth, coord, 0);+}