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: scenery that stays, statues, doors, a steady camera

Mason Chenec4cafab7360
diff --git a/VERSION b/VERSION
index 347f5833..9df886c4 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.4.1
+1.4.2
diff --git a/games/championisland/src/data.bin b/games/championisland/src/data.bin
index 3368a7ab..0bf34909 100644
Binary files a/games/championisland/src/data.bin and b/games/championisland/src/data.bin differ
diff --git a/games/championisland/src/data.h b/games/championisland/src/data.h
index 18c67865..f7ea9cf5 100644
--- a/games/championisland/src/data.h
+++ b/games/championisland/src/data.h
@@ -4,9 +4,9 @@
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_TILES, H_COUNT };
#define BANK_MAX 19296
-#define SPRITE_COUNT 2389
+#define SPRITE_COUNT 2390
#define BANK_COUNT 237
-#define STREAM_MAX 435024
+#define STREAM_MAX 224640
#define SPRITE_W_MAX 752
#define LZMA_DICT 8192
enum { SYM_NONE, SYM_BITMAP, SYM_CLIP, SYM_SHAPE, SYM_CONT };
@@ -5140,6 +5140,7 @@ enum { V_PLAYER_TEAM, V_LEADERBOARD_FIRST, V_ARROWS, V_BIRTHDAY, V_NAME, V_CHASE
#define S_swim_eea 5109
#define S_swim_Gcb 5110
#define S_swim_Stage 5111
-#define SYM_COUNT 5112
+#define S_overworld_DLa_Jna 5112
+#define SYM_COUNT 5113
#endif
diff --git a/games/championisland/src/dialog.c b/games/championisland/src/dialog.c
index 7f5b5396..165e315e 100644
--- a/games/championisland/src/dialog.c
+++ b/games/championisland/src/dialog.c
@@ -98,12 +98,14 @@ static void show(uint16_t npc, uint16_t name) {
if (txt) nodes[txt].x = 10;
text_lw = 217;
}
- /* the text, broken into lines as the box shows it */
+ if (txt) node_set_text_width(txt, (int16_t)text_lw);
+ /* the text, broken into lines as the box shows it (getMetrics: the font's
+ * 10 px against the text's lineWidth, both in the text's own space) */
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);
+ int lw_px = text_lw;
while (*s && k < (int)sizeof wrapped - 2) {
/* reuse the font's wrapping: copy line by line */
const char *nl = strchr(s, '\n');
@@ -134,6 +136,12 @@ static void show(uint16_t npc, uint16_t name) {
wrapped[k] = 0;
shown = 0;
memset(opt_shown, 0, sizeof opt_shown);
+ NodeId base = node_child(box, "base");
+ if (base) {
+ float sx, sy, rot;
+ node_get_xform(base, &sx, &sy, &rot);
+ node_xform(base, sx, 1, rot); /* qK.scaleY = 1 */
+ }
if (txt) node_set_text(txt, "");
NodeId nx = child_with(C_dialogNext);
if (nx) node_set_visible(nx, false);
@@ -184,8 +192,10 @@ void dialog_tick(void) {
memcpy(shown_buf, wrapped, (size_t)shown);
shown_buf[shown] = 0;
if (txt) node_set_text(txt, shown_buf);
+ /* getMeasuredHeight: its lines at its lineHeight */
int lines = font_lines(shown_buf, 0);
- float m = fmaxf((lines * 11) * 0.75f + 20, 68);
+ float lh = txt && nodes[txt].ref != NONE16 ? rds16(payload(nodes[txt].ref) + 10) * .25f : 12;
+ float m = fmaxf(lines * lh + 20, 68);
NodeId nx = child_with(C_dialogNext), ptr = node_child(box, "pointer");
if (nx) node_set_visible(nx, true);
int no = find_options();
@@ -236,7 +246,7 @@ void dialog_tick(void) {
node_get_xform(base, &sx, &sy, &rot);
float bh = 68; /* base art height at scale 1 */
float target = m / bh;
- node_xform(base, sx, sy + (target - sy) * .2f, rot);
+ node_xform(base, sx, sy + (target - sy) * .8f, rot);
}
/* keys: OK goes on (or picks the focused option), arrows move the focus */
if (!done) {
diff --git a/games/championisland/src/game.c b/games/championisland/src/game.c
index fb0d3c2c..07eb5352 100644
--- a/games/championisland/src/game.c
+++ b/games/championisland/src/game.c
@@ -4,6 +4,7 @@
#include <stdio.h>
#include "font.h"
#include "gfx.h"
+#include "phys.h"
#include "spr.h"
Input in;
@@ -213,6 +214,10 @@ static void switch_scene(void) {
}
#endif
toast_style("", 0, -1, -1); /* Hq: a new scene takes the banner away */
+ /* and its own physics world (the doodle's cannonWorld is the scene's): the
+ * island's walls near the player, bodies of no entity, used to stay and fill
+ * it up after a few doors, leaving the player without a body */
+ phys_reset();
state_bytes = 0;
mem_layout(0, 0, 0, NULL);
memset(&in.pressed, 0, sizeof in.pressed);
diff --git a/games/championisland/src/gfx.c b/games/championisland/src/gfx.c
index 8f8fdd31..f110d893 100644
--- a/games/championisland/src/gfx.c
+++ b/games/championisland/src/gfx.c
@@ -50,7 +50,17 @@ void gfx_begin(void) {
void gfx_clear_color(uint16_t c) { clear_color = c; }
-static Item *add(void) { return nitems < MAX_ITEMS ? &items[nitems++] : NULL; }
+#ifdef HOST
+unsigned gfx_drops; /* tests: what the draw list had no room for (a frame missing some of its pictures) */
+#define DROPPED() (gfx_drops++)
+#else
+#define DROPPED() ((void)0)
+#endif
+static Item *add(void) {
+ if (nitems < MAX_ITEMS) return &items[nitems++];
+ DROPPED();
+ return NULL;
+}
static bool axis_aligned(Mat m) {
return fabsf(m.b) < 1e-4f && fabsf(m.c) < 1e-4f && fabsf(fabsf(m.a) - 1) < 1e-3f && fabsf(fabsf(m.d) - 1) < 1e-3f;
@@ -74,6 +84,7 @@ static bool on_view(int x0, int y0, int x1, int y1) { return x1 > 0 && y1 > view
static bool set_affine(Item *it, Mat m) {
float det = m.a * m.d - m.b * m.c;
+ if (naffs >= MAX_AFF) DROPPED();
if (fabsf(det) < 1e-6f || naffs >= MAX_AFF) return false;
Aff *f = &affs[naffs];
f->m = m;
@@ -108,6 +119,15 @@ void gfx_sprite_ex(uint16_t sp, Mat m, uint8_t alpha, bool opaque_only) {
}
}
+void gfx_sprite_rows(uint16_t sp, int x, int y, int h, uint8_t alpha) {
+ if (sp >= SPRITE_COUNT || !alpha || h <= 0) return;
+ Sprite s;
+ sprite_info(sp, &s);
+ if (!on_view(x, y, x + s.w, y + h)) return;
+ Item *it = add();
+ if (it) *it = (Item){DI_SPRITE, alpha, (uint8_t)(overlay ? DF_OVERLAY : 0), 0, (int16_t)x, (int16_t)y, (int16_t)(x + s.w), (int16_t)(y + h), sp, sp};
+}
+
void gfx_rect(int x, int y, int w, int h, uint16_t c, uint8_t alpha) {
if (!on_view(x, y, x + w, y + h) || !alpha) return;
Item *it = add();
@@ -154,8 +174,9 @@ void gfx_shape(const uint8_t *shape, Mat m, uint8_t alpha) {
}
if (!visible) return;
/* an overlay's backdrop over the whole stage (a menu's shade) covers the
- * whole view when it is taller than the stage */
- if (overlay && (view_top < 0 || view_bottom > VIEW_H) && lx <= 0 && ly <= 0 && hx >= VIEW_W && hy >= VIEW_H) {
+ * whole view when it is taller than the stage (to half a pixel: the skip
+ * menu's is a quarter of a stage pixel to the left) */
+ if (overlay && (view_top < 0 || view_bottom > VIEW_H) && lx <= .5f && ly <= .5f && hx >= VIEW_W - .5f && hy >= VIEW_H - .5f) {
float k = (float)(view_bottom - view_top) / VIEW_H;
m = (Mat){m.a, m.b * k, m.c, m.d * k, m.tx, m.ty * k + (float)view_top};
ly = ly * k + (float)view_top;
@@ -196,7 +217,10 @@ void gfx_text_k3(const char *s, Mat m, uint16_t color, uint8_t align, int16_t lw
affs[naffs].m = m;
affs[naffs].scale = (uint8_t)k3;
it->ref = (uint16_t)naffs++;
- } else nitems--;
+ } else {
+ DROPPED();
+ nitems--;
+ }
}
/* ---------------------------------------------------------------- the background layer */
@@ -477,17 +501,21 @@ void bg_draw(uint16_t sp, int x, int y, uint8_t flags, uint8_t alpha) {
}
void bg_blit_stream(uint16_t sp, int x, int y) {
+ if (!spr_stream(sp)) { bg_blit_sprite(sp, x, y, false, false); return; }
+ bg_blit_rows(sp, x, y, clip_y0, clip_y1);
+}
+
+void bg_blit_rows(uint16_t sp, int x, int y, int y0, int y1) {
Sprite s;
sprite_info(sp, &s);
- if (x >= clip_x1 || y >= clip_y1 || x + s.w <= clip_x0 || y + s.h <= clip_y0) return;
- const uint8_t *st = spr_stream(sp);
- if (!st) { bg_blit_sprite(sp, x, y, false, false); return; }
+ if (y0 < clip_y0) y0 = clip_y0;
+ if (y1 > clip_y1) y1 = clip_y1;
+ if (x >= clip_x1 || y >= y1 || x + s.w <= clip_x0 || y + s.h <= y0) return;
const uint8_t *alpha = palalpha(s.sheet);
- z_open(rd32(st + 2), rd32(st + 6), rd32(st + 10));
- int r0 = clip_y0 - y, r1 = clip_y1 - y;
+ int r0 = y0 - y, r1 = y1 - y;
if (r0 < 0) r0 = 0;
if (r1 > s.h) r1 = s.h;
- z_get(NULL, (uint32_t)r0 * s.w);
+ if (!spr_rows_at(sp, &s, r0)) return;
int c0 = clip_x0 - x, c1 = clip_x1 - x;
if (c0 < 0) c0 = 0;
if (c1 > s.w) c1 = s.w;
@@ -682,6 +710,9 @@ static void draw_stream(const Item *it, int y0, int y1, int by, unsigned ga) {
* cache holds, such as a menu over the island): decoded now, unless a stream
* holds the decoder or the menu comes first (then it comes next frame). */
static bool scene_later; /* a menu's frame too big for the cache: the scene's sprites that do not fit wait */
+/* something the band shows could not be drawn (no room in the cache) and was
+ * not known to be missing: the band is drawn again next frame */
+static bool band_short;
static const uint8_t *band_sprite(uint16_t sp, uint8_t flags) {
const uint8_t *r = spr_peek(sp);
if (r || streaming || (scene_later && !(flags & DF_OVERLAY))) return r;
@@ -692,12 +723,12 @@ static const uint8_t *band_sprite(uint16_t sp, uint8_t flags) {
static __attribute__((noinline)) void draw_sprite_item(const Item *it, int y0, int y1, int by, int rows, unsigned ga) {
const uint8_t *r = band_sprite(it->ref, it->flags);
- if (!r) return;
+ if (!r) { band_short |= !(it->flags & DF_MISSING); return; }
Sprite s;
sprite_info(it->ref, &s);
const uint16_t *pal = pal565(s.sheet);
const uint8_t *al = palalpha(s.sheet);
- int h = rd16(r + 2), w = rd16(r);
+ int h = rd16(r + 2), w = rd16(r), ih = it->y1 - it->y0;
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;
@@ -705,6 +736,7 @@ static __attribute__((noinline)) void draw_sprite_item(const Item *it, int y0, i
}
for (int y = y0; y < y1; y++) {
int row = y - it->y0;
+ if (ih != h) row = (2 * row + 1) * h / (2 * ih); /* stretched (gfx_sprite_rows): the row under the pixel's middle */
if (it->flags & DF_FLIPY) row = h - 1 - row;
draw_rle_row(r + rd16(r + 4 + 2 * row), it->x0, w, it->flags & DF_FLIPX, band + (y - by) * VIEW_W, pal, al, ga);
}
@@ -712,7 +744,7 @@ static __attribute__((noinline)) void draw_sprite_item(const Item *it, int y0, i
static __attribute__((noinline)) void draw_affine_item(const Item *it, int y0, int y1, int by, int rows, unsigned ga) {
const uint8_t *r = band_sprite(it->color, it->flags);
- if (!r) return;
+ if (!r) { band_short |= !(it->flags & DF_MISSING); return; }
Sprite s;
sprite_info(it->color, &s);
const uint16_t *pal = pal565(s.sheet);
@@ -823,6 +855,7 @@ static __attribute__((noinline)) void draw_shape_item(const Item *it, int y0, in
static __attribute__((noinline)) void draw_mask_item(const Item *it, int y0, int y1, int by) {
const uint8_t *m = spr_peek_mask(it->ref);
if (!m && !streaming) { m = spr_mask(it->ref); line_spr = NULL; }
+ if (!m) band_short |= !(it->flags & DF_MISSING);
if (!m || !bgmem) return;
const uint16_t *pal = pal565(bgsheet);
const uint8_t *al = palalpha(bgsheet);
@@ -903,7 +936,9 @@ static void draw_item(const Item *it, int by, int rows) {
unsigned ga = (it->alpha * 32u + 127) / 255;
switch (it->kind) {
case DI_STREAM:
- /* another big one this frame is drawn from the cache if it fits */
+ /* the streamed sprite's next item down: read again; another big one
+ * this frame is drawn from the cache if it fits */
+ if (streaming && it != streaming && it->ref == streaming->ref && it->y0 >= streaming->y1) stream_begin(it);
if (it == streaming) draw_stream(it, y0, y1, by, ga);
else draw_sprite_item(it, y0, y1, by, rows, ga);
break;
@@ -986,6 +1021,7 @@ static void release_done(int y) {
#ifdef HOST
int gfx_peak_items, gfx_peak_affs; /* tests: the most a frame used */
+int gfx_missing; /* tests: items the last frame left for the next (not cached) */
#endif
void gfx_end(void) {
#ifdef HOST
@@ -1076,6 +1112,15 @@ void gfx_end(void) {
#endif
}
}
+ /* and the masks of the scenery drawn again in front: without room for
+ * them, houses would be left out behind what stands in front of them */
+ memset(seen, 0, sizeof seen);
+ for (int i = 0; i < nitems; i++) {
+ uint16_t sp = items[i].ref;
+ if (items[i].kind != DI_MASK || !shown[i] || (seen[sp >> 3] & (1 << (sp & 7)))) continue;
+ seen[sp >> 3] |= (uint8_t)(1 << (sp & 7));
+ need += spr_mask_bytes(sp);
+ }
bool over = need + 1024 > spr_capacity();
/* more than the cache holds: the biggest sprite drawn as it decodes (top
* down, once) may leave room for the others; with a menu, the menu's
@@ -1109,16 +1154,26 @@ void gfx_end(void) {
continue;
Sprite t;
sprite_info(it->ref, &t);
- if (t.kind <= 1 && t.rle > bigsz) { big = i; bigsz = t.rle; }
+ if (t.kind <= 1 && t.rle > bigsz && it->y1 - it->y0 == t.h) { big = i; bigsz = t.rle; } /* (a stream is not stretched) */
+ }
+ /* a stream is read top down: a sprite drawn more than once is read
+ * again for each, one below the other (not in the same band) */
+ for (int i = 0; big >= 0 && i < nitems; i++) {
+ const Item *a = &items[i];
+ if (i == big || (a->kind == DI_SPRITE ? a->ref : a->kind == DI_AFFINE ? a->color : NONE16) != items[big].ref) continue;
+ if (a->kind != DI_SPRITE || (a->flags & (DF_FLIPY | DF_OPAQUE))) big = -1;
+ for (int j = 0; big >= 0 && j < nitems; j++)
+ if (j != i && items[j].kind == DI_SPRITE && items[j].ref == a->ref && a->y0 < items[j].y1 + BAND && items[j].y0 < a->y1 + BAND) big = -1;
}
- for (int i = 0; big >= 0 && i < nitems; i++) /* one item: a stream is read once */
- if (i != big && (items[i].kind == DI_SPRITE || items[i].kind == DI_AFFINE) &&
- (items[i].kind == DI_SPRITE ? items[i].ref : items[i].color) == items[big].ref)
- big = -1;
- uint32_t bs = big >= 0 && !stream_already && !spr_peek(items[big].ref) ? (bigsz + 3) & ~3u : 0;
+ uint32_t bs = big >= 0 && !stream_already ? (bigsz + 3) & ~3u : 0;
/* (a little too much: the last small ones come next frame) */
if (menu ? need_menu - bs <= spr_capacity() : bs && need - bs <= spr_capacity() + 1024) {
- if (bs) { items[big].kind = DI_STREAM; need -= bs; }
+ if (bs) {
+ for (int i = 0; i < nitems; i++)
+ if (items[i].kind == DI_SPRITE && items[i].ref == items[big].ref) items[i].kind = DI_STREAM;
+ spr_release(items[big].ref); /* cached: its room goes first */
+ need -= bs;
+ }
over = false;
scene_later = menu;
}
@@ -1142,7 +1197,7 @@ void gfx_end(void) {
for (int i = 0; i < nitems && !over; i++)
if (items[i].kind == DI_MASK && shown[i]) spr_mask(items[i].ref);
/* big sprites are cached too while everything fits; otherwise the first
- * one keeps the decoder while the bands go down */
+ * one keeps the decoder while the bands go down (from its topmost item) */
for (int i = 0; i < nitems; i++) {
Item *it = &items[i];
if (it->kind != DI_STREAM || !shown[i]) continue;
@@ -1152,18 +1207,22 @@ void gfx_end(void) {
if (!over && need + sz + 1024 <= spr_capacity() && spr_get(it->ref)) {
it->kind = DI_SPRITE;
need += sz;
- } else if (!streaming) stream_begin(it);
+ } else if (!streaming || (streaming->ref == it->ref && it->y0 < streaming->y0)) stream_begin(it);
}
/* with a stream holding the decoder nothing is decoded while the bands go
* down: what is not cached is drawn next frame */
for (int i = 0; i < nitems && (streaming || !over); i++) {
Item *it = &items[i];
if (!shown[i]) continue;
- if ((it->kind == DI_SPRITE || it->kind == DI_AFFINE || (it->kind == DI_STREAM && it != streaming)) &&
+ if ((it->kind == DI_SPRITE || it->kind == DI_AFFINE || (it->kind == DI_STREAM && (!streaming || it->ref != streaming->ref))) &&
!spr_peek(it->kind == DI_AFFINE ? it->color : it->ref))
it->flags |= DF_MISSING;
if (it->kind == DI_MASK && !spr_peek_mask(it->ref)) it->flags |= DF_MISSING;
}
+#ifdef HOST
+ gfx_missing = 0;
+ for (int i = 0; i < nitems; i++) gfx_missing += shown[i] && (items[i].flags & DF_MISSING);
+#endif
for (int by = view_top; by < view_bottom; by += BAND) {
int rows = view_bottom - by < BAND ? view_bottom - by : BAND;
if (!dirty[(by - view_top) / BAND]) { if (over) release_done(by + rows); continue; }
@@ -1172,15 +1231,19 @@ void gfx_end(void) {
const Item *it = &items[i];
if (it->y1 > by && it->y0 < by + rows && it->kind != DI_HIDDEN) h = item_hash(h, it, true);
}
- band_hash[(by - view_top) / BAND] = h;
#ifdef HOST
if (getenv("CI_BANDS")) fprintf(stderr, "band %d\n", by);
#endif
band_bg(by, rows);
+ band_short = false;
for (int i = 0; i < nitems; i++) {
const Item *it = &items[i];
if (it->y1 > by && it->y0 < by + rows) draw_item(it, by, rows);
}
+ band_hash[(by - view_top) / BAND] = band_short ? ~h : h;
+#ifdef HOST
+ gfx_missing += band_short;
+#endif
plat_push(0, VIEW_Y + by, VIEW_W, rows, band);
if (over) release_done(by + rows);
}
diff --git a/games/championisland/src/gfx.h b/games/championisland/src/gfx.h
index c7c19bb2..ec577943 100644
--- a/games/championisland/src/gfx.h
+++ b/games/championisland/src/gfx.h
@@ -14,6 +14,9 @@ static const Mat MAT_ID = {1, 0, 0, 1, 0, 0};
void gfx_begin(void); /* new draw list */
void gfx_sprite(uint16_t sprite, Mat m, uint8_t alpha); /* a sprite placed by m */
void gfx_sprite_ex(uint16_t sprite, Mat m, uint8_t alpha, bool opaque_only); /* opaque_only: skips see-through pixels */
+/* a sprite at (x, y) stretched to h rows, each the nearest of its own (the
+ * ending's glow, the doodle's whole screen, over the island's taller view) */
+void gfx_sprite_rows(uint16_t sprite, int x, int y, int h, uint8_t alpha);
void gfx_shape(const uint8_t *shape, Mat m, uint8_t alpha); /* filled polygons (payload) */
void gfx_rect(int x, int y, int w, int h, uint16_t c, uint8_t alpha);
/* one small image at n places (pos: x, y pairs, moved by ox, oy): 4-bit pixels,
@@ -54,6 +57,7 @@ void bg_water4(const uint8_t *tile, int w, int h, const uint16_t *colours); /*
void bg_redraw_water(void); /* the water tile's pixels changed */
int bg_clear_index(void); /* the palette's clear index, -1 if none */
void bg_blit_stream(uint16_t sprite, int x, int y);
+void bg_blit_rows(uint16_t sprite, int x, int y, int y0, int y1); /* only its world rows y0 to y1 (a stream) */
void bg_fill(int x, int y, int w, int h, uint8_t index);
void bg_redraw(uint16_t sprite, int x, int y, uint8_t flags); /* the layer again where the sprite at world x, y is opaque */
uint8_t *bg_layer(int *w, int *h);
diff --git a/games/championisland/src/menus.c b/games/championisland/src/menus.c
index ae2333a3..7eb6fefc 100644
--- a/games/championisland/src/menus.c
+++ b/games/championisland/src/menus.c
@@ -27,6 +27,13 @@ void menus_init(void) {
depth = 0;
}
+/* Er over a menu: the frames its saved values pick (world.c) */
+static void storage_sprites(NodeId n) {
+ extern void storage_sprite(NodeId n);
+ storage_sprite(n);
+ for (NodeId c = nodes[n].first; c; c = nodes[c].next) storage_sprites(c);
+}
+
/* the menus clip at one menu's frame (only that menu's nodes exist) */
static void show_label(const char *label) {
if (root) node_free(root);
@@ -35,6 +42,7 @@ static void show_label(const char *label) {
root = node_new_sym_frame(S_menus_Obb, clip_label(&c, label));
node_update(root);
ent_register_tree(root);
+ storage_sprites(root);
}
static NodeId current_menu(void) {
@@ -98,6 +106,21 @@ static const char *tutorial_of(const char *name) {
return l;
}
+/* Lq: each menu keeps its focus as long as the app runs (the doodle's menus
+ * live as long as the page): its button's event id, by the menu's id */
+static uint16_t kept[16][2];
+static uint16_t *kept_of(NodeId m, bool make) {
+ uint16_t id = m ? comp_str(nodes[m].T, C_menu, F_id) : NONE16;
+ if (id == NONE16) return NULL;
+ for (int i = 0; i < 16; i++) if (kept[i][0] == id + 1) return &kept[i][1];
+ for (int i = 0; make && i < 16; i++) if (!kept[i][0]) { kept[i][0] = id + 1; kept[i][1] = NONE16; return &kept[i][1]; }
+ return NULL;
+}
+static void keep_focus(NodeId m) {
+ uint16_t *k = kept_of(m, true);
+ if (k && focus) *k = comp_str(nodes[focus].T, C_button, F_eventId);
+}
+
static void setup(NodeId m) {
const char *id = menu_id(m);
focus = 0;
@@ -161,6 +184,9 @@ static void setup(NodeId m) {
hide_button(m, "soundOff");
hide_button(m, "textRetro");
hide_button(m, "textModern");
+ NodeId l;
+ if ((l = node_find(m, "soundLabel"))) node_set_visible(l, false); /* and their rows' names */
+ if ((l = node_find(m, "textStyleLabel"))) node_set_visible(l, false);
} else if (!strcmp(id, "newgame")) {
set_text(m, "title", msg("NEW_GAME"));
set_text(m, "prompt", msg("NEW_GAME_PROMPT"));
@@ -170,29 +196,46 @@ static void setup(NodeId m) {
set_text(m, "title", msg("LEADERBOARD"));
set_label(button(m, "back"), "CLOSE");
/* lr: the teams' scores come from the doodle's server; on the calculator
- * there is only the player's own team and the stars they won for it */
- NodeId l = node_find(m, "loading");
- if (l) node_set_visible(l, false);
- for (int i = 1; i < 4; i++) {
- char k[16];
- snprintf(k, sizeof k, "teamName%d", i);
- if ((l = node_find(m, k))) node_set_visible(l, false);
- snprintf(k, sizeof k, "teamScore%d", i);
- if ((l = node_find(m, k))) node_set_visible(l, false);
- }
+ * there is only the player's own team and the stars they won for it, in
+ * its row (teamName + TeamId: the rows' icons are blue, red, green, yellow) */
+ static const char *const rows[4] = {"BLUE", "RED", "GREEN", "YELLOW"};
static char team[16], score[12];
const char *t = store_str("PLAYER_TEAM");
snprintf(team, sizeof team, "%s", t && t[0] ? t : "NO_TEAM");
for (char *c = team; *c; c++) if (*c >= 'a' && *c <= 'z') *c -= 32;
+ int row = 0;
+ for (int i = 0; i < 4; i++) if (!strcmp(team, rows[i])) row = i;
+ NodeId l = node_find(m, "loading");
+ if (l) node_set_visible(l, false);
snprintf(score, sizeof score, "%d", (int)store_num("SUBMITTED_SCORES", 0));
- if ((l = node_find(m, "teamName0"))) {
- node_set_text(l, msg(team));
- node_set_text_color(l, team_color(team));
+ for (int i = 0; i < 4; i++) {
+ char k[16];
+ snprintf(k, sizeof k, "teamName%d", i);
+ if ((l = node_find(m, k))) {
+ node_set_visible(l, i == row);
+ node_set_text(l, msg(team));
+ node_set_text_color(l, team_color(team));
+ }
+ snprintf(k, sizeof k, "teamScore%d", i);
+ if ((l = node_find(m, k))) {
+ node_set_visible(l, i == row);
+ node_set_text(l, score);
+ }
}
- if ((l = node_find(m, "teamScore0"))) node_set_text(l, score);
} else if (!strcmp(id, "controls")) {
set_label(button(m, "back"), "BACK");
+ /* gs: each action's keys, the calculator's (its arrows, OK and Back, and
+ * the keys that do the same) in place of a keyboard's and a gamepad's */
+ static const char *const keys[12][2] = {
+ {"kbUp", "ArrowUp"}, {"kbDown", "ArrowDown"}, {"kbLeft", "ArrowLeft"}, {"kbRight", "ArrowRight"},
+ {"kbAction", "OK"}, {"kbCancel", "Back"}, {"gpUp", "8"}, {"gpDown", "2"}, {"gpLeft", "4"}, {"gpRight", "6"},
+ {"gpAction", "EXE"}, {"gpCancel", "Backspace"}};
+ for (int i = 0; i < 12; i++) set_text(node_find(m, keys[i][0]), "text", keys[i][1]);
+ set_text(node_find(m, "confirmButton"), "label", msg("CONFIRM"));
+ set_text(node_find(m, "defaultsButton"), "label", msg("DEFAULTS"));
}
+ uint16_t *k = kept_of(m, false);
+ if (k && *k != NONE16) focus = button(m, str(*k));
}
bool menus_open(const char *label) {
@@ -301,6 +344,7 @@ static void menu_nav(NodeId m) {
bool ok = false;
for (int i = 0; i < n; i++) if (list[i] == focus) ok = true;
if (!ok) focus = n ? list[0] : 0;
+ keep_focus(m);
for (int i = 0; i < n; i++) node_goto(list[i], list[i] == focus ? "focus" : "idle", 0, false);
if (in.pressed[A_ACTION] && focus) {
input_consume(A_ACTION);
@@ -335,6 +379,7 @@ static void menu_nav(NodeId m) {
}
if (best) focus = best;
}
+ keep_focus(m);
}
/* ---------------------------------------------------------------- results (Xo) */
diff --git a/games/championisland/src/node.c b/games/championisland/src/node.c
index a78829ee..dcdeca7e 100644
--- a/games/championisland/src/node.c
+++ b/games/championisland/src/node.c
@@ -15,7 +15,7 @@ static Xf xfs[XF_MAX];
/* texts set by code */
#define TX_MAX 48
-typedef struct { NodeId n; const char *s; int32_t color; } Tx; /* color: RGB565, -1 as designed */
+typedef struct { NodeId n; int16_t lw; const char *s; int32_t color; } Tx; /* lw: lineWidth set by code (0: as designed); color: RGB565, -1 as designed */
static Tx txs[TX_MAX];
/* event listeners */
@@ -705,7 +705,7 @@ static bool shape_bounds(const uint8_t *sh, float *x, float *y, float *w, float
/* CreateJS getBounds: a bitmap's rectangle, a shape's extent, and for a
* clip the union of its visible children's bounds at its current frame */
-typedef struct { float lx, ly, hx, hy; bool any; } Acc;
+typedef struct { float lx, ly, hx, hy; bool any, texts; } Acc; /* texts: count them too */
static void acc_rect(Acc *a, Mat m, float x, float y, float w, float h) {
float xs[4] = {x, x + w, x, x + w}, ys[4] = {y, y, y + h, y + h};
@@ -724,6 +724,17 @@ static Mat key_mat(const Key *k) {
return (Mat){a, b, c, d, k->x - (rx * a + ry * c), k->y - (rx * b + ry * d)};
}
+/* a text's box as CreateJS measures it: its lines in the font at its size
+ * (the font is 10 px), from its anchor (alignment, baseline) */
+static void text_acc(const uint8_t *t, Mat m, Acc *a) {
+ float k = t[2] * 0.1f;
+ int lw = rds16(t + 8) / 4, w, h;
+ if (!k) return;
+ font_measure(str(rd16(t)), lw > 0 ? (int)(lw / k) : 0, 0, &w, &h);
+ float fw = w * k, fh = h * k;
+ acc_rect(a, m, t[6] == 1 ? -fw / 2 : t[6] == 2 ? -fw : 0, -(t[7] == 1 ? 6 : t[7] >= 2 ? 10 : 1) * k, fw, fh);
+}
+
static void sym_acc(uint16_t sym, unsigned frame, Mat m, Acc *a, int depth) {
if (sym >= SYM_COUNT || depth > 12) return;
SymInfo si;
@@ -747,6 +758,7 @@ static void sym_acc(uint16_t sym, unsigned frame, Mat m, Acc *a, int depth) {
if (idx == NONE16 || (k.flags & (K_ABSENT | K_HIDDEN))) continue;
Mat km = mat_mul(m, key_mat(&k));
if (k.kind == CK_SHAPE) { if (shape_bounds(payload(k.ref), &x, &y, &w, &h)) acc_rect(a, km, x, y, w, h); }
+ else if (k.kind == CK_TEXT) { if (a->texts) text_acc(payload(k.ref), km, a); }
else if (k.kind == CK_SYM) {
unsigned f = k.mode == MODE_SYNCHED ? k.sp + frame - k.start : k.mode == MODE_SINGLE ? k.sp : 0;
sym_acc(k.ref, f, km, a, depth + 1);
@@ -800,7 +812,7 @@ static void node_acc(NodeId id, Mat m, Acc *a, int depth) {
}
bool node_bounds(NodeId n, float *x, float *y, float *w, float *h) {
- Acc a = {0, 0, 0, 0, false};
+ Acc a = {0, 0, 0, 0, false, false};
node_acc(n, MAT_ID, &a, 0);
if (!a.any) {
/* nothing to show: Animate's nominal bounds, if any */
@@ -966,6 +978,41 @@ void clip_each_slot(uint16_t sym, unsigned frame, bool (*fn)(unsigned slot, cons
}
}
+/* where a timeline child shows (in the clip's space): a clip's nominal
+ * bounds are not in the data (the doodle's compiler renamed nominalBounds),
+ * so its bounds are what its first frame shows (CreateJS getBounds) */
+static bool child_bounds(const Key *k, float *x, float *y, float *w, float *h) {
+ if (!key_bounds(k, x, y, w, h)) return false;
+ if (*w || *h) return true;
+ Acc a = {0, 0, 0, 0, false, true};
+ sym_acc(k->ref, k->mode != MODE_INDEPENDENT ? k->sp : 0, key_mat(k), &a, 0);
+ if (a.any) { *x = a.lx; *y = a.ly; *w = a.hx - a.lx; *h = a.hy - a.ly; }
+ return true;
+}
+
+/* how far a lazy clip's children reach out of their origins (left, up,
+ * right, down), measured once: only those whose origin is that near the
+ * rectangle need measuring */
+static uint16_t reach_sym = NONE16, reach_frame;
+static float reach[4];
+static void measure_reach(NodeId n, const Clip *c) {
+ reach_sym = nodes[n].sym;
+ reach_frame = nodes[n].frame;
+ memset(reach, 0, sizeof reach);
+ const uint8_t *q = c->slots;
+ for (unsigned s = 0; s < c->nslots; s++) {
+ Key k;
+ uint16_t idx;
+ float bx, by, bw, bh;
+ q = slot_key(q, nodes[n].frame, &k, &idx);
+ if (idx == NONE16 || (k.flags & K_ABSENT) || !child_bounds(&k, &bx, &by, &bw, &bh)) continue;
+ reach[0] = fmaxf(reach[0], k.x - bx);
+ reach[1] = fmaxf(reach[1], k.y - by);
+ reach[2] = fmaxf(reach[2], bx + bw - k.x);
+ reach[3] = fmaxf(reach[3], by + bh - k.y);
+ }
+}
+
void node_stream(NodeId n, float x0, float y0, float x1, float y1) {
Clip c;
if (!(nodes[n].flags2 & NF2_LAZY) || !clip_get(nodes[n].sym, &c)) return;
@@ -989,8 +1036,15 @@ void node_stream(NodeId n, float x0, float y0, float x1, float y1) {
while (hi < nh && nodes[have[hi]].slot < s) hi++;
NodeId got = hi < nh && nodes[have[hi]].slot == s ? have[hi] : 0;
bool present = idx != NONE16 && !(k.flags & K_ABSENT);
+ /* near: its box (a clip's: its origin) in the rectangle, else what it shows */
float bx, by, bw, bh;
- bool near = present && (needs_node(&k) || map_kids) && key_bounds(&k, &bx, &by, &bw, &bh) && bx < x1 && by < y1 && bx + bw > x0 && by + bh > y0;
+ bool near = false;
+ if (present && (needs_node(&k) || map_kids) && key_bounds(&k, &bx, &by, &bw, &bh)) {
+ near = bx < x1 && by < y1 && bx + bw > x0 && by + bh > y0;
+ if (!near && (reach_sym != nodes[n].sym || reach_frame != nodes[n].frame)) measure_reach(n, &c);
+ if (!near && k.x - reach[0] < x1 && k.y - reach[1] < y1 && k.x + reach[2] > x0 && k.y + reach[3] > y0)
+ near = child_bounds(&k, &bx, &by, &bw, &bh) && bx < x1 && by < y1 && bx + bw > x0 && by + bh > y0;
+ }
if (near && !got) {
if (nh >= HAVE_MAX) continue;
NodeId nc = new_child_for(&k);
@@ -1045,6 +1099,7 @@ static void draw_virtual(uint16_t sym, unsigned frame, Mat m, uint8_t alpha, int
static const char *text_of(NodeId n);
static int32_t text_color(NodeId n);
+static int text_width(NodeId n);
/* a text node's text s (NULL: its own), placed by m (the view's), as the
* doodle's canvas sets it: the size on screen picks the font's scale (in
@@ -1058,8 +1113,9 @@ void node_text_draw(NodeId id, Mat m, const char *s, int32_t color, uint8_t alph
if (!s) s = text_of(id);
float scale = sqrtf(m.a * m.a + m.b * m.b), px = t[2] * scale;
int k3 = px >= 11.5f ? (int)(px * 0.3f + .5f) : 3;
- int lw = (int)(rds16(t + 8) * 0.25f * scale), lh = (int)(rds16(t + 10) * 0.25f * scale);
- if (lh > 0 && lh < FONT_LINE * k3 / 3) lh = FONT_LINE * k3 / 3;
+ int tw = text_width(id);
+ int lw = (int)((tw ? tw : rds16(t + 8) * 0.25f) * scale), lh = (int)(rds16(t + 10) * 0.25f * scale + .5f);
+ if (lh > 0 && lh < FONT_HEIGHT * k3 / 3) lh = FONT_HEIGHT * k3 / 3; /* the lineHeight, at least a glyph (the dialogue's 11 px: its options follow its lines) */
m.ty += (t[7] == 1 ? -6 : t[7] >= 2 ? -10 : -1) * k3 / 3; /* top, middle, alphabetic */
gfx_text_k3(s, m, color >= 0 ? (uint16_t)color : rgb565(t[3], t[4], t[5]), t[6], (int16_t)lw, (int16_t)lh, alpha, k3);
}
@@ -1139,12 +1195,22 @@ static const char *text_of(NodeId n) {
void node_set_text(NodeId n, const char *s) {
for (int i = 0; i < TX_MAX; i++) if (txs[i].n == n) { txs[i].s = s; return; }
- for (int i = 0; i < TX_MAX; i++) if (!txs[i].n) { txs[i] = (Tx){n, s, -1}; return; }
+ for (int i = 0; i < TX_MAX; i++) if (!txs[i].n) { txs[i] = (Tx){n, 0, s, -1}; return; }
}
void node_set_text_color(NodeId n, uint16_t c) {
for (int i = 0; i < TX_MAX; i++) if (txs[i].n == n) { txs[i].color = c; return; }
- for (int i = 0; i < TX_MAX; i++) if (!txs[i].n) { txs[i] = (Tx){n, NULL, c}; return; }
+ for (int i = 0; i < TX_MAX; i++) if (!txs[i].n) { txs[i] = (Tx){n, 0, NULL, c}; return; }
+}
+
+void node_set_text_width(NodeId n, int16_t lw) {
+ for (int i = 0; i < TX_MAX; i++) if (txs[i].n == n) { txs[i].lw = lw; return; }
+ for (int i = 0; i < TX_MAX; i++) if (!txs[i].n) { txs[i] = (Tx){n, lw, NULL, -1}; return; }
+}
+
+static int text_width(NodeId n) {
+ for (int i = 0; i < TX_MAX; i++) if (txs[i].n == n) return txs[i].lw;
+ return 0;
}
static int32_t text_color(NodeId n) {
diff --git a/games/championisland/src/node.h b/games/championisland/src/node.h
index f064734f..f56c51fb 100644
--- a/games/championisland/src/node.h
+++ b/games/championisland/src/node.h
@@ -138,5 +138,6 @@ void node_emit(NodeId n, uint16_t event);
/* text nodes */
void node_set_text(NodeId n, const char *s); /* string kept by pointer */
void node_set_text_color(NodeId n, uint16_t rgb565);
+void node_set_text_width(NodeId n, int16_t lw); /* lineWidth set by code, in its own px (0: as designed) */
const char *node_text(NodeId n);
#endif
diff --git a/games/championisland/src/sport_climbing.c b/games/championisland/src/sport_climbing.c
index 57de4d3e..993346df 100644
--- a/games/championisland/src/sport_climbing.c
+++ b/games/championisland/src/sport_climbing.c
@@ -69,15 +69,10 @@ typedef struct {
/* parallax (Aq) */
bool par_init;
float par_dx, par_dy, par_hx, par_hy, par_fx, par_fy;
- /* the sky (Iba's copies of one big picture, drawn by code) */
+ /* the sky (Iba's copies of one big picture, in the background layer) */
uint16_t sky_sprite;
int nsky;
- float sky_x[SKY_MAX], sky_y[SKY_MAX];
- float sky_ref; /* the copy whose rows the forest texture matches */
- bool tex, tex_on; /* the forest texture is ready, shown */
- uint8_t *tex_mem;
- uint8_t tex_sheet;
- int tex_cx, tex_cy;
+ int16_t sky_x[SKY_MAX], sky_y[SKY_MAX];
Countdown cd;
bool counting;
/* the end (zq) */
@@ -413,19 +408,15 @@ static void end(void) {
/* ---------------------------------------------------------------- the sky
* Iba (the parallax backdrop) holds copies of one 432 x 1007 picture (sky,
- * sea, then forest), stacked with overlaps, the last one on top. The picture
- * is a single LZMA stream: drawing a row decodes every row above it, and the
- * forest's rows are dear (some 0.13 ms each on the calculator). So the sky is
- * drawn here: the copy that shows, as a sprite, while its rows are cheap (the
- * sky and the sea); lower down, a texture of the picture's forest decoded
- * once (the background layer's "water"), under the sea's colour where the
- * sea still shows. */
-#define TEX_W 384 /* the picture's columns 32..415: all the parallax ever shows */
-#define TEX_X0 32
-#define TEX_H 128
-#define TEX_ROW0 879 /* its rows 879..1006 */
-#define SKY_CHEAP 400 /* the deepest row the sprite may be drawn down to */
-#define SEA_END 520 /* the sea's last row, about */
+ * sea, then forest), stacked with overlaps, the last one on top. It shows
+ * through the cliff at every height, the forest too (at the cliff's sides,
+ * and through its holes in the hard variant). The picture is kept in the
+ * background layer: as the camera moves, only the rows and columns it
+ * uncovers are painted, each from the copy on top there (the picture's
+ * stream is cut into strips, so a row deep down costs no more than one near
+ * its top). The layer holds all the columns the parallax shows. */
+#define SKY_W 384
+#define SKY_H (VIEW_H + 8)
static bool sky_slot(unsigned slot, const SlotInfo *si, void *ctx) {
(void)slot; (void)ctx;
@@ -434,90 +425,46 @@ static bool sky_slot(unsigned slot, const SlotInfo *si, void *ctx) {
if (t.type != SYM_BITMAP || S->nsky >= SKY_MAX) return true;
if (S->nsky && (uint16_t)t.v != S->sky_sprite) return true;
S->sky_sprite = (uint16_t)t.v;
- S->sky_x[S->nsky] = si->x;
- S->sky_y[S->nsky] = si->y;
+ S->sky_x[S->nsky] = (int16_t)floorf(si->x + .5f);
+ S->sky_y[S->nsky] = (int16_t)floorf(si->y + .5f);
S->nsky++;
return true;
}
-static void sky_paint(int x0, int y0, int w, int h) { (void)x0; (void)y0; (void)w; (void)h; }
+/* the copy on top at row y of Iba, -1 if none */
+static int sky_top(int y) {
+ Sprite sp;
+ sprite_info(S->sky_sprite, &sp);
+ for (int k = S->nsky - 1; k >= 0; k--)
+ if (y >= S->sky_y[k] && y < S->sky_y[k] + sp.h) return k;
+ return -1;
+}
+
+/* the layer's world is Iba's space: each row from the copy on top there */
+static void sky_paint(int x0, int y0, int w, int h) {
+ (void)x0; (void)w;
+ for (int y = y0, y1; y < y0 + h; y = y1) {
+ int k = sky_top(y);
+ for (y1 = y + 1; y1 < y0 + h && sky_top(y1) == k;) y1++;
+ if (k >= 0) bg_blit_rows(S->sky_sprite, S->sky_x[k], S->sky_y[k], y, y1);
+ }
+}
static void sky_setup(void) {
if (!S->iba) return;
clip_each_slot(nodes[S->iba].sym, nodes[S->iba].frame, sky_slot, NULL);
if (!S->nsky) return;
node_set_visible(S->iba, false);
- S->sky_ref = S->sky_y[S->nsky - 1];
Sprite sp;
sprite_info(S->sky_sprite, &sp);
- const uint8_t *st = spr_stream(S->sky_sprite);
- if (!st || sp.w < TEX_X0 + TEX_W || sp.h < TEX_ROW0 + TEX_H) return;
- /* the layer's memory: one clear pixel (the layer), then the texture */
- mem_layout(TEX_W, TEX_H + 1, sp.sheet, sky_paint);
- int w, h;
- uint8_t *mem = bg_layer(&w, &h);
- if (!mem || w != TEX_W || h != TEX_H + 1) { bg_off(); return; }
- uint8_t *tex = mem + TEX_W;
- z_open(rd32(st + 2), rd32(st + 6), rd32(st + 10));
- bool ok = z_get(NULL, (uint32_t)TEX_ROW0 * sp.w);
- for (int r = 0; ok && r < TEX_H; r++)
- ok = z_get(NULL, TEX_X0) && z_get(tex + r * TEX_W, TEX_W) && z_get(NULL, (uint32_t)(sp.w - TEX_X0 - TEX_W));
- if (!ok) { bg_off(); return; }
- S->tex = true;
- S->tex_mem = mem;
- S->tex_sheet = sp.sheet;
- bg_off();
-}
-
-/* the texture under everything, or nothing (the sky sprite covers the view) */
-static void texture_on(bool on) {
- if (!S->tex || on == S->tex_on) return;
- S->tex_on = on;
- if (on) {
- bg_setup(S->tex_mem, 1, 1, S->tex_sheet, sky_paint);
- bg_water(S->tex_mem + TEX_W, TEX_W, TEX_H);
- S->tex_cx = S->tex_cy = 0x7fffffff;
- } else bg_off();
-}
-
-/* the copy on top at row l of Iba, -1 if none */
-static int sky_top(float l) {
- Sprite sp;
- sprite_info(S->sky_sprite, &sp);
- for (int k = S->nsky - 1; k >= 0; k--)
- if (l >= S->sky_y[k] && l < S->sky_y[k] + sp.h) return k;
- return -1;
+ mem_layout(SKY_W, SKY_H, sp.sheet, sky_paint);
}
static void draw_under(void) {
if (!S || !S->iba || !S->nsky) return;
+ /* the view's top left in Iba's space (its scale is the view's), snapped as a sprite would be */
Mat M = mat_mul((Mat){1.0f / 3, 0, 0, 1.0f / 3, 0, 0}, node_global(S->iba));
- if (M.d < 1e-3f || M.a < 1e-3f) return;
- float v0 = -M.ty / M.d, v1 = v0 + VIEW_H / M.d;
- int k0 = sky_top(v0), k1 = sky_top(v1 - 1);
- if (k0 >= 0 && k0 == k1 && v1 - S->sky_y[k0] <= SKY_CHEAP) {
- Mat t = M;
- t.tx += M.a * S->sky_x[k0] + M.c * S->sky_y[k0];
- t.ty += M.b * S->sky_x[k0] + M.d * S->sky_y[k0];
- texture_on(false);
- gfx_sprite(S->sky_sprite, t, 255);
- return;
- }
- texture_on(true);
- if (!S->tex) return;
- /* the texture: the picture's columns from TEX_X0, the rows of copy sky_ref from TEX_ROW0 */
- int x0 = (int)floorf(M.tx + M.a * S->sky_x[0] + .5f), y0 = (int)floorf(M.ty + M.d * S->sky_ref + .5f);
- int cx = -x0 + TEX_X0, cy = -y0 + TEX_ROW0;
- if (cx != S->tex_cx || cy != S->tex_cy) {
- bg_camera(cx, cy);
- S->tex_cx = cx;
- S->tex_cy = cy;
- }
- /* where the sea still shows */
- if (k0 >= 0 && v0 - S->sky_y[k0] < SEA_END) {
- int ye = (int)floorf(M.ty + M.d * (S->sky_y[k0] + SEA_END) + .5f);
- if (ye > 0) gfx_rect(0, 0, VIEW_W, ye < VIEW_H ? ye : VIEW_H, rgb565(52, 212, 180), 255);
- }
+ bg_camera(-(int)floorf(M.tx + .5f), -(int)floorf(M.ty + .5f));
}
/* ---------------------------------------------------------------- start */
@@ -883,6 +830,10 @@ static void camera_goal(float *gx, float *gy) {
static void sys_camera(void) {
if (!S->target) return;
+#ifdef HOST
+ extern bool host_cam(float *x, float *y);
+ if (host_cam(&nodes[S->map].x, &nodes[S->map].y)) return; /* tests: the camera where they say */
+#endif
camera_goal(&S->qx, &S->qy);
NodeId b = S->map;
uint16_t T = nodes[b].T;
@@ -905,20 +856,6 @@ static void sys_parallax(void) {
S->par_hx = nodes[S->map].x; S->par_hy = nodes[S->map].y;
S->par_fx = S->par_fy = 0;
comp_vec(nodes[p].T, C_parallax, F_factor, &S->par_fx, &S->par_fy);
- /* the forest texture matches the copy of the sky seen from where the climber starts */
- if (S->nsky && S->climber) {
- float gx, gy;
- NodeId t = S->target;
- float tx, ty, cx, cy;
- ent_pos(t, &tx, &ty);
- ent_pos(S->climber, &cx, &cy);
- ent_set_pos(t, cx, cy);
- camera_goal(&gx, &gy);
- ent_set_pos(t, tx, ty);
- float iy = S->par_dy - S->par_fy * (S->par_hy - gy);
- int k = sky_top(-iy / 3);
- if (k >= 0) S->sky_ref = S->sky_y[k];
- }
}
float cx = S->par_hx - nodes[S->map].x, cy = S->par_hy - nodes[S->map].y;
nodes[p].x = S->par_dx - S->par_fx * cx;
diff --git a/games/championisland/src/sport_rugby.c b/games/championisland/src/sport_rugby.c
index e92bd5ed..442bd635 100644
--- a/games/championisland/src/sport_rugby.c
+++ b/games/championisland/src/sport_rugby.c
@@ -399,6 +399,7 @@ static void materialize(Actor *a) {
node_add(S->map, n);
place(n, &k);
lazy_frame(n, a->frame);
+ if (a->kind == A_END) node_play(n); /* the end zone's glow: nothing stops it in the doodle */
a->n = n;
ent_set_pos(n, a->x, a->y);
act_dirs(n, a->dir);
@@ -1198,7 +1199,13 @@ static void paths(void) {
/* ---------------------------------------------------------------- camera (Cq, Dq) */
static void camera(void) {
NodeId cam = S->map;
- if (S->pl >= 0) {
+#ifdef HOST
+ extern bool host_cam(float *x, float *y);
+ bool fixed = host_cam(&nodes[cam].x, &nodes[cam].y); /* tests: the camera where they say */
+#else
+ bool fixed = false;
+#endif
+ if (S->pl >= 0 && !fixed) {
float px, py;
act_pos(&S->act[S->pl], &px, &py);
Mat cg = node_global(cam);
diff --git a/games/championisland/src/sport_skate.c b/games/championisland/src/sport_skate.c
index deb7f5f7..bfff1bb3 100644
--- a/games/championisland/src/sport_skate.c
+++ b/games/championisland/src/sport_skate.c
@@ -666,7 +666,9 @@ static void index_query(const Index *ix, float x0, float y0, float x1, float y1,
int cy0 = (int)floorf((y0 - ix->maxh - ix->y0) / ix->cell), cy1 = (int)floorf((y1 - ix->y0) / ix->cell);
uint16_t pos[QMAX], end[QMAX];
int k = 0;
- if (cx1 >= 0 && cy1 >= 0 && cx0 < ix->nx && cy0 < ix->ny) {
+ /* a grid cut short (STARTS_MAX) keeps what lies past its last row or column
+ * there: a query past it reads that row or column */
+ if (cx1 >= 0 && cy1 >= 0) {
cx0 = clampi(cx0, 0, ix->nx - 1); cx1 = clampi(cx1, 0, ix->nx - 1);
cy0 = clampi(cy0, 0, ix->ny - 1); cy1 = clampi(cy1, 0, ix->ny - 1);
for (int cy = cy0; cy <= cy1; cy++)
@@ -846,6 +848,15 @@ static void draw_screens(NodeId p, Mat parent) {
}
}
+/* CreateJS snaps each object's own offset to a whole pixel of its parent's
+ * space (snapToPixel): ground tiles a quarter pixel apart meet, no seam */
+static float snap(float v) { return (float)(int)(v + (v < 0 ? -.5f : .5f)); }
+static Mat snapped(Mat m) {
+ m.tx = snap(m.tx);
+ m.ty = snap(m.ty);
+ return m;
+}
+
static void draw_item(const Item *it, Mat parent) {
if (it->s->shape & SH_BITMAP) {
Clip c;
@@ -853,7 +864,7 @@ static void draw_item(const Item *it, Mat parent) {
SymInfo si;
if ((it->k.flags & K_HIDDEN) || !clip_get(it->s->sym, &c) || !slot_at(c.slots, 0, &k, NULL) || (k.flags & K_HIDDEN)) return;
sym_info(k.ref, &si);
- gfx_sprite((uint16_t)si.v, mat_mul(mat_mul(parent, key_mat(&it->k)), key_mat(&k)), (uint8_t)(it->k.alpha * k.alpha / 255));
+ gfx_sprite((uint16_t)si.v, mat_mul(mat_mul(parent, snapped(key_mat(&it->k))), snapped(key_mat(&k))), (uint8_t)(it->k.alpha * k.alpha / 255));
return;
}
NodeId p = proto(it->s);
@@ -1644,6 +1655,10 @@ static void champion(void) {
/* ---------------------------------------------------------------- camera (Cq, Dq): the map follows the skater */
static void camera(void) {
NodeId map = S->map;
+#ifdef HOST
+ extern bool host_cam(float *x, float *y);
+ if (host_cam(&nodes[map].x, &nodes[map].y)) return; /* tests: the camera where they say */
+#endif
Mat l = node_local(map);
float cx, cy;
if (!mat_inv_apply(l, 480, 270, &cx, &cy)) return;
diff --git a/games/championisland/src/spr.c b/games/championisland/src/spr.c
index 35b5294d..1ff2c6aa 100644
--- a/games/championisland/src/spr.c
+++ b/games/championisland/src/spr.c
@@ -17,6 +17,7 @@ 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;
+static const uint8_t *z_next; /* a stream's next strip (its record), read on when this one ends */
#ifdef HOST
uint64_t z_bytes, z_opens; /* tests: how much the decoder did */
@@ -41,12 +42,24 @@ void z_open(uint32_t off, uint32_t clen, uint32_t rawlen) {
z_len = clen;
z_out = 0;
z_total = rawlen;
+ z_next = NULL;
+}
+
+/* A stream is one record of the stream table, or several in a row for a tall
+ * image cut into strips (pack.py): read as one, strip after strip. */
+void z_open_stream(const uint8_t *st) {
+ z_open(rd32(st + 2), rd32(st + 6), rd32(st + 10));
+ const uint8_t *end = ci_data + HDR(H_STREAMS) + 14u * HDR(H_NSTREAMS);
+ if (st + 14 < end && rd16(st + 14) == rd16(st)) z_next = st + 14;
}
/* Decodes up to n more bytes; they sit in ring[] from *at (never wrapping:
* a read ends at the end of the ring). Returns how many (0 at the end). */
uint32_t z_read(uint32_t n, const uint8_t **at) {
- if (z_out >= z_total) return 0;
+ if (z_out >= z_total) {
+ if (!z_next) return 0;
+ z_open_stream(z_next);
+ }
if (dec.dicPos == LZMA_DICT) dec.dicPos = 0;
uint32_t start = (uint32_t)dec.dicPos, room = LZMA_DICT - start;
if (n > room) n = room;
@@ -137,6 +150,15 @@ static void compact(void) {
}
static inline uint16_t age(const Entry *e) { return (uint16_t)((uint16_t)tick - e->used); }
+/* what getting an entry back costs for each byte of room it takes: its
+ * sprite's pixels (a mask's too) decoded again, with what comes before them
+ * in their bank (16ths of a byte); a tiny sprite at the end of a bank costs
+ * the most */
+static uint32_t regain(const Entry *e) {
+ Sprite s;
+ sprite_info((uint16_t)(e->spr & 0x7FFF), &s);
+ return (((s.kind ? 0 : s.off) + (uint32_t)s.w * s.h) << 4) / (e->size + 4u);
+}
/* the cache the entries used this tick (keep = 0) or the last too (keep = 1) take */
static uint32_t fresh_bytes(unsigned keep, unsigned *count) {
@@ -148,13 +170,6 @@ static uint32_t fresh_bytes(unsigned keep, unsigned *count) {
return n;
}
-static void evict_one(void) {
- int old = 0;
- for (int i = 1; i < nent; i++)
- if (age(&ent[i]) > age(&ent[old])) old = i;
- ent[old] = ent[--nent];
-}
-
/* Room for n bytes; evicts only entries not used this tick or the last
* (keep = 1), or this tick (keep = 0), unless forced. */
static uint8_t *alloc_keep(uint32_t n, bool force, unsigned keep) {
@@ -164,14 +179,18 @@ static uint8_t *alloc_keep(uint32_t n, bool force, unsigned keep) {
uint32_t live = 0;
for (int i = 0; i < nent; i++) live += (ent[i].size + 3) & ~3u;
while (nent && (live + n > cache_bytes || nent >= ENTRIES)) {
- /* the oldest goes; of what this very frame draws (a frame bigger than
- * the cache), the smallest: a big one costs the most to decode again */
+ /* the oldest goes; of the same age (what this very frame draws, in a
+ * frame bigger than the cache), the one cheapest to get back */
int old = 0;
- for (int i = 1; i < nent; i++)
- if (age(&ent[i]) > age(&ent[old]) || (!age(&ent[i]) && !age(&ent[old]) && ent[i].size < ent[old].size)) old = i;
+ uint32_t r = regain(&ent[0]);
+ for (int i = 1; i < nent; i++) {
+ if (age(&ent[i]) < age(&ent[old])) continue;
+ uint32_t ri = regain(&ent[i]);
+ if (age(&ent[i]) > age(&ent[old]) || ri < r) { old = i; r = ri; }
+ }
if (!force && age(&ent[old]) <= keep) return NULL;
live -= (ent[old].size + 3) & ~3u;
- evict_one();
+ ent[old] = ent[--nent]; /* that one (its size is what live lost) */
}
/* only when the space is short: a full entry table needs no moving */
if (top + n > cache_bytes) compact();
@@ -334,7 +353,7 @@ const uint8_t *spr_get(uint16_t sp) {
if (s.kind == 1) {
const uint8_t *st = spr_stream(sp);
if (!st) return NULL;
- z_open(rd32(st + 2), rd32(st + 6), rd32(st + 10));
+ z_open_stream(st);
add_from_decoder(sp, &s, true);
} else {
const uint8_t *b = ci_data + HDR(H_BANKS) + 12u * s.bank;
@@ -384,7 +403,7 @@ bool spr_rows_open(uint16_t sp, const Sprite *s) {
if (s->kind == 1) {
const uint8_t *st = spr_stream(sp);
if (!st) return false;
- z_open(rd32(st + 2), rd32(st + 6), rd32(st + 10));
+ z_open_stream(st);
return true;
}
if (s->kind != 0) return false;
@@ -393,6 +412,20 @@ bool spr_rows_open(uint16_t sp, const Sprite *s) {
return z_get(NULL, s->off);
}
+/* spr_rows_open at row `row`: a stream in strips starts from the strip holding it */
+bool spr_rows_at(uint16_t sp, const Sprite *s, int row) {
+ const uint8_t *st = s->kind == 1 ? spr_stream(sp) : NULL;
+ if (!st) return spr_rows_open(sp, s) && z_get(NULL, (uint32_t)row * s->w);
+ const uint8_t *end = ci_data + HDR(H_STREAMS) + 14u * HDR(H_NSTREAMS);
+ uint32_t skip = (uint32_t)row * s->w;
+ while (st + 14 < end && rd16(st + 14) == sp && skip >= rd32(st + 10)) {
+ skip -= rd32(st + 10);
+ st += 14;
+ }
+ z_open_stream(st);
+ return z_get(NULL, skip);
+}
+
bool spr_room(uint32_t n) {
n = (n + 3) & ~3u;
if (!mem || n > cache_bytes) return false;
@@ -490,6 +523,21 @@ static uint32_t mask_rows(uint16_t sp, const Sprite *s, const uint8_t *al, uint8
return o.at;
}
+/* the sizes of masks made before: one the cache let go is made again from
+ * the decoder in one pass */
+#define KNOWN 32
+typedef struct { uint16_t sp, size; } Known;
+static Known known[KNOWN];
+static unsigned known_next;
+static uint32_t mask_known(uint16_t sp) {
+ for (int i = 0; i < KNOWN; i++)
+ if (known[i].sp == sp && known[i].size) return known[i].size;
+ return 0;
+}
+static void mask_learn(uint16_t sp, uint32_t n) {
+ if (n && n <= 0xFFFF && !mask_known(sp)) known[known_next++ % KNOWN] = (Known){sp, (uint16_t)n};
+}
+
const uint8_t *spr_mask(uint16_t sp) {
if (sp >= SPRITE_COUNT || !mem) return NULL;
unsigned f = find((uint16_t)(sp | MASK));
@@ -500,24 +548,26 @@ const uint8_t *spr_mask(uint16_t sp) {
Sprite s;
sprite_info(sp, &s);
const uint8_t *al = palalpha(s.sheet);
- if (!find(sp) && !spr_room(s.rle ? s.rle : rle_bound(s.w, s.h))) {
- /* no room for the sprite: its mask straight from the decoder, measured then
- * written; not even measured when what the frame draws leaves too little
- * room (a guess: an eighth of the sprite's runs), as a frame bigger than
- * the cache would measure it again and again */
- if (fresh_bytes(0, NULL) + s.rle / 8 > cache_bytes) return NULL;
- uint32_t n = mask_rows(sp, &s, al, NULL);
- if (!n || n > 0xFFFF || nent >= ENTRIES) return NULL;
- uint8_t *m = alloc_keep(n, false, 0);
+ bool had = find(sp);
+ if (!had && !spr_room(s.rle ? s.rle : rle_bound(s.w, s.h))) {
+ /* no room for the sprite: its mask straight from the decoder, measured
+ * (once: the size is kept, and frames count it) then written, when what
+ * the frame draws leaves room for it */
+ uint32_t n = mask_known(sp);
+ if (!n) mask_learn(sp, n = mask_rows(sp, &s, al, NULL));
+ if (!n || n > 0xFFFF || fresh_bytes(0, NULL) + n > cache_bytes) return NULL;
+ uint8_t *m = alloc_keep(n, false, 0); /* (a full table lets an older entry go) */
if (!m || mask_rows(sp, &s, al, m) != n || nent >= ENTRIES) return NULL;
ent[nent++] = (Entry){(uint16_t)(sp | MASK), (uint16_t)((uint32_t)(m - mem) / 4), (uint16_t)n, (uint16_t)tick};
return m;
}
if (!spr_get(sp)) return NULL;
uint32_t n = mask_build(mem + 4u * ent[find(sp) - 1].off4, al, NULL);
- if (n > 0xFFFF || nent >= ENTRIES) return NULL;
+ if (n > 0xFFFF) return NULL;
+ mask_learn(sp, n);
uint8_t *m = alloc_keep(n, false, 0); /* may move the sprite (compaction): look it up again */
unsigned fs = find(sp);
+ if (fs && !had) ent[fs - 1].used = (uint16_t)(tick - 2); /* decoded for its mask only: the first to go */
if (!m || !fs) return NULL;
mask_build(mem + 4u * ent[fs - 1].off4, al, m);
if (nent >= ENTRIES) return NULL;
@@ -525,6 +575,16 @@ const uint8_t *spr_mask(uint16_t sp) {
return m;
}
+/* the room a sprite's mask takes: its size once made, else a guess (a
+ * quarter of the sprite's runs, about what scenery's masks take) */
+uint32_t spr_mask_bytes(uint16_t sp) {
+ uint32_t n = mask_known(sp);
+ if (n) return (n + 3) & ~3u;
+ Sprite s;
+ sprite_info(sp, &s);
+ return ((s.rle ? s.rle : rle_bound(s.w, s.h)) / 4 + 3) & ~3u;
+}
+
const uint8_t *spr_peek_mask(uint16_t sp) {
unsigned f = sp < SPRITE_COUNT && mem ? find((uint16_t)(sp | MASK)) : 0;
return f ? mem + 4u * ent[f - 1].off4 : NULL;
diff --git a/games/championisland/src/spr.h b/games/championisland/src/spr.h
index d05f2667..228de017 100644
--- a/games/championisland/src/spr.h
+++ b/games/championisland/src/spr.h
@@ -5,6 +5,7 @@
/* LZMA decoding (one stream at a time) */
void z_open(uint32_t off, uint32_t clen, uint32_t rawlen);
+void z_open_stream(const uint8_t *st); /* a stream from its record (spr_stream), all its strips */
uint32_t z_read(uint32_t n, const uint8_t **at);
bool z_get(uint8_t *dst, uint32_t n);
@@ -17,9 +18,11 @@ const uint8_t *spr_get_soft(uint16_t sprite); /* spr_get without letting go of
const uint8_t *spr_stream(uint16_t sprite); /* 14-byte stream record or NULL */
const uint8_t *spr_mask(uint16_t sprite); /* its opaque pixels as spans (decodes it if needed), or NULL */
const uint8_t *spr_peek_mask(uint16_t sprite);
+uint32_t spr_mask_bytes(uint16_t sprite); /* the cache its mask takes (a guess until it is made) */
/* the decoder at the sprite's first row, its pixels following (w a row),
* without the cache: for big scenery the cache has no room for */
bool spr_rows_open(uint16_t sprite, const Sprite *s);
+bool spr_rows_at(uint16_t sprite, const Sprite *s, int row); /* the same from row `row` on */
bool spr_room(uint32_t bytes); /* would fit without letting go of what the last frame drew */
void spr_pin(uint16_t sprite, const uint8_t *rle);
bool spr_pinned(uint16_t sprite); /* kept outside the cache (spr_pin) */
diff --git a/games/championisland/src/world.c b/games/championisland/src/world.c
index 18b1ddc1..45c8fe8d 100644
--- a/games/championisland/src/world.c
+++ b/games/championisland/src/world.c
@@ -190,6 +190,17 @@ static void view_origin(float *x, float *y) {
*y = (m.b * m.tx - m.a * m.ty) / det;
}
+/* the same at a whole pixel: the layer is drawn there, and so is the map (the
+ * doodle's canvas snaps the map's own translation before placing its children,
+ * snapToPixel): people and things keep their pixel on the ground whatever the
+ * camera's fraction, instead of shaking against it as it scrolls */
+static void view_pixel(int *x, int *y) {
+ float vx, vy;
+ view_origin(&vx, &vy);
+ *x = (int)floorf(vx + .5f);
+ *y = (int)floorf(vy + .5f);
+}
+
/* ---------------------------------------------------------------- drawing the map */
static float draw_key(NodeId c) {
if (nodes[c].ent && comp_has(nodes[c].T, C_drawOrderOverride)) return comp_float(nodes[c].T, C_drawOrderOverride, F_drawOrder, 0);
@@ -227,6 +238,10 @@ static void draw_static_over(unsigned id, Mat m, uint8_t alpha) {
/* the map's children in draw order, with the statics that belong in front of them */
static void draw_map(NodeId map, Mat m, uint8_t alpha) {
+ int px, py;
+ view_pixel(&px, &py);
+ m.tx = -(m.a * px + m.c * py); /* map pixel (px, py) at the view's corner, as in the layer */
+ m.ty = -(m.b * px + m.d * py);
float vx, vy;
view_origin(&vx, &vy);
float vx1 = vx + VIEW_W, vy1 = vy + gfx_view_bottom();
@@ -525,22 +540,29 @@ static const uint8_t COND_F[10] = {F_condition1, F_condition2, F_condition3, F_c
static const uint8_t FRAME_F[5] = {F_frame1, F_frame2, F_frame3, F_frame4, F_frame5};
static const uint8_t NODE_F[10] = {F_node1, F_node2, F_node3, F_node4, F_node5, F_node6, F_node7, F_node8, F_node9, F_node10};
-/* Er: storageSprite shows the frame of its first true condition (a quarter of them per tick) */
+/* Er: a storageSprite shows the frame of its first true condition (the
+ * island's and the menus': the map's scrolls and team) */
+void storage_sprite(NodeId n) {
+ uint16_t T = nodes[n].T;
+ if (T == NONE16 || !comp_has(T, C_storageSprite)) return;
+ for (int k = 0; k < 5; k++) {
+ uint16_t fr = comp_str(T, C_storageSprite, FRAME_F[k]);
+ if (fr == NONE16 || !str(fr)[0]) continue;
+ uint16_t cond = comp_str(T, C_storageSprite, COND_F[k]);
+ if (cond == NONE16 || !str(cond)[0] || cond_eval(cond)) {
+ ent_label(n, str(fr), false);
+ break;
+ }
+ }
+}
+
+/* a quarter of them per tick */
static void sys_storage_sprites(void) {
for (int i = 0; i < ent_count(); i++) {
NodeId n = ent_at(i);
if (!n || !comp_has(nodes[n].T, C_storageSprite)) continue;
if (W->tick && n % 4 != W->tick % 4) continue;
- uint16_t T = nodes[n].T;
- for (int k = 0; k < 5; k++) {
- uint16_t fr = comp_str(T, C_storageSprite, FRAME_F[k]);
- if (fr == NONE16 || !str(fr)[0]) continue;
- uint16_t cond = comp_str(T, C_storageSprite, COND_F[k]);
- if (cond == NONE16 || !str(cond)[0] || cond_eval(cond)) {
- ent_label(n, str(fr), false);
- break;
- }
- }
+ storage_sprite(n);
}
}
@@ -668,14 +690,19 @@ static void sys_npcs(void) {
/* tr, ur, Fr: what trigger areas do when the player walks in */
static void on_trigger(NodeId t, NodeId other, bool entered) {
if (!entered) return;
+#ifdef HOST
+ if (getenv("CI_PATH")) return; /* tests fly over the island */
+#endif
uint16_t T = nodes[t].T;
if (comp_has(T, C_dialogTrigger)) {
uint16_t npc = comp_str(T, C_dialogTrigger, F_npc), node = comp_str(T, C_dialogTrigger, F_node);
if (npc != NONE16 && node != NONE16) dialog_start(npc, node);
}
if (comp_has(T, C_sceneTrigger)) {
+ /* ur: no er() here, a room's exit would save a place of the room, not
+ * one of the island (where the game would then open on the dock) */
uint16_t nm = comp_str(T, C_sceneTrigger, F_name);
- if (nm != NONE16) { save_place(); game_go(str(nm)); }
+ if (nm != NONE16) game_go(str(nm));
}
if (comp_has(T, C_storageTrigger)) {
uint16_t k = comp_str(T, C_storageTrigger, F_key), v = comp_str(T, C_storageTrigger, F_value);
@@ -718,7 +745,7 @@ static const uint8_t *pattern(unsigned i) {
return i < rd16(blk) ? blk + rd32(blk + 4 + 4 * i) : NULL;
}
-/* oAa, mAa: after the ending (outro seen), a glow over the top of the view and
+/* oAa, mAa: after the ending (outro seen), a glow over the whole view and
* the petals falling over the island (repeatable tiles of 144 x 62, the 20
* looks of a petal taking turns every 3 ticks) */
static bool petal_slot(unsigned slot, const SlotInfo *si, void *ctx) {
@@ -730,7 +757,11 @@ static bool petal_slot(unsigned slot, const SlotInfo *si, void *ctx) {
}
static void draw_ending(float mx, float my) {
uint16_t gs = glow_sprite();
- if (gs != NONE16) gfx_sprite(gs, (Mat){1, 0, 0, 1, 0, (float)gfx_view_top()}, 255); /* over the top of the screen */
+#ifdef HOST
+ if (getenv("CI_NOGLOW")) gs = NONE16; /* tests: the same frame without the glow */
+#endif
+ /* nAa is the doodle's whole screen (the stage, at 3x): it covers the whole view */
+ if (gs != NONE16) gfx_sprite_rows(gs, 0, gfx_view_top(), gfx_view_bottom() - gfx_view_top(), 255);
const uint8_t *t = pattern(1);
if (!t || !W->npetal) return;
unsigned looks = rd16(t + 2), look = W->tick / 3 % (looks ? looks : 1);
@@ -770,6 +801,62 @@ void nth_place(const char *name, float x, float y, void *ctx) {
if (q->i++ == q->want) snprintf(q->name, sizeof q->name, "%s", name);
(void)x; (void)y;
}
+/* CI_DIFF (play.c): the layer painted again from scratch and the live
+ * children streamed again, as a teleport does, to compare with the frame
+ * kept up as the camera moved; the children that were missing, -1 if not
+ * on the island */
+static int redo_new;
+static void redo_count(NodeId c) {
+ streamed_in(c);
+ float vx, vy, bx, by, bw, bh;
+ view_origin(&vx, &vy);
+ if (!nodes[c].alpha || !node_bounds_in(c, W->map, &bx, &by, &bw, &bh)) return;
+ bx -= vx;
+ by -= vy;
+ if (bx >= VIEW_W || bx + bw <= 0 || by >= gfx_view_bottom() || by + bh <= gfx_view_top()) return;
+ fprintf(stderr, " missing child sym %u at %.0f,%.0f %.0fx%.0f on screen\n", nodes[c].sym, bx, by, bw, bh);
+ redo_new++;
+}
+static uint8_t redo_layer[LAYER_W * LAYER_H];
+/* after the new frame: the layer's pixels on screen that changed, and where */
+int world_layer_diff(int box[4]) {
+ int w, h, n = 0;
+ uint8_t *l = bg_layer(&w, &h);
+ float vx, vy;
+ view_origin(&vx, &vy);
+ int cx = (int)floorf(vx + .5f), cy = (int)floorf(vy + .5f);
+ box[0] = box[1] = 9999;
+ box[2] = box[3] = -9999;
+ for (int y = gfx_view_top(); y < gfx_view_bottom(); y++)
+ for (int x = 0; x < VIEW_W; x++) {
+ int lx = (cx + x) % w, ly = (cy + y) % h;
+ lx += lx < 0 ? w : 0;
+ ly += ly < 0 ? h : 0;
+ if (l[ly * w + lx] == redo_layer[ly * w + lx]) continue;
+ n++;
+ if (x < box[0]) box[0] = x;
+ if (y < box[1]) box[1] = y;
+ if (x > box[2]) box[2] = x;
+ if (y > box[3]) box[3] = y;
+ }
+ return n;
+}
+int world_redo(char *where, int size) {
+ if (!W || !W->map || strcmp(game.name, "overworld")) return -1;
+ int lw, lh;
+ memcpy(redo_layer, bg_layer(&lw, &lh), sizeof redo_layer);
+ float vx, vy;
+ view_origin(&vx, &vy);
+ PlaceQuery q = {NULL, vx + VIEW_W / 2, vy + VIEW_H / 2, 0, false, ""};
+ each_place(find_place, &q);
+ snprintf(where, (size_t)size, "view %.0f,%.0f near %s", vx, vy, q.name);
+ bg_invalidate();
+ redo_new = 0;
+ node_stream_hook = redo_count;
+ stream_children(true);
+ node_stream_hook = streamed_in;
+ return redo_new;
+}
static int subtree(NodeId n) {
int t = 1;
for (NodeId c = nodes[n].first; c; c = nodes[c].next) t += subtree(c);
@@ -872,10 +959,39 @@ static void end_overworld(void) {
W = NULL;
}
+#ifdef HOST
+/* CI_PATH="speed;x,y;x,y;...": the player flies along the path (through
+ * walls) at speed px a tick, the camera following, and stays CI_HOLD ticks
+ * at each point (fly_held: the point whose last tick this is) (tests) */
+int fly_held = -1;
+static void fly_path(const char *s) {
+ float speed = strtof(s, NULL), t = (float)W->tick, px = 0, py = 0;
+ float hold = getenv("CI_HOLD") ? (float)atoi(getenv("CI_HOLD")) : 0;
+ int i = 0;
+ for (const char *p = strchr(s, ';'); p; p = strchr(p + 1, ';'), i++) {
+ float x, y;
+ if (sscanf(p + 1, "%f,%f", &x, &y) != 2) break;
+ float len = i ? hypotf(x - px, y - py) : 0, go = len / speed;
+ if (t < go) { px += (x - px) * t / go; py += (y - py) * t / go; t = -1; break; }
+ px = x; py = y;
+ t -= go;
+ if (t < hold) { if (t + 1 >= hold) fly_held = i; t = -1; break; }
+ t -= hold;
+ }
+ if (!i || !W->player) return;
+ ent_set_pos(W->player, px, py);
+ Ent *e = ent_get(W->player);
+ if (e) e->vx = e->vy = 0;
+}
+#endif
+
static void tick_overworld(void) {
if (!W || !W->map) return;
sys_back_map();
sys_overworld_player();
+#ifdef HOST
+ if (getenv("CI_PATH")) fly_path(getenv("CI_PATH"));
+#endif
sys_camera_target();
sys_camera_move();
sys_tile_backgrounds();
@@ -940,9 +1056,9 @@ static void draw_under_overworld(void) {
water_make(look);
bg_water4(W->water, WATER, WATER, W->water_col);
}
- float vx, vy;
- view_origin(&vx, &vy);
- bg_camera((int)floorf(vx + .5f), (int)floorf(vy + .5f));
+ int px, py;
+ view_pixel(&px, &py);
+ bg_camera(px, py);
}
const SceneDef scene_overworld = {"overworld", start_overworld, tick_overworld, end_overworld, draw_under_overworld, draw_over_overworld, NULL};
@@ -975,6 +1091,10 @@ static void start_interior(void) {
/* sr: places are markers */
if (n && comp_has(nodes[n].T, C_location) && !comp_has(nodes[n].T, C_boundable)) nodes[n].alpha = 0;
}
+ /* sr: at the scene's place (the door he came in by: a hallway's far end,
+ * the top of the banyan tree), else the saved one, as on the island */
+ const char *where = game.location[0] ? game.location : store_str("PLAYER_LOC");
+ if (where && W->map) teleport(where);
ent_on_trigger(on_trigger);
phys_steps(1, 20);
(void)room_label;
diff --git a/games/championisland/tests/check.py b/games/championisland/tests/check.py
index e7e40f14..0b21ea06 100644
--- a/games/championisland/tests/check.py
+++ b/games/championisland/tests/check.py
@@ -6,7 +6,9 @@ AddressSanitizer and UBSan, in scenes that once went wrong.
"""
import os
import random
+import re
import shutil
+import struct
import subprocess
import sys
import tempfile
@@ -18,14 +20,33 @@ PLAY = sys.argv[1] if len(sys.argv) > 1 else "build/play"
failures = []
-def run(scene, frames, keys="", shots=(), env=None):
- """Plays a scene from a fresh save; returns (stdout, stderr, frames saved)."""
+def write_save(path, values):
+ """A save as store.c writes it: "CI1", then key, type and value (bool, number or text)."""
+ out = bytearray(b"CI1")
+ for k, v in values.items():
+ out += bytes([len(k)]) + k.encode()
+ if isinstance(v, bool):
+ out += bytes([2, v])
+ elif isinstance(v, (int, float)):
+ out += bytes([3]) + struct.pack("<f", v)
+ else:
+ out += bytes([4, len(v)]) + v.encode()
+ open(path, "wb").write(out)
+
+
+def run(scene, frames, keys="", shots=(), env=None, saves=None, save=None):
+ """Plays a scene (None: where the game opens) from a fresh save, or from the
+ one kept in `saves`, or from these saved values (`save`); returns (stdout,
+ stderr, frames saved)."""
d = tempfile.mkdtemp(prefix="ci_check_")
os.makedirs(d + "/saves")
+ if save:
+ write_save(d + "/saves/champion.sav", save)
e = dict(os.environ, ASAN_OPTIONS="detect_leaks=0", UBSAN_OPTIONS="halt_on_error=1:print_stacktrace=1",
CI_LEAK="1", CI_CONSIST="1")
e.update(env or {})
- args = [PLAY, "--scene", scene, "--frames", str(frames), "--keys", keys, "--out", d, "--saves", d + "/saves"]
+ args = [PLAY] + (["--scene", scene] if scene else []) + ["--frames", str(frames), "--keys", keys, "--out", d,
+ "--saves", saves or d + "/saves"]
if shots:
args += ["--shots", ",".join(str(s) for s in shots)]
p = subprocess.run(args, capture_output=True, text=True, env=e, timeout=900)
@@ -33,8 +54,9 @@ def run(scene, frames, keys="", shots=(), env=None):
shutil.rmtree(d, ignore_errors=True)
if p.returncode or "runtime error" in p.stderr or "AddressSanitizer" in p.stderr:
failures.append(f"{scene}: crashed or a sanitizer error\n{p.stderr[-2000:]}")
- if "NODE POOL FULL" in p.stdout:
- failures.append(f"{scene}: {p.stdout.strip().splitlines()[0]}")
+ for full in ("NODE POOL FULL", "DRAW LIST FULL"): # nodes not made, pictures not drawn
+ if full in p.stdout:
+ failures.append(f"{scene}: " + next(line for line in p.stdout.splitlines() if full in line))
# every node is under a root: the HUD, the dialogue box, the menus or the scene's (game.c's CI_LEAK) ...
for line in p.stderr.splitlines():
if " not under a root" in line and not line.endswith(" 0 not under a root"):
@@ -103,6 +125,68 @@ check("the island fills the screen", img[39][:30].any() and img[39][210:].any(),
_, _, img = run("pingpong", 40, shots=[39])
check("a sport keeps its frame", not img[39][:30].any() and not img[39][210:].any(), "something is drawn above or below")
+# while the camera scrolls, what stands on the island moves with the ground
+# (the statues and lanterns of the hub used to shake a pixel against it: they
+# were placed with the camera's fraction, the layer at its whole pixel)
+def shaken(a, b):
+ """16 px blocks of frame b a pixel off where the ground's move from frame a puts them."""
+ a, b = a.astype(int), b.astype(int)
+ _, dx, dy = max(((b[40:200, 20:300] == a[40 + y:200 + y, 20 + x:300 + x]).all(-1).mean(), x, y)
+ for y in range(-6, 7) for x in range(-6, 7))
+ n = 0
+ for y in range(16, 208, 16):
+ for x in range(16, 288, 16):
+ if 112 <= x < 208 and 72 <= y < 168:
+ continue # Lucky
+ B = b[y:y + 16, x:x + 16]
+ if (B == a[y + dy:y + dy + 16, x + dx:x + dx + 16]).all():
+ continue
+ n += any((B == a[y + dy + j:y + dy + j + 16, x + dx + i:x + dx + i + 16]).all()
+ for j in (-1, 0, 1) for i in (-1, 0, 1) if i or j)
+ return n
+
+
+_, _, img = run("overworld@hub", 60, "20-58:right,20-58:down", shots=range(20, 59))
+off = [f for f in range(21, 59) if f in img and f - 1 in img and shaken(img[f - 1], img[f])]
+check("the island scrolls in one piece", len(img) == 39 and not off, f"things a pixel off the ground in frames {off}")
+
+# once the climbing scroll is won, Lucky's statue stands on the pedestal at the
+# top of the plaza (the champion's statue under him is masked down to its
+# pedestal: drawn whole, it hid him)
+def lucky_on_pedestal(store):
+ _, _, img = run("overworld@hub", 40, shots=[39], env={"CI_POS": "-11,-60", "CI_STORE": store})
+ r = img[39][40:100, 136:184].astype(int)
+ return int(((r[..., 0] > 200) & (r[..., 1] > 90) & (r[..., 1] < 200) & (r[..., 2] < 90)).sum())
+
+
+won, not_won = lucky_on_pedestal("climbing_rating=3"), lucky_on_pedestal("climbing_rating=2")
+check("Lucky's statue once the climbing scroll is won", won > 40 and not_won == 0, f"orange pixels: {won} won, {not_won} not won")
+# after the ending, the glow (nAa, the doodle's whole screen) covers the whole
+# island view like the doodle's screen: its top is 168/255 pink and its
+# faintest band (21/255) reaches the middle and, down the right edge, the
+# bottom (it used to stop 60 rows short, the top 180 rows only). Pixels are
+# gfx.c's blend of the glow's colour over the same frame drawn without it.
+_, _, glow = run("overworld@start", 40, shots=[39], env={"CI_ENDING": "1"})
+_, _, bare = run("overworld@start", 40, shots=[39], env={"CI_ENDING": "1", "CI_NOGLOW": "1"})
+
+
+def glowed(y0, y1, x0, x1, rgb, a):
+ """Share of the pixels the glow changes that are rgb blended at a/32 (petals aside), and their count."""
+ to565 = np.array([31, 63, 31]) / 255
+ g = np.rint(glow[39][y0:y1, x0:x1] * to565).astype(int)
+ b = np.rint(bare[39][y0:y1, x0:x1] * to565).astype(int)
+ f = np.array([rgb[0] >> 3, rgb[1] >> 2, rgb[2] >> 3])
+ want = b + (f - b) * a // 32
+ changed = (want != b).any(2)
+ return ((want == g).all(2) & changed).sum() / max(changed.sum(), 1), changed.sum()
+
+
+for name, box, rgb, a in (("over the top", (0, 15, 40, 320), (244, 213, 251), 21),
+ ("to the middle", (134, 145, 20, 280), (203, 162, 144), 3),
+ ("down to the bottom right", (220, 240, 318, 320), (203, 162, 144), 3)):
+ share, n = glowed(*box, rgb, a) if 39 in glow and 39 in bare else (0, 0)
+ check(f"the ending's glow {name}", n >= 10 and share > .9, f"{share:.0%} of {n} pixels")
+
# nodes are all freed when a scene ends (node_free used to leave some 50 of
# the climbing wall's 130 children behind, every time)
before = len(failures)
@@ -116,6 +200,102 @@ for v in ("climbing", "climbing:hard"):
run(v, 60)
print(("ok " if len(failures) == before else "FAIL ") + f"{v} has all its nodes")
+# the dialogue box breaks its text as the doodle does (at the text's lineWidth
+# in its own 10 px) and grows to it: the Trophy Master's five lines used to be
+# seven, spilling out of the box
+_, err, _ = run("interior:trophyRoom", 580, "20-80:up,90:ok,190:ok,290:ok,390:ok,490:ok", env={"CI_ITEMS": "1"})
+last = items(err)
+texts = [b for k, b, ref in last if k == 4 and b[1] < 40]
+bases = [b for k, b, ref in last if k == 1 and b[0] < 10 and b[2] > 300]
+check("a long dialogue fits its box", texts and bases and texts[0][3] < bases[0][3] and texts[0][3] - texts[0][1] < 90,
+ f"text {texts} box {bases}")
+
+# the map shows the player's team and the scrolls won (their storageSprites:
+# it used to show the blue team and no scroll, whatever the save)
+won = {"TUTORIAL_DONE": True, "PLAYER_TEAM": "red", "pingpong_score": 5000, "pingpong_rating": 3}
+_, _, img = run("overworld@hub", 60, "30:back", shots=[59], save=won)
+_, _, img0 = run("overworld@hub", 60, "30:back", shots=[59], save={"TUTORIAL_DONE": True, "PLAYER_TEAM": "red"})
+icon = img[59][155:180, 250:272].reshape(-1, 3).mean(0) if 59 in img else np.zeros(3)
+scroll = np.abs(img[59][135:160, 60:85].astype(int) - img0[59][135:160, 60:85].astype(int)).mean() if 59 in img and 59 in img0 else 0
+check("the map shows the team and the scrolls", icon[2] < icon[0] / 2 and scroll > 2, f"team icon {icon}, scroll {scroll}")
+
+# a menu's shade darkens the whole screen on the island (the skip menu's is a
+# quarter pixel short of the stage: the bands above and below stayed bright)
+_, _, img = run("overworld@hub", 40, "20:back", shots=[39])
+band = np.concatenate([img[39][:30], img[39][210:]]).mean() if 39 in img else 255
+check("the skip menu shades the whole island", band < 60, f"bands at {band:.0f}")
+
+# The climbing backdrop (the vista behind the cliff) is the picture itself at
+# every height: the sea at the top of the holes halfway up is its deep blue
+# (it used to be a flat teal below the picture's row 400), and in the hard
+# variant the forest's temples are where the picture has them (it used to be
+# a strip of the forest repeated). CI_CAM puts the camera (the map) there.
+def cam(x, y, f0=130):
+ return {"CI_CAM": f"{f0}:1000:{x}:{x}:0:{y}:{y}:0"}
+
+
+def view_of(img, shot):
+ return img[shot][30:210].astype(int) if shot in img else np.zeros((180, 320, 3), int)
+
+
+sea = view_of(run("climbing", 136, "60:ok", shots=[135], env=cam(120, 2493))[2], 135)[0:20, 40:80].reshape(-1, 3)
+colours, counts = np.unique(sea, axis=0, return_counts=True)
+top = colours[counts.argmax()]
+check("the climbing vista's sea halfway up", top[2] > top[1], f"its main colour is {top.tolist()}")
+
+
+def roofs(v): # the temples' grey-blue roofs
+ return int(((abs(v[..., 0] - v[..., 1]) < 25) & (v[..., 2] > v[..., 1] + 8) & (v[..., 0] > 70) & (v[..., 0] < 190)).sum())
+
+
+view = view_of(run("climbing:hard", 136, "60:ok", shots=[135], env=cam(120, 2403))[2], 135)
+here, there = roofs(view[100:160, 280:320]), roofs(view[20:80, 280:320])
+check("the climbing vista's forest in the hard variant", here > 400 and there < 100,
+ f"roofs: {here} px where the picture has them, {there} where it has none")
+
+# the rugby end zone's grass glows (its clip plays alpha 0 to 1 to 0): it used
+# to stay at its first frame, unseen
+shots = [230, 242, 254, 266, 278]
+_, _, img = run("rugby", 280, "60:ok", shots=shots, env=cam(-3643, 266, 200))
+green = 0.0
+for s in shots:
+ v = view_of(img, s)[20:160, 290:320]
+ green = max(green, ((v[..., 1] > v[..., 0] + 30) & (v[..., 1] > v[..., 2] + 30)).mean())
+check("the rugby end zone shows", green > .5, f"at most {green:.0%} of it green")
+
+# no seam between skate park 2's ground tiles a quarter pixel apart (CreateJS
+# snaps each one's offset to a whole pixel: they meet)
+col = view_of(run("skate:park2", 226, "60:ok", shots=[225], env=cam(3068, -1451, 220))[2], 225)[36:180, 91].sum(1)
+check("no seam in skate park 2's ground", (col < 60).sum() < 20, f"{(col < 60).sum()} dark pixels in column 91")
+
+# the skate tutorial's bottom right houses show with the camera at the bottom
+# (its index of children is cut short: what lies past its last row is kept
+# there, and a query past that row used to skip it)
+shop = view_of(run("skate:tutorial", 226, "60:ok", shots=[225], env=cam(-2342, -1325, 220))[2], 225)[40:130, 0:90]
+kinds = len(np.unique(shop.reshape(-1, 3), axis=0))
+check("the skate tutorial's corner houses", kinds > 25, f"{kinds} colours where the houses are (the ground has 8)")
+
+# the island kept up as the camera moves is the island drawn from scratch
+# (play.c's CI_DIFF; CI_PATH flies the player through the streets by the
+# skate park and past the tutorial's signs): the map's live children were
+# made from their origin alone (the clips' nominal bounds are not in the
+# data), so houses, signs and lanterns showed up late at the edges
+out, err, _ = run("overworld@hub", 720, env={"CI_PATH": "4;-450,860;-1300,860;-1300,650;-700,650;-700,780;150,780;150,600", "CI_DIFF": "3"})
+bad = [] if "scene overworld:" in out else ["not on the island"]
+for line in err.splitlines():
+ m = re.match(r"diff f\d+: (\d+) px .*, (\d+) children missing, (\d+) items left for later, layer (\d+) px", line)
+ if m and (int(m[2]) or int(m[4]) or (int(m[1]) and not int(m[3]))): # (what the cache leaves for the next frame may differ)
+ bad.append(line)
+check("the island drawn as the camera moves is the island drawn from scratch", not bad, "\n".join(bad[:5]))
+
+# once the view is still in the busiest streets, the scenery drawn again in
+# front of someone (a house before a sign) is all there: its masks were not
+# counted in what a frame needs from the cache, and one left out was not
+# tried again
+_, err, _ = run("overworld@hub", 420, env={"CI_PATH": "4;-1240,660;-1380,660;-1170,590;-750,450;-680,450", "CI_HOLD": "30"})
+held = [line for line in err.splitlines() if line.startswith("held ")]
+check("the busiest streets are whole once the view is still", len(held) == 5 and all(line.endswith(" left 0") for line in held), "\n".join(held))
+
# random keys where a crash once was (the trophy room's entities outnumbered
# their state records), and in every kind of scene
for scene in ("interior:trophyRoom", "overworld@hub", "overworld@pingponghouse1", "skate:park2", "rugby", "archery"):
@@ -123,6 +303,40 @@ for scene in ("interior:trophyRoom", "overworld@hub", "overworld@pingponghouse1"
run(scene, 1500, random_keys(scene, 1, 1500))
print(("ok " if len(failures) == before else "FAIL ") + f"random keys in {scene}")
+# the player can always move, however he goes in and out of doors (play.c's
+# CI_WANDER plays at random: arrows held through the change, OK held at a door,
+# the map opened as a room fades in...): the island's walls stayed in the
+# physics world, filling it after a few doors, and the player got no body, in
+# a room or back on the island
+for place, seed in (("trophy", 0), ("pingpongdojo", 0), ("locksmith", 0), ("koma1", 1)):
+ out, err, _ = run(f"overworld@{place}", 3000, env={"CI_WANDER": str(seed), "CI_STUCK": "1", "CI_LOG": "1"})
+ rooms = sum(" scene interior" in line for line in err.splitlines())
+ stuck = [line for line in out.splitlines() if line.startswith(("STUCK", "BODY"))]
+ check(f"in and out of the doors from {place}", rooms >= 8 and not stuck, f"{rooms} rooms, {stuck[:2]}")
+
+
+def at(out, frame):
+ """Where the player is at a frame (play.c's CI_STUCK=2)."""
+ for line in out.splitlines():
+ if line.startswith(f"f{frame} "):
+ x, y = line.split(" at ")[1].split()[0].split(",")
+ return float(x), float(y)
+ return None
+
+
+# a room entered by its far door has the player at that door (a hallway, back
+# from its dojo), and the game opens on the island where he went in: a room's
+# exit saved a place of the room, and the island then opened on the dock
+saves = tempfile.mkdtemp(prefix="ci_check_")
+out, err, _ = run("overworld@pingpongdojo", 300, "10-25:up,30:ok,60-140:up,150-175:down,280:home",
+ env={"CI_TUTORIAL_DONE": "1", "CI_STUCK": "2", "CI_LOG": "1"}, saves=saves)
+p = at(out, 200)
+check("back from the dojo at the hallway's far end", "@pingpongdojohallwayn" in err and p and p[1] < 60, f"at {p}")
+out, _, _ = run(None, 20, env={"CI_STUCK": "2"}, saves=saves)
+p = at(out, 10)
+check("the game opens at the door he went in by", p and abs(p[0] - 1045) < 30 and abs(p[1] + 1080) < 30, f"at {p}")
+shutil.rmtree(saves, ignore_errors=True)
+
if failures:
print("\n".join(failures))
sys.exit(1)
diff --git a/games/championisland/tests/play.c b/games/championisland/tests/play.c
index ea76c5a2..60adb714 100644
--- a/games/championisland/tests/play.c
+++ b/games/championisland/tests/play.c
@@ -4,11 +4,16 @@
* [--out DIR] [--saves DIR] [--fresh]
*
* Keys: left right up down ok back home pause. "a-b:key" holds the key from frame a to b, "a:key" for one frame.
- * Screenshots are DIR/shot_<frame>.ppm; --gif saves every k-th frame of a range as DIR/f_<frame>.ppm. */
+ * Screenshots are DIR/shot_<frame>.ppm; --gif saves every k-th frame of a range as DIR/f_<frame>.ppm.
+ * CI_WANDER=seed plays keys itself (in and out of doors), CI_STUCK=1 says when the player cannot move,
+ * CI_TUTORIAL_DONE=1 starts past the tutorial.
+ * CI_CAM moves the camera of the sports that have one (see host_cam), CI_DROPS tells the frames whose
+ * draw list was full. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
+#include <math.h>
#include "../src/ent.h"
#include "../src/spr.h"
#include "../src/phys.h"
@@ -35,7 +40,247 @@ static uint32_t key_bit(const char *s) {
}
void world_census(void);
+int world_redo(char *where, int size);
+int world_layer_diff(int box[4]);
+extern uint16_t host_fb[SCREEN_W * SCREEN_H];
+
+/* CI_DIFF=k: every k frames on the island, the frame kept up as the camera
+ * moved against one made from scratch there (the layer painted again, the
+ * live children streamed again); prints where they differ (CI_DIFF_OUT=DIR:
+ * saves both) */
+static void diff_check(int f) {
+ static uint16_t kept[SCREEN_W * SCREEN_H];
+ extern int gfx_missing;
+ int missing = gfx_missing;
+ memcpy(kept, host_fb, sizeof kept);
+ char where[96];
+ int kids = world_redo(where, sizeof where);
+ if (kids < 0) return;
+ for (int k = 0; k < 2 || (gfx_missing && k < 6); k++) { /* what one leaves for the next frame (not cached) comes */
+ gfx_redraw_all();
+ game_draw();
+ }
+ if (gfx_missing) return; /* (the frame made from scratch did not fit in the cache either) */
+ int n = 0, x0 = SCREEN_W, y0 = SCREEN_H, x1 = -1, y1 = -1;
+ for (int y = 0; y < SCREEN_H; y++)
+ for (int x = 0; x < SCREEN_W; x++)
+ if (kept[y * SCREEN_W + x] != host_fb[y * SCREEN_W + x]) {
+ n++;
+ if (x < x0) x0 = x;
+ if (x > x1) x1 = x;
+ if (y < y0) y0 = y;
+ if (y > y1) y1 = y;
+ }
+ int lb[4], ln = world_layer_diff(lb);
+ if (!n && !kids && !ln) return;
+ fprintf(stderr, "diff f%d: %d px in %d,%d-%d,%d, %d children missing, %d items left for later, layer %d px in %d,%d-%d,%d, %s\n", f, n,
+ x0, y0, x1, y1, kids, missing, ln, lb[0], lb[1] + VIEW_Y, lb[2], lb[3] + VIEW_Y, where);
+ const char *dir = getenv("CI_DIFF_OUT");
+ if (dir && n) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/diff_%05d_ref.ppm", dir, f);
+ host_shot(p);
+ uint16_t ref[SCREEN_W * SCREEN_H];
+ memcpy(ref, host_fb, sizeof ref);
+ memcpy(host_fb, kept, sizeof kept);
+ snprintf(p, sizeof p, "%s/diff_%05d_kept.ppm", dir, f);
+ host_shot(p);
+ memcpy(host_fb, ref, sizeof ref);
+ }
+}
void ent_stats(int *live, int *states);
+extern unsigned gfx_drops;
+
+/* CI_CAM="f0:hold:x0:x1:dx:y0:y1:dy": from frame f0 the scene's camera puts
+ * the map at each (x, y) of the grid (rows of x first), `hold` frames each
+ * (the sports with a camera ask through host_cam) */
+static int frame_now;
+bool host_cam(float *x, float *y) {
+ const char *s = getenv("CI_CAM");
+ int f0, hold;
+ float x0, x1, dx, y0, y1, dy;
+ if (!s || sscanf(s, "%d:%d:%f:%f:%f:%f:%f:%f", &f0, &hold, &x0, &x1, &dx, &y0, &y1, &dy) != 8 || hold < 1 || frame_now < f0) return false;
+ int nx = dx ? (int)((x1 - x0) / dx + 1.001f) : 1, ny = dy ? (int)((y1 - y0) / dy + 1.001f) : 1;
+ int i = (frame_now - f0) / hold;
+ if (nx < 1 || ny < 1 || i >= nx * ny) i = nx * ny - 1;
+ *x = x0 + dx * (i % nx);
+ *y = y0 + dy * (i / nx);
+ return true;
+}
+
+/* CI_WANDER=seed: the keys of a player going in and out of the doors near
+ * them, at random (tests/check.py): arrows held through a scene change, OK
+ * tapped, held or pressed early at a door, the map opened as a room fades in,
+ * a walk or a talk in the room, then an exit, or the same door again at once */
+static uint32_t rng = 1;
+static int rnd(int n) { rng ^= rng << 13; rng ^= rng >> 17; rng ^= rng << 5; return (int)(rng % (uint32_t)n); }
+static const uint32_t DIR_KEYS[8] = {K_RIGHT, K_RIGHT | K_DOWN, K_DOWN, K_DOWN | K_LEFT, K_LEFT, K_LEFT | K_UP, K_UP, K_UP | K_RIGHT};
+static struct {
+ const SceneDef *def;
+ uint32_t ticks;
+ int phase, t, len; /* phase: 0 carry on, 1 wander, 2 to a door, 3 at the door */
+ uint32_t carry, keys; /* keys kept through a scene change, keys now */
+ int back_at, back_close; /* Back pressed at, closed at (frames of the phase) */
+ NodeId door;
+ float best;
+ int noprog, jig, jig_keys, ok_mode, ok_t;
+} pilot;
+
+static NodeId player_ent(void) { return game.def && game_is_world(game.name) ? ent_first(C_overworldPlayer) : 0; }
+
+static const char *door_name(NodeId n) {
+ uint16_t T = nodes[n].T, s = NONE16;
+ if (comp_has(T, C_scenePortal)) s = comp_str(T, C_scenePortal, F_name);
+ else if (comp_has(T, C_sceneTrigger)) s = comp_str(T, C_sceneTrigger, F_name);
+ return s != NONE16 ? str(s) : NULL;
+}
+
+/* a door of the island or the room (not a sport) near the player: the nearest or the next */
+static NodeId pick_door(NodeId p) {
+ float px, py;
+ ent_pos(p, &px, &py);
+ NodeId best[2] = {0, 0};
+ float bd[2] = {300 * 300, 300 * 300};
+ for (int i = 0; i < ent_count(); i++) {
+ NodeId n = ent_at(i);
+ const char *nm = n ? door_name(n) : NULL;
+ if (!nm || !node_visible_chain(n) || (strncmp(nm, "interior", 8) && strncmp(nm, "overworld", 9))) continue;
+ float x, y;
+ ent_pos(n, &x, &y);
+ float d = (x - px) * (x - px) + (y - py) * (y - py);
+ if (d < bd[0]) { bd[1] = bd[0]; best[1] = best[0]; bd[0] = d; best[0] = n; }
+ else if (d < bd[1]) { bd[1] = d; best[1] = n; }
+ }
+ return best[1] && rnd(2) ? best[1] : best[0];
+}
+
+static uint32_t wander_keys(void) {
+ NodeId p = player_ent();
+ if (!p) return 0;
+ if (game.def != pilot.def || game.ticks < pilot.ticks) { /* a new scene */
+ pilot.def = game.def;
+ pilot.carry = rnd(2) ? pilot.keys & (K_LEFT | K_RIGHT | K_UP | K_DOWN | K_ACTION) : 0;
+ pilot.phase = 0;
+ pilot.t = 0;
+ pilot.len = rnd(3) ? rnd(25) : 0;
+ pilot.back_at = rnd(4) ? -1 : rnd(12);
+ pilot.back_close = pilot.back_at + 2 + rnd(30);
+ pilot.door = 0;
+ }
+ pilot.ticks = game.ticks;
+ uint32_t k = 0;
+ if (pilot.back_at >= 0 && (pilot.t == pilot.back_at || pilot.t == pilot.back_close)) k |= K_BACK;
+ if (menus_active()) { pilot.t++; return k | (pilot.t > pilot.back_close + 5 && pilot.t % 7 == 0 ? K_BACK : 0); }
+ if (dialog_active()) { pilot.t++; return k | (pilot.t % 6 < 2 ? K_ACTION : 0); }
+ pilot.t++;
+ switch (pilot.phase) {
+ case 0: /* the keys held through the change */
+ k |= pilot.carry;
+ if (pilot.t >= pilot.len) { pilot.phase = 1; pilot.t = 0; pilot.len = rnd(3) ? rnd(!strcmp(game.name, "interior") ? 90 : 20) : 0; pilot.jig = 0; }
+ break;
+ case 1: /* a walk, a talk */
+ if (pilot.jig <= 0) { pilot.jig = 3 + rnd(20); pilot.jig_keys = rnd(3) ? DIR_KEYS[rnd(8)] : 0; }
+ pilot.jig--;
+ k |= pilot.jig_keys | (rnd(12) ? 0 : K_ACTION);
+ if (pilot.t >= pilot.len) {
+ pilot.door = pick_door(p);
+ pilot.phase = 2; pilot.t = 0; pilot.best = 1e9f; pilot.noprog = 0; pilot.jig = 0;
+ pilot.ok_mode = rnd(4); /* 0 tap, 1 held from afar, 2 held long with arrows, 3 double tap */
+ pilot.ok_t = 0;
+ }
+ break;
+ case 2: /* to the door */
+ case 3: {
+ if (!pilot.door || !(nodes[pilot.door].flags & NF_USED) || !door_name(pilot.door)) { pilot.phase = 1; pilot.t = 0; pilot.len = 10; break; }
+ float px, py, dx, dy;
+ ent_pos(p, &px, &py);
+ ent_pos(pilot.door, &dx, &dy);
+ dx -= px; dy -= py;
+ float d = dx * dx + dy * dy;
+ Ent *de = ent_peek(pilot.door);
+ bool in_door = de && de->ntrig > 0;
+ if (in_door && comp_has(nodes[pilot.door].T, C_scenePortal)) {
+ pilot.phase = 3;
+ pilot.ok_t++;
+ /* OK let go in the door opens it */
+ if (pilot.ok_mode == 0) k |= pilot.ok_t == 2 ? K_ACTION : 0;
+ else if (pilot.ok_mode == 1) k |= pilot.ok_t < 3 ? K_ACTION : 0;
+ else if (pilot.ok_mode == 2) k |= (pilot.ok_t < 25 ? K_ACTION : 0) | (pilot.ok_t < 30 ? DIR_KEYS[rnd(8)] : 0);
+ else k |= pilot.ok_t == 2 || pilot.ok_t == 5 ? K_ACTION : 0;
+ if (pilot.ok_t > 60) { pilot.phase = 1; pilot.t = 0; pilot.len = 5; }
+ break;
+ }
+ if (pilot.ok_mode == 1 && d < 60 * 60) k |= K_ACTION; /* OK held on the way */
+ if (d < pilot.best - 1) { pilot.best = d; pilot.noprog = 0; } else pilot.noprog++;
+ if (pilot.noprog > 8 && pilot.jig <= 0) { pilot.jig = 5 + rnd(15); pilot.jig_keys = DIR_KEYS[rnd(8)]; pilot.noprog = 0; pilot.best = 1e9f; }
+ if (pilot.jig > 0) { pilot.jig--; k |= pilot.jig_keys; break; }
+ if (dx > 2) k |= K_RIGHT;
+ if (dx < -2) k |= K_LEFT;
+ if (dy > 2) k |= K_DOWN;
+ if (dy < -2) k |= K_UP;
+ if (pilot.t > 400) { pilot.phase = 1; pilot.t = 0; pilot.len = 20; }
+ break;
+ }
+ }
+ pilot.keys = k;
+ return k;
+}
+
+/* CI_STUCK: says when the player cannot move (STUCK): arrows held for 30
+ * frames or more (all four ways, so not a wall), no dialogue or menu, and he
+ * stays where he is; or he has no physics body. CI_STUCK=2 also prints where
+ * he is every 10 frames */
+static struct { const SceneDef *def; uint32_t ticks; NodeId p; float x, y; int still, dirs[4], nobody; } probe;
+static int stuck_count;
+static void stuck_probe(int f) {
+ NodeId p = player_ent();
+ if (!p || game.def != probe.def || game.ticks < probe.ticks || p != probe.p) { /* a new scene */
+ memset(&probe, 0, sizeof probe);
+ probe.def = game.def;
+ probe.p = p;
+ if (p) ent_pos(p, &probe.x, &probe.y);
+ probe.ticks = game.ticks;
+ return;
+ }
+ probe.ticks = game.ticks;
+ float x, y;
+ ent_pos(p, &x, &y);
+ Ent *e = ent_peek(p);
+ int nb = 0;
+ for (int b = 0; b < BODY_MAX; b++) {
+ nb += bodies[b].used;
+ /* a body is the scene's: its entity's (it knows it) or a wall's */
+ NodeId u = bodies[b].user, r = u;
+ while (r && nodes[r].parent) r = nodes[r].parent;
+ Ent *ue = u ? ent_peek(u) : NULL;
+ if (bodies[b].used && u && (r != game.root || !ue || ue->body != b)) printf("BODY f%d %d of node %u not the scene's\n", f, b, u);
+ }
+ bool overlay = dialog_active() || menus_active(); /* the scene's systems wait */
+ if (!overlay) {
+ if (e && e->body >= 0) probe.nobody = 0;
+ else if (++probe.nobody == 3) {
+ stuck_count++;
+ printf("STUCK f%d %s:%s no body, bodies %d\n", f, game.name, game.variant, nb);
+ }
+ }
+ if (atoi(getenv("CI_STUCK")) > 1 && f % 10 == 0)
+ printf("f%d %s:%s keys %x at %.1f,%.1f body %d\n", f, game.name, game.variant, host_keys, x, y, e ? e->body : -9);
+ if (overlay || fabsf(x - probe.x) + fabsf(y - probe.y) > .01f) {
+ probe.still = 0;
+ memset(probe.dirs, 0, sizeof probe.dirs);
+ } else if (host_keys & (K_LEFT | K_RIGHT | K_UP | K_DOWN)) {
+ probe.still++;
+ for (int d = 0; d < 4; d++) if (host_keys & (1u << d)) probe.dirs[d]++; /* K_LEFT, K_RIGHT, K_UP, K_DOWN */
+ if (probe.still >= 30 && probe.dirs[0] >= 4 && probe.dirs[1] >= 4 && probe.dirs[2] >= 4 && probe.dirs[3] >= 4) {
+ stuck_count++;
+ printf("STUCK f%d %s:%s at %.1f,%.1f for %d frames, body %d, bodies %d\n", f, game.name, game.variant, x, y, probe.still,
+ e ? e->body : -9, nb);
+ probe.still = -1000000; /* told once */
+ }
+ }
+ probe.x = x;
+ probe.y = y;
+}
int main(int argc, char **argv) {
const char *scene = NULL, *out = "build/play", *saves = "build/play/saves", *shots = "", *gif = NULL;
@@ -70,15 +315,65 @@ int main(int argc, char **argv) {
int g0 = 0, g1 = -1, gs = 1;
if (gif) sscanf(gif, "%d-%d:%d", &g0, &g1, &gs);
ci_init();
- if (getenv("CI_ENDING")) store_set_bool("outro_VIDEO_SEEN", true); /* the island after the ending */
+ if (getenv("CI_ENDING")) { /* the island after the ending: seven golds, every film seen */
+ static const char *const sports[7] = {"archery", "climbing", "marathon", "pingpong", "rugby", "skate", "swim"};
+ char k[48];
+ for (int i = 0; i < 7; i++) {
+ snprintf(k, sizeof k, "%s_rating", sports[i]);
+ store_set_num(k, 3);
+ snprintf(k, sizeof k, "%sintro_VIDEO_SEEN", sports[i]);
+ store_set_bool(k, true);
+ snprintf(k, sizeof k, "%soutro_VIDEO_SEEN", sports[i]);
+ store_set_bool(k, true);
+ }
+ store_set_bool("TUTORIAL_DONE", true);
+ store_set_bool("intro_VIDEO_SEEN", true);
+ store_set_bool("outro_VIDEO_SEEN", true);
+ }
+ if (getenv("CI_TUTORIAL_DONE")) { /* a player past the tutorial, the game opening on the island */
+ store_set_bool("TUTORIAL_BEGIN", true);
+ store_set_bool("TUTORIAL_DONE", true);
+ store_set_bool("intro_VIDEO_SEEN", true);
+ }
+ /* CI_STORE="swim_rating=3,RAIN=complete": saved values to start with (numbers, else strings) */
+ if (getenv("CI_STORE")) {
+ char *s = strdup(getenv("CI_STORE"));
+ for (char *t = strtok(s, ","); t; t = strtok(NULL, ",")) {
+ char *eq = strchr(t, '='), *end;
+ if (!eq) continue;
+ *eq = 0;
+ double v = strtod(eq + 1, &end);
+ if (*end || end == eq + 1) store_set_str(t, eq + 1);
+ else store_set_num(t, (float)v);
+ }
+ free(s);
+ }
if (scene) game_go(scene);
+ const char *wander = getenv("CI_WANDER"), *stuck = getenv("CI_STUCK");
+ if (wander) rng = 2654435761u * (uint32_t)(atoi(wander) + 1);
for (int f = 0; f < frames && game_running; f++) {
+ /* CI_DLG=npc:node starts that dialogue (its layout, without walking to them) */
+ if (getenv("CI_DLG") && f == 5) {
+ char b[64], *c;
+ snprintf(b, sizeof b, "%s", getenv("CI_DLG"));
+ if ((c = strchr(b, ':'))) { *c = 0; dialog_start(str_id(b), str_id(c + 1)); }
+ }
+ frame_now = f;
host_keys = 0;
for (int i = 0; i < nholds; i++)
if (f >= holds[i].a && f <= holds[i].b) host_keys |= holds[i].k;
+ if (wander) host_keys |= wander_keys();
extern uint64_t z_bytes;
uint64_t zb0 = z_bytes;
game_tick();
+ if (stuck) stuck_probe(f);
+ /* CI_POS="x,y": the player moved there (map space) after the first tick */
+ if (f == 0 && getenv("CI_POS") && ent_first(C_overworldPlayer)) {
+ float x = 0, y = 0;
+ sscanf(getenv("CI_POS"), "%f,%f", &x, &y);
+ ent_set_pos(ent_first(C_overworldPlayer), x, y);
+ sys_camera_snap();
+ }
if (getenv("CI_CONSIST")) {
extern NodeId node_unlisted(void);
static bool told;
@@ -90,6 +385,21 @@ int main(int argc, char **argv) {
}
}
game_draw();
+ static unsigned drops;
+ if (gfx_drops != drops && getenv("CI_DROPS")) fprintf(stderr, "f%d: %u items not drawn\n", f, gfx_drops - drops);
+ drops = gfx_drops;
+ if (getenv("CI_DIFF") && f % atoi(getenv("CI_DIFF")) == 0) diff_check(f);
+ extern int fly_held;
+ if (fly_held >= 0) { /* CI_PATH with CI_HOLD: the view once still at a point (its hash, what it left out) */
+ extern int gfx_missing;
+ uint32_t h = 2166136261u;
+ for (int i = 0; i < SCREEN_W * SCREEN_H; i++) h = (h ^ host_fb[i]) * 16777619u;
+ char p[512];
+ snprintf(p, sizeof p, "%s/held_%03d.ppm", out, fly_held);
+ if (getenv("CI_HOLDSHOT")) host_shot(p);
+ fprintf(stderr, "held %d held_%03d.ppm %08x left %d\n", fly_held, fly_held, h, gfx_missing);
+ fly_held = -1;
+ }
uint64_t zf = z_bytes - zb0;
if (getenv("CI_ZFRAME") && zf) fprintf(stderr, "f%d decoded %.1f KB\n", f, zf / 1024.0);
if (zf > z_max) z_max = zf;
@@ -118,6 +428,7 @@ int main(int argc, char **argv) {
extern int gfx_peak_items, gfx_peak_affs;
extern unsigned node_alloc_fails;
if (node_alloc_fails) printf("NODE POOL FULL: %u nodes not made\n", node_alloc_fails);
+ if (gfx_drops) printf("DRAW LIST FULL: %u items not drawn\n", gfx_drops);
printf("frames done: %u ticks, nodes %u (peak %u), entities peak %d (states %d), bodies %d, items %d affs %d, cache %u, scene %s:%s\n",
game.ticks, node_count(), peak_nodes, peak_live, peak_states, peak_bodies, gfx_peak_items, gfx_peak_affs, spr_cache_used(), game.name,
game.variant);
@@ -127,5 +438,6 @@ int main(int argc, char **argv) {
(double)z_opens / frames, z_max / 1024.0, z_heavy);
}
if (getenv("CI_CENSUS")) world_census();
+ if (stuck) printf("stuck %d\n", stuck_count);
return 0;
}
diff --git a/games/championisland/tools/extract.js b/games/championisland/tools/extract.js
index 03f99bc7..f2b4b104 100644
--- a/games/championisland/tools/extract.js
+++ b/games/championisland/tools/extract.js
@@ -60,6 +60,13 @@ function bake(id) {
return [kind ? kind[1] : 'X', d];
});
}
+ function place(c) {
+ const tr = { x: r2(c.x), y: r2(c.y) };
+ if (c.scaleX !== 1) tr.sx = r2(c.scaleX); if (c.scaleY !== 1) tr.sy = r2(c.scaleY);
+ if (c.rotation) tr.r = r2(c.rotation); if (c.skewX) tr.kx = r2(c.skewX); if (c.skewY) tr.ky = r2(c.skewY);
+ if (c.regX) tr.rx = r2(c.regX); if (c.regY) tr.ry = r2(c.regY);
+ return tr;
+ }
function childDesc(c, idx) {
const n = { i: idx };
const sym = protoName.get(Object.getPrototypeOf(c));
@@ -71,16 +78,14 @@ function bake(id) {
else if (c instanceof cj.MovieClip) { n.t = 'm'; n.mode = c.mode; n.sp = c.startPosition; n.loop = c.loop; n.cf = c.currentFrame; }
else if (c instanceof cj.Container) n.t = 'c';
else n.t = '?';
- const tr = { x: r2(c.x), y: r2(c.y) };
- if (c.scaleX !== 1) tr.sx = r2(c.scaleX); if (c.scaleY !== 1) tr.sy = r2(c.scaleY);
- if (c.rotation) tr.r = r2(c.rotation); if (c.skewX) tr.kx = r2(c.skewX); if (c.skewY) tr.ky = r2(c.skewY);
- if (c.regX) tr.rx = r2(c.regX); if (c.regY) tr.ry = r2(c.regY);
+ const tr = place(c);
if (c.alpha !== 1) tr.a = r2(c.alpha); if (!c.visible) tr.v = 0;
if (c.compositeOperation) tr.co = c.compositeOperation;
if (c.filters && c.filters.length) tr.fl = c.filters.map(f => f.constructor.name);
if (c.name) tr.nm = c.name;
n.tr = tr;
- if (c.mask) n.mask = 1;
+ /* a mask: its path, placed in the parent's space as the child is */
+ if (c.mask) n.mask = { g: c.mask.graphics ? gfx(c.mask.graphics) : [], tr: place(c.mask) };
if (c.hitArea) n.hit = 1;
return n;
}
diff --git a/games/championisland/tools/pack.py b/games/championisland/tools/pack.py
index 780186e7..16a678d4 100644
--- a/games/championisland/tools/pack.py
+++ b/games/championisland/tools/pack.py
@@ -9,7 +9,9 @@ needs goes in one blob:
- sprites: every image the libraries place, as 8-bit palette indices. Small
ones are packed in LZMA "banks" of at most BANK bytes, decoded into a cache
on demand; large backgrounds are LZMA "streams" decoded row by row into the
- background layer. Both use a dictionary of at most DICT bytes.
+ background layer. Both use a dictionary of at most DICT bytes. A very tall
+ stream is cut into strips of about STRIP_BYTES compressed, each its own LZMA
+ stream, so that a row deep down is reached without decoding every row above.
- symbols: bitmaps, shapes, texts and clips. A clip's timeline is a list of
keyframes per child slot, labels, frame scripts (stop, dispatchEvent) and its
components (the Animate "this.T = {...}" data);
@@ -36,6 +38,8 @@ EX = os.path.join(ROOT, 'build/ex')
BANK = 16384 # decoded size of a sprite bank at most
DICT = 8192 # LZMA dictionary: the decoder's ring buffer
STREAM_MIN = 20000 # sprites with more pixels than this are streamed backgrounds
+STRIP_BYTES = 8000 # a stream taller than STRIP_MIN_H starts afresh once a strip compresses to this much,
+STRIP_MIN_H = 512 # so that a row deep down costs no more decoding than that (the climbing vista)
SHEETS = ['preload-sprite.png', 'shared-sprite.png', 'cutscene-sprite.png', 'overworld-sprite.png', 'archery-sprite.png',
'climbing-sprite.png', 'marathon-sprite.png', 'pingpong-sprite.png', 'rugby-sprite.png', 'skate-sprite.png', 'swim-sprite.png']
@@ -182,13 +186,65 @@ def mat_mul(m, n):
return (a * A + c * B, b * A + d * B, a * C + c * D, b * C + d * D, a * TX + c * TY + tx, b * TX + d * TY + ty)
+# ------------------------------------------------------------------ masks
+def mask_box(m):
+ """The rectangle a mask's path is, in its parent's space (x0, y0, x1, y1), or None."""
+ if [op for op, _ in m['g'] if op not in ('P', 'Z')] != ['M', 'L', 'L', 'L']:
+ return None
+ a, b, c, d, tx, ty = matrix(m['tr'])
+ if b or c:
+ return None
+ pts = [(round(a * p.get('x', 0) + tx, 3), round(d * p.get('y', 0) + ty, 3)) for op, p in m['g'] if op in ('M', 'L')]
+ if any((p[0] == q[0]) == (p[1] == q[1]) for p, q in zip(pts, pts[1:] + pts[:1])):
+ return None
+ return min(p[0] for p in pts), min(p[1] for p in pts), max(p[0] for p in pts), max(p[1] for p in pts)
+
+
+# A mask is a clipping path. A bitmap that a rectangle masks, the same on every
+# frame (Lucky's climbing statue shows only the pedestal of the champion's),
+# becomes the part of its image the mask shows: a symbol of its own, after all
+# the others. Masks that move are not kept (the child is drawn whole).
+CUTS = [] # (lib, name) of the cut bitmaps
+for lib, _ in LIBS:
+ syms = LIB[lib]['syms']
+ for k, s in list(syms.items()):
+ masked = defaultdict(list)
+ for fr in s.get('frames') or []:
+ for c in fr:
+ if c.get('mask'):
+ masked[c['i']].append(c)
+ for cs in masked.values():
+ c = cs[0]
+ still = all(json.dumps([o.get('sym'), o['tr'], o['mask']]) == json.dumps([c.get('sym'), c['tr'], c['mask']]) for o in cs)
+ sheet = syms.get(c.get('sym'), {}).get('sheet') if c['t'] == 'b' else None
+ box = mask_box(c['mask'])
+ a, b, cc, d, tx, ty = matrix(c['tr'])
+ if not still or not sheet or not box or b or cc or a <= 0 or d <= 0:
+ continue
+ sh, x, y, w, h = sheet
+ u0, v0 = max(0, math.floor((box[0] - tx) / a + .5)), max(0, math.floor((box[1] - ty) / d + .5))
+ u1, v1 = min(w, math.floor((box[2] - tx) / a + .5)), min(h, math.floor((box[3] - ty) / d + .5))
+ if u0 >= u1 or v0 >= v1:
+ continue
+ name = '%s.%s' % (k, c['sym'])
+ syms[name] = {'t': 'b', 'sheet': (sh, x + u0, y + v0, u1 - u0, v1 - v0)}
+ CUTS.append((lib, name))
+ for o in cs:
+ del o['mask']
+ o['sym'] = name
+ o['tr'] = dict(o['tr'], x=round(o['tr'].get('x', 0) + a * u0, 3), y=round(o['tr'].get('y', 0) + d * v0, 3))
+
# ------------------------------------------------------------------ symbols
SYMS = [] # (lib, name)
SYM_ID = {}
for name, _ in LIBS:
for k in LIB[name]['syms']:
- SYM_ID[(name, k)] = len(SYMS)
- SYMS.append((name, k))
+ if (name, k) not in CUTS:
+ SYM_ID[(name, k)] = len(SYMS)
+ SYMS.append((name, k))
+for key in CUTS:
+ SYM_ID[key] = len(SYMS)
+ SYMS.append(key)
# sprites: every bitmap symbol with an image
SPR_ID, SPR = {}, [] # key (sheet,x,y,w,h) -> id
@@ -1255,11 +1311,29 @@ bank_offs = []
for raw in banks:
comp = lzma_raw(raw, len(raw))
bank_offs.append((blob.add(comp, 1), len(comp), len(raw)))
-stream_off = {}
+
+
+def strips(px):
+ """Where a stream's strips start: rows are added 8 at a time while the strip compresses to STRIP_BYTES."""
+ h, cuts = px.shape[0], [0]
+ while h > STRIP_MIN_H:
+ y = cuts[-1] + 8
+ while y < h and len(lzma_raw(px[cuts[-1]:y + 8].tobytes(), DICT)) <= STRIP_BYTES:
+ y += 8
+ if y >= h:
+ break
+ cuts.append(y)
+ return cuts + [h]
+
+
+stream_off = {} # per stream, its strips: (offset, compressed size, raw size)
for sp in streams:
- raw = sprite_pixels(sp).tobytes()
- comp = lzma_raw(raw, DICT)
- stream_off[sp] = (blob.add(comp, 1), len(comp), len(raw))
+ px = sprite_pixels(sp)
+ cuts = strips(px)
+ stream_off[sp] = []
+ for y0, y1 in zip(cuts, cuts[1:]):
+ comp = lzma_raw(px[y0:y1].tobytes(), DICT)
+ stream_off[sp].append((blob.add(comp, 1), len(comp), (y1 - y0) * px.shape[1]))
# scenery images: columns of BAND_W pixels, each its own stream, so that painting
# a strip of the world decodes only the columns it needs
band_off = {}
@@ -1312,7 +1386,7 @@ spr_bin = bytearray()
for sp, rec in enumerate(SPR):
sh, x, y, w, h = rec['key']
if sp in stream_off:
- o, cl, rl = stream_off[sp]
+ o, cl, rl = stream_off[sp][0]
spr_bin += struct.pack('<HHBBHII', w, h, sh, 1, 0, o, rle_size(sp))
elif sp in band_off:
spr_bin += struct.pack('<HHBBHII', w, h, sh, 2, 0, band_off[sp], 0)
@@ -1333,7 +1407,9 @@ for b in range(len(banks)):
m = sorted(bank_members[b])
bm_offs.append(blob.add(struct.pack('<H', len(m)) + b''.join(struct.pack('<H', sp) for _, sp in m), 2))
off_bankspr = blob.add(b''.join(struct.pack('<I', o) for o in bm_offs))
-off_streams = blob.add(b''.join(struct.pack('<HIII', sp, *stream_off[sp]) for sp in streams))
+# the stream table: a record per strip, those of a stream in a row
+stream_recs = [(sp, *st) for sp in streams for st in stream_off[sp]]
+off_streams = blob.add(b''.join(struct.pack('<HIII', *r) for r in stream_recs))
pal_bin = bytearray()
for i in range(len(SHEETS)):
@@ -1605,7 +1681,7 @@ off_strdata = blob.add(bytes(str_data), 1)
HEADER = [
('magic', 0x31304943), ('nsheets', len(SHEETS)), ('pal', off_pal), ('nsprites', len(SPR)), ('sprites', off_spr),
- ('nbanks', len(banks)), ('banks', off_banks), ('nstreams', len(streams)), ('streams', off_streams),
+ ('nbanks', len(banks)), ('banks', off_banks), ('nstreams', len(stream_recs)), ('streams', off_streams),
('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),
@@ -1621,7 +1697,7 @@ h.append('enum { ' + ', '.join('H_%s' % k.upper() for k, _ in HEADER) + ', H_COU
h.append('#define BANK_MAX %d' % max(len(b) for b in banks))
h.append('#define SPRITE_COUNT %d' % len(SPR))
h.append('#define BANK_COUNT %d' % len(banks))
-h.append('#define STREAM_MAX %d' % max(stream_off[sp][2] for sp in streams))
+h.append('#define STREAM_MAX %d' % max(r[3] for r in stream_recs))
h.append('#define SPRITE_W_MAX %d' % max(r['key'][3] for r in SPR))
h.append('#define LZMA_DICT %d' % DICT)
h.append('enum { SYM_NONE, SYM_BITMAP, SYM_CLIP, SYM_SHAPE, SYM_CONT };')
@@ -1662,7 +1738,7 @@ open(os.path.join(ROOT, 'src/names.c'), 'w').write('\n'.join(names) + '\n')
# ------------------------------------------------------------------ report
tot_banks = sum(b[1] for b in bank_offs)
-tot_streams = sum(v[1] for v in stream_off.values())
+tot_streams = sum(r[2] for r in stream_recs)
print('symbols %d, sprites %d (%d banks %d KB, %d streams %d KB), mats %d, strings %d, exprs %d, dialog nodes %d, vars %d' % (
len(SYMS), len(SPR), len(banks), tot_banks // 1024, len(streams), tot_streams // 1024, len(MATS), len(strings), len(EXPRS), len(dlg_index), len(VARS)))
print({k: v // 1024 for k, v in STATS.items()})
@@ -1693,7 +1769,7 @@ if os.environ.get('PACK_REPORT'):
by = Counter()
for sp in streams:
libs = ','.join(sorted(SPR[sp]['libs']))
- by[libs] += stream_off[sp][1]
+ by[libs] += sum(st[1] for st in stream_off[sp])
print('streams by lib (KB):', {k: v // 1024 for k, v in by.most_common()})
by = Counter()
for sp, rec in enumerate(spr_rec):