Files
brad ArantandClaude Opus 5.5 bda9bb67b6 Add a 640x480 two-colour graphics mode; start in white
The graphics memory doubles as 640x480 at a bit a pixel (port 38), four
pixels to an entry, plotted by read-modify-write, in two colours from
port 39 (0 transparent). BASIC gets SCREEN 0 / SCREEN 1 [,set[,clear]];
a plain fill (as every game does) returns to 320x240 and BASIC follows.
The text now starts in white (SW5:4 = 00; 10 is green). The README is
rewritten to stand on its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 06:06:30 -08:00

241 lines
9.5 KiB
Python

#!/usr/bin/env python3
"""A model of the Basys 3 RISC-V computer's game hardware around
tools/rv32emu.py, for testing programs on the PC: the terminal (port 1), the
graphics layer with scrolling (30h-37h), the sprites (70h-78h) and the
held-key port (88h).
from boardemu import Board, load_ihx, load_font
mem, end = load_ihx("prog.ihx")
b = Board(mem, code_end=end) # runs from GAME_BASE, returns to address 0
b.run_frames(60, joy=FIRE)
b.shot("screen.png", load_font())
The frame counter (78h) moves on when the program comes back to read it after
doing some work (more than 100 instructions since it last moved), so a program
that waits for it to change runs one frame per wait, however long its frames
take, and two reads close together see the same frame. Screenshots need
pyte and Pillow, and are drawn the way the board's video combines the layers:
text over sprites over graphics.
"""
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from rv32emu import RV32 # noqa: E402
GAME_BASE = 0xA200 # where BASIC's loader programs put machine code
STACK_TOP = 0x13FF0
PAL = ["000", "A00", "0A0", "A50", "00A", "A0A", "0AA", "AAA",
"555", "F55", "5F5", "FF5", "55F", "F5F", "5FF", "FFF"]
PAL = [tuple(int(c, 16) * 17 for c in p) for p in PAL]
UP, DOWN, LEFT, RIGHT, FIRE, ENTER, ESC = 1, 2, 4, 8, 16, 32, 128
class Board(RV32):
def __init__(self, mem, code_end=0x14000, start=GAME_BASE, rom_top=0):
super().__init__(mem, rom_top=rom_top)
self.code_end = code_end
self.code_start = start
self.steps = 0 # instructions run
self.scroll_x = self.scroll_y = 0
self.border = False
self.pc, self.sp = start, STACK_TOP
self.x[1] = 0 # ra: the program returns to 0
self.frame = 0
self.frame_at = -1000
self.joy = 0
self.gfx = bytearray(320 * 240)
self.hgfx = bytearray(640 * 480) # 640x480 mode (port 38): 0 or 1 a pixel
self.g_cols = 0x0F
self.gxv = self.gyv = 0
self.spr = [[0, 0, 0, 0] for _ in range(32)] # x, y, shape, ctl
self.sel = 0
self.xst = 0
self.pat = bytearray(8192)
self.pat_a = 0
self.text = bytearray()
self.keys_in = bytearray()
def io_in(self, port):
p = port & 0xFF
if p == 0:
return (1 if self.keys_in else 0) | 2
if p == 1:
return self.keys_in.pop(0) if self.keys_in else 0
if p == 0x78:
if self.steps - self.frame_at > 100:
self.frame += 1
self.frame_at = self.steps
return self.frame & 0xFF
if p == 0x88:
return self.joy
if p == 0x33:
if self.g_hires:
return self.hgfx[self.gyv * 640 + self.gxv] if self.gxv < 640 and self.gyv < 480 else 0
return self.gfx[self.gyv * 320 + self.gxv] if self.gxv < 320 and self.gyv < 240 else 0
if p == 0x34:
return 0
if p == 0x38:
return self.g_hires
return 0xFF
def io_out(self, port, v):
p = port & 0xFF
if p == 1:
self.text.append(v)
elif p == 0x30: self.gxv = (self.gxv & 0x300) | v
elif p == 0x31:
self.gxv = (self.gxv & 0xFF) | (v & 3) << 8
self.gyv = (self.gyv & 0xFF) | (v & 4) << 6
elif p == 0x32: self.gyv = (self.gyv & 0x100) | v
elif p == 0x33:
if self.g_hires:
if self.gxv < 640 and self.gyv < 480:
self.hgfx[self.gyv * 640 + self.gxv] = int(v != 0)
elif self.gxv < 320 and self.gyv < 240:
self.gfx[self.gyv * 320 + self.gxv] = v & 15
self.gxv = (self.gxv + 1) & 0x3FF
elif p == 0x34:
if self.g_hires and v & 0x80:
self.hgfx[:] = bytes([int(v & 15 != 0)]) * (640 * 480)
else:
self.gfx[:] = bytes([v & 15]) * (320 * 240)
self.hgfx[:] = bytes(640 * 480)
if not v & 0x80:
for s in self.spr: s[3] &= ~1
self.scroll_x = self.scroll_y = 0
self.border = False
elif p == 0x35: self.scroll_x = (self.scroll_x & 0x100) | v
elif p == 0x36:
self.scroll_x = (self.scroll_x & 0xFF) | (v & 1) << 8
self.border = bool(v & 2)
elif p == 0x37: self.scroll_y = v - 240 if v >= 240 else v
elif p == 0x39: self.g_cols = v
elif p == 0x70: self.sel = v & 31
elif p == 0x71: self.xst = (self.xst & 0x100) | v
elif p == 0x72: self.xst = (self.xst & 0xFF) | (v & 1) << 8
elif p == 0x73: self.spr[self.sel][0], self.spr[self.sel][1] = self.xst, v
elif p == 0x74: self.spr[self.sel][2] = v & 63
elif p == 0x75: self.spr[self.sel][3] = v & 7
elif p == 0x76: self.pat_a = (v & 63) * 128
elif p == 0x77:
self.pat[self.pat_a & 8191] = v
self.pat_a += 1
def run_frames(self, n, joy=0):
"""Run until the program has waited for n more frames (or returned)."""
self.joy = joy
end = self.frame + n
while self.frame < end and self.pc != 0:
self.step()
self.steps += 1
if not (self.code_start <= self.pc < self.code_end or self.pc == 0):
raise SystemExit("PC left the program: %05X" % self.pc)
if self.sp < STACK_TOP - 0x1000:
raise SystemExit("stack ran into memory: SP %05X" % self.sp)
def screen_text(self):
import pyte
scr = pyte.Screen(80, 32)
pyte.ByteStream(scr).feed(bytes(self.text))
return scr
def shot(self, path, font):
from PIL import Image
scr = self.screen_text()
img = Image.new("RGB", (1280, 1024))
px = img.load()
lay = bytearray(320 * 240) # the graphics as scrolled onto the screen
for y in range(240):
fy = (y + self.scroll_y) % 240
row = self.gfx[fy * 320:(fy + 1) * 320]
sx = self.scroll_x % 320
lay[y * 320:(y + 1) * 320] = row[sx:] + row[:sx]
if self.border: # hidden: 4 columns each side, 2 rows top and bottom
if y < 2 or y >= 238:
lay[y * 320:(y + 1) * 320] = bytes(320)
else:
lay[y * 320:y * 320 + 4] = bytes(4)
lay[y * 320 + 316:(y + 1) * 320] = bytes(4)
for s in reversed(self.spr): # sprite 0 in front
x0, y0, shape, ctl = s
if not ctl & 1:
continue
for r in range(16):
for c in range(16):
rr = 15 - r if ctl & 4 else r
cc = 15 - c if ctl & 2 else c
b = self.pat[shape * 128 + rr * 8 + cc // 2]
col = b & 15 if cc & 1 else b >> 4
x, y = (x0 + c) & 511, (y0 + r) & 255
if col and x < 320 and y < 240:
lay[y * 320 + x] = col | 16
for y in range(1024):
for x in range(1280):
gx, gy = x >> 2, y >> 2
c = lay[gy * 320 + gx] & 15 if gy < 240 else 0
px[x, y] = PAL[c]
names = ["black", "red", "green", "brown", "blue", "magenta", "cyan", "white"]
for r in range(32):
for c in range(80):
ch = scr.buffer[r][c]
code = ord(ch.data[0]) if ch.data else 32
if code == 32 and ch.bg == "default":
continue
def colour(n, d):
if n in names: return PAL[names.index(n)]
if n.startswith("bright") and n[6:] in names: return PAL[names.index(n[6:]) + 8]
try:
v = int(n, 16); return ((v >> 16) & 255, (v >> 8) & 255, v & 255)
except ValueError:
return d
fg = colour(ch.fg, PAL[10])
bg = colour(ch.bg, None)
for y in range(16):
bits = font[(code if code < 256 else 63) * 16 + y]
for x in range(8):
on = bits & (0x80 >> x)
for dy in (0, 1):
for dx in (0, 1):
X, Y = c * 16 + 2 * x + dx, r * 32 + 2 * y + dy
if on: px[X, Y] = fg
elif bg is not None and px[X, Y] == (0, 0, 0): px[X, Y] = bg
img.save(path)
def load_ihx(path):
"""Memory image and the end of the loaded bytes (Intel HEX with type 04
extended linear addresses, as objcopy writes it)."""
mem = bytearray(0x28000)
hi = 0
base = 0
for line in open(path):
if not line.startswith(":"):
continue
n, a, t = int(line[1:3], 16), int(line[3:7], 16), int(line[7:9], 16)
if t == 0:
mem[base + a:base + a + n] = bytes.fromhex(line[9:9 + 2 * n])
hi = max(hi, base + a + n)
elif t == 4:
base = int(line[9:13], 16) << 16
return mem, hi
def load_syms(path):
"""Symbol addresses from `nm` output."""
sym = {}
for line in open(path):
f = line.split()
if len(f) == 3:
sym[f[2]] = int(f[0], 16)
return sym
def load_font():
root = os.path.join(HERE, "..")
return [int(l.split("//")[0], 16) for l in open(os.path.join(root, "font", "font.mem"))
if l.split("//")[0].strip()]