///|
pub const SCREEN_WIDTH : Int32 = 240
///|
pub const SCREEN_HEIGHT : Int32 = 160
///|
pub const CYCLES_HDRAW : Int32 = 960
///|
pub const CYCLES_HBLANK : Int32 = 272
///|
pub const CYCLES_SCANLINE : Int32 = 1232
///|
pub const SCANLINES_TOTAL : Int32 = 228
///|
pub const CYCLES_PER_FRAME : Int32 = 280896 // 1232 * 228
///|
/// Sign-extend a 28-bit affine reference register value to 32-bit signed `Int`.
pub fn sign_ext_28(v : UInt32) -> Int32 {
let masked = v & 0x0FFFFFFFU
if (masked & 0x08000000U) != 0U {
(masked | 0xF0000000U).reinterpret_as_int()
} else {
masked.reinterpret_as_int()
}
}
///|
fn sign_ext_16(v : UInt32) -> Int32 {
let m = v & 0xFFFFU
if (m & 0x8000U) != 0U {
(m | 0xFFFF0000U).reinterpret_as_int()
} else {
m.reinterpret_as_int()
}
}
///|
/// Convert a 15-bit GBA BGR555 color to `(r, g, b)` 8-bit channels.
pub fn bgr555_to_rgb(c : UInt32) -> (Byte, Byte, Byte) {
let r5 = (c & 0x1FU).reinterpret_as_int()
let g5 = ((c >> 5) & 0x1FU).reinterpret_as_int()
let b5 = ((c >> 10) & 0x1FU).reinterpret_as_int()
let r = (r5 << 3) | (r5 >> 2)
let g = (g5 << 3) | (g5 >> 2)
let b = (b5 << 3) | (b5 >> 2)
(r.to_byte(), g.to_byte(), b.to_byte())
}
///|
/// 240x160 GBA Scanline Picture Processing Unit supporting Modes 0–5 and 128 OAM sprites.
pub struct Ppu {
mut dispcnt : UInt32
mut dispstat : UInt32
mut vcount : UInt32
bgcnt : FixedArray[UInt32]
bghofs : FixedArray[UInt32]
bgvofs : FixedArray[UInt32]
// BG2 affine parameters
mut bg2pa : UInt32
mut bg2pb : UInt32
mut bg2pc : UInt32
mut bg2pd : UInt32
mut bg2x : UInt32
mut bg2y : UInt32
mut bg2x_int : Int32
mut bg2y_int : Int32
// BG3 affine parameters
mut bg3pa : UInt32
mut bg3pb : UInt32
mut bg3pc : UInt32
mut bg3pd : UInt32
mut bg3x : UInt32
mut bg3y : UInt32
mut bg3x_int : Int32
mut bg3y_int : Int32
// Scanline timing state
mut line_cycles : Int32
mut in_hblank : Bool
mut frame_count : UInt64
// Debug layer mask: bit0=BG0, bit1=BG1, bit2=BG2, bit3=BG3, bit4=OBJ
mut layer_mask : UInt32
// Output RGBA8888 framebuffer (240 * 160 * 4 bytes)
framebuf : FixedArray[Byte]
// Per-scanline compositing buffers
line_color : FixedArray[UInt32]
line_prio : FixedArray[Int32]
}
///|
pub fn Ppu::new() -> Ppu {
let fb = FixedArray::make(SCREEN_WIDTH * SCREEN_HEIGHT * 4, b'\x00')
for i = 0; i < SCREEN_WIDTH * SCREEN_HEIGHT; i = i + 1 {
fb[i * 4 + 3] = b'\xFF'
}
{
dispcnt: 0U,
dispstat: 0U,
vcount: 0U,
bgcnt: FixedArray::make(4, 0U),
bghofs: FixedArray::make(4, 0U),
bgvofs: FixedArray::make(4, 0U),
bg2pa: 0x100U,
bg2pb: 0U,
bg2pc: 0U,
bg2pd: 0x100U,
bg2x: 0U,
bg2y: 0U,
bg2x_int: 0,
bg2y_int: 0,
bg3pa: 0x100U,
bg3pb: 0U,
bg3pc: 0U,
bg3pd: 0x100U,
bg3x: 0U,
bg3y: 0U,
bg3x_int: 0,
bg3y_int: 0,
line_cycles: 0,
in_hblank: false,
frame_count: 0UL,
layer_mask: 0x1FU,
framebuf: fb,
line_color: FixedArray::make(SCREEN_WIDTH, 0U),
line_prio: FixedArray::make(SCREEN_WIDTH, 8),
}
}
///|
pub fn Ppu::reset(self : Ppu) -> Unit {
self.dispcnt = 0U
self.dispstat = 0U
self.vcount = 0U
for i = 0; i < 4; i = i + 1 {
self.bgcnt[i] = 0U
self.bghofs[i] = 0U
self.bgvofs[i] = 0U
}
self.bg2pa = 0x100U
self.bg2pb = 0U
self.bg2pc = 0U
self.bg2pd = 0x100U
self.bg2x = 0U
self.bg2y = 0U
self.bg2x_int = 0
self.bg2y_int = 0
self.bg3pa = 0x100U
self.bg3pb = 0U
self.bg3pc = 0U
self.bg3pd = 0x100U
self.bg3x = 0U
self.bg3y = 0U
self.bg3x_int = 0
self.bg3y_int = 0
self.line_cycles = 0
self.in_hblank = false
self.frame_count = 0UL
self.layer_mask = 0x1FU
for i = 0; i < SCREEN_WIDTH * SCREEN_HEIGHT; i = i + 1 {
self.framebuf[i * 4] = b'\x00'
self.framebuf[i * 4 + 1] = b'\x00'
self.framebuf[i * 4 + 2] = b'\x00'
self.framebuf[i * 4 + 3] = b'\xFF'
}
}
///|
fn read_pram16(pram : FixedArray[Byte], idx : Int32) -> UInt32 {
let off = (idx & 0x1FF) * 2
let lo = pram[off].to_int().reinterpret_as_uint()
let hi = pram[off + 1].to_int().reinterpret_as_uint()
lo | (hi << 8)
}
///|
fn read_vram16(vram : FixedArray[Byte], off : Int32) -> UInt32 {
let a = off & 0x1FFFE
if a + 1 < vram.length() {
let lo = vram[a].to_int().reinterpret_as_uint()
let hi = vram[a + 1].to_int().reinterpret_as_uint()
lo | (hi << 8)
} else {
0U
}
}
///|
fn read_oam16(oam : FixedArray[Byte], off : Int32) -> UInt32 {
let a = off & 0x3FE
let lo = oam[a].to_int().reinterpret_as_uint()
let hi = oam[a + 1].to_int().reinterpret_as_uint()
lo | (hi << 8)
}
///|
/// Render one regular tiled background layer (`bg = 0..3`) onto the current scanline `y`.
fn Ppu::render_regular_bg(
self : Ppu,
vram : FixedArray[Byte],
pram : FixedArray[Byte],
bg : Int32,
y : Int32,
) -> Unit {
if ((self.dispcnt >> (8 + bg)) & 1U) == 0U {
return
}
if ((self.layer_mask >> bg) & 1U) == 0U {
return
}
let cnt = self.bgcnt[bg]
let prio = (cnt & 3U).reinterpret_as_int()
let char_base = (((cnt >> 2) & 3U) * 0x4000U).reinterpret_as_int()
let is_8bpp = ((cnt >> 7) & 1U) != 0U
let map_base = (((cnt >> 8) & 0x1FU) * 0x800U).reinterpret_as_int()
let size_bits = (cnt >> 14) & 3U
let map_w = if size_bits == 1U || size_bits == 3U { 512 } else { 256 }
let map_h = if size_bits == 2U || size_bits == 3U { 512 } else { 256 }
let hofs = self.bghofs[bg].reinterpret_as_int()
let vofs = self.bgvofs[bg].reinterpret_as_int()
let sy = (y + vofs) % map_h
let ty = sy / 8
let py_base = sy % 8
for x = 0; x < SCREEN_WIDTH; x = x + 1 {
if self.line_prio[x] <= prio {
continue
}
let sx = (x + hofs) % map_w
let tx = sx / 8
let px_base = sx % 8
let mut sbb = 0
if tx >= 32 {
sbb += 1
}
if ty >= 32 {
sbb += if map_w == 512 { 2 } else { 1 }
}
let entry_addr = map_base + sbb * 0x800 + ((ty & 31) * 32 + (tx & 31)) * 2
let entry = read_vram16(vram, entry_addr)
let tile_id = (entry & 0x3FFU).reinterpret_as_int()
let hflip = ((entry >> 10) & 1U) != 0U
let vflip = ((entry >> 11) & 1U) != 0U
let pal_bank = ((entry >> 12) & 0xFU).reinterpret_as_int()
let px = if hflip { 7 - px_base } else { px_base }
let py = if vflip { 7 - py_base } else { py_base }
let color_idx = if is_8bpp {
let addr = char_base + tile_id * 64 + py * 8 + px
if addr < 0x10000 {
vram[addr].to_int()
} else {
0
}
} else {
let addr = char_base + tile_id * 32 + py * 4 + px / 2
if addr < 0x10000 {
let b = vram[addr].to_int()
let nib = if (px & 1) == 0 { b & 0xF } else { (b >> 4) & 0xF }
if nib == 0 {
0
} else {
pal_bank * 16 + nib
}
} else {
0
}
}
if color_idx != 0 {
self.line_color[x] = read_pram16(pram, color_idx)
self.line_prio[x] = prio
}
}
}
///|
/// Render an affine (rotation/scaling) background (`bg = 2` or `3`) onto scanline `y`.
fn Ppu::render_affine_bg(
self : Ppu,
vram : FixedArray[Byte],
pram : FixedArray[Byte],
bg : Int32,
) -> Unit {
if ((self.dispcnt >> (8 + bg)) & 1U) == 0U {
return
}
if ((self.layer_mask >> bg) & 1U) == 0U {
return
}
let cnt = self.bgcnt[bg]
let prio = (cnt & 3U).reinterpret_as_int()
let char_base = (((cnt >> 2) & 3U) * 0x4000U).reinterpret_as_int()
let map_base = (((cnt >> 8) & 0x1FU) * 0x800U).reinterpret_as_int()
let wrap = ((cnt >> 13) & 1U) != 0U
let size_px = 128 << ((cnt >> 14) & 3U).reinterpret_as_int()
let tiles_per_row = size_px / 8
let pa = sign_ext_16(if bg == 2 { self.bg2pa } else { self.bg3pa })
let pc = sign_ext_16(if bg == 2 { self.bg2pc } else { self.bg3pc })
let mut rx = if bg == 2 { self.bg2x_int } else { self.bg3x_int }
let mut ry = if bg == 2 { self.bg2y_int } else { self.bg3y_int }
for x = 0; x < SCREEN_WIDTH; x = x + 1 {
let mut tx_px = rx >> 8
let mut ty_px = ry >> 8
rx += pa
ry += pc
if self.line_prio[x] <= prio {
continue
}
if wrap {
tx_px = (tx_px % size_px + size_px) % size_px
ty_px = (ty_px % size_px + size_px) % size_px
} else if tx_px < 0 || tx_px >= size_px || ty_px < 0 || ty_px >= size_px {
continue
}
let tile_addr = map_base + ty_px / 8 * tiles_per_row + tx_px / 8
if tile_addr >= 0x10000 {
continue
}
let tile_id = vram[tile_addr].to_int()
let px_addr = char_base + tile_id * 64 + (ty_px & 7) * 8 + (tx_px & 7)
if px_addr < 0x10000 {
let cidx = vram[px_addr].to_int()
if cidx != 0 {
self.line_color[x] = read_pram16(pram, cidx)
self.line_prio[x] = prio
}
}
}
}
///|
fn obj_dimensions(shape : UInt32, size : UInt32) -> (Int32, Int32) {
match (shape, size) {
(0U, 0U) => (8, 8)
(0U, 1U) => (16, 16)
(0U, 2U) => (32, 32)
(0U, 3U) => (64, 64)
(1U, 0U) => (16, 8)
(1U, 1U) => (32, 8)
(1U, 2U) => (32, 16)
(1U, 3U) => (64, 32)
(2U, 0U) => (8, 16)
(2U, 1U) => (8, 32)
(2U, 2U) => (16, 32)
(2U, 3U) => (32, 64)
_ => (8, 8)
}
}
///|
/// Render all visible OAM sprites (OBJ layer) onto scanline `y`.
fn Ppu::render_objects(
self : Ppu,
vram : FixedArray[Byte],
pram : FixedArray[Byte],
oam : FixedArray[Byte],
y : Int32,
) -> Unit {
if ((self.dispcnt >> 12) & 1U) == 0U {
return
}
if ((self.layer_mask >> 4) & 1U) == 0U {
return
}
let one_dim = ((self.dispcnt >> 6) & 1U) != 0U
let mode = self.dispcnt & 7U
// Iterate back-to-front (127 down to 0) so lower OAM index wins tie-breaks
for i = 127; i >= 0; i = i - 1 {
let base = i * 8
let attr0 = read_oam16(oam, base)
let attr1 = read_oam16(oam, base + 2)
let attr2 = read_oam16(oam, base + 4)
let obj_mode = (attr0 >> 8) & 3U
if obj_mode == 2U {
continue // Hidden
}
let is_affine = (obj_mode & 1U) != 0U
let double_size = obj_mode == 3U
let shape = (attr0 >> 14) & 3U
let size = (attr1 >> 14) & 3U
let (w, h) = obj_dimensions(shape, size)
let box_w = if double_size { w * 2 } else { w }
let box_h = if double_size { h * 2 } else { h }
let mut oy = (attr0 & 0xFFU).reinterpret_as_int()
if oy >= 160 {
oy -= 256
}
if y < oy || y >= oy + box_h {
continue
}
let mut ox = (attr1 & 0x1FFU).reinterpret_as_int()
if ox >= 240 {
ox -= 512
}
let is_8bpp = ((attr0 >> 13) & 1U) != 0U
let prio = ((attr2 >> 10) & 3U).reinterpret_as_int()
let tile_base = (attr2 & 0x3FFU).reinterpret_as_int()
let pal_bank = ((attr2 >> 12) & 0xFU).reinterpret_as_int()
let hflip = !is_affine && ((attr1 >> 12) & 1U) != 0U
let vflip = !is_affine && ((attr1 >> 13) & 1U) != 0U
let mut pa = 0x100
let mut pb = 0
let mut pc = 0
let mut pd = 0x100
if is_affine {
let aff_idx = ((attr1 >> 9) & 0x1FU).reinterpret_as_int()
let abase = aff_idx * 32
pa = sign_ext_16(read_oam16(oam, abase + 6))
pb = sign_ext_16(read_oam16(oam, abase + 14))
pc = sign_ext_16(read_oam16(oam, abase + 22))
pd = sign_ext_16(read_oam16(oam, abase + 30))
}
let local_y = y - oy
for dx = 0; dx < box_w; dx = dx + 1 {
let sx = ox + dx
if sx < 0 || sx >= SCREEN_WIDTH {
continue
}
if self.line_prio[sx] < prio {
continue
}
let (tx, ty) = if is_affine {
let rx = dx - box_w / 2
let ry = local_y - box_h / 2
(((pa * rx + pb * ry) >> 8) + w / 2, ((pc * rx + pd * ry) >> 8) + h / 2)
} else {
(
if hflip {
w - 1 - dx
} else {
dx
},
if vflip {
h - 1 - local_y
} else {
local_y
},
)
}
if tx < 0 || tx >= w || ty < 0 || ty >= h {
continue
}
let tile_x = tx / 8
let tile_y = ty / 8
let px = tx & 7
let py = ty & 7
let tile_num = if one_dim {
if is_8bpp {
(tile_base & 0x3FE) + (tile_y * (w / 8) + tile_x) * 2
} else {
tile_base + tile_y * (w / 8) + tile_x
}
} else if is_8bpp {
(tile_base & 0x3FE) + tile_y * 32 + tile_x * 2
} else {
tile_base + tile_y * 32 + tile_x
}
if mode >= 3U && tile_num < 512 {
continue
}
let addr = 0x10000 + (tile_num & 0x3FF) * 32
let color_idx = if is_8bpp {
let a = addr + py * 8 + px
if a < 0x18000 {
vram[a].to_int()
} else {
0
}
} else {
let a = addr + py * 4 + px / 2
if a < 0x18000 {
let b = vram[a].to_int()
let nib = if (px & 1) == 0 { b & 0xF } else { (b >> 4) & 0xF }
if nib == 0 {
0
} else {
pal_bank * 16 + nib
}
} else {
0
}
}
if color_idx != 0 {
// OBJ palette starts at PRAM index 256 (0x05000200)
self.line_color[sx] = read_pram16(pram, 256 + color_idx)
self.line_prio[sx] = prio
}
}
}
}
///|
/// Render scanline `y` (0..159) into `self.framebuf`.
pub fn Ppu::render_scanline(
self : Ppu,
vram : FixedArray[Byte],
pram : FixedArray[Byte],
oam : FixedArray[Byte],
y : Int32,
) -> Unit {
if y < 0 || y >= SCREEN_HEIGHT {
return
}
// Forced blank (DISPCNT bit 7) renders pure white
if ((self.dispcnt >> 7) & 1U) != 0U {
let row = y * SCREEN_WIDTH * 4
for x = 0; x < SCREEN_WIDTH; x = x + 1 {
let idx = row + x * 4
self.framebuf[idx] = b'\xFF'
self.framebuf[idx + 1] = b'\xFF'
self.framebuf[idx + 2] = b'\xFF'
self.framebuf[idx + 3] = b'\xFF'
}
return
}
let backdrop = read_pram16(pram, 0)
for x = 0; x < SCREEN_WIDTH; x = x + 1 {
self.line_color[x] = backdrop
self.line_prio[x] = 8
}
let mode = self.dispcnt & 7U
match mode {
0U => {
// 4 regular tiled BGs; render highest priority (0) down to 3
for bg = 0; bg < 4; bg = bg + 1 {
self.render_regular_bg(vram, pram, bg, y)
}
self.render_objects(vram, pram, oam, y)
}
1U => {
self.render_regular_bg(vram, pram, 0, y)
self.render_regular_bg(vram, pram, 1, y)
self.render_affine_bg(vram, pram, 2)
self.render_objects(vram, pram, oam, y)
}
2U => {
self.render_affine_bg(vram, pram, 2)
self.render_affine_bg(vram, pram, 3)
self.render_objects(vram, pram, oam, y)
}
3U => {
// 240x160 15-bit direct color bitmap on BG2
if ((self.dispcnt >> 10) & 1U) != 0U &&
((self.layer_mask >> 2) & 1U) != 0U {
let prio = (self.bgcnt[2] & 3U).reinterpret_as_int()
let row_off = y * SCREEN_WIDTH * 2
for x = 0; x < SCREEN_WIDTH; x = x + 1 {
self.line_color[x] = read_vram16(vram, row_off + x * 2)
self.line_prio[x] = prio
}
}
self.render_objects(vram, pram, oam, y)
}
4U => {
// 240x160 8-bit paletted double-buffered bitmap on BG2
if ((self.dispcnt >> 10) & 1U) != 0U &&
((self.layer_mask >> 2) & 1U) != 0U {
let prio = (self.bgcnt[2] & 3U).reinterpret_as_int()
let page = if ((self.dispcnt >> 4) & 1U) != 0U { 0xA000 } else { 0 }
let row_off = page + y * SCREEN_WIDTH
for x = 0; x < SCREEN_WIDTH; x = x + 1 {
let cidx = vram[row_off + x].to_int()
if cidx != 0 {
self.line_color[x] = read_pram16(pram, cidx)
self.line_prio[x] = prio
}
}
}
self.render_objects(vram, pram, oam, y)
}
5U => {
// 160x128 15-bit double-buffered bitmap on BG2
if ((self.dispcnt >> 10) & 1U) != 0U &&
((self.layer_mask >> 2) & 1U) != 0U &&
y < 128 {
let prio = (self.bgcnt[2] & 3U).reinterpret_as_int()
let page = if ((self.dispcnt >> 4) & 1U) != 0U { 0xA000 } else { 0 }
let row_off = page + y * 160 * 2
for x = 0; x < 160; x = x + 1 {
self.line_color[x] = read_vram16(vram, row_off + x * 2)
self.line_prio[x] = prio
}
}
self.render_objects(vram, pram, oam, y)
}
_ => ()
}
let row = y * SCREEN_WIDTH * 4
for x = 0; x < SCREEN_WIDTH; x = x + 1 {
let (r, g, b) = bgr555_to_rgb(self.line_color[x])
let idx = row + x * 4
self.framebuf[idx] = r
self.framebuf[idx + 1] = g
self.framebuf[idx + 2] = b
self.framebuf[idx + 3] = b'\xFF'
}
}
///|
/// Advance PPU scanline state by `cycles`. Triggers HBlank/VBlank/VCount IRQs and DMAs.
/// Returns `true` when a full frame (VCount wraps to 0) completes.
pub fn tick_ppu(bus : GbaBus, cycles : Int32) -> Bool {
let ppu = bus.ppu
let mut frame_done = false
ppu.line_cycles += cycles
if !ppu.in_hblank && ppu.line_cycles >= CYCLES_HDRAW {
ppu.in_hblank = true
ppu.dispstat = ppu.dispstat | 2U // HBlank flag
let y = ppu.vcount.reinterpret_as_int()
if y < SCREEN_HEIGHT {
ppu.render_scanline(bus.vram, bus.pram, bus.oam, y)
// Advance affine internal reference points at end of visible scanline
ppu.bg2x_int += sign_ext_16(ppu.bg2pb)
ppu.bg2y_int += sign_ext_16(ppu.bg2pd)
ppu.bg3x_int += sign_ext_16(ppu.bg3pb)
ppu.bg3y_int += sign_ext_16(ppu.bg3pd)
trigger_dma(bus, 2U) // HBlank DMA
}
if ((ppu.dispstat >> 4) & 1U) != 0U {
bus.irq_if = bus.irq_if | 2U // HBlank IRQ
}
}
while ppu.line_cycles >= CYCLES_SCANLINE {
ppu.line_cycles -= CYCLES_SCANLINE
ppu.in_hblank = false
ppu.dispstat = ppu.dispstat & 2U.lnot() // Clear HBlank flag
let next_v = (ppu.vcount.reinterpret_as_int() + 1) % SCANLINES_TOTAL
ppu.vcount = next_v.reinterpret_as_uint()
if next_v == SCREEN_HEIGHT {
// Entering VBlank
ppu.dispstat = ppu.dispstat | 1U
ppu.bg2x_int = sign_ext_28(ppu.bg2x)
ppu.bg2y_int = sign_ext_28(ppu.bg2y)
ppu.bg3x_int = sign_ext_28(ppu.bg3x)
ppu.bg3y_int = sign_ext_28(ppu.bg3y)
if ((ppu.dispstat >> 3) & 1U) != 0U {
bus.irq_if = bus.irq_if | 1U // VBlank IRQ
}
trigger_dma(bus, 1U) // VBlank DMA
} else if next_v == 0 {
// New frame begins
ppu.dispstat = ppu.dispstat & 1U.lnot()
ppu.frame_count += 1UL
frame_done = true
}
// VCount match (LYC in DISPSTAT bits 15..8)
let lyc = (ppu.dispstat >> 8) & 0xFFU
if ppu.vcount == lyc {
ppu.dispstat = ppu.dispstat | 4U
if ((ppu.dispstat >> 5) & 1U) != 0U {
bus.irq_if = bus.irq_if | 4U // VCount IRQ
}
} else {
ppu.dispstat = ppu.dispstat & 4U.lnot()
}
}
frame_done
}