# SPDX-License-Identifier: MIT """Census of MAME's Sega Model 1/2/3 romsets we hold, read in place. python -I scripts/census.py model2 # one line per set, then totals python -I scripts/census.py model1 model2 --firmware python -I scripts/census.py model3 --markdown The set list, each set's chips, devices and ROM CRCs come from the installed MAME binary (`mame -listsource`, `mame -listxml`), which is run, never read. Each zip under $MAME_ROMPATH (MAME's non-merged sets) is opened and its members matched by CRC-32; nothing is extracted, copied or written except the report on stdout. --firmware also hashes, by SHA-1, the Sega board ROMs every game of a board needs (TGP tables, the Model 1 TGP internal ROMs, I/O and billboard boards): they are identified, never shipped. Board revisions come from the chips (MAME's `-listxml`); the Model 3 step 2.0/2.1 split and the protection-key flag come from MAME's driver source when its BSD-3-Clause copy has been fetched into reference/mame-bsd/ (scripts/fetch_references.py). Keys are only counted here, never printed. """ from __future__ import annotations import argparse import collections import hashlib import os import re import subprocess import sys import xml.etree.ElementTree as ET import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] BSD = ROOT / "reference" / "mame-bsd" / "mame" / "sega" # Board ROM regions that belong to the board, not the game (MAME 0.285 region names). BOARD_REGIONS = {"copro_tgp_tables", "other_data", "video_unk", "315_5571", "315_5572"} BOARD_DEVICES = {"model1io", "model1io2", "segabill"} STEP_OF_CONFIG = { "model3_10": "1.0", "getbass": "1.0", "model3_15": "1.5", "scud": "1.5", "lostwsga": "1.5", "model3_20": "2.0", "model3_20_5881": "2.0", "srally2": "2.0", "model3_21": "2.1", "model3_21_5881": "2.1", "swtrilgyp": "2.1", "daytona2": "2.1", "spikeout": "2.1", "swtrilgy": "2.1", } # fmt: skip def mame(*args: str) -> str: return subprocess.run(["nice", "mame", *args], capture_output=True, text=True, check=True).stdout def names_for(driver: str) -> list[str]: source = f"sega/{driver}.cpp" return [line.split()[0] for line in mame("-listsource").splitlines() if line.split()[-1:] == [source]] # fmt: skip def game_configs(driver: str) -> dict[str, str]: """Set name -> MAME machine config, from the GAME() lines of the BSD driver copy.""" path = BSD / f"{driver}.cpp" if not path.exists(): return {} configs = {} for match in re.finditer(r"^\s*GAMEL?\(\s*\d+,\s*(\w+),\s*\w+,\s*(\w+),", path.read_text(), re.M): configs[match.group(1)] = match.group(2) return configs def keyed_sets(driver: str) -> set[str]: """Sets whose ROM definition carries a 315-5881 key parameter (values never printed).""" path = BSD / f"{driver}.cpp" if not path.exists(): return set() keyed = set() for block in re.finditer(r"ROM_START\(\s*(\w+)\s*\)(.*?)ROM_END", path.read_text(), re.S): if ":315_5881:key" in block.group(2): keyed.add(block.group(1)) return keyed def board_of(driver: str, chips: list[tuple[str, str, int]], refs: set[str], config: str) -> str: if driver == "model1": return "Model 1" + (" + i386 (Virtuality)" if "i386sx" in refs else "") if driver == "model3": if config in STEP_OF_CONFIG: return "Step " + STEP_OF_CONFIG[config] clock = next(c for t, n, c in chips if t == "maincpu") return {66_000_000: "Step 1.0", 100_000_000: "Step 1.5"}.get(clock, "Step 2.x") sound = "SCSP" if "scsp" in refs else "Model 1 sound" if "segam1audio" in refs and "scsp" in refs: sound = "SCSP + Model 1 sound" if "adsp21062" in refs: return f"2B-CRX ({sound})" if "mb86235" in refs: return f"2C-CRX ({sound})" return ("2A-CRX" if "scsp" in refs else "2 (original)") + f" ({sound})" def machines(names: list[str]) -> dict[str, ET.Element]: root = ET.fromstring(mame("-listxml", *names)) return {m.get("name"): m for m in root.iter("machine")} def zip_crcs(path: Path) -> dict[str, int] | None: if not path.exists(): return None with zipfile.ZipFile(path) as archive: return {f"{info.CRC:08x}": info.file_size for info in archive.infolist()} def census(driver: str, rompath: Path, markdown: bool) -> collections.Counter: names = names_for(driver) xml = machines(names) configs, keyed = game_configs(driver), keyed_sets(driver) totals: collections.Counter = collections.Counter() if markdown: print("| Set | Parent | Year | Board | Protection | Sub-boards | ROMs (have/need) | MAME status |") print("| --- | --- | --- | --- | --- | --- | --- | --- |") for name in sorted(n for n in names if xml[n].get("isdevice") != "yes"): m = xml[name] refs = {d.get("name") for d in m.iter("device_ref")} chips = [(c.get("tag"), c.get("name"), int(c.get("clock") or 0)) for c in m.iter("chip") if c.get("type") == "cpu"] # fmt: skip board = board_of(driver, chips, refs, configs.get(name, "")) prot = [] if "sega315_5881" in refs: prot.append("315-5881" + (" (key in MAME)" if name in keyed else "")) if "sega315_5838" in refs: prot.append("315-5838") regions = {r.get("region") for r in m.iter("rom")} if "pic" in regions or "prot_data" in regions: prot.append("PIC/prot ROM") subs = [s for s, ref in (("drive (315-5296)", "315_5296"), ("DSB", "dsbz80_device"), ("DSB2", "dsb2_device"), ("billboard", "segabill"), ("comm", "m3comm")) if ref in refs] # fmt: skip if any(r in regions for r in ("drivecpu", "drivebd", "drive")): subs.append("drive ROM") roms = [r for r in m.iter("rom") if r.get("status") != "nodump" and r.get("crc")] have = zip_crcs(rompath / f"{name}.zip") found = sum(1 for r in roms if have and r.get("crc") in have) size = sum(int(r.get("size")) for r in roms) status = m.find("driver").get("status") if m.find("driver") is not None else "?" totals["sets"] += 1 totals["complete"] += found == len(roms) totals["bytes"] += size totals[board] += 1 totals["protected"] += bool(prot) totals[f"status {status}"] += 1 cells = [name, m.get("cloneof") or "-", m.findtext("year"), board, ", ".join(prot) or "-", ", ".join(subs) or "-", f"{found}/{len(roms)}", status] # fmt: skip print(("| " + " | ".join(cells) + " |") if markdown else " ".join(cells)) return totals def firmware(drivers: list[str], rompath: Path) -> None: """SHA-1 of the board ROMs each board needs, read from the first set that has them.""" games = [n for d in drivers for n in names_for(d)] used = {d.get("name") for m in machines(games).values() for d in m.iter("device_ref")} xml = machines(games + sorted(BOARD_DEVICES & used)) seen: dict[str, tuple[str, str, str]] = {} for name, m in sorted(xml.items()): for r in m.iter("rom"): if r.get("region") in BOARD_REGIONS or name in BOARD_DEVICES: seen.setdefault(r.get("sha1") or "-", (r.get("name"), r.get("region") or "", name)) for sha1, (rom, region, owner) in sorted(seen.items(), key=lambda kv: kv[1]): path = rompath / f"{owner}.zip" state = "missing" if path.exists(): with zipfile.ZipFile(path) as archive: if rom in archive.namelist(): digest = hashlib.sha1(archive.read(rom)).hexdigest() state = "ok" if digest == sha1 else f"differs ({digest})" print(f"{sha1} {rom:22} {region:18} {owner:10} {state}") def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("drivers", nargs="+", choices=("model1", "model2", "model3")) parser.add_argument("--markdown", action="store_true") parser.add_argument("--firmware", action="store_true", help="hash the shared board ROMs") parser.add_argument("--rompath", default=os.environ.get("MAME_ROMPATH")) args = parser.parse_args() if not args.rompath: print("set MAME_ROMPATH to MAME's non-merged sets", file=sys.stderr) return 2 rompath = Path(args.rompath) for driver in args.drivers: totals = census(driver, rompath, args.markdown) print(f"\n{driver}: " + ", ".join(f"{k}: {v}" for k, v in sorted(totals.items())) + "\n") if args.firmware: firmware(args.drivers, rompath) return 0 if __name__ == "__main__": sys.exit(main())