Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

3.3 KB
Raw Blame
#!/usr/bin/env python3
"""Rasterizes Buckshot's fonts into src/font.h (1 bit per pixel).

- "receipt": Fake Receipt by Ray Larabie (Typodermic Fonts), the original's
  dialogue and menu font, at two sizes.
- "dot": Dot Matrix (Dionaea), the font of the charge display.

The font files come from the original game's project (BR_PROJECT/fonts).
Usage: BR_PROJECT=dir font.py [preview.png]
"""
import os
import sys
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw, ImageFont

HERE = Path(__file__).resolve().parent
FONTS = Path(os.environ.get("BR_PROJECT", "")) / "fonts"
CHARS = "".join(chr(c) for c in range(32, 96))  # space to underscore: the game writes in capitals

# name, file, pixel size, extra advance
SPECS = [("font_small", "fake receipt.otf", 10, 0), ("font_big", "fake receipt.otf", 14, 0),
         ("font_dot", "DOTMATRI.TTF", 23, 1)]


def raster(file, size, extra):
    f = ImageFont.truetype(str(FONTS / file), size)
    asc, desc = f.getmetrics()
    h = asc + desc
    glyphs = []
    for ch in CHARS:
        adv = int(round(f.getlength(ch))) + extra
        im = Image.new("L", (adv + 8, h), 0)
        ImageDraw.Draw(im).text((0, 0), ch, font=f, fill=255)
        a = np.array(im) >= 128
        cols = np.nonzero(a.any(axis=0))[0]
        w = max(adv, int(cols.max()) + 1 if len(cols) else 0)
        glyphs.append((adv, a[:, :w]))
    rows = np.nonzero(np.any([g[1].any(axis=1) for g in glyphs if g[1].size], axis=0))[0]
    top, bot = int(rows.min()), int(rows.max()) + 1
    return bot - top, [(adv, a[top:bot]) for adv, a in glyphs]


def main():
    out = ["/* Generated by tools/font.py: Fake Receipt (Ray Larabie, Typodermic Fonts) and",
           " * Dot Matrix (Dionaea), 1 bit per pixel. Characters 32 to 95. */",
           "#include <stdint.h>", "#include \"font.h\""]
    prev = []
    for name, file, size, extra in SPECS:
        h, glyphs = raster(file, size, extra)
        bits, offs, widths = [], [], []
        for adv, a in glyphs:
            offs.append(len(bits))
            widths.append(a.shape[1])
            bits += [int(v) for v in a.flatten()]
        data = bytearray((len(bits) + 7) // 8)
        for i, b in enumerate(bits):
            if b:
                data[i >> 3] |= 1 << (i & 7)
        advs = [adv for adv, _ in glyphs]
        out.append(f"static const uint8_t {name}_bits[] = {{{','.join(map(str, data))}}};")
        out.append(f"static const uint16_t {name}_off[] = {{{','.join(map(str, offs))}}};")
        out.append(f"static const uint8_t {name}_w[] = {{{','.join(map(str, widths))}}};")
        out.append(f"static const uint8_t {name}_adv[] = {{{','.join(map(str, advs))}}};")
        out.append(f"const font_t {name} = {{{h}, {name}_bits, {name}_off, {name}_w, {name}_adv}};")
        prev.append((h, glyphs))
    (HERE.parent / "src" / "font.c").write_text("\n".join(out) + "\n")
    if len(sys.argv) > 1:
        W = 320
        im = Image.new("L", (W, 120), 0)
        y = 2
        for h, glyphs in prev:
            x = 2
            for adv, a in glyphs:
                if x + adv > W:
                    x, y = 2, y + h + 2
                im.paste(Image.fromarray((a * 255).astype(np.uint8)), (x, y))
                x += adv
            y += h + 4
        im.resize((W * 3, 360), Image.NEAREST).save(sys.argv[1])


if __name__ == "__main__":
    main()