#!/usr/bin/env python3 """Run the game's own scene code in scr_snes and check it against an scr_trace.lua capture. usage: scr_run.py ROM CAPDIR --frames N [--plan "f:btn+btn/hold,..."] [--pokes "f1-f2:addr=val+..."] [--render "mesenframe,..."] [--out DIR] [--report] Our frames run ahead of Mesen's because the stubbed sound driver answers instantly (the real APU uploads take frames). The runner keeps a running offset: every DECOMP / VRAM-DMA event we produce is matched in order with the capture's, and offset = mesen_frame - our_frame of the last match. Inputs and pokes are given in Mesen frame numbers and applied at our frame = mesen - offset. With --report, CGRAM and OAM are compared every frame and VRAM at each capture snapshot (written regions only). """ import argparse import os import re import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import scr_snes # noqa: E402 def capture_events(capdir): ev = [] for line in open(os.path.join(capdir, 'events.txt')): m = re.match(r'f(\d+) DECOMP caller=\w+ src=(\w+) dst=(\w+)', line) if m: ev.append((int(m.group(1)), 'D', m.group(2), m.group(3))) continue m = re.match(r'f(\d+) DMA .*bb=21(18|19) src=(\w+) n=(\w+) vaddr=(\w+)', line) if m: ev.append((int(m.group(1)), 'V', m.group(3), m.group(5))) return ev def parse_plan(spec): out = [] for item in (spec or '').split(','): m = re.match(r'(\d+):([\w+]+)(?:/(\d+))?$', item.strip()) if m: out.append((int(m.group(1)), m.group(2).split('+'), int(m.group(3) or 4))) return out def parse_pokes(spec): out = [] for item in (spec or '').split(','): m = re.match(r'(\d+)-(\d+):(.+)$', item.strip()) if m: sets = [(int(a, 16), int(v, 16)) for a, v in re.findall(r'(\w+)=(\w+)', m.group(3))] out.append((int(m.group(1)), int(m.group(2)), sets)) return out class Runner: def __init__(self, rom, capdir=None): self.s = scr_snes.SNES(rom) self.capdir = capdir self.cap = capture_events(capdir) if capdir else [] self.ci = 0 self.offset = 0 self.mine = [] self.unmatched = 0 s = self.s orig_dma = s.run_dma def dma(mask): for ch in range(8): if mask >> ch & 1: b = ch * 16 if s.dma[b + 1] in (0x18, 0x19) and not s.dma[b] & 0x80: src = f'{s.dma[b + 4]:02X}{s.dma[b + 3]:02X}{s.dma[b + 2]:02X}' self.event('V', src, f'{s.vaddr:04X}') orig_dma(mask) s.cpu.io[0x420B] = (s.cpu.io[0x420B][0], lambda v: (s.reg.__setitem__(0x420B, v), dma(v))) # The capture logs the decompressor at its exit (80:B868), so do the same. pending = [] def decomp_entry(cpu): # 80:B7DA: A = src bank, B = dst bank, X = src, Y = dst pending.append((f'{cpu.a & 0xFF:02X}{cpu.x:04X}', f'{(cpu.a >> 8) & 0xFF:02X}{cpu.y:04X}')) hook = cpu.hooks.pop(0x80B7DA) cpu.step() cpu.hooks[0x80B7DA] = hook def decomp_exit(cpu): if pending: self.event('D', *pending.pop()) hook = cpu.hooks.pop(0x80B868) cpu.step() cpu.hooks[0x80B868] = hook s.cpu.hooks[0x80B7DA] = decomp_entry s.cpu.hooks[0x80B868] = decomp_exit def event(self, kind, a, b): f = self.s.frame + 1 self.mine.append((f, kind, a, b)) # Match against the next capture events of the same kind/content (skip a few if needed). for j in range(self.ci, min(self.ci + 40, len(self.cap))): cf, ck, ca, cb = self.cap[j] if ck == kind and ca == a and (cb == b or kind == 'V'): # capture's vaddr is stale across chained DMAs self.offset = cf - f self.ci = j + 1 return self.unmatched += 1 def mesen_frame(self): return self.s.frame + 1 + self.offset def run(self, frames, plan=(), pokes=(), on_frame=None): s = self.s for _ in range(frames): mf = self.mesen_frame() pad = 0 for f, buttons, hold in plan: if f <= mf < f + hold: pad |= scr_snes.pad_word(buttons) s.pad = [pad, 0] for f1, f2, sets in pokes: if f1 <= mf <= f2: for a, v in sets: s.cpu.wram[a] = v lines = s.frame_step() if on_frame: on_frame(self, lines) def main(): ap = argparse.ArgumentParser() ap.add_argument('rom') ap.add_argument('capdir') ap.add_argument('--frames', type=int, default=600) ap.add_argument('--plan', default='') ap.add_argument('--pokes', default='') ap.add_argument('--render', default='') ap.add_argument('--out', default='re/runs/scr/render') ap.add_argument('--report', action='store_true') args = ap.parse_args() rom = open(args.rom, 'rb').read() r = Runner(rom, args.capdir) cg = open(os.path.join(args.capdir, 'cgram.bin'), 'rb').read() oam = open(os.path.join(args.capdir, 'oam.bin'), 'rb').read() want = {int(x) for x in args.render.split(',') if x} os.makedirs(args.out, exist_ok=True) stats = {'frames': 0, 'cg_ok': 0, 'oam_ok': 0, 'vram': []} def on_frame(rr, lines): s = rr.s mf = rr.mesen_frame() - 1 # state after our frame f corresponds to Mesen's end-of-frame dump f+offset if args.report and 0 < mf <= len(cg) // 0x200: stats['frames'] += 1 c = cg[(mf - 1) * 0x200: mf * 0x200] o = oam[(mf - 1) * 0x220: mf * 0x220] stats['cg_ok'] += c == bytes(s.cgram) stats['oam_ok'] += o == bytes(s.oam) vp = os.path.join(args.capdir, f'f{mf:05d}.vram') if os.path.exists(vp): v = open(vp, 'rb').read() diff = sum(1 for i in range(0x10000) if v[i] != s.vram[i] and s.vram_written[i]) stats['vram'].append((mf, diff, sum(s.vram_written))) if mf in want: import scr_ppu img = scr_ppu.render_frame(s, lines) scr_ppu.write_png(os.path.join(args.out, f'f{mf:05d}.png'), img) # Track which VRAM bytes the program wrote (Mesen starts with noise elsewhere). s = r.s s.vram_written = bytearray(0x10000) orig = s.ppu_write def ppu_write(a, v): if a in (0x2118, 0x2119): s.vram_written[s._vram_word() * 2 + (a - 0x2118)] = 1 orig(a, v) s.ppu_write = ppu_write for a in range(0x2100, 0x2200): s.cpu.io[a] = (s.cpu.io[a][0], lambda v, a=a: s.ppu_write(a, v)) r.run(args.frames, parse_plan(args.plan), parse_pokes(args.pokes), on_frame) print(f'ran {args.frames} frames; matched {r.ci}/{len(r.cap)} capture events, unmatched own events {r.unmatched}; ' f'offset now {r.offset}; pc {r.s.cpu.pbr:02X}:{r.s.cpu.pc:04X}') if args.report: print(f"CGRAM identical {stats['cg_ok']}/{stats['frames']} frames, OAM identical {stats['oam_ok']}/{stats['frames']}") bad = [(f, d, n) for f, d, n in stats['vram'] if d] print(f"VRAM snapshots: {len(stats['vram'])}, with differences in written bytes: {len(bad)}") for f, d, n in bad: print(f" f{f}: {d} of {n} written bytes differ") if __name__ == '__main__': main()