#!/usr/bin/env python3 """Rung 4: an emulated VATT against VATT's results on real MSX1 machines (tier 3). VATT (aoineko, msxgl; ``reference/src/VATT``, CC-BY-SA-4.0) writes 256 reference bytes slowly, overwrites them with 256 writes from an unrolled loop of a fixed period (12-31 Z80 clocks, MSX clocks: one M1 wait per opcode fetch included), reads back slowly and counts how many fast bytes landed; it repeats this (16 or 128 times, no sync to the display) and reports the average percentage. The raw sheet (``reference/docs/vatt-raw.csv``, live export, no licence: numbers are cited, the sheet is never committed) has one row per machine, owner, mode and display setting. Here the same burst is played into the core with windows on: writes every ``period x 3`` master clocks (the MSX Z80 runs at XTAL/3), starting at evenly spread positions in the frame, and the fraction of the 256 positions that hold the fast byte is averaged. VATT's "sprites hidden" setting (sprite 0 at Y = 208) is reproduced; every TMS row in the sheet uses it. python -I validation/vatt.py fit # access_delay x lost-access rule, Graphics II python -I validation/vatt.py check # the default against every row, all modes """ from __future__ import annotations import csv import dataclasses import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] try: # the package under test (validation/faults.py puts a broken copy first) import tms9918_python # noqa: F401 except ImportError: sys.path.insert(0, str(ROOT / "src")) from tms9918_python import TMS9918, TMS9928A, TMS9929A # noqa: E402 SHEET = ROOT / "reference" / "docs" / "vatt-raw.csv" PERIODS = (12, 14, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31) # VATT mode name -> (R0, R1 without BLANK): 16K, IE off. MODES = {"T1": (0x00, 0x90), "G1": (0x00, 0x80), "G2": (0x02, 0x80), "MC": (0x00, 0x88)} EXCLUDED = ("T6950", "YM2220") # not TI parts (brief, rung 4) BUFFER = 0x3800 # where the 256 test bytes go SAT = 0x3F00 # R5 = $7E @dataclasses.dataclass class Row: machine: str owner: str vdp: str hz: int display: bool mode: str percent: dict[int, float] # period -> percent landed (only periods tested) def load_rows() -> list[Row]: rows = [] with SHEET.open(encoding="utf-8") as f: table = list(csv.reader(f)) header = [h.replace("\n", " ") for h in table[0]] first = header.index("12") for r in table[1:]: if r[2] != "MSX1" or r[3] != "Texas Instruments" or any(x in r[4] for x in EXCLUDED): continue percent = {} for period, cell in zip(PERIODS, r[first : first + len(PERIODS)]): cell = cell.strip() if cell == "OK": percent[period] = 100.0 elif cell: percent[period] = float(cell) rows.append(Row(f"{r[0]} {r[1]}", r[8], r[4], int(r[6]), r[13] == "TRUE", r[16], percent)) return rows def emulate( variant, mode: str, display: bool, period: int, rule: str, delay: int, phases: int = 32 ) -> float: """Percent of 256 fast writes that land, averaged over ``phases`` start positions.""" row = dataclasses.replace(variant, access_delay=delay) vdp = TMS9918(row, lost_access=rule) r0, r1 = MODES[mode] for reg, value in ((1, 0x80), (0, r0), (2, 0x0E), (3, 0xFF), (4, 0x03), (5, 0x7E), (6, 0x07)): _reg(vdp, reg, value) vdp.vram[SAT] = 0xD0 # sprites hidden _reg(vdp, 1, r1 | (0x40 if display else 0)) frame = vdp.lines * 684 landed = 0 for k in range(phases): vdp.vram[BUFFER : BUFFER + 256] = bytes(256) # the slow reference write start = (k * frame) // phases + (k * 37) % 684 # spread over lines and dots here = (vdp.line * 684 + vdp.slot * 4 + vdp._phase) % frame vdp.run((start - here) % frame) vdp.write(1, BUFFER & 0xFF) vdp.run(36) vdp.write(1, 0x40 | BUFFER >> 8) for _ in range(256): vdp.run(period * 3) vdp.write(0, 0xFF) vdp.run(684 * 2) # let the last request out landed += sum(1 for b in vdp.vram[BUFFER : BUFFER + 256] if b == 0xFF) return 100.0 * landed / (256 * phases) def _reg(vdp: TMS9918, reg: int, value: int) -> None: vdp.write(1, value) vdp.write(1, 0x80 | reg) def spreads( rows: list[Row], hz: int, display: bool, mode: str ) -> dict[int, tuple[float, float, int]]: """period -> (lowest, highest, number of rows) for one frame rate, display, mode.""" out = {} for period in PERIODS: values = [ r.percent[period] for r in rows if r.hz == hz and r.display == display and r.mode == mode and period in r.percent ] if values: out[period] = (min(values), max(values), len(values)) return out def score( model: dict[int, float], spread: dict[int, tuple[float, float, int]] ) -> tuple[int, float]: """(periods outside the hardware spread, summed distance outside it in percent).""" outside, distance = 0, 0.0 for period, (lo, hi, _) in spread.items(): value = model[period] if value < lo - 1e-9 or value > hi + 1e-9: outside += 1 distance += lo - value if value < lo else value - hi return outside, distance def fit(phases: int = 16) -> None: rows = load_rows() spread = spreads(rows, 60, True, "G2") periods = sorted(spread) print("Graphics II, display on, 60 Hz rows: period: lowest-highest (rows)") print(" " + " ".join(f"{p}:{lo:.0f}-{hi:.0f}({n})" for p, (lo, hi, n) in spread.items())) for rule in ("newer", "restart", "older"): for delay in (0, 8, 12, 16, 20, 22, 24, 28, 32, 40): model = {p: emulate(TMS9928A, "G2", True, p, rule, delay, phases) for p in periods} outside, distance = score(model, spread) cells = " ".join(f"{model[p]:5.1f}" for p in periods) print(f"{rule:8s} delay {delay:2d}: outside {outside:2d}, by {distance:6.1f} {cells}") sys.stdout.flush() def check(phases: int = 32) -> int: rows = load_rows() failures = 0 for hz, variant in ((60, TMS9928A), (50, TMS9929A)): for display in (True, False): for mode in MODES: spread = spreads(rows, hz, display, mode) if not spread: continue model = { p: emulate(variant, mode, display, p, "newer", variant.access_delay, phases) for p in spread } outside, distance = score(model, spread) failures += outside print(f"{hz} Hz display {'on ' if display else 'off'} {mode}: outside {outside}, " f"by {distance:.1f}") # fmt: skip for p, (lo, hi, n) in spread.items(): mark = "" if lo - 1e-9 <= model[p] <= hi + 1e-9 else " <-- outside" print( f" {p:2d} T: core {model[p]:5.1f} hardware {lo:5.1f}-{hi:5.1f} ({n}){mark}" ) sys.stdout.flush() return failures def main() -> int: if len(sys.argv) < 2 or sys.argv[1] not in ("fit", "check"): print(__doc__) return 2 if sys.argv[1] == "fit": fit() return 0 return 1 if check() else 0 if __name__ == "__main__": sys.exit(main())