#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Rung 2's judges on the board: Nintendo's Backup LIB sample and Pokémon Emerald's clock. Both are commercial programs run in place from ``$NO_INTRO_DIR`` (never copied, never committed: docs/handoff-brief.md); a player without them gets "missing" verdicts. jsmolka's ``save/`` ROMs are judged by scripts/judge_text.py with the rest of the library ROMs. **Backup LIB Sample v1.04** (No-Intro "Backup LIB Sample (Unknown) (v1.04) (Program)"; run only). Its menu offers SRAM, FLASH, EEPROM and DACS tests; each test writes a pattern over the whole chip and verifies it, printing "WRITE COMPLETE." or an error ("VERIFY ERROR." and the address). The FLASH test names the chip it identified ("DEVICE"), so each Flash chip the board can be fitted with (cartridge/backup.py FLASH_CHIPS) is a case. Six patterns, chosen with up and down: 0000, FFFF, INC, DEC, 00FF, 55AA (read from its own screen). The text is read from background 0's map, where the sample draws ASCII character n with tile n (as hw-test's console does: scripts/board_screens.py ``screen_text``), so the verdict does not depend on how the picture is drawn. Its EEPROM test reports "4K EEPROM" (512 bytes) whichever chip is fitted: it judges the 512-byte chip only. **Pokémon Emerald** (No-Intro "Pokemon - Emerald Version (USA, Europe)"; run only). Pressing Start at the title screen leads to the main menu (NEW GAME, OPTION) when the game accepts the clock, or to "The internal battery has run dry. The game can be played." when it does not (seen on the detectors: mGBA, with a clock, shows the menu; NanoBoyAdvance's driver, without one, the message; docs/validation.md). The verdict is where the white boxes are: the menu's at the top of the screen, the message's at the bottom. ``emerald-no-rtc`` removes the clock and must show the message: the judge's own proof that it can fail. python scripts/board_saves.py --bios "$NO_INTRO_DIR/.../(World).zip" --jobs 12 python scripts/board_saves.py lib-sram-p0 emerald-rtc --json out.json """ from __future__ import annotations import argparse import datetime import json import os import sys from concurrent.futures import ProcessPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] # GBA_PYTHON_SRC: a copy of src/ to run instead (scripts/seeded_faults.py). sys.path.insert(0, os.environ.get("GBA_PYTHON_SRC", str(ROOT / "src"))) sys.path.insert(0, str(Path(__file__).resolve().parent)) from gba_python.board import GBA from gba_python.cartridge.rom import GamePakROM from gba_python.ppu.timing import FRAME_CYCLES from gba_python.ppu.view import png_bytes RUNS = ROOT / "tests" / "referee_runs" GBA_DIR = "Nintendo - Game Boy Advance" LIB_ROM = "Backup LIB Sample (Unknown) (v1.04) (Program).zip" EMERALD_ROM = "Pokemon - Emerald Version (USA, Europe).zip" PATTERNS = ("0000", "FFFF", "INC", "DEC", "00FF", "55AA") LIB_MENU = {"sram": 0, "flash": 1, "eeprom": 2} FLASH_CHIPS = { # chip: (save type, the DEVICE name the sample prints) "panasonic": ("flash64:panasonic", "MN63F805MNP"), "sst": ("flash64:sst", "LE39FW512"), "macronix": ("flash64:macronix", "MX29L512"), # Atmel (3D1F) is left out: the sample's FLASH512_V131 library prints "DEVICE: UNKNOWN" # for it and stops ("WRITE ERROR."), so it cannot judge the Atmel page write (a blind # spot: docs/validation.md). "sanyo": ("flash128:sanyo", "LE26FV10N1TS_10"), "macronix128": ("flash128:macronix128", "MX29L010"), } KEY_A, KEY_START, KEY_DOWN = 0x001, 0x008, 0x080 # A fixed clock start keeps runs repeatable (the RTC counts emulated time from it). RTC_START = datetime.datetime(2026, 11, 21, 12, 0, 0) def cases() -> dict[str, dict]: table: dict[str, dict] = {} for p, name in enumerate(PATTERNS): table[f"lib-sram-p{p}"] = {"kind": "lib", "test": "sram", "save": "sram", "patterns": [p]} table[f"lib-eeprom-p{p}"] = { "kind": "lib", "test": "eeprom", "save": "eeprom", "patterns": [p], } for chip, (save, device) in FLASH_CHIPS.items(): for p in range(len(PATTERNS)): table[f"lib-flash-{chip}-p{p}"] = { "kind": "lib", "test": "flash", "device": device, "save": save, "patterns": [p], } table[f"lib-flash-{chip}-p0p5"] = { "kind": "lib", "test": "flash", "device": device, "save": save, "patterns": [0, 5], } # The clock is fitted by detection (SIIRTC_V), as in a player's run. table["emerald-rtc"] = {"kind": "emerald", "rtc": None, "expect": "menu"} table["emerald-no-rtc"] = {"kind": "emerald", "rtc": False, "expect": "battery"} return table def rom_path(name: str) -> Path | None: base = os.environ.get("NO_INTRO_DIR") if not base: return None path = Path(base) / GBA_DIR / name return path if path.exists() else None def bg0_text(board: GBA) -> list[str]: from board_screens import screen_text return screen_text(board) def press(script: dict[int, int], frame: int, mask: int) -> int: script[frame] = mask script[frame + 5] = 0 return frame + 12 def run_lib(case: dict, bios) -> dict: path = rom_path(LIB_ROM) if path is None: return {"status": "missing"} board = GBA(GamePakROM.from_path(path), bios=bios, save_type=case["save"]) frame = 0 def run_to(target: int) -> None: nonlocal frame while frame < target: board.run_until((frame + 1) * FRAME_CYCLES) frame += 1 def tap(mask: int) -> None: board.set_keys(mask) run_to(frame + 5) board.set_keys(0) run_to(frame + 7) run_to(600) # the menu is up by then with either BIOS for _ in range(LIB_MENU[case["test"]]): tap(KEY_DOWN) tap(KEY_A) run_to(frame + 60) current = 0 lines: list[str] = [] status = "no verdict" # Several patterns in one session: each later one writes over the last, so a Flash chip # must erase before it programs (the 0000-then-55AA cases). for pattern in case["patterns"]: for _ in range((pattern - current) % len(PATTERNS)): tap(KEY_DOWN) current = pattern run_to(frame + 30) tap(KEY_A) status, fresh = "no verdict", False limit = frame + 3000 while frame < limit: run_to(frame + 10) lines = bg0_text(board) text = "\n".join(lines) done = "WRITE COMPLETE." in text or "ERROR" in text if not done: fresh = True # the last verdict is gone: this one is the new run's continue if not fresh and pattern != case["patterns"][0]: continue status = "pass" if "WRITE COMPLETE." in text else "fail" break shown = { line.split(":")[0].strip(): line.split(":", 1)[1].strip() for line in lines if ":" in line } # The run must have tested the pattern it was asked for (read back from the screen). if shown.get("PATTERN") != PATTERNS[pattern]: status = f"wrong pattern {shown.get('PATTERN')}" # A Flash case must have identified the chip it was given (the sample prints it). if case.get("device") and shown.get("DEVICE") != case["device"]: status = f"wrong device {shown.get('DEVICE')}" if status != "pass": break return {"status": status, "screen": [line for line in lines if line.strip()], "board": board} def boxes(picture: list[list[int]]) -> str: """Where the white text boxes are: 'menu' (top), 'battery' (bottom), or 'other'.""" def white(rows: range) -> int: count = 0 for y in rows: for pixel in picture[y]: r, g, b = pixel & 0x1F, (pixel >> 5) & 0x1F, (pixel >> 10) & 0x1F if r >= 0x1C and g >= 0x1C and b >= 0x1C: count += 1 return count top, bottom = white(range(4, 24)), white(range(120, 150)) if top > 2000 and bottom < 500: return "menu" if bottom > 2000 and top < 500: return "battery" return f"other (top {top}, bottom {bottom})" def run_emerald(case: dict, bios) -> dict: path = rom_path(EMERALD_ROM) if path is None: return {"status": "missing"} board = GBA(GamePakROM.from_path(path), bios=bios, rtc=case["rtc"], rtc_start=RTC_START) script: dict[int, int] = {} press(script, 700, KEY_START) # skip the intro press(script, 1300, KEY_START) # at the title screen seen = "" for f in range(1800): if f in script: board.set_keys(script[f]) board.run_until((f + 1) * FRAME_CYCLES) seen = boxes(board.picture()) status = "pass" if seen == case["expect"] else "fail" return {"status": status, "screen": [seen], "board": board} def run_case(job: tuple) -> dict: name, bios = job case = cases()[name] result = run_lib(case, bios) if case["kind"] == "lib" else run_emerald(case, bios) board = result.pop("board", None) if board is not None: RUNS.mkdir(parents=True, exist_ok=True) png = RUNS / f"{name}-board.png" png.write_bytes(png_bytes(board.picture())) result["png"] = str(png.relative_to(ROOT)) result["case"] = name return result def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cases", nargs="*", help="case names or prefixes (default: all)") parser.add_argument("--bios", default="free") parser.add_argument("--jobs", type=int, default=4) parser.add_argument("--json", type=Path) args = parser.parse_args() os.environ.setdefault("PYPY_GC_NURSERY", "1M") table = cases() names = [n for n in table if not args.cases or any(n.startswith(c) for c in args.cases)] with ProcessPoolExecutor(max_workers=args.jobs) as pool: results = list(pool.map(run_case, [(n, args.bios) for n in names])) for result in results: print( f"{result['status']:12} {result['case']} {' | '.join(result.get('screen', [])[-2:])}" ) good = sum(r["status"] == "pass" for r in results) print(f"{good}/{len(results)} pass") if args.json: args.json.write_text(json.dumps(results, indent=1) + "\n", encoding="utf-8") return 0 if __name__ == "__main__": sys.exit(main())