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.

7.5 KB
Raw Blame
#!/usr/bin/env python3
"""Build src/assets.c and src/assets.h from the procedural artwork.

Formats (see gfx.h): A4 = 4-bit coverage tinted at draw time, LA44 = 4-bit
luminance + 4-bit alpha tinted at draw time, PAL4 = 4-bit index into a
16-entry RGB565+alpha palette. Rows are byte aligned.
"""
import sys
from pathlib import Path
import numpy as np

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(Path(__file__).resolve().parent))
sys.path.insert(0, str(ROOT.parents[1] / 'tools'))

from share import share                        # noqa: E402

from sprites_game import game_sprites          # noqa: E402
from sprites_ui import ui_sprites              # noqa: E402
from fonts import build_fonts                  # noqa: E402
import background                              # noqa: E402

FMT = {'A4': 0, 'LA44': 1, 'PAL4': 2}


def rgb565(r, g, b):
    return (int(round(r * 31)) << 11) | (int(round(g * 63)) << 5) | int(round(b * 31))


def trim(img, ax, ay):
    a = img[..., 3]
    ys, xs = np.nonzero(a > 1.0 / 32)
    if len(xs) == 0:
        return img[:1, :1], 0, 0
    x0, x1, y0, y1 = xs.min(), xs.max() + 1, ys.min(), ys.max() + 1
    return img[y0:y1, x0:x1], ax - x0, ay - y0


def quant4(x):
    return np.clip(np.round(x * 15), 0, 15).astype(np.uint8)


def pack_nibbles(idx):
    h, w = idx.shape
    stride = (w + 1) // 2
    out = np.zeros((h, stride), np.uint8)
    for x in range(w):
        if x & 1:
            out[:, x >> 1] |= idx[:, x] << 4
        else:
            out[:, x >> 1] |= idx[:, x]
    return out.tobytes()


def palette_quantize(img, n=15, iters=12):
    """k-means over opaque-ish pixels in (r,g,b,a); index 0 = transparent."""
    h, w = img.shape[:2]
    flat = img.reshape(-1, 4)
    a4 = quant4(flat[:, 3])
    vis = a4 > 0
    pts = flat[vis]
    idx = np.zeros(h * w, np.uint8)
    pal = [(0, 0, 0, 0)]
    if len(pts):
        feats = np.concatenate([pts[:, :3], pts[:, 3:4] * 1.5], 1)
        uniq = np.unique(np.round(feats, 3), axis=0)
        k = min(n, len(uniq))
        # init: farthest-point sampling for stable, deterministic results
        cent = [uniq[np.argmax(uniq[:, 3])]]
        for _ in range(1, k):
            d = np.min([((uniq - c) ** 2).sum(1) for c in cent], axis=0)
            cent.append(uniq[np.argmax(d)])
        cent = np.array(cent)
        for _ in range(iters):
            d = ((feats[:, None, :] - cent[None]) ** 2).sum(2)
            lab = d.argmin(1)
            for j in range(k):
                sel = feats[lab == j]
                if len(sel):
                    cent[j] = sel.mean(0)
        d = ((feats[:, None, :] - cent[None]) ** 2).sum(2)
        lab = d.argmin(1)
        idx[vis] = lab + 1
        for c in cent:
            pal.append((c[0], c[1], c[2], min(1.0, c[3] / 1.5)))
    while len(pal) < 16:
        pal.append((0, 0, 0, 0))
    return idx.reshape(h, w), pal


class Packer:
    def __init__(self):
        self.blob = bytearray()
        self.sprites = []      # (name, w, h, ax, ay, fmt, pal, off)
        self.palettes = []
        self.data = []         # each sprite's pixels

    def add(self, name, img, ax, ay, fmt):
        img, ax, ay = trim(img, ax, ay)
        h, w = img.shape[:2]
        pal_i = 0
        if fmt == 'A4':
            data = pack_nibbles(quant4(img[..., 3]))
        elif fmt == 'LA44':
            lum = img[..., :3].mean(2)
            l4 = quant4(lum)
            a4 = quant4(img[..., 3])
            data = ((l4 << 4) | a4).astype(np.uint8).tobytes()
        else:
            idx, pal = palette_quantize(img)
            data = pack_nibbles(idx)
            pal_i = len(self.palettes)
            self.palettes.append(pal)
        self.data.append(bytes(data))
        self.sprites.append((name, w, h, ax, ay, FMT[fmt], pal_i, 0))
        return len(self.sprites) - 1

    def layout(self):
        """The blob, sprites sharing what they can (recoloured copies, runs of
        see-through rows): every reader stays inside its sprite's rows."""
        blob, offs = share(self.data)
        self.blob = bytearray(blob)
        self.sprites = [s[:7] + (o,) for s, o in zip(self.sprites, offs)]


def c_ident(name):
    return 'SPR_' + ''.join(ch.upper() if ch.isalnum() else '_' for ch in name)


def main():
    pk = Packer()
    for name, art, fmt in game_sprites() + ui_sprites():
        pk.add(name, art.image(), art.ax, art.ay, fmt)
    fonts = build_fonts(pk)
    pk.layout()
    names = [s[0] for s in pk.sprites]
    assert len(set(names)) == len(names), 'duplicate sprite names'

    h = ['/* Generated by tools/assets.py. Do not edit. */',
         '#ifndef NUMDASH_ASSETS_H', '#define NUMDASH_ASSETS_H', '#include <stdint.h>',
         'typedef struct { uint16_t w, h; int16_t ax, ay; uint8_t fmt, pal; uint32_t off; } Sprite;',
         'typedef struct { uint8_t cap, outline; int8_t sdx, sdy; uint8_t shadow; uint16_t base; const uint8_t *advance; } Font;',
         'enum {']
    for i, n in enumerate(names):
        if not n.startswith('glyph_'):
            h.append('  %s = %d,' % (c_ident(n), i))
    h.append('  SPR_COUNT = %d' % len(names))
    h.append('};')
    h.append('extern const Sprite sprites[SPR_COUNT];')
    h.append('extern const uint8_t sprite_blob[];')
    h.append('extern const uint16_t sprite_pal_rgb[][16];')
    h.append('extern const uint8_t sprite_pal_a[][16];')
    h.append('enum { %s };' % ', '.join('FONT_%s' % f['name'].upper() for f in fonts))
    h.append('extern const Font fonts[%d];' % len(fonts))
    h.append('extern const uint8_t font_charmap[96];')
    rects = background.layout()
    h.append('#define BG_RECTS %d' % len(rects))
    h.append('extern const uint16_t bg_rects[BG_RECTS][4];')
    h.append('#endif')
    (ROOT / 'src/assets.h').write_text('\n'.join(h) + '\n')

    c = ['/* Generated by tools/assets.py. Do not edit. */', '#include "assets.h"',
         'const Sprite sprites[SPR_COUNT] = {']
    for (n, w, hh, ax, ay, fmt, pal, off) in pk.sprites:
        c.append('  {%d,%d,%d,%d,%d,%d,%d},' % (w, hh, ax, ay, fmt, pal, off))
    c.append('};')
    c.append('const uint16_t sprite_pal_rgb[][16] = {')
    for pal in pk.palettes or [[(0, 0, 0, 0)] * 16]:
        c.append('  {' + ','.join('0x%04x' % rgb565(*p[:3]) for p in pal) + '},')
    c.append('};')
    c.append('const uint8_t sprite_pal_a[][16] = {')
    for pal in pk.palettes or [[(0, 0, 0, 0)] * 16]:
        c.append('  {' + ','.join(str(int(round(p[3] * 15))) for p in pal) + '},')
    c.append('};')
    for f in fonts:
        c.append('static const uint8_t adv_%s[] = {%s};' % (f['name'], ','.join(str(a) for a in f['advance'])))
    c.append('const Font fonts[%d] = {' % len(fonts))
    for f in fonts:
        c.append('  {%d,%d,%d,%d,%d,%d,adv_%s},' % (f['cap'], f['outline'], f['sdx'], f['sdy'], f['sa'], f['base'], f['name']))
    c.append('};')
    from fonts import CHARS
    cmap = [255] * 96
    for i, ch in enumerate(CHARS):
        cmap[ord(ch) - 32] = i
    for ch in 'abcdefghijklmnopqrstuvwxyz':
        cmap[ord(ch) - 32] = CHARS.index(ch.upper())
    c.append('const uint8_t font_charmap[96] = {' + ','.join(str(v) for v in cmap) + '};')
    c.append('const uint16_t bg_rects[BG_RECTS][4] = {' + ','.join('{%d,%d,%d,%d}' % r for r in rects) + '};')
    c.append('const uint8_t sprite_blob[] = {')
    blob = bytes(pk.blob)
    for i in range(0, len(blob), 32):
        c.append('  ' + ','.join(str(b) for b in blob[i:i + 32]) + ',')
    c.append('};')
    (ROOT / 'src/assets.c').write_text('\n'.join(c) + '\n')
    print('sprites: %d, blob: %d bytes, palettes: %d' % (len(pk.sprites), len(blob), len(pk.palettes)))


if __name__ == '__main__':
    main()