# SPDX-License-Identifier: MIT """The picture processor's timing: VCOUNT, DISPSTAT, the blanking flags, their IRQs and the DMA start conditions; and the LCD registers' storage. Timing (docs/video.md "Timing"; GBATEK §LCD Dimensions and Timings, §LCD I/O Interrupts and Status; DOC): a dot is 4 cycles, a line 308 dots (1,232 cycles), a frame 228 lines (280,896 cycles). VCOUNT runs 0-227; the V-blank flag is set in lines 160-226, not 227. Each line is counted from its origin, the cycle VCOUNT changes; the other edges' offsets from it are the constants below (rung 4, TEST ROM: hw-test ppu/status-irq-dma 12/12; U-VID-1). Power-on: the board's cycle 0 is cycle POWER_ON of line 0 (HYPOTHESIS, below). The picture (rung 4, gba_python.ppu.dots): drawn where the beam is, by catching up before any write that could change it; each visible line is finished at the next origin and the frame is handed over at the start of V-blank, so ``picture()`` never shows a frame half drawn. Rung 3's line renderer (gba_python.ppu.line) stays as the specification the dot model agrees with on lines where nothing changes (scripts/lockstep_pictures.py drives both through ``lockstep``). The affine reference points (GBATEK §LCD I/O BG Rotation/Scaling, "Internal Reference Point Registers"; DOC): BG2X/Y and BG3X/Y are copied to internal registers in V-blank and the internal registers advance by PB (dmx) and PD (dmy) after each line; a write copies the new value to the internal register at once. When: the copy in line 160 (HYPOTHESIS), the advance in each line 1-159, both REFERENCE_LATCH cycles after the origin, with PB and PD as they stand then, after which the line's value is fixed (TEST ROM: hw-test ppu/bgpd's photograph needs PD read near the line's start, not at H-blank; ppu/bgx's capture fixes the cycle to 1 or 2). """ from __future__ import annotations from gba_python.dma import HBLANK as DMA_HBLANK from gba_python.dma import SPECIAL as DMA_SPECIAL from gba_python.dma import VBLANK as DMA_VBLANK from gba_python.irq import HBLANK, VBLANK, VCOUNT from gba_python.ppu.dots import DotRenderer from gba_python.ppu.line import WIDTH, LineRenderer from gba_python.scheduler import ORDER_PPU LINE_CYCLES = 1232 LINES = 228 FRAME_CYCLES = LINE_CYCLES * LINES # 280,896 VISIBLE_LINES = 160 # Edges within a line, in cycles from the line origin (the cycle VCOUNT changes). TEST ROM: # hw-test ppu/status-irq-dma's expected values (its source's test_expect), read as differences # from the IF bits the board already matched at rung 1 (IF V-count 147, IF H-blank 1153 there): # VCOUNT, the V-blank flag and the H-blank flag's fall at 144; the V-count flag at 145; IF # V-blank at 146 and IF V-count at 147; the H-blank flag's rise at 1151 and IF H-blank at 1153; # the H-blank DMA one cycle and the V-blank DMA two cycles before the board's rung-3 requests # (its DMA sub-test: 1137 and 1362 against the board's 1138 and 1364). So the H-blank flag is 0 # for 1,007 cycles: TEST ROM over GBATEK's 1,006 (DOC) by one (U-VID-1). VMATCH_FLAG = 1 VBLANK_DMA = 1 VBLANK_IRQ = 2 VMATCH_IRQ = 3 HBLANK_START = 1007 # the H-blank flag rises HBLANK_DMA = 1008 HBLANK_IRQ = 1009 # The video capture DMA (DMA3 special): requested at line origin + 4 in lines 2-161 (GBATEK # §GBA DMA Transfers: "VCOUNT 2 to 162"; DOC). status-irq-dma's "VIDEO DMA" (22069 cycles after # its timer starts in line 158's H-blank IRQ) puts the first request after an enable in line 158 # at line 2 of the next frame, not at lines 159-161, and at origin + 4 (TEST ROM). Modelled as a # capture that starts at line 2 for a DMA3 enabled in special timing then, and requests in every # line 2-161 while it stays enabled (HYPOTHESIS beyond the first request). CAPTURE_REQUEST = 4 # The affine reference points advance (or reload, at line 160) and are taken for the line this # many cycles after the origin: FITTED to hw-test ppu/bgx's capture (white column at dot 129: # 1 or 2 fit, the DMA writing BG2X every 2 cycles; 0 gives 130, 3 gives 128) with ppu/bgpd's # photograph (two bands, the first edge at 75 with 1 or 2, 74 with 3; TEST ROM). REFERENCE_LATCH = 2 # Power-on: the board's cycle 0 is cycle POWER_ON of line 0, so that the IRQs stay where rung 1 # fitted them (HYPOTHESIS: alyosha-tas ppu/start_up* would judge the phase). POWER_ON = 3 # Readable bits of the LCD registers, by offset (GBATEK §GBA I/O Map, §LCD I/O; DOC; the mGBA # suite's io-read.c table agrees; TEST ROM). Offsets not listed are write-only or unused. READ_MASKS = { 0x00: 0xFFFF, # DISPCNT 0x02: 0x0001, # green swap (undocumented; GBATEK §GBA I/O Map: R/W, bit 0) 0x08: 0xDFFF, # BG0CNT: bit 13 only for BG2/3 0x0A: 0xDFFF, 0x0C: 0xFFFF, 0x0E: 0xFFFF, 0x48: 0x3F3F, # WININ 0x4A: 0x3F3F, # WINOUT 0x50: 0x3FFF, # BLDCNT 0x52: 0x1F1F, # BLDALPHA } class PPU: def __init__(self, board) -> None: self.board = board self.regs = [0] * 0x30 # halfwords 0x000-0x05E self.vcount = 0 self.dispstat = 0 # the writable bits 3-5 and 8-15 self.vblank = False self.hblank = False self.vmatch = True # VCOUNT = LYC (both 0 at power-on) self.capturing = False # a video capture DMA started at line 2 (CAPTURE_REQUEST) self.line_start = -POWER_ON # the current line's origin # The affine internal reference points, 20.8 fixed point, signed: BG2X, BG2Y, BG3X, # BG3Y; and their values at the start of the current vertical mosaic block. self.ref = [0, 0, 0, 0] self.mosaic_ref = [0, 0, 0, 0] # DISPCNT as the picture sees it, sampled at every line's start (latch_display). self.shown_since = [0] * 5 # lines in a row BG0-3, OBJ have been enabled self.blank_lines = 3 # lines since forced blank was last set (3 = long ago) self.display = 0 self.frame = [[0x7FFF] * WIDTH for _ in range(VISIBLE_LINES)] # being drawn self.shown = [[0x7FFF] * WIDTH for _ in range(VISIBLE_LINES)] # the last finished self.renderer = LineRenderer(self, board.bus) # rung 3: the specification (lockstep) self.dots = DotRenderer(self, board.bus) # rung 4: the picture self.lockstep = None # scripts/lockstep_pictures.py board.bus.dots = self.dots sched = board.scheduler self.start_line(-POWER_ON) sched.schedule(-POWER_ON + VMATCH_FLAG, ORDER_PPU, self.line_flags) sched.schedule(-POWER_ON + REFERENCE_LATCH, ORDER_PPU, self.references) sched.schedule(-POWER_ON + HBLANK_START, ORDER_PPU, self.hblank_begins) sched.schedule(LINE_CYCLES - POWER_ON, ORDER_PPU, self.line_begins) # ---------------------------------------------------------------------------------- # Events def line_begins(self, time: int) -> None: board = self.board self.finish_line(time) self.line_start = time self.hblank = False self.vcount = (self.vcount + 1) % LINES if self.vcount == VISIBLE_LINES: self.vblank = True self.frame, self.shown = self.shown, self.frame board.frame_done(time) elif self.vcount == LINES - 1: self.vblank = False # not set in line 227 (DOC) self.start_line(time) sched = board.scheduler sched.schedule(time + VMATCH_FLAG, ORDER_PPU, self.line_flags) sched.schedule(time + REFERENCE_LATCH, ORDER_PPU, self.references) sched.schedule(time + HBLANK_START, ORDER_PPU, self.hblank_begins) sched.schedule(time + LINE_CYCLES, ORDER_PPU, self.line_begins) def start_line(self, origin: int) -> None: """What every line does at its origin: the display latch, the windows' vertical flags, and the dot renderer's line and OBJ fetch.""" y = self.vcount self.latch_display() dots = self.dots dots.begin_window_flags(y) if self.lockstep is not None: self.lockstep.line_origin(self, y) if y < VISIBLE_LINES: dots.begin_line(y, origin) if y == LINES - 1 or y < VISIBLE_LINES - 1: dots.begin_obj_fetch((y + 1) % LINES, origin) def references(self, time: int) -> None: """The affine reference points: copied from BGxX/Y at line 160, advanced by PB/PD in lines 1-159 (GBATEK §LCD I/O BG Rotation/Scaling; DOC), then taken for the line being drawn (REFERENCE_LATCH).""" y = self.vcount if y == VISIBLE_LINES: self.reload_references() if y >= VISIBLE_LINES: return if y: self.advance_references() # The vertical mosaic block's origin for the affine BGs: the internal reference point # of the block's first line, counted from line 0 (HYPOTHESIS, docs/video.md "Mosaic"). vsize = ((self.regs[0x26] >> 4) & 0xF) + 1 if y % vsize == 0: self.mosaic_ref[:] = self.ref self.dots.take_references() if self.lockstep is not None: self.lockstep.line_start(self, y) def finish_line(self, time: int) -> None: dots = self.dots dots.finish_obj_fetch(time) y = dots.y line = dots.finish_line() if line is not None: self.frame[y][:] = line if self.lockstep is not None: self.lockstep.line_end(self, y, line) def line_flags(self, time: int) -> None: board = self.board self.set_vmatch(self.vcount == self.dispstat >> 8, time) if self.vcount == VISIBLE_LINES: if self.dispstat & 0x08: board.irq.request(VBLANK, time - VMATCH_FLAG + VBLANK_IRQ) board.dma.trigger(DMA_VBLANK, time - VMATCH_FLAG + VBLANK_DMA) if self.vcount == 2: control = board.dma.channels[3].control self.capturing = control & 0xB000 == 0xB000 # enabled, special timing elif self.vcount == 162: if self.capturing: board.dma.end_capture() self.capturing = False if self.capturing: board.dma.trigger(DMA_SPECIAL, time - VMATCH_FLAG + CAPTURE_REQUEST) def set_vmatch(self, match: bool, time: int) -> None: """The V-count flag follows VCOUNT = LYC one cycle after VCOUNT changes, and at once when DISPSTAT's LYC is written; its rise requests the IRQ two cycles later (TEST ROM: status-irq-dma, above; for a write in mid-line, destoer lyc_midline's photograph: the flag reads set right after the write, and a loop rewriting LYC counts 6 IRQs in one line; the IRQ's delay after a write is HYPOTHESIS, the same as at a line's start).""" if match and not self.vmatch and self.dispstat & 0x20: self.board.irq.request(VCOUNT, time + VMATCH_IRQ - VMATCH_FLAG) self.vmatch = match def hblank_begins(self, time: int) -> None: board = self.board self.hblank = True # H-blank IRQs in every line, V-blank lines included (U-VID-2: gbadoc's "verified" # statement and GBATEK §LCD I/O Interrupts and Status; DOC). if self.dispstat & 0x10: board.irq.request(HBLANK, time - HBLANK_START + HBLANK_IRQ) # H-blank DMA does not run in V-blank lines (gbadoc registers.md; DOC). if self.vcount < VISIBLE_LINES: board.dma.trigger(DMA_HBLANK, time - HBLANK_START + HBLANK_DMA) # ---------------------------------------------------------------------------------- # The picture def latch_display(self) -> None: """DISPCNT's display bits as the line about to start sees them, sampled at every line's start, V-blank lines included. Turning a BG or the OBJs on, or forced blank off, shows on the third line whose start sees it (two lines late); turning a layer off or forced blank on shows at once; the window enables act at once (TEST ROM: hw-test ppu/dispcnt-latch's expected picture, lines 8-9, 24-25, 72-73 and 32-56; NBA agrees, OBSERVED). GBATEK's unexplained "when the internal HV synchronous counter cancels a forced blank during a display period, the display begins ... following the display of two vertical lines" (§LCD I/O Display Control; DOC) says the same of forced blank. Why (a pipeline, a counter) is HYPOTHESIS; whether a bit set for fewer than three line starts ever shows is untested.""" dispcnt = self.regs[0] since = self.shown_since display = dispcnt & ~0x1F80 for i in range(5): if dispcnt & (0x100 << i): since[i] = min(since[i] + 1, 3) if since[i] == 3: display |= 0x100 << i else: since[i] = 0 if dispcnt & 0x80: self.blank_lines = 0 elif self.blank_lines < 3: self.blank_lines += 1 if self.blank_lines < 3: display |= 0x80 self.display = display def affine_origin(self, bg: int, mosaic: int) -> tuple[int, int]: i = 0 if bg == 2 else 2 ref = self.mosaic_ref if mosaic else self.ref return ref[i], ref[i + 1] def reload_references(self) -> None: regs = self.regs for i, low in enumerate((0x14, 0x16, 0x1C, 0x1E)): self.ref[i] = reference_point(regs[low], regs[low + 1]) def advance_references(self) -> None: regs = self.regs ref = self.ref ref[0] += signed16(regs[0x11]) # BG2X += BG2PB ref[1] += signed16(regs[0x13]) # BG2Y += BG2PD ref[2] += signed16(regs[0x19]) # BG3X += BG3PB ref[3] += signed16(regs[0x1B]) # BG3Y += BG3PD def picture(self) -> list[list[int]]: """The last finished frame: 160 rows of 240 15-bit BGR colours.""" return [row[:] for row in self.shown] # ---------------------------------------------------------------------------------- # Registers def read16(self, offset: int) -> int | None: if offset == 0x04: value = self.dispstat if self.vblank: value |= 1 if self.hblank: value |= 2 if self.vmatch: value |= 4 return value if offset == 0x06: return self.vcount mask = READ_MASKS.get(offset) if mask is None: return None return self.regs[offset >> 1] & mask def write16(self, offset: int, value: int, mask: int, time: int) -> None: if offset == 0x04: writable = mask & 0xFF38 self.dispstat = (self.dispstat & ~writable) | (value & writable) if time >= self.line_start + VMATCH_FLAG: self.set_vmatch(self.vcount == self.dispstat >> 8, time) return if offset == 0x06: return # VCOUNT is read-only (DOC) # Dots fetched before the write are drawn with the old value (gba_python.ppu.dots). self.dots.note_write(time) if offset == 0x02: self.dots.note_greenswap(time, value) index = offset >> 1 self.regs[index] = (self.regs[index] & ~mask) | (value & mask) if 0x28 <= offset < 0x30 or 0x38 <= offset < 0x40: # A reference point write reaches the internal register at once (DOC). low = index & ~1 self.ref[((low - 0x14) >> 3 << 1) | ((low >> 1) & 1)] = reference_point( self.regs[low], self.regs[low + 1] ) elif offset == 0x00: # DISPCNT bit 3 ("CGB Mode") can only be set by BIOS opcodes (GBATEK §LCD I/O # Display Control; DOC): HYPOTHESIS that the write is stored as given. self.board.bus.bitmap_mode = (self.regs[0] & 7) >= 3 def signed16(value: int) -> int: return value - 0x10000 if value & 0x8000 else value def reference_point(low: int, high: int) -> int: """BGxX/BGxY: 28 bits, signed (bit 27), 8 fraction bits (DOC).""" value = (low | high << 16) & 0x0FFFFFFF return value - 0x10000000 if value & 0x08000000 else value