#!/usr/bin/env python3 """Execute the ROM's leaf collision routine with a bounded 6502 subset. Not a NES emulator: only the opcodes reached by GetCollidingTileMoving for player 0 in overworld room $77. Unsupported instructions fail explicitly. """ import hashlib import json import re from extract_graphics import ROOT, ROM_SHA256 DATA = json.loads((ROOT / 'extracted/overworld/start/collision-data.json').read_text()) ROM = (ROOT / '.tmp/zelda-1.nes').read_bytes() assert hashlib.sha256(ROM).hexdigest() == ROM_SHA256 BASE = bytearray(65536) BASE[0xC000:] = ROM[16 + 7 * 16384:16 + 8 * 16384] for col in range(32): p = BASE[0xE400 + col * 2] | BASE[0xE401 + col * 2] << 8 for row in range(22): BASE[p + row] = DATA['tiles'][row * 32 + col] def rom_probe(x, y, direction, slot=0, room_id=0x77): m = BASE.copy() m[0x70+slot], m[0x84+slot], m[0x0F], m[0xEB] = x, y, direction, room_id a, index = 0, slot iy, sp, pc = 0, 0xFD, 0xEDFA carry = zero = negative = False def nz(v): nonlocal zero, negative v &= 255 zero, negative = v == 0, bool(v & 128) return v def byte(): nonlocal pc v = m[pc] pc += 1 return v def word(): lo = byte() return lo | byte() << 8 for _ in range(1000): at = pc op = byte() if op == 0x60: return a if op in (0xF0, 0xD0, 0xB0, 0x90, 0x30): offset = byte() condition = {0xF0: zero, 0xD0: not zero, 0xB0: carry, 0x90: not carry, 0x30: negative}[op] if condition: pc += offset if offset < 128 else offset - 256 elif op == 0x4C: pc = word() elif op == 0xA0: iy = nz(byte()) elif op == 0xA4: iy = nz(m[byte()]) elif op == 0xB4: iy = nz(m[(byte() + index) & 255]) elif op == 0xA9: a = nz(byte()) elif op == 0xA5: a = nz(m[byte()]) elif op == 0xB5: a = nz(m[(byte() + index) & 255]) elif op == 0xBD: a = nz(m[word() + index]) elif op == 0xB9: a = nz(m[word() + iy]) elif op == 0xB1: p = byte() a = nz(m[(m[p] | m[(p + 1) & 255] << 8) + iy]) elif op == 0x84: m[byte()] = iy elif op == 0x85: m[byte()] = a elif op == 0x8D: m[word()] = a elif op == 0x9D: m[word() + index] = a elif op == 0xA8: iy = nz(a) elif op == 0x98: a = nz(iy) elif op == 0x88: iy = nz(iy - 1) elif op == 0x48: m[0x100 + sp] = a sp = (sp - 1) & 255 elif op == 0x68: sp = (sp + 1) & 255 a = nz(m[0x100 + sp]) elif op == 0x18: carry = False elif op == 0x38: carry = True elif op == 0x29: a = nz(a & byte()) elif op == 0x25: a = nz(a & m[byte()]) elif op == 0x4A: carry = bool(a & 1) a = nz(a >> 1) elif op in (0x69, 0x65, 0xE9): v = m[byte()] if op == 0x65 else byte() result = a + v + carry if op != 0xE9 else a - v - (not carry) carry = result > 255 if op != 0xE9 else result >= 0 a = nz(result) elif op in (0xE0, 0xC0, 0xC9, 0xD9, 0xDD): lhs = index if op == 0xE0 else iy if op == 0xC0 else a rhs = m[word() + iy] if op == 0xD9 else m[word() + index] if op == 0xDD else byte() carry = lhs >= rhs nz(lhs - rhs) else: raise AssertionError(f'Unsupported opcode ${op:02X} at ${at:04X}') raise AssertionError('Collision routine did not return') def port_probe(x, y, direction): offset = {1: 16, 2: -8, 4: 8, 8: -8}[direction] sx, sy = x, (y + 11) % 256 if direction in (4, 8): if direction == 8 or sy < 221: sy = (sy + offset) % 256 elif (direction == 1 and x < 240) or (direction == 2 and x >= 16): sx = (sx + offset) % 256 col, row = sx // 8, ((sy - 64) % 256) // 8 def tile(c, r): return DATA['tiles'][r * 32 + c] if 0 <= c < 32 and 0 <= r < 22 else 255 value = tile(col, row) if direction in (4, 8): value = max(value, tile(col + 1, row)) return 38 if value in DATA['walkable_exceptions'] else value def main(): generated = (ROOT / "src/stages/overworld_start/room.generated.pbs").read_text() literal = generated.split("= [", 1)[1].split("];", 1)[0] assert [int(v) for v in re.findall(r"\d+", literal)] == DATA["tiles"] checked = 0 # Only valid interior probes. The port closes exits, whereas the ROM can # read adjacent column buffers there and then initiate a room transition. for x in range(0, 241, 8): for y in range(61, 222, 8): for direction in (1, 2, 4, 8): # At y=61, upward reads the HUD/buffer before the play area; # that position is an exit, not a terrain query in this wave. if y == 61 and direction == 8: continue actual, expected = port_probe(x, y, direction), rom_probe(x, y, direction) assert actual == expected, (x, y, direction, actual, expected) checked += 1 report = {'rom_sha256': ROM_SHA256, 'room_id': 119, 'entrypoint': 'GetCollidingTileMoving ($EDFA)', 'probes_compared': checked, 'mismatches': 0, 'generated_pbs_tile_array_matches': True, 'scope': 'Leaf 6502 collision routine versus port model, interior grid probes; excludes screen transitions, cave triggers and whole-game execution.'} (ROOT / 'extracted/overworld/start/collision-rom-validation.json').write_text(json.dumps(report, indent=2) + '\n') print(json.dumps(report)) if __name__ == '__main__': main()