"""Comparing the board's frames with the detectors' pictures, by colour index. MAME 0.285 and Gearcoleco write RGB. Both use the same 16-colour table by default (MAME ``tms9928a.cpp`` ``tms9928a_palette``, BSD-3-Clause; Gearcoleco's frames show the same values entry for entry, OBSERVED). The table is quoted below only to read their output back to indices; it is data about the detectors, not used to draw anything. Colours 0 and 1 are both black there, so they compare as one class. MAME's snapshot is 280 x 216: the 256 x 192 picture with 12 pixels of border each side. Gearcoleco's frame is 256 x 192. """ from __future__ import annotations import struct import zlib from pathlib import Path #: MAME tms9928a.cpp l. 695-713 (BSD-3-Clause), the colours Gearcoleco's frames show too #: (detector data). DETECTOR_PALETTE = ( (0, 0, 0), (0, 0, 0), (33, 200, 66), (94, 220, 120), (84, 85, 237), (125, 118, 252), (212, 82, 77), (66, 235, 245), (252, 85, 84), (255, 121, 120), (212, 193, 84), (230, 206, 128), (33, 176, 59), (201, 91, 186), (204, 204, 204), (255, 255, 255), ) # fmt: skip def read_png(path: str | Path) -> tuple[int, int, list[tuple[int, int, int]]]: """Width, height and RGB pixels of an 8-bit RGB or RGBA, non-interlaced PNG.""" data = Path(path).read_bytes() if data[:8] != b"\x89PNG\r\n\x1a\n": raise ValueError(f"{path}: not a PNG") pos, idat, width = 8, b"", 0 height = depth = colour = 0 while pos < len(data): (length,) = struct.unpack(">I", data[pos : pos + 4]) kind = data[pos + 4 : pos + 8] body = data[pos + 8 : pos + 8 + length] if kind == b"IHDR": width, height, depth, colour, _, _, interlace = struct.unpack(">IIBBBBB", body) if depth != 8 or colour not in (2, 6) or interlace: raise ValueError(f"{path}: only 8-bit RGB/RGBA non-interlaced PNGs") elif kind == b"IDAT": idat += body pos += 12 + length channels = 3 if colour == 2 else 4 raw = zlib.decompress(idat) stride = width * channels previous = bytearray(stride) pixels: list[tuple[int, int, int]] = [] offset = 0 for _ in range(height): kind = raw[offset] line = bytearray(raw[offset + 1 : offset + 1 + stride]) offset += 1 + stride for i in range(stride): left = line[i - channels] if i >= channels else 0 up = previous[i] corner = previous[i - channels] if i >= channels else 0 if kind == 1: line[i] = (line[i] + left) & 0xFF elif kind == 2: line[i] = (line[i] + up) & 0xFF elif kind == 3: line[i] = (line[i] + ((left + up) >> 1)) & 0xFF elif kind == 4: p = left + up - corner pa, pb, pc = abs(p - left), abs(p - up), abs(p - corner) pred = left if pa <= pb and pa <= pc else (up if pb <= pc else corner) line[i] = (line[i] + pred) & 0xFF pixels.extend(tuple(line[i : i + 3]) for i in range(0, stride, channels)) previous = line return width, height, pixels def _nearest(rgb: tuple[int, int, int]) -> int: best, best_d = 0, 1 << 30 for index, ref in enumerate(DETECTOR_PALETTE): d = sum((a - b) * (a - b) for a, b in zip(rgb, ref, strict=True)) if d < best_d: best, best_d = index, d return best def detector_indices(path: str | Path) -> list[bytes]: """192 rows of 256 indices from a detector picture (MAME's border cropped).""" width, height, pixels = read_png(path) if (width, height) == (280, 216): x0, y0 = 12, 12 elif (width, height) == (256, 192): x0, y0 = 0, 0 else: raise ValueError(f"{path}: {width} x {height} is neither MAME's nor Gearcoleco's size") cache: dict[tuple[int, int, int], int] = {} rows = [] for y in range(192): base = (y0 + y) * width + x0 row = bytearray(256) for x in range(256): rgb = pixels[base + x] index = cache.get(rgb) if index is None: index = cache[rgb] = _nearest(rgb) row[x] = index rows.append(bytes(row)) return rows def differences(ours: tuple[bytes, ...] | list[bytes], theirs: list[bytes]) -> int: """Pixels whose indices differ, 0 and 1 counted as one (both black).""" count = 0 for a_row, b_row in zip(ours, theirs, strict=True): if a_row == b_row: continue for a, b in zip(a_row, b_row, strict=True): if a != b and not (a <= 1 and b <= 1): count += 1 return count