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.

FNAF CE: pictures in 2 x 2 codewords, decoded in eZ80 code

Mason3633d186a589e7a
diff --git a/games/fnaf/ce/data/FNAFD0.bin b/games/fnaf/ce/data/FNAFD0.bin
index 1f70ab50..1317805b 100644
Binary files a/games/fnaf/ce/data/FNAFD0.bin and b/games/fnaf/ce/data/FNAFD0.bin differ
diff --git a/games/fnaf/ce/data/FNAFD1.bin b/games/fnaf/ce/data/FNAFD1.bin
index 2af96377..05d862f8 100644
Binary files a/games/fnaf/ce/data/FNAFD1.bin and b/games/fnaf/ce/data/FNAFD1.bin differ
diff --git a/games/fnaf/ce/data/FNAFD10.bin b/games/fnaf/ce/data/FNAFD10.bin
deleted file mode 100644
index 78215ed3..00000000
Binary files a/games/fnaf/ce/data/FNAFD10.bin and /dev/null differ
diff --git a/games/fnaf/ce/data/FNAFD2.bin b/games/fnaf/ce/data/FNAFD2.bin
index 8c86d09d..0a355498 100644
Binary files a/games/fnaf/ce/data/FNAFD2.bin and b/games/fnaf/ce/data/FNAFD2.bin differ
diff --git a/games/fnaf/ce/data/FNAFD3.bin b/games/fnaf/ce/data/FNAFD3.bin
index d5ce3795..6263e464 100644
Binary files a/games/fnaf/ce/data/FNAFD3.bin and b/games/fnaf/ce/data/FNAFD3.bin differ
diff --git a/games/fnaf/ce/data/FNAFD4.bin b/games/fnaf/ce/data/FNAFD4.bin
index 2692ed44..5b36048c 100644
Binary files a/games/fnaf/ce/data/FNAFD4.bin and b/games/fnaf/ce/data/FNAFD4.bin differ
diff --git a/games/fnaf/ce/data/FNAFD5.bin b/games/fnaf/ce/data/FNAFD5.bin
index 2039a344..fce57445 100644
Binary files a/games/fnaf/ce/data/FNAFD5.bin and b/games/fnaf/ce/data/FNAFD5.bin differ
diff --git a/games/fnaf/ce/data/FNAFD6.bin b/games/fnaf/ce/data/FNAFD6.bin
index caad8b0e..4631663b 100644
Binary files a/games/fnaf/ce/data/FNAFD6.bin and b/games/fnaf/ce/data/FNAFD6.bin differ
diff --git a/games/fnaf/ce/data/FNAFD7.bin b/games/fnaf/ce/data/FNAFD7.bin
index c4f82d0c..89ba86d9 100644
Binary files a/games/fnaf/ce/data/FNAFD7.bin and b/games/fnaf/ce/data/FNAFD7.bin differ
diff --git a/games/fnaf/ce/data/FNAFD8.bin b/games/fnaf/ce/data/FNAFD8.bin
index ffd283f9..9ad00cd8 100644
Binary files a/games/fnaf/ce/data/FNAFD8.bin and b/games/fnaf/ce/data/FNAFD8.bin differ
diff --git a/games/fnaf/ce/data/FNAFD9.bin b/games/fnaf/ce/data/FNAFD9.bin
index 4b710740..5d4f99ae 100644
Binary files a/games/fnaf/ce/data/FNAFD9.bin and b/games/fnaf/ce/data/FNAFD9.bin differ
diff --git a/games/fnaf/ce/engine/draw_ez80.s b/games/fnaf/ce/engine/draw_ez80.s
new file mode 100644
index 00000000..ec4a21e6
--- /dev/null
+++ b/games/fnaf/ce/engine/draw_ez80.s
@@ -0,0 +1,159 @@
+; Drawing's inner loops on the calculator (gfx.c has them in C for a computer).
+
+ .assume adl=1
+
+; void ce_double(const uint8_t *src, uint8_t *dst, int n): each of n bytes twice (n a multiple of 4)
+ .section .text._ce_double
+ .global _ce_double
+ .type _ce_double, @function
+_ce_double:
+ ld iy, 0
+ add iy, sp
+ ld hl, (iy + 3)
+ ld de, (iy + 6)
+ ld a, (iy + 9)
+ rrca
+ rrca
+ and a, 63
+ ret z
+ ld b, a
+1:
+ ld a, (hl)
+ inc hl
+ ld (de), a
+ inc de
+ ld (de), a
+ inc de
+ ld a, (hl)
+ inc hl
+ ld (de), a
+ inc de
+ ld (de), a
+ inc de
+ ld a, (hl)
+ inc hl
+ ld (de), a
+ inc de
+ ld (de), a
+ inc de
+ ld a, (hl)
+ inc hl
+ ld (de), a
+ inc de
+ ld (de), a
+ inc de
+ djnz 1b
+ ret
+
+; void ce_remap(uint8_t *p, int n, const uint8_t *lut): each of n bytes through the table (256-aligned)
+ .section .text._ce_remap
+ .global _ce_remap
+ .type _ce_remap, @function
+_ce_remap:
+ ld iy, 0
+ add iy, sp
+ ld hl, (iy + 3)
+ ld bc, (iy + 6)
+ ld de, (iy + 9)
+ ld a, b
+ or a, c
+ ret z
+1:
+ ld e, (hl)
+ ld a, (de)
+ ld (hl), a
+ inc hl
+ dec bc
+ ld a, b
+ or a, c
+ jr nz, 1b
+ ret
+
+; void ce_alpha(const uint8_t *rows, int stride, int h, uint8_t *dst, const uint8_t *ink): h rows of 2-bit alpha
+; (stride bytes each, 4 pixels a byte, the first in the top bits) onto the screen (320 a row) from dst, alpha 1 to 3
+; as ink[1] to ink[3], 0 left as it is
+ .section .text._ce_alpha
+ .global _ce_alpha
+ .type _ce_alpha, @function
+_ce_alpha:
+ push ix
+ ld iy, 0
+ add iy, sp
+ ld a, (iy + 9)
+ or a, a
+ jr z, al_done
+ ld (al_stride), a
+ ld a, (iy + 12)
+ or a, a
+ jr z, al_done
+ ld (al_h), a
+ ld ix, (iy + 18)
+ ld a, (ix + 1)
+ ld (al_ink1), a
+ ld a, (ix + 2)
+ ld (al_ink2), a
+ ld a, (ix + 3)
+ ld (al_ink3), a
+ ld hl, (iy + 6)
+ ld de, (iy + 15)
+al_row:
+ push de
+ ld a, (al_stride)
+ ld b, a
+al_byte:
+ ld a, (hl)
+ inc hl
+ or a, a
+ jr z, al_skip4
+ ld c, a
+ call al_px
+ call al_px
+ call al_px
+ call al_px
+ djnz al_byte
+ jr al_next
+al_skip4:
+ inc de
+ inc de
+ inc de
+ inc de
+ djnz al_byte
+al_next:
+ pop de
+ push hl
+ ld hl, 320
+ add hl, de
+ ex de, hl
+ pop hl
+ ld a, (al_h)
+ dec a
+ ld (al_h), a
+ jr nz, al_row
+al_done:
+ pop ix
+ ret
+; one pixel: C's top two bits (C shifted on), at DE (DE on)
+al_px:
+ sla c
+ jr c, 2f
+ sla c
+ jr nc, 1f
+ ld a, (al_ink1)
+ ld (de), a
+1: inc de
+ ret
+2: sla c
+ ld a, (al_ink3)
+ jr c, 3f
+ ld a, (al_ink2)
+3: ld (de), a
+ inc de
+ ret
+
+ .section .bss._ce_alpha
+ .local al_stride, al_h, al_ink1, al_ink2, al_ink3
+al_stride: .ds 1
+al_h: .ds 1
+al_ink1: .ds 1
+al_ink2: .ds 1
+al_ink3: .ds 1
diff --git a/games/fnaf/ce/engine/gfx.c b/games/fnaf/ce/engine/gfx.c
index 580aed30..3caf2ce9 100644
--- a/games/fnaf/ce/engine/gfx.c
+++ b/games/fnaf/ce/engine/gfx.c
@@ -3,12 +3,35 @@
#include <string.h>
void zx0_Decompress(void *dst, const void *src);
+void ce_double(const uint8_t *src, uint8_t *dst, int n); /* (draw_ez80.s, or below) */
+void ce_remap(uint8_t *p, int n, const uint8_t *lut);
+void ce_alpha(const uint8_t *rows, int stride, int h, uint8_t *dst, const uint8_t *ink);
+
+#ifndef CE_ASM
+void ce_double(const uint8_t *src, uint8_t *dst, int n) {
+ while (n--) dst[0] = dst[1] = *src++, dst += 2;
+}
+void ce_remap(uint8_t *p, int n, const uint8_t *lut) {
+ while (n--) *p = lut[*p], p++;
+}
+void ce_alpha(const uint8_t *rows, int stride, int h, uint8_t *dst, const uint8_t *ink) {
+ for (; h; h--, dst += SCR_W)
+ for (int n = 0; n < stride; n++) {
+ uint8_t b = *rows++;
+ for (int k = 0; k < 4; k++, b = (uint8_t)(b << 2))
+ if (b >> 6) dst[4 * n + k] = ink[b >> 6];
+ }
+}
+#endif
static Assets A;
+static uint8_t *temp;
+static size_t temp_len;
+int gfx_temp_uses;
-void gfx_init(const Assets *a, int tables) {
+void gfx_init(const Assets *a, uint8_t *t, size_t len) {
A = *a;
- pic_init(asset(tables));
+ temp = t, temp_len = len;
}
const uint8_t *asset(int id) {
@@ -17,11 +40,9 @@ const uint8_t *asset(int id) {
}
/* ------------------------------------------------------------------ maps: two places, the older one reused */
-static uint8_t maps[2][(MAP_BYTES + 3) & ~3] __attribute__((aligned(4)));
+static uint8_t maps[2][PIC_MAP_SIZE] __attribute__((aligned(1024)));
static int map_group[2] = {-1, -1}, map_age[2];
static int age;
-static PicMap picmap[2];
-static uint8_t phase_bytes[256];
static int slot_of(int group) {
for (int s = 0; s < 2; s++)
@@ -33,21 +54,12 @@ static int slot_of(int group) {
zx0_Decompress(maps[s], asset(A.map_first + group));
map_group[s] = group;
map_age[s] = ++age;
- const uint8_t *m = maps[s] + 512;
- /* a group with phases has its colours four times over: the static's phase goes in the low two bits */
- bool phases = maps[s][MAP_BYTES - 1] == 4;
- if (!phase_bytes[0] && !phase_bytes[1]) { /* (once: random bytes) */
- uint32_t r = 0x9E3779B9u;
- for (int i = 0; i < 256; i++) r ^= r << 13, r ^= r >> 17, r ^= r << 5, phase_bytes[i] = (uint8_t)(r >> 11);
- }
- picmap[s] = (PicMap){m, m + (YQ_HI - YQ_LO), m + (YQ_HI - YQ_LO) + (CQ_HI - CQ_LO),
- m + (YQ_HI - YQ_LO) + 2 * (CQ_HI - CQ_LO), phases ? phase_bytes : NULL};
return s;
}
const uint8_t *map_of(int group) { return maps[slot_of(group)]; }
-const uint16_t *map_palette(int group) { return (const uint16_t *)(const void *)maps[slot_of(group)]; }
-const uint8_t *map_remap(int group, int which) { return maps[slot_of(group)] + MAP_BYTES - 513 + 256 * which; }
+const uint16_t *map_palette(int group) { return (const uint16_t *)(const void *)(maps[slot_of(group)] + MAP_PALETTE); }
+const uint8_t *map_remap(int group, int which) { return maps[slot_of(group)] + MAP_REMAP + 256 * which; }
/* ------------------------------------------------------------------ pictures */
int pic_group_of(int pic) { return A.pic_group[pic]; }
@@ -55,8 +67,10 @@ int pic_w(int pic) { return pic_width(asset(A.pic_first + pic)); }
int pic_h(int pic) { return pic_height(asset(A.pic_first + pic)); }
void pic_into(int pic, uint8_t *dst, int stride) {
- int s = slot_of(A.pic_group[pic]);
- pic_decode(asset(A.pic_first + pic), dst, stride, &picmap[s]);
+ const uint8_t *p = asset(A.pic_first + pic);
+ bool in_place = !pic_keeps(p) && stride == pic_width(p);
+ if (!in_place) gfx_temp_uses++;
+ pic_decode(p, dst, stride, maps[slot_of(A.pic_group[pic])], in_place ? NULL : temp);
}
void pic_full(int pic, uint8_t *dst, int stride) {
@@ -90,8 +104,7 @@ void d_frame(int x, int y, int w, int h, uint8_t c) {
void d_remap(int x, int y, int w, int h, const uint8_t *lut) {
int sx = 0, sy = 0;
if (!clip(&x, &y, &w, &h, &sx, &sy)) return;
- for (uint8_t *row = scr + y * SCR_W + x; h--; row += SCR_W)
- for (uint8_t *p = row, *e = row + w; p < e; p++) *p = lut[*p];
+ for (uint8_t *row = scr + y * SCR_W + x; h--; row += SCR_W) ce_remap(row, w, lut);
}
void d_blit(const uint8_t *src, int stride, int sx, int sy, int w, int h, int x, int y, bool dbl) {
@@ -124,46 +137,60 @@ void d_blit_key(const uint8_t *src, int stride, int w, int h, int x, int y, uint
}
void d_blit2(const uint8_t *src, int stride, int dx, uint8_t fill) {
- int x0 = dx > 0 ? dx : 0, x1 = dx < 0 ? SCR_W + dx : SCR_W;
+ static uint8_t row[SCR_W];
for (int r = 0; r < SCR_H / 2; r++) {
uint8_t *d = scr + 2 * r * SCR_W;
const uint8_t *s = src + r * stride;
- if (dx > 0) memset(d, fill, (size_t)dx);
- if (dx < 0) memset(d + x1, fill, (size_t)-dx);
- uint8_t *o = d + x0;
- const uint8_t *i = s + ((x0 - dx) >> 1);
- int n = x1 - x0;
- if ((x0 - dx) & 1) *o++ = *i++, n--;
- for (; n >= 2; n -= 2, i++) o[0] = o[1] = *i, o += 2;
- if (n) *o = *i;
+ if (!dx) ce_double(s, d, SCR_W / 2);
+ else { /* (shaken: dx to the side) */
+ ce_double(s, row, SCR_W / 2);
+ if (dx > 0) memset(d, fill, (size_t)dx), memcpy(d + dx, row, (size_t)(SCR_W - dx));
+ else memcpy(d, row - dx, (size_t)(SCR_W + dx)), memset(d + SCR_W + dx, fill, (size_t)-dx);
+ }
memcpy(d + SCR_W, d, SCR_W);
}
}
void d_noise(int x, int y, int w, int h, uint32_t seed, const uint8_t *greys) {
+ static uint8_t strip[2 * SCR_W];
+ static uint8_t rnd[256];
+ static const uint8_t *made;
int sx = 0, sy = 0;
if (!clip(&x, &y, &w, &h, &sx, &sy)) return;
- uint32_t r = seed | 1;
- for (uint8_t *row = scr + y * SCR_W + x; h--; row += SCR_W) {
- uint8_t *p = row, *e = row + w;
- while (p < e) {
- r ^= r << 13, r ^= r >> 17, r ^= r << 5;
- uint32_t b = r;
- for (int k = 0; k < 8 && p < e; k++, b >>= 3) *p++ = greys[b & 7];
- }
+ if (!rnd[0] && !rnd[1]) { /* (once: random bytes) */
+ uint32_t r = 0x2545F491u;
+ for (int i = 0; i < 256; i++) r ^= r << 13, r ^= r >> 17, r ^= r << 5, rnd[i] = (uint8_t)(r >> 13);
}
+ if (made != greys) {
+ for (int i = 0; i < 2 * SCR_W; i++) strip[i] = greys[rnd[(uint8_t)(i * 7 + (i >> 8))] & 7];
+ made = greys;
+ }
+ uint8_t k = (uint8_t)seed, step = (uint8_t)(seed >> 8) | 1;
+ for (uint8_t *row = scr + y * SCR_W + x; h--; row += SCR_W, k += step) memcpy(row, strip + rnd[k], (size_t)w);
+}
+
+void d_snow(int n, uint32_t seed, const uint8_t *greys) {
+ static unsigned at[1024]; /* (random places on the screen, made once) */
+ if (!at[0] && !at[1]) {
+ uint32_t r = 0x6F4A7C15u;
+ for (int i = 0; i < 1024; i++) r ^= r << 13, r ^= r >> 17, r ^= r << 5, at[i] = (unsigned)(r % (SCR_W * SCR_H));
+ }
+ unsigned k = (unsigned)seed & 1023, step = ((unsigned)(seed >> 10) & 510) | 1;
+ uint8_t c = (uint8_t)(seed >> 20);
+ while (n--) scr[at[k]] = greys[c++ & 7], k = (k + step) & 1023;
}
/* ------------------------------------------------------------------ text */
static const uint8_t *font_at(int font) { return asset(A.font_first + font); }
int d_line_h(int font) { return font_at(font)[0]; }
-static void glyph(const uint8_t *f, const uint8_t *gl, int x, int y, Ink ink) {
- int w = gl[1], h = gl[2];
- if (!w) return;
- const uint8_t *rows = f + (gl[6] | gl[7] << 8);
+/* 2-bit alpha rows (4 pixels a byte, the first in the top bits) at (x, y) in an ink; clipped */
+static void alpha(const uint8_t *rows, int w, int h, int x, int y, Ink ink) {
int stride = (w + 3) >> 2;
- x += (int8_t)gl[3], y += (int8_t)gl[4];
+ if (x >= 0 && y >= 0 && x + 4 * stride <= SCR_W && y + h <= SCR_H) { /* (all of it on the screen: quick) */
+ ce_alpha(rows, stride, h, scr + y * SCR_W + x, ink);
+ return;
+ }
for (int r = 0; r < h; r++, rows += stride) {
int yy = y + r;
if (yy < 0 || yy >= SCR_H) continue;
@@ -175,6 +202,10 @@ static void glyph(const uint8_t *f, const uint8_t *gl, int x, int y, Ink ink) {
}
}
+static void glyph(const uint8_t *f, const uint8_t *gl, int x, int y, Ink ink) {
+ if (gl[1]) alpha(f + (gl[6] | gl[7] << 8), gl[1], gl[2], x + (int8_t)gl[3], y + (int8_t)gl[4], ink);
+}
+
int d_text_n(int font, int x, int y, const char *s, int n, Ink ink) {
const uint8_t *f = font_at(font);
int x0 = x;
@@ -205,64 +236,66 @@ void d_text_c(int font, int cx, int y, const char *s, Ink ink) { d_text(font, cx
void d_text_r(int font, int rx, int y, const char *s, Ink ink) { d_text(font, rx - d_text_w(font, s), y, s, ink); }
void d_img(const uint8_t *img, int x, int y, Ink ink) {
- int w = img[0] | img[1] << 8, h = img[2] | img[3] << 8, stride = (w + 3) >> 2;
- const uint8_t *rows = img + 4;
- for (int r = 0; r < h; r++, rows += stride) {
- int yy = y + r;
- if (yy < 0 || yy >= SCR_H) continue;
- uint8_t *d = scr + yy * SCR_W;
- for (int c = 0; c < w; c++) {
- int a = rows[c >> 2] >> (6 - 2 * (c & 3)) & 3, xx = x + c;
- if (a && xx >= 0 && xx < SCR_W) d[xx] = ink[a];
- }
- }
+ alpha(img + 4, img[0] | img[1] << 8, img[2] | img[3] << 8, x, y, ink);
}
/* ------------------------------------------------------------------ the palette */
-static uint16_t mix(uint16_t c, int r2, int g2, int b2, int a) { /* c toward (r2, g2, b2) by a / 32 */
- int r = c >> 10 & 31, g = (c >> 5 & 31) << 1 | c >> 15, b = c & 31;
- r += (r2 - r) * a / 32, g += (g2 - g) * a / 32, b += (b2 - b) * a / 32;
- return (uint16_t)((g & 1) << 15 | r << 10 | (g >> 1) << 5 | b);
-}
+/* the group shown: its colours' channels (red and blue 0..31, green 0..63); the channels as they come out, already
+ * in their place in a palette word */
+static uint8_t chan_r[PICS_COLORS], chan_g[PICS_COLORS], chan_b[PICS_COLORS];
+static int chan_group = -1;
+static uint16_t out_r[32], out_g[64], out_b[32];
-static uint16_t scale(uint16_t c, int k) { /* each channel times k / 32 */
- int r = (c >> 10 & 31) * k / 32, g = ((c >> 5 & 31) << 1 | c >> 15) * k / 32, b = (c & 31) * k / 32;
- r = r > 31 ? 31 : r, g = g > 63 ? 63 : g, b = b > 31 ? 31 : b;
- return (uint16_t)((g & 1) << 15 | r << 10 | (g >> 1) << 5 | b);
+/* a channel v (0..max) toward max by white / 32, then times dim / 32 */
+static int chan(int v, int max, int white, int dim) {
+ v = (v * (32 - white) + max * white) >> 5;
+ v = (v * dim) >> 5;
+ return v > max ? max : v;
}
static struct {
int group, dim, white;
} last = {-2, 0, 0};
-void pal_set(int group, int dim, const uint8_t *phase, int white) {
- if (!phase && group == last.group && dim == last.dim && white == last.white) return;
+void pal_set(int group, int dim, int white) {
+ if (group == last.group && dim == last.dim && white == last.white) return;
last.group = group, last.dim = dim, last.white = white;
- if (phase) last.group = -2;
if (group < 0) {
memset(ce_pal, 0, 2 * PICS_COLORS);
if (map_group[0] < 0 && map_group[1] < 0) slot_of(0);
- memcpy(ce_pal + PICS_COLORS, maps[map_group[0] >= 0 ? 0 : 1] + 2 * PICS_COLORS, 2 * (256 - PICS_COLORS));
+ memcpy(ce_pal + PICS_COLORS, maps[map_group[0] >= 0 ? 0 : 1] + MAP_PALETTE + 2 * PICS_COLORS, 2 * (256 - PICS_COLORS));
ce_pal_dirty = true;
return;
}
const uint16_t *p = map_palette(group);
- for (int i = 0; i < PICS_COLORS; i++) {
- uint16_t c = p[i];
- if (phase && phase[i & 3]) { /* the static: each phase toward its grey */
- int k = phase[4 + (i & 3)];
- c = mix(c, k, 2 * k, k, phase[i & 3]);
+ if (chan_group != group) {
+ for (int i = 0; i < PICS_COLORS; i++) {
+ uint16_t c = p[i];
+ chan_r[i] = (uint8_t)(c >> 10 & 31), chan_g[i] = (uint8_t)((c >> 5 & 31) << 1 | c >> 15);
+ chan_b[i] = (uint8_t)(c & 31);
}
- if (white) c = mix(c, 31, 63, 31, white);
- if (dim != 32) c = scale(c, dim);
- ce_pal[i] = c;
+ chan_group = group;
}
+ for (int v = 0; v < 32; v++) {
+ int c = chan(v, 31, white, dim);
+ out_r[v] = (uint16_t)(c << 10), out_b[v] = (uint16_t)c;
+ }
+ for (int v = 0; v < 64; v++) {
+ int g = chan(v, 63, white, dim);
+ out_g[v] = (uint16_t)((g & 1) << 15 | (g >> 1) << 5);
+ }
+ for (int i = 0; i < PICS_COLORS; i++) ce_pal[i] = out_r[chan_r[i]] | out_g[chan_g[i]] | out_b[chan_b[i]];
memcpy(ce_pal + PICS_COLORS, p + PICS_COLORS, 2 * (256 - PICS_COLORS));
ce_pal_dirty = true;
}
void pal_ui(int dim) {
- for (int i = PICS_COLORS; i < 256; i++) ce_pal[i] = scale(ce_pal[i], dim);
+ for (int i = PICS_COLORS; i < 256; i++) {
+ uint16_t c = ce_pal[i];
+ int r = chan(c >> 10 & 31, 31, 0, dim), g = chan((c >> 5 & 31) << 1 | c >> 15, 63, 0, dim);
+ int b = chan(c & 31, 31, 0, dim);
+ ce_pal[i] = (uint16_t)((g & 1) << 15 | r << 10 | (g >> 1) << 5 | b);
+ }
last.group = -2;
ce_pal_dirty = true;
}
diff --git a/games/fnaf/ce/engine/gfx.h b/games/fnaf/ce/engine/gfx.h
index cee70749..2c1c271d 100644
--- a/games/fnaf/ce/engine/gfx.h
+++ b/games/fnaf/ce/engine/gfx.h
@@ -3,12 +3,12 @@
#ifndef CE_GFX_H
#define CE_GFX_H
#include <stdbool.h>
+#include <stddef.h>
#include <stdint.h>
#include "ce.h"
#include "pic.h"
#define PICS_COLORS 224 /* a palette: the group's colours, then 32 fixed ones (the games' UI_*) */
-#define MAP_BYTES (512 + (YQ_HI - YQ_LO) + 2 * (CQ_HI - CQ_LO) + 2048 + 512 + 1) /* (the last: 4 with phases) */
/* the data: the appvars, where each asset is (appvar << 16 | offset), each picture's group, where the kinds
* of assets start */
@@ -18,7 +18,9 @@ typedef struct {
const uint8_t *pic_group;
int pic_first, map_first, font_first;
} Assets;
-void gfx_init(const Assets *a, int tables);
+/* temp: room for a picture's grid when it can't be unpacked where it goes (gfx_temp_uses counts those times) */
+void gfx_init(const Assets *a, uint8_t *temp, size_t temp_len);
+extern int gfx_temp_uses;
const uint8_t *asset(int id);
/* a group's map (decoded once into one of two places): its palette (256 words), and the rest */
@@ -45,6 +47,8 @@ void d_blit_key(const uint8_t *src, int stride, int w, int h, int x, int y, uint
void d_blit2(const uint8_t *src, int stride, int dx, uint8_t fill);
/* static: random greys of the fixed colours (UI) over the rectangle */
void d_noise(int x, int y, int w, int h, uint32_t seed, const uint8_t *greys);
+/* snow: n random pixels of the screen in random greys */
+void d_snow(int n, uint32_t seed, const uint8_t *greys);
/* text: the fonts' glyphs (2-bit alpha) in an ink: the palette indices of alpha 1, 2, 3 (ink[1..3]) */
typedef const uint8_t *Ink;
@@ -59,10 +63,8 @@ void d_text_r(int font, int rx, int y, const char *s, Ink ink);
void d_img(const uint8_t *img, int x, int y, Ink ink);
/* the palette shown (ce_pal) from a group's (-1: none, its colours black): dim (0 black .. 32 as it is .. 64
- * twice as bright), the 4 phases' static (phase[0..3]: 0 .. 32 of the way to the grey phase[4..7], 0 .. 31; NULL:
- * none), white (0 .. 32 of the way
- * to white); the fixed colours as they are */
-void pal_set(int group, int dim, const uint8_t *phase, int white);
+ * twice as bright), white (0 .. 32 of the way to white); the fixed colours as they are */
+void pal_set(int group, int dim, int white);
/* the fixed colours dimmed too (0 .. 32), until the next pal_set */
void pal_ui(int dim);
#endif
diff --git a/games/fnaf/ce/engine/pic.c b/games/fnaf/ce/engine/pic.c
index 62e2d9df..76c83874 100644
--- a/games/fnaf/ce/engine/pic.c
+++ b/games/fnaf/ce/engine/pic.c
@@ -1,166 +1,31 @@
-/* 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). */
+/* Decoding the pictures (pic.h). The grid's blocks into pixels: pic_expand, in C here, in assembly on the
+ * calculator (pic_ez80.s, CE_ASM). */
#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;
+void zx0_Decompress(void *dst, const void *src);
-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; }
+static int bw_of(const uint8_t *pic) { return pic[1] | pic[2] << 8; }
+int pic_width(const uint8_t *pic) { return 2 * bw_of(pic); }
+int pic_height(const uint8_t *pic) { return 2 * pic[3]; }
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;
- }
+bool pic_keeps(const uint8_t *pic) { return (pic[0] & 2) != 0; }
+
+void pic_decode(const uint8_t *pic, uint8_t *dst, int stride, const uint8_t *map, uint8_t *temp) {
+ int bw = bw_of(pic), bh = pic[3];
+ uint8_t *grid = temp ? temp : dst + 2 * bh * stride - bw * bh; /* (in place: the blocks' bytes at its end) */
+ zx0_Decompress(grid, pic + (pic[0] & 1 ? 6 : 4));
+ pic_expand(grid, dst, stride, bw, bh, map);
+}
+
+#ifndef CE_ASM
+void pic_expand(const uint8_t *grid, uint8_t *dst, int stride, int bw, int bh, const uint8_t *map) {
+ for (int by = 0; by < bh; by++) {
+ uint8_t *r0 = dst + 2 * by * stride, *r1 = r0 + stride;
+ for (int bx = 0; bx < bw; bx++, r0 += 2, r1 += 2) {
+ uint8_t k = *grid++;
+ if (k == 255) continue;
+ r0[0] = map[k], r0[1] = map[256 + k], r1[0] = map[512 + k], r1[1] = map[768 + k];
}
- if (skips) at += golomb();
}
}
+#endif
diff --git a/games/fnaf/ce/engine/pic.h b/games/fnaf/ce/engine/pic.h
index cbe85167..63753cd4 100644
--- a/games/fnaf/ce/engine/pic.h
+++ b/games/fnaf/ce/engine/pic.h
@@ -1,32 +1,24 @@
-/* The pictures (tools/cpic.py codes them): decoded into palette indices, a macroblock of 8 x 8 at a time.
+/* The pictures (tools/cvq.py codes them): grids of 2 x 2 blocks, each one of its group's codewords (four palette
+ * indices), the grid's bytes in zx0. A block of 255 keeps what dst holds (a picture coded over its base).
*
- * 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. */
+ * A group's map (MAP_*, unpacked once): the codewords (four pages: top left, top right, bottom left, bottom right)
+ * at 0, the palette at MAP_PALETTE, two remap tables at MAP_REMAP. */
#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
+#define MAP_PALETTE 1024
+#define MAP_REMAP 1536
+#define PIC_MAP_SIZE 2048 /* (unpacked: 1024-aligned, the codewords in one 64 KB bank) */
-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);
+int pic_base(const uint8_t *pic); /* the picture it is coded over, or -1 */
+bool pic_keeps(const uint8_t *pic); /* some blocks keep what dst holds */
+/* decodes the picture into dst (stride bytes a row) with its group's map. Its grid is unpacked into temp (its
+ * blocks' count of bytes); temp NULL: into the end of dst itself (a picture that keeps nothing, as wide as dst) */
+void pic_decode(const uint8_t *pic, uint8_t *dst, int stride, const uint8_t *map, uint8_t *temp);
+/* (the grid's blocks into pixels: pic_ez80.s on the calculator) */
+void pic_expand(const uint8_t *grid, uint8_t *dst, int stride, int bw, int bh, const uint8_t *map);
#endif
diff --git a/games/fnaf/ce/engine/pic_ez80.s b/games/fnaf/ce/engine/pic_ez80.s
new file mode 100644
index 00000000..3cda30f4
--- /dev/null
+++ b/games/fnaf/ce/engine/pic_ez80.s
@@ -0,0 +1,88 @@
+; The grid's blocks into pixels on the calculator: pic.c's pic_expand in eZ80 assembly (pic.h).
+;
+; void pic_expand(const uint8_t *grid, uint8_t *dst, int stride, int bw, int bh, const uint8_t *map)
+;
+; Each byte of the grid a block of 2 x 2: its codeword's four bytes from the map's four pages (DE: D the page, E the
+; codeword), into the block's two rows (IY, IX); 255 leaves the block as it is.
+
+ .assume adl=1
+
+ .section .bss._pic_ez80
+ .local ex_stride2, ex_row, ex_bw, ex_bh
+ex_stride2: .ds 3
+ex_row: .ds 3
+ex_bw: .ds 3
+ex_bh: .ds 1
+
+ .section .text._pic_expand
+ .global _pic_expand
+ .type _pic_expand, @function
+_pic_expand:
+ push ix
+ ld iy, 0
+ add iy, sp
+ ld hl, (iy + 15) ; bw
+ ld (ex_bw), hl
+ ld a, (iy + 18) ; bh
+ or a, a
+ jr z, ex_done
+ ld (ex_bh), a
+ ld hl, (iy + 9) ; dst: the first row of blocks
+ ld (ex_row), hl
+ ld bc, (iy + 12) ; stride
+ ld de, (iy + 21) ; the map: its first page
+ ld hl, (iy + 6) ; the grid
+ push hl
+ ld hl, (iy + 12)
+ add hl, hl
+ ld (ex_stride2), hl
+ pop hl
+ex_rows:
+ ld iy, (ex_row)
+ lea ix, iy + 0
+ add ix, bc ; (the second row: a stride further)
+ push bc
+ ld bc, (ex_bw)
+ex_block:
+ ld a, (hl)
+ inc hl
+ cp a, 255
+ jr z, ex_keep
+ ld e, a
+ ld a, (de)
+ ld (iy + 0), a
+ inc d
+ ld a, (de)
+ ld (iy + 1), a
+ inc d
+ ld a, (de)
+ ld (ix + 0), a
+ inc d
+ ld a, (de)
+ ld (ix + 1), a
+ dec d
+ dec d
+ dec d
+ex_keep:
+ lea iy, iy + 2
+ lea ix, ix + 2
+ dec bc
+ ld a, b
+ or a, c
+ jr nz, ex_block
+ pop bc
+ push hl
+ ld hl, (ex_row)
+ push de
+ ld de, (ex_stride2)
+ add hl, de
+ pop de
+ ld (ex_row), hl
+ pop hl
+ ld a, (ex_bh)
+ dec a
+ ld (ex_bh), a
+ jr nz, ex_rows
+ex_done:
+ pop ix
+ ret
diff --git a/games/fnaf/ce/makefile b/games/fnaf/ce/makefile
index 4d83ef70..e8599671 100644
--- a/games/fnaf/ce/makefile
+++ b/games/fnaf/ce/makefile
@@ -6,9 +6,10 @@ ICON = icon.png
DESCRIPTION = "Five Nights at Freddy's"
COMPRESSED = YES
ARCHIVED = YES
-CFLAGS = -Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Oz
+CFLAGS = -Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Oz -DCE_ASM
SRCDIR = src
EXTRA_C_SOURCES = engine/pic.c engine/gfx.c engine/ce_calc.c
+EXTRA_ASM_SOURCES = engine/pic_ez80.s engine/draw_ez80.s
all: target appvars
include $(shell cedev-config --makefile)
diff --git a/games/fnaf/ce/src/assets.h b/games/fnaf/ce/src/assets.h
index cdf4721f..e067fdd6 100644
--- a/games/fnaf/ce/src/assets.h
+++ b/games/fnaf/ce/src/assets.h
@@ -1,20 +1,17 @@
/* Made by tools/pack.py: what is in the appvars FNAFD0, FNAFD1... */
-#ifndef FNAF_ASSETS_H
-#define FNAF_ASSETS_H
+#ifndef CE_ASSETS_H
+#define CE_ASSETS_H
#include <stdint.h>
#define DATA_VAR "FNAFD"
-#define DATA_VARS 11
-#define ASSET_COUNT 223
-
-#define ASSET_TABLES 0
-#define MAP_FIRST 1
-#define PIC_FIRST 25
-#define FONT_FIRST 214
-#define ASSET_IMG_TITLE 220
-#define ASSET_IMG_STAR 221
-#define ASSET_CAMMAP 222
-
+#define DATA_VARS 10
+#define ASSET_COUNT 222
+#define MAP_FIRST 0
+#define PIC_FIRST 27
+#define FONT_FIRST 213
+#define ASSET_IMG_TITLE 219
+#define ASSET_IMG_STAR 220
+#define ASSET_CAMMAP 221
#define PIC_OFFICE 0
#define PIC_LIGHT_L 1
#define PIC_LIGHT_L_WHO 2
@@ -22,189 +19,186 @@
#define PIC_LIGHT_R_WHO 4
#define PIC_DOOR_L 5
#define PIC_DOOR_R 6
-#define PIC_PANEL_L0 7
-#define PIC_PANEL_L1 8
-#define PIC_PANEL_L2 9
-#define PIC_PANEL_L3 10
-#define PIC_PANEL_R0 11
-#define PIC_PANEL_R1 12
-#define PIC_PANEL_R2 13
-#define PIC_PANEL_R3 14
-#define PIC_FAN0 15
-#define PIC_FAN1 16
-#define PIC_FAN2 17
-#define PIC_OFFICE_GOLD 18
-#define PIC_DARK 19
-#define PIC_DARK_FREDDY 20
-#define PIC_CAM1A_EMPTY 21
-#define PIC_CAM1A_F 22
-#define PIC_CAM1A_BF 23
-#define PIC_CAM1A_CF 24
-#define PIC_CAM1A_BCF 25
-#define PIC_CAM1B_EMPTY 26
-#define PIC_CAM1B_B 27
-#define PIC_CAM1B_C 28
-#define PIC_CAM1B_F 29
-#define PIC_CAM1B_BC 30
-#define PIC_CAM1B_BF 31
-#define PIC_CAM1B_CF 32
-#define PIC_CAM1B_BCF 33
-#define PIC_CAM2A_EMPTY 34
-#define PIC_CAM2A_B 35
-#define PIC_CAM2A_DARK 36
-#define PIC_FOXYRUN0 37
-#define PIC_FOXYRUN1 38
-#define PIC_FOXYRUN2 39
-#define PIC_FOXYRUN3 40
-#define PIC_FOXYRUN4 41
-#define PIC_FOXYRUN5 42
-#define PIC_FOXYRUN6 43
-#define PIC_FOXYRUN7 44
-#define PIC_FOXYRUN8 45
-#define PIC_FOXYRUN9 46
-#define PIC_FOXYRUN10 47
-#define PIC_FOXYRUN11 48
-#define PIC_FOXYRUN12 49
-#define PIC_FOXYRUN13 50
-#define PIC_FOXYRUN14 51
-#define PIC_FOXYRUN15 52
-#define PIC_FOXYRUN16 53
-#define PIC_FOXYRUN17 54
-#define PIC_CAM2B_EMPTY 55
-#define PIC_CAM2B_B 56
-#define PIC_CAM2B_GOLD 57
-#define PIC_CAM3_EMPTY 58
-#define PIC_CAM3_B 59
-#define PIC_CAM4A_EMPTY 60
-#define PIC_CAM4A_C 61
-#define PIC_CAM4A_F 62
-#define PIC_CAM4A_CF 63
-#define PIC_CAM4B_EMPTY 64
-#define PIC_CAM4B_C 65
-#define PIC_CAM4B_F 66
-#define PIC_CAM5_EMPTY 67
-#define PIC_CAM5_B 68
-#define PIC_CAM7_EMPTY 69
-#define PIC_CAM7_C 70
-#define PIC_CAM7_F 71
-#define PIC_CAM7_CF 72
-#define PIC_CAM1C_0 73
-#define PIC_CAM1C_1 74
-#define PIC_CAM1C_2 75
-#define PIC_CAM1C_3 76
-#define PIC_BONNIE0 77
-#define PIC_BONNIE1 78
-#define PIC_BONNIE2 79
-#define PIC_BONNIE3 80
-#define PIC_BONNIE4 81
-#define PIC_BONNIE5 82
-#define PIC_BONNIE6 83
-#define PIC_BONNIE7 84
-#define PIC_BONNIE8 85
-#define PIC_BONNIE9 86
-#define PIC_CHICA0 87
-#define PIC_CHICA1 88
-#define PIC_CHICA2 89
-#define PIC_CHICA3 90
-#define PIC_CHICA4 91
-#define PIC_CHICA5 92
-#define PIC_CHICA6 93
-#define PIC_CHICA7 94
-#define PIC_CHICA8 95
-#define PIC_CHICA9 96
-#define PIC_CHICA10 97
-#define PIC_CHICA11 98
-#define PIC_CHICA12 99
-#define PIC_CHICA13 100
-#define PIC_CHICA14 101
-#define PIC_FREDDY0 102
-#define PIC_FREDDY1 103
-#define PIC_FREDDY2 104
-#define PIC_FREDDY3 105
-#define PIC_FREDDY4 106
-#define PIC_FREDDY5 107
-#define PIC_FREDDY6 108
-#define PIC_FREDDY7 109
-#define PIC_FREDDY8 110
-#define PIC_FREDDY9 111
-#define PIC_FREDDY10 112
-#define PIC_FREDDY11 113
-#define PIC_FREDDY12 114
-#define PIC_FREDDY13 115
-#define PIC_FREDDY14 116
-#define PIC_FREDDY15 117
-#define PIC_FREDDY16 118
-#define PIC_FREDDY17 119
-#define PIC_FREDDY18 120
-#define PIC_FREDDY19 121
-#define PIC_FOXY0 122
-#define PIC_FOXY1 123
-#define PIC_FOXY2 124
-#define PIC_FOXY3 125
-#define PIC_FOXY4 126
-#define PIC_FOXY5 127
-#define PIC_FOXY6 128
-#define PIC_FOXY7 129
-#define PIC_FOXY8 130
-#define PIC_FOXY9 131
-#define PIC_FOXY10 132
-#define PIC_FOXY11 133
-#define PIC_FOXY12 134
-#define PIC_FOXY13 135
-#define PIC_FOXY14 136
-#define PIC_FOXY15 137
-#define PIC_FOXY16 138
-#define PIC_FOXY17 139
-#define PIC_FOXY18 140
-#define PIC_POWEROUT0 141
-#define PIC_POWEROUT1 142
-#define PIC_POWEROUT2 143
-#define PIC_POWEROUT3 144
-#define PIC_POWEROUT4 145
-#define PIC_POWEROUT5 146
-#define PIC_POWEROUT6 147
-#define PIC_POWEROUT7 148
-#define PIC_POWEROUT8 149
-#define PIC_POWEROUT9 150
-#define PIC_POWEROUT10 151
-#define PIC_POWEROUT11 152
-#define PIC_POWEROUT12 153
-#define PIC_POWEROUT13 154
-#define PIC_POWEROUT14 155
-#define PIC_POWEROUT15 156
-#define PIC_POWEROUT16 157
-#define PIC_POWEROUT17 158
-#define PIC_POWEROUT18 159
-#define PIC_POWEROUT19 160
-#define PIC_POWEROUT20 161
-#define PIC_FLIP0 162
-#define PIC_FLIP1 163
-#define PIC_FLIP2 164
-#define PIC_FLIP3 165
-#define PIC_FLIP4 166
-#define PIC_FLIP5 167
-#define PIC_FLIP6 168
-#define PIC_FLIP7 169
-#define PIC_FLIP8 170
-#define PIC_FLIP9 171
-#define PIC_FLIP10 172
-#define PIC_HALLUC_GOLDEN 173
-#define PIC_HALLUC_ENDO 174
-#define PIC_TITLE0 175
-#define PIC_TITLE1 176
-#define PIC_TITLE2 177
-#define PIC_TITLE3 178
-#define PIC_NEWSPAPER 179
-#define PIC_PAYCHECK 180
-#define PIC_OVERTIME 181
-#define PIC_PINKSLIP 182
-#define PIC_GAMEOVER 183
-#define PIC_GOLDEN 184
-#define PIC_FACE_FREDDY 185
-#define PIC_FACE_BONNIE 186
-#define PIC_FACE_CHICA 187
-#define PIC_FACE_FOXY 188
-#define PIC_COUNT 189
+#define PIC_PANEL_L1 7
+#define PIC_PANEL_L2 8
+#define PIC_PANEL_L3 9
+#define PIC_PANEL_R1 10
+#define PIC_PANEL_R2 11
+#define PIC_PANEL_R3 12
+#define PIC_FAN0 13
+#define PIC_FAN1 14
+#define PIC_FAN2 15
+#define PIC_OFFICE_GOLD 16
+#define PIC_DARK 17
+#define PIC_DARK_FREDDY 18
+#define PIC_CAM1A_EMPTY 19
+#define PIC_CAM1A_F 20
+#define PIC_CAM1A_BF 21
+#define PIC_CAM1A_CF 22
+#define PIC_CAM1A_BCF 23
+#define PIC_CAM1B_EMPTY 24
+#define PIC_CAM1B_B 25
+#define PIC_CAM1B_C 26
+#define PIC_CAM1B_F 27
+#define PIC_CAM1B_BC 28
+#define PIC_CAM1B_BF 29
+#define PIC_CAM1B_CF 30
+#define PIC_CAM1B_BCF 31
+#define PIC_CAM2A_EMPTY 32
+#define PIC_CAM2A_B 33
+#define PIC_FOXYRUN0 34
+#define PIC_FOXYRUN1 35
+#define PIC_FOXYRUN2 36
+#define PIC_FOXYRUN3 37
+#define PIC_FOXYRUN4 38
+#define PIC_FOXYRUN5 39
+#define PIC_FOXYRUN6 40
+#define PIC_FOXYRUN7 41
+#define PIC_FOXYRUN8 42
+#define PIC_FOXYRUN9 43
+#define PIC_FOXYRUN10 44
+#define PIC_FOXYRUN11 45
+#define PIC_FOXYRUN12 46
+#define PIC_FOXYRUN13 47
+#define PIC_FOXYRUN14 48
+#define PIC_FOXYRUN15 49
+#define PIC_FOXYRUN16 50
+#define PIC_FOXYRUN17 51
+#define PIC_CAM2B_EMPTY 52
+#define PIC_CAM2B_B 53
+#define PIC_CAM2B_GOLD 54
+#define PIC_CAM3_EMPTY 55
+#define PIC_CAM3_B 56
+#define PIC_CAM4A_EMPTY 57
+#define PIC_CAM4A_C 58
+#define PIC_CAM4A_F 59
+#define PIC_CAM4A_CF 60
+#define PIC_CAM4B_EMPTY 61
+#define PIC_CAM4B_C 62
+#define PIC_CAM4B_F 63
+#define PIC_CAM5_EMPTY 64
+#define PIC_CAM5_B 65
+#define PIC_CAM7_EMPTY 66
+#define PIC_CAM7_C 67
+#define PIC_CAM7_F 68
+#define PIC_CAM7_CF 69
+#define PIC_CAM1C_0 70
+#define PIC_CAM1C_1 71
+#define PIC_CAM1C_2 72
+#define PIC_CAM1C_3 73
+#define PIC_BONNIE0 74
+#define PIC_BONNIE1 75
+#define PIC_BONNIE2 76
+#define PIC_BONNIE3 77
+#define PIC_BONNIE4 78
+#define PIC_BONNIE5 79
+#define PIC_BONNIE6 80
+#define PIC_BONNIE7 81
+#define PIC_BONNIE8 82
+#define PIC_BONNIE9 83
+#define PIC_CHICA0 84
+#define PIC_CHICA1 85
+#define PIC_CHICA2 86
+#define PIC_CHICA3 87
+#define PIC_CHICA4 88
+#define PIC_CHICA5 89
+#define PIC_CHICA6 90
+#define PIC_CHICA7 91
+#define PIC_CHICA8 92
+#define PIC_CHICA9 93
+#define PIC_CHICA10 94
+#define PIC_CHICA11 95
+#define PIC_CHICA12 96
+#define PIC_CHICA13 97
+#define PIC_CHICA14 98
+#define PIC_FREDDY0 99
+#define PIC_FREDDY1 100
+#define PIC_FREDDY2 101
+#define PIC_FREDDY3 102
+#define PIC_FREDDY4 103
+#define PIC_FREDDY5 104
+#define PIC_FREDDY6 105
+#define PIC_FREDDY7 106
+#define PIC_FREDDY8 107
+#define PIC_FREDDY9 108
+#define PIC_FREDDY10 109
+#define PIC_FREDDY11 110
+#define PIC_FREDDY12 111
+#define PIC_FREDDY13 112
+#define PIC_FREDDY14 113
+#define PIC_FREDDY15 114
+#define PIC_FREDDY16 115
+#define PIC_FREDDY17 116
+#define PIC_FREDDY18 117
+#define PIC_FREDDY19 118
+#define PIC_FOXY0 119
+#define PIC_FOXY1 120
+#define PIC_FOXY2 121
+#define PIC_FOXY3 122
+#define PIC_FOXY4 123
+#define PIC_FOXY5 124
+#define PIC_FOXY6 125
+#define PIC_FOXY7 126
+#define PIC_FOXY8 127
+#define PIC_FOXY9 128
+#define PIC_FOXY10 129
+#define PIC_FOXY11 130
+#define PIC_FOXY12 131
+#define PIC_FOXY13 132
+#define PIC_FOXY14 133
+#define PIC_FOXY15 134
+#define PIC_FOXY16 135
+#define PIC_FOXY17 136
+#define PIC_FOXY18 137
+#define PIC_POWEROUT0 138
+#define PIC_POWEROUT1 139
+#define PIC_POWEROUT2 140
+#define PIC_POWEROUT3 141
+#define PIC_POWEROUT4 142
+#define PIC_POWEROUT5 143
+#define PIC_POWEROUT6 144
+#define PIC_POWEROUT7 145
+#define PIC_POWEROUT8 146
+#define PIC_POWEROUT9 147
+#define PIC_POWEROUT10 148
+#define PIC_POWEROUT11 149
+#define PIC_POWEROUT12 150
+#define PIC_POWEROUT13 151
+#define PIC_POWEROUT14 152
+#define PIC_POWEROUT15 153
+#define PIC_POWEROUT16 154
+#define PIC_POWEROUT17 155
+#define PIC_POWEROUT18 156
+#define PIC_POWEROUT19 157
+#define PIC_POWEROUT20 158
+#define PIC_FLIP0 159
+#define PIC_FLIP1 160
+#define PIC_FLIP2 161
+#define PIC_FLIP3 162
+#define PIC_FLIP4 163
+#define PIC_FLIP5 164
+#define PIC_FLIP6 165
+#define PIC_FLIP7 166
+#define PIC_FLIP8 167
+#define PIC_FLIP9 168
+#define PIC_FLIP10 169
+#define PIC_HALLUC_GOLDEN 170
+#define PIC_HALLUC_ENDO 171
+#define PIC_TITLE0 172
+#define PIC_TITLE1 173
+#define PIC_TITLE2 174
+#define PIC_TITLE3 175
+#define PIC_GAMEOVER 176
+#define PIC_GOLDEN 177
+#define PIC_NEWSPAPER 178
+#define PIC_PAYCHECK 179
+#define PIC_OVERTIME 180
+#define PIC_PINKSLIP 181
+#define PIC_FACE_FREDDY 182
+#define PIC_FACE_BONNIE 183
+#define PIC_FACE_CHICA 184
+#define PIC_FACE_FOXY 185
+#define PIC_COUNT 186
#define FONT_HUD 0
#define FONT_BIG 1
#define FONT_TEXT 2
@@ -212,30 +206,33 @@
#define FONT_PIXEL 4
#define FONT_HUGE 5
#define GRP_OFFICE 0
-#define GRP_CAM1A 1
-#define GRP_CAM1B 2
-#define GRP_CAM2A 3
-#define GRP_CAM2B 4
-#define GRP_CAM3 5
-#define GRP_CAM4A 6
-#define GRP_CAM4B 7
-#define GRP_CAM5 8
-#define GRP_CAM7 9
-#define GRP_CAM1C 10
-#define GRP_BONNIE 11
-#define GRP_CHICA 12
-#define GRP_FREDDY 13
-#define GRP_FOXY 14
-#define GRP_POWEROUT 15
-#define GRP_FLIP 16
-#define GRP_HALLUC 17
-#define GRP_TITLE 18
-#define GRP_NEWS 19
-#define GRP_PAPER 20
-#define GRP_GAMEOVER 21
-#define GRP_GOLDEN 22
-#define GRP_FACES 23
-#define GRP_COUNT 24
+#define GRP_DARK 1
+#define GRP_CAM1A 2
+#define GRP_CAM1B 3
+#define GRP_CAM2A 4
+#define GRP_CAM2B 5
+#define GRP_CAM3 6
+#define GRP_CAM4A 7
+#define GRP_CAM4B 8
+#define GRP_CAM5 9
+#define GRP_CAM7 10
+#define GRP_CAM1C 11
+#define GRP_BONNIE 12
+#define GRP_CHICA 13
+#define GRP_FREDDY 14
+#define GRP_FOXY 15
+#define GRP_POWEROUT 16
+#define GRP_FLIP 17
+#define GRP_HALLUC 18
+#define GRP_TITLE 19
+#define GRP_GAMEOVER 20
+#define GRP_GOLDEN 21
+#define GRP_NEWSPAPER 22
+#define GRP_PAYCHECK 23
+#define GRP_OVERTIME 24
+#define GRP_PINKSLIP 25
+#define GRP_FACES 26
+#define GRP_COUNT 27
#define UI_BLACK 224
#define UI_WHITE 225
#define UI_WHITE2 226
@@ -268,23 +265,7 @@
#define UI_EDGE 253
#define UI_MAP_OFF 254
#define UI_SPARE 255
-#define DOOR_L_X 27
-#define DOOR_L_W 70
-#define DOOR_L_H 239
-#define DOOR_R_X 434
-#define DOOR_R_W 60
-#define DOOR_R_H 239
-#define PANEL_L_X 0
-#define PANEL_R_X 496
-#define PANEL_Y 96
-#define FAN_X 256
-#define FAN_Y 96
-#define GOLD_X 176
-#define GOLD_Y 128
-#define GOLD_W 176
-#define GOLD_H 112
-#define MAP_SIZE 133
-#define OFFICE_W 533
+#define OFFICE_W 534
#define LIGHT_L_X 32
#define LIGHT_L_Y 16
#define LIGHT_L_W 56
@@ -316,9 +297,25 @@
#define TITLE3_Y 0
#define TITLE3_W 192
#define TITLE3_H 120
-/* each picture's group, and where it goes (pixels) */
-static const uint8_t pic_group[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 18, 18, 18, 18, 19, 20, 20, 20, 21, 22, 23, 23, 23, 23};
+#define DOOR_L_X 27
+#define DOOR_L_W 70
+#define DOOR_L_H 239
+#define DOOR_R_X 434
+#define DOOR_R_W 60
+#define DOOR_R_H 239
+#define PANEL_L_X 0
+#define PANEL_R_X 496
+#define PANEL_Y 96
+#define FAN_X 256
+#define FAN_Y 96
+#define GOLD_X 176
+#define GOLD_Y 128
+#define GOLD_W 176
+#define GOLD_H 112
+#define MAP_SIZE 133
+/* each picture's group */
+static const uint8_t pic_group[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 19, 19, 19, 19, 20, 21, 22, 23, 24, 25, 26, 26, 26, 26};
/* each asset: its appvar << 16 | its offset */
-static const uint32_t asset_at[] = {0x0, 0x1E5, 0xAEF, 0xF17, 0x12CE, 0x1634, 0x1A35, 0x1E0C, 0x21E9, 0x2613, 0x2945, 0x2CD7, 0x30A8, 0x38FE, 0x41C7, 0x4942, 0x5174, 0x5A37, 0x606B, 0x6946, 0x6D53, 0x75C6, 0x7E70, 0x8187, 0x86EB, 0x9048, 0xB99D, 0xBEE2, 0xC2D6, 0xCB69, 0xCF16, 0xD6B9, 0xDE20, 0xDFB4, 0xE169, 0xE326, 0xE502, 0xE6C0, 0xE89D, 0xEA7E, 0xEC75, 0xEE5F, 0xF04C, 0x10000, 0x10DDD, 0x125F8, 0x12732, 0x13801, 0x14BCD, 0x1669E, 0x1782E, 0x1A12F, 0x1BD26, 0x1C27F, 0x1C776, 0x1C7B9, 0x1D2D9, 0x1E258, 0x20000, 0x210A8, 0x23241, 0x23F5E, 0x250F8, 0x25C69, 0x25F27, 0x2614D, 0x263F0, 0x266BB, 0x26B0D, 0x26F66, 0x2743D, 0x2797D, 0x28064, 0x287DF, 0x290C6, 0x29BBF, 0x2A6F7, 0x2B17E, 0x2BD75, 0x2C8B7, 0x2D3DB, 0x30000, 0x31496, 0x31825, 0x331D7, 0x339FC, 0x355D4, 0x376B3, 0x38ED4, 0x3AF7A, 0x3CE4C, 0x3E708, 0x40000, 0x41C7A, 0x43196, 0x4551B, 0x46509, 0x477D8, 0x49111, 0x4B060, 0x4C119, 0x4D5F3, 0x4E9B2, 0x4F354, 0x50000, 0x509CB, 0x51397, 0x51CEA, 0x524EA, 0x52D13, 0x534C3, 0x53D20, 0x5464D, 0x55397, 0x5610E, 0x56E66, 0x57B26, 0x587E4, 0x593F0, 0x5A069, 0x5AC1B, 0x5B8AE, 0x5C609, 0x5D479, 0x5E1ED, 0x5EF48, 0x60000, 0x60D5E, 0x61796, 0x619F4, 0x61FB4, 0x626FD, 0x62DA2, 0x63416, 0x63A68, 0x63F99, 0x64494, 0x649CF, 0x6504C, 0x65700, 0x65B01, 0x66124, 0x666F5, 0x66C21, 0x670A5, 0x67553, 0x67A66, 0x68032, 0x68B46, 0x68F0E, 0x69322, 0x6979E, 0x69C98, 0x6A216, 0x6A7D0, 0x6AD56, 0x6B2BA, 0x6B71A, 0x6BBD1, 0x6C038, 0x6C4CD, 0x6C961, 0x6CDEF, 0x6CDFF, 0x6CE08, 0x6CE11, 0x6CE1A, 0x6D142, 0x6D1F8, 0x6D437, 0x6D888, 0x6DDFF, 0x6E3CE, 0x6EC39, 0x70000, 0x709AC, 0x71309, 0x71C7A, 0x72618, 0x72F04, 0x738E9, 0x742F8, 0x74DE8, 0x7587D, 0x7622B, 0x76B9D, 0x773F5, 0x77DF6, 0x78168, 0x784C7, 0x78830, 0x78C00, 0x79003, 0x79406, 0x797CC, 0x79BEE, 0x7A037, 0x7A3C3, 0x7A6E3, 0x7BD60, 0x7C5EA, 0x7D347, 0x7E1C5, 0x80000, 0x80F13, 0x866D2, 0x8B237, 0x90000, 0x949C6, 0x96635, 0x9C498, 0x9CE82, 0x9D77A, 0x9E280, 0x9EAD2, 0xA0000, 0xA0FCC, 0xA1852, 0xA1DDB, 0xA22D1, 0xA3E8F, 0xA48ED, 0xA496F};
+static const uint32_t asset_at[] = {0x0, 0x60D, 0xADE, 0x1079, 0x1563, 0x1A50, 0x1F0A, 0x243D, 0x294A, 0x2E3A, 0x32AC, 0x3727, 0x3BD8, 0x417C, 0x4793, 0x4C81, 0x52C7, 0x58AE, 0x5D52, 0x646B, 0x6A02, 0x6DCD, 0x74CF, 0x7B69, 0x8182, 0x876F, 0x8D50, 0x94A1, 0xB049, 0xB408, 0xB6E5, 0xBDB4, 0xC03C, 0xC39E, 0xC67B, 0xC763, 0xC84A, 0xC92D, 0xCA1C, 0xCB07, 0xCBF1, 0xCD05, 0xCE21, 0xCF42, 0xD5F1, 0xEE01, 0xEED6, 0x10000, 0x10F02, 0x121AE, 0x132AE, 0x154B7, 0x16D1E, 0x1735B, 0x17989, 0x17C1A, 0x18755, 0x19534, 0x1A34A, 0x1B154, 0x1DA42, 0x1F036, 0x20000, 0x20684, 0x20B6B, 0x21122, 0x21681, 0x21DB2, 0x22507, 0x22C0B, 0x233A6, 0x23CE0, 0x2465C, 0x2518B, 0x25EC7, 0x26C7E, 0x27985, 0x287B8, 0x29627, 0x2A3FF, 0x2C41A, 0x2DA37, 0x2DD4A, 0x30000, 0x30A1D, 0x32B6F, 0x35157, 0x36FCB, 0x39588, 0x3B7D4, 0x3D0EA, 0x40000, 0x423FA, 0x43D1F, 0x465CF, 0x47CC8, 0x49789, 0x4B574, 0x4D9C3, 0x50000, 0x51844, 0x52BB4, 0x5368D, 0x540AF, 0x54AE7, 0x554F3, 0x55EB2, 0x5681E, 0x57165, 0x57A56, 0x583E9, 0x58E2A, 0x59A6C, 0x5A68B, 0x5B251, 0x5BDAB, 0x5C996, 0x5D4D7, 0x5DF81, 0x5EA14, 0x60000, 0x60C20, 0x6189B, 0x62495, 0x630A5, 0x63BE3, 0x6472F, 0x651E1, 0x6555C, 0x65D81, 0x66861, 0x67385, 0x67DF3, 0x6885D, 0x690AA, 0x698A3, 0x6A14C, 0x6AC83, 0x6B7EF, 0x6BDDE, 0x6C898, 0x6D310, 0x6DB75, 0x6E342, 0x6EB50, 0x70000, 0x70A40, 0x715DD, 0x718B6, 0x71BDD, 0x71F8D, 0x72428, 0x7292A, 0x72E28, 0x732F8, 0x73780, 0x73B02, 0x73EAF, 0x74213, 0x745BA, 0x748F6, 0x74C32, 0x74C68, 0x74C89, 0x74CA8, 0x74CC4, 0x74CF7, 0x74DD1, 0x75088, 0x755AD, 0x75BA7, 0x76225, 0x76C0F, 0x7768D, 0x77FEA, 0x7892B, 0x79273, 0x79BE3, 0x7A58F, 0x7B050, 0x7BB01, 0x7C651, 0x7D0F9, 0x7D9F9, 0x7E118, 0x7E8B0, 0x7F140, 0x7F1B1, 0x7F243, 0x7F33B, 0x7F444, 0x7F5CB, 0x7F752, 0x7F902, 0x80000, 0x8033F, 0x8053E, 0x806CC, 0x81254, 0x8162F, 0x82029, 0x82B3F, 0x835D8, 0x83C22, 0x84F92, 0x86597, 0x88EDA, 0x8B9A7, 0x90000, 0x92D18, 0x9307E, 0x933BC, 0x93701, 0x939C3, 0x94267, 0x95233, 0x95AB9, 0x96042, 0x96538, 0x980F6, 0x98B54, 0x98BD6};
#endif
diff --git a/games/fnaf/ce/src/fnaf.h b/games/fnaf/ce/src/fnaf.h
index 6bec7588..47b6011e 100644
--- a/games/fnaf/ce/src/fnaf.h
+++ b/games/fnaf/ce/src/fnaf.h
@@ -8,10 +8,10 @@
#include "../engine/gfx.h"
#include "assets.h"
-/* the RAM: scene (the office, a camera, the title, an animation's frames) and what is left after it */
-#define SCENE_W 536
+/* the RAM: scene (the office, a camera, the title (its twitches beside it), an animation's frames) and extra */
+#define SCENE_W 534
#define SCENE_H 120
-#define RAM_NEEDED (SCENE_W * SCENE_H + 26 * 1024)
+#define RAM_NEEDED (SCENE_W * SCENE_H + 160 * 120) /* scene, then extra (160 x 120) */
extern uint8_t *scene, *extra;
extern int scene_pic; /* the picture scene holds, -1 none */
void scene_want(int pic); /* scene holds pic: its bases (or the frames before it) decoded first as needed */
@@ -33,7 +33,7 @@ Ink ink_fade(Ink ink, int a);
/* view.c */
void view_paused(void);
-const uint8_t *static_phases(int a); /* the static's four phases this frame, from its strength (of 32) */
+void static_over(int a, int group); /* the static over the screen, of a strength (of 32) */
void view_reset(void); /* a new night: the office's pictures again */
int office_pan(void);
/* save.c */
diff --git a/games/fnaf/ce/src/main.c b/games/fnaf/ce/src/main.c
index 0b6c76c3..8d6dd8d8 100644
--- a/games/fnaf/ce/src/main.c
+++ b/games/fnaf/ce/src/main.c
@@ -47,10 +47,11 @@ void scene_want(int pic) {
scene_pic = pic;
}
+static int extra_gen; /* (extra is also where pictures unpack their grids: gfx_temp_uses) */
void extra_want(int pic, int stride) {
- if (extra_pic == pic) return;
+ if (extra_pic == pic && extra_gen == gfx_temp_uses) return;
pic_full(pic, extra, stride);
- extra_pic = pic;
+ extra_pic = pic, extra_gen = gfx_temp_uses;
}
bool still(int pic) {
@@ -96,7 +97,7 @@ int fnaf_start(void) {
scene = ce_ram(&n);
if (n < RAM_NEEDED) return 2;
extra = scene + SCENE_W * SCENE_H;
- gfx_init(&assets, ASSET_TABLES);
+ gfx_init(&assets, extra, 160 * 120);
game_init();
return 0;
}
diff --git a/games/fnaf/ce/src/scenes.c b/games/fnaf/ce/src/scenes.c
index 7b83c191..68fbbe27 100644
--- a/games/fnaf/ce/src/scenes.c
+++ b/games/fnaf/ce/src/scenes.c
@@ -17,15 +17,18 @@ static void title_draw(void) {
static const int faces[4][5] = {{0}, {PIC_TITLE1, TITLE1_X, TITLE1_Y, TITLE1_W, TITLE1_H},
{PIC_TITLE2, TITLE2_X, TITLE2_Y, TITLE2_W, TITLE2_H},
{PIC_TITLE3, TITLE3_X, TITLE3_Y, TITLE3_W, TITLE3_H}};
+ static int twitch; /* the twitch beside the title in scene (its rows are 536 wide) */
+ if (scene_pic != PIC_TITLE0) twitch = 0;
scene_want(PIC_TITLE0);
d_blit(scene, SCENE_W, 0, 0, SCR_W, SCENE_H, 0, 0, true);
if (face) {
const int *fc = faces[face];
- extra_want(fc[0], fc[3]);
- d_blit(extra, fc[3], 0, 0, fc[3], fc[4], fc[1], 2 * fc[2], true);
+ if (twitch != face) pic_full(fc[0], scene + SCR_W, SCENE_W), twitch = face;
+ d_blit(scene + SCR_W, SCENE_W, 0, 0, fc[3], fc[4], fc[1], 2 * fc[2], true);
}
int grp = pic_group_of(PIC_TITLE0);
- pal_set(grp, face_light, static_phases(7), 0);
+ pal_set(grp, face_light, 0);
+ static_over(7, grp);
/* the slow light band going down, and lines that flash */
const uint8_t *light = map_remap(grp, 1);
int sy = (int)(g.t / 20 * (SCR_H + 10)) % (SCR_H + 10) - 10;
@@ -51,7 +54,7 @@ static void title_draw(void) {
/* ------------------------------------------------------------------ the newspaper, how to play, the card */
static void news_draw(void) {
still(PIC_NEWSPAPER);
- pal_set(pic_group_of(PIC_NEWSPAPER), fade(g.t, 2, 7, 2), NULL, 0);
+ pal_set(pic_group_of(PIC_NEWSPAPER), fade(g.t, 2, 7, 2), 0);
}
static void keys_draw(void) {
@@ -83,7 +86,7 @@ static void keys_draw(void) {
d_text_c(FONT_TEXT, 160, 196, "Watch the power: every door, light and", INK_GREY);
d_text_c(FONT_TEXT, 160, 209, "camera drains it. Survive until 6 AM.", INK_GREY);
if ((int)(g.t * 2) & 1) d_text_c(FONT_HUD, 160, 226, "2nd", INK_WHITE);
- pal_set(-1, 32, NULL, 0);
+ pal_set(-1, 32, 0);
}
static const char *const nth[] = {"", "1st Night", "2nd Night", "3rd Night", "4th Night", "5th Night", "6th Night",
@@ -95,7 +98,7 @@ static void intro_draw(void) {
UI_GREY1, UI_BOX, UI_BLACK, UI_EDGE});
d_text_c(FONT_HUGE, 160, 92, "12:00 AM", INK_WHITE);
d_text_c(FONT_BIG, 160, 124, nth[g.n.night], INK_WHITE);
- pal_set(-1, 32, NULL, 0);
+ pal_set(-1, 32, 0);
if (g.t > 1.2f) pal_ui((int)((2.2f - g.t) * 32));
}
@@ -130,14 +133,14 @@ static void six_draw(void) {
d_fill(110, cy + dh, 30, dh, UI_BLACK);
d_text(FONT_HUGE, 148, cy, "AM", INK_WHITE);
d_text_c(FONT_TEXT, 160, 170, g.t > 6.2f ? "*children cheering*" : "*chimes*", INK_SILVER);
- pal_set(-1, 32, NULL, 0);
+ pal_set(-1, 32, 0);
pal_ui(fade(g.t, 1, 10.5f, 1));
}
static void paper_draw(void) {
static const int pics[3] = {PIC_PAYCHECK, PIC_OVERTIME, PIC_PINKSLIP};
still(pics[g.paper]);
- pal_set(pic_group_of(pics[g.paper]), fade(g.t, 2, 17, 2), NULL, 0);
+ pal_set(pic_group_of(pics[g.paper]), fade(g.t, 2, 17, 2), 0);
}
/* ------------------------------------------------------------------ the end of a night */
@@ -147,16 +150,23 @@ static void over_draw(void) {
if (g.t < 2.5f) {
still_forget();
d_noise(0, 0, SCR_W, SCR_H, rnd(), GREYS);
- pal_set(-1, 32, NULL, 0);
+ pal_set(-1, 32, 0);
return;
}
- if (!still(PIC_GAMEOVER)) d_text_r(FONT_HUGE, 306, 200, "Game Over", INK_WHITE);
- pal_set(pic_group_of(PIC_GAMEOVER), 32, static_phases(g.t < 3 ? 26 : 6), 0);
+ still_forget();
+ scene_want(PIC_GAMEOVER);
+ d_blit(scene, SCENE_W, 0, 0, SCR_W, SCENE_H, 0, 0, true);
+ static_over(g.t < 3 ? 26 : 6, pic_group_of(PIC_GAMEOVER));
+ d_text_r(FONT_HUGE, 306, 200, "Game Over", INK_WHITE);
+ pal_set(pic_group_of(PIC_GAMEOVER), 32, 0);
}
static void golden_draw(void) {
- still(PIC_GOLDEN);
- pal_set(pic_group_of(PIC_GOLDEN), 32, static_phases(6 + (int)(rnd() % 8)), 0);
+ still_forget();
+ scene_want(PIC_GOLDEN);
+ d_blit(scene, SCENE_W, 0, 0, SCR_W, SCENE_H, ((int)(g.t * 60) & 2) - 1, 0, true);
+ static_over(6 + (int)(rnd() % 8), pic_group_of(PIC_GOLDEN));
+ pal_set(pic_group_of(PIC_GOLDEN), 32, 0);
}
/* ------------------------------------------------------------------ the custom night */
@@ -165,9 +175,10 @@ static const char *const names[4] = {"Freddy", "Bonnie", "Chica", "Foxy"};
static void custom_draw(void) {
/* the faces, in extra once */
- if (extra_pic != EXTRA_FACES) {
+ static int faces_gen = -1;
+ if (extra_pic != EXTRA_FACES || faces_gen != gfx_temp_uses) {
for (int i = 0; i < 4; i++) pic_full(face_pics[i], extra + 64 * 64 * i, 64);
- extra_pic = EXTRA_FACES;
+ extra_pic = EXTRA_FACES, faces_gen = gfx_temp_uses;
}
d_fill(0, 0, SCR_W, SCR_H, UI_BLACK);
d_text_c(FONT_BIG, 160, 14, "Customize Night", INK_WHITE);
@@ -186,7 +197,7 @@ static void custom_draw(void) {
}
d_text(FONT_TEXT, 12, 214, "< > pick up down: level", INK_DIM);
d_text_r(FONT_BIG, 308, 208, "Ready", (int)(g.t * 2) & 1 ? INK_WHITE : INK_GREY);
- pal_set(pic_group_of(PIC_FACE_FREDDY), 32, NULL, 0);
+ pal_set(pic_group_of(PIC_FACE_FREDDY), 32, 0);
}
/* ------------------------------------------------------------------ a frame */
diff --git a/games/fnaf/ce/src/view.c b/games/fnaf/ce/src/view.c
index 80c7b968..80694573 100644
--- a/games/fnaf/ce/src/view.c
+++ b/games/fnaf/ce/src/view.c
@@ -9,11 +9,11 @@
#define N g.n
/* the office's small pictures, decoded once */
-#define DOOR_LW 72
-#define DOOR_RW 64
+#define DOOR_LW 70
+#define DOOR_RW 60
#define PATCH_MAX (LIGHT_R_W * LIGHT_R_H > LIGHT_L_W * LIGHT_L_H ? LIGHT_R_W * LIGHT_R_H : LIGHT_L_W * LIGHT_L_H)
static uint8_t door_l[DOOR_LW * 120], door_r[DOOR_RW * 120];
-static uint8_t panel_l[4][32 * 40], panel_r[4][48 * 40], fans[3][48 * 24];
+static uint8_t panel_l[3][32 * 40], panel_r[3][48 * 40], fans[3][48 * 24]; /* (the buttons lit: 1 to 3) */
static uint8_t patch[PATCH_MAX > DARK_FREDDY_W * DARK_FREDDY_H ? PATCH_MAX : DARK_FREDDY_W * DARK_FREDDY_H];
static bool office_ready;
static int patch_pic = -1;
@@ -33,9 +33,9 @@ static void office_pictures(void) {
if (office_ready) return;
pic_full(PIC_DOOR_L, door_l, DOOR_LW);
pic_full(PIC_DOOR_R, door_r, DOOR_RW);
- for (int k = 0; k < 4; k++) {
- pic_full(PIC_PANEL_L0 + k, panel_l[k], 32);
- pic_full(PIC_PANEL_R0 + k, panel_r[k], 48);
+ for (int k = 0; k < 3; k++) {
+ pic_full(PIC_PANEL_L1 + k, panel_l[k], 32);
+ pic_full(PIC_PANEL_R1 + k, panel_r[k], 48);
}
for (int k = 0; k < 3; k++) pic_full(PIC_FAN0 + k, fans[k], 48);
office_ready = true;
@@ -63,21 +63,17 @@ static void prepare(void) {
f.seed = rnd();
}
-/* the static's four phases, from its strength (of 32): each a share of it, toward a grey of its own (the
- * NumWorks version's static: each pixel toward a random grey, 0 to 143) */
-const uint8_t *static_phases(int a) {
- static uint8_t ph[8];
- for (int k = 0; k < 4; k++) {
- uint32_t r = rnd();
- ph[k] = (uint8_t)(a * (int)(r % 5) / 4);
- ph[4 + k] = (uint8_t)(r >> 8 & 15);
- }
- return ph;
-}
-
static const uint8_t GREYS[8] = {UI_BLACK, UI_WHITE1, UI_GREY1, UI_SPARE, UI_DIM, UI_GREY2, UI_EDGE, UI_BOX};
static const uint8_t DARK_GREYS[8] = {UI_BLACK, UI_BLACK, UI_BOX, UI_BLACK, UI_EDGE, UI_BLACK, UI_BOX, UI_GREY1};
+/* the static over a picture (the NumWorks version: each pixel a share of the way to a random grey): snow, and a
+ * lighter line now and then */
+void static_over(int a, int group) {
+ d_snow(a * 110, rnd(), GREYS);
+ uint32_t r = rnd();
+ if ((r & 3) == 0) d_remap(0, (int)(r >> 8) % SCR_H, SCR_W, 1 + (int)(r >> 4 & 1), map_remap(group, 1));
+}
+
/* ------------------------------------------------------------------ text helpers */
static void small_digits(int font, int x, int y, int v, Ink ink) {
char s[4];
@@ -228,8 +224,10 @@ static int office(void) {
d_blit(patch, LIGHT_R_W, 0, 0, LIGHT_R_W, LIGHT_R_H, LIGHT_R_X - px, 2 * LIGHT_R_Y, true);
}
d_blit(fans[f.fan], 48, 0, 0, 48, 24, FAN_X - px, FAN_Y, true);
- d_blit(panel_l[N.door[LEFT] | (N.light == 1 + LEFT) << 1], 32, 0, 0, 26, 40, PANEL_L_X - px, PANEL_Y, true);
- d_blit(panel_r[N.door[RIGHT] | (N.light == 1 + RIGHT) << 1], 48, 0, 0, 48, 40, PANEL_R_X - px, PANEL_Y, true);
+ /* the buttons (all off: as the office has them) */
+ int bl = N.door[LEFT] | (N.light == 1 + LEFT) << 1, br = N.door[RIGHT] | (N.light == 1 + RIGHT) << 1;
+ if (bl) d_blit(panel_l[bl - 1], 32, 0, 0, 26, 40, PANEL_L_X - px, PANEL_Y, true);
+ if (br) d_blit(panel_r[br - 1], 48, 0, 0, 48, 40, PANEL_R_X - px, PANEL_Y, true);
for (int s = 0; s < 2; s++) {
int vis = (int)(N.door_anim[s] * 120 + 0.5f);
if (vis > 0)
@@ -259,7 +257,7 @@ static int cam_picture(void) {
return b && c ? PIC_CAM1A_BCF : b ? PIC_CAM1A_BF : c ? PIC_CAM1A_CF : PIC_CAM1A_F;
case CAM_1B: return PIC_CAM1B_EMPTY + (b && c && fr ? 7 : b && c ? 4 : b && fr ? 5 : c && fr ? 6 : b ? 1 : c ? 2 : fr ? 3 : 0);
case CAM_1C: return PIC_CAM1C_0 + (N.foxy < 3 ? N.foxy : 3);
- case CAM_2A: return !f.hall_lit ? PIC_CAM2A_DARK : b ? PIC_CAM2A_B : PIC_CAM2A_EMPTY;
+ case CAM_2A: return b ? PIC_CAM2A_B : PIC_CAM2A_EMPTY; /* (its light flickering: the palette) */
case CAM_2B: return (N.gold == 1 || N.gold == 2) && !b ? PIC_CAM2B_GOLD : b ? PIC_CAM2B_B : PIC_CAM2B_EMPTY;
case CAM_3: return b ? PIC_CAM3_B : PIC_CAM3_EMPTY;
case CAM_4A: return c && fr ? PIC_CAM4A_CF : c ? PIC_CAM4A_C : fr ? PIC_CAM4A_F : PIC_CAM4A_EMPTY;
@@ -309,8 +307,9 @@ static int cameras(bool paused) {
grp = pic_group_of(pic);
}
if (grp < 0) grp = pic_group_of(PIC_CAM1A_EMPTY); /* (no picture shows: its colours unused) */
- pal_set(grp, paused ? 9 : 32, paused ? NULL : static_phases(noise),
- g.blip > 0 && !paused ? (int)(g.blip * 120) : 0);
+ else if (!paused) static_over(noise, grp);
+ int dim = N.cam == CAM_2A && !f.hall_lit && N.foxy_run < 0 ? 11 : 32; /* 2A's lamp, off most of the time */
+ pal_set(grp, paused ? 9 * dim / 32 : dim, g.blip > 0 && !paused ? (int)(g.blip * 120) : 0);
d_frame(5, 5, 310, 230, UI_FRAME);
if ((int)(g.t * 1.5f) & 1) { /* the recording dot */
static const uint8_t dot[7] = {2, 1, 0, 0, 0, 1, 2};
@@ -349,11 +348,11 @@ static void night_draw(bool paused) {
d_blit2(extra, 160, 0, UI_BLACK);
grp = pic_group_of(PIC_FLIP0 + k);
}
- pal_set(grp, paused ? 9 : 32, NULL, 0);
+ pal_set(grp, paused ? 9 : 32, 0);
}
if (paused) return;
int shown = hallucination(grp);
- if (shown != grp) pal_set(shown, 32, NULL, 0);
+ if (shown != grp) pal_set(shown, 32, 0);
if (!N.dark) {
clock_and_night();
power_hud();
@@ -382,5 +381,5 @@ void view_scare(void) {
int dx = g.scare_t > 0.1f ? f.shake : 0;
scene_want(first[w] + k);
d_blit2(scene, SCENE_W, dx, UI_BLACK);
- pal_set(pic_group_of(first[w]), 32, NULL, 0);
+ pal_set(pic_group_of(first[w]), 32, 0);
}
diff --git a/games/fnaf/ce/tests/ce_pics/makefile b/games/fnaf/ce/tests/ce_pics/makefile
new file mode 100644
index 00000000..e7ccf8ee
--- /dev/null
+++ b/games/fnaf/ce/tests/ce_pics/makefile
@@ -0,0 +1,9 @@
+# The calculator's picture decoder checked (src/main.c): make, then tests/check.py runs bin/PICTEST.8xp in ce_emu
+NAME = PICTEST
+COMPRESSED = YES
+ARCHIVED = NO
+CFLAGS = -Wall -Oz -DCE_ASM
+SRCDIR = src
+EXTRA_C_SOURCES = ../../engine/pic.c ../../engine/gfx.c ../../engine/ce_calc.c
+EXTRA_ASM_SOURCES = ../../engine/pic_ez80.s ../../engine/draw_ez80.s
+include $(shell cedev-config --makefile)
diff --git a/games/fnaf/ce/tests/ce_pics/src/main.c b/games/fnaf/ce/tests/ce_pics/src/main.c
new file mode 100644
index 00000000..6b76f1dd
--- /dev/null
+++ b/games/fnaf/ce/tests/ce_pics/src/main.c
@@ -0,0 +1,46 @@
+/* The calculator's decoder (engine/pic_ez80.s) checked: every picture decoded with its bases, a sum of its bytes
+ * (two 16-bit sums, as tests/pics.c --sums makes them on a computer) into the appvar FNAFSUM. tests/check.py runs
+ * it in tools/ce_emu and compares; it also times the decoding (the cycles in FNAFSUM's last 4 bytes...). */
+#include <fileioc.h>
+#include <string.h>
+#include <time.h>
+#include "../../../src/fnaf.h"
+
+static const uint8_t *vars[DATA_VARS];
+static uint8_t sums[PIC_COUNT * 4 + 8];
+
+int main(void) {
+ if (!ce_data(DATA_VAR, DATA_VARS, vars)) return 1;
+ static const Assets a = {vars, asset_at, pic_group, PIC_FIRST, MAP_FIRST, FONT_FIRST};
+ gfx_init(&a, (uint8_t *)0xD52C00, 160 * 120); /* (the second screen buffer: room) */
+ uint8_t *buf = (uint8_t *)0xD40000; /* (the screen's memory: room for any picture) */
+ clock_t t0 = clock();
+#ifdef ONLY
+ for (int p = ONLY; p <= ONLY; p++) {
+#else
+ for (int p = 0; p < PIC_COUNT; p++) {
+#endif
+ int w = pic_w(p), h = pic_h(p);
+ pic_full(p, buf, w);
+ uint16_t s1 = 0, s2 = 0;
+ for (uint8_t *q = buf, *e = buf + w * h; q < e; q++) s1 += *q, s2 += s1;
+ sums[4 * p] = (uint8_t)s1, sums[4 * p + 1] = (uint8_t)(s1 >> 8);
+ sums[4 * p + 2] = (uint8_t)s2, sums[4 * p + 3] = (uint8_t)(s2 >> 8);
+ }
+ uint32_t t = (uint32_t)(clock() - t0);
+#ifdef DUMP /* (one picture's bytes, to look at: FNAFDMP) */
+ pic_full(DUMP, buf, pic_w(DUMP));
+ uint8_t d = ti_Open("FNAFDMP", "w");
+ if (d) {
+ ti_Write(buf, 1, (size_t)(pic_w(DUMP) * pic_h(DUMP)), d);
+ ti_Close(d);
+ }
+#endif
+ memcpy(sums + PIC_COUNT * 4, &t, 4);
+ uint8_t f = ti_Open("FNAFSUM", "w");
+ if (f) {
+ ti_Write(sums, 1, sizeof sums, f);
+ ti_Close(f);
+ }
+ return 0;
+}
diff --git a/games/fnaf/ce/tests/check.py b/games/fnaf/ce/tests/check.py
new file mode 100644
index 00000000..ee1c6e4a
--- /dev/null
+++ b/games/fnaf/ce/tests/check.py
@@ -0,0 +1,176 @@
+#!/usr/bin/env python3
+"""Checks of the CE version of Five Nights at Freddy's on a computer (make -f host.mk test): every picture decoded
+as tools/pack.py made it, the menus, whole nights played by tests/play.c's own player, each animatronic's attack,
+the power going out, Golden Freddy, the custom night, pausing, Home and the save, and random keys.
+
+ python3 tests/check.py build/play build/pics [--quick]"""
+import os
+import random
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+PLAY = sys.argv[1] if len(sys.argv) > 1 else "build/play"
+PICTURES = sys.argv[2] if len(sys.argv) > 2 else "build/pics"
+QUICK = "--quick" in sys.argv
+ENV = dict(os.environ, ASAN_OPTIONS="detect_leaks=0", UBSAN_OPTIONS="halt_on_error=1:print_stacktrace=1")
+failures = []
+SC_TITLE, SC_NIGHT, SC_SCARE, SC_SIX, SC_PAPER, SC_OVER, SC_CUSTOM = 0, 4, 5, 6, 7, 8, 9
+SCARE_BONNIE, SCARE_CHICA, SCARE_FREDDY, SCARE_FOXY, SCARE_DARK = range(5)
+IN_OFFICE = 12
+NIGHT = 60 * 535 + 200 # a night's steps, its card and a bit
+
+
+def run(args, frames, saves=None, what=""):
+ """Plays; returns the end state (a dict) and the events (6 AM, jumpscares) on the way"""
+ own = saves is None
+ if own:
+ saves = tempfile.mkdtemp(prefix="fnafce_check_")
+ shots = tempfile.mkdtemp(prefix="fnafce_shots_")
+ p = subprocess.run([PLAY, "--saves", saves, "--out", shots, "--frames", str(frames)] + args, capture_output=True,
+ text=True, env=ENV, timeout=1800)
+ shutil.rmtree(shots, ignore_errors=True)
+ if own:
+ shutil.rmtree(saves, ignore_errors=True)
+ if p.returncode or "runtime error" in p.stderr or "AddressSanitizer" in p.stderr:
+ failures.append(f"{what or args}: crashed or a sanitizer error\n{p.stderr[-2000:]}")
+ return None, []
+ m = re.search(r"END (.*)", p.stdout)
+ if not m:
+ failures.append(f"{what}: no end state\n{p.stdout[-500:]}")
+ return None, []
+ words = m.group(1).split()
+ s = {}
+ for k, v in zip(words[::2], words[1::2]):
+ s[k] = [int(x) for x in v.split(",")] if "," in v else float(v) if "." in v else int(v)
+ events = [dict(zip(e.split()[1::2], e.split()[2::2]), kind=e.split()[0])
+ for e in re.findall(r"EVENT (.*)", p.stdout)]
+ return s, events
+
+
+def check(cond, msg):
+ if not cond:
+ failures.append(msg)
+
+
+def save_file(saves):
+ p = os.path.join(saves, "NPfnaf.8xv.bin")
+ return open(p, "rb").read() if os.path.exists(p) else None
+
+
+# every picture decodes as it was made
+p = subprocess.run([PICTURES], capture_output=True, text=True, env=ENV, timeout=600)
+check(p.returncode == 0 and "runtime error" not in p.stderr, f"pictures: {p.stdout[-300:]} {p.stderr[-1500:]}")
+
+# the title, New Game, the newspaper (skipped), how to play, the first night's card, then the office
+saves = tempfile.mkdtemp(prefix="fnafce_check_")
+s, _ = run(["--keys", "60:ok,200:ok,700:ok"], 1400, saves, "a new game")
+if s:
+ check(s["scene"] == SC_NIGHT and s["night"] == 1 and s["keys_seen"] == 1, f"a new game: {s}")
+ check(save_file(saves) is not None, "a new game: no save")
+# clear pauses; Quit night asks, and Yes goes back to the title
+s, _ = run(["--night", "1", "--keys", "400:back,430:down,450:down,470:ok,500:right,520:ok"], 600, saves, "quitting")
+if s:
+ check(s["scene"] == SC_TITLE, f"quitting a night: {s}")
+shutil.rmtree(saves, ignore_errors=True)
+
+# whole nights, played by the test's player: 6 AM, then the next night's card
+for n in ([1] if QUICK else [1, 2, 3]):
+ saves = tempfile.mkdtemp(prefix="fnafce_check_")
+ s, ev = run(["--night", str(n), "--bot"], NIGHT + 800, saves, f"night {n}")
+ if s:
+ six = [e for e in ev if e["kind"] == "six"]
+ check(six and int(six[0]["night"]) == n, f"night {n} not survived: {ev}")
+ check(s["reached"] == n + 1 and s["night"] == n + 1, f"night {n}: the next night not reached: {s}")
+ shutil.rmtree(saves, ignore_errors=True)
+
+# the fifth night's 6 AM: a star and the paycheck, then the title
+s, ev = run(["--night", "5", "--hour", "5", "--bot"], 89 * 60 + 2200, None, "night 5's end")
+if s:
+ check(any(e["kind"] == "six" for e in ev) and s["stars"] & 1 and s["scene"] == SC_TITLE,
+ f"night 5's end: {s} {ev}")
+
+# the doors' and lights' power: two doors and a light drain four points a second
+s, _ = run(["--night", "1", "--keys", "200:7,300:9,400-430:left,440:1"], 140 + 60 * 20, None, "power")
+if s:
+ check(s["doors"] == [1, 1] and 900 < s["power"] < 960, f"doors and lights: {s}")
+
+# the power goes out: Freddy's song, the dark, his jumpscare, the game over, the title
+s, ev = run(["--night", "1", "--power", "3"], 60 * 75, None, "power out")
+if s:
+ check(any(e["kind"] == "scare" and int(e["who"]) == SCARE_DARK for e in ev) and s["scene"] == SC_TITLE,
+ f"power out: {s} {ev}")
+
+# Bonnie and Chica come in while the monitor is up; it comes down by itself, and they get you
+s, ev = run(["--night", "1", "--ai", "0,20,20,0", "--keys", "300:8"], 60 * 80, None, "Bonnie and Chica")
+if s:
+ check(any(e["kind"] == "scare" and int(e["who"]) in (SCARE_BONNIE, SCARE_CHICA) for e in ev),
+ f"Bonnie and Chica: {s} {ev}")
+s, ev = run(["--night", "1", "--ai", "0,20,20,0", "--keys", "200:7,300:9"], 60 * 60, None, "doors closed")
+if s:
+ check(not ev and s["pos"][1] != IN_OFFICE and s["pos"][2] != IN_OFFICE, f"doors closed: {s} {ev}")
+
+# Foxy: out of the cove with the cameras down, down the hall, in through the open door; or banging on it
+s, ev = run(["--night", "1", "--ai", "0,0,0,20"], 60 * 60, None, "Foxy")
+if s:
+ check(any(e["kind"] == "scare" and int(e["who"]) == SCARE_FOXY for e in ev), f"Foxy: {s} {ev}")
+s, ev = run(["--night", "1", "--ai", "0,0,0,20", "--keys", "200:7"], 60 * 60, None, "Foxy at the door")
+if s:
+ check(not ev and s["pounds"] >= 1, f"Foxy at the closed door: {s} {ev}")
+
+# Freddy: in while the monitor looks elsewhere, then he gets you once it is down
+s, ev = run(["--night", "1", "--ai", "20,0,0,0", "--pos", "0,5,7", "--keys", "3000:8,3300:8"], 60 * 80, None, "Freddy")
+if s:
+ check(any(e["kind"] == "scare" and int(e["who"]) == SCARE_FREDDY for e in ev), f"Freddy: {s} {ev}")
+
+# Golden Freddy: his poster on 2B, then in the office, then the game is gone
+s, ev = run(["--night", "1", "--gold", "--keys", "300:8,360:2,400:2,480:8"], 1400, None, "Golden Freddy")
+if s:
+ check(any(e["kind"] == "golden" for e in ev) and s["running"] == 0, f"Golden Freddy: {s} {ev}")
+
+# the custom night: 20/20/20/20 starts the night; 1/9/8/7 is Golden Freddy's
+s, ev = run(["--stars", "3", "--keys", "100:down,120:down,140:down,160:ok,200-560:up,600:right,620-980:up,"
+ "1000:right,1020-1380:up,1400:right,1420-1780:up,1820:ok"], 2200, None, "custom night 20")
+if s:
+ check(s["scene"] == SC_NIGHT and s["night"] == 7 and s["ai"] == [20, 20, 20, 20], f"custom night 20/20/20/20: {s}")
+s, ev = run(["--stars", "3", "--keys", "100:down,120:down,140:down,160:ok,200:up,240:right,"
+ + ",".join(f"{260 + 12 * i}:up" for i in range(9)) + ",400:right,"
+ + ",".join(f"{420 + 12 * i}:up" for i in range(8)) + ",560:right,"
+ + ",".join(f"{580 + 12 * i}:up" for i in range(7)) + ",700:ok"], 1000, None, "custom night 1987")
+if s:
+ check(s["running"] == 0 and any(e["kind"] == "golden" for e in ev), f"custom night 1/9/8/7: {s} {ev}")
+
+# mode keeps the night: the next start is back in it, paused, at the same moment, once
+saves = tempfile.mkdtemp(prefix="fnafce_check_")
+s, _ = run(["--night", "2", "--keys", "200:7,1500:home"], 1600, saves, "mode")
+if s:
+ check(s["running"] == 0, f"mode: {s}")
+ s2, _ = run([], 30, saves, "back after mode")
+ if s2:
+ check(s2["scene"] == SC_NIGHT and s2["paused"] == 1 and s2["night"] == 2 and abs(s2["t"] - s["t"]) < 0.5
+ and s2["doors"][0] == 1, f"back after mode: {s2} (left at {s})")
+ s3, _ = run([], 30, saves, "the next start")
+ if s3:
+ check(s3["scene"] == SC_TITLE, f"the kept night is read once: {s3}")
+shutil.rmtree(saves, ignore_errors=True)
+
+# 0 mutes the call
+s, _ = run(["--night", "1", "--keys", "600:0"], 800, None, "mute")
+if s:
+ check(s["muted"] == 1, f"mute: {s}")
+
+# random keys: no crash
+rng = random.Random(7)
+names = ["left", "right", "up", "down", "2nd", "enter", "clear", "del"] + [str(d) for d in range(10)]
+for k in range(4 if QUICK else 12):
+ keys = ",".join(f"{t}:{rng.choice(names)}" for t in sorted(rng.sample(range(10, 3000), 160)))
+ run(["--night", str(rng.randint(1, 7)), "--ai", "10,10,10,10", "--keys", keys], 3000, None, f"random keys {k}")
+
+if failures:
+ print(f"{len(failures)} failures:")
+ for f in failures:
+ print("-", f)
+ sys.exit(1)
+print("all checks passed")
diff --git a/games/fnaf/ce/tests/pics.c b/games/fnaf/ce/tests/pics.c
index 3688c95a..2296ffdd 100644
--- a/games/fnaf/ce/tests/pics.c
+++ b/games/fnaf/ce/tests/pics.c
@@ -1,5 +1,7 @@
-/* Decodes every picture of the CE version (with its bases) and writes it as the screen would show it:
- * pics OUT_DIR [--data DIR] (OUT_DIR/pic_<id>.ppm, rows doubled for the half-height ones) */
+/* Decodes every picture of the CE version (with its bases), checks it against what tools/pack.py made
+ * (tests/pics.crc: each picture's palette indices, their CRC-32) and writes it as the screen would show it:
+ * pics [OUT_DIR] [--data DIR] [--crc FILE] [--sums FILE] (OUT_DIR/pic_<id>.ppm, rows doubled for the
+ * half-height ones; FILE: each picture's two 16-bit sums, tests/ce_pics's) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -8,24 +10,59 @@
extern const char *host_data_dir;
static const uint8_t *vars[DATA_VARS];
+static uint32_t crc32(const uint8_t *p, size_t n) {
+ uint32_t c = 0xFFFFFFFFu;
+ while (n--) {
+ c ^= *p++;
+ for (int k = 0; k < 8; k++) c = c >> 1 ^ (0xEDB88320u & -(c & 1));
+ }
+ return ~c;
+}
+
int main(int argc, char **argv) {
- if (argc < 2) return 2;
- if (argc > 3 && !strcmp(argv[2], "--data")) host_data_dir = argv[3];
+ const char *out = NULL, *crcfile = "tests/pics.crc", *sumfile = NULL, *rawfile = NULL;
+ int raw = -1;
+ for (int i = 1; i < argc; i++) {
+ if (!strcmp(argv[i], "--data")) host_data_dir = argv[++i];
+ else if (!strcmp(argv[i], "--crc")) crcfile = argv[++i];
+ else if (!strcmp(argv[i], "--sums")) sumfile = argv[++i];
+ else if (!strcmp(argv[i], "--raw")) raw = atoi(argv[i + 1]), rawfile = argv[i + 2], i += 2;
+ else out = argv[i];
+ }
if (!ce_data(DATA_VAR, DATA_VARS, vars)) {
fprintf(stderr, "missing %s\n", ce_missing);
return 1;
}
static const Assets a = {vars, asset_at, pic_group, PIC_FIRST, MAP_FIRST, FONT_FIRST};
- gfx_init(&a, ASSET_TABLES);
+ static uint8_t temp[160 * 120];
+ gfx_init(&a, temp, sizeof temp);
+ FILE *cf = fopen(crcfile, "r"), *sf = sumfile ? fopen(sumfile, "wb") : NULL;
static uint8_t buf[640 * 480];
+ int bad = 0;
for (int p = 0; p < PIC_COUNT; p++) {
int w = pic_w(p), h = pic_h(p);
memset(buf, 0, sizeof buf);
pic_full(p, buf, w);
+ unsigned want = 0;
+ if (cf && fscanf(cf, "%x", &want) == 1 && want != crc32(buf, (size_t)(w * h))) {
+ fprintf(stderr, "picture %d: not what tools/pack.py made\n", p);
+ bad++;
+ }
+ if (p == raw) { /* (its bytes as they are) */
+ FILE *rf = fopen(rawfile, "wb");
+ if (rf) fwrite(buf, 1, (size_t)(w * h), rf), fclose(rf);
+ }
+ if (sf) { /* (tests/ce_pics's sums: two 16-bit ones) */
+ uint16_t s1 = 0, s2 = 0;
+ for (int i = 0; i < w * h; i++) s1 = (uint16_t)(s1 + buf[i]), s2 = (uint16_t)(s2 + s1);
+ uint8_t b[4] = {(uint8_t)s1, (uint8_t)(s1 >> 8), (uint8_t)s2, (uint8_t)(s2 >> 8)};
+ fwrite(b, 1, 4, sf);
+ }
+ if (!out) continue;
const uint16_t *pal = map_palette(pic_group_of(p));
int dbl = h <= 120 && w > 160 ? 2 : 1; /* (the half-height ones as shown) */
char path[512];
- snprintf(path, sizeof path, "%s/pic_%03d.ppm", argv[1], p);
+ snprintf(path, sizeof path, "%s/pic_%03d.ppm", out, p);
FILE *f = fopen(path, "wb");
if (!f) return 1;
fprintf(f, "P6\n%d %d\n255\n", w, h * dbl);
@@ -38,6 +75,7 @@ int main(int argc, char **argv) {
}
fclose(f);
}
- printf("%d pictures\n", PIC_COUNT);
- return 0;
+ if (sf) fclose(sf);
+ printf("%d pictures, %d not as made\n", PIC_COUNT, bad);
+ return bad != 0;
}
diff --git a/games/fnaf/ce/tests/pics.crc b/games/fnaf/ce/tests/pics.crc
new file mode 100644
index 00000000..15fdd57a
--- /dev/null
+++ b/games/fnaf/ce/tests/pics.crc
@@ -0,0 +1,186 @@
+417558c6
+e91de00f
+b94844ac
+a76d74d9
+cb18c84c
+24a778cc
+b74a85c0
+8ed439dd
+92b60ab0
+6983db90
+0e7b78fa
+59e3409a
+5a44aa0c
+8e0275e9
+d433c175
+ef371fcf
+e299c618
+dab905e0
+6e12ec15
+0bea95a5
+1f8eca0b
+c4611eb2
+4d43b7dc
+18384567
+07b1a467
+94ba8c98
+7459eaf3
+b0308351
+81915c6a
+fd7e8e39
+df0019f6
+762ff7e5
+09b0a323
+c79b9af1
+cc4ddf93
+ad1591a7
+f0c07540
+17ff58c3
+435011a4
+0e09dfcd
+26e9bee2
+cbe59acf
+92f6ad58
+8fd328f9
+184930c5
+140c39e7
+30fe0f61
+077acf8e
+031dd23e
+4bf324b3
+3689f396
+ce88d33d
+fd09367f
+c29ed66c
+5876cd8d
+47f5a2a4
+a022171b
+f7678ce8
+50b7d112
+cfd269c3
+b33a907d
+afc00ebf
+a614aa1e
+1be7bb5d
+60aee6a6
+2376a65f
+daa185d1
+67019f31
+7bc098fb
+94514775
+1c615970
+26415aa6
+a6e835da
+b36c4060
+3b1170cf
+a75c4817
+3cd9f3c9
+67b289c8
+a4ae05cc
+f46ae2f1
+b40ea7ef
+60e4dc51
+440516f4
+922100a3
+f0daf503
+ec8aba18
+b673d5e6
+94b1fdd2
+727e1f6f
+c28c32f2
+523d33d7
+3dada105
+6960f00a
+5efad05a
+273b1495
+61488b56
+bd0ae2d4
+81789284
+027beade
+27722018
+f3809462
+9ad77938
+4dda7b48
+b067193d
+ad482d63
+157b4570
+f5adb744
+dc5ef07b
+2dbe413e
+e965c65c
+5ee947d8
+f3640280
+dc0fdfde
+2ad27fef
+721a2bad
+047d194e
+c1c55d93
+2f419241
+0ad0a520
+21a2cc77
+baa6b6de
+2fc5f94c
+defdee1a
+d1326695
+80ea524a
+cbca8fbe
+f3c709c5
+94e2f9be
+fd48df6b
+bb253700
+a2b9104d
+1d7bd5cb
+454908eb
+1023c02e
+74ec16d6
+b9156a0a
+c7047715
+7733fe60
+4846682e
+62145359
+2c6fa641
+bc493fea
+4bb46d51
+60d492d6
+f7e93742
+f6877af9
+a4aca3ef
+51cf66c8
+c3c2c68e
+f1e52168
+de92a628
+0b2b345d
+3a0af953
+430138d9
+6554f1ff
+51d33ea2
+589cd6a5
+f9f48e88
+309bd382
+062c44f7
+cf64ae7b
+2cd10fe3
+d3f8a92e
+235aabb1
+235aabb1
+8f2be688
+a6486b58
+d7d05aee
+0aa33dd2
+ba6ddd30
+9dc1ec46
+928e1ade
+ee22fbff
+9b662076
+ff1ed4e9
+65ff1910
+4d079341
+0cae852f
+e8156bb6
+ed9eaeb2
+4162059a
+6d2cf4dc
+95bb249a
+696abd67
+acd7590d
+4a61e9e9
diff --git a/games/fnaf/ce/tools/cepack.py b/games/fnaf/ce/tools/cepack.py
new file mode 100644
index 00000000..526d684b
--- /dev/null
+++ b/games/fnaf/ce/tools/cepack.py
@@ -0,0 +1,249 @@
+#!/usr/bin/env python3
+"""What the Five Nights at Freddy's games' CE packers share (tools/pack.py of each game): pictures in palette groups
+(tools/cvq.py), fonts and small pictures of 2-bit alpha, the appvars and the header that says where things are.
+
+ p = Pack("FNAFD") the appvars' names: FNAFD0, FNAFD1...
+ g = p.group("office") a palette group
+ p.pic("OFFICE", rgb, g) a picture (rgb: (h, w, 3) floats), maybe over a base (keep: when)
+ p.define("OFFICE_W", 534)
+ p.font("HUD", line, ascent, glyphs) (the NumWorks packers' ttf_font / fnt_font)
+ p.blob("CAMMAP", data) anything else, ASSET_CAMMAP
+ p.write(ce_dir) data/*.bin, src/assets.h, tests/pics.crc"""
+import os
+import struct
+import subprocess
+import tempfile
+import zlib
+
+import numpy as np
+from PIL import Image, ImageFilter
+
+import cvq as V
+
+CONVBIN = os.path.join(os.environ.get("CEDEV", os.path.expanduser("~/Documents/Assets/toolchains/CEdev")), "bin",
+ "convbin")
+VAR_ROOM = 65000
+FONT_DIRS = [os.path.expanduser("~/Documents/Assets/gamesrc/fonts/dejavu")]
+
+# 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)]
+UI_RGB = [((v >> 16) & 255, (v >> 8) & 255, v & 255) for _, v in UI]
+TIGHT = V.keep_within(12, 2.0) # a variant: kept where its source is as good as the base's own
+ANIM = V.keep_within(18, 3.5) # an animation's frame: what hardly moved
+
+
+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()
+
+
+# ------------------------------------------------------------------ pictures
+def pad2(a):
+ h, w = a.shape[:2]
+ return np.pad(a, ((0, h % 2), (0, w % 2), (0, 0)), mode="edge")
+
+
+def pad8(a):
+ h, w = a.shape[:2]
+ return np.pad(a, ((0, -h % 8), (0, -w % 8), (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, sharpen=False):
+ """at half height (the calculator shows each row twice); a little sharper for it when asked"""
+ im = Image.fromarray(np.clip(a, 0, 255).astype(np.uint8))
+ im = im.resize((im.width, (im.height + 1) // 2), Image.LANCZOS)
+ if sharpen:
+ im = im.filter(ImageFilter.UnsharpMask(radius=1.0, percent=50, threshold=1))
+ return np.asarray(im).astype(np.float64)
+
+
+def box(a, b, thresh=10):
+ """the squares of 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 remaps(g):
+ """two 256-byte tables of a group's palette: each colour darkened to 45 %, and lightened a fifth of the way to
+ white: the nearest colour (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] if i < len(pal) else (0, 0, 0) for i in range(224)] + UI_RGB, dtype=np.float64)
+ sets = [list(range(len(pal))), 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 = 0 if i < 224 else 1
+ _, j = trees[k].query(np.sqrt(np.clip(f(cols[i]), 0, 255) / 255))
+ t.append(sets[k][j])
+ out += bytes(t)
+ return out
+
+
+# ------------------------------------------------------------------ fonts and small pictures
+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 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). glyphs: the
+ NumWorks packers' (4-bit alpha, two pixels a byte)"""
+ head = struct.pack("<BB", line, asc)
+ rows = b""
+ table = b""
+ base = 2 + 8 * 95
+ for adv, w, h, x, y, nib in glyphs:
+ a2 = np.clip((unnibble(nib, w, h) * 3 + 7) // 15, 0, 3)
+ table += struct.pack("<BBBbbBH", adv, w, h, x, y, 0, base + len(rows))
+ rows += pack2(a2)
+ return head + table + rows
+
+
+def img_blob(alpha):
+ """a small picture of 2-bit alpha: width, height (u16), rows"""
+ 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 rgba_alpha(path, scale=None, size=None):
+ """a picture's alpha (times its brightness) for img_blob"""
+ t = Image.open(path).convert("RGBA")
+ if scale:
+ t = t.resize((int(t.width * scale), int(t.height * scale)), Image.LANCZOS)
+ if size:
+ t = t.resize(size, Image.LANCZOS)
+ a = np.asarray(t).astype(np.float64)
+ return a[..., 3] * a[..., :3].mean(axis=2) / 255
+
+
+# ------------------------------------------------------------------ all of it
+class Entry:
+ def __init__(self, name, vq, group):
+ self.name, self.vq, self.group = name, vq, group
+
+
+class Pack:
+ def __init__(self, prefix):
+ self.prefix = prefix
+ self.pics, self.groups, self.defines, self.fonts, self.blobs = [], {}, [], [], []
+
+ def group(self, name):
+ self.groups[name] = V.Group(name, 224)
+ return name
+
+ def pic(self, name, rgb, grp, base=None, keep=None):
+ e = Entry(name, V.Picture(pad2(rgb), base.vq if base else None, keep), grp)
+ self.groups[grp].add(e.vq)
+ self.pics.append(e)
+ return e
+
+ def define(self, name, value):
+ self.defines.append((name, value))
+
+ def font(self, name, line, asc, glyphs):
+ self.fonts.append((name, font_blob(line, asc, glyphs)))
+
+ def blob(self, name, data):
+ self.blobs.append((name, bytes(data)))
+
+ def write(self, ce):
+ print(f"coding {len(self.pics)} pictures in {len(self.groups)} groups", flush=True)
+ for g in self.groups.values():
+ g.fit()
+ for e in self.pics:
+ self.groups[e.group].code(e.vq, e.vq.keep)
+ crcs = [zlib.crc32(self.groups[e.group].indices_of(e.vq).astype(np.uint8).tobytes()) for e in self.pics]
+ os.makedirs(os.path.join(ce, "tests"), exist_ok=True)
+ open(os.path.join(ce, "tests", "pics.crc"), "w").write("".join(f"{c:08x}\n" for c in crcs))
+ gnames = list(self.groups)
+ from concurrent.futures import ThreadPoolExecutor
+ ids = {id(e.vq): i for i, e in enumerate(self.pics)}
+ with ThreadPoolExecutor(os.cpu_count() or 4) as ex: # (zx0's compressor takes its time)
+ maps = list(ex.map(lambda n: zx0(self.groups[n].blob(UI_RGB) + remaps(self.groups[n])), gnames))
+ pics = list(ex.map(lambda e: V.write(e.vq, ids.get(id(e.vq.base), 0), zx0), self.pics))
+ blobs = [("MAP_" + n.upper(), m) for n, m in zip(gnames, maps)]
+ blobs += [("PIC_" + e.name, d) for e, d in zip(self.pics, pics)]
+ blobs += [("FONT_" + n, d) for n, d in self.fonts] + self.blobs
+ # into appvars of 64 KB at most
+ data = os.path.join(ce, "data")
+ os.makedirs(data, exist_ok=True)
+ for f in os.listdir(data):
+ if f.startswith(self.prefix) and f.endswith(".bin"):
+ os.remove(os.path.join(data, f))
+ vars_, at = [bytearray()], []
+ for name, d in blobs:
+ if len(vars_[-1]) + len(d) > VAR_ROOM:
+ vars_.append(bytearray())
+ at.append((len(vars_) - 1, len(vars_[-1])))
+ vars_[-1] += d
+ for i, v in enumerate(vars_):
+ open(os.path.join(data, f"{self.prefix}{i}.bin"), "wb").write(v)
+ names = [n for n, _ in blobs]
+ h = [f"/* Made by tools/pack.py: what is in the appvars {self.prefix}0, {self.prefix}1... */",
+ "#ifndef CE_ASSETS_H", "#define CE_ASSETS_H", "#include <stdint.h>", "",
+ f'#define DATA_VAR "{self.prefix}"', f"#define DATA_VARS {len(vars_)}", f"#define ASSET_COUNT {len(blobs)}",
+ f"#define MAP_FIRST {names.index('MAP_' + gnames[0].upper())}",
+ f"#define PIC_FIRST {names.index('PIC_' + self.pics[0].name)}"]
+ if self.fonts:
+ h += [f"#define FONT_FIRST {names.index('FONT_' + self.fonts[0][0])}"]
+ h += [f"#define ASSET_{n} {names.index(n)}" for n, _ in self.blobs]
+ h += [f"#define PIC_{e.name} {i}" for i, e in enumerate(self.pics)] + [f"#define PIC_COUNT {len(self.pics)}"]
+ h += [f"#define FONT_{n} {i}" for i, (n, _) in enumerate(self.fonts)]
+ h += [f"#define GRP_{n.upper()} {i}" for i, n in enumerate(gnames)] + [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 self.defines]
+ h += ["/* each picture's group */",
+ "static const uint8_t pic_group[] = {" + ", ".join(str(gnames.index(e.group)) for e in self.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))
+ print(f"{len(vars_)} appvars, {sum(len(v) for v in vars_)} bytes")
+ sizes = {}
+ group_of = {"PIC_" + e.name: e.group for e in self.pics}
+ for name, d in blobs:
+ k = "pictures " + group_of[name] if name in group_of else name.split("_")[0]
+ sizes[k] = sizes.get(k, 0) + len(d)
+ for k, v in sorted(sizes.items(), key=lambda kv: -kv[1]):
+ print(f" {k}: {v}")
diff --git a/games/fnaf/ce/tools/cpic.py b/games/fnaf/ce/tools/cpic.py
deleted file mode 100644
index eb9e10cf..00000000
--- a/games/fnaf/ce/tools/cpic.py
+++ /dev/null
@@ -1,435 +0,0 @@
-#!/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/cvq.py b/games/fnaf/ce/tools/cvq.py
new file mode 100644
index 00000000..0b66fa21
--- /dev/null
+++ b/games/fnaf/ce/tools/cvq.py
@@ -0,0 +1,145 @@
+#!/usr/bin/env python3
+"""The CE pictures' codec: what engine/pic.c (and pic_ez80.s on the calculator) decodes. Made for the eZ80, where
+every byte read costs cycles: a picture is a grid of 2 x 2 blocks, each one of a group's 255 codewords (four
+palette indices), the grid's bytes compressed with zx0 (the CE toolchain's own decompressor). A group (the office,
+a camera, a jumpscare...) has its palette and its codewords.
+
+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): a block that hardly changed is 255, kept as the base has it.
+
+ picture: flags (1: a base, its id after the header; 2: blocks kept), blocks wide (u16), blocks tall (u8),
+ [the base's id (u16)], then the zx0 stream of blocks wide x blocks tall bytes (rows of blocks, 255: kept).
+ group (map): the codewords (four pages of 256 bytes: top left, top right, bottom left, bottom right; entry
+ 255 unused), then the palette (256 words), then the game's remap tables."""
+import math
+
+import numpy as np
+
+KEEP = 255
+K = 255
+
+
+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 lin(rgb):
+ """the space the codewords are fitted in: closer steps in the dark, where the eye sees them"""
+ return np.sqrt(np.clip(rgb, 0, 255) / 255)
+
+
+def blocks_of(a):
+ """(h, w, 3), h and w even -> (h/2 * w/2, 12): each block's 4 pixels (top left, top right, bottom left,
+ bottom right), rows of blocks"""
+ h, w = a.shape[:2]
+ return a.reshape(h // 2, 2, w // 2, 2, 3).transpose(0, 2, 1, 3, 4).reshape(-1, 12)
+
+
+def image_of(blocks, bw, bh):
+ return blocks.reshape(bh, bw, 2, 2, 3).transpose(0, 2, 1, 3, 4).reshape(bh * 2, bw * 2, 3)
+
+
+class Picture:
+ def __init__(self, rgb, base=None, keep=None):
+ h, w = rgb.shape[:2]
+ assert h % 2 == 0 and w % 2 == 0
+ self.rgb, self.bw, self.bh = rgb, w // 2, h // 2
+ self.base, self.keep = base, keep
+ self.idx = None # the blocks' codewords (KEEP: as the base has it)
+ self.shown = None # each block's codeword as decoded (the base's where kept)
+ self.src = None # the source each shown block came from (no drift along frames)
+
+
+class Group:
+ """a palette group: its pictures, its codewords and palette"""
+
+ def __init__(self, name, ncolors=224):
+ self.name, self.ncolors = name, ncolors
+ self.pics = []
+
+ def add(self, pic):
+ self.pics.append(pic)
+ return pic
+
+ def fit(self, seed=1):
+ from scipy.cluster.vq import kmeans2
+ from scipy.spatial import cKDTree
+ allb = np.concatenate([lin(blocks_of(p.rgb)) for p in self.pics])
+ rng = np.random.default_rng(seed)
+ sample = allb[rng.choice(len(allb), min(len(allb), 60000), replace=False)] if len(allb) > K else allb
+ k = min(K, len(np.unique(np.round(sample, 3), axis=0)))
+ cb, _ = kmeans2(sample, k, minit="++", seed=seed, iter=16)
+ # the palette, from the codewords' pixels (weighted by use), then the codewords in its colours
+ _, use = cKDTree(cb).query(sample)
+ weight = np.bincount(use, minlength=k).astype(np.float64) + 0.01
+ px = cb.reshape(-1, 3)
+ pw = np.repeat(weight, 4)
+ n = min(self.ncolors, len(np.unique(np.round(px, 3), axis=0)))
+ pick = rng.choice(len(px), 30000, p=pw / pw.sum())
+ pal, _ = kmeans2(px[pick], n, minit="++", seed=seed, iter=25)
+ pal = np.unique(to565((np.clip(pal, 0, 1) ** 2) * 255), axis=0)
+ _, pidx = cKDTree(lin(pal)).query(px)
+ self.pal = pal
+ self.cw = pidx.reshape(k, 4) # codeword -> 4 palette indices
+ self.cw_rgb = pal[self.cw].reshape(k, 12) # what they look like
+ self.tree = cKDTree(lin(self.cw_rgb))
+
+ def code(self, pic, keep_test):
+ """each block: its codeword (the nearest as shown), or KEEP where the base's block is near enough to it"""
+ b = blocks_of(pic.rgb)
+ _, idx = self.tree.query(lin(b))
+ shown, src = idx.copy(), b.copy()
+ if pic.base is not None:
+ base = pic.base
+ for i in range(len(idx)):
+ if keep_test(b[i], base.src[i]):
+ idx[i] = KEEP
+ shown[i] = base.shown[i]
+ src[i] = base.src[i]
+ pic.idx, pic.shown, pic.src = idx.astype(np.int64), shown, src
+
+ def rgb_of(self, pic):
+ """the picture as the calculator shows it"""
+ return image_of(self.cw_rgb[pic.shown].reshape(-1, 12), pic.bw, pic.bh)
+
+ def indices_of(self, pic):
+ """the picture's palette indices as decoded: (h, w)"""
+ q = self.cw[pic.shown].reshape(pic.bh, pic.bw, 2, 2)
+ return q.transpose(0, 2, 1, 3).reshape(pic.bh * 2, pic.bw * 2)
+
+ def blob(self, fixed):
+ """the map: the codewords (four pages), the palette (the group's colours, then the fixed ones at the end)"""
+ pages = np.zeros((4, 256), np.uint8)
+ pages[:, :len(self.cw)] = self.cw.T
+ words = [word1555(c) for c in self.pal]
+ words += [0] * (256 - len(fixed) - len(words))
+ words += [word1555(c) for c in fixed]
+ assert len(words) == 256, (self.name, len(words))
+ return pages.tobytes() + b"".join(w.to_bytes(2, "little") for w in words)
+
+
+def keep_within(ymax, ymean):
+ """a block is kept when its pixels are within ymax (each) and ymean (on average) of the base's source"""
+ def test(new, old):
+ d = np.abs(new - old)
+ return d.max() <= ymax and d.mean() <= ymean
+ return test
+
+
+def write(pic, pic_id_of_base, zx0):
+ """the picture's bytes"""
+ flags = (1 if pic.base is not None else 0) | (2 if (pic.idx == KEEP).any() else 0)
+ head = bytes([flags, pic.bw & 255, pic.bw >> 8, pic.bh])
+ if pic.base is not None:
+ head += bytes([pic_id_of_base & 255, pic_id_of_base >> 8])
+ return head + zx0(bytes(pic.idx.astype(np.uint8).tolist()))
diff --git a/games/fnaf/ce/tools/pack.py b/games/fnaf/ce/tools/pack.py
index 6d703284..41a9e4b0 100644
--- a/games/fnaf/ce/tools/pack.py
+++ b/games/fnaf/ce/tools/pack.py
@@ -1,266 +1,151 @@
#!/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.
+"""Five Nights at Freddy's on the TI-84 Plus CE: its pictures, fonts and tables -> data/*.bin, src/assets.h and
+tests/pics.crc (tools/cepack.py).
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."""
+The pictures are the NumWorks version's (../tools/pack.py makes them from the game's): the office and the cameras
+at 534 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."""
import os
-import struct
-import subprocess
import sys
-import tempfile
import numpy as np
-from PIL import Image, ImageFilter
+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
+sys.path.insert(0, os.path.join(os.path.dirname(CE), "tools"))
+import cepack 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, sharpen=False):
- """at half height (the calculator shows each row twice); the office a little sharper for it"""
- im = Image.fromarray(np.clip(a, 0, 255).astype(np.uint8))
- im = im.resize((im.width, (im.height + 1) // 2), Image.LANCZOS)
- if sharpen:
- im = im.filter(ImageFilter.UnsharpMask(radius=1.0, percent=50, threshold=1))
- return np.asarray(im).astype(np.float64)
-
-
-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
+P = C.Pack("FNAFD")
def office_pictures(N):
- g = group("office")
- office = halfv(sharpen=True, a=N["OFFICE"])
- base = pic("OFFICE", office, g, "office")
- define("OFFICE_W", office.shape[1])
+ g = P.group("office")
+ office = C.halfv(N["OFFICE"], True)
+ P.pic("OFFICE", office, g)
+ P.define("OFFICE_W", office.shape[1] + office.shape[1] % 2)
# 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(sharpen=True, a=N[lit]), halfv(sharpen=True, a=N[who])
+ a, b = C.halfv(N[lit], True), C.halfv(N[who], True)
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, 24), mb_box(b, office, 24)))]
- 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(sharpen=True, a=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(sharpen=True, a=N[n]), g, "office")
+ for k, (v1, v2) in enumerate(zip(C.box(a, office, 24), C.box(b, office, 24)))]
+ p = P.pic(f"LIGHT_{side}", C.pad8(a)[y0:y1, x0:x1], g)
+ P.pic(f"LIGHT_{side}_WHO", C.pad8(b)[y0:y1, x0:x1], g, base=p, keep=C.TIGHT)
+ for k, v in zip("XYWH", (x0, y0, x1 - x0, y1 - y0)):
+ P.define(f"LIGHT_{side}_{k}", v)
+ # the doors, the buttons lit, the fan and Golden Freddy, as the NumWorks version places them (rows halved)
+ for n in ["DOOR_L", "DOOR_R"] + [f"PANEL_{s}{k}" for s in "LR" for k in (1, 2, 3)] + \
+ ["FAN0", "FAN1", "FAN2", "OFFICE_GOLD"]:
+ P.pic(n, C.halfv(N[n], True), g)
# out of power: the dark office, and Freddy's face in the doorway (a patch)
- dark = halfv(sharpen=True, a=N["DARK"])
- pic("DARK", dark, g, "office")
- df = halfv(sharpen=True, a=N["DARK_FREDDY"])
- x0, y0, x1, y1 = mb_box(df, dark, 20)
- pic("DARK_FREDDY", pad8(df)[y0:y1, x0:x1], g, "office", x=x0, y=y0)
+ g = P.group("dark")
+ dark = C.halfv(N["DARK"], True)
+ P.pic("DARK", dark, g)
+ df = C.halfv(N["DARK_FREDDY"], True)
+ x0, y0, x1, y1 = C.box(df, dark, 20)
+ P.pic("DARK_FREDDY", C.pad8(df)[y0:y1, x0:x1], g)
for k, v in zip("XYWH", (x0, y0, x1 - x0, y1 - y0)):
- define(f"DARK_FREDDY_{k}", v)
+ P.define(f"DARK_FREDDY_{k}", v)
def camera_pictures(N):
for cam, states in NW.CAMS.items():
- g = group("cam" + cam.lower(), 4)
+ g = P.group("cam" + cam.lower())
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)
+ p = P.pic(name, C.halfv(N[name]), g, base=first, keep=C.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)
+ a = C.halfv(np.asarray(im.convert("RGB").resize((NW.OW, NW.OH), Image.LANCZOS)).astype(np.float64))
+ prev = P.pic(f"FOXYRUN{i}", a, g, base=prev, keep=C.ANIM)
+ P.define("FOXYRUN_N", 18)
if cam == "2B":
- pic("CAM2B_GOLD", halfv(N["CAM2B_GOLD"]), g, "cam", base=first, skip=TIGHT)
+ P.pic("CAM2B_GOLD", C.halfv(N["CAM2B_GOLD"]), g, base=first, keep=C.TIGHT)
-def anim(name, frames, grp, quality="scare", chain=True):
+def anim(name, frames, grp, chain=True):
"""160 x 120 frames, each coded over the one before (chain), or on its own (played both ways)"""
prev = None
for i, a in enumerate(frames):
- p = pic(f"{name}{i}", resize(a, 160, 120), grp, quality, base=prev, skip=ANIM if prev else None)
+ p = P.pic(f"{name}{i}", C.resize(a, 160, 120), grp, base=prev, keep=C.ANIM if prev else None)
prev = p if chain else None
- define(f"{name}_N", len(frames))
+ P.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"), chain=False)
- # 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")
+ anim(name, [N[f"{name}{i}"] for i in range(n)], P.group(name.lower()))
+ anim("FLIP", [N[f"FLIP{i}"] for i in range(11)], P.group("flip"), chain=False)
+ g = P.group("halluc") # the hallucinations (a frame now and then)
+ P.pic("HALLUC_GOLDEN", C.resize(N["GOLDEN"], 160, 120), g)
+ P.pic("HALLUC_ENDO", C.resize(N["TITLE3"], 160, 120), g)
def menu_pictures(N):
- g = group("title", 4)
- t0 = halfv(N["TITLE0"])
- pic("TITLE0", t0, g, "still")
+ g = P.group("title")
+ t0 = C.halfv(N["TITLE0"])
+ P.pic("TITLE0", t0, g)
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)
+ a = C.halfv(N[f"TITLE{k}"])
+ x0, y0, x1, y1 = C.box(a, t0, 12)
+ P.pic(f"TITLE{k}", C.pad8(a)[y0:y1, x0:x1], g)
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")
+ P.define(f"TITLE{k}_{c}", v)
+ for n in ("GAMEOVER", "GOLDEN"): # (in RAM, their static drawn over them each frame)
+ P.pic(n, C.halfv(N[n]), P.group(n.lower()))
+ for n in ("NEWSPAPER", "PAYCHECK", "OVERTIME", "PINKSLIP"):
+ P.pic(n, N[n], P.group(n.lower()))
+ g = P.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
+ P.pic(f"FACE_{n}", N[f"FACE_{n}"], g)
-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"""
+def main():
+ if len(sys.argv) != 2:
+ raise SystemExit(__doc__)
+ NW.REF = sys.argv[1]
+ NW.FONT_DIRS[:0] = C.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)
+ for n, f in zip(["HUD", "BIG", "TEXT", "CLOCK", "PIXEL", "HUGE"], [
+ 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)]):
+ P.font(n, *f)
+ P.blob("IMG_TITLE", C.img_blob(C.rgba_alpha(NW.hx("mainmenu/texts/FIVE_GAME_TITLE.png"), scale=0.5)))
+ P.blob("IMG_STAR", C.img_blob(C.rgba_alpha(NW.hx("mainmenu/STAR.png"), size=(22, 21))))
+ P.blob("CAMMAP", cam_map(NW.camera_map()))
+ for n, v in NW.DEFINES:
+ if n.startswith(("DOOR_", "PANEL_", "FAN_", "GOLD_", "MAP_")):
+ P.define(n, v)
+ P.write(CE)
+
+
+def cam_map(raw):
+ """the camera map: its walls as runs (size, count (u16), then y, x, length as bytes) and the 11 buttons'
+ centres (x, y bytes)"""
+ import struct
size = struct.unpack_from("<H", raw, 0)[0]
stride = (size + 7) // 8
runs = []
@@ -280,136 +165,5 @@ def map_blob(raw):
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]) + bytes([GROUPS[n].phases])))
- 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()