// 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.rs. //! //! **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 //! [`LFSR_ERROR`]. //! //! Rust-forced differences (a2600-python `tia.py` at 28fb095): the callbacks //! `on_line`, `on_vsync` and `pad_source` are boxed closures; `on_line` and //! `pad_source` receive the TIA itself (a Python callback reaches it through //! the objects it holds), and none of them is part of a save state. `step`'s //! optional write is an `Option<(address, value)>`; the write address held //! as -1 when there is none is an `i32`. Python's lists and tuples are //! arrays; the playfield dictionary keyed by PF0-PF2 is an array indexed by //! the register less PF0. The `rdy`, `hclock` and `now` properties are methods. use serde::{Deserialize, Serialize}; use crate::audio::Audio; use crate::machine::{TIARevision, REFERENCE_TIA}; pub const LINE_STEPS: u32 = 456; // half colour clocks per line; DOC: 228 colour clocks (SPG); DIE: every trace pub const LFSR_ERROR: i32 = -1; // DOC: Towers "Polynomial Counters", the all-ones state // Horizontal counter decodes. DOC: Towers' table, lines 131-206; DIE: every trace. pub const SHS: i32 = 4; pub const RHS: i32 = 8; pub const RHB: i32 = 16; pub const LRHB: i32 = 18; pub const CNT: i32 = 36; pub const SHB: i32 = 56; // Object counter START decodes. DOC: Towers 252-293; DIE: players, missiles, retrigger. pub const CLOSE: i32 = 3; pub const MEDIUM: i32 = 7; pub const FAR: i32 = 15; pub const MAIN: i32 = 39; // Write addresses (A0-A5). DOC: SPG register map. pub const VSYNC: i32 = 0x00; pub const VBLANK: i32 = 0x01; pub const WSYNC: i32 = 0x02; pub const RSYNC: i32 = 0x03; pub const NUSIZ0: i32 = 0x04; pub const NUSIZ1: i32 = 0x05; pub const COLUP0: i32 = 0x06; pub const COLUP1: i32 = 0x07; pub const COLUPF: i32 = 0x08; pub const COLUBK: i32 = 0x09; pub const CTRLPF: i32 = 0x0A; pub const REFP0: i32 = 0x0B; pub const REFP1: i32 = 0x0C; pub const PF0: i32 = 0x0D; pub const PF1: i32 = 0x0E; pub const PF2: i32 = 0x0F; pub const RESP0: i32 = 0x10; pub const RESP1: i32 = 0x11; pub const RESM0: i32 = 0x12; pub const RESM1: i32 = 0x13; pub const RESBL: i32 = 0x14; pub const GRP0: i32 = 0x1B; pub const GRP1: i32 = 0x1C; pub const ENAM0: i32 = 0x1D; pub const ENAM1: i32 = 0x1E; pub const ENABL: i32 = 0x1F; pub const HMP0: i32 = 0x20; pub const HMP1: i32 = 0x21; pub const HMM0: i32 = 0x22; pub const HMM1: i32 = 0x23; pub const HMBL: i32 = 0x24; pub const VDELP0: i32 = 0x25; pub const VDELP1: i32 = 0x26; pub const VDELBL: i32 = 0x27; pub const RESMP0: i32 = 0x28; pub const RESMP1: i32 = 0x29; pub const HMOVE: i32 = 0x2A; pub const HMCLR: i32 = 0x2B; pub const CXCLR: i32 = 0x2C; pub const AUDC0: i32 = 0x15; pub const AUDV1: i32 = 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). pub const AUDIO_A: [i32; 2] = [1, 19]; pub const AUDIO_B: [i32; 2] = [9, 37]; // NUSIZ D2-D0: which decodes besides the main one start a copy. DOC: Towers // 252-293; DIE: players, retrigger. pub const COPIES: [&[i32]; 8] = [ &[], &[CLOSE], &[MEDIUM], &[CLOSE, MEDIUM], &[FAR], &[], &[MEDIUM, FAR], &[], ]; /// Playfield bits, left to right within a half line: PF0 D4-D7, PF1 D7-D0, /// PF2 D0-D7. DOC: SPG; DIE: playfield. #[rustfmt::skip] pub const PF_BITS: [(i32, u32); 20] = [ (PF0, 4), (PF0, 5), (PF0, 6), (PF0, 7), (PF1, 7), (PF1, 6), (PF1, 5), (PF1, 4), (PF1, 3), (PF1, 2), (PF1, 1), (PF1, 0), (PF2, 0), (PF2, 1), (PF2, 2), (PF2, 3), (PF2, 4), (PF2, 5), (PF2, 6), (PF2, 7), ]; /// Collision latch bits, and which two each read address returns in D7, D6. /// DOC: SPG read map; DIE: collisions. #[rustfmt::skip] pub const COLLISION_READS: [(u32, Option); 8] = [ (0, Some(1)), (2, Some(3)), (4, Some(5)), (6, Some(7)), (8, Some(9)), (10, Some(11)), (12, None), (13, Some(14)), ]; fn next_count(count: i32, period: i32) -> i32 { if 0 <= count && count < period - 1 { count + 1 } else { 0 } } fn copies(nusiz: u8, count: i32) -> bool { COPIES[nusiz as usize].contains(&count) } /// 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. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct ObjectCounter { pub count: i32, pub ring: i32, pub pending: bool, pub clear_pending: bool, // decided as H@1 ends, applied at H@2 pub deferred: bool, // a stuffed pulse caught by a RESxx, due after it pub strobe_left: i32, // steps of the RESxx strobe still to come pub window_history: i32, // 3 bits: the strobe window, delayed } /// START latches, the stretch gate and the 3-bit scan counter (DOC: Towers 356-411; /// DIE: `players`, `hmove_wrap`, `resp_start`). #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Player { pub start_latched: bool, pub start_q: bool, pub start_q2: bool, pub copy_flag: bool, // FSTOB: drawing a close/medium/far copy, not the main one pub size_history: (u8, u8), // NUSIZ D2-D0, one and two steps ago pub gate: bool, pub scan: i32, pub scanning: bool, } /// The START count and the count after it, for missile and ball widths (DOC: Towers /// 943-968; DIE: `missiles`, `ball`). #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Width { pub start_latched: bool, pub first: bool, pub second: 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`). fn width_active(width: &Width, size: u8, ring: i32) -> bool { if size == 0 { return width.first && ring == 3; } if size == 1 { return width.first && (ring == 3 || ring == 0); } if size == 2 { return width.first; } width.first || width.second } /// A callback given each finished line (it reads `tia.pixels`). pub type LineCallback = Box; /// A callback given the frame count at each VSYNC rising edge. pub type VsyncCallback = Box; /// A controller's pad levels I0-I5 at read time. pub type PadSource = Box u32>; #[derive(Serialize, Deserialize)] pub struct TIA { // Where this chip differs from the reference 10444D (machine.rs). #[serde(with = "revision_serde")] pub revision: TIARevision, pub line: u64, pub frame: u64, #[serde(skip)] pub on_vsync: Option, // 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. pub pixels: Vec, #[serde(skip)] pub on_line: Option, pub registers: Vec, pub audio: Audio, pub au0: u8, pub au1: u8, // Write registers. pub vsync: bool, pub vblank: u8, pub nusiz: [u8; 2], pub missile_size: [u8; 2], pub colours: [u8; 4], // COLUP0, COLUP1, COLUPF, COLUBK pub ctrlpf: u8, pub reflect: [bool; 2], pub pf: [u8; 3], // PF0, PF1, PF2 pub grp_new: [u8; 2], pub grp_old: [u8; 2], pub enam: [bool; 2], pub enabl_new: bool, pub enabl_old: bool, pub hm: [u8; 5], // P0 P1 M0 M1 BL: HMxx D7-D4 pub vdelp: [bool; 2], pub vdelbl: bool, pub resmp: [bool; 2], // Horizontal counter. pub hcount: i32, pub hphase: i32, // falling edges since the last H@2, mod 4 pub hblank: bool, pub hsync: bool, pub rsync_window: i32, pub rsync_wait: i32, pub cpu_divider: i32, // PH0 divider, counted on both edges; high for 3, 4, 5 // RDY. pub rdy_low: bool, pub release_left: i32, pub wsync_left: i32, // HMOVE. pub hmove_latch: bool, pub motion_count: i32, pub motion_more: u8, // P0 P1 M0 M1 BL as bits 4..0 pub motion_armed: bool, pub motion_running: bool, pub h1_history: u32, // 12 steps of H@1, H@2 and HMOVE strobes pub h2_history: u32, pub hmove_history: u32, // 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) pub hm_late: [[u8; 5]; 4], // a2600-rust-fast: steps since HMxx last changed, counted up to 4; at 4 // every row of hm_late equals hm, so the shift is skipped. Not in a save // state: 0 after a load, so the next four steps shift, which is always // exact. Code that writes `hm` directly must zero it. #[serde(skip)] pub hm_settle: u8, // a2600-rust-fast: true when the last check found no counter holding a // strobe, a window or a deferred pulse, and no step has run the counters' // full form since (only `objects::` changes those fields). Not in a // save state: false after a load, so the next step checks again. Code that // writes those counter fields directly must clear it. #[serde(skip)] pub counters_known_idle: bool, pub merge_1: u8, // merged pulses, steps ago pub merge_2: u8, pub merge_3: u8, pub merge_4: u8, pub merged: u8, // Objects: P0 P1 M0 M1 BL. pub counters: [ObjectCounter; 5], pub players: [Player; 2], pub missiles: [Width; 2], pub ball: Width, // Playfield. pub pf_index: i32, pub pf_down: bool, pub pf_read: bool, pub pf_shown: bool, // Collision latches, bit order as COLLISION_READS. pub collisions: u32, // Output latches. pub out_objects: [bool; 5], pub out_colours: [u8; 4], pub out_score: bool, pub out_priority: bool, pub score_right: bool, pub vblank_seen: bool, pub vblank_latched: bool, // Inputs. pub inputs: u32, // pads I0-I5 pub trigger_latch: u32, pub fire: [bool; 2], // board convenience: INPT4/INPT5 pressed #[serde(skip)] pub pad_source: Option, // a controller's pads at read time (controllers.rs) pub dump_released: i64, // when VBLANK D7 last let the paddle pads go (`now`) // Pins after the last step. pub lum: u8, pub col: u8, pub blank: bool, pub sync_low: bool, pub ph0: bool, // Where in the line: step 0 is the step HBLANK starts (a falling edge). pub step_in_line: u32, pub rising: bool, // the next step's edge } /// The revision row is data with static names: a state carries its fields /// and finds the named row again (or keeps the fields under the reference's /// name if it is not a known row). mod revision_serde { use crate::machine::{TIARevision, REFERENCE_TIA, TIA_REVISIONS}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; pub fn serialize(r: &TIARevision, s: S) -> Result { (r.name, r.merge_steps, r.strobe_drops).serialize(s) } pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result { let (name, merge_steps, strobe_drops) = <(String, u8, u8)>::deserialize(d)?; let row = TIA_REVISIONS .iter() .copied() .find(|r| r.name == name) .unwrap_or(REFERENCE_TIA); Ok(TIARevision { merge_steps, strobe_drops, ..row }) } } impl Default for TIA { fn default() -> Self { TIA::new(0, REFERENCE_TIA) } } impl TIA { pub fn new(hclock: u32, revision: TIARevision) -> TIA { let hm = [0u8; 5]; let mut tia = TIA { revision, line: 0, frame: 0, on_vsync: None, pixels: vec![0; 228], on_line: None, registers: vec![0; 0x40], audio: Audio::new(), au0: 0, au1: 0, vsync: false, vblank: 0, nusiz: [0, 0], missile_size: [0, 0], colours: [0, 0, 0, 0], ctrlpf: 0, reflect: [false, false], pf: [0, 0, 0], grp_new: [0, 0], grp_old: [0, 0], enam: [false, false], enabl_new: false, enabl_old: false, hm, vdelp: [false, false], vdelbl: false, resmp: [false, false], hcount: 0, hphase: 3, hblank: true, hsync: false, rsync_window: 0, rsync_wait: 0, cpu_divider: 3, rdy_low: false, release_left: 0, wsync_left: 0, hmove_latch: false, motion_count: 15, motion_more: 0, motion_armed: false, motion_running: false, h1_history: 0, h2_history: 0, hmove_history: 0, hm_late: [hm; 4], hm_settle: 0, counters_known_idle: false, merge_1: 0, merge_2: 0, merge_3: 0, merge_4: 0, merged: 0, counters: Default::default(), players: Default::default(), missiles: Default::default(), ball: Width::default(), pf_index: 0, pf_down: false, pf_read: false, pf_shown: false, collisions: 0, out_objects: [false; 5], out_colours: [0; 4], out_score: false, out_priority: false, score_right: false, vblank_seen: false, vblank_latched: false, inputs: 0x3F, trigger_latch: 0b11, fire: [false, false], pad_source: None, dump_released: 0, lum: 0, col: 0, blank: true, sync_low: false, ph0: true, step_in_line: 0, rising: true, }; for _ in 0..2 * hclock { tia.step(None); } tia } // -- the board's view --------------------------------------------------- pub fn rdy(&self) -> bool { !self.rdy_low } /// Colour clock within the line, 0 at HBLANK's start. pub fn hclock(&self) -> u32 { self.step_in_line / 2 } /// Half colour clocks since power-on, near enough for the paddles' RC /// (lines are counted whole; RSYNC's short line is not). pub fn now(&self) -> i64 { (self.line * LINE_STEPS as u64 + self.step_in_line as u64) as i64 } pub fn clocks_to_line_end(&self) -> u32 { (LINE_STEPS - self.step_in_line) / 2 } /// Advance `clocks` colour clocks (two steps each), writing nothing. pub fn run(&mut self, clocks: u32) { for _ in 0..2 * clocks { self.step(None); } } /// A write on the step that is about to run. pub fn write(&mut self, address: u8, value: u8) { self.step(Some((address, value))); } // -- one half colour clock --------------------------------------------- /// 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. pub fn step(&mut self, write: Option<(u8, u8)>) { // a2600-rust-fast: one body, compiled four times, for each edge with and // without a write, so each copy drops the tests its edge and its write // settle (the same code; only constants folded). match (self.rising, write) { (true, None) => self.edge::(-1, 0), (false, None) => self.edge::(-1, 0), (true, Some((a, v))) => self.edge::((a & 0x3F) as i32, v), (false, Some((a, v))) => self.edge::((a & 0x3F) as i32, v), } } /// `step` for an edge known at compile time (`RISE`, which is `self.rising`) /// and a write known present or absent (`WRITE`; `address` is -1 without one). fn edge(&mut self, address: i32, value: u8) { let rise = RISE; let fall = !rise; let address: i32 = if WRITE { address } else { -1 }; // ---- horizontal counter (DOC: tia-fpga "Clocks and the horizontal // counter", Towers; DIE: vertical, hmove, every trace's SYNC and BLANK) let (hcount, hphase, hblank) = (self.hcount, self.hphase, self.hblank); let h1 = fall && hphase == 0; let h2 = fall && hphase == 2; let rsync_go = self.rsync_wait == 1; let at_shb = hcount == SHB; let at_rhb = hcount == if self.hmove_latch { LRHB } else { RHB }; let shb = (h2 && at_shb) || rsync_go; let release = rise && hphase == 1 && at_shb; // three steps before H@2 let hblank_next = if at_shb || rsync_go { true } else if at_rhb { false } else { hblank }; let (mut n_hcount, mut n_hphase, mut n_hblank) = (hcount, hphase, hblank); if fall { n_hphase = (hphase + 1) & 3; } if rsync_go { n_hcount = 0; n_hblank = true; n_hphase = 3; } else if h2 { n_hcount = if at_shb || hcount == LFSR_ERROR { 0 } else { next_count(hcount, 57) }; if at_shb { n_hblank = true; } else if at_rhb { n_hblank = false; } } if rise && hphase == 1 { // the sync latch, three steps before H@2 if hcount == SHS { self.hsync = true; } else if 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. let (rsync_window, rsync_wait) = (self.rsync_window, self.rsync_wait); if address == RSYNC { self.rsync_window = 3; self.rsync_wait = 0; } else if rsync_window != 0 || rsync_wait != 0 { self.rsync_window = if rsync_window != 0 { rsync_window - 1 } else { 0 }; if rsync_window != 0 && !self.ph0 { self.rsync_wait = 6; } else { self.rsync_wait = if rsync_wait != 0 { rsync_wait - 1 } 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; } else if rsync_wait == 3 { self.cpu_divider = 0; } else { self.cpu_divider = if self.cpu_divider == 5 { 0 } 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). let (release_left, wsync_left) = (self.release_left, self.wsync_left); if release || release_left != 0 || address == WSYNC || wsync_left != 0 { let release_now = release || release_left != 0; let wsync_now = address == WSYNC || wsync_left != 0; self.release_left = if release { 7 } else if release_left != 0 { release_left - 1 } else { 0 }; self.wsync_left = if address == WSYNC { 2 } else if wsync_left != 0 { wsync_left - 1 } else { 0 }; if release_now && fall { self.rdy_low = false; } else if wsync_now && !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). let m_h1 = self.h1_history & 0x800 != 0; let m_h2 = self.h2_history & 0x800 != 0; let m_hmove = self.hmove_history & 0x800 != 0; let mut stuff: u8 = 0; let mut merge_now: u8 = 0; let count = self.motion_count; let mut still: u8 = 0; if m_h1 { let mut hit: u8 = 0; for (i, &hm) in self.hm_late[3].iter().enumerate() { let hm = hm as i32; 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 = 15; self.motion_more = 0x1F; self.motion_armed = true; self.motion_running = true; } else if m_h1 { self.motion_more = still; self.motion_armed = false; } else if m_h2 && !self.motion_armed && 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 = 15; self.motion_running = false; } else { self.motion_count = count - 1; } } let merge = self.merge_4; // Revision field (machine::TIARevision): on some consoles a merged pulse // swallows the next MOTCK without stepping the object first. let revision = self.revision; let 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). let n_hmove_latch = if h2 && self.hmove_history & 0xFF0 != 0 { // a write 5 to 12 steps ago true } else if shb { false } else { 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). let motck = rise && !hblank; let merged = self.merged; let object_motck: u8 = (if motck { 0x1F & !merged } else { 0 }) | merge_step; let object_clock: u8 = object_motck | stuff; self.merged = merge | if motck { 0 } else { merged }; // ---- objects: outputs from the present state (collisions, the pads) let need_pixels = fall || !hblank; let pixels = if need_pixels { self.object_pixels() } else { [false; 5] }; // a2600-rust-fast: `idle` when no object is struck or held (no RESxx // strobe lands, no counter holds a strobe, a window or a deferred pulse, // no RESMPx lock holds): then the object sections run their plain form, // `objects::`. `quiet` when, besides, no object is clocked and // neither player's NUSIZ is still settling: then each section's own skip // test holds for all five objects, so the sections are skipped whole. let idle = !(RESP0..=RESBL).contains(&address) && self.counters_idle() && !(self.resmp[0] && self.players[0].scan == 1 && !self.players[0].copy_flag) && !(self.resmp[1] && self.players[1].scan == 1 && !self.players[1].copy_flag); let quiet = idle && object_clock == 0 && self.players[0].size_history == (self.nusiz[0], self.nusiz[0]) && self.players[1].size_history == (self.nusiz[1], self.nusiz[1]); if !quiet { if idle { self.objects::(address, object_motck, object_clock, stuff, revision); } else { self.objects::(address, object_motck, object_clock, stuff, revision); } } // ---- 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). let pf_pixel = self.pf_shown && !hblank; if h1 { let mut index_next = if hcount == RHB { 0 } else if hcount == CNT { if self.ctrlpf & 1 != 0 { 19 } else { 0 } } else if self.pf_down { self.pf_index - 1 } else { self.pf_index + 1 }; if !(0..=19).contains(&index_next) { index_next = 0; } let (register, bit) = PF_BITS[index_next as usize]; self.pf_read = (self.pf[(register - PF0) as usize] >> bit) & 1 != 0; } if h2 { self.pf_shown = self.pf_read; if hcount == RHB { self.pf_index = 0; self.pf_down = false; } else if hcount == CNT { if self.ctrlpf & 1 != 0 { self.pf_index = 19; self.pf_down = true; } else { self.pf_index = 0; self.pf_down = false; } } else { self.pf_index += if self.pf_down { -1 } 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; } else if rise && !hblank && !self.vblank_latched { let [p0, p1, m0, m1, bl] = pixels; let pf = pf_pixel; if (p0 as u32 + p1 as u32 + m0 as u32 + m1 as u32 + bl as u32 + pf as u32) >= 2 { let b = |x: bool| x as u32; self.collisions |= b(m0 && p1) | b(m0 && p0) << 1 | b(m1 && p0) << 2 | b(m1 && p1) << 3 | b(p0 && pf) << 4 | b(p0 && bl) << 5 | b(p1 && pf) << 6 | b(p1 && bl) << 7 | b(m0 && pf) << 8 | b(m0 && bl) << 9 | b(m1 && pf) << 10 | b(m1 && bl) << 11 | b(bl && pf) << 12 | b(p0 && p1) << 13 | b(m0 && m1) << 14; } } // ---- 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 { for i in 0..5 { if merge_step & (0x10 >> i) == 0 { self.out_objects[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). self.out_colours = self.colours; if (COLUP0..=COLUBK).contains(&address) { self.out_colours[(address - COLUP0) as usize] = value; } self.out_score = self.ctrlpf & 2 != 0; self.out_priority = self.ctrlpf & 4 != 0; } if shb { self.score_right = false; } else if fall && hphase == 1 && 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 = self.vblank & 2 != 0; // ---- 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 != 0 { let fire = self.fire; let pads = (self.inputs >> 4) & !(fire[0] as u32 | (fire[1] as u32) << 1); self.trigger_latch &= pads; } else { self.trigger_latch = 0b11; } // ---- commit the rest self.rising = !rise; self.hcount = n_hcount; self.hphase = n_hphase; self.hblank = n_hblank; self.hmove_latch = n_hmove_latch; self.h1_history = ((self.h1_history << 1) | h1 as u32) & 0xFFF; self.h2_history = ((self.h2_history << 1) | h2 as u32) & 0xFFF; self.hmove_history = ((self.hmove_history << 1) | (address == HMOVE) as u32) & 0xFFF; if self.hm_settle < 4 { let late = self.hm_late; self.hm_late = [self.hm, late[0], late[1], late[2]]; self.hm_settle += 1; } self.merge_4 = self.merge_3; self.merge_3 = self.merge_2; self.merge_2 = self.merge_1; self.merge_1 = merge_now; if merge_step != 0 { // 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). let now = self.object_pixels(); for i in 0..5 { if merge_step & (0x10 >> i) != 0 { self.out_objects[i] = now[i]; } } } if WRITE { self.write_register(address, value); } if shb { if let Some(mut on_line) = self.on_line.take() { on_line(self); if self.on_line.is_none() { self.on_line = Some(on_line); } } 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 && hphase == 1 { if AUDIO_A.contains(&hcount) { self.audio.tick_a(); } else if AUDIO_B.contains(&hcount) { self.audio.tick_b(); } } // ---- pins, from the committed state. Priority and SCORE: DOC: SPG // CTRLPF; DIE: collisions, players, ball_score. let [c0, c1] = &self.audio.channels; self.au0 = if c0.pulse & 1 != 0 { c0.audv } else { 0 }; self.au1 = if c1.pulse & 1 != 0 { c1.audv } else { 0 }; self.ph0 = self.cpu_divider >= 3; self.sync_low = self.hsync != self.vsync; let blank = self.hblank || self.vblank_latched; self.blank = blank; let colour: u8 = if blank { 0 } else { let [p0q, p1q, m0q, m1q, blq] = self.out_objects; let [colup0, colup1, colupf, colubk] = self.out_colours; let pf_or_ball = self.pf_shown || blq; let pf_colour = if self.out_score && !self.out_priority { if self.score_right { colup1 } else { colup0 } } else { colupf }; if self.out_priority && pf_or_ball { pf_colour } else if p0q || m0q { colup0 } else if p1q || m1q { colup1 } else if self.pf_shown { pf_colour } else if blq { // SCORE colours the playfield only: the ball keeps COLUPF // (C32; DIE: ball_score; Alpha Beam with Ernie). colupf } else { colubk } }; self.col = colour >> 4; self.lum = (colour >> 1) & 7; if fall { self.pixels[((self.step_in_line >> 1) % 228) as usize] = if blank { 0 } else { (colour & 0xFE) | 1 }; } } /// No counter holds a strobe, a window or a deferred pulse (remembered /// in `counters_known_idle` until the counters' full form runs). fn counters_idle(&mut self) -> bool { if !self.counters_known_idle { self.counters_known_idle = self .counters .iter() .all(|c| c.strobe_left == 0 && c.window_history == 0 && !c.deferred); } self.counters_known_idle } /// The objects' sections of a step: ring events, players, missiles and the /// ball, then the object counters, from the present state (a2600-rust-fast /// moved them here from `step`, so a quiet step can skip them). /// /// `IDLE` (a2600-rust-fast): the caller found no RESxx strobe on this step /// and no counter holding a strobe, a window or a deferred pulse, and no /// RESMPx lock; then nothing is held or due, and the terms that test those /// are folded away (each marked `IDLE`). The rules are unchanged. fn objects( &mut self, address: i32, object_motck: u8, object_clock: u8, stuff: u8, revision: TIARevision, ) { // 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). let locks = if IDLE { [false; 5] } else { [ false, false, self.resmp[0] && self.players[0].scan == 1 && !self.players[0].copy_flag, self.resmp[1] && self.players[1].scan == 1 && !self.players[1].copy_flag, false, ] }; // Ring events, from the present counter state: // (clocked, H@1 ends, H@2, held, ring). let mut events = [(false, false, false, false, 0i32); 5]; for (i, event) in events.iter_mut().enumerate() { let c = &self.counters[i]; let clocked = object_clock & (0x10 >> i) != 0; let held = !IDLE && ((c.window_history & 4) != 0 || locks[i]); let ring = c.ring; let due = !IDLE && c.deferred && c.window_history == 0 && c.strobe_left == 0; let ring_clock = (clocked || due) && !held; *event = (clocked, ring_clock && ring == 1, ring_clock && ring == 2, held, ring); } // ---- players for i in 0..2 { let (clocked, o_h1_end, o_h2, held, ring) = events[i]; let nusiz = self.nusiz[i]; let count_i = self.counters[i].count; let p = &mut self.players[i]; let (size1, size2) = p.size_history; if !clocked && !o_h1_end && size1 == nusiz && size2 == nusiz && object_motck & (0x10 >> i) == 0 { continue; } let mut start_decode = false; if o_h1_end { start_decode = count_i == MAIN || copies(nusiz, count_i); if start_decode && count_i != MAIN { p.copy_flag = true; } } if o_h2 && count_i == MAIN { p.copy_flag = false; } let (old_gate, old_q, old_q2) = (p.gate, p.start_q, p.start_q2); if clocked || object_motck & (0x10 >> i) != 0 { // 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 = held || ring != 3; } else if size2 == 0b101 { p.gate = !(held || ring == 1 || ring == 3); } else { p.gate = false; } } if clocked { let start_pulse = if nusiz == 0b101 || nusiz == 0b111 { old_q2 } else { old_q }; p.start_q = o_h2 && 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 && !old_gate { p.scan = 0; p.scanning = true; } else if !old_gate && 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 0..2 { let (_, o_h1_end, o_h2, _, _) = events[2 + j]; if o_h1_end { let count_m = self.counters[2 + j].count; self.missiles[j].start_latched = count_m == MAIN || copies(self.nusiz[j], count_m); } else if o_h2 { let m = &mut self.missiles[j]; m.second = m.first; m.first = m.start_latched; } } if events[4].2 { let clear_pending = self.counters[4].clear_pending; let ball = &mut self.ball; ball.second = ball.first; ball.first = clear_pending; } // ---- object counters (after the players, missiles and ball read them) for i in 0..5 { let c = &mut self.counters[i]; let strobe = !IDLE && address == RESP0 + i as i32; let (clocked, o_h1_end, o_h2, held, ring) = events[i]; if IDLE && !clocked { continue; // IDLE: no strobe, window, hold or deferred pulse } if !(clocked || strobe || c.strobe_left != 0 || c.window_history != 0 || held || c.deferred) { continue; } if o_h1_end { c.clear_pending = c.pending || c.count == MAIN || c.count == LFSR_ERROR; } if o_h2 { c.count = if c.clear_pending { 0 } 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`). let due = !IDLE && c.deferred && c.window_history == 0 && c.strobe_left == 0 && !strobe; c.ring = if held { 1 } else if (clocked || due) && !held { (ring + 1) & 3 } else { ring }; let bit: u8 = 0x10 >> i; // IDLE: no strobe or hold to defer a pulse into, nothing due if !IDLE { if stuff & bit != 0 && ((c.strobe_left != 0 && revision.strobe_drops & bit == 0) || held) { c.deferred = true; } else if due { c.deferred = false; } } c.pending = if held { true } else if o_h2 { false } else { c.pending }; // IDLE: no strobe, so strobe_left and the window history stay 0 if !IDLE { let window = strobe || c.strobe_left != 0; c.strobe_left = if strobe { 2 } else if c.strobe_left != 0 { c.strobe_left - 1 } else { 0 }; c.window_history = ((c.window_history << 1) | window as i32) & 0b111; } } if !IDLE { self.counters_known_idle = false; // the full form may have set a strobe, a window or a deferral } } /// Each object's output as the present state gives it (`_pixels`). fn object_pixels(&self) -> [bool; 5] { let mut out = [false; 5]; // a2600-rust-fast: a player shows nothing unless its scan counter runs, a // missile or the ball nothing outside its START count (`width_active` // needs `first` or `second`), so with none of those every output is off. let [p0, p1] = &self.players; let [m0, m1] = &self.missiles; let ball = &self.ball; if !(p0.scanning || p1.scanning || m0.first || m0.second || m1.first || m1.second || ball.first || ball.second) { return out; } for (i, p) in self.players.iter().enumerate() { let grp = if self.vdelp[i] { self.grp_old[i] } else { self.grp_new[i] }; let bit = if self.reflect[i] { p.scan } else { 7 - p.scan }; out[i] = p.scanning && (grp >> bit) & 1 != 0; } for (j, m) in self.missiles.iter().enumerate() { let ring = self.counters[2 + j].ring; out[2 + j] = width_active(m, self.missile_size[j], ring) && self.enam[j] && !self.resmp[j]; } let enabl = if self.vdelbl { self.enabl_old } else { self.enabl_new }; out[4] = width_active(&self.ball, (self.ctrlpf >> 4) & 3, self.counters[4].ring) && enabl; out } /// The register map and bit meanings: DOC: SPG; GRP/ENABL's VDEL copies /// DOC: SPG, DIE: vdel, grp_mid_draw (C30). fn write_register(&mut self, address: i32, value: u8) { self.registers[address as usize] = value; if address == VSYNC { let on = value & 0x02 != 0; if on && !self.vsync { self.frame += 1; if let Some(on_vsync) = self.on_vsync.as_mut() { on_vsync(self.frame); } } self.vsync = on; } else if address == VBLANK { if self.vblank & 0x80 != 0 && value & 0x80 == 0 { self.dump_released = self.now(); } self.vblank = value; } else if address == NUSIZ0 || address == NUSIZ1 { let i = (address - NUSIZ0) as usize; self.nusiz[i] = value & 7; self.missile_size[i] = (value >> 4) & 3; } else if (COLUP0..=COLUBK).contains(&address) { self.colours[(address - COLUP0) as usize] = value; } else if address == CTRLPF { self.ctrlpf = value; } else if address == REFP0 || address == REFP1 { self.reflect[(address - REFP0) as usize] = value & 0x08 != 0; } else if address == PF0 || address == PF1 || address == PF2 { self.pf[(address - PF0) as usize] = value; } else if address == GRP0 { self.grp_new[0] = value; self.grp_old[1] = self.grp_new[1]; } else if address == GRP1 { self.grp_new[1] = value; self.grp_old[0] = self.grp_new[0]; self.enabl_old = self.enabl_new; } else if address == ENAM0 || address == ENAM1 { self.enam[(address - ENAM0) as usize] = value & 0x02 != 0; } else if address == ENABL { self.enabl_new = value & 0x02 != 0; } else if (HMP0..=HMBL).contains(&address) { self.hm[(address - HMP0) as usize] = value >> 4; self.hm_settle = 0; } else if address == VDELP0 || address == VDELP1 { self.vdelp[(address - VDELP0) as usize] = value & 1 != 0; } else if address == VDELBL { self.vdelbl = value & 1 != 0; } else if address == RESMP0 || address == RESMP1 { self.resmp[(address - RESMP0) as usize] = value & 0x02 != 0; } else if address == HMCLR { self.hm = [0, 0, 0, 0, 0]; self.hm_settle = 0; } else if (AUDC0..=AUDV1).contains(&address) { self.audio.write(address as u8, value); } } // -- reads ---------------------------------------------------------------- /// 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). pub fn read(&mut self, address: u16) -> u8 { let address = (address & 0x0F) as u32; if address < 8 { let (d7_bit, d6_bit) = COLLISION_READS[address as usize]; let c = self.collisions; let d6 = match d6_bit { None => 0, Some(bit) => (c >> bit) & 1, }; return (((c >> d7_bit) & 1) << 7 | d6 << 6) as u8; } let inputs = match self.pad_source.take() { None => self.inputs, Some(mut source) => { let levels = source(self); if self.pad_source.is_none() { self.pad_source = Some(source); } levels } }; if address < 12 { return if self.vblank & 0x80 != 0 { 0 } else { (((inputs >> (address - 8)) & 1) << 7) as u8 }; } if address < 14 { let i = (address - 12) as usize; let mut pad = if self.fire[i] { 0 } else { (inputs >> (4 + i)) & 1 }; if self.vblank & 0x40 != 0 { pad &= self.trigger_latch >> i; } return ((pad & 1) << 7) as u8; } 0 } }