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
Simulator build, recording tool, uninstall tests
Mason36364329b5bf19b
diff --git a/Makefile b/Makefileindex 2ba7e444..2f35f12a 100644--- a/Makefile+++ b/Makefile@@ -57,7 +57,7 @@ ENTRY_tetris = np_tetris_main$(B)/tetris/raw.o: FORCE | $(B)mkdir -p $(B)/tetriscd games/tetris/tetris && NWLINK="$(NWLINK)" $(CARGO) build --release --quiet- $(ARM_LD) -r --gc-sections -e np_tetris_main -u np_tetris_main \+ $(ARM_LD) -r -z noexecstack --gc-sections -e np_tetris_main -u np_tetris_main \games/tetris/tetris/target/thumbv7em-none-eabihf/release/libtetris.a -o $@$(B)/modules/%.o: FORCE | $(B)@@ -131,8 +131,8 @@ SIM_tetris = $(B)/sim/tetris.oSIM_CFLAGS = -std=gnu11 -O2 -fPIC -DNP_SIMULATOR=1 $(EADK_SIM_CFLAGS) -Ilauncher/src -Wall -Wno-unused-parameter$(B)/sim/tetris.o: FORCE | $(B)- cd games/tetris/tetris && NWLINK="$(NWLINK)" $(CARGO) build --release --quiet --target aarch64-apple-darwin- ld -r -exported_symbol _np_tetris_main -u _np_tetris_main \+ cd games/tetris/tetris && NWLINK="$(NWLINK)" $(CARGO) build --lib --release --quiet --target aarch64-apple-darwin+ cc -r -nostdlib -arch arm64 -Wl,-u,_np_tetris_main -Wl,-exported_symbol,_np_tetris_main \games/tetris/tetris/target/aarch64-apple-darwin/release/libtetris.a -o $@$(B)/sim/%.mod: FORCE | $(B)diff --git a/games/chess/Makefile b/games/chess/Makefileindex ae73f824..25d61acf 100644--- a/games/chess/Makefile+++ b/games/chess/Makefile@@ -57,6 +57,6 @@ $(BUILD_DIR)/module.o: $(SRC) src/chess.h src/sprites.h | $(BUILD_DIR)sim-module: $(BUILD_DIR)/sim-module.o$(BUILD_DIR)/sim-module.o: src/main.c src/chess.c src/chess.h src/sprites.h | $(BUILD_DIR)$(Q) mkdir -p $(BUILD_DIR)/sim- $(Q) for f in main chess; do cc -std=c99 -O2 -fPIC -fvisibility=hidden $(shell $(NWLINK) eadk-cflags-simulator) \+ $(Q) for f in main chess; do cc -std=c99 -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) \-Dmain=np_chess_main -c src/$$f.c -o $(BUILD_DIR)/sim/$$f.o || exit 1; done$(Q) ld -r $(BUILD_DIR)/sim/*.o -exported_symbol _np_chess_main -o $@diff --git a/games/chess/src/main.c b/games/chess/src/main.cindex 36940a88..55d4c783 100644--- a/games/chess/src/main.c+++ b/games/chess/src/main.c@@ -3,8 +3,10 @@#include "chess.h"#include "sprites.h"+#ifdef __ELF__ /* app name and API level, for the calculator's installer */const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Chess";const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;+#endiftypedef uint16_t C;#define RGB(r, g, b) ((C)((((r) & 0xF8) << 8) | (((g) & 0xFC) << 3) | ((b) >> 3)))diff --git a/games/crossyroad/Makefile b/games/crossyroad/Makefileindex 43208330..3ef99fbe 100644--- a/games/crossyroad/Makefile+++ b/games/crossyroad/Makefile@@ -65,6 +65,6 @@ $(BUILD)/module.o: src/crossy.c $(BUILD)/rom.inc | $(BUILD)sim-module: $(BUILD)/sim-module.o$(BUILD)/sim-module.o: src/crossy.c | $(BUILD)- cc -std=c11 -O2 -fno-math-errno -fPIC -fvisibility=hidden -DPLATFORM_SIM=1 -I$(EADK_INC) -Dmain=np_crossyroad_main \+ cc -std=c11 -O2 -fno-math-errno -fPIC -DPLATFORM_SIM=1 -I$(EADK_INC) -Dmain=np_crossyroad_main \-c src/crossy.c -o $(BUILD)/sim.old -r $(BUILD)/sim.o -exported_symbol _np_crossyroad_main -o $@diff --git a/games/crossyroad/src/crossy.c b/games/crossyroad/src/crossy.cindex 3caa9212..aa9d4ada 100644--- a/games/crossyroad/src/crossy.c+++ b/games/crossyroad/src/crossy.c@@ -26,8 +26,10 @@ __attribute__((used, externally_visible)) void *memcpy(void *d, const void *s, s#include <string.h>#endif+#ifdef __ELF__ /* app name and API level, for the calculator's installer */const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Crossy Road";const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;+#endif#define SW 320#define SH 240@@ -489,7 +491,11 @@ static void init_palette(void) {// ceil(v - 0.5): index of the first pixel whose center is at or after v// (a single VCVTP instruction on the Cortex-M7).+#ifdef __clang__+static inline int ceil_half(float v) { return (int)__builtin_ceilf(v - 0.5f); }+#elsestatic inline int ceil_half(float v) { return (int)__builtin_lceilf(v - 0.5f); }+#endif#ifdef HOST_STATSlong st_polys, st_lines, st_pixels;diff --git a/games/numdash/Makefile b/games/numdash/Makefileindex 45c6a939..8ee74c9a 100644--- a/games/numdash/Makefile+++ b/games/numdash/Makefile@@ -62,6 +62,6 @@ build/module.o: $(DEVICE_OBJECTS) | build/.stampsim-module: build/sim-module.obuild/sim-module.o: $(COMMON) src/platform_eadk.c src/main.c $(HEADERS) node_modules/nwlink/bin/nwlink | build/.stampmkdir -p build/sim- for f in $(COMMON) src/platform_eadk.c src/main.c; do cc -std=c11 -O2 -fPIC -fvisibility=hidden -Isrc \+ for f in $(COMMON) src/platform_eadk.c src/main.c; do cc -std=c11 -O2 -fPIC -Isrc \$(shell $(NWLINK) eadk-cflags-simulator) -Dmain=np_numdash_main -c $$f -o build/sim/$$(basename $$f .c).o || exit 1; doneld -r build/sim/*.o -exported_symbol _np_numdash_main -o $@diff --git a/games/numdrive/Makefile b/games/numdrive/Makefileindex db3c8164..76033460 100644--- a/games/numdrive/Makefile+++ b/games/numdrive/Makefile@@ -68,8 +68,8 @@ sim-module: output/npsim/sim-module.ooutput/npsim/sim-module.o: $(addprefix src/,$(SOURCES)) src/pack.bin src/*.h@mkdir -p output/npsim$(Q) cd src && xxd -i -n pack_bin pack.bin > ../output/npsim/pack_bin.c- $(Q) for f in $(SOURCES); do cc -std=gnu11 -O2 -fPIC -fvisibility=hidden -fsingle-precision-constant -Wno-unused-function \+ $(Q) for f in $(SOURCES); do cc -std=gnu11 -O2 -fPIC -fsingle-precision-constant -Wno-unused-function \$(shell $(NWLINK) eadk-cflags-simulator) -DNO_STORAGE -Dpack_data=pack_bin -Dmain=np_numdrive_main \-c src/$$f -o output/npsim/$${f%.c}.o || exit 1; done- $(Q) cc -fPIC -fvisibility=hidden -c output/npsim/pack_bin.c -o output/npsim/pack_bin.o+ $(Q) cc -fPIC -c output/npsim/pack_bin.c -o output/npsim/pack_bin.o$(Q) ld -r output/npsim/*.o -exported_symbol _np_numdrive_main -o $@diff --git a/games/numdrive/src/main.c b/games/numdrive/src/main.cindex 198c85ae..8be0b28a 100644--- a/games/numdrive/src/main.c+++ b/games/numdrive/src/main.c@@ -13,9 +13,11 @@#ifndef HOST#include <eadk.h>+#ifdef __ELF__ /* app name and API level, for the calculator's installer */const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "NumDrive";const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;#endif+#endifenum { ST_PLAY, ST_CARD, ST_LEVELS };#define SHOT_FRAMES 10 /* viewfinder shown before the photo */@@ -232,11 +234,7 @@ int main(int argc, char **argv) {state = ST_PLAY;continue;}- if (hit & KEY(K_BACK)) {- state = ST_CARD;- dirty = true;- continue;- }+ if (hit & KEY(K_BACK)) break; /* leave the game (Home also works, but it closes NumPlay too) */if (dirty) levels_draw(lsel, lscroll);dirty = false;}diff --git a/launcher/sim/sim.c b/launcher/sim/sim.cnew file mode 100644index 00000000..925260ea--- /dev/null+++ b/launcher/sim/sim.c@@ -0,0 +1,203 @@+/* Glue for the simulator build (NumPlay.nwb), which runs natively inside the+ * Epsilon simulator.+ *+ * - Rust (Tetris) calls eadk_keyboard_scan and eadk_timing_millis as real+ * functions; the simulator's eadk.h only has them inline.+ * - Tetris's storage helpers get an in-memory stand-in.+ * - Recording: with NUMPLAY_SCRIPT set (keys over time, "500-600:right,900:ok"),+ * the keyboard follows the script instead of the user, and with+ * NUMPLAY_FRAMES set to a directory, the screen is saved there as raw+ * RGB565 frames (NUMPLAY_FPS per second). The app quits when the script ends+ * (NUMPLAY_END_MS). tools/record.py turns the frames into PNGs and GIFs. */+#include <dlfcn.h>+#include <stdbool.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++typedef struct {+ uint16_t x, y, width, height;+} rect_t;+void eadk_display_pull_rect(rect_t rect, uint16_t *pixels);+void eadk_timing_msleep(uint32_t ms);++/* ---------------------------------------------------------------- recording */+typedef struct {+ uint32_t a, b;+ int key;+} press_t;+static press_t presses[512];+static int npresses = -1;+static uint32_t t0, end_ms, frame_ms = 40, next_frame, nframes;+static const char *frames_dir;++static const struct {+ const char *name;+ int key;+} names[] = {{"left", 0}, {"up", 1}, {"down", 2}, {"right", 3}, {"ok", 4}, {"back", 5},+ {"home", 6}, {"shift", 12}, {"alpha", 13}, {"backspace", 17}, {"exe", 52}, {"0", 48},+ {"1", 42}, {"2", 43}, {"3", 44}, {"4", 36}, {"5", 37}, {"6", 38},+ {"7", 30}, {"8", 31}, {"9", 32}, {"plus", 45}, {"minus", 46}, {"toolbox", 16},+ {"var", 15}, {"xnt", 14}, {"ln", 19}};++static void (*real_do_scan)(void);+static uint32_t (*real_scan_low)(void), (*real_scan_high)(void);+static uint32_t (*real_millis_low)(void), (*real_millis_high)(void);+static uint16_t (*real_event_get)(int32_t *);++static uint32_t now_real(void) {+ if (!real_millis_low) {+ real_millis_low = dlsym(RTLD_MAIN_ONLY, "_eadk_timing_millis_low");+ real_millis_high = dlsym(RTLD_MAIN_ONLY, "_eadk_timing_millis_high");+ }+ return real_millis_low ? real_millis_low() : 0;+}++static void load(void) {+ if (npresses >= 0) return;+ npresses = 0;+ real_do_scan = dlsym(RTLD_MAIN_ONLY, "_eadk_keyboard_scan_do_scan");+ real_scan_low = dlsym(RTLD_MAIN_ONLY, "_eadk_keyboard_scan_low");+ real_scan_high = dlsym(RTLD_MAIN_ONLY, "_eadk_keyboard_scan_high");+ real_event_get = dlsym(RTLD_MAIN_ONLY, "eadk_event_get");+ const char *s = getenv("NUMPLAY_SCRIPT");+ frames_dir = getenv("NUMPLAY_FRAMES");+ if (getenv("NUMPLAY_FPS")) frame_ms = 1000 / (uint32_t)atoi(getenv("NUMPLAY_FPS"));+ if (getenv("NUMPLAY_END_MS")) end_ms = (uint32_t)atoi(getenv("NUMPLAY_END_MS"));+ t0 = now_real();+ if (!s) {+ npresses = -2; /* not recording */+ return;+ }+ char buf[8192];+ strncpy(buf, s, sizeof buf - 1);+ buf[sizeof buf - 1] = 0;+ for (char *item = strtok(buf, ","); item && npresses < 512; item = strtok(NULL, ",")) {+ char *colon = strchr(item, ':');+ if (!colon) continue;+ *colon = 0;+ uint32_t a = (uint32_t)atoi(item), b = a + 120;+ char *dash = strchr(item, '-');+ if (dash) b = (uint32_t)atoi(dash + 1);+ int key = -1;+ for (size_t i = 0; i < sizeof names / sizeof names[0]; i++)+ if (!strcmp(colon + 1, names[i].name)) key = names[i].key;+ if (key < 0) key = atoi(colon + 1);+ presses[npresses++] = (press_t){a, b, key};+ if (b + 1500 > end_ms) end_ms = b + 1500;+ }+}++static bool recording(void) {+ load();+ return npresses >= 0;+}++static void grab(uint32_t t) {+ if (!frames_dir || t < next_frame) return;+ static uint16_t px[320 * 240];+ eadk_display_pull_rect((rect_t){0, 0, 320, 240}, px);+ char path[1024];+ snprintf(path, sizeof path, "%s/%06u_%06u.raw", frames_dir, nframes++, t);+ FILE *f = fopen(path, "wb");+ if (f) {+ fwrite(px, sizeof px, 1, f);+ fclose(f);+ }+ next_frame = t + frame_ms;+}++static uint64_t scripted_state(uint32_t t) {+ uint64_t s = 0;+ for (int i = 0; i < npresses; i++)+ if (t >= presses[i].a && t < presses[i].b) s |= (uint64_t)1 << presses[i].key;+ return s;+}++static uint64_t state;+void _eadk_keyboard_scan_do_scan(void) {+ if (!recording()) {+ real_do_scan();+ state = (uint64_t)real_scan_high() << 32 | real_scan_low();+ return;+ }+ uint32_t t = now_real() - t0;+ grab(t);+ if (end_ms && t > end_ms) {+ fflush(stdout);+ exit(0);+ }+ state = scripted_state(t);+}+uint32_t _eadk_keyboard_scan_low(void) { return (uint32_t)state; }+uint32_t _eadk_keyboard_scan_high(void) { return (uint32_t)(state >> 32); }++/* Games that wait for events (Chess) get the scripted presses as events. */+uint16_t eadk_event_get(int32_t *timeout) {+ if (!recording()) return real_event_get(timeout);+ static uint64_t previous;+ for (;;) {+ uint32_t t = now_real() - t0;+ grab(t);+ if (end_ms && t > end_ms) exit(0);+ uint64_t s = scripted_state(t), pressed = s & ~previous;+ previous = s;+ for (int k = 0; k < 64; k++)+ if (pressed >> k & 1) return (uint16_t)k;+ if (timeout && *timeout <= 0) return 216; /* Ion::Events::None */+ eadk_timing_msleep(10);+ if (timeout) *timeout -= 10;+ }+}++/* ---------------------------------------------------------------- for Rust */+uint64_t eadk_keyboard_scan(void) {+ _eadk_keyboard_scan_do_scan();+ return state;+}+uint64_t eadk_timing_millis(void) {+ now_real();+ return real_millis_high ? ((uint64_t)real_millis_high() << 32 | real_millis_low()) : 0;+}++/* ---------------------------------------------------------------- Tetris's files */+static struct {+ char name[32];+ uint8_t data[256];+ uint32_t len;+ bool used;+} files[8];++static int find_file(const char *name) {+ for (int i = 0; i < 8; i++)+ if (files[i].used && !strcmp(files[i].name, name)) return i;+ return -1;+}+bool extapp_fileExists(const char *name) { return find_file(name) >= 0; }+const uint8_t *extapp_fileRead(const char *name, uint32_t *len) {+ int i = find_file(name);+ if (i < 0) return NULL;+ *len = files[i].len;+ return files[i].data;+}+bool extapp_fileWrite(const char *name, const uint8_t *content, uint32_t len) {+ int i = find_file(name);+ for (int k = 0; i < 0 && k < 8; k++)+ if (!files[k].used) i = k;+ if (i < 0 || len > sizeof files[i].data || strlen(name) >= sizeof files[i].name) return false;+ strcpy(files[i].name, name);+ if (content) memcpy(files[i].data, content, len);+ files[i].len = len;+ files[i].used = true;+ return true;+}+bool extapp_fileErase(const char *name) {+ int i = find_file(name);+ if (i >= 0) files[i].used = false;+ return i >= 0;+}++/* Rust's prebuilt core for the host references an unwinding personality;+ * NumPlay's Rust code aborts on panic and never unwinds. */+void rust_eh_personality(void) {}diff --git a/launcher/src/flash.c b/launcher/src/flash.cindex 178643cf..6eeb8054 100644--- a/launcher/src/flash.c+++ b/launcher/src/flash.c@@ -100,7 +100,9 @@ int np_uninstall(int i, void (*progress)(int, int)) {const np_game_t *g = &np_games[i];if (!np_uninstall_supported()) return NP_UNINSTALL_UNSUPPORTED;if (!np_battery_ok()) return NP_UNINSTALL_BATTERY;+ np_interrupts_lock();for (const char *const *r = g->records; r && *r; r++) np_storage_delete(*r);+ np_interrupts_unlock();#if NP_SIMULATORfor (int k = 0; k <= 4; k++) {if (progress) progress(k, 4);@@ -111,7 +113,10 @@ int np_uninstall(int i, void (*progress)(int, int)) {#elseuint32_t a = (uint32_t)(uintptr_t)g->begin, b = (uint32_t)(uintptr_t)g->end;if (!range_ok(a, b)) return NP_UNINSTALL_FAILED;- return wipe(a, b, progress);+ np_interrupts_lock(); /* Home must not stop us halfway */+ int r = wipe(a, b, progress);+ np_interrupts_unlock();+ return r;#endif}@@ -126,7 +131,9 @@ void np_finish_pending_uninstalls(void) {uint32_t s0 = (a + SECTOR - 1) & ~(SECTOR - 1), s1 = b & ~(SECTOR - 1);if (s1 < s0) s0 = s1 = b;if (zeroed(a, s0) && erased(s0, s1) && zeroed(s1, b)) continue;+ np_interrupts_lock();wipe(a, b, 0);+ np_interrupts_unlock();}#endif}diff --git a/launcher/src/home.c b/launcher/src/home.cindex 43829cad..b6bca3db 100644--- a/launcher/src/home.c+++ b/launcher/src/home.c@@ -120,6 +120,11 @@ static void scene(void *ctx) {uint32_t top = gfx_lerp888(item_color(h->item[a], 0), item_color(h->item[b], 0), t);uint32_t bottom = gfx_lerp888(item_color(h->item[a], 1), item_color(h->item[b], 1), t);gfx_vgrad(0, 0, SCREEN_W, SCREEN_H, top, bottom);+ /* a faint dot grid gives the background some texture */+ for (int y = (gfx_y0 + 15) / 16 * 16 + 8 - 16; y < gfx_y1; y += 16) {+ if (y < gfx_y0) continue;+ for (int x = 8; x < SCREEN_W; x += 16) gfx_fill_alpha(x, y, 2, 1, 0xFFFF, 22);+ }float z = ui_ease_in_out(h->zoom);int ui_alpha = (int)(256 * (1 - z));@@ -178,7 +183,7 @@ static int build_items(home_t *h) {return h->n;}-int np_home(int *selected) {+int np_home(int *selected, bool returning) {ui_init();home_t h = {0};build_items(&h);@@ -192,6 +197,8 @@ int np_home(int *selected) {h.pos = h.sel + 1.2f;first_open = false;}+ bool unzooming = returning && h.item[h.sel] == *selected && *selected >= 0;+ if (unzooming) h.zoom = 1;ui_keys_t keys = {np_keys(), 0, 0}; /* ignore keys still held from before */uint32_t last = np_millis();bool dirty = true;@@ -213,7 +220,7 @@ int np_home(int *selected) {h.badge = 0;}if (pressed & K_OK) result = h.item[h.sel];- if (pressed & K_HOME) return -2;+ if (pressed & (K_HOME | K_BACK)) return -2;}/* motion */float pos = ui_approach(h.pos, (float)h.sel, dt, 0.075f);@@ -244,6 +251,11 @@ int np_home(int *selected) {}}}+ if (unzooming) {+ h.zoom = NP_MAX(h.zoom - dt / 0.26f, 0.f);+ unzooming = h.zoom > 0;+ dirty = true;+ }if (result != -3) {if (result == -1 || !settled) {if (result == -1) {diff --git a/launcher/src/main.c b/launcher/src/main.cindex 4dd495fa..cea22eb1 100644--- a/launcher/src/main.c+++ b/launcher/src/main.c@@ -9,8 +9,10 @@ const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level")))int main(void) {np_finish_pending_uninstalls();int selected = np_game_count ? 0 : -1;+ bool returning = false;for (;;) {- int r = np_home(&selected);+ int r = np_home(&selected, returning);+ returning = false;if (r == -2) break;if (r == -1) {np_settings();@@ -18,6 +20,7 @@ int main(void) {}np_game_run(r);np_wait_release();+ returning = true;}np_wait_release();return 0;diff --git a/launcher/src/np.h b/launcher/src/np.hindex 234d3114..873fdfc2 100644--- a/launcher/src/np.h+++ b/launcher/src/np.h@@ -80,7 +80,7 @@ int np_uninstall(int game, void (*progress)(int done, int total));void np_finish_pending_uninstalls(void);/* ---- the screens (home.c, settings.c) */-int np_home(int *selected); /* returns a game index, -1 for settings, -2 to quit */+int np_home(int *selected, bool returning); /* a game index, -1 for settings, -2 to quit */void np_settings(void);#endifdiff --git a/launcher/src/sys.c b/launcher/src/sys.cindex 9ca74b20..c090cf72 100644--- a/launcher/src/sys.c+++ b/launcher/src/sys.c@@ -63,6 +63,8 @@ int np_battery_level(void) { return (int)(SVC2(4, 0, 0) & 0xFF); }bool np_battery_charging(void) { return (SVC2(3, 0, 0) & 0xFF) != 0; }bool np_flash_erase_sector(int sector) { return (SVC2(30, sector, 1) & 0xFF) != 0; }bool np_flash_write(void *dst, const void *src, uint32_t len) { return (SVC4(32, dst, src, len, 1) & 0xFF) != 0; }+void np_interrupts_lock(void) { SVC2(10, 0, 0); }+void np_interrupts_unlock(void) { SVC2(13, 0, 0); }#else /* simulator */@@ -85,6 +87,8 @@ bool np_flash_write(void *dst, const void *src, uint32_t len) {(void)dst, (void)src, (void)len;return false;}+void np_interrupts_lock(void) {}+void np_interrupts_unlock(void) {}#endifint np_software_major(void) {diff --git a/launcher/src/sys.h b/launcher/src/sys.hindex 824856ce..9ef160ac 100644--- a/launcher/src/sys.h+++ b/launcher/src/sys.h@@ -25,5 +25,9 @@ uint32_t np_crc32_words(const uint32_t *data, uint32_t words);int np_battery_level(void); /* 0 empty .. 3+ full, -1 unknown */bool np_battery_charging(void);bool np_flash_erase_sector(int sector);+/* While locked, the Home key cannot interrupt the app (Epsilon's circuit+ * breaker), so a critical section runs to its end. */+void np_interrupts_lock(void);+void np_interrupts_unlock(void);bool np_flash_write(void *dst, const void *src, uint32_t len);#endifdiff --git a/tests/test_uninstall.py b/tests/test_uninstall.pyindex 036ab57b..17f79506 100644--- a/tests/test_uninstall.py+++ b/tests/test_uninstall.py@@ -32,6 +32,9 @@ def main():ap.add_argument("nwa")ap.add_argument("--out", default="build/test_uninstall")ap.add_argument("--game", default="crossyroad")+ ap.add_argument("--cut-power", type=int, default=0,+ help="stop the calculator after this many flash operations, then check that the next launch "+ "finishes the job")a = ap.parse_args()os.makedirs(a.out, exist_ok=True)c = emu.Calculator(a.nwa)@@ -82,7 +85,36 @@ def main():c.keys = keysshots = {dialog: "1_warning", hold + 900: "2_holding", done: "3_done", listing: "4_list", home: "5_home"}c.pending_shots = sorted((ms, os.path.join(a.out, name + ".png")) for ms, name in shots.items())- c.run(t + 3000)+ if a.cut_power:+ original = c._intr++ def intr(uc, intno, data):+ original(uc, intno, data)+ if len(c.flash_log) >= a.cut_power and not c.exited:+ c.exited = True # power cut: nothing more runs+ uc.emu_stop()+ c.uc.hook_del(c.intr_hook)+ c.intr_hook = c.uc.hook_add(emu.UC_HOOK_INTR, intr)+ c.run(t + 3000)+ if len(c.flash_log) < a.cut_power:+ fail("the uninstall did not reach the power cut")+ print(f"power cut after {len(c.flash_log)} flash operations")+ # power back on: RAM is gone, flash stays; NumPlay starts and should finish the job+ c.uc.hook_del(c.intr_hook)+ c.intr_hook = c.uc.hook_add(emu.UC_HOOK_INTR, original)+ c.exited = False+ c.locks = c.max_locks = 0 # the kernel starts afresh too+ ops = len(c.flash_log)+ c.pc = c.entry | 1+ c.uc.reg_write(emu.UC_ARM_REG_SP, emu.STACK_TOP)+ c.uc.reg_write(emu.UC_ARM_REG_LR, emu.EXIT_HOOK | 1)+ start = c.now_ms+ c.keys = [(start + 2500, start + 2590, emu.KEYS["home"])]+ c.pending_shots = [(start + 2400, os.path.join(a.out, "after_power_cut.png"))]+ c.run(start + 4000)+ print(f"next launch: {len(c.flash_log) - ops} flash operations to finish the uninstall")+ else:+ c.run(t + 3000)if not c.exited:fail("NumPlay did not quit")@@ -113,6 +145,8 @@ def main():b, e = c.symbols[f"np_{g}_begin"], c.symbols[f"np_{g}_end"]if struct.unpack_from("<I", flash, off(b))[0] != 0x3147504E or struct.unpack_from("<I", flash, off(e) - 4)[0] != 0x444E4550:fail(f"{g} lost its marks")+ if c.locks != 0 or c.max_locks != 1:+ fail(f"Home interrupt lock not balanced (depth {c.locks}, max {c.max_locks})")erased = sum(1 for op in c.flash_log if op[0] == "erase")print(f"flash: {target} block {begin:#x}-{end:#x} ({(end - begin) / 1024:.1f} KB) wiped, "f"{erased} sectors erased, nothing else changed")diff --git a/tools/emu.py b/tools/emu.pyindex 13269a8b..7ddbd50d 100644--- a/tools/emu.py+++ b/tools/emu.py@@ -208,7 +208,8 @@ class Calculator:self.insns = 0self.exited = Falseself.svc_counts = {}- uc.hook_add(UC_HOOK_INTR, self._intr)+ self.locks = self.max_locks = 0+ self.intr_hook = uc.hook_add(UC_HOOK_INTR, self._intr)uc.hook_add(UC_HOOK_CODE, self._draw_string, begin=DRAW_STRING_HOOK, end=DRAW_STRING_HOOK + 1)uc.hook_add(UC_HOOK_CODE, self._exit, begin=EXIT_HOOK, end=EXIT_HOOK + 1)uc.hook_add(UC_HOOK_MEM_INVALID, self._invalid)@@ -352,13 +353,13 @@ class Calculator:self.rng ^= (self.rng << 5) & 0xFFFFFFFFret = self.rngelif n == 23: # event get- ret = 0xFFFF+ ret = 216 # Ion::Events::Nones = self.keyboard_state()for k in range(64):if s >> k & 1:ret = kbreak- if ret == 0xFFFF:+ if ret == 216:self.now_ms += 10elif n in (1,):ret = 128@@ -388,6 +389,11 @@ class Calculator:uc.mem_write(dst, bytes(a & b for a, b in zip(old, new)))self.now_ms += length / 1024ret = 1 if ok else 0+ elif n == 10: # circuit breaker lock: Home cannot interrupt until unlock+ self.locks += 1+ self.max_locks = max(self.max_locks, self.locks)+ elif n == 13:+ self.locks -= 1elif n == 15: # Ion::crc32Byte(data, length)ret = epsilon_crc32(bytes(uc.mem_read(r0, r1)))elif n == 16: # Ion::crc32DoubleWord(data, words)diff --git a/tools/record.py b/tools/record.pynew file mode 100644index 00000000..7236500a--- /dev/null+++ b/tools/record.py@@ -0,0 +1,98 @@+#!/usr/bin/env python3+"""Records NumPlay in the official Epsilon simulator (headless).++The simulator build (NumPlay.nwb) follows a scripted keyboard and saves the+screen as it runs (see launcher/sim/sim.c); this turns the frames into PNG+screenshots and GIFs.++Usage:+ record.py --simulator PATH/Epsilon --nwb build/NumPlay.nwb \+ --keys "1500-1600:right,3000:ok" --out docs/raw \+ [--png 1200:home.png,3400:game.png] [--gif 500-4000:carousel.gif] [--fps 30] [--scale 2]+"""+import argparse+import glob+import os+import subprocess+import tempfile++import numpy as np+from PIL import Image+++def load_frames(d):+ frames = []+ for path in sorted(glob.glob(os.path.join(d, "*.raw"))):+ t = int(os.path.basename(path).split("_")[1].split(".")[0])+ a = np.fromfile(path, dtype="<u2").reshape(240, 320)+ rgb = np.stack([((a >> 11) & 31) * 255 // 31, ((a >> 5) & 63) * 255 // 63, (a & 31) * 255 // 31], -1)+ frames.append((t, Image.fromarray(rgb.astype("uint8"), "RGB")))+ return frames+++def save_gif(frames, path, scale, fps):+ ims = [im.resize((320 * scale, 240 * scale), Image.NEAREST) if scale != 1 else im for _, im in frames]+ # keep the timing of the recording+ durations = []+ for i, (t, _) in enumerate(frames):+ nxt = frames[i + 1][0] if i + 1 < len(frames) else t + 1000 // fps+ durations.append(max(20, nxt - t))+ tmp = path + ".tmp.gif"+ ims[0].save(tmp, save_all=True, append_images=ims[1:], duration=durations, loop=0, optimize=False, disposal=1)+ try:+ subprocess.run(["gifsicle", "-O3", "--lossy=30", "--colors", "256", tmp, "-o", path], check=True)+ os.remove(tmp)+ except (FileNotFoundError, subprocess.CalledProcessError):+ os.replace(tmp, path)+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--simulator", default=os.environ.get("EPSILON"))+ ap.add_argument("--nwb", default="build/NumPlay.nwb")+ ap.add_argument("--keys", required=True)+ ap.add_argument("--end", type=int, default=0)+ ap.add_argument("--fps", type=int, default=30)+ ap.add_argument("--out", required=True)+ ap.add_argument("--png", default="")+ ap.add_argument("--gif", action="append", default=[])+ ap.add_argument("--scale", type=int, default=1)+ ap.add_argument("--keep", help="also save every frame as PNG in this directory")+ a = ap.parse_args()+ os.makedirs(a.out, exist_ok=True)+ with tempfile.TemporaryDirectory() as d:+ state = os.path.join(d, "events.nws")+ open(state, "wb").write(b"\x04")+ env = dict(os.environ, NUMPLAY_SCRIPT=a.keys, NUMPLAY_FRAMES=d, NUMPLAY_FPS=str(a.fps))+ if a.end:+ env["NUMPLAY_END_MS"] = str(a.end)+ # asking for a screenshot is what turns on the headless simulator's frame buffer+ subprocess.run([a.simulator, "--headless", "--headless-state-file", "--load-state-file", state,+ "--take-screenshot", os.path.join(d, "last.png"), "--nwb", os.path.abspath(a.nwb)],+ env=env, check=False, timeout=600)+ frames = load_frames(d)+ if not frames:+ raise SystemExit("record: no frames (is the simulator path right?)")+ print(f"record: {len(frames)} frames over {frames[-1][0] / 1000:.1f} s")+ if a.keep:+ os.makedirs(a.keep, exist_ok=True)+ for t, im in frames:+ im.save(os.path.join(a.keep, f"{t:06d}.png"))+ for spec in filter(None, a.png.split(",")):+ t, name = spec.split(":")+ t = int(t)+ best = min(frames, key=lambda f: abs(f[0] - t))+ im = best[1]+ if a.scale != 1:+ im = im.resize((320 * a.scale, 240 * a.scale), Image.NEAREST)+ im.save(os.path.join(a.out, name))+ for spec in a.gif:+ rng, name = spec.split(":")+ t0, t1 = (int(x) for x in rng.split("-"))+ part = [f for f in frames if t0 <= f[0] <= t1]+ save_gif(part, os.path.join(a.out, name), a.scale, a.fps)+ print(f"record: {name}: {len(part)} frames, {os.path.getsize(os.path.join(a.out, name)) // 1024} KB")+++if __name__ == "__main__":+ main()