# SPDX-License-Identifier: MIT """The HG51B169's data ROM: 1,024 words of 24 bits, computed from fullsnes' six formulas. The chip's only internal ROM holds six math tables (fullsnes "SNES Cart Capcom CX4", the "CX4ROM" table). Each word is the formula's exact real value, **floored** and saturated at FFFFFFh (U21). Evaluated exactly (``decimal`` at 50 digits; the nearest non-exact entry is 7.2e-4 from an integer, so the precision is far beyond what the floor needs), the result equals a real chip's dump word for word: MAME's ``cx4.bin`` (SHA-1 :data:`DUMP_SHA1`, from MAME's CC0 software list ``hash/snes.xml``; ``scripts/check_data_rom.py`` compares a player's own dump; handoff decision 3). Its byte sum, :data:`BYTE_SUM`, is what the game's IMMEDIATE ROM test (page 0Eh, entry 89h) computes. IEEE double gets exactly one word wrong (tan 45 deg), which is why the generator uses ``decimal``. ``data_rom()`` computes the table once per process (cached) and returns a fresh list each call. ``load_data_rom(path)`` reads a BYOR image (``cx4.bin``, higan's ``cx4.data.rom``, ares' ``hg51bs169.data.rom``: 3,072 bytes, little-endian 24-bit words) and checks its SHA-1 against the dump's unless ``check=False``. """ from __future__ import annotations import hashlib import math from decimal import ROUND_FLOOR, ROUND_HALF_EVEN, Decimal, localcontext from functools import cache from pathlib import Path WORDS = 1024 SIZE = WORDS * 3 #: SHA-1 of a real chip's dump (MAME ``hash/snes.xml``: ``cx4.bin``, CRC b6e76a6a). DUMP_SHA1 = "a002f4efba42775a31185d443f3ed1790b0e949a" #: The byte sum of the 3,072 bytes: R0 after the IMMEDIATE ROM test (0E:89). BYTE_SUM = 0x054336 #: (name, first word, count): fullsnes' index column. TABLES = ( ("div", 0x000, 256), ("sqrt", 0x100, 256), ("sin", 0x200, 128), ("asin", 0x280, 128), ("tan", 0x300, 128), ("cos", 0x380, 128), ) _DIGITS = 50 _EXACT = Decimal(10) ** -40 # closer than this to an integer: the value *is* that integer def _pi() -> Decimal: """Pi to the context precision (Machin's formula).""" def arctan_inverse(x: int) -> Decimal: total, power, k, square = Decimal(0), Decimal(1) / x, 0, x * x limit = Decimal(10) ** -(_DIGITS + 5) while power > limit: term = power / (2 * k + 1) total += -term if k & 1 else term power /= square k += 1 return total return 16 * arctan_inverse(5) - 4 * arctan_inverse(239) def _sin(x: Decimal) -> Decimal: """Taylor series; the arguments here lie in [0, pi/2].""" term, total, n = x, x, 1 limit = Decimal(10) ** -(_DIGITS + 5) while abs(term) > limit: term = -term * x * x / ((2 * n) * (2 * n + 1)) total += term n += 1 return total def _asin(y: Decimal, pi: Decimal) -> Decimal: """Newton's method on sin(x) = y, from the float64 estimate (y < 1 here).""" x = Decimal(math.asin(float(y))) for _ in range(8): # quadratic convergence: 16 digits -> far beyond 50 sine = _sin(x) cosine = _sin(pi / 2 - x) x -= (sine - y) / cosine return x def _floor(value: Decimal) -> int: """Floor, except that a value within :data:`_EXACT` of an integer is that integer (tan 45 deg = 1 exactly; a 50-digit evaluation may land a hair below), saturated at FFFFFFh.""" nearest = value.to_integral_value(rounding=ROUND_HALF_EVEN) if abs(value - nearest) < _EXACT: result = int(nearest) else: result = int(value.to_integral_value(rounding=ROUND_FLOOR)) return min(result, 0xFFFFFF) @cache def _computed() -> tuple[int, ...]: with localcontext() as context: context.prec = _DIGITS pi = _pi() step = pi / 256 # n x 90 deg / 128 words: list[int] = [] # div: 800000h / n; n = 0 has no quotient and reads FFFFFFh (saturated). words += [min(0x800000 // n, 0xFFFFFF) if n else 0xFFFFFF for n in range(256)] # sqrt: 100000h x sqrt(n) = isqrt(n << 40), exact in integers. words += [math.isqrt(n << 40) for n in range(256)] # sin: 1000000h x sin(n x 90 deg / 128). sines = [_sin(step * n) for n in range(128)] words += [_floor(0x1000000 * s) for s in sines] # asin: 800000h / 90 deg x asin(n / 128), the angle in units of 90 deg / 800000h. words += [_floor(0x800000 * 2 / pi * _asin(Decimal(n) / 128, pi)) for n in range(128)] # tan: 10000h x tan(n x 90 deg / 128); cos as sin of the complement. cosines = [_sin(pi / 2 - step * n) for n in range(128)] words += [_floor(0x10000 * s / c) for s, c in zip(sines, cosines, strict=True)] # cos: 1000000h x cos(n x 90 deg / 128); cos 0 = 1000000h saturates to FFFFFFh. words += [_floor(0x1000000 * c) for c in cosines] return tuple(words) def data_rom() -> list[int]: """The 1,024 words of the data ROM, computed (U21); a new list each call.""" return list(_computed()) def to_bytes(words: list[int] | tuple[int, ...]) -> bytes: """The image layout: each word as three little-endian bytes.""" return b"".join(word.to_bytes(3, "little") for word in words) def from_bytes(data: bytes) -> list[int]: if len(data) != SIZE: raise ValueError(f"a data ROM image is {SIZE} bytes, not {len(data)}") return [int.from_bytes(data[i : i + 3], "little") for i in range(0, SIZE, 3)] def load_data_rom(path: str | Path, *, check: bool = True) -> list[int]: """Read a BYOR image in place; with ``check``, its SHA-1 must be the dump's.""" data = Path(path).read_bytes() words = from_bytes(data) if check: digest = hashlib.sha1(data).hexdigest() if digest != DUMP_SHA1: raise ValueError(f"{path}: SHA-1 {digest} is not the HG51B169 dump's {DUMP_SHA1}") return words __all__ = [ "BYTE_SUM", "DUMP_SHA1", "SIZE", "TABLES", "WORDS", "data_rom", "from_bytes", "load_data_rom", "to_bytes", ]