"""Build the console probe pack: an SD-card folder for the Super EverDrive X5. python -I scripts/build_probe_pack.py [--out probe-pack] Needs the test ROMs from `python scripts/fetch_references.py` and ca65/ld65 (cc65 2.19, found on PATH or in CC65_DIR, default ~/.local/opt/cc65-2.19/bin). The pack is the console's turn as an oracle (handoff-brief.md, "Decided by the user" 6): our revision reporter first, then the self-checking CPU and SPC700 suites, then the probes the two detectors disagree on. Each ROM gets a row in CHECKLIST.md and results.csv saying what to look for and what MAME 0.285 and Mesen2 showed (validation.md, 2026-10-21), so a photo of the console's screen settles the row. The pack holds third-party ROMs and is never committed (.gitignore: probe-pack/). """ from __future__ import annotations import argparse import csv import os import shutil import subprocess import zipfile from dataclasses import dataclass from pathlib import Path ROOT = Path(__file__).resolve().parents[1] ROMS = ROOT / "tests" / "test_roms" PROBES = ROOT / "probes" CC65 = Path(os.environ.get("CC65_DIR", Path.home() / ".local" / "opt" / "cc65-2.19" / "bin")) # 5x7 glyphs, rows top to bottom, bit 4 = leftmost pixel. ASCII 32-95; the rest blank. GLYPHS = { "0": "0E 11 13 15 19 11 0E", "1": "04 0C 04 04 04 04 0E", "2": "0E 11 01 02 04 08 1F", "3": "1F 02 04 02 01 11 0E", "4": "02 06 0A 12 1F 02 02", "5": "1F 10 1E 01 01 11 0E", "6": "06 08 10 1E 11 11 0E", "7": "1F 01 02 04 08 08 08", "8": "0E 11 11 0E 11 11 0E", "9": "0E 11 11 0F 01 02 0C", "A": "0E 11 11 11 1F 11 11", "B": "1E 11 11 1E 11 11 1E", "C": "0E 11 10 10 10 11 0E", "D": "1C 12 11 11 11 12 1C", "E": "1F 10 10 1E 10 10 1F", "F": "1F 10 10 1E 10 10 10", "G": "0E 11 10 17 11 11 0F", "H": "11 11 11 1F 11 11 11", "I": "0E 04 04 04 04 04 0E", "J": "07 02 02 02 02 12 0C", "K": "11 12 14 18 14 12 11", "L": "10 10 10 10 10 10 1F", "M": "11 1B 15 15 11 11 11", "N": "11 11 19 15 13 11 11", "O": "0E 11 11 11 11 11 0E", "P": "1E 11 11 1E 10 10 10", "Q": "0E 11 11 11 15 12 0D", "R": "1E 11 11 1E 14 12 11", "S": "0F 10 10 0E 01 01 1E", "T": "1F 04 04 04 04 04 04", "U": "11 11 11 11 11 11 0E", "V": "11 11 11 11 11 0A 04", "W": "11 11 11 15 15 15 0A", "X": "11 11 0A 04 0A 11 11", "Y": "11 11 11 0A 04 04 04", "Z": "1F 01 02 04 08 10 1F", ":": "00 0C 0C 00 0C 0C 00", "=": "00 00 1F 00 1F 00 00", "(": "02 04 08 08 08 04 02", ")": "08 04 02 02 02 04 08", ".": "00 00 00 00 00 0C 0C", "-": "00 00 00 1F 00 00 00", "$": "04 0F 14 0E 05 1E 04", "/": "00 01 02 04 08 10 00", ",": "00 00 00 00 0C 04 08", } # MAME 0.285 vs Mesen2 on undisbeliever's v20210217 ROMs (validation.md). AGREE = "MAME and Mesen2 agree (neither shows a glitch)" DETECTORS = { **{f"inidisp_hammer_{s}": AGREE for s in ("0f", "0f_long", "0f00", "0f0f", "0f8f", "0f8f_fast", "8f0f")}, "inidisp_d7_glitch_test": AGREE, "hdma-2100-glitch": AGREE, "hdma-21ff-glitch": AGREE, "hdma-21ff-2100-0f-glitch": AGREE, "hdmaen_latch_test": "DISAGREE: Mesen2 red stripes, MAME white screen", "hdmaen_latch_test_2": "DISAGREE: Mesen2 red stripes, MAME white screen", "hdma-2100-glitch-2ch-0a": "DISAGREE: brightness per line", "hdma-2100-glitch-2ch-81": "DISAGREE: brightness per line", "hdma-21ff-2100-glitch": "DISAGREE: brightness per line", "inidisp_forgot_to_force_blank": "DISAGREE: whole picture", "inidisp_brightness_delay": "DISAGREE: single-line brightness timing", "inidisp_enable_display_mid_frame": "DISAGREE: single-line brightness timing", "gradient-test": "DISAGREE: gradient banding (CGWSEL)", } # Need peripherals Aubrey has not mentioned owning: a SNES mouse, a rumble controller. PERIPHERALS = {"mouse-cycle-sensitivity-test", "rumble-controller-latching"} SCPU_A = ("DISAGREE: both green; Mesen2 draws the HDMA-to-INIDISP scanline " "effect, MAME does not") @dataclass class Entry: folder: str name: str # file name on the card source: Path | None # None: built here look_for: str detectors: str = "" priority: str = "" # "MOST WANTED" for detector disagreements probe: str = "" # ours: built from probes//.s def tool(name: str) -> str: found = shutil.which(name) if found: return found local = CC65 / name if local.exists(): return str(local) raise SystemExit(f"{name} not found on PATH or in {CC65}") def font_inc() -> str: lines = ["; Generated by scripts/build_probe_pack.py: 2bpp, ASCII 32-95, colour 1.", "Font:"] for code in range(32, 96): rows = [0] + [int(r, 16) << 2 for r in GLYPHS.get(chr(code), "00 " * 6 + "00").split()] words = ", ".join(f"${r:04X}" for r in rows) # plane 0 low byte, plane 1 = 0 lines.append(f" .word {words} ; {chr(code)!r}") return "\n".join(lines) + "\n" def fix_checksum(rom: bytearray) -> None: """LoROM header at $7FC0: complement at $7FDC, checksum at $7FDE.""" rom[0x7FDC:0x7FE0] = b"\xff\xff\x00\x00" total = sum(rom) & 0xFFFF rom[0x7FDC:0x7FDE] = (total ^ 0xFFFF).to_bytes(2, "little") rom[0x7FDE:0x7FE0] = total.to_bytes(2, "little") def build_probe(name: str, dest: Path) -> None: """Assemble probes//.s with probes/common into a LoROM (32 KiB, or the banks probes//.cfg lays out).""" src = PROBES / name common = PROBES / "common" build = src / "build" build.mkdir(exist_ok=True) (build / "font.inc").write_text(font_inc()) obj = build / f"{name}.o" raw = build / f"{name}.bin" subprocess.run([tool("ca65"), "--cpu", "65816", "-I", str(build), "-I", str(common), "-o", str(obj), str(src / f"{name}.s")], check=True) own = src / f"{name}.cfg" # the suite is two banks; the single probes one cfg = own if own.exists() else common / "lorom32k.cfg" subprocess.run([tool("ld65"), "-C", str(cfg), "-o", str(raw), str(obj)], check=True) rom = bytearray(raw.read_bytes()) assert len(rom) in (0x8000, 0x10000), len(rom) fix_checksum(rom) dest.write_bytes(rom) def header_comment(path: Path) -> str: """The comment block at the top of a bass source file, up to the licence.""" text = [] for line in path.read_text(errors="replace").splitlines(): if not line.startswith("//") or "SPDX" in line: break text.append(line[2:].strip().strip("=").strip()) return " ".join(t for t in text if t) def undisbeliever_note(stem: str) -> str: """The ROM source's header, plus the headers of the files it includes from its own directory (the scpu-a-dma-bug ROMs keep "green squares = no DMA issues" in dma-test.inc).""" src = ROMS / "undisbeliever-src" / "src" # The v20210217 binaries use underscores where the current sources use hyphens. for path in [*src.rglob(f"{stem}.asm"), *src.rglob(f"{stem.replace('_', '-')}.asm")]: notes = [header_comment(path)] for line in path.read_text(errors="replace").splitlines(): if line.startswith("include \"") and "/" not in line: inc = path.parent / line.split('"')[1] if inc.exists(): notes.append(header_comment(inc)) return " ".join(n for n in notes if n).rstrip(".") + "." return "(no source header found)" def entries() -> list[Entry]: # The probe suite (docs/probe-suite.md) carries our five probes and every # CPU-measurable test; probes/ still build on their own. out = [Entry("00-OURS", "suite.sfc", None, "RUN THIS FIRST. It runs about 35 tests by itself (about 2 minutes) and " "saves every result. Hold B on controller 1 whenever the screen asks. If " "the screen does not change for 2 minutes, press RESET (start the ROM " "again if the menu comes up): it skips what froze and carries on. The " "last test (DMA CRASH) may need a few resets. When it says ALL DONE: " "power off, power on, and send the SD card's SAVE/suite.srm.", "Mesen2 and MAME 0.285 run it to ALL DONE (scripts/suite_run.py)", "MOST WANTED", probe="suite")] out.append(Entry("00-OURS", "photo-brightness.sfc", None, "U10, the brightness curve: 14 bands, each a white strip at brightness " "1-14 over a row of 32 grey blocks. Photograph the whole screen straight " "on, no flash, the room dim; nothing else to do.", "fullsnes and ares: c(N+1)/16; the other candidate: c*N/15", "MOST WANTED", probe="photo_bright")) out.append(Entry("00-OURS", "photo-hires-edge.sfc", None, "U9, the first hi-res half-dot: black with six thin white vertical " "lines. Photograph close up so the leftmost line and the next one " "(x = 64) are both sharp: is the left-edge line as bright as the others, " "dimmer, or missing?", "ares: transparent (unconfirmed); krom's higan pictures: as bright", "MOST WANTED", probe="photo_hires")) out.append(Entry("00-OURS", "05-poweron.sfc", None, "Memory at start and WAI with the IRQ held. Power the console OFF for at " "least 10 seconds, ON, and start this ROM from the menu straight away. It " "finishes by itself in under a second: photograph the screen. Power off " "and do it once more: the RUN COUNT should go up by one (the first count " "is whatever the save RAM held). Then send SAVE/05-poweron.srm.", "WAI row A (IRQ held): board and Mesen2 b9fa69d 0E1 00A 00A 00A / 00B 00B " "00B 00C (resumes at once); MAME 0.285 0E1 00A 0E1 0E1 ... (waits). Memory: " "board zeros, MAME WRAM $55, Mesen2 random", "MOST WANTED", probe="poweron")) out.append(Entry("00-OURS", "port-race.sfc", None, "The S-CPU/S-SMP port race (Kishin Douji Zenki, Kawasaki Superbike " "Challenge). Start it and wait: it counts to cell 286 by itself (about 30 " "seconds) and shows ALL DONE. If the cell number stops for 10 seconds, " "press RESET (start the ROM again if the menu comes up): it goes on with " "the next cell. Photograph the ALL DONE screen, power off, and send " "SAVE/port-race.srm.", "Zenki's FastROM loop against Zenki's S-SMP sequence: board (snes-python, " "predicted) 0 of 4096 reads zero, window D cycles + 21 clocks; Mesen2 " "b9fa69d 26 of 4096, window D cycles - 10.5 clocks (docs/port-race.md)", "MOST WANTED", probe="port_race")) gilyon = ROMS / "gilyon" # What ran on 2026-10-21 (validation.md; 65816-python docs/validation.md). for rel, what, det in ( ("cputest/cputest-basic.sfc", "65816 self-check", "MAME 0.285: Success (1,107)"), ("cputest/cputest-full.sfc", "65816 self-check", "MAME 0.285: Success; Mesen2: Success"), ("spctest/spctest.sfc", "SPC700 self-check", "MAME 0.285: Success; Mesen2: Success"), ): out.append(Entry("01-CPU-GILYON", Path(rel).name, gilyon / rel, f"{what}. Wait until it stops; photograph 'Success' or the " "failing test number and values.", det)) for rom in sorted((ROMS / "krom" / "CPUTest").rglob("*.sfc")): cpu = rom.parent.parent.name == "CPU" out.append(Entry("02-CPU-KROM", f"{rom.parent.parent.name}-{rom.name}", rom, "Each row prints PASS or FAIL. Photograph the full screen.", "MAME 0.285: all PASS" if cpu else "MAME 0.285: one header row fewer than krom's picture" if rom.stem in ("SPC700INC", "SPC700DEC") else "MAME 0.285: identical to krom's picture")) for rom in sorted((ROMS / "undisbeliever" / "snes-test-roms").glob("*.sfc")): det = DETECTORS.get(rom.stem, SCPU_A if rom.stem.startswith("scpu-a-dma-bug") else "") out.append(Entry("03-GLITCH-UNDISBELIEVER", rom.name, rom, undisbeliever_note(rom.stem) + " Reset 3 times; photograph each " "look that differs.", det, "MOST WANTED" if det.startswith("DISAGREE") else "")) out.append(Entry("03-GLITCH-UNDISBELIEVER", "gradient-test.sfc", ROMS / "gradient-test.sfc", "A colour gradient. Photograph it straight on, no flash.", DETECTORS["gradient-test"], "MOST WANTED")) # undisbeliever's tests newer than the v20210217 binaries, built from source # (docs/probe-pack.md, "Building undisbeliever's newer tests"). Detector # results from scripts/detectors_compare.py, kept in tests/detectors/. built = ROMS / "undisbeliever-src" / "bin" if built.exists(): old = {p.stem.replace("_", "-") for p in (ROMS / "undisbeliever" / "snes-test-roms").glob("*.sfc")} compared = {} for line in (ROOT / "tests" / "detectors" / "undisbeliever-new.tsv").read_text().splitlines(): if line and not line.startswith("#"): name, pixels = line.split("\t") compared[name] = pixels roms = sorted([*built.glob("hardware-tests/**/*.sfc"), *built.glob("hardware-glitch-tests/**/*.sfc")]) for rom in roms: if rom.stem.replace("_", "-") in old or rom.stem in PERIPHERALS: continue pixels = compared.get(rom.stem, "not compared") det = (AGREE if pixels == "0" else f"DISAGREE: {pixels} pixels differ" if pixels.isdigit() else pixels) out.append(Entry("05-NEW-UNDISBELIEVER", rom.name, rom, undisbeliever_note(rom.stem) + " Follow any on-screen button " "prompts; reset 3 times; photograph each look that differs.", det, "MOST WANTED" if det.startswith("DISAGREE") else "")) else: print("05-NEW-UNDISBELIEVER skipped: undisbeliever-src/bin not built") blargg = ROMS / "blargg" with zipfile.ZipFile(blargg / "exec_io_tests.zip") as z: for member in sorted(n for n in z.namelist() if n.endswith(".smc")): out.append(Entry("04-SMP-BLARGG", Path(member).name, None, "blargg self-check: photograph the result text.", "not run on detectors yet")) for rom in sorted(blargg.glob("*.smc")): out.append(Entry("04-SMP-BLARGG", rom.name.replace(" ", "_"), rom, "blargg probe (S-SMP timers, IPL disable, controller strobe): it " "prints numbers; photograph the screen after it settles.", "not run on detectors yet")) return out def main() -> None: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--out", type=Path, default=ROOT / "probe-pack") args = parser.parse_args() if not (ROMS / "gilyon").exists(): raise SystemExit("test ROMs missing: run python scripts/fetch_references.py first") args.out.mkdir(exist_ok=True) rows = sorted(entries(), key=lambda e: e.folder) # stable: keeps order in a folder exec_io = ROMS / "blargg" / "exec_io_tests.zip" for e in rows: folder = args.out / e.folder folder.mkdir(exist_ok=True) dest = folder / e.name if e.probe: build_probe(e.probe, dest) elif e.source is None: with zipfile.ZipFile(exec_io) as z: dest.write_bytes(z.read(f"exec_io_tests/{e.name}")) else: shutil.copyfile(e.source, dest) with (args.out / "results.csv").open("w", newline="") as f: w = csv.writer(f) w.writerow(["folder", "rom", "priority", "look_for", "detectors", "console_result", "photo"]) for e in rows: w.writerow([e.folder, e.name, e.priority, e.look_for, e.detectors, "", ""]) md = ["# SNES probe pack: console checklist", "", "Copy every folder to the X5's SD card. Run the ROMs in order, top to bottom.", "Photograph each result screen with the phone straight on, and name or note the", "photo with the ROM's name. Write anything odd in results.csv's console_result.", "**MOST WANTED** rows are where MAME and Mesen2 disagree: only the console can say", "which is right.", ""] folder = None for e in rows: if e.folder != folder: folder = e.folder md += ["", f"## {folder}", "", "| Done | ROM | Look for | Detectors |", "| --- | --- | --- | --- |"] tag = f"**{e.priority}** " if e.priority else "" md.append(f"| [ ] | `{e.name}` | {tag}{e.look_for} | {e.detectors} |") md += ["", "When done: copy the SD card's save files (.srm) and the photos back, and", "fill in console_result in results.csv (or just send the photos).", ""] (args.out / "CHECKLIST.md").write_text("\n".join(md)) by_folder: dict[str, int] = {} for e in rows: by_folder[e.folder] = by_folder.get(e.folder, 0) + 1 for name, n in by_folder.items(): print(f"{name:26} {n:3} ROMs") print(f"{'total':26} {len(rows):3} ROMs -> {args.out}") if __name__ == "__main__": main()