#!/usr/bin/env python3 """Synthetic register streams for every mode, run through MAME as SG-1000 cartridges. Each case is a full 16K VRAM image (pseudo-random tables plus hand-placed sprites) and eight register writes. ``build_rom`` wraps them in a 32K SG-1000 image: a hand-assembled Z80 loop copies the image to VRAM at about 50 clocks a byte and then plays the register stream at about 68 clocks a write (both slower than any access window), then spins with interrupts off. MAME's VDP log of that cartridge (scripts/mame_vdp_log.py) is then a register stream with a detector picture at its end. python -I validation/synthetic.py record # one MAME run per case, 2 s each python -I validation/synthetic.py compare # core vs MAME vs sms-python The images are generated here and written under tests/mame_traces/ (git-ignored). """ from __future__ import annotations import os import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "validation")) import mame_replay # noqa: E402 (puts src on the path if the package is not importable) TRACES = ROOT / "tests" / "mame_traces" # read-only detector, never copied: a sibling sms-python checkout (SMS_PYTHON overrides) SMS_PYTHON = Path(os.environ.get("SMS_PYTHON") or ROOT.parent / "sms-python") / "src" # Hand-assembled Z80 (addresses in the comments): # 0000 F3 DI # 0001 31 F0 C3 LD SP,$C3F0 # 0004 3E xx LD A,r1_first ; R1 before the copy: $80 (16K, blanked) or $00 # 0006 D3 BF OUT ($BF),A # 0008 3E 81 LD A,$81 # 000A D3 BF OUT ($BF),A # 000C 3E 00 LD A,$00 # 000E D3 BF OUT ($BF),A ; VRAM address $0000 for writing # 0010 3E 40 LD A,$40 # 0012 D3 BF OUT ($BF),A # 0014 21 00 40 LD HL,$4000 ; the VRAM image # 0017 01 00 40 LD BC,$4000 # 001A 7E LD A,(HL) ; L1 # 001B D3 BE OUT ($BE),A # 001D 23 INC HL # 001E 0B DEC BC # 001F 78 LD A,B # 0020 B1 OR C # 0021 20 F7 JR NZ,L1 # 0023 21 00 01 LD HL,$0100 ; (port, value) pairs, port $FF ends # 0026 7E LD A,(HL) ; L2 # 0027 FE FF CP $FF # 0029 28 FE JR Z,$ ; spin # 002B 4F LD C,A # 002C 23 INC HL # 002D 7E LD A,(HL) # 002E 23 INC HL # 002F ED 79 OUT (C),A # 0031 18 F3 JR L2 PROGRAM = bytes.fromhex( "F331F0C3" "3E80D3BF3E81D3BF" "3E00D3BF3E40D3BF" "2100400100407ED3BE230B78B120F7" "2100017EFEFF28FE4F237E23ED7918F3" ) R1_FIRST = 5 # offset of the immediate R1 value in PROGRAM def build_rom(vram: bytes, registers: list[int], r1_first: int = 0x80) -> bytes: rom = bytearray(0x8000) rom[: len(PROGRAM)] = PROGRAM rom[R1_FIRST] = r1_first stream = bytearray() for reg, value in enumerate(registers): stream += bytes((0xBF, value, 0xBF, 0x80 | reg)) stream += b"\xff\xff" rom[0x100 : 0x100 + len(stream)] = stream rom[0x4000:0x8000] = vram return bytes(rom) def _noise(seed: int, n: int) -> bytearray: out = bytearray(n) x = seed & 0xFFFFFFFF for i in range(n): x = (x * 1103515245 + 12345) & 0xFFFFFFFF out[i] = (x >> 16) & 0xFF return out def _sprites(vram: bytearray, sat: int, entries: list[tuple[int, int, int, int]]) -> None: for i, (y, x, name, tag) in enumerate(entries): vram[sat + 4 * i : sat + 4 * i + 4] = bytes((y, x, name, tag)) # Registers: R0, R1 (16K, display on, IE off), R2 names, R3 colours, R4 patterns, # R5 sprite attributes, R6 sprite patterns, R7 colours/backdrop. _SPRITES_A = [ (20, 30, 1, 0x0F), (24, 34, 2, 0x06), (60, 250, 3, 0x89), # overlap; one off the right (60, 0, 4, 0x82), (100, 100, 5, 0x00), (102, 104, 6, 0x0B), # EC; transparent over another (0xF0, 120, 7, 0x0C), (186, 200, 8, 0x0D), # bleeds in from the top; reaches line 192 (140, 10, 9, 0x03), (140, 40, 10, 0x04), (140, 70, 11, 0x05), (140, 100, 12, 0x07), (140, 130, 13, 0x08), # five on lines 141-148: 5S (0xD0, 0, 0, 0x0F), (50, 50, 14, 0x0E), # terminator, then one never shown ] def cases() -> dict[str, tuple[bytes, list[int], int]]: """name -> (VRAM image, R0-R7, R1 during the copy).""" out: dict[str, tuple[bytes, list[int], int]] = {} def case(name, r0, r1, r2, r3, r4, r5, r6, r7, sat, seed, sprites=_SPRITES_A, first=0x80): vram = _noise(seed, 0x4000) if sprites is not None: _sprites(vram, sat, sprites) out[name] = (bytes(vram), [r0, r1, r2, r3, r4, r5, r6, r7], first) # Graphics I: names $1800, colours $2000, patterns $0000, SAT $1B00, sprites $3800. case("g1", 0x00, 0xC0, 0x06, 0x80, 0x00, 0x36, 0x07, 0x14, 0x1B00, 1) case("g1-mag16", 0x00, 0xC3, 0x06, 0x80, 0x00, 0x36, 0x07, 0x14, 0x1B00, 2) # Graphics II, full tables: patterns $0000, colours $2000. case("g2", 0x02, 0xC2, 0x06, 0xFF, 0x03, 0x36, 0x07, 0x05, 0x1B00, 3) # Graphics II masks: R4 = 0 (one pattern third), R3 = $9F (2K colour table). case("g2-r4mask", 0x02, 0xC0, 0x06, 0x9F, 0x00, 0x36, 0x07, 0x05, 0x1B00, 4) # Graphics II, R3 = $83: a 256-byte colour table (C3: patterns masked too on 99x8). case("g2-c3", 0x02, 0xC1, 0x06, 0x83, 0x03, 0x36, 0x07, 0x09, 0x1B00, 5) # Multicolor: names $0800, patterns $0000. case("mc", 0x00, 0xCA, 0x02, 0x00, 0x00, 0x36, 0x07, 0x0D, 0x1B00, 6) # Text: names $0800, patterns $0000, colours white on dark blue. case("text", 0x00, 0xD0, 0x02, 0x00, 0x00, 0x36, 0x07, 0xF4, 0x1B00, 7) # Undocumented: Text + Graphics II, Multicolor + Graphics II, the table-less two. case("text-g2", 0x02, 0xD0, 0x02, 0xFF, 0x03, 0x36, 0x07, 0xE1, 0x1B00, 8) case("mc-g2", 0x02, 0xC8, 0x02, 0xFF, 0x03, 0x36, 0x07, 0x06, 0x1B00, 9) case("bogus", 0x00, 0xD8, 0x02, 0x00, 0x00, 0x36, 0x07, 0xA7, 0x1B00, 10) case("bogus-all", 0x02, 0xD8, 0x02, 0x00, 0x00, 0x36, 0x07, 0x3B, 0x1B00, 11) # Blanked: backdrop only. case("blank", 0x00, 0x80, 0x06, 0x80, 0x00, 0x36, 0x07, 0x1C, 0x1B00, 12) # 4K mode throughout (R1 bit 7 never set): C11's two effects against MAME's none. case("g1-4k", 0x00, 0x40, 0x06, 0x80, 0x00, 0x36, 0x07, 0x14, 0x1B00, 13, first=0x00) return out def record(names: list[str]) -> None: for name, (vram, regs, first) in cases().items(): if names and name not in names: continue rom_dir = TRACES / "synth-roms" rom_dir.mkdir(parents=True, exist_ok=True) rom = rom_dir / f"{name}.sg" rom.write_bytes(build_rom(vram, regs, first)) out = TRACES / f"synth-{name}" if out.exists(): print(f"{out} exists; move it to trash/ to record again") continue subprocess.run( [sys.executable, "-I", str(ROOT / "scripts/mame_vdp_log.py"), "sg1000", str(rom), "--seconds", "2", "--out", str(out)], check=True, ) # fmt: skip def sms_python_rgb(run: Path) -> list[list[int]] | None: """The same stream through sms-python's TMS9918A row (Sega timing), its last frame.""" if not SMS_PYTHON.exists(): return None if str(SMS_PYTHON) not in sys.path: sys.path.insert(0, str(SMS_PYTHON)) from sms_python.vdp import TMS9918A, VDP # noqa: PLC0415 events, end = mame_replay.parse_log(run) vdp = VDP(TMS9918A, "NTSC") now = 0 for e in events: cycles = (e.time - now) // 3 vdp.run(cycles) now += cycles * 3 if e.write: (vdp.write_control if e.mode else vdp.write_data)(e.value) else: vdp.read_status() if e.mode else vdp.read_data() vdp.run(max(0, (end - now) // 3)) return vdp.frame def compare(names: list[str]) -> dict[str, tuple[int, int, int]]: """Per case: (VRAM bytes differing from MAME, pixels differing from MAME's snapshot, pixels differing from sms-python's frame).""" results = {} for name in cases(): if names and name not in names: continue run = TRACES / f"synth-{name}" if not run.exists(): continue r = mame_replay.replay(run) ours = _final_frame(run) sms = sms_python_rgb(run) sms_differ = -1 if sms is not None: sms_differ = sum( 1 for y in range(192) for x in range(256) if _rgb(mame_replay.MAME_PALETTE[ours[y][x]]) != sms[y][x] ) results[name] = (r.vram_differ, r.frame_pixels_differ, sms_differ) return results def _final_frame(run: Path) -> list[bytes]: from tms9918_python import TMS9918 # noqa: PLC0415 events, end = mame_replay.parse_log(run) vdp = TMS9918(mame_replay.DRIVERS[mame_replay.driver_of(run)], windows=False) now = 0 for e in events: vdp.run(e.time - now) now = e.time (vdp.write if e.write else (lambda m, v: vdp.read(m)))(e.mode, e.value) vdp.run(end - now) return list(vdp._rows) def _rgb(t: tuple[int, int, int]) -> int: return t[0] << 16 | t[1] << 8 | t[2] def main() -> int: if len(sys.argv) < 2 or sys.argv[1] not in ("record", "compare"): print(__doc__) return 2 names = sys.argv[2:] if sys.argv[1] == "record": record(names) else: for name, (vram, mame, sms) in compare(names).items(): print( f"{name:10s} VRAM vs MAME {vram:5d} pixels vs MAME {mame:6d} vs sms-python {sms:6d}" ) return 0 if __name__ == "__main__": sys.exit(main())