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: all seven sports, rain over the table tennis village, faster scenery redraws
Mason Chen19727492cdd8
diff --git a/Makefile b/Makefileindex 840257f7..fa3cac78 100644--- a/Makefile+++ b/Makefile@@ -138,6 +138,8 @@ APP_portal = games/portal/output/portal.nwa:PortalReturns.nwaAPP_chess = games/chess/output/chess.nwa:NumChess.nwaAPP_tetris = games/tetris/tetris/target/thumbv7em-none-eabihf/release/tetris:Tetris.nwaAPP_numvisuals = games/numvisuals/output/numvisuals.nwa:NumVisuals.nwa+# too big to share the calculator's app space with NumPlay: only on its own+APP_championisland = games/championisland/output/championisland.nwa:ChampionIsland.nwaapps: | $(B)$(MAKE) -C games/numdash build NWLINK="node node_modules/nwlink/bin/nwlink"@@ -148,6 +150,7 @@ apps: | $(B)$(MAKE) -C games/portal build NWLINK="$(NWLINK)"$(MAKE) -C games/chess build NWLINK="$(NWLINK)"$(MAKE) -C games/numvisuals build NWLINK="$(NWLINK)"+ $(MAKE) -C games/championisland build NWLINK="$(NWLINK)"cd games/tetris/tetris && NWLINK="$(NWLINK)" $(CARGO) build --release --quietcp $(word 1,$(subst :, ,$(APP_numdash))) $(B)/apps/$(word 2,$(subst :, ,$(APP_numdash)))cp $(word 1,$(subst :, ,$(APP_crossyroad))) $(B)/apps/$(word 2,$(subst :, ,$(APP_crossyroad)))@@ -158,6 +161,7 @@ apps: | $(B)cp $(word 1,$(subst :, ,$(APP_chess))) $(B)/apps/$(word 2,$(subst :, ,$(APP_chess)))cp $(word 1,$(subst :, ,$(APP_tetris))) $(B)/apps/$(word 2,$(subst :, ,$(APP_tetris)))cp $(word 1,$(subst :, ,$(APP_numvisuals))) $(B)/apps/$(word 2,$(subst :, ,$(APP_numvisuals)))+ cp $(word 1,$(subst :, ,$(APP_championisland))) $(B)/apps/$(word 2,$(subst :, ,$(APP_championisland)))arm-none-eabi-strip --strip-unneeded $(B)/apps/Tetris.nwaSTD_APPS = $(foreach g,$(STD_GAMES),$(B)/apps/$(NWA_$(g)))@@ -210,5 +214,6 @@ clean:-$(MAKE) -C games/portal clean-$(MAKE) -C games/chess clean-$(MAKE) -C games/numvisuals clean+ -$(MAKE) -C games/championisland clean-cd games/tetris/tetris && $(CARGO) clean-$(foreach g,$(STD_GAMES),$(MAKE) -C games/$(g) clean;)diff --git a/games/championisland/Makefile b/games/championisland/Makefileindex e98358a2..8896f00f 100644--- a/games/championisland/Makefile+++ b/games/championisland/Makefile@@ -9,10 +9,15 @@ NWLINK ?= npx --yes -- [email protected]STRIP ?= arm-none-eabi-strip --strip-unneeded # STRIP=true keeps symbols (tools/emu.py --profile)BUILD_DIR = outputDOODLE ?= ../../../potherca-blog/google-doodle-champion-island-GAME = src/res.c src/spr.c src/gfx.c src/font.c src/font_data.c src/node.c src/ent.c src/phys.c src/store.c src/game.c \- src/menus.c src/dialog.c src/hud.c src/world.c src/film.c src/names.c src/lzma/LzmaDec.c $(SPORTS)+GAME = $(HOT) $(COLD)+# the drawing and the island run every frame at -O2; menus, dialogue and the+# sports' rules are small at -Os (the app has to fit in the calculator)+HOT = src/res.c src/spr.c src/gfx.c src/font.c src/font_data.c src/node.c src/ent.c src/phys.c src/game.c \+ src/world.c src/lzma/LzmaDec.c+COLD = src/store.c src/menus.c src/dialog.c src/hud.c src/film.c src/names.c $(SPORTS)SPORTS ?= $(wildcard src/sport_*.c)SRC = $(GAME) src/plat_eadk.c src/main.c+COLD_OBJ = $(patsubst src/%.c,$(BUILD_DIR)/cold/%.o,$(COLD))HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.hCFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DDATA_BIN='"src/data.bin"'@@ -34,9 +39,13 @@ check: $(BUILD_DIR)/championisland.nwa$(BUILD_DIR)/data.o: src/data.S src/data.bin | $(BUILD_DIR)$(Q) $(CC) -c -DDATA_BIN='"src/data.bin"' $< -o $@-$(BUILD_DIR)/championisland.nwa: $(SRC) $(HEADERS) $(BUILD_DIR)/icon.o $(BUILD_DIR)/data.o+$(BUILD_DIR)/cold/%.o: src/%.c $(HEADERS)+ @mkdir -p $(@D)+ $(Q) $(CC) $(CFLAGS) -Os -c $< -o $@++$(BUILD_DIR)/championisland.nwa: $(HOT) src/plat_eadk.c src/main.c $(COLD_OBJ) $(HEADERS) $(BUILD_DIR)/icon.o $(BUILD_DIR)/data.o@echo "LD $@"- $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(SRC) $(BUILD_DIR)/data.o $(BUILD_DIR)/icon.o -lm -o $@+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(HOT) src/plat_eadk.c src/main.c $(COLD_OBJ) $(BUILD_DIR)/data.o $(BUILD_DIR)/icon.o -lm -o $@$(Q) $(STRIP) $@$(Q) arm-none-eabi-size $@diff --git a/games/championisland/src/data.bin b/games/championisland/src/data.binindex dda98ee5..327fa796 100644Binary files a/games/championisland/src/data.bin and b/games/championisland/src/data.bin differdiff --git a/games/championisland/src/data.h b/games/championisland/src/data.hindex 5b8dc4e9..18c67865 100644--- a/games/championisland/src/data.h+++ b/games/championisland/src/data.h@@ -2,7 +2,7 @@#ifndef CI_DATA_H#define CI_DATA_H-enum { H_MAGIC, H_NSHEETS, H_PAL, H_NSPRITES, H_SPRITES, H_NBANKS, H_BANKS, H_NSTREAMS, H_STREAMS, H_NSYMS, H_SYMS, H_NMATS, H_MATS, H_NSTRINGS, H_STRTAB, H_STRDATA, H_NEXPRS, H_EXPRS, H_NDLG, H_DLG, H_NMSGS, H_MSGS, H_NVARS, H_PAYLOADS, H_TTAB, H_BANKSPR, H_WORLDS, H_DTEXT, H_STRSORT, H_RESERVED3, H_COUNT };+enum { H_MAGIC, H_NSHEETS, H_PAL, H_NSPRITES, H_SPRITES, H_NBANKS, H_BANKS, H_NSTREAMS, H_STREAMS, H_NSYMS, H_SYMS, H_NMATS, H_MATS, H_NSTRINGS, H_STRTAB, H_STRDATA, H_NEXPRS, H_EXPRS, H_NDLG, H_DLG, H_NMSGS, H_MSGS, H_NVARS, H_PAYLOADS, H_TTAB, H_BANKSPR, H_WORLDS, H_DTEXT, H_STRSORT, H_TILES, H_COUNT };#define BANK_MAX 19296#define SPRITE_COUNT 2389#define BANK_COUNT 237diff --git a/games/championisland/src/game.h b/games/championisland/src/game.hindex 4e55575b..2a257315 100644--- a/games/championisland/src/game.h+++ b/games/championisland/src/game.h@@ -46,7 +46,7 @@ typedef struct {} Game;extern Game game;-#define ARENA_BYTES (84 * 1024)+#define ARENA_BYTES (85 * 1024)/* 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 129e9202..b7da9eb1 100644--- a/games/championisland/src/gfx.c+++ b/games/championisland/src/gfx.c@@ -10,7 +10,7 @@#define MAX_ITEMS 320#define MAX_AFF 64-enum { DI_SPRITE, DI_AFFINE, DI_RECT, DI_SHAPE, DI_TEXT, DI_STREAM };+enum { DI_SPRITE, DI_AFFINE, DI_RECT, DI_SHAPE, DI_TEXT, DI_STREAM, DI_TILES, DI_MASK, 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 */typedef struct {@@ -109,6 +109,16 @@ void gfx_rect(int x, int y, int w, int h, uint16_t c, uint8_t alpha) {if (it) *it = (Item){DI_RECT, alpha, 0, 0, (int16_t)x, (int16_t)y, (int16_t)(x + w), (int16_t)(y + h), 0, c};}+/* one pattern a frame: a small 4-bit image at n places (gfx_tiles) */+static struct { const uint8_t *px; const uint16_t *pal; const uint8_t *al; const int16_t *pos; int n, w, h, ox, oy; } tl;+void gfx_tiles(const uint8_t *px, 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) {+ if (!alpha || n <= 0 || w <= 0 || h <= 0) return;+ Item *it = add();+ if (!it) return;+ tl.px = px; 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)};+}+void gfx_shape(const uint8_t *shape, Mat m, uint8_t alpha) {if (!alpha || !shape[0]) return;/* bounds from the points */@@ -258,6 +268,20 @@ void bg_camera(int cx, int cy) {}}+/* scenery standing in front of the actors: the layer's own pixels again where+ * the sprite drawn at world (x, y) is opaque (its mask), so only the mask needs+ * to be in the cache, and what the layer has over it stays over it */+void bg_redraw(uint16_t sp, int x, int y, uint8_t flags) {+ if (!bgmem || sp >= SPRITE_COUNT) return;+ Sprite s;+ sprite_info(sp, &s);+ int x0 = x - bg_cx, y0 = y - bg_cy;+ if (!on_view(x0, y0, x0 + s.w, y0 + s.h)) return;+ Item *it = add();+ if (it) *it = (Item){DI_MASK, 255, (uint8_t)((flags & BD_FLIPX ? DF_FLIPX : 0) | (flags & BD_FLIPY ? DF_FLIPY : 0)), 0,+ (int16_t)x0, (int16_t)y0, (int16_t)(x0 + s.w), (int16_t)(y0 + s.h), sp, 0};+}+void bg_fill(int x, int y, int w, int h, uint8_t index) {int x0 = x > clip_x0 ? x : clip_x0, y0 = y > clip_y0 ? y : clip_y0;int x1 = x + w < clip_x1 ? x + w : clip_x1, y1 = y + h < clip_y1 ? y + h : clip_y1;@@ -361,6 +385,9 @@ void bg_draw(uint16_t sp, int x, int y, uint8_t flags, uint8_t alpha) {bool fx = flags & BD_FLIPX, fy = flags & BD_FLIPY;int w = rd16(r), h = rd16(r + 2);for (int v = 0; v < h; v++) {+ /* a row out of the painted strip is skipped whole, a run too */+ int rv = tr ? (fx ? dw - 1 - v : v) : (fy ? dh - 1 - v : v);+ if (tr ? (x + rv < clip_x0 || x + rv >= clip_x1) : (y + rv < clip_y0 || y + rv >= clip_y1)) continue;const uint8_t *p = r + rd16(r + 4 + 2 * v);int n = rd16(p), u = 0;p += 2;@@ -368,6 +395,9 @@ void bg_draw(uint16_t sp, int x, int y, uint8_t flags, uint8_t alpha) {u += *p++;int code = *p++, len = code & 0x80 ? (code & 0x7F) + 1 : code;bool fill = code & 0x80;+ int f = fx && !tr ? dw - u - len : fy && tr ? dh - u - len : u; /* the run's first cell along the row */+ int lo = tr ? y + f : x + f, c0 = tr ? clip_y0 : clip_x0, c1 = tr ? clip_y1 : clip_x1;+ if (lo >= c1 || lo + len <= c0) { u += len; p += fill ? 1 : len; continue; }for (int i = 0; i < len; i++, u++) {/* source (u, v) -> offset (i, j) in the drawn rectangle */int di = tr ? v : u, dj = tr ? u : v;@@ -606,16 +636,34 @@ static __attribute__((noinline)) void draw_affine_item(const Item *it, int y0, iint x0 = it->x0 < 0 ? 0 : it->x0, x1 = it->x1 > VIEW_W ? VIEW_W : it->x1;if (fabsf(ib) > fabsf(ia)) {/* turned about 90 degrees: a screen column walks one source row, so go- * column by column (one row decode per column, not one per pixel) */+ * column by column; a band needs a few neighbouring pixels of that row,+ * read from its runs into a small window (no row decode per pixel) */+ int wv = -1, wu0 = 0;+ int16_t win[8];for (int x = x0; x < x1; x++) {float fu = ia * (x + 0.5f) + ic * (y0 + 0.5f) + itx, fv = ib * (x + 0.5f) + id * (y0 + 0.5f) + ity;for (int y = y0; y < y1; y++, fu += ic, fv += id) {if (fu < 0 || fv < 0 || fu >= w || fv >= h) continue;int v = (int)fv, u = (int)fu;- if (r != line_spr || v != line_v) line_decode(r, v, w);- if (!(line_mask[u >> 3] & (1 << (u & 7)))) continue;+ if (v != wv || u < wu0 || u >= wu0 + 8) {+ wv = v;+ wu0 = ic < 0 ? u - 7 : u;+ for (int i = 0; i < 8; i++) win[i] = -1;+ const uint8_t *p = r + rd16(r + 4 + 2 * v);+ int n = rd16(p), cx = 0;+ p += 2;+ for (int k = 0; k < n && cx < wu0 + 8; k++) {+ cx += *p++;+ int code = *p++, len = code & 0x80 ? (code & 0x7F) + 1 : code;+ for (int i = cx > wu0 ? cx : wu0; i < cx + len && i < wu0 + 8; i++) win[i - wu0] = code & 0x80 ? p[0] : p[i - cx];+ p += code & 0x80 ? 1 : len;+ cx += len;+ }+ }+ int c = win[u - wu0];+ if (c < 0) continue;uint16_t *d = band + (y - by) * VIEW_W + x;- unsigned c = stream_buf[u], a = al[c];+ unsigned a = al[c];*d = (a == 255 && ga == 32) ? pal[c] : blend(pal[c], *d, (a * ga + 128) >> 8);}}@@ -683,6 +731,65 @@ 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 || !bgmem) return;+ const uint16_t *pal = pal565(bgsheet);+ const uint8_t *al = palalpha(bgsheet);+ int w = rd16(m), h = rd16(m + 2);+ bool fx = it->flags & DF_FLIPX;+ for (int y = y0; y < y1; y++) {+ int row = y - it->y0;+ if (it->flags & DF_FLIPY) row = h - 1 - row;+ const uint8_t *p = m + rd16(m + 4 + 2 * row);+ int n = rd16(p), x = 0;+ p += 2;+ uint16_t *d = band + (y - by) * VIEW_W;+ int ly = (bg_cy + y) % bgh;+ if (ly < 0) ly += bgh;+ const uint8_t *lrow = bgmem + ly * bgw;+ for (int k = 0; k < n; k++, p += 2) {+ x += p[0];+ int a = x, b = x + p[1];+ x = b;+ if (fx) { int t = w - b; b = w - a; a = t; }+ a += it->x0;+ b += it->x0;+ if (a < 0) a = 0;+ if (b > VIEW_W) b = VIEW_W;+ int lx = (bg_cx + a) % bgw;+ if (lx < 0) lx += bgw;+ for (int sx = a; sx < b; sx++) {+ uint8_t c = lrow[lx];+ if (al[c] == 255) d[sx] = pal[c];+ if (++lx == bgw) lx = 0;+ }+ }+ }+}++static __attribute__((noinline)) void draw_tiles_item(int y0, int y1, int by, unsigned ga) {+ for (int i = 0; i < tl.n; i++) {+ int tx = tl.ox + tl.pos[2 * i], ty = tl.oy + tl.pos[2 * i + 1];+ int a = ty > y0 ? ty : y0, b = ty + tl.h < y1 ? ty + tl.h : y1;+ if (a >= b || tx >= VIEW_W || tx + tl.w <= 0) continue;+ int x0 = tx < 0 ? -tx : 0, x1 = tx + tl.w > VIEW_W ? VIEW_W - tx : tl.w;+ for (int y = a; y < b; y++) {+ const uint8_t *row = tl.px + (y - ty) * (tl.w >> 1);+ uint16_t *d = band + (y - by) * VIEW_W;+ for (int bx = x0 >> 1; bx < (x1 + 1) >> 1; bx++) { /* two pixels a byte, mostly clear */+ unsigned v = row[bx];+ if (!v) continue;+ int x = 2 * bx;+ unsigned c = v & 15;+ if (c && x >= x0) d[tx + x] = blend(tl.pal[c], d[tx + x], (tl.al[c] * ga + 16) >> 5);+ c = v >> 4;+ if (c && x + 1 < x1) d[tx + x + 1] = blend(tl.pal[c], d[tx + x + 1], (tl.al[c] * ga + 16) >> 5);+ }+ }+ }+}+static __attribute__((noinline)) void draw_text_item(const Item *it, int y0, int y1, int by, int rows, unsigned ga) {const Aff *f = &affs[it->ref];font_scale(f->scale);@@ -712,6 +819,8 @@ static void draw_item(const Item *it, int by, int rows) {case DI_AFFINE: draw_affine_item(it, y0, y1, by, rows, ga); break;case DI_SHAPE: draw_shape_item(it, y0, y1, by, rows, ga); break;case DI_TEXT: draw_text_item(it, y0, y1, by, rows, ga); break;+ case DI_TILES: draw_tiles_item(y0, y1, by, ga); break;+ case DI_MASK: draw_mask_item(it, y0, y1, by); break;}}@@ -761,8 +870,8 @@ void gfx_end(void) {}#ifdef HOSTif (getenv("CI_STATS")) {- long area[6] = {0};- int cnt[6] = {0};+ long area[DI_KINDS] = {0};+ int cnt[DI_KINDS] = {0};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;@@ -792,6 +901,9 @@ void gfx_end(void) {}spr_get(sp);}+#ifdef HOST+ if (getenv("CI_NEED")) fprintf(stderr, "need %u of %u\n", (unsigned)need, (unsigned)spr_capacity());+#endif/* 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++) {@@ -805,12 +917,15 @@ void gfx_end(void) {need += sz;} else if (!streaming) stream_begin(it);}+ for (int i = 0; i < nitems; i++)+ if (items[i].kind == DI_MASK) spr_mask(items[i].ref);/* a sprite pushed out of the cache by a later one is drawn next frame */for (int i = 0; i < nitems; i++) {Item *it = &items[i];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);diff --git a/games/championisland/src/gfx.h b/games/championisland/src/gfx.hindex cf21fbfc..cb15c46c 100644--- a/games/championisland/src/gfx.h+++ b/games/championisland/src/gfx.h@@ -16,6 +16,9 @@ void gfx_sprite(uint16_t sprite, Mat m, uint8_t alpha); /* a sprite placed by mvoid gfx_sprite_ex(uint16_t sprite, Mat m, uint8_t alpha, bool opaque_only); /* opaque_only: skips see-through pixels */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,+ * index 0 clear, pal/al: RGB565 and alpha (0..32) of each index (the island's rain) */+void gfx_tiles(const uint8_t *px, 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);/* text: font size in px of the doodle's layout, colour RGB565 */void gfx_text(const char *s, Mat m, uint16_t color, uint8_t align, int16_t line_w, int16_t line_h, uint8_t alpha);void gfx_text_k(const char *s, Mat m, uint16_t color, uint8_t align, int16_t line_w, int16_t line_h, uint8_t alpha, int scale);@@ -42,6 +45,7 @@ void bg_redraw_water(void); /* the water tile's piint 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_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);uint16_t rgb565(uint8_t r, uint8_t g, uint8_t b);diff --git a/games/championisland/src/icon.png b/games/championisland/src/icon.pngindex 3fb559cc..f925eb25 100644Binary files a/games/championisland/src/icon.png and b/games/championisland/src/icon.png differdiff --git a/games/championisland/src/main.c b/games/championisland/src/main.cindex eee5c26a..b5661bf5 100644--- a/games/championisland/src/main.c+++ b/games/championisland/src/main.c@@ -35,6 +35,7 @@ void ci_init(void) {uint32_t perf_frames __attribute__((used)); /* read by tools/emu.py */uint32_t perf_ms __attribute__((used));uint32_t perf_max __attribute__((used)); /* the slowest frame's work, ms (after the first second) */+uint32_t perf_slow __attribute__((used)); /* frames (after the first second) over 33 ms of work */int main(void) {plat_begin();@@ -66,6 +67,7 @@ int main(void) {game_draw();perf_frames++;if (perf_frames > 30 && plat_millis() - t0 > perf_max) perf_max = plat_millis() - t0;+ if (perf_frames > 30 && plat_millis() - t0 > 33) perf_slow++;next += 1000 / FPS + (game.ticks % 3 == 0 ? 1 : 0); /* 33.3 ms */uint32_t now = plat_millis();if ((int32_t)(next - now) > 0) plat_sleep(next - now);diff --git a/games/championisland/src/sport_climbing.c b/games/championisland/src/sport_climbing.cindex 9feefab8..7e9e3ca9 100644--- a/games/championisland/src/sport_climbing.c+++ b/games/championisland/src/sport_climbing.c@@ -15,11 +15,12 @@enum { M_GROUND, M_JUMP, M_GRAB, M_HANG, M_FALL };enum { H_STATIC, H_MOVING, H_CIRCLING };-#define HOLD_MAX 64+#define HOLD_MAX 50#define GROUND_MAX 16#define CHECK_MAX 10#define NEVER 1e30f /* Number.MAX_SAFE_INTEGER */#define SKY_MAX 8+#define BG_MAX 768typedef struct {NodeId n;@@ -36,7 +37,12 @@ typedef struct { NodeId n; Rect r; } Area;typedef struct { NodeId n, lantern; Rect r; float px, py; bool mY; float delay; } Check;typedef struct {- NodeId root, map, climber, target, meter_text, clock_text, meter, clock, iba;+ NodeId root, map, climber, target, meter_text, clock_text, meter, clock, iba, bg;+ /* the cliff's tiles: where their keys are, their boxes */+ uint16_t bg_off[BG_MAX];+ uint8_t bg_box[BG_MAX][4];+ int nbg;+ uint32_t bg_ticks;Hold holds[HOLD_MAX];int nholds;Area grounds[GROUND_MAX];@@ -68,7 +74,9 @@ typedef struct {int nsky;float sky_x[SKY_MAX], sky_y[SKY_MAX];float sky_ref; /* the copy whose rows the forest texture matches */- bool tex; /* the forest texture is ready */+ bool tex, tex_on; /* the forest texture is ready, shown */+ uint8_t *tex_mem;+ uint8_t tex_sheet;int tex_cx, tex_cy;Countdown cd;bool counting;@@ -304,6 +312,214 @@ static void materialize(NodeId m) {}}+/* ---------------------------------------------------------------- the cliff+ * The cliff behind everything (f1 / Jba: 400 to 740 tiles, some of them the+ * sea's animated water) is drawn by code from a table of where each tile is,+ * so a frame only reads the tiles in view, and it needs no nodes: the water+ * tiles show the frame all of them are at (they started together). */+#define BG_UNIT 16+#define BG_ORG (-512)++static void bg_hook(NodeId n, Mat m, uint8_t al) {+ Clip c;+ if (n != S->bg || !clip_get(nodes[n].sym, &c)) return;+ float det = m.a * m.d - m.b * m.c;+ if (fabsf(det) < 1e-9f) return;+ /* the view in the cliff's space, in table units */+ float lx = 1e9f, ly = 1e9f, hx = -1e9f, hy = -1e9f;+ for (int i = 0; i < 4; i++) {+ float X = (i & 1) ? VIEW_W : 0, Y = (i & 2) ? VIEW_H : 0, dx = X - m.tx, dy = Y - m.ty;+ float u = (m.d * dx - m.c * dy) / det, v = (-m.b * dx + m.a * dy) / det;+ lx = fminf(lx, u); hx = fmaxf(hx, u); ly = fminf(ly, v); hy = fmaxf(hy, v);+ }+ int x0 = (int)floorf((lx - BG_ORG) / BG_UNIT), x1 = (int)floorf((hx - BG_ORG) / BG_UNIT);+ int y0 = (int)floorf((ly - BG_ORG) / BG_UNIT), y1 = (int)floorf((hy - BG_ORG) / BG_UNIT);+ for (int i = 0; i < S->nbg; i++) {+ const uint8_t *b = S->bg_box[i];+ if (b[0] > x1 || b[2] < x0 || b[1] > y1 || b[3] < y0) continue;+ unsigned nk;+ const uint8_t *p = varint(c.slots + S->bg_off[i], &nk);+ TKey cur = {0}, k;+ int idx = -1;+ for (unsigned j = 0; j < nk; j++) {+ p = tkey(p, &k);+ if (k.start <= nodes[n].frame) { cur = k; idx = (int)j; }+ }+ if (idx < 0 || (cur.flags & (K_ABSENT | K_HIDDEN)) || !cur.alpha || cur.kind != CK_SYM) continue;+ float a = 1, bb = 0, cc = 0, d = 1;+ if (cur.mat) { const float *mm = mat(cur.mat); a = mm[0]; bb = mm[1]; cc = mm[2]; d = mm[3]; }+ Mat km = mat_mul(m, (Mat){a, bb, cc, d, cur.x - (cur.rx4 * .25f * a + cur.ry4 * .25f * cc), cur.y - (cur.rx4 * .25f * bb + cur.ry4 * .25f * d)});+ node_draw_sym(cur.ref, S->bg_ticks, km, (uint8_t)((al * cur.alpha + 127) / 255));+ }+}++static uint8_t bg_unit(float v) {+ int u = (int)floorf((v - BG_ORG) / BG_UNIT);+ return (uint8_t)(u < 0 ? 0 : u > 255 ? 255 : u);+}++/* the map's biggest clip child becomes an empty (lazy) node drawn by bg_hook */+static void bg_setup_cliff(void) {+ NodeId old = 0;+ unsigned most = 0;+ Clip c;+ for (NodeId ch = nodes[S->map].first; ch; ch = nodes[ch].next)+ if (nodes[ch].kind == NK_CLIP && clip_get(nodes[ch].sym, &c) && c.nslots > most) { most = c.nslots; old = ch; }+ if (!old || most < 64 || !clip_get(nodes[old].sym, &c)) return;+ NodeId bg = node_new_sym_lazy(nodes[old].sym);+ if (!bg) return;+ Node *o = &nodes[old], *q = &nodes[bg];+ 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->name = o->name; q->key = o->key; q->frame = o->frame;+ uint16_t slot = o->slot;+ node_add_at(S->map, bg, old);+ node_free(old);+ nodes[bg].slot = slot;+ S->bg = bg;+ const uint8_t *p = c.slots;+ for (unsigned s = 0; s < c.nslots && S->nbg < BG_MAX; s++) {+ uint16_t off = (uint16_t)(p - c.slots);+ unsigned nk;+ p = varint(p, &nk);+ TKey cur = {0}, k;+ int idx = -1;+ for (unsigned j = 0; j < nk; j++) {+ p = tkey(p, &k);+ if (k.start <= nodes[bg].frame) { cur = k; idx = (int)j; }+ }+ float x, y, w, h;+ if (idx < 0 || (cur.flags & K_ABSENT) || cur.kind != CK_SYM || !sym_bounds(cur.ref, 0, 0, &x, &y, &w, &h)) continue;+ float a = 1, bb = 0, cc = 0, d = 1;+ if (cur.mat) { const float *mm = mat(cur.mat); a = mm[0]; bb = mm[1]; cc = mm[2]; d = mm[3]; }+ float tx = cur.x - (cur.rx4 * .25f * a + cur.ry4 * .25f * cc), ty = cur.y - (cur.rx4 * .25f * bb + cur.ry4 * .25f * d);+ float xs[4] = {x, x + w, x, x + w}, ys[4] = {y, y, y + h, y + h};+ float lx = 1e9f, ly = 1e9f, hx = -1e9f, hy = -1e9f;+ for (int i = 0; i < 4; i++) {+ float X = a * xs[i] + cc * ys[i] + tx, Y = bb * xs[i] + d * ys[i] + ty;+ lx = fminf(lx, X); hx = fmaxf(hx, X); ly = fminf(ly, Y); hy = fmaxf(hy, Y);+ }+ uint8_t *b = S->bg_box[S->nbg];+ b[0] = bg_unit(lx); b[1] = bg_unit(ly); b[2] = bg_unit(hx); b[3] = bg_unit(hy);+ S->bg_off[S->nbg++] = off;+ }+ node_draw_hook_id = bg;+ node_draw_hook = bg_hook;+}++static void end(void) {+ node_draw_hook = NULL;+ node_draw_hook_id = 0;+}++/* ---------------------------------------------------------------- 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 */++static bool sky_slot(unsigned slot, const SlotInfo *si, void *ctx) {+ (void)slot; (void)ctx;+ SymInfo t;+ sym_info(si->sym, &t);+ 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->nsky++;+ return true;+}++static void sky_paint(int x0, int y0, int w, int h) { (void)x0; (void)y0; (void)w; (void)h; }++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;+}++static void draw_under(void) {+ if (!S || !S->iba || !S->nsky) return;+ 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);+ }+}+/* ---------------------------------------------------------------- start */static void start(void) {S = scene_state(sizeof(State));@@ -328,9 +544,11 @@ static void start(void) {break;}if (!S->map) return;+ bg_setup_cliff();materialize(S->map);ent_register_tree(root);S->iba = ent_first(C_parallax);+ sky_setup();S->meter = ent_first(C_altitudeMeter);S->clock = ent_first(C_clock);S->climber = ent_first(C_climber);@@ -684,6 +902,20 @@ 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;@@ -729,6 +961,7 @@ static void tick(void) {if (menus_active()) return;sys_tutorial_once();if (menus_active() || !S || !S->map) return;+ S->bg_ticks++;tweens();camera_tween();sys_sort_draw();@@ -748,10 +981,9 @@ static void tick(void) {S->qq_on = S->oq_on = false;if (sys_countdown(&S->cd)) {S->counting = false;- if (!S->ended) { S->qq_on = S->oq_on = true; }- else S->oq_on = true;+ S->qq_on = S->oq_on = true;}}}-const SceneDef scene_climbing = {"climbing", start, tick, NULL, NULL, NULL, NULL};+const SceneDef scene_climbing = {"climbing", start, tick, end, draw_under, NULL, NULL};diff --git a/games/championisland/src/sport_marathon.c b/games/championisland/src/sport_marathon.cindex 58ad4d23..75f59122 100644--- a/games/championisland/src/sport_marathon.c+++ b/games/championisland/src/sport_marathon.c@@ -1,10 +1,801 @@-/* The marathon scene (a stub until it is ported). */-#include "../src/ent.h"+/* Marathon: the doodle's scene es (library 6A005E6C90D74E9A971A793C2ECC526F).+ *+ * Lucky races the tanuki along a beach track that scrolls by: the arrows+ * steer, pressing right near the front speeds up, staying on the sand path+ * builds speed and leaving it loses it. Rocks rolling in, and the projectiles+ * the spawners throw across the track, make her stumble (a quarter of her+ * speed gone); OK dodges them (40 ticks, then 150 to recharge). The time to+ * the finish is the score; the place (1st, 2nd, 3rd) gives the stars.+ * Variants: 400m (default), 800m, 1500m, 5000m.+ *+ * Systems, in the doodle's order: Ep (pause), Uo (rules), Wo (countdown),+ * Hr (triggers: path, obstacles), Ur (scrolling), Yr (new path pieces),+ * Rr (Lucky), Vr (spawners and rocks), Wr (speed lines), Xr (spawners'+ * throws), Tr (the tanuki), aq (sprite directions), zr (moves), yr (physics),+ * $r (HUD), as (the finish), Up (off screen), Vp (effects), Pp (draw order).+ * Speed lines are cosmetic streaks: kept in a table and drawn through one+ * node, not one node each. */+#include <math.h>+#include <stdio.h>+#include "ent.h"+#include "phys.h"+#define OPP_MAX 12+#define PATH_MAX 24+#define LINE_MAX 128+#define WALL_MAX 6+#define END_DELAY 80+#define MR (180 * .55f) /* Mr */++typedef struct {+ NodeId n, cursor, text;+ float speed, ncx, ncy, vx, vy, calpha;+ bool nc;+ int16_t body;+ const char *color;+} Opp;++typedef struct { float x, y; int8_t vx; uint8_t cls; } Line;++typedef struct {+ NodeId root, map, hud, player, ref, line_proto;+ NodeId t_time, t_time_s, t_speed, t_speed_s, t_dist, t_dist_s, placement, pcursor, ptext, needle, poof;+ /* the variant */+ int total, count;+ float opp_min, opp_max;+ uint16_t spawners[8], obstacles[2];+ int nspawners, nobstacles;+ /* the map (Ug): ticks, speed build-up, speed, distance scrolled */+ uint32_t tick;+ float LL, UB, off;+ /* Lucky (Sg) */+ bool on_path, trig_path, trig_obst;+ float pcalpha;+ int vK, KQ, U_;+ float eqa, vx, vy;+ int16_t body;+ /* the tanuki (Xg) */+ Opp opp[OPP_MAX];+ int nopp;+ /* the track's walls */+ NodeId walls[WALL_MAX];+ int16_t wall_body[WALL_MAX];+ int nwalls;+ /* spawner timers (Vr) and path pieces (Yr) */+ float t_spawn, t_obst;+ NodeId path[PATH_MAX];+ int npath;+ Line line[LINE_MAX];+ int nline;+ /* flow */+ Countdown cd;+ bool started, ended, finish_shown;+ int end_t, rating, banner_t;+ const char *banner;+ uint16_t banner_color, banner_outline;+ uint32_t score;+ char time_buf[16], speed_buf[32], dist_buf[24], place_buf[OPP_MAX + 1][12];+ uint16_t place_color[OPP_MAX + 1];+ NodeId place_text[OPP_MAX + 1];+ int nplace;+} State;++static State *S;++/* ---------------------------------------------------------------- helpers */+static bool has(NodeId n, int c) { return n && nodes[n].T != NONE16 && comp_has(nodes[n].T, c); }+static float jround(float v) { return floorf(v + 0.5f); }+static float len2(float x, float y) { return sqrtf(x * x + y * y); }+static float lerp(float a, float t, float b) { return a + (b - a) * t; } /* eh */+static int qh(int a, int b) { return (int)floorf(frand_range((float)a, (float)b)); }+static float pos_x(NodeId n) { float x, y; ent_pos(n, &x, &y); return x; }+static float track(NodeId n) { return pos_x(n) + S->off - 27; } /* Qr: where on the track, in px */++/* lk: frames as m:ss.cc */+static void fmt_time(char *b, size_t n, uint32_t f) {+ snprintf(b, n, "%u:%02u.%02u", (unsigned)(f / 1800 % 60), (unsigned)(f / 30 % 60), (unsigned)(f % 30 * 100 / 30));+}++/* Pr: the speed's class, 0 (still) to 4 (supernaruto) */+static int speed_class(float ub) { return ub == 0 ? 0 : ub < 5 ? 1 : ub < 6 ? 2 : ub < 7.5f ? 3 : 4; }++static void set_label(NodeId n, const char *l) { /* Kj without keeping the pose's frame */+ if (!n || !node_has_label(n, l)) return;+ if (!strcmp(node_label(n), l)) { node_stop(n); return; }+ node_goto(n, l, 0, false);+ node_update_one(n);+}++/* The scene's entities are not put in ent.c's registry: its records would run+ * short with twelve tanuki and a dozen path pieces. The systems below walk the+ * map's children instead. */+static NodeId spawn(uint16_t sym, NodeId parent, float x, float y) { /* Pj + Qj + Fj */+ NodeId e = node_new_sym(sym);+ if (!e) return 0;+ node_add(parent, e);+ ent_set_pos(e, x, y);+ return e;+}++static void kill(NodeId e) { /* co */+ if (e) node_free(e);+}++/* Hr: is Lucky's origin in one of t's trigger areas (t shown)? */+static bool inside(NodeId t) {+ NodeId p = S->player;+ if (!p || !node_visible(t)) return false;+ Mat og = node_global(p);+ for (NodeId c = nodes[t].first; c; c = nodes[c].next) {+ if (!has(c, C_triggerArea)) continue;+ Mat ag = node_global(c);+ float det = ag.a * ag.d - ag.b * ag.c;+ if (fabsf(det) < 1e-9f) continue;+ float dx = og.tx - ag.tx, dy = og.ty - ag.ty;+ if (node_hit(c, (ag.d * dx - ag.c * dy) / det, (-ag.b * dx + ag.a * dy) / det)) return true;+ }+ return false;+}++static void triggers(void) {+ S->trig_path = S->trig_obst = false;+ for (NodeId c = nodes[S->map].first; c; c = nodes[c].next) {+ if (!has(c, C_trigger)) continue;+ bool in = inside(c);+ if (in && has(c, C_marathonPath)) S->trig_path = true;+ if (in && has(c, C_marathonObstacle)) S->trig_obst = true;+ }+}++/* zr: what has a velocity and no body moves by it */+static void move_direct(void) {+ for (NodeId c = nodes[S->map].first; c; c = nodes[c].next) {+ float vx = 0, vy = 0;+ if (!has(c, C_velocity) || (has(c, C_collidable) && has(c, C_boundable))) continue;+ comp_vec(nodes[c].T, C_velocity, F_velocity, &vx, &vy);+ float x, y;+ ent_pos(c, &x, &y);+ ent_set_pos(c, x + vx, y + vy);+ }+}++/* Up: far off the stage, gone. The doodle's spawners have no deleteOffScreen+ * and pile up off the left edge forever (what they throw from there is gone at+ * once): here they go too, or the nodes would run out in the long races. */+static void delete_offscreen(void) {+ for (NodeId c = nodes[S->map].first, nx; c; c = nx) {+ nx = nodes[c].next;+ if (!has(c, C_deleteOffScreen) && !has(c, C_marathonSpawn)) continue;+ Mat g = node_global(c);+ if (g.tx < -1440 || g.ty < -1440 || g.tx >= 960 + 1440 || g.ty >= 540 + 1440) {+ for (int i = 0; i < S->npath; i++) if (S->path[i] == c) S->path[i] = S->path[--S->npath];+ if (c == S->ref) S->ref = 0;+ kill(c);+ }+ }+}++/* Vp: effects end on their death frame */+static void ephemeral_in(NodeId p) {+ for (NodeId c = nodes[p].first, nx; c; c = nx) {+ nx = nodes[c].next;+ if (!has(c, C_ephemeral)) continue;+ int df = comp_int(nodes[c].T, C_ephemeral, F_deathFrame, -1);+ if (nodes[c].frame == (df >= 0 ? df : node_frames(c) - 1)) kill(c);+ }+}++/* Pp: the map's children by draw order, else by y (hidden ones first) */+static void sort_draw(void) {+ NodeId m = S->map, list[160];+ float key[160];+ int n = 0;+ for (NodeId c = nodes[m].first; c && n < 160; c = nodes[c].next) {+ float k;+ if (has(c, C_drawOrderOverride)) k = comp_float(nodes[c].T, C_drawOrderOverride, F_drawOrder, 0);+ else if (!node_visible(c)) k = -1e15f;+ else { float x; ent_pos(c, &x, &k); }+ int j = n++;+ while (j > 0 && key[j - 1] > k) { list[j] = list[j - 1]; key[j] = key[j - 1]; j--; }+ list[j] = c;+ key[j] = k;+ }+ if (nodes[m].first && n < 160) { /* (more than 160: left as they are) */+ for (int i = 0; i < n; i++) nodes[list[i]].next = i + 1 < n ? list[i + 1] : 0;+ nodes[m].first = n ? list[0] : 0;+ }+ nodes[m].flags |= NF_SORTED;+}++/* aq: Lucky's sprites face her direction (s) */+static void sprite_dirs(void) {+ if (!S->player) return;+ for (NodeId c = nodes[S->player].first; c; c = nodes[c].next)+ if (has(c, C_sprite) && node_visible(c) && node_has_label(c, "n") && node_has_label(c, "e") && node_has_label(c, "w"))+ set_label(c, "s");+}++/* ---------------------------------------------------------------- setting up */static void start(void) {- NodeId n = node_new_sym(S_marathon_kU);- node_add(game.root, n);- ent_register_tree(n);+ S = scene_state(sizeof(State));+ phys_reset();+ /* ds: the body types of this race */+ phys_body_type("character", "bodyMaterial", 40, 4, 19, 0);+ phys_body_type("prop", "bodyMaterial", 0, 2, 4, 0);+ phys_body_type("opponent", "bodyMaterial", 10, 16, 5, 0);+ S->body = -1;+ /* the variants (es.start) */+ const char *v = game.variant;+ S->spawners[0] = S_marathon_dL;+ S->spawners[1] = S_marathon_ZK;+ S->nspawners = 2;+ S->obstacles[0] = S_marathon_kY;+ S->obstacles[1] = S_marathon_lY;+ S->nobstacles = 2;+ if (!strcmp(v, "800m")) { S->total = 800; S->count = 6; S->opp_max = 7.6f; S->opp_min = 4.2f; }+ else if (!strcmp(v, "1500m") || !strcmp(v, "5000m")) {+ bool k5 = v[0] == '5';+ S->total = k5 ? 5000 : 1500;+ S->count = k5 ? 12 : 8;+ S->opp_max = k5 ? 8.4f : 7.8f;+ S->opp_min = k5 ? 4.7f : 4.5f;+ static const uint16_t sp[7] = {S_marathon_dL, S_marathon_ZK, S_marathon_dL, S_marathon_ZK, S_marathon_dL, S_marathon_ZK, S_marathon_mja};+ memcpy(S->spawners, sp, sizeof sp);+ S->nspawners = 7;+ } else { S->total = 400; S->count = 6; S->opp_max = 7; S->opp_min = 4; }+ S->LL = 1;+ S->off = 1;+ S->pcalpha = 1;+ S->t_spawn = S->t_obst = 200;++ S->root = node_new_sym(S_marathon_kU);+ if (!S->root) return;+ node_add(game.root, S->root);+ for (NodeId c = nodes[S->root].first; c; c = nodes[c].next) {+ if (has(c, C_map)) S->map = c;+ if (has(c, C_marathonHud)) S->hud = c;+ }+ if (!S->map || !S->hud) return;+ nodes[S->map].alpha = 0; /* drawn by draw_under, with the speed lines over it */+ S->t_time = node_find(S->hud, "time");+ S->t_time_s = node_find(S->hud, "timeShadow");+ S->t_speed = node_find(S->hud, "speed");+ S->t_speed_s = node_find(S->hud, "speedShadow");+ S->t_dist = node_find(S->hud, "dist");+ S->t_dist_s = node_find(S->hud, "distShadow");+ S->placement = node_find(S->hud, "placement");+ S->pcursor = S->placement ? node_find(S->placement, "player") : 0;+ S->ptext = S->pcursor ? node_find(S->pcursor, "place") : 0;+ NodeId sm = node_find(S->hud, "speedometer");+ S->needle = sm ? node_find(sm, "needle") : 0;+ S->poof = node_find(S->hud, "poof");+ S->ref = node_find(S->map, "ref");++ /* the map's children */+ for (NodeId c = nodes[S->map].first; c; c = nodes[c].next) {+ if (has(c, C_marathonPlayer)) S->player = c;+ else if (has(c, C_marathonOpponent) && S->nopp < OPP_MAX) {+ Opp *o = &S->opp[S->nopp++];+ o->n = c;+ o->body = -1;+ uint16_t col = comp_str(nodes[c].T, C_marathonOpponent, F_cursorColor);+ o->color = col != NONE16 ? str(col) : "op1";+ } else if (has(c, C_marathonPath) && S->npath < PATH_MAX) S->path[S->npath++] = c;+ else if (has(c, C_boundable) && has(c, C_collidable) && S->nwalls < WALL_MAX) {+ S->wall_body[S->nwalls] = -1;+ S->walls[S->nwalls++] = c;+ }+ }+ /* bs: the finish line */+ spawn(S_marathon_dfa, S->map, 24.0f * S->total + 20, 34);+ /* cs: the leftmost `count` tanuki run, in a shuffled order of speeds */+ for (int i = 1; i < S->nopp; i++)+ for (int j = i; j > 0 && nodes[S->opp[j - 1].n].x > nodes[S->opp[j].n].x; j--) {+ Opp t = S->opp[j]; S->opp[j] = S->opp[j - 1]; S->opp[j - 1] = t;+ }+ while (S->nopp > S->count) kill(S->opp[--S->nopp].n);+ for (int m = S->nopp - 1; m > 0; m--) { /* bb: Fisher-Yates */+ int k = (int)floorf(frand() * (m + 1));+ Opp t = S->opp[m]; S->opp[m] = S->opp[k]; S->opp[k] = t;+ }+ for (int k = 0; k < S->nopp; k++) S->opp[k].speed = lerp(S->opp_min, powf((float)k / S->nopp, .85f), S->opp_max);+ /* the speed lines' shape */+ S->line_proto = node_new_sym(S_marathon_Cna);+ sys_countdown_start(&S->cd);+}++/* ---------------------------------------------------------------- Ur: the world scrolls by */+static void scroll(void) {+ for (NodeId n = nodes[S->map].first; n; n = nodes[n].next) {+ if (!has(n, C_marathonTile)) continue;+ float x, y;+ ent_pos(n, &x, &y);+ ent_set_pos(n, x - S->UB, y);+ }}-static void tick(void) { sys_back_pauses(); }-const SceneDef scene_marathon = {"marathon", start, tick, NULL, NULL, NULL, NULL};++/* ---------------------------------------------------------------- Yr: the path goes on */+static float path_width(NodeId n) { return (float)comp_int(nodes[n].T, C_marathonPath, F_width, 64); }++static void paths(void) {+ /* sorted by x; gone once past the left edge */+ for (int i = 1; i < S->npath; i++)+ for (int j = i; j > 0 && pos_x(S->path[j - 1]) > pos_x(S->path[j]); j--) {+ NodeId t = S->path[j]; S->path[j] = S->path[j - 1]; S->path[j - 1] = t;+ }+ int k = 0;+ for (int i = 0; i < S->npath; i++) {+ NodeId n = S->path[i];+ if (pos_x(n) < -path_width(n)) kill(n);+ else S->path[k++] = n;+ }+ S->npath = k;+ if (!k) return;+ NodeId g = S->path[k - 1];+ float m = path_width(g), b = pos_x(g) + m;+ if (b >= 800) return;+ uint16_t sym;+ if ((track(g) + m) / 24 > S->total) sym = S_marathon_hka;+ else {+ uint16_t e = comp_str(nodes[g].T, C_marathonPath, F_end);+ const char *end = e != NONE16 ? str(e) : "";+ static const uint16_t next[3][3] = {{S_marathon_aL, S_marathon_Zja, S_marathon__S_ja},+ {S_marathon_aka, S_marathon_bka, S_marathon_cka},+ {S_marathon_eka, S_marathon_fka, S_marathon_gka}};+ if (end[0] < 'a' || end[0] > 'c') return; /* after the finish: nothing (the doodle throws) */+ sym = next[end[0] - 'a'][qh(0, 3)];+ }+ if (S->npath >= PATH_MAX) return;+ NodeId n = spawn(sym, S->map, b, 0);+ if (n) S->path[S->npath++] = n;+}++/* ---------------------------------------------------------------- Rr: Lucky */+static void lucky(void) {+ NodeId b = S->player;+ if (!b) return;+ float mx, my;+ ent_pos(b, &mx, &my);+ S->on_path = S->trig_path;+ if (S->trig_obst && S->vK == 0 && S->KQ == 0) {+ SOUND(COa);+ S->vK = 30;+ S->LL *= .25f;+ }+ int mask;+ if (S->vK > 0) { S->vK--; mask = 3; }+ else if (S->KQ > 0) {+ S->KQ--;+ mask = 3;+ if (S->KQ == 4) { NodeId fx = node_new_sym(S_marathon_kXa); if (fx) node_add(b, fx); }+ } else {+ mask = 19;+ if (S->on_path) S->LL++;+ else S->LL *= .9f;+ }+ if (S->body >= 0) bodies[S->body].mask = (uint16_t)mask;+ if (S->U_ > 0) S->U_--;+ else if (S->vK == 0 && S->KQ == 0 && in.pressed[A_ACTION]) {+ S->KQ = 40;+ S->U_ = 150;+ NodeId fx = node_new_sym(S_marathon_iXa);+ if (fx) node_add(b, fx);+ }+ S->UB = sqrtf(111 + S->LL) / 3;+ S->eqa = fminf(2.5f, .45f * S->UB);+ for (NodeId c = nodes[b].first; c; c = nodes[c].next)+ if (has(c, C_sprite)) nodes[c].alpha = (S->vK % 8 < 4 && S->KQ == 0) ? 255 : 77;+ S->off += S->UB;+ float cl = len2(in.jx, in.jy);+ if (cl > 0) {+ S->vx = in.jx / cl * S->eqa * cl;+ S->vy = in.jy / cl * S->eqa * cl;+ float a = clampf((mx / 320 - .2f) / .2f, 0, 1), n = S->vK == 0 ? (1 - a) * (1 - a) : 0;+ if (S->vx > 0) { S->vx *= n; S->LL += a * a * .4f; }+ } else S->vx = S->vy = 0;+ if (cl == 0 || S->vK > 0) S->vx -= 5 * clampf(mx / 320 - .1f, 0, .4f);+ static const char *const poses[5] = {"idle", "walk", "run", "naruto", "supernaruto"};+ int m = speed_class(S->UB);+ set_label(b, S->vK > 0 ? "stumble" : poses[m]);+ S->tick++;+}++/* ---------------------------------------------------------------- Vr: spawners and rocks come in */+static void spawners(void) {+ float m = 5 / powf(S->UB, 1.5f);+ if (S->off / 24 + 30 > S->total) return;+ S->t_spawn--;+ if (S->UB > 4.5f && S->t_spawn <= 0) {+ S->t_spawn = qh(80, 140) * m;+ NodeId k = spawn(S->spawners[qh(0, S->nspawners)], S->map, 0, 0);+ if (k) {+ uint16_t d = comp_str(nodes[k].T, C_marathonSpawn, F_direction);+ const char *dir = d != NONE16 ? str(d) : "";+ if (!strcmp(dir, "s")) ent_set_pos(k, 340, 20);+ else if (!strcmp(dir, "n")) ent_set_pos(k, 340, 160);+ }+ }+ S->t_obst--;+ if (S->UB > 4.5f && S->t_obst <= 0) {+ S->t_obst = qh(170, 200) * m;+ spawn(S->obstacles[qh(0, S->nobstacles)], S->map, 340, (float)qh(40, 140));+ }+}++/* ---------------------------------------------------------------- Wr: speed lines */+static void speed_lines(void) {+ static const float counts[5] = {0, 0, 1, 2, 4};+ int g = speed_class(S->UB);+ float a = counts[g];+ int n = frand() > fmodf(a, 1) ? (int)ceilf(a) : (int)floorf(a);+ static const int8_t vel[5] = {0, 0, -20, -25, -30};+ for (int i = 0; i < n && S->nline < LINE_MAX; i++)+ S->line[S->nline++] = (Line){(float)(340 - qh(1, 10)), (float)qh(5, 175), vel[g], (uint8_t)g};+}++/* zr for the lines; they are gone once off the screen (Up takes them much later) */+static void move_lines(void) {+ static const float sx[5] = {0, 0, 1, 1.5f, 2};+ int k = 0;+ for (int i = 0; i < S->nline; i++) {+ Line *l = &S->line[i];+ l->x += l->vx;+ if (l->x + 60 * sx[l->cls] >= 0) S->line[k++] = *l;+ }+ S->nline = k;+}++/* ---------------------------------------------------------------- Xr: what spawners throw */+static void throws(void) {+ for (NodeId n = nodes[S->map].first; n; n = nodes[n].next) {+ if (!has(n, C_marathonSpawn)) continue;+ int f = comp_int(nodes[n].T, C_marathonSpawn, F_spawnFrame, -1);+ uint16_t s = comp_sym(nodes[n].T, C_marathonSpawn, F_toSpawn);+ if (nodes[n].frame != f || s == NONE16) continue;+ float x, y;+ ent_pos(n, &x, &y);+ spawn(s, S->map, x, y);+ }+}++/* ---------------------------------------------------------------- Tr: the tanuki */+static void tanuki(void) {+ NodeId p = S->player;+ if (!p) return;+ float kx, ky;+ ent_pos(p, &kx, &ky);+ for (int i = 0; i < S->nopp; i++) {+ Opp *o = &S->opp[i];+ float hx, hy;+ ent_pos(o->n, &hx, &hy);+ set_label(o->n, "idle");+ if (!o->nc) { o->nc = true; o->ncx = hx; o->ncy = hy; }+ float e = .85f * (o->ncy - MR);+ float vx = (hx - kx) / 24, vy = (hy - ky) / 24, u = 1;+ if (vx < 4) u = powf(1 + clampf(fabsf(vx - 4), 0, 12) / 100, 1.5f);+ /* (the doodle's bonus for runners "3" and "4" compares a string with numbers: never) */+ float E = track(o->n) / 24, left = S->total - track(o->n) / 24;+ if (left < 100 && left > 0) u += .1f * sqrtf(1 - left / 100);+ if (E < 100) u += E / 100 * .05f;+ if (E < 3) u *= .4f + .6f * E / 3;+ float d = o->speed;+ if (E > 20 && vx < 5) {+ float n = powf((6 - fabsf(clampf(vx + 1, -5, 6))) / 9, 1.5f);+ d = d * (1 - n) + S->UB * n;+ }+ float nx = d * u, ny = 0;+ /* towards the next waypoint ahead, in its own lane */+ NodeId wp = 0;+ float wx = 1e9f, wy = 0;+ for (int j = 0; j < S->npath; j++)+ for (NodeId w = nodes[S->path[j]].first; w; w = nodes[w].next) {+ if (!has(w, C_marathonWaypoint)) continue;+ float x, y;+ ent_pos(w, &x, &y);+ if (x > hx && x < wx) { wp = w; wx = x; wy = y; }+ }+ if (wp) {+ float ex = wx - hx, ey = wy + e - hy, el = len2(ex, ey);+ if (el > 0) {+ u += .15f * ey / el;+ float s = fminf(d * u, el);+ nx = ex / el * s;+ ny = ey / el * s;+ } else nx = ny = 0;+ } else { nx = .7f * d * u; ny = 0; }+ if (S->on_path && E > 20 && fabsf(vy) < 1.5f && vx < 5 && vx > 0)+ ny = lerp(ny, powf(.25f - vx / 5 * .22f, 1.4f), ky - hy);+ o->vx += (nx - o->vx) * .2f;+ o->vy += (ny - o->vy) * .2f;+ }+}++/* ---------------------------------------------------------------- yr: physics */+static int16_t body_for(NodeId n, int type) {+ Rect r;+ if (!ent_bounds(n, &r)) return -1;+ int b = phys_add(type, SH_BOX, r.x + r.w / 2, r.y + r.h / 2, 50, r.w / 2, r.h / 2, 50);+ if (b >= 0) bodies[b].user = n;+ return (int16_t)b;+}++static void sync_in(NodeId n, int16_t b, float vx, float vy) {+ Rect r;+ if (b < 0 || !ent_bounds(n, &r)) return;+ Body *bd = &bodies[b];+ bd->x = r.x + r.w / 2;+ bd->y = r.y + r.h / 2;+ bd->z = 50;+ bd->vx = 30 * vx;+ bd->vy = 30 * vy;+ bd->vz = 0;+}++static void sync_out(NodeId n, int16_t b, float *vx, float *vy) {+ Rect r;+ if (b < 0 || !ent_bounds(n, &r)) return;+ Body *bd = &bodies[b];+ *vx = bd->vx / 30;+ *vy = bd->vy / 30;+ float px, py;+ ent_pos(n, &px, &py);+ ent_set_pos(n, bd->x + (px - (r.x + r.w / 2)), bd->y + (py - (r.y + r.h / 2)));+}++static void physics(void) {+ int tc = phys_type("character"), to = phys_type("opponent"), tp = phys_type("prop");+ if (S->player && S->body < 0) S->body = body_for(S->player, tc);+ for (int i = 0; i < S->nopp; i++)+ if (S->opp[i].body < 0) S->opp[i].body = body_for(S->opp[i].n, to);+ for (int i = 0; i < S->nwalls; i++)+ if (S->wall_body[i] < 0) S->wall_body[i] = body_for(S->walls[i], tp);+ sync_in(S->player, S->body, S->vx, S->vy);+ for (int i = 0; i < S->nopp; i++) sync_in(S->opp[i].n, S->opp[i].body, S->opp[i].vx, S->opp[i].vy);+ phys_step(1.0f / FPS);+ sync_out(S->player, S->body, &S->vx, &S->vy);+ for (int i = 0; i < S->nopp; i++) sync_out(S->opp[i].n, S->opp[i].body, &S->opp[i].vx, &S->opp[i].vy);+}++/* ---------------------------------------------------------------- $r: HUD */+static void set_text2(NodeId a, NodeId b, const char *s) {+ if (a) node_set_text(a, s);+ if (b) node_set_text(b, s);+}++static void hud(void) {+ NodeId b = S->player;+ if (!b) return;+ float kmh = S->UB / 24 * 108;+ int tenths = (int)jround(kmh * 10); /* toFixed(1) (the calculator's printf has no %f) */+ snprintf(S->speed_buf, sizeof S->speed_buf, "%d.%dkm/h", tenths / 10, tenths % 10);+ set_text2(S->t_speed, S->t_speed_s, S->speed_buf);+ float h = track(b) / 24;+ snprintf(S->dist_buf, sizeof S->dist_buf, "%dm/%dm", (int)jround(h), S->total);+ set_text2(S->t_dist, S->t_dist_s, S->dist_buf);+ if (S->needle) {+ int n = (int)floorf(22 * clampf((kmh - 18) / 20, 0, 1));+ n = (int)jround(lerp(nodes[S->needle].frame, .3f, (float)n));+ if (n == 22 && frand() < .5f) n--;+ node_goto(S->needle, NULL, n, false);+ }+ if (S->poof) node_goto(S->poof, NULL, (int)jround(10 * (1 - S->U_ / 150.0f)), false);+ fmt_time(S->time_buf, sizeof S->time_buf, S->tick);+ set_text2(S->t_time, S->t_time_s, S->time_buf);+ if (S->ref && S->tick == 1) { node_play(S->ref); S->ref = 0; } /* the referee's flag */+ if (!S->placement) return;+ /* the runners around Lucky, by x */+ NodeId a[OPP_MAX + 1];+ int na = 0, idx[OPP_MAX + 1];+ a[na] = b; idx[na++] = -1;+ for (int i = 0; i < S->nopp; i++) { a[na] = S->opp[i].n; idx[na++] = i; }+ for (int i = 1; i < na; i++)+ for (int j = i; j > 0 && nodes[a[j - 1]].x > nodes[a[j]].x; j--) {+ NodeId t = a[j]; a[j] = a[j - 1]; a[j - 1] = t;+ int ti = idx[j]; idx[j] = idx[j - 1]; idx[j - 1] = ti;+ }+ int g = 0;+ while (g < na && a[g] != b) g++;+ S->nplace = na;+ int n0 = g - (na - 5) > 0 ? g - (na - 5) : 0;+ for (int f = 0; f < na; f++) {+ NodeId d, t;+ char *buf = S->place_buf[f];+ uint16_t *col = &S->place_color[f];+ float *ca = &S->pcalpha;+ if (idx[f] < 0) { d = S->pcursor; t = S->ptext; }+ else {+ Opp *o = &S->opp[idx[f]];+ if (!o->cursor) {+ o->cursor = node_new_sym(S_marathon_JWa);+ if (o->cursor) {+ node_add(S->placement, o->cursor);+ node_goto(o->cursor, o->color, 0, false);+ node_update_one(o->cursor);+ o->text = node_find(o->cursor, "place");+ nodes[o->cursor].alpha = 255;+ o->calpha = 1;+ }+ }+ d = o->cursor;+ t = o->text;+ ca = &o->calpha;+ }+ if (!d) continue;+ int v = n0 + (f - g);+ float u = 6 + 105 * clampf((float)v, 0, 4);+ *col = rgb565(0x11, 0xae, 0x00);+ if (v == n0) snprintf(buf, 12, "%d", na - f);+ else {+ float fm = fabsf(jround(track(a[f]) / 24 - h));+ unsigned m = fm > 99 || fm != fm ? 99u : (unsigned)fm;+ if (v > n0) { u -= 30; snprintf(buf, 12, "+%um", m); *col = rgb565(0x11, 0xcc, 0x11); }+ else { snprintf(buf, 12, "-%um", m); *col = rgb565(0xcc, 0x11, 0x11); }+ }+ if (t) node_set_text(t, ""); /* drawn by draw_over, in its colour */+ S->place_text[f] = t;+ float e = (v >= 0 && v < 5) ? 1 : 0;+ float cx, cy;+ ent_local_pos(d, &cx, &cy);+ ent_set_local_pos(d, lerp(cx, .5f, u), lerp(cy, .5f, 0));+ *ca = lerp(*ca, .5f, e);+ nodes[d].alpha = (uint8_t)(*ca * 255);+ }+ nodes[S->placement].alpha = (uint8_t)(clampf(((float)S->tick - 45) / 30, 0, 1) * 255);+}++/* ---------------------------------------------------------------- the finish (as) */+static void banner(const char *s, uint16_t color, uint16_t outline) { /* To */+ S->banner = s;+ S->banner_color = color;+ S->banner_outline = outline;+ S->banner_t = 1;+}++static void finish(void) {+ if (S->ended) {+ if (S->end_t > 0 && --S->end_t == 0) menus_game_over_rated((float)S->score, S->rating);+ return;+ }+ NodeId b = S->player;+ if (!b || track(b) / 24 <= S->total) return;+ if (S->body >= 0) bodies[S->body].mask = 1;+ S->vx = len2(S->vx, S->vy) + S->UB;+ S->vy = 0;+ S->UB = 0;+ int m = 0;+ float bx = pos_x(b);+ for (int i = 0; i < S->nopp; i++) {+ Opp *o = &S->opp[i];+ o->vx = len2(o->vx, o->vy);+ o->vy = 0;+ if (pos_x(o->n) > bx) m++;+ }+ if (m == 0) banner(msg("FIRST_PLACE"), rgb565(0xff, 0xde, 0x38), rgb565(0xa1, 0x87, 0x22));+ else if (m == 1) banner(msg("SECOND_PLACE"), rgb565(0xa1, 0xa4, 0xa6), rgb565(0x5f, 0x62, 0x63));+ else if (m == 2) banner(msg("THIRD_PLACE"), rgb565(0xb5, 0x86, 0x57), rgb565(0x6b, 0x4a, 0x29));+ else banner(msg("FINISH"), rgb565(0xff, 0xff, 0xff), rgb565(0x55, 0x55, 0x55));+ S->ended = true;+ S->end_t = END_DELAY;+ S->score = S->tick;+ S->rating = 3 - m > 0 ? 3 - m : 0;+ SOUND($Za);+}++/* ---------------------------------------------------------------- the scene */+static void tick(void) {+ sys_back_pauses(); /* Ep */+ if (!S || !S->map || menus_active()) return;+ if (!S->started) { /* Uo */+ S->started = true;+ sys_tutorial_once();+ if (menus_active()) return;+ }+ bool go = sys_countdown(&S->cd); /* Wo */+ bool on = go && !S->ended;+ if (go) triggers(); /* Hr */+ if (go) scroll(); /* Ur */+ if (on) paths(); /* Yr */+ if (on) lucky(); /* Rr */+ if (on) spawners(); /* Vr */+ if (go) speed_lines(); /* Wr */+ if (go) throws(); /* Xr */+ if (on) tanuki(); /* Tr */+ if (go) sprite_dirs(); /* aq */+ if (go) { move_direct(); move_lines(); } /* zr */+ if (go) physics(); /* yr */+ if (!S->ended) hud(); /* $r */+ if (go) finish(); /* as */+ if (go) delete_offscreen(); /* Up */+ ephemeral_in(S->map); /* Vp */+ if (S->player) ephemeral_in(S->player);+ sort_draw(); /* Pp */+ if (S->banner_t > 0) S->banner_t++;+}++/* ---------------------------------------------------------------- drawing */+static void draw_under(void) {+ if (!S || !S->map) return;+ Mat third = {1.0f / 3, 0, 0, 1.0f / 3, 0, 0};+ Mat pm = mat_mul(third, node_global(S->root));+ /* path pieces wait off the right edge (up to x 800): not drawn there */+ for (int i = 0; i < S->npath; i++) {+ float x = pos_x(S->path[i]);+ node_set_visible(S->path[i], x < VIEW_W + 16 && x + path_width(S->path[i]) > -16);+ }+ nodes[S->map].alpha = 255;+ node_draw_in(S->map, pm, 255);+ nodes[S->map].alpha = 0;+ for (int i = 0; i < S->npath; i++) node_set_visible(S->path[i], true);+ /* the speed lines, over the map (drawOrder 1000) */+ if (!S->line_proto) return;+ static const float sx[5] = {0, 0, 1, 1.5f, 2};+ static const uint8_t al[5] = {0, 0, 77, 102, 128};+ Mat mm = mat_mul(third, node_global(S->map));+ for (int i = 0; i < S->nline; i++) {+ Line *l = &S->line[i];+ nodes[S->line_proto].x = l->x;+ nodes[S->line_proto].y = l->y;+ nodes[S->line_proto].alpha = al[l->cls];+ node_xform(S->line_proto, sx[l->cls], 1, 0);+ node_draw(S->line_proto, mm);+ }+}++/* a text of the HUD, in a colour of its own (the doodle sets Text.color) */+static void draw_text_as(NodeId t, const char *s, uint16_t color) {+ if (!t || !s[0] || nodes[t].ref == NONE16 || !node_visible_chain(t)) return;+ uint8_t alpha = 255;+ for (NodeId p = t; p; p = nodes[p].parent) alpha = (uint8_t)((alpha * nodes[p].alpha + 127) / 255);+ if (!alpha) return;+ Mat m = mat_mul((Mat){1.0f / 3, 0, 0, 1.0f / 3, 0, 0}, node_global(t));+ const uint8_t *p = payload(nodes[t].ref);+ float scale = sqrtf(m.a * m.a + m.b * m.b), px = p[2] * scale;+ int k = px >= 26 ? 3 : px >= 16 ? 2 : 1;+ int lh = (int)(rds16(p + 10) * 0.25f * scale);+ /* one word: CreateJS only wraps at spaces */+ gfx_text_k(s, m, color, p[6], 0, (int16_t)lh, alpha, k);+}++static float cubic_out(float t) { return 1 - (1 - t) * (1 - t) * (1 - t); }++static void draw_over(void) {+ if (!S || !S->map) return;+ /* the placement bar's texts */+ if (S->placement && nodes[S->placement].alpha) {+ for (int f = 0; f < S->nplace; f++) draw_text_as(S->place_text[f], S->place_buf[f], S->place_color[f]);+ }+ /* To: the banner slides in from the right, stays two seconds, leaves to the left */+ if (S->banner_t > 0 && S->banner) {+ int t = S->banner_t - 1;+ float dx;+ if (t < 12) dx = 1000 * (1 - cubic_out(t / 12.0f));+ else if (t < 72) dx = 0;+ else if (t < 81) { float q = (t - 72) / 9.0f; dx = -1000 * q * q * q; }+ else return;+ Mat m = MAT_ID;+ m.tx = (480 + dx) / 3;+ m.ty = (151.2f - 40) / 3;+ Mat s = m;+ s.ty += 80.0f / 12 / 3;+ gfx_text_k(S->banner, s, rgb565(0x11, 0x11, 0x11), 1, 0, 0, 204, 3);+ for (int oy = -1; oy <= 1; oy++)+ for (int ox = -1; ox <= 1; ox++) {+ if (!ox && !oy) continue;+ Mat o = m;+ o.tx += ox;+ o.ty += oy;+ gfx_text_k(S->banner, o, S->banner_outline, 1, 0, 0, 255, 3);+ }+ gfx_text_k(S->banner, m, S->banner_color, 1, 0, 0, 255, 3);+ }+}++static void end(void) {+ if (S && S->line_proto) node_free(S->line_proto);+ phys_reset();+ S = NULL;+}++static void goto_frame(const char *label) { (void)label; } /* the variant is read in start() */++const SceneDef scene_marathon = {"marathon", start, tick, end, draw_under, draw_over, goto_frame};diff --git a/games/championisland/src/sport_rugby.c b/games/championisland/src/sport_rugby.cindex 828e2df9..511680a8 100644--- a/games/championisland/src/sport_rugby.c+++ b/games/championisland/src/sport_rugby.c@@ -24,9 +24,6 @@#include <stdio.h>#include "ent.h"#include "phys.h"-#ifdef RG_DEBUG-#include <stdlib.h>-#endif#define ACT_MAX 32#define OB_MAX 176@@ -62,7 +59,7 @@ typedef struct {NodeId proto[PROTO_MAX]; /* one node per kind of rock and background tile */uint16_t proto_sym[PROTO_MAX];int16_t proto_nb[PROTO_MAX][4];- int nproto;+ int nproto, proto_last;int bg_slot;Actor act[ACT_MAX];int nact;@@ -438,8 +435,9 @@ static void act_remove(Actor *a) { /* co, with removeFx (Yp) *//* ---------------------------------------------------------------- setting up */static int proto_of(uint16_t sym) {+ if (S->proto_last < S->nproto && S->proto_sym[S->proto_last] == sym) return S->proto_last; /* runs of one kind */for (int i = 0; i < S->nproto; i++)- if (S->proto_sym[i] == sym) return i;+ if (S->proto_sym[i] == sym) return S->proto_last = i;if (S->nproto >= PROTO_MAX) return -1;NodeId n = node_new_sym(sym);if (!n) return -1;@@ -614,10 +612,6 @@ static void start(void) {S->nact++;}build_grid();-#ifdef RG_DEBUG- fprintf(stderr, "nob %d pa %.1f %.1f %.1f %.1f grid %dx%d end %.1f %.1f %.1f %.1f nact %d\n", S->nob, S->pa.x, S->pa.y, S->pa.w, S->pa.h, S->gw, S->gh, S->end_r.x, S->end_r.y, S->end_r.w, S->end_r.h, S->nact);- for (int i = 0; i < 3; i++) fprintf(stderr, "ob %d: %d %d %d %d\n", i, S->ob_r[i][0], S->ob_r[i][1], S->ob_r[i][2], S->ob_r[i][3]);-#endif/* the camera's view at the start (Ls is off during the countdown: what is near shows) */{@@ -628,15 +622,6 @@ static void start(void) {S->view = (Rect){x0, y0, 960 / g.a, 540 / g.d};}}-#ifdef RG_DEBUG- if (getenv("RG_X")) /* tests: the team starts further on */- for (int i = 0; i < S->nact; i++)- if (S->act[i].kind == A_CHAR) { S->act[i].x += atof(getenv("RG_X")); if (getenv("RG_Y")) S->act[i].y += atof(getenv("RG_Y")); }-#endif-#ifdef RG_START_X /* performance tests on the calculator: the team starts further on */- for (int i = 0; i < S->nact; i++)- if (S->act[i].kind == A_CHAR) S->act[i].x += RG_START_X;-#endiffor (int i = 0; i < S->nact; i++) {Actor *a = &S->act[i];Rect v = rect_pad(S->view, 240, 216, 240, 432);@@ -665,9 +650,7 @@ static void visibility(void) {}for (int i = 0; i < S->nob; i++) {if ((uint32_t)(i + 3) % 4 != t % 4) continue;- Key k;float x = S->ob_r[i][0] * .25f + S->ob_r[i][2] * .125f, y = S->ob_r[i][1] * .25f + S->ob_r[i][3] * .125f;- (void)k;if (rect_contains(v, x, y)) S->ob_vis[i >> 3] |= (uint8_t)(1 << (i & 7));else S->ob_vis[i >> 3] &= (uint8_t)~(1 << (i & 7));}@@ -1289,9 +1272,9 @@ static bool in_end_zone(void) {return false;}-static void big_toast(const char *s) {+static void big_toast(const char *s) { /* To(..., {size: 100, shadow: "#222", outline: "#aaa"}) */S->toast_s = s;- S->toast_t = 37; /* To: 400 ms in, 2 s, 300 ms out */+ S->toast_t = 1;}static void finish(int rating) {@@ -1302,7 +1285,7 @@ static void finish(int rating) {}static void the_end(bool zone) {- if (S->toast_t > 0) { S->toast_t--; toast_countdown(S->toast_s); }+ if (S->toast_t > 0) S->toast_t++;if (S->ended) {if (S->win_t > 0 && --S->win_t == 0 && S->pl >= 0) act_label(&S->act[S->pl], "win");if (S->end_t > 0 && --S->end_t == 0) menus_game_over_rated((float)S->score, S->rating);@@ -1365,11 +1348,6 @@ static void tick(void) {if (go) sprite_dirs(); /* aq */rhud_tick(); /* Ct */the_end(zone); /* Et */-#ifdef RG_DEBUG- if (S->pl >= 0) { Actor *a = &S->act[S->pl]; float x, y; act_pos(a, &x, &y);- { int nb = 0; for (int i = 0; i < BODY_MAX; i++) nb += bodies[i].used; static int mx; if (nb > mx) { mx = nb; fprintf(stderr, "bodies max %d, state %d\n", mx, (int)sizeof(State)); } }- fprintf(stderr, "t%u pl %d pos %.2f %.2f v %.2f %.2f body %d go %d label %s nodes %u\n", game.ticks, S->pl, x, y, a->vx, a->vy, a->body, go, a->n ? node_label(a->n) : "-", node_count()); }-#endif}/* ---------------------------------------------------------------- drawing: the map in the doodle's order */@@ -1463,6 +1441,34 @@ static void draw_under(void) {}}+/* To: the banner slides in from the right (400 ms), stays 2 s, leaves to the left (300 ms) */+static float cubic_out(float t) { return 1 - (1 - t) * (1 - t) * (1 - t); }++static void draw_over(void) {+ if (!S || S->toast_t <= 0 || !S->toast_s) return;+ int t = S->toast_t - 1;+ float dx;+ if (t < 12) dx = 1000 * (1 - cubic_out(t / 12.0f));+ else if (t < 72) dx = 0;+ else if (t < 81) { float q = (t - 72) / 9.0f; dx = -1000 * q * q * q; }+ else return;+ Mat m = MAT_ID;+ m.tx = (480 + dx) / 3;+ m.ty = (151.2f - 50) / 3;+ Mat sh = m;+ sh.ty += 100.0f / 12 / 3;+ gfx_text_k(S->toast_s, sh, rgb565(0x22, 0x22, 0x22), 1, 0, 0, 204, 3);+ for (int oy = -1; oy <= 1; oy++)+ for (int ox = -1; ox <= 1; ox++) {+ if (!ox && !oy) continue;+ Mat o = m;+ o.tx += ox;+ o.ty += oy;+ gfx_text_k(S->toast_s, o, rgb565(0xaa, 0xaa, 0xaa), 1, 0, 0, 255, 3);+ }+ gfx_text_k(S->toast_s, m, rgb565(0xff, 0xff, 0xff), 1, 0, 0, 255, 3);+}+static void end(void) {if (S)for (int i = 0; i < S->nproto; i++) node_free(S->proto[i]); /* not in the scene's tree */@@ -1470,4 +1476,4 @@ static void end(void) {S = NULL;}-const SceneDef scene_rugby = {"rugby", start, tick, end, draw_under, NULL, NULL};+const SceneDef scene_rugby = {"rugby", start, tick, end, draw_under, draw_over, NULL};diff --git a/games/championisland/src/sport_skate.c b/games/championisland/src/sport_skate.cindex 4cc10af3..1bb16fe5 100644--- a/games/championisland/src/sport_skate.c+++ b/games/championisland/src/sport_skate.c@@ -29,12 +29,14 @@#include <stdlib.h>#include "../src/ent.h"#include "../src/font.h"+#include "../src/spr.h"#define SYM_MAX 64#define PROTO_RESERVE 72 /* nodes kept free for menus, prompt icons, champions */-#define BANDS_MAX 120+#define MENU_RESERVE 40 /* nodes always kept free for the pause and results menus */+#define STARTS_MAX 480#define ENT_CAP 2300-#define VIS_MAX 160+#define VIS_MAX 128#define CH_MAX 24#define KK_MAX 40#define ACT_KEEP 6@@ -43,6 +45,7 @@#define TIME_START 2700 /* CN */#define END_DELAY 80 /* Yo */#define PI_F 3.14159265f+#define GRAD_STRIPS 12/* ---------------------------------------------------------------- the data's timeline keys (as node.c reads them) */typedef struct {@@ -128,6 +131,10 @@ static bool mat_inv_apply(Mat m, float x, float y, float *ox, float *oy) {/* the axis-aligned box of rect r placed by m */static Rect mat_rect(Mat m, Rect r) {+ if (m.b == 0 && m.c == 0) {+ float x0 = m.a * r.x + m.tx, x1 = m.a * (r.x + r.w) + m.tx, y0 = m.d * r.y + m.ty, y1 = m.d * (r.y + r.h) + m.ty;+ return (Rect){fminf(x0, x1), fminf(y0, y1), fabsf(x1 - x0), fabsf(y1 - y0)};+ }float xs[4] = {r.x, r.x + r.w, r.x, r.x + r.w}, ys[4] = {r.y, r.y, r.y + r.h, r.y + r.h};float lx = 1e9f, ly = 1e9f, hx = -1e9f, hy = -1e9f;for (int i = 0; i < 4; i++) {@@ -138,6 +145,12 @@ static Rect mat_rect(Mat m, Rect r) {return (Rect){lx, ly, hx - lx, hy - ly};}+/* CreateJS runs the frame scripts (this.T = {...}) of independent clips only:+ * a synched or single-frame child never gets its components */+static bool has_comp(NodeId n, int comp) {+ return nodes[n].T != NONE16 && node_mode(&nodes[n]) == MODE_INDEPENDENT && comp_has(nodes[n].T, comp);+}+/* ---------------------------------------------------------------- vectors and directions, as kitsune has them */static float vlen(float x, float y) { return sqrtf(x * x + y * y); }/* hh: the angle of a vector in degrees [0, 360), NaN for a zero vector */@@ -208,12 +221,13 @@ static const char *const player_labels[6] = {"stop", "slow", "fast", "jump", "grenum {SF_COLL = 1, SF_ZOBJ = 2, SF_ZB = 4, SF_DORD = 8, SF_RAIL = 16, SF_CHAMP = 32, SF_BOOST = 64, SF_PLAYER = 128,SF_GROUND = 256, SF_BG = 512, SF_NODRAW = 1024, SF_TILEANIM = 2048, SF_BOUNDS = 4096, SF_MARKERS = 8192,- SF_KEYB = 16384 /* draw order from the bounds (zObject, boundable, zBoundable) */+ SF_KEYB = 16384, /* draw order from the bounds (zObject, boundable, zBoundable) */+ SF_SCREENS = 32768 /* has billboard screens (a colour filter the renderer lacks) */};typedef struct {uint16_t sym, T, fl, stamp;NodeId proto;- uint8_t shape, fc; /* body shape (0 box, 1 left ramp, 2 right ramp); tile frameCount */+ uint8_t shape, fc; /* body shape (0 box, 1 left ramp, 2 right ramp; | SH_BITMAP: one bitmap); tile frameCount */int8_t bdir; /* speed boost direction */uint8_t bspeed;float z, h, dord; /* zObject z, zBoundable height (for the draw order), drawOrderOverride */@@ -222,10 +236,12 @@ typedef struct {int16_t b[4]; /* bounds child rect x0 y0 x1 y1, 1/8 px */int16_t r[6]; /* rail markers: x y (1/8 px), z; twice */} Sym;+#define SH_BITMAP 0x80 /* a static clip showing one bitmap: drawn straight */+#define SH_OPAQUE 0x40 /* ... fully opaque: hides what is under it */#define Q8(v) ((int16_t)lrintf((v) * 8))#define F8(v) ((v) * 0.125f)-typedef struct { float y0, maxh; uint16_t nb, s0; uint16_t bh; } Index;+typedef struct { float x0, y0, maxw, maxh; uint16_t nx, ny, s0, cell; } Index;typedef struct { float key; uint16_t off; uint16_t what; } Vis; /* what: 0 static, 1 player, 2 + champion */typedef struct { uint16_t off; NodeId n; uint8_t alpha, active, out; uint16_t out_t; } Champ;typedef struct { uint8_t type; int8_t dir; float vx, vy; } Action;@@ -233,7 +249,7 @@ typedef struct {NodeId n;float x0, x1, a0, a1;uint8_t tx, ta; /* tween ticks done (5 = over) */- bool used, listed, fading;+ bool used, listed, fading, green;} Icon;typedef struct {@@ -243,10 +259,11 @@ typedef struct {Mat bgm; /* the ground entity in map space */Index mi, bi;uint16_t nent, nstarts;- uint16_t starts[BANDS_MAX];+ uint16_t starts[STARTS_MAX];uint16_t ent[ENT_CAP];uint16_t nsym, stamp;Sym sym[SYM_MAX];+ uint8_t symh[128]; /* symbol -> index + 1, open addressing */uint8_t nkk;int16_t kk[KK_MAX][2]; /* park 1: origins of the 288 px ground tiles (Kk) */uint16_t kk_sprite;@@ -292,18 +309,116 @@ typedef struct {Countdown cd;uint32_t ticks;char score_buf[12], time_buf[12], tscore_buf[24], tname_buf[120];+ uint8_t grad[1 + GRAD_STRIPS * 23];} State;static State *S;_Static_assert(sizeof(State) <= SCENE_STATE_MAX, "skate state too big");+/* the box of a shape's polygons */+static bool shape_rect(const uint8_t *sh, Rect *r) {+ float lx = 1e9f, ly = 1e9f, hx = -1e9f, hy = -1e9f;+ const uint8_t *p = sh + 1;+ for (int s = 0; s < sh[0]; s++) {+ int np = p[4];+ p += 5;+ for (int k = 0; k < np; k++) {+ int n = rd16(p);+ p += 2;+ for (int i = 0; i < n; i++, p += 4) {+ float x = rds16(p) * .25f, y = rds16(p + 2) * .25f;+ lx = fminf(lx, x); hx = fmaxf(hx, x); ly = fminf(ly, y); hy = fmaxf(hy, y);+ }+ }+ }+ if (lx > hx) return false;+ *r = (Rect){lx, ly, hx - lx, hy - ly};+ return true;+}++/* CreateJS's getBounds from the data: what a symbol shows at a frame (visible children), placed by m */+typedef struct { float lx, ly, hx, hy; bool any; } Acc;+static void acc_rect(Acc *a, Rect r) {+ if (!a->any) { a->lx = r.x; a->ly = r.y; a->hx = r.x + r.w; a->hy = r.y + r.h; a->any = true; return; }+ a->lx = fminf(a->lx, r.x); a->ly = fminf(a->ly, r.y); a->hx = fmaxf(a->hx, r.x + r.w); a->hy = fmaxf(a->hy, r.y + r.h);+}+static void content(uint16_t sym, unsigned frame, Mat m, Acc *a, int depth) {+ if (sym >= SYM_COUNT || depth > 8) return;+ SymInfo si;+ sym_info(sym, &si);+ if (si.type == SYM_BITMAP) {+ Sprite sp;+ sprite_info((uint16_t)si.v, &sp);+ acc_rect(a, mat_rect(m, (Rect){0, 0, sp.w, sp.h}));+ return;+ }+ Rect r;+ if (si.type == SYM_SHAPE) { if (shape_rect(payload((uint16_t)si.v), &r)) acc_rect(a, mat_rect(m, r)); return; }+ Clip c;+ if (si.type != SYM_CLIP || !clip_get(sym, &c) || !c.nframes) return;+ frame %= c.nframes;+ const uint8_t *p = c.slots;+ for (unsigned i = 0; i < c.nslots; i++) {+ Key k;+ const uint8_t *nx;+ bool on = slot_at(p, frame, &k, &nx);+ p = nx;+ if (!on || (k.flags & K_HIDDEN)) continue;+ Mat km = mat_mul(m, key_mat(&k));+ if (k.kind == CK_SHAPE) { if (shape_rect(payload(k.ref), &r)) acc_rect(a, mat_rect(km, r)); }+ else if (k.kind == CK_SYM) {+ unsigned f = k.mode == MODE_SYNCHED ? k.sp + frame - k.start : k.mode == MODE_SINGLE ? k.sp : 0;+ content(k.ref, f, km, a, depth + 1);+ }+ }+}++/* is every pixel of a sprite opaque? (its cached run-length rows) */+static bool sprite_opaque(uint16_t sp) {+ const uint8_t *r = spr_get(sp);+ if (!r) return false;+ Sprite si;+ sprite_info(sp, &si);+ const uint8_t *al = palalpha(si.sheet);+ int w = rd16(r), h = rd16(r + 2);+ for (int y = 0; y < h; y++) {+ const uint8_t *p = r + rd16(r + 4 + 2 * y);+ int n = rd16(p), cx = 0;+ p += 2;+ for (int k = 0; k < n; k++) {+ if (*p++) return false; /* a gap */+ int code = *p++;+ bool fill = code & 0x80;+ int len = fill ? (code & 0x7F) + 1 : code;+ for (int i = 0; i < (fill ? 1 : len); i++) if (al[p[i]] != 255) return false;+ p += fill ? 1 : len;+ cx += len;+ }+ if (cx < w) return false;+ }+ return true;+}+/* ---------------------------------------------------------------- symbols */+/* the billboards' screens: their first child is drawn in one colour (ColorFilter(0, 0, 0, 1, r, g, b)) */+static const struct { uint16_t sym; uint8_t r, g, b; } screens[6] = {+ {S_skate_Mla, 109, 101, 223}, {S_skate_Nla, 0, 219, 176}, {S_skate_Ola, 241, 108, 235},+ {S_skate_Pla, 243, 39, 98}, {S_skate_Qla, 170, 218, 78}, {S_skate_Rla, 55, 190, 236}};+static int screen_of(uint16_t sym) {+ for (int i = 0; i < 6; i++) if (screens[i].sym == sym) return i;+ return -1;+}static void clip_frame0(uint16_t sym, Clip *c) { if (!clip_get(sym, c)) memset(c, 0, sizeof *c); }static Sym *sym_get(uint16_t ref) {- for (int i = 0; i < S->nsym; i++)- if (S->sym[i].sym == ref) return &S->sym[i];+ unsigned h = (ref * 2654435761u) >> 25;+ while (S->symh[h]) {+ Sym *o = &S->sym[S->symh[h] - 1];+ if (o->sym == ref) return o;+ h = (h + 1) & 127;+ }if (S->nsym >= SYM_MAX) return NULL;+ S->symh[h] = (uint8_t)(S->nsym + 1);SymInfo si;if (ref >= SYM_COUNT) return NULL;sym_info(ref, &si);@@ -363,8 +478,11 @@ static Sym *sym_get(uint16_t ref) {if (ci.type != SYM_CLIP) continue;clip_frame0(k.ref, &cc);Mat m = key_mat(&k);- if (!(s->fl & SF_BOUNDS) && comp_has(cc.T, C_bounds) && (cc.nb[2] || cc.nb[3])) {- Rect r = mat_rect(m, (Rect){cc.nb[0], cc.nb[1], cc.nb[2], cc.nb[3]});+ if (k.mode != MODE_INDEPENDENT) continue;+ if (screen_of(k.ref) >= 0) s->fl |= SF_SCREENS;+ Acc ba = {0, 0, 0, 0, false};+ if (!(s->fl & SF_BOUNDS) && comp_has(cc.T, C_bounds) && (content(k.ref, 0, m, &ba, 0), ba.any)) {+ Rect r = {ba.lx, ba.ly, ba.hx - ba.lx, ba.hy - ba.ly};s->b[0] = Q8(r.x); s->b[1] = Q8(r.y); s->b[2] = Q8(r.x + r.w); s->b[3] = Q8(r.y + r.h);s->fl |= SF_BOUNDS;}@@ -377,12 +495,22 @@ static Sym *sym_get(uint16_t ref) {}}if (nmark < 2) s->fl &= (uint16_t)~(SF_MARKERS | SF_RAIL);+ if (T == NONE16 && c.nframes == 1 && c.nslots == 1) {+ Key k;+ SymInfo ci;+ if (slot_at(c.slots, 0, &k, NULL) && k.kind == CK_SYM && k.ref < SYM_COUNT && (sym_info(k.ref, &ci), ci.type == SYM_BITMAP)) {+ s->shape |= SH_BITMAP;+ if (k.alpha == 255 && !(k.flags & K_HIDDEN) && sprite_opaque((uint16_t)ci.v)) s->shape |= SH_OPAQUE;+ }+ }if (!draws && c.nframes <= 1) s->fl |= SF_NODRAW;if (comp_has(T, C_collidable) && comp_has(T, C_boundable) && (s->fl & SF_BOUNDS)) s->fl |= SF_COLL;if ((s->fl & SF_ZOBJ) && (s->fl & SF_ZB) && (s->fl & SF_BOUNDS) && comp_has(T, C_boundable)) s->fl |= SF_KEYB;/* what it may draw: nominal bounds, up by its height (dq) and some room for effects */- float x0 = c.nb[0], y0 = c.nb[1], x1 = c.nb[0] + c.nb[2], y1 = c.nb[1] + c.nb[3];- if (!c.nb[2] && !c.nb[3]) { x0 = -64; y0 = -128; x1 = 64; y1 = 32; }+ Acc va = {0, 0, 0, 0, false};+ content(ref, 0, MAT_ID, &va, 0);+ float x0 = va.lx, y0 = va.ly, x1 = va.hx, y1 = va.hy;+ if (!va.any) { x0 = -64; y0 = -128; x1 = 64; y1 = 32; }if (s->fl & SF_ZOBJ) y0 -= s->z;if (s->fl & SF_CHAMP) y0 -= 200;s->vis[0] = (int16_t)floorf(x0); s->vis[1] = (int16_t)floorf(y0); s->vis[2] = (int16_t)ceilf(x1); s->vis[3] = (int16_t)ceilf(y1);@@ -403,6 +531,24 @@ static bool item_at(const uint8_t *slots, uint16_t off, Mat parent, Item *it, flreturn true;}+/* a text or a shape of the map's own timeline (no symbol) */+static bool loose_at(const uint8_t *slots, uint16_t off, Mat parent, Key *k, Mat *m, Rect *box) {+ if (!slot_at(slots + off, 0, k, NULL) || (k->kind != CK_TEXT && k->kind != CK_SHAPE)) return false;+ *m = mat_mul(parent, key_mat(k));+ Rect r;+ if (k->kind == CK_SHAPE) {+ if (!shape_rect(payload(k->ref), &r)) return false;+ } else {+ const uint8_t *t = payload(k->ref);+ float lw = rds16(t + 8) * .25f, lh = rds16(t + 10) * .25f;+ if (lw <= 0) lw = 600;+ if (lh <= 0) lh = t[2] * 1.2f;+ r = (Rect){t[6] == 1 ? -lw / 2 : t[6] == 2 ? -lw : 0, -lh, lw, lh * 6};+ }+ *box = mat_rect(*m, r);+ return true;+}+static Rect item_bounds(const Item *it) {const int16_t *b = it->s->b;return mat_rect(it->m, (Rect){F8(b[0]), F8(b[1]), F8(b[2] - b[0]), F8(b[3] - b[1])});@@ -412,13 +558,16 @@ static Rect item_bounds(const Item *it) {static float body_z0(const Sym *s) { return (s->fl & SF_ZOBJ) && (s->fl & SF_ZB) ? s->z : 0; }static float body_h(const Sym *s) { return (s->fl & SF_ZOBJ) && (s->fl & SF_ZB) ? fminf(s->h, 20000) : 100; }-/* ---------------------------------------------------------------- band index- * Each child is listed once, in the band of its top edge, in timeline order;- * a query looks up to the index's tallest child above. Children taller than- * TALL are in one more list that every query reads. */+/* ---------------------------------------------------------------- the index: children by grid cell+ * Each child is listed once, in the cell of its box's top left corner, in+ * timeline order; a query also reads the cells up to the index's widest and+ * tallest child to the left and above. Bigger children are in one more list+ * that every query reads. Queries merge the lists back into timeline order. */#define TALL 160-static void index_build(Index *ix, const uint8_t *slots, unsigned nslots, Mat parent, uint16_t bh, bool ground) {- float lo = 1e9f, hi = -1e9f, maxh = 0;+#define QMAX 48+static void index_build(Index *ix, const uint8_t *slots, unsigned nslots, Mat parent, uint16_t cell, bool ground) {+ float lx = 1e9f, ly = 1e9f, hx = -1e9f, hy = -1e9f, maxw = 0, maxh = 0;+ ix->nx = ix->ny = 0;for (int pass = 0; pass < 3; pass++) {const uint8_t *p = slots;for (unsigned i = 0; i < nslots; i++) {@@ -428,11 +577,18 @@ static void index_build(Index *ix, const uint8_t *slots, unsigned nslots, Mat paslot_at(p, 0, &k, &nx);p = nx;Item it;- if (!item_at(slots, off, parent, &it, ground ? 0 : 8)) continue;- uint16_t fl = it.s->fl;+ Rect r;+ uint16_t fl = 0;+ if (!item_at(slots, off, parent, &it, ground ? 0 : 8)) {+ Key lk;+ Mat lm;+ if (!loose_at(slots, off, parent, &lk, &lm, &r)) continue;+ } else {+ fl = it.s->fl;+ r = it.box;+ }if (!ground && (fl & (SF_GROUND | SF_BG | SF_PLAYER))) continue;if ((fl & SF_NODRAW) && !(fl & (SF_COLL | SF_RAIL | SF_BOOST))) continue;- Rect r = it.box;if (fl & SF_COLL) {Rect c = item_bounds(&it);float x0 = fminf(r.x, c.x), y0 = fminf(r.y, c.y);@@ -445,30 +601,37 @@ static void index_build(Index *ix, const uint8_t *slots, unsigned nslots, Mat pafloat x0 = fminf(r.x, fminf(ax, bx)), y0 = fminf(r.y, fminf(ay, by));r = (Rect){x0, y0, fmaxf(r.x + r.w, fmaxf(ax, bx)) - x0, fmaxf(r.y + r.h, fmaxf(ay, by)) - y0};}- bool tall = r.h > TALL;+ bool big = r.w > TALL || r.h > TALL;if (pass == 0) {- lo = fminf(lo, r.y);- hi = fmaxf(hi, r.y);- if (!tall) maxh = fmaxf(maxh, r.h);+ lx = fminf(lx, r.x); ly = fminf(ly, r.y); hx = fmaxf(hx, r.x); hy = fmaxf(hy, r.y);+ if (!big) { maxw = fmaxf(maxw, r.w); maxh = fmaxf(maxh, r.h); }continue;}- int b = tall ? ix->nb : clampi((int)floorf((r.y - ix->y0) / bh), 0, ix->nb - 1);- if (pass == 1) S->starts[ix->s0 + b + 1]++;- else if (S->starts[ix->s0 + b] < ENT_CAP) S->ent[S->starts[ix->s0 + b]++] = off;+ int c = big ? ix->nx * ix->ny+ : clampi((int)floorf((r.y - ix->y0) / cell), 0, ix->ny - 1) * ix->nx + clampi((int)floorf((r.x - ix->x0) / cell), 0, ix->nx - 1);+ if (pass == 1) S->starts[ix->s0 + c + 1]++;+ else if (S->starts[ix->s0 + c] < ENT_CAP) S->ent[S->starts[ix->s0 + c]++] = off;}if (pass == 0) {- if (lo > hi) { lo = 0; hi = 1; }- ix->y0 = floorf(lo);- ix->bh = bh;+ if (lx > hx) { lx = ly = 0; hx = hy = 1; }+ ix->x0 = floorf(lx);+ ix->y0 = floorf(ly);+ ix->cell = cell;+ ix->maxw = maxw;ix->maxh = maxh;- int nb = (int)((hi - ix->y0) / bh) + 1;- ix->nb = (uint16_t)clampi(nb, 1, BANDS_MAX - 2 - S->nstarts);+ int nx = (int)((hx - ix->x0) / cell) + 1, ny = (int)((hy - ix->y0) / cell) + 1;+ int room = STARTS_MAX - 2 - S->nstarts;+ nx = clampi(nx, 1, room > 1 ? room : 1);+ ny = clampi(ny, 1, room / nx > 1 ? room / nx : 1);+ ix->nx = (uint16_t)nx;+ ix->ny = (uint16_t)ny;+ int n = nx * ny;ix->s0 = S->nstarts;- S->nstarts = (uint16_t)(S->nstarts + ix->nb + 2);+ S->nstarts = (uint16_t)(S->nstarts + n + 2);S->starts[ix->s0] = S->nent;- for (int b = 1; b <= ix->nb + 1; b++) S->starts[ix->s0 + b] = 0;+ for (int b = 1; b <= n + 1; b++) S->starts[ix->s0 + b] = 0;} else if (pass == 1) {- for (int b = 1; b <= ix->nb + 1; b++) {+ for (int b = 1; b <= ix->nx * ix->ny + 1; b++) {uint32_t v = (uint32_t)S->starts[ix->s0 + b] + S->starts[ix->s0 + b - 1];#ifdef HOSTif (v > ENT_CAP) fprintf(stderr, "skate: index needs %u entries\n", v);@@ -478,36 +641,55 @@ static void index_build(Index *ix, const uint8_t *slots, unsigned nslots, Mat pa}}/* pass 2 left each list's start at the next one's: shift back */- for (int b = ix->nb + 1; b >= 1; b--) S->starts[ix->s0 + b] = S->starts[ix->s0 + b - 1];+ int n = ix->nx * ix->ny;+ for (int b = n + 1; b >= 1; b--) S->starts[ix->s0 + b] = S->starts[ix->s0 + b - 1];S->starts[ix->s0] = S->nent;- S->nent = S->starts[ix->s0 + ix->nb + 1];+ S->nent = S->starts[ix->s0 + n + 1];+ /* the parks' ground has layers: an opaque tile hides the tiles placed just like it before it */+ if (!ground) return;+ for (int c = 0; c < n; c++)+ for (int i = S->starts[ix->s0 + c]; i < S->starts[ix->s0 + c + 1]; i++) {+ Item a, b;+ if (!item_at(slots, S->ent[i], parent, &a, 0) || !(a.s->shape & SH_OPAQUE)) continue;+ for (int j = S->starts[ix->s0 + c]; j < i; j++)+ if (S->ent[j] != 0xFFFF && item_at(slots, S->ent[j], parent, &b, 0) && fabsf(a.box.x - b.box.x) < .5f &&+ fabsf(a.box.y - b.box.y) < .5f && fabsf(a.box.w - b.box.w) < .5f && fabsf(a.box.h - b.box.h) < .5f)+ S->ent[j] = 0xFFFF;+ }}-/* the children that may reach rows [y0, y1), each once, in timeline order */+/* the children that may reach the rectangle, each once, in timeline order */typedef void (*ItemFn)(uint16_t off, void *ctx);-static void index_query(const Index *ix, float y0, float y1, ItemFn fn, void *ctx) {- if (!ix->nb) return;- int b0 = (int)floorf((y0 - ix->maxh - ix->y0) / ix->bh), b1 = (int)floorf((y1 - ix->y0) / ix->bh);- uint16_t pos[18], end[18];+static void index_query(const Index *ix, float x0, float y0, float x1, float y1, ItemFn fn, void *ctx) {+ if (!ix->nx) return;+ int cx0 = (int)floorf((x0 - ix->maxw - ix->x0) / ix->cell), cx1 = (int)floorf((x1 - ix->x0) / ix->cell);+ 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 (b1 >= 0 && b0 < ix->nb) {- b0 = clampi(b0, 0, ix->nb - 1);- b1 = clampi(b1, 0, ix->nb - 1);- if (b1 - b0 > 16) b1 = b0 + 16;- for (int b = b0; b <= b1; b++, k++) {- pos[k] = S->starts[ix->s0 + b];- end[k] = S->starts[ix->s0 + b + 1];- }+ if (cx1 >= 0 && cy1 >= 0 && cx0 < ix->nx && cy0 < ix->ny) {+ 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++)+ for (int cx = cx0; cx <= cx1 && k < QMAX - 1; cx++) {+ int c = ix->s0 + cy * ix->nx + cx;+ if (S->starts[c] == S->starts[c + 1]) continue;+ pos[k] = S->starts[c];+ end[k++] = S->starts[c + 1];+ }}- pos[k] = S->starts[ix->s0 + ix->nb]; /* the tall ones */- end[k] = S->starts[ix->s0 + ix->nb + 1];- k++;+ int t = ix->s0 + ix->nx * ix->ny; /* the big ones */+ pos[k] = S->starts[t];+ end[k++] = S->starts[t + 1];for (;;) {int best = -1;- for (int i = 0; i < k; i++)- if (pos[i] < end[i] && (best < 0 || S->ent[pos[i]] < S->ent[pos[best]])) best = i;+ uint16_t bo = 0xFFFF;+ for (int i = 0; i < k; i++) {+ while (pos[i] < end[i] && S->ent[pos[i]] == 0xFFFF) pos[i]++; /* hidden ground tiles */+ if (pos[i] < end[i] && S->ent[pos[i]] < bo) { best = i; bo = S->ent[pos[i]]; }+ }if (best < 0) break;- fn(S->ent[pos[best]++], ctx);+ pos[best]++;+ fn(bo, ctx);}}@@ -555,12 +737,11 @@ static void set_local(NodeId n, float x, float y) {static void zsprites(NodeId n, NodeId root, float root_z, int depth) {if (depth > 10) return;for (NodeId c = nodes[n].first; c; c = nodes[c].next) {- uint16_t T = nodes[c].T;- if (T != NONE16 && comp_has(T, C_zSprite)) {+ if (has_comp(c, C_zSprite)) {NodeId a = n;for (int up = 0; up < 3 && a; up++, a = nodes[a].parent) {if (a == root) { set_local(c, 0, -root_z); break; }- if (nodes[a].T != NONE16 && comp_has(nodes[a].T, C_zObject)) { set_local(c, 0, -comp_float(nodes[a].T, C_zObject, F_z, 0)); break; }+ if (has_comp(a, C_zObject)) { set_local(c, 0, -comp_float(nodes[a].T, C_zObject, F_z, 0)); break; }}}zsprites(c, root, root_z, depth + 1);@@ -569,7 +750,7 @@ static void zsprites(NodeId n, NodeId root, float root_z, int depth) {static void hide_markers(NodeId n) {for (NodeId c = nodes[n].first; c; c = nodes[c].next)- if (nodes[c].T != NONE16 && comp_has(nodes[c].T, C_skateRailMarker)) nodes[c].alpha = 0;+ if (has_comp(c, C_skateRailMarker)) nodes[c].alpha = 0;}static void proto_setup(Sym *s) {@@ -584,20 +765,25 @@ static void proto_setup(Sym *s) {if (S->markers_hidden && (s->fl & SF_MARKERS)) hide_markers(p);}-static NodeId proto(Sym *s) {- s->stamp = S->stamp;- if (s->proto) return s->proto;- /* room: forget the prototypes not drawn lately */- while (node_count() + PROTO_RESERVE >= NODE_MAX) {+/* make room for `need` more nodes: forget the prototypes not drawn lately */+static bool room(unsigned need) {+ while (node_count() + need >= NODE_MAX) {Sym *old = NULL;for (int i = 0; i < S->nsym; i++) {Sym *o = &S->sym[i];if (o->proto && o->stamp != S->stamp && (!old || (uint16_t)(S->stamp - o->stamp) > (uint16_t)(S->stamp - old->stamp))) old = o;}- if (!old) return 0;+ if (!old) return false;node_free(old->proto);old->proto = 0;}+ return true;+}++static NodeId proto(Sym *s) {+ s->stamp = S->stamp;+ if (s->proto) return s->proto;+ if (!room(PROTO_RESERVE)) return 0;NodeId n = node_new_sym(s->sym);if (!n) return 0;node_add(S->map, n);@@ -627,12 +813,66 @@ static void tile_frames(Sym *s) {}}+/* a billboard: first without its screens, then each screen: its colour, then the rest of it */+static void draw_screens(NodeId p, Mat parent) {+ NodeId sc[6];+ int n = 0;+ for (NodeId c = nodes[p].first; c && n < 6; c = nodes[c].next)+ if (screen_of(nodes[c].sym) >= 0 && node_visible(c)) {+ sc[n++] = c;+ nodes[c].flags &= (uint8_t)~NF_VISIBLE;+ }+ node_draw(p, parent);+ Mat pm = mat_mul(parent, node_local(p));+ for (int i = 0; i < n; i++) {+ NodeId c = sc[i];+ nodes[c].flags |= NF_VISIBLE;+ Mat cm = mat_mul(pm, node_local(c));+ uint8_t al = (uint8_t)(nodes[p].alpha * nodes[c].alpha / 255);+ Clip cc;+ Key k0;+ if (clip_get(nodes[c].sym, &cc) && cc.nslots && slot_at(cc.slots, nodes[c].frame, &k0, NULL) && k0.kind == CK_SYM) {+ Acc sa = {0, 0, 0, 0, false};+ content(k0.ref, 0, mat_mul(cm, key_mat(&k0)), &sa, 0);+ if (sa.any) {+ Rect r = {sa.lx, sa.ly, sa.hx - sa.lx, sa.hy - sa.ly};+ int x0 = (int)floorf(r.x + .5f), y0 = (int)floorf(r.y + .5f), x1 = (int)floorf(r.x + r.w + .5f), y1 = (int)floorf(r.y + r.h + .5f);+ int k = screen_of(nodes[c].sym);+ gfx_rect(x0, y0, x1 - x0, y1 - y0, rgb565(screens[k].r, screens[k].g, screens[k].b), al);+ }+ }+ for (NodeId g = nodes[c].first; g; g = nodes[g].next)+ if (nodes[g].slot != 0) node_draw_in(g, cm, al);+ }+}+static void draw_item(const Item *it, Mat parent) {+ if (it->s->shape & SH_BITMAP) {+ Clip c;+ Key k;+ 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));+ return;+ }NodeId p = proto(it->s);if (!p) return;if (it->s->fl & SF_TILEANIM) tile_frames(it->s);place(p, &it->k);- node_draw(p, parent);+ if (it->s->fl & SF_SCREENS) draw_screens(p, parent);+ else node_draw(p, parent);+}++static void draw_loose(const Key *k, Mat m) {+ if ((k->flags & K_HIDDEN) || !k->alpha) return;+ if (k->kind == CK_SHAPE) { gfx_shape(payload(k->ref), mat_mul(m, key_mat(k)), k->alpha); return; }+ NodeId t = node_new(NK_TEXT);+ if (!t) return;+ nodes[t].ref = k->ref;+ place(t, k);+ node_draw(t, m);+ node_free(t);}/* ---------------------------------------------------------------- the HUD (ck): texts, trick prompt icons, tweens */@@ -721,13 +961,14 @@ static void pt(uint8_t type) {if (type > AC_ACTION || !S->prompt) return;int i = icon_new();if (i < 0) return;+ if (!room(MENU_RESERVE + 8)) return;NodeId n = node_new_sym(S_skate_Lqa);if (!n) return;node_add(S->prompt, n);node_goto(n, icon_labels[type], 0, false);node_update_one(n);Icon *ic = &S->icon[i];- *ic = (Icon){n, 0, 0, 1, 1, 5, 5, true, true, false};+ *ic = (Icon){n, 0, 0, 1, 1, 5, 5, true, true, false, false};if (S->nlist < ICON_MAX) S->list[S->nlist++] = (uint8_t)i;int g = S->nlist;bool k = g > 4;@@ -772,7 +1013,7 @@ static void xt(int t, int nacts) {ic->fading = false;icon_x(ic, x);if (a < c) { icon_fade(ic); ic->listed = false; }- /* else: the doodle tints the trick's icons green (ColorFilter), which the renderer cannot */+ else ic->green = true; /* ColorFilter(.2, 1, .2): drawn by draw_over */}if (c > 0) {memmove(S->list, S->list + c, (size_t)(m - c));@@ -799,6 +1040,11 @@ static void tweens(void) {S->tr_t++;S->tr_alpha = (uint8_t)(255 * lerp(S->tr_a0, S->tr_a1, S->tr_t / 30.0f) + .5f);}+ for (int i = 0; i < ICON_MAX; i++)+ if (S->icon[i].used && S->icon[i].n) {+ if (S->icon[i].green) nodes[S->icon[i].n].flags &= (uint8_t)~NF_VISIBLE;+ else nodes[S->icon[i].n].flags |= NF_VISIBLE;+ }if (S->tname) nodes[S->tname].alpha = S->tr_alpha;if (S->tscore) nodes[S->tscore].alpha = S->tr_alpha;}@@ -851,7 +1097,7 @@ static void col_add(uint16_t off, void *ctx) {Rect b = item_bounds(&it);if (b.x > cs->x1 || b.y > cs->y1 || b.x + b.w < cs->x0 || b.y + b.h < cs->y0) return;float z0 = body_z0(it.s);- cs->c[cs->n++] = (Col){b.x, b.y, b.x + b.w, b.y + b.h, z0, z0 + body_h(it.s), it.s->shape};+ cs->c[cs->n++] = (Col){b.x, b.y, b.x + b.w, b.y + b.h, z0, z0 + body_h(it.s), (uint8_t)(it.s->shape & 3)};}/* the top of a collider at x (a ramp's slope) */@@ -865,54 +1111,77 @@ static float col_top(const Col *c, float x) {typedef struct { float x, y, z, vx, vy, vz, hx, hy, hz; } Body;-/* pushes the body out of c; 0: no contact, 1: a side, 2: a surface it stands on */-static int collide(Body *b, const Col *c) {- float ox = fminf(b->x + b->hx, c->x1) - fmaxf(b->x - b->hx, c->x0);- float oy = fminf(b->y + b->hy, c->y1) - fmaxf(b->y - b->hy, c->y0);- float bot = b->z - b->hz, top = b->z + b->hz;- if (ox <= 0 || oy <= 0 || top <= c->z0 || bot >= c->z1) return 0;- float sy = b->y < (c->y0 + c->y1) / 2 ? -1.0f : 1.0f;- if (!c->shape) {- float oz = fminf(top, c->z1) - fmaxf(bot, c->z0);- if (oz <= ox && oz <= oy) {- if (b->z > (c->z0 + c->z1) / 2) { b->z += c->z1 - bot; if (b->vz < 0) b->vz = 0; return 2; }- b->z -= top - c->z0;- if (b->vz > 0) b->vz = 0;- return 1;+/* a contact of cannon's narrowphase: normal (towards the skater), depth (< 0 inside), points */+typedef struct { float nx, ny, nz, g; uint8_t np; bool flat; } Contact;+#define CONTACT_MAX 24++/* SAT between the skater's box and a box or ramp (cannon's convexConvex over the face axes): the+ * axis of least overlap is the contact's normal */+static bool contact_with(const Body *b, const Col *c, Contact *o) {+ float ox = fminf(b->x + b->hx, c->x1) - fmaxf(b->x - b->hx, c->x0), oy = fminf(b->y + b->hy, c->y1) - fmaxf(b->y - b->hy, c->y0);+ float oz = fminf(b->z + b->hz, c->z1) - fmaxf(b->z - b->hz, c->z0);+ if (ox < 0 || oy < 0 || oz < 0) return false;+ float best = ox;+ *o = (Contact){b->x < (c->x0 + c->x1) / 2 ? -1.0f : 1.0f, 0, 0, 0, 4, false};+ if (oy < best) { best = oy; *o = (Contact){0, b->y < (c->y0 + c->y1) / 2 ? -1.0f : 1.0f, 0, 0, 4, false}; }+ if (oz < best) { best = oz; *o = (Contact){0, 0, b->z > (c->z0 + c->z1) / 2 ? 1.0f : -1.0f, 0, 4, true}; }+ if (c->shape) {+ /* the slope: the ramp reaches its plane, the box down to its lowest corner */+ bool left = c->shape == 1;+ float span = c->x1 - c->x0, s = span > 0 ? (c->z1 - c->z0) / span : 0, l = sqrtf(1 + s * s);+ float nx = (left ? -s : s) / l, nz = 1 / l;+ float top = nx * (left ? c->x0 : c->x1) + nz * c->z0, bottom = nx * (left ? c->x1 : c->x0) + nz * c->z0;+ float ext = fabsf(nx) * b->hx + nz * b->hz, mid = nx * b->x + nz * b->z;+ float on = fminf(top, mid + ext) - fmaxf(bottom, mid - ext);+ if (on < 0) return false; /* a separating axis */+ if (on < best) { best = on; *o = (Contact){nx, 0, nz, 0, 2, true}; }+ }+ o->g = -best;+ return true;+}++static int contacts_at(const Body *b, const ColSet *cs, Contact *out) {+ int n = 0;+ if (b->z - b->hz <= 0) out[n++] = (Contact){0, 0, 1, b->z - b->hz, 4, true}; /* the ground plane */+ for (int i = 0; i < cs->n && n < CONTACT_MAX; i++)+ if (contact_with(b, &cs->c[i], &out[n])) n++;+ return n;+}++/* cannon's GSSolver with SPOOK contact equations (stiffness 1e7, relaxation 3), the skater's side only */+static void solve(Body *b, const Contact *c, int n, float h, float gz) {+ const float k = 1e7f, d = 3, im = 1.0f / 10; /* mass 10 */+ const float sa = 4 / (h * (1 + 4 * d)), sb = 4 * d / (1 + 4 * d), eps = 4 / (h * h * k * (1 + 4 * d));+ float lam[CONTACT_MAX * 4], rhs[CONTACT_MAX * 4];+ const Contact *eq[CONTACT_MAX * 4];+ int m = 0;+ for (int i = 0; i < n; i++)+ for (int p = 0; p < c[i].np && m < CONTACT_MAX * 4; p++, m++) {+ eq[m] = &c[i];+ lam[m] = 0;+ float gw = b->vx * c[i].nx + b->vy * c[i].ny + b->vz * c[i].nz;+ rhs[m] = -c[i].g * sa - gw * sb - gz * c[i].nz * h;}- if (ox <= oy) {- if (b->x < (c->x0 + c->x1) / 2) { b->x -= b->x + b->hx - c->x0; if (b->vx > 0) b->vx = 0; }- else { b->x += c->x1 - (b->x - b->hx); if (b->vx < 0) b->vx = 0; }- return 1;+ float wx = 0, wy = 0, wz = 0;+ const float cc = im + eps;+ for (int it = 0; it < 40 && m; it++) {+ float tot = 0;+ for (int i = 0; i < m; i++) {+ const Contact *e = eq[i];+ float gwl = wx * e->nx + wy * e->ny + wz * e->nz;+ float dl = (rhs[i] - gwl - eps * lam[i]) / cc;+ if (lam[i] + dl < 0) dl = -lam[i];+ lam[i] += dl;+ tot += fabsf(dl);+ wx += im * dl * e->nx;+ wy += im * dl * e->ny;+ wz += im * dl * e->nz;}- if (sy < 0) { b->y -= b->y + b->hy - c->y0; if (b->vy > 0) b->vy = 0; }- else { b->y += c->y1 - (b->y - b->hy); if (b->vy < 0) b->vy = 0; }- return 1;- }- /* a ramp (cannon's convex leftRamp / rightRamp): the slope, the wall at its high end, its sides */- bool left = c->shape == 1;- float span = c->x1 - c->x0, hgt = c->z1 - c->z0, s = span > 0 ? hgt / span : 0;- float up = left ? fminf(b->x + b->hx, c->x1) : fmaxf(b->x - b->hx, c->x0);- float over = col_top(c, up) - bot;- if (over <= 0) return 0;- float l = sqrtf(1 + s * s), pn = over / l;- bool behind = left ? b->x > c->x1 : b->x < c->x0;- float wall = left ? c->x1 - (b->x - b->hx) : b->x + b->hx - c->x0;- if (behind && wall < pn && wall <= oy) {- if (left) { b->x += wall; if (b->vx < 0) b->vx = 0; }- else { b->x -= wall; if (b->vx > 0) b->vx = 0; }- return 1;- }- if (oy < pn) {- if (sy < 0) { b->y -= oy; if (b->vy > 0) b->vy = 0; }- else { b->y += oy; if (b->vy < 0) b->vy = 0; }- return 1;- }- b->z += over;- float nx = (left ? -s : s) / l, nz = 1 / l;- float vn = b->vx * nx + b->vz * nz;- if (vn < 0) { b->vx -= vn * nx; b->vz -= vn * nz; }- return 2;+ if (tot * tot < 1e-14f) break;+ }+ b->vx += wx;+ b->vy += wy;+ b->vz += wz;}/* yr: one frame of the cannon world (4 substeps), then Ar (the ground under the skater) */@@ -923,33 +1192,25 @@ static void physics(void) {cs.x1 = S->px + S->bcx + S->bhx + 40;cs.y0 = S->py + S->bcy - S->bhy - 40;cs.y1 = S->py + S->bcy + S->bhy + 40;- index_query(&S->mi, cs.y0 - 8, cs.y1 + 8, col_add, &cs);+ index_query(&S->mi, cs.x0, cs.y0, cs.x1, cs.y1, col_add, &cs);Body b = {S->px + S->bcx, S->py + S->bcy, S->z + 10, S->vx * 30, S->vy * 30, S->vz * 30, S->bhx, S->bhy, 10};float h = 1.0f / (FPS * 4), damp = powf(1 - .4f, h);bool flat = false;+ Contact ct[CONTACT_MAX];for (int st = 0; st < 4; st++) {- b.vz += S->gravity * h;+ int n = contacts_at(&b, &cs, ct);+ if (st == 3) {+ flat = false;+ for (int i = 0; i < n; i++) if (ct[i].flat) flat = true;+ }+ solve(&b, ct, n, h, S->gravity);b.vx *= damp;b.vy *= damp;b.vz *= damp;+ b.vz += S->gravity * h;b.x += b.vx * h;b.y += b.vy * h;b.z += b.vz * h;- flat = false;- for (int it = 0; it < 4; it++) {- bool any = false;- if (b.z - b.hz < 0) { /* the ground plane */- b.z = b.hz;- if (b.vz < 0) b.vz = 0;- flat = any = true;- }- for (int i = 0; i < cs.n; i++) {- int r = collide(&b, &cs.c[i]);- if (r) any = true;- if (r == 2) flat = true;- }- if (!any) break;- }}S->vx = b.vx / 30;S->vy = b.vy / 30;@@ -1129,7 +1390,7 @@ static void skater(void) {if (!(S->sk > 0 || S->kbt > 0)) {if (!S->markers_hidden) markers_hide_all();RailCtx rc = {{S->px, S->py, S->z}, {S->vx, S->vy}};- index_query(&S->mi, S->py - 48, S->py + 48, rail_check, &rc);+ index_query(&S->mi, S->px - 48, S->py - 48, S->px + 48, S->py + 48, rail_check, &rc);if (S->grinding) {float h[3];nt(S->rail, S->rail + 3, rc.p, false, h);@@ -1216,7 +1477,7 @@ static void skater(void) {else if (S->bb > 0 || S->ca > 0) {if (S->bb == 1 || S->ca == 1)for (NodeId c = nodes[P].first; c; c = nodes[c].next)- if (node_visible(c) && nodes[c].T != NONE16 && comp_has(nodes[c].T, C_sprite))+ if (node_visible(c) && has_comp(c, C_sprite))for (NodeId g = nodes[c].first; g; g = nodes[g].next)if (nodes[g].kind == NK_CLIP) node_goto(g, NULL, 0, true);kj(P, player_labels[3]);@@ -1225,7 +1486,12 @@ static void skater(void) {kj(P, player_labels[jl == 0 && v < .3f ? 0 : v < 2 ? 1 : 2]);}for (NodeId c = nodes[P].first; c; c = nodes[c].next)- if (node_visible(c) && nodes[c].T != NONE16 && comp_has(nodes[c].T, C_sprite)) ent_dir_label(c, S->dir);+ if (node_visible(c) && has_comp(c, C_sprite)) ent_dir_label(c, S->dir);+#ifdef HOST+ if (getenv("SKATE_TRACE"))+ fprintf(stderr, "T %u %g %g %d %.3f %.3f %.3f %.4f %.4f %.4f %d %s %s %d %d %d %d %d\n", game.ticks, in.jx, in.jy, in.held[A_ACTION], S->px, S->py, S->z,+ S->vx, S->vy, S->vz, S->tb, dir_names[S->dir], node_label(P), (int)S->hf, S->bb, S->ca, S->kbt, S->grinding);+#endif}/* dq and tt for the skater: its sprites at -z, its shadow on the ground (-KT) */@@ -1249,7 +1515,7 @@ static void player_place(void) {static bool in_trigger(NodeId e, Mat m, int z0, int z1) {if (!bh(z0 - .1f, S->z, z1 + .1f)) return false;for (NodeId a = nodes[e].first; a; a = nodes[a].next) {- if (nodes[a].T == NONE16 || !comp_has(nodes[a].T, C_triggerArea) || !(nodes[a].flags & NF_ONSTAGE)) continue;+ if (!has_comp(a, C_triggerArea) || !(nodes[a].flags & NF_ONSTAGE)) continue;float u, v;if (mat_inv_apply(mat_mul(m, node_local(a)), S->px, S->py, &u, &v) && node_hit(a, u, v)) return true;}@@ -1281,7 +1547,7 @@ static void boost_fire(uint16_t off) {static void triggers(void) {HitSet hs = {{0}, 0};- index_query(&S->mi, S->py - 64, S->py + 64, boost_check, &hs);+ index_query(&S->mi, S->px - 64, S->py - 64, S->px + 64, S->py + 64, boost_check, &hs);for (int i = 0; i < S->ninside; i++) {bool still = false;for (int j = 0; j < hs.n; j++) if (hs.hit[j] == S->inside[i]) still = true;@@ -1312,7 +1578,7 @@ static void champs_sync(Rect view) {Item it;if (!item_at(S->mslots, c->off, MAT_ID, &it, 0)) continue;bool want = rect_intersects(it.box, near);- if (want && !c->n && node_count() + 40 < NODE_MAX) {+ if (want && !c->n && room(MENU_RESERVE + 40)) {NodeId n = node_new_sym(it.s->sym);if (!n) continue;node_add(S->map, n);@@ -1363,6 +1629,11 @@ static void champion(void) {}} else if (S->nch) {S->champ = (int8_t)champ_pick(false);+#ifdef HOST+ Item it;+ if (getenv("SKATE_DEBUG") && S->champ >= 0 && item_at(S->mslots, S->ch[S->champ].off, MAT_ID, &it, 0))+ fprintf(stderr, "skate: champion %d of %d at %.1f %.1f z %.0f\n", S->champ, S->nch, it.m.tx, it.m.ty, it.s->z);+#endiffor (int i = 0; i < S->nch; i++) {S->ch[i].alpha = S->ch[i].active = i == S->champ;champ_node_state(i);@@ -1424,6 +1695,11 @@ static void timer(void) {}static void on_go(void) {+#ifdef HOST+ const char *tp = getenv("SKATE_TP"); /* tests: start somewhere else */+ float x, y, z = 0;+ if (tp && sscanf(tp, "%f,%f,%f", &x, &y, &z) >= 2) { S->px = x; S->py = y; S->z = z; }+#endiffor (int i = 0; i < S->nsym; i++)if (S->sym[i].proto) zsprites(S->sym[i].proto, S->sym[i].proto, S->sym[i].z, 0);for (int i = 0; i < S->nch; i++)@@ -1494,7 +1770,14 @@ static void vis_add(float key, uint16_t off, uint16_t what) {static void object_item(uint16_t off, void *ctx) {DrawCtx *dc = ctx;Item it;- if (!item_at(S->mslots, off, MAT_ID, &it, 8) || !rect_intersects(it.box, dc->view)) return;+ if (!item_at(S->mslots, off, MAT_ID, &it, 8)) {+ Key k;+ Mat lm;+ Rect r;+ if (loose_at(S->mslots, off, MAT_ID, &k, &lm, &r) && rect_intersects(r, dc->view)) vis_add(lm.ty, off, 0);+ return;+ }+ if (!rect_intersects(it.box, dc->view)) return;if (it.s->fl & SF_CHAMP) {for (int i = 0; i < S->nch; i++)if (S->ch[i].off == off) vis_add(it.m.ty, off, (uint16_t)(2 + i));@@ -1525,11 +1808,11 @@ static void draw_under(void) {}if (S->bslots) {DrawCtx g = {view, mat_mul(m, S->bgm)};- index_query(&S->bi, view.y, view.y + view.h, ground_item, &g);+ index_query(&S->bi, view.x, view.y, view.x + view.w, view.y + view.h, ground_item, &g);}/* everything else, in draw order */S->nvis = 0;- index_query(&S->mi, view.y - 8, view.y + view.h + 8, object_item, &dc);+ index_query(&S->mi, view.x - 8, view.y - 8, view.x + view.w + 8, view.y + view.h + 8, object_item, &dc);if (S->player) {vis_add(S->py + S->bcy - S->bhy + 20 + S->kt, S->player_off, 1);}@@ -1541,9 +1824,18 @@ static void draw_under(void) {if (c < S->nch && S->ch[c].n) node_draw(S->ch[c].n, m);} else {Item it;+ Key k;+ Mat lm;+ Rect r;if (item_at(S->mslots, v->off, MAT_ID, &it, 0)) draw_item(&it, m);+ else if (loose_at(S->mslots, v->off, MAT_ID, &k, &lm, &r)) draw_loose(&k, m);}}+ /* the prompt's bar is a gradient, which the data does not keep: drawn in strips */+ if (S->prompt && node_visible_chain(S->prompt)) {+ Mat g = mat_mul(mat_mul((Mat){1.0f / 3, 0, 0, 1.0f / 3, 0, 0}, node_global(S->prompt)), (Mat){1.178f, 0, 0, 1, 0, 0});+ gfx_shape(S->grad, g, nodes[S->prompt].alpha);+ }}/* a HUD text in a colour of the code's (the time's red, a fall's red) */@@ -1559,7 +1851,79 @@ static void text_in(NodeId n, uint16_t color) {gfx_text_k(node_text(n), m, color, t[6], (int16_t)lw, (int16_t)lh, nodes[n].alpha, k);}+/* a sprite as a shape of one colour (the icons tinted green): a rectangle per run of pixels, built in+ * buf; returns its size, 0 if it does not fit */+static int sprite_shape(uint16_t sp, uint8_t *buf, int room, float fr, float fg, float fb) {+ const uint8_t *r = spr_get(sp);+ if (!r || room < 6) return 0;+ Sprite si;+ sprite_info(sp, &si);+ const uint16_t *pal = pal565(si.sheet);+ int w = rd16(r), h = rd16(r + 2), n = 6;+ uint16_t col = 0xFFFF;+ buf[0] = 1;+ buf[5] = 0;+ (void)w;+ for (int y = 0; y < h; y++) {+ const uint8_t *p = r + rd16(r + 4 + 2 * y);+ int runs = rd16(p), cx = 0;+ p += 2;+ for (int k = 0; k < runs; k++) {+ cx += *p++;+ int code = *p++;+ bool fill = code & 0x80;+ int len = fill ? (code & 0x7F) + 1 : code;+ if (col == 0xFFFF) col = pal[p[0]];+ p += fill ? 1 : len;+ if (n + 18 > room || buf[5] == 255) return 0;+ int16_t pts[8] = {(int16_t)(cx * 4), (int16_t)(y * 4), (int16_t)((cx + len) * 4), (int16_t)(y * 4),+ (int16_t)((cx + len) * 4), (int16_t)((y + 1) * 4), (int16_t)(cx * 4), (int16_t)((y + 1) * 4)};+ buf[n++] = 4;+ buf[n++] = 0;+ for (int i = 0; i < 8; i++) { buf[n++] = (uint8_t)(pts[i] & 0xFF); buf[n++] = (uint8_t)((uint16_t)pts[i] >> 8); }+ buf[5]++;+ cx += len;+ }+ }+ /* RGB565 to 8 bits, times the filter */+ float cr = (col >> 11) * 255.0f / 31, cg = ((col >> 5) & 63) * 255.0f / 63, cb = (col & 31) * 255.0f / 31;+ buf[1] = (uint8_t)(cr * fr + .5f);+ buf[2] = (uint8_t)(cg * fg + .5f);+ buf[3] = (uint8_t)(cb * fb + .5f);+ buf[4] = 255;+ return n;+}+static void draw_over(void) {+ /* the green icons of a trick (the vis list is free once draw_under is done) */+ uint8_t *buf = (uint8_t *)S->vis;+ int used = 0;+ uint16_t made[2] = {NONE16, NONE16}, at[2] = {0, 0};+ for (int i = 0; i < ICON_MAX; i++) {+ Icon *ic = &S->icon[i];+ if (!ic->used || !ic->green || !ic->n || !nodes[ic->n].alpha) continue;+ Clip c;+ Key k;+ SymInfo si;+ if (!clip_get(nodes[ic->n].sym, &c)) continue;+ const uint8_t *q = c.slots, *nx;+ bool found = false;+ for (unsigned sl = 0; sl < c.nslots && !found; sl++, q = nx)+ if (slot_at(q, nodes[ic->n].frame, &k, &nx) && k.kind == CK_SYM) found = true;+ if (!found || (sym_info(k.ref, &si), si.type != SYM_BITMAP)) continue;+ uint16_t sp = (uint16_t)si.v;+ int m = made[0] == sp ? 0 : made[1] == sp ? 1 : -1;+ if (m < 0) {+ m = made[0] == NONE16 ? 0 : made[1] == NONE16 ? 1 : -1;+ int n = m < 0 ? 0 : sprite_shape(sp, buf + used, (int)sizeof S->vis - used, .2f, 1, .2f);+ if (!n) continue;+ made[m] = sp;+ at[m] = (uint16_t)used;+ used += (n + 3) & ~3;+ }+ Mat g = mat_mul(mat_mul((Mat){1.0f / 3, 0, 0, 1.0f / 3, 0, 0}, node_global(ic->n)), key_mat(&k));+ gfx_shape(buf + at[m], g, (uint8_t)(nodes[ic->n].alpha * k.alpha / 255));+ }if (S->time_red) text_in(S->time, rgb565(0xff, 0x30, 0x30));if (S->trick_red) {text_in(S->tscore, rgb565(0xff, 0x11, 0x11));@@ -1587,6 +1951,19 @@ static void start(void) {S->tr_alpha = 0;S->tr_t = 255;sys_countdown_start(&S->cd);+ /* iba: lf(["rgba(0,0,0,0)", "rgba(0,0,0,0.427)", "rgba(0,0,0,0)"], [0, .518, 1]) from x -118 to 118, y -24 to 24 */+ {+ uint8_t *g = S->grad;+ *g++ = GRAD_STRIPS;+ for (int i = 0; i < GRAD_STRIPS; i++) {+ float x0 = -118 + 236.0f * i / GRAD_STRIPS, x1 = -118 + 236.0f * (i + 1) / GRAD_STRIPS, t = (i + .5f) / GRAD_STRIPS;+ float a = t < .518f ? .427f * t / .518f : .427f * (1 - t) / (1 - .518f);+ *g++ = 0; *g++ = 0; *g++ = 0; *g++ = (uint8_t)(a * 255 + .5f); *g++ = 1;+ *g++ = 4; *g++ = 0;+ int16_t pts[8] = {(int16_t)(x0 * 4), -96, (int16_t)(x1 * 4), -96, (int16_t)(x1 * 4), 96, (int16_t)(x0 * 4), 96};+ for (int k = 0; k < 8; k++) { *g++ = (uint8_t)(pts[k] & 0xFF); *g++ = (uint8_t)((uint16_t)pts[k] >> 8); }+ }+ }/* the root clip ycb: one frame per park, each with its map and the HUD */Clip rc;clip_frame0(S_skate_ycb, &rc);@@ -1660,7 +2037,7 @@ static void start(void) {S->bg_sym = k.ref;S->bslots = bc.slots;S->bgm = km;- index_build(&S->bi, bc.slots, bc.nslots, km, 48, true);+ index_build(&S->bi, bc.slots, bc.nslots, km, 96, true);} else if ((sy->fl & SF_CHAMP) && S->nch < CH_MAX) {S->ch[S->nch++] = (Champ){off, 0, 0, 0, 0, 0};}@@ -1670,10 +2047,11 @@ static void start(void) {sym_info(S_skate_eGa, &si);S->kk_sprite = (uint16_t)si.v;}- index_build(&S->mi, mc.slots, mc.nslots, MAT_ID, 64, false);+ index_build(&S->mi, mc.slots, mc.nslots, MAT_ID, 128, false);#ifdef HOSTif (getenv("SKATE_DEBUG"))- fprintf(stderr, "skate: %u slots, %u syms, %u entries, bands %u+%u, nodes %u\n", mc.nslots, S->nsym, S->nent, S->mi.nb, S->bi.nb, node_count());+ fprintf(stderr, "skate: %u slots, %u syms, %u entries, cells %ux%u+%ux%u (max %.0fx%.0f, %.0fx%.0f), nodes %u, state %u\n", mc.nslots, S->nsym, S->nent,+ S->mi.nx, S->mi.ny, S->bi.nx, S->bi.ny, S->mi.maxw, S->mi.maxh, S->bi.maxw, S->bi.maxh, node_count(), (unsigned)sizeof(State));#endifif (S->player) ent_register_tree(S->player);/* the HUD */diff --git a/games/championisland/src/sport_swim.c b/games/championisland/src/sport_swim.cindex be8795a2..6a675566 100644--- a/games/championisland/src/sport_swim.c+++ b/games/championisland/src/sport_swim.c@@ -1,10 +1,508 @@-/* The swim scene (a stub until it is ported). */-#include "../src/ent.h"+/* Artistic swimming: the doodle's scene Hu (library 81A4DDA62E6C4693B3A00E8A0484897E).+ *+ * A rhythm game: arrows come down four lanes (left, up, down, right) and the+ * player presses that direction as each one reaches its circle. The doodle+ * times everything by its song; the calculator has no sound, so the song's+ * clock is the frame clock: the song starts 3.5 s after the scene, as the+ * countdown says GO, and every tick is 1000/30 ms of it. Each variant is one+ * song with its own chart and scroll speed: "ballad", "rock", and the default+ * ("disco"). Systems, in the doodle's order: Ep (pause), Wo (countdown), Uo+ * (rules), ku (the song's start and end), lu (the clock), mu (new arrows), pu+ * (arrows move, late ones miss), ru (the swimmers bob), uu (keys, the+ * player's moves, hits), tu (the others dance just before each beat), yu (the+ * score), Vp, Up. The arrows have no nodes: they are drawn in their lanes. */+#include <math.h>+#include <stdio.h>+#include "ent.h"+/* the doodle's charts: direction (0 up, 1 right, 2 down, 3 left, 10 the end) and time (ms) */+/* Eu: 91 moves, times shifted by 50 ms */+static const uint16_t eu_t[] = {100, 3680, 4383, 5114, 5846, 6548, 7616, 8017, 8185, 8754, 9468, 9799, 10600, 11685, 12399, 12736, 13299, 13468, 14582, 15180, 15348, 15482, 15650, 15819, 16382, 16747, 17113, 17450, 18251, 18953, 19656, 20364, 21101, 21444, 22181, 23284, 24021, 24358, 24735, 25101, 26256, 26970, 27336, 28050, 28415, 28752, 29129, 29797, 30563, 31231, 31968, 32729, 33065, 33733, 34934, 35683, 35979, 36612, 36780, 37866, 38197, 38580, 38946, 39323, 40078, 40728, 41070, 41442, 41813, 42150, 42551, 43265, 43636, 44344, 45128, 45796, 46533, 46933, 47299, 47607, 47949, 48350, 48721, 49099, 50434, 50805, 52053, 52396, 53441, 53812, 54000};+static const uint8_t eu_k[] = {0, 0, 0, 0, 0, 0, 3, 1, 1, 1, 1, 3, 3, 1, 0, 0, 3, 2, 2, 2, 2, 1, 1, 1, 3, 0, 1, 3, 2, 1, 3, 0, 0, 3, 1, 0, 0, 1, 1, 3, 0, 2, 2, 0, 0, 0, 3, 1, 1, 0, 3, 3, 1, 0, 3, 3, 3, 1, 1, 0, 3, 2, 2, 2, 2, 3, 2, 1, 1, 2, 2, 3, 2, 2, 3, 2, 2, 1, 1, 3, 3, 0, 1, 3, 2, 2, 2, 2, 2, 2, 10};+/* Fu: 159 moves, times shifted by 120 ms */+static const uint16_t fu_t[] = {100, 2757, 2926, 3094, 3262, 3396, 3558, 3727, 3895, 4058, 4226, 4394, 4557, 4690, 4894, 5062, 5224, 5393, 5590, 5759, 5892, 6060, 6223, 6391, 6560, 8092, 8226, 8394, 8557, 8725, 8893, 9062, 9195, 9398, 9561, 9700, 9868, 10106, 10240, 10408, 10681, 11012, 11146, 12655, 13038, 13380, 13746, 14083, 14216, 14524, 14861, 14994, 15464, 16028, 16393, 16562, 16997, 17984, 18361, 18663, 19029, 19360, 19528, 19859, 20660, 21037, 21415, 21745, 21914, 23342, 23713, 24015, 24381, 24718, 24886, 25165, 25530, 25664, 26070, 26680, 27011, 27179, 27678, 28648, 29013, 29379, 29710, 30012, 30244, 30679, 31376, 32078, 32247, 32583, 32885, 33228, 34029, 34331, 34696, 35062, 35230, 35730, 35927, 36293, 36426, 36595, 36763, 36897, 37065, 37227, 37431, 38063, 38528, 39329, 39695, 40031, 40635, 40844, 41047, 41244, 42028, 42742, 43056, 43224, 43595, 43926, 44681, 45047, 45383, 45755, 45923, 46695, 47026, 47398, 47694, 48060, 48396, 48570, 48739, 48878, 49244, 49580, 49778, 49946, 50242, 50445, 50747, 51078, 51415, 51746, 51914, 52680, 53377, 53743, 54079, 54248, 54579, 55380, 56000};+static const uint8_t fu_k[] = {2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 1, 0, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, 2, 1, 0, 3, 0, 1, 0, 3, 3, 1, 0, 3, 1, 0, 0, 0, 0, 1, 0, 3, 0, 1, 0, 3, 0, 1, 0, 0, 0, 1, 0, 3, 0, 1, 0, 3, 0, 1, 0, 3, 0, 0, 0, 1, 0, 3, 0, 1, 2, 3, 2, 2, 2, 3, 2, 1, 2, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 0, 1, 2, 3, 0, 1, 0, 0, 3, 0, 1, 0, 3, 0, 1, 0, 0, 3, 0, 1, 2, 2, 3, 2, 1, 0, 3, 0, 1, 0, 3, 0, 1, 1, 1, 2, 3, 0, 3, 3, 1, 1, 1, 0, 10};+/* Gu: 140 moves, times shifted by -3900 ms */+static const uint16_t gu_t[] = {3951, 5320, 6735, 7470, 8156, 9580, 11003, 12749, 13308, 13683, 14457, 14883, 15248, 15579, 15947, 16216, 16447, 16846, 17027, 17371, 17606, 17856, 18053, 18384, 18747, 18987, 19272, 19824, 20206, 20504, 20871, 21249, 21572, 21840, 22085, 22451, 22638, 22980, 23246, 23484, 23716, 24057, 24422, 24670, 24922, 26850, 27216, 27552, 27757, 28103, 28276, 28484, 28821, 29010, 29350, 30072, 30423, 30760, 32140, 32871, 33384, 33738, 33912, 34305, 34623, 35004, 35350, 35707, 36058, 36224, 37800, 38155, 38517, 38704, 39044, 39903, 40274, 40614, 40985, 41172, 41690, 41885, 42403, 42780, 43121, 43472, 43802, 44171, 44350, 44647, 45569, 45958, 46282, 46454, 46646, 46839, 47017, 47204, 47374, 47527, 47709, 48412, 49115, 49453, 49827, 49999, 50321, 51221, 51554, 51938, 52287, 52475, 52818, 52990, 53171, 53546, 53725, 53905, 54267, 54442, 54624, 54808, 55147, 55503, 55871, 56204, 56558, 56909, 57246, 57590, 57956, 58323, 58679, 59028, 59701, 60390, 60971, 61508, 63259, 64259};+static const uint8_t gu_k[] = {2, 2, 3, 2, 1, 0, 3, 0, 0, 0, 0, 0, 3, 3, 1, 1, 1, 2, 2, 0, 0, 0, 3, 3, 0, 0, 0, 1, 2, 2, 3, 3, 1, 1, 1, 0, 0, 3, 3, 3, 2, 2, 0, 0, 0, 1, 1, 2, 2, 0, 0, 0, 0, 0, 1, 3, 3, 1, 1, 0, 3, 1, 1, 3, 3, 1, 1, 1, 1, 1, 3, 0, 1, 0, 0, 3, 1, 0, 0, 0, 0, 0, 1, 3, 1, 0, 0, 3, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 0, 1, 0, 0, 0, 3, 3, 3, 1, 1, 1, 0, 0, 0, 3, 3, 3, 0, 0, 1, 1, 0, 0, 3, 3, 2, 1, 0, 3, 2, 1, 0, 0, 0, 0, 10};++typedef struct { const uint16_t *t; const uint8_t *k; int n; int shift; float speed; } Chart;++enum { ST_WAIT, ST_MISSED, ST_HIT }; /* danceMoveArrow.state */+enum { L_DEFAULT, L_SUCCESS, L_MISS };+#define ARROW_MAX 48++typedef struct {+ int32_t time;+ float y;+ int16_t anim; /* frames into its sprite's current animation */+ uint8_t type, state, look;+ bool opa; /* the others already danced to it */+} Arrow;++typedef struct {+ NodeId root, map, track[4], target[4], player, champion, oldman, turtle, red, score_text, combo, combo_text;+ NodeId chars[4]; /* the swimmers, left to right */+ float base_x[4], base_y[4];+ int nchars;+ Chart chart;+ /* the arrows' drawing, by direction and look: the animation and its offset */+ uint16_t look_sym[4][3];+ Mat look_m[4][3];+ int16_t look_end[4][3];+ Arrow arrows[ARROW_MAX];+ int narrows;+ /* clockState, playbackState, swimState */+ bool clock_started;+ uint32_t ticks, t0;+ int frame; /* currentFrame */+ float RB; /* the song's time (ms) */+ int rY;+ int wp, ut, sqa, GQ;+ float xL[4]; /* when each direction was last pressed (song time), NAN: never */+ int V6; /* the player's move, -1: none */+ Countdown cd;+ /* the doodle's centred message for Miss / Good / Perfect */+ int judge, judge_t; /* -1: none */+ bool ended;+ int end_t, rating;+ char score_buf[16], combo_buf[16];+} State;++static State *S;++static const char *const dir_label[4] = {"up", "right", "down", "left"};+static const uint8_t dir_input[4] = {A_UP, A_RIGHT, A_DOWN, A_LEFT};+static const uint8_t iu[4] = {0, 2, 1, 3};++static bool has(NodeId n, int c) { return n && nodes[n].T != NONE16 && comp_has(nodes[n].T, c); }++/* ---------------------------------------------------------------- the arrows' looks */+/* a clip's timeline child at a frame (the first one, or the first that is a+ * sprite): its symbol and its matrix in the clip */+static const uint8_t *varint(const uint8_t *p, unsigned *v) {+ unsigned r = 0, sh = 0;+ for (int i = 0; i < 5; i++) {+ uint8_t c = *p++;+ r |= (unsigned)(c & 0x7F) << sh;+ if (!(c & 0x80)) break;+ sh += 7;+ }+ *v = r;+ return p;+}++typedef struct { unsigned start; uint8_t flags, kind; uint16_t ref, mat; float x, y; int16_t rx4, ry4; } TKey;++static const uint8_t *tkey(const uint8_t *p, TKey *k) {+ p = varint(p, &k->start);+ k->flags = *p++;+ if (k->flags & K_ABSENT) return p;+ if (k->flags & K_KIND) { k->kind = *p++; k->ref = rd16(p); p += 2; }+ else { k->kind = CK_SYM; k->ref = rd16(p); p += 2; }+ k->x = rds16(p) * 0.25f;+ k->y = rds16(p + 2) * 0.25f;+ p += 4;+ k->mat = 0;+ if (k->flags & K_MAT) { k->mat = rd16(p); p += 2; }+ k->rx4 = k->ry4 = 0;+ if (k->flags & K_REG) { k->rx4 = rds16(p); k->ry4 = rds16(p + 2); p += 4; }+ if (k->flags & K_ALPHA) p++;+ if (k->flags & K_CLIP) p += 4;+ if (k->flags & K_NAME) p += 2;+ return p;+}++static bool child_key(uint16_t sym, unsigned frame, bool sprite, uint16_t *out, Mat *m) {+ Clip c;+ if (!clip_get(sym, &c)) return false;+ const uint8_t *p = c.slots;+ for (unsigned s = 0; s < c.nslots; s++) {+ unsigned nk;+ p = varint(p, &nk);+ TKey cur = {0}, k;+ int idx = -1;+ for (unsigned j = 0; j < nk; j++) {+ p = tkey(p, &k);+ if (k.start <= frame) { cur = k; idx = (int)j; }+ }+ if (idx < 0 || (cur.flags & K_ABSENT) || cur.kind != CK_SYM) continue;+ Clip cc;+ if (!clip_get(cur.ref, &cc) || (sprite && !(cc.T != NONE16 && comp_has(cc.T, C_sprite)))) continue;+ float a = 1, b = 0, d0 = 0, d = 1;+ if (cur.mat) { const float *mm = mat(cur.mat); a = mm[0]; b = mm[1]; d0 = mm[2]; d = mm[3]; }+ *m = (Mat){a, b, d0, d, cur.x - (cur.rx4 * .25f * a + cur.ry4 * .25f * d0), cur.y - (cur.rx4 * .25f * b + cur.ry4 * .25f * d)};+ *out = cur.ref;+ return true;+ }+ return false;+}++/* the frame an animation stops at or reports that it is over */+static int16_t anim_end(uint16_t sym, int look) {+ Clip c;+ if (!clip_get(sym, &c)) return 0;+ for (int i = 0; i < c.nacts; i++) {+ const uint8_t *a = c.acts + 5 * i;+ if ((look == L_SUCCESS && a[2] == ACT_DISPATCH_PARENT) || (look == L_MISS && a[2] == ACT_STOP)) return (int16_t)rd16(a);+ }+ return (int16_t)(c.nframes - 1);+}++static void looks_setup(void) {+ Clip ya;+ if (!clip_get(S_swim_ysa, &ya)) return;+ static const char *const looks[3] = {"default", "success", "miss"};+ for (int d = 0; d < 4; d++) {+ int f = clip_label(&ya, dir_label[d]);+ uint16_t s1, s2;+ Mat m1, m2;+ Clip sc;+ if (f < 0 || !child_key(S_swim_ysa, (unsigned)f, true, &s1, &m1) || !clip_get(s1, &sc)) continue;+ for (int l = 0; l < 3; l++) {+ int g = clip_label(&sc, looks[l]);+ if (g < 0 || !child_key(s1, (unsigned)g, false, &s2, &m2)) continue;+ S->look_sym[d][l] = s2;+ S->look_m[d][l] = mat_mul(m1, m2);+ S->look_end[d][l] = anim_end(s2, l);+ }+ }+}++static void arrow_look(Arrow *a, int look) {+ a->look = (uint8_t)look;+ a->anim = 0;+}++/* ---------------------------------------------------------------- the map, drawn by code for the arrows */+static void map_hook(NodeId n, Mat m, uint8_t al) {+ for (NodeId c = nodes[n].first; c; c = nodes[c].next) {+ node_draw_in(c, m, al);+ int d = -1;+ for (int k = 0; k < 4; k++) if (S->track[k] == c) d = k;+ if (d < 0 || !node_visible(c)) continue;+ Mat mt = mat_mul(m, node_local(c));+ for (int i = 0; i < S->narrows; i++) {+ Arrow *a = &S->arrows[i];+ if (a->type != d || !S->look_sym[d][a->look]) continue;+ Mat ma = mt;+ ma.tx += mt.c * a->y;+ ma.ty += mt.d * a->y;+ if (ma.ty < -40 || ma.ty > VIEW_H + 40) continue;+ ma = mat_mul(ma, S->look_m[d][a->look]);+ node_draw_sym(S->look_sym[d][a->look], (unsigned)a->anim, ma, al);+ }+ }+}++/* ---------------------------------------------------------------- the swimmers */+static void dance(NodeId c, const char *label) {+ ent_label(c, label, false);+ for (NodeId s = nodes[c].first; s; s = nodes[s].next)+ if ((nodes[s].flags & NF_ONSTAGE) && has(s, C_sprite)) { node_goto(s, NULL, 0, true); break; }+}++static void on_move_finished(NodeId c, uint16_t ev, void *ctx) {+ (void)ev; (void)ctx;+ dance(c, "idle");+ if (c == S->player) S->V6 = -1;+}++static void on_beat_finished(NodeId c, uint16_t ev, void *ctx) { (void)ev; (void)ctx; node_goto(c, NULL, 0, false); }++/* ---------------------------------------------------------------- scoring (qu, xu, wu) */+static void judge(Arrow *a, int points) {+ bool hit = points == 50 || points == 100;+ if (hit) {+ a->state = ST_HIT;+ arrow_look(a, L_SUCCESS);+ } else {+ a->state = ST_MISSED;+ arrow_look(a, L_MISS);+ }+ /* wu: the message (it replaces the one showing) */+ S->judge = points == 100 ? 2 : points == 50 ? 1 : 0;+ S->judge_t = 0;+ toast("");+ /* xu */+ int mult = 1;+ if (hit && S->ut > 10 && S->ut <= 20) mult = 3;+ else if (hit && S->ut > 20) mult = 5;+ S->wp = S->wp + points * mult;+ if (S->wp < 0) S->wp = 0;+ if (hit) {+ S->sqa++;+ S->ut++;+ S->GQ = S->GQ + 1 > 5 ? 5 : S->GQ + 1;+ } else {+ S->ut = 0;+ S->GQ = S->GQ - 1 < -10 ? -10 : S->GQ - 1;+ }+}++/* ---------------------------------------------------------------- start */static void start(void) {- NodeId n = node_new_sym(S_swim_Gcb);- node_add(game.root, n);- ent_register_tree(n);+ S = scene_state(sizeof(State));+ if (!strcmp(game.variant, "rock")) S->chart = (Chart){fu_t, fu_k, (int)sizeof fu_t / 2, 120, 130};+ else if (!strcmp(game.variant, "ballad")) S->chart = (Chart){eu_t, eu_k, (int)sizeof eu_t / 2, 50, 100};+ else S->chart = (Chart){gu_t, gu_k, (int)sizeof gu_t / 2, -3900, 120};+ NodeId root = node_new_sym(S_swim_Gcb);+ if (!root) return;+ node_add(game.root, root);+ S->root = root;+ ent_register_tree(root);+ S->map = ent_first(C_map);+ if (!S->map) return;+ static const char *const names[4] = {"up", "right", "down", "left"};+ for (int d = 0; d < 4; d++) {+ S->track[d] = node_child(S->map, names[d]);+ S->target[d] = S->track[d] ? node_child(S->track[d], "target") : 0;+ /* createjs.ButtonHelper: out, over, down = frames 0, 1, 2 */+ if (S->target[d]) node_goto(S->target[d], NULL, 0, false);+ S->xL[d] = NAN;+ }+ S->player = ent_first2(C_character, C_player);+ S->champion = ent_first2(C_character, C_champion);+ S->oldman = ent_first2(C_character, C_oldMan);+ S->turtle = ent_first2(C_character, C_turtle);+ S->red = ent_first(C_redBg);+ NodeId score = node_find(root, "score");+ if (score) {+ S->score_text = node_child(score, "scoreText");+ S->combo = node_child(score, "combo");+ S->combo_text = S->combo ? node_child(S->combo, "comboText") : 0;+ }+ /* zu: the swimmers, their places, their moves' ends (ru sorts them by x) */+ for (int i = 0; i < ent_count(); i++) {+ NodeId e = ent_at(i);+ if (!has(e, C_character) || S->nchars >= 4) continue;+ float x, y;+ ent_pos(e, &x, &y);+ int j = S->nchars++;+ while (j > 0 && S->base_x[j - 1] > x) {+ S->chars[j] = S->chars[j - 1]; S->base_x[j] = S->base_x[j - 1]; S->base_y[j] = S->base_y[j - 1];+ j--;+ }+ S->chars[j] = e; S->base_x[j] = x; S->base_y[j] = y;+ node_on(e, "move_finished", on_move_finished, NULL);+ }+ /* Au: beat targets wait on their first frame */+ for (int i = 0; i < ent_count(); i++) {+ NodeId e = ent_at(i);+ if (!has(e, C_beatTarget)) continue;+ node_goto(e, NULL, 0, false);+ node_on(e, "beat_finished", on_beat_finished, NULL);+ }+ looks_setup();+ S->V6 = -1;+ S->judge = -1;+ S->frame = -1;+ sys_countdown_start(&S->cd);+ node_draw_hook_id = S->map;+ node_draw_hook = map_hook;+}++static void end(void) {+ node_draw_hook = NULL;+ node_draw_hook_id = 0;+}++/* ---------------------------------------------------------------- systems */+static int chart_time(int i) { return (int)S->chart.t[i] + S->chart.shift; }++/* ku: the song starts with the scene (3.5 s of countdown), and its end marker ends the game */+static void sys_song(void) {+ if (S->ended) {+ if (--S->end_t == 0) menus_game_over_rated((float)S->wp, S->rating);+ }+ if (!S->clock_started) {+ S->clock_started = true;+ S->t0 = S->ticks;+ }+ const Chart *c = &S->chart;+ if (S->rY < c->n && c->k[S->rY] == 10 && S->RB >= chart_time(S->rY) && !S->ended) {+ S->rating = (int)floorf((float)S->sqa / (float)(c->n - 1) * 3 + .5f);+ S->ended = true;+ S->end_t = 80;+ SOUND();+ S->judge = -1;+ toast(msg("NICE_MOVES"));+ }+}++/* lu: the song's clock */+static void sys_clock(void) {+ S->frame++;+ S->RB = (float)(S->ticks - S->t0) * (1000.0f / FPS) - 3500;+}++/* mu: the arrows of the next 2 s */+static void sys_spawn(void) {+ const Chart *c = &S->chart;+ while (S->rY < c->n) {+ int t = chart_time(S->rY);+ if (t > S->RB + 2000 || c->k[S->rY] == 10) break;+ if (S->narrows < ARROW_MAX && c->k[S->rY] < 4) {+ Arrow *a = &S->arrows[S->narrows++];+ memset(a, 0, sizeof *a);+ a->time = t;+ a->type = c->k[S->rY];+ a->y = -1000;+ arrow_look(a, L_DEFAULT);+ }+ S->rY++;+ }+}++/* pu: arrows come down; one 130 ms late is missed */+static void sys_arrows(void) {+ for (int i = 0; i < S->narrows; i++) {+ Arrow *a = &S->arrows[i];+ if (a->state == ST_HIT) continue;+ float n = S->RB - (float)a->time;+ a->y = n / 1000 * S->chart.speed;+ if (n > 130 && a->state == ST_WAIT) judge(a, -5);+ }+}++/* ru: the swimmers bob (out of step when the dancing goes badly), the red light */+static void sys_bob(void) {+ static const int8_t k[4] = {1, 0, -2, 3};+ for (int i = 0; i < S->nchars; i++) {+ NodeId c = S->chars[i];+ float h = 0;+ if (S->GQ <= 0 && c != S->player) h = fabsf((float)S->GQ) / 10 * k[i];+ float b = 20 * sinf(3.14159265f / 60 * S->frame + h);+ ent_set_pos(c, S->base_x[i], S->base_y[i] + (b > 0 ? floorf(b) : ceilf(b)));+ }+ if (S->red) nodes[S->red].alpha = S->GQ < -5 ? (uint8_t)((sinf(3.14159265f / 60 * S->frame) + 1) / 2 * 255 + .5f) : 0;+}++/* uu: the circles, the player's moves, hits */+static void sys_keys(void) {+ for (int i = 0; i < 4; i++) {+ int d = iu[i], e = dir_input[d];+ if (in.pressed[e]) {+ if (S->target[d]) node_goto(S->target[d], NULL, 2, false);+ S->xL[d] = S->RB;+ } else if (!in.held[e] && S->target[d]) node_goto(S->target[d], NULL, 0, false);+ }+ int n = -1;+ for (int i = 0; i < 4; i++)+ if (fabsf(S->RB - S->xL[iu[i]]) < 50) { n = iu[i]; break; }+ if (n >= 0 && n != S->V6 && S->player) {+ S->V6 = n;+ dance(S->player, dir_label[n]);+ }+ /* the arrows by y (vu), the lowest on screen last */+ int order[ARROW_MAX];+ for (int i = 0; i < S->narrows; i++) {+ int j = i;+ while (j > 0 && S->arrows[order[j - 1]].y > S->arrows[i].y) { order[j] = order[j - 1]; j--; }+ order[j] = i;+ }+ for (int i = 0; i < S->narrows; i++) {+ Arrow *a = &S->arrows[order[i]];+ if (a->state != ST_WAIT) continue;+ float d = fabsf((float)a->time - S->xL[a->type]);+ if (d < 70) { judge(a, 100); S->xL[a->type] = 0; }+ else if (d < 130) { judge(a, 50); S->xL[a->type] = 0; }+ }+}++/* tu: the others dance 150 ms before the next arrow */+static void sys_others(void) {+ Arrow *next = NULL;+ for (int i = 0; i < S->narrows; i++) {+ Arrow *a = &S->arrows[i];+ if (!a->opa && (float)a->time > S->RB && (!next || a->time < next->time)) next = a;+ }+ if (!next || (float)next->time - S->RB >= 150) return;+ next->opa = true;+ NodeId who[3] = {S->champion, S->oldman, S->turtle};+ for (int i = 0; i < 3; i++)+ if (who[i]) dance(who[i], dir_label[next->type]);+}++/* yu: the score and the combo */+static void sys_hud(void) {+ snprintf(S->score_buf, sizeof S->score_buf, "%d", S->wp);+ if (S->score_text) node_set_text(S->score_text, S->score_buf);+ if (!S->combo) return;+ node_set_visible(S->combo, S->ut >= 3);+ if (S->ut >= 3 && S->combo_text) {+ snprintf(S->combo_buf, sizeof S->combo_buf, "%d", S->ut);+ node_set_text(S->combo_text, S->combo_buf);+ }}-static void tick(void) { sys_back_pauses(); }-const SceneDef scene_swim = {"swim", start, tick, NULL, NULL, NULL, NULL};++/* the arrows' animations; a hit one goes when its animation is over, a missed+ * one once far below the stage (Up) */+static void animate(void) {+ float track_y = S->track[0] ? node_global(S->track[0]).ty : 0;+ for (int i = 0; i < S->narrows; i++) {+ Arrow *a = &S->arrows[i];+ int16_t e = S->look_end[a->type][a->look];+ bool gone = false;+ if (a->look == L_SUCCESS && a->anim >= e) gone = true;+ else if (a->look == L_MISS && a->anim >= e) a->anim = e;+ else a->anim++;+ if (track_y + 3 * a->y >= 540 + 1440) gone = true;+ if (gone) {+ S->arrows[i] = S->arrows[--S->narrows];+ i--;+ }+ }+}++static void tick(void) {+ sys_back_pauses();+ if (menus_active() || !S || !S->map) return;+ sys_countdown(&S->cd);+ sys_tutorial_once();+ if (menus_active()) return;+ S->ticks++;+ animate();+ if (S->judge >= 0) S->judge_t++;+ sys_song();+ sys_clock();+ sys_spawn();+ sys_arrows();+ sys_bob();+ sys_keys();+ sys_others();+ sys_hud();+ sys_ephemeral();+}++/* ---------------------------------------------------------------- the judgement (To, "scale") */+static void draw_over(void) {+ if (!S || S->judge < 0) return;+ static const char *const keys[3] = {"MISS", "GOOD", "PERFECT"};+ static const uint8_t col[3][6] = {{0xf0, 0x1d, 0x1d, 0x6e, 0x05, 0x05}, {0xff, 0xd5, 0x00, 0x96, 0x50, 0x00}, {0x0b, 0xd6, 0x0b, 0x05, 0x5e, 0x05}};+ static const float scale0[3] = {1.2f, 1.4f, 1.5f};+ float ms = S->judge_t * (1000.0f / FPS);+ /* 500 ms from the big size to 1 (quintOut), 200 ms still, 300 ms to nothing */+ float t = ms < 500 ? ms / 500 : 1, e = 1 - powf(1 - t, 5);+ float sc = scale0[S->judge] + (1 - scale0[S->judge]) * e;+ float alpha = ms <= 700 ? 1 : ms >= 1000 ? 0 : 1 - (ms - 700) / 300;+ if (alpha <= 0) return;+ const char *s = msg(keys[S->judge]);+ int k = 40.0f / 3 * sc >= 17 ? 2 : 1;+ Mat m = MAT_ID;+ m.tx = VIEW_W / 2;+ m.ty = 540 * .28f / 3 - 5.5f * k;+ uint8_t a = (uint8_t)(alpha * 255);+ uint16_t fg = rgb565(col[S->judge][0], col[S->judge][1], col[S->judge][2]);+ uint16_t ol = rgb565(col[S->judge][3], col[S->judge][4], col[S->judge][5]);+ static const int8_t off[8][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, -1}, {-1, 1}, {1, 1}};+ for (int i = 0; i < 8; i++) {+ Mat o = m;+ o.tx += off[i][0];+ o.ty += off[i][1];+ gfx_text_k(s, o, ol, 1, 0, 0, a, k);+ }+ gfx_text_k(s, m, fg, 1, 0, 0, a, k);+}++const SceneDef scene_swim = {"swim", start, tick, end, NULL, draw_over, NULL};diff --git a/games/championisland/src/spr.c b/games/championisland/src/spr.cindex 0c887fed..9c8cf7c6 100644--- a/games/championisland/src/spr.c+++ b/games/championisland/src/spr.c@@ -1,3 +1,5 @@+#include <stdio.h>+#include <stdlib.h>/* Sprites: LZMA decoding into a cache of run-length rows.** data.bin keeps the doodle's images as 8-bit palette indices, compressed@@ -149,7 +151,8 @@ static uint8_t *alloc(uint32_t n, bool force) {live -= (ent[old].size + 3) & ~3u;evict_one();}- compact();+ /* only when the space is short: a full entry table needs no moving */+ if (top + n > cache_bytes) compact();}if (top + n > cache_bytes) return NULL;uint8_t *p = mem + top;@@ -246,6 +249,9 @@ const uint8_t *spr_get(uint16_t sp) {}Sprite s;sprite_info(sp, &s);+#ifdef HOST+ if (getenv("CI_SPR_MISS")) fprintf(stderr, "miss %u kind %d %dx%d rle %u bank %u\n", sp, s.kind, s.w, s.h, (unsigned)s.rle, (unsigned)s.bank);+#endifif (s.kind == 1) {const uint8_t *st = spr_stream(sp);if (!st) return NULL;@@ -262,7 +268,7 @@ const uint8_t *spr_get(uint16_t sp) {sprite_info(o, &t);if (t.off > pos) z_get(NULL, t.off - pos);pos = t.off + (uint32_t)t.w * t.h;- if (find(o) || (o != sp && top + (t.rle ? t.rle : rle_bound(t.w, t.h)) > cache_bytes)) {+ if (find(o) || (o != sp && (nent >= ENTRIES || top + (t.rle ? t.rle : rle_bound(t.w, t.h)) > cache_bytes))) {z_get(NULL, (uint32_t)t.w * t.h);continue;}@@ -291,5 +297,87 @@ const uint8_t *spr_stream(uint16_t sp) {return NULL;}+/* ---------------------------------------------------------------- masks */+/* A sprite's fully opaque pixels as spans, kept in the cache as entry+ * sprite | 0x8000: u16 w, u16 h, u16 row offsets[h], then per row: u16 n,+ * and n spans of (skip, len) bytes (a skip over 255 goes as (255, 0)).+ * Scenery in front of the actors is redrawn from the layer through these:+ * far smaller than the sprite's colours. */+#define MASK 0x8000u+typedef struct { uint8_t *out; uint32_t at, n; int last; } MaskOut;+static void mask_span(MaskOut *o, int a, int b) {+ int gap = a - o->last, l = b - a;+ while (gap > 255) {+ if (o->out) { o->out[o->at] = 255; o->out[o->at + 1] = 0; }+ o->at += 2; o->n++; gap -= 255;+ }+ while (l > 0) {+ int part = l > 255 ? 255 : l;+ if (o->out) { o->out[o->at] = (uint8_t)gap; o->out[o->at + 1] = (uint8_t)part; }+ o->at += 2; o->n++; gap = 0; l -= part;+ }+ o->last = b;+}+/* the mask of a sprite's runs r into out (NULL: only its size), returns the size */+static uint32_t mask_build(const uint8_t *r, const uint8_t *al, uint8_t *out) {+ int w = rd16(r), h = rd16(r + 2);+ MaskOut o = {out, 4 + 2u * (uint32_t)h, 0, 0};+ for (int y = 0; y < h; y++) {+ 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;+ const uint8_t *p = r + rd16(r + 4 + 2 * y);+ int runs = rd16(p), x = 0, s0 = -1;+ p += 2;+ for (int k = 0; k < runs; k++) {+ int skip = *p++, code = *p++;+ bool fill = code & 0x80;+ int len = fill ? (code & 0x7F) + 1 : code;+ const uint8_t *px = p;+ p += fill ? 1 : len;+ if (skip && s0 >= 0) { mask_span(&o, s0, x); s0 = -1; }+ x += skip;+ for (int i = 0; i < len; i++, x++) {+ bool op = al[fill ? px[0] : px[i]] == 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, x);+ if (out) { out[cnt_at] = (uint8_t)o.n; out[cnt_at + 1] = (uint8_t)(o.n >> 8); }+ }+ if (out) { out[0] = (uint8_t)w; out[1] = (uint8_t)(w >> 8); out[2] = (uint8_t)h; out[3] = (uint8_t)(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));+ if (f) {+ 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);+ 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 */+ unsigned fs = find(sp);+ if (!m || !fs) return NULL;+ mask_build(mem + 4u * ent[fs - 1].off4, al, m);+ if (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;+}++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;+}+uint32_t spr_cache_used(void) { return top; }uint32_t spr_capacity(void) { return cache_bytes; }diff --git a/games/championisland/src/spr.h b/games/championisland/src/spr.hindex eb6370f6..77eee072 100644--- a/games/championisland/src/spr.h+++ b/games/championisland/src/spr.h@@ -14,6 +14,8 @@ bool z_get(uint8_t *dst, uint32_t n);const uint8_t *spr_get(uint16_t sprite);const uint8_t *spr_peek(uint16_t sprite); /* only if cached */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);void spr_setup(uint8_t *mem, uint32_t size); /* where the cache lives (game.c's arena) */void spr_reset(void);uint8_t *z_scratch(uint32_t *size); /* the decoder's ring when it is idle */diff --git a/games/championisland/src/world.c b/games/championisland/src/world.cindex bafafa5e..70200048 100644--- a/games/championisland/src/world.c+++ b/games/championisland/src/world.c@@ -88,9 +88,13 @@ static void wall_get(unsigned i, int16_t c[4]) {#define STATIC_BITS 2048/* marks the ids of a grid (statics or walls) whose cells meet the world rect */+static int cell_at(float v, float o) {+ float c = floorf((v - o) / wd.cell);+ return !(c >= -1) ? -1 : c > 4096 ? 4096 : (int)c; /* NaN and far away too */+}static int grid_in(const uint8_t *cells, const uint8_t *list, float x0, float y0, float x1, float y1, uint8_t *bits, int *lo, int *hi) {- int cx0 = (int)floorf((x0 - wd.gx0) / wd.cell), cy0 = (int)floorf((y0 - wd.gy0) / wd.cell);- int cx1 = (int)floorf((x1 - wd.gx0) / wd.cell), cy1 = (int)floorf((y1 - wd.gy0) / wd.cell);+ int cx0 = cell_at(x0, wd.gx0), cy0 = cell_at(y0, wd.gy0);+ int cx1 = cell_at(x1, wd.gx0), cy1 = cell_at(y1, wd.gy0);if (cx0 < 0) cx0 = 0;if (cy0 < 0) cy0 = 0;if (cx1 >= wd.gw) cx1 = wd.gw - 1;@@ -122,10 +126,15 @@ static int statics_in(float x0, float y0, float x1, float y1, uint8_t *bits, int#define WATER 48#define FRONT_MAX 40#define SOLID_MAX 40+#define RAIN_MAX 48typedef struct {uint8_t water[WATER * WATER]; /* the sea's tile now (w9a: frames 0-15, 16-31) */int water_look; /* which, -1 before the first */- NodeId map, player, rain, water_clip;+ NodeId map, player, water_clip;+ float rain; /* bca's alpha (drawn by code, draw_over) */+ uint16_t rain_cond; /* its conditionallyVisible */+ int16_t rain_pos[2 * RAIN_MAX]; /* its tiles */+ int rain_n;uint32_t tick;int roll; /* Bi.Jaa: ticks left in a roll */float stream_x, stream_y; /* camera when the live children were last streamed */@@ -193,6 +202,7 @@ static void draw_static_over(unsigned id, Mat m, uint8_t alpha) {if (si.kind > 1) continue; /* big ground images never stand in front */int x = dr.x, y = dr.y;uint8_t f = dr.flags;+ if (!(f & BD_TRANSPOSE) && alpha == 255) { bg_redraw(dr.sp, x, y, f); continue; }/* the drawn rectangle's corner, back to a matrix */Mat dm;if (f & BD_TRANSPOSE) {@@ -238,6 +248,27 @@ static void draw_map(NodeId map, Mat m, uint8_t alpha) {front[j] = (uint16_t)id;}}+ /* and what is in front of those (a bamboo before a house before the player) */+#ifndef NO_CLOSURE+ for (int i = 0; i < nfront && nfront < FRONT_MAX; i++) {+ Static fs;+ static_get(front[i], &fs);+ uint8_t cb[STATIC_BITS / 8];+ memset(cb, 0, sizeof cb);+ int lo, hi;+ if (!statics_in(fs.x0, fs.y0, fs.x1, fs.y1, cb, &lo, &hi)) continue;+ for (int id = front[i] + 1; id <= hi && nfront < FRONT_MAX; id++) {+ if (!(cb[id >> 3] & (1 << (id & 7))) || (bits[id >> 3] & (1 << (id & 7)))) continue;+ Static s;+ static_get((unsigned)id, &s);+ if (s.x1 <= fs.x0 || s.y1 <= fs.y0 || s.x0 >= fs.x1 || s.y0 >= fs.y1 || s.x0 >= vx1 || s.y0 >= vy1 || s.x1 <= vx || s.y1 <= vy) continue;+ bits[id >> 3] |= (uint8_t)(1 << (id & 7));+ int j = nfront++;+ while (j > i + 1 && front[j - 1] > id) { front[j] = front[j - 1]; j--; }+ front[j] = (uint16_t)id;+ }+ }+#endifint f = 0;for (NodeId c = nodes[map].first; c; c = nodes[c].next) {if (f < nfront && node_visible(c)) {@@ -634,14 +665,36 @@ static void on_trigger(NodeId t, NodeId other, bool entered) {/* rr: the rain over the mountain fades in near it (until the RAIN quest is done) */static void sys_rain(void) {- if (!W->rain || W->region_rain < 0 || !W->player) return;+ if (W->region_rain < 0 || !W->player) return;const uint8_t *r = wd.regions + 10 * (unsigned)W->region_rain;float rx = rds16(r + 2), rb = rds16(r + 8);float px, py;ent_pos(W->player, &px, &py);float a = fminf(clampf((px - rx - 250) / 300, 0, 1), clampf((rb - py) / 400, 0, 1));- float al = nodes[W->rain].alpha / 255.f * .8f + .2f * a;- nodes[W->rain].alpha = (uint8_t)(al * 255 + .5f);+ W->rain = W->rain * .8f + .2f * a;+}++/* bca: 48 px rain tiles over the view, moved with the camera (qr, repeatable+ * tiles), its two looks (Yi: u_a, v_a) taking turns every 3 ticks (Os), at+ * half alpha; drawn as one pattern from the data (pack.py's tiles4) */+static bool rain_slot(unsigned slot, const SlotInfo *si, void *ctx) {+ if (W->rain_n >= RAIN_MAX) return false;+ W->rain_pos[2 * W->rain_n] = (int16_t)floorf(si->x + .5f);+ W->rain_pos[2 * W->rain_n + 1] = (int16_t)floorf(si->y + .5f);+ W->rain_n++;+ return true;+}+static void draw_over_overworld(void) {+ if (!W || !W->map || W->rain < .01f || !W->rain_n || !HDR(H_TILES)) return;+ if (W->rain_cond != NONE16 && str(W->rain_cond)[0] && !cond_eval(W->rain_cond)) return;+ const uint8_t *t = ci_data + HDR(H_TILES);+ int w = rd16(t), h = rd16(t + 2), looks = rd16(t + 4);+ unsigned look = (W->tick / 3) % 2 % (unsigned)(looks ? looks : 1);+ float mx = nodes[W->map].x, my = nodes[W->map].y;+ int ox = (int)floorf((fmodf(fmodf(mx, 144) + 144, 144) - 144) / 3 + .5f);+ int oy = (int)floorf((fmodf(fmodf(my, 144) + 144, 144) - 144) / 3 + .5f);+ gfx_tiles(t + 56 + look * (unsigned)(w * h / 2), w, h, (const uint16_t *)(t + 8), t + 40, W->rain_pos, W->rain_n, ox, oy,+ (uint8_t)(W->rain * 128 + .5f));}/* mr: the place is saved every two seconds */@@ -708,8 +761,10 @@ static void start_overworld(void) {W->map = child_of_sym(root, S_overworld_jqa);/* the sea and the rain are drawn by code (the layer's water, draw_over) */node_free(child_of_sym(root, S_overworld_w9a));- W->rain = child_of_sym(root, S_overworld_bca);- if (W->rain) { node_remove(W->rain); node_free(W->rain); W->rain = 0; }+ NodeId rain = child_of_sym(root, S_overworld_bca);+ W->rain_cond = rain && nodes[rain].T != NONE16 ? comp_str(nodes[rain].T, C_conditionallyVisible, F_condition) : NONE16;+ if (rain) { node_remove(rain); node_free(rain); }+ clip_each_slot(S_overworld_bca, 0, rain_slot, NULL);NodeId sky = child_of_sym(root, S_overworld_mAa);if (sky) node_free(sky);if (!W->map) return;@@ -820,7 +875,7 @@ static void draw_under_overworld(void) {bg_camera((int)floorf(vx + .5f), (int)floorf(vy + .5f));}-const SceneDef scene_overworld = {"overworld", start_overworld, tick_overworld, end_overworld, draw_under_overworld, NULL, NULL};+const SceneDef scene_overworld = {"overworld", start_overworld, tick_overworld, end_overworld, draw_under_overworld, draw_over_overworld, NULL};/* ---------------------------------------------------------------- interiors *//* Ir: a room is a frame of the interior library's root (its label is thediff --git a/games/championisland/tools/pack.py b/games/championisland/tools/pack.pyindex 8a8b047c..3a19aa72 100644--- a/games/championisland/tools/pack.py+++ b/games/championisland/tools/pack.py@@ -513,7 +513,7 @@ for lib, mapsym in WORLDS:order_i = classify(lib, c, matrix(c.get('tr', {})), statics, kids, order_i, lib == 'interior')continueMr = matrix(c['tr'])- nb = rs.get('nb')+ nb = sym_bounds(lib, c['sym']) or rs.get('nb') # Gj: getBounds, the union of its childrenregions.append((SYM_ID[(lib, c['sym'])], aabb(Mr, nb) if nb else (0, 0, 0, 0)))world_drop.add((lib, c['sym']))for g in rs['frames'][0]:@@ -1234,6 +1234,38 @@ for i in range(len(SHEETS)):pal_bin += bytes(sheet_alpha[i])off_pal = blob.add(bytes(pal_bin))+# the island's rain (bca): its two looks (Yi shows u_a, then v_a) drawn as a+# pattern over the view straight from here, 4 bits a pixel with their own 15+# colours (u16 w, h, looks, colours; u16 rgb565[16]; u8 alpha 0..32 [16]; pixels)+def tiles4(lib, names):+ looks = [LIB[lib]['syms'][n]['sheet'] for n in names]+ sh, _, _, w, h = looks[0]+ assert all(l[0] == sh and l[3:] == (w, h) for l in looks) and w % 2 == 0+ cols, px = [], bytearray()+ for _, x, y, _, _ in looks:+ a = sheet_px[sh][y:y + h, x:x + w]+ for row in a:+ nib = []+ for v in row.tolist():+ if sheet_alpha[sh][v] == 0:+ nib.append(0)+ continue+ if v not in cols:+ cols.append(v)+ nib.append(cols.index(v) + 1)+ px += bytes(nib[i] | nib[i + 1] << 4 for i in range(0, w, 2))+ assert len(cols) <= 15, cols+ pal = [0] * 16+ al = [0] * 16+ for i, v in enumerate(cols):+ r, g, b = pal_rgb[sh][v]+ pal[i + 1] = (r >> 3) << 11 | (g >> 2) << 5 | (b >> 3)+ al[i + 1] = (int(sheet_alpha[sh][v]) * 32 + 127) // 255+ return struct.pack('<HHHH', w, h, len(looks), len(cols)) + struct.pack('<16H', *pal) + bytes(al) + bytes(px)+++off_tiles = blob.add(tiles4('overworld', ['u_a', 'v_a']), 2)+pay_offs = [blob.add(p_, 2, cat='payload') for p_ in PAYLOADS]off_payloads = blob.add(b''.join(struct.pack('<I', o) for o in pay_offs))t_offs = [blob.add(t_, 1, cat='T') for t_ in T_TABLE]@@ -1378,7 +1410,7 @@ HEADER = [('nsyms', len(SYMS)), ('syms', off_syms), ('nmats', len(MATS)), ('mats', off_mats),('nstrings', len(strings)), ('strtab', off_strtab), ('strdata', off_strdata),('nexprs', len(EXPRS)), ('exprs', off_exprs), ('ndlg', len(dlg_index)), ('dlg', off_dlg_index),- ('nmsgs', len(msg_keys)), ('msgs', off_msgs), ('nvars', len(VARS)), ('payloads', off_payloads), ('ttab', off_ttab), ('bankspr', off_bankspr), ('worlds', off_worlds), ('dtext', off_dtext), ('strsort', off_strsort), ('reserved3', 0)]+ ('nmsgs', len(msg_keys)), ('msgs', off_msgs), ('nvars', len(VARS)), ('payloads', off_payloads), ('ttab', off_ttab), ('bankspr', off_bankspr), ('worlds', off_worlds), ('dtext', off_dtext), ('strsort', off_strsort), ('tiles', off_tiles)]assert len(HEADER) == HEADER_WORDSfinal = bytearray(blob.b)final[:4 * HEADER_WORDS] = b''.join(struct.pack('<I', v) for _, v in HEADER)diff --git a/tests/test_games.py b/tests/test_games.pyindex 5eccfd79..5136099c 100644--- a/tests/test_games.py+++ b/tests/test_games.py@@ -100,6 +100,11 @@ GAMES = {# start, then through the bathroom and the hallway to the table; then continue"buckshot": ("BuckshotRoulette.nwa", "buckshot.sav", every(1500, 14000, 900, "ok"), 16000,presses((1500, "ok")), 4000),+ # the intro film is skipped (seen), Lucky walks up the dock and talks to the+ # guardians; next time the game starts where it was left+ "championisland": ("ChampionIsland.nwa", "champion.sav",+ presses((2000, "up", 1500)) + every(4000, 9000, 700, "ok"), 11000,+ presses((2000, "up", 400)), 4000),# a level, its message, then play; then back to the level select"portal": ("PortalReturns.nwa", "portal.sav",presses((1500, "ok"), (2500, "ok"), (3500, "ok")) + every(4000, 7000, 400, "right", 300), 8000,diff --git a/tools/emu.py b/tools/emu.pyindex fbe56193..90372424 100644--- a/tools/emu.py+++ b/tools/emu.py@@ -568,6 +568,8 @@ def main():f"{(c.now_ms - c.slept_ms) / max(n, 1):.1f} ms of work per frame", end="")if "perf_max" in c.symbols:print(f", slowest {struct.unpack('<I', bytes(c.uc.mem_read(c.symbols['perf_max'], 4)))[0]} ms", end="")+ if "perf_slow" in c.symbols:+ print(f", {struct.unpack('<I', bytes(c.uc.mem_read(c.symbols['perf_slow'], 4)))[0]} over 33 ms", end="")print()if a.profile and c.samples:import bisectdiff --git a/tools/release.py b/tools/release.pyindex 854e75d6..ffa2d539 100644--- a/tools/release.py+++ b/tools/release.py@@ -21,6 +21,11 @@ ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")REPO = "https://github.com/Mason363/NumPlay"# in games.json, but not gamesEXTRAS = {"numvisuals"}+# games too big to fit next to NumPlay on the calculator: only on their own+ALONE = {+ "championisland": ("Champion Island", "the Doodle Champion Island Games. Too big to share the calculator with "+ "NumPlay: install it on its own"),+}VARIANTS = [("NumPlay-Invisible.nwa", "The same app, hidden: a blank icon with no name"),("NumPlay-Matrices.nwa", "The same app, disguised as a math app called Matrices"),@@ -68,6 +73,14 @@ def main():what = f"Only {g['title']}: {tagline}"files.append((os.path.join(a.build, "apps", name), f"{name} · {what}"))notes.append(f"| {link(name)} | {what} |")+ alone = [(gid, apps[gid]) for gid in ALONE if gid in apps]+ if alone:+ notes += ["", "### Too big for NumPlay", "", "| File | |", "| --- | --- |"]+ for gid, name in alone:+ title, what = ALONE[gid]+ what = f"{title}: {what}"+ files.append((os.path.join(a.build, "apps", name), f"{name} · {what}"))+ notes.append(f"| {link(name)} | {what} |")notes += ["", "<sub>The file list below is sorted A to Z by GitHub. Each file's label says what it is.</sub>"]intro = open(os.path.join(ROOT, ".github", "release.md")).read().rstrip()