"""The TMS9918A family video display processor. One engine, the parts as data (``variants.py``), the manual's tables as data (``tables.py``). The chip is stepped one memory cycle (4 master clocks) at a time; each cycle does what TI's 1978 timing drawing says that cycle of the line does (a name, colour or pattern fetch, a sprite fetch, a refresh, or a CPU window), so pictures are built from the bytes fetched at their cycles and CPU accesses wait for windows. Source tags as in ``docs/chip.md`` and ``tables.py``. Every behaviour no source settles is a named keyword with its default recorded in ``docs/claims.md``. """ from __future__ import annotations from tms9918_python import tables as T from tms9918_python.frame import Frame from tms9918_python.variants import TMS9928A, VDPVariant _READ = 1 _WRITE = 2 class TMS9918: """A TMS9918A, TMS9928A or TMS9929A with ``vram_size`` bytes of DRAM. The host owns time: it calls :meth:`run` with master clocks up to the moment of each port access, then :meth:`read` or :meth:`write`. See ``docs/api.md``. Keywords (defaults in ``docs/claims.md``): - ``windows``: CPU accesses wait for the schedule's access windows (True), or are served the moment they are made (False: the model of MAME and sms-python, for detector comparisons). - ``lost_access``: what a second access does while the first still waits for a window (U3). ``"newer"``: its byte and address replace the first's in the one waiting request, which keeps its time (the first's memory cycle never happens). ``"restart"``: the same, but the VDP delay starts again from the second access. ``"older"``: the second is dropped. Every rule counts every CPU access in the address register. - ``roll_over_4k``: the address counter wraps within 4K in 4K mode (C11). - ``mux_4k``: 4K mode changes the DRAM row/column mapping (MacDonald; C11). With both C11 keywords False, R1 bit 7 does nothing, as in MAME and sms-python. - ``offscreen_collisions``: sprite pixels outside the 256 visible columns collide (TI 2.3.2; C7). False tests the visible columns only, as MAME does. - ``flag_dot``: (line, dot) at which F sets (C10). Default TI's wording, the end of line 191's active pixels. ``(193, 10)`` is MAME 0.285's point. - ``status_race``: a status read within ``race_window`` master clocks of F setting returns F = 0 and the frame's F is lost (U8). Off by default. - ``power_on_vram``: the DRAM's contents at power-on (U4); zeros if None. - ``power_on_status``: the status register at power-on (U4); 0. MAME starts with the number at 31. (TI 2.3.2 says C is not cleared by power-on; F and 5S are then cleared by the reset that follows.) """ def __init__( self, variant: VDPVariant = TMS9928A, vram_size: int = 16384, *, windows: bool = True, lost_access: str = "newer", roll_over_4k: bool = True, mux_4k: bool = True, offscreen_collisions: bool = True, flag_dot: tuple[int, int] = (191, 266), status_race: bool = False, race_window: int = 8, power_on_vram: bytes | None = None, power_on_status: int = 0, ) -> None: if vram_size not in (4096, 8192, 16384): raise ValueError(f"vram_size must be 4096, 8192 or 16384, not {vram_size}") if lost_access not in ("newer", "restart", "older"): raise ValueError(f"lost_access must be newer, restart or older: {lost_access!r}") if flag_dot[1] % 2: raise ValueError("flag_dot's dot must be even (a memory-cycle boundary)") self.variant = variant self.vram_size = vram_size self.windows = windows self.lost_access = lost_access self.roll_over_4k = roll_over_4k self.mux_4k = mux_4k self.offscreen_collisions = offscreen_collisions self.flag_dot = flag_dot self.status_race = status_race self.race_window = race_window self._lines = variant.layout.lines self._flag_line, self._flag_slot = flag_dot[0], flag_dot[1] // 2 # Power-on state (U4): registers, status and the address register zero. if power_on_vram is None: self.vram = bytearray(vram_size) else: if len(power_on_vram) != vram_size: raise ValueError("power_on_vram must be vram_size bytes") self.vram = bytearray(power_on_vram) self.regs = [0] * 8 self.status = power_on_status & 0xFF self.addr = 0 self.read_ahead = 0 self.lost_accesses = 0 # CPU accesses whose memory cycle never happened self.frame_count = 0 self.clock = 0 # master clocks since power-on, at the start of the current slot self._phase = 0 # master clocks into the current slot (0-3) self._f_clock = -(1 << 60) # when F last set (for the race window) self._frame: Frame | None = None self.reset() # ------------------------------------------------------------------ host surface def reset(self) -> None: """/RESET [TI 2.1.7]: clears R0 and R1, F (and C, 5S) [TI 2.3.1-2.3.3], and sets the counters to "known states" (U4: line 0, dot 0 here). The first-byte flip-flop and the read-ahead are cleared too (U2, provisional). VRAM is left alone.""" self.regs[0] = 0 self.regs[1] = 0 self.status &= T.STATUS_NUMBER self.read_ahead = 0 self._first = 0 # the first control byte self._second = False # the flip-flop: the next control byte is the second self._pending = 0 # 0, _READ or _WRITE: an access waiting for a window self._pending_addr = 0 self._pending_value = 0 self._pending_ready = 0 self._suppress_f = False # Sprite pre-processing (the 32 vertical checks for the line ahead). self._eval_target = -1 self._eval_done = True self._eval_found: list[int] = [] # Sprite processing (attributes and patterns of up to four sprites). self._fetch_target = -1 self._fetch_count = 0 self._fetch = [[0, 0, 0, 0, 0, 0] for _ in range(4)] # row, x, name, tag, p1, p2 self._sprite_colours = bytes(256) self._collision_slot = 1 << 30 # Picture. self._rows = [bytes(256)] * 192 self._border = [0] * self._lines self._row = bytearray(256) self._name = 0 self._colour = 0 self.line = 0 self.slot = 0 self._phase = 0 self._begin_line(0, new_frame=False) self._do_slot(0) @property def dot(self) -> int: """Pixel clocks into the line (0-341), counted as in ``tables.py``.""" return self.slot * 2 + self._phase // 2 @property def int_line(self) -> bool: """/INT asserted: F and IE both 1 [TI 2.1.6, 2.3.1]. A level.""" return bool(self.status & T.STATUS_F and self.regs[1] & T.R1_IE) @property def lines(self) -> int: return self._lines def take_frame(self) -> Frame | None: """The most recent finished frame, once; None until another finishes.""" frame, self._frame = self._frame, None return frame def run(self, master_clocks: int) -> None: """Advance ``master_clocks`` master clocks (XTAL periods).""" if master_clocks < 0: raise ValueError("time runs forward") phase = self._phase + master_clocks while phase >= T.MASTER_PER_SLOT: phase -= T.MASTER_PER_SLOT self.clock += T.MASTER_PER_SLOT slot = self.slot + 1 if slot == T.SLOTS_PER_LINE: slot = 0 line = self.line + 1 if line == self._lines: line = 0 self._end_line() self.slot = 0 self._begin_line(line, new_frame=line == 0) else: self.slot = slot self._do_slot(slot) self._phase = phase def write(self, mode: int, value: int) -> None: """A CPU write: ``mode`` is the MODE pin (0 data, 1 control) [TI 2.1, table 2-1].""" value &= 0xFF if mode & 1: if not self._second: # First byte. U1: it goes into the address register's low byte at once # (MAME, sms-python; no hardware source). self._first = value self._second = True self.addr = (self.addr & 0x3F00) | value return self._second = False # The second byte sets the address in every case; "The CPU address is # destroyed by writing to the VDP register" [TI 2.1.2 note]. self.addr = (value & 0x3F) << 8 | self._first if value & 0x80: # Register write; bits 6-3 "don't care" [Young 2.2]. reg = value & 7 self.regs[reg] = self._first & T.REGISTER_MASKS[reg] elif not value & 0x40: # Address setup for reading starts a VRAM read [TI 2.1.5; Young 2.1]. self._request(_READ, 0) else: # Any data-port access clears the flip-flop [Young 2.3]. # The byte also replaces the read-ahead [Young 2.1]. self.read_ahead = value self._request(_WRITE, value) def read(self, mode: int) -> int: """A CPU read: ``mode`` 0 returns the read-ahead byte, 1 the status register.""" self._second = False if mode & 1: value = self.status if self.status_race and self._in_race_window(): value &= ~T.STATUS_F # A status read clears F, 5S and C (TI 2.3; C1); the number stays. self.status &= T.STATUS_NUMBER return value value = self.read_ahead self._request(_READ, 0) return value # ------------------------------------------------------------------ CPU accesses def _request(self, kind: int, value: int) -> None: """A VRAM access from the CPU. The address register counts it at once; the memory cycle happens at the first window ``access_delay`` master clocks or more later.""" addr = self.addr self.addr = T.increment_address(addr, self._mode_16k(), self.roll_over_4k) if not self.windows: self._memory_cycle(kind, addr, value) return now = self.clock + self._phase if self._pending: self.lost_accesses += 1 if self.lost_access == "older": return # the waiting access keeps its place; this one is dropped if self.lost_access == "newer": # One request, one data register: the new byte and address replace the # old, and the request already waiting keeps its time. self._pending = kind self._pending_addr = addr self._pending_value = value return # "restart": as "newer", but the VDP delay starts again from this access. self._pending = kind self._pending_addr = addr self._pending_value = value self._pending_ready = now + self.variant.access_delay def _memory_cycle(self, kind: int, addr: int, value: int) -> None: cell = T.dram_address(addr, self._mux_16k(), self.vram_size) if kind == _WRITE: self.vram[cell] = value else: self.read_ahead = self.vram[cell] def _mode_16k(self) -> bool: """R1 bit 7 as the address counter sees it (always 16K on a part without it).""" return bool(self.regs[1] & T.R1_16K) or not self.variant.has_4k_select def _mux_16k(self) -> bool: """R1 bit 7 as the DRAM address multiplexer sees it.""" return self._mode_16k() or not self.mux_4k def _vram(self, addr: int) -> int: """A display fetch at VDP address ``addr`` (through the 4K/16K mapping).""" return self.vram[T.dram_address(addr, self._mux_16k(), self.vram_size)] # ------------------------------------------------------------------ status race def _in_race_window(self) -> bool: """U8: is now within ``race_window`` master clocks of F setting? A read just before the set also cancels it (the set is lost).""" now = self.clock + self._phase if 0 <= now - self._f_clock <= self.race_window: return True until = self._clocks_until(self._flag_line, self._flag_slot) if 0 < until <= self.race_window: self._suppress_f = True return True return False def _clocks_until(self, line: int, slot: int) -> int: here = self.line * T.SLOTS_PER_LINE + self.slot there = line * T.SLOTS_PER_LINE + slot frame = self._lines * T.SLOTS_PER_LINE return ((there - here) % frame) * T.MASTER_PER_SLOT - self._phase # ------------------------------------------------------------------ lines def _begin_line(self, line: int, new_frame: bool) -> None: """Choose the line's schedule and get its picture state ready.""" if new_frame: self._frame = Frame(tuple(self._rows), tuple(self._border), self.frame_count) self.frame_count += 1 self.line = line regs = self.regs self._border[line] = regs[7] & 0x0F mode = T.mode_of(regs[0], regs[1], self.variant.graphics2) self._line_mode = mode shown = bool(regs[1] & T.R1_BLANK) last = self._lines - 1 # Lines that run the display schedule: the active lines and the one before them # (its sprite processing serves line 0). [1978] places the sprite fetches in the # line before; that this line is the one before line 0 is the core's reading # (docs/schedule.md), provisional. fetching = shown and (line < 192 or line == last) nxt = 0 if line == last else line + 1 next_fetching = shown and (nxt < 192 or nxt == last) sprites = not T.is_text_like(mode) kind = T.line_kind(mode) if fetching else "refresh" self._schedule = T.SCHEDULES[(kind, next_fetching and sprites and kind != "text")] self._sprite_line = fetching and sprites self._render = line < 192 and shown # pattern fetches build this line's pixels self._collision_slot = 1 << 30 if line < 192: backdrop = regs[7] & 0x0F self._row[:] = bytes((backdrop,)) * 256 self._sprite_colours = bytes(256) if self._render and sprites and self._fetch_target == line: self._build_sprite_line() self._fetch_target = -1 # used up (or stale): this line's fetches set it anew if self._sprite_line and self._eval_target != (line + 1) % self._lines: # The early checks did not run (the line before was not a sprite line, e.g. # the display was turned on during it): no evaluation for the next line, so # no sprites on it and no 5S from it. Provisional. self._start_evaluation((line + 1) % self._lines) self._eval_done = True def _end_line(self) -> None: if self.line < 192: self._rows[self.line] = bytes(self._row) # ------------------------------------------------------------------ the memory cycle def _do_slot(self, slot: int) -> None: kind, arg = self._schedule[slot] line = self.line if line == self._flag_line and slot == self._flag_slot: if self._suppress_f: self._suppress_f = False else: self.status |= T.STATUS_F self._f_clock = self.clock if slot >= self._collision_slot: self.status |= T.STATUS_C self._collision_slot = 1 << 30 if kind == T.CPU: if self._pending and self._pending_ready <= self.clock: self._memory_cycle(self._pending, self._pending_addr, self._pending_value) self._pending = 0 elif kind == T.NAME: if self._render: self._name = self._vram(T.name_address(self.regs[2], line, arg)) elif kind == T.COLOUR: if self._render: self._fetch_colour(line) elif kind == T.PATTERN: if self._render: self._draw_group(line, arg) elif kind == T.SPRITE_Y: self._check_sprite(slot, arg) elif kind == T.TEXT_NAME: if self._render and self._line_mode in (T.TEXT, T.TEXT_GRAPHICS_II): self._name = self._vram(T.text_name_address(self.regs[2], line, arg)) elif kind == T.TEXT_PATTERN: if self._render: self._draw_text(line, arg) elif kind == T.REFRESH: pass else: self._sprite_fetch(kind, arg) def _fetch_colour(self, line: int) -> None: regs = self.regs if self._line_mode == T.GRAPHICS_II: char = (line >> 6) << 8 | self._name addr = T.graphics2_colour_address( regs[3], regs[4], char, line, self.variant.colour_mask_masks_patterns ) else: addr = T.graphics1_colour_address(regs[3], self._name) self._colour = self._vram(addr) def _draw_group(self, line: int, column: int) -> None: """The pattern fetch of an 8-pixel group, then its eight pixels [TI 2.4.1-2.4.3].""" regs = self.regs mode = self._line_mode name = self._name gate = self.variant.colour_mask_masks_patterns if mode == T.GRAPHICS_I: pattern = self._vram(T.graphics1_pattern_address(regs[4], name, line)) elif mode == T.GRAPHICS_II: char = (line >> 6) << 8 | name pattern = self._vram( T.graphics2_pattern_address(regs[3], regs[4], char, line & 7, gate) ) elif mode == T.MULTICOLOR: pattern = self._vram(T.multicolor_pattern_address(regs[4], name, line)) else: # Multicolor + Graphics II [Young 3.6] char = (line >> 6) << 8 | name pattern = self._vram( T.graphics2_pattern_address(regs[3], regs[4], char, (line >> 2) & 7, gate) ) backdrop = regs[7] & 0x0F x = column << 3 row = self._row sprites = self._sprite_colours if mode & 2: # Multicolor: the byte is two 4-pixel blocks, high nibble on the left [TI 2.4.3]. left, right = pattern >> 4, pattern & 0x0F colours = (left or backdrop,) * 4 + (right or backdrop,) * 4 else: fg = self._colour >> 4 or backdrop bg = self._colour & 0x0F or backdrop colours = tuple(fg if pattern & (0x80 >> i) else bg for i in range(8)) for i in range(8): row[x + i] = sprites[x + i] or colours[i] def _draw_text(self, line: int, column: int) -> None: """Text mode's 6-pixel character [TI 2.4.4]; the table-less modes' bars [Young 3.7].""" regs = self.regs backdrop = regs[7] & 0x0F fg = regs[7] >> 4 or backdrop mode = self._line_mode if mode == T.TEXT: pattern = self._vram(T.graphics1_pattern_address(regs[4], self._name, line)) elif mode == T.TEXT_GRAPHICS_II: char = (line >> 6) << 8 | self._name pattern = self._vram( T.graphics2_pattern_address( regs[3], regs[4], char, line & 7, self.variant.colour_mask_masks_patterns ) ) else: pattern = 0xF0 # "4 pixels TC, 2 pixels BD" [Young 3.7] x = T.TEXT_LEFT + column * 6 row = self._row for i in range(6): row[x + i] = fg if pattern & (0x80 >> i) else backdrop # ------------------------------------------------------------------ sprites def _start_evaluation(self, target: int) -> None: self._eval_target = target self._eval_done = False self._eval_found = [] def _check_sprite(self, slot: int, sprite: int) -> None: """One vertical check of sprite pre-processing [1978 "VERT ATT. ADDRESS SELECT"; TI 2.3.2-2.3.3, 2.4.5; Young 4.1-4.3].""" if slot >= T.EARLY_Y_SLOTS.start: if sprite == 0: self._start_evaluation((self.line + 2) % self._lines) if self._eval_done: return regs = self.regs y = self._vram(T.sprite_attribute_address(regs[5], sprite, 0)) status = self.status if y == 0xD0: # "Sprites beyond the Sprite Attribute Table terminator (D0) are not # considered" [TI 2.3.2]; the number shows the terminator [Young 4.3]. self._eval_done = True if not status & T.STATUS_5S: self.status = (status & ~T.STATUS_NUMBER) | sprite return height = (16 if regs[1] & T.R1_SIZE else 8) << (regs[1] & T.R1_MAG) top = y - 256 if y > 0xE0 else y # E1-FF bleed in from the top [TI 2.4.5] dy = self._eval_target - top - 1 if 0 <= dy < height: if len(self._eval_found) < 4: self._eval_found.append(sprite) else: # The fifth sprite on the line [TI 2.3.3]: 5S only while F = 0; the number # is the fifth sprite's (C6: the data manual). self._eval_done = True if not status & T.STATUS_5S: status = (status & ~T.STATUS_NUMBER) | sprite if not status & T.STATUS_F: status |= T.STATUS_5S self.status = status return if sprite == 31: self._eval_done = True if not status & T.STATUS_5S: self.status = (status & ~T.STATUS_NUMBER) | 31 def _sprite_fetch(self, kind: int, k: int) -> None: """Sprite processing for the k-th sprite found [1978 rows DDYY-RRYY]: attribute bytes V, H, N, T, then the pattern bytes P1 and P2, for the next line.""" if not self._sprite_line: return if kind == T.SPRITE_V and k == 0: self._fetch_target = self._eval_target self._fetch_count = len(self._eval_found) if k >= self._fetch_count or self._fetch_target != (self.line + 1) % self._lines: return regs = self.regs sprite = self._eval_found[k] entry = self._fetch[k] size16 = bool(regs[1] & T.R1_SIZE) if kind == T.SPRITE_V: y = self._vram(T.sprite_attribute_address(regs[5], sprite, 0)) top = y - 256 if y > 0xE0 else y entry[0] = ((self._fetch_target - top - 1) >> (regs[1] & T.R1_MAG)) & 0x0F elif kind == T.SPRITE_H: entry[1] = self._vram(T.sprite_attribute_address(regs[5], sprite, 1)) elif kind == T.SPRITE_N: entry[2] = self._vram(T.sprite_attribute_address(regs[5], sprite, 2)) elif kind == T.SPRITE_T: entry[3] = self._vram(T.sprite_attribute_address(regs[5], sprite, 3)) elif kind == T.SPRITE_P1: entry[4] = self._vram(T.sprite_pattern_address(regs[6], entry[2], size16, entry[0])) elif kind == T.SPRITE_P2: if size16: addr = T.sprite_pattern_address(regs[6], entry[2], True, entry[0]) + 16 entry[5] = self._vram(addr) else: entry[5] = 0 def _build_sprite_line(self) -> None: """The line's sprite plane from the bytes fetched during the line before: colours per visible column (the lowest-numbered non-transparent sprite wins [TI 2.4]) and the first pixel where two sprites have a 1 (C [TI 2.3.2]).""" regs = self.regs size16 = bool(regs[1] & T.R1_SIZE) mag = regs[1] & T.R1_MAG width = 16 if size16 else 8 colours = bytearray(256) cover = bytearray(256 + 64) # columns -32 .. 287 first_hit = None for k in range(self._fetch_count): _, x, _, tag, p1, p2 = self._fetch[k] if tag & 0x80: x -= 32 # early clock [TI 2.4.5] colour = tag & 0x0F bits = p1 << 8 | p2 if size16 else p1 << 8 for b in range(width): if not bits & (0x8000 >> b): continue for m in range(1 + mag): px = x + (b << mag) + m if cover[px + 32]: if first_hit is None or px < first_hit: if self.offscreen_collisions or 0 <= px < 256: first_hit = px cover[px + 32] = 1 if 0 <= px < 256 and colour and not colours[px]: colours[px] = colour self._sprite_colours = bytes(colours) if first_hit is not None: # C is set "during the generation of the pixel" [TI 2.3.2]: at the dot the # pixel is shown (provisional, U10). self._collision_slot = max(0, first_hit + T.DISPLAY_START_DOT) // 2