rustynes_core/bus.rs
1// SPDX-License-Identifier: GPL-3.0-or-later
2//
3// Provenance: this bus is RustyNES's own, but it incorporates models ported from TriCNES (MIT): the OAM-DMA register-window read (`oam_dma_read_reg_active`) is a direct port of TriCNES's `Fetch` address-bus-window block, and the unified DMA engine's state (`dmc_halt`, `uni_oam_active` / `_halt` / `_aligned` / `_addr`) is modelled on TriCNES's DMA flags. See docs/originality-and-provenance.md (Section 1)
4// and NOTICE for the complete, audited derivation record.
5//! The system bus behind the `Nes` facade.
6//!
7//! Per `docs/scheduler.md` §Bus design: [`SystemBus`] owns CPU RAM, the PPU,
8//! the APU, the cartridge mapper, the controller ports and the two data-bus
9//! latches, and implements `rustynes_cpu::Bus`. The CPU clocks every cycle in
10//! two halves (ADR 0002 / ADR 0029): `run_ppu_to` catches the PPU up to the
11//! master clock, `cpu_clock` runs the cycle-start work (APU, mapper hook,
12//! the deferred controller strobe), the access is dispatched to the right
13//! device, and `cpu_clock_apu_dmc` ticks the DMC at the cycle's end. OAM and
14//! DMC DMA run through one unified engine (`unified_dma_cycle_impl`), one
15//! full CPU cycle at a time.
16//!
17//! The type was `LockstepBus` until v2.9.8 (ADR 0042), a name left over from
18//! the pre-v2.0.0 dot-lockstep scheduler.
19
20use alloc::collections::BTreeMap;
21use alloc::format;
22use alloc::{boxed::Box, vec::Vec};
23
24use crate::genie::{GenieCode, GenieError};
25use rustynes_apu::{Apu, ApuSnapshotError, Region as ApuRegion};
26
27/// v2.0 R1c-1 DIAGNOSTIC (gated `cpu-instr-cycle-trace`).
28///
29/// A per-CPU-instruction `(PC, cumulative cpu_cycle)` ring buffer (keeps the
30/// LAST `CAP` instructions). `Cpu::step` calls `trace_instr` at each opcode
31/// fetch; the harness dumps the ring (R1 + default) and diffs the
32/// per-instruction cycle deltas to pin the odd-cycle cumulative divergence (the
33/// Y=3-vs-4 source). Read via `rustynes_core::instr_trace`.
34#[cfg(feature = "cpu-instr-cycle-trace")]
35pub mod instr_trace {
36 use core::sync::atomic::{AtomicU32, AtomicU64, Ordering::Relaxed};
37 /// Ring capacity (last CAP instructions kept).
38 pub const CAP: usize = 1 << 18; // 262144
39 /// Per-entry instruction PC.
40 pub static PC: [AtomicU32; CAP] = [const { AtomicU32::new(0) }; CAP];
41 /// Per-entry cumulative CPU cycle.
42 pub static CYC: [AtomicU64; CAP] = [const { AtomicU64::new(0) }; CAP];
43 /// Monotonic write index (total instructions; ring slot = `IDX % CAP`).
44 pub static IDX: AtomicU64 = AtomicU64::new(0);
45
46 /// Record one instruction `(pc, cpu_cycle)` into the ring.
47 #[allow(clippy::cast_possible_truncation)]
48 pub fn record(pc: u16, cpu_cycle: u64) {
49 let slot = (IDX.fetch_add(1, Relaxed) % CAP as u64) as usize;
50 PC[slot].store(u32::from(pc), Relaxed);
51 CYC[slot].store(cpu_cycle, Relaxed);
52 }
53}
54use rustynes_cpu::Bus;
55use rustynes_mappers::{Cartridge, Mapper, MapperError, MapperFrameEvents, RomError};
56use rustynes_ppu::{
57 BgSplitState as PpuBgSplitState, ExAttribute as PpuExAttribute, PaletteInit, Ppu, PpuBus,
58 PpuPalette, PpuRegion, PpuRevision, PpuSnapshotError,
59};
60
61use crate::Cpu2A03Revision;
62use crate::controller::{Buttons, Controller};
63#[cfg(feature = "irq-timing-trace")]
64use crate::irq_trace::{BusAccess, CycleRecord, IrqTrace};
65use crate::save_state::{self, SnapshotError};
66
67/// CPU RAM (2 KiB).
68const RAM_SIZE: usize = 0x0800;
69
70/// OAM DMA source-page write target (`$4014`). Triggers a 256-byte DMA on
71/// the next CPU read cycle.
72const REG_OAM_DMA: u16 = 0x4014;
73
74/// Default audio sample rate. The frontend may rebuild the bus with a
75/// different rate when CPAL picks something else.
76pub const DEFAULT_SAMPLE_RATE: u32 = 44_100;
77
78/// Map the cartridge-layer [`rustynes_mappers::VsPpuPalette`] to the PPU's
79/// [`PpuPalette`]. `rustynes-core` is the one crate that depends on both `rustynes-ppu`
80/// and `rustynes-mappers`, so the bridge lives here rather than creating a
81/// cross-crate dependency edge.
82const fn vs_palette_to_ppu(p: rustynes_mappers::VsPpuPalette) -> PpuPalette {
83 match p {
84 rustynes_mappers::VsPpuPalette::Composite2C02 => PpuPalette::Composite2C02,
85 rustynes_mappers::VsPpuPalette::Rgb2C03 => PpuPalette::Rgb2C03,
86 rustynes_mappers::VsPpuPalette::Rgb2C04_0001 => PpuPalette::Rgb2C04_0001,
87 rustynes_mappers::VsPpuPalette::Rgb2C04_0002 => PpuPalette::Rgb2C04_0002,
88 rustynes_mappers::VsPpuPalette::Rgb2C04_0003 => PpuPalette::Rgb2C04_0003,
89 rustynes_mappers::VsPpuPalette::Rgb2C04_0004 => PpuPalette::Rgb2C04_0004,
90 rustynes_mappers::VsPpuPalette::Rgb2C05 => PpuPalette::Rgb2C05,
91 }
92}
93
94/// Initial reset state for the bus.
95fn fresh_ram() -> Box<[u8; RAM_SIZE]> {
96 // Deterministic seeded fill — for now zero, matching most emulators'
97 // "post-power-on" approximation.
98 Box::new([0u8; RAM_SIZE])
99}
100
101/// v1.1.0 beta.2 (Workstream C, T-110-C3) — the class of a captured CPU write.
102///
103/// One per event-viewer timeline entry: PPU `$2000-$3FFF`, APU `$4000-$4017`,
104/// or mapper `$4020-$FFFF`, tagged (in [`EventRec`]) with the PPU position at
105/// the moment of the write.
106#[cfg(feature = "debug-hooks")]
107#[derive(Clone, Copy, Debug, Eq, PartialEq)]
108pub enum EventKind {
109 /// A `$2000-$3FFF` PPU-register write.
110 PpuWrite,
111 /// A `$4000-$4017` APU / I/O-register write.
112 ApuWrite,
113 /// A `$4020-$FFFF` mapper-register write.
114 MapperWrite,
115 /// A `$2000-$3FFF` PPU-register read (v1.5.0 Workstream A2 — the graphical
116 /// PPU Event Viewer draws reads as well as writes, so the read/write heatmap
117 /// + the register-access table can show both directions).
118 PpuRead,
119}
120
121#[cfg(feature = "debug-hooks")]
122impl EventKind {
123 /// Whether this event is a CPU read (vs a write). Used by the v1.5.0 PPU
124 /// Event Viewer heatmap to colour reads (blue) vs writes (red).
125 #[must_use]
126 pub const fn is_read(self) -> bool {
127 matches!(self, Self::PpuRead)
128 }
129}
130
131/// One event-viewer record: kind + the PPU `(scanline, dot)` + the address +
132/// (v1.5.0 A2) the byte read or written.
133#[cfg(feature = "debug-hooks")]
134#[derive(Clone, Copy, Debug)]
135pub struct EventRec {
136 /// What happened.
137 pub kind: EventKind,
138 /// PPU scanline at the event (`-1` = pre-render, `0..=239` visible, ...).
139 pub scanline: i16,
140 /// PPU dot (`0..=340`).
141 pub dot: u16,
142 /// The accessed address.
143 pub addr: u16,
144 /// The byte written, or the byte the read returned (v1.5.0 Workstream A2).
145 pub value: u8,
146}
147
148/// Max events captured per frame (bounded so a write-heavy frame can't grow the
149/// log without limit; a frame has at most a few thousand CPU writes).
150#[cfg(feature = "debug-hooks")]
151const EVENT_CAP: usize = 20_000;
152
153/// v1.1.0 beta.3 (Workstream E, T-110-E2) — one CPU bus-access record for the
154/// Lua `onRead` / `onWrite` callbacks: direction + full address + the byte.
155///
156/// Distinct from [`EventRec`] (which is the scanline/dot-oriented event-viewer
157/// record): this captures *every* CPU read and write across the whole address
158/// space, with the value, so a script can react to a specific access. Output-
159/// only and gated behind `access_logging`; the host (Lua engine) enables it
160/// only while `onRead`/`onWrite` callbacks are registered.
161#[cfg(feature = "debug-hooks")]
162#[derive(Clone, Copy, Debug)]
163pub struct AccessRec {
164 /// `true` for a CPU write, `false` for a CPU read.
165 pub write: bool,
166 /// The accessed CPU address (`$0000-$FFFF`).
167 pub addr: u16,
168 /// The byte written, or the byte the read returned.
169 pub value: u8,
170}
171
172/// Max bus accesses captured per frame. A frame issues on the order of 30k CPU
173/// cycles; this caps the worst case so a tight loop can't grow the log
174/// unbounded. A frame that overflows the cap is truncated (the tail is dropped).
175#[cfg(feature = "debug-hooks")]
176const ACCESS_CAP: usize = 60_000;
177
178/// v1.2.0 (Workstream E, T-110-E1) — one interrupt-service record for the Lua
179/// `onNmi` / `onIrq` callbacks: the service direction + the vector the CPU
180/// fetched its new PC from.
181///
182/// Captured at the commit point — [`Bus::notify_irq_service`], called once per
183/// real interrupt entry right before the CPU reads the service vector. This is
184/// the *committed* service (the same point the IRQ trace records), NOT the
185/// speculative `poll_nmi` / `poll_irq` sampler that ADR 0010 flagged as
186/// unreliable — so a script that watches `onNmi`/`onIrq` sees exactly the
187/// interrupts the CPU actually serviced this frame, in order. Output-only and
188/// gated behind `interrupt_logging`; the host (Lua engine) enables it only
189/// while `onNmi`/`onIrq` callbacks are registered.
190#[cfg(feature = "debug-hooks")]
191#[derive(Clone, Copy, Debug, Eq, PartialEq)]
192pub struct InterruptRec {
193 /// `true` for an NMI service entry (`$FFFA`), `false` for an IRQ/BRK
194 /// service entry (`$FFFE`).
195 pub is_nmi: bool,
196 /// The service vector the CPU fetched its new PC from (`$FFFA` for an NMI,
197 /// `$FFFE` for IRQ/BRK).
198 pub vector: u16,
199}
200
201/// Max interrupt-service records captured per frame. A frame services at most a
202/// few hundred interrupts (NMI once + mapper/APU IRQs); this caps a pathological
203/// case so the log can't grow unbounded. A frame that overflows is truncated.
204#[cfg(feature = "debug-hooks")]
205const INTERRUPT_CAP: usize = 4_096;
206
207/// v1.4.0 Workstream D (D2) — the class of hardware event an event-driven
208/// breakpoint can trigger on.
209///
210/// These are tapped at the SAME observational commit points the event-viewer /
211/// interrupt-service / bus-access logs already use (`Bus::cpu_read`,
212/// `Bus::cpu_write`, `Bus::notify_irq_service`, the DMC-DMA GET, the `$4014`
213/// write). A hit only RECORDS the event (kind + PPU position); it never mutates
214/// emulator-visible state, so the determinism contract holds and the
215/// feature-off build is byte-identical.
216///
217/// The 16 categories are packed into a `u16` arm mask (see
218/// [`SystemBus::set_event_breakpoints`]); the bit index is the discriminant.
219#[cfg(feature = "debug-hooks")]
220#[derive(Clone, Copy, Debug, Eq, PartialEq)]
221#[repr(u8)]
222pub enum EventBpKind {
223 /// An NMI service entry (`$FFFA`), observed at the interrupt-service commit.
224 Nmi = 0,
225 /// An IRQ / BRK service entry (`$FFFE`), observed at the same commit.
226 Irq = 1,
227 /// A sprite-0 hit, observed when the CPU reads `$2002` with bit 6 set (the
228 /// point games actually detect the hit; purely observational).
229 Sprite0Hit = 2,
230 /// An OAM DMA, observed at the `$4014` write that starts it.
231 OamDma = 3,
232 /// A DMC DMA sample fetch (the GET cycle).
233 DmcDma = 4,
234 /// A PPU-register read (`$2000-$3FFF`).
235 PpuRead = 5,
236 /// A PPU-register write (`$2000-$3FFF`).
237 PpuWrite = 6,
238 /// An APU / I/O-register read (`$4000-$4017`).
239 ApuRead = 7,
240 /// An APU / I/O-register write (`$4000-$4017`).
241 ApuWrite = 8,
242 /// A mapper-register read (`$4020-$FFFF`).
243 MapperRead = 9,
244 /// A mapper-register write (`$4020-$FFFF`).
245 MapperWrite = 10,
246}
247
248#[cfg(feature = "debug-hooks")]
249impl EventBpKind {
250 /// The arm-mask bit for this kind.
251 #[must_use]
252 pub const fn bit(self) -> u16 {
253 1u16 << (self as u8)
254 }
255
256 /// A human-readable label (used by the debugger UI + tests).
257 #[must_use]
258 pub const fn label(self) -> &'static str {
259 match self {
260 Self::Nmi => "NMI entry",
261 Self::Irq => "IRQ entry",
262 Self::Sprite0Hit => "Sprite-0 hit",
263 Self::OamDma => "OAM DMA",
264 Self::DmcDma => "DMC DMA",
265 Self::PpuRead => "PPU read",
266 Self::PpuWrite => "PPU write",
267 Self::ApuRead => "APU read",
268 Self::ApuWrite => "APU write",
269 Self::MapperRead => "Mapper read",
270 Self::MapperWrite => "Mapper write",
271 }
272 }
273
274 /// All categories, in discriminant order (for the UI checkbox list).
275 #[must_use]
276 pub const fn all() -> [Self; 11] {
277 [
278 Self::Nmi,
279 Self::Irq,
280 Self::Sprite0Hit,
281 Self::OamDma,
282 Self::DmcDma,
283 Self::PpuRead,
284 Self::PpuWrite,
285 Self::ApuRead,
286 Self::ApuWrite,
287 Self::MapperRead,
288 Self::MapperWrite,
289 ]
290 }
291}
292
293/// v1.4.0 Workstream D (D2) — one event-driven breakpoint hit.
294///
295/// Carries the kind, the associated address (`0` for the interrupt entries that
296/// carry none), and the full timing context (frame / CPU cycle / PPU
297/// scanline+dot) at the moment of the event. Recorded by the first armed-event
298/// tap of a frame; the frontend takes it via
299/// [`crate::Nes::take_event_break_hit`] to pause + report.
300#[cfg(feature = "debug-hooks")]
301#[derive(Clone, Copy, Debug, Eq, PartialEq)]
302pub struct EventBreakHit {
303 /// Which event fired.
304 pub kind: EventBpKind,
305 /// The associated CPU address (the read/write address, the OAM-DMA `$4014`,
306 /// the DMC sample address, or the service vector for NMI/IRQ).
307 pub addr: u16,
308 /// PPU frame counter at the event.
309 pub frame: u64,
310 /// Cumulative CPU cycle at the event.
311 pub cycle: u64,
312 /// PPU scanline (`-1` pre-render .. `260`).
313 pub scanline: i16,
314 /// PPU dot (`0..=340`).
315 pub dot: u16,
316}
317
318/// The system bus.
319///
320/// Owns the entire emulator's mutable state. The CPU borrows `&mut SystemBus`
321/// during `Cpu::step`, and the bus advances the PPU (`run_ppu_to`, 3 dots per
322/// CPU cycle on NTSC / Dendy, 3.2 on PAL) and the APU (`cpu_clock`, every CPU
323/// cycle) from the hooks the CPU calls around each access. Named
324/// `LockstepBus` until v2.9.8 (ADR 0042).
325// The bus carries many independent `bool` state words (the Four Score and
326// Vs. flags, `in_dmc_dma`, the unified DMA engine's OAM latches, the
327// debug-hook toggles). They are not a single enum-modelled machine, so
328// silencing the lint is the right call.
329#[allow(clippy::struct_excessive_bools)]
330pub struct SystemBus {
331 /// CPU RAM (2 KiB), mirrored every 0x800 bytes from `$0000-$1FFF`.
332 pub(crate) ram: Box<[u8; RAM_SIZE]>,
333 /// PPU instance.
334 pub(crate) ppu: Ppu,
335 /// APU instance.
336 pub(crate) apu: Apu,
337 /// Cartridge metadata (kept for save-state and debugger).
338 pub(crate) cart: Cartridge,
339 /// Boxed mapper.
340 pub(crate) mapper: Box<dyn Mapper>,
341 /// v2.8.0 Phase 4 — the mapper's capability flags, cached at
342 /// construction (and refreshed when [`Self::power_cycle`] rebuilds the
343 /// mapper) so the per-CPU-cycle hot loop can skip the up-to-four
344 /// virtual dispatches (`notify_cpu_cycle` / `mix_audio` /
345 /// `notify_frame_event` / `irq_pending`) on boards that don't use
346 /// them. Constant per mapper type; NOT part of the save-state.
347 mapper_caps: rustynes_mappers::MapperCaps,
348 /// v3.2.0 — [`Mapper::may_unmap_prg_rom`], cached beside
349 /// [`Self::mapper_caps`] with the same refresh points. When `false` the
350 /// `$8000-$FFFF` read path skips the per-read `cpu_read_unmapped`
351 /// dispatch. Constant per mapper type; NOT part of the save-state.
352 prg_may_unmap: bool,
353 /// v3.5.0 — [`Mapper::snoops_ppu_reads`], cached beside
354 /// [`Self::mapper_caps`] with the same refresh points and handed to every
355 /// [`PpuBusAdapter`]. When `false` (every board but the MMC5) the PPU's
356 /// per-read `notify_ppu_read` stops at one branch in the adapter instead
357 /// of a virtual call. Constant per mapper type; NOT part of the
358 /// save-state.
359 ppu_read_snoop: bool,
360 /// The original iNES/NES-2.0 ROM bytes, kept so [`Self::power_cycle`] can
361 /// rebuild the mapper to a true power-on state (fresh bank registers,
362 /// cleared CHR-RAM + volatile PRG-RAM). `None` on the FDS path (which has
363 /// no iNES image; FDS netplay is unsupported). NOT part of the save-state
364 /// (constant; the encoder skips it).
365 rom_bytes: Option<Box<[u8]>>,
366 /// Standard NES controllers (player 1 on `$4016`, player 2 on `$4017`).
367 pub(crate) controllers: [Controller; 2],
368 /// Four Score 4-player adapter. When `true`, `$4016`/`$4017` multiplex
369 /// four controllers + an adapter signature over a 24-read serial sequence
370 /// (nesdev "Four score"; matches `Mesen2` / `TetaNES`). When `false` (default)
371 /// the read path is byte-identical to the standard two-controller
372 /// behavior, so the determinism contract and existing save-states are
373 /// unaffected.
374 four_score: bool,
375 /// v2.1.7 P5 — power-on 2 KiB work-RAM fill selection. [`crate::nes::PowerOnRam::Zeroed`]
376 /// (default) leaves the established all-zero power-up state; the other
377 /// variants are opt-in and deterministic. Stored so [`Self::power_cycle`] can
378 /// re-apply the same fill after it zeroes RAM, keeping `power_cycle == fresh
379 /// boot`. At the default this is inert (the zero fill matches `fresh_ram()`).
380 power_on_ram: crate::nes::PowerOnRam,
381 /// v2.1.7 P5 — selected 2C02 die revision (see [`PpuRevision`]). Stored so
382 /// [`Self::power_cycle`] can re-apply it after the PPU is reconstructed
383 /// (the PPU field is lost on rebuild, like the Vs. palette).
384 /// [`PpuRevision::default`] models no extra behavior → byte-identical.
385 ppu_die_revision: PpuRevision,
386 /// v2.9.8 — which console's reset wiring is modelled (see
387 /// [`crate::nes::ConsoleModel`]). Consulted at power-on and warm reset.
388 /// [`crate::nes::ConsoleModel::Nes`] (default) is byte-identical to every
389 /// earlier release. Config, not save-state.
390 console_model: crate::nes::ConsoleModel,
391 /// v2.1.7 P5 — selected power-up palette pattern (see [`PaletteInit`]).
392 /// Re-applied on [`Self::power_cycle`] after the PPU (and thus its palette
393 /// RAM) is rebuilt. [`PaletteInit::default`] is all-zero → byte-identical.
394 power_up_palette: PaletteInit,
395 /// Players 3 (`$4016`) and 4 (`$4017`) — only polled when
396 /// [`Self::four_score`] is set.
397 controllers34: [Controller; 2],
398 /// Per-port Four Score read counter (0-7 = primary pad, 8-15 = secondary
399 /// pad, 16-23 = signature, then 1s). Reset on each strobe.
400 four_score_idx: [u8; 2],
401 /// Does the Four Score chain owe a clock edge on this port?
402 ///
403 /// The exact counterpart of `Controller::pending_shift`, and it exists for
404 /// the same reason. v2.6.5 made a contiguous read of a port return the same
405 /// bit — `CLK` stays low across the run, so the pads do not advance — but
406 /// the adapter's 24-read multiplexer went on advancing `four_score_idx` and
407 /// shifting `four_score_sig` on EVERY read. The chain then ran ahead of the
408 /// pads feeding it: a contiguous pair at index 7 moved to the pad-3 window
409 /// after only seven advances of pad 1, and a pair inside the signature
410 /// window consumed two signature bits where the hardware returns one twice.
411 ///
412 /// The Four Score is one shift chain, so it clocks on the same edge the
413 /// pads do. Cleared by a strobe, exactly as `pending_shift` is.
414 four_score_pending: [bool; 2],
415 /// CPU cycle of the most recent read of each controller port, or
416 /// `u64::MAX` for "never".
417 ///
418 /// `CLK` on the controller port is LOW only while `$4016`/`$4017` is being
419 /// read, and the shift register advances on its low-to-high transition —
420 /// when the read ENDS. Consecutive read cycles hold it low throughout and
421 /// so produce one edge between them, not two. This is what says whether a
422 /// read continues such a run. Every CPU cycle is a bus access in this core
423 /// (ADR 0029), so cycle adjacency IS address-bus continuity.
424 port_read_cycle: [u64; 2],
425 /// Per-port Four Score signature shift register, reloaded on each strobe
426 /// (port 0 = `0x08`, port 1 = `0x04`; shifted out LSB-first).
427 four_score_sig: [u8; 2],
428 /// Output-only `TAStudio` lag-log flag (v1.6.0 Workstream A3): set `true`
429 /// whenever the running program reads a controller port (`$4016`/`$4017`)
430 /// during the current frame; cleared at the top of each
431 /// [`crate::Nes::run_frame`]. A frame still `false` at frame end is a "lag
432 /// frame" (the game polled no input that frame). `debug-hooks`-gated and
433 /// never read back into emulation, so the shipped build stays byte-identical
434 /// and the determinism contract is unaffected.
435 #[cfg(feature = "debug-hooks")]
436 controller_polled: bool,
437 /// Vs. System DIP switches (8 bits, switch 1 = bit 0 .. switch 8 = bit 7).
438 /// Read through the upper bits of `$4016`/`$4017` per the Vs. protocol
439 /// (nesdev "Vs. System"). Only consulted when the cart is
440 /// [`rustynes_mappers::ConsoleType::VsSystem`]; on a standard NES cart the
441 /// `$4016`/`$4017` read path is byte-identical regardless of this value.
442 vs_dip: u8,
443 /// Vs. System coin-acceptor state: bit 0 = acceptor #1 ($4016 bit 5),
444 /// bit 1 = acceptor #2 ($4016 bit 6). A real coin pulse reads true for
445 /// ~40-70 ms; the frontend latches it for a configurable number of frames
446 /// via [`SystemBus::insert_coin`] and clears it with
447 /// [`SystemBus::clear_coin`]. Vs.-System carts only.
448 vs_coin: u8,
449 /// Vs. System service button ($4016 bit 2). Vs.-System carts only.
450 vs_service: bool,
451 /// v2.0.0 beta.5 (Vs. `DualSystem`): `true` when this console is the SUB
452 /// half of a `DualSystem` pair — `$4016` reads then return bit 7 = `0x80`
453 /// (the main/sub identity bit the ROM polls; hard-pinned `0` on a single
454 /// console, byte-identically). Set only by the `VsDualSystem` wrapper.
455 vs_is_sub: bool,
456 /// v2.0.0 beta.5 (Vs. `DualSystem`): the external `/IRQ` line driven by the
457 /// PARTNER console's `$4016` bit-1 signal (Mesen2 `IRQSource::External`
458 /// via `UpdateMainSubBit`). OR'd into [`Bus::irq_level`]; always `false`
459 /// on a single console, so the default IRQ path is byte-identical.
460 vs_external_irq: bool,
461 /// v2.0.0 beta.5 (Vs. `DualSystem`): the last `$4016`-write bit-1 value
462 /// (the main/sub comms signal) + a dirty latch the wrapper polls after
463 /// each step batch. The bus only RECORDS the LEVEL (deliberately not
464 /// edge-filtered — see [`Self::vs_4016_bit1_dirty`]); the cross-console
465 /// wiring (asserting the partner's `/IRQ`, the shared-WRAM swap) lives in
466 /// the wrapper — no bus ever references the other console.
467 vs_4016_bit1: bool,
468 /// See [`Self::vs_4016_bit1`] — set on EVERY `$4016` write, regardless
469 /// of whether bit 1 changed; cleared by [`Self::take_vs_mainsub_edge`].
470 /// Deliberately level-driven, not edge-filtered: at reset both consoles
471 /// write `$4016 = $00` to establish the wrapper's seeded main/sub
472 /// levels, and an edge filter starting from a `false` latch would
473 /// swallow that seeded-HIGH -> written-LOW transition and deadlock the
474 /// boot handshake (see the `cpu_write` `$4016` arm for the full
475 /// rationale). Re-applying an unchanged level is idempotent in the
476 /// wrapper, so marking every write dirty (not just changed ones) is
477 /// correct, if conservatively named.
478 vs_4016_bit1_dirty: bool,
479 /// Optional non-standard input-device overlay per port (`$4016`/`$4017`).
480 /// When a port has `Some(device)`, [`Self::read_port`] returns that
481 /// device's byte instead of the standard controller / Four Score serial
482 /// byte. `None` (the default) leaves the existing path byte-identical, so
483 /// the default + Four Score reads and the determinism contract are
484 /// unaffected unless a device is explicitly attached.
485 expansion_device: [Option<crate::input_device::InputDevice>; 2],
486 /// A3 (v2.2.3): serve a Zapper's light bit from the beam-relative
487 /// temporal model instead of the frame-granular one. Default **on** since
488 /// v2.3.6 (the constructor sets `true`); off restores the frame-granular
489 /// model. See [`SystemBus::set_zapper_temporal_light`].
490 zapper_temporal_light: bool,
491 /// Famicom built-in **microphone** signal (v2.2.0 "Capstone"). The hardwired
492 /// second Famicom controller carries a push-to-talk microphone whose state is
493 /// read on **`$4016` bit 2** (not `$4017`) — games such as *The Legend of
494 /// Zelda* (killing Pols Voice), *Kid Icarus*, *Raid on Bungeling Bay*, and
495 /// *Takeshi no Chōsenjō* poll it. Modelled as a single live bit (the analog
496 /// mic is quantized to "loud enough / not" by the frontend, matching how the
497 /// Famicom's comparator fed the port): `true` ORs `1` into `$4016.D2`.
498 /// Default `false` leaves the `$4016` read byte-identical (bit 2 is otherwise
499 /// open-bus / 0), so the standard controller path is unaffected until a
500 /// frontend explicitly drives the mic via [`Self::set_microphone`].
501 famicom_mic: bool,
502 /// v1.1.0 beta.1 (T-110-B4) — optional per-game nametable mirroring
503 /// override. `None` (default) defers to the mapper's `nametable_address`
504 /// (byte-identical). When `Some`, the standard `$2000-$3EFF` nametable
505 /// translation uses this mirroring instead — a load-time correction for
506 /// ROMs with a wrong iNES mirroring flag, supplied by the frontend's game
507 /// database. Does NOT affect mapper-supplied VRAM (`nametable_fetch`, e.g.
508 /// 4-screen). Persisted in the save-state so rollback / restore stay
509 /// consistent. The core test suites never set it, so `AccuracyCoin` / the
510 /// oracle are unaffected.
511 nt_mirroring_override: Option<rustynes_mappers::Mirroring>,
512 /// v1.1.0 beta.2 (T-110-C3) — event-viewer log (this frame's CPU-write
513 /// events). Output-only; populated only while `event_logging`, cleared per
514 /// frame. Gated on `debug-hooks` so the default hot path is untouched.
515 #[cfg(feature = "debug-hooks")]
516 events: alloc::vec::Vec<EventRec>,
517 /// Whether the event viewer is recording. Default `false`.
518 #[cfg(feature = "debug-hooks")]
519 event_logging: bool,
520 /// v1.1.0 beta.3 (T-110-E2) — full CPU bus-access log (reads + writes +
521 /// values) for the Lua `onRead`/`onWrite` callbacks. Output-only; populated
522 /// only while `access_logging`, cleared per frame.
523 #[cfg(feature = "debug-hooks")]
524 accesses: alloc::vec::Vec<AccessRec>,
525 /// Whether the bus-access log is recording. Default `false`.
526 #[cfg(feature = "debug-hooks")]
527 access_logging: bool,
528 /// v1.2.0 (T-110-E1) — per-frame interrupt-service log (this frame's
529 /// committed NMI / IRQ / BRK service entries) for the Lua `onNmi`/`onIrq`
530 /// callbacks. Output-only; populated only while `interrupt_logging`, cleared
531 /// per frame.
532 #[cfg(feature = "debug-hooks")]
533 interrupts: alloc::vec::Vec<InterruptRec>,
534 /// Whether the interrupt-service log is recording. Default `false`.
535 #[cfg(feature = "debug-hooks")]
536 interrupt_logging: bool,
537 /// v1.4.0 Workstream D (D2) — armed event-breakpoint categories, packed as a
538 /// bitmask of [`EventBpKind::bit`]. `0` (default) disarms every category, so
539 /// the per-access tap is a single `mask == 0` early-out — the default + the
540 /// feature-off build are byte-identical and pay no per-cycle cost. Output-
541 /// only: a hit records [`Self::event_break_hit`] but never mutates state.
542 #[cfg(feature = "debug-hooks")]
543 event_bp_mask: u16,
544 /// The first event-breakpoint hit of the current frame (`None` until one
545 /// fires). Recorded by the taps, taken by the frontend after `run_frame`.
546 #[cfg(feature = "debug-hooks")]
547 event_break_hit: Option<EventBreakHit>,
548 /// Cumulative CPU cycle counter.
549 pub(crate) cycle: u64,
550
551 /// OAM DMA pending source page (set by `$4014` write; consumed on the
552 /// next `cpu_read`/`cpu_write`).
553 dma_pending: Option<u8>,
554 /// OAM DMA scratch byte: read on even cycles, written on odd cycles.
555 dma_byte: u8,
556 /// OAM DMA active source page (latched from `dma_pending`).
557 dma_page: u8,
558 /// CPU read address that OAM DMA halted. While the CPU is halted,
559 /// no-op DMA cycles keep this address on the 6502 core bus.
560 dma_halt_addr: u16,
561
562 /// v2.5.1 (ADR 0038) — externally asserted /NMI, for co-simulation only.
563 ///
564 /// Active-high here (`true` = the pin is asserted, i.e. /NMI low). It is
565 /// OR'd into the poll rather than replacing it, so an injected NMI and a
566 /// PPU-generated one are the same event to the CPU -- which is the point:
567 /// the API sets the pin the CPU samples and does nothing else. It does not
568 /// bypass the poll, force a vector, or short-circuit the sequence.
569 ///
570 /// The field does not exist in a default build.
571 #[cfg(feature = "cosim-interrupt-inject")]
572 inject_nmi: bool,
573 /// v2.5.1 (ADR 0038) — externally asserted /IRQ. Level-sensitive, exactly
574 /// as the pin is, so it is masked by `I` through the CPU's own logic and a
575 /// pulse shorter than a poll is missed. Modelling it as a latch would make
576 /// injected IRQs behave unlike real ones.
577 #[cfg(feature = "cosim-interrupt-inject")]
578 inject_irq: bool,
579
580 /// v2.0 master-clock R1 substrate (Phase 1): PPU progress in master-clock
581 /// units, consumed by `run_ppu_to(target)` (ticks a dot while
582 /// `ppu_clock + ppu_divider <= target`). Only used under the R1 CPU loop.
583 ppu_clock: u64,
584 /// v2.0 master-clock R1 substrate: the cartridge region's `(cpu_divider,
585 /// ppu_divider)` in master clocks (NTSC 12/4, PAL 16/5, Dendy 15/5),
586 /// computed once at construction. The region never changes after power-on,
587 /// so caching these removes the per-CPU-cycle `match self.cart.region` from
588 /// the hottest R1 paths (`cpu_divider`, `run_ppu_to`). Behaviour-identical:
589 /// the value equals what the prior `region_dividers()` match returned.
590 cpu_div_cached: u8,
591 ppu_div_cached: u8,
592
593 /// v3.1.0 (`T-CPU-OVERCLOCK`): the CPU-multiplier overclock, `1..=4`
594 /// ([`crate::MAX_CPU_OVERCLOCK`]); `1` is stock. Configuration, like the
595 /// extra-scanline overclock: not part of the save-state, re-applied by
596 /// the host (and by a movie's or netplay session's options record).
597 cpu_overclock: u8,
598 /// v3.1.0 (`T-MMC3-NEC-OVERRIDE`): a forced MMC3 IRQ revision, or `None`
599 /// for the header's. Configuration, re-applied to every mapper the bus
600 /// builds (a power cycle rebuilds it); only mapper 4 acts on it.
601 mmc3_revision_override: Option<rustynes_mappers::Mmc3Revision>,
602 /// The master clocks the CPU cycle in progress takes under the overclock,
603 /// [`overclock_cycle_len`] of `overclock_phase`; `cpu_div_cached` at
604 /// `x1`. This is what [`Bus::cpu_divider`] returns. It changes only at a
605 /// cycle's END (`cpu_clock_apu_dmc`), because the CPU reads the divider
606 /// twice per cycle, once for each half, and both reads must agree.
607 ///
608 /// Until the v3.1.0 review (#594) this was `cpu_div_cached / k`, rounded
609 /// down: exact on NTSC (12 divides by 2, 3 and 4) and wrong elsewhere,
610 /// `x3` on PAL (16) running 3.2x and `x4` on Dendy (15) 5x, so a movie
611 /// that recorded "x4" did not get four times the CPU.
612 cpu_div_effective: u8,
613 /// Which of the `k` CPU cycles of the current stock cycle is in progress,
614 /// `0..cpu_overclock`.
615 ///
616 /// Under the overclock the APU, the DMC, the mappers' CPU-cycle hooks and
617 /// the PPU's open-bus / post-reset timers stay at the STOCK rate, so a
618 /// game gets more CPU time per frame without a pitch change, a faster
619 /// tempo or cycle-timed mapper IRQs firing early. Every `k` CPU cycles
620 /// make one stock cycle exactly: cycle `i` of the group lasts
621 /// [`overclock_cycle_len`] master clocks, which sum to `cpu_div_cached`
622 /// over the group (PAL x3: 5, 5, 6), and the stock step runs on the last.
623 /// Always 0 at `x1`, where every CPU cycle is a stock step. In the BUS
624 /// save-state section: run-ahead restores mid-run.
625 overclock_phase: u8,
626 /// The stock-rate domain's own cycle counter under the overclock, handed
627 /// to the APU in place of the CPU cycle counter (the APU derives its
628 /// put/get phase from it). Re-based to [`Self::cycle`] when the overclock
629 /// is switched on, so the phase continues; unused at `x1`. In the BUS
630 /// save-state section.
631 apu_cycle: u64,
632 /// Whether the cycle in progress is a stock step (set in `cpu_clock`,
633 /// read by `cpu_clock_apu_dmc` at the same cycle's end). Always `true` at
634 /// `x1`. Transient: a snapshot is taken between cycles.
635 stock_step: bool,
636
637 /// External CPU data bus latch: last value driven onto the bus
638 /// by ANY device (CPU, DMC DMA, OAM DMA conflict reads).
639 ///
640 /// This is the classic "open bus" floating-latch value that NES
641 /// emulation refers to. Reads from unmapped or open-bus regions
642 /// return this value; the upper 3 bits of the controller-strobe
643 /// register reads (`$4016` / `$4017`) bleed through from this
644 /// latch. DMC DMA fetches update this latch (because the DMC
645 /// drives the external bus during halt).
646 open_bus: u8,
647 /// Internal CPU data bus latch: last value driven onto the bus
648 /// by a CPU-initiated read or write.
649 ///
650 /// The 2A03 silicon has two distinct data buses. The
651 /// **internal** bus is driven only by CPU operations (instruction
652 /// fetch, operand read, ALU result, write). DMC DMA fetches
653 /// drive only the **external** bus (`open_bus` above) — the
654 /// internal bus retains its prior value across a DMC halt. This
655 /// distinction is invisible while the CPU runs unimpeded (the
656 /// two buses carry the same value), but it surfaces on the SH*
657 /// unstable-store family when DMC DMA interleaves with the
658 /// store's address-high-byte AND computation, and on the `$4015`
659 /// bit-5 open-bus read after a DMC DMA fetch.
660 ///
661 /// Phase 1 of the v1.0.0-final `linked-puzzling-sutherland`
662 /// brief (`to-dos/phase-6-v1.0.0-final/sprint-6-sh-unstable-stores.md`).
663 /// Mirrored from every `cpu_read` / `cpu_write` path; explicitly
664 /// NOT updated by `dmc_dma_read` (the DMC fetch path).
665 internal_data_bus: u8,
666
667 /// Most recent CPU bus access — used by the 2A03 DMC-DMA readout-bug
668 /// emulation. (Address only; some bug variants need the address, the
669 /// bus value is the open-bus latch above.)
670 last_read_addr: u16,
671 /// Side-effect register read whose absolute high-byte operand was
672 /// halted by DMC DMA one CPU read before the actual register access.
673 deferred_dma_replay_addr: u16,
674 /// True while we're servicing a DMC DMA fetch — used to suppress
675 /// recursion / re-entrancy when the DMA controller invokes `raw_cpu_read`.
676 in_dmc_dma: bool,
677 /// v2.0 interleaved-DMA Phase B (`mc-r1-substrate`): the `TriCNES`
678 /// `DMCDMA_Halt` flag — set when the interleaved DMC DMA starts, cleared
679 /// after a GET cycle. Gates whether the current get cycle is the halt
680 /// re-read or the actual sample fetch. Read and written by the unified
681 /// DMA engine (`unified_dma_cycle_impl`).
682 dmc_halt: bool,
683 /// v3.1.0 (`AccuracyCoin` "DMA Landing on Write", test 9): a pending LOAD
684 /// DMC DMA reached the get half on which it would have entered, but that
685 /// cycle was a CPU WRITE, and RDY cannot halt a write. The load then
686 /// enters on the very next read whichever half it is, so a load refused
687 /// by one write takes four cycles (`[Put (halt)] [Get] [Put] [Get]`)
688 /// instead of being deferred a second cycle to its get half and taking
689 /// three. Without this latch the CPU ran one real cycle the hardware
690 /// spends halted. Set in [`Bus::write`], consumed by the DMC entry in
691 /// `unified_dma_cycle_impl`, and cleared by the next CPU read either way.
692 ///
693 /// Written from the test ROM's own description (`TEST_DMALandingOnWrite`
694 /// test 9 and its cycle comments) and pinned by a black-box per-cycle
695 /// comparison against `TriCNES`'s output at the test's `STA $5000`. No
696 /// emulator source was consulted.
697 dmc_load_write_delayed: bool,
698 /// W3-Stage-1 (`mc-r1-dma-unified`): the unified engine's OAM-DMA-active
699 /// flag (`TriCNES` `DoOAMDMA` once latched). The 513/514 length is EMERGENT
700 /// from `uni_oam_halt`/`uni_oam_aligned` + the per-cycle dispatch — no
701 /// owed-cycle counter.
702 uni_oam_active: bool,
703 /// W3-Stage-1: `TriCNES` `OAMDMA_Halt` — set when the OAM DMA's FIRST
704 /// serviced cycle lands on the OAM engine's read half (at floor parity:
705 /// `put_cycle == true`, the floor's `self.cycle & 1 == 0` -> 514 case);
706 /// cleared at the end of every OAM-read-half cycle.
707 uni_oam_halt: bool,
708 /// W3-Stage-1: `TriCNES` `OAMDMA_Aligned` — set by the OAM read, consumed
709 /// by the OAM write; force-cleared by a DMC GET (the emergent post-GET
710 /// realign: the next write half becomes an alignment dummy and the byte
711 /// is re-read).
712 uni_oam_aligned: bool,
713 /// W3-Stage-1: `TriCNES` `DMAAddress` — the OAM byte index (0..=255;
714 /// reaching 256 on a write completes the DMA). Only increments on writes,
715 /// so a DMC-GET-stalled byte is re-read.
716 uni_oam_addr: u16,
717
718 /// v2.1.7 "Hardware Revisions & DMA Frontier" — the emulated Ricoh 2A03 die
719 /// revision, gating the DMA unit's "unexpected DMA" extra halt-read on the
720 /// DMC-halt-overlaps-OAM-halt cycle. **Default [`Cpu2A03Revision::Rp2A03G`]**
721 /// = byte-identical to the pre-v2.1.7 core; it performs the extra read *in
722 /// the model*, but that read is a documented no-op on every committed oracle
723 /// (the parked address during a DMC+OAM overlap is never a side-effect
724 /// register — see the enum docs + ADR 0033), so it changes nothing
725 /// observable. [`Cpu2A03Revision::Rp2A03H`] omits the modeled read and is
726 /// consequently byte-identical to `Rp2A03G` across the entire committed DMA
727 /// corpus today (opt-in, deterministic, unverified direction). A config
728 /// knob, NOT part of the save-state: the only state it influences (the
729 /// parked-address side-effect re-read count during a DMC+OAM overlap) is
730 /// fully re-derived from the deterministic timeline, so a save/restore
731 /// round-trip stays byte-identical for a fixed revision.
732 cpu_2a03_revision: Cpu2A03Revision,
733
734 /// Active Game Genie codes, keyed by the PRG address they patch
735 /// (`$8000-$FFFF`). Applied on the CPU read path; empty by default, so
736 /// with no codes active reads are byte-identical to a build without the
737 /// feature (the determinism contract is preserved). NOT part of the
738 /// save-state — codes are a user overlay persisted by the frontend, not
739 /// emulation state. See [`crate::genie`].
740 genie_codes: BTreeMap<u16, GenieCode>,
741
742 /// Deferred controller strobe write (Session-24 / Phase 3 of the
743 /// v1.0.0-final brief). Mirrors Mesen2's `NesControlManager`
744 /// `_writeAddr` / `_writeValue` / `_writePending` triplet (see
745 /// `Core/NES/NesControlManager.cpp` lines 252-273): a CPU write to
746 /// `$4016` (or `$4017`) does NOT directly update the controllers'
747 /// strobe state. Instead the write is buffered here.
748 /// `controller_write_pending` is set to 1 (odd-cycle write) or 2
749 /// (even-cycle write) at the moment of the CPU write, then
750 /// decremented every CPU cycle at the START of `cpu_clock` (the
751 /// cycle-start half of the one-clock scheduler); when it reaches 0 the buffered
752 /// value is committed to `Controller::write_strobe`. Multiple
753 /// writes within the commit window collapse — the latest value
754 /// wins (the buffer is single-slot, the previous value is
755 /// silently overwritten).
756 ///
757 /// This is the load-bearing structural change for `AccuracyCoin`
758 /// `Controller Strobing` Test 4 (a 1-cycle DEC `$4016` strobe pulse
759 /// whose 0→1→0 sequence must NOT fire the latch when it happens
760 /// to span an L→H half-cycle pair — under deferred commit both
761 /// writes target the SAME commit cycle, the second overwrites the
762 /// first, no edge is observed). See
763 /// `docs/audit/session-24-phase3-controller-strobing-2026-05-23.md`.
764 controller_write_pending: u8,
765 /// Buffered controller-write value (latched at the moment of the
766 /// CPU write; committed when `controller_write_pending` reaches 0).
767 controller_write_value: u8,
768
769 /// APU-side IRQ line snapshotted at the start of each CPU cycle, before
770 /// `apu_advance_one` runs the frame counter (`irq-timing-trace` only).
771 /// `trace_end_cycle` pairs it with the end-of-cycle level so a record
772 /// shows whether the frame-counter flag was SET or a `$4015` read CLEARED
773 /// it within the cycle.
774 ///
775 /// v2.9.8 (ADR 0042) removed the four unconditional per-phase snapshots
776 /// this replaced. They were written by the dead pre-v2.0.0
777 /// `tick_one_cpu_cycle` and read only by the removed `poll_irq` /
778 /// `poll_irq_at_phase`.
779 #[cfg(feature = "irq-timing-trace")]
780 irq_snapshot_apu_at_low: bool,
781
782 /// Optional IRQ-timing trace buffer (Track C1 pre-work, gated on the
783 /// `irq-timing-trace` cargo feature). See `crates/rustynes-core/src/irq_trace.rs`
784 /// and ADR-0002 "Decision (revised, 2026-05-13)".
785 #[cfg(feature = "irq-timing-trace")]
786 pub(crate) irq_trace: Option<IrqTrace>,
787 /// Session-21 (Sprint 1 iteration 2 prereq) bus-access tracker.
788 ///
789 /// Set by `cpu_read` / `cpu_write` / the unified DMA engine BEFORE
790 /// `trace_end_cycle` records the per-cycle bus-access columns; consumed
791 /// (and reset to `BusAccess::Idle` / 0) by `trace_end_cycle` when it
792 /// pushes the record. A single CPU cycle has at most one external
793 /// bus access — burn cycles (`idle_tick`) leave the tracker at
794 /// `BusAccess::Idle`, which is the correct semantics for the trace
795 /// (CPU internal cycles do not drive the bus).
796 ///
797 /// The DMA paths set this directly because the bus owns the cycle
798 /// during DMA halt and the CPU's `cpu_read` / `cpu_write` is not
799 /// invoked (the bus's `raw_cpu_read` is invoked instead, which
800 /// does not advance time on its own — the CPU's surrounding
801 /// `start_cycle` / `end_cycle` do).
802 #[cfg(feature = "irq-timing-trace")]
803 pub(crate) trace_bus_access: BusAccess,
804 #[cfg(feature = "irq-timing-trace")]
805 pub(crate) trace_bus_addr: u16,
806 #[cfg(feature = "irq-timing-trace")]
807 pub(crate) trace_bus_data: u8,
808 /// PC of the instruction currently executing, latched by the
809 /// `trace_instr` hook (`cpu-instr-cycle-trace`). Copied into each
810 /// `CycleRecord.pc` so the per-cycle trace can be diffed against
811 /// `TriCNES` by ROM PC. Stays at the halted instruction's PC across
812 /// DMA-insertion cycles. `0` unless `cpu-instr-cycle-trace` is on.
813 #[cfg(feature = "irq-timing-trace")]
814 pub(crate) trace_last_pc: u16,
815 /// R1-path PPU position captured at cycle-start (`cpu_clock`) for the
816 /// `trace_end_cycle` diagnostic push.
817 #[cfg(feature = "irq-timing-trace")]
818 pub(crate) trace_r1_scanline_start: i16,
819 #[cfg(feature = "irq-timing-trace")]
820 pub(crate) trace_r1_dot_start: u16,
821 #[cfg(feature = "irq-timing-trace")]
822 pub(crate) trace_r1_frame_start: u64,
823}
824
825impl SystemBus {
826 /// v2.7.0 -- reject a restored CPU/PPU clock pair too far apart to be real.
827 ///
828 /// `run_ppu_to` ticks the PPU until `ppu_clock` catches up to the CPU's
829 /// `master_clock`. The two live in different save-state sections (BUS and
830 /// CPU) and the running machine keeps them within a CPU cycle of each
831 /// other, but a restore took both raw. A `ppu_clock` far BEHIND made the
832 /// next catch-up tick billions of dots; one far AHEAD meant the PPU never
833 /// ticked again, so no frame ever completed. Either is a hang, found by the
834 /// v2.7.0 `save_state` fuzz target as a libFuzzer timeout once its patch
835 /// offsets could reach the sections behind the framebuffer.
836 ///
837 /// The allowance, [`Self::RESTORED_CLOCK_SKEW_MAX`] master clocks, is ~85
838 /// CPU cycles: generous against anything the machine produces, and it
839 /// bounds the first catch-up at a few hundred dots.
840 pub(crate) fn check_restored_clocks(&self, master_clock: u64) -> Result<(), SnapshotError> {
841 // v2.9.0 (re-audit NC-04): the skew alone is not enough; see
842 // [`Self::RESTORED_CLOCK_MAX`]. Checking the larger of the two is
843 // enough to bound both, since they are then also within the skew.
844 let highest = master_clock.max(self.ppu_clock);
845 if highest > Self::RESTORED_CLOCK_MAX {
846 return Err(SnapshotError::SectionInvalid {
847 tag: "BUS ".into(),
848 reason: format!(
849 "master clock {highest} exceeds the {} a real machine can reach",
850 Self::RESTORED_CLOCK_MAX
851 ),
852 });
853 }
854 let skew = master_clock.abs_diff(self.ppu_clock);
855 if skew > Self::RESTORED_CLOCK_SKEW_MAX {
856 return Err(SnapshotError::SectionInvalid {
857 tag: "BUS ".into(),
858 reason: format!(
859 "PPU clock {} is {skew} master clocks from the CPU's {master_clock}",
860 self.ppu_clock
861 ),
862 });
863 }
864 Ok(())
865 }
866
867 /// Largest CPU/PPU master-clock skew [`Self::check_restored_clocks`] accepts.
868 pub(crate) const RESTORED_CLOCK_SKEW_MAX: u64 = 1024;
869
870 /// Largest absolute master clock [`Self::check_restored_clocks`] accepts,
871 /// for either clock: 2^62.
872 ///
873 /// v2.9.0 (re-audit NC-04). The skew bound alone let a crafted state put
874 /// BOTH clocks just below 2^64; the CPU's `wrapping_add` then took its
875 /// clock back to a small value within a frame while the PPU's stayed high,
876 /// and `run_ppu_to`'s `ppu_clock + div <= target` never held again — the
877 /// frozen-PPU state F-05 exists to reject.
878 ///
879 /// Why 2^62. It must sit far above anything a real machine reaches and far
880 /// enough below 2^64 that no run from an accepted state can wrap. The
881 /// fastest master clock is NTSC/Dendy's ~21.477 MHz (PAL's is slower), so
882 /// 2^62 master clocks is ~2.1e11 s, about **6,800 years** of continuous
883 /// emulation — no genuine state can be refused. The remaining headroom to
884 /// the wrap is 3 x 2^62, about **20,000 years** more from the worst
885 /// accepted state, so the catch-up loop's addition cannot overflow either.
886 /// A power of two keeps the bound legible in a hex dump of a rejected blob.
887 pub(crate) const RESTORED_CLOCK_MAX: u64 = 1 << 62;
888
889 /// Test seam: move the PPU clock so a snapshot carries a chosen skew.
890 #[cfg(test)]
891 pub(crate) const fn set_ppu_clock_for_test(&mut self, v: u64) {
892 self.ppu_clock = v;
893 }
894
895 /// Test seam: the PPU clock, for the skew tests.
896 #[cfg(test)]
897 pub(crate) const fn ppu_clock_for_test(&self) -> u64 {
898 self.ppu_clock
899 }
900
901 /// Construct from a parsed ROM with a default 44.1 kHz audio sample rate.
902 ///
903 /// # Errors
904 ///
905 /// Returns the underlying [`RomError`] if the bytes don't parse.
906 pub fn new(rom_bytes: &[u8]) -> Result<Self, RomError> {
907 Self::with_sample_rate(rom_bytes, DEFAULT_SAMPLE_RATE)
908 }
909
910 /// Construct with an explicit audio sample rate.
911 ///
912 /// # Errors
913 ///
914 /// Returns the underlying [`RomError`] if the bytes don't parse.
915 // The struct-literal init grows with every feature-gated field; the W3
916 // unified-engine fields pushed it past the line gate.
917 #[allow(clippy::too_many_lines)]
918 pub fn with_sample_rate(rom_bytes: &[u8], sample_rate: u32) -> Result<Self, RomError> {
919 let (cart, mapper) = rustynes_mappers::parse(rom_bytes)?;
920 let mut bus = Self::from_cart_and_mapper(cart, mapper, sample_rate);
921 // Keep the iNES bytes so `power_cycle` can rebuild the mapper to a true
922 // power-on state. Cheap relative to the cart it already holds, and never
923 // serialized into the save-state.
924 bus.rom_bytes = Some(Box::from(rom_bytes));
925 // v3.6.2: the per-game coherent mid-line copy correction, on by
926 // default for the dumps `game_corrections` lists (Rad Racer). A host
927 // can turn it off; a power cycle carries it (`adopt_settings_from`).
928 bus.ppu.set_coherent_midline_copy(
929 crate::game_corrections::coherent_midline_copy_by_default(rom_bytes),
930 );
931 Ok(bus)
932 }
933
934 /// Construct a bus directly from an already-parsed cartridge + boxed mapper.
935 ///
936 /// This is the shared core of [`Self::with_sample_rate`] (iNES / NES 2.0
937 /// path) and [`Self::with_disk`] (Famicom Disk System path). Both produce a
938 /// [`Cartridge`] metadata value plus a `Box<dyn Mapper>`; this routine wires
939 /// up the PPU/APU region, the R1 master-clock dividers, and the rest of the
940 /// bus state identically for both.
941 // The struct-literal init grows with every feature-gated field; the W3
942 // unified-engine fields pushed it past the line gate.
943 #[allow(clippy::too_many_lines)]
944 pub(crate) fn from_cart_and_mapper(
945 cart: Cartridge,
946 mapper: Box<dyn Mapper>,
947 sample_rate: u32,
948 ) -> Self {
949 let region = match cart.region {
950 rustynes_mappers::Region::Pal => PpuRegion::Pal,
951 rustynes_mappers::Region::Dendy => PpuRegion::Dendy,
952 _ => PpuRegion::Ntsc,
953 };
954 let apu_region = match cart.region {
955 rustynes_mappers::Region::Pal => ApuRegion::Pal,
956 rustynes_mappers::Region::Dendy => ApuRegion::Dendy,
957 _ => ApuRegion::Ntsc,
958 };
959 // R1 master-clock dividers, cached once (region is immutable after parse).
960 // Identical to the prior `region_dividers()` match: NTSC 12/4, PAL 16/5,
961 // Dendy 15/5.
962 let (cpu_div_cached, ppu_div_cached): (u8, u8) = match cart.region {
963 rustynes_mappers::Region::Pal => (16, 5),
964 rustynes_mappers::Region::Dendy => (15, 5),
965 _ => (12, 4),
966 };
967 // v2.8.0 Phase 4 — cache the capability flags once (constant per
968 // mapper type); the per-cycle hot loop reads the copy.
969 let mapper_caps = mapper.caps();
970 let prg_may_unmap = mapper.may_unmap_prg_rom();
971 let ppu_read_snoop = mapper.snoops_ppu_reads();
972 let mut bus = Self {
973 ram: fresh_ram(),
974 ppu: Ppu::new(region),
975 apu: Apu::new(apu_region, sample_rate),
976 cart,
977 mapper,
978 mapper_caps,
979 prg_may_unmap,
980 ppu_read_snoop,
981 // Set by `with_sample_rate` (iNES path); stays `None` for FDS.
982 rom_bytes: None,
983 controllers: [Controller::new(); 2],
984 four_score: false,
985 // v2.1.7 P5 — power-on config knobs, all at their byte-identical
986 // defaults (zeroed RAM, default revision, all-zero power-up palette).
987 power_on_ram: crate::nes::PowerOnRam::Zeroed,
988 ppu_die_revision: PpuRevision::Rp2c02H,
989 console_model: crate::nes::ConsoleModel::Nes,
990 power_up_palette: PaletteInit::Zeroed,
991 controllers34: [Controller::new(); 2],
992 four_score_idx: [0; 2],
993 four_score_pending: [false; 2],
994 port_read_cycle: [u64::MAX; 2],
995 four_score_sig: [0; 2],
996 #[cfg(feature = "debug-hooks")]
997 controller_polled: false,
998 vs_dip: 0,
999 vs_coin: 0,
1000 vs_service: false,
1001 vs_is_sub: false,
1002 vs_external_irq: false,
1003 vs_4016_bit1: false,
1004 vs_4016_bit1_dirty: false,
1005 expansion_device: [None, None],
1006 // v2.3.6: ON by default. See `set_zapper_temporal_light` — the frame
1007 // model made a Duck Hunt hit impossible.
1008 zapper_temporal_light: true,
1009 famicom_mic: false,
1010 nt_mirroring_override: None,
1011 #[cfg(feature = "debug-hooks")]
1012 events: alloc::vec::Vec::new(),
1013 #[cfg(feature = "debug-hooks")]
1014 event_logging: false,
1015 #[cfg(feature = "debug-hooks")]
1016 accesses: alloc::vec::Vec::new(),
1017 #[cfg(feature = "debug-hooks")]
1018 access_logging: false,
1019 #[cfg(feature = "debug-hooks")]
1020 interrupts: alloc::vec::Vec::new(),
1021 #[cfg(feature = "debug-hooks")]
1022 interrupt_logging: false,
1023 #[cfg(feature = "debug-hooks")]
1024 event_bp_mask: 0,
1025 #[cfg(feature = "debug-hooks")]
1026 event_break_hit: None,
1027 cycle: 0,
1028 dma_pending: None,
1029 dma_byte: 0,
1030 dma_page: 0,
1031 dma_halt_addr: 0,
1032 #[cfg(feature = "cosim-interrupt-inject")]
1033 inject_nmi: false,
1034 #[cfg(feature = "cosim-interrupt-inject")]
1035 inject_irq: false,
1036 ppu_clock: 0,
1037 cpu_div_cached,
1038 ppu_div_cached,
1039 cpu_overclock: 1,
1040 mmc3_revision_override: None,
1041 cpu_div_effective: cpu_div_cached,
1042 overclock_phase: 0,
1043 apu_cycle: 0,
1044 stock_step: true,
1045 open_bus: 0,
1046 internal_data_bus: 0,
1047 last_read_addr: 0,
1048 deferred_dma_replay_addr: 0,
1049 in_dmc_dma: false,
1050 uni_oam_active: false,
1051 uni_oam_halt: false,
1052 uni_oam_aligned: false,
1053 uni_oam_addr: 0,
1054 cpu_2a03_revision: Cpu2A03Revision::default(),
1055 dmc_halt: false,
1056 dmc_load_write_delayed: false,
1057 genie_codes: BTreeMap::new(),
1058 #[cfg(feature = "irq-timing-trace")]
1059 irq_snapshot_apu_at_low: false,
1060 controller_write_pending: 0,
1061 controller_write_value: 0,
1062 #[cfg(feature = "irq-timing-trace")]
1063 irq_trace: None,
1064 #[cfg(feature = "irq-timing-trace")]
1065 trace_bus_access: BusAccess::Idle,
1066 #[cfg(feature = "irq-timing-trace")]
1067 trace_bus_addr: 0,
1068 #[cfg(feature = "irq-timing-trace")]
1069 trace_bus_data: 0,
1070 #[cfg(feature = "irq-timing-trace")]
1071 trace_last_pc: 0,
1072 #[cfg(feature = "irq-timing-trace")]
1073 trace_r1_scanline_start: 0,
1074 #[cfg(feature = "irq-timing-trace")]
1075 trace_r1_dot_start: 0,
1076 #[cfg(feature = "irq-timing-trace")]
1077 trace_r1_frame_start: 0,
1078 };
1079 // Vs. System / PlayChoice-10: the arcade boards replace the 2C02 with a
1080 // 2C03 / 2C04 / 2C05 RGB PPU. For ConsoleType::Nes (the default), the
1081 // resolved type is VsPpuType::None -> Composite2C02, is_2c05 = false, so
1082 // this is byte-for-byte a no-op on normal carts.
1083 bus.reapply_vs_palette();
1084 // F-2: under R1 the DMC byte-timer is driven at end-of-cycle by
1085 // `cpu_clock_apu_dmc` (main's DMC fire-phase for DMASync).
1086 {
1087 bus.apu.set_dmc_driven_externally(true);
1088 // Interleaved-DMA Phase A: seed the get/put + DMC fire-phase from one
1089 // APUAlignment value. Fixed alignment 0 for now; Phase B drives it
1090 // from the power-on PRNG (the 2 AccuracyCoin answer-key alignments).
1091 bus.apu.seed_apu_alignment(0);
1092 }
1093 bus
1094 }
1095
1096 /// Construct a Famicom Disk System bus from a `.fds` disk image and a
1097 /// user-supplied 8 KiB BIOS (`disksys.rom`).
1098 ///
1099 /// Parses the disk container ([`rustynes_mappers::parse_fds`]), constructs the
1100 /// FDS device ([`rustynes_mappers::Fds`]) as the bus's `Box<dyn Mapper>`, and
1101 /// wires the bus exactly like a cartridge build (shared internal
1102 /// `from_cart_and_mapper`). The FDS is NTSC/Famicom hardware, so the
1103 /// synthetic [`Cartridge`] metadata reports [`rustynes_mappers::Region::Ntsc`].
1104 ///
1105 /// # Errors
1106 ///
1107 /// Returns [`RomError`] if the disk image is unparseable, or the BIOS is not
1108 /// exactly 8 KiB.
1109 pub fn with_disk(
1110 disk_bytes: &[u8],
1111 bios_bytes: &[u8],
1112 sample_rate: u32,
1113 ) -> Result<Self, RomError> {
1114 let disk = rustynes_mappers::parse_fds(disk_bytes)?;
1115 let fds = rustynes_mappers::Fds::new(disk, bios_bytes)?;
1116 // Synthetic cartridge metadata: the bus only consults `cart.region`
1117 // (verified — see `docs/audit` FDS Stage 1). The FDS device owns all
1118 // PRG/CHR/BIOS storage, so the ROM byte fields are empty.
1119 let cart = Cartridge::synthetic(20, 0x8000, 0x2000);
1120 Ok(Self::from_cart_and_mapper(cart, Box::new(fds), sample_rate))
1121 }
1122
1123 /// Build a bus that plays an NSF music file. Parses the `.nsf`, builds an
1124 /// [`rustynes_mappers::NsfMapper`] (a synthetic driver + the program image)
1125 /// as the bus's `Box<dyn Mapper>`, and reports synthetic NTSC cartridge
1126 /// metadata (the file carries no CHR / PPU program).
1127 ///
1128 /// # Errors
1129 ///
1130 /// Returns [`RomError::InvalidConfig`] when the NSF header is malformed.
1131 pub fn with_nsf(nsf_bytes: &[u8], sample_rate: u32) -> Result<Self, RomError> {
1132 let nsf = rustynes_mappers::parse_nsf(nsf_bytes)
1133 .map_err(|e| RomError::InvalidConfig(alloc::format!("{e}")))?;
1134 let mapper = rustynes_mappers::NsfMapper::new(&nsf);
1135 // Mapper 31: NSF banking is conventionally documented as mapper
1136 // 31-like. `synthetic` plays NTSC 60 Hz (vblank-NMI-driven) regardless
1137 // of the file's region preference; the PAL flag only feeds the
1138 // driver's init X-register. Exact non-60 Hz play rates are a
1139 // documented deferral (see `nsf.rs` module docs).
1140 let cart = Cartridge::synthetic(31, 0x2000, 0);
1141 Ok(Self::from_cart_and_mapper(
1142 cart,
1143 Box::new(mapper),
1144 sample_rate,
1145 ))
1146 }
1147
1148 /// Reset (warm). Defers to `Ppu::reset` and clears DMA state. CPU is
1149 /// reset by the caller.
1150 pub fn reset(&mut self) {
1151 // v2.9.8 — on a Famicom the PPU's /RESET is tied to 5 V, so the Reset
1152 // button reaches only the CPU (NESdev "PPU power up state", §Famicom):
1153 // the PPU keeps PPUCTRL/PPUMASK, its latches and its frame position,
1154 // and no warm-up window is re-armed. The NES (default) resets both.
1155 if matches!(self.console_model, crate::nes::ConsoleModel::Nes) {
1156 self.ppu.reset();
1157 }
1158 self.apu.reset();
1159 {
1160 self.apu.set_dmc_driven_externally(true);
1161 self.apu.seed_apu_alignment(0);
1162 }
1163 self.dma_pending = None;
1164 self.dma_halt_addr = 0;
1165 self.deferred_dma_replay_addr = 0;
1166 self.unified_dma_clear();
1167 // v2.9.6: the boards that see the reset line (`Mapper::reset`).
1168 self.mapper.reset();
1169 }
1170
1171 /// Power-cycle. Zeroes RAM and resets all state. Caller resets the CPU.
1172 pub fn power_cycle(&mut self) {
1173 self.ram.fill(0);
1174 // v2.9.8 — the PPU is rebuilt to its power-on state, but the host's
1175 // settings stored on it (custom palette, overclock scanlines, fast dot
1176 // path, OAM-decay model) are configuration, not console state: carry
1177 // them onto the new PPU, so every host gets a correct power cycle
1178 // without re-pushing them. Until v2.9.8 they reverted to their
1179 // defaults here. See `Ppu::adopt_settings_from`.
1180 let fresh_ppu = Ppu::new(self.ppu_region());
1181 #[cfg_attr(not(feature = "debug-hooks"), allow(unused_mut))]
1182 let mut prev_ppu = core::mem::replace(&mut self.ppu, fresh_ppu);
1183 self.ppu.adopt_settings_from(&prev_ppu);
1184 // The provenance stores stay ARMED across the cycle (the user asked
1185 // for them); `Nes::power_cycle` then empties them, since a cold boot
1186 // ends the history they describe. Until v2.9.8 they were dropped with
1187 // the old PPU, which made that clear a no-op.
1188 #[cfg(feature = "debug-hooks")]
1189 self.ppu.put_provenance(prev_ppu.take_provenance());
1190 drop(prev_ppu);
1191 // Re-apply the Vs./PC10 RGB-PPU configuration (lost when the PPU is
1192 // reconstructed). No-op for ConsoleType::Nes carts.
1193 self.reapply_vs_palette();
1194 // v2.1.7 P5 — re-apply the PPU-revision + power-up-palette config lost
1195 // when the PPU was reconstructed above, so `power_cycle == fresh boot`
1196 // holds for these knobs too (a core-only consumer that power-cycles
1197 // without a frontend still gets the configured hardware). All no-ops at
1198 // their defaults, so a default power-cycle stays byte-identical.
1199 self.ppu.set_revision(self.ppu_die_revision);
1200 self.ppu.apply_power_up_palette(self.power_up_palette);
1201 // v2.9.8 — the rebuilt PPU starts a fresh warm-up window; a Famicom's
1202 // closes before the CPU's first instruction. No-op on the NES.
1203 self.apply_console_model_power_on();
1204 // v2.1.7 P5 — re-apply the power-on work-RAM fill after the `fill(0)`
1205 // above. At the default (`Zeroed`) this is the same zero fill.
1206 self.apply_power_on_ram();
1207 // v2.9.8 — as for the PPU above: the rebuilt APU keeps the host's
1208 // channel mask, per-channel gain and filter model (until v2.9.8 they
1209 // reverted to their defaults), and its audio provenance stays armed
1210 // for `Nes::power_cycle` to empty. See `Apu::adopt_settings_from`.
1211 let fresh_apu = Apu::new(self.apu_region(), self.apu.sample_rate);
1212 #[cfg_attr(not(feature = "debug-hooks"), allow(unused_mut))]
1213 let mut prev_apu = core::mem::replace(&mut self.apu, fresh_apu);
1214 self.apu.adopt_settings_from(&prev_apu);
1215 #[cfg(feature = "debug-hooks")]
1216 self.apu
1217 .put_audio_provenance(prev_apu.take_audio_provenance());
1218 drop(prev_apu);
1219 {
1220 self.apu.set_dmc_driven_externally(true);
1221 self.apu.seed_apu_alignment(0);
1222 }
1223 self.controllers = [Controller::new(); 2];
1224 // The Four Score stays "plugged in" (it's hardware config), but its
1225 // transient strobe/read state resets like the controllers above.
1226 self.controllers34 = [Controller::new(); 2];
1227 self.four_score_idx = [0; 2];
1228 self.four_score_pending = [false; 2];
1229 self.four_score_sig = [0; 2];
1230 // Vs. System coin/service inputs are transient (DIP switches are
1231 // hardware config and persist across a power-cycle, like the panel).
1232 self.vs_coin = 0;
1233 self.vs_service = false;
1234 // v2.0.0 beta.5 (Vs. DualSystem): the comms latch + external IRQ are
1235 // transient signals; the sub identity is cabinet wiring and persists
1236 // (re-applied by the wrapper anyway).
1237 self.vs_external_irq = false;
1238 self.vs_4016_bit1 = false;
1239 self.vs_4016_bit1_dirty = false;
1240 // Non-standard input devices are unplugged on power-cycle (they are
1241 // re-attached explicitly by the frontend, like the controllers above).
1242 self.expansion_device = [None, None];
1243 // The microphone is a transient live signal; a power-cycle releases it
1244 // (the frontend re-drives it each frame while a key is held).
1245 self.famicom_mic = false;
1246 self.cycle = 0;
1247 self.dma_pending = None;
1248 self.dma_halt_addr = 0;
1249 self.open_bus = 0;
1250 self.internal_data_bus = 0;
1251 self.deferred_dma_replay_addr = 0;
1252 #[cfg(feature = "irq-timing-trace")]
1253 {
1254 self.irq_snapshot_apu_at_low = false;
1255 }
1256 self.unified_dma_clear();
1257 // A cold boot must reset EVERY run-history-dependent field, or the
1258 // post-power-cycle machine depends on how long it ran before — breaking
1259 // the `power_cycle == fresh boot` equivalence (netplay power-cycles
1260 // both peers at session start and requires byte-identical state). A
1261 // residual `ppu_clock` in particular carries the old master-clock
1262 // CPU/PPU phase into the "new" boot, diverging timing-sensitive games
1263 // from frame 0. Mirrors the `with_sample_rate` initial values.
1264 self.ppu_clock = 0;
1265 // The stock-rate domain restarts with the clock; the multiplier itself
1266 // is configuration and survives the power cycle.
1267 self.overclock_phase = 0;
1268 self.cpu_div_effective = overclock_cycle_len(self.cpu_div_cached, self.cpu_overclock, 0);
1269 self.apu_cycle = 0;
1270 self.stock_step = true;
1271 self.dma_byte = 0;
1272 self.dma_page = 0;
1273 self.last_read_addr = 0;
1274 self.in_dmc_dma = false;
1275 self.dmc_halt = false;
1276 self.dmc_load_write_delayed = false;
1277 self.controller_write_pending = 0;
1278 self.controller_write_value = 0;
1279 // v2.9.8 — the ports' last-read stamps are bus cycles of the OLD
1280 // timeline; `cycle` restarts at 0 above, so a kept stamp made the
1281 // cycled state depend on how long the console had run (and could, in
1282 // principle, read as "continues a run" against the new clock). A
1283 // fresh bus has never read either port.
1284 self.port_read_cycle = [u64::MAX; 2];
1285 // Rebuild the mapper to its power-on state (fresh bank registers, cleared
1286 // CHR-RAM + volatile PRG-RAM), so a power-cycle is a true cold boot for
1287 // mapper-stateful games (MMC1/MMC3/…) too — without this, a stateful
1288 // mapper's banking + CHR-RAM survive, so two netplay peers that power-
1289 // cycled from different running states would desync. The existing `cart`
1290 // metadata (incl. any post-load `set_vs_ppu_type` override) is kept; only
1291 // the mapper is replaced. FDS (`rom_bytes == None`) keeps its mapper.
1292 //
1293 // v2.9.0 — battery-backed PRG-RAM SURVIVES, as it does on a console.
1294 // Until v2.9.0 the rebuild cleared it too ("a battery-pull"), which was
1295 // harmless while RustyNES persisted no battery saves; from v2.7.3 the
1296 // desktop writes the live RAM to a `.sav` whenever it changes, so a
1297 // Power Cycle wrote zeros over the player's save. Volatile PRG-RAM and
1298 // CHR-RAM are still cleared. A power-on MOVIE wants cleared save RAM
1299 // and asks for it explicitly (`movie::power_on_for_movie`).
1300 let battery_ram: Option<Vec<u8>> = self
1301 .cart
1302 .has_battery
1303 .then(|| self.mapper.save_data().to_vec());
1304 if let Some(bytes) = self.rom_bytes.take() {
1305 if let Ok((_cart, mapper)) = rustynes_mappers::parse(&bytes) {
1306 self.mapper = mapper;
1307 if let Some(saved) = battery_ram.as_deref() {
1308 let fresh = self.mapper.save_data_mut();
1309 // Same ROM, same board: the sizes match. Guarded anyway,
1310 // since a mismatch would mean the rebuild is not the board
1311 // the RAM came from, and copying into it would be wrong.
1312 if fresh.len() == saved.len() {
1313 fresh.copy_from_slice(saved);
1314 }
1315 }
1316 // v2.8.0 Phase 4 — re-cache the capability flags for the
1317 // fresh mapper instance (same type, same flags, but keep
1318 // the invariant mechanical).
1319 self.mapper_caps = self.mapper.caps();
1320 self.prg_may_unmap = self.mapper.may_unmap_prg_rom();
1321 self.ppu_read_snoop = self.mapper.snoops_ppu_reads();
1322 // v3.1.0: a fresh board starts on its header's MMC3 revision;
1323 // the override is configuration and carries over.
1324 if self.mmc3_revision_override.is_some() {
1325 self.mapper
1326 .set_mmc3_revision_override(self.mmc3_revision_override);
1327 }
1328 }
1329 self.rom_bytes = Some(bytes);
1330 }
1331 }
1332
1333 /// Developer-mode power-on randomization (Phase 7 / T-72-005).
1334 ///
1335 /// Fills the 2 KiB CPU work RAM and the external open-bus latch from a
1336 /// deterministic `xorshift64` PRNG. Real hardware powers up with
1337 /// unreliable RAM (see nesdev "CPU power up state"); games that depend on
1338 /// a particular post-power-on RAM pattern are buggy, and this option
1339 /// surfaces such bugs the way Mesen2's "randomize RAM on power-on" does.
1340 ///
1341 /// The fill is **seeded and deterministic** — the same `seed` always
1342 /// yields the same power-on state, so the
1343 /// `same seed + ROM + input ⇒ bit-identical` determinism contract (and
1344 /// therefore save-state round-trip and the regression oracle) is
1345 /// preserved. CI and tests use the default (zeroed) path; this is opt-in
1346 /// via [`crate::Nes::from_rom_with_power_on_seed`].
1347 ///
1348 /// CPU/PPU phase alignment and DMA get/put phase are intentionally **not**
1349 /// randomized here: the lockstep scheduler's phase is deterministic by
1350 /// design and randomizing it is entangled with the v2.0 master-clock
1351 /// scheduling refactor (see `docs/audit/phase-7-assessment-2026-05-24.md`).
1352 pub fn randomize_power_on_ram(&mut self, seed: u64) {
1353 // Avoid the xorshift64 zero fixed point.
1354 let mut s = if seed == 0 {
1355 0x9E37_79B9_7F4A_7C15
1356 } else {
1357 seed
1358 };
1359 let mut next = || {
1360 s ^= s << 13;
1361 s ^= s >> 7;
1362 s ^= s << 17;
1363 // Byte 3 (bits 24-31) — extracted without a truncating cast.
1364 s.to_le_bytes()[3]
1365 };
1366 // `&mut *self.ram` reborrows the array: iterating `&mut Box<[T; N]>`
1367 // directly needs Rust 1.97+. The crate's floor is 1.99, so either form
1368 // compiles today; the reborrow dates from v3.0.1's one-day split, when
1369 // the libretro buildbot briefly built this crate on 1.96.
1370 for byte in &mut *self.ram {
1371 *byte = next();
1372 }
1373 self.open_bus = next();
1374 }
1375
1376 /// Assert or release the injected /NMI pin. See [`crate::Nes::inject_nmi`].
1377 #[cfg(feature = "cosim-interrupt-inject")]
1378 pub const fn set_inject_nmi(&mut self, asserted: bool) {
1379 self.inject_nmi = asserted;
1380 }
1381
1382 /// Assert or release the injected /IRQ pin. See [`crate::Nes::inject_irq`].
1383 #[cfg(feature = "cosim-interrupt-inject")]
1384 pub const fn set_inject_irq(&mut self, asserted: bool) {
1385 self.inject_irq = asserted;
1386 }
1387
1388 /// Borrow the framebuffer (RGBA8, 256x240).
1389 #[must_use]
1390 pub fn framebuffer(&self) -> &[u8] {
1391 self.ppu.framebuffer()
1392 }
1393
1394 /// v1.7.0 "Forge" Workstream B (B3) — overwrite the RGBA8 output framebuffer
1395 /// (the Lua `emu:setScreenBuffer`). Output-only; see
1396 /// [`rustynes_ppu::Ppu::debug_set_framebuffer`]. `debug-hooks`-gated.
1397 #[cfg(feature = "debug-hooks")]
1398 pub fn debug_set_framebuffer(&mut self, rgba: &[u8]) {
1399 self.ppu.debug_set_framebuffer(rgba);
1400 }
1401
1402 /// Borrow the parallel palette-index framebuffer (256x240 `u16`s) for the
1403 /// `NES_NTSC` composite filter. See [`rustynes_ppu::Ppu::index_framebuffer`].
1404 #[must_use]
1405 pub fn index_framebuffer(&self) -> &[u16] {
1406 self.ppu.index_framebuffer()
1407 }
1408
1409 /// v1.2.0 C3 (hd-pack) — borrow the per-pixel HD-pack tile-source buffer.
1410 /// See [`rustynes_ppu::Ppu::hd_tile_source`]. Output-only telemetry.
1411 #[cfg(feature = "hd-pack")]
1412 #[must_use]
1413 pub fn hd_tile_source(&self) -> &[rustynes_ppu::HdTileSource] {
1414 self.ppu.hd_tile_source()
1415 }
1416
1417 /// The per-frame NTSC composite colour phase for the `NES_NTSC` filter
1418 /// (`0..=2` on NTSC; frame parity `0..=1` on PAL/Dendy). See
1419 /// [`rustynes_ppu::Ppu::ntsc_phase`].
1420 #[must_use]
1421 pub const fn ntsc_phase(&self) -> u8 {
1422 self.ppu.ntsc_phase()
1423 }
1424
1425 /// v1.1.0 beta.1 — install (`Some`) or clear (`None`) a custom 64-entry base
1426 /// palette from a loaded `.pal` file. A presentation override; `None` (default)
1427 /// is byte-identical to the built-in palette.
1428 pub const fn set_custom_palette(&mut self, base: Option<[[u8; 3]; 64]>) {
1429 self.ppu.set_custom_palette(base);
1430 }
1431
1432 /// v1.7.0 "Forge" F3 — set the PPU extra-scanlines overclock (extra idle
1433 /// vblank lines per frame). `0` (default) is byte-identical to stock timing.
1434 pub const fn set_extra_scanlines(&mut self, lines: u16) {
1435 self.ppu.set_extra_scanlines(lines);
1436 }
1437
1438 /// v1.7.0 F3 — the configured extra-scanline count (`0` = stock).
1439 #[must_use]
1440 pub const fn extra_scanlines(&self) -> u16 {
1441 self.ppu.extra_scanlines()
1442 }
1443
1444 /// v3.1.0 (`T-CPU-OVERCLOCK`) — set the CPU-multiplier overclock. The
1445 /// caller ([`crate::Nes::set_cpu_overclock`]) has already clamped `k` to
1446 /// `1..=MAX_CPU_OVERCLOCK`. Switching it ON re-bases the stock-rate
1447 /// domain's cycle counter on the CPU's, so the APU's put/get phase
1448 /// continues across the switch; switching it OFF hands the APU the CPU
1449 /// counter again, as stock does.
1450 pub const fn set_cpu_overclock(&mut self, k: u8) {
1451 if k == self.cpu_overclock {
1452 return;
1453 }
1454 if self.cpu_overclock == 1 {
1455 self.apu_cycle = self.cycle;
1456 }
1457 self.cpu_overclock = k;
1458 self.overclock_phase = 0;
1459 self.cpu_div_effective = overclock_cycle_len(self.cpu_div_cached, k, 0);
1460 self.stock_step = true;
1461 }
1462
1463 /// v3.1.0 — the CPU-multiplier overclock (`1` = stock).
1464 #[must_use]
1465 pub const fn cpu_overclock(&self) -> u8 {
1466 self.cpu_overclock
1467 }
1468
1469 /// v3.1.0 (`T-MMC3-NEC-OVERRIDE`) — force the MMC3 IRQ revision, or
1470 /// `None` for the header's. Returns whether the board applied it (only an
1471 /// MMC3, mapper 4, does); the setting is kept either way.
1472 pub fn set_mmc3_revision_override(
1473 &mut self,
1474 revision: Option<rustynes_mappers::Mmc3Revision>,
1475 ) -> bool {
1476 self.mmc3_revision_override = revision;
1477 self.mapper.set_mmc3_revision_override(revision)
1478 }
1479
1480 /// v3.1.0 — the forced MMC3 IRQ revision (`None` = the header's).
1481 #[must_use]
1482 pub const fn mmc3_revision_override(&self) -> Option<rustynes_mappers::Mmc3Revision> {
1483 self.mmc3_revision_override
1484 }
1485
1486 /// v3.1.0 (`T-SPRITE-LIMIT`) — draw the sprites beyond the eighth on a
1487 /// scanline (forwarded to the PPU).
1488 pub const fn set_sprite_limit_disabled(&mut self, disabled: bool) {
1489 self.ppu.set_sprite_limit_disabled(disabled);
1490 }
1491
1492 /// v3.1.0 — whether the sprites beyond the eighth are drawn.
1493 #[must_use]
1494 pub const fn sprite_limit_disabled(&self) -> bool {
1495 self.ppu.sprite_limit_disabled()
1496 }
1497
1498 /// v3.6.2 — the per-game coherent mid-line copy correction (forwarded to
1499 /// the PPU).
1500 pub const fn set_coherent_midline_copy(&mut self, on: bool) {
1501 self.ppu.set_coherent_midline_copy(on);
1502 }
1503
1504 /// v3.6.2 — whether the coherent mid-line copy correction is on.
1505 #[must_use]
1506 pub const fn coherent_midline_copy(&self) -> bool {
1507 self.ppu.coherent_midline_copy()
1508 }
1509
1510 /// v2.1.8 A1 — enable/disable the specialized visible-scanline fast dot
1511 /// path. `false` (default) is byte-identical to a build without it. See
1512 /// [`rustynes_ppu::Ppu::set_fast_dotloop`].
1513 pub const fn set_fast_dotloop(&mut self, enabled: bool) {
1514 self.ppu.set_fast_dotloop(enabled);
1515 }
1516
1517 /// v2.1.8 A1 — whether the visible-scanline fast dot path is enabled.
1518 #[must_use]
1519 pub const fn fast_dotloop(&self) -> bool {
1520 self.ppu.fast_dotloop()
1521 }
1522
1523 /// v2.1.4 F2.3 — enable/disable the optional OAM-decay accuracy model.
1524 /// `false` (default) is byte-identical to a decay-free PPU. See
1525 /// [`rustynes_ppu::Ppu::set_oam_decay`].
1526 pub const fn set_oam_decay(&mut self, enabled: bool) {
1527 self.ppu.set_oam_decay(enabled);
1528 }
1529
1530 /// v2.1.7 P5 — select the emulated 2C02 die revision, storing it so a
1531 /// power-cycle re-applies it, and applying it to the live PPU now. The
1532 /// default revision is byte-identical. See [`PpuRevision`].
1533 pub const fn set_ppu_revision(&mut self, revision: PpuRevision) {
1534 self.ppu_die_revision = revision;
1535 self.ppu.set_revision(revision);
1536 }
1537
1538 /// v2.1.7 P5 — the currently-selected 2C02 die revision.
1539 #[must_use]
1540 pub const fn ppu_revision(&self) -> PpuRevision {
1541 self.ppu_die_revision
1542 }
1543
1544 /// v2.9.8 — select the console's reset wiring (see
1545 /// [`crate::nes::ConsoleModel`]), storing it for [`Self::power_cycle`] and
1546 /// [`Self::reset`].
1547 ///
1548 /// Selecting [`crate::nes::ConsoleModel::Famicom`] also ends any PPU warm-up
1549 /// in progress, since a Famicom's PPU is never held in reset while the CPU
1550 /// runs; that is what gives a host that applies the knob straight after
1551 /// construction the Famicom power-on. At the default this is a store only.
1552 pub const fn set_console_model(&mut self, model: crate::nes::ConsoleModel) {
1553 self.console_model = model;
1554 self.apply_console_model_power_on();
1555 }
1556
1557 /// v2.9.8 — the power-on half of the console model: on a Famicom the PPU
1558 /// left reset about one frame before the CPU, which is longer than the
1559 /// warm-up window, so the window is already closed. No-op on the NES.
1560 const fn apply_console_model_power_on(&mut self) {
1561 if matches!(self.console_model, crate::nes::ConsoleModel::Famicom) {
1562 self.ppu.end_warmup();
1563 }
1564 }
1565
1566 /// v2.9.8 — the currently-selected console reset wiring.
1567 #[must_use]
1568 pub const fn console_model(&self) -> crate::nes::ConsoleModel {
1569 self.console_model
1570 }
1571
1572 /// v2.1.7 P5 — apply a power-up palette-RAM pattern, storing it so a
1573 /// power-cycle re-applies it and writing it to the live PPU's palette RAM
1574 /// now. The default ([`PaletteInit::Zeroed`]) is byte-identical. See
1575 /// [`PaletteInit`].
1576 pub const fn set_power_up_palette(&mut self, init: PaletteInit) {
1577 self.power_up_palette = init;
1578 self.ppu.apply_power_up_palette(init);
1579 }
1580
1581 /// v2.1.7 P5 — the currently-selected power-up palette pattern.
1582 #[must_use]
1583 pub const fn power_up_palette(&self) -> PaletteInit {
1584 self.power_up_palette
1585 }
1586
1587 /// v2.1.7 P5 — select the power-on work-RAM fill, storing it so a
1588 /// power-cycle re-applies it, and applying it to the current RAM now. The
1589 /// default ([`crate::nes::PowerOnRam::Zeroed`]) is byte-identical. See [`crate::nes::PowerOnRam`].
1590 pub fn set_power_on_ram(&mut self, ram: crate::nes::PowerOnRam) {
1591 self.power_on_ram = ram;
1592 self.apply_power_on_ram();
1593 }
1594
1595 /// v2.1.7 P5 — the currently-selected power-on work-RAM fill.
1596 #[must_use]
1597 pub const fn power_on_ram(&self) -> crate::nes::PowerOnRam {
1598 self.power_on_ram
1599 }
1600
1601 /// v2.1.7 P5 — apply the stored [`Self::power_on_ram`] selection to the 2 KiB
1602 /// work RAM (and the open-bus latch). Called by [`Self::set_power_on_ram`]
1603 /// and re-applied by [`Self::power_cycle`] after it zeroes RAM. RAM is not
1604 /// consulted during the reset sequence (only the `$FFFC/D` vector is), so
1605 /// applying it here is correct. Deterministic: no wall-clock / OS RNG.
1606 fn apply_power_on_ram(&mut self) {
1607 match self.power_on_ram {
1608 crate::nes::PowerOnRam::Zeroed => {
1609 self.ram.fill(0);
1610 self.open_bus = 0;
1611 }
1612 crate::nes::PowerOnRam::Seeded(seed) => self.randomize_power_on_ram(seed),
1613 crate::nes::PowerOnRam::Filled(byte) => {
1614 self.ram.fill(byte);
1615 self.open_bus = byte;
1616 }
1617 }
1618 }
1619
1620 /// v2.1.4 F2.3 — whether the optional OAM-decay model is enabled.
1621 #[must_use]
1622 pub const fn oam_decay_enabled(&self) -> bool {
1623 self.ppu.oam_decay_enabled()
1624 }
1625
1626 /// v2.1.7 — set the emulated 2A03 die revision (DMA "unexpected read" axis).
1627 /// [`Cpu2A03Revision::Rp2A03G`] (default) is byte-identical to the pre-v2.1.7
1628 /// core; [`Cpu2A03Revision::Rp2A03H`] is the opt-in later-die model. See the
1629 /// [`Cpu2A03Revision`] docs + ADR 0033.
1630 pub const fn set_cpu_2a03_revision(&mut self, revision: Cpu2A03Revision) {
1631 self.cpu_2a03_revision = revision;
1632 }
1633
1634 /// v2.1.7 — the configured 2A03 die revision (default
1635 /// [`Cpu2A03Revision::Rp2A03G`]).
1636 #[must_use]
1637 pub const fn cpu_2a03_revision(&self) -> Cpu2A03Revision {
1638 self.cpu_2a03_revision
1639 }
1640
1641 /// Cartridge region (NTSC / PAL / Dendy / Multi). Drives wall-clock
1642 /// frame pacing in the frontend and clock-divider selection inside the
1643 /// PPU + APU.
1644 #[must_use]
1645 pub const fn region(&self) -> rustynes_mappers::Region {
1646 self.cart.region
1647 }
1648
1649 /// Length in bytes of the loaded cartridge's PRG-ROM (read-only metadata).
1650 #[must_use]
1651 pub const fn prg_rom_len(&self) -> usize {
1652 self.cart.prg_rom.len()
1653 }
1654
1655 /// Length in bytes of the loaded cartridge's CHR-ROM (0 when the board uses
1656 /// CHR-RAM). Read-only metadata.
1657 #[must_use]
1658 pub const fn chr_rom_len(&self) -> usize {
1659 self.cart.chr_rom.len()
1660 }
1661
1662 /// Enable the per-CPU-cycle IRQ-timing trace fixture with the given
1663 /// record capacity. Records past the cap are silently dropped (see
1664 /// `IrqTrace::overflow`). See ADR-0002 "Decision (revised,
1665 /// 2026-05-13)" → "Test fixture" and
1666 /// `crates/rustynes-core/src/irq_trace.rs`.
1667 #[cfg(feature = "irq-timing-trace")]
1668 pub fn enable_irq_trace(&mut self, capacity: usize) {
1669 self.irq_trace = Some(IrqTrace::with_capacity(capacity));
1670 // Session-21: reset bus-access tracker so the first traced cycle
1671 // reflects accurate (CPU-driven) state rather than a stale
1672 // pre-trace driver.
1673 self.trace_bus_access = BusAccess::Idle;
1674 self.trace_bus_addr = 0;
1675 self.trace_bus_data = 0;
1676 }
1677
1678 /// Take the accumulated IRQ trace, leaving the bus's trace slot empty.
1679 /// Returns `None` if tracing was never enabled.
1680 #[cfg(feature = "irq-timing-trace")]
1681 #[must_use]
1682 pub const fn take_irq_trace(&mut self) -> Option<IrqTrace> {
1683 self.irq_trace.take()
1684 }
1685
1686 /// Borrow the in-flight IRQ trace for inspection without taking it.
1687 #[cfg(feature = "irq-timing-trace")]
1688 #[must_use]
1689 pub const fn irq_trace(&self) -> Option<&IrqTrace> {
1690 self.irq_trace.as_ref()
1691 }
1692
1693 /// Direct CPU-bus probe (does **not** advance time). Intended for
1694 /// blargg-style status polls at `$6000-$7FFF` and the test harness's
1695 /// mapper-resident WRAM peek. Note that this still has side effects on
1696 /// PPU registers (`$2002` clears VBL and toggle, `$2007` reads advance
1697 /// the buffer); callers should avoid touching `$2000-$3FFF` via peek.
1698 pub fn peek_cpu(&mut self, addr: u16) -> u8 {
1699 self.raw_cpu_read(addr)
1700 }
1701
1702 /// Add a Game Genie code (6 or 8 characters, case-insensitive). The code
1703 /// patches a PRG address (`$8000-$FFFF`) on the CPU read path; adding a
1704 /// code at an address that already has one replaces it.
1705 ///
1706 /// # Errors
1707 ///
1708 /// Returns [`GenieError`] if the code string cannot be decoded.
1709 pub fn add_genie_code(&mut self, code: &str) -> Result<(), GenieError> {
1710 let gc = GenieCode::new(code)?;
1711 self.genie_codes.insert(gc.addr(), gc);
1712 Ok(())
1713 }
1714
1715 /// Remove the active Game Genie code whose canonical (upper-case) string
1716 /// matches `code`. No-op if no such code is active.
1717 pub fn remove_genie_code(&mut self, code: &str) {
1718 let want = code.to_ascii_uppercase();
1719 self.genie_codes.retain(|_, gc| gc.code() != want.as_str());
1720 }
1721
1722 /// Remove all active Game Genie codes.
1723 pub fn clear_genie_codes(&mut self) {
1724 self.genie_codes.clear();
1725 }
1726
1727 /// Iterate the active Game Genie codes (address-sorted).
1728 pub fn genie_codes(&self) -> impl Iterator<Item = &GenieCode> {
1729 self.genie_codes.values()
1730 }
1731
1732 /// Apply any active Game Genie code at `addr` to a freshly-read byte.
1733 /// Fast-paths (single branch) when no codes are active.
1734 fn apply_genie(&self, addr: u16, original: u8) -> u8 {
1735 if self.genie_codes.is_empty() {
1736 return original;
1737 }
1738 self.genie_codes
1739 .get(&addr)
1740 .map_or(original, |gc| gc.read(original))
1741 }
1742
1743 /// Side-effect-free CPU bus sample for the debugger hex viewer.
1744 ///
1745 /// Returns the bus's view of the byte at `addr` without the side
1746 /// effects `peek_cpu` / `raw_cpu_read` carry on PPU register space
1747 /// (no VBL clear, no PPUDATA buffer advance, no open-bus update). For
1748 /// PPU registers we read back the cached snapshot; for mappers we go
1749 /// through `cpu_read` — the overwhelming majority of mappers are
1750 /// idempotent on `$8000-$FFFF` reads, and the few that latch on read
1751 /// (MMC2 in particular) document that behavior as inherent.
1752 ///
1753 /// Takes `&mut self` because mapper `cpu_read` is `&mut` — but no
1754 /// emulator-visible state advances. The CPU cycle counter, PPU
1755 /// scheduler, and APU all stay put.
1756 pub fn debug_peek_cpu(&mut self, addr: u16) -> u8 {
1757 match addr {
1758 0x0000..=0x1FFF => self.ram[(addr & 0x07FF) as usize],
1759 0x2000..=0x3FFF => {
1760 let reg = (addr & 7) as u8;
1761 let regs = self.ppu.debug_registers();
1762 match reg {
1763 0 => regs[0],
1764 1 => regs[1],
1765 2 => regs[2],
1766 3 => regs[3],
1767 _ => 0,
1768 }
1769 }
1770 0x4015 => {
1771 let mut v = 0u8;
1772 if self.apu.pulse1_out() != 0 {
1773 v |= 0x01;
1774 }
1775 if self.apu.pulse2_out() != 0 {
1776 v |= 0x02;
1777 }
1778 if self.apu.triangle_out() != 0 {
1779 v |= 0x04;
1780 }
1781 if self.apu.noise_out() != 0 {
1782 v |= 0x08;
1783 }
1784 if self.apu.frame_irq_pending() {
1785 v |= 0x40;
1786 }
1787 if self.apu.dmc_irq_pending() {
1788 v |= 0x80;
1789 }
1790 v
1791 }
1792 0x4016 => 0x40 | self.peek_port(0) | (u8::from(self.famicom_mic) << 2),
1793 0x4017 => 0x40 | self.peek_port(1),
1794 0x4000..=0x4014 | 0x4018..=0x401F => self.open_bus,
1795 0x4020..=0xFFFF => {
1796 // Mirror the production read path so the debugger hex viewer
1797 // shows the Game-Genie-substituted byte the CPU would see,
1798 // through `cpu_peek` so a board whose read consumes state
1799 // keeps it (v3.2.0: the FFE trainer boot).
1800 let raw = self.mapper.cpu_peek(addr);
1801 self.apply_genie(addr, raw)
1802 }
1803 }
1804 }
1805
1806 /// Side-effect-free PPU bus sample (`$0000-$3FFF`).
1807 ///
1808 /// `$0000-$1FFF` -> mapper CHR, `$2000-$3EFF` -> nametable
1809 /// (via mapper's mirroring), `$3F00-$3FFF` -> palette RAM.
1810 pub fn debug_peek_ppu(&mut self, addr: u16) -> u8 {
1811 let addr = addr & 0x3FFF;
1812 match addr {
1813 // Side-effect-free on every board: a debugger panel or an HD-pack
1814 // tile hash must never change the game (until v3.1.0 opening the
1815 // pattern viewer on Punch-Out!! flipped its CHR latch). Since v3.2.0
1816 // that is `Mapper::ppu_peek`'s contract -- exactly the byte
1817 // `ppu_read` would return, with no state change -- checked for every
1818 // board by `ppu_peek_matches_a_side_effect_free_ppu_read`, instead of
1819 // a save / `ppu_read` / restore around impure boards here.
1820 0x0000..=0x1FFF => self.mapper.ppu_peek(addr),
1821 0x2000..=0x3EFF => {
1822 let addr = if addr >= 0x3000 && !self.mapper.nametable_unfolded() {
1823 addr - 0x1000
1824 } else {
1825 addr
1826 };
1827 if let Some(v) = self.mapper.nametable_fetch(addr) {
1828 v
1829 } else {
1830 let phys = match self.nt_mirroring_override {
1831 Some(m) => override_nt_addr(m, addr) as usize,
1832 None => self.mapper.nametable_address(addr) as usize,
1833 };
1834 let ciram = self.ppu.ciram();
1835 ciram[phys % ciram.len()]
1836 }
1837 }
1838 0x3F00..=0x3FFF => {
1839 let idx = (addr & 0x1F) as usize;
1840 let palette = self.ppu.palette_ram();
1841 // Mirror sprite-palette zero into BG-palette zero.
1842 let idx = if idx & 0x13 == 0x10 { idx & 0x0F } else { idx };
1843 palette[idx]
1844 }
1845 _ => 0,
1846 }
1847 }
1848
1849 /// v1.7.0 "Forge" Workstream A1 — debugger writeback. The structural mirror
1850 /// of [`Self::debug_peek_ppu`]: `$0000-$1FFF` → mapper CHR (`ppu_write`,
1851 /// a no-op on CHR-ROM), `$2000-$3EFF` → nametable (mapper-absorbed, else
1852 /// CIRAM via the active mirroring), `$3F00-$3FFF` → palette RAM.
1853 ///
1854 /// Side-effect-free w.r.t. the run loop: it is reached *only* through the
1855 /// gated post-frame poke path (the same caller-side, after-`run_frame` stage
1856 /// the raw RAM cheats use), so the deterministic core run loop is unchanged
1857 /// and the no-edit path is byte-identical. `debug-hooks`-gated.
1858 #[cfg(feature = "debug-hooks")]
1859 pub fn debug_poke_ppu(&mut self, addr: u16, value: u8) {
1860 let addr = addr & 0x3FFF;
1861 match addr {
1862 0x0000..=0x1FFF => self.mapper.ppu_write(addr & 0x1FFF, value),
1863 0x2000..=0x3EFF => {
1864 let nt_addr = if addr >= 0x3000 && !self.mapper.nametable_unfolded() {
1865 addr - 0x1000
1866 } else {
1867 addr
1868 };
1869 // Give the mapper a chance to absorb the write (ExRAM
1870 // nametables, fill-mode drops), exactly like `write_vram`.
1871 if !self.mapper.nametable_write(nt_addr, value) {
1872 let phys = match self.nt_mirroring_override {
1873 Some(m) => override_nt_addr(m, nt_addr) as usize,
1874 None => self.mapper.nametable_address(nt_addr) as usize,
1875 };
1876 self.ppu.debug_poke_ciram(phys, value);
1877 }
1878 }
1879 0x3F00..=0x3FFF => self.ppu.debug_poke_palette((addr & 0x1F) as u8, value),
1880 _ => {}
1881 }
1882 }
1883
1884 /// v1.7.0 "Forge" Workstream A1 — debugger writeback for one OAM byte
1885 /// (`idx` = 0..256). `debug-hooks`-gated; reached only through the gated
1886 /// post-frame poke path, so the default build is byte-identical.
1887 #[cfg(feature = "debug-hooks")]
1888 pub const fn debug_poke_oam(&mut self, idx: u8, value: u8) {
1889 self.ppu.debug_poke_oam(idx, value);
1890 }
1891
1892 /// v3.7.0 — the board's buffer for one ROM section, in image order
1893 /// (`Mapper::debug_prg_rom_mut` / `debug_chr_rom_mut`), or `None` when the
1894 /// board does not offer it.
1895 #[cfg(feature = "debug-hooks")]
1896 fn debug_rom_buf(&mut self, space: crate::RomSpace) -> Option<&mut [u8]> {
1897 match space {
1898 crate::RomSpace::Prg => self.mapper.debug_prg_rom_mut(),
1899 crate::RomSpace::Chr => self.mapper.debug_chr_rom_mut(),
1900 }
1901 }
1902
1903 /// v3.7.0 — the length of one ROM section as the debugger can edit it, or
1904 /// `None` when the board does not offer that section. Reads nothing the
1905 /// emulation sees.
1906 #[cfg(feature = "debug-hooks")]
1907 pub fn debug_rom_len(&mut self, space: crate::RomSpace) -> Option<usize> {
1908 self.debug_rom_buf(space).map(|b| b.len())
1909 }
1910
1911 /// v3.7.0 — one ROM byte by image offset (see [`crate::RomSpace`]), with no
1912 /// side effect. `None` when the board does not offer the section or the
1913 /// offset is past its end.
1914 #[cfg(feature = "debug-hooks")]
1915 pub fn debug_peek_rom(&mut self, space: crate::RomSpace, offset: usize) -> Option<u8> {
1916 self.debug_rom_buf(space)?.get(offset).copied()
1917 }
1918
1919 /// v3.7.0 (`T-HACK-BPS-RECORDER`) — write one ROM byte in place, by image
1920 /// offset: the debugger's live ROM editor.
1921 ///
1922 /// The board's own buffer is changed, so the CPU fetches the new byte at
1923 /// whatever address its banking maps the offset to, and the PPU draws the
1924 /// new pattern byte, from the next access on; there is no decoded copy to
1925 /// refresh. Nothing in the run loop calls this. Like `debug_poke_ppu` it
1926 /// is reached only through the frontend's gated post-frame poke path, so
1927 /// the default build, and a debugger session with no ROM edit, run
1928 /// byte-identically.
1929 ///
1930 /// What it does not do: change [`crate::Nes::rom_sha256`] (the identity
1931 /// stays the clean image's, which is what a patch is made against) or
1932 /// enter any save state (states carry no ROM; see
1933 /// `docs/live-patch-recorder.md`).
1934 ///
1935 /// # Errors
1936 ///
1937 /// [`crate::RomWriteError::Unsupported`] when the board does not offer the
1938 /// section, [`crate::RomWriteError::OutOfRange`] past its end; in both
1939 /// cases nothing changes.
1940 #[cfg(feature = "debug-hooks")]
1941 pub fn debug_poke_rom(
1942 &mut self,
1943 space: crate::RomSpace,
1944 offset: usize,
1945 value: u8,
1946 ) -> Result<(), crate::RomWriteError> {
1947 let buf = self
1948 .debug_rom_buf(space)
1949 .ok_or(crate::RomWriteError::Unsupported(space))?;
1950 let len = buf.len();
1951 let byte = buf
1952 .get_mut(offset)
1953 .ok_or(crate::RomWriteError::OutOfRange { space, offset, len })?;
1954 *byte = value;
1955 Ok(())
1956 }
1957
1958 /// Borrow the PPU (debugger / tests).
1959 #[must_use]
1960 pub const fn ppu(&self) -> &Ppu {
1961 &self.ppu
1962 }
1963
1964 /// Mutably borrow the PPU (debugger / tests).
1965 pub const fn ppu_mut(&mut self) -> &mut Ppu {
1966 &mut self.ppu
1967 }
1968
1969 /// Borrow the APU (debugger / tests).
1970 #[must_use]
1971 pub const fn apu(&self) -> &Apu {
1972 &self.apu
1973 }
1974
1975 /// Mutably borrow the APU (debugger / tests).
1976 pub const fn apu_mut(&mut self) -> &mut Apu {
1977 &mut self.apu
1978 }
1979
1980 /// Set the buttons currently held on player `port`. Ports 0/1 are the
1981 /// standard `$4016`/`$4017` controllers; ports 2/3 are players 3/4 on the
1982 /// Four Score adapter (only polled when [`Self::set_four_score`] is on).
1983 /// The change takes effect on the next strobe edge.
1984 ///
1985 /// # Panics
1986 ///
1987 /// Panics if `port` is not in `0..=3`.
1988 pub const fn set_buttons(&mut self, port: usize, buttons: Buttons) {
1989 assert!(
1990 port < 4,
1991 "controller port must be 0..=3 (2/3 are the Four Score)"
1992 );
1993 match port {
1994 0 | 1 => self.controllers[port].set_buttons(buttons),
1995 _ => self.controllers34[port - 2].set_buttons(buttons),
1996 }
1997 }
1998
1999 /// Enable the **beam-relative** Zapper light model.
2000 ///
2001 /// **Default ON since v2.3.6.** The light bit is derived from where the CRT
2002 /// beam is at the moment of the `$4016`/`$4017` read: dark before the beam
2003 /// paints the aim row, lit while the photodiode holds (~19-26 scanlines,
2004 /// per the `NESdev` wiki's capacitor model), dark once it drains. That is what
2005 /// real hardware does, and the frame-granular model structurally cannot
2006 /// express it — it returns one answer for the whole frame, sampled at
2007 /// end-of-frame, so every read during frame N reports frame N-1.
2008 ///
2009 /// # Why it was promoted (v2.3.6)
2010 ///
2011 /// A3 (v2.2.3) shipped this off, on the reasoning that "there is no pass/fail
2012 /// light-gun test ROM… the supported titles re-poll every frame and are
2013 /// satisfied by either model". **The second half of that was false**, and no
2014 /// test ROM was needed to show it — the game itself is the oracle.
2015 ///
2016 /// *Duck Hunt* requires the gun to see **nothing for one frame** and then a
2017 /// bright spot in the next. Under the frame model it received exactly the
2018 /// inverse: on the blanked frame it read the previous (bright) frame's
2019 /// answer, and on the target frame it read the blanked frame's. The shot was
2020 /// discarded before hit-testing, so the gun fired and **nothing could ever be
2021 /// hit** — reported by the maintainer, then reproduced headlessly from the
2022 /// game's own `$4017` traffic (`zapper_light_probe`).
2023 ///
2024 /// Measured A/B on the same ROM, aim and inputs: frame model → score 000000,
2025 /// duck still flying; beam-relative → score 000500, duck marked hit.
2026 ///
2027 /// Turning it off restores the pre-v2.3.6 frame-granular behaviour.
2028 /// Deterministic either way: the answer is a pure function of framebuffer +
2029 /// aim + scanline and holds no state, so it adds nothing to serialize.
2030 pub const fn set_zapper_temporal_light(&mut self, on: bool) {
2031 self.zapper_temporal_light = on;
2032 }
2033
2034 /// Whether the beam-relative Zapper light model is enabled (A3).
2035 #[must_use]
2036 pub const fn zapper_temporal_light(&self) -> bool {
2037 self.zapper_temporal_light
2038 }
2039
2040 /// Attach (or replace) a non-standard overlay device on `port` (0 =
2041 /// `$4016`, 1 = `$4017`). Pass `None` to unplug the device and return the
2042 /// port to the standard controller / Four Score path (byte-identical).
2043 ///
2044 /// # Panics
2045 ///
2046 /// Panics if `port` is not in `0..=1`.
2047 pub fn set_expansion_device(
2048 &mut self,
2049 port: usize,
2050 device: Option<crate::input_device::InputDevice>,
2051 ) {
2052 assert!(port < 2, "expansion-device port must be 0..=1");
2053 self.expansion_device[port] = device;
2054 }
2055
2056 /// Borrow the overlay device attached to `port`, if any.
2057 ///
2058 /// # Panics
2059 ///
2060 /// Panics if `port` is not in `0..=1`.
2061 #[must_use]
2062 pub const fn expansion_device(&self, port: usize) -> &Option<crate::input_device::InputDevice> {
2063 assert!(port < 2, "expansion-device port must be 0..=1");
2064 &self.expansion_device[port]
2065 }
2066
2067 /// Update an attached Vaus paddle's position + fire state on `port`. No-op
2068 /// if the attached device is not a Vaus (or no device is attached).
2069 ///
2070 /// # Panics
2071 ///
2072 /// Panics if `port` is not in `0..=1`.
2073 pub const fn set_paddle(&mut self, port: usize, position: u8, fire: bool) {
2074 assert!(port < 2, "paddle port must be 0..=1");
2075 if let Some(crate::input_device::InputDevice::Vaus(v)) = &mut self.expansion_device[port] {
2076 v.set(position, fire);
2077 }
2078 }
2079
2080 /// Update an attached Zapper's aim point + trigger on `port`. No-op if the
2081 /// attached device is not a Zapper (or no device is attached).
2082 ///
2083 /// # Panics
2084 ///
2085 /// Panics if `port` is not in `0..=1`.
2086 pub const fn set_zapper(&mut self, port: usize, x: u16, y: u16, trigger: bool) {
2087 assert!(port < 2, "zapper port must be 0..=1");
2088 if let Some(crate::input_device::InputDevice::Zapper(z)) = &mut self.expansion_device[port]
2089 {
2090 z.set(x, y, trigger);
2091 }
2092 }
2093
2094 /// Drive the Famicom built-in microphone signal (read on `$4016` bit 2).
2095 ///
2096 /// `pressed` = the frontend's quantized "mic is loud" verdict. Additive:
2097 /// leaving it `false` (the default) keeps the `$4016` read byte-identical.
2098 pub const fn set_microphone(&mut self, pressed: bool) {
2099 self.famicom_mic = pressed;
2100 }
2101
2102 /// Whether the Famicom microphone signal is currently asserted.
2103 #[must_use]
2104 pub const fn microphone(&self) -> bool {
2105 self.famicom_mic
2106 }
2107
2108 /// Update an attached Power Pad's live button mask (bit `i` = mat button
2109 /// `i+1`) on `port`. No-op if the attached device is not a Power Pad.
2110 ///
2111 /// # Panics
2112 ///
2113 /// Panics if `port` is not in `0..=1`.
2114 pub const fn set_power_pad(&mut self, port: usize, buttons: u16) {
2115 assert!(port < 2, "power pad port must be 0..=1");
2116 if let Some(crate::input_device::InputDevice::PowerPad(p)) =
2117 &mut self.expansion_device[port]
2118 {
2119 p.set(buttons);
2120 }
2121 }
2122
2123 /// Update an attached SNES mouse's movement + buttons + sensitivity on
2124 /// `port`. No-op if the attached device is not a mouse.
2125 ///
2126 /// # Panics
2127 ///
2128 /// Panics if `port` is not in `0..=1`.
2129 pub const fn set_snes_mouse(
2130 &mut self,
2131 port: usize,
2132 dx: i16,
2133 dy: i16,
2134 left: bool,
2135 right: bool,
2136 sensitivity: u8,
2137 ) {
2138 assert!(port < 2, "mouse port must be 0..=1");
2139 if let Some(crate::input_device::InputDevice::SnesMouse(m)) =
2140 &mut self.expansion_device[port]
2141 {
2142 m.set(dx, dy, left, right, sensitivity);
2143 }
2144 }
2145
2146 /// Update an attached Family BASIC keyboard's pressed-key bitmap on `port`
2147 /// (one byte per matrix row). No-op if the attached device is not a keyboard.
2148 ///
2149 /// # Panics
2150 ///
2151 /// Panics if `port` is not in `0..=1`.
2152 pub const fn set_family_keyboard(&mut self, port: usize, keys: [u8; 9]) {
2153 assert!(port < 2, "keyboard port must be 0..=1");
2154 if let Some(crate::input_device::InputDevice::FamilyKeyboard(k)) =
2155 &mut self.expansion_device[port]
2156 {
2157 k.set_keys(keys);
2158 }
2159 }
2160
2161 /// v1.3.0 Workstream F1 — update an attached Family Trainer mat's 12-button
2162 /// mask on `port`. No-op if the attached device is not a Family Trainer.
2163 ///
2164 /// # Panics
2165 ///
2166 /// Panics if `port` is not in `0..=1`.
2167 pub const fn set_family_trainer(&mut self, port: usize, buttons: u16) {
2168 assert!(port < 2, "family trainer port must be 0..=1");
2169 if let Some(crate::input_device::InputDevice::FamilyTrainer(p)) =
2170 &mut self.expansion_device[port]
2171 {
2172 p.set(buttons);
2173 }
2174 }
2175
2176 /// v1.3.0 Workstream F1 — update an attached Subor keyboard's pressed-key
2177 /// bitmap on `port`. No-op if the attached device is not a Subor keyboard.
2178 ///
2179 /// # Panics
2180 ///
2181 /// Panics if `port` is not in `0..=1`.
2182 pub const fn set_subor_keyboard(&mut self, port: usize, keys: [u8; 9]) {
2183 assert!(port < 2, "subor keyboard port must be 0..=1");
2184 if let Some(crate::input_device::InputDevice::SuborKeyboard(k)) =
2185 &mut self.expansion_device[port]
2186 {
2187 k.set_keys(keys);
2188 }
2189 }
2190
2191 /// v1.3.0 Workstream F1 — update an attached Konami Hyper Shot's 4-button
2192 /// mask on `port`. No-op if the attached device is not a Konami Hyper Shot.
2193 ///
2194 /// # Panics
2195 ///
2196 /// Panics if `port` is not in `0..=1`.
2197 pub const fn set_konami_hyper_shot(&mut self, port: usize, buttons: u8) {
2198 assert!(port < 2, "konami hyper shot port must be 0..=1");
2199 if let Some(crate::input_device::InputDevice::KonamiHyperShot(h)) =
2200 &mut self.expansion_device[port]
2201 {
2202 h.set(buttons);
2203 }
2204 }
2205
2206 /// v1.3.0 Workstream F1 — update an attached Bandai Hyper Shot's 8-sensor
2207 /// mask on `port`. No-op if the attached device is not a Bandai Hyper Shot.
2208 ///
2209 /// # Panics
2210 ///
2211 /// Panics if `port` is not in `0..=1`.
2212 pub const fn set_bandai_hyper_shot(&mut self, port: usize, sensors: u8) {
2213 assert!(port < 2, "bandai hyper shot port must be 0..=1");
2214 if let Some(crate::input_device::InputDevice::BandaiHyperShot(b)) =
2215 &mut self.expansion_device[port]
2216 {
2217 b.set(sensors);
2218 }
2219 }
2220
2221 /// v1.1.0 beta.1 (T-110-B4) — set (`Some`) or clear (`None`) the per-game
2222 /// nametable mirroring override. A frontend load-time correction; `None`
2223 /// (default) defers to the mapper (byte-identical).
2224 pub const fn set_mirroring_override(&mut self, m: Option<rustynes_mappers::Mirroring>) {
2225 self.nt_mirroring_override = m;
2226 }
2227
2228 /// The current per-game mirroring override (for the save-state).
2229 #[must_use]
2230 pub const fn mirroring_override(&self) -> Option<rustynes_mappers::Mirroring> {
2231 self.nt_mirroring_override
2232 }
2233
2234 /// Whether the loaded mapper hardwires its nametable mirroring (so an
2235 /// external mirroring correction is safe to honor). See
2236 /// [`rustynes_mappers::Mapper::has_hardwired_mirroring`].
2237 #[must_use]
2238 pub fn mapper_has_hardwired_mirroring(&self) -> bool {
2239 self.mapper.has_hardwired_mirroring()
2240 }
2241
2242 /// v1.1.0 beta.2 (T-110-C3) — start/stop event-viewer recording.
2243 #[cfg(feature = "debug-hooks")]
2244 pub const fn set_event_logging(&mut self, enabled: bool) {
2245 self.event_logging = enabled;
2246 }
2247
2248 /// Whether event-viewer recording is on.
2249 #[cfg(feature = "debug-hooks")]
2250 #[must_use]
2251 pub const fn event_logging(&self) -> bool {
2252 self.event_logging
2253 }
2254
2255 /// The events captured so far this frame.
2256 #[cfg(feature = "debug-hooks")]
2257 #[must_use]
2258 #[allow(clippy::missing_const_for_fn)] // Vec->slice deref is not const.
2259 pub fn events(&self) -> &[EventRec] {
2260 &self.events
2261 }
2262
2263 /// v1.1.0 beta.3 (T-110-E2) — start/stop the Lua bus-access log.
2264 #[cfg(feature = "debug-hooks")]
2265 pub const fn set_access_logging(&mut self, enabled: bool) {
2266 self.access_logging = enabled;
2267 }
2268
2269 /// Whether the bus-access log is recording.
2270 #[cfg(feature = "debug-hooks")]
2271 #[must_use]
2272 pub const fn access_logging(&self) -> bool {
2273 self.access_logging
2274 }
2275
2276 /// The CPU bus accesses captured so far this frame.
2277 #[cfg(feature = "debug-hooks")]
2278 #[must_use]
2279 #[allow(clippy::missing_const_for_fn)] // Vec->slice deref is not const.
2280 pub fn accesses(&self) -> &[AccessRec] {
2281 &self.accesses
2282 }
2283
2284 /// Clear the bus-access log (called per frame by the run loop).
2285 #[cfg(feature = "debug-hooks")]
2286 pub fn clear_accesses(&mut self) {
2287 self.accesses.clear();
2288 }
2289
2290 /// v1.2.0 (T-110-E1) — start/stop the Lua interrupt-service log.
2291 #[cfg(feature = "debug-hooks")]
2292 pub const fn set_interrupt_logging(&mut self, enabled: bool) {
2293 self.interrupt_logging = enabled;
2294 }
2295
2296 /// Whether the interrupt-service log is recording.
2297 #[cfg(feature = "debug-hooks")]
2298 #[must_use]
2299 pub const fn interrupt_logging(&self) -> bool {
2300 self.interrupt_logging
2301 }
2302
2303 /// The interrupt-service entries captured so far this frame.
2304 #[cfg(feature = "debug-hooks")]
2305 #[must_use]
2306 #[allow(clippy::missing_const_for_fn)] // Vec->slice deref is not const.
2307 pub fn interrupts(&self) -> &[InterruptRec] {
2308 &self.interrupts
2309 }
2310
2311 /// Clear the interrupt-service log (called per frame by the run loop).
2312 #[cfg(feature = "debug-hooks")]
2313 pub fn clear_interrupts(&mut self) {
2314 self.interrupts.clear();
2315 }
2316
2317 /// v1.4.0 Workstream D (D2) — set the armed event-breakpoint category mask
2318 /// (a bit-OR of [`EventBpKind::bit`]). `0` disarms all (the default + the
2319 /// per-cycle-cheap path).
2320 #[cfg(feature = "debug-hooks")]
2321 pub const fn set_event_breakpoints(&mut self, mask: u16) {
2322 self.event_bp_mask = mask;
2323 }
2324
2325 /// The armed event-breakpoint category mask.
2326 #[cfg(feature = "debug-hooks")]
2327 #[must_use]
2328 pub const fn event_breakpoints(&self) -> u16 {
2329 self.event_bp_mask
2330 }
2331
2332 /// Take the first event-breakpoint hit of the current frame (cleared on
2333 /// read). The frontend polls this after `run_frame`.
2334 #[cfg(feature = "debug-hooks")]
2335 pub const fn take_event_break_hit(&mut self) -> Option<EventBreakHit> {
2336 self.event_break_hit.take()
2337 }
2338
2339 /// Clear any recorded event-breakpoint hit (called per frame by the run
2340 /// loop so each frame starts fresh).
2341 #[cfg(feature = "debug-hooks")]
2342 pub const fn clear_event_break_hit(&mut self) {
2343 self.event_break_hit = None;
2344 }
2345
2346 /// v1.4.0 Workstream D (D2) — observational event-breakpoint tap. If `kind`
2347 /// is armed and no hit has been recorded yet this frame, latch the event
2348 /// with its full timing context. Pure observation — no emulator-visible
2349 /// state changes, so determinism holds. The `mask == 0` fast path keeps the
2350 /// default (no armed categories) cheap.
2351 #[cfg(feature = "debug-hooks")]
2352 const fn record_event_break(&mut self, kind: EventBpKind, addr: u16) {
2353 if self.event_bp_mask & kind.bit() == 0 || self.event_break_hit.is_some() {
2354 return;
2355 }
2356 self.event_break_hit = Some(EventBreakHit {
2357 kind,
2358 addr,
2359 frame: self.ppu.frame(),
2360 cycle: self.cycle,
2361 scanline: self.ppu.scanline(),
2362 dot: self.ppu.dot(),
2363 });
2364 }
2365
2366 /// Clear the event log (called at each frame start while recording).
2367 #[cfg(feature = "debug-hooks")]
2368 pub fn clear_events(&mut self) {
2369 self.events.clear();
2370 }
2371
2372 /// Clear the per-frame `TAStudio` lag-log "controller polled" flag (called at
2373 /// the top of each [`crate::Nes::run_frame`]). `debug-hooks`-gated;
2374 /// output-only, so the shipped build is byte-identical.
2375 #[cfg(feature = "debug-hooks")]
2376 pub(crate) const fn clear_controller_polled(&mut self) {
2377 self.controller_polled = false;
2378 }
2379
2380 /// `true` if a controller port (`$4016`/`$4017`) was read since the last
2381 /// [`Self::clear_controller_polled`] — i.e. during the current frame.
2382 #[cfg(feature = "debug-hooks")]
2383 #[must_use]
2384 pub(crate) const fn controller_polled(&self) -> bool {
2385 self.controller_polled
2386 }
2387
2388 /// Sample the framebuffer luminance at each attached Zapper's aim point.
2389 /// Called once per frame (only does work when a Zapper is attached, so the
2390 /// no-device path is byte-identical).
2391 pub fn sample_zapper_light(&mut self) {
2392 let has_zapper = self
2393 .expansion_device
2394 .iter()
2395 .any(|d| matches!(d, Some(crate::input_device::InputDevice::Zapper(_))));
2396 if !has_zapper {
2397 return;
2398 }
2399 // Borrow the framebuffer once; copy the per-port aim sample.
2400 for port in 0..2 {
2401 if let Some(crate::input_device::InputDevice::Zapper(_)) = &self.expansion_device[port]
2402 {
2403 // Take the device out to avoid the &mut self / &self.ppu borrow
2404 // conflict, sample, then put it back.
2405 let mut dev = self.expansion_device[port].take();
2406 if let Some(crate::input_device::InputDevice::Zapper(z)) = &mut dev {
2407 z.sample_light(self.ppu.framebuffer());
2408 }
2409 self.expansion_device[port] = dev;
2410 }
2411 }
2412 }
2413
2414 /// Borrow controller `port` (0/1 = `$4016`/`$4017`; 2/3 = Four Score
2415 /// players 3/4).
2416 ///
2417 /// # Panics
2418 ///
2419 /// Panics if `port` is not in `0..=3`.
2420 #[must_use]
2421 pub const fn controller(&self, port: usize) -> &Controller {
2422 match port {
2423 0 | 1 => &self.controllers[port],
2424 _ => &self.controllers34[port - 2],
2425 }
2426 }
2427
2428 /// Has the PPU completed a frame? Drains the latch.
2429 pub const fn take_frame_complete(&mut self) -> bool {
2430 self.ppu.take_frame_complete()
2431 }
2432
2433 /// Drain finalized audio samples (host sample rate, normalized `[0, ~1]`).
2434 pub fn drain_audio(&mut self) -> Vec<f32> {
2435 self.apu.drain_audio()
2436 }
2437
2438 /// Drain into a slice.
2439 pub fn drain_audio_into(&mut self, out: &mut [f32]) -> usize {
2440 self.apu.drain_audio_into(out)
2441 }
2442
2443 /// Cumulative CPU cycle count.
2444 #[must_use]
2445 pub const fn cycle(&self) -> u64 {
2446 self.cycle
2447 }
2448
2449 /// Set the Vs. System 8-bit DIP switch bank (switch 1 = bit 0 ..
2450 /// switch 8 = bit 7). No effect on non-Vs. carts. Default 0.
2451 pub const fn set_vs_dip(&mut self, dip: u8) {
2452 self.vs_dip = dip;
2453 }
2454
2455 /// Current Vs. System DIP switch bank.
2456 #[must_use]
2457 pub const fn vs_dip(&self) -> u8 {
2458 self.vs_dip
2459 }
2460
2461 /// Push the cartridge's current [`rustynes_mappers::VsPpuType`] into the PPU
2462 /// (output palette + 2C05 `$2000`/`$2001` swap + `$2002` identifier).
2463 ///
2464 /// Called from the constructor, [`Self::power_cycle`], and
2465 /// [`Self::set_vs_ppu_type`]. For [`rustynes_mappers::ConsoleType::Nes`] carts
2466 /// the resolved type is [`rustynes_mappers::VsPpuType::None`] -> `Composite2C02`,
2467 /// `is_2c05 = false`, so this is byte-for-byte a no-op on normal carts.
2468 const fn reapply_vs_palette(&mut self) {
2469 let vs = self.cart.vs_ppu_type;
2470 let palette = vs_palette_to_ppu(vs.ppu_palette());
2471 self.ppu
2472 .set_palette(palette, vs.is_2c05(), vs.ppu_2c05_id());
2473 }
2474
2475 /// Override the Vs. System PPU type and re-apply the output palette / 2C05
2476 /// quirks immediately.
2477 ///
2478 /// iNES-1.0 dumps carry no NES 2.0 byte-13, so the parser defaults a Vs.
2479 /// cart to [`rustynes_mappers::VsPpuType::Rp2C03`]; a per-game database (keyed on
2480 /// the ROM SHA-256) supplies the correct 2C04-000x / 2C05 type, which the
2481 /// frontend applies through this setter. No effect on the running game's
2482 /// logic — only the colour LUT the PPU emits through. No-op shape on
2483 /// non-Vs. carts (the default path never calls this).
2484 pub const fn set_vs_ppu_type(&mut self, t: rustynes_mappers::VsPpuType) {
2485 self.cart.vs_ppu_type = t;
2486 self.reapply_vs_palette();
2487 }
2488
2489 /// Latch a Vs. System coin insertion. `acceptor` 0 = acceptor #1 ($4016
2490 /// bit 5), 1 = acceptor #2 ($4016 bit 6); any other value is ignored. The
2491 /// frontend should clear the latch (see [`Self::clear_coin`]) after the
2492 /// real-hardware ~40-70 ms window (a few frames). No effect on non-Vs.
2493 /// carts.
2494 pub const fn insert_coin(&mut self, acceptor: u8) {
2495 match acceptor {
2496 0 => self.vs_coin |= 0x01,
2497 1 => self.vs_coin |= 0x02,
2498 _ => {}
2499 }
2500 }
2501
2502 /// Clear all latched Vs. System coin-insert signals.
2503 pub const fn clear_coin(&mut self) {
2504 self.vs_coin = 0;
2505 }
2506
2507 /// Set / clear the Vs. System service button ($4016 bit 2).
2508 pub const fn set_vs_service(&mut self, pressed: bool) {
2509 self.vs_service = pressed;
2510 }
2511
2512 /// v3.5.0 — the latched coin-insert bits (bit 0 = acceptor #1, bit 1 =
2513 /// acceptor #2), for a movie recorder.
2514 #[must_use]
2515 pub const fn vs_coin(&self) -> u8 {
2516 self.vs_coin
2517 }
2518
2519 /// v3.5.0 — whether the service button is held, for a movie recorder.
2520 #[must_use]
2521 pub const fn vs_service(&self) -> bool {
2522 self.vs_service
2523 }
2524
2525 /// v2.0.0 beta.5 (Vs. `DualSystem`): mark this console as the SUB half of a
2526 /// `DualSystem` pair (`$4016` reads return bit 7 = `0x80`). Wrapper-only.
2527 pub const fn set_vs_sub(&mut self, is_sub: bool) {
2528 self.vs_is_sub = is_sub;
2529 }
2530
2531 /// v2.0.0 beta.5 (Vs. `DualSystem`): drive this console's external `/IRQ`
2532 /// line (the partner console's `$4016` bit-1 signal, Mesen2
2533 /// `IRQSource::External`). Wrapper-only; OR'd into the IRQ level.
2534 pub const fn set_vs_external_irq(&mut self, asserted: bool) {
2535 self.vs_external_irq = asserted;
2536 }
2537
2538 /// v2.0.0 beta.5 (Vs. `DualSystem`): poll-and-clear the latched `$4016`
2539 /// bit-1 (main/sub comms signal) LEVEL. Returns `Some(level)` whenever
2540 /// this console wrote `$4016` since the last poll — deliberately
2541 /// level-driven, not edge-filtered (see the `vs_4016_bit1_dirty` field
2542 /// doc); the wrapper turns the level into the partner's external-IRQ
2543 /// assert (LOW asserts, HIGH clears). The shared-WRAM convergence
2544 /// (`pump_comms`'s separate `drain_vs_dual_wram_writes` step) runs on
2545 /// BOTH consoles every poll, independent of this bit-1 signal.
2546 pub const fn take_vs_mainsub_edge(&mut self) -> Option<bool> {
2547 if self.vs_4016_bit1_dirty {
2548 self.vs_4016_bit1_dirty = false;
2549 Some(self.vs_4016_bit1)
2550 } else {
2551 None
2552 }
2553 }
2554
2555 /// v2.0.0 beta.5 (Vs. `DualSystem`): provision the mapper-99 shared 2 KiB
2556 /// WRAM window (`$6000-$7FFF`). Wrapper-only; no-op on other boards.
2557 pub fn enable_vs_dual_wram(&mut self) {
2558 self.mapper.enable_vs_dual_wram();
2559 }
2560
2561 /// v2.0.0 beta.5 (Vs. `DualSystem`): mark the mapper as the SUB
2562 /// console's instance (banks the second PRG half + upper CHR pages —
2563 /// the two CPUs run different programs). Wrapper-only cabinet wiring.
2564 pub fn set_vs_dual_sub(&mut self) {
2565 self.mapper.set_vs_dual_sub();
2566 }
2567
2568 /// v2.0.0 beta.5 (Vs. `DualSystem`): drain this console's shared-WRAM
2569 /// write log for the wrapper to replay into the partner console (the
2570 /// fully-shared MAME model). Empty off-board. Allocates a fresh `Vec`
2571 /// each call — fine for diagnostics/tests, NOT used by the hot
2572 /// `pump_comms` path (see [`Self::drain_vs_dual_wram_writes`]).
2573 pub fn take_vs_dual_wram_writes(&mut self) -> alloc::vec::Vec<(u16, u8)> {
2574 self.mapper.take_vs_dual_wram_writes()
2575 }
2576
2577 /// v2.0.0 beta.5 (Vs. `DualSystem`): drain this console's shared-WRAM
2578 /// write log into a caller-owned, reusable `dst` buffer — the
2579 /// hot-path counterpart of [`Self::take_vs_dual_wram_writes`], used by
2580 /// `VsDualSystem::pump_comms` (called after every stepped instruction)
2581 /// to avoid allocating a fresh `Vec` on every call.
2582 pub fn drain_vs_dual_wram_writes(&mut self, dst: &mut alloc::vec::Vec<(u16, u8)>) {
2583 self.mapper.drain_vs_dual_wram_writes(dst);
2584 }
2585
2586 /// v2.0.0 beta.5 (Vs. `DualSystem`): replay one partner-console write
2587 /// into this console's shared-WRAM copy (no re-log).
2588 pub fn apply_vs_dual_wram_write(&mut self, offset: u16, value: u8) {
2589 self.mapper.apply_vs_dual_wram_write(offset, value);
2590 }
2591
2592 /// v2.0.0 beta.5 (Vs. `DualSystem`): take the shared-WRAM copy (wrapper
2593 /// snapshot-restore normalization). `None` off-board.
2594 pub fn take_vs_dual_wram(&mut self) -> Option<alloc::boxed::Box<[u8]>> {
2595 self.mapper.take_vs_dual_wram()
2596 }
2597
2598 /// v2.0.0 beta.5 (Vs. `DualSystem`): install a shared-WRAM copy (the
2599 /// other half of the restore normalization).
2600 pub fn set_vs_dual_wram(&mut self, wram: alloc::boxed::Box<[u8]>) {
2601 self.mapper.set_vs_dual_wram(wram);
2602 }
2603
2604 /// True when the running cart is Vs. System hardware (NES 2.0 console type).
2605 #[must_use]
2606 pub fn is_vs_system(&self) -> bool {
2607 self.cart.console_type == rustynes_mappers::ConsoleType::VsSystem
2608 }
2609
2610 /// True when the cart's header marks a Vs. `DualSystem` board (two CPUs /
2611 /// two PPUs). Detection only — the dual-console emulation is a documented
2612 /// v2.0 deferral (`docs/audit/vs-dualsystem-design-2026-06-11.md`); this
2613 /// lets the frontend surface a clear note instead of a black screen.
2614 #[must_use]
2615 pub const fn is_vs_dual_system(&self) -> bool {
2616 self.cart.vs_dual_system
2617 }
2618
2619 /// Overlay the Vs. System `$4016` upper bits (service, DIP 1/2, coins) onto
2620 /// the standard controller read. No-op on non-Vs. carts, so the standard
2621 /// `$4016` read is byte-identical.
2622 ///
2623 /// Layout (nesdev "Vs. System" §`$4016` read): `PCCD DS0B` — bit 0 = right
2624 /// stick (already in `base`), bit 2 = service, bit 3 = DIP switch 1, bit 4 =
2625 /// DIP switch 2, bit 5 = coin #1, bit 6 = coin #2, bit 7 = primary CPU.
2626 /// Bit 7 is `0` on a single console / the `DualSystem` MAIN half and `0x80`
2627 /// on the `DualSystem` SUB half (Mesen2 `IsVsMainConsole() ? 0 : 0x80` —
2628 /// the identity bit the `DualSystem` ROM polls; v2.0.0 beta.5).
2629 fn vs_overlay_4016(&self, base: u8) -> u8 {
2630 if !self.is_vs_system() {
2631 return base;
2632 }
2633 // Keep only bit 0 (controller D0) + bit 1 (D1, always 0 here); the Vs.
2634 // bus drives bits 2-7 from the panel, not from open bus.
2635 let mut v = base & 0x01;
2636 if self.vs_service {
2637 v |= 0x04;
2638 }
2639 // DIP switch 1 -> bit 3, switch 2 -> bit 4.
2640 v |= (self.vs_dip & 0x01) << 3;
2641 v |= ((self.vs_dip >> 1) & 0x01) << 4;
2642 // Coin acceptors -> bits 5/6.
2643 v |= (self.vs_coin & 0x03) << 5;
2644 // v2.0.0 beta.5: the DualSystem main/sub identity bit.
2645 if self.vs_is_sub {
2646 v |= 0x80;
2647 }
2648 v
2649 }
2650
2651 /// Overlay the Vs. System `$4017` upper bits (DIP 3-8) onto the standard
2652 /// controller read. No-op on non-Vs. carts.
2653 ///
2654 /// Layout (nesdev "Vs. System" §`$4017` read): `DDDD DD0B` — bit 0 = left
2655 /// stick (already in `base`), bits 2-7 = DIP switches 3 through 8.
2656 fn vs_overlay_4017(&self, base: u8) -> u8 {
2657 if !self.is_vs_system() {
2658 return base;
2659 }
2660 // DIP switches 3..=8 occupy bits 2..=7 (switch 3 = DIP bit 2 -> $4017
2661 // bit 2, switch 8 = DIP bit 7 -> $4017 bit 7); a 1:1 mapping.
2662 (base & 0x01) | (self.vs_dip & 0xFC)
2663 }
2664
2665 /// Mapper debug info for the debugger UI: the mapper's own bank/IRQ state
2666 /// ENRICHED (v1.5.0 "Lens" Workstream I8) with the cartridge-level metadata
2667 /// the bus owns — submapper, accuracy tier, ROM/RAM sizes, battery, the IRQ
2668 /// mechanism, and the expansion-audio chip. Output-only; these enrichment
2669 /// fields are filled here rather than in each of the 100+ mappers, and they
2670 /// default to empty (so a mapper's own `debug_info()` is unchanged).
2671 #[must_use]
2672 pub fn mapper_debug_info(&self) -> rustynes_mappers::MapperDebugInfo {
2673 let mut info = self.mapper.debug_info();
2674 let cart = &self.cart;
2675 // v2.9.8 — the id is cartridge metadata, like the submapper below. A
2676 // board's `debug_info` names its own id only when it overrides the
2677 // default, which names mapper 0, so the debugger's mapper panel showed
2678 // "Mapper 0" for `UxROM`, CNROM, `AxROM` and every other board without
2679 // an override (and for an NSF, whose synthetic cartridge is mapper 31).
2680 info.mapper_id = cart.mapper_id;
2681 info.submapper = cart.submapper;
2682 info.tier = rustynes_mappers::mapper_tier(cart.mapper_id, cart.submapper)
2683 .map_or("", rustynes_mappers::MapperTier::name);
2684 info.prg_rom_size = cart.prg_rom.len();
2685 info.chr_rom_size = cart.chr_rom.len();
2686 info.prg_ram_size = cart.prg_ram_size as usize;
2687 info.chr_ram_size = cart.chr_ram_size as usize;
2688 info.has_battery = cart.has_battery;
2689 // IRQ mechanism: named per the documented per-mapper IRQ family table
2690 // (docs/mappers.md). MMC3/RAMBO use PPU A12; MMC5 uses scanline
2691 // detection; the VRC/FME-7/N163 families tick on the CPU-cycle hook.
2692 info.irq_kind = match cart.mapper_id {
2693 4 | 64 | 118 | 119 | 206 => "PPU A12 counter (MMC3-style)",
2694 5 => "PPU scanline (MMC5)",
2695 // CPU-cycle-clocked IRQ counters surface via the caps hook.
2696 _ if self.mapper_caps.cpu_cycle_hook => "CPU cycle (VRC / FME-7 / N163)",
2697 _ => "",
2698 };
2699 info.expansion_audio = if self.mapper_caps.audio {
2700 Some(match cart.mapper_id {
2701 5 => "MMC5",
2702 19 | 210 => "Namco 163",
2703 20 => "FDS",
2704 24 | 26 => "VRC6",
2705 69 => "Sunsoft 5B",
2706 85 => "VRC7 (OPLL)",
2707 _ => "Expansion audio",
2708 })
2709 } else {
2710 None
2711 };
2712 info
2713 }
2714
2715 /// The cached per-cycle mapper capability flags (see
2716 /// [`rustynes_mappers::MapperCaps`]). `caps.audio` reflects whether the
2717 /// loaded mapper has on-cart expansion audio with the `mapper-audio` feature
2718 /// compiled in — used by the frontend to surface expansion-channel mixing
2719 /// controls only for boards that actually have them.
2720 #[must_use]
2721 pub const fn mapper_caps(&self) -> rustynes_mappers::MapperCaps {
2722 self.mapper_caps
2723 }
2724
2725 /// Borrow CPU RAM (2 KiB).
2726 #[must_use]
2727 pub fn ram_bytes(&self) -> &[u8] {
2728 &*self.ram
2729 }
2730
2731 /// Borrow both controllers as a slice.
2732 #[must_use]
2733 pub const fn controllers_ref(&self) -> &[Controller; 2] {
2734 &self.controllers
2735 }
2736
2737 /// Borrow the Four Score players 3 & 4 (save-state).
2738 #[must_use]
2739 pub const fn controllers34_ref(&self) -> &[Controller; 2] {
2740 &self.controllers34
2741 }
2742
2743 /// The CPU cycle of `port`'s most recent read (`u64::MAX` = never), for
2744 /// the save state.
2745 #[must_use]
2746 pub const fn port_read_cycle(&self, port: usize) -> u64 {
2747 self.port_read_cycle[port]
2748 }
2749
2750 /// Restore the controller-port CLK run state: four `pending_shift` flags
2751 /// (ports 1-2 then the Four Score's 3-4) and the two per-port read cycles.
2752 /// The Four Score chain's owed-edge flags, for the snapshot.
2753 #[must_use]
2754 pub const fn four_score_pending(&self) -> [bool; 2] {
2755 self.four_score_pending
2756 }
2757
2758 /// Restore the Four Score chain's owed-edge flags. See
2759 /// [`Self::set_controller_run_state`]; kept beside it because the two are
2760 /// one piece of state split across two devices.
2761 pub const fn set_four_score_pending(&mut self, pending: [bool; 2]) {
2762 self.four_score_pending = pending;
2763 }
2764
2765 /// Restore the controller-port CLK run state: four `pending_shift` flags
2766 /// (ports 1-2 then the Four Score's 3-4) and the two per-port read cycles.
2767 pub const fn set_controller_run_state(&mut self, pending: [bool; 4], cycles: [u64; 2]) {
2768 self.controllers[0].pending_shift = pending[0];
2769 self.controllers[1].pending_shift = pending[1];
2770 self.controllers34[0].pending_shift = pending[2];
2771 self.controllers34[1].pending_shift = pending[3];
2772 self.port_read_cycle[0] = cycles[0];
2773 self.port_read_cycle[1] = cycles[1];
2774 }
2775
2776 /// Enable/disable the Four Score 4-player adapter. Off by default; while
2777 /// off, `$4016`/`$4017` behave exactly as the standard two controllers
2778 /// (byte-identical reads — determinism + save-states unaffected).
2779 pub const fn set_four_score(&mut self, enabled: bool) {
2780 self.four_score = enabled;
2781 }
2782
2783 /// Whether the Four Score adapter is currently enabled.
2784 #[must_use]
2785 pub const fn four_score(&self) -> bool {
2786 self.four_score
2787 }
2788
2789 // --- Famicom Disk System disk control (delegates to the mapper) ---
2790
2791 /// Number of disk sides in the inserted FDS image (0 for cartridge builds).
2792 #[must_use]
2793 pub fn disk_side_count(&self) -> usize {
2794 self.mapper.disk_side_count()
2795 }
2796
2797 /// The currently inserted FDS disk side, or `None` when ejected (or for a
2798 /// cartridge build).
2799 #[must_use]
2800 pub fn inserted_disk_side(&self) -> Option<usize> {
2801 self.mapper.inserted_disk_side()
2802 }
2803
2804 /// Insert FDS side `i` (`Some`) or eject (`None`). No-op on cartridge builds.
2805 pub fn set_disk_side(&mut self, side: Option<usize>) {
2806 self.mapper.set_disk_side(side);
2807 }
2808
2809 /// Whether the cartridge has a barcode reader (Datach, mapper 157).
2810 #[must_use]
2811 pub fn has_barcode_reader(&self) -> bool {
2812 self.mapper.has_barcode_reader()
2813 }
2814
2815 /// Present a validated barcode to the cartridge's reader; `false` when
2816 /// the cartridge has none.
2817 pub fn scan_barcode(&mut self, code: &rustynes_mappers::Barcode) -> bool {
2818 self.mapper.scan_barcode(code)
2819 }
2820
2821 /// Whether a barcode scan is still being presented.
2822 #[must_use]
2823 pub fn barcode_scan_in_progress(&self) -> bool {
2824 self.mapper.barcode_scan_in_progress()
2825 }
2826
2827 /// Number of selectable NSF songs (0 for cartridge / disk builds).
2828 #[must_use]
2829 pub fn nsf_song_count(&self) -> u8 {
2830 self.mapper.nsf_song_count()
2831 }
2832
2833 /// The currently-selected 0-based NSF song (0 for cartridge / disk builds).
2834 #[must_use]
2835 pub fn nsf_current_song(&self) -> u8 {
2836 self.mapper.nsf_current_song()
2837 }
2838
2839 /// Select a 0-based NSF song. Returns `true` if this is an NSF build (so the
2840 /// caller re-runs the reset that re-enters the driver's `init`).
2841 pub fn nsf_set_song(&mut self, song: u8) -> bool {
2842 self.mapper.nsf_set_song(song)
2843 }
2844
2845 /// Start recording the diagnostic FDS read-stream trace (off by default;
2846 /// observation-only). No-op on cartridge builds.
2847 pub fn enable_fds_trace(&mut self) {
2848 self.mapper.enable_fds_trace();
2849 }
2850
2851 /// Drain the accumulated FDS read-stream trace records (empty for cartridge
2852 /// builds / when tracing was never enabled).
2853 pub fn take_fds_trace(&mut self) -> Vec<rustynes_mappers::FdsTraceRec> {
2854 self.mapper.take_fds_trace()
2855 }
2856
2857 /// Re-serialize the (possibly-modified) FDS disk image to its byte layout
2858 /// for host persistence. Empty for cartridge builds.
2859 #[must_use]
2860 pub fn disk_image_bytes(&self) -> Vec<u8> {
2861 self.mapper.disk_image_bytes()
2862 }
2863
2864 /// Whether the FDS disk image has unsaved writes.
2865 #[must_use]
2866 pub fn disk_is_dirty(&self) -> bool {
2867 self.mapper.disk_is_dirty()
2868 }
2869
2870 /// Clear the FDS disk dirty flag (after the host persists the image).
2871 pub fn clear_disk_dirty(&mut self) {
2872 self.mapper.clear_disk_dirty();
2873 }
2874
2875 /// Mark the inserted FDS disk read-only (`true`) or writable (`false`).
2876 pub fn set_disk_write_protected(&mut self, protected: bool) {
2877 self.mapper.set_disk_write_protected(protected);
2878 }
2879
2880 /// Commit a controller-strobe write to all controllers, resetting the
2881 /// Four Score read sequence + reloading its signature when enabled.
2882 const fn commit_controller_strobe(&mut self, value: u8) {
2883 self.controllers[0].write_strobe(value);
2884 self.controllers[1].write_strobe(value);
2885 // Forward the strobe to any attached overlay device (only the Vaus
2886 // latches on it; the Zapper ignores it). Done unconditionally — the
2887 // standard controllers above are still strobed, so detaching a device
2888 // returns to byte-identical behavior.
2889 if let Some(d) = &mut self.expansion_device[0] {
2890 d.write_strobe(value);
2891 }
2892 if let Some(d) = &mut self.expansion_device[1] {
2893 d.write_strobe(value);
2894 }
2895 if self.four_score {
2896 self.controllers34[0].write_strobe(value);
2897 self.controllers34[1].write_strobe(value);
2898 // Reset the 24-read sequence + reload the adapter signature
2899 // (port 0 = 0x08, port 1 = 0x04, shifted out LSB-first).
2900 self.four_score_idx = [0, 0];
2901 self.four_score_sig = [0x08, 0x04];
2902 // The chain owes nothing immediately after a strobe, so the FIRST
2903 // read serves index 0 rather than advancing past it.
2904 self.four_score_pending = [false, false];
2905 }
2906 }
2907
2908 /// Read the D0 controller bit for `port` (0 = `$4016`, 1 = `$4017`),
2909 /// advancing the shift register. Four Score off → just
2910 /// `controllers[port].read()`; on → the multiplexed 24-read sequence
2911 /// (primary pad → secondary pad → signature → 1s).
2912 /// Does a read of `port` on this cycle continue an unbroken run of reads
2913 /// of the same port? Records this cycle as the port's latest read either
2914 /// way, so callers must invoke it exactly once per read.
2915 const fn port_continues_run(&mut self, port: usize) -> bool {
2916 let last = self.port_read_cycle[port];
2917 let cont = last != u64::MAX && self.cycle == last.wrapping_add(1);
2918 self.port_read_cycle[port] = self.cycle;
2919 cont
2920 }
2921
2922 fn read_port(&mut self, port: usize) -> u8 {
2923 // v1.6.0 Workstream A3 (`TAStudio` lag log): any read of $4016/$4017
2924 // counts as the game polling input this frame. Output-only; gated.
2925 #[cfg(feature = "debug-hooks")]
2926 {
2927 self.controller_polled = true;
2928 }
2929 // A non-standard overlay device takes over the port entirely: it
2930 // returns its own bit-positioned byte (Vaus = bits 3/4, Zapper =
2931 // bits 3/4) instead of the standard D0 shift-register bit. The
2932 // standard controller is still strobed (in `commit_controller_strobe`)
2933 // so detaching the device restores byte-identical behavior.
2934 // A3 (v2.2.3, opt-in): serve the Zapper's light bit from the
2935 // beam-relative model. `read_at_scanline` takes `&self` and the PPU is a
2936 // different field, so these are disjoint borrows. Off by default, so the
2937 // shipped path below is byte-identical.
2938 if self.zapper_temporal_light
2939 && let Some(crate::input_device::InputDevice::Zapper(z)) = &self.expansion_device[port]
2940 {
2941 // `scanline()` is `i16` but is non-negative on every current region
2942 // (visible 0..=239, then post-render / vblank up to the pre-render
2943 // line — 261 NTSC / 311 PAL, NOT -1), so `try_from` always succeeds
2944 // and this resolves to `read_at_scanline`, which already yields
2945 // no-light for the pre-render line (`prerender - y >= HOLD` for every
2946 // visible aim). The `Err` arm is a total-conversion fallback: if a
2947 // future convention ever produced a negative scanline (a -1
2948 // pre-render), the correct answer is "no light yet" —
2949 // `read_before_visible` — rather than the row-0 fold a bare
2950 // `unwrap_or(0)` would give.
2951 return match u16::try_from(self.ppu.scanline()) {
2952 Ok(sl) => z.read_at_scanline(self.ppu.framebuffer(), sl),
2953 Err(_) => z.read_before_visible(),
2954 };
2955 }
2956 if let Some(d) = &mut self.expansion_device[port] {
2957 return d.read();
2958 }
2959 let cont = self.port_continues_run(port);
2960 if !self.four_score || self.controllers[port].strobe {
2961 return self.controllers[port].read(cont);
2962 }
2963 // ADVANCE FIRST, THEN SERVE — the same shape as `Controller::read`,
2964 // and for the same reason. The chain clocks on the rising edge that
2965 // ENDS the previous run, so a contiguous read serves the position it
2966 // already served instead of stepping past it. Advancing after the
2967 // serve, unconditionally, is what let the adapter run ahead of the pads
2968 // feeding it once contiguous reads stopped advancing them.
2969 if self.four_score_pending[port] && !cont && self.four_score_idx[port] < 24 {
2970 if self.four_score_idx[port] >= 16 {
2971 self.four_score_sig[port] = (self.four_score_sig[port] >> 1) | 0x80;
2972 }
2973 self.four_score_idx[port] += 1;
2974 }
2975 self.four_score_pending[port] = true;
2976 let idx = self.four_score_idx[port];
2977 if idx < 8 {
2978 self.controllers[port].read(cont)
2979 } else if idx < 16 {
2980 self.controllers34[port].read(cont)
2981 } else if idx < 24 {
2982 self.four_score_sig[port] & 1
2983 } else {
2984 1
2985 }
2986 }
2987
2988 /// Side-effect-free companion to [`Self::read_port`] (debugger peek).
2989 fn peek_port(&self, port: usize) -> u8 {
2990 // Mirror the temporal-Zapper branch in `read_port` so a debugger peek
2991 // shows the same `$4016`/`$4017` byte the CPU would receive. Without
2992 // this, with `zapper_temporal_light` on, `peek_port` fell through to the
2993 // overlay's frame-granular `peek()` and could disagree with the live
2994 // read. `peek` is non-mutating and all of `scanline()` / `framebuffer()`
2995 // / `read_at_scanline` / `read_before_visible` take `&self`, so this is a
2996 // pure read; it costs `peek_port` its `const` (try_from/match are not
2997 // const here), which nothing relied on. Off by default → byte-identical.
2998 if self.zapper_temporal_light
2999 && let Some(crate::input_device::InputDevice::Zapper(z)) = &self.expansion_device[port]
3000 {
3001 return u16::try_from(self.ppu.scanline()).map_or_else(
3002 |_| z.read_before_visible(),
3003 |sl| z.read_at_scanline(self.ppu.framebuffer(), sl),
3004 );
3005 }
3006 if let Some(d) = &self.expansion_device[port] {
3007 return d.peek();
3008 }
3009 if !self.four_score || self.controllers[port].strobe {
3010 return self.controllers[port].peek();
3011 }
3012 let idx = self.four_score_idx[port];
3013 if idx < 8 {
3014 self.controllers[port].peek()
3015 } else if idx < 16 {
3016 self.controllers34[port].peek()
3017 } else if idx < 24 {
3018 self.four_score_sig[port] & 1
3019 } else {
3020 1
3021 }
3022 }
3023
3024 /// Bus-side bookkeeping snapshot used by `bus_snapshot::encode_bus`.
3025 #[must_use]
3026 pub const fn bus_misc_state(&self) -> crate::bus_snapshot::BusMiscState {
3027 crate::bus_snapshot::BusMiscState {
3028 dma_pending: self.dma_pending,
3029 dma_byte: self.dma_byte,
3030 dma_page: self.dma_page,
3031 dma_halt_addr: self.dma_halt_addr,
3032 open_bus: self.open_bus,
3033 internal_data_bus: self.internal_data_bus,
3034 last_read_addr: self.last_read_addr,
3035 deferred_dma_replay_addr: self.deferred_dma_replay_addr,
3036 in_dmc_dma: self.in_dmc_dma,
3037 controller_write_pending: self.controller_write_pending,
3038 controller_write_value: self.controller_write_value,
3039 four_score: self.four_score,
3040 four_score_idx: self.four_score_idx,
3041 four_score_sig: self.four_score_sig,
3042 // W3-Stage-4 (2026-06-10): the unified-engine OAM state + the
3043 // DMC halt latch. Always present in the ferry struct (zeros when
3044 // the engine feature is off) so the BUS section layout is
3045 // identical across feature builds.
3046 dmc_halt: self.dmc_halt,
3047 dmc_load_write_delayed: self.dmc_load_write_delayed,
3048 overclock_phase: self.overclock_phase,
3049 apu_cycle: self.apu_cycle,
3050 uni_oam_active: self.uni_oam_active,
3051 uni_oam_halt: self.uni_oam_halt,
3052 uni_oam_aligned: self.uni_oam_aligned,
3053 uni_oam_addr: self.uni_oam_addr,
3054 ppu_clock: self.ppu_clock,
3055 }
3056 }
3057
3058 /// Apply a previously-snapshotted bus bookkeeping state.
3059 pub const fn set_bus_misc_state(&mut self, s: crate::bus_snapshot::BusMiscState) {
3060 self.dma_pending = s.dma_pending;
3061 self.dma_byte = s.dma_byte;
3062 self.dma_page = s.dma_page;
3063 self.dma_halt_addr = s.dma_halt_addr;
3064 self.open_bus = s.open_bus;
3065 self.internal_data_bus = s.internal_data_bus;
3066 self.last_read_addr = s.last_read_addr;
3067 self.deferred_dma_replay_addr = s.deferred_dma_replay_addr;
3068 self.in_dmc_dma = s.in_dmc_dma;
3069 self.controller_write_pending = s.controller_write_pending;
3070 self.controller_write_value = s.controller_write_value;
3071 self.four_score = s.four_score;
3072 self.four_score_idx = s.four_score_idx;
3073 self.four_score_sig = s.four_score_sig;
3074 // W3-Stage-4 (2026-06-10): the unified engine's OAM state + the DMC
3075 // halt latch are serialized, replacing the Stage-1 clear-on-restore.
3076 // Snapshots are taken at instruction boundaries where the engine is
3077 // idle, so for every legitimately produced blob these decode to the
3078 // same inactive state the clear imposed -- but a restored blob
3079 // reproduces them EXACTLY instead of by assumption.
3080 self.dmc_halt = s.dmc_halt;
3081 self.dmc_load_write_delayed = s.dmc_load_write_delayed;
3082 // The overclock's stock-rate position. The multiplier itself is
3083 // configuration (re-applied by the host); a phase the current
3084 // multiplier could not have produced is clamped to its last cycle, so
3085 // a stock step still comes due. The cycle length follows the phase.
3086 let last = self.cpu_overclock.saturating_sub(1);
3087 self.overclock_phase = if s.overclock_phase > last {
3088 last
3089 } else {
3090 s.overclock_phase
3091 };
3092 self.cpu_div_effective = overclock_cycle_len(
3093 self.cpu_div_cached,
3094 self.cpu_overclock,
3095 self.overclock_phase,
3096 );
3097 self.apu_cycle = s.apu_cycle;
3098 self.stock_step = true;
3099 self.uni_oam_active = s.uni_oam_active;
3100 self.uni_oam_halt = s.uni_oam_halt;
3101 self.uni_oam_aligned = s.uni_oam_aligned;
3102 self.uni_oam_addr = s.uni_oam_addr;
3103 // Half of the master-clock pair; the other half is
3104 // `Cpu::master_clock` in the CPU section (see `BusMiscState::ppu_clock`).
3105 self.ppu_clock = s.ppu_clock;
3106 }
3107
3108 /// Set the cumulative CPU cycle counter (used by save-state restore).
3109 pub const fn set_cycle(&mut self, cycle: u64) {
3110 self.cycle = cycle;
3111 }
3112
3113 /// Overwrite the 2 KiB CPU RAM.
3114 ///
3115 /// # Errors
3116 ///
3117 /// Returns [`SnapshotError::SectionInvalid`] if `bytes.len() != 2048`.
3118 pub fn set_ram_bytes(&mut self, bytes: &[u8]) -> Result<(), SnapshotError> {
3119 if bytes.len() != self.ram.len() {
3120 return Err(SnapshotError::SectionInvalid {
3121 tag: "BUS ".into(),
3122 reason: format!("ram length {} != {}", bytes.len(), self.ram.len()),
3123 });
3124 }
3125 self.ram.copy_from_slice(bytes);
3126 Ok(())
3127 }
3128
3129 /// Overwrite both controllers' state.
3130 pub const fn set_controllers(&mut self, controllers: [Controller; 2]) {
3131 self.controllers = controllers;
3132 }
3133
3134 /// Overwrite the Four Score players 3 & 4 (save-state restore).
3135 pub const fn set_controllers34(&mut self, controllers: [Controller; 2]) {
3136 self.controllers34 = controllers;
3137 }
3138
3139 /// Write a byte directly into CPU work RAM (`$0000-$1FFF`, mirrored every
3140 /// `$800`). Used by the frontend's raw RAM cheats (GameShark-style),
3141 /// applied caller-side *after* [`crate::Nes::run_frame`] so the core run
3142 /// loop stays pure (the determinism contract is unperturbed for the
3143 /// no-cheat path). No-op for addresses outside system RAM.
3144 pub fn poke_ram(&mut self, addr: u16, value: u8) {
3145 if addr < 0x2000 {
3146 self.ram[(addr & 0x07FF) as usize] = value;
3147 }
3148 }
3149
3150 /// Encode the entire bus + chip state into a `.rns` snapshot.
3151 ///
3152 /// Returns the bytes the caller should persist via
3153 /// `frontend::save_state` (or feed into the rewind ring).
3154 ///
3155 /// The output is bit-deterministic: same `(seed, ROM, input sequence)`
3156 /// produces identical bytes.
3157 #[must_use]
3158 pub fn snapshot(&self, rom_hash_tag: [u8; save_state::ROM_HASH_TAG_LEN]) -> Vec<u8> {
3159 let mut out = Vec::with_capacity(0x4_0000);
3160 self.snapshot_into(&mut out, rom_hash_tag);
3161 out
3162 }
3163
3164 /// v2.8.0 Phase 3 — [`Self::snapshot`] into a caller-owned buffer
3165 /// (cleared first; capacity reused across calls). The per-call
3166 /// allocation of the ~250 KiB blob matters to per-frame consumers
3167 /// (run-ahead, the netplay save-state ring, rewind).
3168 pub fn snapshot_into(
3169 &self,
3170 out: &mut Vec<u8>,
3171 rom_hash_tag: [u8; save_state::ROM_HASH_TAG_LEN],
3172 ) {
3173 self.snapshot_into_with(out, rom_hash_tag, false);
3174 }
3175
3176 /// v2.3.3 — [`Self::snapshot_into`] with the PPU encoded slim (no
3177 /// framebuffer). See `rustynes_ppu::PPU_SNAPSHOT_SLIM_FLAG`.
3178 pub fn snapshot_into_slim(
3179 &self,
3180 out: &mut Vec<u8>,
3181 rom_hash_tag: [u8; save_state::ROM_HASH_TAG_LEN],
3182 ) {
3183 self.snapshot_into_with(out, rom_hash_tag, true);
3184 }
3185
3186 fn snapshot_into_with(
3187 &self,
3188 out: &mut Vec<u8>,
3189 rom_hash_tag: [u8; save_state::ROM_HASH_TAG_LEN],
3190 slim: bool,
3191 ) {
3192 out.clear();
3193 save_state::write_header(out, rom_hash_tag);
3194
3195 // BUS section.
3196 let bus_body = crate::bus_snapshot::encode_bus(self);
3197 save_state::write_section(
3198 out,
3199 save_state::tag::BUS,
3200 crate::bus_snapshot::BUS_SECTION_VERSION,
3201 &bus_body,
3202 );
3203
3204 // CPU is owned by the surrounding `Nes` facade — but the bus is
3205 // the canonical owner of the persistable state, so the public
3206 // `snapshot` lives there. The CPU section is appended by
3207 // `Nes::snapshot` because the CPU isn't reachable from inside
3208 // the bus without violating the dependency graph. We stub
3209 // section emission here; `Nes::snapshot` will re-call this and
3210 // splice the CPU bytes in.
3211
3212 // PPU section.
3213 let ppu_body = if slim {
3214 self.ppu.snapshot_slim()
3215 } else {
3216 self.ppu.snapshot()
3217 };
3218 save_state::write_section(
3219 out,
3220 save_state::tag::PPU,
3221 rustynes_ppu::PPU_SNAPSHOT_VERSION,
3222 &ppu_body,
3223 );
3224
3225 // APU section.
3226 let apu_body = self.apu.snapshot();
3227 save_state::write_section(
3228 out,
3229 save_state::tag::APU,
3230 rustynes_apu::APU_SNAPSHOT_VERSION,
3231 &apu_body,
3232 );
3233
3234 // MAP section (mapper-resident state).
3235 let map_body = self.mapper.save_state();
3236 save_state::write_section(out, save_state::tag::MAP, 1, &map_body);
3237 }
3238
3239 /// Apply a previously snapshotted blob *to the bus and chips*. The CPU
3240 /// is restored separately by [`crate::Nes::restore`].
3241 ///
3242 /// # Errors
3243 ///
3244 /// Returns [`SnapshotError`] for unknown sections, version mismatches,
3245 /// or malformed bodies.
3246 pub fn restore(&mut self, data: &[u8]) -> Result<(), SnapshotError> {
3247 let (header, body_off) = save_state::parse_header(data)?;
3248 let _ = header; // currently informational
3249 let mut saw_bus = false;
3250 let mut saw_ppu = false;
3251 let mut saw_apu = false;
3252 let mut saw_map = false;
3253 for s in save_state::SectionIter::new(&data[body_off..]) {
3254 let s = s?;
3255 match s.tag {
3256 save_state::tag::BUS => {
3257 if s.version != crate::bus_snapshot::BUS_SECTION_VERSION {
3258 return Err(SnapshotError::VersionMismatch {
3259 tag: save_state::tag_string(s.tag),
3260 file_version: s.version,
3261 chip_supports: crate::bus_snapshot::BUS_SECTION_VERSION,
3262 });
3263 }
3264 crate::bus_snapshot::decode_bus(self, s.body)?;
3265 saw_bus = true;
3266 }
3267 save_state::tag::PPU => {
3268 if s.version != rustynes_ppu::PPU_SNAPSHOT_VERSION {
3269 return Err(SnapshotError::VersionMismatch {
3270 tag: save_state::tag_string(s.tag),
3271 file_version: s.version,
3272 chip_supports: rustynes_ppu::PPU_SNAPSHOT_VERSION,
3273 });
3274 }
3275 self.ppu.restore(s.body).map_err(|e: PpuSnapshotError| {
3276 SnapshotError::SectionInvalid {
3277 tag: save_state::tag_string(s.tag),
3278 reason: format!("{e}"),
3279 }
3280 })?;
3281 saw_ppu = true;
3282 }
3283 save_state::tag::APU => {
3284 if s.version != rustynes_apu::APU_SNAPSHOT_VERSION {
3285 return Err(SnapshotError::VersionMismatch {
3286 tag: save_state::tag_string(s.tag),
3287 file_version: s.version,
3288 chip_supports: rustynes_apu::APU_SNAPSHOT_VERSION,
3289 });
3290 }
3291 self.apu.restore(s.body).map_err(|e: ApuSnapshotError| {
3292 SnapshotError::SectionInvalid {
3293 tag: save_state::tag_string(s.tag),
3294 reason: format!("{e}"),
3295 }
3296 })?;
3297 saw_apu = true;
3298 }
3299 save_state::tag::MAP => {
3300 self.mapper.load_state(s.body).map_err(|e: MapperError| {
3301 SnapshotError::SectionInvalid {
3302 tag: save_state::tag_string(s.tag),
3303 reason: format!("{e}"),
3304 }
3305 })?;
3306 saw_map = true;
3307 }
3308 save_state::tag::CPU => {
3309 // Skipped — restored by the surrounding `Nes` facade.
3310 }
3311 _other => {
3312 // Unknown tags are forward-compatible: skip silently
3313 // so cross-version files load when they include
3314 // sections this build doesn't know about (e.g. a
3315 // future "DBG " debugger section).
3316 }
3317 }
3318 }
3319 // BUS is mandatory; chip sections are mandatory too because
3320 // they round-trip the entire emulator state.
3321 if !saw_bus {
3322 return Err(SnapshotError::MissingSection("BUS ".into()));
3323 }
3324 if !saw_ppu {
3325 return Err(SnapshotError::MissingSection("PPU ".into()));
3326 }
3327 if !saw_apu {
3328 return Err(SnapshotError::MissingSection("APU ".into()));
3329 }
3330 if !saw_map {
3331 return Err(SnapshotError::MissingSection("MAP ".into()));
3332 }
3333 // v3.1.0 (PR #594 review): the MMC3's MAP section carries its LIVE
3334 // IRQ revision, which is configuration rather than console state, so
3335 // re-apply the configured override (`None` = the header's). Without
3336 // this a state saved under the override and loaded without it kept
3337 // running the alternate revision while `mmc3_revision_override()`
3338 // reported `None`, and the reverse. A no-op on every other board.
3339 self.mapper
3340 .set_mmc3_revision_override(self.mmc3_revision_override);
3341 // RW-0 fix: under R1, `dmc_driven_externally` is NOT serialized (it is
3342 // build configuration, not emulated state), so after `apu.restore` it
3343 // reverts to the `Apu::new` default (`false`), which STOPS `put_cycle`
3344 // toggling and disables the interleaved DMC DMA service — a latent R1
3345 // save-state correctness bug. Re-apply the R1 drive here exactly as
3346 // `new`/`reset`/`power_cycle` do.
3347 //
3348 // W3-Stage-4 (2026-06-10, the RW-3 follow-through): the APU snapshot
3349 // carries the exact `put_cycle` / `parity_seed` phase, so the boot
3350 // alignment is NOT re-seeded -- that would overwrite the restored
3351 // mid-state parity the counter-collapse end-flip reads at the next
3352 // access point. (Until v2.9.8 a pre-Stage-4 blob without that tail
3353 // was accepted and re-seeded here; ADR 0042 removed that path.)
3354 self.apu.set_dmc_driven_externally(true);
3355 Ok(())
3356 }
3357
3358 const fn ppu_region(&self) -> PpuRegion {
3359 match self.cart.region {
3360 rustynes_mappers::Region::Pal => PpuRegion::Pal,
3361 rustynes_mappers::Region::Dendy => PpuRegion::Dendy,
3362 _ => PpuRegion::Ntsc,
3363 }
3364 }
3365
3366 const fn apu_region(&self) -> ApuRegion {
3367 match self.cart.region {
3368 rustynes_mappers::Region::Pal => ApuRegion::Pal,
3369 rustynes_mappers::Region::Dendy => ApuRegion::Dendy,
3370 _ => ApuRegion::Ntsc,
3371 }
3372 }
3373
3374 /// OAM-DMA source fetch (Session-26 / Sprint 2 iter 4).
3375 ///
3376 /// The 2A03 has three internal address buses (6502, OAM DMA, DMC
3377 /// DMA), but only the 6502 bus asserts the APU/controller chip
3378 /// select. During OAM DMA the 6502 is halted, so its bus is parked
3379 /// at `self.dma_halt_addr` (last CPU read address). The OAM DMA
3380 /// engine drives the EXTERNAL address bus with `src_addr`, but the
3381 /// APU registers' `CHIP_SELECT` is gated on `6502_addr ∈ $4000-$401F`,
3382 /// not on the DMA's source page.
3383 ///
3384 /// Consequence: if the 6502 bus is parked outside `$4000-$401F`
3385 /// and the OAM DMA reads a source address inside that range, the
3386 /// APU/controllers are silent — the read returns the open-bus
3387 /// latch and triggers no register side-effects (no `apu.read_status()`,
3388 /// no controller shift, etc.). The DMC DMA helper already implements
3389 /// the equivalent gate (`dmc_dma_read` lines 1329-1356).
3390 ///
3391 /// `AccuracyCoin` `APU Register Activation` Test 4 (asm:8091-8109)
3392 /// exercises this: `LDA #$40; STA $4014` runs an OAM DMA from page
3393 /// `$40` while CPU code lives in PRG ROM. Without this gate, the
3394 /// DMA's `$4015` read clears the frame-counter IRQ flag, failing
3395 /// the subsequent `LDA $4015 / AND #$40 / BEQ FAIL` check.
3396 ///
3397 /// The Test 5/6 conflict-path semantics (where the 6502 bus IS in
3398 /// `$4000-$401F` because the test uses `JSR $3FFE` + the BRK trick)
3399 /// need additional modelling — deferred. Two components, established by
3400 /// the 2026-06-05 investigation (`docs/audit/`):
3401 /// 1. **Active-window mirror decode.** When the 6502 bus is parked in
3402 /// `$4000-$401F`, an OAM DMA reading page `$40` reads the readable
3403 /// registers (`$4015`/`$4016`/`$4017`) AND their `$20`-byte mirrors:
3404 /// the 2A03 decodes on the low 5 address bits, so `$4020-$40FF` mirror
3405 /// `$4000-$401F` (`$4035` -> `$4015`) with side-effects (`$4015` clears
3406 /// the frame IRQ flag; `$4016`/`$4017` advance the controller shift).
3407 /// The fix is to mask `src` to `0x4000 | (src & 0x1F)` here when active.
3408 /// 2. **Upstream coupling (the actual blocker).** This is NOT independently
3409 /// reachable: Test 6's OAM-copy is all-zeros in this emulator because the
3410 /// page-`$40` register-read OAM DMA does not fire as the test intends — it
3411 /// depends on Test 5's `[DMC DMA! Overwrite data bus with $40]` trick
3412 /// landing cycle-exactly so `STA $4014` reads `$40` and the 6502 bus is
3413 /// parked in `$40xx` during the DMA. That is the deferred DMC-DMA-timing /
3414 /// data-bus axis. So component 1 is correct hardware behavior but inert
3415 /// until that axis lands — do NOT add it speculatively (it touches the
3416 /// default build and cannot be verified against the test in isolation).
3417 fn raw_oam_dma_read(&mut self, src_addr: u16) -> u8 {
3418 if (self.dma_halt_addr & 0xFFE0) != 0x4000 && (src_addr & 0xFFE0) == 0x4000 {
3419 // APU/controllers inactive: return the floating-bus latch
3420 // without firing any register side-effects. The latch
3421 // itself is NOT updated — DMA reads of the inactive
3422 // register window don't drive the external data bus
3423 // (the chip is silent).
3424 return self.open_bus;
3425 }
3426 // W3-Stage-4 (`mc-r1-oam-dma-reg-window`): the ACTIVE-window arm —
3427 // the 6502 bus is parked in `$4000-$401F`, so the APU/controller
3428 // chip select is asserted for EVERY OAM-DMA source read and the
3429 // readable registers decode at `$4000 | (src & $1F)` (the `$20`-byte
3430 // mirrors AccuracyCoin `APU Register Activation` Tests 5-7 bracket).
3431 if (self.dma_halt_addr & 0xFFE0) == 0x4000 {
3432 return self.oam_dma_read_reg_active(src_addr);
3433 }
3434 self.raw_cpu_read(src_addr)
3435 }
3436
3437 /// W3-Stage-4 (`mc-r1-oam-dma-reg-window`): one OAM-DMA source read with
3438 /// the 2A03 register window ACTIVE (the halted 6502 address bus is parked
3439 /// in `$4000-$401F`, e.g. the `AccuracyCoin` `APU Register Activation`
3440 /// Test 5/7 `JSR $3FFE` + BRK choreography parks it at `$4001`).
3441 ///
3442 /// Direct port of the `TriCNES` `Fetch` addressBus-window block
3443 /// (`Emulator.cs:9252-9311`):
3444 ///
3445 /// * The normal external decode of `src_addr` runs first (RAM / PPU /
3446 /// cartridge / floating), tracking whether the region DRIVES the data
3447 /// pins (`dataPinsAreNotFloating`).
3448 /// * `Reg == $15` (`$4015` mirror): returns the APU status on the
3449 /// INTERNAL bus — the frame-IRQ flag is cleared (the side effect Test 4
3450 /// brackets from the inactive side), bit 5 comes from the internal-bus
3451 /// latch (Test 7's `$24` = triangle + bit 5 of the previous page-2
3452 /// fetch), and the data bus / open-bus latch is NOT driven ("reading
3453 /// from `$4015` can not affect the databus"). The status value still
3454 /// reaches OAM because the DMA PUT half writes (and drives the bus
3455 /// with) the byte — see [`Self::oam_dma_put`].
3456 /// * `Reg == $16`/`$17` (`$4016`/`$4017` mirrors): the controller shift
3457 /// register is clocked; the value is `bit | (open_bus & $E0)` when the
3458 /// source region floats (Test 5's page-`$50` chain: `$41`, `$40`, then
3459 /// `$01`/`$00` after the `$4015` value decays bit 6 off the bus), but
3460 /// when the source DRIVES the pins the external byte wins the bus
3461 /// conflict and the controller bits are invisible (Test 7's page-`$02`
3462 /// variant — "it does not appear to have read the controllers...
3463 /// but they are still getting clocked").
3464 /// * Everything else: the external fetch value (floating sources return
3465 /// the open-bus latch untouched).
3466 ///
3467 /// The end of the Test-5 chain leaves `$00` on the bus, so the resumed
3468 /// opcode fetch at `$4001` (open bus) executes BRK — the value path is
3469 /// load-bearing for the test's own control flow: any divergence here is
3470 /// what wedged the Stage-3 attempt (runaway execution instead of BRK).
3471 fn oam_dma_read_reg_active(&mut self, src_addr: u16) -> u8 {
3472 // Does the external decode of `src_addr` drive the data pins?
3473 // (TriCNES `dataPinsAreNotFloating` after the normal decode.)
3474 let drives = match src_addr {
3475 // RAM and the PPU registers always drive (write-only PPU regs
3476 // return the PPU-bus latch — still driven).
3477 0x0000..=0x3FFF => true,
3478 // The `$4000-$401F` window itself: the APU drives the INTERNAL
3479 // bus only; the external pins float. (The register overlay
3480 // below is the single decode — skip the external fetch so the
3481 // readable registers don't double-fire.)
3482 0x4000..=0x401F => false,
3483 // Cartridge space: mapper-dependent.
3484 _ => !self.mapper.cpu_read_unmapped(src_addr),
3485 };
3486 let external = if (src_addr & 0xFFE0) == 0x4000 {
3487 self.last_read_addr = src_addr;
3488 self.open_bus
3489 } else {
3490 // Normal external fetch (side effects included — a PPU-register
3491 // source behaves exactly as TriCNES's normal decode does).
3492 // Floating sources early-return the open-bus latch untouched.
3493 self.raw_cpu_read(src_addr)
3494 };
3495 match src_addr & 0x1F {
3496 0x15 => {
3497 // `$4015` mirror: internal-bus read, external bus untouched.
3498 // Mirrors the normal-CPU `$4015` composition in
3499 // `raw_cpu_read` (status bits + internal-bus bit 5).
3500 let status = self.apu.read_status();
3501 (status & 0xDF) | (self.internal_data_bus & 0x20)
3502 }
3503 reg @ (0x16 | 0x17) => {
3504 let port = usize::from(reg - 0x16);
3505 let bit = self.read_port(port);
3506 if drives {
3507 // Bus conflict: the externally-driven byte wins; the
3508 // controller was still clocked (`read_port` above).
3509 external
3510 } else {
3511 let v = (self.open_bus & 0xE0) | bit;
3512 self.open_bus = v;
3513 v
3514 }
3515 }
3516 _ => external,
3517 }
3518 }
3519
3520 /// OAM-DMA PUT half: write the latched byte to OAM.
3521 ///
3522 /// W3-Stage-4 (`mc-r1-oam-dma-reg-window`): when the halted 6502 bus is
3523 /// parked in `$4000-$401F`, the put (a `$2004` write) DRIVES the external
3524 /// data bus with the byte — `TriCNES` `OAMDMA_Put` ->
3525 /// `Store(OAM_InternalBus, 0x2004)`, where every `Store` puts the value
3526 /// on `dataBus`. This is how the `$4015`-mirror value (which cannot drive
3527 /// the bus on its read) reaches the open-bus latch for the NEXT mirror
3528 /// read's `& $E0` merge, and how the Test-5 chain decays to `$00` so the
3529 /// resumed `$4001` fetch executes BRK. On real silicon every OAM put
3530 /// drives the bus; the model is deliberately scoped to the parked-window
3531 /// case so all other OAM DMAs stay byte-identical to the floor.
3532 fn oam_dma_put(&mut self) {
3533 self.ppu.oam_dma_write(self.dma_byte);
3534 if (self.dma_halt_addr & 0xFFE0) == 0x4000 {
3535 self.open_bus = self.dma_byte;
3536 }
3537 }
3538
3539 /// Session-21: set the bus-access tracker for an upcoming DMA cycle.
3540 /// `trace_end_cycle` consumes this when it pushes the record.
3541 /// No-op (no field even exists) when the trace feature is disabled.
3542 #[cfg(feature = "irq-timing-trace")]
3543 const fn set_trace_dma_access(&mut self, access: BusAccess, addr: u16, data: u8) {
3544 self.trace_bus_access = access;
3545 self.trace_bus_addr = addr;
3546 self.trace_bus_data = data;
3547 }
3548
3549 const fn capture_deferred_dma_replay(&mut self) {
3550 self.deferred_dma_replay_addr = match self.open_bus {
3551 0x02 => 0x2002,
3552 0x07 => 0x2007,
3553 0x15 => 0x4015,
3554 0x16 => 0x4016,
3555 0x17 => 0x4017,
3556 _ => 0,
3557 };
3558 }
3559
3560 /// Re-execute the side-effect of the most recent CPU read for the
3561 /// 2A03 DMC-DMA readout bug. Replays side effects of reads from
3562 /// `$2002`, `$2007`, `$4015`, `$4016` and `$4017`. Per `AccuracyCoin`
3563 /// "APU Registers and DMA tests" — sub-tests check that the DMC
3564 /// DMA halt cycles re-trigger the cached read's side effects on
3565 /// real silicon.
3566 fn replay_dma_noop_read(&mut self, addr: u16) {
3567 if matches!(self.apu_region(), ApuRegion::Pal) {
3568 return;
3569 }
3570 match addr {
3571 0x2002 => {
3572 let mut adapter = PpuBusAdapter {
3573 mapper: self.mapper.as_mut(),
3574 nt_override: self.nt_mirroring_override,
3575 snoop_reads: self.ppu_read_snoop,
3576 sub_dot: 2,
3577 };
3578 let _ = self.ppu.cpu_read_register(2, &mut adapter);
3579 }
3580 0x2007 => {
3581 let mut adapter = PpuBusAdapter {
3582 mapper: self.mapper.as_mut(),
3583 nt_override: self.nt_mirroring_override,
3584 snoop_reads: self.ppu_read_snoop,
3585 // CPU register replay (e.g. $2007 read-bug): treated as
3586 // M2-high (sub_dot 2) since the 6502 drives its bus
3587 // during φ2.
3588 sub_dot: 2,
3589 };
3590 let _ = self.ppu.cpu_read_register(7, &mut adapter);
3591 }
3592 0x4015 => {
3593 let _ = self.apu.read_status();
3594 self.apu.clear_frame_irq_immediate_for_dma();
3595 }
3596 0x4016 => {
3597 let cont = self.port_continues_run(0);
3598 let _ = self.controllers[0].read(cont);
3599 }
3600 0x4017 => {
3601 let cont = self.port_continues_run(1);
3602 let _ = self.controllers[1].read(cont);
3603 }
3604 _ => {}
3605 }
3606 }
3607
3608 /// Read the DMC sample byte and model the 2A03 register-conflict path
3609 /// where 6502 core address bits 15..=5 remain from the halted CPU read
3610 /// while DMA supplies address bits 4..=0.
3611 fn dmc_dma_read(&mut self, addr: u16, halted_addr: u16) -> u8 {
3612 let sample = self.raw_cpu_read(addr);
3613 if matches!(self.apu_region(), ApuRegion::Pal) || (halted_addr & 0xFFE0) != 0x4000 {
3614 return sample;
3615 }
3616
3617 let conflict_addr = 0x4000 | (addr & 0x001F);
3618 match conflict_addr {
3619 0x4015 => {
3620 let _ = self.apu.read_status();
3621 sample
3622 }
3623 0x4016 => {
3624 // Keep the DMC-conflict $4016 composition consistent with the
3625 // normal controller read (line ~3890): D2 carries the Famicom
3626 // built-in microphone. Default-off (mic released) leaves `mic`
3627 // = 0, so the returned byte is byte-identical to prior releases.
3628 let mic = u8::from(self.famicom_mic) << 2;
3629 let cont = self.port_continues_run(0);
3630 let v = (sample & 0xE0) | self.controllers[0].read(cont) | mic;
3631 self.open_bus = v;
3632 v
3633 }
3634 0x4017 => {
3635 let cont = self.port_continues_run(1);
3636 let v = (sample & 0xE0) | self.controllers[1].read(cont);
3637 self.open_bus = v;
3638 v
3639 }
3640 _ => sample,
3641 }
3642 }
3643
3644 /// W3-Stage-1 (`mc-r1-dma-unified`): clear the unified engine's transient
3645 /// OAM-DMA state (reset / power-cycle / snapshot-restore).
3646 const fn unified_dma_clear(&mut self) {
3647 self.uni_oam_active = false;
3648 self.uni_oam_halt = false;
3649 self.uni_oam_aligned = false;
3650 self.uni_oam_addr = 0;
3651 }
3652
3653 /// W3-Stage-1 (`mc-r1-dma-unified`): ONE cycle of the unified DMC/OAM DMA
3654 /// engine — a direct port of the `TriCNES` `_6502` per-cycle DMA dispatch
3655 /// table (the instrumented harness's `Emulator.cs` ~4233-4357; out of the
3656 /// repository since v3.0.1, at `~/reference-oracles/TriCNES-rustynes-harness`), the SINGLE driver that standalone DMC,
3657 /// standalone OAM, and the DMC-during-OAM overlap all ride — AT FLOOR
3658 /// PARITY for this stage (the structural-equivalence proof; Stage 2 flips
3659 /// the one engine to the breakthrough parity).
3660 ///
3661 /// The "floor" functions named below (`dmc_dma_step_impl`,
3662 /// `oam_dma_step`) were the per-engine drivers this engine replaced. They
3663 /// were deprecated at v2.7.5 and removed at v2.9.8 (ADR 0042); git history
3664 /// holds them.
3665 ///
3666 /// Floor-parity mapping (the structural truth Stage 2 collapses): the
3667 /// floor's two drivers run on OPPOSITE halves of the shared cycle counter
3668 /// (`put_cycle == (self.cycle & 1 == 0)` at the access point):
3669 ///
3670 /// * the DMC engine's GET half is `!put_cycle` (ODD bus cycles) — the
3671 /// emergent `dmc_dma_step_impl` span (halt latched on entry, cleared at
3672 /// the end of the first odd cycle, GET on the next odd) is preserved
3673 /// exactly: entry-on-even = span 4, entry-on-odd = span 3;
3674 /// * the OAM engine's READ half is `put_cycle` (EVEN bus cycles) — the
3675 /// floor's `oam_dma_step` latches 514 (halt + align + 512) when its
3676 /// first serviced cycle is even (`self.cycle & 1 == 0`) and its reads
3677 /// always land on even cycles; the emergent `uni_oam_halt` (`TriCNES`
3678 /// `OAMDMA_Halt`, set only when the first serviced cycle is the read
3679 /// half) reproduces the same 514/513 split with no owed-cycle counter.
3680 ///
3681 /// Each engine's halt clears at the end of ITS OWN get half — `TriCNES`
3682 /// "both halt cycles get cleared after a get cycle", split across the
3683 /// floor's two parities (Stage 2 merges them onto one). The post-GET
3684 /// realign is EMERGENT: a DMC GET stalls OAM for the slot AND forces
3685 /// `uni_oam_aligned = false` (`TriCNES` `DMCDMA_Get` ->
3686 /// `OAMDMA_Aligned = false`), so the in-flight byte is re-read.
3687 ///
3688 /// ONE bus slot per cycle. When a halted DMC overlaps an advancing OAM
3689 /// cycle, the held CPU read's side-effect replay still fires alongside —
3690 /// the lockstep `service_dmc_dma_during_oam` noop-body model (the in-tree
3691 /// overlap spec that passes the whole abort cluster on the default build).
3692 #[allow(clippy::too_many_lines)] // the cfg-split floor + merged dispatches
3693 fn unified_dma_cycle_impl(&mut self, halted_addr: u16) {
3694 // Cycle-half label at the access point (post `cpu_clock`, the APU
3695 // counter has flipped): even bus cycle == `put_cycle` at floor parity.
3696 // W3-Stage-2 (`mc-r1-dma-unified-collapse`): under the put_cycle
3697 // END-flip (the counter-collapse breakthrough parity) the access-point
3698 // read is the references' in-cycle `APU_PutCycle` label DIRECTLY —
3699 // TriCNES also flips at end-of-cycle — so the dispatch runs the single
3700 // TriCNES labeling: `get = !APU_PutCycle`. The floor's split halves
3701 // (DMC GET = odd / OAM READ = even) merge onto this one label.
3702 let get = !self.apu.put_cycle();
3703
3704 // The two activation-time roles, derived per parity model:
3705 // * `oam_halt_on_first` — TriCNES `FirstCycleOfOAMDMA`: halt when the
3706 // first serviced cycle lands on the OAM READ half (floor: even; the
3707 // merged labeling: the GET half). Half-swap x parity-flip = the SAME
3708 // absolute cycles, so standalone OAM timing is invariant.
3709 // * `dmc_noop_half` — the half a LOAD may not ENTER on (the span-3
3710 // load-get-entry rule: a load enters on its get half).
3711 let (oam_halt_on_first, dmc_noop_half) = (get, !get);
3712
3713 // --- OAM activation (TriCNES `$4014` -> FirstCycleOfOAMDMA) ---
3714 // The first serviced cycle after the `$4014` write latches the page +
3715 // the parked CPU address; `uni_oam_halt` is set only when this first
3716 // cycle lands on the OAM read half (floor: even -> the 514 case).
3717 // Latching here, regardless of any in-flight DMC, natively absorbs the
3718 // Stage-0 `$4014`-write-to-first-OAM-cycle gap (lockstep `drain_dma`
3719 // latches OAM BEFORE its DMC-pending check).
3720 if let Some(page) = self.dma_pending.take() {
3721 self.dma_page = page;
3722 self.uni_oam_addr = 0;
3723 self.uni_oam_aligned = false;
3724 self.uni_oam_active = true;
3725 self.uni_oam_halt = oam_halt_on_first;
3726 self.dma_halt_addr = halted_addr;
3727 }
3728
3729 // --- DMC activation (the floor `dmc_dma_step_impl` first-cycle latch)
3730 // A LOAD may not ENTER on the DMC noop half: the floor's
3731 // `dmc_dma_defer_load_entry` while-gate defers exactly the entries
3732 // whose access-point parity is the noop half, so a load enters on its
3733 // get half = span 3 (`mc-r1-dmc-load-get-entry`). The same defer is
3734 // re-derived here for cycles the loop runs anyway because OAM is
3735 // active.
3736 // W3-Stage-3 (`mc-r1-dmc-delayed-4015`): a pending DMC whose APPLIED
3737 // status is false may not ACTIVATE either (the loop can still be
3738 // running for an active OAM; TriCNES's stale `DoDMCDMA` similarly
3739 // never re-enters the halt-latch path — `DMCDMA_Halt` was latched at
3740 // the original activation).
3741 let dmc_serviceable = self.apu.dmc_dma_serviceable();
3742 if self.apu.dmc_dma_pending() && dmc_serviceable && !self.in_dmc_dma {
3743 // A load refused by a write enters here regardless of the half.
3744 let defer_load =
3745 self.apu.dmc_dma_is_load() && dmc_noop_half && !self.dmc_load_write_delayed;
3746 if !defer_load {
3747 self.in_dmc_dma = true;
3748 self.dmc_halt = true;
3749 self.dmc_load_write_delayed = false;
3750 self.capture_deferred_dma_replay();
3751 }
3752 }
3753
3754 // --- Dispatch: ONE bus slot per cycle (floor parity: split halves) ---
3755
3756 // --- Dispatch: ONE bus slot per cycle (W3-Stage-2: the references'
3757 // single get/put labeling — the literal TriCNES `_6502` table) ---
3758 if get {
3759 // GET half: DMC GET (priority) > OAM READ > halted reads.
3760 if self.in_dmc_dma && !self.dmc_halt {
3761 // THE DMC GET: owns the bus slot (with the `$4000` open-bus
3762 // conflict the DMA cluster brackets); a sharing OAM is STALLED
3763 // for the slot AND loses alignment (TriCNES `DMCDMA_Get` ->
3764 // `OAMDMA_Aligned = false`, the emergent post-GET realign).
3765 let addr = self.apu.dmc_dma_addr();
3766 let byte = self.dmc_dma_read(addr, halted_addr);
3767 #[cfg(feature = "irq-timing-trace")]
3768 self.set_trace_dma_access(BusAccess::DmaRead, addr, byte);
3769 self.apu.complete_dmc_dma(byte);
3770 self.in_dmc_dma = false;
3771 if self.uni_oam_active {
3772 self.uni_oam_aligned = false;
3773 }
3774 } else if self.uni_oam_active && !self.uni_oam_halt {
3775 // A halted DMC shares this OAM-READ cycle: on `Rp2A03G` the held
3776 // CPU read's side-effect replay fires first (lockstep noop-body
3777 // order: `replay_dma_noop_read` THEN the OAM slot). This extra
3778 // parked-address re-read — a *halted* DMC squeezing a side-effect
3779 // into an OAM-owned read cycle — is v2.1.7's "unexpected DMA"
3780 // extra read, and it is revision-gated: `Rp2A03G` (default)
3781 // performs it, `Rp2A03H` OMITS it (opt-in later-die model —
3782 // unverified direction; see ADR 0033). Suppression is
3783 // deterministic and cannot desync the transfer:
3784 // `replay_dma_noop_read` only re-triggers a *register's*
3785 // side-effect (a `$2007` buffer advance / `$4016`-`$4017` shift /
3786 // `$4015` IRQ-clear); it ticks no time and advances no DMA
3787 // counter, so the OAM/DMC data path and cycle length are
3788 // identical on both arms.
3789 //
3790 // HONEST RESIDUAL (ADR 0033): on this ported engine the branch
3791 // FIRES (measured ~75× in a synthetic DMC+OAM+`$2007`-loop probe)
3792 // but `replay_dma_noop_read(halted_addr)` is a no-op every time,
3793 // because `halted_addr` during a DMC+OAM overlap is always the
3794 // post-`$4014` *instruction fetch* in PRG (OAM DMA drains on the
3795 // next opcode read, not on a register operand read), never a
3796 // `$2002/$2007/$4015/$4016/$4017` address. So `Rp2A03G` and
3797 // `Rp2A03H` are, in practice, byte-identical on every public
3798 // oracle and every constructible scenario — the die-revision
3799 // extra read is unobservable here, not merely unverified. The
3800 // gate is kept at its mechanism-correct location so it becomes
3801 // live immediately if the parked-address model ever exposes a
3802 // register during the overlap; it never perturbs the default
3803 // (`Rp2A03G`) path.
3804 if self.in_dmc_dma && self.cpu_2a03_revision.has_unexpected_dma_extra_read() {
3805 self.replay_dma_noop_read(halted_addr);
3806 }
3807 // OAM GET: the OAM engine owns the bus slot.
3808 let src = (u16::from(self.dma_page) << 8) | self.uni_oam_addr;
3809 self.dma_byte = self.raw_oam_dma_read(src);
3810 self.uni_oam_aligned = true;
3811 #[cfg(feature = "irq-timing-trace")]
3812 self.set_trace_dma_access(BusAccess::DmaRead, src, self.dma_byte);
3813 } else if self.in_dmc_dma {
3814 // DMC halted get: re-read the parked CPU address (TriCNES
3815 // `Fetch(addressBus)`). Covers the both-halted shared cycle
3816 // too (ONE re-read — TriCNES `DMCDMA_Halted`).
3817 self.replay_dma_noop_read(halted_addr);
3818 #[cfg(feature = "irq-timing-trace")]
3819 self.set_trace_dma_access(BusAccess::DmaRead, halted_addr, self.open_bus);
3820 } else {
3821 // OAM halt cycle alone: the parked address stays on the bus
3822 // (the floor `oam_dma_step` halt branch — no side-effect
3823 // replay).
3824 #[cfg(feature = "irq-timing-trace")]
3825 self.set_trace_dma_access(BusAccess::DmaRead, self.dma_halt_addr, self.open_bus);
3826 }
3827 // TriCNES: BOTH halt cycles get cleared after a get cycle.
3828 self.dmc_halt = false;
3829 self.uni_oam_halt = false;
3830 } else {
3831 // PUT half: OAM WRITE/align; a waiting/halted DMC replays the held
3832 // CPU read's side-effect alongside (TriCNES `DMCDMA_Put` /
3833 // `DMCDMA_Halted` — both `Fetch(addressBus)`).
3834 if self.in_dmc_dma {
3835 self.replay_dma_noop_read(halted_addr);
3836 #[cfg(feature = "irq-timing-trace")]
3837 self.set_trace_dma_access(BusAccess::DmaRead, halted_addr, self.open_bus);
3838 }
3839 if self.uni_oam_active && !self.uni_oam_halt {
3840 if self.uni_oam_aligned {
3841 // OAM PUT: write the latched byte to OAM ($2004).
3842 // `uni_oam_aligned` stays set through the transfer
3843 // (TriCNES: only `DMCDMA_Get` and completion clear it).
3844 self.oam_dma_put();
3845 #[cfg(feature = "irq-timing-trace")]
3846 self.set_trace_dma_access(BusAccess::DmaWrite, 0x2004, self.dma_byte);
3847 self.uni_oam_addr += 1;
3848 if self.uni_oam_addr == 256 {
3849 // The DMA completes on the 256th write.
3850 self.uni_oam_active = false;
3851 self.uni_oam_aligned = false;
3852 }
3853 } else {
3854 // OAM alignment dummy: the parked address stays on the
3855 // bus (the floor `oam_dma_step` align branch — no
3856 // side-effect replay).
3857 #[cfg(feature = "irq-timing-trace")]
3858 if !self.in_dmc_dma {
3859 self.set_trace_dma_access(
3860 BusAccess::DmaRead,
3861 self.dma_halt_addr,
3862 self.open_bus,
3863 );
3864 }
3865 }
3866 }
3867 // (An OAM halt can never land on the PUT half under the merged
3868 // labeling — `uni_oam_halt` is set only on a GET first cycle and
3869 // clears at the end of that same GET half.)
3870 }
3871 }
3872
3873 /// Raw CPU read that does **not** advance time — used by the OAM DMA
3874 /// engine and DMC DMA fetches. Time is advanced by the CPU's
3875 /// surrounding `start_cycle` / `end_cycle`.
3876 pub(crate) fn raw_cpu_read(&mut self, addr: u16) -> u8 {
3877 // $4015 special case: reading from the APU status port reads
3878 // 2A03 internal state but does NOT drive the data bus (per
3879 // nesdev "Open bus behavior" + AccuracyCoin `CPU Behavior ::
3880 // Open Bus` Test 7). The CPU still receives the APU status,
3881 // but the open-bus latch stays at its prior value, so a
3882 // subsequent open-bus-region read returns the *previous*
3883 // floating-bus value rather than the APU status.
3884 if addr == 0x4015 {
3885 // $4015 read returns the APU status (internal silicon
3886 // state) and does NOT drive the external data bus, so
3887 // `self.open_bus` stays at its prior value (per nesdev
3888 // "Open bus behavior" + AccuracyCoin `CPU Behavior ::
3889 // Open Bus` Test 7).
3890 //
3891 // Bit 5 of $4015 is documented as open-bus on silicon.
3892 // With the Phase 1a internal-vs-external bus split, we
3893 // expose this from the INTERNAL data bus (CPU-only, NOT
3894 // polluted by DMC DMA fetches). This satisfies BOTH:
3895 // * Open Bus Test 9 — bit 5 returns the bus latch value
3896 // * Internal Data Bus Test 2 — DMC DMA does NOT change
3897 // bit 5 because DMC drives only the external bus.
3898 //
3899 // The pre-2026-05-23 conflated `open_bus` model could
3900 // not honour both tests simultaneously: empirically (per
3901 // CLAUDE.md Phase D3 audit), OR-ing `open_bus & 0x20`
3902 // into the read flipped Test 9 PASS but tripped Test 2
3903 // to FAIL — net-zero swap. With the internal-bus
3904 // separation, the trade-off is resolved.
3905 let status = self.apu.read_status();
3906 let v = (status & 0xDF) | (self.internal_data_bus & 0x20);
3907 self.last_read_addr = addr;
3908 return v;
3909 }
3910 let v = match addr {
3911 0x0000..=0x1FFF => self.ram[(addr & 0x07FF) as usize],
3912 0x2000..=0x3FFF => self.ppu_register_read(addr),
3913 0x4000..=0x4014 | 0x4018..=0x401F => self.open_bus,
3914 0x4015 => unreachable!("handled above"),
3915 // Controllers drive D0 (and D1 on Famicom expansion port,
3916 // unused here). Bits 5-7 are open bus — the bus latch's
3917 // upper 3 bits show through. Bit 4 is the secondary
3918 // controller D1 (also open bus on stock NES). Per nesdev
3919 // "Standard controller" + AccuracyCoin `CPU Behavior ::
3920 // Open Bus` Test 6.
3921 0x4016 => {
3922 let mic = u8::from(self.famicom_mic) << 2;
3923 let base = (self.open_bus & 0xE0) | self.read_port(0) | mic;
3924 self.vs_overlay_4016(base)
3925 }
3926 0x4017 => {
3927 let base = (self.open_bus & 0xE0) | self.read_port(1);
3928 self.vs_overlay_4017(base)
3929 }
3930 0x4020..=0xFFFF => {
3931 // `$8000-$FFFF` asks only a board that can leave it undriven
3932 // (`prg_may_unmap`, v3.2.0): PRG-ROM fetches are the hottest
3933 // reads, and almost every board always drives them. A v3.2.0
3934 // import skipped the question above `$8000` for EVERY board,
3935 // which read ROM where 228 / 235 float the bus
3936 // (`boards_that_unmap_prg_rom_read_open_bus_above_8000`).
3937 debug_assert!(
3938 addr < 0x8000 || self.prg_may_unmap || !self.mapper.cpu_read_unmapped(addr),
3939 "mapper unmaps ${addr:04X} but does not declare may_unmap_prg_rom"
3940 );
3941 if (addr < 0x8000 || self.prg_may_unmap) && self.mapper.cpu_read_unmapped(addr) {
3942 // Unmapped read: nothing drives the bus, so the CPU sees
3943 // the floating-latch value (nesdev "Open bus behavior":
3944 // "all it sees on its data inputs is whatever was left to
3945 // float"). It falls through like the undecoded
3946 // `$4000-$401F` arm above: `open_bus` is rewritten with the
3947 // value it already holds, and -- the point -- the CPU's
3948 // internal bus latches it, so a following `$4015` read's
3949 // bit 5 comes from THIS cycle ("the last cycle that did
3950 // not read $4015", nesdev APU). Until v2.9.2 this arm
3951 // returned early and skipped that update, which is visible
3952 // only after something has moved the external bus alone --
3953 // a DMC DMA fetch, or an OAM-DMA put with the 6502 bus
3954 // parked in `$4000-$401F` (core audit v2.9.2 AUD-03).
3955 // v2.9.6: a board whose register latches on reads (GTROM)
3956 // sees the value that floated.
3957 self.mapper.notify_floating_read(addr, self.open_bus);
3958 self.open_bus
3959 } else {
3960 // The Game Genie physically substitutes the byte on the
3961 // cartridge bus, so the (possibly substituted) value is
3962 // what the CPU sees AND what latches onto `open_bus` below.
3963 let raw = self.mapper.cpu_read(addr);
3964 // Register-window reads may drive only some data bits; the
3965 // rest keep the floating latch (v2.7.2, core audit §4.5).
3966 // Limited to `$4020-$5FFF`, so PRG fetches pay nothing.
3967 let raw = if addr < 0x6000 {
3968 let driven = self.mapper.cpu_read_driven_mask(addr);
3969 (self.open_bus & !driven) | (raw & driven)
3970 } else {
3971 raw
3972 };
3973 self.apply_genie(addr, raw)
3974 }
3975 }
3976 };
3977 self.last_read_addr = addr;
3978 self.open_bus = v;
3979 // Mirror the read onto the internal data bus, but ONLY when
3980 // this is a CPU-initiated access. DMC DMA fetches drive
3981 // only the EXTERNAL (`open_bus`) bus per nesdev's two-bus
3982 // 2A03 model and per AccuracyCoin's `CPU Behavior 2 ::
3983 // Internal Data Bus` Test 2 ("This DMC DMA does not update
3984 // the external data bus. Only the internal one." — the
3985 // upstream comment treats "internal" as the OPPOSITE of
3986 // what we call internal here; per the test sequence the
3987 // INTERNAL_data_bus is what `$4015` bit-5 returns, and DMC
3988 // DMA must NOT pollute it). The `in_dmc_dma` guard is set
3989 // by `service_dmc_dma` before invoking `dmc_dma_read` →
3990 // `raw_cpu_read`; we skip the internal-bus mirror in that
3991 // path so the internal latch retains its prior CPU-driven
3992 // value across DMC halts. Phase 1 of `linked-puzzling-sutherland`.
3993 if !self.in_dmc_dma {
3994 self.internal_data_bus = v;
3995 }
3996 v
3997 }
3998
3999 /// PPU register read with side effects.
4000 fn ppu_register_read(&mut self, addr: u16) -> u8 {
4001 let reg = (addr & 7) as u8;
4002 let mut adapter = PpuBusAdapter {
4003 mapper: self.mapper.as_mut(),
4004 nt_override: self.nt_mirroring_override,
4005 snoop_reads: self.ppu_read_snoop,
4006 // CPU bus access happens during φ2 → sub_dot 2 (M2-high).
4007 sub_dot: 2,
4008 };
4009 self.ppu.cpu_read_register(reg, &mut adapter)
4010 }
4011
4012 /// PPU register write with side effects.
4013 fn ppu_register_write(&mut self, addr: u16, value: u8) {
4014 // MMC5 decodes `$2000` / `$2001` itself (8x16 mode, render enables);
4015 // it sees the undecoded address, so a mirror write is not snooped.
4016 self.mapper.notify_ppu_register_write(addr, value);
4017 let reg = (addr & 7) as u8;
4018 let mut adapter = PpuBusAdapter {
4019 mapper: self.mapper.as_mut(),
4020 nt_override: self.nt_mirroring_override,
4021 snoop_reads: self.ppu_read_snoop,
4022 // CPU bus access happens during φ2 → sub_dot 2 (M2-high).
4023 sub_dot: 2,
4024 };
4025 self.ppu.cpu_write_register(reg, value, &mut adapter);
4026 }
4027}
4028
4029/// v1.1.0 beta.1 (T-110-B4) — translate a `$2000-$3EFF` PPU address to a
4030/// CIRAM offset under an explicit mirroring (the per-game override path),
4031/// mirroring the `Mapper::nametable_address` default impl.
4032#[allow(clippy::cast_possible_truncation)] // physical_bank is always 0 or 1.
4033const fn override_nt_addr(m: rustynes_mappers::Mirroring, addr: u16) -> u16 {
4034 const NT: u16 = 0x0400;
4035 let table = ((addr.wrapping_sub(0x2000)) / NT) & 0x03;
4036 let local = addr & (NT - 1);
4037 (m.physical_bank(table as u8) as u16) * NT + local
4038}
4039
4040/// Adapter that exposes the [`PpuBus`] interface over a `&mut dyn Mapper`.
4041struct PpuBusAdapter<'a> {
4042 mapper: &'a mut dyn Mapper,
4043 /// v1.1.0 beta.1 (T-110-B4) — the bus's per-game mirroring override, copied
4044 /// in at construction. When `Some`, `nametable_address` uses it instead of
4045 /// the mapper's mirroring.
4046 nt_override: Option<rustynes_mappers::Mirroring>,
4047 /// v3.5.0 — the bus's cached [`Mapper::snoops_ppu_reads`]. The PPU
4048 /// reports every read it makes; only when this is `true` does the
4049 /// adapter forward it to the mapper (`notify_ppu_read`).
4050 snoop_reads: bool,
4051 /// Current PPU sub-dot of the host CPU cycle (0, 1, or 2). Set by
4052 /// the bus's tick loop before each `Ppu::tick` call so that
4053 /// `notify_a12_at_sub_dot` (C1 step B4-successor M2-phase plumbing)
4054 /// can forward the sub-dot to the mapper for cycle-precise IRQ
4055 /// propagation modeling. Sub-dots 0 / 1 are M2-low (φ1) and 2 is
4056 /// M2-high (φ2) per our convention.
4057 sub_dot: u8,
4058}
4059
4060impl PpuBus for PpuBusAdapter<'_> {
4061 fn ppu_read(&mut self, addr: u16) -> u8 {
4062 self.mapper.ppu_read(addr & 0x1FFF)
4063 }
4064
4065 fn chr_reads_are_pure(&self) -> bool {
4066 self.mapper.chr_reads_are_pure()
4067 }
4068 fn ppu_read_sprite(&mut self, addr: u16) -> u8 {
4069 self.mapper.ppu_read_sprite(addr & 0x1FFF)
4070 }
4071 fn chr_phys(&self, addr: u16) -> Option<u32> {
4072 self.mapper.chr_phys(addr & 0x1FFF)
4073 }
4074 fn ppu_write(&mut self, addr: u16, value: u8) {
4075 self.mapper.ppu_write(addr & 0x1FFF, value);
4076 }
4077 fn nametable_unfolded(&self) -> bool {
4078 self.mapper.nametable_unfolded()
4079 }
4080 fn peek_nametable(&mut self, addr: u16) -> Option<u8> {
4081 self.mapper.nametable_fetch(addr)
4082 }
4083 fn write_nametable(&mut self, addr: u16, value: u8) -> bool {
4084 self.mapper.nametable_write(addr, value)
4085 }
4086 fn peek_ex_attribute(&mut self, v: u16) -> Option<PpuExAttribute> {
4087 self.mapper.peek_ex_attribute(v).map(|ex| PpuExAttribute {
4088 palette: ex.palette,
4089 chr_bank: ex.chr_bank,
4090 })
4091 }
4092 fn bg_split_state(&mut self, scanline_y: u16, coarse_x: u16) -> Option<PpuBgSplitState> {
4093 self.mapper
4094 .bg_split_state(scanline_y, coarse_x)
4095 .map(|s| PpuBgSplitState {
4096 nt_addr: s.nt_addr,
4097 at_addr: s.at_addr,
4098 fine_y: s.fine_y,
4099 chr_bank: s.chr_bank,
4100 })
4101 }
4102 fn notify_a12(&mut self, level: bool) {
4103 // C1 step B4 successor: forward the current sub-dot to the
4104 // mapper so MMC3 can apply the M2-phase-aware IRQ-output
4105 // propagation delay required by `mmc3_test_2/4-scanline_timing`
4106 // sub-test #3. Non-MMC3 mappers' default
4107 // `notify_a12_at_sub_dot` impl falls back to plain `notify_a12`,
4108 // so this thread-through is invisible to NROM / UxROM / etc.
4109 self.mapper.notify_a12_at_sub_dot(level, self.sub_dot);
4110 }
4111 #[inline]
4112 fn notify_ppu_read(&mut self, addr: u16) {
4113 if self.snoop_reads {
4114 self.mapper.notify_ppu_read(addr);
4115 }
4116 }
4117 fn notify_scanline_start(&mut self) {
4118 self.mapper.notify_scanline_start();
4119 }
4120 fn notify_vblank(&mut self) {
4121 self.mapper.notify_vblank();
4122 }
4123 fn nametable_address(&self, addr: u16) -> u16 {
4124 resolve_nt_addr(self.nt_override, &*self.mapper, addr)
4125 }
4126}
4127
4128/// Resolve a nametable address to a physical CIRAM offset, honouring the
4129/// per-game mirroring override when one is set.
4130///
4131/// Factored out of [`PpuBusAdapter::nametable_address`] (v2.3.2 "Lucid") so
4132/// [`SystemBus::resolve_nametable_address`] can answer the same question
4133/// without constructing an adapter. One definition, so the fetch path and the
4134/// provenance panel cannot drift apart on a board with an override.
4135fn resolve_nt_addr(
4136 nt_override: Option<rustynes_mappers::Mirroring>,
4137 mapper: &dyn Mapper,
4138 addr: u16,
4139) -> u16 {
4140 nt_override.map_or_else(
4141 || mapper.nametable_address(addr),
4142 |m| override_nt_addr(m, addr),
4143 )
4144}
4145
4146impl SystemBus {
4147 /// Read-only nametable-address resolution for the pixel-provenance panel.
4148 ///
4149 /// Shares [`resolve_nt_addr`] with the PPU's own fetch path, so a board with
4150 /// a per-game mirroring override reports the offset its fetches really use.
4151 #[cfg(feature = "debug-hooks")]
4152 pub(crate) fn resolve_nametable_address(&self, addr: u16) -> u16 {
4153 resolve_nt_addr(self.nt_mirroring_override, &*self.mapper, addr)
4154 }
4155}
4156
4157/// v2.0 master-clock R1 substrate helpers (Phase 1). Compiled only under
4158/// `mc-r1-substrate`; used by the clean `Bus` contract overrides below.
4159impl SystemBus {
4160 /// Tick the APU + frame counter once and fan frame events out to on-cart
4161 /// audio (the per-CPU-cycle APU advance `cpu_clock` runs at cycle start).
4162 ///
4163 /// v2.8.0 Phase 4 — the mapper dispatches are gated on the cached
4164 /// capability flags: boards without on-cart audio would return 0 from
4165 /// the default `mix_audio` (0.0 after the f32 conversion — identical),
4166 /// and boards without the frame hook have the default no-op. Skipping
4167 /// both saves two virtual calls + an f32 divide per CPU cycle.
4168 fn apu_advance_one(&mut self, apu_cycle: u64) {
4169 // `Mapper::mix_audio` returns i32 (widened from i16 in v2.2.3 so the
4170 // Sunsoft 5B's ~3.6x full-volume level is representable); scale it to
4171 // about the APU mixer's own [-0.5, 0.5] range. `as f32` rather than
4172 // `f32::from`: there is no lossless From<i32> for f32, and the cast
4173 // is exact for every value a board produces (|sample| well under
4174 // 2^24, where f32 is still integer-exact).
4175 #[allow(clippy::cast_precision_loss)]
4176 let mapper_sample = if self.mapper_caps.audio {
4177 self.mapper.mix_audio() as f32 / 65536.0
4178 } else {
4179 0.0
4180 };
4181 // v2.0.0 beta.1 (A1 one-clock collapse): hand the APU the canonical
4182 // bus cycle counter (incremented earlier in this same `cpu_clock`)
4183 // instead of letting it keep an independent `+= 1` mirror (the
4184 // one-clock collapse, promoted to the only path in v2.0.0 beta.4).
4185 // v3.1.0: `apu_cycle` is that same counter at `x1`, and the stock-rate
4186 // domain's own counter under the CPU overclock.
4187 self.apu.set_canonical_cycle(apu_cycle);
4188 self.apu.tick_with_external(mapper_sample);
4189 if self.mapper_caps.frame_event_hook {
4190 let ev = self.apu.last_frame_events();
4191 self.mapper.notify_frame_event(MapperFrameEvents {
4192 quarter: ev.quarter,
4193 half: ev.half,
4194 });
4195 }
4196 }
4197}
4198
4199impl Bus for SystemBus {
4200 fn cpu_read(&mut self, addr: u16) -> u8 {
4201 if self.deferred_dma_replay_addr != 0
4202 && self.open_bus == (self.deferred_dma_replay_addr >> 8) as u8
4203 {
4204 if self.deferred_dma_replay_addr == addr {
4205 self.replay_dma_noop_read(addr);
4206 }
4207 self.deferred_dma_replay_addr = 0;
4208 }
4209 let value = self.raw_cpu_read(addr);
4210 // v1.1.0 beta.3 (T-110-E2) — Lua onRead access tap. Output-only, gated.
4211 #[cfg(feature = "debug-hooks")]
4212 if self.access_logging && self.accesses.len() < ACCESS_CAP {
4213 self.accesses.push(AccessRec {
4214 write: false,
4215 addr,
4216 value,
4217 });
4218 }
4219 // v1.5.0 Workstream A2 — event-viewer read tap: the graphical PPU Event
4220 // Viewer needs PPU-register READS (`$2002` status polls, `$2007` data
4221 // fetches) plotted alongside writes. Only the `$2000-$3FFF` PPU window is
4222 // captured (the dense APU/RAM/PRG read stream would swamp the timeline);
4223 // writes across PPU/APU/mapper are captured in `cpu_write`. Output-only,
4224 // gated, bounded by `EVENT_CAP` — determinism-neutral.
4225 #[cfg(feature = "debug-hooks")]
4226 if self.event_logging && matches!(addr, 0x2000..=0x3FFF) && self.events.len() < EVENT_CAP {
4227 self.events.push(EventRec {
4228 kind: EventKind::PpuRead,
4229 scanline: self.ppu.scanline(),
4230 dot: self.ppu.dot(),
4231 addr,
4232 value,
4233 });
4234 }
4235 // v1.4.0 Workstream D (D2) — event-breakpoint read taps. Output-only.
4236 // The `mask == 0` early-out in `record_event_break` keeps the default
4237 // path cheap; the sprite-0-hit category is observed where games detect
4238 // it: a `$2002` read returning bit 6 set.
4239 #[cfg(feature = "debug-hooks")]
4240 if self.event_bp_mask != 0 {
4241 match addr {
4242 0x2002 if value & 0x40 != 0 => {
4243 self.record_event_break(EventBpKind::Sprite0Hit, addr);
4244 }
4245 0x2000..=0x3FFF => self.record_event_break(EventBpKind::PpuRead, addr),
4246 0x4000..=0x4017 => self.record_event_break(EventBpKind::ApuRead, addr),
4247 0x4020..=0xFFFF => self.record_event_break(EventBpKind::MapperRead, addr),
4248 _ => {}
4249 }
4250 }
4251 #[cfg(feature = "irq-timing-trace")]
4252 {
4253 // Session-21: record the CPU-initiated read at the bus-access
4254 // tracker. `Cpu::read1` performs the access between
4255 // `start_cycle` and `end_cycle`, and `end_cycle` ends with
4256 // `trace_end_cycle`, which consumes the tracker into this cycle's
4257 // record.
4258 self.trace_bus_access = BusAccess::Read;
4259 self.trace_bus_addr = addr;
4260 self.trace_bus_data = value;
4261 }
4262 value
4263 }
4264
4265 fn cpu_write(&mut self, addr: u16, value: u8) {
4266 self.open_bus = value;
4267 // Mirror the CPU-initiated write onto the internal data bus.
4268 // Symmetric with `raw_cpu_read`'s mirror — DMC DMA does not
4269 // perform writes, so internal-vs-external divergence only
4270 // arises across DMC read halts. (No `in_dmc_dma` guard
4271 // here because DMC DMA never invokes `cpu_write`.)
4272 self.internal_data_bus = value;
4273 // v1.1.0 beta.3 (T-110-E2) — Lua onWrite access tap. Output-only, gated.
4274 #[cfg(feature = "debug-hooks")]
4275 if self.access_logging && self.accesses.len() < ACCESS_CAP {
4276 self.accesses.push(AccessRec {
4277 write: true,
4278 addr,
4279 value,
4280 });
4281 }
4282 // v1.1.0 beta.2 (T-110-C3) — event-viewer tap: classify the write +
4283 // record it with the current PPU position. Output-only, gated.
4284 #[cfg(feature = "debug-hooks")]
4285 if self.event_logging {
4286 let kind = match addr {
4287 0x2000..=0x3FFF => Some(EventKind::PpuWrite),
4288 // The whole `$4000-$4017` APU / I/O window (Copilot #43): this
4289 // now also captures `$4014` OAM DMA and `$4016` controller
4290 // strobe, which the legend's "$4000-4017" already advertises.
4291 0x4000..=0x4017 => Some(EventKind::ApuWrite),
4292 0x4020..=0xFFFF => Some(EventKind::MapperWrite),
4293 _ => None,
4294 };
4295 if let Some(kind) = kind
4296 && self.events.len() < EVENT_CAP
4297 {
4298 self.events.push(EventRec {
4299 kind,
4300 scanline: self.ppu.scanline(),
4301 dot: self.ppu.dot(),
4302 addr,
4303 value,
4304 });
4305 }
4306 }
4307 // v1.4.0 Workstream D (D2) — event-breakpoint write taps. Output-only.
4308 // `$4014` is the OAM-DMA trigger; the rest classify by window.
4309 #[cfg(feature = "debug-hooks")]
4310 if self.event_bp_mask != 0 {
4311 match addr {
4312 0x2000..=0x3FFF => self.record_event_break(EventBpKind::PpuWrite, addr),
4313 REG_OAM_DMA => self.record_event_break(EventBpKind::OamDma, addr),
4314 0x4000..=0x4017 => self.record_event_break(EventBpKind::ApuWrite, addr),
4315 0x4020..=0xFFFF => self.record_event_break(EventBpKind::MapperWrite, addr),
4316 _ => {}
4317 }
4318 }
4319 match addr {
4320 0x0000..=0x1FFF => self.ram[(addr & 0x07FF) as usize] = value,
4321 0x2000..=0x3FFF => self.ppu_register_write(addr, value),
4322 REG_OAM_DMA => {
4323 // v2.3.2 "Lucid" — freeze THIS instruction (the `STA $4014`) as
4324 // the cause of the burst before it is armed. The 513/514 DMA
4325 // cycles are stolen from the instructions that follow, so by the
4326 // time the first OAM byte lands the live attribution context has
4327 // moved on to whichever instruction is being halted.
4328 #[cfg(feature = "debug-hooks")]
4329 self.ppu.latch_dma_attrib_context();
4330 // v2.3.7 "Overtone" — `$4014` sits inside the `$4000-$4017`
4331 // window the audio-provenance table reserves a slot for, but the
4332 // arm below routes only `$4000-$4013 | $4015 | $4017` to
4333 // `Apu::write_register`, where attribution is recorded. Record it
4334 // here so the reserved slot is actually populated; nothing is
4335 // dispatched to the APU, so the DMA behaviour is unchanged.
4336 #[cfg(feature = "debug-hooks")]
4337 self.apu
4338 .record_bus_handled_register_write(REG_OAM_DMA, value);
4339 self.dma_pending = Some(value);
4340 }
4341 0x4000..=0x4013 | 0x4015 | 0x4017 => self.apu.write_register(addr, value),
4342 0x4016 => {
4343 // v2.3.7 "Overtone" — same as `$4014` above: inside the
4344 // provenance window, never routed to `Apu::write_register`, so
4345 // attribute it here. The strobe itself is still buffered and
4346 // committed by the code below; this only records the cause.
4347 #[cfg(feature = "debug-hooks")]
4348 self.apu.record_bus_handled_register_write(0x4016, value);
4349 // Session-24 / Phase 3 (Controller Strobing): the
4350 // controllers' OUT pins are only updated at the start
4351 // of M2-low (PUT) cycles. Buffer the write and
4352 // commit at the next M2-low boundary inside
4353 // `cpu_clock` (`tick_one_cpu_cycle` until v2.9.8). Mirrors Mesen2's
4354 // `NesControlManager::WriteRam` (Core/NES/
4355 // NesControlManager.cpp lines 252-273).
4356 //
4357 // Parity convention: in `RustyNES` the bus enters each
4358 // CPU cycle at `M2Phase::Low` and transitions to
4359 // `M2Phase::High` after PPU sub-dot 1. The cycle
4360 // counter advances at end-of-cycle. So a CPU write
4361 // executed during cycle `self.cycle` lands at the END
4362 // of that cycle's M2-high half. The NEXT cycle
4363 // (`self.cycle + 1`) starts at M2-low — which is the
4364 // commit boundary. In Mesen2's master-clock terms,
4365 // odd master clocks mean "one cycle from PUT" and
4366 // even mean "two cycles from PUT"; the corresponding
4367 // `RustyNES` rule is: if `self.cycle` is odd at write
4368 // time, pending = 1 (commit at next cycle); if even,
4369 // pending = 2 (commit at cycle-after-next). This
4370 // collapses the AccuracyCoin Test 4 1-cycle DEC
4371 // `$4016` strobe pulse (both writes target the SAME
4372 // commit cycle; the second overwrites the first; no
4373 // edge is observed → no latch). See
4374 // `docs/audit/session-24-phase3-controller-strobing-2026-05-23.md`.
4375 self.controller_write_value = value;
4376 // Parity convention: in `RustyNES` the CPU `cpu_write` runs
4377 // AFTER `cpu_clock` has incremented `self.cycle` to the
4378 // post-cycle value (`Cpu::start_cycle` calls `cpu_clock`
4379 // before the access; `tick_one_cpu_cycle` until v2.9.8). The committed commit
4380 // cycle MUST land on an M2-low boundary (PUT cycle).
4381 // In `RustyNES` every CPU cycle starts at M2-low and
4382 // transitions to M2-high after sub-dot 1, so every
4383 // cycle has an M2-low half — but only cycles where
4384 // the COMMITTED strobe value is observable AT the
4385 // beginning of the cycle qualify as the deferred-
4386 // write commit target.
4387 //
4388 // The empirical calibration from the Phase 3 oracle:
4389 // Mesen2 PUT cycles correspond to ODD `cpu.cycleCount`
4390 // (per `NesCpu.cpp:400` `bool getCycle = (CycleCount &
4391 // 0x01) == 0;` — get cycles are even, put cycles are
4392 // odd). Our `self.cycle` parity at the moment of
4393 // `cpu_write` differs from Mesen2's by an offset
4394 // (Mesen2's cycle count includes the boot/reset
4395 // sequence differently); empirically, our EVEN cycles
4396 // correspond to Mesen2's PUT cycles in the
4397 // `controller-strobing.nes` Test 3 vs Test 4
4398 // discrimination. Hence: even `self.cycle` → pending
4399 // = 1 (commit next cycle); odd `self.cycle` → pending
4400 // = 2 (commit cycle-after-next).
4401 self.controller_write_pending = if (self.cycle & 1) == 0 { 1 } else { 2 };
4402 // Vs. System (mapper 99): the CHR bank select is bit 2 of the
4403 // value written to $4016 (shared with the controller strobe).
4404 // Forward every $4016 write to the mapper; only mapper 99
4405 // consumes it — every other mapper's `cpu_write` ignores the
4406 // $4016 address (their match arms only cover $8000-$FFFF /
4407 // $4020-$7FFF), so this is byte-for-byte a no-op on all
4408 // non-Vs. carts.
4409 self.mapper.cpu_write(0x4016, value);
4410 // v2.0.0 beta.5 (Vs. DualSystem): report the bit-1 (main/sub
4411 // comms signal) LEVEL on EVERY $4016 write for the wrapper
4412 // to poll. Deliberately not edge-filtered: the wrapper seeds
4413 // the reset-time levels itself (Mesen2's
4414 // `UpdateMainSubBit(main ? 0x00 : 0x02)`), so a bus-side
4415 // edge filter starting from a `false` latch would swallow a
4416 // genuine seeded-HIGH → written-LOW transition (Balloon
4417 // Fight's reset writes `$4016 = $00` on both consoles) and
4418 // deadlock the boot handshake. Applying an unchanged level
4419 // is idempotent in the wrapper. The latch is only consulted
4420 // by the DualSystem wrapper; single-console behavior is
4421 // untouched (two dead field writes on non-Vs carts, no
4422 // reads).
4423 self.vs_4016_bit1 = (value & 0x02) != 0;
4424 self.vs_4016_bit1_dirty = true;
4425 }
4426 0x4018..=0x401F => {}
4427 0x4020..=0xFFFF => self.mapper.cpu_write(addr, value),
4428 }
4429 #[cfg(feature = "irq-timing-trace")]
4430 {
4431 // Session-21: record the CPU-initiated write at the bus-access
4432 // tracker for the same reason `cpu_read` does above.
4433 self.trace_bus_access = BusAccess::Write;
4434 self.trace_bus_addr = addr;
4435 self.trace_bus_data = value;
4436 }
4437 }
4438
4439 fn cycle_count(&self) -> u64 {
4440 // Cumulative bus-side cycle counter, including DMC DMA cycles
4441 // that the CPU's own `Cpu::cycles` field does not count. Used
4442 // by the SH* unstable-store family to detect DMA interrupting
4443 // their dummy-read cycle per Mesen2's `SyaSxaAxa` algorithm.
4444 self.cycle
4445 }
4446
4447 fn notify_irq_service(&mut self, vector: u16, is_nmi: bool) {
4448 // v1.2.0 (T-110-E1) — Lua onNmi/onIrq interrupt-service tap. This is the
4449 // committed-service commit point (same as the IRQ trace below), NOT the
4450 // speculative poll_nmi/poll_irq sampler. Output-only, gated; no-op when
4451 // `debug-hooks` is off (the log slot only exists feature-gated).
4452 //
4453 // The reliable NMI/IRQ discriminator here is the COMMITTED `vector`
4454 // ($FFFA = NMI, $FFFE = IRQ/BRK), not the `is_nmi` arg: the unified
4455 // dispatch always enters `service_interrupt` with the IRQ vector and
4456 // resolves the NMI *hijack* internally (so the `is_nmi` arg reads
4457 // `false` on a hijacked NMI). Classifying by the vector the CPU actually
4458 // fetched reports exactly the service that committed.
4459 #[cfg(feature = "debug-hooks")]
4460 if self.interrupt_logging && self.interrupts.len() < INTERRUPT_CAP {
4461 let _ = is_nmi;
4462 self.interrupts.push(InterruptRec {
4463 is_nmi: vector == 0xFFFA,
4464 vector,
4465 });
4466 }
4467 // v1.4.0 Workstream D (D2) — NMI/IRQ event-breakpoint tap. Classified by
4468 // the COMMITTED vector (same discriminator the interrupt log uses).
4469 #[cfg(feature = "debug-hooks")]
4470 if self.event_bp_mask != 0 {
4471 let kind = if vector == 0xFFFA {
4472 EventBpKind::Nmi
4473 } else {
4474 EventBpKind::Irq
4475 };
4476 self.record_event_break(kind, vector);
4477 }
4478 // Phase 1.2 of Track C1 attempt 14: emit a [`ServiceEvent`] into
4479 // the IRQ trace if the trace is armed. Production builds with
4480 // the `irq-timing-trace` feature OFF compile this down to a
4481 // no-op (the trace slot only exists feature-gated).
4482 #[cfg(feature = "irq-timing-trace")]
4483 if let Some(trace) = self.irq_trace.as_mut() {
4484 let frame_start = self.ppu.frame();
4485 let scanline_start = self.ppu.scanline();
4486 let dot_start = self.ppu.dot();
4487 let kind = if is_nmi {
4488 crate::irq_trace::ServiceKind::Nmi
4489 } else {
4490 crate::irq_trace::ServiceKind::Irq
4491 };
4492 // `self.cycle` is the count of cycles already consumed; the
4493 // service-vector fetch is the cycle the CPU is ABOUT to
4494 // emit, so reporting `self.cycle` (== the next cycle index)
4495 // matches Mesen2's `cpu.cycleCount` at the moment its
4496 // `emu.eventType.irq` callback fires (its cycle count is
4497 // sampled at the start of the service cycle).
4498 trace.push_service(crate::irq_trace::ServiceEvent {
4499 cpu_cycle: self.cycle,
4500 ppu_scanline: scanline_start,
4501 ppu_dot: dot_start,
4502 ppu_frame: frame_start,
4503 kind,
4504 vector,
4505 });
4506 } else {
4507 let _ = (vector, is_nmi);
4508 }
4509 // Suppress unused-variable warnings when the feature is off.
4510 #[cfg(not(feature = "irq-timing-trace"))]
4511 {
4512 let _ = (vector, is_nmi);
4513 }
4514 }
4515
4516 // ============================================================
4517 // v2.0 master-clock R1 substrate — production overrides (Phase 1).
4518 // Compiled only under `mc-r1-substrate`; consulted by the R1 CPU loop
4519 // (Phases 2+). NOT exercised on the default build, so default behaviour
4520 // is byte-identical. Ported from refactor/v2.0-master-clock with the
4521 // trace + S1/S2 (mc-apu-subcycle / r4-cpu-dma) wiring stripped.
4522 // ============================================================
4523
4524 /// Pure address-space read under R1 (the DMA drain happens in
4525 /// [`Bus::cpu_clock`]; Phase 3 will split the drain out of `cpu_read`).
4526 /// Phase 1 delegates to the legacy path so the contract compiles.
4527 fn read(&mut self, addr: u16) -> u8 {
4528 // A CPU read cycle ran, so any write-refused load either entered on
4529 // the DMA cycles before it (clearing the latch there) or was not
4530 // serviceable; the latch spans exactly one write-to-read boundary.
4531 self.dmc_load_write_delayed = false;
4532 self.cpu_read(addr)
4533 }
4534
4535 fn write(&mut self, addr: u16, value: u8) {
4536 // RDY cannot halt a write. A pending load that would have entered on
4537 // this cycle (the get half: the access-point label is `!put_cycle`,
4538 // as in `unified_dma_cycle_impl`) is refused, and enters on the next
4539 // read without the get-half deferral (`dmc_load_write_delayed`).
4540 if self.apu.dmc_dma_pending()
4541 && self.apu.dmc_dma_is_load()
4542 && self.apu.dmc_dma_serviceable()
4543 && !self.in_dmc_dma
4544 && !self.apu.put_cycle()
4545 {
4546 self.dmc_load_write_delayed = true;
4547 }
4548 self.cpu_write(addr, value);
4549 }
4550
4551 /// R1 master clocks per CPU cycle for the cartridge region (NTSC 12 / PAL
4552 /// 16 / Dendy 15) — the `cpu_divider` half of `region_dividers`.
4553 /// Drives the CPU loop's `master_clock` advance + read/write split so the
4554 /// CPU<->PPU phase is 3:1 NTSC, 3.2:1 PAL, 3:1 Dendy.
4555 fn cpu_divider(&self) -> u64 {
4556 // The overclocked CPU cycle length; `cpu_div_cached` at `x1`.
4557 u64::from(self.cpu_div_effective)
4558 }
4559
4560 /// R1 double catch-up: tick whole PPU dots while
4561 /// `ppu_clock + ppu_divider <= target`.
4562 ///
4563 /// R1c-3 (v2.0.0's `mmc3-m2-phase-irq`, removed at v2.9.9; now
4564 /// `mmc3-a12-phase-probe` only): when the feature is enabled, `sub_dot` is seeded from the REAL M2-phase of this catch-up
4565 /// call (`0` = pre-access / M2-low, called from `Cpu::start_cycle`
4566 /// before the bus access; `2` = post-access / M2-high, called from
4567 /// `Cpu::end_cycle` after it) instead of always restarting at `0`. Prior
4568 /// to this experiment `sub_dot` was a call-LOCAL counter that reset to
4569 /// zero on every invocation of this function — since `run_ppu_to` is
4570 /// called twice per CPU cycle (once per half) and each half typically
4571 /// ticks at most one PPU dot, the value threaded to
4572 /// `Mapper::notify_a12_at_sub_dot` was almost always `0` regardless of
4573 /// which half of the cycle actually produced the A12 transition. That
4574 /// meant the M2-phase plumbing ADR-0002 describes ("sub-dot 0/1 is
4575 /// M2-low, 2 is M2-high") was never actually true on the live R1
4576 /// (non-DMA) scheduler path — only on the legacy `tick_one_cpu_cycle`
4577 /// DMA-burst path (removed at v2.9.8, ADR 0042), which genuinely walked
4578 /// all 3 dots of a cycle in one call with a persistent counter. This experiment closes that gap so
4579 /// MMC3's (default-off) M2-phase-aware IRQ-visibility pipeline can be
4580 /// evaluated against real phase data on the promoted core. See
4581 /// `docs/adr/0002-irq-timing-coordination.md` and
4582 /// `docs/audit/r1r2-per-dot-scheduler-attempt-2026-07-02.md`.
4583 ///
4584 /// When the feature is OFF this compiles to the exact prior
4585 /// call-local-counter behavior (`sub_dot` always starts at `0`) —
4586 /// byte-identical default build, per the project's additive/off-by-
4587 /// default convention.
4588 fn run_ppu_to(&mut self, target: u64, is_post_access: bool) {
4589 let ppu_div = u64::from(self.ppu_div_cached);
4590 // Seed the real M2-phase into `sub_dot` (0 = pre-access/M2-low catch-up,
4591 // 2 = post-access/M2-high catch-up) for the v2.1.5 F5.0
4592 // `mmc3-a12-phase-probe` observational tally (v2.0.0's
4593 // `mmc3-m2-phase-irq` deferral also read it; removed at v2.9.9).
4594 // The probe only counts, so the emulated timeline stays byte-identical
4595 // even with its feature on. See ADR 0002.
4596 #[cfg(feature = "mmc3-a12-phase-probe")]
4597 let mut sub_dot = if is_post_access { 2u8 } else { 0u8 };
4598 #[cfg(not(feature = "mmc3-a12-phase-probe"))]
4599 let (mut sub_dot, _) = (0u8, is_post_access);
4600 while self.ppu_clock + ppu_div <= target {
4601 let mut adapter = PpuBusAdapter {
4602 mapper: self.mapper.as_mut(),
4603 nt_override: self.nt_mirroring_override,
4604 snoop_reads: self.ppu_read_snoop,
4605 sub_dot,
4606 };
4607 // No per-dot /NMI sampling here: the CPU reads the live level
4608 // through `nmi_level` and edge-detects it itself. The bus-side
4609 // edge detector that used to run on every dot fed only the
4610 // removed `poll_nmi` (ADR 0042, v2.9.8).
4611 self.ppu.tick(&mut adapter);
4612 self.ppu_clock += ppu_div;
4613 sub_dot = sub_dot.wrapping_add(1);
4614 }
4615 }
4616
4617 /// R1: one CPU cycle of bus-side work (NO PPU advance — that lives in
4618 /// [`Bus::run_ppu_to`]). Controller strobe commit + cycle counter +
4619 /// per-cycle PPU/mapper hooks + APU tick. DMA is not run here: the CPU
4620 /// drives the unified engine through `unified_dma_cycle`, one full cycle
4621 /// at a time.
4622 fn cpu_clock(&mut self) {
4623 // Stamp the PPU with the cycle whose dots this call is about to run.
4624 // See `Ppu::set_trace_cpu_cycle`.
4625 //
4626 // This is the path a running console takes. The stamp once lived only
4627 // in the pre-v2.0.0 `tick_one_cpu_cycle` (removed at v2.9.8), which left
4628 // every record stamped `0` while the field, the column and the
4629 // plumbing all looked correct -- caught by
4630 // `tests/state_trace_records_carry_their_cpu_cycle.rs`, which exists
4631 // because a present-but-constant field reinstates the whole problem it
4632 // was added to solve while appearing to fix it.
4633 #[cfg(feature = "ppu-state-trace")]
4634 self.ppu.set_trace_cpu_cycle(self.cycle);
4635
4636 // Diagnostic: snapshot the APU IRQ line (frame-counter | DMC) BEFORE
4637 // `apu_advance_one` runs the frame counter, so `trace_end_cycle` can
4638 // expose the within-cycle frame-counter SET (low=0 -> high=1) vs the
4639 // DMA `$4015` CLEAR (low=1 -> high=0) ordering. Only meaningful under
4640 // the trace feature; the field is otherwise unused on the R1 path.
4641 #[cfg(feature = "irq-timing-trace")]
4642 {
4643 self.irq_snapshot_apu_at_low = self.apu.irq_line();
4644 self.trace_r1_scanline_start = self.ppu.scanline();
4645 self.trace_r1_dot_start = self.ppu.dot();
4646 self.trace_r1_frame_start = self.ppu.frame();
4647 }
4648 if self.controller_write_pending > 0 {
4649 self.controller_write_pending -= 1;
4650 if self.controller_write_pending == 0 {
4651 let value = self.controller_write_value;
4652 self.commit_controller_strobe(value);
4653 }
4654 }
4655 self.cycle = self.cycle.wrapping_add(1);
4656 // v3.1.0 (`T-CPU-OVERCLOCK`): under the overclock only some CPU cycles
4657 // are stock steps, and everything below this point that measures
4658 // console time (the PPU's decay / post-reset timers, the mappers'
4659 // M2-cycle IRQ counters, the APU) runs on those only. At `x1` the
4660 // branch is never taken: every cycle is a stock step and the APU gets
4661 // the CPU counter, exactly as before.
4662 let apu_cycle = if self.cpu_overclock == 1 {
4663 self.cycle
4664 } else {
4665 // The stock step is the LAST cycle of each group of `k`; the phase
4666 // itself advances at this cycle's end (`cpu_clock_apu_dmc`).
4667 self.stock_step = self.overclock_phase + 1 >= self.cpu_overclock;
4668 if !self.stock_step {
4669 return;
4670 }
4671 self.apu_cycle = self.apu_cycle.wrapping_add(1);
4672 self.apu_cycle
4673 };
4674 self.ppu.on_cpu_cycle();
4675 // v2.8.0 Phase 4 — skip the virtual dispatch on boards whose
4676 // `notify_cpu_cycle` is the default no-op (capability-flag cache).
4677 if self.mapper_caps.cpu_cycle_hook {
4678 self.mapper.notify_cpu_cycle();
4679 }
4680 // F-2: `apu_advance_one` (start) ticks the whole APU EXCEPT the DMC
4681 // byte-timer (gated out by `dmc_driven_externally`); the DMC is ticked
4682 // at end-of-cycle by `cpu_clock_apu_dmc`.
4683 self.apu_advance_one(apu_cycle);
4684 // (W2 $2007 Stress) The deferred $2007 render-buffer reload is now
4685 // PPU-dot-scheduled and consumed inside `Ppu::tick` — the prior
4686 // per-CPU-cycle `apply_pending_render_buffer` hook here was quantized
4687 // to 3-dot steps and structurally aliased mod 3 against the test's
4688 // 1-dot-per-iteration clockslide.
4689 }
4690
4691 // RA-1 (mc-r1-apu-unified-clock): the DMC byte-timer is now clocked at cycle
4692 // START (in `Apu::tick_with_external` via `apu_advance_one` in `cpu_clock`),
4693 // unified with the rest of the APU and advancing through the DMC DMA span,
4694 // matching Mesen's `ProcessCpuClock` at `StartCpuCycle`. So the END-of-cycle
4695 // DMC tick is a no-op here.
4696 fn cpu_clock_apu_dmc(&mut self) {
4697 // v3.1.0: the overclock's phase moves to the next cycle HERE, after
4698 // both of this cycle's `cpu_divider` reads (the CPU calls this once
4699 // per cycle, DMA cycles included), so the next cycle's length is in
4700 // place before its first half.
4701 if self.cpu_overclock > 1 {
4702 self.overclock_phase = (self.overclock_phase + 1) % self.cpu_overclock;
4703 self.cpu_div_effective = overclock_cycle_len(
4704 self.cpu_div_cached,
4705 self.cpu_overclock,
4706 self.overclock_phase,
4707 );
4708 }
4709 // v3.1.0: the DMC end-of-cycle half belongs to the stock step its
4710 // start half ran in (always `true` at `x1`).
4711 if !self.stock_step {
4712 return;
4713 }
4714 // v2.0 Program M (M-1): clock the DMC byte-timer + arm the reload HERE at
4715 // end-of-cycle (after the CPU's bus access), the references' within-cycle
4716 // order. When the flag is OFF the byte-timer stays at cycle-start (above,
4717 // in `tick_with_external`) and this is a no-op -> floor byte-identical.
4718 // Runs BEFORE `promote_dmc_pending_next` so a reload armed at end-of-cycle
4719 // N latches `_next` and is promoted by this SAME call -> serviced N+1
4720 // (the floor service cadence), the byte-timer position being the only
4721 // shift (vs promote-before, which adds a full +1 service cycle and
4722 // over-shifts every DMA).
4723 self.apu.dmc_tick_end();
4724 // Visibility-delay: promote a reload latched this cycle at END (after the
4725 // CPU's bus access) so the NEXT cycle's DMA loop first-services it (put).
4726 self.apu.promote_dmc_pending_next();
4727 }
4728
4729 fn irq_level(&self) -> bool {
4730 // Bound BEFORE the expression rather than as an inline `#[cfg]` block
4731 // inside it. The two forms compile identically -- the default build
4732 // still emits nothing named `inject_`, which is ADR 0038's structural
4733 // gate -- but a `cfg` block in the middle of a boolean chain is hard to
4734 // read, and this chain is the wire-OR of every /IRQ source.
4735 #[cfg(feature = "cosim-interrupt-inject")]
4736 let injected = self.inject_irq;
4737 #[cfg(not(feature = "cosim-interrupt-inject"))]
4738 let injected = false;
4739
4740 // v2.8.0 Phase 4 — boards without an IRQ source have the default
4741 // `irq_pending() == false`; skip the per-cycle virtual call.
4742 // v2.0.0 beta.5 — `vs_external_irq` is the DualSystem partner
4743 // console's `$4016` bit-1 signal (always `false` on a single
4744 // console, so the default path is unchanged).
4745 (self.mapper_caps.irq_source && self.mapper.irq_pending())
4746 || self.apu.irq_line()
4747 || self.vs_external_irq
4748 // v2.5.1 (ADR 0038). Level-sensitive and OR'd, exactly like
4749 // `vs_external_irq` beside it -- which is the precedent: an external
4750 // IRQ source already joins the wire-OR here, and this is the same
4751 // shape with a different driver.
4752 || injected
4753 }
4754
4755 fn nmi_level(&self) -> bool {
4756 // v2.5.1 (ADR 0038). Injected here, on the LEVEL: the production CPU
4757 // samples it every cycle and edge-detects it itself (`nmi_first_tick`
4758 // -> `pending_nmi` -> `armed_nmi`).
4759 //
4760 // The first implementation injected at `poll_nmi` (a dead hook,
4761 // removed at v2.9.8 with ADR 0042), which looked like the right
4762 // function and was never called on this path. The rung-2 sweep found it on
4763 // its first real run -- the DUT took the injected NMI and the oracle did
4764 // not -- which is exactly the defect class a co-simulation exists to
4765 // catch, arriving in the harness rather than in the RTL.
4766 //
4767 // A LEVEL, not a latch: the CPU does its own edge detection, so
4768 // consuming it here would make an injected NMI behave unlike a PPU one.
4769 #[cfg(feature = "cosim-interrupt-inject")]
4770 if self.inject_nmi {
4771 return true;
4772 }
4773 self.ppu.nmi_line()
4774 }
4775
4776 fn dmc_dma_defer_load_entry(&self) -> bool {
4777 {
4778 // The while-gate runs PRE-cycle (before `start_cycle`'s APU tick).
4779 // Floor: the start-flip means the pre-cycle `!put_cycle` predicts
4780 // an access-point parity on the DMC noop half (defer it).
4781 // W3-Stage-2 (`mc-r1-dma-unified-collapse`): the flip moved to
4782 // end-of-cycle, so the pre-cycle value IS the upcoming
4783 // access-point label — the noop half is now the PUT half, so the
4784 // defer condition INVERTS to `put_cycle` (pre-cycle reads are
4785 // flip-invariant in value; the predicted half changes).
4786 let lands_on_noop_half = self.apu.put_cycle();
4787 self.apu.dmc_dma_pending()
4788 && self.apu.dmc_dma_is_load()
4789 && lands_on_noop_half
4790 && !self.in_dmc_dma
4791 // A load refused by a write may not be deferred again.
4792 && !self.dmc_load_write_delayed
4793 }
4794 }
4795
4796 // W3-Stage-1 (`mc-r1-dma-unified`): the unified engine's pending query.
4797 // Folds the floor's load-get-entry defer (the standalone DMC loop's
4798 // pre-flip while-gate: a deferred load alone does NOT hold the CPU — the
4799 // real read runs and the load enters on the next cycle, its get half) with
4800 // the OAM pending/in-flight state. The engine re-derives the same defer at
4801 // the access point for cycles the loop runs anyway because OAM is active.
4802 fn unified_dma_pending(&self) -> bool {
4803 let dmc = self.apu.dmc_dma_pending() && !Bus::dmc_dma_defer_load_entry(self);
4804 // W3-Stage-3 (`mc-r1-dmc-delayed-4015`): the TriCNES `_6502` line-4218
4805 // service gate — `DoDMCDMA && (APU_Status_DMC || implicit-abort)`. A
4806 // pending (or halted in-flight) DMC DMA whose APPLIED status dropped
4807 // is NOT serviced: the loop exits and the CPU resumes mid-DMA — the
4808 // emergent explicit abort. The engine's transient state (`in_dmc_dma`
4809 // / `dmc_halt` / the APU pending flag) persists, like TriCNES's stale
4810 // `DoDMCDMA`/`DMCDMA_Halt`, and resumes if the status re-applies.
4811 let dmc = dmc && self.apu.dmc_dma_serviceable();
4812 dmc || self.dma_pending.is_some() || self.uni_oam_active
4813 }
4814
4815 // W3-Stage-1: one unified-engine cycle at a CPU read (the preempted
4816 // instruction/operand read supplies the parked 6502 address).
4817 fn unified_dma_cycle(&mut self, halted_addr: u16) {
4818 self.unified_dma_cycle_impl(halted_addr);
4819 }
4820
4821 // W3-Stage-1: one unified-engine cycle at a CPU internal cycle — the bus
4822 // supplies its held (last-read) address, like `dmc_dma_step_idle`.
4823 fn unified_dma_cycle_idle(&mut self) {
4824 let halted = self.last_read_addr;
4825 self.unified_dma_cycle_impl(halted);
4826 }
4827
4828 fn dmc_abort_pending(&self) -> bool {
4829 self.apu.dmc_abort_pending()
4830 }
4831
4832 fn dmc_abort_is_get_cycle(&self) -> bool {
4833 // get = read half (TriCNES `!APU_PutCycle`); the 1-cycle abort DMA can
4834 // only land its halt on a get cycle.
4835 !self.apu.put_cycle()
4836 }
4837
4838 fn dmc_abort_halt_step(&mut self, halted_addr: u16) {
4839 // 1-cycle abort DMA (Y=1): one halt re-read of the held CPU address (the
4840 // DMASync `$4000` the spin polls — drives the open-bus conflict), then
4841 // cancel the reload + the abort. The surrounding `read1` start/end_cycle
4842 // advances the clock, so CalculateDMADuration measures exactly 1 cycle.
4843 self.replay_dma_noop_read(halted_addr);
4844 #[cfg(feature = "irq-timing-trace")]
4845 self.set_trace_dma_access(BusAccess::DmaRead, halted_addr, self.open_bus);
4846 self.apu.cancel_dmc_dma();
4847 }
4848
4849 fn dmc_abort_cancel(&mut self) {
4850 // Y=0: the abort matured on a put/write cycle — no DMA occurs. Clear the
4851 // reload + the abort with no halt cycle consumed.
4852 self.apu.cancel_dmc_dma();
4853 }
4854
4855 #[cfg(not(feature = "irq-timing-trace"))]
4856 fn trace_end_cycle(&mut self) {}
4857
4858 /// v2.0 R1c-1 diagnostic: record this instruction's `(pc, cpu_cycle)` into
4859 /// the per-instruction trace ring (default + R1 both; not mc-r1-gated).
4860 #[cfg(feature = "cpu-instr-cycle-trace")]
4861 fn trace_instr(&mut self, pc: u16, cpu_cycle: u64) {
4862 instr_trace::record(pc, cpu_cycle);
4863 // Latch the PC so the per-cycle `CycleRecord` push can stamp every
4864 // cycle (including DMA-insertion cycles, which hold this PC) with the
4865 // instruction currently executing — the TriCNES cross-diff landmark.
4866 #[cfg(feature = "irq-timing-trace")]
4867 {
4868 self.trace_last_pc = pc;
4869 }
4870 }
4871
4872 /// Per-cycle trace push, the one `CycleRecord` producer since v2.9.8
4873 /// removed the legacy `tick_one_cpu_cycle` build. `irq_pending_apu_at_low` was
4874 /// snapshotted at cycle-start in `cpu_clock` (before `apu_advance_one`);
4875 /// `_at_high` is read here at end-of-cycle (after the access + DMC tick), so
4876 /// a record where low=0/high=1 is a frame-counter SET this cycle and
4877 /// low=1/high=0 is a DMA `$4015` CLEAR this cycle — the ordering signal the
4878 /// `DMA + $4015` diagnostic needs.
4879 #[cfg(feature = "irq-timing-trace")]
4880 fn trace_end_cycle(&mut self) {
4881 if self.irq_trace.is_none() {
4882 return;
4883 }
4884 let bus_access = core::mem::replace(&mut self.trace_bus_access, BusAccess::Idle);
4885 let bus_addr = core::mem::take(&mut self.trace_bus_addr);
4886 let bus_data = core::mem::take(&mut self.trace_bus_data);
4887 let mapper_irq = self.mapper.irq_pending();
4888 let rec = CycleRecord {
4889 cpu_cycle: self.cycle.wrapping_sub(1),
4890 pc: self.trace_last_pc,
4891 ppu_scanline: self.trace_r1_scanline_start,
4892 ppu_dot: self.trace_r1_dot_start,
4893 ppu_frame: self.trace_r1_frame_start,
4894 irq_pending_mapper_at_low: mapper_irq,
4895 irq_pending_apu_at_low: self.irq_snapshot_apu_at_low,
4896 irq_pending_mapper_at_high: mapper_irq,
4897 irq_pending_apu_at_high: self.apu.irq_line(),
4898 nmi_line: self.ppu.nmi_line(),
4899 // The per-sub-dot A12 capture lived in the pre-v2.0.0
4900 // `tick_one_cpu_cycle`, removed at v2.9.8 (ADR 0042); the R1 path
4901 // never fed it, so the column has been empty on every record
4902 // since v2.0.0 and stays in the schema as such.
4903 a12_events: alloc::vec::Vec::new(),
4904 dmc_dma_pending_pre: false,
4905 dmc_dma_pending_post: self.apu.dmc_dma_pending(),
4906 dmc_dma_short_post: self.apu.dmc_dma_short(),
4907 dmc_abort_pending_post: self.apu.dmc_abort_pending(),
4908 dmc_abort_delay_post: self.apu.dmc_abort_delay(),
4909 dmc_dma_cooldown_post: self.apu.dmc_dma_cooldown(),
4910 dmc_dma_delay_post: self.apu.dmc_dma_delay(),
4911 apu_phase_post: self.apu.apu_phase(),
4912 in_dmc_dma: self.in_dmc_dma,
4913 // No owed-cycle counter exists since the unified DMA engine
4914 // (its 513/514 length is emergent); the column is kept so the
4915 // trace CSV schema is unchanged.
4916 dma_cycles_owed: 0,
4917 bus_access,
4918 bus_addr,
4919 bus_data,
4920 put_cycle_post: self.apu.put_cycle(),
4921 dmc_timer_post: self.apu.dmc_timer(),
4922 dmc_bits_remaining_post: self.apu.dmc_bits_remaining(),
4923 dmc_silence_post: self.apu.dmc_silence(),
4924 dmc_buffer_full_post: self.apu.dmc_buffer_full(),
4925 };
4926 if let Some(t) = self.irq_trace.as_mut() {
4927 t.push(rec);
4928 }
4929 }
4930}
4931
4932/// v3.1.0 (`T-CPU-OVERCLOCK`): the master clocks CPU cycle `phase` of a
4933/// stock cycle takes at overclock `k`, for a region whose stock CPU cycle is
4934/// `div` master clocks. The lengths of phases `0..k` sum to exactly `div`
4935/// (they are the differences of `phase * div / k`), so `k` CPU cycles always
4936/// fill one stock cycle and the multiplier is exact on every region: NTSC
4937/// (12) gives 6/6, 4/4/4 and 3/3/3/3; PAL (16) 8/8, 5/5/6 and 4/4/4/4;
4938/// Dendy (15) 7/8, 5/5/5 and 3/4/4/4. At `k = 1` it is `div`.
4939const fn overclock_cycle_len(div: u8, k: u8, phase: u8) -> u8 {
4940 let (div, k, phase) = (div as u16, k as u16, phase as u16);
4941 // `k >= 1` by construction (`set_cpu_overclock` clamps); at most 16 * 4.
4942 #[allow(clippy::cast_possible_truncation)] // a part of `div`, at most 16
4943 let len = (((phase + 1) * div) / k - (phase * div) / k) as u8;
4944 len
4945}
4946
4947#[cfg(test)]
4948mod four_score_tests {
4949 use super::*;
4950 use crate::controller::Buttons;
4951
4952 /// Minimal NROM (16-byte iNES header + 16 KiB PRG + 8 KiB CHR). Enough to
4953 /// construct a `SystemBus`; these tests never run the CPU.
4954 fn test_bus() -> SystemBus {
4955 let mut rom = Vec::with_capacity(16 + 0x4000 + 0x2000);
4956 rom.extend_from_slice(b"NES\x1A");
4957 rom.push(1); // 16 KiB PRG
4958 rom.push(1); // 8 KiB CHR
4959 rom.extend_from_slice(&[0u8; 10]);
4960 rom.extend_from_slice(&[0u8; 0x4000]);
4961 rom.extend_from_slice(&[0u8; 0x2000]);
4962 SystemBus::new(&rom).expect("synthetic NROM parses")
4963 }
4964
4965 fn strobe(bus: &mut SystemBus) {
4966 bus.commit_controller_strobe(1);
4967 bus.commit_controller_strobe(0);
4968 }
4969
4970 #[test]
4971 fn famicom_microphone_drives_4016_bit2() {
4972 let mut bus = test_bus();
4973 // Default: mic released -> $4016 bit 2 clear (byte-identical stock read).
4974 assert!(!bus.microphone());
4975 assert_eq!(bus.peek_cpu(0x4016) & 0x04, 0x00, "mic off -> D2 clear");
4976 // Press the mic: $4016 bit 2 reads 1.
4977 bus.set_microphone(true);
4978 assert!(bus.microphone());
4979 assert_eq!(bus.peek_cpu(0x4016) & 0x04, 0x04, "mic on -> D2 set");
4980 // $4017 is unaffected (the Famicom mic is a $4016-only signal).
4981 assert_eq!(bus.peek_cpu(0x4017) & 0x04, 0x00, "mic never touches $4017");
4982 // Release restores the stock read.
4983 bus.set_microphone(false);
4984 assert_eq!(
4985 bus.peek_cpu(0x4016) & 0x04,
4986 0x00,
4987 "mic released -> D2 clear"
4988 );
4989 }
4990
4991 #[test]
4992 fn four_score_off_reads_like_standard_controller() {
4993 let mut bus = test_bus();
4994 assert!(!bus.four_score());
4995 bus.set_buttons(0, Buttons::A);
4996 strobe(&mut bus);
4997 // A, then 7 zeros, then 1s — exactly the standard pad.
4998 assert_eq!(bus.read_port(0), 1);
4999 for _ in 0..7 {
5000 assert_eq!(bus.read_port(0), 0);
5001 }
5002 for _ in 0..3 {
5003 assert_eq!(bus.read_port(0), 1);
5004 }
5005 }
5006
5007 #[test]
5008 fn four_score_multiplexes_four_pads_and_signature() {
5009 let mut bus = test_bus();
5010 bus.set_four_score(true);
5011 bus.set_buttons(0, Buttons::A); // pad 1
5012 bus.set_buttons(2, Buttons::B); // pad 3
5013 bus.set_buttons(1, Buttons::SELECT); // pad 2
5014 bus.set_buttons(3, Buttons::START); // pad 4
5015 strobe(&mut bus);
5016
5017 // Port 0 ($4016): pad1 (A) | pad3 (B) | signature 0x08 (LSB-first) | 1.
5018 let p0: Vec<u8> = (0..25).map(|_| bus.read_port(0)).collect();
5019 assert_eq!(&p0[0..8], &[1, 0, 0, 0, 0, 0, 0, 0], "pad 1: A");
5020 assert_eq!(&p0[8..16], &[0, 1, 0, 0, 0, 0, 0, 0], "pad 3: B");
5021 assert_eq!(&p0[16..24], &[0, 0, 0, 1, 0, 0, 0, 0], "signature 0x08");
5022 assert_eq!(p0[24], 1, "past 24 reads -> 1");
5023
5024 // Port 1 ($4017): pad2 (Select) | pad4 (Start) | signature 0x04 | 1.
5025 let p1: Vec<u8> = (0..25).map(|_| bus.read_port(1)).collect();
5026 assert_eq!(&p1[0..8], &[0, 0, 1, 0, 0, 0, 0, 0], "pad 2: Select");
5027 assert_eq!(&p1[8..16], &[0, 0, 0, 1, 0, 0, 0, 0], "pad 4: Start");
5028 assert_eq!(&p1[16..24], &[0, 0, 1, 0, 0, 0, 0, 0], "signature 0x04");
5029 assert_eq!(p1[24], 1);
5030 }
5031
5032 #[test]
5033 fn four_score_state_round_trips_through_save_state() {
5034 let mut bus = test_bus();
5035 bus.set_four_score(true);
5036 bus.set_buttons(2, Buttons::B | Buttons::A); // pad 3
5037 bus.set_buttons(3, Buttons::START); // pad 4
5038 strobe(&mut bus);
5039 let _ = bus.read_port(0); // advance idx[0] off zero
5040 let blob = crate::bus_snapshot::encode_bus(&bus);
5041
5042 let mut restored = test_bus();
5043 crate::bus_snapshot::decode_bus(&mut restored, &blob).unwrap();
5044 assert!(restored.four_score());
5045 assert_eq!(restored.controller(2).buttons(), Buttons::B | Buttons::A);
5046 assert_eq!(restored.controller(3).buttons(), Buttons::START);
5047 }
5048
5049 #[test]
5050 fn override_nt_addr_maps_per_mirroring() {
5051 use rustynes_mappers::Mirroring;
5052 // Logical tables $2000/$2400/$2800/$2C00, offset 0.
5053 // Horizontal: tables 0/1 -> bank 0, 2/3 -> bank 1.
5054 assert_eq!(override_nt_addr(Mirroring::Horizontal, 0x2000), 0x000);
5055 assert_eq!(override_nt_addr(Mirroring::Horizontal, 0x2400), 0x000);
5056 assert_eq!(override_nt_addr(Mirroring::Horizontal, 0x2800), 0x400);
5057 assert_eq!(override_nt_addr(Mirroring::Horizontal, 0x2C00), 0x400);
5058 // Vertical: tables 0/2 -> bank 0, 1/3 -> bank 1.
5059 assert_eq!(override_nt_addr(Mirroring::Vertical, 0x2000), 0x000);
5060 assert_eq!(override_nt_addr(Mirroring::Vertical, 0x2400), 0x400);
5061 assert_eq!(override_nt_addr(Mirroring::Vertical, 0x2800), 0x000);
5062 assert_eq!(override_nt_addr(Mirroring::Vertical, 0x2C00), 0x400);
5063 // Local offset preserved.
5064 assert_eq!(override_nt_addr(Mirroring::Vertical, 0x2456), 0x456);
5065 }
5066
5067 #[test]
5068 fn mirroring_override_round_trips_through_save_state() {
5069 use rustynes_mappers::Mirroring;
5070 let mut bus = test_bus();
5071 assert_eq!(bus.mirroring_override(), None, "default is no override");
5072 bus.set_mirroring_override(Some(Mirroring::Vertical));
5073 let blob = crate::bus_snapshot::encode_bus(&bus);
5074 let mut restored = test_bus();
5075 crate::bus_snapshot::decode_bus(&mut restored, &blob).unwrap();
5076 assert_eq!(restored.mirroring_override(), Some(Mirroring::Vertical));
5077 }
5078
5079 #[test]
5080 fn a_short_bus_section_is_refused_at_every_length() {
5081 // v2.9.8 (BUS section version 2, ADR 0042). Version 1 decoded every
5082 // missing tail as its default, so a body cut short anywhere after the
5083 // first ~2 KiB loaded as an "older" layout. Version 2 has no older
5084 // layout to fall back to: the section version check refuses a v1
5085 // body before it reaches the decoder, so a short v2 body can only be
5086 // damage. Every cut is checked, not a representative, because the
5087 // failure this guards is a single trailing-default read left behind.
5088 let mut bus = test_bus();
5089 // Attach the largest device so the device decoder's own reads are in
5090 // the range the cuts walk through.
5091 bus.set_expansion_device(
5092 0,
5093 Some(crate::input_device::InputDevice::FamilyKeyboard(
5094 crate::input_device::FamilyKeyboardState::new(),
5095 )),
5096 );
5097 let blob = crate::bus_snapshot::encode_bus(&bus);
5098 crate::bus_snapshot::decode_bus(&mut test_bus(), &blob).expect("the whole body loads");
5099 for len in 0..blob.len() {
5100 assert!(
5101 crate::bus_snapshot::decode_bus(&mut test_bus(), &blob[..len]).is_err(),
5102 "a BUS body cut to {len} of {} bytes decoded cleanly",
5103 blob.len()
5104 );
5105 }
5106 }
5107
5108 #[test]
5109 fn trailing_bytes_after_a_bus_section_are_refused() {
5110 // The other half of a fixed layout: bytes past the last field are not
5111 // a newer tail this build can ignore, because the section version is
5112 // what announces a newer layout.
5113 let bus = test_bus();
5114 let mut blob = crate::bus_snapshot::encode_bus(&bus);
5115 blob.push(0);
5116 assert!(matches!(
5117 crate::bus_snapshot::decode_bus(&mut test_bus(), &blob),
5118 Err(SnapshotError::SectionInvalid { .. })
5119 ));
5120 }
5121
5122 #[test]
5123 fn an_unknown_expansion_device_tag_is_refused() {
5124 // Version 1 read an unknown tag as "no device" and carried on reading
5125 // the bytes behind it as the next field. Tag 0 is the empty port; the
5126 // first unassigned tag is 10.
5127 let bus = test_bus();
5128 let mut bad = crate::bus_snapshot::encode_bus(&bus);
5129 // The two device tags sit before a fixed tail with both ports empty:
5130 // mirroring override (1) + controller-run tail (22) + internal bus
5131 // (1) + the version-3 fields (DMC write-refusal latch 1, overclock
5132 // phase 1, `apu_cycle` 8) follow them, and port 1's tag is the second.
5133 //
5134 // v3.1.0: the version-3 bytes were missing from this sum for one
5135 // commit. With only the 1-byte latch appended the window still read
5136 // `[0, 0]` (the mirroring byte and port 1's tag), and the 10 written
5137 // into the mirroring byte was refused for ITS own reason, so the
5138 // test passed while testing something else. The assertion below
5139 // that the window holds the two empty tags is what caught it once
5140 // the overclock added 9 more bytes.
5141 let tail = 1 + 22 + 1 + (1 + 1 + 8);
5142 let port0_tag = bad.len() - tail - 2;
5143 assert_eq!(&bad[port0_tag..port0_tag + 2], &[0, 0]);
5144 bad[port0_tag] = 10;
5145 assert!(matches!(
5146 crate::bus_snapshot::decode_bus(&mut test_bus(), &bad),
5147 Err(SnapshotError::SectionInvalid { .. })
5148 ));
5149 }
5150
5151 #[test]
5152 fn an_out_of_range_oam_dma_index_is_rejected() {
5153 // Found by the v2.7.0 `save_state` fuzz target: an active OAM DMA
5154 // restored at index >= 256 never completes and overflows the `u16`.
5155 // Legal: 0..=255 while active, and 256 once the transfer has ended.
5156 let decode = |active: bool, addr: u16| {
5157 let mut bus = test_bus();
5158 bus.uni_oam_active = active;
5159 bus.uni_oam_addr = addr;
5160 let blob = crate::bus_snapshot::encode_bus(&bus);
5161 crate::bus_snapshot::decode_bus(&mut test_bus(), &blob)
5162 };
5163 assert!(decode(true, 255).is_ok(), "the last in-flight index loads");
5164 assert!(
5165 decode(false, 256).is_ok(),
5166 "the completed-transfer index loads"
5167 );
5168 for (active, addr) in [(true, 256), (true, 257), (false, 257), (false, u16::MAX)] {
5169 assert!(
5170 matches!(
5171 decode(active, addr),
5172 Err(SnapshotError::SectionInvalid { .. })
5173 ),
5174 "active={active} addr={addr} must be rejected"
5175 );
5176 }
5177 }
5178
5179 #[test]
5180 fn expansion_device_state_round_trips_through_save_state() {
5181 use crate::input_device::{InputDevice, VausState, ZapperState};
5182 let mut bus = test_bus();
5183 // Vaus on port 0, Zapper on port 1, with distinctive non-default state.
5184 bus.set_expansion_device(0, Some(InputDevice::Vaus(VausState::new())));
5185 bus.set_paddle(0, 0x3C, true);
5186 bus.set_expansion_device(1, Some(InputDevice::Zapper(ZapperState::new())));
5187 bus.set_zapper(1, 100, 50, true);
5188 let blob = crate::bus_snapshot::encode_bus(&bus);
5189
5190 let mut restored = test_bus();
5191 crate::bus_snapshot::decode_bus(&mut restored, &blob).unwrap();
5192 match restored.expansion_device(0) {
5193 Some(InputDevice::Vaus(v)) => {
5194 assert_eq!(v.position_raw(), 0x3C);
5195 assert!(v.fire_raw());
5196 }
5197 other => panic!("port 0 should be a Vaus, got {other:?}"),
5198 }
5199 match restored.expansion_device(1) {
5200 Some(InputDevice::Zapper(z)) => {
5201 assert_eq!(z.x_raw(), 100);
5202 assert_eq!(z.y_raw(), 50);
5203 assert!(z.trigger_raw());
5204 }
5205 other => panic!("port 1 should be a Zapper, got {other:?}"),
5206 }
5207 }
5208
5209 /// With the beam-relative Zapper model on, a debugger peek of `$4017` must
5210 /// return the SAME light contribution the CPU read produces — at the
5211 /// pre-render line and at a visible line — and must not advance device
5212 /// state.
5213 ///
5214 /// Regression pin for the `peek_port` parity fix: before it, `peek_port`
5215 /// fell through to the overlay's frame-granular `peek()` and could report a
5216 /// different light bit than `read_port` at the same instant. (This is the
5217 /// real defect the fix addressed; the separate `read_before_visible`
5218 /// conversion fallback is defensive, since `scanline()` is non-negative on
5219 /// every current region — pre-render is line 261 NTSC / 311 PAL, not -1.)
5220 #[test]
5221 fn temporal_zapper_debugger_peek_matches_cpu_read() {
5222 use crate::input_device::{InputDevice, ZapperState};
5223
5224 // $4017 bit 3 is the (inverted) light bit; the open-bus upper bits differ
5225 // between the read and peek paths, so compare only the device bit.
5226 const LIGHT: u8 = 0b0000_1000;
5227
5228 // The two models are constructed to DISAGREE, so the test fails if
5229 // `peek_port` does not mirror `read_port`'s temporal branch:
5230 // * frame model (`peek()` -> `ZapperState::read()`) reads `light_seen`,
5231 // which we force TRUE via `from_parts` -> reports light;
5232 // * temporal model (`read_at_scanline`) reads the current scanline. A
5233 // fresh bus sits on the pre-render line (261 NTSC), past the
5234 // photodiode hold window -> reports NO light.
5235 // So a peek that (wrongly) fell through to the frame `peek()` would
5236 // return light while the CPU read returns none. No framebuffer or
5237 // scanline poke is needed — the injected `light_seen` supplies the
5238 // divergence, and the default dark framebuffer keeps the temporal path
5239 // at no-light on every line anyway.
5240 let mut bus = test_bus();
5241 // from_parts(x, y, trigger, light_seen): trigger + light_seen both true.
5242 let zapper = ZapperState::from_parts(128, 12, true, true);
5243 bus.set_expansion_device(1, Some(InputDevice::Zapper(zapper)));
5244 bus.set_zapper_temporal_light(true);
5245
5246 assert!(
5247 bus.ppu.scanline() > 239,
5248 "fresh PPU is on the pre-render line"
5249 );
5250 let cpu = bus.read_port(1) & LIGHT;
5251 let peek = bus.peek_port(1) & LIGHT;
5252 assert_eq!(cpu, LIGHT, "temporal read at pre-render reports NO light");
5253 assert_eq!(
5254 peek, cpu,
5255 "debugger peek must match the CPU read, not the frame `peek()` \
5256 (which would report light from the injected light_seen)",
5257 );
5258
5259 // The peek must be side-effect-free: repeating it does not change the
5260 // answer (guards a regression where a peek routes through mutating state).
5261 assert_eq!(bus.peek_port(1) & LIGHT, peek);
5262 assert_eq!(bus.peek_port(1) & LIGHT, peek);
5263 }
5264
5265 #[test]
5266 fn a_contiguous_four_score_read_does_not_advance_the_chain() {
5267 // The adapter is one shift chain with the pads it multiplexes, so a
5268 // contiguous read -- `CLK` staying low across consecutive-cycle reads
5269 // of the same port -- must return the SAME bit from the SAME position,
5270 // exactly as a bare controller does.
5271 //
5272 // Before this guard the chain advanced on every read while the pads
5273 // advanced only on a rising edge, so it ran ahead of them: reaching the
5274 // pad-3 window after seven advances of pad 1 rather than eight, and
5275 // consuming two signature bits where the hardware returns one twice.
5276 let mut bus = test_bus();
5277 bus.set_four_score(true);
5278 bus.write(0x4016, 1);
5279 bus.write(0x4016, 0);
5280
5281 // Walk the whole 24-read sequence. At each position, a read on the very
5282 // next CPU cycle must repeat it, and must leave the chain where it was.
5283 for step in 0..24u8 {
5284 let first = bus.read_port(0);
5285 // Where the run's OWN rising edge left the chain. The contiguous
5286 // read must not move it from here — comparing against the position
5287 // before the first read would instead assert the first read does
5288 // not advance, which is a different (and wrong) claim.
5289 let idx_in_run = bus.four_score_idx[0];
5290 bus.cycle = bus.cycle.wrapping_add(1);
5291 let contiguous = bus.read_port(0);
5292 assert_eq!(
5293 first, contiguous,
5294 "step {step}: a contiguous read returned a different bit"
5295 );
5296 assert_eq!(
5297 bus.four_score_idx[0], idx_in_run,
5298 "step {step}: the chain advanced during a contiguous read"
5299 );
5300 // Break the run so the next iteration starts a fresh one.
5301 bus.cycle = bus.cycle.wrapping_add(4);
5302 }
5303 }
5304
5305 #[test]
5306 fn the_four_score_owed_edge_survives_a_save_state() {
5307 // `four_score_pending` is the adapter's half of the same state
5308 // `pending_shift` is for the pads. Restoring one without the other puts
5309 // the two halves of one shift chain on different positions.
5310 let mut bus = test_bus();
5311 bus.set_four_score(true);
5312 bus.write(0x4016, 1);
5313 bus.write(0x4016, 0);
5314 bus.read_port(0);
5315 assert_eq!(bus.four_score_pending(), [true, false]);
5316
5317 let blob = crate::bus_snapshot::encode_bus(&bus);
5318 let mut restored = test_bus();
5319 restored.set_four_score(true);
5320 crate::bus_snapshot::decode_bus(&mut restored, &blob).unwrap();
5321 assert_eq!(
5322 restored.four_score_pending(),
5323 [true, false],
5324 "the adapter resumed without the edge it owed"
5325 );
5326 }
5327
5328 /// Core audit v2.9.2 AUD-03. A CPU read of an address nothing decodes
5329 /// (`$5000` on NROM) returns the floating bus value, and the CPU latches
5330 /// that value like any other read: `nesdev_wiki/Open_bus_behavior.xhtml`
5331 /// ("when the CPU reads an address that no circuit decodes, all it sees on
5332 /// its data inputs is whatever was left to float on the data bus"). The
5333 /// `$4015` read's bit 5 then comes from it: `nesdev_wiki/APU.xhtml`
5334 /// ("Bit 5 is open bus ... the open bus value comes from the last cycle
5335 /// that did not read `$4015`").
5336 ///
5337 /// The two latches differ only after something drives the external bus
5338 /// alone: a DMC DMA fetch (`AccuracyCoin` `Internal Data Bus` Test 2), or
5339 /// an OAM-DMA put with the 6502 bus parked in `$4000-$401F`. So: a CPU
5340 /// read leaves both at `$00`, a DMC fetch floats `$20` onto the external
5341 /// bus, the CPU reads the undecoded `$5000` (and sees `$20`), then reads
5342 /// `$4015`. The last non-`$4015` cycle carried `$20`, so bit 5 is set.
5343 /// Before the fix the unmapped arm returned early and skipped the
5344 /// internal-bus update, so bit 5 still came from the `$00` read before
5345 /// the DMC fetch -- unlike the `$4000-$401F` undecoded arm, which always
5346 /// updated it.
5347 #[test]
5348 fn an_unmapped_cartridge_read_latches_the_floating_value_onto_the_internal_bus() {
5349 let mut rom = Vec::with_capacity(16 + 0x4000 + 0x2000);
5350 rom.extend_from_slice(b"NES\x1A");
5351 rom.push(1); // 16 KiB PRG
5352 rom.push(1); // 8 KiB CHR
5353 rom.extend_from_slice(&[0u8; 10]);
5354 let mut prg = [0u8; 0x4000];
5355 prg[0] = 0x20; // $C000 (and $8000): the DMC sample byte
5356 rom.extend_from_slice(&prg);
5357 rom.extend_from_slice(&[0u8; 0x2000]);
5358 let mut bus = SystemBus::new(&rom).expect("synthetic NROM parses");
5359 assert!(
5360 bus.mapper.cpu_read_unmapped(0x5000),
5361 "fixture: $5000 floats"
5362 );
5363
5364 bus.ram[0] = 0x00;
5365 assert_eq!(bus.raw_cpu_read(0x0000), 0x00);
5366 // A DMC DMA sample fetch, as `dmc_dma_step_impl` performs it.
5367 bus.in_dmc_dma = true;
5368 assert_eq!(bus.dmc_dma_read(0xC000, 0x8000), 0x20);
5369 bus.in_dmc_dma = false;
5370 assert_eq!(bus.open_bus, 0x20, "the DMC fetch drove the external bus");
5371 assert_eq!(bus.internal_data_bus, 0x00, "but not the internal one");
5372
5373 assert_eq!(bus.raw_cpu_read(0x5000), 0x20, "the undecoded read floats");
5374 assert_eq!(
5375 bus.internal_data_bus, 0x20,
5376 "the CPU latched the floating value it read"
5377 );
5378 assert_eq!(
5379 bus.raw_cpu_read(0x4015) & 0x20,
5380 0x20,
5381 "$4015 bit 5 comes from the last non-$4015 cycle: the $5000 read"
5382 );
5383 }
5384
5385 /// iNES image for mapper `mapper` with `prg_16k` x 16 KiB of PRG filled
5386 /// with `$AA` and CHR-RAM.
5387 fn prg_filled_rom(mapper: u8, prg_16k: u8) -> Vec<u8> {
5388 let mut rom = Vec::new();
5389 rom.extend_from_slice(b"NES\x1A");
5390 rom.push(prg_16k);
5391 rom.push(0); // CHR-RAM
5392 rom.push((mapper & 0x0F) << 4);
5393 rom.push(mapper & 0xF0);
5394 rom.extend_from_slice(&[0u8; 8]);
5395 rom.resize(16 + usize::from(prg_16k) * 0x4000, 0xAA);
5396 rom
5397 }
5398
5399 /// Two boards can leave `$8000-$FFFF` undriven: *Action 52* (mapper 228)
5400 /// with its absent third chip selected, and the Golden Game multicart
5401 /// (mapper 235) with an empty socket selected. Both must read open bus
5402 /// there, not ROM. Regression for a v3.2.0 import that consulted
5403 /// `cpu_read_unmapped` only below `$8000` (a hot-path shortcut), which made
5404 /// both read the ROM byte (`$AA` here) instead of the floating `$5A`.
5405 #[test]
5406 fn boards_that_unmap_prg_rom_read_open_bus_above_8000() {
5407 // 228: 1.5 MiB = chips 0, 1, 3. `$9000` selects chip 2 (addr bits
5408 // 12-11 = 0b10), the one the image does not carry.
5409 let mut bus = SystemBus::new(&prg_filled_rom(228, 96)).expect("228 parses");
5410 assert_eq!(bus.raw_cpu_read(0x8000), 0xAA, "fixture: chip 0 is ROM");
5411 bus.mapper.cpu_write(0x9000, 0x00);
5412 bus.ram[0] = 0x5A;
5413 assert_eq!(bus.raw_cpu_read(0x0000), 0x5A);
5414 assert_eq!(
5415 bus.raw_cpu_read(0x8000),
5416 0x5A,
5417 "228 absent chip floats the bus"
5418 );
5419
5420 // 235: a 1 MiB image fills socket 0 only; `$8100` selects socket 1.
5421 let mut bus = SystemBus::new(&prg_filled_rom(235, 64)).expect("235 parses");
5422 assert_eq!(bus.raw_cpu_read(0x8000), 0xAA, "fixture: socket 0 is ROM");
5423 bus.mapper.cpu_write(0x8100, 0x00);
5424 bus.ram[0] = 0x5A;
5425 assert_eq!(bus.raw_cpu_read(0x0000), 0x5A);
5426 assert_eq!(
5427 bus.raw_cpu_read(0xC000),
5428 0x5A,
5429 "235 empty socket floats the bus"
5430 );
5431 }
5432
5433 #[test]
5434 fn internal_data_bus_round_trips_through_save_state() {
5435 // v2.8.0 (libretro audit §2.4). The 2A03's internal data bus is a
5436 // separate latch from the external open bus: a DMC DMA fetch drives
5437 // the external bus only, so across a DMC halt the two differ, and a
5438 // `$4015` read returns bit 5 from the INTERNAL one. It was not in the
5439 // BUS section, so a restore left whatever the running machine held --
5440 // a value from a discarded timeline under run-ahead and rollback.
5441 // Found by the widened `snapshot_schema_audit`, which now covers the
5442 // bus. The two latches are set to different values here so a decoder
5443 // that restored one from the other would fail.
5444 let mut bus = test_bus();
5445 bus.open_bus = 0x00;
5446 bus.internal_data_bus = 0x20;
5447 let blob = crate::bus_snapshot::encode_bus(&bus);
5448 let mut restored = test_bus();
5449 restored.internal_data_bus = 0xFF;
5450 crate::bus_snapshot::decode_bus(&mut restored, &blob).unwrap();
5451 assert_eq!(restored.internal_data_bus, 0x20);
5452 assert_eq!(restored.open_bus, 0x00);
5453 }
5454
5455 #[test]
5456 fn power_pad_state_round_trips_through_save_state() {
5457 use crate::input_device::{InputDevice, PowerPadState};
5458 let mut bus = test_bus();
5459 bus.set_expansion_device(1, Some(InputDevice::PowerPad(PowerPadState::new())));
5460 bus.set_power_pad(1, 0b1010_0101_0011);
5461 let blob = crate::bus_snapshot::encode_bus(&bus);
5462 let mut restored = test_bus();
5463 crate::bus_snapshot::decode_bus(&mut restored, &blob).unwrap();
5464 match restored.expansion_device(1) {
5465 Some(InputDevice::PowerPad(p)) => {
5466 assert_eq!(p.buttons_raw(), 0b1010_0101_0011);
5467 }
5468 other => panic!("expected a Power Pad on port 1, got {other:?}"),
5469 }
5470 }
5471
5472 #[test]
5473 fn snes_mouse_state_round_trips_through_save_state() {
5474 use crate::input_device::{InputDevice, SnesMouseState};
5475 let mut bus = test_bus();
5476 bus.set_expansion_device(0, Some(InputDevice::SnesMouse(SnesMouseState::new())));
5477 bus.set_snes_mouse(0, -7, 9, true, false, 2);
5478 let blob = crate::bus_snapshot::encode_bus(&bus);
5479 let mut restored = test_bus();
5480 crate::bus_snapshot::decode_bus(&mut restored, &blob).unwrap();
5481 match restored.expansion_device(0) {
5482 Some(InputDevice::SnesMouse(m)) => {
5483 assert_eq!(m.dx_raw(), -7);
5484 assert_eq!(m.dy_raw(), 9);
5485 assert!(m.left_raw());
5486 assert!(!m.right_raw());
5487 assert_eq!(m.sensitivity_raw(), 2);
5488 }
5489 other => panic!("expected a SNES mouse on port 0, got {other:?}"),
5490 }
5491 }
5492
5493 #[test]
5494 fn family_keyboard_state_round_trips_through_save_state() {
5495 use crate::input_device::{FamilyKeyboardState, InputDevice};
5496 let mut bus = test_bus();
5497 bus.set_expansion_device(
5498 1,
5499 Some(InputDevice::FamilyKeyboard(FamilyKeyboardState::new())),
5500 );
5501 let keys = [0x01, 0x10, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00];
5502 bus.set_family_keyboard(1, keys);
5503 let blob = crate::bus_snapshot::encode_bus(&bus);
5504 let mut restored = test_bus();
5505 crate::bus_snapshot::decode_bus(&mut restored, &blob).unwrap();
5506 match restored.expansion_device(1) {
5507 Some(InputDevice::FamilyKeyboard(k)) => {
5508 assert_eq!(k.keys_raw(), keys);
5509 }
5510 other => panic!("expected a Family BASIC keyboard on port 1, got {other:?}"),
5511 }
5512 }
5513}
5514
5515#[cfg(test)]
5516mod partial_drive_tests {
5517 use super::*;
5518
5519 /// Sachen SA-020A (mapper 150): the `$4101` data register drives D2-D0
5520 /// only (`nesdev_wiki/INES_Mapper_150.xhtml`), so D7-D3 keep whatever
5521 /// was floating on the bus. Core audit section 4.5 found them read as 0,
5522 /// which the bus then latched.
5523 #[test]
5524 fn a_sachen_register_read_keeps_the_floating_high_bits() {
5525 let mut rom = Vec::with_capacity(16 + 0x8000 + 0x2000);
5526 rom.extend_from_slice(b"NES\x1A");
5527 rom.push(2); // 32 KiB PRG
5528 rom.push(1); // 8 KiB CHR
5529 rom.push(0x60); // mapper 150: low nibble 6
5530 rom.push(0x90); // high nibble 9
5531 rom.extend_from_slice(&[0u8; 8]);
5532 rom.resize(16 + 0x8000 + 0x2000, 0);
5533 let mut bus = SystemBus::new(&rom).expect("mapper 150 parses");
5534 bus.mapper.cpu_write(0x4100, 0x05); // select register 5
5535 bus.mapper.cpu_write(0x4101, 0x03); // R5 = 3
5536 bus.open_bus = 0xA8; // the last value driven on the bus
5537 let v = bus.raw_cpu_read(0x4101);
5538 assert_eq!(v & 0x07, 0x03, "the driven bits are the register");
5539 assert_eq!(v & 0xF8, 0xA8, "the undriven bits are the floating latch");
5540 assert_eq!(bus.open_bus, v, "and the latch keeps them");
5541 }
5542}
5543
5544#[cfg(test)]
5545mod n163_nametable_tests {
5546 use super::*;
5547
5548 /// Namco 163 (mapper 19) with 32 KiB PRG and 8 KiB CHR-ROM whose 1 KiB
5549 /// page `p` is filled with `0x40 + p`. The CPU spins on `JMP $E000` with
5550 /// rendering off; two frames take the PPU past its post-power-on window,
5551 /// in which `$2006` writes are ignored.
5552 fn n163() -> crate::Nes {
5553 let mut rom = Vec::with_capacity(16 + 0x8000 + 0x2000);
5554 rom.extend_from_slice(b"NES\x1A");
5555 rom.push(2); // 32 KiB PRG
5556 rom.push(1); // 8 KiB CHR-ROM
5557 rom.push(0x31); // mapper 19 low nibble 3, vertical
5558 rom.push(0x10); // high nibble 1
5559 rom.extend_from_slice(&[0u8; 8]);
5560 let mut prg = alloc::vec![0u8; 0x8000];
5561 // The last 8 KiB is fixed at $E000: `JMP $E000`, vectors -> $E000.
5562 prg[0x6000..0x6003].copy_from_slice(&[0x4C, 0x00, 0xE0]);
5563 prg[0x7FFA..0x8000].copy_from_slice(&[0x00, 0xE0, 0x00, 0xE0, 0x00, 0xE0]);
5564 rom.extend_from_slice(&prg);
5565 for page in 0..8u8 {
5566 rom.extend(core::iter::repeat_n(0x40 + page, 0x400));
5567 }
5568 let mut nes = crate::Nes::from_rom(&rom).expect("mapper 19 parses");
5569 nes.run_frame();
5570 nes.run_frame();
5571 nes
5572 }
5573
5574 /// A `$2007` write, through the PPU's own register path.
5575 fn poke(nes: &mut crate::Nes, addr: u16, value: u8) {
5576 let bus = nes.bus_mut();
5577 let [hi, lo] = addr.to_be_bytes();
5578 bus.cpu_write(0x2006, hi);
5579 bus.cpu_write(0x2006, lo);
5580 bus.cpu_write(0x2007, value);
5581 }
5582
5583 // The PPU reaches nametables only through `nametable_fetch` /
5584 // `nametable_write` / `nametable_address`. v2.7.2's first cut implemented
5585 // N163's nametable select in `ppu_read`/`ppu_write`, which the PPU never
5586 // calls for `$2000-$3EFF`, and its unit tests called `ppu_read` directly,
5587 // so none of this was reachable in the emulator (PR #550 review).
5588
5589 #[test]
5590 fn a_chr_rom_nametable_page_is_fetched_and_read_only() {
5591 let mut nes = n163();
5592 nes.bus_mut().mapper.cpu_write(0xC000, 0x03); // quadrant 0 -> CHR-ROM page 3
5593 assert_eq!(nes.bus_mut().debug_peek_ppu(0x2005), 0x43);
5594 poke(&mut nes, 0x2005, 0x99);
5595 assert_eq!(
5596 nes.bus_mut().debug_peek_ppu(0x2005),
5597 0x43,
5598 "CHR-ROM is read-only"
5599 );
5600 }
5601
5602 #[test]
5603 fn the_nametable_registers_pick_the_ciram_page() {
5604 let mut nes = n163();
5605 nes.bus_mut().mapper.cpu_write(0xC000, 0xE1); // quadrant 0 -> CIRAM B
5606 nes.bus_mut().mapper.cpu_write(0xC800, 0xE1); // quadrant 1 -> CIRAM B
5607 poke(&mut nes, 0x2010, 0x77);
5608 assert_eq!(
5609 nes.bus_mut().debug_peek_ppu(0x2410),
5610 0x77,
5611 "both quadrants are page B"
5612 );
5613 }
5614
5615 #[test]
5616 fn ciram_mapped_as_chr_sees_nametable_writes() {
5617 let mut nes = n163();
5618 nes.bus_mut().mapper.cpu_write(0xE800, 0x00); // CIRAM-as-CHR allowed in both halves
5619 nes.bus_mut().mapper.cpu_write(0x8000, 0xE0); // pattern $0000-$03FF -> CIRAM A
5620 nes.bus_mut().mapper.cpu_write(0xC000, 0xE0); // quadrant 0 -> CIRAM A
5621 poke(&mut nes, 0x2005, 0x5C);
5622 assert_eq!(
5623 nes.bus_mut().debug_peek_ppu(0x0005),
5624 0x5C,
5625 "one RAM, two windows"
5626 );
5627 poke(&mut nes, 0x0006, 0xA7);
5628 assert_eq!(
5629 nes.bus_mut().debug_peek_ppu(0x2006),
5630 0xA7,
5631 "and the other way"
5632 );
5633 }
5634}