A GameCube/Wii emulator and debugger written in Rust.
efb writeback performs better. is a must have feature now
Layleae442a761bde
diff --git a/crates/backend-wgpu/Cargo.toml b/crates/backend-wgpu/Cargo.tomlindex 4594f92..cfa6910 100644--- a/crates/backend-wgpu/Cargo.toml+++ b/crates/backend-wgpu/Cargo.toml@@ -4,7 +4,6 @@ version = "0.1.0"edition = "2024"[features]-efb-writeback = ["gecko/efb-writeback"]renderdoc-capture = ["dep:renderdoc"]hotpath = ["dep:hotpath", "hotpath/hotpath", "hotpath/crossbeam"]diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rsindex e1e4c4c..e4b4b89 100644--- a/crates/backend-wgpu/src/action.rs+++ b/crates/backend-wgpu/src/action.rs@@ -5,6 +5,7 @@ use crate::{SamplerKey, helpers,};use gecko::flipper::gx::regs::{MagFilter, MinFilter, WrapMode};+use gecko::flipper::gx::texture::CopyFormat;use gecko::host::{DrawData, GxAction};use glam::{Mat4, UVec4, Vec4};@@ -124,12 +125,13 @@ impl GxRenderer {rows_per_image: None,};- // A fresh RAM upload means the game wrote this address- // after a prior EFB copy. Return the stale GPU copy to- // its pool and let the RAM-decoded entry win. EFB copies- // are keyed by bare ram_addr (no TLUT variant).- if let Some((old_tex, old_view)) = self.efb_copy_cache.remove(&tid.ram_addr) {- self.return_to_pool(old_tex, old_view);+ let keep_cached = self.efb_copy_cache.get(&tid.ram_addr).is_some_and(|e| {+ e.format.base_texture_format() == *fmt+ && e.texture.size().width == *width+ && e.texture.size().height == *height+ });+ if !keep_cached && let Some(entry) = self.efb_copy_cache.remove(&tid.ram_addr) {+ self.return_to_pool(entry.texture, entry.view);}if let Some((cached_fmt, cached_tex, _)) = self.texture_cache.get_mut(&tid) {@@ -179,7 +181,7 @@ impl GxRenderer {self.flush_pending_draws(device, queue);self.submit_pending(queue);self.texture_cache.clear();- let drained: Vec<_> = self.efb_copy_cache.drain().map(|(_, v)| v).collect();+ let drained: Vec<_> = self.efb_copy_cache.drain().map(|(_, e)| (e.texture, e.view)).collect();for (tex, view) in drained {self.return_to_pool(tex, view);}@@ -354,6 +356,7 @@ impl GxRenderer {GxAction::PresentXfb { width, height, parts } => {self.flush_pending_draws(device, queue);self.execute_present_xfb(device, queue, *width, *height, parts);+ self.drain_pending_writebacks(device, queue);}GxAction::CopyEfbToTexture {@@ -362,9 +365,9 @@ impl GxRenderer {src_y,src_w,src_h,- copy_format: _copy_format,+ copy_format: raw_copy_format,mipmap,- stride: _stride,+ stride,clear,clear_color,clear_z,@@ -376,10 +379,10 @@ impl GxRenderer {} => {self.flush_pending_draws(device, queue);- // With `efb-writeback`: read the EFB back, encode it in- // `copy_format`, ship the bytes to the emu thread so they- // land in `Mmio::ram` at `dest_addr`. Expensive (GPU stall).- #[cfg(feature = "efb-writeback")]+ // Readback + per-format encode is queued onto+ // `pending_writebacks` for the next frame-boundary drain.+ // The bind path samples `efb_copy_cache` (populated below)+ // for same-frame correctness.self.execute_copy_efb_to_texture(device,queue,@@ -388,9 +391,9 @@ impl GxRenderer {*src_y,*src_w,*src_h,- *_copy_format,+ *raw_copy_format,*mipmap,- *_stride,+ *stride,*depth_copy,*clear,*clear_color,@@ -401,11 +404,10 @@ impl GxRenderer {*alpha_supported,);- // 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);+ if !*depth_copy && let Some(copy_fmt) = CopyFormat::from_u8_color(*raw_copy_format) {+ self.cache_efb_copy_color(+ device, queue, *dest_addr, *src_x, *src_y, *src_w, *src_h, *mipmap, copy_fmt,+ );}if *clear {@@ -482,7 +484,7 @@ impl GxRenderer {let view = self.efb_copy_cache.get(&tid.ram_addr)- .map(|(_, v)| v)+ .map(|e| &e.view).or_else(|| self.texture_cache.get(tid).map(|(_, _, v)| v));if let Some(view) = view {tex_views[slot] = view;diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rsindex 910af58..2f579f9 100644--- a/crates/backend-wgpu/src/lib.rs+++ b/crates/backend-wgpu/src/lib.rs@@ -16,9 +16,8 @@ use gecko::common::Address;use gecko::flipper::gx::draw::Primitive;use gecko::flipper::gx::draw::{Scissor, TextureFormat, Viewport};use gecko::flipper::gx::regs::{AlphaCompare, BlendMode, CompareFunc, CullMode, MagFilter, MinFilter, WrapMode, ZMode};-#[cfg(feature = "efb-writeback")]-use gecko::host::EfbWriteback;-use gecko::host::TextureKey;++use gecko::host::{EfbWriteback, TextureKey};use glam::Mat4;use pipeline::FullPipelineKey;use rustc_hash::FxHashMap;@@ -104,6 +103,12 @@ pub const EFB_WIDTH: u32 = 640;pub const EFB_HEIGHT: u32 = 528;pub const EFB_SAMPLE_COUNT: u32 = 4;+pub(crate) struct EfbCopyEntry {+ pub(crate) format: gecko::flipper::gx::texture::CopyFormat,+ pub(crate) texture: wgpu::Texture,+ pub(crate) view: wgpu::TextureView,+}+pub struct GxRenderer {pub(crate) pipeline_cache: FxHashMap<FullPipelineKey, wgpu::RenderPipeline>,pub(crate) shader_cache: FxHashMap<ShaderKey, wgpu::ShaderModule>,@@ -133,21 +138,13 @@ pub struct GxRenderer {pub(crate) texture_cache: FxHashMap<TextureKey, (TextureFormat, wgpu::Texture, wgpu::TextureView)>,// Retired LoadTexture allocations grouped by (w, h).pub(crate) texture_pool: FxHashMap<(u32, u32), Vec<wgpu::Texture>>,- // GPU textures holding EFB copy results, checked before `texture_cache` on every texture bind.- pub(crate) efb_copy_cache: FxHashMap<Address, (wgpu::Texture, wgpu::TextureView)>,- // Retired EFB-copy textures grouped by size, popped by the next copy to skip reallocating.+ pub(crate) efb_copy_cache: FxHashMap<Address, EfbCopyEntry>,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_pack_pipelines: render::EfbPackPipelines,pub(crate) efb_depth_resolve_bg_layout: wgpu::BindGroupLayout,pub(crate) efb_depth_resolve_uniform_buffer: wgpu::Buffer,- #[cfg(feature = "efb-writeback")]+pub(crate) efb_depth_writeback_pipeline: wgpu::RenderPipeline,- #[cfg(feature = "efb-writeback")]pub(crate) efb_depth_writeback_target: Option<(wgpu::Texture, wgpu::TextureView)>,pub(crate) fallback_view: wgpu::TextureView,pub(crate) scratch_vertices: Vec<GpuVertex>,@@ -203,18 +200,26 @@ pub struct GxRenderer {pub(crate) xfb_copy_uniform_write_pending: bool,pub(crate) efb_clear_uniform_write_pending: bool,pub(crate) efb_depth_resolve_uniform_write_pending: bool,- // EFB-to-texture readback. Only allocated with `efb-writeback`.- #[cfg(feature = "efb-writeback")]- pub(crate) efb_readback_staging: Option<wgpu::Buffer>,- #[cfg(feature = "efb-writeback")]- pub(crate) efb_readback_capacity: u64,- // Sender used to ship encoded EFB-to-texture bytes back to the emu- // thread. Installed by `sink::Renderer::new` via- // [`GxRenderer::set_efb_writeback_tx`].- #[cfg(feature = "efb-writeback")]+ pub(crate) efb_readback_staging_pool: FxHashMap<u64, Vec<wgpu::Buffer>>,+ pub(crate) pending_writebacks: Vec<PendingWriteback>,pub(crate) efb_writeback_tx: Option<crossbeam_channel::Sender<EfbWriteback>>,}+pub(crate) struct PendingWriteback {+ pub dest_addr: Address,+ pub staging: wgpu::Buffer,+ pub staging_capacity: u64,+ pub bytes_per_row: u64,+ pub staging_size: u64,+ pub width: u32,+ pub height: u32,+ pub copy_format: gecko::flipper::gx::texture::CopyFormat,+ pub stride: u32,+ pub swap_bgra: bool,+ pub box_filter_downsample: bool,+ pub label: &'static str,+}+impl GxRenderer {pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, surface_format: wgpu::TextureFormat) -> Self {let frame_uniform_size = FRAME_UNIFORMS_SIZE.get();@@ -232,6 +237,10 @@ impl GxRenderer {label: Some("efb_depth_shader"),source: wgpu::ShaderSource::Wgsl(include_str!("shaders/efb_depth.wgsl").into()),});+ let efb_pack_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("efb_pack_shader"),+ source: wgpu::ShaderSource::Wgsl(include_str!("shaders/efb_pack.wgsl").into()),+ });// Bindings: 0=FrameUniforms, 1=DrawUniforms, 2-9=textures 0-7, 10-17=samplers 0-7let mut layout_entries = vec![@@ -499,40 +508,6 @@ impl GxRenderer {cache: None,});- // Same shader and layout as xfb_copy, but writes `Rgba8Unorm` so the output matches `LoadTexture`.- let efb_copy_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {- label: Some("efb_copy_pipeline"),- layout: Some(&xfb_copy_pipeline_layout),- vertex: wgpu::VertexState {- module: &xfb_copy_shader,- entry_point: Some("vs_main"),- buffers: &[],- compilation_options: Default::default(),- },- fragment: Some(wgpu::FragmentState {- module: &xfb_copy_shader,- entry_point: Some("fs_main"),- targets: &[Some(wgpu::ColorTargetState {- format: wgpu::TextureFormat::Rgba8Unorm,- blend: None,- write_mask: wgpu::ColorWrites::ALL,- })],- 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 xfb_copy_sampler = device.create_sampler(&wgpu::SamplerDescriptor {label: Some("xfb_copy_sampler"),address_mode_u: wgpu::AddressMode::ClampToEdge,@@ -577,42 +552,10 @@ impl GxRenderer {],});let efb_depth_resolve_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {- label: Some("efb_depth_resolve_layout"),+ label: Some("efb_depth_pack_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,@@ -620,39 +563,61 @@ impl GxRenderer {mapped_at_creation: false,});- #[cfg(feature = "efb-writeback")]- let efb_depth_writeback_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {- label: Some("efb_depth_writeback_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_writeback_z24"),- targets: &[Some(wgpu::ColorTargetState {- format: wgpu::TextureFormat::Rgba8Unorm,- blend: None,- write_mask: wgpu::ColorWrites::ALL,- })],- 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 make_pack_pipeline =+ |label: &str, entry: &str, layout: &wgpu::PipelineLayout, shader: &wgpu::ShaderModule| {+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some(label),+ layout: Some(layout),+ vertex: wgpu::VertexState {+ module: shader,+ entry_point: Some("vs_main"),+ buffers: &[],+ compilation_options: Default::default(),+ },+ fragment: Some(wgpu::FragmentState {+ module: shader,+ entry_point: Some(entry),+ targets: &[Some(wgpu::ColorTargetState {+ format: wgpu::TextureFormat::Rgba8Unorm,+ blend: None,+ write_mask: wgpu::ColorWrites::ALL,+ })],+ 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 color_pack =+ |label: &str, entry: &str| make_pack_pipeline(label, entry, &xfb_copy_pipeline_layout, &efb_pack_shader);+ let efb_pack_pipelines = render::EfbPackPipelines {+ rgba8: color_pack("efb_pack_rgba8", "fs_rgba8"),+ i8: color_pack("efb_pack_i8", "fs_i8"),+ i4: color_pack("efb_pack_i4", "fs_i4"),+ ia8: color_pack("efb_pack_ia8", "fs_ia8"),+ ia4: color_pack("efb_pack_ia4", "fs_ia4"),+ rgb565: color_pack("efb_pack_rgb565", "fs_rgb565"),+ rgb5a3: color_pack("efb_pack_rgb5a3", "fs_rgb5a3"),+ a8: color_pack("efb_pack_a8", "fs_a8"),+ r8: color_pack("efb_pack_r8", "fs_r8"),+ rg8: color_pack("efb_pack_rg8", "fs_rg8"),+ };+ let efb_depth_writeback_pipeline = make_pack_pipeline(+ "efb_depth_writeback_pipeline",+ "fs_writeback_z24",+ &efb_depth_resolve_pipeline_layout,+ &efb_depth_shader,+ );let efb_clear = clear::EfbClear::new(device,@@ -707,9 +672,7 @@ impl GxRenderer {texture_pool: FxHashMap::default(),efb_copy_cache: FxHashMap::default(),efb_copy_pool: FxHashMap::default(),- efb_copy_pipeline,- efb_depth_pool: FxHashMap::default(),- efb_depth_resolve_pipeline,+ efb_pack_pipelines,efb_depth_resolve_bg_layout,efb_depth_resolve_uniform_buffer,fallback_view,@@ -755,22 +718,18 @@ impl GxRenderer {xfb_copy_uniform_write_pending: false,efb_clear_uniform_write_pending: false,efb_depth_resolve_uniform_write_pending: false,- #[cfg(feature = "efb-writeback")]- efb_readback_staging: None,- #[cfg(feature = "efb-writeback")]- efb_readback_capacity: 0,- #[cfg(feature = "efb-writeback")]++ efb_readback_staging_pool: FxHashMap::default(),+ pending_writebacks: Vec::new(),efb_writeback_tx: None,- #[cfg(feature = "efb-writeback")]+efb_depth_writeback_pipeline,- #[cfg(feature = "efb-writeback")]efb_depth_writeback_target: None,}}/// Install the sender used to ship encoded EFB-to-texture bytes back/// to the emulator thread. Called by `sink::Renderer` during setup.- #[cfg(feature = "efb-writeback")]pub fn set_efb_writeback_tx(&mut self, tx: crossbeam_channel::Sender<EfbWriteback>) {self.efb_writeback_tx = Some(tx);}diff --git a/crates/backend-wgpu/src/render.rs b/crates/backend-wgpu/src/render.rsindex 84f1954..dc58c90 100644--- a/crates/backend-wgpu/src/render.rs+++ b/crates/backend-wgpu/src/render.rs@@ -1,12 +1,7 @@-#[cfg(feature = "efb-writeback")]-use crate::align_up;-use crate::{GpuVertex, GxRenderer};+use crate::{GpuVertex, GxRenderer, PendingWriteback, align_up};use gecko::common::Address;-#[cfg(feature = "efb-writeback")]-use gecko::flipper::gx::texture;-#[cfg(feature = "efb-writeback")]-use gecko::host::EfbWriteback;-use gecko::host::XfbPart;+use gecko::flipper::gx::texture::{self, CopyFormat};+use gecko::host::{EfbWriteback, XfbPart};#[repr(C)]#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]@@ -17,6 +12,37 @@ pub(crate) struct XfbCopyUniforms {filter_mode: u32,}+pub(crate) struct EfbPackPipelines {+ pub(crate) rgba8: wgpu::RenderPipeline,+ pub(crate) i8: wgpu::RenderPipeline,+ pub(crate) i4: wgpu::RenderPipeline,+ pub(crate) ia8: wgpu::RenderPipeline,+ pub(crate) ia4: wgpu::RenderPipeline,+ pub(crate) rgb565: wgpu::RenderPipeline,+ pub(crate) rgb5a3: wgpu::RenderPipeline,+ pub(crate) a8: wgpu::RenderPipeline,+ pub(crate) r8: wgpu::RenderPipeline,+ pub(crate) rg8: wgpu::RenderPipeline,+}++impl EfbPackPipelines {+ pub(crate) fn for_color(&self, fmt: CopyFormat) -> Option<&wgpu::RenderPipeline> {+ Some(match fmt {+ CopyFormat::RGBA8 => &self.rgba8,+ CopyFormat::I8 => &self.i8,+ CopyFormat::I4 => &self.i4,+ CopyFormat::IA8 => &self.ia8,+ CopyFormat::IA4 => &self.ia4,+ CopyFormat::RGB565 => &self.rgb565,+ CopyFormat::RGB5A3 => &self.rgb5a3,+ CopyFormat::A8 => &self.a8,+ CopyFormat::R8 => &self.r8,+ CopyFormat::RG8 => &self.rg8,+ CopyFormat::Z24X8 => return None,+ })+ }+}+/// Upload `bytes` into `buffer` at offset 0 via `write_buffer_with`, which/// hands us a writable view into wgpu's staging memory and skips the extra/// copy `write_buffer` would do. No-op when `bytes` is empty.@@ -276,7 +302,7 @@ impl GxRenderer {}}- /// Blits the resolved EFB region into a GPU texture keyed by `dest_addr` for later texture binds to sample. Color only.+ #[allow(clippy::too_many_arguments)]pub(crate) fn cache_efb_copy_color(&mut self,device: &wgpu::Device,@@ -287,7 +313,13 @@ impl GxRenderer {src_w: u32,src_h: u32,half: bool,+ copy_format: CopyFormat,) {+ debug_assert!(+ self.efb_pack_pipelines.for_color(copy_format).is_some(),+ "cache_efb_copy_color called with depth-only copy format {copy_format:?}",+ );+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 {@@ -304,9 +336,8 @@ impl GxRenderer {let dst_w = (width / divisor).max(1);let dst_h = (height / divisor).max(1);- // 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) {- self.return_to_pool(old_tex, old_view);+ if let Some(entry) = self.efb_copy_cache.remove(&dest_addr) {+ self.return_to_pool(entry.texture, entry.view);}self.bind_group_cache.retain(|key, _| !key.tex_keys.iter().any(|k| k.map(|t| t.ram_addr) == Some(dest_addr)));@@ -316,7 +347,7 @@ impl GxRenderer {.get_mut(&(dst_w, dst_h)).and_then(Vec::pop).unwrap_or_else(|| {- let label = format!("efb_copy addr={dest_addr:#010x} size={dst_w}x{dst_h}");+ let label = format!("efb_copy addr={dest_addr:#010x} size={dst_w}x{dst_h} fmt={copy_format:?}");let tex = device.create_texture(&wgpu::TextureDescriptor {label: Some(&label),size: wgpu::Extent3d {@@ -350,7 +381,7 @@ impl GxRenderer {queue.write_buffer(&self.xfb_copy_uniform_buffer, 0, bytemuck::bytes_of(&uniforms));let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {- label: Some("efb_copy_bg"),+ label: Some("efb_pack_bg"),layout: &self.xfb_copy_bind_group_layout,entries: &[wgpu::BindGroupEntry {@@ -369,15 +400,15 @@ impl GxRenderer {});let group_label = format!(- "CopyEfbToTexture addr={dest_addr:#010x} src=({src_x},{src_y} {width}x{height}) dst={dst_w}x{dst_h}"+ "CopyEfbToTexture addr={dest_addr:#010x} src=({src_x},{src_y} {width}x{height}) dst={dst_w}x{dst_h} fmt={copy_format:?}");let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {- label: Some("efb_copy_encoder"),+ label: Some("efb_pack_encoder"),});encoder.push_debug_group(&group_label);{let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {- label: Some("efb_copy"),+ label: Some("efb_pack"),color_attachments: &[Some(wgpu::RenderPassColorAttachment {view: &view,resolve_target: None,@@ -392,25 +423,32 @@ impl GxRenderer {timestamp_writes: None,multiview_mask: None,});- rpass.set_pipeline(&self.efb_copy_pipeline);+ rpass.set_pipeline(self.efb_pack_pipelines.for_color(copy_format).unwrap());rpass.set_bind_group(0, &bind_group, &[]);- rpass.insert_debug_marker("EFB copy: resolved color to texture cache");+ rpass.insert_debug_marker("EFB copy: per-format pack into cache");rpass.draw(0..3, 0..1);}encoder.pop_debug_group();self.pending_command_buffers.push(encoder.finish());self.xfb_copy_uniform_write_pending = true;- self.efb_copy_cache.insert(dest_addr, (tex, view));+ self.efb_copy_cache.insert(+ dest_addr,+ crate::EfbCopyEntry {+ format: copy_format,+ texture: 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) {+ const PER_BUCKET_CAP: usize = 8;+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)),+ let bucket = self.efb_copy_pool.entry((size.width, size.height)).or_default();+ if bucket.len() < PER_BUCKET_CAP {+ bucket.push((tex, view));}}@@ -432,127 +470,6 @@ impl GxRenderer {}}- /// 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.iter().any(|k| k.map(|t| t.ram_addr) == 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)- });-- if self.efb_depth_resolve_uniform_write_pending {- self.submit_pending(queue);- }-- 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.insert_debug_marker("EFB copy: resolve depth to texture cache");- rpass.draw(0..3, 0..1);- }- encoder.pop_debug_group();- self.pending_command_buffers.push(encoder.finish());- self.efb_depth_resolve_uniform_write_pending = true;-- self.efb_copy_cache.insert(dest_addr, (tex, view));- }-pub(crate) fn execute_present_xfb(&mut self,device: &wgpu::Device,@@ -651,17 +568,9 @@ impl GxRenderer {self.xfb_has_content = true;}- /// EFB-to-texture copy: read a region of the resolved EFB back into a- /// staging buffer, convert from the wgpu surface format to RGBA8,- /// optional 2x downsample, encode into the requested GX texture format,- /// and ship the bytes back to the emu thread via the writeback channel.- ///- /// The clear flag and per-channel update masks are applied after the- /// copy, matching GX copy-clear ordering.- ///- /// Only compiled with `efb-writeback`. The default no-feature path- /// handles CopyEfbToTexture inline in `action.rs` with just a clear.- #[cfg(feature = "efb-writeback")]+ /// Queue an EFB region readback into `pending_writebacks`. The actual+ /// map+encode+ship happens at the next frame boundary via+ /// `drain_pending_writebacks`.pub(crate) fn execute_copy_efb_to_texture(&mut self,device: &wgpu::Device,@@ -762,20 +671,8 @@ impl GxRenderer {// wgpu requires 256-byte row alignment for texture<->buffer copies.let bytes_per_row = align_up(width as u64 * 4, 256);let staging_size = bytes_per_row * height as u64;+ let (staging, staging_capacity) = self.acquire_readback_staging(device, staging_size);- // Grow staging buffer on demand.- if self.efb_readback_staging.is_none() || self.efb_readback_capacity < staging_size {- let new_cap = staging_size.next_power_of_two().max(4096);- self.efb_readback_staging = Some(device.create_buffer(&wgpu::BufferDescriptor {- label: Some("efb_readback_staging"),- size: new_cap,- usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,- mapped_at_creation: false,- }));- self.efb_readback_capacity = new_cap;- }-- // Submit the EFB -> staging copy.let group_label = format!("CopyEfbToTexture addr={dest_addr:#010x} src=({src_x},{src_y} {width}x{height}) fmt={copy_format_enum:?} mip={mipmap} stride={stride} depth={depth_copy}");@@ -783,11 +680,6 @@ impl GxRenderer {label: Some("efb_to_texture_copy_encoder"),});encoder.push_debug_group(&group_label);- let copy_marker = format!(- "EFB readback copy: bytes_per_row={} staging_size={}",- bytes_per_row, staging_size- );- encoder.insert_debug_marker(©_marker);encoder.copy_texture_to_buffer(wgpu::TexelCopyTextureInfo {texture: &self.efb_texture,@@ -800,7 +692,7 @@ impl GxRenderer {aspect: wgpu::TextureAspect::default(),},wgpu::TexelCopyBufferInfo {- buffer: self.efb_readback_staging.as_ref().unwrap(),+ buffer: &staging,layout: wgpu::TexelCopyBufferLayout {offset: 0,bytes_per_row: Some(bytes_per_row as u32),@@ -816,24 +708,24 @@ impl GxRenderer {encoder.pop_debug_group();self.pending_command_buffers.push(encoder.finish());- let swap = matches!(+ let swap_bgra = matches!(self.surface_format,wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb);- self.map_encode_and_ship(- device,- queue,- width,- height,+ self.pending_writebacks.push(PendingWriteback {+ dest_addr,+ staging,+ staging_capacity,bytes_per_row,staging_size,- swap,- mipmap,- copy_format_enum,- dest_addr,+ width,+ height,+ copy_format: copy_format_enum,stride,- "efb_to_texture",- );+ swap_bgra,+ box_filter_downsample: mipmap,+ label: "efb_to_texture",+ });if clear {self.clear_efb_region(@@ -852,7 +744,6 @@ impl GxRenderer {}}- #[cfg(feature = "efb-writeback")]fn execute_depth_writeback(&mut self,device: &wgpu::Device,@@ -924,24 +815,15 @@ impl GxRenderer {],});- let (target_tex, target_view) = self.efb_depth_writeback_target.as_ref().unwrap();let group_label = format!("DepthWriteback addr={dest_addr:#010x} src=({src_x},{src_y} {width}x{height}) dst={encode_w}x{encode_h} stride={stride}");let bytes_per_row = align_up(encode_w as u64 * 4, 256);let staging_size = bytes_per_row * encode_h as u64;+ let (staging, staging_capacity) = self.acquire_readback_staging(device, staging_size);- if self.efb_readback_staging.is_none() || self.efb_readback_capacity < staging_size {- let new_cap = staging_size.next_power_of_two().max(4096);- self.efb_readback_staging = Some(device.create_buffer(&wgpu::BufferDescriptor {- label: Some("efb_readback_staging"),- size: new_cap,- usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,- mapped_at_creation: false,- }));- self.efb_readback_capacity = new_cap;- }+ let (target_tex, target_view) = self.efb_depth_writeback_target.as_ref().unwrap();let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {label: Some("efb_depth_writeback_encoder"),@@ -979,7 +861,7 @@ impl GxRenderer {aspect: wgpu::TextureAspect::default(),},wgpu::TexelCopyBufferInfo {- buffer: self.efb_readback_staging.as_ref().unwrap(),+ buffer: &staging,layout: wgpu::TexelCopyBufferLayout {offset: 0,bytes_per_row: Some(bytes_per_row as u32),@@ -995,96 +877,132 @@ impl GxRenderer {encoder.pop_debug_group();self.pending_command_buffers.push(encoder.finish());self.efb_depth_resolve_uniform_write_pending = false;+ let _ = queue;- self.map_encode_and_ship(- device,- queue,- encode_w,- encode_h,+ self.pending_writebacks.push(PendingWriteback {+ dest_addr,+ staging,+ staging_capacity,bytes_per_row,staging_size,- false,- false,- copy_format_enum,- dest_addr,+ width: encode_w,+ height: encode_h,+ copy_format: copy_format_enum,stride,- "efb_depth_writeback",- );+ swap_bgra: false,+ box_filter_downsample: false,+ label: "efb_depth_writeback",+ });}- #[cfg(feature = "efb-writeback")]- #[allow(clippy::too_many_arguments)]- fn map_encode_and_ship(- &mut self,- device: &wgpu::Device,- queue: &wgpu::Queue,- width: u32,- height: u32,- bytes_per_row: u64,- staging_size: u64,- swap_bgra: bool,- box_filter_downsample: bool,- copy_format: texture::CopyFormat,- dest_addr: Address,- stride: u32,- label: &'static str,- ) {+ pub(crate) fn acquire_readback_staging(&mut self, device: &wgpu::Device, staging_size: u64) -> (wgpu::Buffer, u64) {+ let capacity = staging_size.next_power_of_two().max(4096);+ if let Some(bucket) = self.efb_readback_staging_pool.get_mut(&capacity) {+ if let Some(buf) = bucket.pop() {+ return (buf, capacity);+ }+ }++ let buf = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("efb_readback_staging"),+ size: capacity,+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,+ mapped_at_creation: false,+ });++ (buf, capacity)+ }++ pub(crate) fn return_readback_staging(&mut self, buf: wgpu::Buffer, capacity: u64) {+ const MAX_PER_BUCKET: usize = 8;+ let bucket = self.efb_readback_staging_pool.entry(capacity).or_default();+ if bucket.len() < MAX_PER_BUCKET {+ bucket.push(buf);+ }+ }++ pub(crate) fn drain_pending_writebacks(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {+ if self.pending_writebacks.is_empty() {+ return;+ }+self.submit_pending(queue);- let staging = self.efb_readback_staging.as_ref().unwrap();- let slice = staging.slice(..staging_size);- slice.map_async(wgpu::MapMode::Read, |_| {});+ for pending in &self.pending_writebacks {+ pending+ .staging+ .slice(..pending.staging_size)+ .map_async(wgpu::MapMode::Read, |_| {});+ }+if let Err(err) = device.poll(wgpu::PollType::Wait {submission_index: None,timeout: Some(std::time::Duration::from_secs(5)),}) {- tracing::warn!(?err, label, "device poll failed");+ tracing::warn!(?err, "efb writeback drain: device poll failed");+ // Best-effort: drop the buffers back into the pool so we don't leak.+ let pending: Vec<PendingWriteback> = self.pending_writebacks.drain(..).collect();+ for w in pending {+ self.return_readback_staging(w.staging, w.staging_capacity);+ }return;}- let mut rgba = vec![0u8; (width * height * 4) as usize];- {- let mapped = slice.get_mapped_range();- let row_bytes = (width * 4) as usize;- let src_row_bytes = bytes_per_row as usize;- for y in 0..height as usize {- let src_row = &mapped[y * src_row_bytes..y * src_row_bytes + row_bytes];- let dst_row = &mut rgba[y * row_bytes..y * row_bytes + row_bytes];- if swap_bgra {- for i in 0..width as usize {- dst_row[i * 4] = src_row[i * 4 + 2];- dst_row[i * 4 + 1] = src_row[i * 4 + 1];- dst_row[i * 4 + 2] = src_row[i * 4];- dst_row[i * 4 + 3] = src_row[i * 4 + 3];+ let pending: Vec<PendingWriteback> = self.pending_writebacks.drain(..).collect();+ for w in pending {+ let mut rgba = vec![0u8; (w.width * w.height * 4) as usize];+ {+ let slice = w.staging.slice(..w.staging_size);+ let mapped = slice.get_mapped_range();+ let row_bytes = (w.width * 4) as usize;+ let src_row_bytes = w.bytes_per_row as usize;++ for y in 0..w.height as usize {+ let src_row = &mapped[y * src_row_bytes..y * src_row_bytes + row_bytes];+ let dst_row = &mut rgba[y * row_bytes..y * row_bytes + row_bytes];++ if w.swap_bgra {+ for i in 0..w.width as usize {+ dst_row[i * 4] = src_row[i * 4 + 2];+ dst_row[i * 4 + 1] = src_row[i * 4 + 1];+ dst_row[i * 4 + 2] = src_row[i * 4];+ dst_row[i * 4 + 3] = src_row[i * 4 + 3];+ }+ } else {+ dst_row.copy_from_slice(src_row);}- } else {- dst_row.copy_from_slice(src_row);}}- }- staging.unmap();-- let (encode_w, encode_h, encode_src) = if box_filter_downsample {- (width / 2, height / 2, texture::downsample_box_2x(&rgba, width, height))- } else {- (width, height, rgba)- };-- let encoded = texture::encode_from_rgba(&encode_src, encode_w as usize, encode_h as usize, copy_format);- let row_bytes = texture::encoded_row_bytes(encode_w, copy_format);- let row_count = texture::encoded_row_count(encode_h, copy_format);- let dest_stride_bytes = stride as usize;+ w.staging.unmap();++ let (encode_w, encode_h, encode_src) = if w.box_filter_downsample {+ (+ w.width / 2,+ w.height / 2,+ texture::downsample_box_2x(&rgba, w.width, w.height),+ )+ } else {+ (w.width, w.height, rgba)+ };- if let Some(tx) = &self.efb_writeback_tx {- if let Err(err) = tx.try_send(EfbWriteback {- dest_addr,- bytes: encoded,- row_bytes,- row_count,- dest_stride_bytes,- }) {- tracing::warn!(?err, label, "writeback channel send failed");+ let encoded = texture::encode_from_rgba(&encode_src, encode_w as usize, encode_h as usize, w.copy_format);+ let row_bytes = texture::encoded_row_bytes(encode_w, w.copy_format);+ let row_count = texture::encoded_row_count(encode_h, w.copy_format);+ let dest_stride_bytes = w.stride as usize;++ if let Some(tx) = &self.efb_writeback_tx {+ if let Err(err) = tx.try_send(EfbWriteback {+ dest_addr: w.dest_addr,+ bytes: encoded,+ row_bytes,+ row_count,+ dest_stride_bytes,+ }) {+ tracing::warn!(?err, label = w.label, "writeback channel send failed");+ }}++ self.return_readback_staging(w.staging, w.staging_capacity);}}diff --git a/crates/backend-wgpu/src/shader_specialization.rs b/crates/backend-wgpu/src/shader_specialization.rsindex de0198b..5b50dc2 100644--- a/crates/backend-wgpu/src/shader_specialization.rs+++ b/crates/backend-wgpu/src/shader_specialization.rs@@ -15,7 +15,7 @@ const MAIN_WESL: &str = include_str!("shaders/main.wesl");pub(crate) const KEY_BYTES: usize = 5;const CACHE_MAGIC: [u8; 4] = *b"GSKC";-pub(crate) const CACHE_VERSION: u32 = 3;+pub(crate) const CACHE_VERSION: u32 = 5;pub(crate) const SHADER_CACHE_PATH: &str = "cache/shader_keys.bin";#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]diff --git a/crates/backend-wgpu/src/shaders/efb_depth.wgsl b/crates/backend-wgpu/src/shaders/efb_depth.wgslindex b63aac4..18c0f6b 100644--- a/crates/backend-wgpu/src/shaders/efb_depth.wgsl+++ b/crates/backend-wgpu/src/shaders/efb_depth.wgsl@@ -45,3 +45,4 @@ fn fs_writeback_z24(@builtin(position) position: vec4<f32>) -> @location(0) vec4let b = f32( z24 & 0xFFu) / 255.0;return vec4<f32>(r, g, b, 1.0);}+diff --git a/crates/backend-wgpu/src/shaders/efb_pack.wgsl b/crates/backend-wgpu/src/shaders/efb_pack.wgslnew file mode 100644index 0000000..e70aea2--- /dev/null+++ b/crates/backend-wgpu/src/shaders/efb_pack.wgsl@@ -0,0 +1,153 @@+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_color: texture_2d<f32>;+@group(0) @binding(2) var efb_color_sampler: sampler;++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;+}++fn fetch(pos: vec2<f32>) -> vec4<f32> {+ let dst_size = max(u.dst_size, vec2<f32>(1.0, 1.0));+ let src_pixel = u.src_rect.xy + (pos / dst_size) * u.src_rect.zw;+ let coord = vec2<i32>(src_pixel);+ return textureLoad(efb_color, coord, 0);+}++@fragment+fn fs_rgba8(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> {+ return fetch(p.xy);+}++@fragment+fn fs_i8(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> {+ let s = fetch(p.xy);+ let r = u32(round(s.r * 255.0));+ let g = u32(round(s.g * 255.0));+ let b = u32(round(s.b * 255.0));+ let y = (299u * r + 587u * g + 114u * b) / 1000u;+ let yf = f32(min(y, 255u)) / 255.0;+ return vec4<f32>(yf, yf, yf, yf);+}++@fragment+fn fs_i4(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> {+ let s = fetch(p.xy);+ let r = u32(round(s.r * 255.0));+ let g = u32(round(s.g * 255.0));+ let b = u32(round(s.b * 255.0));+ let y = (299u * r + 587u * g + 114u * b) / 1000u;+ let q = (min(y, 255u) >> 4u) & 0xFu;+ let v = (q << 4u) | q;+ let vf = f32(v) / 255.0;+ return vec4<f32>(vf, vf, vf, vf);+}++@fragment+fn fs_ia8(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> {+ let s = fetch(p.xy);+ let r = u32(round(s.r * 255.0));+ let g = u32(round(s.g * 255.0));+ let b = u32(round(s.b * 255.0));+ let y = (299u * r + 587u * g + 114u * b) / 1000u;+ let yf = f32(min(y, 255u)) / 255.0;+ return vec4<f32>(yf, yf, yf, s.a);+}++@fragment+fn fs_ia4(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> {+ let s = fetch(p.xy);+ let r = u32(round(s.r * 255.0));+ let g = u32(round(s.g * 255.0));+ let b = u32(round(s.b * 255.0));+ let a = u32(round(s.a * 255.0));+ let y = (299u * r + 587u * g + 114u * b) / 1000u;+ let iq = (min(y, 255u) >> 4u) & 0xFu;+ let aq = (a >> 4u) & 0xFu;+ let iv = (iq << 4u) | iq;+ let av = (aq << 4u) | aq;+ let ivf = f32(iv) / 255.0;+ let avf = f32(av) / 255.0;+ return vec4<f32>(ivf, ivf, ivf, avf);+}++@fragment+fn fs_rgb565(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> {+ let s = fetch(p.xy);++ let r5 = (u32(round(s.r * 255.0)) >> 3u) & 0x1Fu;+ let g6 = (u32(round(s.g * 255.0)) >> 2u) & 0x3Fu;+ let b5 = (u32(round(s.b * 255.0)) >> 3u) & 0x1Fu;++ let r8 = (r5 << 3u) | (r5 >> 2u);+ let g8 = (g6 << 2u) | (g6 >> 4u);+ let b8 = (b5 << 3u) | (b5 >> 2u);++ return vec4<f32>(f32(r8) / 255.0, f32(g8) / 255.0, f32(b8) / 255.0, 1.0);+}++@fragment+fn fs_rgb5a3(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> {+ let s = fetch(p.xy);++ let r = u32(round(s.r * 255.0));+ let g = u32(round(s.g * 255.0));+ let b = u32(round(s.b * 255.0));+ let a = u32(round(s.a * 255.0));++ if (a == 255u) {+ let r5 = (r >> 3u) & 0x1Fu;+ let g5 = (g >> 3u) & 0x1Fu;+ let b5 = (b >> 3u) & 0x1Fu;++ let r8 = (r5 << 3u) | (r5 >> 2u);+ let g8 = (g5 << 3u) | (g5 >> 2u);+ let b8 = (b5 << 3u) | (b5 >> 2u);++ return vec4<f32>(f32(r8) / 255.0, f32(g8) / 255.0, f32(b8) / 255.0, 1.0);+ } else {+ let r4 = (r >> 4u) & 0xFu;+ let g4 = (g >> 4u) & 0xFu;+ let b4 = (b >> 4u) & 0xFu;+ let a3 = (a >> 5u) & 0x7u;++ let r8 = (r4 << 4u) | r4;+ let g8 = (g4 << 4u) | g4;+ let b8 = (b4 << 4u) | b4;+ let a8 = (a3 << 5u) | (a3 << 2u) | (a3 >> 1u);++ return vec4<f32>(f32(r8) / 255.0, f32(g8) / 255.0, f32(b8) / 255.0, f32(a8) / 255.0);+ }+}++@fragment+fn fs_a8(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> {+ let a = fetch(p.xy).a;+ return vec4<f32>(a, a, a, a);+}++@fragment+fn fs_r8(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> {+ let r = fetch(p.xy).r;+ return vec4<f32>(r, r, r, r);+}++@fragment+fn fs_rg8(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> {+ let s = fetch(p.xy);+ return vec4<f32>(s.g, s.g, s.g, s.r);+}diff --git a/crates/backend-wgpu/src/sink.rs b/crates/backend-wgpu/src/sink.rsindex 89c53c6..7faeff3 100644--- a/crates/backend-wgpu/src/sink.rs+++ b/crates/backend-wgpu/src/sink.rs@@ -14,9 +14,7 @@ macro_rules! instrument_channel {};}-#[cfg(feature = "efb-writeback")]-use gecko::host::EfbWriteback;-use gecko::host::{DrawData, GxAction, RenderSink};+use gecko::host::{DrawData, EfbWriteback, GxAction, RenderSink};use std::sync::atomic::{AtomicU64, Ordering};use std::sync::{Arc, Mutex, OnceLock};#[cfg(feature = "renderdoc-capture")]@@ -181,9 +179,7 @@ pub struct Renderer {/// Receiver end of the EFB-to-texture writeback channel. Taken by the/// emulator setup code (via [`Renderer::take_writeback_rx`]) and/// installed into `GraphicsProcessor::efb_writeback_rx`. Wrapped in- /// `Arc<Mutex<Option<_>>>` so `Renderer` stays `Clone`. Only built when- /// `efb-writeback` is enabled.- #[cfg(feature = "efb-writeback")]+ /// `Arc<Mutex<Option<_>>>` so `Renderer` stays `Clone`.writeback_rx: Arc<Mutex<Option<Receiver<EfbWriteback>>>>,recycle_rx: Arc<Mutex<Option<Receiver<Box<DrawData>>>>>,batch_recycle_rx: Arc<Mutex<Option<Receiver<Vec<GxAction>>>>>,@@ -203,8 +199,6 @@ impl Renderer {// Writeback channel: GxRenderer sends encoded EFB-to-texture bytes,// GraphicsProcessor consumes them synchronously on the emu thread.- // Only created with `efb-writeback`.- #[cfg(feature = "efb-writeback")]let writeback_rx = {let (writeback_tx, writeback_rx) =instrument_channel!(bounded::<EfbWriteback>(CHANNEL_CAPACITY), "efb_writeback");@@ -314,7 +308,6 @@ impl Renderer {target_aspect,actions_sent: Arc::new(AtomicU64::new(0)),frame_ready_cb,- #[cfg(feature = "efb-writeback")]writeback_rx: Arc::new(Mutex::new(Some(writeback_rx))),recycle_rx: Arc::new(Mutex::new(Some(recycle_rx))),batch_recycle_rx: Arc::new(Mutex::new(Some(batch_recycle_rx))),@@ -332,9 +325,7 @@ impl Renderer {/// Take the writeback receiver once. Returns `Some` on the first call,/// `None` thereafter. The caller installs it into- /// `GraphicsProcessor::efb_writeback_rx`. Only available when the- /// `efb-writeback` feature is enabled.- #[cfg(feature = "efb-writeback")]+ /// `GraphicsProcessor::efb_writeback_rx`.pub fn take_writeback_rx(&self) -> Option<Receiver<EfbWriteback>> {self.writeback_rx.lock().ok()?.take()}diff --git a/crates/debugger/Cargo.toml b/crates/debugger/Cargo.tomlindex 86a4666..51b59f8 100644--- a/crates/debugger/Cargo.toml+++ b/crates/debugger/Cargo.toml@@ -5,7 +5,6 @@ edition = "2024"[features]scripting-mut-traps = ["gecko/hooks-mut-traps", "scripting/hooks-mut-traps"]-efb-writeback = ["backend-wgpu/efb-writeback"]renderdoc-capture = ["backend-wgpu/renderdoc-capture"][dependencies]diff --git a/crates/debugger/src/main.rs b/crates/debugger/src/main.rsindex 58f3b27..f410d00 100644--- a/crates/debugger/src/main.rs+++ b/crates/debugger/src/main.rs@@ -57,7 +57,6 @@ impl EmulatorVariant {}}- #[cfg(feature = "efb-writeback")]fn install_efb_writeback(&mut self, rx: Option<crossbeam_channel::Receiver<gecko::host::EfbWriteback>>) {match self {Self::Gc(e) => e.gx.efb_writeback_rx = rx,@@ -526,10 +525,7 @@ fn main() {emulator.install_recycle_rx(renderer.take_recycle_rx());emulator.install_render_sink(Box::new(renderer.take_batching_sink()));- #[cfg(feature = "efb-writeback")]- {- emulator.install_efb_writeback(renderer.take_writeback_rx());- }+ emulator.install_efb_writeback(renderer.take_writeback_rx());let ui = DebuggerUi {symbols,diff --git a/crates/gecko/Cargo.toml b/crates/gecko/Cargo.tomlindex 58c0bac..fe18f5a 100644--- a/crates/gecko/Cargo.toml+++ b/crates/gecko/Cargo.toml@@ -8,11 +8,6 @@ default = ["jit", "idle-skip"]idle-skip = []hooks = []hooks-mut-traps = ["hooks"]-# Full EFB-to-texture writeback: the renderer reads the EFB back, encodes-# it in the GX copy format, and ships the bytes over a channel to the emu-# thread which copies them into `Mmio::ram` synchronously. Expensive (GPU-# stall, encode, RAM copy).-efb-writeback = []# Enable the WAV file audio sinkaudio-wav-dump = ["dep:hound"]# Cranelift JIT for Gekkodiff --git a/crates/gecko/src/flipper/dsp/jit.rs b/crates/gecko/src/flipper/dsp/jit.rsindex 5b35d38..02e02d7 100644--- a/crates/gecko/src/flipper/dsp/jit.rs+++ b/crates/gecko/src/flipper/dsp/jit.rs@@ -461,7 +461,11 @@ impl<const SYSTEM: SystemId> JitEngine<SYSTEM> {continue;}- tracing::info!(pc = format!("{:04X}", b.pc), count = b.instr_count, "compiling DSP JIT block from cache");+ tracing::info!(+ pc = format!("{:04X}", b.pc),+ count = b.instr_count,+ "compiling DSP JIT block from cache"+ );self.lookup_or_compile(iram, irom, b.pc);compiled += 1;diff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rsindex 9a351c4..895a3f7 100644--- a/crates/gecko/src/flipper/gx.rs+++ b/crates/gecko/src/flipper/gx.rs@@ -17,9 +17,7 @@ use crate::flipper::gx::draw::Matrix4;use crate::flipper::gx::regs::{AlphaCompare, BlendMode, ChanCtrl, TevAlphaEnv, TevColorEnv, TevRegisterH, TevRegisterL, ZMode,};-#[cfg(feature = "efb-writeback")]-use crate::host::EfbWriteback;-use crate::host::{DrawData, DrawVertex, GxAction, LightData, TextureKey, XfbPart};+use crate::host::{DrawData, DrawVertex, EfbWriteback, GxAction, LightData, TextureKey, XfbPart};use crate::system::{System, SystemId};use rustc_hash::FxHashMap;@@ -98,11 +96,7 @@ pub struct GraphicsProcessor {// [`GxAction::LoadTexture`].pub texture_hashes: FxHashMap<TextureKey, u64>,// Receiver for encoded EFB-to-texture bytes coming back from the- // renderer worker. `efb_copy` drains this synchronously right after- // emitting the copy action, so the next FIFO command in the same burst- // (usually a `TX_SETIMAGE3` that samples the just-written region)- // sees fresh RAM. Only present when the `efb-writeback` feature is on.- #[cfg(feature = "efb-writeback")]+ // renderer worker.pub efb_writeback_rx: Option<crossbeam_channel::Receiver<EfbWriteback>>,pub draw_box_pool: Vec<Box<DrawData>>,pub draw_box_recycle_rx: Option<crossbeam_channel::Receiver<Box<DrawData>>>,@@ -188,7 +182,6 @@ impl GraphicsProcessor {#[cfg(feature = "gx-stats")]stats: GxStats::default(),texture_hashes: FxHashMap::default(),- #[cfg(feature = "efb-writeback")]efb_writeback_rx: None,draw_box_pool: {const POOL_PREALLOC: usize = 1024;diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rsindex f6add75..e110698 100644--- a/crates/gecko/src/flipper/gx/bp.rs+++ b/crates/gecko/src/flipper/gx/bp.rs@@ -3,8 +3,6 @@ use super::regs::*;use super::{GraphicsProcessor, draw, texture};use crate::host::{GxAction, RenderSink, TextureKey};use crate::mmio::{RamView, RamViewMut};-#[cfg(feature = "efb-writeback")]-use std::time::Duration;impl GraphicsProcessor {#[cfg_attr(feature = "hotpath", hotpath::measure)]@@ -188,12 +186,14 @@ impl GraphicsProcessor {// PE finishif idx == BP_PE_DONE && (val & BP_PE_DONE_FINISH_BIT) != 0 {self.raise_interrupt = true;+ self.drain_efb_writebacks(ram);}// PE token (0x47): store token value onlyif idx == BP_PE_TOKEN {self.pending_token = (val & 0xFFFF) as u16;self.token_dirty = true;+ self.drain_efb_writebacks(ram);}// PE token interrupt (0x48): store token value + raise interrupt@@ -202,6 +202,7 @@ impl GraphicsProcessor {self.pending_token = (val & 0xFFFF) as u16;self.token_dirty = true;self.raise_token_interrupt = true;+ self.drain_efb_writebacks(ram);}// Scissor registers (BP 0x20 = TL, 0x21 = BR, 0x59 = OFFSET).@@ -529,35 +530,30 @@ impl GraphicsProcessor {depth_copy: self.cur_pe_control.pixel_format().is_depth_only(),});- // Writeback overwrites RAM, so drop every cached hash that- // points at this ram_addr (any TLUT variant) to force a redecode.- #[cfg(feature = "efb-writeback")]+ // Drop cached hashes for this ram_addr (any TLUT variant) so the+ // next snapshot at this address re decodes once the deferred+ // RAM writeback lands.self.texture_hashes.retain(|k, _| k.ram_addr != dest_addr);- let _ = ram;-- // With `efb-writeback`: block until the renderer finishes the- // readback + encode and ships the encoded bytes back. This- // preserves ordering with subsequent FIFO commands (a- // `TX_SETIMAGE3` at `dest_addr` immediately after this copy- // sees up-to-date RAM + a freshly re-hashable texture).- #[cfg(feature = "efb-writeback")]- if let Some(rx) = &self.efb_writeback_rx {- match rx.recv_timeout(Duration::from_secs(2)) {- Ok(wb) => {- texture::write_strided_copy_to_ram(- ram,- wb.dest_addr,- &wb.bytes,- wb.row_bytes,- wb.row_count,- wb.dest_stride_bytes,- );- }- Err(err) => {- tracing::warn!(?err, "efb writeback recv timed out");- }- }- }++ self.drain_efb_writebacks(ram);+ }+ }++ #[cfg_attr(feature = "hotpath", hotpath::measure)]+ pub fn drain_efb_writebacks(&mut self, ram: &mut RamViewMut<'_>) {+ let Some(rx) = self.efb_writeback_rx.as_ref() else {+ return;+ };++ while let Ok(wb) = rx.try_recv() {+ texture::write_strided_copy_to_ram(+ ram,+ wb.dest_addr,+ &wb.bytes,+ wb.row_bytes,+ wb.row_count,+ wb.dest_stride_bytes,+ );}}diff --git a/crates/gecko/src/gekko/jit.rs b/crates/gecko/src/gekko/jit.rsindex 44ae81d..92e31a4 100644--- a/crates/gecko/src/gekko/jit.rs+++ b/crates/gecko/src/gekko/jit.rs@@ -552,7 +552,11 @@ impl<const SYSTEM: SystemId> JitEngine<SYSTEM> {continue;}- tracing::info!(pc = format!("{:08X}", b.pc), count = b.instr_count, "compiling PPC JIT block from cache");+ tracing::info!(+ pc = format!("{:08X}", b.pc),+ count = b.instr_count,+ "compiling PPC JIT block from cache"+ );self.lookup_or_compile(sys, b.pc);compiled += 1;diff --git a/crates/gecko/src/host.rs b/crates/gecko/src/host.rsindex 81cb156..ad8a7ac 100644--- a/crates/gecko/src/host.rs+++ b/crates/gecko/src/host.rs@@ -138,13 +138,9 @@ pub enum GxAction {},}-/// Payload sent from the renderer worker back to the emulator thread after-/// an EFB-to-texture copy completes. The emu thread copies `bytes` into-/// `Mmio::ram` at `dest_addr` and invalidates the texture-hash cache so the-/// next `TX_SETIMAGE3` at that address re-decodes.-///-/// Only compiled when the `efb-writeback` feature is enabled.-#[cfg(feature = "efb-writeback")]+/// Payload the renderer worker ships back when an EFB-to-texture readback+/// completes. The emu thread copies `bytes` into `Mmio::ram` at `dest_addr`+/// at the next safe drain point.#[derive(Debug)]pub struct EfbWriteback {pub dest_addr: Address,diff --git a/crates/tinyapp/Cargo.toml b/crates/tinyapp/Cargo.tomlindex 2623793..bb968de 100644--- a/crates/tinyapp/Cargo.toml+++ b/crates/tinyapp/Cargo.toml@@ -7,7 +7,6 @@ edition = "2024"default = ["fps-counter"]scripting = ["gecko/hooks", "dep:scripting"]scripting-mut-traps = ["scripting", "gecko/hooks-mut-traps", "scripting/hooks-mut-traps"]-efb-writeback = ["backend-wgpu/efb-writeback"]renderdoc-capture = ["backend-wgpu/renderdoc-capture"]audio-wav-dump = ["gecko/audio-wav-dump"]fps-counter = ["gecko/fps-counter"]diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rsindex 5110be6..c083c84 100644--- a/crates/tinyapp/src/main.rs+++ b/crates/tinyapp/src/main.rs@@ -355,10 +355,7 @@ fn run<const SYSTEM: SystemId>(emulator.gx.draw_box_recycle_rx = renderer.take_recycle_rx();emulator.render_sink = Box::new(renderer.take_batching_sink());- #[cfg(feature = "efb-writeback")]- {- emulator.gx.efb_writeback_rx = renderer.take_writeback_rx();- }+ emulator.gx.efb_writeback_rx = renderer.take_writeback_rx();let audio_stream = install_audio_sink(args, &mut emulator);