"""The picture processor: video memory, its registers, the line's timing and the picture. What other units and the CPU observe: - VRAM (96 KiB), palette RAM (1 KiB) and OAM (1 KiB) with their mirrors and 8-bit write rules (GBATEK "GBA Memory Map"; quirks 4 and 5 in docs/undocumented-behavior.md). - The display registers, stored as written and read back through their read masks. - The line's events at NanoBoyAdvance's cycles (docs/timing.md "The PPU's line"): VCOUNT, the DISPSTAT flags, VBlank/HBlank/VCount-match IRQs, HBlank/VBlank DMA requests, and the video capture DMA on lines 2-161. At power-on VCOUNT reads 225 with VBlank and HBlank set, and line 226 starts 226 cycles later (NBA's reset, "measured after reset on a 3DS in GBA mode"). The picture (rung 4, dot-exact); ``screen`` holds the last finished frame (240x160 BGR555): - cycle 0: the affine BGs' internal reference points step by PB/PD (or reload, line 0 and after a write), the window's vertical flags update, and the window engine starts its run across the line (a dot every four cycles, reading WINxH as it goes). - cycle 40: DISPCNT's three-deep latch shifts (BG enables act two lines after a write), and the OBJ engine hands over the line it fetched and starts on the next (``objects.Engine``). - cycles 0-1006: the BG and merge engines (``dot.DotLine``) fetch and draw dot by dot. The engines run lazily: each is brought up to the present only when something it reads is about to change (a display register, palette, VRAM or OAM write) or the CPU or a DMA touches the memory it reads (the access waits a cycle while the PPU reads the same memory, quirk 18). A visible line on which nothing of the kind happens is drawn whole at HBlank by the line renderer (``background.py``, ``compose.py``), which gives the dot engine's picture: setting ``GBA_PPU_EXACT=1`` runs every line on the dot engine, and docs/validation.md (rung 4) records the two agreeing. """ from __future__ import annotations import os from array import array from gba_python.dma import DMA from gba_python.irq import HBLANK, IRQ, VBLANK, VCOUNT from gba_python.ppu import objects from gba_python.ppu.background import Latch, affine_line, bitmap_line, text_line from gba_python.ppu.compose import compose from gba_python.ppu.dot import DotLine from gba_python.scheduler import Scheduler LINE = 1232 # cycles per line: 308 dots x 4 HBLANK_START = 1007 # line cycle the HBlank flag rises; hw-test/ppu/status-irq-dma passes (C1) VISIBLE_LINES = 160 LINES = 228 LATCH_CYCLE = 40 # DISPCNT latch and the OBJ engine's window start (NBA ``PPU_latch_dispcnt``) WHITE = 0x7FFF # forced blank shows white WINDOW_CYCLES = 1024 # the window engine's run each line: dots 0-255, one per four cycles BG_FETCH_END = 1040 # after this line cycle the BG engine reads no VRAM (its last tile fetch) #: run every visible line on the dot engine (to check it gives the line renderer's picture) EXACT = os.environ.get("GBA_PPU_EXACT", "") not in ("", "0") #: register writes that never reach a line already being drawn: DISPSTAT, VCOUNT, the affine #: reference points (they load at the next line start) and the window edges (the window engine #: takes them as it goes) LINE_SAFE = ( frozenset(range(0x04, 0x08)) | frozenset(range(0x28, 0x30)) | frozenset(range(0x38, 0x48)) ) #: the readable bits of each display register, by halfword offset from 4000000; #: absent means write-only (BG offsets, affine parameters, windows, MOSAIC, BLDY) READ_MASK = { 0x00: 0xFFFF, # DISPCNT (bit 3, CGB mode, is stored and read back) 0x02: 0x0001, # GREENSWAP 0x08: 0xDFFF, # BG0CNT: bit 13 (wrap) exists only for the affine layers 0x0A: 0xDFFF, 0x0C: 0xFFFF, 0x0E: 0xFFFF, 0x48: 0x3F3F, # WININ 0x4A: 0x3F3F, # WINOUT 0x50: 0x3FFF, # BLDCNT 0x52: 0x1F1F, # BLDALPHA } class PPU: def __init__(self, scheduler: Scheduler, irq: IRQ, dma: DMA) -> None: self.scheduler = scheduler self.irq = irq self.dma = dma self.vram = bytearray(0x18000) self.palette = bytearray(0x400) self.oam = bytearray(0x400) self.registers = [0] * 0x30 # halfwords 4000000-400005E as written self.vcount = 225 self.vblank_flag = True self.hblank_flag = True self.vcount_flag = False self.dispstat = 0 # the writable bits: IRQ enables (3-5) and the VCount setting (8-15) self.video_dma = False self.frame = 0 # frames completed (line 227 -> 0) # BGR555, row after row: ``screen`` is the last finished frame, ``_drawing`` the one # being drawn; they swap at the frame's end (line 227 -> 0), as a display would latch it self.screen = array("H", [0] * 240 * VISIBLE_LINES) self._drawing = array("H", [0] * 240 * VISIBLE_LINES) self.dispcnt_latch = [0, 0, 0] # oldest first: [0] is what the BG enables use # BG2/BG3 affine reference points: as written (28-bit signed) and the internal copy # that steps by PB/PD each line (GBATEK "BG Rotation/Scaling"; quirk 15) self.affine_written = [[0, 0], [0, 0]] # [bg][x, y] self.affine_current = [[0, 0], [0, 0]] self.affine_dirty = [[False, False], [False, False]] self.bg_mosaic_y = 0 # the BG mosaic's line counter self.obj_mosaic_y = 0 self.window_v = [False, False] # WIN0/WIN1 vertical flags, set at the top edge self.window_h = [False, False] # horizontal flags; they carry over from line to line # the window engine: each window's flag per dot of the line, filled as the line runs self.window_buffer = [[False] * 240, [False] * 240] self.window_cycle = WINDOW_CYCLES # the OBJ engine's output for this line, and the engine fetching the next self.objects = objects.ObjLine() self.obj_engine: objects.Engine | None = None self.obj_start = 0 # board cycle of the engine's step 0 self.bg_latch = Latch() self.line_start = 0 # board cycle of this line's cycle 0 self.dot: DotLine | None = None # the dot engine, when this line runs on it scheduler.add(226, self._hdraw_vblank) scheduler.add(226 + LATCH_CYCLE, self._latch_and_objects) # ----- registers ---------------------------------------------------------------------- def read_register(self, offset: int) -> int | None: """A display register's halfword, or None if it is not readable.""" if offset == 0x04: return ( self.vblank_flag | self.hblank_flag << 1 | self.vcount_flag << 2 | self.dispstat & 0xFF38 ) if offset == 0x06: return self.vcount mask = READ_MASK.get(offset) return None if mask is None else self.registers[offset >> 1] & mask def write_register(self, offset: int, value: int, mask: int) -> None: self._before_write(offset) if offset == 0x04: self.dispstat = (self.dispstat & ~mask | value & mask) & 0xFF38 self._update_vcount_flag(0) elif offset != 0x06: # VCOUNT is read-only index = offset >> 1 self.registers[index] = self.registers[index] & ~mask | value & mask if 0x28 <= offset < 0x40 and offset & 0x0F >= 8: # BG2X/BG2Y/BG3X/BG3Y bg, axis = offset >> 4 & 1, offset >> 2 & 1 low = self.registers[(offset & ~3) >> 1] high = self.registers[((offset & ~3) >> 1) + 1] & 0x0FFF point = high << 16 | low self.affine_written[bg][axis] = point - (1 << 28) if point & 1 << 27 else point self.affine_dirty[bg][axis] = True @property def sprite_vram_boundary(self) -> int: """Where OBJ tiles start in VRAM: 6010000, or 6014000 in the bitmap modes 3-5.""" return 0x14000 if self.registers[0] & 7 >= 3 else 0x10000 # ----- what the CPU and DMA see of the engines ------------------------------------- def _before_write(self, offset: int) -> None: """Bring the engines up to now before a display register write lands, so the dots, OBJ steps and window flags before it see the old value (NBA ``Bus::Write`` syncs the PPU before DISPCNT-BLDY writes).""" now = self.scheduler.now if self.dot is not None: self._sync_window(now) self.dot.run_to(now) elif ( self.vcount < VISIBLE_LINES and offset not in LINE_SAFE and now - self.line_start < HBLANK_START ): self._start_dot(now) # the line changes while it is drawn: draw it dot by dot elif offset == 0x40 or offset == 0x42: # WIN0H, WIN1H self._sync_window(now) if (offset == 0x00 or offset == 0x4C) and self.obj_engine is not None: self._sync_objects(now) def _start_dot(self, now: int) -> None: """Move the rest of this line to the dot engine: run it from the line's start, on the state the line started with (nothing it reads has changed since: any change would have started it), up to now.""" self._sync_window(now) self.dot = DotLine(self, self.line_start) self.dot.run_to(now) def palette_busy(self) -> bool: """Whether the merge read palette RAM in the cycle just ended (the CPU or DMA access there waits a cycle more, quirk 18). Brings the line up to now first.""" now = self.scheduler.now dot = self.dot if dot is None: if self.vcount >= VISIBLE_LINES or now - self.line_start >= HBLANK_START: return False self._start_dot(now) dot = self.dot assert dot is not None else: self._sync_window(now) dot.run_to(now) return dot.pram_access == now - 1 def bg_vram_busy(self) -> bool: """The same for the BG engine and BG VRAM.""" now = self.scheduler.now dot = self.dot if dot is None: if self.vcount >= VISIBLE_LINES or now - self.line_start >= BG_FETCH_END: return False self._start_dot(now) dot = self.dot assert dot is not None else: self._sync_window(now) dot.run_to(now) return dot.vram_access == now - 1 def obj_vram_busy(self) -> bool: """The same for the OBJ engine and OBJ VRAM.""" engine = self.obj_engine if engine is None: return False now = self.scheduler.now self._sync_objects(now) return engine.last_vram >= 0 and self.obj_start + 2 * engine.last_vram == now - 1 def oam_busy(self) -> bool: """The same for the OBJ engine and OAM.""" engine = self.obj_engine if engine is None: return False now = self.scheduler.now self._sync_objects(now) return engine.last_oam >= 0 and self.obj_start + 2 * engine.last_oam == now - 1 def _sync_objects(self, now: int) -> None: engine = self.obj_engine if engine is not None: engine.run((now - self.obj_start + 1) >> 1) # the steps whose cycle has passed # ----- the line ----------------------------------------------------------------------- def _end_line(self) -> None: """Cycle 1232 of every line: the window engine and, if the line ran on it, the dot engine finish their runs.""" now = self.scheduler.now self._sync_window(now) if self.dot is not None: self.dot.run_to(now) self.dot = None def _hdraw_vdraw(self, _: int) -> None: add = self.scheduler.add add(1, self._update_vcount_flag) self.hblank_flag = False self._end_line() self._end_visible_line() self.vcount += 1 self._begin_line() self._video_dma_line() if self.vcount == VISIBLE_LINES: add(HBLANK_START, self._hblank_vblank) self.dma.request_vblank() self.vblank_flag = True if self.dispstat & 0x08: add(1, self._vblank_irq) else: add(HBLANK_START, self._hblank_vdraw) def _hblank_vdraw(self, _: int) -> None: if self.dot is None: self._draw_line() self.hblank_flag = True self.dma.request_hblank() if self.dispstat & 0x10: self.scheduler.add(1, self._hblank_irq) self.scheduler.add(LINE - HBLANK_START, self._hdraw_vdraw) def _hdraw_vblank(self, _: int) -> None: add = self.scheduler.add add(1, self._update_vcount_flag) self.hblank_flag = False self._end_line() if self.vcount == 162: self.video_dma = self.dma.has_video() if self.vcount == LINES - 1: add(HBLANK_START, self._hblank_vdraw) self.vcount = 0 self.frame += 1 self.screen, self._drawing = self._drawing, self.screen else: add(HBLANK_START, self._hblank_vblank) self.vcount += 1 if self.vcount == LINES - 1: self.vblank_flag = False self._video_dma_line() self._begin_line() def _hblank_vblank(self, _: int) -> None: self.hblank_flag = True # NBA and mGBA raise HBlank IRQs in VBlank; GBATEK says they do not (C2: unsettled). if self.dispstat & 0x10: self.scheduler.add(1, self._hblank_irq) self.scheduler.add(LINE - HBLANK_START, self._hdraw_vblank) def _update_vcount_flag(self, _: int) -> None: match = (self.dispstat >> 8) == self.vcount if self.dispstat & 0x20 and not self.vcount_flag and match: self.scheduler.add(1, self._vcount_irq, priority=1) self.vcount_flag = match def _video_dma_line(self) -> None: if self.video_dma: if self.vcount == 162: self.dma.stop_video() elif 2 <= self.vcount < 162: self.scheduler.add(3, self._request_video_dma) def _request_video_dma(self, _: int) -> None: self.dma.request_video() def _vblank_irq(self, _: int) -> None: self.irq.raise_(VBLANK) def _hblank_irq(self, _: int) -> None: self.irq.raise_(HBLANK) def _vcount_irq(self, _: int) -> None: self.irq.raise_(VCOUNT) # ----- the picture -------------------------------------------------------------------- def _begin_line(self) -> None: """Cycle 0 of every line: affine reference points, the window's vertical flags, and the window engine's (and on request the dot engine's) start.""" line = self.vcount now = self.scheduler.now self.line_start = now if line < VISIBLE_LINES: for bg in (0, 1): for axis in (0, 1): # a write takes effect at the next line start; line 0 reloads both if self.affine_dirty[bg][axis] or line == 0: self.affine_current[bg][axis] = self.affine_written[bg][axis] self.affine_dirty[bg][axis] = False if EXACT: self.dot = DotLine(self, now) winv = self.registers[0x44 >> 1], self.registers[0x46 >> 1] for window in (0, 1): if line == winv[window] >> 8: # top edge (inclusive) self.window_v[window] = True if line == winv[window] & 0xFF: # bottom edge (exclusive) self.window_v[window] = False self.window_cycle = 0 # the horizontal flags run on through VBlank too def _end_visible_line(self) -> None: """Cycle 1232 of a visible line: the BG mosaic counter and the affine steps.""" line = self.vcount if line >= VISIBLE_LINES: return size_y = (self.registers[0x4C >> 1] >> 4 & 15) + 1 if line < VISIBLE_LINES - 1: self.bg_mosaic_y += 1 self.bg_mosaic_y = 0 if self.bg_mosaic_y == size_y else self.bg_mosaic_y & 15 else: self.bg_mosaic_y = 0 dispcnt = self.registers[0] enabled = self.dispcnt_latch[0] & dispcnt mode = dispcnt & 7 for bg, active in ((0, 1 <= mode <= 5), (1, mode == 2)): # the internal point only steps while the BG is enabled (NBA, "confirmed on real # hardware"); with mosaic it steps size_y lines at once if not active or not enabled & 0x400 << bg: continue base = (0x20 + 0x10 * bg) >> 1 pb, pd = _s16(self.registers[base + 1]), _s16(self.registers[base + 3]) current = self.affine_current[bg] if self.registers[(0x0C >> 1) + bg] & 0x40: if self.bg_mosaic_y == 0: current[0] += size_y * pb current[1] += size_y * pd else: current[0] += pb current[1] += pd def _latch_and_objects(self, _: int) -> None: """Cycle 40 of every line: DISPCNT's latch, then the OBJ engine hands over the line it fetched and starts on the next.""" line = self.vcount if line <= VISIBLE_LINES or line >= 225: latch = self.dispcnt_latch latch[0], latch[1], latch[2] = latch[1], latch[2], self.registers[0] if line == LINES - 1 or line < VISIBLE_LINES: engine = self.obj_engine if engine is not None: engine.run(engine.steps) # the rest of its window: nothing it reads changed self.objects = engine.out self.obj_engine = None if line == LINES - 1 or (line < VISIBLE_LINES and line != VISIBLE_LINES - 1): target = (line + 1) % LINES self.obj_engine = objects.Engine(self, target, self.obj_mosaic_y) self.obj_start = self.scheduler.now size_y = (self.registers[0x4C >> 1] >> 12) + 1 if target < VISIBLE_LINES - 1: self.obj_mosaic_y += 1 self.obj_mosaic_y = 0 if self.obj_mosaic_y == size_y else self.obj_mosaic_y & 15 else: self.obj_mosaic_y = 0 self.scheduler.add(LINE, self._latch_and_objects) def _sync_window(self, now: int) -> None: """Run WIN0's and WIN1's horizontal flags up to ``now``, a dot every four cycles from the line's cycle 0 to dot 255: a flag rises at the left edge and falls at the right edge (the fall wins when they are equal), reading WINxH as it goes, and carries into the next line (NBA ``DrawWindow``). ``window_buffer`` gets each dot's flag, with the vertical flag applied.""" start = self.window_cycle if start >= WINDOW_CYCLES: return cycle = min(now - self.line_start, WINDOW_CYCLES) if cycle <= start: return x0, x1 = (start + 3) >> 2, (cycle + 3) >> 2 # dots whose cycle 4x has passed self.window_cycle = cycle for window in (0, 1): winh = self.registers[(0x40 >> 1) + window] left, right = winh >> 8, winh & 0xFF flag = self.window_h[window] vertical = self.window_v[window] buffer = self.window_buffer[window] x = x0 while x < x1: if x == left: flag = True if x == right: flag = False following = x1 if x < left < following: following = left if x < right < following: following = right last = min(following, 240) if x < last: buffer[x:last] = [flag and vertical] * (last - x) x = following self.window_h[window] = flag def _draw_line(self) -> None: """HBlank of a visible line nothing changed during: draw it whole, as the dot engine would have.""" line = self.vcount self._sync_window(self.scheduler.now) registers = self.registers dispcnt = registers[0] row = [WHITE] * 240 if not (self.dispcnt_latch[0] | dispcnt) & 0x80: # forced blank: white, no fetches self._draw_visible(line, dispcnt, self.window_buffer, row) if registers[1] & 1: # green swap: each pair of dots exchanges its green for x in range(0, 240, 2): left, right = row[x], row[x + 1] row[x] = left & ~0x3E0 | right & 0x3E0 row[x + 1] = right & ~0x3E0 | left & 0x3E0 self._drawing[line * 240 : line * 240 + 240] = array("H", row) def _draw_visible( self, line: int, dispcnt: int, inside: list[list[bool]], row: list[int] ) -> None: registers = self.registers mode = dispcnt & 7 enabled = self.dispcnt_latch[0] & dispcnt # BG/OBJ enables pass the latch vram = self.vram latch = self.bg_latch boundary = self.sprite_vram_boundary drawn: list[tuple[int, int, bool, list[int]]] = [] for number in MODE_LAYERS[mode]: if not enabled & 0x100 << number: continue bgcnt = registers[(0x08 >> 1) + number] if number < 2 or mode == 0: hofs = registers[(0x10 >> 1) + 2 * number] vofs = registers[(0x12 >> 1) + 2 * number] text_y = line + vofs if bgcnt & 0x40: # mosaic: repeat the block's top line text_y -= self.bg_mosaic_y pixels = text_line(vram, bgcnt, hofs, text_y, boundary, latch) else: bg = number - 2 base = (0x20 + 0x10 * bg) >> 1 pa, pc = _s16(registers[base]), _s16(registers[base + 2]) x, y = self.affine_current[bg] if mode >= 3: pixels = bitmap_line(vram, mode, dispcnt & 0x10, x, y, pa, pc) else: pixels = affine_line(vram, bgcnt, x, y, pa, pc, latch) drawn.append((number, bgcnt & 3, bool(bgcnt & 0x40), pixels)) drawn.sort(key=lambda layer: (layer[1], layer[0])) shows_objects = bool(enabled & 0x1000) obj_line = self.objects if shows_objects else None window_masks = None win0, win1 = dispcnt & 0x2000, dispcnt & 0x4000 obj_window = dispcnt & 0x8000 and shows_objects if win0 or win1 or obj_window: winin, winout = registers[0x48 >> 1], registers[0x4A >> 1] window_masks = [] for x, (in0, in1) in enumerate(zip(*inside, strict=True)): if win0 and in0: window_masks.append(winin & 0x3F) elif win1 and in1: window_masks.append(winin >> 8 & 0x3F) elif obj_window and obj_line is not None and obj_line.window[x]: window_masks.append(winout >> 8 & 0x3F) else: window_masks.append(winout & 0x3F) compose( palette=self.palette, layers=drawn, objects=obj_line, window_masks=window_masks, bldcnt=registers[0x50 >> 1], bldalpha=registers[0x52 >> 1], bldy=registers[0x54 >> 1], mosaic=registers[0x4C >> 1], out=row, ) #: the BGs each mode shows (modes 6 and 7 show none) MODE_LAYERS = ((0, 1, 2, 3), (0, 1, 2), (2, 3), (2,), (2,), (2,), (), ()) def _s16(value: int) -> int: return value - 0x10000 if value & 0x8000 else value