Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
Champion Island: the island fills the screen, and fixes
Mason Chena90084715954
diff --git a/VERSION b/VERSIONindex 88c5fb89..347f5833 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.4.0+1.4.1diff --git a/docs/media/championisland.gif b/docs/media/championisland.gifindex b2b283dd..1ca50bc7 100644Binary files a/docs/media/championisland.gif and b/docs/media/championisland.gif differdiff --git a/docs/media/thumb_championisland.png b/docs/media/thumb_championisland.pngindex 397ee1d6..bb6158f2 100644Binary files a/docs/media/thumb_championisland.png and b/docs/media/thumb_championisland.png differdiff --git a/games/championisland/Makefile b/games/championisland/Makefileindex 8896f00f..8ea5b1d6 100644--- a/games/championisland/Makefile+++ b/games/championisland/Makefile@@ -2,6 +2,7 @@# make output/championisland.nwa# make check link it like the calculator does (output/championisland.bin)# make host build/play: the game on a computer, for tests and screenshots+# make test checks of the host build (tests/check.py)# make data regenerate src/data.bin (needs the doodle: DOODLE=path, Node + Playwright, Python + Pillow)Q ?= @CC = arm-none-eabi-gcc@@ -28,7 +29,7 @@ LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specsLDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_levelLDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel-.PHONY: build check clean host data+.PHONY: build check clean host data testbuild: $(BUILD_DIR)/championisland.nwa# the calculator gives apps 153676 bytes of RAM (data + bss)@@ -64,6 +65,10 @@ $(HOST_OUT): $(GAME) src/plat_host.c tests/play.c src/main.c src/data.S src/data$(Q) cc $(HOST_FLAGS) -fsanitize=address,undefined $(GAME) src/plat_host.c src/main.c tests/play.c src/data.S -lm -o $@@echo "HOST $@"+# the host build in scenes that once went wrong (tests/check.py)+test: $(HOST_OUT)+ python3 tests/check.py $(HOST_OUT)+data:cd tools && node extract.js $(DOODLE) ../build/expython3 tools/pack.py $(DOODLE)diff --git a/games/championisland/README.md b/games/championisland/README.mdindex c536199d..903533d8 100644--- a/games/championisland/README.md+++ b/games/championisland/README.md@@ -25,6 +25,7 @@* **The whole island:** every path, house and cave of the original, with its 57 rooms, its people, their stories and side quests, and the four teams.* **All seven sports:** Table Tennis, Skateboarding, Archery, Rugby, Artistic Swimming, Marathon and Climbing, with the same rules, champions and harder versions as the original.* **The original's look:** every picture and animation comes from the doodle itself, down to the rain over the Table Tennis village and the island's opening scene.+* **Full screen:** the island fills the calculator's whole screen, so you see more of it around Lucky than the original's wide frame shows. The sports and the insides of houses keep the original's frame.* **Medals and the map:** Back opens the island map with your scores and stars, and your team.* **Saved as you go:** quit at any time and you come back where you were. Your progress is also copied into `champion_saves.py`, so installing the app again doesn't erase it.diff --git a/games/championisland/docs/map.png b/games/championisland/docs/map.pngindex 5b7c10ad..19d19099 100644Binary files a/games/championisland/docs/map.png and b/games/championisland/docs/map.png differdiff --git a/games/championisland/src/dialog.c b/games/championisland/src/dialog.cindex d3505642..7f5b5396 100644--- a/games/championisland/src/dialog.c+++ b/games/championisland/src/dialog.c@@ -1,6 +1,9 @@/* The dialogue box (kitsune's dialog scene: Wq, Yq, Zq). */#include <math.h>#include <stdio.h>+#ifdef HOST+#include <stdlib.h>+#endif#include "ent.h"#include "font.h"@@ -155,6 +158,9 @@ static void show(uint16_t npc, uint16_t name) {void dialog_start(uint16_t npc, uint16_t node) {DNode d;if (!dnode_find(npc, node, &d)) return;+#ifdef HOST+ if (getenv("CI_LOG")) { extern uint32_t host_time; fprintf(stderr, "t%u dialog %s %s\n", host_time / 33, str(npc), str(node)); }+#endifactive = true;show(npc, node);}@@ -166,7 +172,7 @@ static void next(int opt) {if (shown < len - 1) { shown = len - 1; return; }if (opt < cur.nopts) show(cur_npc, rd16(cur.opts + 4 * opt));else active = false;- if (!active) return;+ if (!active) input_latch(); /* the OK that ended it opens no door */}void dialog_tick(void) {@@ -267,5 +273,6 @@ void dialog_tick(void) {void dialog_draw(void) {if (!active) return;- node_draw(root, (Mat){1.0f / 3, 0, 0, 1.0f / 3, 0, 0});+ /* at the top of the screen, as at the top of the stage */+ node_draw(root, (Mat){1.0f / 3, 0, 0, 1.0f / 3, 0, (float)gfx_view_top()});}diff --git a/games/championisland/src/ent.c b/games/championisland/src/ent.cindex 16fca420..dc4ddf2b 100644--- a/games/championisland/src/ent.c+++ b/games/championisland/src/ent.c@@ -9,7 +9,7 @@ const char *const dir_names[8] = {"e", "se", "s", "sw", "w", "nw", "n", "ne"};NodeId ent_map, ent_camera;-#define REG_MAX 320+#define REG_MAX 192 /* registered entities (153 at most seen) */typedef struct { NodeId n; uint16_t T; uint16_t state; } Reg; /* state: Ent + 1 */static Reg reg[REG_MAX];static int nreg;@@ -17,6 +17,7 @@ static Ent ents[ENT_MAX];static TriggerFn trigger_fn;static void on_free(NodeId n) { ent_unregister(n); }+static void on_made(NodeId n);void ent_reset(void) {memset(reg, 0, sizeof reg);@@ -25,6 +26,7 @@ void ent_reset(void) {ent_map = ent_camera = 0;trigger_fn = NULL;node_free_hook = on_free;+ node_partial_hook = on_made;phys_reset();}@@ -64,6 +66,22 @@ static void register_rec(NodeId n) {void ent_register_tree(NodeId root) { register_rec(root); }+/* a child a room or a menu made when its frame first showed it (node.c's+ * partial clips): an entity as if it had been there from the start */+static void made_rec(NodeId n) {+ ent_translate(n);+ uint16_t T = nodes[n].T;+ /* sr: places are markers for the designers */+ if (T != NONE16 && comp_has(T, C_location) && !comp_has(T, C_boundable)) nodes[n].alpha = 0;+ for (NodeId c = nodes[n].first; c; c = nodes[c].next) made_rec(c);+}+static void on_made(NodeId n) {+ for (NodeId a = nodes[n].parent; a; a = nodes[a].parent)+ if (nodes[a].T != NONE16 && comp_has(nodes[a].T, C_untraversable)) return;+ register_rec(n);+ made_rec(n);+}+void ent_unregister(NodeId n) {int i = reg_of(n);if (i < 0) return;@@ -82,6 +100,22 @@ void ent_unregister(NodeId n) {if (ents[k].trig[t] == n) { ents[k].trig[t] = ents[k].trig[--ents[k].ntrig]; t--; }}+/* the state record if it has one (never makes one): caches only use this,+ * so the records go to the entities that move, turn or hold triggers */+Ent *ent_peek(NodeId n) {+ int i = n ? reg_of(n) : -1;+ return i >= 0 && reg[i].state ? &ents[reg[i].state - 1] : NULL;+}++#ifdef HOST+/* tests: registered entities and state records in use */+void ent_stats(int *live, int *states) {+ *live = *states = 0;+ for (int k = 0; k < nreg; k++) if (reg[k].n) (*live)++;+ for (int k = 0; k < ENT_MAX; k++) if (ents[k].n) (*states)++;+}+#endif+Ent *ent_get(NodeId n) {int i = n ? reg_of(n) : -1;if (i < 0) return NULL;@@ -149,14 +183,14 @@ static NodeId map_of(NodeId e) {void ent_moved(NodeId e) {/* xj: this entity and its descendants forget their cached position and bounds */- Ent *s = nodes[e].ent ? ent_get(e) : NULL;+ Ent *s = ent_peek(e);if (s) s->bounds_valid = s->pos_valid = false;for (NodeId c = nodes[e].first; c; c = nodes[c].next)if (nodes[c].ent) ent_moved(c);}void ent_pos(NodeId e, float *x, float *y) {- Ent *s = nodes[e].ent ? ent_get(e) : NULL;+ Ent *s = ent_peek(e);if (s && s->pos_valid) { *x = s->px; *y = s->py; return; }NodeId m = map_of(e);Mat t = node_to(e, m);@@ -201,7 +235,7 @@ static NodeId find_bounds_child(NodeId n) {}bool ent_bounds(NodeId e, Rect *r) {- Ent *s = nodes[e].ent ? ent_get(e) : NULL;+ Ent *s = ent_peek(e);if (s && s->bounds_valid) { *r = s->bounds; return true; }if (!comp_has(nodes[e].T, C_boundable)) return false;NodeId b = find_bounds_child(e);@@ -436,6 +470,7 @@ void sys_move_direct(void) {if (!n || !comp_has(reg[i].T, C_velocity)) continue;if (comp_has(reg[i].T, C_collidable) && comp_has(reg[i].T, C_boundable)) continue;Ent *e = ent_get(n);+ if (!e) continue;float x, y;ent_pos(n, &x, &y);ent_set_pos(n, x + e->vx, y + e->vy);@@ -478,7 +513,7 @@ static float key_positional(NodeId c) {uint16_t T = nodes[c].T;if (comp_has(T, C_drawOrderOverride)) return comp_float(T, C_drawOrderOverride, F_drawOrder, 0);Rect r;- Ent *e = ent_get(c);+ Ent *e = ent_peek(c);if (comp_has(T, C_zObject) && comp_has(T, C_boundable) && comp_has(T, C_zBoundable) && ent_bounds(c, &r)) {float h = comp_float(T, C_zBoundable, F_height, 100);return r.y + h + (comp_has(T, C_velocity) ? (e && e->has_ground ? e->ground : 0) : e ? e->z : 0);@@ -577,6 +612,7 @@ void sys_player_movement(void) {NodeId n = reg[i].n;if (!n || !comp_has(reg[i].T, C_playerMovement) || !comp_has(reg[i].T, C_velocity)) continue;Ent *e = ent_get(n);+ if (!e) continue;float sp = comp_float(reg[i].T, C_playerMovement, F_speed, 1);float len = sqrtf(in.jx * in.jx + in.jy * in.jy);e->vx = len ? in.jx / len * sp * len : 0;@@ -618,6 +654,7 @@ void sys_tile_backgrounds(void) {int fc = comp_int(reg[i].T, C_tileBackground, F_frameCount, 0), fd = comp_int(reg[i].T, C_tileBackground, F_frameDuration, 1);if (fc <= 0) continue;Ent *e = ent_get(n);+ if (!e) continue;e->anim_t++;int f = (int)(e->anim_t / (fd > 0 ? fd : 1)) % fc;/* its children are clips: all show frame f * frameDuration */diff --git a/games/championisland/src/ent.h b/games/championisland/src/ent.hindex 9f19fbdd..dfcf4f1d 100644--- a/games/championisland/src/ent.h+++ b/games/championisland/src/ent.h@@ -32,7 +32,7 @@ int dir_of(float x, float y, bool four); /* mh(): 8 (or 4) way nameint dir_parse(const char *s);float dir_angle(int d); /* degrees */-#define ENT_MAX 96+#define ENT_MAX 48 /* records: only what moves, turns or holds a trigger (34 at most seen) */#define TRIG_MAX 4typedef struct {NodeId n;@@ -55,6 +55,7 @@ void ent_reset(void);void ent_register_tree(NodeId root); /* Mj on a subtree: finds entities */void ent_unregister(NodeId n); /* on removal (node.c calls it on free) */Ent *ent_get(NodeId n); /* state record (made on demand), NULL if not an entity */+Ent *ent_peek(NodeId n); /* the state record if it has one (never makes one) */bool ent_has(NodeId n, int comp);uint16_t ent_T(NodeId n);NodeId ent_first(int comp);diff --git a/games/championisland/src/game.c b/games/championisland/src/game.cindex 07592c08..fb0d3c2c 100644--- a/games/championisland/src/game.c+++ b/games/championisland/src/game.c@@ -19,7 +19,7 @@ static struct { int w, h; uint8_t sheet; BgPaint paint; } bg_def;static void relayout(void) {uint32_t bg = bg_def.w > 0 && bg_def.h > 0 ? (uint32_t)(bg_def.w * bg_def.h + 3) & ~3u : 0;- if (state_bytes + bg > ARENA_BYTES - 16 * 1024) bg = 0;+ if (state_bytes + bg > ARENA_BYTES - MIN_CACHE) bg = 0;if (bg) bg_setup(arena + state_bytes, bg_def.w, bg_def.h, bg_def.sheet, bg_def.paint); else bg_off();spr_setup(arena + state_bytes + bg, ARENA_BYTES - state_bytes - bg);}@@ -43,6 +43,17 @@ void *scene_state(uint32_t size) {/* ---------------------------------------------------------------- input */static uint32_t prev_keys;+/* OK or Back still down from a press a scene or an overlay already used: the+ * key is up for the game until it is let go (its release would otherwise+ * count: an island door opens when OK is let go) */+static bool latched[A_COUNT];++void input_latch(void) {+ latched[A_ACTION] = (prev_keys & K_ACTION) != 0;+ latched[A_BACK] = (prev_keys & K_BACK) != 0;+ for (int a = A_ACTION; a <= A_BACK; a++)+ if (latched[a]) in.held[a] = in.pressed[a] = in.released[a] = false;+}void input_tick(void) {uint32_t k = plat_keys();@@ -53,6 +64,10 @@ void input_tick(void) {in.jy = y;bool now[A_COUNT] = {x < -.1f, x > .1f, y < -.1f, y > .1f, (k & K_ACTION) != 0, (k & K_BACK) != 0};for (int i = 0; i < A_COUNT; i++) {+ if (latched[i]) {+ if (!now[i]) latched[i] = false;+ now[i] = false;+ }in.pressed[i] = now[i] && !in.held[i];in.released[i] = !now[i] && in.held[i];in.held[i] = now[i];@@ -128,6 +143,10 @@ bool game_is_sport(const char *name) {}bool game_is_world(const char *name) { return !strcmp(name, "overworld") || !strcmp(name, "interior"); }+#ifdef HOST+#include <stdlib.h>+extern uint32_t host_time;+#endifstatic char pending[80];static bool has_pending;@@ -158,12 +177,46 @@ static void switch_scene(void) {for (unsigned i = 0; i < sizeof scenes / sizeof scenes[0]; i++)if (scenes[i] && !strcmp(scenes[i]->name, name)) def = scenes[i];if (!def) return;+#ifdef HOST+ if (getenv("CI_LOG")) fprintf(stderr, "t%u scene %s\n", host_time / 33, pending);+#endifif (game.def && game.def->end) game.def->end();if (game.root) node_free(game.root);+#ifdef HOST+ if (getenv("CI_LEAK")) { /* nodes nobody holds: not under a root (the HUD, the dialogue box, the menus) */+ extern NodeId node_first_used(NodeId after);+ int n = 0, orphans = 0;+ for (NodeId i = node_first_used(0); i; i = node_first_used(i)) {+ n++;+ NodeId r = i;+ while (nodes[r].parent) r = nodes[r].parent;+ if (nodes[r].sym != S_hud_Ap && nodes[r].sym != S_dialog_Spa && nodes[r].sym != S_menus_Obb) {+ orphans++;+ if (orphans <= 3) {+ fprintf(stderr, " leaked %u sym %u:", i, nodes[i].sym);+ for (NodeId q = i; q; q = nodes[q].parent) fprintf(stderr, " %u(sym %u used %d)", q, nodes[q].sym, (nodes[q].flags & NF_USED) != 0);+ fprintf(stderr, "\n");+ }+ if (nodes[i].parent == 0) {+ int sub = 0;+ for (NodeId j = node_first_used(0); j; j = node_first_used(j)) {+ NodeId q = j;+ while (nodes[q].parent) q = nodes[q].parent;+ if (q == i) sub++;+ }+ fprintf(stderr, " leaked root %u sym %u kind %u first %u (sym %u) nodes %d\n", i, nodes[i].sym, nodes[i].kind, nodes[i].first,+ nodes[i].first ? nodes[nodes[i].first].sym : 0, sub);+ }+ }+ }+ fprintf(stderr, "t%u switch to %s: %d nodes used, %d not under a root\n", host_time / 33, pending, n, orphans);+ }+#endiftoast_style("", 0, -1, -1); /* Hq: a new scene takes the banner away */state_bytes = 0;mem_layout(0, 0, 0, NULL);memset(&in.pressed, 0, sizeof in.pressed);+ input_latch();game.def = def;snprintf(game.name, sizeof game.name, "%s", name);snprintf(game.variant, sizeof game.variant, "%s", variant);@@ -173,6 +226,7 @@ static void switch_scene(void) {game.paused = false;game.ticks = 0;game.fade = 10;+ gfx_view(0, VIEW_H); /* the stage; the island asks for more */def->start();if (variant[0] && def->goto_frame) def->goto_frame(variant);store_save();@@ -258,8 +312,9 @@ void game_draw(void) {dialog_draw();menus_draw();banner_draw();- if (game.fade > 0 && game.fade <= 8) gfx_rect(0, 0, VIEW_W, VIEW_H, 0, (uint8_t)(game.fade * 255 / 8));- else if (game.fade > 8) gfx_rect(0, 0, VIEW_W, VIEW_H, 0, 255);+ int top = gfx_view_top(), h = gfx_view_bottom() - top;+ if (game.fade > 0 && game.fade <= 8) gfx_rect(0, top, VIEW_W, h, 0, (uint8_t)(game.fade * 255 / 8));+ else if (game.fade > 8) gfx_rect(0, top, VIEW_W, h, 0, 255);gfx_end();}diff --git a/games/championisland/src/game.h b/games/championisland/src/game.hindex 92c78ff0..ccf74861 100644--- a/games/championisland/src/game.h+++ b/games/championisland/src/game.h@@ -23,6 +23,7 @@ typedef struct {extern Input in;void input_tick(void);void input_consume(int action); /* an overlay used this press */+void input_latch(void); /* OK and Back, if down now, count again only once let go *//* ---------------------------------------------------------------- scenes */typedef struct {@@ -46,7 +47,16 @@ typedef struct {} Game;extern Game game;-#define ARENA_BYTES (85 * 1024)+/* all the RAM the app has left (tests can ask for another size): the island+ * needs its 328 x 244 layer and a cache of 12 KB or more */+#ifndef ARENA_BYTES+#define ARENA_BYTES 100000+#endif+/* the sprite cache a scene with a layer keeps at least: a frame's sprites+ * (big scenery goes straight from the decoder into the layer) */+#ifndef MIN_CACHE+#define MIN_CACHE (12 * 1024)+#endif/* a scene with a background layer of bg_w x bg_h (0: none) calls this in start() */void mem_layout(int bg_w, int bg_h, uint8_t sheet, BgPaint paint);/* the scene's own state (zeroed), taken from the arena until the next scene:diff --git a/games/championisland/src/gfx.c b/games/championisland/src/gfx.cindex 65a04465..8f8fdd31 100644--- a/games/championisland/src/gfx.c+++ b/games/championisland/src/gfx.c@@ -6,13 +6,13 @@#include <stdlib.h>#include <stdio.h>-#define BAND 6-#define MAX_ITEMS 320-#define MAX_AFF 64+#define BAND 4+#define MAX_ITEMS 288 /* 215 at most seen */+#define MAX_AFF 56 /* 41 at most seen */-enum { DI_SPRITE, DI_AFFINE, DI_RECT, DI_SHAPE, DI_TEXT, DI_STREAM, DI_TILES, DI_MASK, DI_KINDS };+enum { DI_SPRITE, DI_AFFINE, DI_RECT, DI_SHAPE, DI_TEXT, DI_STREAM, DI_TILES, DI_MASK, DI_HIDDEN /* under an overlay's panel */, DI_KINDS };#define STREAM_OVER (16 * 1024) /* sprites bigger than this once cached are decoded as they are drawn */-enum { DF_FLIPX = 1, DF_FLIPY = 2, DF_MISSING = 4, DF_OPAQUE = 8 }; /* missing: not in the cache this frame; opaque: only fully opaque pixels */+enum { DF_FLIPX = 1, DF_FLIPY = 2, DF_MISSING = 4, DF_OPAQUE = 8, DF_OVERLAY = 16 }; /* missing: not in the cache this frame; opaque: only fully opaque pixels; overlay: a menu's */typedef struct {uint8_t kind, alpha, flags, pad;int16_t x0, y0, x1, y1; /* covered screen area in view coordinates (x1, y1 excluded) */@@ -29,6 +29,11 @@ static Aff affs[MAX_AFF];static int nitems, naffs;static uint16_t band[VIEW_W * BAND];static uint16_t clear_color;+/* the stage rows on screen: the doodle's 180 (0 to 180), or, on the island,+ * the whole screen (-30 to 210) */+static int view_top = 0, view_bottom = VIEW_H;+static bool overlay; /* drawing an overlay (gfx_overlay) */+void gfx_overlay(bool on) { overlay = on; }uint16_t rgb565(uint8_t r, uint8_t g, uint8_t b) { return (uint16_t)((r >> 3) << 11 | (g >> 2) << 5 | b >> 3); }@@ -65,7 +70,7 @@ static void bbox(Mat m, float w, float h, int *x0, int *y0, int *x1, int *y1) {*x0 = (int)floorf(lx); *y0 = (int)floorf(ly); *x1 = (int)ceilf(hx); *y1 = (int)ceilf(hy);}-static bool on_view(int x0, int y0, int x1, int y1) { return x1 > 0 && y1 > 0 && x0 < VIEW_W && y0 < VIEW_H && x1 > x0 && y1 > y0; }+static bool on_view(int x0, int y0, int x1, int y1) { return x1 > 0 && y1 > view_top && x0 < VIEW_W && y0 < view_bottom && x1 > x0 && y1 > y0; }static bool set_affine(Item *it, Mat m) {float det = m.a * m.d - m.b * m.c;@@ -93,12 +98,12 @@ void gfx_sprite_ex(uint16_t sp, Mat m, uint8_t alpha, bool opaque_only) {/* the canvas snaps unrotated images to whole pixels */int x = (int)floorf((m.a < 0 ? m.tx - s.w : m.tx) + 0.5f), y = (int)floorf((m.d < 0 ? m.ty - s.h : m.ty) + 0.5f);it->x0 = (int16_t)x; it->y0 = (int16_t)y; it->x1 = (int16_t)(x + s.w); it->y1 = (int16_t)(y + s.h);- it->flags = (uint8_t)((m.a < 0 ? DF_FLIPX : 0) | (m.d < 0 ? DF_FLIPY : 0) | (opaque_only ? DF_OPAQUE : 0));+ it->flags = (uint8_t)((m.a < 0 ? DF_FLIPX : 0) | (m.d < 0 ? DF_FLIPY : 0) | (opaque_only ? DF_OPAQUE : 0) | (overlay ? DF_OVERLAY : 0));it->color = sp;} else {it->kind = DI_AFFINE;it->color = sp;- it->flags = opaque_only ? DF_OPAQUE : 0;+ it->flags = (uint8_t)((opaque_only ? DF_OPAQUE : 0) | (overlay ? DF_OVERLAY : 0));if (!set_affine(it, m)) nitems--;}}@@ -116,7 +121,7 @@ void gfx_tiles(const uint8_t *px, int w, int h, const uint16_t *pal, const uint8Item *it = add();if (!it) return;tl.px = px; tl.pts = NULL; tl.pal = pal; tl.al = al; tl.pos = pos; tl.n = n; tl.w = w; tl.h = h; tl.ox = ox; tl.oy = oy;- *it = (Item){DI_TILES, alpha, 0, 0, 0, 0, VIEW_W, VIEW_H, (uint16_t)(uintptr_t)px, (uint16_t)((ox & 0xFF) | (oy & 0xFF) << 8)};+ *it = (Item){DI_TILES, alpha, 0, 0, 0, (int16_t)view_top, VIEW_W, (int16_t)view_bottom, (uint16_t)(uintptr_t)px, (uint16_t)((ox & 0xFF) | (oy & 0xFF) << 8)};}void gfx_points(const uint8_t *pts, int w, int h, const uint16_t *pal, const uint8_t *al, const int16_t *pos, int n, int ox, int oy, uint8_t alpha) {@@ -148,6 +153,14 @@ 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) {+ 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;+ hy = hy * k + (float)view_top;+ }int x0 = (int)floorf(lx), y0 = (int)floorf(ly), x1 = (int)ceilf(hx), y1 = (int)ceilf(hy);if (!on_view(x0, y0, x1, y1)) return;Item *it = add();@@ -197,6 +210,7 @@ static int clip_x0, clip_y0, clip_x1, clip_y1; /* world rect being painted */static uint32_t bg_gen; /* changes whenever the layer's pixels do */static int bg_see; /* palette index that shows the water (-1: none) */static const uint8_t *water; /* the water: a tile of palette indices, repeating from world (0, 0) */+static const uint16_t *water_cols; /* or of 4-bit indices into these colours */static int water_w, water_h;static const uint8_t *bglut; /* RGB444 -> palette index, to blend into the layer *//* the see-through entries of the layer's palette: a pixel partly over the@@ -212,6 +226,7 @@ void bg_setup(uint8_t *mem, int w, int h, uint8_t sheet, BgPaint paint) {bg_valid = false;bg_see = -1;water = NULL;+ water_cols = NULL;bglut = NULL;bg_gen++;const uint8_t *al = palalpha(sheet);@@ -226,7 +241,8 @@ void bg_off(void) { bgmem = NULL; bg_gen++; }void bg_invalidate(void) { bg_valid = false; }uint8_t *bg_layer(int *w, int *h) { *w = bgw; *h = bgh; return bgmem; }static uint32_t water_gen;-void bg_water(const uint8_t *tile, int w, int h) { water = tile; water_w = w; water_h = h; water_gen++; }+void bg_water(const uint8_t *tile, int w, int h) { water = tile; water_cols = NULL; water_w = w; water_h = h; water_gen++; }+void bg_water4(const uint8_t *tile, int w, int h, const uint16_t *cols) { bg_water(tile, w, h); water_cols = cols; }void bg_redraw_water(void) { water_gen++; }void bg_blend_lut(const uint8_t *lut) { bglut = lut; }int bg_clear_index(void) { return bg_see; }@@ -253,10 +269,12 @@ void bg_camera(int cx, int cy) {if (!bgmem) return;bg_cx = cx;bg_cy = cy;+ cy += view_top; /* the top row on screen */+ int vh = view_bottom - view_top;if (!bg_valid || cx < bgx - bgw || cx > bgx + 2 * bgw || cy < bgy - bgh || cy > bgy + 2 * bgh) {/* center the spare margin around the view */bgx = cx - (bgw - VIEW_W) / 2;- bgy = cy - (bgh - VIEW_H) / 2;+ bgy = cy - (bgh - vh) / 2;bg_paint_rect(bgx, bgy, bgx + bgw, bgy + bgh);bg_valid = true;return;@@ -269,8 +287,8 @@ void bg_camera(int cx, int cy) {else bg_paint_rect(nx, bgy, bgx < nx + bgw ? bgx : nx + bgw, bgy + bgh);bgx = nx;}- if (cy < bgy || cy + VIEW_H > bgy + bgh) {- int ny = cy < bgy ? cy + VIEW_H - bgh : cy;+ if (cy < bgy || cy + vh > bgy + bgh) {+ int ny = cy < bgy ? cy + vh - bgh : cy;if (ny > bgy) bg_paint_rect(bgx, bgy + bgh > ny ? bgy + bgh : ny, bgx + bgw, ny + bgh);else bg_paint_rect(bgx, ny, bgx + bgw, bgy < ny + bgh ? bgy : ny + bgh);bgy = ny;@@ -378,6 +396,38 @@ static void bg_draw_banded(uint16_t sp, const Sprite *s, int x, int y, uint8_t f}}+/* bg_draw from the decoder's rows (the sprite is not in the cache) */+static void bg_draw_rows(uint16_t sp, const Sprite *s, int x, int y, uint8_t flags, uint8_t alpha) {+#ifdef HOST+ if (getenv("CI_SPR_MISS")) fprintf(stderr, "paintrows %u %dx%d rle %u\n", sp, s->w, s->h, (unsigned)s->rle);+#endif+ if (!spr_rows_open(sp, s)) return;+ const uint16_t *spal = pal565(s->sheet);+ const uint8_t *sal = palalpha(s->sheet);+ bool tr = flags & BD_TRANSPOSE, fx = flags & BD_FLIPX, fy = flags & BD_FLIPY;+ int dw = tr ? s->h : s->w, dh = tr ? s->w : s->h;+ for (int v = 0; v < s->h; v++) {+ /* the row's place across the painted strip (a column when transposed) */+ int rv = tr ? (fx ? dw - 1 - v : v) : (fy ? dh - 1 - v : v);+ int at = tr ? x + rv : y + rv, lo = tr ? clip_x0 : clip_y0, hi = tr ? clip_x1 : clip_y1;+ bool back = tr ? fx : fy; /* rows go the other way */+ if ((at >= hi && !back) || (at < lo && back)) return; /* the rest is past the strip */+ bool skip = at < lo || at >= hi;+ if (!z_get(skip ? NULL : stream_buf, s->w)) return;+ if (skip) continue;+ for (int u = 0; u < s->w; u++) {+ uint8_t c = stream_buf[u];+ if (!sal[c]) continue;+ int di = tr ? v : u, dj = tr ? u : v;+ if (fx) di = dw - 1 - di;+ if (fy) dj = dh - 1 - dj;+ int wx = x + di, wy = y + dj;+ if (wx < clip_x0 || wx >= clip_x1 || wy < clip_y0 || wy >= clip_y1) continue;+ bg_put(bg_at(wx, wy), c, spal, sal, s->sheet, alpha);+ }+ }+}+void bg_draw(uint16_t sp, int x, int y, uint8_t flags, uint8_t alpha) {if (sp >= SPRITE_COUNT || !bgmem) return;Sprite s;@@ -387,7 +437,11 @@ void bg_draw(uint16_t sp, int x, int y, uint8_t flags, uint8_t alpha) {if (x >= clip_x1 || y >= clip_y1 || x + dw <= clip_x0 || y + dh <= clip_y0 || !alpha) return;if (s.kind == 2) { if (!tr) bg_draw_banded(sp, &s, x, y, flags, alpha); return; }if (s.kind == 1 && !flags) { bg_blit_stream(sp, x, y); return; }- const uint8_t *r = spr_get(sp);+ const uint8_t *r = spr_peek(sp);+ /* big scenery the cache has no room for (without dropping what the+ * frames draw) goes straight from the decoder into the layer */+ if (!r && !spr_room(s.rle ? s.rle : (uint32_t)s.w * s.h)) { bg_draw_rows(sp, &s, x, y, flags, alpha); return; }+ if (!r) r = spr_get(sp);if (!r) return;const uint16_t *spal = pal565(s.sheet);const uint8_t *sal = palalpha(s.sheet);@@ -472,16 +526,31 @@ static void band_bg(int by, int rows) {/* where the layer is clear, the water shows */int ty = wy % water_h;if (ty < 0) ty += water_h;- const uint8_t *wrow = water + ty * water_w;int tx = bg_cx % water_w;if (tx < 0) tx += water_w;const uint8_t *al = palalpha(bgsheet);- for (int x = 0; x < VIEW_W; x++) {- uint8_t c = row[lx];- unsigned a = al[c];- d[x] = a == 255 ? pal[c] : !a ? pal[wrow[tx]] : blend(pal[c], pal[wrow[tx]], (a + 4) >> 3);- if (++lx == bgw) lx = 0;- if (++tx == water_w) tx = 0;+ if (water_cols) {+ const uint8_t *wrow = water + ty * (water_w >> 1);+ for (int x = 0; x < VIEW_W; x++) {+ uint8_t c = row[lx];+ unsigned a = al[c];+ if (a == 255) d[x] = pal[c];+ else {+ uint16_t wc = water_cols[wrow[tx >> 1] >> ((tx & 1) << 2) & 15];+ d[x] = !a ? wc : blend(pal[c], wc, (a + 4) >> 3);+ }+ if (++lx == bgw) lx = 0;+ if (++tx == water_w) tx = 0;+ }+ } else {+ const uint8_t *wrow = water + ty * water_w;+ for (int x = 0; x < VIEW_W; x++) {+ uint8_t c = row[lx];+ unsigned a = al[c];+ d[x] = a == 255 ? pal[c] : !a ? pal[wrow[tx]] : blend(pal[c], pal[wrow[tx]], (a + 4) >> 3);+ if (++lx == bgw) lx = 0;+ if (++tx == water_w) tx = 0;+ }}} else {for (int x = 0; x < VIEW_W; x++) {@@ -578,10 +647,9 @@ static void line_decode(const uint8_t *r, int v, int w) {}static void stream_begin(const Item *it) {- streaming = it;- const uint8_t *st = spr_stream(it->ref);- if (!st) { streaming = NULL; return; }- z_open(rd32(st + 2), rd32(st + 6), rd32(st + 10));+ Sprite s;+ sprite_info(it->ref, &s);+ streaming = spr_rows_open(it->ref, &s) ? it : NULL;stream_row = 0;}@@ -612,17 +680,18 @@ static void draw_stream(const Item *it, int y0, int y1, int by, unsigned ga) {/* A sprite the cache let go before its band (a frame needing more than the* cache holds, such as a menu over the island): decoded now, unless a stream- * holds the decoder (then it comes next frame). */-static const uint8_t *band_sprite(uint16_t sp) {+ * 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 */+static const uint8_t *band_sprite(uint16_t sp, uint8_t flags) {const uint8_t *r = spr_peek(sp);- if (r || streaming) return r;+ if (r || streaming || (scene_later && !(flags & DF_OVERLAY))) return r;r = spr_get(sp);line_spr = NULL; /* the cache may have moved */return r;}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);+ const uint8_t *r = band_sprite(it->ref, it->flags);if (!r) return;Sprite s;sprite_info(it->ref, &s);@@ -642,7 +711,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);+ const uint8_t *r = band_sprite(it->color, it->flags);if (!r) return;Sprite s;sprite_info(it->color, &s);@@ -857,7 +926,7 @@ static void draw_item(const Item *it, int by, int rows) {/* Bands whose content is the same as last frame's are not drawn again: the* screen keeps them. A band's content is summed up as a hash of its items. */-#define NBANDS ((VIEW_H + BAND - 1) / BAND)+#define NBANDS ((SCREEN_H + BAND - 1) / BAND)static uint32_t band_hash[NBANDS];static bool redraw_all = true;void gfx_redraw_all(void) { redraw_all = true; }@@ -868,8 +937,11 @@ static uint32_t mixf(uint32_t h, float f) {memcpy(&v, &f, 4);return mix(h, v);}-static uint32_t item_hash(uint32_t h, const Item *it) {- h = mix(h, (uint32_t)it->kind | (uint32_t)it->alpha << 8 | (uint32_t)it->flags << 16);+/* missing: whether DF_MISSING counts (the band drawn has it: when the sprite+ * comes, the band is drawn again) */+static uint32_t item_hash(uint32_t h, const Item *it, bool missing) {+ unsigned kind = it->kind == DI_STREAM ? DI_SPRITE : it->kind, flags = missing ? it->flags : it->flags & ~DF_MISSING;+ h = mix(h, (uint32_t)kind | (uint32_t)it->alpha << 8 | (uint32_t)flags << 16);h = mix(h, (uint32_t)(uint16_t)it->x0 | (uint32_t)(uint16_t)it->y0 << 16);h = mix(h, (uint32_t)(uint16_t)it->x1 | (uint32_t)(uint16_t)it->y1 << 16);h = mix(h, (uint32_t)it->ref | (uint32_t)it->color << 16);@@ -893,6 +965,15 @@ void gfx_letterbox(uint16_t c) {letter_color = c;}+void gfx_view(int top, int bottom) {+ if (top == view_top && bottom == view_bottom) return;+ view_top = top;+ view_bottom = bottom;+ letter_dirty = redraw_all = true;+}+int gfx_view_top(void) { return view_top; }+int gfx_view_bottom(void) { return view_bottom; }+/* sprites whose items all end above y: the cache may let them go first */static void release_done(int y) {for (int i = 0; i < nitems; i++) {@@ -903,10 +984,17 @@ static void release_done(int y) {}}+#ifdef HOST+int gfx_peak_items, gfx_peak_affs; /* tests: the most a frame used */+#endifvoid gfx_end(void) {+#ifdef HOST+ if (nitems > gfx_peak_items) gfx_peak_items = nitems;+ if (naffs > gfx_peak_affs) gfx_peak_affs = naffs;+#endifif (letter_dirty) {- plat_fill(0, 0, SCREEN_W, VIEW_Y, letter_color);- plat_fill(0, VIEW_Y + VIEW_H, SCREEN_W, SCREEN_H - VIEW_Y - VIEW_H, letter_color);+ if (VIEW_Y + view_top > 0) plat_fill(0, 0, SCREEN_W, VIEW_Y + view_top, letter_color);+ if (VIEW_Y + view_bottom < SCREEN_H) plat_fill(0, VIEW_Y + view_bottom, SCREEN_W, SCREEN_H - VIEW_Y - view_bottom, letter_color);letter_dirty = false;}#ifdef HOST@@ -916,7 +1004,7 @@ void gfx_end(void) {for (int i = 0; i < nitems; i++) {const Item *it = &items[i];int x0 = it->x0 < 0 ? 0 : it->x0, x1 = it->x1 > VIEW_W ? VIEW_W : it->x1;- int y0 = it->y0 < 0 ? 0 : it->y0, y1 = it->y1 > VIEW_H ? VIEW_H : it->y1;+ int y0 = it->y0 < view_top ? view_top : it->y0, y1 = it->y1 > view_bottom ? view_bottom : it->y1;if (x1 > x0 && y1 > y0) area[it->kind] += (long)(x1 - x0) * (y1 - y0);cnt[it->kind]++;}@@ -936,34 +1024,128 @@ void gfx_end(void) {* once its last band is drawn (release_done) */streaming = NULL;line_spr = NULL;+ /* what a menu's opaque panel hides is not drawn (nor decoded) */+ for (int j = 0; j < nitems; j++) {+ const Item *o = &items[j];+ if (o->kind != DI_SPRITE || !(o->flags & DF_OVERLAY) || o->alpha != 255 || (o->flags & (DF_FLIPX | DF_FLIPY | DF_OPAQUE)) ||+ (o->x1 - o->x0) * (o->y1 - o->y0) < VIEW_W * VIEW_H / 4)+ continue;+ int16_t b[4];+ if (!spr_opaque_box(o->ref, b)) continue;+ int bx0 = o->x0 + b[0], by0 = o->y0 + b[1], bx1 = o->x0 + b[2], by1 = o->y0 + b[3];+ for (int i = 0; i < j; i++) {+ Item *it = &items[i];+ if (it->x0 >= bx0 && it->y0 >= by0 && it->x1 <= bx1 && it->y1 <= by1) it->kind = DI_HIDDEN;+ }+ }+ /* the bands to draw: those whose items changed since they were drawn (the+ * others keep their pixels); only what they show is decoded */+ uint32_t base = bgmem ? mix(mix(mix(mix(2166136261u, (uint32_t)bg_cx), (uint32_t)bg_cy), bg_gen), water_gen)+ : mix(1, clear_color);+ bool dirty[NBANDS];+ for (int by = view_top; by < view_bottom; by += BAND) {+ int rows = view_bottom - by < BAND ? view_bottom - by : BAND;+ uint32_t h = base;+ for (int i = 0; i < nitems; i++) {+ const Item *it = &items[i];+ if (it->y1 > by && it->y0 < by + rows && it->kind != DI_HIDDEN) h = item_hash(h, it, false);+ }+ dirty[(by - view_top) / BAND] = redraw_all || h != band_hash[(by - view_top) / BAND];+ }+ bool shown[MAX_ITEMS];+ for (int i = 0; i < nitems; i++) {+ const Item *it = &items[i];+ int y0 = it->y0 > view_top ? it->y0 : view_top, y1 = it->y1 < view_bottom ? it->y1 : view_bottom;+ shown[i] = false;+ for (int b = (y0 - view_top) / BAND; y0 < y1 && b <= (y1 - 1 - view_top) / BAND && !shown[i]; b++) shown[i] = dirty[b];+ }uint8_t seen[(SPRITE_COUNT + 7) / 8];memset(seen, 0, sizeof seen);uint32_t need = 0; /* cache the frame's sprites take */for (int i = 0; i < nitems; i++) {Item *it = &items[i];- if (it->kind != DI_SPRITE && it->kind != DI_AFFINE) continue;+ if ((it->kind != DI_SPRITE && it->kind != DI_AFFINE) || !shown[i]) continue;uint16_t sp = it->kind == DI_SPRITE ? it->ref : it->color;- if (!(seen[sp >> 3] & (1 << (sp & 7)))) {+ if (!(seen[sp >> 3] & (1 << (sp & 7))) && !spr_pinned(sp)) { /* pinned ones take no room */Sprite t;sprite_info(sp, &t);need += (t.rle + 3) & ~3u;seen[sp >> 3] |= (uint8_t)(1 << (sp & 7));+#ifdef HOST+ if (getenv("CI_NEED") && atoi(getenv("CI_NEED")) > 1) fprintf(stderr, " counts %u (%u B) item %d kind %d box %d %d %d %d\n", sp, (unsigned)t.rle, i, it->kind, it->x0, it->y0, it->x1, it->y1);+#endif}}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+ * biggest, and the scene's sprites that do not fit then come in the next+ * frames (only their bands are drawn again) */+ scene_later = false;+ if (over) {+ uint32_t need_menu = 0; /* the menu's part of need */+ memset(seen, 0, sizeof seen);+ for (int i = 0; i < nitems; i++) {+ const Item *it = &items[i];+ if ((it->kind != DI_SPRITE && it->kind != DI_AFFINE) || !shown[i] || !(it->flags & DF_OVERLAY)) continue;+ uint16_t sp = it->kind == DI_SPRITE ? it->ref : it->color;+ if (!(seen[sp >> 3] & (1 << (sp & 7))) && !spr_pinned(sp)) {+ Sprite t;+ sprite_info(sp, &t);+ need_menu += (t.rle + 3) & ~3u;+ seen[sp >> 3] |= (uint8_t)(1 << (sp & 7));+ }+ }+ for (int menu = 0; menu < 2 && over; menu++) {+ if (menu && !need_menu) break;+ int big = -1;+ uint32_t bigsz = 0;+ bool stream_already = false;+ for (int i = 0; i < nitems; i++) {+ const Item *it = &items[i];+ if (it->kind == DI_STREAM && shown[i]) stream_already = true;+ if (it->kind != DI_SPRITE || !shown[i] || (it->flags & (DF_FLIPY | DF_OPAQUE)) || spr_pinned(it->ref) ||+ (menu && !(it->flags & DF_OVERLAY)))+ continue;+ Sprite t;+ sprite_info(it->ref, &t);+ if (t.kind <= 1 && t.rle > bigsz) { big = i; bigsz = t.rle; }+ }+ 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;+ /* (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; }+ over = false;+ scene_later = menu;+ }+ }+ }#ifdef HOST- if (getenv("CI_NEED")) fprintf(stderr, "need %u of %u%s\n", (unsigned)need, (unsigned)spr_capacity(), over ? " (by band)" : "");+ if (getenv("CI_NEED")) fprintf(stderr, "need %u of %u%s%s\n", (unsigned)need, (unsigned)spr_capacity(), over ? " (by band)" : "",+ scene_later ? " (scene later)" : "");#endif- for (int i = 0; i < nitems && !over; i++) {- Item *it = &items[i];- if (it->kind == DI_SPRITE || it->kind == DI_AFFINE) spr_get(it->kind == DI_SPRITE ? it->ref : it->color);- else if (it->kind == DI_MASK) spr_mask(it->ref);- }+ /* the menus' first; then the scene's, as long as the menus' can stay (too+ * many: some of the scene's come next frame) */+ for (int pass = 0; pass < 2; pass++)+ for (int i = 0; i < nitems && !over; i++) {+ Item *it = &items[i];+ if ((it->kind != DI_SPRITE && it->kind != DI_AFFINE) || !shown[i] || !(it->flags & DF_OVERLAY) != pass) continue;+ uint16_t sp = it->kind == DI_SPRITE ? it->ref : it->color;+ if (pass) spr_get_soft(sp);+ else spr_get(sp);+ }+ /* then the masks, which may take the place of what this frame does not draw */+ 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 */for (int i = 0; i < nitems; i++) {Item *it = &items[i];- if (it->kind != DI_STREAM) continue;+ if (it->kind != DI_STREAM || !shown[i]) continue;Sprite t;sprite_info(it->ref, &t);uint32_t sz = (t.rle + 3) & ~3u;@@ -976,22 +1158,24 @@ void gfx_end(void) {* 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)) &&!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;}- uint32_t base = bgmem ? mix(mix(mix(mix(2166136261u, (uint32_t)bg_cx), (uint32_t)bg_cy), bg_gen), water_gen)- : mix(1, clear_color);- for (int by = 0; by < VIEW_H; by += BAND) {- int rows = VIEW_H - by < BAND ? VIEW_H - by : BAND;+ 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; }uint32_t h = base;for (int i = 0; i < nitems; i++) {const Item *it = &items[i];- if (it->y1 > by && it->y0 < by + rows) h = item_hash(h, it);+ if (it->y1 > by && it->y0 < by + rows && it->kind != DI_HIDDEN) h = item_hash(h, it, true);}- if (!redraw_all && h == band_hash[by / BAND]) { if (over) release_done(by + rows); continue; }- band_hash[by / BAND] = h;+ band_hash[(by - view_top) / BAND] = h;+#ifdef HOST+ if (getenv("CI_BANDS")) fprintf(stderr, "band %d\n", by);+#endifband_bg(by, rows);for (int i = 0; i < nitems; i++) {const Item *it = &items[i];diff --git a/games/championisland/src/gfx.h b/games/championisland/src/gfx.hindex edc521b9..c7c19bb2 100644--- a/games/championisland/src/gfx.h+++ b/games/championisland/src/gfx.h@@ -28,6 +28,13 @@ void gfx_end(void); /* rasterise and pushvoid gfx_redraw_all(void); /* next frame: every band */void gfx_clear_color(uint16_t c); /* what shows where nothing is drawn */void gfx_letterbox(uint16_t c); /* fills the bands above and below the view */+/* the stage rows the screen shows: 0 to VIEW_H (bands above and below), or+ * more (-VIEW_Y to VIEW_H + VIEW_Y: the whole screen); a scene's own choice,+ * back to the stage at each new scene */+void gfx_view(int top, int bottom);+int gfx_view_top(void);+int gfx_view_bottom(void);+void gfx_overlay(bool on); /* menus: a shape over the whole stage covers the whole view *//* The background layer: an 8-bit image of the scene's static backdrop in* world coordinates, redrawn only where the camera uncovers something. */@@ -43,6 +50,7 @@ enum { BD_FLIPX = 1, BD_FLIPY = 2, BD_TRANSPOSE = 4 };void bg_draw(uint16_t sprite, int x, int y, uint8_t flags, uint8_t alpha);void bg_blend_lut(const uint8_t *lut444); /* RGB444 -> palette index (pack.py) */void bg_water(const uint8_t *tile, int w, int h); /* shown where the layer is clear (NULL: none) */+void bg_water4(const uint8_t *tile, int w, int h, const uint16_t *colours); /* the same, 4 bits a pixel (low first) */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);diff --git a/games/championisland/src/hud.c b/games/championisland/src/hud.cindex 03e07296..282c0359 100644--- a/games/championisland/src/hud.c+++ b/games/championisland/src/hud.c@@ -28,5 +28,6 @@ void hud_tick(void) {}void hud_draw(void) {- if (root) node_draw(root, (Mat){1.0f / 3, 0, 0, 1.0f / 3, 0, 0});+ /* in the screen's top left corner, above the island too */+ if (root) node_draw(root, (Mat){1.0f / 3, 0, 0, 1.0f / 3, 0, (float)gfx_view_top()});}diff --git a/games/championisland/src/menus.c b/games/championisland/src/menus.cindex 31551d21..ae2333a3 100644--- a/games/championisland/src/menus.c+++ b/games/championisland/src/menus.c@@ -3,6 +3,9 @@* driven with the arrows and OK like the doodle's keyboard navigation. */#include <math.h>#include <stdio.h>+#ifdef HOST+#include <stdlib.h>+#endif#include "ent.h"#include "font.h"@@ -203,6 +206,7 @@ bool menus_open(const char *label) {}static void close_all(void) {+ input_latch();depth = 0;if (root) node_free(root);root = 0;@@ -210,6 +214,7 @@ static void close_all(void) {void menus_close(void) {if (!depth) return;+ input_latch();depth--;if (depth) {show_label(stack[depth - 1]);@@ -220,6 +225,9 @@ void menus_close(void) {/* ---------------------------------------------------------------- events */static void on_event(NodeId m, const char *ev) {const char *id = menu_id(m);+#ifdef HOST+ if (getenv("CI_LOG")) { extern uint32_t host_time; fprintf(stderr, "t%u menu %s %s\n", host_time / 33, id, ev); }+#endifif (!strcmp(id, "pause")) {if (!strcmp(ev, "resume")) menus_close();else if (!strcmp(ev, "how")) { const char *t = tutorial_of(game.name); if (t) menus_open(t); }@@ -472,5 +480,7 @@ void menus_tick(void) {void menus_draw(void) {if (!depth || !root) return;+ gfx_overlay(true);node_draw(root, (Mat){1.0f / 3, 0, 0, 1.0f / 3, 0, 0});+ gfx_overlay(false);}diff --git a/games/championisland/src/node.c b/games/championisland/src/node.cindex 2600af64..a78829ee 100644--- a/games/championisland/src/node.c+++ b/games/championisland/src/node.c@@ -36,8 +36,14 @@ void node_reset(void) {unsigned node_count(void) { return used_count; }+#ifdef HOST+unsigned node_alloc_fails; /* tests: nodes asked for with none left */+#endifstatic NodeId alloc_node(void) {NodeId n = free_head;+#ifdef HOST+ if (!n) node_alloc_fails++;+#endifif (!n) return 0;free_head = nodes[n].next;memset(&nodes[n], 0, sizeof nodes[n]);@@ -255,6 +261,7 @@ NodeId node_new_sym_dynamic(uint16_t sym) {static void instantiate_children(NodeId n) {Clip c;if (!clip_get(nodes[n].sym, &c)) return;+ if (only_current) nodes[n].flags2 |= NF2_PARTIAL;bool map_kids = c.T != NONE16 && comp_has(c.T, C_map);const uint8_t *p = c.slots;NodeId last = 0;@@ -288,35 +295,57 @@ static void instantiate_children(NodeId n) {void (*node_free_hook)(NodeId n);void (*node_stream_hook)(NodeId n);+void (*node_partial_hook)(NodeId n);NodeId node_draw_hook_id;void (*node_draw_hook)(NodeId n, Mat m, uint8_t alpha);+static void release(NodeId m) {+ if (nodes[m].ent && node_free_hook) node_free_hook(m);+ if (nodes[m].flags & NF_XFORM)+ for (int i = 0; i < XF_MAX; i++) if (xfs[i].n == m) xfs[i].n = 0;+ for (int i = 0; i < TX_MAX; i++) if (txs[i].n == m) txs[i].n = 0;+ for (int i = 0; i < EV_MAX; i++) if (evs[i].n == m) evs[i].n = 0;+ nodes[m].flags = 0;+ nodes[m].next = free_head;+ free_head = m;+ used_count--;+}+void node_free(NodeId n) {if (!n || !(nodes[n].flags & NF_USED)) return;node_remove(n);- /* free the subtree iteratively */- NodeId stack[64];- int sp = 0;- stack[sp++] = n;- while (sp) {- NodeId m = stack[--sp];- for (NodeId c = nodes[m].first; c;) {- NodeId nx = nodes[c].next;- if (sp < 64) stack[sp++] = c;- c = nx;- }- if (nodes[m].ent && node_free_hook) node_free_hook(m);- if (nodes[m].flags & NF_XFORM)- for (int i = 0; i < XF_MAX; i++) if (xfs[i].n == m) xfs[i].n = 0;- for (int i = 0; i < TX_MAX; i++) if (txs[i].n == m) txs[i].n = 0;- for (int i = 0; i < EV_MAX; i++) if (evs[i].n == m) evs[i].n = 0;- nodes[m].flags = 0;- nodes[m].next = free_head;- free_head = m;- used_count--;+ /* the subtree, deepest first, through its own links (a stack would have a+ * size: the climbing wall's map has some 130 children) */+ for (NodeId m = n;;) {+ while (nodes[m].first) m = nodes[m].first;+ NodeId p = nodes[m].parent;+ bool last = m == n;+ if (!last) nodes[p].first = nodes[m].next; /* m was p's first child */+ release(m);+ if (last) break;+ m = p;}}+#ifdef HOST+/* tests: a node in use that its parent does not list (0 if none) */+NodeId node_unlisted(void) {+ for (NodeId i = 1; i < NODE_MAX; i++) {+ if (!(nodes[i].flags & NF_USED) || !nodes[i].parent) continue;+ NodeId c = nodes[nodes[i].parent].first;+ int guard = 0;+ while (c && c != i && guard++ < NODE_MAX) c = nodes[c].next;+ if (c != i) return i;+ }+ return 0;+}+NodeId node_first_used(NodeId after) { /* tests: the next node in use */+ for (NodeId i = (NodeId)(after + 1); i < NODE_MAX; i++)+ if (nodes[i].flags & NF_USED) return i;+ return 0;+}+#endif+void node_remove(NodeId c) {NodeId p = nodes[c].parent;if (!p) return;@@ -481,18 +510,22 @@ static void update_rec(NodeId n) {if (clip_get(p->sym, &c) && c.nframes > 1) {const uint8_t *q = c.slots;NodeId ch = p->first, prev = 0;- bool dyn = p->flags2 & NF2_DYN;+ bool dyn = p->flags2 & NF2_DYN, partial = p->flags2 & NF2_PARTIAL;for (unsigned s = 0; s < c.nslots; s++) {while (ch && nodes[ch].slot != NONE16 && nodes[ch].slot < s) { prev = ch; ch = nodes[ch].next; }- if (dyn) {- /* a long movie: its children exist while they are on stage */+ if (dyn || partial) {+ /* a long movie: its children exist while they are on stage; a+ * partial clip: from when they are first on stage */Key k;uint16_t idx;const uint8_t *q2 = slot_key(q, p->frame, &k, &idx);bool present = idx != NONE16 && !(k.flags & K_ABSENT);bool have = ch && nodes[ch].slot == s;if (present && !have && needs_node(&k)) {+ bool oc = only_current;+ only_current = partial && !dyn; /* its own children: made when shown too */NodeId nc = new_child_for(&k);+ only_current = oc;if (nc) {nodes[nc].slot = (uint16_t)s;nodes[nc].parent = n;@@ -501,9 +534,10 @@ static void update_rec(NodeId n) {nodes[nc].flags &= (uint8_t)~NF_ONSTAGE;if (prev) nodes[prev].next = nc; else nodes[n].first = nc;ch = nc;- if (node_stream_hook) node_stream_hook(nc);+ if (dyn && node_stream_hook) node_stream_hook(nc);+ if (!dyn && node_partial_hook) node_partial_hook(nc);}- } else if (!present && have && !(nodes[ch].flags2 & NF2_KEEP) && nodes[ch].name == NONE16) {+ } else if (dyn && !present && have && !(nodes[ch].flags2 & NF2_KEEP) && nodes[ch].name == NONE16) {NodeId nx = nodes[ch].next;node_free(ch);ch = nx;diff --git a/games/championisland/src/node.h b/games/championisland/src/node.hindex 5ef6e5e5..f064734f 100644--- a/games/championisland/src/node.h+++ b/games/championisland/src/node.h@@ -41,7 +41,8 @@ typedef struct {uint8_t kind, flags, flags2, alpha;} Node;/* flags2: how its parent's timeline drives it, streaming */-enum { NF2_LAZY = 1, NF2_KEEP = 2, NF2_NOLOOP = 4, NF2_MODE = 24 /* mode << 3 */, NF2_DYN = 32, NF2_FRESH = 64 /* its first tick is to come */ };+enum { NF2_LAZY = 1, NF2_KEEP = 2, NF2_NOLOOP = 4, NF2_MODE = 24 /* mode << 3 */, NF2_DYN = 32, NF2_FRESH = 64 /* its first tick is to come */,+ NF2_PARTIAL = 128 /* made by node_new_sym_frame: children made when first shown */ };static inline uint8_t node_mode(const Node *n) { return (uint8_t)((n->flags2 & NF2_MODE) >> 3); }static inline bool node_loops(const Node *n) { return !(n->flags2 & NF2_NOLOOP); }@@ -100,6 +101,10 @@ extern uint16_t node_lazy_sym; /* instances of this symbol are m/* A long movie (NF2_DYN) has nodes only for the children on stage now; they* are made and freed as it plays (new ones go through node_stream_hook). */NodeId node_new_sym_dynamic(uint16_t sym);+/* A clip made by node_new_sym_frame (a room, a menu) has nodes only for what+ * its frame showed; a child a later frame shows is made then, and kept (new+ * ones go through node_partial_hook). */+extern void (*node_partial_hook)(NodeId n);extern uint16_t node_dynamic_sym; /* instances of this symbol are made dynamic *//* a clip's timeline children at a frame, without nodes: symbol, instancediff --git a/games/championisland/src/phys.c b/games/championisland/src/phys.cindex 825d184f..483ab10d 100644--- a/games/championisland/src/phys.c+++ b/games/championisland/src/phys.c@@ -3,6 +3,7 @@* the approaching speed is cancelled (or bounced, with restitution), for a* few iterations per substep like cannon.js's solver. */#include "phys.h"+_Static_assert(BODY_MAX < 128, "a contact is a body index in an int8_t");#include <math.h>Body bodies[BODY_MAX];@@ -127,7 +128,7 @@ static float ramp_height(const Body *r, float x) {static void add_contact(Body *b, int other) {for (int i = 0; i < b->ncontacts; i++)if (b->contacts[i] == other) return;- if (b->ncontacts < 6) b->contacts[b->ncontacts++] = (int16_t)other;+ if (b->ncontacts < 6) b->contacts[b->ncontacts++] = (int8_t)other;}/* resolve a dynamic body against another body (static or dynamic) */diff --git a/games/championisland/src/phys.h b/games/championisland/src/phys.hindex a3896431..0adafddf 100644--- a/games/championisland/src/phys.h+++ b/games/championisland/src/phys.h@@ -18,7 +18,7 @@ typedef struct {bool used, active;uint16_t user; /* the entity (NodeId) */uint8_t ncontacts;- int16_t contacts[6]; /* bodies touched in the last step (-1 = the ground) */+ int8_t contacts[6]; /* bodies touched in the last step (-1 = the ground) */} Body;extern Body bodies[BODY_MAX];diff --git a/games/championisland/src/sport_climbing.c b/games/championisland/src/sport_climbing.cindex f41adef2..57de4d3e 100644--- a/games/championisland/src/sport_climbing.c+++ b/games/championisland/src/sport_climbing.c@@ -528,18 +528,21 @@ static void start(void) {if (!root) return;node_add(game.root, root);S->root = root;- /* the variant's map, whole (the root was made with just what its frame shows) */+ /* the variant's map, whole (the root was made with just what its frame+ * shows): the partial one goes first, the nodes have room for one map */for (NodeId c = nodes[root].first; c; c = nodes[c].next) {if (!has(c, C_map) || !(nodes[c].flags & NF_ONSTAGE)) continue;- NodeId m = node_new_sym(nodes[c].sym);- if (!m) break;- Node *o = &nodes[c], *q = &nodes[m];- q->x = o->x; q->y = o->y; q->rx4 = o->rx4; q->ry4 = o->ry4; q->mat = o->mat; q->alpha = o->alpha;- q->flags = o->flags; q->flags2 = o->flags2; q->name = o->name; q->key = o->key;- uint16_t slot = o->slot;- node_add_at(root, m, c);+ Node o = nodes[c];+ NodeId after = o.next;node_free(c);- nodes[m].slot = slot;+ NodeId m = node_new_sym(o.sym);+ if (!m) break;+ Node *q = &nodes[m];+ q->x = o.x; q->y = o.y; q->rx4 = o.rx4; q->ry4 = o.ry4; q->mat = o.mat; q->alpha = o.alpha;+ q->flags = o.flags; q->flags2 = o.flags2 & (uint8_t)~NF2_PARTIAL; /* whole: no children to make later */+ q->name = o.name; q->key = o.key;+ node_add_at(root, m, after);+ nodes[m].slot = o.slot;S->map = m;break;}diff --git a/games/championisland/src/spr.c b/games/championisland/src/spr.cindex 1eeb0150..35b5294d 100644--- a/games/championisland/src/spr.c+++ b/games/championisland/src/spr.c@@ -18,6 +18,9 @@ static CLzmaDec dec;static const uint8_t *z_src;static uint32_t z_in, z_len, z_out, z_total;+#ifdef HOST+uint64_t z_bytes, z_opens; /* tests: how much the decoder did */+#endifvoid z_open(uint32_t off, uint32_t clen, uint32_t rawlen) {memset(&dec, 0, sizeof dec);dec.prop.lc = 0;@@ -31,6 +34,9 @@ void z_open(uint32_t off, uint32_t clen, uint32_t rawlen) {dec.dicBufSize = LZMA_DICT;LzmaDec_Init(&dec);z_src = ci_data + off;+#ifdef HOST+ z_opens++;+#endifz_in = 0;z_len = clen;z_out = 0;@@ -54,6 +60,9 @@ uint32_t z_read(uint32_t n, const uint8_t **at) {z_in += (uint32_t)inlen;uint32_t got = (uint32_t)dec.dicPos - start;z_out += got;+#ifdef HOST+ z_bytes += got;+#endif*at = ring + start;return got;}@@ -129,6 +138,16 @@ static void compact(void) {static inline uint16_t age(const Entry *e) { return (uint16_t)((uint16_t)tick - e->used); }+/* 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) {+ uint32_t n = 0;+ unsigned c = 0;+ for (unsigned i = 0; i < nent; i++)+ if (age(&ent[i]) <= keep) { n += (ent[i].size + 3) & ~3u; c++; }+ if (count) *count = c;+ return n;+}+static void evict_one(void) {int old = 0;for (int i = 1; i < nent; i++)@@ -136,18 +155,21 @@ static void evict_one(void) {ent[old] = ent[--nent];}-/* Room for n bytes; evicts only entries not used this tick unless forced. */-static uint8_t *alloc(uint32_t n, bool force) {+/* 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) {n = (n + 3) & ~3u;if (n > cache_bytes) return NULL;if (top + n > cache_bytes || nent >= ENTRIES) {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 */int old = 0;for (int i = 1; i < nent; i++)- if (age(&ent[i]) > age(&ent[old])) old = i;- if (!force && age(&ent[old]) <= 1) return NULL;+ if (age(&ent[i]) > age(&ent[old]) || (!age(&ent[i]) && !age(&ent[old]) && ent[i].size < ent[old].size)) old = i;+ if (!force && age(&ent[old]) <= keep) return NULL;live -= (ent[old].size + 3) & ~3u;evict_one();}@@ -159,6 +181,7 @@ static uint8_t *alloc(uint32_t n, bool force) {top += n;return p;}+static uint8_t *alloc(uint32_t n, bool force) { return alloc_keep(n, force, 1); }/* Encodes rows of palette indices as runs of visible pixels:* u16 w, u16 h, u16 row offsets[h] (from the start), then per row: u16 nruns,@@ -254,6 +277,44 @@ static const uint8_t *pinned(uint16_t sp) {if (pins[i].rle && pins[i].sp == sp) return pins[i].rle;return NULL;}+bool spr_pinned(uint16_t sp) { return pinned(sp) != NULL; }++/* A big sprite's opaque inner rectangle (a menu's panel: what it covers is not+ * drawn), measured once from its pixels: the rows around the middle one whose+ * middle pixel is opaque, and the opaque run through it that they all share.+ * box: x0, y0, x1, y1 in the sprite (excluded ends); false if none. */+#define BOXES 8+static struct { uint16_t sp; int16_t b[4]; } boxes[BOXES];+static int nboxes, box_next;+bool spr_opaque_box(uint16_t sp, int16_t box[4]) {+ for (int i = 0; i < nboxes; i++)+ if (boxes[i].sp == sp) { memcpy(box, boxes[i].b, sizeof boxes[i].b); return box[2] > box[0] && box[3] > box[1]; }+ Sprite s;+ sprite_info(sp, &s);+ if (s.w > SPRITE_W_MAX || !spr_rows_open(sp, &s)) return false;+ const uint8_t *al = palalpha(s.sheet);+ int cx = s.w / 2, cy = s.h / 2, x0 = 0, x1 = s.w, y0 = -1, y1 = -1;+ for (int y = 0; y < s.h; y++) {+ if (!z_get(rowbuf, s.w)) { y0 = -1; break; }+ if (al[rowbuf[cx]] != 255) {+ if (y > cy) break; /* the block around the middle row ended */+ y0 = -1; /* a block above the middle: not it */+ continue;+ }+ int a = cx, b = cx + 1;+ while (a > 0 && al[rowbuf[a - 1]] == 255) a--;+ while (b < s.w && al[rowbuf[b]] == 255) b++;+ if (y0 < 0) { y0 = y; x0 = a; x1 = b; }+ else { x0 = a > x0 ? a : x0; x1 = b < x1 ? b : x1; }+ y1 = y + 1;+ }+ int16_t b[4] = {(int16_t)x0, (int16_t)(y0 < 0 ? 0 : y0), (int16_t)x1, (int16_t)(y0 < 0 ? 0 : y1)};+ int i = nboxes < BOXES ? nboxes++ : box_next++ % BOXES;+ boxes[i].sp = sp;+ memcpy(boxes[i].b, b, sizeof b);+ memcpy(box, b, sizeof b);+ return b[2] > b[0] && b[3] > b[1];+}const uint8_t *spr_get(uint16_t sp) {if (sp >= SPRITE_COUNT || !mem) return NULL;@@ -298,6 +359,16 @@ const uint8_t *spr_get(uint16_t sp) {return f2 ? mem + 4u * ent[f2 - 1].off4 : NULL;}+/* spr_get, only if what this frame drew so far can stay */+const uint8_t *spr_get_soft(uint16_t sp) {+ const uint8_t *r = spr_peek(sp);+ if (r || sp >= SPRITE_COUNT || !mem) return r;+ Sprite s;+ sprite_info(sp, &s);+ if (fresh_bytes(0, NULL) + (((s.rle ? s.rle : rle_bound(s.w, s.h)) + 3) & ~3u) > cache_bytes) return NULL;+ return spr_get(sp);+}+/* the cached runs if the sprite is in the cache now (never decodes) */const uint8_t *spr_peek(uint16_t sp) {const uint8_t *pn = pinned(sp);@@ -309,6 +380,26 @@ const uint8_t *spr_peek(uint16_t sp) {return mem + 4u * e->off4;}+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));+ return true;+ }+ if (s->kind != 0) return false;+ const uint8_t *b = ci_data + HDR(H_BANKS) + 12u * s->bank;+ z_open(rd32(b), rd32(b + 4), rd32(b + 8));+ return z_get(NULL, s->off);+}++bool spr_room(uint32_t n) {+ n = (n + 3) & ~3u;+ if (!mem || n > cache_bytes) return false;+ unsigned nfresh;+ return fresh_bytes(1, &nfresh) + n <= cache_bytes && nfresh < ENTRIES;+}+const uint8_t *spr_stream(uint16_t sp) {uint32_t n = HDR(H_NSTREAMS);const uint8_t *t = ci_data + HDR(H_STREAMS);@@ -372,6 +463,33 @@ static uint32_t mask_build(const uint8_t *r, const uint8_t *al, uint8_t *out) {return o.at;}+/* the same from the decoder's rows (the sprite is not in the cache) */+static uint32_t mask_rows(uint16_t sp, const Sprite *s, const uint8_t *al, uint8_t *out) {+#ifdef HOST+ if (getenv("CI_SPR_MISS")) fprintf(stderr, "maskrows %u %dx%d rle %u out %d\n", sp, s->w, s->h, (unsigned)s->rle, out != NULL);+#endif+ if (!spr_rows_open(sp, s)) return 0;+ MaskOut o = {out, 4 + 2u * s->h, 0, 0};+ for (int y = 0; y < s->h; y++) {+ if (!z_get(rowbuf, s->w)) return 0;+ if (out) { out[4 + 2 * y] = (uint8_t)o.at; out[5 + 2 * y] = (uint8_t)(o.at >> 8); }+ uint32_t cnt_at = o.at;+ o.at += 2;+ o.n = 0;+ o.last = 0;+ int s0 = -1;+ for (int x = 0; x < s->w; x++) {+ bool op = al[rowbuf[x]] == 255;+ if (op && s0 < 0) s0 = x;+ else if (!op && s0 >= 0) { mask_span(&o, s0, x); s0 = -1; }+ }+ if (s0 >= 0) mask_span(&o, s0, s->w);+ if (out) { out[cnt_at] = (uint8_t)o.n; out[cnt_at + 1] = (uint8_t)(o.n >> 8); }+ }+ if (out) { out[0] = (uint8_t)s->w; out[1] = (uint8_t)(s->w >> 8); out[2] = (uint8_t)s->h; out[3] = (uint8_t)(s->h >> 8); }+ return o.at;+}+const uint8_t *spr_mask(uint16_t sp) {if (sp >= SPRITE_COUNT || !mem) return NULL;unsigned f = find((uint16_t)(sp | MASK));@@ -379,13 +497,26 @@ const uint8_t *spr_mask(uint16_t sp) {ent[f - 1].used = (uint16_t)tick;return mem + 4u * ent[f - 1].off4;}- if (!spr_get(sp)) return NULL;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);+ 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;- uint8_t *m = alloc(n, false); /* may move the sprite (compaction): look it up again */+ uint8_t *m = alloc_keep(n, false, 0); /* may move the sprite (compaction): look it up again */unsigned fs = find(sp);if (!m || !fs) return NULL;mask_build(mem + 4u * ent[fs - 1].off4, al, m);diff --git a/games/championisland/src/spr.h b/games/championisland/src/spr.hindex a549e541..d05f2667 100644--- a/games/championisland/src/spr.h+++ b/games/championisland/src/spr.h@@ -13,10 +13,17 @@ bool z_get(uint8_t *dst, uint32_t n);* nruns, then (skip, len, len palette indices) per run. */const uint8_t *spr_get(uint16_t sprite);const uint8_t *spr_peek(uint16_t sprite); /* only if cached */+const uint8_t *spr_get_soft(uint16_t sprite); /* spr_get without letting go of what this frame already took */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);+/* 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_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) */+bool spr_opaque_box(uint16_t sprite, int16_t box[4]); /* its opaque middle: x0, y0, x1, y1 (decodes it once) */void spr_release(uint16_t sprite); /* not needed again this frame */ /* its runs kept elsewhere by the scene (NULL: no more) */void spr_setup(uint8_t *mem, uint32_t size); /* where the cache lives (game.c's arena) */void spr_reset(void);diff --git a/games/championisland/src/world.c b/games/championisland/src/world.cindex 8c23d823..18b1ddc1 100644--- a/games/championisland/src/world.c+++ b/games/championisland/src/world.c@@ -129,7 +129,8 @@ static int statics_in(float x0, float y0, float x1, float y1, uint8_t *bits, int#define RAIN_MAX 48#define PETAL_MAX 80typedef struct {- uint8_t water[WATER * WATER]; /* the sea's tile now (w9a: frames 0-15, 16-31) */+ uint8_t water[WATER * WATER / 2]; /* the sea's tile now (w9a: frames 0-15, 16-31), 4 bits a pixel */+ uint16_t water_col[16]; /* their colours (it has 10) */int water_look; /* which, -1 before the first */NodeId map, player, water_clip;float rain; /* bca's alpha (drawn by code, draw_over) */@@ -155,6 +156,10 @@ typedef struct {uint8_t npc_beeps;} World;static World *W;+/* the island's layer (the screen and a margin) fits, with its cache */+#define LAYER_W (VIEW_W + 8)+#define LAYER_H (SCREEN_H + 4)+_Static_assert(sizeof(World) + LAYER_W * LAYER_H + MIN_CACHE <= ARENA_BYTES, "the island's layer does not fit");/* ---------------------------------------------------------------- the layer */static void paint(int x0, int y0, int w, int h) {@@ -224,7 +229,8 @@ static void draw_static_over(unsigned id, Mat m, uint8_t alpha) {static void draw_map(NodeId map, Mat m, uint8_t alpha) {float vx, vy;view_origin(&vx, &vy);- float vx1 = vx + VIEW_W, vy1 = vy + VIEW_H;+ float vx1 = vx + VIEW_W, vy1 = vy + gfx_view_bottom();+ vy += gfx_view_top();uint8_t bits[STATIC_BITS / 8];memset(bits, 0, sizeof bits);uint16_t front[FRONT_MAX];@@ -314,7 +320,7 @@ static void stream_children(bool force) {W->stream_x = vx;W->stream_y = vy;W->streamed = true;- node_stream(W->map, vx - 40, vy - 40, vx + VIEW_W + 40, vy + VIEW_H + 40);+ node_stream(W->map, vx - 40, vy + gfx_view_top() - 40, vx + VIEW_W + 40, vy + gfx_view_bottom() + 40);}/* ---------------------------------------------------------------- places (location markers) */@@ -437,31 +443,42 @@ static uint16_t sprite_of(uint16_t sym) {return si.type == SYM_BITMAP ? (uint16_t)si.v : NONE16;}+extern uint8_t spr_rowbuf[SPRITE_W_MAX];+static void water_make(int look) {/* w9a: the tile NewLargeWater1Art2 (frames 0-15), with Art1 over it (frames 16-31) */const uint16_t spr[2] = {sprite_of(S_overworld_Mf), sprite_of(S_overworld_Uf)};+ const uint16_t *pal = pal565(SHEET_OVERWORLD);+ const uint8_t *al = palalpha(SHEET_OVERWORLD);int clear = bg_clear_index();- memset(W->water, clear < 0 ? 0 : clear, sizeof W->water);+ /* colour 0 is the clear one, the others come as the tile shows them */+ uint8_t used[16];+ int nused = 1;+ used[0] = (uint8_t)(clear < 0 ? 0 : clear);+ memset(W->water, 0, sizeof W->water);+ /* straight from the decoder: the cache keeps what the frames draw */for (int k = 0; k <= look; k++) {- const uint8_t *r = spr[k] != NONE16 ? spr_get(spr[k]) : NULL;- if (!r) continue;- const uint8_t *al = palalpha(SHEET_OVERWORLD);- int h = rd16(r + 2);- for (int v = 0; v < h && v < WATER; v++) {- const uint8_t *p = r + rd16(r + 4 + 2 * v);- int n = rd16(p), u = 0;- p += 2;- for (int j = 0; j < n; j++) {- u += *p++;- int code = *p++, len = code & 0x80 ? (code & 0x7F) + 1 : code;- for (int i = 0; i < len; i++, u++) {- uint8_t c = code & 0x80 ? p[0] : p[i];- if (u < WATER && al[c] >= 128) W->water[v * WATER + u] = c;+ Sprite si;+ if (spr[k] == NONE16) continue;+ sprite_info(spr[k], &si);+ if (si.w > SPRITE_W_MAX || !spr_rows_open(spr[k], &si)) continue;+ for (int v = 0; v < si.h && v < WATER; v++) {+ if (!z_get(spr_rowbuf, si.w)) break;+ for (int u = 0; u < si.w && u < WATER; u++) {+ uint8_t c = spr_rowbuf[u];+ if (al[c] < 128) continue;+ int j = 0;+ while (j < nused && used[j] != c) j++;+ if (j == nused) {+ if (nused < 16) used[nused++] = c;+ else j = nused - 1; /* more than 16 colours (never): the last one */}- p += code & 0x80 ? 1 : len;+ uint8_t *b = &W->water[(v * WATER + u) >> 1];+ *b = (uint8_t)(u & 1 ? (*b & 0x0F) | j << 4 : (*b & 0xF0) | j);}}}+ for (int j = 0; j < 16; j++) W->water_col[j] = pal[used[j < nused ? j : 0]];W->water_look = look;}@@ -538,7 +555,7 @@ static void sys_conditional(void) {}static bool triggered(NodeId n) {- Ent *e = ent_get(n);+ Ent *e = ent_peek(n); /* a trigger has one (sys_triggers) */return e && e->ntrig > 0;}@@ -713,7 +730,7 @@ 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_ID, 255);+ if (gs != NONE16) gfx_sprite(gs, (Mat){1, 0, 0, 1, 0, (float)gfx_view_top()}, 255); /* over the top of the screen */const uint8_t *t = pattern(1);if (!t || !W->npetal) return;unsigned looks = rd16(t + 2), look = W->tick / 3 % (looks ? looks : 1);@@ -815,7 +832,9 @@ static void start_overworld(void) {W->ending = ending;if (W->ending) clip_each_slot(S_overworld_mAa, 0, petal_slot, NULL);if (!W->map) return;- mem_layout(VIEW_W + 8, VIEW_H + 8, SHEET_OVERWORLD, paint);+ /* the island fills the screen: the stage and 30 rows above and below */+ gfx_view(-VIEW_Y, VIEW_H + VIEW_Y);+ mem_layout(LAYER_W, LAYER_H, SHEET_OVERWORLD, paint);/* after the ending, the glow is read from its runs in the data (pack.py) */const uint8_t *glow = pattern(2);if (ending && glow && rd16(glow + 2) == glow_sprite()) spr_pin(glow_sprite(), glow + 4);@@ -894,7 +913,7 @@ static void tick_overworld(void) {if (getenv("CI_DEBUG") && W->player && W->tick % 10 == 0) {float px, py;ent_pos(W->player, &px, &py);- Ent *e = ent_get(W->player);+ Ent *e = ent_peek(W->player);Rect r;bool hb = ent_bounds(W->player, &r);for (int i = 0; i < ent_count(); i++) {@@ -902,7 +921,7 @@ static void tick_overworld(void) {if (!n || !comp_has(nodes[n].T, C_scenePortal)) continue;float x, y;ent_pos(n, &x, &y);- Ent *pe = ent_get(n);+ Ent *pe = ent_peek(n);if (fabsf(x - px) < 150 && fabsf(y - py) < 150)fprintf(stderr, " portal %s at %.0f,%.0f trig %d vis %d\n", str(comp_str(nodes[n].T, C_scenePortal, F_name)), x, y, pe ? pe->ntrig : -1, node_visible(n));}@@ -915,11 +934,11 @@ static void tick_overworld(void) {static void draw_under_overworld(void) {if (!W || !W->map) return;- /* the sea's look changes every 16 frames */- int look = (int)(game.ticks / 16) % 2;+ /* the sea's look changes every 16 frames (of the island's: still under a menu) */+ int look = (int)(W->tick / 16) % 2;if (look != W->water_look) {water_make(look);- bg_water(W->water, WATER, WATER);+ bg_water4(W->water, WATER, WATER, W->water_col);}float vx, vy;view_origin(&vx, &vy);diff --git a/games/championisland/tests/check.py b/games/championisland/tests/check.pynew file mode 100644index 00000000..e7e40f14--- /dev/null+++ b/games/championisland/tests/check.py@@ -0,0 +1,129 @@+#!/usr/bin/env python3+"""Checks of Champion Island on a computer (make test): the host build, with+AddressSanitizer and UBSan, in scenes that once went wrong.++ python3 tests/check.py build/play+"""+import os+import random+import shutil+import subprocess+import sys+import tempfile++import numpy as np+from PIL import Image++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)."""+ d = tempfile.mkdtemp(prefix="ci_check_")+ os.makedirs(d + "/saves")+ 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"]+ if shots:+ args += ["--shots", ",".join(str(s) for s in shots)]+ p = subprocess.run(args, capture_output=True, text=True, env=e, timeout=900)+ imgs = {s: np.asarray(Image.open(f"{d}/shot_{s}.ppm").convert("RGB")) for s in shots if os.path.exists(f"{d}/shot_{s}.ppm")}+ 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]}")+ # 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"):+ failures.append(f"{scene}: nodes leaked, {line.strip()}")+ break+ # ... and listed by its parent (play.c's CI_CONSIST)+ if "is not listed by its parent" in p.stderr:+ failures.append(f"{scene}: " + next(l for l in p.stderr.splitlines() if "is not listed" in l))+ return p.stdout, p.stderr, imgs+++def check(name, ok, why=""):+ print(("ok " if ok else "FAIL ") + name)+ if not ok:+ failures.append(f"{name}: {why}")+++def items(stderr):+ """The last frame's draw list (CI_ITEMS): (kind, box) per item."""+ frames, cur = [], None+ for line in stderr.splitlines():+ f = line.split()+ if len(f) < 17 or f[0] != "item":+ continue+ if f[1] == "0":+ cur = []+ frames.append(cur)+ cur.append((int(f[3]), [int(v) for v in f[9:13]], int(f[14])))+ return frames[-1] if frames else []+++def random_keys(scene, seed, frames):+ rng = random.Random(seed)+ out, t = [], 0+ while t < frames:+ k = rng.choices(["left", "right", "up", "down", "ok", "back", "pause"], weights=[5, 5, 5, 5, 4, 1, 0.3])[0]+ d = rng.randint(1, 40)+ out.append(f"{t}-{t + d}:{k}")+ t += d + rng.randint(0, 10)+ return ",".join(out)+++# Lucky is drawn while he walks inside a house (his walk is shown from the+# second frame of his clip: it used to be missing, only the shadow was left)+_, err, _ = run("interior:teahouse", 50, "30-70:up", env={"CI_ITEMS": "1"})+sprites = [b for k, b, ref in items(err) if k == 0]+shadows = [s for s in sprites if s[3] - s[1] <= 4]+++def stands_on(s): # someone's size, across the shadow, their feet on it+ return any(b[2] - b[0] <= 48 and b[1] < s[1] and s[1] - 2 <= b[3] <= s[3] + 2 and b[0] <= s[2] and b[2] >= s[0]+ for b in sprites if b is not s)+++check("Lucky walks inside a house", bool(shadows) and all(stands_on(s) for s in shadows), "a shadow with nobody on it")++# Exit in a sport's pause menu goes back to the island and stays there (the+# OK that chose it, let go on the island, used to open the door again)+_, err, _ = run("pingpong", 1100, "600:ok,900:back,910:down,920:down,930:down,940-943:ok", env={"CI_LOG": "1"})+scenes = [line.split(" scene ")[1] for line in err.splitlines() if " scene " in line]+check("Exit stays on the island", scenes[-1:] == ["overworld"] and "menu pause quit" in err, f"scenes {scenes}")++# the island fills the screen, the sports keep the doodle's frame+_, _, img = run("overworld@hub", 40, shots=[39])+check("the island fills the screen", img[39][:30].any() and img[39][210:].any(), "the bands above and below are black")+_, _, 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")++# 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)+run("climbing", 1200, "60:ok,300:back,310:down,320:down,330:ok,400:ok,700:back,710:down,720:down,730:down,740:ok,"+ "900-960:down,1000:back,1050:back")+print(("ok " if len(failures) == before else "FAIL ") + "no nodes left behind by a scene")++# the climbing wall is made whole (its nodes used to run out: 40 to 62 missing)+for v in ("climbing", "climbing:hard"):+ before = len(failures)+ run(v, 60)+ print(("ok " if len(failures) == before else "FAIL ") + f"{v} has all its nodes")++# 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"):+ before = len(failures)+ run(scene, 1500, random_keys(scene, 1, 1500))+ print(("ok " if len(failures) == before else "FAIL ") + f"random keys in {scene}")++if failures:+ print("\n".join(failures))+ sys.exit(1)+print("all checks passed")diff --git a/games/championisland/tests/play.c b/games/championisland/tests/play.cindex a752d22f..ea76c5a2 100644--- a/games/championisland/tests/play.c+++ b/games/championisland/tests/play.c@@ -11,6 +11,7 @@#include <sys/stat.h>#include "../src/ent.h"#include "../src/spr.h"+#include "../src/phys.h"extern uint32_t host_keys, host_time;void host_shot(const char *path);@@ -34,10 +35,15 @@ static uint32_t key_bit(const char *s) {}void world_census(void);+void ent_stats(int *live, int *states);int main(int argc, char **argv) {const char *scene = NULL, *out = "build/play", *saves = "build/play/saves", *shots = "", *gif = NULL;int frames = 300;+ unsigned peak_nodes = 0;+ uint64_t z_max = 0;+ int z_heavy = 0; /* frames decoding more than 60 KB */+ int peak_live = 0, peak_states = 0, peak_bodies = 0;bool fresh = false;for (int i = 1; i < argc; i++) {if (!strcmp(argv[i], "--scene") && i + 1 < argc) scene = argv[++i];@@ -64,13 +70,39 @@ 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 (scene) game_go(scene);for (int f = 0; f < frames && game_running; 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;+ extern uint64_t z_bytes;+ uint64_t zb0 = z_bytes;game_tick();+ if (getenv("CI_CONSIST")) {+ extern NodeId node_unlisted(void);+ static bool told;+ NodeId u = node_unlisted();+ if (u && !told) {+ told = true;+ fprintf(stderr, "f%d: node %u (sym %u) is not listed by its parent %u (sym %u), scene %s\n", f, u, nodes[u].sym, nodes[u].parent,+ nodes[nodes[u].parent].sym, game.name);+ }+ }game_draw();+ 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;+ if (zf > 60 * 1024) z_heavy++;+ if (node_count() > peak_nodes) peak_nodes = node_count();+ if (getenv("CI_NODES") && f % atoi(getenv("CI_NODES")) == 0) fprintf(stderr, "f%d nodes %u scene %s\n", f, node_count(), game.name);+ int live, states;+ ent_stats(&live, &states);+ if (live > peak_live) peak_live = live;+ if (states > peak_states) peak_states = states;+ int nb = 0;+ for (int b = 0; b < BODY_MAX; b++) nb += bodies[b].used;+ if (nb > peak_bodies) peak_bodies = nb;host_time += 33;char p[512];bool shot = false;@@ -83,7 +115,17 @@ int main(int argc, char **argv) {if (shot) { snprintf(p, sizeof p, "%s/shot_%d.ppm", out, f); host_shot(p); }if (gif && f >= g0 && f <= g1 && (f - g0) % gs == 0) { snprintf(p, sizeof p, "%s/f_%05d.ppm", out, f); host_shot(p); }}- printf("frames done: %u ticks, nodes %u, cache %u, scene %s:%s\n", game.ticks, node_count(), spr_cache_used(), game.name, game.variant);+ 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);+ 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);+ if (getenv("CI_ZSTAT")) {+ extern uint64_t z_bytes, z_opens;+ fprintf(stderr, "decoded %.1f KB a frame in %.1f opens, at most %.0f KB, %d frames over 60 KB\n", z_bytes / 1024.0 / frames,+ (double)z_opens / frames, z_max / 1024.0, z_heavy);+ }if (getenv("CI_CENSUS")) world_census();return 0;}