# SPDX-License-Identifier: MIT """The 32X VDP (315-5781): registers, palette, frame-buffer control, auto fill, the line timing its status bits and interrupts follow, and its own picture (milestone 3, docs/handoff-brief.md). Each row is the 32X's alone, 320 pixels wide whatever the Mega Drive's mode; ``composite.py`` (milestone 4) lays it over the Mega Drive's line. **Where its time comes from.** The 32X VDP has no clock of its own: it takes the Mega Drive's EDCLK, HSYNC and VSYNC off the cartridge slot (service manual ``A408a``, IC6 pins 64-69). Here that is socket 6: one :class:`~megadrive_python.sockets.VideoLine` per Mega Drive line, each pixel's start in master clocks. From each record the VDP places, in dots of that line (so EDCLK's slow pixels around HSYNC count as one dot each, as the Manual's 100 dots = 860 MCLK does): ======================== ============================================================== HBLANK rises 12 dots before the Mega Drive's HBlank flag sets (H40 H $15A), 23 before EDCLK's first slow dot (HSYNC): the one place where the Manual's four spans below come out in its own MCLK figures (``Quirks.hblank_phase``). In H32 the same 23 EDCLK dots before HSYNC: EDCLK keeps H40's dots there (``Quirks.edclk_h32``) PEN rises 3 dots after HBLANK (Manual 3.3, figure 3.17, A) FEN refresh pulse 40 Sclk from HBLANK (figure 3.17, B; ``Quirks.fen_refresh``) register latch 76 dots after HBLANK (figure 3.17, C) HBLANK falls, display 100 dots after HBLANK (figure 3.15, A = 100 dots, B = 320) VBLANK edges 27 dots after HBLANK, on the HBLANK that follows the last display line (rise) and on the one before line 0 (fall) (figure 3.15, C; ``Quirks.vblank_after_hblank``) ======================== ============================================================== The HBLANK that precedes display row ``n`` lies in the Mega Drive line whose V counter is ``n``: H40's V counter steps at H $14A, so H $15A comes 16 dots into that record, and the display it opens runs from H $01A to H $159. That window opens over the Mega Drive's own output pixel 0, as Sega's H/W Information says the two pictures lie, within half a dot (``Quirks.composite_alignment``). In H32 HBLANK rises 184 MCLK into the record (HSYNC at 368, provisional: ``Quirks.edclk_h32``). Rows count from the Mega Drive's V counter; there are 224, or 240 with the 240 bit on a PAL console (Manual 3.3: blank periods of 38, 89 and 73 lines). **Events.** The status bits (VBLK, HBLK, PEN, FEN) are computed from the line records at the clock they are read. Everything that changes state is an event at its master clock, run in order with the SH-2s' instructions (``SH2Side.catch_up``) or up to a 68000 access (``Sega32X.catch_up``): HINT at HBLANK and the H counter's reload when it falls, the register latch, a row drawn when its display starts, VINT and the FS swap at VBLANK. **The picture.** Rows of 320 words: BGR555 with the through bit (bit 15), as the palette or the direct-colour pixel gives it, or None for a blank-mode row (Manual 3.3: "when the 32X designates blank ... [it] becomes transparent"). :meth:`frame_rgb` gives RGB888 for a PNG. Every choice a source does not fix is a :class:`~sega32x_python.machine.Quirk`. """ from __future__ import annotations import functools import heapq import struct from typing import TYPE_CHECKING if TYPE_CHECKING: from megadrive_python.sockets import VideoLine from .machine import Quirks from .slot import Sega32X #: Frame buffer: 1 Mbit, 64K words (Manual 2.1); the line table is its first 256 words. WORDS = 0x10000 WIDTH = 320 #: Event kinds, in the order two at the same clock run. RISE, PEN_RISE, LATCH, FALL, VBLANK_ON, VBLANK_OFF = range(6) _DIRECT = struct.Struct(">320H") _FAR = 1 << 62 #: EDCLK's 33 slow dots from HSYNC, in MCLK: four runs of 15 EDCLK cycles of 5 MCLK, one #: 8-MCLK dot apart, paired two cycles to a dot -- the H40 line's $1CD-$1ED as #: megadrive-python has them; in H32 taken the same (EDCLK is made outside the VDP: #: ``Quirks.edclk_h32``). _SLOW_DOTS = (10,) * 7 + (9, 9) + (10,) * 7 + (8,) + (10,) * 7 + (9, 9) + (10,) * 7 #: The H40 HBlank flag ($166) lies this many dots before EDCLK's first slow dot ($1CD), so #: ``Quirks.hblank_phase`` (dots before the flag) + this = dots before the slow run. _FLAG_TO_SLOW = 11 @functools.cache def edclk_dots(slow: int, length: int) -> tuple[tuple[int, ...], int]: """EDCLK's dot starts over a line of ``length`` MCLK whose slow run starts ``slow`` MCLK in, 8 MCLK apart elsewhere (the first at or after 0), and the slow run's index.""" dots = list(range(slow % 8, slow, 8)) first = len(dots) t = slow for width in _SLOW_DOTS: dots.append(t) t += width dots.extend(range(t, length, 8)) return tuple(dots), first class LineTiming: """One Mega Drive line as the 32X VDP sees it: its edges in master clocks.""" __slots__ = ( "cancelled", "end", "fall", "latch", "pal", "pen_rise", "published", "refresh_end", "rise", "start", "v", "vedge", ) def __init__(self, line: VideoLine, q: Quirks) -> None: start = line.start pixels = line.pixels self.start = start self.end = start + line.length self.v = line.v self.pal = line.pal self.published = line.published self.cancelled = False dots = q.hblank_phase.value # dots before the H40 flag (negative: after) if line.hmode == "H40": # The Mega Drive's HBlank flag sets at pixel k of the record ($166); socket 6's # H40 pixels are EDCLK's dots. offset = line.hblank_set - start k = 0 while k < len(pixels) and pixels[k] < offset: k += 1 rise_dot = k - dots else: # H32: the record's pixels are the Mega Drive's 10-MCLK dots, but EDCLK, which # the 32X counts, keeps H40's dots and slow run, from HSYNC (Quirks.edclk_h32). pixels, slow = edclk_dots(q.edclk_h32.value, line.length) rise_dot = slow - dots - _FLAG_TO_SLOW last = len(pixels) - 1 def at(dot: int) -> int: if dot <= last: return start + pixels[dot] return start + line.length + (dot - last - 1) * 8 # past the record: 8 MCLK dots timings = q.hblank_timing.value self.rise = at(rise_dot) self.pen_rise = at(rise_dot + timings["pen"]) self.latch = at(rise_dot + timings["latch"]) self.fall = at(rise_dot + timings["blank"]) self.vedge = at(rise_dot + q.vblank_after_hblank.value) self.refresh_end = self.rise + q.fen_refresh.value * 7 // 3 class VDP32X: """The 32X VDP that both CPUs reach (``$A15180``/``$20004100``) and its picture.""" def __init__(self, device: Sega32X) -> None: self.device = device self.framebuffers = device.framebuffers q = device.machine.quirks self.quirks = q self.bitmap_writable = q.bitmap_bits.value self.reset() def reset(self) -> None: # The registers as written (and read back: Manual 3.2.3 gives no read delay, and # the Mars Check Program's register tests poll until a written mode reads back). self.bitmap = 0 self.shift = 0 self.fill_length = 0 self.fill_start = 0 self.fill_data = 0 #: As the display circuit latched them, 76 dots after HBLANK (Manual 3.3). self.latched_mode = 0 self.latched_pri = 0 self.latched_shift = 0 self.latched_240 = 0 #: FS: the frame buffer displayed; the CPUs reach the other one (Manual 3.1). self.fs = 0 self.fs_pending: int | None = None self.palette = [0] * 256 self.ntsc = True #: The end of the auto fill under way (master clocks), for FEN. self.fill_end = -1 #: The H interrupt's internal counter and whether HBLANK's fall reloads it. self.hint_counter = 0 self.hint_reload = False self.vblank = True #: Line records still needed, oldest first; the event queue. self.timings: list[LineTiming] = [] self.events: list[tuple[int, int, int, LineTiming]] = [] self._seq = 0 self.next_event = _FAR #: The first SH-2 state an event is due at (``SH2Side.catch_up``). self.next_state = _FAR #: The frame being drawn, row by row, and the last finished one. self.rows: list[list[int] | None] = [None] * 240 self.row_pri = [0] * 240 self.picture: list[list[int] | None] | None = None self.picture_pri: list[int] = [] self.frames = 0 # -- socket 6 --------------------------------------------------------------------- def video_line(self, line: VideoLine, running: bool) -> None: """A line record. With ADEN = 0 (``running`` False) the VDP keeps only its timing: nothing can reach the registers then (testpico t_32x_init: the VDP hangs without ADEN), and no event is queued.""" timing = LineTiming(line, self.quirks) self.ntsc = not line.pal timings = self.timings if timings and timings[-1].start == timing.start and timings[-1].v == timing.v: # Re-anchored at its HBlank by an H32/H40 change: the old record's events not # yet run are dropped, the new one's from its publication on are queued. timings[-1].cancelled = True timings[-1] = timing else: timings.append(timing) if len(timings) > 512: del timings[:-256] if not running: if self.events: self.events.clear() self._next() del timings[:-4] return after = timing.published push = self._push if timing.rise >= after: push(timing.rise, RISE, timing) if timing.latch >= after: push(timing.latch, LATCH, timing) if timing.fall >= after: push(timing.fall, FALL, timing) if timing.vedge >= after: active = self.active_rows(timing) if timing.v == active: push(timing.vedge, VBLANK_ON, timing) elif timing.v == 0: push(timing.vedge, VBLANK_OFF, timing) def _push(self, at: int, kind: int, timing: LineTiming) -> None: self._seq += 1 heapq.heappush(self.events, (at, kind, self._seq, timing)) if at < self.next_event: self.next_event = at self.next_state = (at * 3 + 6) // 7 def _next(self) -> None: events = self.events if events: self.next_event = events[0][0] self.next_state = (self.next_event * 3 + 6) // 7 else: self.next_event = self.next_state = _FAR def advance(self, mclk: int) -> None: """Run every event due at or before ``mclk``.""" events = self.events while events and events[0][0] <= mclk: _at, kind, _seq, timing = heapq.heappop(events) if timing.cancelled: continue if kind == RISE: self._hblank_rise(timing) elif kind == LATCH: self._latch() elif kind == FALL: self._hblank_fall(timing) elif kind == VBLANK_ON: self._vblank_on() elif kind == VBLANK_OFF: self._vblank_off() self._next() def prune(self, mclk: int) -> None: """Forget line records that end before ``mclk`` (no CPU is behind it), keeping two.""" timings = self.timings drop = 0 while drop < len(timings) - 2 and timings[drop].end <= mclk: drop += 1 if drop: del timings[:drop] # -- the line's edges --------------------------------------------------------------- def active_rows(self, timing: LineTiming | None = None) -> int: """224, or 240 with the 240 bit on a PAL console (Manual 3.2.3: "Valid only when PAL"; on NTSC the bit causes "operating errors", not modelled).""" pal = timing.pal if timing is not None else not self.ntsc return 240 if pal and self.latched_240 else 224 def _hblank_rise(self, timing: LineTiming) -> None: """HINT at HBLANK (Manual 3.2.2): the internal counter fires at 0 and is reloaded from the H count register when this HBLANK falls, else counts down; in VBLANK only with HEN, and without HEN it is reloaded at each fall (``Quirks.hint_counter``).""" device = self.device if self._vblank_at(timing, timing.rise) and not device.hen: self.hint_reload = True return if self.hint_counter <= 0: self.hint_reload = True sh2 = device.sh2 if sh2 is not None and sh2.running: sh2.raise_hint() else: self.hint_counter -= 1 def _hblank_fall(self, timing: LineTiming) -> None: if self.hint_reload: self.hint_counter = self.device.hcount self.hint_reload = False row = timing.v if row < self.active_rows(timing) and row < 240: self._draw(row) composite = self.device.composite if composite is not None: composite.row_drawn(timing.start, self.rows[row], self.row_pri[row]) def _latch(self) -> None: """The display circuit takes bitmap mode, PRI, 240 and shift for the next row (Manual 3.3, "VDP Register Latch Timing"); a swap waiting for blank mode happens now (``Quirks.fs_swap``).""" bitmap = self.bitmap self.latched_mode = bitmap & 3 self.latched_pri = (bitmap >> 7) & 1 self.latched_240 = (bitmap >> 6) & 1 self.latched_shift = self.shift & 1 if self.latched_mode == 0 and self.fs_pending is not None: self.fs, self.fs_pending = self.fs_pending, None def _vblank_on(self) -> None: """VBLANK: the frame is finished, a pending FS swaps (Manual 3.2.3: "swapping is done at the next V Blank"), VINT is raised (``Quirks.vint_at``).""" self.vblank = True active = self.active_rows() self.picture = self.rows[:active] self.picture_pri = self.row_pri[:active] self.rows = [None] * 240 self.frames += 1 if self.fs_pending is not None: self.fs, self.fs_pending = self.fs_pending, None sh2 = self.device.sh2 if sh2 is not None and sh2.running: sh2.raise_vint(True) def _vblank_off(self) -> None: self.vblank = False sh2 = self.device.sh2 if sh2 is not None and sh2.running: sh2.raise_vint(False) # -- status at a clock ---------------------------------------------------------------- def timing_at(self, mclk: int) -> LineTiming | None: timings = self.timings for index in range(len(timings) - 1, -1, -1): timing = timings[index] if timing.start <= mclk: return timing return timings[0] if timings else None def _vblank_at(self, timing: LineTiming, mclk: int) -> bool: v = timing.v if v == 0: return mclk < timing.vedge active = self.active_rows(timing) if v < active: return False if v == active: return mclk >= timing.vedge return True def status(self, mclk: int) -> tuple[bool, bool, bool, bool]: """(VBLK, HBLK, PEN, FEN) at ``mclk``.""" timing = self.timing_at(mclk) if timing is None: return True, True, True, mclk < self.fill_end if mclk >= timing.end: # Not yet published (the Mega Drive's VDP is lazy): the next line, predicted # with this one's geometry. length = timing.end - timing.start offset = (mclk - timing.start) % length hblank = timing.rise - timing.start <= offset < timing.fall - timing.start pen_on = timing.pen_rise - timing.start <= offset < timing.fall - timing.start refresh = timing.rise - timing.start <= offset < timing.refresh_end - timing.start vblank = self.vblank else: hblank = timing.rise <= mclk < timing.fall pen_on = timing.pen_rise <= mclk < timing.fall refresh = timing.rise <= mclk < timing.refresh_end vblank = self._vblank_at(timing, mclk) pen = vblank or pen_on or self.latched_mode in (0, 2) fen = refresh or mclk < self.fill_end return vblank, hblank, pen, fen def palette_wait(self, mclk: int) -> int: """Master clocks until PEN = 1 from ``mclk`` (0 if it is): "If accessing when PEN = 0, wait is held until PEN = 1" (Manual 3.3; ``Quirks.palette_wait``).""" if self.status(mclk)[2]: return 0 timing = self.timing_at(mclk) if timing is None: return 0 length = timing.end - timing.start pen = timing.pen_rise - timing.start offset = (mclk - timing.start) % length return pen - offset if offset < pen else length - offset + pen # -- registers -------------------------------------------------------------------------- def read(self, offset: int, mclk: int) -> int: """A word of $A15180-$A1518F (``offset`` 0-$E).""" if offset == 0x0: return (0x8000 if self.ntsc else 0) | self.bitmap # PAL bit: 0 = PAL if offset == 0x2: return self.shift if offset == 0x4: return self.fill_length if offset == 0x6: return self.fill_start if offset == 0x8: return self.fill_data if offset == 0xA: vblank, hblank, pen, fen = self.status(mclk) return (vblank << 15) | (hblank << 14) | (pen << 13) | (fen << 1) | self.fs return 0 def write(self, offset: int, value: int, lanes: int, mclk: int) -> None: keep = ~lanes & 0xFFFF value &= lanes if offset == 0x0: self.bitmap = ((self.bitmap & keep) | value) & self.bitmap_writable elif offset == 0x2: self.shift = ((self.shift & keep) | value) & 1 elif offset == 0x4: self.fill_length = ((self.fill_length & keep) | value) & 0xFF elif offset == 0x6: self.fill_start = ((self.fill_start & keep) | value) & 0xFFFF elif offset == 0x8: self.fill_data = (self.fill_data & keep) | value self._fill(mclk) elif offset == 0xA and lanes & 0x00FF: fs = value & 1 if self.status(mclk)[0] or not self.bitmap & 3: self.fs, self.fs_pending = fs, None else: self.fs_pending = fs # "swapping is done at the next V Blank" def _fill(self, mclk: int) -> None: """Manual 3.2.3: length + 1 words of the data from the start address, A16-A9 fixed and A8-A1 counting (so it wraps in its 256-word page). The words are written at once; FEN reads 1 for the fill's 7 + 3 x length Sclk (Manual 3.3; ``Quirks. auto_fill``).""" buffer = self.framebuffers[self.fs ^ 1] start = self.fill_start high, low = self.fill_data >> 8, self.fill_data & 0xFF words = self.fill_length + 1 for _ in range(words): offset = start << 1 buffer[offset] = high buffer[offset + 1] = low start = (start & 0xFF00) | ((start + 1) & 0xFF) self.fill_start = start busy = (7 + 3 * words) * 7 // 3 self.fill_end = max(self.fill_end, mclk) + busy # -- the picture -------------------------------------------------------------------------- def _draw(self, row: int) -> None: """Row ``row`` from the displayed frame buffer, as latched for it (Manual 3.3, "Line Table Format": the row's word address, and 320 pixels' worth from there, running on through the address space, so into the overwrite image's alias of the same DRAM).""" self.row_pri[row] = self.latched_pri mode = self.latched_mode if mode == 0: self.rows[row] = None return fb = self.framebuffers[self.fs] address = (fb[row << 1] << 8) | fb[(row << 1) + 1] palette = self.palette if mode == 1: # packed pixel: a palette index a byte, high byte first # DOC: Technical Bulletin #14, the shift is ignored on a line whose address's # low byte is $FF. OBSERVED (ares 9408cb4, M32X::VDP::scanlineMode1): the # shift moves packed pixels only (Quirks.screen_shift_modes, provisional). shift = self.latched_shift and (address & 0xFF) != 0xFF data = _bytes_at(fb, (address << 1) + shift, WIDTH) self.rows[row] = [palette[index] for index in data] elif mode == 2: # direct colour: a word a pixel data = _bytes_at(fb, address << 1, WIDTH * 2) self.rows[row] = list(_DIRECT.unpack(data)) else: # run length: (length - 1, index) a word, 1-256 pixels out: list[int] = [] while len(out) < WIDTH: offset = (address & 0xFFFF) << 1 count = fb[offset] + 1 colour = palette[fb[offset + 1]] address += 1 out.extend([colour] * count) del out[WIDTH:] self.rows[row] = out def frame_rgb(self, *, blank: int = 0) -> list[list[int]]: """The last finished frame as rows of RGB888 (each 5-bit level as ``v << 3 | v >> 2``: the RAMDAC's levels are unmeasured, docs/undocumented-behavior.md); a blank-mode row is ``blank``.""" picture = self.picture if picture is None: return [[blank] * WIDTH for _ in range(224)] out = [] for row in picture: if row is None: out.append([blank] * WIDTH) continue out.append([_RGB[word & 0x7FFF] for word in row]) return out def _bytes_at(fb: bytearray, offset: int, size: int) -> bytes: offset &= 0x1FFFF end = offset + size if end <= 0x20000: return bytes(fb[offset:end]) return bytes(fb[offset:]) + bytes(fb[: end - 0x20000]) def _level(v: int) -> int: return (v << 3) | (v >> 2) #: BGR555 -> RGB888 (R in bits 4-0, G 9-5, B 14-10: Manual 3.3, "Color Palette"). _RGB = [ (_level(c & 31) << 16) | (_level((c >> 5) & 31) << 8) | _level((c >> 10) & 31) for c in range(0x8000) ] __all__ = ["VDP32X", "WIDTH", "LineTiming"]