# SPDX-License-Identifier: MIT """A desktop window: play a cartridge with the picture and the keyboard (milestone 8). python -m a7800_python.frontend CART [--palette warm] [--composite] [--scale 3] The only module that needs a library beyond the pins: pygame-ce, for SDL's window. Run it on PyPy; the board is the reference, correct before fast, and runs well under real time, so the window shows every frame the board makes and never waits (there is no sound in the window yet: ``--wav`` on the command line records it). Picture: the television stage's window (television.py: the frame MAME shows, NTSC lines 27-250 or the PAL window), 320 clocks wide, each colour byte through one of three palettes. The palettes are frontend data computed from the wiki's colour documentation (DOC, tier 3, "Atari 7800 Color Documentation"): one uniform saturation for hues 1-15, none for hue 0, sixteen luminance steps, and the hue step that depends on the console's tuning and warmth: **cool** 24.7 degrees (a cold console), **warm** 26.7 (the second published tuning standard), **hot** 27.7 (fully warmed up). Where hue 1 sits (on the colour burst) and the saturation and luminance scales are fits, not measurements (FITTED in claims.md's word, but scripts/m8_frontend.py judges only the hue step, so nothing constrains them: in effect HYPOTHESIS; a capture of a console's video output would settle it). Composite artefacts (``--composite``, off by default; a fit, as above): the wiki (DOC) says a 320-mode pixel is half a colour-burst cycle, so alternating light and dark pixels read as colour, one hue with light pixels on even positions and another with dark ones there, and pairs give a weaker striped set. The option averages luminance over each two-pixel cycle and adds the alternation as chroma on one fixed axis (``ARTEFACT_ANGLE``, a fit) on top of the pixels' own chroma averaged the same way. Keys: arrows = joystick 1, Z / X = its left and right buttons (Space = both), Enter = Reset, Tab = Select, P = Pause, F1 / F2 toggle the left and right difficulty switches, Escape quits. """ from __future__ import annotations import argparse import math import sys from pathlib import Path PALETTES = {"cool": 24.7, "warm": 26.7, "hot": 27.7} # hue step, degrees (DOC: wiki) # The next three: "fits" no judge constrains (HYPOTHESIS; a console video capture would # settle them); scripts/m8_frontend.py checks only the hue step and the read-back. BURST_ANGLE = 180.0 # hue 1 on the colour burst, in the U/V plane (a fit) SATURATION = 0.2 # chroma amplitude, luminance 0-1 (a fit) ARTEFACT_ANGLE = 135.0 # the artefact axis (a fit) def _yuv_rgb(y: float, u: float, v: float) -> tuple[int, int, int]: # The standard YUV -> RGB matrix: a display conversion, not a hardware value. r = y + 1.140 * v g = y - 0.395 * u - 0.581 * v b = y + 2.032 * u return tuple(max(0, min(255, round(c * 255))) for c in (r, g, b)) def chroma(colour: int, step: float) -> tuple[float, float]: """(U, V) of a colour byte's hue: none for hue 0, else on the wheel at ``step``.""" hue = colour >> 4 if hue == 0: return 0.0, 0.0 angle = math.radians(BURST_ANGLE + (hue - 1) * step) return SATURATION * math.cos(angle), SATURATION * math.sin(angle) def palette(kind: str = "warm") -> list[tuple[int, int, int]]: """256 RGB triples, index = MARIA colour byte.""" step = PALETTES[kind] out = [] for colour in range(256): u, v = chroma(colour, step) out.append(_yuv_rgb((colour & 0x0F) / 15, u, v)) return out def render(frame: list[bytes], kind: str = "warm", composite: bool = False) -> bytes: """A frame of colour bytes as packed RGB rows (320 pixels a row).""" if not composite: table = [bytes(rgb) for rgb in palette(kind)] return b"".join(b"".join(table[c] for c in row) for row in frame) step = PALETTES[kind] axis = (math.cos(math.radians(ARTEFACT_ANGLE)), math.sin(math.radians(ARTEFACT_ANGLE))) out = bytearray() for row in frame: n = len(row) for x in range(n): a, b = row[x], row[x + 1 if x + 1 < n else x] ya, yb = (a & 0x0F) / 15, (b & 0x0F) / 15 ua, va = chroma(a, step) ub, vb = chroma(b, step) alt = (ya - yb) / 2 * (1 if x % 2 == 0 else -1) # light on even: +, dark on even: - y = (ya + yb) / 2 u = (ua + ub) / 2 + alt * axis[0] v = (va + vb) / 2 + alt * axis[1] out += bytes(_yuv_rgb(y, u, v)) return bytes(out) # Key -> action; resolved to pygame key codes when the window opens. Not hardware values. KEYS = { "up": "up", "down": "down", "left": "left", "right": "right", "z": "b1", "x": "b2", "space": "b12", "return": "reset", "tab": "select", "p": "pause", "f1": "left-difficulty", "f2": "right-difficulty", } # fmt: skip class Frontend: """The board, its television and a pygame-ce window (or SDL's dummy driver).""" def __init__(self, system, kind: str = "warm", composite: bool = False, scale: int = 3) -> None: import pygame from .television import Television, crop_for self.pygame = pygame self.system = system first, lines = crop_for(system.machine) self.tv = Television(system.board.maria, keep=1, first_line=first, lines=lines) self.kind, self.composite, self.scale = kind, composite, scale self.lines = lines self.held: set[str] = set() self.faults: set[str] = set() pygame.display.init() self.window = pygame.display.set_mode((320 * scale, lines * scale)) pygame.display.set_caption("a7800-python") self.surface = pygame.Surface((320, lines)) self.keymap = {pygame.key.key_code(name): action for name, action in KEYS.items()} self.running = True def handle(self, event) -> None: pygame = self.pygame if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): self.running = False return if event.type not in (pygame.KEYDOWN, pygame.KEYUP): return action = self.keymap.get(event.key) if action is None or ("keys" in self.faults and action == "right"): return down = event.type == pygame.KEYDOWN riot = self.system.board.riot # SWCHB: difficulties D6/D7, reset D0, select D1, pause D3, low = pressed (DOC: [SG]) if action.endswith("-difficulty"): if down: riot.input_b ^= 0x40 if action == "left-difficulty" else 0x80 return if action in ("reset", "select", "pause"): bit = {"reset": 0x01, "select": 0x02, "pause": 0x08}[action] riot.input_b = (riot.input_b & ~bit) if down else (riot.input_b | bit) return (self.held.add if down else self.held.discard)(action) held = self.held self.system.controllers.set( 0, up="up" in held, down="down" in held, left="left" in held, right="right" in held, left_button=bool(held & {"b1", "b12"}), right_button=bool(held & {"b2", "b12"}), ) # fmt: skip def run_frame(self) -> None: """Events, then the board to its next frame.""" for event in self.pygame.event.get(): self.handle(event) before = self.tv.count while self.tv.count == before: self.system.step() def draw(self) -> None: frame = self.tv.frames[-1] kind = self.kind if "pixels" in self.faults: # seeded: the wrong palette kind = "cool" if kind != "cool" else "hot" data = render(frame, kind, self.composite and "composite" not in self.faults) image = self.pygame.image.frombuffer(data, (320, self.lines), "RGB") self.surface.blit(image, (0, 0)) self.pygame.transform.scale(self.surface, self.window.get_size(), self.window) self.pygame.display.flip() def loop(self) -> None: while self.running: self.run_frame() self.draw() def main(argv: list[str] | None = None) -> int: from .system import System parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cart", type=Path) parser.add_argument("--palette", choices=sorted(PALETTES), default="warm") parser.add_argument("--composite", action="store_true") parser.add_argument("--scale", type=int, default=3) args = parser.parse_args(argv) system = System.from_rom(args.cart) Frontend(system, args.palette, args.composite, args.scale).loop() return 0 if __name__ == "__main__": sys.exit(main())