A GameCube/Wii emulator and debugger written in Rust.
fix split xfb tearing
Laylebc923ff50f5a
diff --git a/crates/fifoplayer/src/playback.rs b/crates/fifoplayer/src/playback.rsindex f29a9a2..18f2c60 100644--- a/crates/fifoplayer/src/playback.rs+++ b/crates/fifoplayer/src/playback.rs@@ -166,19 +166,26 @@ impl<const SYSTEM: SystemId> Playback<SYSTEM> {pub fn present(&mut self, sink: &mut PlayerSink) -> bool {let heights = std::mem::take(&mut sink.xfb_heights);- if self.gx.xfb_copies.is_empty() {+ if !self.gx.xfb_dirty {return false;}-- let bytes_per_row = self.gx.xfb_copies[0].dest_stride.max(2);+ self.gx.xfb_dirty = false;++ let bytes_per_row = self+ .gx+ .xfb_regions+ .values()+ .max_by_key(|r| r.copy_seq)+ .map(|r| r.stride.max(2))+ .unwrap();let stride_px = bytes_per_row / 2;- let min_base = self.gx.xfb_copies.iter().map(|c| c.dest_addr).min().unwrap();+ let min_base = self.gx.xfb_regions.keys().min().copied().unwrap();- let mut parts: Vec<XfbPart> = Vec::new();+ let mut parts: Vec<(u64, XfbPart)> = Vec::new();let mut frame_h = 0u32;- for copy in &self.gx.xfb_copies {- let delta_px = (copy.dest_addr - min_base) / 2;+ for (&addr, region) in self.gx.xfb_regions.iter() {+ let delta_px = (addr - min_base) / 2;let offset_x = delta_px % stride_px;let offset_y = delta_px / stride_px;@@ -189,22 +196,26 @@ impl<const SYSTEM: SystemId> Playback<SYSTEM> {let dst_h = heights.iter().rev()- .find(|(id, _)| *id == copy.dest_addr)+ .find(|(id, _)| *id == addr).map(|(_, h)| *h)- .unwrap_or(copy.src_h);+ .unwrap_or(0);frame_h = frame_h.max(offset_y + dst_h);- if !parts.iter().any(|p| p.id == copy.dest_addr) {- parts.push(XfbPart {- id: copy.dest_addr,+ parts.push((+ region.first_seq,+ XfbPart {+ id: addr,offset_x: 0,offset_y,- });- }+ },+ ));}- self.gx.xfb_copies.clear();+ self.gx.xfb_regions.clear();++ parts.sort_by_key(|(first_seq, _)| *first_seq);+ let parts: Vec<XfbPart> = parts.into_iter().map(|(_, p)| p).collect();if parts.is_empty() || frame_h == 0 {return false;diff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rsindex 0bf48b5..e6c7a4e 100644--- a/crates/gecko/src/flipper/gx.rs+++ b/crates/gecko/src/flipper/gx.rs@@ -80,9 +80,15 @@ pub struct GraphicsProcessor {// projection or logical viewport.pub cur_scissor_offset_x: i32,pub cur_scissor_offset_y: i32,- // 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>,++ // Every XFB address the game has recently copied to. `present_xfb()`+ // composes the regions that overlap the buffer the VI is scanning.+ pub xfb_regions: FxHashMap<u32, XfbRegion>,+ pub xfb_dirty: bool,+ pub xfb_copy_seq: u64,+ pub xfb_present_seq: u64,+ pub xfb_last_present_base: u32,+#[cfg(feature = "jit")]pub jit_vtx: jit::JitVertexEngine,#[cfg(feature = "jit")]@@ -107,13 +113,22 @@ pub struct GraphicsProcessor {pub execution_mode: ExecutionMode,}-/// A single EFB-to-XFB copy, stored until `present_xfb` computes the layout.-pub struct XfbCopy {- pub dest_addr: u32,- pub dest_stride: u32,- pub src_h: u32,+/// One known EFB-to-XFB copy destination. Compositing in `first_seq` order+/// keeps a split XFB's bottom copy over the top copy's junk padding rows,+/// like Dolphin. `seen_present_seq` ages out dead regions. As seen in+/// Another Code: R or whatever it's called, it builds each frame from a+/// 230+228 line copy pair and showed a black seam plus a lagging bottom half.+pub struct XfbRegion {+ pub stride: u32,+ pub first_seq: u64,+ pub copy_seq: u64,+ pub seen_present_seq: u64,}+// Drop regions that haven't been re-copied for a few frames so dead layouts+// don't composite over fresh ones.+const XFB_REGION_MAX_AGE_PRESENTS: u64 = 8;+#[cfg(feature = "gx-stats")]#[derive(Default, Clone)]pub(crate) struct GxStats {@@ -170,7 +185,11 @@ impl GraphicsProcessor {cur_scissor: Default::default(),cur_scissor_offset_x: 0,cur_scissor_offset_y: 0,- xfb_copies: Vec::new(),+ xfb_regions: FxHashMap::default(),+ xfb_dirty: false,+ xfb_copy_seq: 0,+ xfb_present_seq: 0,+ xfb_last_present_base: 0,#[cfg(feature = "jit")]jit_vtx: jit::JitVertexEngine::new(),#[cfg(feature = "jit")]@@ -203,9 +222,14 @@ pub fn present_xfb<const SYSTEM: SystemId>(sys: &mut System<SYSTEM>) {sys.fps_counter.vsync_count += 1;}- if sys.gx.xfb_copies.is_empty() {+ // Present when new copies arrived or the VI flipped to a buffer whose+ // copies were already consumed (pageflip).+ let vi_base = sys.vi.latched_xfb_base;+ if !sys.gx.xfb_dirty && vi_base == sys.gx.xfb_last_present_base {return;}+ sys.gx.xfb_dirty = false;+ sys.gx.xfb_present_seq += 1;if sys.gx.recorder.is_some() {let mut rec = sys.gx.recorder.take().unwrap();@@ -223,33 +247,45 @@ pub fn present_xfb<const SYSTEM: SystemId>(sys: &mut System<SYSTEM>) {sys.gx.stats.xfb_presents += 1;}+ let seq = sys.gx.xfb_present_seq;+ sys.gx+ .xfb_regions+ .retain(|_, r| seq - r.seen_present_seq <= XFB_REGION_MAX_AGE_PRESENTS);+let (frame_w, frame_h) = sys.vi.frame_dimensions();- let vi_base = sys.vi.xfb_addr();- // All copies in a frame share the same stride.- let bytes_per_row = sys.gx.xfb_copies[0].dest_stride as u64;+ let Some(bytes_per_row) = sys+ .gx+ .xfb_regions+ .values()+ .max_by_key(|r| r.copy_seq)+ .map(|r| r.stride as u64)+ else {+ return;+ };if bytes_per_row == 0 {- tracing::warn!("present_xfb: zero bytes_per_row, dropping XFB copies");- sys.gx.xfb_copies.clear();+ tracing::warn!("present_xfb: zero bytes_per_row, skipping present");return;}+let xfb_bytes = bytes_per_row * frame_h as u64;let stride_in_pixels = (bytes_per_row / 2) as u32;- let frame_base = if sys.vi.dcr.interlaced() && sys.vi.in_even_field() {+ let frame_base = if sys.vi.dcr.interlaced() && sys.vi.latched_even_field {vi_base.saturating_sub(bytes_per_row as u32)} else {vi_base};- let build_parts = |base_addr: u32| -> Vec<XfbPart> {- let mut parts = Vec::with_capacity(sys.gx.xfb_copies.len());- for copy in sys.gx.xfb_copies.iter() {- if copy.dest_addr < base_addr {+ let build_parts = |base_addr: u32| -> Vec<(u64, u64, XfbPart)> {+ let mut parts = Vec::with_capacity(sys.gx.xfb_regions.len());++ for (&addr, region) in sys.gx.xfb_regions.iter() {+ if addr < base_addr {continue;}- let delta_bytes = (copy.dest_addr - base_addr) as u64;+ let delta_bytes = (addr - base_addr) as u64;if delta_bytes >= xfb_bytes {continue;}@@ -259,38 +295,48 @@ pub fn present_xfb<const SYSTEM: SystemId>(sys: &mut System<SYSTEM>) {let offset_y = delta_pixels / stride_in_pixels;// Real XFB copies always land at row boundaries (offset_x == 0).- // A non-zero offset_x means this copy belongs to a different+ // A non-zero offset_x means this region belongs to a different// buffer that happens to sit nearby in memory, reject it? TODOif offset_x != 0 || offset_y >= frame_h as u32 {tracing::debug!(- copy_dest = copy.dest_addr,+ region = addr,base = base_addr,offset_x,offset_y,- "present_xfb: rejecting XFB copy with invalid offset"+ "present_xfb: rejecting XFB region with invalid offset");continue;}- parts.push(XfbPart {- id: copy.dest_addr,- offset_x,- offset_y,- });+ parts.push((+ region.first_seq,+ region.copy_seq,+ XfbPart {+ id: addr,+ offset_x,+ offset_y,+ },+ ));}++ parts.sort_by_key(|(first_seq, _, _)| *first_seq);parts};- let min_base = sys.gx.xfb_copies.iter().map(|c| c.dest_addr).min().unwrap_or(0);+ let min_base = sys.gx.xfb_regions.keys().min().copied().unwrap_or(0);let parts = if frame_base != 0 {let mut p = build_parts(frame_base);if p.is_empty() {- p.push(XfbPart {- id: frame_base,- offset_x: 0,- offset_y: 0,- });+ p.push((+ 0,+ 0,+ XfbPart {+ id: frame_base,+ offset_x: 0,+ offset_y: 0,+ },+ ));}p} else {@@ -298,17 +344,24 @@ pub fn present_xfb<const SYSTEM: SystemId>(sys: &mut System<SYSTEM>) {};if parts.is_empty() {- tracing::debug!("present_xfb: no XFB copies matched the frame buffer region");- sys.gx.xfb_copies.clear();+ tracing::debug!("present_xfb: no XFB regions matched the frame buffer region");return;}+ let closer_copy_seq = parts.last().map(|(_, copy_seq, _)| *copy_seq).unwrap_or(0);+ if parts.iter().any(|(_, copy_seq, _)| *copy_seq > closer_copy_seq) {+ sys.gx.xfb_dirty = true;+ return;+ }++ let parts: Vec<XfbPart> = parts.into_iter().map(|(_, _, p)| p).collect();+sys.render_sink.exec(GxAction::PresentXfb {width: frame_w,height: frame_h,parts,});- sys.gx.xfb_copies.clear();+ sys.gx.xfb_last_present_base = vi_base;}impl<const SYSTEM: SystemId> System<SYSTEM> {diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rsindex 546b2c5..4fd6312 100644--- a/crates/gecko/src/flipper/gx/bp.rs+++ b/crates/gecko/src/flipper/gx/bp.rs@@ -507,17 +507,30 @@ impl GraphicsProcessor {2 | 3 => 2.2,_ => 1.0,};- // XFB copy: queue the copy for present_xfb() to compose at vblank,- // and tell the renderer to snapshot the EFB region now. The renderer- // keys its snapshot textures by this id; using the destination- // address makes them persist per XFB buffer across frames, so present_xfb- // can show the buffer the VI is scanning even on frames where the game only- // copied the other (back) buffer.- self.xfb_copies.push(super::XfbCopy {- dest_addr,- dest_stride,- src_h,- });++ // XFB copy: record the destination region for present_xfb() and+ // tell the renderer to snapshot the EFB now. Textures are keyed+ // by destination address so each buffer's snapshot persists+ // across frames.+ self.xfb_copy_seq += 1;+ let copy_seq = self.xfb_copy_seq;+ let present_seq = self.xfb_present_seq;++ self.xfb_regions+ .entry(dest_addr)+ .and_modify(|r| {+ r.stride = dest_stride;+ r.copy_seq = copy_seq;+ r.seen_present_seq = present_seq;+ })+ .or_insert(super::XfbRegion {+ stride: dest_stride,+ first_seq: copy_seq,+ copy_seq,+ seen_present_seq: present_seq,+ });++ self.xfb_dirty = true;if let Some(rec) = self.recorder.as_deref_mut() {rec.note_xfb_copy();diff --git a/crates/gecko/src/flipper/vi.rs b/crates/gecko/src/flipper/vi.rsindex c9d52cf..84f5ded 100644--- a/crates/gecko/src/flipper/vi.rs+++ b/crates/gecko/src/flipper/vi.rs@@ -45,6 +45,9 @@ pub struct VideoInterface {pub half_line_count: u32,pub ticks_last_line_start: u64,pub half_line_scheduled: bool,++ pub latched_xfb_base: u32,+ pub latched_even_field: bool,}impl VideoInterface {@@ -87,6 +90,8 @@ impl VideoInterface {half_line_count: 0,ticks_last_line_start: 0,half_line_scheduled: false,+ latched_xfb_base: 0,+ latched_even_field: false,}}@@ -119,6 +124,20 @@ impl VideoInterface {self.half_lines_per_even_field() + self.half_lines_per_odd_field()}+ fn odd_field_active_half_lines(&self) -> (u32, u32) {+ let equ = self.vtr.equalization_pulse() as u32;+ let acv = self.vtr.active_video() as u32;+ let start = 3 * equ + self.vto.pre_blanking_in_half_lines() as u32;+ (start, start + 2 * acv)+ }++ fn even_field_active_half_lines(&self) -> (u32, u32) {+ let equ = self.vtr.equalization_pulse() as u32;+ let acv = self.vtr.active_video() as u32;+ let start = self.half_lines_per_odd_field() + 3 * equ + self.vte.pre_blanking_in_half_lines() as u32;+ (start, start + 2 * acv)+ }+/// Returns true if any DI register has both IR_INT and IR_MASK set.#[inline(always)]pub fn vi_interrupt_active(&self) -> bool {@@ -276,11 +295,21 @@ pub fn ensure_half_line_scheduled<const SYSTEM: SystemId>(sys: &mut System<SYSTEsys.vi.half_line_scheduled = false;let curr_hl = sys.vi.half_line_count;- let total_hl = sys.vi.total_half_lines();- let odd_field_start = 0u32;- let even_field_start = sys.vi.half_lines_per_odd_field();- if total_hl > 0 && (curr_hl == odd_field_start || curr_hl == even_field_start) && curr_hl != prev_hl {- crate::flipper::gx::present_xfb(sys);+ if curr_hl != prev_hl {+ let (odd_av_start, odd_av_end) = sys.vi.odd_field_active_half_lines();+ let (even_av_start, even_av_end) = sys.vi.even_field_active_half_lines();++ if curr_hl == odd_av_start || curr_hl == even_av_start {+ sys.vi.latched_xfb_base = sys.vi.xfb_addr();+ sys.vi.latched_even_field = sys.vi.in_even_field();+ }++ // Present at the end of active video so copies made while+ // the field is scanning out are included (Another Code: R+ // copies its split XFB halves mid-frame).+ if curr_hl == odd_av_end || curr_hl == even_av_end {+ crate::flipper::gx::present_xfb(sys);+ }}self::ensure_half_line_scheduled(sys);diff --git a/crates/gecko/src/host.rs b/crates/gecko/src/host.rsindex 64ec7bf..3a6be4e 100644--- a/crates/gecko/src/host.rs+++ b/crates/gecko/src/host.rs@@ -78,9 +78,8 @@ pub enum GxAction {/// TEV/lighting snapshot carried here.Draw(Box<DrawData>),- /// Copy the EFB source region to a temporary texture identified by `id`.- /// The renderer stores this until the next [`PresentXfb`] composites it- /// into the output framebuffer.+ /// Copy the EFB source region to a persistent texture keyed by `id` (the+ /// guest XFB address). [`PresentXfb`] composites the latest snapshots.CopyXfb {id: Address,src_x: u32,@@ -98,9 +97,9 @@ pub enum GxAction {alpha_supported: bool,},- /// Composite all XFB copies from this frame into the output framebuffer.- /// Emitted once per vblank by `present_xfb()`. Each [`XfbPart`]- /// identifies a copy by `id` and places it at `(offset_x, offset_y)`.+ /// Composite the scanned buffer's XFB regions into the output+ /// framebuffer. Emitted by `present_xfb()` at the end of each field's+ /// active video. Later parts win overlapping rows.PresentXfb {width: u32,height: u32,