Files

114 lines
4.9 KiB
Python

#!/usr/bin/env python3
"""Attribute VRAM contents to ROM assets by replaying a capture's decompressor calls and VRAM DMAs.
Input: a re/lua/gfx_dma.lua capture (dma.txt with DMA + DECOMP lines in execution order, fNNNNN.vram dumps). Models WRAM bank $7F (and $7E8000+) as "which asset byte lives here", replays the DMAs into
a VRAM model, and at every dump frame reports which VRAM ranges came from which compressed asset and how much
of VRAM is reproducible from the ROM alone.
usage: gfx_screens.py ROM DMA_DIR [--json OUT]"""
import json
import os
import re
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from gfx_decomp import decompress # noqa: E402
def parse(dma_dir):
"""Events in execution order from gfx_dma.lua's dma.txt (DMA and DECOMP lines)."""
ev = []
rx = re.compile(r'f(\d+) pc=(\w+) ch\d dmap=(\w+) bb=21(\w\w) src=(\w+) n=(\w+) vaddr=(\w+) vmain=(\w+)')
rd = re.compile(r'f(\d+) DECOMP caller=(\w+) src=(\w+) dst=(\w+)')
for line in open(os.path.join(dma_dir, 'dma.txt')):
m = rd.match(line)
if m:
f, caller, src, dst = m.groups()
ev.append((int(f), 0, 'decomp', int(src, 16), int(dst, 16), int(caller, 16)))
continue
m = rx.match(line)
if not m:
continue
f, pc, dmap, bb, src, n, vaddr, vmain = m.groups()
if bb not in ('18', '19'):
continue
ev.append((int(f), 1, 'dma', int(src, 16), int(n, 16), int(vaddr, 16), int(dmap, 16), int(vmain, 16), int(pc, 16)))
return ev
def main():
rom = open(sys.argv[1], 'rb').read()
dma_dir = sys.argv[2]
out_json = sys.argv[sys.argv.index('--json') + 1] if '--json' in sys.argv else None
ev = parse(dma_dir)
dumps = sorted(int(fn[1:6]) for fn in os.listdir(dma_dir) if re.match(r'f\d{5}\.vram$', fn))
wram = {} # 24-bit addr -> (asset_src, offset, value)
vram = [None] * 0x10000 # byte -> (asset_src, offset, value) or ('dyn', src_addr) or None
report = {}
di = 0
for e in ev + [(10 ** 9, 9, 'end')]:
while di < len(dumps) and e[0] > dumps[di]:
f = dumps[di]
real = open(os.path.join(dma_dir, f'f{f:05d}.vram'), 'rb').read()
ranges, cur = [], None
ok = rom_bytes = 0
for a in range(0x10000):
v = vram[a]
tag = v[0] if v and v[0] != 'dyn' else ('dyn' if v else None)
if v and v[0] != 'dyn':
rom_bytes += 1
ok += v[2] == real[a]
key = (tag, (a - v[1]) if v and v[0] != 'dyn' else None)
if cur and cur['key'] == key and cur['end'] == a:
cur['end'] = a + 1
else:
cur = {'key': key, 'start': a, 'end': a + 1}
ranges.append(cur)
rep = []
for r in ranges:
tag, base = r['key']
if tag is None:
continue
if tag == 'dyn':
rep.append({'vram': f"{r['start']:04X}-{r['end'] - 1:04X}", 'source': 'runtime buffer'})
else:
rep.append({'vram': f"{r['start']:04X}-{r['end'] - 1:04X}", 'asset': f'{tag:06X}',
'asset_offset': f"{r['start'] - base:04X}"})
report[f] = {'rom_bytes': rom_bytes, 'rom_bytes_matching_dump': ok, 'ranges': rep}
print(f'== frame {f}: {rom_bytes} VRAM bytes attributed to ROM assets, {ok} match the dump '
f'({100 * ok / max(rom_bytes, 1):.2f}%)')
for r in rep:
if 'asset' in r and int(r['vram'].split('-')[1], 16) - int(r['vram'].split('-')[0], 16) >= 0x7F:
print(f" VRAM {r['vram']} <- {r['asset']} +{r['asset_offset']}")
di += 1
if e[2] == 'end':
break
if e[2] == 'decomp':
_, _, _, src, dst, caller = e
out, _, _ = decompress(rom, src)
for i, v in enumerate(out):
wram[(dst + i) & 0xFFFFFF] = (src, i, v)
else:
_, _, _, src, n, vaddr, dmap, vmain, pc = e
if n == 0:
n = 0x10000
fixed = dmap & 0x08
# vmain $80: word increment after the high byte; bb=18 dmap=01 writes lo/hi pairs.
word_mode = (dmap & 7) == 1
for i in range(n):
s = src if fixed else (src + i) & 0xFFFFFF
if word_mode:
a = ((vaddr + i // 2) * 2 + (i & 1)) & 0xFFFF
elif vmain & 0x80:
a = ((vaddr + i) * 2 + 1) & 0xFFFF
else:
a = ((vaddr + i) * 2) & 0xFFFF
w = wram.get(s) if (s >> 16) in (0x7E, 0x7F) else None
vram[a] = w if w else ('dyn', s)
if out_json:
json.dump(report, open(out_json, 'w'), indent=1)
if __name__ == '__main__':
main()