# SPDX-License-Identifier: MIT """GTIA (C014805, NTSC) behind a pin-shaped interface. GTIA owns the picture: it turns ANTIC's AN0-AN2 codes into colour-register values, shifts out players and missiles, applies priority, records collisions, reads the triggers and drives the four CONSOL lines. It sees the bus only as the data byte of each cycle and ANTIC's HALT pin (it latches P/M DMA bytes itself: [AHRM] 6.5 "Player/missile graphics DMA"). It imports nothing from the board (tests/test_boundaries.py). The working specification is [AHRM] chapter 6 (tier 3) and the GTIA data sheet [DS-G] (tier 2). **One cycle** is ``cycle(an_a, an_b, halt, data)``: the two colour clocks of a machine cycle, at horizontal positions 2c and 2c+1 of ANTIC's cycle c. GTIA keeps its own horizontal counter, set to $DE at the leading edge of horizontal blank (an AN code 2 or 3 after a non-blank one) and free-running otherwise ([AHRM] 6.2 "Blanking and sync regions"); a line starts when it reaches $DE. Output goes to :attr:`line`, two bytes per colour clock (the two half-clock pixels, equal except in high resolution), indexed by position, as colour-register values (hue << 4 | luma), not RGB. **Register writes take effect after the delays of [AHRM] 6.10 Table 18**, counted in colour clocks from the first colour clock of the write cycle: colour 1, PRIOR 2, P/M graphics 3, P/M position and size 5 (the 2-3 and 3-5 ranges there are unit-dependent: the first value is modelled). **Priority is the logic of [AHRM] 6.7**, evaluated as written (the SP/SF/SB equations), and cached per input combination; it is not a fitted table. Evidence tags (methodology): DOC is [AHRM] and [DS-G]; TEST ROM is an Acid5200 test (author-stated hardware passes, no recorded 5200 run: U7); FITTED names the tests a value was chosen for. """ from __future__ import annotations HBLANK_START = 0xDE # DOC: [AHRM] 6.2 (the counter's value at the blank edge) VISIBLE_LEFT = 0x22 # DOC: [AHRM] 6.2 LINE_POSITIONS = 228 # DOC: [AHRM] 4.2, 228 colour clocks per line # Write delays in colour clocks (DOC [AHRM] 6.10 Table 18), by register 0-31. DELAY = [5] * 8 + [3] * 5 + [3] * 5 + [1] * 9 + [2, 0, 0, 0, 0] # HPOS (0-7) SIZE (8-12) GRAF (13-17) COLPM0-COLBK (18-26) PRIOR VDELAY GRACTL HITCLR CONSOL # SIZE: FITTED 3, not Table 18's 5 (which lists position and size together): # gtia_pmresize needs a size change to steer the state machine from the third # colour clock (C13); 5 (Table 18) was tried first and fails it. HPOS: DOC 5 as # in Table 18; TEST ROM gtia_pmretrigger brackets it at 5-8 and gtia_pmoverlap # at 5-6. GRAF 3, colours 1, PRIOR 2: DOC Table 18 (first value of each range). def resolve(prior: int, players: int, playfield: int) -> tuple[int, ...]: """The colour registers that show, from [AHRM] 6.7's priority equations. DOC: the equations as [AHRM] 6.7 writes them (themselves from the GTIA data sheet's logic); TEST ROM gtia_collision, gtia_collision2, gtia_psuedomodee. ``players``: bits 0-3 = P0-P3 (missiles already merged in unless fifth player); ``playfield``: bits 0-3 = PF0-PF3 (fifth player merged into PF3). Returns indices: 0-3 COLPM0-3, 4-7 COLPF0-3, 8 COLBK; empty = black. """ pri0, pri1, pri2, pri3 = (prior >> 0) & 1, (prior >> 1) & 1, (prior >> 2) & 1, (prior >> 3) & 1 multi = (prior >> 5) & 1 p0, p1, p2, p3 = (players >> 0) & 1, (players >> 1) & 1, (players >> 2) & 1, (players >> 3) & 1 f0, f1, f2, f3 = ( (playfield >> 0) & 1, (playfield >> 1) & 1, (playfield >> 2) & 1, (playfield >> 3) & 1, ) pri01, pri12, pri23, pri03 = pri0 | pri1, pri1 | pri2, pri2 | pri3, pri0 | pri3 pf01, pf23, p01, p23 = f0 | f1, f2 | f3, p0 | p1, p2 | p3 n = (1).__xor__ # logical NOT of a bit sp0 = p0 & n(pf01 & pri23) & n(pri2 & pf23) sp1 = p1 & n(pf01 & pri23) & n(pri2 & pf23) & (n(p0) | multi) sp2 = p2 & n(p01) & n(pf23 & pri12) & n(pf01 & n(pri0)) sp3 = p3 & n(p01) & n(pf23 & pri12) & n(pf01 & n(pri0)) & (n(p2) | multi) sf3 = f3 & n(p23 & pri03) & n(p01 & n(pri2)) sf0 = f0 & n(p23 & pri0) & n(p01 & pri01) & n(sf3) sf1 = f1 & n(p23 & pri0) & n(p01 & pri01) & n(sf3) sf2 = f2 & n(p23 & pri03) & n(p01 & n(pri2)) & n(sf3) sb = n(p01) & n(p23) & n(pf01) & n(pf23) out = [] for index, bit in enumerate((sp0, sp1, sp2, sp3, sf0, sf1, sf2, sf3, sb)): if bit: out.append(index) return tuple(out) class GTIA: def __init__(self, pal: bool = False, ctia: bool = False) -> None: self.pal = pal # chip fields for a future computer board (U14) # Registers power up at 0: HYPOTHESIS (U8); TEST ROM gtia_default passes. self.ctia = ctia self.hposp = [0, 0, 0, 0] self.hposm = [0, 0, 0, 0] self.sizep = [0, 0, 0, 0] self.sizem = 0 self.grafp = [0, 0, 0, 0] self.grafm = 0 # COLPM0-3, COLPF0-3, COLBK in register order (index 0-8). self.colour = [0] * 9 self.prior = 0 self.vdelay = 0 self.gractl = 0 self.consol_out = 0 # lines pulled down by writes (bits 0-3) # Collisions: M0PF-M3PF, P0PF-P3PF, M0PL-M3PL, P0PL-P3PL. self.mpf = [0, 0, 0, 0] self.ppf = [0, 0, 0, 0] self.mpl = [0, 0, 0, 0] self.ppl = [0, 0, 0, 0] self.trig_in = [1, 1, 1, 1] # pin levels: 0 = pressed self.trig_latch = [1, 1, 1, 1] # P/M shifters (DOC [AHRM] 6.5): eight-bit players, two-bit missiles, two-bit states. self.psr = [0, 0, 0, 0] self.pst = [0, 0, 0, 0] self.msr = [0, 0, 0, 0] self.mst = [0, 0, 0, 0] self.pm_live = False self._triggers: dict[int, int] = {} self.pending: list[tuple[int, int, int]] = [] self.cc = 0 # absolute colour clock of this cycle's first half self.hpos = HBLANK_START # position of the colour clock last processed self.vline = 0 self.hires = False self._blank = True self._pm_slot = -1 self._pair = 0 self._pixel10 = -1 # mode 10: the delayed pixel still to show, -1 = none since blank self._pm_even = (0, 0) # modes 9/11: the even clock's players and missiles self._cache: dict[int, tuple[int, ...]] = {} self.line = bytearray(2 * LINE_POSITIONS) self.line_done = False # set when a line ended (hpos reached $DE) # -- registers ---------------------------------------------------------- def read(self, register: int) -> int: r = register & 0x1F if r < 4: return self.mpf[r] if r < 8: return self.ppf[r - 4] if r < 12: return self.mpl[r - 8] if r < 16: return self.ppl[r - 12] if r < 20: n = r - 16 # DOC: GRACTL bit 2 latches the triggers ([AHRM] 6.1); TEST ROM gtia_default. return self.trig_latch[n] if self.gractl & 4 else self.trig_in[n] if r == 0x1F: # DOC: CONSOL reads the lines the writes left high ([AHRM] 6.1, 13.3); # TEST ROM gtia_consol. return ~self.consol_out & 0x0F # DOC: PAL at $14; unassigned reads alike ([AHRM] 6.1); TEST ROM gtia_default. return 0x01 if self.pal else 0x0F def write(self, register: int, value: int) -> None: r = register & 0x1F delay = DELAY[r] if r == 27: # PRIOR bits 6-7 (the GTIA modes) take 3 colour clocks, the rest 2 # (DOC [AHRM] 6.10 Table 18: "3-5", first value modelled). Index 32 is # an internal name for the late half. self.pending.append((self.cc + 3, 32, value)) if delay: self.pending.append((self.cc + delay, r, value)) return self._apply(r, value) def _apply(self, r: int, value: int) -> None: if r < 4: self.hposp[r] = value elif r < 8: self.hposm[r - 4] = value elif r < 12: self.sizep[r - 8] = value & 3 elif r == 12: self.sizem = value elif r < 17: self.grafp[r - 13] = value elif r == 17: self.grafm = value elif r < 27: self.colour[r - 18] = value & 0xFE # DOC: luma bit 0 not stored ([AHRM] 6.1) elif r == 27: self.prior = (self.prior & 0xC0) | (value & 0x3F) elif r == 32: self.prior = (self.prior & 0x3F) | (value & 0xC0) return elif r == 28: self.vdelay = value elif r == 29: self.gractl = value if not value & 4: self.trig_latch = [1, 1, 1, 1] elif r == 30: self.mpf = [0, 0, 0, 0] self.ppf = [0, 0, 0, 0] self.mpl = [0, 0, 0, 0] self.ppl = [0, 0, 0, 0] elif r == 31: self.consol_out = value & 0x0F self._retrigger() def _retrigger(self) -> None: """Positions where an object with a non-empty image triggers.""" triggers: dict[int, int] = {} for n in range(4): if self.grafp[n]: triggers[self.hposp[n]] = triggers.get(self.hposp[n], 0) | (1 << n) if self.grafm >> (2 * n) & 3: triggers[self.hposm[n]] = triggers.get(self.hposm[n], 0) | (16 << n) self._triggers = triggers def set_trigger(self, n: int, pressed: bool) -> None: self.trig_in[n] = 0 if pressed else 1 if pressed: self.trig_latch[n] = 0 # -- one machine cycle ---------------------------------------------------- def cycle(self, an_a: int, an_b: int, halt: bool, data: int) -> None: # P/M DMA as GTIA sees it: the first halted cycle in horizontal blank is # the missile fetch; players follow two to five cycles later (DOC [AHRM] 6.5; # TEST ROM gtia_phantomdma, gtia_vdelay with the writes redirected). VDELAY's # odd-line rule: DOC [AHRM] 6.5. pos = (self.hpos + 1) % LINE_POSITIONS if pos >= HBLANK_START or pos < VISIBLE_LEFT: slot = self._pm_slot if slot < 0: if halt: slot = 0 else: slot += 1 if slot >= 0: self._pm_slot = slot if slot == 0: if self.gractl & 1: self._dma_missiles(data) elif 2 <= slot <= 5 and self.gractl & 2: n = slot - 2 if not (self.vdelay >> (4 + n)) & 1 or self.vline & 1: self.pending.append((self.cc + 3, 13 + n, data)) self._clock(an_a) self.cc += 1 self._clock(an_b) self.cc += 1 def _dma_missiles(self, data: int) -> None: keep = 0 if not self.vline & 1: for n in range(4): if (self.vdelay >> n) & 1: keep |= 3 << (2 * n) value = (self.grafm & keep) | (data & ~keep & 0xFF) self.pending.append((self.cc + 3, 17, value)) def _clock(self, code: int) -> None: if self.pending: now = self.cc due = [p for p in self.pending if p[0] <= now] if due: self.pending = [p for p in self.pending if p[0] > now] for _, r, value in due: self._apply(r, value) hpos = self.hpos + 1 if hpos == LINE_POSITIONS: hpos = 0 blank = code == 2 or code == 3 if blank and not self._blank: hpos = HBLANK_START # DOC: resynchronise at the blank's leading edge ([AHRM] 6.2) self._blank = blank if hpos == HBLANK_START: self.vline += 1 self._pm_slot = -1 self.line_done = True self.hpos = hpos # The high-resolution flip-flop (DOC [AHRM] 6.8): set from ANTIC's blank # code during horizontal blank, reset whenever PRIOR 6-7 is non-zero, # so a GTIA mode switched off after blank leaves "pseudo mode E" (TEST # ROM gtia_psuedomodee). if self.prior & 0xC0 and not self.ctia: self.hires = False elif blank: self.hires = code == 3 if code == 1: self.vline = 251 # DOC: vertical sync lines are 251-253 ([AHRM] 6.2) # Players and missiles: trigger on position, then shift (DOC [AHRM] 6.5; # TEST ROM gtia_pmretrigger, gtia_pmoverlap, gtia_pmresize). players = missiles = 0 if self.pm_live or hpos in self._triggers: players, missiles = self._shift_objects(hpos) line = self.line i = 2 * hpos if blank or code == 1: line[i] = line[i + 1] = 0 self._pixel10 = -1 return prior = self.prior gmode = 0 if self.ctia else prior >> 6 hires = self.hires and not gmode if gmode: self._gtia_mode(code, hpos, players, missiles, gmode) return # Playfield signals from the AN code (DOC [AHRM] 6.9 Table 17, 6.8). if hires: playfield = 4 if code >= 4 else 0 pf_collide = 4 if code & 3 and code >= 4 else 0 else: playfield = (1 << (code - 4)) if code >= 4 else 0 pf_collide = playfield if players or missiles: self._collide(players, missiles, pf_collide) if prior & 0x10: # DOC: fifth player, missiles join PF3's layer ([AHRM] 6.7) pm = players if missiles: playfield |= 8 else: pm = players | missiles else: pm = 0 key = (prior & 0x3F) << 8 | pm << 4 | playfield sel = self._cache.get(key) if sel is None: sel = self._cache[key] = resolve(prior, pm, playfield) colour = self.colour value = 0 for index in sel: value |= colour[index] if prior & 0x10 and missiles and 7 in sel and playfield & 8: pass # the fifth player already shows as COLPF3 through index 7 if hires and code >= 4: lum = colour[5] & 0x0E # DOC: PF1's luminance on 1 bits ([AHRM] 6.8) line[i] = (value & 0xF0) | lum if code & 2 else value line[i + 1] = (value & 0xF0) | lum if code & 1 else value else: line[i] = line[i + 1] = value def _shift_objects(self, hpos: int) -> tuple[int, int]: trig = self._triggers.get(hpos, 0) players = missiles = 0 live = False psr, pst, msr, mst = self.psr, self.pst, self.msr, self.mst for n in range(4): # A trigger forces the state machine to %00; if it was elsewhere, # that transition shifts the register once before the image is ORed # in ([AHRM] 6.5: "a shift occurs each time the state machine # transitions to %00, which is forced whenever the shift register is # reloaded"; C14). DOC read literally; TEST ROM gtia_pmoverlap needs # exactly that. if trig & (1 << n): sr = psr[n] if pst[n]: sr = (sr << 1) & 0xFF psr[n] = sr | self.grafp[n] pst[n] = 0 sr = psr[n] if sr: if sr & 0x80: players |= 1 << n st = (pst[n] + 1) & self.sizep[n] pst[n] = st if not st: sr = (sr << 1) & 0xFF psr[n] = sr live = live or sr != 0 if trig & (16 << n): sr = msr[n] if mst[n]: sr = (sr << 1) & 3 msr[n] = sr | ((self.grafm >> (2 * n)) & 3) mst[n] = 0 sr = msr[n] if sr: if sr & 2: missiles |= 1 << n st = (mst[n] + 1) & ((self.sizem >> (2 * n)) & 3) mst[n] = st if not st: sr = (sr << 1) & 3 msr[n] = sr live = live or sr != 0 self.pm_live = live return players, missiles def _collide(self, players: int, missiles: int, playfield: int) -> None: # DOC: collision latches ([AHRM] 6.6); TEST ROM gtia_collision, gtia_collision2. for n in range(4): bit = 1 << n if players & bit: self.ppf[n] |= playfield self.ppl[n] |= players & ~bit if missiles & bit: self.mpf[n] |= playfield self.mpl[n] |= players def _gtia_mode(self, code: int, hpos: int, players: int, missiles: int, gmode: int) -> None: """GTIA modes 9-11 ([AHRM] 6.9): two colour clocks form one 4-bit pixel. Only the playfield pixel is two colour clocks wide (and, in mode 10, delayed by one colour clock: it covers the odd clock and the even clock after it). Players and missiles keep their colour-clock resolution (DOC [AHRM] 6.5: "Position registers have color clock resolution"; OBSERVED: Atari800 98cc2dc agrees on the three titles; no Acid5200 test covers it), so priority, colour and collisions are resolved on every colour clock with that clock's objects. Before 2026-11-12 the board sampled the objects on the odd clock only and painted the result over the pair, which moved Rescue on Fractalus!'s fifth-player missiles one colour clock right (docs/validation.md, milestone 7). """ line = self.line i = 2 * hpos if not hpos & 1: self._pair = code & 3 if gmode == 2: # The second half of the delayed pixel of the previous pair. pixel = self._pixel10 if pixel < 0: line[i] = line[i + 1] = line[i - 1] if i else 0 else: line[i] = line[i + 1] = self._gtia_value(pixel, players, missiles, gmode) else: # Drawn when the pair completes, with this clock's objects. self._pm_even = (players, missiles) return pixel = self._pair << 2 | (code & 3) value = self._gtia_value(pixel, players, missiles, gmode) if gmode == 2: # DOC: mode 10 is delayed by one colour clock ([AHRM] 6.9). self._pixel10 = pixel line[i] = line[i + 1] = value else: even_players, even_missiles = self._pm_even if i >= 2: first = self._gtia_value(pixel, even_players, even_missiles, gmode) line[i - 2] = line[i - 1] = first line[i] = line[i + 1] = value def _gtia_value(self, pixel: int, players: int, missiles: int, gmode: int) -> int: """One colour clock of a GTIA-mode pixel with that clock's players and missiles.""" colour = self.colour prior = self.prior fifth = prior & 0x10 pm = players | (0 if fifth else missiles) playfield = 0 pf_collide = 0 if gmode == 2: # DOC: nine colours, 0-3 P0-P3, x100-x111 PF0-PF3, 10xx background ([AHRM] 6.9). if pixel < 4: pm |= 1 << pixel elif pixel & 4: playfield = 1 << (pixel & 3) pf_collide = playfield if fifth and missiles: playfield |= 8 if players or missiles: self._collide(players, missiles, pf_collide) key = (prior & 0x3F) << 8 | pm << 4 | playfield sel = self._cache.get(key) if sel is None: sel = self._cache[key] = resolve(prior, pm, playfield) value = 0 for index in sel: value |= colour[index] if gmode != 2 and (not pm): # DOC: mode 9 takes luma from the pixel, mode 11 hue ([AHRM] 6.9). base = value if fifth and missiles else colour[8] value = base | pixel if gmode == 1 else base | pixel << 4 if pixel else base & 240 return value # -- state ------------------------------------------------------------------ def snapshot(self) -> dict: state = {} for key, value in vars(self).items(): if key == "_cache": continue if isinstance(value, bytearray): value = bytes(value) elif isinstance(value, list): value = list(value) elif isinstance(value, dict): value = dict(value) state[key] = value return state def restore(self, state: dict) -> None: for key, value in state.items(): if key == "line": value = bytearray(value) elif isinstance(value, list): value = list(value) setattr(self, key, value) self._cache = {}