Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

efb to texture, fixes ghosts in wario world

Laylecdfbe4ebf5bb
diff --git a/.gitignore b/.gitignore
index 8acea6c..f81f8c5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,4 +5,5 @@ perf.*
profile.json.gz
out*.txt
private/
-*.log
\ No newline at end of file
+*.log
+out/
\ No newline at end of file
diff --git a/.gitmodules b/.gitmodules
index c56ae55..e21a991 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -13,3 +13,6 @@
[submodule "submodules/solstice"]
path = submodules/solstice
url = https://codeberg.org/hazelwiss/solstice
+[submodule "submodules/beanwii"]
+ path = submodules/beanwii
+ url = https://github.com/zaydlang/beanwii
diff --git a/Cargo.lock b/Cargo.lock
index f24b687..ec4d6b2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1273,6 +1273,7 @@ dependencies = [
"bytemuck",
"chapa",
"chipi-build",
+ "crossbeam-channel",
"glam",
"image 0.1.0",
"tracing",
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rs
index 78820fb..c79530c 100644
--- a/crates/backend-wgpu/src/action.rs
+++ b/crates/backend-wgpu/src/action.rs
@@ -228,6 +228,46 @@ impl GxRenderer {
self.flush_pending_draws(device, queue);
self.execute_present_xfb(device, queue, *width, *height, parts);
}
+
+ GxAction::CopyEfbToTexture {
+ dest_addr,
+ src_x,
+ src_y,
+ src_w,
+ src_h,
+ copy_format,
+ mipmap,
+ stride: _,
+ clear,
+ clear_color,
+ clear_z,
+ color_update,
+ alpha_update: _,
+ z_update: _,
+ } => {
+ // Dolphin (`BPFunctions::ClearScreen`) clears per-channel
+ // using the current blend/depth write masks; if a channel
+ // is not write-enabled it is not cleared. Our
+ // `clear_region` wipes color+depth together.
+ // TODO: split `clear_region` into color- and depth-only
+ // variants and gate on each mask independently.
+ let effective_clear = *clear && *color_update;
+ self.flush_pending_draws(device, queue);
+ self.execute_copy_efb_to_texture(
+ device,
+ queue,
+ *dest_addr,
+ *src_x,
+ *src_y,
+ *src_w,
+ *src_h,
+ *copy_format,
+ *mipmap,
+ effective_clear,
+ *clear_color,
+ *clear_z,
+ );
+ }
}
}
diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rs
index 7a5ea38..9737a6a 100644
--- a/crates/backend-wgpu/src/lib.rs
+++ b/crates/backend-wgpu/src/lib.rs
@@ -9,6 +9,7 @@ use encase::ShaderType as _;
use gecko::common::Address;
use gecko::flipper::gx::draw::{Scissor, Viewport};
use gecko::flipper::gx::regs::{AlphaCompare, BlendMode, CompareFunc, CullMode, MagFilter, MinFilter, WrapMode, ZMode};
+use gecko::host::EfbWriteback;
use glam::Mat4;
use pipeline::PipelineKey;
use std::collections::HashMap;
@@ -137,6 +138,13 @@ pub struct GxRenderer {
pub(crate) xfb_copies: HashMap<u32, (wgpu::Texture, wgpu::TextureView)>,
// Region-scoped EFB clear.
pub(crate) efb_clear: clear::EfbClear,
+ // EFB-to-texture readback.
+ pub(crate) efb_readback_staging: Option<wgpu::Buffer>,
+ 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`].
+ pub(crate) efb_writeback_tx: Option<crossbeam_channel::Sender<EfbWriteback>>,
}
impl GxRenderer {
@@ -402,6 +410,15 @@ impl GxRenderer {
xfb_has_content: false,
xfb_copies: HashMap::new(),
efb_clear,
+ efb_readback_staging: None,
+ efb_readback_capacity: 0,
+ efb_writeback_tx: None,
}
}
+
+ /// Install the sender used to ship encoded EFB-to-texture bytes back
+ /// to the emulator thread. Called by `sink::Renderer` during setup.
+ 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.rs
index 1201026..5522383 100644
--- a/crates/backend-wgpu/src/render.rs
+++ b/crates/backend-wgpu/src/render.rs
@@ -1,7 +1,9 @@
use crate::{FrameUniforms, GxRenderer};
use crate::{GpuVertex, align_up};
use encase::ShaderType as _;
-use gecko::host::XfbPart;
+use gecko::common::Address;
+use gecko::flipper::gx::texture;
+use gecko::host::{EfbWriteback, XfbPart};
impl GxRenderer {
pub(crate) fn upload_buffers(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, frame_uniform_bytes: &[u8]) {
@@ -232,6 +234,197 @@ 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.
+ ///
+ /// `effective_clear` is the already-gated clear flag (see the
+ /// `CopyEfbToTexture` arm in `action.rs`); this function does not look
+ /// at the per-channel write masks itself.
+ pub(crate) fn execute_copy_efb_to_texture(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ dest_addr: Address,
+ src_x: u32,
+ src_y: u32,
+ src_w: u32,
+ src_h: u32,
+ copy_format: u8,
+ mipmap: bool,
+ effective_clear: bool,
+ clear_color: [f32; 4],
+ clear_z: f32,
+ ) {
+ // Clamp the source to EFB bounds (mirrors execute_copy_xfb).
+ 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_to_texture: zero-area region after clamping, skipping"
+ );
+ return;
+ }
+
+ // Early-out for formats we don't encode: skip the expensive readback
+ // but still honor the clear.
+ let Some(copy_format_enum) = texture::CopyFormat::from_u8(copy_format) else {
+ tracing::warn!(
+ copy_format = format!("{copy_format:#x}"),
+ "efb_to_texture: unsupported copy format, skipping readback"
+ );
+ if effective_clear {
+ self.efb_clear.clear_region(
+ device,
+ queue,
+ &self.efb_msaa_view,
+ &self.efb_view,
+ &self.efb_depth_view,
+ crate::EFB_WIDTH,
+ crate::EFB_HEIGHT,
+ src_x,
+ src_y,
+ src_w,
+ src_h,
+ clear_color,
+ clear_z,
+ );
+ }
+ return;
+ };
+
+ // 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;
+
+ // 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;
+ }
+ let staging = self.efb_readback_staging.as_ref().unwrap();
+
+ // Submit the EFB -> staging copy.
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("efb_to_texture_copy"),
+ });
+ encoder.copy_texture_to_buffer(
+ wgpu::TexelCopyTextureInfo {
+ texture: &self.efb_texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: src_x,
+ y: src_y,
+ z: 0,
+ },
+ aspect: wgpu::TextureAspect::default(),
+ },
+ wgpu::TexelCopyBufferInfo {
+ buffer: staging,
+ layout: wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(bytes_per_row as u32),
+ rows_per_image: Some(height),
+ },
+ },
+ wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ );
+ queue.submit([encoder.finish()]);
+
+ // Map and wait. This stalls the renderer worker (not the emu
+ // thread). Hello zayd, this mirrors beanwii's synchronous glReadPixels I think?
+ let slice = staging.slice(..staging_size);
+ slice.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, "efb_to_texture: device poll failed");
+ return;
+ }
+
+ // Extract RGBA8, converting from BGRA if the surface format
+ // requires it, and stripping wgpu's row padding.
+ let mut rgba = vec![0u8; (width * height * 4) as usize];
+ {
+ let mapped = slice.get_mapped_range();
+ let swap = matches!(
+ self.surface_format,
+ wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb
+ );
+ 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 {
+ 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];
+ }
+ } else {
+ dst_row.copy_from_slice(src_row);
+ }
+ }
+ }
+ staging.unmap();
+
+ // Optional 2x box-filter downsample.
+ let (encode_w, encode_h, encode_src) = if mipmap {
+ let down = texture::downsample_box_2x(&rgba, width, height);
+ (width / 2, height / 2, down)
+ } else {
+ (width, height, rgba)
+ };
+
+ // Encode and ship back.
+ let encoded = texture::encode_from_rgba(&encode_src, encode_w as usize, encode_h as usize, copy_format_enum);
+
+ if let Some(tx) = &self.efb_writeback_tx {
+ if let Err(err) = tx.try_send(EfbWriteback {
+ dest_addr,
+ bytes: encoded,
+ }) {
+ tracing::warn!(?err, "efb_to_texture: writeback channel send failed");
+ }
+ }
+
+ if effective_clear {
+ self.efb_clear.clear_region(
+ device,
+ queue,
+ &self.efb_msaa_view,
+ &self.efb_view,
+ &self.efb_depth_view,
+ crate::EFB_WIDTH,
+ crate::EFB_HEIGHT,
+ src_x,
+ src_y,
+ src_w,
+ src_h,
+ clear_color,
+ clear_z,
+ );
+ }
+ }
+
fn ensure_draw_capacity(&mut self, device: &wgpu::Device, count: usize) {
if count <= self.draw_uniform_capacity {
return;
diff --git a/crates/backend-wgpu/src/sink.rs b/crates/backend-wgpu/src/sink.rs
index 484d541..773bd28 100644
--- a/crates/backend-wgpu/src/sink.rs
+++ b/crates/backend-wgpu/src/sink.rs
@@ -1,6 +1,6 @@
use crate::GxRenderer;
use crossbeam_channel::{Receiver, Sender, bounded};
-use gecko::host::{GxAction, RenderSink};
+use gecko::host::{EfbWriteback, GxAction, RenderSink};
use std::sync::{Arc, Mutex};
const CHANNEL_CAPACITY: usize = 8192;
@@ -32,13 +32,23 @@ pub struct Renderer {
blit_pipeline: wgpu::RenderPipeline,
blit_bind_group_layout: wgpu::BindGroupLayout,
blit_sampler: wgpu::Sampler,
+ /// 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`.
+ writeback_rx: Arc<Mutex<Option<Receiver<EfbWriteback>>>>,
}
impl Renderer {
/// Create the renderer, spawning the worker thread. The caller must
/// provide a wgpu device and queue.
pub fn new(device: wgpu::Device, queue: wgpu::Queue, surface_format: wgpu::TextureFormat) -> Self {
- let gx = GxRenderer::new(&device, &queue, surface_format);
+ let mut gx = GxRenderer::new(&device, &queue, surface_format);
+
+ // Writeback channel: GxRenderer sends encoded EFB-to-texture bytes,
+ // GraphicsProcessor consumes them synchronously on the emu thread.
+ let (writeback_tx, writeback_rx) = bounded::<EfbWriteback>(CHANNEL_CAPACITY);
+ gx.set_efb_writeback_tx(writeback_tx);
// Initial shared output: the XFB view (black until first PresentXfb).
let shared = Arc::new(Shared {
@@ -129,9 +139,17 @@ impl Renderer {
blit_pipeline,
blit_bind_group_layout,
blit_sampler,
+ writeback_rx: Arc::new(Mutex::new(Some(writeback_rx))),
}
}
+ /// Take the writeback receiver once. Returns `Some` on the first call,
+ /// `None` thereafter. The caller installs it into
+ /// `GraphicsProcessor::efb_writeback_rx`.
+ pub fn take_writeback_rx(&self) -> Option<Receiver<EfbWriteback>> {
+ self.writeback_rx.lock().ok()?.take()
+ }
+
/// Blit the latest XFB output to the given render target. Called by the
/// main thread on each redraw.
pub fn blit(&self, queue: &wgpu::Queue, target: &wgpu::TextureView) {
diff --git a/crates/debugger/src/main.rs b/crates/debugger/src/main.rs
index e264c91..fd6d883 100644
--- a/crates/debugger/src/main.rs
+++ b/crates/debugger/src/main.rs
@@ -237,6 +237,9 @@ fn main() {
// Install the renderer as the emulator's render sink.
emulator.render_sink = Box::new(renderer.clone());
+ // Install the EFB-to-texture writeback receiver.
+ emulator.gx.efb_writeback_rx = renderer.take_writeback_rx();
+
let ui = DebuggerUi {
symbols,
..DebuggerUi::default()
diff --git a/crates/dsptestrunner/Cargo.toml b/crates/dsptestrunner/Cargo.toml
index 353c725..1c6bb3e 100644
--- a/crates/dsptestrunner/Cargo.toml
+++ b/crates/dsptestrunner/Cargo.toml
@@ -5,4 +5,5 @@ edition = "2024"
[dependencies]
image = { path = "../image" }
-gecko = { path = "../gecko", features = ["hooks"] }
\ No newline at end of file
+gecko = { path = "../gecko", features = ["hooks"] }
+disasm = { path = "../disasm" }
\ No newline at end of file
diff --git a/crates/gecko/Cargo.toml b/crates/gecko/Cargo.toml
index b66d216..86c0ba8 100644
--- a/crates/gecko/Cargo.toml
+++ b/crates/gecko/Cargo.toml
@@ -18,3 +18,4 @@ image = { path = "../image", default-features = false }
glam = { version = "0.32.1", features = ["bytemuck"] }
bytemuck = { version = "1.25.0", features = ["derive"] }
twox-hash = "2.1.2"
+crossbeam-channel = "0.5.15"
diff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rs
index 7e0e193..e5fd927 100644
--- a/crates/gecko/src/flipper/gx.rs
+++ b/crates/gecko/src/flipper/gx.rs
@@ -14,7 +14,7 @@ use crate::flipper::gx::constants::{BP_REG_SIZE, CP_REG_SIZE, XF_MEM_SIZE};
use crate::flipper::gx::draw::Matrix4;
use crate::flipper::gx::regs::{AlphaCompare, BlendMode, TevAlphaEnv, TevColorEnv, TevRegisterH, TevRegisterL, ZMode};
use crate::gamecube::GameCube;
-use crate::host::{GxAction, RenderSink, XfbPart};
+use crate::host::{EfbWriteback, GxAction, RenderSink, XfbPart};
use crate::mmio::Mmio;
use fifo::FifoCmd;
use std::collections::HashMap;
@@ -57,6 +57,12 @@ pub struct GraphicsProcessor {
// Hash of the raw texture data at each RAM address; used to detect when
// texture content changes and avoid redundant decodes + LoadTexture sends.
pub texture_hashes: HashMap<u32, 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.
+ pub efb_writeback_rx: Option<crossbeam_channel::Receiver<EfbWriteback>>,
}
/// A single EFB-to-XFB copy, stored until `present_xfb` computes the layout.
@@ -97,6 +103,7 @@ impl GraphicsProcessor {
cur_scissor_offset_y: 0,
xfb_copies: Vec::new(),
texture_hashes: HashMap::new(),
+ efb_writeback_rx: None,
}
}
@@ -120,7 +127,7 @@ impl GraphicsProcessor {
match cmd {
FifoCmd::Cp(data) => self.load_cp(&data),
FifoCmd::Xf(data) => self.load_xf(renderer, &data),
- FifoCmd::Bp(data) => self.load_bp(renderer, &mmio.ram, &data),
+ FifoCmd::Bp(data) => self.load_bp(renderer, &mut mmio.ram, &data),
FifoCmd::LoadIndexedXf {
cp_array_index,
index,
diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rs
index b006849..35799a0 100644
--- a/crates/gecko/src/flipper/gx/bp.rs
+++ b/crates/gecko/src/flipper/gx/bp.rs
@@ -14,9 +14,10 @@ use super::regs::{
use super::{GraphicsProcessor, draw, texture};
use crate::common::Address;
use crate::host::{GxAction, RenderSink};
+use std::time::Duration;
impl GraphicsProcessor {
- pub fn load_bp(&mut self, renderer: &mut dyn RenderSink, ram: &[u8], data: &[u8]) {
+ pub fn load_bp(&mut self, renderer: &mut dyn RenderSink, ram: &mut [u8], data: &[u8]) {
let idx = data[0] as usize;
let val = u32::from_be_bytes([0, data[1], data[2], data[3]]);
self.bp_regs[idx] = val;
@@ -129,7 +130,7 @@ impl GraphicsProcessor {
// EFB copy trigger (BP 0x52)
if idx == BP_PE_COPY_CMD {
- self.efb_copy(renderer, val);
+ self.efb_copy(renderer, ram, val);
}
}
@@ -274,7 +275,7 @@ impl GraphicsProcessor {
}
}
- fn efb_copy(&mut self, renderer: &mut dyn RenderSink, trigger: u32) {
+ fn efb_copy(&mut self, renderer: &mut dyn RenderSink, ram: &mut [u8], trigger: u32) {
let src = EfbCopySrc::from_raw(self.bp_regs[BP_PE_COPY_SRC]);
let dims = EfbCopyDims::from_raw(self.bp_regs[BP_PE_COPY_DIMS]);
let src_x = src.left() as u32;
@@ -331,7 +332,57 @@ impl GraphicsProcessor {
clear_z,
});
} else {
- let _ = (dest_addr, dest_stride, clear, half, r, g, b, a, clear_z);
+ let copy_format = cmd.copy_format();
+ // Per Dolphin BPFunctions::ClearScreen: the `clear` bit only
+ // affects channels whose write mask is currently enabled.
+ // Carry the masks along so the backend can gate correctly.
+ let color_update = self.cur_blend_mode.color_update();
+ let alpha_update = self.cur_blend_mode.alpha_update();
+ let z_update = self.cur_zmode.update_enable();
+
+ renderer.exec(GxAction::CopyEfbToTexture {
+ dest_addr,
+ src_x,
+ src_y,
+ src_w,
+ src_h,
+ copy_format,
+ mipmap: half,
+ stride: dest_stride,
+ clear,
+ clear_color: [r, g, b, a],
+ clear_z,
+ color_update,
+ alpha_update,
+ z_update,
+ });
+
+ // Block until the renderer finishes the readback + encode and
+ // ships the encoded bytes back. This preserves ordering with
+ // subsequent FIFO commands (e.g. a TX_SETIMAGE3 at `dest_addr`
+ // immediately after this copy): by the time efb_copy returns,
+ // RAM is up to date and the next texture load re-hashes.
+ if let Some(rx) = &self.efb_writeback_rx {
+ match rx.recv_timeout(Duration::from_secs(2)) {
+ Ok(wb) => {
+ let start = wb.dest_addr as usize;
+ let end = start + wb.bytes.len();
+ if end <= ram.len() {
+ ram[start..end].copy_from_slice(&wb.bytes);
+ self.texture_hashes.remove(&wb.dest_addr);
+ } else {
+ tracing::warn!(
+ addr = format!("{:#010X}", wb.dest_addr),
+ len = wb.bytes.len(),
+ "efb writeback OOB, dropping"
+ );
+ }
+ }
+ Err(err) => {
+ tracing::warn!(?err, "efb writeback recv timed out");
+ }
+ }
+ }
}
}
diff --git a/crates/gecko/src/flipper/gx/regs.rs b/crates/gecko/src/flipper/gx/regs.rs
index 720f228..f079dd0 100644
--- a/crates/gecko/src/flipper/gx/regs.rs
+++ b/crates/gecko/src/flipper/gx/regs.rs
@@ -1111,6 +1111,14 @@ pub struct PeCopyCmd {
#[bits(0..=1)]
pub clamp: u8,
+ // Texture copy format: bit 3 is the high nibble-bit, bits 4-6 are the low
+ // three bits.
+ #[bits(3)]
+ pub fmt_hi: bool,
+
+ #[bits(4..=6)]
+ pub fmt_lo: u8,
+
#[bits(9)]
pub half: bool,
@@ -1127,6 +1135,14 @@ pub struct PeCopyCmd {
pub copy_to_xfb: bool,
}
+impl PeCopyCmd {
+ /// 4-bit GX texture copy destination format (only valid when
+ /// `copy_to_xfb == false`).
+ pub fn copy_format(&self) -> u8 {
+ ((self.fmt_hi() as u8) << 3) | self.fmt_lo()
+ }
+}
+
// BP 0x4F BPMEM_CLEAR_AR (PE clear alpha/red)
#[chapa::bitfield(u32, order = lsb0)]
#[derive(Debug, Clone, Copy, Default)]
diff --git a/crates/gecko/src/flipper/gx/texture.rs b/crates/gecko/src/flipper/gx/texture.rs
index e125c12..6dcf958 100644
--- a/crates/gecko/src/flipper/gx/texture.rs
+++ b/crates/gecko/src/flipper/gx/texture.rs
@@ -21,9 +21,21 @@ pub fn decode_to_rgba(ram: &[u8], desc: &TextureDescriptor) -> Vec<u8> {
rgba
}
-/// Compute the number of raw bytes a GX texture occupies in RAM.
-pub fn raw_data_size(width: u32, height: u32, format: TextureFormat) -> usize {
- let (block_w, block_h, block_bytes): (u32, u32, u32) = match format {
+#[derive(Clone, Copy, Debug)]
+pub struct BlockDims {
+ pub tile_w: u32,
+ pub tile_h: u32,
+ pub bytes_per_tile: u32,
+}
+
+impl BlockDims {
+ pub const fn bytes_for(self, w: u32, h: u32) -> usize {
+ (w.div_ceil(self.tile_w) * h.div_ceil(self.tile_h) * self.bytes_per_tile) as usize
+ }
+}
+
+pub const fn block_dims(format: TextureFormat) -> BlockDims {
+ let (tw, th, bb) = match format {
TextureFormat::I4 => (8, 8, 32),
TextureFormat::I8 => (8, 4, 32),
TextureFormat::IA4 => (8, 4, 32),
@@ -36,9 +48,17 @@ pub fn raw_data_size(width: u32, height: u32, format: TextureFormat) -> usize {
TextureFormat::CI8 => (8, 4, 32),
TextureFormat::CI14 => (4, 4, 32),
};
- let blocks_x = width.div_ceil(block_w);
- let blocks_y = height.div_ceil(block_h);
- (blocks_x * blocks_y * block_bytes) as usize
+ BlockDims {
+ tile_w: tw,
+ tile_h: th,
+ bytes_per_tile: bb,
+ }
+}
+
+/// Compute the number of raw bytes a GX texture occupies in RAM.
+#[inline(always)]
+pub fn raw_data_size(width: u32, height: u32, format: TextureFormat) -> usize {
+ block_dims(format).bytes_for(width, height)
}
fn decode_i4(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize, h: usize) {
@@ -67,10 +87,13 @@ fn decode_i4(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize, h:
for ty in 0..th {
for tx in 0..tw {
unsafe {
- let byte = read_u8_unchecked(src, blk + (ty * BW + tx) / 2);
+ let byte = *src.add(blk + (ty * BW + tx) / 2);
let nibble = if tx & 1 == 0 { byte >> 4 } else { byte & 0x0F };
- let i = expand_4_to_8(nibble);
- write_pixel(dst, ((base_y + ty) * w + base_x + tx) * 4, [i, i, i, i]);
+ let i = expand_to_8::<4>(nibble);
+ std::ptr::write(
+ dst.add(((base_y + ty) * w + base_x + tx) * 4).cast::<[u8; 4]>(),
+ [i, i, i, i],
+ );
}
}
}
@@ -104,8 +127,11 @@ fn decode_i8(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize, h:
for ty in 0..th {
for tx in 0..tw {
unsafe {
- let i = read_u8_unchecked(src, blk + ty * BW + tx);
- write_pixel(dst, ((base_y + ty) * w + base_x + tx) * 4, [i, i, i, i]);
+ let i = *src.add(blk + ty * BW + tx);
+ std::ptr::write(
+ dst.add(((base_y + ty) * w + base_x + tx) * 4).cast::<[u8; 4]>(),
+ [i, i, i, i],
+ );
}
}
}
@@ -139,10 +165,13 @@ fn decode_ia4(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize, h
for ty in 0..th {
for tx in 0..tw {
unsafe {
- let packed = read_u8_unchecked(src, blk + ty * BW + tx);
- let a = expand_4_to_8(packed >> 4);
- let i = expand_4_to_8(packed & 0x0F);
- write_pixel(dst, ((base_y + ty) * w + base_x + tx) * 4, [i, i, i, a]);
+ let packed = *src.add(blk + ty * BW + tx);
+ let a = expand_to_8::<4>(packed >> 4);
+ let i = expand_to_8::<4>(packed & 0x0F);
+ std::ptr::write(
+ dst.add(((base_y + ty) * w + base_x + tx) * 4).cast::<[u8; 4]>(),
+ [i, i, i, a],
+ );
}
}
}
@@ -178,9 +207,12 @@ fn decode_ia8(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize, h
for tx in 0..tw {
unsafe {
let off = blk + (ty * BW + tx) * 2;
- let a = read_u8_unchecked(src, off);
- let i = read_u8_unchecked(src, off + 1);
- write_pixel(dst, ((base_y + ty) * w + base_x + tx) * 4, [i, i, i, a]);
+ let a = *src.add(off);
+ let i = *src.add(off + 1);
+ std::ptr::write(
+ dst.add(((base_y + ty) * w + base_x + tx) * 4).cast::<[u8; 4]>(),
+ [i, i, i, a],
+ );
}
}
}
@@ -214,9 +246,12 @@ fn decode_rgb565(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize
for ty in 0..th {
for tx in 0..tw {
unsafe {
- let packed = read_be_u16_unchecked(src, blk + (ty * BW + tx) * 2);
+ let packed = u16::from_be_bytes([
+ *src.add(blk + (ty * BW + tx) * 2),
+ *src.add(blk + (ty * BW + tx) * 2 + 1),
+ ]);
let pixel = self::rgb565_to_rgba(packed);
- write_pixel(dst, ((base_y + ty) * w + base_x + tx) * 4, pixel);
+ std::ptr::write(dst.add(((base_y + ty) * w + base_x + tx) * 4).cast::<[u8; 4]>(), pixel);
}
}
}
@@ -250,20 +285,23 @@ fn decode_rgb5a3(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize
for ty in 0..th {
for tx in 0..tw {
unsafe {
- let packed = read_be_u16_unchecked(src, blk + (ty * BW + tx) * 2);
+ let packed = u16::from_be_bytes([
+ *src.add(blk + (ty * BW + tx) * 2),
+ *src.add(blk + (ty * BW + tx) * 2 + 1),
+ ]);
let pixel = if packed & 0x8000 != 0 {
- let r = expand_5_to_8(((packed >> 10) & 0x1F) as u8);
- let g = expand_5_to_8(((packed >> 5) & 0x1F) as u8);
- let b = expand_5_to_8((packed & 0x1F) as u8);
+ let r = expand_to_8::<5>(((packed >> 10) & 0x1F) as u8);
+ let g = expand_to_8::<5>(((packed >> 5) & 0x1F) as u8);
+ let b = expand_to_8::<5>((packed & 0x1F) as u8);
[r, g, b, 255]
} else {
- let a = expand_3_to_8(((packed >> 12) & 0x7) as u8);
- let r = expand_4_to_8(((packed >> 8) & 0xF) as u8);
- let g = expand_4_to_8(((packed >> 4) & 0xF) as u8);
- let b = expand_4_to_8((packed & 0xF) as u8);
+ let a = expand_to_8::<3>(((packed >> 12) & 0x7) as u8);
+ let r = expand_to_8::<4>(((packed >> 8) & 0xF) as u8);
+ let g = expand_to_8::<4>(((packed >> 4) & 0xF) as u8);
+ let b = expand_to_8::<4>((packed & 0xF) as u8);
[r, g, b, a]
};
- write_pixel(dst, ((base_y + ty) * w + base_x + tx) * 4, pixel);
+ std::ptr::write(dst.add(((base_y + ty) * w + base_x + tx) * 4).cast::<[u8; 4]>(), pixel);
}
}
}
@@ -300,11 +338,14 @@ fn decode_rgba8(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize,
let ti = ty * BW + tx;
let ar = blk + ti * 2;
let gb = blk + 32 + ti * 2;
- let a = read_u8_unchecked(src, ar);
- let r = read_u8_unchecked(src, ar + 1);
- let g = read_u8_unchecked(src, gb);
- let b = read_u8_unchecked(src, gb + 1);
- write_pixel(dst, ((base_y + ty) * w + base_x + tx) * 4, [r, g, b, a]);
+ let a = *src.add(ar);
+ let r = *src.add(ar + 1);
+ let g = *src.add(gb);
+ let b = *src.add(gb + 1);
+ std::ptr::write(
+ dst.add(((base_y + ty) * w + base_x + tx) * 4).cast::<[u8; 4]>(),
+ [r, g, b, a],
+ );
}
}
}
@@ -345,15 +386,18 @@ fn decode_cmpr(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize,
let th = 4usize.min(h - sub_y);
unsafe {
- let c0 = read_be_u16_unchecked(src, sub_off);
- let c1 = read_be_u16_unchecked(src, sub_off + 2);
+ let c0 = u16::from_be_bytes([*src.add(sub_off), *src.add(sub_off + 1)]);
+ let c1 = u16::from_be_bytes([*src.add(sub_off + 2), *src.add(sub_off + 3)]);
let palette = self::build_dxt1_palette(c0, c1);
for row in 0..th {
- let idx = read_u8_unchecked(src, sub_off + 4 + row);
+ let idx = *src.add(sub_off + 4 + row);
for col in 0..tw {
let pi = ((idx >> ((3 - col) * 2)) & 0x03) as usize;
- write_pixel(dst, ((sub_y + row) * w + sub_x + col) * 4, palette[pi]);
+ std::ptr::write(
+ dst.add(((sub_y + row) * w + sub_x + col) * 4).cast::<[u8; 4]>(),
+ palette[pi],
+ );
}
}
}
@@ -395,45 +439,403 @@ fn build_dxt1_palette(c0: u16, c1: u16) -> [[u8; 4]; 4] {
p
}
+// i have cancer
#[inline(always)]
-fn expand_3_to_8(v: u8) -> u8 {
- (v << 5) | (v << 2) | (v >> 1)
+const fn expand_to_8<const BITS: u32>(v: u8) -> u8 {
+ let mut result = v << (8 - BITS);
+ let mut pos = 8 - BITS;
+ while pos > 0 {
+ if pos >= BITS {
+ pos -= BITS;
+ result |= v << pos;
+ } else {
+ result |= v >> (BITS - pos);
+ break;
+ }
+ }
+ result
}
#[inline(always)]
-fn expand_4_to_8(v: u8) -> u8 {
- (v << 4) | v
+fn rgb565_to_rgba(packed: u16) -> [u8; 4] {
+ let r = ((packed >> 11) & 0x1F) as u8;
+ let g = ((packed >> 5) & 0x3F) as u8;
+ let b = (packed & 0x1F) as u8;
+ [expand_to_8::<5>(r), expand_to_8::<6>(g), expand_to_8::<5>(b), 255]
}
-#[inline(always)]
-fn expand_5_to_8(v: u8) -> u8 {
- (v << 3) | (v >> 2)
+#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
+pub enum CopyFormat {
+ I8 = 0x1,
+ RGB565 = 0x4,
+ RGB5A3 = 0x5,
+ RGBA8 = 0x6,
+ A8 = 0x7,
+ R8 = 0x8,
+ RG8 = 0xB,
}
-#[inline(always)]
-fn expand_6_to_8(v: u8) -> u8 {
- (v << 2) | (v >> 4)
+impl CopyFormat {
+ pub fn from_u8(code: u8) -> Option<Self> {
+ Some(match code {
+ 0x1 => Self::I8,
+ 0x4 => Self::RGB565,
+ 0x5 => Self::RGB5A3,
+ 0x6 => Self::RGBA8,
+ 0x7 => Self::A8,
+ 0x8 => Self::R8,
+ 0xB => Self::RG8,
+ _ => return None,
+ })
+ }
}
-#[inline(always)]
-fn rgb565_to_rgba(packed: u16) -> [u8; 4] {
- let r = ((packed >> 11) & 0x1F) as u8;
- let g = ((packed >> 5) & 0x3F) as u8;
- let b = (packed & 0x1F) as u8;
- [expand_5_to_8(r), expand_6_to_8(g), expand_5_to_8(b), 255]
+pub fn encoded_size(w: u32, h: u32, format: CopyFormat) -> usize {
+ let dims = match format {
+ CopyFormat::I8 => block_dims(TextureFormat::I8),
+ CopyFormat::RGB565 => block_dims(TextureFormat::RGB565),
+ CopyFormat::RGB5A3 => block_dims(TextureFormat::RGB5A3),
+ CopyFormat::RGBA8 => block_dims(TextureFormat::RGBA8),
+ CopyFormat::A8 | CopyFormat::R8 => BlockDims {
+ tile_w: 8,
+ tile_h: 4,
+ bytes_per_tile: 32,
+ },
+ CopyFormat::RG8 => BlockDims {
+ tile_w: 4,
+ tile_h: 4,
+ bytes_per_tile: 32,
+ },
+ };
+ dims.bytes_for(w, h)
}
-#[inline(always)]
-unsafe fn write_pixel(dst: *mut u8, offset: usize, pixel: [u8; 4]) {
- unsafe { std::ptr::write(dst.add(offset).cast::<[u8; 4]>(), pixel) };
+// ref downsample_rgba_buffer_by_2 @ beanwii, zayd is smarter than me
+
+pub fn downsample_box_2x(src: &[u8], w: u32, h: u32) -> Vec<u8> {
+ let nw = (w / 2) as usize;
+ let nh = (h / 2) as usize;
+ let sw = w as usize;
+ let mut out = vec![0u8; nw * nh * 4];
+
+ for y in 0..nh {
+ for x in 0..nw {
+ let sx = x * 2;
+ let sy = y * 2;
+ let s0 = (sy * sw + sx) * 4;
+ let s1 = (sy * sw + sx + 1) * 4;
+ let s2 = ((sy + 1) * sw + sx) * 4;
+ let s3 = ((sy + 1) * sw + sx + 1) * 4;
+ let d = (y * nw + x) * 4;
+ for c in 0..4 {
+ out[d + c] =
+ ((src[s0 + c] as u16 + src[s1 + c] as u16 + src[s2 + c] as u16 + src[s3 + c] as u16) / 4) as u8;
+ }
+ }
+ }
+ out
}
-#[inline(always)]
-unsafe fn read_u8_unchecked(src: *const u8, offset: usize) -> u8 {
- unsafe { *src.add(offset) }
+/// Encode a linear RGBA8 buffer into a freshly-allocated tiled GX copy
+/// format. Mirror of [`decode_to_rgba`] for the EFB-to-texture direction.
+pub fn encode_from_rgba(rgba: &[u8], w: usize, h: usize, format: CopyFormat) -> Vec<u8> {
+ let size = encoded_size(w as u32, h as u32, format);
+ let mut out = vec![0u8; size];
+ match format {
+ CopyFormat::I8 => encode_i8(rgba, &mut out, w, h),
+ CopyFormat::A8 => encode_a8(rgba, &mut out, w, h),
+ CopyFormat::R8 => encode_r8(rgba, &mut out, w, h),
+ CopyFormat::RG8 => encode_rg8(rgba, &mut out, w, h),
+ CopyFormat::RGB565 => encode_rgb565(rgba, &mut out, w, h),
+ CopyFormat::RGB5A3 => encode_rgb5a3(rgba, &mut out, w, h),
+ CopyFormat::RGBA8 => encode_rgba8(rgba, &mut out, w, h),
+ }
+ out
}
#[inline(always)]
-unsafe fn read_be_u16_unchecked(src: *const u8, offset: usize) -> u16 {
- unsafe { u16::from_be_bytes([*src.add(offset), *src.add(offset + 1)]) }
+fn luminance(r: u8, g: u8, b: u8) -> u8 {
+ ((r as u32 * 299 + g as u32 * 587 + b as u32 * 114) / 1000) as u8
+}
+
+fn encode_i8(rgba: &[u8], out: &mut [u8], w: usize, h: usize) {
+ const BW: usize = 8;
+ const BH: usize = 4;
+ const BB: usize = 32;
+
+ let bcx = w.div_ceil(BW);
+ let bcy = h.div_ceil(BH);
+ if bcx * bcy * BB > out.len() || rgba.len() < w * h * 4 {
+ tracing::warn!(w, h, "encode_i8: buffer OOB, skipping");
+ return;
+ }
+
+ let src = rgba.as_ptr();
+ let dst = out.as_mut_ptr();
+
+ for by in 0..bcy {
+ let base_y = by * BH;
+ let th = BH.min(h - base_y);
+ for bx in 0..bcx {
+ let base_x = bx * BW;
+ let tw = BW.min(w - base_x);
+ let blk = (by * bcx + bx) * BB;
+
+ for ty in 0..th {
+ for tx in 0..tw {
+ unsafe {
+ let s = ((base_y + ty) * w + base_x + tx) * 4;
+ let r = *src.add(s);
+ let g = *src.add(s + 1);
+ let b = *src.add(s + 2);
+ *dst.add(blk + ty * BW + tx) = luminance(r, g, b);
+ }
+ }
+ }
+ }
+ }
+}
+
+fn encode_a8(rgba: &[u8], out: &mut [u8], w: usize, h: usize) {
+ const BW: usize = 8;
+ const BH: usize = 4;
+ const BB: usize = 32;
+
+ let bcx = w.div_ceil(BW);
+ let bcy = h.div_ceil(BH);
+ if bcx * bcy * BB > out.len() || rgba.len() < w * h * 4 {
+ tracing::warn!(w, h, "encode_a8: buffer OOB, skipping");
+ return;
+ }
+
+ let src = rgba.as_ptr();
+ let dst = out.as_mut_ptr();
+
+ for by in 0..bcy {
+ let base_y = by * BH;
+ let th = BH.min(h - base_y);
+ for bx in 0..bcx {
+ let base_x = bx * BW;
+ let tw = BW.min(w - base_x);
+ let blk = (by * bcx + bx) * BB;
+
+ for ty in 0..th {
+ for tx in 0..tw {
+ unsafe {
+ let s = ((base_y + ty) * w + base_x + tx) * 4;
+ *dst.add(blk + ty * BW + tx) = *src.add(s + 3);
+ }
+ }
+ }
+ }
+ }
+}
+
+fn encode_r8(rgba: &[u8], out: &mut [u8], w: usize, h: usize) {
+ const BW: usize = 8;
+ const BH: usize = 4;
+ const BB: usize = 32;
+
+ let bcx = w.div_ceil(BW);
+ let bcy = h.div_ceil(BH);
+ if bcx * bcy * BB > out.len() || rgba.len() < w * h * 4 {
+ tracing::warn!(w, h, "encode_r8: buffer OOB, skipping");
+ return;
+ }
+
+ let src = rgba.as_ptr();
+ let dst = out.as_mut_ptr();
+
+ for by in 0..bcy {
+ let base_y = by * BH;
+ let th = BH.min(h - base_y);
+ for bx in 0..bcx {
+ let base_x = bx * BW;
+ let tw = BW.min(w - base_x);
+ let blk = (by * bcx + bx) * BB;
+
+ for ty in 0..th {
+ for tx in 0..tw {
+ unsafe {
+ let s = ((base_y + ty) * w + base_x + tx) * 4;
+ *dst.add(blk + ty * BW + tx) = *src.add(s);
+ }
+ }
+ }
+ }
+ }
+}
+
+fn encode_rg8(rgba: &[u8], out: &mut [u8], w: usize, h: usize) {
+ const BW: usize = 4;
+ const BH: usize = 4;
+ const BB: usize = 32;
+
+ let bcx = w.div_ceil(BW);
+ let bcy = h.div_ceil(BH);
+ if bcx * bcy * BB > out.len() || rgba.len() < w * h * 4 {
+ tracing::warn!(w, h, "encode_rg8: buffer OOB, skipping");
+ return;
+ }
+
+ let src = rgba.as_ptr();
+ let dst = out.as_mut_ptr();
+
+ for by in 0..bcy {
+ let base_y = by * BH;
+ let th = BH.min(h - base_y);
+ for bx in 0..bcx {
+ let base_x = bx * BW;
+ let tw = BW.min(w - base_x);
+ let blk = (by * bcx + bx) * BB;
+
+ for ty in 0..th {
+ for tx in 0..tw {
+ unsafe {
+ let s = ((base_y + ty) * w + base_x + tx) * 4;
+ let off = blk + (ty * BW + tx) * 2;
+ std::ptr::write(dst.add(off).cast::<[u8; 2]>(), [*src.add(s), *src.add(s + 1)]);
+ }
+ }
+ }
+ }
+ }
+}
+
+fn encode_rgb565(rgba: &[u8], out: &mut [u8], w: usize, h: usize) {
+ const BW: usize = 4;
+ const BH: usize = 4;
+ const BB: usize = 32;
+
+ let bcx = w.div_ceil(BW);
+ let bcy = h.div_ceil(BH);
+ if bcx * bcy * BB > out.len() || rgba.len() < w * h * 4 {
+ tracing::warn!(w, h, "encode_rgb565: buffer OOB, skipping");
+ return;
+ }
+
+ let src = rgba.as_ptr();
+ let dst = out.as_mut_ptr();
+
+ for by in 0..bcy {
+ let base_y = by * BH;
+ let th = BH.min(h - base_y);
+ for bx in 0..bcx {
+ let base_x = bx * BW;
+ let tw = BW.min(w - base_x);
+ let blk = (by * bcx + bx) * BB;
+
+ for ty in 0..th {
+ for tx in 0..tw {
+ unsafe {
+ let s = ((base_y + ty) * w + base_x + tx) * 4;
+ let r = (*src.add(s) >> 3) as u16;
+ let g = (*src.add(s + 1) >> 2) as u16;
+ let b = (*src.add(s + 2) >> 3) as u16;
+ let pixel = (r << 11) | (g << 5) | b;
+ let off = blk + (ty * BW + tx) * 2;
+ std::ptr::write(
+ dst.add(off).cast::<[u8; 2]>(),
+ [(pixel >> 8) as u8, (pixel & 0xFF) as u8],
+ );
+ }
+ }
+ }
+ }
+ }
+}
+
+fn encode_rgb5a3(rgba: &[u8], out: &mut [u8], w: usize, h: usize) {
+ const BW: usize = 4;
+ const BH: usize = 4;
+ const BB: usize = 32;
+
+ let bcx = w.div_ceil(BW);
+ let bcy = h.div_ceil(BH);
+ if bcx * bcy * BB > out.len() || rgba.len() < w * h * 4 {
+ tracing::warn!(w, h, "encode_rgb5a3: buffer OOB, skipping");
+ return;
+ }
+
+ let src = rgba.as_ptr();
+ let dst = out.as_mut_ptr();
+
+ for by in 0..bcy {
+ let base_y = by * BH;
+ let th = BH.min(h - base_y);
+ for bx in 0..bcx {
+ let base_x = bx * BW;
+ let tw = BW.min(w - base_x);
+ let blk = (by * bcx + bx) * BB;
+
+ for ty in 0..th {
+ for tx in 0..tw {
+ unsafe {
+ let s = ((base_y + ty) * w + base_x + tx) * 4;
+ let r = *src.add(s);
+ let g = *src.add(s + 1);
+ let b = *src.add(s + 2);
+ let a = *src.add(s + 3);
+ let pixel: u16 = if a == 255 {
+ // RGB555 with high bit set.
+ 0x8000 | (((r >> 3) as u16) << 10) | (((g >> 3) as u16) << 5) | ((b >> 3) as u16)
+ } else {
+ // RGBA4443 with high bit clear.
+ (((a >> 5) as u16) << 12)
+ | (((r >> 4) as u16) << 8)
+ | (((g >> 4) as u16) << 4)
+ | ((b >> 4) as u16)
+ };
+ let off = blk + (ty * BW + tx) * 2;
+ std::ptr::write(
+ dst.add(off).cast::<[u8; 2]>(),
+ [(pixel >> 8) as u8, (pixel & 0xFF) as u8],
+ );
+ }
+ }
+ }
+ }
+ }
+}
+
+fn encode_rgba8(rgba: &[u8], out: &mut [u8], w: usize, h: usize) {
+ const BW: usize = 4;
+ const BH: usize = 4;
+ const BB: usize = 64;
+
+ let bcx = w.div_ceil(BW);
+ let bcy = h.div_ceil(BH);
+ if bcx * bcy * BB > out.len() || rgba.len() < w * h * 4 {
+ tracing::warn!(w, h, "encode_rgba8: buffer OOB, skipping");
+ return;
+ }
+
+ let src = rgba.as_ptr();
+ let dst = out.as_mut_ptr();
+
+ // 4x4 tiles split into two 32-byte half-blocks per tile: AR pairs
+ // first, then GB pairs, both indexed by `ty * BW + tx`. Inverse of
+ // `decode_rgba8`'s unpack.
+ for by in 0..bcy {
+ let base_y = by * BH;
+ let th = BH.min(h - base_y);
+ for bx in 0..bcx {
+ let base_x = bx * BW;
+ let tw = BW.min(w - base_x);
+ let blk = (by * bcx + bx) * BB;
+
+ for ty in 0..th {
+ for tx in 0..tw {
+ unsafe {
+ let s = ((base_y + ty) * w + base_x + tx) * 4;
+ let ti = ty * BW + tx;
+ let ar = blk + ti * 2;
+ let gb = blk + 32 + ti * 2;
+ std::ptr::write(dst.add(ar).cast::<[u8; 2]>(), [*src.add(s + 3), *src.add(s)]);
+ std::ptr::write(dst.add(gb).cast::<[u8; 2]>(), [*src.add(s + 1), *src.add(s + 2)]);
+ }
+ }
+ }
+ }
+ }
}
diff --git a/crates/gecko/src/host.rs b/crates/gecko/src/host.rs
index f20c435..d951065 100644
--- a/crates/gecko/src/host.rs
+++ b/crates/gecko/src/host.rs
@@ -64,6 +64,44 @@ pub enum GxAction {
height: u32,
parts: Vec<XfbPart>,
},
+
+ /// Copy an EFB region back into system RAM, encoded in a GX texture
+ /// format. The renderer does a GPU readback, converts the pixels to
+ /// `copy_format`, and ships the encoded bytes back over the writeback
+ /// channel. The emu side spits them into `Mmio::ram` synchronously so
+ /// subsequent texture loads see fresh data.
+ ///
+ /// Per Dolphin (`BPFunctions::ClearScreen`), the `clear` bit on BP 0x52
+ /// only affects channels whose write mask is enabled. We carry the
+ /// current `color_update`/`alpha_update`/`z_update` so the backend can
+ /// gate the post-copy clear correctly; when color writes are off, the
+ /// clear must be a no-op for color?
+ CopyEfbToTexture {
+ dest_addr: Address,
+ src_x: u32,
+ src_y: u32,
+ src_w: u32,
+ src_h: u32,
+ copy_format: u8,
+ mipmap: bool,
+ stride: u32,
+ clear: bool,
+ clear_color: [f32; 4],
+ clear_z: f32,
+ color_update: bool,
+ alpha_update: bool,
+ z_update: bool,
+ },
+}
+
+/// 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.
+#[derive(Debug)]
+pub struct EfbWriteback {
+ pub dest_addr: Address,
+ pub bytes: Vec<u8>,
}
/// Identifies one tile in a composited XFB frame. The `id` matches the
diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rs
index b0205b3..c64bc92 100644
--- a/crates/tinyapp/src/main.rs
+++ b/crates/tinyapp/src/main.rs
@@ -138,6 +138,10 @@ fn main() {
// Install the renderer as the emulator's render sink.
emulator.render_sink = Box::new(renderer.clone());
+ // Install the EFB-to-texture writeback receiver so the emu thread
+ // can copy encoded texture bytes back into RAM after each readback.
+ emulator.gx.efb_writeback_rx = renderer.take_writeback_rx();
+
let input = Arc::new(Mutex::new(*emulator.primary_controller_mut()));
let (frame_tx, frame_rx) = bounded::<thread::FrameMessage>(2);
diff --git a/submodules/beanwii b/submodules/beanwii
new file mode 160000
index 0000000..901c414
--- /dev/null
+++ b/submodules/beanwii
@@ -0,0 +1 @@
+Subproject commit 901c414e8355401582eb3f01abf71666b9cfbb73