Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

many fixes for cpu. texture cache fixed. tev swap table. fifo streaming

Layled8c5882e7543
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rs
index 81192d1..438760a 100644
--- a/crates/backend-wgpu/src/action.rs
+++ b/crates/backend-wgpu/src/action.rs
@@ -1,5 +1,5 @@
use crate::pipeline::PipelineKey;
-use crate::{BindGroupCacheKey, DrawUniforms, FrameUniforms, GpuVertex, GxRenderer, SamplerKey, helpers};
+use crate::{BindGroupCacheKey, DrawUniforms, FrameUniforms, GpuVertex, GxRenderer, SamplerKey, helpers, ram_addr_of};
use encase::{ShaderType as _, UniformBuffer};
use gecko::flipper::gx::regs::{MagFilter, MinFilter, WrapMode};
use gecko::host::{DrawData, GxAction};
@@ -76,7 +76,7 @@ impl GxRenderer {
fmt,
rgba,
} => {
- let texture_label = format!("gx_tex addr={:#010x} fmt={:?} size={}x{}", *id, *fmt, *width, *height);
+ let texture_label = format!("gx_tex id={:#018x} fmt={:?} size={}x{}", *id, *fmt, *width, *height);
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some(&texture_label),
size: wgpu::Extent3d {
@@ -109,15 +109,19 @@ impl GxRenderer {
);
let view = tex.create_view(&Default::default());
- // Invalidate bind groups that referenced the old texture.
+ // Invalidate bind groups that referenced the old entry for
+ // this exact cache id (variant-specific).
let tid = *id;
self.bind_group_cache
.retain(|key, _| !key.tex_keys.iter().any(|k| *k == Some(tid)));
// 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.
- if let Some((old_tex, old_view)) = self.efb_copy_cache.remove(&tid) {
+ // 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 the bare ram_addr, so strip the TLUT
+ // variant bits before looking up.
+ let ram_addr = ram_addr_of(tid);
+ if let Some((old_tex, old_view)) = self.efb_copy_cache.remove(&ram_addr) {
self.return_to_pool(old_tex, old_view);
}
@@ -190,6 +194,7 @@ impl GxRenderer {
tev_color_env: pack_u32_slice_to_uvec4x4(&draw.tev_color_env),
tev_alpha_env: pack_u32_slice_to_uvec4x4(&draw.tev_alpha_env),
tev_orders: pack_u32_slice_to_uvec4x4(&draw.tev_orders),
+ tev_ksel: pack_u32_slice_to_uvec4x4(&draw.tev_ksel),
num_tev_stages: draw.num_tev_stages as u32,
alpha_ref0: alpha_cmp.ref0() as f32 / 255.0,
alpha_ref1: alpha_cmp.ref1() as f32 / 255.0,
@@ -385,11 +390,10 @@ impl GxRenderer {
for slot in 0..8 {
if let Some(tid) = &bg_key.tex_keys[slot] {
- // The EFB-copy cache wins over the RAM-decoded
- // `texture_cache`.
+ let ram_addr = ram_addr_of(*tid);
let view = self
.efb_copy_cache
- .get(tid)
+ .get(&ram_addr)
.map(|(_, v)| v)
.or_else(|| self.texture_cache.get(tid).map(|(_, _, v)| v));
if let Some(view) = view {
diff --git a/crates/backend-wgpu/src/dump.rs b/crates/backend-wgpu/src/dump.rs
index 26b640e..5e26dbb 100644
--- a/crates/backend-wgpu/src/dump.rs
+++ b/crates/backend-wgpu/src/dump.rs
@@ -17,7 +17,7 @@ impl GxRenderer {
}
let mut saved = 0usize;
- for (addr, (fmt, tex, _)) in self.texture_cache.iter() {
+ for (cache_id, (fmt, tex, _)) in self.texture_cache.iter() {
let size = tex.size();
let width = size.width;
let height = size.height;
@@ -27,7 +27,7 @@ impl GxRenderer {
if tex.format() != wgpu::TextureFormat::Rgba8Unorm {
tracing::warn!(
- addr = *addr,
+ cache_id = *cache_id,
wgpu_fmt = ?tex.format(),
"dump_textures: skipping non-Rgba8Unorm texture"
);
@@ -75,7 +75,7 @@ impl GxRenderer {
submission_index: None,
timeout: Some(Duration::from_secs(5)),
}) {
- tracing::warn!(addr = *addr, ?err, "dump_textures: device poll failed");
+ tracing::warn!(cache_id = *cache_id, ?err, "dump_textures: device poll failed");
continue;
}
@@ -92,7 +92,9 @@ impl GxRenderer {
}
staging.unmap();
- let filename = format!("{millis}_{:08X}_{:?}_{}x{}.png", *addr, *fmt, width, height);
+ let ram_addr = (*cache_id) as u32;
+ let variant = (*cache_id >> 32) as u32;
+ let filename = format!("{millis}_{ram_addr:08X}_{variant:08X}_{fmt:?}_{width}x{height}.png");
let path: PathBuf = dir.join(filename);
capture::save_png_async(path, CapturedFrame { width, height, rgba }, false);
saved += 1;
diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rs
index a8f9ae5..9be22c2 100644
--- a/crates/backend-wgpu/src/lib.rs
+++ b/crates/backend-wgpu/src/lib.rs
@@ -42,9 +42,16 @@ pub(crate) fn align_up(value: u64, alignment: u64) -> u64 {
type SamplerKey = (WrapMode, WrapMode, MagFilter, MinFilter);
+pub(crate) type TextureKey = u64;
+
+#[inline(always)]
+pub(crate) fn ram_addr_of(key: TextureKey) -> Address {
+ key as Address
+}
+
#[derive(Clone, PartialEq, Eq, Hash)]
pub(crate) struct BindGroupCacheKey {
- tex_keys: [Option<Address>; 8],
+ tex_keys: [Option<TextureKey>; 8],
sampler_keys: [Option<SamplerKey>; 8],
}
@@ -55,6 +62,7 @@ pub(crate) struct FrameUniforms {
tev_color_env: [glam::UVec4; 4],
tev_alpha_env: [glam::UVec4; 4],
tev_orders: [glam::UVec4; 4],
+ tev_ksel: [glam::UVec4; 4],
num_tev_stages: u32,
alpha_ref0: f32,
alpha_ref1: f32,
@@ -121,7 +129,7 @@ pub struct GxRenderer {
pub(crate) efb_depth_view: wgpu::TextureView,
pub(crate) efb_needs_clear: bool,
pub(crate) sampler_cache: FxHashMap<(WrapMode, WrapMode, MagFilter, MinFilter), wgpu::Sampler>,
- pub(crate) texture_cache: FxHashMap<Address, (TextureFormat, wgpu::Texture, wgpu::TextureView)>,
+ pub(crate) texture_cache: FxHashMap<TextureKey, (TextureFormat, wgpu::Texture, wgpu::TextureView)>,
// 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.
@@ -156,7 +164,7 @@ pub struct GxRenderer {
pub(crate) current_blend_mode: BlendMode,
pub(crate) current_alpha_compare: AlphaCompare,
pub(crate) current_cull_mode: CullMode,
- pub(crate) current_texture_ids: [Option<Address>; 8],
+ pub(crate) current_texture_ids: [Option<TextureKey>; 8],
pub(crate) current_sampler_keys: [Option<SamplerKey>; 8],
// XFB output texture: composited from per-copy snapshots by PresentXfb.
pub xfb_texture: wgpu::Texture,
diff --git a/crates/backend-wgpu/src/render.rs b/crates/backend-wgpu/src/render.rs
index 51b5814..41ef1f0 100644
--- a/crates/backend-wgpu/src/render.rs
+++ b/crates/backend-wgpu/src/render.rs
@@ -1,4 +1,4 @@
-use crate::{FrameUniforms, GpuVertex, GxRenderer, align_up};
+use crate::{FrameUniforms, GpuVertex, GxRenderer, align_up, ram_addr_of};
use encase::ShaderType as _;
use gecko::common::Address;
#[cfg(feature = "efb-writeback")]
@@ -282,9 +282,8 @@ impl GxRenderer {
if let Some((old_tex, old_view)) = self.efb_copy_cache.remove(&dest_addr) {
self.return_to_pool(old_tex, old_view);
}
- // Drop stale bind groups that captured the old view.
self.bind_group_cache
- .retain(|key, _| !key.tex_keys.contains(&Some(dest_addr)));
+ .retain(|key, _| !key.tex_keys.iter().any(|k| k.map(ram_addr_of) == Some(dest_addr)));
let (tex, view) = self
.efb_copy_pool
@@ -415,7 +414,7 @@ impl GxRenderer {
self.return_to_pool(old_tex, old_view);
}
self.bind_group_cache
- .retain(|key, _| !key.tex_keys.contains(&Some(dest_addr)));
+ .retain(|key, _| !key.tex_keys.iter().any(|k| k.map(ram_addr_of) == Some(dest_addr)));
let (tex, view) = self
.efb_depth_pool
diff --git a/crates/backend-wgpu/src/shaders/common.wesl b/crates/backend-wgpu/src/shaders/common.wesl
index cdecd6f..5224c39 100644
--- a/crates/backend-wgpu/src/shaders/common.wesl
+++ b/crates/backend-wgpu/src/shaders/common.wesl
@@ -7,6 +7,7 @@ struct FrameUniforms {
tev_color_env: array<vec4<u32>, 4>,
tev_alpha_env: array<vec4<u32>, 4>,
tev_orders: array<vec4<u32>, 4>,
+ tev_ksel: array<vec4<u32>, 4>,
num_tev_stages: u32,
alpha_ref0: f32,
alpha_ref1: f32,
diff --git a/crates/backend-wgpu/src/shaders/main.wesl b/crates/backend-wgpu/src/shaders/main.wesl
index c5b43bc..d7e7a18 100644
--- a/crates/backend-wgpu/src/shaders/main.wesl
+++ b/crates/backend-wgpu/src/shaders/main.wesl
@@ -1,5 +1,5 @@
import super::common::{FrameUniforms, DrawUniforms, VsIn, VsOut, frame, draw, tex0, tex1, tex2, tex3, tex4, tex5, tex6, tex7, samp0, samp1, samp2, samp3, samp4, samp5, samp6, samp7};
-import super::tev_helpers::{read_packed, extract_bits, select_texcoord, stq_to_uv, sample_texmap, tev_color_in, tev_alpha_in};
+import super::tev_helpers::{read_packed, extract_bits, select_texcoord, stq_to_uv, sample_texmap, swizzle_tev_color, tev_color_in, tev_alpha_in};
import super::tev_indirect::{IndirectSamples, IndirectResult, sample_indirect_textures, apply_indirect, texmap_size};
import super::tev_combiners::{tev_combine_color, tev_combine_alpha};
import super::alpha_test::{alpha_compare, alpha_combine};
@@ -62,6 +62,7 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
let texcoord_idx = (order >> 3u) & 7u;
let tex_enabled = ((order >> 6u) & 1u) != 0u;
let ras_channel = (order >> 7u) & 7u;
+ let aenv = read_packed(frame.tev_alpha_env, stage);
// Run the stage's indirect pipeline first. It yields the final
// direct-texmap UV, the fixpoint chaining value, and any bump
@@ -94,6 +95,9 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
tex_color = vec4<f32>(1.0, 1.0, 1.0, 1.0);
}
+ ras_color = swizzle_tev_color(extract_bits(aenv, 0u, 2u), ras_color);
+ tex_color = swizzle_tev_color(extract_bits(aenv, 2u, 2u), tex_color);
+
// Combine colors
let cenv = read_packed(frame.tev_color_env, stage);
@@ -121,9 +125,6 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
// Write RGB to dest, preserve alpha
regs[c_dest] = vec4(color_result, regs[c_dest].a);
- // Combine alpha
- let aenv = read_packed(frame.tev_alpha_env, stage);
-
// TevAlphaEnv bit layout (LSB0):
// [6:4]=d [9:7]=c [12:10]=b [15:13]=a
// [17:16]=bias [18]=sub [19]=clamp [21:20]=scale [23:22]=dest
diff --git a/crates/backend-wgpu/src/shaders/tev_helpers.wesl b/crates/backend-wgpu/src/shaders/tev_helpers.wesl
index c9e85ba..f61e8d5 100644
--- a/crates/backend-wgpu/src/shaders/tev_helpers.wesl
+++ b/crates/backend-wgpu/src/shaders/tev_helpers.wesl
@@ -1,4 +1,4 @@
-import super::common::{VsOut, tex0, tex1, tex2, tex3, tex4, tex5, tex6, tex7, samp0, samp1, samp2, samp3, samp4, samp5, samp6, samp7};
+import super::common::{VsOut, frame, tex0, tex1, tex2, tex3, tex4, tex5, tex6, tex7, samp0, samp1, samp2, samp3, samp4, samp5, samp6, samp7};
// Index into a packed array<vec4<u32>, 4> by flat index
fn read_packed(arr: array<vec4<u32>, 4>, idx: u32) -> u32 {
@@ -11,6 +11,31 @@ fn extract_bits(val: u32, lo: u32, width: u32) -> u32 {
return (val >> lo) & ((1u << width) - 1u);
}
+fn select_color_channel(color: vec4<f32>, channel: u32) -> f32 {
+ switch channel {
+ case 0u: { return color.r; }
+ case 1u: { return color.g; }
+ case 2u: { return color.b; }
+ default: { return color.a; }
+ }
+}
+
+fn swizzle_tev_color(swap_table: u32, color: vec4<f32>) -> vec4<f32> {
+ let rg = read_packed(frame.tev_ksel, swap_table * 2u);
+ let ba = read_packed(frame.tev_ksel, swap_table * 2u + 1u);
+ let r = extract_bits(rg, 0u, 2u);
+ let g = extract_bits(rg, 2u, 2u);
+ let b = extract_bits(ba, 0u, 2u);
+ let a = extract_bits(ba, 2u, 2u);
+
+ return vec4<f32>(
+ select_color_channel(color, r),
+ select_color_channel(color, g),
+ select_color_channel(color, b),
+ select_color_channel(color, a),
+ );
+}
+
fn select_texcoord(in: VsOut, idx: u32) -> vec3<f32> {
switch idx {
case 0u: { return in.uv0; }
diff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rs
index 41d657b..d320c2c 100644
--- a/crates/gecko/src/flipper/gx.rs
+++ b/crates/gecko/src/flipper/gx.rs
@@ -18,7 +18,6 @@ use crate::host::EfbWriteback;
use crate::host::{GxAction, RenderSink, XfbPart};
use crate::mmio::Mmio;
use crate::system::{System, SystemId};
-use fifo::FifoCmd;
use rustc_hash::FxHashMap;
pub struct GraphicsProcessor {
@@ -71,9 +70,11 @@ 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: FxHashMap<u32, u64>,
+ // Hash of the raw texture data at each (ram_addr, tlut_variant) cache id;
+ // used to detect when texture content changes and avoid redundant
+ // decodes + LoadTexture sends. Keyed by the same u64 cache id sent to
+ // the renderer in [`GxAction::LoadTexture`].
+ pub texture_hashes: FxHashMap<u64, 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
@@ -165,44 +166,6 @@ impl GraphicsProcessor {
self.drain_fifo(mmio, renderer);
}
- fn drain_fifo<const SYSTEM: SystemId>(&mut self, mmio: &mut Mmio<SYSTEM>, renderer: &mut dyn RenderSink) {
- for cmd in self.drain() {
- match cmd {
- FifoCmd::Cp(data) => self.load_cp(&data),
- FifoCmd::Xf(data) => self.load_xf(renderer, &data),
- FifoCmd::Bp(data) => {
- let mut view = mmio.ram_view_mut();
- self.load_bp(renderer, &mut view, &data);
- }
- FifoCmd::LoadIndexedXf {
- cp_array_index,
- index,
- xf_addr,
- xf_count,
- } => {
- let view = mmio.ram_view();
- self.load_indexed_xf(renderer, &view, cp_array_index, index, xf_addr, xf_count);
- }
- FifoCmd::CallDisplayList { phys_addr, nbytes } => {
- let addr = (phys_addr & 0x3FFFFFFF) as usize;
- let len = nbytes as usize;
- let view = mmio.ram_view();
- let Some(slice) = view.slice(addr, len) else {
- tracing::warn!(
- addr = format!("{addr:#010X}"),
- len,
- "CallDisplayList: source not mapped to MEM1/MEM2, skipping"
- );
- continue;
- };
- let dl = slice.to_vec();
- self.execute_display_list(mmio, renderer, &dl);
- }
- FifoCmd::DrawCall(cmd, data) => self.create_draw_call(mmio, renderer, cmd, data),
- }
- }
- }
-
fn execute_display_list<const SYSTEM: SystemId>(
&mut self,
mmio: &mut Mmio<SYSTEM>,
diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rs
index 3c19c2e..5d3c08a 100644
--- a/crates/gecko/src/flipper/gx/bp.rs
+++ b/crates/gecko/src/flipper/gx/bp.rs
@@ -1,7 +1,6 @@
use super::constants::*;
use super::regs::*;
use super::{GraphicsProcessor, draw, texture};
-use crate::common::Address;
use crate::host::{GxAction, RenderSink};
use crate::mmio::{RamView, RamViewMut};
#[cfg(feature = "efb-writeback")]
@@ -238,6 +237,13 @@ impl GraphicsProcessor {
let tlut = self.cur_tluts[slot];
let palette = slot_palette(&self.palette_mem, tlut.tmem_offset);
+ // Cache id mixes the bound TLUT identity into the high 32 bits so
+ // the same CI* texture bound with two different palettes (FFCC
+ // title logo binds the same RAM bytes via slot 0 RGB5A3@512 and
+ // slot 1 IA8@528 every frame) doesn't clobber a single GPU side
+ // entry on each rebind.
+ let cache_id = self::texture_cache_id(ram_addr, format, tlut);
+
// Resolve the texture's raw bytes once, against MEM1 or MEM2. If the
// address doesn't fall in either bank, leave the slot's last binding
// alone but skip the decode (the renderer will keep its previous
@@ -246,9 +252,7 @@ impl GraphicsProcessor {
let tex_slice = ram.slice(ram_addr, raw_size);
let changed = match tex_slice {
- Some(tex) => {
- self::texture_data_changed(&mut self.texture_hashes, tex, ram_addr as u32, palette, tlut, format)
- }
+ Some(tex) => self::texture_data_changed(&mut self.texture_hashes, tex, cache_id, palette, tlut, format),
None => {
tracing::warn!(
addr = format!("{ram_addr:#010X}"),
@@ -271,7 +275,7 @@ impl GraphicsProcessor {
min_filter: mode0.min_filter(),
};
renderer.exec(GxAction::LoadTexture {
- id: ram_addr as Address,
+ id: cache_id,
width,
height,
fmt: format,
@@ -292,7 +296,7 @@ impl GraphicsProcessor {
renderer.exec(GxAction::SetTexture {
slot,
- id: ram_addr as Address,
+ id: cache_id,
wrap_s: mode0.wrap_s(),
wrap_t: mode0.wrap_t(),
mag_filter: mode0.mag_filter(),
@@ -493,9 +497,13 @@ impl GraphicsProcessor {
depth_copy: self.cur_pe_control.pixel_format().is_depth_only(),
});
- // Writeback overwrites RAM, so drop the hash to force a re-decode. The default path keeps it GPU-side.
+ // 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")]
- self.texture_hashes.remove(&dest_addr);
+ {
+ let dest_addr_lo = dest_addr as u64;
+ self.texture_hashes.retain(|k, _| (*k & 0xFFFFFFFF) != dest_addr_lo);
+ }
let _ = ram;
// With `efb-writeback`: block until the renderer finishes the
@@ -566,13 +574,30 @@ fn slot_palette(palette_mem: &[u16], tmem_offset: u16) -> &[u16] {
palette_mem.get(base..).unwrap_or(&[])
}
+/// Mint the `(ram_addr, tlut_variant)` cache key sent to the renderer.
+/// Low 32 bits = ram_addr, high 32 bits = TLUT identity (0 for non-paletted).
+/// Variant fits in 12 bits (10 for tmem_offset, 2 for format) but we leave
+/// room for future expansion.
+#[inline(always)]
+fn texture_cache_id(ram_addr: usize, format: draw::TextureFormat, tlut: draw::TlutRef) -> u64 {
+ let lo = (ram_addr as u32) as u64;
+ let hi = if format.is_paletted() {
+ ((tlut.format as u32) << 16 | (tlut.tmem_offset as u32 & 0x3FF)) as u64
+ } else {
+ 0
+ };
+ (hi << 32) | lo
+}
+
/// Returns `true` when the raw texture data in `tex` differs from the last
-/// hash recorded for the given address. `tex` is the already resolved slice
-/// for the texture (caller has already mapped MEM1/MEM2).
+/// hash recorded for this cache id. `tex` is the already resolved slice for
+/// the texture (caller has already mapped MEM1/MEM2). The hash is keyed by
+/// cache_id so paletted textures bound with multiple TLUTs are tracked
+/// independently.
fn texture_data_changed(
- hashes: &mut rustc_hash::FxHashMap<u32, u64>,
+ hashes: &mut rustc_hash::FxHashMap<u64, u64>,
tex: &[u8],
- addr: u32,
+ cache_id: u64,
palette: &[u16],
tlut: draw::TlutRef,
format: draw::TextureFormat,
@@ -592,7 +617,7 @@ fn texture_data_changed(
// into the hash or a format switch alone wouldn't force a redecode.
hash ^= tlut.format as u64;
}
- let prev = hashes.insert(addr, hash);
+ let prev = hashes.insert(cache_id, hash);
prev != Some(hash)
}
diff --git a/crates/gecko/src/flipper/gx/fifo.rs b/crates/gecko/src/flipper/gx/fifo.rs
index 415ed4f..5fd39e4 100644
--- a/crates/gecko/src/flipper/gx/fifo.rs
+++ b/crates/gecko/src/flipper/gx/fifo.rs
@@ -1,7 +1,9 @@
use super::constants::*;
use super::regs::*;
use crate::flipper::gx::GraphicsProcessor;
-use std::io::{Cursor, Read};
+use crate::host::RenderSink;
+use crate::mmio::Mmio;
+use crate::system::SystemId;
impl GraphicsProcessor {
pub fn push_u8(&mut self, val: u8) {
@@ -16,88 +18,65 @@ impl GraphicsProcessor {
self.fifo.extend_from_slice(&val.to_be_bytes());
}
- /// Drain complete commands from the FIFO, returning each as a `FifoCmd`.
- pub fn drain(&mut self) -> Vec<FifoCmd> {
- let mut cmds = Vec::new();
- let mut cur = Cursor::new(&self.fifo);
-
+ /// Streaming GP FIFO command processor: parses and dispatches each
+ /// command inline so state writes (CP/XF/BP) take effect before the
+ /// next command's parse decisions read them.
+ ///
+ /// Partial commands are left in `self.fifo` for the next push to
+ /// complete: when a command's payload isn't fully present, we `break`
+ /// without advancing `pos`, then drain only the consumed prefix below.
+ pub fn drain_fifo<const SYSTEM: SystemId>(&mut self, mmio: &mut Mmio<SYSTEM>, renderer: &mut dyn RenderSink) {
+ let mut pos = 0usize;
loop {
- let pos = cur.position() as usize;
let remaining = self.fifo.len() - pos;
if remaining == 0 {
break;
}
-
- let mut cmd_buf = [0u8; 1];
- cur.read_exact(&mut cmd_buf).unwrap();
- let cmd = cmd_buf[0];
+ let cmd = self.fifo[pos];
match cmd {
NOP_CMD | INV_VTX_CACHE_CMD => {
- // NOP / vertex cache invalidate, skip
- }
- CALL_DL_CMD => {
- // 4-byte physical address + 4-byte size = 8 bytes payload
- if remaining < 9 {
- cur.set_position(pos as u64);
- break;
- }
- let mut addr_buf = [0u8; 4];
- let mut size_buf = [0u8; 4];
- cur.read_exact(&mut addr_buf).unwrap();
- cur.read_exact(&mut size_buf).unwrap();
- let phys_addr = u32::from_be_bytes(addr_buf);
- let nbytes = u32::from_be_bytes(size_buf);
- cmds.push(FifoCmd::CallDisplayList { phys_addr, nbytes });
+ pos += 1;
}
CP_CMD => {
- // 1 addr + 4 data = 5 bytes
if remaining < 6 {
- cur.set_position(pos as u64);
break;
}
let mut data = [0u8; 5];
- cur.read_exact(&mut data).unwrap();
- cmds.push(FifoCmd::Cp(data));
+ data.copy_from_slice(&self.fifo[pos + 1..pos + 6]);
+ pos += 6;
+ self.load_cp(&data);
}
XF_CMD => {
- // 2 length + 2 addr = 4 byte header
if remaining < 5 {
- cur.set_position(pos as u64);
break;
}
- let mut header = [0u8; 4];
- cur.read_exact(&mut header).unwrap();
- let length = u16::from_be_bytes([header[0], header[1]]) as usize;
+ let length = u16::from_be_bytes([self.fifo[pos + 1], self.fifo[pos + 2]]) as usize;
let n = length + 1;
let total = 5 + n * 4;
if remaining < total {
- cur.set_position(pos as u64);
break;
}
- let mut rest = vec![0u8; n * 4];
- cur.read_exact(&mut rest).unwrap();
- let data = [header.as_slice(), rest.as_slice()].concat();
- cmds.push(FifoCmd::Xf(data));
+ let data = self.fifo[pos + 1..pos + total].to_vec();
+ pos += total;
+ self.load_xf(renderer, &data);
}
BP_CMD => {
- // 4 data bytes
if remaining < 5 {
- cur.set_position(pos as u64);
break;
}
let mut data = [0u8; 4];
- cur.read_exact(&mut data).unwrap();
- cmds.push(FifoCmd::Bp(data));
+ data.copy_from_slice(&self.fifo[pos + 1..pos + 5]);
+ pos += 5;
+ let mut view = mmio.ram_view_mut();
+ self.load_bp(renderer, &mut view, &data);
}
LOAD_INDX_A_CMD | LOAD_INDX_B_CMD | LOAD_INDX_C_CMD | LOAD_INDX_D_CMD => {
- // 4 bytes payload: 2-byte index + 2-byte descriptor
if remaining < 5 {
- cur.set_position(pos as u64);
break;
}
- let mut payload = [0u8; 4];
- cur.read_exact(&mut payload).unwrap();
+ let payload: [u8; 4] = self.fifo[pos + 1..pos + 5].try_into().unwrap();
+ pos += 5;
let index = u16::from_be_bytes([payload[0], payload[1]]);
let descriptor = u16::from_be_bytes([payload[2], payload[3]]);
@@ -112,45 +91,57 @@ impl GraphicsProcessor {
_ => unreachable!(),
} as u8;
- cmds.push(FifoCmd::LoadIndexedXf {
- cp_array_index,
- index,
- xf_addr,
- xf_count,
- });
+ let view = mmio.ram_view();
+ self.load_indexed_xf(renderer, &view, cp_array_index, index, xf_addr, xf_count);
+ }
+ CALL_DL_CMD => {
+ if remaining < 9 {
+ break;
+ }
+ let phys_addr = u32::from_be_bytes(self.fifo[pos + 1..pos + 5].try_into().unwrap());
+ let nbytes = u32::from_be_bytes(self.fifo[pos + 5..pos + 9].try_into().unwrap());
+ pos += 9;
+
+ let addr = (phys_addr & 0x3FFFFFFF) as usize;
+ let len = nbytes as usize;
+ let dl = match mmio.ram_view().slice(addr, len) {
+ Some(slice) => slice.to_vec(),
+ None => {
+ tracing::warn!(
+ addr = format!("{addr:#010X}"),
+ len,
+ "CallDisplayList: source not mapped to MEM1/MEM2, skipping"
+ );
+ continue;
+ }
+ };
+ self.execute_display_list(mmio, renderer, &dl);
}
DRAW_COMMANDS_START..=DRAW_COMMANDS_END => {
- // [count_hi] [count_lo] [vertex_0_data...] ...
if remaining < 3 {
- cur.set_position(pos as u64);
break;
}
- let mut count_buf = [0u8; 2];
- cur.read_exact(&mut count_buf).unwrap();
- let count = u16::from_be_bytes(count_buf) as usize;
+ let count = u16::from_be_bytes([self.fifo[pos + 1], self.fifo[pos + 2]]) as usize;
let vertex_format_index = (cmd & 0b111) as usize;
let vertex_data_len = count * self.vertex_stride(vertex_format_index);
let total = 3 + vertex_data_len;
if remaining < total {
- cur.set_position(pos as u64);
break;
}
- let mut vertex_data = vec![0u8; vertex_data_len];
- cur.read_exact(&mut vertex_data).unwrap();
- cmds.push(FifoCmd::DrawCall(cmd, vertex_data));
+ let vertex_data = self.fifo[pos + 3..pos + total].to_vec();
+ pos += total;
+ self.create_draw_call(mmio, renderer, cmd, vertex_data);
}
_ => {
tracing::error!(cmd = format!("{cmd:02X}"), "unknown FIFO command");
+ pos += 1;
}
}
}
- let consumed = cur.position() as usize;
- if consumed > 0 {
- self.fifo.drain(..consumed);
+ if pos > 0 {
+ self.fifo.drain(..pos);
}
-
- cmds
}
fn vertex_stride(&self, vertex_format_index: usize) -> usize {
@@ -185,21 +176,3 @@ impl GraphicsProcessor {
+ attr_size(vcd_hi.tex7(), vat_c.tex7_data_size())
}
}
-
-#[derive(Debug)]
-pub enum FifoCmd {
- Cp([u8; 5]),
- Xf(Vec<u8>),
- Bp([u8; 4]),
- LoadIndexedXf {
- cp_array_index: u8,
- index: u16,
- xf_addr: u16,
- xf_count: u8,
- },
- CallDisplayList {
- phys_addr: u32,
- nbytes: u32,
- },
- DrawCall(u8, Vec<u8>),
-}
diff --git a/crates/gecko/src/flipper/gx/texture.rs b/crates/gecko/src/flipper/gx/texture.rs
index 3978c71..3a2d9ab 100644
--- a/crates/gecko/src/flipper/gx/texture.rs
+++ b/crates/gecko/src/flipper/gx/texture.rs
@@ -437,8 +437,7 @@ fn decode_cmpr(tex: &[u8], rgba: &mut [u8], w: usize, h: usize) {
fn tlut_entry_to_rgba(packed: u16, format: TlutFormat) -> [u8; 4] {
match format {
TlutFormat::IA8 => {
- // Palette IA8 is stored big-endian in TMEM; after our from_be_bytes
- // load, high byte = alpha, low byte = intensity.
+ // Palette IA8 is stored in raw TMEM order as alpha then intensity.
let a = (packed >> 8) as u8;
let i = (packed & 0xFF) as u8;
[i, i, i, a]
diff --git a/crates/gecko/src/flipper/gx/vertex.rs b/crates/gecko/src/flipper/gx/vertex.rs
index 4249591..fd21379 100644
--- a/crates/gecko/src/flipper/gx/vertex.rs
+++ b/crates/gecko/src/flipper/gx/vertex.rs
@@ -167,6 +167,7 @@ impl GraphicsProcessor {
tev_color_env: self.cur_tev_color_env.iter().map(|e| e.raw()).collect(),
tev_alpha_env: self.cur_tev_alpha_env.iter().map(|e| e.raw()).collect(),
tev_orders: tev_orders.iter().map(|o| o.raw()).collect(),
+ tev_ksel: (0..8).map(|i| self.bp_regs[BP_TEV_KSEL_0 + i]).collect(),
tev_color_regs,
tev_konst_colors: self.cur_tev_konst_colors,
num_tev_stages: self.cur_num_tev_stages,
diff --git a/crates/gecko/src/gekko/interpreter/alu.rs b/crates/gecko/src/gekko/interpreter/alu.rs
index 42f7e48..7e69f7a 100644
--- a/crates/gecko/src/gekko/interpreter/alu.rs
+++ b/crates/gecko/src/gekko/interpreter/alu.rs
@@ -2,15 +2,32 @@ use crate::gekko::instruction::Instruction;
use crate::gekko::lut::*;
use crate::system::{System, SystemId};
+#[inline(always)]
+fn set_overflow<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, overflow: bool) {
+ ctx.gekko.spr.xer = ctx
+ .gekko
+ .spr
+ .xer
+ .with_overflow(overflow)
+ .with_summary_overflow(ctx.gekko.spr.xer.summary_overflow() || overflow);
+}
+
+#[inline(always)]
+fn add_overflow(a: u32, b: u32, result: u32) -> bool {
+ (((a ^ result) & (b ^ result)) >> 31) != 0
+}
+
#[inline(always)]
pub fn alu<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {
match OP {
OP_ADDX => {
- let res = ctx
- .gekko
- .read_gpr(instr.ra())
- .wrapping_add(ctx.gekko.read_gpr(instr.rb()));
+ let a = ctx.gekko.read_gpr(instr.ra());
+ let b = ctx.gekko.read_gpr(instr.rb());
+ let res = a.wrapping_add(b);
ctx.gekko.write_gpr(instr.rd(), res);
+ if instr.oe() {
+ set_overflow(ctx, add_overflow(a, b, res));
+ }
if instr.rc() {
ctx.gekko.update_cr0(res);
}
@@ -51,18 +68,24 @@ pub fn alu<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, inst
ctx.gekko.update_cr0(val);
}
OP_SUBFX => {
- let res = ctx
- .gekko
- .read_gpr(instr.rb())
- .wrapping_sub(ctx.gekko.read_gpr(instr.ra()));
+ let a = !ctx.gekko.read_gpr(instr.ra());
+ let b = ctx.gekko.read_gpr(instr.rb());
+ let res = a.wrapping_add(b).wrapping_add(1);
ctx.gekko.write_gpr(instr.rd(), res);
+ if instr.oe() {
+ set_overflow(ctx, add_overflow(a, b, res));
+ }
if instr.rc() {
ctx.gekko.update_cr0(res);
}
}
OP_NEGX => {
- let res = (!ctx.gekko.read_gpr(instr.ra())).wrapping_add(1);
+ let a = ctx.gekko.read_gpr(instr.ra());
+ let res = (!a).wrapping_add(1);
ctx.gekko.write_gpr(instr.rd(), res);
+ if instr.oe() {
+ set_overflow(ctx, a == 0x8000_0000);
+ }
if instr.rc() {
ctx.gekko.update_cr0(res);
}
@@ -73,6 +96,9 @@ pub fn alu<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, inst
let (res, carry) = ra.overflowing_add(rb);
ctx.gekko.write_gpr(instr.rd(), res);
ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(carry);
+ if instr.oe() {
+ set_overflow(ctx, add_overflow(ra, rb, res));
+ }
if instr.rc() {
ctx.gekko.update_cr0(res);
}
@@ -83,6 +109,9 @@ pub fn alu<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, inst
let res = rb.wrapping_sub(ra);
ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(rb >= ra);
ctx.gekko.write_gpr(instr.rd(), res);
+ if instr.oe() {
+ set_overflow(ctx, add_overflow(!ra, rb, res));
+ }
if instr.rc() {
ctx.gekko.update_cr0(res);
}
@@ -95,6 +124,9 @@ pub fn alu<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, inst
let (res, c2) = t1.overflowing_add(ca);
ctx.gekko.write_gpr(instr.rd(), res);
ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(c1 || c2);
+ if instr.oe() {
+ set_overflow(ctx, add_overflow(ra, rb, res));
+ }
if instr.rc() {
ctx.gekko.update_cr0(res);
}
@@ -107,6 +139,9 @@ pub fn alu<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, inst
let (res, c2) = t1.overflowing_add(ca);
ctx.gekko.write_gpr(instr.rd(), res);
ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(c1 || c2);
+ if instr.oe() {
+ set_overflow(ctx, add_overflow(!ra, rb, res));
+ }
if instr.rc() {
ctx.gekko.update_cr0(res);
}
@@ -117,6 +152,9 @@ pub fn alu<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, inst
let (res, carry) = ra.overflowing_add(ca);
ctx.gekko.write_gpr(instr.rd(), res);
ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(carry);
+ if instr.oe() {
+ set_overflow(ctx, add_overflow(ra, 0, res));
+ }
if instr.rc() {
ctx.gekko.update_cr0(res);
}
@@ -127,6 +165,9 @@ pub fn alu<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, inst
let (res, carry) = (!ra).overflowing_add(ca);
ctx.gekko.write_gpr(instr.rd(), res);
ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(carry);
+ if instr.oe() {
+ set_overflow(ctx, add_overflow(!ra, 0, res));
+ }
if instr.rc() {
ctx.gekko.update_cr0(res);
}
@@ -138,6 +179,9 @@ pub fn alu<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, inst
let (res, c2) = t1.overflowing_add(0xFFFF_FFFF);
ctx.gekko.write_gpr(instr.rd(), res);
ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(c1 || c2);
+ if instr.oe() {
+ set_overflow(ctx, add_overflow(ra, 0xFFFF_FFFF, res));
+ }
if instr.rc() {
ctx.gekko.update_cr0(res);
}
@@ -149,14 +193,21 @@ pub fn alu<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, inst
let (res, c2) = t1.overflowing_add(0xFFFF_FFFF);
ctx.gekko.write_gpr(instr.rd(), res);
ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(c1 || c2);
+ if instr.oe() {
+ set_overflow(ctx, add_overflow(!ra, 0xFFFF_FFFF, res));
+ }
if instr.rc() {
ctx.gekko.update_cr0(res);
}
}
OP_MULLWX => {
- let res = (ctx.gekko.read_gpr(instr.ra()) as i32 as i64)
- .wrapping_mul(ctx.gekko.read_gpr(instr.rb()) as i32 as i64) as u32;
+ let full = (ctx.gekko.read_gpr(instr.ra()) as i32 as i64)
+ .wrapping_mul(ctx.gekko.read_gpr(instr.rb()) as i32 as i64);
+ let res = full as u32;
ctx.gekko.write_gpr(instr.rd(), res);
+ if instr.oe() {
+ set_overflow(ctx, full < i32::MIN as i64 || full > i32::MAX as i64);
+ }
if instr.rc() {
ctx.gekko.update_cr0(res);
}
@@ -166,6 +217,9 @@ pub fn alu<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, inst
let rb = ctx.gekko.read_gpr(instr.rb());
let res = if rb == 0 { 0 } else { ra / rb };
ctx.gekko.write_gpr(instr.rd(), res);
+ if instr.oe() {
+ set_overflow(ctx, rb == 0);
+ }
if instr.rc() {
ctx.gekko.update_cr0(res);
}
@@ -174,11 +228,14 @@ pub fn alu<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, inst
let ra = ctx.gekko.read_gpr(instr.ra()) as i32;
let rb = ctx.gekko.read_gpr(instr.rb()) as i32;
let res = if rb == 0 || (ra == i32::MIN && rb == -1) {
- 0u32
+ if ra < 0 { u32::MAX } else { 0 }
} else {
(ra / rb) as u32
};
ctx.gekko.write_gpr(instr.rd(), res);
+ if instr.oe() {
+ set_overflow(ctx, rb == 0 || (ra == i32::MIN && rb == -1));
+ }
if instr.rc() {
ctx.gekko.update_cr0(res);
}
diff --git a/crates/gecko/src/gekko/interpreter/branch.rs b/crates/gecko/src/gekko/interpreter/branch.rs
index fb7ba1e..3059cdb 100644
--- a/crates/gecko/src/gekko/interpreter/branch.rs
+++ b/crates/gecko/src/gekko/interpreter/branch.rs
@@ -5,22 +5,18 @@ use crate::system::{System, SystemId};
#[inline(always)]
pub fn branch<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {
- // Read LR before potentially overwriting LR with CIA+4 (matters for blrl/bctrl)
- let old_lr = ctx.gekko.spr.lr;
-
- if instr.lk() {
- ctx.gekko.spr.lr = ctx.gekko.cia.wrapping_add(4);
- }
-
match OP {
OP_BX => {
ctx.gekko.nia = if instr.aa() {
instr.li() as u32
} else {
ctx.gekko.cia.wrapping_add_signed(instr.li())
+ };
+ if instr.lk() {
+ ctx.gekko.spr.lr = ctx.gekko.cia.wrapping_add(4);
}
}
- OP_BCLRX | OP_BCX | OP_BCCTRX => {
+ OP_BCX => {
let ctrl = BranchControl::from_bo(instr.bo());
tracing::trace!("Branch control: {ctrl:?}");
@@ -33,17 +29,43 @@ pub fn branch<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, i
return;
}
- match OP {
- OP_BCLRX => ctx.gekko.nia = old_lr,
- OP_BCX => {
- ctx.gekko.nia = if instr.aa() {
- instr.bd() as u32
- } else {
- ctx.gekko.cia.wrapping_add_signed(instr.bd())
- }
- }
- OP_BCCTRX => ctx.gekko.nia = ctx.gekko.spr.ctr,
- _ => tracing::error!("missing OP = {OP:#x}"),
+ ctx.gekko.nia = if instr.aa() {
+ instr.bd() as u32
+ } else {
+ ctx.gekko.cia.wrapping_add_signed(instr.bd())
+ };
+ if instr.lk() {
+ ctx.gekko.spr.lr = ctx.gekko.cia.wrapping_add(4);
+ }
+ }
+ OP_BCLRX => {
+ let ctrl = BranchControl::from_bo(instr.bo());
+ tracing::trace!("Branch control: {ctrl:?}");
+
+ if ctrl.should_decrement_ctr() {
+ ctx.gekko.spr.ctr = ctx.gekko.spr.ctr.wrapping_sub(1);
+ }
+
+ let condition = ctx.gekko.cr.get_bit(instr.bi());
+ if !ctrl.should_branch(ctx.gekko.spr.ctr, condition) {
+ return;
+ }
+
+ ctx.gekko.nia = ctx.gekko.spr.lr & !3;
+ if instr.lk() {
+ ctx.gekko.spr.lr = ctx.gekko.cia.wrapping_add(4);
+ }
+ }
+ OP_BCCTRX => {
+ let bo = instr.bo();
+ let condition = (bo & 0x10) != 0 || (ctx.gekko.cr.get_bit(instr.bi()) == ((bo & 0x08) != 0));
+ if !condition {
+ return;
+ }
+
+ ctx.gekko.nia = ctx.gekko.spr.ctr & !3;
+ if instr.lk() {
+ ctx.gekko.spr.lr = ctx.gekko.cia.wrapping_add(4);
}
}
_ => todo!("branch instruction with OP = {OP:#x}"),
diff --git a/crates/gecko/src/gekko/interpreter/compare.rs b/crates/gecko/src/gekko/interpreter/compare.rs
index bbec3af..f245dee 100644
--- a/crates/gecko/src/gekko/interpreter/compare.rs
+++ b/crates/gecko/src/gekko/interpreter/compare.rs
@@ -5,7 +5,7 @@ use crate::system::{System, SystemId};
#[inline(always)]
pub fn compare<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {
- let field = match OP {
+ let mut field = match OP {
OP_CMP => ConditionRegister::field_from_ord(
(ctx.gekko.read_gpr(instr.ra()) as i32).cmp(&(ctx.gekko.read_gpr(instr.rb()) as i32)),
),
@@ -17,5 +17,6 @@ pub fn compare<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>,
_ => todo!("Compare instruction with OP = {OP:#x}"),
};
+ field = field.with_so(ctx.gekko.spr.xer.summary_overflow());
ctx.gekko.cr.set_field(instr.crfd(), field);
}
diff --git a/crates/gecko/src/gekko/interpreter/fp_ops.rs b/crates/gecko/src/gekko/interpreter/fp_ops.rs
index c234dc5..766f3a1 100644
--- a/crates/gecko/src/gekko/interpreter/fp_ops.rs
+++ b/crates/gecko/src/gekko/interpreter/fp_ops.rs
@@ -4,6 +4,34 @@ use crate::gekko::instruction::Instruction;
use crate::gekko::lut::*;
use crate::system::{System, SystemId};
+const FPSCR_FX: u32 = 1 << (31 - 0);
+const FPSCR_OX: u32 = 1 << (31 - 3);
+const FPSCR_UX: u32 = 1 << (31 - 4);
+const FPSCR_ZX: u32 = 1 << (31 - 5);
+const FPSCR_XX: u32 = 1 << (31 - 6);
+const FPSCR_VXSNAN: u32 = 1 << (31 - 7);
+const FPSCR_VXISI: u32 = 1 << (31 - 8);
+const FPSCR_VXIDI: u32 = 1 << (31 - 9);
+const FPSCR_VXZDZ: u32 = 1 << (31 - 10);
+const FPSCR_VXIMZ: u32 = 1 << (31 - 11);
+const FPSCR_VXVC: u32 = 1 << (31 - 12);
+const FPSCR_VXSOFT: u32 = 1 << (31 - 21);
+const FPSCR_VXSQRT: u32 = 1 << (31 - 22);
+const FPSCR_VXCVI: u32 = 1 << (31 - 23);
+const FPSCR_ANY_X: u32 = FPSCR_OX
+ | FPSCR_UX
+ | FPSCR_ZX
+ | FPSCR_XX
+ | FPSCR_VXSNAN
+ | FPSCR_VXISI
+ | FPSCR_VXIDI
+ | FPSCR_VXZDZ
+ | FPSCR_VXIMZ
+ | FPSCR_VXVC
+ | FPSCR_VXSOFT
+ | FPSCR_VXSQRT
+ | FPSCR_VXCVI;
+
#[inline(always)]
pub fn fp_ops<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {
if !ctx.check_fp_available() {
@@ -22,10 +50,15 @@ pub fn fp_ops<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, i
}
ctx.gekko.fpscr = Fpscr::from((ctx.gekko.fpscr.raw() & !mask) | (fb & mask));
ctx.gekko.recompute_fpscr_summary();
+ if instr.rc() {
+ ctx.gekko.update_cr1();
+ }
}
OP_MFFSX => {
- ctx.gekko
- .write_fpr(instr.rd(), f64::from_bits(ctx.gekko.fpscr.raw() as u64));
+ ctx.gekko.write_fpr(
+ instr.rd(),
+ f64::from_bits(0xFFF8_0000_0000_0000 | ctx.gekko.fpscr.raw() as u64),
+ );
if instr.rc() {
ctx.gekko.update_cr1();
}
@@ -33,10 +66,21 @@ pub fn fp_ops<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, i
OP_MTFSB0X => {
ctx.gekko.fpscr = Fpscr::from(ctx.gekko.fpscr.raw() & !(1 << (31 - instr.crbd())));
ctx.gekko.recompute_fpscr_summary();
+ if instr.rc() {
+ ctx.gekko.update_cr1();
+ }
}
OP_MTFSB1X => {
- ctx.gekko.fpscr = Fpscr::from(ctx.gekko.fpscr.raw() | (1 << (31 - instr.crbd())));
+ let bit = 1 << (31 - instr.crbd());
+ let mut fpscr = ctx.gekko.fpscr.raw();
+ if bit & FPSCR_ANY_X != 0 && fpscr & bit == 0 {
+ fpscr |= FPSCR_FX;
+ }
+ ctx.gekko.fpscr = Fpscr::from(fpscr | bit);
ctx.gekko.recompute_fpscr_summary();
+ if instr.rc() {
+ ctx.gekko.update_cr1();
+ }
}
OP_MTFSFIX => {
let crfd = instr.crfd();
@@ -45,6 +89,9 @@ pub fn fp_ops<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, i
let mask = 0xFu32 << shift;
ctx.gekko.fpscr = Fpscr::from((ctx.gekko.fpscr.raw() & !mask) | (imm << shift));
ctx.gekko.recompute_fpscr_summary();
+ if instr.rc() {
+ ctx.gekko.update_cr1();
+ }
}
OP_MCRFS => {
let src_field = instr.crfs();
@@ -53,10 +100,9 @@ pub fn fp_ops<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, i
ctx.gekko
.cr
.set_field(instr.crfd(), ConditionField::from(fpscr_nibble as u8));
- if src_field != 0 && src_field != 1 {
- ctx.gekko.fpscr = Fpscr::from(ctx.gekko.fpscr.raw() & !(0xF << shift));
- ctx.gekko.recompute_fpscr_summary();
- }
+ let clear_mask = (0xF << shift) & (FPSCR_FX | FPSCR_ANY_X);
+ ctx.gekko.fpscr = Fpscr::from(ctx.gekko.fpscr.raw() & !clear_mask);
+ ctx.gekko.recompute_fpscr_summary();
}
OP_FMRX => {
ctx.gekko.write_fpr(instr.rd(), ctx.gekko.read_fpr(instr.rb()));
diff --git a/crates/gecko/src/gekko/interpreter/store_load.rs b/crates/gecko/src/gekko/interpreter/store_load.rs
index 86c312b..d17d2f7 100644
--- a/crates/gecko/src/gekko/interpreter/store_load.rs
+++ b/crates/gecko/src/gekko/interpreter/store_load.rs
@@ -201,10 +201,10 @@ pub fn stwcx_dot<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instru
.read_gpr_or_zero(instr.ra())
.wrapping_add(ctx.gekko.read_gpr(instr.rb()));
let so = ctx.gekko.spr.xer.summary_overflow();
- let store_performed = ctx.gekko.reserve_addr.is_some();
- ctx.gekko.reserve_addr = None;
+ let store_performed = ctx.gekko.reserve_addr == Some(addr);
if store_performed {
ctx.write_u32(addr, ctx.gekko.read_gpr(instr.rs()));
+ ctx.gekko.reserve_addr = None;
ctx.gekko.cr.set_cr0(ConditionField::new().with_eq(true).with_so(so));
} else {
ctx.gekko.cr.set_cr0(ConditionField::new().with_so(so));
diff --git a/crates/gecko/src/gekko/interpreter/system.rs b/crates/gecko/src/gekko/interpreter/system.rs
index 9147164..2a59005 100644
--- a/crates/gecko/src/gekko/interpreter/system.rs
+++ b/crates/gecko/src/gekko/interpreter/system.rs
@@ -13,10 +13,9 @@ pub fn msr<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, inst
ctx.gekko.write_gpr(instr.rd(), ctx.gekko.msr.raw());
}
OP_RFI => {
- const RFI_MSR_MASK: u32 = 0x0000_FF73;
- ctx.gekko.msr = crate::gekko::msr::Msr::from(
- (ctx.gekko.msr.raw() & !RFI_MSR_MASK) | (ctx.gekko.spr.srr1 & RFI_MSR_MASK),
- );
+ const RFI_MSR_MASK: u32 = 0x87C0_FFFF;
+ let msr = (ctx.gekko.msr.raw() & !RFI_MSR_MASK) | (ctx.gekko.spr.srr1 & RFI_MSR_MASK);
+ ctx.gekko.msr = crate::gekko::msr::Msr::from(msr & !0x0004_0000);
ctx.gekko.nia = ctx.gekko.spr.srr0.value() << 2;
}
_ => todo!("MSR instruction with OP = {OP:#x}"),
diff --git a/crates/gecko/src/host.rs b/crates/gecko/src/host.rs
index aeb31cb..14839ac 100644
--- a/crates/gecko/src/host.rs
+++ b/crates/gecko/src/host.rs
@@ -22,8 +22,14 @@ pub enum GxAction {
/// Upload pre-decoded texture data. Emitted when texture content at a
/// given address changes (detected by hash).
+ ///
+ /// `id` is the renderer side cache key. The low 32 bits are the source
+ /// `ram_addr`; for paletted (CI*) textures the high 32 bits encode the
+ /// bound TLUT (format + tmem_offset), so the same RAM-resident index
+ /// stream bound with two different palettes occupies two distinct cache
+ /// entries instead of clobbering each other.
LoadTexture {
- id: Address,
+ id: u64,
width: u32,
height: u32,
fmt: TextureFormat,
@@ -41,10 +47,11 @@ pub enum GxAction {
dir: PathBuf,
},
- /// Bind a previously loaded texture to a TEV texture slot.
+ /// Bind a previously loaded texture to a TEV texture slot. `id` matches
+ /// the cache key used in [`Self::LoadTexture`].
SetTexture {
slot: usize,
- id: Address,
+ id: u64,
wrap_s: WrapMode,
wrap_t: WrapMode,
mag_filter: MagFilter,
@@ -154,6 +161,7 @@ pub struct DrawData {
pub tev_color_env: Vec<u32>,
pub tev_alpha_env: Vec<u32>,
pub tev_orders: Vec<u32>,
+ pub tev_ksel: Vec<u32>,
pub tev_color_regs: [[f32; 4]; 4],
pub tev_konst_colors: [[f32; 4]; 16],
pub num_tev_stages: u8,