# SPDX-License-Identifier: MIT """Rung 3: the picture, a line at a time. One visible line is drawn whole from the registers, video memory, palette and OAM as they stand at the line's start (docs/video.md "The dot-level model (rung 4)": changes made while a line is being drawn are rung 4's). The rules and their evidence: - Backgrounds, modes 0-5 (GBATEK §LCD I/O Display Control, §LCD I/O BG Control, §LCD I/O BG Scrolling, §LCD I/O BG Rotation/Scaling, §LCD VRAM BG Screen Data Format, §LCD VRAM Character Data, §LCD VRAM Bitmap BG Modes; DOC). The affine reference points' internal registers live in gba_python.ppu.timing (they are latched by the line events). - OBJs (GBATEK §LCD OBJ - Overview, OAM Attributes, OAM Rotation/Scaling Parameters, VRAM Character (Tile) Mapping; DOC). - Windows (§LCD I/O Window Feature; DOC), colour special effects (§LCD I/O Color Special Effects; DOC), mosaic (§LCD I/O Mosaic Function; DOC), green swap (§LCD I/O Display Control, "4000002h"; DOC), forced blank (same section; DOC). Where no permitted source decides, the choice is marked HYPOTHESIS and listed in docs/video.md "The line renderer as built", with the test that would settle it. Colours are 15-bit BGR values (bit 15 dropped); a transparent dot is -1. """ from __future__ import annotations WIDTH = 240 WHITE = 0x7FFF TRANSPARENT = -1 BACKDROP_LAYER = 5 # BLDCNT's layer numbering: BG0-3 = 0-3, OBJ = 4, backdrop = 5 OBJ_LAYER = 4 # OBJ sizes by shape and size (GBATEK §LCD OBJ - OAM Attributes, attribute 1; DOC). Shape 3 # is "prohibited": such OBJs are not drawn (HYPOTHESIS, U-VID-5). OBJ_SIZES = ( ((8, 8), (16, 16), (32, 32), (64, 64)), ((16, 8), (32, 8), (32, 16), (64, 32)), ((8, 16), (8, 32), (16, 32), (32, 64)), ) # OBJ rendering cycles per line (GBATEK §LCD OBJ - Overview, "Maximum Number of Sprites per # Line"; DOC): 1,210 (304*4-6), or 954 (240*4-6) with "H-Blank Interval Free". OBJ_CYCLES = 1210 OBJ_CYCLES_HBLANK_FREE = 954 def signed16(value: int) -> int: return value - 0x10000 if value & 0x8000 else value class LineRenderer: """Draws one line into a 240-entry list. Holds no state of its own between lines except scratch buffers: everything it reads belongs to the bus (memories) or the PPU (registers, affine reference points).""" def __init__(self, ppu, bus) -> None: self.ppu = ppu self.bus = bus self.bg_buffers = [[TRANSPARENT] * WIDTH for _ in range(4)] self.obj_color = [TRANSPARENT] * WIDTH self.obj_prio = [4] * WIDTH self.obj_semi = [False] * WIDTH self.obj_window = [False] * WIDTH self.window = [0x3F] * WIDTH # ---------------------------------------------------------------------------------- def render(self, y: int, out: list[int]) -> None: regs = self.ppu.regs dispcnt = self.ppu.display # DISPCNT as latched for this line (ppu.timing) if dispcnt & 0x80: # Forced blank: white lines (§LCD I/O Display Control; DOC). for x in range(WIDTH): out[x] = WHITE return mode = dispcnt & 7 # Which BGs a mode has, and how each is drawn (§LCD I/O Display Control table; DOC). # Modes 6 and 7 are prohibited: no BG is drawn (HYPOTHESIS, U-VID-5). if mode == 0: kinds = ((0, "text"), (1, "text"), (2, "text"), (3, "text")) elif mode == 1: kinds = ((0, "text"), (1, "text"), (2, "affine")) elif mode == 2: kinds = ((2, "affine"), (3, "affine")) elif mode <= 5: kinds = ((2, "bitmap"),) else: kinds = () layers = [] for bg, kind in kinds: if not dispcnt & (0x100 << bg): continue buffer = self.bg_buffers[bg] if kind == "text": self.text_line(bg, y, buffer) elif kind == "affine": self.affine_line(bg, buffer) else: self.bitmap_line(mode, dispcnt, buffer) # Lower priority numbers are on top; equal priorities: BG0 first (§LCD I/O BG # Control; DOC). layers.append((regs[4 + bg] & 3, bg, buffer)) layers.sort() obj_on = dispcnt & 0x1000 if obj_on: self.obj_line(y, mode, dispcnt) self.window_line(y, dispcnt, obj_on) self.compose(out, layers, obj_on) if regs[1] & 1: # Green swap: each pair of dots exchanges its green intensities, on the final # picture (GBATEK "4000002h - Undocumented - Green Swap"; DOC). for x in range(0, WIDTH, 2): a, b = out[x], out[x + 1] out[x] = (a & ~0x3E0) | (b & 0x3E0) out[x + 1] = (b & ~0x3E0) | (a & 0x3E0) # ---------------------------------------------------------------------------------- # Backgrounds def mosaic_h(self, buffer: list[int], size: int) -> None: """Horizontal mosaic: dots 0..size-1 show dot 0, and so on, counted from the left edge of the screen (§LCD I/O Mosaic Function, "pixels 0-5 of each display row are colorized as pixel 0"; DOC).""" if size <= 1: return for x in range(WIDTH): buffer[x] = buffer[x - x % size] def text_line(self, bg: int, y: 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 if mosaic: # Vertical mosaic counts lines from line 0 (HYPOTHESIS: docs/video.md "Mosaic"). vsize = ((regs[0x26] >> 4) & 0xF) + 1 y -= y % vsize 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 x = -(hofs & 7) sx = hofs & ~7 while x < WIDTH: tx = (sx & width_mask) >> 3 at = screen_base + ((tx >> 5) + block_row) * 0x800 + ((ty & 31) * 32 + (tx & 31)) * 2 # A map beyond the 96 KB of VRAM wraps (HYPOTHESIS; base 31 and size 3 reach # 0x11800 at most, inside VRAM, so it is never exercised). at %= 0x18000 entry = vram[at] | vram[at + 1] << 8 tile = entry & 0x3FF py = 7 - row_in_tile if entry & 0x800 else row_in_tile hflip = entry & 0x400 if eight_bpp: start = char_base + tile * 64 + py * 8 if start < 0x10000: row = vram[start : start + 8] else: # Character data beyond BG VRAM shows the map entry's value as if the # tile were filled with it (GBATEK §GBA Unpredictable Things; DOC, for a # single layer; with more layers GBATEK says it is "more complicated": # U-VID-6, not modelled). row = bytes((entry & 0xFF, entry >> 8)) * 4 for i in range(8): px = x + i if 0 <= px < WIDTH: index = row[7 - i] if hflip else row[i] out[px] = ( (palette[index * 2] | palette[index * 2 + 1] << 8) & 0x7FFF if index else TRANSPARENT ) else: start = char_base + tile * 32 + py * 4 if start < 0x10000: row = vram[start : start + 4] else: row = bytes((entry & 0xFF, entry >> 8)) * 2 # as above (DOC; U-VID-6) bank = (entry >> 12) << 5 for i in range(8): px = x + i if 0 <= px < WIDTH: j = 7 - i if hflip else i index = (row[j >> 1] >> ((j & 1) << 2)) & 0xF if index: at = bank + index * 2 out[px] = (palette[at] | palette[at + 1] << 8) & 0x7FFF else: out[px] = TRANSPARENT x += 8 sx += 8 if mosaic: self.mosaic_h(out, (regs[0x26] & 0xF) + 1) def affine_line(self, bg: int, out: list[int]) -> None: ppu = self.ppu regs = 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 ref_x, ref_y = ppu.affine_origin(bg, mosaic) char_base = ((control >> 2) & 3) * 0x4000 screen_base = ((control >> 8) & 0x1F) * 0x800 size_shift = 7 + ((control >> 14) & 3) # 128 << size dots square (DOC) size = 1 << size_shift mask = size - 1 tiles_shift = size_shift - 3 wrap = control & 0x2000 # display area overflow: wrap or transparent (DOC) for x in range(WIDTH): tx = (ref_x + pa * x) >> 8 ty = (ref_y + pc * x) >> 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 # HYPOTHESIS 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 if mosaic: self.mosaic_h(out, (regs[0x26] & 0xF) + 1) def bitmap_line(self, mode: int, dispcnt: int, out: list[int]) -> None: """Bitmap modes are BG2 with rotation/scaling; outside the bitmap is always transparent (§LCD VRAM Bitmap BG Modes, §LCD I/O BG Rotation/Scaling "Area Overflow"; DOC). Mode 4's colour 0 is transparent; modes 3 and 5 have none (DOC).""" ppu = self.ppu regs = 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_x, ref_y = ppu.affine_origin(2, mosaic) page = 0xA000 if dispcnt & 0x10 and mode != 3 else 0 # frame select, modes 4-5 (DOC) width, height = (160, 128) if mode == 5 else (240, 160) for x in range(WIDTH): tx = (ref_x + pa * x) >> 8 ty = (ref_y + pc * x) >> 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 if mosaic: self.mosaic_h(out, (regs[0x26] & 0xF) + 1) # ---------------------------------------------------------------------------------- # OBJs def obj_line(self, y: int, mode: int, dispcnt: int) -> None: """The OBJ layer for line ``y``: per dot the top-most OBJ's colour, priority and semi-transparency, and the OBJ window mask. Among OBJs a lower OAM number is on top whatever the priorities ("OBJ0 is always having priority above OBJ1-127": GBATEK §LCD OBJ - OAM Attributes, "Priority"; DOC), so the colour (and semi-transparency) is the first non-transparent dot in OAM order. The priority compared with the BGs is the best priority of any non-transparent OBJ dot there: Tonc §24 "The object-priority bug" says that with obj1 at priority 0, bg0 at priority 0 and obj0 at priority 1, obj0 "will shine through the background in the region where the two objects overlap", and GBATEK calls the same arrangement "garbage" (DOC for the effect; HYPOTHESIS that it is exactly this mechanism). gbadoc orders OBJs by priority first (registers.md "Priority"; DOC, which contradicts the two), and so does NanoBoyAdvance (OBSERVED, the objs1d/objs2d scenes): U-VID-12.""" oam = self.bus.oam vram = self.bus.vram palette = self.bus.palette color = self.obj_color prio = self.obj_prio semi = self.obj_semi window = self.obj_window for x in range(WIDTH): color[x] = TRANSPARENT prio[x] = 4 semi[x] = False window[x] = False one_d = dispcnt & 0x40 # In bitmap modes the lower 16 KB of OBJ VRAM belongs to the BG: OBJ tiles 0-511 # "are ignored (not displayed)" (DOC); applied per dot (HYPOTHESIS for an OBJ whose # tiles straddle tile 512). lowest = 0x14000 if mode >= 3 else 0x10000 mosaic = self.ppu.regs[0x26] mosaic_h = ((mosaic >> 8) & 0xF) + 1 mosaic_v = ((mosaic >> 12) & 0xF) + 1 budget = OBJ_CYCLES_HBLANK_FREE if dispcnt & 0x20 else OBJ_CYCLES dots = [TRANSPARENT] * 128 # one OBJ's dots across its box, before placing for n in range(128): at = n * 8 a0 = oam[at] | oam[at + 1] << 8 affine = a0 & 0x100 if not affine and a0 & 0x200: continue # OBJ disable (DOC); costs nothing (HYPOTHESIS, U-VID-7) shape = a0 >> 14 if shape == 3: continue # prohibited shape (HYPOTHESIS, U-VID-5) a1 = oam[at + 2] | oam[at + 3] << 8 a2 = oam[at + 4] | oam[at + 5] << 8 width, height = OBJ_SIZES[shape][a1 >> 14] double = affine and a0 & 0x200 box_w = width * 2 if double else width box_h = height * 2 if double else height # Y wraps at 256: an OBJ at Y>128 that is 128 tall shows at the top (DOC). line = (y - (a0 & 0xFF)) & 0xFF if line >= box_h: continue # not on this line: costs nothing (HYPOTHESIS, U-VID-7) # Rendering cycles: n for a normal OBJ n dots wide, 10 + 2n for an affine one # over its (double-size) box, horizontally off-screen OBJs included (DOC). An # OBJ that does not fit in what is left draws the dots its remaining cycles # reach (dot i of a normal OBJ in cycle i, of an affine one in cycle 10 + 2i), # and no OBJ after it: rung 4 (U-VID-14), TEST ROM: alyosha-tas # ppu/Sprite_Last_VRAM_Access_Free expects the CPU to wait on VRAM in the # budget's last cycles, which only such an OBJ's reads fill; that its dots show # is HYPOTHESIS (NBA draws them, OBSERVED, scene objbudget). cost = 10 + 2 * box_w if affine else width last = box_w if cost > budget: last = (budget - 10 + 1) // 2 if affine else budget if last <= 0: break budget = 0 else: budget -= cost obj_mode = (a0 >> 10) & 3 if obj_mode == 3: continue # prohibited mode: not drawn (HYPOTHESIS, U-VID-5) obj_x = a1 & 0x1FF if obj_x >= 256: obj_x -= 512 # X is 9 bits; 256-511 lie left of the screen (DOC) if obj_x >= WIDTH or obj_x + box_w <= 0: continue mosaic_on = a0 & 0x1000 if mosaic_on and mosaic_v > 1: # OBJ vertical mosaic: the line shown is the first of its mosaic block, # counted on the screen from line 0 (HYPOTHESIS, like the BGs'); a block # starting above the OBJ shows its top line (HYPOTHESIS). line = (y - y % mosaic_v - (a0 & 0xFF)) & 0xFF if line >= box_h: line = 0 eight_bpp = a0 & 0x2000 tile_base = a2 & 0x3FF bank = 0x200 + ((a2 >> 12) << 5) if eight_bpp: # 8-bit OBJ tiles take two tile numbers; in 2D mapping the number's low bit # is ignored (DOC). 2D rows are 32 tile numbers apart; 1D rows follow on. 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 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) # The rotation centre is the middle of the OBJ and of its box (GBATEK §LCD # OBJ - OAM Rotation/Scaling Parameters; DOC): texture = P * (box dot - # box centre) + OBJ centre, 8.8 fixed point. dy = line - (box_h >> 1) half_w = width >> 1 half_h = height >> 1 start_x = pb * dy - pa * (box_w >> 1) start_y = pd * dy - pc * (box_w >> 1) for i in range(box_w): tx = ((start_x + pa * i) >> 8) + half_w ty = ((start_y + pc * i) >> 8) + half_h if 0 <= tx < width and 0 <= ty < height: dots[i] = self.obj_dot(vram, tile_base, row_step, tx, ty, eight_bpp, lowest) else: dots[i] = TRANSPARENT else: py = height - 1 - line if a1 & 0x2000 else line # vertical flip (DOC) hflip = a1 & 0x1000 for i in range(width): tx = width - 1 - i if hflip else i dots[i] = self.obj_dot(vram, tile_base, row_step, tx, py, eight_bpp, lowest) # Place the OBJ's dots on the line (only those fetched: ``last``). obj_prio = (a2 >> 10) & 3 for i in range(box_w): x = obj_x + i if x < 0 or x >= WIDTH: continue if i >= last: break if mosaic_on and mosaic_h > 1: # OBJ horizontal mosaic, counted on the screen from dot 0 as for the # BGs (HYPOTHESIS: hw-test sprite-hmosaic's expected picture is a # detector's, U-VID-10); a block starting left of the OBJ shows its # first dot (HYPOTHESIS). source = x - x % mosaic_h - obj_x index = dots[max(source, 0)] else: index = dots[i] if index < 0: continue if obj_mode == 2: window[x] = True # OBJ window dots are not drawn (DOC) continue prio[x] = min(prio[x], obj_prio) # the best priority among the OBJs here if color[x] >= 0: continue # a lower OAM number already drew this dot (DOC) if eight_bpp: at = 0x200 + index * 2 else: at = bank + index * 2 color[x] = (palette[at] | palette[at + 1] << 8) & 0x7FFF semi[x] = obj_mode == 1 @staticmethod def obj_dot(vram, tile_base, row_step, tx, ty, eight_bpp, lowest) -> int: """The palette index of an OBJ's dot (0 transparent → -1).""" if eight_bpp: tile = tile_base + (ty >> 3) * row_step + (tx >> 3) * 2 # Tile numbers wrap within the 32 KB of OBJ VRAM (HYPOTHESIS). at = 0x10000 + ((tile & 0x3FF) << 5) + ((ty & 7) << 3) + (tx & 7) if at < lowest: return TRANSPARENT index = vram[at] else: tile = tile_base + (ty >> 3) * row_step + (tx >> 3) at = 0x10000 + ((tile & 0x3FF) << 5) + ((ty & 7) << 2) + ((tx & 7) >> 1) if at < lowest: return TRANSPARENT index = (vram[at] >> ((tx & 1) << 2)) & 0xF return index if index else TRANSPARENT # ---------------------------------------------------------------------------------- # Windows def window_line(self, y: int, dispcnt: int, obj_on: int) -> None: """Per dot, the enable bits of the window region it lies in (bits 0-3 BG0-3, bit 4 OBJ, bit 5 colour effects). Window 0 over window 1 over the OBJ window over outside; with no window enabled everything is enabled (§LCD I/O Window Feature; DOC).""" window = self.window if not dispcnt & 0xE000: for x in range(WIDTH): window[x] = 0x3F return regs = self.ppu.regs outside = regs[0x25] & 0x3F for x in range(WIDTH): window[x] = outside # The OBJ window needs both DISPCNT bits 12 and 15 (DOC). if dispcnt & 0x8000 and obj_on: inside = (regs[0x25] >> 8) & 0x3F mask = self.obj_window for x in range(WIDTH): if mask[x]: window[x] = inside for win in (1, 0): if not dispcnt & (0x2000 << win): continue left, right = self.window_span(regs[0x20 + win], WIDTH) top, bottom = self.window_span(regs[0x22 + win], 160) if not top <= y < bottom: continue inside = (regs[0x24] >> (8 * win)) & 0x3F for x in range(left, right): window[x] = inside @staticmethod def window_span(value: int, limit: int) -> tuple[int, int]: """WINxH/WINxV: bits 8-15 the first dot or line, bits 0-7 the last plus one. "Garbage values of X2>240 or X1>X2 are interpreted as X2=240" (and Y2>160, Y1>Y2 as Y2=160) (§LCD I/O Window Feature; DOC).""" first = value >> 8 end = value & 0xFF if end > limit or first > end: end = limit return min(first, limit), end # ---------------------------------------------------------------------------------- # Priority and colour special effects def compose(self, out: list[int], layers: list, obj_on: int) -> 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) # 17-31 act as 16 (DOC) evb = min((alpha >> 8) & 0x1F, 16) evy = min(regs[0x2A] & 0x1F, 16) window = self.window obj_color = self.obj_color obj_prio = self.obj_prio obj_semi = self.obj_semi for x in range(WIDTH): enabled = window[x] # The top two non-transparent dots, in priority order, among the layers the # window shows; an OBJ is above BGs of its own priority (§LCD OBJ - OAM # Attributes "Priority"; DOC). The backdrop is below everything. top = second = backdrop top_layer = second_layer = BACKDROP_LAYER found = 0 obj = obj_color[x] if obj_on and enabled & 0x10 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 # Colour special effects, where the window allows them (DOC; HYPOTHESIS that the # window's bit gates semi-transparent OBJs too). if enabled & 0x20: if top_layer == OBJ_LAYER and obj_semi[x] and second_targets & (1 << second_layer): # A semi-transparent OBJ over a second target always alpha-blends, # whatever BLDCNT's effect (DOC). top = blend(top, second, eva, evb) 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) elif effect == 2: top = brighten(top, evy) elif effect == 3: top = darken(top, evy) out[x] = top def blend(a: int, b: int, eva: int, evb: int) -> int: """I = MIN(31, I1*EVA/16 + I2*EVB/16) per channel (§LCD I/O Color Special Effects; DOC); the sum is truncated once (HYPOTHESIS: U-VID-9, jsmolka and alyosha-tas `ppu/shades` are picture tests without stored expectations).""" r = ((a & 31) * eva + (b & 31) * evb) >> 4 g = (((a >> 5) & 31) * eva + ((b >> 5) & 31) * evb) >> 4 bl = (((a >> 10) & 31) * eva + ((b >> 10) & 31) * evb) >> 4 return min(r, 31) | min(g, 31) << 5 | min(bl, 31) << 10 def brighten(a: int, evy: int) -> int: """I = I1 + (31-I1)*EVY/16 (DOC; truncation HYPOTHESIS, U-VID-9).""" r, g, b = a & 31, (a >> 5) & 31, (a >> 10) & 31 r += ((31 - r) * evy) >> 4 g += ((31 - g) * evy) >> 4 b += ((31 - b) * evy) >> 4 return r | g << 5 | b << 10 def darken(a: int, evy: int) -> int: """I = I1 - I1*EVY/16 (DOC; truncation HYPOTHESIS, U-VID-9).""" r, g, b = a & 31, (a >> 5) & 31, (a >> 10) & 31 r -= (r * evy) >> 4 g -= (g * evy) >> 4 b -= (b * evy) >> 4 return r | g << 5 | b << 10