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.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
FNAF: a picture codec for the TI-84 Plus CE
Mason3634a856cd03953
diff --git a/games/fnaf/ce/engine/pic.c b/games/fnaf/ce/engine/pic.cnew file mode 100644index 00000000..62e2d9df--- /dev/null+++ b/games/fnaf/ce/engine/pic.c@@ -0,0 +1,166 @@+/* Decoding the pictures (pic.h; tools/cpic.py writes them). Written for the eZ80 as much as C allows: int is+ * 24 bits there, so no value here needs more (the coefficients stay within +-2^17). */+#include "pic.h"+#include <string.h>++typedef struct {+ int32_t maxcode[18]; /* the largest code of each length (-1: none), 17 ends the search */+ int16_t valoff[17]; /* code - valoff[l]: the symbol's place in vals */+ const uint8_t *vals;+} Huff;++static Huff huff[4]; /* Y DC, Y AC, colour DC, colour AC */+static const uint8_t *quant; /* per quality: 16 Y steps then 16 colour steps (u16, raster order) */++static const uint8_t ZZ[16] = {0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15};++void pic_init(const uint8_t *t) {+ int nq = *t++;+ quant = t;+ t += nq * 64;+ for (int k = 0; k < 4; k++) {+ Huff *h = &huff[k];+ const uint8_t *counts = t;+ t += 16;+ h->vals = t;+ int32_t code = 0;+ int n = 0;+ for (int l = 1; l <= 16; l++) {+ int c = counts[l - 1];+ h->valoff[l] = (int16_t)(code - n);+ code += c;+ n += c;+ h->maxcode[l] = c ? code - 1 : -1;+ code <<= 1;+ }+ h->maxcode[17] = 0x7FFFFFFF;+ t += n;+ }+}++int pic_width(const uint8_t *pic) { return pic[1] * 8; }+int pic_height(const uint8_t *pic) { return pic[2] * 8; }+int pic_base(const uint8_t *pic) { return pic[0] & 1 ? pic[4] | pic[5] << 8 : -1; }++/* ------------------------------------------------------------------ bits */+static const uint8_t *bp;+static uint8_t bitbuf, bitcnt;++static unsigned bit(void) {+ if (!bitcnt) bitbuf = *bp++, bitcnt = 8;+ bitcnt--;+ unsigned b = bitbuf >> 7;+ bitbuf = (uint8_t)(bitbuf << 1);+ return b;+}++static int bits(int n) {+ int v = 0;+ while (n--) v = v << 1 | (int)bit();+ return v;+}++/* JPEG's: s bits to a signed value */+static int extend(int s) {+ if (!s) return 0;+ int v = bits(s);+ return v < 1 << (s - 1) ? v - (1 << s) + 1 : v;+}++static int decode(const Huff *h) {+ int32_t code = 0;+ int l = 1;+ for (;; l++) {+ code = code << 1 | (int32_t)bit();+ if (code <= h->maxcode[l]) break;+ if (l == 16) return 0; /* (corrupt) */+ }+ return h->vals[(code - h->valoff[l]) & 0xFF];+}++static int golomb(void) {+ int n = 0;+ while (!bit() && n < 20) n++;+ return ((1 << n) | bits(n)) - 1;+}++/* ------------------------------------------------------------------ a block */+/* decodes a 4 x 4 block into out (raster order): t the table pair (0 Y, 2 colour), q its steps */+static void block(int t, int *pred, const uint8_t *q, int *out) {+ int c[16];+ memset(c, 0, sizeof c);+ *pred += extend(decode(&huff[t]));+ c[0] = *pred * (q[0] | q[1] << 8);+ bool ac = false;+ for (int k = 1; k < 16; k++) {+ int rs = decode(&huff[t + 1]);+ if (!rs) break;+ k += rs >> 4;+ if (k > 15) break;+ int z = ZZ[k];+ c[z] = extend(rs & 15) * (q[2 * z] | q[2 * z + 1] << 8);+ ac = true;+ }+ if (!ac) { /* one value */+ int v = (c[0] + 32) >> 6;+ for (int i = 0; i < 16; i++) out[i] = v;+ return;+ }+ int r[16];+ for (int i = 0; i < 16; i += 4) { /* rows */+ int e = c[i] + c[i + 2], f = c[i] - c[i + 2];+ int g = (c[i + 1] >> 1) - c[i + 3], h = c[i + 1] + (c[i + 3] >> 1);+ r[i] = e + h, r[i + 1] = f + g, r[i + 2] = f - g, r[i + 3] = e - h;+ }+ for (int j = 0; j < 4; j++) { /* columns */+ int e = r[j] + r[j + 8], f = r[j] - r[j + 8];+ int g = (r[j + 4] >> 1) - r[j + 12], h = r[j + 4] + (r[j + 12] >> 1);+ out[j] = (e + h + 32) >> 6, out[j + 4] = (f + g + 32) >> 6;+ out[j + 8] = (f - g + 32) >> 6, out[j + 12] = (e - h + 32) >> 6;+ }+}++/* ------------------------------------------------------------------ a picture */+/* the ordered dither: on Y (0..7) for each pixel of a macroblock, on Cb and Cr (0..30) for each 2 x 2 */+static const uint8_t DY[64] = {+ 0, 4, 1, 5, 0, 4, 1, 5, 6, 2, 7, 3, 6, 2, 7, 3, 1, 5, 0, 4, 1, 5, 0, 4, 7, 3, 6, 2, 7, 3, 6, 2,+ 0, 4, 1, 5, 0, 4, 1, 5, 6, 2, 7, 3, 6, 2, 7, 3, 1, 5, 0, 4, 1, 5, 0, 4, 7, 3, 6, 2, 7, 3, 6, 2};+static const uint8_t DCB[16] = {0, 16, 4, 20, 24, 8, 28, 12, 6, 22, 2, 18, 30, 14, 26, 10};+static const uint8_t DCR[16] = {30, 14, 26, 10, 6, 22, 2, 18, 24, 8, 28, 12, 0, 16, 4, 20};++static int clampi(int v, int lo, int hi) { return v < lo ? lo : v >= hi ? hi - 1 : v; }++void pic_decode(const uint8_t *pic, uint8_t *dst, int stride, const PicMap *m) {+ int flags = pic[0], mw = pic[1], mh = pic[2];+ const uint8_t *qy = quant + 64 * pic[3], *qc = qy + 32;+ bp = pic + (flags & 1 ? 6 : 4);+ bitcnt = 0;+ bool skips = (flags & 2) != 0;+ int total = mw * mh, at = skips ? golomb() : 0, last = -1;+ int pred[3] = {0, 0, 0};+ int y[4][16], cb[16], cr[16];+ for (; at < total; at++) {+ int my = at / mw, mx = at - my * mw;+ if (at != last + 1 || mx == 0) pred[0] = pred[1] = pred[2] = 0;+ last = at;+ for (int k = 0; k < 4; k++) block(0, &pred[0], qy, y[k]);+ block(2, &pred[1], qc, cb);+ block(2, &pred[2], qc, cr);+ /* to palette indices: each 2 x 2 shares its colour */+ uint8_t *row = dst + my * 8 * stride + mx * 8;+ for (int ci = 0; ci < 16; ci++) {+ int cy = ci >> 2, cx = ci & 3;+ int part = (m->cbq[clampi(cb[ci], CQ_LO, CQ_HI) - CQ_LO] + DCB[ci]) >> 5 << 3 |+ (m->crq[clampi(cr[ci], CQ_LO, CQ_HI) - CQ_LO] + DCR[ci]) >> 5;+ for (int dy = 0; dy < 2; dy++)+ for (int dx = 0; dx < 2; dx++) {+ int py = cy * 2 + dy, px = cx * 2 + dx; /* in the macroblock */+ int v = y[(py >> 2) * 2 + (px >> 2)][(py & 3) * 4 + (px & 3)] + 128;+ uint8_t o = m->lut[(m->yq[clampi(v, YQ_LO, YQ_HI) - YQ_LO] + DY[py * 8 + px]) >> 3 << 6 | part];+ if (m->phase) o |= m->phase[(mx * 8 + px + m->phase[(my * 8 + py) & 255]) & 255] & 3;+ row[py * stride + px] = o;+ }+ }+ if (skips) at += golomb();+ }+}diff --git a/games/fnaf/ce/engine/pic.h b/games/fnaf/ce/engine/pic.hnew file mode 100644index 00000000..cbe85167--- /dev/null+++ b/games/fnaf/ce/engine/pic.h@@ -0,0 +1,32 @@+/* The pictures (tools/cpic.py codes them): decoded into palette indices, a macroblock of 8 x 8 at a time.+ *+ * A picture is H.264's 4 x 4 integer transform of Y, Cb and Cr (the colour at half resolution), Huffman coded;+ * one coded over its base keeps the base's macroblocks it skips (what dst already holds). Each picture group+ * (the office, a camera, a jumpscare...) has a Map: from (Y, Cb, Cr) to its palette, with ordered dithering. */+#ifndef CE_PIC_H+#define CE_PIC_H+#include <stdbool.h>+#include <stdint.h>++#define YQ_LO (-96) /* the Y values the Map's YQ covers: YQ_LO to YQ_HI - 1 (dither included) */+#define YQ_HI 352+#define CQ_LO (-192) /* and the colour ones */+#define CQ_HI 192++typedef struct {+ const uint8_t *yq; /* (YQ_HI - YQ_LO): Y -> its place among the 32 levels, times 8 */+ const uint8_t *cbq; /* (CQ_HI - CQ_LO): Cb -> its place among 8 levels, times 32 */+ const uint8_t *crq; /* and Cr */+ const uint8_t *lut; /* 32 x 8 x 8: the levels -> a palette index */+ const uint8_t *phase; /* NULL, or 256 random bytes: the static's phase (their low 2 bits), ORed in */+} PicMap;++/* the codec's tables (the Huffman tables, the dequantization steps), from the data: once */+void pic_init(const uint8_t *tables);+/* a picture's size in pixels, and the base picture it is coded over (-1: none) */+int pic_width(const uint8_t *pic);+int pic_height(const uint8_t *pic);+int pic_base(const uint8_t *pic);+/* decodes the picture into dst (stride bytes a row, room for all of it) */+void pic_decode(const uint8_t *pic, uint8_t *dst, int stride, const PicMap *m);+#endifdiff --git a/games/fnaf/ce/tools/cpic.py b/games/fnaf/ce/tools/cpic.pynew file mode 100644index 00000000..eb9e10cf--- /dev/null+++ b/games/fnaf/ce/tools/cpic.py@@ -0,0 +1,435 @@+#!/usr/bin/env python3+"""The CE pictures' codec: what src/pic.c decodes, made small enough for the calculator's archive.++A picture is coded like a little JPEG made for the eZ80: Y, Cb and Cr (the colour at half resolution), in+macroblocks of 8 x 8 pixels (four 4 x 4 blocks of Y, one of Cb, one of Cr), each 4 x 4 block a list of+coefficients of H.264's integer transform (adds and shifts only, no multiplications to undo it), quantized,+then Huffman coded (DC: the difference from the block before; AC: run and size, as JPEG). A picture may be+coded over another one (its base: a camera with someone in it over the empty room, an animation's frame over+the frame before): then only the macroblocks that differ are coded, each after the number skipped.++The calculator shows 256 colours: a picture group (the office, a camera, a jumpscare...) has its palette and+a table from (Y, Cb, Cr) to a palette index, with ordered dithering on the way (tables YQ, CQ). Decoding gives+palette indices straight away.++ bitstream: MSB first. Picture header (bytes): flags (1 base, 2 skips coded), mb width, mb height, quality,+ then (if base) the base picture's id (u16). Then for each coded macroblock (with skips: an Exp-Golomb+ count of macroblocks skipped first; the end is a count that runs past the last one): Y0 Y1 Y2 Y3 Cb Cr.+ A block: DC size (Huffman) + bits, then AC (run << 4 | size) + bits until EOB (0) or the 15th."""+import heapq+import math+from collections import Counter++import numpy as np++# the 4 x 4 zigzag: zigzag position -> raster index (row * 4 + column)+ZZ = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]+ROW_NORM2 = [4.0, 2.5, 4.0, 2.5] # the inverse core's basis rows: their squared norms+++def inv_core(c):+ """H.264's inverse 4 x 4 transform, exactly as pic.c does it: c (..., 16) integers in raster order ->+ (..., 16) values ((x + 32) >> 6)"""+ c = c.reshape(c.shape[:-1] + (4, 4)).astype(np.int64)++ def one(d0, d1, d2, d3):+ e, f = d0 + d2, d0 - d2+ g, h = (d1 >> 1) - d3, d1 + (d3 >> 1)+ return e + h, f + g, f - g, e - h++ r = one(c[..., 0], c[..., 1], c[..., 2], c[..., 3]) # rows: along the last axis+ t = np.stack(r, axis=-1)+ col = one(t[..., 0, :], t[..., 1, :], t[..., 2, :], t[..., 3, :])+ u = np.stack(col, axis=-2)+ return ((u + 32) >> 6).reshape(u.shape[:-2] + (16,))+++def _basis():+ """the decoder's output for a coefficient of 1 (without its roundings): 16 patterns of 16"""+ b = np.zeros((16, 16))+ one = [[1, 1, 1, 1], [1, 0.5, -0.5, -1], [1, -1, -1, 1], [0.5, -1, 1, -0.5]]+ for i in range(4):+ for j in range(4):+ b[i * 4 + j] = np.outer(one[i], one[j]).reshape(16) / 64+ return b+++BASIS = _basis()+ANALYSE = np.linalg.inv(BASIS) # x (16) @ ANALYSE -> the coefficients giving back x+NORM = np.array([math.sqrt(ROW_NORM2[i // 4] * ROW_NORM2[i % 4]) / 64 for i in range(16)])+++def qtable(step, slope):+ """the dequantization steps (raster order): step (in pixel levels) for DC, rising with frequency"""+ q = []+ for k in range(16):+ i, j = k // 4, k % 4+ d = step * 4 * (1 + slope * (i + j)) # in the orthonormal transform's units+ q.append(max(1, int(round(d / NORM[k] / 4))))+ return np.array(q, dtype=np.int64)+++# ------------------------------------------------------------------ colour+def ycc(rgb):+ r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]+ y = 0.299 * r + 0.587 * g + 0.114 * b+ cb = -0.168736 * r - 0.331264 * g + 0.5 * b+ cr = 0.5 * r - 0.418688 * g - 0.081312 * b+ return y, cb, cr+++def rgb_of(y, cb, cr):+ return np.stack([y + 1.402 * cr, y - 0.344136 * cb - 0.714136 * cr, y + 1.772 * cb], -1)+++# ------------------------------------------------------------------ coding a picture+class Coded:+ """a picture coded: its macroblocks' symbols, and what the decoder will have (Y, Cb, Cr planes)"""++ def __init__(self, mw, mh, quality, base):+ self.mw, self.mh, self.quality, self.base = mw, mh, quality, base+ self.mbs = [] # (index, [6 blocks of (dc level, [16 levels zigzag])])+ self.rec = None # (y, cb, cr) integer planes, y at full size, chroma at half+++def blocks_of(plane):+ h, w = plane.shape+ return plane.reshape(h // 4, 4, w // 4, 4).transpose(0, 2, 1, 3).reshape(h // 4, w // 4, 16)+++def plane_of(blocks):+ nby, nbx, _ = blocks.shape+ return blocks.reshape(nby, nbx, 4, 4).transpose(0, 2, 1, 3).reshape(nby * 4, nbx * 4)+++def quantize(x, q, dz):+ """x (..., 16) values -> levels (..., 16), raster order"""+ c = x @ ANALYSE+ v = c / q+ lv = np.sign(v) * np.floor(np.abs(v) + dz)+ lv[..., 0] = np.round(v[..., 0])+ return lv.astype(np.int64)+++def code(rgb, quality, base=None, skip=None):+ """rgb: (h, w, 3) floats, h and w multiples of 8. quality: (qy, qc, dz). base: a Coded of the same size+ whose decoded planes this one starts from: a macroblock skip(new, old) finds near enough to the source the+ base's one was made from is kept as it is (no drift along an animation's frames)."""+ h, w = rgb.shape[:2]+ assert h % 8 == 0 and w % 8 == 0+ mw, mh = w // 8, h // 8+ qy, qc, dz = quality+ y, cb, cr = ycc(rgb)+ sub = lambda c: c.reshape(h // 2, 2, w // 2, 2).mean(axis=(1, 3)) # noqa: E731+ planes = [y - 128, sub(cb), sub(cr)]+ lv = [quantize(blocks_of(planes[0]), qy, dz), quantize(blocks_of(planes[1]), qc, dz),+ quantize(blocks_of(planes[2]), qc, dz)]+ rec = [plane_of(inv_core(lv[0] * qy)) + 128, plane_of(inv_core(lv[1] * qc)), plane_of(inv_core(lv[2] * qc))]+ src = [planes[0] + 128, planes[1], planes[2]]+ out = Coded(mw, mh, quality, base)+ keep = np.ones((mh, mw), bool)+ if base is not None:+ assert (base.mw, base.mh) == (mw, mh)+ for my in range(mh):+ for mx in range(mw):+ ys, xs = slice(my * 8, my * 8 + 8), slice(mx * 8, mx * 8 + 8)+ cs, cxs = slice(my * 4, my * 4 + 4), slice(mx * 4, mx * 4 + 4)+ new = (src[0][ys, xs], src[1][cs, cxs], src[2][cs, cxs])+ old = (base.src[0][ys, xs], base.src[1][cs, cxs], base.src[2][cs, cxs])+ if skip(new, old):+ keep[my, mx] = False+ for k, (a_, b_) in enumerate(((ys, xs), (cs, cxs), (cs, cxs))):+ rec[k][a_, b_] = base.rec[k][a_, b_]+ src[k][a_, b_] = base.src[k][a_, b_]+ for my in range(mh):+ for mx in range(mw):+ if not keep[my, mx]:+ continue+ bl = []+ for by_, bx_ in ((0, 0), (0, 1), (1, 0), (1, 1)):+ bl.append(lv[0][my * 2 + by_, mx * 2 + bx_])+ bl.append(lv[1][my, mx])+ bl.append(lv[2][my, mx])+ out.mbs.append((my * mw + mx, [[int(b[ZZ[k]]) for k in range(16)] for b in bl]))+ out.rec = rec+ out.src = src+ return out+++def default_skip(ymax, ymean, cmax):+ def skip(new, old):+ dy = np.abs(new[0] - old[0])+ dc = max(np.abs(new[1] - old[1]).max(), np.abs(new[2] - old[2]).max())+ return dy.max() <= ymax and dy.mean() <= ymean and dc <= cmax+ return skip+++# ------------------------------------------------------------------ the symbols, Huffman, bits+def size_of(v):+ v = abs(v)+ return v.bit_length()+++def stream(coded):+ """what a coded picture writes, in order: ("g", n) an Exp-Golomb count, ("h", table, symbol, value, size)+ a Huffman symbol (tables 0 Y DC, 1 Y AC, 2 colour DC, 3 colour AC) and its size bits of value"""+ out = []+ pred = [0, 0, 0]+ last = -1+ skips = coded.base is not None+ total = coded.mw * coded.mh+ for idx, blocks in coded.mbs:+ if skips:+ out.append(("g", idx - last - 1))+ if idx != last + 1 or idx % coded.mw == 0:+ pred = [0, 0, 0]+ last = idx+ for k, blk in enumerate(blocks):+ comp = 0 if k < 4 else k - 3+ t = 0 if k < 4 else 2+ d = blk[0] - pred[comp]+ pred[comp] = blk[0]+ out.append(("h", t, size_of(d), d, size_of(d)))+ run = 0+ nz = [i for i in range(1, 16) if blk[i]]+ lastnz = nz[-1] if nz else 0+ for i in range(1, lastnz + 1):+ if blk[i] == 0:+ run += 1+ continue+ s = size_of(blk[i])+ out.append(("h", t + 1, run << 4 | s, blk[i], s))+ run = 0+ if lastnz < 15:+ out.append(("h", t + 1, 0, 0, 0))+ if skips:+ out.append(("g", total - last - 1))+ return out+++def count(streams):+ """symbol counts of the four tables over many pictures"""+ freq = [Counter() for _ in range(4)]+ for st in streams:+ for it in st:+ if it[0] == "h":+ freq[it[1]][it[2]] += 1+ return freq+++def huffman_lengths(freq, limit=16):+ """code lengths from symbol counts, at most limit bits (package-merge would be exact; this squeezes)"""+ if not freq:+ return {}+ if len(freq) == 1:+ return {next(iter(freq)): 1}+ heap = [(f, i, [s]) for i, (s, f) in enumerate(sorted(freq.items()))]+ heapq.heapify(heap)+ depth = {s: 0 for s in freq}+ n = len(heap)+ while len(heap) > 1:+ f1, _, s1 = heapq.heappop(heap)+ f2, _, s2 = heapq.heappop(heap)+ for s in s1 + s2:+ depth[s] += 1+ heapq.heappush(heap, (f1 + f2, n, s1 + s2))+ n += 1+ while max(depth.values()) > limit: # flatten: the rarest symbols up, Kraft kept+ for s in sorted(depth, key=lambda s: (-depth[s], freq[s])):+ if depth[s] > limit:+ depth[s] = limit+ while sum(2.0 ** -d for d in depth.values()) > 1:+ s = max((s for s in depth if depth[s] < limit), key=lambda s: (depth[s], -freq[s]))+ depth[s] += 1+ return depth+++def canonical(lengths):+ """lengths -> (codes {sym: (code, len)}, counts per length 1..16, symbols in order)"""+ items = sorted(lengths.items(), key=lambda kv: (kv[1], kv[0]))+ codes, code, prev = {}, 0, 0+ counts = [0] * 17+ for s, l in items:+ code <<= l - prev+ prev = l+ codes[s] = (code, l)+ code += 1+ counts[l] += 1+ return codes, counts[1:], [s for s, _ in items]+++class Bits:+ def __init__(self):+ self.out = bytearray()+ self.acc = 0+ self.n = 0++ def put(self, v, n):+ for i in range(n - 1, -1, -1):+ self.acc = self.acc << 1 | (v >> i & 1)+ self.n += 1+ if self.n == 8:+ self.out.append(self.acc)+ self.acc = self.n = 0++ def golomb(self, v):+ """Exp-Golomb of v >= 0"""+ v += 1+ n = v.bit_length()+ self.put(0, n - 1)+ self.put(v, n)++ def done(self):+ if self.n:+ self.put(0, 8 - self.n)+ return bytes(self.out)+++def write(coded, st, codes, quality_id, base_id=None):+ """a coded picture (and its stream) -> its bytes: the header, then the bits. codes: the 4 tables' codes"""+ flags = (1 if base_id is not None else 0) | (2 if coded.base is not None else 0)+ head = bytes([flags, coded.mw, coded.mh, quality_id])+ if base_id is not None:+ head += bytes([base_id & 255, base_id >> 8])+ b = Bits()+ for it in st:+ if it[0] == "g":+ b.golomb(it[1])+ continue+ _, t, sym, v, s = it+ c, l = codes[t][sym]+ b.put(c, l)+ if s:+ b.put(v if v > 0 else v + (1 << s) - 1, s)+ return head + b.done()+++def tables_blob(qualities, codes_counts):+ """pic_init's tables: the qualities' steps (u16, raster: 16 Y then 16 colour), then the 4 Huffman tables+ (16 counts, then the symbols)"""+ out = bytearray([len(qualities)])+ for qy, qc, _ in qualities:+ for v in list(qy) + list(qc):+ out += int(v).to_bytes(2, "little")+ for counts, syms in codes_counts:+ out += bytes(counts) + bytes(syms)+ return bytes(out)+++# ------------------------------------------------------------------ palettes: (Y, Cb, Cr) -> an index+Y_LEVELS, C_LEVELS = 32, 8+YQ_LO, YQ_HI, CQ_LO, CQ_HI = -96, 352, -192, 192+# the ordered dither (0..15) of a pixel in a macroblock, and of its 2 x 2's colour+B4 = np.array([[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]])+DY = np.array([[B4[r & 3][c & 3] for c in range(8)] for r in range(8)])+DCB = B4.copy()+DCR = 15 - DCB+++def to565(c):+ c = np.clip(np.round(c), 0, 255)+ r = np.round(c[..., 0] * 31 / 255) * 255 / 31+ g = np.round(c[..., 1] * 63 / 255) * 255 / 63+ b = np.round(c[..., 2] * 31 / 255) * 255 / 31+ return np.stack([r, g, b], -1)+++def word1555(c):+ """a 565 colour as the CE's palette holds it: 1555, the top bit green's lowest"""+ r, g, b = int(round(c[0] * 31 / 255)), int(round(c[1] * 63 / 255)), int(round(c[2] * 31 / 255))+ return (g & 1) << 15 | r << 10 | (g >> 1) << 5 | b+++def spread(lo, hi, n, gamma):+ """n levels from lo to hi, closer together at the dark end (gamma > 1)"""+ t = np.linspace(0, 1, n) ** gamma+ return lo + (hi - lo) * t+++def position(levels, v, scale):+ """v -> its place among the levels (0 .. n-1, linear between two), times scale, as integers"""+ p = np.interp(v, levels, np.arange(len(levels)))+ return np.clip(np.floor(p * scale), 0, (len(levels) - 1) * scale).astype(np.int64)+++class Group:+ """a palette group: the pictures shown together (the office, a camera, a jumpscare...). Its colours (240,+ or 60 for 4 phases of static) and the decoder's tables to them"""++ def __init__(self, name, ncolors=240, phases=1):+ self.name, self.ncolors, self.phases = name, ncolors, phases+ self.planes = [] # decoded (y, cb, cr) of its pictures++ def fit(self, seed=1):+ from scipy.cluster.vq import kmeans2+ from scipy.spatial import cKDTree+ ys = np.concatenate([p[0].ravel() for p in self.planes]).astype(np.float64)+ cbs = np.concatenate([p[1].ravel() for p in self.planes]).astype(np.float64)+ crs = np.concatenate([p[2].ravel() for p in self.planes]).astype(np.float64)+ lo, hi = max(0.0, np.percentile(ys, 0.1) - 1), min(255.0, np.percentile(ys, 99.95) + 1)+ self.ylev = spread(lo, hi, Y_LEVELS, 1.6)+ self.cblev = np.linspace(np.percentile(cbs, 0.3) - 1, np.percentile(cbs, 99.7) + 1, C_LEVELS)+ self.crlev = np.linspace(np.percentile(crs, 0.3) - 1, np.percentile(crs, 99.7) + 1, C_LEVELS)+ # the cells the pictures use (as the decoder dithers them), weighted by use: k-means on their colours+ used = Counter()+ for y, cb, cr in self.planes:+ mapped = self.cells(y, cb, cr)+ used.update(mapped.ravel().tolist())+ cells = np.array(list(used.keys()))+ weight = np.array([used[c] for c in cells], dtype=np.float64)+ rgb = self.cell_rgb(cells)+ f = np.sqrt(rgb / 255) * 255+ n_pic = self.ncolors // self.phases+ rng = np.random.default_rng(seed)+ sample = f[rng.choice(len(f), 40000, p=weight / weight.sum())] if len(f) > n_pic else f+ k = min(n_pic, len(cells))+ cent, _ = kmeans2(sample, k, minit="++", seed=seed, iter=30)+ pal = np.unique(to565((np.clip(cent, 0, 255) / 255) ** 2 * 255), axis=0)+ self.pal = pal+ tree = cKDTree(np.sqrt(pal / 255) * 255)+ allc = np.arange(Y_LEVELS * C_LEVELS * C_LEVELS)+ _, idx = tree.query(np.sqrt(self.cell_rgb(allc) / 255) * 255)+ self.lut = idx.astype(np.int64) * self.phases++ def cell_rgb(self, cells):+ yl, cbl, crl = cells >> 6, cells >> 3 & 7, cells & 7+ return np.clip(rgb_of(self.ylev[yl], self.cblev[cbl], self.crlev[crl]), 0, 255)++ def tables(self):+ """YQ (u8 for Y + 128 from YQ_LO): its place among the levels times 8, CBQ/CRQ (Cb, Cr from CQ_LO): times 32"""+ yq = position(self.ylev, np.arange(YQ_LO, YQ_HI), 8)+ cbq = position(self.cblev, np.arange(CQ_LO, CQ_HI), 32)+ crq = position(self.crlev, np.arange(CQ_LO, CQ_HI), 32)+ return yq, cbq, crq++ def cells(self, y, cb, cr):+ """decoded planes (y: Y + 128, full size; cb, cr half) -> each pixel's cell (y level << 6 | cb << 3 | cr),+ as pic.c finds it"""+ yq, cbq, crq = self.tables()+ h, w = y.shape+ dy = np.tile(DY, (h // 8, w // 8)) >> 1+ dcb = np.tile(DCB, (h // 8, w // 8))+ dcr = np.tile(DCR, (h // 8, w // 8))+ yl = (yq[np.clip(y, YQ_LO, YQ_HI - 1) - YQ_LO] + dy) >> 3+ cbl = (cbq[np.clip(cb, CQ_LO, CQ_HI - 1) - CQ_LO] + (dcb << 1)) >> 5+ crl = (crq[np.clip(cr, CQ_LO, CQ_HI - 1) - CQ_LO] + (dcr << 1)) >> 5+ part = np.repeat(np.repeat(cbl << 3 | crl, 2, 0), 2, 1)+ return yl << 6 | part++ def indices(self, planes):+ return self.lut[self.cells(*planes)]++ def rgb(self, idx):+ return self.pal[idx // self.phases]++ def blob(self, fixed):+ """the map in the data: 256 palette words (the group's colours, then fixed at the end), YQ, CBQ, CRQ, LUT"""+ words = []+ for c in self.pal:+ words += [word1555(c)] * self.phases+ words += [0] * (256 - len(fixed) - len(words))+ words += [word1555(c) for c in fixed]+ assert len(words) == 256, (self.name, len(words))+ yq, cbq, crq = self.tables()+ out = b"".join(w.to_bytes(2, "little") for w in words)+ return out + bytes(yq.tolist()) + bytes(cbq.tolist()) + bytes(crq.tolist()) + bytes(self.lut.tolist())diff --git a/games/fnaf/ce/tools/pack.py b/games/fnaf/ce/tools/pack.pynew file mode 100644index 00000000..50ee5eee--- /dev/null+++ b/games/fnaf/ce/tools/pack.py@@ -0,0 +1,408 @@+#!/usr/bin/env python3+"""Five Nights at Freddy's on the TI-84 Plus CE: its pictures, fonts and tables -> data/*.bin + src/assets.h.++ python3 -I tools/pack.py REF (REF: the folder ../tools/fetch.py filled; Python + Pillow + NumPy + SciPy,+ and the CE toolchain's convbin for zx0)++The pictures are the NumWorks version's (../tools/pack.py makes them from the game's), coded by tools/cpic.py:+the office and the cameras at 533 x 120 (the calculator doubles each row), the jumpscares and the monitor at+160 x 120 (doubled both ways), the newspaper, the paychecks and the like at 320 x 240.++data/FNAFD<n>.bin become the appvars FNAFD0, FNAFD1... (each under 64 KB): the blobs one after the other.+src/assets.h says where each one is (asset_at: the appvar << 16 | its offset), and the pictures' places."""+import os+import struct+import subprocess+import sys+import tempfile++import numpy as np+from PIL import Image++HERE = os.path.dirname(os.path.abspath(__file__))+CE = os.path.dirname(HERE)+GAME = os.path.dirname(CE)+sys.path.insert(0, HERE)+sys.path.insert(0, os.path.join(GAME, "tools"))+import cpic as C # noqa: E402+import pack as NW # noqa: E402 (the NumWorks version's pictures)++CONVBIN = os.path.join(os.environ.get("CEDEV", os.path.expanduser("~/Documents/Assets/toolchains/CEdev")), "bin",+ "convbin")+VAR_PREFIX = "FNAFD"+VAR_ROOM = 65000+FONT_DIRS = [os.path.expanduser("~/Documents/Assets/gamesrc/fonts/dejavu")]++# the qualities: (step, slope, dead zone); colour steps 1.6 times Y's+QUALITY = {"office": (4.5, 0.3), "cam": (6.5, 0.35), "scare": (7.5, 0.35), "still": (5.0, 0.3), "small": (4.0, 0.3)}+QNAMES = list(QUALITY)+Q = [(C.qtable(s, sl), C.qtable(s * 1.6, sl), 0.36) for s, sl in QUALITY.values()]++# the fixed colours, the last 32 of every palette (UI_* in assets.h)+UI = [("BLACK", 0x000000), ("WHITE", 0xFFFFFF), ("WHITE2", 0xAAAAAA), ("WHITE1", 0x555555),+ ("GREY", 0xC8C8C8), ("GREY2", 0x858585), ("GREY1", 0x434343), ("SILVER", 0xB0B0B0), ("DIM", 0x909090),+ ("CAPTION", 0xD8E8FF), ("CAPTION2", 0x9098A8), ("CAPTION1", 0x484C55),+ ("CALL", 0xF2F2C8), ("CALL2", 0xA0A084), ("CALL1", 0x505042),+ ("MINT", 0x8FD18F), ("MINT2", 0x5E8A5E), ("MINT1", 0x2F452F),+ ("REC", 0xE02020), ("BAR_G", 0x00C000), ("BAR_Y", 0xE6E600), ("BAR_R", 0xE00000),+ ("BAR_GL", 0x66D966), ("BAR_YL", 0xEEEE66), ("BAR_RL", 0xEB6666),+ ("MAP_ON", 0x8BC34A), ("MAP_LINE", 0xD0D0D0), ("FRAME", 0xA0A0A0), ("BOX", 0x202020), ("EDGE", 0x404040),+ ("MAP_OFF", 0x424242), ("SPARE", 0x707070)]+assert len(UI) == 32+UI_RGB = [((v >> 16) & 255, (v >> 8) & 255, v & 255) for _, v in UI]+++def zx0(data):+ with tempfile.TemporaryDirectory() as d:+ i, o = os.path.join(d, "i"), os.path.join(d, "o")+ open(i, "wb").write(bytes(data))+ subprocess.run([CONVBIN, "-j", "bin", "-k", "bin", "-c", "zx0", "-i", i, "-o", o, "-l", "0"], check=True)+ return open(o, "rb").read()+++# ------------------------------------------------------------------ the pictures+def pad8(a):+ h, w = a.shape[:2]+ H, W = -(-h // 8) * 8, -(-w // 8) * 8+ return np.pad(a, ((0, H - h), (0, W - w), (0, 0)), mode="edge")+++def resize(a, w, h):+ return np.asarray(Image.fromarray(np.clip(a, 0, 255).astype(np.uint8)).resize((w, h), Image.LANCZOS)).astype(+ np.float64)+++def halfv(a):+ return resize(a, a.shape[1], (a.shape[0] + 1) // 2)+++class Pic:+ def __init__(self, name, rgb, group, quality, base=None, skip=None, x=0, y=0):+ self.name, self.group, self.q = name, group, QNAMES.index(quality)+ self.rgb = pad8(rgb)+ self.base, self.skip, self.x, self.y = base, skip, x, y+++PICS = []+GROUPS = {}+DEFINES = []+++def group(name, phases=1):+ GROUPS[name] = C.Group(name, 224, phases)+ return name+++def pic(name, rgb, grp, quality, base=None, skip=None, x=0, y=0):+ p = Pic(name, rgb, grp, quality, base, skip, x, y)+ PICS.append(p)+ return p+++def define(name, value):+ DEFINES.append((name, value))+++TIGHT = C.default_skip(10, 1.6, 8) # variants: what differs from the base's own source+ANIM = C.default_skip(14, 2.5, 10) # an animation's frames: what moved+++def mb_box(a, b, thresh=10):+ """the macroblocks (8 x 8) where a and b differ: x0, y0, x1, y1 in pixels"""+ d = np.abs(pad8(a) - pad8(b)).max(axis=2)+ h, w = d.shape+ m = d.reshape(h // 8, 8, w // 8, 8).max(axis=(1, 3)) > thresh+ ys, xs = np.nonzero(m)+ return xs.min() * 8, ys.min() * 8, (xs.max() + 1) * 8, (ys.max() + 1) * 8+++def office_pictures(N):+ g = group("office")+ office = halfv(N["OFFICE"])+ base = pic("OFFICE", office, g, "office")+ define("OFFICE_W", office.shape[1])+ # the lights: each side's lit doorway, a patch over the office (with Bonnie or Chica: over it again)+ for side, lit, who in (("L", "OFFICE_LL", "OFFICE_LLB"), ("R", "OFFICE_RL", "OFFICE_RLC")):+ a, b = halfv(N[lit]), halfv(N[who])+ x0, y0, x1, y1 = [min(v1, v2) if k < 2 else max(v1, v2)+ for k, (v1, v2) in enumerate(zip(mb_box(a, office), mb_box(b, office)))]+ p = pic(f"LIGHT_{side}", pad8(a)[y0:y1, x0:x1], g, "office", x=x0, y=y0)+ pic(f"LIGHT_{side}_WHO", pad8(b)[y0:y1, x0:x1], g, "office", base=p, skip=TIGHT, x=x0, y=y0)+ define(f"LIGHT_{side}_X", x0)+ define(f"LIGHT_{side}_Y", y0)+ define(f"LIGHT_{side}_W", x1 - x0)+ define(f"LIGHT_{side}_H", y1 - y0)+ # the doors, buttons, fan and Golden Freddy, as the NumWorks version places them (rows halved)+ for n in ("DOOR_L", "DOOR_R"):+ pic(n, halfv(N[n]), g, "office")+ for n in [f"PANEL_{s}{k}" for s in "LR" for k in range(4)] + ["FAN0", "FAN1", "FAN2", "OFFICE_GOLD"]:+ pic(n, halfv(N[n]), g, "office")+ # out of power: the dark office, and Freddy's face in the doorway (a patch)+ dark = halfv(N["DARK"])+ pic("DARK", dark, g, "office")+ df = halfv(N["DARK_FREDDY"])+ x0, y0, x1, y1 = mb_box(df, dark, 6)+ pic("DARK_FREDDY", pad8(df)[y0:y1, x0:x1], g, "office", x=x0, y=y0)+ for k, v in zip("XYWH", (x0, y0, x1 - x0, y1 - y0)):+ define(f"DARK_FREDDY_{k}", v)+++def camera_pictures(N):+ for cam, states in NW.CAMS.items():+ g = group("cam" + cam.lower(), 4)+ first = None+ for who, _ in states:+ name = f"CAM{cam}_{who.upper() or 'EMPTY'}"+ p = pic(name, halfv(N[name]), g, "cam", base=first, skip=TIGHT if first else None)+ first = first or p+ if cam == "2A":+ pic("CAM2A_DARK", halfv(N["CAM2A_DARK"]), g, "cam", base=first, skip=TIGHT)+ # Foxy running down the hall: the whole hall, each frame over the one before+ im = Image.open(NW.web("Foxy-Hallway.webp"))+ prev = first+ for i in range(min(im.n_frames, 18)):+ im.seek(i)+ a = halfv(np.asarray(im.convert("RGB").resize((NW.OW, NW.OH), Image.LANCZOS)).astype(np.float64))+ prev = pic(f"FOXYRUN{i}", a, g, "cam", base=prev, skip=ANIM)+ define("FOXYRUN_N", 18)+ if cam == "2B":+ pic("CAM2B_GOLD", halfv(N["CAM2B_GOLD"]), g, "cam", base=first, skip=TIGHT)+++def anim(name, frames, grp, quality="scare"):+ prev = None+ for i, a in enumerate(frames):+ prev = pic(f"{name}{i}", resize(a, 160, 120), grp, quality, base=prev, skip=ANIM if prev else None)+ define(f"{name}_N", len(frames))+++def scare_pictures(N):+ for name, n in (("BONNIE", 10), ("CHICA", 15), ("FREDDY", 20), ("FOXY", 19), ("POWEROUT", 21)):+ anim(name, [N[f"{name}{i}"] for i in range(n)], group(name.lower()))+ anim("FLIP", [N[f"FLIP{i}"] for i in range(11)], group("flip"))+ # the hallucinations' pictures (a frame now and then): small+ g = group("halluc")+ pic("HALLUC_GOLDEN", resize(N["GOLDEN"], 160, 120), g, "scare")+ pic("HALLUC_ENDO", resize(N["TITLE3"], 160, 120), g, "scare")+++def menu_pictures(N):+ g = group("title", 4)+ t0 = halfv(N["TITLE0"])+ pic("TITLE0", t0, g, "still")+ for k in (1, 2, 3): # Freddy's twitches: patches over the face+ a = halfv(N[f"TITLE{k}"])+ x0, y0, x1, y1 = mb_box(a, t0, 12)+ pic(f"TITLE{k}", pad8(a)[y0:y1, x0:x1], g, "still", x=x0, y=y0)+ for c, v in zip("XYWH", (x0, y0, x1 - x0, y1 - y0)):+ define(f"TITLE{k}_{c}", v)+ pic("NEWSPAPER", N["NEWSPAPER"], group("news"), "still")+ g = group("paper")+ for n in ("PAYCHECK", "OVERTIME", "PINKSLIP"):+ pic(n, N[n], g, "still")+ pic("GAMEOVER", N["GAMEOVER"], group("gameover", 4), "still")+ pic("GOLDEN", N["GOLDEN"], group("golden", 4), "still")+ g = group("faces")+ for n in ("FREDDY", "BONNIE", "CHICA", "FOXY"):+ pic(f"FACE_{n}", N[f"FACE_{n}"], g, "small")+++# ------------------------------------------------------------------ fonts, small pictures, the map+def font_blob(line, asc, glyphs):+ """line height, ascent, then 95 glyphs (32..126) of 8 bytes: advance, width, height, x, y (s8), 0, offset+ (u16, from the font's start) of rows of 2-bit alpha (4 pixels a byte, the first in the top bits)"""+ head = struct.pack("<BB", line, asc)+ rows = b""+ table = b""+ base = 2 + 8 * 95+ for adv, w, h, x, y, nib in glyphs:+ a4 = unnibble(nib, w, h)+ a2 = np.clip((a4.astype(np.int64) * 3 + 7) // 15, 0, 3)+ data = pack2(a2)+ table += struct.pack("<BBBbbBH", adv, w, h, x, y, 0, base + len(rows))+ rows += data+ return head + table + rows+++def unnibble(nib, w, h):+ if not w:+ return np.zeros((0, 0), np.int64)+ stride = (w + 1) // 2+ a = np.zeros((h, w), np.int64)+ for r in range(h):+ for c in range(w):+ b = nib[r * stride + c // 2]+ a[r, c] = (b >> 4) if c & 1 else b & 15+ return a+++def pack2(a2):+ h, w = a2.shape if a2.size else (0, 0)+ out = bytearray()+ for r in range(h):+ row = list(a2[r]) + [0, 0, 0]+ for c in range(0, w, 4):+ out.append(row[c] << 6 | row[c + 1] << 4 | row[c + 2] << 2 | row[c + 3])+ return bytes(out)+++def img_blob(alpha):+ a2 = np.clip(np.round(np.asarray(alpha, dtype=np.float64) / 255 * 3), 0, 3).astype(np.int64)+ h, w = a2.shape+ return struct.pack("<HH", w, h) + pack2(a2)+++def map_blob(raw):+ """the camera map: its walls as runs (count, then y, x, length as bytes) and the 11 buttons' centres"""+ size = struct.unpack_from("<H", raw, 0)[0]+ stride = (size + 7) // 8+ runs = []+ for r in range(size):+ row = raw[4 + r * stride:4 + (r + 1) * stride]+ c = 0+ while c < size:+ if row[c >> 3] >> (c & 7) & 1:+ s = c+ while c < size and row[c >> 3] >> (c & 7) & 1:+ c += 1+ runs.append((r, s, c - s))+ else:+ c += 1+ centres = raw[4 + size * stride:4 + size * stride + 44]+ out = struct.pack("<BH", size, len(runs)) + b"".join(struct.pack("<BBB", *r) for r in runs)+ return out + bytes(v for i in range(11) for v in struct.unpack_from("<HH", centres, 4 * i))+++# ------------------------------------------------------------------ all of it+def main():+ if len(sys.argv) != 2:+ raise SystemExit(__doc__)+ NW.REF = sys.argv[1]+ NW.FONT_DIRS[:0] = FONT_DIRS+ NW.office_pictures()+ NW.camera_pictures()+ NW.scare_pictures()+ NW.menu_pictures()+ N = {p.name: p.a[:p.h, :p.w].astype(np.float64) for p in NW.PICS}++ office_pictures(N)+ camera_pictures(N)+ scare_pictures(N)+ menu_pictures(N)++ # code every picture (bases first: they come first), then the palettes, then the Huffman tables+ print(f"coding {len(PICS)} pictures", flush=True)+ for p in PICS:+ p.coded = C.code(p.rgb, Q[p.q], base=p.base.coded if p.base else None, skip=p.skip)+ GROUPS[p.group].planes.append(p.coded.rec)+ for g in GROUPS.values():+ g.fit()+ streams = [C.stream(p.coded) for p in PICS]+ codes, cc = [], []+ for f in C.count(streams):+ cds, counts, syms = C.canonical(C.huffman_lengths(dict(f) or {0: 1}))+ codes.append(cds)+ cc.append((counts, syms))++ blobs = [] # (name, bytes)++ def blob(name, data):+ blobs.append((name, bytes(data)))++ blob("TABLES", C.tables_blob(Q, cc))+ gnames = list(GROUPS)+ for n in gnames:+ blob("MAP_" + n.upper(), zx0(GROUPS[n].blob(UI_RGB) + remaps(GROUPS[n])))+ pic_ids = {p.name: i for i, p in enumerate(PICS)}+ for p, st in zip(PICS, streams):+ blob("PIC_" + p.name, C.write(p.coded, st, codes, p.q, pic_ids[p.base.name] if p.base else None))+ fonts = [+ NW.ttf_font(NW.find_font("DejaVuSansMono-Bold.ttf"), 11),+ NW.ttf_font(NW.find_font("DejaVuSansMono.ttf"), 17),+ NW.ttf_font(NW.find_font("DejaVuSans.ttf"), 11),+ NW.fnt_font(NW.hx("numbers/NUMBER.fnt"), NW.hx("numbers/NUMBER.png"), 0.36),+ NW.fnt_font(NW.hx("numbers/PIXEL_NUMBER.fnt"), NW.hx("numbers/PIXEL_NUMBER.png"), 0.36),+ NW.ttf_font(NW.find_font("DejaVuSansMono.ttf"), 24),+ ]+ for n, f in zip(["HUD", "BIG", "TEXT", "CLOCK", "PIXEL", "HUGE"], fonts):+ blob("FONT_" + n, font_blob(*f))+ t = Image.open(NW.hx("mainmenu/texts/FIVE_GAME_TITLE.png")).convert("RGBA")+ t = t.resize((int(t.width * 0.5), int(t.height * 0.5)), Image.LANCZOS)+ a = np.asarray(t).astype(np.float64)+ blob("IMG_TITLE", img_blob(a[..., 3] * a[..., :3].mean(axis=2) / 255))+ s = Image.open(NW.hx("mainmenu/STAR.png")).convert("RGBA").resize((22, 21), Image.LANCZOS)+ a = np.asarray(s).astype(np.float64)+ blob("IMG_STAR", img_blob(a[..., 3] * a[..., :3].mean(axis=2) / 255))+ blob("CAMMAP", map_blob(NW.camera_map()))++ # into appvars+ os.makedirs(os.path.join(CE, "data"), exist_ok=True)+ for f in os.listdir(os.path.join(CE, "data")):+ if f.startswith(VAR_PREFIX) and f.endswith(".bin"):+ os.remove(os.path.join(CE, "data", f))+ vars_, at = [bytearray()], []+ for name, data in blobs:+ if len(vars_[-1]) + len(data) > VAR_ROOM:+ vars_.append(bytearray())+ at.append((len(vars_) - 1, len(vars_[-1])))+ vars_[-1] += data+ for i, v in enumerate(vars_):+ open(os.path.join(CE, "data", f"{VAR_PREFIX}{i}.bin"), "wb").write(v)+ h = ["/* Made by tools/pack.py: what is in the appvars FNAFD0, FNAFD1... */", "#ifndef FNAF_ASSETS_H",+ "#define FNAF_ASSETS_H", "#include <stdint.h>", "", f'#define DATA_VAR "{VAR_PREFIX}"',+ f"#define DATA_VARS {len(vars_)}", f"#define ASSET_COUNT {len(blobs)}", ""]+ names = [n for n, _ in blobs]+ h += [f"#define ASSET_TABLES {names.index('TABLES')}", f"#define MAP_FIRST {names.index('MAP_' + gnames[0].upper())}",+ f"#define PIC_FIRST {names.index('PIC_' + PICS[0].name)}", f"#define FONT_FIRST {names.index('FONT_HUD')}",+ f"#define ASSET_IMG_TITLE {names.index('IMG_TITLE')}", f"#define ASSET_IMG_STAR {names.index('IMG_STAR')}",+ f"#define ASSET_CAMMAP {names.index('CAMMAP')}", ""]+ h += [f"#define PIC_{p.name} {i}" for i, p in enumerate(PICS)]+ h += [f"#define PIC_COUNT {len(PICS)}"]+ h += [f"#define FONT_{n} {i}" for i, n in enumerate(["HUD", "BIG", "TEXT", "CLOCK", "PIXEL", "HUGE"])]+ h += [f"#define GRP_{n.upper()} {i}" for i, n in enumerate(gnames)]+ h += [f"#define GRP_COUNT {len(gnames)}"]+ h += [f"#define UI_{n} {224 + i}" for i, (n, _) in enumerate(UI)]+ h += [f"#define {n} {v}" for n, v in NW.DEFINES if n.startswith(("DOOR_", "PANEL_", "FAN_", "GOLD_", "MAP_"))]+ h += [f"#define {n} {v}" for n, v in DEFINES]+ h += ["/* each picture's group, and where it goes (pixels) */",+ "static const uint8_t pic_group[] = {" + ", ".join(str(gnames.index(p.group)) for p in PICS) + "};",+ "/* each asset: its appvar << 16 | its offset */",+ "static const uint32_t asset_at[] = {" + ", ".join(f"0x{v << 16 | o:X}" for v, o in at) + "};",+ "", "#endif", ""]+ open(os.path.join(CE, "src", "assets.h"), "w").write("\n".join(h))+ total = sum(len(v) for v in vars_)+ print(f"{len(vars_)} appvars, {total} bytes")+ sizes = {}+ for (name, data) in blobs:+ k = name.split("_")[0]+ if name.startswith("PIC_"):+ p = PICS[pic_ids[name[4:]]]+ k = "PIC " + p.group+ sizes[k] = sizes.get(k, 0) + len(data)+ for k, v in sorted(sizes.items(), key=lambda kv: -kv[1]):+ print(f" {k}: {v}")+++def remaps(g):+ """two 256-byte tables of the group's palette: each colour darkened to 45 %, and lightened a little (a+ fifth of the way to white): the nearest colour of the same phase (the fixed ones: among the fixed ones)"""+ from scipy.spatial import cKDTree+ pal = [tuple(c) for c in g.pal]+ cols = np.array([pal[i // g.phases] if i // g.phases < len(pal) else (0, 0, 0) for i in range(224)] + UI_RGB,+ dtype=np.float64)+ used = len(pal) * g.phases+ sets = [[j for j in range(used) if j % g.phases == p] for p in range(g.phases)] + [list(range(224, 256))]+ trees = [cKDTree(np.sqrt(cols[c] / 255)) for c in sets]+ out = b""+ for f in (lambda c: c * 0.45, lambda c: c + (255 - c) * 0.2):+ t = []+ for i in range(256):+ k = (i % g.phases) if i < 224 else g.phases+ _, j = trees[k].query(np.sqrt(np.clip(f(cols[i]), 0, 255) / 255))+ t.append(sets[k][j])+ out += bytes(t)+ return out+++if __name__ == "__main__":+ main()