# snes.asm — 65C816 assembler
A two-pass 65C816 assembler in Luau, for Super Nintendo homebrew built inside the engine (also fine for any 65816 / 6502-family target).
```lua
local Asm = require("snes.asm")
local bin, symbols = Asm.assemble(source, { map = "lorom", size = 0x40000, fill = 0xFF, blobs = { tiles = "..." } })
```
- Addresses are 24-bit. `org $808000` sets the full address; the file offset comes from the map: `lorom` = (bank & $7F) * $8000 + (addr & $7FFF), running past $FFFF continues at the next bank's $8000; `hirom` = addr & $3FFFFF; `flat` = addr - org of the first `org`.
- Immediate widths: `.a8 .a16 .i8 .i16` (also `.smart`-style tracking: `rep #$20/$10/$30` and `sep` with a constant switch the widths for the lines after them), or a `.b`/`.w` suffix on the mnemonic.
- Operand sizes are decided in pass 1 so the layout never moves: `<expr` direct page, `!expr` or `|expr` absolute, `>expr` long; a mnemonic suffix `.b .w .l` does the same. Without a prefix: a value known in pass 1 that is <= $FF is direct page, a plain number literal > $FFFF is long, everything else is absolute (labels are absolute: their bank comes from DBR/PBR). `jsl`/`jml` are always long.
- Every 65816 addressing mode: `#`, dp, dp,x, dp,y, (dp), (dp,x), (dp),y, [dp], [dp],y, abs, abs,x, abs,y, long, long,x, sr,s, (sr,s),y, (abs) / (abs,x) for jmp/jsr, [abs] for jml, rel8, rel16 (`brl`, `per`), `mvn src,dst` / `mvp src,dst` (bank numbers or `#bank`, written in WLA/ca65 source order: source first).
- Directives: `org`, `db/byte`, `dw/word`, `dl/long` (24-bit), `ds n[,fill]`, `align n`, `assert expr`, `incbin name` (bytes from `opts.blobs[name]`), `name equ expr` / `name = expr`.
- Expressions: `$FF`, `0xFF`, `%0101`, `'c'`, `*` (here), `+ - * / % << >> & | ^ ~ ( )`, `lo() hi() bank()` and `^label` (bank byte).
- Labels `name:`, local `.x` scoped to the last global label. Errors name the line.
# snes.cpu65816 — WDC 65C816 CPU
A reusable 65C816 core (Super Nintendo, Apple IIGS, SA-1 style machines) as a table of 256 closures over upvalue registers.
```lua
local Cpu = require("snes.cpu65816")
local cpu = Cpu.new({
read = function(adr24) return byte end, -- slow path (I/O, unmapped)
write = function(adr24, v) end,
-- fast path, per 8 KB page (2048 pages over 24 bits): buffer + offset (+ writable)
-- and the master clocks one access to the page costs
map = function(page) return buf, off, writable, clocks end,
})
cpu.reset()
local used = cpu.run(untilMasterClock) -- runs whole instructions until cycles() >= the limit
cpu.nmi() ; cpu.setIrq(true/false) ; cpu.remap(page?) ; cpu.addCycles(n) ; cpu.setLimit(n)
cpu.getState() / cpu.setState(t) ; cpu.regs() / cpu.setRegs(t)
```
- Registers: A/C (16-bit, B is the high byte while M=1), X, Y (high byte 0 while X=1), S (page 1 in emulation), D, DBR, PBR, PC, P, E.
- Every documented opcode incl. MVN/MVP (one byte per step, interruptible), PEA/PEI/PER, REP/SEP, XCE, XBA, COP, BRK, WDM, WAI (wakes on NMI or IRQ, even with I set), STP.
- Decimal ADC/SBC in 8 and 16 bit.
- Timing in master clocks: each bus access costs what `map` says for its page, each internal operation 6; dp with D low byte set, index page crossing, 16-bit operands and RMW add the documented extra cycles.
- Flags kept as `nf`/`zf` values (N = bit 7 of nf, which holds the high byte of 16-bit results; Z = zf == 0).
Tests: `snes.package/tests/cpu_tests.luau`.
# snes.homebrew — original CC0 Super Nintendo carts, built in-engine
Everything here is written for this world and released under **CC0 1.0** (public domain): the 65816 runtime, the SPC700 sound driver, the BRR instruments (synthesised in Luau), the music and both games.
- **Horizon Kart** (`kart.luau`, 1 player): a time-trial kart racer on a mode 7 track. HDMA sets the mode 7 matrix on every line from per-angle tables in ROM (perspective + rotation), switches mode 1 → mode 7 at the horizon so a mountain BG scrolls with the heading above a sky gradient (HDMA on colour 0). The kart and the HUD are sprites. Off-road slows you down; three laps with checkpoints; the best total time is kept in battery SRAM. B = accelerate, Y = brake, D-pad = steer, Start = start/pause.
- **Puck Rush** (`puck.luau`, 2 players): air hockey in mode 1. Pad 2 plays the right mallet (the CPU plays it until pad 2 presses a button). Shows windows (an HDMA-shaped spotlight on goals), colour math (additive glow on the puck trail, subtractive shadow), BG3 text, sprites, music and sound effects. First to 7.
Luau API:
```lua
local H = require("snes.homebrew")
H.build(true) -- assemble every game; write /zero/source/snes_roms/*.sfc
H.buildGame("kart") -- -> rom bytes
H.tile4(pixels) / H.tile2 / H.tile8 -- 64 palette indices -> planar tile bytes
H.rgb(r, g, b) -- 0..31 each -> BGR555
H.brr(samples, loop) -- int16 samples -> BRR blocks
H.track("I0 C4:2 E4:2 G4:4 R:4", ticksPerUnit) -- sequence bytes for the driver
H.driverImage(songs, sfx) -- the sound driver + instruments + songs as one ARAM image from $0200
H.RUNTIME -- 65816 runtime source (reset, NMI with OAM DMA, pads, APU boot, music/SFX commands, sprites, text)
```
Runtime conventions: the game runs in native mode with 8-bit A / 16-bit X,Y, DBR = $80, D = 0, code in fast ROM bank $80. WRAM $00 is the logic-step counter (advanced once per game step: the logic-rate probe), OAM buffer at $0200, BG text buffer at $7E2000. A game defines `Main`, `VBlank` (run inside NMI when a frame is ready) and `Irq`.
# snes.machine
The Super Nintendo (NTSC) machine: the 65C816 (`snes.cpu65816`) on a 24-bit bus with LoROM/HiROM carts (`cart.luau`: copier header, zip, header scoring, SRAM), WRAM 128 KB + the WRAM port, the multiplier/divider, auto and manual joypad reads, NMI and H/V timer IRQs, MEMSEL fast ROM, 8 DMA channels (all transfer modes) and HDMA (direct/indirect, repeat, line counters), the S-PPU line renderer (`ppu.luau`), the APU (`apu.luau`: SPC700 + S-DSP, caught up on every port access), a 262-line scheduler and save states. Called by the `snes` emulatorCore and the package tests.
```lua
local Snes = require("snes.machine")
local m = Snes.new(cartBytes)
m:runFrame(true) -- one frame; false skips drawing
m.fb -- 512x224 RGBA (256-pixel modes doubled, hi-res 1:1)
m:setPad(p1, p2) -- station words (bit0 R,1 L,2 U,3 D,4 A,5 B,6 C,7 D,8 Start,9 Select,10 L,11 R)
m:drainAudio() -- 44.1 kHz stereo f32
m:snapshot() / m:restore(s) ; m:saveSram() / m:loadSram(s) ; m:watchRam(addr)
```
PPU: modes 0-7, 8x8/16x16 tiles, 32/64 maps, per-BG scroll, mosaic, offset-per-tile (modes 2/4/6), mode 7 (matrix, flips, wrap/transparent/tile-0, EXTBG), direct colour, 128 OBJ with OBSEL sizes, 32-per-line and 34-sliver limits and flags, priority rotation, two windows with OR/AND/XOR/XNOR per layer and the colour window, main/sub screens with add/sub/half colour math and the fixed colour, brightness and forced blank. Hi-res modes 5/6 draw 512 pixels; pseudo-hires and interlace draw as 256/224.
# snes (emulatorCore)
Super Nintendo / Super Famicom (NTSC) console spec for the room's console TVs and any RetroConsole cabinet: a 512×224 picture at 60.1 Hz (256-pixel modes doubled, hi-res modes 5/6 at 512 1:1, so every mode fills the tube), the SPC700 + S-DSP as 44.1 kHz stereo PCM, battery SRAM saved per cart under `snes_saves/`, and whole-machine save states. The machine is `snes.machine`.
- Carts: `.sfc` / `.smc` (raw; a 512-byte copier header is dropped; LoROM/HiROM from the header) or a `.zip` holding one (`claims` files it under this console).
- `tv = true`: a room TV offers it by itself; `padBar` names its buttons.
- Runs on the station's worker thread (`workerModule`), drawing only the frame shown (`drawControl`).
- `setPad(m, p1, p2)`: TV pad A → SNES B, B → A, C → Y, D → X, Start, Select; station bits 10/11 → L/R (the TV pad has no shoulder buttons in its word today, so L/R are reachable from scripts and the keyboard only). Pad 2 = player 2.
- Keyboard (standalone): arrows/WASD, J/Z = B, K/X = A, U = Y, I = X, Q/E = L/R, Enter = Start, Shift = Select.
- The shelf's built-in carts are the package's CC0 homebrew (`snes.homebrew`) in `/zero/source/snes_roms/`.
# snes.spc700 — Sony SPC700 CPU
The Super Nintendo sound CPU as a reusable core: a table of 256 closures over upvalue registers, cycle counts per instruction (taken branches +2).
```lua
local Spc = require("snes.spc700")
local cpu = Spc.new(aram, { read = fn(adr) for $F0-$FF and the IPL window, write = fn(adr, v), iplOn = fn() -> boolean })
cpu.reset() ; cpu.run(untilCycle) ; cpu.cycles()
cpu.regs() / cpu.setRegs(t) ; cpu.getState() / cpu.setState(t)
```
- Registers A, X, Y, SP, PC, PSW (N V P B H I Z C), the direct page at $00xx or $01xx by P.
- Every opcode: MOV/MOVW, ADC/SBC/CMP/AND/OR/EOR in all their forms incl. memory-to-memory, ADDW/SUBW/CMPW/INCW/DECW, MUL, DIV (with the hardware's overflow behaviour), DAA/DAS, XCN, bit ops (SET1/CLR1/TSET1/TCLR1, AND1/OR1/EOR1/NOT1/MOV1), BBS/BBC/CBNE/DBNZ, CALL/PCALL/TCALL/BRK/RET/RETI, PUSH/POP, SLEEP/STOP.
- RAM reads go straight to the 64 KB buffer except $00F0-$00FF and $FFC0-$FFFF (when the IPL ROM is shown), which go to `io.read`.
Tests: `snes.package/tests/apu_tests.luau`.
# snes.spcasm — SPC700 assembler
A two-pass SPC700 assembler in Luau for Super Nintendo sound programs (the APU's IPL boot ROM and the homebrew sound driver are built with it).
```lua
local SpcAsm = require("snes.spcasm")
local bytes, symbols, base = SpcAsm.assemble(source, { org = 0x0200, blobs = { samples = "..." } })
```
- Sony-style syntax: `mov a,#$12`, `mov $12,a`, `mov !$1234,a`, `mov a,(x)`, `mov a,(x)+`, `mov a,[$12+x]`, `mov a,[$12]+y`, `mov a,$12+x`, `mov a,!table+y`, `mov $12,#$34`, `mov $12,$34` (dest, source), `movw ya,$12`, `set1 $12.3`, `bbs $12.3,label`, `cbne $12,label`, `dbnz y,label`, `mov1 c,$1234.5`, `or1 c,/$1234.5`, `tcall 3`, `pcall $80`, `call label`, `jmp [!table+x]`, `push psw`, `mul ya`, `div ya,x`, every opcode of the set.
- Operand sizes are decided in pass 1: `!expr` is absolute; otherwise a value known in pass 1 and <= $FF is direct page and anything else absolute.
- Directives: `org`, `db/byte`, `dw/word`, `ds n[,fill]`, `align n`, `assert expr`, `incbin name` (bytes from `opts.blobs[name]`), `name equ expr` / `name = expr`; labels `name:`, local `.x`. Expressions as in `snes.asm` (shares its evaluator).
- Returns the bytes from the lowest to the highest address written, the symbol table and the lowest address.