"""Rasterize printable ASCII from a monospace font into 6-pixel-wide glyphs for the GBA screen, and write font.h. Needs Pillow; the generated font.h is kept, so this only runs again to change the font. python3 font.py [FONT_FILE] [SIZE] [CELL_HEIGHT] """ import sys from pathlib import Path from PIL import Image, ImageDraw, ImageFont FONT = sys.argv[1] if len(sys.argv) > 1 else "/System/Library/Fonts/Monaco.ttf" SIZE = int(sys.argv[2]) if len(sys.argv) > 2 else 9 WIDTH = 6 HEIGHT = int(sys.argv[3]) if len(sys.argv) > 3 else 10 font = ImageFont.truetype(FONT, SIZE) ascent, _ = font.getmetrics() rows = [] for code in range(32, 127): image = Image.new("1", (WIDTH, HEIGHT), 0) draw = ImageDraw.Draw(image) draw.fontmode = "1" # no antialiasing: on or off draw.text((0, HEIGHT - 1 - ascent), chr(code), font=font, fill=1) glyph = [] for y in range(HEIGHT): bits = 0 for x in range(WIDTH): if image.getpixel((x, y)): bits |= 1 << x glyph.append(bits) rows.append(glyph) # Monaco at this size gives the descenders one row, which makes g and q the # same glyph: move every glyph up a row (row 0 is blank but for the tops of # / \ |) and draw g j p q y by hand with two-row descenders, and _ (the # typing cursor) just below the baseline again. rows = [glyph[1:] + [0] for glyph in rows] HAND = { "g": ["......", "......", "......", ".####.", "#...#.", "#...#.", "#...#.", ".####.", "....#.", ".###.."], "j": ["......", "..#...", "......", "..#...", "..#...", "..#...", "..#...", "..#...", "..#...", "##...."], "p": ["......", "......", "......", "####..", "#...#.", "#...#.", "#...#.", "####..", "#.....", "#....."], "q": ["......", "......", "......", ".####.", "#...#.", "#...#.", "#...#.", ".####.", "....#.", "....#."], "y": ["......", "......", "......", "#...#.", "#...#.", "#...#.", "#...#.", ".####.", "....#.", ".###.."], "_": ["......", "......", "......", "......", "......", "......", "......", "......", "######", "......"], } assert HEIGHT == 10 and WIDTH == 6 for c, picture in HAND.items(): rows[ord(c) - 32] = [sum(1 << x for x, p in enumerate(line) if p == "#") for line in picture] lines = [f" {{{', '.join(f'0x{b:02x}' for b in g)}}}, // {chr(32 + i)!r}" for i, g in enumerate(rows)] Path(__file__).with_name("font.h").write_text( f"// Generated by font.py from {Path(FONT).name} at {SIZE} px, with hand-drawn descenders; do not edit.\n" f"// Glyphs for ASCII 32-126, {WIDTH}x{HEIGHT}: one byte per row, bit x is column x.\n" "#pragma once\n#include \n" f"#define FONT_WIDTH {WIDTH}\n#define FONT_HEIGHT {HEIGHT}\n" f"static const uint8_t font[95][{HEIGHT}] = {{\n" + "\n".join(lines) + "\n};\n" ) # A preview in the terminal. for start in (33, 65, 97): for y in range(HEIGHT): print("".join(("#" if rows[c - 32][y] >> x & 1 else ".") for c in range(start, start + 12) for x in range(WIDTH))) print()