# SPDX-License-Identifier: MIT """The TIA, half colour clock by half colour clock: picture, sync, RDY, collisions, inputs. **Modelling level: signal**, judged by the die (39 Sim2600 traces, every pin, every half clock). Evidence tags: DIE marks a rule a die trace settles (the trace named); DOC marks Towers' notes, tia-fpga's README findings or the Stella Programmer's Guide (SPG); TEST ROM marks console results (#699, Bradford Mott's table). Where several apply the strongest is named first. Modelled as the circuit (docs/timing.md), and judged against the die: the visual6502 netlist of the 10444D simulated by Sim2600, through tia-fpga's recorded traces (every pin, every half clock; docs/validation.md "Die-derived"). The timing rules are those Towers read off the schematics (``reference/docs/TIA_HW_Notes.txt``) as corrected by the netlist findings tia-fpga published (``reference/src/tia-fpga/sim/README.md``, "What the traces have settled"; cited below as *tia-fpga*). The sound channels are in audio.py. **Time.** One step is one half colour clock: a rising or a falling edge of the colour clock. A line is 456 steps; a CPU cycle is six. Each step computes the next state of every latch from the present state, then commits it all at once, and the pins are read from the committed state, as synchronous logic does. **Writes** land on the step where the 6507's Φ2 falls (tia-fpga "The bus"). A register takes the value on that step and shows it from the next; a strobe (WSYNC, RSYNC, RESxx) also has a window of three steps, the three half clocks CLK2 is low after the write. **Counters** are 6-bit polynomial counters (Towers "Polynomial Counters"), kept here as the count they represent (0-56 for the horizontal counter, 0-39 for objects): a bijection with the LFSR's states. The one state outside it, the illegal all-ones the counters can power up in and reset from, is :data:`LFSR_ERROR`. """ from __future__ import annotations from .audio import Audio from .machine import REFERENCE_TIA, TIARevision LINE_STEPS = 456 # half colour clocks per line; DOC: 228 colour clocks (SPG); DIE: every trace LFSR_ERROR = -1 # DOC: Towers "Polynomial Counters", the all-ones state # Horizontal counter decodes. DOC: Towers' table, lines 131-206; DIE: every trace. SHS, RHS, RHB, LRHB, CNT, SHB = 4, 8, 16, 18, 36, 56 # Object counter START decodes. DOC: Towers 252-293; DIE: players, missiles, retrigger. CLOSE, MEDIUM, FAR, MAIN = 3, 7, 15, 39 # Write addresses (A0-A5). DOC: SPG register map. VSYNC, VBLANK, WSYNC, RSYNC = 0x00, 0x01, 0x02, 0x03 NUSIZ0, NUSIZ1, COLUP0, COLUP1, COLUPF, COLUBK, CTRLPF = range(0x04, 0x0B) REFP0, REFP1, PF0, PF1, PF2 = range(0x0B, 0x10) RESP0, RESP1, RESM0, RESM1, RESBL = range(0x10, 0x15) GRP0, GRP1, ENAM0, ENAM1, ENABL = range(0x1B, 0x20) HMP0, HMP1, HMM0, HMM1, HMBL, VDELP0, VDELP1, VDELBL, RESMP0, RESMP1 = range(0x20, 0x2A) HMOVE, HMCLR, CXCLR = 0x2A, 0x2B, 0x2C AUDC0, AUDV1 = 0x15, 0x1A # Audio ticks: phase A and phase B at these horizontal counts. DOC: tia-fpga # "Audio"; DIE: the audio and audio_modes traces (both pads, milestone 3). AUDIO_A, AUDIO_B = (1, 19), (9, 37) # NUSIZ D2-D0: which decodes besides the main one start a copy. DOC: Towers # 252-293; DIE: players, retrigger. COPIES = { 0b000: (), 0b001: (CLOSE,), 0b010: (MEDIUM,), 0b011: (CLOSE, MEDIUM), 0b100: (FAR,), 0b101: (), 0b110: (MEDIUM, FAR), 0b111: (), } # fmt: skip # Playfield bits, left to right within a half line: PF0 D4-D7, PF1 D7-D0, # PF2 D0-D7. DOC: SPG; DIE: playfield. PF_BITS = ( [(PF0, b) for b in range(4, 8)] + [(PF1, b) for b in range(7, -1, -1)] + [(PF2, b) for b in range(8)] ) # fmt: skip # Collision latch bits, and which two each read address returns in D7, D6. # DOC: SPG read map; DIE: collisions. COLLISION_READS = ( (0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11), (12, None), (13, 14), ) # fmt: skip def _next_count(count: int, period: int) -> int: return count + 1 if 0 <= count < period - 1 else 0 class ObjectCounter: """A movable object's position counter and its two-phase clock (Towers 230-251). The two-phase clock is a ring of four stages stepped by the object's clock: stage 0 begins H@1, 1 ends it (START decodes are latched there), 2 is H@2, where the counter steps. A RESxx strobe does not zero the counter: it holds the ring in H@1 for as long as its window lasts and sets a latch, and the next H@2 clears the counter (tia-fpga "Objects"). The window reaches the ring three steps after the strobe's own three steps. DIE: C4, the ``players``, ``resets_hblank`` and ``retrigger`` traces. """ __slots__ = ( "clear_pending", "count", "deferred", "pending", "ring", "strobe_left", "window_history", ) # fmt: skip def __init__(self) -> None: self.count = 0 self.ring = 0 self.pending = False self.clear_pending = False # decided as H@1 ends, applied at H@2 self.deferred = False # a stuffed pulse caught by a RESxx, due after it self.strobe_left = 0 # steps of the RESxx strobe still to come self.window_history = 0 # 3 bits: the strobe window, delayed class Player: """START latches, the stretch gate and the 3-bit scan counter (DOC: Towers 356-411; DIE: ``players``, ``hmove_wrap``, ``resp_start``).""" __slots__ = ( "copy_flag", "gate", "scan", "scanning", "size_history", "start_latched", "start_q", "start_q2", ) # fmt: skip def __init__(self) -> None: self.start_latched = False self.start_q = False self.start_q2 = False self.copy_flag = False # FSTOB: drawing a close/medium/far copy, not the main one self.size_history = (0, 0) # NUSIZ D2-D0, one and two steps ago self.gate = False self.scan = 0 self.scanning = False class Width: """The START count and the count after it, for missile and ball widths (DOC: Towers 943-968; DIE: ``missiles``, ``ball``).""" __slots__ = ("first", "second", "start_latched") def __init__(self) -> None: self.start_latched = False self.first = False self.second = False def _width_active(width: Width, size: int, ring: int) -> bool: """1 and 2 pixels are the first colour clocks of the START count, 4 the count, 8 the count and the one after (DOC: tia-fpga "Objects"; DIE: ``missiles``, ``ball``, ``resmp_release``).""" if size == 0: return width.first and ring == 3 if size == 1: return width.first and ring in (3, 0) if size == 2: return width.first return width.first or width.second class TIA: def __init__(self, hclock: int = 0, revision: TIARevision = REFERENCE_TIA) -> None: # Where this chip differs from the reference 10444D (machine.py). self.revision = revision self.line = 0 self.frame = 0 self.on_vsync = None # The picture: one byte per colour clock of the line being drawn, the # colour (D7-D1, as COLUxx) with D0 set when not blanked, taken on each # falling edge; ``on_line`` receives each finished line. self.pixels = bytearray(228) self.on_line = None self.registers = bytearray(0x40) self.audio = Audio() self.au0 = 0 self.au1 = 0 # Write registers. self.vsync = False self.vblank = 0 self.nusiz = [0, 0] self.missile_size = [0, 0] self.colours = [0, 0, 0, 0] # COLUP0, COLUP1, COLUPF, COLUBK self.ctrlpf = 0 self.reflect = [False, False] self.pf = {PF0: 0, PF1: 0, PF2: 0} self.grp_new = [0, 0] self.grp_old = [0, 0] self.enam = [False, False] self.enabl_new = False self.enabl_old = False self.hm = (0, 0, 0, 0, 0) # P0 P1 M0 M1 BL: HMxx D7-D4 self.vdelp = [False, False] self.vdelbl = False self.resmp = [False, False] # Horizontal counter. self.hcount = 0 self.hphase = 3 # falling edges since the last H@2, mod 4 self.hblank = True self.hsync = False self.rsync_window = 0 self.rsync_wait = 0 self.cpu_divider = 3 # PH0 divider, counted on both edges; high for 3, 4, 5 # RDY. self.rdy_low = False self.release_left = 0 self.wsync_left = 0 # HMOVE. self.hmove_latch = False self.motion_count = 15 self.motion_more = 0 # P0 P1 M0 M1 BL as bits 4..0 self.motion_armed = False self.motion_running = False self.h1_history = 0 # 12 steps of H@1, H@2 and HMOVE strobes self.h2_history = 0 self.hmove_history = 0 # HMxx 1 to 4 steps ago, one tuple: four attributes would take the TIA # past 80, where PyPy keeps an instance as a dict (twice as slow) self.hm_late = (self.hm,) * 4 self.merge_1 = self.merge_2 = self.merge_3 = self.merge_4 = 0 # merged pulses, steps ago self.merged = 0 # Objects: P0 P1 M0 M1 BL. self.counters = [ObjectCounter() for _ in range(5)] self.players = [Player(), Player()] self.missiles = [Width(), Width()] self.ball = Width() # Playfield. self.pf_index = 0 self.pf_down = False self.pf_read = False self.pf_shown = False # Collision latches, bit order as COLLISION_READS. self.collisions = 0 # Output latches. self.out_objects = [False, False, False, False, False] self.out_colours = [0, 0, 0, 0] self.out_score = False self.out_priority = False self.score_right = False self.vblank_seen = False self.vblank_latched = False # Inputs. self.inputs = 0x3F # pads I0-I5 self.trigger_latch = 0b11 self.fire = [False, False] # board convenience: INPT4/INPT5 pressed self.pad_source = None # a controller's pads at read time (controllers.py) self.dump_released = 0 # when VBLANK D7 last let the paddle pads go (``now``) # Pins after the last step. self.lum = 0 self.col = 0 self.blank = True self.sync_low = False self.ph0 = True # Where in the line: step 0 is the step HBLANK starts (a falling edge). self.step_in_line = 0 self.rising = True # the next step's edge for _ in range(2 * hclock): self.step() # -- the board's view --------------------------------------------------- @property def rdy(self) -> bool: return not self.rdy_low @property def hclock(self) -> int: """Colour clock within the line, 0 at HBLANK's start.""" return self.step_in_line // 2 @property def now(self) -> int: """Half colour clocks since power-on, near enough for the paddles' RC (lines are counted whole; RSYNC's short line is not).""" return self.line * LINE_STEPS + self.step_in_line def clocks_to_line_end(self) -> int: return (LINE_STEPS - self.step_in_line) // 2 def run(self, clocks: int) -> None: """Advance ``clocks`` colour clocks (two steps each), writing nothing.""" for _ in range(2 * clocks): self.step() def write(self, address: int, value: int) -> None: """A write on the step that is about to run.""" self.step((address, value)) # -- one half colour clock --------------------------------------------- def step(self, write: tuple[int, int] | None = None) -> None: """One half colour clock; ``write`` = (address, value) when the 6507's Φ2 falls on this step with a write to the TIA. Everything below reads the present state before anything is written back, so the order of the sections is free; objects whose clock did not tick and that hold no strobe skip their update (all of them through HBLANK and on every falling edge but HMOVE's), which is most steps. """ rise = self.rising fall = not rise address = write[0] & 0x3F if write is not None else -1 # ---- horizontal counter (DOC: tia-fpga "Clocks and the horizontal # counter", Towers; DIE: vertical, hmove, every trace's SYNC and BLANK) hcount, hphase, hblank = self.hcount, self.hphase, self.hblank h1 = fall and hphase == 0 h2 = fall and hphase == 2 rsync_go = self.rsync_wait == 1 at_shb = hcount == SHB at_rhb = hcount == (LRHB if self.hmove_latch else RHB) shb = (h2 and at_shb) or rsync_go release = rise and hphase == 1 and at_shb # three steps before H@2 hblank_next = True if (at_shb or rsync_go) else (False if at_rhb else hblank) n_hcount, n_hphase, n_hblank = hcount, hphase, hblank if fall: n_hphase = (hphase + 1) & 3 if rsync_go: n_hcount, n_hblank, n_hphase = 0, True, 3 elif h2: n_hcount = 0 if (at_shb or hcount == LFSR_ERROR) else _next_count(hcount, 57) if at_shb: n_hblank = True elif at_rhb: n_hblank = False if rise and hphase == 1: # the sync latch, three steps before H@2 if hcount == SHS: self.hsync = True elif hcount == RHS: self.hsync = False # RSYNC restarts the counter seven steps after the last step its strobe # shares with PH0 low (PH0 as it stood after the step before). DIE: C3, # every trace's opening RSYNC and Donkey Kong's power-on. rsync_window, rsync_wait = self.rsync_window, self.rsync_wait if address == RSYNC: self.rsync_window, self.rsync_wait = 3, 0 elif rsync_window or rsync_wait: self.rsync_window = rsync_window - 1 if rsync_window else 0 if rsync_window and not self.ph0: self.rsync_wait = 6 else: self.rsync_wait = rsync_wait - 1 if rsync_wait else 0 # PH0: the colour clock divided by three on both edges, reloaded at every # line start (DOC: tia-fpga, "the horizontal counter reloads it"; DIE: # the PH0 pin in every trace). if shb: self.cpu_divider = 3 elif rsync_wait == 3: self.cpu_divider = 0 else: self.cpu_divider = 0 if self.cpu_divider == 5 else self.cpu_divider + 1 # ---- RDY: set by WSYNC's strobe, released by an eight-step pulse that # starts three steps before HBLANK (DOC: tia-fpga "The bus"; DIE: the RDY # pin in every trace, C16; scripts/die_board.py on Sim2600's 6507). release_left, wsync_left = self.release_left, self.wsync_left if release or release_left or address == WSYNC or wsync_left: release_now = release or release_left != 0 wsync_now = address == WSYNC or wsync_left != 0 self.release_left = 7 if release else (release_left - 1 if release_left else 0) self.wsync_left = 2 if address == WSYNC else (wsync_left - 1 if wsync_left else 0) if release_now and fall: self.rdy_low = False elif wsync_now and not release_now: self.rdy_low = True # ---- HMOVE (Towers 604-753; tia-fpga "HMOVE"): the motion counter and # its comparators run 12 steps behind the horizontal counter, and the # comparators see HMxx as it stood four steps before: an HMxx write # just as the motion runs out still counts (DIE: hm_late, C36; BASIC # Programming; two steps missed it, five or more break tia-fpga's # hmove trace on its own wiring; milestone 4). m_h1 = self.h1_history & 0x800 m_h2 = self.h2_history & 0x800 m_hmove = self.hmove_history & 0x800 stuff = merge_now = 0 count = self.motion_count if m_h1: hit = 0 for i, hm in enumerate(self.hm_late[3]): if count == (hm & 0x8) | (~hm & 0x7): # D7 is wired the other way hit |= 0x10 >> i still = self.motion_more & ~hit if hblank_next: stuff = still else: merge_now = still if m_hmove: self.motion_count, self.motion_more, self.motion_armed = 15, 0x1F, True self.motion_running = True elif m_h1: self.motion_more, self.motion_armed = still, False elif m_h2 and not self.motion_armed and self.motion_running: # Down to 0, then reset to 15, where it rests until the next HMOVE # (Towers: "64 CLK (including counter reset at the end)"): so after # an HMOVE no HMxx of $70 (compare value 0) can clear a stuck # latch, only another HMOVE can (DIE: hmove_cycles; DOC: Towers). if count == 0: self.motion_count, self.motion_running = 15, False else: self.motion_count = count - 1 merge = self.merge_4 # Revision field (machine.TIARevision): on some consoles a merged pulse # swallows the next MOTCK without stepping the object first. revision = self.revision merge_step = merge & revision.merge_steps # The latch that moves HBLANK's end to LRHB samples the strobe on H@2, # the first one at least five steps after the write (Towers: "3 CLK # after the HMOVE command ... at most 6 CLK depending on the timing of # STA HMOVE"), and the counter's wrap clears it: so an HMOVE on cycle # 20 is too late for this line's RHB (DIE: hmove_cycles). When the # set and the wrap's clear fall on one half clock (an HMOVE on cycle # 74) the set wins, as on seven consoles (TEST ROM: Bradford Mott's NTSC table, # ale-79's six PAL/SECAM ones, Stella #699), so the next line gets the # comb; Sim2600's netlist settles that race the other way # (docs/undocumented-behavior.md C27). if h2 and self.hmove_history & 0xFF0: # a write 5 to 12 steps ago n_hmove_latch = True elif shb: n_hmove_latch = False else: n_hmove_latch = self.hmove_latch # ---- object clocks: MOTCK while HBLANK is off, plus stuffed pulses; a # merged pulse steps the object early and absorbs its next MOTCK (DOC: # tia-fpga "HMOVE"; DIE: hmove, hmove_cycles; TEST ROM: #699 for the # consoles whose revision does not step, machine.TIARevision). motck = rise and not hblank merged = self.merged object_motck = ((0x1F & ~merged) if motck else 0) | merge_step object_clock = object_motck | stuff self.merged = merge | (0 if motck else merged) # ---- objects: outputs from the present state (collisions, the pads) counters, players = self.counters, self.players need_pixels = fall or not hblank pixels = self._pixels() if need_pixels else None # RESMPx holds the missile's ring like a RESxx window, from the step # its player's scan counter shows 1, with no delay: a 2-clock delay # put a released missile two clocks right of the die's # (DIE: resmp_release, C38; Frostbite's ice floes; milestone 4). locks = ( False, False, self.resmp[0] and players[0].scan == 1 and not players[0].copy_flag, self.resmp[1] and players[1].scan == 1 and not players[1].copy_flag, False, ) # Ring events, from the present counter state. events = [] for i in range(5): c = counters[i] clocked = object_clock & (0x10 >> i) held = (c.window_history & 4) or locks[i] ring = c.ring due = c.deferred and not c.window_history and not c.strobe_left ring_clock = (clocked or due) and not held events.append((clocked, ring_clock and ring == 1, ring_clock and ring == 2, held, ring)) # ---- players for i in range(2): p, c = players[i], counters[i] clocked, o_h1_end, o_h2, held, ring = events[i] nusiz = self.nusiz[i] size1, size2 = p.size_history if ( not clocked and not o_h1_end and size1 == nusiz and size2 == nusiz and not (object_motck & (0x10 >> i)) ): continue start_decode = False if o_h1_end: start_decode = c.count == MAIN or c.count in COPIES[nusiz] if start_decode and c.count != MAIN: p.copy_flag = True if o_h2 and c.count == MAIN: p.copy_flag = False old_gate, old_q, old_q2 = p.gate, p.start_q, p.start_q2 if clocked or object_motck & (0x10 >> i): # The stretch gate: the two-phase state caught on MOTCK and on # HMOVE's stuffed pulses too, so under the comb those shift out # a wrapped player's last pixels (Towers: "a HMOVE can gobble # up the wrapped player graphics"; DIE: hmove_wrap, C34; Sea # Hawk), NUSIZ taken two steps late (DOC: tia-fpga "Objects"). A # RESxx hold opens a 2x gate and shuts a 4x one (DIE: resp_start, C35). if size2 == 0b111: p.gate = bool(held) or ring != 3 elif size2 == 0b101: p.gate = not (held or ring == 1 or ring == 3) else: p.gate = False if clocked: start_pulse = old_q2 if nusiz in (0b101, 0b111) else old_q p.start_q = o_h2 and p.start_latched p.start_q2 = old_q # The scan counter takes START only on a clock the stretch gate # lets through: a 4x copy whose start falls in a RESxx hold is # never drawn, a 2x one is (DIE: hmove_wrap, resp_start). if start_pulse and not old_gate: p.scan, p.scanning = 0, True elif not old_gate and p.scanning: p.scanning = p.scan != 7 p.scan = (p.scan + 1) & 7 if o_h1_end: p.start_latched = start_decode p.size_history = (nusiz, size1) # ---- missiles and the ball for j in range(2): _, o_h1_end, o_h2, _, _ = events[2 + j] if o_h1_end: c = counters[2 + j] self.missiles[j].start_latched = c.count == MAIN or c.count in COPIES[self.nusiz[j]] elif o_h2: m = self.missiles[j] m.second, m.first = m.first, m.start_latched if events[4][2]: ball = self.ball ball.second, ball.first = ball.first, counters[4].clear_pending # ---- object counters (after the players, missiles and ball read them) for i in range(5): c = counters[i] strobe = address == RESP0 + i clocked, o_h1_end, o_h2, held, ring = events[i] if not (clocked or strobe or c.strobe_left or c.window_history or held or c.deferred): continue if o_h1_end: c.clear_pending = c.pending or c.count == MAIN or c.count == LFSR_ERROR if o_h2: c.count = 0 if c.clear_pending else _next_count(c.count, 40) # A stuffed (HMOVE) pulse that arrives after the RESxx strobe's own # step and before its hold lets go is not lost: it steps the ring # once the hold is over. MOTCK pulses, on the other edge, never # meet the strobe's steps (DIE: hmove_resp0, C28). Some consoles # lose one that comes while the strobe is still low (TEST ROM: the # #699 tables; revision field ``strobe_drops``). due = c.deferred and not c.window_history and not c.strobe_left and not strobe c.ring = 1 if held else ((ring + 1) & 3 if ((clocked or due) and not held) else ring) bit = 0x10 >> i if stuff & bit and ((c.strobe_left and not revision.strobe_drops & bit) or held): c.deferred = True elif due: c.deferred = False c.pending = True if held else (False if o_h2 else c.pending) window = strobe or c.strobe_left != 0 c.strobe_left = 2 if strobe else (c.strobe_left - 1 if c.strobe_left else 0) c.window_history = ((c.window_history << 1) | window) & 0b111 # ---- playfield: each bit is read on H@1 and shown from the next H@2 # (DOC: tia-fpga "The picture"; DIE: playfield, C17). The bit is chosen # by the horizontal count alone, from RHB even on a line HMOVE's comb # blanks to LRHB, so the comb hides the first two bits but does not # delay the rest (Pitfall!'s trunks; DIE: hmove_playfield, C29). pf_pixel = self.pf_shown and not hblank if h1: if hcount == RHB: index_next = 0 elif hcount == CNT: index_next = 19 if self.ctrlpf & 1 else 0 else: index_next = self.pf_index - 1 if self.pf_down else self.pf_index + 1 if not 0 <= index_next <= 19: index_next = 0 register, bit = PF_BITS[index_next] self.pf_read = bool(self.pf[register] >> bit & 1) if h2: self.pf_shown = self.pf_read if hcount == RHB: self.pf_index, self.pf_down = 0, False elif hcount == CNT: self.pf_index, self.pf_down = (19, True) if self.ctrlpf & 1 else (0, False) else: self.pf_index += -1 if self.pf_down else 1 # ---- collisions, on the visible rising edges; VBLANK gates them too # (DIE: this project's vblank_collisions trace, C24; collisions) if address == CXCLR: self.collisions = 0 elif rise and not hblank and not self.vblank_latched: p0, p1, m0, m1, bl = pixels pf = pf_pixel if (p0 + p1 + m0 + m1 + bl + pf) >= 2: self.collisions |= ( (m0 and p1) | (m0 and p0) << 1 | (m1 and p0) << 2 | (m1 and p1) << 3 | (p0 and pf) << 4 | (p0 and bl) << 5 | (p1 and pf) << 6 | (p1 and bl) << 7 | (m0 and pf) << 8 | (m0 and bl) << 9 | (m1 and pf) << 10 | (m1 and bl) << 11 | (bl and pf) << 12 | (p0 and p1) << 13 | (m0 and m1) << 14 ) # fmt: skip # ---- output latches: objects and colours on the falling edge; an object # that took a merged pulse is latched just after it steps, below. The # playfield and blanking reach the pads directly (DOC: tia-fpga "The # picture"; DIE: every trace's LUM/COL pins). if fall: out = self.out_objects for i in range(5): if not merge_step & (0x10 >> i): out[i] = pixels[i] # A colour register written on this step reaches the latch on this # same falling edge: the die shows a mid-line COLUBK write on the # write's own half clock (DIE: retrigger, step 184; C25). out_colours = self.out_colours out_colours[:] = self.colours if COLUP0 <= address <= COLUBK: out_colours[address - COLUP0] = write[1] self.out_score, self.out_priority = bool(self.ctrlpf & 2), bool(self.ctrlpf & 4) if shb: self.score_right = False elif fall and hphase == 1 and hcount == CNT: # two steps before H@2 (DIE: playfield) self.score_right = True # VBLANK's bit settles a step after the write, then waits for a falling # edge (DIE: vertical, C31; DOC: tia-fpga "VBLANK does not blank where it # is written"). if fall: self.vblank_latched = self.vblank_seen self.vblank_seen = bool(self.vblank & 2) # ---- inputs: VBLANK D6 latches the triggers once low (DOC: SPG, VBLANK # D6; settling instantly is HYPOTHESIS: the die traces drive no pads). if self.vblank & 0x40: fire = self.fire pads = (self.inputs >> 4) & ~(fire[0] | fire[1] << 1) self.trigger_latch &= pads else: self.trigger_latch = 0b11 # ---- commit the rest self.rising = not rise self.hcount, self.hphase, self.hblank = n_hcount, n_hphase, n_hblank self.hmove_latch = n_hmove_latch self.h1_history = ((self.h1_history << 1) | h1) & 0xFFF self.h2_history = ((self.h2_history << 1) | h2) & 0xFFF self.hmove_history = ((self.hmove_history << 1) | (address == HMOVE)) & 0xFFF late = self.hm_late self.hm_late = (self.hm, late[0], late[1], late[2]) self.merge_4, self.merge_3, self.merge_2, self.merge_1 = ( self.merge_3, self.merge_2, self.merge_1, merge_now, ) if merge_step: # A merged pulse steps the object half a colour clock early, and the # pads take it on this same step (DOC: tia-fpga "HMOVE": "the object # shows its next state half a colour clock early"; DIE: hmove). now = self._pixels() for i in range(5): if merge_step & (0x10 >> i): self.out_objects[i] = now[i] if write is not None: self._write_register(address, write[1]) if shb: if self.on_line is not None: self.on_line(self.pixels) self.step_in_line = 0 self.line += 1 else: self.step_in_line += 1 # ---- sound: two ticks a line, each in two phases, on the rising edge # that latches the sync decodes; the pads change at phase B, steps 77 # and 301 of the line, 112 and 116 colour clocks apart (DIE: ``audio`` # and ``audio_modes``). if rise and hphase == 1: if hcount in AUDIO_A: self.audio.tick_a() elif hcount in AUDIO_B: self.audio.tick_b() # ---- pins, from the committed state. Priority and SCORE: DOC: SPG # CTRLPF; DIE: collisions, players, ball_score. c0, c1 = self.audio.channels self.au0 = c0.audv if c0.pulse & 1 else 0 self.au1 = c1.audv if c1.pulse & 1 else 0 self.ph0 = self.cpu_divider >= 3 self.sync_low = self.hsync != self.vsync blank = self.hblank or self.vblank_latched self.blank = blank if blank: colour = 0 else: p0q, p1q, m0q, m1q, blq = self.out_objects colup0, colup1, colupf, colubk = self.out_colours pf_or_ball = self.pf_shown or blq if self.out_score and not self.out_priority: pf_colour = colup1 if self.score_right else colup0 else: pf_colour = colupf if self.out_priority and pf_or_ball: colour = pf_colour elif p0q or m0q: colour = colup0 elif p1q or m1q: colour = colup1 elif self.pf_shown: colour = pf_colour elif blq: # SCORE colours the playfield only: the ball keeps COLUPF # (C32; DIE: ball_score; Alpha Beam with Ernie). colour = colupf else: colour = colubk self.col = colour >> 4 self.lum = (colour >> 1) & 7 if fall: self.pixels[(self.step_in_line >> 1) % 228] = 0 if blank else (colour & 0xFE) | 1 def _pixels(self) -> list[bool]: """Each object's output as the present state gives it.""" out = [] for i, p in enumerate(self.players): grp = self.grp_old[i] if self.vdelp[i] else self.grp_new[i] bit = p.scan if self.reflect[i] else 7 - p.scan out.append(p.scanning and bool(grp >> bit & 1)) for j, m in enumerate(self.missiles): ring = self.counters[2 + j].ring out.append( _width_active(m, self.missile_size[j], ring) and self.enam[j] and not self.resmp[j] ) enabl = self.enabl_old if self.vdelbl else self.enabl_new out.append( _width_active(self.ball, (self.ctrlpf >> 4) & 3, self.counters[4].ring) and enabl ) return out def _write_register(self, address: int, value: int) -> None: """The register map and bit meanings: DOC: SPG; GRP/ENABL's VDEL copies DOC: SPG, DIE: vdel, grp_mid_draw (C30).""" self.registers[address] = value if address == VSYNC: on = bool(value & 0x02) if on and not self.vsync: self.frame += 1 if self.on_vsync is not None: self.on_vsync(self.frame) self.vsync = on elif address == VBLANK: if self.vblank & 0x80 and not value & 0x80: self.dump_released = self.now self.vblank = value elif address in (NUSIZ0, NUSIZ1): i = address - NUSIZ0 self.nusiz[i] = value & 7 self.missile_size[i] = (value >> 4) & 3 elif COLUP0 <= address <= COLUBK: self.colours[address - COLUP0] = value elif address == CTRLPF: self.ctrlpf = value elif address in (REFP0, REFP1): self.reflect[address - REFP0] = bool(value & 0x08) elif address in (PF0, PF1, PF2): self.pf[address] = value elif address == GRP0: self.grp_new[0] = value self.grp_old[1] = self.grp_new[1] elif address == GRP1: self.grp_new[1] = value self.grp_old[0] = self.grp_new[0] self.enabl_old = self.enabl_new elif address in (ENAM0, ENAM1): self.enam[address - ENAM0] = bool(value & 0x02) elif address == ENABL: self.enabl_new = bool(value & 0x02) elif HMP0 <= address <= HMBL: hm = list(self.hm) hm[address - HMP0] = value >> 4 self.hm = tuple(hm) elif address in (VDELP0, VDELP1): self.vdelp[address - VDELP0] = bool(value & 1) elif address == VDELBL: self.vdelbl = bool(value & 1) elif address in (RESMP0, RESMP1): self.resmp[address - RESMP0] = bool(value & 0x02) elif address == HMCLR: self.hm = (0, 0, 0, 0, 0) elif AUDC0 <= address <= AUDV1: self.audio.write(address, value) # -- reads ---------------------------------------------------------------- def read(self, address: int) -> int: """D7 and D6 of a read, as the die drives them during Φ2; D5-D0 float. The two read addresses with no register ($E, $F) are driven as zeros (DOC: tia-fpga "The bus"; DIE: the D7/D6 drive pins of every trace). VBLANK D7 grounds the paddle pads; VBLANK D6 makes the trigger pads latch low (DOC: SPG). """ address &= 0x0F if address < 8: d7_bit, d6_bit = COLLISION_READS[address] c = self.collisions d6 = 0 if d6_bit is None else c >> d6_bit & 1 return (c >> d7_bit & 1) << 7 | d6 << 6 inputs = self.inputs if self.pad_source is None else self.pad_source() if address < 12: return 0 if self.vblank & 0x80 else ((inputs >> (address - 8)) & 1) << 7 if address < 14: i = address - 12 pad = 0 if self.fire[i] else (inputs >> (4 + i)) & 1 if self.vblank & 0x40: pad &= self.trigger_latch >> i return (pad & 1) << 7 return 0