# SPDX-License-Identifier: MIT """Rung 4: the picture drawn where the beam is, and the picture processor's use of video memory (docs/video.md "The dot-level model (rung 4)", "CPU access to video memory"). The picture is drawn by catching up: before anything that could change a dot not yet drawn (a write to an LCD register, palette RAM, VRAM or OAM, by the CPU or by DMA), the dots whose fetch time has passed are drawn with the state as it stood, and only then does the write land. At the end of each line the rest is drawn. When nothing changes during a line (and, for the OBJs, during the line before it) the result is the line renderer's (gba_python.ppu.line, rung 3's specification): scripts/lockstep_pictures.py checks that line by line. The rules and their evidence (constants below; every one is listed in docs/video.md "The dot model as built"): - **When a dot is fetched.** Dot x of a visible line is fetched at ``FETCH_START + 4x`` cycles after the line's VCOUNT change (``line origin``). "PPU begins to fetch the BG2 bitmap 32 cycles into the scanline. It fetches a single pixel from the bitmap every four cycles" (hw-test archive/ppu mode3, mode4: source comments, BSD-3; TEST ROM prose), and the two photographs of those ROMs (a DS-family console in GBA mode) put the band edges at dots 120 and 180 as that rule predicts relative to the H-blank DMA that writes VRAM; FETCH_START is FITTED so the board's own H-blank DMA gives those edges (scripts/hw_pictures.py ``mode3``, ``mode4``). Every layer, the palette, the windows and the colour effects are sampled at that time too (HYPOTHESIS for all but the bitmap: no permitted source gives the text BGs' tile-ahead fetch order; alyosha-tas ppu/stripes_x_offset, which writes BG0HOFS early in a line, has no stored expectation). - **Affine reference points** are taken once, at the line origin: later writes during the line reach the internal register (GBATEK; DOC) but not the line being drawn (TEST ROM: hw-test ppu/bgx, whose H-blank DMA keeps writing BG2X 240 times well into the next line, shows the value written about the line's start for the whole line). - **Green swap** is applied ``GREENSWAP_DELAY`` cycles after a dot pair's fetch: FITTED to hw-test ppu/greenswap's photograph, where an H-blank DMA's last write (0) ends the swap at about dot 81 of each line (the fetch rule alone would end it at dot 89). - **DISPCNT inside a line**: a BG is drawn at a dot only if its enable bit is set both in the line's latched copy (rung 3's two-line latch) and in DISPCNT at that dot; forced blank blanks a dot if it is set in either: "BG VRAM fetch happens only if both the latched and current BG enable bit are set", "only if both the latched and current 'forced blank' bits are cleared" (hw-test ppu/ram-access-timing, source comments: the author's hardware findings; TEST ROM prose). OBJs: "OBJ VRAM fetch happens only if the current OBJ enable bit is set (the latched one is disregarded)" and "does not seem to be affected by 'forced blank' at all" (same; TEST ROM prose), so the OBJ fetch for the next line skips the cycles while OBJs are off; their display on the line keeps rung 3's latch, ANDed with the bit at the dot (HYPOTHESIS, as for the BGs). - **OBJs one line ahead**: the OBJs of line y+1 are fetched during line y ("enable sprites at scanline 0 / will render one scanline earlier": alyosha-tas ppu/Sprite_Disable_Midline, source comment; TEST ROM). The fetch starts ``OBJ_START`` cycles after the line origin and walks OAM in order: an OBJ on the line costs n cycles for n dots, an affine one 10 + 2n over its box (GBATEK §LCD OBJ - Overview; DOC), within 1,210 cycles, or 954 with "H-Blank Interval Free" (DOC); an OBJ only part of which fits is read until the budget runs out and ends the line's OBJs (TEST ROM: alyosha-tas ppu/Sprite_Last_VRAM_Access_Free waits on VRAM in the budget's last cycles; U-VID-14); dot i of a normal OBJ is read at cycle i of its share, of an affine OBJ at 10 + 2i (HYPOTHESIS: one VRAM read per GBATEK cycle); an OBJ's attributes are read when its share begins (HYPOTHESIS). OBJs not on the line cost nothing (HYPOTHESIS, U-VID-7). OBJ_START is FITTED (alyosha-tas ppu/Sprite_Last_VRAM_Access, _Free). Lines 227 and 0-158 fetch for lines 0-159 (HYPOTHESIS). The fetch stops at the line's end whatever is left (HYPOTHESIS). - **The windows' vertical test** is a flag per window, set at a line origin whose VCOUNT equals Y1 and cleared at one whose VCOUNT equals Y2 (clear after set), in every line, V-blank included: destoer window_midframe's source prose (its author's model, "thanks fleroviux for testing this in nba"), whose expected screenshot (Powerlated's; origin not stated, H?) shows window 0 in lines 0-4 after Y1=161, Y2=5 are written in V-blank. GBATEK's "Y1>Y2 are interpreted as Y2=160" (DOC) agrees on lines Y1-159 and not on lines 0..Y2-1 of the next frame: HYPOTHESIS, provisional (U-VID-8). The horizontal test stays a compare at each dot with GBATEK's garbage rule (DOC). Video-memory contention ("a waitstate (one clock cycle) being inserted automatically in case that the display controller was accessing memory simultaneously": GBATEK §GBA Memory Map; DOC). Which cycles the picture processor uses (``busy``): - Palette: one read at each dot's fetch cycle for the top colour unless it is a direct-colour bitmap dot, and a second two cycles later when the dot is alpha-blended with a second colour from the palette: the stall patterns "1000", "1010" (blending two opaque targets, or with the backdrop as second target), "0000" (mode 3) and "0010" (mode 3 blended with the backdrop) beside the PRAM options of hw-test ppu/ram-access-timing (source comments; TEST ROM prose). Which of the four cycles is the first is not given (HYPOTHESIS: the fetch cycle). - BG VRAM: bitmap modes one read per dot at its fetch cycle (the mode3/mode4 prose above); affine BGs two reads per dot (map, then tile), BG2 in the dot's cycles 0-1 and BG3 in 2-3; text BGs, for each 8 dots, one map read and two (4 bpp) or four (8 bpp) tile reads at cycle 8 x BG number of the 32 (HYPOTHESIS throughout: no permitted source gives the order; hw-test ram-access-timing's Mode 0/2 stall maps are printed by scripts/hw_menus.py, read by eye). - OBJ VRAM: each cycle in which an OBJ dot is read (above). OAM: the 10 parameter cycles of an affine OBJ (HYPOTHESIS). """ from __future__ import annotations from gba_python.ppu.line import ( BACKDROP_LAYER, OBJ_CYCLES, OBJ_CYCLES_HBLANK_FREE, OBJ_LAYER, OBJ_SIZES, TRANSPARENT, WHITE, WIDTH, LineRenderer, blend, brighten, darken, signed16, ) # Cycles from the line origin (VCOUNT's change) to dot 0's fetch; dot x at FETCH_START + 4x. # FITTED to the hw-test archive mode3/mode4 photographs (band edges at dots 120 and 180). FETCH_START = 37 # Cycles from a dot pair's fetch to the green swap being applied to it. FITTED to hw-test # ppu/greenswap's photograph (the swap ends at about dot 81). GREENSWAP_DELAY = 34 # Cycles from the line origin to the OBJ fetch for the next line. FITTED (alyosha-tas # ppu/Sprite_Last_VRAM_Access, _Free). OBJ_START = 16 LAST_FETCH = FETCH_START + 4 * (WIDTH - 1) # Text BGs' VRAM reads per 8 dots (a map entry, then the tile row as 16-bit reads) and where # in the 32 cycles BG n's reads begin (8n + TEXT_SLOT). HYPOTHESIS. destoer lyc_midline's # photograph bounds the total: its printing code (VRAM writes during drawing) must wait 37 # cycles; 3 reads give 54-63 at every slot, 2 reads 0-8, so whole contiguous reads cannot fit # it (docs/validation.md "Rung 4"; U-VID-11 stays open). 3 is kept: the 16-bit reasoning, and # nearer the photograph. TEXT_READS_4BPP = 3 TEXT_READS_8BPP = 3 TEXT_SLOT = 0 PALETTE, VRAM, OAM = 5, 6, 7 class DotRenderer: """The line being drawn, the OBJs being fetched for the next line, and the cycles the picture processor uses video memory. Fields stay under PyPy's 80-attribute limit.""" def __init__(self, ppu, bus) -> None: self.ppu = ppu self.bus = bus self.y = -1 # the visible line being drawn, or -1 self.origin = 0 # the line origin of the current line (VCOUNT's change) self.next_x = WIDTH # the first dot not yet drawn self.out = [WHITE] * WIDTH self.raw = [WHITE] * WIDTH # before green swap self.display = 0 # DISPCNT's latched display bits for the line (ppu.latch_display) self.ref = [0, 0, 0, 0] # the affine reference points taken at the line origin self.mosaic_ref = [0, 0, 0, 0] self.win_v = [False, False] # the windows' vertical flags for the line self.swap_log: list = [] # (time, green swap) writes during the line self.swap_start = 0 # Per dot, how many palette reads the dot made and when (for ``busy``). self.pram_top = [False] * WIDTH self.pram_second = [False] * WIDTH self.bg = [[TRANSPARENT] * WIDTH for _ in range(4)] self.window = [0x3F] * WIDTH # The OBJs of the line being drawn (fetched during the previous line): per dot the # palette byte address of the top-most OBJ's colour (-1 none), the best priority, the # semi-transparency, and the OBJ window mask. self.obj_addr = [TRANSPARENT] * WIDTH self.obj_prio = [4] * WIDTH self.obj_semi = [False] * WIDTH self.obj_win = [False] * WIDTH # The OBJs being fetched for the next line. self.f_addr = [TRANSPARENT] * WIDTH self.f_prio = [4] * WIDTH self.f_semi = [False] * WIDTH self.f_win = [False] * WIDTH self.f_line = -1 # the line being fetched for, or -1 when no fetch is running self.f_time = 0 # the fetch cursor: the next cycle to account for self.f_end = 0 # when the fetch stops (budget or line end) self.f_n = 0 # the next OAM entry self.f_obj = None # the OBJ whose dots are being read: a tuple of its parameters self.f_i = 0 # its next dot self.f_dots = [TRANSPARENT] * 128 self.f_busy: list = [] # (start, end, region) cycles of the current fetch's VRAM/OAM use self.f_budget = 0 self.f_bitmap = False self.f_one_d = False self.writes = 0 # picture-affecting writes so far (scripts/lockstep_pictures.py) # ---------------------------------------------------------------------------------- # The line def begin_line(self, y: int, origin: int) -> None: """A visible line starts at its origin: latch what the line takes once.""" ppu = self.ppu self.y = y self.origin = origin self.next_x = 0 self.display = ppu.display self.swap_log = [] self.swap_start = ppu.regs[1] & 1 # The OBJs fetched during the previous line become this line's. self.obj_addr, self.f_addr = self.f_addr, self.obj_addr self.obj_prio, self.f_prio = self.f_prio, self.obj_prio self.obj_semi, self.f_semi = self.f_semi, self.obj_semi self.obj_win, self.f_win = self.f_win, self.obj_win if self.f_line != y: # Nothing was fetched for this line (power-on): no OBJs. for x in range(WIDTH): self.obj_addr[x] = TRANSPARENT self.obj_prio[x] = 4 self.obj_semi[x] = False self.obj_win[x] = False self.f_line = -1 def take_references(self) -> None: """The affine reference points for the whole line (gba_python.ppu.timing REFERENCE_LATCH; hw-test ppu/bgx, TEST ROM).""" self.ref[:] = self.ppu.ref self.mosaic_ref[:] = self.ppu.mosaic_ref def finish_line(self) -> list[int] | None: """Draw what is left of the line and apply green swap; returns the finished line.""" if self.y < 0: return None self.draw_to(WIDTH) raw = self.raw out = self.out log = self.swap_log swap = self.swap_start k = 0 base = self.origin + FETCH_START + GREENSWAP_DELAY for x in range(0, WIDTH, 2): # The pair's swap is the register's value when the pair's first dot is output. at = base + 4 * x while k < len(log) and log[k][0] <= at: swap = log[k][1] k += 1 a, b = raw[x], raw[x + 1] if swap: out[x] = (a & ~0x3E0) | (b & 0x3E0) out[x + 1] = (b & ~0x3E0) | (a & 0x3E0) else: out[x] = a out[x + 1] = b self.y = -1 return out def note_greenswap(self, time: int, value: int) -> None: if self.y >= 0: self.swap_log.append((time, value & 1)) # ---------------------------------------------------------------------------------- # Catching up def note_write(self, time: int) -> None: """A write that may change the picture is about to land at ``time``: draw what was fetched before it.""" self.writes += 1 self.catch_up(time) def catch_up(self, time: int) -> None: """Draw every dot fetched before ``time`` and run the OBJ fetch up to it.""" if self.y >= 0 and self.next_x < WIDTH: reach = time - self.origin - FETCH_START if reach > 0: self.draw_to(min(WIDTH, (reach + 3) >> 2)) if self.f_line >= 0 and self.f_time < time: self.fetch_objs(time) def draw_to(self, end: int) -> None: start = self.next_x if end <= start: return self.next_x = end ppu = self.ppu regs = ppu.regs dispcnt = regs[0] latched = self.display raw = self.raw if (latched | dispcnt) & 0x80: # Forced blank in the latched copy or now (TEST ROM prose, above). for x in range(start, end): raw[x] = WHITE self.pram_top[x] = False self.pram_second[x] = False return enabled = latched & dispcnt mode = latched & 7 layers = [] if mode == 0: kinds = ((0, 0), (1, 0), (2, 0), (3, 0)) elif mode == 1: kinds = ((0, 0), (1, 0), (2, 1)) elif mode == 2: kinds = ((2, 1), (3, 1)) elif mode <= 5: kinds = ((2, 2),) else: kinds = () # modes 6-7: no BGs (HYPOTHESIS, U-VID-5) y = self.y for bg, kind in kinds: if not enabled & (0x100 << bg): continue buffer = self.bg[bg] if kind == 0: self.text_span(bg, y, start, end, buffer) elif kind == 1: self.affine_span(bg, start, end, buffer) else: self.bitmap_span(mode, latched, start, end, buffer) layers.append((regs[4 + bg] & 3, bg, buffer)) layers.sort() obj_on = enabled & 0x1000 self.window_span(start, end, dispcnt, obj_on) self.compose_span(start, end, layers, obj_on, mode >= 3 and mode != 4) # ---------------------------------------------------------------------------------- # Backgrounds (the formulas of gba_python.ppu.line, per dot; DOC as cited there) def text_span(self, bg: int, y: int, start: int, end: int, out: list[int]) -> None: regs = self.ppu.regs vram = self.bus.vram palette = self.bus.palette control = regs[4 + bg] hofs = regs[8 + 2 * bg] & 0x1FF vofs = regs[9 + 2 * bg] & 0x1FF mosaic = control & 0x40 msize = 1 if mosaic: vsize = ((regs[0x26] >> 4) & 0xF) + 1 y -= y % vsize msize = (regs[0x26] & 0xF) + 1 char_base = ((control >> 2) & 3) * 0x4000 screen_base = ((control >> 8) & 0x1F) * 0x800 eight_bpp = control & 0x80 size = (control >> 14) & 3 wide = size & 1 tall = size & 2 sy = (y + vofs) & (0x1FF if tall else 0xFF) ty = sy >> 3 row_in_tile = sy & 7 block_row = (ty >> 5) * (2 if wide else 1) width_mask = 0x1FF if wide else 0xFF last_tx = -1 entry = 0 row = b"" for x in range(start, end): source = x - x % msize if msize > 1 else x sx = (source + hofs) & width_mask tx = sx >> 3 if tx != last_tx: last_tx = tx at = ( screen_base + ((tx >> 5) + block_row) * 0x800 + ((ty & 31) * 32 + (tx & 31)) * 2 ) at %= 0x18000 entry = vram[at] | vram[at + 1] << 8 tile = entry & 0x3FF py = 7 - row_in_tile if entry & 0x800 else row_in_tile if eight_bpp: first = char_base + tile * 64 + py * 8 row = ( vram[first : first + 8] if first < 0x10000 else bytes((entry & 0xFF, entry >> 8)) * 4 ) else: first = char_base + tile * 32 + py * 4 row = ( vram[first : first + 4] if first < 0x10000 else bytes((entry & 0xFF, entry >> 8)) * 2 ) i = sx & 7 if entry & 0x400: i = 7 - i if eight_bpp: index = row[i] out[x] = ( (palette[index * 2] | palette[index * 2 + 1] << 8) & 0x7FFF if index else -1 ) else: index = (row[i >> 1] >> ((i & 1) << 2)) & 0xF if index: at = ((entry >> 12) << 5) + index * 2 out[x] = (palette[at] | palette[at + 1] << 8) & 0x7FFF else: out[x] = TRANSPARENT def affine_span(self, bg: int, start: int, end: int, out: list[int]) -> None: regs = self.ppu.regs vram = self.bus.vram palette = self.bus.palette control = regs[4 + bg] base = 0x10 if bg == 2 else 0x18 pa = signed16(regs[base]) pc = signed16(regs[base + 2]) mosaic = control & 0x40 i = 0 if bg == 2 else 2 ref = self.mosaic_ref if mosaic else self.ref ref_x, ref_y = ref[i], ref[i + 1] msize = (regs[0x26] & 0xF) + 1 if mosaic else 1 char_base = ((control >> 2) & 3) * 0x4000 screen_base = ((control >> 8) & 0x1F) * 0x800 size_shift = 7 + ((control >> 14) & 3) size = 1 << size_shift mask = size - 1 tiles_shift = size_shift - 3 wrap = control & 0x2000 for x in range(start, end): source = x - x % msize if msize > 1 else x tx = (ref_x + pa * source) >> 8 ty = (ref_y + pc * source) >> 8 if wrap: tx &= mask ty &= mask elif tx < 0 or ty < 0 or tx >= size or ty >= size: out[x] = TRANSPARENT continue at = (screen_base + ((ty >> 3) << tiles_shift) + (tx >> 3)) % 0x18000 tile = vram[at] index = vram[char_base + tile * 64 + (ty & 7) * 8 + (tx & 7)] out[x] = (palette[index * 2] | palette[index * 2 + 1] << 8) & 0x7FFF if index else -1 def bitmap_span(self, mode: int, latched: int, start: int, end: int, out: list[int]) -> None: regs = self.ppu.regs vram = self.bus.vram palette = self.bus.palette control = regs[6] pa = signed16(regs[0x10]) pc = signed16(regs[0x12]) mosaic = control & 0x40 ref = self.mosaic_ref if mosaic else self.ref ref_x, ref_y = ref[0], ref[1] msize = (regs[0x26] & 0xF) + 1 if mosaic else 1 # Frame select is read at the dot (HYPOTHESIS, like the other registers). page = 0xA000 if regs[0] & 0x10 and mode != 3 else 0 width, height = (160, 128) if mode == 5 else (240, 160) for x in range(start, end): source = x - x % msize if msize > 1 else x tx = (ref_x + pa * source) >> 8 ty = (ref_y + pc * source) >> 8 if tx < 0 or ty < 0 or tx >= width or ty >= height: out[x] = TRANSPARENT elif mode == 4: index = vram[page + ty * 240 + tx] out[x] = ( (palette[index * 2] | palette[index * 2 + 1] << 8) & 0x7FFF if index else -1 ) else: at = page + (ty * width + tx) * 2 out[x] = (vram[at] | vram[at + 1] << 8) & 0x7FFF # ---------------------------------------------------------------------------------- # Windows def begin_window_flags(self, vcount: int) -> None: """At every line origin: each window's vertical flag is set when VCOUNT equals its Y1 and cleared when it equals its Y2, the clear after the set (destoer window_midframe; HYPOTHESIS, provisional, U-VID-8; docstring above).""" regs = self.ppu.regs for win in (0, 1): value = regs[0x22 + win] if vcount == value >> 8: self.win_v[win] = True if vcount == value & 0xFF: self.win_v[win] = False def window_span(self, start: int, end: int, dispcnt: int, obj_on: int) -> None: window = self.window if not dispcnt & 0xE000: for x in range(start, end): window[x] = 0x3F return regs = self.ppu.regs outside = regs[0x25] & 0x3F for x in range(start, end): window[x] = outside if dispcnt & 0x8000 and obj_on: inside = (regs[0x25] >> 8) & 0x3F mask = self.obj_win for x in range(start, end): if mask[x]: window[x] = inside for win in (1, 0): if not dispcnt & (0x2000 << win) or not self.win_v[win]: continue left, right = LineRenderer.window_span(regs[0x20 + win], WIDTH) inside = (regs[0x24] >> (8 * win)) & 0x3F for x in range(max(start, left), min(end, right)): window[x] = inside # ---------------------------------------------------------------------------------- # Priority and colour effects (gba_python.ppu.line.compose, per dot) def compose_span(self, start, end, layers, obj_on, direct) -> None: regs = self.ppu.regs palette = self.bus.palette backdrop = (palette[0] | palette[1] << 8) & 0x7FFF bldcnt = regs[0x28] effect = (bldcnt >> 6) & 3 first_targets = bldcnt & 0x3F second_targets = (bldcnt >> 8) & 0x3F alpha = regs[0x29] eva = min(alpha & 0x1F, 16) evb = min((alpha >> 8) & 0x1F, 16) evy = min(regs[0x2A] & 0x1F, 16) window = self.window obj_addr = self.obj_addr obj_prio = self.obj_prio obj_semi = self.obj_semi raw = self.raw pram_top = self.pram_top pram_second = self.pram_second for x in range(start, end): enabled = window[x] top = second = backdrop top_layer = second_layer = BACKDROP_LAYER found = 0 addr = obj_addr[x] if obj_on and enabled & 0x10 else TRANSPARENT obj = (palette[addr] | palette[addr + 1] << 8) & 0x7FFF if addr >= 0 else TRANSPARENT obj_p = obj_prio[x] for p, bg, buffer in layers: if obj >= 0 and obj_p <= p: if found == 0: top, top_layer = obj, OBJ_LAYER found = 1 else: second, second_layer = obj, OBJ_LAYER found = 2 break obj = TRANSPARENT if not enabled & (1 << bg): continue dot = buffer[x] if dot < 0: continue if found == 0: top, top_layer = dot, bg found = 1 else: second, second_layer = dot, bg found = 2 break if found < 2 and obj >= 0: if found == 0: top, top_layer = obj, OBJ_LAYER else: second, second_layer = obj, OBJ_LAYER blended = False if enabled & 0x20: if top_layer == OBJ_LAYER and obj_semi[x] and second_targets & (1 << second_layer): top = blend(top, second, eva, evb) blended = True elif first_targets & (1 << top_layer): if effect == 1: if second_targets & (1 << second_layer) and second_layer != top_layer: top = blend(top, second, eva, evb) blended = True elif effect == 2: top = brighten(top, evy) elif effect == 3: top = darken(top, evy) raw[x] = top # Palette reads (ram-access-timing PRAM comments): the top colour unless a # direct-colour bitmap dot; the second when blended, unless a bitmap dot. pram_top[x] = not (direct and top_layer == 2) pram_second[x] = blended and not (direct and second_layer == 2) # ---------------------------------------------------------------------------------- # The OBJ fetch for the next line def begin_obj_fetch(self, line: int, origin: int) -> None: dispcnt = self.ppu.regs[0] self.f_line = line self.f_time = origin + OBJ_START # The budget's base is DISPCNT bit 5 when the fetch starts (HYPOTHESIS). self.f_budget = OBJ_CYCLES_HBLANK_FREE if dispcnt & 0x20 else OBJ_CYCLES self.f_end = min(origin + 1232, self.f_time + self.f_budget) self.f_n = 0 self.f_obj = None self.f_busy = [] self.f_bitmap = (dispcnt & 7) >= 3 self.f_one_d = bool(dispcnt & 0x40) for x in range(WIDTH): self.f_addr[x] = TRANSPARENT self.f_prio[x] = 4 self.f_semi[x] = False self.f_win[x] = False def finish_obj_fetch(self, time: int) -> None: if self.f_line >= 0: self.fetch_objs(time) def fetch_objs(self, time: int) -> None: """Run the OBJ fetch from its cursor up to ``time`` (not including it).""" limit = min(time, self.f_end) oam = self.bus.oam on = self.ppu.regs[0] & 0x1000 # the current OBJ enable (TEST ROM prose, above) while self.f_time < limit: obj = self.f_obj if obj is None: if self.f_n >= 128: self.f_time = self.f_end break obj = self.next_obj(oam) if obj is None: continue if obj == "end": self.f_time = self.f_end break # Read the OBJ's dots whose cycle has come. (start, cost, affine, box_w) = obj[0], obj[1], obj[2], obj[3] i = self.f_i while i < box_w: at = start + (10 + 2 * i if affine else i) if at >= limit: break if on: self.f_dots[i] = self.obj_dot_at(obj, i) self.place(obj, i) else: self.f_dots[i] = TRANSPARENT i += 1 self.f_i = i if i >= box_w: self.f_time = start + cost self.f_obj = None self.f_n += 1 if self.f_time > limit: break else: self.f_time = limit break def next_obj(self, oam): """Read OAM entry ``f_n`` at the cursor: None to skip it (costs nothing), "end" when it does not fit, else the OBJ's parameters (rung 3's rules, gba_python.ppu.line).""" n = self.f_n at = n * 8 a0 = oam[at] | oam[at + 1] << 8 affine = a0 & 0x100 if (not affine and a0 & 0x200) or a0 >> 14 == 3: self.f_n += 1 return None a1 = oam[at + 2] | oam[at + 3] << 8 width, height = OBJ_SIZES[a0 >> 14][a1 >> 14] double = affine and a0 & 0x200 box_w = width * 2 if double else width box_h = height * 2 if double else height y = self.f_line line = (y - (a0 & 0xFF)) & 0xFF if line >= box_h: self.f_n += 1 return None cost = 10 + 2 * box_w if affine else width if cost > self.f_budget: # Only part fits: its dots are read until the budget runs out, and no OBJ after # it (U-VID-14; gba_python.ppu.line, TEST ROM Sprite_Last_VRAM_Access_Free). if self.f_budget <= (10 if affine else 0): return "end" cost = self.f_budget self.f_budget -= cost a2 = oam[at + 4] | oam[at + 5] << 8 obj_mode = (a0 >> 10) & 3 obj_x = a1 & 0x1FF if obj_x >= 256: obj_x -= 512 mosaic = self.ppu.regs[0x26] mosaic_h = ((mosaic >> 8) & 0xF) + 1 mosaic_v = ((mosaic >> 12) & 0xF) + 1 mosaic_on = a0 & 0x1000 if mosaic_on and mosaic_v > 1: line = (y - y % mosaic_v - (a0 & 0xFF)) & 0xFF if line >= box_h: line = 0 eight_bpp = a0 & 0x2000 tile_base = a2 & 0x3FF one_d = self.f_one_d if eight_bpp: if not one_d: tile_base &= ~1 row_step = (width >> 3) * 2 if one_d else 32 else: row_step = (width >> 3) if one_d else 32 params = None if affine: group = ((a1 >> 9) & 0x1F) * 32 pa = signed16(oam[group + 6] | oam[group + 7] << 8) pb = signed16(oam[group + 14] | oam[group + 15] << 8) pc = signed16(oam[group + 22] | oam[group + 23] << 8) pd = signed16(oam[group + 30] | oam[group + 31] << 8) dy = line - (box_h >> 1) params = ( pa, pc, pb * dy - pa * (box_w >> 1), pd * dy - pc * (box_w >> 1), ) start = self.f_time obj = ( start, cost, affine, box_w, width, height, line, a1, eight_bpp, tile_base, row_step, params, obj_mode, obj_x, (a2 >> 10) & 3, 0x200 + ((a2 >> 12) << 5), mosaic_h if mosaic_on else 1, ) if affine: self.f_busy.append((start, start + 10, OAM)) self.f_busy.append((start + 10, start + cost, VRAM)) else: self.f_busy.append((start, start + cost, VRAM)) if len(self.f_busy) > 8: del self.f_busy[:-8] self.f_obj = obj self.f_i = 0 return obj def obj_dot_at(self, obj, i: int) -> int: width, height, line, a1 = obj[4], obj[5], obj[6], obj[7] eight_bpp, tile_base, row_step, params = obj[8], obj[9], obj[10], obj[11] lowest = 0x14000 if self.f_bitmap else 0x10000 vram = self.bus.vram if params is not None: pa, pc, start_x, start_y = params tx = ((start_x + pa * i) >> 8) + (width >> 1) ty = ((start_y + pc * i) >> 8) + (height >> 1) if not (0 <= tx < width and 0 <= ty < height): return TRANSPARENT else: ty = height - 1 - line if a1 & 0x2000 else line tx = width - 1 - i if a1 & 0x1000 else i return LineRenderer.obj_dot(vram, tile_base, row_step, tx, ty, eight_bpp, lowest) def place(self, obj, i: int) -> None: """Put dot i of the OBJ on the line being fetched, as rung 3 places it.""" obj_x = obj[13] x = obj_x + i if x < 0 or x >= WIDTH: return mosaic_h = obj[16] if mosaic_h > 1: source = x - x % mosaic_h - obj_x index = self.f_dots[max(source, 0)] else: index = self.f_dots[i] if index < 0: return if obj[12] == 2: self.f_win[x] = True return if obj[12] == 3: return # prohibited mode: not drawn (HYPOTHESIS, U-VID-5) self.f_prio[x] = min(self.f_prio[x], obj[14]) if self.f_addr[x] >= 0: return self.f_addr[x] = 0x200 + index * 2 if obj[8] else obj[15] + index * 2 self.f_semi[x] = obj[12] == 1 # ---------------------------------------------------------------------------------- # Contention def busy(self, region: int, address: int, time: int) -> bool: """Does the picture processor use this memory in cycle ``time``?""" if region == PALETTE: if self.y < 0: return False offset = time - self.origin - FETCH_START if offset < 0 or offset >= 4 * WIDTH: return False x = offset >> 2 phase = offset & 3 if phase != 0 and phase != 2: return False if (self.display | self.ppu.regs[0]) & 0x80: return False self.catch_up(time + 1) return self.pram_top[x] if phase == 0 else self.pram_second[x] if region == VRAM: offset = address & 0x1FFFF if offset >= 0x18000: offset -= 0x8000 obj_area = offset >= (0x14000 if self.ppu.regs[0] & 7 >= 3 else 0x10000) if obj_area: return self.obj_busy(time, VRAM) return self.bg_busy(time) return self.obj_busy(time, OAM) def obj_busy(self, time: int, region: int) -> bool: if self.f_line < 0 or time < self.f_time - 2000: return False self.catch_up(time + 1) if not self.ppu.regs[0] & 0x1000: return False for start, end, kind in self.f_busy: if kind == region and start <= time < end: return True return False def bg_busy(self, time: int) -> bool: if self.y < 0: return False offset = time - self.origin - FETCH_START if offset < 0 or offset >= 4 * WIDTH: return False ppu = self.ppu dispcnt = ppu.regs[0] latched = self.display if (latched | dispcnt) & 0x80: return False enabled = latched & dispcnt mode = latched & 7 phase = offset & 3 if mode >= 3: return mode <= 5 and bool(enabled & 0x400) and phase == 0 if mode == 2 or mode == 1: if enabled & 0x400 and phase < 2: return True if mode == 2 and enabled & 0x800 and phase >= 2: return True if mode == 2: return False group = offset & 31 for bg in (0, 1) if mode == 1 else (0, 1, 2, 3): if not enabled & (0x100 << bg): continue first = 8 * bg + TEXT_SLOT reads = TEXT_READS_8BPP if ppu.regs[4 + bg] & 0x80 else TEXT_READS_4BPP if first <= group < first + reads: return True return False