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.

Champion Island: compressed dialogue, 8 KB less RAM, sturdier saves

Mason Chenfaf35167468c
diff --git a/games/championisland/src/ci.h b/games/championisland/src/ci.h
index 649cb224..8645b7fe 100644
--- a/games/championisland/src/ci.h
+++ b/games/championisland/src/ci.h
@@ -30,7 +30,7 @@ static inline float rdf(const uint8_t *p) { uint32_t v = rd32(p); float f; memcp
#define NONE16 0xFFFF
const char *str(uint16_t id); /* identifiers and short strings */
-const char *text(uint16_t id); /* same table; kept apart for dialogue */
+int dtext(uint16_t id, char *buf, int size); /* a dialogue line (decompressed into buf), its length */
int str_find(const char *s); /* id of a string, or -1 */
uint16_t str_id(const char *s); /* id of a string that must exist */
diff --git a/games/championisland/src/data.h b/games/championisland/src/data.h
index b5203514..5b8dc4e9 100644
--- a/games/championisland/src/data.h
+++ b/games/championisland/src/data.h
@@ -2,7 +2,7 @@
#ifndef CI_DATA_H
#define CI_DATA_H
-enum { H_MAGIC, H_NSHEETS, H_PAL, H_NSPRITES, H_SPRITES, H_NBANKS, H_BANKS, H_NSTREAMS, H_STREAMS, H_NSYMS, H_SYMS, H_NMATS, H_MATS, H_NSTRINGS, H_STRTAB, H_STRDATA, H_NEXPRS, H_EXPRS, H_NDLG, H_DLG, H_NMSGS, H_MSGS, H_NVARS, H_PAYLOADS, H_TTAB, H_BANKSPR, H_WORLDS, H_RESERVED2, H_COUNT };
+enum { H_MAGIC, H_NSHEETS, H_PAL, H_NSPRITES, H_SPRITES, H_NBANKS, H_BANKS, H_NSTREAMS, H_STREAMS, H_NSYMS, H_SYMS, H_NMATS, H_MATS, H_NSTRINGS, H_STRTAB, H_STRDATA, H_NEXPRS, H_EXPRS, H_NDLG, H_DLG, H_NMSGS, H_MSGS, H_NVARS, H_PAYLOADS, H_TTAB, H_BANKSPR, H_WORLDS, H_DTEXT, H_STRSORT, H_RESERVED3, H_COUNT };
#define BANK_MAX 19296
#define SPRITE_COUNT 2389
#define BANK_COUNT 237
diff --git a/games/championisland/src/dialog.c b/games/championisland/src/dialog.c
index dec94038..d3505642 100644
--- a/games/championisland/src/dialog.c
+++ b/games/championisland/src/dialog.c
@@ -79,6 +79,7 @@ static bool single_next(const DNode *d) { /* bl: one option with no text */
}
static int text_lw;
+static char shown_buf[400];
static void show(uint16_t npc, uint16_t name) {
if (!dnode_find(npc, name, &cur)) { active = false; return; }
cur_npc = npc;
@@ -95,7 +96,8 @@ static void show(uint16_t npc, uint16_t name) {
text_lw = 217;
}
/* the text, broken into lines as the box shows it */
- const char *t = text(cur.text);
+ dtext(cur.text, shown_buf, sizeof shown_buf); /* shown_buf is free until the text types */
+ const char *t = shown_buf;
int k = 0;
const char *s = t;
int lw_px = (int)(text_lw * 4.0f / 3);
@@ -157,7 +159,7 @@ void dialog_start(uint16_t npc, uint16_t node) {
show(npc, node);
}
-static char shown_buf[400], opt_buf[3][96];
+static char opt_buf[3][96];
static void next(int opt) {
int len = (int)strlen(wrapped);
@@ -193,7 +195,8 @@ void dialog_tick(void) {
NodeId o = options[a];
nodes[o].y = m - 8 + 12 * a;
c = nodes[o].y;
- const char *ot = text(rd16(cur.opts + 4 * a + 2));
+ char ot[96];
+ dtext(rd16(cur.opts + 4 * a + 2), ot, sizeof ot);
if (node_visible(o)) {
if (opt_shown[a] < (int)strlen(ot)) {
opt_shown[a]++;
@@ -204,7 +207,8 @@ void dialog_tick(void) {
if (ttx) node_set_text(ttx, opt_buf[a]);
}
} else {
- if (a == 0 || opt_shown[a - 1] >= (int)strlen(text(rd16(cur.opts + 4 * (a - 1) + 2)))) {
+ char pt[96];
+ if (a == 0 || opt_shown[a - 1] >= dtext(rd16(cur.opts + 4 * (a - 1) + 2), pt, sizeof pt)) {
node_set_visible(o, true);
opt_shown[a] = 0;
NodeId ttx = node_child(o, "text");
@@ -215,7 +219,8 @@ void dialog_tick(void) {
}
m = c + 8;
int last = cur.nopts - 1;
- can_go = last >= 0 && last < no && node_visible(options[last]) && opt_shown[last] >= (int)strlen(text(rd16(cur.opts + 4 * last + 2)));
+ char lt[96];
+ can_go = last >= 0 && last < no && node_visible(options[last]) && opt_shown[last] >= dtext(rd16(cur.opts + 4 * last + 2), lt, sizeof lt);
}
}
/* the box grows to the text (qK: base) */
diff --git a/games/championisland/src/ent.c b/games/championisland/src/ent.c
index 94ac1924..16fca420 100644
--- a/games/championisland/src/ent.c
+++ b/games/championisland/src/ent.c
@@ -1,5 +1,6 @@
/* Entities and the doodle's shared systems (see ent.h). */
#include "ent.h"
+#include "spr.h"
#include <math.h>
#include <stdio.h>
#include "phys.h"
@@ -444,7 +445,9 @@ void sys_move_direct(void) {
/* insertion sort of the map's children by a key (stable, like Array.sort in V8 for small arrays) */
static void sort_children(NodeId m, float (*key)(NodeId)) {
NodeId sorted = 0;
- static float keys[NODE_MAX];
+ /* the keys live in the decoder's ring, idle between frames */
+ uint32_t cap;
+ float *keys = (float *)(void *)z_scratch(&cap);
NodeId c = nodes[m].first;
while (c) {
NodeId nx = nodes[c].next;
diff --git a/games/championisland/src/gfx.c b/games/championisland/src/gfx.c
index aad41124..03ce7018 100644
--- a/games/championisland/src/gfx.c
+++ b/games/championisland/src/gfx.c
@@ -20,9 +20,10 @@ typedef struct {
uint16_t color; /* rect/text colour, or the sprite of an affine item */
} Item;
static const void *item_ptr[MAX_AFF]; /* shape payload or text, by affine slot */
-typedef struct { float ia, ib, ic, id, itx, ity; Mat m; uint8_t align, scale; int16_t lw, lh; } Aff;
+typedef struct { Mat m; uint8_t align, scale; int16_t lw, lh; } Aff;
-static uint8_t stream_buf[SPRITE_W_MAX]; /* a decoded row (streams, affine sprites, scenery) */
+extern uint8_t spr_rowbuf[SPRITE_W_MAX];
+#define stream_buf spr_rowbuf /* a decoded row (streams, affine sprites, scenery) */
static Item items[MAX_ITEMS];
static Aff affs[MAX_AFF];
static int nitems, naffs;
@@ -70,8 +71,6 @@ static bool set_affine(Item *it, Mat m) {
float det = m.a * m.d - m.b * m.c;
if (fabsf(det) < 1e-6f || naffs >= MAX_AFF) return false;
Aff *f = &affs[naffs];
- f->ia = m.d / det; f->ib = -m.b / det; f->ic = -m.c / det; f->id = m.a / det;
- f->itx = -(f->ia * m.tx + f->ic * m.ty); f->ity = -(f->ib * m.tx + f->id * m.ty);
f->m = m;
it->ref = (uint16_t)naffs++;
return true;
@@ -580,7 +579,7 @@ static __attribute__((noinline)) void draw_sprite_item(const Item *it, int y0, i
const uint16_t *pal = pal565(s.sheet);
const uint8_t *al = palalpha(s.sheet);
int h = rd16(r + 2), w = rd16(r);
- static uint8_t al_opaque[256]; /* for DF_OPAQUE: 255 stays, the rest are skipped */
+ uint8_t al_opaque[256]; /* for DF_OPAQUE: 255 stays, the rest are skipped */
if (it->flags & DF_OPAQUE) {
for (int i = 0; i < 256; i++) al_opaque[i] = al[i] == 255 ? 255 : 0;
al = al_opaque;
@@ -599,13 +598,16 @@ static __attribute__((noinline)) void draw_affine_item(const Item *it, int y0, i
sprite_info(it->color, &s);
const uint16_t *pal = pal565(s.sheet);
const uint8_t *al = palalpha(s.sheet);
- const Aff *f = &affs[it->ref];
+ const Mat *m = &affs[it->ref].m;
+ float det = m->a * m->d - m->b * m->c;
+ float ia = m->d / det, ib = -m->b / det, ic = -m->c / det, id = m->a / det;
+ float itx = -(ia * m->tx + ic * m->ty), ity = -(ib * m->tx + id * m->ty);
int w = rd16(r), h = rd16(r + 2);
int x0 = it->x0 < 0 ? 0 : it->x0, x1 = it->x1 > VIEW_W ? VIEW_W : it->x1;
for (int y = y0; y < y1; y++) {
uint16_t *d = band + (y - by) * VIEW_W;
- float fu = f->ia * (x0 + 0.5f) + f->ic * (y + 0.5f) + f->itx, fv = f->ib * (x0 + 0.5f) + f->id * (y + 0.5f) + f->ity;
- for (int x = x0; x < x1; x++, fu += f->ia, fv += f->ib) {
+ float fu = ia * (x0 + 0.5f) + ic * (y + 0.5f) + itx, fv = ib * (x0 + 0.5f) + id * (y + 0.5f) + ity;
+ for (int x = x0; x < x1; x++, fu += ia, fv += ib) {
if (fu < 0 || fv < 0 || fu >= w || fv >= h) continue;
int v = (int)fv, u = (int)fu;
if (r != line_spr || v != line_v) line_decode(r, v, w);
diff --git a/games/championisland/src/res.c b/games/championisland/src/res.c
index dc5951e5..7ea3def9 100644
--- a/games/championisland/src/res.c
+++ b/games/championisland/src/res.c
@@ -5,12 +5,46 @@ const char *str(uint16_t id) {
if (id >= HDR(H_NSTRINGS)) return "";
return (const char *)ci_data + HDR(H_STRDATA) + rd32(ci_data + HDR(H_STRTAB) + 4u * id);
}
-const char *text(uint16_t id) { return str(id); }
+/* the dialogue's lines: byte-pair encoded (pack.py: bpe); a code byte stands
+ * for two bytes, each a code or a character */
+int dtext(uint16_t id, char *buf, int size) {
+ const uint8_t *t = ci_data + HDR(H_DTEXT);
+ if (!size) return 0;
+ buf[0] = 0;
+ if (id >= rd16(t)) return 0;
+ const uint8_t *codes = t + 4, *pairs = t + 36, *offs = t + 36 + 512;
+ unsigned n = rd16(t);
+ const uint8_t *data = offs + 4 * (n + 1);
+ const uint8_t *p = data + rd32(offs + 4 * id), *end = data + rd32(offs + 4 * id + 4);
+ uint8_t stack[32];
+ int len = 0;
+ while (p < end) {
+ int sp = 0;
+ stack[sp++] = *p++;
+ while (sp) {
+ uint8_t c = stack[--sp];
+ if (codes[c >> 3] & (1 << (c & 7))) {
+ if (sp + 2 > (int)sizeof stack) break;
+ stack[sp++] = pairs[2 * c + 1];
+ stack[sp++] = pairs[2 * c];
+ } else if (len < size - 1) buf[len++] = (char)c;
+ }
+ }
+ buf[len] = 0;
+ return len;
+}
+/* binary search in the ids sorted by their bytes */
int str_find(const char *s) {
- uint32_t n = HDR(H_NSTRINGS);
- for (uint32_t i = 0; i < n; i++)
- if (!strcmp(str((uint16_t)i), s)) return (int)i;
+ const uint8_t *sorted = ci_data + HDR(H_STRSORT);
+ int lo = 0, hi = (int)HDR(H_NSTRINGS) - 1;
+ while (lo <= hi) {
+ int mid = (lo + hi) / 2;
+ uint16_t id = rd16(sorted + 2 * mid);
+ int c = strcmp(str(id), s);
+ if (!c) return id;
+ if (c < 0) lo = mid + 1; else hi = mid - 1;
+ }
return -1;
}
diff --git a/games/championisland/src/spr.c b/games/championisland/src/spr.c
index 9052984f..0c887fed 100644
--- a/games/championisland/src/spr.c
+++ b/games/championisland/src/spr.c
@@ -11,7 +11,7 @@
/* ---------------------------------------------------------------- LZMA */
static CLzmaProb probs[1984 + 0x300];
-static uint8_t ring[LZMA_DICT];
+static uint8_t ring[LZMA_DICT] __attribute__((aligned(4)));
static CLzmaDec dec;
static const uint8_t *z_src;
static uint32_t z_in, z_len, z_out, z_total;
@@ -76,7 +76,8 @@ uint8_t *z_scratch(uint32_t *size) { *size = sizeof ring; return ring; }
/* ---------------------------------------------------------------- the cache */
#define ENTRIES 160
-typedef struct { uint16_t spr; uint16_t pad; uint32_t off, size, used; } Entry;
+/* off in 4-byte units, used: the tick it was last drawn (16 bits, compared as ages) */
+typedef struct { uint16_t spr, off4, size, used; } Entry;
static uint8_t *mem;
static uint32_t cache_bytes;
static Entry ent[ENTRIES];
@@ -112,22 +113,24 @@ static void compact(void) {
for (int i = 1; i < nent; i++) {
Entry e = ent[i];
int j = i - 1;
- while (j >= 0 && ent[j].off > e.off) { ent[j + 1] = ent[j]; j--; }
+ while (j >= 0 && ent[j].off4 > e.off4) { ent[j + 1] = ent[j]; j--; }
ent[j + 1] = e;
}
uint32_t at = 0;
for (int i = 0; i < nent; i++) {
- if (ent[i].off != at) memmove(mem + at, mem + ent[i].off, ent[i].size);
- ent[i].off = at;
+ if (4u * ent[i].off4 != at) memmove(mem + at, mem + 4u * ent[i].off4, ent[i].size);
+ ent[i].off4 = (uint16_t)(at / 4);
at += (ent[i].size + 3) & ~3u;
}
top = at;
}
+static inline uint16_t age(const Entry *e) { return (uint16_t)((uint16_t)tick - e->used); }
+
static void evict_one(void) {
int old = 0;
for (int i = 1; i < nent; i++)
- if (ent[i].used < ent[old].used) old = i;
+ if (age(&ent[i]) > age(&ent[old])) old = i;
ent[old] = ent[--nent];
}
@@ -141,8 +144,8 @@ static uint8_t *alloc(uint32_t n, bool force) {
while (nent && (live + n > cache_bytes || nent >= ENTRIES)) {
int old = 0;
for (int i = 1; i < nent; i++)
- if (ent[i].used < ent[old].used) old = i;
- if (!force && ent[old].used + 1 >= tick) return NULL;
+ if (age(&ent[i]) > age(&ent[old])) old = i;
+ if (!force && age(&ent[old]) <= 1) return NULL;
live -= (ent[old].size + 3) & ~3u;
evict_one();
}
@@ -207,7 +210,8 @@ static void rle_row(Rle *r, const uint8_t *px, int w, const uint8_t *alpha) {
}
/* Worst-case size of a sprite's runs. */
static uint32_t rle_bound(int w, int h) { return 4 + 2u * h + (uint32_t)h * (2 + 3 * ((uint32_t)w / 2 + 2) + (uint32_t)w); }
-static uint8_t rowbuf[SPRITE_W_MAX];
+uint8_t spr_rowbuf[SPRITE_W_MAX]; /* one decoded row (shared with gfx.c) */
+#define rowbuf spr_rowbuf
/* Adds sprite sp from the decoder, whose next bytes are its pixels. */
static bool add_from_decoder(uint16_t sp, const Sprite *s, bool force) {
@@ -227,7 +231,8 @@ static bool add_from_decoder(uint16_t sp, const Sprite *s, bool force) {
if (!r.ok) return false;
top += (used + 3) & ~3u;
/* sprites decoded on the way (bank neighbours) count as older than any in use */
- ent[nent++] = (Entry){sp, 0, (uint32_t)(p - mem), used, force || !tick ? tick : tick - 1};
+ if (used > 0xFFFF) { top -= (used + 3) & ~3u; return false; }
+ ent[nent++] = (Entry){sp, (uint16_t)((p - mem) / 4), (uint16_t)used, (uint16_t)(force ? tick : tick - 1)};
return true;
}
@@ -236,8 +241,8 @@ const uint8_t *spr_get(uint16_t sp) {
unsigned f = find(sp);
if (f) {
Entry *e = &ent[f - 1];
- e->used = tick;
- return mem + e->off;
+ e->used = (uint16_t)tick;
+ return mem + 4u * e->off4;
}
Sprite s;
sprite_info(sp, &s);
@@ -266,7 +271,7 @@ const uint8_t *spr_get(uint16_t sp) {
}
}
unsigned f2 = find(sp);
- return f2 ? mem + ent[f2 - 1].off : NULL;
+ return f2 ? mem + 4u * ent[f2 - 1].off4 : NULL;
}
/* the cached runs if the sprite is in the cache now (never decodes) */
@@ -274,8 +279,8 @@ const uint8_t *spr_peek(uint16_t sp) {
unsigned f = sp < SPRITE_COUNT && mem ? find(sp) : 0;
if (!f) return NULL;
Entry *e = &ent[f - 1];
- e->used = tick;
- return mem + e->off;
+ e->used = (uint16_t)tick;
+ return mem + 4u * e->off4;
}
const uint8_t *spr_stream(uint16_t sp) {
diff --git a/games/championisland/src/store.c b/games/championisland/src/store.c
index 4a5908eb..aeba6295 100644
--- a/games/championisland/src/store.c
+++ b/games/championisland/src/store.c
@@ -2,27 +2,47 @@
#include "store.h"
#define SAVE_NAME "champion.sav"
-#define MAX_KEYS 96
-#define KEY_LEN 26
-typedef struct { char key[KEY_LEN]; Value v; } Slot;
+/* a value's name is a string id of data.bin (pack.py adds every name the game
+ * saves); a name not there takes one of a few spare slots */
+#define MAX_KEYS 128
+#define SPARE 8
+#define SPARE_LEN 24
+typedef struct { uint16_t key; uint8_t type; bool b; uint16_t s, pad; float num; } Slot;
static Slot slots[MAX_KEYS];
+static char spare[SPARE][SPARE_LEN];
static int nslots;
static bool dirty;
+static const char *key_name(uint16_t k) { return k >= 0xFF00 ? spare[k - 0xFF00] : str(k); }
+
+static int key_of(const char *key, bool make) {
+ int id = str_find(key);
+ if (id >= 0) return id;
+ for (int i = 0; i < SPARE; i++) if (spare[i][0] && !strcmp(spare[i], key)) return 0xFF00 + i;
+ if (!make || strlen(key) >= SPARE_LEN) return -1;
+ for (int i = 0; i < SPARE; i++)
+ if (!spare[i][0]) { strcpy(spare[i], key); return 0xFF00 + i; }
+ return -1;
+}
+
static Slot *find(const char *key, bool make) {
+ int k = key_of(key, make);
+ if (k < 0) return NULL;
for (int i = 0; i < nslots; i++)
- if (!strcmp(slots[i].key, key)) return &slots[i];
- if (!make || nslots >= MAX_KEYS || strlen(key) >= KEY_LEN) return NULL;
+ if (slots[i].key == k) return &slots[i];
+ if (!make || nslots >= MAX_KEYS) return NULL;
Slot *s = &slots[nslots++];
memset(s, 0, sizeof *s);
- strcpy(s->key, key);
+ s->key = (uint16_t)k;
return s;
}
+static Value value_of_slot(const Slot *s) { return (Value){s->type, s->b, s->num, s->s}; }
+
Value store_get(const char *key) {
Slot *s = find(key, false);
Value none = {SV_NONE, false, 0, NONE16};
- return s ? s->v : none;
+ return s ? value_of_slot(s) : none;
}
bool store_bool(const char *key, bool def) {
@@ -65,8 +85,11 @@ static bool same(Value a, Value b) {
void store_set(const char *key, Value v) {
Slot *s = find(key, true);
if (!s) return;
- if (same(s->v, v)) return;
- s->v = v;
+ if (same(value_of_slot(s), v)) return;
+ s->type = v.type;
+ s->b = v.b;
+ s->num = v.num;
+ s->s = v.s;
dirty = true;
}
@@ -80,6 +103,7 @@ void store_set_str(const char *key, const char *s) {
void store_clear(void) {
nslots = 0;
+ memset(spare, 0, sizeof spare);
dirty = true;
}
@@ -96,19 +120,21 @@ bool store_save(void) {
n = 3;
for (int i = 0; i < nslots; i++) {
const Slot *s = &slots[i];
- if (s->v.type == SV_NONE) continue;
- size_t kl = strlen(s->key);
- const char *t = s->v.type == SV_STR ? str(s->v.s) : NULL;
+ if (s->type == SV_NONE) continue;
+ const char *kn = key_name(s->key);
+ size_t kl = strlen(kn);
+ if (kl > 255) continue;
+ const char *t = s->type == SV_STR ? str(s->s) : NULL;
size_t tl = t ? strlen(t) : 0;
if (tl > 255) tl = 255;
if (n + 2 + kl + 6 + tl > cap) break;
buf[n++] = (uint8_t)kl;
- memcpy(buf + n, s->key, kl);
+ memcpy(buf + n, kn, kl);
n += (uint32_t)kl;
- buf[n++] = s->v.type;
- if (s->v.type == SV_BOOL) buf[n++] = s->v.b;
- else if (s->v.type == SV_NUM) { memcpy(buf + n, &s->v.num, 4); n += 4; }
- else if (s->v.type == SV_STR) { buf[n++] = (uint8_t)tl; memcpy(buf + n, t, tl); n += (uint32_t)tl; }
+ buf[n++] = s->type;
+ if (s->type == SV_BOOL) buf[n++] = s->b;
+ else if (s->type == SV_NUM) { memcpy(buf + n, &s->num, 4); n += 4; }
+ else if (s->type == SV_STR) { buf[n++] = (uint8_t)tl; memcpy(buf + n, t, tl); n += (uint32_t)tl; }
}
if (!plat_save(SAVE_NAME, buf, n)) return false;
dirty = false;
@@ -119,12 +145,13 @@ void store_load(void) {
uint32_t len;
const uint8_t *d = plat_load(SAVE_NAME, &len);
nslots = 0;
+ memset(spare, 0, sizeof spare);
if (!d || len < 3 || memcmp(d, "CI1", 3)) return;
uint32_t i = 3;
while (i < len) {
- char key[KEY_LEN];
+ char key[64];
uint8_t kl = d[i++];
- if (kl >= KEY_LEN || i + kl + 1 > len) break;
+ if (kl >= sizeof key || i + kl + 1 > len) break;
memcpy(key, d + i, kl);
key[kl] = 0;
i += kl;
@@ -145,7 +172,7 @@ void store_load(void) {
v.s = (uint16_t)id;
} else if (t != SV_NULL) break;
Slot *s = find(key, true);
- if (s) s->v = v;
+ if (s) { s->type = v.type; s->b = v.b; s->num = v.num; s->s = v.s; }
}
dirty = false;
}
diff --git a/games/championisland/tools/pack.py b/games/championisland/tools/pack.py
index b42965ee..bd0293be 100644
--- a/games/championisland/tools/pack.py
+++ b/games/championisland/tools/pack.py
@@ -85,7 +85,7 @@ for _k in ('PRESS_SPACE', 'ARIA_BILLBOARD_DOCK', 'SPACEBAR', 'BACKSPACE', 'quest
MESSAGES[_k] = MESSAGES[_k].replace(a_, b_)
# ------------------------------------------------------------------ blob helpers
-HEADER_WORDS = 28
+HEADER_WORDS = 30
STATS = {}
@@ -1035,20 +1035,35 @@ def storage_value(v):
return struct.pack('<BI', 3, sid(v))
+# the dialogue's lines are kept apart, compressed (see dtext below): only the
+# dialogue box reads them, one at a time
+DTEXT = OrderedDict()
+DLG_KEYS = set()
+
+
+def dtext_id(t):
+ if t is None:
+ return 0xFFFF
+ return DTEXT.setdefault(t, len(DTEXT))
+
+
dialog_groups = []
for g in DIALOG:
nodes = []
for n in g:
# texts come from the translations (npc + node name), else the tree's own
base = n['V'] + n['nodeName']
+ DLG_KEYS.add(base)
n['text'] = MESSAGES.get(base, n.get('text'))
- opts = [(sid(o.get('next')), sid(MESSAGES.get(base + 'opt' + str(k), o.get('text')) if o.get('text') else None))
- for k, o in enumerate(n.get('U', []))]
+ opts = []
+ for k, o in enumerate(n.get('U', [])):
+ DLG_KEYS.add(base + 'opt' + str(k))
+ opts.append((sid(o.get('next')), dtext_id(MESSAGES.get(base + 'opt' + str(k), o.get('text')) if o.get('text') else None)))
tags = n.get('tags', {})
avatar = (tags.get('W') or [''])[0]
zd = tags.get('zd')
setv = (var_id(zd[0]), storage_value(zd[1])) if zd else None
- nodes.append((sid(n['nodeName']), sid(n['V']), sid(avatar), sid(n.get('text')), opts, setv))
+ nodes.append((sid(n['nodeName']), sid(n['V']), sid(avatar), dtext_id(n.get('text')), opts, setv))
dialog_groups.append(nodes)
dlg = bytearray()
@@ -1067,8 +1082,59 @@ for nodes in dialog_groups:
off_dlg = blob.add(bytes(dlg))
off_dlg_index = blob.add(b''.join(struct.pack('<I', off_dlg + o) for o in dlg_index))
+def bpe(texts):
+ """Byte-pair encoding: bytes the texts never use stand for frequent pairs."""
+ data = [list(t.encode('utf-8')) for t in texts]
+ used = set(b for t in data for b in t) | {0}
+ pairs = {}
+ for code in [b for b in range(1, 256) if b not in used]:
+ cnt = Counter()
+ for t in data:
+ cnt.update(zip(t, t[1:]))
+ if not cnt:
+ break
+ (a, b), n = cnt.most_common(1)[0]
+ if n < 3:
+ break
+ pairs[code] = (a, b)
+ for i, t in enumerate(data):
+ out, j = [], 0
+ while j < len(t):
+ if j + 1 < len(t) and t[j] == a and t[j + 1] == b:
+ out.append(code)
+ j += 2
+ else:
+ out.append(t[j])
+ j += 1
+ data[i] = out
+ return data, pairs
+
+
+_dt, _pairs = bpe(list(DTEXT))
+_tab = bytearray(512)
+for c, (a, b) in _pairs.items():
+ _tab[2 * c], _tab[2 * c + 1] = a, b
+_codes = bytearray(32)
+for c in _pairs:
+ _codes[c >> 3] |= 1 << (c & 7)
+_offs, _blob = [], bytearray()
+for t in _dt:
+ _offs.append(len(_blob))
+ _blob += bytes(t)
+_offs.append(len(_blob))
+off_dtext = blob.add(struct.pack('<H', len(_dt)) + b'\0\0' + bytes(_codes) + bytes(_tab) +
+ b''.join(struct.pack('<I', o) for o in _offs) + bytes(_blob), cat='dtext')
+print('dialogue texts: %d lines, %d KB -> %d KB with %d pairs' % (len(_dt), sum(len(t.encode()) for t in DTEXT) // 1024,
+ len(_blob) // 1024, len(_pairs)))
+
# messages (translatable UI texts), sorted by key for binary search
-msg_keys = sorted(MESSAGES)
+_named = set(re.findall(r'"([A-Za-z0-9_]+)"', KITSUNE))
+for _lib in LIB.values():
+ for _s in _lib['syms'].values():
+ for _c in (_s.get('T') or {}).values():
+ if isinstance(_c, dict):
+ _named.update(v for v in _c.values() if isinstance(v, str))
+msg_keys = sorted(k for k in MESSAGES if k not in DLG_KEYS or k in _named)
off_msgs = blob.add(b''.join(struct.pack('<HH', sid(k), sid(MESSAGES[k])) for k in msg_keys))
# compiled expressions
@@ -1281,12 +1347,29 @@ for w in WORLD:
(sum(len(r) for r in recs) + 2 * (nrefs + nwrefs + 2 * gw * gh + len(recs)) + 8 * len(walls)) // 1024))
off_worlds = blob.add(struct.pack('<I', len(world_offs)) + b''.join(struct.pack('<I', o) for o in world_offs))
+# the saved values' names (store.c keeps a name as its string id)
+_SPORTS = ['archery', 'climbing', 'marathon', 'pingpong', 'rugby', 'skate', 'swim']
+for _k in ['PLAYER_LOC', 'PLAYER_POS_X', 'PLAYER_POS_Y', 'PLAYER_TEAM', 'SUBMITTED_SCORES', 'TUTORIAL_DONE', 'TUTORIAL_BEGIN', 'FIRST_PLACE']:
+ sid(_k)
+for _r in re.findall(r'"?([a-z]+(?::[a-z0-9]+)?)"?: \{type: "(?:points|time)"', KITSUNE):
+ sid(_r + '_score')
+ sid(_r + '_rating')
+for _v in ['intro', 'outro'] + [x + 'intro' for x in _SPORTS] + [x + 'outro' for x in _SPORTS]:
+ sid(_v + '_VIDEO_SEEN')
+for _x in _SPORTS:
+ sid(_x + '_TUTORIAL_SEEN')
+for _v in VARS:
+ sid(_v)
+
# strings last (everything above may have added some)
str_offs, str_data = [], bytearray()
for s in strings:
str_offs.append(len(str_data))
str_data += s.encode('utf-8') + b'\0'
off_strtab = blob.add(b''.join(struct.pack('<I', o) for o in str_offs))
+# string ids in byte order, for str_find's binary search
+_sl = list(strings)
+off_strsort = blob.add(b''.join(struct.pack('<H', i) for i in sorted(range(len(_sl)), key=lambda i: _sl[i].encode('utf-8'))), 2)
off_strdata = blob.add(bytes(str_data), 1)
HEADER = [
@@ -1295,7 +1378,7 @@ HEADER = [
('nsyms', len(SYMS)), ('syms', off_syms), ('nmats', len(MATS)), ('mats', off_mats),
('nstrings', len(strings)), ('strtab', off_strtab), ('strdata', off_strdata),
('nexprs', len(EXPRS)), ('exprs', off_exprs), ('ndlg', len(dlg_index)), ('dlg', off_dlg_index),
- ('nmsgs', len(msg_keys)), ('msgs', off_msgs), ('nvars', len(VARS)), ('payloads', off_payloads), ('ttab', off_ttab), ('bankspr', off_bankspr), ('worlds', off_worlds), ('reserved2', 0)]
+ ('nmsgs', len(msg_keys)), ('msgs', off_msgs), ('nvars', len(VARS)), ('payloads', off_payloads), ('ttab', off_ttab), ('bankspr', off_bankspr), ('worlds', off_worlds), ('dtext', off_dtext), ('strsort', off_strsort), ('reserved3', 0)]
assert len(HEADER) == HEADER_WORDS
final = bytearray(blob.b)
final[:4 * HEADER_WORDS] = b''.join(struct.pack('<I', v) for _, v in HEADER)