Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

x-nes

A cycle-accurate NES emulator written in Rust, targeting everything from microcontrollers to modern desktops.

What is an Emulator?

An emulator is a program that mimics the behavior of a hardware system. For the NES, this means simulating:

  • The CPU (6502) — executes game code, handles interrupts
  • The PPU — generates the video signal, scanlines, sprites, and scrolling
  • The APU — generates the audio signal (5 channels: 2 pulse, triangle, noise, DMC)
  • The Memory Bus — routes data between components and the cartridge mapper
  • The Mapper — cartridge chip that provides bank switching, IRQs, extra RAM, and custom features

All running in lockstep, synchronized to the NES’s master clock.

What is x-nes?

x-nes is a from-scratch implementation of the NES hardware in Rust. It is:

  • Cycle-accurate — the CPU follows the expected cycle timing for each instruction, including page-cross penalties
  • no_std — no operating system dependencies, so it can run on bare metal
  • Portable — the same core code is shared across desktop and embedded targets
  • Practical — 8 mappers implemented (NROM, MMC1, UxROM, CNROM, MMC3, MMC5, AxROM, GxROM), covering ~90% of the NES library
  • Full-featured APU — all 5 audio channels with frame sequencer, sweep units, envelope generators, and DMC DMA

The current implementation passes 86% of the AccuracyCoin test suite (86/141 tests), with all Blargg CPU tests passing cleanly.

Current Status

ComponentStatus
CPU (all 151 opcodes)✅ Cycle-accurate, all unofficial opcodes
PPU rendering✅ On-the-fly renderer with NMI edge detection
PPU scrolling✅ $2005/$2006 with loopy-V register, fine X/Y
APU (5 channels)⚠️ Functional, timing needs refinement
Mapper 0 (NROM)✅ Complete
Mapper 1 (MMC1)✅ Complete
Mapper 2 (UxROM)✅ Complete
Mapper 3 (CNROM)✅ Complete
Mapper 4 (MMC3)✅ Complete — SMB3, Mega Man 3, Kirby support
Mapper 5 (MMC5)✅ Complete — Castlevania III support
Mapper 7 (AxROM)✅ Complete
Mapper 66 (GxROM)✅ Complete
Open bus emulation✅ With capacitive decay
NMI penultimate cycle✅ Deferred NMI from $2000 writes
iNES 2.0 headers✅ Correct detection
AccuracyCoin⚠️ 86/141 (61%)
Expansion audio (MMC5)❌ Not yet implemented

Highlights

MMC5 Support

x-nes is one of the few emulators with working MMC5 support, enabling Castlevania III and other rare MMC5 games:

  • 4 PRG modes (32KB, 2×16KB, 16KB+8KB+8KB, 4×8KB) with up to 1MB PRG ROM
  • 4 CHR modes (8KB, 4KB, 2KB, 1KB) with separate BG/sprite banking and up to 1MB CHR ROM
  • ExRAM with 4 operating modes (extra nametable, extended attributes, CPU RAM, read-only)
  • Scanline IRQ for split-screen effects
  • Hardware 8×8→16 multiplier at $5205/$5206
  • Fill mode and per-nametable source mapping via $5105

On-the-Fly Rendering

Instead of emulating the PPU’s internal shift registers (which would require complex tile caching), x-nes computes each pixel directly from scroll state snapshots. This approach:

  • Simplifies the renderer significantly
  • Naturally supports MMC5 extended attributes (per-tile CHR bank + palette)
  • Uses render_v snapshots at prerender cycle 0 and cycle 257

Want to Contribute?

x-nes is an open-source project aiming to be the most accurate NES emulator library in Rust. We’re actively looking for help with:

  • Audio accuracy — APU timing and tone refinement
  • PPU edge cases — sprite evaluation corner cases, OAM corruption
  • DMA timing — DMC DMA + OAM DMA interaction
  • Expansion audio — MMC5 extra pulse channels, VRC6, etc.
  • New mappers — VRC series, FME-7, Namco 163, etc.
  • RetroArch integration — libretro core support

Contributing guide | Issue tracker

How This Book is Organized

ChapterWhat You’ll Learn
1. ArchitectureSystem design, tick function, PPU sync, open bus
2. The 6502 CPUCPU registers, flags, stack, memory model
3. Instruction SetAll 56 official + unofficial opcodes, 13 addressing modes
4. Memory & I/ONES memory map, PPU/APU registers, OAM DMA
5. PPUVideo generation, scanlines, scrolling, NMI, on-the-fly rendering
6. Audio & ROMAPU channels, frame sequencer, iNES format
7. MappersAll 8 mappers, bank switching, IRQs, CHR banking
8. MMC5 Deep DiveComplete register map, ExRAM modes, extended attributes
9. DebuggingCPU/PPU/mapper debugging, crash triage, diagnostic tools
10. Graphics DebuggingVisual symptom diagnosis, pixel inspection, frame comparison
11. PerformanceCross-platform design, optimization techniques
12. Building & TestingBuild targets, test suite, profiling, CI

Each chapter explains the hardware first, then shows the Rust implementation. The code is designed to match the hardware behavior as closely as possible.

Architecture Overview

The NES is a carefully balanced system where three processors — CPU, PPU, and APU — run in lockstep. x-nes models this with a synchronous tick-based architecture.

Data Flow

┌──────────────┐    opcode      ┌─────────┐
│     Bus       │◄────────────►│   CPU   │
│               │               │         │
│  ┌──────────┐ │   address     │ 6502    │
│  │ RAM 2KB  │ │   data        │ core    │
│  ├──────────┤ │               └─────────┘
│  │ PPU regs │ │   cycles × 3      │
│  │ $2000-7  │ │◄──────────────────┘
│  ├──────────┤ │                   │
│  │ APU regs │ │   cycles          │
│  │ $4000-17 │ │◄──────────────────┘
│  ├──────────┤ │                   │
│  │ Mapper   │ │   tick() in lib.rs
│  │ (PRG ROM,│ │   orchestrates all
│  │  CHR ROM,│ │   three components
│  │  ExRAM)  │ │
│  └──────────┘ │
└──────────────┘

The Tick Function

The heart of the emulator is in lib.rs. The current implementation is more sophisticated than early versions, handling penultimate-cycle NMI sampling, SH instruction DMC timing, and deferred NMI from $2000 writes:

#![allow(unused)]
fn main() {
pub fn tick(cpu: &mut CpuRp2a03, bus: &mut Bus) -> u8 {
    let start_cycle = bus.cpu_cycle;
    let mut cycles_extra = 0u8;

    // 1. Fetch opcode from the address PC points to
    let opcode = bus.read(cpu.pc());
    cpu.set_pc(cpu.pc().wrapping_add(1));

    // 2. Set up penultimate-cycle NMI sampling point
    let base_cycles = BASE_CYCLES[opcode as usize] as u64;
    bus.penultimate_sample_cycle = start_cycle + base_cycles.saturating_sub(2);

    // 3. Handle CLI/SEI one-instruction IRQ latency
    let is_cli_sei = opcode == 0x58 || opcode == 0x78;
    let i_flag_for_irq = if is_cli_sei {
        cpu.get_flag(FLAG_INTERRUPT)
    } else { false };

    // 4. Pre-tick APU and handle SH instruction DMC saving
    bus.apu.tick(base_cycles as u16);

    // 5. Dispatch instruction — TABLE[opcode](cpu, bus)
    let cycles = TABLE[opcode as usize](cpu, bus) as u64;

    // 6. Sync PPU for remaining cycles (catch_up_ppu uses cpu_cycle)
    bus.cpu_cycle = start_cycle + cycles;
    bus.catch_up_ppu();

    // 7. Tick remaining APU cycles
    if cycles > base_cycles {
        bus.apu.tick_without_dmc((cycles - base_cycles) as u16);
    }

    // 8. Handle SH instruction DMC post-tick
    // ... (special handling for SHA/SHS/SHY/SHX opcodes)

    // 9. Check NMI (from VBlank or deferred $2000 write)
    if bus.ppu.nmi_from_vblank || bus.ppu.nmi_deferred_pending {
        bus.ppu.nmi_from_vblank = false;
        bus.ppu.nmi_deferred_pending = false;
        nmi(cpu, bus);
    }
    // 10. Check IRQ (with CLI/SEI latency)
    else if !cpu.get_flag(FLAG_INTERRUPT) && bus.poll_irq() {
        irq(cpu, bus);
    }

    (cycles + cycles_extra as u64) as u8
}
}

PPU Synchronization

The PPU runs at 3× the CPU speed. x-nes uses a catch-up model:

  • bus.cpu_cycle tracks the current CPU cycle globally
  • bus.ppu_sync_cycle tracks the last cycle the PPU was synced to
  • When the bus accesses PPU registers or the CPU finishes an instruction, catch_up_ppu() advances the PPU by (cpu_cycle - ppu_sync_cycle) * 3 dots
#![allow(unused)]
fn main() {
pub fn catch_up_ppu(&mut self) {
    if self.cpu_cycle > self.ppu_sync_cycle {
        let ppu_dots = (self.cpu_cycle - self.ppu_sync_cycle) * 3;
        self.ppu.tick_batch(ppu_dots as u16, &mut self.mapper);
        self.ppu_sync_cycle = self.cpu_cycle;
    }
}
}

This is called on every bus read/write so that PPU register access always sees up-to-date PPU state.

NES Timing

The NES runs on a ~21.47727 MHz master clock, divided into:

ComponentDivisorFrequencyRatio per CPU cycle
CPU/12~1.79 MHz1
PPU/4~5.37 MHz3
APU/12~1.79 MHz1

So for every CPU cycle, the PPU advances 3 dots. The APU runs at roughly the same rate as the CPU.

Module Responsibilities

ModuleRole
cpu.rsRegister file, flag manipulation, PC management
ops.rs256-entry jump table with all instruction implementations
bus.rsMemory routing, PPU catch-up sync, OAM DMA, open bus emulation
ppu/mod.rsPPU state machine, scanline timing, NMI edge detection
ppu/render.rsOn-the-fly background and sprite pixel rendering
ppu/registers.rsPPU register read/write ($2000-$2007)
ppu/bus.rsVRAM address space, NT mapping, palette access, open bus decay
apu/mod.rsAPU state, frame sequencer, mixer, register I/O
apu/pulse.rsSquare wave channels (pulse 1, pulse 2)
apu/triangle.rsTriangle wave channel
apu/noise.rsNoise channel (LFSR)
apu/dmc.rsDelta Modulation Channel (DMC)
rom.rsiNES 1.0/2.0 ROM parser, mapper dispatch
mapper/mod.rsMapper trait, Mapper enum, dispatch methods
mapper/*.rsIndividual mapper implementations (8 mappers)
controller.rsGamepad input (standard NES controller)
clock.rsMaster/CPU/PPU cycle conversion
address.rsMemory region classification helpers
interrupt.rsVector address constants (NMI=$FFFA, RESET=$FFFC, IRQ=$FFFE)

Open Bus Emulation

x-nes emulates the NES open bus behavior — when reading unmapped addresses, the last value on the data bus is returned (not 0). The bus also simulates capacitive decay:

#![allow(unused)]
fn main() {
pub fn get_open_bus(&self) -> u8 {
    const DECAY_CYCLES: u64 = 5_000_000; // ~1 second
    let elapsed = self.tick_count.saturating_sub(self.last_bus_write_tick);
    if elapsed >= DECAY_CYCLES { return 0; }
    let decay = (elapsed * 255 / DECAY_CYCLES) as u8;
    self.last_bus_value & !(decay | decay >> 1 | decay >> 2)
}
}

NMI Timing (Penultimate Cycle Rule)

The real NES samples NMI on the penultimate cycle (second-to-last) of each instruction. This means if a write to $2000 enables NMI on the last cycle of an instruction, the NMI is deferred to the NEXT instruction. x-nes implements this via:

#![allow(unused)]
fn main() {
bus.penultimate_sample_cycle = start_cycle + base_cycles.saturating_sub(2);
}

On each bus access, if the current cycle matches the penultimate cycle and NMI is latched, the NMI is deferred:

#![allow(unused)]
fn main() {
fn sample_penultimate(&mut self) {
    if self.cpu_cycle > 0
        && (self.cpu_cycle - 1) == self.penultimate_sample_cycle
        && self.ppu.nmi_latched
    {
        self.ppu.nmi_latched = false;
        self.ppu.nmi_deferred_pending = true;
    }
}
}

Mapper Architecture

Mappers use a trait-based dispatch system. See the Mappers Overview for full details.

no_std Design

The emulator uses #![cfg_attr(not(any(test, feature = "std")), no_std)]. When std is enabled (tests, examples), the emulator can use Vec and heap allocation. On no_std targets, all state is stack-allocated or uses alloc for Vec-based PRG/CHR storage.

1. The 6502 CPU

The 6502 is an 8-bit microprocessor designed by MOS Technology in 1975. It powered the NES, Commodore 64, Apple II, and countless other systems. Understanding its architecture is the first step to building an emulator.

1.1 CPU Registers

The 6502 has six registers. In the real chip, these are physical storage locations inside the processor. In our emulator, they are fields in a struct.

Register   Size    Name
─────────────────────────────
PC         16-bit  Program Counter
A          8-bit   Accumulator
X          8-bit   Index Register X
Y          8-bit   Index Register Y
ST         8-bit   Stack Pointer
SR         8-bit   Status Register (flags)

1.1.1 Program Counter (PC)

The PC holds the address of the next instruction to execute. When the CPU finishes one instruction, it reads from the address in PC, executes, and advances PC past that instruction.

Start:    PC → $C000  (read opcode here)
After:    PC → $C001  (PC advanced by 1)

In x-nes, PC is stored as two bytes (little-endian) at the start of our CPU struct:

#![allow(unused)]
fn main() {
pub struct CpuRp2a03 {
    bytes: [u8; 7],
    // [0..2] = PC (low byte at index 0, high byte at index 1)
    // [2]    = A
    // [3]    = X
    // [4]    = Y
    // [5]    = ST
    // [6]    = SR
}
}

The PC value is reconstructed from the two bytes:

#![allow(unused)]
fn main() {
pub fn pc(&self) -> u16 {
    u16::from_le_bytes([self.bytes[0], self.bytes[1]])
}
}

Why 7 bytes? The 6502’s registers total exactly 7 bytes: one 16-bit value (PC) and five 8-bit values (A, X, Y, ST, SR). By storing them as raw bytes, we avoid alignment issues and keep the struct compact.

1.1.2 Accumulator (A)

The accumulator is the primary working register. All arithmetic (addition, subtraction) and logical operations (AND, OR, XOR) use it. Most data movement involves loading values into A or storing A to memory.

InstructionWhat it does
LDA #$05Load value 5 into A
ADC #$03Add 3 to A (with carry)
STA $0200Store A to address $0200

1.1.3 Index Registers (X and Y)

X and Y serve multiple purposes:

  • Indexing: Adding to memory addresses for array access
  • Counting: Loop counters (DEX, DEY, INX, INY)
  • Copying: Transferring values to/from A (TAX, TAY, TXA, TYA)

X and Y are similar but not identical — some instructions work only with X, others only with Y.

1.1.4 Stack Pointer (ST)

The 6502 uses a hardware stack at $0100-$01FF. The stack pointer holds the low byte of the current stack address. It starts at $FF (meaning the first push goes to $01FF) and grows downward.

Stack operations:
  PHA  → Push A onto stack (ST decrements)
  PLA  → Pull value from stack into A (ST increments)
  JSR  → Push return address, jump to subroutine
  RTS  → Pull return address from stack, return from subroutine

In x-nes, push and pull are straightforward:

#![allow(unused)]
fn main() {
fn push(cpu: &mut CpuRp2a03, bus: &mut Bus<'_>, val: u8) {
    bus.write(0x0100 | cpu.st() as u16, val);
    cpu.set_st(cpu.st().wrapping_sub(1));
}

fn pull(cpu: &mut CpuRp2a03, bus: &mut Bus<'_>) -> u8 {
    cpu.set_st(cpu.st().wrapping_add(1));
    bus.read(0x0100 | cpu.st() as u16)
}
}

The stack page ($0100) is fixed in hardware. 0x0100 | cpu.st() as u16 assembles the full address.

1.1.5 Status Register (SR)

The status register contains 8 flag bits that change based on instruction results:

Bit  7     6     5     4     3     2     1     0
    ┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
    │  N  │  V  │  -  │  B  │  D  │  I  │  Z  │  C  │
    └─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘
BitNameMeaning
0CCarry — set if arithmetic result exceeds 255 (or borrow in subtraction)
1ZZero — set if result is zero
2IInterrupt Disable — if set, IRQ is ignored
3DDecimal Mode — if set, ADC/SBC use BCD arithmetic
4BBreak — set when BRK instruction executes
5—Unused (always reads as 1 on real hardware)
6VOverflow — set if signed arithmetic overflows
7NNegative — set if bit 7 of result is 1

In x-nes, flags are stored as bit constants:

#![allow(unused)]
fn main() {
pub const FLAG_CARRY: u8    = 0b0000_0001;
pub const FLAG_ZERO: u8     = 0b0000_0010;
pub const FLAG_INTERRUPT: u8 = 0b0000_0100;
pub const FLAG_DECIMAL: u8  = 0b0000_1000;
pub const FLAG_BREAK: u8    = 0b0001_0000;
pub const FLAG_OVERFLOW: u8 = 0b0100_0000;
pub const FLAG_NEGATIVE: u8 = 0b1000_0000;
}

Reading and setting individual flags:

#![allow(unused)]
fn main() {
pub fn get_flag(&self, flag: u8) -> bool {
    self.bytes[6] & flag != 0
}

pub fn set_flag(&mut self, flag: u8, set: bool) {
    let mask = set as u8;
    self.bytes[6] = (self.bytes[6] & !flag) | (mask * flag);
}
}

When set is true, mask is 1 and mask * flag equals flag — the flag bit becomes 1. When set is false, mask is 0 and mask * flag is 0 — the flag bit becomes 0. No if statement needed.

1.2 The NES Memory Model

The CPU sees a 16-bit address space (64KB). The NES divides this into regions:

Address Range    Size    Region
──────────────────────────────────────
$0000-$07FF     2KB     Internal CPU RAM
$0800-$1FFF     —       RAM Mirrors (repeats every 2KB)
$2000-$3FFF     —       PPU Registers (repeats every 8 bytes)
$4000-$401F     32B     APU & I/O Registers
$4020-$FFFF     —       Cartridge PRG-ROM

1.2.1 RAM and Mirroring

The NES has only 2KB of CPU RAM, but it appears to occupy 8KB of address space ($0000-$1FFF). Addresses $0800-$1FFF are mirrors — they reference the same physical RAM cells. Our emulator handles this with a bitmask:

#![allow(unused)]
fn main() {
pub fn read(&mut self, addr: u16) -> u8 {
    let top = (addr >> 12) as u8;
    match top {
        0 | 1 => self.ram[(addr & 0x07FF) as usize],
        // $0000-$1FFF: all redirected to 2KB RAM via mask
}

addr & 0x07FF maps all addresses in the $0000-$1FFF range to 0-2047.

1.2.2 Cartridge ROM

Games are stored on cartridges containing ROM chips. The PRG-ROM is mapped to $4020-$FFFF. Most NES games use 16KB or 32KB of PRG-ROM. For 16KB cartridges, the ROM is mirrored — it appears at both $8000-$BFFF and $C000-$FFFF.

#![allow(unused)]
fn main() {
fn read_prg(&self, addr: u16) -> u8 {
    if addr < 0x8000 || self.prg.is_empty() {
        return 0;
    }
    self.prg[((addr - 0x8000) as usize) % self.prg.len()]
}
}

The modulo automatically handles mirroring: a 16KB ROM (16384 bytes) at address $C000 gives $C000 - $8000 = $4000 = 16384, and 16384 % 16384 = 0 — it wraps to the start.

1.3 How Instructions Execute

Every instruction follows the same three-step cycle:

1. FETCH   — Read the opcode from the address in PC
2. DECODE  — Look up which instruction it is
3. EXECUTE — Run the instruction, return cycle count

In x-nes, this is implemented in lib.rs:

#![allow(unused)]
fn main() {
pub fn tick(cpu: &mut CpuRp2a03, bus: &mut Bus<'_>) -> u8 {
    // 1. FETCH: read the opcode byte
    let opcode = bus.read(cpu.pc());

    // 2. DECODE + ADVANCE: move PC past the opcode
    cpu.set_pc(cpu.pc().wrapping_add(1));

    // 3. EXECUTE: jump to the correct handler
    let cycles = TABLE[opcode as usize](cpu, bus);

    // Advance PPU and APU in sync
    bus.ppu.tick_batch((cycles as u16) * 3);
    bus.apu.tick(cycles);

    cycles
}
}

The decode step uses a jump table — an array of 256 function pointers, one per possible opcode:

#![allow(unused)]
fn main() {
type Op = for<'a> fn(&mut CpuRp2a03, &mut Bus<'a>) -> u8;

pub static TABLE: [Op; 256] = [
    brk, ora_indx, illegal, illegal, ...
];
}

TABLE[opcode as usize] selects the right function in constant time. No searching, no matching — just a lookup and a call.

1.4 The Complete CPU State

Putting it all together, the CPU struct contains everything needed to represent the 6502’s state:

#![allow(unused)]
fn main() {
#[repr(C)]
#[derive(Clone, Copy)]
pub struct CpuRp2a03 {
    bytes: [u8; 7],
}
}

With accessor methods for each register:

MethodReadsWrites
pc() / set_pc()bytes[0..2] as u16bytes[0..2] from u16
a() / set_a()bytes[2]bytes[2]
x() / set_x()bytes[3]bytes[3]
y() / set_y()bytes[4]bytes[4]
st() / set_st()bytes[5]bytes[5]
sr() / set_sr()bytes[6]bytes[6]

Plus flag helpers:

  • get_flag(flag) — test a specific flag
  • set_flag(flag, set) — set or clear a specific flag
  • set_sign(val) — set N flag based on bit 7 of val
  • set_zero(val) — set Z flag if val is zero

Summary

  • The 6502 has 6 registers totaling 7 bytes
  • The NES memory map has RAM, PPU registers, APU registers, and cartridge ROM
  • Instruction execution follows fetch-decode-execute
  • Flags track the results of operations
  • The stack lives at $0100-$01FF and grows downward

2. Instruction Set & Addressing Modes

The 6502 has 56 documented instructions and 13 addressing modes. Not every instruction works with every mode, but the combination produces 256 possible opcodes (0x00-0xFF).

2.1 Addressing Modes

An instruction needs data to operate on. The addressing mode tells the CPU where to find that data. Each mode has its own machine code format and timing.

2.1.1 Immediate (#)

The value is embedded directly in the instruction. The operand byte IS the value.

Assembly:   LDA #$29      ; Load value 0x29 into A
Machine:    $A9 $29       ; Opcode $A9 = LDA immediate, next byte = value
Cycles:     2
#![allow(unused)]
fn main() {
pub fn lda_imm(cpu: &mut CpuRp2a03, bus: &mut Bus<'_>) -> u8 {
    let val = bus.read(cpu.pc());         // read the immediate value
    cpu.set_pc(cpu.pc().wrapping_add(1)); // advance past it
    cpu.set_a(val);
    cpu.set_sign(val);
    cpu.set_zero(val);
    2
}
}

2.1.2 Zero Page (zp)

The address is a single byte (0x00-0xFF), referring to the first page of memory. This is faster than full 16-bit addressing because only one byte needs to be read.

Assembly:   LDA $F4       ; Load from address $00F4
Machine:    $A5 $F4       ; Opcode = LDA zero page, address byte
Cycles:     3
#![allow(unused)]
fn main() {
pub fn lda_zp(cpu: &mut CpuRp2a03, bus: &mut Bus<'_>) -> u8 {
    let addr = bus.read(cpu.pc()) as u16;  // one byte address
    cpu.set_pc(cpu.pc().wrapping_add(1));
    let val = bus.read(addr);
    cpu.set_a(val); cpu.set_sign(val); cpu.set_zero(val);
    3
}
}

2.1.3 Zero Page, X (zpx)

The address is computed as (zp_addr + X) & 0xFF. The result wraps around the zero page — it never crosses into $0100.

Assembly:   LDA $20, X    ; Load from ($0020 + X)
Machine:    $B5 $20
Cycles:     4

The “wrap around” is important: $FF + 2 = $01, not $101.

2.1.4 Absolute (abs)

The full 16-bit address follows the opcode, low byte first.

Assembly:   LDA $31F6     ; Load from address $31F6
Machine:    $AD $F6 $31   ; Low byte first, then high byte
Cycles:     4
#![allow(unused)]
fn main() {
pub fn lda_abs(cpu: &mut CpuRp2a03, bus: &mut Bus<'_>) -> u8 {
    let lo = bus.read(cpu.pc()) as u16;
    let hi = bus.read(cpu.pc().wrapping_add(1)) as u16;
    cpu.set_pc(cpu.pc().wrapping_add(2));
    let addr = lo | (hi << 8);
    let val = bus.read(addr);
    cpu.set_a(val); cpu.set_sign(val); cpu.set_zero(val);
    4
}
}

2.1.5 Absolute, X (absx) and Absolute, Y (absy)

The address is computed as base + X (or base + Y). If the addition crosses a page boundary, an extra cycle is needed.

Assembly:   LDA $31F6, X
Machine:    $DD $F6 $31
Cycles:     4 (no page cross) or 5 (page cross)

Page-cross detection in x-nes is branchless:

#![allow(unused)]
fn main() {
pub fn absx(cpu: &CpuRp2a03, bus: &mut Bus<'_>) -> (u16, u8) {
    let base = abs(cpu, bus);
    let addr = base.wrapping_add(cpu.x() as u16);
    // XOR compares bits 8-15: same page = 0, different = 1
    (addr, ((base ^ addr) >> 8) as u8)
}
}

2.1.6 Indirect (for JMP only)

The instruction contains a pointer, and the actual destination is read from that pointer.

Assembly:   JMP ($215F)
Machine:    $6C $5F $21
Result:     Jump to the address stored at $215F-$2160

This is the only instruction that uses indirect addressing.

2.1.7 Indexed Indirect (indx) — Pre-indexed

First adds X to a zero-page address, then reads the effective address from that location.

LDA ($3E, X) where X = $05
1. Compute pointer: $3E + $05 = $43
2. Read address from $43-$44: $2415
3. Load value from $2415
#![allow(unused)]
fn main() {
pub fn indx(cpu: &CpuRp2a03, bus: &mut Bus<'_>) -> u16 {
    let ptr = bus.read(cpu.pc()).wrapping_add(cpu.x()) as u16;
    let lo = bus.read(ptr) as u16;
    let hi = bus.read(ptr.wrapping_add(1)) as u16;
    lo | (hi << 8)
}
}

2.1.8 Indirect Indexed (indy) — Post-indexed

First reads a base address from zero page, then adds Y.

LDA ($4C), Y where Y = $05
1. Read base from $4C-$4D: $2100
2. Add Y: $2100 + $05 = $2105
3. Load value from $2105
#![allow(unused)]
fn main() {
pub fn indy(cpu: &CpuRp2a03, bus: &mut Bus<'_>) -> (u16, u8) {
    let ptr = bus.read(cpu.pc()) as u16;
    let base = bus.read(ptr) as u16 | (bus.read(ptr.wrapping_add(1)) as u16) << 8;
    let addr = base.wrapping_add(cpu.y() as u16);
    (addr, ((base ^ addr) >> 8) as u8)  // page-cross penalty
}
}

2.1.9 Relative

Used for branch instructions. A signed byte displacement is added to PC if the branch is taken.

BEQ $A7  →  if Z flag is set, PC += $A7 (as signed -89 or +39)

The displacement range is -128 to +127 bytes from the instruction after the branch.

2.1.10 Implied

The operand is implied by the instruction itself. No additional bytes needed.

TAX   →   Transfer A to X (opcode $AA)
CLC   →   Clear carry flag (opcode $18)

2.1.11 Accumulator

The instruction operates on the accumulator directly, not on memory.

LSR A   →   Shift A right by one bit (opcode $4A)
ASL A   →   Shift A left by one bit (opcode $0A)

2.2 Instruction Categories

2.2.1 Data Movement

MnemonicOperationFlags
LDALoad A from memoryN, Z
LDXLoad X from memoryN, Z
LDYLoad Y from memoryN, Z
STAStore A to memory—
STXStore X to memory—
STYStore Y to memory—
TAXTransfer A to XN, Z
TAYTransfer A to YN, Z
TXATransfer X to AN, Z
TYATransfer Y to AN, Z
TSXTransfer ST to XN, Z
TXSTransfer X to ST—

2.2.2 Arithmetic

MnemonicOperationFlags
ADCAdd with CarryN, V, Z, C
SBCSubtract with BorrowN, V, Z, C
INCIncrement memoryN, Z
DECDecrement memoryN, Z
INXIncrement XN, Z
DEXDecrement XN, Z
INYIncrement YN, Z
DEYDecrement YN, Z

2.2.3 Logical

MnemonicOperationFlags
ANDA = A & memoryN, Z
ORAA = A | memoryN, Z
EORA = A ^ memoryN, Z
BITTest bits of memory with AN, V, Z

2.2.4 Shifts and Rotates

MnemonicOperationFlags
ASLArithmetic shift leftN, Z, C
LSRLogical shift rightN, Z, C
ROLRotate left through carryN, Z, C
RORRotate right through carryN, Z, C

2.2.5 Branches

MnemonicConditionChecked flag
BPLBranch if plusN = 0
BMIBranch if minusN = 1
BVCBranch if overflow clearV = 0
BVSBranch if overflow setV = 1
BCCBranch if carry clearC = 0
BCSBranch if carry setC = 1
BNEBranch if not equalZ = 0
BEQBranch if equalZ = 1

2.2.6 Jumps and Subroutines

MnemonicOperation
JMPJump to address
JSRJump to subroutine (push return address)
RTSReturn from subroutine (pull return address)
BRKSoftware interrupt
RTIReturn from interrupt

2.2.7 Stack Operations

MnemonicOperation
PHAPush A onto stack
PHPPush status register onto stack
PLAPull A from stack
PLPPull status register from stack

2.2.8 Flag Control

MnemonicOperation
CLCClear carry
SECSet carry
CLDClear decimal mode
SEDSet decimal mode
CLIClear interrupt disable
SEISet interrupt disable
CLVClear overflow
NOPNo operation

2.3 The Jump Table

With 256 possible opcodes and 56 instructions across 13 modes, the 6502 instruction set maps onto exactly 256 byte values. x-nes encodes this mapping as a static array:

#![allow(unused)]
fn main() {
pub static TABLE: [Op; 256] = {
    use self::op::*;
    [
        // 0x00-0x0F
        brk, ora_indx, illegal, illegal,
        illegal, ora_zp, asl_zp, illegal,
        php, ora_imm, asl_a, illegal,
        illegal, ora_abs, asl_abs, illegal,
        // 0x10-0x1F
        bpl, ora_indy, illegal, illegal,
        // ... continues for all 256 entries ...
    ]
};
}

Each entry is a function pointer. illegal is used for undocumented opcodes (treated as NOP).

2.4 How ADC Works (Add with Carry)

ADC is the most complex arithmetic instruction. It adds memory + accumulator + carry:

result = A + M + C

In Rust:

#![allow(unused)]
fn main() {
fn adc_inner(cpu: &mut CpuRp2a03, operand: u8) {
    let a = cpu.a();
    let carry = cpu.get_flag(FLAG_CARRY) as u16;
    let result = a as u16 + operand as u16 + carry;
    let lo = result as u8;

    if cpu.get_flag(FLAG_DECIMAL) {
        // BCD mode: each nibble is a decimal digit (0-9)
        let low = (a & 0x0F) + (operand & 0x0F) + cpu.get_flag(FLAG_CARRY) as u8;
        let mut temp = result;
        if low > 9 { temp += 6; }          // adjust low digit
        cpu.set_flag(FLAG_CARRY, temp > 0x99);
        if temp > 0x99 { temp += 96; }     // adjust high digit
        cpu.set_a(temp as u8);
    } else {
        // Binary mode: standard 8-bit addition
        cpu.set_sign(lo);
        cpu.set_zero(lo);
        cpu.set_flag(FLAG_CARRY, result > 0xFF);
        cpu.set_flag(FLAG_OVERFLOW, !((a ^ operand) & 0x80) != 0 && ((a ^ lo) & 0x80) != 0);
        cpu.set_a(lo);
    }
}
}

How the overflow flag works:

  • In signed arithmetic, overflow occurs when the sign of the result doesn’t match the signs of the operands
  • (a ^ operand) & 0x80 checks if a and operand have different signs
  • (a ^ lo) & 0x80 checks if a and the result have different signs
  • Both being true means a sign change that shouldn’t have happened → overflow

Summary

  • The 6502 has 56 instructions and 13 addressing modes
  • The jump table maps all 256 opcodes to their handlers
  • Each addressing mode reads its operand differently
  • ADC/SBC handle both binary and decimal (BCD) mode
  • Branch instructions check status flags and add a signed displacement to PC

3. Memory & I/O

The NES CPU can address 64KB of memory, but not all of it is RAM. Different address ranges connect to different hardware components. The bus routes each read/write to the correct destination.

3.1 NES Memory Map

$0000 - $07FF   2KB     CPU RAM
$0800 - $1FFF           RAM Mirrors
$2000 - $3FFF           PPU Registers
$4000 - $4017           APU & I/O Registers
$4018 - $401F           Test Mode (unused)
$4020 - $FFFF           Cartridge PRG-ROM

3.2 The Bus Implementation

The bus is the central connector in x-nes. Every CPU memory access passes through it:

#![allow(unused)]
fn main() {
pub struct Bus<'a> {
    pub ram: [u8; 2048],  // 2KB internal RAM
    pub prg: &'a [u8],    // borrowed ROM data
    pub ppu: Ppu,         // Picture Processing Unit
    pub apu: Apu,         // Audio Processing Unit
}
}

The prg field borrows ROM data from the caller (the person running the emulator). This means the emulator never needs to allocate memory for ROM — it uses whatever the caller provides.

3.2.1 Reading from the Bus

#![allow(unused)]
fn main() {
pub fn read(&mut self, addr: u16) -> u8 {
    let top = (addr >> 12) as u8;
    match top {
        0 | 1 => self.ram[(addr & 0x07FF) as usize],
        2 | 3 => self.read_ppu(addr),
        4 if addr < 0x4020 => self.apu.read(addr),
        _ => self.read_prg(addr),
    }
}
}

The address is shifted right by 12 to extract the top nibble (0-15), which identifies the memory region. This compiles to a single shr instruction followed by an indexed jump.

3.2.2 Writing to the Bus

#![allow(unused)]
fn main() {
pub fn write(&mut self, addr: u16, val: u8) {
    let top = (addr >> 12) as u8;
    match top {
        0 | 1 => self.ram[(addr & 0x07FF) as usize] = val,
        2 | 3 => self.write_ppu(addr, val),
        4 if addr < 0x4020 => {
            if addr == 0x4014 {
                self.oam_dma(val);
            } else {
                self.apu.write(addr, val);
            }
        }
        _ => {}  // ROM writes are ignored (no mapper yet)
    }
}
}

3.3 CPU RAM

The NES has 2KB of RAM ($0000-$07FF). Addresses outside this range, up to $1FFF, are mirrors — they reference the same physical memory. The CPU sees its RAM at every 2KB boundary:

$0000-$07FF:  Actual RAM
$0800-$0FFF:  Mirror of $0000-$07FF
$1000-$17FF:  Mirror of $0000-$07FF
$1800-$1FFF:  Mirror of $0000-$07FF

x-nes handles this with a single mask operation: addr & 0x07FF maps all addresses in the range to 0-2047.

3.4 PPU Register Access

The PPU has 8 registers ($2000-$2007), mirrored across the entire $2000-$3FFF range. The mask addr & 7 extracts the register number:

#![allow(unused)]
fn main() {
fn read_ppu(&mut self, addr: u16) -> u8 {
    match addr & 7 {
        2 => self.ppu.read_status(),
        4 => self.ppu.read_oam_data(),
        7 => self.ppu.read_data(),
        _ => 0,
    }
}

fn write_ppu(&mut self, addr: u16, val: u8) {
    match addr & 7 {
        0 => self.ppu.write_ctrl(val),
        1 => self.ppu.write_mask(val),
        3 => self.ppu.write_oam_addr(val),
        4 => self.ppu.write_oam_data(val),
        5 => self.ppu.write_scroll(val),
        6 => self.ppu.write_addr(val),
        7 => self.ppu.write_data(val),
        _ => {}
    }
}
}

Some PPU registers are read-only ($2002), others are write-only ($2000, $2001, $2003, $2005, $2006). Reading a write-only register returns 0.

3.4.1 PPU Register Descriptions

PPUCTRL ($2000) — Controls high-level PPU operation:

Bit 7:   NMI enable (V) — generate NMI at start of vblank
Bit 6:   PPU master/slave (P)
Bit 5:   Sprite size (H) — 0=8x8, 1=8x16
Bit 4:   Background pattern table (B) — 0=$0000, 1=$1000
Bit 3:   Sprite pattern table (S) — 0=$0000, 1=$1000
Bit 2:   VRAM increment (I) — 0=+1, 1=+32
Bits 1-0: Base nametable (NN)

PPUMASK ($2001) — Controls rendering:

Bit 7-5:  Color emphasis (blue, green, red)
Bit 4:    Show sprites
Bit 3:    Show background
Bit 2:    Show sprites in left 8 columns
Bit 1:    Show background in left 8 columns
Bit 0:    Greyscale

PPUSTATUS ($2002) — Read-only status:

Bit 7:    Vblank flag (V) — set when PPU enters vblank
Bit 6:    Sprite 0 hit (S)
Bit 5:    Sprite overflow (O)
Bits 4-0: Unused

Reading $2002 clears bit 7 and the write toggle (used by $2005/$2006).

3.5 APU & I/O Access

The APU occupies $4000-$4017, with the important exception of $4014 (OAM DMA):

#![allow(unused)]
fn main() {
4 if addr < 0x4020 => {
    if addr == 0x4014 {
        self.oam_dma(val);
    } else {
        self.apu.write(addr, val);
    }
}
}

3.5.1 OAM DMA ($4014)

Writing to $4014 triggers a DMA transfer: 256 bytes are copied from CPU memory (page specified by the written value) to PPU sprite RAM (OAM):

Writing $02 to $4014 copies $0200-$02FF into OAM
#![allow(unused)]
fn main() {
fn oam_dma(&mut self, page: u8) {
    let base = (page as u16) << 8;
    for i in 0..256 {
        let addr = base | i;
        let val = self.read(addr);  // reads from CPU memory or ROM
        self.ppu.oam[self.ppu.oam_addr as usize] = val;
        self.ppu.oam_addr = self.ppu.oam_addr.wrapping_add(1);
    }
}
}

3.6 Cartridge PRG-ROM

The cartridge ROM is mapped to $4020-$FFFF. For NROM (mapper 0), the simplest cartridge type:

#![allow(unused)]
fn main() {
fn read_prg(&self, addr: u16) -> u8 {
    if addr < 0x8000 || self.prg.is_empty() {
        return 0;
    }
    self.prg[((addr - 0x8000) as usize) % self.prg.len()]
}
}

16KB ROMs are mirrored — $C000-$FFFF wraps around to $8000-$BFFF. 32KB ROMs fill the entire $8000-$FFFF range without mirroring.

3.7 NMI Handling

The PPU can interrupt the CPU at the start of vblank (when it finishes drawing the visible scanlines). This is called a Non-Maskable Interrupt (NMI) — the CPU must handle it.

In x-nes, after each instruction executes, we check if the PPU raised an NMI:

#![allow(unused)]
fn main() {
if bus.poll_nmi() {
    nmi(cpu, bus);
}
}

The NMI handler pushes the program counter and status register onto the stack, then loads a new PC from the NMI vector ($FFFA):

#![allow(unused)]
fn main() {
pub fn nmi(cpu: &mut CpuRp2a03, bus: &mut Bus<'_>) {
    crate::ops::push(cpu, bus, (cpu.pc() >> 8) as u8);
    crate::ops::push(cpu, bus, cpu.pc() as u8);
    let sr = cpu.sr() | 0x20;  // set unused bit
    crate::ops::push(cpu, bus, sr);
    cpu.set_flag(FLAG_INTERRUPT, true);
    let lo = bus.read(0xFFFA) as u16;
    let hi = bus.read(0xFFFB) as u16;
    cpu.set_pc(lo | (hi << 8));
}
}

Summary

  • The bus routes addresses to the correct hardware component
  • RAM is mirrored — 2KB appears to fill 8KB of address space
  • PPU registers are at $2000-$2007, mirrored every 8 bytes
  • OAM DMA copies 256 bytes from CPU memory to PPU sprite memory
  • Cartridge ROM wraps around for 16KB banks
  • NMI interrupts the CPU at the start of vblank

4. Picture Processing Unit

The PPU (Picture Processing Unit) generates the NES video signal. It runs at three times the CPU speed and has its own memory system for tiles, palettes, and sprites.

4.1 PPU Memory

The PPU has its own 16KB address space ($0000-$3FFF), separate from the CPU:

$0000-$0FFF   4KB     Pattern Table 0 (256 tiles, 16 bytes each)
$1000-$1FFF   4KB     Pattern Table 1 (256 tiles)
$2000-$23BF   960B    Name Table 0 (tile indices)
$23C0-$23FF   64B     Attribute Table 0 (palette assignments per 2×2 tile group)
$2400-$27BF   960B    Name Table 1
$27C0-$27FF   64B     Attribute Table 1
$2800-$2BFF            Name Table 2 (usually mirror of 0)
$2C00-$2FFF            Name Table 3 (usually mirror of 1)
$3F00-$3F0F   16B     Background palette
$3F10-$3F1F   16B     Sprite palette (mirrors $3F00/$3F04/$3F08/$3F0C)

4.1.1 Pattern Tables

Tiles are 8×8 pixels, each pixel being 2 bits (selecting one of 4 colors from a palette). A tile takes 16 bytes: 8 bytes for the low bitplane (bits 0-7), 8 bytes for the high bitplane (bits 8-15).

Tile at $0000:
  Byte 0:  $7E → bitplane 0 row 0: 01111110
  Byte 1:  $FF → bitplane 0 row 1: 11111111
  ...
  Byte 7:  $42 → bitplane 0 row 7: 01000010
  Byte 8:  $00 → bitplane 1 row 0: 00000000
  Byte 9:  $00 → bitplane 1 row 1: 00000000
  ...
  Byte 15: $00 → bitplane 1 row 7: 00000000

Pixel (x,y) color = ((bitplane1[y] >> (7-x)) & 1) << 1
                  |  ((bitplane0[y] >> (7-x)) & 1)
                 = value 0-3 (transparent, color 1, color 2, color 3)

4.1.2 Name Tables

A name table is a 32×30 grid of tile indices (960 bytes). Each byte selects which 8×8 tile to draw from the pattern tables. The PPU’s current name table is selected by bits 1-0 of PPUCTRL ($2000).

4.1.3 Attribute Tables

Attribute tables assign palettes to 2×2 tile groups (4 tiles). Each byte covers a 32×32 pixel region (4×4 tile groups). Each 2-bit field selects one of 4 background palettes:

Attribute byte for 4×4 tile groups:
  Bits 0-1: Top-left 2×2 group
  Bits 2-3: Top-right 2×2 group
  Bits 4-5: Bottom-left 2×2 group
  Bits 6-7: Bottom-right 2×2 group

4.1.4 Palette RAM

The NES has 32 palette entries. Addresses $3F10/$3F14/$3F18/$3F1C mirror $3F00/$3F04/$3F08/$3F0C:

$3F00:  Universal background color (used for color 0 everywhere)
$3F01:  BG Palette 0, color 1
$3F02:  BG Palette 0, color 2
$3F03:  BG Palette 0, color 3
$3F04:  BG Palette 1, color 1
...
$3F0F:  BG Palette 3, color 3
$3F10:  Mirror of $3F00
$3F11:  Sprite Palette 0, color 1
...
$3F1F:  Sprite Palette 3, color 3

x-nes handles the mirroring:

#![allow(unused)]
fn main() {
let i = (addr & 0x1F) as usize;
let i = if i & 0x13 == 0x10 { i & 0x0F } else { i };
// $10→$00, $14→$04, $18→$08, $1C→$0C
self.palette[i]
}

4.2 PPU Timing

The PPU generates a video frame as a sequence of scanlines. Each scanline has 341 dot cycles.

4.2.1 Frame Structure

┌─────────────────────────────────────────────────────────┐
│ Scanlines 0-239:  Visible picture (240 scanlines)       │
│   Cycles 1-256:   Background tile fetch + pixel render  │
│   Cycle 257:      Horizontal scroll copy + sprite eval  │
│   Cycles 258-340: Idle (no rendering)                   │
├─────────────────────────────────────────────────────────┤
│ Scanline 240:     Post-render (idle)                    │
├─────────────────────────────────────────────────────────┤
│ Scanlines 241-260: VBlank (vertical blanking interval)  │
│   Scanline 241, cycle 1: Set VBlank flag, trigger NMI   │
├─────────────────────────────────────────────────────────┤
│ Scanline 261:     Pre-render line (idle)                │
│   Cycle 1: Clear VBlank/sprite flags                    │
│   Cycle 0 (start): Vertical scroll copy                 │
│   Cycle 340: Skip on odd frames (rendering enabled)     │
└─────────────────────────────────────────────────────────┘
Total: 262 scanlines × 341 cycles = 89,342 PPU dots per frame

4.2.2 Rendering Per Scanline

During visible scanlines, the PPU uses an on-the-fly renderer that computes each pixel independently from scroll state snapshots:

  1. Cycle 1 (and every 8th cycle): Fetch background tile pattern, increment coarse X
  2. Cycles 1-256: Render one pixel per cycle
  3. Cycle 256: Increment coarse Y (vertical scroll)
  4. Cycle 257: Copy horizontal scroll bits from t to v, evaluate sprites for next scanline

4.2.3 Scroll State Snapshots

The on-the-fly renderer uses render_v and render_fine_x — snapshots taken at prerender cycle 0 and updated at cycle 257 of each scanline:

#![allow(unused)]
fn main() {
// Prerender cycle 0:
self.render_v = self.v;
self.render_fine_x = self.fine_x;

// Cycle 257:
self.render_v = (self.render_v & !V_HORIZONTAL_MASK) | (self.v & V_HORIZONTAL_MASK);
self.render_fine_x = self.fine_x;
}

4.3 PPU Registers

4.3.1 PPUCTRL ($2000) — Write Only

Bit 7: NMI on VBlank (V)
Bit 6: PPU master/slave (P) — ignored by most emulators
Bit 5: Sprite size (H) — 0=8×8, 1=8×16
Bit 4: Background pattern table (B) — 0=$0000, 1=$1000
Bit 3: Sprite pattern table (S) — 0=$0000, 1=$1000
Bit 2: VRAM address increment (I) — 0=+1, 1=+32
Bits 1-0: Base nametable (NN) — 0-3 for $2000/$2400/$2800/$2C00

Writing $2000 triggers NMI edge detection. If NMI was disabled and is now enabled while VBlank is active, the NMI fires immediately.

4.3.2 PPUMASK ($2001) — Write Only

Bit 7: Emphasize blue
Bit 6: Emphasize green
Bit 5: Emphasize red
Bit 4: Show sprites (s)
Bit 3: Show background (b)
Bit 2: Show sprites in left 8 columns (M)
Bit 1: Show background in left 8 columns (m)
Bit 0: Greyscale (G)

4.3.3 PPUSTATUS ($2002) — Read Only

Bit 7: VBlank flag (V)
Bit 6: Sprite 0 hit (S)
Bit 5: Sprite overflow (O)
Bits 4-0: Open bus (decayed)

Reading $2002 clears bit 7, resets the write toggle (w), and the low 5 bits return the open bus value with decay. If read on the same cycle that VBlank would be set (scanline 241, cycle 1), VBlank is suppressed.

#![allow(unused)]
fn main() {
pub fn read_status(&mut self) -> u8 {
    let s = self.status;
    self.status &= !0x80;  // clear VBlank flag
    self.w = 0;            // reset write toggle
    let result = (s & 0xE0) | (self.get_open_bus() & 0x1F);
    // VBlank suppression edge case
    if self.scanline == VBLANK_START && self.cycle == 1 && (s & 0x80) == 0 {
        self.vbl_suppressed = true;
    }
    self.update_nmi_edge(false);
    result
}
}

4.3.4 PPUADDR ($2006) and PPUDATA ($2007)

These work together to provide random access to PPU memory:

#![allow(unused)]
fn main() {
pub fn write_addr(&mut self, val: u8) {
    if self.w == 0 {
        // First write: high byte (upper 6 bits to t)
        self.t = ((self.t & 0x00FF) | ((val as u16) << 8)) & 0x3FFF;
        self.w = 1;
    } else {
        // Second write: low byte, then t→v
        self.t = (self.t & 0xFF00) | val as u16;
        self.v = self.t;
        self.w = 0;
    }
}

pub fn read_data(&mut self, mapper: &mut Mapper) -> u8 {
    let addr = self.v & 0x3FFF;
    let val = if addr < 0x2000 {
        self.chr_read(addr, mapper)         // CHR read via mapper
    } else {
        self.ppu_read_nt(addr, mapper)      // Nametable/palette read
    };
    let result = if addr < 0x3F00 {
        self.data_buffer                     // Buffer: 1-cycle delay
    } else {
        (self.get_open_bus() & 0xC0) | (val & 0x3F)  // Palette: immediate + open bus
    };
    // Update buffer for next read
    if addr < 0x3F00 {
        self.data_buffer = val;
    } else {
        self.data_buffer = self.ppu_read_nt(addr & 0x2FFF, mapper);
    }
    self.v = self.v.wrapping_add(if self.ctrl & 0x04 != 0 { 32 } else { 1 });
    result
}
}

4.3.5 PPUSCROLL ($2005) — Write Only

Two writes (toggled by w):

#![allow(unused)]
fn main() {
pub fn write_scroll(&mut self, val: u8) {
    if self.w == 0 {
        // First write: coarse X (val >> 3) + fine X (val & 7)
        self.t = (self.t & 0xFFE0) | ((val >> 3) as u16);
        self.fine_x = val & 7;
        self.w = 1;
    } else {
        // Second write: coarse Y + fine Y + nametable Y
        self.t = (self.t & 0xFC1F)
            | (((val as u16) & 0x07) << 12)   // fine Y → bits 12-14
            | (((val as u16) & 0xF8) << 2);   // coarse Y → bits 5-9
        self.w = 0;
    }
}
}

4.3.6 OAMADDR ($2003) and OAMDATA ($2004)

OAM (Object Attribute Memory) holds 64 sprites at 4 bytes each (Y, tile, attr, X):

#![allow(unused)]
fn main() {
pub fn write_oam_addr(&mut self, val: u8) { self.oam_addr = val; }
pub fn write_oam_data(&mut self, val: u8) {
    self.oam[self.oam_addr as usize] = val;
    self.oam_addr = self.oam_addr.wrapping_add(1);
}
pub fn read_oam_data(&mut self) -> u8 {
    let mut val = self.oam[self.oam_addr as usize];
    if self.oam_addr & 0x03 == 2 { val &= 0xE3; } // Bits 2-4 read as 0
    val
}
}

4.4 On-the-Fly Rendering

x-nes uses an on-the-fly pixel renderer that computes each pixel independently rather than emulating the PPU’s internal shift registers. This gives more flexibility and simplifies MMC5 extended attribute support.

4.4.1 Background Pixel Computation

#![allow(unused)]
fn main() {
fn compute_bg_pixel(&mut self, x: u16, y: u16, mapper: &mut Mapper) -> (u8, u8) {
    // 1. Extract scroll state from render_v snapshot
    let coarse_x = self.render_v & 0x001F;
    let coarse_y = (self.render_v >> 5) & 0x001F;
    let fine_y = (self.render_v >> 12) & 0x0007;
    let nt = (self.render_v >> 10) & 0x0003;

    // 2. Compute world coordinates
    let world_x = (coarse_x << 3) + self.render_fine_x as u16 + x;
    let world_y = (coarse_y << 3) + fine_y + y;

    // 3. Handle nametable wrapping
    let mut actual_nt = nt;
    if (world_x >> 8) & 1 != 0 { actual_nt ^= 1; }    // Horizontal wrap
    if ((world_y >> 3) / 30) & 1 != 0 { actual_nt ^= 2; } // Vertical wrap

    // 4. Compute tile position
    let tile_x = (world_x >> 3) & 31;
    let tile_y = ((world_y >> 3) % 30) & 31;
    let pixel_x = world_x & 7;
    let pixel_y = world_y & 7;

    // 5. Fetch tile index from nametable
    let nt_addr = 0x2000 | (actual_nt << 10) | (tile_y << 5) | tile_x;
    let tile_index = self.ppu_read_nt(nt_addr, mapper);

    // 6. MMC5 ExRAM mode 1: extended attributes
    let ex_ram_mode = mapper.get_ex_ram_mode();
    if ex_ram_mode == 1 {
        let exram_byte = mapper.read_ex_ram_byte(nt_addr & 0x03FF);
        mapper.set_extended_chr_bank(exram_byte);
        mapper.set_chr_fetch_bg();
        let tile_addr = ((tile_index as u16) << 4) | pixel_y;
        let low = mapper.ppu_read(tile_addr);
        let high = mapper.ppu_read(tile_addr | 0x0008);
        let pixel = ((high >> (7-pixel_x)) & 1) << 1 | ((low >> (7-pixel_x)) & 1);
        if pixel == 0 { return (0, self.palette[0]); }
        let pal_group = (exram_byte >> 6) & 3;
        return (pixel, self.palette[((pal_group as usize) << 2) | pixel as usize]);
    }

    // 7. Standard rendering: fetch tile data + attribute
    mapper.set_chr_fetch_bg();
    let bg_table = if self.ctrl & 0x10 != 0 { 0x1000 } else { 0x0000 };
    let tile_addr = bg_table | ((tile_index as u16) << 4) | pixel_y;
    let low = mapper.ppu_read(tile_addr);
    let high = mapper.ppu_read(tile_addr | 0x0008);
    let pixel = ((high >> (7-pixel_x)) & 1) << 1 | ((low >> (7-pixel_x)) & 1);

    if pixel == 0 {
        (0, self.palette[0])
    } else {
        // Fetch attribute for palette group
        let attr_addr = nt_base | 0x03C0 | ((tile_y >> 2) << 3) | (tile_x >> 2);
        let attr = self.ppu_read_nt(attr_addr, mapper);
        let pal_group = (attr >> (((tile_x>>1)&1)<<1 | ((tile_y>>1)&1)<<2)) & 3;
        (pixel, self.palette[((pal_group as usize) << 2) | pixel as usize])
    }
}
}

4.4.2 Sprite Rendering

Sprites are evaluated once per scanline (at cycle 257 for the next line). The evaluator scans OAM and selects up to 8 sprites that intersect the next scanline:

#![allow(unused)]
fn main() {
fn evaluate_sprites_for(&mut self, sl: u16, mapper: &mut Mapper) {
    self.sprite_count = 0;
    let sprite_h = if self.ctrl & 0x20 != 0 { 16 } else { 8 };
    for i in (0..0x100).step_by(4) {
        let sy = self.oam[i] as u16;
        if sy <= sl && sl < sy + sprite_h {
            if self.sprite_count < 8 {
                self.sprite_indices[self.sprite_count as usize] = (i >> 2) as u8;
                self.sprite_count += 1;
            } else {
                self.status |= 0x20; // Sprite overflow
            }
        }
    }
    // Fetch sprite patterns for all 8 slots (including dummy fetches for unused)
    mapper.set_chr_fetch_sprite();
    for si in 0..8 { /* pattern fetch for each slot */ }
}
}

Sprite rendering per pixel checks if any evaluated sprite covers this X position, handles priority (behind background), sprite 0 hit detection, and 8×16 vs 8×8 sprite size.

4.5 MMC5 Integration Points

The PPU has specific hooks for MMC5 features:

HookPurpose
nt_mapping()Returns MMC5’s $5105 value for custom NT routing
read_nt_ext() / write_nt_ext()Handle ExRAM and fill mode NT sources (2 and 3)
set_chr_fetch_bg() / set_chr_fetch_sprite()Tell MMC5 whether current PPU read is BG or sprite
set_extended_chr_bank()Set ExRAM mode 1 per-tile CHR bank
get_ex_ram_mode()Check if ExRAM mode 1 is active
read_ex_ram_byte()Read ExRAM byte for extended attributes

4.6 NMI Edge Detection

The PPU detects rising edges on the NMI enable signal (VBlank AND NMI-enabled). It tracks:

  • nmi_output: previous NMI line state
  • nmi_latched: edge detected, pending CPU sample (penultimate cycle)
  • nmi_from_vblank: edge was from VBlank start (fires immediately)
  • nmi_deferred_pending: NMI from $2000 write deferred to next instruction
#![allow(unused)]
fn main() {
pub fn update_nmi_edge(&mut self, from_vblank: bool) {
    let new_output = (self.status & STATUS_VBLANK != 0) && (self.ctrl & CTRL_NMI_ENABLE != 0);
    let edge = !self.nmi_output && new_output;
    if edge {
        self.nmi_latched = true;
        if from_vblank { self.nmi_from_vblank = true; }
    }
    self.nmi_output = new_output;
}
}

Summary

  • The PPU has its own 16KB memory with pattern tables, name tables, and palettes
  • A frame is 262 scanlines × 341 cycles = 89,342 dots (~16.67ms at 60Hz)
  • 240 scanlines are visible, 241-261 are VBlank + prerender
  • NMI triggers at the start of VBlank (scanline 241, cycle 1)
  • The on-the-fly renderer computes each pixel from scroll state snapshots
  • MMC5 extended attributes add per-tile CHR bank and palette selection
  • The write toggle (w) alternates between first/second writes for $2005/$2006
  • $2007 reads have a 1-cycle buffer delay (except palettes)

5. Audio & ROM Loading

5.1 Audio Processing Unit (APU)

The NES APU generates sound through five channels:

ChannelTypeCharacteristics
Pulse 1Square wave4 duty cycles, sweep, envelope
Pulse 2Square wave4 duty cycles, sweep, envelope
TriangleTriangle waveLinear counter, no volume control
NoisePseudo-random16-bit shift register, 16 frequencies
DMCDelta Modulation1-bit samples, DMA from ROM

5.1.1 APU Registers

The APU occupies $4000-$4017:

$4000-$4003:   Pulse 1 (duty/volume, sweep, timer low, timer high/len)
$4004-$4007:   Pulse 2
$4008-$400B:   Triangle
$400C-$400F:   Noise
$4010-$4013:   DMC
$4015:         Status register (read = channel activity, write = enable)
$4017:         Frame counter (mode, IRQ disable)

The x-nes APU is a minimal stub that tracks timing and accepts register writes without generating audio samples yet:

#![allow(unused)]
fn main() {
pub struct Apu {
    pub cycles: u64,
}

impl Apu {
    pub fn new() -> Self { Self { cycles: 0 } }

    pub fn tick(&mut self, cpu_cycles: u8) {
        self.cycles += cpu_cycles as u64;
    }

    pub fn read(&self, addr: u16) -> u8 {
        match addr {
            0x4015 => 0,
            _ => 0,
        }
    }

    pub fn write(&mut self, addr: u16, _val: u8) {
        match addr {
            0x4000..=0x4013 | 0x4017 => {}
            0x4015 => {}
            _ => {}
        }
    }
}
}

5.1.2 APU Frame Sequencer

The APU operates on a frame sequencer that runs at 60 Hz (for NTSC). Each frame step updates:

  • Envelope units (every step)
  • Sweep units (every other step)
  • Length counters (every step or every other step, depending on mode)

The frame sequencer is driven by writing $4017 or by the CPU’s frame counter.

5.2 ROM Loading

NES games are distributed as ROM files using the iNES format. x-nes implements a parser for this format.

5.2.1 iNES Header Format

Every iNES ROM starts with a 16-byte header:

Offset  Size  Field
0       4     Identifier: "NES^Z" ($4E $45 $53 $1A)
4       1     PRG-ROM size (16KB units)
5       1     CHR-ROM size (8KB units)
6       1     Flags 6:
                Bit 0: Mirroring (0=horizontal, 1=vertical)
                Bit 1: Battery-backed SRAM
                Bit 2: Trainer present (512 bytes after header)
                Bit 3: Four-screen VRAM
                Bits 7-4: Mapper nibble (low)
7       1     Flags 7:
                Bits 7-4: Mapper nibble (high)
                Bit 0: VS Unisystem
                Bit 1: PlayChoice-10
8       1     PRG-RAM size (8KB units)
9       1     Flags 9: TV system (0=NTSC, 1=PAL)
10      1     Flags 10: TV system, PRG-RAM
11-15   5     Unused padding

5.2.2 The Rom Struct

#![allow(unused)]
fn main() {
pub struct Rom {
    pub prg: [u8; 0x8000],  // PRG-ROM data (up to 32KB)
    pub chr: [u8; 0x2000],  // CHR-ROM data (up to 8KB)
    pub mapper: u8,          // Mapper number
    pub mirroring: u8,       // 0=horizontal, 1=vertical
    pub has_chr_ram: bool,   // True if no CHR-ROM (use writable RAM)
}
}

5.2.3 Parsing the ROM

#![allow(unused)]
fn main() {
impl Rom {
    pub fn new(data: &[u8]) -> Option<Self> {
        // Validate header
        if data.len() < 16 || data[0..4] != [0x4E, 0x45, 0x53, 0x1A] {
            return None;
        }

        let prg_16kb = data[4] as usize;   // number of 16KB PRG banks
        let chr_8kb = data[5] as usize;    // number of 8KB CHR banks
        let flags6 = data[6];
        let flags7 = data[7];

        let mapper = (flags7 & 0xF0) | (flags6 >> 4);
        let mirroring = flags6 & 0x01;
        let has_chr_ram = chr_8kb == 0;

        // Trainer is 512 bytes between header and ROM data
        let header_size = if flags6 & 0x04 != 0 { 16 + 512 } else { 16 };

        // Copy PRG-ROM
        let prg_size = prg_16kb * 0x4000;
        let mut prg = [0u8; 0x8000];
        let prg_src = &data[header_size..header_size + prg_size];
        if prg_size <= 0x8000 {
            prg[..prg_size].copy_from_slice(prg_src);
            // Mirror 16KB to 32KB if needed
            if prg_size == 0x4000 {
                prg[0x4000..0x8000].copy_from_slice(prg_src);
            }
        }

        // Copy CHR-ROM (or leave as zeros for CHR-RAM)
        let chr_start = header_size + prg_size;
        let chr_size = if chr_8kb == 0 { 0x2000 } else { chr_8kb * 0x2000 };
        let mut chr = [0u8; 0x2000];
        if chr_size > 0 {
            let chr_src = &data[chr_start..chr_start + chr_size.min(0x2000)];
            chr[..chr_src.len()].copy_from_slice(chr_src);
        }

        Some(Self { prg, chr, mapper, mirroring, has_chr_ram })
    }
}
}

5.2.4 Mapper Overview

NES cartridges use a mapper chip to extend the console’s memory and features. The iNES header stores the mapper number and mirroring mode, and x-nes currently parses those values from the ROM header so the emulator can identify the cartridge configuration.

Common official examples include:

  • Mapper 0 (NROM): used by games such as Super Mario Bros. and 10-Yard Fight
  • Mapper 1 (MMC1): used by games such as The Legend of Zelda and Metroid
  • Mapper 2 (UxROM): used by games such as Castlevania and Contra
  • Mapper 3 (CNROM): used by games such as 1942 and The Goonies
  • Mapper 4 (MMC3): used by games such as Super Mario Bros. 3 and Mega Man 3
  • Mapper 9 (MMC2): used by Mike Tyson’s Punch-Out!!

For a complete reference of all known mappers, see the NesDev wiki’s mapper list.

5.2.5 NROM (Mapper 0)

NROM is the simplest mapper and the only one implemented. In NROM:

  • 16KB PRG-ROM: Mirrored to fill 32KB ($8000-$FFFF)
  • 32KB PRG-ROM: Used as-is ($8000-$FFFF)
  • 8KB CHR-ROM: Connected directly to PPU pattern tables
  • No CHR-ROM: PPU uses CHR-RAM (writable memory for pattern tables)

The Bus reads PRG data using the mod mirroring pattern:

#![allow(unused)]
fn main() {
fn read_prg(&self, addr: u16) -> u8 {
    let idx = ((addr - 0x8000) as usize) % self.prg.len();
    self.prg[idx]
}
}

For a 16KB ROM (16384 bytes):

  • $8000 → index 0
  • $BFFF → index 16383
  • $C000 → index 16384 % 16384 = 0 (mirror!)
  • $FFFF → index 32767 % 16384 = 16383 (mirror!)

5.3 How to Load a ROM

#![allow(unused)]
fn main() {
use nes::{bus::Bus, cpu::CpuRp2a03, rom::Rom, reset, tick};

// Read ROM file
let data = std::fs::read("game.nes").unwrap();

// Parse ROM header
let rom = Rom::new(&data).unwrap();

// Create CPU and Bus
let mut cpu = CpuRp2a03::new(0);
let mut bus = Bus::new(&rom.prg, &rom.chr, rom.mirroring);

// Reset (read reset vector from ROM)
reset(&mut cpu, &mut bus);

// Emulate
loop {
    tick(&mut cpu, &mut bus);
    if bus.ppu.frame_complete {
        // Display frame from bus.ppu.frame
        bus.ppu.frame_complete = false;
    }
}
}

Summary

  • The APU has 5 sound channels, but x-nes currently implements register stubs and timing hooks rather than full synthesis
  • iNES ROMs have a 16-byte header followed by PRG and CHR data
  • NROM (mapper 0) is the simplest cartridge type and is the main mapper supported today
  • 16KB PRG-ROM is mirrored to fill 32KB
  • The emulator core is designed to stay small, portable, and suitable for both desktop and embedded targets
  • ROM data is borrowed, not owned — no allocation needed

Mappers Overview

NES cartridges contain mapper chips that extend the console’s capabilities — bank switching PRG-ROM and CHR-ROM, adding scanline IRQs, extra RAM, and custom nametable features. x-nes currently implements 8 mappers covering most of the NES library.

How Mappers Work

The NES CPU can only address 64KB. The cartridge provides the upper 32KB ($8000-$FFFF) as PRG-ROM. For games larger than 32KB, a mapper chip sits between the CPU and the ROM, listening for writes to specific addresses and using those writes as bank-switch commands.

CPU writes to $8000-$FFFF
        │
        ▼
┌──────────────┐     Bank select     ┌──────────────┐
│   Mapper      │◄───────────────────│  Game Code    │
│   Chip        │                    │  (writes to   │
│  (bank logic) │                    │   mapper regs)│
└──────┬───────┘                    └──────────────┘
       │
       │  Physical bank address
       ▼
┌──────────────┐
│  PRG-ROM     │   (up to 2MB)
│  CHR-ROM     │
└──────────────┘

All mappers implement the MapperImpl trait:

#![allow(unused)]
fn main() {
pub trait MapperImpl {
    fn cpu_read(&mut self, addr: u16) -> u8;
    fn cpu_write(&mut self, addr: u16, val: u8);
    fn ppu_read(&mut self, addr: u16) -> u8;
    fn ppu_write(&mut self, addr: u16, val: u8);
    fn mirroring(&self) -> u8;
    fn irq_pending(&self) -> bool;
    fn ack_irq(&mut self);
    fn clock_scanline(&mut self) {}
    fn has_chr_ram(&self) -> bool;

    // MMC5-specific extensions (default no-ops):
    fn notify_scanline(&mut self, _scanline: u16) {}
    fn nt_mapping(&self) -> u8 { 0xFF }
    fn read_nt_ext(&mut self, _addr: u16, _nt_source: u8) -> u8 { 0 }
    fn write_nt_ext(&mut self, _addr: u16, _nt_source: u8, _val: u8) {}
    fn set_chr_fetch_bg(&mut self) {}
    fn set_chr_fetch_sprite(&mut self) {}
    fn set_extended_chr_bank(&mut self, _bank: u8) {}
    fn get_extended_chr_bank(&self) -> u8 { 0 }
    fn get_ex_ram_mode(&self) -> u8 { 0 }
    fn get_fill_tile(&self) -> u8 { 0 }
    fn get_fill_attr(&self) -> u8 { 0 }
    fn read_ex_ram_byte(&mut self, _offset: u16) -> u8 { 0 }
}
}

Mapper Selection

Mappers are selected automatically from the iNES header’s mapper number:

#![allow(unused)]
fn main() {
impl Mapper {
    pub fn from_ines(id: u8, mirroring: u8, prg_data: &[u8], chr_data: &[u8], chr_ram: bool) -> Self {
        match id {
            0 => Self::Nrom(...),    // NROM
            1 => Self::Mmc1(...),    // MMC1 (SxROM)
            2 => Self::UxRom(...),   // UxROM
            3 => Self::Cnrom(...),   // CNROM
            4 => Self::Mmc3(...),    // MMC3 (TxROM)
            5 => Self::Mmc5(...),    // MMC5 (ExROM)
            7 => Self::Axrom(...),   // AxROM
            66 => Self::Gxrom(...),  // GxROM
            _ => Self::Nrom(...),    // Unknown → NROM fallback
        }
    }
}
}

Implemented Mappers

Mapper 0 — NROM (nrom.rs)

Used by: Super Mario Bros., Donkey Kong, Excitebike, Ice Climber

The simplest mapper. No bank switching at all.

  • 16KB PRG-ROM: mirrored to fill $8000-$FFFF
  • 32KB PRG-ROM: fills entire range
  • 8KB CHR-ROM: connected directly to PPU
  • No CHR-ROM: uses CHR-RAM (writable pattern tables)
#![allow(unused)]
fn main() {
pub struct Nrom { prg: Vec<u8>, chr: Vec<u8>, mirror: u8, has_chr_ram: bool }
}

PRG reads simply wrap around for 16KB ROMs using % prg.len().

Mapper 1 — MMC1 (mmc1.rs)

Used by: The Legend of Zelda, Metroid, Mega Man 2, Castlevania II

Nintendo’s first advanced mapper. Features serial register writes (5 writes to build one register value), 4 PRG modes, 2 CHR modes, and variable mirroring.

  • PRG modes: 32KB switchable, 16KB+16KB fixed, 16KB+16KB swapped
  • CHR modes: 8KB switchable, 4KB+4KB
  • Mirroring: Horizontal, Vertical, Single-screen A, Single-screen B
  • PRG RAM: 8KB at $6000-$7FFF, enable/disable via register bit
  • Serial interface: 5 consecutive writes with bit 7 determining reset

Mapper 2 — UxROM (uxrom.rs)

Used by: Castlevania, Contra, Mega Man, DuckTales

Simple PRG bank switching with a single register.

  • 16KB switchable PRG bank at $8000-$BFFF
  • 16KB fixed PRG bank (last bank) at $C000-$FFFF
  • 8KB CHR-RAM (fixed, writable)
  • Horizontal or vertical mirroring (fixed by cartridge)
#![allow(unused)]
fn main() {
pub struct UxRom {
    prg: Vec<u8>, chr: Vec<u8>, mirror: u8,
    prg_bank: u8,    // selects which 16KB bank at $8000
    has_chr_ram: bool,
}
}

Mapper 3 — CNROM (cnrom.rs)

Used by: 1942, The Goonies, Gradius

Simple CHR bank switching.

  • 32KB PRG-ROM (or 16KB mirrored)
  • 8KB switchable CHR bank at PPU $0000-$1FFF
  • Horizontal or vertical mirroring

Mapper 4 — MMC3 (mmc3.rs)

Used by: Super Mario Bros. 3, Mega Man 3, Kirby’s Adventure

The most common advanced mapper. Features dual 8KB PRG banks (one fixed, one switchable), 2KB+1KB CHR granularity, scanline-based IRQ counter, and configurable mirroring.

  • PRG: Two 8KB switchable banks at $8000 and $A000, two fixed banks (second-to-last and last) at $C000 and $E000. PRG mode swaps which is fixed/switchable.
  • CHR: 2KB banks at $0000-$0FFF (R0, R1), 1KB banks at $1000-$1FFF (R2-R7). CHR mode swaps these groups.
  • IRQ: 8-bit down-counter triggered by A12 rising edges (PPU rendering). When it reaches 0, it reloads and fires IRQ.
  • Mirroring: Dynamic — write to $A000 sets horizontal or vertical.
#![allow(unused)]
fn main() {
pub struct Mmc3 {
    prg: Vec<u8>, chr: Vec<u8>,
    bank_select: u8,     // $8000: bit 6=PRG mode, bit 7=CHR mode, bits 0-2=bank index
    prg_banks: [u8; 4],  // R2,R3 (CHR), R4(R6,R7 PRG) — only indices 2,3 used for PRG
    chr_banks: [u8; 8],  // R0-R7: 2KB+1KB CHR banks
    irq_latch: u8,       // value to reload into counter
    irq_counter: u8,     // current counter value
    irq_enabled: bool,
    irq_reload: bool,
    irq_flag: bool,
    // PRG RAM
    prg_ram: [u8; 0x2000],
    prg_ram_enable: bool,
    prg_ram_write: bool,
}
}

Register writes:

AddressEven (A0=0)Odd (A0=1)
$8000-$9FFFBank Select (bank_select)Bank Data (loads bank_select & 7)
$A000-$BFFFMirroringPRG RAM protect
$C000-$DFFFIRQ LatchIRQ Reload
$E000-$FFFFIRQ DisableIRQ Enable

Mapper 5 — MMC5 (mmc5.rs) ⭐

Used by: Castlevania III, Just Breed, Metal Slader Glory, Uncharted Waters

Nintendo’s most powerful mapper. See the MMC5 Deep Dive for full details.

  • PRG: 4 modes: 32KB, 2×16KB, 16KB+8KB+8KB, 4×8KB
  • CHR: 4 modes: 8KB, 4KB+4KB, 2KB×4, 1KB×8 — separate banks for BG and sprites
  • ExRAM: 1024 bytes with 4 operating modes:
    • Mode 0: Extra nametable (5th screen)
    • Mode 1: Extended attributes (per-tile CHR bank + palette)
    • Mode 2: CPU read/write RAM
    • Mode 3: CPU read-only
  • Scanline IRQ: for split-screen effects (status bars)
  • Multiplier: hardware 8×8=16 multiply at $5205/$5206
  • Fill mode: nametable auto-filling with a single tile
  • Vertical split: independent scrolling for two screen halves
  • Expansion audio: 2 extra pulse channels (not yet implemented in x-nes)

Mapper 7 — AxROM (axrom.rs)

Used by: Battletoads, Solstice, Marble Madness

Single-screen mirroring with 32KB PRG bank switching.

  • 32KB PRG bank at $8000-$FFFF
  • 8KB CHR-RAM
  • Mirroring selectable (single-screen A or B) via PRG bank write

Mapper 66 — GxROM (gxrom.rs)

Used by: Doraemon, Giant Step

Simple dual-bank switching.

  • 32KB PRG bank (select via bits 4-5 of register write)
  • 8KB CHR bank (select via bits 0-1 of register write)
  • Fixed mirroring (hardware-set)

How the Emulator Dispatches to Mappers

The Mapper enum wraps all mapper types:

#![allow(unused)]
fn main() {
pub enum Mapper {
    Nrom(Box<nrom::Nrom>),
    UxRom(Box<uxrom::UxRom>),
    Cnrom(Box<cnrom::Cnrom>),
    Mmc1(Box<mmc1::Mmc1>),
    Mmc3(Box<mmc3::Mmc3>),
    Mmc5(Box<mmc5::Mmc5>),
    Axrom(Box<axrom::Axrom>),
    Gxrom(Box<gxrom::Gxrom>),
    Null,
}
}

Each method in Mapper dispatches via match self to the correct implementation:

#![allow(unused)]
fn main() {
pub fn cpu_read(&mut self, addr: u16) -> u8 {
    match self {
        Self::Nrom(m) => m.cpu_read(addr),
        Self::Mmc3(m) => m.cpu_read(addr),
        Self::Mmc5(m) => m.cpu_read(addr),
        // ...
        Self::Null => 0,
    }
}
}

Adding a New Mapper

  1. Create src/mapper/your_mapper.rs with a struct implementing MapperImpl
  2. Add pub mod your_mapper; to src/mapper/mod.rs
  3. Add a variant to the Mapper enum
  4. Add the match arm to each dispatch method
  5. Add mapping in Mapper::from_ines() based on the mapper ID

Example skeleton:

#![allow(unused)]
fn main() {
use super::MapperImpl;
use alloc::vec::Vec;

pub struct YourMapper {
    prg: Vec<u8>,
    chr: Vec<u8>,
    mirror: u8,
    has_chr_ram: bool,
    // ... your registers
}

impl YourMapper {
    pub fn new(prg: &[u8], chr: &[u8], chr_ram: bool, mirror: u8) -> Self {
        Self {
            prg: prg.to_vec(),
            chr: if chr_ram { alloc::vec![0u8; 0x2000] } else { chr.to_vec() },
            mirror,
            has_chr_ram: chr_ram,
        }
    }
}

impl MapperImpl for YourMapper {
    fn cpu_read(&mut self, addr: u16) -> u8 { /* ... */ 0 }
    fn cpu_write(&mut self, addr: u16, val: u8) { /* ... */ }
    fn ppu_read(&mut self, addr: u16) -> u8 { /* ... */ 0 }
    fn ppu_write(&mut self, addr: u16, val: u8) { /* ... */ }
    fn mirroring(&self) -> u8 { self.mirror }
    fn irq_pending(&self) -> bool { false }
    fn ack_irq(&mut self) {}
    fn has_chr_ram(&self) -> bool { self.has_chr_ram }
}
}

MMC5 Deep Dive

The MMC5 (Nintendo MMC5, mapper 5) is the most complex mapper ever produced for the NES. Used by only a handful of games including Castlevania III, it provides features far beyond any other mapper.

MMC5 Features at a Glance

FeatureDescription
PRG ROMUp to 2MB (1024 × 8KB banks) via 4 switching modes
CHR ROMUp to 1MB (1024 × 1KB banks) with separate BG/sprite banking
ExRAM1024 bytes with 4 operating modes
Scanline IRQFor split-screen effects (status bars)
Hardware multiplier8×8→16 multiply at $5205/$5206
Fill modeNametable auto-filling
Vertical splitIndependent scrolling for two screen halves
Expansion audio2 extra pulse channels (PCM-capable)

Register Map

Core Configuration Registers

RegisterFunction
$5100PRG mode (0-3)
$5101CHR mode (0-3)
$5102PRG RAM protect 1
$5103PRG RAM protect 2
$5104ExRAM mode (0-3)
$5105Nametable mapping (2 bits per NT)
$5106Fill-mode tile
$5107Fill-mode attribute (bits 0-1)

Bank Registers

RegisterFunction
$5113PRG RAM bank select (0-7)
$5114-$5117PRG ROM bank registers (8KB each)
$5120-$5127CHR sprite banks (1KB each, 8 total)
$5128-$512BCHR background banks (1KB each, 4 total)
$5130CHR upper bits (bits 8-9 of all CHR banks)

IRQ & Multiplier

RegisterFunction
$5203IRQ scanline target
$5204IRQ status (read) / enable (write)
$5205Multiplier: write operand A (read: result low)
$5206Multiplier: write operand B (read: result high)

ExRAM Access

AddressFunction
$5C00-$5FFFExRAM read/write (mode-dependent)

PRG Banking

MMC5 offers 4 PRG modes, selected by $5100 bits 0-1:

Mode 0: 32KB (like NROM)

The entire $8000-$FFFF range comes from one 32KB-aligned bank. Register $5117 bits 2-6 select the bank (×1 multiplier).

$8000-$FFFF → PRG register $5117, bits 2-6 (32KB granularity)

Mode 1: 2×16KB (like UxROM)

Two independent 16KB regions:

$8000-$BFFF → PRG register $5115, bits 1-6 (16KB granularity)
$C000-$FFFF → PRG register $5117, bits 1-6 (16KB granularity)

Mode 2: 16KB + 8KB + 8KB

One 16KB bank plus two 8KB banks:

$8000-$BFFF → PRG register $5115, bits 1-6 (16KB granularity)
$C000-$DFFF → PRG register $5116, bits 0-6 (8KB granularity)
$E000-$FFFF → PRG register $5117, bits 0-6 (8KB granularity)

Mode 3: 4×8KB

Four independent 8KB banks — this is the most common mode:

$8000-$9FFF → PRG register $5114
$A000-$BFFF → PRG register $5115
$C000-$DFFF → PRG register $5116
$E000-$FFFF → PRG register $5117

Bank registers are masked to 7 bits (& 0x7F), allowing up to 128 8KB banks = 1MB PRG ROM.

Initial Bank Setup

On power-up, the last two 8KB banks are guaranteed to be at $C000-$FFFF:

#![allow(unused)]
fn main() {
let prg_reg = [
    0,                                      // $8000: bank 0
    1,                                      // $A000: bank 1
    if prg8_count >= 2 { prg8_count - 2 } else { 0 },  // $C000: second-to-last
    if prg8_count >= 1 { prg8_count - 1 } else { 0 },  // $E000: last (reset vector)
];
}

CHR Banking

MMC5 has separate CHR banking for background and sprites. The PPU tells the mapper whether it’s fetching background or sprite data via the M2/RW timing signals. In x-nes, this is modeled with chr_fetch_bg:

#![allow(unused)]
fn main() {
fn set_chr_fetch_bg(&mut self)     { self.chr_fetch_bg = true; }
fn set_chr_fetch_sprite(&mut self) { self.chr_fetch_bg = false; }
}

CHR mode (from $5101) determines granularity:

Mode 0: 8KB

  • BG: chr_bg_reg[3] & 0xFC selects 4KB page (×4 multiplier)
  • Sprites: chr_sprite_reg[7] & 0xF8 selects 8KB page (×8 multiplier)

Mode 1: 4KB

  • BG: chr_bg_reg[3] & 0xFC selects 4KB page
  • Sprites: chr_sprite_reg[3] or chr_sprite_reg[7] select 4KB pages (split at $1000)

Mode 2: 2KB

  • BG: chr_bg_reg[1], chr_bg_reg[3] each select 2KB (4 pages total)
  • Sprites: chr_sprite_reg[1], chr_sprite_reg[3], chr_sprite_reg[5], chr_sprite_reg[7] select 2KB each

Mode 3: 1KB (Castlevania III uses this)

  • BG: chr_bg_reg[0..3] select 1KB each
  • Sprites: chr_sprite_reg[0..7] select 1KB each

The CHR upper bits ($5130) provide bits 8-9 of all CHR bank numbers, extending the addressable range to 1024 1KB banks = 1MB CHR ROM.

ExRAM

The MMC5 has 1024 bytes of extra RAM (ex_ram). Its function depends on $5104:

Mode 0: Extra Nametable

ExRAM appears as a 5th physical nametable. The $5105 register can map any of the 4 NT slots to ExRAM (source 2):

$5105 bits for each NT:
  00 = CIRAM A (internal VRAM page 0)
  01 = CIRAM B (internal VRAM page 1)
  10 = ExRAM (mapper's extended RAM)
  11 = Fill mode

Mode 1: Extended Attributes (⭐ Castlevania III uses this)

Each byte in ExRAM corresponds to a background tile (same index as nametable). The ExRAM byte provides:

  • Bits 0-5: 4KB CHR page (64 pages = 256KB CHR)
  • Bits 6-7: Palette group (0-3) — replaces the attribute table for this tile

This allows every background tile to have its own CHR bank and palette, completely bypassing the standard attribute table! This is how Castlevania III achieves its rich, colorful backgrounds.

#![allow(unused)]
fn main() {
// In ppu_read, ExRAM mode 1 background fetch:
let bank = (u16::from(extended_chr_bank & 0x3F) << 2) + bg_slot;
// extended_chr_bank = 6-bit 4KB page from ExRAM
// bg_slot = 2-bit 1KB sub-slot within the 4KB page
}

Mode 2: CPU RAM

ExRAM is accessible only by the CPU at $5C00-$5FFF for both read and write. Not mapped to PPU space.

Mode 3: CPU Read-Only

Same as mode 2, but CPU writes are ignored. Useful for read-only lookup tables.

ExRAM Access Control

#![allow(unused)]
fn main() {
// CPU $5C00-$5FFF reads:
if ex_ram_mode >= 2 {     // Only modes 2 and 3
    ex_ram[addr & 0x3FF]
} else { 0 }              // Modes 0/1: open bus

// CPU $5C00-$5FFF writes:
if ex_ram_mode < 3 {      // Modes 0, 1, 2
    ex_ram[addr & 0x3FF] = val;
}                          // Mode 3: writes ignored
}

PPU Nametable Mapping ($5105)

Unlike other mappers that just pick between horizontal and vertical mirroring, MMC5 can independently map each of the 4 nametables (NT0-NT3) to any of 4 sources:

BitsNametableSource
1-0NT0 ($2000)0=CIRAM_A, 1=CIRAM_B, 2=ExRAM, 3=Fill
3-2NT1 ($2400)Same encoding
5-4NT2 ($2800)Same encoding
7-6NT3 ($2C00)Same encoding

Example: $5105 = 0x44 = vertical mirroring (NT0→A, NT1→B, NT2→A, NT3→B)

#![allow(unused)]
fn main() {
fn nt_mapping(&self) -> u8 { self.nt_mapping_reg }

// PPU resolves NT reads/writes via nt_index():
fn nt_index(addr: u16, mirroring: u8, nt_mapping: u8) -> (u8, u16) {
    if nt_mapping != 0xFF {  // MMC5 path
        let nt = ((addr >> 10) & 3) as u8;
        let source = (nt_mapping >> (nt * 2)) & 0x03;
        (source, addr & 0x03FF)
    } else {
        // Standard mirroring path
    }
}
}

Fill Mode (source 3)

When a nametable slot is mapped to fill mode (source 3), the PPU always returns the same data regardless of address:

  • Tile areas: Returns fill_tile ($5106)
  • Attribute areas: Returns (fill_attr & 3) * 0x55 ($5107)

This creates a solid-color background with a single repeating tile — useful for status bars, menus, or solid-color areas without using up nametable space.

Scanline IRQ

MMC5 provides a scanline-based IRQ for split-screen effects. Castlevania III uses this for its status bar at the bottom of the screen.

$5203 write: Set IRQ target scanline (0-239)
$5204 write: Bit 7 enables IRQ, also acknowledges pending IRQ
$5204 read:  Bit 7 = IRQ pending, Bit 6 = in-frame, Bits 5-0 = current scanline

The PPU calls notify_scanline() at the start of each scanline:

#![allow(unused)]
fn main() {
fn notify_scanline(&mut self, scanline: u16) {
    if scanline < 240 {
        // Store scanline counter in status bits 0-5
        self.irq_status = (self.irq_status & 0xC0) | (scanline as u8 & 0x3F);
        self.irq_status |= 0x40;  // in-frame flag

        // Fire IRQ when counter matches target
        if self.irq_enabled && scanline as u8 == self.irq_scanline {
            self.irq_status |= 0x80;  // IRQ pending
            self.irq_pending_flag = true;
        }
    } else {
        self.irq_status &= !0x40;  // Clear in-frame flag
    }
}
}

When the IRQ fires, the game’s IRQ handler changes the scroll registers mid-screen, creating a visual split. This is how Castlevania III shows the gameplay area on top and the status bar (health, lives, weapon) on the bottom.

Hardware Multiplier

Writing to $5205 or $5206 triggers an unsigned 8×8→16 multiplication. The result is readable from $5205 (low byte) and $5206 (high byte).

#![allow(unused)]
fn main() {
0x5205 => {
    self.mul_a = val;
    self.mul_result = u16::from(self.mul_a) * u16::from(self.mul_b);
}
0x5206 => {
    self.mul_b = val;
    self.mul_result = u16::from(self.mul_a) * u16::from(self.mul_b);
}
}

Castlevania III uses the multiplier for coordinate calculations, screen position math, and game logic.

PRG RAM Protection

The MMC5 includes PRG RAM at $6000-$7FFF with write protection:

#![allow(unused)]
fn main() {
fn prg_ram_is_protected(&self) -> bool {
    // Protected when $5102 == 0x02 AND $5103 == 0x01
    self.prg_ram_protect1 == 0x02 && self.prg_ram_protect2 == 0x01
}
}

Castlevania III uses PRG RAM for save data (game progress, settings). After writing save data, it locks the RAM by writing $5102=$02 and $5103=$01 to prevent corruption.

Expansion Audio

MMC5 adds two extra square-wave channels (PCM-capable) accessed via $5000-$5015. These provide richer soundtracks in MMC5 games. x-nes currently accepts register writes but does not synthesize the audio:

#![allow(unused)]
fn main() {
0x5000..=0x5015 => {
    // MMC5 expansion audio registers — accepted but not implemented
}
}

Debugging MMC5 Games

Key things to check when debugging MMC5 games:

  1. PRG banking: Verify that $5100 and $5114-$5117 are set correctly. The reset vector MUST be in the last 8KB bank.
  2. CHR banking: Verify $5101 and $5120-$512B. In mode 3, there are 12 separate 1KB CHR bank registers.
  3. ExRAM mode: Check $5104. Mode 1 (extended attributes) requires the PPU to correctly set chr_fetch_bg/chr_fetch_sprite.
  4. NT mapping: Check $5105. Non-standard NT mappings (ExRAM or fill mode) must be handled by ppu_read_nt.
  5. IRQ timing: Verify $5203 and $5204. The IRQ must fire at exactly the right scanline for correct screen splits.
  6. PRG RAM protection: Check $5102/$5103 — inverted logic is a common bug!

Common Bug: PRG RAM Protection Inverted

A very common MMC5 bug is inverting the PRG RAM write protection logic. After reset, $5102=0, $5103=0 means “not protected” — writes to $6000-$7FFF must be ALLOWED. When $5102=2, $5103=1, writes must be BLOCKED.

Debugging Guide

This guide covers techniques for debugging NES emulation issues in x-nes, from CPU bugs to PPU rendering glitches, mapper problems, and APU timing.

Quick Diagnostic Commands

Run ROM headless (check if it boots)

cargo run --example main -- "path/to/rom.nes"

Watch the PC values. If they cycle predictably and you see Frame complete messages, the game is executing code and generating frames.

Run with window (see visuals)

cargo run --example window -- "path/to/rom.nes"

Run test suite

cargo test                          # Unit tests
cargo test --test accuracy_coin     # AccuracyCoin (comprehensive)

Debugging CPU Issues

Inspect CPU State

Add this to the main loop for per-instruction tracing:

#![allow(unused)]
fn main() {
println!(
    "{:04X}  A:{:02X} X:{:02X} Y:{:02X} P:{:02X} SP:{:02X}  CYC:{}",
    cpu.pc(), cpu.a(), cpu.x(), cpu.y(), cpu.sr(), cpu.st(),
    bus.cpu_cycle
);
}

Check Reset Vectors

The NES boots by reading the reset vector at $FFFC-$FFFD. Verify these addresses contain valid ROM data:

#![allow(unused)]
fn main() {
let lo = bus.read(0xFFFC);
let hi = bus.read(0xFFFD);
println!("Reset vector: ${:02X}{:02X} → ${:04X}", hi, lo, (hi as u16) << 8 | lo as u16);
}

If the reset vector points to $0000 or a non-ROM address, the ROM isn’t loading correctly.

Trace PC history

Keep a rolling window of last N PCs to see code flow:

#![allow(unused)]
fn main() {
let mut pc_history = [0u16; 64];
let mut pc_idx = 0;

// In the tick loop:
pc_history[pc_idx % 64] = cpu.pc();
pc_idx += 1;

// Print on crash/detection:
for i in 0..64.min(pc_idx) {
    let idx = (pc_idx - 1 - i) % 64;
    println!("  [-{}] PC=${:04X}", i, pc_history[idx]);
}
}

Detect Infinite Loops

If the game hangs, it’s often in a tight loop. Watch for the same PC repeating:

#![allow(unused)]
fn main() {
let mut last_pc = 0u16;
let mut repeat_count = 0u32;

// In tick:
if cpu.pc() == last_pc {
    repeat_count += 1;
    if repeat_count > 1_000_000 {
        eprintln!("HANG DETECTED at PC=${:04X}", cpu.pc());
        break;
    }
} else {
    repeat_count = 0;
    last_pc = cpu.pc();
}
}

Illegal Opcodes

If the CPU hits an unofficial opcode, it may crash or behave unexpectedly. x-nes implements all official and unofficial opcodes. Verify the opcode table covers the full 256 entries:

#![allow(unused)]
fn main() {
// Check if any slot is missing:
for i in 0..256 {
    // TABLE[i] should always be a valid function pointer
}
}

Debugging PPU / Graphics Issues

See the Graphics Debugging chapter for a dedicated guide.

Quick PPU State Dump

#![allow(unused)]
fn main() {
fn dump_ppu(ppu: &Ppu) {
    println!("Scanline: {}  Cycle: {}  Frame: {}",
        ppu.scanline, ppu.cycle, ppu.frame_complete);
    println!("CTRL: {:02X}  MASK: {:02X}  STATUS: {:02X}",
        ppu.ctrl, ppu.mask, ppu.status);
    println!("v: ${:04X}  t: ${:04X}  fine_x: {}  w: {}",
        ppu.v, ppu.t, ppu.fine_x, ppu.w);
    println!("NMI: output={} latched={} vblank={} deferred={}",
        ppu.nmi_output, ppu.nmi_latched,
        ppu.nmi_from_vblank, ppu.nmi_deferred_pending);
}
}

Dump Frame to PPM

Save the frame buffer as a viewable image for offline analysis:

#![allow(unused)]
fn main() {
fn save_ppm(frame: &[u8; 61440], path: &str, palette: &[u32; 64]) {
    use std::io::Write;
    let mut f = std::fs::File::create(path).unwrap();
    writeln!(f, "P6\n256 240\n255").unwrap();
    for y in 0..240 {
        for x in 0..256 {
            let idx = y * 256 + x;
            let color = palette[(frame[idx] & 0x3F) as usize];
            let r = ((color >> 16) & 0xFF) as u8;
            let g = ((color >> 8) & 0xFF) as u8;
            let b = (color & 0xFF) as u8;
            f.write_all(&[r, g, b]).unwrap();
        }
    }
    // View with: ffplay path.ppm or convert to PNG
}
}

Debugging Mapper Issues

Verify Mapper Detection

#![allow(unused)]
fn main() {
let rom = Rom::new(&data).unwrap();
println!("Mapper: {}  Mirroring: {}  PRG: {}KB  CHR: {}KB  CHR-RAM: {}",
    rom.mapper_id, rom.mirroring,
    rom.prg.len()/1024, rom.chr.len()/1024, rom.has_chr_ram);
}

Log Mapper Register Writes

Add conditional logging for your mapper:

#![allow(unused)]
fn main() {
// In MMC5 cpu_write, add:
if addr >= 0x5100 && addr <= 0x5117 {
    eprintln!("MMC5 write ${:04X} = ${:02X}  (PC=${:04X})", addr, val, cpu_pc);
}
}

This reveals what the game writes to configuration registers.

Check Bank Mapping

Verify PRG banks are being set correctly:

#![allow(unused)]
fn main() {
fn dump_mmc5_banks(mmc5: &Mmc5) {
    println!("PRG mode: {}  Banks: {:02X} {:02X} {:02X} {:02X}",
        mmc5.prg_mode,
        mmc5.prg_reg[0], mmc5.prg_reg[1],
        mmc5.prg_reg[2], mmc5.prg_reg[3]);
    println!("CHR mode: {}  NT mapping: {:02X}",
        mmc5.chr_mode, mmc5.nt_mapping_reg);
    println!("ExRAM mode: {}  IRQ: scanline={} enabled={} pending={}",
        mmc5.ex_ram_mode, mmc5.irq_scanline,
        mmc5.irq_enable, mmc5.irq_pending_flag);
}
}

Verify PRG RAM Protection Logic

A common bug is inverted PRG RAM protection. Check:

#![allow(unused)]
fn main() {
// After reset ($5102=0, $5103=0), writes to $6000-$7FFF should be ALLOWED
// When $5102=2, $5103=1, writes should be BLOCKED

// Correct:
fn prg_ram_is_protected(&self) -> bool {
    self.prg_ram_protect1 == 0x02 && self.prg_ram_protect2 == 0x01
}
// Call site: if !self.prg_ram_is_protected() { /* allow write */ }
}

Debugging IRQ Issues

IRQ bugs cause screen splits to be at the wrong position, audio glitches, or game hangs.

Log IRQ Events

#![allow(unused)]
fn main() {
// In notify_scanline:
if scanline < 240 && irq_enabled && scanline as u8 == irq_scanline {
    eprintln!("MMC5 IRQ FIRED at scanline {} (target={})", scanline, irq_scanline);
}
}

Verify Scanline Counter

Check that the IRQ fires at the expected scanline. For Castlevania III, the status bar split should be at a consistent scanline (around 200-210 depending on the screen).

Check IRQ Acknowledgment

After the game handles an IRQ, it must read $5204 (or write $5204 with bit 7 clear) to acknowledge. If acknowledgment doesn’t clear irq_pending_flag, the CPU will re-enter the IRQ handler immediately, causing a crash.

Debugging APU / Audio Issues

Check APU Sample Output

Log audio samples to detect silence, clipping, or DC offset:

#![allow(unused)]
fn main() {
let mut max_sample = 0i16;
let mut min_sample = 0i16;
for &s in &apu.audio_samples[..apu.sample_count] {
    max_sample = max_sample.max(s);
    min_sample = min_sample.min(s);
}
eprintln!("Audio: {} samples, range [{}, {}]", apu.sample_count, min_sample, max_sample);
}

Verify APU Channel States

#![allow(unused)]
fn main() {
fn dump_apu(apu: &Apu) {
    println!("Pulse1: enabled={} duty={} vol={} timer={} len={}",
        apu.p1.enabled, apu.p1.duty, apu.p1.vol,
        apu.p1.timer_val, apu.p1.length_counter);
    println!("Pulse2: enabled={} duty={} vol={} timer={} len={}",
        apu.p2.enabled, apu.p2.duty, apu.p2.vol,
        apu.p2.timer_val, apu.p2.length_counter);
    println!("Triangle: enabled={} timer={} lin_ctr={}",
        apu.triangle.enabled, apu.triangle.timer_val,
        apu.triangle.linear_counter);
    println!("Noise: enabled={} vol={} mode={} period={}",
        apu.noise.enabled, apu.noise.vol,
        apu.noise.mode, apu.noise.period_index);
}
}

Test ROMs for Validation

ROMTests
nestest.nesCPU instructions (all official + unofficial)
instr_test-v5/Per-instruction CPU tests
blargg_ppu_tests/PPU timing, VBlank, NMI
AccuracyCoinComprehensive (CPU, PPU, APU, DMA, controllers)
Any NROM gameBasic mapper + PPU integration

Crashes: First Steps

When a game crashes, check in this order:

  1. PC valid? Is it in the ROM range ($8000-$FFFF)?
  2. Opcode valid? Print the opcode at PC
  3. Stack overflow? Check if SP is near 0
  4. IRQ storm? Check if poll_irq() returns true repeatedly
  5. Mapper config? Dump mapper register state
  6. NMI timing? Check if NMI fires at the right scanline

Quick Crash Checklist

□ PC = ${:04X} — in ROM range?
□ Opcode at PC = ${:02X} — valid instruction?
□ Stack SP = ${:02X} — not near overflow?
□ Mapper ID = {} — correct for this ROM?
□ PPU scanline {} cycle {} — stuck in VBlank?
□ IRQ pending? {} — stuck in interrupt handler?

Graphics Debugging

NES graphics bugs are notoriously hard to diagnose because a single PPU timing error can cascade into completely broken visuals. This guide covers systematic approaches to identifying and fixing rendering issues.

Understanding NES Graphics Architecture

Quick refresher on how the PPU builds a frame:

For each scanline (0-239):
    For each cycle (1-256):
        1. Fetch nametable byte (tile index)
        2. Fetch attribute byte (palette group)
        3. Fetch pattern table low byte (bitplane 0)
        4. Fetch pattern table high byte (bitplane 1)
        5. Combine into 2-bit pixel value
        6. Look up color from palette

For each scanline (1-256 during visible):
    Evaluate sprites for NEXT scanline (cycle 257)
    Render sprites on current scanline

Visual Symptom → Likely Cause Map

Black screen / no output

Likely CauseWhat to Check
PPU not renderingmask & 0x08 (BG) or mask & 0x10 (sprites) = 0?
Palette all zerosCheck palette[0..32] — all $0F?
CHR bank pointing to empty ROMVerify CHR bank registers in mapper
Nametable filled with tile $00Dump nametable memory
Wrong bank at $C000-$FFFFPRG register init — reset vector must be in last bank

Garbled graphics / wrong tiles

Likely CauseWhat to Check
Wrong CHR bankMapper CHR register writes correct?
Wrong BG pattern tablectrl & 0x10 selects $0000 or $1000
CHR-RAM not writtenGame writes to PPU $0000-$1FFF but mapper ignores?
NT mapping wrong (MMC5)Check $5105 value

Wrong colors / wrong palette

Likely CauseWhat to Check
Palette not loadedCheck writes to $3F00-$3F1F
Attribute table corruptDump attribute memory at $23C0-$23FF
Palette mirroring wrongi & 0x13 == 0x10 → i & 0x0F correct?
ExRAM mode 1 paletteExRAM bits 6-7 used for palette, not attribute table

Screen scrolling / tearing / wrong position

Likely CauseWhat to Check
Scroll registers wrongfine_x, v, t values during rendering
copy_horizontal() timingHappens at cycle 257, not earlier/later
NMI timing wrongNMI fires during VBlank, game writes scroll in NMI handler
render_v out of syncSnapshot taken at prerender cycle 0 and cycle 257

Split-screen / status bar broken (MMC5/MMC3 IRQ)

Likely CauseWhat to Check
IRQ fires at wrong scanlineCheck $5203 value, scanline counter accuracy
IRQ not firingirq_enable true? Scanline counter matching?
IRQ acknowledged too early/lateGame reads $5204 to clear. Check timing.
Scroll change in IRQ handlerGame writes $2005/$2006 during IRQ

Sprites missing / wrong position

Likely CauseWhat to Check
OAM DMA not working$4014 write triggers 256-byte copy to OAM
Sprite evaluation wrongCheck sprite_count, sprite_indices
Sprite 0 hit timingstatus & 0x40 set at correct pixel?
8×16 sprite selectionctrl & 0x20 — uses different pattern table logic

Flickering / missing scanlines

Likely CauseWhat to Check
PPU cycle counting off341 cycles per line, 262 lines per frame
Odd frame skipCycle 340 of prerender line skipped on odd frames
Rendering enable mid-scanlinemask written during visible scanline?

Pixel-Level Debugging

Dump a Scanline as Text

For a quick visual of what the PPU is drawing:

#![allow(unused)]
fn main() {
fn dump_scanline(ppu: &Ppu, scanline: u16, palette: &[u32; 64]) {
    print!("SL {:3}: ", scanline);
    for x in 0..256 {
        let color_idx = ppu.frame[(scanline as usize) * 256 + x];
        // Map color index to representative char
        let ch = match color_idx & 0x3F {
            0 => '.',    // background
            1..=15 => '#',  // BG colors
            16..=31 => 'S', // sprite colors
            _ => '?',
        };
        print!("{}", ch);
    }
    println!();
}
}

Compare Frame Output

Save frames at specific intervals and compare:

#![allow(unused)]
fn main() {
// Save frame 0
if frame_count == 0 {
    save_ppm(&ppu.frame, "frame0.ppm", &PALETTE);
}
// Save frame 60
if frame_count == 60 {
    save_ppm(&ppu.frame, "frame60.ppm", &PALETTE);
}
}

Use an image diff tool to compare with Mesen’s output frame-by-frame.

Look at Specific Pixels

Examine what happened at a particular (x,y) coordinate:

#![allow(unused)]
fn main() {
fn inspect_pixel(ppu: &Ppu, x: u16, y: u16) {
    let idx = (y as usize) * 256 + (x as usize);
    let color = ppu.frame[idx] & 0x3F;

    // Reconstruct what the pixel should be
    let coarse_x = (ppu.render_v & 0x001F) as u16;
    let coarse_y = ((ppu.render_v >> 5) & 0x001F) as u16;
    let fine_y = (ppu.render_v >> 12) & 0x0007;
    let nt = (ppu.render_v >> 10) & 0x0003;

    let world_x = (coarse_x << 3) + ppu.render_fine_x as u16 + x;
    let world_y = (coarse_y << 3) + fine_y + y;

    let tile_x = (world_x >> 3) & 31;
    let tile_y = ((world_y >> 3) % 30) & 31;

    println!("Pixel ({},{}): color=${:02X}  tile=({},{})  NT={}",
        x, y, color, tile_x, tile_y, nt);
}
}

Nametable Viewer

Dump the nametable contents to understand what the PPU sees:

#![allow(unused)]
fn main() {
fn dump_nametable(ppu: &Ppu, nt: u16) {
    // nt: 0-3 for each 1KB nametable
    let base = 0x2000 | (nt << 10);
    println!("--- Nametable {} ---", nt);

    // Tile indices (32×30)
    for row in 0..30 {
        for col in 0..32 {
            let addr = base | (row << 5) | col;
            // NOTE: you need access to mapper and ppu_read_nt for this
        }
    }

    // Attribute table (8×8 groups of 2×2 tiles)
    println!("--- Attributes ---");
    for row in 0..8 {
        for col in 0..8 {
            let addr = base | 0x03C0 | (row << 3) | col;
        }
    }
}
}

Better approach: dump nametable from ppu.vram:

#![allow(unused)]
fn main() {
fn dump_nametable_vram(ppu: &Ppu, nt: u16) {
    let base = (nt as usize & 1) * 0x400;
    println!("--- Nametable {} (from VRAM) ---", nt);
    for row in 0..30 {
        print!("{:2}: ", row);
        for col in 0..32 {
            let tile = ppu.vram[base + (row * 32 + col) as usize];
            print!("{:02X} ", tile);
        }
        println!();
    }
}
}

Pattern Table Viewer

Visualize CHR pattern data to verify tiles are what you expect:

#![allow(unused)]
fn main() {
fn dump_tile(chr: &[u8], tile_idx: u16) {
    println!("--- Tile {} ---", tile_idx);
    let base = (tile_idx as usize) * 16;
    for y in 0..8 {
        let lo = chr[base + y];
        let hi = chr[base + y + 8];
        for x in (0..8).rev() {
            let bit = ((hi >> x) & 1) << 1 | ((lo >> x) & 1);
            print!("{}", match bit { 0=>'.', 1=>'1', 2=>'2', _=>'3' });
        }
        println!();
    }
}
}

Common Graphics Bug Fixes

Bug: Background tiles show wrong pattern

Symptom: Tiles appear from wrong pattern table or wrong CHR bank.

Cause checklist:

  1. Is ctrl & 0x10 selecting the correct pattern table?
  2. For mappers: is the CHR bank register correct?
  3. For MMC5 ExRAM mode 1: is set_chr_fetch_bg() called before PPU reads?
  4. For MMC5: is extended_chr_bank set from correct ExRAM byte?

Fix: Add logging at PPU read time to see what bank is being used.

Bug: Nametable shows garbage data

Symptom: Screen full of wrong tiles, or tiles from wrong area.

Cause checklist:

  1. Did the game write nametable data? Check writes to $2000-$2FFF.
  2. Is mirroring correct? Check mirroring() return value.
  3. For MMC5: is $5105 (nt_mapping_reg) correct?
  4. For MMC5: is ExRAM (source 2) or fill mode (source 3) being used?

Fix: Dump ppu.vram[0..0x800] and verify tiles are what the game wrote.

Bug: Palette colors are wrong

Symptom: Everything has a color tint, or specific colors are incorrect.

Cause checklist:

  1. Has the game written palette data? Check writes to $3F00-$3F1F.
  2. Is palette mirroring correct? Check i & 0x13 == 0x10 → i & 0x0F.
  3. Are attribute table reads correct? Each 2-bit group selects palette 0-3.
  4. For MMC5 ExRAM mode 1: is the palette coming from ExRAM bits 6-7?

Fix: Dump palette after the game has loaded it:

#![allow(unused)]
fn main() {
for i in 0..32 {
    println!("Palette {:02X}: {:02X}", i, ppu.palette[i]);
}
}

Bug: Sprites not appearing

Symptom: No sprites visible, or sprites at wrong positions.

Cause checklist:

  1. Is mask & 0x10 (show sprites) set?
  2. Did OAM DMA ($4014 write) execute?
  3. Is sprite_count > 0 after evaluation?
  4. Are sprite indices correct?
  5. For MMC5: is set_chr_fetch_sprite() called for sprite CHR reads?
  6. Is sprite 0 hit detection interfering?

Fix: Dump OAM after DMA:

#![allow(unused)]
fn main() {
for i in (0..256).step_by(4) {
    let y = ppu.oam[i];
    let tile = ppu.oam[i+1];
    let attr = ppu.oam[i+2];
    let x = ppu.oam[i+3];
    if y < 0xEF {  // valid sprite
        println!("Sprite {}: ({},{}) tile={:02X} attr={:02X}",
            i/4, x, y, tile, attr);
    }
}
}

Bug: Screen split at wrong position (MMC3/MMC5 IRQ)

Symptom: Status bar too high/low, or screen shake.

Cause checklist:

  1. Is the IRQ counter/target correct? Check $5203 (MMC5) or $C000 (MMC3).
  2. Is the IRQ firing at the right scanline? Add logging in notify_scanline.
  3. After IRQ, does the game change scroll registers correctly?
  4. For MMC3: is copy_horizontal() timing correct at cycle 257?

Fix: Log IRQ fires with scanline position:

#![allow(unused)]
fn main() {
// In notify_scanline or clock_scanline:
if irq_fired {
    eprintln!("IRQ at scanline {} (PPU cycle {})", scanline, ppu_cycle);
}
}

Bug: ExRAM Mode 1 rendering incorrect (MMC5)

Symptom: Castlevania III backgrounds look wrong — wrong tiles or colors.

Cause checklist:

  1. Is ex_ram_mode == 1? Check $5104.
  2. Is ExRAM populated? Dump first 64 bytes of ExRAM.
  3. Is compute_bg_pixel reading the ExRAM byte for each tile?
  4. Is ppu_read using extended_chr_bank when bg_fetch && ex_ram_mode == 1?
  5. Is the palette from ExRAM bits 6-7 being used (not the attribute table)?

Fix: Add verbose logging in compute_bg_pixel for ExRAM mode 1:

#![allow(unused)]
fn main() {
if ex_ram_mode == 1 {
    let exram_byte = mapper.read_ex_ram_byte(exram_offset);
    eprintln!("Tile ({},{}): ExRAM={:02X} → CHR page={} palette={}",
        tile_x, tile_y, exram_byte,
        exram_byte & 0x3F, (exram_byte >> 6) & 3);
}
}

Frame Diffing

The fastest way to find graphics bugs is to compare frames at different points in execution:

  1. Save frame N and frame N+1 to PPM files
  2. Pixel-diff them to find when/where changes occur
  3. At first differing pixel, inspect PPU state:
    • What tile is at that position?
    • What palette was selected?
    • What CHR bank is mapped?
    • What are the scroll register values?
#![allow(unused)]
fn main() {
fn compare_frames(a: &[u8; 61440], b: &[u8; 61440]) -> Option<(usize, usize)> {
    for i in 0..61440 {
        if a[i] != b[i] {
            let y = i / 256;
            let x = i % 256;
            return Some((x, y));
        }
    }
    None
}
}

Pixel Color Reference

The NES palette (64 colors, but only 54 unique):

$00 Gray      $01 Blue      $02 Dark Blue $03 Purple   $04 Dark Purple $05 Dark Red  $06 Brown     $07 Dark Brown
$08 Olive     $09 Green     $0A Dark Green $0B Cyan     $0C Dark Cyan  $0D Blue-Gray $0E Dark Gray $0F Black
$10 Lt Gray   $11 Lt Blue   $12 Lt Blue 2 $13 Lt Purple $14 Lt Magenta  $15 Lt Red    $16 Yellow    $17 Gold
$18 Lt Olive  $19 Lt Green  $1A Lt Green2 $1B Lt Cyan   $1C Lt Cyan 2  $1D Lt Gray 2 $1E Lt Gray3 $1F White
$20-$3F: Mirrors of $00-$1F

6. Performance & Portability

6.1 Design for no_std

x-nes is built without the Rust standard library. This means it can run on any platform with a Rust compiler, from 8-bit microcontrollers to 64-bit desktops.

#![allow(unused)]
#![cfg_attr(not(test), no_std)]
fn main() {
}

The cfg_attr allows std during testing for convenience while keeping the release build minimal.

6.1.1 No Heap Allocation

The emulator never allocates memory. ROM data is borrowed from the caller as &[u8], and all internal state is fixed-size arrays:

StateSizeType
CPU registers7 bytes[u8; 7]
CPU RAM2KB[u8; 2048]
PPU VRAM4KB[u8; 0x1000]
PPU pattern tables8KB[u8; 0x2000]
PPU palette32 bytes[u8; 0x20]
PPU OAM256 bytes[u8; 0x100]
PPU frame buffer61KB[u8; 256 * 240]
Total~75KB

6.1.2 Custom Panic Handler

Without std, there’s no default panic handler. x-nes provides its own:

#![allow(unused)]
fn main() {
#[cfg(not(test))]
#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
    loop {}
}
}

On panic, the CPU loops forever. A debugger can breakpoint on this function to inspect state.

6.2 Cross-Platform Configuration

6.2.1 Cargo Configuration (.cargo/config.toml)

[target.'cfg(any(target_arch = "x86_64", target_arch = "aarch64"))']
rustflags = ["-C", "target-cpu=native"]

[target.thumbv7em-none-eabihf]
rustflags = ["-C", "opt-level=s"]

Desktop builds use target-cpu=native to let LLVM use every instruction your CPU supports. MCU builds optimize for size.

6.2.2 Rust Toolchain (rust-toolchain.toml)

[toolchain]
channel = "stable"
targets = [
    "x86_64-pc-windows-msvc",
    "thumbv7em-none-eabihf",
]

6.2.3 Cargo.toml

[lib]
name = "nes"
crate-type = ["cdylib", "staticlib"]

cdylib produces a shared library (.dll/.so/.dylib) for desktop use. staticlib produces a static archive (.a) for embedded use.

6.3 Crate Type: cdylib vs staticlib

cdylib (Dynamic Library)

Used when x-nes is loaded by another program at runtime:

Desktop app (C, Python, etc.)
          │
          │  FFI call
          ▼
    x-nes.dll / x-nes.so  ← built as cdylib

The host program calls tick(), reset(), etc. through a C-compatible interface.

staticlib (Static Library)

Used when x-nes is linked directly into another program:

Firmware binary
    ├── game code
    ├── x-nes code  ← built as staticlib
    └── board support

Everything is linked into one binary — no runtime loading needed.

6.4 Release Profile

[profile.release]
opt-level      = 3
lto            = true
codegen-units  = 1
strip          = "symbols"
panic          = "abort"
SettingEffect
opt-level = 3Maximum optimization — prioritizes speed
lto = trueLink-time optimization across all dependency boundaries
codegen-units = 1Compiler sees entire crate at once for better inlining
strip = "symbols"Removes debug symbols from output
panic = "abort"No unwind tables (required for no_std + cdylib)

6.5 Build Targets

Building for Desktop

cargo build --release

Output: target/release/nes.dll (Windows), target/release/libnes.so (Linux), or target/release/libnes.dylib (macOS)

Building for Microcontroller (ARM Cortex-M)

rustup target add thumbv7em-none-eabihf
cargo build --release --target thumbv7em-none-eabihf

Output: target/thumbv7em-none-eabihf/release/libnes.a

6.6 Performance Design Decisions

6.6.1 7-Byte CPU Struct

The CPU state is exactly 7 bytes — it fits in a single 64-bit register on x86_64. Register accessors inline to 1-2 mov instructions.

6.6.2 Branchless Flag Operations

set_flag(flag, true):    sr = (sr & !flag) | (1 * flag) = sr | flag
set_flag(flag, false):   sr = (sr & !flag) | (0 * flag) = sr & !flag

The multiply by 0 or 1 replaces a branch. No branch mispredictions.

6.6.3 Jump Table Dispatch

TABLE[opcode as usize](cpu, bus) — a single indexed indirect call. No binary search, no match tree, no bounds check.

6.6.4 Bus Dispatch

Shifting the address right by 12 extracts the top nibble (0-15), which selects the memory region. A match on a small integer compiles to a compact jump table.

6.6.5 Page-Cross Penalty

(base ^ addr) >> 8 is 0 if same page, 1 if different. Added directly to the cycle count — no branch needed.

Summary

  • x-nes is no_std — runs anywhere Rust runs
  • No heap allocation — all state is fixed-size arrays
  • Builds as both dynamic and static library
  • Release profile strips everything unnecessary
  • Same code compiles for desktop and microcontroller targets
  • Binary sizes range from 4KB (MCU) to 9KB (desktop)

Portability: From Microcontrollers to x86_64

x-nes is designed to run on any platform with a Rust compiler — from 8-bit microcontrollers to 64-bit desktops.

no_std

The entire emulator uses #![no_std], which means:

  • No dependency on the Rust standard library
  • No OS syscalls (no file I/O, no threads, no networking)
  • No heap allocator required
  • No floating point (the 6502 has no FPU)
#![allow(unused)]
#![cfg_attr(not(test), no_std)]
fn main() {
}

The cfg_attr(not(test)) allows std during testing so you can use #[test] and cargo test.

Borrowed ROM Data

Instead of owning ROM data with Vec<u8>, the bus borrows it:

#![allow(unused)]
fn main() {
pub struct Bus<'a> {
    pub prg: &'a [u8],  // Borrowed, not owned
    pub ppu: Ppu,        // Owned, fixed-size
    pub apu: Apu,        // Owned, fixed-size
}
}

This means the caller — whether it’s a desktop app, a webassembly runtime, or a microcontroller firmware — retains ownership of the ROM data. The emulator never allocates.

Cross-Compilation Targets

Desktop (cdylib)

[lib]
crate-type = ["cdylib", "staticlib"]

Produces a shared library (.dll/.so/.dylib) that can be linked from C, Python, or any language with FFI.

cargo build --release

Microcontroller (staticlib)

# Add the target
rustup target add thumbv7em-none-eabihf

# Build for Cortex-M4
cargo build --release --target thumbv7em-none-eabihf

The result is a .a file (static library) that links into your firmware.

Configuration Files

.cargo/config.toml

[target.'cfg(any(target_arch = "x86_64", target_arch = "aarch64"))']
rustflags = ["-C", "target-cpu=native"]

[target.thumbv7em-none-eabihf]
rustflags = ["-C", "opt-level=s"]

Desktop builds use target-cpu=native for maximum instruction-level optimization. MCU builds optimize for size (opt-level=s).

rust-toolchain.toml

[toolchain]
channel = "stable"
targets = [
    "x86_64-pc-windows-msvc",
    "thumbv7em-none-eabihf",
]

Auto-installs targets when cloning the repo.

Release Profile

[profile.release]
opt-level      = 3
lto            = true
codegen-units  = 1
strip          = "symbols"
panic          = "abort"
SettingEffect
lto = trueLink-time optimization across all dependencies
codegen-units = 1Single compilation unit — maximum optimization
strip = "symbols"Removes debug symbols from output
panic = "abort"No unwind tables (required for no_std + cdylib)

Test Harness (Desktop Only)

The dev-dependencies section in Cargo.toml includes desktop-only crates for testing:

[dev-dependencies]
softbuffer = "0.4.8"   # Software framebuffer
winit = "0.30.13"      # Window creation
config = "0.15.25"     # Configuration

These are only available when std is linked (i.e., during cargo test or when building tests).

Panic Handler

Since there’s no std to handle panics, a custom panic handler is required:

#![allow(unused)]
fn main() {
#[cfg(not(test))]
#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
    loop {}
}
}

This loops forever on panic. For desktop debugging, you can breakpoint on this function.

No Floating Point

The 6502 has no floating-point instructions. The emulator uses only integer arithmetic. This means:

  • No f32 or f64 types
  • No floating-point emulation
  • Works on microcontrollers without FPUs

Building & Testing

This chapter covers how to build, test, and profile x-nes across different targets.

Quick Start

# Clone and build
git clone https://github.com/ChaoswareHQ/x-nes
cd x-nes

# Build the library
cargo build

# Run the headless example with a ROM
cargo run --example main -- "path/to/rom.nes"

# Run the graphical window example
cargo run --example window -- "path/to/rom.nes"

# Run all tests
cargo test

Build Targets

Desktop (default)

cargo build --release

Produces:

  • target/release/nes.dll (Windows)
  • target/release/libnes.so (Linux)
  • target/release/libnes.dylib (macOS)
  • target/release/libnes.rlib (Rust static lib)

Shared library with FFI

cargo build --release --no-default-features --features ffi

This exposes C-compatible symbols (nes_init, nes_load_rom, etc.) for use from other languages.

Static library for embedded

rustup target add thumbv7em-none-eabihf
cargo build --release --target thumbv7em-none-eabihf --no-default-features --features ffi

WebAssembly (future)

rustup target add wasm32-unknown-unknown
cargo build --release --target wasm32-unknown-unknown

Test Suite

Unit Tests

cargo test                          # All unit tests
cargo test --lib                    # Library tests only
cargo test rom                      # ROM parser tests only

The unit tests cover:

  • ROM parsing: iNES 1.0/2.0 detection, mapper identification, mirroring, trainer, PRG/CHR sizing
  • Mapper creation: NROM, UxROM, MMC3 initialization and basic reads
  • Bank switching: MMC3 PRG bank switching, SMB3 header verification

AccuracyCoin

cargo test --test accuracy_coin

This runs the comprehensive AccuracyCoin test suite (141 tests) that validates:

  • CPU instructions (all official + unofficial)
  • PPU timing (VBlank, NMI, sprite evaluation)
  • APU channels and frame counter
  • DMA (OAM DMA, DMC DMA)
  • Controller input
  • Edge cases (open bus, dummy reads, bus conflicts)

Current score: 86/141 pass, 55 fail (61%)

Blargg Tests (external)

Download Blargg’s test ROMs and run them:

# CPU instruction test
cargo run --example main -- "tests/nestest.nes"

# PPU VBlank/NMI test
cargo run --example main -- "tests/blargg_ppu_tests/ppu_vbl_nmi.nes"

Performance Profiling

Release Build

Always test performance with --release. Debug builds are 10-100x slower:

cargo run --release --example main -- "rom.nes"

Benchmark Frames Per Second

#![allow(unused)]
fn main() {
let start = std::time::Instant::now();
let target_frames = 600; // 10 seconds at 60fps
let mut frame_count = 0u32;

while frame_count < target_frames {
    tick(&mut cpu, &mut bus);
    if bus.ppu.frame_complete {
        bus.ppu.frame_complete = false;
        frame_count += 1;
    }
}

let elapsed = start.elapsed();
let fps = frame_count as f64 / elapsed.as_secs_f64();
println!("{:.1} FPS (target: 60.0)", fps);
}

CPU Profiling

Use perf on Linux or samply (cross-platform):

# Linux
perf record --call-graph dwarf cargo run --release --example main -- "rom.nes"
perf report

# Cross-platform
cargo install samply
samply record cargo run --release --example main -- "rom.nes"

Cycle Counting

Add a cycle counter to find expensive code paths:

#![allow(unused)]
fn main() {
use std::time::Instant;

let start = Instant::now();
for _ in 0..10_000_000 {
    tick(&mut cpu, &mut bus);
}
let elapsed = start.elapsed();
let ns_per_tick = elapsed.as_nanos() as f64 / 10_000_000.0;
println!("{} ns per tick ({} MHz emulated)", ns_per_tick, 1000.0 / ns_per_tick);
}

Debug Builds

The debug profile (cargo build) is useful for:

  • Faster compile times during development
  • Debug symbols for breakpoints
  • Assertions and overflow checks

But it’s 10-100x slower than release. Use --release for performance testing.

Dev Profile Optimizations

The Cargo.toml dev profile is configured for faster iteration:

[profile.dev]
panic = "abort"    # Smaller binaries, no unwinding overhead

Crate Structure

x-nes/
├── Cargo.toml          # Library + example config
├── src/
│   ├── lib.rs          # Main tick/reset/NMI/IRQ functions
│   ├── cpu.rs          # CPU register struct (RP2A03)
│   ├── ops.rs          # Instruction implementations (256-entry jump table)
│   ├── bus.rs          # Memory bus, PPU sync, OAM DMA
│   ├── rom.rs          # iNES parser, mapper dispatch
│   ├── controller.rs   # Gamepad input
│   ├── clock.rs        # Timing conversions
│   ├── address.rs      # Memory region classification
│   ├── interrupt.rs    # Vector address constants
│   ├── apu/            # Audio Processing Unit
│   │   ├── mod.rs      # APU state machine, mixer
│   │   ├── pulse.rs    # Square wave channels
│   │   ├── triangle.rs # Triangle wave channel
│   │   ├── noise.rs    # Noise channel (LFSR)
│   │   └── dmc.rs      # Delta Modulation Channel
│   ├── ppu/            # Picture Processing Unit
│   │   ├── mod.rs      # PPU state, tick, timing
│   │   ├── registers.rs # PPU register I/O
│   │   ├── bus.rs       # VRAM address space, NT/palette access
│   │   └── render.rs    # Background/sprite pixel rendering
│   └── mapper/         # Cartridge mappers
│       ├── mod.rs       # MapperImpl trait, Mapper enum
│       ├── nrom.rs      # Mapper 0 (NROM)
│       ├── mmc1.rs      # Mapper 1 (MMC1)
│       ├── uxrom.rs     # Mapper 2 (UxROM)
│       ├── cnrom.rs     # Mapper 3 (CNROM)
│       ├── mmc3.rs      # Mapper 4 (MMC3)
│       ├── mmc5.rs      # Mapper 5 (MMC5)
│       ├── axrom.rs     # Mapper 7 (AxROM)
│       └── gxrom.rs     # Mapper 66 (GxROM)
├── examples/
│   ├── main.rs         # Headless emulator (console output only)
│   └── window.rs       # GUI emulator (softbuffer + winit, with audio)
├── docs/
│   └── src/            # This documentation (mdBook)
└── tests/              # Test ROMs and test harnesses

Adding Features

Adding a Feature Flag

In Cargo.toml:

[features]
my_feature = []

In code:

#![allow(unused)]
fn main() {
#[cfg(feature = "my_feature")]
fn extra_functionality() { ... }
}

Build with:

cargo build --features my_feature

Adding a New Example

  1. Create examples/my_example.rs
  2. Add to Cargo.toml:
[[example]]
name = "my_example"
path = "examples/my_example.rs"
  1. Run: cargo run --example my_example

Continuous Integration

The project uses GitHub Actions (.github/workflows/ci.yml). CI runs:

  • cargo build and cargo test on Linux, Windows, macOS
  • cargo clippy for linting
  • cargo fmt --check for formatting

Running CI Locally

# Check formatting
cargo fmt --check

# Run linter
cargo clippy -- -D warnings

# Run all tests
cargo test --all

Common Build Issues

“file too big” when building for MCU

Reduce binary size:

[profile.release]
opt-level = "s"     # Optimize for size
lto = true
codegen-units = 1
strip = true

“can’t find crate for std” on embedded

Make sure you’re using --no-default-features and targeting a no_std platform.

Softbuffer/winit errors on Wayland

Set environment variable:

WINIT_UNIX_BACKEND=x11 cargo run --example window -- "rom.nes"

“missing config” or other dependency errors

The window example needs dev-dependencies:

cargo run --example window   # NOT --lib or --release-only

These are in [dev-dependencies], available when building examples and tests.