#!/usr/bin/env python3 """Census of the Neo Geo cartridge library from listings only (no emulator runs). Sources, all read in place: - ``reference/mame/listxml-0285.xml``: ``mame -listxml`` of the installed MAME 0.285 (made by ``--listxml``; 314 MB, git-ignored). - ``reference/src/mame/src/mame/neogeo/neogeo.cpp``: the ``GAME(...)`` lines; the fourth argument is the machine configuration, which names the cartridge type. - ``reference/src/mame/hash/neogeo.xml``: the software list, whose ``slot`` feature names the same cartridge type and whose comments name PROG/CHA boards. - the local zip directories (central directories only) and the BIOS zips (members are hashed with SHA-1). python -I scripts/census.py --listxml # write the MAME XML (once, ~10 s) python -I scripts/census.py > tests/census/census-YYYY-MM-DD.txt """ from __future__ import annotations import argparse import collections import hashlib import os import re import subprocess import sys import zipfile from pathlib import Path from xml.etree import ElementTree def local(variable: str, *parts: str) -> Path: """A local ROM folder from an environment variable (no machine path lives here). Unset, it is a path that does not exist, so the folder counts as absent: CURATED_ROMS (a frontend library with neogeo/, mame/, fbneo/ and neogeocd/), FRONTEND_BIOS (a frontend's BIOS folder), FBNEO_DAT (FinalBurn Neo's ClrMame Pro XML dat, arcade only). """ value = os.environ.get(variable) if not value: print(f"{variable} is unset: its folder counts as absent", file=sys.stderr) return Path(value or f"${variable}", *parts) ROOT = Path(__file__).resolve().parents[1] LISTXML = ROOT / "reference" / "mame" / "listxml-0285.xml" DRIVER = ROOT / "reference" / "src" / "mame" / "src" / "mame" / "neogeo" / "neogeo.cpp" SOFTLIST = ROOT / "reference" / "src" / "mame" / "hash" / "neogeo.xml" LIBRARY = local("CURATED_ROMS", "neogeo") MAME_SETS = local("CURATED_ROMS", "mame") FBNEO_SETS = local("CURATED_ROMS", "fbneo") FBNEO_DAT = local("FBNEO_DAT") CD_LIBRARY = local("CURATED_ROMS", "neogeocd") BIOS_ZIPS = [ LIBRARY / "neogeo.zip", MAME_SETS / "neogeo.zip", FBNEO_SETS / "neogeo.zip", local("FRONTEND_BIOS", "neogeo.zip"), MAME_SETS / "aes.zip", LIBRARY / "aes.zip", FBNEO_SETS / "aes.zip", LIBRARY / "neocdz.zip", FBNEO_SETS / "neocdz.zip", MAME_SETS / "neocdz.zip", MAME_SETS / "neocd.zip", ] # Machine configuration (GAME's fourth argument) -> protection / banking family. # Checked against neogeo.cpp's configs and bus/neogeo/*.cpp on 2026-11-12 (docs/cartridges.md). SMA42 = "NEO-SMA (live RNG + bank) + static P decrypt + NEO-CMC42 C/S" PCM2_99 = "NEO-CMC50 C/S/M1 + NEO-PCM2 (SNK 1999 V scramble)" PCM2_02 = "NEO-CMC50 C/S/M1 + NEO-PCM2 (Playmore 2002 V decrypt) + KOF2002-type P scramble" FAMILY = { "neobase": "none (plain ROM, standard P2 banking where a P2 exists)", "neogeo_mj": "none (mahjong panel, Japan system ROM)", "fatfur2": "PRO-CT0 / ALPHA-8921 security chip (live, whole port zone)", "kof98": "KOF98 static P descramble + live header overlay", "mslugx": "Metal Slug X challenge chip (live, $2FFFE0-$2FFFEF)", "kof99": SMA42, "garou": SMA42, "garouh": SMA42, "mslug3": SMA42, "mslug3a": SMA42, "kof2000": "NEO-SMA (live RNG + bank) + static P decrypt + NEO-CMC50 C/S/M1", "zupapa": "NEO-CMC42 C/S", "mslug3h": "NEO-CMC42 C/S", "ganryu": "NEO-CMC42 C/S", "s1945p": "NEO-CMC42 C/S", "preisle2": "NEO-CMC42 C/S", "bangbead": "NEO-CMC42 C/S", "nitd": "NEO-CMC42 C/S", "sengoku3": "NEO-CMC42 C/S", "kof99k": "NEO-CMC42 C/S", "kof2001": "NEO-CMC50 C/S/M1", "kof2000n": "NEO-CMC50 C/S/M1", "jockeygp": "NEO-CMC50 C/S/M1 + 8 KiB battery RAM at $200000", "vliner": "none (V-Liner: battery RAM at $200000, extra I/O, no controller ports)", "mslug4": PCM2_99, "ms4plus": PCM2_99 + " (external S1)", "rotd": PCM2_99, "pnyaa": PCM2_99, "kof2002": PCM2_02, "matrim": PCM2_02, "samsho5": PCM2_02, "samsh5sp": PCM2_02, "kf2k2pls": PCM2_02 + " (external S1)", "mslug5": "NEO-PVC (live RAM, colour pack, bank) + static P decrypt + CMC50 + PCM2 2002", "svc": "NEO-PVC (live RAM, colour pack, bank) + static P decrypt + CMC50 + PCM2 2002", "kof2003": "NEO-PVC (live RAM, colour pack, bank) + static P decrypt + CMC50 + PCM2 2002", "kof2003h": "NEO-PVC (live RAM, colour pack, bank) + static P decrypt + CMC50 + PCM2 2002", "sbp": "Super Bubble Pop nibble-swap read window (MAME: unemulated protection)", "irrmaze": "none (trackball, own system ROM 236-bios.sp1)", "kizuna4p": "none (NEO-FTC1B 4-player adapter)", "popbounc": "none (dial)", } def write_listxml() -> int: LISTXML.parent.mkdir(parents=True, exist_ok=True) with LISTXML.open("wb") as handle: return subprocess.run(["mame", "-listxml"], stdout=handle, check=False).returncode def machines() -> dict[str, dict]: """Every machine whose source file is one of the Neo Geo drivers.""" found: dict[str, dict] = {} for _event, node in ElementTree.iterparse(LISTXML, events=("end",)): if node.tag != "machine": continue source = node.get("sourcefile", "") if source.startswith("neogeo/"): roms = [ { "name": rom.get("name"), "size": int(rom.get("size", "0")), "crc": rom.get("crc"), "sha1": rom.get("sha1"), "region": rom.get("region", ""), "bios": rom.get("bios"), "merge": rom.get("merge"), } for rom in node.findall("rom") ] driver = node.find("driver") found[node.get("name")] = { "source": source, "cloneof": node.get("cloneof"), "romof": node.get("romof"), "isbios": node.get("isbios") == "yes", "description": node.findtext("description", ""), "year": node.findtext("year", ""), "manufacturer": node.findtext("manufacturer", ""), "status": driver.get("status") if driver is not None else "", "roms": roms, } node.clear() return found def game_configs() -> dict[str, str]: configs = {} # The year may carry a "?" (mvstemp: "1995?"). pattern = re.compile(r"^GAME\(\s*\w+\??,\s*(\w+),\s*(\w+),\s*(\w+),") for line in DRIVER.read_text(encoding="utf-8", errors="replace").splitlines(): match = pattern.match(line) if match: configs[match.group(1)] = match.group(3) return configs def softlist() -> tuple[dict[str, str], dict[str, str]]: """Software name -> slot type, and -> the board comment that precedes it.""" text = SOFTLIST.read_text(encoding="utf-8") slots: dict[str, str] = {} boards: dict[str, str] = {} comment = "" position = 0 token = re.compile(r"|", re.S) for match in token.finditer(text, position): if match.group(1) is not None: if "ID-" in match.group(1): comment = match.group(1) continue name, body = match.group(2), match.group(3) slot = re.search(r'name="slot" value="([^"]+)"', body) slots[name] = slot.group(1) if slot else "rom" boards[name] = comment return slots, boards def fbneo_games() -> dict[str, dict]: """FinalBurn Neo's Neo Geo sets (romof neogeo) from its ClrMame dat: name -> comment, description.""" games: dict[str, dict] = {} if not FBNEO_DAT.exists(): return games for _event, node in ElementTree.iterparse(FBNEO_DAT, events=("end",)): if node.tag != "game": continue if node.get("romof") == "neogeo" or node.get("sourcefile", "").startswith("neogeo/"): games[node.get("name")] = { "comment": node.findtext("comment", ""), "description": node.findtext("description", ""), "cloneof": node.get("cloneof"), "size": sum(int(r.get("size", "0")) for r in node.findall("rom") if not r.get("merge")), } node.clear() return games def kind(name: str, machine: dict) -> str: description = machine["description"].lower() maker = machine["manufacturer"].lower() if "bootleg" in description or "bootleg" in maker: return "bootleg" if "prototype" in description or "location test" in description: return "prototype" if "hack" in description or "hack" in maker: return "hack" return "official" if machine["year"] and machine["year"] <= "2004" else "aftermarket" def cart_size(machine: dict) -> int: return sum(r["size"] for r in machine["roms"] if r["region"].startswith("cslot1")) def region_sizes(machine: dict) -> dict[str, int]: sizes: dict[str, int] = collections.Counter() for rom in machine["roms"]: if rom["region"].startswith("cslot1:"): sizes[rom["region"].split(":", 1)[1]] += rom["size"] return sizes def sha1_members(path: Path) -> list[tuple[str, int, str, str]]: rows = [] with zipfile.ZipFile(path) as archive: for info in archive.infolist(): data = archive.read(info) rows.append((info.filename, info.file_size, f"{info.CRC:08x}", hashlib.sha1(data).hexdigest())) return rows def zip_crcs(path: Path) -> set[str]: try: with zipfile.ZipFile(path) as archive: return {f"{info.CRC:08x}" for info in archive.infolist()} except (zipfile.BadZipFile, OSError): return set() def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--listxml", action="store_true", help="write the MAME XML and exit") args = parser.parse_args() if args.listxml: return write_listxml() every = machines() configs = game_configs() slots, boards = softlist() carts = { n: m for n, m in every.items() if m["source"] == "neogeo/neogeo.cpp" and not m["isbios"] and n != "aes" and not n.startswith("ng_mv") } boards_only = sorted(n for n, m in every.items() if m["source"] == "neogeo/neogeo.cpp" and n not in carts) parents = {n: m for n, m in carts.items() if m["cloneof"] in (None, "neogeo")} clones = {n: m for n, m in carts.items() if n not in parents} print("# Neo Geo census (MAME 0.285 listings; no emulator was run)") print() print("## Drivers") by_source = collections.Counter(m["source"] for m in every.values()) for source, count in sorted(by_source.items()): print(f"{count:4d} {source}") print() print(f"neogeo.cpp machines: {len(carts) + len(boards_only)} = {len(boards_only)} system machines ({' '.join(boards_only)}) + {len(carts)} cartridge sets") print(f"parents: {len(parents)} clones: {len(clones)}") print() print("## Kind (parents / clones)") kinds_parent = collections.Counter(kind(n, m) for n, m in parents.items()) kinds_clone = collections.Counter(kind(n, m) for n, m in clones.items()) for name in sorted(set(kinds_parent) | set(kinds_clone)): print(f"{name:12s} {kinds_parent[name]:4d} {kinds_clone[name]:4d}") print("bootleg parents: " + " ".join(sorted(n for n, m in parents.items() if kind(n, m) == "bootleg"))) print("prototype parents: " + " ".join(sorted(n for n, m in parents.items() if kind(n, m) == "prototype"))) print() print("## Driver status (all cartridge sets)") for status, count in collections.Counter(m["status"] for m in carts.values()).most_common(): print(f"{count:4d} {status}") print() print("## Parents by protection / banking family (machine configuration in neogeo.cpp)") family_sets: dict[str, list[str]] = collections.defaultdict(list) for name in sorted(parents): config = configs.get(name, "?") label = FAMILY.get(config) or f"bootleg/other board ({config})" family_sets[label].append(name) for label, names in sorted(family_sets.items(), key=lambda item: -len(item[1])): shown = " ".join(names) if len(names) <= 40 else f"{' '.join(names[:12])} ..." print(f"{len(names):4d} {label}: {shown}") print() print("## All sets by machine configuration (parents + clones)") for config, count in collections.Counter(configs.get(n, "?") for n in carts).most_common(): print(f"{count:4d} {config}") print() print("## Cartridge ROM sizes (parents; bytes as listed, encrypted sets include their extra regions)") sizes = sorted(((cart_size(m), n) for n, m in parents.items())) total = sum(s for s, _ in sizes) print(f"total {total:,} bytes ({total / 2**30:.2f} GiB) over {len(sizes)} parents") print(f"smallest: {sizes[0][1]} {sizes[0][0]:,} median: {sizes[len(sizes) // 2][1]} {sizes[len(sizes) // 2][0]:,} largest: {sizes[-1][1]} {sizes[-1][0]:,}") all_total = sum(cart_size(m) for m in carts.values()) print(f"all {len(carts)} sets, non-merged: {all_total:,} bytes ({all_total / 2**30:.2f} GiB)") largest: dict[str, tuple[int, str]] = {} for name, machine in parents.items(): for region, size in region_sizes(machine).items(): if size > largest.get(region, (0, ""))[0]: largest[region] = (size, name) for region, (size, name) in sorted(largest.items()): print(f"largest {region:16s} {size:>11,} {name}") megs = collections.Counter() for size, _name in sizes: megs[min(1 << (size - 1).bit_length(), 1 << 30) >> 20] += 1 print("parents by total size (rounded up to a power of two, MiB): " + ", ".join(f"<={k}: {v}" for k, v in sorted(megs.items()))) print() print("## Software list hash/neogeo.xml") print(f"{len(slots)} software entries; slot types:") grouped = collections.Counter(re.sub(r"_.*", "", s) if s != "rom" else "rom" for s in slots.values()) for slot, count in grouped.most_common(): print(f"{count:4d} {slot}") progs = collections.Counter() chas = collections.Counter() for comment in set(boards.values()): for board in set(re.findall(r"NEO-(?:MVS|AEG) (PROG[\w-]*|CHA[\w-]*)", comment)): (progs if board.startswith("PROG") else chas)[board] += 1 print("PROG boards named in the list's comments (titles naming each): " + ", ".join(f"{b} {c}" for b, c in progs.most_common())) print("CHA boards named in the list's comments: " + ", ".join(f"{b} {c}" for b, c in chas.most_common())) missing = sorted(set(carts) - set(slots)) extra = sorted(set(slots) - set(carts)) print(f"machines without a software entry: {len(missing)} {' '.join(missing[:20])}") print(f"software entries without a machine: {len(extra)} {' '.join(extra[:20])}") print() print("## BIOS: what MAME 0.285 lists") for name in ("neogeo", "aes", "neocdz", "neocdzj", "neocd", "ms5pcb", "svcpcb", "kf2k3pcb", "irrmaze"): machine = every.get(name) if not machine: continue rows = [r for r in machine["roms"] if not r["region"].startswith("cslot1")] if name not in ("neogeo", "aes") and machine["romof"] == "neogeo": rows = [r for r in rows if not r["merge"]] print(f"### {name}: {machine['description']}") for rom in rows: print(f" {rom['name']:22s} {rom['size']:>8d} {rom['crc']} {rom['sha1']} {rom['region']} {rom['bios'] or ''}") print() print("## BIOS: what the local zips hold (SHA-1 of each member, computed here)") known = {r["sha1"]: r["name"] for m in every.values() for r in m["roms"] if r["sha1"]} for path in BIOS_ZIPS: if not path.exists(): print(f"### {path}: MISSING") continue rows = sha1_members(path) print(f"### {path} ({len(rows)} members, zip sha1 {hashlib.sha1(path.read_bytes()).hexdigest()})") for filename, size, crc, digest in rows: print(f" {filename:22s} {size:>8d} {crc} {digest} {'= MAME ' + known[digest] if digest in known else 'not in MAME 0.285 neogeo drivers'}") wanted = {r["sha1"]: r["name"] for n in ("neogeo", "aes") for r in every[n]["roms"]} held = set() for path in BIOS_ZIPS: if path.exists(): held |= {digest for _f, _s, _c, digest in sha1_members(path)} lacking = sorted(name for digest, name in wanted.items() if digest not in held) print(f"neogeo + aes system ROMs listed by MAME: {len(wanted)}; held locally: {len(wanted) - len(lacking)}; lacking: {' '.join(lacking) or 'none'}") print() print("## Local libraries (zip central directories only)") for label, directory in (("roms-retrobat/neogeo", LIBRARY), ("roms-retrobat/mame", MAME_SETS), ("roms-retrobat/fbneo", FBNEO_SETS)): zips = {p.stem: p for p in directory.glob("*.zip")} present = sorted(set(zips) & set(carts)) present_parents = sorted(set(zips) & set(parents)) complete = 0 for name in present: need = {r["crc"] for r in carts[name]["roms"] if r["region"].startswith("cslot1") and r["crc"]} have = zip_crcs(zips[name]) parent = carts[name]["cloneof"] if parent and parent in zips: have |= zip_crcs(zips[parent]) complete += need <= have unknown = sorted(set(zips) - set(every)) size = sum(zips[n].stat().st_size for n in present) print(f"### {label}: {len(zips)} zips; {len(present)} are MAME 0.285 Neo Geo cartridge sets ({len(present_parents)} parents of {len(parents)}), {size / 2**30:.2f} GiB zipped") print(f" CRC-complete against MAME 0.285 (own zip + parent zip): {complete} of {len(present)}") if directory == LIBRARY: fbneo = fbneo_games() print(f" FinalBurn Neo dat ({FBNEO_DAT.name}): {len(fbneo)} Neo Geo sets") in_fbneo = [n for n in unknown if n in fbneo] comments = collections.Counter(fbneo[n]["comment"] or "(no comment: FBNeo treats it as a regular set)" for n in in_fbneo) print(f" not MAME 0.285 Neo Geo names: {len(unknown)}; of these in the FBNeo dat: {len(in_fbneo)}") for comment, count in comments.most_common(): print(f" {count:4d} {comment}") plain = sorted(n for n in in_fbneo if not fbneo[n]["comment"]) print(f" FBNeo sets without a comment: {' '.join(plain)}") print(f" in neither list: {' '.join(n for n in unknown if n not in fbneo)}") absent = sorted(set(parents) - set(zips)) print(f" MAME parents absent ({len(absent)}): {' '.join(absent)}") fams = collections.Counter(FAMILY.get(configs.get(n, "?")) or f"bootleg/other ({configs.get(n, '?')})" for n in present) for fam, count in fams.most_common(): print(f" {count:4d} {fam}") ks = collections.Counter(kind(n, carts[n]) for n in present) print(" kinds: " + ", ".join(f"{k} {v}" for k, v in ks.most_common())) print() chds = sorted(CD_LIBRARY.glob("*.chd")) print(f"## Neo Geo CD: {len(chds)} .chd in {CD_LIBRARY}, {sum(p.stat().st_size for p in chds) / 2**30:.2f} GiB") return 0 if __name__ == "__main__": sys.exit(main())