Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

textures are no core-controlled, no more cloning RAM!

Layle4e0f4b3be90d
diff --git a/Cargo.lock b/Cargo.lock
index 73ef766..63e0bf8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1236,6 +1236,7 @@ dependencies = [
"glam",
"image 0.1.0",
"tracing",
+ "twox-hash",
]
[[package]]
@@ -2632,6 +2633,15 @@ dependencies = [
"zerovec",
]
+[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
[[package]]
name = "precomputed-hash"
version = "0.1.1"
@@ -2704,6 +2714,35 @@ version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+[[package]]
+name = "rand"
+version = "0.9.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ec095654a25171c2124e9e3393a930bddbffdc939556c914957a4c3e0a87166"
+dependencies = [
+ "rand_chacha",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
+dependencies = [
+ "ppv-lite86",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
+dependencies = [
+ "getrandom",
+]
+
[[package]]
name = "range-alloc"
version = "0.1.5"
@@ -3491,6 +3530,15 @@ version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
+[[package]]
+name = "twox-hash"
+version = "2.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ea3136b675547379c4bd395ca6b938e5ad3c3d20fad76e7fe85f9e0d011419c"
+dependencies = [
+ "rand",
+]
+
[[package]]
name = "type-map"
version = "0.5.1"
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rs
index 18bf583..7f3681f 100644
--- a/crates/backend-wgpu/src/action.rs
+++ b/crates/backend-wgpu/src/action.rs
@@ -1,8 +1,7 @@
use crate::pipeline::PipelineKey;
-use crate::{BindGroupCacheKey, DrawUniforms, FrameUniforms, GxRenderer, helpers, texture};
+use crate::{BindGroupCacheKey, DrawUniforms, FrameUniforms, GxRenderer, SamplerKey, helpers};
use crate::{GpuVertex, align_up};
use encase::{ShaderType as _, UniformBuffer};
-use gecko::flipper::gx::draw::TextureDescriptor;
use gecko::flipper::gx::regs::{MagFilter, MinFilter, WrapMode};
use gecko::host::{DrawData, GxAction};
use glam::{Mat4, UVec4, Vec4};
@@ -37,20 +36,15 @@ impl GxRenderer {
/// Build a bind-group cache key from the current tracked textures.
fn current_bind_group_key(&self) -> BindGroupCacheKey {
- let mut tex_keys = [None; 8];
- let mut sampler_keys = [None; 8];
- for slot in 0..8 {
- if let Some(desc) = &self.current_textures[slot] {
- tex_keys[slot] = Some((desc.ram_addr, desc.width, desc.height, desc.format));
- sampler_keys[slot] = Some((desc.wrap_s, desc.wrap_t, desc.mag_filter, desc.min_filter));
- }
+ BindGroupCacheKey {
+ tex_keys: self.current_texture_ids,
+ sampler_keys: self.current_sampler_keys,
}
- BindGroupCacheKey { tex_keys, sampler_keys }
}
/// Process a batch of [`GxAction`] values, rendering draw calls into the
/// internal EFB and handling EFB copies / XFB presentation.
- pub fn render_actions(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, actions: &[GxAction], ram: &[u8]) {
+ pub fn render_actions(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, actions: &[GxAction]) {
self.scratch_vertices.clear();
self.scratch_draws.clear();
self.scratch_uniform_bytes.clear();
@@ -92,21 +86,65 @@ impl GxRenderer {
GxAction::SetAlphaCompare(ac) => {
self.current_alpha_compare = *ac;
}
- GxAction::SetTexture { slot, descriptor } => {
- self.current_textures[*slot] = Some(*descriptor);
+ GxAction::LoadTexture {
+ id,
+ width,
+ height,
+ rgba,
+ } => {
+ let tex = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("gx_tex"),
+ size: wgpu::Extent3d {
+ width: *width,
+ height: *height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
+ queue.write_texture(
+ tex.as_image_copy(),
+ rgba,
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(*width * 4),
+ rows_per_image: None,
+ },
+ wgpu::Extent3d {
+ width: *width,
+ height: *height,
+ depth_or_array_layers: 1,
+ },
+ );
+ let view = tex.create_view(&Default::default());
+ // Invalidate bind groups that referenced the old texture.
+ let tid = *id;
+ self.bind_group_cache
+ .retain(|key, _| !key.tex_keys.iter().any(|k| *k == Some(tid)));
+ self.texture_cache.insert(*id, (tex, view));
+ }
+ GxAction::SetTexture {
+ slot,
+ id,
+ wrap_s,
+ wrap_t,
+ mag_filter,
+ min_filter,
+ } => {
+ self.current_texture_ids[*slot] = Some(*id);
+ let sampler_key: SamplerKey = (*wrap_s, *wrap_t, *mag_filter, *min_filter);
+ self.current_sampler_keys[*slot] = Some(sampler_key);
+ self.ensure_sampler(device, &sampler_key);
}
GxAction::SetCullMode(mode) => {
self.current_cull_mode = *mode;
}
GxAction::Draw(draw) => {
- // Copy tracked textures to avoid borrow conflict with &mut self.
- let tex_snapshot = self.current_textures;
- for desc in tex_snapshot.iter().flatten() {
- self.ensure_texture(device, queue, ram, desc);
- self.ensure_sampler(device, desc);
- }
-
// Ensure pipeline for current tracked blend/depth state.
let pipeline_key = self.current_pipeline_key();
if !self.pipeline_cache.contains_key(&pipeline_key) {
@@ -313,8 +351,8 @@ impl GxRenderer {
let mut tex_samplers: [&wgpu::Sampler; 8] = [&self.sampler_cache[&fallback_sampler_key]; 8];
for slot in 0..8 {
- if let Some(tk) = &bg_key.tex_keys[slot] {
- if let Some((_, view)) = self.texture_cache.get(tk) {
+ if let Some(tid) = &bg_key.tex_keys[slot] {
+ if let Some((_, view)) = self.texture_cache.get(tid) {
tex_views[slot] = view;
}
if let Some(sk) = &bg_key.sampler_keys[slot] {
@@ -412,11 +450,13 @@ impl GxRenderer {
let draw_offset = (index as u64 * self.draw_uniform_stride) as u32;
rpass.set_bind_group(0, bind_group, &[frame_offset, draw_offset]);
- // TODO: verify?
let vp = &viewports[index];
- let vp_w = vp.w.max(1.0);
- let vp_h = vp.h.max(1.0);
- rpass.set_viewport(vp.x, vp.y, vp_w, vp_h, vp.min_depth, vp.max_depth);
+ let max_dim = target_width.max(target_height) as f32;
+ let vp_w = vp.w.clamp(1.0, max_dim);
+ let vp_h = vp.h.clamp(1.0, max_dim);
+ if vp.x.is_finite() && vp.y.is_finite() && vp_w.is_finite() && vp_h.is_finite() {
+ rpass.set_viewport(vp.x, vp.y, vp_w, vp_h, vp.min_depth, vp.max_depth);
+ }
let sc = &scissors[index];
let sc_w = sc.w.max(1).min(target_width.saturating_sub(sc.x));
@@ -430,16 +470,8 @@ impl GxRenderer {
queue.submit([encoder.finish()]);
}
- fn ensure_texture(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, ram: &[u8], desc: &TextureDescriptor) {
- let key = (desc.ram_addr, desc.width, desc.height, desc.format);
- self.texture_cache
- .entry(key)
- .or_insert_with(|| texture::upload_texture(device, queue, ram, desc));
- }
-
- fn ensure_sampler(&mut self, device: &wgpu::Device, desc: &TextureDescriptor) {
- let key = (desc.wrap_s, desc.wrap_t, desc.mag_filter, desc.min_filter);
- self.sampler_cache.entry(key).or_insert_with(|| {
+ fn ensure_sampler(&mut self, device: &wgpu::Device, key: &SamplerKey) {
+ self.sampler_cache.entry(*key).or_insert_with(|| {
device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("gx_sampler"),
address_mode_u: helpers::map_wrap_mode(key.0),
diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rs
index f2d2adc..20f5c0a 100644
--- a/crates/backend-wgpu/src/lib.rs
+++ b/crates/backend-wgpu/src/lib.rs
@@ -4,12 +4,11 @@ mod helpers;
mod pipeline;
mod render;
pub mod sink;
-pub mod texture;
use encase::ShaderType as _;
-use gecko::flipper::gx::draw::TextureFormat;
-use gecko::flipper::gx::draw::{Scissor, TextureDescriptor, Viewport};
+use gecko::flipper::gx::draw::{Scissor, Viewport};
use gecko::flipper::gx::regs::{AlphaCompare, BlendMode, CompareFunc, CullMode, MagFilter, MinFilter, WrapMode, ZMode};
+use gecko::host::TextureId;
use glam::Mat4;
use pipeline::PipelineKey;
use std::collections::HashMap;
@@ -36,12 +35,11 @@ pub(crate) fn align_up(value: u64, alignment: u64) -> u64 {
(value + alignment - 1) & !(alignment - 1)
}
-type TexKey = (usize, u32, u32, TextureFormat);
type SamplerKey = (WrapMode, WrapMode, MagFilter, MinFilter);
#[derive(Clone, PartialEq, Eq, Hash)]
pub(crate) struct BindGroupCacheKey {
- tex_keys: [Option<TexKey>; 8],
+ tex_keys: [Option<TextureId>; 8],
sampler_keys: [Option<SamplerKey>; 8],
}
@@ -106,7 +104,7 @@ pub struct GxRenderer {
pub(crate) efb_depth_view: wgpu::TextureView,
pub(crate) efb_needs_clear: bool,
pub(crate) sampler_cache: HashMap<(WrapMode, WrapMode, MagFilter, MinFilter), wgpu::Sampler>,
- pub(crate) texture_cache: HashMap<(usize, u32, u32, TextureFormat), (wgpu::Texture, wgpu::TextureView)>,
+ pub(crate) texture_cache: HashMap<TextureId, (wgpu::Texture, wgpu::TextureView)>,
pub(crate) fallback_view: wgpu::TextureView,
pub(crate) scratch_vertices: Vec<GpuVertex>,
pub(crate) scratch_draws: Vec<(u32, u32)>,
@@ -120,7 +118,8 @@ pub struct GxRenderer {
pub(crate) current_blend_mode: BlendMode,
pub(crate) current_alpha_compare: AlphaCompare,
pub(crate) current_cull_mode: CullMode,
- pub(crate) current_textures: [Option<TextureDescriptor>; 8],
+ pub(crate) current_texture_ids: [Option<TextureId>; 8],
+ pub(crate) current_sampler_keys: [Option<SamplerKey>; 8],
// Blit pipeline (EFB -> swapchain)
pub(crate) blit_pipeline: wgpu::RenderPipeline,
pub(crate) blit_bind_group_layout: wgpu::BindGroupLayout,
@@ -448,7 +447,8 @@ impl GxRenderer {
current_alpha_compare: AlphaCompare::from_raw(0)
.with_comp0(CompareFunc::Always)
.with_comp1(CompareFunc::Always),
- current_textures: Default::default(),
+ current_texture_ids: Default::default(),
+ current_sampler_keys: Default::default(),
blit_pipeline,
blit_bind_group_layout,
blit_sampler,
diff --git a/crates/gecko/Cargo.toml b/crates/gecko/Cargo.toml
index 4091203..96d3a98 100644
--- a/crates/gecko/Cargo.toml
+++ b/crates/gecko/Cargo.toml
@@ -17,3 +17,4 @@ tracing = { version = "0.1.44", features = ["release_max_level_off"] }
image = { path = "../image" }
glam = { version = "0.32.1", features = ["bytemuck"] }
bytemuck = { version = "1.25.0", features = ["derive"] }
+twox-hash = "2.1.2"
diff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rs
index b8b0494..537b10a 100644
--- a/crates/gecko/src/flipper/gx.rs
+++ b/crates/gecko/src/flipper/gx.rs
@@ -6,9 +6,12 @@ pub mod math;
pub mod regs;
pub mod tev;
mod texgen;
+pub mod texture;
mod vertex;
mod xf;
+use std::collections::HashMap;
+
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};
@@ -52,6 +55,9 @@ pub struct GraphicsProcessor {
// XFB copies accumulated since the last vblank. `present_xfb()` drains
// this at each field boundary to emit a PresentXfb action.
pub xfb_copies: Vec<XfbCopy>,
+ // 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>,
}
/// A single EFB-to-XFB copy, stored until `present_xfb` computes the layout.
@@ -91,6 +97,7 @@ impl GraphicsProcessor {
cur_scissor_offset_x: 0,
cur_scissor_offset_y: 0,
xfb_copies: Vec::new(),
+ texture_hashes: HashMap::new(),
}
}
@@ -114,7 +121,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, &data),
+ FifoCmd::Bp(data) => self.load_bp(renderer, &mmio.ram, &data),
FifoCmd::CallDisplayList { phys_addr, nbytes } => {
let addr = (phys_addr & 0x3FFFFFFF) as usize;
let len = nbytes as usize;
diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rs
index 36c1ab8..12d1629 100644
--- a/crates/gecko/src/flipper/gx/bp.rs
+++ b/crates/gecko/src/flipper/gx/bp.rs
@@ -11,11 +11,11 @@ use super::regs::{
PeClearZ, PeCopyCmd, SuScisOffset, SuScisRect, TevAlphaEnv, TevColorEnv, TevOrder, TevRegType, TevRegisterH,
TevRegisterL, TxSetImage0, TxSetImage3, TxSetMode0, ZMode,
};
-use super::{GraphicsProcessor, draw};
-use crate::host::{GxAction, RenderSink};
+use super::{GraphicsProcessor, draw, texture};
+use crate::host::{GxAction, RenderSink, TextureId};
impl GraphicsProcessor {
- pub fn load_bp(&mut self, renderer: &mut dyn RenderSink, data: &[u8]) {
+ pub fn load_bp(&mut self, renderer: &mut dyn RenderSink, ram: &[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;
@@ -37,7 +37,7 @@ impl GraphicsProcessor {
};
if let Some(slot) = texture_slot {
- self.snapshot_texture(renderer, slot, val);
+ self.snapshot_texture(renderer, ram, slot, val);
}
// Forward PE render state
@@ -132,7 +132,7 @@ impl GraphicsProcessor {
}
}
- fn snapshot_texture(&mut self, renderer: &mut dyn RenderSink, slot: usize, image3_val: u32) {
+ fn snapshot_texture(&mut self, renderer: &mut dyn RenderSink, ram: &[u8], slot: usize, image3_val: u32) {
let image0_reg = if slot < 4 {
BP_TX_SETIMAGE0_I0 + slot
} else {
@@ -149,26 +149,49 @@ impl GraphicsProcessor {
};
let mode0 = TxSetMode0::from_raw(self.bp_regs[mode0_reg]);
- let width = image0.width() + 1;
- let height = image0.height() + 1;
+ let width = (image0.width() + 1) as u32;
+ let height = (image0.height() + 1) as u32;
let ram_addr = image3.ram_addr();
+ let format = image0.format();
+ let id = TextureId(ram_addr as u32);
tracing::debug!(
slot,
width,
height,
- format = format!("{:?}", image0.format()),
+ format = format!("{:?}", format),
ram_addr = format!("{ram_addr:#010X}"),
wrap_s = format!("{:?}", mode0.wrap_s()),
wrap_t = format!("{:?}", mode0.wrap_t()),
"texture descriptor updated"
);
+ let changed = self::texture_data_changed(&mut self.texture_hashes, ram, ram_addr, width, height, format);
+
+ if changed {
+ let desc = draw::TextureDescriptor {
+ ram_addr,
+ width,
+ height,
+ format,
+ wrap_s: mode0.wrap_s(),
+ wrap_t: mode0.wrap_t(),
+ mag_filter: mode0.mag_filter(),
+ min_filter: mode0.min_filter(),
+ };
+ renderer.exec(GxAction::LoadTexture {
+ id,
+ width,
+ height,
+ rgba: texture::decode_to_rgba(ram, &desc)
+ });
+ }
+
self.cur_textures[slot] = Some(draw::TextureDescriptor {
ram_addr,
- width: width as u32,
- height: height as u32,
- format: image0.format(),
+ width,
+ height,
+ format,
wrap_s: mode0.wrap_s(),
wrap_t: mode0.wrap_t(),
mag_filter: mode0.mag_filter(),
@@ -177,7 +200,11 @@ impl GraphicsProcessor {
renderer.exec(GxAction::SetTexture {
slot,
- descriptor: self.cur_textures[slot].unwrap(),
+ id,
+ wrap_s: mode0.wrap_s(),
+ wrap_t: mode0.wrap_t(),
+ mag_filter: mode0.mag_filter(),
+ min_filter: mode0.min_filter(),
});
}
@@ -358,3 +385,22 @@ impl GraphicsProcessor {
self.cur_scissor_offset_y = reg.y() as i32 * 2 - 342;
}
}
+
+/// Returns `true` when the raw texture data in RAM differs from the last
+/// hash recorded for the given address.
+fn texture_data_changed(
+ hashes: &mut std::collections::HashMap<u32, u64>,
+ ram: &[u8],
+ addr: usize,
+ width: u32,
+ height: u32,
+ format: draw::TextureFormat,
+) -> bool {
+ let size = texture::raw_data_size(width, height, format);
+ let Some(slice) = ram.get(addr..addr + size) else {
+ return true;
+ };
+ let hash = twox_hash::xxhash3_64::Hasher::oneshot(slice);
+ let prev = hashes.insert(addr as u32, hash);
+ prev != Some(hash)
+}
diff --git a/crates/backend-wgpu/src/texture.rs b/crates/gecko/src/flipper/gx/texture.rs
similarity index 90%
rename from crates/backend-wgpu/src/texture.rs
rename to crates/gecko/src/flipper/gx/texture.rs
index 936573a..75a0210 100644
--- a/crates/backend-wgpu/src/texture.rs
+++ b/crates/gecko/src/flipper/gx/texture.rs
@@ -1,5 +1,6 @@
-use gecko::flipper::gx::draw::{TextureDescriptor, TextureFormat};
+use super::draw::{TextureDescriptor, TextureFormat};
+/// Decode a GX-format texture from RAM into RGBA8 pixels.
pub fn decode_to_rgba(ram: &[u8], desc: &TextureDescriptor) -> Vec<u8> {
let w = desc.width as usize;
let h = desc.height as usize;
@@ -14,50 +15,30 @@ pub fn decode_to_rgba(ram: &[u8], desc: &TextureDescriptor) -> Vec<u8> {
TextureFormat::RGB5A3 => decode_rgb5a3(ram, desc, &mut rgba, w, h),
TextureFormat::RGBA8 => decode_rgba8(ram, desc, &mut rgba, w, h),
TextureFormat::CMPR => decode_cmpr(ram, desc, &mut rgba, w, h),
- _ => panic!("Unsupported texture format: {:?}", desc.format),
+ _ => tracing::error!(?desc.format, "unsupported texture format"),
}
rgba
}
-pub fn upload_texture(
- device: &wgpu::Device,
- queue: &wgpu::Queue,
- ram: &[u8],
- desc: &TextureDescriptor,
-) -> (wgpu::Texture, wgpu::TextureView) {
- let rgba = decode_to_rgba(ram, desc);
-
- let tex = device.create_texture(&wgpu::TextureDescriptor {
- label: Some("gx_tex"),
- size: wgpu::Extent3d {
- width: desc.width,
- height: desc.height,
- depth_or_array_layers: 1,
- },
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::Rgba8Unorm,
- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
- view_formats: &[],
- });
- queue.write_texture(
- tex.as_image_copy(),
- &rgba,
- wgpu::TexelCopyBufferLayout {
- offset: 0,
- bytes_per_row: Some(desc.width * 4),
- rows_per_image: None,
- },
- wgpu::Extent3d {
- width: desc.width,
- height: desc.height,
- depth_or_array_layers: 1,
- },
- );
- let view = tex.create_view(&Default::default());
- (tex, view)
+/// 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 {
+ TextureFormat::I4 => (8, 8, 32),
+ TextureFormat::I8 => (8, 4, 32),
+ TextureFormat::IA4 => (8, 4, 32),
+ TextureFormat::IA8 => (4, 4, 32),
+ TextureFormat::RGB565 => (4, 4, 32),
+ TextureFormat::RGB5A3 => (4, 4, 32),
+ TextureFormat::RGBA8 => (4, 4, 64),
+ TextureFormat::CMPR => (8, 8, 32),
+ TextureFormat::CI4 => (8, 8, 32),
+ 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
}
#[inline(always)]
@@ -87,10 +68,6 @@ fn rgb565_to_rgba(packed: u16) -> [u8; 4] {
]
}
-// GX textures are stored in a tiled layout. The image is divided into
-// fixed-size blocks (e.g. 4x4 or 8x8 pixels). Blocks are stored left-to-right,
-// top-to-bottom, and within each block pixels are also stored row by row.
-
fn decode_i4(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
const BLOCK_W: usize = 8;
const BLOCK_H: usize = 8;
diff --git a/crates/gecko/src/gamecube.rs b/crates/gecko/src/gamecube.rs
index 2d7915e..6e7757a 100644
--- a/crates/gecko/src/gamecube.rs
+++ b/crates/gecko/src/gamecube.rs
@@ -247,7 +247,7 @@ impl GameCube {
pub fn run_until_vsync(&mut self) {
self.prepare_frame();
while !self.vsync_pending {
- self.scheduler.update_deadline();
+ self.scheduler.refresh_deadline();
// Execute a slice of CPU instructions until the next event deadline
while self.scheduler.cycles < self.scheduler.next_deadline() {
self.step_cpu();
diff --git a/crates/gecko/src/host.rs b/crates/gecko/src/host.rs
index 5163b76..2572669 100644
--- a/crates/gecko/src/host.rs
+++ b/crates/gecko/src/host.rs
@@ -1,5 +1,9 @@
-use crate::flipper::gx::draw::{EfbCopyCmd, Primitive, Scissor, TextureDescriptor, Viewport};
-use crate::flipper::gx::regs::{AlphaCompare, BlendMode, ChanCtrl, CullMode, ZMode};
+use crate::flipper::gx::draw::{EfbCopyCmd, Primitive, Scissor, Viewport};
+use crate::flipper::gx::regs::{AlphaCompare, BlendMode, ChanCtrl, CullMode, MagFilter, MinFilter, WrapMode, ZMode};
+
+/// Identifies a texture by its RAM base address.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct TextureId(pub u32);
#[derive(Debug)]
pub enum GxAction {
@@ -16,9 +20,24 @@ pub enum GxAction {
SetBlendMode(BlendMode),
SetAlphaCompare(AlphaCompare),
SetCullMode(CullMode),
+
+ /// Upload pre-decoded texture data. Emitted when texture content at a
+ /// given address changes (detected by hash).
+ LoadTexture {
+ id: TextureId,
+ width: u32,
+ height: u32,
+ rgba: Vec<u8>,
+ },
+
+ /// Bind a previously loaded texture to a TEV texture slot.
SetTexture {
slot: usize,
- descriptor: TextureDescriptor,
+ id: TextureId,
+ wrap_s: WrapMode,
+ wrap_t: WrapMode,
+ mag_filter: MagFilter,
+ min_filter: MinFilter,
},
/// Issue a draw call. The renderer uses its tracked state (projection,
diff --git a/crates/gecko/src/scheduler.rs b/crates/gecko/src/scheduler.rs
index 6d69a87..56c3d33 100644
--- a/crates/gecko/src/scheduler.rs
+++ b/crates/gecko/src/scheduler.rs
@@ -40,18 +40,10 @@ impl Scheduler {
}
#[inline(always)]
- fn refresh_deadline(&mut self) {
+ pub fn refresh_deadline(&mut self) {
self.next_deadline = self.events.front().map_or(u64::MAX, |e| e.deadline);
}
- /// Set `next_deadline` to the next event deadline so the CPU knows
- /// how far it can run before an event must be serviced.
- /// This may later be updated if an event is scheduled sooner than the current target.
- #[inline(always)]
- pub fn update_deadline(&mut self) {
- self.refresh_deadline();
- }
-
pub fn timebase(&self) -> u64 {
((self.cycles / TIMEBASE_DIVISOR) as i64 + self.timebase_offset) as u64
}
diff --git a/crates/tinyapp/src/app.rs b/crates/tinyapp/src/app.rs
index da0c612..0c26c12 100644
--- a/crates/tinyapp/src/app.rs
+++ b/crates/tinyapp/src/app.rs
@@ -136,7 +136,6 @@ impl State {
};
let view = frame.texture.create_view(&Default::default());
- let ram = msg.ram;
self.action_buf.clear();
self.action_rx.drain(&mut self.action_buf);
@@ -144,7 +143,7 @@ impl State {
// and updates the snapshot on CopyEfb).
if !self.action_buf.is_empty() {
self.gx_renderer
- .render_actions(&self.device, &self.queue, &self.action_buf, &ram);
+ .render_actions(&self.device, &self.queue, &self.action_buf);
}
// Blit the latest EFB snapshot to the swapchain.
diff --git a/crates/tinyapp/src/thread.rs b/crates/tinyapp/src/thread.rs
index ceec883..e4280ae 100644
--- a/crates/tinyapp/src/thread.rs
+++ b/crates/tinyapp/src/thread.rs
@@ -7,9 +7,6 @@ use std::sync::{Arc, Mutex};
use winit::event_loop::EventLoopProxy;
pub struct FrameMessage {
- /// Guest RAM snapshot so the renderer can upload textures referenced by
- /// the actions in the channel.
- pub ram: Vec<u8>,
pub native_hz: f64,
}
@@ -28,13 +25,7 @@ pub fn emu_thread(
RefreshRate::Hz50 => 50.0,
};
- if frame_tx
- .send(FrameMessage {
- ram: emulator.mmio.ram.clone(),
- native_hz,
- })
- .is_err()
- {
+ if frame_tx.send(FrameMessage { native_hz }).is_err() {
break;
}
let _ = proxy.send_event(());