Files
barantandClaude Opus 5.5 0e95a14cfe Basys 3 ASCII terminal: VGA 80x30 text, USB keyboard, UART
- VGA 640x480@60 text display, 8x16 CP437 font ROM from Linux console fonts
- USB HID keyboard (PS/2 via onboard PIC24), scan code set 2 to ASCII
  with xterm sequences for cursor/editing keys
- UART RX/TX with switch-selectable baud, local echo option
- Terminal engine: control codes, deferred wrap, hardware scroll,
  VT100/ANSI subset (cursor moves, erase, reverse video, cursor hide)
- Vivado build/program/flash scripts and xsim whole-design testbench

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:26:13 -08:00

109 lines
4.0 KiB
Python

#!/usr/bin/env python3
"""Convert a Linux console PSF font (8x16) into a CP437-ordered font ROM.
Output is a $readmemh file with 4096 lines: byte (code*16 + row), MSB = leftmost pixel.
usage: psf2mem.py [font.psf.gz[,fallback.psf.gz...]] [out.mem] [preview.png]
Glyphs missing from the first font are taken from the fallbacks in order.
"""
import gzip
import struct
import sys
CP437_LOW = ("\u0000☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼")
DEFAULT_FONTS = ",".join("/usr/share/consolefonts/%s.psf.gz" % f for f in
("Uni2-VGA16", "FullGreek-VGA16", "Vietnamese-TerminusBoldVGA16"))
# Fonts often carry the triangle pointers under their newer code points.
CP437_ALT = {"►": "▶", "◄": "◀"}
def cp437(code):
if code < 0x20:
return CP437_LOW[code]
if code == 0x7F:
return "⌂"
return bytes([code]).decode("cp437")
def load_psf(path):
raw = gzip.open(path).read() if path.endswith(".gz") else open(path, "rb").read()
if raw[:2] == b"\x36\x04":
mode, charsize = raw[2], raw[3]
count = 512 if mode & 1 else 256
width, height, hdr = 8, charsize, 4
has_table = bool(mode & 6)
glyphs = [raw[hdr + i * charsize: hdr + (i + 1) * charsize] for i in range(count)]
table = {}
if has_table:
pos, g = hdr + count * charsize, 0
while g < count and pos + 1 < len(raw):
(u,) = struct.unpack_from("<H", raw, pos)
pos += 2
if u == 0xFFFF:
g += 1
elif u != 0xFFFE:
table.setdefault(chr(u), g)
return glyphs, table, width, height
if raw[:4] == b"\x72\xb5\x4a\x86":
_, hdr, flags, count, charsize, height, width = struct.unpack_from("<7I", raw, 4)
glyphs = [raw[hdr + i * charsize: hdr + (i + 1) * charsize] for i in range(count)]
table = {}
if flags & 1:
data = raw[hdr + count * charsize:]
for g, entry in enumerate(data.split(b"\xff")[:count]):
for seq in entry.split(b"\xfe")[:1]:
for ch in seq.decode("utf-8", "ignore"):
table.setdefault(ch, g)
return glyphs, table, width, height
raise SystemExit("not a PSF font: " + path)
def main():
src = sys.argv[1] if len(sys.argv) > 1 and sys.argv[1] else DEFAULT_FONTS
out = sys.argv[2] if len(sys.argv) > 2 else "font.mem"
fonts = []
for path in src.split(","):
glyphs, table, width, height = load_psf(path)
if width != 8 or height != 16:
raise SystemExit(f"{path}: need an 8x16 font, got {width}x{height}")
fonts.append((glyphs, table))
missing = []
rom = []
for code in range(256):
ch = cp437(code)
glyph = None
if code not in (0, 0x20):
for glyphs, table in fonts:
g = table.get(ch, code if not table else None)
if g is None and ch in CP437_ALT:
g = table.get(CP437_ALT[ch])
if g is not None:
glyph = glyphs[g][:16]
break
if glyph is None:
missing.append(f"{code:02X}")
rom.extend(glyph or [0] * 16)
with open(out, "w") as f:
f.write("// CP437 order, 256 glyphs x 16 rows, from: %s\n"
% ", ".join(p.split("/")[-1] for p in src.split(",")))
for b in rom:
f.write(f"{b:02x}\n")
print(f"wrote {out}; glyphs missing: {' '.join(missing) or 'none'}")
if len(sys.argv) > 3:
from PIL import Image
img = Image.new("1", (32 * 9, 8 * 17), 0)
for code in range(256):
ox, oy = (code % 32) * 9, (code // 32) * 17
for r in range(16):
for c in range(8):
if rom[code * 16 + r] & (0x80 >> c):
img.putpixel((ox + c, oy + r), 1)
img.save(sys.argv[3])
if __name__ == "__main__":
main()