#!/usr/bin/env python3 """Compute the Cx4's 3 KiB data ROM from fullsnes' formulas and compare it with every copy found. The HG51B169 in the Cx4 has one internal ROM: 1,024 words of 24 bits (fullsnes "CX4ROM (3Kbytes)"), six tables of division, square root, sine, arcsine, tangent and cosine. fullsnes gives a formula per table; this script evaluates them exactly (``fractions``/``decimal``, 60 digits: no float rounding) with **floor** (truncation toward zero), saturating at FFFFFFh, and compares the result word for word with: - a BYOR image passed with ``--image`` (3,072 bytes, little-endian 24-bit words: MAME's ``cx4.bin`` from a software-list set, higan's ``cx4.data.rom``, ares' ``hg51bs169.data.rom``; read in place, never copied); - the tables the pinned emulator sources carry, read in place as text from ``reference/`` (or snes-python's tree): bsnes ``hitachidsp/data-rom.cpp``, Mesen2 ``Cx4.Instructions.cpp`` ``_dataRom``, MiSTer ``drom.mif``. It prints each copy's SHA-1 (MAME's software list names a002f4efba42775a31185d443f3ed1790b0e949a, CRC b6e76a6a), the mismatches per table under floor and under round-to-nearest, the byte sum the program's "IMMEDIATE ROM" test (page 000Eh, entry 89h) computes, and how close each transcendental entry comes to an integer boundary (the margin a float64 implementation would need). Nothing is written. Run with ``python -I``:: python -I scripts/survey_data_rom.py python -I scripts/survey_data_rom.py --image "/path/to/cx4.bin" """ from __future__ import annotations import argparse import hashlib import math import re import sys import zlib from decimal import ROUND_FLOOR, ROUND_HALF_EVEN, Decimal, getcontext from pathlib import Path ROOT = Path(__file__).resolve().parents[1] TREES = (ROOT / "reference" / "src", Path("/data/emu/snes-python/reference/src")) COPIES = { "bsnes data-rom.cpp": "bsnes/bsnes/sfc/coprocessor/hitachidsp/data-rom.cpp", "Mesen2 _dataRom": "Mesen2/Core/SNES/Coprocessors/CX4/Cx4.Instructions.cpp", "MiSTer drom.mif": "SNES_MiSTer/rtl/chip/CX4/drom.mif", } MAME_SHA1 = "a002f4efba42775a31185d443f3ed1790b0e949a" TABLES = ( # (name, first word, count) - fullsnes "CX4ROM" index column ("div", 0x000, 256), ("sqrt", 0x100, 256), ("sin", 0x200, 128), ("asin", 0x280, 128), ("tan", 0x300, 128), ("cos", 0x380, 128), ) getcontext().prec = 60 EPSILON = Decimal(10) ** -45 # closer than this to an integer counts as that integer def pi() -> Decimal: """Pi to the context precision (Machin: 16 atan(1/5) - 4 atan(1/239)).""" def atan_inverse(x: int) -> Decimal: total, term, k, x2 = Decimal(0), Decimal(1) / x, 0, x * x while term > Decimal(10) ** -(getcontext().prec + 2): total += term / (2 * k + 1) if k % 2 == 0 else -term / (2 * k + 1) term /= x2 k += 1 return total return 16 * atan_inverse(5) - 4 * atan_inverse(239) PI = pi() def sin(x: Decimal) -> Decimal: term, total, n = x, x, 1 while abs(term) > Decimal(10) ** -58: term = -term * x * x / ((2 * n) * (2 * n + 1)) total += term n += 1 return total def cos(x: Decimal) -> Decimal: return sin(PI / 2 - x) def asin(y: Decimal) -> Decimal: """Bisection on sin over [0, pi/2]; 200 halvings is far below 60 digits.""" low, high = Decimal(0), PI / 2 for _ in range(200): middle = (low + high) / 2 if sin(middle) < y: low = middle else: high = middle return (low + high) / 2 def exact_values() -> list[Decimal]: """The six tables' real values, before rounding, from fullsnes' formulas.""" values: list[Decimal] = [] values += [ Decimal(0x800000) / n if n else Decimal(0x1000000) for n in range(256) ] # Div(0) saturates values += [Decimal(0x100000) * Decimal(n).sqrt() for n in range(256)] values += [ Decimal(0x1000000) * sin(PI * n / 256) for n in range(128) ] # 0..89.3 degrees in 128 steps values += [ Decimal(0x800000) * 2 / PI * asin(Decimal(n) / 128) for n in range(128) ] # 800000h/90 deg values += [Decimal(0x10000) * sin(PI * n / 256) / cos(PI * n / 256) for n in range(128)] values += [Decimal(0x1000000) * cos(PI * n / 256) for n in range(128)] # Cos(0) saturates return values def quantise(value: Decimal, rounding: str) -> int: nearest = value.to_integral_value(rounding=ROUND_HALF_EVEN) if abs(value - nearest) < EPSILON: result = int(nearest) # an exact case (tan 45 deg = 1, the integer square roots) else: result = int(value.to_integral_value(rounding=rounding)) return min(result, 0xFFFFFF) def generate(rounding: str = ROUND_FLOOR) -> list[int]: return [quantise(v, rounding) for v in exact_values()] def words_to_bytes(words: list[int]) -> bytes: return b"".join(w.to_bytes(3, "little") for w in words) def read_copy(path: Path) -> list[int] | None: """The 1,024 words of a copy: a raw 3,072-byte image or one of the emulator sources.""" if path.suffix in (".bin", ".rom") or path.stat().st_size == 3072: data = path.read_bytes() if len(data) != 3072: print(f"{path}: {len(data)} bytes, expected 3072") return None return [int.from_bytes(data[i : i + 3], "little") for i in range(0, 3072, 3)] text = path.read_text(encoding="utf-8", errors="replace") if path.suffix == ".mif": return [int(v, 16) for v in re.findall(r"[0-9A-Fa-f]{4}\s*:\s*([0-9A-Fa-f]{6});", text)] if "staticDataROM" in text: # bsnes: 3,072 decimal bytes body = text.split("staticDataROM[3072] = {", 1)[1].split("};", 1)[0] data = [int(x) for x in re.findall(r"\d+", body)] return [data[i] | data[i + 1] << 8 | data[i + 2] << 16 for i in range(0, len(data), 3)] if "_dataRom[1024] = {" in text: # Mesen2: 1,024 hex words body = text.split("_dataRom[1024] = {", 1)[1].split("};", 1)[0] return [int(x, 16) for x in re.findall(r"0x([0-9A-Fa-f]{6})", body)] return None def compare(name: str, words: list[int], floor: list[int], nearest: list[int]) -> None: data = words_to_bytes(words) sha1 = hashlib.sha1(data).hexdigest() print(f"{name}: {len(words)} words, SHA-1 {sha1}{' (= MAME cx4.bin)' if sha1 == MAME_SHA1 else ''}, " f"CRC {zlib.crc32(data):08x}, SHA-256 {hashlib.sha256(data).hexdigest()[:16]}...") # fmt: skip for table, first, count in TABLES: miss_floor = [i for i in range(first, first + count) if words[i] != floor[i]] miss_round = [i for i in range(first, first + count) if words[i] != nearest[i]] shown = ", ".join(f"{i:03X}: {words[i]:06X} vs {floor[i]:06X}" for i in miss_floor[:4]) print( f" {table:5s} floor: {len(miss_floor):3d} mismatches round: {len(miss_round):3d} {shown}" ) def margins(values: list[Decimal]) -> None: """How close each table's non-exact entries come to an integer (float64 needs < this error).""" for table, first, count in TABLES[2:]: closest = None for i in range(first, first + count): value = values[i] nearest = value.to_integral_value(rounding=ROUND_HALF_EVEN) gap = abs(value - nearest) if gap >= EPSILON and (closest is None or gap < closest[0]): closest = (gap, i) if closest: print( f" {table:5s} closest non-exact entry {closest[1]:03X}: {float(closest[0]):.3e} from an integer" ) def float64_table() -> list[int]: """The same formulas in IEEE double, to show what a float implementation gets.""" out = [min(0xFFFFFF, 0x800000 // n) if n else 0xFFFFFF for n in range(256)] out += [math.isqrt(n << 40) for n in range(256)] out += [min(0xFFFFFF, math.floor(0x1000000 * math.sin(math.pi * n / 256))) for n in range(128)] out += [math.floor(0x800000 * 2 / math.pi * math.asin(n / 128)) for n in range(128)] out += [math.floor(0x10000 * math.tan(math.pi * n / 256)) for n in range(128)] out += [min(0xFFFFFF, math.floor(0x1000000 * math.cos(math.pi * n / 256))) for n in range(128)] return out def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument( "--image", type=Path, action="append", default=[], help="a BYOR 3,072-byte data ROM" ) args = parser.parse_args() values = exact_values() floor = [quantise(v, ROUND_FLOOR) for v in values] nearest = [quantise(v, ROUND_HALF_EVEN) for v in values] data = words_to_bytes(floor) print(f"computed (floor): SHA-1 {hashlib.sha1(data).hexdigest()}" f"{' (= MAME cx4.bin)' if hashlib.sha1(data).hexdigest() == MAME_SHA1 else ''}; " f"byte sum {sum(data):06X} (the IMMEDIATE ROM test's R0); word sum {sum(floor) & 0xFFFFFF:06X}") # fmt: skip copies: list[tuple[str, Path]] = [(str(p), p) for p in args.image] for name, relative in COPIES.items(): found = next((tree / relative for tree in TREES if (tree / relative).exists()), None) if found: copies.append((name, found)) else: print(f"{name}: not found under {', '.join(map(str, TREES))}") for name, path in copies: words = read_copy(path) if words is None or len(words) != 1024: print(f"{name}: could not read 1,024 words from {path}") continue compare(name, words, floor, nearest) print("margins of the transcendental tables:") margins(values) as_float = float64_table() wrong = [ f"{i:03X}: {as_float[i]:06X} vs {floor[i]:06X}" for i in range(1024) if as_float[i] != floor[i] ] print(f"float64 evaluation: {len(wrong)} mismatches {', '.join(wrong)}") return 0 if __name__ == "__main__": sys.exit(main())